xref: /netbsd-src/external/apache2/llvm/dist/llvm/tools/llvm-objdump/MachODump.cpp (revision 76c7fc5f6b13ed0b1508e6b313e88e59977ed78e)
1 //===-- MachODump.cpp - Object file dumping utility for llvm --------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the MachO-specific dumper for llvm-objdump.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm-objdump.h"
14 #include "llvm-c/Disassembler.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/ADT/Triple.h"
18 #include "llvm/BinaryFormat/MachO.h"
19 #include "llvm/Config/config.h"
20 #include "llvm/DebugInfo/DIContext.h"
21 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
22 #include "llvm/Demangle/Demangle.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/MC/MCTargetOptions.h"
33 #include "llvm/Object/MachO.h"
34 #include "llvm/Object/MachOUniversal.h"
35 #include "llvm/Support/Casting.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/Endian.h"
39 #include "llvm/Support/Format.h"
40 #include "llvm/Support/FormattedStream.h"
41 #include "llvm/Support/GraphWriter.h"
42 #include "llvm/Support/LEB128.h"
43 #include "llvm/Support/MemoryBuffer.h"
44 #include "llvm/Support/TargetRegistry.h"
45 #include "llvm/Support/TargetSelect.h"
46 #include "llvm/Support/ToolOutputFile.h"
47 #include "llvm/Support/WithColor.h"
48 #include "llvm/Support/raw_ostream.h"
49 #include <algorithm>
50 #include <cstring>
51 #include <system_error>
52 
53 #ifdef HAVE_LIBXAR
54 extern "C" {
55 #include <xar/xar.h>
56 }
57 #endif
58 
59 using namespace llvm::object;
60 
61 namespace llvm {
62 
63 cl::OptionCategory MachOCat("llvm-objdump MachO Specific Options");
64 
65 extern cl::opt<bool> ArchiveHeaders;
66 extern cl::opt<bool> Disassemble;
67 extern cl::opt<bool> DisassembleAll;
68 extern cl::opt<DIDumpType> DwarfDumpType;
69 extern cl::list<std::string> FilterSections;
70 extern cl::list<std::string> MAttrs;
71 extern cl::opt<std::string> MCPU;
72 extern cl::opt<bool> NoShowRawInsn;
73 extern cl::opt<bool> NoLeadingAddr;
74 extern cl::opt<bool> PrintImmHex;
75 extern cl::opt<bool> PrivateHeaders;
76 extern cl::opt<bool> Relocations;
77 extern cl::opt<bool> SectionHeaders;
78 extern cl::opt<bool> SectionContents;
79 extern cl::opt<bool> SymbolTable;
80 extern cl::opt<std::string> TripleName;
81 extern cl::opt<bool> UnwindInfo;
82 
83 cl::opt<bool>
84     FirstPrivateHeader("private-header",
85                        cl::desc("Display only the first format specific file "
86                                 "header"),
87                        cl::cat(MachOCat));
88 
89 cl::opt<bool> ExportsTrie("exports-trie",
90                           cl::desc("Display mach-o exported symbols"),
91                           cl::cat(MachOCat));
92 
93 cl::opt<bool> Rebase("rebase", cl::desc("Display mach-o rebasing info"),
94                      cl::cat(MachOCat));
95 
96 cl::opt<bool> Bind("bind", cl::desc("Display mach-o binding info"),
97                    cl::cat(MachOCat));
98 
99 cl::opt<bool> LazyBind("lazy-bind",
100                        cl::desc("Display mach-o lazy binding info"),
101                        cl::cat(MachOCat));
102 
103 cl::opt<bool> WeakBind("weak-bind",
104                        cl::desc("Display mach-o weak binding info"),
105                        cl::cat(MachOCat));
106 
107 static cl::opt<bool>
108     UseDbg("g", cl::Grouping,
109            cl::desc("Print line information from debug info if available"),
110            cl::cat(MachOCat));
111 
112 static cl::opt<std::string> DSYMFile("dsym",
113                                      cl::desc("Use .dSYM file for debug info"),
114                                      cl::cat(MachOCat));
115 
116 static cl::opt<bool> FullLeadingAddr("full-leading-addr",
117                                      cl::desc("Print full leading address"),
118                                      cl::cat(MachOCat));
119 
120 static cl::opt<bool> NoLeadingHeaders("no-leading-headers",
121                                       cl::desc("Print no leading headers"),
122                                       cl::cat(MachOCat));
123 
124 cl::opt<bool> UniversalHeaders("universal-headers",
125                                cl::desc("Print Mach-O universal headers "
126                                         "(requires -macho)"),
127                                cl::cat(MachOCat));
128 
129 cl::opt<bool>
130     ArchiveMemberOffsets("archive-member-offsets",
131                          cl::desc("Print the offset to each archive member for "
132                                   "Mach-O archives (requires -macho and "
133                                   "-archive-headers)"),
134                          cl::cat(MachOCat));
135 
136 cl::opt<bool> IndirectSymbols("indirect-symbols",
137                               cl::desc("Print indirect symbol table for Mach-O "
138                                        "objects (requires -macho)"),
139                               cl::cat(MachOCat));
140 
141 cl::opt<bool>
142     DataInCode("data-in-code",
143                cl::desc("Print the data in code table for Mach-O objects "
144                         "(requires -macho)"),
145                cl::cat(MachOCat));
146 
147 cl::opt<bool> LinkOptHints("link-opt-hints",
148                            cl::desc("Print the linker optimization hints for "
149                                     "Mach-O objects (requires -macho)"),
150                            cl::cat(MachOCat));
151 
152 cl::opt<bool> InfoPlist("info-plist",
153                         cl::desc("Print the info plist section as strings for "
154                                  "Mach-O objects (requires -macho)"),
155                         cl::cat(MachOCat));
156 
157 cl::opt<bool> DylibsUsed("dylibs-used",
158                          cl::desc("Print the shared libraries used for linked "
159                                   "Mach-O files (requires -macho)"),
160                          cl::cat(MachOCat));
161 
162 cl::opt<bool>
163     DylibId("dylib-id",
164             cl::desc("Print the shared library's id for the dylib Mach-O "
165                      "file (requires -macho)"),
166             cl::cat(MachOCat));
167 
168 cl::opt<bool>
169     NonVerbose("non-verbose",
170                cl::desc("Print the info for Mach-O objects in "
171                         "non-verbose or numeric form (requires -macho)"),
172                cl::cat(MachOCat));
173 
174 cl::opt<bool>
175     ObjcMetaData("objc-meta-data",
176                  cl::desc("Print the Objective-C runtime meta data for "
177                           "Mach-O files (requires -macho)"),
178                  cl::cat(MachOCat));
179 
180 cl::opt<std::string> DisSymName(
181     "dis-symname",
182     cl::desc("disassemble just this symbol's instructions (requires -macho)"),
183     cl::cat(MachOCat));
184 
185 static cl::opt<bool> NoSymbolicOperands(
186     "no-symbolic-operands",
187     cl::desc("do not symbolic operands when disassembling (requires -macho)"),
188     cl::cat(MachOCat));
189 
190 static cl::list<std::string>
191     ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
192               cl::ZeroOrMore, cl::cat(MachOCat));
193 
194 bool ArchAll = false;
195 
196 static std::string ThumbTripleName;
197 
198 static const Target *GetTarget(const MachOObjectFile *MachOObj,
199                                const char **McpuDefault,
200                                const Target **ThumbTarget) {
201   // Figure out the target triple.
202   Triple TT(TripleName);
203   if (TripleName.empty()) {
204     TT = MachOObj->getArchTriple(McpuDefault);
205     TripleName = TT.str();
206   }
207 
208   if (TT.getArch() == Triple::arm) {
209     // We've inferred a 32-bit ARM target from the object file. All MachO CPUs
210     // that support ARM are also capable of Thumb mode.
211     Triple ThumbTriple = TT;
212     std::string ThumbName = (Twine("thumb") + TT.getArchName().substr(3)).str();
213     ThumbTriple.setArchName(ThumbName);
214     ThumbTripleName = ThumbTriple.str();
215   }
216 
217   // Get the target specific parser.
218   std::string Error;
219   const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
220   if (TheTarget && ThumbTripleName.empty())
221     return TheTarget;
222 
223   *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
224   if (*ThumbTarget)
225     return TheTarget;
226 
227   WithColor::error(errs(), "llvm-objdump") << "unable to get target for '";
228   if (!TheTarget)
229     errs() << TripleName;
230   else
231     errs() << ThumbTripleName;
232   errs() << "', see --version and --triple.\n";
233   return nullptr;
234 }
235 
236 struct SymbolSorter {
237   bool operator()(const SymbolRef &A, const SymbolRef &B) {
238     Expected<SymbolRef::Type> ATypeOrErr = A.getType();
239     if (!ATypeOrErr)
240       reportError(ATypeOrErr.takeError(), A.getObject()->getFileName());
241     SymbolRef::Type AType = *ATypeOrErr;
242     Expected<SymbolRef::Type> BTypeOrErr = B.getType();
243     if (!BTypeOrErr)
244       reportError(BTypeOrErr.takeError(), B.getObject()->getFileName());
245     SymbolRef::Type BType = *BTypeOrErr;
246     uint64_t AAddr = (AType != SymbolRef::ST_Function) ? 0 : A.getValue();
247     uint64_t BAddr = (BType != SymbolRef::ST_Function) ? 0 : B.getValue();
248     return AAddr < BAddr;
249   }
250 };
251 
252 // Types for the storted data in code table that is built before disassembly
253 // and the predicate function to sort them.
254 typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
255 typedef std::vector<DiceTableEntry> DiceTable;
256 typedef DiceTable::iterator dice_table_iterator;
257 
258 #ifdef HAVE_LIBXAR
259 namespace {
260 struct ScopedXarFile {
261   xar_t xar;
262   ScopedXarFile(const char *filename, int32_t flags)
263       : xar(xar_open(filename, flags)) {}
264   ~ScopedXarFile() {
265     if (xar)
266       xar_close(xar);
267   }
268   ScopedXarFile(const ScopedXarFile &) = delete;
269   ScopedXarFile &operator=(const ScopedXarFile &) = delete;
270   operator xar_t() { return xar; }
271 };
272 
273 struct ScopedXarIter {
274   xar_iter_t iter;
275   ScopedXarIter() : iter(xar_iter_new()) {}
276   ~ScopedXarIter() {
277     if (iter)
278       xar_iter_free(iter);
279   }
280   ScopedXarIter(const ScopedXarIter &) = delete;
281   ScopedXarIter &operator=(const ScopedXarIter &) = delete;
282   operator xar_iter_t() { return iter; }
283 };
284 } // namespace
285 #endif // defined(HAVE_LIBXAR)
286 
287 // This is used to search for a data in code table entry for the PC being
288 // disassembled.  The j parameter has the PC in j.first.  A single data in code
289 // table entry can cover many bytes for each of its Kind's.  So if the offset,
290 // aka the i.first value, of the data in code table entry plus its Length
291 // covers the PC being searched for this will return true.  If not it will
292 // return false.
293 static bool compareDiceTableEntries(const DiceTableEntry &i,
294                                     const DiceTableEntry &j) {
295   uint16_t Length;
296   i.second.getLength(Length);
297 
298   return j.first >= i.first && j.first < i.first + Length;
299 }
300 
301 static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
302                                unsigned short Kind) {
303   uint32_t Value, Size = 1;
304 
305   switch (Kind) {
306   default:
307   case MachO::DICE_KIND_DATA:
308     if (Length >= 4) {
309       if (!NoShowRawInsn)
310         dumpBytes(makeArrayRef(bytes, 4), outs());
311       Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
312       outs() << "\t.long " << Value;
313       Size = 4;
314     } else if (Length >= 2) {
315       if (!NoShowRawInsn)
316         dumpBytes(makeArrayRef(bytes, 2), outs());
317       Value = bytes[1] << 8 | bytes[0];
318       outs() << "\t.short " << Value;
319       Size = 2;
320     } else {
321       if (!NoShowRawInsn)
322         dumpBytes(makeArrayRef(bytes, 2), outs());
323       Value = bytes[0];
324       outs() << "\t.byte " << Value;
325       Size = 1;
326     }
327     if (Kind == MachO::DICE_KIND_DATA)
328       outs() << "\t@ KIND_DATA\n";
329     else
330       outs() << "\t@ data in code kind = " << Kind << "\n";
331     break;
332   case MachO::DICE_KIND_JUMP_TABLE8:
333     if (!NoShowRawInsn)
334       dumpBytes(makeArrayRef(bytes, 1), outs());
335     Value = bytes[0];
336     outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
337     Size = 1;
338     break;
339   case MachO::DICE_KIND_JUMP_TABLE16:
340     if (!NoShowRawInsn)
341       dumpBytes(makeArrayRef(bytes, 2), outs());
342     Value = bytes[1] << 8 | bytes[0];
343     outs() << "\t.short " << format("%5u", Value & 0xffff)
344            << "\t@ KIND_JUMP_TABLE16\n";
345     Size = 2;
346     break;
347   case MachO::DICE_KIND_JUMP_TABLE32:
348   case MachO::DICE_KIND_ABS_JUMP_TABLE32:
349     if (!NoShowRawInsn)
350       dumpBytes(makeArrayRef(bytes, 4), outs());
351     Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
352     outs() << "\t.long " << Value;
353     if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
354       outs() << "\t@ KIND_JUMP_TABLE32\n";
355     else
356       outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
357     Size = 4;
358     break;
359   }
360   return Size;
361 }
362 
363 static void getSectionsAndSymbols(MachOObjectFile *MachOObj,
364                                   std::vector<SectionRef> &Sections,
365                                   std::vector<SymbolRef> &Symbols,
366                                   SmallVectorImpl<uint64_t> &FoundFns,
367                                   uint64_t &BaseSegmentAddress) {
368   const StringRef FileName = MachOObj->getFileName();
369   for (const SymbolRef &Symbol : MachOObj->symbols()) {
370     StringRef SymName = unwrapOrError(Symbol.getName(), FileName);
371     if (!SymName.startswith("ltmp"))
372       Symbols.push_back(Symbol);
373   }
374 
375   for (const SectionRef &Section : MachOObj->sections())
376     Sections.push_back(Section);
377 
378   bool BaseSegmentAddressSet = false;
379   for (const auto &Command : MachOObj->load_commands()) {
380     if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
381       // We found a function starts segment, parse the addresses for later
382       // consumption.
383       MachO::linkedit_data_command LLC =
384           MachOObj->getLinkeditDataLoadCommand(Command);
385 
386       MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
387     } else if (Command.C.cmd == MachO::LC_SEGMENT) {
388       MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
389       StringRef SegName = SLC.segname;
390       if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
391         BaseSegmentAddressSet = true;
392         BaseSegmentAddress = SLC.vmaddr;
393       }
394     } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
395       MachO::segment_command_64 SLC = MachOObj->getSegment64LoadCommand(Command);
396       StringRef SegName = SLC.segname;
397       if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
398         BaseSegmentAddressSet = true;
399         BaseSegmentAddress = SLC.vmaddr;
400       }
401     }
402   }
403 }
404 
405 static bool DumpAndSkipDataInCode(uint64_t PC, const uint8_t *bytes,
406                                  DiceTable &Dices, uint64_t &InstSize) {
407   // Check the data in code table here to see if this is data not an
408   // instruction to be disassembled.
409   DiceTable Dice;
410   Dice.push_back(std::make_pair(PC, DiceRef()));
411   dice_table_iterator DTI =
412       std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
413                   compareDiceTableEntries);
414   if (DTI != Dices.end()) {
415     uint16_t Length;
416     DTI->second.getLength(Length);
417     uint16_t Kind;
418     DTI->second.getKind(Kind);
419     InstSize = DumpDataInCode(bytes, Length, Kind);
420     if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
421         (PC == (DTI->first + Length - 1)) && (Length & 1))
422       InstSize++;
423     return true;
424   }
425   return false;
426 }
427 
428 static void printRelocationTargetName(const MachOObjectFile *O,
429                                       const MachO::any_relocation_info &RE,
430                                       raw_string_ostream &Fmt) {
431   // Target of a scattered relocation is an address.  In the interest of
432   // generating pretty output, scan through the symbol table looking for a
433   // symbol that aligns with that address.  If we find one, print it.
434   // Otherwise, we just print the hex address of the target.
435   const StringRef FileName = O->getFileName();
436   if (O->isRelocationScattered(RE)) {
437     uint32_t Val = O->getPlainRelocationSymbolNum(RE);
438 
439     for (const SymbolRef &Symbol : O->symbols()) {
440       uint64_t Addr = unwrapOrError(Symbol.getAddress(), FileName);
441       if (Addr != Val)
442         continue;
443       Fmt << unwrapOrError(Symbol.getName(), FileName);
444       return;
445     }
446 
447     // If we couldn't find a symbol that this relocation refers to, try
448     // to find a section beginning instead.
449     for (const SectionRef &Section : ToolSectionFilter(*O)) {
450       uint64_t Addr = Section.getAddress();
451       if (Addr != Val)
452         continue;
453       StringRef NameOrErr = unwrapOrError(Section.getName(), O->getFileName());
454       Fmt << NameOrErr;
455       return;
456     }
457 
458     Fmt << format("0x%x", Val);
459     return;
460   }
461 
462   StringRef S;
463   bool isExtern = O->getPlainRelocationExternal(RE);
464   uint64_t Val = O->getPlainRelocationSymbolNum(RE);
465 
466   if (O->getAnyRelocationType(RE) == MachO::ARM64_RELOC_ADDEND) {
467     Fmt << format("0x%0" PRIx64, Val);
468     return;
469   }
470 
471   if (isExtern) {
472     symbol_iterator SI = O->symbol_begin();
473     advance(SI, Val);
474     S = unwrapOrError(SI->getName(), FileName);
475   } else {
476     section_iterator SI = O->section_begin();
477     // Adjust for the fact that sections are 1-indexed.
478     if (Val == 0) {
479       Fmt << "0 (?,?)";
480       return;
481     }
482     uint32_t I = Val - 1;
483     while (I != 0 && SI != O->section_end()) {
484       --I;
485       advance(SI, 1);
486     }
487     if (SI == O->section_end()) {
488       Fmt << Val << " (?,?)";
489     } else {
490       if (Expected<StringRef> NameOrErr = SI->getName())
491         S = *NameOrErr;
492       else
493         consumeError(NameOrErr.takeError());
494     }
495   }
496 
497   Fmt << S;
498 }
499 
500 Error getMachORelocationValueString(const MachOObjectFile *Obj,
501                                     const RelocationRef &RelRef,
502                                     SmallVectorImpl<char> &Result) {
503   DataRefImpl Rel = RelRef.getRawDataRefImpl();
504   MachO::any_relocation_info RE = Obj->getRelocation(Rel);
505 
506   unsigned Arch = Obj->getArch();
507 
508   std::string FmtBuf;
509   raw_string_ostream Fmt(FmtBuf);
510   unsigned Type = Obj->getAnyRelocationType(RE);
511   bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
512 
513   // Determine any addends that should be displayed with the relocation.
514   // These require decoding the relocation type, which is triple-specific.
515 
516   // X86_64 has entirely custom relocation types.
517   if (Arch == Triple::x86_64) {
518     switch (Type) {
519     case MachO::X86_64_RELOC_GOT_LOAD:
520     case MachO::X86_64_RELOC_GOT: {
521       printRelocationTargetName(Obj, RE, Fmt);
522       Fmt << "@GOT";
523       if (IsPCRel)
524         Fmt << "PCREL";
525       break;
526     }
527     case MachO::X86_64_RELOC_SUBTRACTOR: {
528       DataRefImpl RelNext = Rel;
529       Obj->moveRelocationNext(RelNext);
530       MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
531 
532       // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
533       // X86_64_RELOC_UNSIGNED.
534       // NOTE: Scattered relocations don't exist on x86_64.
535       unsigned RType = Obj->getAnyRelocationType(RENext);
536       if (RType != MachO::X86_64_RELOC_UNSIGNED)
537         reportError(Obj->getFileName(), "Expected X86_64_RELOC_UNSIGNED after "
538                                         "X86_64_RELOC_SUBTRACTOR.");
539 
540       // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
541       // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
542       printRelocationTargetName(Obj, RENext, Fmt);
543       Fmt << "-";
544       printRelocationTargetName(Obj, RE, Fmt);
545       break;
546     }
547     case MachO::X86_64_RELOC_TLV:
548       printRelocationTargetName(Obj, RE, Fmt);
549       Fmt << "@TLV";
550       if (IsPCRel)
551         Fmt << "P";
552       break;
553     case MachO::X86_64_RELOC_SIGNED_1:
554       printRelocationTargetName(Obj, RE, Fmt);
555       Fmt << "-1";
556       break;
557     case MachO::X86_64_RELOC_SIGNED_2:
558       printRelocationTargetName(Obj, RE, Fmt);
559       Fmt << "-2";
560       break;
561     case MachO::X86_64_RELOC_SIGNED_4:
562       printRelocationTargetName(Obj, RE, Fmt);
563       Fmt << "-4";
564       break;
565     default:
566       printRelocationTargetName(Obj, RE, Fmt);
567       break;
568     }
569     // X86 and ARM share some relocation types in common.
570   } else if (Arch == Triple::x86 || Arch == Triple::arm ||
571              Arch == Triple::ppc) {
572     // Generic relocation types...
573     switch (Type) {
574     case MachO::GENERIC_RELOC_PAIR: // prints no info
575       return Error::success();
576     case MachO::GENERIC_RELOC_SECTDIFF: {
577       DataRefImpl RelNext = Rel;
578       Obj->moveRelocationNext(RelNext);
579       MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
580 
581       // X86 sect diff's must be followed by a relocation of type
582       // GENERIC_RELOC_PAIR.
583       unsigned RType = Obj->getAnyRelocationType(RENext);
584 
585       if (RType != MachO::GENERIC_RELOC_PAIR)
586         reportError(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
587                                         "GENERIC_RELOC_SECTDIFF.");
588 
589       printRelocationTargetName(Obj, RE, Fmt);
590       Fmt << "-";
591       printRelocationTargetName(Obj, RENext, Fmt);
592       break;
593     }
594     }
595 
596     if (Arch == Triple::x86 || Arch == Triple::ppc) {
597       switch (Type) {
598       case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
599         DataRefImpl RelNext = Rel;
600         Obj->moveRelocationNext(RelNext);
601         MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
602 
603         // X86 sect diff's must be followed by a relocation of type
604         // GENERIC_RELOC_PAIR.
605         unsigned RType = Obj->getAnyRelocationType(RENext);
606         if (RType != MachO::GENERIC_RELOC_PAIR)
607           reportError(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
608                                           "GENERIC_RELOC_LOCAL_SECTDIFF.");
609 
610         printRelocationTargetName(Obj, RE, Fmt);
611         Fmt << "-";
612         printRelocationTargetName(Obj, RENext, Fmt);
613         break;
614       }
615       case MachO::GENERIC_RELOC_TLV: {
616         printRelocationTargetName(Obj, RE, Fmt);
617         Fmt << "@TLV";
618         if (IsPCRel)
619           Fmt << "P";
620         break;
621       }
622       default:
623         printRelocationTargetName(Obj, RE, Fmt);
624       }
625     } else { // ARM-specific relocations
626       switch (Type) {
627       case MachO::ARM_RELOC_HALF:
628       case MachO::ARM_RELOC_HALF_SECTDIFF: {
629         // Half relocations steal a bit from the length field to encode
630         // whether this is an upper16 or a lower16 relocation.
631         bool isUpper = (Obj->getAnyRelocationLength(RE) & 0x1) == 1;
632 
633         if (isUpper)
634           Fmt << ":upper16:(";
635         else
636           Fmt << ":lower16:(";
637         printRelocationTargetName(Obj, RE, Fmt);
638 
639         DataRefImpl RelNext = Rel;
640         Obj->moveRelocationNext(RelNext);
641         MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
642 
643         // ARM half relocs must be followed by a relocation of type
644         // ARM_RELOC_PAIR.
645         unsigned RType = Obj->getAnyRelocationType(RENext);
646         if (RType != MachO::ARM_RELOC_PAIR)
647           reportError(Obj->getFileName(), "Expected ARM_RELOC_PAIR after "
648                                           "ARM_RELOC_HALF");
649 
650         // NOTE: The half of the target virtual address is stashed in the
651         // address field of the secondary relocation, but we can't reverse
652         // engineer the constant offset from it without decoding the movw/movt
653         // instruction to find the other half in its immediate field.
654 
655         // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
656         // symbol/section pointer of the follow-on relocation.
657         if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
658           Fmt << "-";
659           printRelocationTargetName(Obj, RENext, Fmt);
660         }
661 
662         Fmt << ")";
663         break;
664       }
665       default: {
666         printRelocationTargetName(Obj, RE, Fmt);
667       }
668       }
669     }
670   } else
671     printRelocationTargetName(Obj, RE, Fmt);
672 
673   Fmt.flush();
674   Result.append(FmtBuf.begin(), FmtBuf.end());
675   return Error::success();
676 }
677 
678 static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
679                                      uint32_t n, uint32_t count,
680                                      uint32_t stride, uint64_t addr) {
681   MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
682   uint32_t nindirectsyms = Dysymtab.nindirectsyms;
683   if (n > nindirectsyms)
684     outs() << " (entries start past the end of the indirect symbol "
685               "table) (reserved1 field greater than the table size)";
686   else if (n + count > nindirectsyms)
687     outs() << " (entries extends past the end of the indirect symbol "
688               "table)";
689   outs() << "\n";
690   uint32_t cputype = O->getHeader().cputype;
691   if (cputype & MachO::CPU_ARCH_ABI64)
692     outs() << "address            index";
693   else
694     outs() << "address    index";
695   if (verbose)
696     outs() << " name\n";
697   else
698     outs() << "\n";
699   for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
700     if (cputype & MachO::CPU_ARCH_ABI64)
701       outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
702     else
703       outs() << format("0x%08" PRIx32, (uint32_t)addr + j * stride) << " ";
704     MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
705     uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
706     if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
707       outs() << "LOCAL\n";
708       continue;
709     }
710     if (indirect_symbol ==
711         (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
712       outs() << "LOCAL ABSOLUTE\n";
713       continue;
714     }
715     if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
716       outs() << "ABSOLUTE\n";
717       continue;
718     }
719     outs() << format("%5u ", indirect_symbol);
720     if (verbose) {
721       MachO::symtab_command Symtab = O->getSymtabLoadCommand();
722       if (indirect_symbol < Symtab.nsyms) {
723         symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
724         SymbolRef Symbol = *Sym;
725         outs() << unwrapOrError(Symbol.getName(), O->getFileName());
726       } else {
727         outs() << "?";
728       }
729     }
730     outs() << "\n";
731   }
732 }
733 
734 static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
735   for (const auto &Load : O->load_commands()) {
736     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
737       MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
738       for (unsigned J = 0; J < Seg.nsects; ++J) {
739         MachO::section_64 Sec = O->getSection64(Load, J);
740         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
741         if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
742             section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
743             section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
744             section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
745             section_type == MachO::S_SYMBOL_STUBS) {
746           uint32_t stride;
747           if (section_type == MachO::S_SYMBOL_STUBS)
748             stride = Sec.reserved2;
749           else
750             stride = 8;
751           if (stride == 0) {
752             outs() << "Can't print indirect symbols for (" << Sec.segname << ","
753                    << Sec.sectname << ") "
754                    << "(size of stubs in reserved2 field is zero)\n";
755             continue;
756           }
757           uint32_t count = Sec.size / stride;
758           outs() << "Indirect symbols for (" << Sec.segname << ","
759                  << Sec.sectname << ") " << count << " entries";
760           uint32_t n = Sec.reserved1;
761           PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
762         }
763       }
764     } else if (Load.C.cmd == MachO::LC_SEGMENT) {
765       MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
766       for (unsigned J = 0; J < Seg.nsects; ++J) {
767         MachO::section Sec = O->getSection(Load, J);
768         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
769         if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
770             section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
771             section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
772             section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
773             section_type == MachO::S_SYMBOL_STUBS) {
774           uint32_t stride;
775           if (section_type == MachO::S_SYMBOL_STUBS)
776             stride = Sec.reserved2;
777           else
778             stride = 4;
779           if (stride == 0) {
780             outs() << "Can't print indirect symbols for (" << Sec.segname << ","
781                    << Sec.sectname << ") "
782                    << "(size of stubs in reserved2 field is zero)\n";
783             continue;
784           }
785           uint32_t count = Sec.size / stride;
786           outs() << "Indirect symbols for (" << Sec.segname << ","
787                  << Sec.sectname << ") " << count << " entries";
788           uint32_t n = Sec.reserved1;
789           PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
790         }
791       }
792     }
793   }
794 }
795 
796 static void PrintRType(const uint64_t cputype, const unsigned r_type) {
797   static char const *generic_r_types[] = {
798     "VANILLA ", "PAIR    ", "SECTDIF ", "PBLAPTR ", "LOCSDIF ", "TLV     ",
799     "  6 (?) ", "  7 (?) ", "  8 (?) ", "  9 (?) ", " 10 (?) ", " 11 (?) ",
800     " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
801   };
802   static char const *x86_64_r_types[] = {
803     "UNSIGND ", "SIGNED  ", "BRANCH  ", "GOT_LD  ", "GOT     ", "SUB     ",
804     "SIGNED1 ", "SIGNED2 ", "SIGNED4 ", "TLV     ", " 10 (?) ", " 11 (?) ",
805     " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
806   };
807   static char const *arm_r_types[] = {
808     "VANILLA ", "PAIR    ", "SECTDIFF", "LOCSDIF ", "PBLAPTR ",
809     "BR24    ", "T_BR22  ", "T_BR32  ", "HALF    ", "HALFDIF ",
810     " 10 (?) ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
811   };
812   static char const *arm64_r_types[] = {
813     "UNSIGND ", "SUB     ", "BR26    ", "PAGE21  ", "PAGOF12 ",
814     "GOTLDP  ", "GOTLDPOF", "PTRTGOT ", "TLVLDP  ", "TLVLDPOF",
815     "ADDEND  ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
816   };
817 
818   if (r_type > 0xf){
819     outs() << format("%-7u", r_type) << " ";
820     return;
821   }
822   switch (cputype) {
823     case MachO::CPU_TYPE_I386:
824       outs() << generic_r_types[r_type];
825       break;
826     case MachO::CPU_TYPE_X86_64:
827       outs() << x86_64_r_types[r_type];
828       break;
829     case MachO::CPU_TYPE_ARM:
830       outs() << arm_r_types[r_type];
831       break;
832     case MachO::CPU_TYPE_ARM64:
833     case MachO::CPU_TYPE_ARM64_32:
834       outs() << arm64_r_types[r_type];
835       break;
836     default:
837       outs() << format("%-7u ", r_type);
838   }
839 }
840 
841 static void PrintRLength(const uint64_t cputype, const unsigned r_type,
842                          const unsigned r_length, const bool previous_arm_half){
843   if (cputype == MachO::CPU_TYPE_ARM &&
844       (r_type == MachO::ARM_RELOC_HALF ||
845        r_type == MachO::ARM_RELOC_HALF_SECTDIFF || previous_arm_half == true)) {
846     if ((r_length & 0x1) == 0)
847       outs() << "lo/";
848     else
849       outs() << "hi/";
850     if ((r_length & 0x1) == 0)
851       outs() << "arm ";
852     else
853       outs() << "thm ";
854   } else {
855     switch (r_length) {
856       case 0:
857         outs() << "byte   ";
858         break;
859       case 1:
860         outs() << "word   ";
861         break;
862       case 2:
863         outs() << "long   ";
864         break;
865       case 3:
866         if (cputype == MachO::CPU_TYPE_X86_64)
867           outs() << "quad   ";
868         else
869           outs() << format("?(%2d)  ", r_length);
870         break;
871       default:
872         outs() << format("?(%2d)  ", r_length);
873     }
874   }
875 }
876 
877 static void PrintRelocationEntries(const MachOObjectFile *O,
878                                    const relocation_iterator Begin,
879                                    const relocation_iterator End,
880                                    const uint64_t cputype,
881                                    const bool verbose) {
882   const MachO::symtab_command Symtab = O->getSymtabLoadCommand();
883   bool previous_arm_half = false;
884   bool previous_sectdiff = false;
885   uint32_t sectdiff_r_type = 0;
886 
887   for (relocation_iterator Reloc = Begin; Reloc != End; ++Reloc) {
888     const DataRefImpl Rel = Reloc->getRawDataRefImpl();
889     const MachO::any_relocation_info RE = O->getRelocation(Rel);
890     const unsigned r_type = O->getAnyRelocationType(RE);
891     const bool r_scattered = O->isRelocationScattered(RE);
892     const unsigned r_pcrel = O->getAnyRelocationPCRel(RE);
893     const unsigned r_length = O->getAnyRelocationLength(RE);
894     const unsigned r_address = O->getAnyRelocationAddress(RE);
895     const bool r_extern = (r_scattered ? false :
896                            O->getPlainRelocationExternal(RE));
897     const uint32_t r_value = (r_scattered ?
898                               O->getScatteredRelocationValue(RE) : 0);
899     const unsigned r_symbolnum = (r_scattered ? 0 :
900                                   O->getPlainRelocationSymbolNum(RE));
901 
902     if (r_scattered && cputype != MachO::CPU_TYPE_X86_64) {
903       if (verbose) {
904         // scattered: address
905         if ((cputype == MachO::CPU_TYPE_I386 &&
906              r_type == MachO::GENERIC_RELOC_PAIR) ||
907             (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR))
908           outs() << "         ";
909         else
910           outs() << format("%08x ", (unsigned int)r_address);
911 
912         // scattered: pcrel
913         if (r_pcrel)
914           outs() << "True  ";
915         else
916           outs() << "False ";
917 
918         // scattered: length
919         PrintRLength(cputype, r_type, r_length, previous_arm_half);
920 
921         // scattered: extern & type
922         outs() << "n/a    ";
923         PrintRType(cputype, r_type);
924 
925         // scattered: scattered & value
926         outs() << format("True      0x%08x", (unsigned int)r_value);
927         if (previous_sectdiff == false) {
928           if ((cputype == MachO::CPU_TYPE_ARM &&
929                r_type == MachO::ARM_RELOC_PAIR))
930             outs() << format(" half = 0x%04x ", (unsigned int)r_address);
931         } else if (cputype == MachO::CPU_TYPE_ARM &&
932                    sectdiff_r_type == MachO::ARM_RELOC_HALF_SECTDIFF)
933           outs() << format(" other_half = 0x%04x ", (unsigned int)r_address);
934         if ((cputype == MachO::CPU_TYPE_I386 &&
935              (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
936               r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) ||
937             (cputype == MachO::CPU_TYPE_ARM &&
938              (sectdiff_r_type == MachO::ARM_RELOC_SECTDIFF ||
939               sectdiff_r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
940               sectdiff_r_type == MachO::ARM_RELOC_HALF_SECTDIFF))) {
941           previous_sectdiff = true;
942           sectdiff_r_type = r_type;
943         } else {
944           previous_sectdiff = false;
945           sectdiff_r_type = 0;
946         }
947         if (cputype == MachO::CPU_TYPE_ARM &&
948             (r_type == MachO::ARM_RELOC_HALF ||
949              r_type == MachO::ARM_RELOC_HALF_SECTDIFF))
950           previous_arm_half = true;
951         else
952           previous_arm_half = false;
953         outs() << "\n";
954       }
955       else {
956         // scattered: address pcrel length extern type scattered value
957         outs() << format("%08x %1d     %-2d     n/a    %-7d 1         0x%08x\n",
958                          (unsigned int)r_address, r_pcrel, r_length, r_type,
959                          (unsigned int)r_value);
960       }
961     }
962     else {
963       if (verbose) {
964         // plain: address
965         if (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR)
966           outs() << "         ";
967         else
968           outs() << format("%08x ", (unsigned int)r_address);
969 
970         // plain: pcrel
971         if (r_pcrel)
972           outs() << "True  ";
973         else
974           outs() << "False ";
975 
976         // plain: length
977         PrintRLength(cputype, r_type, r_length, previous_arm_half);
978 
979         if (r_extern) {
980           // plain: extern & type & scattered
981           outs() << "True   ";
982           PrintRType(cputype, r_type);
983           outs() << "False     ";
984 
985           // plain: symbolnum/value
986           if (r_symbolnum > Symtab.nsyms)
987             outs() << format("?(%d)\n", r_symbolnum);
988           else {
989             SymbolRef Symbol = *O->getSymbolByIndex(r_symbolnum);
990             Expected<StringRef> SymNameNext = Symbol.getName();
991             const char *name = NULL;
992             if (SymNameNext)
993               name = SymNameNext->data();
994             if (name == NULL)
995               outs() << format("?(%d)\n", r_symbolnum);
996             else
997               outs() << name << "\n";
998           }
999         }
1000         else {
1001           // plain: extern & type & scattered
1002           outs() << "False  ";
1003           PrintRType(cputype, r_type);
1004           outs() << "False     ";
1005 
1006           // plain: symbolnum/value
1007           if (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR)
1008             outs() << format("other_half = 0x%04x\n", (unsigned int)r_address);
1009           else if ((cputype == MachO::CPU_TYPE_ARM64 ||
1010                     cputype == MachO::CPU_TYPE_ARM64_32) &&
1011                    r_type == MachO::ARM64_RELOC_ADDEND)
1012             outs() << format("addend = 0x%06x\n", (unsigned int)r_symbolnum);
1013           else {
1014             outs() << format("%d ", r_symbolnum);
1015             if (r_symbolnum == MachO::R_ABS)
1016               outs() << "R_ABS\n";
1017             else {
1018               // in this case, r_symbolnum is actually a 1-based section number
1019               uint32_t nsects = O->section_end()->getRawDataRefImpl().d.a;
1020               if (r_symbolnum > 0 && r_symbolnum <= nsects) {
1021                 object::DataRefImpl DRI;
1022                 DRI.d.a = r_symbolnum-1;
1023                 StringRef SegName = O->getSectionFinalSegmentName(DRI);
1024                 if (Expected<StringRef> NameOrErr = O->getSectionName(DRI))
1025                   outs() << "(" << SegName << "," << *NameOrErr << ")\n";
1026                 else
1027                   outs() << "(?,?)\n";
1028               }
1029               else {
1030                 outs() << "(?,?)\n";
1031               }
1032             }
1033           }
1034         }
1035         if (cputype == MachO::CPU_TYPE_ARM &&
1036             (r_type == MachO::ARM_RELOC_HALF ||
1037              r_type == MachO::ARM_RELOC_HALF_SECTDIFF))
1038           previous_arm_half = true;
1039         else
1040           previous_arm_half = false;
1041       }
1042       else {
1043         // plain: address pcrel length extern type scattered symbolnum/section
1044         outs() << format("%08x %1d     %-2d     %1d      %-7d 0         %d\n",
1045                          (unsigned int)r_address, r_pcrel, r_length, r_extern,
1046                          r_type, r_symbolnum);
1047       }
1048     }
1049   }
1050 }
1051 
1052 static void PrintRelocations(const MachOObjectFile *O, const bool verbose) {
1053   const uint64_t cputype = O->getHeader().cputype;
1054   const MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
1055   if (Dysymtab.nextrel != 0) {
1056     outs() << "External relocation information " << Dysymtab.nextrel
1057            << " entries";
1058     outs() << "\naddress  pcrel length extern type    scattered "
1059               "symbolnum/value\n";
1060     PrintRelocationEntries(O, O->extrel_begin(), O->extrel_end(), cputype,
1061                            verbose);
1062   }
1063   if (Dysymtab.nlocrel != 0) {
1064     outs() << format("Local relocation information %u entries",
1065                      Dysymtab.nlocrel);
1066     outs() << "\naddress  pcrel length extern type    scattered "
1067               "symbolnum/value\n";
1068     PrintRelocationEntries(O, O->locrel_begin(), O->locrel_end(), cputype,
1069                            verbose);
1070   }
1071   for (const auto &Load : O->load_commands()) {
1072     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
1073       const MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
1074       for (unsigned J = 0; J < Seg.nsects; ++J) {
1075         const MachO::section_64 Sec = O->getSection64(Load, J);
1076         if (Sec.nreloc != 0) {
1077           DataRefImpl DRI;
1078           DRI.d.a = J;
1079           const StringRef SegName = O->getSectionFinalSegmentName(DRI);
1080           if (Expected<StringRef> NameOrErr = O->getSectionName(DRI))
1081             outs() << "Relocation information (" << SegName << "," << *NameOrErr
1082                    << format(") %u entries", Sec.nreloc);
1083           else
1084             outs() << "Relocation information (" << SegName << ",?) "
1085                    << format("%u entries", Sec.nreloc);
1086           outs() << "\naddress  pcrel length extern type    scattered "
1087                     "symbolnum/value\n";
1088           PrintRelocationEntries(O, O->section_rel_begin(DRI),
1089                                  O->section_rel_end(DRI), cputype, verbose);
1090         }
1091       }
1092     } else if (Load.C.cmd == MachO::LC_SEGMENT) {
1093       const MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
1094       for (unsigned J = 0; J < Seg.nsects; ++J) {
1095         const MachO::section Sec = O->getSection(Load, J);
1096         if (Sec.nreloc != 0) {
1097           DataRefImpl DRI;
1098           DRI.d.a = J;
1099           const StringRef SegName = O->getSectionFinalSegmentName(DRI);
1100           if (Expected<StringRef> NameOrErr = O->getSectionName(DRI))
1101             outs() << "Relocation information (" << SegName << "," << *NameOrErr
1102                    << format(") %u entries", Sec.nreloc);
1103           else
1104             outs() << "Relocation information (" << SegName << ",?) "
1105                    << format("%u entries", Sec.nreloc);
1106           outs() << "\naddress  pcrel length extern type    scattered "
1107                     "symbolnum/value\n";
1108           PrintRelocationEntries(O, O->section_rel_begin(DRI),
1109                                  O->section_rel_end(DRI), cputype, verbose);
1110         }
1111       }
1112     }
1113   }
1114 }
1115 
1116 static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
1117   MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
1118   uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
1119   outs() << "Data in code table (" << nentries << " entries)\n";
1120   outs() << "offset     length kind\n";
1121   for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
1122        ++DI) {
1123     uint32_t Offset;
1124     DI->getOffset(Offset);
1125     outs() << format("0x%08" PRIx32, Offset) << " ";
1126     uint16_t Length;
1127     DI->getLength(Length);
1128     outs() << format("%6u", Length) << " ";
1129     uint16_t Kind;
1130     DI->getKind(Kind);
1131     if (verbose) {
1132       switch (Kind) {
1133       case MachO::DICE_KIND_DATA:
1134         outs() << "DATA";
1135         break;
1136       case MachO::DICE_KIND_JUMP_TABLE8:
1137         outs() << "JUMP_TABLE8";
1138         break;
1139       case MachO::DICE_KIND_JUMP_TABLE16:
1140         outs() << "JUMP_TABLE16";
1141         break;
1142       case MachO::DICE_KIND_JUMP_TABLE32:
1143         outs() << "JUMP_TABLE32";
1144         break;
1145       case MachO::DICE_KIND_ABS_JUMP_TABLE32:
1146         outs() << "ABS_JUMP_TABLE32";
1147         break;
1148       default:
1149         outs() << format("0x%04" PRIx32, Kind);
1150         break;
1151       }
1152     } else
1153       outs() << format("0x%04" PRIx32, Kind);
1154     outs() << "\n";
1155   }
1156 }
1157 
1158 static void PrintLinkOptHints(MachOObjectFile *O) {
1159   MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
1160   const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
1161   uint32_t nloh = LohLC.datasize;
1162   outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
1163   for (uint32_t i = 0; i < nloh;) {
1164     unsigned n;
1165     uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
1166     i += n;
1167     outs() << "    identifier " << identifier << " ";
1168     if (i >= nloh)
1169       return;
1170     switch (identifier) {
1171     case 1:
1172       outs() << "AdrpAdrp\n";
1173       break;
1174     case 2:
1175       outs() << "AdrpLdr\n";
1176       break;
1177     case 3:
1178       outs() << "AdrpAddLdr\n";
1179       break;
1180     case 4:
1181       outs() << "AdrpLdrGotLdr\n";
1182       break;
1183     case 5:
1184       outs() << "AdrpAddStr\n";
1185       break;
1186     case 6:
1187       outs() << "AdrpLdrGotStr\n";
1188       break;
1189     case 7:
1190       outs() << "AdrpAdd\n";
1191       break;
1192     case 8:
1193       outs() << "AdrpLdrGot\n";
1194       break;
1195     default:
1196       outs() << "Unknown identifier value\n";
1197       break;
1198     }
1199     uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
1200     i += n;
1201     outs() << "    narguments " << narguments << "\n";
1202     if (i >= nloh)
1203       return;
1204 
1205     for (uint32_t j = 0; j < narguments; j++) {
1206       uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
1207       i += n;
1208       outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
1209       if (i >= nloh)
1210         return;
1211     }
1212   }
1213 }
1214 
1215 static void PrintDylibs(MachOObjectFile *O, bool JustId) {
1216   unsigned Index = 0;
1217   for (const auto &Load : O->load_commands()) {
1218     if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
1219         (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
1220                      Load.C.cmd == MachO::LC_LOAD_DYLIB ||
1221                      Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
1222                      Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
1223                      Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
1224                      Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
1225       MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
1226       if (dl.dylib.name < dl.cmdsize) {
1227         const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
1228         if (JustId)
1229           outs() << p << "\n";
1230         else {
1231           outs() << "\t" << p;
1232           outs() << " (compatibility version "
1233                  << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
1234                  << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
1235                  << (dl.dylib.compatibility_version & 0xff) << ",";
1236           outs() << " current version "
1237                  << ((dl.dylib.current_version >> 16) & 0xffff) << "."
1238                  << ((dl.dylib.current_version >> 8) & 0xff) << "."
1239                  << (dl.dylib.current_version & 0xff);
1240           if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
1241             outs() << ", weak";
1242           if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
1243             outs() << ", reexport";
1244           if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
1245             outs() << ", upward";
1246           if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
1247             outs() << ", lazy";
1248           outs() << ")\n";
1249         }
1250       } else {
1251         outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
1252         if (Load.C.cmd == MachO::LC_ID_DYLIB)
1253           outs() << "LC_ID_DYLIB ";
1254         else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
1255           outs() << "LC_LOAD_DYLIB ";
1256         else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
1257           outs() << "LC_LOAD_WEAK_DYLIB ";
1258         else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
1259           outs() << "LC_LAZY_LOAD_DYLIB ";
1260         else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
1261           outs() << "LC_REEXPORT_DYLIB ";
1262         else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
1263           outs() << "LC_LOAD_UPWARD_DYLIB ";
1264         else
1265           outs() << "LC_??? ";
1266         outs() << "command " << Index++ << "\n";
1267       }
1268     }
1269   }
1270 }
1271 
1272 typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
1273 
1274 static void CreateSymbolAddressMap(MachOObjectFile *O,
1275                                    SymbolAddressMap *AddrMap) {
1276   // Create a map of symbol addresses to symbol names.
1277   const StringRef FileName = O->getFileName();
1278   for (const SymbolRef &Symbol : O->symbols()) {
1279     SymbolRef::Type ST = unwrapOrError(Symbol.getType(), FileName);
1280     if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
1281         ST == SymbolRef::ST_Other) {
1282       uint64_t Address = Symbol.getValue();
1283       StringRef SymName = unwrapOrError(Symbol.getName(), FileName);
1284       if (!SymName.startswith(".objc"))
1285         (*AddrMap)[Address] = SymName;
1286     }
1287   }
1288 }
1289 
1290 // GuessSymbolName is passed the address of what might be a symbol and a
1291 // pointer to the SymbolAddressMap.  It returns the name of a symbol
1292 // with that address or nullptr if no symbol is found with that address.
1293 static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
1294   const char *SymbolName = nullptr;
1295   // A DenseMap can't lookup up some values.
1296   if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
1297     StringRef name = AddrMap->lookup(value);
1298     if (!name.empty())
1299       SymbolName = name.data();
1300   }
1301   return SymbolName;
1302 }
1303 
1304 static void DumpCstringChar(const char c) {
1305   char p[2];
1306   p[0] = c;
1307   p[1] = '\0';
1308   outs().write_escaped(p);
1309 }
1310 
1311 static void DumpCstringSection(MachOObjectFile *O, const char *sect,
1312                                uint32_t sect_size, uint64_t sect_addr,
1313                                bool print_addresses) {
1314   for (uint32_t i = 0; i < sect_size; i++) {
1315     if (print_addresses) {
1316       if (O->is64Bit())
1317         outs() << format("%016" PRIx64, sect_addr + i) << "  ";
1318       else
1319         outs() << format("%08" PRIx64, sect_addr + i) << "  ";
1320     }
1321     for (; i < sect_size && sect[i] != '\0'; i++)
1322       DumpCstringChar(sect[i]);
1323     if (i < sect_size && sect[i] == '\0')
1324       outs() << "\n";
1325   }
1326 }
1327 
1328 static void DumpLiteral4(uint32_t l, float f) {
1329   outs() << format("0x%08" PRIx32, l);
1330   if ((l & 0x7f800000) != 0x7f800000)
1331     outs() << format(" (%.16e)\n", f);
1332   else {
1333     if (l == 0x7f800000)
1334       outs() << " (+Infinity)\n";
1335     else if (l == 0xff800000)
1336       outs() << " (-Infinity)\n";
1337     else if ((l & 0x00400000) == 0x00400000)
1338       outs() << " (non-signaling Not-a-Number)\n";
1339     else
1340       outs() << " (signaling Not-a-Number)\n";
1341   }
1342 }
1343 
1344 static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
1345                                 uint32_t sect_size, uint64_t sect_addr,
1346                                 bool print_addresses) {
1347   for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
1348     if (print_addresses) {
1349       if (O->is64Bit())
1350         outs() << format("%016" PRIx64, sect_addr + i) << "  ";
1351       else
1352         outs() << format("%08" PRIx64, sect_addr + i) << "  ";
1353     }
1354     float f;
1355     memcpy(&f, sect + i, sizeof(float));
1356     if (O->isLittleEndian() != sys::IsLittleEndianHost)
1357       sys::swapByteOrder(f);
1358     uint32_t l;
1359     memcpy(&l, sect + i, sizeof(uint32_t));
1360     if (O->isLittleEndian() != sys::IsLittleEndianHost)
1361       sys::swapByteOrder(l);
1362     DumpLiteral4(l, f);
1363   }
1364 }
1365 
1366 static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
1367                          double d) {
1368   outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
1369   uint32_t Hi, Lo;
1370   Hi = (O->isLittleEndian()) ? l1 : l0;
1371   Lo = (O->isLittleEndian()) ? l0 : l1;
1372 
1373   // Hi is the high word, so this is equivalent to if(isfinite(d))
1374   if ((Hi & 0x7ff00000) != 0x7ff00000)
1375     outs() << format(" (%.16e)\n", d);
1376   else {
1377     if (Hi == 0x7ff00000 && Lo == 0)
1378       outs() << " (+Infinity)\n";
1379     else if (Hi == 0xfff00000 && Lo == 0)
1380       outs() << " (-Infinity)\n";
1381     else if ((Hi & 0x00080000) == 0x00080000)
1382       outs() << " (non-signaling Not-a-Number)\n";
1383     else
1384       outs() << " (signaling Not-a-Number)\n";
1385   }
1386 }
1387 
1388 static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
1389                                 uint32_t sect_size, uint64_t sect_addr,
1390                                 bool print_addresses) {
1391   for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
1392     if (print_addresses) {
1393       if (O->is64Bit())
1394         outs() << format("%016" PRIx64, sect_addr + i) << "  ";
1395       else
1396         outs() << format("%08" PRIx64, sect_addr + i) << "  ";
1397     }
1398     double d;
1399     memcpy(&d, sect + i, sizeof(double));
1400     if (O->isLittleEndian() != sys::IsLittleEndianHost)
1401       sys::swapByteOrder(d);
1402     uint32_t l0, l1;
1403     memcpy(&l0, sect + i, sizeof(uint32_t));
1404     memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
1405     if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1406       sys::swapByteOrder(l0);
1407       sys::swapByteOrder(l1);
1408     }
1409     DumpLiteral8(O, l0, l1, d);
1410   }
1411 }
1412 
1413 static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
1414   outs() << format("0x%08" PRIx32, l0) << " ";
1415   outs() << format("0x%08" PRIx32, l1) << " ";
1416   outs() << format("0x%08" PRIx32, l2) << " ";
1417   outs() << format("0x%08" PRIx32, l3) << "\n";
1418 }
1419 
1420 static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
1421                                  uint32_t sect_size, uint64_t sect_addr,
1422                                  bool print_addresses) {
1423   for (uint32_t i = 0; i < sect_size; i += 16) {
1424     if (print_addresses) {
1425       if (O->is64Bit())
1426         outs() << format("%016" PRIx64, sect_addr + i) << "  ";
1427       else
1428         outs() << format("%08" PRIx64, sect_addr + i) << "  ";
1429     }
1430     uint32_t l0, l1, l2, l3;
1431     memcpy(&l0, sect + i, sizeof(uint32_t));
1432     memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
1433     memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
1434     memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
1435     if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1436       sys::swapByteOrder(l0);
1437       sys::swapByteOrder(l1);
1438       sys::swapByteOrder(l2);
1439       sys::swapByteOrder(l3);
1440     }
1441     DumpLiteral16(l0, l1, l2, l3);
1442   }
1443 }
1444 
1445 static void DumpLiteralPointerSection(MachOObjectFile *O,
1446                                       const SectionRef &Section,
1447                                       const char *sect, uint32_t sect_size,
1448                                       uint64_t sect_addr,
1449                                       bool print_addresses) {
1450   // Collect the literal sections in this Mach-O file.
1451   std::vector<SectionRef> LiteralSections;
1452   for (const SectionRef &Section : O->sections()) {
1453     DataRefImpl Ref = Section.getRawDataRefImpl();
1454     uint32_t section_type;
1455     if (O->is64Bit()) {
1456       const MachO::section_64 Sec = O->getSection64(Ref);
1457       section_type = Sec.flags & MachO::SECTION_TYPE;
1458     } else {
1459       const MachO::section Sec = O->getSection(Ref);
1460       section_type = Sec.flags & MachO::SECTION_TYPE;
1461     }
1462     if (section_type == MachO::S_CSTRING_LITERALS ||
1463         section_type == MachO::S_4BYTE_LITERALS ||
1464         section_type == MachO::S_8BYTE_LITERALS ||
1465         section_type == MachO::S_16BYTE_LITERALS)
1466       LiteralSections.push_back(Section);
1467   }
1468 
1469   // Set the size of the literal pointer.
1470   uint32_t lp_size = O->is64Bit() ? 8 : 4;
1471 
1472   // Collect the external relocation symbols for the literal pointers.
1473   std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1474   for (const RelocationRef &Reloc : Section.relocations()) {
1475     DataRefImpl Rel;
1476     MachO::any_relocation_info RE;
1477     bool isExtern = false;
1478     Rel = Reloc.getRawDataRefImpl();
1479     RE = O->getRelocation(Rel);
1480     isExtern = O->getPlainRelocationExternal(RE);
1481     if (isExtern) {
1482       uint64_t RelocOffset = Reloc.getOffset();
1483       symbol_iterator RelocSym = Reloc.getSymbol();
1484       Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
1485     }
1486   }
1487   array_pod_sort(Relocs.begin(), Relocs.end());
1488 
1489   // Dump each literal pointer.
1490   for (uint32_t i = 0; i < sect_size; i += lp_size) {
1491     if (print_addresses) {
1492       if (O->is64Bit())
1493         outs() << format("%016" PRIx64, sect_addr + i) << "  ";
1494       else
1495         outs() << format("%08" PRIx64, sect_addr + i) << "  ";
1496     }
1497     uint64_t lp;
1498     if (O->is64Bit()) {
1499       memcpy(&lp, sect + i, sizeof(uint64_t));
1500       if (O->isLittleEndian() != sys::IsLittleEndianHost)
1501         sys::swapByteOrder(lp);
1502     } else {
1503       uint32_t li;
1504       memcpy(&li, sect + i, sizeof(uint32_t));
1505       if (O->isLittleEndian() != sys::IsLittleEndianHost)
1506         sys::swapByteOrder(li);
1507       lp = li;
1508     }
1509 
1510     // First look for an external relocation entry for this literal pointer.
1511     auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
1512       return P.first == i;
1513     });
1514     if (Reloc != Relocs.end()) {
1515       symbol_iterator RelocSym = Reloc->second;
1516       StringRef SymName = unwrapOrError(RelocSym->getName(), O->getFileName());
1517       outs() << "external relocation entry for symbol:" << SymName << "\n";
1518       continue;
1519     }
1520 
1521     // For local references see what the section the literal pointer points to.
1522     auto Sect = find_if(LiteralSections, [&](const SectionRef &R) {
1523       return lp >= R.getAddress() && lp < R.getAddress() + R.getSize();
1524     });
1525     if (Sect == LiteralSections.end()) {
1526       outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
1527       continue;
1528     }
1529 
1530     uint64_t SectAddress = Sect->getAddress();
1531     uint64_t SectSize = Sect->getSize();
1532 
1533     StringRef SectName;
1534     Expected<StringRef> SectNameOrErr = Sect->getName();
1535     if (SectNameOrErr)
1536       SectName = *SectNameOrErr;
1537     else
1538       consumeError(SectNameOrErr.takeError());
1539 
1540     DataRefImpl Ref = Sect->getRawDataRefImpl();
1541     StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
1542     outs() << SegmentName << ":" << SectName << ":";
1543 
1544     uint32_t section_type;
1545     if (O->is64Bit()) {
1546       const MachO::section_64 Sec = O->getSection64(Ref);
1547       section_type = Sec.flags & MachO::SECTION_TYPE;
1548     } else {
1549       const MachO::section Sec = O->getSection(Ref);
1550       section_type = Sec.flags & MachO::SECTION_TYPE;
1551     }
1552 
1553     StringRef BytesStr = unwrapOrError(Sect->getContents(), O->getFileName());
1554 
1555     const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
1556 
1557     switch (section_type) {
1558     case MachO::S_CSTRING_LITERALS:
1559       for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
1560            i++) {
1561         DumpCstringChar(Contents[i]);
1562       }
1563       outs() << "\n";
1564       break;
1565     case MachO::S_4BYTE_LITERALS:
1566       float f;
1567       memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
1568       uint32_t l;
1569       memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
1570       if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1571         sys::swapByteOrder(f);
1572         sys::swapByteOrder(l);
1573       }
1574       DumpLiteral4(l, f);
1575       break;
1576     case MachO::S_8BYTE_LITERALS: {
1577       double d;
1578       memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
1579       uint32_t l0, l1;
1580       memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
1581       memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
1582              sizeof(uint32_t));
1583       if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1584         sys::swapByteOrder(f);
1585         sys::swapByteOrder(l0);
1586         sys::swapByteOrder(l1);
1587       }
1588       DumpLiteral8(O, l0, l1, d);
1589       break;
1590     }
1591     case MachO::S_16BYTE_LITERALS: {
1592       uint32_t l0, l1, l2, l3;
1593       memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
1594       memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
1595              sizeof(uint32_t));
1596       memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
1597              sizeof(uint32_t));
1598       memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
1599              sizeof(uint32_t));
1600       if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1601         sys::swapByteOrder(l0);
1602         sys::swapByteOrder(l1);
1603         sys::swapByteOrder(l2);
1604         sys::swapByteOrder(l3);
1605       }
1606       DumpLiteral16(l0, l1, l2, l3);
1607       break;
1608     }
1609     }
1610   }
1611 }
1612 
1613 static void DumpInitTermPointerSection(MachOObjectFile *O,
1614                                        const SectionRef &Section,
1615                                        const char *sect,
1616                                        uint32_t sect_size, uint64_t sect_addr,
1617                                        SymbolAddressMap *AddrMap,
1618                                        bool verbose) {
1619   uint32_t stride;
1620   stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t);
1621 
1622   // Collect the external relocation symbols for the pointers.
1623   std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1624   for (const RelocationRef &Reloc : Section.relocations()) {
1625     DataRefImpl Rel;
1626     MachO::any_relocation_info RE;
1627     bool isExtern = false;
1628     Rel = Reloc.getRawDataRefImpl();
1629     RE = O->getRelocation(Rel);
1630     isExtern = O->getPlainRelocationExternal(RE);
1631     if (isExtern) {
1632       uint64_t RelocOffset = Reloc.getOffset();
1633       symbol_iterator RelocSym = Reloc.getSymbol();
1634       Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
1635     }
1636   }
1637   array_pod_sort(Relocs.begin(), Relocs.end());
1638 
1639   for (uint32_t i = 0; i < sect_size; i += stride) {
1640     const char *SymbolName = nullptr;
1641     uint64_t p;
1642     if (O->is64Bit()) {
1643       outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
1644       uint64_t pointer_value;
1645       memcpy(&pointer_value, sect + i, stride);
1646       if (O->isLittleEndian() != sys::IsLittleEndianHost)
1647         sys::swapByteOrder(pointer_value);
1648       outs() << format("0x%016" PRIx64, pointer_value);
1649       p = pointer_value;
1650     } else {
1651       outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
1652       uint32_t pointer_value;
1653       memcpy(&pointer_value, sect + i, stride);
1654       if (O->isLittleEndian() != sys::IsLittleEndianHost)
1655         sys::swapByteOrder(pointer_value);
1656       outs() << format("0x%08" PRIx32, pointer_value);
1657       p = pointer_value;
1658     }
1659     if (verbose) {
1660       // First look for an external relocation entry for this pointer.
1661       auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
1662         return P.first == i;
1663       });
1664       if (Reloc != Relocs.end()) {
1665         symbol_iterator RelocSym = Reloc->second;
1666         outs() << " " << unwrapOrError(RelocSym->getName(), O->getFileName());
1667       } else {
1668         SymbolName = GuessSymbolName(p, AddrMap);
1669         if (SymbolName)
1670           outs() << " " << SymbolName;
1671       }
1672     }
1673     outs() << "\n";
1674   }
1675 }
1676 
1677 static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
1678                                    uint32_t size, uint64_t addr) {
1679   uint32_t cputype = O->getHeader().cputype;
1680   if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
1681     uint32_t j;
1682     for (uint32_t i = 0; i < size; i += j, addr += j) {
1683       if (O->is64Bit())
1684         outs() << format("%016" PRIx64, addr) << "\t";
1685       else
1686         outs() << format("%08" PRIx64, addr) << "\t";
1687       for (j = 0; j < 16 && i + j < size; j++) {
1688         uint8_t byte_word = *(sect + i + j);
1689         outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1690       }
1691       outs() << "\n";
1692     }
1693   } else {
1694     uint32_t j;
1695     for (uint32_t i = 0; i < size; i += j, addr += j) {
1696       if (O->is64Bit())
1697         outs() << format("%016" PRIx64, addr) << "\t";
1698       else
1699         outs() << format("%08" PRIx64, addr) << "\t";
1700       for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
1701            j += sizeof(int32_t)) {
1702         if (i + j + sizeof(int32_t) <= size) {
1703           uint32_t long_word;
1704           memcpy(&long_word, sect + i + j, sizeof(int32_t));
1705           if (O->isLittleEndian() != sys::IsLittleEndianHost)
1706             sys::swapByteOrder(long_word);
1707           outs() << format("%08" PRIx32, long_word) << " ";
1708         } else {
1709           for (uint32_t k = 0; i + j + k < size; k++) {
1710             uint8_t byte_word = *(sect + i + j + k);
1711             outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1712           }
1713         }
1714       }
1715       outs() << "\n";
1716     }
1717   }
1718 }
1719 
1720 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
1721                              StringRef DisSegName, StringRef DisSectName);
1722 static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
1723                                 uint32_t size, uint32_t addr);
1724 #ifdef HAVE_LIBXAR
1725 static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
1726                                 uint32_t size, bool verbose,
1727                                 bool PrintXarHeader, bool PrintXarFileHeaders,
1728                                 std::string XarMemberName);
1729 #endif // defined(HAVE_LIBXAR)
1730 
1731 static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
1732                                 bool verbose) {
1733   SymbolAddressMap AddrMap;
1734   if (verbose)
1735     CreateSymbolAddressMap(O, &AddrMap);
1736 
1737   for (unsigned i = 0; i < FilterSections.size(); ++i) {
1738     StringRef DumpSection = FilterSections[i];
1739     std::pair<StringRef, StringRef> DumpSegSectName;
1740     DumpSegSectName = DumpSection.split(',');
1741     StringRef DumpSegName, DumpSectName;
1742     if (!DumpSegSectName.second.empty()) {
1743       DumpSegName = DumpSegSectName.first;
1744       DumpSectName = DumpSegSectName.second;
1745     } else {
1746       DumpSegName = "";
1747       DumpSectName = DumpSegSectName.first;
1748     }
1749     for (const SectionRef &Section : O->sections()) {
1750       StringRef SectName;
1751       Expected<StringRef> SecNameOrErr = Section.getName();
1752       if (SecNameOrErr)
1753         SectName = *SecNameOrErr;
1754       else
1755         consumeError(SecNameOrErr.takeError());
1756 
1757       DataRefImpl Ref = Section.getRawDataRefImpl();
1758       StringRef SegName = O->getSectionFinalSegmentName(Ref);
1759       if ((DumpSegName.empty() || SegName == DumpSegName) &&
1760           (SectName == DumpSectName)) {
1761 
1762         uint32_t section_flags;
1763         if (O->is64Bit()) {
1764           const MachO::section_64 Sec = O->getSection64(Ref);
1765           section_flags = Sec.flags;
1766 
1767         } else {
1768           const MachO::section Sec = O->getSection(Ref);
1769           section_flags = Sec.flags;
1770         }
1771         uint32_t section_type = section_flags & MachO::SECTION_TYPE;
1772 
1773         StringRef BytesStr =
1774             unwrapOrError(Section.getContents(), O->getFileName());
1775         const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1776         uint32_t sect_size = BytesStr.size();
1777         uint64_t sect_addr = Section.getAddress();
1778 
1779         outs() << "Contents of (" << SegName << "," << SectName
1780                << ") section\n";
1781 
1782         if (verbose) {
1783           if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1784               (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1785             DisassembleMachO(Filename, O, SegName, SectName);
1786             continue;
1787           }
1788           if (SegName == "__TEXT" && SectName == "__info_plist") {
1789             outs() << sect;
1790             continue;
1791           }
1792           if (SegName == "__OBJC" && SectName == "__protocol") {
1793             DumpProtocolSection(O, sect, sect_size, sect_addr);
1794             continue;
1795           }
1796 #ifdef HAVE_LIBXAR
1797           if (SegName == "__LLVM" && SectName == "__bundle") {
1798             DumpBitcodeSection(O, sect, sect_size, verbose, !NoSymbolicOperands,
1799                                ArchiveHeaders, "");
1800             continue;
1801           }
1802 #endif // defined(HAVE_LIBXAR)
1803           switch (section_type) {
1804           case MachO::S_REGULAR:
1805             DumpRawSectionContents(O, sect, sect_size, sect_addr);
1806             break;
1807           case MachO::S_ZEROFILL:
1808             outs() << "zerofill section and has no contents in the file\n";
1809             break;
1810           case MachO::S_CSTRING_LITERALS:
1811             DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1812             break;
1813           case MachO::S_4BYTE_LITERALS:
1814             DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1815             break;
1816           case MachO::S_8BYTE_LITERALS:
1817             DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1818             break;
1819           case MachO::S_16BYTE_LITERALS:
1820             DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1821             break;
1822           case MachO::S_LITERAL_POINTERS:
1823             DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
1824                                       !NoLeadingAddr);
1825             break;
1826           case MachO::S_MOD_INIT_FUNC_POINTERS:
1827           case MachO::S_MOD_TERM_FUNC_POINTERS:
1828             DumpInitTermPointerSection(O, Section, sect, sect_size, sect_addr,
1829                                        &AddrMap, verbose);
1830             break;
1831           default:
1832             outs() << "Unknown section type ("
1833                    << format("0x%08" PRIx32, section_type) << ")\n";
1834             DumpRawSectionContents(O, sect, sect_size, sect_addr);
1835             break;
1836           }
1837         } else {
1838           if (section_type == MachO::S_ZEROFILL)
1839             outs() << "zerofill section and has no contents in the file\n";
1840           else
1841             DumpRawSectionContents(O, sect, sect_size, sect_addr);
1842         }
1843       }
1844     }
1845   }
1846 }
1847 
1848 static void DumpInfoPlistSectionContents(StringRef Filename,
1849                                          MachOObjectFile *O) {
1850   for (const SectionRef &Section : O->sections()) {
1851     StringRef SectName;
1852     Expected<StringRef> SecNameOrErr = Section.getName();
1853     if (SecNameOrErr)
1854       SectName = *SecNameOrErr;
1855     else
1856       consumeError(SecNameOrErr.takeError());
1857 
1858     DataRefImpl Ref = Section.getRawDataRefImpl();
1859     StringRef SegName = O->getSectionFinalSegmentName(Ref);
1860     if (SegName == "__TEXT" && SectName == "__info_plist") {
1861       if (!NoLeadingHeaders)
1862         outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
1863       StringRef BytesStr =
1864           unwrapOrError(Section.getContents(), O->getFileName());
1865       const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1866       outs() << format("%.*s", BytesStr.size(), sect) << "\n";
1867       return;
1868     }
1869   }
1870 }
1871 
1872 // checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1873 // and if it is and there is a list of architecture flags is specified then
1874 // check to make sure this Mach-O file is one of those architectures or all
1875 // architectures were specified.  If not then an error is generated and this
1876 // routine returns false.  Else it returns true.
1877 static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
1878   auto *MachO = dyn_cast<MachOObjectFile>(O);
1879 
1880   if (!MachO || ArchAll || ArchFlags.empty())
1881     return true;
1882 
1883   MachO::mach_header H;
1884   MachO::mach_header_64 H_64;
1885   Triple T;
1886   const char *McpuDefault, *ArchFlag;
1887   if (MachO->is64Bit()) {
1888     H_64 = MachO->MachOObjectFile::getHeader64();
1889     T = MachOObjectFile::getArchTriple(H_64.cputype, H_64.cpusubtype,
1890                                        &McpuDefault, &ArchFlag);
1891   } else {
1892     H = MachO->MachOObjectFile::getHeader();
1893     T = MachOObjectFile::getArchTriple(H.cputype, H.cpusubtype,
1894                                        &McpuDefault, &ArchFlag);
1895   }
1896   const std::string ArchFlagName(ArchFlag);
1897   if (none_of(ArchFlags, [&](const std::string &Name) {
1898         return Name == ArchFlagName;
1899       })) {
1900     WithColor::error(errs(), "llvm-objdump")
1901         << Filename << ": no architecture specified.\n";
1902     return false;
1903   }
1904   return true;
1905 }
1906 
1907 static void printObjcMetaData(MachOObjectFile *O, bool verbose);
1908 
1909 // ProcessMachO() is passed a single opened Mach-O file, which may be an
1910 // archive member and or in a slice of a universal file.  It prints the
1911 // the file name and header info and then processes it according to the
1912 // command line options.
1913 static void ProcessMachO(StringRef Name, MachOObjectFile *MachOOF,
1914                          StringRef ArchiveMemberName = StringRef(),
1915                          StringRef ArchitectureName = StringRef()) {
1916   // If we are doing some processing here on the Mach-O file print the header
1917   // info.  And don't print it otherwise like in the case of printing the
1918   // UniversalHeaders or ArchiveHeaders.
1919   if (Disassemble || Relocations || PrivateHeaders || ExportsTrie || Rebase ||
1920       Bind || SymbolTable || LazyBind || WeakBind || IndirectSymbols ||
1921       DataInCode || LinkOptHints || DylibsUsed || DylibId || ObjcMetaData ||
1922       (!FilterSections.empty())) {
1923     if (!NoLeadingHeaders) {
1924       outs() << Name;
1925       if (!ArchiveMemberName.empty())
1926         outs() << '(' << ArchiveMemberName << ')';
1927       if (!ArchitectureName.empty())
1928         outs() << " (architecture " << ArchitectureName << ")";
1929       outs() << ":\n";
1930     }
1931   }
1932   // To use the report_error() form with an ArchiveName and FileName set
1933   // these up based on what is passed for Name and ArchiveMemberName.
1934   StringRef ArchiveName;
1935   StringRef FileName;
1936   if (!ArchiveMemberName.empty()) {
1937     ArchiveName = Name;
1938     FileName = ArchiveMemberName;
1939   } else {
1940     ArchiveName = StringRef();
1941     FileName = Name;
1942   }
1943 
1944   // If we need the symbol table to do the operation then check it here to
1945   // produce a good error message as to where the Mach-O file comes from in
1946   // the error message.
1947   if (Disassemble || IndirectSymbols || !FilterSections.empty() || UnwindInfo)
1948     if (Error Err = MachOOF->checkSymbolTable())
1949       reportError(std::move(Err), FileName, ArchiveName, ArchitectureName);
1950 
1951   if (DisassembleAll) {
1952     for (const SectionRef &Section : MachOOF->sections()) {
1953       StringRef SectName;
1954       if (Expected<StringRef> NameOrErr = Section.getName())
1955         SectName = *NameOrErr;
1956       else
1957         consumeError(NameOrErr.takeError());
1958 
1959       if (SectName.equals("__text")) {
1960         DataRefImpl Ref = Section.getRawDataRefImpl();
1961         StringRef SegName = MachOOF->getSectionFinalSegmentName(Ref);
1962         DisassembleMachO(FileName, MachOOF, SegName, SectName);
1963       }
1964     }
1965   }
1966   else if (Disassemble) {
1967     if (MachOOF->getHeader().filetype == MachO::MH_KEXT_BUNDLE &&
1968         MachOOF->getHeader().cputype == MachO::CPU_TYPE_ARM64)
1969       DisassembleMachO(FileName, MachOOF, "__TEXT_EXEC", "__text");
1970     else
1971       DisassembleMachO(FileName, MachOOF, "__TEXT", "__text");
1972   }
1973   if (IndirectSymbols)
1974     PrintIndirectSymbols(MachOOF, !NonVerbose);
1975   if (DataInCode)
1976     PrintDataInCodeTable(MachOOF, !NonVerbose);
1977   if (LinkOptHints)
1978     PrintLinkOptHints(MachOOF);
1979   if (Relocations)
1980     PrintRelocations(MachOOF, !NonVerbose);
1981   if (SectionHeaders)
1982     printSectionHeaders(MachOOF);
1983   if (SectionContents)
1984     printSectionContents(MachOOF);
1985   if (!FilterSections.empty())
1986     DumpSectionContents(FileName, MachOOF, !NonVerbose);
1987   if (InfoPlist)
1988     DumpInfoPlistSectionContents(FileName, MachOOF);
1989   if (DylibsUsed)
1990     PrintDylibs(MachOOF, false);
1991   if (DylibId)
1992     PrintDylibs(MachOOF, true);
1993   if (SymbolTable)
1994     printSymbolTable(MachOOF, ArchiveName, ArchitectureName);
1995   if (UnwindInfo)
1996     printMachOUnwindInfo(MachOOF);
1997   if (PrivateHeaders) {
1998     printMachOFileHeader(MachOOF);
1999     printMachOLoadCommands(MachOOF);
2000   }
2001   if (FirstPrivateHeader)
2002     printMachOFileHeader(MachOOF);
2003   if (ObjcMetaData)
2004     printObjcMetaData(MachOOF, !NonVerbose);
2005   if (ExportsTrie)
2006     printExportsTrie(MachOOF);
2007   if (Rebase)
2008     printRebaseTable(MachOOF);
2009   if (Bind)
2010     printBindTable(MachOOF);
2011   if (LazyBind)
2012     printLazyBindTable(MachOOF);
2013   if (WeakBind)
2014     printWeakBindTable(MachOOF);
2015 
2016   if (DwarfDumpType != DIDT_Null) {
2017     std::unique_ptr<DIContext> DICtx = DWARFContext::create(*MachOOF);
2018     // Dump the complete DWARF structure.
2019     DIDumpOptions DumpOpts;
2020     DumpOpts.DumpType = DwarfDumpType;
2021     DICtx->dump(outs(), DumpOpts);
2022   }
2023 }
2024 
2025 // printUnknownCPUType() helps print_fat_headers for unknown CPU's.
2026 static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
2027   outs() << "    cputype (" << cputype << ")\n";
2028   outs() << "    cpusubtype (" << cpusubtype << ")\n";
2029 }
2030 
2031 // printCPUType() helps print_fat_headers by printing the cputype and
2032 // pusubtype (symbolically for the one's it knows about).
2033 static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
2034   switch (cputype) {
2035   case MachO::CPU_TYPE_I386:
2036     switch (cpusubtype) {
2037     case MachO::CPU_SUBTYPE_I386_ALL:
2038       outs() << "    cputype CPU_TYPE_I386\n";
2039       outs() << "    cpusubtype CPU_SUBTYPE_I386_ALL\n";
2040       break;
2041     default:
2042       printUnknownCPUType(cputype, cpusubtype);
2043       break;
2044     }
2045     break;
2046   case MachO::CPU_TYPE_X86_64:
2047     switch (cpusubtype) {
2048     case MachO::CPU_SUBTYPE_X86_64_ALL:
2049       outs() << "    cputype CPU_TYPE_X86_64\n";
2050       outs() << "    cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
2051       break;
2052     case MachO::CPU_SUBTYPE_X86_64_H:
2053       outs() << "    cputype CPU_TYPE_X86_64\n";
2054       outs() << "    cpusubtype CPU_SUBTYPE_X86_64_H\n";
2055       break;
2056     default:
2057       printUnknownCPUType(cputype, cpusubtype);
2058       break;
2059     }
2060     break;
2061   case MachO::CPU_TYPE_ARM:
2062     switch (cpusubtype) {
2063     case MachO::CPU_SUBTYPE_ARM_ALL:
2064       outs() << "    cputype CPU_TYPE_ARM\n";
2065       outs() << "    cpusubtype CPU_SUBTYPE_ARM_ALL\n";
2066       break;
2067     case MachO::CPU_SUBTYPE_ARM_V4T:
2068       outs() << "    cputype CPU_TYPE_ARM\n";
2069       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V4T\n";
2070       break;
2071     case MachO::CPU_SUBTYPE_ARM_V5TEJ:
2072       outs() << "    cputype CPU_TYPE_ARM\n";
2073       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
2074       break;
2075     case MachO::CPU_SUBTYPE_ARM_XSCALE:
2076       outs() << "    cputype CPU_TYPE_ARM\n";
2077       outs() << "    cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
2078       break;
2079     case MachO::CPU_SUBTYPE_ARM_V6:
2080       outs() << "    cputype CPU_TYPE_ARM\n";
2081       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V6\n";
2082       break;
2083     case MachO::CPU_SUBTYPE_ARM_V6M:
2084       outs() << "    cputype CPU_TYPE_ARM\n";
2085       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V6M\n";
2086       break;
2087     case MachO::CPU_SUBTYPE_ARM_V7:
2088       outs() << "    cputype CPU_TYPE_ARM\n";
2089       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V7\n";
2090       break;
2091     case MachO::CPU_SUBTYPE_ARM_V7EM:
2092       outs() << "    cputype CPU_TYPE_ARM\n";
2093       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
2094       break;
2095     case MachO::CPU_SUBTYPE_ARM_V7K:
2096       outs() << "    cputype CPU_TYPE_ARM\n";
2097       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V7K\n";
2098       break;
2099     case MachO::CPU_SUBTYPE_ARM_V7M:
2100       outs() << "    cputype CPU_TYPE_ARM\n";
2101       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V7M\n";
2102       break;
2103     case MachO::CPU_SUBTYPE_ARM_V7S:
2104       outs() << "    cputype CPU_TYPE_ARM\n";
2105       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V7S\n";
2106       break;
2107     default:
2108       printUnknownCPUType(cputype, cpusubtype);
2109       break;
2110     }
2111     break;
2112   case MachO::CPU_TYPE_ARM64:
2113     switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2114     case MachO::CPU_SUBTYPE_ARM64_ALL:
2115       outs() << "    cputype CPU_TYPE_ARM64\n";
2116       outs() << "    cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
2117       break;
2118     case MachO::CPU_SUBTYPE_ARM64E:
2119       outs() << "    cputype CPU_TYPE_ARM64\n";
2120       outs() << "    cpusubtype CPU_SUBTYPE_ARM64E\n";
2121       break;
2122     default:
2123       printUnknownCPUType(cputype, cpusubtype);
2124       break;
2125     }
2126     break;
2127   case MachO::CPU_TYPE_ARM64_32:
2128     switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2129     case MachO::CPU_SUBTYPE_ARM64_32_V8:
2130       outs() << "    cputype CPU_TYPE_ARM64_32\n";
2131       outs() << "    cpusubtype CPU_SUBTYPE_ARM64_32_V8\n";
2132       break;
2133     default:
2134       printUnknownCPUType(cputype, cpusubtype);
2135       break;
2136     }
2137     break;
2138   default:
2139     printUnknownCPUType(cputype, cpusubtype);
2140     break;
2141   }
2142 }
2143 
2144 static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
2145                                        bool verbose) {
2146   outs() << "Fat headers\n";
2147   if (verbose) {
2148     if (UB->getMagic() == MachO::FAT_MAGIC)
2149       outs() << "fat_magic FAT_MAGIC\n";
2150     else // UB->getMagic() == MachO::FAT_MAGIC_64
2151       outs() << "fat_magic FAT_MAGIC_64\n";
2152   } else
2153     outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
2154 
2155   uint32_t nfat_arch = UB->getNumberOfObjects();
2156   StringRef Buf = UB->getData();
2157   uint64_t size = Buf.size();
2158   uint64_t big_size = sizeof(struct MachO::fat_header) +
2159                       nfat_arch * sizeof(struct MachO::fat_arch);
2160   outs() << "nfat_arch " << UB->getNumberOfObjects();
2161   if (nfat_arch == 0)
2162     outs() << " (malformed, contains zero architecture types)\n";
2163   else if (big_size > size)
2164     outs() << " (malformed, architectures past end of file)\n";
2165   else
2166     outs() << "\n";
2167 
2168   for (uint32_t i = 0; i < nfat_arch; ++i) {
2169     MachOUniversalBinary::ObjectForArch OFA(UB, i);
2170     uint32_t cputype = OFA.getCPUType();
2171     uint32_t cpusubtype = OFA.getCPUSubType();
2172     outs() << "architecture ";
2173     for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
2174       MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
2175       uint32_t other_cputype = other_OFA.getCPUType();
2176       uint32_t other_cpusubtype = other_OFA.getCPUSubType();
2177       if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
2178           (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
2179               (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
2180         outs() << "(illegal duplicate architecture) ";
2181         break;
2182       }
2183     }
2184     if (verbose) {
2185       outs() << OFA.getArchFlagName() << "\n";
2186       printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2187     } else {
2188       outs() << i << "\n";
2189       outs() << "    cputype " << cputype << "\n";
2190       outs() << "    cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
2191              << "\n";
2192     }
2193     if (verbose &&
2194         (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
2195       outs() << "    capabilities CPU_SUBTYPE_LIB64\n";
2196     else
2197       outs() << "    capabilities "
2198              << format("0x%" PRIx32,
2199                        (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
2200     outs() << "    offset " << OFA.getOffset();
2201     if (OFA.getOffset() > size)
2202       outs() << " (past end of file)";
2203     if (OFA.getOffset() % (1ull << OFA.getAlign()) != 0)
2204       outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
2205     outs() << "\n";
2206     outs() << "    size " << OFA.getSize();
2207     big_size = OFA.getOffset() + OFA.getSize();
2208     if (big_size > size)
2209       outs() << " (past end of file)";
2210     outs() << "\n";
2211     outs() << "    align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
2212            << ")\n";
2213   }
2214 }
2215 
2216 static void printArchiveChild(StringRef Filename, const Archive::Child &C,
2217                               size_t ChildIndex, bool verbose,
2218                               bool print_offset,
2219                               StringRef ArchitectureName = StringRef()) {
2220   if (print_offset)
2221     outs() << C.getChildOffset() << "\t";
2222   sys::fs::perms Mode =
2223       unwrapOrError(C.getAccessMode(), getFileNameForError(C, ChildIndex),
2224                     Filename, ArchitectureName);
2225   if (verbose) {
2226     // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
2227     // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
2228     outs() << "-";
2229     outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
2230     outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
2231     outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
2232     outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
2233     outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
2234     outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
2235     outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
2236     outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
2237     outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
2238   } else {
2239     outs() << format("0%o ", Mode);
2240   }
2241 
2242   outs() << format("%3d/%-3d %5" PRId64 " ",
2243                    unwrapOrError(C.getUID(), getFileNameForError(C, ChildIndex),
2244                                  Filename, ArchitectureName),
2245                    unwrapOrError(C.getGID(), getFileNameForError(C, ChildIndex),
2246                                  Filename, ArchitectureName),
2247                    unwrapOrError(C.getRawSize(),
2248                                  getFileNameForError(C, ChildIndex), Filename,
2249                                  ArchitectureName));
2250 
2251   StringRef RawLastModified = C.getRawLastModified();
2252   if (verbose) {
2253     unsigned Seconds;
2254     if (RawLastModified.getAsInteger(10, Seconds))
2255       outs() << "(date: \"" << RawLastModified
2256              << "\" contains non-decimal chars) ";
2257     else {
2258       // Since cime(3) returns a 26 character string of the form:
2259       // "Sun Sep 16 01:03:52 1973\n\0"
2260       // just print 24 characters.
2261       time_t t = Seconds;
2262       outs() << format("%.24s ", ctime(&t));
2263     }
2264   } else {
2265     outs() << RawLastModified << " ";
2266   }
2267 
2268   if (verbose) {
2269     Expected<StringRef> NameOrErr = C.getName();
2270     if (!NameOrErr) {
2271       consumeError(NameOrErr.takeError());
2272       outs() << unwrapOrError(C.getRawName(),
2273                               getFileNameForError(C, ChildIndex), Filename,
2274                               ArchitectureName)
2275              << "\n";
2276     } else {
2277       StringRef Name = NameOrErr.get();
2278       outs() << Name << "\n";
2279     }
2280   } else {
2281     outs() << unwrapOrError(C.getRawName(), getFileNameForError(C, ChildIndex),
2282                             Filename, ArchitectureName)
2283            << "\n";
2284   }
2285 }
2286 
2287 static void printArchiveHeaders(StringRef Filename, Archive *A, bool verbose,
2288                                 bool print_offset,
2289                                 StringRef ArchitectureName = StringRef()) {
2290   Error Err = Error::success();
2291   size_t I = 0;
2292   for (const auto &C : A->children(Err, false))
2293     printArchiveChild(Filename, C, I++, verbose, print_offset,
2294                       ArchitectureName);
2295 
2296   if (Err)
2297     reportError(std::move(Err), Filename, "", ArchitectureName);
2298 }
2299 
2300 static bool ValidateArchFlags() {
2301   // Check for -arch all and verifiy the -arch flags are valid.
2302   for (unsigned i = 0; i < ArchFlags.size(); ++i) {
2303     if (ArchFlags[i] == "all") {
2304       ArchAll = true;
2305     } else {
2306       if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
2307         WithColor::error(errs(), "llvm-objdump")
2308             << "unknown architecture named '" + ArchFlags[i] +
2309                    "'for the -arch option\n";
2310         return false;
2311       }
2312     }
2313   }
2314   return true;
2315 }
2316 
2317 // ParseInputMachO() parses the named Mach-O file in Filename and handles the
2318 // -arch flags selecting just those slices as specified by them and also parses
2319 // archive files.  Then for each individual Mach-O file ProcessMachO() is
2320 // called to process the file based on the command line options.
2321 void parseInputMachO(StringRef Filename) {
2322   if (!ValidateArchFlags())
2323     return;
2324 
2325   // Attempt to open the binary.
2326   Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
2327   if (!BinaryOrErr) {
2328     if (Error E = isNotObjectErrorInvalidFileType(BinaryOrErr.takeError()))
2329       reportError(std::move(E), Filename);
2330     else
2331       outs() << Filename << ": is not an object file\n";
2332     return;
2333   }
2334   Binary &Bin = *BinaryOrErr.get().getBinary();
2335 
2336   if (Archive *A = dyn_cast<Archive>(&Bin)) {
2337     outs() << "Archive : " << Filename << "\n";
2338     if (ArchiveHeaders)
2339       printArchiveHeaders(Filename, A, !NonVerbose, ArchiveMemberOffsets);
2340 
2341     Error Err = Error::success();
2342     unsigned I = -1;
2343     for (auto &C : A->children(Err)) {
2344       ++I;
2345       Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2346       if (!ChildOrErr) {
2347         if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2348           reportError(std::move(E), getFileNameForError(C, I), Filename);
2349         continue;
2350       }
2351       if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
2352         if (!checkMachOAndArchFlags(O, Filename))
2353           return;
2354         ProcessMachO(Filename, O, O->getFileName());
2355       }
2356     }
2357     if (Err)
2358       reportError(std::move(Err), Filename);
2359     return;
2360   }
2361   if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
2362     parseInputMachO(UB);
2363     return;
2364   }
2365   if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
2366     if (!checkMachOAndArchFlags(O, Filename))
2367       return;
2368     if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O))
2369       ProcessMachO(Filename, MachOOF);
2370     else
2371       WithColor::error(errs(), "llvm-objdump")
2372           << Filename << "': "
2373           << "object is not a Mach-O file type.\n";
2374     return;
2375   }
2376   llvm_unreachable("Input object can't be invalid at this point");
2377 }
2378 
2379 void parseInputMachO(MachOUniversalBinary *UB) {
2380   if (!ValidateArchFlags())
2381     return;
2382 
2383   auto Filename = UB->getFileName();
2384 
2385   if (UniversalHeaders)
2386     printMachOUniversalHeaders(UB, !NonVerbose);
2387 
2388   // If we have a list of architecture flags specified dump only those.
2389   if (!ArchAll && !ArchFlags.empty()) {
2390     // Look for a slice in the universal binary that matches each ArchFlag.
2391     bool ArchFound;
2392     for (unsigned i = 0; i < ArchFlags.size(); ++i) {
2393       ArchFound = false;
2394       for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2395                                                   E = UB->end_objects();
2396             I != E; ++I) {
2397         if (ArchFlags[i] == I->getArchFlagName()) {
2398           ArchFound = true;
2399           Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
2400               I->getAsObjectFile();
2401           std::string ArchitectureName = "";
2402           if (ArchFlags.size() > 1)
2403             ArchitectureName = I->getArchFlagName();
2404           if (ObjOrErr) {
2405             ObjectFile &O = *ObjOrErr.get();
2406             if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
2407               ProcessMachO(Filename, MachOOF, "", ArchitectureName);
2408           } else if (Error E = isNotObjectErrorInvalidFileType(
2409                          ObjOrErr.takeError())) {
2410             reportError(std::move(E), "", Filename, ArchitectureName);
2411             continue;
2412           } else if (Expected<std::unique_ptr<Archive>> AOrErr =
2413                          I->getAsArchive()) {
2414             std::unique_ptr<Archive> &A = *AOrErr;
2415             outs() << "Archive : " << Filename;
2416             if (!ArchitectureName.empty())
2417               outs() << " (architecture " << ArchitectureName << ")";
2418             outs() << "\n";
2419             if (ArchiveHeaders)
2420               printArchiveHeaders(Filename, A.get(), !NonVerbose,
2421                                   ArchiveMemberOffsets, ArchitectureName);
2422             Error Err = Error::success();
2423             unsigned I = -1;
2424             for (auto &C : A->children(Err)) {
2425               ++I;
2426               Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2427               if (!ChildOrErr) {
2428                 if (Error E =
2429                         isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2430                   reportError(std::move(E), getFileNameForError(C, I), Filename,
2431                               ArchitectureName);
2432                 continue;
2433               }
2434               if (MachOObjectFile *O =
2435                       dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
2436                 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
2437             }
2438             if (Err)
2439               reportError(std::move(Err), Filename);
2440           } else {
2441             consumeError(AOrErr.takeError());
2442             reportError(Filename,
2443                         "Mach-O universal file for architecture " +
2444                             StringRef(I->getArchFlagName()) +
2445                             " is not a Mach-O file or an archive file");
2446           }
2447         }
2448       }
2449       if (!ArchFound) {
2450         WithColor::error(errs(), "llvm-objdump")
2451             << "file: " + Filename + " does not contain "
2452             << "architecture: " + ArchFlags[i] + "\n";
2453         return;
2454       }
2455     }
2456     return;
2457   }
2458   // No architecture flags were specified so if this contains a slice that
2459   // matches the host architecture dump only that.
2460   if (!ArchAll) {
2461     for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2462                                                 E = UB->end_objects();
2463           I != E; ++I) {
2464       if (MachOObjectFile::getHostArch().getArchName() ==
2465           I->getArchFlagName()) {
2466         Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2467         std::string ArchiveName;
2468         ArchiveName.clear();
2469         if (ObjOrErr) {
2470           ObjectFile &O = *ObjOrErr.get();
2471           if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
2472             ProcessMachO(Filename, MachOOF);
2473         } else if (Error E =
2474                        isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) {
2475           reportError(std::move(E), Filename);
2476         } else if (Expected<std::unique_ptr<Archive>> AOrErr =
2477                        I->getAsArchive()) {
2478           std::unique_ptr<Archive> &A = *AOrErr;
2479           outs() << "Archive : " << Filename << "\n";
2480           if (ArchiveHeaders)
2481             printArchiveHeaders(Filename, A.get(), !NonVerbose,
2482                                 ArchiveMemberOffsets);
2483           Error Err = Error::success();
2484           unsigned I = -1;
2485           for (auto &C : A->children(Err)) {
2486             ++I;
2487             Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2488             if (!ChildOrErr) {
2489               if (Error E =
2490                       isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2491                 reportError(std::move(E), getFileNameForError(C, I), Filename);
2492               continue;
2493             }
2494             if (MachOObjectFile *O =
2495                     dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
2496               ProcessMachO(Filename, O, O->getFileName());
2497           }
2498           if (Err)
2499             reportError(std::move(Err), Filename);
2500         } else {
2501           consumeError(AOrErr.takeError());
2502           reportError(Filename, "Mach-O universal file for architecture " +
2503                                     StringRef(I->getArchFlagName()) +
2504                                     " is not a Mach-O file or an archive file");
2505         }
2506         return;
2507       }
2508     }
2509   }
2510   // Either all architectures have been specified or none have been specified
2511   // and this does not contain the host architecture so dump all the slices.
2512   bool moreThanOneArch = UB->getNumberOfObjects() > 1;
2513   for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2514                                               E = UB->end_objects();
2515         I != E; ++I) {
2516     Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2517     std::string ArchitectureName = "";
2518     if (moreThanOneArch)
2519       ArchitectureName = I->getArchFlagName();
2520     if (ObjOrErr) {
2521       ObjectFile &Obj = *ObjOrErr.get();
2522       if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
2523         ProcessMachO(Filename, MachOOF, "", ArchitectureName);
2524     } else if (Error E =
2525                    isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) {
2526       reportError(std::move(E), Filename, "", ArchitectureName);
2527     } else if (Expected<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
2528       std::unique_ptr<Archive> &A = *AOrErr;
2529       outs() << "Archive : " << Filename;
2530       if (!ArchitectureName.empty())
2531         outs() << " (architecture " << ArchitectureName << ")";
2532       outs() << "\n";
2533       if (ArchiveHeaders)
2534         printArchiveHeaders(Filename, A.get(), !NonVerbose,
2535                             ArchiveMemberOffsets, ArchitectureName);
2536       Error Err = Error::success();
2537       unsigned I = -1;
2538       for (auto &C : A->children(Err)) {
2539         ++I;
2540         Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2541         if (!ChildOrErr) {
2542           if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2543             reportError(std::move(E), getFileNameForError(C, I), Filename,
2544                         ArchitectureName);
2545           continue;
2546         }
2547         if (MachOObjectFile *O =
2548                 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
2549           if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
2550             ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
2551                           ArchitectureName);
2552         }
2553       }
2554       if (Err)
2555         reportError(std::move(Err), Filename);
2556     } else {
2557       consumeError(AOrErr.takeError());
2558       reportError(Filename, "Mach-O universal file for architecture " +
2559                                 StringRef(I->getArchFlagName()) +
2560                                 " is not a Mach-O file or an archive file");
2561     }
2562   }
2563 }
2564 
2565 // The block of info used by the Symbolizer call backs.
2566 struct DisassembleInfo {
2567   DisassembleInfo(MachOObjectFile *O, SymbolAddressMap *AddrMap,
2568                   std::vector<SectionRef> *Sections, bool verbose)
2569     : verbose(verbose), O(O), AddrMap(AddrMap), Sections(Sections) {}
2570   bool verbose;
2571   MachOObjectFile *O;
2572   SectionRef S;
2573   SymbolAddressMap *AddrMap;
2574   std::vector<SectionRef> *Sections;
2575   const char *class_name = nullptr;
2576   const char *selector_name = nullptr;
2577   std::unique_ptr<char[]> method = nullptr;
2578   char *demangled_name = nullptr;
2579   uint64_t adrp_addr = 0;
2580   uint32_t adrp_inst = 0;
2581   std::unique_ptr<SymbolAddressMap> bindtable;
2582   uint32_t depth = 0;
2583 };
2584 
2585 // SymbolizerGetOpInfo() is the operand information call back function.
2586 // This is called to get the symbolic information for operand(s) of an
2587 // instruction when it is being done.  This routine does this from
2588 // the relocation information, symbol table, etc. That block of information
2589 // is a pointer to the struct DisassembleInfo that was passed when the
2590 // disassembler context was created and passed to back to here when
2591 // called back by the disassembler for instruction operands that could have
2592 // relocation information. The address of the instruction containing operand is
2593 // at the Pc parameter.  The immediate value the operand has is passed in
2594 // op_info->Value and is at Offset past the start of the instruction and has a
2595 // byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
2596 // LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
2597 // names and addends of the symbolic expression to add for the operand.  The
2598 // value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
2599 // information is returned then this function returns 1 else it returns 0.
2600 static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
2601                                uint64_t Size, int TagType, void *TagBuf) {
2602   struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
2603   struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
2604   uint64_t value = op_info->Value;
2605 
2606   // Make sure all fields returned are zero if we don't set them.
2607   memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
2608   op_info->Value = value;
2609 
2610   // If the TagType is not the value 1 which it code knows about or if no
2611   // verbose symbolic information is wanted then just return 0, indicating no
2612   // information is being returned.
2613   if (TagType != 1 || !info->verbose)
2614     return 0;
2615 
2616   unsigned int Arch = info->O->getArch();
2617   if (Arch == Triple::x86) {
2618     if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
2619       return 0;
2620     if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2621       // TODO:
2622       // Search the external relocation entries of a fully linked image
2623       // (if any) for an entry that matches this segment offset.
2624       // uint32_t seg_offset = (Pc + Offset);
2625       return 0;
2626     }
2627     // In MH_OBJECT filetypes search the section's relocation entries (if any)
2628     // for an entry for this section offset.
2629     uint32_t sect_addr = info->S.getAddress();
2630     uint32_t sect_offset = (Pc + Offset) - sect_addr;
2631     bool reloc_found = false;
2632     DataRefImpl Rel;
2633     MachO::any_relocation_info RE;
2634     bool isExtern = false;
2635     SymbolRef Symbol;
2636     bool r_scattered = false;
2637     uint32_t r_value, pair_r_value, r_type;
2638     for (const RelocationRef &Reloc : info->S.relocations()) {
2639       uint64_t RelocOffset = Reloc.getOffset();
2640       if (RelocOffset == sect_offset) {
2641         Rel = Reloc.getRawDataRefImpl();
2642         RE = info->O->getRelocation(Rel);
2643         r_type = info->O->getAnyRelocationType(RE);
2644         r_scattered = info->O->isRelocationScattered(RE);
2645         if (r_scattered) {
2646           r_value = info->O->getScatteredRelocationValue(RE);
2647           if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2648               r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
2649             DataRefImpl RelNext = Rel;
2650             info->O->moveRelocationNext(RelNext);
2651             MachO::any_relocation_info RENext;
2652             RENext = info->O->getRelocation(RelNext);
2653             if (info->O->isRelocationScattered(RENext))
2654               pair_r_value = info->O->getScatteredRelocationValue(RENext);
2655             else
2656               return 0;
2657           }
2658         } else {
2659           isExtern = info->O->getPlainRelocationExternal(RE);
2660           if (isExtern) {
2661             symbol_iterator RelocSym = Reloc.getSymbol();
2662             Symbol = *RelocSym;
2663           }
2664         }
2665         reloc_found = true;
2666         break;
2667       }
2668     }
2669     if (reloc_found && isExtern) {
2670       op_info->AddSymbol.Present = 1;
2671       op_info->AddSymbol.Name =
2672           unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
2673       // For i386 extern relocation entries the value in the instruction is
2674       // the offset from the symbol, and value is already set in op_info->Value.
2675       return 1;
2676     }
2677     if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2678                         r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
2679       const char *add = GuessSymbolName(r_value, info->AddrMap);
2680       const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
2681       uint32_t offset = value - (r_value - pair_r_value);
2682       op_info->AddSymbol.Present = 1;
2683       if (add != nullptr)
2684         op_info->AddSymbol.Name = add;
2685       else
2686         op_info->AddSymbol.Value = r_value;
2687       op_info->SubtractSymbol.Present = 1;
2688       if (sub != nullptr)
2689         op_info->SubtractSymbol.Name = sub;
2690       else
2691         op_info->SubtractSymbol.Value = pair_r_value;
2692       op_info->Value = offset;
2693       return 1;
2694     }
2695     return 0;
2696   }
2697   if (Arch == Triple::x86_64) {
2698     if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
2699       return 0;
2700     // For non MH_OBJECT types, like MH_KEXT_BUNDLE, Search the external
2701     // relocation entries of a linked image (if any) for an entry that matches
2702     // this segment offset.
2703     if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2704       uint64_t seg_offset = Pc + Offset;
2705       bool reloc_found = false;
2706       DataRefImpl Rel;
2707       MachO::any_relocation_info RE;
2708       bool isExtern = false;
2709       SymbolRef Symbol;
2710       for (const RelocationRef &Reloc : info->O->external_relocations()) {
2711         uint64_t RelocOffset = Reloc.getOffset();
2712         if (RelocOffset == seg_offset) {
2713           Rel = Reloc.getRawDataRefImpl();
2714           RE = info->O->getRelocation(Rel);
2715           // external relocation entries should always be external.
2716           isExtern = info->O->getPlainRelocationExternal(RE);
2717           if (isExtern) {
2718             symbol_iterator RelocSym = Reloc.getSymbol();
2719             Symbol = *RelocSym;
2720           }
2721           reloc_found = true;
2722           break;
2723         }
2724       }
2725       if (reloc_found && isExtern) {
2726         // The Value passed in will be adjusted by the Pc if the instruction
2727         // adds the Pc.  But for x86_64 external relocation entries the Value
2728         // is the offset from the external symbol.
2729         if (info->O->getAnyRelocationPCRel(RE))
2730           op_info->Value -= Pc + Offset + Size;
2731         const char *name =
2732             unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
2733         op_info->AddSymbol.Present = 1;
2734         op_info->AddSymbol.Name = name;
2735         return 1;
2736       }
2737       return 0;
2738     }
2739     // In MH_OBJECT filetypes search the section's relocation entries (if any)
2740     // for an entry for this section offset.
2741     uint64_t sect_addr = info->S.getAddress();
2742     uint64_t sect_offset = (Pc + Offset) - sect_addr;
2743     bool reloc_found = false;
2744     DataRefImpl Rel;
2745     MachO::any_relocation_info RE;
2746     bool isExtern = false;
2747     SymbolRef Symbol;
2748     for (const RelocationRef &Reloc : info->S.relocations()) {
2749       uint64_t RelocOffset = Reloc.getOffset();
2750       if (RelocOffset == sect_offset) {
2751         Rel = Reloc.getRawDataRefImpl();
2752         RE = info->O->getRelocation(Rel);
2753         // NOTE: Scattered relocations don't exist on x86_64.
2754         isExtern = info->O->getPlainRelocationExternal(RE);
2755         if (isExtern) {
2756           symbol_iterator RelocSym = Reloc.getSymbol();
2757           Symbol = *RelocSym;
2758         }
2759         reloc_found = true;
2760         break;
2761       }
2762     }
2763     if (reloc_found && isExtern) {
2764       // The Value passed in will be adjusted by the Pc if the instruction
2765       // adds the Pc.  But for x86_64 external relocation entries the Value
2766       // is the offset from the external symbol.
2767       if (info->O->getAnyRelocationPCRel(RE))
2768         op_info->Value -= Pc + Offset + Size;
2769       const char *name =
2770           unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
2771       unsigned Type = info->O->getAnyRelocationType(RE);
2772       if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
2773         DataRefImpl RelNext = Rel;
2774         info->O->moveRelocationNext(RelNext);
2775         MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2776         unsigned TypeNext = info->O->getAnyRelocationType(RENext);
2777         bool isExternNext = info->O->getPlainRelocationExternal(RENext);
2778         unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
2779         if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
2780           op_info->SubtractSymbol.Present = 1;
2781           op_info->SubtractSymbol.Name = name;
2782           symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
2783           Symbol = *RelocSymNext;
2784           name = unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
2785         }
2786       }
2787       // TODO: add the VariantKinds to op_info->VariantKind for relocation types
2788       // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
2789       op_info->AddSymbol.Present = 1;
2790       op_info->AddSymbol.Name = name;
2791       return 1;
2792     }
2793     return 0;
2794   }
2795   if (Arch == Triple::arm) {
2796     if (Offset != 0 || (Size != 4 && Size != 2))
2797       return 0;
2798     if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2799       // TODO:
2800       // Search the external relocation entries of a fully linked image
2801       // (if any) for an entry that matches this segment offset.
2802       // uint32_t seg_offset = (Pc + Offset);
2803       return 0;
2804     }
2805     // In MH_OBJECT filetypes search the section's relocation entries (if any)
2806     // for an entry for this section offset.
2807     uint32_t sect_addr = info->S.getAddress();
2808     uint32_t sect_offset = (Pc + Offset) - sect_addr;
2809     DataRefImpl Rel;
2810     MachO::any_relocation_info RE;
2811     bool isExtern = false;
2812     SymbolRef Symbol;
2813     bool r_scattered = false;
2814     uint32_t r_value, pair_r_value, r_type, r_length, other_half;
2815     auto Reloc =
2816         find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2817           uint64_t RelocOffset = Reloc.getOffset();
2818           return RelocOffset == sect_offset;
2819         });
2820 
2821     if (Reloc == info->S.relocations().end())
2822       return 0;
2823 
2824     Rel = Reloc->getRawDataRefImpl();
2825     RE = info->O->getRelocation(Rel);
2826     r_length = info->O->getAnyRelocationLength(RE);
2827     r_scattered = info->O->isRelocationScattered(RE);
2828     if (r_scattered) {
2829       r_value = info->O->getScatteredRelocationValue(RE);
2830       r_type = info->O->getScatteredRelocationType(RE);
2831     } else {
2832       r_type = info->O->getAnyRelocationType(RE);
2833       isExtern = info->O->getPlainRelocationExternal(RE);
2834       if (isExtern) {
2835         symbol_iterator RelocSym = Reloc->getSymbol();
2836         Symbol = *RelocSym;
2837       }
2838     }
2839     if (r_type == MachO::ARM_RELOC_HALF ||
2840         r_type == MachO::ARM_RELOC_SECTDIFF ||
2841         r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
2842         r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2843       DataRefImpl RelNext = Rel;
2844       info->O->moveRelocationNext(RelNext);
2845       MachO::any_relocation_info RENext;
2846       RENext = info->O->getRelocation(RelNext);
2847       other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
2848       if (info->O->isRelocationScattered(RENext))
2849         pair_r_value = info->O->getScatteredRelocationValue(RENext);
2850     }
2851 
2852     if (isExtern) {
2853       const char *name =
2854           unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
2855       op_info->AddSymbol.Present = 1;
2856       op_info->AddSymbol.Name = name;
2857       switch (r_type) {
2858       case MachO::ARM_RELOC_HALF:
2859         if ((r_length & 0x1) == 1) {
2860           op_info->Value = value << 16 | other_half;
2861           op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2862         } else {
2863           op_info->Value = other_half << 16 | value;
2864           op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
2865         }
2866         break;
2867       default:
2868         break;
2869       }
2870       return 1;
2871     }
2872     // If we have a branch that is not an external relocation entry then
2873     // return 0 so the code in tryAddingSymbolicOperand() can use the
2874     // SymbolLookUp call back with the branch target address to look up the
2875     // symbol and possibility add an annotation for a symbol stub.
2876     if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
2877                           r_type == MachO::ARM_THUMB_RELOC_BR22))
2878       return 0;
2879 
2880     uint32_t offset = 0;
2881     if (r_type == MachO::ARM_RELOC_HALF ||
2882         r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2883       if ((r_length & 0x1) == 1)
2884         value = value << 16 | other_half;
2885       else
2886         value = other_half << 16 | value;
2887     }
2888     if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
2889                         r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
2890       offset = value - r_value;
2891       value = r_value;
2892     }
2893 
2894     if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2895       if ((r_length & 0x1) == 1)
2896         op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2897       else
2898         op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
2899       const char *add = GuessSymbolName(r_value, info->AddrMap);
2900       const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
2901       int32_t offset = value - (r_value - pair_r_value);
2902       op_info->AddSymbol.Present = 1;
2903       if (add != nullptr)
2904         op_info->AddSymbol.Name = add;
2905       else
2906         op_info->AddSymbol.Value = r_value;
2907       op_info->SubtractSymbol.Present = 1;
2908       if (sub != nullptr)
2909         op_info->SubtractSymbol.Name = sub;
2910       else
2911         op_info->SubtractSymbol.Value = pair_r_value;
2912       op_info->Value = offset;
2913       return 1;
2914     }
2915 
2916     op_info->AddSymbol.Present = 1;
2917     op_info->Value = offset;
2918     if (r_type == MachO::ARM_RELOC_HALF) {
2919       if ((r_length & 0x1) == 1)
2920         op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2921       else
2922         op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
2923     }
2924     const char *add = GuessSymbolName(value, info->AddrMap);
2925     if (add != nullptr) {
2926       op_info->AddSymbol.Name = add;
2927       return 1;
2928     }
2929     op_info->AddSymbol.Value = value;
2930     return 1;
2931   }
2932   if (Arch == Triple::aarch64) {
2933     if (Offset != 0 || Size != 4)
2934       return 0;
2935     if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2936       // TODO:
2937       // Search the external relocation entries of a fully linked image
2938       // (if any) for an entry that matches this segment offset.
2939       // uint64_t seg_offset = (Pc + Offset);
2940       return 0;
2941     }
2942     // In MH_OBJECT filetypes search the section's relocation entries (if any)
2943     // for an entry for this section offset.
2944     uint64_t sect_addr = info->S.getAddress();
2945     uint64_t sect_offset = (Pc + Offset) - sect_addr;
2946     auto Reloc =
2947         find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2948           uint64_t RelocOffset = Reloc.getOffset();
2949           return RelocOffset == sect_offset;
2950         });
2951 
2952     if (Reloc == info->S.relocations().end())
2953       return 0;
2954 
2955     DataRefImpl Rel = Reloc->getRawDataRefImpl();
2956     MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2957     uint32_t r_type = info->O->getAnyRelocationType(RE);
2958     if (r_type == MachO::ARM64_RELOC_ADDEND) {
2959       DataRefImpl RelNext = Rel;
2960       info->O->moveRelocationNext(RelNext);
2961       MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2962       if (value == 0) {
2963         value = info->O->getPlainRelocationSymbolNum(RENext);
2964         op_info->Value = value;
2965       }
2966     }
2967     // NOTE: Scattered relocations don't exist on arm64.
2968     if (!info->O->getPlainRelocationExternal(RE))
2969       return 0;
2970     const char *name =
2971         unwrapOrError(Reloc->getSymbol()->getName(), info->O->getFileName())
2972             .data();
2973     op_info->AddSymbol.Present = 1;
2974     op_info->AddSymbol.Name = name;
2975 
2976     switch (r_type) {
2977     case MachO::ARM64_RELOC_PAGE21:
2978       /* @page */
2979       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2980       break;
2981     case MachO::ARM64_RELOC_PAGEOFF12:
2982       /* @pageoff */
2983       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2984       break;
2985     case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2986       /* @gotpage */
2987       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2988       break;
2989     case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2990       /* @gotpageoff */
2991       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2992       break;
2993     case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2994       /* @tvlppage is not implemented in llvm-mc */
2995       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2996       break;
2997     case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2998       /* @tvlppageoff is not implemented in llvm-mc */
2999       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
3000       break;
3001     default:
3002     case MachO::ARM64_RELOC_BRANCH26:
3003       op_info->VariantKind = LLVMDisassembler_VariantKind_None;
3004       break;
3005     }
3006     return 1;
3007   }
3008   return 0;
3009 }
3010 
3011 // GuessCstringPointer is passed the address of what might be a pointer to a
3012 // literal string in a cstring section.  If that address is in a cstring section
3013 // it returns a pointer to that string.  Else it returns nullptr.
3014 static const char *GuessCstringPointer(uint64_t ReferenceValue,
3015                                        struct DisassembleInfo *info) {
3016   for (const auto &Load : info->O->load_commands()) {
3017     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
3018       MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
3019       for (unsigned J = 0; J < Seg.nsects; ++J) {
3020         MachO::section_64 Sec = info->O->getSection64(Load, J);
3021         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3022         if (section_type == MachO::S_CSTRING_LITERALS &&
3023             ReferenceValue >= Sec.addr &&
3024             ReferenceValue < Sec.addr + Sec.size) {
3025           uint64_t sect_offset = ReferenceValue - Sec.addr;
3026           uint64_t object_offset = Sec.offset + sect_offset;
3027           StringRef MachOContents = info->O->getData();
3028           uint64_t object_size = MachOContents.size();
3029           const char *object_addr = (const char *)MachOContents.data();
3030           if (object_offset < object_size) {
3031             const char *name = object_addr + object_offset;
3032             return name;
3033           } else {
3034             return nullptr;
3035           }
3036         }
3037       }
3038     } else if (Load.C.cmd == MachO::LC_SEGMENT) {
3039       MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
3040       for (unsigned J = 0; J < Seg.nsects; ++J) {
3041         MachO::section Sec = info->O->getSection(Load, J);
3042         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3043         if (section_type == MachO::S_CSTRING_LITERALS &&
3044             ReferenceValue >= Sec.addr &&
3045             ReferenceValue < Sec.addr + Sec.size) {
3046           uint64_t sect_offset = ReferenceValue - Sec.addr;
3047           uint64_t object_offset = Sec.offset + sect_offset;
3048           StringRef MachOContents = info->O->getData();
3049           uint64_t object_size = MachOContents.size();
3050           const char *object_addr = (const char *)MachOContents.data();
3051           if (object_offset < object_size) {
3052             const char *name = object_addr + object_offset;
3053             return name;
3054           } else {
3055             return nullptr;
3056           }
3057         }
3058       }
3059     }
3060   }
3061   return nullptr;
3062 }
3063 
3064 // GuessIndirectSymbol returns the name of the indirect symbol for the
3065 // ReferenceValue passed in or nullptr.  This is used when ReferenceValue maybe
3066 // an address of a symbol stub or a lazy or non-lazy pointer to associate the
3067 // symbol name being referenced by the stub or pointer.
3068 static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
3069                                        struct DisassembleInfo *info) {
3070   MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
3071   MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
3072   for (const auto &Load : info->O->load_commands()) {
3073     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
3074       MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
3075       for (unsigned J = 0; J < Seg.nsects; ++J) {
3076         MachO::section_64 Sec = info->O->getSection64(Load, J);
3077         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3078         if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
3079              section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
3080              section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
3081              section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
3082              section_type == MachO::S_SYMBOL_STUBS) &&
3083             ReferenceValue >= Sec.addr &&
3084             ReferenceValue < Sec.addr + Sec.size) {
3085           uint32_t stride;
3086           if (section_type == MachO::S_SYMBOL_STUBS)
3087             stride = Sec.reserved2;
3088           else
3089             stride = 8;
3090           if (stride == 0)
3091             return nullptr;
3092           uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
3093           if (index < Dysymtab.nindirectsyms) {
3094             uint32_t indirect_symbol =
3095                 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
3096             if (indirect_symbol < Symtab.nsyms) {
3097               symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
3098               return unwrapOrError(Sym->getName(), info->O->getFileName())
3099                   .data();
3100             }
3101           }
3102         }
3103       }
3104     } else if (Load.C.cmd == MachO::LC_SEGMENT) {
3105       MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
3106       for (unsigned J = 0; J < Seg.nsects; ++J) {
3107         MachO::section Sec = info->O->getSection(Load, J);
3108         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3109         if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
3110              section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
3111              section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
3112              section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
3113              section_type == MachO::S_SYMBOL_STUBS) &&
3114             ReferenceValue >= Sec.addr &&
3115             ReferenceValue < Sec.addr + Sec.size) {
3116           uint32_t stride;
3117           if (section_type == MachO::S_SYMBOL_STUBS)
3118             stride = Sec.reserved2;
3119           else
3120             stride = 4;
3121           if (stride == 0)
3122             return nullptr;
3123           uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
3124           if (index < Dysymtab.nindirectsyms) {
3125             uint32_t indirect_symbol =
3126                 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
3127             if (indirect_symbol < Symtab.nsyms) {
3128               symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
3129               return unwrapOrError(Sym->getName(), info->O->getFileName())
3130                   .data();
3131             }
3132           }
3133         }
3134       }
3135     }
3136   }
3137   return nullptr;
3138 }
3139 
3140 // method_reference() is called passing it the ReferenceName that might be
3141 // a reference it to an Objective-C method call.  If so then it allocates and
3142 // assembles a method call string with the values last seen and saved in
3143 // the DisassembleInfo's class_name and selector_name fields.  This is saved
3144 // into the method field of the info and any previous string is free'ed.
3145 // Then the class_name field in the info is set to nullptr.  The method call
3146 // string is set into ReferenceName and ReferenceType is set to
3147 // LLVMDisassembler_ReferenceType_Out_Objc_Message.  If this not a method call
3148 // then both ReferenceType and ReferenceName are left unchanged.
3149 static void method_reference(struct DisassembleInfo *info,
3150                              uint64_t *ReferenceType,
3151                              const char **ReferenceName) {
3152   unsigned int Arch = info->O->getArch();
3153   if (*ReferenceName != nullptr) {
3154     if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
3155       if (info->selector_name != nullptr) {
3156         if (info->class_name != nullptr) {
3157           info->method = std::make_unique<char[]>(
3158               5 + strlen(info->class_name) + strlen(info->selector_name));
3159           char *method = info->method.get();
3160           if (method != nullptr) {
3161             strcpy(method, "+[");
3162             strcat(method, info->class_name);
3163             strcat(method, " ");
3164             strcat(method, info->selector_name);
3165             strcat(method, "]");
3166             *ReferenceName = method;
3167             *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3168           }
3169         } else {
3170           info->method =
3171               std::make_unique<char[]>(9 + strlen(info->selector_name));
3172           char *method = info->method.get();
3173           if (method != nullptr) {
3174             if (Arch == Triple::x86_64)
3175               strcpy(method, "-[%rdi ");
3176             else if (Arch == Triple::aarch64)
3177               strcpy(method, "-[x0 ");
3178             else
3179               strcpy(method, "-[r? ");
3180             strcat(method, info->selector_name);
3181             strcat(method, "]");
3182             *ReferenceName = method;
3183             *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3184           }
3185         }
3186         info->class_name = nullptr;
3187       }
3188     } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
3189       if (info->selector_name != nullptr) {
3190         info->method =
3191             std::make_unique<char[]>(17 + strlen(info->selector_name));
3192         char *method = info->method.get();
3193         if (method != nullptr) {
3194           if (Arch == Triple::x86_64)
3195             strcpy(method, "-[[%rdi super] ");
3196           else if (Arch == Triple::aarch64)
3197             strcpy(method, "-[[x0 super] ");
3198           else
3199             strcpy(method, "-[[r? super] ");
3200           strcat(method, info->selector_name);
3201           strcat(method, "]");
3202           *ReferenceName = method;
3203           *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3204         }
3205         info->class_name = nullptr;
3206       }
3207     }
3208   }
3209 }
3210 
3211 // GuessPointerPointer() is passed the address of what might be a pointer to
3212 // a reference to an Objective-C class, selector, message ref or cfstring.
3213 // If so the value of the pointer is returned and one of the booleans are set
3214 // to true.  If not zero is returned and all the booleans are set to false.
3215 static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
3216                                     struct DisassembleInfo *info,
3217                                     bool &classref, bool &selref, bool &msgref,
3218                                     bool &cfstring) {
3219   classref = false;
3220   selref = false;
3221   msgref = false;
3222   cfstring = false;
3223   for (const auto &Load : info->O->load_commands()) {
3224     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
3225       MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
3226       for (unsigned J = 0; J < Seg.nsects; ++J) {
3227         MachO::section_64 Sec = info->O->getSection64(Load, J);
3228         if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
3229              strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
3230              strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
3231              strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
3232              strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
3233             ReferenceValue >= Sec.addr &&
3234             ReferenceValue < Sec.addr + Sec.size) {
3235           uint64_t sect_offset = ReferenceValue - Sec.addr;
3236           uint64_t object_offset = Sec.offset + sect_offset;
3237           StringRef MachOContents = info->O->getData();
3238           uint64_t object_size = MachOContents.size();
3239           const char *object_addr = (const char *)MachOContents.data();
3240           if (object_offset < object_size) {
3241             uint64_t pointer_value;
3242             memcpy(&pointer_value, object_addr + object_offset,
3243                    sizeof(uint64_t));
3244             if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3245               sys::swapByteOrder(pointer_value);
3246             if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
3247               selref = true;
3248             else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
3249                      strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
3250               classref = true;
3251             else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
3252                      ReferenceValue + 8 < Sec.addr + Sec.size) {
3253               msgref = true;
3254               memcpy(&pointer_value, object_addr + object_offset + 8,
3255                      sizeof(uint64_t));
3256               if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3257                 sys::swapByteOrder(pointer_value);
3258             } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
3259               cfstring = true;
3260             return pointer_value;
3261           } else {
3262             return 0;
3263           }
3264         }
3265       }
3266     }
3267     // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
3268   }
3269   return 0;
3270 }
3271 
3272 // get_pointer_64 returns a pointer to the bytes in the object file at the
3273 // Address from a section in the Mach-O file.  And indirectly returns the
3274 // offset into the section, number of bytes left in the section past the offset
3275 // and which section is was being referenced.  If the Address is not in a
3276 // section nullptr is returned.
3277 static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
3278                                   uint32_t &left, SectionRef &S,
3279                                   DisassembleInfo *info,
3280                                   bool objc_only = false) {
3281   offset = 0;
3282   left = 0;
3283   S = SectionRef();
3284   for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
3285     uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
3286     uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
3287     if (SectSize == 0)
3288       continue;
3289     if (objc_only) {
3290       StringRef SectName;
3291       Expected<StringRef> SecNameOrErr =
3292           ((*(info->Sections))[SectIdx]).getName();
3293       if (SecNameOrErr)
3294         SectName = *SecNameOrErr;
3295       else
3296         consumeError(SecNameOrErr.takeError());
3297 
3298       DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
3299       StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
3300       if (SegName != "__OBJC" && SectName != "__cstring")
3301         continue;
3302     }
3303     if (Address >= SectAddress && Address < SectAddress + SectSize) {
3304       S = (*(info->Sections))[SectIdx];
3305       offset = Address - SectAddress;
3306       left = SectSize - offset;
3307       StringRef SectContents = unwrapOrError(
3308           ((*(info->Sections))[SectIdx]).getContents(), info->O->getFileName());
3309       return SectContents.data() + offset;
3310     }
3311   }
3312   return nullptr;
3313 }
3314 
3315 static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
3316                                   uint32_t &left, SectionRef &S,
3317                                   DisassembleInfo *info,
3318                                   bool objc_only = false) {
3319   return get_pointer_64(Address, offset, left, S, info, objc_only);
3320 }
3321 
3322 // get_symbol_64() returns the name of a symbol (or nullptr) and the address of
3323 // the symbol indirectly through n_value. Based on the relocation information
3324 // for the specified section offset in the specified section reference.
3325 // If no relocation information is found and a non-zero ReferenceValue for the
3326 // symbol is passed, look up that address in the info's AddrMap.
3327 static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
3328                                  DisassembleInfo *info, uint64_t &n_value,
3329                                  uint64_t ReferenceValue = 0) {
3330   n_value = 0;
3331   if (!info->verbose)
3332     return nullptr;
3333 
3334   // See if there is an external relocation entry at the sect_offset.
3335   bool reloc_found = false;
3336   DataRefImpl Rel;
3337   MachO::any_relocation_info RE;
3338   bool isExtern = false;
3339   SymbolRef Symbol;
3340   for (const RelocationRef &Reloc : S.relocations()) {
3341     uint64_t RelocOffset = Reloc.getOffset();
3342     if (RelocOffset == sect_offset) {
3343       Rel = Reloc.getRawDataRefImpl();
3344       RE = info->O->getRelocation(Rel);
3345       if (info->O->isRelocationScattered(RE))
3346         continue;
3347       isExtern = info->O->getPlainRelocationExternal(RE);
3348       if (isExtern) {
3349         symbol_iterator RelocSym = Reloc.getSymbol();
3350         Symbol = *RelocSym;
3351       }
3352       reloc_found = true;
3353       break;
3354     }
3355   }
3356   // If there is an external relocation entry for a symbol in this section
3357   // at this section_offset then use that symbol's value for the n_value
3358   // and return its name.
3359   const char *SymbolName = nullptr;
3360   if (reloc_found && isExtern) {
3361     n_value = Symbol.getValue();
3362     StringRef Name = unwrapOrError(Symbol.getName(), info->O->getFileName());
3363     if (!Name.empty()) {
3364       SymbolName = Name.data();
3365       return SymbolName;
3366     }
3367   }
3368 
3369   // TODO: For fully linked images, look through the external relocation
3370   // entries off the dynamic symtab command. For these the r_offset is from the
3371   // start of the first writeable segment in the Mach-O file.  So the offset
3372   // to this section from that segment is passed to this routine by the caller,
3373   // as the database_offset. Which is the difference of the section's starting
3374   // address and the first writable segment.
3375   //
3376   // NOTE: need add passing the database_offset to this routine.
3377 
3378   // We did not find an external relocation entry so look up the ReferenceValue
3379   // as an address of a symbol and if found return that symbol's name.
3380   SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
3381 
3382   return SymbolName;
3383 }
3384 
3385 static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
3386                                  DisassembleInfo *info,
3387                                  uint32_t ReferenceValue) {
3388   uint64_t n_value64;
3389   return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
3390 }
3391 
3392 // These are structs in the Objective-C meta data and read to produce the
3393 // comments for disassembly.  While these are part of the ABI they are no
3394 // public defintions.  So the are here not in include/llvm/BinaryFormat/MachO.h
3395 // .
3396 
3397 // The cfstring object in a 64-bit Mach-O file.
3398 struct cfstring64_t {
3399   uint64_t isa;        // class64_t * (64-bit pointer)
3400   uint64_t flags;      // flag bits
3401   uint64_t characters; // char * (64-bit pointer)
3402   uint64_t length;     // number of non-NULL characters in above
3403 };
3404 
3405 // The class object in a 64-bit Mach-O file.
3406 struct class64_t {
3407   uint64_t isa;        // class64_t * (64-bit pointer)
3408   uint64_t superclass; // class64_t * (64-bit pointer)
3409   uint64_t cache;      // Cache (64-bit pointer)
3410   uint64_t vtable;     // IMP * (64-bit pointer)
3411   uint64_t data;       // class_ro64_t * (64-bit pointer)
3412 };
3413 
3414 struct class32_t {
3415   uint32_t isa;        /* class32_t * (32-bit pointer) */
3416   uint32_t superclass; /* class32_t * (32-bit pointer) */
3417   uint32_t cache;      /* Cache (32-bit pointer) */
3418   uint32_t vtable;     /* IMP * (32-bit pointer) */
3419   uint32_t data;       /* class_ro32_t * (32-bit pointer) */
3420 };
3421 
3422 struct class_ro64_t {
3423   uint32_t flags;
3424   uint32_t instanceStart;
3425   uint32_t instanceSize;
3426   uint32_t reserved;
3427   uint64_t ivarLayout;     // const uint8_t * (64-bit pointer)
3428   uint64_t name;           // const char * (64-bit pointer)
3429   uint64_t baseMethods;    // const method_list_t * (64-bit pointer)
3430   uint64_t baseProtocols;  // const protocol_list_t * (64-bit pointer)
3431   uint64_t ivars;          // const ivar_list_t * (64-bit pointer)
3432   uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
3433   uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
3434 };
3435 
3436 struct class_ro32_t {
3437   uint32_t flags;
3438   uint32_t instanceStart;
3439   uint32_t instanceSize;
3440   uint32_t ivarLayout;     /* const uint8_t * (32-bit pointer) */
3441   uint32_t name;           /* const char * (32-bit pointer) */
3442   uint32_t baseMethods;    /* const method_list_t * (32-bit pointer) */
3443   uint32_t baseProtocols;  /* const protocol_list_t * (32-bit pointer) */
3444   uint32_t ivars;          /* const ivar_list_t * (32-bit pointer) */
3445   uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
3446   uint32_t baseProperties; /* const struct objc_property_list *
3447                                                    (32-bit pointer) */
3448 };
3449 
3450 /* Values for class_ro{64,32}_t->flags */
3451 #define RO_META (1 << 0)
3452 #define RO_ROOT (1 << 1)
3453 #define RO_HAS_CXX_STRUCTORS (1 << 2)
3454 
3455 struct method_list64_t {
3456   uint32_t entsize;
3457   uint32_t count;
3458   /* struct method64_t first;  These structures follow inline */
3459 };
3460 
3461 struct method_list32_t {
3462   uint32_t entsize;
3463   uint32_t count;
3464   /* struct method32_t first;  These structures follow inline */
3465 };
3466 
3467 struct method64_t {
3468   uint64_t name;  /* SEL (64-bit pointer) */
3469   uint64_t types; /* const char * (64-bit pointer) */
3470   uint64_t imp;   /* IMP (64-bit pointer) */
3471 };
3472 
3473 struct method32_t {
3474   uint32_t name;  /* SEL (32-bit pointer) */
3475   uint32_t types; /* const char * (32-bit pointer) */
3476   uint32_t imp;   /* IMP (32-bit pointer) */
3477 };
3478 
3479 struct protocol_list64_t {
3480   uint64_t count; /* uintptr_t (a 64-bit value) */
3481   /* struct protocol64_t * list[0];  These pointers follow inline */
3482 };
3483 
3484 struct protocol_list32_t {
3485   uint32_t count; /* uintptr_t (a 32-bit value) */
3486   /* struct protocol32_t * list[0];  These pointers follow inline */
3487 };
3488 
3489 struct protocol64_t {
3490   uint64_t isa;                     /* id * (64-bit pointer) */
3491   uint64_t name;                    /* const char * (64-bit pointer) */
3492   uint64_t protocols;               /* struct protocol_list64_t *
3493                                                     (64-bit pointer) */
3494   uint64_t instanceMethods;         /* method_list_t * (64-bit pointer) */
3495   uint64_t classMethods;            /* method_list_t * (64-bit pointer) */
3496   uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
3497   uint64_t optionalClassMethods;    /* method_list_t * (64-bit pointer) */
3498   uint64_t instanceProperties;      /* struct objc_property_list *
3499                                                        (64-bit pointer) */
3500 };
3501 
3502 struct protocol32_t {
3503   uint32_t isa;                     /* id * (32-bit pointer) */
3504   uint32_t name;                    /* const char * (32-bit pointer) */
3505   uint32_t protocols;               /* struct protocol_list_t *
3506                                                     (32-bit pointer) */
3507   uint32_t instanceMethods;         /* method_list_t * (32-bit pointer) */
3508   uint32_t classMethods;            /* method_list_t * (32-bit pointer) */
3509   uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
3510   uint32_t optionalClassMethods;    /* method_list_t * (32-bit pointer) */
3511   uint32_t instanceProperties;      /* struct objc_property_list *
3512                                                        (32-bit pointer) */
3513 };
3514 
3515 struct ivar_list64_t {
3516   uint32_t entsize;
3517   uint32_t count;
3518   /* struct ivar64_t first;  These structures follow inline */
3519 };
3520 
3521 struct ivar_list32_t {
3522   uint32_t entsize;
3523   uint32_t count;
3524   /* struct ivar32_t first;  These structures follow inline */
3525 };
3526 
3527 struct ivar64_t {
3528   uint64_t offset; /* uintptr_t * (64-bit pointer) */
3529   uint64_t name;   /* const char * (64-bit pointer) */
3530   uint64_t type;   /* const char * (64-bit pointer) */
3531   uint32_t alignment;
3532   uint32_t size;
3533 };
3534 
3535 struct ivar32_t {
3536   uint32_t offset; /* uintptr_t * (32-bit pointer) */
3537   uint32_t name;   /* const char * (32-bit pointer) */
3538   uint32_t type;   /* const char * (32-bit pointer) */
3539   uint32_t alignment;
3540   uint32_t size;
3541 };
3542 
3543 struct objc_property_list64 {
3544   uint32_t entsize;
3545   uint32_t count;
3546   /* struct objc_property64 first;  These structures follow inline */
3547 };
3548 
3549 struct objc_property_list32 {
3550   uint32_t entsize;
3551   uint32_t count;
3552   /* struct objc_property32 first;  These structures follow inline */
3553 };
3554 
3555 struct objc_property64 {
3556   uint64_t name;       /* const char * (64-bit pointer) */
3557   uint64_t attributes; /* const char * (64-bit pointer) */
3558 };
3559 
3560 struct objc_property32 {
3561   uint32_t name;       /* const char * (32-bit pointer) */
3562   uint32_t attributes; /* const char * (32-bit pointer) */
3563 };
3564 
3565 struct category64_t {
3566   uint64_t name;               /* const char * (64-bit pointer) */
3567   uint64_t cls;                /* struct class_t * (64-bit pointer) */
3568   uint64_t instanceMethods;    /* struct method_list_t * (64-bit pointer) */
3569   uint64_t classMethods;       /* struct method_list_t * (64-bit pointer) */
3570   uint64_t protocols;          /* struct protocol_list_t * (64-bit pointer) */
3571   uint64_t instanceProperties; /* struct objc_property_list *
3572                                   (64-bit pointer) */
3573 };
3574 
3575 struct category32_t {
3576   uint32_t name;               /* const char * (32-bit pointer) */
3577   uint32_t cls;                /* struct class_t * (32-bit pointer) */
3578   uint32_t instanceMethods;    /* struct method_list_t * (32-bit pointer) */
3579   uint32_t classMethods;       /* struct method_list_t * (32-bit pointer) */
3580   uint32_t protocols;          /* struct protocol_list_t * (32-bit pointer) */
3581   uint32_t instanceProperties; /* struct objc_property_list *
3582                                   (32-bit pointer) */
3583 };
3584 
3585 struct objc_image_info64 {
3586   uint32_t version;
3587   uint32_t flags;
3588 };
3589 struct objc_image_info32 {
3590   uint32_t version;
3591   uint32_t flags;
3592 };
3593 struct imageInfo_t {
3594   uint32_t version;
3595   uint32_t flags;
3596 };
3597 /* masks for objc_image_info.flags */
3598 #define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
3599 #define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
3600 #define OBJC_IMAGE_IS_SIMULATED (1 << 5)
3601 #define OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES (1 << 6)
3602 
3603 struct message_ref64 {
3604   uint64_t imp; /* IMP (64-bit pointer) */
3605   uint64_t sel; /* SEL (64-bit pointer) */
3606 };
3607 
3608 struct message_ref32 {
3609   uint32_t imp; /* IMP (32-bit pointer) */
3610   uint32_t sel; /* SEL (32-bit pointer) */
3611 };
3612 
3613 // Objective-C 1 (32-bit only) meta data structs.
3614 
3615 struct objc_module_t {
3616   uint32_t version;
3617   uint32_t size;
3618   uint32_t name;   /* char * (32-bit pointer) */
3619   uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
3620 };
3621 
3622 struct objc_symtab_t {
3623   uint32_t sel_ref_cnt;
3624   uint32_t refs; /* SEL * (32-bit pointer) */
3625   uint16_t cls_def_cnt;
3626   uint16_t cat_def_cnt;
3627   // uint32_t defs[1];        /* void * (32-bit pointer) variable size */
3628 };
3629 
3630 struct objc_class_t {
3631   uint32_t isa;         /* struct objc_class * (32-bit pointer) */
3632   uint32_t super_class; /* struct objc_class * (32-bit pointer) */
3633   uint32_t name;        /* const char * (32-bit pointer) */
3634   int32_t version;
3635   int32_t info;
3636   int32_t instance_size;
3637   uint32_t ivars;       /* struct objc_ivar_list * (32-bit pointer) */
3638   uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
3639   uint32_t cache;       /* struct objc_cache * (32-bit pointer) */
3640   uint32_t protocols;   /* struct objc_protocol_list * (32-bit pointer) */
3641 };
3642 
3643 #define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
3644 // class is not a metaclass
3645 #define CLS_CLASS 0x1
3646 // class is a metaclass
3647 #define CLS_META 0x2
3648 
3649 struct objc_category_t {
3650   uint32_t category_name;    /* char * (32-bit pointer) */
3651   uint32_t class_name;       /* char * (32-bit pointer) */
3652   uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
3653   uint32_t class_methods;    /* struct objc_method_list * (32-bit pointer) */
3654   uint32_t protocols;        /* struct objc_protocol_list * (32-bit ptr) */
3655 };
3656 
3657 struct objc_ivar_t {
3658   uint32_t ivar_name; /* char * (32-bit pointer) */
3659   uint32_t ivar_type; /* char * (32-bit pointer) */
3660   int32_t ivar_offset;
3661 };
3662 
3663 struct objc_ivar_list_t {
3664   int32_t ivar_count;
3665   // struct objc_ivar_t ivar_list[1];          /* variable length structure */
3666 };
3667 
3668 struct objc_method_list_t {
3669   uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
3670   int32_t method_count;
3671   // struct objc_method_t method_list[1];      /* variable length structure */
3672 };
3673 
3674 struct objc_method_t {
3675   uint32_t method_name;  /* SEL, aka struct objc_selector * (32-bit pointer) */
3676   uint32_t method_types; /* char * (32-bit pointer) */
3677   uint32_t method_imp;   /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
3678                             (32-bit pointer) */
3679 };
3680 
3681 struct objc_protocol_list_t {
3682   uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
3683   int32_t count;
3684   // uint32_t list[1];   /* Protocol *, aka struct objc_protocol_t *
3685   //                        (32-bit pointer) */
3686 };
3687 
3688 struct objc_protocol_t {
3689   uint32_t isa;              /* struct objc_class * (32-bit pointer) */
3690   uint32_t protocol_name;    /* char * (32-bit pointer) */
3691   uint32_t protocol_list;    /* struct objc_protocol_list * (32-bit pointer) */
3692   uint32_t instance_methods; /* struct objc_method_description_list *
3693                                 (32-bit pointer) */
3694   uint32_t class_methods;    /* struct objc_method_description_list *
3695                                 (32-bit pointer) */
3696 };
3697 
3698 struct objc_method_description_list_t {
3699   int32_t count;
3700   // struct objc_method_description_t list[1];
3701 };
3702 
3703 struct objc_method_description_t {
3704   uint32_t name;  /* SEL, aka struct objc_selector * (32-bit pointer) */
3705   uint32_t types; /* char * (32-bit pointer) */
3706 };
3707 
3708 inline void swapStruct(struct cfstring64_t &cfs) {
3709   sys::swapByteOrder(cfs.isa);
3710   sys::swapByteOrder(cfs.flags);
3711   sys::swapByteOrder(cfs.characters);
3712   sys::swapByteOrder(cfs.length);
3713 }
3714 
3715 inline void swapStruct(struct class64_t &c) {
3716   sys::swapByteOrder(c.isa);
3717   sys::swapByteOrder(c.superclass);
3718   sys::swapByteOrder(c.cache);
3719   sys::swapByteOrder(c.vtable);
3720   sys::swapByteOrder(c.data);
3721 }
3722 
3723 inline void swapStruct(struct class32_t &c) {
3724   sys::swapByteOrder(c.isa);
3725   sys::swapByteOrder(c.superclass);
3726   sys::swapByteOrder(c.cache);
3727   sys::swapByteOrder(c.vtable);
3728   sys::swapByteOrder(c.data);
3729 }
3730 
3731 inline void swapStruct(struct class_ro64_t &cro) {
3732   sys::swapByteOrder(cro.flags);
3733   sys::swapByteOrder(cro.instanceStart);
3734   sys::swapByteOrder(cro.instanceSize);
3735   sys::swapByteOrder(cro.reserved);
3736   sys::swapByteOrder(cro.ivarLayout);
3737   sys::swapByteOrder(cro.name);
3738   sys::swapByteOrder(cro.baseMethods);
3739   sys::swapByteOrder(cro.baseProtocols);
3740   sys::swapByteOrder(cro.ivars);
3741   sys::swapByteOrder(cro.weakIvarLayout);
3742   sys::swapByteOrder(cro.baseProperties);
3743 }
3744 
3745 inline void swapStruct(struct class_ro32_t &cro) {
3746   sys::swapByteOrder(cro.flags);
3747   sys::swapByteOrder(cro.instanceStart);
3748   sys::swapByteOrder(cro.instanceSize);
3749   sys::swapByteOrder(cro.ivarLayout);
3750   sys::swapByteOrder(cro.name);
3751   sys::swapByteOrder(cro.baseMethods);
3752   sys::swapByteOrder(cro.baseProtocols);
3753   sys::swapByteOrder(cro.ivars);
3754   sys::swapByteOrder(cro.weakIvarLayout);
3755   sys::swapByteOrder(cro.baseProperties);
3756 }
3757 
3758 inline void swapStruct(struct method_list64_t &ml) {
3759   sys::swapByteOrder(ml.entsize);
3760   sys::swapByteOrder(ml.count);
3761 }
3762 
3763 inline void swapStruct(struct method_list32_t &ml) {
3764   sys::swapByteOrder(ml.entsize);
3765   sys::swapByteOrder(ml.count);
3766 }
3767 
3768 inline void swapStruct(struct method64_t &m) {
3769   sys::swapByteOrder(m.name);
3770   sys::swapByteOrder(m.types);
3771   sys::swapByteOrder(m.imp);
3772 }
3773 
3774 inline void swapStruct(struct method32_t &m) {
3775   sys::swapByteOrder(m.name);
3776   sys::swapByteOrder(m.types);
3777   sys::swapByteOrder(m.imp);
3778 }
3779 
3780 inline void swapStruct(struct protocol_list64_t &pl) {
3781   sys::swapByteOrder(pl.count);
3782 }
3783 
3784 inline void swapStruct(struct protocol_list32_t &pl) {
3785   sys::swapByteOrder(pl.count);
3786 }
3787 
3788 inline void swapStruct(struct protocol64_t &p) {
3789   sys::swapByteOrder(p.isa);
3790   sys::swapByteOrder(p.name);
3791   sys::swapByteOrder(p.protocols);
3792   sys::swapByteOrder(p.instanceMethods);
3793   sys::swapByteOrder(p.classMethods);
3794   sys::swapByteOrder(p.optionalInstanceMethods);
3795   sys::swapByteOrder(p.optionalClassMethods);
3796   sys::swapByteOrder(p.instanceProperties);
3797 }
3798 
3799 inline void swapStruct(struct protocol32_t &p) {
3800   sys::swapByteOrder(p.isa);
3801   sys::swapByteOrder(p.name);
3802   sys::swapByteOrder(p.protocols);
3803   sys::swapByteOrder(p.instanceMethods);
3804   sys::swapByteOrder(p.classMethods);
3805   sys::swapByteOrder(p.optionalInstanceMethods);
3806   sys::swapByteOrder(p.optionalClassMethods);
3807   sys::swapByteOrder(p.instanceProperties);
3808 }
3809 
3810 inline void swapStruct(struct ivar_list64_t &il) {
3811   sys::swapByteOrder(il.entsize);
3812   sys::swapByteOrder(il.count);
3813 }
3814 
3815 inline void swapStruct(struct ivar_list32_t &il) {
3816   sys::swapByteOrder(il.entsize);
3817   sys::swapByteOrder(il.count);
3818 }
3819 
3820 inline void swapStruct(struct ivar64_t &i) {
3821   sys::swapByteOrder(i.offset);
3822   sys::swapByteOrder(i.name);
3823   sys::swapByteOrder(i.type);
3824   sys::swapByteOrder(i.alignment);
3825   sys::swapByteOrder(i.size);
3826 }
3827 
3828 inline void swapStruct(struct ivar32_t &i) {
3829   sys::swapByteOrder(i.offset);
3830   sys::swapByteOrder(i.name);
3831   sys::swapByteOrder(i.type);
3832   sys::swapByteOrder(i.alignment);
3833   sys::swapByteOrder(i.size);
3834 }
3835 
3836 inline void swapStruct(struct objc_property_list64 &pl) {
3837   sys::swapByteOrder(pl.entsize);
3838   sys::swapByteOrder(pl.count);
3839 }
3840 
3841 inline void swapStruct(struct objc_property_list32 &pl) {
3842   sys::swapByteOrder(pl.entsize);
3843   sys::swapByteOrder(pl.count);
3844 }
3845 
3846 inline void swapStruct(struct objc_property64 &op) {
3847   sys::swapByteOrder(op.name);
3848   sys::swapByteOrder(op.attributes);
3849 }
3850 
3851 inline void swapStruct(struct objc_property32 &op) {
3852   sys::swapByteOrder(op.name);
3853   sys::swapByteOrder(op.attributes);
3854 }
3855 
3856 inline void swapStruct(struct category64_t &c) {
3857   sys::swapByteOrder(c.name);
3858   sys::swapByteOrder(c.cls);
3859   sys::swapByteOrder(c.instanceMethods);
3860   sys::swapByteOrder(c.classMethods);
3861   sys::swapByteOrder(c.protocols);
3862   sys::swapByteOrder(c.instanceProperties);
3863 }
3864 
3865 inline void swapStruct(struct category32_t &c) {
3866   sys::swapByteOrder(c.name);
3867   sys::swapByteOrder(c.cls);
3868   sys::swapByteOrder(c.instanceMethods);
3869   sys::swapByteOrder(c.classMethods);
3870   sys::swapByteOrder(c.protocols);
3871   sys::swapByteOrder(c.instanceProperties);
3872 }
3873 
3874 inline void swapStruct(struct objc_image_info64 &o) {
3875   sys::swapByteOrder(o.version);
3876   sys::swapByteOrder(o.flags);
3877 }
3878 
3879 inline void swapStruct(struct objc_image_info32 &o) {
3880   sys::swapByteOrder(o.version);
3881   sys::swapByteOrder(o.flags);
3882 }
3883 
3884 inline void swapStruct(struct imageInfo_t &o) {
3885   sys::swapByteOrder(o.version);
3886   sys::swapByteOrder(o.flags);
3887 }
3888 
3889 inline void swapStruct(struct message_ref64 &mr) {
3890   sys::swapByteOrder(mr.imp);
3891   sys::swapByteOrder(mr.sel);
3892 }
3893 
3894 inline void swapStruct(struct message_ref32 &mr) {
3895   sys::swapByteOrder(mr.imp);
3896   sys::swapByteOrder(mr.sel);
3897 }
3898 
3899 inline void swapStruct(struct objc_module_t &module) {
3900   sys::swapByteOrder(module.version);
3901   sys::swapByteOrder(module.size);
3902   sys::swapByteOrder(module.name);
3903   sys::swapByteOrder(module.symtab);
3904 }
3905 
3906 inline void swapStruct(struct objc_symtab_t &symtab) {
3907   sys::swapByteOrder(symtab.sel_ref_cnt);
3908   sys::swapByteOrder(symtab.refs);
3909   sys::swapByteOrder(symtab.cls_def_cnt);
3910   sys::swapByteOrder(symtab.cat_def_cnt);
3911 }
3912 
3913 inline void swapStruct(struct objc_class_t &objc_class) {
3914   sys::swapByteOrder(objc_class.isa);
3915   sys::swapByteOrder(objc_class.super_class);
3916   sys::swapByteOrder(objc_class.name);
3917   sys::swapByteOrder(objc_class.version);
3918   sys::swapByteOrder(objc_class.info);
3919   sys::swapByteOrder(objc_class.instance_size);
3920   sys::swapByteOrder(objc_class.ivars);
3921   sys::swapByteOrder(objc_class.methodLists);
3922   sys::swapByteOrder(objc_class.cache);
3923   sys::swapByteOrder(objc_class.protocols);
3924 }
3925 
3926 inline void swapStruct(struct objc_category_t &objc_category) {
3927   sys::swapByteOrder(objc_category.category_name);
3928   sys::swapByteOrder(objc_category.class_name);
3929   sys::swapByteOrder(objc_category.instance_methods);
3930   sys::swapByteOrder(objc_category.class_methods);
3931   sys::swapByteOrder(objc_category.protocols);
3932 }
3933 
3934 inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3935   sys::swapByteOrder(objc_ivar_list.ivar_count);
3936 }
3937 
3938 inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3939   sys::swapByteOrder(objc_ivar.ivar_name);
3940   sys::swapByteOrder(objc_ivar.ivar_type);
3941   sys::swapByteOrder(objc_ivar.ivar_offset);
3942 }
3943 
3944 inline void swapStruct(struct objc_method_list_t &method_list) {
3945   sys::swapByteOrder(method_list.obsolete);
3946   sys::swapByteOrder(method_list.method_count);
3947 }
3948 
3949 inline void swapStruct(struct objc_method_t &method) {
3950   sys::swapByteOrder(method.method_name);
3951   sys::swapByteOrder(method.method_types);
3952   sys::swapByteOrder(method.method_imp);
3953 }
3954 
3955 inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3956   sys::swapByteOrder(protocol_list.next);
3957   sys::swapByteOrder(protocol_list.count);
3958 }
3959 
3960 inline void swapStruct(struct objc_protocol_t &protocol) {
3961   sys::swapByteOrder(protocol.isa);
3962   sys::swapByteOrder(protocol.protocol_name);
3963   sys::swapByteOrder(protocol.protocol_list);
3964   sys::swapByteOrder(protocol.instance_methods);
3965   sys::swapByteOrder(protocol.class_methods);
3966 }
3967 
3968 inline void swapStruct(struct objc_method_description_list_t &mdl) {
3969   sys::swapByteOrder(mdl.count);
3970 }
3971 
3972 inline void swapStruct(struct objc_method_description_t &md) {
3973   sys::swapByteOrder(md.name);
3974   sys::swapByteOrder(md.types);
3975 }
3976 
3977 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3978                                                  struct DisassembleInfo *info);
3979 
3980 // get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3981 // to an Objective-C class and returns the class name.  It is also passed the
3982 // address of the pointer, so when the pointer is zero as it can be in an .o
3983 // file, that is used to look for an external relocation entry with a symbol
3984 // name.
3985 static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3986                                               uint64_t ReferenceValue,
3987                                               struct DisassembleInfo *info) {
3988   const char *r;
3989   uint32_t offset, left;
3990   SectionRef S;
3991 
3992   // The pointer_value can be 0 in an object file and have a relocation
3993   // entry for the class symbol at the ReferenceValue (the address of the
3994   // pointer).
3995   if (pointer_value == 0) {
3996     r = get_pointer_64(ReferenceValue, offset, left, S, info);
3997     if (r == nullptr || left < sizeof(uint64_t))
3998       return nullptr;
3999     uint64_t n_value;
4000     const char *symbol_name = get_symbol_64(offset, S, info, n_value);
4001     if (symbol_name == nullptr)
4002       return nullptr;
4003     const char *class_name = strrchr(symbol_name, '$');
4004     if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
4005       return class_name + 2;
4006     else
4007       return nullptr;
4008   }
4009 
4010   // The case were the pointer_value is non-zero and points to a class defined
4011   // in this Mach-O file.
4012   r = get_pointer_64(pointer_value, offset, left, S, info);
4013   if (r == nullptr || left < sizeof(struct class64_t))
4014     return nullptr;
4015   struct class64_t c;
4016   memcpy(&c, r, sizeof(struct class64_t));
4017   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4018     swapStruct(c);
4019   if (c.data == 0)
4020     return nullptr;
4021   r = get_pointer_64(c.data, offset, left, S, info);
4022   if (r == nullptr || left < sizeof(struct class_ro64_t))
4023     return nullptr;
4024   struct class_ro64_t cro;
4025   memcpy(&cro, r, sizeof(struct class_ro64_t));
4026   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4027     swapStruct(cro);
4028   if (cro.name == 0)
4029     return nullptr;
4030   const char *name = get_pointer_64(cro.name, offset, left, S, info);
4031   return name;
4032 }
4033 
4034 // get_objc2_64bit_cfstring_name is used for disassembly and is passed a
4035 // pointer to a cfstring and returns its name or nullptr.
4036 static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
4037                                                  struct DisassembleInfo *info) {
4038   const char *r, *name;
4039   uint32_t offset, left;
4040   SectionRef S;
4041   struct cfstring64_t cfs;
4042   uint64_t cfs_characters;
4043 
4044   r = get_pointer_64(ReferenceValue, offset, left, S, info);
4045   if (r == nullptr || left < sizeof(struct cfstring64_t))
4046     return nullptr;
4047   memcpy(&cfs, r, sizeof(struct cfstring64_t));
4048   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4049     swapStruct(cfs);
4050   if (cfs.characters == 0) {
4051     uint64_t n_value;
4052     const char *symbol_name = get_symbol_64(
4053         offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
4054     if (symbol_name == nullptr)
4055       return nullptr;
4056     cfs_characters = n_value;
4057   } else
4058     cfs_characters = cfs.characters;
4059   name = get_pointer_64(cfs_characters, offset, left, S, info);
4060 
4061   return name;
4062 }
4063 
4064 // get_objc2_64bit_selref() is used for disassembly and is passed a the address
4065 // of a pointer to an Objective-C selector reference when the pointer value is
4066 // zero as in a .o file and is likely to have a external relocation entry with
4067 // who's symbol's n_value is the real pointer to the selector name.  If that is
4068 // the case the real pointer to the selector name is returned else 0 is
4069 // returned
4070 static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
4071                                        struct DisassembleInfo *info) {
4072   uint32_t offset, left;
4073   SectionRef S;
4074 
4075   const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
4076   if (r == nullptr || left < sizeof(uint64_t))
4077     return 0;
4078   uint64_t n_value;
4079   const char *symbol_name = get_symbol_64(offset, S, info, n_value);
4080   if (symbol_name == nullptr)
4081     return 0;
4082   return n_value;
4083 }
4084 
4085 static const SectionRef get_section(MachOObjectFile *O, const char *segname,
4086                                     const char *sectname) {
4087   for (const SectionRef &Section : O->sections()) {
4088     StringRef SectName;
4089     Expected<StringRef> SecNameOrErr = Section.getName();
4090     if (SecNameOrErr)
4091       SectName = *SecNameOrErr;
4092     else
4093       consumeError(SecNameOrErr.takeError());
4094 
4095     DataRefImpl Ref = Section.getRawDataRefImpl();
4096     StringRef SegName = O->getSectionFinalSegmentName(Ref);
4097     if (SegName == segname && SectName == sectname)
4098       return Section;
4099   }
4100   return SectionRef();
4101 }
4102 
4103 static void
4104 walk_pointer_list_64(const char *listname, const SectionRef S,
4105                      MachOObjectFile *O, struct DisassembleInfo *info,
4106                      void (*func)(uint64_t, struct DisassembleInfo *info)) {
4107   if (S == SectionRef())
4108     return;
4109 
4110   StringRef SectName;
4111   Expected<StringRef> SecNameOrErr = S.getName();
4112   if (SecNameOrErr)
4113     SectName = *SecNameOrErr;
4114   else
4115     consumeError(SecNameOrErr.takeError());
4116 
4117   DataRefImpl Ref = S.getRawDataRefImpl();
4118   StringRef SegName = O->getSectionFinalSegmentName(Ref);
4119   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4120 
4121   StringRef BytesStr = unwrapOrError(S.getContents(), O->getFileName());
4122   const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
4123 
4124   for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
4125     uint32_t left = S.getSize() - i;
4126     uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
4127     uint64_t p = 0;
4128     memcpy(&p, Contents + i, size);
4129     if (i + sizeof(uint64_t) > S.getSize())
4130       outs() << listname << " list pointer extends past end of (" << SegName
4131              << "," << SectName << ") section\n";
4132     outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
4133 
4134     if (O->isLittleEndian() != sys::IsLittleEndianHost)
4135       sys::swapByteOrder(p);
4136 
4137     uint64_t n_value = 0;
4138     const char *name = get_symbol_64(i, S, info, n_value, p);
4139     if (name == nullptr)
4140       name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
4141 
4142     if (n_value != 0) {
4143       outs() << format("0x%" PRIx64, n_value);
4144       if (p != 0)
4145         outs() << " + " << format("0x%" PRIx64, p);
4146     } else
4147       outs() << format("0x%" PRIx64, p);
4148     if (name != nullptr)
4149       outs() << " " << name;
4150     outs() << "\n";
4151 
4152     p += n_value;
4153     if (func)
4154       func(p, info);
4155   }
4156 }
4157 
4158 static void
4159 walk_pointer_list_32(const char *listname, const SectionRef S,
4160                      MachOObjectFile *O, struct DisassembleInfo *info,
4161                      void (*func)(uint32_t, struct DisassembleInfo *info)) {
4162   if (S == SectionRef())
4163     return;
4164 
4165   StringRef SectName = unwrapOrError(S.getName(), O->getFileName());
4166   DataRefImpl Ref = S.getRawDataRefImpl();
4167   StringRef SegName = O->getSectionFinalSegmentName(Ref);
4168   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4169 
4170   StringRef BytesStr = unwrapOrError(S.getContents(), O->getFileName());
4171   const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
4172 
4173   for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
4174     uint32_t left = S.getSize() - i;
4175     uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
4176     uint32_t p = 0;
4177     memcpy(&p, Contents + i, size);
4178     if (i + sizeof(uint32_t) > S.getSize())
4179       outs() << listname << " list pointer extends past end of (" << SegName
4180              << "," << SectName << ") section\n";
4181     uint32_t Address = S.getAddress() + i;
4182     outs() << format("%08" PRIx32, Address) << " ";
4183 
4184     if (O->isLittleEndian() != sys::IsLittleEndianHost)
4185       sys::swapByteOrder(p);
4186     outs() << format("0x%" PRIx32, p);
4187 
4188     const char *name = get_symbol_32(i, S, info, p);
4189     if (name != nullptr)
4190       outs() << " " << name;
4191     outs() << "\n";
4192 
4193     if (func)
4194       func(p, info);
4195   }
4196 }
4197 
4198 static void print_layout_map(const char *layout_map, uint32_t left) {
4199   if (layout_map == nullptr)
4200     return;
4201   outs() << "                layout map: ";
4202   do {
4203     outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
4204     left--;
4205     layout_map++;
4206   } while (*layout_map != '\0' && left != 0);
4207   outs() << "\n";
4208 }
4209 
4210 static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
4211   uint32_t offset, left;
4212   SectionRef S;
4213   const char *layout_map;
4214 
4215   if (p == 0)
4216     return;
4217   layout_map = get_pointer_64(p, offset, left, S, info);
4218   print_layout_map(layout_map, left);
4219 }
4220 
4221 static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
4222   uint32_t offset, left;
4223   SectionRef S;
4224   const char *layout_map;
4225 
4226   if (p == 0)
4227     return;
4228   layout_map = get_pointer_32(p, offset, left, S, info);
4229   print_layout_map(layout_map, left);
4230 }
4231 
4232 static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
4233                                   const char *indent) {
4234   struct method_list64_t ml;
4235   struct method64_t m;
4236   const char *r;
4237   uint32_t offset, xoffset, left, i;
4238   SectionRef S, xS;
4239   const char *name, *sym_name;
4240   uint64_t n_value;
4241 
4242   r = get_pointer_64(p, offset, left, S, info);
4243   if (r == nullptr)
4244     return;
4245   memset(&ml, '\0', sizeof(struct method_list64_t));
4246   if (left < sizeof(struct method_list64_t)) {
4247     memcpy(&ml, r, left);
4248     outs() << "   (method_list_t entends past the end of the section)\n";
4249   } else
4250     memcpy(&ml, r, sizeof(struct method_list64_t));
4251   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4252     swapStruct(ml);
4253   outs() << indent << "\t\t   entsize " << ml.entsize << "\n";
4254   outs() << indent << "\t\t     count " << ml.count << "\n";
4255 
4256   p += sizeof(struct method_list64_t);
4257   offset += sizeof(struct method_list64_t);
4258   for (i = 0; i < ml.count; i++) {
4259     r = get_pointer_64(p, offset, left, S, info);
4260     if (r == nullptr)
4261       return;
4262     memset(&m, '\0', sizeof(struct method64_t));
4263     if (left < sizeof(struct method64_t)) {
4264       memcpy(&m, r, left);
4265       outs() << indent << "   (method_t extends past the end of the section)\n";
4266     } else
4267       memcpy(&m, r, sizeof(struct method64_t));
4268     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4269       swapStruct(m);
4270 
4271     outs() << indent << "\t\t      name ";
4272     sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
4273                              info, n_value, m.name);
4274     if (n_value != 0) {
4275       if (info->verbose && sym_name != nullptr)
4276         outs() << sym_name;
4277       else
4278         outs() << format("0x%" PRIx64, n_value);
4279       if (m.name != 0)
4280         outs() << " + " << format("0x%" PRIx64, m.name);
4281     } else
4282       outs() << format("0x%" PRIx64, m.name);
4283     name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
4284     if (name != nullptr)
4285       outs() << format(" %.*s", left, name);
4286     outs() << "\n";
4287 
4288     outs() << indent << "\t\t     types ";
4289     sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
4290                              info, n_value, m.types);
4291     if (n_value != 0) {
4292       if (info->verbose && sym_name != nullptr)
4293         outs() << sym_name;
4294       else
4295         outs() << format("0x%" PRIx64, n_value);
4296       if (m.types != 0)
4297         outs() << " + " << format("0x%" PRIx64, m.types);
4298     } else
4299       outs() << format("0x%" PRIx64, m.types);
4300     name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
4301     if (name != nullptr)
4302       outs() << format(" %.*s", left, name);
4303     outs() << "\n";
4304 
4305     outs() << indent << "\t\t       imp ";
4306     name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
4307                          n_value, m.imp);
4308     if (info->verbose && name == nullptr) {
4309       if (n_value != 0) {
4310         outs() << format("0x%" PRIx64, n_value) << " ";
4311         if (m.imp != 0)
4312           outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
4313       } else
4314         outs() << format("0x%" PRIx64, m.imp) << " ";
4315     }
4316     if (name != nullptr)
4317       outs() << name;
4318     outs() << "\n";
4319 
4320     p += sizeof(struct method64_t);
4321     offset += sizeof(struct method64_t);
4322   }
4323 }
4324 
4325 static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
4326                                   const char *indent) {
4327   struct method_list32_t ml;
4328   struct method32_t m;
4329   const char *r, *name;
4330   uint32_t offset, xoffset, left, i;
4331   SectionRef S, xS;
4332 
4333   r = get_pointer_32(p, offset, left, S, info);
4334   if (r == nullptr)
4335     return;
4336   memset(&ml, '\0', sizeof(struct method_list32_t));
4337   if (left < sizeof(struct method_list32_t)) {
4338     memcpy(&ml, r, left);
4339     outs() << "   (method_list_t entends past the end of the section)\n";
4340   } else
4341     memcpy(&ml, r, sizeof(struct method_list32_t));
4342   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4343     swapStruct(ml);
4344   outs() << indent << "\t\t   entsize " << ml.entsize << "\n";
4345   outs() << indent << "\t\t     count " << ml.count << "\n";
4346 
4347   p += sizeof(struct method_list32_t);
4348   offset += sizeof(struct method_list32_t);
4349   for (i = 0; i < ml.count; i++) {
4350     r = get_pointer_32(p, offset, left, S, info);
4351     if (r == nullptr)
4352       return;
4353     memset(&m, '\0', sizeof(struct method32_t));
4354     if (left < sizeof(struct method32_t)) {
4355       memcpy(&ml, r, left);
4356       outs() << indent << "   (method_t entends past the end of the section)\n";
4357     } else
4358       memcpy(&m, r, sizeof(struct method32_t));
4359     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4360       swapStruct(m);
4361 
4362     outs() << indent << "\t\t      name " << format("0x%" PRIx32, m.name);
4363     name = get_pointer_32(m.name, xoffset, left, xS, info);
4364     if (name != nullptr)
4365       outs() << format(" %.*s", left, name);
4366     outs() << "\n";
4367 
4368     outs() << indent << "\t\t     types " << format("0x%" PRIx32, m.types);
4369     name = get_pointer_32(m.types, xoffset, left, xS, info);
4370     if (name != nullptr)
4371       outs() << format(" %.*s", left, name);
4372     outs() << "\n";
4373 
4374     outs() << indent << "\t\t       imp " << format("0x%" PRIx32, m.imp);
4375     name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
4376                          m.imp);
4377     if (name != nullptr)
4378       outs() << " " << name;
4379     outs() << "\n";
4380 
4381     p += sizeof(struct method32_t);
4382     offset += sizeof(struct method32_t);
4383   }
4384 }
4385 
4386 static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
4387   uint32_t offset, left, xleft;
4388   SectionRef S;
4389   struct objc_method_list_t method_list;
4390   struct objc_method_t method;
4391   const char *r, *methods, *name, *SymbolName;
4392   int32_t i;
4393 
4394   r = get_pointer_32(p, offset, left, S, info, true);
4395   if (r == nullptr)
4396     return true;
4397 
4398   outs() << "\n";
4399   if (left > sizeof(struct objc_method_list_t)) {
4400     memcpy(&method_list, r, sizeof(struct objc_method_list_t));
4401   } else {
4402     outs() << "\t\t objc_method_list extends past end of the section\n";
4403     memset(&method_list, '\0', sizeof(struct objc_method_list_t));
4404     memcpy(&method_list, r, left);
4405   }
4406   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4407     swapStruct(method_list);
4408 
4409   outs() << "\t\t         obsolete "
4410          << format("0x%08" PRIx32, method_list.obsolete) << "\n";
4411   outs() << "\t\t     method_count " << method_list.method_count << "\n";
4412 
4413   methods = r + sizeof(struct objc_method_list_t);
4414   for (i = 0; i < method_list.method_count; i++) {
4415     if ((i + 1) * sizeof(struct objc_method_t) > left) {
4416       outs() << "\t\t remaining method's extend past the of the section\n";
4417       break;
4418     }
4419     memcpy(&method, methods + i * sizeof(struct objc_method_t),
4420            sizeof(struct objc_method_t));
4421     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4422       swapStruct(method);
4423 
4424     outs() << "\t\t      method_name "
4425            << format("0x%08" PRIx32, method.method_name);
4426     if (info->verbose) {
4427       name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
4428       if (name != nullptr)
4429         outs() << format(" %.*s", xleft, name);
4430       else
4431         outs() << " (not in an __OBJC section)";
4432     }
4433     outs() << "\n";
4434 
4435     outs() << "\t\t     method_types "
4436            << format("0x%08" PRIx32, method.method_types);
4437     if (info->verbose) {
4438       name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
4439       if (name != nullptr)
4440         outs() << format(" %.*s", xleft, name);
4441       else
4442         outs() << " (not in an __OBJC section)";
4443     }
4444     outs() << "\n";
4445 
4446     outs() << "\t\t       method_imp "
4447            << format("0x%08" PRIx32, method.method_imp) << " ";
4448     if (info->verbose) {
4449       SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
4450       if (SymbolName != nullptr)
4451         outs() << SymbolName;
4452     }
4453     outs() << "\n";
4454   }
4455   return false;
4456 }
4457 
4458 static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
4459   struct protocol_list64_t pl;
4460   uint64_t q, n_value;
4461   struct protocol64_t pc;
4462   const char *r;
4463   uint32_t offset, xoffset, left, i;
4464   SectionRef S, xS;
4465   const char *name, *sym_name;
4466 
4467   r = get_pointer_64(p, offset, left, S, info);
4468   if (r == nullptr)
4469     return;
4470   memset(&pl, '\0', sizeof(struct protocol_list64_t));
4471   if (left < sizeof(struct protocol_list64_t)) {
4472     memcpy(&pl, r, left);
4473     outs() << "   (protocol_list_t entends past the end of the section)\n";
4474   } else
4475     memcpy(&pl, r, sizeof(struct protocol_list64_t));
4476   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4477     swapStruct(pl);
4478   outs() << "                      count " << pl.count << "\n";
4479 
4480   p += sizeof(struct protocol_list64_t);
4481   offset += sizeof(struct protocol_list64_t);
4482   for (i = 0; i < pl.count; i++) {
4483     r = get_pointer_64(p, offset, left, S, info);
4484     if (r == nullptr)
4485       return;
4486     q = 0;
4487     if (left < sizeof(uint64_t)) {
4488       memcpy(&q, r, left);
4489       outs() << "   (protocol_t * entends past the end of the section)\n";
4490     } else
4491       memcpy(&q, r, sizeof(uint64_t));
4492     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4493       sys::swapByteOrder(q);
4494 
4495     outs() << "\t\t      list[" << i << "] ";
4496     sym_name = get_symbol_64(offset, S, info, n_value, q);
4497     if (n_value != 0) {
4498       if (info->verbose && sym_name != nullptr)
4499         outs() << sym_name;
4500       else
4501         outs() << format("0x%" PRIx64, n_value);
4502       if (q != 0)
4503         outs() << " + " << format("0x%" PRIx64, q);
4504     } else
4505       outs() << format("0x%" PRIx64, q);
4506     outs() << " (struct protocol_t *)\n";
4507 
4508     r = get_pointer_64(q + n_value, offset, left, S, info);
4509     if (r == nullptr)
4510       return;
4511     memset(&pc, '\0', sizeof(struct protocol64_t));
4512     if (left < sizeof(struct protocol64_t)) {
4513       memcpy(&pc, r, left);
4514       outs() << "   (protocol_t entends past the end of the section)\n";
4515     } else
4516       memcpy(&pc, r, sizeof(struct protocol64_t));
4517     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4518       swapStruct(pc);
4519 
4520     outs() << "\t\t\t      isa " << format("0x%" PRIx64, pc.isa) << "\n";
4521 
4522     outs() << "\t\t\t     name ";
4523     sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
4524                              info, n_value, pc.name);
4525     if (n_value != 0) {
4526       if (info->verbose && sym_name != nullptr)
4527         outs() << sym_name;
4528       else
4529         outs() << format("0x%" PRIx64, n_value);
4530       if (pc.name != 0)
4531         outs() << " + " << format("0x%" PRIx64, pc.name);
4532     } else
4533       outs() << format("0x%" PRIx64, pc.name);
4534     name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
4535     if (name != nullptr)
4536       outs() << format(" %.*s", left, name);
4537     outs() << "\n";
4538 
4539     outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
4540 
4541     outs() << "\t\t  instanceMethods ";
4542     sym_name =
4543         get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
4544                       S, info, n_value, pc.instanceMethods);
4545     if (n_value != 0) {
4546       if (info->verbose && sym_name != nullptr)
4547         outs() << sym_name;
4548       else
4549         outs() << format("0x%" PRIx64, n_value);
4550       if (pc.instanceMethods != 0)
4551         outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
4552     } else
4553       outs() << format("0x%" PRIx64, pc.instanceMethods);
4554     outs() << " (struct method_list_t *)\n";
4555     if (pc.instanceMethods + n_value != 0)
4556       print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
4557 
4558     outs() << "\t\t     classMethods ";
4559     sym_name =
4560         get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
4561                       info, n_value, pc.classMethods);
4562     if (n_value != 0) {
4563       if (info->verbose && sym_name != nullptr)
4564         outs() << sym_name;
4565       else
4566         outs() << format("0x%" PRIx64, n_value);
4567       if (pc.classMethods != 0)
4568         outs() << " + " << format("0x%" PRIx64, pc.classMethods);
4569     } else
4570       outs() << format("0x%" PRIx64, pc.classMethods);
4571     outs() << " (struct method_list_t *)\n";
4572     if (pc.classMethods + n_value != 0)
4573       print_method_list64_t(pc.classMethods + n_value, info, "\t");
4574 
4575     outs() << "\t  optionalInstanceMethods "
4576            << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
4577     outs() << "\t     optionalClassMethods "
4578            << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
4579     outs() << "\t       instanceProperties "
4580            << format("0x%" PRIx64, pc.instanceProperties) << "\n";
4581 
4582     p += sizeof(uint64_t);
4583     offset += sizeof(uint64_t);
4584   }
4585 }
4586 
4587 static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
4588   struct protocol_list32_t pl;
4589   uint32_t q;
4590   struct protocol32_t pc;
4591   const char *r;
4592   uint32_t offset, xoffset, left, i;
4593   SectionRef S, xS;
4594   const char *name;
4595 
4596   r = get_pointer_32(p, offset, left, S, info);
4597   if (r == nullptr)
4598     return;
4599   memset(&pl, '\0', sizeof(struct protocol_list32_t));
4600   if (left < sizeof(struct protocol_list32_t)) {
4601     memcpy(&pl, r, left);
4602     outs() << "   (protocol_list_t entends past the end of the section)\n";
4603   } else
4604     memcpy(&pl, r, sizeof(struct protocol_list32_t));
4605   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4606     swapStruct(pl);
4607   outs() << "                      count " << pl.count << "\n";
4608 
4609   p += sizeof(struct protocol_list32_t);
4610   offset += sizeof(struct protocol_list32_t);
4611   for (i = 0; i < pl.count; i++) {
4612     r = get_pointer_32(p, offset, left, S, info);
4613     if (r == nullptr)
4614       return;
4615     q = 0;
4616     if (left < sizeof(uint32_t)) {
4617       memcpy(&q, r, left);
4618       outs() << "   (protocol_t * entends past the end of the section)\n";
4619     } else
4620       memcpy(&q, r, sizeof(uint32_t));
4621     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4622       sys::swapByteOrder(q);
4623     outs() << "\t\t      list[" << i << "] " << format("0x%" PRIx32, q)
4624            << " (struct protocol_t *)\n";
4625     r = get_pointer_32(q, offset, left, S, info);
4626     if (r == nullptr)
4627       return;
4628     memset(&pc, '\0', sizeof(struct protocol32_t));
4629     if (left < sizeof(struct protocol32_t)) {
4630       memcpy(&pc, r, left);
4631       outs() << "   (protocol_t entends past the end of the section)\n";
4632     } else
4633       memcpy(&pc, r, sizeof(struct protocol32_t));
4634     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4635       swapStruct(pc);
4636     outs() << "\t\t\t      isa " << format("0x%" PRIx32, pc.isa) << "\n";
4637     outs() << "\t\t\t     name " << format("0x%" PRIx32, pc.name);
4638     name = get_pointer_32(pc.name, xoffset, left, xS, info);
4639     if (name != nullptr)
4640       outs() << format(" %.*s", left, name);
4641     outs() << "\n";
4642     outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
4643     outs() << "\t\t  instanceMethods "
4644            << format("0x%" PRIx32, pc.instanceMethods)
4645            << " (struct method_list_t *)\n";
4646     if (pc.instanceMethods != 0)
4647       print_method_list32_t(pc.instanceMethods, info, "\t");
4648     outs() << "\t\t     classMethods " << format("0x%" PRIx32, pc.classMethods)
4649            << " (struct method_list_t *)\n";
4650     if (pc.classMethods != 0)
4651       print_method_list32_t(pc.classMethods, info, "\t");
4652     outs() << "\t  optionalInstanceMethods "
4653            << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
4654     outs() << "\t     optionalClassMethods "
4655            << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
4656     outs() << "\t       instanceProperties "
4657            << format("0x%" PRIx32, pc.instanceProperties) << "\n";
4658     p += sizeof(uint32_t);
4659     offset += sizeof(uint32_t);
4660   }
4661 }
4662 
4663 static void print_indent(uint32_t indent) {
4664   for (uint32_t i = 0; i < indent;) {
4665     if (indent - i >= 8) {
4666       outs() << "\t";
4667       i += 8;
4668     } else {
4669       for (uint32_t j = i; j < indent; j++)
4670         outs() << " ";
4671       return;
4672     }
4673   }
4674 }
4675 
4676 static bool print_method_description_list(uint32_t p, uint32_t indent,
4677                                           struct DisassembleInfo *info) {
4678   uint32_t offset, left, xleft;
4679   SectionRef S;
4680   struct objc_method_description_list_t mdl;
4681   struct objc_method_description_t md;
4682   const char *r, *list, *name;
4683   int32_t i;
4684 
4685   r = get_pointer_32(p, offset, left, S, info, true);
4686   if (r == nullptr)
4687     return true;
4688 
4689   outs() << "\n";
4690   if (left > sizeof(struct objc_method_description_list_t)) {
4691     memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
4692   } else {
4693     print_indent(indent);
4694     outs() << " objc_method_description_list extends past end of the section\n";
4695     memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
4696     memcpy(&mdl, r, left);
4697   }
4698   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4699     swapStruct(mdl);
4700 
4701   print_indent(indent);
4702   outs() << "        count " << mdl.count << "\n";
4703 
4704   list = r + sizeof(struct objc_method_description_list_t);
4705   for (i = 0; i < mdl.count; i++) {
4706     if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
4707       print_indent(indent);
4708       outs() << " remaining list entries extend past the of the section\n";
4709       break;
4710     }
4711     print_indent(indent);
4712     outs() << "        list[" << i << "]\n";
4713     memcpy(&md, list + i * sizeof(struct objc_method_description_t),
4714            sizeof(struct objc_method_description_t));
4715     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4716       swapStruct(md);
4717 
4718     print_indent(indent);
4719     outs() << "             name " << format("0x%08" PRIx32, md.name);
4720     if (info->verbose) {
4721       name = get_pointer_32(md.name, offset, xleft, S, info, true);
4722       if (name != nullptr)
4723         outs() << format(" %.*s", xleft, name);
4724       else
4725         outs() << " (not in an __OBJC section)";
4726     }
4727     outs() << "\n";
4728 
4729     print_indent(indent);
4730     outs() << "            types " << format("0x%08" PRIx32, md.types);
4731     if (info->verbose) {
4732       name = get_pointer_32(md.types, offset, xleft, S, info, true);
4733       if (name != nullptr)
4734         outs() << format(" %.*s", xleft, name);
4735       else
4736         outs() << " (not in an __OBJC section)";
4737     }
4738     outs() << "\n";
4739   }
4740   return false;
4741 }
4742 
4743 static bool print_protocol_list(uint32_t p, uint32_t indent,
4744                                 struct DisassembleInfo *info);
4745 
4746 static bool print_protocol(uint32_t p, uint32_t indent,
4747                            struct DisassembleInfo *info) {
4748   uint32_t offset, left;
4749   SectionRef S;
4750   struct objc_protocol_t protocol;
4751   const char *r, *name;
4752 
4753   r = get_pointer_32(p, offset, left, S, info, true);
4754   if (r == nullptr)
4755     return true;
4756 
4757   outs() << "\n";
4758   if (left >= sizeof(struct objc_protocol_t)) {
4759     memcpy(&protocol, r, sizeof(struct objc_protocol_t));
4760   } else {
4761     print_indent(indent);
4762     outs() << "            Protocol extends past end of the section\n";
4763     memset(&protocol, '\0', sizeof(struct objc_protocol_t));
4764     memcpy(&protocol, r, left);
4765   }
4766   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4767     swapStruct(protocol);
4768 
4769   print_indent(indent);
4770   outs() << "              isa " << format("0x%08" PRIx32, protocol.isa)
4771          << "\n";
4772 
4773   print_indent(indent);
4774   outs() << "    protocol_name "
4775          << format("0x%08" PRIx32, protocol.protocol_name);
4776   if (info->verbose) {
4777     name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
4778     if (name != nullptr)
4779       outs() << format(" %.*s", left, name);
4780     else
4781       outs() << " (not in an __OBJC section)";
4782   }
4783   outs() << "\n";
4784 
4785   print_indent(indent);
4786   outs() << "    protocol_list "
4787          << format("0x%08" PRIx32, protocol.protocol_list);
4788   if (print_protocol_list(protocol.protocol_list, indent + 4, info))
4789     outs() << " (not in an __OBJC section)\n";
4790 
4791   print_indent(indent);
4792   outs() << " instance_methods "
4793          << format("0x%08" PRIx32, protocol.instance_methods);
4794   if (print_method_description_list(protocol.instance_methods, indent, info))
4795     outs() << " (not in an __OBJC section)\n";
4796 
4797   print_indent(indent);
4798   outs() << "    class_methods "
4799          << format("0x%08" PRIx32, protocol.class_methods);
4800   if (print_method_description_list(protocol.class_methods, indent, info))
4801     outs() << " (not in an __OBJC section)\n";
4802 
4803   return false;
4804 }
4805 
4806 static bool print_protocol_list(uint32_t p, uint32_t indent,
4807                                 struct DisassembleInfo *info) {
4808   uint32_t offset, left, l;
4809   SectionRef S;
4810   struct objc_protocol_list_t protocol_list;
4811   const char *r, *list;
4812   int32_t i;
4813 
4814   r = get_pointer_32(p, offset, left, S, info, true);
4815   if (r == nullptr)
4816     return true;
4817 
4818   outs() << "\n";
4819   if (left > sizeof(struct objc_protocol_list_t)) {
4820     memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
4821   } else {
4822     outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
4823     memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
4824     memcpy(&protocol_list, r, left);
4825   }
4826   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4827     swapStruct(protocol_list);
4828 
4829   print_indent(indent);
4830   outs() << "         next " << format("0x%08" PRIx32, protocol_list.next)
4831          << "\n";
4832   print_indent(indent);
4833   outs() << "        count " << protocol_list.count << "\n";
4834 
4835   list = r + sizeof(struct objc_protocol_list_t);
4836   for (i = 0; i < protocol_list.count; i++) {
4837     if ((i + 1) * sizeof(uint32_t) > left) {
4838       outs() << "\t\t remaining list entries extend past the of the section\n";
4839       break;
4840     }
4841     memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
4842     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4843       sys::swapByteOrder(l);
4844 
4845     print_indent(indent);
4846     outs() << "      list[" << i << "] " << format("0x%08" PRIx32, l);
4847     if (print_protocol(l, indent, info))
4848       outs() << "(not in an __OBJC section)\n";
4849   }
4850   return false;
4851 }
4852 
4853 static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
4854   struct ivar_list64_t il;
4855   struct ivar64_t i;
4856   const char *r;
4857   uint32_t offset, xoffset, left, j;
4858   SectionRef S, xS;
4859   const char *name, *sym_name, *ivar_offset_p;
4860   uint64_t ivar_offset, n_value;
4861 
4862   r = get_pointer_64(p, offset, left, S, info);
4863   if (r == nullptr)
4864     return;
4865   memset(&il, '\0', sizeof(struct ivar_list64_t));
4866   if (left < sizeof(struct ivar_list64_t)) {
4867     memcpy(&il, r, left);
4868     outs() << "   (ivar_list_t entends past the end of the section)\n";
4869   } else
4870     memcpy(&il, r, sizeof(struct ivar_list64_t));
4871   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4872     swapStruct(il);
4873   outs() << "                    entsize " << il.entsize << "\n";
4874   outs() << "                      count " << il.count << "\n";
4875 
4876   p += sizeof(struct ivar_list64_t);
4877   offset += sizeof(struct ivar_list64_t);
4878   for (j = 0; j < il.count; j++) {
4879     r = get_pointer_64(p, offset, left, S, info);
4880     if (r == nullptr)
4881       return;
4882     memset(&i, '\0', sizeof(struct ivar64_t));
4883     if (left < sizeof(struct ivar64_t)) {
4884       memcpy(&i, r, left);
4885       outs() << "   (ivar_t entends past the end of the section)\n";
4886     } else
4887       memcpy(&i, r, sizeof(struct ivar64_t));
4888     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4889       swapStruct(i);
4890 
4891     outs() << "\t\t\t   offset ";
4892     sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
4893                              info, n_value, i.offset);
4894     if (n_value != 0) {
4895       if (info->verbose && sym_name != nullptr)
4896         outs() << sym_name;
4897       else
4898         outs() << format("0x%" PRIx64, n_value);
4899       if (i.offset != 0)
4900         outs() << " + " << format("0x%" PRIx64, i.offset);
4901     } else
4902       outs() << format("0x%" PRIx64, i.offset);
4903     ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
4904     if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4905       memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4906       if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4907         sys::swapByteOrder(ivar_offset);
4908       outs() << " " << ivar_offset << "\n";
4909     } else
4910       outs() << "\n";
4911 
4912     outs() << "\t\t\t     name ";
4913     sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
4914                              n_value, i.name);
4915     if (n_value != 0) {
4916       if (info->verbose && sym_name != nullptr)
4917         outs() << sym_name;
4918       else
4919         outs() << format("0x%" PRIx64, n_value);
4920       if (i.name != 0)
4921         outs() << " + " << format("0x%" PRIx64, i.name);
4922     } else
4923       outs() << format("0x%" PRIx64, i.name);
4924     name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
4925     if (name != nullptr)
4926       outs() << format(" %.*s", left, name);
4927     outs() << "\n";
4928 
4929     outs() << "\t\t\t     type ";
4930     sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
4931                              n_value, i.name);
4932     name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
4933     if (n_value != 0) {
4934       if (info->verbose && sym_name != nullptr)
4935         outs() << sym_name;
4936       else
4937         outs() << format("0x%" PRIx64, n_value);
4938       if (i.type != 0)
4939         outs() << " + " << format("0x%" PRIx64, i.type);
4940     } else
4941       outs() << format("0x%" PRIx64, i.type);
4942     if (name != nullptr)
4943       outs() << format(" %.*s", left, name);
4944     outs() << "\n";
4945 
4946     outs() << "\t\t\talignment " << i.alignment << "\n";
4947     outs() << "\t\t\t     size " << i.size << "\n";
4948 
4949     p += sizeof(struct ivar64_t);
4950     offset += sizeof(struct ivar64_t);
4951   }
4952 }
4953 
4954 static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4955   struct ivar_list32_t il;
4956   struct ivar32_t i;
4957   const char *r;
4958   uint32_t offset, xoffset, left, j;
4959   SectionRef S, xS;
4960   const char *name, *ivar_offset_p;
4961   uint32_t ivar_offset;
4962 
4963   r = get_pointer_32(p, offset, left, S, info);
4964   if (r == nullptr)
4965     return;
4966   memset(&il, '\0', sizeof(struct ivar_list32_t));
4967   if (left < sizeof(struct ivar_list32_t)) {
4968     memcpy(&il, r, left);
4969     outs() << "   (ivar_list_t entends past the end of the section)\n";
4970   } else
4971     memcpy(&il, r, sizeof(struct ivar_list32_t));
4972   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4973     swapStruct(il);
4974   outs() << "                    entsize " << il.entsize << "\n";
4975   outs() << "                      count " << il.count << "\n";
4976 
4977   p += sizeof(struct ivar_list32_t);
4978   offset += sizeof(struct ivar_list32_t);
4979   for (j = 0; j < il.count; j++) {
4980     r = get_pointer_32(p, offset, left, S, info);
4981     if (r == nullptr)
4982       return;
4983     memset(&i, '\0', sizeof(struct ivar32_t));
4984     if (left < sizeof(struct ivar32_t)) {
4985       memcpy(&i, r, left);
4986       outs() << "   (ivar_t entends past the end of the section)\n";
4987     } else
4988       memcpy(&i, r, sizeof(struct ivar32_t));
4989     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4990       swapStruct(i);
4991 
4992     outs() << "\t\t\t   offset " << format("0x%" PRIx32, i.offset);
4993     ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4994     if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4995       memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4996       if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4997         sys::swapByteOrder(ivar_offset);
4998       outs() << " " << ivar_offset << "\n";
4999     } else
5000       outs() << "\n";
5001 
5002     outs() << "\t\t\t     name " << format("0x%" PRIx32, i.name);
5003     name = get_pointer_32(i.name, xoffset, left, xS, info);
5004     if (name != nullptr)
5005       outs() << format(" %.*s", left, name);
5006     outs() << "\n";
5007 
5008     outs() << "\t\t\t     type " << format("0x%" PRIx32, i.type);
5009     name = get_pointer_32(i.type, xoffset, left, xS, info);
5010     if (name != nullptr)
5011       outs() << format(" %.*s", left, name);
5012     outs() << "\n";
5013 
5014     outs() << "\t\t\talignment " << i.alignment << "\n";
5015     outs() << "\t\t\t     size " << i.size << "\n";
5016 
5017     p += sizeof(struct ivar32_t);
5018     offset += sizeof(struct ivar32_t);
5019   }
5020 }
5021 
5022 static void print_objc_property_list64(uint64_t p,
5023                                        struct DisassembleInfo *info) {
5024   struct objc_property_list64 opl;
5025   struct objc_property64 op;
5026   const char *r;
5027   uint32_t offset, xoffset, left, j;
5028   SectionRef S, xS;
5029   const char *name, *sym_name;
5030   uint64_t n_value;
5031 
5032   r = get_pointer_64(p, offset, left, S, info);
5033   if (r == nullptr)
5034     return;
5035   memset(&opl, '\0', sizeof(struct objc_property_list64));
5036   if (left < sizeof(struct objc_property_list64)) {
5037     memcpy(&opl, r, left);
5038     outs() << "   (objc_property_list entends past the end of the section)\n";
5039   } else
5040     memcpy(&opl, r, sizeof(struct objc_property_list64));
5041   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5042     swapStruct(opl);
5043   outs() << "                    entsize " << opl.entsize << "\n";
5044   outs() << "                      count " << opl.count << "\n";
5045 
5046   p += sizeof(struct objc_property_list64);
5047   offset += sizeof(struct objc_property_list64);
5048   for (j = 0; j < opl.count; j++) {
5049     r = get_pointer_64(p, offset, left, S, info);
5050     if (r == nullptr)
5051       return;
5052     memset(&op, '\0', sizeof(struct objc_property64));
5053     if (left < sizeof(struct objc_property64)) {
5054       memcpy(&op, r, left);
5055       outs() << "   (objc_property entends past the end of the section)\n";
5056     } else
5057       memcpy(&op, r, sizeof(struct objc_property64));
5058     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5059       swapStruct(op);
5060 
5061     outs() << "\t\t\t     name ";
5062     sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
5063                              info, n_value, op.name);
5064     if (n_value != 0) {
5065       if (info->verbose && sym_name != nullptr)
5066         outs() << sym_name;
5067       else
5068         outs() << format("0x%" PRIx64, n_value);
5069       if (op.name != 0)
5070         outs() << " + " << format("0x%" PRIx64, op.name);
5071     } else
5072       outs() << format("0x%" PRIx64, op.name);
5073     name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
5074     if (name != nullptr)
5075       outs() << format(" %.*s", left, name);
5076     outs() << "\n";
5077 
5078     outs() << "\t\t\tattributes ";
5079     sym_name =
5080         get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
5081                       info, n_value, op.attributes);
5082     if (n_value != 0) {
5083       if (info->verbose && sym_name != nullptr)
5084         outs() << sym_name;
5085       else
5086         outs() << format("0x%" PRIx64, n_value);
5087       if (op.attributes != 0)
5088         outs() << " + " << format("0x%" PRIx64, op.attributes);
5089     } else
5090       outs() << format("0x%" PRIx64, op.attributes);
5091     name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
5092     if (name != nullptr)
5093       outs() << format(" %.*s", left, name);
5094     outs() << "\n";
5095 
5096     p += sizeof(struct objc_property64);
5097     offset += sizeof(struct objc_property64);
5098   }
5099 }
5100 
5101 static void print_objc_property_list32(uint32_t p,
5102                                        struct DisassembleInfo *info) {
5103   struct objc_property_list32 opl;
5104   struct objc_property32 op;
5105   const char *r;
5106   uint32_t offset, xoffset, left, j;
5107   SectionRef S, xS;
5108   const char *name;
5109 
5110   r = get_pointer_32(p, offset, left, S, info);
5111   if (r == nullptr)
5112     return;
5113   memset(&opl, '\0', sizeof(struct objc_property_list32));
5114   if (left < sizeof(struct objc_property_list32)) {
5115     memcpy(&opl, r, left);
5116     outs() << "   (objc_property_list entends past the end of the section)\n";
5117   } else
5118     memcpy(&opl, r, sizeof(struct objc_property_list32));
5119   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5120     swapStruct(opl);
5121   outs() << "                    entsize " << opl.entsize << "\n";
5122   outs() << "                      count " << opl.count << "\n";
5123 
5124   p += sizeof(struct objc_property_list32);
5125   offset += sizeof(struct objc_property_list32);
5126   for (j = 0; j < opl.count; j++) {
5127     r = get_pointer_32(p, offset, left, S, info);
5128     if (r == nullptr)
5129       return;
5130     memset(&op, '\0', sizeof(struct objc_property32));
5131     if (left < sizeof(struct objc_property32)) {
5132       memcpy(&op, r, left);
5133       outs() << "   (objc_property entends past the end of the section)\n";
5134     } else
5135       memcpy(&op, r, sizeof(struct objc_property32));
5136     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5137       swapStruct(op);
5138 
5139     outs() << "\t\t\t     name " << format("0x%" PRIx32, op.name);
5140     name = get_pointer_32(op.name, xoffset, left, xS, info);
5141     if (name != nullptr)
5142       outs() << format(" %.*s", left, name);
5143     outs() << "\n";
5144 
5145     outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
5146     name = get_pointer_32(op.attributes, xoffset, left, xS, info);
5147     if (name != nullptr)
5148       outs() << format(" %.*s", left, name);
5149     outs() << "\n";
5150 
5151     p += sizeof(struct objc_property32);
5152     offset += sizeof(struct objc_property32);
5153   }
5154 }
5155 
5156 static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
5157                                bool &is_meta_class) {
5158   struct class_ro64_t cro;
5159   const char *r;
5160   uint32_t offset, xoffset, left;
5161   SectionRef S, xS;
5162   const char *name, *sym_name;
5163   uint64_t n_value;
5164 
5165   r = get_pointer_64(p, offset, left, S, info);
5166   if (r == nullptr || left < sizeof(struct class_ro64_t))
5167     return false;
5168   memcpy(&cro, r, sizeof(struct class_ro64_t));
5169   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5170     swapStruct(cro);
5171   outs() << "                    flags " << format("0x%" PRIx32, cro.flags);
5172   if (cro.flags & RO_META)
5173     outs() << " RO_META";
5174   if (cro.flags & RO_ROOT)
5175     outs() << " RO_ROOT";
5176   if (cro.flags & RO_HAS_CXX_STRUCTORS)
5177     outs() << " RO_HAS_CXX_STRUCTORS";
5178   outs() << "\n";
5179   outs() << "            instanceStart " << cro.instanceStart << "\n";
5180   outs() << "             instanceSize " << cro.instanceSize << "\n";
5181   outs() << "                 reserved " << format("0x%" PRIx32, cro.reserved)
5182          << "\n";
5183   outs() << "               ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
5184          << "\n";
5185   print_layout_map64(cro.ivarLayout, info);
5186 
5187   outs() << "                     name ";
5188   sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
5189                            info, n_value, cro.name);
5190   if (n_value != 0) {
5191     if (info->verbose && sym_name != nullptr)
5192       outs() << sym_name;
5193     else
5194       outs() << format("0x%" PRIx64, n_value);
5195     if (cro.name != 0)
5196       outs() << " + " << format("0x%" PRIx64, cro.name);
5197   } else
5198     outs() << format("0x%" PRIx64, cro.name);
5199   name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
5200   if (name != nullptr)
5201     outs() << format(" %.*s", left, name);
5202   outs() << "\n";
5203 
5204   outs() << "              baseMethods ";
5205   sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
5206                            S, info, n_value, cro.baseMethods);
5207   if (n_value != 0) {
5208     if (info->verbose && sym_name != nullptr)
5209       outs() << sym_name;
5210     else
5211       outs() << format("0x%" PRIx64, n_value);
5212     if (cro.baseMethods != 0)
5213       outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
5214   } else
5215     outs() << format("0x%" PRIx64, cro.baseMethods);
5216   outs() << " (struct method_list_t *)\n";
5217   if (cro.baseMethods + n_value != 0)
5218     print_method_list64_t(cro.baseMethods + n_value, info, "");
5219 
5220   outs() << "            baseProtocols ";
5221   sym_name =
5222       get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
5223                     info, n_value, cro.baseProtocols);
5224   if (n_value != 0) {
5225     if (info->verbose && sym_name != nullptr)
5226       outs() << sym_name;
5227     else
5228       outs() << format("0x%" PRIx64, n_value);
5229     if (cro.baseProtocols != 0)
5230       outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
5231   } else
5232     outs() << format("0x%" PRIx64, cro.baseProtocols);
5233   outs() << "\n";
5234   if (cro.baseProtocols + n_value != 0)
5235     print_protocol_list64_t(cro.baseProtocols + n_value, info);
5236 
5237   outs() << "                    ivars ";
5238   sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
5239                            info, n_value, cro.ivars);
5240   if (n_value != 0) {
5241     if (info->verbose && sym_name != nullptr)
5242       outs() << sym_name;
5243     else
5244       outs() << format("0x%" PRIx64, n_value);
5245     if (cro.ivars != 0)
5246       outs() << " + " << format("0x%" PRIx64, cro.ivars);
5247   } else
5248     outs() << format("0x%" PRIx64, cro.ivars);
5249   outs() << "\n";
5250   if (cro.ivars + n_value != 0)
5251     print_ivar_list64_t(cro.ivars + n_value, info);
5252 
5253   outs() << "           weakIvarLayout ";
5254   sym_name =
5255       get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
5256                     info, n_value, cro.weakIvarLayout);
5257   if (n_value != 0) {
5258     if (info->verbose && sym_name != nullptr)
5259       outs() << sym_name;
5260     else
5261       outs() << format("0x%" PRIx64, n_value);
5262     if (cro.weakIvarLayout != 0)
5263       outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
5264   } else
5265     outs() << format("0x%" PRIx64, cro.weakIvarLayout);
5266   outs() << "\n";
5267   print_layout_map64(cro.weakIvarLayout + n_value, info);
5268 
5269   outs() << "           baseProperties ";
5270   sym_name =
5271       get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
5272                     info, n_value, cro.baseProperties);
5273   if (n_value != 0) {
5274     if (info->verbose && sym_name != nullptr)
5275       outs() << sym_name;
5276     else
5277       outs() << format("0x%" PRIx64, n_value);
5278     if (cro.baseProperties != 0)
5279       outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
5280   } else
5281     outs() << format("0x%" PRIx64, cro.baseProperties);
5282   outs() << "\n";
5283   if (cro.baseProperties + n_value != 0)
5284     print_objc_property_list64(cro.baseProperties + n_value, info);
5285 
5286   is_meta_class = (cro.flags & RO_META) != 0;
5287   return true;
5288 }
5289 
5290 static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
5291                                bool &is_meta_class) {
5292   struct class_ro32_t cro;
5293   const char *r;
5294   uint32_t offset, xoffset, left;
5295   SectionRef S, xS;
5296   const char *name;
5297 
5298   r = get_pointer_32(p, offset, left, S, info);
5299   if (r == nullptr)
5300     return false;
5301   memset(&cro, '\0', sizeof(struct class_ro32_t));
5302   if (left < sizeof(struct class_ro32_t)) {
5303     memcpy(&cro, r, left);
5304     outs() << "   (class_ro_t entends past the end of the section)\n";
5305   } else
5306     memcpy(&cro, r, sizeof(struct class_ro32_t));
5307   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5308     swapStruct(cro);
5309   outs() << "                    flags " << format("0x%" PRIx32, cro.flags);
5310   if (cro.flags & RO_META)
5311     outs() << " RO_META";
5312   if (cro.flags & RO_ROOT)
5313     outs() << " RO_ROOT";
5314   if (cro.flags & RO_HAS_CXX_STRUCTORS)
5315     outs() << " RO_HAS_CXX_STRUCTORS";
5316   outs() << "\n";
5317   outs() << "            instanceStart " << cro.instanceStart << "\n";
5318   outs() << "             instanceSize " << cro.instanceSize << "\n";
5319   outs() << "               ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
5320          << "\n";
5321   print_layout_map32(cro.ivarLayout, info);
5322 
5323   outs() << "                     name " << format("0x%" PRIx32, cro.name);
5324   name = get_pointer_32(cro.name, xoffset, left, xS, info);
5325   if (name != nullptr)
5326     outs() << format(" %.*s", left, name);
5327   outs() << "\n";
5328 
5329   outs() << "              baseMethods "
5330          << format("0x%" PRIx32, cro.baseMethods)
5331          << " (struct method_list_t *)\n";
5332   if (cro.baseMethods != 0)
5333     print_method_list32_t(cro.baseMethods, info, "");
5334 
5335   outs() << "            baseProtocols "
5336          << format("0x%" PRIx32, cro.baseProtocols) << "\n";
5337   if (cro.baseProtocols != 0)
5338     print_protocol_list32_t(cro.baseProtocols, info);
5339   outs() << "                    ivars " << format("0x%" PRIx32, cro.ivars)
5340          << "\n";
5341   if (cro.ivars != 0)
5342     print_ivar_list32_t(cro.ivars, info);
5343   outs() << "           weakIvarLayout "
5344          << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
5345   print_layout_map32(cro.weakIvarLayout, info);
5346   outs() << "           baseProperties "
5347          << format("0x%" PRIx32, cro.baseProperties) << "\n";
5348   if (cro.baseProperties != 0)
5349     print_objc_property_list32(cro.baseProperties, info);
5350   is_meta_class = (cro.flags & RO_META) != 0;
5351   return true;
5352 }
5353 
5354 static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
5355   struct class64_t c;
5356   const char *r;
5357   uint32_t offset, left;
5358   SectionRef S;
5359   const char *name;
5360   uint64_t isa_n_value, n_value;
5361 
5362   r = get_pointer_64(p, offset, left, S, info);
5363   if (r == nullptr || left < sizeof(struct class64_t))
5364     return;
5365   memcpy(&c, r, sizeof(struct class64_t));
5366   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5367     swapStruct(c);
5368 
5369   outs() << "           isa " << format("0x%" PRIx64, c.isa);
5370   name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
5371                        isa_n_value, c.isa);
5372   if (name != nullptr)
5373     outs() << " " << name;
5374   outs() << "\n";
5375 
5376   outs() << "    superclass " << format("0x%" PRIx64, c.superclass);
5377   name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
5378                        n_value, c.superclass);
5379   if (name != nullptr)
5380     outs() << " " << name;
5381   else {
5382     name = get_dyld_bind_info_symbolname(S.getAddress() +
5383              offset + offsetof(struct class64_t, superclass), info);
5384     if (name != nullptr)
5385       outs() << " " << name;
5386   }
5387   outs() << "\n";
5388 
5389   outs() << "         cache " << format("0x%" PRIx64, c.cache);
5390   name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
5391                        n_value, c.cache);
5392   if (name != nullptr)
5393     outs() << " " << name;
5394   outs() << "\n";
5395 
5396   outs() << "        vtable " << format("0x%" PRIx64, c.vtable);
5397   name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
5398                        n_value, c.vtable);
5399   if (name != nullptr)
5400     outs() << " " << name;
5401   outs() << "\n";
5402 
5403   name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
5404                        n_value, c.data);
5405   outs() << "          data ";
5406   if (n_value != 0) {
5407     if (info->verbose && name != nullptr)
5408       outs() << name;
5409     else
5410       outs() << format("0x%" PRIx64, n_value);
5411     if (c.data != 0)
5412       outs() << " + " << format("0x%" PRIx64, c.data);
5413   } else
5414     outs() << format("0x%" PRIx64, c.data);
5415   outs() << " (struct class_ro_t *)";
5416 
5417   // This is a Swift class if some of the low bits of the pointer are set.
5418   if ((c.data + n_value) & 0x7)
5419     outs() << " Swift class";
5420   outs() << "\n";
5421   bool is_meta_class;
5422   if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
5423     return;
5424 
5425   if (!is_meta_class &&
5426       c.isa + isa_n_value != p &&
5427       c.isa + isa_n_value != 0 &&
5428       info->depth < 100) {
5429       info->depth++;
5430       outs() << "Meta Class\n";
5431       print_class64_t(c.isa + isa_n_value, info);
5432   }
5433 }
5434 
5435 static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
5436   struct class32_t c;
5437   const char *r;
5438   uint32_t offset, left;
5439   SectionRef S;
5440   const char *name;
5441 
5442   r = get_pointer_32(p, offset, left, S, info);
5443   if (r == nullptr)
5444     return;
5445   memset(&c, '\0', sizeof(struct class32_t));
5446   if (left < sizeof(struct class32_t)) {
5447     memcpy(&c, r, left);
5448     outs() << "   (class_t entends past the end of the section)\n";
5449   } else
5450     memcpy(&c, r, sizeof(struct class32_t));
5451   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5452     swapStruct(c);
5453 
5454   outs() << "           isa " << format("0x%" PRIx32, c.isa);
5455   name =
5456       get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
5457   if (name != nullptr)
5458     outs() << " " << name;
5459   outs() << "\n";
5460 
5461   outs() << "    superclass " << format("0x%" PRIx32, c.superclass);
5462   name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
5463                        c.superclass);
5464   if (name != nullptr)
5465     outs() << " " << name;
5466   outs() << "\n";
5467 
5468   outs() << "         cache " << format("0x%" PRIx32, c.cache);
5469   name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
5470                        c.cache);
5471   if (name != nullptr)
5472     outs() << " " << name;
5473   outs() << "\n";
5474 
5475   outs() << "        vtable " << format("0x%" PRIx32, c.vtable);
5476   name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
5477                        c.vtable);
5478   if (name != nullptr)
5479     outs() << " " << name;
5480   outs() << "\n";
5481 
5482   name =
5483       get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
5484   outs() << "          data " << format("0x%" PRIx32, c.data)
5485          << " (struct class_ro_t *)";
5486 
5487   // This is a Swift class if some of the low bits of the pointer are set.
5488   if (c.data & 0x3)
5489     outs() << " Swift class";
5490   outs() << "\n";
5491   bool is_meta_class;
5492   if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
5493     return;
5494 
5495   if (!is_meta_class) {
5496     outs() << "Meta Class\n";
5497     print_class32_t(c.isa, info);
5498   }
5499 }
5500 
5501 static void print_objc_class_t(struct objc_class_t *objc_class,
5502                                struct DisassembleInfo *info) {
5503   uint32_t offset, left, xleft;
5504   const char *name, *p, *ivar_list;
5505   SectionRef S;
5506   int32_t i;
5507   struct objc_ivar_list_t objc_ivar_list;
5508   struct objc_ivar_t ivar;
5509 
5510   outs() << "\t\t      isa " << format("0x%08" PRIx32, objc_class->isa);
5511   if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
5512     name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
5513     if (name != nullptr)
5514       outs() << format(" %.*s", left, name);
5515     else
5516       outs() << " (not in an __OBJC section)";
5517   }
5518   outs() << "\n";
5519 
5520   outs() << "\t      super_class "
5521          << format("0x%08" PRIx32, objc_class->super_class);
5522   if (info->verbose) {
5523     name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
5524     if (name != nullptr)
5525       outs() << format(" %.*s", left, name);
5526     else
5527       outs() << " (not in an __OBJC section)";
5528   }
5529   outs() << "\n";
5530 
5531   outs() << "\t\t     name " << format("0x%08" PRIx32, objc_class->name);
5532   if (info->verbose) {
5533     name = get_pointer_32(objc_class->name, offset, left, S, info, true);
5534     if (name != nullptr)
5535       outs() << format(" %.*s", left, name);
5536     else
5537       outs() << " (not in an __OBJC section)";
5538   }
5539   outs() << "\n";
5540 
5541   outs() << "\t\t  version " << format("0x%08" PRIx32, objc_class->version)
5542          << "\n";
5543 
5544   outs() << "\t\t     info " << format("0x%08" PRIx32, objc_class->info);
5545   if (info->verbose) {
5546     if (CLS_GETINFO(objc_class, CLS_CLASS))
5547       outs() << " CLS_CLASS";
5548     else if (CLS_GETINFO(objc_class, CLS_META))
5549       outs() << " CLS_META";
5550   }
5551   outs() << "\n";
5552 
5553   outs() << "\t    instance_size "
5554          << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
5555 
5556   p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
5557   outs() << "\t\t    ivars " << format("0x%08" PRIx32, objc_class->ivars);
5558   if (p != nullptr) {
5559     if (left > sizeof(struct objc_ivar_list_t)) {
5560       outs() << "\n";
5561       memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
5562     } else {
5563       outs() << " (entends past the end of the section)\n";
5564       memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
5565       memcpy(&objc_ivar_list, p, left);
5566     }
5567     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5568       swapStruct(objc_ivar_list);
5569     outs() << "\t\t       ivar_count " << objc_ivar_list.ivar_count << "\n";
5570     ivar_list = p + sizeof(struct objc_ivar_list_t);
5571     for (i = 0; i < objc_ivar_list.ivar_count; i++) {
5572       if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
5573         outs() << "\t\t remaining ivar's extend past the of the section\n";
5574         break;
5575       }
5576       memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
5577              sizeof(struct objc_ivar_t));
5578       if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5579         swapStruct(ivar);
5580 
5581       outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
5582       if (info->verbose) {
5583         name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
5584         if (name != nullptr)
5585           outs() << format(" %.*s", xleft, name);
5586         else
5587           outs() << " (not in an __OBJC section)";
5588       }
5589       outs() << "\n";
5590 
5591       outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
5592       if (info->verbose) {
5593         name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
5594         if (name != nullptr)
5595           outs() << format(" %.*s", xleft, name);
5596         else
5597           outs() << " (not in an __OBJC section)";
5598       }
5599       outs() << "\n";
5600 
5601       outs() << "\t\t      ivar_offset "
5602              << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
5603     }
5604   } else {
5605     outs() << " (not in an __OBJC section)\n";
5606   }
5607 
5608   outs() << "\t\t  methods " << format("0x%08" PRIx32, objc_class->methodLists);
5609   if (print_method_list(objc_class->methodLists, info))
5610     outs() << " (not in an __OBJC section)\n";
5611 
5612   outs() << "\t\t    cache " << format("0x%08" PRIx32, objc_class->cache)
5613          << "\n";
5614 
5615   outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
5616   if (print_protocol_list(objc_class->protocols, 16, info))
5617     outs() << " (not in an __OBJC section)\n";
5618 }
5619 
5620 static void print_objc_objc_category_t(struct objc_category_t *objc_category,
5621                                        struct DisassembleInfo *info) {
5622   uint32_t offset, left;
5623   const char *name;
5624   SectionRef S;
5625 
5626   outs() << "\t       category name "
5627          << format("0x%08" PRIx32, objc_category->category_name);
5628   if (info->verbose) {
5629     name = get_pointer_32(objc_category->category_name, offset, left, S, info,
5630                           true);
5631     if (name != nullptr)
5632       outs() << format(" %.*s", left, name);
5633     else
5634       outs() << " (not in an __OBJC section)";
5635   }
5636   outs() << "\n";
5637 
5638   outs() << "\t\t  class name "
5639          << format("0x%08" PRIx32, objc_category->class_name);
5640   if (info->verbose) {
5641     name =
5642         get_pointer_32(objc_category->class_name, offset, left, S, info, true);
5643     if (name != nullptr)
5644       outs() << format(" %.*s", left, name);
5645     else
5646       outs() << " (not in an __OBJC section)";
5647   }
5648   outs() << "\n";
5649 
5650   outs() << "\t    instance methods "
5651          << format("0x%08" PRIx32, objc_category->instance_methods);
5652   if (print_method_list(objc_category->instance_methods, info))
5653     outs() << " (not in an __OBJC section)\n";
5654 
5655   outs() << "\t       class methods "
5656          << format("0x%08" PRIx32, objc_category->class_methods);
5657   if (print_method_list(objc_category->class_methods, info))
5658     outs() << " (not in an __OBJC section)\n";
5659 }
5660 
5661 static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
5662   struct category64_t c;
5663   const char *r;
5664   uint32_t offset, xoffset, left;
5665   SectionRef S, xS;
5666   const char *name, *sym_name;
5667   uint64_t n_value;
5668 
5669   r = get_pointer_64(p, offset, left, S, info);
5670   if (r == nullptr)
5671     return;
5672   memset(&c, '\0', sizeof(struct category64_t));
5673   if (left < sizeof(struct category64_t)) {
5674     memcpy(&c, r, left);
5675     outs() << "   (category_t entends past the end of the section)\n";
5676   } else
5677     memcpy(&c, r, sizeof(struct category64_t));
5678   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5679     swapStruct(c);
5680 
5681   outs() << "              name ";
5682   sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
5683                            info, n_value, c.name);
5684   if (n_value != 0) {
5685     if (info->verbose && sym_name != nullptr)
5686       outs() << sym_name;
5687     else
5688       outs() << format("0x%" PRIx64, n_value);
5689     if (c.name != 0)
5690       outs() << " + " << format("0x%" PRIx64, c.name);
5691   } else
5692     outs() << format("0x%" PRIx64, c.name);
5693   name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
5694   if (name != nullptr)
5695     outs() << format(" %.*s", left, name);
5696   outs() << "\n";
5697 
5698   outs() << "               cls ";
5699   sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
5700                            n_value, c.cls);
5701   if (n_value != 0) {
5702     if (info->verbose && sym_name != nullptr)
5703       outs() << sym_name;
5704     else
5705       outs() << format("0x%" PRIx64, n_value);
5706     if (c.cls != 0)
5707       outs() << " + " << format("0x%" PRIx64, c.cls);
5708   } else
5709     outs() << format("0x%" PRIx64, c.cls);
5710   outs() << "\n";
5711   if (c.cls + n_value != 0)
5712     print_class64_t(c.cls + n_value, info);
5713 
5714   outs() << "   instanceMethods ";
5715   sym_name =
5716       get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
5717                     info, n_value, c.instanceMethods);
5718   if (n_value != 0) {
5719     if (info->verbose && sym_name != nullptr)
5720       outs() << sym_name;
5721     else
5722       outs() << format("0x%" PRIx64, n_value);
5723     if (c.instanceMethods != 0)
5724       outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
5725   } else
5726     outs() << format("0x%" PRIx64, c.instanceMethods);
5727   outs() << "\n";
5728   if (c.instanceMethods + n_value != 0)
5729     print_method_list64_t(c.instanceMethods + n_value, info, "");
5730 
5731   outs() << "      classMethods ";
5732   sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
5733                            S, info, n_value, c.classMethods);
5734   if (n_value != 0) {
5735     if (info->verbose && sym_name != nullptr)
5736       outs() << sym_name;
5737     else
5738       outs() << format("0x%" PRIx64, n_value);
5739     if (c.classMethods != 0)
5740       outs() << " + " << format("0x%" PRIx64, c.classMethods);
5741   } else
5742     outs() << format("0x%" PRIx64, c.classMethods);
5743   outs() << "\n";
5744   if (c.classMethods + n_value != 0)
5745     print_method_list64_t(c.classMethods + n_value, info, "");
5746 
5747   outs() << "         protocols ";
5748   sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
5749                            info, n_value, c.protocols);
5750   if (n_value != 0) {
5751     if (info->verbose && sym_name != nullptr)
5752       outs() << sym_name;
5753     else
5754       outs() << format("0x%" PRIx64, n_value);
5755     if (c.protocols != 0)
5756       outs() << " + " << format("0x%" PRIx64, c.protocols);
5757   } else
5758     outs() << format("0x%" PRIx64, c.protocols);
5759   outs() << "\n";
5760   if (c.protocols + n_value != 0)
5761     print_protocol_list64_t(c.protocols + n_value, info);
5762 
5763   outs() << "instanceProperties ";
5764   sym_name =
5765       get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
5766                     S, info, n_value, c.instanceProperties);
5767   if (n_value != 0) {
5768     if (info->verbose && sym_name != nullptr)
5769       outs() << sym_name;
5770     else
5771       outs() << format("0x%" PRIx64, n_value);
5772     if (c.instanceProperties != 0)
5773       outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
5774   } else
5775     outs() << format("0x%" PRIx64, c.instanceProperties);
5776   outs() << "\n";
5777   if (c.instanceProperties + n_value != 0)
5778     print_objc_property_list64(c.instanceProperties + n_value, info);
5779 }
5780 
5781 static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
5782   struct category32_t c;
5783   const char *r;
5784   uint32_t offset, left;
5785   SectionRef S, xS;
5786   const char *name;
5787 
5788   r = get_pointer_32(p, offset, left, S, info);
5789   if (r == nullptr)
5790     return;
5791   memset(&c, '\0', sizeof(struct category32_t));
5792   if (left < sizeof(struct category32_t)) {
5793     memcpy(&c, r, left);
5794     outs() << "   (category_t entends past the end of the section)\n";
5795   } else
5796     memcpy(&c, r, sizeof(struct category32_t));
5797   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5798     swapStruct(c);
5799 
5800   outs() << "              name " << format("0x%" PRIx32, c.name);
5801   name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
5802                        c.name);
5803   if (name)
5804     outs() << " " << name;
5805   outs() << "\n";
5806 
5807   outs() << "               cls " << format("0x%" PRIx32, c.cls) << "\n";
5808   if (c.cls != 0)
5809     print_class32_t(c.cls, info);
5810   outs() << "   instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
5811          << "\n";
5812   if (c.instanceMethods != 0)
5813     print_method_list32_t(c.instanceMethods, info, "");
5814   outs() << "      classMethods " << format("0x%" PRIx32, c.classMethods)
5815          << "\n";
5816   if (c.classMethods != 0)
5817     print_method_list32_t(c.classMethods, info, "");
5818   outs() << "         protocols " << format("0x%" PRIx32, c.protocols) << "\n";
5819   if (c.protocols != 0)
5820     print_protocol_list32_t(c.protocols, info);
5821   outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
5822          << "\n";
5823   if (c.instanceProperties != 0)
5824     print_objc_property_list32(c.instanceProperties, info);
5825 }
5826 
5827 static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
5828   uint32_t i, left, offset, xoffset;
5829   uint64_t p, n_value;
5830   struct message_ref64 mr;
5831   const char *name, *sym_name;
5832   const char *r;
5833   SectionRef xS;
5834 
5835   if (S == SectionRef())
5836     return;
5837 
5838   StringRef SectName;
5839   Expected<StringRef> SecNameOrErr = S.getName();
5840   if (SecNameOrErr)
5841     SectName = *SecNameOrErr;
5842   else
5843     consumeError(SecNameOrErr.takeError());
5844 
5845   DataRefImpl Ref = S.getRawDataRefImpl();
5846   StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5847   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5848   offset = 0;
5849   for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5850     p = S.getAddress() + i;
5851     r = get_pointer_64(p, offset, left, S, info);
5852     if (r == nullptr)
5853       return;
5854     memset(&mr, '\0', sizeof(struct message_ref64));
5855     if (left < sizeof(struct message_ref64)) {
5856       memcpy(&mr, r, left);
5857       outs() << "   (message_ref entends past the end of the section)\n";
5858     } else
5859       memcpy(&mr, r, sizeof(struct message_ref64));
5860     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5861       swapStruct(mr);
5862 
5863     outs() << "  imp ";
5864     name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
5865                          n_value, mr.imp);
5866     if (n_value != 0) {
5867       outs() << format("0x%" PRIx64, n_value) << " ";
5868       if (mr.imp != 0)
5869         outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
5870     } else
5871       outs() << format("0x%" PRIx64, mr.imp) << " ";
5872     if (name != nullptr)
5873       outs() << " " << name;
5874     outs() << "\n";
5875 
5876     outs() << "  sel ";
5877     sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
5878                              info, n_value, mr.sel);
5879     if (n_value != 0) {
5880       if (info->verbose && sym_name != nullptr)
5881         outs() << sym_name;
5882       else
5883         outs() << format("0x%" PRIx64, n_value);
5884       if (mr.sel != 0)
5885         outs() << " + " << format("0x%" PRIx64, mr.sel);
5886     } else
5887       outs() << format("0x%" PRIx64, mr.sel);
5888     name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
5889     if (name != nullptr)
5890       outs() << format(" %.*s", left, name);
5891     outs() << "\n";
5892 
5893     offset += sizeof(struct message_ref64);
5894   }
5895 }
5896 
5897 static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
5898   uint32_t i, left, offset, xoffset, p;
5899   struct message_ref32 mr;
5900   const char *name, *r;
5901   SectionRef xS;
5902 
5903   if (S == SectionRef())
5904     return;
5905 
5906   StringRef SectName;
5907   Expected<StringRef> SecNameOrErr = S.getName();
5908   if (SecNameOrErr)
5909     SectName = *SecNameOrErr;
5910   else
5911     consumeError(SecNameOrErr.takeError());
5912 
5913   DataRefImpl Ref = S.getRawDataRefImpl();
5914   StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5915   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5916   offset = 0;
5917   for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5918     p = S.getAddress() + i;
5919     r = get_pointer_32(p, offset, left, S, info);
5920     if (r == nullptr)
5921       return;
5922     memset(&mr, '\0', sizeof(struct message_ref32));
5923     if (left < sizeof(struct message_ref32)) {
5924       memcpy(&mr, r, left);
5925       outs() << "   (message_ref entends past the end of the section)\n";
5926     } else
5927       memcpy(&mr, r, sizeof(struct message_ref32));
5928     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5929       swapStruct(mr);
5930 
5931     outs() << "  imp " << format("0x%" PRIx32, mr.imp);
5932     name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
5933                          mr.imp);
5934     if (name != nullptr)
5935       outs() << " " << name;
5936     outs() << "\n";
5937 
5938     outs() << "  sel " << format("0x%" PRIx32, mr.sel);
5939     name = get_pointer_32(mr.sel, xoffset, left, xS, info);
5940     if (name != nullptr)
5941       outs() << " " << name;
5942     outs() << "\n";
5943 
5944     offset += sizeof(struct message_ref32);
5945   }
5946 }
5947 
5948 static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
5949   uint32_t left, offset, swift_version;
5950   uint64_t p;
5951   struct objc_image_info64 o;
5952   const char *r;
5953 
5954   if (S == SectionRef())
5955     return;
5956 
5957   StringRef SectName;
5958   Expected<StringRef> SecNameOrErr = S.getName();
5959   if (SecNameOrErr)
5960     SectName = *SecNameOrErr;
5961   else
5962     consumeError(SecNameOrErr.takeError());
5963 
5964   DataRefImpl Ref = S.getRawDataRefImpl();
5965   StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5966   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5967   p = S.getAddress();
5968   r = get_pointer_64(p, offset, left, S, info);
5969   if (r == nullptr)
5970     return;
5971   memset(&o, '\0', sizeof(struct objc_image_info64));
5972   if (left < sizeof(struct objc_image_info64)) {
5973     memcpy(&o, r, left);
5974     outs() << "   (objc_image_info entends past the end of the section)\n";
5975   } else
5976     memcpy(&o, r, sizeof(struct objc_image_info64));
5977   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5978     swapStruct(o);
5979   outs() << "  version " << o.version << "\n";
5980   outs() << "    flags " << format("0x%" PRIx32, o.flags);
5981   if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5982     outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5983   if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5984     outs() << " OBJC_IMAGE_SUPPORTS_GC";
5985   if (o.flags & OBJC_IMAGE_IS_SIMULATED)
5986     outs() << " OBJC_IMAGE_IS_SIMULATED";
5987   if (o.flags & OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES)
5988     outs() << " OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES";
5989   swift_version = (o.flags >> 8) & 0xff;
5990   if (swift_version != 0) {
5991     if (swift_version == 1)
5992       outs() << " Swift 1.0";
5993     else if (swift_version == 2)
5994       outs() << " Swift 1.1";
5995     else if(swift_version == 3)
5996       outs() << " Swift 2.0";
5997     else if(swift_version == 4)
5998       outs() << " Swift 3.0";
5999     else if(swift_version == 5)
6000       outs() << " Swift 4.0";
6001     else if(swift_version == 6)
6002       outs() << " Swift 4.1/Swift 4.2";
6003     else if(swift_version == 7)
6004       outs() << " Swift 5 or later";
6005     else
6006       outs() << " unknown future Swift version (" << swift_version << ")";
6007   }
6008   outs() << "\n";
6009 }
6010 
6011 static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
6012   uint32_t left, offset, swift_version, p;
6013   struct objc_image_info32 o;
6014   const char *r;
6015 
6016   if (S == SectionRef())
6017     return;
6018 
6019   StringRef SectName;
6020   Expected<StringRef> SecNameOrErr = S.getName();
6021   if (SecNameOrErr)
6022     SectName = *SecNameOrErr;
6023   else
6024     consumeError(SecNameOrErr.takeError());
6025 
6026   DataRefImpl Ref = S.getRawDataRefImpl();
6027   StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
6028   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
6029   p = S.getAddress();
6030   r = get_pointer_32(p, offset, left, S, info);
6031   if (r == nullptr)
6032     return;
6033   memset(&o, '\0', sizeof(struct objc_image_info32));
6034   if (left < sizeof(struct objc_image_info32)) {
6035     memcpy(&o, r, left);
6036     outs() << "   (objc_image_info entends past the end of the section)\n";
6037   } else
6038     memcpy(&o, r, sizeof(struct objc_image_info32));
6039   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
6040     swapStruct(o);
6041   outs() << "  version " << o.version << "\n";
6042   outs() << "    flags " << format("0x%" PRIx32, o.flags);
6043   if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
6044     outs() << " OBJC_IMAGE_IS_REPLACEMENT";
6045   if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
6046     outs() << " OBJC_IMAGE_SUPPORTS_GC";
6047   swift_version = (o.flags >> 8) & 0xff;
6048   if (swift_version != 0) {
6049     if (swift_version == 1)
6050       outs() << " Swift 1.0";
6051     else if (swift_version == 2)
6052       outs() << " Swift 1.1";
6053     else if(swift_version == 3)
6054       outs() << " Swift 2.0";
6055     else if(swift_version == 4)
6056       outs() << " Swift 3.0";
6057     else if(swift_version == 5)
6058       outs() << " Swift 4.0";
6059     else if(swift_version == 6)
6060       outs() << " Swift 4.1/Swift 4.2";
6061     else if(swift_version == 7)
6062       outs() << " Swift 5 or later";
6063     else
6064       outs() << " unknown future Swift version (" << swift_version << ")";
6065   }
6066   outs() << "\n";
6067 }
6068 
6069 static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
6070   uint32_t left, offset, p;
6071   struct imageInfo_t o;
6072   const char *r;
6073 
6074   StringRef SectName;
6075   Expected<StringRef> SecNameOrErr = S.getName();
6076   if (SecNameOrErr)
6077     SectName = *SecNameOrErr;
6078   else
6079     consumeError(SecNameOrErr.takeError());
6080 
6081   DataRefImpl Ref = S.getRawDataRefImpl();
6082   StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
6083   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
6084   p = S.getAddress();
6085   r = get_pointer_32(p, offset, left, S, info);
6086   if (r == nullptr)
6087     return;
6088   memset(&o, '\0', sizeof(struct imageInfo_t));
6089   if (left < sizeof(struct imageInfo_t)) {
6090     memcpy(&o, r, left);
6091     outs() << " (imageInfo entends past the end of the section)\n";
6092   } else
6093     memcpy(&o, r, sizeof(struct imageInfo_t));
6094   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
6095     swapStruct(o);
6096   outs() << "  version " << o.version << "\n";
6097   outs() << "    flags " << format("0x%" PRIx32, o.flags);
6098   if (o.flags & 0x1)
6099     outs() << "  F&C";
6100   if (o.flags & 0x2)
6101     outs() << " GC";
6102   if (o.flags & 0x4)
6103     outs() << " GC-only";
6104   else
6105     outs() << " RR";
6106   outs() << "\n";
6107 }
6108 
6109 static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
6110   SymbolAddressMap AddrMap;
6111   if (verbose)
6112     CreateSymbolAddressMap(O, &AddrMap);
6113 
6114   std::vector<SectionRef> Sections;
6115   for (const SectionRef &Section : O->sections())
6116     Sections.push_back(Section);
6117 
6118   struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
6119 
6120   SectionRef CL = get_section(O, "__OBJC2", "__class_list");
6121   if (CL == SectionRef())
6122     CL = get_section(O, "__DATA", "__objc_classlist");
6123   if (CL == SectionRef())
6124     CL = get_section(O, "__DATA_CONST", "__objc_classlist");
6125   if (CL == SectionRef())
6126     CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
6127   info.S = CL;
6128   walk_pointer_list_64("class", CL, O, &info, print_class64_t);
6129 
6130   SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
6131   if (CR == SectionRef())
6132     CR = get_section(O, "__DATA", "__objc_classrefs");
6133   if (CR == SectionRef())
6134     CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
6135   if (CR == SectionRef())
6136     CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
6137   info.S = CR;
6138   walk_pointer_list_64("class refs", CR, O, &info, nullptr);
6139 
6140   SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
6141   if (SR == SectionRef())
6142     SR = get_section(O, "__DATA", "__objc_superrefs");
6143   if (SR == SectionRef())
6144     SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
6145   if (SR == SectionRef())
6146     SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
6147   info.S = SR;
6148   walk_pointer_list_64("super refs", SR, O, &info, nullptr);
6149 
6150   SectionRef CA = get_section(O, "__OBJC2", "__category_list");
6151   if (CA == SectionRef())
6152     CA = get_section(O, "__DATA", "__objc_catlist");
6153   if (CA == SectionRef())
6154     CA = get_section(O, "__DATA_CONST", "__objc_catlist");
6155   if (CA == SectionRef())
6156     CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
6157   info.S = CA;
6158   walk_pointer_list_64("category", CA, O, &info, print_category64_t);
6159 
6160   SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
6161   if (PL == SectionRef())
6162     PL = get_section(O, "__DATA", "__objc_protolist");
6163   if (PL == SectionRef())
6164     PL = get_section(O, "__DATA_CONST", "__objc_protolist");
6165   if (PL == SectionRef())
6166     PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
6167   info.S = PL;
6168   walk_pointer_list_64("protocol", PL, O, &info, nullptr);
6169 
6170   SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
6171   if (MR == SectionRef())
6172     MR = get_section(O, "__DATA", "__objc_msgrefs");
6173   if (MR == SectionRef())
6174     MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
6175   if (MR == SectionRef())
6176     MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
6177   info.S = MR;
6178   print_message_refs64(MR, &info);
6179 
6180   SectionRef II = get_section(O, "__OBJC2", "__image_info");
6181   if (II == SectionRef())
6182     II = get_section(O, "__DATA", "__objc_imageinfo");
6183   if (II == SectionRef())
6184     II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
6185   if (II == SectionRef())
6186     II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
6187   info.S = II;
6188   print_image_info64(II, &info);
6189 }
6190 
6191 static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
6192   SymbolAddressMap AddrMap;
6193   if (verbose)
6194     CreateSymbolAddressMap(O, &AddrMap);
6195 
6196   std::vector<SectionRef> Sections;
6197   for (const SectionRef &Section : O->sections())
6198     Sections.push_back(Section);
6199 
6200   struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
6201 
6202   SectionRef CL = get_section(O, "__OBJC2", "__class_list");
6203   if (CL == SectionRef())
6204     CL = get_section(O, "__DATA", "__objc_classlist");
6205   if (CL == SectionRef())
6206     CL = get_section(O, "__DATA_CONST", "__objc_classlist");
6207   if (CL == SectionRef())
6208     CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
6209   info.S = CL;
6210   walk_pointer_list_32("class", CL, O, &info, print_class32_t);
6211 
6212   SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
6213   if (CR == SectionRef())
6214     CR = get_section(O, "__DATA", "__objc_classrefs");
6215   if (CR == SectionRef())
6216     CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
6217   if (CR == SectionRef())
6218     CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
6219   info.S = CR;
6220   walk_pointer_list_32("class refs", CR, O, &info, nullptr);
6221 
6222   SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
6223   if (SR == SectionRef())
6224     SR = get_section(O, "__DATA", "__objc_superrefs");
6225   if (SR == SectionRef())
6226     SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
6227   if (SR == SectionRef())
6228     SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
6229   info.S = SR;
6230   walk_pointer_list_32("super refs", SR, O, &info, nullptr);
6231 
6232   SectionRef CA = get_section(O, "__OBJC2", "__category_list");
6233   if (CA == SectionRef())
6234     CA = get_section(O, "__DATA", "__objc_catlist");
6235   if (CA == SectionRef())
6236     CA = get_section(O, "__DATA_CONST", "__objc_catlist");
6237   if (CA == SectionRef())
6238     CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
6239   info.S = CA;
6240   walk_pointer_list_32("category", CA, O, &info, print_category32_t);
6241 
6242   SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
6243   if (PL == SectionRef())
6244     PL = get_section(O, "__DATA", "__objc_protolist");
6245   if (PL == SectionRef())
6246     PL = get_section(O, "__DATA_CONST", "__objc_protolist");
6247   if (PL == SectionRef())
6248     PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
6249   info.S = PL;
6250   walk_pointer_list_32("protocol", PL, O, &info, nullptr);
6251 
6252   SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
6253   if (MR == SectionRef())
6254     MR = get_section(O, "__DATA", "__objc_msgrefs");
6255   if (MR == SectionRef())
6256     MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
6257   if (MR == SectionRef())
6258     MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
6259   info.S = MR;
6260   print_message_refs32(MR, &info);
6261 
6262   SectionRef II = get_section(O, "__OBJC2", "__image_info");
6263   if (II == SectionRef())
6264     II = get_section(O, "__DATA", "__objc_imageinfo");
6265   if (II == SectionRef())
6266     II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
6267   if (II == SectionRef())
6268     II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
6269   info.S = II;
6270   print_image_info32(II, &info);
6271 }
6272 
6273 static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
6274   uint32_t i, j, p, offset, xoffset, left, defs_left, def;
6275   const char *r, *name, *defs;
6276   struct objc_module_t module;
6277   SectionRef S, xS;
6278   struct objc_symtab_t symtab;
6279   struct objc_class_t objc_class;
6280   struct objc_category_t objc_category;
6281 
6282   outs() << "Objective-C segment\n";
6283   S = get_section(O, "__OBJC", "__module_info");
6284   if (S == SectionRef())
6285     return false;
6286 
6287   SymbolAddressMap AddrMap;
6288   if (verbose)
6289     CreateSymbolAddressMap(O, &AddrMap);
6290 
6291   std::vector<SectionRef> Sections;
6292   for (const SectionRef &Section : O->sections())
6293     Sections.push_back(Section);
6294 
6295   struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
6296 
6297   for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
6298     p = S.getAddress() + i;
6299     r = get_pointer_32(p, offset, left, S, &info, true);
6300     if (r == nullptr)
6301       return true;
6302     memset(&module, '\0', sizeof(struct objc_module_t));
6303     if (left < sizeof(struct objc_module_t)) {
6304       memcpy(&module, r, left);
6305       outs() << "   (module extends past end of __module_info section)\n";
6306     } else
6307       memcpy(&module, r, sizeof(struct objc_module_t));
6308     if (O->isLittleEndian() != sys::IsLittleEndianHost)
6309       swapStruct(module);
6310 
6311     outs() << "Module " << format("0x%" PRIx32, p) << "\n";
6312     outs() << "    version " << module.version << "\n";
6313     outs() << "       size " << module.size << "\n";
6314     outs() << "       name ";
6315     name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
6316     if (name != nullptr)
6317       outs() << format("%.*s", left, name);
6318     else
6319       outs() << format("0x%08" PRIx32, module.name)
6320              << "(not in an __OBJC section)";
6321     outs() << "\n";
6322 
6323     r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
6324     if (module.symtab == 0 || r == nullptr) {
6325       outs() << "     symtab " << format("0x%08" PRIx32, module.symtab)
6326              << " (not in an __OBJC section)\n";
6327       continue;
6328     }
6329     outs() << "     symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
6330     memset(&symtab, '\0', sizeof(struct objc_symtab_t));
6331     defs_left = 0;
6332     defs = nullptr;
6333     if (left < sizeof(struct objc_symtab_t)) {
6334       memcpy(&symtab, r, left);
6335       outs() << "\tsymtab extends past end of an __OBJC section)\n";
6336     } else {
6337       memcpy(&symtab, r, sizeof(struct objc_symtab_t));
6338       if (left > sizeof(struct objc_symtab_t)) {
6339         defs_left = left - sizeof(struct objc_symtab_t);
6340         defs = r + sizeof(struct objc_symtab_t);
6341       }
6342     }
6343     if (O->isLittleEndian() != sys::IsLittleEndianHost)
6344       swapStruct(symtab);
6345 
6346     outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
6347     r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
6348     outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
6349     if (r == nullptr)
6350       outs() << " (not in an __OBJC section)";
6351     outs() << "\n";
6352     outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
6353     outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
6354     if (symtab.cls_def_cnt > 0)
6355       outs() << "\tClass Definitions\n";
6356     for (j = 0; j < symtab.cls_def_cnt; j++) {
6357       if ((j + 1) * sizeof(uint32_t) > defs_left) {
6358         outs() << "\t(remaining class defs entries entends past the end of the "
6359                << "section)\n";
6360         break;
6361       }
6362       memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
6363       if (O->isLittleEndian() != sys::IsLittleEndianHost)
6364         sys::swapByteOrder(def);
6365 
6366       r = get_pointer_32(def, xoffset, left, xS, &info, true);
6367       outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
6368       if (r != nullptr) {
6369         if (left > sizeof(struct objc_class_t)) {
6370           outs() << "\n";
6371           memcpy(&objc_class, r, sizeof(struct objc_class_t));
6372         } else {
6373           outs() << " (entends past the end of the section)\n";
6374           memset(&objc_class, '\0', sizeof(struct objc_class_t));
6375           memcpy(&objc_class, r, left);
6376         }
6377         if (O->isLittleEndian() != sys::IsLittleEndianHost)
6378           swapStruct(objc_class);
6379         print_objc_class_t(&objc_class, &info);
6380       } else {
6381         outs() << "(not in an __OBJC section)\n";
6382       }
6383 
6384       if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
6385         outs() << "\tMeta Class";
6386         r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
6387         if (r != nullptr) {
6388           if (left > sizeof(struct objc_class_t)) {
6389             outs() << "\n";
6390             memcpy(&objc_class, r, sizeof(struct objc_class_t));
6391           } else {
6392             outs() << " (entends past the end of the section)\n";
6393             memset(&objc_class, '\0', sizeof(struct objc_class_t));
6394             memcpy(&objc_class, r, left);
6395           }
6396           if (O->isLittleEndian() != sys::IsLittleEndianHost)
6397             swapStruct(objc_class);
6398           print_objc_class_t(&objc_class, &info);
6399         } else {
6400           outs() << "(not in an __OBJC section)\n";
6401         }
6402       }
6403     }
6404     if (symtab.cat_def_cnt > 0)
6405       outs() << "\tCategory Definitions\n";
6406     for (j = 0; j < symtab.cat_def_cnt; j++) {
6407       if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
6408         outs() << "\t(remaining category defs entries entends past the end of "
6409                << "the section)\n";
6410         break;
6411       }
6412       memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
6413              sizeof(uint32_t));
6414       if (O->isLittleEndian() != sys::IsLittleEndianHost)
6415         sys::swapByteOrder(def);
6416 
6417       r = get_pointer_32(def, xoffset, left, xS, &info, true);
6418       outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
6419              << format("0x%08" PRIx32, def);
6420       if (r != nullptr) {
6421         if (left > sizeof(struct objc_category_t)) {
6422           outs() << "\n";
6423           memcpy(&objc_category, r, sizeof(struct objc_category_t));
6424         } else {
6425           outs() << " (entends past the end of the section)\n";
6426           memset(&objc_category, '\0', sizeof(struct objc_category_t));
6427           memcpy(&objc_category, r, left);
6428         }
6429         if (O->isLittleEndian() != sys::IsLittleEndianHost)
6430           swapStruct(objc_category);
6431         print_objc_objc_category_t(&objc_category, &info);
6432       } else {
6433         outs() << "(not in an __OBJC section)\n";
6434       }
6435     }
6436   }
6437   const SectionRef II = get_section(O, "__OBJC", "__image_info");
6438   if (II != SectionRef())
6439     print_image_info(II, &info);
6440 
6441   return true;
6442 }
6443 
6444 static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
6445                                 uint32_t size, uint32_t addr) {
6446   SymbolAddressMap AddrMap;
6447   CreateSymbolAddressMap(O, &AddrMap);
6448 
6449   std::vector<SectionRef> Sections;
6450   for (const SectionRef &Section : O->sections())
6451     Sections.push_back(Section);
6452 
6453   struct DisassembleInfo info(O, &AddrMap, &Sections, true);
6454 
6455   const char *p;
6456   struct objc_protocol_t protocol;
6457   uint32_t left, paddr;
6458   for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
6459     memset(&protocol, '\0', sizeof(struct objc_protocol_t));
6460     left = size - (p - sect);
6461     if (left < sizeof(struct objc_protocol_t)) {
6462       outs() << "Protocol extends past end of __protocol section\n";
6463       memcpy(&protocol, p, left);
6464     } else
6465       memcpy(&protocol, p, sizeof(struct objc_protocol_t));
6466     if (O->isLittleEndian() != sys::IsLittleEndianHost)
6467       swapStruct(protocol);
6468     paddr = addr + (p - sect);
6469     outs() << "Protocol " << format("0x%" PRIx32, paddr);
6470     if (print_protocol(paddr, 0, &info))
6471       outs() << "(not in an __OBJC section)\n";
6472   }
6473 }
6474 
6475 #ifdef HAVE_LIBXAR
6476 inline void swapStruct(struct xar_header &xar) {
6477   sys::swapByteOrder(xar.magic);
6478   sys::swapByteOrder(xar.size);
6479   sys::swapByteOrder(xar.version);
6480   sys::swapByteOrder(xar.toc_length_compressed);
6481   sys::swapByteOrder(xar.toc_length_uncompressed);
6482   sys::swapByteOrder(xar.cksum_alg);
6483 }
6484 
6485 static void PrintModeVerbose(uint32_t mode) {
6486   switch(mode & S_IFMT){
6487   case S_IFDIR:
6488     outs() << "d";
6489     break;
6490   case S_IFCHR:
6491     outs() << "c";
6492     break;
6493   case S_IFBLK:
6494     outs() << "b";
6495     break;
6496   case S_IFREG:
6497     outs() << "-";
6498     break;
6499   case S_IFLNK:
6500     outs() << "l";
6501     break;
6502   case S_IFSOCK:
6503     outs() << "s";
6504     break;
6505   default:
6506     outs() << "?";
6507     break;
6508   }
6509 
6510   /* owner permissions */
6511   if(mode & S_IREAD)
6512     outs() << "r";
6513   else
6514     outs() << "-";
6515   if(mode & S_IWRITE)
6516     outs() << "w";
6517   else
6518     outs() << "-";
6519   if(mode & S_ISUID)
6520     outs() << "s";
6521   else if(mode & S_IEXEC)
6522     outs() << "x";
6523   else
6524     outs() << "-";
6525 
6526   /* group permissions */
6527   if(mode & (S_IREAD >> 3))
6528     outs() << "r";
6529   else
6530     outs() << "-";
6531   if(mode & (S_IWRITE >> 3))
6532     outs() << "w";
6533   else
6534     outs() << "-";
6535   if(mode & S_ISGID)
6536     outs() << "s";
6537   else if(mode & (S_IEXEC >> 3))
6538     outs() << "x";
6539   else
6540     outs() << "-";
6541 
6542   /* other permissions */
6543   if(mode & (S_IREAD >> 6))
6544     outs() << "r";
6545   else
6546     outs() << "-";
6547   if(mode & (S_IWRITE >> 6))
6548     outs() << "w";
6549   else
6550     outs() << "-";
6551   if(mode & S_ISVTX)
6552     outs() << "t";
6553   else if(mode & (S_IEXEC >> 6))
6554     outs() << "x";
6555   else
6556     outs() << "-";
6557 }
6558 
6559 static void PrintXarFilesSummary(const char *XarFilename, xar_t xar) {
6560   xar_file_t xf;
6561   const char *key, *type, *mode, *user, *group, *size, *mtime, *name, *m;
6562   char *endp;
6563   uint32_t mode_value;
6564 
6565   ScopedXarIter xi;
6566   if (!xi) {
6567     WithColor::error(errs(), "llvm-objdump")
6568         << "can't obtain an xar iterator for xar archive " << XarFilename
6569         << "\n";
6570     return;
6571   }
6572 
6573   // Go through the xar's files.
6574   for (xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)) {
6575     ScopedXarIter xp;
6576     if(!xp){
6577       WithColor::error(errs(), "llvm-objdump")
6578           << "can't obtain an xar iterator for xar archive " << XarFilename
6579           << "\n";
6580       return;
6581     }
6582     type = nullptr;
6583     mode = nullptr;
6584     user = nullptr;
6585     group = nullptr;
6586     size = nullptr;
6587     mtime = nullptr;
6588     name = nullptr;
6589     for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
6590       const char *val = nullptr;
6591       xar_prop_get(xf, key, &val);
6592 #if 0 // Useful for debugging.
6593       outs() << "key: " << key << " value: " << val << "\n";
6594 #endif
6595       if(strcmp(key, "type") == 0)
6596         type = val;
6597       if(strcmp(key, "mode") == 0)
6598         mode = val;
6599       if(strcmp(key, "user") == 0)
6600         user = val;
6601       if(strcmp(key, "group") == 0)
6602         group = val;
6603       if(strcmp(key, "data/size") == 0)
6604         size = val;
6605       if(strcmp(key, "mtime") == 0)
6606         mtime = val;
6607       if(strcmp(key, "name") == 0)
6608         name = val;
6609     }
6610     if(mode != nullptr){
6611       mode_value = strtoul(mode, &endp, 8);
6612       if(*endp != '\0')
6613         outs() << "(mode: \"" << mode << "\" contains non-octal chars) ";
6614       if(strcmp(type, "file") == 0)
6615         mode_value |= S_IFREG;
6616       PrintModeVerbose(mode_value);
6617       outs() << " ";
6618     }
6619     if(user != nullptr)
6620       outs() << format("%10s/", user);
6621     if(group != nullptr)
6622       outs() << format("%-10s ", group);
6623     if(size != nullptr)
6624       outs() << format("%7s ", size);
6625     if(mtime != nullptr){
6626       for(m = mtime; *m != 'T' && *m != '\0'; m++)
6627         outs() << *m;
6628       if(*m == 'T')
6629         m++;
6630       outs() << " ";
6631       for( ; *m != 'Z' && *m != '\0'; m++)
6632         outs() << *m;
6633       outs() << " ";
6634     }
6635     if(name != nullptr)
6636       outs() << name;
6637     outs() << "\n";
6638   }
6639 }
6640 
6641 static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
6642                                 uint32_t size, bool verbose,
6643                                 bool PrintXarHeader, bool PrintXarFileHeaders,
6644                                 std::string XarMemberName) {
6645   if(size < sizeof(struct xar_header)) {
6646     outs() << "size of (__LLVM,__bundle) section too small (smaller than size "
6647               "of struct xar_header)\n";
6648     return;
6649   }
6650   struct xar_header XarHeader;
6651   memcpy(&XarHeader, sect, sizeof(struct xar_header));
6652   if (sys::IsLittleEndianHost)
6653     swapStruct(XarHeader);
6654   if (PrintXarHeader) {
6655     if (!XarMemberName.empty())
6656       outs() << "In xar member " << XarMemberName << ": ";
6657     else
6658       outs() << "For (__LLVM,__bundle) section: ";
6659     outs() << "xar header\n";
6660     if (XarHeader.magic == XAR_HEADER_MAGIC)
6661       outs() << "                  magic XAR_HEADER_MAGIC\n";
6662     else
6663       outs() << "                  magic "
6664              << format_hex(XarHeader.magic, 10, true)
6665              << " (not XAR_HEADER_MAGIC)\n";
6666     outs() << "                   size " << XarHeader.size << "\n";
6667     outs() << "                version " << XarHeader.version << "\n";
6668     outs() << "  toc_length_compressed " << XarHeader.toc_length_compressed
6669            << "\n";
6670     outs() << "toc_length_uncompressed " << XarHeader.toc_length_uncompressed
6671            << "\n";
6672     outs() << "              cksum_alg ";
6673     switch (XarHeader.cksum_alg) {
6674       case XAR_CKSUM_NONE:
6675         outs() << "XAR_CKSUM_NONE\n";
6676         break;
6677       case XAR_CKSUM_SHA1:
6678         outs() << "XAR_CKSUM_SHA1\n";
6679         break;
6680       case XAR_CKSUM_MD5:
6681         outs() << "XAR_CKSUM_MD5\n";
6682         break;
6683 #ifdef XAR_CKSUM_SHA256
6684       case XAR_CKSUM_SHA256:
6685         outs() << "XAR_CKSUM_SHA256\n";
6686         break;
6687 #endif
6688 #ifdef XAR_CKSUM_SHA512
6689       case XAR_CKSUM_SHA512:
6690         outs() << "XAR_CKSUM_SHA512\n";
6691         break;
6692 #endif
6693       default:
6694         outs() << XarHeader.cksum_alg << "\n";
6695     }
6696   }
6697 
6698   SmallString<128> XarFilename;
6699   int FD;
6700   std::error_code XarEC =
6701       sys::fs::createTemporaryFile("llvm-objdump", "xar", FD, XarFilename);
6702   if (XarEC) {
6703     WithColor::error(errs(), "llvm-objdump") << XarEC.message() << "\n";
6704     return;
6705   }
6706   ToolOutputFile XarFile(XarFilename, FD);
6707   raw_fd_ostream &XarOut = XarFile.os();
6708   StringRef XarContents(sect, size);
6709   XarOut << XarContents;
6710   XarOut.close();
6711   if (XarOut.has_error())
6712     return;
6713 
6714   ScopedXarFile xar(XarFilename.c_str(), READ);
6715   if (!xar) {
6716     WithColor::error(errs(), "llvm-objdump")
6717         << "can't create temporary xar archive " << XarFilename << "\n";
6718     return;
6719   }
6720 
6721   SmallString<128> TocFilename;
6722   std::error_code TocEC =
6723       sys::fs::createTemporaryFile("llvm-objdump", "toc", TocFilename);
6724   if (TocEC) {
6725     WithColor::error(errs(), "llvm-objdump") << TocEC.message() << "\n";
6726     return;
6727   }
6728   xar_serialize(xar, TocFilename.c_str());
6729 
6730   if (PrintXarFileHeaders) {
6731     if (!XarMemberName.empty())
6732       outs() << "In xar member " << XarMemberName << ": ";
6733     else
6734       outs() << "For (__LLVM,__bundle) section: ";
6735     outs() << "xar archive files:\n";
6736     PrintXarFilesSummary(XarFilename.c_str(), xar);
6737   }
6738 
6739   ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
6740     MemoryBuffer::getFileOrSTDIN(TocFilename.c_str());
6741   if (std::error_code EC = FileOrErr.getError()) {
6742     WithColor::error(errs(), "llvm-objdump") << EC.message() << "\n";
6743     return;
6744   }
6745   std::unique_ptr<MemoryBuffer> &Buffer = FileOrErr.get();
6746 
6747   if (!XarMemberName.empty())
6748     outs() << "In xar member " << XarMemberName << ": ";
6749   else
6750     outs() << "For (__LLVM,__bundle) section: ";
6751   outs() << "xar table of contents:\n";
6752   outs() << Buffer->getBuffer() << "\n";
6753 
6754   // TODO: Go through the xar's files.
6755   ScopedXarIter xi;
6756   if(!xi){
6757     WithColor::error(errs(), "llvm-objdump")
6758         << "can't obtain an xar iterator for xar archive "
6759         << XarFilename.c_str() << "\n";
6760     return;
6761   }
6762   for(xar_file_t xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)){
6763     const char *key;
6764     const char *member_name, *member_type, *member_size_string;
6765     size_t member_size;
6766 
6767     ScopedXarIter xp;
6768     if(!xp){
6769       WithColor::error(errs(), "llvm-objdump")
6770           << "can't obtain an xar iterator for xar archive "
6771           << XarFilename.c_str() << "\n";
6772       return;
6773     }
6774     member_name = NULL;
6775     member_type = NULL;
6776     member_size_string = NULL;
6777     for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
6778       const char *val = nullptr;
6779       xar_prop_get(xf, key, &val);
6780 #if 0 // Useful for debugging.
6781       outs() << "key: " << key << " value: " << val << "\n";
6782 #endif
6783       if (strcmp(key, "name") == 0)
6784         member_name = val;
6785       if (strcmp(key, "type") == 0)
6786         member_type = val;
6787       if (strcmp(key, "data/size") == 0)
6788         member_size_string = val;
6789     }
6790     /*
6791      * If we find a file with a name, date/size and type properties
6792      * and with the type being "file" see if that is a xar file.
6793      */
6794     if (member_name != NULL && member_type != NULL &&
6795         strcmp(member_type, "file") == 0 &&
6796         member_size_string != NULL){
6797       // Extract the file into a buffer.
6798       char *endptr;
6799       member_size = strtoul(member_size_string, &endptr, 10);
6800       if (*endptr == '\0' && member_size != 0) {
6801         char *buffer;
6802         if (xar_extract_tobuffersz(xar, xf, &buffer, &member_size) == 0) {
6803 #if 0 // Useful for debugging.
6804           outs() << "xar member: " << member_name << " extracted\n";
6805 #endif
6806           // Set the XarMemberName we want to see printed in the header.
6807           std::string OldXarMemberName;
6808           // If XarMemberName is already set this is nested. So
6809           // save the old name and create the nested name.
6810           if (!XarMemberName.empty()) {
6811             OldXarMemberName = XarMemberName;
6812             XarMemberName =
6813                 (Twine("[") + XarMemberName + "]" + member_name).str();
6814           } else {
6815             OldXarMemberName = "";
6816             XarMemberName = member_name;
6817           }
6818           // See if this is could be a xar file (nested).
6819           if (member_size >= sizeof(struct xar_header)) {
6820 #if 0 // Useful for debugging.
6821             outs() << "could be a xar file: " << member_name << "\n";
6822 #endif
6823             memcpy((char *)&XarHeader, buffer, sizeof(struct xar_header));
6824             if (sys::IsLittleEndianHost)
6825               swapStruct(XarHeader);
6826             if (XarHeader.magic == XAR_HEADER_MAGIC)
6827               DumpBitcodeSection(O, buffer, member_size, verbose,
6828                                  PrintXarHeader, PrintXarFileHeaders,
6829                                  XarMemberName);
6830           }
6831           XarMemberName = OldXarMemberName;
6832           delete buffer;
6833         }
6834       }
6835     }
6836   }
6837 }
6838 #endif // defined(HAVE_LIBXAR)
6839 
6840 static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
6841   if (O->is64Bit())
6842     printObjc2_64bit_MetaData(O, verbose);
6843   else {
6844     MachO::mach_header H;
6845     H = O->getHeader();
6846     if (H.cputype == MachO::CPU_TYPE_ARM)
6847       printObjc2_32bit_MetaData(O, verbose);
6848     else {
6849       // This is the 32-bit non-arm cputype case.  Which is normally
6850       // the first Objective-C ABI.  But it may be the case of a
6851       // binary for the iOS simulator which is the second Objective-C
6852       // ABI.  In that case printObjc1_32bit_MetaData() will determine that
6853       // and return false.
6854       if (!printObjc1_32bit_MetaData(O, verbose))
6855         printObjc2_32bit_MetaData(O, verbose);
6856     }
6857   }
6858 }
6859 
6860 // GuessLiteralPointer returns a string which for the item in the Mach-O file
6861 // for the address passed in as ReferenceValue for printing as a comment with
6862 // the instruction and also returns the corresponding type of that item
6863 // indirectly through ReferenceType.
6864 //
6865 // If ReferenceValue is an address of literal cstring then a pointer to the
6866 // cstring is returned and ReferenceType is set to
6867 // LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
6868 //
6869 // If ReferenceValue is an address of an Objective-C CFString, Selector ref or
6870 // Class ref that name is returned and the ReferenceType is set accordingly.
6871 //
6872 // Lastly, literals which are Symbol address in a literal pool are looked for
6873 // and if found the symbol name is returned and ReferenceType is set to
6874 // LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
6875 //
6876 // If there is no item in the Mach-O file for the address passed in as
6877 // ReferenceValue nullptr is returned and ReferenceType is unchanged.
6878 static const char *GuessLiteralPointer(uint64_t ReferenceValue,
6879                                        uint64_t ReferencePC,
6880                                        uint64_t *ReferenceType,
6881                                        struct DisassembleInfo *info) {
6882   // First see if there is an external relocation entry at the ReferencePC.
6883   if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
6884     uint64_t sect_addr = info->S.getAddress();
6885     uint64_t sect_offset = ReferencePC - sect_addr;
6886     bool reloc_found = false;
6887     DataRefImpl Rel;
6888     MachO::any_relocation_info RE;
6889     bool isExtern = false;
6890     SymbolRef Symbol;
6891     for (const RelocationRef &Reloc : info->S.relocations()) {
6892       uint64_t RelocOffset = Reloc.getOffset();
6893       if (RelocOffset == sect_offset) {
6894         Rel = Reloc.getRawDataRefImpl();
6895         RE = info->O->getRelocation(Rel);
6896         if (info->O->isRelocationScattered(RE))
6897           continue;
6898         isExtern = info->O->getPlainRelocationExternal(RE);
6899         if (isExtern) {
6900           symbol_iterator RelocSym = Reloc.getSymbol();
6901           Symbol = *RelocSym;
6902         }
6903         reloc_found = true;
6904         break;
6905       }
6906     }
6907     // If there is an external relocation entry for a symbol in a section
6908     // then used that symbol's value for the value of the reference.
6909     if (reloc_found && isExtern) {
6910       if (info->O->getAnyRelocationPCRel(RE)) {
6911         unsigned Type = info->O->getAnyRelocationType(RE);
6912         if (Type == MachO::X86_64_RELOC_SIGNED) {
6913           ReferenceValue = Symbol.getValue();
6914         }
6915       }
6916     }
6917   }
6918 
6919   // Look for literals such as Objective-C CFStrings refs, Selector refs,
6920   // Message refs and Class refs.
6921   bool classref, selref, msgref, cfstring;
6922   uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
6923                                                selref, msgref, cfstring);
6924   if (classref && pointer_value == 0) {
6925     // Note the ReferenceValue is a pointer into the __objc_classrefs section.
6926     // And the pointer_value in that section is typically zero as it will be
6927     // set by dyld as part of the "bind information".
6928     const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
6929     if (name != nullptr) {
6930       *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
6931       const char *class_name = strrchr(name, '$');
6932       if (class_name != nullptr && class_name[1] == '_' &&
6933           class_name[2] != '\0') {
6934         info->class_name = class_name + 2;
6935         return name;
6936       }
6937     }
6938   }
6939 
6940   if (classref) {
6941     *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
6942     const char *name =
6943         get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
6944     if (name != nullptr)
6945       info->class_name = name;
6946     else
6947       name = "bad class ref";
6948     return name;
6949   }
6950 
6951   if (cfstring) {
6952     *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
6953     const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
6954     return name;
6955   }
6956 
6957   if (selref && pointer_value == 0)
6958     pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
6959 
6960   if (pointer_value != 0)
6961     ReferenceValue = pointer_value;
6962 
6963   const char *name = GuessCstringPointer(ReferenceValue, info);
6964   if (name) {
6965     if (pointer_value != 0 && selref) {
6966       *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
6967       info->selector_name = name;
6968     } else if (pointer_value != 0 && msgref) {
6969       info->class_name = nullptr;
6970       *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
6971       info->selector_name = name;
6972     } else
6973       *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
6974     return name;
6975   }
6976 
6977   // Lastly look for an indirect symbol with this ReferenceValue which is in
6978   // a literal pool.  If found return that symbol name.
6979   name = GuessIndirectSymbol(ReferenceValue, info);
6980   if (name) {
6981     *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
6982     return name;
6983   }
6984 
6985   return nullptr;
6986 }
6987 
6988 // SymbolizerSymbolLookUp is the symbol lookup function passed when creating
6989 // the Symbolizer.  It looks up the ReferenceValue using the info passed via the
6990 // pointer to the struct DisassembleInfo that was passed when MCSymbolizer
6991 // is created and returns the symbol name that matches the ReferenceValue or
6992 // nullptr if none.  The ReferenceType is passed in for the IN type of
6993 // reference the instruction is making from the values in defined in the header
6994 // "llvm-c/Disassembler.h".  On return the ReferenceType can set to a specific
6995 // Out type and the ReferenceName will also be set which is added as a comment
6996 // to the disassembled instruction.
6997 //
6998 // If the symbol name is a C++ mangled name then the demangled name is
6999 // returned through ReferenceName and ReferenceType is set to
7000 // LLVMDisassembler_ReferenceType_DeMangled_Name .
7001 //
7002 // When this is called to get a symbol name for a branch target then the
7003 // ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
7004 // SymbolValue will be looked for in the indirect symbol table to determine if
7005 // it is an address for a symbol stub.  If so then the symbol name for that
7006 // stub is returned indirectly through ReferenceName and then ReferenceType is
7007 // set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
7008 //
7009 // When this is called with an value loaded via a PC relative load then
7010 // ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
7011 // SymbolValue is checked to be an address of literal pointer, symbol pointer,
7012 // or an Objective-C meta data reference.  If so the output ReferenceType is
7013 // set to correspond to that as well as setting the ReferenceName.
7014 static const char *SymbolizerSymbolLookUp(void *DisInfo,
7015                                           uint64_t ReferenceValue,
7016                                           uint64_t *ReferenceType,
7017                                           uint64_t ReferencePC,
7018                                           const char **ReferenceName) {
7019   struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
7020   // If no verbose symbolic information is wanted then just return nullptr.
7021   if (!info->verbose) {
7022     *ReferenceName = nullptr;
7023     *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7024     return nullptr;
7025   }
7026 
7027   const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
7028 
7029   if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
7030     *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
7031     if (*ReferenceName != nullptr) {
7032       method_reference(info, ReferenceType, ReferenceName);
7033       if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
7034         *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
7035     } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
7036       if (info->demangled_name != nullptr)
7037         free(info->demangled_name);
7038       int status;
7039       info->demangled_name =
7040           itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
7041       if (info->demangled_name != nullptr) {
7042         *ReferenceName = info->demangled_name;
7043         *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
7044       } else
7045         *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7046     } else
7047       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7048   } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
7049     *ReferenceName =
7050         GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7051     if (*ReferenceName)
7052       method_reference(info, ReferenceType, ReferenceName);
7053     else
7054       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7055     // If this is arm64 and the reference is an adrp instruction save the
7056     // instruction, passed in ReferenceValue and the address of the instruction
7057     // for use later if we see and add immediate instruction.
7058   } else if (info->O->getArch() == Triple::aarch64 &&
7059              *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
7060     info->adrp_inst = ReferenceValue;
7061     info->adrp_addr = ReferencePC;
7062     SymbolName = nullptr;
7063     *ReferenceName = nullptr;
7064     *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7065     // If this is arm64 and reference is an add immediate instruction and we
7066     // have
7067     // seen an adrp instruction just before it and the adrp's Xd register
7068     // matches
7069     // this add's Xn register reconstruct the value being referenced and look to
7070     // see if it is a literal pointer.  Note the add immediate instruction is
7071     // passed in ReferenceValue.
7072   } else if (info->O->getArch() == Triple::aarch64 &&
7073              *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
7074              ReferencePC - 4 == info->adrp_addr &&
7075              (info->adrp_inst & 0x9f000000) == 0x90000000 &&
7076              (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
7077     uint32_t addxri_inst;
7078     uint64_t adrp_imm, addxri_imm;
7079 
7080     adrp_imm =
7081         ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
7082     if (info->adrp_inst & 0x0200000)
7083       adrp_imm |= 0xfffffffffc000000LL;
7084 
7085     addxri_inst = ReferenceValue;
7086     addxri_imm = (addxri_inst >> 10) & 0xfff;
7087     if (((addxri_inst >> 22) & 0x3) == 1)
7088       addxri_imm <<= 12;
7089 
7090     ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
7091                      (adrp_imm << 12) + addxri_imm;
7092 
7093     *ReferenceName =
7094         GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7095     if (*ReferenceName == nullptr)
7096       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7097     // If this is arm64 and the reference is a load register instruction and we
7098     // have seen an adrp instruction just before it and the adrp's Xd register
7099     // matches this add's Xn register reconstruct the value being referenced and
7100     // look to see if it is a literal pointer.  Note the load register
7101     // instruction is passed in ReferenceValue.
7102   } else if (info->O->getArch() == Triple::aarch64 &&
7103              *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
7104              ReferencePC - 4 == info->adrp_addr &&
7105              (info->adrp_inst & 0x9f000000) == 0x90000000 &&
7106              (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
7107     uint32_t ldrxui_inst;
7108     uint64_t adrp_imm, ldrxui_imm;
7109 
7110     adrp_imm =
7111         ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
7112     if (info->adrp_inst & 0x0200000)
7113       adrp_imm |= 0xfffffffffc000000LL;
7114 
7115     ldrxui_inst = ReferenceValue;
7116     ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
7117 
7118     ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
7119                      (adrp_imm << 12) + (ldrxui_imm << 3);
7120 
7121     *ReferenceName =
7122         GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7123     if (*ReferenceName == nullptr)
7124       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7125   }
7126   // If this arm64 and is an load register (PC-relative) instruction the
7127   // ReferenceValue is the PC plus the immediate value.
7128   else if (info->O->getArch() == Triple::aarch64 &&
7129            (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
7130             *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
7131     *ReferenceName =
7132         GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7133     if (*ReferenceName == nullptr)
7134       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7135   } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
7136     if (info->demangled_name != nullptr)
7137       free(info->demangled_name);
7138     int status;
7139     info->demangled_name =
7140         itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
7141     if (info->demangled_name != nullptr) {
7142       *ReferenceName = info->demangled_name;
7143       *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
7144     }
7145   }
7146   else {
7147     *ReferenceName = nullptr;
7148     *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7149   }
7150 
7151   return SymbolName;
7152 }
7153 
7154 /// Emits the comments that are stored in the CommentStream.
7155 /// Each comment in the CommentStream must end with a newline.
7156 static void emitComments(raw_svector_ostream &CommentStream,
7157                          SmallString<128> &CommentsToEmit,
7158                          formatted_raw_ostream &FormattedOS,
7159                          const MCAsmInfo &MAI) {
7160   // Flush the stream before taking its content.
7161   StringRef Comments = CommentsToEmit.str();
7162   // Get the default information for printing a comment.
7163   StringRef CommentBegin = MAI.getCommentString();
7164   unsigned CommentColumn = MAI.getCommentColumn();
7165   bool IsFirst = true;
7166   while (!Comments.empty()) {
7167     if (!IsFirst)
7168       FormattedOS << '\n';
7169     // Emit a line of comments.
7170     FormattedOS.PadToColumn(CommentColumn);
7171     size_t Position = Comments.find('\n');
7172     FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
7173     // Move after the newline character.
7174     Comments = Comments.substr(Position + 1);
7175     IsFirst = false;
7176   }
7177   FormattedOS.flush();
7178 
7179   // Tell the comment stream that the vector changed underneath it.
7180   CommentsToEmit.clear();
7181 }
7182 
7183 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
7184                              StringRef DisSegName, StringRef DisSectName) {
7185   const char *McpuDefault = nullptr;
7186   const Target *ThumbTarget = nullptr;
7187   const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
7188   if (!TheTarget) {
7189     // GetTarget prints out stuff.
7190     return;
7191   }
7192   std::string MachOMCPU;
7193   if (MCPU.empty() && McpuDefault)
7194     MachOMCPU = McpuDefault;
7195   else
7196     MachOMCPU = MCPU;
7197 
7198   std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
7199   std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
7200   if (ThumbTarget)
7201     ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
7202 
7203   // Package up features to be passed to target/subtarget
7204   std::string FeaturesStr;
7205   if (!MAttrs.empty()) {
7206     SubtargetFeatures Features;
7207     for (unsigned i = 0; i != MAttrs.size(); ++i)
7208       Features.AddFeature(MAttrs[i]);
7209     FeaturesStr = Features.getString();
7210   }
7211 
7212   MCTargetOptions MCOptions;
7213   // Set up disassembler.
7214   std::unique_ptr<const MCRegisterInfo> MRI(
7215       TheTarget->createMCRegInfo(TripleName));
7216   std::unique_ptr<const MCAsmInfo> AsmInfo(
7217       TheTarget->createMCAsmInfo(*MRI, TripleName, MCOptions));
7218   std::unique_ptr<const MCSubtargetInfo> STI(
7219       TheTarget->createMCSubtargetInfo(TripleName, MachOMCPU, FeaturesStr));
7220   MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
7221   std::unique_ptr<MCDisassembler> DisAsm(
7222       TheTarget->createMCDisassembler(*STI, Ctx));
7223   std::unique_ptr<MCSymbolizer> Symbolizer;
7224   struct DisassembleInfo SymbolizerInfo(nullptr, nullptr, nullptr, false);
7225   std::unique_ptr<MCRelocationInfo> RelInfo(
7226       TheTarget->createMCRelocationInfo(TripleName, Ctx));
7227   if (RelInfo) {
7228     Symbolizer.reset(TheTarget->createMCSymbolizer(
7229         TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
7230         &SymbolizerInfo, &Ctx, std::move(RelInfo)));
7231     DisAsm->setSymbolizer(std::move(Symbolizer));
7232   }
7233   int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
7234   std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
7235       Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
7236   // Set the display preference for hex vs. decimal immediates.
7237   IP->setPrintImmHex(PrintImmHex);
7238   // Comment stream and backing vector.
7239   SmallString<128> CommentsToEmit;
7240   raw_svector_ostream CommentStream(CommentsToEmit);
7241   // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
7242   // if it is done then arm64 comments for string literals don't get printed
7243   // and some constant get printed instead and not setting it causes intel
7244   // (32-bit and 64-bit) comments printed with different spacing before the
7245   // comment causing different diffs with the 'C' disassembler library API.
7246   // IP->setCommentStream(CommentStream);
7247 
7248   if (!AsmInfo || !STI || !DisAsm || !IP) {
7249     WithColor::error(errs(), "llvm-objdump")
7250         << "couldn't initialize disassembler for target " << TripleName << '\n';
7251     return;
7252   }
7253 
7254   // Set up separate thumb disassembler if needed.
7255   std::unique_ptr<const MCRegisterInfo> ThumbMRI;
7256   std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
7257   std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
7258   std::unique_ptr<MCDisassembler> ThumbDisAsm;
7259   std::unique_ptr<MCInstPrinter> ThumbIP;
7260   std::unique_ptr<MCContext> ThumbCtx;
7261   std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
7262   struct DisassembleInfo ThumbSymbolizerInfo(nullptr, nullptr, nullptr, false);
7263   std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
7264   if (ThumbTarget) {
7265     ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
7266     ThumbAsmInfo.reset(
7267         ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName, MCOptions));
7268     ThumbSTI.reset(
7269         ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MachOMCPU,
7270                                            FeaturesStr));
7271     ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
7272     ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
7273     MCContext *PtrThumbCtx = ThumbCtx.get();
7274     ThumbRelInfo.reset(
7275         ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
7276     if (ThumbRelInfo) {
7277       ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
7278           ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
7279           &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
7280       ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
7281     }
7282     int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
7283     ThumbIP.reset(ThumbTarget->createMCInstPrinter(
7284         Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
7285         *ThumbInstrInfo, *ThumbMRI));
7286     // Set the display preference for hex vs. decimal immediates.
7287     ThumbIP->setPrintImmHex(PrintImmHex);
7288   }
7289 
7290   if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
7291     WithColor::error(errs(), "llvm-objdump")
7292         << "couldn't initialize disassembler for target " << ThumbTripleName
7293         << '\n';
7294     return;
7295   }
7296 
7297   MachO::mach_header Header = MachOOF->getHeader();
7298 
7299   // FIXME: Using the -cfg command line option, this code used to be able to
7300   // annotate relocations with the referenced symbol's name, and if this was
7301   // inside a __[cf]string section, the data it points to. This is now replaced
7302   // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
7303   std::vector<SectionRef> Sections;
7304   std::vector<SymbolRef> Symbols;
7305   SmallVector<uint64_t, 8> FoundFns;
7306   uint64_t BaseSegmentAddress = 0;
7307 
7308   getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
7309                         BaseSegmentAddress);
7310 
7311   // Sort the symbols by address, just in case they didn't come in that way.
7312   llvm::sort(Symbols, SymbolSorter());
7313 
7314   // Build a data in code table that is sorted on by the address of each entry.
7315   uint64_t BaseAddress = 0;
7316   if (Header.filetype == MachO::MH_OBJECT)
7317     BaseAddress = Sections[0].getAddress();
7318   else
7319     BaseAddress = BaseSegmentAddress;
7320   DiceTable Dices;
7321   for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
7322        DI != DE; ++DI) {
7323     uint32_t Offset;
7324     DI->getOffset(Offset);
7325     Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
7326   }
7327   array_pod_sort(Dices.begin(), Dices.end());
7328 
7329 #ifndef NDEBUG
7330   raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
7331 #else
7332   raw_ostream &DebugOut = nulls();
7333 #endif
7334 
7335   // Try to find debug info and set up the DIContext for it.
7336   std::unique_ptr<DIContext> diContext;
7337   std::unique_ptr<Binary> DSYMBinary;
7338   std::unique_ptr<MemoryBuffer> DSYMBuf;
7339   if (UseDbg) {
7340     ObjectFile *DbgObj = MachOOF;
7341 
7342     // A separate DSym file path was specified, parse it as a macho file,
7343     // get the sections and supply it to the section name parsing machinery.
7344     if (!DSYMFile.empty()) {
7345       std::string DSYMPath(DSYMFile);
7346 
7347       // If DSYMPath is a .dSYM directory, append the Mach-O file.
7348       if (llvm::sys::fs::is_directory(DSYMPath) &&
7349           llvm::sys::path::extension(DSYMPath) == ".dSYM") {
7350         SmallString<128> ShortName(llvm::sys::path::filename(DSYMPath));
7351         llvm::sys::path::replace_extension(ShortName, "");
7352         SmallString<1024> FullPath(DSYMPath);
7353         llvm::sys::path::append(FullPath, "Contents", "Resources", "DWARF",
7354                                 ShortName);
7355         DSYMPath = FullPath.str();
7356       }
7357 
7358       // Load the file.
7359       ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
7360           MemoryBuffer::getFileOrSTDIN(DSYMPath);
7361       if (std::error_code EC = BufOrErr.getError()) {
7362         reportError(errorCodeToError(EC), DSYMPath);
7363         return;
7364       }
7365 
7366       // We need to keep the file alive, because we're replacing DbgObj with it.
7367       DSYMBuf = std::move(BufOrErr.get());
7368 
7369       Expected<std::unique_ptr<Binary>> BinaryOrErr =
7370       createBinary(DSYMBuf.get()->getMemBufferRef());
7371       if (!BinaryOrErr) {
7372         reportError(BinaryOrErr.takeError(), DSYMPath);
7373         return;
7374       }
7375 
7376       // We need to keep the Binary alive with the buffer
7377       DSYMBinary = std::move(BinaryOrErr.get());
7378       if (ObjectFile *O = dyn_cast<ObjectFile>(DSYMBinary.get())) {
7379         // this is a Mach-O object file, use it
7380         if (MachOObjectFile *MachDSYM = dyn_cast<MachOObjectFile>(&*O)) {
7381           DbgObj = MachDSYM;
7382         }
7383         else {
7384           WithColor::error(errs(), "llvm-objdump")
7385             << DSYMPath << " is not a Mach-O file type.\n";
7386           return;
7387         }
7388       }
7389       else if (auto UB = dyn_cast<MachOUniversalBinary>(DSYMBinary.get())){
7390         // this is a Universal Binary, find a Mach-O for this architecture
7391         uint32_t CPUType, CPUSubType;
7392         const char *ArchFlag;
7393         if (MachOOF->is64Bit()) {
7394           const MachO::mach_header_64 H_64 = MachOOF->getHeader64();
7395           CPUType = H_64.cputype;
7396           CPUSubType = H_64.cpusubtype;
7397         } else {
7398           const MachO::mach_header H = MachOOF->getHeader();
7399           CPUType = H.cputype;
7400           CPUSubType = H.cpusubtype;
7401         }
7402         Triple T = MachOObjectFile::getArchTriple(CPUType, CPUSubType, nullptr,
7403                                                   &ArchFlag);
7404         Expected<std::unique_ptr<MachOObjectFile>> MachDSYM =
7405             UB->getMachOObjectForArch(ArchFlag);
7406         if (!MachDSYM) {
7407           reportError(MachDSYM.takeError(), DSYMPath);
7408           return;
7409         }
7410 
7411         // We need to keep the Binary alive with the buffer
7412         DbgObj = &*MachDSYM.get();
7413         DSYMBinary = std::move(*MachDSYM);
7414       }
7415       else {
7416         WithColor::error(errs(), "llvm-objdump")
7417           << DSYMPath << " is not a Mach-O or Universal file type.\n";
7418         return;
7419       }
7420     }
7421 
7422     // Setup the DIContext
7423     diContext = DWARFContext::create(*DbgObj);
7424   }
7425 
7426   if (FilterSections.empty())
7427     outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
7428 
7429   for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
7430     Expected<StringRef> SecNameOrErr = Sections[SectIdx].getName();
7431     if (!SecNameOrErr) {
7432       consumeError(SecNameOrErr.takeError());
7433       continue;
7434     }
7435     if (*SecNameOrErr != DisSectName)
7436       continue;
7437 
7438     DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
7439 
7440     StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
7441     if (SegmentName != DisSegName)
7442       continue;
7443 
7444     StringRef BytesStr =
7445         unwrapOrError(Sections[SectIdx].getContents(), Filename);
7446     ArrayRef<uint8_t> Bytes = arrayRefFromStringRef(BytesStr);
7447     uint64_t SectAddress = Sections[SectIdx].getAddress();
7448 
7449     bool symbolTableWorked = false;
7450 
7451     // Create a map of symbol addresses to symbol names for use by
7452     // the SymbolizerSymbolLookUp() routine.
7453     SymbolAddressMap AddrMap;
7454     bool DisSymNameFound = false;
7455     for (const SymbolRef &Symbol : MachOOF->symbols()) {
7456       SymbolRef::Type ST =
7457           unwrapOrError(Symbol.getType(), MachOOF->getFileName());
7458       if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
7459           ST == SymbolRef::ST_Other) {
7460         uint64_t Address = Symbol.getValue();
7461         StringRef SymName =
7462             unwrapOrError(Symbol.getName(), MachOOF->getFileName());
7463         AddrMap[Address] = SymName;
7464         if (!DisSymName.empty() && DisSymName == SymName)
7465           DisSymNameFound = true;
7466       }
7467     }
7468     if (!DisSymName.empty() && !DisSymNameFound) {
7469       outs() << "Can't find -dis-symname: " << DisSymName << "\n";
7470       return;
7471     }
7472     // Set up the block of info used by the Symbolizer call backs.
7473     SymbolizerInfo.verbose = !NoSymbolicOperands;
7474     SymbolizerInfo.O = MachOOF;
7475     SymbolizerInfo.S = Sections[SectIdx];
7476     SymbolizerInfo.AddrMap = &AddrMap;
7477     SymbolizerInfo.Sections = &Sections;
7478     // Same for the ThumbSymbolizer
7479     ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
7480     ThumbSymbolizerInfo.O = MachOOF;
7481     ThumbSymbolizerInfo.S = Sections[SectIdx];
7482     ThumbSymbolizerInfo.AddrMap = &AddrMap;
7483     ThumbSymbolizerInfo.Sections = &Sections;
7484 
7485     unsigned int Arch = MachOOF->getArch();
7486 
7487     // Skip all symbols if this is a stubs file.
7488     if (Bytes.empty())
7489       return;
7490 
7491     // If the section has symbols but no symbol at the start of the section
7492     // these are used to make sure the bytes before the first symbol are
7493     // disassembled.
7494     bool FirstSymbol = true;
7495     bool FirstSymbolAtSectionStart = true;
7496 
7497     // Disassemble symbol by symbol.
7498     for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
7499       StringRef SymName =
7500           unwrapOrError(Symbols[SymIdx].getName(), MachOOF->getFileName());
7501       SymbolRef::Type ST =
7502           unwrapOrError(Symbols[SymIdx].getType(), MachOOF->getFileName());
7503       if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
7504         continue;
7505 
7506       // Make sure the symbol is defined in this section.
7507       bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
7508       if (!containsSym) {
7509         if (!DisSymName.empty() && DisSymName == SymName) {
7510           outs() << "-dis-symname: " << DisSymName << " not in the section\n";
7511           return;
7512         }
7513         continue;
7514       }
7515       // The __mh_execute_header is special and we need to deal with that fact
7516       // this symbol is before the start of the (__TEXT,__text) section and at the
7517       // address of the start of the __TEXT segment.  This is because this symbol
7518       // is an N_SECT symbol in the (__TEXT,__text) but its address is before the
7519       // start of the section in a standard MH_EXECUTE filetype.
7520       if (!DisSymName.empty() && DisSymName == "__mh_execute_header") {
7521         outs() << "-dis-symname: __mh_execute_header not in any section\n";
7522         return;
7523       }
7524       // When this code is trying to disassemble a symbol at a time and in the
7525       // case there is only the __mh_execute_header symbol left as in a stripped
7526       // executable, we need to deal with this by ignoring this symbol so the
7527       // whole section is disassembled and this symbol is then not displayed.
7528       if (SymName == "__mh_execute_header" || SymName == "__mh_dylib_header" ||
7529           SymName == "__mh_bundle_header" || SymName == "__mh_object_header" ||
7530           SymName == "__mh_preload_header" || SymName == "__mh_dylinker_header")
7531         continue;
7532 
7533       // If we are only disassembling one symbol see if this is that symbol.
7534       if (!DisSymName.empty() && DisSymName != SymName)
7535         continue;
7536 
7537       // Start at the address of the symbol relative to the section's address.
7538       uint64_t SectSize = Sections[SectIdx].getSize();
7539       uint64_t Start = Symbols[SymIdx].getValue();
7540       uint64_t SectionAddress = Sections[SectIdx].getAddress();
7541       Start -= SectionAddress;
7542 
7543       if (Start > SectSize) {
7544         outs() << "section data ends, " << SymName
7545                << " lies outside valid range\n";
7546         return;
7547       }
7548 
7549       // Stop disassembling either at the beginning of the next symbol or at
7550       // the end of the section.
7551       bool containsNextSym = false;
7552       uint64_t NextSym = 0;
7553       uint64_t NextSymIdx = SymIdx + 1;
7554       while (Symbols.size() > NextSymIdx) {
7555         SymbolRef::Type NextSymType = unwrapOrError(
7556             Symbols[NextSymIdx].getType(), MachOOF->getFileName());
7557         if (NextSymType == SymbolRef::ST_Function) {
7558           containsNextSym =
7559               Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
7560           NextSym = Symbols[NextSymIdx].getValue();
7561           NextSym -= SectionAddress;
7562           break;
7563         }
7564         ++NextSymIdx;
7565       }
7566 
7567       uint64_t End = containsNextSym ? std::min(NextSym, SectSize) : SectSize;
7568       uint64_t Size;
7569 
7570       symbolTableWorked = true;
7571 
7572       DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
7573       bool IsThumb = MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb;
7574 
7575       // We only need the dedicated Thumb target if there's a real choice
7576       // (i.e. we're not targeting M-class) and the function is Thumb.
7577       bool UseThumbTarget = IsThumb && ThumbTarget;
7578 
7579       // If we are not specifying a symbol to start disassembly with and this
7580       // is the first symbol in the section but not at the start of the section
7581       // then move the disassembly index to the start of the section and
7582       // don't print the symbol name just yet.  This is so the bytes before the
7583       // first symbol are disassembled.
7584       uint64_t SymbolStart = Start;
7585       if (DisSymName.empty() && FirstSymbol && Start != 0) {
7586         FirstSymbolAtSectionStart = false;
7587         Start = 0;
7588       }
7589       else
7590         outs() << SymName << ":\n";
7591 
7592       DILineInfo lastLine;
7593       for (uint64_t Index = Start; Index < End; Index += Size) {
7594         MCInst Inst;
7595 
7596         // If this is the first symbol in the section and it was not at the
7597         // start of the section, see if we are at its Index now and if so print
7598         // the symbol name.
7599         if (FirstSymbol && !FirstSymbolAtSectionStart && Index == SymbolStart)
7600           outs() << SymName << ":\n";
7601 
7602         uint64_t PC = SectAddress + Index;
7603         if (!NoLeadingAddr) {
7604           if (FullLeadingAddr) {
7605             if (MachOOF->is64Bit())
7606               outs() << format("%016" PRIx64, PC);
7607             else
7608               outs() << format("%08" PRIx64, PC);
7609           } else {
7610             outs() << format("%8" PRIx64 ":", PC);
7611           }
7612         }
7613         if (!NoShowRawInsn || Arch == Triple::arm)
7614           outs() << "\t";
7615 
7616         if (DumpAndSkipDataInCode(PC, Bytes.data() + Index, Dices, Size))
7617           continue;
7618 
7619         SmallVector<char, 64> AnnotationsBytes;
7620         raw_svector_ostream Annotations(AnnotationsBytes);
7621 
7622         bool gotInst;
7623         if (UseThumbTarget)
7624           gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
7625                                                 PC, DebugOut, Annotations);
7626         else
7627           gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
7628                                            DebugOut, Annotations);
7629         if (gotInst) {
7630           if (!NoShowRawInsn || Arch == Triple::arm) {
7631             dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
7632           }
7633           formatted_raw_ostream FormattedOS(outs());
7634           StringRef AnnotationsStr = Annotations.str();
7635           if (UseThumbTarget)
7636             ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
7637           else
7638             IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
7639           emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
7640 
7641           // Print debug info.
7642           if (diContext) {
7643             DILineInfo dli = diContext->getLineInfoForAddress({PC, SectIdx});
7644             // Print valid line info if it changed.
7645             if (dli != lastLine && dli.Line != 0)
7646               outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
7647                      << dli.Column;
7648             lastLine = dli;
7649           }
7650           outs() << "\n";
7651         } else {
7652           unsigned int Arch = MachOOF->getArch();
7653           if (Arch == Triple::x86_64 || Arch == Triple::x86) {
7654             outs() << format("\t.byte 0x%02x #bad opcode\n",
7655                              *(Bytes.data() + Index) & 0xff);
7656             Size = 1; // skip exactly one illegible byte and move on.
7657           } else if (Arch == Triple::aarch64 ||
7658                      (Arch == Triple::arm && !IsThumb)) {
7659             uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7660                               (*(Bytes.data() + Index + 1) & 0xff) << 8 |
7661                               (*(Bytes.data() + Index + 2) & 0xff) << 16 |
7662                               (*(Bytes.data() + Index + 3) & 0xff) << 24;
7663             outs() << format("\t.long\t0x%08x\n", opcode);
7664             Size = 4;
7665           } else if (Arch == Triple::arm) {
7666             assert(IsThumb && "ARM mode should have been dealt with above");
7667             uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7668                               (*(Bytes.data() + Index + 1) & 0xff) << 8;
7669             outs() << format("\t.short\t0x%04x\n", opcode);
7670             Size = 2;
7671           } else{
7672             WithColor::warning(errs(), "llvm-objdump")
7673                 << "invalid instruction encoding\n";
7674             if (Size == 0)
7675               Size = 1; // skip illegible bytes
7676           }
7677         }
7678       }
7679       // Now that we are done disassembled the first symbol set the bool that
7680       // were doing this to false.
7681       FirstSymbol = false;
7682     }
7683     if (!symbolTableWorked) {
7684       // Reading the symbol table didn't work, disassemble the whole section.
7685       uint64_t SectAddress = Sections[SectIdx].getAddress();
7686       uint64_t SectSize = Sections[SectIdx].getSize();
7687       uint64_t InstSize;
7688       for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
7689         MCInst Inst;
7690 
7691         uint64_t PC = SectAddress + Index;
7692 
7693         if (DumpAndSkipDataInCode(PC, Bytes.data() + Index, Dices, InstSize))
7694           continue;
7695 
7696         SmallVector<char, 64> AnnotationsBytes;
7697         raw_svector_ostream Annotations(AnnotationsBytes);
7698         if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
7699                                    DebugOut, Annotations)) {
7700           if (!NoLeadingAddr) {
7701             if (FullLeadingAddr) {
7702               if (MachOOF->is64Bit())
7703                 outs() << format("%016" PRIx64, PC);
7704               else
7705                 outs() << format("%08" PRIx64, PC);
7706             } else {
7707               outs() << format("%8" PRIx64 ":", PC);
7708             }
7709           }
7710           if (!NoShowRawInsn || Arch == Triple::arm) {
7711             outs() << "\t";
7712             dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
7713           }
7714           StringRef AnnotationsStr = Annotations.str();
7715           IP->printInst(&Inst, outs(), AnnotationsStr, *STI);
7716           outs() << "\n";
7717         } else {
7718           unsigned int Arch = MachOOF->getArch();
7719           if (Arch == Triple::x86_64 || Arch == Triple::x86) {
7720             outs() << format("\t.byte 0x%02x #bad opcode\n",
7721                              *(Bytes.data() + Index) & 0xff);
7722             InstSize = 1; // skip exactly one illegible byte and move on.
7723           } else {
7724             WithColor::warning(errs(), "llvm-objdump")
7725                 << "invalid instruction encoding\n";
7726             if (InstSize == 0)
7727               InstSize = 1; // skip illegible bytes
7728           }
7729         }
7730       }
7731     }
7732     // The TripleName's need to be reset if we are called again for a different
7733     // archtecture.
7734     TripleName = "";
7735     ThumbTripleName = "";
7736 
7737     if (SymbolizerInfo.demangled_name != nullptr)
7738       free(SymbolizerInfo.demangled_name);
7739     if (ThumbSymbolizerInfo.demangled_name != nullptr)
7740       free(ThumbSymbolizerInfo.demangled_name);
7741   }
7742 }
7743 
7744 //===----------------------------------------------------------------------===//
7745 // __compact_unwind section dumping
7746 //===----------------------------------------------------------------------===//
7747 
7748 namespace {
7749 
7750 template <typename T>
7751 static uint64_t read(StringRef Contents, ptrdiff_t Offset) {
7752   using llvm::support::little;
7753   using llvm::support::unaligned;
7754 
7755   if (Offset + sizeof(T) > Contents.size()) {
7756     outs() << "warning: attempt to read past end of buffer\n";
7757     return T();
7758   }
7759 
7760   uint64_t Val =
7761       support::endian::read<T, little, unaligned>(Contents.data() + Offset);
7762   return Val;
7763 }
7764 
7765 template <typename T>
7766 static uint64_t readNext(StringRef Contents, ptrdiff_t &Offset) {
7767   T Val = read<T>(Contents, Offset);
7768   Offset += sizeof(T);
7769   return Val;
7770 }
7771 
7772 struct CompactUnwindEntry {
7773   uint32_t OffsetInSection;
7774 
7775   uint64_t FunctionAddr;
7776   uint32_t Length;
7777   uint32_t CompactEncoding;
7778   uint64_t PersonalityAddr;
7779   uint64_t LSDAAddr;
7780 
7781   RelocationRef FunctionReloc;
7782   RelocationRef PersonalityReloc;
7783   RelocationRef LSDAReloc;
7784 
7785   CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
7786       : OffsetInSection(Offset) {
7787     if (Is64)
7788       read<uint64_t>(Contents, Offset);
7789     else
7790       read<uint32_t>(Contents, Offset);
7791   }
7792 
7793 private:
7794   template <typename UIntPtr> void read(StringRef Contents, ptrdiff_t Offset) {
7795     FunctionAddr = readNext<UIntPtr>(Contents, Offset);
7796     Length = readNext<uint32_t>(Contents, Offset);
7797     CompactEncoding = readNext<uint32_t>(Contents, Offset);
7798     PersonalityAddr = readNext<UIntPtr>(Contents, Offset);
7799     LSDAAddr = readNext<UIntPtr>(Contents, Offset);
7800   }
7801 };
7802 }
7803 
7804 /// Given a relocation from __compact_unwind, consisting of the RelocationRef
7805 /// and data being relocated, determine the best base Name and Addend to use for
7806 /// display purposes.
7807 ///
7808 /// 1. An Extern relocation will directly reference a symbol (and the data is
7809 ///    then already an addend), so use that.
7810 /// 2. Otherwise the data is an offset in the object file's layout; try to find
7811 //     a symbol before it in the same section, and use the offset from there.
7812 /// 3. Finally, if all that fails, fall back to an offset from the start of the
7813 ///    referenced section.
7814 static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
7815                                       std::map<uint64_t, SymbolRef> &Symbols,
7816                                       const RelocationRef &Reloc, uint64_t Addr,
7817                                       StringRef &Name, uint64_t &Addend) {
7818   if (Reloc.getSymbol() != Obj->symbol_end()) {
7819     Name = unwrapOrError(Reloc.getSymbol()->getName(), Obj->getFileName());
7820     Addend = Addr;
7821     return;
7822   }
7823 
7824   auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
7825   SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
7826 
7827   uint64_t SectionAddr = RelocSection.getAddress();
7828 
7829   auto Sym = Symbols.upper_bound(Addr);
7830   if (Sym == Symbols.begin()) {
7831     // The first symbol in the object is after this reference, the best we can
7832     // do is section-relative notation.
7833     if (Expected<StringRef> NameOrErr = RelocSection.getName())
7834       Name = *NameOrErr;
7835     else
7836       consumeError(NameOrErr.takeError());
7837 
7838     Addend = Addr - SectionAddr;
7839     return;
7840   }
7841 
7842   // Go back one so that SymbolAddress <= Addr.
7843   --Sym;
7844 
7845   section_iterator SymSection =
7846       unwrapOrError(Sym->second.getSection(), Obj->getFileName());
7847   if (RelocSection == *SymSection) {
7848     // There's a valid symbol in the same section before this reference.
7849     Name = unwrapOrError(Sym->second.getName(), Obj->getFileName());
7850     Addend = Addr - Sym->first;
7851     return;
7852   }
7853 
7854   // There is a symbol before this reference, but it's in a different
7855   // section. Probably not helpful to mention it, so use the section name.
7856   if (Expected<StringRef> NameOrErr = RelocSection.getName())
7857     Name = *NameOrErr;
7858   else
7859     consumeError(NameOrErr.takeError());
7860 
7861   Addend = Addr - SectionAddr;
7862 }
7863 
7864 static void printUnwindRelocDest(const MachOObjectFile *Obj,
7865                                  std::map<uint64_t, SymbolRef> &Symbols,
7866                                  const RelocationRef &Reloc, uint64_t Addr) {
7867   StringRef Name;
7868   uint64_t Addend;
7869 
7870   if (!Reloc.getObject())
7871     return;
7872 
7873   findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
7874 
7875   outs() << Name;
7876   if (Addend)
7877     outs() << " + " << format("0x%" PRIx64, Addend);
7878 }
7879 
7880 static void
7881 printMachOCompactUnwindSection(const MachOObjectFile *Obj,
7882                                std::map<uint64_t, SymbolRef> &Symbols,
7883                                const SectionRef &CompactUnwind) {
7884 
7885   if (!Obj->isLittleEndian()) {
7886     outs() << "Skipping big-endian __compact_unwind section\n";
7887     return;
7888   }
7889 
7890   bool Is64 = Obj->is64Bit();
7891   uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
7892   uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
7893 
7894   StringRef Contents =
7895       unwrapOrError(CompactUnwind.getContents(), Obj->getFileName());
7896   SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
7897 
7898   // First populate the initial raw offsets, encodings and so on from the entry.
7899   for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
7900     CompactUnwindEntry Entry(Contents, Offset, Is64);
7901     CompactUnwinds.push_back(Entry);
7902   }
7903 
7904   // Next we need to look at the relocations to find out what objects are
7905   // actually being referred to.
7906   for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
7907     uint64_t RelocAddress = Reloc.getOffset();
7908 
7909     uint32_t EntryIdx = RelocAddress / EntrySize;
7910     uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
7911     CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
7912 
7913     if (OffsetInEntry == 0)
7914       Entry.FunctionReloc = Reloc;
7915     else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
7916       Entry.PersonalityReloc = Reloc;
7917     else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
7918       Entry.LSDAReloc = Reloc;
7919     else {
7920       outs() << "Invalid relocation in __compact_unwind section\n";
7921       return;
7922     }
7923   }
7924 
7925   // Finally, we're ready to print the data we've gathered.
7926   outs() << "Contents of __compact_unwind section:\n";
7927   for (auto &Entry : CompactUnwinds) {
7928     outs() << "  Entry at offset "
7929            << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
7930 
7931     // 1. Start of the region this entry applies to.
7932     outs() << "    start:                " << format("0x%" PRIx64,
7933                                                      Entry.FunctionAddr) << ' ';
7934     printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
7935     outs() << '\n';
7936 
7937     // 2. Length of the region this entry applies to.
7938     outs() << "    length:               " << format("0x%" PRIx32, Entry.Length)
7939            << '\n';
7940     // 3. The 32-bit compact encoding.
7941     outs() << "    compact encoding:     "
7942            << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
7943 
7944     // 4. The personality function, if present.
7945     if (Entry.PersonalityReloc.getObject()) {
7946       outs() << "    personality function: "
7947              << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
7948       printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
7949                            Entry.PersonalityAddr);
7950       outs() << '\n';
7951     }
7952 
7953     // 5. This entry's language-specific data area.
7954     if (Entry.LSDAReloc.getObject()) {
7955       outs() << "    LSDA:                 " << format("0x%" PRIx64,
7956                                                        Entry.LSDAAddr) << ' ';
7957       printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
7958       outs() << '\n';
7959     }
7960   }
7961 }
7962 
7963 //===----------------------------------------------------------------------===//
7964 // __unwind_info section dumping
7965 //===----------------------------------------------------------------------===//
7966 
7967 static void printRegularSecondLevelUnwindPage(StringRef PageData) {
7968   ptrdiff_t Pos = 0;
7969   uint32_t Kind = readNext<uint32_t>(PageData, Pos);
7970   (void)Kind;
7971   assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
7972 
7973   uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
7974   uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
7975 
7976   Pos = EntriesStart;
7977   for (unsigned i = 0; i < NumEntries; ++i) {
7978     uint32_t FunctionOffset = readNext<uint32_t>(PageData, Pos);
7979     uint32_t Encoding = readNext<uint32_t>(PageData, Pos);
7980 
7981     outs() << "      [" << i << "]: "
7982            << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7983            << ", "
7984            << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
7985   }
7986 }
7987 
7988 static void printCompressedSecondLevelUnwindPage(
7989     StringRef PageData, uint32_t FunctionBase,
7990     const SmallVectorImpl<uint32_t> &CommonEncodings) {
7991   ptrdiff_t Pos = 0;
7992   uint32_t Kind = readNext<uint32_t>(PageData, Pos);
7993   (void)Kind;
7994   assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
7995 
7996   uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
7997   uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
7998 
7999   uint16_t EncodingsStart = readNext<uint16_t>(PageData, Pos);
8000   readNext<uint16_t>(PageData, Pos);
8001   StringRef PageEncodings = PageData.substr(EncodingsStart, StringRef::npos);
8002 
8003   Pos = EntriesStart;
8004   for (unsigned i = 0; i < NumEntries; ++i) {
8005     uint32_t Entry = readNext<uint32_t>(PageData, Pos);
8006     uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
8007     uint32_t EncodingIdx = Entry >> 24;
8008 
8009     uint32_t Encoding;
8010     if (EncodingIdx < CommonEncodings.size())
8011       Encoding = CommonEncodings[EncodingIdx];
8012     else
8013       Encoding = read<uint32_t>(PageEncodings,
8014                                 sizeof(uint32_t) *
8015                                     (EncodingIdx - CommonEncodings.size()));
8016 
8017     outs() << "      [" << i << "]: "
8018            << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
8019            << ", "
8020            << "encoding[" << EncodingIdx
8021            << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
8022   }
8023 }
8024 
8025 static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
8026                                         std::map<uint64_t, SymbolRef> &Symbols,
8027                                         const SectionRef &UnwindInfo) {
8028 
8029   if (!Obj->isLittleEndian()) {
8030     outs() << "Skipping big-endian __unwind_info section\n";
8031     return;
8032   }
8033 
8034   outs() << "Contents of __unwind_info section:\n";
8035 
8036   StringRef Contents =
8037       unwrapOrError(UnwindInfo.getContents(), Obj->getFileName());
8038   ptrdiff_t Pos = 0;
8039 
8040   //===----------------------------------
8041   // Section header
8042   //===----------------------------------
8043 
8044   uint32_t Version = readNext<uint32_t>(Contents, Pos);
8045   outs() << "  Version:                                   "
8046          << format("0x%" PRIx32, Version) << '\n';
8047   if (Version != 1) {
8048     outs() << "    Skipping section with unknown version\n";
8049     return;
8050   }
8051 
8052   uint32_t CommonEncodingsStart = readNext<uint32_t>(Contents, Pos);
8053   outs() << "  Common encodings array section offset:     "
8054          << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
8055   uint32_t NumCommonEncodings = readNext<uint32_t>(Contents, Pos);
8056   outs() << "  Number of common encodings in array:       "
8057          << format("0x%" PRIx32, NumCommonEncodings) << '\n';
8058 
8059   uint32_t PersonalitiesStart = readNext<uint32_t>(Contents, Pos);
8060   outs() << "  Personality function array section offset: "
8061          << format("0x%" PRIx32, PersonalitiesStart) << '\n';
8062   uint32_t NumPersonalities = readNext<uint32_t>(Contents, Pos);
8063   outs() << "  Number of personality functions in array:  "
8064          << format("0x%" PRIx32, NumPersonalities) << '\n';
8065 
8066   uint32_t IndicesStart = readNext<uint32_t>(Contents, Pos);
8067   outs() << "  Index array section offset:                "
8068          << format("0x%" PRIx32, IndicesStart) << '\n';
8069   uint32_t NumIndices = readNext<uint32_t>(Contents, Pos);
8070   outs() << "  Number of indices in array:                "
8071          << format("0x%" PRIx32, NumIndices) << '\n';
8072 
8073   //===----------------------------------
8074   // A shared list of common encodings
8075   //===----------------------------------
8076 
8077   // These occupy indices in the range [0, N] whenever an encoding is referenced
8078   // from a compressed 2nd level index table. In practice the linker only
8079   // creates ~128 of these, so that indices are available to embed encodings in
8080   // the 2nd level index.
8081 
8082   SmallVector<uint32_t, 64> CommonEncodings;
8083   outs() << "  Common encodings: (count = " << NumCommonEncodings << ")\n";
8084   Pos = CommonEncodingsStart;
8085   for (unsigned i = 0; i < NumCommonEncodings; ++i) {
8086     uint32_t Encoding = readNext<uint32_t>(Contents, Pos);
8087     CommonEncodings.push_back(Encoding);
8088 
8089     outs() << "    encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
8090            << '\n';
8091   }
8092 
8093   //===----------------------------------
8094   // Personality functions used in this executable
8095   //===----------------------------------
8096 
8097   // There should be only a handful of these (one per source language,
8098   // roughly). Particularly since they only get 2 bits in the compact encoding.
8099 
8100   outs() << "  Personality functions: (count = " << NumPersonalities << ")\n";
8101   Pos = PersonalitiesStart;
8102   for (unsigned i = 0; i < NumPersonalities; ++i) {
8103     uint32_t PersonalityFn = readNext<uint32_t>(Contents, Pos);
8104     outs() << "    personality[" << i + 1
8105            << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
8106   }
8107 
8108   //===----------------------------------
8109   // The level 1 index entries
8110   //===----------------------------------
8111 
8112   // These specify an approximate place to start searching for the more detailed
8113   // information, sorted by PC.
8114 
8115   struct IndexEntry {
8116     uint32_t FunctionOffset;
8117     uint32_t SecondLevelPageStart;
8118     uint32_t LSDAStart;
8119   };
8120 
8121   SmallVector<IndexEntry, 4> IndexEntries;
8122 
8123   outs() << "  Top level indices: (count = " << NumIndices << ")\n";
8124   Pos = IndicesStart;
8125   for (unsigned i = 0; i < NumIndices; ++i) {
8126     IndexEntry Entry;
8127 
8128     Entry.FunctionOffset = readNext<uint32_t>(Contents, Pos);
8129     Entry.SecondLevelPageStart = readNext<uint32_t>(Contents, Pos);
8130     Entry.LSDAStart = readNext<uint32_t>(Contents, Pos);
8131     IndexEntries.push_back(Entry);
8132 
8133     outs() << "    [" << i << "]: "
8134            << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
8135            << ", "
8136            << "2nd level page offset="
8137            << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
8138            << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
8139   }
8140 
8141   //===----------------------------------
8142   // Next come the LSDA tables
8143   //===----------------------------------
8144 
8145   // The LSDA layout is rather implicit: it's a contiguous array of entries from
8146   // the first top-level index's LSDAOffset to the last (sentinel).
8147 
8148   outs() << "  LSDA descriptors:\n";
8149   Pos = IndexEntries[0].LSDAStart;
8150   const uint32_t LSDASize = 2 * sizeof(uint32_t);
8151   int NumLSDAs =
8152       (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) / LSDASize;
8153 
8154   for (int i = 0; i < NumLSDAs; ++i) {
8155     uint32_t FunctionOffset = readNext<uint32_t>(Contents, Pos);
8156     uint32_t LSDAOffset = readNext<uint32_t>(Contents, Pos);
8157     outs() << "    [" << i << "]: "
8158            << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
8159            << ", "
8160            << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
8161   }
8162 
8163   //===----------------------------------
8164   // Finally, the 2nd level indices
8165   //===----------------------------------
8166 
8167   // Generally these are 4K in size, and have 2 possible forms:
8168   //   + Regular stores up to 511 entries with disparate encodings
8169   //   + Compressed stores up to 1021 entries if few enough compact encoding
8170   //     values are used.
8171   outs() << "  Second level indices:\n";
8172   for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
8173     // The final sentinel top-level index has no associated 2nd level page
8174     if (IndexEntries[i].SecondLevelPageStart == 0)
8175       break;
8176 
8177     outs() << "    Second level index[" << i << "]: "
8178            << "offset in section="
8179            << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
8180            << ", "
8181            << "base function offset="
8182            << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
8183 
8184     Pos = IndexEntries[i].SecondLevelPageStart;
8185     if (Pos + sizeof(uint32_t) > Contents.size()) {
8186       outs() << "warning: invalid offset for second level page: " << Pos << '\n';
8187       continue;
8188     }
8189 
8190     uint32_t Kind =
8191         *reinterpret_cast<const support::ulittle32_t *>(Contents.data() + Pos);
8192     if (Kind == 2)
8193       printRegularSecondLevelUnwindPage(Contents.substr(Pos, 4096));
8194     else if (Kind == 3)
8195       printCompressedSecondLevelUnwindPage(Contents.substr(Pos, 4096),
8196                                            IndexEntries[i].FunctionOffset,
8197                                            CommonEncodings);
8198     else
8199       outs() << "    Skipping 2nd level page with unknown kind " << Kind
8200              << '\n';
8201   }
8202 }
8203 
8204 void printMachOUnwindInfo(const MachOObjectFile *Obj) {
8205   std::map<uint64_t, SymbolRef> Symbols;
8206   for (const SymbolRef &SymRef : Obj->symbols()) {
8207     // Discard any undefined or absolute symbols. They're not going to take part
8208     // in the convenience lookup for unwind info and just take up resources.
8209     auto SectOrErr = SymRef.getSection();
8210     if (!SectOrErr) {
8211       // TODO: Actually report errors helpfully.
8212       consumeError(SectOrErr.takeError());
8213       continue;
8214     }
8215     section_iterator Section = *SectOrErr;
8216     if (Section == Obj->section_end())
8217       continue;
8218 
8219     uint64_t Addr = SymRef.getValue();
8220     Symbols.insert(std::make_pair(Addr, SymRef));
8221   }
8222 
8223   for (const SectionRef &Section : Obj->sections()) {
8224     StringRef SectName;
8225     if (Expected<StringRef> NameOrErr = Section.getName())
8226       SectName = *NameOrErr;
8227     else
8228       consumeError(NameOrErr.takeError());
8229 
8230     if (SectName == "__compact_unwind")
8231       printMachOCompactUnwindSection(Obj, Symbols, Section);
8232     else if (SectName == "__unwind_info")
8233       printMachOUnwindInfoSection(Obj, Symbols, Section);
8234   }
8235 }
8236 
8237 static void PrintMachHeader(uint32_t magic, uint32_t cputype,
8238                             uint32_t cpusubtype, uint32_t filetype,
8239                             uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
8240                             bool verbose) {
8241   outs() << "Mach header\n";
8242   outs() << "      magic cputype cpusubtype  caps    filetype ncmds "
8243             "sizeofcmds      flags\n";
8244   if (verbose) {
8245     if (magic == MachO::MH_MAGIC)
8246       outs() << "   MH_MAGIC";
8247     else if (magic == MachO::MH_MAGIC_64)
8248       outs() << "MH_MAGIC_64";
8249     else
8250       outs() << format(" 0x%08" PRIx32, magic);
8251     switch (cputype) {
8252     case MachO::CPU_TYPE_I386:
8253       outs() << "    I386";
8254       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8255       case MachO::CPU_SUBTYPE_I386_ALL:
8256         outs() << "        ALL";
8257         break;
8258       default:
8259         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8260         break;
8261       }
8262       break;
8263     case MachO::CPU_TYPE_X86_64:
8264       outs() << "  X86_64";
8265       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8266       case MachO::CPU_SUBTYPE_X86_64_ALL:
8267         outs() << "        ALL";
8268         break;
8269       case MachO::CPU_SUBTYPE_X86_64_H:
8270         outs() << "    Haswell";
8271         break;
8272       default:
8273         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8274         break;
8275       }
8276       break;
8277     case MachO::CPU_TYPE_ARM:
8278       outs() << "     ARM";
8279       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8280       case MachO::CPU_SUBTYPE_ARM_ALL:
8281         outs() << "        ALL";
8282         break;
8283       case MachO::CPU_SUBTYPE_ARM_V4T:
8284         outs() << "        V4T";
8285         break;
8286       case MachO::CPU_SUBTYPE_ARM_V5TEJ:
8287         outs() << "      V5TEJ";
8288         break;
8289       case MachO::CPU_SUBTYPE_ARM_XSCALE:
8290         outs() << "     XSCALE";
8291         break;
8292       case MachO::CPU_SUBTYPE_ARM_V6:
8293         outs() << "         V6";
8294         break;
8295       case MachO::CPU_SUBTYPE_ARM_V6M:
8296         outs() << "        V6M";
8297         break;
8298       case MachO::CPU_SUBTYPE_ARM_V7:
8299         outs() << "         V7";
8300         break;
8301       case MachO::CPU_SUBTYPE_ARM_V7EM:
8302         outs() << "       V7EM";
8303         break;
8304       case MachO::CPU_SUBTYPE_ARM_V7K:
8305         outs() << "        V7K";
8306         break;
8307       case MachO::CPU_SUBTYPE_ARM_V7M:
8308         outs() << "        V7M";
8309         break;
8310       case MachO::CPU_SUBTYPE_ARM_V7S:
8311         outs() << "        V7S";
8312         break;
8313       default:
8314         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8315         break;
8316       }
8317       break;
8318     case MachO::CPU_TYPE_ARM64:
8319       outs() << "   ARM64";
8320       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8321       case MachO::CPU_SUBTYPE_ARM64_ALL:
8322         outs() << "        ALL";
8323         break;
8324       case MachO::CPU_SUBTYPE_ARM64E:
8325         outs() << "          E";
8326         break;
8327       default:
8328         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8329         break;
8330       }
8331       break;
8332     case MachO::CPU_TYPE_ARM64_32:
8333       outs() << " ARM64_32";
8334       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8335       case MachO::CPU_SUBTYPE_ARM64_32_V8:
8336         outs() << "        V8";
8337         break;
8338       default:
8339         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8340         break;
8341       }
8342       break;
8343     case MachO::CPU_TYPE_POWERPC:
8344       outs() << "     PPC";
8345       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8346       case MachO::CPU_SUBTYPE_POWERPC_ALL:
8347         outs() << "        ALL";
8348         break;
8349       default:
8350         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8351         break;
8352       }
8353       break;
8354     case MachO::CPU_TYPE_POWERPC64:
8355       outs() << "   PPC64";
8356       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8357       case MachO::CPU_SUBTYPE_POWERPC_ALL:
8358         outs() << "        ALL";
8359         break;
8360       default:
8361         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8362         break;
8363       }
8364       break;
8365     default:
8366       outs() << format(" %7d", cputype);
8367       outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8368       break;
8369     }
8370     if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
8371       outs() << " LIB64";
8372     } else {
8373       outs() << format("  0x%02" PRIx32,
8374                        (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
8375     }
8376     switch (filetype) {
8377     case MachO::MH_OBJECT:
8378       outs() << "      OBJECT";
8379       break;
8380     case MachO::MH_EXECUTE:
8381       outs() << "     EXECUTE";
8382       break;
8383     case MachO::MH_FVMLIB:
8384       outs() << "      FVMLIB";
8385       break;
8386     case MachO::MH_CORE:
8387       outs() << "        CORE";
8388       break;
8389     case MachO::MH_PRELOAD:
8390       outs() << "     PRELOAD";
8391       break;
8392     case MachO::MH_DYLIB:
8393       outs() << "       DYLIB";
8394       break;
8395     case MachO::MH_DYLIB_STUB:
8396       outs() << "  DYLIB_STUB";
8397       break;
8398     case MachO::MH_DYLINKER:
8399       outs() << "    DYLINKER";
8400       break;
8401     case MachO::MH_BUNDLE:
8402       outs() << "      BUNDLE";
8403       break;
8404     case MachO::MH_DSYM:
8405       outs() << "        DSYM";
8406       break;
8407     case MachO::MH_KEXT_BUNDLE:
8408       outs() << "  KEXTBUNDLE";
8409       break;
8410     default:
8411       outs() << format("  %10u", filetype);
8412       break;
8413     }
8414     outs() << format(" %5u", ncmds);
8415     outs() << format(" %10u", sizeofcmds);
8416     uint32_t f = flags;
8417     if (f & MachO::MH_NOUNDEFS) {
8418       outs() << "   NOUNDEFS";
8419       f &= ~MachO::MH_NOUNDEFS;
8420     }
8421     if (f & MachO::MH_INCRLINK) {
8422       outs() << " INCRLINK";
8423       f &= ~MachO::MH_INCRLINK;
8424     }
8425     if (f & MachO::MH_DYLDLINK) {
8426       outs() << " DYLDLINK";
8427       f &= ~MachO::MH_DYLDLINK;
8428     }
8429     if (f & MachO::MH_BINDATLOAD) {
8430       outs() << " BINDATLOAD";
8431       f &= ~MachO::MH_BINDATLOAD;
8432     }
8433     if (f & MachO::MH_PREBOUND) {
8434       outs() << " PREBOUND";
8435       f &= ~MachO::MH_PREBOUND;
8436     }
8437     if (f & MachO::MH_SPLIT_SEGS) {
8438       outs() << " SPLIT_SEGS";
8439       f &= ~MachO::MH_SPLIT_SEGS;
8440     }
8441     if (f & MachO::MH_LAZY_INIT) {
8442       outs() << " LAZY_INIT";
8443       f &= ~MachO::MH_LAZY_INIT;
8444     }
8445     if (f & MachO::MH_TWOLEVEL) {
8446       outs() << " TWOLEVEL";
8447       f &= ~MachO::MH_TWOLEVEL;
8448     }
8449     if (f & MachO::MH_FORCE_FLAT) {
8450       outs() << " FORCE_FLAT";
8451       f &= ~MachO::MH_FORCE_FLAT;
8452     }
8453     if (f & MachO::MH_NOMULTIDEFS) {
8454       outs() << " NOMULTIDEFS";
8455       f &= ~MachO::MH_NOMULTIDEFS;
8456     }
8457     if (f & MachO::MH_NOFIXPREBINDING) {
8458       outs() << " NOFIXPREBINDING";
8459       f &= ~MachO::MH_NOFIXPREBINDING;
8460     }
8461     if (f & MachO::MH_PREBINDABLE) {
8462       outs() << " PREBINDABLE";
8463       f &= ~MachO::MH_PREBINDABLE;
8464     }
8465     if (f & MachO::MH_ALLMODSBOUND) {
8466       outs() << " ALLMODSBOUND";
8467       f &= ~MachO::MH_ALLMODSBOUND;
8468     }
8469     if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
8470       outs() << " SUBSECTIONS_VIA_SYMBOLS";
8471       f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
8472     }
8473     if (f & MachO::MH_CANONICAL) {
8474       outs() << " CANONICAL";
8475       f &= ~MachO::MH_CANONICAL;
8476     }
8477     if (f & MachO::MH_WEAK_DEFINES) {
8478       outs() << " WEAK_DEFINES";
8479       f &= ~MachO::MH_WEAK_DEFINES;
8480     }
8481     if (f & MachO::MH_BINDS_TO_WEAK) {
8482       outs() << " BINDS_TO_WEAK";
8483       f &= ~MachO::MH_BINDS_TO_WEAK;
8484     }
8485     if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
8486       outs() << " ALLOW_STACK_EXECUTION";
8487       f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
8488     }
8489     if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
8490       outs() << " DEAD_STRIPPABLE_DYLIB";
8491       f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
8492     }
8493     if (f & MachO::MH_PIE) {
8494       outs() << " PIE";
8495       f &= ~MachO::MH_PIE;
8496     }
8497     if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
8498       outs() << " NO_REEXPORTED_DYLIBS";
8499       f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
8500     }
8501     if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
8502       outs() << " MH_HAS_TLV_DESCRIPTORS";
8503       f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
8504     }
8505     if (f & MachO::MH_NO_HEAP_EXECUTION) {
8506       outs() << " MH_NO_HEAP_EXECUTION";
8507       f &= ~MachO::MH_NO_HEAP_EXECUTION;
8508     }
8509     if (f & MachO::MH_APP_EXTENSION_SAFE) {
8510       outs() << " APP_EXTENSION_SAFE";
8511       f &= ~MachO::MH_APP_EXTENSION_SAFE;
8512     }
8513     if (f & MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO) {
8514       outs() << " NLIST_OUTOFSYNC_WITH_DYLDINFO";
8515       f &= ~MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO;
8516     }
8517     if (f != 0 || flags == 0)
8518       outs() << format(" 0x%08" PRIx32, f);
8519   } else {
8520     outs() << format(" 0x%08" PRIx32, magic);
8521     outs() << format(" %7d", cputype);
8522     outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8523     outs() << format("  0x%02" PRIx32,
8524                      (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
8525     outs() << format("  %10u", filetype);
8526     outs() << format(" %5u", ncmds);
8527     outs() << format(" %10u", sizeofcmds);
8528     outs() << format(" 0x%08" PRIx32, flags);
8529   }
8530   outs() << "\n";
8531 }
8532 
8533 static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
8534                                 StringRef SegName, uint64_t vmaddr,
8535                                 uint64_t vmsize, uint64_t fileoff,
8536                                 uint64_t filesize, uint32_t maxprot,
8537                                 uint32_t initprot, uint32_t nsects,
8538                                 uint32_t flags, uint32_t object_size,
8539                                 bool verbose) {
8540   uint64_t expected_cmdsize;
8541   if (cmd == MachO::LC_SEGMENT) {
8542     outs() << "      cmd LC_SEGMENT\n";
8543     expected_cmdsize = nsects;
8544     expected_cmdsize *= sizeof(struct MachO::section);
8545     expected_cmdsize += sizeof(struct MachO::segment_command);
8546   } else {
8547     outs() << "      cmd LC_SEGMENT_64\n";
8548     expected_cmdsize = nsects;
8549     expected_cmdsize *= sizeof(struct MachO::section_64);
8550     expected_cmdsize += sizeof(struct MachO::segment_command_64);
8551   }
8552   outs() << "  cmdsize " << cmdsize;
8553   if (cmdsize != expected_cmdsize)
8554     outs() << " Inconsistent size\n";
8555   else
8556     outs() << "\n";
8557   outs() << "  segname " << SegName << "\n";
8558   if (cmd == MachO::LC_SEGMENT_64) {
8559     outs() << "   vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
8560     outs() << "   vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
8561   } else {
8562     outs() << "   vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
8563     outs() << "   vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
8564   }
8565   outs() << "  fileoff " << fileoff;
8566   if (fileoff > object_size)
8567     outs() << " (past end of file)\n";
8568   else
8569     outs() << "\n";
8570   outs() << " filesize " << filesize;
8571   if (fileoff + filesize > object_size)
8572     outs() << " (past end of file)\n";
8573   else
8574     outs() << "\n";
8575   if (verbose) {
8576     if ((maxprot &
8577          ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8578            MachO::VM_PROT_EXECUTE)) != 0)
8579       outs() << "  maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
8580     else {
8581       outs() << "  maxprot ";
8582       outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
8583       outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8584       outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
8585     }
8586     if ((initprot &
8587          ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8588            MachO::VM_PROT_EXECUTE)) != 0)
8589       outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
8590     else {
8591       outs() << " initprot ";
8592       outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
8593       outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8594       outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
8595     }
8596   } else {
8597     outs() << "  maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
8598     outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
8599   }
8600   outs() << "   nsects " << nsects << "\n";
8601   if (verbose) {
8602     outs() << "    flags";
8603     if (flags == 0)
8604       outs() << " (none)\n";
8605     else {
8606       if (flags & MachO::SG_HIGHVM) {
8607         outs() << " HIGHVM";
8608         flags &= ~MachO::SG_HIGHVM;
8609       }
8610       if (flags & MachO::SG_FVMLIB) {
8611         outs() << " FVMLIB";
8612         flags &= ~MachO::SG_FVMLIB;
8613       }
8614       if (flags & MachO::SG_NORELOC) {
8615         outs() << " NORELOC";
8616         flags &= ~MachO::SG_NORELOC;
8617       }
8618       if (flags & MachO::SG_PROTECTED_VERSION_1) {
8619         outs() << " PROTECTED_VERSION_1";
8620         flags &= ~MachO::SG_PROTECTED_VERSION_1;
8621       }
8622       if (flags)
8623         outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
8624       else
8625         outs() << "\n";
8626     }
8627   } else {
8628     outs() << "    flags " << format("0x%" PRIx32, flags) << "\n";
8629   }
8630 }
8631 
8632 static void PrintSection(const char *sectname, const char *segname,
8633                          uint64_t addr, uint64_t size, uint32_t offset,
8634                          uint32_t align, uint32_t reloff, uint32_t nreloc,
8635                          uint32_t flags, uint32_t reserved1, uint32_t reserved2,
8636                          uint32_t cmd, const char *sg_segname,
8637                          uint32_t filetype, uint32_t object_size,
8638                          bool verbose) {
8639   outs() << "Section\n";
8640   outs() << "  sectname " << format("%.16s\n", sectname);
8641   outs() << "   segname " << format("%.16s", segname);
8642   if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
8643     outs() << " (does not match segment)\n";
8644   else
8645     outs() << "\n";
8646   if (cmd == MachO::LC_SEGMENT_64) {
8647     outs() << "      addr " << format("0x%016" PRIx64, addr) << "\n";
8648     outs() << "      size " << format("0x%016" PRIx64, size);
8649   } else {
8650     outs() << "      addr " << format("0x%08" PRIx64, addr) << "\n";
8651     outs() << "      size " << format("0x%08" PRIx64, size);
8652   }
8653   if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
8654     outs() << " (past end of file)\n";
8655   else
8656     outs() << "\n";
8657   outs() << "    offset " << offset;
8658   if (offset > object_size)
8659     outs() << " (past end of file)\n";
8660   else
8661     outs() << "\n";
8662   uint32_t align_shifted = 1 << align;
8663   outs() << "     align 2^" << align << " (" << align_shifted << ")\n";
8664   outs() << "    reloff " << reloff;
8665   if (reloff > object_size)
8666     outs() << " (past end of file)\n";
8667   else
8668     outs() << "\n";
8669   outs() << "    nreloc " << nreloc;
8670   if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
8671     outs() << " (past end of file)\n";
8672   else
8673     outs() << "\n";
8674   uint32_t section_type = flags & MachO::SECTION_TYPE;
8675   if (verbose) {
8676     outs() << "      type";
8677     if (section_type == MachO::S_REGULAR)
8678       outs() << " S_REGULAR\n";
8679     else if (section_type == MachO::S_ZEROFILL)
8680       outs() << " S_ZEROFILL\n";
8681     else if (section_type == MachO::S_CSTRING_LITERALS)
8682       outs() << " S_CSTRING_LITERALS\n";
8683     else if (section_type == MachO::S_4BYTE_LITERALS)
8684       outs() << " S_4BYTE_LITERALS\n";
8685     else if (section_type == MachO::S_8BYTE_LITERALS)
8686       outs() << " S_8BYTE_LITERALS\n";
8687     else if (section_type == MachO::S_16BYTE_LITERALS)
8688       outs() << " S_16BYTE_LITERALS\n";
8689     else if (section_type == MachO::S_LITERAL_POINTERS)
8690       outs() << " S_LITERAL_POINTERS\n";
8691     else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
8692       outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
8693     else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
8694       outs() << " S_LAZY_SYMBOL_POINTERS\n";
8695     else if (section_type == MachO::S_SYMBOL_STUBS)
8696       outs() << " S_SYMBOL_STUBS\n";
8697     else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
8698       outs() << " S_MOD_INIT_FUNC_POINTERS\n";
8699     else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
8700       outs() << " S_MOD_TERM_FUNC_POINTERS\n";
8701     else if (section_type == MachO::S_COALESCED)
8702       outs() << " S_COALESCED\n";
8703     else if (section_type == MachO::S_INTERPOSING)
8704       outs() << " S_INTERPOSING\n";
8705     else if (section_type == MachO::S_DTRACE_DOF)
8706       outs() << " S_DTRACE_DOF\n";
8707     else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
8708       outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
8709     else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
8710       outs() << " S_THREAD_LOCAL_REGULAR\n";
8711     else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
8712       outs() << " S_THREAD_LOCAL_ZEROFILL\n";
8713     else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
8714       outs() << " S_THREAD_LOCAL_VARIABLES\n";
8715     else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8716       outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
8717     else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
8718       outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
8719     else
8720       outs() << format("0x%08" PRIx32, section_type) << "\n";
8721     outs() << "attributes";
8722     uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
8723     if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
8724       outs() << " PURE_INSTRUCTIONS";
8725     if (section_attributes & MachO::S_ATTR_NO_TOC)
8726       outs() << " NO_TOC";
8727     if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
8728       outs() << " STRIP_STATIC_SYMS";
8729     if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
8730       outs() << " NO_DEAD_STRIP";
8731     if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
8732       outs() << " LIVE_SUPPORT";
8733     if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
8734       outs() << " SELF_MODIFYING_CODE";
8735     if (section_attributes & MachO::S_ATTR_DEBUG)
8736       outs() << " DEBUG";
8737     if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
8738       outs() << " SOME_INSTRUCTIONS";
8739     if (section_attributes & MachO::S_ATTR_EXT_RELOC)
8740       outs() << " EXT_RELOC";
8741     if (section_attributes & MachO::S_ATTR_LOC_RELOC)
8742       outs() << " LOC_RELOC";
8743     if (section_attributes == 0)
8744       outs() << " (none)";
8745     outs() << "\n";
8746   } else
8747     outs() << "     flags " << format("0x%08" PRIx32, flags) << "\n";
8748   outs() << " reserved1 " << reserved1;
8749   if (section_type == MachO::S_SYMBOL_STUBS ||
8750       section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
8751       section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
8752       section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
8753       section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8754     outs() << " (index into indirect symbol table)\n";
8755   else
8756     outs() << "\n";
8757   outs() << " reserved2 " << reserved2;
8758   if (section_type == MachO::S_SYMBOL_STUBS)
8759     outs() << " (size of stubs)\n";
8760   else
8761     outs() << "\n";
8762 }
8763 
8764 static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
8765                                    uint32_t object_size) {
8766   outs() << "     cmd LC_SYMTAB\n";
8767   outs() << " cmdsize " << st.cmdsize;
8768   if (st.cmdsize != sizeof(struct MachO::symtab_command))
8769     outs() << " Incorrect size\n";
8770   else
8771     outs() << "\n";
8772   outs() << "  symoff " << st.symoff;
8773   if (st.symoff > object_size)
8774     outs() << " (past end of file)\n";
8775   else
8776     outs() << "\n";
8777   outs() << "   nsyms " << st.nsyms;
8778   uint64_t big_size;
8779   if (Is64Bit) {
8780     big_size = st.nsyms;
8781     big_size *= sizeof(struct MachO::nlist_64);
8782     big_size += st.symoff;
8783     if (big_size > object_size)
8784       outs() << " (past end of file)\n";
8785     else
8786       outs() << "\n";
8787   } else {
8788     big_size = st.nsyms;
8789     big_size *= sizeof(struct MachO::nlist);
8790     big_size += st.symoff;
8791     if (big_size > object_size)
8792       outs() << " (past end of file)\n";
8793     else
8794       outs() << "\n";
8795   }
8796   outs() << "  stroff " << st.stroff;
8797   if (st.stroff > object_size)
8798     outs() << " (past end of file)\n";
8799   else
8800     outs() << "\n";
8801   outs() << " strsize " << st.strsize;
8802   big_size = st.stroff;
8803   big_size += st.strsize;
8804   if (big_size > object_size)
8805     outs() << " (past end of file)\n";
8806   else
8807     outs() << "\n";
8808 }
8809 
8810 static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
8811                                      uint32_t nsyms, uint32_t object_size,
8812                                      bool Is64Bit) {
8813   outs() << "            cmd LC_DYSYMTAB\n";
8814   outs() << "        cmdsize " << dyst.cmdsize;
8815   if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
8816     outs() << " Incorrect size\n";
8817   else
8818     outs() << "\n";
8819   outs() << "      ilocalsym " << dyst.ilocalsym;
8820   if (dyst.ilocalsym > nsyms)
8821     outs() << " (greater than the number of symbols)\n";
8822   else
8823     outs() << "\n";
8824   outs() << "      nlocalsym " << dyst.nlocalsym;
8825   uint64_t big_size;
8826   big_size = dyst.ilocalsym;
8827   big_size += dyst.nlocalsym;
8828   if (big_size > nsyms)
8829     outs() << " (past the end of the symbol table)\n";
8830   else
8831     outs() << "\n";
8832   outs() << "     iextdefsym " << dyst.iextdefsym;
8833   if (dyst.iextdefsym > nsyms)
8834     outs() << " (greater than the number of symbols)\n";
8835   else
8836     outs() << "\n";
8837   outs() << "     nextdefsym " << dyst.nextdefsym;
8838   big_size = dyst.iextdefsym;
8839   big_size += dyst.nextdefsym;
8840   if (big_size > nsyms)
8841     outs() << " (past the end of the symbol table)\n";
8842   else
8843     outs() << "\n";
8844   outs() << "      iundefsym " << dyst.iundefsym;
8845   if (dyst.iundefsym > nsyms)
8846     outs() << " (greater than the number of symbols)\n";
8847   else
8848     outs() << "\n";
8849   outs() << "      nundefsym " << dyst.nundefsym;
8850   big_size = dyst.iundefsym;
8851   big_size += dyst.nundefsym;
8852   if (big_size > nsyms)
8853     outs() << " (past the end of the symbol table)\n";
8854   else
8855     outs() << "\n";
8856   outs() << "         tocoff " << dyst.tocoff;
8857   if (dyst.tocoff > object_size)
8858     outs() << " (past end of file)\n";
8859   else
8860     outs() << "\n";
8861   outs() << "           ntoc " << dyst.ntoc;
8862   big_size = dyst.ntoc;
8863   big_size *= sizeof(struct MachO::dylib_table_of_contents);
8864   big_size += dyst.tocoff;
8865   if (big_size > object_size)
8866     outs() << " (past end of file)\n";
8867   else
8868     outs() << "\n";
8869   outs() << "      modtaboff " << dyst.modtaboff;
8870   if (dyst.modtaboff > object_size)
8871     outs() << " (past end of file)\n";
8872   else
8873     outs() << "\n";
8874   outs() << "        nmodtab " << dyst.nmodtab;
8875   uint64_t modtabend;
8876   if (Is64Bit) {
8877     modtabend = dyst.nmodtab;
8878     modtabend *= sizeof(struct MachO::dylib_module_64);
8879     modtabend += dyst.modtaboff;
8880   } else {
8881     modtabend = dyst.nmodtab;
8882     modtabend *= sizeof(struct MachO::dylib_module);
8883     modtabend += dyst.modtaboff;
8884   }
8885   if (modtabend > object_size)
8886     outs() << " (past end of file)\n";
8887   else
8888     outs() << "\n";
8889   outs() << "   extrefsymoff " << dyst.extrefsymoff;
8890   if (dyst.extrefsymoff > object_size)
8891     outs() << " (past end of file)\n";
8892   else
8893     outs() << "\n";
8894   outs() << "    nextrefsyms " << dyst.nextrefsyms;
8895   big_size = dyst.nextrefsyms;
8896   big_size *= sizeof(struct MachO::dylib_reference);
8897   big_size += dyst.extrefsymoff;
8898   if (big_size > object_size)
8899     outs() << " (past end of file)\n";
8900   else
8901     outs() << "\n";
8902   outs() << " indirectsymoff " << dyst.indirectsymoff;
8903   if (dyst.indirectsymoff > object_size)
8904     outs() << " (past end of file)\n";
8905   else
8906     outs() << "\n";
8907   outs() << "  nindirectsyms " << dyst.nindirectsyms;
8908   big_size = dyst.nindirectsyms;
8909   big_size *= sizeof(uint32_t);
8910   big_size += dyst.indirectsymoff;
8911   if (big_size > object_size)
8912     outs() << " (past end of file)\n";
8913   else
8914     outs() << "\n";
8915   outs() << "      extreloff " << dyst.extreloff;
8916   if (dyst.extreloff > object_size)
8917     outs() << " (past end of file)\n";
8918   else
8919     outs() << "\n";
8920   outs() << "        nextrel " << dyst.nextrel;
8921   big_size = dyst.nextrel;
8922   big_size *= sizeof(struct MachO::relocation_info);
8923   big_size += dyst.extreloff;
8924   if (big_size > object_size)
8925     outs() << " (past end of file)\n";
8926   else
8927     outs() << "\n";
8928   outs() << "      locreloff " << dyst.locreloff;
8929   if (dyst.locreloff > object_size)
8930     outs() << " (past end of file)\n";
8931   else
8932     outs() << "\n";
8933   outs() << "        nlocrel " << dyst.nlocrel;
8934   big_size = dyst.nlocrel;
8935   big_size *= sizeof(struct MachO::relocation_info);
8936   big_size += dyst.locreloff;
8937   if (big_size > object_size)
8938     outs() << " (past end of file)\n";
8939   else
8940     outs() << "\n";
8941 }
8942 
8943 static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
8944                                      uint32_t object_size) {
8945   if (dc.cmd == MachO::LC_DYLD_INFO)
8946     outs() << "            cmd LC_DYLD_INFO\n";
8947   else
8948     outs() << "            cmd LC_DYLD_INFO_ONLY\n";
8949   outs() << "        cmdsize " << dc.cmdsize;
8950   if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
8951     outs() << " Incorrect size\n";
8952   else
8953     outs() << "\n";
8954   outs() << "     rebase_off " << dc.rebase_off;
8955   if (dc.rebase_off > object_size)
8956     outs() << " (past end of file)\n";
8957   else
8958     outs() << "\n";
8959   outs() << "    rebase_size " << dc.rebase_size;
8960   uint64_t big_size;
8961   big_size = dc.rebase_off;
8962   big_size += dc.rebase_size;
8963   if (big_size > object_size)
8964     outs() << " (past end of file)\n";
8965   else
8966     outs() << "\n";
8967   outs() << "       bind_off " << dc.bind_off;
8968   if (dc.bind_off > object_size)
8969     outs() << " (past end of file)\n";
8970   else
8971     outs() << "\n";
8972   outs() << "      bind_size " << dc.bind_size;
8973   big_size = dc.bind_off;
8974   big_size += dc.bind_size;
8975   if (big_size > object_size)
8976     outs() << " (past end of file)\n";
8977   else
8978     outs() << "\n";
8979   outs() << "  weak_bind_off " << dc.weak_bind_off;
8980   if (dc.weak_bind_off > object_size)
8981     outs() << " (past end of file)\n";
8982   else
8983     outs() << "\n";
8984   outs() << " weak_bind_size " << dc.weak_bind_size;
8985   big_size = dc.weak_bind_off;
8986   big_size += dc.weak_bind_size;
8987   if (big_size > object_size)
8988     outs() << " (past end of file)\n";
8989   else
8990     outs() << "\n";
8991   outs() << "  lazy_bind_off " << dc.lazy_bind_off;
8992   if (dc.lazy_bind_off > object_size)
8993     outs() << " (past end of file)\n";
8994   else
8995     outs() << "\n";
8996   outs() << " lazy_bind_size " << dc.lazy_bind_size;
8997   big_size = dc.lazy_bind_off;
8998   big_size += dc.lazy_bind_size;
8999   if (big_size > object_size)
9000     outs() << " (past end of file)\n";
9001   else
9002     outs() << "\n";
9003   outs() << "     export_off " << dc.export_off;
9004   if (dc.export_off > object_size)
9005     outs() << " (past end of file)\n";
9006   else
9007     outs() << "\n";
9008   outs() << "    export_size " << dc.export_size;
9009   big_size = dc.export_off;
9010   big_size += dc.export_size;
9011   if (big_size > object_size)
9012     outs() << " (past end of file)\n";
9013   else
9014     outs() << "\n";
9015 }
9016 
9017 static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
9018                                  const char *Ptr) {
9019   if (dyld.cmd == MachO::LC_ID_DYLINKER)
9020     outs() << "          cmd LC_ID_DYLINKER\n";
9021   else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
9022     outs() << "          cmd LC_LOAD_DYLINKER\n";
9023   else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
9024     outs() << "          cmd LC_DYLD_ENVIRONMENT\n";
9025   else
9026     outs() << "          cmd ?(" << dyld.cmd << ")\n";
9027   outs() << "      cmdsize " << dyld.cmdsize;
9028   if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
9029     outs() << " Incorrect size\n";
9030   else
9031     outs() << "\n";
9032   if (dyld.name >= dyld.cmdsize)
9033     outs() << "         name ?(bad offset " << dyld.name << ")\n";
9034   else {
9035     const char *P = (const char *)(Ptr) + dyld.name;
9036     outs() << "         name " << P << " (offset " << dyld.name << ")\n";
9037   }
9038 }
9039 
9040 static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
9041   outs() << "     cmd LC_UUID\n";
9042   outs() << " cmdsize " << uuid.cmdsize;
9043   if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
9044     outs() << " Incorrect size\n";
9045   else
9046     outs() << "\n";
9047   outs() << "    uuid ";
9048   for (int i = 0; i < 16; ++i) {
9049     outs() << format("%02" PRIX32, uuid.uuid[i]);
9050     if (i == 3 || i == 5 || i == 7 || i == 9)
9051       outs() << "-";
9052   }
9053   outs() << "\n";
9054 }
9055 
9056 static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
9057   outs() << "          cmd LC_RPATH\n";
9058   outs() << "      cmdsize " << rpath.cmdsize;
9059   if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
9060     outs() << " Incorrect size\n";
9061   else
9062     outs() << "\n";
9063   if (rpath.path >= rpath.cmdsize)
9064     outs() << "         path ?(bad offset " << rpath.path << ")\n";
9065   else {
9066     const char *P = (const char *)(Ptr) + rpath.path;
9067     outs() << "         path " << P << " (offset " << rpath.path << ")\n";
9068   }
9069 }
9070 
9071 static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
9072   StringRef LoadCmdName;
9073   switch (vd.cmd) {
9074   case MachO::LC_VERSION_MIN_MACOSX:
9075     LoadCmdName = "LC_VERSION_MIN_MACOSX";
9076     break;
9077   case MachO::LC_VERSION_MIN_IPHONEOS:
9078     LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
9079     break;
9080   case MachO::LC_VERSION_MIN_TVOS:
9081     LoadCmdName = "LC_VERSION_MIN_TVOS";
9082     break;
9083   case MachO::LC_VERSION_MIN_WATCHOS:
9084     LoadCmdName = "LC_VERSION_MIN_WATCHOS";
9085     break;
9086   default:
9087     llvm_unreachable("Unknown version min load command");
9088   }
9089 
9090   outs() << "      cmd " << LoadCmdName << '\n';
9091   outs() << "  cmdsize " << vd.cmdsize;
9092   if (vd.cmdsize != sizeof(struct MachO::version_min_command))
9093     outs() << " Incorrect size\n";
9094   else
9095     outs() << "\n";
9096   outs() << "  version "
9097          << MachOObjectFile::getVersionMinMajor(vd, false) << "."
9098          << MachOObjectFile::getVersionMinMinor(vd, false);
9099   uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
9100   if (Update != 0)
9101     outs() << "." << Update;
9102   outs() << "\n";
9103   if (vd.sdk == 0)
9104     outs() << "      sdk n/a";
9105   else {
9106     outs() << "      sdk "
9107            << MachOObjectFile::getVersionMinMajor(vd, true) << "."
9108            << MachOObjectFile::getVersionMinMinor(vd, true);
9109   }
9110   Update = MachOObjectFile::getVersionMinUpdate(vd, true);
9111   if (Update != 0)
9112     outs() << "." << Update;
9113   outs() << "\n";
9114 }
9115 
9116 static void PrintNoteLoadCommand(MachO::note_command Nt) {
9117   outs() << "       cmd LC_NOTE\n";
9118   outs() << "   cmdsize " << Nt.cmdsize;
9119   if (Nt.cmdsize != sizeof(struct MachO::note_command))
9120     outs() << " Incorrect size\n";
9121   else
9122     outs() << "\n";
9123   const char *d = Nt.data_owner;
9124   outs() << "data_owner " << format("%.16s\n", d);
9125   outs() << "    offset " << Nt.offset << "\n";
9126   outs() << "      size " << Nt.size << "\n";
9127 }
9128 
9129 static void PrintBuildToolVersion(MachO::build_tool_version bv) {
9130   outs() << "      tool " << MachOObjectFile::getBuildTool(bv.tool) << "\n";
9131   outs() << "   version " << MachOObjectFile::getVersionString(bv.version)
9132          << "\n";
9133 }
9134 
9135 static void PrintBuildVersionLoadCommand(const MachOObjectFile *obj,
9136                                          MachO::build_version_command bd) {
9137   outs() << "       cmd LC_BUILD_VERSION\n";
9138   outs() << "   cmdsize " << bd.cmdsize;
9139   if (bd.cmdsize !=
9140       sizeof(struct MachO::build_version_command) +
9141           bd.ntools * sizeof(struct MachO::build_tool_version))
9142     outs() << " Incorrect size\n";
9143   else
9144     outs() << "\n";
9145   outs() << "  platform " << MachOObjectFile::getBuildPlatform(bd.platform)
9146          << "\n";
9147   if (bd.sdk)
9148     outs() << "       sdk " << MachOObjectFile::getVersionString(bd.sdk)
9149            << "\n";
9150   else
9151     outs() << "       sdk n/a\n";
9152   outs() << "     minos " << MachOObjectFile::getVersionString(bd.minos)
9153          << "\n";
9154   outs() << "    ntools " << bd.ntools << "\n";
9155   for (unsigned i = 0; i < bd.ntools; ++i) {
9156     MachO::build_tool_version bv = obj->getBuildToolVersion(i);
9157     PrintBuildToolVersion(bv);
9158   }
9159 }
9160 
9161 static void PrintSourceVersionCommand(MachO::source_version_command sd) {
9162   outs() << "      cmd LC_SOURCE_VERSION\n";
9163   outs() << "  cmdsize " << sd.cmdsize;
9164   if (sd.cmdsize != sizeof(struct MachO::source_version_command))
9165     outs() << " Incorrect size\n";
9166   else
9167     outs() << "\n";
9168   uint64_t a = (sd.version >> 40) & 0xffffff;
9169   uint64_t b = (sd.version >> 30) & 0x3ff;
9170   uint64_t c = (sd.version >> 20) & 0x3ff;
9171   uint64_t d = (sd.version >> 10) & 0x3ff;
9172   uint64_t e = sd.version & 0x3ff;
9173   outs() << "  version " << a << "." << b;
9174   if (e != 0)
9175     outs() << "." << c << "." << d << "." << e;
9176   else if (d != 0)
9177     outs() << "." << c << "." << d;
9178   else if (c != 0)
9179     outs() << "." << c;
9180   outs() << "\n";
9181 }
9182 
9183 static void PrintEntryPointCommand(MachO::entry_point_command ep) {
9184   outs() << "       cmd LC_MAIN\n";
9185   outs() << "   cmdsize " << ep.cmdsize;
9186   if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
9187     outs() << " Incorrect size\n";
9188   else
9189     outs() << "\n";
9190   outs() << "  entryoff " << ep.entryoff << "\n";
9191   outs() << " stacksize " << ep.stacksize << "\n";
9192 }
9193 
9194 static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
9195                                        uint32_t object_size) {
9196   outs() << "          cmd LC_ENCRYPTION_INFO\n";
9197   outs() << "      cmdsize " << ec.cmdsize;
9198   if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
9199     outs() << " Incorrect size\n";
9200   else
9201     outs() << "\n";
9202   outs() << "     cryptoff " << ec.cryptoff;
9203   if (ec.cryptoff > object_size)
9204     outs() << " (past end of file)\n";
9205   else
9206     outs() << "\n";
9207   outs() << "    cryptsize " << ec.cryptsize;
9208   if (ec.cryptsize > object_size)
9209     outs() << " (past end of file)\n";
9210   else
9211     outs() << "\n";
9212   outs() << "      cryptid " << ec.cryptid << "\n";
9213 }
9214 
9215 static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
9216                                          uint32_t object_size) {
9217   outs() << "          cmd LC_ENCRYPTION_INFO_64\n";
9218   outs() << "      cmdsize " << ec.cmdsize;
9219   if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
9220     outs() << " Incorrect size\n";
9221   else
9222     outs() << "\n";
9223   outs() << "     cryptoff " << ec.cryptoff;
9224   if (ec.cryptoff > object_size)
9225     outs() << " (past end of file)\n";
9226   else
9227     outs() << "\n";
9228   outs() << "    cryptsize " << ec.cryptsize;
9229   if (ec.cryptsize > object_size)
9230     outs() << " (past end of file)\n";
9231   else
9232     outs() << "\n";
9233   outs() << "      cryptid " << ec.cryptid << "\n";
9234   outs() << "          pad " << ec.pad << "\n";
9235 }
9236 
9237 static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
9238                                      const char *Ptr) {
9239   outs() << "     cmd LC_LINKER_OPTION\n";
9240   outs() << " cmdsize " << lo.cmdsize;
9241   if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
9242     outs() << " Incorrect size\n";
9243   else
9244     outs() << "\n";
9245   outs() << "   count " << lo.count << "\n";
9246   const char *string = Ptr + sizeof(struct MachO::linker_option_command);
9247   uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
9248   uint32_t i = 0;
9249   while (left > 0) {
9250     while (*string == '\0' && left > 0) {
9251       string++;
9252       left--;
9253     }
9254     if (left > 0) {
9255       i++;
9256       outs() << "  string #" << i << " " << format("%.*s\n", left, string);
9257       uint32_t NullPos = StringRef(string, left).find('\0');
9258       uint32_t len = std::min(NullPos, left) + 1;
9259       string += len;
9260       left -= len;
9261     }
9262   }
9263   if (lo.count != i)
9264     outs() << "   count " << lo.count << " does not match number of strings "
9265            << i << "\n";
9266 }
9267 
9268 static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
9269                                      const char *Ptr) {
9270   outs() << "          cmd LC_SUB_FRAMEWORK\n";
9271   outs() << "      cmdsize " << sub.cmdsize;
9272   if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
9273     outs() << " Incorrect size\n";
9274   else
9275     outs() << "\n";
9276   if (sub.umbrella < sub.cmdsize) {
9277     const char *P = Ptr + sub.umbrella;
9278     outs() << "     umbrella " << P << " (offset " << sub.umbrella << ")\n";
9279   } else {
9280     outs() << "     umbrella ?(bad offset " << sub.umbrella << ")\n";
9281   }
9282 }
9283 
9284 static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
9285                                     const char *Ptr) {
9286   outs() << "          cmd LC_SUB_UMBRELLA\n";
9287   outs() << "      cmdsize " << sub.cmdsize;
9288   if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
9289     outs() << " Incorrect size\n";
9290   else
9291     outs() << "\n";
9292   if (sub.sub_umbrella < sub.cmdsize) {
9293     const char *P = Ptr + sub.sub_umbrella;
9294     outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
9295   } else {
9296     outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
9297   }
9298 }
9299 
9300 static void PrintSubLibraryCommand(MachO::sub_library_command sub,
9301                                    const char *Ptr) {
9302   outs() << "          cmd LC_SUB_LIBRARY\n";
9303   outs() << "      cmdsize " << sub.cmdsize;
9304   if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
9305     outs() << " Incorrect size\n";
9306   else
9307     outs() << "\n";
9308   if (sub.sub_library < sub.cmdsize) {
9309     const char *P = Ptr + sub.sub_library;
9310     outs() << "  sub_library " << P << " (offset " << sub.sub_library << ")\n";
9311   } else {
9312     outs() << "  sub_library ?(bad offset " << sub.sub_library << ")\n";
9313   }
9314 }
9315 
9316 static void PrintSubClientCommand(MachO::sub_client_command sub,
9317                                   const char *Ptr) {
9318   outs() << "          cmd LC_SUB_CLIENT\n";
9319   outs() << "      cmdsize " << sub.cmdsize;
9320   if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
9321     outs() << " Incorrect size\n";
9322   else
9323     outs() << "\n";
9324   if (sub.client < sub.cmdsize) {
9325     const char *P = Ptr + sub.client;
9326     outs() << "       client " << P << " (offset " << sub.client << ")\n";
9327   } else {
9328     outs() << "       client ?(bad offset " << sub.client << ")\n";
9329   }
9330 }
9331 
9332 static void PrintRoutinesCommand(MachO::routines_command r) {
9333   outs() << "          cmd LC_ROUTINES\n";
9334   outs() << "      cmdsize " << r.cmdsize;
9335   if (r.cmdsize != sizeof(struct MachO::routines_command))
9336     outs() << " Incorrect size\n";
9337   else
9338     outs() << "\n";
9339   outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
9340   outs() << "  init_module " << r.init_module << "\n";
9341   outs() << "    reserved1 " << r.reserved1 << "\n";
9342   outs() << "    reserved2 " << r.reserved2 << "\n";
9343   outs() << "    reserved3 " << r.reserved3 << "\n";
9344   outs() << "    reserved4 " << r.reserved4 << "\n";
9345   outs() << "    reserved5 " << r.reserved5 << "\n";
9346   outs() << "    reserved6 " << r.reserved6 << "\n";
9347 }
9348 
9349 static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
9350   outs() << "          cmd LC_ROUTINES_64\n";
9351   outs() << "      cmdsize " << r.cmdsize;
9352   if (r.cmdsize != sizeof(struct MachO::routines_command_64))
9353     outs() << " Incorrect size\n";
9354   else
9355     outs() << "\n";
9356   outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
9357   outs() << "  init_module " << r.init_module << "\n";
9358   outs() << "    reserved1 " << r.reserved1 << "\n";
9359   outs() << "    reserved2 " << r.reserved2 << "\n";
9360   outs() << "    reserved3 " << r.reserved3 << "\n";
9361   outs() << "    reserved4 " << r.reserved4 << "\n";
9362   outs() << "    reserved5 " << r.reserved5 << "\n";
9363   outs() << "    reserved6 " << r.reserved6 << "\n";
9364 }
9365 
9366 static void Print_x86_thread_state32_t(MachO::x86_thread_state32_t &cpu32) {
9367   outs() << "\t    eax " << format("0x%08" PRIx32, cpu32.eax);
9368   outs() << " ebx    " << format("0x%08" PRIx32, cpu32.ebx);
9369   outs() << " ecx " << format("0x%08" PRIx32, cpu32.ecx);
9370   outs() << " edx " << format("0x%08" PRIx32, cpu32.edx) << "\n";
9371   outs() << "\t    edi " << format("0x%08" PRIx32, cpu32.edi);
9372   outs() << " esi    " << format("0x%08" PRIx32, cpu32.esi);
9373   outs() << " ebp " << format("0x%08" PRIx32, cpu32.ebp);
9374   outs() << " esp " << format("0x%08" PRIx32, cpu32.esp) << "\n";
9375   outs() << "\t    ss  " << format("0x%08" PRIx32, cpu32.ss);
9376   outs() << " eflags " << format("0x%08" PRIx32, cpu32.eflags);
9377   outs() << " eip " << format("0x%08" PRIx32, cpu32.eip);
9378   outs() << " cs  " << format("0x%08" PRIx32, cpu32.cs) << "\n";
9379   outs() << "\t    ds  " << format("0x%08" PRIx32, cpu32.ds);
9380   outs() << " es     " << format("0x%08" PRIx32, cpu32.es);
9381   outs() << " fs  " << format("0x%08" PRIx32, cpu32.fs);
9382   outs() << " gs  " << format("0x%08" PRIx32, cpu32.gs) << "\n";
9383 }
9384 
9385 static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
9386   outs() << "   rax  " << format("0x%016" PRIx64, cpu64.rax);
9387   outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
9388   outs() << " rcx  " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
9389   outs() << "   rdx  " << format("0x%016" PRIx64, cpu64.rdx);
9390   outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
9391   outs() << " rsi  " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
9392   outs() << "   rbp  " << format("0x%016" PRIx64, cpu64.rbp);
9393   outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
9394   outs() << " r8   " << format("0x%016" PRIx64, cpu64.r8) << "\n";
9395   outs() << "    r9  " << format("0x%016" PRIx64, cpu64.r9);
9396   outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
9397   outs() << " r11  " << format("0x%016" PRIx64, cpu64.r11) << "\n";
9398   outs() << "   r12  " << format("0x%016" PRIx64, cpu64.r12);
9399   outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
9400   outs() << " r14  " << format("0x%016" PRIx64, cpu64.r14) << "\n";
9401   outs() << "   r15  " << format("0x%016" PRIx64, cpu64.r15);
9402   outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
9403   outs() << "rflags  " << format("0x%016" PRIx64, cpu64.rflags);
9404   outs() << " cs  " << format("0x%016" PRIx64, cpu64.cs);
9405   outs() << " fs   " << format("0x%016" PRIx64, cpu64.fs) << "\n";
9406   outs() << "    gs  " << format("0x%016" PRIx64, cpu64.gs) << "\n";
9407 }
9408 
9409 static void Print_mmst_reg(MachO::mmst_reg_t &r) {
9410   uint32_t f;
9411   outs() << "\t      mmst_reg  ";
9412   for (f = 0; f < 10; f++)
9413     outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
9414   outs() << "\n";
9415   outs() << "\t      mmst_rsrv ";
9416   for (f = 0; f < 6; f++)
9417     outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
9418   outs() << "\n";
9419 }
9420 
9421 static void Print_xmm_reg(MachO::xmm_reg_t &r) {
9422   uint32_t f;
9423   outs() << "\t      xmm_reg ";
9424   for (f = 0; f < 16; f++)
9425     outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
9426   outs() << "\n";
9427 }
9428 
9429 static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
9430   outs() << "\t    fpu_reserved[0] " << fpu.fpu_reserved[0];
9431   outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
9432   outs() << "\t    control: invalid " << fpu.fpu_fcw.invalid;
9433   outs() << " denorm " << fpu.fpu_fcw.denorm;
9434   outs() << " zdiv " << fpu.fpu_fcw.zdiv;
9435   outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
9436   outs() << " undfl " << fpu.fpu_fcw.undfl;
9437   outs() << " precis " << fpu.fpu_fcw.precis << "\n";
9438   outs() << "\t\t     pc ";
9439   if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
9440     outs() << "FP_PREC_24B ";
9441   else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
9442     outs() << "FP_PREC_53B ";
9443   else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
9444     outs() << "FP_PREC_64B ";
9445   else
9446     outs() << fpu.fpu_fcw.pc << " ";
9447   outs() << "rc ";
9448   if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
9449     outs() << "FP_RND_NEAR ";
9450   else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
9451     outs() << "FP_RND_DOWN ";
9452   else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
9453     outs() << "FP_RND_UP ";
9454   else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
9455     outs() << "FP_CHOP ";
9456   outs() << "\n";
9457   outs() << "\t    status: invalid " << fpu.fpu_fsw.invalid;
9458   outs() << " denorm " << fpu.fpu_fsw.denorm;
9459   outs() << " zdiv " << fpu.fpu_fsw.zdiv;
9460   outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
9461   outs() << " undfl " << fpu.fpu_fsw.undfl;
9462   outs() << " precis " << fpu.fpu_fsw.precis;
9463   outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
9464   outs() << "\t            errsumm " << fpu.fpu_fsw.errsumm;
9465   outs() << " c0 " << fpu.fpu_fsw.c0;
9466   outs() << " c1 " << fpu.fpu_fsw.c1;
9467   outs() << " c2 " << fpu.fpu_fsw.c2;
9468   outs() << " tos " << fpu.fpu_fsw.tos;
9469   outs() << " c3 " << fpu.fpu_fsw.c3;
9470   outs() << " busy " << fpu.fpu_fsw.busy << "\n";
9471   outs() << "\t    fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
9472   outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
9473   outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
9474   outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
9475   outs() << "\t    fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
9476   outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
9477   outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
9478   outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
9479   outs() << "\t    fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
9480   outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
9481   outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
9482   outs() << "\n";
9483   outs() << "\t    fpu_stmm0:\n";
9484   Print_mmst_reg(fpu.fpu_stmm0);
9485   outs() << "\t    fpu_stmm1:\n";
9486   Print_mmst_reg(fpu.fpu_stmm1);
9487   outs() << "\t    fpu_stmm2:\n";
9488   Print_mmst_reg(fpu.fpu_stmm2);
9489   outs() << "\t    fpu_stmm3:\n";
9490   Print_mmst_reg(fpu.fpu_stmm3);
9491   outs() << "\t    fpu_stmm4:\n";
9492   Print_mmst_reg(fpu.fpu_stmm4);
9493   outs() << "\t    fpu_stmm5:\n";
9494   Print_mmst_reg(fpu.fpu_stmm5);
9495   outs() << "\t    fpu_stmm6:\n";
9496   Print_mmst_reg(fpu.fpu_stmm6);
9497   outs() << "\t    fpu_stmm7:\n";
9498   Print_mmst_reg(fpu.fpu_stmm7);
9499   outs() << "\t    fpu_xmm0:\n";
9500   Print_xmm_reg(fpu.fpu_xmm0);
9501   outs() << "\t    fpu_xmm1:\n";
9502   Print_xmm_reg(fpu.fpu_xmm1);
9503   outs() << "\t    fpu_xmm2:\n";
9504   Print_xmm_reg(fpu.fpu_xmm2);
9505   outs() << "\t    fpu_xmm3:\n";
9506   Print_xmm_reg(fpu.fpu_xmm3);
9507   outs() << "\t    fpu_xmm4:\n";
9508   Print_xmm_reg(fpu.fpu_xmm4);
9509   outs() << "\t    fpu_xmm5:\n";
9510   Print_xmm_reg(fpu.fpu_xmm5);
9511   outs() << "\t    fpu_xmm6:\n";
9512   Print_xmm_reg(fpu.fpu_xmm6);
9513   outs() << "\t    fpu_xmm7:\n";
9514   Print_xmm_reg(fpu.fpu_xmm7);
9515   outs() << "\t    fpu_xmm8:\n";
9516   Print_xmm_reg(fpu.fpu_xmm8);
9517   outs() << "\t    fpu_xmm9:\n";
9518   Print_xmm_reg(fpu.fpu_xmm9);
9519   outs() << "\t    fpu_xmm10:\n";
9520   Print_xmm_reg(fpu.fpu_xmm10);
9521   outs() << "\t    fpu_xmm11:\n";
9522   Print_xmm_reg(fpu.fpu_xmm11);
9523   outs() << "\t    fpu_xmm12:\n";
9524   Print_xmm_reg(fpu.fpu_xmm12);
9525   outs() << "\t    fpu_xmm13:\n";
9526   Print_xmm_reg(fpu.fpu_xmm13);
9527   outs() << "\t    fpu_xmm14:\n";
9528   Print_xmm_reg(fpu.fpu_xmm14);
9529   outs() << "\t    fpu_xmm15:\n";
9530   Print_xmm_reg(fpu.fpu_xmm15);
9531   outs() << "\t    fpu_rsrv4:\n";
9532   for (uint32_t f = 0; f < 6; f++) {
9533     outs() << "\t            ";
9534     for (uint32_t g = 0; g < 16; g++)
9535       outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
9536     outs() << "\n";
9537   }
9538   outs() << "\t    fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
9539   outs() << "\n";
9540 }
9541 
9542 static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
9543   outs() << "\t    trapno " << format("0x%08" PRIx32, exc64.trapno);
9544   outs() << " err " << format("0x%08" PRIx32, exc64.err);
9545   outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
9546 }
9547 
9548 static void Print_arm_thread_state32_t(MachO::arm_thread_state32_t &cpu32) {
9549   outs() << "\t    r0  " << format("0x%08" PRIx32, cpu32.r[0]);
9550   outs() << " r1     "   << format("0x%08" PRIx32, cpu32.r[1]);
9551   outs() << " r2  "      << format("0x%08" PRIx32, cpu32.r[2]);
9552   outs() << " r3  "      << format("0x%08" PRIx32, cpu32.r[3]) << "\n";
9553   outs() << "\t    r4  " << format("0x%08" PRIx32, cpu32.r[4]);
9554   outs() << " r5     "   << format("0x%08" PRIx32, cpu32.r[5]);
9555   outs() << " r6  "      << format("0x%08" PRIx32, cpu32.r[6]);
9556   outs() << " r7  "      << format("0x%08" PRIx32, cpu32.r[7]) << "\n";
9557   outs() << "\t    r8  " << format("0x%08" PRIx32, cpu32.r[8]);
9558   outs() << " r9     "   << format("0x%08" PRIx32, cpu32.r[9]);
9559   outs() << " r10 "      << format("0x%08" PRIx32, cpu32.r[10]);
9560   outs() << " r11 "      << format("0x%08" PRIx32, cpu32.r[11]) << "\n";
9561   outs() << "\t    r12 " << format("0x%08" PRIx32, cpu32.r[12]);
9562   outs() << " sp     "   << format("0x%08" PRIx32, cpu32.sp);
9563   outs() << " lr  "      << format("0x%08" PRIx32, cpu32.lr);
9564   outs() << " pc  "      << format("0x%08" PRIx32, cpu32.pc) << "\n";
9565   outs() << "\t   cpsr " << format("0x%08" PRIx32, cpu32.cpsr) << "\n";
9566 }
9567 
9568 static void Print_arm_thread_state64_t(MachO::arm_thread_state64_t &cpu64) {
9569   outs() << "\t    x0  " << format("0x%016" PRIx64, cpu64.x[0]);
9570   outs() << " x1  "      << format("0x%016" PRIx64, cpu64.x[1]);
9571   outs() << " x2  "      << format("0x%016" PRIx64, cpu64.x[2]) << "\n";
9572   outs() << "\t    x3  " << format("0x%016" PRIx64, cpu64.x[3]);
9573   outs() << " x4  "      << format("0x%016" PRIx64, cpu64.x[4]);
9574   outs() << " x5  "      << format("0x%016" PRIx64, cpu64.x[5]) << "\n";
9575   outs() << "\t    x6  " << format("0x%016" PRIx64, cpu64.x[6]);
9576   outs() << " x7  "      << format("0x%016" PRIx64, cpu64.x[7]);
9577   outs() << " x8  "      << format("0x%016" PRIx64, cpu64.x[8]) << "\n";
9578   outs() << "\t    x9  " << format("0x%016" PRIx64, cpu64.x[9]);
9579   outs() << " x10 "      << format("0x%016" PRIx64, cpu64.x[10]);
9580   outs() << " x11 "      << format("0x%016" PRIx64, cpu64.x[11]) << "\n";
9581   outs() << "\t    x12 " << format("0x%016" PRIx64, cpu64.x[12]);
9582   outs() << " x13 "      << format("0x%016" PRIx64, cpu64.x[13]);
9583   outs() << " x14 "      << format("0x%016" PRIx64, cpu64.x[14]) << "\n";
9584   outs() << "\t    x15 " << format("0x%016" PRIx64, cpu64.x[15]);
9585   outs() << " x16 "      << format("0x%016" PRIx64, cpu64.x[16]);
9586   outs() << " x17 "      << format("0x%016" PRIx64, cpu64.x[17]) << "\n";
9587   outs() << "\t    x18 " << format("0x%016" PRIx64, cpu64.x[18]);
9588   outs() << " x19 "      << format("0x%016" PRIx64, cpu64.x[19]);
9589   outs() << " x20 "      << format("0x%016" PRIx64, cpu64.x[20]) << "\n";
9590   outs() << "\t    x21 " << format("0x%016" PRIx64, cpu64.x[21]);
9591   outs() << " x22 "      << format("0x%016" PRIx64, cpu64.x[22]);
9592   outs() << " x23 "      << format("0x%016" PRIx64, cpu64.x[23]) << "\n";
9593   outs() << "\t    x24 " << format("0x%016" PRIx64, cpu64.x[24]);
9594   outs() << " x25 "      << format("0x%016" PRIx64, cpu64.x[25]);
9595   outs() << " x26 "      << format("0x%016" PRIx64, cpu64.x[26]) << "\n";
9596   outs() << "\t    x27 " << format("0x%016" PRIx64, cpu64.x[27]);
9597   outs() << " x28 "      << format("0x%016" PRIx64, cpu64.x[28]);
9598   outs() << "  fp "      << format("0x%016" PRIx64, cpu64.fp) << "\n";
9599   outs() << "\t     lr " << format("0x%016" PRIx64, cpu64.lr);
9600   outs() << " sp  "      << format("0x%016" PRIx64, cpu64.sp);
9601   outs() << "  pc "      << format("0x%016" PRIx64, cpu64.pc) << "\n";
9602   outs() << "\t   cpsr " << format("0x%08"  PRIx32, cpu64.cpsr) << "\n";
9603 }
9604 
9605 static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
9606                                bool isLittleEndian, uint32_t cputype) {
9607   if (t.cmd == MachO::LC_THREAD)
9608     outs() << "        cmd LC_THREAD\n";
9609   else if (t.cmd == MachO::LC_UNIXTHREAD)
9610     outs() << "        cmd LC_UNIXTHREAD\n";
9611   else
9612     outs() << "        cmd " << t.cmd << " (unknown)\n";
9613   outs() << "    cmdsize " << t.cmdsize;
9614   if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
9615     outs() << " Incorrect size\n";
9616   else
9617     outs() << "\n";
9618 
9619   const char *begin = Ptr + sizeof(struct MachO::thread_command);
9620   const char *end = Ptr + t.cmdsize;
9621   uint32_t flavor, count, left;
9622   if (cputype == MachO::CPU_TYPE_I386) {
9623     while (begin < end) {
9624       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9625         memcpy((char *)&flavor, begin, sizeof(uint32_t));
9626         begin += sizeof(uint32_t);
9627       } else {
9628         flavor = 0;
9629         begin = end;
9630       }
9631       if (isLittleEndian != sys::IsLittleEndianHost)
9632         sys::swapByteOrder(flavor);
9633       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9634         memcpy((char *)&count, begin, sizeof(uint32_t));
9635         begin += sizeof(uint32_t);
9636       } else {
9637         count = 0;
9638         begin = end;
9639       }
9640       if (isLittleEndian != sys::IsLittleEndianHost)
9641         sys::swapByteOrder(count);
9642       if (flavor == MachO::x86_THREAD_STATE32) {
9643         outs() << "     flavor i386_THREAD_STATE\n";
9644         if (count == MachO::x86_THREAD_STATE32_COUNT)
9645           outs() << "      count i386_THREAD_STATE_COUNT\n";
9646         else
9647           outs() << "      count " << count
9648                  << " (not x86_THREAD_STATE32_COUNT)\n";
9649         MachO::x86_thread_state32_t cpu32;
9650         left = end - begin;
9651         if (left >= sizeof(MachO::x86_thread_state32_t)) {
9652           memcpy(&cpu32, begin, sizeof(MachO::x86_thread_state32_t));
9653           begin += sizeof(MachO::x86_thread_state32_t);
9654         } else {
9655           memset(&cpu32, '\0', sizeof(MachO::x86_thread_state32_t));
9656           memcpy(&cpu32, begin, left);
9657           begin += left;
9658         }
9659         if (isLittleEndian != sys::IsLittleEndianHost)
9660           swapStruct(cpu32);
9661         Print_x86_thread_state32_t(cpu32);
9662       } else if (flavor == MachO::x86_THREAD_STATE) {
9663         outs() << "     flavor x86_THREAD_STATE\n";
9664         if (count == MachO::x86_THREAD_STATE_COUNT)
9665           outs() << "      count x86_THREAD_STATE_COUNT\n";
9666         else
9667           outs() << "      count " << count
9668                  << " (not x86_THREAD_STATE_COUNT)\n";
9669         struct MachO::x86_thread_state_t ts;
9670         left = end - begin;
9671         if (left >= sizeof(MachO::x86_thread_state_t)) {
9672           memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
9673           begin += sizeof(MachO::x86_thread_state_t);
9674         } else {
9675           memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
9676           memcpy(&ts, begin, left);
9677           begin += left;
9678         }
9679         if (isLittleEndian != sys::IsLittleEndianHost)
9680           swapStruct(ts);
9681         if (ts.tsh.flavor == MachO::x86_THREAD_STATE32) {
9682           outs() << "\t    tsh.flavor x86_THREAD_STATE32 ";
9683           if (ts.tsh.count == MachO::x86_THREAD_STATE32_COUNT)
9684             outs() << "tsh.count x86_THREAD_STATE32_COUNT\n";
9685           else
9686             outs() << "tsh.count " << ts.tsh.count
9687                    << " (not x86_THREAD_STATE32_COUNT\n";
9688           Print_x86_thread_state32_t(ts.uts.ts32);
9689         } else {
9690           outs() << "\t    tsh.flavor " << ts.tsh.flavor << "  tsh.count "
9691                  << ts.tsh.count << "\n";
9692         }
9693       } else {
9694         outs() << "     flavor " << flavor << " (unknown)\n";
9695         outs() << "      count " << count << "\n";
9696         outs() << "      state (unknown)\n";
9697         begin += count * sizeof(uint32_t);
9698       }
9699     }
9700   } else if (cputype == MachO::CPU_TYPE_X86_64) {
9701     while (begin < end) {
9702       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9703         memcpy((char *)&flavor, begin, sizeof(uint32_t));
9704         begin += sizeof(uint32_t);
9705       } else {
9706         flavor = 0;
9707         begin = end;
9708       }
9709       if (isLittleEndian != sys::IsLittleEndianHost)
9710         sys::swapByteOrder(flavor);
9711       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9712         memcpy((char *)&count, begin, sizeof(uint32_t));
9713         begin += sizeof(uint32_t);
9714       } else {
9715         count = 0;
9716         begin = end;
9717       }
9718       if (isLittleEndian != sys::IsLittleEndianHost)
9719         sys::swapByteOrder(count);
9720       if (flavor == MachO::x86_THREAD_STATE64) {
9721         outs() << "     flavor x86_THREAD_STATE64\n";
9722         if (count == MachO::x86_THREAD_STATE64_COUNT)
9723           outs() << "      count x86_THREAD_STATE64_COUNT\n";
9724         else
9725           outs() << "      count " << count
9726                  << " (not x86_THREAD_STATE64_COUNT)\n";
9727         MachO::x86_thread_state64_t cpu64;
9728         left = end - begin;
9729         if (left >= sizeof(MachO::x86_thread_state64_t)) {
9730           memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
9731           begin += sizeof(MachO::x86_thread_state64_t);
9732         } else {
9733           memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
9734           memcpy(&cpu64, begin, left);
9735           begin += left;
9736         }
9737         if (isLittleEndian != sys::IsLittleEndianHost)
9738           swapStruct(cpu64);
9739         Print_x86_thread_state64_t(cpu64);
9740       } else if (flavor == MachO::x86_THREAD_STATE) {
9741         outs() << "     flavor x86_THREAD_STATE\n";
9742         if (count == MachO::x86_THREAD_STATE_COUNT)
9743           outs() << "      count x86_THREAD_STATE_COUNT\n";
9744         else
9745           outs() << "      count " << count
9746                  << " (not x86_THREAD_STATE_COUNT)\n";
9747         struct MachO::x86_thread_state_t ts;
9748         left = end - begin;
9749         if (left >= sizeof(MachO::x86_thread_state_t)) {
9750           memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
9751           begin += sizeof(MachO::x86_thread_state_t);
9752         } else {
9753           memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
9754           memcpy(&ts, begin, left);
9755           begin += left;
9756         }
9757         if (isLittleEndian != sys::IsLittleEndianHost)
9758           swapStruct(ts);
9759         if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
9760           outs() << "\t    tsh.flavor x86_THREAD_STATE64 ";
9761           if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
9762             outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
9763           else
9764             outs() << "tsh.count " << ts.tsh.count
9765                    << " (not x86_THREAD_STATE64_COUNT\n";
9766           Print_x86_thread_state64_t(ts.uts.ts64);
9767         } else {
9768           outs() << "\t    tsh.flavor " << ts.tsh.flavor << "  tsh.count "
9769                  << ts.tsh.count << "\n";
9770         }
9771       } else if (flavor == MachO::x86_FLOAT_STATE) {
9772         outs() << "     flavor x86_FLOAT_STATE\n";
9773         if (count == MachO::x86_FLOAT_STATE_COUNT)
9774           outs() << "      count x86_FLOAT_STATE_COUNT\n";
9775         else
9776           outs() << "      count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
9777         struct MachO::x86_float_state_t fs;
9778         left = end - begin;
9779         if (left >= sizeof(MachO::x86_float_state_t)) {
9780           memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
9781           begin += sizeof(MachO::x86_float_state_t);
9782         } else {
9783           memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
9784           memcpy(&fs, begin, left);
9785           begin += left;
9786         }
9787         if (isLittleEndian != sys::IsLittleEndianHost)
9788           swapStruct(fs);
9789         if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
9790           outs() << "\t    fsh.flavor x86_FLOAT_STATE64 ";
9791           if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
9792             outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
9793           else
9794             outs() << "fsh.count " << fs.fsh.count
9795                    << " (not x86_FLOAT_STATE64_COUNT\n";
9796           Print_x86_float_state_t(fs.ufs.fs64);
9797         } else {
9798           outs() << "\t    fsh.flavor " << fs.fsh.flavor << "  fsh.count "
9799                  << fs.fsh.count << "\n";
9800         }
9801       } else if (flavor == MachO::x86_EXCEPTION_STATE) {
9802         outs() << "     flavor x86_EXCEPTION_STATE\n";
9803         if (count == MachO::x86_EXCEPTION_STATE_COUNT)
9804           outs() << "      count x86_EXCEPTION_STATE_COUNT\n";
9805         else
9806           outs() << "      count " << count
9807                  << " (not x86_EXCEPTION_STATE_COUNT)\n";
9808         struct MachO::x86_exception_state_t es;
9809         left = end - begin;
9810         if (left >= sizeof(MachO::x86_exception_state_t)) {
9811           memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
9812           begin += sizeof(MachO::x86_exception_state_t);
9813         } else {
9814           memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
9815           memcpy(&es, begin, left);
9816           begin += left;
9817         }
9818         if (isLittleEndian != sys::IsLittleEndianHost)
9819           swapStruct(es);
9820         if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
9821           outs() << "\t    esh.flavor x86_EXCEPTION_STATE64\n";
9822           if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
9823             outs() << "\t    esh.count x86_EXCEPTION_STATE64_COUNT\n";
9824           else
9825             outs() << "\t    esh.count " << es.esh.count
9826                    << " (not x86_EXCEPTION_STATE64_COUNT\n";
9827           Print_x86_exception_state_t(es.ues.es64);
9828         } else {
9829           outs() << "\t    esh.flavor " << es.esh.flavor << "  esh.count "
9830                  << es.esh.count << "\n";
9831         }
9832       } else if (flavor == MachO::x86_EXCEPTION_STATE64) {
9833         outs() << "     flavor x86_EXCEPTION_STATE64\n";
9834         if (count == MachO::x86_EXCEPTION_STATE64_COUNT)
9835           outs() << "      count x86_EXCEPTION_STATE64_COUNT\n";
9836         else
9837           outs() << "      count " << count
9838                  << " (not x86_EXCEPTION_STATE64_COUNT)\n";
9839         struct MachO::x86_exception_state64_t es64;
9840         left = end - begin;
9841         if (left >= sizeof(MachO::x86_exception_state64_t)) {
9842           memcpy(&es64, begin, sizeof(MachO::x86_exception_state64_t));
9843           begin += sizeof(MachO::x86_exception_state64_t);
9844         } else {
9845           memset(&es64, '\0', sizeof(MachO::x86_exception_state64_t));
9846           memcpy(&es64, begin, left);
9847           begin += left;
9848         }
9849         if (isLittleEndian != sys::IsLittleEndianHost)
9850           swapStruct(es64);
9851         Print_x86_exception_state_t(es64);
9852       } else {
9853         outs() << "     flavor " << flavor << " (unknown)\n";
9854         outs() << "      count " << count << "\n";
9855         outs() << "      state (unknown)\n";
9856         begin += count * sizeof(uint32_t);
9857       }
9858     }
9859   } else if (cputype == MachO::CPU_TYPE_ARM) {
9860     while (begin < end) {
9861       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9862         memcpy((char *)&flavor, begin, sizeof(uint32_t));
9863         begin += sizeof(uint32_t);
9864       } else {
9865         flavor = 0;
9866         begin = end;
9867       }
9868       if (isLittleEndian != sys::IsLittleEndianHost)
9869         sys::swapByteOrder(flavor);
9870       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9871         memcpy((char *)&count, begin, sizeof(uint32_t));
9872         begin += sizeof(uint32_t);
9873       } else {
9874         count = 0;
9875         begin = end;
9876       }
9877       if (isLittleEndian != sys::IsLittleEndianHost)
9878         sys::swapByteOrder(count);
9879       if (flavor == MachO::ARM_THREAD_STATE) {
9880         outs() << "     flavor ARM_THREAD_STATE\n";
9881         if (count == MachO::ARM_THREAD_STATE_COUNT)
9882           outs() << "      count ARM_THREAD_STATE_COUNT\n";
9883         else
9884           outs() << "      count " << count
9885                  << " (not ARM_THREAD_STATE_COUNT)\n";
9886         MachO::arm_thread_state32_t cpu32;
9887         left = end - begin;
9888         if (left >= sizeof(MachO::arm_thread_state32_t)) {
9889           memcpy(&cpu32, begin, sizeof(MachO::arm_thread_state32_t));
9890           begin += sizeof(MachO::arm_thread_state32_t);
9891         } else {
9892           memset(&cpu32, '\0', sizeof(MachO::arm_thread_state32_t));
9893           memcpy(&cpu32, begin, left);
9894           begin += left;
9895         }
9896         if (isLittleEndian != sys::IsLittleEndianHost)
9897           swapStruct(cpu32);
9898         Print_arm_thread_state32_t(cpu32);
9899       } else {
9900         outs() << "     flavor " << flavor << " (unknown)\n";
9901         outs() << "      count " << count << "\n";
9902         outs() << "      state (unknown)\n";
9903         begin += count * sizeof(uint32_t);
9904       }
9905     }
9906   } else if (cputype == MachO::CPU_TYPE_ARM64 ||
9907              cputype == MachO::CPU_TYPE_ARM64_32) {
9908     while (begin < end) {
9909       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9910         memcpy((char *)&flavor, begin, sizeof(uint32_t));
9911         begin += sizeof(uint32_t);
9912       } else {
9913         flavor = 0;
9914         begin = end;
9915       }
9916       if (isLittleEndian != sys::IsLittleEndianHost)
9917         sys::swapByteOrder(flavor);
9918       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9919         memcpy((char *)&count, begin, sizeof(uint32_t));
9920         begin += sizeof(uint32_t);
9921       } else {
9922         count = 0;
9923         begin = end;
9924       }
9925       if (isLittleEndian != sys::IsLittleEndianHost)
9926         sys::swapByteOrder(count);
9927       if (flavor == MachO::ARM_THREAD_STATE64) {
9928         outs() << "     flavor ARM_THREAD_STATE64\n";
9929         if (count == MachO::ARM_THREAD_STATE64_COUNT)
9930           outs() << "      count ARM_THREAD_STATE64_COUNT\n";
9931         else
9932           outs() << "      count " << count
9933                  << " (not ARM_THREAD_STATE64_COUNT)\n";
9934         MachO::arm_thread_state64_t cpu64;
9935         left = end - begin;
9936         if (left >= sizeof(MachO::arm_thread_state64_t)) {
9937           memcpy(&cpu64, begin, sizeof(MachO::arm_thread_state64_t));
9938           begin += sizeof(MachO::arm_thread_state64_t);
9939         } else {
9940           memset(&cpu64, '\0', sizeof(MachO::arm_thread_state64_t));
9941           memcpy(&cpu64, begin, left);
9942           begin += left;
9943         }
9944         if (isLittleEndian != sys::IsLittleEndianHost)
9945           swapStruct(cpu64);
9946         Print_arm_thread_state64_t(cpu64);
9947       } else {
9948         outs() << "     flavor " << flavor << " (unknown)\n";
9949         outs() << "      count " << count << "\n";
9950         outs() << "      state (unknown)\n";
9951         begin += count * sizeof(uint32_t);
9952       }
9953     }
9954   } else {
9955     while (begin < end) {
9956       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9957         memcpy((char *)&flavor, begin, sizeof(uint32_t));
9958         begin += sizeof(uint32_t);
9959       } else {
9960         flavor = 0;
9961         begin = end;
9962       }
9963       if (isLittleEndian != sys::IsLittleEndianHost)
9964         sys::swapByteOrder(flavor);
9965       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9966         memcpy((char *)&count, begin, sizeof(uint32_t));
9967         begin += sizeof(uint32_t);
9968       } else {
9969         count = 0;
9970         begin = end;
9971       }
9972       if (isLittleEndian != sys::IsLittleEndianHost)
9973         sys::swapByteOrder(count);
9974       outs() << "     flavor " << flavor << "\n";
9975       outs() << "      count " << count << "\n";
9976       outs() << "      state (Unknown cputype/cpusubtype)\n";
9977       begin += count * sizeof(uint32_t);
9978     }
9979   }
9980 }
9981 
9982 static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
9983   if (dl.cmd == MachO::LC_ID_DYLIB)
9984     outs() << "          cmd LC_ID_DYLIB\n";
9985   else if (dl.cmd == MachO::LC_LOAD_DYLIB)
9986     outs() << "          cmd LC_LOAD_DYLIB\n";
9987   else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
9988     outs() << "          cmd LC_LOAD_WEAK_DYLIB\n";
9989   else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
9990     outs() << "          cmd LC_REEXPORT_DYLIB\n";
9991   else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
9992     outs() << "          cmd LC_LAZY_LOAD_DYLIB\n";
9993   else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
9994     outs() << "          cmd LC_LOAD_UPWARD_DYLIB\n";
9995   else
9996     outs() << "          cmd " << dl.cmd << " (unknown)\n";
9997   outs() << "      cmdsize " << dl.cmdsize;
9998   if (dl.cmdsize < sizeof(struct MachO::dylib_command))
9999     outs() << " Incorrect size\n";
10000   else
10001     outs() << "\n";
10002   if (dl.dylib.name < dl.cmdsize) {
10003     const char *P = (const char *)(Ptr) + dl.dylib.name;
10004     outs() << "         name " << P << " (offset " << dl.dylib.name << ")\n";
10005   } else {
10006     outs() << "         name ?(bad offset " << dl.dylib.name << ")\n";
10007   }
10008   outs() << "   time stamp " << dl.dylib.timestamp << " ";
10009   time_t t = dl.dylib.timestamp;
10010   outs() << ctime(&t);
10011   outs() << "      current version ";
10012   if (dl.dylib.current_version == 0xffffffff)
10013     outs() << "n/a\n";
10014   else
10015     outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
10016            << ((dl.dylib.current_version >> 8) & 0xff) << "."
10017            << (dl.dylib.current_version & 0xff) << "\n";
10018   outs() << "compatibility version ";
10019   if (dl.dylib.compatibility_version == 0xffffffff)
10020     outs() << "n/a\n";
10021   else
10022     outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
10023            << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
10024            << (dl.dylib.compatibility_version & 0xff) << "\n";
10025 }
10026 
10027 static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
10028                                      uint32_t object_size) {
10029   if (ld.cmd == MachO::LC_CODE_SIGNATURE)
10030     outs() << "      cmd LC_CODE_SIGNATURE\n";
10031   else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
10032     outs() << "      cmd LC_SEGMENT_SPLIT_INFO\n";
10033   else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
10034     outs() << "      cmd LC_FUNCTION_STARTS\n";
10035   else if (ld.cmd == MachO::LC_DATA_IN_CODE)
10036     outs() << "      cmd LC_DATA_IN_CODE\n";
10037   else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
10038     outs() << "      cmd LC_DYLIB_CODE_SIGN_DRS\n";
10039   else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
10040     outs() << "      cmd LC_LINKER_OPTIMIZATION_HINT\n";
10041   else
10042     outs() << "      cmd " << ld.cmd << " (?)\n";
10043   outs() << "  cmdsize " << ld.cmdsize;
10044   if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
10045     outs() << " Incorrect size\n";
10046   else
10047     outs() << "\n";
10048   outs() << "  dataoff " << ld.dataoff;
10049   if (ld.dataoff > object_size)
10050     outs() << " (past end of file)\n";
10051   else
10052     outs() << "\n";
10053   outs() << " datasize " << ld.datasize;
10054   uint64_t big_size = ld.dataoff;
10055   big_size += ld.datasize;
10056   if (big_size > object_size)
10057     outs() << " (past end of file)\n";
10058   else
10059     outs() << "\n";
10060 }
10061 
10062 static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
10063                               uint32_t cputype, bool verbose) {
10064   StringRef Buf = Obj->getData();
10065   unsigned Index = 0;
10066   for (const auto &Command : Obj->load_commands()) {
10067     outs() << "Load command " << Index++ << "\n";
10068     if (Command.C.cmd == MachO::LC_SEGMENT) {
10069       MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
10070       const char *sg_segname = SLC.segname;
10071       PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
10072                           SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
10073                           SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
10074                           verbose);
10075       for (unsigned j = 0; j < SLC.nsects; j++) {
10076         MachO::section S = Obj->getSection(Command, j);
10077         PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
10078                      S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
10079                      SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
10080       }
10081     } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
10082       MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
10083       const char *sg_segname = SLC_64.segname;
10084       PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
10085                           SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
10086                           SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
10087                           SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
10088       for (unsigned j = 0; j < SLC_64.nsects; j++) {
10089         MachO::section_64 S_64 = Obj->getSection64(Command, j);
10090         PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
10091                      S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
10092                      S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
10093                      sg_segname, filetype, Buf.size(), verbose);
10094       }
10095     } else if (Command.C.cmd == MachO::LC_SYMTAB) {
10096       MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
10097       PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
10098     } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
10099       MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
10100       MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
10101       PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
10102                                Obj->is64Bit());
10103     } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
10104                Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
10105       MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
10106       PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
10107     } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
10108                Command.C.cmd == MachO::LC_ID_DYLINKER ||
10109                Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
10110       MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
10111       PrintDyldLoadCommand(Dyld, Command.Ptr);
10112     } else if (Command.C.cmd == MachO::LC_UUID) {
10113       MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
10114       PrintUuidLoadCommand(Uuid);
10115     } else if (Command.C.cmd == MachO::LC_RPATH) {
10116       MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
10117       PrintRpathLoadCommand(Rpath, Command.Ptr);
10118     } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
10119                Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
10120                Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
10121                Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
10122       MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
10123       PrintVersionMinLoadCommand(Vd);
10124     } else if (Command.C.cmd == MachO::LC_NOTE) {
10125       MachO::note_command Nt = Obj->getNoteLoadCommand(Command);
10126       PrintNoteLoadCommand(Nt);
10127     } else if (Command.C.cmd == MachO::LC_BUILD_VERSION) {
10128       MachO::build_version_command Bv =
10129           Obj->getBuildVersionLoadCommand(Command);
10130       PrintBuildVersionLoadCommand(Obj, Bv);
10131     } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
10132       MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
10133       PrintSourceVersionCommand(Sd);
10134     } else if (Command.C.cmd == MachO::LC_MAIN) {
10135       MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
10136       PrintEntryPointCommand(Ep);
10137     } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
10138       MachO::encryption_info_command Ei =
10139           Obj->getEncryptionInfoCommand(Command);
10140       PrintEncryptionInfoCommand(Ei, Buf.size());
10141     } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
10142       MachO::encryption_info_command_64 Ei =
10143           Obj->getEncryptionInfoCommand64(Command);
10144       PrintEncryptionInfoCommand64(Ei, Buf.size());
10145     } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
10146       MachO::linker_option_command Lo =
10147           Obj->getLinkerOptionLoadCommand(Command);
10148       PrintLinkerOptionCommand(Lo, Command.Ptr);
10149     } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
10150       MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
10151       PrintSubFrameworkCommand(Sf, Command.Ptr);
10152     } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
10153       MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
10154       PrintSubUmbrellaCommand(Sf, Command.Ptr);
10155     } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
10156       MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
10157       PrintSubLibraryCommand(Sl, Command.Ptr);
10158     } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
10159       MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
10160       PrintSubClientCommand(Sc, Command.Ptr);
10161     } else if (Command.C.cmd == MachO::LC_ROUTINES) {
10162       MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
10163       PrintRoutinesCommand(Rc);
10164     } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
10165       MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
10166       PrintRoutinesCommand64(Rc);
10167     } else if (Command.C.cmd == MachO::LC_THREAD ||
10168                Command.C.cmd == MachO::LC_UNIXTHREAD) {
10169       MachO::thread_command Tc = Obj->getThreadCommand(Command);
10170       PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
10171     } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
10172                Command.C.cmd == MachO::LC_ID_DYLIB ||
10173                Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
10174                Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
10175                Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
10176                Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
10177       MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
10178       PrintDylibCommand(Dl, Command.Ptr);
10179     } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
10180                Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
10181                Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
10182                Command.C.cmd == MachO::LC_DATA_IN_CODE ||
10183                Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
10184                Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
10185       MachO::linkedit_data_command Ld =
10186           Obj->getLinkeditDataLoadCommand(Command);
10187       PrintLinkEditDataCommand(Ld, Buf.size());
10188     } else {
10189       outs() << "      cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
10190              << ")\n";
10191       outs() << "  cmdsize " << Command.C.cmdsize << "\n";
10192       // TODO: get and print the raw bytes of the load command.
10193     }
10194     // TODO: print all the other kinds of load commands.
10195   }
10196 }
10197 
10198 static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
10199   if (Obj->is64Bit()) {
10200     MachO::mach_header_64 H_64;
10201     H_64 = Obj->getHeader64();
10202     PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
10203                     H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
10204   } else {
10205     MachO::mach_header H;
10206     H = Obj->getHeader();
10207     PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
10208                     H.sizeofcmds, H.flags, verbose);
10209   }
10210 }
10211 
10212 void printMachOFileHeader(const object::ObjectFile *Obj) {
10213   const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
10214   PrintMachHeader(file, !NonVerbose);
10215 }
10216 
10217 void printMachOLoadCommands(const object::ObjectFile *Obj) {
10218   const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
10219   uint32_t filetype = 0;
10220   uint32_t cputype = 0;
10221   if (file->is64Bit()) {
10222     MachO::mach_header_64 H_64;
10223     H_64 = file->getHeader64();
10224     filetype = H_64.filetype;
10225     cputype = H_64.cputype;
10226   } else {
10227     MachO::mach_header H;
10228     H = file->getHeader();
10229     filetype = H.filetype;
10230     cputype = H.cputype;
10231   }
10232   PrintLoadCommands(file, filetype, cputype, !NonVerbose);
10233 }
10234 
10235 //===----------------------------------------------------------------------===//
10236 // export trie dumping
10237 //===----------------------------------------------------------------------===//
10238 
10239 void printMachOExportsTrie(const object::MachOObjectFile *Obj) {
10240   uint64_t BaseSegmentAddress = 0;
10241   for (const auto &Command : Obj->load_commands()) {
10242     if (Command.C.cmd == MachO::LC_SEGMENT) {
10243       MachO::segment_command Seg = Obj->getSegmentLoadCommand(Command);
10244       if (Seg.fileoff == 0 && Seg.filesize != 0) {
10245         BaseSegmentAddress = Seg.vmaddr;
10246         break;
10247       }
10248     } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
10249       MachO::segment_command_64 Seg = Obj->getSegment64LoadCommand(Command);
10250       if (Seg.fileoff == 0 && Seg.filesize != 0) {
10251         BaseSegmentAddress = Seg.vmaddr;
10252         break;
10253       }
10254     }
10255   }
10256   Error Err = Error::success();
10257   for (const object::ExportEntry &Entry : Obj->exports(Err)) {
10258     uint64_t Flags = Entry.flags();
10259     bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
10260     bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
10261     bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
10262                         MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
10263     bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
10264                 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
10265     bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
10266     if (ReExport)
10267       outs() << "[re-export] ";
10268     else
10269       outs() << format("0x%08llX  ",
10270                        Entry.address() + BaseSegmentAddress);
10271     outs() << Entry.name();
10272     if (WeakDef || ThreadLocal || Resolver || Abs) {
10273       bool NeedsComma = false;
10274       outs() << " [";
10275       if (WeakDef) {
10276         outs() << "weak_def";
10277         NeedsComma = true;
10278       }
10279       if (ThreadLocal) {
10280         if (NeedsComma)
10281           outs() << ", ";
10282         outs() << "per-thread";
10283         NeedsComma = true;
10284       }
10285       if (Abs) {
10286         if (NeedsComma)
10287           outs() << ", ";
10288         outs() << "absolute";
10289         NeedsComma = true;
10290       }
10291       if (Resolver) {
10292         if (NeedsComma)
10293           outs() << ", ";
10294         outs() << format("resolver=0x%08llX", Entry.other());
10295         NeedsComma = true;
10296       }
10297       outs() << "]";
10298     }
10299     if (ReExport) {
10300       StringRef DylibName = "unknown";
10301       int Ordinal = Entry.other() - 1;
10302       Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
10303       if (Entry.otherName().empty())
10304         outs() << " (from " << DylibName << ")";
10305       else
10306         outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
10307     }
10308     outs() << "\n";
10309   }
10310   if (Err)
10311     reportError(std::move(Err), Obj->getFileName());
10312 }
10313 
10314 //===----------------------------------------------------------------------===//
10315 // rebase table dumping
10316 //===----------------------------------------------------------------------===//
10317 
10318 void printMachORebaseTable(object::MachOObjectFile *Obj) {
10319   outs() << "segment  section            address     type\n";
10320   Error Err = Error::success();
10321   for (const object::MachORebaseEntry &Entry : Obj->rebaseTable(Err)) {
10322     StringRef SegmentName = Entry.segmentName();
10323     StringRef SectionName = Entry.sectionName();
10324     uint64_t Address = Entry.address();
10325 
10326     // Table lines look like: __DATA  __nl_symbol_ptr  0x0000F00C  pointer
10327     outs() << format("%-8s %-18s 0x%08" PRIX64 "  %s\n",
10328                      SegmentName.str().c_str(), SectionName.str().c_str(),
10329                      Address, Entry.typeName().str().c_str());
10330   }
10331   if (Err)
10332     reportError(std::move(Err), Obj->getFileName());
10333 }
10334 
10335 static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
10336   StringRef DylibName;
10337   switch (Ordinal) {
10338   case MachO::BIND_SPECIAL_DYLIB_SELF:
10339     return "this-image";
10340   case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
10341     return "main-executable";
10342   case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
10343     return "flat-namespace";
10344   default:
10345     if (Ordinal > 0) {
10346       std::error_code EC =
10347           Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
10348       if (EC)
10349         return "<<bad library ordinal>>";
10350       return DylibName;
10351     }
10352   }
10353   return "<<unknown special ordinal>>";
10354 }
10355 
10356 //===----------------------------------------------------------------------===//
10357 // bind table dumping
10358 //===----------------------------------------------------------------------===//
10359 
10360 void printMachOBindTable(object::MachOObjectFile *Obj) {
10361   // Build table of sections so names can used in final output.
10362   outs() << "segment  section            address    type       "
10363             "addend dylib            symbol\n";
10364   Error Err = Error::success();
10365   for (const object::MachOBindEntry &Entry : Obj->bindTable(Err)) {
10366     StringRef SegmentName = Entry.segmentName();
10367     StringRef SectionName = Entry.sectionName();
10368     uint64_t Address = Entry.address();
10369 
10370     // Table lines look like:
10371     //  __DATA  __got  0x00012010    pointer   0 libSystem ___stack_chk_guard
10372     StringRef Attr;
10373     if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
10374       Attr = " (weak_import)";
10375     outs() << left_justify(SegmentName, 8) << " "
10376            << left_justify(SectionName, 18) << " "
10377            << format_hex(Address, 10, true) << " "
10378            << left_justify(Entry.typeName(), 8) << " "
10379            << format_decimal(Entry.addend(), 8) << " "
10380            << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
10381            << Entry.symbolName() << Attr << "\n";
10382   }
10383   if (Err)
10384     reportError(std::move(Err), Obj->getFileName());
10385 }
10386 
10387 //===----------------------------------------------------------------------===//
10388 // lazy bind table dumping
10389 //===----------------------------------------------------------------------===//
10390 
10391 void printMachOLazyBindTable(object::MachOObjectFile *Obj) {
10392   outs() << "segment  section            address     "
10393             "dylib            symbol\n";
10394   Error Err = Error::success();
10395   for (const object::MachOBindEntry &Entry : Obj->lazyBindTable(Err)) {
10396     StringRef SegmentName = Entry.segmentName();
10397     StringRef SectionName = Entry.sectionName();
10398     uint64_t Address = Entry.address();
10399 
10400     // Table lines look like:
10401     //  __DATA  __got  0x00012010 libSystem ___stack_chk_guard
10402     outs() << left_justify(SegmentName, 8) << " "
10403            << left_justify(SectionName, 18) << " "
10404            << format_hex(Address, 10, true) << " "
10405            << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
10406            << Entry.symbolName() << "\n";
10407   }
10408   if (Err)
10409     reportError(std::move(Err), Obj->getFileName());
10410 }
10411 
10412 //===----------------------------------------------------------------------===//
10413 // weak bind table dumping
10414 //===----------------------------------------------------------------------===//
10415 
10416 void printMachOWeakBindTable(object::MachOObjectFile *Obj) {
10417   outs() << "segment  section            address     "
10418             "type       addend   symbol\n";
10419   Error Err = Error::success();
10420   for (const object::MachOBindEntry &Entry : Obj->weakBindTable(Err)) {
10421     // Strong symbols don't have a location to update.
10422     if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
10423       outs() << "                                        strong              "
10424              << Entry.symbolName() << "\n";
10425       continue;
10426     }
10427     StringRef SegmentName = Entry.segmentName();
10428     StringRef SectionName = Entry.sectionName();
10429     uint64_t Address = Entry.address();
10430 
10431     // Table lines look like:
10432     // __DATA  __data  0x00001000  pointer    0   _foo
10433     outs() << left_justify(SegmentName, 8) << " "
10434            << left_justify(SectionName, 18) << " "
10435            << format_hex(Address, 10, true) << " "
10436            << left_justify(Entry.typeName(), 8) << " "
10437            << format_decimal(Entry.addend(), 8) << "   " << Entry.symbolName()
10438            << "\n";
10439   }
10440   if (Err)
10441     reportError(std::move(Err), Obj->getFileName());
10442 }
10443 
10444 // get_dyld_bind_info_symbolname() is used for disassembly and passed an
10445 // address, ReferenceValue, in the Mach-O file and looks in the dyld bind
10446 // information for that address. If the address is found its binding symbol
10447 // name is returned.  If not nullptr is returned.
10448 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
10449                                                  struct DisassembleInfo *info) {
10450   if (info->bindtable == nullptr) {
10451     info->bindtable = std::make_unique<SymbolAddressMap>();
10452     Error Err = Error::success();
10453     for (const object::MachOBindEntry &Entry : info->O->bindTable(Err)) {
10454       uint64_t Address = Entry.address();
10455       StringRef name = Entry.symbolName();
10456       if (!name.empty())
10457         (*info->bindtable)[Address] = name;
10458     }
10459     if (Err)
10460       reportError(std::move(Err), info->O->getFileName());
10461   }
10462   auto name = info->bindtable->lookup(ReferenceValue);
10463   return !name.empty() ? name.data() : nullptr;
10464 }
10465 
10466 void printLazyBindTable(ObjectFile *o) {
10467   outs() << "Lazy bind table:\n";
10468   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10469     printMachOLazyBindTable(MachO);
10470   else
10471     WithColor::error()
10472         << "This operation is only currently supported "
10473            "for Mach-O executable files.\n";
10474 }
10475 
10476 void printWeakBindTable(ObjectFile *o) {
10477   outs() << "Weak bind table:\n";
10478   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10479     printMachOWeakBindTable(MachO);
10480   else
10481     WithColor::error()
10482         << "This operation is only currently supported "
10483            "for Mach-O executable files.\n";
10484 }
10485 
10486 void printExportsTrie(const ObjectFile *o) {
10487   outs() << "Exports trie:\n";
10488   if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10489     printMachOExportsTrie(MachO);
10490   else
10491     WithColor::error()
10492         << "This operation is only currently supported "
10493            "for Mach-O executable files.\n";
10494 }
10495 
10496 void printRebaseTable(ObjectFile *o) {
10497   outs() << "Rebase table:\n";
10498   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10499     printMachORebaseTable(MachO);
10500   else
10501     WithColor::error()
10502         << "This operation is only currently supported "
10503            "for Mach-O executable files.\n";
10504 }
10505 
10506 void printBindTable(ObjectFile *o) {
10507   outs() << "Bind table:\n";
10508   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10509     printMachOBindTable(MachO);
10510   else
10511     WithColor::error()
10512         << "This operation is only currently supported "
10513            "for Mach-O executable files.\n";
10514 }
10515 } // namespace llvm
10516