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/Object/MachO.h"
15 #include "llvm-objdump.h"
16 #include "llvm-c/Disassembler.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/Triple.h"
20 #include "llvm/Config/config.h"
21 #include "llvm/DebugInfo/DIContext.h"
22 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
23 #include "llvm/MC/MCAsmInfo.h"
24 #include "llvm/MC/MCContext.h"
25 #include "llvm/MC/MCDisassembler/MCDisassembler.h"
26 #include "llvm/MC/MCInst.h"
27 #include "llvm/MC/MCInstPrinter.h"
28 #include "llvm/MC/MCInstrDesc.h"
29 #include "llvm/MC/MCInstrInfo.h"
30 #include "llvm/MC/MCRegisterInfo.h"
31 #include "llvm/MC/MCSubtargetInfo.h"
32 #include "llvm/Object/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/ToolOutputFile.h"
46 #include "llvm/Support/raw_ostream.h"
49 #include <system_error>
62 using namespace object;
66 cl::desc("Print line information from debug info if available"));
68 static cl::opt<std::string> DSYMFile("dsym",
69 cl::desc("Use .dSYM file for debug info"));
71 static cl::opt<bool> FullLeadingAddr("full-leading-addr",
72 cl::desc("Print full leading address"));
74 static cl::opt<bool> NoLeadingAddr("no-leading-addr",
75 cl::desc("Print no leading address"));
77 cl::opt<bool> llvm::UniversalHeaders("universal-headers",
78 cl::desc("Print Mach-O universal headers "
79 "(requires -macho)"));
82 llvm::ArchiveHeaders("archive-headers",
83 cl::desc("Print archive headers for Mach-O archives "
84 "(requires -macho)"));
87 ArchiveMemberOffsets("archive-member-offsets",
88 cl::desc("Print the offset to each archive member for "
89 "Mach-O archives (requires -macho and "
90 "-archive-headers)"));
93 llvm::IndirectSymbols("indirect-symbols",
94 cl::desc("Print indirect symbol table for Mach-O "
95 "objects (requires -macho)"));
98 llvm::DataInCode("data-in-code",
99 cl::desc("Print the data in code table for Mach-O objects "
100 "(requires -macho)"));
103 llvm::LinkOptHints("link-opt-hints",
104 cl::desc("Print the linker optimization hints for "
105 "Mach-O objects (requires -macho)"));
108 llvm::InfoPlist("info-plist",
109 cl::desc("Print the info plist section as strings for "
110 "Mach-O objects (requires -macho)"));
113 llvm::DylibsUsed("dylibs-used",
114 cl::desc("Print the shared libraries used for linked "
115 "Mach-O files (requires -macho)"));
118 llvm::DylibId("dylib-id",
119 cl::desc("Print the shared library's id for the dylib Mach-O "
120 "file (requires -macho)"));
123 llvm::NonVerbose("non-verbose",
124 cl::desc("Print the info for Mach-O objects in "
125 "non-verbose or numeric form (requires -macho)"));
128 llvm::ObjcMetaData("objc-meta-data",
129 cl::desc("Print the Objective-C runtime meta data for "
130 "Mach-O files (requires -macho)"));
132 cl::opt<std::string> llvm::DisSymName(
134 cl::desc("disassemble just this symbol's instructions (requires -macho"));
136 static cl::opt<bool> NoSymbolicOperands(
137 "no-symbolic-operands",
138 cl::desc("do not symbolic operands when disassembling (requires -macho)"));
140 static cl::list<std::string>
141 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 llvm::Triple TT(TripleName);
153 if (TripleName.empty()) {
154 TT = MachOObj->getArchTriple(McpuDefault);
155 TripleName = TT.str();
158 if (TT.getArch() == Triple::arm) {
159 // We've inferred a 32-bit ARM target from the object file. All MachO CPUs
160 // that support ARM are also capable of Thumb mode.
161 llvm::Triple ThumbTriple = TT;
162 std::string ThumbName = (Twine("thumb") + TT.getArchName().substr(3)).str();
163 ThumbTriple.setArchName(ThumbName);
164 ThumbTripleName = ThumbTriple.str();
167 // Get the target specific parser.
169 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
170 if (TheTarget && ThumbTripleName.empty())
173 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
177 errs() << "llvm-objdump: error: unable to get target for '";
179 errs() << TripleName;
181 errs() << ThumbTripleName;
182 errs() << "', see --version and --triple.\n";
186 struct SymbolSorter {
187 bool operator()(const SymbolRef &A, const SymbolRef &B) {
188 Expected<SymbolRef::Type> ATypeOrErr = A.getType();
191 raw_string_ostream OS(Buf);
192 logAllUnhandledErrors(ATypeOrErr.takeError(), OS, "");
194 report_fatal_error(Buf);
196 SymbolRef::Type AType = *ATypeOrErr;
197 Expected<SymbolRef::Type> BTypeOrErr = B.getType();
200 raw_string_ostream OS(Buf);
201 logAllUnhandledErrors(BTypeOrErr.takeError(), OS, "");
203 report_fatal_error(Buf);
205 SymbolRef::Type BType = *BTypeOrErr;
206 uint64_t AAddr = (AType != SymbolRef::ST_Function) ? 0 : A.getValue();
207 uint64_t BAddr = (BType != SymbolRef::ST_Function) ? 0 : B.getValue();
208 return AAddr < BAddr;
212 // Types for the storted data in code table that is built before disassembly
213 // and the predicate function to sort them.
214 typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
215 typedef std::vector<DiceTableEntry> DiceTable;
216 typedef DiceTable::iterator dice_table_iterator;
218 // This is used to search for a data in code table entry for the PC being
219 // disassembled. The j parameter has the PC in j.first. A single data in code
220 // table entry can cover many bytes for each of its Kind's. So if the offset,
221 // aka the i.first value, of the data in code table entry plus its Length
222 // covers the PC being searched for this will return true. If not it will
224 static bool compareDiceTableEntries(const DiceTableEntry &i,
225 const DiceTableEntry &j) {
227 i.second.getLength(Length);
229 return j.first >= i.first && j.first < i.first + Length;
232 static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
233 unsigned short Kind) {
234 uint32_t Value, Size = 1;
238 case MachO::DICE_KIND_DATA:
241 dumpBytes(makeArrayRef(bytes, 4), outs());
242 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
243 outs() << "\t.long " << Value;
245 } else if (Length >= 2) {
247 dumpBytes(makeArrayRef(bytes, 2), outs());
248 Value = bytes[1] << 8 | bytes[0];
249 outs() << "\t.short " << Value;
253 dumpBytes(makeArrayRef(bytes, 2), outs());
255 outs() << "\t.byte " << Value;
258 if (Kind == MachO::DICE_KIND_DATA)
259 outs() << "\t@ KIND_DATA\n";
261 outs() << "\t@ data in code kind = " << Kind << "\n";
263 case MachO::DICE_KIND_JUMP_TABLE8:
265 dumpBytes(makeArrayRef(bytes, 1), outs());
267 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
270 case MachO::DICE_KIND_JUMP_TABLE16:
272 dumpBytes(makeArrayRef(bytes, 2), outs());
273 Value = bytes[1] << 8 | bytes[0];
274 outs() << "\t.short " << format("%5u", Value & 0xffff)
275 << "\t@ KIND_JUMP_TABLE16\n";
278 case MachO::DICE_KIND_JUMP_TABLE32:
279 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
281 dumpBytes(makeArrayRef(bytes, 4), outs());
282 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
283 outs() << "\t.long " << Value;
284 if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
285 outs() << "\t@ KIND_JUMP_TABLE32\n";
287 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
294 static void getSectionsAndSymbols(MachOObjectFile *MachOObj,
295 std::vector<SectionRef> &Sections,
296 std::vector<SymbolRef> &Symbols,
297 SmallVectorImpl<uint64_t> &FoundFns,
298 uint64_t &BaseSegmentAddress) {
299 for (const SymbolRef &Symbol : MachOObj->symbols()) {
300 Expected<StringRef> SymName = Symbol.getName();
303 raw_string_ostream OS(Buf);
304 logAllUnhandledErrors(SymName.takeError(), OS, "");
306 report_fatal_error(Buf);
308 if (!SymName->startswith("ltmp"))
309 Symbols.push_back(Symbol);
312 for (const SectionRef &Section : MachOObj->sections()) {
314 Section.getName(SectName);
315 Sections.push_back(Section);
318 bool BaseSegmentAddressSet = false;
319 for (const auto &Command : MachOObj->load_commands()) {
320 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
321 // We found a function starts segment, parse the addresses for later
323 MachO::linkedit_data_command LLC =
324 MachOObj->getLinkeditDataLoadCommand(Command);
326 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
327 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
328 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
329 StringRef SegName = SLC.segname;
330 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
331 BaseSegmentAddressSet = true;
332 BaseSegmentAddress = SLC.vmaddr;
338 static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
339 uint32_t n, uint32_t count,
340 uint32_t stride, uint64_t addr) {
341 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
342 uint32_t nindirectsyms = Dysymtab.nindirectsyms;
343 if (n > nindirectsyms)
344 outs() << " (entries start past the end of the indirect symbol "
345 "table) (reserved1 field greater than the table size)";
346 else if (n + count > nindirectsyms)
347 outs() << " (entries extends past the end of the indirect symbol "
350 uint32_t cputype = O->getHeader().cputype;
351 if (cputype & MachO::CPU_ARCH_ABI64)
352 outs() << "address index";
354 outs() << "address index";
359 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
360 if (cputype & MachO::CPU_ARCH_ABI64)
361 outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
363 outs() << format("0x%08" PRIx32, (uint32_t)addr + j * stride) << " ";
364 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
365 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
366 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
370 if (indirect_symbol ==
371 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
372 outs() << "LOCAL ABSOLUTE\n";
375 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
376 outs() << "ABSOLUTE\n";
379 outs() << format("%5u ", indirect_symbol);
381 MachO::symtab_command Symtab = O->getSymtabLoadCommand();
382 if (indirect_symbol < Symtab.nsyms) {
383 symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
384 SymbolRef Symbol = *Sym;
385 Expected<StringRef> SymName = Symbol.getName();
388 raw_string_ostream OS(Buf);
389 logAllUnhandledErrors(SymName.takeError(), OS, "");
391 report_fatal_error(Buf);
402 static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
403 for (const auto &Load : O->load_commands()) {
404 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
405 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
406 for (unsigned J = 0; J < Seg.nsects; ++J) {
407 MachO::section_64 Sec = O->getSection64(Load, J);
408 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
409 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
410 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
411 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
412 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
413 section_type == MachO::S_SYMBOL_STUBS) {
415 if (section_type == MachO::S_SYMBOL_STUBS)
416 stride = Sec.reserved2;
420 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
421 << Sec.sectname << ") "
422 << "(size of stubs in reserved2 field is zero)\n";
425 uint32_t count = Sec.size / stride;
426 outs() << "Indirect symbols for (" << Sec.segname << ","
427 << Sec.sectname << ") " << count << " entries";
428 uint32_t n = Sec.reserved1;
429 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
432 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
433 MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
434 for (unsigned J = 0; J < Seg.nsects; ++J) {
435 MachO::section Sec = O->getSection(Load, J);
436 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
437 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
438 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
439 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
440 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
441 section_type == MachO::S_SYMBOL_STUBS) {
443 if (section_type == MachO::S_SYMBOL_STUBS)
444 stride = Sec.reserved2;
448 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
449 << Sec.sectname << ") "
450 << "(size of stubs in reserved2 field is zero)\n";
453 uint32_t count = Sec.size / stride;
454 outs() << "Indirect symbols for (" << Sec.segname << ","
455 << Sec.sectname << ") " << count << " entries";
456 uint32_t n = Sec.reserved1;
457 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
464 static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
465 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
466 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
467 outs() << "Data in code table (" << nentries << " entries)\n";
468 outs() << "offset length kind\n";
469 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
472 DI->getOffset(Offset);
473 outs() << format("0x%08" PRIx32, Offset) << " ";
475 DI->getLength(Length);
476 outs() << format("%6u", Length) << " ";
481 case MachO::DICE_KIND_DATA:
484 case MachO::DICE_KIND_JUMP_TABLE8:
485 outs() << "JUMP_TABLE8";
487 case MachO::DICE_KIND_JUMP_TABLE16:
488 outs() << "JUMP_TABLE16";
490 case MachO::DICE_KIND_JUMP_TABLE32:
491 outs() << "JUMP_TABLE32";
493 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
494 outs() << "ABS_JUMP_TABLE32";
497 outs() << format("0x%04" PRIx32, Kind);
501 outs() << format("0x%04" PRIx32, Kind);
506 static void PrintLinkOptHints(MachOObjectFile *O) {
507 MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
508 const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
509 uint32_t nloh = LohLC.datasize;
510 outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
511 for (uint32_t i = 0; i < nloh;) {
513 uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
515 outs() << " identifier " << identifier << " ";
518 switch (identifier) {
520 outs() << "AdrpAdrp\n";
523 outs() << "AdrpLdr\n";
526 outs() << "AdrpAddLdr\n";
529 outs() << "AdrpLdrGotLdr\n";
532 outs() << "AdrpAddStr\n";
535 outs() << "AdrpLdrGotStr\n";
538 outs() << "AdrpAdd\n";
541 outs() << "AdrpLdrGot\n";
544 outs() << "Unknown identifier value\n";
547 uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
549 outs() << " narguments " << narguments << "\n";
553 for (uint32_t j = 0; j < narguments; j++) {
554 uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
556 outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
563 static void PrintDylibs(MachOObjectFile *O, bool JustId) {
565 for (const auto &Load : O->load_commands()) {
566 if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
567 (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
568 Load.C.cmd == MachO::LC_LOAD_DYLIB ||
569 Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
570 Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
571 Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
572 Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
573 MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
574 if (dl.dylib.name < dl.cmdsize) {
575 const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
580 outs() << " (compatibility version "
581 << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
582 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
583 << (dl.dylib.compatibility_version & 0xff) << ",";
584 outs() << " current version "
585 << ((dl.dylib.current_version >> 16) & 0xffff) << "."
586 << ((dl.dylib.current_version >> 8) & 0xff) << "."
587 << (dl.dylib.current_version & 0xff) << ")\n";
590 outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
591 if (Load.C.cmd == MachO::LC_ID_DYLIB)
592 outs() << "LC_ID_DYLIB ";
593 else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
594 outs() << "LC_LOAD_DYLIB ";
595 else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
596 outs() << "LC_LOAD_WEAK_DYLIB ";
597 else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
598 outs() << "LC_LAZY_LOAD_DYLIB ";
599 else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
600 outs() << "LC_REEXPORT_DYLIB ";
601 else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
602 outs() << "LC_LOAD_UPWARD_DYLIB ";
605 outs() << "command " << Index++ << "\n";
611 typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
613 static void CreateSymbolAddressMap(MachOObjectFile *O,
614 SymbolAddressMap *AddrMap) {
615 // Create a map of symbol addresses to symbol names.
616 for (const SymbolRef &Symbol : O->symbols()) {
617 Expected<SymbolRef::Type> STOrErr = Symbol.getType();
620 raw_string_ostream OS(Buf);
621 logAllUnhandledErrors(STOrErr.takeError(), OS, "");
623 report_fatal_error(Buf);
625 SymbolRef::Type ST = *STOrErr;
626 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
627 ST == SymbolRef::ST_Other) {
628 uint64_t Address = Symbol.getValue();
629 Expected<StringRef> SymNameOrErr = Symbol.getName();
632 raw_string_ostream OS(Buf);
633 logAllUnhandledErrors(SymNameOrErr.takeError(), OS, "");
635 report_fatal_error(Buf);
637 StringRef SymName = *SymNameOrErr;
638 if (!SymName.startswith(".objc"))
639 (*AddrMap)[Address] = SymName;
644 // GuessSymbolName is passed the address of what might be a symbol and a
645 // pointer to the SymbolAddressMap. It returns the name of a symbol
646 // with that address or nullptr if no symbol is found with that address.
647 static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
648 const char *SymbolName = nullptr;
649 // A DenseMap can't lookup up some values.
650 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
651 StringRef name = AddrMap->lookup(value);
653 SymbolName = name.data();
658 static void DumpCstringChar(const char c) {
662 outs().write_escaped(p);
665 static void DumpCstringSection(MachOObjectFile *O, const char *sect,
666 uint32_t sect_size, uint64_t sect_addr,
667 bool print_addresses) {
668 for (uint32_t i = 0; i < sect_size; i++) {
669 if (print_addresses) {
671 outs() << format("%016" PRIx64, sect_addr + i) << " ";
673 outs() << format("%08" PRIx64, sect_addr + i) << " ";
675 for (; i < sect_size && sect[i] != '\0'; i++)
676 DumpCstringChar(sect[i]);
677 if (i < sect_size && sect[i] == '\0')
682 static void DumpLiteral4(uint32_t l, float f) {
683 outs() << format("0x%08" PRIx32, l);
684 if ((l & 0x7f800000) != 0x7f800000)
685 outs() << format(" (%.16e)\n", f);
688 outs() << " (+Infinity)\n";
689 else if (l == 0xff800000)
690 outs() << " (-Infinity)\n";
691 else if ((l & 0x00400000) == 0x00400000)
692 outs() << " (non-signaling Not-a-Number)\n";
694 outs() << " (signaling Not-a-Number)\n";
698 static void DumpLiteral4Section(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(float)) {
702 if (print_addresses) {
704 outs() << format("%016" PRIx64, sect_addr + i) << " ";
706 outs() << format("%08" PRIx64, sect_addr + i) << " ";
709 memcpy(&f, sect + i, sizeof(float));
710 if (O->isLittleEndian() != sys::IsLittleEndianHost)
711 sys::swapByteOrder(f);
713 memcpy(&l, sect + i, sizeof(uint32_t));
714 if (O->isLittleEndian() != sys::IsLittleEndianHost)
715 sys::swapByteOrder(l);
720 static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
722 outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
724 Hi = (O->isLittleEndian()) ? l1 : l0;
725 Lo = (O->isLittleEndian()) ? l0 : l1;
727 // Hi is the high word, so this is equivalent to if(isfinite(d))
728 if ((Hi & 0x7ff00000) != 0x7ff00000)
729 outs() << format(" (%.16e)\n", d);
731 if (Hi == 0x7ff00000 && Lo == 0)
732 outs() << " (+Infinity)\n";
733 else if (Hi == 0xfff00000 && Lo == 0)
734 outs() << " (-Infinity)\n";
735 else if ((Hi & 0x00080000) == 0x00080000)
736 outs() << " (non-signaling Not-a-Number)\n";
738 outs() << " (signaling Not-a-Number)\n";
742 static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
743 uint32_t sect_size, uint64_t sect_addr,
744 bool print_addresses) {
745 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
746 if (print_addresses) {
748 outs() << format("%016" PRIx64, sect_addr + i) << " ";
750 outs() << format("%08" PRIx64, sect_addr + i) << " ";
753 memcpy(&d, sect + i, sizeof(double));
754 if (O->isLittleEndian() != sys::IsLittleEndianHost)
755 sys::swapByteOrder(d);
757 memcpy(&l0, sect + i, sizeof(uint32_t));
758 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
759 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
760 sys::swapByteOrder(l0);
761 sys::swapByteOrder(l1);
763 DumpLiteral8(O, l0, l1, d);
767 static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
768 outs() << format("0x%08" PRIx32, l0) << " ";
769 outs() << format("0x%08" PRIx32, l1) << " ";
770 outs() << format("0x%08" PRIx32, l2) << " ";
771 outs() << format("0x%08" PRIx32, l3) << "\n";
774 static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
775 uint32_t sect_size, uint64_t sect_addr,
776 bool print_addresses) {
777 for (uint32_t i = 0; i < sect_size; i += 16) {
778 if (print_addresses) {
780 outs() << format("%016" PRIx64, sect_addr + i) << " ";
782 outs() << format("%08" PRIx64, sect_addr + i) << " ";
784 uint32_t l0, l1, l2, l3;
785 memcpy(&l0, sect + i, sizeof(uint32_t));
786 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
787 memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
788 memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
789 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
790 sys::swapByteOrder(l0);
791 sys::swapByteOrder(l1);
792 sys::swapByteOrder(l2);
793 sys::swapByteOrder(l3);
795 DumpLiteral16(l0, l1, l2, l3);
799 static void DumpLiteralPointerSection(MachOObjectFile *O,
800 const SectionRef &Section,
801 const char *sect, uint32_t sect_size,
803 bool print_addresses) {
804 // Collect the literal sections in this Mach-O file.
805 std::vector<SectionRef> LiteralSections;
806 for (const SectionRef &Section : O->sections()) {
807 DataRefImpl Ref = Section.getRawDataRefImpl();
808 uint32_t section_type;
810 const MachO::section_64 Sec = O->getSection64(Ref);
811 section_type = Sec.flags & MachO::SECTION_TYPE;
813 const MachO::section Sec = O->getSection(Ref);
814 section_type = Sec.flags & MachO::SECTION_TYPE;
816 if (section_type == MachO::S_CSTRING_LITERALS ||
817 section_type == MachO::S_4BYTE_LITERALS ||
818 section_type == MachO::S_8BYTE_LITERALS ||
819 section_type == MachO::S_16BYTE_LITERALS)
820 LiteralSections.push_back(Section);
823 // Set the size of the literal pointer.
824 uint32_t lp_size = O->is64Bit() ? 8 : 4;
826 // Collect the external relocation symbols for the literal pointers.
827 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
828 for (const RelocationRef &Reloc : Section.relocations()) {
830 MachO::any_relocation_info RE;
831 bool isExtern = false;
832 Rel = Reloc.getRawDataRefImpl();
833 RE = O->getRelocation(Rel);
834 isExtern = O->getPlainRelocationExternal(RE);
836 uint64_t RelocOffset = Reloc.getOffset();
837 symbol_iterator RelocSym = Reloc.getSymbol();
838 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
841 array_pod_sort(Relocs.begin(), Relocs.end());
843 // Dump each literal pointer.
844 for (uint32_t i = 0; i < sect_size; i += lp_size) {
845 if (print_addresses) {
847 outs() << format("%016" PRIx64, sect_addr + i) << " ";
849 outs() << format("%08" PRIx64, sect_addr + i) << " ";
853 memcpy(&lp, sect + i, sizeof(uint64_t));
854 if (O->isLittleEndian() != sys::IsLittleEndianHost)
855 sys::swapByteOrder(lp);
858 memcpy(&li, sect + i, sizeof(uint32_t));
859 if (O->isLittleEndian() != sys::IsLittleEndianHost)
860 sys::swapByteOrder(li);
864 // First look for an external relocation entry for this literal pointer.
865 auto Reloc = std::find_if(
866 Relocs.begin(), Relocs.end(),
867 [&](const std::pair<uint64_t, SymbolRef> &P) { return P.first == i; });
868 if (Reloc != Relocs.end()) {
869 symbol_iterator RelocSym = Reloc->second;
870 Expected<StringRef> SymName = RelocSym->getName();
873 raw_string_ostream OS(Buf);
874 logAllUnhandledErrors(SymName.takeError(), OS, "");
876 report_fatal_error(Buf);
878 outs() << "external relocation entry for symbol:" << *SymName << "\n";
882 // For local references see what the section the literal pointer points to.
883 auto Sect = std::find_if(LiteralSections.begin(), LiteralSections.end(),
884 [&](const SectionRef &R) {
885 return lp >= R.getAddress() &&
886 lp < R.getAddress() + R.getSize();
888 if (Sect == LiteralSections.end()) {
889 outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
893 uint64_t SectAddress = Sect->getAddress();
894 uint64_t SectSize = Sect->getSize();
897 Sect->getName(SectName);
898 DataRefImpl Ref = Sect->getRawDataRefImpl();
899 StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
900 outs() << SegmentName << ":" << SectName << ":";
902 uint32_t section_type;
904 const MachO::section_64 Sec = O->getSection64(Ref);
905 section_type = Sec.flags & MachO::SECTION_TYPE;
907 const MachO::section Sec = O->getSection(Ref);
908 section_type = Sec.flags & MachO::SECTION_TYPE;
912 Sect->getContents(BytesStr);
913 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
915 switch (section_type) {
916 case MachO::S_CSTRING_LITERALS:
917 for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
919 DumpCstringChar(Contents[i]);
923 case MachO::S_4BYTE_LITERALS:
925 memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
927 memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
928 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
929 sys::swapByteOrder(f);
930 sys::swapByteOrder(l);
934 case MachO::S_8BYTE_LITERALS: {
936 memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
938 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
939 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
941 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
942 sys::swapByteOrder(f);
943 sys::swapByteOrder(l0);
944 sys::swapByteOrder(l1);
946 DumpLiteral8(O, l0, l1, d);
949 case MachO::S_16BYTE_LITERALS: {
950 uint32_t l0, l1, l2, l3;
951 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
952 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
954 memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
956 memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
958 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
959 sys::swapByteOrder(l0);
960 sys::swapByteOrder(l1);
961 sys::swapByteOrder(l2);
962 sys::swapByteOrder(l3);
964 DumpLiteral16(l0, l1, l2, l3);
971 static void DumpInitTermPointerSection(MachOObjectFile *O, const char *sect,
972 uint32_t sect_size, uint64_t sect_addr,
973 SymbolAddressMap *AddrMap,
976 stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t);
977 for (uint32_t i = 0; i < sect_size; i += stride) {
978 const char *SymbolName = nullptr;
980 outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
981 uint64_t pointer_value;
982 memcpy(&pointer_value, sect + i, stride);
983 if (O->isLittleEndian() != sys::IsLittleEndianHost)
984 sys::swapByteOrder(pointer_value);
985 outs() << format("0x%016" PRIx64, pointer_value);
987 SymbolName = GuessSymbolName(pointer_value, AddrMap);
989 outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
990 uint32_t pointer_value;
991 memcpy(&pointer_value, sect + i, stride);
992 if (O->isLittleEndian() != sys::IsLittleEndianHost)
993 sys::swapByteOrder(pointer_value);
994 outs() << format("0x%08" PRIx32, pointer_value);
996 SymbolName = GuessSymbolName(pointer_value, AddrMap);
999 outs() << " " << SymbolName;
1004 static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
1005 uint32_t size, uint64_t addr) {
1006 uint32_t cputype = O->getHeader().cputype;
1007 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
1009 for (uint32_t i = 0; i < size; i += j, addr += j) {
1011 outs() << format("%016" PRIx64, addr) << "\t";
1013 outs() << format("%08" PRIx64, addr) << "\t";
1014 for (j = 0; j < 16 && i + j < size; j++) {
1015 uint8_t byte_word = *(sect + i + j);
1016 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1022 for (uint32_t i = 0; i < size; i += j, addr += j) {
1024 outs() << format("%016" PRIx64, addr) << "\t";
1026 outs() << format("%08" PRIx64, addr) << "\t";
1027 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
1028 j += sizeof(int32_t)) {
1029 if (i + j + sizeof(int32_t) <= size) {
1031 memcpy(&long_word, sect + i + j, sizeof(int32_t));
1032 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1033 sys::swapByteOrder(long_word);
1034 outs() << format("%08" PRIx32, long_word) << " ";
1036 for (uint32_t k = 0; i + j + k < size; k++) {
1037 uint8_t byte_word = *(sect + i + j + k);
1038 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1047 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
1048 StringRef DisSegName, StringRef DisSectName);
1049 static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
1050 uint32_t size, uint32_t addr);
1052 static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
1053 uint32_t size, bool verbose,
1054 bool PrintXarHeader, bool PrintXarFileHeaders,
1055 std::string XarMemberName);
1056 #endif // defined(HAVE_LIBXAR)
1058 static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
1060 SymbolAddressMap AddrMap;
1062 CreateSymbolAddressMap(O, &AddrMap);
1064 for (unsigned i = 0; i < FilterSections.size(); ++i) {
1065 StringRef DumpSection = FilterSections[i];
1066 std::pair<StringRef, StringRef> DumpSegSectName;
1067 DumpSegSectName = DumpSection.split(',');
1068 StringRef DumpSegName, DumpSectName;
1069 if (DumpSegSectName.second.size()) {
1070 DumpSegName = DumpSegSectName.first;
1071 DumpSectName = DumpSegSectName.second;
1074 DumpSectName = DumpSegSectName.first;
1076 for (const SectionRef &Section : O->sections()) {
1078 Section.getName(SectName);
1079 DataRefImpl Ref = Section.getRawDataRefImpl();
1080 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1081 if ((DumpSegName.empty() || SegName == DumpSegName) &&
1082 (SectName == DumpSectName)) {
1084 uint32_t section_flags;
1086 const MachO::section_64 Sec = O->getSection64(Ref);
1087 section_flags = Sec.flags;
1090 const MachO::section Sec = O->getSection(Ref);
1091 section_flags = Sec.flags;
1093 uint32_t section_type = section_flags & MachO::SECTION_TYPE;
1096 Section.getContents(BytesStr);
1097 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1098 uint32_t sect_size = BytesStr.size();
1099 uint64_t sect_addr = Section.getAddress();
1101 outs() << "Contents of (" << SegName << "," << SectName
1105 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1106 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1107 DisassembleMachO(Filename, O, SegName, SectName);
1110 if (SegName == "__TEXT" && SectName == "__info_plist") {
1114 if (SegName == "__OBJC" && SectName == "__protocol") {
1115 DumpProtocolSection(O, sect, sect_size, sect_addr);
1119 if (SegName == "__LLVM" && SectName == "__bundle") {
1120 DumpBitcodeSection(O, sect, sect_size, verbose, !NoSymbolicOperands,
1121 ArchiveHeaders, "");
1124 #endif // defined(HAVE_LIBXAR)
1125 switch (section_type) {
1126 case MachO::S_REGULAR:
1127 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1129 case MachO::S_ZEROFILL:
1130 outs() << "zerofill section and has no contents in the file\n";
1132 case MachO::S_CSTRING_LITERALS:
1133 DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1135 case MachO::S_4BYTE_LITERALS:
1136 DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1138 case MachO::S_8BYTE_LITERALS:
1139 DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1141 case MachO::S_16BYTE_LITERALS:
1142 DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1144 case MachO::S_LITERAL_POINTERS:
1145 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
1148 case MachO::S_MOD_INIT_FUNC_POINTERS:
1149 case MachO::S_MOD_TERM_FUNC_POINTERS:
1150 DumpInitTermPointerSection(O, sect, sect_size, sect_addr, &AddrMap,
1154 outs() << "Unknown section type ("
1155 << format("0x%08" PRIx32, section_type) << ")\n";
1156 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1160 if (section_type == MachO::S_ZEROFILL)
1161 outs() << "zerofill section and has no contents in the file\n";
1163 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1170 static void DumpInfoPlistSectionContents(StringRef Filename,
1171 MachOObjectFile *O) {
1172 for (const SectionRef &Section : O->sections()) {
1174 Section.getName(SectName);
1175 DataRefImpl Ref = Section.getRawDataRefImpl();
1176 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1177 if (SegName == "__TEXT" && SectName == "__info_plist") {
1178 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
1180 Section.getContents(BytesStr);
1181 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1188 // checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1189 // and if it is and there is a list of architecture flags is specified then
1190 // check to make sure this Mach-O file is one of those architectures or all
1191 // architectures were specified. If not then an error is generated and this
1192 // routine returns false. Else it returns true.
1193 static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
1194 if (isa<MachOObjectFile>(O) && !ArchAll && ArchFlags.size() != 0) {
1195 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O);
1196 bool ArchFound = false;
1197 MachO::mach_header H;
1198 MachO::mach_header_64 H_64;
1200 if (MachO->is64Bit()) {
1201 H_64 = MachO->MachOObjectFile::getHeader64();
1202 T = MachOObjectFile::getArchTriple(H_64.cputype, H_64.cpusubtype);
1204 H = MachO->MachOObjectFile::getHeader();
1205 T = MachOObjectFile::getArchTriple(H.cputype, H.cpusubtype);
1208 for (i = 0; i < ArchFlags.size(); ++i) {
1209 if (ArchFlags[i] == T.getArchName())
1214 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1215 << "architecture: " + ArchFlags[i] + "\n";
1222 static void printObjcMetaData(MachOObjectFile *O, bool verbose);
1224 // ProcessMachO() is passed a single opened Mach-O file, which may be an
1225 // archive member and or in a slice of a universal file. It prints the
1226 // the file name and header info and then processes it according to the
1227 // command line options.
1228 static void ProcessMachO(StringRef Filename, MachOObjectFile *MachOOF,
1229 StringRef ArchiveMemberName = StringRef(),
1230 StringRef ArchitectureName = StringRef()) {
1231 // If we are doing some processing here on the Mach-O file print the header
1232 // info. And don't print it otherwise like in the case of printing the
1233 // UniversalHeaders or ArchiveHeaders.
1234 if (Disassemble || PrivateHeaders || ExportsTrie || Rebase || Bind || SymbolTable ||
1235 LazyBind || WeakBind || IndirectSymbols || DataInCode || LinkOptHints ||
1236 DylibsUsed || DylibId || ObjcMetaData || (FilterSections.size() != 0)) {
1238 if (!ArchiveMemberName.empty())
1239 outs() << '(' << ArchiveMemberName << ')';
1240 if (!ArchitectureName.empty())
1241 outs() << " (architecture " << ArchitectureName << ")";
1246 DisassembleMachO(Filename, MachOOF, "__TEXT", "__text");
1247 if (IndirectSymbols)
1248 PrintIndirectSymbols(MachOOF, !NonVerbose);
1250 PrintDataInCodeTable(MachOOF, !NonVerbose);
1252 PrintLinkOptHints(MachOOF);
1254 PrintRelocations(MachOOF);
1256 PrintSectionHeaders(MachOOF);
1257 if (SectionContents)
1258 PrintSectionContents(MachOOF);
1259 if (FilterSections.size() != 0)
1260 DumpSectionContents(Filename, MachOOF, !NonVerbose);
1262 DumpInfoPlistSectionContents(Filename, MachOOF);
1264 PrintDylibs(MachOOF, false);
1266 PrintDylibs(MachOOF, true);
1268 StringRef ArchiveName = ArchiveMemberName == StringRef() ? "" : Filename;
1269 PrintSymbolTable(MachOOF, ArchiveName, ArchitectureName);
1272 printMachOUnwindInfo(MachOOF);
1273 if (PrivateHeaders) {
1274 printMachOFileHeader(MachOOF);
1275 printMachOLoadCommands(MachOOF);
1277 if (FirstPrivateHeader)
1278 printMachOFileHeader(MachOOF);
1280 printObjcMetaData(MachOOF, !NonVerbose);
1282 printExportsTrie(MachOOF);
1284 printRebaseTable(MachOOF);
1286 printBindTable(MachOOF);
1288 printLazyBindTable(MachOOF);
1290 printWeakBindTable(MachOOF);
1292 if (DwarfDumpType != DIDT_Null) {
1293 std::unique_ptr<DIContext> DICtx(new DWARFContextInMemory(*MachOOF));
1294 // Dump the complete DWARF structure.
1295 DICtx->dump(outs(), DwarfDumpType, true /* DumpEH */);
1299 // printUnknownCPUType() helps print_fat_headers for unknown CPU's.
1300 static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
1301 outs() << " cputype (" << cputype << ")\n";
1302 outs() << " cpusubtype (" << cpusubtype << ")\n";
1305 // printCPUType() helps print_fat_headers by printing the cputype and
1306 // pusubtype (symbolically for the one's it knows about).
1307 static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
1309 case MachO::CPU_TYPE_I386:
1310 switch (cpusubtype) {
1311 case MachO::CPU_SUBTYPE_I386_ALL:
1312 outs() << " cputype CPU_TYPE_I386\n";
1313 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
1316 printUnknownCPUType(cputype, cpusubtype);
1320 case MachO::CPU_TYPE_X86_64:
1321 switch (cpusubtype) {
1322 case MachO::CPU_SUBTYPE_X86_64_ALL:
1323 outs() << " cputype CPU_TYPE_X86_64\n";
1324 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
1326 case MachO::CPU_SUBTYPE_X86_64_H:
1327 outs() << " cputype CPU_TYPE_X86_64\n";
1328 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
1331 printUnknownCPUType(cputype, cpusubtype);
1335 case MachO::CPU_TYPE_ARM:
1336 switch (cpusubtype) {
1337 case MachO::CPU_SUBTYPE_ARM_ALL:
1338 outs() << " cputype CPU_TYPE_ARM\n";
1339 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
1341 case MachO::CPU_SUBTYPE_ARM_V4T:
1342 outs() << " cputype CPU_TYPE_ARM\n";
1343 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
1345 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1346 outs() << " cputype CPU_TYPE_ARM\n";
1347 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
1349 case MachO::CPU_SUBTYPE_ARM_XSCALE:
1350 outs() << " cputype CPU_TYPE_ARM\n";
1351 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
1353 case MachO::CPU_SUBTYPE_ARM_V6:
1354 outs() << " cputype CPU_TYPE_ARM\n";
1355 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
1357 case MachO::CPU_SUBTYPE_ARM_V6M:
1358 outs() << " cputype CPU_TYPE_ARM\n";
1359 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
1361 case MachO::CPU_SUBTYPE_ARM_V7:
1362 outs() << " cputype CPU_TYPE_ARM\n";
1363 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
1365 case MachO::CPU_SUBTYPE_ARM_V7EM:
1366 outs() << " cputype CPU_TYPE_ARM\n";
1367 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
1369 case MachO::CPU_SUBTYPE_ARM_V7K:
1370 outs() << " cputype CPU_TYPE_ARM\n";
1371 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
1373 case MachO::CPU_SUBTYPE_ARM_V7M:
1374 outs() << " cputype CPU_TYPE_ARM\n";
1375 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
1377 case MachO::CPU_SUBTYPE_ARM_V7S:
1378 outs() << " cputype CPU_TYPE_ARM\n";
1379 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
1382 printUnknownCPUType(cputype, cpusubtype);
1386 case MachO::CPU_TYPE_ARM64:
1387 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1388 case MachO::CPU_SUBTYPE_ARM64_ALL:
1389 outs() << " cputype CPU_TYPE_ARM64\n";
1390 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
1393 printUnknownCPUType(cputype, cpusubtype);
1398 printUnknownCPUType(cputype, cpusubtype);
1403 static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
1405 outs() << "Fat headers\n";
1407 if (UB->getMagic() == MachO::FAT_MAGIC)
1408 outs() << "fat_magic FAT_MAGIC\n";
1409 else // UB->getMagic() == MachO::FAT_MAGIC_64
1410 outs() << "fat_magic FAT_MAGIC_64\n";
1412 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
1414 uint32_t nfat_arch = UB->getNumberOfObjects();
1415 StringRef Buf = UB->getData();
1416 uint64_t size = Buf.size();
1417 uint64_t big_size = sizeof(struct MachO::fat_header) +
1418 nfat_arch * sizeof(struct MachO::fat_arch);
1419 outs() << "nfat_arch " << UB->getNumberOfObjects();
1421 outs() << " (malformed, contains zero architecture types)\n";
1422 else if (big_size > size)
1423 outs() << " (malformed, architectures past end of file)\n";
1427 for (uint32_t i = 0; i < nfat_arch; ++i) {
1428 MachOUniversalBinary::ObjectForArch OFA(UB, i);
1429 uint32_t cputype = OFA.getCPUType();
1430 uint32_t cpusubtype = OFA.getCPUSubType();
1431 outs() << "architecture ";
1432 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
1433 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
1434 uint32_t other_cputype = other_OFA.getCPUType();
1435 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
1436 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
1437 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
1438 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
1439 outs() << "(illegal duplicate architecture) ";
1444 outs() << OFA.getArchTypeName() << "\n";
1445 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1447 outs() << i << "\n";
1448 outs() << " cputype " << cputype << "\n";
1449 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
1453 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
1454 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
1456 outs() << " capabilities "
1457 << format("0x%" PRIx32,
1458 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
1459 outs() << " offset " << OFA.getOffset();
1460 if (OFA.getOffset() > size)
1461 outs() << " (past end of file)";
1462 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
1463 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
1465 outs() << " size " << OFA.getSize();
1466 big_size = OFA.getOffset() + OFA.getSize();
1467 if (big_size > size)
1468 outs() << " (past end of file)";
1470 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
1475 static void printArchiveChild(const Archive::Child &C, bool verbose,
1476 bool print_offset) {
1478 outs() << C.getChildOffset() << "\t";
1479 sys::fs::perms Mode = C.getAccessMode();
1481 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
1482 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
1484 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
1485 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
1486 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
1487 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
1488 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
1489 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
1490 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
1491 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
1492 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
1494 outs() << format("0%o ", Mode);
1497 unsigned UID = C.getUID();
1498 outs() << format("%3d/", UID);
1499 unsigned GID = C.getGID();
1500 outs() << format("%-3d ", GID);
1501 ErrorOr<uint64_t> Size = C.getRawSize();
1502 if (std::error_code EC = Size.getError())
1503 report_fatal_error(EC.message());
1504 outs() << format("%5" PRId64, Size.get()) << " ";
1506 StringRef RawLastModified = C.getRawLastModified();
1509 if (RawLastModified.getAsInteger(10, Seconds))
1510 outs() << "(date: \"%s\" contains non-decimal chars) " << RawLastModified;
1512 // Since cime(3) returns a 26 character string of the form:
1513 // "Sun Sep 16 01:03:52 1973\n\0"
1514 // just print 24 characters.
1516 outs() << format("%.24s ", ctime(&t));
1519 outs() << RawLastModified << " ";
1523 ErrorOr<StringRef> NameOrErr = C.getName();
1524 if (NameOrErr.getError()) {
1525 StringRef RawName = C.getRawName();
1526 outs() << RawName << "\n";
1528 StringRef Name = NameOrErr.get();
1529 outs() << Name << "\n";
1532 StringRef RawName = C.getRawName();
1533 outs() << RawName << "\n";
1537 static void printArchiveHeaders(Archive *A, bool verbose, bool print_offset) {
1539 for (const auto &C : A->children(Err, false))
1540 printArchiveChild(C, verbose, print_offset);
1542 report_fatal_error(std::move(Err));
1545 // ParseInputMachO() parses the named Mach-O file in Filename and handles the
1546 // -arch flags selecting just those slices as specified by them and also parses
1547 // archive files. Then for each individual Mach-O file ProcessMachO() is
1548 // called to process the file based on the command line options.
1549 void llvm::ParseInputMachO(StringRef Filename) {
1550 // Check for -arch all and verifiy the -arch flags are valid.
1551 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1552 if (ArchFlags[i] == "all") {
1555 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
1556 errs() << "llvm-objdump: Unknown architecture named '" + ArchFlags[i] +
1557 "'for the -arch option\n";
1563 // Attempt to open the binary.
1564 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
1566 report_error(Filename, BinaryOrErr.takeError());
1567 Binary &Bin = *BinaryOrErr.get().getBinary();
1569 if (Archive *A = dyn_cast<Archive>(&Bin)) {
1570 outs() << "Archive : " << Filename << "\n";
1572 printArchiveHeaders(A, !NonVerbose, ArchiveMemberOffsets);
1574 for (auto &C : A->children(Err)) {
1575 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1577 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
1578 report_error(Filename, C, std::move(E));
1581 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1582 if (!checkMachOAndArchFlags(O, Filename))
1584 ProcessMachO(Filename, O, O->getFileName());
1588 report_error(Filename, std::move(Err));
1591 if (UniversalHeaders) {
1592 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin))
1593 printMachOUniversalHeaders(UB, !NonVerbose);
1595 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
1596 // If we have a list of architecture flags specified dump only those.
1597 if (!ArchAll && ArchFlags.size() != 0) {
1598 // Look for a slice in the universal binary that matches each ArchFlag.
1600 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1602 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1603 E = UB->end_objects();
1605 if (ArchFlags[i] == I->getArchTypeName()) {
1607 Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
1608 I->getAsObjectFile();
1609 std::string ArchitectureName = "";
1610 if (ArchFlags.size() > 1)
1611 ArchitectureName = I->getArchTypeName();
1613 ObjectFile &O = *ObjOrErr.get();
1614 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
1615 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
1616 } else if (auto E = isNotObjectErrorInvalidFileType(
1617 ObjOrErr.takeError())) {
1618 report_error(Filename, StringRef(), std::move(E),
1621 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
1622 I->getAsArchive()) {
1623 std::unique_ptr<Archive> &A = *AOrErr;
1624 outs() << "Archive : " << Filename;
1625 if (!ArchitectureName.empty())
1626 outs() << " (architecture " << ArchitectureName << ")";
1629 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
1631 for (auto &C : A->children(Err)) {
1632 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1634 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
1635 report_error(Filename, C, std::move(E), ArchitectureName);
1638 if (MachOObjectFile *O =
1639 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
1640 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
1643 report_error(Filename, std::move(Err));
1645 consumeError(AOrErr.takeError());
1646 error("Mach-O universal file: " + Filename + " for " +
1647 "architecture " + StringRef(I->getArchTypeName()) +
1648 " is not a Mach-O file or an archive file");
1653 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1654 << "architecture: " + ArchFlags[i] + "\n";
1660 // No architecture flags were specified so if this contains a slice that
1661 // matches the host architecture dump only that.
1663 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1664 E = UB->end_objects();
1666 if (MachOObjectFile::getHostArch().getArchName() ==
1667 I->getArchTypeName()) {
1668 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
1669 std::string ArchiveName;
1670 ArchiveName.clear();
1672 ObjectFile &O = *ObjOrErr.get();
1673 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
1674 ProcessMachO(Filename, MachOOF);
1675 } else if (auto E = isNotObjectErrorInvalidFileType(
1676 ObjOrErr.takeError())) {
1677 report_error(Filename, std::move(E));
1679 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
1680 I->getAsArchive()) {
1681 std::unique_ptr<Archive> &A = *AOrErr;
1682 outs() << "Archive : " << Filename << "\n";
1684 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
1686 for (auto &C : A->children(Err)) {
1687 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1689 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
1690 report_error(Filename, C, std::move(E));
1693 if (MachOObjectFile *O =
1694 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
1695 ProcessMachO(Filename, O, O->getFileName());
1698 report_error(Filename, std::move(Err));
1700 consumeError(AOrErr.takeError());
1701 error("Mach-O universal file: " + Filename + " for architecture " +
1702 StringRef(I->getArchTypeName()) +
1703 " is not a Mach-O file or an archive file");
1709 // Either all architectures have been specified or none have been specified
1710 // and this does not contain the host architecture so dump all the slices.
1711 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
1712 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1713 E = UB->end_objects();
1715 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
1716 std::string ArchitectureName = "";
1717 if (moreThanOneArch)
1718 ArchitectureName = I->getArchTypeName();
1720 ObjectFile &Obj = *ObjOrErr.get();
1721 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
1722 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
1723 } else if (auto E = isNotObjectErrorInvalidFileType(
1724 ObjOrErr.takeError())) {
1725 report_error(StringRef(), Filename, std::move(E), ArchitectureName);
1727 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
1728 I->getAsArchive()) {
1729 std::unique_ptr<Archive> &A = *AOrErr;
1730 outs() << "Archive : " << Filename;
1731 if (!ArchitectureName.empty())
1732 outs() << " (architecture " << ArchitectureName << ")";
1735 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
1737 for (auto &C : A->children(Err)) {
1738 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1740 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
1741 report_error(Filename, C, std::move(E), ArchitectureName);
1744 if (MachOObjectFile *O =
1745 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1746 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
1747 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
1752 report_error(Filename, std::move(Err));
1754 consumeError(AOrErr.takeError());
1755 error("Mach-O universal file: " + Filename + " for architecture " +
1756 StringRef(I->getArchTypeName()) +
1757 " is not a Mach-O file or an archive file");
1762 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
1763 if (!checkMachOAndArchFlags(O, Filename))
1765 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) {
1766 ProcessMachO(Filename, MachOOF);
1768 errs() << "llvm-objdump: '" << Filename << "': "
1769 << "Object is not a Mach-O file type.\n";
1772 llvm_unreachable("Input object can't be invalid at this point");
1775 typedef std::pair<uint64_t, const char *> BindInfoEntry;
1776 typedef std::vector<BindInfoEntry> BindTable;
1777 typedef BindTable::iterator bind_table_iterator;
1779 // The block of info used by the Symbolizer call backs.
1780 struct DisassembleInfo {
1784 SymbolAddressMap *AddrMap;
1785 std::vector<SectionRef> *Sections;
1786 const char *class_name;
1787 const char *selector_name;
1789 char *demangled_name;
1792 BindTable *bindtable;
1796 // SymbolizerGetOpInfo() is the operand information call back function.
1797 // This is called to get the symbolic information for operand(s) of an
1798 // instruction when it is being done. This routine does this from
1799 // the relocation information, symbol table, etc. That block of information
1800 // is a pointer to the struct DisassembleInfo that was passed when the
1801 // disassembler context was created and passed to back to here when
1802 // called back by the disassembler for instruction operands that could have
1803 // relocation information. The address of the instruction containing operand is
1804 // at the Pc parameter. The immediate value the operand has is passed in
1805 // op_info->Value and is at Offset past the start of the instruction and has a
1806 // byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
1807 // LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
1808 // names and addends of the symbolic expression to add for the operand. The
1809 // value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
1810 // information is returned then this function returns 1 else it returns 0.
1811 static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
1812 uint64_t Size, int TagType, void *TagBuf) {
1813 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
1814 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
1815 uint64_t value = op_info->Value;
1817 // Make sure all fields returned are zero if we don't set them.
1818 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
1819 op_info->Value = value;
1821 // If the TagType is not the value 1 which it code knows about or if no
1822 // verbose symbolic information is wanted then just return 0, indicating no
1823 // information is being returned.
1824 if (TagType != 1 || !info->verbose)
1827 unsigned int Arch = info->O->getArch();
1828 if (Arch == Triple::x86) {
1829 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1831 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1833 // Search the external relocation entries of a fully linked image
1834 // (if any) for an entry that matches this segment offset.
1835 // uint32_t seg_offset = (Pc + Offset);
1838 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1839 // for an entry for this section offset.
1840 uint32_t sect_addr = info->S.getAddress();
1841 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1842 bool reloc_found = false;
1844 MachO::any_relocation_info RE;
1845 bool isExtern = false;
1847 bool r_scattered = false;
1848 uint32_t r_value, pair_r_value, r_type;
1849 for (const RelocationRef &Reloc : info->S.relocations()) {
1850 uint64_t RelocOffset = Reloc.getOffset();
1851 if (RelocOffset == sect_offset) {
1852 Rel = Reloc.getRawDataRefImpl();
1853 RE = info->O->getRelocation(Rel);
1854 r_type = info->O->getAnyRelocationType(RE);
1855 r_scattered = info->O->isRelocationScattered(RE);
1857 r_value = info->O->getScatteredRelocationValue(RE);
1858 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1859 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
1860 DataRefImpl RelNext = Rel;
1861 info->O->moveRelocationNext(RelNext);
1862 MachO::any_relocation_info RENext;
1863 RENext = info->O->getRelocation(RelNext);
1864 if (info->O->isRelocationScattered(RENext))
1865 pair_r_value = info->O->getScatteredRelocationValue(RENext);
1870 isExtern = info->O->getPlainRelocationExternal(RE);
1872 symbol_iterator RelocSym = Reloc.getSymbol();
1880 if (reloc_found && isExtern) {
1881 Expected<StringRef> SymName = Symbol.getName();
1884 raw_string_ostream OS(Buf);
1885 logAllUnhandledErrors(SymName.takeError(), OS, "");
1887 report_fatal_error(Buf);
1889 const char *name = SymName->data();
1890 op_info->AddSymbol.Present = 1;
1891 op_info->AddSymbol.Name = name;
1892 // For i386 extern relocation entries the value in the instruction is
1893 // the offset from the symbol, and value is already set in op_info->Value.
1896 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1897 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
1898 const char *add = GuessSymbolName(r_value, info->AddrMap);
1899 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
1900 uint32_t offset = value - (r_value - pair_r_value);
1901 op_info->AddSymbol.Present = 1;
1903 op_info->AddSymbol.Name = add;
1905 op_info->AddSymbol.Value = r_value;
1906 op_info->SubtractSymbol.Present = 1;
1908 op_info->SubtractSymbol.Name = sub;
1910 op_info->SubtractSymbol.Value = pair_r_value;
1911 op_info->Value = offset;
1916 if (Arch == Triple::x86_64) {
1917 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1919 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1921 // Search the external relocation entries of a fully linked image
1922 // (if any) for an entry that matches this segment offset.
1923 // uint64_t seg_offset = (Pc + Offset);
1926 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1927 // for an entry for this section offset.
1928 uint64_t sect_addr = info->S.getAddress();
1929 uint64_t sect_offset = (Pc + Offset) - sect_addr;
1930 bool reloc_found = false;
1932 MachO::any_relocation_info RE;
1933 bool isExtern = false;
1935 for (const RelocationRef &Reloc : info->S.relocations()) {
1936 uint64_t RelocOffset = Reloc.getOffset();
1937 if (RelocOffset == sect_offset) {
1938 Rel = Reloc.getRawDataRefImpl();
1939 RE = info->O->getRelocation(Rel);
1940 // NOTE: Scattered relocations don't exist on x86_64.
1941 isExtern = info->O->getPlainRelocationExternal(RE);
1943 symbol_iterator RelocSym = Reloc.getSymbol();
1950 if (reloc_found && isExtern) {
1951 // The Value passed in will be adjusted by the Pc if the instruction
1952 // adds the Pc. But for x86_64 external relocation entries the Value
1953 // is the offset from the external symbol.
1954 if (info->O->getAnyRelocationPCRel(RE))
1955 op_info->Value -= Pc + Offset + Size;
1956 Expected<StringRef> SymName = Symbol.getName();
1959 raw_string_ostream OS(Buf);
1960 logAllUnhandledErrors(SymName.takeError(), OS, "");
1962 report_fatal_error(Buf);
1964 const char *name = SymName->data();
1965 unsigned Type = info->O->getAnyRelocationType(RE);
1966 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
1967 DataRefImpl RelNext = Rel;
1968 info->O->moveRelocationNext(RelNext);
1969 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
1970 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
1971 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
1972 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
1973 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
1974 op_info->SubtractSymbol.Present = 1;
1975 op_info->SubtractSymbol.Name = name;
1976 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
1977 Symbol = *RelocSymNext;
1978 Expected<StringRef> SymNameNext = Symbol.getName();
1981 raw_string_ostream OS(Buf);
1982 logAllUnhandledErrors(SymNameNext.takeError(), OS, "");
1984 report_fatal_error(Buf);
1986 name = SymNameNext->data();
1989 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
1990 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
1991 op_info->AddSymbol.Present = 1;
1992 op_info->AddSymbol.Name = name;
1997 if (Arch == Triple::arm) {
1998 if (Offset != 0 || (Size != 4 && Size != 2))
2000 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2002 // Search the external relocation entries of a fully linked image
2003 // (if any) for an entry that matches this segment offset.
2004 // uint32_t seg_offset = (Pc + Offset);
2007 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2008 // for an entry for this section offset.
2009 uint32_t sect_addr = info->S.getAddress();
2010 uint32_t sect_offset = (Pc + Offset) - sect_addr;
2012 MachO::any_relocation_info RE;
2013 bool isExtern = false;
2015 bool r_scattered = false;
2016 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
2018 std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
2019 [&](const RelocationRef &Reloc) {
2020 uint64_t RelocOffset = Reloc.getOffset();
2021 return RelocOffset == sect_offset;
2024 if (Reloc == info->S.relocations().end())
2027 Rel = Reloc->getRawDataRefImpl();
2028 RE = info->O->getRelocation(Rel);
2029 r_length = info->O->getAnyRelocationLength(RE);
2030 r_scattered = info->O->isRelocationScattered(RE);
2032 r_value = info->O->getScatteredRelocationValue(RE);
2033 r_type = info->O->getScatteredRelocationType(RE);
2035 r_type = info->O->getAnyRelocationType(RE);
2036 isExtern = info->O->getPlainRelocationExternal(RE);
2038 symbol_iterator RelocSym = Reloc->getSymbol();
2042 if (r_type == MachO::ARM_RELOC_HALF ||
2043 r_type == MachO::ARM_RELOC_SECTDIFF ||
2044 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
2045 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2046 DataRefImpl RelNext = Rel;
2047 info->O->moveRelocationNext(RelNext);
2048 MachO::any_relocation_info RENext;
2049 RENext = info->O->getRelocation(RelNext);
2050 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
2051 if (info->O->isRelocationScattered(RENext))
2052 pair_r_value = info->O->getScatteredRelocationValue(RENext);
2056 Expected<StringRef> SymName = Symbol.getName();
2059 raw_string_ostream OS(Buf);
2060 logAllUnhandledErrors(SymName.takeError(), OS, "");
2062 report_fatal_error(Buf);
2064 const char *name = SymName->data();
2065 op_info->AddSymbol.Present = 1;
2066 op_info->AddSymbol.Name = name;
2068 case MachO::ARM_RELOC_HALF:
2069 if ((r_length & 0x1) == 1) {
2070 op_info->Value = value << 16 | other_half;
2071 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2073 op_info->Value = other_half << 16 | value;
2074 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
2082 // If we have a branch that is not an external relocation entry then
2083 // return 0 so the code in tryAddingSymbolicOperand() can use the
2084 // SymbolLookUp call back with the branch target address to look up the
2085 // symbol and possiblity add an annotation for a symbol stub.
2086 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
2087 r_type == MachO::ARM_THUMB_RELOC_BR22))
2090 uint32_t offset = 0;
2091 if (r_type == MachO::ARM_RELOC_HALF ||
2092 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2093 if ((r_length & 0x1) == 1)
2094 value = value << 16 | other_half;
2096 value = other_half << 16 | value;
2098 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
2099 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
2100 offset = value - r_value;
2104 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2105 if ((r_length & 0x1) == 1)
2106 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2108 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
2109 const char *add = GuessSymbolName(r_value, info->AddrMap);
2110 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
2111 int32_t offset = value - (r_value - pair_r_value);
2112 op_info->AddSymbol.Present = 1;
2114 op_info->AddSymbol.Name = add;
2116 op_info->AddSymbol.Value = r_value;
2117 op_info->SubtractSymbol.Present = 1;
2119 op_info->SubtractSymbol.Name = sub;
2121 op_info->SubtractSymbol.Value = pair_r_value;
2122 op_info->Value = offset;
2126 op_info->AddSymbol.Present = 1;
2127 op_info->Value = offset;
2128 if (r_type == MachO::ARM_RELOC_HALF) {
2129 if ((r_length & 0x1) == 1)
2130 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2132 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
2134 const char *add = GuessSymbolName(value, info->AddrMap);
2135 if (add != nullptr) {
2136 op_info->AddSymbol.Name = add;
2139 op_info->AddSymbol.Value = value;
2142 if (Arch == Triple::aarch64) {
2143 if (Offset != 0 || Size != 4)
2145 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2147 // Search the external relocation entries of a fully linked image
2148 // (if any) for an entry that matches this segment offset.
2149 // uint64_t seg_offset = (Pc + Offset);
2152 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2153 // for an entry for this section offset.
2154 uint64_t sect_addr = info->S.getAddress();
2155 uint64_t sect_offset = (Pc + Offset) - sect_addr;
2157 std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
2158 [&](const RelocationRef &Reloc) {
2159 uint64_t RelocOffset = Reloc.getOffset();
2160 return RelocOffset == sect_offset;
2163 if (Reloc == info->S.relocations().end())
2166 DataRefImpl Rel = Reloc->getRawDataRefImpl();
2167 MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2168 uint32_t r_type = info->O->getAnyRelocationType(RE);
2169 if (r_type == MachO::ARM64_RELOC_ADDEND) {
2170 DataRefImpl RelNext = Rel;
2171 info->O->moveRelocationNext(RelNext);
2172 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2174 value = info->O->getPlainRelocationSymbolNum(RENext);
2175 op_info->Value = value;
2178 // NOTE: Scattered relocations don't exist on arm64.
2179 if (!info->O->getPlainRelocationExternal(RE))
2181 Expected<StringRef> SymName = Reloc->getSymbol()->getName();
2184 raw_string_ostream OS(Buf);
2185 logAllUnhandledErrors(SymName.takeError(), OS, "");
2187 report_fatal_error(Buf);
2189 const char *name = SymName->data();
2190 op_info->AddSymbol.Present = 1;
2191 op_info->AddSymbol.Name = name;
2194 case MachO::ARM64_RELOC_PAGE21:
2196 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2198 case MachO::ARM64_RELOC_PAGEOFF12:
2200 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2202 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2204 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2206 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2208 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2210 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2211 /* @tvlppage is not implemented in llvm-mc */
2212 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2214 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2215 /* @tvlppageoff is not implemented in llvm-mc */
2216 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2219 case MachO::ARM64_RELOC_BRANCH26:
2220 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2228 // GuessCstringPointer is passed the address of what might be a pointer to a
2229 // literal string in a cstring section. If that address is in a cstring section
2230 // it returns a pointer to that string. Else it returns nullptr.
2231 static const char *GuessCstringPointer(uint64_t ReferenceValue,
2232 struct DisassembleInfo *info) {
2233 for (const auto &Load : info->O->load_commands()) {
2234 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2235 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2236 for (unsigned J = 0; J < Seg.nsects; ++J) {
2237 MachO::section_64 Sec = info->O->getSection64(Load, J);
2238 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2239 if (section_type == MachO::S_CSTRING_LITERALS &&
2240 ReferenceValue >= Sec.addr &&
2241 ReferenceValue < Sec.addr + Sec.size) {
2242 uint64_t sect_offset = ReferenceValue - Sec.addr;
2243 uint64_t object_offset = Sec.offset + sect_offset;
2244 StringRef MachOContents = info->O->getData();
2245 uint64_t object_size = MachOContents.size();
2246 const char *object_addr = (const char *)MachOContents.data();
2247 if (object_offset < object_size) {
2248 const char *name = object_addr + object_offset;
2255 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2256 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2257 for (unsigned J = 0; J < Seg.nsects; ++J) {
2258 MachO::section Sec = info->O->getSection(Load, J);
2259 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2260 if (section_type == MachO::S_CSTRING_LITERALS &&
2261 ReferenceValue >= Sec.addr &&
2262 ReferenceValue < Sec.addr + Sec.size) {
2263 uint64_t sect_offset = ReferenceValue - Sec.addr;
2264 uint64_t object_offset = Sec.offset + sect_offset;
2265 StringRef MachOContents = info->O->getData();
2266 uint64_t object_size = MachOContents.size();
2267 const char *object_addr = (const char *)MachOContents.data();
2268 if (object_offset < object_size) {
2269 const char *name = object_addr + object_offset;
2281 // GuessIndirectSymbol returns the name of the indirect symbol for the
2282 // ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
2283 // an address of a symbol stub or a lazy or non-lazy pointer to associate the
2284 // symbol name being referenced by the stub or pointer.
2285 static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2286 struct DisassembleInfo *info) {
2287 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
2288 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
2289 for (const auto &Load : info->O->load_commands()) {
2290 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2291 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2292 for (unsigned J = 0; J < Seg.nsects; ++J) {
2293 MachO::section_64 Sec = info->O->getSection64(Load, J);
2294 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2295 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2296 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2297 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2298 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2299 section_type == MachO::S_SYMBOL_STUBS) &&
2300 ReferenceValue >= Sec.addr &&
2301 ReferenceValue < Sec.addr + Sec.size) {
2303 if (section_type == MachO::S_SYMBOL_STUBS)
2304 stride = Sec.reserved2;
2309 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2310 if (index < Dysymtab.nindirectsyms) {
2311 uint32_t indirect_symbol =
2312 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
2313 if (indirect_symbol < Symtab.nsyms) {
2314 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2315 SymbolRef Symbol = *Sym;
2316 Expected<StringRef> SymName = Symbol.getName();
2319 raw_string_ostream OS(Buf);
2320 logAllUnhandledErrors(SymName.takeError(), OS, "");
2322 report_fatal_error(Buf);
2324 const char *name = SymName->data();
2330 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2331 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2332 for (unsigned J = 0; J < Seg.nsects; ++J) {
2333 MachO::section Sec = info->O->getSection(Load, J);
2334 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2335 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2336 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2337 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2338 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2339 section_type == MachO::S_SYMBOL_STUBS) &&
2340 ReferenceValue >= Sec.addr &&
2341 ReferenceValue < Sec.addr + Sec.size) {
2343 if (section_type == MachO::S_SYMBOL_STUBS)
2344 stride = Sec.reserved2;
2349 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2350 if (index < Dysymtab.nindirectsyms) {
2351 uint32_t indirect_symbol =
2352 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
2353 if (indirect_symbol < Symtab.nsyms) {
2354 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2355 SymbolRef Symbol = *Sym;
2356 Expected<StringRef> SymName = Symbol.getName();
2359 raw_string_ostream OS(Buf);
2360 logAllUnhandledErrors(SymName.takeError(), OS, "");
2362 report_fatal_error(Buf);
2364 const char *name = SymName->data();
2375 // method_reference() is called passing it the ReferenceName that might be
2376 // a reference it to an Objective-C method call. If so then it allocates and
2377 // assembles a method call string with the values last seen and saved in
2378 // the DisassembleInfo's class_name and selector_name fields. This is saved
2379 // into the method field of the info and any previous string is free'ed.
2380 // Then the class_name field in the info is set to nullptr. The method call
2381 // string is set into ReferenceName and ReferenceType is set to
2382 // LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
2383 // then both ReferenceType and ReferenceName are left unchanged.
2384 static void method_reference(struct DisassembleInfo *info,
2385 uint64_t *ReferenceType,
2386 const char **ReferenceName) {
2387 unsigned int Arch = info->O->getArch();
2388 if (*ReferenceName != nullptr) {
2389 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
2390 if (info->selector_name != nullptr) {
2391 if (info->method != nullptr)
2393 if (info->class_name != nullptr) {
2394 info->method = (char *)malloc(5 + strlen(info->class_name) +
2395 strlen(info->selector_name));
2396 if (info->method != nullptr) {
2397 strcpy(info->method, "+[");
2398 strcat(info->method, info->class_name);
2399 strcat(info->method, " ");
2400 strcat(info->method, info->selector_name);
2401 strcat(info->method, "]");
2402 *ReferenceName = info->method;
2403 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2406 info->method = (char *)malloc(9 + strlen(info->selector_name));
2407 if (info->method != nullptr) {
2408 if (Arch == Triple::x86_64)
2409 strcpy(info->method, "-[%rdi ");
2410 else if (Arch == Triple::aarch64)
2411 strcpy(info->method, "-[x0 ");
2413 strcpy(info->method, "-[r? ");
2414 strcat(info->method, info->selector_name);
2415 strcat(info->method, "]");
2416 *ReferenceName = info->method;
2417 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2420 info->class_name = nullptr;
2422 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
2423 if (info->selector_name != nullptr) {
2424 if (info->method != nullptr)
2426 info->method = (char *)malloc(17 + strlen(info->selector_name));
2427 if (info->method != nullptr) {
2428 if (Arch == Triple::x86_64)
2429 strcpy(info->method, "-[[%rdi super] ");
2430 else if (Arch == Triple::aarch64)
2431 strcpy(info->method, "-[[x0 super] ");
2433 strcpy(info->method, "-[[r? super] ");
2434 strcat(info->method, info->selector_name);
2435 strcat(info->method, "]");
2436 *ReferenceName = info->method;
2437 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2439 info->class_name = nullptr;
2445 // GuessPointerPointer() is passed the address of what might be a pointer to
2446 // a reference to an Objective-C class, selector, message ref or cfstring.
2447 // If so the value of the pointer is returned and one of the booleans are set
2448 // to true. If not zero is returned and all the booleans are set to false.
2449 static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
2450 struct DisassembleInfo *info,
2451 bool &classref, bool &selref, bool &msgref,
2457 for (const auto &Load : info->O->load_commands()) {
2458 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2459 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2460 for (unsigned J = 0; J < Seg.nsects; ++J) {
2461 MachO::section_64 Sec = info->O->getSection64(Load, J);
2462 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
2463 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2464 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
2465 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
2466 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
2467 ReferenceValue >= Sec.addr &&
2468 ReferenceValue < Sec.addr + Sec.size) {
2469 uint64_t sect_offset = ReferenceValue - Sec.addr;
2470 uint64_t object_offset = Sec.offset + sect_offset;
2471 StringRef MachOContents = info->O->getData();
2472 uint64_t object_size = MachOContents.size();
2473 const char *object_addr = (const char *)MachOContents.data();
2474 if (object_offset < object_size) {
2475 uint64_t pointer_value;
2476 memcpy(&pointer_value, object_addr + object_offset,
2478 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2479 sys::swapByteOrder(pointer_value);
2480 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
2482 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2483 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
2485 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
2486 ReferenceValue + 8 < Sec.addr + Sec.size) {
2488 memcpy(&pointer_value, object_addr + object_offset + 8,
2490 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2491 sys::swapByteOrder(pointer_value);
2492 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
2494 return pointer_value;
2501 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
2506 // get_pointer_64 returns a pointer to the bytes in the object file at the
2507 // Address from a section in the Mach-O file. And indirectly returns the
2508 // offset into the section, number of bytes left in the section past the offset
2509 // and which section is was being referenced. If the Address is not in a
2510 // section nullptr is returned.
2511 static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
2512 uint32_t &left, SectionRef &S,
2513 DisassembleInfo *info,
2514 bool objc_only = false) {
2518 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
2519 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
2520 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
2525 ((*(info->Sections))[SectIdx]).getName(SectName);
2526 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
2527 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
2528 if (SegName != "__OBJC" && SectName != "__cstring")
2531 if (Address >= SectAddress && Address < SectAddress + SectSize) {
2532 S = (*(info->Sections))[SectIdx];
2533 offset = Address - SectAddress;
2534 left = SectSize - offset;
2535 StringRef SectContents;
2536 ((*(info->Sections))[SectIdx]).getContents(SectContents);
2537 return SectContents.data() + offset;
2543 static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
2544 uint32_t &left, SectionRef &S,
2545 DisassembleInfo *info,
2546 bool objc_only = false) {
2547 return get_pointer_64(Address, offset, left, S, info, objc_only);
2550 // get_symbol_64() returns the name of a symbol (or nullptr) and the address of
2551 // the symbol indirectly through n_value. Based on the relocation information
2552 // for the specified section offset in the specified section reference.
2553 // If no relocation information is found and a non-zero ReferenceValue for the
2554 // symbol is passed, look up that address in the info's AddrMap.
2555 static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
2556 DisassembleInfo *info, uint64_t &n_value,
2557 uint64_t ReferenceValue = 0) {
2562 // See if there is an external relocation entry at the sect_offset.
2563 bool reloc_found = false;
2565 MachO::any_relocation_info RE;
2566 bool isExtern = false;
2568 for (const RelocationRef &Reloc : S.relocations()) {
2569 uint64_t RelocOffset = Reloc.getOffset();
2570 if (RelocOffset == sect_offset) {
2571 Rel = Reloc.getRawDataRefImpl();
2572 RE = info->O->getRelocation(Rel);
2573 if (info->O->isRelocationScattered(RE))
2575 isExtern = info->O->getPlainRelocationExternal(RE);
2577 symbol_iterator RelocSym = Reloc.getSymbol();
2584 // If there is an external relocation entry for a symbol in this section
2585 // at this section_offset then use that symbol's value for the n_value
2586 // and return its name.
2587 const char *SymbolName = nullptr;
2588 if (reloc_found && isExtern) {
2589 n_value = Symbol.getValue();
2590 Expected<StringRef> NameOrError = Symbol.getName();
2593 raw_string_ostream OS(Buf);
2594 logAllUnhandledErrors(NameOrError.takeError(), OS, "");
2596 report_fatal_error(Buf);
2598 StringRef Name = *NameOrError;
2599 if (!Name.empty()) {
2600 SymbolName = Name.data();
2605 // TODO: For fully linked images, look through the external relocation
2606 // entries off the dynamic symtab command. For these the r_offset is from the
2607 // start of the first writeable segment in the Mach-O file. So the offset
2608 // to this section from that segment is passed to this routine by the caller,
2609 // as the database_offset. Which is the difference of the section's starting
2610 // address and the first writable segment.
2612 // NOTE: need add passing the database_offset to this routine.
2614 // We did not find an external relocation entry so look up the ReferenceValue
2615 // as an address of a symbol and if found return that symbol's name.
2616 SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
2621 static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
2622 DisassembleInfo *info,
2623 uint32_t ReferenceValue) {
2625 return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
2628 // These are structs in the Objective-C meta data and read to produce the
2629 // comments for disassembly. While these are part of the ABI they are no
2630 // public defintions. So the are here not in include/llvm/Support/MachO.h .
2632 // The cfstring object in a 64-bit Mach-O file.
2633 struct cfstring64_t {
2634 uint64_t isa; // class64_t * (64-bit pointer)
2635 uint64_t flags; // flag bits
2636 uint64_t characters; // char * (64-bit pointer)
2637 uint64_t length; // number of non-NULL characters in above
2640 // The class object in a 64-bit Mach-O file.
2642 uint64_t isa; // class64_t * (64-bit pointer)
2643 uint64_t superclass; // class64_t * (64-bit pointer)
2644 uint64_t cache; // Cache (64-bit pointer)
2645 uint64_t vtable; // IMP * (64-bit pointer)
2646 uint64_t data; // class_ro64_t * (64-bit pointer)
2650 uint32_t isa; /* class32_t * (32-bit pointer) */
2651 uint32_t superclass; /* class32_t * (32-bit pointer) */
2652 uint32_t cache; /* Cache (32-bit pointer) */
2653 uint32_t vtable; /* IMP * (32-bit pointer) */
2654 uint32_t data; /* class_ro32_t * (32-bit pointer) */
2657 struct class_ro64_t {
2659 uint32_t instanceStart;
2660 uint32_t instanceSize;
2662 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
2663 uint64_t name; // const char * (64-bit pointer)
2664 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
2665 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
2666 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
2667 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
2668 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
2671 struct class_ro32_t {
2673 uint32_t instanceStart;
2674 uint32_t instanceSize;
2675 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
2676 uint32_t name; /* const char * (32-bit pointer) */
2677 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
2678 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
2679 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
2680 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
2681 uint32_t baseProperties; /* const struct objc_property_list *
2685 /* Values for class_ro{64,32}_t->flags */
2686 #define RO_META (1 << 0)
2687 #define RO_ROOT (1 << 1)
2688 #define RO_HAS_CXX_STRUCTORS (1 << 2)
2690 struct method_list64_t {
2693 /* struct method64_t first; These structures follow inline */
2696 struct method_list32_t {
2699 /* struct method32_t first; These structures follow inline */
2703 uint64_t name; /* SEL (64-bit pointer) */
2704 uint64_t types; /* const char * (64-bit pointer) */
2705 uint64_t imp; /* IMP (64-bit pointer) */
2709 uint32_t name; /* SEL (32-bit pointer) */
2710 uint32_t types; /* const char * (32-bit pointer) */
2711 uint32_t imp; /* IMP (32-bit pointer) */
2714 struct protocol_list64_t {
2715 uint64_t count; /* uintptr_t (a 64-bit value) */
2716 /* struct protocol64_t * list[0]; These pointers follow inline */
2719 struct protocol_list32_t {
2720 uint32_t count; /* uintptr_t (a 32-bit value) */
2721 /* struct protocol32_t * list[0]; These pointers follow inline */
2724 struct protocol64_t {
2725 uint64_t isa; /* id * (64-bit pointer) */
2726 uint64_t name; /* const char * (64-bit pointer) */
2727 uint64_t protocols; /* struct protocol_list64_t *
2729 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
2730 uint64_t classMethods; /* method_list_t * (64-bit pointer) */
2731 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
2732 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
2733 uint64_t instanceProperties; /* struct objc_property_list *
2737 struct protocol32_t {
2738 uint32_t isa; /* id * (32-bit pointer) */
2739 uint32_t name; /* const char * (32-bit pointer) */
2740 uint32_t protocols; /* struct protocol_list_t *
2742 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
2743 uint32_t classMethods; /* method_list_t * (32-bit pointer) */
2744 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
2745 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
2746 uint32_t instanceProperties; /* struct objc_property_list *
2750 struct ivar_list64_t {
2753 /* struct ivar64_t first; These structures follow inline */
2756 struct ivar_list32_t {
2759 /* struct ivar32_t first; These structures follow inline */
2763 uint64_t offset; /* uintptr_t * (64-bit pointer) */
2764 uint64_t name; /* const char * (64-bit pointer) */
2765 uint64_t type; /* const char * (64-bit pointer) */
2771 uint32_t offset; /* uintptr_t * (32-bit pointer) */
2772 uint32_t name; /* const char * (32-bit pointer) */
2773 uint32_t type; /* const char * (32-bit pointer) */
2778 struct objc_property_list64 {
2781 /* struct objc_property64 first; These structures follow inline */
2784 struct objc_property_list32 {
2787 /* struct objc_property32 first; These structures follow inline */
2790 struct objc_property64 {
2791 uint64_t name; /* const char * (64-bit pointer) */
2792 uint64_t attributes; /* const char * (64-bit pointer) */
2795 struct objc_property32 {
2796 uint32_t name; /* const char * (32-bit pointer) */
2797 uint32_t attributes; /* const char * (32-bit pointer) */
2800 struct category64_t {
2801 uint64_t name; /* const char * (64-bit pointer) */
2802 uint64_t cls; /* struct class_t * (64-bit pointer) */
2803 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
2804 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
2805 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
2806 uint64_t instanceProperties; /* struct objc_property_list *
2810 struct category32_t {
2811 uint32_t name; /* const char * (32-bit pointer) */
2812 uint32_t cls; /* struct class_t * (32-bit pointer) */
2813 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
2814 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
2815 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
2816 uint32_t instanceProperties; /* struct objc_property_list *
2820 struct objc_image_info64 {
2824 struct objc_image_info32 {
2828 struct imageInfo_t {
2832 /* masks for objc_image_info.flags */
2833 #define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
2834 #define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
2836 struct message_ref64 {
2837 uint64_t imp; /* IMP (64-bit pointer) */
2838 uint64_t sel; /* SEL (64-bit pointer) */
2841 struct message_ref32 {
2842 uint32_t imp; /* IMP (32-bit pointer) */
2843 uint32_t sel; /* SEL (32-bit pointer) */
2846 // Objective-C 1 (32-bit only) meta data structs.
2848 struct objc_module_t {
2851 uint32_t name; /* char * (32-bit pointer) */
2852 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
2855 struct objc_symtab_t {
2856 uint32_t sel_ref_cnt;
2857 uint32_t refs; /* SEL * (32-bit pointer) */
2858 uint16_t cls_def_cnt;
2859 uint16_t cat_def_cnt;
2860 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
2863 struct objc_class_t {
2864 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2865 uint32_t super_class; /* struct objc_class * (32-bit pointer) */
2866 uint32_t name; /* const char * (32-bit pointer) */
2869 int32_t instance_size;
2870 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
2871 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
2872 uint32_t cache; /* struct objc_cache * (32-bit pointer) */
2873 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
2876 #define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
2877 // class is not a metaclass
2878 #define CLS_CLASS 0x1
2879 // class is a metaclass
2880 #define CLS_META 0x2
2882 struct objc_category_t {
2883 uint32_t category_name; /* char * (32-bit pointer) */
2884 uint32_t class_name; /* char * (32-bit pointer) */
2885 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
2886 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
2887 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
2890 struct objc_ivar_t {
2891 uint32_t ivar_name; /* char * (32-bit pointer) */
2892 uint32_t ivar_type; /* char * (32-bit pointer) */
2893 int32_t ivar_offset;
2896 struct objc_ivar_list_t {
2898 // struct objc_ivar_t ivar_list[1]; /* variable length structure */
2901 struct objc_method_list_t {
2902 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
2903 int32_t method_count;
2904 // struct objc_method_t method_list[1]; /* variable length structure */
2907 struct objc_method_t {
2908 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2909 uint32_t method_types; /* char * (32-bit pointer) */
2910 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
2914 struct objc_protocol_list_t {
2915 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
2917 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
2918 // (32-bit pointer) */
2921 struct objc_protocol_t {
2922 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2923 uint32_t protocol_name; /* char * (32-bit pointer) */
2924 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
2925 uint32_t instance_methods; /* struct objc_method_description_list *
2927 uint32_t class_methods; /* struct objc_method_description_list *
2931 struct objc_method_description_list_t {
2933 // struct objc_method_description_t list[1];
2936 struct objc_method_description_t {
2937 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2938 uint32_t types; /* char * (32-bit pointer) */
2941 inline void swapStruct(struct cfstring64_t &cfs) {
2942 sys::swapByteOrder(cfs.isa);
2943 sys::swapByteOrder(cfs.flags);
2944 sys::swapByteOrder(cfs.characters);
2945 sys::swapByteOrder(cfs.length);
2948 inline void swapStruct(struct class64_t &c) {
2949 sys::swapByteOrder(c.isa);
2950 sys::swapByteOrder(c.superclass);
2951 sys::swapByteOrder(c.cache);
2952 sys::swapByteOrder(c.vtable);
2953 sys::swapByteOrder(c.data);
2956 inline void swapStruct(struct class32_t &c) {
2957 sys::swapByteOrder(c.isa);
2958 sys::swapByteOrder(c.superclass);
2959 sys::swapByteOrder(c.cache);
2960 sys::swapByteOrder(c.vtable);
2961 sys::swapByteOrder(c.data);
2964 inline void swapStruct(struct class_ro64_t &cro) {
2965 sys::swapByteOrder(cro.flags);
2966 sys::swapByteOrder(cro.instanceStart);
2967 sys::swapByteOrder(cro.instanceSize);
2968 sys::swapByteOrder(cro.reserved);
2969 sys::swapByteOrder(cro.ivarLayout);
2970 sys::swapByteOrder(cro.name);
2971 sys::swapByteOrder(cro.baseMethods);
2972 sys::swapByteOrder(cro.baseProtocols);
2973 sys::swapByteOrder(cro.ivars);
2974 sys::swapByteOrder(cro.weakIvarLayout);
2975 sys::swapByteOrder(cro.baseProperties);
2978 inline void swapStruct(struct class_ro32_t &cro) {
2979 sys::swapByteOrder(cro.flags);
2980 sys::swapByteOrder(cro.instanceStart);
2981 sys::swapByteOrder(cro.instanceSize);
2982 sys::swapByteOrder(cro.ivarLayout);
2983 sys::swapByteOrder(cro.name);
2984 sys::swapByteOrder(cro.baseMethods);
2985 sys::swapByteOrder(cro.baseProtocols);
2986 sys::swapByteOrder(cro.ivars);
2987 sys::swapByteOrder(cro.weakIvarLayout);
2988 sys::swapByteOrder(cro.baseProperties);
2991 inline void swapStruct(struct method_list64_t &ml) {
2992 sys::swapByteOrder(ml.entsize);
2993 sys::swapByteOrder(ml.count);
2996 inline void swapStruct(struct method_list32_t &ml) {
2997 sys::swapByteOrder(ml.entsize);
2998 sys::swapByteOrder(ml.count);
3001 inline void swapStruct(struct method64_t &m) {
3002 sys::swapByteOrder(m.name);
3003 sys::swapByteOrder(m.types);
3004 sys::swapByteOrder(m.imp);
3007 inline void swapStruct(struct method32_t &m) {
3008 sys::swapByteOrder(m.name);
3009 sys::swapByteOrder(m.types);
3010 sys::swapByteOrder(m.imp);
3013 inline void swapStruct(struct protocol_list64_t &pl) {
3014 sys::swapByteOrder(pl.count);
3017 inline void swapStruct(struct protocol_list32_t &pl) {
3018 sys::swapByteOrder(pl.count);
3021 inline void swapStruct(struct protocol64_t &p) {
3022 sys::swapByteOrder(p.isa);
3023 sys::swapByteOrder(p.name);
3024 sys::swapByteOrder(p.protocols);
3025 sys::swapByteOrder(p.instanceMethods);
3026 sys::swapByteOrder(p.classMethods);
3027 sys::swapByteOrder(p.optionalInstanceMethods);
3028 sys::swapByteOrder(p.optionalClassMethods);
3029 sys::swapByteOrder(p.instanceProperties);
3032 inline void swapStruct(struct protocol32_t &p) {
3033 sys::swapByteOrder(p.isa);
3034 sys::swapByteOrder(p.name);
3035 sys::swapByteOrder(p.protocols);
3036 sys::swapByteOrder(p.instanceMethods);
3037 sys::swapByteOrder(p.classMethods);
3038 sys::swapByteOrder(p.optionalInstanceMethods);
3039 sys::swapByteOrder(p.optionalClassMethods);
3040 sys::swapByteOrder(p.instanceProperties);
3043 inline void swapStruct(struct ivar_list64_t &il) {
3044 sys::swapByteOrder(il.entsize);
3045 sys::swapByteOrder(il.count);
3048 inline void swapStruct(struct ivar_list32_t &il) {
3049 sys::swapByteOrder(il.entsize);
3050 sys::swapByteOrder(il.count);
3053 inline void swapStruct(struct ivar64_t &i) {
3054 sys::swapByteOrder(i.offset);
3055 sys::swapByteOrder(i.name);
3056 sys::swapByteOrder(i.type);
3057 sys::swapByteOrder(i.alignment);
3058 sys::swapByteOrder(i.size);
3061 inline void swapStruct(struct ivar32_t &i) {
3062 sys::swapByteOrder(i.offset);
3063 sys::swapByteOrder(i.name);
3064 sys::swapByteOrder(i.type);
3065 sys::swapByteOrder(i.alignment);
3066 sys::swapByteOrder(i.size);
3069 inline void swapStruct(struct objc_property_list64 &pl) {
3070 sys::swapByteOrder(pl.entsize);
3071 sys::swapByteOrder(pl.count);
3074 inline void swapStruct(struct objc_property_list32 &pl) {
3075 sys::swapByteOrder(pl.entsize);
3076 sys::swapByteOrder(pl.count);
3079 inline void swapStruct(struct objc_property64 &op) {
3080 sys::swapByteOrder(op.name);
3081 sys::swapByteOrder(op.attributes);
3084 inline void swapStruct(struct objc_property32 &op) {
3085 sys::swapByteOrder(op.name);
3086 sys::swapByteOrder(op.attributes);
3089 inline void swapStruct(struct category64_t &c) {
3090 sys::swapByteOrder(c.name);
3091 sys::swapByteOrder(c.cls);
3092 sys::swapByteOrder(c.instanceMethods);
3093 sys::swapByteOrder(c.classMethods);
3094 sys::swapByteOrder(c.protocols);
3095 sys::swapByteOrder(c.instanceProperties);
3098 inline void swapStruct(struct category32_t &c) {
3099 sys::swapByteOrder(c.name);
3100 sys::swapByteOrder(c.cls);
3101 sys::swapByteOrder(c.instanceMethods);
3102 sys::swapByteOrder(c.classMethods);
3103 sys::swapByteOrder(c.protocols);
3104 sys::swapByteOrder(c.instanceProperties);
3107 inline void swapStruct(struct objc_image_info64 &o) {
3108 sys::swapByteOrder(o.version);
3109 sys::swapByteOrder(o.flags);
3112 inline void swapStruct(struct objc_image_info32 &o) {
3113 sys::swapByteOrder(o.version);
3114 sys::swapByteOrder(o.flags);
3117 inline void swapStruct(struct imageInfo_t &o) {
3118 sys::swapByteOrder(o.version);
3119 sys::swapByteOrder(o.flags);
3122 inline void swapStruct(struct message_ref64 &mr) {
3123 sys::swapByteOrder(mr.imp);
3124 sys::swapByteOrder(mr.sel);
3127 inline void swapStruct(struct message_ref32 &mr) {
3128 sys::swapByteOrder(mr.imp);
3129 sys::swapByteOrder(mr.sel);
3132 inline void swapStruct(struct objc_module_t &module) {
3133 sys::swapByteOrder(module.version);
3134 sys::swapByteOrder(module.size);
3135 sys::swapByteOrder(module.name);
3136 sys::swapByteOrder(module.symtab);
3139 inline void swapStruct(struct objc_symtab_t &symtab) {
3140 sys::swapByteOrder(symtab.sel_ref_cnt);
3141 sys::swapByteOrder(symtab.refs);
3142 sys::swapByteOrder(symtab.cls_def_cnt);
3143 sys::swapByteOrder(symtab.cat_def_cnt);
3146 inline void swapStruct(struct objc_class_t &objc_class) {
3147 sys::swapByteOrder(objc_class.isa);
3148 sys::swapByteOrder(objc_class.super_class);
3149 sys::swapByteOrder(objc_class.name);
3150 sys::swapByteOrder(objc_class.version);
3151 sys::swapByteOrder(objc_class.info);
3152 sys::swapByteOrder(objc_class.instance_size);
3153 sys::swapByteOrder(objc_class.ivars);
3154 sys::swapByteOrder(objc_class.methodLists);
3155 sys::swapByteOrder(objc_class.cache);
3156 sys::swapByteOrder(objc_class.protocols);
3159 inline void swapStruct(struct objc_category_t &objc_category) {
3160 sys::swapByteOrder(objc_category.category_name);
3161 sys::swapByteOrder(objc_category.class_name);
3162 sys::swapByteOrder(objc_category.instance_methods);
3163 sys::swapByteOrder(objc_category.class_methods);
3164 sys::swapByteOrder(objc_category.protocols);
3167 inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3168 sys::swapByteOrder(objc_ivar_list.ivar_count);
3171 inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3172 sys::swapByteOrder(objc_ivar.ivar_name);
3173 sys::swapByteOrder(objc_ivar.ivar_type);
3174 sys::swapByteOrder(objc_ivar.ivar_offset);
3177 inline void swapStruct(struct objc_method_list_t &method_list) {
3178 sys::swapByteOrder(method_list.obsolete);
3179 sys::swapByteOrder(method_list.method_count);
3182 inline void swapStruct(struct objc_method_t &method) {
3183 sys::swapByteOrder(method.method_name);
3184 sys::swapByteOrder(method.method_types);
3185 sys::swapByteOrder(method.method_imp);
3188 inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3189 sys::swapByteOrder(protocol_list.next);
3190 sys::swapByteOrder(protocol_list.count);
3193 inline void swapStruct(struct objc_protocol_t &protocol) {
3194 sys::swapByteOrder(protocol.isa);
3195 sys::swapByteOrder(protocol.protocol_name);
3196 sys::swapByteOrder(protocol.protocol_list);
3197 sys::swapByteOrder(protocol.instance_methods);
3198 sys::swapByteOrder(protocol.class_methods);
3201 inline void swapStruct(struct objc_method_description_list_t &mdl) {
3202 sys::swapByteOrder(mdl.count);
3205 inline void swapStruct(struct objc_method_description_t &md) {
3206 sys::swapByteOrder(md.name);
3207 sys::swapByteOrder(md.types);
3210 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3211 struct DisassembleInfo *info);
3213 // get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3214 // to an Objective-C class and returns the class name. It is also passed the
3215 // address of the pointer, so when the pointer is zero as it can be in an .o
3216 // file, that is used to look for an external relocation entry with a symbol
3218 static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3219 uint64_t ReferenceValue,
3220 struct DisassembleInfo *info) {
3222 uint32_t offset, left;
3225 // The pointer_value can be 0 in an object file and have a relocation
3226 // entry for the class symbol at the ReferenceValue (the address of the
3228 if (pointer_value == 0) {
3229 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3230 if (r == nullptr || left < sizeof(uint64_t))
3233 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3234 if (symbol_name == nullptr)
3236 const char *class_name = strrchr(symbol_name, '$');
3237 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
3238 return class_name + 2;
3243 // The case were the pointer_value is non-zero and points to a class defined
3244 // in this Mach-O file.
3245 r = get_pointer_64(pointer_value, offset, left, S, info);
3246 if (r == nullptr || left < sizeof(struct class64_t))
3249 memcpy(&c, r, sizeof(struct class64_t));
3250 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3254 r = get_pointer_64(c.data, offset, left, S, info);
3255 if (r == nullptr || left < sizeof(struct class_ro64_t))
3257 struct class_ro64_t cro;
3258 memcpy(&cro, r, sizeof(struct class_ro64_t));
3259 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3263 const char *name = get_pointer_64(cro.name, offset, left, S, info);
3267 // get_objc2_64bit_cfstring_name is used for disassembly and is passed a
3268 // pointer to a cfstring and returns its name or nullptr.
3269 static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
3270 struct DisassembleInfo *info) {
3271 const char *r, *name;
3272 uint32_t offset, left;
3274 struct cfstring64_t cfs;
3275 uint64_t cfs_characters;
3277 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3278 if (r == nullptr || left < sizeof(struct cfstring64_t))
3280 memcpy(&cfs, r, sizeof(struct cfstring64_t));
3281 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3283 if (cfs.characters == 0) {
3285 const char *symbol_name = get_symbol_64(
3286 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
3287 if (symbol_name == nullptr)
3289 cfs_characters = n_value;
3291 cfs_characters = cfs.characters;
3292 name = get_pointer_64(cfs_characters, offset, left, S, info);
3297 // get_objc2_64bit_selref() is used for disassembly and is passed a the address
3298 // of a pointer to an Objective-C selector reference when the pointer value is
3299 // zero as in a .o file and is likely to have a external relocation entry with
3300 // who's symbol's n_value is the real pointer to the selector name. If that is
3301 // the case the real pointer to the selector name is returned else 0 is
3303 static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
3304 struct DisassembleInfo *info) {
3305 uint32_t offset, left;
3308 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
3309 if (r == nullptr || left < sizeof(uint64_t))
3312 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3313 if (symbol_name == nullptr)
3318 static const SectionRef get_section(MachOObjectFile *O, const char *segname,
3319 const char *sectname) {
3320 for (const SectionRef &Section : O->sections()) {
3322 Section.getName(SectName);
3323 DataRefImpl Ref = Section.getRawDataRefImpl();
3324 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3325 if (SegName == segname && SectName == sectname)
3328 return SectionRef();
3332 walk_pointer_list_64(const char *listname, const SectionRef S,
3333 MachOObjectFile *O, struct DisassembleInfo *info,
3334 void (*func)(uint64_t, struct DisassembleInfo *info)) {
3335 if (S == SectionRef())
3339 S.getName(SectName);
3340 DataRefImpl Ref = S.getRawDataRefImpl();
3341 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3342 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3345 S.getContents(BytesStr);
3346 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3348 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
3349 uint32_t left = S.getSize() - i;
3350 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
3352 memcpy(&p, Contents + i, size);
3353 if (i + sizeof(uint64_t) > S.getSize())
3354 outs() << listname << " list pointer extends past end of (" << SegName
3355 << "," << SectName << ") section\n";
3356 outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
3358 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3359 sys::swapByteOrder(p);
3361 uint64_t n_value = 0;
3362 const char *name = get_symbol_64(i, S, info, n_value, p);
3363 if (name == nullptr)
3364 name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
3367 outs() << format("0x%" PRIx64, n_value);
3369 outs() << " + " << format("0x%" PRIx64, p);
3371 outs() << format("0x%" PRIx64, p);
3372 if (name != nullptr)
3373 outs() << " " << name;
3383 walk_pointer_list_32(const char *listname, const SectionRef S,
3384 MachOObjectFile *O, struct DisassembleInfo *info,
3385 void (*func)(uint32_t, struct DisassembleInfo *info)) {
3386 if (S == SectionRef())
3390 S.getName(SectName);
3391 DataRefImpl Ref = S.getRawDataRefImpl();
3392 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3393 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3396 S.getContents(BytesStr);
3397 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3399 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
3400 uint32_t left = S.getSize() - i;
3401 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
3403 memcpy(&p, Contents + i, size);
3404 if (i + sizeof(uint32_t) > S.getSize())
3405 outs() << listname << " list pointer extends past end of (" << SegName
3406 << "," << SectName << ") section\n";
3407 uint32_t Address = S.getAddress() + i;
3408 outs() << format("%08" PRIx32, Address) << " ";
3410 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3411 sys::swapByteOrder(p);
3412 outs() << format("0x%" PRIx32, p);
3414 const char *name = get_symbol_32(i, S, info, p);
3415 if (name != nullptr)
3416 outs() << " " << name;
3424 static void print_layout_map(const char *layout_map, uint32_t left) {
3425 if (layout_map == nullptr)
3427 outs() << " layout map: ";
3429 outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
3432 } while (*layout_map != '\0' && left != 0);
3436 static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
3437 uint32_t offset, left;
3439 const char *layout_map;
3443 layout_map = get_pointer_64(p, offset, left, S, info);
3444 print_layout_map(layout_map, left);
3447 static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
3448 uint32_t offset, left;
3450 const char *layout_map;
3454 layout_map = get_pointer_32(p, offset, left, S, info);
3455 print_layout_map(layout_map, left);
3458 static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
3459 const char *indent) {
3460 struct method_list64_t ml;
3461 struct method64_t m;
3463 uint32_t offset, xoffset, left, i;
3465 const char *name, *sym_name;
3468 r = get_pointer_64(p, offset, left, S, info);
3471 memset(&ml, '\0', sizeof(struct method_list64_t));
3472 if (left < sizeof(struct method_list64_t)) {
3473 memcpy(&ml, r, left);
3474 outs() << " (method_list_t entends past the end of the section)\n";
3476 memcpy(&ml, r, sizeof(struct method_list64_t));
3477 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3479 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3480 outs() << indent << "\t\t count " << ml.count << "\n";
3482 p += sizeof(struct method_list64_t);
3483 offset += sizeof(struct method_list64_t);
3484 for (i = 0; i < ml.count; i++) {
3485 r = get_pointer_64(p, offset, left, S, info);
3488 memset(&m, '\0', sizeof(struct method64_t));
3489 if (left < sizeof(struct method64_t)) {
3490 memcpy(&m, r, left);
3491 outs() << indent << " (method_t extends past the end of the section)\n";
3493 memcpy(&m, r, sizeof(struct method64_t));
3494 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3497 outs() << indent << "\t\t name ";
3498 sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
3499 info, n_value, m.name);
3501 if (info->verbose && sym_name != nullptr)
3504 outs() << format("0x%" PRIx64, n_value);
3506 outs() << " + " << format("0x%" PRIx64, m.name);
3508 outs() << format("0x%" PRIx64, m.name);
3509 name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
3510 if (name != nullptr)
3511 outs() << format(" %.*s", left, name);
3514 outs() << indent << "\t\t types ";
3515 sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
3516 info, n_value, m.types);
3518 if (info->verbose && sym_name != nullptr)
3521 outs() << format("0x%" PRIx64, n_value);
3523 outs() << " + " << format("0x%" PRIx64, m.types);
3525 outs() << format("0x%" PRIx64, m.types);
3526 name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
3527 if (name != nullptr)
3528 outs() << format(" %.*s", left, name);
3531 outs() << indent << "\t\t imp ";
3532 name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
3534 if (info->verbose && name == nullptr) {
3536 outs() << format("0x%" PRIx64, n_value) << " ";
3538 outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
3540 outs() << format("0x%" PRIx64, m.imp) << " ";
3542 if (name != nullptr)
3546 p += sizeof(struct method64_t);
3547 offset += sizeof(struct method64_t);
3551 static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
3552 const char *indent) {
3553 struct method_list32_t ml;
3554 struct method32_t m;
3555 const char *r, *name;
3556 uint32_t offset, xoffset, left, i;
3559 r = get_pointer_32(p, offset, left, S, info);
3562 memset(&ml, '\0', sizeof(struct method_list32_t));
3563 if (left < sizeof(struct method_list32_t)) {
3564 memcpy(&ml, r, left);
3565 outs() << " (method_list_t entends past the end of the section)\n";
3567 memcpy(&ml, r, sizeof(struct method_list32_t));
3568 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3570 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3571 outs() << indent << "\t\t count " << ml.count << "\n";
3573 p += sizeof(struct method_list32_t);
3574 offset += sizeof(struct method_list32_t);
3575 for (i = 0; i < ml.count; i++) {
3576 r = get_pointer_32(p, offset, left, S, info);
3579 memset(&m, '\0', sizeof(struct method32_t));
3580 if (left < sizeof(struct method32_t)) {
3581 memcpy(&ml, r, left);
3582 outs() << indent << " (method_t entends past the end of the section)\n";
3584 memcpy(&m, r, sizeof(struct method32_t));
3585 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3588 outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name);
3589 name = get_pointer_32(m.name, xoffset, left, xS, info);
3590 if (name != nullptr)
3591 outs() << format(" %.*s", left, name);
3594 outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types);
3595 name = get_pointer_32(m.types, xoffset, left, xS, info);
3596 if (name != nullptr)
3597 outs() << format(" %.*s", left, name);
3600 outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp);
3601 name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
3603 if (name != nullptr)
3604 outs() << " " << name;
3607 p += sizeof(struct method32_t);
3608 offset += sizeof(struct method32_t);
3612 static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
3613 uint32_t offset, left, xleft;
3615 struct objc_method_list_t method_list;
3616 struct objc_method_t method;
3617 const char *r, *methods, *name, *SymbolName;
3620 r = get_pointer_32(p, offset, left, S, info, true);
3625 if (left > sizeof(struct objc_method_list_t)) {
3626 memcpy(&method_list, r, sizeof(struct objc_method_list_t));
3628 outs() << "\t\t objc_method_list extends past end of the section\n";
3629 memset(&method_list, '\0', sizeof(struct objc_method_list_t));
3630 memcpy(&method_list, r, left);
3632 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3633 swapStruct(method_list);
3635 outs() << "\t\t obsolete "
3636 << format("0x%08" PRIx32, method_list.obsolete) << "\n";
3637 outs() << "\t\t method_count " << method_list.method_count << "\n";
3639 methods = r + sizeof(struct objc_method_list_t);
3640 for (i = 0; i < method_list.method_count; i++) {
3641 if ((i + 1) * sizeof(struct objc_method_t) > left) {
3642 outs() << "\t\t remaining method's extend past the of the section\n";
3645 memcpy(&method, methods + i * sizeof(struct objc_method_t),
3646 sizeof(struct objc_method_t));
3647 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3650 outs() << "\t\t method_name "
3651 << format("0x%08" PRIx32, method.method_name);
3652 if (info->verbose) {
3653 name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
3654 if (name != nullptr)
3655 outs() << format(" %.*s", xleft, name);
3657 outs() << " (not in an __OBJC section)";
3661 outs() << "\t\t method_types "
3662 << format("0x%08" PRIx32, method.method_types);
3663 if (info->verbose) {
3664 name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
3665 if (name != nullptr)
3666 outs() << format(" %.*s", xleft, name);
3668 outs() << " (not in an __OBJC section)";
3672 outs() << "\t\t method_imp "
3673 << format("0x%08" PRIx32, method.method_imp) << " ";
3674 if (info->verbose) {
3675 SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
3676 if (SymbolName != nullptr)
3677 outs() << SymbolName;
3684 static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
3685 struct protocol_list64_t pl;
3686 uint64_t q, n_value;
3687 struct protocol64_t pc;
3689 uint32_t offset, xoffset, left, i;
3691 const char *name, *sym_name;
3693 r = get_pointer_64(p, offset, left, S, info);
3696 memset(&pl, '\0', sizeof(struct protocol_list64_t));
3697 if (left < sizeof(struct protocol_list64_t)) {
3698 memcpy(&pl, r, left);
3699 outs() << " (protocol_list_t entends past the end of the section)\n";
3701 memcpy(&pl, r, sizeof(struct protocol_list64_t));
3702 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3704 outs() << " count " << pl.count << "\n";
3706 p += sizeof(struct protocol_list64_t);
3707 offset += sizeof(struct protocol_list64_t);
3708 for (i = 0; i < pl.count; i++) {
3709 r = get_pointer_64(p, offset, left, S, info);
3713 if (left < sizeof(uint64_t)) {
3714 memcpy(&q, r, left);
3715 outs() << " (protocol_t * entends past the end of the section)\n";
3717 memcpy(&q, r, sizeof(uint64_t));
3718 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3719 sys::swapByteOrder(q);
3721 outs() << "\t\t list[" << i << "] ";
3722 sym_name = get_symbol_64(offset, S, info, n_value, q);
3724 if (info->verbose && sym_name != nullptr)
3727 outs() << format("0x%" PRIx64, n_value);
3729 outs() << " + " << format("0x%" PRIx64, q);
3731 outs() << format("0x%" PRIx64, q);
3732 outs() << " (struct protocol_t *)\n";
3734 r = get_pointer_64(q + n_value, offset, left, S, info);
3737 memset(&pc, '\0', sizeof(struct protocol64_t));
3738 if (left < sizeof(struct protocol64_t)) {
3739 memcpy(&pc, r, left);
3740 outs() << " (protocol_t entends past the end of the section)\n";
3742 memcpy(&pc, r, sizeof(struct protocol64_t));
3743 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3746 outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n";
3748 outs() << "\t\t\t name ";
3749 sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
3750 info, n_value, pc.name);
3752 if (info->verbose && sym_name != nullptr)
3755 outs() << format("0x%" PRIx64, n_value);
3757 outs() << " + " << format("0x%" PRIx64, pc.name);
3759 outs() << format("0x%" PRIx64, pc.name);
3760 name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
3761 if (name != nullptr)
3762 outs() << format(" %.*s", left, name);
3765 outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
3767 outs() << "\t\t instanceMethods ";
3769 get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
3770 S, info, n_value, pc.instanceMethods);
3772 if (info->verbose && sym_name != nullptr)
3775 outs() << format("0x%" PRIx64, n_value);
3776 if (pc.instanceMethods != 0)
3777 outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
3779 outs() << format("0x%" PRIx64, pc.instanceMethods);
3780 outs() << " (struct method_list_t *)\n";
3781 if (pc.instanceMethods + n_value != 0)
3782 print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
3784 outs() << "\t\t classMethods ";
3786 get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
3787 info, n_value, pc.classMethods);
3789 if (info->verbose && sym_name != nullptr)
3792 outs() << format("0x%" PRIx64, n_value);
3793 if (pc.classMethods != 0)
3794 outs() << " + " << format("0x%" PRIx64, pc.classMethods);
3796 outs() << format("0x%" PRIx64, pc.classMethods);
3797 outs() << " (struct method_list_t *)\n";
3798 if (pc.classMethods + n_value != 0)
3799 print_method_list64_t(pc.classMethods + n_value, info, "\t");
3801 outs() << "\t optionalInstanceMethods "
3802 << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
3803 outs() << "\t optionalClassMethods "
3804 << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
3805 outs() << "\t instanceProperties "
3806 << format("0x%" PRIx64, pc.instanceProperties) << "\n";
3808 p += sizeof(uint64_t);
3809 offset += sizeof(uint64_t);
3813 static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
3814 struct protocol_list32_t pl;
3816 struct protocol32_t pc;
3818 uint32_t offset, xoffset, left, i;
3822 r = get_pointer_32(p, offset, left, S, info);
3825 memset(&pl, '\0', sizeof(struct protocol_list32_t));
3826 if (left < sizeof(struct protocol_list32_t)) {
3827 memcpy(&pl, r, left);
3828 outs() << " (protocol_list_t entends past the end of the section)\n";
3830 memcpy(&pl, r, sizeof(struct protocol_list32_t));
3831 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3833 outs() << " count " << pl.count << "\n";
3835 p += sizeof(struct protocol_list32_t);
3836 offset += sizeof(struct protocol_list32_t);
3837 for (i = 0; i < pl.count; i++) {
3838 r = get_pointer_32(p, offset, left, S, info);
3842 if (left < sizeof(uint32_t)) {
3843 memcpy(&q, r, left);
3844 outs() << " (protocol_t * entends past the end of the section)\n";
3846 memcpy(&q, r, sizeof(uint32_t));
3847 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3848 sys::swapByteOrder(q);
3849 outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q)
3850 << " (struct protocol_t *)\n";
3851 r = get_pointer_32(q, offset, left, S, info);
3854 memset(&pc, '\0', sizeof(struct protocol32_t));
3855 if (left < sizeof(struct protocol32_t)) {
3856 memcpy(&pc, r, left);
3857 outs() << " (protocol_t entends past the end of the section)\n";
3859 memcpy(&pc, r, sizeof(struct protocol32_t));
3860 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3862 outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n";
3863 outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name);
3864 name = get_pointer_32(pc.name, xoffset, left, xS, info);
3865 if (name != nullptr)
3866 outs() << format(" %.*s", left, name);
3868 outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
3869 outs() << "\t\t instanceMethods "
3870 << format("0x%" PRIx32, pc.instanceMethods)
3871 << " (struct method_list_t *)\n";
3872 if (pc.instanceMethods != 0)
3873 print_method_list32_t(pc.instanceMethods, info, "\t");
3874 outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods)
3875 << " (struct method_list_t *)\n";
3876 if (pc.classMethods != 0)
3877 print_method_list32_t(pc.classMethods, info, "\t");
3878 outs() << "\t optionalInstanceMethods "
3879 << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
3880 outs() << "\t optionalClassMethods "
3881 << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
3882 outs() << "\t instanceProperties "
3883 << format("0x%" PRIx32, pc.instanceProperties) << "\n";
3884 p += sizeof(uint32_t);
3885 offset += sizeof(uint32_t);
3889 static void print_indent(uint32_t indent) {
3890 for (uint32_t i = 0; i < indent;) {
3891 if (indent - i >= 8) {
3895 for (uint32_t j = i; j < indent; j++)
3902 static bool print_method_description_list(uint32_t p, uint32_t indent,
3903 struct DisassembleInfo *info) {
3904 uint32_t offset, left, xleft;
3906 struct objc_method_description_list_t mdl;
3907 struct objc_method_description_t md;
3908 const char *r, *list, *name;
3911 r = get_pointer_32(p, offset, left, S, info, true);
3916 if (left > sizeof(struct objc_method_description_list_t)) {
3917 memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
3919 print_indent(indent);
3920 outs() << " objc_method_description_list extends past end of the section\n";
3921 memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
3922 memcpy(&mdl, r, left);
3924 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3927 print_indent(indent);
3928 outs() << " count " << mdl.count << "\n";
3930 list = r + sizeof(struct objc_method_description_list_t);
3931 for (i = 0; i < mdl.count; i++) {
3932 if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
3933 print_indent(indent);
3934 outs() << " remaining list entries extend past the of the section\n";
3937 print_indent(indent);
3938 outs() << " list[" << i << "]\n";
3939 memcpy(&md, list + i * sizeof(struct objc_method_description_t),
3940 sizeof(struct objc_method_description_t));
3941 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3944 print_indent(indent);
3945 outs() << " name " << format("0x%08" PRIx32, md.name);
3946 if (info->verbose) {
3947 name = get_pointer_32(md.name, offset, xleft, S, info, true);
3948 if (name != nullptr)
3949 outs() << format(" %.*s", xleft, name);
3951 outs() << " (not in an __OBJC section)";
3955 print_indent(indent);
3956 outs() << " types " << format("0x%08" PRIx32, md.types);
3957 if (info->verbose) {
3958 name = get_pointer_32(md.types, offset, xleft, S, info, true);
3959 if (name != nullptr)
3960 outs() << format(" %.*s", xleft, name);
3962 outs() << " (not in an __OBJC section)";
3969 static bool print_protocol_list(uint32_t p, uint32_t indent,
3970 struct DisassembleInfo *info);
3972 static bool print_protocol(uint32_t p, uint32_t indent,
3973 struct DisassembleInfo *info) {
3974 uint32_t offset, left;
3976 struct objc_protocol_t protocol;
3977 const char *r, *name;
3979 r = get_pointer_32(p, offset, left, S, info, true);
3984 if (left >= sizeof(struct objc_protocol_t)) {
3985 memcpy(&protocol, r, sizeof(struct objc_protocol_t));
3987 print_indent(indent);
3988 outs() << " Protocol extends past end of the section\n";
3989 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
3990 memcpy(&protocol, r, left);
3992 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3993 swapStruct(protocol);
3995 print_indent(indent);
3996 outs() << " isa " << format("0x%08" PRIx32, protocol.isa)
3999 print_indent(indent);
4000 outs() << " protocol_name "
4001 << format("0x%08" PRIx32, protocol.protocol_name);
4002 if (info->verbose) {
4003 name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
4004 if (name != nullptr)
4005 outs() << format(" %.*s", left, name);
4007 outs() << " (not in an __OBJC section)";
4011 print_indent(indent);
4012 outs() << " protocol_list "
4013 << format("0x%08" PRIx32, protocol.protocol_list);
4014 if (print_protocol_list(protocol.protocol_list, indent + 4, info))
4015 outs() << " (not in an __OBJC section)\n";
4017 print_indent(indent);
4018 outs() << " instance_methods "
4019 << format("0x%08" PRIx32, protocol.instance_methods);
4020 if (print_method_description_list(protocol.instance_methods, indent, info))
4021 outs() << " (not in an __OBJC section)\n";
4023 print_indent(indent);
4024 outs() << " class_methods "
4025 << format("0x%08" PRIx32, protocol.class_methods);
4026 if (print_method_description_list(protocol.class_methods, indent, info))
4027 outs() << " (not in an __OBJC section)\n";
4032 static bool print_protocol_list(uint32_t p, uint32_t indent,
4033 struct DisassembleInfo *info) {
4034 uint32_t offset, left, l;
4036 struct objc_protocol_list_t protocol_list;
4037 const char *r, *list;
4040 r = get_pointer_32(p, offset, left, S, info, true);
4045 if (left > sizeof(struct objc_protocol_list_t)) {
4046 memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
4048 outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
4049 memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
4050 memcpy(&protocol_list, r, left);
4052 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4053 swapStruct(protocol_list);
4055 print_indent(indent);
4056 outs() << " next " << format("0x%08" PRIx32, protocol_list.next)
4058 print_indent(indent);
4059 outs() << " count " << protocol_list.count << "\n";
4061 list = r + sizeof(struct objc_protocol_list_t);
4062 for (i = 0; i < protocol_list.count; i++) {
4063 if ((i + 1) * sizeof(uint32_t) > left) {
4064 outs() << "\t\t remaining list entries extend past the of the section\n";
4067 memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
4068 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4069 sys::swapByteOrder(l);
4071 print_indent(indent);
4072 outs() << " list[" << i << "] " << format("0x%08" PRIx32, l);
4073 if (print_protocol(l, indent, info))
4074 outs() << "(not in an __OBJC section)\n";
4079 static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
4080 struct ivar_list64_t il;
4083 uint32_t offset, xoffset, left, j;
4085 const char *name, *sym_name, *ivar_offset_p;
4086 uint64_t ivar_offset, n_value;
4088 r = get_pointer_64(p, offset, left, S, info);
4091 memset(&il, '\0', sizeof(struct ivar_list64_t));
4092 if (left < sizeof(struct ivar_list64_t)) {
4093 memcpy(&il, r, left);
4094 outs() << " (ivar_list_t entends past the end of the section)\n";
4096 memcpy(&il, r, sizeof(struct ivar_list64_t));
4097 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4099 outs() << " entsize " << il.entsize << "\n";
4100 outs() << " count " << il.count << "\n";
4102 p += sizeof(struct ivar_list64_t);
4103 offset += sizeof(struct ivar_list64_t);
4104 for (j = 0; j < il.count; j++) {
4105 r = get_pointer_64(p, offset, left, S, info);
4108 memset(&i, '\0', sizeof(struct ivar64_t));
4109 if (left < sizeof(struct ivar64_t)) {
4110 memcpy(&i, r, left);
4111 outs() << " (ivar_t entends past the end of the section)\n";
4113 memcpy(&i, r, sizeof(struct ivar64_t));
4114 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4117 outs() << "\t\t\t offset ";
4118 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
4119 info, n_value, i.offset);
4121 if (info->verbose && sym_name != nullptr)
4124 outs() << format("0x%" PRIx64, n_value);
4126 outs() << " + " << format("0x%" PRIx64, i.offset);
4128 outs() << format("0x%" PRIx64, i.offset);
4129 ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
4130 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4131 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4132 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4133 sys::swapByteOrder(ivar_offset);
4134 outs() << " " << ivar_offset << "\n";
4138 outs() << "\t\t\t name ";
4139 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
4142 if (info->verbose && sym_name != nullptr)
4145 outs() << format("0x%" PRIx64, n_value);
4147 outs() << " + " << format("0x%" PRIx64, i.name);
4149 outs() << format("0x%" PRIx64, i.name);
4150 name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
4151 if (name != nullptr)
4152 outs() << format(" %.*s", left, name);
4155 outs() << "\t\t\t type ";
4156 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
4158 name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
4160 if (info->verbose && sym_name != nullptr)
4163 outs() << format("0x%" PRIx64, n_value);
4165 outs() << " + " << format("0x%" PRIx64, i.type);
4167 outs() << format("0x%" PRIx64, i.type);
4168 if (name != nullptr)
4169 outs() << format(" %.*s", left, name);
4172 outs() << "\t\t\talignment " << i.alignment << "\n";
4173 outs() << "\t\t\t size " << i.size << "\n";
4175 p += sizeof(struct ivar64_t);
4176 offset += sizeof(struct ivar64_t);
4180 static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4181 struct ivar_list32_t il;
4184 uint32_t offset, xoffset, left, j;
4186 const char *name, *ivar_offset_p;
4187 uint32_t ivar_offset;
4189 r = get_pointer_32(p, offset, left, S, info);
4192 memset(&il, '\0', sizeof(struct ivar_list32_t));
4193 if (left < sizeof(struct ivar_list32_t)) {
4194 memcpy(&il, r, left);
4195 outs() << " (ivar_list_t entends past the end of the section)\n";
4197 memcpy(&il, r, sizeof(struct ivar_list32_t));
4198 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4200 outs() << " entsize " << il.entsize << "\n";
4201 outs() << " count " << il.count << "\n";
4203 p += sizeof(struct ivar_list32_t);
4204 offset += sizeof(struct ivar_list32_t);
4205 for (j = 0; j < il.count; j++) {
4206 r = get_pointer_32(p, offset, left, S, info);
4209 memset(&i, '\0', sizeof(struct ivar32_t));
4210 if (left < sizeof(struct ivar32_t)) {
4211 memcpy(&i, r, left);
4212 outs() << " (ivar_t entends past the end of the section)\n";
4214 memcpy(&i, r, sizeof(struct ivar32_t));
4215 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4218 outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset);
4219 ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4220 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4221 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4222 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4223 sys::swapByteOrder(ivar_offset);
4224 outs() << " " << ivar_offset << "\n";
4228 outs() << "\t\t\t name " << format("0x%" PRIx32, i.name);
4229 name = get_pointer_32(i.name, xoffset, left, xS, info);
4230 if (name != nullptr)
4231 outs() << format(" %.*s", left, name);
4234 outs() << "\t\t\t type " << format("0x%" PRIx32, i.type);
4235 name = get_pointer_32(i.type, xoffset, left, xS, info);
4236 if (name != nullptr)
4237 outs() << format(" %.*s", left, name);
4240 outs() << "\t\t\talignment " << i.alignment << "\n";
4241 outs() << "\t\t\t size " << i.size << "\n";
4243 p += sizeof(struct ivar32_t);
4244 offset += sizeof(struct ivar32_t);
4248 static void print_objc_property_list64(uint64_t p,
4249 struct DisassembleInfo *info) {
4250 struct objc_property_list64 opl;
4251 struct objc_property64 op;
4253 uint32_t offset, xoffset, left, j;
4255 const char *name, *sym_name;
4258 r = get_pointer_64(p, offset, left, S, info);
4261 memset(&opl, '\0', sizeof(struct objc_property_list64));
4262 if (left < sizeof(struct objc_property_list64)) {
4263 memcpy(&opl, r, left);
4264 outs() << " (objc_property_list entends past the end of the section)\n";
4266 memcpy(&opl, r, sizeof(struct objc_property_list64));
4267 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4269 outs() << " entsize " << opl.entsize << "\n";
4270 outs() << " count " << opl.count << "\n";
4272 p += sizeof(struct objc_property_list64);
4273 offset += sizeof(struct objc_property_list64);
4274 for (j = 0; j < opl.count; j++) {
4275 r = get_pointer_64(p, offset, left, S, info);
4278 memset(&op, '\0', sizeof(struct objc_property64));
4279 if (left < sizeof(struct objc_property64)) {
4280 memcpy(&op, r, left);
4281 outs() << " (objc_property entends past the end of the section)\n";
4283 memcpy(&op, r, sizeof(struct objc_property64));
4284 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4287 outs() << "\t\t\t name ";
4288 sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
4289 info, n_value, op.name);
4291 if (info->verbose && sym_name != nullptr)
4294 outs() << format("0x%" PRIx64, n_value);
4296 outs() << " + " << format("0x%" PRIx64, op.name);
4298 outs() << format("0x%" PRIx64, op.name);
4299 name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
4300 if (name != nullptr)
4301 outs() << format(" %.*s", left, name);
4304 outs() << "\t\t\tattributes ";
4306 get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
4307 info, n_value, op.attributes);
4309 if (info->verbose && sym_name != nullptr)
4312 outs() << format("0x%" PRIx64, n_value);
4313 if (op.attributes != 0)
4314 outs() << " + " << format("0x%" PRIx64, op.attributes);
4316 outs() << format("0x%" PRIx64, op.attributes);
4317 name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
4318 if (name != nullptr)
4319 outs() << format(" %.*s", left, name);
4322 p += sizeof(struct objc_property64);
4323 offset += sizeof(struct objc_property64);
4327 static void print_objc_property_list32(uint32_t p,
4328 struct DisassembleInfo *info) {
4329 struct objc_property_list32 opl;
4330 struct objc_property32 op;
4332 uint32_t offset, xoffset, left, j;
4336 r = get_pointer_32(p, offset, left, S, info);
4339 memset(&opl, '\0', sizeof(struct objc_property_list32));
4340 if (left < sizeof(struct objc_property_list32)) {
4341 memcpy(&opl, r, left);
4342 outs() << " (objc_property_list entends past the end of the section)\n";
4344 memcpy(&opl, r, sizeof(struct objc_property_list32));
4345 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4347 outs() << " entsize " << opl.entsize << "\n";
4348 outs() << " count " << opl.count << "\n";
4350 p += sizeof(struct objc_property_list32);
4351 offset += sizeof(struct objc_property_list32);
4352 for (j = 0; j < opl.count; j++) {
4353 r = get_pointer_32(p, offset, left, S, info);
4356 memset(&op, '\0', sizeof(struct objc_property32));
4357 if (left < sizeof(struct objc_property32)) {
4358 memcpy(&op, r, left);
4359 outs() << " (objc_property entends past the end of the section)\n";
4361 memcpy(&op, r, sizeof(struct objc_property32));
4362 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4365 outs() << "\t\t\t name " << format("0x%" PRIx32, op.name);
4366 name = get_pointer_32(op.name, xoffset, left, xS, info);
4367 if (name != nullptr)
4368 outs() << format(" %.*s", left, name);
4371 outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
4372 name = get_pointer_32(op.attributes, xoffset, left, xS, info);
4373 if (name != nullptr)
4374 outs() << format(" %.*s", left, name);
4377 p += sizeof(struct objc_property32);
4378 offset += sizeof(struct objc_property32);
4382 static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
4383 bool &is_meta_class) {
4384 struct class_ro64_t cro;
4386 uint32_t offset, xoffset, left;
4388 const char *name, *sym_name;
4391 r = get_pointer_64(p, offset, left, S, info);
4392 if (r == nullptr || left < sizeof(struct class_ro64_t))
4394 memset(&cro, '\0', sizeof(struct class_ro64_t));
4395 if (left < sizeof(struct class_ro64_t)) {
4396 memcpy(&cro, r, left);
4397 outs() << " (class_ro_t entends past the end of the section)\n";
4399 memcpy(&cro, r, sizeof(struct class_ro64_t));
4400 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4402 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4403 if (cro.flags & RO_META)
4404 outs() << " RO_META";
4405 if (cro.flags & RO_ROOT)
4406 outs() << " RO_ROOT";
4407 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4408 outs() << " RO_HAS_CXX_STRUCTORS";
4410 outs() << " instanceStart " << cro.instanceStart << "\n";
4411 outs() << " instanceSize " << cro.instanceSize << "\n";
4412 outs() << " reserved " << format("0x%" PRIx32, cro.reserved)
4414 outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
4416 print_layout_map64(cro.ivarLayout, info);
4419 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
4420 info, n_value, cro.name);
4422 if (info->verbose && sym_name != nullptr)
4425 outs() << format("0x%" PRIx64, n_value);
4427 outs() << " + " << format("0x%" PRIx64, cro.name);
4429 outs() << format("0x%" PRIx64, cro.name);
4430 name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
4431 if (name != nullptr)
4432 outs() << format(" %.*s", left, name);
4435 outs() << " baseMethods ";
4436 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
4437 S, info, n_value, cro.baseMethods);
4439 if (info->verbose && sym_name != nullptr)
4442 outs() << format("0x%" PRIx64, n_value);
4443 if (cro.baseMethods != 0)
4444 outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
4446 outs() << format("0x%" PRIx64, cro.baseMethods);
4447 outs() << " (struct method_list_t *)\n";
4448 if (cro.baseMethods + n_value != 0)
4449 print_method_list64_t(cro.baseMethods + n_value, info, "");
4451 outs() << " baseProtocols ";
4453 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
4454 info, n_value, cro.baseProtocols);
4456 if (info->verbose && sym_name != nullptr)
4459 outs() << format("0x%" PRIx64, n_value);
4460 if (cro.baseProtocols != 0)
4461 outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
4463 outs() << format("0x%" PRIx64, cro.baseProtocols);
4465 if (cro.baseProtocols + n_value != 0)
4466 print_protocol_list64_t(cro.baseProtocols + n_value, info);
4468 outs() << " ivars ";
4469 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
4470 info, n_value, cro.ivars);
4472 if (info->verbose && sym_name != nullptr)
4475 outs() << format("0x%" PRIx64, n_value);
4477 outs() << " + " << format("0x%" PRIx64, cro.ivars);
4479 outs() << format("0x%" PRIx64, cro.ivars);
4481 if (cro.ivars + n_value != 0)
4482 print_ivar_list64_t(cro.ivars + n_value, info);
4484 outs() << " weakIvarLayout ";
4486 get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
4487 info, n_value, cro.weakIvarLayout);
4489 if (info->verbose && sym_name != nullptr)
4492 outs() << format("0x%" PRIx64, n_value);
4493 if (cro.weakIvarLayout != 0)
4494 outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
4496 outs() << format("0x%" PRIx64, cro.weakIvarLayout);
4498 print_layout_map64(cro.weakIvarLayout + n_value, info);
4500 outs() << " baseProperties ";
4502 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
4503 info, n_value, cro.baseProperties);
4505 if (info->verbose && sym_name != nullptr)
4508 outs() << format("0x%" PRIx64, n_value);
4509 if (cro.baseProperties != 0)
4510 outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
4512 outs() << format("0x%" PRIx64, cro.baseProperties);
4514 if (cro.baseProperties + n_value != 0)
4515 print_objc_property_list64(cro.baseProperties + n_value, info);
4517 is_meta_class = (cro.flags & RO_META) != 0;
4521 static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
4522 bool &is_meta_class) {
4523 struct class_ro32_t cro;
4525 uint32_t offset, xoffset, left;
4529 r = get_pointer_32(p, offset, left, S, info);
4532 memset(&cro, '\0', sizeof(struct class_ro32_t));
4533 if (left < sizeof(struct class_ro32_t)) {
4534 memcpy(&cro, r, left);
4535 outs() << " (class_ro_t entends past the end of the section)\n";
4537 memcpy(&cro, r, sizeof(struct class_ro32_t));
4538 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4540 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4541 if (cro.flags & RO_META)
4542 outs() << " RO_META";
4543 if (cro.flags & RO_ROOT)
4544 outs() << " RO_ROOT";
4545 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4546 outs() << " RO_HAS_CXX_STRUCTORS";
4548 outs() << " instanceStart " << cro.instanceStart << "\n";
4549 outs() << " instanceSize " << cro.instanceSize << "\n";
4550 outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
4552 print_layout_map32(cro.ivarLayout, info);
4554 outs() << " name " << format("0x%" PRIx32, cro.name);
4555 name = get_pointer_32(cro.name, xoffset, left, xS, info);
4556 if (name != nullptr)
4557 outs() << format(" %.*s", left, name);
4560 outs() << " baseMethods "
4561 << format("0x%" PRIx32, cro.baseMethods)
4562 << " (struct method_list_t *)\n";
4563 if (cro.baseMethods != 0)
4564 print_method_list32_t(cro.baseMethods, info, "");
4566 outs() << " baseProtocols "
4567 << format("0x%" PRIx32, cro.baseProtocols) << "\n";
4568 if (cro.baseProtocols != 0)
4569 print_protocol_list32_t(cro.baseProtocols, info);
4570 outs() << " ivars " << format("0x%" PRIx32, cro.ivars)
4573 print_ivar_list32_t(cro.ivars, info);
4574 outs() << " weakIvarLayout "
4575 << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
4576 print_layout_map32(cro.weakIvarLayout, info);
4577 outs() << " baseProperties "
4578 << format("0x%" PRIx32, cro.baseProperties) << "\n";
4579 if (cro.baseProperties != 0)
4580 print_objc_property_list32(cro.baseProperties, info);
4581 is_meta_class = (cro.flags & RO_META) != 0;
4585 static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
4588 uint32_t offset, left;
4591 uint64_t isa_n_value, n_value;
4593 r = get_pointer_64(p, offset, left, S, info);
4594 if (r == nullptr || left < sizeof(struct class64_t))
4596 memset(&c, '\0', sizeof(struct class64_t));
4597 if (left < sizeof(struct class64_t)) {
4598 memcpy(&c, r, left);
4599 outs() << " (class_t entends past the end of the section)\n";
4601 memcpy(&c, r, sizeof(struct class64_t));
4602 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4605 outs() << " isa " << format("0x%" PRIx64, c.isa);
4606 name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
4607 isa_n_value, c.isa);
4608 if (name != nullptr)
4609 outs() << " " << name;
4612 outs() << " superclass " << format("0x%" PRIx64, c.superclass);
4613 name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
4614 n_value, c.superclass);
4615 if (name != nullptr)
4616 outs() << " " << name;
4619 outs() << " cache " << format("0x%" PRIx64, c.cache);
4620 name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
4622 if (name != nullptr)
4623 outs() << " " << name;
4626 outs() << " vtable " << format("0x%" PRIx64, c.vtable);
4627 name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
4629 if (name != nullptr)
4630 outs() << " " << name;
4633 name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
4637 if (info->verbose && name != nullptr)
4640 outs() << format("0x%" PRIx64, n_value);
4642 outs() << " + " << format("0x%" PRIx64, c.data);
4644 outs() << format("0x%" PRIx64, c.data);
4645 outs() << " (struct class_ro_t *)";
4647 // This is a Swift class if some of the low bits of the pointer are set.
4648 if ((c.data + n_value) & 0x7)
4649 outs() << " Swift class";
4652 if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
4655 if (!is_meta_class &&
4656 c.isa + isa_n_value != p &&
4657 c.isa + isa_n_value != 0 &&
4658 info->depth < 100) {
4660 outs() << "Meta Class\n";
4661 print_class64_t(c.isa + isa_n_value, info);
4665 static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
4668 uint32_t offset, left;
4672 r = get_pointer_32(p, offset, left, S, info);
4675 memset(&c, '\0', sizeof(struct class32_t));
4676 if (left < sizeof(struct class32_t)) {
4677 memcpy(&c, r, left);
4678 outs() << " (class_t entends past the end of the section)\n";
4680 memcpy(&c, r, sizeof(struct class32_t));
4681 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4684 outs() << " isa " << format("0x%" PRIx32, c.isa);
4686 get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
4687 if (name != nullptr)
4688 outs() << " " << name;
4691 outs() << " superclass " << format("0x%" PRIx32, c.superclass);
4692 name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
4694 if (name != nullptr)
4695 outs() << " " << name;
4698 outs() << " cache " << format("0x%" PRIx32, c.cache);
4699 name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
4701 if (name != nullptr)
4702 outs() << " " << name;
4705 outs() << " vtable " << format("0x%" PRIx32, c.vtable);
4706 name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
4708 if (name != nullptr)
4709 outs() << " " << name;
4713 get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
4714 outs() << " data " << format("0x%" PRIx32, c.data)
4715 << " (struct class_ro_t *)";
4717 // This is a Swift class if some of the low bits of the pointer are set.
4719 outs() << " Swift class";
4722 if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
4725 if (!is_meta_class) {
4726 outs() << "Meta Class\n";
4727 print_class32_t(c.isa, info);
4731 static void print_objc_class_t(struct objc_class_t *objc_class,
4732 struct DisassembleInfo *info) {
4733 uint32_t offset, left, xleft;
4734 const char *name, *p, *ivar_list;
4737 struct objc_ivar_list_t objc_ivar_list;
4738 struct objc_ivar_t ivar;
4740 outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa);
4741 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
4742 name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
4743 if (name != nullptr)
4744 outs() << format(" %.*s", left, name);
4746 outs() << " (not in an __OBJC section)";
4750 outs() << "\t super_class "
4751 << format("0x%08" PRIx32, objc_class->super_class);
4752 if (info->verbose) {
4753 name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
4754 if (name != nullptr)
4755 outs() << format(" %.*s", left, name);
4757 outs() << " (not in an __OBJC section)";
4761 outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name);
4762 if (info->verbose) {
4763 name = get_pointer_32(objc_class->name, offset, left, S, info, true);
4764 if (name != nullptr)
4765 outs() << format(" %.*s", left, name);
4767 outs() << " (not in an __OBJC section)";
4771 outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version)
4774 outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info);
4775 if (info->verbose) {
4776 if (CLS_GETINFO(objc_class, CLS_CLASS))
4777 outs() << " CLS_CLASS";
4778 else if (CLS_GETINFO(objc_class, CLS_META))
4779 outs() << " CLS_META";
4783 outs() << "\t instance_size "
4784 << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
4786 p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
4787 outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars);
4789 if (left > sizeof(struct objc_ivar_list_t)) {
4791 memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
4793 outs() << " (entends past the end of the section)\n";
4794 memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
4795 memcpy(&objc_ivar_list, p, left);
4797 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4798 swapStruct(objc_ivar_list);
4799 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
4800 ivar_list = p + sizeof(struct objc_ivar_list_t);
4801 for (i = 0; i < objc_ivar_list.ivar_count; i++) {
4802 if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
4803 outs() << "\t\t remaining ivar's extend past the of the section\n";
4806 memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
4807 sizeof(struct objc_ivar_t));
4808 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4811 outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
4812 if (info->verbose) {
4813 name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
4814 if (name != nullptr)
4815 outs() << format(" %.*s", xleft, name);
4817 outs() << " (not in an __OBJC section)";
4821 outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
4822 if (info->verbose) {
4823 name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
4824 if (name != nullptr)
4825 outs() << format(" %.*s", xleft, name);
4827 outs() << " (not in an __OBJC section)";
4831 outs() << "\t\t ivar_offset "
4832 << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
4835 outs() << " (not in an __OBJC section)\n";
4838 outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists);
4839 if (print_method_list(objc_class->methodLists, info))
4840 outs() << " (not in an __OBJC section)\n";
4842 outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache)
4845 outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
4846 if (print_protocol_list(objc_class->protocols, 16, info))
4847 outs() << " (not in an __OBJC section)\n";
4850 static void print_objc_objc_category_t(struct objc_category_t *objc_category,
4851 struct DisassembleInfo *info) {
4852 uint32_t offset, left;
4856 outs() << "\t category name "
4857 << format("0x%08" PRIx32, objc_category->category_name);
4858 if (info->verbose) {
4859 name = get_pointer_32(objc_category->category_name, offset, left, S, info,
4861 if (name != nullptr)
4862 outs() << format(" %.*s", left, name);
4864 outs() << " (not in an __OBJC section)";
4868 outs() << "\t\t class name "
4869 << format("0x%08" PRIx32, objc_category->class_name);
4870 if (info->verbose) {
4872 get_pointer_32(objc_category->class_name, offset, left, S, info, true);
4873 if (name != nullptr)
4874 outs() << format(" %.*s", left, name);
4876 outs() << " (not in an __OBJC section)";
4880 outs() << "\t instance methods "
4881 << format("0x%08" PRIx32, objc_category->instance_methods);
4882 if (print_method_list(objc_category->instance_methods, info))
4883 outs() << " (not in an __OBJC section)\n";
4885 outs() << "\t class methods "
4886 << format("0x%08" PRIx32, objc_category->class_methods);
4887 if (print_method_list(objc_category->class_methods, info))
4888 outs() << " (not in an __OBJC section)\n";
4891 static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
4892 struct category64_t c;
4894 uint32_t offset, xoffset, left;
4896 const char *name, *sym_name;
4899 r = get_pointer_64(p, offset, left, S, info);
4902 memset(&c, '\0', sizeof(struct category64_t));
4903 if (left < sizeof(struct category64_t)) {
4904 memcpy(&c, r, left);
4905 outs() << " (category_t entends past the end of the section)\n";
4907 memcpy(&c, r, sizeof(struct category64_t));
4908 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4912 sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
4913 info, n_value, c.name);
4915 if (info->verbose && sym_name != nullptr)
4918 outs() << format("0x%" PRIx64, n_value);
4920 outs() << " + " << format("0x%" PRIx64, c.name);
4922 outs() << format("0x%" PRIx64, c.name);
4923 name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
4924 if (name != nullptr)
4925 outs() << format(" %.*s", left, name);
4929 sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
4932 if (info->verbose && sym_name != nullptr)
4935 outs() << format("0x%" PRIx64, n_value);
4937 outs() << " + " << format("0x%" PRIx64, c.cls);
4939 outs() << format("0x%" PRIx64, c.cls);
4941 if (c.cls + n_value != 0)
4942 print_class64_t(c.cls + n_value, info);
4944 outs() << " instanceMethods ";
4946 get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
4947 info, n_value, c.instanceMethods);
4949 if (info->verbose && sym_name != nullptr)
4952 outs() << format("0x%" PRIx64, n_value);
4953 if (c.instanceMethods != 0)
4954 outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
4956 outs() << format("0x%" PRIx64, c.instanceMethods);
4958 if (c.instanceMethods + n_value != 0)
4959 print_method_list64_t(c.instanceMethods + n_value, info, "");
4961 outs() << " classMethods ";
4962 sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
4963 S, info, n_value, c.classMethods);
4965 if (info->verbose && sym_name != nullptr)
4968 outs() << format("0x%" PRIx64, n_value);
4969 if (c.classMethods != 0)
4970 outs() << " + " << format("0x%" PRIx64, c.classMethods);
4972 outs() << format("0x%" PRIx64, c.classMethods);
4974 if (c.classMethods + n_value != 0)
4975 print_method_list64_t(c.classMethods + n_value, info, "");
4977 outs() << " protocols ";
4978 sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
4979 info, n_value, c.protocols);
4981 if (info->verbose && sym_name != nullptr)
4984 outs() << format("0x%" PRIx64, n_value);
4985 if (c.protocols != 0)
4986 outs() << " + " << format("0x%" PRIx64, c.protocols);
4988 outs() << format("0x%" PRIx64, c.protocols);
4990 if (c.protocols + n_value != 0)
4991 print_protocol_list64_t(c.protocols + n_value, info);
4993 outs() << "instanceProperties ";
4995 get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
4996 S, info, n_value, c.instanceProperties);
4998 if (info->verbose && sym_name != nullptr)
5001 outs() << format("0x%" PRIx64, n_value);
5002 if (c.instanceProperties != 0)
5003 outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
5005 outs() << format("0x%" PRIx64, c.instanceProperties);
5007 if (c.instanceProperties + n_value != 0)
5008 print_objc_property_list64(c.instanceProperties + n_value, info);
5011 static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
5012 struct category32_t c;
5014 uint32_t offset, left;
5018 r = get_pointer_32(p, offset, left, S, info);
5021 memset(&c, '\0', sizeof(struct category32_t));
5022 if (left < sizeof(struct category32_t)) {
5023 memcpy(&c, r, left);
5024 outs() << " (category_t entends past the end of the section)\n";
5026 memcpy(&c, r, sizeof(struct category32_t));
5027 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5030 outs() << " name " << format("0x%" PRIx32, c.name);
5031 name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
5034 outs() << " " << name;
5037 outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n";
5039 print_class32_t(c.cls, info);
5040 outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
5042 if (c.instanceMethods != 0)
5043 print_method_list32_t(c.instanceMethods, info, "");
5044 outs() << " classMethods " << format("0x%" PRIx32, c.classMethods)
5046 if (c.classMethods != 0)
5047 print_method_list32_t(c.classMethods, info, "");
5048 outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n";
5049 if (c.protocols != 0)
5050 print_protocol_list32_t(c.protocols, info);
5051 outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
5053 if (c.instanceProperties != 0)
5054 print_objc_property_list32(c.instanceProperties, info);
5057 static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
5058 uint32_t i, left, offset, xoffset;
5059 uint64_t p, n_value;
5060 struct message_ref64 mr;
5061 const char *name, *sym_name;
5065 if (S == SectionRef())
5069 S.getName(SectName);
5070 DataRefImpl Ref = S.getRawDataRefImpl();
5071 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5072 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5074 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5075 p = S.getAddress() + i;
5076 r = get_pointer_64(p, offset, left, S, info);
5079 memset(&mr, '\0', sizeof(struct message_ref64));
5080 if (left < sizeof(struct message_ref64)) {
5081 memcpy(&mr, r, left);
5082 outs() << " (message_ref entends past the end of the section)\n";
5084 memcpy(&mr, r, sizeof(struct message_ref64));
5085 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5089 name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
5092 outs() << format("0x%" PRIx64, n_value) << " ";
5094 outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
5096 outs() << format("0x%" PRIx64, mr.imp) << " ";
5097 if (name != nullptr)
5098 outs() << " " << name;
5102 sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
5103 info, n_value, mr.sel);
5105 if (info->verbose && sym_name != nullptr)
5108 outs() << format("0x%" PRIx64, n_value);
5110 outs() << " + " << format("0x%" PRIx64, mr.sel);
5112 outs() << format("0x%" PRIx64, mr.sel);
5113 name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
5114 if (name != nullptr)
5115 outs() << format(" %.*s", left, name);
5118 offset += sizeof(struct message_ref64);
5122 static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
5123 uint32_t i, left, offset, xoffset, p;
5124 struct message_ref32 mr;
5125 const char *name, *r;
5128 if (S == SectionRef())
5132 S.getName(SectName);
5133 DataRefImpl Ref = S.getRawDataRefImpl();
5134 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5135 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5137 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5138 p = S.getAddress() + i;
5139 r = get_pointer_32(p, offset, left, S, info);
5142 memset(&mr, '\0', sizeof(struct message_ref32));
5143 if (left < sizeof(struct message_ref32)) {
5144 memcpy(&mr, r, left);
5145 outs() << " (message_ref entends past the end of the section)\n";
5147 memcpy(&mr, r, sizeof(struct message_ref32));
5148 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5151 outs() << " imp " << format("0x%" PRIx32, mr.imp);
5152 name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
5154 if (name != nullptr)
5155 outs() << " " << name;
5158 outs() << " sel " << format("0x%" PRIx32, mr.sel);
5159 name = get_pointer_32(mr.sel, xoffset, left, xS, info);
5160 if (name != nullptr)
5161 outs() << " " << name;
5164 offset += sizeof(struct message_ref32);
5168 static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
5169 uint32_t left, offset, swift_version;
5171 struct objc_image_info64 o;
5174 if (S == SectionRef())
5178 S.getName(SectName);
5179 DataRefImpl Ref = S.getRawDataRefImpl();
5180 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5181 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5183 r = get_pointer_64(p, offset, left, S, info);
5186 memset(&o, '\0', sizeof(struct objc_image_info64));
5187 if (left < sizeof(struct objc_image_info64)) {
5188 memcpy(&o, r, left);
5189 outs() << " (objc_image_info entends past the end of the section)\n";
5191 memcpy(&o, r, sizeof(struct objc_image_info64));
5192 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5194 outs() << " version " << o.version << "\n";
5195 outs() << " flags " << format("0x%" PRIx32, o.flags);
5196 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5197 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5198 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5199 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5200 swift_version = (o.flags >> 8) & 0xff;
5201 if (swift_version != 0) {
5202 if (swift_version == 1)
5203 outs() << " Swift 1.0";
5204 else if (swift_version == 2)
5205 outs() << " Swift 1.1";
5207 outs() << " unknown future Swift version (" << swift_version << ")";
5212 static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
5213 uint32_t left, offset, swift_version, p;
5214 struct objc_image_info32 o;
5217 if (S == SectionRef())
5221 S.getName(SectName);
5222 DataRefImpl Ref = S.getRawDataRefImpl();
5223 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5224 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5226 r = get_pointer_32(p, offset, left, S, info);
5229 memset(&o, '\0', sizeof(struct objc_image_info32));
5230 if (left < sizeof(struct objc_image_info32)) {
5231 memcpy(&o, r, left);
5232 outs() << " (objc_image_info entends past the end of the section)\n";
5234 memcpy(&o, r, sizeof(struct objc_image_info32));
5235 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5237 outs() << " version " << o.version << "\n";
5238 outs() << " flags " << format("0x%" PRIx32, o.flags);
5239 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5240 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5241 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5242 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5243 swift_version = (o.flags >> 8) & 0xff;
5244 if (swift_version != 0) {
5245 if (swift_version == 1)
5246 outs() << " Swift 1.0";
5247 else if (swift_version == 2)
5248 outs() << " Swift 1.1";
5250 outs() << " unknown future Swift version (" << swift_version << ")";
5255 static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
5256 uint32_t left, offset, p;
5257 struct imageInfo_t o;
5261 S.getName(SectName);
5262 DataRefImpl Ref = S.getRawDataRefImpl();
5263 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5264 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5266 r = get_pointer_32(p, offset, left, S, info);
5269 memset(&o, '\0', sizeof(struct imageInfo_t));
5270 if (left < sizeof(struct imageInfo_t)) {
5271 memcpy(&o, r, left);
5272 outs() << " (imageInfo entends past the end of the section)\n";
5274 memcpy(&o, r, sizeof(struct imageInfo_t));
5275 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5277 outs() << " version " << o.version << "\n";
5278 outs() << " flags " << format("0x%" PRIx32, o.flags);
5284 outs() << " GC-only";
5290 static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
5291 SymbolAddressMap AddrMap;
5293 CreateSymbolAddressMap(O, &AddrMap);
5295 std::vector<SectionRef> Sections;
5296 for (const SectionRef &Section : O->sections()) {
5298 Section.getName(SectName);
5299 Sections.push_back(Section);
5302 struct DisassembleInfo info;
5303 // Set up the block of info used by the Symbolizer call backs.
5304 info.verbose = verbose;
5306 info.AddrMap = &AddrMap;
5307 info.Sections = &Sections;
5308 info.class_name = nullptr;
5309 info.selector_name = nullptr;
5310 info.method = nullptr;
5311 info.demangled_name = nullptr;
5312 info.bindtable = nullptr;
5317 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5318 if (CL == SectionRef())
5319 CL = get_section(O, "__DATA", "__objc_classlist");
5321 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
5323 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5324 if (CR == SectionRef())
5325 CR = get_section(O, "__DATA", "__objc_classrefs");
5327 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
5329 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5330 if (SR == SectionRef())
5331 SR = get_section(O, "__DATA", "__objc_superrefs");
5333 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
5335 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5336 if (CA == SectionRef())
5337 CA = get_section(O, "__DATA", "__objc_catlist");
5339 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
5341 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5342 if (PL == SectionRef())
5343 PL = get_section(O, "__DATA", "__objc_protolist");
5345 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
5347 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5348 if (MR == SectionRef())
5349 MR = get_section(O, "__DATA", "__objc_msgrefs");
5351 print_message_refs64(MR, &info);
5353 SectionRef II = get_section(O, "__OBJC2", "__image_info");
5354 if (II == SectionRef())
5355 II = get_section(O, "__DATA", "__objc_imageinfo");
5357 print_image_info64(II, &info);
5359 if (info.bindtable != nullptr)
5360 delete info.bindtable;
5363 static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
5364 SymbolAddressMap AddrMap;
5366 CreateSymbolAddressMap(O, &AddrMap);
5368 std::vector<SectionRef> Sections;
5369 for (const SectionRef &Section : O->sections()) {
5371 Section.getName(SectName);
5372 Sections.push_back(Section);
5375 struct DisassembleInfo info;
5376 // Set up the block of info used by the Symbolizer call backs.
5377 info.verbose = verbose;
5379 info.AddrMap = &AddrMap;
5380 info.Sections = &Sections;
5381 info.class_name = nullptr;
5382 info.selector_name = nullptr;
5383 info.method = nullptr;
5384 info.demangled_name = nullptr;
5385 info.bindtable = nullptr;
5389 const SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5390 if (CL != SectionRef()) {
5392 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5394 const SectionRef CL = get_section(O, "__DATA", "__objc_classlist");
5396 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5399 const SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5400 if (CR != SectionRef()) {
5402 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5404 const SectionRef CR = get_section(O, "__DATA", "__objc_classrefs");
5406 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5409 const SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5410 if (SR != SectionRef()) {
5412 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5414 const SectionRef SR = get_section(O, "__DATA", "__objc_superrefs");
5416 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5419 const SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5420 if (CA != SectionRef()) {
5422 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5424 const SectionRef CA = get_section(O, "__DATA", "__objc_catlist");
5426 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5429 const SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5430 if (PL != SectionRef()) {
5432 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5434 const SectionRef PL = get_section(O, "__DATA", "__objc_protolist");
5436 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5439 const SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5440 if (MR != SectionRef()) {
5442 print_message_refs32(MR, &info);
5444 const SectionRef MR = get_section(O, "__DATA", "__objc_msgrefs");
5446 print_message_refs32(MR, &info);
5449 const SectionRef II = get_section(O, "__OBJC2", "__image_info");
5450 if (II != SectionRef()) {
5452 print_image_info32(II, &info);
5454 const SectionRef II = get_section(O, "__DATA", "__objc_imageinfo");
5456 print_image_info32(II, &info);
5460 static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
5461 uint32_t i, j, p, offset, xoffset, left, defs_left, def;
5462 const char *r, *name, *defs;
5463 struct objc_module_t module;
5465 struct objc_symtab_t symtab;
5466 struct objc_class_t objc_class;
5467 struct objc_category_t objc_category;
5469 outs() << "Objective-C segment\n";
5470 S = get_section(O, "__OBJC", "__module_info");
5471 if (S == SectionRef())
5474 SymbolAddressMap AddrMap;
5476 CreateSymbolAddressMap(O, &AddrMap);
5478 std::vector<SectionRef> Sections;
5479 for (const SectionRef &Section : O->sections()) {
5481 Section.getName(SectName);
5482 Sections.push_back(Section);
5485 struct DisassembleInfo info;
5486 // Set up the block of info used by the Symbolizer call backs.
5487 info.verbose = verbose;
5489 info.AddrMap = &AddrMap;
5490 info.Sections = &Sections;
5491 info.class_name = nullptr;
5492 info.selector_name = nullptr;
5493 info.method = nullptr;
5494 info.demangled_name = nullptr;
5495 info.bindtable = nullptr;
5499 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
5500 p = S.getAddress() + i;
5501 r = get_pointer_32(p, offset, left, S, &info, true);
5504 memset(&module, '\0', sizeof(struct objc_module_t));
5505 if (left < sizeof(struct objc_module_t)) {
5506 memcpy(&module, r, left);
5507 outs() << " (module extends past end of __module_info section)\n";
5509 memcpy(&module, r, sizeof(struct objc_module_t));
5510 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5513 outs() << "Module " << format("0x%" PRIx32, p) << "\n";
5514 outs() << " version " << module.version << "\n";
5515 outs() << " size " << module.size << "\n";
5517 name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
5518 if (name != nullptr)
5519 outs() << format("%.*s", left, name);
5521 outs() << format("0x%08" PRIx32, module.name)
5522 << "(not in an __OBJC section)";
5525 r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
5526 if (module.symtab == 0 || r == nullptr) {
5527 outs() << " symtab " << format("0x%08" PRIx32, module.symtab)
5528 << " (not in an __OBJC section)\n";
5531 outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
5532 memset(&symtab, '\0', sizeof(struct objc_symtab_t));
5535 if (left < sizeof(struct objc_symtab_t)) {
5536 memcpy(&symtab, r, left);
5537 outs() << "\tsymtab extends past end of an __OBJC section)\n";
5539 memcpy(&symtab, r, sizeof(struct objc_symtab_t));
5540 if (left > sizeof(struct objc_symtab_t)) {
5541 defs_left = left - sizeof(struct objc_symtab_t);
5542 defs = r + sizeof(struct objc_symtab_t);
5545 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5548 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
5549 r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
5550 outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
5552 outs() << " (not in an __OBJC section)";
5554 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
5555 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
5556 if (symtab.cls_def_cnt > 0)
5557 outs() << "\tClass Definitions\n";
5558 for (j = 0; j < symtab.cls_def_cnt; j++) {
5559 if ((j + 1) * sizeof(uint32_t) > defs_left) {
5560 outs() << "\t(remaining class defs entries entends past the end of the "
5564 memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
5565 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5566 sys::swapByteOrder(def);
5568 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5569 outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
5571 if (left > sizeof(struct objc_class_t)) {
5573 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5575 outs() << " (entends past the end of the section)\n";
5576 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5577 memcpy(&objc_class, r, left);
5579 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5580 swapStruct(objc_class);
5581 print_objc_class_t(&objc_class, &info);
5583 outs() << "(not in an __OBJC section)\n";
5586 if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
5587 outs() << "\tMeta Class";
5588 r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
5590 if (left > sizeof(struct objc_class_t)) {
5592 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5594 outs() << " (entends past the end of the section)\n";
5595 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5596 memcpy(&objc_class, r, left);
5598 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5599 swapStruct(objc_class);
5600 print_objc_class_t(&objc_class, &info);
5602 outs() << "(not in an __OBJC section)\n";
5606 if (symtab.cat_def_cnt > 0)
5607 outs() << "\tCategory Definitions\n";
5608 for (j = 0; j < symtab.cat_def_cnt; j++) {
5609 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
5610 outs() << "\t(remaining category defs entries entends past the end of "
5611 << "the section)\n";
5614 memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
5616 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5617 sys::swapByteOrder(def);
5619 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5620 outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
5621 << format("0x%08" PRIx32, def);
5623 if (left > sizeof(struct objc_category_t)) {
5625 memcpy(&objc_category, r, sizeof(struct objc_category_t));
5627 outs() << " (entends past the end of the section)\n";
5628 memset(&objc_category, '\0', sizeof(struct objc_category_t));
5629 memcpy(&objc_category, r, left);
5631 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5632 swapStruct(objc_category);
5633 print_objc_objc_category_t(&objc_category, &info);
5635 outs() << "(not in an __OBJC section)\n";
5639 const SectionRef II = get_section(O, "__OBJC", "__image_info");
5640 if (II != SectionRef())
5641 print_image_info(II, &info);
5646 static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
5647 uint32_t size, uint32_t addr) {
5648 SymbolAddressMap AddrMap;
5649 CreateSymbolAddressMap(O, &AddrMap);
5651 std::vector<SectionRef> Sections;
5652 for (const SectionRef &Section : O->sections()) {
5654 Section.getName(SectName);
5655 Sections.push_back(Section);
5658 struct DisassembleInfo info;
5659 // Set up the block of info used by the Symbolizer call backs.
5660 info.verbose = true;
5662 info.AddrMap = &AddrMap;
5663 info.Sections = &Sections;
5664 info.class_name = nullptr;
5665 info.selector_name = nullptr;
5666 info.method = nullptr;
5667 info.demangled_name = nullptr;
5668 info.bindtable = nullptr;
5673 struct objc_protocol_t protocol;
5674 uint32_t left, paddr;
5675 for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
5676 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
5677 left = size - (p - sect);
5678 if (left < sizeof(struct objc_protocol_t)) {
5679 outs() << "Protocol extends past end of __protocol section\n";
5680 memcpy(&protocol, p, left);
5682 memcpy(&protocol, p, sizeof(struct objc_protocol_t));
5683 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5684 swapStruct(protocol);
5685 paddr = addr + (p - sect);
5686 outs() << "Protocol " << format("0x%" PRIx32, paddr);
5687 if (print_protocol(paddr, 0, &info))
5688 outs() << "(not in an __OBJC section)\n";
5693 inline void swapStruct(struct xar_header &xar) {
5694 sys::swapByteOrder(xar.magic);
5695 sys::swapByteOrder(xar.size);
5696 sys::swapByteOrder(xar.version);
5697 sys::swapByteOrder(xar.toc_length_compressed);
5698 sys::swapByteOrder(xar.toc_length_uncompressed);
5699 sys::swapByteOrder(xar.cksum_alg);
5702 static void PrintModeVerbose(uint32_t mode) {
5703 switch(mode & S_IFMT){
5727 /* owner permissions */
5738 else if(mode & S_IEXEC)
5743 /* group permissions */
5744 if(mode & (S_IREAD >> 3))
5748 if(mode & (S_IWRITE >> 3))
5754 else if(mode & (S_IEXEC >> 3))
5759 /* other permissions */
5760 if(mode & (S_IREAD >> 6))
5764 if(mode & (S_IWRITE >> 6))
5770 else if(mode & (S_IEXEC >> 6))
5776 static void PrintXarFilesSummary(const char *XarFilename, xar_t xar) {
5780 const char *key, *type, *mode, *user, *group, *size, *mtime, *name, *m;
5782 uint32_t mode_value;
5784 xi = xar_iter_new();
5786 errs() << "Can't obtain an xar iterator for xar archive "
5787 << XarFilename << "\n";
5791 // Go through the xar's files.
5792 for (xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)) {
5793 xp = xar_iter_new();
5795 errs() << "Can't obtain an xar iterator for xar archive "
5796 << XarFilename << "\n";
5806 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
5807 const char *val = nullptr;
5808 xar_prop_get(xf, key, &val);
5809 #if 0 // Useful for debugging.
5810 outs() << "key: " << key << " value: " << val << "\n";
5812 if(strcmp(key, "type") == 0)
5814 if(strcmp(key, "mode") == 0)
5816 if(strcmp(key, "user") == 0)
5818 if(strcmp(key, "group") == 0)
5820 if(strcmp(key, "data/size") == 0)
5822 if(strcmp(key, "mtime") == 0)
5824 if(strcmp(key, "name") == 0)
5827 if(mode != nullptr){
5828 mode_value = strtoul(mode, &endp, 8);
5830 outs() << "(mode: \"" << mode << "\" contains non-octal chars) ";
5831 if(strcmp(type, "file") == 0)
5832 mode_value |= S_IFREG;
5833 PrintModeVerbose(mode_value);
5837 outs() << format("%10s/", user);
5838 if(group != nullptr)
5839 outs() << format("%-10s ", group);
5841 outs() << format("%7s ", size);
5842 if(mtime != nullptr){
5843 for(m = mtime; *m != 'T' && *m != '\0'; m++)
5848 for( ; *m != 'Z' && *m != '\0'; m++)
5858 static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
5859 uint32_t size, bool verbose,
5860 bool PrintXarHeader, bool PrintXarFileHeaders,
5861 std::string XarMemberName) {
5862 if(size < sizeof(struct xar_header)) {
5863 outs() << "size of (__LLVM,__bundle) section too small (smaller than size "
5864 "of struct xar_header)\n";
5867 struct xar_header XarHeader;
5868 memcpy(&XarHeader, sect, sizeof(struct xar_header));
5869 if (sys::IsLittleEndianHost)
5870 swapStruct(XarHeader);
5871 if (PrintXarHeader) {
5872 if (!XarMemberName.empty())
5873 outs() << "In xar member " << XarMemberName << ": ";
5875 outs() << "For (__LLVM,__bundle) section: ";
5876 outs() << "xar header\n";
5877 if (XarHeader.magic == XAR_HEADER_MAGIC)
5878 outs() << " magic XAR_HEADER_MAGIC\n";
5881 << format_hex(XarHeader.magic, 10, true)
5882 << " (not XAR_HEADER_MAGIC)\n";
5883 outs() << " size " << XarHeader.size << "\n";
5884 outs() << " version " << XarHeader.version << "\n";
5885 outs() << " toc_length_compressed " << XarHeader.toc_length_compressed
5887 outs() << "toc_length_uncompressed " << XarHeader.toc_length_uncompressed
5889 outs() << " cksum_alg ";
5890 switch (XarHeader.cksum_alg) {
5891 case XAR_CKSUM_NONE:
5892 outs() << "XAR_CKSUM_NONE\n";
5894 case XAR_CKSUM_SHA1:
5895 outs() << "XAR_CKSUM_SHA1\n";
5898 outs() << "XAR_CKSUM_MD5\n";
5900 #ifdef XAR_CKSUM_SHA256
5901 case XAR_CKSUM_SHA256:
5902 outs() << "XAR_CKSUM_SHA256\n";
5905 #ifdef XAR_CKSUM_SHA512
5906 case XAR_CKSUM_SHA512:
5907 outs() << "XAR_CKSUM_SHA512\n";
5911 outs() << XarHeader.cksum_alg << "\n";
5915 SmallString<128> XarFilename;
5917 std::error_code XarEC =
5918 sys::fs::createTemporaryFile("llvm-objdump", "xar", FD, XarFilename);
5920 errs() << XarEC.message() << "\n";
5923 tool_output_file XarFile(XarFilename, FD);
5924 raw_fd_ostream &XarOut = XarFile.os();
5925 StringRef XarContents(sect, size);
5926 XarOut << XarContents;
5928 if (XarOut.has_error())
5931 xar_t xar = xar_open(XarFilename.c_str(), READ);
5933 errs() << "Can't create temporary xar archive " << XarFilename << "\n";
5937 SmallString<128> TocFilename;
5938 std::error_code TocEC =
5939 sys::fs::createTemporaryFile("llvm-objdump", "toc", TocFilename);
5941 errs() << TocEC.message() << "\n";
5944 xar_serialize(xar, TocFilename.c_str());
5946 if (PrintXarFileHeaders) {
5947 if (!XarMemberName.empty())
5948 outs() << "In xar member " << XarMemberName << ": ";
5950 outs() << "For (__LLVM,__bundle) section: ";
5951 outs() << "xar archive files:\n";
5952 PrintXarFilesSummary(XarFilename.c_str(), xar);
5955 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
5956 MemoryBuffer::getFileOrSTDIN(TocFilename.c_str());
5957 if (std::error_code EC = FileOrErr.getError()) {
5958 errs() << EC.message() << "\n";
5961 std::unique_ptr<MemoryBuffer> &Buffer = FileOrErr.get();
5963 if (!XarMemberName.empty())
5964 outs() << "In xar member " << XarMemberName << ": ";
5966 outs() << "For (__LLVM,__bundle) section: ";
5967 outs() << "xar table of contents:\n";
5968 outs() << Buffer->getBuffer() << "\n";
5970 // TODO: Go through the xar's files.
5971 xar_iter_t xi = xar_iter_new();
5973 errs() << "Can't obtain an xar iterator for xar archive "
5974 << XarFilename.c_str() << "\n";
5978 for(xar_file_t xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)){
5981 const char *member_name, *member_type, *member_size_string;
5984 xp = xar_iter_new();
5986 errs() << "Can't obtain an xar iterator for xar archive "
5987 << XarFilename.c_str() << "\n";
5993 member_size_string = NULL;
5994 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
5995 const char *val = nullptr;
5996 xar_prop_get(xf, key, &val);
5997 #if 0 // Useful for debugging.
5998 outs() << "key: " << key << " value: " << val << "\n";
6000 if(strcmp(key, "name") == 0)
6002 if(strcmp(key, "type") == 0)
6004 if(strcmp(key, "data/size") == 0)
6005 member_size_string = val;
6008 * If we find a file with a name, date/size and type properties
6009 * and with the type being "file" see if that is a xar file.
6011 if (member_name != NULL && member_type != NULL &&
6012 strcmp(member_type, "file") == 0 &&
6013 member_size_string != NULL){
6014 // Extract the file into a buffer.
6016 member_size = strtoul(member_size_string, &endptr, 10);
6017 if (*endptr == '\0' && member_size != 0) {
6018 char *buffer = (char *) ::operator new (member_size);
6019 if (xar_extract_tobuffersz(xar, xf, &buffer, &member_size) == 0) {
6020 #if 0 // Useful for debugging.
6021 outs() << "xar member: " << member_name << " extracted\n";
6023 // Set the XarMemberName we want to see printed in the header.
6024 std::string OldXarMemberName;
6025 // If XarMemberName is already set this is nested. So
6026 // save the old name and create the nested name.
6027 if (!XarMemberName.empty()) {
6028 OldXarMemberName = XarMemberName;
6030 (Twine("[") + XarMemberName + "]" + member_name).str();
6032 OldXarMemberName = "";
6033 XarMemberName = member_name;
6035 // See if this is could be a xar file (nested).
6036 if (member_size >= sizeof(struct xar_header)) {
6037 #if 0 // Useful for debugging.
6038 outs() << "could be a xar file: " << member_name << "\n";
6040 memcpy((char *)&XarHeader, buffer, sizeof(struct xar_header));
6041 if (sys::IsLittleEndianHost)
6042 swapStruct(XarHeader);
6043 if(XarHeader.magic == XAR_HEADER_MAGIC)
6044 DumpBitcodeSection(O, buffer, member_size, verbose,
6045 PrintXarHeader, PrintXarFileHeaders,
6048 XarMemberName = OldXarMemberName;
6057 #endif // defined(HAVE_LIBXAR)
6059 static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
6061 printObjc2_64bit_MetaData(O, verbose);
6063 MachO::mach_header H;
6065 if (H.cputype == MachO::CPU_TYPE_ARM)
6066 printObjc2_32bit_MetaData(O, verbose);
6068 // This is the 32-bit non-arm cputype case. Which is normally
6069 // the first Objective-C ABI. But it may be the case of a
6070 // binary for the iOS simulator which is the second Objective-C
6071 // ABI. In that case printObjc1_32bit_MetaData() will determine that
6072 // and return false.
6073 if (!printObjc1_32bit_MetaData(O, verbose))
6074 printObjc2_32bit_MetaData(O, verbose);
6079 // GuessLiteralPointer returns a string which for the item in the Mach-O file
6080 // for the address passed in as ReferenceValue for printing as a comment with
6081 // the instruction and also returns the corresponding type of that item
6082 // indirectly through ReferenceType.
6084 // If ReferenceValue is an address of literal cstring then a pointer to the
6085 // cstring is returned and ReferenceType is set to
6086 // LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
6088 // If ReferenceValue is an address of an Objective-C CFString, Selector ref or
6089 // Class ref that name is returned and the ReferenceType is set accordingly.
6091 // Lastly, literals which are Symbol address in a literal pool are looked for
6092 // and if found the symbol name is returned and ReferenceType is set to
6093 // LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
6095 // If there is no item in the Mach-O file for the address passed in as
6096 // ReferenceValue nullptr is returned and ReferenceType is unchanged.
6097 static const char *GuessLiteralPointer(uint64_t ReferenceValue,
6098 uint64_t ReferencePC,
6099 uint64_t *ReferenceType,
6100 struct DisassembleInfo *info) {
6101 // First see if there is an external relocation entry at the ReferencePC.
6102 if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
6103 uint64_t sect_addr = info->S.getAddress();
6104 uint64_t sect_offset = ReferencePC - sect_addr;
6105 bool reloc_found = false;
6107 MachO::any_relocation_info RE;
6108 bool isExtern = false;
6110 for (const RelocationRef &Reloc : info->S.relocations()) {
6111 uint64_t RelocOffset = Reloc.getOffset();
6112 if (RelocOffset == sect_offset) {
6113 Rel = Reloc.getRawDataRefImpl();
6114 RE = info->O->getRelocation(Rel);
6115 if (info->O->isRelocationScattered(RE))
6117 isExtern = info->O->getPlainRelocationExternal(RE);
6119 symbol_iterator RelocSym = Reloc.getSymbol();
6126 // If there is an external relocation entry for a symbol in a section
6127 // then used that symbol's value for the value of the reference.
6128 if (reloc_found && isExtern) {
6129 if (info->O->getAnyRelocationPCRel(RE)) {
6130 unsigned Type = info->O->getAnyRelocationType(RE);
6131 if (Type == MachO::X86_64_RELOC_SIGNED) {
6132 ReferenceValue = Symbol.getValue();
6138 // Look for literals such as Objective-C CFStrings refs, Selector refs,
6139 // Message refs and Class refs.
6140 bool classref, selref, msgref, cfstring;
6141 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
6142 selref, msgref, cfstring);
6143 if (classref && pointer_value == 0) {
6144 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
6145 // And the pointer_value in that section is typically zero as it will be
6146 // set by dyld as part of the "bind information".
6147 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
6148 if (name != nullptr) {
6149 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
6150 const char *class_name = strrchr(name, '$');
6151 if (class_name != nullptr && class_name[1] == '_' &&
6152 class_name[2] != '\0') {
6153 info->class_name = class_name + 2;
6160 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
6162 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
6163 if (name != nullptr)
6164 info->class_name = name;
6166 name = "bad class ref";
6171 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
6172 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
6176 if (selref && pointer_value == 0)
6177 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
6179 if (pointer_value != 0)
6180 ReferenceValue = pointer_value;
6182 const char *name = GuessCstringPointer(ReferenceValue, info);
6184 if (pointer_value != 0 && selref) {
6185 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
6186 info->selector_name = name;
6187 } else if (pointer_value != 0 && msgref) {
6188 info->class_name = nullptr;
6189 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
6190 info->selector_name = name;
6192 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
6196 // Lastly look for an indirect symbol with this ReferenceValue which is in
6197 // a literal pool. If found return that symbol name.
6198 name = GuessIndirectSymbol(ReferenceValue, info);
6200 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
6207 // SymbolizerSymbolLookUp is the symbol lookup function passed when creating
6208 // the Symbolizer. It looks up the ReferenceValue using the info passed via the
6209 // pointer to the struct DisassembleInfo that was passed when MCSymbolizer
6210 // is created and returns the symbol name that matches the ReferenceValue or
6211 // nullptr if none. The ReferenceType is passed in for the IN type of
6212 // reference the instruction is making from the values in defined in the header
6213 // "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
6214 // Out type and the ReferenceName will also be set which is added as a comment
6215 // to the disassembled instruction.
6218 // If the symbol name is a C++ mangled name then the demangled name is
6219 // returned through ReferenceName and ReferenceType is set to
6220 // LLVMDisassembler_ReferenceType_DeMangled_Name .
6223 // When this is called to get a symbol name for a branch target then the
6224 // ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
6225 // SymbolValue will be looked for in the indirect symbol table to determine if
6226 // it is an address for a symbol stub. If so then the symbol name for that
6227 // stub is returned indirectly through ReferenceName and then ReferenceType is
6228 // set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
6230 // When this is called with an value loaded via a PC relative load then
6231 // ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
6232 // SymbolValue is checked to be an address of literal pointer, symbol pointer,
6233 // or an Objective-C meta data reference. If so the output ReferenceType is
6234 // set to correspond to that as well as setting the ReferenceName.
6235 static const char *SymbolizerSymbolLookUp(void *DisInfo,
6236 uint64_t ReferenceValue,
6237 uint64_t *ReferenceType,
6238 uint64_t ReferencePC,
6239 const char **ReferenceName) {
6240 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
6241 // If no verbose symbolic information is wanted then just return nullptr.
6242 if (!info->verbose) {
6243 *ReferenceName = nullptr;
6244 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6248 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
6250 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
6251 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
6252 if (*ReferenceName != nullptr) {
6253 method_reference(info, ReferenceType, ReferenceName);
6254 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
6255 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
6258 if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
6259 if (info->demangled_name != nullptr)
6260 free(info->demangled_name);
6262 info->demangled_name =
6263 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
6264 if (info->demangled_name != nullptr) {
6265 *ReferenceName = info->demangled_name;
6266 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
6268 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6271 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6272 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
6274 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6276 method_reference(info, ReferenceType, ReferenceName);
6278 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6279 // If this is arm64 and the reference is an adrp instruction save the
6280 // instruction, passed in ReferenceValue and the address of the instruction
6281 // for use later if we see and add immediate instruction.
6282 } else if (info->O->getArch() == Triple::aarch64 &&
6283 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
6284 info->adrp_inst = ReferenceValue;
6285 info->adrp_addr = ReferencePC;
6286 SymbolName = nullptr;
6287 *ReferenceName = nullptr;
6288 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6289 // If this is arm64 and reference is an add immediate instruction and we
6291 // seen an adrp instruction just before it and the adrp's Xd register
6293 // this add's Xn register reconstruct the value being referenced and look to
6294 // see if it is a literal pointer. Note the add immediate instruction is
6295 // passed in ReferenceValue.
6296 } else if (info->O->getArch() == Triple::aarch64 &&
6297 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
6298 ReferencePC - 4 == info->adrp_addr &&
6299 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
6300 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
6301 uint32_t addxri_inst;
6302 uint64_t adrp_imm, addxri_imm;
6305 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
6306 if (info->adrp_inst & 0x0200000)
6307 adrp_imm |= 0xfffffffffc000000LL;
6309 addxri_inst = ReferenceValue;
6310 addxri_imm = (addxri_inst >> 10) & 0xfff;
6311 if (((addxri_inst >> 22) & 0x3) == 1)
6314 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
6315 (adrp_imm << 12) + addxri_imm;
6318 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6319 if (*ReferenceName == nullptr)
6320 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6321 // If this is arm64 and the reference is a load register instruction and we
6322 // have seen an adrp instruction just before it and the adrp's Xd register
6323 // matches this add's Xn register reconstruct the value being referenced and
6324 // look to see if it is a literal pointer. Note the load register
6325 // instruction is passed in ReferenceValue.
6326 } else if (info->O->getArch() == Triple::aarch64 &&
6327 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
6328 ReferencePC - 4 == info->adrp_addr &&
6329 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
6330 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
6331 uint32_t ldrxui_inst;
6332 uint64_t adrp_imm, ldrxui_imm;
6335 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
6336 if (info->adrp_inst & 0x0200000)
6337 adrp_imm |= 0xfffffffffc000000LL;
6339 ldrxui_inst = ReferenceValue;
6340 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
6342 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
6343 (adrp_imm << 12) + (ldrxui_imm << 3);
6346 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6347 if (*ReferenceName == nullptr)
6348 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6350 // If this arm64 and is an load register (PC-relative) instruction the
6351 // ReferenceValue is the PC plus the immediate value.
6352 else if (info->O->getArch() == Triple::aarch64 &&
6353 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
6354 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
6356 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6357 if (*ReferenceName == nullptr)
6358 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6361 else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
6362 if (info->demangled_name != nullptr)
6363 free(info->demangled_name);
6365 info->demangled_name =
6366 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
6367 if (info->demangled_name != nullptr) {
6368 *ReferenceName = info->demangled_name;
6369 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
6374 *ReferenceName = nullptr;
6375 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6381 /// \brief Emits the comments that are stored in the CommentStream.
6382 /// Each comment in the CommentStream must end with a newline.
6383 static void emitComments(raw_svector_ostream &CommentStream,
6384 SmallString<128> &CommentsToEmit,
6385 formatted_raw_ostream &FormattedOS,
6386 const MCAsmInfo &MAI) {
6387 // Flush the stream before taking its content.
6388 StringRef Comments = CommentsToEmit.str();
6389 // Get the default information for printing a comment.
6390 const char *CommentBegin = MAI.getCommentString();
6391 unsigned CommentColumn = MAI.getCommentColumn();
6392 bool IsFirst = true;
6393 while (!Comments.empty()) {
6395 FormattedOS << '\n';
6396 // Emit a line of comments.
6397 FormattedOS.PadToColumn(CommentColumn);
6398 size_t Position = Comments.find('\n');
6399 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
6400 // Move after the newline character.
6401 Comments = Comments.substr(Position + 1);
6404 FormattedOS.flush();
6406 // Tell the comment stream that the vector changed underneath it.
6407 CommentsToEmit.clear();
6410 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
6411 StringRef DisSegName, StringRef DisSectName) {
6412 const char *McpuDefault = nullptr;
6413 const Target *ThumbTarget = nullptr;
6414 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
6416 // GetTarget prints out stuff.
6419 if (MCPU.empty() && McpuDefault)
6422 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
6423 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
6425 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
6427 // Package up features to be passed to target/subtarget
6428 std::string FeaturesStr;
6429 if (MAttrs.size()) {
6430 SubtargetFeatures Features;
6431 for (unsigned i = 0; i != MAttrs.size(); ++i)
6432 Features.AddFeature(MAttrs[i]);
6433 FeaturesStr = Features.getString();
6436 // Set up disassembler.
6437 std::unique_ptr<const MCRegisterInfo> MRI(
6438 TheTarget->createMCRegInfo(TripleName));
6439 std::unique_ptr<const MCAsmInfo> AsmInfo(
6440 TheTarget->createMCAsmInfo(*MRI, TripleName));
6441 std::unique_ptr<const MCSubtargetInfo> STI(
6442 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
6443 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
6444 std::unique_ptr<MCDisassembler> DisAsm(
6445 TheTarget->createMCDisassembler(*STI, Ctx));
6446 std::unique_ptr<MCSymbolizer> Symbolizer;
6447 struct DisassembleInfo SymbolizerInfo;
6448 std::unique_ptr<MCRelocationInfo> RelInfo(
6449 TheTarget->createMCRelocationInfo(TripleName, Ctx));
6451 Symbolizer.reset(TheTarget->createMCSymbolizer(
6452 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
6453 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
6454 DisAsm->setSymbolizer(std::move(Symbolizer));
6456 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
6457 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
6458 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
6459 // Set the display preference for hex vs. decimal immediates.
6460 IP->setPrintImmHex(PrintImmHex);
6461 // Comment stream and backing vector.
6462 SmallString<128> CommentsToEmit;
6463 raw_svector_ostream CommentStream(CommentsToEmit);
6464 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
6465 // if it is done then arm64 comments for string literals don't get printed
6466 // and some constant get printed instead and not setting it causes intel
6467 // (32-bit and 64-bit) comments printed with different spacing before the
6468 // comment causing different diffs with the 'C' disassembler library API.
6469 // IP->setCommentStream(CommentStream);
6471 if (!AsmInfo || !STI || !DisAsm || !IP) {
6472 errs() << "error: couldn't initialize disassembler for target "
6473 << TripleName << '\n';
6477 // Set up separate thumb disassembler if needed.
6478 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
6479 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
6480 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
6481 std::unique_ptr<MCDisassembler> ThumbDisAsm;
6482 std::unique_ptr<MCInstPrinter> ThumbIP;
6483 std::unique_ptr<MCContext> ThumbCtx;
6484 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
6485 struct DisassembleInfo ThumbSymbolizerInfo;
6486 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
6488 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
6490 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
6492 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
6493 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
6494 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
6495 MCContext *PtrThumbCtx = ThumbCtx.get();
6497 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
6499 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
6500 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
6501 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
6502 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
6504 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
6505 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
6506 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
6507 *ThumbInstrInfo, *ThumbMRI));
6508 // Set the display preference for hex vs. decimal immediates.
6509 ThumbIP->setPrintImmHex(PrintImmHex);
6512 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
6513 errs() << "error: couldn't initialize disassembler for target "
6514 << ThumbTripleName << '\n';
6518 MachO::mach_header Header = MachOOF->getHeader();
6520 // FIXME: Using the -cfg command line option, this code used to be able to
6521 // annotate relocations with the referenced symbol's name, and if this was
6522 // inside a __[cf]string section, the data it points to. This is now replaced
6523 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
6524 std::vector<SectionRef> Sections;
6525 std::vector<SymbolRef> Symbols;
6526 SmallVector<uint64_t, 8> FoundFns;
6527 uint64_t BaseSegmentAddress;
6529 getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
6530 BaseSegmentAddress);
6532 // Sort the symbols by address, just in case they didn't come in that way.
6533 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
6535 // Build a data in code table that is sorted on by the address of each entry.
6536 uint64_t BaseAddress = 0;
6537 if (Header.filetype == MachO::MH_OBJECT)
6538 BaseAddress = Sections[0].getAddress();
6540 BaseAddress = BaseSegmentAddress;
6542 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
6545 DI->getOffset(Offset);
6546 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
6548 array_pod_sort(Dices.begin(), Dices.end());
6551 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
6553 raw_ostream &DebugOut = nulls();
6556 std::unique_ptr<DIContext> diContext;
6557 ObjectFile *DbgObj = MachOOF;
6558 // Try to find debug info and set up the DIContext for it.
6560 // A separate DSym file path was specified, parse it as a macho file,
6561 // get the sections and supply it to the section name parsing machinery.
6562 if (!DSYMFile.empty()) {
6563 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
6564 MemoryBuffer::getFileOrSTDIN(DSYMFile);
6565 if (std::error_code EC = BufOrErr.getError()) {
6566 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
6570 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
6575 // Setup the DIContext
6576 diContext.reset(new DWARFContextInMemory(*DbgObj));
6579 if (FilterSections.size() == 0)
6580 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
6582 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
6584 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
6587 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
6589 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
6590 if (SegmentName != DisSegName)
6594 Sections[SectIdx].getContents(BytesStr);
6595 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
6597 uint64_t SectAddress = Sections[SectIdx].getAddress();
6599 bool symbolTableWorked = false;
6601 // Create a map of symbol addresses to symbol names for use by
6602 // the SymbolizerSymbolLookUp() routine.
6603 SymbolAddressMap AddrMap;
6604 bool DisSymNameFound = false;
6605 for (const SymbolRef &Symbol : MachOOF->symbols()) {
6606 Expected<SymbolRef::Type> STOrErr = Symbol.getType();
6609 raw_string_ostream OS(Buf);
6610 logAllUnhandledErrors(STOrErr.takeError(), OS, "");
6612 report_fatal_error(Buf);
6614 SymbolRef::Type ST = *STOrErr;
6615 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
6616 ST == SymbolRef::ST_Other) {
6617 uint64_t Address = Symbol.getValue();
6618 Expected<StringRef> SymNameOrErr = Symbol.getName();
6619 if (!SymNameOrErr) {
6621 raw_string_ostream OS(Buf);
6622 logAllUnhandledErrors(SymNameOrErr.takeError(), OS, "");
6624 report_fatal_error(Buf);
6626 StringRef SymName = *SymNameOrErr;
6627 AddrMap[Address] = SymName;
6628 if (!DisSymName.empty() && DisSymName == SymName)
6629 DisSymNameFound = true;
6632 if (!DisSymName.empty() && !DisSymNameFound) {
6633 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
6636 // Set up the block of info used by the Symbolizer call backs.
6637 SymbolizerInfo.verbose = !NoSymbolicOperands;
6638 SymbolizerInfo.O = MachOOF;
6639 SymbolizerInfo.S = Sections[SectIdx];
6640 SymbolizerInfo.AddrMap = &AddrMap;
6641 SymbolizerInfo.Sections = &Sections;
6642 SymbolizerInfo.class_name = nullptr;
6643 SymbolizerInfo.selector_name = nullptr;
6644 SymbolizerInfo.method = nullptr;
6645 SymbolizerInfo.demangled_name = nullptr;
6646 SymbolizerInfo.bindtable = nullptr;
6647 SymbolizerInfo.adrp_addr = 0;
6648 SymbolizerInfo.adrp_inst = 0;
6649 // Same for the ThumbSymbolizer
6650 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
6651 ThumbSymbolizerInfo.O = MachOOF;
6652 ThumbSymbolizerInfo.S = Sections[SectIdx];
6653 ThumbSymbolizerInfo.AddrMap = &AddrMap;
6654 ThumbSymbolizerInfo.Sections = &Sections;
6655 ThumbSymbolizerInfo.class_name = nullptr;
6656 ThumbSymbolizerInfo.selector_name = nullptr;
6657 ThumbSymbolizerInfo.method = nullptr;
6658 ThumbSymbolizerInfo.demangled_name = nullptr;
6659 ThumbSymbolizerInfo.bindtable = nullptr;
6660 ThumbSymbolizerInfo.adrp_addr = 0;
6661 ThumbSymbolizerInfo.adrp_inst = 0;
6663 unsigned int Arch = MachOOF->getArch();
6665 // Skip all symbols if this is a stubs file.
6666 if (Bytes.size() == 0)
6669 // Disassemble symbol by symbol.
6670 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
6671 Expected<StringRef> SymNameOrErr = Symbols[SymIdx].getName();
6672 if (!SymNameOrErr) {
6674 raw_string_ostream OS(Buf);
6675 logAllUnhandledErrors(SymNameOrErr.takeError(), OS, "");
6677 report_fatal_error(Buf);
6679 StringRef SymName = *SymNameOrErr;
6681 Expected<SymbolRef::Type> STOrErr = Symbols[SymIdx].getType();
6684 raw_string_ostream OS(Buf);
6685 logAllUnhandledErrors(STOrErr.takeError(), OS, "");
6687 report_fatal_error(Buf);
6689 SymbolRef::Type ST = *STOrErr;
6690 if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
6693 // Make sure the symbol is defined in this section.
6694 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
6696 if (!DisSymName.empty() && DisSymName == SymName) {
6697 outs() << "-dis-symname: " << DisSymName << " not in the section\n";
6702 // The __mh_execute_header is special and we need to deal with that fact
6703 // this symbol is before the start of the (__TEXT,__text) section and at the
6704 // address of the start of the __TEXT segment. This is because this symbol
6705 // is an N_SECT symbol in the (__TEXT,__text) but its address is before the
6706 // start of the section in a standard MH_EXECUTE filetype.
6707 if (!DisSymName.empty() && DisSymName == "__mh_execute_header") {
6708 outs() << "-dis-symname: __mh_execute_header not in any section\n";
6711 // When this code is trying to disassemble a symbol at a time and in the
6712 // case there is only the __mh_execute_header symbol left as in a stripped
6713 // executable, we need to deal with this by ignoring this symbol so the
6714 // whole section is disassembled and this symbol is then not displayed.
6715 if (SymName == "__mh_execute_header" || SymName == "__mh_dylib_header" ||
6716 SymName == "__mh_bundle_header" || SymName == "__mh_object_header" ||
6717 SymName == "__mh_preload_header" || SymName == "__mh_dylinker_header")
6720 // If we are only disassembling one symbol see if this is that symbol.
6721 if (!DisSymName.empty() && DisSymName != SymName)
6724 // Start at the address of the symbol relative to the section's address.
6725 uint64_t SectSize = Sections[SectIdx].getSize();
6726 uint64_t Start = Symbols[SymIdx].getValue();
6727 uint64_t SectionAddress = Sections[SectIdx].getAddress();
6728 Start -= SectionAddress;
6730 if (Start > SectSize) {
6731 outs() << "section data ends, " << SymName
6732 << " lies outside valid range\n";
6736 // Stop disassembling either at the beginning of the next symbol or at
6737 // the end of the section.
6738 bool containsNextSym = false;
6739 uint64_t NextSym = 0;
6740 uint64_t NextSymIdx = SymIdx + 1;
6741 while (Symbols.size() > NextSymIdx) {
6742 Expected<SymbolRef::Type> STOrErr = Symbols[NextSymIdx].getType();
6745 raw_string_ostream OS(Buf);
6746 logAllUnhandledErrors(STOrErr.takeError(), OS, "");
6748 report_fatal_error(Buf);
6750 SymbolRef::Type NextSymType = *STOrErr;
6751 if (NextSymType == SymbolRef::ST_Function) {
6753 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
6754 NextSym = Symbols[NextSymIdx].getValue();
6755 NextSym -= SectionAddress;
6761 uint64_t End = containsNextSym ? std::min(NextSym, SectSize) : SectSize;
6764 symbolTableWorked = true;
6766 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
6767 bool IsThumb = MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb;
6769 // We only need the dedicated Thumb target if there's a real choice
6770 // (i.e. we're not targeting M-class) and the function is Thumb.
6771 bool UseThumbTarget = IsThumb && ThumbTarget;
6773 outs() << SymName << ":\n";
6774 DILineInfo lastLine;
6775 for (uint64_t Index = Start; Index < End; Index += Size) {
6778 uint64_t PC = SectAddress + Index;
6779 if (!NoLeadingAddr) {
6780 if (FullLeadingAddr) {
6781 if (MachOOF->is64Bit())
6782 outs() << format("%016" PRIx64, PC);
6784 outs() << format("%08" PRIx64, PC);
6786 outs() << format("%8" PRIx64 ":", PC);
6789 if (!NoShowRawInsn || Arch == Triple::arm)
6792 // Check the data in code table here to see if this is data not an
6793 // instruction to be disassembled.
6795 Dice.push_back(std::make_pair(PC, DiceRef()));
6796 dice_table_iterator DTI =
6797 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
6798 compareDiceTableEntries);
6799 if (DTI != Dices.end()) {
6801 DTI->second.getLength(Length);
6803 DTI->second.getKind(Kind);
6804 Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
6805 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
6806 (PC == (DTI->first + Length - 1)) && (Length & 1))
6811 SmallVector<char, 64> AnnotationsBytes;
6812 raw_svector_ostream Annotations(AnnotationsBytes);
6816 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
6817 PC, DebugOut, Annotations);
6819 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
6820 DebugOut, Annotations);
6822 if (!NoShowRawInsn || Arch == Triple::arm) {
6823 dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
6825 formatted_raw_ostream FormattedOS(outs());
6826 StringRef AnnotationsStr = Annotations.str();
6828 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
6830 IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
6831 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
6833 // Print debug info.
6835 DILineInfo dli = diContext->getLineInfoForAddress(PC);
6836 // Print valid line info if it changed.
6837 if (dli != lastLine && dli.Line != 0)
6838 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
6844 unsigned int Arch = MachOOF->getArch();
6845 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
6846 outs() << format("\t.byte 0x%02x #bad opcode\n",
6847 *(Bytes.data() + Index) & 0xff);
6848 Size = 1; // skip exactly one illegible byte and move on.
6849 } else if (Arch == Triple::aarch64 ||
6850 (Arch == Triple::arm && !IsThumb)) {
6851 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
6852 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
6853 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
6854 (*(Bytes.data() + Index + 3) & 0xff) << 24;
6855 outs() << format("\t.long\t0x%08x\n", opcode);
6857 } else if (Arch == Triple::arm) {
6858 assert(IsThumb && "ARM mode should have been dealt with above");
6859 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
6860 (*(Bytes.data() + Index + 1) & 0xff) << 8;
6861 outs() << format("\t.short\t0x%04x\n", opcode);
6864 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6866 Size = 1; // skip illegible bytes
6871 if (!symbolTableWorked) {
6872 // Reading the symbol table didn't work, disassemble the whole section.
6873 uint64_t SectAddress = Sections[SectIdx].getAddress();
6874 uint64_t SectSize = Sections[SectIdx].getSize();
6876 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
6879 uint64_t PC = SectAddress + Index;
6880 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
6881 DebugOut, nulls())) {
6882 if (!NoLeadingAddr) {
6883 if (FullLeadingAddr) {
6884 if (MachOOF->is64Bit())
6885 outs() << format("%016" PRIx64, PC);
6887 outs() << format("%08" PRIx64, PC);
6889 outs() << format("%8" PRIx64 ":", PC);
6892 if (!NoShowRawInsn || Arch == Triple::arm) {
6894 dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
6896 IP->printInst(&Inst, outs(), "", *STI);
6899 unsigned int Arch = MachOOF->getArch();
6900 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
6901 outs() << format("\t.byte 0x%02x #bad opcode\n",
6902 *(Bytes.data() + Index) & 0xff);
6903 InstSize = 1; // skip exactly one illegible byte and move on.
6905 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6907 InstSize = 1; // skip illegible bytes
6912 // The TripleName's need to be reset if we are called again for a different
6915 ThumbTripleName = "";
6917 if (SymbolizerInfo.method != nullptr)
6918 free(SymbolizerInfo.method);
6919 if (SymbolizerInfo.demangled_name != nullptr)
6920 free(SymbolizerInfo.demangled_name);
6921 if (SymbolizerInfo.bindtable != nullptr)
6922 delete SymbolizerInfo.bindtable;
6923 if (ThumbSymbolizerInfo.method != nullptr)
6924 free(ThumbSymbolizerInfo.method);
6925 if (ThumbSymbolizerInfo.demangled_name != nullptr)
6926 free(ThumbSymbolizerInfo.demangled_name);
6927 if (ThumbSymbolizerInfo.bindtable != nullptr)
6928 delete ThumbSymbolizerInfo.bindtable;
6932 //===----------------------------------------------------------------------===//
6933 // __compact_unwind section dumping
6934 //===----------------------------------------------------------------------===//
6938 template <typename T> static uint64_t readNext(const char *&Buf) {
6939 using llvm::support::little;
6940 using llvm::support::unaligned;
6942 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
6947 struct CompactUnwindEntry {
6948 uint32_t OffsetInSection;
6950 uint64_t FunctionAddr;
6952 uint32_t CompactEncoding;
6953 uint64_t PersonalityAddr;
6956 RelocationRef FunctionReloc;
6957 RelocationRef PersonalityReloc;
6958 RelocationRef LSDAReloc;
6960 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
6961 : OffsetInSection(Offset) {
6963 read<uint64_t>(Contents.data() + Offset);
6965 read<uint32_t>(Contents.data() + Offset);
6969 template <typename UIntPtr> void read(const char *Buf) {
6970 FunctionAddr = readNext<UIntPtr>(Buf);
6971 Length = readNext<uint32_t>(Buf);
6972 CompactEncoding = readNext<uint32_t>(Buf);
6973 PersonalityAddr = readNext<UIntPtr>(Buf);
6974 LSDAAddr = readNext<UIntPtr>(Buf);
6979 /// Given a relocation from __compact_unwind, consisting of the RelocationRef
6980 /// and data being relocated, determine the best base Name and Addend to use for
6981 /// display purposes.
6983 /// 1. An Extern relocation will directly reference a symbol (and the data is
6984 /// then already an addend), so use that.
6985 /// 2. Otherwise the data is an offset in the object file's layout; try to find
6986 // a symbol before it in the same section, and use the offset from there.
6987 /// 3. Finally, if all that fails, fall back to an offset from the start of the
6988 /// referenced section.
6989 static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
6990 std::map<uint64_t, SymbolRef> &Symbols,
6991 const RelocationRef &Reloc, uint64_t Addr,
6992 StringRef &Name, uint64_t &Addend) {
6993 if (Reloc.getSymbol() != Obj->symbol_end()) {
6994 Expected<StringRef> NameOrErr = Reloc.getSymbol()->getName();
6997 raw_string_ostream OS(Buf);
6998 logAllUnhandledErrors(NameOrErr.takeError(), OS, "");
7000 report_fatal_error(Buf);
7007 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
7008 SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
7010 uint64_t SectionAddr = RelocSection.getAddress();
7012 auto Sym = Symbols.upper_bound(Addr);
7013 if (Sym == Symbols.begin()) {
7014 // The first symbol in the object is after this reference, the best we can
7015 // do is section-relative notation.
7016 RelocSection.getName(Name);
7017 Addend = Addr - SectionAddr;
7021 // Go back one so that SymbolAddress <= Addr.
7024 auto SectOrErr = Sym->second.getSection();
7027 raw_string_ostream OS(Buf);
7028 logAllUnhandledErrors(SectOrErr.takeError(), OS, "");
7030 report_fatal_error(Buf);
7032 section_iterator SymSection = *SectOrErr;
7033 if (RelocSection == *SymSection) {
7034 // There's a valid symbol in the same section before this reference.
7035 Expected<StringRef> NameOrErr = Sym->second.getName();
7038 raw_string_ostream OS(Buf);
7039 logAllUnhandledErrors(NameOrErr.takeError(), OS, "");
7041 report_fatal_error(Buf);
7044 Addend = Addr - Sym->first;
7048 // There is a symbol before this reference, but it's in a different
7049 // section. Probably not helpful to mention it, so use the section name.
7050 RelocSection.getName(Name);
7051 Addend = Addr - SectionAddr;
7054 static void printUnwindRelocDest(const MachOObjectFile *Obj,
7055 std::map<uint64_t, SymbolRef> &Symbols,
7056 const RelocationRef &Reloc, uint64_t Addr) {
7060 if (!Reloc.getObject())
7063 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
7067 outs() << " + " << format("0x%" PRIx64, Addend);
7071 printMachOCompactUnwindSection(const MachOObjectFile *Obj,
7072 std::map<uint64_t, SymbolRef> &Symbols,
7073 const SectionRef &CompactUnwind) {
7075 assert(Obj->isLittleEndian() &&
7076 "There should not be a big-endian .o with __compact_unwind");
7078 bool Is64 = Obj->is64Bit();
7079 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
7080 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
7083 CompactUnwind.getContents(Contents);
7085 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
7087 // First populate the initial raw offsets, encodings and so on from the entry.
7088 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
7089 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
7090 CompactUnwinds.push_back(Entry);
7093 // Next we need to look at the relocations to find out what objects are
7094 // actually being referred to.
7095 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
7096 uint64_t RelocAddress = Reloc.getOffset();
7098 uint32_t EntryIdx = RelocAddress / EntrySize;
7099 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
7100 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
7102 if (OffsetInEntry == 0)
7103 Entry.FunctionReloc = Reloc;
7104 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
7105 Entry.PersonalityReloc = Reloc;
7106 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
7107 Entry.LSDAReloc = Reloc;
7109 llvm_unreachable("Unexpected relocation in __compact_unwind section");
7112 // Finally, we're ready to print the data we've gathered.
7113 outs() << "Contents of __compact_unwind section:\n";
7114 for (auto &Entry : CompactUnwinds) {
7115 outs() << " Entry at offset "
7116 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
7118 // 1. Start of the region this entry applies to.
7119 outs() << " start: " << format("0x%" PRIx64,
7120 Entry.FunctionAddr) << ' ';
7121 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
7124 // 2. Length of the region this entry applies to.
7125 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
7127 // 3. The 32-bit compact encoding.
7128 outs() << " compact encoding: "
7129 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
7131 // 4. The personality function, if present.
7132 if (Entry.PersonalityReloc.getObject()) {
7133 outs() << " personality function: "
7134 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
7135 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
7136 Entry.PersonalityAddr);
7140 // 5. This entry's language-specific data area.
7141 if (Entry.LSDAReloc.getObject()) {
7142 outs() << " LSDA: " << format("0x%" PRIx64,
7143 Entry.LSDAAddr) << ' ';
7144 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
7150 //===----------------------------------------------------------------------===//
7151 // __unwind_info section dumping
7152 //===----------------------------------------------------------------------===//
7154 static void printRegularSecondLevelUnwindPage(const char *PageStart) {
7155 const char *Pos = PageStart;
7156 uint32_t Kind = readNext<uint32_t>(Pos);
7158 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
7160 uint16_t EntriesStart = readNext<uint16_t>(Pos);
7161 uint16_t NumEntries = readNext<uint16_t>(Pos);
7163 Pos = PageStart + EntriesStart;
7164 for (unsigned i = 0; i < NumEntries; ++i) {
7165 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
7166 uint32_t Encoding = readNext<uint32_t>(Pos);
7168 outs() << " [" << i << "]: "
7169 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7171 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
7175 static void printCompressedSecondLevelUnwindPage(
7176 const char *PageStart, uint32_t FunctionBase,
7177 const SmallVectorImpl<uint32_t> &CommonEncodings) {
7178 const char *Pos = PageStart;
7179 uint32_t Kind = readNext<uint32_t>(Pos);
7181 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
7183 uint16_t EntriesStart = readNext<uint16_t>(Pos);
7184 uint16_t NumEntries = readNext<uint16_t>(Pos);
7186 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
7187 readNext<uint16_t>(Pos);
7188 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
7189 PageStart + EncodingsStart);
7191 Pos = PageStart + EntriesStart;
7192 for (unsigned i = 0; i < NumEntries; ++i) {
7193 uint32_t Entry = readNext<uint32_t>(Pos);
7194 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
7195 uint32_t EncodingIdx = Entry >> 24;
7198 if (EncodingIdx < CommonEncodings.size())
7199 Encoding = CommonEncodings[EncodingIdx];
7201 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
7203 outs() << " [" << i << "]: "
7204 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7206 << "encoding[" << EncodingIdx
7207 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
7211 static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
7212 std::map<uint64_t, SymbolRef> &Symbols,
7213 const SectionRef &UnwindInfo) {
7215 assert(Obj->isLittleEndian() &&
7216 "There should not be a big-endian .o with __unwind_info");
7218 outs() << "Contents of __unwind_info section:\n";
7221 UnwindInfo.getContents(Contents);
7222 const char *Pos = Contents.data();
7224 //===----------------------------------
7226 //===----------------------------------
7228 uint32_t Version = readNext<uint32_t>(Pos);
7229 outs() << " Version: "
7230 << format("0x%" PRIx32, Version) << '\n';
7231 assert(Version == 1 && "only understand version 1");
7233 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
7234 outs() << " Common encodings array section offset: "
7235 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
7236 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
7237 outs() << " Number of common encodings in array: "
7238 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
7240 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
7241 outs() << " Personality function array section offset: "
7242 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
7243 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
7244 outs() << " Number of personality functions in array: "
7245 << format("0x%" PRIx32, NumPersonalities) << '\n';
7247 uint32_t IndicesStart = readNext<uint32_t>(Pos);
7248 outs() << " Index array section offset: "
7249 << format("0x%" PRIx32, IndicesStart) << '\n';
7250 uint32_t NumIndices = readNext<uint32_t>(Pos);
7251 outs() << " Number of indices in array: "
7252 << format("0x%" PRIx32, NumIndices) << '\n';
7254 //===----------------------------------
7255 // A shared list of common encodings
7256 //===----------------------------------
7258 // These occupy indices in the range [0, N] whenever an encoding is referenced
7259 // from a compressed 2nd level index table. In practice the linker only
7260 // creates ~128 of these, so that indices are available to embed encodings in
7261 // the 2nd level index.
7263 SmallVector<uint32_t, 64> CommonEncodings;
7264 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
7265 Pos = Contents.data() + CommonEncodingsStart;
7266 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
7267 uint32_t Encoding = readNext<uint32_t>(Pos);
7268 CommonEncodings.push_back(Encoding);
7270 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
7274 //===----------------------------------
7275 // Personality functions used in this executable
7276 //===----------------------------------
7278 // There should be only a handful of these (one per source language,
7279 // roughly). Particularly since they only get 2 bits in the compact encoding.
7281 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
7282 Pos = Contents.data() + PersonalitiesStart;
7283 for (unsigned i = 0; i < NumPersonalities; ++i) {
7284 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
7285 outs() << " personality[" << i + 1
7286 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
7289 //===----------------------------------
7290 // The level 1 index entries
7291 //===----------------------------------
7293 // These specify an approximate place to start searching for the more detailed
7294 // information, sorted by PC.
7297 uint32_t FunctionOffset;
7298 uint32_t SecondLevelPageStart;
7302 SmallVector<IndexEntry, 4> IndexEntries;
7304 outs() << " Top level indices: (count = " << NumIndices << ")\n";
7305 Pos = Contents.data() + IndicesStart;
7306 for (unsigned i = 0; i < NumIndices; ++i) {
7309 Entry.FunctionOffset = readNext<uint32_t>(Pos);
7310 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
7311 Entry.LSDAStart = readNext<uint32_t>(Pos);
7312 IndexEntries.push_back(Entry);
7314 outs() << " [" << i << "]: "
7315 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
7317 << "2nd level page offset="
7318 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
7319 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
7322 //===----------------------------------
7323 // Next come the LSDA tables
7324 //===----------------------------------
7326 // The LSDA layout is rather implicit: it's a contiguous array of entries from
7327 // the first top-level index's LSDAOffset to the last (sentinel).
7329 outs() << " LSDA descriptors:\n";
7330 Pos = Contents.data() + IndexEntries[0].LSDAStart;
7331 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
7332 (2 * sizeof(uint32_t));
7333 for (int i = 0; i < NumLSDAs; ++i) {
7334 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
7335 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
7336 outs() << " [" << i << "]: "
7337 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7339 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
7342 //===----------------------------------
7343 // Finally, the 2nd level indices
7344 //===----------------------------------
7346 // Generally these are 4K in size, and have 2 possible forms:
7347 // + Regular stores up to 511 entries with disparate encodings
7348 // + Compressed stores up to 1021 entries if few enough compact encoding
7350 outs() << " Second level indices:\n";
7351 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
7352 // The final sentinel top-level index has no associated 2nd level page
7353 if (IndexEntries[i].SecondLevelPageStart == 0)
7356 outs() << " Second level index[" << i << "]: "
7357 << "offset in section="
7358 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
7360 << "base function offset="
7361 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
7363 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
7364 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
7366 printRegularSecondLevelUnwindPage(Pos);
7368 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
7371 llvm_unreachable("Do not know how to print this kind of 2nd level page");
7375 void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
7376 std::map<uint64_t, SymbolRef> Symbols;
7377 for (const SymbolRef &SymRef : Obj->symbols()) {
7378 // Discard any undefined or absolute symbols. They're not going to take part
7379 // in the convenience lookup for unwind info and just take up resources.
7380 auto SectOrErr = SymRef.getSection();
7382 // TODO: Actually report errors helpfully.
7383 consumeError(SectOrErr.takeError());
7386 section_iterator Section = *SectOrErr;
7387 if (Section == Obj->section_end())
7390 uint64_t Addr = SymRef.getValue();
7391 Symbols.insert(std::make_pair(Addr, SymRef));
7394 for (const SectionRef &Section : Obj->sections()) {
7396 Section.getName(SectName);
7397 if (SectName == "__compact_unwind")
7398 printMachOCompactUnwindSection(Obj, Symbols, Section);
7399 else if (SectName == "__unwind_info")
7400 printMachOUnwindInfoSection(Obj, Symbols, Section);
7404 static void PrintMachHeader(uint32_t magic, uint32_t cputype,
7405 uint32_t cpusubtype, uint32_t filetype,
7406 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
7408 outs() << "Mach header\n";
7409 outs() << " magic cputype cpusubtype caps filetype ncmds "
7410 "sizeofcmds flags\n";
7412 if (magic == MachO::MH_MAGIC)
7413 outs() << " MH_MAGIC";
7414 else if (magic == MachO::MH_MAGIC_64)
7415 outs() << "MH_MAGIC_64";
7417 outs() << format(" 0x%08" PRIx32, magic);
7419 case MachO::CPU_TYPE_I386:
7421 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7422 case MachO::CPU_SUBTYPE_I386_ALL:
7426 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7430 case MachO::CPU_TYPE_X86_64:
7431 outs() << " X86_64";
7432 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7433 case MachO::CPU_SUBTYPE_X86_64_ALL:
7436 case MachO::CPU_SUBTYPE_X86_64_H:
7437 outs() << " Haswell";
7440 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7444 case MachO::CPU_TYPE_ARM:
7446 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7447 case MachO::CPU_SUBTYPE_ARM_ALL:
7450 case MachO::CPU_SUBTYPE_ARM_V4T:
7453 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
7456 case MachO::CPU_SUBTYPE_ARM_XSCALE:
7457 outs() << " XSCALE";
7459 case MachO::CPU_SUBTYPE_ARM_V6:
7462 case MachO::CPU_SUBTYPE_ARM_V6M:
7465 case MachO::CPU_SUBTYPE_ARM_V7:
7468 case MachO::CPU_SUBTYPE_ARM_V7EM:
7471 case MachO::CPU_SUBTYPE_ARM_V7K:
7474 case MachO::CPU_SUBTYPE_ARM_V7M:
7477 case MachO::CPU_SUBTYPE_ARM_V7S:
7481 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7485 case MachO::CPU_TYPE_ARM64:
7487 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7488 case MachO::CPU_SUBTYPE_ARM64_ALL:
7492 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7496 case MachO::CPU_TYPE_POWERPC:
7498 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7499 case MachO::CPU_SUBTYPE_POWERPC_ALL:
7503 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7507 case MachO::CPU_TYPE_POWERPC64:
7509 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7510 case MachO::CPU_SUBTYPE_POWERPC_ALL:
7514 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7519 outs() << format(" %7d", cputype);
7520 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7523 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
7526 outs() << format(" 0x%02" PRIx32,
7527 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7530 case MachO::MH_OBJECT:
7531 outs() << " OBJECT";
7533 case MachO::MH_EXECUTE:
7534 outs() << " EXECUTE";
7536 case MachO::MH_FVMLIB:
7537 outs() << " FVMLIB";
7539 case MachO::MH_CORE:
7542 case MachO::MH_PRELOAD:
7543 outs() << " PRELOAD";
7545 case MachO::MH_DYLIB:
7548 case MachO::MH_DYLIB_STUB:
7549 outs() << " DYLIB_STUB";
7551 case MachO::MH_DYLINKER:
7552 outs() << " DYLINKER";
7554 case MachO::MH_BUNDLE:
7555 outs() << " BUNDLE";
7557 case MachO::MH_DSYM:
7560 case MachO::MH_KEXT_BUNDLE:
7561 outs() << " KEXTBUNDLE";
7564 outs() << format(" %10u", filetype);
7567 outs() << format(" %5u", ncmds);
7568 outs() << format(" %10u", sizeofcmds);
7570 if (f & MachO::MH_NOUNDEFS) {
7571 outs() << " NOUNDEFS";
7572 f &= ~MachO::MH_NOUNDEFS;
7574 if (f & MachO::MH_INCRLINK) {
7575 outs() << " INCRLINK";
7576 f &= ~MachO::MH_INCRLINK;
7578 if (f & MachO::MH_DYLDLINK) {
7579 outs() << " DYLDLINK";
7580 f &= ~MachO::MH_DYLDLINK;
7582 if (f & MachO::MH_BINDATLOAD) {
7583 outs() << " BINDATLOAD";
7584 f &= ~MachO::MH_BINDATLOAD;
7586 if (f & MachO::MH_PREBOUND) {
7587 outs() << " PREBOUND";
7588 f &= ~MachO::MH_PREBOUND;
7590 if (f & MachO::MH_SPLIT_SEGS) {
7591 outs() << " SPLIT_SEGS";
7592 f &= ~MachO::MH_SPLIT_SEGS;
7594 if (f & MachO::MH_LAZY_INIT) {
7595 outs() << " LAZY_INIT";
7596 f &= ~MachO::MH_LAZY_INIT;
7598 if (f & MachO::MH_TWOLEVEL) {
7599 outs() << " TWOLEVEL";
7600 f &= ~MachO::MH_TWOLEVEL;
7602 if (f & MachO::MH_FORCE_FLAT) {
7603 outs() << " FORCE_FLAT";
7604 f &= ~MachO::MH_FORCE_FLAT;
7606 if (f & MachO::MH_NOMULTIDEFS) {
7607 outs() << " NOMULTIDEFS";
7608 f &= ~MachO::MH_NOMULTIDEFS;
7610 if (f & MachO::MH_NOFIXPREBINDING) {
7611 outs() << " NOFIXPREBINDING";
7612 f &= ~MachO::MH_NOFIXPREBINDING;
7614 if (f & MachO::MH_PREBINDABLE) {
7615 outs() << " PREBINDABLE";
7616 f &= ~MachO::MH_PREBINDABLE;
7618 if (f & MachO::MH_ALLMODSBOUND) {
7619 outs() << " ALLMODSBOUND";
7620 f &= ~MachO::MH_ALLMODSBOUND;
7622 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
7623 outs() << " SUBSECTIONS_VIA_SYMBOLS";
7624 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
7626 if (f & MachO::MH_CANONICAL) {
7627 outs() << " CANONICAL";
7628 f &= ~MachO::MH_CANONICAL;
7630 if (f & MachO::MH_WEAK_DEFINES) {
7631 outs() << " WEAK_DEFINES";
7632 f &= ~MachO::MH_WEAK_DEFINES;
7634 if (f & MachO::MH_BINDS_TO_WEAK) {
7635 outs() << " BINDS_TO_WEAK";
7636 f &= ~MachO::MH_BINDS_TO_WEAK;
7638 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
7639 outs() << " ALLOW_STACK_EXECUTION";
7640 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
7642 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
7643 outs() << " DEAD_STRIPPABLE_DYLIB";
7644 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
7646 if (f & MachO::MH_PIE) {
7648 f &= ~MachO::MH_PIE;
7650 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
7651 outs() << " NO_REEXPORTED_DYLIBS";
7652 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
7654 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
7655 outs() << " MH_HAS_TLV_DESCRIPTORS";
7656 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
7658 if (f & MachO::MH_NO_HEAP_EXECUTION) {
7659 outs() << " MH_NO_HEAP_EXECUTION";
7660 f &= ~MachO::MH_NO_HEAP_EXECUTION;
7662 if (f & MachO::MH_APP_EXTENSION_SAFE) {
7663 outs() << " APP_EXTENSION_SAFE";
7664 f &= ~MachO::MH_APP_EXTENSION_SAFE;
7666 if (f != 0 || flags == 0)
7667 outs() << format(" 0x%08" PRIx32, f);
7669 outs() << format(" 0x%08" PRIx32, magic);
7670 outs() << format(" %7d", cputype);
7671 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7672 outs() << format(" 0x%02" PRIx32,
7673 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7674 outs() << format(" %10u", filetype);
7675 outs() << format(" %5u", ncmds);
7676 outs() << format(" %10u", sizeofcmds);
7677 outs() << format(" 0x%08" PRIx32, flags);
7682 static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
7683 StringRef SegName, uint64_t vmaddr,
7684 uint64_t vmsize, uint64_t fileoff,
7685 uint64_t filesize, uint32_t maxprot,
7686 uint32_t initprot, uint32_t nsects,
7687 uint32_t flags, uint32_t object_size,
7689 uint64_t expected_cmdsize;
7690 if (cmd == MachO::LC_SEGMENT) {
7691 outs() << " cmd LC_SEGMENT\n";
7692 expected_cmdsize = nsects;
7693 expected_cmdsize *= sizeof(struct MachO::section);
7694 expected_cmdsize += sizeof(struct MachO::segment_command);
7696 outs() << " cmd LC_SEGMENT_64\n";
7697 expected_cmdsize = nsects;
7698 expected_cmdsize *= sizeof(struct MachO::section_64);
7699 expected_cmdsize += sizeof(struct MachO::segment_command_64);
7701 outs() << " cmdsize " << cmdsize;
7702 if (cmdsize != expected_cmdsize)
7703 outs() << " Inconsistent size\n";
7706 outs() << " segname " << SegName << "\n";
7707 if (cmd == MachO::LC_SEGMENT_64) {
7708 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
7709 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
7711 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
7712 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
7714 outs() << " fileoff " << fileoff;
7715 if (fileoff > object_size)
7716 outs() << " (past end of file)\n";
7719 outs() << " filesize " << filesize;
7720 if (fileoff + filesize > object_size)
7721 outs() << " (past end of file)\n";
7726 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7727 MachO::VM_PROT_EXECUTE)) != 0)
7728 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
7730 outs() << " maxprot ";
7731 outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
7732 outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
7733 outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
7736 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7737 MachO::VM_PROT_EXECUTE)) != 0)
7738 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
7740 outs() << " initprot ";
7741 outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
7742 outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
7743 outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
7746 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
7747 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
7749 outs() << " nsects " << nsects << "\n";
7753 outs() << " (none)\n";
7755 if (flags & MachO::SG_HIGHVM) {
7756 outs() << " HIGHVM";
7757 flags &= ~MachO::SG_HIGHVM;
7759 if (flags & MachO::SG_FVMLIB) {
7760 outs() << " FVMLIB";
7761 flags &= ~MachO::SG_FVMLIB;
7763 if (flags & MachO::SG_NORELOC) {
7764 outs() << " NORELOC";
7765 flags &= ~MachO::SG_NORELOC;
7767 if (flags & MachO::SG_PROTECTED_VERSION_1) {
7768 outs() << " PROTECTED_VERSION_1";
7769 flags &= ~MachO::SG_PROTECTED_VERSION_1;
7772 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
7777 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
7781 static void PrintSection(const char *sectname, const char *segname,
7782 uint64_t addr, uint64_t size, uint32_t offset,
7783 uint32_t align, uint32_t reloff, uint32_t nreloc,
7784 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
7785 uint32_t cmd, const char *sg_segname,
7786 uint32_t filetype, uint32_t object_size,
7788 outs() << "Section\n";
7789 outs() << " sectname " << format("%.16s\n", sectname);
7790 outs() << " segname " << format("%.16s", segname);
7791 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
7792 outs() << " (does not match segment)\n";
7795 if (cmd == MachO::LC_SEGMENT_64) {
7796 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
7797 outs() << " size " << format("0x%016" PRIx64, size);
7799 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
7800 outs() << " size " << format("0x%08" PRIx64, size);
7802 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
7803 outs() << " (past end of file)\n";
7806 outs() << " offset " << offset;
7807 if (offset > object_size)
7808 outs() << " (past end of file)\n";
7811 uint32_t align_shifted = 1 << align;
7812 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
7813 outs() << " reloff " << reloff;
7814 if (reloff > object_size)
7815 outs() << " (past end of file)\n";
7818 outs() << " nreloc " << nreloc;
7819 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
7820 outs() << " (past end of file)\n";
7823 uint32_t section_type = flags & MachO::SECTION_TYPE;
7826 if (section_type == MachO::S_REGULAR)
7827 outs() << " S_REGULAR\n";
7828 else if (section_type == MachO::S_ZEROFILL)
7829 outs() << " S_ZEROFILL\n";
7830 else if (section_type == MachO::S_CSTRING_LITERALS)
7831 outs() << " S_CSTRING_LITERALS\n";
7832 else if (section_type == MachO::S_4BYTE_LITERALS)
7833 outs() << " S_4BYTE_LITERALS\n";
7834 else if (section_type == MachO::S_8BYTE_LITERALS)
7835 outs() << " S_8BYTE_LITERALS\n";
7836 else if (section_type == MachO::S_16BYTE_LITERALS)
7837 outs() << " S_16BYTE_LITERALS\n";
7838 else if (section_type == MachO::S_LITERAL_POINTERS)
7839 outs() << " S_LITERAL_POINTERS\n";
7840 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
7841 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
7842 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
7843 outs() << " S_LAZY_SYMBOL_POINTERS\n";
7844 else if (section_type == MachO::S_SYMBOL_STUBS)
7845 outs() << " S_SYMBOL_STUBS\n";
7846 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
7847 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
7848 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
7849 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
7850 else if (section_type == MachO::S_COALESCED)
7851 outs() << " S_COALESCED\n";
7852 else if (section_type == MachO::S_INTERPOSING)
7853 outs() << " S_INTERPOSING\n";
7854 else if (section_type == MachO::S_DTRACE_DOF)
7855 outs() << " S_DTRACE_DOF\n";
7856 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
7857 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
7858 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
7859 outs() << " S_THREAD_LOCAL_REGULAR\n";
7860 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
7861 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
7862 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
7863 outs() << " S_THREAD_LOCAL_VARIABLES\n";
7864 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7865 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
7866 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
7867 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
7869 outs() << format("0x%08" PRIx32, section_type) << "\n";
7870 outs() << "attributes";
7871 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
7872 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
7873 outs() << " PURE_INSTRUCTIONS";
7874 if (section_attributes & MachO::S_ATTR_NO_TOC)
7875 outs() << " NO_TOC";
7876 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
7877 outs() << " STRIP_STATIC_SYMS";
7878 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
7879 outs() << " NO_DEAD_STRIP";
7880 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
7881 outs() << " LIVE_SUPPORT";
7882 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
7883 outs() << " SELF_MODIFYING_CODE";
7884 if (section_attributes & MachO::S_ATTR_DEBUG)
7886 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
7887 outs() << " SOME_INSTRUCTIONS";
7888 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
7889 outs() << " EXT_RELOC";
7890 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
7891 outs() << " LOC_RELOC";
7892 if (section_attributes == 0)
7893 outs() << " (none)";
7896 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
7897 outs() << " reserved1 " << reserved1;
7898 if (section_type == MachO::S_SYMBOL_STUBS ||
7899 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
7900 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
7901 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
7902 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7903 outs() << " (index into indirect symbol table)\n";
7906 outs() << " reserved2 " << reserved2;
7907 if (section_type == MachO::S_SYMBOL_STUBS)
7908 outs() << " (size of stubs)\n";
7913 static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
7914 uint32_t object_size) {
7915 outs() << " cmd LC_SYMTAB\n";
7916 outs() << " cmdsize " << st.cmdsize;
7917 if (st.cmdsize != sizeof(struct MachO::symtab_command))
7918 outs() << " Incorrect size\n";
7921 outs() << " symoff " << st.symoff;
7922 if (st.symoff > object_size)
7923 outs() << " (past end of file)\n";
7926 outs() << " nsyms " << st.nsyms;
7929 big_size = st.nsyms;
7930 big_size *= sizeof(struct MachO::nlist_64);
7931 big_size += st.symoff;
7932 if (big_size > object_size)
7933 outs() << " (past end of file)\n";
7937 big_size = st.nsyms;
7938 big_size *= sizeof(struct MachO::nlist);
7939 big_size += st.symoff;
7940 if (big_size > object_size)
7941 outs() << " (past end of file)\n";
7945 outs() << " stroff " << st.stroff;
7946 if (st.stroff > object_size)
7947 outs() << " (past end of file)\n";
7950 outs() << " strsize " << st.strsize;
7951 big_size = st.stroff;
7952 big_size += st.strsize;
7953 if (big_size > object_size)
7954 outs() << " (past end of file)\n";
7959 static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
7960 uint32_t nsyms, uint32_t object_size,
7962 outs() << " cmd LC_DYSYMTAB\n";
7963 outs() << " cmdsize " << dyst.cmdsize;
7964 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
7965 outs() << " Incorrect size\n";
7968 outs() << " ilocalsym " << dyst.ilocalsym;
7969 if (dyst.ilocalsym > nsyms)
7970 outs() << " (greater than the number of symbols)\n";
7973 outs() << " nlocalsym " << dyst.nlocalsym;
7975 big_size = dyst.ilocalsym;
7976 big_size += dyst.nlocalsym;
7977 if (big_size > nsyms)
7978 outs() << " (past the end of the symbol table)\n";
7981 outs() << " iextdefsym " << dyst.iextdefsym;
7982 if (dyst.iextdefsym > nsyms)
7983 outs() << " (greater than the number of symbols)\n";
7986 outs() << " nextdefsym " << dyst.nextdefsym;
7987 big_size = dyst.iextdefsym;
7988 big_size += dyst.nextdefsym;
7989 if (big_size > nsyms)
7990 outs() << " (past the end of the symbol table)\n";
7993 outs() << " iundefsym " << dyst.iundefsym;
7994 if (dyst.iundefsym > nsyms)
7995 outs() << " (greater than the number of symbols)\n";
7998 outs() << " nundefsym " << dyst.nundefsym;
7999 big_size = dyst.iundefsym;
8000 big_size += dyst.nundefsym;
8001 if (big_size > nsyms)
8002 outs() << " (past the end of the symbol table)\n";
8005 outs() << " tocoff " << dyst.tocoff;
8006 if (dyst.tocoff > object_size)
8007 outs() << " (past end of file)\n";
8010 outs() << " ntoc " << dyst.ntoc;
8011 big_size = dyst.ntoc;
8012 big_size *= sizeof(struct MachO::dylib_table_of_contents);
8013 big_size += dyst.tocoff;
8014 if (big_size > object_size)
8015 outs() << " (past end of file)\n";
8018 outs() << " modtaboff " << dyst.modtaboff;
8019 if (dyst.modtaboff > object_size)
8020 outs() << " (past end of file)\n";
8023 outs() << " nmodtab " << dyst.nmodtab;
8026 modtabend = dyst.nmodtab;
8027 modtabend *= sizeof(struct MachO::dylib_module_64);
8028 modtabend += dyst.modtaboff;
8030 modtabend = dyst.nmodtab;
8031 modtabend *= sizeof(struct MachO::dylib_module);
8032 modtabend += dyst.modtaboff;
8034 if (modtabend > object_size)
8035 outs() << " (past end of file)\n";
8038 outs() << " extrefsymoff " << dyst.extrefsymoff;
8039 if (dyst.extrefsymoff > object_size)
8040 outs() << " (past end of file)\n";
8043 outs() << " nextrefsyms " << dyst.nextrefsyms;
8044 big_size = dyst.nextrefsyms;
8045 big_size *= sizeof(struct MachO::dylib_reference);
8046 big_size += dyst.extrefsymoff;
8047 if (big_size > object_size)
8048 outs() << " (past end of file)\n";
8051 outs() << " indirectsymoff " << dyst.indirectsymoff;
8052 if (dyst.indirectsymoff > object_size)
8053 outs() << " (past end of file)\n";
8056 outs() << " nindirectsyms " << dyst.nindirectsyms;
8057 big_size = dyst.nindirectsyms;
8058 big_size *= sizeof(uint32_t);
8059 big_size += dyst.indirectsymoff;
8060 if (big_size > object_size)
8061 outs() << " (past end of file)\n";
8064 outs() << " extreloff " << dyst.extreloff;
8065 if (dyst.extreloff > object_size)
8066 outs() << " (past end of file)\n";
8069 outs() << " nextrel " << dyst.nextrel;
8070 big_size = dyst.nextrel;
8071 big_size *= sizeof(struct MachO::relocation_info);
8072 big_size += dyst.extreloff;
8073 if (big_size > object_size)
8074 outs() << " (past end of file)\n";
8077 outs() << " locreloff " << dyst.locreloff;
8078 if (dyst.locreloff > object_size)
8079 outs() << " (past end of file)\n";
8082 outs() << " nlocrel " << dyst.nlocrel;
8083 big_size = dyst.nlocrel;
8084 big_size *= sizeof(struct MachO::relocation_info);
8085 big_size += dyst.locreloff;
8086 if (big_size > object_size)
8087 outs() << " (past end of file)\n";
8092 static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
8093 uint32_t object_size) {
8094 if (dc.cmd == MachO::LC_DYLD_INFO)
8095 outs() << " cmd LC_DYLD_INFO\n";
8097 outs() << " cmd LC_DYLD_INFO_ONLY\n";
8098 outs() << " cmdsize " << dc.cmdsize;
8099 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
8100 outs() << " Incorrect size\n";
8103 outs() << " rebase_off " << dc.rebase_off;
8104 if (dc.rebase_off > object_size)
8105 outs() << " (past end of file)\n";
8108 outs() << " rebase_size " << dc.rebase_size;
8110 big_size = dc.rebase_off;
8111 big_size += dc.rebase_size;
8112 if (big_size > object_size)
8113 outs() << " (past end of file)\n";
8116 outs() << " bind_off " << dc.bind_off;
8117 if (dc.bind_off > object_size)
8118 outs() << " (past end of file)\n";
8121 outs() << " bind_size " << dc.bind_size;
8122 big_size = dc.bind_off;
8123 big_size += dc.bind_size;
8124 if (big_size > object_size)
8125 outs() << " (past end of file)\n";
8128 outs() << " weak_bind_off " << dc.weak_bind_off;
8129 if (dc.weak_bind_off > object_size)
8130 outs() << " (past end of file)\n";
8133 outs() << " weak_bind_size " << dc.weak_bind_size;
8134 big_size = dc.weak_bind_off;
8135 big_size += dc.weak_bind_size;
8136 if (big_size > object_size)
8137 outs() << " (past end of file)\n";
8140 outs() << " lazy_bind_off " << dc.lazy_bind_off;
8141 if (dc.lazy_bind_off > object_size)
8142 outs() << " (past end of file)\n";
8145 outs() << " lazy_bind_size " << dc.lazy_bind_size;
8146 big_size = dc.lazy_bind_off;
8147 big_size += dc.lazy_bind_size;
8148 if (big_size > object_size)
8149 outs() << " (past end of file)\n";
8152 outs() << " export_off " << dc.export_off;
8153 if (dc.export_off > object_size)
8154 outs() << " (past end of file)\n";
8157 outs() << " export_size " << dc.export_size;
8158 big_size = dc.export_off;
8159 big_size += dc.export_size;
8160 if (big_size > object_size)
8161 outs() << " (past end of file)\n";
8166 static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
8168 if (dyld.cmd == MachO::LC_ID_DYLINKER)
8169 outs() << " cmd LC_ID_DYLINKER\n";
8170 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
8171 outs() << " cmd LC_LOAD_DYLINKER\n";
8172 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
8173 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
8175 outs() << " cmd ?(" << dyld.cmd << ")\n";
8176 outs() << " cmdsize " << dyld.cmdsize;
8177 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
8178 outs() << " Incorrect size\n";
8181 if (dyld.name >= dyld.cmdsize)
8182 outs() << " name ?(bad offset " << dyld.name << ")\n";
8184 const char *P = (const char *)(Ptr) + dyld.name;
8185 outs() << " name " << P << " (offset " << dyld.name << ")\n";
8189 static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
8190 outs() << " cmd LC_UUID\n";
8191 outs() << " cmdsize " << uuid.cmdsize;
8192 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
8193 outs() << " Incorrect size\n";
8197 for (int i = 0; i < 16; ++i) {
8198 outs() << format("%02" PRIX32, uuid.uuid[i]);
8199 if (i == 3 || i == 5 || i == 7 || i == 9)
8205 static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
8206 outs() << " cmd LC_RPATH\n";
8207 outs() << " cmdsize " << rpath.cmdsize;
8208 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
8209 outs() << " Incorrect size\n";
8212 if (rpath.path >= rpath.cmdsize)
8213 outs() << " path ?(bad offset " << rpath.path << ")\n";
8215 const char *P = (const char *)(Ptr) + rpath.path;
8216 outs() << " path " << P << " (offset " << rpath.path << ")\n";
8220 static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
8221 StringRef LoadCmdName;
8223 case MachO::LC_VERSION_MIN_MACOSX:
8224 LoadCmdName = "LC_VERSION_MIN_MACOSX";
8226 case MachO::LC_VERSION_MIN_IPHONEOS:
8227 LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
8229 case MachO::LC_VERSION_MIN_TVOS:
8230 LoadCmdName = "LC_VERSION_MIN_TVOS";
8232 case MachO::LC_VERSION_MIN_WATCHOS:
8233 LoadCmdName = "LC_VERSION_MIN_WATCHOS";
8236 llvm_unreachable("Unknown version min load command");
8239 outs() << " cmd " << LoadCmdName << '\n';
8240 outs() << " cmdsize " << vd.cmdsize;
8241 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
8242 outs() << " Incorrect size\n";
8245 outs() << " version "
8246 << MachOObjectFile::getVersionMinMajor(vd, false) << "."
8247 << MachOObjectFile::getVersionMinMinor(vd, false);
8248 uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
8250 outs() << "." << Update;
8253 outs() << " sdk n/a";
8256 << MachOObjectFile::getVersionMinMajor(vd, true) << "."
8257 << MachOObjectFile::getVersionMinMinor(vd, true);
8259 Update = MachOObjectFile::getVersionMinUpdate(vd, true);
8261 outs() << "." << Update;
8265 static void PrintSourceVersionCommand(MachO::source_version_command sd) {
8266 outs() << " cmd LC_SOURCE_VERSION\n";
8267 outs() << " cmdsize " << sd.cmdsize;
8268 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
8269 outs() << " Incorrect size\n";
8272 uint64_t a = (sd.version >> 40) & 0xffffff;
8273 uint64_t b = (sd.version >> 30) & 0x3ff;
8274 uint64_t c = (sd.version >> 20) & 0x3ff;
8275 uint64_t d = (sd.version >> 10) & 0x3ff;
8276 uint64_t e = sd.version & 0x3ff;
8277 outs() << " version " << a << "." << b;
8279 outs() << "." << c << "." << d << "." << e;
8281 outs() << "." << c << "." << d;
8287 static void PrintEntryPointCommand(MachO::entry_point_command ep) {
8288 outs() << " cmd LC_MAIN\n";
8289 outs() << " cmdsize " << ep.cmdsize;
8290 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
8291 outs() << " Incorrect size\n";
8294 outs() << " entryoff " << ep.entryoff << "\n";
8295 outs() << " stacksize " << ep.stacksize << "\n";
8298 static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
8299 uint32_t object_size) {
8300 outs() << " cmd LC_ENCRYPTION_INFO\n";
8301 outs() << " cmdsize " << ec.cmdsize;
8302 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
8303 outs() << " Incorrect size\n";
8306 outs() << " cryptoff " << ec.cryptoff;
8307 if (ec.cryptoff > object_size)
8308 outs() << " (past end of file)\n";
8311 outs() << " cryptsize " << ec.cryptsize;
8312 if (ec.cryptsize > object_size)
8313 outs() << " (past end of file)\n";
8316 outs() << " cryptid " << ec.cryptid << "\n";
8319 static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
8320 uint32_t object_size) {
8321 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
8322 outs() << " cmdsize " << ec.cmdsize;
8323 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
8324 outs() << " Incorrect size\n";
8327 outs() << " cryptoff " << ec.cryptoff;
8328 if (ec.cryptoff > object_size)
8329 outs() << " (past end of file)\n";
8332 outs() << " cryptsize " << ec.cryptsize;
8333 if (ec.cryptsize > object_size)
8334 outs() << " (past end of file)\n";
8337 outs() << " cryptid " << ec.cryptid << "\n";
8338 outs() << " pad " << ec.pad << "\n";
8341 static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
8343 outs() << " cmd LC_LINKER_OPTION\n";
8344 outs() << " cmdsize " << lo.cmdsize;
8345 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
8346 outs() << " Incorrect size\n";
8349 outs() << " count " << lo.count << "\n";
8350 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
8351 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
8354 while (*string == '\0' && left > 0) {
8360 outs() << " string #" << i << " " << format("%.*s\n", left, string);
8361 uint32_t NullPos = StringRef(string, left).find('\0');
8362 uint32_t len = std::min(NullPos, left) + 1;
8368 outs() << " count " << lo.count << " does not match number of strings "
8372 static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
8374 outs() << " cmd LC_SUB_FRAMEWORK\n";
8375 outs() << " cmdsize " << sub.cmdsize;
8376 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
8377 outs() << " Incorrect size\n";
8380 if (sub.umbrella < sub.cmdsize) {
8381 const char *P = Ptr + sub.umbrella;
8382 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
8384 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
8388 static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
8390 outs() << " cmd LC_SUB_UMBRELLA\n";
8391 outs() << " cmdsize " << sub.cmdsize;
8392 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
8393 outs() << " Incorrect size\n";
8396 if (sub.sub_umbrella < sub.cmdsize) {
8397 const char *P = Ptr + sub.sub_umbrella;
8398 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
8400 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
8404 static void PrintSubLibraryCommand(MachO::sub_library_command sub,
8406 outs() << " cmd LC_SUB_LIBRARY\n";
8407 outs() << " cmdsize " << sub.cmdsize;
8408 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
8409 outs() << " Incorrect size\n";
8412 if (sub.sub_library < sub.cmdsize) {
8413 const char *P = Ptr + sub.sub_library;
8414 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
8416 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
8420 static void PrintSubClientCommand(MachO::sub_client_command sub,
8422 outs() << " cmd LC_SUB_CLIENT\n";
8423 outs() << " cmdsize " << sub.cmdsize;
8424 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
8425 outs() << " Incorrect size\n";
8428 if (sub.client < sub.cmdsize) {
8429 const char *P = Ptr + sub.client;
8430 outs() << " client " << P << " (offset " << sub.client << ")\n";
8432 outs() << " client ?(bad offset " << sub.client << ")\n";
8436 static void PrintRoutinesCommand(MachO::routines_command r) {
8437 outs() << " cmd LC_ROUTINES\n";
8438 outs() << " cmdsize " << r.cmdsize;
8439 if (r.cmdsize != sizeof(struct MachO::routines_command))
8440 outs() << " Incorrect size\n";
8443 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
8444 outs() << " init_module " << r.init_module << "\n";
8445 outs() << " reserved1 " << r.reserved1 << "\n";
8446 outs() << " reserved2 " << r.reserved2 << "\n";
8447 outs() << " reserved3 " << r.reserved3 << "\n";
8448 outs() << " reserved4 " << r.reserved4 << "\n";
8449 outs() << " reserved5 " << r.reserved5 << "\n";
8450 outs() << " reserved6 " << r.reserved6 << "\n";
8453 static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
8454 outs() << " cmd LC_ROUTINES_64\n";
8455 outs() << " cmdsize " << r.cmdsize;
8456 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
8457 outs() << " Incorrect size\n";
8460 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
8461 outs() << " init_module " << r.init_module << "\n";
8462 outs() << " reserved1 " << r.reserved1 << "\n";
8463 outs() << " reserved2 " << r.reserved2 << "\n";
8464 outs() << " reserved3 " << r.reserved3 << "\n";
8465 outs() << " reserved4 " << r.reserved4 << "\n";
8466 outs() << " reserved5 " << r.reserved5 << "\n";
8467 outs() << " reserved6 " << r.reserved6 << "\n";
8470 static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
8471 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
8472 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
8473 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
8474 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
8475 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
8476 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
8477 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
8478 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
8479 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
8480 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
8481 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
8482 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
8483 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
8484 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
8485 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
8486 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
8487 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
8488 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
8489 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
8490 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
8491 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
8494 static void Print_mmst_reg(MachO::mmst_reg_t &r) {
8496 outs() << "\t mmst_reg ";
8497 for (f = 0; f < 10; f++)
8498 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
8500 outs() << "\t mmst_rsrv ";
8501 for (f = 0; f < 6; f++)
8502 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
8506 static void Print_xmm_reg(MachO::xmm_reg_t &r) {
8508 outs() << "\t xmm_reg ";
8509 for (f = 0; f < 16; f++)
8510 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
8514 static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
8515 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
8516 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
8517 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
8518 outs() << " denorm " << fpu.fpu_fcw.denorm;
8519 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
8520 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
8521 outs() << " undfl " << fpu.fpu_fcw.undfl;
8522 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
8523 outs() << "\t\t pc ";
8524 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
8525 outs() << "FP_PREC_24B ";
8526 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
8527 outs() << "FP_PREC_53B ";
8528 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
8529 outs() << "FP_PREC_64B ";
8531 outs() << fpu.fpu_fcw.pc << " ";
8533 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
8534 outs() << "FP_RND_NEAR ";
8535 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
8536 outs() << "FP_RND_DOWN ";
8537 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
8538 outs() << "FP_RND_UP ";
8539 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
8540 outs() << "FP_CHOP ";
8542 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
8543 outs() << " denorm " << fpu.fpu_fsw.denorm;
8544 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
8545 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
8546 outs() << " undfl " << fpu.fpu_fsw.undfl;
8547 outs() << " precis " << fpu.fpu_fsw.precis;
8548 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
8549 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
8550 outs() << " c0 " << fpu.fpu_fsw.c0;
8551 outs() << " c1 " << fpu.fpu_fsw.c1;
8552 outs() << " c2 " << fpu.fpu_fsw.c2;
8553 outs() << " tos " << fpu.fpu_fsw.tos;
8554 outs() << " c3 " << fpu.fpu_fsw.c3;
8555 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
8556 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
8557 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
8558 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
8559 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
8560 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
8561 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
8562 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
8563 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
8564 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
8565 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
8566 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
8568 outs() << "\t fpu_stmm0:\n";
8569 Print_mmst_reg(fpu.fpu_stmm0);
8570 outs() << "\t fpu_stmm1:\n";
8571 Print_mmst_reg(fpu.fpu_stmm1);
8572 outs() << "\t fpu_stmm2:\n";
8573 Print_mmst_reg(fpu.fpu_stmm2);
8574 outs() << "\t fpu_stmm3:\n";
8575 Print_mmst_reg(fpu.fpu_stmm3);
8576 outs() << "\t fpu_stmm4:\n";
8577 Print_mmst_reg(fpu.fpu_stmm4);
8578 outs() << "\t fpu_stmm5:\n";
8579 Print_mmst_reg(fpu.fpu_stmm5);
8580 outs() << "\t fpu_stmm6:\n";
8581 Print_mmst_reg(fpu.fpu_stmm6);
8582 outs() << "\t fpu_stmm7:\n";
8583 Print_mmst_reg(fpu.fpu_stmm7);
8584 outs() << "\t fpu_xmm0:\n";
8585 Print_xmm_reg(fpu.fpu_xmm0);
8586 outs() << "\t fpu_xmm1:\n";
8587 Print_xmm_reg(fpu.fpu_xmm1);
8588 outs() << "\t fpu_xmm2:\n";
8589 Print_xmm_reg(fpu.fpu_xmm2);
8590 outs() << "\t fpu_xmm3:\n";
8591 Print_xmm_reg(fpu.fpu_xmm3);
8592 outs() << "\t fpu_xmm4:\n";
8593 Print_xmm_reg(fpu.fpu_xmm4);
8594 outs() << "\t fpu_xmm5:\n";
8595 Print_xmm_reg(fpu.fpu_xmm5);
8596 outs() << "\t fpu_xmm6:\n";
8597 Print_xmm_reg(fpu.fpu_xmm6);
8598 outs() << "\t fpu_xmm7:\n";
8599 Print_xmm_reg(fpu.fpu_xmm7);
8600 outs() << "\t fpu_xmm8:\n";
8601 Print_xmm_reg(fpu.fpu_xmm8);
8602 outs() << "\t fpu_xmm9:\n";
8603 Print_xmm_reg(fpu.fpu_xmm9);
8604 outs() << "\t fpu_xmm10:\n";
8605 Print_xmm_reg(fpu.fpu_xmm10);
8606 outs() << "\t fpu_xmm11:\n";
8607 Print_xmm_reg(fpu.fpu_xmm11);
8608 outs() << "\t fpu_xmm12:\n";
8609 Print_xmm_reg(fpu.fpu_xmm12);
8610 outs() << "\t fpu_xmm13:\n";
8611 Print_xmm_reg(fpu.fpu_xmm13);
8612 outs() << "\t fpu_xmm14:\n";
8613 Print_xmm_reg(fpu.fpu_xmm14);
8614 outs() << "\t fpu_xmm15:\n";
8615 Print_xmm_reg(fpu.fpu_xmm15);
8616 outs() << "\t fpu_rsrv4:\n";
8617 for (uint32_t f = 0; f < 6; f++) {
8619 for (uint32_t g = 0; g < 16; g++)
8620 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
8623 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
8627 static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
8628 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
8629 outs() << " err " << format("0x%08" PRIx32, exc64.err);
8630 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
8633 static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
8634 bool isLittleEndian, uint32_t cputype) {
8635 if (t.cmd == MachO::LC_THREAD)
8636 outs() << " cmd LC_THREAD\n";
8637 else if (t.cmd == MachO::LC_UNIXTHREAD)
8638 outs() << " cmd LC_UNIXTHREAD\n";
8640 outs() << " cmd " << t.cmd << " (unknown)\n";
8641 outs() << " cmdsize " << t.cmdsize;
8642 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
8643 outs() << " Incorrect size\n";
8647 const char *begin = Ptr + sizeof(struct MachO::thread_command);
8648 const char *end = Ptr + t.cmdsize;
8649 uint32_t flavor, count, left;
8650 if (cputype == MachO::CPU_TYPE_X86_64) {
8651 while (begin < end) {
8652 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8653 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8654 begin += sizeof(uint32_t);
8659 if (isLittleEndian != sys::IsLittleEndianHost)
8660 sys::swapByteOrder(flavor);
8661 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8662 memcpy((char *)&count, begin, sizeof(uint32_t));
8663 begin += sizeof(uint32_t);
8668 if (isLittleEndian != sys::IsLittleEndianHost)
8669 sys::swapByteOrder(count);
8670 if (flavor == MachO::x86_THREAD_STATE64) {
8671 outs() << " flavor x86_THREAD_STATE64\n";
8672 if (count == MachO::x86_THREAD_STATE64_COUNT)
8673 outs() << " count x86_THREAD_STATE64_COUNT\n";
8675 outs() << " count " << count
8676 << " (not x86_THREAD_STATE64_COUNT)\n";
8677 MachO::x86_thread_state64_t cpu64;
8679 if (left >= sizeof(MachO::x86_thread_state64_t)) {
8680 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
8681 begin += sizeof(MachO::x86_thread_state64_t);
8683 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
8684 memcpy(&cpu64, begin, left);
8687 if (isLittleEndian != sys::IsLittleEndianHost)
8689 Print_x86_thread_state64_t(cpu64);
8690 } else if (flavor == MachO::x86_THREAD_STATE) {
8691 outs() << " flavor x86_THREAD_STATE\n";
8692 if (count == MachO::x86_THREAD_STATE_COUNT)
8693 outs() << " count x86_THREAD_STATE_COUNT\n";
8695 outs() << " count " << count
8696 << " (not x86_THREAD_STATE_COUNT)\n";
8697 struct MachO::x86_thread_state_t ts;
8699 if (left >= sizeof(MachO::x86_thread_state_t)) {
8700 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
8701 begin += sizeof(MachO::x86_thread_state_t);
8703 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
8704 memcpy(&ts, begin, left);
8707 if (isLittleEndian != sys::IsLittleEndianHost)
8709 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
8710 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
8711 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
8712 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
8714 outs() << "tsh.count " << ts.tsh.count
8715 << " (not x86_THREAD_STATE64_COUNT\n";
8716 Print_x86_thread_state64_t(ts.uts.ts64);
8718 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
8719 << ts.tsh.count << "\n";
8721 } else if (flavor == MachO::x86_FLOAT_STATE) {
8722 outs() << " flavor x86_FLOAT_STATE\n";
8723 if (count == MachO::x86_FLOAT_STATE_COUNT)
8724 outs() << " count x86_FLOAT_STATE_COUNT\n";
8726 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
8727 struct MachO::x86_float_state_t fs;
8729 if (left >= sizeof(MachO::x86_float_state_t)) {
8730 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
8731 begin += sizeof(MachO::x86_float_state_t);
8733 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
8734 memcpy(&fs, begin, left);
8737 if (isLittleEndian != sys::IsLittleEndianHost)
8739 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
8740 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
8741 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
8742 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
8744 outs() << "fsh.count " << fs.fsh.count
8745 << " (not x86_FLOAT_STATE64_COUNT\n";
8746 Print_x86_float_state_t(fs.ufs.fs64);
8748 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
8749 << fs.fsh.count << "\n";
8751 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
8752 outs() << " flavor x86_EXCEPTION_STATE\n";
8753 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
8754 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
8756 outs() << " count " << count
8757 << " (not x86_EXCEPTION_STATE_COUNT)\n";
8758 struct MachO::x86_exception_state_t es;
8760 if (left >= sizeof(MachO::x86_exception_state_t)) {
8761 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
8762 begin += sizeof(MachO::x86_exception_state_t);
8764 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
8765 memcpy(&es, begin, left);
8768 if (isLittleEndian != sys::IsLittleEndianHost)
8770 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
8771 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
8772 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
8773 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
8775 outs() << "\t esh.count " << es.esh.count
8776 << " (not x86_EXCEPTION_STATE64_COUNT\n";
8777 Print_x86_exception_state_t(es.ues.es64);
8779 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
8780 << es.esh.count << "\n";
8783 outs() << " flavor " << flavor << " (unknown)\n";
8784 outs() << " count " << count << "\n";
8785 outs() << " state (unknown)\n";
8786 begin += count * sizeof(uint32_t);
8790 while (begin < end) {
8791 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8792 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8793 begin += sizeof(uint32_t);
8798 if (isLittleEndian != sys::IsLittleEndianHost)
8799 sys::swapByteOrder(flavor);
8800 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8801 memcpy((char *)&count, begin, sizeof(uint32_t));
8802 begin += sizeof(uint32_t);
8807 if (isLittleEndian != sys::IsLittleEndianHost)
8808 sys::swapByteOrder(count);
8809 outs() << " flavor " << flavor << "\n";
8810 outs() << " count " << count << "\n";
8811 outs() << " state (Unknown cputype/cpusubtype)\n";
8812 begin += count * sizeof(uint32_t);
8817 static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
8818 if (dl.cmd == MachO::LC_ID_DYLIB)
8819 outs() << " cmd LC_ID_DYLIB\n";
8820 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
8821 outs() << " cmd LC_LOAD_DYLIB\n";
8822 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
8823 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
8824 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
8825 outs() << " cmd LC_REEXPORT_DYLIB\n";
8826 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
8827 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
8828 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
8829 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
8831 outs() << " cmd " << dl.cmd << " (unknown)\n";
8832 outs() << " cmdsize " << dl.cmdsize;
8833 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
8834 outs() << " Incorrect size\n";
8837 if (dl.dylib.name < dl.cmdsize) {
8838 const char *P = (const char *)(Ptr) + dl.dylib.name;
8839 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
8841 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
8843 outs() << " time stamp " << dl.dylib.timestamp << " ";
8844 time_t t = dl.dylib.timestamp;
8845 outs() << ctime(&t);
8846 outs() << " current version ";
8847 if (dl.dylib.current_version == 0xffffffff)
8850 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
8851 << ((dl.dylib.current_version >> 8) & 0xff) << "."
8852 << (dl.dylib.current_version & 0xff) << "\n";
8853 outs() << "compatibility version ";
8854 if (dl.dylib.compatibility_version == 0xffffffff)
8857 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
8858 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
8859 << (dl.dylib.compatibility_version & 0xff) << "\n";
8862 static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
8863 uint32_t object_size) {
8864 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
8865 outs() << " cmd LC_CODE_SIGNATURE\n";
8866 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
8867 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
8868 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
8869 outs() << " cmd LC_FUNCTION_STARTS\n";
8870 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
8871 outs() << " cmd LC_DATA_IN_CODE\n";
8872 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
8873 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
8874 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
8875 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
8877 outs() << " cmd " << ld.cmd << " (?)\n";
8878 outs() << " cmdsize " << ld.cmdsize;
8879 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
8880 outs() << " Incorrect size\n";
8883 outs() << " dataoff " << ld.dataoff;
8884 if (ld.dataoff > object_size)
8885 outs() << " (past end of file)\n";
8888 outs() << " datasize " << ld.datasize;
8889 uint64_t big_size = ld.dataoff;
8890 big_size += ld.datasize;
8891 if (big_size > object_size)
8892 outs() << " (past end of file)\n";
8897 static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
8898 uint32_t cputype, bool verbose) {
8899 StringRef Buf = Obj->getData();
8901 for (const auto &Command : Obj->load_commands()) {
8902 outs() << "Load command " << Index++ << "\n";
8903 if (Command.C.cmd == MachO::LC_SEGMENT) {
8904 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
8905 const char *sg_segname = SLC.segname;
8906 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
8907 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
8908 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
8910 for (unsigned j = 0; j < SLC.nsects; j++) {
8911 MachO::section S = Obj->getSection(Command, j);
8912 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
8913 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
8914 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
8916 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
8917 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
8918 const char *sg_segname = SLC_64.segname;
8919 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
8920 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
8921 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
8922 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
8923 for (unsigned j = 0; j < SLC_64.nsects; j++) {
8924 MachO::section_64 S_64 = Obj->getSection64(Command, j);
8925 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
8926 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
8927 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
8928 sg_segname, filetype, Buf.size(), verbose);
8930 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
8931 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
8932 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
8933 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
8934 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
8935 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
8936 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
8938 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
8939 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
8940 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
8941 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
8942 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
8943 Command.C.cmd == MachO::LC_ID_DYLINKER ||
8944 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
8945 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
8946 PrintDyldLoadCommand(Dyld, Command.Ptr);
8947 } else if (Command.C.cmd == MachO::LC_UUID) {
8948 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
8949 PrintUuidLoadCommand(Uuid);
8950 } else if (Command.C.cmd == MachO::LC_RPATH) {
8951 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
8952 PrintRpathLoadCommand(Rpath, Command.Ptr);
8953 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
8954 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
8955 Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
8956 Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
8957 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
8958 PrintVersionMinLoadCommand(Vd);
8959 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
8960 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
8961 PrintSourceVersionCommand(Sd);
8962 } else if (Command.C.cmd == MachO::LC_MAIN) {
8963 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
8964 PrintEntryPointCommand(Ep);
8965 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
8966 MachO::encryption_info_command Ei =
8967 Obj->getEncryptionInfoCommand(Command);
8968 PrintEncryptionInfoCommand(Ei, Buf.size());
8969 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
8970 MachO::encryption_info_command_64 Ei =
8971 Obj->getEncryptionInfoCommand64(Command);
8972 PrintEncryptionInfoCommand64(Ei, Buf.size());
8973 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
8974 MachO::linker_option_command Lo =
8975 Obj->getLinkerOptionLoadCommand(Command);
8976 PrintLinkerOptionCommand(Lo, Command.Ptr);
8977 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
8978 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
8979 PrintSubFrameworkCommand(Sf, Command.Ptr);
8980 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
8981 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
8982 PrintSubUmbrellaCommand(Sf, Command.Ptr);
8983 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
8984 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
8985 PrintSubLibraryCommand(Sl, Command.Ptr);
8986 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
8987 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
8988 PrintSubClientCommand(Sc, Command.Ptr);
8989 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
8990 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
8991 PrintRoutinesCommand(Rc);
8992 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
8993 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
8994 PrintRoutinesCommand64(Rc);
8995 } else if (Command.C.cmd == MachO::LC_THREAD ||
8996 Command.C.cmd == MachO::LC_UNIXTHREAD) {
8997 MachO::thread_command Tc = Obj->getThreadCommand(Command);
8998 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
8999 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
9000 Command.C.cmd == MachO::LC_ID_DYLIB ||
9001 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
9002 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
9003 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
9004 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
9005 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
9006 PrintDylibCommand(Dl, Command.Ptr);
9007 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
9008 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
9009 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
9010 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
9011 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
9012 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
9013 MachO::linkedit_data_command Ld =
9014 Obj->getLinkeditDataLoadCommand(Command);
9015 PrintLinkEditDataCommand(Ld, Buf.size());
9017 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
9019 outs() << " cmdsize " << Command.C.cmdsize << "\n";
9020 // TODO: get and print the raw bytes of the load command.
9022 // TODO: print all the other kinds of load commands.
9026 static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
9027 if (Obj->is64Bit()) {
9028 MachO::mach_header_64 H_64;
9029 H_64 = Obj->getHeader64();
9030 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
9031 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
9033 MachO::mach_header H;
9034 H = Obj->getHeader();
9035 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
9036 H.sizeofcmds, H.flags, verbose);
9040 void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
9041 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
9042 PrintMachHeader(file, !NonVerbose);
9045 void llvm::printMachOLoadCommands(const object::ObjectFile *Obj) {
9046 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
9047 uint32_t filetype = 0;
9048 uint32_t cputype = 0;
9049 if (file->is64Bit()) {
9050 MachO::mach_header_64 H_64;
9051 H_64 = file->getHeader64();
9052 filetype = H_64.filetype;
9053 cputype = H_64.cputype;
9055 MachO::mach_header H;
9056 H = file->getHeader();
9057 filetype = H.filetype;
9058 cputype = H.cputype;
9060 PrintLoadCommands(file, filetype, cputype, !NonVerbose);
9063 //===----------------------------------------------------------------------===//
9064 // export trie dumping
9065 //===----------------------------------------------------------------------===//
9067 void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
9068 for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
9069 uint64_t Flags = Entry.flags();
9070 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
9071 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
9072 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
9073 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
9074 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
9075 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
9076 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
9078 outs() << "[re-export] ";
9080 outs() << format("0x%08llX ",
9081 Entry.address()); // FIXME:add in base address
9082 outs() << Entry.name();
9083 if (WeakDef || ThreadLocal || Resolver || Abs) {
9084 bool NeedsComma = false;
9087 outs() << "weak_def";
9093 outs() << "per-thread";
9099 outs() << "absolute";
9105 outs() << format("resolver=0x%08llX", Entry.other());
9111 StringRef DylibName = "unknown";
9112 int Ordinal = Entry.other() - 1;
9113 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
9114 if (Entry.otherName().empty())
9115 outs() << " (from " << DylibName << ")";
9117 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
9123 //===----------------------------------------------------------------------===//
9124 // rebase table dumping
9125 //===----------------------------------------------------------------------===//
9130 SegInfo(const object::MachOObjectFile *Obj);
9132 StringRef segmentName(uint32_t SegIndex);
9133 StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
9134 uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
9135 bool isValidSegIndexAndOffset(uint32_t SegIndex, uint64_t SegOffset);
9138 struct SectionInfo {
9141 StringRef SectionName;
9142 StringRef SegmentName;
9143 uint64_t OffsetInSegment;
9144 uint64_t SegmentStartAddress;
9145 uint32_t SegmentIndex;
9147 const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
9148 SmallVector<SectionInfo, 32> Sections;
9152 SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
9153 // Build table of sections so segIndex/offset pairs can be translated.
9154 uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
9155 StringRef CurSegName;
9156 uint64_t CurSegAddress;
9157 for (const SectionRef &Section : Obj->sections()) {
9159 error(Section.getName(Info.SectionName));
9160 Info.Address = Section.getAddress();
9161 Info.Size = Section.getSize();
9163 Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
9164 if (!Info.SegmentName.equals(CurSegName)) {
9166 CurSegName = Info.SegmentName;
9167 CurSegAddress = Info.Address;
9169 Info.SegmentIndex = CurSegIndex - 1;
9170 Info.OffsetInSegment = Info.Address - CurSegAddress;
9171 Info.SegmentStartAddress = CurSegAddress;
9172 Sections.push_back(Info);
9176 StringRef SegInfo::segmentName(uint32_t SegIndex) {
9177 for (const SectionInfo &SI : Sections) {
9178 if (SI.SegmentIndex == SegIndex)
9179 return SI.SegmentName;
9181 llvm_unreachable("invalid segIndex");
9184 bool SegInfo::isValidSegIndexAndOffset(uint32_t SegIndex,
9185 uint64_t OffsetInSeg) {
9186 for (const SectionInfo &SI : Sections) {
9187 if (SI.SegmentIndex != SegIndex)
9189 if (SI.OffsetInSegment > OffsetInSeg)
9191 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
9198 const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
9199 uint64_t OffsetInSeg) {
9200 for (const SectionInfo &SI : Sections) {
9201 if (SI.SegmentIndex != SegIndex)
9203 if (SI.OffsetInSegment > OffsetInSeg)
9205 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
9209 llvm_unreachable("segIndex and offset not in any section");
9212 StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
9213 return findSection(SegIndex, OffsetInSeg).SectionName;
9216 uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
9217 const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
9218 return SI.SegmentStartAddress + OffsetInSeg;
9221 void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
9222 // Build table of sections so names can used in final output.
9223 SegInfo sectionTable(Obj);
9225 outs() << "segment section address type\n";
9226 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
9227 uint32_t SegIndex = Entry.segmentIndex();
9228 uint64_t OffsetInSeg = Entry.segmentOffset();
9229 StringRef SegmentName = sectionTable.segmentName(SegIndex);
9230 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
9231 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
9233 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
9234 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
9235 SegmentName.str().c_str(), SectionName.str().c_str(),
9236 Address, Entry.typeName().str().c_str());
9240 static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
9241 StringRef DylibName;
9243 case MachO::BIND_SPECIAL_DYLIB_SELF:
9244 return "this-image";
9245 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
9246 return "main-executable";
9247 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
9248 return "flat-namespace";
9251 std::error_code EC =
9252 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
9254 return "<<bad library ordinal>>";
9258 return "<<unknown special ordinal>>";
9261 //===----------------------------------------------------------------------===//
9262 // bind table dumping
9263 //===----------------------------------------------------------------------===//
9265 void llvm::printMachOBindTable(const object::MachOObjectFile *Obj) {
9266 // Build table of sections so names can used in final output.
9267 SegInfo sectionTable(Obj);
9269 outs() << "segment section address type "
9270 "addend dylib symbol\n";
9271 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
9272 uint32_t SegIndex = Entry.segmentIndex();
9273 uint64_t OffsetInSeg = Entry.segmentOffset();
9274 StringRef SegmentName = sectionTable.segmentName(SegIndex);
9275 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
9276 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
9278 // Table lines look like:
9279 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
9281 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
9282 Attr = " (weak_import)";
9283 outs() << left_justify(SegmentName, 8) << " "
9284 << left_justify(SectionName, 18) << " "
9285 << format_hex(Address, 10, true) << " "
9286 << left_justify(Entry.typeName(), 8) << " "
9287 << format_decimal(Entry.addend(), 8) << " "
9288 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
9289 << Entry.symbolName() << Attr << "\n";
9293 //===----------------------------------------------------------------------===//
9294 // lazy bind table dumping
9295 //===----------------------------------------------------------------------===//
9297 void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) {
9298 // Build table of sections so names can used in final output.
9299 SegInfo sectionTable(Obj);
9301 outs() << "segment section address "
9303 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
9304 uint32_t SegIndex = Entry.segmentIndex();
9305 uint64_t OffsetInSeg = Entry.segmentOffset();
9306 StringRef SegmentName = sectionTable.segmentName(SegIndex);
9307 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
9308 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
9310 // Table lines look like:
9311 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
9312 outs() << left_justify(SegmentName, 8) << " "
9313 << left_justify(SectionName, 18) << " "
9314 << format_hex(Address, 10, true) << " "
9315 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
9316 << Entry.symbolName() << "\n";
9320 //===----------------------------------------------------------------------===//
9321 // weak bind table dumping
9322 //===----------------------------------------------------------------------===//
9324 void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
9325 // Build table of sections so names can used in final output.
9326 SegInfo sectionTable(Obj);
9328 outs() << "segment section address "
9329 "type addend symbol\n";
9330 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
9331 // Strong symbols don't have a location to update.
9332 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
9333 outs() << " strong "
9334 << Entry.symbolName() << "\n";
9337 uint32_t SegIndex = Entry.segmentIndex();
9338 uint64_t OffsetInSeg = Entry.segmentOffset();
9339 StringRef SegmentName = sectionTable.segmentName(SegIndex);
9340 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
9341 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
9343 // Table lines look like:
9344 // __DATA __data 0x00001000 pointer 0 _foo
9345 outs() << left_justify(SegmentName, 8) << " "
9346 << left_justify(SectionName, 18) << " "
9347 << format_hex(Address, 10, true) << " "
9348 << left_justify(Entry.typeName(), 8) << " "
9349 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
9354 // get_dyld_bind_info_symbolname() is used for disassembly and passed an
9355 // address, ReferenceValue, in the Mach-O file and looks in the dyld bind
9356 // information for that address. If the address is found its binding symbol
9357 // name is returned. If not nullptr is returned.
9358 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
9359 struct DisassembleInfo *info) {
9360 if (info->bindtable == nullptr) {
9361 info->bindtable = new (BindTable);
9362 SegInfo sectionTable(info->O);
9363 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) {
9364 uint32_t SegIndex = Entry.segmentIndex();
9365 uint64_t OffsetInSeg = Entry.segmentOffset();
9366 if (!sectionTable.isValidSegIndexAndOffset(SegIndex, OffsetInSeg))
9368 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
9369 const char *SymbolName = nullptr;
9370 StringRef name = Entry.symbolName();
9372 SymbolName = name.data();
9373 info->bindtable->push_back(std::make_pair(Address, SymbolName));
9376 for (bind_table_iterator BI = info->bindtable->begin(),
9377 BE = info->bindtable->end();
9379 uint64_t Address = BI->first;
9380 if (ReferenceValue == Address) {
9381 const char *SymbolName = BI->second;