1 //===-- MachODump.cpp - Object file dumping utility for llvm --------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the MachO-specific dumper for llvm-objdump.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm-objdump.h"
15 #include "llvm-c/Disassembler.h"
16 #include "llvm/ADT/Optional.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/Triple.h"
20 #include "llvm/Config/config.h"
21 #include "llvm/DebugInfo/DIContext.h"
22 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
23 #include "llvm/MC/MCAsmInfo.h"
24 #include "llvm/MC/MCContext.h"
25 #include "llvm/MC/MCDisassembler/MCDisassembler.h"
26 #include "llvm/MC/MCInst.h"
27 #include "llvm/MC/MCInstPrinter.h"
28 #include "llvm/MC/MCInstrDesc.h"
29 #include "llvm/MC/MCInstrInfo.h"
30 #include "llvm/MC/MCRegisterInfo.h"
31 #include "llvm/MC/MCSubtargetInfo.h"
32 #include "llvm/Object/MachO.h"
33 #include "llvm/Object/MachOUniversal.h"
34 #include "llvm/Support/Casting.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/Endian.h"
38 #include "llvm/Support/Format.h"
39 #include "llvm/Support/FormattedStream.h"
40 #include "llvm/Support/GraphWriter.h"
41 #include "llvm/Support/LEB128.h"
42 #include "llvm/Support/MachO.h"
43 #include "llvm/Support/MemoryBuffer.h"
44 #include "llvm/Support/TargetRegistry.h"
45 #include "llvm/Support/TargetSelect.h"
46 #include "llvm/Support/raw_ostream.h"
47 #include <algorithm>
48 #include <cstring>
49 #include <system_error>
50 
51 #if HAVE_CXXABI_H
52 #include <cxxabi.h>
53 #endif
54 
55 using namespace llvm;
56 using namespace object;
57 
58 static cl::opt<bool>
59     UseDbg("g",
60            cl::desc("Print line information from debug info if available"));
61 
62 static cl::opt<std::string> DSYMFile("dsym",
63                                      cl::desc("Use .dSYM file for debug info"));
64 
65 static cl::opt<bool> FullLeadingAddr("full-leading-addr",
66                                      cl::desc("Print full leading address"));
67 
68 static cl::opt<bool> NoLeadingAddr("no-leading-addr",
69                                    cl::desc("Print no leading address"));
70 
71 cl::opt<bool> llvm::UniversalHeaders("universal-headers",
72                                      cl::desc("Print Mach-O universal headers "
73                                               "(requires -macho)"));
74 
75 cl::opt<bool>
76     llvm::ArchiveHeaders("archive-headers",
77                          cl::desc("Print archive headers for Mach-O archives "
78                                   "(requires -macho)"));
79 
80 cl::opt<bool>
81     ArchiveMemberOffsets("archive-member-offsets",
82                          cl::desc("Print the offset to each archive member for "
83                                   "Mach-O archives (requires -macho and "
84                                   "-archive-headers)"));
85 
86 cl::opt<bool>
87     llvm::IndirectSymbols("indirect-symbols",
88                           cl::desc("Print indirect symbol table for Mach-O "
89                                    "objects (requires -macho)"));
90 
91 cl::opt<bool>
92     llvm::DataInCode("data-in-code",
93                      cl::desc("Print the data in code table for Mach-O objects "
94                               "(requires -macho)"));
95 
96 cl::opt<bool>
97     llvm::LinkOptHints("link-opt-hints",
98                        cl::desc("Print the linker optimization hints for "
99                                 "Mach-O objects (requires -macho)"));
100 
101 cl::opt<bool>
102     llvm::InfoPlist("info-plist",
103                     cl::desc("Print the info plist section as strings for "
104                              "Mach-O objects (requires -macho)"));
105 
106 cl::opt<bool>
107     llvm::DylibsUsed("dylibs-used",
108                      cl::desc("Print the shared libraries used for linked "
109                               "Mach-O files (requires -macho)"));
110 
111 cl::opt<bool>
112     llvm::DylibId("dylib-id",
113                   cl::desc("Print the shared library's id for the dylib Mach-O "
114                            "file (requires -macho)"));
115 
116 cl::opt<bool>
117     llvm::NonVerbose("non-verbose",
118                      cl::desc("Print the info for Mach-O objects in "
119                               "non-verbose or numeric form (requires -macho)"));
120 
121 cl::opt<bool>
122     llvm::ObjcMetaData("objc-meta-data",
123                        cl::desc("Print the Objective-C runtime meta data for "
124                                 "Mach-O files (requires -macho)"));
125 
126 cl::opt<std::string> llvm::DisSymName(
127     "dis-symname",
128     cl::desc("disassemble just this symbol's instructions (requires -macho"));
129 
130 static cl::opt<bool> NoSymbolicOperands(
131     "no-symbolic-operands",
132     cl::desc("do not symbolic operands when disassembling (requires -macho)"));
133 
134 static cl::list<std::string>
135     ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
136               cl::ZeroOrMore);
137 
138 bool ArchAll = false;
139 
140 static std::string ThumbTripleName;
141 
142 static const Target *GetTarget(const MachOObjectFile *MachOObj,
143                                const char **McpuDefault,
144                                const Target **ThumbTarget) {
145   // Figure out the target triple.
146   if (TripleName.empty()) {
147     llvm::Triple TT("unknown-unknown-unknown");
148     llvm::Triple ThumbTriple = Triple();
149     TT = MachOObj->getArch(McpuDefault, &ThumbTriple);
150     TripleName = TT.str();
151     ThumbTripleName = ThumbTriple.str();
152   }
153 
154   // Get the target specific parser.
155   std::string Error;
156   const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
157   if (TheTarget && ThumbTripleName.empty())
158     return TheTarget;
159 
160   *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
161   if (*ThumbTarget)
162     return TheTarget;
163 
164   errs() << "llvm-objdump: error: unable to get target for '";
165   if (!TheTarget)
166     errs() << TripleName;
167   else
168     errs() << ThumbTripleName;
169   errs() << "', see --version and --triple.\n";
170   return nullptr;
171 }
172 
173 struct SymbolSorter {
174   bool operator()(const SymbolRef &A, const SymbolRef &B) {
175     uint64_t AAddr = (A.getType() != SymbolRef::ST_Function) ? 0 : A.getValue();
176     uint64_t BAddr = (B.getType() != SymbolRef::ST_Function) ? 0 : B.getValue();
177     return AAddr < BAddr;
178   }
179 };
180 
181 // Types for the storted data in code table that is built before disassembly
182 // and the predicate function to sort them.
183 typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
184 typedef std::vector<DiceTableEntry> DiceTable;
185 typedef DiceTable::iterator dice_table_iterator;
186 
187 // This is used to search for a data in code table entry for the PC being
188 // disassembled.  The j parameter has the PC in j.first.  A single data in code
189 // table entry can cover many bytes for each of its Kind's.  So if the offset,
190 // aka the i.first value, of the data in code table entry plus its Length
191 // covers the PC being searched for this will return true.  If not it will
192 // return false.
193 static bool compareDiceTableEntries(const DiceTableEntry &i,
194                                     const DiceTableEntry &j) {
195   uint16_t Length;
196   i.second.getLength(Length);
197 
198   return j.first >= i.first && j.first < i.first + Length;
199 }
200 
201 static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
202                                unsigned short Kind) {
203   uint32_t Value, Size = 1;
204 
205   switch (Kind) {
206   default:
207   case MachO::DICE_KIND_DATA:
208     if (Length >= 4) {
209       if (!NoShowRawInsn)
210         dumpBytes(makeArrayRef(bytes, 4), outs());
211       Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
212       outs() << "\t.long " << Value;
213       Size = 4;
214     } else if (Length >= 2) {
215       if (!NoShowRawInsn)
216         dumpBytes(makeArrayRef(bytes, 2), outs());
217       Value = bytes[1] << 8 | bytes[0];
218       outs() << "\t.short " << Value;
219       Size = 2;
220     } else {
221       if (!NoShowRawInsn)
222         dumpBytes(makeArrayRef(bytes, 2), outs());
223       Value = bytes[0];
224       outs() << "\t.byte " << Value;
225       Size = 1;
226     }
227     if (Kind == MachO::DICE_KIND_DATA)
228       outs() << "\t@ KIND_DATA\n";
229     else
230       outs() << "\t@ data in code kind = " << Kind << "\n";
231     break;
232   case MachO::DICE_KIND_JUMP_TABLE8:
233     if (!NoShowRawInsn)
234       dumpBytes(makeArrayRef(bytes, 1), outs());
235     Value = bytes[0];
236     outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
237     Size = 1;
238     break;
239   case MachO::DICE_KIND_JUMP_TABLE16:
240     if (!NoShowRawInsn)
241       dumpBytes(makeArrayRef(bytes, 2), outs());
242     Value = bytes[1] << 8 | bytes[0];
243     outs() << "\t.short " << format("%5u", Value & 0xffff)
244            << "\t@ KIND_JUMP_TABLE16\n";
245     Size = 2;
246     break;
247   case MachO::DICE_KIND_JUMP_TABLE32:
248   case MachO::DICE_KIND_ABS_JUMP_TABLE32:
249     if (!NoShowRawInsn)
250       dumpBytes(makeArrayRef(bytes, 4), outs());
251     Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
252     outs() << "\t.long " << Value;
253     if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
254       outs() << "\t@ KIND_JUMP_TABLE32\n";
255     else
256       outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
257     Size = 4;
258     break;
259   }
260   return Size;
261 }
262 
263 static void getSectionsAndSymbols(MachOObjectFile *MachOObj,
264                                   std::vector<SectionRef> &Sections,
265                                   std::vector<SymbolRef> &Symbols,
266                                   SmallVectorImpl<uint64_t> &FoundFns,
267                                   uint64_t &BaseSegmentAddress) {
268   for (const SymbolRef &Symbol : MachOObj->symbols()) {
269     ErrorOr<StringRef> SymName = Symbol.getName();
270     if (std::error_code EC = SymName.getError())
271       report_fatal_error(EC.message());
272     if (!SymName->startswith("ltmp"))
273       Symbols.push_back(Symbol);
274   }
275 
276   for (const SectionRef &Section : MachOObj->sections()) {
277     StringRef SectName;
278     Section.getName(SectName);
279     Sections.push_back(Section);
280   }
281 
282   bool BaseSegmentAddressSet = false;
283   for (const auto &Command : MachOObj->load_commands()) {
284     if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
285       // We found a function starts segment, parse the addresses for later
286       // consumption.
287       MachO::linkedit_data_command LLC =
288           MachOObj->getLinkeditDataLoadCommand(Command);
289 
290       MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
291     } else if (Command.C.cmd == MachO::LC_SEGMENT) {
292       MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
293       StringRef SegName = SLC.segname;
294       if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
295         BaseSegmentAddressSet = true;
296         BaseSegmentAddress = SLC.vmaddr;
297       }
298     }
299   }
300 }
301 
302 static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
303                                      uint32_t n, uint32_t count,
304                                      uint32_t stride, uint64_t addr) {
305   MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
306   uint32_t nindirectsyms = Dysymtab.nindirectsyms;
307   if (n > nindirectsyms)
308     outs() << " (entries start past the end of the indirect symbol "
309               "table) (reserved1 field greater than the table size)";
310   else if (n + count > nindirectsyms)
311     outs() << " (entries extends past the end of the indirect symbol "
312               "table)";
313   outs() << "\n";
314   uint32_t cputype = O->getHeader().cputype;
315   if (cputype & MachO::CPU_ARCH_ABI64)
316     outs() << "address            index";
317   else
318     outs() << "address    index";
319   if (verbose)
320     outs() << " name\n";
321   else
322     outs() << "\n";
323   for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
324     if (cputype & MachO::CPU_ARCH_ABI64)
325       outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
326     else
327       outs() << format("0x%08" PRIx32, addr + j * stride) << " ";
328     MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
329     uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
330     if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
331       outs() << "LOCAL\n";
332       continue;
333     }
334     if (indirect_symbol ==
335         (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
336       outs() << "LOCAL ABSOLUTE\n";
337       continue;
338     }
339     if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
340       outs() << "ABSOLUTE\n";
341       continue;
342     }
343     outs() << format("%5u ", indirect_symbol);
344     if (verbose) {
345       MachO::symtab_command Symtab = O->getSymtabLoadCommand();
346       if (indirect_symbol < Symtab.nsyms) {
347         symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
348         SymbolRef Symbol = *Sym;
349         ErrorOr<StringRef> SymName = Symbol.getName();
350         if (std::error_code EC = SymName.getError())
351           report_fatal_error(EC.message());
352         outs() << *SymName;
353       } else {
354         outs() << "?";
355       }
356     }
357     outs() << "\n";
358   }
359 }
360 
361 static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
362   for (const auto &Load : O->load_commands()) {
363     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
364       MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
365       for (unsigned J = 0; J < Seg.nsects; ++J) {
366         MachO::section_64 Sec = O->getSection64(Load, J);
367         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
368         if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
369             section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
370             section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
371             section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
372             section_type == MachO::S_SYMBOL_STUBS) {
373           uint32_t stride;
374           if (section_type == MachO::S_SYMBOL_STUBS)
375             stride = Sec.reserved2;
376           else
377             stride = 8;
378           if (stride == 0) {
379             outs() << "Can't print indirect symbols for (" << Sec.segname << ","
380                    << Sec.sectname << ") "
381                    << "(size of stubs in reserved2 field is zero)\n";
382             continue;
383           }
384           uint32_t count = Sec.size / stride;
385           outs() << "Indirect symbols for (" << Sec.segname << ","
386                  << Sec.sectname << ") " << count << " entries";
387           uint32_t n = Sec.reserved1;
388           PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
389         }
390       }
391     } else if (Load.C.cmd == MachO::LC_SEGMENT) {
392       MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
393       for (unsigned J = 0; J < Seg.nsects; ++J) {
394         MachO::section Sec = O->getSection(Load, J);
395         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
396         if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
397             section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
398             section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
399             section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
400             section_type == MachO::S_SYMBOL_STUBS) {
401           uint32_t stride;
402           if (section_type == MachO::S_SYMBOL_STUBS)
403             stride = Sec.reserved2;
404           else
405             stride = 4;
406           if (stride == 0) {
407             outs() << "Can't print indirect symbols for (" << Sec.segname << ","
408                    << Sec.sectname << ") "
409                    << "(size of stubs in reserved2 field is zero)\n";
410             continue;
411           }
412           uint32_t count = Sec.size / stride;
413           outs() << "Indirect symbols for (" << Sec.segname << ","
414                  << Sec.sectname << ") " << count << " entries";
415           uint32_t n = Sec.reserved1;
416           PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
417         }
418       }
419     }
420   }
421 }
422 
423 static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
424   MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
425   uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
426   outs() << "Data in code table (" << nentries << " entries)\n";
427   outs() << "offset     length kind\n";
428   for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
429        ++DI) {
430     uint32_t Offset;
431     DI->getOffset(Offset);
432     outs() << format("0x%08" PRIx32, Offset) << " ";
433     uint16_t Length;
434     DI->getLength(Length);
435     outs() << format("%6u", Length) << " ";
436     uint16_t Kind;
437     DI->getKind(Kind);
438     if (verbose) {
439       switch (Kind) {
440       case MachO::DICE_KIND_DATA:
441         outs() << "DATA";
442         break;
443       case MachO::DICE_KIND_JUMP_TABLE8:
444         outs() << "JUMP_TABLE8";
445         break;
446       case MachO::DICE_KIND_JUMP_TABLE16:
447         outs() << "JUMP_TABLE16";
448         break;
449       case MachO::DICE_KIND_JUMP_TABLE32:
450         outs() << "JUMP_TABLE32";
451         break;
452       case MachO::DICE_KIND_ABS_JUMP_TABLE32:
453         outs() << "ABS_JUMP_TABLE32";
454         break;
455       default:
456         outs() << format("0x%04" PRIx32, Kind);
457         break;
458       }
459     } else
460       outs() << format("0x%04" PRIx32, Kind);
461     outs() << "\n";
462   }
463 }
464 
465 static void PrintLinkOptHints(MachOObjectFile *O) {
466   MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
467   const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
468   uint32_t nloh = LohLC.datasize;
469   outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
470   for (uint32_t i = 0; i < nloh;) {
471     unsigned n;
472     uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
473     i += n;
474     outs() << "    identifier " << identifier << " ";
475     if (i >= nloh)
476       return;
477     switch (identifier) {
478     case 1:
479       outs() << "AdrpAdrp\n";
480       break;
481     case 2:
482       outs() << "AdrpLdr\n";
483       break;
484     case 3:
485       outs() << "AdrpAddLdr\n";
486       break;
487     case 4:
488       outs() << "AdrpLdrGotLdr\n";
489       break;
490     case 5:
491       outs() << "AdrpAddStr\n";
492       break;
493     case 6:
494       outs() << "AdrpLdrGotStr\n";
495       break;
496     case 7:
497       outs() << "AdrpAdd\n";
498       break;
499     case 8:
500       outs() << "AdrpLdrGot\n";
501       break;
502     default:
503       outs() << "Unknown identifier value\n";
504       break;
505     }
506     uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
507     i += n;
508     outs() << "    narguments " << narguments << "\n";
509     if (i >= nloh)
510       return;
511 
512     for (uint32_t j = 0; j < narguments; j++) {
513       uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
514       i += n;
515       outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
516       if (i >= nloh)
517         return;
518     }
519   }
520 }
521 
522 static void PrintDylibs(MachOObjectFile *O, bool JustId) {
523   unsigned Index = 0;
524   for (const auto &Load : O->load_commands()) {
525     if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
526         (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
527                      Load.C.cmd == MachO::LC_LOAD_DYLIB ||
528                      Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
529                      Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
530                      Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
531                      Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
532       MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
533       if (dl.dylib.name < dl.cmdsize) {
534         const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
535         if (JustId)
536           outs() << p << "\n";
537         else {
538           outs() << "\t" << p;
539           outs() << " (compatibility version "
540                  << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
541                  << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
542                  << (dl.dylib.compatibility_version & 0xff) << ",";
543           outs() << " current version "
544                  << ((dl.dylib.current_version >> 16) & 0xffff) << "."
545                  << ((dl.dylib.current_version >> 8) & 0xff) << "."
546                  << (dl.dylib.current_version & 0xff) << ")\n";
547         }
548       } else {
549         outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
550         if (Load.C.cmd == MachO::LC_ID_DYLIB)
551           outs() << "LC_ID_DYLIB ";
552         else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
553           outs() << "LC_LOAD_DYLIB ";
554         else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
555           outs() << "LC_LOAD_WEAK_DYLIB ";
556         else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
557           outs() << "LC_LAZY_LOAD_DYLIB ";
558         else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
559           outs() << "LC_REEXPORT_DYLIB ";
560         else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
561           outs() << "LC_LOAD_UPWARD_DYLIB ";
562         else
563           outs() << "LC_??? ";
564         outs() << "command " << Index++ << "\n";
565       }
566     }
567   }
568 }
569 
570 typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
571 
572 static void CreateSymbolAddressMap(MachOObjectFile *O,
573                                    SymbolAddressMap *AddrMap) {
574   // Create a map of symbol addresses to symbol names.
575   for (const SymbolRef &Symbol : O->symbols()) {
576     SymbolRef::Type ST = Symbol.getType();
577     if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
578         ST == SymbolRef::ST_Other) {
579       uint64_t Address = Symbol.getValue();
580       ErrorOr<StringRef> SymNameOrErr = Symbol.getName();
581       if (std::error_code EC = SymNameOrErr.getError())
582         report_fatal_error(EC.message());
583       StringRef SymName = *SymNameOrErr;
584       if (!SymName.startswith(".objc"))
585         (*AddrMap)[Address] = SymName;
586     }
587   }
588 }
589 
590 // GuessSymbolName is passed the address of what might be a symbol and a
591 // pointer to the SymbolAddressMap.  It returns the name of a symbol
592 // with that address or nullptr if no symbol is found with that address.
593 static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
594   const char *SymbolName = nullptr;
595   // A DenseMap can't lookup up some values.
596   if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
597     StringRef name = AddrMap->lookup(value);
598     if (!name.empty())
599       SymbolName = name.data();
600   }
601   return SymbolName;
602 }
603 
604 static void DumpCstringChar(const char c) {
605   char p[2];
606   p[0] = c;
607   p[1] = '\0';
608   outs().write_escaped(p);
609 }
610 
611 static void DumpCstringSection(MachOObjectFile *O, const char *sect,
612                                uint32_t sect_size, uint64_t sect_addr,
613                                bool print_addresses) {
614   for (uint32_t i = 0; i < sect_size; i++) {
615     if (print_addresses) {
616       if (O->is64Bit())
617         outs() << format("%016" PRIx64, sect_addr + i) << "  ";
618       else
619         outs() << format("%08" PRIx64, sect_addr + i) << "  ";
620     }
621     for (; i < sect_size && sect[i] != '\0'; i++)
622       DumpCstringChar(sect[i]);
623     if (i < sect_size && sect[i] == '\0')
624       outs() << "\n";
625   }
626 }
627 
628 static void DumpLiteral4(uint32_t l, float f) {
629   outs() << format("0x%08" PRIx32, l);
630   if ((l & 0x7f800000) != 0x7f800000)
631     outs() << format(" (%.16e)\n", f);
632   else {
633     if (l == 0x7f800000)
634       outs() << " (+Infinity)\n";
635     else if (l == 0xff800000)
636       outs() << " (-Infinity)\n";
637     else if ((l & 0x00400000) == 0x00400000)
638       outs() << " (non-signaling Not-a-Number)\n";
639     else
640       outs() << " (signaling Not-a-Number)\n";
641   }
642 }
643 
644 static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
645                                 uint32_t sect_size, uint64_t sect_addr,
646                                 bool print_addresses) {
647   for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
648     if (print_addresses) {
649       if (O->is64Bit())
650         outs() << format("%016" PRIx64, sect_addr + i) << "  ";
651       else
652         outs() << format("%08" PRIx64, sect_addr + i) << "  ";
653     }
654     float f;
655     memcpy(&f, sect + i, sizeof(float));
656     if (O->isLittleEndian() != sys::IsLittleEndianHost)
657       sys::swapByteOrder(f);
658     uint32_t l;
659     memcpy(&l, sect + i, sizeof(uint32_t));
660     if (O->isLittleEndian() != sys::IsLittleEndianHost)
661       sys::swapByteOrder(l);
662     DumpLiteral4(l, f);
663   }
664 }
665 
666 static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
667                          double d) {
668   outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
669   uint32_t Hi, Lo;
670   Hi = (O->isLittleEndian()) ? l1 : l0;
671   Lo = (O->isLittleEndian()) ? l0 : l1;
672 
673   // Hi is the high word, so this is equivalent to if(isfinite(d))
674   if ((Hi & 0x7ff00000) != 0x7ff00000)
675     outs() << format(" (%.16e)\n", d);
676   else {
677     if (Hi == 0x7ff00000 && Lo == 0)
678       outs() << " (+Infinity)\n";
679     else if (Hi == 0xfff00000 && Lo == 0)
680       outs() << " (-Infinity)\n";
681     else if ((Hi & 0x00080000) == 0x00080000)
682       outs() << " (non-signaling Not-a-Number)\n";
683     else
684       outs() << " (signaling Not-a-Number)\n";
685   }
686 }
687 
688 static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
689                                 uint32_t sect_size, uint64_t sect_addr,
690                                 bool print_addresses) {
691   for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
692     if (print_addresses) {
693       if (O->is64Bit())
694         outs() << format("%016" PRIx64, sect_addr + i) << "  ";
695       else
696         outs() << format("%08" PRIx64, sect_addr + i) << "  ";
697     }
698     double d;
699     memcpy(&d, sect + i, sizeof(double));
700     if (O->isLittleEndian() != sys::IsLittleEndianHost)
701       sys::swapByteOrder(d);
702     uint32_t l0, l1;
703     memcpy(&l0, sect + i, sizeof(uint32_t));
704     memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
705     if (O->isLittleEndian() != sys::IsLittleEndianHost) {
706       sys::swapByteOrder(l0);
707       sys::swapByteOrder(l1);
708     }
709     DumpLiteral8(O, l0, l1, d);
710   }
711 }
712 
713 static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
714   outs() << format("0x%08" PRIx32, l0) << " ";
715   outs() << format("0x%08" PRIx32, l1) << " ";
716   outs() << format("0x%08" PRIx32, l2) << " ";
717   outs() << format("0x%08" PRIx32, l3) << "\n";
718 }
719 
720 static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
721                                  uint32_t sect_size, uint64_t sect_addr,
722                                  bool print_addresses) {
723   for (uint32_t i = 0; i < sect_size; i += 16) {
724     if (print_addresses) {
725       if (O->is64Bit())
726         outs() << format("%016" PRIx64, sect_addr + i) << "  ";
727       else
728         outs() << format("%08" PRIx64, sect_addr + i) << "  ";
729     }
730     uint32_t l0, l1, l2, l3;
731     memcpy(&l0, sect + i, sizeof(uint32_t));
732     memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
733     memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
734     memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
735     if (O->isLittleEndian() != sys::IsLittleEndianHost) {
736       sys::swapByteOrder(l0);
737       sys::swapByteOrder(l1);
738       sys::swapByteOrder(l2);
739       sys::swapByteOrder(l3);
740     }
741     DumpLiteral16(l0, l1, l2, l3);
742   }
743 }
744 
745 static void DumpLiteralPointerSection(MachOObjectFile *O,
746                                       const SectionRef &Section,
747                                       const char *sect, uint32_t sect_size,
748                                       uint64_t sect_addr,
749                                       bool print_addresses) {
750   // Collect the literal sections in this Mach-O file.
751   std::vector<SectionRef> LiteralSections;
752   for (const SectionRef &Section : O->sections()) {
753     DataRefImpl Ref = Section.getRawDataRefImpl();
754     uint32_t section_type;
755     if (O->is64Bit()) {
756       const MachO::section_64 Sec = O->getSection64(Ref);
757       section_type = Sec.flags & MachO::SECTION_TYPE;
758     } else {
759       const MachO::section Sec = O->getSection(Ref);
760       section_type = Sec.flags & MachO::SECTION_TYPE;
761     }
762     if (section_type == MachO::S_CSTRING_LITERALS ||
763         section_type == MachO::S_4BYTE_LITERALS ||
764         section_type == MachO::S_8BYTE_LITERALS ||
765         section_type == MachO::S_16BYTE_LITERALS)
766       LiteralSections.push_back(Section);
767   }
768 
769   // Set the size of the literal pointer.
770   uint32_t lp_size = O->is64Bit() ? 8 : 4;
771 
772   // Collect the external relocation symbols for the literal pointers.
773   std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
774   for (const RelocationRef &Reloc : Section.relocations()) {
775     DataRefImpl Rel;
776     MachO::any_relocation_info RE;
777     bool isExtern = false;
778     Rel = Reloc.getRawDataRefImpl();
779     RE = O->getRelocation(Rel);
780     isExtern = O->getPlainRelocationExternal(RE);
781     if (isExtern) {
782       uint64_t RelocOffset = Reloc.getOffset();
783       symbol_iterator RelocSym = Reloc.getSymbol();
784       Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
785     }
786   }
787   array_pod_sort(Relocs.begin(), Relocs.end());
788 
789   // Dump each literal pointer.
790   for (uint32_t i = 0; i < sect_size; i += lp_size) {
791     if (print_addresses) {
792       if (O->is64Bit())
793         outs() << format("%016" PRIx64, sect_addr + i) << "  ";
794       else
795         outs() << format("%08" PRIx64, sect_addr + i) << "  ";
796     }
797     uint64_t lp;
798     if (O->is64Bit()) {
799       memcpy(&lp, sect + i, sizeof(uint64_t));
800       if (O->isLittleEndian() != sys::IsLittleEndianHost)
801         sys::swapByteOrder(lp);
802     } else {
803       uint32_t li;
804       memcpy(&li, sect + i, sizeof(uint32_t));
805       if (O->isLittleEndian() != sys::IsLittleEndianHost)
806         sys::swapByteOrder(li);
807       lp = li;
808     }
809 
810     // First look for an external relocation entry for this literal pointer.
811     auto Reloc = std::find_if(
812         Relocs.begin(), Relocs.end(),
813         [&](const std::pair<uint64_t, SymbolRef> &P) { return P.first == i; });
814     if (Reloc != Relocs.end()) {
815       symbol_iterator RelocSym = Reloc->second;
816       ErrorOr<StringRef> SymName = RelocSym->getName();
817       if (std::error_code EC = SymName.getError())
818         report_fatal_error(EC.message());
819       outs() << "external relocation entry for symbol:" << *SymName << "\n";
820       continue;
821     }
822 
823     // For local references see what the section the literal pointer points to.
824     auto Sect = std::find_if(LiteralSections.begin(), LiteralSections.end(),
825                              [&](const SectionRef &R) {
826                                return lp >= R.getAddress() &&
827                                       lp < R.getAddress() + R.getSize();
828                              });
829     if (Sect == LiteralSections.end()) {
830       outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
831       continue;
832     }
833 
834     uint64_t SectAddress = Sect->getAddress();
835     uint64_t SectSize = Sect->getSize();
836 
837     StringRef SectName;
838     Sect->getName(SectName);
839     DataRefImpl Ref = Sect->getRawDataRefImpl();
840     StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
841     outs() << SegmentName << ":" << SectName << ":";
842 
843     uint32_t section_type;
844     if (O->is64Bit()) {
845       const MachO::section_64 Sec = O->getSection64(Ref);
846       section_type = Sec.flags & MachO::SECTION_TYPE;
847     } else {
848       const MachO::section Sec = O->getSection(Ref);
849       section_type = Sec.flags & MachO::SECTION_TYPE;
850     }
851 
852     StringRef BytesStr;
853     Sect->getContents(BytesStr);
854     const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
855 
856     switch (section_type) {
857     case MachO::S_CSTRING_LITERALS:
858       for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
859            i++) {
860         DumpCstringChar(Contents[i]);
861       }
862       outs() << "\n";
863       break;
864     case MachO::S_4BYTE_LITERALS:
865       float f;
866       memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
867       uint32_t l;
868       memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
869       if (O->isLittleEndian() != sys::IsLittleEndianHost) {
870         sys::swapByteOrder(f);
871         sys::swapByteOrder(l);
872       }
873       DumpLiteral4(l, f);
874       break;
875     case MachO::S_8BYTE_LITERALS: {
876       double d;
877       memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
878       uint32_t l0, l1;
879       memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
880       memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
881              sizeof(uint32_t));
882       if (O->isLittleEndian() != sys::IsLittleEndianHost) {
883         sys::swapByteOrder(f);
884         sys::swapByteOrder(l0);
885         sys::swapByteOrder(l1);
886       }
887       DumpLiteral8(O, l0, l1, d);
888       break;
889     }
890     case MachO::S_16BYTE_LITERALS: {
891       uint32_t l0, l1, l2, l3;
892       memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
893       memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
894              sizeof(uint32_t));
895       memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
896              sizeof(uint32_t));
897       memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
898              sizeof(uint32_t));
899       if (O->isLittleEndian() != sys::IsLittleEndianHost) {
900         sys::swapByteOrder(l0);
901         sys::swapByteOrder(l1);
902         sys::swapByteOrder(l2);
903         sys::swapByteOrder(l3);
904       }
905       DumpLiteral16(l0, l1, l2, l3);
906       break;
907     }
908     }
909   }
910 }
911 
912 static void DumpInitTermPointerSection(MachOObjectFile *O, const char *sect,
913                                        uint32_t sect_size, uint64_t sect_addr,
914                                        SymbolAddressMap *AddrMap,
915                                        bool verbose) {
916   uint32_t stride;
917   stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t);
918   for (uint32_t i = 0; i < sect_size; i += stride) {
919     const char *SymbolName = nullptr;
920     if (O->is64Bit()) {
921       outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
922       uint64_t pointer_value;
923       memcpy(&pointer_value, sect + i, stride);
924       if (O->isLittleEndian() != sys::IsLittleEndianHost)
925         sys::swapByteOrder(pointer_value);
926       outs() << format("0x%016" PRIx64, pointer_value);
927       if (verbose)
928         SymbolName = GuessSymbolName(pointer_value, AddrMap);
929     } else {
930       outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
931       uint32_t pointer_value;
932       memcpy(&pointer_value, sect + i, stride);
933       if (O->isLittleEndian() != sys::IsLittleEndianHost)
934         sys::swapByteOrder(pointer_value);
935       outs() << format("0x%08" PRIx32, pointer_value);
936       if (verbose)
937         SymbolName = GuessSymbolName(pointer_value, AddrMap);
938     }
939     if (SymbolName)
940       outs() << " " << SymbolName;
941     outs() << "\n";
942   }
943 }
944 
945 static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
946                                    uint32_t size, uint64_t addr) {
947   uint32_t cputype = O->getHeader().cputype;
948   if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
949     uint32_t j;
950     for (uint32_t i = 0; i < size; i += j, addr += j) {
951       if (O->is64Bit())
952         outs() << format("%016" PRIx64, addr) << "\t";
953       else
954         outs() << format("%08" PRIx64, addr) << "\t";
955       for (j = 0; j < 16 && i + j < size; j++) {
956         uint8_t byte_word = *(sect + i + j);
957         outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
958       }
959       outs() << "\n";
960     }
961   } else {
962     uint32_t j;
963     for (uint32_t i = 0; i < size; i += j, addr += j) {
964       if (O->is64Bit())
965         outs() << format("%016" PRIx64, addr) << "\t";
966       else
967         outs() << format("%08" PRIx64, sect) << "\t";
968       for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
969            j += sizeof(int32_t)) {
970         if (i + j + sizeof(int32_t) < size) {
971           uint32_t long_word;
972           memcpy(&long_word, sect + i + j, sizeof(int32_t));
973           if (O->isLittleEndian() != sys::IsLittleEndianHost)
974             sys::swapByteOrder(long_word);
975           outs() << format("%08" PRIx32, long_word) << " ";
976         } else {
977           for (uint32_t k = 0; i + j + k < size; k++) {
978             uint8_t byte_word = *(sect + i + j);
979             outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
980           }
981         }
982       }
983       outs() << "\n";
984     }
985   }
986 }
987 
988 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
989                              StringRef DisSegName, StringRef DisSectName);
990 static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
991                                 uint32_t size, uint32_t addr);
992 
993 static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
994                                 bool verbose) {
995   SymbolAddressMap AddrMap;
996   if (verbose)
997     CreateSymbolAddressMap(O, &AddrMap);
998 
999   for (unsigned i = 0; i < FilterSections.size(); ++i) {
1000     StringRef DumpSection = FilterSections[i];
1001     std::pair<StringRef, StringRef> DumpSegSectName;
1002     DumpSegSectName = DumpSection.split(',');
1003     StringRef DumpSegName, DumpSectName;
1004     if (DumpSegSectName.second.size()) {
1005       DumpSegName = DumpSegSectName.first;
1006       DumpSectName = DumpSegSectName.second;
1007     } else {
1008       DumpSegName = "";
1009       DumpSectName = DumpSegSectName.first;
1010     }
1011     for (const SectionRef &Section : O->sections()) {
1012       StringRef SectName;
1013       Section.getName(SectName);
1014       DataRefImpl Ref = Section.getRawDataRefImpl();
1015       StringRef SegName = O->getSectionFinalSegmentName(Ref);
1016       if ((DumpSegName.empty() || SegName == DumpSegName) &&
1017           (SectName == DumpSectName)) {
1018 
1019         uint32_t section_flags;
1020         if (O->is64Bit()) {
1021           const MachO::section_64 Sec = O->getSection64(Ref);
1022           section_flags = Sec.flags;
1023 
1024         } else {
1025           const MachO::section Sec = O->getSection(Ref);
1026           section_flags = Sec.flags;
1027         }
1028         uint32_t section_type = section_flags & MachO::SECTION_TYPE;
1029 
1030         StringRef BytesStr;
1031         Section.getContents(BytesStr);
1032         const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1033         uint32_t sect_size = BytesStr.size();
1034         uint64_t sect_addr = Section.getAddress();
1035 
1036         outs() << "Contents of (" << SegName << "," << SectName
1037                << ") section\n";
1038 
1039         if (verbose) {
1040           if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1041               (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1042             DisassembleMachO(Filename, O, SegName, SectName);
1043             continue;
1044           }
1045           if (SegName == "__TEXT" && SectName == "__info_plist") {
1046             outs() << sect;
1047             continue;
1048           }
1049           if (SegName == "__OBJC" && SectName == "__protocol") {
1050             DumpProtocolSection(O, sect, sect_size, sect_addr);
1051             continue;
1052           }
1053           switch (section_type) {
1054           case MachO::S_REGULAR:
1055             DumpRawSectionContents(O, sect, sect_size, sect_addr);
1056             break;
1057           case MachO::S_ZEROFILL:
1058             outs() << "zerofill section and has no contents in the file\n";
1059             break;
1060           case MachO::S_CSTRING_LITERALS:
1061             DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1062             break;
1063           case MachO::S_4BYTE_LITERALS:
1064             DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1065             break;
1066           case MachO::S_8BYTE_LITERALS:
1067             DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1068             break;
1069           case MachO::S_16BYTE_LITERALS:
1070             DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1071             break;
1072           case MachO::S_LITERAL_POINTERS:
1073             DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
1074                                       !NoLeadingAddr);
1075             break;
1076           case MachO::S_MOD_INIT_FUNC_POINTERS:
1077           case MachO::S_MOD_TERM_FUNC_POINTERS:
1078             DumpInitTermPointerSection(O, sect, sect_size, sect_addr, &AddrMap,
1079                                        verbose);
1080             break;
1081           default:
1082             outs() << "Unknown section type ("
1083                    << format("0x%08" PRIx32, section_type) << ")\n";
1084             DumpRawSectionContents(O, sect, sect_size, sect_addr);
1085             break;
1086           }
1087         } else {
1088           if (section_type == MachO::S_ZEROFILL)
1089             outs() << "zerofill section and has no contents in the file\n";
1090           else
1091             DumpRawSectionContents(O, sect, sect_size, sect_addr);
1092         }
1093       }
1094     }
1095   }
1096 }
1097 
1098 static void DumpInfoPlistSectionContents(StringRef Filename,
1099                                          MachOObjectFile *O) {
1100   for (const SectionRef &Section : O->sections()) {
1101     StringRef SectName;
1102     Section.getName(SectName);
1103     DataRefImpl Ref = Section.getRawDataRefImpl();
1104     StringRef SegName = O->getSectionFinalSegmentName(Ref);
1105     if (SegName == "__TEXT" && SectName == "__info_plist") {
1106       outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
1107       StringRef BytesStr;
1108       Section.getContents(BytesStr);
1109       const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1110       outs() << sect;
1111       return;
1112     }
1113   }
1114 }
1115 
1116 // checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1117 // and if it is and there is a list of architecture flags is specified then
1118 // check to make sure this Mach-O file is one of those architectures or all
1119 // architectures were specified.  If not then an error is generated and this
1120 // routine returns false.  Else it returns true.
1121 static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
1122   if (isa<MachOObjectFile>(O) && !ArchAll && ArchFlags.size() != 0) {
1123     MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O);
1124     bool ArchFound = false;
1125     MachO::mach_header H;
1126     MachO::mach_header_64 H_64;
1127     Triple T;
1128     if (MachO->is64Bit()) {
1129       H_64 = MachO->MachOObjectFile::getHeader64();
1130       T = MachOObjectFile::getArch(H_64.cputype, H_64.cpusubtype);
1131     } else {
1132       H = MachO->MachOObjectFile::getHeader();
1133       T = MachOObjectFile::getArch(H.cputype, H.cpusubtype);
1134     }
1135     unsigned i;
1136     for (i = 0; i < ArchFlags.size(); ++i) {
1137       if (ArchFlags[i] == T.getArchName())
1138         ArchFound = true;
1139       break;
1140     }
1141     if (!ArchFound) {
1142       errs() << "llvm-objdump: file: " + Filename + " does not contain "
1143              << "architecture: " + ArchFlags[i] + "\n";
1144       return false;
1145     }
1146   }
1147   return true;
1148 }
1149 
1150 static void printObjcMetaData(MachOObjectFile *O, bool verbose);
1151 
1152 // ProcessMachO() is passed a single opened Mach-O file, which may be an
1153 // archive member and or in a slice of a universal file.  It prints the
1154 // the file name and header info and then processes it according to the
1155 // command line options.
1156 static void ProcessMachO(StringRef Filename, MachOObjectFile *MachOOF,
1157                          StringRef ArchiveMemberName = StringRef(),
1158                          StringRef ArchitectureName = StringRef()) {
1159   // If we are doing some processing here on the Mach-O file print the header
1160   // info.  And don't print it otherwise like in the case of printing the
1161   // UniversalHeaders or ArchiveHeaders.
1162   if (Disassemble || PrivateHeaders || ExportsTrie || Rebase || Bind ||
1163       LazyBind || WeakBind || IndirectSymbols || DataInCode || LinkOptHints ||
1164       DylibsUsed || DylibId || ObjcMetaData || (FilterSections.size() != 0)) {
1165     outs() << Filename;
1166     if (!ArchiveMemberName.empty())
1167       outs() << '(' << ArchiveMemberName << ')';
1168     if (!ArchitectureName.empty())
1169       outs() << " (architecture " << ArchitectureName << ")";
1170     outs() << ":\n";
1171   }
1172 
1173   if (Disassemble)
1174     DisassembleMachO(Filename, MachOOF, "__TEXT", "__text");
1175   if (IndirectSymbols)
1176     PrintIndirectSymbols(MachOOF, !NonVerbose);
1177   if (DataInCode)
1178     PrintDataInCodeTable(MachOOF, !NonVerbose);
1179   if (LinkOptHints)
1180     PrintLinkOptHints(MachOOF);
1181   if (Relocations)
1182     PrintRelocations(MachOOF);
1183   if (SectionHeaders)
1184     PrintSectionHeaders(MachOOF);
1185   if (SectionContents)
1186     PrintSectionContents(MachOOF);
1187   if (FilterSections.size() != 0)
1188     DumpSectionContents(Filename, MachOOF, !NonVerbose);
1189   if (InfoPlist)
1190     DumpInfoPlistSectionContents(Filename, MachOOF);
1191   if (DylibsUsed)
1192     PrintDylibs(MachOOF, false);
1193   if (DylibId)
1194     PrintDylibs(MachOOF, true);
1195   if (SymbolTable)
1196     PrintSymbolTable(MachOOF);
1197   if (UnwindInfo)
1198     printMachOUnwindInfo(MachOOF);
1199   if (PrivateHeaders) {
1200     printMachOFileHeader(MachOOF);
1201     printMachOLoadCommands(MachOOF);
1202   }
1203   if (FirstPrivateHeader)
1204     printMachOFileHeader(MachOOF);
1205   if (ObjcMetaData)
1206     printObjcMetaData(MachOOF, !NonVerbose);
1207   if (ExportsTrie)
1208     printExportsTrie(MachOOF);
1209   if (Rebase)
1210     printRebaseTable(MachOOF);
1211   if (Bind)
1212     printBindTable(MachOOF);
1213   if (LazyBind)
1214     printLazyBindTable(MachOOF);
1215   if (WeakBind)
1216     printWeakBindTable(MachOOF);
1217 
1218   if (DwarfDumpType != DIDT_Null) {
1219     std::unique_ptr<DIContext> DICtx(new DWARFContextInMemory(*MachOOF));
1220     // Dump the complete DWARF structure.
1221     DICtx->dump(outs(), DwarfDumpType, true /* DumpEH */);
1222   }
1223 }
1224 
1225 // printUnknownCPUType() helps print_fat_headers for unknown CPU's.
1226 static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
1227   outs() << "    cputype (" << cputype << ")\n";
1228   outs() << "    cpusubtype (" << cpusubtype << ")\n";
1229 }
1230 
1231 // printCPUType() helps print_fat_headers by printing the cputype and
1232 // pusubtype (symbolically for the one's it knows about).
1233 static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
1234   switch (cputype) {
1235   case MachO::CPU_TYPE_I386:
1236     switch (cpusubtype) {
1237     case MachO::CPU_SUBTYPE_I386_ALL:
1238       outs() << "    cputype CPU_TYPE_I386\n";
1239       outs() << "    cpusubtype CPU_SUBTYPE_I386_ALL\n";
1240       break;
1241     default:
1242       printUnknownCPUType(cputype, cpusubtype);
1243       break;
1244     }
1245     break;
1246   case MachO::CPU_TYPE_X86_64:
1247     switch (cpusubtype) {
1248     case MachO::CPU_SUBTYPE_X86_64_ALL:
1249       outs() << "    cputype CPU_TYPE_X86_64\n";
1250       outs() << "    cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
1251       break;
1252     case MachO::CPU_SUBTYPE_X86_64_H:
1253       outs() << "    cputype CPU_TYPE_X86_64\n";
1254       outs() << "    cpusubtype CPU_SUBTYPE_X86_64_H\n";
1255       break;
1256     default:
1257       printUnknownCPUType(cputype, cpusubtype);
1258       break;
1259     }
1260     break;
1261   case MachO::CPU_TYPE_ARM:
1262     switch (cpusubtype) {
1263     case MachO::CPU_SUBTYPE_ARM_ALL:
1264       outs() << "    cputype CPU_TYPE_ARM\n";
1265       outs() << "    cpusubtype CPU_SUBTYPE_ARM_ALL\n";
1266       break;
1267     case MachO::CPU_SUBTYPE_ARM_V4T:
1268       outs() << "    cputype CPU_TYPE_ARM\n";
1269       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V4T\n";
1270       break;
1271     case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1272       outs() << "    cputype CPU_TYPE_ARM\n";
1273       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
1274       break;
1275     case MachO::CPU_SUBTYPE_ARM_XSCALE:
1276       outs() << "    cputype CPU_TYPE_ARM\n";
1277       outs() << "    cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
1278       break;
1279     case MachO::CPU_SUBTYPE_ARM_V6:
1280       outs() << "    cputype CPU_TYPE_ARM\n";
1281       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V6\n";
1282       break;
1283     case MachO::CPU_SUBTYPE_ARM_V6M:
1284       outs() << "    cputype CPU_TYPE_ARM\n";
1285       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V6M\n";
1286       break;
1287     case MachO::CPU_SUBTYPE_ARM_V7:
1288       outs() << "    cputype CPU_TYPE_ARM\n";
1289       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V7\n";
1290       break;
1291     case MachO::CPU_SUBTYPE_ARM_V7EM:
1292       outs() << "    cputype CPU_TYPE_ARM\n";
1293       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
1294       break;
1295     case MachO::CPU_SUBTYPE_ARM_V7K:
1296       outs() << "    cputype CPU_TYPE_ARM\n";
1297       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V7K\n";
1298       break;
1299     case MachO::CPU_SUBTYPE_ARM_V7M:
1300       outs() << "    cputype CPU_TYPE_ARM\n";
1301       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V7M\n";
1302       break;
1303     case MachO::CPU_SUBTYPE_ARM_V7S:
1304       outs() << "    cputype CPU_TYPE_ARM\n";
1305       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V7S\n";
1306       break;
1307     default:
1308       printUnknownCPUType(cputype, cpusubtype);
1309       break;
1310     }
1311     break;
1312   case MachO::CPU_TYPE_ARM64:
1313     switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1314     case MachO::CPU_SUBTYPE_ARM64_ALL:
1315       outs() << "    cputype CPU_TYPE_ARM64\n";
1316       outs() << "    cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
1317       break;
1318     default:
1319       printUnknownCPUType(cputype, cpusubtype);
1320       break;
1321     }
1322     break;
1323   default:
1324     printUnknownCPUType(cputype, cpusubtype);
1325     break;
1326   }
1327 }
1328 
1329 static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
1330                                        bool verbose) {
1331   outs() << "Fat headers\n";
1332   if (verbose)
1333     outs() << "fat_magic FAT_MAGIC\n";
1334   else
1335     outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
1336 
1337   uint32_t nfat_arch = UB->getNumberOfObjects();
1338   StringRef Buf = UB->getData();
1339   uint64_t size = Buf.size();
1340   uint64_t big_size = sizeof(struct MachO::fat_header) +
1341                       nfat_arch * sizeof(struct MachO::fat_arch);
1342   outs() << "nfat_arch " << UB->getNumberOfObjects();
1343   if (nfat_arch == 0)
1344     outs() << " (malformed, contains zero architecture types)\n";
1345   else if (big_size > size)
1346     outs() << " (malformed, architectures past end of file)\n";
1347   else
1348     outs() << "\n";
1349 
1350   for (uint32_t i = 0; i < nfat_arch; ++i) {
1351     MachOUniversalBinary::ObjectForArch OFA(UB, i);
1352     uint32_t cputype = OFA.getCPUType();
1353     uint32_t cpusubtype = OFA.getCPUSubType();
1354     outs() << "architecture ";
1355     for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
1356       MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
1357       uint32_t other_cputype = other_OFA.getCPUType();
1358       uint32_t other_cpusubtype = other_OFA.getCPUSubType();
1359       if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
1360           (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
1361               (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
1362         outs() << "(illegal duplicate architecture) ";
1363         break;
1364       }
1365     }
1366     if (verbose) {
1367       outs() << OFA.getArchTypeName() << "\n";
1368       printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1369     } else {
1370       outs() << i << "\n";
1371       outs() << "    cputype " << cputype << "\n";
1372       outs() << "    cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
1373              << "\n";
1374     }
1375     if (verbose &&
1376         (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
1377       outs() << "    capabilities CPU_SUBTYPE_LIB64\n";
1378     else
1379       outs() << "    capabilities "
1380              << format("0x%" PRIx32,
1381                        (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
1382     outs() << "    offset " << OFA.getOffset();
1383     if (OFA.getOffset() > size)
1384       outs() << " (past end of file)";
1385     if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
1386       outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
1387     outs() << "\n";
1388     outs() << "    size " << OFA.getSize();
1389     big_size = OFA.getOffset() + OFA.getSize();
1390     if (big_size > size)
1391       outs() << " (past end of file)";
1392     outs() << "\n";
1393     outs() << "    align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
1394            << ")\n";
1395   }
1396 }
1397 
1398 static void printArchiveChild(const Archive::Child &C, bool verbose,
1399                               bool print_offset) {
1400   if (print_offset)
1401     outs() << C.getChildOffset() << "\t";
1402   sys::fs::perms Mode = C.getAccessMode();
1403   if (verbose) {
1404     // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
1405     // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
1406     outs() << "-";
1407     outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
1408     outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
1409     outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
1410     outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
1411     outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
1412     outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
1413     outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
1414     outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
1415     outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
1416   } else {
1417     outs() << format("0%o ", Mode);
1418   }
1419 
1420   unsigned UID = C.getUID();
1421   outs() << format("%3d/", UID);
1422   unsigned GID = C.getGID();
1423   outs() << format("%-3d ", GID);
1424   ErrorOr<uint64_t> Size = C.getRawSize();
1425   if (std::error_code EC = Size.getError())
1426     report_fatal_error(EC.message());
1427   outs() << format("%5" PRId64, Size.get()) << " ";
1428 
1429   StringRef RawLastModified = C.getRawLastModified();
1430   if (verbose) {
1431     unsigned Seconds;
1432     if (RawLastModified.getAsInteger(10, Seconds))
1433       outs() << "(date: \"%s\" contains non-decimal chars) " << RawLastModified;
1434     else {
1435       // Since cime(3) returns a 26 character string of the form:
1436       // "Sun Sep 16 01:03:52 1973\n\0"
1437       // just print 24 characters.
1438       time_t t = Seconds;
1439       outs() << format("%.24s ", ctime(&t));
1440     }
1441   } else {
1442     outs() << RawLastModified << " ";
1443   }
1444 
1445   if (verbose) {
1446     ErrorOr<StringRef> NameOrErr = C.getName();
1447     if (NameOrErr.getError()) {
1448       StringRef RawName = C.getRawName();
1449       outs() << RawName << "\n";
1450     } else {
1451       StringRef Name = NameOrErr.get();
1452       outs() << Name << "\n";
1453     }
1454   } else {
1455     StringRef RawName = C.getRawName();
1456     outs() << RawName << "\n";
1457   }
1458 }
1459 
1460 static void printArchiveHeaders(Archive *A, bool verbose, bool print_offset) {
1461   for (Archive::child_iterator I = A->child_begin(false), E = A->child_end();
1462        I != E; ++I) {
1463     if (std::error_code EC = I->getError())
1464       report_fatal_error(EC.message());
1465     const Archive::Child &C = **I;
1466     printArchiveChild(C, verbose, print_offset);
1467   }
1468 }
1469 
1470 // ParseInputMachO() parses the named Mach-O file in Filename and handles the
1471 // -arch flags selecting just those slices as specified by them and also parses
1472 // archive files.  Then for each individual Mach-O file ProcessMachO() is
1473 // called to process the file based on the command line options.
1474 void llvm::ParseInputMachO(StringRef Filename) {
1475   // Check for -arch all and verifiy the -arch flags are valid.
1476   for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1477     if (ArchFlags[i] == "all") {
1478       ArchAll = true;
1479     } else {
1480       if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
1481         errs() << "llvm-objdump: Unknown architecture named '" + ArchFlags[i] +
1482                       "'for the -arch option\n";
1483         return;
1484       }
1485     }
1486   }
1487 
1488   // Attempt to open the binary.
1489   ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
1490   if (std::error_code EC = BinaryOrErr.getError())
1491     report_error(Filename, EC);
1492   Binary &Bin = *BinaryOrErr.get().getBinary();
1493 
1494   if (Archive *A = dyn_cast<Archive>(&Bin)) {
1495     outs() << "Archive : " << Filename << "\n";
1496     if (ArchiveHeaders)
1497       printArchiveHeaders(A, !NonVerbose, ArchiveMemberOffsets);
1498     for (Archive::child_iterator I = A->child_begin(), E = A->child_end();
1499          I != E; ++I) {
1500       if (std::error_code EC = I->getError())
1501         report_error(Filename, EC);
1502       auto &C = I->get();
1503       ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1504       if (ChildOrErr.getError())
1505         continue;
1506       if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1507         if (!checkMachOAndArchFlags(O, Filename))
1508           return;
1509         ProcessMachO(Filename, O, O->getFileName());
1510       }
1511     }
1512     return;
1513   }
1514   if (UniversalHeaders) {
1515     if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin))
1516       printMachOUniversalHeaders(UB, !NonVerbose);
1517   }
1518   if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
1519     // If we have a list of architecture flags specified dump only those.
1520     if (!ArchAll && ArchFlags.size() != 0) {
1521       // Look for a slice in the universal binary that matches each ArchFlag.
1522       bool ArchFound;
1523       for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1524         ArchFound = false;
1525         for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1526                                                    E = UB->end_objects();
1527              I != E; ++I) {
1528           if (ArchFlags[i] == I->getArchTypeName()) {
1529             ArchFound = true;
1530             ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr =
1531                 I->getAsObjectFile();
1532             std::string ArchitectureName = "";
1533             if (ArchFlags.size() > 1)
1534               ArchitectureName = I->getArchTypeName();
1535             if (ObjOrErr) {
1536               ObjectFile &O = *ObjOrErr.get();
1537               if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
1538                 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
1539             } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1540                            I->getAsArchive()) {
1541               std::unique_ptr<Archive> &A = *AOrErr;
1542               outs() << "Archive : " << Filename;
1543               if (!ArchitectureName.empty())
1544                 outs() << " (architecture " << ArchitectureName << ")";
1545               outs() << "\n";
1546               if (ArchiveHeaders)
1547                 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
1548               for (Archive::child_iterator AI = A->child_begin(),
1549                                            AE = A->child_end();
1550                    AI != AE; ++AI) {
1551                 if (std::error_code EC = AI->getError())
1552                   report_error(Filename, EC);
1553                 auto &C = AI->get();
1554                 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1555                 if (ChildOrErr.getError())
1556                   continue;
1557                 if (MachOObjectFile *O =
1558                         dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
1559                   ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
1560               }
1561             }
1562           }
1563         }
1564         if (!ArchFound) {
1565           errs() << "llvm-objdump: file: " + Filename + " does not contain "
1566                  << "architecture: " + ArchFlags[i] + "\n";
1567           return;
1568         }
1569       }
1570       return;
1571     }
1572     // No architecture flags were specified so if this contains a slice that
1573     // matches the host architecture dump only that.
1574     if (!ArchAll) {
1575       for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1576                                                  E = UB->end_objects();
1577            I != E; ++I) {
1578         if (MachOObjectFile::getHostArch().getArchName() ==
1579             I->getArchTypeName()) {
1580           ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
1581           std::string ArchiveName;
1582           ArchiveName.clear();
1583           if (ObjOrErr) {
1584             ObjectFile &O = *ObjOrErr.get();
1585             if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
1586               ProcessMachO(Filename, MachOOF);
1587           } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1588                          I->getAsArchive()) {
1589             std::unique_ptr<Archive> &A = *AOrErr;
1590             outs() << "Archive : " << Filename << "\n";
1591             if (ArchiveHeaders)
1592               printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
1593             for (Archive::child_iterator AI = A->child_begin(),
1594                                          AE = A->child_end();
1595                  AI != AE; ++AI) {
1596               if (std::error_code EC = AI->getError())
1597                 report_error(Filename, EC);
1598               auto &C = AI->get();
1599               ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1600               if (ChildOrErr.getError())
1601                 continue;
1602               if (MachOObjectFile *O =
1603                       dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
1604                 ProcessMachO(Filename, O, O->getFileName());
1605             }
1606           }
1607           return;
1608         }
1609       }
1610     }
1611     // Either all architectures have been specified or none have been specified
1612     // and this does not contain the host architecture so dump all the slices.
1613     bool moreThanOneArch = UB->getNumberOfObjects() > 1;
1614     for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1615                                                E = UB->end_objects();
1616          I != E; ++I) {
1617       ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
1618       std::string ArchitectureName = "";
1619       if (moreThanOneArch)
1620         ArchitectureName = I->getArchTypeName();
1621       if (ObjOrErr) {
1622         ObjectFile &Obj = *ObjOrErr.get();
1623         if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
1624           ProcessMachO(Filename, MachOOF, "", ArchitectureName);
1625       } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
1626         std::unique_ptr<Archive> &A = *AOrErr;
1627         outs() << "Archive : " << Filename;
1628         if (!ArchitectureName.empty())
1629           outs() << " (architecture " << ArchitectureName << ")";
1630         outs() << "\n";
1631         if (ArchiveHeaders)
1632           printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
1633         for (Archive::child_iterator AI = A->child_begin(), AE = A->child_end();
1634              AI != AE; ++AI) {
1635           if (std::error_code EC = AI->getError())
1636             report_error(Filename, EC);
1637           auto &C = AI->get();
1638           ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1639           if (ChildOrErr.getError())
1640             continue;
1641           if (MachOObjectFile *O =
1642                   dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1643             if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
1644               ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
1645                            ArchitectureName);
1646           }
1647         }
1648       }
1649     }
1650     return;
1651   }
1652   if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
1653     if (!checkMachOAndArchFlags(O, Filename))
1654       return;
1655     if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) {
1656       ProcessMachO(Filename, MachOOF);
1657     } else
1658       errs() << "llvm-objdump: '" << Filename << "': "
1659              << "Object is not a Mach-O file type.\n";
1660     return;
1661   }
1662   llvm_unreachable("Input object can't be invalid at this point");
1663 }
1664 
1665 typedef std::pair<uint64_t, const char *> BindInfoEntry;
1666 typedef std::vector<BindInfoEntry> BindTable;
1667 typedef BindTable::iterator bind_table_iterator;
1668 
1669 // The block of info used by the Symbolizer call backs.
1670 struct DisassembleInfo {
1671   bool verbose;
1672   MachOObjectFile *O;
1673   SectionRef S;
1674   SymbolAddressMap *AddrMap;
1675   std::vector<SectionRef> *Sections;
1676   const char *class_name;
1677   const char *selector_name;
1678   char *method;
1679   char *demangled_name;
1680   uint64_t adrp_addr;
1681   uint32_t adrp_inst;
1682   BindTable *bindtable;
1683   uint32_t depth;
1684 };
1685 
1686 // SymbolizerGetOpInfo() is the operand information call back function.
1687 // This is called to get the symbolic information for operand(s) of an
1688 // instruction when it is being done.  This routine does this from
1689 // the relocation information, symbol table, etc. That block of information
1690 // is a pointer to the struct DisassembleInfo that was passed when the
1691 // disassembler context was created and passed to back to here when
1692 // called back by the disassembler for instruction operands that could have
1693 // relocation information. The address of the instruction containing operand is
1694 // at the Pc parameter.  The immediate value the operand has is passed in
1695 // op_info->Value and is at Offset past the start of the instruction and has a
1696 // byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
1697 // LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
1698 // names and addends of the symbolic expression to add for the operand.  The
1699 // value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
1700 // information is returned then this function returns 1 else it returns 0.
1701 static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
1702                                uint64_t Size, int TagType, void *TagBuf) {
1703   struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
1704   struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
1705   uint64_t value = op_info->Value;
1706 
1707   // Make sure all fields returned are zero if we don't set them.
1708   memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
1709   op_info->Value = value;
1710 
1711   // If the TagType is not the value 1 which it code knows about or if no
1712   // verbose symbolic information is wanted then just return 0, indicating no
1713   // information is being returned.
1714   if (TagType != 1 || !info->verbose)
1715     return 0;
1716 
1717   unsigned int Arch = info->O->getArch();
1718   if (Arch == Triple::x86) {
1719     if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1720       return 0;
1721     if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1722       // TODO:
1723       // Search the external relocation entries of a fully linked image
1724       // (if any) for an entry that matches this segment offset.
1725       // uint32_t seg_offset = (Pc + Offset);
1726       return 0;
1727     }
1728     // In MH_OBJECT filetypes search the section's relocation entries (if any)
1729     // for an entry for this section offset.
1730     uint32_t sect_addr = info->S.getAddress();
1731     uint32_t sect_offset = (Pc + Offset) - sect_addr;
1732     bool reloc_found = false;
1733     DataRefImpl Rel;
1734     MachO::any_relocation_info RE;
1735     bool isExtern = false;
1736     SymbolRef Symbol;
1737     bool r_scattered = false;
1738     uint32_t r_value, pair_r_value, r_type;
1739     for (const RelocationRef &Reloc : info->S.relocations()) {
1740       uint64_t RelocOffset = Reloc.getOffset();
1741       if (RelocOffset == sect_offset) {
1742         Rel = Reloc.getRawDataRefImpl();
1743         RE = info->O->getRelocation(Rel);
1744         r_type = info->O->getAnyRelocationType(RE);
1745         r_scattered = info->O->isRelocationScattered(RE);
1746         if (r_scattered) {
1747           r_value = info->O->getScatteredRelocationValue(RE);
1748           if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1749               r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
1750             DataRefImpl RelNext = Rel;
1751             info->O->moveRelocationNext(RelNext);
1752             MachO::any_relocation_info RENext;
1753             RENext = info->O->getRelocation(RelNext);
1754             if (info->O->isRelocationScattered(RENext))
1755               pair_r_value = info->O->getScatteredRelocationValue(RENext);
1756             else
1757               return 0;
1758           }
1759         } else {
1760           isExtern = info->O->getPlainRelocationExternal(RE);
1761           if (isExtern) {
1762             symbol_iterator RelocSym = Reloc.getSymbol();
1763             Symbol = *RelocSym;
1764           }
1765         }
1766         reloc_found = true;
1767         break;
1768       }
1769     }
1770     if (reloc_found && isExtern) {
1771       ErrorOr<StringRef> SymName = Symbol.getName();
1772       if (std::error_code EC = SymName.getError())
1773         report_fatal_error(EC.message());
1774       const char *name = SymName->data();
1775       op_info->AddSymbol.Present = 1;
1776       op_info->AddSymbol.Name = name;
1777       // For i386 extern relocation entries the value in the instruction is
1778       // the offset from the symbol, and value is already set in op_info->Value.
1779       return 1;
1780     }
1781     if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1782                         r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
1783       const char *add = GuessSymbolName(r_value, info->AddrMap);
1784       const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
1785       uint32_t offset = value - (r_value - pair_r_value);
1786       op_info->AddSymbol.Present = 1;
1787       if (add != nullptr)
1788         op_info->AddSymbol.Name = add;
1789       else
1790         op_info->AddSymbol.Value = r_value;
1791       op_info->SubtractSymbol.Present = 1;
1792       if (sub != nullptr)
1793         op_info->SubtractSymbol.Name = sub;
1794       else
1795         op_info->SubtractSymbol.Value = pair_r_value;
1796       op_info->Value = offset;
1797       return 1;
1798     }
1799     return 0;
1800   }
1801   if (Arch == Triple::x86_64) {
1802     if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1803       return 0;
1804     if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1805       // TODO:
1806       // Search the external relocation entries of a fully linked image
1807       // (if any) for an entry that matches this segment offset.
1808       // uint64_t seg_offset = (Pc + Offset);
1809       return 0;
1810     }
1811     // In MH_OBJECT filetypes search the section's relocation entries (if any)
1812     // for an entry for this section offset.
1813     uint64_t sect_addr = info->S.getAddress();
1814     uint64_t sect_offset = (Pc + Offset) - sect_addr;
1815     bool reloc_found = false;
1816     DataRefImpl Rel;
1817     MachO::any_relocation_info RE;
1818     bool isExtern = false;
1819     SymbolRef Symbol;
1820     for (const RelocationRef &Reloc : info->S.relocations()) {
1821       uint64_t RelocOffset = Reloc.getOffset();
1822       if (RelocOffset == sect_offset) {
1823         Rel = Reloc.getRawDataRefImpl();
1824         RE = info->O->getRelocation(Rel);
1825         // NOTE: Scattered relocations don't exist on x86_64.
1826         isExtern = info->O->getPlainRelocationExternal(RE);
1827         if (isExtern) {
1828           symbol_iterator RelocSym = Reloc.getSymbol();
1829           Symbol = *RelocSym;
1830         }
1831         reloc_found = true;
1832         break;
1833       }
1834     }
1835     if (reloc_found && isExtern) {
1836       // The Value passed in will be adjusted by the Pc if the instruction
1837       // adds the Pc.  But for x86_64 external relocation entries the Value
1838       // is the offset from the external symbol.
1839       if (info->O->getAnyRelocationPCRel(RE))
1840         op_info->Value -= Pc + Offset + Size;
1841       ErrorOr<StringRef> SymName = Symbol.getName();
1842       if (std::error_code EC = SymName.getError())
1843         report_fatal_error(EC.message());
1844       const char *name = SymName->data();
1845       unsigned Type = info->O->getAnyRelocationType(RE);
1846       if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
1847         DataRefImpl RelNext = Rel;
1848         info->O->moveRelocationNext(RelNext);
1849         MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
1850         unsigned TypeNext = info->O->getAnyRelocationType(RENext);
1851         bool isExternNext = info->O->getPlainRelocationExternal(RENext);
1852         unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
1853         if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
1854           op_info->SubtractSymbol.Present = 1;
1855           op_info->SubtractSymbol.Name = name;
1856           symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
1857           Symbol = *RelocSymNext;
1858           ErrorOr<StringRef> SymNameNext = Symbol.getName();
1859           if (std::error_code EC = SymNameNext.getError())
1860             report_fatal_error(EC.message());
1861           name = SymNameNext->data();
1862         }
1863       }
1864       // TODO: add the VariantKinds to op_info->VariantKind for relocation types
1865       // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
1866       op_info->AddSymbol.Present = 1;
1867       op_info->AddSymbol.Name = name;
1868       return 1;
1869     }
1870     return 0;
1871   }
1872   if (Arch == Triple::arm) {
1873     if (Offset != 0 || (Size != 4 && Size != 2))
1874       return 0;
1875     if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1876       // TODO:
1877       // Search the external relocation entries of a fully linked image
1878       // (if any) for an entry that matches this segment offset.
1879       // uint32_t seg_offset = (Pc + Offset);
1880       return 0;
1881     }
1882     // In MH_OBJECT filetypes search the section's relocation entries (if any)
1883     // for an entry for this section offset.
1884     uint32_t sect_addr = info->S.getAddress();
1885     uint32_t sect_offset = (Pc + Offset) - sect_addr;
1886     DataRefImpl Rel;
1887     MachO::any_relocation_info RE;
1888     bool isExtern = false;
1889     SymbolRef Symbol;
1890     bool r_scattered = false;
1891     uint32_t r_value, pair_r_value, r_type, r_length, other_half;
1892     auto Reloc =
1893         std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
1894                      [&](const RelocationRef &Reloc) {
1895                        uint64_t RelocOffset = Reloc.getOffset();
1896                        return RelocOffset == sect_offset;
1897                      });
1898 
1899     if (Reloc == info->S.relocations().end())
1900       return 0;
1901 
1902     Rel = Reloc->getRawDataRefImpl();
1903     RE = info->O->getRelocation(Rel);
1904     r_length = info->O->getAnyRelocationLength(RE);
1905     r_scattered = info->O->isRelocationScattered(RE);
1906     if (r_scattered) {
1907       r_value = info->O->getScatteredRelocationValue(RE);
1908       r_type = info->O->getScatteredRelocationType(RE);
1909     } else {
1910       r_type = info->O->getAnyRelocationType(RE);
1911       isExtern = info->O->getPlainRelocationExternal(RE);
1912       if (isExtern) {
1913         symbol_iterator RelocSym = Reloc->getSymbol();
1914         Symbol = *RelocSym;
1915       }
1916     }
1917     if (r_type == MachO::ARM_RELOC_HALF ||
1918         r_type == MachO::ARM_RELOC_SECTDIFF ||
1919         r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
1920         r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1921       DataRefImpl RelNext = Rel;
1922       info->O->moveRelocationNext(RelNext);
1923       MachO::any_relocation_info RENext;
1924       RENext = info->O->getRelocation(RelNext);
1925       other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
1926       if (info->O->isRelocationScattered(RENext))
1927         pair_r_value = info->O->getScatteredRelocationValue(RENext);
1928     }
1929 
1930     if (isExtern) {
1931       ErrorOr<StringRef> SymName = Symbol.getName();
1932       if (std::error_code EC = SymName.getError())
1933         report_fatal_error(EC.message());
1934       const char *name = SymName->data();
1935       op_info->AddSymbol.Present = 1;
1936       op_info->AddSymbol.Name = name;
1937       switch (r_type) {
1938       case MachO::ARM_RELOC_HALF:
1939         if ((r_length & 0x1) == 1) {
1940           op_info->Value = value << 16 | other_half;
1941           op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1942         } else {
1943           op_info->Value = other_half << 16 | value;
1944           op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
1945         }
1946         break;
1947       default:
1948         break;
1949       }
1950       return 1;
1951     }
1952     // If we have a branch that is not an external relocation entry then
1953     // return 0 so the code in tryAddingSymbolicOperand() can use the
1954     // SymbolLookUp call back with the branch target address to look up the
1955     // symbol and possiblity add an annotation for a symbol stub.
1956     if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
1957                           r_type == MachO::ARM_THUMB_RELOC_BR22))
1958       return 0;
1959 
1960     uint32_t offset = 0;
1961     if (r_type == MachO::ARM_RELOC_HALF ||
1962         r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1963       if ((r_length & 0x1) == 1)
1964         value = value << 16 | other_half;
1965       else
1966         value = other_half << 16 | value;
1967     }
1968     if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
1969                         r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
1970       offset = value - r_value;
1971       value = r_value;
1972     }
1973 
1974     if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1975       if ((r_length & 0x1) == 1)
1976         op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1977       else
1978         op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
1979       const char *add = GuessSymbolName(r_value, info->AddrMap);
1980       const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
1981       int32_t offset = value - (r_value - pair_r_value);
1982       op_info->AddSymbol.Present = 1;
1983       if (add != nullptr)
1984         op_info->AddSymbol.Name = add;
1985       else
1986         op_info->AddSymbol.Value = r_value;
1987       op_info->SubtractSymbol.Present = 1;
1988       if (sub != nullptr)
1989         op_info->SubtractSymbol.Name = sub;
1990       else
1991         op_info->SubtractSymbol.Value = pair_r_value;
1992       op_info->Value = offset;
1993       return 1;
1994     }
1995 
1996     op_info->AddSymbol.Present = 1;
1997     op_info->Value = offset;
1998     if (r_type == MachO::ARM_RELOC_HALF) {
1999       if ((r_length & 0x1) == 1)
2000         op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2001       else
2002         op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
2003     }
2004     const char *add = GuessSymbolName(value, info->AddrMap);
2005     if (add != nullptr) {
2006       op_info->AddSymbol.Name = add;
2007       return 1;
2008     }
2009     op_info->AddSymbol.Value = value;
2010     return 1;
2011   }
2012   if (Arch == Triple::aarch64) {
2013     if (Offset != 0 || Size != 4)
2014       return 0;
2015     if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2016       // TODO:
2017       // Search the external relocation entries of a fully linked image
2018       // (if any) for an entry that matches this segment offset.
2019       // uint64_t seg_offset = (Pc + Offset);
2020       return 0;
2021     }
2022     // In MH_OBJECT filetypes search the section's relocation entries (if any)
2023     // for an entry for this section offset.
2024     uint64_t sect_addr = info->S.getAddress();
2025     uint64_t sect_offset = (Pc + Offset) - sect_addr;
2026     auto Reloc =
2027         std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
2028                      [&](const RelocationRef &Reloc) {
2029                        uint64_t RelocOffset = Reloc.getOffset();
2030                        return RelocOffset == sect_offset;
2031                      });
2032 
2033     if (Reloc == info->S.relocations().end())
2034       return 0;
2035 
2036     DataRefImpl Rel = Reloc->getRawDataRefImpl();
2037     MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2038     uint32_t r_type = info->O->getAnyRelocationType(RE);
2039     if (r_type == MachO::ARM64_RELOC_ADDEND) {
2040       DataRefImpl RelNext = Rel;
2041       info->O->moveRelocationNext(RelNext);
2042       MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2043       if (value == 0) {
2044         value = info->O->getPlainRelocationSymbolNum(RENext);
2045         op_info->Value = value;
2046       }
2047     }
2048     // NOTE: Scattered relocations don't exist on arm64.
2049     if (!info->O->getPlainRelocationExternal(RE))
2050       return 0;
2051     ErrorOr<StringRef> SymName = Reloc->getSymbol()->getName();
2052     if (std::error_code EC = SymName.getError())
2053       report_fatal_error(EC.message());
2054     const char *name = SymName->data();
2055     op_info->AddSymbol.Present = 1;
2056     op_info->AddSymbol.Name = name;
2057 
2058     switch (r_type) {
2059     case MachO::ARM64_RELOC_PAGE21:
2060       /* @page */
2061       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2062       break;
2063     case MachO::ARM64_RELOC_PAGEOFF12:
2064       /* @pageoff */
2065       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2066       break;
2067     case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2068       /* @gotpage */
2069       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2070       break;
2071     case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2072       /* @gotpageoff */
2073       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2074       break;
2075     case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2076       /* @tvlppage is not implemented in llvm-mc */
2077       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2078       break;
2079     case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2080       /* @tvlppageoff is not implemented in llvm-mc */
2081       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2082       break;
2083     default:
2084     case MachO::ARM64_RELOC_BRANCH26:
2085       op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2086       break;
2087     }
2088     return 1;
2089   }
2090   return 0;
2091 }
2092 
2093 // GuessCstringPointer is passed the address of what might be a pointer to a
2094 // literal string in a cstring section.  If that address is in a cstring section
2095 // it returns a pointer to that string.  Else it returns nullptr.
2096 static const char *GuessCstringPointer(uint64_t ReferenceValue,
2097                                        struct DisassembleInfo *info) {
2098   for (const auto &Load : info->O->load_commands()) {
2099     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2100       MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2101       for (unsigned J = 0; J < Seg.nsects; ++J) {
2102         MachO::section_64 Sec = info->O->getSection64(Load, J);
2103         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2104         if (section_type == MachO::S_CSTRING_LITERALS &&
2105             ReferenceValue >= Sec.addr &&
2106             ReferenceValue < Sec.addr + Sec.size) {
2107           uint64_t sect_offset = ReferenceValue - Sec.addr;
2108           uint64_t object_offset = Sec.offset + sect_offset;
2109           StringRef MachOContents = info->O->getData();
2110           uint64_t object_size = MachOContents.size();
2111           const char *object_addr = (const char *)MachOContents.data();
2112           if (object_offset < object_size) {
2113             const char *name = object_addr + object_offset;
2114             return name;
2115           } else {
2116             return nullptr;
2117           }
2118         }
2119       }
2120     } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2121       MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2122       for (unsigned J = 0; J < Seg.nsects; ++J) {
2123         MachO::section Sec = info->O->getSection(Load, J);
2124         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2125         if (section_type == MachO::S_CSTRING_LITERALS &&
2126             ReferenceValue >= Sec.addr &&
2127             ReferenceValue < Sec.addr + Sec.size) {
2128           uint64_t sect_offset = ReferenceValue - Sec.addr;
2129           uint64_t object_offset = Sec.offset + sect_offset;
2130           StringRef MachOContents = info->O->getData();
2131           uint64_t object_size = MachOContents.size();
2132           const char *object_addr = (const char *)MachOContents.data();
2133           if (object_offset < object_size) {
2134             const char *name = object_addr + object_offset;
2135             return name;
2136           } else {
2137             return nullptr;
2138           }
2139         }
2140       }
2141     }
2142   }
2143   return nullptr;
2144 }
2145 
2146 // GuessIndirectSymbol returns the name of the indirect symbol for the
2147 // ReferenceValue passed in or nullptr.  This is used when ReferenceValue maybe
2148 // an address of a symbol stub or a lazy or non-lazy pointer to associate the
2149 // symbol name being referenced by the stub or pointer.
2150 static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2151                                        struct DisassembleInfo *info) {
2152   MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
2153   MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
2154   for (const auto &Load : info->O->load_commands()) {
2155     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2156       MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2157       for (unsigned J = 0; J < Seg.nsects; ++J) {
2158         MachO::section_64 Sec = info->O->getSection64(Load, J);
2159         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2160         if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2161              section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2162              section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2163              section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2164              section_type == MachO::S_SYMBOL_STUBS) &&
2165             ReferenceValue >= Sec.addr &&
2166             ReferenceValue < Sec.addr + Sec.size) {
2167           uint32_t stride;
2168           if (section_type == MachO::S_SYMBOL_STUBS)
2169             stride = Sec.reserved2;
2170           else
2171             stride = 8;
2172           if (stride == 0)
2173             return nullptr;
2174           uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2175           if (index < Dysymtab.nindirectsyms) {
2176             uint32_t indirect_symbol =
2177                 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
2178             if (indirect_symbol < Symtab.nsyms) {
2179               symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2180               SymbolRef Symbol = *Sym;
2181               ErrorOr<StringRef> SymName = Symbol.getName();
2182               if (std::error_code EC = SymName.getError())
2183                 report_fatal_error(EC.message());
2184               const char *name = SymName->data();
2185               return name;
2186             }
2187           }
2188         }
2189       }
2190     } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2191       MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2192       for (unsigned J = 0; J < Seg.nsects; ++J) {
2193         MachO::section Sec = info->O->getSection(Load, J);
2194         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2195         if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2196              section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2197              section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2198              section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2199              section_type == MachO::S_SYMBOL_STUBS) &&
2200             ReferenceValue >= Sec.addr &&
2201             ReferenceValue < Sec.addr + Sec.size) {
2202           uint32_t stride;
2203           if (section_type == MachO::S_SYMBOL_STUBS)
2204             stride = Sec.reserved2;
2205           else
2206             stride = 4;
2207           if (stride == 0)
2208             return nullptr;
2209           uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2210           if (index < Dysymtab.nindirectsyms) {
2211             uint32_t indirect_symbol =
2212                 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
2213             if (indirect_symbol < Symtab.nsyms) {
2214               symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2215               SymbolRef Symbol = *Sym;
2216               ErrorOr<StringRef> SymName = Symbol.getName();
2217               if (std::error_code EC = SymName.getError())
2218                 report_fatal_error(EC.message());
2219               const char *name = SymName->data();
2220               return name;
2221             }
2222           }
2223         }
2224       }
2225     }
2226   }
2227   return nullptr;
2228 }
2229 
2230 // method_reference() is called passing it the ReferenceName that might be
2231 // a reference it to an Objective-C method call.  If so then it allocates and
2232 // assembles a method call string with the values last seen and saved in
2233 // the DisassembleInfo's class_name and selector_name fields.  This is saved
2234 // into the method field of the info and any previous string is free'ed.
2235 // Then the class_name field in the info is set to nullptr.  The method call
2236 // string is set into ReferenceName and ReferenceType is set to
2237 // LLVMDisassembler_ReferenceType_Out_Objc_Message.  If this not a method call
2238 // then both ReferenceType and ReferenceName are left unchanged.
2239 static void method_reference(struct DisassembleInfo *info,
2240                              uint64_t *ReferenceType,
2241                              const char **ReferenceName) {
2242   unsigned int Arch = info->O->getArch();
2243   if (*ReferenceName != nullptr) {
2244     if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
2245       if (info->selector_name != nullptr) {
2246         if (info->method != nullptr)
2247           free(info->method);
2248         if (info->class_name != nullptr) {
2249           info->method = (char *)malloc(5 + strlen(info->class_name) +
2250                                         strlen(info->selector_name));
2251           if (info->method != nullptr) {
2252             strcpy(info->method, "+[");
2253             strcat(info->method, info->class_name);
2254             strcat(info->method, " ");
2255             strcat(info->method, info->selector_name);
2256             strcat(info->method, "]");
2257             *ReferenceName = info->method;
2258             *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2259           }
2260         } else {
2261           info->method = (char *)malloc(9 + strlen(info->selector_name));
2262           if (info->method != nullptr) {
2263             if (Arch == Triple::x86_64)
2264               strcpy(info->method, "-[%rdi ");
2265             else if (Arch == Triple::aarch64)
2266               strcpy(info->method, "-[x0 ");
2267             else
2268               strcpy(info->method, "-[r? ");
2269             strcat(info->method, info->selector_name);
2270             strcat(info->method, "]");
2271             *ReferenceName = info->method;
2272             *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2273           }
2274         }
2275         info->class_name = nullptr;
2276       }
2277     } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
2278       if (info->selector_name != nullptr) {
2279         if (info->method != nullptr)
2280           free(info->method);
2281         info->method = (char *)malloc(17 + strlen(info->selector_name));
2282         if (info->method != nullptr) {
2283           if (Arch == Triple::x86_64)
2284             strcpy(info->method, "-[[%rdi super] ");
2285           else if (Arch == Triple::aarch64)
2286             strcpy(info->method, "-[[x0 super] ");
2287           else
2288             strcpy(info->method, "-[[r? super] ");
2289           strcat(info->method, info->selector_name);
2290           strcat(info->method, "]");
2291           *ReferenceName = info->method;
2292           *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2293         }
2294         info->class_name = nullptr;
2295       }
2296     }
2297   }
2298 }
2299 
2300 // GuessPointerPointer() is passed the address of what might be a pointer to
2301 // a reference to an Objective-C class, selector, message ref or cfstring.
2302 // If so the value of the pointer is returned and one of the booleans are set
2303 // to true.  If not zero is returned and all the booleans are set to false.
2304 static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
2305                                     struct DisassembleInfo *info,
2306                                     bool &classref, bool &selref, bool &msgref,
2307                                     bool &cfstring) {
2308   classref = false;
2309   selref = false;
2310   msgref = false;
2311   cfstring = false;
2312   for (const auto &Load : info->O->load_commands()) {
2313     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2314       MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2315       for (unsigned J = 0; J < Seg.nsects; ++J) {
2316         MachO::section_64 Sec = info->O->getSection64(Load, J);
2317         if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
2318              strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2319              strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
2320              strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
2321              strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
2322             ReferenceValue >= Sec.addr &&
2323             ReferenceValue < Sec.addr + Sec.size) {
2324           uint64_t sect_offset = ReferenceValue - Sec.addr;
2325           uint64_t object_offset = Sec.offset + sect_offset;
2326           StringRef MachOContents = info->O->getData();
2327           uint64_t object_size = MachOContents.size();
2328           const char *object_addr = (const char *)MachOContents.data();
2329           if (object_offset < object_size) {
2330             uint64_t pointer_value;
2331             memcpy(&pointer_value, object_addr + object_offset,
2332                    sizeof(uint64_t));
2333             if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2334               sys::swapByteOrder(pointer_value);
2335             if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
2336               selref = true;
2337             else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2338                      strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
2339               classref = true;
2340             else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
2341                      ReferenceValue + 8 < Sec.addr + Sec.size) {
2342               msgref = true;
2343               memcpy(&pointer_value, object_addr + object_offset + 8,
2344                      sizeof(uint64_t));
2345               if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2346                 sys::swapByteOrder(pointer_value);
2347             } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
2348               cfstring = true;
2349             return pointer_value;
2350           } else {
2351             return 0;
2352           }
2353         }
2354       }
2355     }
2356     // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
2357   }
2358   return 0;
2359 }
2360 
2361 // get_pointer_64 returns a pointer to the bytes in the object file at the
2362 // Address from a section in the Mach-O file.  And indirectly returns the
2363 // offset into the section, number of bytes left in the section past the offset
2364 // and which section is was being referenced.  If the Address is not in a
2365 // section nullptr is returned.
2366 static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
2367                                   uint32_t &left, SectionRef &S,
2368                                   DisassembleInfo *info,
2369                                   bool objc_only = false) {
2370   offset = 0;
2371   left = 0;
2372   S = SectionRef();
2373   for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
2374     uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
2375     uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
2376     if (SectSize == 0)
2377       continue;
2378     if (objc_only) {
2379       StringRef SectName;
2380       ((*(info->Sections))[SectIdx]).getName(SectName);
2381       DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
2382       StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
2383       if (SegName != "__OBJC" && SectName != "__cstring")
2384         continue;
2385     }
2386     if (Address >= SectAddress && Address < SectAddress + SectSize) {
2387       S = (*(info->Sections))[SectIdx];
2388       offset = Address - SectAddress;
2389       left = SectSize - offset;
2390       StringRef SectContents;
2391       ((*(info->Sections))[SectIdx]).getContents(SectContents);
2392       return SectContents.data() + offset;
2393     }
2394   }
2395   return nullptr;
2396 }
2397 
2398 static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
2399                                   uint32_t &left, SectionRef &S,
2400                                   DisassembleInfo *info,
2401                                   bool objc_only = false) {
2402   return get_pointer_64(Address, offset, left, S, info, objc_only);
2403 }
2404 
2405 // get_symbol_64() returns the name of a symbol (or nullptr) and the address of
2406 // the symbol indirectly through n_value. Based on the relocation information
2407 // for the specified section offset in the specified section reference.
2408 // If no relocation information is found and a non-zero ReferenceValue for the
2409 // symbol is passed, look up that address in the info's AddrMap.
2410 static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
2411                                  DisassembleInfo *info, uint64_t &n_value,
2412                                  uint64_t ReferenceValue = 0) {
2413   n_value = 0;
2414   if (!info->verbose)
2415     return nullptr;
2416 
2417   // See if there is an external relocation entry at the sect_offset.
2418   bool reloc_found = false;
2419   DataRefImpl Rel;
2420   MachO::any_relocation_info RE;
2421   bool isExtern = false;
2422   SymbolRef Symbol;
2423   for (const RelocationRef &Reloc : S.relocations()) {
2424     uint64_t RelocOffset = Reloc.getOffset();
2425     if (RelocOffset == sect_offset) {
2426       Rel = Reloc.getRawDataRefImpl();
2427       RE = info->O->getRelocation(Rel);
2428       if (info->O->isRelocationScattered(RE))
2429         continue;
2430       isExtern = info->O->getPlainRelocationExternal(RE);
2431       if (isExtern) {
2432         symbol_iterator RelocSym = Reloc.getSymbol();
2433         Symbol = *RelocSym;
2434       }
2435       reloc_found = true;
2436       break;
2437     }
2438   }
2439   // If there is an external relocation entry for a symbol in this section
2440   // at this section_offset then use that symbol's value for the n_value
2441   // and return its name.
2442   const char *SymbolName = nullptr;
2443   if (reloc_found && isExtern) {
2444     n_value = Symbol.getValue();
2445     ErrorOr<StringRef> NameOrError = Symbol.getName();
2446     if (std::error_code EC = NameOrError.getError())
2447       report_fatal_error(EC.message());
2448     StringRef Name = *NameOrError;
2449     if (!Name.empty()) {
2450       SymbolName = Name.data();
2451       return SymbolName;
2452     }
2453   }
2454 
2455   // TODO: For fully linked images, look through the external relocation
2456   // entries off the dynamic symtab command. For these the r_offset is from the
2457   // start of the first writeable segment in the Mach-O file.  So the offset
2458   // to this section from that segment is passed to this routine by the caller,
2459   // as the database_offset. Which is the difference of the section's starting
2460   // address and the first writable segment.
2461   //
2462   // NOTE: need add passing the database_offset to this routine.
2463 
2464   // We did not find an external relocation entry so look up the ReferenceValue
2465   // as an address of a symbol and if found return that symbol's name.
2466   SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
2467 
2468   return SymbolName;
2469 }
2470 
2471 static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
2472                                  DisassembleInfo *info,
2473                                  uint32_t ReferenceValue) {
2474   uint64_t n_value64;
2475   return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
2476 }
2477 
2478 // These are structs in the Objective-C meta data and read to produce the
2479 // comments for disassembly.  While these are part of the ABI they are no
2480 // public defintions.  So the are here not in include/llvm/Support/MachO.h .
2481 
2482 // The cfstring object in a 64-bit Mach-O file.
2483 struct cfstring64_t {
2484   uint64_t isa;        // class64_t * (64-bit pointer)
2485   uint64_t flags;      // flag bits
2486   uint64_t characters; // char * (64-bit pointer)
2487   uint64_t length;     // number of non-NULL characters in above
2488 };
2489 
2490 // The class object in a 64-bit Mach-O file.
2491 struct class64_t {
2492   uint64_t isa;        // class64_t * (64-bit pointer)
2493   uint64_t superclass; // class64_t * (64-bit pointer)
2494   uint64_t cache;      // Cache (64-bit pointer)
2495   uint64_t vtable;     // IMP * (64-bit pointer)
2496   uint64_t data;       // class_ro64_t * (64-bit pointer)
2497 };
2498 
2499 struct class32_t {
2500   uint32_t isa;        /* class32_t * (32-bit pointer) */
2501   uint32_t superclass; /* class32_t * (32-bit pointer) */
2502   uint32_t cache;      /* Cache (32-bit pointer) */
2503   uint32_t vtable;     /* IMP * (32-bit pointer) */
2504   uint32_t data;       /* class_ro32_t * (32-bit pointer) */
2505 };
2506 
2507 struct class_ro64_t {
2508   uint32_t flags;
2509   uint32_t instanceStart;
2510   uint32_t instanceSize;
2511   uint32_t reserved;
2512   uint64_t ivarLayout;     // const uint8_t * (64-bit pointer)
2513   uint64_t name;           // const char * (64-bit pointer)
2514   uint64_t baseMethods;    // const method_list_t * (64-bit pointer)
2515   uint64_t baseProtocols;  // const protocol_list_t * (64-bit pointer)
2516   uint64_t ivars;          // const ivar_list_t * (64-bit pointer)
2517   uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
2518   uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
2519 };
2520 
2521 struct class_ro32_t {
2522   uint32_t flags;
2523   uint32_t instanceStart;
2524   uint32_t instanceSize;
2525   uint32_t ivarLayout;     /* const uint8_t * (32-bit pointer) */
2526   uint32_t name;           /* const char * (32-bit pointer) */
2527   uint32_t baseMethods;    /* const method_list_t * (32-bit pointer) */
2528   uint32_t baseProtocols;  /* const protocol_list_t * (32-bit pointer) */
2529   uint32_t ivars;          /* const ivar_list_t * (32-bit pointer) */
2530   uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
2531   uint32_t baseProperties; /* const struct objc_property_list *
2532                                                    (32-bit pointer) */
2533 };
2534 
2535 /* Values for class_ro{64,32}_t->flags */
2536 #define RO_META (1 << 0)
2537 #define RO_ROOT (1 << 1)
2538 #define RO_HAS_CXX_STRUCTORS (1 << 2)
2539 
2540 struct method_list64_t {
2541   uint32_t entsize;
2542   uint32_t count;
2543   /* struct method64_t first;  These structures follow inline */
2544 };
2545 
2546 struct method_list32_t {
2547   uint32_t entsize;
2548   uint32_t count;
2549   /* struct method32_t first;  These structures follow inline */
2550 };
2551 
2552 struct method64_t {
2553   uint64_t name;  /* SEL (64-bit pointer) */
2554   uint64_t types; /* const char * (64-bit pointer) */
2555   uint64_t imp;   /* IMP (64-bit pointer) */
2556 };
2557 
2558 struct method32_t {
2559   uint32_t name;  /* SEL (32-bit pointer) */
2560   uint32_t types; /* const char * (32-bit pointer) */
2561   uint32_t imp;   /* IMP (32-bit pointer) */
2562 };
2563 
2564 struct protocol_list64_t {
2565   uint64_t count; /* uintptr_t (a 64-bit value) */
2566   /* struct protocol64_t * list[0];  These pointers follow inline */
2567 };
2568 
2569 struct protocol_list32_t {
2570   uint32_t count; /* uintptr_t (a 32-bit value) */
2571   /* struct protocol32_t * list[0];  These pointers follow inline */
2572 };
2573 
2574 struct protocol64_t {
2575   uint64_t isa;                     /* id * (64-bit pointer) */
2576   uint64_t name;                    /* const char * (64-bit pointer) */
2577   uint64_t protocols;               /* struct protocol_list64_t *
2578                                                     (64-bit pointer) */
2579   uint64_t instanceMethods;         /* method_list_t * (64-bit pointer) */
2580   uint64_t classMethods;            /* method_list_t * (64-bit pointer) */
2581   uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
2582   uint64_t optionalClassMethods;    /* method_list_t * (64-bit pointer) */
2583   uint64_t instanceProperties;      /* struct objc_property_list *
2584                                                        (64-bit pointer) */
2585 };
2586 
2587 struct protocol32_t {
2588   uint32_t isa;                     /* id * (32-bit pointer) */
2589   uint32_t name;                    /* const char * (32-bit pointer) */
2590   uint32_t protocols;               /* struct protocol_list_t *
2591                                                     (32-bit pointer) */
2592   uint32_t instanceMethods;         /* method_list_t * (32-bit pointer) */
2593   uint32_t classMethods;            /* method_list_t * (32-bit pointer) */
2594   uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
2595   uint32_t optionalClassMethods;    /* method_list_t * (32-bit pointer) */
2596   uint32_t instanceProperties;      /* struct objc_property_list *
2597                                                        (32-bit pointer) */
2598 };
2599 
2600 struct ivar_list64_t {
2601   uint32_t entsize;
2602   uint32_t count;
2603   /* struct ivar64_t first;  These structures follow inline */
2604 };
2605 
2606 struct ivar_list32_t {
2607   uint32_t entsize;
2608   uint32_t count;
2609   /* struct ivar32_t first;  These structures follow inline */
2610 };
2611 
2612 struct ivar64_t {
2613   uint64_t offset; /* uintptr_t * (64-bit pointer) */
2614   uint64_t name;   /* const char * (64-bit pointer) */
2615   uint64_t type;   /* const char * (64-bit pointer) */
2616   uint32_t alignment;
2617   uint32_t size;
2618 };
2619 
2620 struct ivar32_t {
2621   uint32_t offset; /* uintptr_t * (32-bit pointer) */
2622   uint32_t name;   /* const char * (32-bit pointer) */
2623   uint32_t type;   /* const char * (32-bit pointer) */
2624   uint32_t alignment;
2625   uint32_t size;
2626 };
2627 
2628 struct objc_property_list64 {
2629   uint32_t entsize;
2630   uint32_t count;
2631   /* struct objc_property64 first;  These structures follow inline */
2632 };
2633 
2634 struct objc_property_list32 {
2635   uint32_t entsize;
2636   uint32_t count;
2637   /* struct objc_property32 first;  These structures follow inline */
2638 };
2639 
2640 struct objc_property64 {
2641   uint64_t name;       /* const char * (64-bit pointer) */
2642   uint64_t attributes; /* const char * (64-bit pointer) */
2643 };
2644 
2645 struct objc_property32 {
2646   uint32_t name;       /* const char * (32-bit pointer) */
2647   uint32_t attributes; /* const char * (32-bit pointer) */
2648 };
2649 
2650 struct category64_t {
2651   uint64_t name;               /* const char * (64-bit pointer) */
2652   uint64_t cls;                /* struct class_t * (64-bit pointer) */
2653   uint64_t instanceMethods;    /* struct method_list_t * (64-bit pointer) */
2654   uint64_t classMethods;       /* struct method_list_t * (64-bit pointer) */
2655   uint64_t protocols;          /* struct protocol_list_t * (64-bit pointer) */
2656   uint64_t instanceProperties; /* struct objc_property_list *
2657                                   (64-bit pointer) */
2658 };
2659 
2660 struct category32_t {
2661   uint32_t name;               /* const char * (32-bit pointer) */
2662   uint32_t cls;                /* struct class_t * (32-bit pointer) */
2663   uint32_t instanceMethods;    /* struct method_list_t * (32-bit pointer) */
2664   uint32_t classMethods;       /* struct method_list_t * (32-bit pointer) */
2665   uint32_t protocols;          /* struct protocol_list_t * (32-bit pointer) */
2666   uint32_t instanceProperties; /* struct objc_property_list *
2667                                   (32-bit pointer) */
2668 };
2669 
2670 struct objc_image_info64 {
2671   uint32_t version;
2672   uint32_t flags;
2673 };
2674 struct objc_image_info32 {
2675   uint32_t version;
2676   uint32_t flags;
2677 };
2678 struct imageInfo_t {
2679   uint32_t version;
2680   uint32_t flags;
2681 };
2682 /* masks for objc_image_info.flags */
2683 #define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
2684 #define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
2685 
2686 struct message_ref64 {
2687   uint64_t imp; /* IMP (64-bit pointer) */
2688   uint64_t sel; /* SEL (64-bit pointer) */
2689 };
2690 
2691 struct message_ref32 {
2692   uint32_t imp; /* IMP (32-bit pointer) */
2693   uint32_t sel; /* SEL (32-bit pointer) */
2694 };
2695 
2696 // Objective-C 1 (32-bit only) meta data structs.
2697 
2698 struct objc_module_t {
2699   uint32_t version;
2700   uint32_t size;
2701   uint32_t name;   /* char * (32-bit pointer) */
2702   uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
2703 };
2704 
2705 struct objc_symtab_t {
2706   uint32_t sel_ref_cnt;
2707   uint32_t refs; /* SEL * (32-bit pointer) */
2708   uint16_t cls_def_cnt;
2709   uint16_t cat_def_cnt;
2710   // uint32_t defs[1];        /* void * (32-bit pointer) variable size */
2711 };
2712 
2713 struct objc_class_t {
2714   uint32_t isa;         /* struct objc_class * (32-bit pointer) */
2715   uint32_t super_class; /* struct objc_class * (32-bit pointer) */
2716   uint32_t name;        /* const char * (32-bit pointer) */
2717   int32_t version;
2718   int32_t info;
2719   int32_t instance_size;
2720   uint32_t ivars;       /* struct objc_ivar_list * (32-bit pointer) */
2721   uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
2722   uint32_t cache;       /* struct objc_cache * (32-bit pointer) */
2723   uint32_t protocols;   /* struct objc_protocol_list * (32-bit pointer) */
2724 };
2725 
2726 #define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
2727 // class is not a metaclass
2728 #define CLS_CLASS 0x1
2729 // class is a metaclass
2730 #define CLS_META 0x2
2731 
2732 struct objc_category_t {
2733   uint32_t category_name;    /* char * (32-bit pointer) */
2734   uint32_t class_name;       /* char * (32-bit pointer) */
2735   uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
2736   uint32_t class_methods;    /* struct objc_method_list * (32-bit pointer) */
2737   uint32_t protocols;        /* struct objc_protocol_list * (32-bit ptr) */
2738 };
2739 
2740 struct objc_ivar_t {
2741   uint32_t ivar_name; /* char * (32-bit pointer) */
2742   uint32_t ivar_type; /* char * (32-bit pointer) */
2743   int32_t ivar_offset;
2744 };
2745 
2746 struct objc_ivar_list_t {
2747   int32_t ivar_count;
2748   // struct objc_ivar_t ivar_list[1];          /* variable length structure */
2749 };
2750 
2751 struct objc_method_list_t {
2752   uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
2753   int32_t method_count;
2754   // struct objc_method_t method_list[1];      /* variable length structure */
2755 };
2756 
2757 struct objc_method_t {
2758   uint32_t method_name;  /* SEL, aka struct objc_selector * (32-bit pointer) */
2759   uint32_t method_types; /* char * (32-bit pointer) */
2760   uint32_t method_imp;   /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
2761                             (32-bit pointer) */
2762 };
2763 
2764 struct objc_protocol_list_t {
2765   uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
2766   int32_t count;
2767   // uint32_t list[1];   /* Protocol *, aka struct objc_protocol_t *
2768   //                        (32-bit pointer) */
2769 };
2770 
2771 struct objc_protocol_t {
2772   uint32_t isa;              /* struct objc_class * (32-bit pointer) */
2773   uint32_t protocol_name;    /* char * (32-bit pointer) */
2774   uint32_t protocol_list;    /* struct objc_protocol_list * (32-bit pointer) */
2775   uint32_t instance_methods; /* struct objc_method_description_list *
2776                                 (32-bit pointer) */
2777   uint32_t class_methods;    /* struct objc_method_description_list *
2778                                 (32-bit pointer) */
2779 };
2780 
2781 struct objc_method_description_list_t {
2782   int32_t count;
2783   // struct objc_method_description_t list[1];
2784 };
2785 
2786 struct objc_method_description_t {
2787   uint32_t name;  /* SEL, aka struct objc_selector * (32-bit pointer) */
2788   uint32_t types; /* char * (32-bit pointer) */
2789 };
2790 
2791 inline void swapStruct(struct cfstring64_t &cfs) {
2792   sys::swapByteOrder(cfs.isa);
2793   sys::swapByteOrder(cfs.flags);
2794   sys::swapByteOrder(cfs.characters);
2795   sys::swapByteOrder(cfs.length);
2796 }
2797 
2798 inline void swapStruct(struct class64_t &c) {
2799   sys::swapByteOrder(c.isa);
2800   sys::swapByteOrder(c.superclass);
2801   sys::swapByteOrder(c.cache);
2802   sys::swapByteOrder(c.vtable);
2803   sys::swapByteOrder(c.data);
2804 }
2805 
2806 inline void swapStruct(struct class32_t &c) {
2807   sys::swapByteOrder(c.isa);
2808   sys::swapByteOrder(c.superclass);
2809   sys::swapByteOrder(c.cache);
2810   sys::swapByteOrder(c.vtable);
2811   sys::swapByteOrder(c.data);
2812 }
2813 
2814 inline void swapStruct(struct class_ro64_t &cro) {
2815   sys::swapByteOrder(cro.flags);
2816   sys::swapByteOrder(cro.instanceStart);
2817   sys::swapByteOrder(cro.instanceSize);
2818   sys::swapByteOrder(cro.reserved);
2819   sys::swapByteOrder(cro.ivarLayout);
2820   sys::swapByteOrder(cro.name);
2821   sys::swapByteOrder(cro.baseMethods);
2822   sys::swapByteOrder(cro.baseProtocols);
2823   sys::swapByteOrder(cro.ivars);
2824   sys::swapByteOrder(cro.weakIvarLayout);
2825   sys::swapByteOrder(cro.baseProperties);
2826 }
2827 
2828 inline void swapStruct(struct class_ro32_t &cro) {
2829   sys::swapByteOrder(cro.flags);
2830   sys::swapByteOrder(cro.instanceStart);
2831   sys::swapByteOrder(cro.instanceSize);
2832   sys::swapByteOrder(cro.ivarLayout);
2833   sys::swapByteOrder(cro.name);
2834   sys::swapByteOrder(cro.baseMethods);
2835   sys::swapByteOrder(cro.baseProtocols);
2836   sys::swapByteOrder(cro.ivars);
2837   sys::swapByteOrder(cro.weakIvarLayout);
2838   sys::swapByteOrder(cro.baseProperties);
2839 }
2840 
2841 inline void swapStruct(struct method_list64_t &ml) {
2842   sys::swapByteOrder(ml.entsize);
2843   sys::swapByteOrder(ml.count);
2844 }
2845 
2846 inline void swapStruct(struct method_list32_t &ml) {
2847   sys::swapByteOrder(ml.entsize);
2848   sys::swapByteOrder(ml.count);
2849 }
2850 
2851 inline void swapStruct(struct method64_t &m) {
2852   sys::swapByteOrder(m.name);
2853   sys::swapByteOrder(m.types);
2854   sys::swapByteOrder(m.imp);
2855 }
2856 
2857 inline void swapStruct(struct method32_t &m) {
2858   sys::swapByteOrder(m.name);
2859   sys::swapByteOrder(m.types);
2860   sys::swapByteOrder(m.imp);
2861 }
2862 
2863 inline void swapStruct(struct protocol_list64_t &pl) {
2864   sys::swapByteOrder(pl.count);
2865 }
2866 
2867 inline void swapStruct(struct protocol_list32_t &pl) {
2868   sys::swapByteOrder(pl.count);
2869 }
2870 
2871 inline void swapStruct(struct protocol64_t &p) {
2872   sys::swapByteOrder(p.isa);
2873   sys::swapByteOrder(p.name);
2874   sys::swapByteOrder(p.protocols);
2875   sys::swapByteOrder(p.instanceMethods);
2876   sys::swapByteOrder(p.classMethods);
2877   sys::swapByteOrder(p.optionalInstanceMethods);
2878   sys::swapByteOrder(p.optionalClassMethods);
2879   sys::swapByteOrder(p.instanceProperties);
2880 }
2881 
2882 inline void swapStruct(struct protocol32_t &p) {
2883   sys::swapByteOrder(p.isa);
2884   sys::swapByteOrder(p.name);
2885   sys::swapByteOrder(p.protocols);
2886   sys::swapByteOrder(p.instanceMethods);
2887   sys::swapByteOrder(p.classMethods);
2888   sys::swapByteOrder(p.optionalInstanceMethods);
2889   sys::swapByteOrder(p.optionalClassMethods);
2890   sys::swapByteOrder(p.instanceProperties);
2891 }
2892 
2893 inline void swapStruct(struct ivar_list64_t &il) {
2894   sys::swapByteOrder(il.entsize);
2895   sys::swapByteOrder(il.count);
2896 }
2897 
2898 inline void swapStruct(struct ivar_list32_t &il) {
2899   sys::swapByteOrder(il.entsize);
2900   sys::swapByteOrder(il.count);
2901 }
2902 
2903 inline void swapStruct(struct ivar64_t &i) {
2904   sys::swapByteOrder(i.offset);
2905   sys::swapByteOrder(i.name);
2906   sys::swapByteOrder(i.type);
2907   sys::swapByteOrder(i.alignment);
2908   sys::swapByteOrder(i.size);
2909 }
2910 
2911 inline void swapStruct(struct ivar32_t &i) {
2912   sys::swapByteOrder(i.offset);
2913   sys::swapByteOrder(i.name);
2914   sys::swapByteOrder(i.type);
2915   sys::swapByteOrder(i.alignment);
2916   sys::swapByteOrder(i.size);
2917 }
2918 
2919 inline void swapStruct(struct objc_property_list64 &pl) {
2920   sys::swapByteOrder(pl.entsize);
2921   sys::swapByteOrder(pl.count);
2922 }
2923 
2924 inline void swapStruct(struct objc_property_list32 &pl) {
2925   sys::swapByteOrder(pl.entsize);
2926   sys::swapByteOrder(pl.count);
2927 }
2928 
2929 inline void swapStruct(struct objc_property64 &op) {
2930   sys::swapByteOrder(op.name);
2931   sys::swapByteOrder(op.attributes);
2932 }
2933 
2934 inline void swapStruct(struct objc_property32 &op) {
2935   sys::swapByteOrder(op.name);
2936   sys::swapByteOrder(op.attributes);
2937 }
2938 
2939 inline void swapStruct(struct category64_t &c) {
2940   sys::swapByteOrder(c.name);
2941   sys::swapByteOrder(c.cls);
2942   sys::swapByteOrder(c.instanceMethods);
2943   sys::swapByteOrder(c.classMethods);
2944   sys::swapByteOrder(c.protocols);
2945   sys::swapByteOrder(c.instanceProperties);
2946 }
2947 
2948 inline void swapStruct(struct category32_t &c) {
2949   sys::swapByteOrder(c.name);
2950   sys::swapByteOrder(c.cls);
2951   sys::swapByteOrder(c.instanceMethods);
2952   sys::swapByteOrder(c.classMethods);
2953   sys::swapByteOrder(c.protocols);
2954   sys::swapByteOrder(c.instanceProperties);
2955 }
2956 
2957 inline void swapStruct(struct objc_image_info64 &o) {
2958   sys::swapByteOrder(o.version);
2959   sys::swapByteOrder(o.flags);
2960 }
2961 
2962 inline void swapStruct(struct objc_image_info32 &o) {
2963   sys::swapByteOrder(o.version);
2964   sys::swapByteOrder(o.flags);
2965 }
2966 
2967 inline void swapStruct(struct imageInfo_t &o) {
2968   sys::swapByteOrder(o.version);
2969   sys::swapByteOrder(o.flags);
2970 }
2971 
2972 inline void swapStruct(struct message_ref64 &mr) {
2973   sys::swapByteOrder(mr.imp);
2974   sys::swapByteOrder(mr.sel);
2975 }
2976 
2977 inline void swapStruct(struct message_ref32 &mr) {
2978   sys::swapByteOrder(mr.imp);
2979   sys::swapByteOrder(mr.sel);
2980 }
2981 
2982 inline void swapStruct(struct objc_module_t &module) {
2983   sys::swapByteOrder(module.version);
2984   sys::swapByteOrder(module.size);
2985   sys::swapByteOrder(module.name);
2986   sys::swapByteOrder(module.symtab);
2987 }
2988 
2989 inline void swapStruct(struct objc_symtab_t &symtab) {
2990   sys::swapByteOrder(symtab.sel_ref_cnt);
2991   sys::swapByteOrder(symtab.refs);
2992   sys::swapByteOrder(symtab.cls_def_cnt);
2993   sys::swapByteOrder(symtab.cat_def_cnt);
2994 }
2995 
2996 inline void swapStruct(struct objc_class_t &objc_class) {
2997   sys::swapByteOrder(objc_class.isa);
2998   sys::swapByteOrder(objc_class.super_class);
2999   sys::swapByteOrder(objc_class.name);
3000   sys::swapByteOrder(objc_class.version);
3001   sys::swapByteOrder(objc_class.info);
3002   sys::swapByteOrder(objc_class.instance_size);
3003   sys::swapByteOrder(objc_class.ivars);
3004   sys::swapByteOrder(objc_class.methodLists);
3005   sys::swapByteOrder(objc_class.cache);
3006   sys::swapByteOrder(objc_class.protocols);
3007 }
3008 
3009 inline void swapStruct(struct objc_category_t &objc_category) {
3010   sys::swapByteOrder(objc_category.category_name);
3011   sys::swapByteOrder(objc_category.class_name);
3012   sys::swapByteOrder(objc_category.instance_methods);
3013   sys::swapByteOrder(objc_category.class_methods);
3014   sys::swapByteOrder(objc_category.protocols);
3015 }
3016 
3017 inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3018   sys::swapByteOrder(objc_ivar_list.ivar_count);
3019 }
3020 
3021 inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3022   sys::swapByteOrder(objc_ivar.ivar_name);
3023   sys::swapByteOrder(objc_ivar.ivar_type);
3024   sys::swapByteOrder(objc_ivar.ivar_offset);
3025 }
3026 
3027 inline void swapStruct(struct objc_method_list_t &method_list) {
3028   sys::swapByteOrder(method_list.obsolete);
3029   sys::swapByteOrder(method_list.method_count);
3030 }
3031 
3032 inline void swapStruct(struct objc_method_t &method) {
3033   sys::swapByteOrder(method.method_name);
3034   sys::swapByteOrder(method.method_types);
3035   sys::swapByteOrder(method.method_imp);
3036 }
3037 
3038 inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3039   sys::swapByteOrder(protocol_list.next);
3040   sys::swapByteOrder(protocol_list.count);
3041 }
3042 
3043 inline void swapStruct(struct objc_protocol_t &protocol) {
3044   sys::swapByteOrder(protocol.isa);
3045   sys::swapByteOrder(protocol.protocol_name);
3046   sys::swapByteOrder(protocol.protocol_list);
3047   sys::swapByteOrder(protocol.instance_methods);
3048   sys::swapByteOrder(protocol.class_methods);
3049 }
3050 
3051 inline void swapStruct(struct objc_method_description_list_t &mdl) {
3052   sys::swapByteOrder(mdl.count);
3053 }
3054 
3055 inline void swapStruct(struct objc_method_description_t &md) {
3056   sys::swapByteOrder(md.name);
3057   sys::swapByteOrder(md.types);
3058 }
3059 
3060 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3061                                                  struct DisassembleInfo *info);
3062 
3063 // get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3064 // to an Objective-C class and returns the class name.  It is also passed the
3065 // address of the pointer, so when the pointer is zero as it can be in an .o
3066 // file, that is used to look for an external relocation entry with a symbol
3067 // name.
3068 static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3069                                               uint64_t ReferenceValue,
3070                                               struct DisassembleInfo *info) {
3071   const char *r;
3072   uint32_t offset, left;
3073   SectionRef S;
3074 
3075   // The pointer_value can be 0 in an object file and have a relocation
3076   // entry for the class symbol at the ReferenceValue (the address of the
3077   // pointer).
3078   if (pointer_value == 0) {
3079     r = get_pointer_64(ReferenceValue, offset, left, S, info);
3080     if (r == nullptr || left < sizeof(uint64_t))
3081       return nullptr;
3082     uint64_t n_value;
3083     const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3084     if (symbol_name == nullptr)
3085       return nullptr;
3086     const char *class_name = strrchr(symbol_name, '$');
3087     if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
3088       return class_name + 2;
3089     else
3090       return nullptr;
3091   }
3092 
3093   // The case were the pointer_value is non-zero and points to a class defined
3094   // in this Mach-O file.
3095   r = get_pointer_64(pointer_value, offset, left, S, info);
3096   if (r == nullptr || left < sizeof(struct class64_t))
3097     return nullptr;
3098   struct class64_t c;
3099   memcpy(&c, r, sizeof(struct class64_t));
3100   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3101     swapStruct(c);
3102   if (c.data == 0)
3103     return nullptr;
3104   r = get_pointer_64(c.data, offset, left, S, info);
3105   if (r == nullptr || left < sizeof(struct class_ro64_t))
3106     return nullptr;
3107   struct class_ro64_t cro;
3108   memcpy(&cro, r, sizeof(struct class_ro64_t));
3109   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3110     swapStruct(cro);
3111   if (cro.name == 0)
3112     return nullptr;
3113   const char *name = get_pointer_64(cro.name, offset, left, S, info);
3114   return name;
3115 }
3116 
3117 // get_objc2_64bit_cfstring_name is used for disassembly and is passed a
3118 // pointer to a cfstring and returns its name or nullptr.
3119 static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
3120                                                  struct DisassembleInfo *info) {
3121   const char *r, *name;
3122   uint32_t offset, left;
3123   SectionRef S;
3124   struct cfstring64_t cfs;
3125   uint64_t cfs_characters;
3126 
3127   r = get_pointer_64(ReferenceValue, offset, left, S, info);
3128   if (r == nullptr || left < sizeof(struct cfstring64_t))
3129     return nullptr;
3130   memcpy(&cfs, r, sizeof(struct cfstring64_t));
3131   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3132     swapStruct(cfs);
3133   if (cfs.characters == 0) {
3134     uint64_t n_value;
3135     const char *symbol_name = get_symbol_64(
3136         offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
3137     if (symbol_name == nullptr)
3138       return nullptr;
3139     cfs_characters = n_value;
3140   } else
3141     cfs_characters = cfs.characters;
3142   name = get_pointer_64(cfs_characters, offset, left, S, info);
3143 
3144   return name;
3145 }
3146 
3147 // get_objc2_64bit_selref() is used for disassembly and is passed a the address
3148 // of a pointer to an Objective-C selector reference when the pointer value is
3149 // zero as in a .o file and is likely to have a external relocation entry with
3150 // who's symbol's n_value is the real pointer to the selector name.  If that is
3151 // the case the real pointer to the selector name is returned else 0 is
3152 // returned
3153 static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
3154                                        struct DisassembleInfo *info) {
3155   uint32_t offset, left;
3156   SectionRef S;
3157 
3158   const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
3159   if (r == nullptr || left < sizeof(uint64_t))
3160     return 0;
3161   uint64_t n_value;
3162   const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3163   if (symbol_name == nullptr)
3164     return 0;
3165   return n_value;
3166 }
3167 
3168 static const SectionRef get_section(MachOObjectFile *O, const char *segname,
3169                                     const char *sectname) {
3170   for (const SectionRef &Section : O->sections()) {
3171     StringRef SectName;
3172     Section.getName(SectName);
3173     DataRefImpl Ref = Section.getRawDataRefImpl();
3174     StringRef SegName = O->getSectionFinalSegmentName(Ref);
3175     if (SegName == segname && SectName == sectname)
3176       return Section;
3177   }
3178   return SectionRef();
3179 }
3180 
3181 static void
3182 walk_pointer_list_64(const char *listname, const SectionRef S,
3183                      MachOObjectFile *O, struct DisassembleInfo *info,
3184                      void (*func)(uint64_t, struct DisassembleInfo *info)) {
3185   if (S == SectionRef())
3186     return;
3187 
3188   StringRef SectName;
3189   S.getName(SectName);
3190   DataRefImpl Ref = S.getRawDataRefImpl();
3191   StringRef SegName = O->getSectionFinalSegmentName(Ref);
3192   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3193 
3194   StringRef BytesStr;
3195   S.getContents(BytesStr);
3196   const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3197 
3198   for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
3199     uint32_t left = S.getSize() - i;
3200     uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
3201     uint64_t p = 0;
3202     memcpy(&p, Contents + i, size);
3203     if (i + sizeof(uint64_t) > S.getSize())
3204       outs() << listname << " list pointer extends past end of (" << SegName
3205              << "," << SectName << ") section\n";
3206     outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
3207 
3208     if (O->isLittleEndian() != sys::IsLittleEndianHost)
3209       sys::swapByteOrder(p);
3210 
3211     uint64_t n_value = 0;
3212     const char *name = get_symbol_64(i, S, info, n_value, p);
3213     if (name == nullptr)
3214       name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
3215 
3216     if (n_value != 0) {
3217       outs() << format("0x%" PRIx64, n_value);
3218       if (p != 0)
3219         outs() << " + " << format("0x%" PRIx64, p);
3220     } else
3221       outs() << format("0x%" PRIx64, p);
3222     if (name != nullptr)
3223       outs() << " " << name;
3224     outs() << "\n";
3225 
3226     p += n_value;
3227     if (func)
3228       func(p, info);
3229   }
3230 }
3231 
3232 static void
3233 walk_pointer_list_32(const char *listname, const SectionRef S,
3234                      MachOObjectFile *O, struct DisassembleInfo *info,
3235                      void (*func)(uint32_t, struct DisassembleInfo *info)) {
3236   if (S == SectionRef())
3237     return;
3238 
3239   StringRef SectName;
3240   S.getName(SectName);
3241   DataRefImpl Ref = S.getRawDataRefImpl();
3242   StringRef SegName = O->getSectionFinalSegmentName(Ref);
3243   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3244 
3245   StringRef BytesStr;
3246   S.getContents(BytesStr);
3247   const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3248 
3249   for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
3250     uint32_t left = S.getSize() - i;
3251     uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
3252     uint32_t p = 0;
3253     memcpy(&p, Contents + i, size);
3254     if (i + sizeof(uint32_t) > S.getSize())
3255       outs() << listname << " list pointer extends past end of (" << SegName
3256              << "," << SectName << ") section\n";
3257     uint32_t Address = S.getAddress() + i;
3258     outs() << format("%08" PRIx32, Address) << " ";
3259 
3260     if (O->isLittleEndian() != sys::IsLittleEndianHost)
3261       sys::swapByteOrder(p);
3262     outs() << format("0x%" PRIx32, p);
3263 
3264     const char *name = get_symbol_32(i, S, info, p);
3265     if (name != nullptr)
3266       outs() << " " << name;
3267     outs() << "\n";
3268 
3269     if (func)
3270       func(p, info);
3271   }
3272 }
3273 
3274 static void print_layout_map(const char *layout_map, uint32_t left) {
3275   if (layout_map == nullptr)
3276     return;
3277   outs() << "                layout map: ";
3278   do {
3279     outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
3280     left--;
3281     layout_map++;
3282   } while (*layout_map != '\0' && left != 0);
3283   outs() << "\n";
3284 }
3285 
3286 static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
3287   uint32_t offset, left;
3288   SectionRef S;
3289   const char *layout_map;
3290 
3291   if (p == 0)
3292     return;
3293   layout_map = get_pointer_64(p, offset, left, S, info);
3294   print_layout_map(layout_map, left);
3295 }
3296 
3297 static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
3298   uint32_t offset, left;
3299   SectionRef S;
3300   const char *layout_map;
3301 
3302   if (p == 0)
3303     return;
3304   layout_map = get_pointer_32(p, offset, left, S, info);
3305   print_layout_map(layout_map, left);
3306 }
3307 
3308 static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
3309                                   const char *indent) {
3310   struct method_list64_t ml;
3311   struct method64_t m;
3312   const char *r;
3313   uint32_t offset, xoffset, left, i;
3314   SectionRef S, xS;
3315   const char *name, *sym_name;
3316   uint64_t n_value;
3317 
3318   r = get_pointer_64(p, offset, left, S, info);
3319   if (r == nullptr)
3320     return;
3321   memset(&ml, '\0', sizeof(struct method_list64_t));
3322   if (left < sizeof(struct method_list64_t)) {
3323     memcpy(&ml, r, left);
3324     outs() << "   (method_list_t entends past the end of the section)\n";
3325   } else
3326     memcpy(&ml, r, sizeof(struct method_list64_t));
3327   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3328     swapStruct(ml);
3329   outs() << indent << "\t\t   entsize " << ml.entsize << "\n";
3330   outs() << indent << "\t\t     count " << ml.count << "\n";
3331 
3332   p += sizeof(struct method_list64_t);
3333   offset += sizeof(struct method_list64_t);
3334   for (i = 0; i < ml.count; i++) {
3335     r = get_pointer_64(p, offset, left, S, info);
3336     if (r == nullptr)
3337       return;
3338     memset(&m, '\0', sizeof(struct method64_t));
3339     if (left < sizeof(struct method64_t)) {
3340       memcpy(&m, r, left);
3341       outs() << indent << "   (method_t extends past the end of the section)\n";
3342     } else
3343       memcpy(&m, r, sizeof(struct method64_t));
3344     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3345       swapStruct(m);
3346 
3347     outs() << indent << "\t\t      name ";
3348     sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
3349                              info, n_value, m.name);
3350     if (n_value != 0) {
3351       if (info->verbose && sym_name != nullptr)
3352         outs() << sym_name;
3353       else
3354         outs() << format("0x%" PRIx64, n_value);
3355       if (m.name != 0)
3356         outs() << " + " << format("0x%" PRIx64, m.name);
3357     } else
3358       outs() << format("0x%" PRIx64, m.name);
3359     name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
3360     if (name != nullptr)
3361       outs() << format(" %.*s", left, name);
3362     outs() << "\n";
3363 
3364     outs() << indent << "\t\t     types ";
3365     sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
3366                              info, n_value, m.types);
3367     if (n_value != 0) {
3368       if (info->verbose && sym_name != nullptr)
3369         outs() << sym_name;
3370       else
3371         outs() << format("0x%" PRIx64, n_value);
3372       if (m.types != 0)
3373         outs() << " + " << format("0x%" PRIx64, m.types);
3374     } else
3375       outs() << format("0x%" PRIx64, m.types);
3376     name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
3377     if (name != nullptr)
3378       outs() << format(" %.*s", left, name);
3379     outs() << "\n";
3380 
3381     outs() << indent << "\t\t       imp ";
3382     name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
3383                          n_value, m.imp);
3384     if (info->verbose && name == nullptr) {
3385       if (n_value != 0) {
3386         outs() << format("0x%" PRIx64, n_value) << " ";
3387         if (m.imp != 0)
3388           outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
3389       } else
3390         outs() << format("0x%" PRIx64, m.imp) << " ";
3391     }
3392     if (name != nullptr)
3393       outs() << name;
3394     outs() << "\n";
3395 
3396     p += sizeof(struct method64_t);
3397     offset += sizeof(struct method64_t);
3398   }
3399 }
3400 
3401 static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
3402                                   const char *indent) {
3403   struct method_list32_t ml;
3404   struct method32_t m;
3405   const char *r, *name;
3406   uint32_t offset, xoffset, left, i;
3407   SectionRef S, xS;
3408 
3409   r = get_pointer_32(p, offset, left, S, info);
3410   if (r == nullptr)
3411     return;
3412   memset(&ml, '\0', sizeof(struct method_list32_t));
3413   if (left < sizeof(struct method_list32_t)) {
3414     memcpy(&ml, r, left);
3415     outs() << "   (method_list_t entends past the end of the section)\n";
3416   } else
3417     memcpy(&ml, r, sizeof(struct method_list32_t));
3418   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3419     swapStruct(ml);
3420   outs() << indent << "\t\t   entsize " << ml.entsize << "\n";
3421   outs() << indent << "\t\t     count " << ml.count << "\n";
3422 
3423   p += sizeof(struct method_list32_t);
3424   offset += sizeof(struct method_list32_t);
3425   for (i = 0; i < ml.count; i++) {
3426     r = get_pointer_32(p, offset, left, S, info);
3427     if (r == nullptr)
3428       return;
3429     memset(&m, '\0', sizeof(struct method32_t));
3430     if (left < sizeof(struct method32_t)) {
3431       memcpy(&ml, r, left);
3432       outs() << indent << "   (method_t entends past the end of the section)\n";
3433     } else
3434       memcpy(&m, r, sizeof(struct method32_t));
3435     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3436       swapStruct(m);
3437 
3438     outs() << indent << "\t\t      name " << format("0x%" PRIx32, m.name);
3439     name = get_pointer_32(m.name, xoffset, left, xS, info);
3440     if (name != nullptr)
3441       outs() << format(" %.*s", left, name);
3442     outs() << "\n";
3443 
3444     outs() << indent << "\t\t     types " << format("0x%" PRIx32, m.types);
3445     name = get_pointer_32(m.types, xoffset, left, xS, info);
3446     if (name != nullptr)
3447       outs() << format(" %.*s", left, name);
3448     outs() << "\n";
3449 
3450     outs() << indent << "\t\t       imp " << format("0x%" PRIx32, m.imp);
3451     name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
3452                          m.imp);
3453     if (name != nullptr)
3454       outs() << " " << name;
3455     outs() << "\n";
3456 
3457     p += sizeof(struct method32_t);
3458     offset += sizeof(struct method32_t);
3459   }
3460 }
3461 
3462 static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
3463   uint32_t offset, left, xleft;
3464   SectionRef S;
3465   struct objc_method_list_t method_list;
3466   struct objc_method_t method;
3467   const char *r, *methods, *name, *SymbolName;
3468   int32_t i;
3469 
3470   r = get_pointer_32(p, offset, left, S, info, true);
3471   if (r == nullptr)
3472     return true;
3473 
3474   outs() << "\n";
3475   if (left > sizeof(struct objc_method_list_t)) {
3476     memcpy(&method_list, r, sizeof(struct objc_method_list_t));
3477   } else {
3478     outs() << "\t\t objc_method_list extends past end of the section\n";
3479     memset(&method_list, '\0', sizeof(struct objc_method_list_t));
3480     memcpy(&method_list, r, left);
3481   }
3482   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3483     swapStruct(method_list);
3484 
3485   outs() << "\t\t         obsolete "
3486          << format("0x%08" PRIx32, method_list.obsolete) << "\n";
3487   outs() << "\t\t     method_count " << method_list.method_count << "\n";
3488 
3489   methods = r + sizeof(struct objc_method_list_t);
3490   for (i = 0; i < method_list.method_count; i++) {
3491     if ((i + 1) * sizeof(struct objc_method_t) > left) {
3492       outs() << "\t\t remaining method's extend past the of the section\n";
3493       break;
3494     }
3495     memcpy(&method, methods + i * sizeof(struct objc_method_t),
3496            sizeof(struct objc_method_t));
3497     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3498       swapStruct(method);
3499 
3500     outs() << "\t\t      method_name "
3501            << format("0x%08" PRIx32, method.method_name);
3502     if (info->verbose) {
3503       name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
3504       if (name != nullptr)
3505         outs() << format(" %.*s", xleft, name);
3506       else
3507         outs() << " (not in an __OBJC section)";
3508     }
3509     outs() << "\n";
3510 
3511     outs() << "\t\t     method_types "
3512            << format("0x%08" PRIx32, method.method_types);
3513     if (info->verbose) {
3514       name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
3515       if (name != nullptr)
3516         outs() << format(" %.*s", xleft, name);
3517       else
3518         outs() << " (not in an __OBJC section)";
3519     }
3520     outs() << "\n";
3521 
3522     outs() << "\t\t       method_imp "
3523            << format("0x%08" PRIx32, method.method_imp) << " ";
3524     if (info->verbose) {
3525       SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
3526       if (SymbolName != nullptr)
3527         outs() << SymbolName;
3528     }
3529     outs() << "\n";
3530   }
3531   return false;
3532 }
3533 
3534 static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
3535   struct protocol_list64_t pl;
3536   uint64_t q, n_value;
3537   struct protocol64_t pc;
3538   const char *r;
3539   uint32_t offset, xoffset, left, i;
3540   SectionRef S, xS;
3541   const char *name, *sym_name;
3542 
3543   r = get_pointer_64(p, offset, left, S, info);
3544   if (r == nullptr)
3545     return;
3546   memset(&pl, '\0', sizeof(struct protocol_list64_t));
3547   if (left < sizeof(struct protocol_list64_t)) {
3548     memcpy(&pl, r, left);
3549     outs() << "   (protocol_list_t entends past the end of the section)\n";
3550   } else
3551     memcpy(&pl, r, sizeof(struct protocol_list64_t));
3552   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3553     swapStruct(pl);
3554   outs() << "                      count " << pl.count << "\n";
3555 
3556   p += sizeof(struct protocol_list64_t);
3557   offset += sizeof(struct protocol_list64_t);
3558   for (i = 0; i < pl.count; i++) {
3559     r = get_pointer_64(p, offset, left, S, info);
3560     if (r == nullptr)
3561       return;
3562     q = 0;
3563     if (left < sizeof(uint64_t)) {
3564       memcpy(&q, r, left);
3565       outs() << "   (protocol_t * entends past the end of the section)\n";
3566     } else
3567       memcpy(&q, r, sizeof(uint64_t));
3568     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3569       sys::swapByteOrder(q);
3570 
3571     outs() << "\t\t      list[" << i << "] ";
3572     sym_name = get_symbol_64(offset, S, info, n_value, q);
3573     if (n_value != 0) {
3574       if (info->verbose && sym_name != nullptr)
3575         outs() << sym_name;
3576       else
3577         outs() << format("0x%" PRIx64, n_value);
3578       if (q != 0)
3579         outs() << " + " << format("0x%" PRIx64, q);
3580     } else
3581       outs() << format("0x%" PRIx64, q);
3582     outs() << " (struct protocol_t *)\n";
3583 
3584     r = get_pointer_64(q + n_value, offset, left, S, info);
3585     if (r == nullptr)
3586       return;
3587     memset(&pc, '\0', sizeof(struct protocol64_t));
3588     if (left < sizeof(struct protocol64_t)) {
3589       memcpy(&pc, r, left);
3590       outs() << "   (protocol_t entends past the end of the section)\n";
3591     } else
3592       memcpy(&pc, r, sizeof(struct protocol64_t));
3593     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3594       swapStruct(pc);
3595 
3596     outs() << "\t\t\t      isa " << format("0x%" PRIx64, pc.isa) << "\n";
3597 
3598     outs() << "\t\t\t     name ";
3599     sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
3600                              info, n_value, pc.name);
3601     if (n_value != 0) {
3602       if (info->verbose && sym_name != nullptr)
3603         outs() << sym_name;
3604       else
3605         outs() << format("0x%" PRIx64, n_value);
3606       if (pc.name != 0)
3607         outs() << " + " << format("0x%" PRIx64, pc.name);
3608     } else
3609       outs() << format("0x%" PRIx64, pc.name);
3610     name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
3611     if (name != nullptr)
3612       outs() << format(" %.*s", left, name);
3613     outs() << "\n";
3614 
3615     outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
3616 
3617     outs() << "\t\t  instanceMethods ";
3618     sym_name =
3619         get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
3620                       S, info, n_value, pc.instanceMethods);
3621     if (n_value != 0) {
3622       if (info->verbose && sym_name != nullptr)
3623         outs() << sym_name;
3624       else
3625         outs() << format("0x%" PRIx64, n_value);
3626       if (pc.instanceMethods != 0)
3627         outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
3628     } else
3629       outs() << format("0x%" PRIx64, pc.instanceMethods);
3630     outs() << " (struct method_list_t *)\n";
3631     if (pc.instanceMethods + n_value != 0)
3632       print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
3633 
3634     outs() << "\t\t     classMethods ";
3635     sym_name =
3636         get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
3637                       info, n_value, pc.classMethods);
3638     if (n_value != 0) {
3639       if (info->verbose && sym_name != nullptr)
3640         outs() << sym_name;
3641       else
3642         outs() << format("0x%" PRIx64, n_value);
3643       if (pc.classMethods != 0)
3644         outs() << " + " << format("0x%" PRIx64, pc.classMethods);
3645     } else
3646       outs() << format("0x%" PRIx64, pc.classMethods);
3647     outs() << " (struct method_list_t *)\n";
3648     if (pc.classMethods + n_value != 0)
3649       print_method_list64_t(pc.classMethods + n_value, info, "\t");
3650 
3651     outs() << "\t  optionalInstanceMethods "
3652            << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
3653     outs() << "\t     optionalClassMethods "
3654            << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
3655     outs() << "\t       instanceProperties "
3656            << format("0x%" PRIx64, pc.instanceProperties) << "\n";
3657 
3658     p += sizeof(uint64_t);
3659     offset += sizeof(uint64_t);
3660   }
3661 }
3662 
3663 static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
3664   struct protocol_list32_t pl;
3665   uint32_t q;
3666   struct protocol32_t pc;
3667   const char *r;
3668   uint32_t offset, xoffset, left, i;
3669   SectionRef S, xS;
3670   const char *name;
3671 
3672   r = get_pointer_32(p, offset, left, S, info);
3673   if (r == nullptr)
3674     return;
3675   memset(&pl, '\0', sizeof(struct protocol_list32_t));
3676   if (left < sizeof(struct protocol_list32_t)) {
3677     memcpy(&pl, r, left);
3678     outs() << "   (protocol_list_t entends past the end of the section)\n";
3679   } else
3680     memcpy(&pl, r, sizeof(struct protocol_list32_t));
3681   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3682     swapStruct(pl);
3683   outs() << "                      count " << pl.count << "\n";
3684 
3685   p += sizeof(struct protocol_list32_t);
3686   offset += sizeof(struct protocol_list32_t);
3687   for (i = 0; i < pl.count; i++) {
3688     r = get_pointer_32(p, offset, left, S, info);
3689     if (r == nullptr)
3690       return;
3691     q = 0;
3692     if (left < sizeof(uint32_t)) {
3693       memcpy(&q, r, left);
3694       outs() << "   (protocol_t * entends past the end of the section)\n";
3695     } else
3696       memcpy(&q, r, sizeof(uint32_t));
3697     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3698       sys::swapByteOrder(q);
3699     outs() << "\t\t      list[" << i << "] " << format("0x%" PRIx32, q)
3700            << " (struct protocol_t *)\n";
3701     r = get_pointer_32(q, offset, left, S, info);
3702     if (r == nullptr)
3703       return;
3704     memset(&pc, '\0', sizeof(struct protocol32_t));
3705     if (left < sizeof(struct protocol32_t)) {
3706       memcpy(&pc, r, left);
3707       outs() << "   (protocol_t entends past the end of the section)\n";
3708     } else
3709       memcpy(&pc, r, sizeof(struct protocol32_t));
3710     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3711       swapStruct(pc);
3712     outs() << "\t\t\t      isa " << format("0x%" PRIx32, pc.isa) << "\n";
3713     outs() << "\t\t\t     name " << format("0x%" PRIx32, pc.name);
3714     name = get_pointer_32(pc.name, xoffset, left, xS, info);
3715     if (name != nullptr)
3716       outs() << format(" %.*s", left, name);
3717     outs() << "\n";
3718     outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
3719     outs() << "\t\t  instanceMethods "
3720            << format("0x%" PRIx32, pc.instanceMethods)
3721            << " (struct method_list_t *)\n";
3722     if (pc.instanceMethods != 0)
3723       print_method_list32_t(pc.instanceMethods, info, "\t");
3724     outs() << "\t\t     classMethods " << format("0x%" PRIx32, pc.classMethods)
3725            << " (struct method_list_t *)\n";
3726     if (pc.classMethods != 0)
3727       print_method_list32_t(pc.classMethods, info, "\t");
3728     outs() << "\t  optionalInstanceMethods "
3729            << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
3730     outs() << "\t     optionalClassMethods "
3731            << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
3732     outs() << "\t       instanceProperties "
3733            << format("0x%" PRIx32, pc.instanceProperties) << "\n";
3734     p += sizeof(uint32_t);
3735     offset += sizeof(uint32_t);
3736   }
3737 }
3738 
3739 static void print_indent(uint32_t indent) {
3740   for (uint32_t i = 0; i < indent;) {
3741     if (indent - i >= 8) {
3742       outs() << "\t";
3743       i += 8;
3744     } else {
3745       for (uint32_t j = i; j < indent; j++)
3746         outs() << " ";
3747       return;
3748     }
3749   }
3750 }
3751 
3752 static bool print_method_description_list(uint32_t p, uint32_t indent,
3753                                           struct DisassembleInfo *info) {
3754   uint32_t offset, left, xleft;
3755   SectionRef S;
3756   struct objc_method_description_list_t mdl;
3757   struct objc_method_description_t md;
3758   const char *r, *list, *name;
3759   int32_t i;
3760 
3761   r = get_pointer_32(p, offset, left, S, info, true);
3762   if (r == nullptr)
3763     return true;
3764 
3765   outs() << "\n";
3766   if (left > sizeof(struct objc_method_description_list_t)) {
3767     memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
3768   } else {
3769     print_indent(indent);
3770     outs() << " objc_method_description_list extends past end of the section\n";
3771     memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
3772     memcpy(&mdl, r, left);
3773   }
3774   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3775     swapStruct(mdl);
3776 
3777   print_indent(indent);
3778   outs() << "        count " << mdl.count << "\n";
3779 
3780   list = r + sizeof(struct objc_method_description_list_t);
3781   for (i = 0; i < mdl.count; i++) {
3782     if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
3783       print_indent(indent);
3784       outs() << " remaining list entries extend past the of the section\n";
3785       break;
3786     }
3787     print_indent(indent);
3788     outs() << "        list[" << i << "]\n";
3789     memcpy(&md, list + i * sizeof(struct objc_method_description_t),
3790            sizeof(struct objc_method_description_t));
3791     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3792       swapStruct(md);
3793 
3794     print_indent(indent);
3795     outs() << "             name " << format("0x%08" PRIx32, md.name);
3796     if (info->verbose) {
3797       name = get_pointer_32(md.name, offset, xleft, S, info, true);
3798       if (name != nullptr)
3799         outs() << format(" %.*s", xleft, name);
3800       else
3801         outs() << " (not in an __OBJC section)";
3802     }
3803     outs() << "\n";
3804 
3805     print_indent(indent);
3806     outs() << "            types " << format("0x%08" PRIx32, md.types);
3807     if (info->verbose) {
3808       name = get_pointer_32(md.types, offset, xleft, S, info, true);
3809       if (name != nullptr)
3810         outs() << format(" %.*s", xleft, name);
3811       else
3812         outs() << " (not in an __OBJC section)";
3813     }
3814     outs() << "\n";
3815   }
3816   return false;
3817 }
3818 
3819 static bool print_protocol_list(uint32_t p, uint32_t indent,
3820                                 struct DisassembleInfo *info);
3821 
3822 static bool print_protocol(uint32_t p, uint32_t indent,
3823                            struct DisassembleInfo *info) {
3824   uint32_t offset, left;
3825   SectionRef S;
3826   struct objc_protocol_t protocol;
3827   const char *r, *name;
3828 
3829   r = get_pointer_32(p, offset, left, S, info, true);
3830   if (r == nullptr)
3831     return true;
3832 
3833   outs() << "\n";
3834   if (left >= sizeof(struct objc_protocol_t)) {
3835     memcpy(&protocol, r, sizeof(struct objc_protocol_t));
3836   } else {
3837     print_indent(indent);
3838     outs() << "            Protocol extends past end of the section\n";
3839     memset(&protocol, '\0', sizeof(struct objc_protocol_t));
3840     memcpy(&protocol, r, left);
3841   }
3842   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3843     swapStruct(protocol);
3844 
3845   print_indent(indent);
3846   outs() << "              isa " << format("0x%08" PRIx32, protocol.isa)
3847          << "\n";
3848 
3849   print_indent(indent);
3850   outs() << "    protocol_name "
3851          << format("0x%08" PRIx32, protocol.protocol_name);
3852   if (info->verbose) {
3853     name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
3854     if (name != nullptr)
3855       outs() << format(" %.*s", left, name);
3856     else
3857       outs() << " (not in an __OBJC section)";
3858   }
3859   outs() << "\n";
3860 
3861   print_indent(indent);
3862   outs() << "    protocol_list "
3863          << format("0x%08" PRIx32, protocol.protocol_list);
3864   if (print_protocol_list(protocol.protocol_list, indent + 4, info))
3865     outs() << " (not in an __OBJC section)\n";
3866 
3867   print_indent(indent);
3868   outs() << " instance_methods "
3869          << format("0x%08" PRIx32, protocol.instance_methods);
3870   if (print_method_description_list(protocol.instance_methods, indent, info))
3871     outs() << " (not in an __OBJC section)\n";
3872 
3873   print_indent(indent);
3874   outs() << "    class_methods "
3875          << format("0x%08" PRIx32, protocol.class_methods);
3876   if (print_method_description_list(protocol.class_methods, indent, info))
3877     outs() << " (not in an __OBJC section)\n";
3878 
3879   return false;
3880 }
3881 
3882 static bool print_protocol_list(uint32_t p, uint32_t indent,
3883                                 struct DisassembleInfo *info) {
3884   uint32_t offset, left, l;
3885   SectionRef S;
3886   struct objc_protocol_list_t protocol_list;
3887   const char *r, *list;
3888   int32_t i;
3889 
3890   r = get_pointer_32(p, offset, left, S, info, true);
3891   if (r == nullptr)
3892     return true;
3893 
3894   outs() << "\n";
3895   if (left > sizeof(struct objc_protocol_list_t)) {
3896     memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
3897   } else {
3898     outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
3899     memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
3900     memcpy(&protocol_list, r, left);
3901   }
3902   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3903     swapStruct(protocol_list);
3904 
3905   print_indent(indent);
3906   outs() << "         next " << format("0x%08" PRIx32, protocol_list.next)
3907          << "\n";
3908   print_indent(indent);
3909   outs() << "        count " << protocol_list.count << "\n";
3910 
3911   list = r + sizeof(struct objc_protocol_list_t);
3912   for (i = 0; i < protocol_list.count; i++) {
3913     if ((i + 1) * sizeof(uint32_t) > left) {
3914       outs() << "\t\t remaining list entries extend past the of the section\n";
3915       break;
3916     }
3917     memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
3918     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3919       sys::swapByteOrder(l);
3920 
3921     print_indent(indent);
3922     outs() << "      list[" << i << "] " << format("0x%08" PRIx32, l);
3923     if (print_protocol(l, indent, info))
3924       outs() << "(not in an __OBJC section)\n";
3925   }
3926   return false;
3927 }
3928 
3929 static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
3930   struct ivar_list64_t il;
3931   struct ivar64_t i;
3932   const char *r;
3933   uint32_t offset, xoffset, left, j;
3934   SectionRef S, xS;
3935   const char *name, *sym_name, *ivar_offset_p;
3936   uint64_t ivar_offset, n_value;
3937 
3938   r = get_pointer_64(p, offset, left, S, info);
3939   if (r == nullptr)
3940     return;
3941   memset(&il, '\0', sizeof(struct ivar_list64_t));
3942   if (left < sizeof(struct ivar_list64_t)) {
3943     memcpy(&il, r, left);
3944     outs() << "   (ivar_list_t entends past the end of the section)\n";
3945   } else
3946     memcpy(&il, r, sizeof(struct ivar_list64_t));
3947   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3948     swapStruct(il);
3949   outs() << "                    entsize " << il.entsize << "\n";
3950   outs() << "                      count " << il.count << "\n";
3951 
3952   p += sizeof(struct ivar_list64_t);
3953   offset += sizeof(struct ivar_list64_t);
3954   for (j = 0; j < il.count; j++) {
3955     r = get_pointer_64(p, offset, left, S, info);
3956     if (r == nullptr)
3957       return;
3958     memset(&i, '\0', sizeof(struct ivar64_t));
3959     if (left < sizeof(struct ivar64_t)) {
3960       memcpy(&i, r, left);
3961       outs() << "   (ivar_t entends past the end of the section)\n";
3962     } else
3963       memcpy(&i, r, sizeof(struct ivar64_t));
3964     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3965       swapStruct(i);
3966 
3967     outs() << "\t\t\t   offset ";
3968     sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
3969                              info, n_value, i.offset);
3970     if (n_value != 0) {
3971       if (info->verbose && sym_name != nullptr)
3972         outs() << sym_name;
3973       else
3974         outs() << format("0x%" PRIx64, n_value);
3975       if (i.offset != 0)
3976         outs() << " + " << format("0x%" PRIx64, i.offset);
3977     } else
3978       outs() << format("0x%" PRIx64, i.offset);
3979     ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
3980     if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
3981       memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
3982       if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3983         sys::swapByteOrder(ivar_offset);
3984       outs() << " " << ivar_offset << "\n";
3985     } else
3986       outs() << "\n";
3987 
3988     outs() << "\t\t\t     name ";
3989     sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
3990                              n_value, i.name);
3991     if (n_value != 0) {
3992       if (info->verbose && sym_name != nullptr)
3993         outs() << sym_name;
3994       else
3995         outs() << format("0x%" PRIx64, n_value);
3996       if (i.name != 0)
3997         outs() << " + " << format("0x%" PRIx64, i.name);
3998     } else
3999       outs() << format("0x%" PRIx64, i.name);
4000     name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
4001     if (name != nullptr)
4002       outs() << format(" %.*s", left, name);
4003     outs() << "\n";
4004 
4005     outs() << "\t\t\t     type ";
4006     sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
4007                              n_value, i.name);
4008     name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
4009     if (n_value != 0) {
4010       if (info->verbose && sym_name != nullptr)
4011         outs() << sym_name;
4012       else
4013         outs() << format("0x%" PRIx64, n_value);
4014       if (i.type != 0)
4015         outs() << " + " << format("0x%" PRIx64, i.type);
4016     } else
4017       outs() << format("0x%" PRIx64, i.type);
4018     if (name != nullptr)
4019       outs() << format(" %.*s", left, name);
4020     outs() << "\n";
4021 
4022     outs() << "\t\t\talignment " << i.alignment << "\n";
4023     outs() << "\t\t\t     size " << i.size << "\n";
4024 
4025     p += sizeof(struct ivar64_t);
4026     offset += sizeof(struct ivar64_t);
4027   }
4028 }
4029 
4030 static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4031   struct ivar_list32_t il;
4032   struct ivar32_t i;
4033   const char *r;
4034   uint32_t offset, xoffset, left, j;
4035   SectionRef S, xS;
4036   const char *name, *ivar_offset_p;
4037   uint32_t ivar_offset;
4038 
4039   r = get_pointer_32(p, offset, left, S, info);
4040   if (r == nullptr)
4041     return;
4042   memset(&il, '\0', sizeof(struct ivar_list32_t));
4043   if (left < sizeof(struct ivar_list32_t)) {
4044     memcpy(&il, r, left);
4045     outs() << "   (ivar_list_t entends past the end of the section)\n";
4046   } else
4047     memcpy(&il, r, sizeof(struct ivar_list32_t));
4048   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4049     swapStruct(il);
4050   outs() << "                    entsize " << il.entsize << "\n";
4051   outs() << "                      count " << il.count << "\n";
4052 
4053   p += sizeof(struct ivar_list32_t);
4054   offset += sizeof(struct ivar_list32_t);
4055   for (j = 0; j < il.count; j++) {
4056     r = get_pointer_32(p, offset, left, S, info);
4057     if (r == nullptr)
4058       return;
4059     memset(&i, '\0', sizeof(struct ivar32_t));
4060     if (left < sizeof(struct ivar32_t)) {
4061       memcpy(&i, r, left);
4062       outs() << "   (ivar_t entends past the end of the section)\n";
4063     } else
4064       memcpy(&i, r, sizeof(struct ivar32_t));
4065     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4066       swapStruct(i);
4067 
4068     outs() << "\t\t\t   offset " << format("0x%" PRIx32, i.offset);
4069     ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4070     if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4071       memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4072       if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4073         sys::swapByteOrder(ivar_offset);
4074       outs() << " " << ivar_offset << "\n";
4075     } else
4076       outs() << "\n";
4077 
4078     outs() << "\t\t\t     name " << format("0x%" PRIx32, i.name);
4079     name = get_pointer_32(i.name, xoffset, left, xS, info);
4080     if (name != nullptr)
4081       outs() << format(" %.*s", left, name);
4082     outs() << "\n";
4083 
4084     outs() << "\t\t\t     type " << format("0x%" PRIx32, i.type);
4085     name = get_pointer_32(i.type, xoffset, left, xS, info);
4086     if (name != nullptr)
4087       outs() << format(" %.*s", left, name);
4088     outs() << "\n";
4089 
4090     outs() << "\t\t\talignment " << i.alignment << "\n";
4091     outs() << "\t\t\t     size " << i.size << "\n";
4092 
4093     p += sizeof(struct ivar32_t);
4094     offset += sizeof(struct ivar32_t);
4095   }
4096 }
4097 
4098 static void print_objc_property_list64(uint64_t p,
4099                                        struct DisassembleInfo *info) {
4100   struct objc_property_list64 opl;
4101   struct objc_property64 op;
4102   const char *r;
4103   uint32_t offset, xoffset, left, j;
4104   SectionRef S, xS;
4105   const char *name, *sym_name;
4106   uint64_t n_value;
4107 
4108   r = get_pointer_64(p, offset, left, S, info);
4109   if (r == nullptr)
4110     return;
4111   memset(&opl, '\0', sizeof(struct objc_property_list64));
4112   if (left < sizeof(struct objc_property_list64)) {
4113     memcpy(&opl, r, left);
4114     outs() << "   (objc_property_list entends past the end of the section)\n";
4115   } else
4116     memcpy(&opl, r, sizeof(struct objc_property_list64));
4117   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4118     swapStruct(opl);
4119   outs() << "                    entsize " << opl.entsize << "\n";
4120   outs() << "                      count " << opl.count << "\n";
4121 
4122   p += sizeof(struct objc_property_list64);
4123   offset += sizeof(struct objc_property_list64);
4124   for (j = 0; j < opl.count; j++) {
4125     r = get_pointer_64(p, offset, left, S, info);
4126     if (r == nullptr)
4127       return;
4128     memset(&op, '\0', sizeof(struct objc_property64));
4129     if (left < sizeof(struct objc_property64)) {
4130       memcpy(&op, r, left);
4131       outs() << "   (objc_property entends past the end of the section)\n";
4132     } else
4133       memcpy(&op, r, sizeof(struct objc_property64));
4134     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4135       swapStruct(op);
4136 
4137     outs() << "\t\t\t     name ";
4138     sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
4139                              info, n_value, op.name);
4140     if (n_value != 0) {
4141       if (info->verbose && sym_name != nullptr)
4142         outs() << sym_name;
4143       else
4144         outs() << format("0x%" PRIx64, n_value);
4145       if (op.name != 0)
4146         outs() << " + " << format("0x%" PRIx64, op.name);
4147     } else
4148       outs() << format("0x%" PRIx64, op.name);
4149     name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
4150     if (name != nullptr)
4151       outs() << format(" %.*s", left, name);
4152     outs() << "\n";
4153 
4154     outs() << "\t\t\tattributes ";
4155     sym_name =
4156         get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
4157                       info, n_value, op.attributes);
4158     if (n_value != 0) {
4159       if (info->verbose && sym_name != nullptr)
4160         outs() << sym_name;
4161       else
4162         outs() << format("0x%" PRIx64, n_value);
4163       if (op.attributes != 0)
4164         outs() << " + " << format("0x%" PRIx64, op.attributes);
4165     } else
4166       outs() << format("0x%" PRIx64, op.attributes);
4167     name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
4168     if (name != nullptr)
4169       outs() << format(" %.*s", left, name);
4170     outs() << "\n";
4171 
4172     p += sizeof(struct objc_property64);
4173     offset += sizeof(struct objc_property64);
4174   }
4175 }
4176 
4177 static void print_objc_property_list32(uint32_t p,
4178                                        struct DisassembleInfo *info) {
4179   struct objc_property_list32 opl;
4180   struct objc_property32 op;
4181   const char *r;
4182   uint32_t offset, xoffset, left, j;
4183   SectionRef S, xS;
4184   const char *name;
4185 
4186   r = get_pointer_32(p, offset, left, S, info);
4187   if (r == nullptr)
4188     return;
4189   memset(&opl, '\0', sizeof(struct objc_property_list32));
4190   if (left < sizeof(struct objc_property_list32)) {
4191     memcpy(&opl, r, left);
4192     outs() << "   (objc_property_list entends past the end of the section)\n";
4193   } else
4194     memcpy(&opl, r, sizeof(struct objc_property_list32));
4195   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4196     swapStruct(opl);
4197   outs() << "                    entsize " << opl.entsize << "\n";
4198   outs() << "                      count " << opl.count << "\n";
4199 
4200   p += sizeof(struct objc_property_list32);
4201   offset += sizeof(struct objc_property_list32);
4202   for (j = 0; j < opl.count; j++) {
4203     r = get_pointer_32(p, offset, left, S, info);
4204     if (r == nullptr)
4205       return;
4206     memset(&op, '\0', sizeof(struct objc_property32));
4207     if (left < sizeof(struct objc_property32)) {
4208       memcpy(&op, r, left);
4209       outs() << "   (objc_property entends past the end of the section)\n";
4210     } else
4211       memcpy(&op, r, sizeof(struct objc_property32));
4212     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4213       swapStruct(op);
4214 
4215     outs() << "\t\t\t     name " << format("0x%" PRIx32, op.name);
4216     name = get_pointer_32(op.name, xoffset, left, xS, info);
4217     if (name != nullptr)
4218       outs() << format(" %.*s", left, name);
4219     outs() << "\n";
4220 
4221     outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
4222     name = get_pointer_32(op.attributes, xoffset, left, xS, info);
4223     if (name != nullptr)
4224       outs() << format(" %.*s", left, name);
4225     outs() << "\n";
4226 
4227     p += sizeof(struct objc_property32);
4228     offset += sizeof(struct objc_property32);
4229   }
4230 }
4231 
4232 static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
4233                                bool &is_meta_class) {
4234   struct class_ro64_t cro;
4235   const char *r;
4236   uint32_t offset, xoffset, left;
4237   SectionRef S, xS;
4238   const char *name, *sym_name;
4239   uint64_t n_value;
4240 
4241   r = get_pointer_64(p, offset, left, S, info);
4242   if (r == nullptr || left < sizeof(struct class_ro64_t))
4243     return false;
4244   memset(&cro, '\0', sizeof(struct class_ro64_t));
4245   if (left < sizeof(struct class_ro64_t)) {
4246     memcpy(&cro, r, left);
4247     outs() << "   (class_ro_t entends past the end of the section)\n";
4248   } else
4249     memcpy(&cro, r, sizeof(struct class_ro64_t));
4250   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4251     swapStruct(cro);
4252   outs() << "                    flags " << format("0x%" PRIx32, cro.flags);
4253   if (cro.flags & RO_META)
4254     outs() << " RO_META";
4255   if (cro.flags & RO_ROOT)
4256     outs() << " RO_ROOT";
4257   if (cro.flags & RO_HAS_CXX_STRUCTORS)
4258     outs() << " RO_HAS_CXX_STRUCTORS";
4259   outs() << "\n";
4260   outs() << "            instanceStart " << cro.instanceStart << "\n";
4261   outs() << "             instanceSize " << cro.instanceSize << "\n";
4262   outs() << "                 reserved " << format("0x%" PRIx32, cro.reserved)
4263          << "\n";
4264   outs() << "               ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
4265          << "\n";
4266   print_layout_map64(cro.ivarLayout, info);
4267 
4268   outs() << "                     name ";
4269   sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
4270                            info, n_value, cro.name);
4271   if (n_value != 0) {
4272     if (info->verbose && sym_name != nullptr)
4273       outs() << sym_name;
4274     else
4275       outs() << format("0x%" PRIx64, n_value);
4276     if (cro.name != 0)
4277       outs() << " + " << format("0x%" PRIx64, cro.name);
4278   } else
4279     outs() << format("0x%" PRIx64, cro.name);
4280   name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
4281   if (name != nullptr)
4282     outs() << format(" %.*s", left, name);
4283   outs() << "\n";
4284 
4285   outs() << "              baseMethods ";
4286   sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
4287                            S, info, n_value, cro.baseMethods);
4288   if (n_value != 0) {
4289     if (info->verbose && sym_name != nullptr)
4290       outs() << sym_name;
4291     else
4292       outs() << format("0x%" PRIx64, n_value);
4293     if (cro.baseMethods != 0)
4294       outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
4295   } else
4296     outs() << format("0x%" PRIx64, cro.baseMethods);
4297   outs() << " (struct method_list_t *)\n";
4298   if (cro.baseMethods + n_value != 0)
4299     print_method_list64_t(cro.baseMethods + n_value, info, "");
4300 
4301   outs() << "            baseProtocols ";
4302   sym_name =
4303       get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
4304                     info, n_value, cro.baseProtocols);
4305   if (n_value != 0) {
4306     if (info->verbose && sym_name != nullptr)
4307       outs() << sym_name;
4308     else
4309       outs() << format("0x%" PRIx64, n_value);
4310     if (cro.baseProtocols != 0)
4311       outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
4312   } else
4313     outs() << format("0x%" PRIx64, cro.baseProtocols);
4314   outs() << "\n";
4315   if (cro.baseProtocols + n_value != 0)
4316     print_protocol_list64_t(cro.baseProtocols + n_value, info);
4317 
4318   outs() << "                    ivars ";
4319   sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
4320                            info, n_value, cro.ivars);
4321   if (n_value != 0) {
4322     if (info->verbose && sym_name != nullptr)
4323       outs() << sym_name;
4324     else
4325       outs() << format("0x%" PRIx64, n_value);
4326     if (cro.ivars != 0)
4327       outs() << " + " << format("0x%" PRIx64, cro.ivars);
4328   } else
4329     outs() << format("0x%" PRIx64, cro.ivars);
4330   outs() << "\n";
4331   if (cro.ivars + n_value != 0)
4332     print_ivar_list64_t(cro.ivars + n_value, info);
4333 
4334   outs() << "           weakIvarLayout ";
4335   sym_name =
4336       get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
4337                     info, n_value, cro.weakIvarLayout);
4338   if (n_value != 0) {
4339     if (info->verbose && sym_name != nullptr)
4340       outs() << sym_name;
4341     else
4342       outs() << format("0x%" PRIx64, n_value);
4343     if (cro.weakIvarLayout != 0)
4344       outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
4345   } else
4346     outs() << format("0x%" PRIx64, cro.weakIvarLayout);
4347   outs() << "\n";
4348   print_layout_map64(cro.weakIvarLayout + n_value, info);
4349 
4350   outs() << "           baseProperties ";
4351   sym_name =
4352       get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
4353                     info, n_value, cro.baseProperties);
4354   if (n_value != 0) {
4355     if (info->verbose && sym_name != nullptr)
4356       outs() << sym_name;
4357     else
4358       outs() << format("0x%" PRIx64, n_value);
4359     if (cro.baseProperties != 0)
4360       outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
4361   } else
4362     outs() << format("0x%" PRIx64, cro.baseProperties);
4363   outs() << "\n";
4364   if (cro.baseProperties + n_value != 0)
4365     print_objc_property_list64(cro.baseProperties + n_value, info);
4366 
4367   is_meta_class = (cro.flags & RO_META) != 0;
4368   return true;
4369 }
4370 
4371 static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
4372                                bool &is_meta_class) {
4373   struct class_ro32_t cro;
4374   const char *r;
4375   uint32_t offset, xoffset, left;
4376   SectionRef S, xS;
4377   const char *name;
4378 
4379   r = get_pointer_32(p, offset, left, S, info);
4380   if (r == nullptr)
4381     return false;
4382   memset(&cro, '\0', sizeof(struct class_ro32_t));
4383   if (left < sizeof(struct class_ro32_t)) {
4384     memcpy(&cro, r, left);
4385     outs() << "   (class_ro_t entends past the end of the section)\n";
4386   } else
4387     memcpy(&cro, r, sizeof(struct class_ro32_t));
4388   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4389     swapStruct(cro);
4390   outs() << "                    flags " << format("0x%" PRIx32, cro.flags);
4391   if (cro.flags & RO_META)
4392     outs() << " RO_META";
4393   if (cro.flags & RO_ROOT)
4394     outs() << " RO_ROOT";
4395   if (cro.flags & RO_HAS_CXX_STRUCTORS)
4396     outs() << " RO_HAS_CXX_STRUCTORS";
4397   outs() << "\n";
4398   outs() << "            instanceStart " << cro.instanceStart << "\n";
4399   outs() << "             instanceSize " << cro.instanceSize << "\n";
4400   outs() << "               ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
4401          << "\n";
4402   print_layout_map32(cro.ivarLayout, info);
4403 
4404   outs() << "                     name " << format("0x%" PRIx32, cro.name);
4405   name = get_pointer_32(cro.name, xoffset, left, xS, info);
4406   if (name != nullptr)
4407     outs() << format(" %.*s", left, name);
4408   outs() << "\n";
4409 
4410   outs() << "              baseMethods "
4411          << format("0x%" PRIx32, cro.baseMethods)
4412          << " (struct method_list_t *)\n";
4413   if (cro.baseMethods != 0)
4414     print_method_list32_t(cro.baseMethods, info, "");
4415 
4416   outs() << "            baseProtocols "
4417          << format("0x%" PRIx32, cro.baseProtocols) << "\n";
4418   if (cro.baseProtocols != 0)
4419     print_protocol_list32_t(cro.baseProtocols, info);
4420   outs() << "                    ivars " << format("0x%" PRIx32, cro.ivars)
4421          << "\n";
4422   if (cro.ivars != 0)
4423     print_ivar_list32_t(cro.ivars, info);
4424   outs() << "           weakIvarLayout "
4425          << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
4426   print_layout_map32(cro.weakIvarLayout, info);
4427   outs() << "           baseProperties "
4428          << format("0x%" PRIx32, cro.baseProperties) << "\n";
4429   if (cro.baseProperties != 0)
4430     print_objc_property_list32(cro.baseProperties, info);
4431   is_meta_class = (cro.flags & RO_META) != 0;
4432   return true;
4433 }
4434 
4435 static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
4436   struct class64_t c;
4437   const char *r;
4438   uint32_t offset, left;
4439   SectionRef S;
4440   const char *name;
4441   uint64_t isa_n_value, n_value;
4442 
4443   r = get_pointer_64(p, offset, left, S, info);
4444   if (r == nullptr || left < sizeof(struct class64_t))
4445     return;
4446   memset(&c, '\0', sizeof(struct class64_t));
4447   if (left < sizeof(struct class64_t)) {
4448     memcpy(&c, r, left);
4449     outs() << "   (class_t entends past the end of the section)\n";
4450   } else
4451     memcpy(&c, r, sizeof(struct class64_t));
4452   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4453     swapStruct(c);
4454 
4455   outs() << "           isa " << format("0x%" PRIx64, c.isa);
4456   name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
4457                        isa_n_value, c.isa);
4458   if (name != nullptr)
4459     outs() << " " << name;
4460   outs() << "\n";
4461 
4462   outs() << "    superclass " << format("0x%" PRIx64, c.superclass);
4463   name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
4464                        n_value, c.superclass);
4465   if (name != nullptr)
4466     outs() << " " << name;
4467   outs() << "\n";
4468 
4469   outs() << "         cache " << format("0x%" PRIx64, c.cache);
4470   name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
4471                        n_value, c.cache);
4472   if (name != nullptr)
4473     outs() << " " << name;
4474   outs() << "\n";
4475 
4476   outs() << "        vtable " << format("0x%" PRIx64, c.vtable);
4477   name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
4478                        n_value, c.vtable);
4479   if (name != nullptr)
4480     outs() << " " << name;
4481   outs() << "\n";
4482 
4483   name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
4484                        n_value, c.data);
4485   outs() << "          data ";
4486   if (n_value != 0) {
4487     if (info->verbose && name != nullptr)
4488       outs() << name;
4489     else
4490       outs() << format("0x%" PRIx64, n_value);
4491     if (c.data != 0)
4492       outs() << " + " << format("0x%" PRIx64, c.data);
4493   } else
4494     outs() << format("0x%" PRIx64, c.data);
4495   outs() << " (struct class_ro_t *)";
4496 
4497   // This is a Swift class if some of the low bits of the pointer are set.
4498   if ((c.data + n_value) & 0x7)
4499     outs() << " Swift class";
4500   outs() << "\n";
4501   bool is_meta_class;
4502   if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
4503     return;
4504 
4505   if (!is_meta_class &&
4506       c.isa + isa_n_value != p &&
4507       c.isa + isa_n_value != 0 &&
4508       info->depth < 100) {
4509       info->depth++;
4510       outs() << "Meta Class\n";
4511       print_class64_t(c.isa + isa_n_value, info);
4512   }
4513 }
4514 
4515 static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
4516   struct class32_t c;
4517   const char *r;
4518   uint32_t offset, left;
4519   SectionRef S;
4520   const char *name;
4521 
4522   r = get_pointer_32(p, offset, left, S, info);
4523   if (r == nullptr)
4524     return;
4525   memset(&c, '\0', sizeof(struct class32_t));
4526   if (left < sizeof(struct class32_t)) {
4527     memcpy(&c, r, left);
4528     outs() << "   (class_t entends past the end of the section)\n";
4529   } else
4530     memcpy(&c, r, sizeof(struct class32_t));
4531   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4532     swapStruct(c);
4533 
4534   outs() << "           isa " << format("0x%" PRIx32, c.isa);
4535   name =
4536       get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
4537   if (name != nullptr)
4538     outs() << " " << name;
4539   outs() << "\n";
4540 
4541   outs() << "    superclass " << format("0x%" PRIx32, c.superclass);
4542   name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
4543                        c.superclass);
4544   if (name != nullptr)
4545     outs() << " " << name;
4546   outs() << "\n";
4547 
4548   outs() << "         cache " << format("0x%" PRIx32, c.cache);
4549   name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
4550                        c.cache);
4551   if (name != nullptr)
4552     outs() << " " << name;
4553   outs() << "\n";
4554 
4555   outs() << "        vtable " << format("0x%" PRIx32, c.vtable);
4556   name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
4557                        c.vtable);
4558   if (name != nullptr)
4559     outs() << " " << name;
4560   outs() << "\n";
4561 
4562   name =
4563       get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
4564   outs() << "          data " << format("0x%" PRIx32, c.data)
4565          << " (struct class_ro_t *)";
4566 
4567   // This is a Swift class if some of the low bits of the pointer are set.
4568   if (c.data & 0x3)
4569     outs() << " Swift class";
4570   outs() << "\n";
4571   bool is_meta_class;
4572   if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
4573     return;
4574 
4575   if (!is_meta_class) {
4576     outs() << "Meta Class\n";
4577     print_class32_t(c.isa, info);
4578   }
4579 }
4580 
4581 static void print_objc_class_t(struct objc_class_t *objc_class,
4582                                struct DisassembleInfo *info) {
4583   uint32_t offset, left, xleft;
4584   const char *name, *p, *ivar_list;
4585   SectionRef S;
4586   int32_t i;
4587   struct objc_ivar_list_t objc_ivar_list;
4588   struct objc_ivar_t ivar;
4589 
4590   outs() << "\t\t      isa " << format("0x%08" PRIx32, objc_class->isa);
4591   if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
4592     name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
4593     if (name != nullptr)
4594       outs() << format(" %.*s", left, name);
4595     else
4596       outs() << " (not in an __OBJC section)";
4597   }
4598   outs() << "\n";
4599 
4600   outs() << "\t      super_class "
4601          << format("0x%08" PRIx32, objc_class->super_class);
4602   if (info->verbose) {
4603     name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
4604     if (name != nullptr)
4605       outs() << format(" %.*s", left, name);
4606     else
4607       outs() << " (not in an __OBJC section)";
4608   }
4609   outs() << "\n";
4610 
4611   outs() << "\t\t     name " << format("0x%08" PRIx32, objc_class->name);
4612   if (info->verbose) {
4613     name = get_pointer_32(objc_class->name, offset, left, S, info, true);
4614     if (name != nullptr)
4615       outs() << format(" %.*s", left, name);
4616     else
4617       outs() << " (not in an __OBJC section)";
4618   }
4619   outs() << "\n";
4620 
4621   outs() << "\t\t  version " << format("0x%08" PRIx32, objc_class->version)
4622          << "\n";
4623 
4624   outs() << "\t\t     info " << format("0x%08" PRIx32, objc_class->info);
4625   if (info->verbose) {
4626     if (CLS_GETINFO(objc_class, CLS_CLASS))
4627       outs() << " CLS_CLASS";
4628     else if (CLS_GETINFO(objc_class, CLS_META))
4629       outs() << " CLS_META";
4630   }
4631   outs() << "\n";
4632 
4633   outs() << "\t    instance_size "
4634          << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
4635 
4636   p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
4637   outs() << "\t\t    ivars " << format("0x%08" PRIx32, objc_class->ivars);
4638   if (p != nullptr) {
4639     if (left > sizeof(struct objc_ivar_list_t)) {
4640       outs() << "\n";
4641       memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
4642     } else {
4643       outs() << " (entends past the end of the section)\n";
4644       memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
4645       memcpy(&objc_ivar_list, p, left);
4646     }
4647     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4648       swapStruct(objc_ivar_list);
4649     outs() << "\t\t       ivar_count " << objc_ivar_list.ivar_count << "\n";
4650     ivar_list = p + sizeof(struct objc_ivar_list_t);
4651     for (i = 0; i < objc_ivar_list.ivar_count; i++) {
4652       if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
4653         outs() << "\t\t remaining ivar's extend past the of the section\n";
4654         break;
4655       }
4656       memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
4657              sizeof(struct objc_ivar_t));
4658       if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4659         swapStruct(ivar);
4660 
4661       outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
4662       if (info->verbose) {
4663         name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
4664         if (name != nullptr)
4665           outs() << format(" %.*s", xleft, name);
4666         else
4667           outs() << " (not in an __OBJC section)";
4668       }
4669       outs() << "\n";
4670 
4671       outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
4672       if (info->verbose) {
4673         name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
4674         if (name != nullptr)
4675           outs() << format(" %.*s", xleft, name);
4676         else
4677           outs() << " (not in an __OBJC section)";
4678       }
4679       outs() << "\n";
4680 
4681       outs() << "\t\t      ivar_offset "
4682              << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
4683     }
4684   } else {
4685     outs() << " (not in an __OBJC section)\n";
4686   }
4687 
4688   outs() << "\t\t  methods " << format("0x%08" PRIx32, objc_class->methodLists);
4689   if (print_method_list(objc_class->methodLists, info))
4690     outs() << " (not in an __OBJC section)\n";
4691 
4692   outs() << "\t\t    cache " << format("0x%08" PRIx32, objc_class->cache)
4693          << "\n";
4694 
4695   outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
4696   if (print_protocol_list(objc_class->protocols, 16, info))
4697     outs() << " (not in an __OBJC section)\n";
4698 }
4699 
4700 static void print_objc_objc_category_t(struct objc_category_t *objc_category,
4701                                        struct DisassembleInfo *info) {
4702   uint32_t offset, left;
4703   const char *name;
4704   SectionRef S;
4705 
4706   outs() << "\t       category name "
4707          << format("0x%08" PRIx32, objc_category->category_name);
4708   if (info->verbose) {
4709     name = get_pointer_32(objc_category->category_name, offset, left, S, info,
4710                           true);
4711     if (name != nullptr)
4712       outs() << format(" %.*s", left, name);
4713     else
4714       outs() << " (not in an __OBJC section)";
4715   }
4716   outs() << "\n";
4717 
4718   outs() << "\t\t  class name "
4719          << format("0x%08" PRIx32, objc_category->class_name);
4720   if (info->verbose) {
4721     name =
4722         get_pointer_32(objc_category->class_name, offset, left, S, info, true);
4723     if (name != nullptr)
4724       outs() << format(" %.*s", left, name);
4725     else
4726       outs() << " (not in an __OBJC section)";
4727   }
4728   outs() << "\n";
4729 
4730   outs() << "\t    instance methods "
4731          << format("0x%08" PRIx32, objc_category->instance_methods);
4732   if (print_method_list(objc_category->instance_methods, info))
4733     outs() << " (not in an __OBJC section)\n";
4734 
4735   outs() << "\t       class methods "
4736          << format("0x%08" PRIx32, objc_category->class_methods);
4737   if (print_method_list(objc_category->class_methods, info))
4738     outs() << " (not in an __OBJC section)\n";
4739 }
4740 
4741 static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
4742   struct category64_t c;
4743   const char *r;
4744   uint32_t offset, xoffset, left;
4745   SectionRef S, xS;
4746   const char *name, *sym_name;
4747   uint64_t n_value;
4748 
4749   r = get_pointer_64(p, offset, left, S, info);
4750   if (r == nullptr)
4751     return;
4752   memset(&c, '\0', sizeof(struct category64_t));
4753   if (left < sizeof(struct category64_t)) {
4754     memcpy(&c, r, left);
4755     outs() << "   (category_t entends past the end of the section)\n";
4756   } else
4757     memcpy(&c, r, sizeof(struct category64_t));
4758   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4759     swapStruct(c);
4760 
4761   outs() << "              name ";
4762   sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
4763                            info, n_value, c.name);
4764   if (n_value != 0) {
4765     if (info->verbose && sym_name != nullptr)
4766       outs() << sym_name;
4767     else
4768       outs() << format("0x%" PRIx64, n_value);
4769     if (c.name != 0)
4770       outs() << " + " << format("0x%" PRIx64, c.name);
4771   } else
4772     outs() << format("0x%" PRIx64, c.name);
4773   name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
4774   if (name != nullptr)
4775     outs() << format(" %.*s", left, name);
4776   outs() << "\n";
4777 
4778   outs() << "               cls ";
4779   sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
4780                            n_value, c.cls);
4781   if (n_value != 0) {
4782     if (info->verbose && sym_name != nullptr)
4783       outs() << sym_name;
4784     else
4785       outs() << format("0x%" PRIx64, n_value);
4786     if (c.cls != 0)
4787       outs() << " + " << format("0x%" PRIx64, c.cls);
4788   } else
4789     outs() << format("0x%" PRIx64, c.cls);
4790   outs() << "\n";
4791   if (c.cls + n_value != 0)
4792     print_class64_t(c.cls + n_value, info);
4793 
4794   outs() << "   instanceMethods ";
4795   sym_name =
4796       get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
4797                     info, n_value, c.instanceMethods);
4798   if (n_value != 0) {
4799     if (info->verbose && sym_name != nullptr)
4800       outs() << sym_name;
4801     else
4802       outs() << format("0x%" PRIx64, n_value);
4803     if (c.instanceMethods != 0)
4804       outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
4805   } else
4806     outs() << format("0x%" PRIx64, c.instanceMethods);
4807   outs() << "\n";
4808   if (c.instanceMethods + n_value != 0)
4809     print_method_list64_t(c.instanceMethods + n_value, info, "");
4810 
4811   outs() << "      classMethods ";
4812   sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
4813                            S, info, n_value, c.classMethods);
4814   if (n_value != 0) {
4815     if (info->verbose && sym_name != nullptr)
4816       outs() << sym_name;
4817     else
4818       outs() << format("0x%" PRIx64, n_value);
4819     if (c.classMethods != 0)
4820       outs() << " + " << format("0x%" PRIx64, c.classMethods);
4821   } else
4822     outs() << format("0x%" PRIx64, c.classMethods);
4823   outs() << "\n";
4824   if (c.classMethods + n_value != 0)
4825     print_method_list64_t(c.classMethods + n_value, info, "");
4826 
4827   outs() << "         protocols ";
4828   sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
4829                            info, n_value, c.protocols);
4830   if (n_value != 0) {
4831     if (info->verbose && sym_name != nullptr)
4832       outs() << sym_name;
4833     else
4834       outs() << format("0x%" PRIx64, n_value);
4835     if (c.protocols != 0)
4836       outs() << " + " << format("0x%" PRIx64, c.protocols);
4837   } else
4838     outs() << format("0x%" PRIx64, c.protocols);
4839   outs() << "\n";
4840   if (c.protocols + n_value != 0)
4841     print_protocol_list64_t(c.protocols + n_value, info);
4842 
4843   outs() << "instanceProperties ";
4844   sym_name =
4845       get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
4846                     S, info, n_value, c.instanceProperties);
4847   if (n_value != 0) {
4848     if (info->verbose && sym_name != nullptr)
4849       outs() << sym_name;
4850     else
4851       outs() << format("0x%" PRIx64, n_value);
4852     if (c.instanceProperties != 0)
4853       outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
4854   } else
4855     outs() << format("0x%" PRIx64, c.instanceProperties);
4856   outs() << "\n";
4857   if (c.instanceProperties + n_value != 0)
4858     print_objc_property_list64(c.instanceProperties + n_value, info);
4859 }
4860 
4861 static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
4862   struct category32_t c;
4863   const char *r;
4864   uint32_t offset, left;
4865   SectionRef S, xS;
4866   const char *name;
4867 
4868   r = get_pointer_32(p, offset, left, S, info);
4869   if (r == nullptr)
4870     return;
4871   memset(&c, '\0', sizeof(struct category32_t));
4872   if (left < sizeof(struct category32_t)) {
4873     memcpy(&c, r, left);
4874     outs() << "   (category_t entends past the end of the section)\n";
4875   } else
4876     memcpy(&c, r, sizeof(struct category32_t));
4877   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4878     swapStruct(c);
4879 
4880   outs() << "              name " << format("0x%" PRIx32, c.name);
4881   name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
4882                        c.name);
4883   if (name)
4884     outs() << " " << name;
4885   outs() << "\n";
4886 
4887   outs() << "               cls " << format("0x%" PRIx32, c.cls) << "\n";
4888   if (c.cls != 0)
4889     print_class32_t(c.cls, info);
4890   outs() << "   instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
4891          << "\n";
4892   if (c.instanceMethods != 0)
4893     print_method_list32_t(c.instanceMethods, info, "");
4894   outs() << "      classMethods " << format("0x%" PRIx32, c.classMethods)
4895          << "\n";
4896   if (c.classMethods != 0)
4897     print_method_list32_t(c.classMethods, info, "");
4898   outs() << "         protocols " << format("0x%" PRIx32, c.protocols) << "\n";
4899   if (c.protocols != 0)
4900     print_protocol_list32_t(c.protocols, info);
4901   outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
4902          << "\n";
4903   if (c.instanceProperties != 0)
4904     print_objc_property_list32(c.instanceProperties, info);
4905 }
4906 
4907 static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
4908   uint32_t i, left, offset, xoffset;
4909   uint64_t p, n_value;
4910   struct message_ref64 mr;
4911   const char *name, *sym_name;
4912   const char *r;
4913   SectionRef xS;
4914 
4915   if (S == SectionRef())
4916     return;
4917 
4918   StringRef SectName;
4919   S.getName(SectName);
4920   DataRefImpl Ref = S.getRawDataRefImpl();
4921   StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
4922   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4923   offset = 0;
4924   for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
4925     p = S.getAddress() + i;
4926     r = get_pointer_64(p, offset, left, S, info);
4927     if (r == nullptr)
4928       return;
4929     memset(&mr, '\0', sizeof(struct message_ref64));
4930     if (left < sizeof(struct message_ref64)) {
4931       memcpy(&mr, r, left);
4932       outs() << "   (message_ref entends past the end of the section)\n";
4933     } else
4934       memcpy(&mr, r, sizeof(struct message_ref64));
4935     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4936       swapStruct(mr);
4937 
4938     outs() << "  imp ";
4939     name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
4940                          n_value, mr.imp);
4941     if (n_value != 0) {
4942       outs() << format("0x%" PRIx64, n_value) << " ";
4943       if (mr.imp != 0)
4944         outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
4945     } else
4946       outs() << format("0x%" PRIx64, mr.imp) << " ";
4947     if (name != nullptr)
4948       outs() << " " << name;
4949     outs() << "\n";
4950 
4951     outs() << "  sel ";
4952     sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
4953                              info, n_value, mr.sel);
4954     if (n_value != 0) {
4955       if (info->verbose && sym_name != nullptr)
4956         outs() << sym_name;
4957       else
4958         outs() << format("0x%" PRIx64, n_value);
4959       if (mr.sel != 0)
4960         outs() << " + " << format("0x%" PRIx64, mr.sel);
4961     } else
4962       outs() << format("0x%" PRIx64, mr.sel);
4963     name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
4964     if (name != nullptr)
4965       outs() << format(" %.*s", left, name);
4966     outs() << "\n";
4967 
4968     offset += sizeof(struct message_ref64);
4969   }
4970 }
4971 
4972 static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
4973   uint32_t i, left, offset, xoffset, p;
4974   struct message_ref32 mr;
4975   const char *name, *r;
4976   SectionRef xS;
4977 
4978   if (S == SectionRef())
4979     return;
4980 
4981   StringRef SectName;
4982   S.getName(SectName);
4983   DataRefImpl Ref = S.getRawDataRefImpl();
4984   StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
4985   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4986   offset = 0;
4987   for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
4988     p = S.getAddress() + i;
4989     r = get_pointer_32(p, offset, left, S, info);
4990     if (r == nullptr)
4991       return;
4992     memset(&mr, '\0', sizeof(struct message_ref32));
4993     if (left < sizeof(struct message_ref32)) {
4994       memcpy(&mr, r, left);
4995       outs() << "   (message_ref entends past the end of the section)\n";
4996     } else
4997       memcpy(&mr, r, sizeof(struct message_ref32));
4998     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4999       swapStruct(mr);
5000 
5001     outs() << "  imp " << format("0x%" PRIx32, mr.imp);
5002     name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
5003                          mr.imp);
5004     if (name != nullptr)
5005       outs() << " " << name;
5006     outs() << "\n";
5007 
5008     outs() << "  sel " << format("0x%" PRIx32, mr.sel);
5009     name = get_pointer_32(mr.sel, xoffset, left, xS, info);
5010     if (name != nullptr)
5011       outs() << " " << name;
5012     outs() << "\n";
5013 
5014     offset += sizeof(struct message_ref32);
5015   }
5016 }
5017 
5018 static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
5019   uint32_t left, offset, swift_version;
5020   uint64_t p;
5021   struct objc_image_info64 o;
5022   const char *r;
5023 
5024   if (S == SectionRef())
5025     return;
5026 
5027   StringRef SectName;
5028   S.getName(SectName);
5029   DataRefImpl Ref = S.getRawDataRefImpl();
5030   StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5031   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5032   p = S.getAddress();
5033   r = get_pointer_64(p, offset, left, S, info);
5034   if (r == nullptr)
5035     return;
5036   memset(&o, '\0', sizeof(struct objc_image_info64));
5037   if (left < sizeof(struct objc_image_info64)) {
5038     memcpy(&o, r, left);
5039     outs() << "   (objc_image_info entends past the end of the section)\n";
5040   } else
5041     memcpy(&o, r, sizeof(struct objc_image_info64));
5042   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5043     swapStruct(o);
5044   outs() << "  version " << o.version << "\n";
5045   outs() << "    flags " << format("0x%" PRIx32, o.flags);
5046   if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5047     outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5048   if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5049     outs() << " OBJC_IMAGE_SUPPORTS_GC";
5050   swift_version = (o.flags >> 8) & 0xff;
5051   if (swift_version != 0) {
5052     if (swift_version == 1)
5053       outs() << " Swift 1.0";
5054     else if (swift_version == 2)
5055       outs() << " Swift 1.1";
5056     else
5057       outs() << " unknown future Swift version (" << swift_version << ")";
5058   }
5059   outs() << "\n";
5060 }
5061 
5062 static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
5063   uint32_t left, offset, swift_version, p;
5064   struct objc_image_info32 o;
5065   const char *r;
5066 
5067   StringRef SectName;
5068   S.getName(SectName);
5069   DataRefImpl Ref = S.getRawDataRefImpl();
5070   StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5071   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5072   p = S.getAddress();
5073   r = get_pointer_32(p, offset, left, S, info);
5074   if (r == nullptr)
5075     return;
5076   memset(&o, '\0', sizeof(struct objc_image_info32));
5077   if (left < sizeof(struct objc_image_info32)) {
5078     memcpy(&o, r, left);
5079     outs() << "   (objc_image_info entends past the end of the section)\n";
5080   } else
5081     memcpy(&o, r, sizeof(struct objc_image_info32));
5082   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5083     swapStruct(o);
5084   outs() << "  version " << o.version << "\n";
5085   outs() << "    flags " << format("0x%" PRIx32, o.flags);
5086   if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5087     outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5088   if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5089     outs() << " OBJC_IMAGE_SUPPORTS_GC";
5090   swift_version = (o.flags >> 8) & 0xff;
5091   if (swift_version != 0) {
5092     if (swift_version == 1)
5093       outs() << " Swift 1.0";
5094     else if (swift_version == 2)
5095       outs() << " Swift 1.1";
5096     else
5097       outs() << " unknown future Swift version (" << swift_version << ")";
5098   }
5099   outs() << "\n";
5100 }
5101 
5102 static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
5103   uint32_t left, offset, p;
5104   struct imageInfo_t o;
5105   const char *r;
5106 
5107   StringRef SectName;
5108   S.getName(SectName);
5109   DataRefImpl Ref = S.getRawDataRefImpl();
5110   StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5111   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5112   p = S.getAddress();
5113   r = get_pointer_32(p, offset, left, S, info);
5114   if (r == nullptr)
5115     return;
5116   memset(&o, '\0', sizeof(struct imageInfo_t));
5117   if (left < sizeof(struct imageInfo_t)) {
5118     memcpy(&o, r, left);
5119     outs() << " (imageInfo entends past the end of the section)\n";
5120   } else
5121     memcpy(&o, r, sizeof(struct imageInfo_t));
5122   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5123     swapStruct(o);
5124   outs() << "  version " << o.version << "\n";
5125   outs() << "    flags " << format("0x%" PRIx32, o.flags);
5126   if (o.flags & 0x1)
5127     outs() << "  F&C";
5128   if (o.flags & 0x2)
5129     outs() << " GC";
5130   if (o.flags & 0x4)
5131     outs() << " GC-only";
5132   else
5133     outs() << " RR";
5134   outs() << "\n";
5135 }
5136 
5137 static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
5138   SymbolAddressMap AddrMap;
5139   if (verbose)
5140     CreateSymbolAddressMap(O, &AddrMap);
5141 
5142   std::vector<SectionRef> Sections;
5143   for (const SectionRef &Section : O->sections()) {
5144     StringRef SectName;
5145     Section.getName(SectName);
5146     Sections.push_back(Section);
5147   }
5148 
5149   struct DisassembleInfo info;
5150   // Set up the block of info used by the Symbolizer call backs.
5151   info.verbose = verbose;
5152   info.O = O;
5153   info.AddrMap = &AddrMap;
5154   info.Sections = &Sections;
5155   info.class_name = nullptr;
5156   info.selector_name = nullptr;
5157   info.method = nullptr;
5158   info.demangled_name = nullptr;
5159   info.bindtable = nullptr;
5160   info.adrp_addr = 0;
5161   info.adrp_inst = 0;
5162 
5163   info.depth = 0;
5164   SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5165   if (CL == SectionRef())
5166     CL = get_section(O, "__DATA", "__objc_classlist");
5167   info.S = CL;
5168   walk_pointer_list_64("class", CL, O, &info, print_class64_t);
5169 
5170   SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5171   if (CR == SectionRef())
5172     CR = get_section(O, "__DATA", "__objc_classrefs");
5173   info.S = CR;
5174   walk_pointer_list_64("class refs", CR, O, &info, nullptr);
5175 
5176   SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5177   if (SR == SectionRef())
5178     SR = get_section(O, "__DATA", "__objc_superrefs");
5179   info.S = SR;
5180   walk_pointer_list_64("super refs", SR, O, &info, nullptr);
5181 
5182   SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5183   if (CA == SectionRef())
5184     CA = get_section(O, "__DATA", "__objc_catlist");
5185   info.S = CA;
5186   walk_pointer_list_64("category", CA, O, &info, print_category64_t);
5187 
5188   SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5189   if (PL == SectionRef())
5190     PL = get_section(O, "__DATA", "__objc_protolist");
5191   info.S = PL;
5192   walk_pointer_list_64("protocol", PL, O, &info, nullptr);
5193 
5194   SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5195   if (MR == SectionRef())
5196     MR = get_section(O, "__DATA", "__objc_msgrefs");
5197   info.S = MR;
5198   print_message_refs64(MR, &info);
5199 
5200   SectionRef II = get_section(O, "__OBJC2", "__image_info");
5201   if (II == SectionRef())
5202     II = get_section(O, "__DATA", "__objc_imageinfo");
5203   info.S = II;
5204   print_image_info64(II, &info);
5205 
5206   if (info.bindtable != nullptr)
5207     delete info.bindtable;
5208 }
5209 
5210 static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
5211   SymbolAddressMap AddrMap;
5212   if (verbose)
5213     CreateSymbolAddressMap(O, &AddrMap);
5214 
5215   std::vector<SectionRef> Sections;
5216   for (const SectionRef &Section : O->sections()) {
5217     StringRef SectName;
5218     Section.getName(SectName);
5219     Sections.push_back(Section);
5220   }
5221 
5222   struct DisassembleInfo info;
5223   // Set up the block of info used by the Symbolizer call backs.
5224   info.verbose = verbose;
5225   info.O = O;
5226   info.AddrMap = &AddrMap;
5227   info.Sections = &Sections;
5228   info.class_name = nullptr;
5229   info.selector_name = nullptr;
5230   info.method = nullptr;
5231   info.demangled_name = nullptr;
5232   info.bindtable = nullptr;
5233   info.adrp_addr = 0;
5234   info.adrp_inst = 0;
5235 
5236   const SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5237   if (CL != SectionRef()) {
5238     info.S = CL;
5239     walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5240   } else {
5241     const SectionRef CL = get_section(O, "__DATA", "__objc_classlist");
5242     info.S = CL;
5243     walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5244   }
5245 
5246   const SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5247   if (CR != SectionRef()) {
5248     info.S = CR;
5249     walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5250   } else {
5251     const SectionRef CR = get_section(O, "__DATA", "__objc_classrefs");
5252     info.S = CR;
5253     walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5254   }
5255 
5256   const SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5257   if (SR != SectionRef()) {
5258     info.S = SR;
5259     walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5260   } else {
5261     const SectionRef SR = get_section(O, "__DATA", "__objc_superrefs");
5262     info.S = SR;
5263     walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5264   }
5265 
5266   const SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5267   if (CA != SectionRef()) {
5268     info.S = CA;
5269     walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5270   } else {
5271     const SectionRef CA = get_section(O, "__DATA", "__objc_catlist");
5272     info.S = CA;
5273     walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5274   }
5275 
5276   const SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5277   if (PL != SectionRef()) {
5278     info.S = PL;
5279     walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5280   } else {
5281     const SectionRef PL = get_section(O, "__DATA", "__objc_protolist");
5282     info.S = PL;
5283     walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5284   }
5285 
5286   const SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5287   if (MR != SectionRef()) {
5288     info.S = MR;
5289     print_message_refs32(MR, &info);
5290   } else {
5291     const SectionRef MR = get_section(O, "__DATA", "__objc_msgrefs");
5292     info.S = MR;
5293     print_message_refs32(MR, &info);
5294   }
5295 
5296   const SectionRef II = get_section(O, "__OBJC2", "__image_info");
5297   if (II != SectionRef()) {
5298     info.S = II;
5299     print_image_info32(II, &info);
5300   } else {
5301     const SectionRef II = get_section(O, "__DATA", "__objc_imageinfo");
5302     info.S = II;
5303     print_image_info32(II, &info);
5304   }
5305 }
5306 
5307 static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
5308   uint32_t i, j, p, offset, xoffset, left, defs_left, def;
5309   const char *r, *name, *defs;
5310   struct objc_module_t module;
5311   SectionRef S, xS;
5312   struct objc_symtab_t symtab;
5313   struct objc_class_t objc_class;
5314   struct objc_category_t objc_category;
5315 
5316   outs() << "Objective-C segment\n";
5317   S = get_section(O, "__OBJC", "__module_info");
5318   if (S == SectionRef())
5319     return false;
5320 
5321   SymbolAddressMap AddrMap;
5322   if (verbose)
5323     CreateSymbolAddressMap(O, &AddrMap);
5324 
5325   std::vector<SectionRef> Sections;
5326   for (const SectionRef &Section : O->sections()) {
5327     StringRef SectName;
5328     Section.getName(SectName);
5329     Sections.push_back(Section);
5330   }
5331 
5332   struct DisassembleInfo info;
5333   // Set up the block of info used by the Symbolizer call backs.
5334   info.verbose = verbose;
5335   info.O = O;
5336   info.AddrMap = &AddrMap;
5337   info.Sections = &Sections;
5338   info.class_name = nullptr;
5339   info.selector_name = nullptr;
5340   info.method = nullptr;
5341   info.demangled_name = nullptr;
5342   info.bindtable = nullptr;
5343   info.adrp_addr = 0;
5344   info.adrp_inst = 0;
5345 
5346   for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
5347     p = S.getAddress() + i;
5348     r = get_pointer_32(p, offset, left, S, &info, true);
5349     if (r == nullptr)
5350       return true;
5351     memset(&module, '\0', sizeof(struct objc_module_t));
5352     if (left < sizeof(struct objc_module_t)) {
5353       memcpy(&module, r, left);
5354       outs() << "   (module extends past end of __module_info section)\n";
5355     } else
5356       memcpy(&module, r, sizeof(struct objc_module_t));
5357     if (O->isLittleEndian() != sys::IsLittleEndianHost)
5358       swapStruct(module);
5359 
5360     outs() << "Module " << format("0x%" PRIx32, p) << "\n";
5361     outs() << "    version " << module.version << "\n";
5362     outs() << "       size " << module.size << "\n";
5363     outs() << "       name ";
5364     name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
5365     if (name != nullptr)
5366       outs() << format("%.*s", left, name);
5367     else
5368       outs() << format("0x%08" PRIx32, module.name)
5369              << "(not in an __OBJC section)";
5370     outs() << "\n";
5371 
5372     r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
5373     if (module.symtab == 0 || r == nullptr) {
5374       outs() << "     symtab " << format("0x%08" PRIx32, module.symtab)
5375              << " (not in an __OBJC section)\n";
5376       continue;
5377     }
5378     outs() << "     symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
5379     memset(&symtab, '\0', sizeof(struct objc_symtab_t));
5380     defs_left = 0;
5381     defs = nullptr;
5382     if (left < sizeof(struct objc_symtab_t)) {
5383       memcpy(&symtab, r, left);
5384       outs() << "\tsymtab extends past end of an __OBJC section)\n";
5385     } else {
5386       memcpy(&symtab, r, sizeof(struct objc_symtab_t));
5387       if (left > sizeof(struct objc_symtab_t)) {
5388         defs_left = left - sizeof(struct objc_symtab_t);
5389         defs = r + sizeof(struct objc_symtab_t);
5390       }
5391     }
5392     if (O->isLittleEndian() != sys::IsLittleEndianHost)
5393       swapStruct(symtab);
5394 
5395     outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
5396     r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
5397     outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
5398     if (r == nullptr)
5399       outs() << " (not in an __OBJC section)";
5400     outs() << "\n";
5401     outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
5402     outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
5403     if (symtab.cls_def_cnt > 0)
5404       outs() << "\tClass Definitions\n";
5405     for (j = 0; j < symtab.cls_def_cnt; j++) {
5406       if ((j + 1) * sizeof(uint32_t) > defs_left) {
5407         outs() << "\t(remaining class defs entries entends past the end of the "
5408                << "section)\n";
5409         break;
5410       }
5411       memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
5412       if (O->isLittleEndian() != sys::IsLittleEndianHost)
5413         sys::swapByteOrder(def);
5414 
5415       r = get_pointer_32(def, xoffset, left, xS, &info, true);
5416       outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
5417       if (r != nullptr) {
5418         if (left > sizeof(struct objc_class_t)) {
5419           outs() << "\n";
5420           memcpy(&objc_class, r, sizeof(struct objc_class_t));
5421         } else {
5422           outs() << " (entends past the end of the section)\n";
5423           memset(&objc_class, '\0', sizeof(struct objc_class_t));
5424           memcpy(&objc_class, r, left);
5425         }
5426         if (O->isLittleEndian() != sys::IsLittleEndianHost)
5427           swapStruct(objc_class);
5428         print_objc_class_t(&objc_class, &info);
5429       } else {
5430         outs() << "(not in an __OBJC section)\n";
5431       }
5432 
5433       if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
5434         outs() << "\tMeta Class";
5435         r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
5436         if (r != nullptr) {
5437           if (left > sizeof(struct objc_class_t)) {
5438             outs() << "\n";
5439             memcpy(&objc_class, r, sizeof(struct objc_class_t));
5440           } else {
5441             outs() << " (entends past the end of the section)\n";
5442             memset(&objc_class, '\0', sizeof(struct objc_class_t));
5443             memcpy(&objc_class, r, left);
5444           }
5445           if (O->isLittleEndian() != sys::IsLittleEndianHost)
5446             swapStruct(objc_class);
5447           print_objc_class_t(&objc_class, &info);
5448         } else {
5449           outs() << "(not in an __OBJC section)\n";
5450         }
5451       }
5452     }
5453     if (symtab.cat_def_cnt > 0)
5454       outs() << "\tCategory Definitions\n";
5455     for (j = 0; j < symtab.cat_def_cnt; j++) {
5456       if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
5457         outs() << "\t(remaining category defs entries entends past the end of "
5458                << "the section)\n";
5459         break;
5460       }
5461       memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
5462              sizeof(uint32_t));
5463       if (O->isLittleEndian() != sys::IsLittleEndianHost)
5464         sys::swapByteOrder(def);
5465 
5466       r = get_pointer_32(def, xoffset, left, xS, &info, true);
5467       outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
5468              << format("0x%08" PRIx32, def);
5469       if (r != nullptr) {
5470         if (left > sizeof(struct objc_category_t)) {
5471           outs() << "\n";
5472           memcpy(&objc_category, r, sizeof(struct objc_category_t));
5473         } else {
5474           outs() << " (entends past the end of the section)\n";
5475           memset(&objc_category, '\0', sizeof(struct objc_category_t));
5476           memcpy(&objc_category, r, left);
5477         }
5478         if (O->isLittleEndian() != sys::IsLittleEndianHost)
5479           swapStruct(objc_category);
5480         print_objc_objc_category_t(&objc_category, &info);
5481       } else {
5482         outs() << "(not in an __OBJC section)\n";
5483       }
5484     }
5485   }
5486   const SectionRef II = get_section(O, "__OBJC", "__image_info");
5487   if (II != SectionRef())
5488     print_image_info(II, &info);
5489 
5490   return true;
5491 }
5492 
5493 static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
5494                                 uint32_t size, uint32_t addr) {
5495   SymbolAddressMap AddrMap;
5496   CreateSymbolAddressMap(O, &AddrMap);
5497 
5498   std::vector<SectionRef> Sections;
5499   for (const SectionRef &Section : O->sections()) {
5500     StringRef SectName;
5501     Section.getName(SectName);
5502     Sections.push_back(Section);
5503   }
5504 
5505   struct DisassembleInfo info;
5506   // Set up the block of info used by the Symbolizer call backs.
5507   info.verbose = true;
5508   info.O = O;
5509   info.AddrMap = &AddrMap;
5510   info.Sections = &Sections;
5511   info.class_name = nullptr;
5512   info.selector_name = nullptr;
5513   info.method = nullptr;
5514   info.demangled_name = nullptr;
5515   info.bindtable = nullptr;
5516   info.adrp_addr = 0;
5517   info.adrp_inst = 0;
5518 
5519   const char *p;
5520   struct objc_protocol_t protocol;
5521   uint32_t left, paddr;
5522   for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
5523     memset(&protocol, '\0', sizeof(struct objc_protocol_t));
5524     left = size - (p - sect);
5525     if (left < sizeof(struct objc_protocol_t)) {
5526       outs() << "Protocol extends past end of __protocol section\n";
5527       memcpy(&protocol, p, left);
5528     } else
5529       memcpy(&protocol, p, sizeof(struct objc_protocol_t));
5530     if (O->isLittleEndian() != sys::IsLittleEndianHost)
5531       swapStruct(protocol);
5532     paddr = addr + (p - sect);
5533     outs() << "Protocol " << format("0x%" PRIx32, paddr);
5534     if (print_protocol(paddr, 0, &info))
5535       outs() << "(not in an __OBJC section)\n";
5536   }
5537 }
5538 
5539 static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
5540   if (O->is64Bit())
5541     printObjc2_64bit_MetaData(O, verbose);
5542   else {
5543     MachO::mach_header H;
5544     H = O->getHeader();
5545     if (H.cputype == MachO::CPU_TYPE_ARM)
5546       printObjc2_32bit_MetaData(O, verbose);
5547     else {
5548       // This is the 32-bit non-arm cputype case.  Which is normally
5549       // the first Objective-C ABI.  But it may be the case of a
5550       // binary for the iOS simulator which is the second Objective-C
5551       // ABI.  In that case printObjc1_32bit_MetaData() will determine that
5552       // and return false.
5553       if (!printObjc1_32bit_MetaData(O, verbose))
5554         printObjc2_32bit_MetaData(O, verbose);
5555     }
5556   }
5557 }
5558 
5559 // GuessLiteralPointer returns a string which for the item in the Mach-O file
5560 // for the address passed in as ReferenceValue for printing as a comment with
5561 // the instruction and also returns the corresponding type of that item
5562 // indirectly through ReferenceType.
5563 //
5564 // If ReferenceValue is an address of literal cstring then a pointer to the
5565 // cstring is returned and ReferenceType is set to
5566 // LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
5567 //
5568 // If ReferenceValue is an address of an Objective-C CFString, Selector ref or
5569 // Class ref that name is returned and the ReferenceType is set accordingly.
5570 //
5571 // Lastly, literals which are Symbol address in a literal pool are looked for
5572 // and if found the symbol name is returned and ReferenceType is set to
5573 // LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
5574 //
5575 // If there is no item in the Mach-O file for the address passed in as
5576 // ReferenceValue nullptr is returned and ReferenceType is unchanged.
5577 static const char *GuessLiteralPointer(uint64_t ReferenceValue,
5578                                        uint64_t ReferencePC,
5579                                        uint64_t *ReferenceType,
5580                                        struct DisassembleInfo *info) {
5581   // First see if there is an external relocation entry at the ReferencePC.
5582   if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
5583     uint64_t sect_addr = info->S.getAddress();
5584     uint64_t sect_offset = ReferencePC - sect_addr;
5585     bool reloc_found = false;
5586     DataRefImpl Rel;
5587     MachO::any_relocation_info RE;
5588     bool isExtern = false;
5589     SymbolRef Symbol;
5590     for (const RelocationRef &Reloc : info->S.relocations()) {
5591       uint64_t RelocOffset = Reloc.getOffset();
5592       if (RelocOffset == sect_offset) {
5593         Rel = Reloc.getRawDataRefImpl();
5594         RE = info->O->getRelocation(Rel);
5595         if (info->O->isRelocationScattered(RE))
5596           continue;
5597         isExtern = info->O->getPlainRelocationExternal(RE);
5598         if (isExtern) {
5599           symbol_iterator RelocSym = Reloc.getSymbol();
5600           Symbol = *RelocSym;
5601         }
5602         reloc_found = true;
5603         break;
5604       }
5605     }
5606     // If there is an external relocation entry for a symbol in a section
5607     // then used that symbol's value for the value of the reference.
5608     if (reloc_found && isExtern) {
5609       if (info->O->getAnyRelocationPCRel(RE)) {
5610         unsigned Type = info->O->getAnyRelocationType(RE);
5611         if (Type == MachO::X86_64_RELOC_SIGNED) {
5612           ReferenceValue = Symbol.getValue();
5613         }
5614       }
5615     }
5616   }
5617 
5618   // Look for literals such as Objective-C CFStrings refs, Selector refs,
5619   // Message refs and Class refs.
5620   bool classref, selref, msgref, cfstring;
5621   uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
5622                                                selref, msgref, cfstring);
5623   if (classref && pointer_value == 0) {
5624     // Note the ReferenceValue is a pointer into the __objc_classrefs section.
5625     // And the pointer_value in that section is typically zero as it will be
5626     // set by dyld as part of the "bind information".
5627     const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
5628     if (name != nullptr) {
5629       *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
5630       const char *class_name = strrchr(name, '$');
5631       if (class_name != nullptr && class_name[1] == '_' &&
5632           class_name[2] != '\0') {
5633         info->class_name = class_name + 2;
5634         return name;
5635       }
5636     }
5637   }
5638 
5639   if (classref) {
5640     *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
5641     const char *name =
5642         get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
5643     if (name != nullptr)
5644       info->class_name = name;
5645     else
5646       name = "bad class ref";
5647     return name;
5648   }
5649 
5650   if (cfstring) {
5651     *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
5652     const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
5653     return name;
5654   }
5655 
5656   if (selref && pointer_value == 0)
5657     pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
5658 
5659   if (pointer_value != 0)
5660     ReferenceValue = pointer_value;
5661 
5662   const char *name = GuessCstringPointer(ReferenceValue, info);
5663   if (name) {
5664     if (pointer_value != 0 && selref) {
5665       *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
5666       info->selector_name = name;
5667     } else if (pointer_value != 0 && msgref) {
5668       info->class_name = nullptr;
5669       *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
5670       info->selector_name = name;
5671     } else
5672       *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
5673     return name;
5674   }
5675 
5676   // Lastly look for an indirect symbol with this ReferenceValue which is in
5677   // a literal pool.  If found return that symbol name.
5678   name = GuessIndirectSymbol(ReferenceValue, info);
5679   if (name) {
5680     *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
5681     return name;
5682   }
5683 
5684   return nullptr;
5685 }
5686 
5687 // SymbolizerSymbolLookUp is the symbol lookup function passed when creating
5688 // the Symbolizer.  It looks up the ReferenceValue using the info passed via the
5689 // pointer to the struct DisassembleInfo that was passed when MCSymbolizer
5690 // is created and returns the symbol name that matches the ReferenceValue or
5691 // nullptr if none.  The ReferenceType is passed in for the IN type of
5692 // reference the instruction is making from the values in defined in the header
5693 // "llvm-c/Disassembler.h".  On return the ReferenceType can set to a specific
5694 // Out type and the ReferenceName will also be set which is added as a comment
5695 // to the disassembled instruction.
5696 //
5697 #if HAVE_CXXABI_H
5698 // If the symbol name is a C++ mangled name then the demangled name is
5699 // returned through ReferenceName and ReferenceType is set to
5700 // LLVMDisassembler_ReferenceType_DeMangled_Name .
5701 #endif
5702 //
5703 // When this is called to get a symbol name for a branch target then the
5704 // ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
5705 // SymbolValue will be looked for in the indirect symbol table to determine if
5706 // it is an address for a symbol stub.  If so then the symbol name for that
5707 // stub is returned indirectly through ReferenceName and then ReferenceType is
5708 // set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
5709 //
5710 // When this is called with an value loaded via a PC relative load then
5711 // ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
5712 // SymbolValue is checked to be an address of literal pointer, symbol pointer,
5713 // or an Objective-C meta data reference.  If so the output ReferenceType is
5714 // set to correspond to that as well as setting the ReferenceName.
5715 static const char *SymbolizerSymbolLookUp(void *DisInfo,
5716                                           uint64_t ReferenceValue,
5717                                           uint64_t *ReferenceType,
5718                                           uint64_t ReferencePC,
5719                                           const char **ReferenceName) {
5720   struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
5721   // If no verbose symbolic information is wanted then just return nullptr.
5722   if (!info->verbose) {
5723     *ReferenceName = nullptr;
5724     *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5725     return nullptr;
5726   }
5727 
5728   const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
5729 
5730   if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
5731     *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
5732     if (*ReferenceName != nullptr) {
5733       method_reference(info, ReferenceType, ReferenceName);
5734       if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
5735         *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
5736     } else
5737 #if HAVE_CXXABI_H
5738         if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
5739       if (info->demangled_name != nullptr)
5740         free(info->demangled_name);
5741       int status;
5742       info->demangled_name =
5743           abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
5744       if (info->demangled_name != nullptr) {
5745         *ReferenceName = info->demangled_name;
5746         *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
5747       } else
5748         *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5749     } else
5750 #endif
5751       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5752   } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
5753     *ReferenceName =
5754         GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5755     if (*ReferenceName)
5756       method_reference(info, ReferenceType, ReferenceName);
5757     else
5758       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5759     // If this is arm64 and the reference is an adrp instruction save the
5760     // instruction, passed in ReferenceValue and the address of the instruction
5761     // for use later if we see and add immediate instruction.
5762   } else if (info->O->getArch() == Triple::aarch64 &&
5763              *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
5764     info->adrp_inst = ReferenceValue;
5765     info->adrp_addr = ReferencePC;
5766     SymbolName = nullptr;
5767     *ReferenceName = nullptr;
5768     *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5769     // If this is arm64 and reference is an add immediate instruction and we
5770     // have
5771     // seen an adrp instruction just before it and the adrp's Xd register
5772     // matches
5773     // this add's Xn register reconstruct the value being referenced and look to
5774     // see if it is a literal pointer.  Note the add immediate instruction is
5775     // passed in ReferenceValue.
5776   } else if (info->O->getArch() == Triple::aarch64 &&
5777              *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
5778              ReferencePC - 4 == info->adrp_addr &&
5779              (info->adrp_inst & 0x9f000000) == 0x90000000 &&
5780              (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
5781     uint32_t addxri_inst;
5782     uint64_t adrp_imm, addxri_imm;
5783 
5784     adrp_imm =
5785         ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
5786     if (info->adrp_inst & 0x0200000)
5787       adrp_imm |= 0xfffffffffc000000LL;
5788 
5789     addxri_inst = ReferenceValue;
5790     addxri_imm = (addxri_inst >> 10) & 0xfff;
5791     if (((addxri_inst >> 22) & 0x3) == 1)
5792       addxri_imm <<= 12;
5793 
5794     ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
5795                      (adrp_imm << 12) + addxri_imm;
5796 
5797     *ReferenceName =
5798         GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5799     if (*ReferenceName == nullptr)
5800       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5801     // If this is arm64 and the reference is a load register instruction and we
5802     // have seen an adrp instruction just before it and the adrp's Xd register
5803     // matches this add's Xn register reconstruct the value being referenced and
5804     // look to see if it is a literal pointer.  Note the load register
5805     // instruction is passed in ReferenceValue.
5806   } else if (info->O->getArch() == Triple::aarch64 &&
5807              *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
5808              ReferencePC - 4 == info->adrp_addr &&
5809              (info->adrp_inst & 0x9f000000) == 0x90000000 &&
5810              (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
5811     uint32_t ldrxui_inst;
5812     uint64_t adrp_imm, ldrxui_imm;
5813 
5814     adrp_imm =
5815         ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
5816     if (info->adrp_inst & 0x0200000)
5817       adrp_imm |= 0xfffffffffc000000LL;
5818 
5819     ldrxui_inst = ReferenceValue;
5820     ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
5821 
5822     ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
5823                      (adrp_imm << 12) + (ldrxui_imm << 3);
5824 
5825     *ReferenceName =
5826         GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5827     if (*ReferenceName == nullptr)
5828       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5829   }
5830   // If this arm64 and is an load register (PC-relative) instruction the
5831   // ReferenceValue is the PC plus the immediate value.
5832   else if (info->O->getArch() == Triple::aarch64 &&
5833            (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
5834             *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
5835     *ReferenceName =
5836         GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5837     if (*ReferenceName == nullptr)
5838       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5839   }
5840 #if HAVE_CXXABI_H
5841   else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
5842     if (info->demangled_name != nullptr)
5843       free(info->demangled_name);
5844     int status;
5845     info->demangled_name =
5846         abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
5847     if (info->demangled_name != nullptr) {
5848       *ReferenceName = info->demangled_name;
5849       *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
5850     }
5851   }
5852 #endif
5853   else {
5854     *ReferenceName = nullptr;
5855     *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5856   }
5857 
5858   return SymbolName;
5859 }
5860 
5861 /// \brief Emits the comments that are stored in the CommentStream.
5862 /// Each comment in the CommentStream must end with a newline.
5863 static void emitComments(raw_svector_ostream &CommentStream,
5864                          SmallString<128> &CommentsToEmit,
5865                          formatted_raw_ostream &FormattedOS,
5866                          const MCAsmInfo &MAI) {
5867   // Flush the stream before taking its content.
5868   StringRef Comments = CommentsToEmit.str();
5869   // Get the default information for printing a comment.
5870   const char *CommentBegin = MAI.getCommentString();
5871   unsigned CommentColumn = MAI.getCommentColumn();
5872   bool IsFirst = true;
5873   while (!Comments.empty()) {
5874     if (!IsFirst)
5875       FormattedOS << '\n';
5876     // Emit a line of comments.
5877     FormattedOS.PadToColumn(CommentColumn);
5878     size_t Position = Comments.find('\n');
5879     FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
5880     // Move after the newline character.
5881     Comments = Comments.substr(Position + 1);
5882     IsFirst = false;
5883   }
5884   FormattedOS.flush();
5885 
5886   // Tell the comment stream that the vector changed underneath it.
5887   CommentsToEmit.clear();
5888 }
5889 
5890 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
5891                              StringRef DisSegName, StringRef DisSectName) {
5892   const char *McpuDefault = nullptr;
5893   const Target *ThumbTarget = nullptr;
5894   const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
5895   if (!TheTarget) {
5896     // GetTarget prints out stuff.
5897     return;
5898   }
5899   if (MCPU.empty() && McpuDefault)
5900     MCPU = McpuDefault;
5901 
5902   std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
5903   std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
5904   if (ThumbTarget)
5905     ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
5906 
5907   // Package up features to be passed to target/subtarget
5908   std::string FeaturesStr;
5909   if (MAttrs.size()) {
5910     SubtargetFeatures Features;
5911     for (unsigned i = 0; i != MAttrs.size(); ++i)
5912       Features.AddFeature(MAttrs[i]);
5913     FeaturesStr = Features.getString();
5914   }
5915 
5916   // Set up disassembler.
5917   std::unique_ptr<const MCRegisterInfo> MRI(
5918       TheTarget->createMCRegInfo(TripleName));
5919   std::unique_ptr<const MCAsmInfo> AsmInfo(
5920       TheTarget->createMCAsmInfo(*MRI, TripleName));
5921   std::unique_ptr<const MCSubtargetInfo> STI(
5922       TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
5923   MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
5924   std::unique_ptr<MCDisassembler> DisAsm(
5925       TheTarget->createMCDisassembler(*STI, Ctx));
5926   std::unique_ptr<MCSymbolizer> Symbolizer;
5927   struct DisassembleInfo SymbolizerInfo;
5928   std::unique_ptr<MCRelocationInfo> RelInfo(
5929       TheTarget->createMCRelocationInfo(TripleName, Ctx));
5930   if (RelInfo) {
5931     Symbolizer.reset(TheTarget->createMCSymbolizer(
5932         TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
5933         &SymbolizerInfo, &Ctx, std::move(RelInfo)));
5934     DisAsm->setSymbolizer(std::move(Symbolizer));
5935   }
5936   int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
5937   std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
5938       Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
5939   // Set the display preference for hex vs. decimal immediates.
5940   IP->setPrintImmHex(PrintImmHex);
5941   // Comment stream and backing vector.
5942   SmallString<128> CommentsToEmit;
5943   raw_svector_ostream CommentStream(CommentsToEmit);
5944   // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
5945   // if it is done then arm64 comments for string literals don't get printed
5946   // and some constant get printed instead and not setting it causes intel
5947   // (32-bit and 64-bit) comments printed with different spacing before the
5948   // comment causing different diffs with the 'C' disassembler library API.
5949   // IP->setCommentStream(CommentStream);
5950 
5951   if (!AsmInfo || !STI || !DisAsm || !IP) {
5952     errs() << "error: couldn't initialize disassembler for target "
5953            << TripleName << '\n';
5954     return;
5955   }
5956 
5957   // Set up thumb disassembler.
5958   std::unique_ptr<const MCRegisterInfo> ThumbMRI;
5959   std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
5960   std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
5961   std::unique_ptr<MCDisassembler> ThumbDisAsm;
5962   std::unique_ptr<MCInstPrinter> ThumbIP;
5963   std::unique_ptr<MCContext> ThumbCtx;
5964   std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
5965   struct DisassembleInfo ThumbSymbolizerInfo;
5966   std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
5967   if (ThumbTarget) {
5968     ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
5969     ThumbAsmInfo.reset(
5970         ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
5971     ThumbSTI.reset(
5972         ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
5973     ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
5974     ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
5975     MCContext *PtrThumbCtx = ThumbCtx.get();
5976     ThumbRelInfo.reset(
5977         ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
5978     if (ThumbRelInfo) {
5979       ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
5980           ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
5981           &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
5982       ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
5983     }
5984     int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
5985     ThumbIP.reset(ThumbTarget->createMCInstPrinter(
5986         Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
5987         *ThumbInstrInfo, *ThumbMRI));
5988     // Set the display preference for hex vs. decimal immediates.
5989     ThumbIP->setPrintImmHex(PrintImmHex);
5990   }
5991 
5992   if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
5993     errs() << "error: couldn't initialize disassembler for target "
5994            << ThumbTripleName << '\n';
5995     return;
5996   }
5997 
5998   MachO::mach_header Header = MachOOF->getHeader();
5999 
6000   // FIXME: Using the -cfg command line option, this code used to be able to
6001   // annotate relocations with the referenced symbol's name, and if this was
6002   // inside a __[cf]string section, the data it points to. This is now replaced
6003   // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
6004   std::vector<SectionRef> Sections;
6005   std::vector<SymbolRef> Symbols;
6006   SmallVector<uint64_t, 8> FoundFns;
6007   uint64_t BaseSegmentAddress;
6008 
6009   getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
6010                         BaseSegmentAddress);
6011 
6012   // Sort the symbols by address, just in case they didn't come in that way.
6013   std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
6014 
6015   // Build a data in code table that is sorted on by the address of each entry.
6016   uint64_t BaseAddress = 0;
6017   if (Header.filetype == MachO::MH_OBJECT)
6018     BaseAddress = Sections[0].getAddress();
6019   else
6020     BaseAddress = BaseSegmentAddress;
6021   DiceTable Dices;
6022   for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
6023        DI != DE; ++DI) {
6024     uint32_t Offset;
6025     DI->getOffset(Offset);
6026     Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
6027   }
6028   array_pod_sort(Dices.begin(), Dices.end());
6029 
6030 #ifndef NDEBUG
6031   raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
6032 #else
6033   raw_ostream &DebugOut = nulls();
6034 #endif
6035 
6036   std::unique_ptr<DIContext> diContext;
6037   ObjectFile *DbgObj = MachOOF;
6038   // Try to find debug info and set up the DIContext for it.
6039   if (UseDbg) {
6040     // A separate DSym file path was specified, parse it as a macho file,
6041     // get the sections and supply it to the section name parsing machinery.
6042     if (!DSYMFile.empty()) {
6043       ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
6044           MemoryBuffer::getFileOrSTDIN(DSYMFile);
6045       if (std::error_code EC = BufOrErr.getError()) {
6046         errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
6047         return;
6048       }
6049       DbgObj =
6050           ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
6051               .get()
6052               .release();
6053     }
6054 
6055     // Setup the DIContext
6056     diContext.reset(new DWARFContextInMemory(*DbgObj));
6057   }
6058 
6059   if (FilterSections.size() == 0)
6060     outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
6061 
6062   for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
6063     StringRef SectName;
6064     if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
6065       continue;
6066 
6067     DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
6068 
6069     StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
6070     if (SegmentName != DisSegName)
6071       continue;
6072 
6073     StringRef BytesStr;
6074     Sections[SectIdx].getContents(BytesStr);
6075     ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
6076                             BytesStr.size());
6077     uint64_t SectAddress = Sections[SectIdx].getAddress();
6078 
6079     bool symbolTableWorked = false;
6080 
6081     // Create a map of symbol addresses to symbol names for use by
6082     // the SymbolizerSymbolLookUp() routine.
6083     SymbolAddressMap AddrMap;
6084     bool DisSymNameFound = false;
6085     for (const SymbolRef &Symbol : MachOOF->symbols()) {
6086       SymbolRef::Type ST = Symbol.getType();
6087       if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
6088           ST == SymbolRef::ST_Other) {
6089         uint64_t Address = Symbol.getValue();
6090         ErrorOr<StringRef> SymNameOrErr = Symbol.getName();
6091         if (std::error_code EC = SymNameOrErr.getError())
6092           report_fatal_error(EC.message());
6093         StringRef SymName = *SymNameOrErr;
6094         AddrMap[Address] = SymName;
6095         if (!DisSymName.empty() && DisSymName == SymName)
6096           DisSymNameFound = true;
6097       }
6098     }
6099     if (!DisSymName.empty() && !DisSymNameFound) {
6100       outs() << "Can't find -dis-symname: " << DisSymName << "\n";
6101       return;
6102     }
6103     // Set up the block of info used by the Symbolizer call backs.
6104     SymbolizerInfo.verbose = !NoSymbolicOperands;
6105     SymbolizerInfo.O = MachOOF;
6106     SymbolizerInfo.S = Sections[SectIdx];
6107     SymbolizerInfo.AddrMap = &AddrMap;
6108     SymbolizerInfo.Sections = &Sections;
6109     SymbolizerInfo.class_name = nullptr;
6110     SymbolizerInfo.selector_name = nullptr;
6111     SymbolizerInfo.method = nullptr;
6112     SymbolizerInfo.demangled_name = nullptr;
6113     SymbolizerInfo.bindtable = nullptr;
6114     SymbolizerInfo.adrp_addr = 0;
6115     SymbolizerInfo.adrp_inst = 0;
6116     // Same for the ThumbSymbolizer
6117     ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
6118     ThumbSymbolizerInfo.O = MachOOF;
6119     ThumbSymbolizerInfo.S = Sections[SectIdx];
6120     ThumbSymbolizerInfo.AddrMap = &AddrMap;
6121     ThumbSymbolizerInfo.Sections = &Sections;
6122     ThumbSymbolizerInfo.class_name = nullptr;
6123     ThumbSymbolizerInfo.selector_name = nullptr;
6124     ThumbSymbolizerInfo.method = nullptr;
6125     ThumbSymbolizerInfo.demangled_name = nullptr;
6126     ThumbSymbolizerInfo.bindtable = nullptr;
6127     ThumbSymbolizerInfo.adrp_addr = 0;
6128     ThumbSymbolizerInfo.adrp_inst = 0;
6129 
6130     // Disassemble symbol by symbol.
6131     for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
6132       ErrorOr<StringRef> SymNameOrErr = Symbols[SymIdx].getName();
6133       if (std::error_code EC = SymNameOrErr.getError())
6134         report_fatal_error(EC.message());
6135       StringRef SymName = *SymNameOrErr;
6136 
6137       SymbolRef::Type ST = Symbols[SymIdx].getType();
6138       if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
6139         continue;
6140 
6141       // Make sure the symbol is defined in this section.
6142       bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
6143       if (!containsSym)
6144         continue;
6145 
6146       // If we are only disassembling one symbol see if this is that symbol.
6147       if (!DisSymName.empty() && DisSymName != SymName)
6148         continue;
6149 
6150       // Start at the address of the symbol relative to the section's address.
6151       uint64_t Start = Symbols[SymIdx].getValue();
6152       uint64_t SectionAddress = Sections[SectIdx].getAddress();
6153       Start -= SectionAddress;
6154 
6155       // Stop disassembling either at the beginning of the next symbol or at
6156       // the end of the section.
6157       bool containsNextSym = false;
6158       uint64_t NextSym = 0;
6159       uint64_t NextSymIdx = SymIdx + 1;
6160       while (Symbols.size() > NextSymIdx) {
6161         SymbolRef::Type NextSymType = Symbols[NextSymIdx].getType();
6162         if (NextSymType == SymbolRef::ST_Function) {
6163           containsNextSym =
6164               Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
6165           NextSym = Symbols[NextSymIdx].getValue();
6166           NextSym -= SectionAddress;
6167           break;
6168         }
6169         ++NextSymIdx;
6170       }
6171 
6172       uint64_t SectSize = Sections[SectIdx].getSize();
6173       uint64_t End = containsNextSym ? NextSym : SectSize;
6174       uint64_t Size;
6175 
6176       symbolTableWorked = true;
6177 
6178       DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
6179       bool isThumb =
6180           (MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb) && ThumbTarget;
6181 
6182       outs() << SymName << ":\n";
6183       DILineInfo lastLine;
6184       for (uint64_t Index = Start; Index < End; Index += Size) {
6185         MCInst Inst;
6186 
6187         uint64_t PC = SectAddress + Index;
6188         if (!NoLeadingAddr) {
6189           if (FullLeadingAddr) {
6190             if (MachOOF->is64Bit())
6191               outs() << format("%016" PRIx64, PC);
6192             else
6193               outs() << format("%08" PRIx64, PC);
6194           } else {
6195             outs() << format("%8" PRIx64 ":", PC);
6196           }
6197         }
6198         if (!NoShowRawInsn)
6199           outs() << "\t";
6200 
6201         // Check the data in code table here to see if this is data not an
6202         // instruction to be disassembled.
6203         DiceTable Dice;
6204         Dice.push_back(std::make_pair(PC, DiceRef()));
6205         dice_table_iterator DTI =
6206             std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
6207                         compareDiceTableEntries);
6208         if (DTI != Dices.end()) {
6209           uint16_t Length;
6210           DTI->second.getLength(Length);
6211           uint16_t Kind;
6212           DTI->second.getKind(Kind);
6213           Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
6214           if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
6215               (PC == (DTI->first + Length - 1)) && (Length & 1))
6216             Size++;
6217           continue;
6218         }
6219 
6220         SmallVector<char, 64> AnnotationsBytes;
6221         raw_svector_ostream Annotations(AnnotationsBytes);
6222 
6223         bool gotInst;
6224         if (isThumb)
6225           gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
6226                                                 PC, DebugOut, Annotations);
6227         else
6228           gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
6229                                            DebugOut, Annotations);
6230         if (gotInst) {
6231           if (!NoShowRawInsn) {
6232             dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
6233           }
6234           formatted_raw_ostream FormattedOS(outs());
6235           StringRef AnnotationsStr = Annotations.str();
6236           if (isThumb)
6237             ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
6238           else
6239             IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
6240           emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
6241 
6242           // Print debug info.
6243           if (diContext) {
6244             DILineInfo dli = diContext->getLineInfoForAddress(PC);
6245             // Print valid line info if it changed.
6246             if (dli != lastLine && dli.Line != 0)
6247               outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
6248                      << dli.Column;
6249             lastLine = dli;
6250           }
6251           outs() << "\n";
6252         } else {
6253           unsigned int Arch = MachOOF->getArch();
6254           if (Arch == Triple::x86_64 || Arch == Triple::x86) {
6255             outs() << format("\t.byte 0x%02x #bad opcode\n",
6256                              *(Bytes.data() + Index) & 0xff);
6257             Size = 1; // skip exactly one illegible byte and move on.
6258           } else if (Arch == Triple::aarch64) {
6259             uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
6260                               (*(Bytes.data() + Index + 1) & 0xff) << 8 |
6261                               (*(Bytes.data() + Index + 2) & 0xff) << 16 |
6262                               (*(Bytes.data() + Index + 3) & 0xff) << 24;
6263             outs() << format("\t.long\t0x%08x\n", opcode);
6264             Size = 4;
6265           } else {
6266             errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6267             if (Size == 0)
6268               Size = 1; // skip illegible bytes
6269           }
6270         }
6271       }
6272     }
6273     if (!symbolTableWorked) {
6274       // Reading the symbol table didn't work, disassemble the whole section.
6275       uint64_t SectAddress = Sections[SectIdx].getAddress();
6276       uint64_t SectSize = Sections[SectIdx].getSize();
6277       uint64_t InstSize;
6278       for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
6279         MCInst Inst;
6280 
6281         uint64_t PC = SectAddress + Index;
6282         if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
6283                                    DebugOut, nulls())) {
6284           if (!NoLeadingAddr) {
6285             if (FullLeadingAddr) {
6286               if (MachOOF->is64Bit())
6287                 outs() << format("%016" PRIx64, PC);
6288               else
6289                 outs() << format("%08" PRIx64, PC);
6290             } else {
6291               outs() << format("%8" PRIx64 ":", PC);
6292             }
6293           }
6294           if (!NoShowRawInsn) {
6295             outs() << "\t";
6296             dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
6297           }
6298           IP->printInst(&Inst, outs(), "", *STI);
6299           outs() << "\n";
6300         } else {
6301           unsigned int Arch = MachOOF->getArch();
6302           if (Arch == Triple::x86_64 || Arch == Triple::x86) {
6303             outs() << format("\t.byte 0x%02x #bad opcode\n",
6304                              *(Bytes.data() + Index) & 0xff);
6305             InstSize = 1; // skip exactly one illegible byte and move on.
6306           } else {
6307             errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6308             if (InstSize == 0)
6309               InstSize = 1; // skip illegible bytes
6310           }
6311         }
6312       }
6313     }
6314     // The TripleName's need to be reset if we are called again for a different
6315     // archtecture.
6316     TripleName = "";
6317     ThumbTripleName = "";
6318 
6319     if (SymbolizerInfo.method != nullptr)
6320       free(SymbolizerInfo.method);
6321     if (SymbolizerInfo.demangled_name != nullptr)
6322       free(SymbolizerInfo.demangled_name);
6323     if (SymbolizerInfo.bindtable != nullptr)
6324       delete SymbolizerInfo.bindtable;
6325     if (ThumbSymbolizerInfo.method != nullptr)
6326       free(ThumbSymbolizerInfo.method);
6327     if (ThumbSymbolizerInfo.demangled_name != nullptr)
6328       free(ThumbSymbolizerInfo.demangled_name);
6329     if (ThumbSymbolizerInfo.bindtable != nullptr)
6330       delete ThumbSymbolizerInfo.bindtable;
6331   }
6332 }
6333 
6334 //===----------------------------------------------------------------------===//
6335 // __compact_unwind section dumping
6336 //===----------------------------------------------------------------------===//
6337 
6338 namespace {
6339 
6340 template <typename T> static uint64_t readNext(const char *&Buf) {
6341   using llvm::support::little;
6342   using llvm::support::unaligned;
6343 
6344   uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
6345   Buf += sizeof(T);
6346   return Val;
6347 }
6348 
6349 struct CompactUnwindEntry {
6350   uint32_t OffsetInSection;
6351 
6352   uint64_t FunctionAddr;
6353   uint32_t Length;
6354   uint32_t CompactEncoding;
6355   uint64_t PersonalityAddr;
6356   uint64_t LSDAAddr;
6357 
6358   RelocationRef FunctionReloc;
6359   RelocationRef PersonalityReloc;
6360   RelocationRef LSDAReloc;
6361 
6362   CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
6363       : OffsetInSection(Offset) {
6364     if (Is64)
6365       read<uint64_t>(Contents.data() + Offset);
6366     else
6367       read<uint32_t>(Contents.data() + Offset);
6368   }
6369 
6370 private:
6371   template <typename UIntPtr> void read(const char *Buf) {
6372     FunctionAddr = readNext<UIntPtr>(Buf);
6373     Length = readNext<uint32_t>(Buf);
6374     CompactEncoding = readNext<uint32_t>(Buf);
6375     PersonalityAddr = readNext<UIntPtr>(Buf);
6376     LSDAAddr = readNext<UIntPtr>(Buf);
6377   }
6378 };
6379 }
6380 
6381 /// Given a relocation from __compact_unwind, consisting of the RelocationRef
6382 /// and data being relocated, determine the best base Name and Addend to use for
6383 /// display purposes.
6384 ///
6385 /// 1. An Extern relocation will directly reference a symbol (and the data is
6386 ///    then already an addend), so use that.
6387 /// 2. Otherwise the data is an offset in the object file's layout; try to find
6388 //     a symbol before it in the same section, and use the offset from there.
6389 /// 3. Finally, if all that fails, fall back to an offset from the start of the
6390 ///    referenced section.
6391 static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
6392                                       std::map<uint64_t, SymbolRef> &Symbols,
6393                                       const RelocationRef &Reloc, uint64_t Addr,
6394                                       StringRef &Name, uint64_t &Addend) {
6395   if (Reloc.getSymbol() != Obj->symbol_end()) {
6396     ErrorOr<StringRef> NameOrErr = Reloc.getSymbol()->getName();
6397     if (std::error_code EC = NameOrErr.getError())
6398       report_fatal_error(EC.message());
6399     Name = *NameOrErr;
6400     Addend = Addr;
6401     return;
6402   }
6403 
6404   auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
6405   SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
6406 
6407   uint64_t SectionAddr = RelocSection.getAddress();
6408 
6409   auto Sym = Symbols.upper_bound(Addr);
6410   if (Sym == Symbols.begin()) {
6411     // The first symbol in the object is after this reference, the best we can
6412     // do is section-relative notation.
6413     RelocSection.getName(Name);
6414     Addend = Addr - SectionAddr;
6415     return;
6416   }
6417 
6418   // Go back one so that SymbolAddress <= Addr.
6419   --Sym;
6420 
6421   section_iterator SymSection = *Sym->second.getSection();
6422   if (RelocSection == *SymSection) {
6423     // There's a valid symbol in the same section before this reference.
6424     ErrorOr<StringRef> NameOrErr = Sym->second.getName();
6425     if (std::error_code EC = NameOrErr.getError())
6426       report_fatal_error(EC.message());
6427     Name = *NameOrErr;
6428     Addend = Addr - Sym->first;
6429     return;
6430   }
6431 
6432   // There is a symbol before this reference, but it's in a different
6433   // section. Probably not helpful to mention it, so use the section name.
6434   RelocSection.getName(Name);
6435   Addend = Addr - SectionAddr;
6436 }
6437 
6438 static void printUnwindRelocDest(const MachOObjectFile *Obj,
6439                                  std::map<uint64_t, SymbolRef> &Symbols,
6440                                  const RelocationRef &Reloc, uint64_t Addr) {
6441   StringRef Name;
6442   uint64_t Addend;
6443 
6444   if (!Reloc.getObject())
6445     return;
6446 
6447   findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
6448 
6449   outs() << Name;
6450   if (Addend)
6451     outs() << " + " << format("0x%" PRIx64, Addend);
6452 }
6453 
6454 static void
6455 printMachOCompactUnwindSection(const MachOObjectFile *Obj,
6456                                std::map<uint64_t, SymbolRef> &Symbols,
6457                                const SectionRef &CompactUnwind) {
6458 
6459   assert(Obj->isLittleEndian() &&
6460          "There should not be a big-endian .o with __compact_unwind");
6461 
6462   bool Is64 = Obj->is64Bit();
6463   uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
6464   uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
6465 
6466   StringRef Contents;
6467   CompactUnwind.getContents(Contents);
6468 
6469   SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
6470 
6471   // First populate the initial raw offsets, encodings and so on from the entry.
6472   for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
6473     CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
6474     CompactUnwinds.push_back(Entry);
6475   }
6476 
6477   // Next we need to look at the relocations to find out what objects are
6478   // actually being referred to.
6479   for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
6480     uint64_t RelocAddress = Reloc.getOffset();
6481 
6482     uint32_t EntryIdx = RelocAddress / EntrySize;
6483     uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
6484     CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
6485 
6486     if (OffsetInEntry == 0)
6487       Entry.FunctionReloc = Reloc;
6488     else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
6489       Entry.PersonalityReloc = Reloc;
6490     else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
6491       Entry.LSDAReloc = Reloc;
6492     else
6493       llvm_unreachable("Unexpected relocation in __compact_unwind section");
6494   }
6495 
6496   // Finally, we're ready to print the data we've gathered.
6497   outs() << "Contents of __compact_unwind section:\n";
6498   for (auto &Entry : CompactUnwinds) {
6499     outs() << "  Entry at offset "
6500            << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
6501 
6502     // 1. Start of the region this entry applies to.
6503     outs() << "    start:                " << format("0x%" PRIx64,
6504                                                      Entry.FunctionAddr) << ' ';
6505     printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
6506     outs() << '\n';
6507 
6508     // 2. Length of the region this entry applies to.
6509     outs() << "    length:               " << format("0x%" PRIx32, Entry.Length)
6510            << '\n';
6511     // 3. The 32-bit compact encoding.
6512     outs() << "    compact encoding:     "
6513            << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
6514 
6515     // 4. The personality function, if present.
6516     if (Entry.PersonalityReloc.getObject()) {
6517       outs() << "    personality function: "
6518              << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
6519       printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
6520                            Entry.PersonalityAddr);
6521       outs() << '\n';
6522     }
6523 
6524     // 5. This entry's language-specific data area.
6525     if (Entry.LSDAReloc.getObject()) {
6526       outs() << "    LSDA:                 " << format("0x%" PRIx64,
6527                                                        Entry.LSDAAddr) << ' ';
6528       printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
6529       outs() << '\n';
6530     }
6531   }
6532 }
6533 
6534 //===----------------------------------------------------------------------===//
6535 // __unwind_info section dumping
6536 //===----------------------------------------------------------------------===//
6537 
6538 static void printRegularSecondLevelUnwindPage(const char *PageStart) {
6539   const char *Pos = PageStart;
6540   uint32_t Kind = readNext<uint32_t>(Pos);
6541   (void)Kind;
6542   assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
6543 
6544   uint16_t EntriesStart = readNext<uint16_t>(Pos);
6545   uint16_t NumEntries = readNext<uint16_t>(Pos);
6546 
6547   Pos = PageStart + EntriesStart;
6548   for (unsigned i = 0; i < NumEntries; ++i) {
6549     uint32_t FunctionOffset = readNext<uint32_t>(Pos);
6550     uint32_t Encoding = readNext<uint32_t>(Pos);
6551 
6552     outs() << "      [" << i << "]: "
6553            << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6554            << ", "
6555            << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
6556   }
6557 }
6558 
6559 static void printCompressedSecondLevelUnwindPage(
6560     const char *PageStart, uint32_t FunctionBase,
6561     const SmallVectorImpl<uint32_t> &CommonEncodings) {
6562   const char *Pos = PageStart;
6563   uint32_t Kind = readNext<uint32_t>(Pos);
6564   (void)Kind;
6565   assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
6566 
6567   uint16_t EntriesStart = readNext<uint16_t>(Pos);
6568   uint16_t NumEntries = readNext<uint16_t>(Pos);
6569 
6570   uint16_t EncodingsStart = readNext<uint16_t>(Pos);
6571   readNext<uint16_t>(Pos);
6572   const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
6573       PageStart + EncodingsStart);
6574 
6575   Pos = PageStart + EntriesStart;
6576   for (unsigned i = 0; i < NumEntries; ++i) {
6577     uint32_t Entry = readNext<uint32_t>(Pos);
6578     uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
6579     uint32_t EncodingIdx = Entry >> 24;
6580 
6581     uint32_t Encoding;
6582     if (EncodingIdx < CommonEncodings.size())
6583       Encoding = CommonEncodings[EncodingIdx];
6584     else
6585       Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
6586 
6587     outs() << "      [" << i << "]: "
6588            << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6589            << ", "
6590            << "encoding[" << EncodingIdx
6591            << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
6592   }
6593 }
6594 
6595 static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
6596                                         std::map<uint64_t, SymbolRef> &Symbols,
6597                                         const SectionRef &UnwindInfo) {
6598 
6599   assert(Obj->isLittleEndian() &&
6600          "There should not be a big-endian .o with __unwind_info");
6601 
6602   outs() << "Contents of __unwind_info section:\n";
6603 
6604   StringRef Contents;
6605   UnwindInfo.getContents(Contents);
6606   const char *Pos = Contents.data();
6607 
6608   //===----------------------------------
6609   // Section header
6610   //===----------------------------------
6611 
6612   uint32_t Version = readNext<uint32_t>(Pos);
6613   outs() << "  Version:                                   "
6614          << format("0x%" PRIx32, Version) << '\n';
6615   assert(Version == 1 && "only understand version 1");
6616 
6617   uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
6618   outs() << "  Common encodings array section offset:     "
6619          << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
6620   uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
6621   outs() << "  Number of common encodings in array:       "
6622          << format("0x%" PRIx32, NumCommonEncodings) << '\n';
6623 
6624   uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
6625   outs() << "  Personality function array section offset: "
6626          << format("0x%" PRIx32, PersonalitiesStart) << '\n';
6627   uint32_t NumPersonalities = readNext<uint32_t>(Pos);
6628   outs() << "  Number of personality functions in array:  "
6629          << format("0x%" PRIx32, NumPersonalities) << '\n';
6630 
6631   uint32_t IndicesStart = readNext<uint32_t>(Pos);
6632   outs() << "  Index array section offset:                "
6633          << format("0x%" PRIx32, IndicesStart) << '\n';
6634   uint32_t NumIndices = readNext<uint32_t>(Pos);
6635   outs() << "  Number of indices in array:                "
6636          << format("0x%" PRIx32, NumIndices) << '\n';
6637 
6638   //===----------------------------------
6639   // A shared list of common encodings
6640   //===----------------------------------
6641 
6642   // These occupy indices in the range [0, N] whenever an encoding is referenced
6643   // from a compressed 2nd level index table. In practice the linker only
6644   // creates ~128 of these, so that indices are available to embed encodings in
6645   // the 2nd level index.
6646 
6647   SmallVector<uint32_t, 64> CommonEncodings;
6648   outs() << "  Common encodings: (count = " << NumCommonEncodings << ")\n";
6649   Pos = Contents.data() + CommonEncodingsStart;
6650   for (unsigned i = 0; i < NumCommonEncodings; ++i) {
6651     uint32_t Encoding = readNext<uint32_t>(Pos);
6652     CommonEncodings.push_back(Encoding);
6653 
6654     outs() << "    encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
6655            << '\n';
6656   }
6657 
6658   //===----------------------------------
6659   // Personality functions used in this executable
6660   //===----------------------------------
6661 
6662   // There should be only a handful of these (one per source language,
6663   // roughly). Particularly since they only get 2 bits in the compact encoding.
6664 
6665   outs() << "  Personality functions: (count = " << NumPersonalities << ")\n";
6666   Pos = Contents.data() + PersonalitiesStart;
6667   for (unsigned i = 0; i < NumPersonalities; ++i) {
6668     uint32_t PersonalityFn = readNext<uint32_t>(Pos);
6669     outs() << "    personality[" << i + 1
6670            << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
6671   }
6672 
6673   //===----------------------------------
6674   // The level 1 index entries
6675   //===----------------------------------
6676 
6677   // These specify an approximate place to start searching for the more detailed
6678   // information, sorted by PC.
6679 
6680   struct IndexEntry {
6681     uint32_t FunctionOffset;
6682     uint32_t SecondLevelPageStart;
6683     uint32_t LSDAStart;
6684   };
6685 
6686   SmallVector<IndexEntry, 4> IndexEntries;
6687 
6688   outs() << "  Top level indices: (count = " << NumIndices << ")\n";
6689   Pos = Contents.data() + IndicesStart;
6690   for (unsigned i = 0; i < NumIndices; ++i) {
6691     IndexEntry Entry;
6692 
6693     Entry.FunctionOffset = readNext<uint32_t>(Pos);
6694     Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
6695     Entry.LSDAStart = readNext<uint32_t>(Pos);
6696     IndexEntries.push_back(Entry);
6697 
6698     outs() << "    [" << i << "]: "
6699            << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
6700            << ", "
6701            << "2nd level page offset="
6702            << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
6703            << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
6704   }
6705 
6706   //===----------------------------------
6707   // Next come the LSDA tables
6708   //===----------------------------------
6709 
6710   // The LSDA layout is rather implicit: it's a contiguous array of entries from
6711   // the first top-level index's LSDAOffset to the last (sentinel).
6712 
6713   outs() << "  LSDA descriptors:\n";
6714   Pos = Contents.data() + IndexEntries[0].LSDAStart;
6715   int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
6716                  (2 * sizeof(uint32_t));
6717   for (int i = 0; i < NumLSDAs; ++i) {
6718     uint32_t FunctionOffset = readNext<uint32_t>(Pos);
6719     uint32_t LSDAOffset = readNext<uint32_t>(Pos);
6720     outs() << "    [" << i << "]: "
6721            << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6722            << ", "
6723            << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
6724   }
6725 
6726   //===----------------------------------
6727   // Finally, the 2nd level indices
6728   //===----------------------------------
6729 
6730   // Generally these are 4K in size, and have 2 possible forms:
6731   //   + Regular stores up to 511 entries with disparate encodings
6732   //   + Compressed stores up to 1021 entries if few enough compact encoding
6733   //     values are used.
6734   outs() << "  Second level indices:\n";
6735   for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
6736     // The final sentinel top-level index has no associated 2nd level page
6737     if (IndexEntries[i].SecondLevelPageStart == 0)
6738       break;
6739 
6740     outs() << "    Second level index[" << i << "]: "
6741            << "offset in section="
6742            << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
6743            << ", "
6744            << "base function offset="
6745            << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
6746 
6747     Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
6748     uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
6749     if (Kind == 2)
6750       printRegularSecondLevelUnwindPage(Pos);
6751     else if (Kind == 3)
6752       printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
6753                                            CommonEncodings);
6754     else
6755       llvm_unreachable("Do not know how to print this kind of 2nd level page");
6756   }
6757 }
6758 
6759 void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
6760   std::map<uint64_t, SymbolRef> Symbols;
6761   for (const SymbolRef &SymRef : Obj->symbols()) {
6762     // Discard any undefined or absolute symbols. They're not going to take part
6763     // in the convenience lookup for unwind info and just take up resources.
6764     section_iterator Section = *SymRef.getSection();
6765     if (Section == Obj->section_end())
6766       continue;
6767 
6768     uint64_t Addr = SymRef.getValue();
6769     Symbols.insert(std::make_pair(Addr, SymRef));
6770   }
6771 
6772   for (const SectionRef &Section : Obj->sections()) {
6773     StringRef SectName;
6774     Section.getName(SectName);
6775     if (SectName == "__compact_unwind")
6776       printMachOCompactUnwindSection(Obj, Symbols, Section);
6777     else if (SectName == "__unwind_info")
6778       printMachOUnwindInfoSection(Obj, Symbols, Section);
6779   }
6780 }
6781 
6782 static void PrintMachHeader(uint32_t magic, uint32_t cputype,
6783                             uint32_t cpusubtype, uint32_t filetype,
6784                             uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
6785                             bool verbose) {
6786   outs() << "Mach header\n";
6787   outs() << "      magic cputype cpusubtype  caps    filetype ncmds "
6788             "sizeofcmds      flags\n";
6789   if (verbose) {
6790     if (magic == MachO::MH_MAGIC)
6791       outs() << "   MH_MAGIC";
6792     else if (magic == MachO::MH_MAGIC_64)
6793       outs() << "MH_MAGIC_64";
6794     else
6795       outs() << format(" 0x%08" PRIx32, magic);
6796     switch (cputype) {
6797     case MachO::CPU_TYPE_I386:
6798       outs() << "    I386";
6799       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6800       case MachO::CPU_SUBTYPE_I386_ALL:
6801         outs() << "        ALL";
6802         break;
6803       default:
6804         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6805         break;
6806       }
6807       break;
6808     case MachO::CPU_TYPE_X86_64:
6809       outs() << "  X86_64";
6810       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6811       case MachO::CPU_SUBTYPE_X86_64_ALL:
6812         outs() << "        ALL";
6813         break;
6814       case MachO::CPU_SUBTYPE_X86_64_H:
6815         outs() << "    Haswell";
6816         break;
6817       default:
6818         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6819         break;
6820       }
6821       break;
6822     case MachO::CPU_TYPE_ARM:
6823       outs() << "     ARM";
6824       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6825       case MachO::CPU_SUBTYPE_ARM_ALL:
6826         outs() << "        ALL";
6827         break;
6828       case MachO::CPU_SUBTYPE_ARM_V4T:
6829         outs() << "        V4T";
6830         break;
6831       case MachO::CPU_SUBTYPE_ARM_V5TEJ:
6832         outs() << "      V5TEJ";
6833         break;
6834       case MachO::CPU_SUBTYPE_ARM_XSCALE:
6835         outs() << "     XSCALE";
6836         break;
6837       case MachO::CPU_SUBTYPE_ARM_V6:
6838         outs() << "         V6";
6839         break;
6840       case MachO::CPU_SUBTYPE_ARM_V6M:
6841         outs() << "        V6M";
6842         break;
6843       case MachO::CPU_SUBTYPE_ARM_V7:
6844         outs() << "         V7";
6845         break;
6846       case MachO::CPU_SUBTYPE_ARM_V7EM:
6847         outs() << "       V7EM";
6848         break;
6849       case MachO::CPU_SUBTYPE_ARM_V7K:
6850         outs() << "        V7K";
6851         break;
6852       case MachO::CPU_SUBTYPE_ARM_V7M:
6853         outs() << "        V7M";
6854         break;
6855       case MachO::CPU_SUBTYPE_ARM_V7S:
6856         outs() << "        V7S";
6857         break;
6858       default:
6859         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6860         break;
6861       }
6862       break;
6863     case MachO::CPU_TYPE_ARM64:
6864       outs() << "   ARM64";
6865       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6866       case MachO::CPU_SUBTYPE_ARM64_ALL:
6867         outs() << "        ALL";
6868         break;
6869       default:
6870         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6871         break;
6872       }
6873       break;
6874     case MachO::CPU_TYPE_POWERPC:
6875       outs() << "     PPC";
6876       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6877       case MachO::CPU_SUBTYPE_POWERPC_ALL:
6878         outs() << "        ALL";
6879         break;
6880       default:
6881         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6882         break;
6883       }
6884       break;
6885     case MachO::CPU_TYPE_POWERPC64:
6886       outs() << "   PPC64";
6887       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6888       case MachO::CPU_SUBTYPE_POWERPC_ALL:
6889         outs() << "        ALL";
6890         break;
6891       default:
6892         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6893         break;
6894       }
6895       break;
6896     default:
6897       outs() << format(" %7d", cputype);
6898       outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6899       break;
6900     }
6901     if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
6902       outs() << " LIB64";
6903     } else {
6904       outs() << format("  0x%02" PRIx32,
6905                        (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
6906     }
6907     switch (filetype) {
6908     case MachO::MH_OBJECT:
6909       outs() << "      OBJECT";
6910       break;
6911     case MachO::MH_EXECUTE:
6912       outs() << "     EXECUTE";
6913       break;
6914     case MachO::MH_FVMLIB:
6915       outs() << "      FVMLIB";
6916       break;
6917     case MachO::MH_CORE:
6918       outs() << "        CORE";
6919       break;
6920     case MachO::MH_PRELOAD:
6921       outs() << "     PRELOAD";
6922       break;
6923     case MachO::MH_DYLIB:
6924       outs() << "       DYLIB";
6925       break;
6926     case MachO::MH_DYLIB_STUB:
6927       outs() << "  DYLIB_STUB";
6928       break;
6929     case MachO::MH_DYLINKER:
6930       outs() << "    DYLINKER";
6931       break;
6932     case MachO::MH_BUNDLE:
6933       outs() << "      BUNDLE";
6934       break;
6935     case MachO::MH_DSYM:
6936       outs() << "        DSYM";
6937       break;
6938     case MachO::MH_KEXT_BUNDLE:
6939       outs() << "  KEXTBUNDLE";
6940       break;
6941     default:
6942       outs() << format("  %10u", filetype);
6943       break;
6944     }
6945     outs() << format(" %5u", ncmds);
6946     outs() << format(" %10u", sizeofcmds);
6947     uint32_t f = flags;
6948     if (f & MachO::MH_NOUNDEFS) {
6949       outs() << "   NOUNDEFS";
6950       f &= ~MachO::MH_NOUNDEFS;
6951     }
6952     if (f & MachO::MH_INCRLINK) {
6953       outs() << " INCRLINK";
6954       f &= ~MachO::MH_INCRLINK;
6955     }
6956     if (f & MachO::MH_DYLDLINK) {
6957       outs() << " DYLDLINK";
6958       f &= ~MachO::MH_DYLDLINK;
6959     }
6960     if (f & MachO::MH_BINDATLOAD) {
6961       outs() << " BINDATLOAD";
6962       f &= ~MachO::MH_BINDATLOAD;
6963     }
6964     if (f & MachO::MH_PREBOUND) {
6965       outs() << " PREBOUND";
6966       f &= ~MachO::MH_PREBOUND;
6967     }
6968     if (f & MachO::MH_SPLIT_SEGS) {
6969       outs() << " SPLIT_SEGS";
6970       f &= ~MachO::MH_SPLIT_SEGS;
6971     }
6972     if (f & MachO::MH_LAZY_INIT) {
6973       outs() << " LAZY_INIT";
6974       f &= ~MachO::MH_LAZY_INIT;
6975     }
6976     if (f & MachO::MH_TWOLEVEL) {
6977       outs() << " TWOLEVEL";
6978       f &= ~MachO::MH_TWOLEVEL;
6979     }
6980     if (f & MachO::MH_FORCE_FLAT) {
6981       outs() << " FORCE_FLAT";
6982       f &= ~MachO::MH_FORCE_FLAT;
6983     }
6984     if (f & MachO::MH_NOMULTIDEFS) {
6985       outs() << " NOMULTIDEFS";
6986       f &= ~MachO::MH_NOMULTIDEFS;
6987     }
6988     if (f & MachO::MH_NOFIXPREBINDING) {
6989       outs() << " NOFIXPREBINDING";
6990       f &= ~MachO::MH_NOFIXPREBINDING;
6991     }
6992     if (f & MachO::MH_PREBINDABLE) {
6993       outs() << " PREBINDABLE";
6994       f &= ~MachO::MH_PREBINDABLE;
6995     }
6996     if (f & MachO::MH_ALLMODSBOUND) {
6997       outs() << " ALLMODSBOUND";
6998       f &= ~MachO::MH_ALLMODSBOUND;
6999     }
7000     if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
7001       outs() << " SUBSECTIONS_VIA_SYMBOLS";
7002       f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
7003     }
7004     if (f & MachO::MH_CANONICAL) {
7005       outs() << " CANONICAL";
7006       f &= ~MachO::MH_CANONICAL;
7007     }
7008     if (f & MachO::MH_WEAK_DEFINES) {
7009       outs() << " WEAK_DEFINES";
7010       f &= ~MachO::MH_WEAK_DEFINES;
7011     }
7012     if (f & MachO::MH_BINDS_TO_WEAK) {
7013       outs() << " BINDS_TO_WEAK";
7014       f &= ~MachO::MH_BINDS_TO_WEAK;
7015     }
7016     if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
7017       outs() << " ALLOW_STACK_EXECUTION";
7018       f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
7019     }
7020     if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
7021       outs() << " DEAD_STRIPPABLE_DYLIB";
7022       f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
7023     }
7024     if (f & MachO::MH_PIE) {
7025       outs() << " PIE";
7026       f &= ~MachO::MH_PIE;
7027     }
7028     if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
7029       outs() << " NO_REEXPORTED_DYLIBS";
7030       f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
7031     }
7032     if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
7033       outs() << " MH_HAS_TLV_DESCRIPTORS";
7034       f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
7035     }
7036     if (f & MachO::MH_NO_HEAP_EXECUTION) {
7037       outs() << " MH_NO_HEAP_EXECUTION";
7038       f &= ~MachO::MH_NO_HEAP_EXECUTION;
7039     }
7040     if (f & MachO::MH_APP_EXTENSION_SAFE) {
7041       outs() << " APP_EXTENSION_SAFE";
7042       f &= ~MachO::MH_APP_EXTENSION_SAFE;
7043     }
7044     if (f != 0 || flags == 0)
7045       outs() << format(" 0x%08" PRIx32, f);
7046   } else {
7047     outs() << format(" 0x%08" PRIx32, magic);
7048     outs() << format(" %7d", cputype);
7049     outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7050     outs() << format("  0x%02" PRIx32,
7051                      (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7052     outs() << format("  %10u", filetype);
7053     outs() << format(" %5u", ncmds);
7054     outs() << format(" %10u", sizeofcmds);
7055     outs() << format(" 0x%08" PRIx32, flags);
7056   }
7057   outs() << "\n";
7058 }
7059 
7060 static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
7061                                 StringRef SegName, uint64_t vmaddr,
7062                                 uint64_t vmsize, uint64_t fileoff,
7063                                 uint64_t filesize, uint32_t maxprot,
7064                                 uint32_t initprot, uint32_t nsects,
7065                                 uint32_t flags, uint32_t object_size,
7066                                 bool verbose) {
7067   uint64_t expected_cmdsize;
7068   if (cmd == MachO::LC_SEGMENT) {
7069     outs() << "      cmd LC_SEGMENT\n";
7070     expected_cmdsize = nsects;
7071     expected_cmdsize *= sizeof(struct MachO::section);
7072     expected_cmdsize += sizeof(struct MachO::segment_command);
7073   } else {
7074     outs() << "      cmd LC_SEGMENT_64\n";
7075     expected_cmdsize = nsects;
7076     expected_cmdsize *= sizeof(struct MachO::section_64);
7077     expected_cmdsize += sizeof(struct MachO::segment_command_64);
7078   }
7079   outs() << "  cmdsize " << cmdsize;
7080   if (cmdsize != expected_cmdsize)
7081     outs() << " Inconsistent size\n";
7082   else
7083     outs() << "\n";
7084   outs() << "  segname " << SegName << "\n";
7085   if (cmd == MachO::LC_SEGMENT_64) {
7086     outs() << "   vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
7087     outs() << "   vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
7088   } else {
7089     outs() << "   vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
7090     outs() << "   vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
7091   }
7092   outs() << "  fileoff " << fileoff;
7093   if (fileoff > object_size)
7094     outs() << " (past end of file)\n";
7095   else
7096     outs() << "\n";
7097   outs() << " filesize " << filesize;
7098   if (fileoff + filesize > object_size)
7099     outs() << " (past end of file)\n";
7100   else
7101     outs() << "\n";
7102   if (verbose) {
7103     if ((maxprot &
7104          ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7105            MachO::VM_PROT_EXECUTE)) != 0)
7106       outs() << "  maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
7107     else {
7108       outs() << "  maxprot ";
7109       outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
7110       outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
7111       outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
7112     }
7113     if ((initprot &
7114          ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7115            MachO::VM_PROT_EXECUTE)) != 0)
7116       outs() << "  initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
7117     else {
7118       outs() << "  initprot ";
7119       outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
7120       outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
7121       outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
7122     }
7123   } else {
7124     outs() << "  maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
7125     outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
7126   }
7127   outs() << "   nsects " << nsects << "\n";
7128   if (verbose) {
7129     outs() << "    flags";
7130     if (flags == 0)
7131       outs() << " (none)\n";
7132     else {
7133       if (flags & MachO::SG_HIGHVM) {
7134         outs() << " HIGHVM";
7135         flags &= ~MachO::SG_HIGHVM;
7136       }
7137       if (flags & MachO::SG_FVMLIB) {
7138         outs() << " FVMLIB";
7139         flags &= ~MachO::SG_FVMLIB;
7140       }
7141       if (flags & MachO::SG_NORELOC) {
7142         outs() << " NORELOC";
7143         flags &= ~MachO::SG_NORELOC;
7144       }
7145       if (flags & MachO::SG_PROTECTED_VERSION_1) {
7146         outs() << " PROTECTED_VERSION_1";
7147         flags &= ~MachO::SG_PROTECTED_VERSION_1;
7148       }
7149       if (flags)
7150         outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
7151       else
7152         outs() << "\n";
7153     }
7154   } else {
7155     outs() << "    flags " << format("0x%" PRIx32, flags) << "\n";
7156   }
7157 }
7158 
7159 static void PrintSection(const char *sectname, const char *segname,
7160                          uint64_t addr, uint64_t size, uint32_t offset,
7161                          uint32_t align, uint32_t reloff, uint32_t nreloc,
7162                          uint32_t flags, uint32_t reserved1, uint32_t reserved2,
7163                          uint32_t cmd, const char *sg_segname,
7164                          uint32_t filetype, uint32_t object_size,
7165                          bool verbose) {
7166   outs() << "Section\n";
7167   outs() << "  sectname " << format("%.16s\n", sectname);
7168   outs() << "   segname " << format("%.16s", segname);
7169   if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
7170     outs() << " (does not match segment)\n";
7171   else
7172     outs() << "\n";
7173   if (cmd == MachO::LC_SEGMENT_64) {
7174     outs() << "      addr " << format("0x%016" PRIx64, addr) << "\n";
7175     outs() << "      size " << format("0x%016" PRIx64, size);
7176   } else {
7177     outs() << "      addr " << format("0x%08" PRIx64, addr) << "\n";
7178     outs() << "      size " << format("0x%08" PRIx64, size);
7179   }
7180   if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
7181     outs() << " (past end of file)\n";
7182   else
7183     outs() << "\n";
7184   outs() << "    offset " << offset;
7185   if (offset > object_size)
7186     outs() << " (past end of file)\n";
7187   else
7188     outs() << "\n";
7189   uint32_t align_shifted = 1 << align;
7190   outs() << "     align 2^" << align << " (" << align_shifted << ")\n";
7191   outs() << "    reloff " << reloff;
7192   if (reloff > object_size)
7193     outs() << " (past end of file)\n";
7194   else
7195     outs() << "\n";
7196   outs() << "    nreloc " << nreloc;
7197   if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
7198     outs() << " (past end of file)\n";
7199   else
7200     outs() << "\n";
7201   uint32_t section_type = flags & MachO::SECTION_TYPE;
7202   if (verbose) {
7203     outs() << "      type";
7204     if (section_type == MachO::S_REGULAR)
7205       outs() << " S_REGULAR\n";
7206     else if (section_type == MachO::S_ZEROFILL)
7207       outs() << " S_ZEROFILL\n";
7208     else if (section_type == MachO::S_CSTRING_LITERALS)
7209       outs() << " S_CSTRING_LITERALS\n";
7210     else if (section_type == MachO::S_4BYTE_LITERALS)
7211       outs() << " S_4BYTE_LITERALS\n";
7212     else if (section_type == MachO::S_8BYTE_LITERALS)
7213       outs() << " S_8BYTE_LITERALS\n";
7214     else if (section_type == MachO::S_16BYTE_LITERALS)
7215       outs() << " S_16BYTE_LITERALS\n";
7216     else if (section_type == MachO::S_LITERAL_POINTERS)
7217       outs() << " S_LITERAL_POINTERS\n";
7218     else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
7219       outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
7220     else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
7221       outs() << " S_LAZY_SYMBOL_POINTERS\n";
7222     else if (section_type == MachO::S_SYMBOL_STUBS)
7223       outs() << " S_SYMBOL_STUBS\n";
7224     else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
7225       outs() << " S_MOD_INIT_FUNC_POINTERS\n";
7226     else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
7227       outs() << " S_MOD_TERM_FUNC_POINTERS\n";
7228     else if (section_type == MachO::S_COALESCED)
7229       outs() << " S_COALESCED\n";
7230     else if (section_type == MachO::S_INTERPOSING)
7231       outs() << " S_INTERPOSING\n";
7232     else if (section_type == MachO::S_DTRACE_DOF)
7233       outs() << " S_DTRACE_DOF\n";
7234     else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
7235       outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
7236     else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
7237       outs() << " S_THREAD_LOCAL_REGULAR\n";
7238     else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
7239       outs() << " S_THREAD_LOCAL_ZEROFILL\n";
7240     else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
7241       outs() << " S_THREAD_LOCAL_VARIABLES\n";
7242     else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7243       outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
7244     else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
7245       outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
7246     else
7247       outs() << format("0x%08" PRIx32, section_type) << "\n";
7248     outs() << "attributes";
7249     uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
7250     if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
7251       outs() << " PURE_INSTRUCTIONS";
7252     if (section_attributes & MachO::S_ATTR_NO_TOC)
7253       outs() << " NO_TOC";
7254     if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
7255       outs() << " STRIP_STATIC_SYMS";
7256     if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
7257       outs() << " NO_DEAD_STRIP";
7258     if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
7259       outs() << " LIVE_SUPPORT";
7260     if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
7261       outs() << " SELF_MODIFYING_CODE";
7262     if (section_attributes & MachO::S_ATTR_DEBUG)
7263       outs() << " DEBUG";
7264     if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
7265       outs() << " SOME_INSTRUCTIONS";
7266     if (section_attributes & MachO::S_ATTR_EXT_RELOC)
7267       outs() << " EXT_RELOC";
7268     if (section_attributes & MachO::S_ATTR_LOC_RELOC)
7269       outs() << " LOC_RELOC";
7270     if (section_attributes == 0)
7271       outs() << " (none)";
7272     outs() << "\n";
7273   } else
7274     outs() << "     flags " << format("0x%08" PRIx32, flags) << "\n";
7275   outs() << " reserved1 " << reserved1;
7276   if (section_type == MachO::S_SYMBOL_STUBS ||
7277       section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
7278       section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
7279       section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
7280       section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7281     outs() << " (index into indirect symbol table)\n";
7282   else
7283     outs() << "\n";
7284   outs() << " reserved2 " << reserved2;
7285   if (section_type == MachO::S_SYMBOL_STUBS)
7286     outs() << " (size of stubs)\n";
7287   else
7288     outs() << "\n";
7289 }
7290 
7291 static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
7292                                    uint32_t object_size) {
7293   outs() << "     cmd LC_SYMTAB\n";
7294   outs() << " cmdsize " << st.cmdsize;
7295   if (st.cmdsize != sizeof(struct MachO::symtab_command))
7296     outs() << " Incorrect size\n";
7297   else
7298     outs() << "\n";
7299   outs() << "  symoff " << st.symoff;
7300   if (st.symoff > object_size)
7301     outs() << " (past end of file)\n";
7302   else
7303     outs() << "\n";
7304   outs() << "   nsyms " << st.nsyms;
7305   uint64_t big_size;
7306   if (Is64Bit) {
7307     big_size = st.nsyms;
7308     big_size *= sizeof(struct MachO::nlist_64);
7309     big_size += st.symoff;
7310     if (big_size > object_size)
7311       outs() << " (past end of file)\n";
7312     else
7313       outs() << "\n";
7314   } else {
7315     big_size = st.nsyms;
7316     big_size *= sizeof(struct MachO::nlist);
7317     big_size += st.symoff;
7318     if (big_size > object_size)
7319       outs() << " (past end of file)\n";
7320     else
7321       outs() << "\n";
7322   }
7323   outs() << "  stroff " << st.stroff;
7324   if (st.stroff > object_size)
7325     outs() << " (past end of file)\n";
7326   else
7327     outs() << "\n";
7328   outs() << " strsize " << st.strsize;
7329   big_size = st.stroff;
7330   big_size += st.strsize;
7331   if (big_size > object_size)
7332     outs() << " (past end of file)\n";
7333   else
7334     outs() << "\n";
7335 }
7336 
7337 static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
7338                                      uint32_t nsyms, uint32_t object_size,
7339                                      bool Is64Bit) {
7340   outs() << "            cmd LC_DYSYMTAB\n";
7341   outs() << "        cmdsize " << dyst.cmdsize;
7342   if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
7343     outs() << " Incorrect size\n";
7344   else
7345     outs() << "\n";
7346   outs() << "      ilocalsym " << dyst.ilocalsym;
7347   if (dyst.ilocalsym > nsyms)
7348     outs() << " (greater than the number of symbols)\n";
7349   else
7350     outs() << "\n";
7351   outs() << "      nlocalsym " << dyst.nlocalsym;
7352   uint64_t big_size;
7353   big_size = dyst.ilocalsym;
7354   big_size += dyst.nlocalsym;
7355   if (big_size > nsyms)
7356     outs() << " (past the end of the symbol table)\n";
7357   else
7358     outs() << "\n";
7359   outs() << "     iextdefsym " << dyst.iextdefsym;
7360   if (dyst.iextdefsym > nsyms)
7361     outs() << " (greater than the number of symbols)\n";
7362   else
7363     outs() << "\n";
7364   outs() << "     nextdefsym " << dyst.nextdefsym;
7365   big_size = dyst.iextdefsym;
7366   big_size += dyst.nextdefsym;
7367   if (big_size > nsyms)
7368     outs() << " (past the end of the symbol table)\n";
7369   else
7370     outs() << "\n";
7371   outs() << "      iundefsym " << dyst.iundefsym;
7372   if (dyst.iundefsym > nsyms)
7373     outs() << " (greater than the number of symbols)\n";
7374   else
7375     outs() << "\n";
7376   outs() << "      nundefsym " << dyst.nundefsym;
7377   big_size = dyst.iundefsym;
7378   big_size += dyst.nundefsym;
7379   if (big_size > nsyms)
7380     outs() << " (past the end of the symbol table)\n";
7381   else
7382     outs() << "\n";
7383   outs() << "         tocoff " << dyst.tocoff;
7384   if (dyst.tocoff > object_size)
7385     outs() << " (past end of file)\n";
7386   else
7387     outs() << "\n";
7388   outs() << "           ntoc " << dyst.ntoc;
7389   big_size = dyst.ntoc;
7390   big_size *= sizeof(struct MachO::dylib_table_of_contents);
7391   big_size += dyst.tocoff;
7392   if (big_size > object_size)
7393     outs() << " (past end of file)\n";
7394   else
7395     outs() << "\n";
7396   outs() << "      modtaboff " << dyst.modtaboff;
7397   if (dyst.modtaboff > object_size)
7398     outs() << " (past end of file)\n";
7399   else
7400     outs() << "\n";
7401   outs() << "        nmodtab " << dyst.nmodtab;
7402   uint64_t modtabend;
7403   if (Is64Bit) {
7404     modtabend = dyst.nmodtab;
7405     modtabend *= sizeof(struct MachO::dylib_module_64);
7406     modtabend += dyst.modtaboff;
7407   } else {
7408     modtabend = dyst.nmodtab;
7409     modtabend *= sizeof(struct MachO::dylib_module);
7410     modtabend += dyst.modtaboff;
7411   }
7412   if (modtabend > object_size)
7413     outs() << " (past end of file)\n";
7414   else
7415     outs() << "\n";
7416   outs() << "   extrefsymoff " << dyst.extrefsymoff;
7417   if (dyst.extrefsymoff > object_size)
7418     outs() << " (past end of file)\n";
7419   else
7420     outs() << "\n";
7421   outs() << "    nextrefsyms " << dyst.nextrefsyms;
7422   big_size = dyst.nextrefsyms;
7423   big_size *= sizeof(struct MachO::dylib_reference);
7424   big_size += dyst.extrefsymoff;
7425   if (big_size > object_size)
7426     outs() << " (past end of file)\n";
7427   else
7428     outs() << "\n";
7429   outs() << " indirectsymoff " << dyst.indirectsymoff;
7430   if (dyst.indirectsymoff > object_size)
7431     outs() << " (past end of file)\n";
7432   else
7433     outs() << "\n";
7434   outs() << "  nindirectsyms " << dyst.nindirectsyms;
7435   big_size = dyst.nindirectsyms;
7436   big_size *= sizeof(uint32_t);
7437   big_size += dyst.indirectsymoff;
7438   if (big_size > object_size)
7439     outs() << " (past end of file)\n";
7440   else
7441     outs() << "\n";
7442   outs() << "      extreloff " << dyst.extreloff;
7443   if (dyst.extreloff > object_size)
7444     outs() << " (past end of file)\n";
7445   else
7446     outs() << "\n";
7447   outs() << "        nextrel " << dyst.nextrel;
7448   big_size = dyst.nextrel;
7449   big_size *= sizeof(struct MachO::relocation_info);
7450   big_size += dyst.extreloff;
7451   if (big_size > object_size)
7452     outs() << " (past end of file)\n";
7453   else
7454     outs() << "\n";
7455   outs() << "      locreloff " << dyst.locreloff;
7456   if (dyst.locreloff > object_size)
7457     outs() << " (past end of file)\n";
7458   else
7459     outs() << "\n";
7460   outs() << "        nlocrel " << dyst.nlocrel;
7461   big_size = dyst.nlocrel;
7462   big_size *= sizeof(struct MachO::relocation_info);
7463   big_size += dyst.locreloff;
7464   if (big_size > object_size)
7465     outs() << " (past end of file)\n";
7466   else
7467     outs() << "\n";
7468 }
7469 
7470 static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
7471                                      uint32_t object_size) {
7472   if (dc.cmd == MachO::LC_DYLD_INFO)
7473     outs() << "            cmd LC_DYLD_INFO\n";
7474   else
7475     outs() << "            cmd LC_DYLD_INFO_ONLY\n";
7476   outs() << "        cmdsize " << dc.cmdsize;
7477   if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
7478     outs() << " Incorrect size\n";
7479   else
7480     outs() << "\n";
7481   outs() << "     rebase_off " << dc.rebase_off;
7482   if (dc.rebase_off > object_size)
7483     outs() << " (past end of file)\n";
7484   else
7485     outs() << "\n";
7486   outs() << "    rebase_size " << dc.rebase_size;
7487   uint64_t big_size;
7488   big_size = dc.rebase_off;
7489   big_size += dc.rebase_size;
7490   if (big_size > object_size)
7491     outs() << " (past end of file)\n";
7492   else
7493     outs() << "\n";
7494   outs() << "       bind_off " << dc.bind_off;
7495   if (dc.bind_off > object_size)
7496     outs() << " (past end of file)\n";
7497   else
7498     outs() << "\n";
7499   outs() << "      bind_size " << dc.bind_size;
7500   big_size = dc.bind_off;
7501   big_size += dc.bind_size;
7502   if (big_size > object_size)
7503     outs() << " (past end of file)\n";
7504   else
7505     outs() << "\n";
7506   outs() << "  weak_bind_off " << dc.weak_bind_off;
7507   if (dc.weak_bind_off > object_size)
7508     outs() << " (past end of file)\n";
7509   else
7510     outs() << "\n";
7511   outs() << " weak_bind_size " << dc.weak_bind_size;
7512   big_size = dc.weak_bind_off;
7513   big_size += dc.weak_bind_size;
7514   if (big_size > object_size)
7515     outs() << " (past end of file)\n";
7516   else
7517     outs() << "\n";
7518   outs() << "  lazy_bind_off " << dc.lazy_bind_off;
7519   if (dc.lazy_bind_off > object_size)
7520     outs() << " (past end of file)\n";
7521   else
7522     outs() << "\n";
7523   outs() << " lazy_bind_size " << dc.lazy_bind_size;
7524   big_size = dc.lazy_bind_off;
7525   big_size += dc.lazy_bind_size;
7526   if (big_size > object_size)
7527     outs() << " (past end of file)\n";
7528   else
7529     outs() << "\n";
7530   outs() << "     export_off " << dc.export_off;
7531   if (dc.export_off > object_size)
7532     outs() << " (past end of file)\n";
7533   else
7534     outs() << "\n";
7535   outs() << "    export_size " << dc.export_size;
7536   big_size = dc.export_off;
7537   big_size += dc.export_size;
7538   if (big_size > object_size)
7539     outs() << " (past end of file)\n";
7540   else
7541     outs() << "\n";
7542 }
7543 
7544 static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
7545                                  const char *Ptr) {
7546   if (dyld.cmd == MachO::LC_ID_DYLINKER)
7547     outs() << "          cmd LC_ID_DYLINKER\n";
7548   else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
7549     outs() << "          cmd LC_LOAD_DYLINKER\n";
7550   else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
7551     outs() << "          cmd LC_DYLD_ENVIRONMENT\n";
7552   else
7553     outs() << "          cmd ?(" << dyld.cmd << ")\n";
7554   outs() << "      cmdsize " << dyld.cmdsize;
7555   if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
7556     outs() << " Incorrect size\n";
7557   else
7558     outs() << "\n";
7559   if (dyld.name >= dyld.cmdsize)
7560     outs() << "         name ?(bad offset " << dyld.name << ")\n";
7561   else {
7562     const char *P = (const char *)(Ptr) + dyld.name;
7563     outs() << "         name " << P << " (offset " << dyld.name << ")\n";
7564   }
7565 }
7566 
7567 static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
7568   outs() << "     cmd LC_UUID\n";
7569   outs() << " cmdsize " << uuid.cmdsize;
7570   if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
7571     outs() << " Incorrect size\n";
7572   else
7573     outs() << "\n";
7574   outs() << "    uuid ";
7575   for (int i = 0; i < 16; ++i) {
7576     outs() << format("%02" PRIX32, uuid.uuid[i]);
7577     if (i == 3 || i == 5 || i == 7 || i == 9)
7578       outs() << "-";
7579   }
7580   outs() << "\n";
7581 }
7582 
7583 static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
7584   outs() << "          cmd LC_RPATH\n";
7585   outs() << "      cmdsize " << rpath.cmdsize;
7586   if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
7587     outs() << " Incorrect size\n";
7588   else
7589     outs() << "\n";
7590   if (rpath.path >= rpath.cmdsize)
7591     outs() << "         path ?(bad offset " << rpath.path << ")\n";
7592   else {
7593     const char *P = (const char *)(Ptr) + rpath.path;
7594     outs() << "         path " << P << " (offset " << rpath.path << ")\n";
7595   }
7596 }
7597 
7598 static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
7599   StringRef LoadCmdName;
7600   switch (vd.cmd) {
7601   case MachO::LC_VERSION_MIN_MACOSX:
7602     LoadCmdName = "LC_VERSION_MIN_MACOSX";
7603     break;
7604   case MachO::LC_VERSION_MIN_IPHONEOS:
7605     LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
7606     break;
7607   case MachO::LC_VERSION_MIN_TVOS:
7608     LoadCmdName = "LC_VERSION_MIN_TVOS";
7609     break;
7610   case MachO::LC_VERSION_MIN_WATCHOS:
7611     LoadCmdName = "LC_VERSION_MIN_WATCHOS";
7612     break;
7613   default:
7614     llvm_unreachable("Unknown version min load command");
7615   }
7616 
7617   outs() << "      cmd " << LoadCmdName << '\n';
7618   outs() << "  cmdsize " << vd.cmdsize;
7619   if (vd.cmdsize != sizeof(struct MachO::version_min_command))
7620     outs() << " Incorrect size\n";
7621   else
7622     outs() << "\n";
7623   outs() << "  version "
7624          << MachOObjectFile::getVersionMinMajor(vd, false) << "."
7625          << MachOObjectFile::getVersionMinMinor(vd, false);
7626   uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
7627   if (Update != 0)
7628     outs() << "." << Update;
7629   outs() << "\n";
7630   if (vd.sdk == 0)
7631     outs() << "      sdk n/a";
7632   else {
7633     outs() << "      sdk "
7634            << MachOObjectFile::getVersionMinMajor(vd, true) << "."
7635            << MachOObjectFile::getVersionMinMinor(vd, true);
7636   }
7637   Update = MachOObjectFile::getVersionMinUpdate(vd, true);
7638   if (Update != 0)
7639     outs() << "." << Update;
7640   outs() << "\n";
7641 }
7642 
7643 static void PrintSourceVersionCommand(MachO::source_version_command sd) {
7644   outs() << "      cmd LC_SOURCE_VERSION\n";
7645   outs() << "  cmdsize " << sd.cmdsize;
7646   if (sd.cmdsize != sizeof(struct MachO::source_version_command))
7647     outs() << " Incorrect size\n";
7648   else
7649     outs() << "\n";
7650   uint64_t a = (sd.version >> 40) & 0xffffff;
7651   uint64_t b = (sd.version >> 30) & 0x3ff;
7652   uint64_t c = (sd.version >> 20) & 0x3ff;
7653   uint64_t d = (sd.version >> 10) & 0x3ff;
7654   uint64_t e = sd.version & 0x3ff;
7655   outs() << "  version " << a << "." << b;
7656   if (e != 0)
7657     outs() << "." << c << "." << d << "." << e;
7658   else if (d != 0)
7659     outs() << "." << c << "." << d;
7660   else if (c != 0)
7661     outs() << "." << c;
7662   outs() << "\n";
7663 }
7664 
7665 static void PrintEntryPointCommand(MachO::entry_point_command ep) {
7666   outs() << "       cmd LC_MAIN\n";
7667   outs() << "   cmdsize " << ep.cmdsize;
7668   if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
7669     outs() << " Incorrect size\n";
7670   else
7671     outs() << "\n";
7672   outs() << "  entryoff " << ep.entryoff << "\n";
7673   outs() << " stacksize " << ep.stacksize << "\n";
7674 }
7675 
7676 static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
7677                                        uint32_t object_size) {
7678   outs() << "          cmd LC_ENCRYPTION_INFO\n";
7679   outs() << "      cmdsize " << ec.cmdsize;
7680   if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
7681     outs() << " Incorrect size\n";
7682   else
7683     outs() << "\n";
7684   outs() << "     cryptoff " << ec.cryptoff;
7685   if (ec.cryptoff > object_size)
7686     outs() << " (past end of file)\n";
7687   else
7688     outs() << "\n";
7689   outs() << "    cryptsize " << ec.cryptsize;
7690   if (ec.cryptsize > object_size)
7691     outs() << " (past end of file)\n";
7692   else
7693     outs() << "\n";
7694   outs() << "      cryptid " << ec.cryptid << "\n";
7695 }
7696 
7697 static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
7698                                          uint32_t object_size) {
7699   outs() << "          cmd LC_ENCRYPTION_INFO_64\n";
7700   outs() << "      cmdsize " << ec.cmdsize;
7701   if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
7702     outs() << " Incorrect size\n";
7703   else
7704     outs() << "\n";
7705   outs() << "     cryptoff " << ec.cryptoff;
7706   if (ec.cryptoff > object_size)
7707     outs() << " (past end of file)\n";
7708   else
7709     outs() << "\n";
7710   outs() << "    cryptsize " << ec.cryptsize;
7711   if (ec.cryptsize > object_size)
7712     outs() << " (past end of file)\n";
7713   else
7714     outs() << "\n";
7715   outs() << "      cryptid " << ec.cryptid << "\n";
7716   outs() << "          pad " << ec.pad << "\n";
7717 }
7718 
7719 static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
7720                                      const char *Ptr) {
7721   outs() << "     cmd LC_LINKER_OPTION\n";
7722   outs() << " cmdsize " << lo.cmdsize;
7723   if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
7724     outs() << " Incorrect size\n";
7725   else
7726     outs() << "\n";
7727   outs() << "   count " << lo.count << "\n";
7728   const char *string = Ptr + sizeof(struct MachO::linker_option_command);
7729   uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
7730   uint32_t i = 0;
7731   while (left > 0) {
7732     while (*string == '\0' && left > 0) {
7733       string++;
7734       left--;
7735     }
7736     if (left > 0) {
7737       i++;
7738       outs() << "  string #" << i << " " << format("%.*s\n", left, string);
7739       uint32_t NullPos = StringRef(string, left).find('\0');
7740       uint32_t len = std::min(NullPos, left) + 1;
7741       string += len;
7742       left -= len;
7743     }
7744   }
7745   if (lo.count != i)
7746     outs() << "   count " << lo.count << " does not match number of strings "
7747            << i << "\n";
7748 }
7749 
7750 static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
7751                                      const char *Ptr) {
7752   outs() << "          cmd LC_SUB_FRAMEWORK\n";
7753   outs() << "      cmdsize " << sub.cmdsize;
7754   if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
7755     outs() << " Incorrect size\n";
7756   else
7757     outs() << "\n";
7758   if (sub.umbrella < sub.cmdsize) {
7759     const char *P = Ptr + sub.umbrella;
7760     outs() << "     umbrella " << P << " (offset " << sub.umbrella << ")\n";
7761   } else {
7762     outs() << "     umbrella ?(bad offset " << sub.umbrella << ")\n";
7763   }
7764 }
7765 
7766 static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
7767                                     const char *Ptr) {
7768   outs() << "          cmd LC_SUB_UMBRELLA\n";
7769   outs() << "      cmdsize " << sub.cmdsize;
7770   if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
7771     outs() << " Incorrect size\n";
7772   else
7773     outs() << "\n";
7774   if (sub.sub_umbrella < sub.cmdsize) {
7775     const char *P = Ptr + sub.sub_umbrella;
7776     outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
7777   } else {
7778     outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
7779   }
7780 }
7781 
7782 static void PrintSubLibraryCommand(MachO::sub_library_command sub,
7783                                    const char *Ptr) {
7784   outs() << "          cmd LC_SUB_LIBRARY\n";
7785   outs() << "      cmdsize " << sub.cmdsize;
7786   if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
7787     outs() << " Incorrect size\n";
7788   else
7789     outs() << "\n";
7790   if (sub.sub_library < sub.cmdsize) {
7791     const char *P = Ptr + sub.sub_library;
7792     outs() << "  sub_library " << P << " (offset " << sub.sub_library << ")\n";
7793   } else {
7794     outs() << "  sub_library ?(bad offset " << sub.sub_library << ")\n";
7795   }
7796 }
7797 
7798 static void PrintSubClientCommand(MachO::sub_client_command sub,
7799                                   const char *Ptr) {
7800   outs() << "          cmd LC_SUB_CLIENT\n";
7801   outs() << "      cmdsize " << sub.cmdsize;
7802   if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
7803     outs() << " Incorrect size\n";
7804   else
7805     outs() << "\n";
7806   if (sub.client < sub.cmdsize) {
7807     const char *P = Ptr + sub.client;
7808     outs() << "       client " << P << " (offset " << sub.client << ")\n";
7809   } else {
7810     outs() << "       client ?(bad offset " << sub.client << ")\n";
7811   }
7812 }
7813 
7814 static void PrintRoutinesCommand(MachO::routines_command r) {
7815   outs() << "          cmd LC_ROUTINES\n";
7816   outs() << "      cmdsize " << r.cmdsize;
7817   if (r.cmdsize != sizeof(struct MachO::routines_command))
7818     outs() << " Incorrect size\n";
7819   else
7820     outs() << "\n";
7821   outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
7822   outs() << "  init_module " << r.init_module << "\n";
7823   outs() << "    reserved1 " << r.reserved1 << "\n";
7824   outs() << "    reserved2 " << r.reserved2 << "\n";
7825   outs() << "    reserved3 " << r.reserved3 << "\n";
7826   outs() << "    reserved4 " << r.reserved4 << "\n";
7827   outs() << "    reserved5 " << r.reserved5 << "\n";
7828   outs() << "    reserved6 " << r.reserved6 << "\n";
7829 }
7830 
7831 static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
7832   outs() << "          cmd LC_ROUTINES_64\n";
7833   outs() << "      cmdsize " << r.cmdsize;
7834   if (r.cmdsize != sizeof(struct MachO::routines_command_64))
7835     outs() << " Incorrect size\n";
7836   else
7837     outs() << "\n";
7838   outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
7839   outs() << "  init_module " << r.init_module << "\n";
7840   outs() << "    reserved1 " << r.reserved1 << "\n";
7841   outs() << "    reserved2 " << r.reserved2 << "\n";
7842   outs() << "    reserved3 " << r.reserved3 << "\n";
7843   outs() << "    reserved4 " << r.reserved4 << "\n";
7844   outs() << "    reserved5 " << r.reserved5 << "\n";
7845   outs() << "    reserved6 " << r.reserved6 << "\n";
7846 }
7847 
7848 static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
7849   outs() << "   rax  " << format("0x%016" PRIx64, cpu64.rax);
7850   outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
7851   outs() << " rcx  " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
7852   outs() << "   rdx  " << format("0x%016" PRIx64, cpu64.rdx);
7853   outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
7854   outs() << " rsi  " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
7855   outs() << "   rbp  " << format("0x%016" PRIx64, cpu64.rbp);
7856   outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
7857   outs() << " r8   " << format("0x%016" PRIx64, cpu64.r8) << "\n";
7858   outs() << "    r9  " << format("0x%016" PRIx64, cpu64.r9);
7859   outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
7860   outs() << " r11  " << format("0x%016" PRIx64, cpu64.r11) << "\n";
7861   outs() << "   r12  " << format("0x%016" PRIx64, cpu64.r12);
7862   outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
7863   outs() << " r14  " << format("0x%016" PRIx64, cpu64.r14) << "\n";
7864   outs() << "   r15  " << format("0x%016" PRIx64, cpu64.r15);
7865   outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
7866   outs() << "rflags  " << format("0x%016" PRIx64, cpu64.rflags);
7867   outs() << " cs  " << format("0x%016" PRIx64, cpu64.cs);
7868   outs() << " fs   " << format("0x%016" PRIx64, cpu64.fs) << "\n";
7869   outs() << "    gs  " << format("0x%016" PRIx64, cpu64.gs) << "\n";
7870 }
7871 
7872 static void Print_mmst_reg(MachO::mmst_reg_t &r) {
7873   uint32_t f;
7874   outs() << "\t      mmst_reg  ";
7875   for (f = 0; f < 10; f++)
7876     outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
7877   outs() << "\n";
7878   outs() << "\t      mmst_rsrv ";
7879   for (f = 0; f < 6; f++)
7880     outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
7881   outs() << "\n";
7882 }
7883 
7884 static void Print_xmm_reg(MachO::xmm_reg_t &r) {
7885   uint32_t f;
7886   outs() << "\t      xmm_reg ";
7887   for (f = 0; f < 16; f++)
7888     outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
7889   outs() << "\n";
7890 }
7891 
7892 static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
7893   outs() << "\t    fpu_reserved[0] " << fpu.fpu_reserved[0];
7894   outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
7895   outs() << "\t    control: invalid " << fpu.fpu_fcw.invalid;
7896   outs() << " denorm " << fpu.fpu_fcw.denorm;
7897   outs() << " zdiv " << fpu.fpu_fcw.zdiv;
7898   outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
7899   outs() << " undfl " << fpu.fpu_fcw.undfl;
7900   outs() << " precis " << fpu.fpu_fcw.precis << "\n";
7901   outs() << "\t\t     pc ";
7902   if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
7903     outs() << "FP_PREC_24B ";
7904   else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
7905     outs() << "FP_PREC_53B ";
7906   else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
7907     outs() << "FP_PREC_64B ";
7908   else
7909     outs() << fpu.fpu_fcw.pc << " ";
7910   outs() << "rc ";
7911   if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
7912     outs() << "FP_RND_NEAR ";
7913   else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
7914     outs() << "FP_RND_DOWN ";
7915   else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
7916     outs() << "FP_RND_UP ";
7917   else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
7918     outs() << "FP_CHOP ";
7919   outs() << "\n";
7920   outs() << "\t    status: invalid " << fpu.fpu_fsw.invalid;
7921   outs() << " denorm " << fpu.fpu_fsw.denorm;
7922   outs() << " zdiv " << fpu.fpu_fsw.zdiv;
7923   outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
7924   outs() << " undfl " << fpu.fpu_fsw.undfl;
7925   outs() << " precis " << fpu.fpu_fsw.precis;
7926   outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
7927   outs() << "\t            errsumm " << fpu.fpu_fsw.errsumm;
7928   outs() << " c0 " << fpu.fpu_fsw.c0;
7929   outs() << " c1 " << fpu.fpu_fsw.c1;
7930   outs() << " c2 " << fpu.fpu_fsw.c2;
7931   outs() << " tos " << fpu.fpu_fsw.tos;
7932   outs() << " c3 " << fpu.fpu_fsw.c3;
7933   outs() << " busy " << fpu.fpu_fsw.busy << "\n";
7934   outs() << "\t    fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
7935   outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
7936   outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
7937   outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
7938   outs() << "\t    fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
7939   outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
7940   outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
7941   outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
7942   outs() << "\t    fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
7943   outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
7944   outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
7945   outs() << "\n";
7946   outs() << "\t    fpu_stmm0:\n";
7947   Print_mmst_reg(fpu.fpu_stmm0);
7948   outs() << "\t    fpu_stmm1:\n";
7949   Print_mmst_reg(fpu.fpu_stmm1);
7950   outs() << "\t    fpu_stmm2:\n";
7951   Print_mmst_reg(fpu.fpu_stmm2);
7952   outs() << "\t    fpu_stmm3:\n";
7953   Print_mmst_reg(fpu.fpu_stmm3);
7954   outs() << "\t    fpu_stmm4:\n";
7955   Print_mmst_reg(fpu.fpu_stmm4);
7956   outs() << "\t    fpu_stmm5:\n";
7957   Print_mmst_reg(fpu.fpu_stmm5);
7958   outs() << "\t    fpu_stmm6:\n";
7959   Print_mmst_reg(fpu.fpu_stmm6);
7960   outs() << "\t    fpu_stmm7:\n";
7961   Print_mmst_reg(fpu.fpu_stmm7);
7962   outs() << "\t    fpu_xmm0:\n";
7963   Print_xmm_reg(fpu.fpu_xmm0);
7964   outs() << "\t    fpu_xmm1:\n";
7965   Print_xmm_reg(fpu.fpu_xmm1);
7966   outs() << "\t    fpu_xmm2:\n";
7967   Print_xmm_reg(fpu.fpu_xmm2);
7968   outs() << "\t    fpu_xmm3:\n";
7969   Print_xmm_reg(fpu.fpu_xmm3);
7970   outs() << "\t    fpu_xmm4:\n";
7971   Print_xmm_reg(fpu.fpu_xmm4);
7972   outs() << "\t    fpu_xmm5:\n";
7973   Print_xmm_reg(fpu.fpu_xmm5);
7974   outs() << "\t    fpu_xmm6:\n";
7975   Print_xmm_reg(fpu.fpu_xmm6);
7976   outs() << "\t    fpu_xmm7:\n";
7977   Print_xmm_reg(fpu.fpu_xmm7);
7978   outs() << "\t    fpu_xmm8:\n";
7979   Print_xmm_reg(fpu.fpu_xmm8);
7980   outs() << "\t    fpu_xmm9:\n";
7981   Print_xmm_reg(fpu.fpu_xmm9);
7982   outs() << "\t    fpu_xmm10:\n";
7983   Print_xmm_reg(fpu.fpu_xmm10);
7984   outs() << "\t    fpu_xmm11:\n";
7985   Print_xmm_reg(fpu.fpu_xmm11);
7986   outs() << "\t    fpu_xmm12:\n";
7987   Print_xmm_reg(fpu.fpu_xmm12);
7988   outs() << "\t    fpu_xmm13:\n";
7989   Print_xmm_reg(fpu.fpu_xmm13);
7990   outs() << "\t    fpu_xmm14:\n";
7991   Print_xmm_reg(fpu.fpu_xmm14);
7992   outs() << "\t    fpu_xmm15:\n";
7993   Print_xmm_reg(fpu.fpu_xmm15);
7994   outs() << "\t    fpu_rsrv4:\n";
7995   for (uint32_t f = 0; f < 6; f++) {
7996     outs() << "\t            ";
7997     for (uint32_t g = 0; g < 16; g++)
7998       outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
7999     outs() << "\n";
8000   }
8001   outs() << "\t    fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
8002   outs() << "\n";
8003 }
8004 
8005 static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
8006   outs() << "\t    trapno " << format("0x%08" PRIx32, exc64.trapno);
8007   outs() << " err " << format("0x%08" PRIx32, exc64.err);
8008   outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
8009 }
8010 
8011 static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
8012                                bool isLittleEndian, uint32_t cputype) {
8013   if (t.cmd == MachO::LC_THREAD)
8014     outs() << "        cmd LC_THREAD\n";
8015   else if (t.cmd == MachO::LC_UNIXTHREAD)
8016     outs() << "        cmd LC_UNIXTHREAD\n";
8017   else
8018     outs() << "        cmd " << t.cmd << " (unknown)\n";
8019   outs() << "    cmdsize " << t.cmdsize;
8020   if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
8021     outs() << " Incorrect size\n";
8022   else
8023     outs() << "\n";
8024 
8025   const char *begin = Ptr + sizeof(struct MachO::thread_command);
8026   const char *end = Ptr + t.cmdsize;
8027   uint32_t flavor, count, left;
8028   if (cputype == MachO::CPU_TYPE_X86_64) {
8029     while (begin < end) {
8030       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8031         memcpy((char *)&flavor, begin, sizeof(uint32_t));
8032         begin += sizeof(uint32_t);
8033       } else {
8034         flavor = 0;
8035         begin = end;
8036       }
8037       if (isLittleEndian != sys::IsLittleEndianHost)
8038         sys::swapByteOrder(flavor);
8039       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8040         memcpy((char *)&count, begin, sizeof(uint32_t));
8041         begin += sizeof(uint32_t);
8042       } else {
8043         count = 0;
8044         begin = end;
8045       }
8046       if (isLittleEndian != sys::IsLittleEndianHost)
8047         sys::swapByteOrder(count);
8048       if (flavor == MachO::x86_THREAD_STATE64) {
8049         outs() << "     flavor x86_THREAD_STATE64\n";
8050         if (count == MachO::x86_THREAD_STATE64_COUNT)
8051           outs() << "      count x86_THREAD_STATE64_COUNT\n";
8052         else
8053           outs() << "      count " << count
8054                  << " (not x86_THREAD_STATE64_COUNT)\n";
8055         MachO::x86_thread_state64_t cpu64;
8056         left = end - begin;
8057         if (left >= sizeof(MachO::x86_thread_state64_t)) {
8058           memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
8059           begin += sizeof(MachO::x86_thread_state64_t);
8060         } else {
8061           memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
8062           memcpy(&cpu64, begin, left);
8063           begin += left;
8064         }
8065         if (isLittleEndian != sys::IsLittleEndianHost)
8066           swapStruct(cpu64);
8067         Print_x86_thread_state64_t(cpu64);
8068       } else if (flavor == MachO::x86_THREAD_STATE) {
8069         outs() << "     flavor x86_THREAD_STATE\n";
8070         if (count == MachO::x86_THREAD_STATE_COUNT)
8071           outs() << "      count x86_THREAD_STATE_COUNT\n";
8072         else
8073           outs() << "      count " << count
8074                  << " (not x86_THREAD_STATE_COUNT)\n";
8075         struct MachO::x86_thread_state_t ts;
8076         left = end - begin;
8077         if (left >= sizeof(MachO::x86_thread_state_t)) {
8078           memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
8079           begin += sizeof(MachO::x86_thread_state_t);
8080         } else {
8081           memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
8082           memcpy(&ts, begin, left);
8083           begin += left;
8084         }
8085         if (isLittleEndian != sys::IsLittleEndianHost)
8086           swapStruct(ts);
8087         if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
8088           outs() << "\t    tsh.flavor x86_THREAD_STATE64 ";
8089           if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
8090             outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
8091           else
8092             outs() << "tsh.count " << ts.tsh.count
8093                    << " (not x86_THREAD_STATE64_COUNT\n";
8094           Print_x86_thread_state64_t(ts.uts.ts64);
8095         } else {
8096           outs() << "\t    tsh.flavor " << ts.tsh.flavor << "  tsh.count "
8097                  << ts.tsh.count << "\n";
8098         }
8099       } else if (flavor == MachO::x86_FLOAT_STATE) {
8100         outs() << "     flavor x86_FLOAT_STATE\n";
8101         if (count == MachO::x86_FLOAT_STATE_COUNT)
8102           outs() << "      count x86_FLOAT_STATE_COUNT\n";
8103         else
8104           outs() << "      count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
8105         struct MachO::x86_float_state_t fs;
8106         left = end - begin;
8107         if (left >= sizeof(MachO::x86_float_state_t)) {
8108           memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
8109           begin += sizeof(MachO::x86_float_state_t);
8110         } else {
8111           memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
8112           memcpy(&fs, begin, left);
8113           begin += left;
8114         }
8115         if (isLittleEndian != sys::IsLittleEndianHost)
8116           swapStruct(fs);
8117         if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
8118           outs() << "\t    fsh.flavor x86_FLOAT_STATE64 ";
8119           if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
8120             outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
8121           else
8122             outs() << "fsh.count " << fs.fsh.count
8123                    << " (not x86_FLOAT_STATE64_COUNT\n";
8124           Print_x86_float_state_t(fs.ufs.fs64);
8125         } else {
8126           outs() << "\t    fsh.flavor " << fs.fsh.flavor << "  fsh.count "
8127                  << fs.fsh.count << "\n";
8128         }
8129       } else if (flavor == MachO::x86_EXCEPTION_STATE) {
8130         outs() << "     flavor x86_EXCEPTION_STATE\n";
8131         if (count == MachO::x86_EXCEPTION_STATE_COUNT)
8132           outs() << "      count x86_EXCEPTION_STATE_COUNT\n";
8133         else
8134           outs() << "      count " << count
8135                  << " (not x86_EXCEPTION_STATE_COUNT)\n";
8136         struct MachO::x86_exception_state_t es;
8137         left = end - begin;
8138         if (left >= sizeof(MachO::x86_exception_state_t)) {
8139           memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
8140           begin += sizeof(MachO::x86_exception_state_t);
8141         } else {
8142           memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
8143           memcpy(&es, begin, left);
8144           begin += left;
8145         }
8146         if (isLittleEndian != sys::IsLittleEndianHost)
8147           swapStruct(es);
8148         if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
8149           outs() << "\t    esh.flavor x86_EXCEPTION_STATE64\n";
8150           if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
8151             outs() << "\t    esh.count x86_EXCEPTION_STATE64_COUNT\n";
8152           else
8153             outs() << "\t    esh.count " << es.esh.count
8154                    << " (not x86_EXCEPTION_STATE64_COUNT\n";
8155           Print_x86_exception_state_t(es.ues.es64);
8156         } else {
8157           outs() << "\t    esh.flavor " << es.esh.flavor << "  esh.count "
8158                  << es.esh.count << "\n";
8159         }
8160       } else {
8161         outs() << "     flavor " << flavor << " (unknown)\n";
8162         outs() << "      count " << count << "\n";
8163         outs() << "      state (unknown)\n";
8164         begin += count * sizeof(uint32_t);
8165       }
8166     }
8167   } else {
8168     while (begin < end) {
8169       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8170         memcpy((char *)&flavor, begin, sizeof(uint32_t));
8171         begin += sizeof(uint32_t);
8172       } else {
8173         flavor = 0;
8174         begin = end;
8175       }
8176       if (isLittleEndian != sys::IsLittleEndianHost)
8177         sys::swapByteOrder(flavor);
8178       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8179         memcpy((char *)&count, begin, sizeof(uint32_t));
8180         begin += sizeof(uint32_t);
8181       } else {
8182         count = 0;
8183         begin = end;
8184       }
8185       if (isLittleEndian != sys::IsLittleEndianHost)
8186         sys::swapByteOrder(count);
8187       outs() << "     flavor " << flavor << "\n";
8188       outs() << "      count " << count << "\n";
8189       outs() << "      state (Unknown cputype/cpusubtype)\n";
8190       begin += count * sizeof(uint32_t);
8191     }
8192   }
8193 }
8194 
8195 static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
8196   if (dl.cmd == MachO::LC_ID_DYLIB)
8197     outs() << "          cmd LC_ID_DYLIB\n";
8198   else if (dl.cmd == MachO::LC_LOAD_DYLIB)
8199     outs() << "          cmd LC_LOAD_DYLIB\n";
8200   else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
8201     outs() << "          cmd LC_LOAD_WEAK_DYLIB\n";
8202   else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
8203     outs() << "          cmd LC_REEXPORT_DYLIB\n";
8204   else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
8205     outs() << "          cmd LC_LAZY_LOAD_DYLIB\n";
8206   else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
8207     outs() << "          cmd LC_LOAD_UPWARD_DYLIB\n";
8208   else
8209     outs() << "          cmd " << dl.cmd << " (unknown)\n";
8210   outs() << "      cmdsize " << dl.cmdsize;
8211   if (dl.cmdsize < sizeof(struct MachO::dylib_command))
8212     outs() << " Incorrect size\n";
8213   else
8214     outs() << "\n";
8215   if (dl.dylib.name < dl.cmdsize) {
8216     const char *P = (const char *)(Ptr) + dl.dylib.name;
8217     outs() << "         name " << P << " (offset " << dl.dylib.name << ")\n";
8218   } else {
8219     outs() << "         name ?(bad offset " << dl.dylib.name << ")\n";
8220   }
8221   outs() << "   time stamp " << dl.dylib.timestamp << " ";
8222   time_t t = dl.dylib.timestamp;
8223   outs() << ctime(&t);
8224   outs() << "      current version ";
8225   if (dl.dylib.current_version == 0xffffffff)
8226     outs() << "n/a\n";
8227   else
8228     outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
8229            << ((dl.dylib.current_version >> 8) & 0xff) << "."
8230            << (dl.dylib.current_version & 0xff) << "\n";
8231   outs() << "compatibility version ";
8232   if (dl.dylib.compatibility_version == 0xffffffff)
8233     outs() << "n/a\n";
8234   else
8235     outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
8236            << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
8237            << (dl.dylib.compatibility_version & 0xff) << "\n";
8238 }
8239 
8240 static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
8241                                      uint32_t object_size) {
8242   if (ld.cmd == MachO::LC_CODE_SIGNATURE)
8243     outs() << "      cmd LC_FUNCTION_STARTS\n";
8244   else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
8245     outs() << "      cmd LC_SEGMENT_SPLIT_INFO\n";
8246   else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
8247     outs() << "      cmd LC_FUNCTION_STARTS\n";
8248   else if (ld.cmd == MachO::LC_DATA_IN_CODE)
8249     outs() << "      cmd LC_DATA_IN_CODE\n";
8250   else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
8251     outs() << "      cmd LC_DYLIB_CODE_SIGN_DRS\n";
8252   else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
8253     outs() << "      cmd LC_LINKER_OPTIMIZATION_HINT\n";
8254   else
8255     outs() << "      cmd " << ld.cmd << " (?)\n";
8256   outs() << "  cmdsize " << ld.cmdsize;
8257   if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
8258     outs() << " Incorrect size\n";
8259   else
8260     outs() << "\n";
8261   outs() << "  dataoff " << ld.dataoff;
8262   if (ld.dataoff > object_size)
8263     outs() << " (past end of file)\n";
8264   else
8265     outs() << "\n";
8266   outs() << " datasize " << ld.datasize;
8267   uint64_t big_size = ld.dataoff;
8268   big_size += ld.datasize;
8269   if (big_size > object_size)
8270     outs() << " (past end of file)\n";
8271   else
8272     outs() << "\n";
8273 }
8274 
8275 static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
8276                               uint32_t cputype, bool verbose) {
8277   StringRef Buf = Obj->getData();
8278   unsigned Index = 0;
8279   for (const auto &Command : Obj->load_commands()) {
8280     outs() << "Load command " << Index++ << "\n";
8281     if (Command.C.cmd == MachO::LC_SEGMENT) {
8282       MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
8283       const char *sg_segname = SLC.segname;
8284       PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
8285                           SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
8286                           SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
8287                           verbose);
8288       for (unsigned j = 0; j < SLC.nsects; j++) {
8289         MachO::section S = Obj->getSection(Command, j);
8290         PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
8291                      S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
8292                      SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
8293       }
8294     } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
8295       MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
8296       const char *sg_segname = SLC_64.segname;
8297       PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
8298                           SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
8299                           SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
8300                           SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
8301       for (unsigned j = 0; j < SLC_64.nsects; j++) {
8302         MachO::section_64 S_64 = Obj->getSection64(Command, j);
8303         PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
8304                      S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
8305                      S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
8306                      sg_segname, filetype, Buf.size(), verbose);
8307       }
8308     } else if (Command.C.cmd == MachO::LC_SYMTAB) {
8309       MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
8310       PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
8311     } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
8312       MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
8313       MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
8314       PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
8315                                Obj->is64Bit());
8316     } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
8317                Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
8318       MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
8319       PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
8320     } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
8321                Command.C.cmd == MachO::LC_ID_DYLINKER ||
8322                Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
8323       MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
8324       PrintDyldLoadCommand(Dyld, Command.Ptr);
8325     } else if (Command.C.cmd == MachO::LC_UUID) {
8326       MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
8327       PrintUuidLoadCommand(Uuid);
8328     } else if (Command.C.cmd == MachO::LC_RPATH) {
8329       MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
8330       PrintRpathLoadCommand(Rpath, Command.Ptr);
8331     } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
8332                Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
8333                Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
8334                Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
8335       MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
8336       PrintVersionMinLoadCommand(Vd);
8337     } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
8338       MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
8339       PrintSourceVersionCommand(Sd);
8340     } else if (Command.C.cmd == MachO::LC_MAIN) {
8341       MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
8342       PrintEntryPointCommand(Ep);
8343     } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
8344       MachO::encryption_info_command Ei =
8345           Obj->getEncryptionInfoCommand(Command);
8346       PrintEncryptionInfoCommand(Ei, Buf.size());
8347     } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
8348       MachO::encryption_info_command_64 Ei =
8349           Obj->getEncryptionInfoCommand64(Command);
8350       PrintEncryptionInfoCommand64(Ei, Buf.size());
8351     } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
8352       MachO::linker_option_command Lo =
8353           Obj->getLinkerOptionLoadCommand(Command);
8354       PrintLinkerOptionCommand(Lo, Command.Ptr);
8355     } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
8356       MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
8357       PrintSubFrameworkCommand(Sf, Command.Ptr);
8358     } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
8359       MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
8360       PrintSubUmbrellaCommand(Sf, Command.Ptr);
8361     } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
8362       MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
8363       PrintSubLibraryCommand(Sl, Command.Ptr);
8364     } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
8365       MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
8366       PrintSubClientCommand(Sc, Command.Ptr);
8367     } else if (Command.C.cmd == MachO::LC_ROUTINES) {
8368       MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
8369       PrintRoutinesCommand(Rc);
8370     } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
8371       MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
8372       PrintRoutinesCommand64(Rc);
8373     } else if (Command.C.cmd == MachO::LC_THREAD ||
8374                Command.C.cmd == MachO::LC_UNIXTHREAD) {
8375       MachO::thread_command Tc = Obj->getThreadCommand(Command);
8376       PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
8377     } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
8378                Command.C.cmd == MachO::LC_ID_DYLIB ||
8379                Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
8380                Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
8381                Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
8382                Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
8383       MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
8384       PrintDylibCommand(Dl, Command.Ptr);
8385     } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
8386                Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
8387                Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
8388                Command.C.cmd == MachO::LC_DATA_IN_CODE ||
8389                Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
8390                Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
8391       MachO::linkedit_data_command Ld =
8392           Obj->getLinkeditDataLoadCommand(Command);
8393       PrintLinkEditDataCommand(Ld, Buf.size());
8394     } else {
8395       outs() << "      cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
8396              << ")\n";
8397       outs() << "  cmdsize " << Command.C.cmdsize << "\n";
8398       // TODO: get and print the raw bytes of the load command.
8399     }
8400     // TODO: print all the other kinds of load commands.
8401   }
8402 }
8403 
8404 static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
8405   if (Obj->is64Bit()) {
8406     MachO::mach_header_64 H_64;
8407     H_64 = Obj->getHeader64();
8408     PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
8409                     H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
8410   } else {
8411     MachO::mach_header H;
8412     H = Obj->getHeader();
8413     PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
8414                     H.sizeofcmds, H.flags, verbose);
8415   }
8416 }
8417 
8418 void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
8419   const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
8420   PrintMachHeader(file, !NonVerbose);
8421 }
8422 
8423 void llvm::printMachOLoadCommands(const object::ObjectFile *Obj) {
8424   const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
8425   uint32_t filetype = 0;
8426   uint32_t cputype = 0;
8427   if (file->is64Bit()) {
8428     MachO::mach_header_64 H_64;
8429     H_64 = file->getHeader64();
8430     filetype = H_64.filetype;
8431     cputype = H_64.cputype;
8432   } else {
8433     MachO::mach_header H;
8434     H = file->getHeader();
8435     filetype = H.filetype;
8436     cputype = H.cputype;
8437   }
8438   PrintLoadCommands(file, filetype, cputype, !NonVerbose);
8439 }
8440 
8441 //===----------------------------------------------------------------------===//
8442 // export trie dumping
8443 //===----------------------------------------------------------------------===//
8444 
8445 void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
8446   for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
8447     uint64_t Flags = Entry.flags();
8448     bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
8449     bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
8450     bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
8451                         MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
8452     bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
8453                 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
8454     bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
8455     if (ReExport)
8456       outs() << "[re-export] ";
8457     else
8458       outs() << format("0x%08llX  ",
8459                        Entry.address()); // FIXME:add in base address
8460     outs() << Entry.name();
8461     if (WeakDef || ThreadLocal || Resolver || Abs) {
8462       bool NeedsComma = false;
8463       outs() << " [";
8464       if (WeakDef) {
8465         outs() << "weak_def";
8466         NeedsComma = true;
8467       }
8468       if (ThreadLocal) {
8469         if (NeedsComma)
8470           outs() << ", ";
8471         outs() << "per-thread";
8472         NeedsComma = true;
8473       }
8474       if (Abs) {
8475         if (NeedsComma)
8476           outs() << ", ";
8477         outs() << "absolute";
8478         NeedsComma = true;
8479       }
8480       if (Resolver) {
8481         if (NeedsComma)
8482           outs() << ", ";
8483         outs() << format("resolver=0x%08llX", Entry.other());
8484         NeedsComma = true;
8485       }
8486       outs() << "]";
8487     }
8488     if (ReExport) {
8489       StringRef DylibName = "unknown";
8490       int Ordinal = Entry.other() - 1;
8491       Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
8492       if (Entry.otherName().empty())
8493         outs() << " (from " << DylibName << ")";
8494       else
8495         outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
8496     }
8497     outs() << "\n";
8498   }
8499 }
8500 
8501 //===----------------------------------------------------------------------===//
8502 // rebase table dumping
8503 //===----------------------------------------------------------------------===//
8504 
8505 namespace {
8506 class SegInfo {
8507 public:
8508   SegInfo(const object::MachOObjectFile *Obj);
8509 
8510   StringRef segmentName(uint32_t SegIndex);
8511   StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
8512   uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
8513   bool isValidSegIndexAndOffset(uint32_t SegIndex, uint64_t SegOffset);
8514 
8515 private:
8516   struct SectionInfo {
8517     uint64_t Address;
8518     uint64_t Size;
8519     StringRef SectionName;
8520     StringRef SegmentName;
8521     uint64_t OffsetInSegment;
8522     uint64_t SegmentStartAddress;
8523     uint32_t SegmentIndex;
8524   };
8525   const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
8526   SmallVector<SectionInfo, 32> Sections;
8527 };
8528 }
8529 
8530 SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
8531   // Build table of sections so segIndex/offset pairs can be translated.
8532   uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
8533   StringRef CurSegName;
8534   uint64_t CurSegAddress;
8535   for (const SectionRef &Section : Obj->sections()) {
8536     SectionInfo Info;
8537     error(Section.getName(Info.SectionName));
8538     Info.Address = Section.getAddress();
8539     Info.Size = Section.getSize();
8540     Info.SegmentName =
8541         Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
8542     if (!Info.SegmentName.equals(CurSegName)) {
8543       ++CurSegIndex;
8544       CurSegName = Info.SegmentName;
8545       CurSegAddress = Info.Address;
8546     }
8547     Info.SegmentIndex = CurSegIndex - 1;
8548     Info.OffsetInSegment = Info.Address - CurSegAddress;
8549     Info.SegmentStartAddress = CurSegAddress;
8550     Sections.push_back(Info);
8551   }
8552 }
8553 
8554 StringRef SegInfo::segmentName(uint32_t SegIndex) {
8555   for (const SectionInfo &SI : Sections) {
8556     if (SI.SegmentIndex == SegIndex)
8557       return SI.SegmentName;
8558   }
8559   llvm_unreachable("invalid segIndex");
8560 }
8561 
8562 bool SegInfo::isValidSegIndexAndOffset(uint32_t SegIndex,
8563                                        uint64_t OffsetInSeg) {
8564   for (const SectionInfo &SI : Sections) {
8565     if (SI.SegmentIndex != SegIndex)
8566       continue;
8567     if (SI.OffsetInSegment > OffsetInSeg)
8568       continue;
8569     if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
8570       continue;
8571     return true;
8572   }
8573   return false;
8574 }
8575 
8576 const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
8577                                                  uint64_t OffsetInSeg) {
8578   for (const SectionInfo &SI : Sections) {
8579     if (SI.SegmentIndex != SegIndex)
8580       continue;
8581     if (SI.OffsetInSegment > OffsetInSeg)
8582       continue;
8583     if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
8584       continue;
8585     return SI;
8586   }
8587   llvm_unreachable("segIndex and offset not in any section");
8588 }
8589 
8590 StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
8591   return findSection(SegIndex, OffsetInSeg).SectionName;
8592 }
8593 
8594 uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
8595   const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
8596   return SI.SegmentStartAddress + OffsetInSeg;
8597 }
8598 
8599 void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
8600   // Build table of sections so names can used in final output.
8601   SegInfo sectionTable(Obj);
8602 
8603   outs() << "segment  section            address     type\n";
8604   for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
8605     uint32_t SegIndex = Entry.segmentIndex();
8606     uint64_t OffsetInSeg = Entry.segmentOffset();
8607     StringRef SegmentName = sectionTable.segmentName(SegIndex);
8608     StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8609     uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8610 
8611     // Table lines look like: __DATA  __nl_symbol_ptr  0x0000F00C  pointer
8612     outs() << format("%-8s %-18s 0x%08" PRIX64 "  %s\n",
8613                      SegmentName.str().c_str(), SectionName.str().c_str(),
8614                      Address, Entry.typeName().str().c_str());
8615   }
8616 }
8617 
8618 static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
8619   StringRef DylibName;
8620   switch (Ordinal) {
8621   case MachO::BIND_SPECIAL_DYLIB_SELF:
8622     return "this-image";
8623   case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
8624     return "main-executable";
8625   case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
8626     return "flat-namespace";
8627   default:
8628     if (Ordinal > 0) {
8629       std::error_code EC =
8630           Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
8631       if (EC)
8632         return "<<bad library ordinal>>";
8633       return DylibName;
8634     }
8635   }
8636   return "<<unknown special ordinal>>";
8637 }
8638 
8639 //===----------------------------------------------------------------------===//
8640 // bind table dumping
8641 //===----------------------------------------------------------------------===//
8642 
8643 void llvm::printMachOBindTable(const object::MachOObjectFile *Obj) {
8644   // Build table of sections so names can used in final output.
8645   SegInfo sectionTable(Obj);
8646 
8647   outs() << "segment  section            address    type       "
8648             "addend dylib            symbol\n";
8649   for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
8650     uint32_t SegIndex = Entry.segmentIndex();
8651     uint64_t OffsetInSeg = Entry.segmentOffset();
8652     StringRef SegmentName = sectionTable.segmentName(SegIndex);
8653     StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8654     uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8655 
8656     // Table lines look like:
8657     //  __DATA  __got  0x00012010    pointer   0 libSystem ___stack_chk_guard
8658     StringRef Attr;
8659     if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
8660       Attr = " (weak_import)";
8661     outs() << left_justify(SegmentName, 8) << " "
8662            << left_justify(SectionName, 18) << " "
8663            << format_hex(Address, 10, true) << " "
8664            << left_justify(Entry.typeName(), 8) << " "
8665            << format_decimal(Entry.addend(), 8) << " "
8666            << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
8667            << Entry.symbolName() << Attr << "\n";
8668   }
8669 }
8670 
8671 //===----------------------------------------------------------------------===//
8672 // lazy bind table dumping
8673 //===----------------------------------------------------------------------===//
8674 
8675 void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) {
8676   // Build table of sections so names can used in final output.
8677   SegInfo sectionTable(Obj);
8678 
8679   outs() << "segment  section            address     "
8680             "dylib            symbol\n";
8681   for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
8682     uint32_t SegIndex = Entry.segmentIndex();
8683     uint64_t OffsetInSeg = Entry.segmentOffset();
8684     StringRef SegmentName = sectionTable.segmentName(SegIndex);
8685     StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8686     uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8687 
8688     // Table lines look like:
8689     //  __DATA  __got  0x00012010 libSystem ___stack_chk_guard
8690     outs() << left_justify(SegmentName, 8) << " "
8691            << left_justify(SectionName, 18) << " "
8692            << format_hex(Address, 10, true) << " "
8693            << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
8694            << Entry.symbolName() << "\n";
8695   }
8696 }
8697 
8698 //===----------------------------------------------------------------------===//
8699 // weak bind table dumping
8700 //===----------------------------------------------------------------------===//
8701 
8702 void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
8703   // Build table of sections so names can used in final output.
8704   SegInfo sectionTable(Obj);
8705 
8706   outs() << "segment  section            address     "
8707             "type       addend   symbol\n";
8708   for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
8709     // Strong symbols don't have a location to update.
8710     if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
8711       outs() << "                                        strong              "
8712              << Entry.symbolName() << "\n";
8713       continue;
8714     }
8715     uint32_t SegIndex = Entry.segmentIndex();
8716     uint64_t OffsetInSeg = Entry.segmentOffset();
8717     StringRef SegmentName = sectionTable.segmentName(SegIndex);
8718     StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8719     uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8720 
8721     // Table lines look like:
8722     // __DATA  __data  0x00001000  pointer    0   _foo
8723     outs() << left_justify(SegmentName, 8) << " "
8724            << left_justify(SectionName, 18) << " "
8725            << format_hex(Address, 10, true) << " "
8726            << left_justify(Entry.typeName(), 8) << " "
8727            << format_decimal(Entry.addend(), 8) << "   " << Entry.symbolName()
8728            << "\n";
8729   }
8730 }
8731 
8732 // get_dyld_bind_info_symbolname() is used for disassembly and passed an
8733 // address, ReferenceValue, in the Mach-O file and looks in the dyld bind
8734 // information for that address. If the address is found its binding symbol
8735 // name is returned.  If not nullptr is returned.
8736 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
8737                                                  struct DisassembleInfo *info) {
8738   if (info->bindtable == nullptr) {
8739     info->bindtable = new (BindTable);
8740     SegInfo sectionTable(info->O);
8741     for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) {
8742       uint32_t SegIndex = Entry.segmentIndex();
8743       uint64_t OffsetInSeg = Entry.segmentOffset();
8744       if (!sectionTable.isValidSegIndexAndOffset(SegIndex, OffsetInSeg))
8745         continue;
8746       uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8747       const char *SymbolName = nullptr;
8748       StringRef name = Entry.symbolName();
8749       if (!name.empty())
8750         SymbolName = name.data();
8751       info->bindtable->push_back(std::make_pair(Address, SymbolName));
8752     }
8753   }
8754   for (bind_table_iterator BI = info->bindtable->begin(),
8755                            BE = info->bindtable->end();
8756        BI != BE; ++BI) {
8757     uint64_t Address = BI->first;
8758     if (ReferenceValue == Address) {
8759       const char *SymbolName = BI->second;
8760       return SymbolName;
8761     }
8762   }
8763   return nullptr;
8764 }
8765