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