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/Object/MachO.h"
33 #include "llvm/Object/MachOUniversal.h"
34 #include "llvm/Support/Casting.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/Endian.h"
38 #include "llvm/Support/Format.h"
39 #include "llvm/Support/FormattedStream.h"
40 #include "llvm/Support/GraphWriter.h"
41 #include "llvm/Support/LEB128.h"
42 #include "llvm/Support/MemoryBuffer.h"
43 #include "llvm/Support/TargetRegistry.h"
44 #include "llvm/Support/TargetSelect.h"
45 #include "llvm/Support/ToolOutputFile.h"
46 #include "llvm/Support/WithColor.h"
47 #include "llvm/Support/raw_ostream.h"
48 #include <algorithm>
49 #include <cstring>
50 #include <system_error>
51 
52 #ifdef HAVE_LIBXAR
53 extern "C" {
54 #include <xar/xar.h>
55 }
56 #endif
57 
58 using namespace llvm::object;
59 
60 namespace llvm {
61 
62 cl::OptionCategory MachOCat("llvm-objdump MachO Specific Options");
63 
64 extern cl::opt<bool> ArchiveHeaders;
65 extern cl::opt<bool> Disassemble;
66 extern cl::opt<bool> DisassembleAll;
67 extern cl::opt<DIDumpType> DwarfDumpType;
68 extern cl::list<std::string> FilterSections;
69 extern cl::list<std::string> MAttrs;
70 extern cl::opt<std::string> MCPU;
71 extern cl::opt<bool> NoShowRawInsn;
72 extern cl::opt<bool> NoLeadingAddr;
73 extern cl::opt<bool> PrintImmHex;
74 extern cl::opt<bool> PrivateHeaders;
75 extern cl::opt<bool> Relocations;
76 extern cl::opt<bool> SectionHeaders;
77 extern cl::opt<bool> SectionContents;
78 extern cl::opt<bool> SymbolTable;
79 extern cl::opt<std::string> TripleName;
80 extern cl::opt<bool> UnwindInfo;
81 
82 cl::opt<bool>
83     FirstPrivateHeader("private-header",
84                        cl::desc("Display only the first format specific file "
85                                 "header"),
86                        cl::cat(MachOCat));
87 
88 cl::opt<bool> ExportsTrie("exports-trie",
89                           cl::desc("Display mach-o exported symbols"),
90                           cl::cat(MachOCat));
91 
92 cl::opt<bool> Rebase("rebase", cl::desc("Display mach-o rebasing info"),
93                      cl::cat(MachOCat));
94 
95 cl::opt<bool> Bind("bind", cl::desc("Display mach-o binding info"),
96                    cl::cat(MachOCat));
97 
98 cl::opt<bool> LazyBind("lazy-bind",
99                        cl::desc("Display mach-o lazy binding info"),
100                        cl::cat(MachOCat));
101 
102 cl::opt<bool> WeakBind("weak-bind",
103                        cl::desc("Display mach-o weak binding info"),
104                        cl::cat(MachOCat));
105 
106 static cl::opt<bool>
107     UseDbg("g", cl::Grouping,
108            cl::desc("Print line information from debug info if available"),
109            cl::cat(MachOCat));
110 
111 static cl::opt<std::string> DSYMFile("dsym",
112                                      cl::desc("Use .dSYM file for debug info"),
113                                      cl::cat(MachOCat));
114 
115 static cl::opt<bool> FullLeadingAddr("full-leading-addr",
116                                      cl::desc("Print full leading address"),
117                                      cl::cat(MachOCat));
118 
119 static cl::opt<bool> NoLeadingHeaders("no-leading-headers",
120                                       cl::desc("Print no leading headers"),
121                                       cl::cat(MachOCat));
122 
123 cl::opt<bool> UniversalHeaders("universal-headers",
124                                cl::desc("Print Mach-O universal headers "
125                                         "(requires -macho)"),
126                                cl::cat(MachOCat));
127 
128 cl::opt<bool>
129     ArchiveMemberOffsets("archive-member-offsets",
130                          cl::desc("Print the offset to each archive member for "
131                                   "Mach-O archives (requires -macho and "
132                                   "-archive-headers)"),
133                          cl::cat(MachOCat));
134 
135 cl::opt<bool> IndirectSymbols("indirect-symbols",
136                               cl::desc("Print indirect symbol table for Mach-O "
137                                        "objects (requires -macho)"),
138                               cl::cat(MachOCat));
139 
140 cl::opt<bool>
141     DataInCode("data-in-code",
142                cl::desc("Print the data in code table for Mach-O objects "
143                         "(requires -macho)"),
144                cl::cat(MachOCat));
145 
146 cl::opt<bool> LinkOptHints("link-opt-hints",
147                            cl::desc("Print the linker optimization hints for "
148                                     "Mach-O objects (requires -macho)"),
149                            cl::cat(MachOCat));
150 
151 cl::opt<bool> InfoPlist("info-plist",
152                         cl::desc("Print the info plist section as strings for "
153                                  "Mach-O objects (requires -macho)"),
154                         cl::cat(MachOCat));
155 
156 cl::opt<bool> DylibsUsed("dylibs-used",
157                          cl::desc("Print the shared libraries used for linked "
158                                   "Mach-O files (requires -macho)"),
159                          cl::cat(MachOCat));
160 
161 cl::opt<bool>
162     DylibId("dylib-id",
163             cl::desc("Print the shared library's id for the dylib Mach-O "
164                      "file (requires -macho)"),
165             cl::cat(MachOCat));
166 
167 cl::opt<bool>
168     NonVerbose("non-verbose",
169                cl::desc("Print the info for Mach-O objects in "
170                         "non-verbose or numeric form (requires -macho)"),
171                cl::cat(MachOCat));
172 
173 cl::opt<bool>
174     ObjcMetaData("objc-meta-data",
175                  cl::desc("Print the Objective-C runtime meta data for "
176                           "Mach-O files (requires -macho)"),
177                  cl::cat(MachOCat));
178 
179 cl::opt<std::string> DisSymName(
180     "dis-symname",
181     cl::desc("disassemble just this symbol's instructions (requires -macho)"),
182     cl::cat(MachOCat));
183 
184 static cl::opt<bool> NoSymbolicOperands(
185     "no-symbolic-operands",
186     cl::desc("do not symbolic operands when disassembling (requires -macho)"),
187     cl::cat(MachOCat));
188 
189 static cl::list<std::string>
190     ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
191               cl::ZeroOrMore, cl::cat(MachOCat));
192 
193 bool ArchAll = false;
194 
195 static std::string ThumbTripleName;
196 
197 static const Target *GetTarget(const MachOObjectFile *MachOObj,
198                                const char **McpuDefault,
199                                const Target **ThumbTarget) {
200   // Figure out the target triple.
201   Triple TT(TripleName);
202   if (TripleName.empty()) {
203     TT = MachOObj->getArchTriple(McpuDefault);
204     TripleName = TT.str();
205   }
206 
207   if (TT.getArch() == Triple::arm) {
208     // We've inferred a 32-bit ARM target from the object file. All MachO CPUs
209     // that support ARM are also capable of Thumb mode.
210     Triple ThumbTriple = TT;
211     std::string ThumbName = (Twine("thumb") + TT.getArchName().substr(3)).str();
212     ThumbTriple.setArchName(ThumbName);
213     ThumbTripleName = ThumbTriple.str();
214   }
215 
216   // Get the target specific parser.
217   std::string Error;
218   const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
219   if (TheTarget && ThumbTripleName.empty())
220     return TheTarget;
221 
222   *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
223   if (*ThumbTarget)
224     return TheTarget;
225 
226   WithColor::error(errs(), "llvm-objdump") << "unable to get target for '";
227   if (!TheTarget)
228     errs() << TripleName;
229   else
230     errs() << ThumbTripleName;
231   errs() << "', see --version and --triple.\n";
232   return nullptr;
233 }
234 
235 struct SymbolSorter {
236   bool operator()(const SymbolRef &A, const SymbolRef &B) {
237     Expected<SymbolRef::Type> ATypeOrErr = A.getType();
238     if (!ATypeOrErr)
239       reportError(ATypeOrErr.takeError(), A.getObject()->getFileName());
240     SymbolRef::Type AType = *ATypeOrErr;
241     Expected<SymbolRef::Type> BTypeOrErr = B.getType();
242     if (!BTypeOrErr)
243       reportError(BTypeOrErr.takeError(), B.getObject()->getFileName());
244     SymbolRef::Type BType = *BTypeOrErr;
245     uint64_t AAddr = (AType != SymbolRef::ST_Function) ? 0 : A.getValue();
246     uint64_t BAddr = (BType != SymbolRef::ST_Function) ? 0 : B.getValue();
247     return AAddr < BAddr;
248   }
249 };
250 
251 // Types for the storted data in code table that is built before disassembly
252 // and the predicate function to sort them.
253 typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
254 typedef std::vector<DiceTableEntry> DiceTable;
255 typedef DiceTable::iterator dice_table_iterator;
256 
257 #ifdef HAVE_LIBXAR
258 namespace {
259 struct ScopedXarFile {
260   xar_t xar;
261   ScopedXarFile(const char *filename, int32_t flags)
262       : xar(xar_open(filename, flags)) {}
263   ~ScopedXarFile() {
264     if (xar)
265       xar_close(xar);
266   }
267   ScopedXarFile(const ScopedXarFile &) = delete;
268   ScopedXarFile &operator=(const ScopedXarFile &) = delete;
269   operator xar_t() { return xar; }
270 };
271 
272 struct ScopedXarIter {
273   xar_iter_t iter;
274   ScopedXarIter() : iter(xar_iter_new()) {}
275   ~ScopedXarIter() {
276     if (iter)
277       xar_iter_free(iter);
278   }
279   ScopedXarIter(const ScopedXarIter &) = delete;
280   ScopedXarIter &operator=(const ScopedXarIter &) = delete;
281   operator xar_iter_t() { return iter; }
282 };
283 } // namespace
284 #endif // defined(HAVE_LIBXAR)
285 
286 // This is used to search for a data in code table entry for the PC being
287 // disassembled.  The j parameter has the PC in j.first.  A single data in code
288 // table entry can cover many bytes for each of its Kind's.  So if the offset,
289 // aka the i.first value, of the data in code table entry plus its Length
290 // covers the PC being searched for this will return true.  If not it will
291 // return false.
292 static bool compareDiceTableEntries(const DiceTableEntry &i,
293                                     const DiceTableEntry &j) {
294   uint16_t Length;
295   i.second.getLength(Length);
296 
297   return j.first >= i.first && j.first < i.first + Length;
298 }
299 
300 static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
301                                unsigned short Kind) {
302   uint32_t Value, Size = 1;
303 
304   switch (Kind) {
305   default:
306   case MachO::DICE_KIND_DATA:
307     if (Length >= 4) {
308       if (!NoShowRawInsn)
309         dumpBytes(makeArrayRef(bytes, 4), outs());
310       Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
311       outs() << "\t.long " << Value;
312       Size = 4;
313     } else if (Length >= 2) {
314       if (!NoShowRawInsn)
315         dumpBytes(makeArrayRef(bytes, 2), outs());
316       Value = bytes[1] << 8 | bytes[0];
317       outs() << "\t.short " << Value;
318       Size = 2;
319     } else {
320       if (!NoShowRawInsn)
321         dumpBytes(makeArrayRef(bytes, 2), outs());
322       Value = bytes[0];
323       outs() << "\t.byte " << Value;
324       Size = 1;
325     }
326     if (Kind == MachO::DICE_KIND_DATA)
327       outs() << "\t@ KIND_DATA\n";
328     else
329       outs() << "\t@ data in code kind = " << Kind << "\n";
330     break;
331   case MachO::DICE_KIND_JUMP_TABLE8:
332     if (!NoShowRawInsn)
333       dumpBytes(makeArrayRef(bytes, 1), outs());
334     Value = bytes[0];
335     outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
336     Size = 1;
337     break;
338   case MachO::DICE_KIND_JUMP_TABLE16:
339     if (!NoShowRawInsn)
340       dumpBytes(makeArrayRef(bytes, 2), outs());
341     Value = bytes[1] << 8 | bytes[0];
342     outs() << "\t.short " << format("%5u", Value & 0xffff)
343            << "\t@ KIND_JUMP_TABLE16\n";
344     Size = 2;
345     break;
346   case MachO::DICE_KIND_JUMP_TABLE32:
347   case MachO::DICE_KIND_ABS_JUMP_TABLE32:
348     if (!NoShowRawInsn)
349       dumpBytes(makeArrayRef(bytes, 4), outs());
350     Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
351     outs() << "\t.long " << Value;
352     if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
353       outs() << "\t@ KIND_JUMP_TABLE32\n";
354     else
355       outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
356     Size = 4;
357     break;
358   }
359   return Size;
360 }
361 
362 static void getSectionsAndSymbols(MachOObjectFile *MachOObj,
363                                   std::vector<SectionRef> &Sections,
364                                   std::vector<SymbolRef> &Symbols,
365                                   SmallVectorImpl<uint64_t> &FoundFns,
366                                   uint64_t &BaseSegmentAddress) {
367   const StringRef FileName = MachOObj->getFileName();
368   for (const SymbolRef &Symbol : MachOObj->symbols()) {
369     StringRef SymName = unwrapOrError(Symbol.getName(), FileName);
370     if (!SymName.startswith("ltmp"))
371       Symbols.push_back(Symbol);
372   }
373 
374   for (const SectionRef &Section : MachOObj->sections())
375     Sections.push_back(Section);
376 
377   bool BaseSegmentAddressSet = false;
378   for (const auto &Command : MachOObj->load_commands()) {
379     if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
380       // We found a function starts segment, parse the addresses for later
381       // consumption.
382       MachO::linkedit_data_command LLC =
383           MachOObj->getLinkeditDataLoadCommand(Command);
384 
385       MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
386     } else if (Command.C.cmd == MachO::LC_SEGMENT) {
387       MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
388       StringRef SegName = SLC.segname;
389       if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
390         BaseSegmentAddressSet = true;
391         BaseSegmentAddress = SLC.vmaddr;
392       }
393     } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
394       MachO::segment_command_64 SLC = MachOObj->getSegment64LoadCommand(Command);
395       StringRef SegName = SLC.segname;
396       if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
397         BaseSegmentAddressSet = true;
398         BaseSegmentAddress = SLC.vmaddr;
399       }
400     }
401   }
402 }
403 
404 static bool DumpAndSkipDataInCode(uint64_t PC, const uint8_t *bytes,
405                                  DiceTable &Dices, uint64_t &InstSize) {
406   // Check the data in code table here to see if this is data not an
407   // instruction to be disassembled.
408   DiceTable Dice;
409   Dice.push_back(std::make_pair(PC, DiceRef()));
410   dice_table_iterator DTI =
411       std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
412                   compareDiceTableEntries);
413   if (DTI != Dices.end()) {
414     uint16_t Length;
415     DTI->second.getLength(Length);
416     uint16_t Kind;
417     DTI->second.getKind(Kind);
418     InstSize = DumpDataInCode(bytes, Length, Kind);
419     if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
420         (PC == (DTI->first + Length - 1)) && (Length & 1))
421       InstSize++;
422     return true;
423   }
424   return false;
425 }
426 
427 static void printRelocationTargetName(const MachOObjectFile *O,
428                                       const MachO::any_relocation_info &RE,
429                                       raw_string_ostream &Fmt) {
430   // Target of a scattered relocation is an address.  In the interest of
431   // generating pretty output, scan through the symbol table looking for a
432   // symbol that aligns with that address.  If we find one, print it.
433   // Otherwise, we just print the hex address of the target.
434   const StringRef FileName = O->getFileName();
435   if (O->isRelocationScattered(RE)) {
436     uint32_t Val = O->getPlainRelocationSymbolNum(RE);
437 
438     for (const SymbolRef &Symbol : O->symbols()) {
439       uint64_t Addr = unwrapOrError(Symbol.getAddress(), FileName);
440       if (Addr != Val)
441         continue;
442       Fmt << unwrapOrError(Symbol.getName(), FileName);
443       return;
444     }
445 
446     // If we couldn't find a symbol that this relocation refers to, try
447     // to find a section beginning instead.
448     for (const SectionRef &Section : ToolSectionFilter(*O)) {
449       uint64_t Addr = Section.getAddress();
450       if (Addr != Val)
451         continue;
452       StringRef NameOrErr = unwrapOrError(Section.getName(), O->getFileName());
453       Fmt << NameOrErr;
454       return;
455     }
456 
457     Fmt << format("0x%x", Val);
458     return;
459   }
460 
461   StringRef S;
462   bool isExtern = O->getPlainRelocationExternal(RE);
463   uint64_t Val = O->getPlainRelocationSymbolNum(RE);
464 
465   if (O->getAnyRelocationType(RE) == MachO::ARM64_RELOC_ADDEND) {
466     Fmt << format("0x%0" PRIx64, Val);
467     return;
468   }
469 
470   if (isExtern) {
471     symbol_iterator SI = O->symbol_begin();
472     advance(SI, Val);
473     S = unwrapOrError(SI->getName(), FileName);
474   } else {
475     section_iterator SI = O->section_begin();
476     // Adjust for the fact that sections are 1-indexed.
477     if (Val == 0) {
478       Fmt << "0 (?,?)";
479       return;
480     }
481     uint32_t I = Val - 1;
482     while (I != 0 && SI != O->section_end()) {
483       --I;
484       advance(SI, 1);
485     }
486     if (SI == O->section_end()) {
487       Fmt << Val << " (?,?)";
488     } else {
489       if (Expected<StringRef> NameOrErr = SI->getName())
490         S = *NameOrErr;
491       else
492         consumeError(NameOrErr.takeError());
493     }
494   }
495 
496   Fmt << S;
497 }
498 
499 Error getMachORelocationValueString(const MachOObjectFile *Obj,
500                                     const RelocationRef &RelRef,
501                                     SmallVectorImpl<char> &Result) {
502   DataRefImpl Rel = RelRef.getRawDataRefImpl();
503   MachO::any_relocation_info RE = Obj->getRelocation(Rel);
504 
505   unsigned Arch = Obj->getArch();
506 
507   std::string FmtBuf;
508   raw_string_ostream Fmt(FmtBuf);
509   unsigned Type = Obj->getAnyRelocationType(RE);
510   bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
511 
512   // Determine any addends that should be displayed with the relocation.
513   // These require decoding the relocation type, which is triple-specific.
514 
515   // X86_64 has entirely custom relocation types.
516   if (Arch == Triple::x86_64) {
517     switch (Type) {
518     case MachO::X86_64_RELOC_GOT_LOAD:
519     case MachO::X86_64_RELOC_GOT: {
520       printRelocationTargetName(Obj, RE, Fmt);
521       Fmt << "@GOT";
522       if (IsPCRel)
523         Fmt << "PCREL";
524       break;
525     }
526     case MachO::X86_64_RELOC_SUBTRACTOR: {
527       DataRefImpl RelNext = Rel;
528       Obj->moveRelocationNext(RelNext);
529       MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
530 
531       // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
532       // X86_64_RELOC_UNSIGNED.
533       // NOTE: Scattered relocations don't exist on x86_64.
534       unsigned RType = Obj->getAnyRelocationType(RENext);
535       if (RType != MachO::X86_64_RELOC_UNSIGNED)
536         reportError(Obj->getFileName(), "Expected X86_64_RELOC_UNSIGNED after "
537                                         "X86_64_RELOC_SUBTRACTOR.");
538 
539       // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
540       // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
541       printRelocationTargetName(Obj, RENext, Fmt);
542       Fmt << "-";
543       printRelocationTargetName(Obj, RE, Fmt);
544       break;
545     }
546     case MachO::X86_64_RELOC_TLV:
547       printRelocationTargetName(Obj, RE, Fmt);
548       Fmt << "@TLV";
549       if (IsPCRel)
550         Fmt << "P";
551       break;
552     case MachO::X86_64_RELOC_SIGNED_1:
553       printRelocationTargetName(Obj, RE, Fmt);
554       Fmt << "-1";
555       break;
556     case MachO::X86_64_RELOC_SIGNED_2:
557       printRelocationTargetName(Obj, RE, Fmt);
558       Fmt << "-2";
559       break;
560     case MachO::X86_64_RELOC_SIGNED_4:
561       printRelocationTargetName(Obj, RE, Fmt);
562       Fmt << "-4";
563       break;
564     default:
565       printRelocationTargetName(Obj, RE, Fmt);
566       break;
567     }
568     // X86 and ARM share some relocation types in common.
569   } else if (Arch == Triple::x86 || Arch == Triple::arm ||
570              Arch == Triple::ppc) {
571     // Generic relocation types...
572     switch (Type) {
573     case MachO::GENERIC_RELOC_PAIR: // prints no info
574       return Error::success();
575     case MachO::GENERIC_RELOC_SECTDIFF: {
576       DataRefImpl RelNext = Rel;
577       Obj->moveRelocationNext(RelNext);
578       MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
579 
580       // X86 sect diff's must be followed by a relocation of type
581       // GENERIC_RELOC_PAIR.
582       unsigned RType = Obj->getAnyRelocationType(RENext);
583 
584       if (RType != MachO::GENERIC_RELOC_PAIR)
585         reportError(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
586                                         "GENERIC_RELOC_SECTDIFF.");
587 
588       printRelocationTargetName(Obj, RE, Fmt);
589       Fmt << "-";
590       printRelocationTargetName(Obj, RENext, Fmt);
591       break;
592     }
593     }
594 
595     if (Arch == Triple::x86 || Arch == Triple::ppc) {
596       switch (Type) {
597       case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
598         DataRefImpl RelNext = Rel;
599         Obj->moveRelocationNext(RelNext);
600         MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
601 
602         // X86 sect diff's must be followed by a relocation of type
603         // GENERIC_RELOC_PAIR.
604         unsigned RType = Obj->getAnyRelocationType(RENext);
605         if (RType != MachO::GENERIC_RELOC_PAIR)
606           reportError(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
607                                           "GENERIC_RELOC_LOCAL_SECTDIFF.");
608 
609         printRelocationTargetName(Obj, RE, Fmt);
610         Fmt << "-";
611         printRelocationTargetName(Obj, RENext, Fmt);
612         break;
613       }
614       case MachO::GENERIC_RELOC_TLV: {
615         printRelocationTargetName(Obj, RE, Fmt);
616         Fmt << "@TLV";
617         if (IsPCRel)
618           Fmt << "P";
619         break;
620       }
621       default:
622         printRelocationTargetName(Obj, RE, Fmt);
623       }
624     } else { // ARM-specific relocations
625       switch (Type) {
626       case MachO::ARM_RELOC_HALF:
627       case MachO::ARM_RELOC_HALF_SECTDIFF: {
628         // Half relocations steal a bit from the length field to encode
629         // whether this is an upper16 or a lower16 relocation.
630         bool isUpper = (Obj->getAnyRelocationLength(RE) & 0x1) == 1;
631 
632         if (isUpper)
633           Fmt << ":upper16:(";
634         else
635           Fmt << ":lower16:(";
636         printRelocationTargetName(Obj, RE, Fmt);
637 
638         DataRefImpl RelNext = Rel;
639         Obj->moveRelocationNext(RelNext);
640         MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
641 
642         // ARM half relocs must be followed by a relocation of type
643         // ARM_RELOC_PAIR.
644         unsigned RType = Obj->getAnyRelocationType(RENext);
645         if (RType != MachO::ARM_RELOC_PAIR)
646           reportError(Obj->getFileName(), "Expected ARM_RELOC_PAIR after "
647                                           "ARM_RELOC_HALF");
648 
649         // NOTE: The half of the target virtual address is stashed in the
650         // address field of the secondary relocation, but we can't reverse
651         // engineer the constant offset from it without decoding the movw/movt
652         // instruction to find the other half in its immediate field.
653 
654         // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
655         // symbol/section pointer of the follow-on relocation.
656         if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
657           Fmt << "-";
658           printRelocationTargetName(Obj, RENext, Fmt);
659         }
660 
661         Fmt << ")";
662         break;
663       }
664       default: {
665         printRelocationTargetName(Obj, RE, Fmt);
666       }
667       }
668     }
669   } else
670     printRelocationTargetName(Obj, RE, Fmt);
671 
672   Fmt.flush();
673   Result.append(FmtBuf.begin(), FmtBuf.end());
674   return Error::success();
675 }
676 
677 static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
678                                      uint32_t n, uint32_t count,
679                                      uint32_t stride, uint64_t addr) {
680   MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
681   uint32_t nindirectsyms = Dysymtab.nindirectsyms;
682   if (n > nindirectsyms)
683     outs() << " (entries start past the end of the indirect symbol "
684               "table) (reserved1 field greater than the table size)";
685   else if (n + count > nindirectsyms)
686     outs() << " (entries extends past the end of the indirect symbol "
687               "table)";
688   outs() << "\n";
689   uint32_t cputype = O->getHeader().cputype;
690   if (cputype & MachO::CPU_ARCH_ABI64)
691     outs() << "address            index";
692   else
693     outs() << "address    index";
694   if (verbose)
695     outs() << " name\n";
696   else
697     outs() << "\n";
698   for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
699     if (cputype & MachO::CPU_ARCH_ABI64)
700       outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
701     else
702       outs() << format("0x%08" PRIx32, (uint32_t)addr + j * stride) << " ";
703     MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
704     uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
705     if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
706       outs() << "LOCAL\n";
707       continue;
708     }
709     if (indirect_symbol ==
710         (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
711       outs() << "LOCAL ABSOLUTE\n";
712       continue;
713     }
714     if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
715       outs() << "ABSOLUTE\n";
716       continue;
717     }
718     outs() << format("%5u ", indirect_symbol);
719     if (verbose) {
720       MachO::symtab_command Symtab = O->getSymtabLoadCommand();
721       if (indirect_symbol < Symtab.nsyms) {
722         symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
723         SymbolRef Symbol = *Sym;
724         outs() << unwrapOrError(Symbol.getName(), O->getFileName());
725       } else {
726         outs() << "?";
727       }
728     }
729     outs() << "\n";
730   }
731 }
732 
733 static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
734   for (const auto &Load : O->load_commands()) {
735     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
736       MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
737       for (unsigned J = 0; J < Seg.nsects; ++J) {
738         MachO::section_64 Sec = O->getSection64(Load, J);
739         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
740         if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
741             section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
742             section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
743             section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
744             section_type == MachO::S_SYMBOL_STUBS) {
745           uint32_t stride;
746           if (section_type == MachO::S_SYMBOL_STUBS)
747             stride = Sec.reserved2;
748           else
749             stride = 8;
750           if (stride == 0) {
751             outs() << "Can't print indirect symbols for (" << Sec.segname << ","
752                    << Sec.sectname << ") "
753                    << "(size of stubs in reserved2 field is zero)\n";
754             continue;
755           }
756           uint32_t count = Sec.size / stride;
757           outs() << "Indirect symbols for (" << Sec.segname << ","
758                  << Sec.sectname << ") " << count << " entries";
759           uint32_t n = Sec.reserved1;
760           PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
761         }
762       }
763     } else if (Load.C.cmd == MachO::LC_SEGMENT) {
764       MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
765       for (unsigned J = 0; J < Seg.nsects; ++J) {
766         MachO::section Sec = O->getSection(Load, J);
767         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
768         if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
769             section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
770             section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
771             section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
772             section_type == MachO::S_SYMBOL_STUBS) {
773           uint32_t stride;
774           if (section_type == MachO::S_SYMBOL_STUBS)
775             stride = Sec.reserved2;
776           else
777             stride = 4;
778           if (stride == 0) {
779             outs() << "Can't print indirect symbols for (" << Sec.segname << ","
780                    << Sec.sectname << ") "
781                    << "(size of stubs in reserved2 field is zero)\n";
782             continue;
783           }
784           uint32_t count = Sec.size / stride;
785           outs() << "Indirect symbols for (" << Sec.segname << ","
786                  << Sec.sectname << ") " << count << " entries";
787           uint32_t n = Sec.reserved1;
788           PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
789         }
790       }
791     }
792   }
793 }
794 
795 static void PrintRType(const uint64_t cputype, const unsigned r_type) {
796   static char const *generic_r_types[] = {
797     "VANILLA ", "PAIR    ", "SECTDIF ", "PBLAPTR ", "LOCSDIF ", "TLV     ",
798     "  6 (?) ", "  7 (?) ", "  8 (?) ", "  9 (?) ", " 10 (?) ", " 11 (?) ",
799     " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
800   };
801   static char const *x86_64_r_types[] = {
802     "UNSIGND ", "SIGNED  ", "BRANCH  ", "GOT_LD  ", "GOT     ", "SUB     ",
803     "SIGNED1 ", "SIGNED2 ", "SIGNED4 ", "TLV     ", " 10 (?) ", " 11 (?) ",
804     " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
805   };
806   static char const *arm_r_types[] = {
807     "VANILLA ", "PAIR    ", "SECTDIFF", "LOCSDIF ", "PBLAPTR ",
808     "BR24    ", "T_BR22  ", "T_BR32  ", "HALF    ", "HALFDIF ",
809     " 10 (?) ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
810   };
811   static char const *arm64_r_types[] = {
812     "UNSIGND ", "SUB     ", "BR26    ", "PAGE21  ", "PAGOF12 ",
813     "GOTLDP  ", "GOTLDPOF", "PTRTGOT ", "TLVLDP  ", "TLVLDPOF",
814     "ADDEND  ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
815   };
816 
817   if (r_type > 0xf){
818     outs() << format("%-7u", r_type) << " ";
819     return;
820   }
821   switch (cputype) {
822     case MachO::CPU_TYPE_I386:
823       outs() << generic_r_types[r_type];
824       break;
825     case MachO::CPU_TYPE_X86_64:
826       outs() << x86_64_r_types[r_type];
827       break;
828     case MachO::CPU_TYPE_ARM:
829       outs() << arm_r_types[r_type];
830       break;
831     case MachO::CPU_TYPE_ARM64:
832     case MachO::CPU_TYPE_ARM64_32:
833       outs() << arm64_r_types[r_type];
834       break;
835     default:
836       outs() << format("%-7u ", r_type);
837   }
838 }
839 
840 static void PrintRLength(const uint64_t cputype, const unsigned r_type,
841                          const unsigned r_length, const bool previous_arm_half){
842   if (cputype == MachO::CPU_TYPE_ARM &&
843       (r_type == MachO::ARM_RELOC_HALF ||
844        r_type == MachO::ARM_RELOC_HALF_SECTDIFF || previous_arm_half == true)) {
845     if ((r_length & 0x1) == 0)
846       outs() << "lo/";
847     else
848       outs() << "hi/";
849     if ((r_length & 0x1) == 0)
850       outs() << "arm ";
851     else
852       outs() << "thm ";
853   } else {
854     switch (r_length) {
855       case 0:
856         outs() << "byte   ";
857         break;
858       case 1:
859         outs() << "word   ";
860         break;
861       case 2:
862         outs() << "long   ";
863         break;
864       case 3:
865         if (cputype == MachO::CPU_TYPE_X86_64)
866           outs() << "quad   ";
867         else
868           outs() << format("?(%2d)  ", r_length);
869         break;
870       default:
871         outs() << format("?(%2d)  ", r_length);
872     }
873   }
874 }
875 
876 static void PrintRelocationEntries(const MachOObjectFile *O,
877                                    const relocation_iterator Begin,
878                                    const relocation_iterator End,
879                                    const uint64_t cputype,
880                                    const bool verbose) {
881   const MachO::symtab_command Symtab = O->getSymtabLoadCommand();
882   bool previous_arm_half = false;
883   bool previous_sectdiff = false;
884   uint32_t sectdiff_r_type = 0;
885 
886   for (relocation_iterator Reloc = Begin; Reloc != End; ++Reloc) {
887     const DataRefImpl Rel = Reloc->getRawDataRefImpl();
888     const MachO::any_relocation_info RE = O->getRelocation(Rel);
889     const unsigned r_type = O->getAnyRelocationType(RE);
890     const bool r_scattered = O->isRelocationScattered(RE);
891     const unsigned r_pcrel = O->getAnyRelocationPCRel(RE);
892     const unsigned r_length = O->getAnyRelocationLength(RE);
893     const unsigned r_address = O->getAnyRelocationAddress(RE);
894     const bool r_extern = (r_scattered ? false :
895                            O->getPlainRelocationExternal(RE));
896     const uint32_t r_value = (r_scattered ?
897                               O->getScatteredRelocationValue(RE) : 0);
898     const unsigned r_symbolnum = (r_scattered ? 0 :
899                                   O->getPlainRelocationSymbolNum(RE));
900 
901     if (r_scattered && cputype != MachO::CPU_TYPE_X86_64) {
902       if (verbose) {
903         // scattered: address
904         if ((cputype == MachO::CPU_TYPE_I386 &&
905              r_type == MachO::GENERIC_RELOC_PAIR) ||
906             (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR))
907           outs() << "         ";
908         else
909           outs() << format("%08x ", (unsigned int)r_address);
910 
911         // scattered: pcrel
912         if (r_pcrel)
913           outs() << "True  ";
914         else
915           outs() << "False ";
916 
917         // scattered: length
918         PrintRLength(cputype, r_type, r_length, previous_arm_half);
919 
920         // scattered: extern & type
921         outs() << "n/a    ";
922         PrintRType(cputype, r_type);
923 
924         // scattered: scattered & value
925         outs() << format("True      0x%08x", (unsigned int)r_value);
926         if (previous_sectdiff == false) {
927           if ((cputype == MachO::CPU_TYPE_ARM &&
928                r_type == MachO::ARM_RELOC_PAIR))
929             outs() << format(" half = 0x%04x ", (unsigned int)r_address);
930         } else if (cputype == MachO::CPU_TYPE_ARM &&
931                    sectdiff_r_type == MachO::ARM_RELOC_HALF_SECTDIFF)
932           outs() << format(" other_half = 0x%04x ", (unsigned int)r_address);
933         if ((cputype == MachO::CPU_TYPE_I386 &&
934              (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
935               r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) ||
936             (cputype == MachO::CPU_TYPE_ARM &&
937              (sectdiff_r_type == MachO::ARM_RELOC_SECTDIFF ||
938               sectdiff_r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
939               sectdiff_r_type == MachO::ARM_RELOC_HALF_SECTDIFF))) {
940           previous_sectdiff = true;
941           sectdiff_r_type = r_type;
942         } else {
943           previous_sectdiff = false;
944           sectdiff_r_type = 0;
945         }
946         if (cputype == MachO::CPU_TYPE_ARM &&
947             (r_type == MachO::ARM_RELOC_HALF ||
948              r_type == MachO::ARM_RELOC_HALF_SECTDIFF))
949           previous_arm_half = true;
950         else
951           previous_arm_half = false;
952         outs() << "\n";
953       }
954       else {
955         // scattered: address pcrel length extern type scattered value
956         outs() << format("%08x %1d     %-2d     n/a    %-7d 1         0x%08x\n",
957                          (unsigned int)r_address, r_pcrel, r_length, r_type,
958                          (unsigned int)r_value);
959       }
960     }
961     else {
962       if (verbose) {
963         // plain: address
964         if (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR)
965           outs() << "         ";
966         else
967           outs() << format("%08x ", (unsigned int)r_address);
968 
969         // plain: pcrel
970         if (r_pcrel)
971           outs() << "True  ";
972         else
973           outs() << "False ";
974 
975         // plain: length
976         PrintRLength(cputype, r_type, r_length, previous_arm_half);
977 
978         if (r_extern) {
979           // plain: extern & type & scattered
980           outs() << "True   ";
981           PrintRType(cputype, r_type);
982           outs() << "False     ";
983 
984           // plain: symbolnum/value
985           if (r_symbolnum > Symtab.nsyms)
986             outs() << format("?(%d)\n", r_symbolnum);
987           else {
988             SymbolRef Symbol = *O->getSymbolByIndex(r_symbolnum);
989             Expected<StringRef> SymNameNext = Symbol.getName();
990             const char *name = NULL;
991             if (SymNameNext)
992               name = SymNameNext->data();
993             if (name == NULL)
994               outs() << format("?(%d)\n", r_symbolnum);
995             else
996               outs() << name << "\n";
997           }
998         }
999         else {
1000           // plain: extern & type & scattered
1001           outs() << "False  ";
1002           PrintRType(cputype, r_type);
1003           outs() << "False     ";
1004 
1005           // plain: symbolnum/value
1006           if (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR)
1007             outs() << format("other_half = 0x%04x\n", (unsigned int)r_address);
1008           else if ((cputype == MachO::CPU_TYPE_ARM64 ||
1009                     cputype == MachO::CPU_TYPE_ARM64_32) &&
1010                    r_type == MachO::ARM64_RELOC_ADDEND)
1011             outs() << format("addend = 0x%06x\n", (unsigned int)r_symbolnum);
1012           else {
1013             outs() << format("%d ", r_symbolnum);
1014             if (r_symbolnum == MachO::R_ABS)
1015               outs() << "R_ABS\n";
1016             else {
1017               // in this case, r_symbolnum is actually a 1-based section number
1018               uint32_t nsects = O->section_end()->getRawDataRefImpl().d.a;
1019               if (r_symbolnum > 0 && r_symbolnum <= nsects) {
1020                 object::DataRefImpl DRI;
1021                 DRI.d.a = r_symbolnum-1;
1022                 StringRef SegName = O->getSectionFinalSegmentName(DRI);
1023                 if (Expected<StringRef> NameOrErr = O->getSectionName(DRI))
1024                   outs() << "(" << SegName << "," << *NameOrErr << ")\n";
1025                 else
1026                   outs() << "(?,?)\n";
1027               }
1028               else {
1029                 outs() << "(?,?)\n";
1030               }
1031             }
1032           }
1033         }
1034         if (cputype == MachO::CPU_TYPE_ARM &&
1035             (r_type == MachO::ARM_RELOC_HALF ||
1036              r_type == MachO::ARM_RELOC_HALF_SECTDIFF))
1037           previous_arm_half = true;
1038         else
1039           previous_arm_half = false;
1040       }
1041       else {
1042         // plain: address pcrel length extern type scattered symbolnum/section
1043         outs() << format("%08x %1d     %-2d     %1d      %-7d 0         %d\n",
1044                          (unsigned int)r_address, r_pcrel, r_length, r_extern,
1045                          r_type, r_symbolnum);
1046       }
1047     }
1048   }
1049 }
1050 
1051 static void PrintRelocations(const MachOObjectFile *O, const bool verbose) {
1052   const uint64_t cputype = O->getHeader().cputype;
1053   const MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
1054   if (Dysymtab.nextrel != 0) {
1055     outs() << "External relocation information " << Dysymtab.nextrel
1056            << " entries";
1057     outs() << "\naddress  pcrel length extern type    scattered "
1058               "symbolnum/value\n";
1059     PrintRelocationEntries(O, O->extrel_begin(), O->extrel_end(), cputype,
1060                            verbose);
1061   }
1062   if (Dysymtab.nlocrel != 0) {
1063     outs() << format("Local relocation information %u entries",
1064                      Dysymtab.nlocrel);
1065     outs() << "\naddress  pcrel length extern type    scattered "
1066               "symbolnum/value\n";
1067     PrintRelocationEntries(O, O->locrel_begin(), O->locrel_end(), cputype,
1068                            verbose);
1069   }
1070   for (const auto &Load : O->load_commands()) {
1071     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
1072       const MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
1073       for (unsigned J = 0; J < Seg.nsects; ++J) {
1074         const MachO::section_64 Sec = O->getSection64(Load, J);
1075         if (Sec.nreloc != 0) {
1076           DataRefImpl DRI;
1077           DRI.d.a = J;
1078           const StringRef SegName = O->getSectionFinalSegmentName(DRI);
1079           if (Expected<StringRef> NameOrErr = O->getSectionName(DRI))
1080             outs() << "Relocation information (" << SegName << "," << *NameOrErr
1081                    << format(") %u entries", Sec.nreloc);
1082           else
1083             outs() << "Relocation information (" << SegName << ",?) "
1084                    << format("%u entries", Sec.nreloc);
1085           outs() << "\naddress  pcrel length extern type    scattered "
1086                     "symbolnum/value\n";
1087           PrintRelocationEntries(O, O->section_rel_begin(DRI),
1088                                  O->section_rel_end(DRI), cputype, verbose);
1089         }
1090       }
1091     } else if (Load.C.cmd == MachO::LC_SEGMENT) {
1092       const MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
1093       for (unsigned J = 0; J < Seg.nsects; ++J) {
1094         const MachO::section Sec = O->getSection(Load, J);
1095         if (Sec.nreloc != 0) {
1096           DataRefImpl DRI;
1097           DRI.d.a = J;
1098           const StringRef SegName = O->getSectionFinalSegmentName(DRI);
1099           if (Expected<StringRef> NameOrErr = O->getSectionName(DRI))
1100             outs() << "Relocation information (" << SegName << "," << *NameOrErr
1101                    << format(") %u entries", Sec.nreloc);
1102           else
1103             outs() << "Relocation information (" << SegName << ",?) "
1104                    << format("%u entries", Sec.nreloc);
1105           outs() << "\naddress  pcrel length extern type    scattered "
1106                     "symbolnum/value\n";
1107           PrintRelocationEntries(O, O->section_rel_begin(DRI),
1108                                  O->section_rel_end(DRI), cputype, verbose);
1109         }
1110       }
1111     }
1112   }
1113 }
1114 
1115 static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
1116   MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
1117   uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
1118   outs() << "Data in code table (" << nentries << " entries)\n";
1119   outs() << "offset     length kind\n";
1120   for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
1121        ++DI) {
1122     uint32_t Offset;
1123     DI->getOffset(Offset);
1124     outs() << format("0x%08" PRIx32, Offset) << " ";
1125     uint16_t Length;
1126     DI->getLength(Length);
1127     outs() << format("%6u", Length) << " ";
1128     uint16_t Kind;
1129     DI->getKind(Kind);
1130     if (verbose) {
1131       switch (Kind) {
1132       case MachO::DICE_KIND_DATA:
1133         outs() << "DATA";
1134         break;
1135       case MachO::DICE_KIND_JUMP_TABLE8:
1136         outs() << "JUMP_TABLE8";
1137         break;
1138       case MachO::DICE_KIND_JUMP_TABLE16:
1139         outs() << "JUMP_TABLE16";
1140         break;
1141       case MachO::DICE_KIND_JUMP_TABLE32:
1142         outs() << "JUMP_TABLE32";
1143         break;
1144       case MachO::DICE_KIND_ABS_JUMP_TABLE32:
1145         outs() << "ABS_JUMP_TABLE32";
1146         break;
1147       default:
1148         outs() << format("0x%04" PRIx32, Kind);
1149         break;
1150       }
1151     } else
1152       outs() << format("0x%04" PRIx32, Kind);
1153     outs() << "\n";
1154   }
1155 }
1156 
1157 static void PrintLinkOptHints(MachOObjectFile *O) {
1158   MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
1159   const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
1160   uint32_t nloh = LohLC.datasize;
1161   outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
1162   for (uint32_t i = 0; i < nloh;) {
1163     unsigned n;
1164     uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
1165     i += n;
1166     outs() << "    identifier " << identifier << " ";
1167     if (i >= nloh)
1168       return;
1169     switch (identifier) {
1170     case 1:
1171       outs() << "AdrpAdrp\n";
1172       break;
1173     case 2:
1174       outs() << "AdrpLdr\n";
1175       break;
1176     case 3:
1177       outs() << "AdrpAddLdr\n";
1178       break;
1179     case 4:
1180       outs() << "AdrpLdrGotLdr\n";
1181       break;
1182     case 5:
1183       outs() << "AdrpAddStr\n";
1184       break;
1185     case 6:
1186       outs() << "AdrpLdrGotStr\n";
1187       break;
1188     case 7:
1189       outs() << "AdrpAdd\n";
1190       break;
1191     case 8:
1192       outs() << "AdrpLdrGot\n";
1193       break;
1194     default:
1195       outs() << "Unknown identifier value\n";
1196       break;
1197     }
1198     uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
1199     i += n;
1200     outs() << "    narguments " << narguments << "\n";
1201     if (i >= nloh)
1202       return;
1203 
1204     for (uint32_t j = 0; j < narguments; j++) {
1205       uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
1206       i += n;
1207       outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
1208       if (i >= nloh)
1209         return;
1210     }
1211   }
1212 }
1213 
1214 static void PrintDylibs(MachOObjectFile *O, bool JustId) {
1215   unsigned Index = 0;
1216   for (const auto &Load : O->load_commands()) {
1217     if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
1218         (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
1219                      Load.C.cmd == MachO::LC_LOAD_DYLIB ||
1220                      Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
1221                      Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
1222                      Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
1223                      Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
1224       MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
1225       if (dl.dylib.name < dl.cmdsize) {
1226         const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
1227         if (JustId)
1228           outs() << p << "\n";
1229         else {
1230           outs() << "\t" << p;
1231           outs() << " (compatibility version "
1232                  << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
1233                  << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
1234                  << (dl.dylib.compatibility_version & 0xff) << ",";
1235           outs() << " current version "
1236                  << ((dl.dylib.current_version >> 16) & 0xffff) << "."
1237                  << ((dl.dylib.current_version >> 8) & 0xff) << "."
1238                  << (dl.dylib.current_version & 0xff);
1239           if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
1240             outs() << ", weak";
1241           if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
1242             outs() << ", reexport";
1243           if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
1244             outs() << ", upward";
1245           if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
1246             outs() << ", lazy";
1247           outs() << ")\n";
1248         }
1249       } else {
1250         outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
1251         if (Load.C.cmd == MachO::LC_ID_DYLIB)
1252           outs() << "LC_ID_DYLIB ";
1253         else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
1254           outs() << "LC_LOAD_DYLIB ";
1255         else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
1256           outs() << "LC_LOAD_WEAK_DYLIB ";
1257         else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
1258           outs() << "LC_LAZY_LOAD_DYLIB ";
1259         else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
1260           outs() << "LC_REEXPORT_DYLIB ";
1261         else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
1262           outs() << "LC_LOAD_UPWARD_DYLIB ";
1263         else
1264           outs() << "LC_??? ";
1265         outs() << "command " << Index++ << "\n";
1266       }
1267     }
1268   }
1269 }
1270 
1271 typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
1272 
1273 static void CreateSymbolAddressMap(MachOObjectFile *O,
1274                                    SymbolAddressMap *AddrMap) {
1275   // Create a map of symbol addresses to symbol names.
1276   const StringRef FileName = O->getFileName();
1277   for (const SymbolRef &Symbol : O->symbols()) {
1278     SymbolRef::Type ST = unwrapOrError(Symbol.getType(), FileName);
1279     if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
1280         ST == SymbolRef::ST_Other) {
1281       uint64_t Address = Symbol.getValue();
1282       StringRef SymName = unwrapOrError(Symbol.getName(), FileName);
1283       if (!SymName.startswith(".objc"))
1284         (*AddrMap)[Address] = SymName;
1285     }
1286   }
1287 }
1288 
1289 // GuessSymbolName is passed the address of what might be a symbol and a
1290 // pointer to the SymbolAddressMap.  It returns the name of a symbol
1291 // with that address or nullptr if no symbol is found with that address.
1292 static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
1293   const char *SymbolName = nullptr;
1294   // A DenseMap can't lookup up some values.
1295   if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
1296     StringRef name = AddrMap->lookup(value);
1297     if (!name.empty())
1298       SymbolName = name.data();
1299   }
1300   return SymbolName;
1301 }
1302 
1303 static void DumpCstringChar(const char c) {
1304   char p[2];
1305   p[0] = c;
1306   p[1] = '\0';
1307   outs().write_escaped(p);
1308 }
1309 
1310 static void DumpCstringSection(MachOObjectFile *O, const char *sect,
1311                                uint32_t sect_size, uint64_t sect_addr,
1312                                bool print_addresses) {
1313   for (uint32_t i = 0; i < sect_size; i++) {
1314     if (print_addresses) {
1315       if (O->is64Bit())
1316         outs() << format("%016" PRIx64, sect_addr + i) << "  ";
1317       else
1318         outs() << format("%08" PRIx64, sect_addr + i) << "  ";
1319     }
1320     for (; i < sect_size && sect[i] != '\0'; i++)
1321       DumpCstringChar(sect[i]);
1322     if (i < sect_size && sect[i] == '\0')
1323       outs() << "\n";
1324   }
1325 }
1326 
1327 static void DumpLiteral4(uint32_t l, float f) {
1328   outs() << format("0x%08" PRIx32, l);
1329   if ((l & 0x7f800000) != 0x7f800000)
1330     outs() << format(" (%.16e)\n", f);
1331   else {
1332     if (l == 0x7f800000)
1333       outs() << " (+Infinity)\n";
1334     else if (l == 0xff800000)
1335       outs() << " (-Infinity)\n";
1336     else if ((l & 0x00400000) == 0x00400000)
1337       outs() << " (non-signaling Not-a-Number)\n";
1338     else
1339       outs() << " (signaling Not-a-Number)\n";
1340   }
1341 }
1342 
1343 static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
1344                                 uint32_t sect_size, uint64_t sect_addr,
1345                                 bool print_addresses) {
1346   for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
1347     if (print_addresses) {
1348       if (O->is64Bit())
1349         outs() << format("%016" PRIx64, sect_addr + i) << "  ";
1350       else
1351         outs() << format("%08" PRIx64, sect_addr + i) << "  ";
1352     }
1353     float f;
1354     memcpy(&f, sect + i, sizeof(float));
1355     if (O->isLittleEndian() != sys::IsLittleEndianHost)
1356       sys::swapByteOrder(f);
1357     uint32_t l;
1358     memcpy(&l, sect + i, sizeof(uint32_t));
1359     if (O->isLittleEndian() != sys::IsLittleEndianHost)
1360       sys::swapByteOrder(l);
1361     DumpLiteral4(l, f);
1362   }
1363 }
1364 
1365 static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
1366                          double d) {
1367   outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
1368   uint32_t Hi, Lo;
1369   Hi = (O->isLittleEndian()) ? l1 : l0;
1370   Lo = (O->isLittleEndian()) ? l0 : l1;
1371 
1372   // Hi is the high word, so this is equivalent to if(isfinite(d))
1373   if ((Hi & 0x7ff00000) != 0x7ff00000)
1374     outs() << format(" (%.16e)\n", d);
1375   else {
1376     if (Hi == 0x7ff00000 && Lo == 0)
1377       outs() << " (+Infinity)\n";
1378     else if (Hi == 0xfff00000 && Lo == 0)
1379       outs() << " (-Infinity)\n";
1380     else if ((Hi & 0x00080000) == 0x00080000)
1381       outs() << " (non-signaling Not-a-Number)\n";
1382     else
1383       outs() << " (signaling Not-a-Number)\n";
1384   }
1385 }
1386 
1387 static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
1388                                 uint32_t sect_size, uint64_t sect_addr,
1389                                 bool print_addresses) {
1390   for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
1391     if (print_addresses) {
1392       if (O->is64Bit())
1393         outs() << format("%016" PRIx64, sect_addr + i) << "  ";
1394       else
1395         outs() << format("%08" PRIx64, sect_addr + i) << "  ";
1396     }
1397     double d;
1398     memcpy(&d, sect + i, sizeof(double));
1399     if (O->isLittleEndian() != sys::IsLittleEndianHost)
1400       sys::swapByteOrder(d);
1401     uint32_t l0, l1;
1402     memcpy(&l0, sect + i, sizeof(uint32_t));
1403     memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
1404     if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1405       sys::swapByteOrder(l0);
1406       sys::swapByteOrder(l1);
1407     }
1408     DumpLiteral8(O, l0, l1, d);
1409   }
1410 }
1411 
1412 static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
1413   outs() << format("0x%08" PRIx32, l0) << " ";
1414   outs() << format("0x%08" PRIx32, l1) << " ";
1415   outs() << format("0x%08" PRIx32, l2) << " ";
1416   outs() << format("0x%08" PRIx32, l3) << "\n";
1417 }
1418 
1419 static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
1420                                  uint32_t sect_size, uint64_t sect_addr,
1421                                  bool print_addresses) {
1422   for (uint32_t i = 0; i < sect_size; i += 16) {
1423     if (print_addresses) {
1424       if (O->is64Bit())
1425         outs() << format("%016" PRIx64, sect_addr + i) << "  ";
1426       else
1427         outs() << format("%08" PRIx64, sect_addr + i) << "  ";
1428     }
1429     uint32_t l0, l1, l2, l3;
1430     memcpy(&l0, sect + i, sizeof(uint32_t));
1431     memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
1432     memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
1433     memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
1434     if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1435       sys::swapByteOrder(l0);
1436       sys::swapByteOrder(l1);
1437       sys::swapByteOrder(l2);
1438       sys::swapByteOrder(l3);
1439     }
1440     DumpLiteral16(l0, l1, l2, l3);
1441   }
1442 }
1443 
1444 static void DumpLiteralPointerSection(MachOObjectFile *O,
1445                                       const SectionRef &Section,
1446                                       const char *sect, uint32_t sect_size,
1447                                       uint64_t sect_addr,
1448                                       bool print_addresses) {
1449   // Collect the literal sections in this Mach-O file.
1450   std::vector<SectionRef> LiteralSections;
1451   for (const SectionRef &Section : O->sections()) {
1452     DataRefImpl Ref = Section.getRawDataRefImpl();
1453     uint32_t section_type;
1454     if (O->is64Bit()) {
1455       const MachO::section_64 Sec = O->getSection64(Ref);
1456       section_type = Sec.flags & MachO::SECTION_TYPE;
1457     } else {
1458       const MachO::section Sec = O->getSection(Ref);
1459       section_type = Sec.flags & MachO::SECTION_TYPE;
1460     }
1461     if (section_type == MachO::S_CSTRING_LITERALS ||
1462         section_type == MachO::S_4BYTE_LITERALS ||
1463         section_type == MachO::S_8BYTE_LITERALS ||
1464         section_type == MachO::S_16BYTE_LITERALS)
1465       LiteralSections.push_back(Section);
1466   }
1467 
1468   // Set the size of the literal pointer.
1469   uint32_t lp_size = O->is64Bit() ? 8 : 4;
1470 
1471   // Collect the external relocation symbols for the literal pointers.
1472   std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1473   for (const RelocationRef &Reloc : Section.relocations()) {
1474     DataRefImpl Rel;
1475     MachO::any_relocation_info RE;
1476     bool isExtern = false;
1477     Rel = Reloc.getRawDataRefImpl();
1478     RE = O->getRelocation(Rel);
1479     isExtern = O->getPlainRelocationExternal(RE);
1480     if (isExtern) {
1481       uint64_t RelocOffset = Reloc.getOffset();
1482       symbol_iterator RelocSym = Reloc.getSymbol();
1483       Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
1484     }
1485   }
1486   array_pod_sort(Relocs.begin(), Relocs.end());
1487 
1488   // Dump each literal pointer.
1489   for (uint32_t i = 0; i < sect_size; i += lp_size) {
1490     if (print_addresses) {
1491       if (O->is64Bit())
1492         outs() << format("%016" PRIx64, sect_addr + i) << "  ";
1493       else
1494         outs() << format("%08" PRIx64, sect_addr + i) << "  ";
1495     }
1496     uint64_t lp;
1497     if (O->is64Bit()) {
1498       memcpy(&lp, sect + i, sizeof(uint64_t));
1499       if (O->isLittleEndian() != sys::IsLittleEndianHost)
1500         sys::swapByteOrder(lp);
1501     } else {
1502       uint32_t li;
1503       memcpy(&li, sect + i, sizeof(uint32_t));
1504       if (O->isLittleEndian() != sys::IsLittleEndianHost)
1505         sys::swapByteOrder(li);
1506       lp = li;
1507     }
1508 
1509     // First look for an external relocation entry for this literal pointer.
1510     auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
1511       return P.first == i;
1512     });
1513     if (Reloc != Relocs.end()) {
1514       symbol_iterator RelocSym = Reloc->second;
1515       StringRef SymName = unwrapOrError(RelocSym->getName(), O->getFileName());
1516       outs() << "external relocation entry for symbol:" << SymName << "\n";
1517       continue;
1518     }
1519 
1520     // For local references see what the section the literal pointer points to.
1521     auto Sect = find_if(LiteralSections, [&](const SectionRef &R) {
1522       return lp >= R.getAddress() && lp < R.getAddress() + R.getSize();
1523     });
1524     if (Sect == LiteralSections.end()) {
1525       outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
1526       continue;
1527     }
1528 
1529     uint64_t SectAddress = Sect->getAddress();
1530     uint64_t SectSize = Sect->getSize();
1531 
1532     StringRef SectName;
1533     Expected<StringRef> SectNameOrErr = Sect->getName();
1534     if (SectNameOrErr)
1535       SectName = *SectNameOrErr;
1536     else
1537       consumeError(SectNameOrErr.takeError());
1538 
1539     DataRefImpl Ref = Sect->getRawDataRefImpl();
1540     StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
1541     outs() << SegmentName << ":" << SectName << ":";
1542 
1543     uint32_t section_type;
1544     if (O->is64Bit()) {
1545       const MachO::section_64 Sec = O->getSection64(Ref);
1546       section_type = Sec.flags & MachO::SECTION_TYPE;
1547     } else {
1548       const MachO::section Sec = O->getSection(Ref);
1549       section_type = Sec.flags & MachO::SECTION_TYPE;
1550     }
1551 
1552     StringRef BytesStr = unwrapOrError(Sect->getContents(), O->getFileName());
1553 
1554     const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
1555 
1556     switch (section_type) {
1557     case MachO::S_CSTRING_LITERALS:
1558       for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
1559            i++) {
1560         DumpCstringChar(Contents[i]);
1561       }
1562       outs() << "\n";
1563       break;
1564     case MachO::S_4BYTE_LITERALS:
1565       float f;
1566       memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
1567       uint32_t l;
1568       memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
1569       if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1570         sys::swapByteOrder(f);
1571         sys::swapByteOrder(l);
1572       }
1573       DumpLiteral4(l, f);
1574       break;
1575     case MachO::S_8BYTE_LITERALS: {
1576       double d;
1577       memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
1578       uint32_t l0, l1;
1579       memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
1580       memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
1581              sizeof(uint32_t));
1582       if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1583         sys::swapByteOrder(f);
1584         sys::swapByteOrder(l0);
1585         sys::swapByteOrder(l1);
1586       }
1587       DumpLiteral8(O, l0, l1, d);
1588       break;
1589     }
1590     case MachO::S_16BYTE_LITERALS: {
1591       uint32_t l0, l1, l2, l3;
1592       memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
1593       memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
1594              sizeof(uint32_t));
1595       memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
1596              sizeof(uint32_t));
1597       memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
1598              sizeof(uint32_t));
1599       if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1600         sys::swapByteOrder(l0);
1601         sys::swapByteOrder(l1);
1602         sys::swapByteOrder(l2);
1603         sys::swapByteOrder(l3);
1604       }
1605       DumpLiteral16(l0, l1, l2, l3);
1606       break;
1607     }
1608     }
1609   }
1610 }
1611 
1612 static void DumpInitTermPointerSection(MachOObjectFile *O,
1613                                        const SectionRef &Section,
1614                                        const char *sect,
1615                                        uint32_t sect_size, uint64_t sect_addr,
1616                                        SymbolAddressMap *AddrMap,
1617                                        bool verbose) {
1618   uint32_t stride;
1619   stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t);
1620 
1621   // Collect the external relocation symbols for the pointers.
1622   std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1623   for (const RelocationRef &Reloc : Section.relocations()) {
1624     DataRefImpl Rel;
1625     MachO::any_relocation_info RE;
1626     bool isExtern = false;
1627     Rel = Reloc.getRawDataRefImpl();
1628     RE = O->getRelocation(Rel);
1629     isExtern = O->getPlainRelocationExternal(RE);
1630     if (isExtern) {
1631       uint64_t RelocOffset = Reloc.getOffset();
1632       symbol_iterator RelocSym = Reloc.getSymbol();
1633       Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
1634     }
1635   }
1636   array_pod_sort(Relocs.begin(), Relocs.end());
1637 
1638   for (uint32_t i = 0; i < sect_size; i += stride) {
1639     const char *SymbolName = nullptr;
1640     uint64_t p;
1641     if (O->is64Bit()) {
1642       outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
1643       uint64_t pointer_value;
1644       memcpy(&pointer_value, sect + i, stride);
1645       if (O->isLittleEndian() != sys::IsLittleEndianHost)
1646         sys::swapByteOrder(pointer_value);
1647       outs() << format("0x%016" PRIx64, pointer_value);
1648       p = pointer_value;
1649     } else {
1650       outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
1651       uint32_t pointer_value;
1652       memcpy(&pointer_value, sect + i, stride);
1653       if (O->isLittleEndian() != sys::IsLittleEndianHost)
1654         sys::swapByteOrder(pointer_value);
1655       outs() << format("0x%08" PRIx32, pointer_value);
1656       p = pointer_value;
1657     }
1658     if (verbose) {
1659       // First look for an external relocation entry for this pointer.
1660       auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
1661         return P.first == i;
1662       });
1663       if (Reloc != Relocs.end()) {
1664         symbol_iterator RelocSym = Reloc->second;
1665         outs() << " " << unwrapOrError(RelocSym->getName(), O->getFileName());
1666       } else {
1667         SymbolName = GuessSymbolName(p, AddrMap);
1668         if (SymbolName)
1669           outs() << " " << SymbolName;
1670       }
1671     }
1672     outs() << "\n";
1673   }
1674 }
1675 
1676 static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
1677                                    uint32_t size, uint64_t addr) {
1678   uint32_t cputype = O->getHeader().cputype;
1679   if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
1680     uint32_t j;
1681     for (uint32_t i = 0; i < size; i += j, addr += j) {
1682       if (O->is64Bit())
1683         outs() << format("%016" PRIx64, addr) << "\t";
1684       else
1685         outs() << format("%08" PRIx64, addr) << "\t";
1686       for (j = 0; j < 16 && i + j < size; j++) {
1687         uint8_t byte_word = *(sect + i + j);
1688         outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1689       }
1690       outs() << "\n";
1691     }
1692   } else {
1693     uint32_t j;
1694     for (uint32_t i = 0; i < size; i += j, addr += j) {
1695       if (O->is64Bit())
1696         outs() << format("%016" PRIx64, addr) << "\t";
1697       else
1698         outs() << format("%08" PRIx64, addr) << "\t";
1699       for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
1700            j += sizeof(int32_t)) {
1701         if (i + j + sizeof(int32_t) <= size) {
1702           uint32_t long_word;
1703           memcpy(&long_word, sect + i + j, sizeof(int32_t));
1704           if (O->isLittleEndian() != sys::IsLittleEndianHost)
1705             sys::swapByteOrder(long_word);
1706           outs() << format("%08" PRIx32, long_word) << " ";
1707         } else {
1708           for (uint32_t k = 0; i + j + k < size; k++) {
1709             uint8_t byte_word = *(sect + i + j + k);
1710             outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1711           }
1712         }
1713       }
1714       outs() << "\n";
1715     }
1716   }
1717 }
1718 
1719 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
1720                              StringRef DisSegName, StringRef DisSectName);
1721 static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
1722                                 uint32_t size, uint32_t addr);
1723 #ifdef HAVE_LIBXAR
1724 static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
1725                                 uint32_t size, bool verbose,
1726                                 bool PrintXarHeader, bool PrintXarFileHeaders,
1727                                 std::string XarMemberName);
1728 #endif // defined(HAVE_LIBXAR)
1729 
1730 static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
1731                                 bool verbose) {
1732   SymbolAddressMap AddrMap;
1733   if (verbose)
1734     CreateSymbolAddressMap(O, &AddrMap);
1735 
1736   for (unsigned i = 0; i < FilterSections.size(); ++i) {
1737     StringRef DumpSection = FilterSections[i];
1738     std::pair<StringRef, StringRef> DumpSegSectName;
1739     DumpSegSectName = DumpSection.split(',');
1740     StringRef DumpSegName, DumpSectName;
1741     if (!DumpSegSectName.second.empty()) {
1742       DumpSegName = DumpSegSectName.first;
1743       DumpSectName = DumpSegSectName.second;
1744     } else {
1745       DumpSegName = "";
1746       DumpSectName = DumpSegSectName.first;
1747     }
1748     for (const SectionRef &Section : O->sections()) {
1749       StringRef SectName;
1750       Expected<StringRef> SecNameOrErr = Section.getName();
1751       if (SecNameOrErr)
1752         SectName = *SecNameOrErr;
1753       else
1754         consumeError(SecNameOrErr.takeError());
1755 
1756       DataRefImpl Ref = Section.getRawDataRefImpl();
1757       StringRef SegName = O->getSectionFinalSegmentName(Ref);
1758       if ((DumpSegName.empty() || SegName == DumpSegName) &&
1759           (SectName == DumpSectName)) {
1760 
1761         uint32_t section_flags;
1762         if (O->is64Bit()) {
1763           const MachO::section_64 Sec = O->getSection64(Ref);
1764           section_flags = Sec.flags;
1765 
1766         } else {
1767           const MachO::section Sec = O->getSection(Ref);
1768           section_flags = Sec.flags;
1769         }
1770         uint32_t section_type = section_flags & MachO::SECTION_TYPE;
1771 
1772         StringRef BytesStr =
1773             unwrapOrError(Section.getContents(), O->getFileName());
1774         const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1775         uint32_t sect_size = BytesStr.size();
1776         uint64_t sect_addr = Section.getAddress();
1777 
1778         outs() << "Contents of (" << SegName << "," << SectName
1779                << ") section\n";
1780 
1781         if (verbose) {
1782           if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1783               (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1784             DisassembleMachO(Filename, O, SegName, SectName);
1785             continue;
1786           }
1787           if (SegName == "__TEXT" && SectName == "__info_plist") {
1788             outs() << sect;
1789             continue;
1790           }
1791           if (SegName == "__OBJC" && SectName == "__protocol") {
1792             DumpProtocolSection(O, sect, sect_size, sect_addr);
1793             continue;
1794           }
1795 #ifdef HAVE_LIBXAR
1796           if (SegName == "__LLVM" && SectName == "__bundle") {
1797             DumpBitcodeSection(O, sect, sect_size, verbose, !NoSymbolicOperands,
1798                                ArchiveHeaders, "");
1799             continue;
1800           }
1801 #endif // defined(HAVE_LIBXAR)
1802           switch (section_type) {
1803           case MachO::S_REGULAR:
1804             DumpRawSectionContents(O, sect, sect_size, sect_addr);
1805             break;
1806           case MachO::S_ZEROFILL:
1807             outs() << "zerofill section and has no contents in the file\n";
1808             break;
1809           case MachO::S_CSTRING_LITERALS:
1810             DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1811             break;
1812           case MachO::S_4BYTE_LITERALS:
1813             DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1814             break;
1815           case MachO::S_8BYTE_LITERALS:
1816             DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1817             break;
1818           case MachO::S_16BYTE_LITERALS:
1819             DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1820             break;
1821           case MachO::S_LITERAL_POINTERS:
1822             DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
1823                                       !NoLeadingAddr);
1824             break;
1825           case MachO::S_MOD_INIT_FUNC_POINTERS:
1826           case MachO::S_MOD_TERM_FUNC_POINTERS:
1827             DumpInitTermPointerSection(O, Section, sect, sect_size, sect_addr,
1828                                        &AddrMap, verbose);
1829             break;
1830           default:
1831             outs() << "Unknown section type ("
1832                    << format("0x%08" PRIx32, section_type) << ")\n";
1833             DumpRawSectionContents(O, sect, sect_size, sect_addr);
1834             break;
1835           }
1836         } else {
1837           if (section_type == MachO::S_ZEROFILL)
1838             outs() << "zerofill section and has no contents in the file\n";
1839           else
1840             DumpRawSectionContents(O, sect, sect_size, sect_addr);
1841         }
1842       }
1843     }
1844   }
1845 }
1846 
1847 static void DumpInfoPlistSectionContents(StringRef Filename,
1848                                          MachOObjectFile *O) {
1849   for (const SectionRef &Section : O->sections()) {
1850     StringRef SectName;
1851     Expected<StringRef> SecNameOrErr = Section.getName();
1852     if (SecNameOrErr)
1853       SectName = *SecNameOrErr;
1854     else
1855       consumeError(SecNameOrErr.takeError());
1856 
1857     DataRefImpl Ref = Section.getRawDataRefImpl();
1858     StringRef SegName = O->getSectionFinalSegmentName(Ref);
1859     if (SegName == "__TEXT" && SectName == "__info_plist") {
1860       if (!NoLeadingHeaders)
1861         outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
1862       StringRef BytesStr =
1863           unwrapOrError(Section.getContents(), O->getFileName());
1864       const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1865       outs() << format("%.*s", BytesStr.size(), sect) << "\n";
1866       return;
1867     }
1868   }
1869 }
1870 
1871 // checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1872 // and if it is and there is a list of architecture flags is specified then
1873 // check to make sure this Mach-O file is one of those architectures or all
1874 // architectures were specified.  If not then an error is generated and this
1875 // routine returns false.  Else it returns true.
1876 static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
1877   auto *MachO = dyn_cast<MachOObjectFile>(O);
1878 
1879   if (!MachO || ArchAll || ArchFlags.empty())
1880     return true;
1881 
1882   MachO::mach_header H;
1883   MachO::mach_header_64 H_64;
1884   Triple T;
1885   const char *McpuDefault, *ArchFlag;
1886   if (MachO->is64Bit()) {
1887     H_64 = MachO->MachOObjectFile::getHeader64();
1888     T = MachOObjectFile::getArchTriple(H_64.cputype, H_64.cpusubtype,
1889                                        &McpuDefault, &ArchFlag);
1890   } else {
1891     H = MachO->MachOObjectFile::getHeader();
1892     T = MachOObjectFile::getArchTriple(H.cputype, H.cpusubtype,
1893                                        &McpuDefault, &ArchFlag);
1894   }
1895   const std::string ArchFlagName(ArchFlag);
1896   if (none_of(ArchFlags, [&](const std::string &Name) {
1897         return Name == ArchFlagName;
1898       })) {
1899     WithColor::error(errs(), "llvm-objdump")
1900         << Filename << ": no architecture specified.\n";
1901     return false;
1902   }
1903   return true;
1904 }
1905 
1906 static void printObjcMetaData(MachOObjectFile *O, bool verbose);
1907 
1908 // ProcessMachO() is passed a single opened Mach-O file, which may be an
1909 // archive member and or in a slice of a universal file.  It prints the
1910 // the file name and header info and then processes it according to the
1911 // command line options.
1912 static void ProcessMachO(StringRef Name, MachOObjectFile *MachOOF,
1913                          StringRef ArchiveMemberName = StringRef(),
1914                          StringRef ArchitectureName = StringRef()) {
1915   // If we are doing some processing here on the Mach-O file print the header
1916   // info.  And don't print it otherwise like in the case of printing the
1917   // UniversalHeaders or ArchiveHeaders.
1918   if (Disassemble || Relocations || PrivateHeaders || ExportsTrie || Rebase ||
1919       Bind || SymbolTable || LazyBind || WeakBind || IndirectSymbols ||
1920       DataInCode || LinkOptHints || DylibsUsed || DylibId || ObjcMetaData ||
1921       (!FilterSections.empty())) {
1922     if (!NoLeadingHeaders) {
1923       outs() << Name;
1924       if (!ArchiveMemberName.empty())
1925         outs() << '(' << ArchiveMemberName << ')';
1926       if (!ArchitectureName.empty())
1927         outs() << " (architecture " << ArchitectureName << ")";
1928       outs() << ":\n";
1929     }
1930   }
1931   // To use the report_error() form with an ArchiveName and FileName set
1932   // these up based on what is passed for Name and ArchiveMemberName.
1933   StringRef ArchiveName;
1934   StringRef FileName;
1935   if (!ArchiveMemberName.empty()) {
1936     ArchiveName = Name;
1937     FileName = ArchiveMemberName;
1938   } else {
1939     ArchiveName = StringRef();
1940     FileName = Name;
1941   }
1942 
1943   // If we need the symbol table to do the operation then check it here to
1944   // produce a good error message as to where the Mach-O file comes from in
1945   // the error message.
1946   if (Disassemble || IndirectSymbols || !FilterSections.empty() || UnwindInfo)
1947     if (Error Err = MachOOF->checkSymbolTable())
1948       reportError(std::move(Err), ArchiveName, FileName, ArchitectureName);
1949 
1950   if (DisassembleAll) {
1951     for (const SectionRef &Section : MachOOF->sections()) {
1952       StringRef SectName;
1953       if (Expected<StringRef> NameOrErr = Section.getName())
1954         SectName = *NameOrErr;
1955       else
1956         consumeError(NameOrErr.takeError());
1957 
1958       if (SectName.equals("__text")) {
1959         DataRefImpl Ref = Section.getRawDataRefImpl();
1960         StringRef SegName = MachOOF->getSectionFinalSegmentName(Ref);
1961         DisassembleMachO(FileName, MachOOF, SegName, SectName);
1962       }
1963     }
1964   }
1965   else if (Disassemble) {
1966     if (MachOOF->getHeader().filetype == MachO::MH_KEXT_BUNDLE &&
1967         MachOOF->getHeader().cputype == MachO::CPU_TYPE_ARM64)
1968       DisassembleMachO(FileName, MachOOF, "__TEXT_EXEC", "__text");
1969     else
1970       DisassembleMachO(FileName, MachOOF, "__TEXT", "__text");
1971   }
1972   if (IndirectSymbols)
1973     PrintIndirectSymbols(MachOOF, !NonVerbose);
1974   if (DataInCode)
1975     PrintDataInCodeTable(MachOOF, !NonVerbose);
1976   if (LinkOptHints)
1977     PrintLinkOptHints(MachOOF);
1978   if (Relocations)
1979     PrintRelocations(MachOOF, !NonVerbose);
1980   if (SectionHeaders)
1981     printSectionHeaders(MachOOF);
1982   if (SectionContents)
1983     printSectionContents(MachOOF);
1984   if (!FilterSections.empty())
1985     DumpSectionContents(FileName, MachOOF, !NonVerbose);
1986   if (InfoPlist)
1987     DumpInfoPlistSectionContents(FileName, MachOOF);
1988   if (DylibsUsed)
1989     PrintDylibs(MachOOF, false);
1990   if (DylibId)
1991     PrintDylibs(MachOOF, true);
1992   if (SymbolTable)
1993     printSymbolTable(MachOOF, ArchiveName, ArchitectureName);
1994   if (UnwindInfo)
1995     printMachOUnwindInfo(MachOOF);
1996   if (PrivateHeaders) {
1997     printMachOFileHeader(MachOOF);
1998     printMachOLoadCommands(MachOOF);
1999   }
2000   if (FirstPrivateHeader)
2001     printMachOFileHeader(MachOOF);
2002   if (ObjcMetaData)
2003     printObjcMetaData(MachOOF, !NonVerbose);
2004   if (ExportsTrie)
2005     printExportsTrie(MachOOF);
2006   if (Rebase)
2007     printRebaseTable(MachOOF);
2008   if (Bind)
2009     printBindTable(MachOOF);
2010   if (LazyBind)
2011     printLazyBindTable(MachOOF);
2012   if (WeakBind)
2013     printWeakBindTable(MachOOF);
2014 
2015   if (DwarfDumpType != DIDT_Null) {
2016     std::unique_ptr<DIContext> DICtx = DWARFContext::create(*MachOOF);
2017     // Dump the complete DWARF structure.
2018     DIDumpOptions DumpOpts;
2019     DumpOpts.DumpType = DwarfDumpType;
2020     DICtx->dump(outs(), DumpOpts);
2021   }
2022 }
2023 
2024 // printUnknownCPUType() helps print_fat_headers for unknown CPU's.
2025 static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
2026   outs() << "    cputype (" << cputype << ")\n";
2027   outs() << "    cpusubtype (" << cpusubtype << ")\n";
2028 }
2029 
2030 // printCPUType() helps print_fat_headers by printing the cputype and
2031 // pusubtype (symbolically for the one's it knows about).
2032 static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
2033   switch (cputype) {
2034   case MachO::CPU_TYPE_I386:
2035     switch (cpusubtype) {
2036     case MachO::CPU_SUBTYPE_I386_ALL:
2037       outs() << "    cputype CPU_TYPE_I386\n";
2038       outs() << "    cpusubtype CPU_SUBTYPE_I386_ALL\n";
2039       break;
2040     default:
2041       printUnknownCPUType(cputype, cpusubtype);
2042       break;
2043     }
2044     break;
2045   case MachO::CPU_TYPE_X86_64:
2046     switch (cpusubtype) {
2047     case MachO::CPU_SUBTYPE_X86_64_ALL:
2048       outs() << "    cputype CPU_TYPE_X86_64\n";
2049       outs() << "    cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
2050       break;
2051     case MachO::CPU_SUBTYPE_X86_64_H:
2052       outs() << "    cputype CPU_TYPE_X86_64\n";
2053       outs() << "    cpusubtype CPU_SUBTYPE_X86_64_H\n";
2054       break;
2055     default:
2056       printUnknownCPUType(cputype, cpusubtype);
2057       break;
2058     }
2059     break;
2060   case MachO::CPU_TYPE_ARM:
2061     switch (cpusubtype) {
2062     case MachO::CPU_SUBTYPE_ARM_ALL:
2063       outs() << "    cputype CPU_TYPE_ARM\n";
2064       outs() << "    cpusubtype CPU_SUBTYPE_ARM_ALL\n";
2065       break;
2066     case MachO::CPU_SUBTYPE_ARM_V4T:
2067       outs() << "    cputype CPU_TYPE_ARM\n";
2068       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V4T\n";
2069       break;
2070     case MachO::CPU_SUBTYPE_ARM_V5TEJ:
2071       outs() << "    cputype CPU_TYPE_ARM\n";
2072       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
2073       break;
2074     case MachO::CPU_SUBTYPE_ARM_XSCALE:
2075       outs() << "    cputype CPU_TYPE_ARM\n";
2076       outs() << "    cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
2077       break;
2078     case MachO::CPU_SUBTYPE_ARM_V6:
2079       outs() << "    cputype CPU_TYPE_ARM\n";
2080       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V6\n";
2081       break;
2082     case MachO::CPU_SUBTYPE_ARM_V6M:
2083       outs() << "    cputype CPU_TYPE_ARM\n";
2084       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V6M\n";
2085       break;
2086     case MachO::CPU_SUBTYPE_ARM_V7:
2087       outs() << "    cputype CPU_TYPE_ARM\n";
2088       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V7\n";
2089       break;
2090     case MachO::CPU_SUBTYPE_ARM_V7EM:
2091       outs() << "    cputype CPU_TYPE_ARM\n";
2092       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
2093       break;
2094     case MachO::CPU_SUBTYPE_ARM_V7K:
2095       outs() << "    cputype CPU_TYPE_ARM\n";
2096       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V7K\n";
2097       break;
2098     case MachO::CPU_SUBTYPE_ARM_V7M:
2099       outs() << "    cputype CPU_TYPE_ARM\n";
2100       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V7M\n";
2101       break;
2102     case MachO::CPU_SUBTYPE_ARM_V7S:
2103       outs() << "    cputype CPU_TYPE_ARM\n";
2104       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V7S\n";
2105       break;
2106     default:
2107       printUnknownCPUType(cputype, cpusubtype);
2108       break;
2109     }
2110     break;
2111   case MachO::CPU_TYPE_ARM64:
2112     switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2113     case MachO::CPU_SUBTYPE_ARM64_ALL:
2114       outs() << "    cputype CPU_TYPE_ARM64\n";
2115       outs() << "    cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
2116       break;
2117     case MachO::CPU_SUBTYPE_ARM64E:
2118       outs() << "    cputype CPU_TYPE_ARM64\n";
2119       outs() << "    cpusubtype CPU_SUBTYPE_ARM64E\n";
2120       break;
2121     default:
2122       printUnknownCPUType(cputype, cpusubtype);
2123       break;
2124     }
2125     break;
2126   case MachO::CPU_TYPE_ARM64_32:
2127     switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2128     case MachO::CPU_SUBTYPE_ARM64_32_V8:
2129       outs() << "    cputype CPU_TYPE_ARM64_32\n";
2130       outs() << "    cpusubtype CPU_SUBTYPE_ARM64_32_V8\n";
2131       break;
2132     default:
2133       printUnknownCPUType(cputype, cpusubtype);
2134       break;
2135     }
2136     break;
2137   default:
2138     printUnknownCPUType(cputype, cpusubtype);
2139     break;
2140   }
2141 }
2142 
2143 static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
2144                                        bool verbose) {
2145   outs() << "Fat headers\n";
2146   if (verbose) {
2147     if (UB->getMagic() == MachO::FAT_MAGIC)
2148       outs() << "fat_magic FAT_MAGIC\n";
2149     else // UB->getMagic() == MachO::FAT_MAGIC_64
2150       outs() << "fat_magic FAT_MAGIC_64\n";
2151   } else
2152     outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
2153 
2154   uint32_t nfat_arch = UB->getNumberOfObjects();
2155   StringRef Buf = UB->getData();
2156   uint64_t size = Buf.size();
2157   uint64_t big_size = sizeof(struct MachO::fat_header) +
2158                       nfat_arch * sizeof(struct MachO::fat_arch);
2159   outs() << "nfat_arch " << UB->getNumberOfObjects();
2160   if (nfat_arch == 0)
2161     outs() << " (malformed, contains zero architecture types)\n";
2162   else if (big_size > size)
2163     outs() << " (malformed, architectures past end of file)\n";
2164   else
2165     outs() << "\n";
2166 
2167   for (uint32_t i = 0; i < nfat_arch; ++i) {
2168     MachOUniversalBinary::ObjectForArch OFA(UB, i);
2169     uint32_t cputype = OFA.getCPUType();
2170     uint32_t cpusubtype = OFA.getCPUSubType();
2171     outs() << "architecture ";
2172     for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
2173       MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
2174       uint32_t other_cputype = other_OFA.getCPUType();
2175       uint32_t other_cpusubtype = other_OFA.getCPUSubType();
2176       if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
2177           (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
2178               (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
2179         outs() << "(illegal duplicate architecture) ";
2180         break;
2181       }
2182     }
2183     if (verbose) {
2184       outs() << OFA.getArchFlagName() << "\n";
2185       printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2186     } else {
2187       outs() << i << "\n";
2188       outs() << "    cputype " << cputype << "\n";
2189       outs() << "    cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
2190              << "\n";
2191     }
2192     if (verbose &&
2193         (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
2194       outs() << "    capabilities CPU_SUBTYPE_LIB64\n";
2195     else
2196       outs() << "    capabilities "
2197              << format("0x%" PRIx32,
2198                        (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
2199     outs() << "    offset " << OFA.getOffset();
2200     if (OFA.getOffset() > size)
2201       outs() << " (past end of file)";
2202     if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
2203       outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
2204     outs() << "\n";
2205     outs() << "    size " << OFA.getSize();
2206     big_size = OFA.getOffset() + OFA.getSize();
2207     if (big_size > size)
2208       outs() << " (past end of file)";
2209     outs() << "\n";
2210     outs() << "    align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
2211            << ")\n";
2212   }
2213 }
2214 
2215 static void printArchiveChild(StringRef Filename, const Archive::Child &C,
2216                               size_t ChildIndex, bool verbose,
2217                               bool print_offset,
2218                               StringRef ArchitectureName = StringRef()) {
2219   if (print_offset)
2220     outs() << C.getChildOffset() << "\t";
2221   sys::fs::perms Mode =
2222       unwrapOrError(C.getAccessMode(), Filename,
2223                     getFileNameForError(C, ChildIndex),
2224                     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(
2243       "%3d/%-3d %5" PRId64 " ",
2244       unwrapOrError(C.getUID(), Filename, getFileNameForError(C, ChildIndex),
2245                     ArchitectureName),
2246       unwrapOrError(C.getGID(), Filename, getFileNameForError(C, ChildIndex),
2247                     ArchitectureName),
2248       unwrapOrError(C.getRawSize(), Filename,
2249                     getFileNameForError(C, ChildIndex), 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(), Filename,
2273                               getFileNameForError(C, ChildIndex),
2274                               ArchitectureName)
2275              << "\n";
2276     } else {
2277       StringRef Name = NameOrErr.get();
2278       outs() << Name << "\n";
2279     }
2280   } else {
2281     outs() << unwrapOrError(C.getRawName(), Filename,
2282                             getFileNameForError(C, ChildIndex),
2283                             ArchitectureName)
2284            << "\n";
2285   }
2286 }
2287 
2288 static void printArchiveHeaders(StringRef Filename, Archive *A, bool verbose,
2289                                 bool print_offset,
2290                                 StringRef ArchitectureName = StringRef()) {
2291   Error Err = Error::success();
2292   size_t I = 0;
2293   for (const auto &C : A->children(Err, false))
2294     printArchiveChild(Filename, C, I++, verbose, print_offset,
2295                       ArchitectureName);
2296 
2297   if (Err)
2298     reportError(std::move(Err), StringRef(), Filename, ArchitectureName);
2299 }
2300 
2301 static bool ValidateArchFlags() {
2302   // Check for -arch all and verifiy the -arch flags are valid.
2303   for (unsigned i = 0; i < ArchFlags.size(); ++i) {
2304     if (ArchFlags[i] == "all") {
2305       ArchAll = true;
2306     } else {
2307       if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
2308         WithColor::error(errs(), "llvm-objdump")
2309             << "unknown architecture named '" + ArchFlags[i] +
2310                    "'for the -arch option\n";
2311         return false;
2312       }
2313     }
2314   }
2315   return true;
2316 }
2317 
2318 // ParseInputMachO() parses the named Mach-O file in Filename and handles the
2319 // -arch flags selecting just those slices as specified by them and also parses
2320 // archive files.  Then for each individual Mach-O file ProcessMachO() is
2321 // called to process the file based on the command line options.
2322 void parseInputMachO(StringRef Filename) {
2323   if (!ValidateArchFlags())
2324     return;
2325 
2326   // Attempt to open the binary.
2327   Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
2328   if (!BinaryOrErr) {
2329     if (Error E = isNotObjectErrorInvalidFileType(BinaryOrErr.takeError()))
2330       reportError(std::move(E), Filename);
2331     else
2332       outs() << Filename << ": is not an object file\n";
2333     return;
2334   }
2335   Binary &Bin = *BinaryOrErr.get().getBinary();
2336 
2337   if (Archive *A = dyn_cast<Archive>(&Bin)) {
2338     outs() << "Archive : " << Filename << "\n";
2339     if (ArchiveHeaders)
2340       printArchiveHeaders(Filename, A, !NonVerbose, ArchiveMemberOffsets);
2341 
2342     Error Err = Error::success();
2343     unsigned I = -1;
2344     for (auto &C : A->children(Err)) {
2345       ++I;
2346       Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2347       if (!ChildOrErr) {
2348         if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2349           reportError(std::move(E), Filename, getFileNameForError(C, I));
2350         continue;
2351       }
2352       if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
2353         if (!checkMachOAndArchFlags(O, Filename))
2354           return;
2355         ProcessMachO(Filename, O, O->getFileName());
2356       }
2357     }
2358     if (Err)
2359       reportError(std::move(Err), Filename);
2360     return;
2361   }
2362   if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
2363     parseInputMachO(UB);
2364     return;
2365   }
2366   if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
2367     if (!checkMachOAndArchFlags(O, Filename))
2368       return;
2369     if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O))
2370       ProcessMachO(Filename, MachOOF);
2371     else
2372       WithColor::error(errs(), "llvm-objdump")
2373           << Filename << "': "
2374           << "object is not a Mach-O file type.\n";
2375     return;
2376   }
2377   llvm_unreachable("Input object can't be invalid at this point");
2378 }
2379 
2380 void parseInputMachO(MachOUniversalBinary *UB) {
2381   if (!ValidateArchFlags())
2382     return;
2383 
2384   auto Filename = UB->getFileName();
2385 
2386   if (UniversalHeaders)
2387     printMachOUniversalHeaders(UB, !NonVerbose);
2388 
2389   // If we have a list of architecture flags specified dump only those.
2390   if (!ArchAll && !ArchFlags.empty()) {
2391     // Look for a slice in the universal binary that matches each ArchFlag.
2392     bool ArchFound;
2393     for (unsigned i = 0; i < ArchFlags.size(); ++i) {
2394       ArchFound = false;
2395       for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2396                                                   E = UB->end_objects();
2397             I != E; ++I) {
2398         if (ArchFlags[i] == I->getArchFlagName()) {
2399           ArchFound = true;
2400           Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
2401               I->getAsObjectFile();
2402           std::string ArchitectureName = "";
2403           if (ArchFlags.size() > 1)
2404             ArchitectureName = I->getArchFlagName();
2405           if (ObjOrErr) {
2406             ObjectFile &O = *ObjOrErr.get();
2407             if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
2408               ProcessMachO(Filename, MachOOF, "", ArchitectureName);
2409           } else if (Error E = isNotObjectErrorInvalidFileType(
2410                          ObjOrErr.takeError())) {
2411             reportError(std::move(E), Filename, StringRef(), ArchitectureName);
2412             continue;
2413           } else if (Expected<std::unique_ptr<Archive>> AOrErr =
2414                          I->getAsArchive()) {
2415             std::unique_ptr<Archive> &A = *AOrErr;
2416             outs() << "Archive : " << Filename;
2417             if (!ArchitectureName.empty())
2418               outs() << " (architecture " << ArchitectureName << ")";
2419             outs() << "\n";
2420             if (ArchiveHeaders)
2421               printArchiveHeaders(Filename, A.get(), !NonVerbose,
2422                                   ArchiveMemberOffsets, ArchitectureName);
2423             Error Err = Error::success();
2424             unsigned I = -1;
2425             for (auto &C : A->children(Err)) {
2426               ++I;
2427               Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2428               if (!ChildOrErr) {
2429                 if (Error E =
2430                         isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2431                   reportError(std::move(E), Filename, getFileNameForError(C, I),
2432                               ArchitectureName);
2433                 continue;
2434               }
2435               if (MachOObjectFile *O =
2436                       dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
2437                 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
2438             }
2439             if (Err)
2440               reportError(std::move(Err), Filename);
2441           } else {
2442             consumeError(AOrErr.takeError());
2443             reportError(Filename,
2444                         "Mach-O universal file for architecture " +
2445                             StringRef(I->getArchFlagName()) +
2446                             " is not a Mach-O file or an archive file");
2447           }
2448         }
2449       }
2450       if (!ArchFound) {
2451         WithColor::error(errs(), "llvm-objdump")
2452             << "file: " + Filename + " does not contain "
2453             << "architecture: " + ArchFlags[i] + "\n";
2454         return;
2455       }
2456     }
2457     return;
2458   }
2459   // No architecture flags were specified so if this contains a slice that
2460   // matches the host architecture dump only that.
2461   if (!ArchAll) {
2462     for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2463                                                 E = UB->end_objects();
2464           I != E; ++I) {
2465       if (MachOObjectFile::getHostArch().getArchName() ==
2466           I->getArchFlagName()) {
2467         Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2468         std::string ArchiveName;
2469         ArchiveName.clear();
2470         if (ObjOrErr) {
2471           ObjectFile &O = *ObjOrErr.get();
2472           if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
2473             ProcessMachO(Filename, MachOOF);
2474         } else if (Error E =
2475                        isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) {
2476           reportError(std::move(E), Filename);
2477         } else if (Expected<std::unique_ptr<Archive>> AOrErr =
2478                        I->getAsArchive()) {
2479           std::unique_ptr<Archive> &A = *AOrErr;
2480           outs() << "Archive : " << Filename << "\n";
2481           if (ArchiveHeaders)
2482             printArchiveHeaders(Filename, A.get(), !NonVerbose,
2483                                 ArchiveMemberOffsets);
2484           Error Err = Error::success();
2485           unsigned I = -1;
2486           for (auto &C : A->children(Err)) {
2487             ++I;
2488             Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2489             if (!ChildOrErr) {
2490               if (Error E =
2491                       isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2492                 reportError(std::move(E), Filename, getFileNameForError(C, I));
2493               continue;
2494             }
2495             if (MachOObjectFile *O =
2496                     dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
2497               ProcessMachO(Filename, O, O->getFileName());
2498           }
2499           if (Err)
2500             reportError(std::move(Err), Filename);
2501         } else {
2502           consumeError(AOrErr.takeError());
2503           reportError(Filename, "Mach-O universal file for architecture " +
2504                                     StringRef(I->getArchFlagName()) +
2505                                     " is not a Mach-O file or an archive file");
2506         }
2507         return;
2508       }
2509     }
2510   }
2511   // Either all architectures have been specified or none have been specified
2512   // and this does not contain the host architecture so dump all the slices.
2513   bool moreThanOneArch = UB->getNumberOfObjects() > 1;
2514   for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2515                                               E = UB->end_objects();
2516         I != E; ++I) {
2517     Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2518     std::string ArchitectureName = "";
2519     if (moreThanOneArch)
2520       ArchitectureName = I->getArchFlagName();
2521     if (ObjOrErr) {
2522       ObjectFile &Obj = *ObjOrErr.get();
2523       if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
2524         ProcessMachO(Filename, MachOOF, "", ArchitectureName);
2525     } else if (Error E =
2526                    isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) {
2527       reportError(std::move(E), StringRef(), Filename, ArchitectureName);
2528     } else if (Expected<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
2529       std::unique_ptr<Archive> &A = *AOrErr;
2530       outs() << "Archive : " << Filename;
2531       if (!ArchitectureName.empty())
2532         outs() << " (architecture " << ArchitectureName << ")";
2533       outs() << "\n";
2534       if (ArchiveHeaders)
2535         printArchiveHeaders(Filename, A.get(), !NonVerbose,
2536                             ArchiveMemberOffsets, ArchitectureName);
2537       Error Err = Error::success();
2538       unsigned I = -1;
2539       for (auto &C : A->children(Err)) {
2540         ++I;
2541         Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2542         if (!ChildOrErr) {
2543           if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2544             reportError(std::move(E), Filename, getFileNameForError(C, I),
2545                         ArchitectureName);
2546           continue;
2547         }
2548         if (MachOObjectFile *O =
2549                 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
2550           if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
2551             ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
2552                           ArchitectureName);
2553         }
2554       }
2555       if (Err)
2556         reportError(std::move(Err), Filename);
2557     } else {
2558       consumeError(AOrErr.takeError());
2559       reportError(Filename, "Mach-O universal file for architecture " +
2560                                 StringRef(I->getArchFlagName()) +
2561                                 " is not a Mach-O file or an archive file");
2562     }
2563   }
2564 }
2565 
2566 // The block of info used by the Symbolizer call backs.
2567 struct DisassembleInfo {
2568   DisassembleInfo(MachOObjectFile *O, SymbolAddressMap *AddrMap,
2569                   std::vector<SectionRef> *Sections, bool verbose)
2570     : verbose(verbose), O(O), AddrMap(AddrMap), Sections(Sections) {}
2571   bool verbose;
2572   MachOObjectFile *O;
2573   SectionRef S;
2574   SymbolAddressMap *AddrMap;
2575   std::vector<SectionRef> *Sections;
2576   const char *class_name = nullptr;
2577   const char *selector_name = nullptr;
2578   std::unique_ptr<char[]> method = nullptr;
2579   char *demangled_name = nullptr;
2580   uint64_t adrp_addr = 0;
2581   uint32_t adrp_inst = 0;
2582   std::unique_ptr<SymbolAddressMap> bindtable;
2583   uint32_t depth = 0;
2584 };
2585 
2586 // SymbolizerGetOpInfo() is the operand information call back function.
2587 // This is called to get the symbolic information for operand(s) of an
2588 // instruction when it is being done.  This routine does this from
2589 // the relocation information, symbol table, etc. That block of information
2590 // is a pointer to the struct DisassembleInfo that was passed when the
2591 // disassembler context was created and passed to back to here when
2592 // called back by the disassembler for instruction operands that could have
2593 // relocation information. The address of the instruction containing operand is
2594 // at the Pc parameter.  The immediate value the operand has is passed in
2595 // op_info->Value and is at Offset past the start of the instruction and has a
2596 // byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
2597 // LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
2598 // names and addends of the symbolic expression to add for the operand.  The
2599 // value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
2600 // information is returned then this function returns 1 else it returns 0.
2601 static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
2602                                uint64_t Size, int TagType, void *TagBuf) {
2603   struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
2604   struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
2605   uint64_t value = op_info->Value;
2606 
2607   // Make sure all fields returned are zero if we don't set them.
2608   memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
2609   op_info->Value = value;
2610 
2611   // If the TagType is not the value 1 which it code knows about or if no
2612   // verbose symbolic information is wanted then just return 0, indicating no
2613   // information is being returned.
2614   if (TagType != 1 || !info->verbose)
2615     return 0;
2616 
2617   unsigned int Arch = info->O->getArch();
2618   if (Arch == Triple::x86) {
2619     if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
2620       return 0;
2621     if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2622       // TODO:
2623       // Search the external relocation entries of a fully linked image
2624       // (if any) for an entry that matches this segment offset.
2625       // uint32_t seg_offset = (Pc + Offset);
2626       return 0;
2627     }
2628     // In MH_OBJECT filetypes search the section's relocation entries (if any)
2629     // for an entry for this section offset.
2630     uint32_t sect_addr = info->S.getAddress();
2631     uint32_t sect_offset = (Pc + Offset) - sect_addr;
2632     bool reloc_found = false;
2633     DataRefImpl Rel;
2634     MachO::any_relocation_info RE;
2635     bool isExtern = false;
2636     SymbolRef Symbol;
2637     bool r_scattered = false;
2638     uint32_t r_value, pair_r_value, r_type;
2639     for (const RelocationRef &Reloc : info->S.relocations()) {
2640       uint64_t RelocOffset = Reloc.getOffset();
2641       if (RelocOffset == sect_offset) {
2642         Rel = Reloc.getRawDataRefImpl();
2643         RE = info->O->getRelocation(Rel);
2644         r_type = info->O->getAnyRelocationType(RE);
2645         r_scattered = info->O->isRelocationScattered(RE);
2646         if (r_scattered) {
2647           r_value = info->O->getScatteredRelocationValue(RE);
2648           if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2649               r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
2650             DataRefImpl RelNext = Rel;
2651             info->O->moveRelocationNext(RelNext);
2652             MachO::any_relocation_info RENext;
2653             RENext = info->O->getRelocation(RelNext);
2654             if (info->O->isRelocationScattered(RENext))
2655               pair_r_value = info->O->getScatteredRelocationValue(RENext);
2656             else
2657               return 0;
2658           }
2659         } else {
2660           isExtern = info->O->getPlainRelocationExternal(RE);
2661           if (isExtern) {
2662             symbol_iterator RelocSym = Reloc.getSymbol();
2663             Symbol = *RelocSym;
2664           }
2665         }
2666         reloc_found = true;
2667         break;
2668       }
2669     }
2670     if (reloc_found && isExtern) {
2671       op_info->AddSymbol.Present = 1;
2672       op_info->AddSymbol.Name =
2673           unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
2674       // For i386 extern relocation entries the value in the instruction is
2675       // the offset from the symbol, and value is already set in op_info->Value.
2676       return 1;
2677     }
2678     if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2679                         r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
2680       const char *add = GuessSymbolName(r_value, info->AddrMap);
2681       const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
2682       uint32_t offset = value - (r_value - pair_r_value);
2683       op_info->AddSymbol.Present = 1;
2684       if (add != nullptr)
2685         op_info->AddSymbol.Name = add;
2686       else
2687         op_info->AddSymbol.Value = r_value;
2688       op_info->SubtractSymbol.Present = 1;
2689       if (sub != nullptr)
2690         op_info->SubtractSymbol.Name = sub;
2691       else
2692         op_info->SubtractSymbol.Value = pair_r_value;
2693       op_info->Value = offset;
2694       return 1;
2695     }
2696     return 0;
2697   }
2698   if (Arch == Triple::x86_64) {
2699     if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
2700       return 0;
2701     // For non MH_OBJECT types, like MH_KEXT_BUNDLE, Search the external
2702     // relocation entries of a linked image (if any) for an entry that matches
2703     // this segment offset.
2704     if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2705       uint64_t seg_offset = Pc + Offset;
2706       bool reloc_found = false;
2707       DataRefImpl Rel;
2708       MachO::any_relocation_info RE;
2709       bool isExtern = false;
2710       SymbolRef Symbol;
2711       for (const RelocationRef &Reloc : info->O->external_relocations()) {
2712         uint64_t RelocOffset = Reloc.getOffset();
2713         if (RelocOffset == seg_offset) {
2714           Rel = Reloc.getRawDataRefImpl();
2715           RE = info->O->getRelocation(Rel);
2716           // external relocation entries should always be external.
2717           isExtern = info->O->getPlainRelocationExternal(RE);
2718           if (isExtern) {
2719             symbol_iterator RelocSym = Reloc.getSymbol();
2720             Symbol = *RelocSym;
2721           }
2722           reloc_found = true;
2723           break;
2724         }
2725       }
2726       if (reloc_found && isExtern) {
2727         // The Value passed in will be adjusted by the Pc if the instruction
2728         // adds the Pc.  But for x86_64 external relocation entries the Value
2729         // is the offset from the external symbol.
2730         if (info->O->getAnyRelocationPCRel(RE))
2731           op_info->Value -= Pc + Offset + Size;
2732         const char *name =
2733             unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
2734         op_info->AddSymbol.Present = 1;
2735         op_info->AddSymbol.Name = name;
2736         return 1;
2737       }
2738       return 0;
2739     }
2740     // In MH_OBJECT filetypes search the section's relocation entries (if any)
2741     // for an entry for this section offset.
2742     uint64_t sect_addr = info->S.getAddress();
2743     uint64_t sect_offset = (Pc + Offset) - sect_addr;
2744     bool reloc_found = false;
2745     DataRefImpl Rel;
2746     MachO::any_relocation_info RE;
2747     bool isExtern = false;
2748     SymbolRef Symbol;
2749     for (const RelocationRef &Reloc : info->S.relocations()) {
2750       uint64_t RelocOffset = Reloc.getOffset();
2751       if (RelocOffset == sect_offset) {
2752         Rel = Reloc.getRawDataRefImpl();
2753         RE = info->O->getRelocation(Rel);
2754         // NOTE: Scattered relocations don't exist on x86_64.
2755         isExtern = info->O->getPlainRelocationExternal(RE);
2756         if (isExtern) {
2757           symbol_iterator RelocSym = Reloc.getSymbol();
2758           Symbol = *RelocSym;
2759         }
2760         reloc_found = true;
2761         break;
2762       }
2763     }
2764     if (reloc_found && isExtern) {
2765       // The Value passed in will be adjusted by the Pc if the instruction
2766       // adds the Pc.  But for x86_64 external relocation entries the Value
2767       // is the offset from the external symbol.
2768       if (info->O->getAnyRelocationPCRel(RE))
2769         op_info->Value -= Pc + Offset + Size;
2770       const char *name =
2771           unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
2772       unsigned Type = info->O->getAnyRelocationType(RE);
2773       if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
2774         DataRefImpl RelNext = Rel;
2775         info->O->moveRelocationNext(RelNext);
2776         MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2777         unsigned TypeNext = info->O->getAnyRelocationType(RENext);
2778         bool isExternNext = info->O->getPlainRelocationExternal(RENext);
2779         unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
2780         if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
2781           op_info->SubtractSymbol.Present = 1;
2782           op_info->SubtractSymbol.Name = name;
2783           symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
2784           Symbol = *RelocSymNext;
2785           name = unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
2786         }
2787       }
2788       // TODO: add the VariantKinds to op_info->VariantKind for relocation types
2789       // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
2790       op_info->AddSymbol.Present = 1;
2791       op_info->AddSymbol.Name = name;
2792       return 1;
2793     }
2794     return 0;
2795   }
2796   if (Arch == Triple::arm) {
2797     if (Offset != 0 || (Size != 4 && Size != 2))
2798       return 0;
2799     if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2800       // TODO:
2801       // Search the external relocation entries of a fully linked image
2802       // (if any) for an entry that matches this segment offset.
2803       // uint32_t seg_offset = (Pc + Offset);
2804       return 0;
2805     }
2806     // In MH_OBJECT filetypes search the section's relocation entries (if any)
2807     // for an entry for this section offset.
2808     uint32_t sect_addr = info->S.getAddress();
2809     uint32_t sect_offset = (Pc + Offset) - sect_addr;
2810     DataRefImpl Rel;
2811     MachO::any_relocation_info RE;
2812     bool isExtern = false;
2813     SymbolRef Symbol;
2814     bool r_scattered = false;
2815     uint32_t r_value, pair_r_value, r_type, r_length, other_half;
2816     auto Reloc =
2817         find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2818           uint64_t RelocOffset = Reloc.getOffset();
2819           return RelocOffset == sect_offset;
2820         });
2821 
2822     if (Reloc == info->S.relocations().end())
2823       return 0;
2824 
2825     Rel = Reloc->getRawDataRefImpl();
2826     RE = info->O->getRelocation(Rel);
2827     r_length = info->O->getAnyRelocationLength(RE);
2828     r_scattered = info->O->isRelocationScattered(RE);
2829     if (r_scattered) {
2830       r_value = info->O->getScatteredRelocationValue(RE);
2831       r_type = info->O->getScatteredRelocationType(RE);
2832     } else {
2833       r_type = info->O->getAnyRelocationType(RE);
2834       isExtern = info->O->getPlainRelocationExternal(RE);
2835       if (isExtern) {
2836         symbol_iterator RelocSym = Reloc->getSymbol();
2837         Symbol = *RelocSym;
2838       }
2839     }
2840     if (r_type == MachO::ARM_RELOC_HALF ||
2841         r_type == MachO::ARM_RELOC_SECTDIFF ||
2842         r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
2843         r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2844       DataRefImpl RelNext = Rel;
2845       info->O->moveRelocationNext(RelNext);
2846       MachO::any_relocation_info RENext;
2847       RENext = info->O->getRelocation(RelNext);
2848       other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
2849       if (info->O->isRelocationScattered(RENext))
2850         pair_r_value = info->O->getScatteredRelocationValue(RENext);
2851     }
2852 
2853     if (isExtern) {
2854       const char *name =
2855           unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
2856       op_info->AddSymbol.Present = 1;
2857       op_info->AddSymbol.Name = name;
2858       switch (r_type) {
2859       case MachO::ARM_RELOC_HALF:
2860         if ((r_length & 0x1) == 1) {
2861           op_info->Value = value << 16 | other_half;
2862           op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2863         } else {
2864           op_info->Value = other_half << 16 | value;
2865           op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
2866         }
2867         break;
2868       default:
2869         break;
2870       }
2871       return 1;
2872     }
2873     // If we have a branch that is not an external relocation entry then
2874     // return 0 so the code in tryAddingSymbolicOperand() can use the
2875     // SymbolLookUp call back with the branch target address to look up the
2876     // symbol and possibility add an annotation for a symbol stub.
2877     if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
2878                           r_type == MachO::ARM_THUMB_RELOC_BR22))
2879       return 0;
2880 
2881     uint32_t offset = 0;
2882     if (r_type == MachO::ARM_RELOC_HALF ||
2883         r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2884       if ((r_length & 0x1) == 1)
2885         value = value << 16 | other_half;
2886       else
2887         value = other_half << 16 | value;
2888     }
2889     if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
2890                         r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
2891       offset = value - r_value;
2892       value = r_value;
2893     }
2894 
2895     if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2896       if ((r_length & 0x1) == 1)
2897         op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2898       else
2899         op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
2900       const char *add = GuessSymbolName(r_value, info->AddrMap);
2901       const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
2902       int32_t offset = value - (r_value - pair_r_value);
2903       op_info->AddSymbol.Present = 1;
2904       if (add != nullptr)
2905         op_info->AddSymbol.Name = add;
2906       else
2907         op_info->AddSymbol.Value = r_value;
2908       op_info->SubtractSymbol.Present = 1;
2909       if (sub != nullptr)
2910         op_info->SubtractSymbol.Name = sub;
2911       else
2912         op_info->SubtractSymbol.Value = pair_r_value;
2913       op_info->Value = offset;
2914       return 1;
2915     }
2916 
2917     op_info->AddSymbol.Present = 1;
2918     op_info->Value = offset;
2919     if (r_type == MachO::ARM_RELOC_HALF) {
2920       if ((r_length & 0x1) == 1)
2921         op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2922       else
2923         op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
2924     }
2925     const char *add = GuessSymbolName(value, info->AddrMap);
2926     if (add != nullptr) {
2927       op_info->AddSymbol.Name = add;
2928       return 1;
2929     }
2930     op_info->AddSymbol.Value = value;
2931     return 1;
2932   }
2933   if (Arch == Triple::aarch64) {
2934     if (Offset != 0 || Size != 4)
2935       return 0;
2936     if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2937       // TODO:
2938       // Search the external relocation entries of a fully linked image
2939       // (if any) for an entry that matches this segment offset.
2940       // uint64_t seg_offset = (Pc + Offset);
2941       return 0;
2942     }
2943     // In MH_OBJECT filetypes search the section's relocation entries (if any)
2944     // for an entry for this section offset.
2945     uint64_t sect_addr = info->S.getAddress();
2946     uint64_t sect_offset = (Pc + Offset) - sect_addr;
2947     auto Reloc =
2948         find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2949           uint64_t RelocOffset = Reloc.getOffset();
2950           return RelocOffset == sect_offset;
2951         });
2952 
2953     if (Reloc == info->S.relocations().end())
2954       return 0;
2955 
2956     DataRefImpl Rel = Reloc->getRawDataRefImpl();
2957     MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2958     uint32_t r_type = info->O->getAnyRelocationType(RE);
2959     if (r_type == MachO::ARM64_RELOC_ADDEND) {
2960       DataRefImpl RelNext = Rel;
2961       info->O->moveRelocationNext(RelNext);
2962       MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2963       if (value == 0) {
2964         value = info->O->getPlainRelocationSymbolNum(RENext);
2965         op_info->Value = value;
2966       }
2967     }
2968     // NOTE: Scattered relocations don't exist on arm64.
2969     if (!info->O->getPlainRelocationExternal(RE))
2970       return 0;
2971     const char *name =
2972         unwrapOrError(Reloc->getSymbol()->getName(), info->O->getFileName())
2973             .data();
2974     op_info->AddSymbol.Present = 1;
2975     op_info->AddSymbol.Name = name;
2976 
2977     switch (r_type) {
2978     case MachO::ARM64_RELOC_PAGE21:
2979       /* @page */
2980       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2981       break;
2982     case MachO::ARM64_RELOC_PAGEOFF12:
2983       /* @pageoff */
2984       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2985       break;
2986     case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2987       /* @gotpage */
2988       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2989       break;
2990     case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2991       /* @gotpageoff */
2992       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2993       break;
2994     case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2995       /* @tvlppage is not implemented in llvm-mc */
2996       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2997       break;
2998     case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2999       /* @tvlppageoff is not implemented in llvm-mc */
3000       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
3001       break;
3002     default:
3003     case MachO::ARM64_RELOC_BRANCH26:
3004       op_info->VariantKind = LLVMDisassembler_VariantKind_None;
3005       break;
3006     }
3007     return 1;
3008   }
3009   return 0;
3010 }
3011 
3012 // GuessCstringPointer is passed the address of what might be a pointer to a
3013 // literal string in a cstring section.  If that address is in a cstring section
3014 // it returns a pointer to that string.  Else it returns nullptr.
3015 static const char *GuessCstringPointer(uint64_t ReferenceValue,
3016                                        struct DisassembleInfo *info) {
3017   for (const auto &Load : info->O->load_commands()) {
3018     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
3019       MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
3020       for (unsigned J = 0; J < Seg.nsects; ++J) {
3021         MachO::section_64 Sec = info->O->getSection64(Load, J);
3022         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3023         if (section_type == MachO::S_CSTRING_LITERALS &&
3024             ReferenceValue >= Sec.addr &&
3025             ReferenceValue < Sec.addr + Sec.size) {
3026           uint64_t sect_offset = ReferenceValue - Sec.addr;
3027           uint64_t object_offset = Sec.offset + sect_offset;
3028           StringRef MachOContents = info->O->getData();
3029           uint64_t object_size = MachOContents.size();
3030           const char *object_addr = (const char *)MachOContents.data();
3031           if (object_offset < object_size) {
3032             const char *name = object_addr + object_offset;
3033             return name;
3034           } else {
3035             return nullptr;
3036           }
3037         }
3038       }
3039     } else if (Load.C.cmd == MachO::LC_SEGMENT) {
3040       MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
3041       for (unsigned J = 0; J < Seg.nsects; ++J) {
3042         MachO::section Sec = info->O->getSection(Load, J);
3043         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3044         if (section_type == MachO::S_CSTRING_LITERALS &&
3045             ReferenceValue >= Sec.addr &&
3046             ReferenceValue < Sec.addr + Sec.size) {
3047           uint64_t sect_offset = ReferenceValue - Sec.addr;
3048           uint64_t object_offset = Sec.offset + sect_offset;
3049           StringRef MachOContents = info->O->getData();
3050           uint64_t object_size = MachOContents.size();
3051           const char *object_addr = (const char *)MachOContents.data();
3052           if (object_offset < object_size) {
3053             const char *name = object_addr + object_offset;
3054             return name;
3055           } else {
3056             return nullptr;
3057           }
3058         }
3059       }
3060     }
3061   }
3062   return nullptr;
3063 }
3064 
3065 // GuessIndirectSymbol returns the name of the indirect symbol for the
3066 // ReferenceValue passed in or nullptr.  This is used when ReferenceValue maybe
3067 // an address of a symbol stub or a lazy or non-lazy pointer to associate the
3068 // symbol name being referenced by the stub or pointer.
3069 static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
3070                                        struct DisassembleInfo *info) {
3071   MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
3072   MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
3073   for (const auto &Load : info->O->load_commands()) {
3074     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
3075       MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
3076       for (unsigned J = 0; J < Seg.nsects; ++J) {
3077         MachO::section_64 Sec = info->O->getSection64(Load, J);
3078         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3079         if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
3080              section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
3081              section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
3082              section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
3083              section_type == MachO::S_SYMBOL_STUBS) &&
3084             ReferenceValue >= Sec.addr &&
3085             ReferenceValue < Sec.addr + Sec.size) {
3086           uint32_t stride;
3087           if (section_type == MachO::S_SYMBOL_STUBS)
3088             stride = Sec.reserved2;
3089           else
3090             stride = 8;
3091           if (stride == 0)
3092             return nullptr;
3093           uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
3094           if (index < Dysymtab.nindirectsyms) {
3095             uint32_t indirect_symbol =
3096                 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
3097             if (indirect_symbol < Symtab.nsyms) {
3098               symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
3099               return unwrapOrError(Sym->getName(), info->O->getFileName())
3100                   .data();
3101             }
3102           }
3103         }
3104       }
3105     } else if (Load.C.cmd == MachO::LC_SEGMENT) {
3106       MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
3107       for (unsigned J = 0; J < Seg.nsects; ++J) {
3108         MachO::section Sec = info->O->getSection(Load, J);
3109         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3110         if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
3111              section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
3112              section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
3113              section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
3114              section_type == MachO::S_SYMBOL_STUBS) &&
3115             ReferenceValue >= Sec.addr &&
3116             ReferenceValue < Sec.addr + Sec.size) {
3117           uint32_t stride;
3118           if (section_type == MachO::S_SYMBOL_STUBS)
3119             stride = Sec.reserved2;
3120           else
3121             stride = 4;
3122           if (stride == 0)
3123             return nullptr;
3124           uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
3125           if (index < Dysymtab.nindirectsyms) {
3126             uint32_t indirect_symbol =
3127                 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
3128             if (indirect_symbol < Symtab.nsyms) {
3129               symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
3130               return unwrapOrError(Sym->getName(), info->O->getFileName())
3131                   .data();
3132             }
3133           }
3134         }
3135       }
3136     }
3137   }
3138   return nullptr;
3139 }
3140 
3141 // method_reference() is called passing it the ReferenceName that might be
3142 // a reference it to an Objective-C method call.  If so then it allocates and
3143 // assembles a method call string with the values last seen and saved in
3144 // the DisassembleInfo's class_name and selector_name fields.  This is saved
3145 // into the method field of the info and any previous string is free'ed.
3146 // Then the class_name field in the info is set to nullptr.  The method call
3147 // string is set into ReferenceName and ReferenceType is set to
3148 // LLVMDisassembler_ReferenceType_Out_Objc_Message.  If this not a method call
3149 // then both ReferenceType and ReferenceName are left unchanged.
3150 static void method_reference(struct DisassembleInfo *info,
3151                              uint64_t *ReferenceType,
3152                              const char **ReferenceName) {
3153   unsigned int Arch = info->O->getArch();
3154   if (*ReferenceName != nullptr) {
3155     if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
3156       if (info->selector_name != nullptr) {
3157         if (info->class_name != nullptr) {
3158           info->method = std::make_unique<char[]>(
3159               5 + strlen(info->class_name) + strlen(info->selector_name));
3160           char *method = info->method.get();
3161           if (method != nullptr) {
3162             strcpy(method, "+[");
3163             strcat(method, info->class_name);
3164             strcat(method, " ");
3165             strcat(method, info->selector_name);
3166             strcat(method, "]");
3167             *ReferenceName = method;
3168             *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3169           }
3170         } else {
3171           info->method =
3172               std::make_unique<char[]>(9 + strlen(info->selector_name));
3173           char *method = info->method.get();
3174           if (method != nullptr) {
3175             if (Arch == Triple::x86_64)
3176               strcpy(method, "-[%rdi ");
3177             else if (Arch == Triple::aarch64)
3178               strcpy(method, "-[x0 ");
3179             else
3180               strcpy(method, "-[r? ");
3181             strcat(method, info->selector_name);
3182             strcat(method, "]");
3183             *ReferenceName = method;
3184             *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3185           }
3186         }
3187         info->class_name = nullptr;
3188       }
3189     } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
3190       if (info->selector_name != nullptr) {
3191         info->method =
3192             std::make_unique<char[]>(17 + strlen(info->selector_name));
3193         char *method = info->method.get();
3194         if (method != nullptr) {
3195           if (Arch == Triple::x86_64)
3196             strcpy(method, "-[[%rdi super] ");
3197           else if (Arch == Triple::aarch64)
3198             strcpy(method, "-[[x0 super] ");
3199           else
3200             strcpy(method, "-[[r? super] ");
3201           strcat(method, info->selector_name);
3202           strcat(method, "]");
3203           *ReferenceName = method;
3204           *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3205         }
3206         info->class_name = nullptr;
3207       }
3208     }
3209   }
3210 }
3211 
3212 // GuessPointerPointer() is passed the address of what might be a pointer to
3213 // a reference to an Objective-C class, selector, message ref or cfstring.
3214 // If so the value of the pointer is returned and one of the booleans are set
3215 // to true.  If not zero is returned and all the booleans are set to false.
3216 static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
3217                                     struct DisassembleInfo *info,
3218                                     bool &classref, bool &selref, bool &msgref,
3219                                     bool &cfstring) {
3220   classref = false;
3221   selref = false;
3222   msgref = false;
3223   cfstring = false;
3224   for (const auto &Load : info->O->load_commands()) {
3225     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
3226       MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
3227       for (unsigned J = 0; J < Seg.nsects; ++J) {
3228         MachO::section_64 Sec = info->O->getSection64(Load, J);
3229         if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
3230              strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
3231              strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
3232              strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
3233              strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
3234             ReferenceValue >= Sec.addr &&
3235             ReferenceValue < Sec.addr + Sec.size) {
3236           uint64_t sect_offset = ReferenceValue - Sec.addr;
3237           uint64_t object_offset = Sec.offset + sect_offset;
3238           StringRef MachOContents = info->O->getData();
3239           uint64_t object_size = MachOContents.size();
3240           const char *object_addr = (const char *)MachOContents.data();
3241           if (object_offset < object_size) {
3242             uint64_t pointer_value;
3243             memcpy(&pointer_value, object_addr + object_offset,
3244                    sizeof(uint64_t));
3245             if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3246               sys::swapByteOrder(pointer_value);
3247             if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
3248               selref = true;
3249             else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
3250                      strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
3251               classref = true;
3252             else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
3253                      ReferenceValue + 8 < Sec.addr + Sec.size) {
3254               msgref = true;
3255               memcpy(&pointer_value, object_addr + object_offset + 8,
3256                      sizeof(uint64_t));
3257               if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3258                 sys::swapByteOrder(pointer_value);
3259             } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
3260               cfstring = true;
3261             return pointer_value;
3262           } else {
3263             return 0;
3264           }
3265         }
3266       }
3267     }
3268     // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
3269   }
3270   return 0;
3271 }
3272 
3273 // get_pointer_64 returns a pointer to the bytes in the object file at the
3274 // Address from a section in the Mach-O file.  And indirectly returns the
3275 // offset into the section, number of bytes left in the section past the offset
3276 // and which section is was being referenced.  If the Address is not in a
3277 // section nullptr is returned.
3278 static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
3279                                   uint32_t &left, SectionRef &S,
3280                                   DisassembleInfo *info,
3281                                   bool objc_only = false) {
3282   offset = 0;
3283   left = 0;
3284   S = SectionRef();
3285   for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
3286     uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
3287     uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
3288     if (SectSize == 0)
3289       continue;
3290     if (objc_only) {
3291       StringRef SectName;
3292       Expected<StringRef> SecNameOrErr =
3293           ((*(info->Sections))[SectIdx]).getName();
3294       if (SecNameOrErr)
3295         SectName = *SecNameOrErr;
3296       else
3297         consumeError(SecNameOrErr.takeError());
3298 
3299       DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
3300       StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
3301       if (SegName != "__OBJC" && SectName != "__cstring")
3302         continue;
3303     }
3304     if (Address >= SectAddress && Address < SectAddress + SectSize) {
3305       S = (*(info->Sections))[SectIdx];
3306       offset = Address - SectAddress;
3307       left = SectSize - offset;
3308       StringRef SectContents = unwrapOrError(
3309           ((*(info->Sections))[SectIdx]).getContents(), info->O->getFileName());
3310       return SectContents.data() + offset;
3311     }
3312   }
3313   return nullptr;
3314 }
3315 
3316 static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
3317                                   uint32_t &left, SectionRef &S,
3318                                   DisassembleInfo *info,
3319                                   bool objc_only = false) {
3320   return get_pointer_64(Address, offset, left, S, info, objc_only);
3321 }
3322 
3323 // get_symbol_64() returns the name of a symbol (or nullptr) and the address of
3324 // the symbol indirectly through n_value. Based on the relocation information
3325 // for the specified section offset in the specified section reference.
3326 // If no relocation information is found and a non-zero ReferenceValue for the
3327 // symbol is passed, look up that address in the info's AddrMap.
3328 static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
3329                                  DisassembleInfo *info, uint64_t &n_value,
3330                                  uint64_t ReferenceValue = 0) {
3331   n_value = 0;
3332   if (!info->verbose)
3333     return nullptr;
3334 
3335   // See if there is an external relocation entry at the sect_offset.
3336   bool reloc_found = false;
3337   DataRefImpl Rel;
3338   MachO::any_relocation_info RE;
3339   bool isExtern = false;
3340   SymbolRef Symbol;
3341   for (const RelocationRef &Reloc : S.relocations()) {
3342     uint64_t RelocOffset = Reloc.getOffset();
3343     if (RelocOffset == sect_offset) {
3344       Rel = Reloc.getRawDataRefImpl();
3345       RE = info->O->getRelocation(Rel);
3346       if (info->O->isRelocationScattered(RE))
3347         continue;
3348       isExtern = info->O->getPlainRelocationExternal(RE);
3349       if (isExtern) {
3350         symbol_iterator RelocSym = Reloc.getSymbol();
3351         Symbol = *RelocSym;
3352       }
3353       reloc_found = true;
3354       break;
3355     }
3356   }
3357   // If there is an external relocation entry for a symbol in this section
3358   // at this section_offset then use that symbol's value for the n_value
3359   // and return its name.
3360   const char *SymbolName = nullptr;
3361   if (reloc_found && isExtern) {
3362     n_value = Symbol.getValue();
3363     StringRef Name = unwrapOrError(Symbol.getName(), info->O->getFileName());
3364     if (!Name.empty()) {
3365       SymbolName = Name.data();
3366       return SymbolName;
3367     }
3368   }
3369 
3370   // TODO: For fully linked images, look through the external relocation
3371   // entries off the dynamic symtab command. For these the r_offset is from the
3372   // start of the first writeable segment in the Mach-O file.  So the offset
3373   // to this section from that segment is passed to this routine by the caller,
3374   // as the database_offset. Which is the difference of the section's starting
3375   // address and the first writable segment.
3376   //
3377   // NOTE: need add passing the database_offset to this routine.
3378 
3379   // We did not find an external relocation entry so look up the ReferenceValue
3380   // as an address of a symbol and if found return that symbol's name.
3381   SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
3382 
3383   return SymbolName;
3384 }
3385 
3386 static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
3387                                  DisassembleInfo *info,
3388                                  uint32_t ReferenceValue) {
3389   uint64_t n_value64;
3390   return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
3391 }
3392 
3393 // These are structs in the Objective-C meta data and read to produce the
3394 // comments for disassembly.  While these are part of the ABI they are no
3395 // public defintions.  So the are here not in include/llvm/BinaryFormat/MachO.h
3396 // .
3397 
3398 // The cfstring object in a 64-bit Mach-O file.
3399 struct cfstring64_t {
3400   uint64_t isa;        // class64_t * (64-bit pointer)
3401   uint64_t flags;      // flag bits
3402   uint64_t characters; // char * (64-bit pointer)
3403   uint64_t length;     // number of non-NULL characters in above
3404 };
3405 
3406 // The class object in a 64-bit Mach-O file.
3407 struct class64_t {
3408   uint64_t isa;        // class64_t * (64-bit pointer)
3409   uint64_t superclass; // class64_t * (64-bit pointer)
3410   uint64_t cache;      // Cache (64-bit pointer)
3411   uint64_t vtable;     // IMP * (64-bit pointer)
3412   uint64_t data;       // class_ro64_t * (64-bit pointer)
3413 };
3414 
3415 struct class32_t {
3416   uint32_t isa;        /* class32_t * (32-bit pointer) */
3417   uint32_t superclass; /* class32_t * (32-bit pointer) */
3418   uint32_t cache;      /* Cache (32-bit pointer) */
3419   uint32_t vtable;     /* IMP * (32-bit pointer) */
3420   uint32_t data;       /* class_ro32_t * (32-bit pointer) */
3421 };
3422 
3423 struct class_ro64_t {
3424   uint32_t flags;
3425   uint32_t instanceStart;
3426   uint32_t instanceSize;
3427   uint32_t reserved;
3428   uint64_t ivarLayout;     // const uint8_t * (64-bit pointer)
3429   uint64_t name;           // const char * (64-bit pointer)
3430   uint64_t baseMethods;    // const method_list_t * (64-bit pointer)
3431   uint64_t baseProtocols;  // const protocol_list_t * (64-bit pointer)
3432   uint64_t ivars;          // const ivar_list_t * (64-bit pointer)
3433   uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
3434   uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
3435 };
3436 
3437 struct class_ro32_t {
3438   uint32_t flags;
3439   uint32_t instanceStart;
3440   uint32_t instanceSize;
3441   uint32_t ivarLayout;     /* const uint8_t * (32-bit pointer) */
3442   uint32_t name;           /* const char * (32-bit pointer) */
3443   uint32_t baseMethods;    /* const method_list_t * (32-bit pointer) */
3444   uint32_t baseProtocols;  /* const protocol_list_t * (32-bit pointer) */
3445   uint32_t ivars;          /* const ivar_list_t * (32-bit pointer) */
3446   uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
3447   uint32_t baseProperties; /* const struct objc_property_list *
3448                                                    (32-bit pointer) */
3449 };
3450 
3451 /* Values for class_ro{64,32}_t->flags */
3452 #define RO_META (1 << 0)
3453 #define RO_ROOT (1 << 1)
3454 #define RO_HAS_CXX_STRUCTORS (1 << 2)
3455 
3456 struct method_list64_t {
3457   uint32_t entsize;
3458   uint32_t count;
3459   /* struct method64_t first;  These structures follow inline */
3460 };
3461 
3462 struct method_list32_t {
3463   uint32_t entsize;
3464   uint32_t count;
3465   /* struct method32_t first;  These structures follow inline */
3466 };
3467 
3468 struct method64_t {
3469   uint64_t name;  /* SEL (64-bit pointer) */
3470   uint64_t types; /* const char * (64-bit pointer) */
3471   uint64_t imp;   /* IMP (64-bit pointer) */
3472 };
3473 
3474 struct method32_t {
3475   uint32_t name;  /* SEL (32-bit pointer) */
3476   uint32_t types; /* const char * (32-bit pointer) */
3477   uint32_t imp;   /* IMP (32-bit pointer) */
3478 };
3479 
3480 struct protocol_list64_t {
3481   uint64_t count; /* uintptr_t (a 64-bit value) */
3482   /* struct protocol64_t * list[0];  These pointers follow inline */
3483 };
3484 
3485 struct protocol_list32_t {
3486   uint32_t count; /* uintptr_t (a 32-bit value) */
3487   /* struct protocol32_t * list[0];  These pointers follow inline */
3488 };
3489 
3490 struct protocol64_t {
3491   uint64_t isa;                     /* id * (64-bit pointer) */
3492   uint64_t name;                    /* const char * (64-bit pointer) */
3493   uint64_t protocols;               /* struct protocol_list64_t *
3494                                                     (64-bit pointer) */
3495   uint64_t instanceMethods;         /* method_list_t * (64-bit pointer) */
3496   uint64_t classMethods;            /* method_list_t * (64-bit pointer) */
3497   uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
3498   uint64_t optionalClassMethods;    /* method_list_t * (64-bit pointer) */
3499   uint64_t instanceProperties;      /* struct objc_property_list *
3500                                                        (64-bit pointer) */
3501 };
3502 
3503 struct protocol32_t {
3504   uint32_t isa;                     /* id * (32-bit pointer) */
3505   uint32_t name;                    /* const char * (32-bit pointer) */
3506   uint32_t protocols;               /* struct protocol_list_t *
3507                                                     (32-bit pointer) */
3508   uint32_t instanceMethods;         /* method_list_t * (32-bit pointer) */
3509   uint32_t classMethods;            /* method_list_t * (32-bit pointer) */
3510   uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
3511   uint32_t optionalClassMethods;    /* method_list_t * (32-bit pointer) */
3512   uint32_t instanceProperties;      /* struct objc_property_list *
3513                                                        (32-bit pointer) */
3514 };
3515 
3516 struct ivar_list64_t {
3517   uint32_t entsize;
3518   uint32_t count;
3519   /* struct ivar64_t first;  These structures follow inline */
3520 };
3521 
3522 struct ivar_list32_t {
3523   uint32_t entsize;
3524   uint32_t count;
3525   /* struct ivar32_t first;  These structures follow inline */
3526 };
3527 
3528 struct ivar64_t {
3529   uint64_t offset; /* uintptr_t * (64-bit pointer) */
3530   uint64_t name;   /* const char * (64-bit pointer) */
3531   uint64_t type;   /* const char * (64-bit pointer) */
3532   uint32_t alignment;
3533   uint32_t size;
3534 };
3535 
3536 struct ivar32_t {
3537   uint32_t offset; /* uintptr_t * (32-bit pointer) */
3538   uint32_t name;   /* const char * (32-bit pointer) */
3539   uint32_t type;   /* const char * (32-bit pointer) */
3540   uint32_t alignment;
3541   uint32_t size;
3542 };
3543 
3544 struct objc_property_list64 {
3545   uint32_t entsize;
3546   uint32_t count;
3547   /* struct objc_property64 first;  These structures follow inline */
3548 };
3549 
3550 struct objc_property_list32 {
3551   uint32_t entsize;
3552   uint32_t count;
3553   /* struct objc_property32 first;  These structures follow inline */
3554 };
3555 
3556 struct objc_property64 {
3557   uint64_t name;       /* const char * (64-bit pointer) */
3558   uint64_t attributes; /* const char * (64-bit pointer) */
3559 };
3560 
3561 struct objc_property32 {
3562   uint32_t name;       /* const char * (32-bit pointer) */
3563   uint32_t attributes; /* const char * (32-bit pointer) */
3564 };
3565 
3566 struct category64_t {
3567   uint64_t name;               /* const char * (64-bit pointer) */
3568   uint64_t cls;                /* struct class_t * (64-bit pointer) */
3569   uint64_t instanceMethods;    /* struct method_list_t * (64-bit pointer) */
3570   uint64_t classMethods;       /* struct method_list_t * (64-bit pointer) */
3571   uint64_t protocols;          /* struct protocol_list_t * (64-bit pointer) */
3572   uint64_t instanceProperties; /* struct objc_property_list *
3573                                   (64-bit pointer) */
3574 };
3575 
3576 struct category32_t {
3577   uint32_t name;               /* const char * (32-bit pointer) */
3578   uint32_t cls;                /* struct class_t * (32-bit pointer) */
3579   uint32_t instanceMethods;    /* struct method_list_t * (32-bit pointer) */
3580   uint32_t classMethods;       /* struct method_list_t * (32-bit pointer) */
3581   uint32_t protocols;          /* struct protocol_list_t * (32-bit pointer) */
3582   uint32_t instanceProperties; /* struct objc_property_list *
3583                                   (32-bit pointer) */
3584 };
3585 
3586 struct objc_image_info64 {
3587   uint32_t version;
3588   uint32_t flags;
3589 };
3590 struct objc_image_info32 {
3591   uint32_t version;
3592   uint32_t flags;
3593 };
3594 struct imageInfo_t {
3595   uint32_t version;
3596   uint32_t flags;
3597 };
3598 /* masks for objc_image_info.flags */
3599 #define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
3600 #define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
3601 #define OBJC_IMAGE_IS_SIMULATED (1 << 5)
3602 #define OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES (1 << 6)
3603 
3604 struct message_ref64 {
3605   uint64_t imp; /* IMP (64-bit pointer) */
3606   uint64_t sel; /* SEL (64-bit pointer) */
3607 };
3608 
3609 struct message_ref32 {
3610   uint32_t imp; /* IMP (32-bit pointer) */
3611   uint32_t sel; /* SEL (32-bit pointer) */
3612 };
3613 
3614 // Objective-C 1 (32-bit only) meta data structs.
3615 
3616 struct objc_module_t {
3617   uint32_t version;
3618   uint32_t size;
3619   uint32_t name;   /* char * (32-bit pointer) */
3620   uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
3621 };
3622 
3623 struct objc_symtab_t {
3624   uint32_t sel_ref_cnt;
3625   uint32_t refs; /* SEL * (32-bit pointer) */
3626   uint16_t cls_def_cnt;
3627   uint16_t cat_def_cnt;
3628   // uint32_t defs[1];        /* void * (32-bit pointer) variable size */
3629 };
3630 
3631 struct objc_class_t {
3632   uint32_t isa;         /* struct objc_class * (32-bit pointer) */
3633   uint32_t super_class; /* struct objc_class * (32-bit pointer) */
3634   uint32_t name;        /* const char * (32-bit pointer) */
3635   int32_t version;
3636   int32_t info;
3637   int32_t instance_size;
3638   uint32_t ivars;       /* struct objc_ivar_list * (32-bit pointer) */
3639   uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
3640   uint32_t cache;       /* struct objc_cache * (32-bit pointer) */
3641   uint32_t protocols;   /* struct objc_protocol_list * (32-bit pointer) */
3642 };
3643 
3644 #define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
3645 // class is not a metaclass
3646 #define CLS_CLASS 0x1
3647 // class is a metaclass
3648 #define CLS_META 0x2
3649 
3650 struct objc_category_t {
3651   uint32_t category_name;    /* char * (32-bit pointer) */
3652   uint32_t class_name;       /* char * (32-bit pointer) */
3653   uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
3654   uint32_t class_methods;    /* struct objc_method_list * (32-bit pointer) */
3655   uint32_t protocols;        /* struct objc_protocol_list * (32-bit ptr) */
3656 };
3657 
3658 struct objc_ivar_t {
3659   uint32_t ivar_name; /* char * (32-bit pointer) */
3660   uint32_t ivar_type; /* char * (32-bit pointer) */
3661   int32_t ivar_offset;
3662 };
3663 
3664 struct objc_ivar_list_t {
3665   int32_t ivar_count;
3666   // struct objc_ivar_t ivar_list[1];          /* variable length structure */
3667 };
3668 
3669 struct objc_method_list_t {
3670   uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
3671   int32_t method_count;
3672   // struct objc_method_t method_list[1];      /* variable length structure */
3673 };
3674 
3675 struct objc_method_t {
3676   uint32_t method_name;  /* SEL, aka struct objc_selector * (32-bit pointer) */
3677   uint32_t method_types; /* char * (32-bit pointer) */
3678   uint32_t method_imp;   /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
3679                             (32-bit pointer) */
3680 };
3681 
3682 struct objc_protocol_list_t {
3683   uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
3684   int32_t count;
3685   // uint32_t list[1];   /* Protocol *, aka struct objc_protocol_t *
3686   //                        (32-bit pointer) */
3687 };
3688 
3689 struct objc_protocol_t {
3690   uint32_t isa;              /* struct objc_class * (32-bit pointer) */
3691   uint32_t protocol_name;    /* char * (32-bit pointer) */
3692   uint32_t protocol_list;    /* struct objc_protocol_list * (32-bit pointer) */
3693   uint32_t instance_methods; /* struct objc_method_description_list *
3694                                 (32-bit pointer) */
3695   uint32_t class_methods;    /* struct objc_method_description_list *
3696                                 (32-bit pointer) */
3697 };
3698 
3699 struct objc_method_description_list_t {
3700   int32_t count;
3701   // struct objc_method_description_t list[1];
3702 };
3703 
3704 struct objc_method_description_t {
3705   uint32_t name;  /* SEL, aka struct objc_selector * (32-bit pointer) */
3706   uint32_t types; /* char * (32-bit pointer) */
3707 };
3708 
3709 inline void swapStruct(struct cfstring64_t &cfs) {
3710   sys::swapByteOrder(cfs.isa);
3711   sys::swapByteOrder(cfs.flags);
3712   sys::swapByteOrder(cfs.characters);
3713   sys::swapByteOrder(cfs.length);
3714 }
3715 
3716 inline void swapStruct(struct class64_t &c) {
3717   sys::swapByteOrder(c.isa);
3718   sys::swapByteOrder(c.superclass);
3719   sys::swapByteOrder(c.cache);
3720   sys::swapByteOrder(c.vtable);
3721   sys::swapByteOrder(c.data);
3722 }
3723 
3724 inline void swapStruct(struct class32_t &c) {
3725   sys::swapByteOrder(c.isa);
3726   sys::swapByteOrder(c.superclass);
3727   sys::swapByteOrder(c.cache);
3728   sys::swapByteOrder(c.vtable);
3729   sys::swapByteOrder(c.data);
3730 }
3731 
3732 inline void swapStruct(struct class_ro64_t &cro) {
3733   sys::swapByteOrder(cro.flags);
3734   sys::swapByteOrder(cro.instanceStart);
3735   sys::swapByteOrder(cro.instanceSize);
3736   sys::swapByteOrder(cro.reserved);
3737   sys::swapByteOrder(cro.ivarLayout);
3738   sys::swapByteOrder(cro.name);
3739   sys::swapByteOrder(cro.baseMethods);
3740   sys::swapByteOrder(cro.baseProtocols);
3741   sys::swapByteOrder(cro.ivars);
3742   sys::swapByteOrder(cro.weakIvarLayout);
3743   sys::swapByteOrder(cro.baseProperties);
3744 }
3745 
3746 inline void swapStruct(struct class_ro32_t &cro) {
3747   sys::swapByteOrder(cro.flags);
3748   sys::swapByteOrder(cro.instanceStart);
3749   sys::swapByteOrder(cro.instanceSize);
3750   sys::swapByteOrder(cro.ivarLayout);
3751   sys::swapByteOrder(cro.name);
3752   sys::swapByteOrder(cro.baseMethods);
3753   sys::swapByteOrder(cro.baseProtocols);
3754   sys::swapByteOrder(cro.ivars);
3755   sys::swapByteOrder(cro.weakIvarLayout);
3756   sys::swapByteOrder(cro.baseProperties);
3757 }
3758 
3759 inline void swapStruct(struct method_list64_t &ml) {
3760   sys::swapByteOrder(ml.entsize);
3761   sys::swapByteOrder(ml.count);
3762 }
3763 
3764 inline void swapStruct(struct method_list32_t &ml) {
3765   sys::swapByteOrder(ml.entsize);
3766   sys::swapByteOrder(ml.count);
3767 }
3768 
3769 inline void swapStruct(struct method64_t &m) {
3770   sys::swapByteOrder(m.name);
3771   sys::swapByteOrder(m.types);
3772   sys::swapByteOrder(m.imp);
3773 }
3774 
3775 inline void swapStruct(struct method32_t &m) {
3776   sys::swapByteOrder(m.name);
3777   sys::swapByteOrder(m.types);
3778   sys::swapByteOrder(m.imp);
3779 }
3780 
3781 inline void swapStruct(struct protocol_list64_t &pl) {
3782   sys::swapByteOrder(pl.count);
3783 }
3784 
3785 inline void swapStruct(struct protocol_list32_t &pl) {
3786   sys::swapByteOrder(pl.count);
3787 }
3788 
3789 inline void swapStruct(struct protocol64_t &p) {
3790   sys::swapByteOrder(p.isa);
3791   sys::swapByteOrder(p.name);
3792   sys::swapByteOrder(p.protocols);
3793   sys::swapByteOrder(p.instanceMethods);
3794   sys::swapByteOrder(p.classMethods);
3795   sys::swapByteOrder(p.optionalInstanceMethods);
3796   sys::swapByteOrder(p.optionalClassMethods);
3797   sys::swapByteOrder(p.instanceProperties);
3798 }
3799 
3800 inline void swapStruct(struct protocol32_t &p) {
3801   sys::swapByteOrder(p.isa);
3802   sys::swapByteOrder(p.name);
3803   sys::swapByteOrder(p.protocols);
3804   sys::swapByteOrder(p.instanceMethods);
3805   sys::swapByteOrder(p.classMethods);
3806   sys::swapByteOrder(p.optionalInstanceMethods);
3807   sys::swapByteOrder(p.optionalClassMethods);
3808   sys::swapByteOrder(p.instanceProperties);
3809 }
3810 
3811 inline void swapStruct(struct ivar_list64_t &il) {
3812   sys::swapByteOrder(il.entsize);
3813   sys::swapByteOrder(il.count);
3814 }
3815 
3816 inline void swapStruct(struct ivar_list32_t &il) {
3817   sys::swapByteOrder(il.entsize);
3818   sys::swapByteOrder(il.count);
3819 }
3820 
3821 inline void swapStruct(struct ivar64_t &i) {
3822   sys::swapByteOrder(i.offset);
3823   sys::swapByteOrder(i.name);
3824   sys::swapByteOrder(i.type);
3825   sys::swapByteOrder(i.alignment);
3826   sys::swapByteOrder(i.size);
3827 }
3828 
3829 inline void swapStruct(struct ivar32_t &i) {
3830   sys::swapByteOrder(i.offset);
3831   sys::swapByteOrder(i.name);
3832   sys::swapByteOrder(i.type);
3833   sys::swapByteOrder(i.alignment);
3834   sys::swapByteOrder(i.size);
3835 }
3836 
3837 inline void swapStruct(struct objc_property_list64 &pl) {
3838   sys::swapByteOrder(pl.entsize);
3839   sys::swapByteOrder(pl.count);
3840 }
3841 
3842 inline void swapStruct(struct objc_property_list32 &pl) {
3843   sys::swapByteOrder(pl.entsize);
3844   sys::swapByteOrder(pl.count);
3845 }
3846 
3847 inline void swapStruct(struct objc_property64 &op) {
3848   sys::swapByteOrder(op.name);
3849   sys::swapByteOrder(op.attributes);
3850 }
3851 
3852 inline void swapStruct(struct objc_property32 &op) {
3853   sys::swapByteOrder(op.name);
3854   sys::swapByteOrder(op.attributes);
3855 }
3856 
3857 inline void swapStruct(struct category64_t &c) {
3858   sys::swapByteOrder(c.name);
3859   sys::swapByteOrder(c.cls);
3860   sys::swapByteOrder(c.instanceMethods);
3861   sys::swapByteOrder(c.classMethods);
3862   sys::swapByteOrder(c.protocols);
3863   sys::swapByteOrder(c.instanceProperties);
3864 }
3865 
3866 inline void swapStruct(struct category32_t &c) {
3867   sys::swapByteOrder(c.name);
3868   sys::swapByteOrder(c.cls);
3869   sys::swapByteOrder(c.instanceMethods);
3870   sys::swapByteOrder(c.classMethods);
3871   sys::swapByteOrder(c.protocols);
3872   sys::swapByteOrder(c.instanceProperties);
3873 }
3874 
3875 inline void swapStruct(struct objc_image_info64 &o) {
3876   sys::swapByteOrder(o.version);
3877   sys::swapByteOrder(o.flags);
3878 }
3879 
3880 inline void swapStruct(struct objc_image_info32 &o) {
3881   sys::swapByteOrder(o.version);
3882   sys::swapByteOrder(o.flags);
3883 }
3884 
3885 inline void swapStruct(struct imageInfo_t &o) {
3886   sys::swapByteOrder(o.version);
3887   sys::swapByteOrder(o.flags);
3888 }
3889 
3890 inline void swapStruct(struct message_ref64 &mr) {
3891   sys::swapByteOrder(mr.imp);
3892   sys::swapByteOrder(mr.sel);
3893 }
3894 
3895 inline void swapStruct(struct message_ref32 &mr) {
3896   sys::swapByteOrder(mr.imp);
3897   sys::swapByteOrder(mr.sel);
3898 }
3899 
3900 inline void swapStruct(struct objc_module_t &module) {
3901   sys::swapByteOrder(module.version);
3902   sys::swapByteOrder(module.size);
3903   sys::swapByteOrder(module.name);
3904   sys::swapByteOrder(module.symtab);
3905 }
3906 
3907 inline void swapStruct(struct objc_symtab_t &symtab) {
3908   sys::swapByteOrder(symtab.sel_ref_cnt);
3909   sys::swapByteOrder(symtab.refs);
3910   sys::swapByteOrder(symtab.cls_def_cnt);
3911   sys::swapByteOrder(symtab.cat_def_cnt);
3912 }
3913 
3914 inline void swapStruct(struct objc_class_t &objc_class) {
3915   sys::swapByteOrder(objc_class.isa);
3916   sys::swapByteOrder(objc_class.super_class);
3917   sys::swapByteOrder(objc_class.name);
3918   sys::swapByteOrder(objc_class.version);
3919   sys::swapByteOrder(objc_class.info);
3920   sys::swapByteOrder(objc_class.instance_size);
3921   sys::swapByteOrder(objc_class.ivars);
3922   sys::swapByteOrder(objc_class.methodLists);
3923   sys::swapByteOrder(objc_class.cache);
3924   sys::swapByteOrder(objc_class.protocols);
3925 }
3926 
3927 inline void swapStruct(struct objc_category_t &objc_category) {
3928   sys::swapByteOrder(objc_category.category_name);
3929   sys::swapByteOrder(objc_category.class_name);
3930   sys::swapByteOrder(objc_category.instance_methods);
3931   sys::swapByteOrder(objc_category.class_methods);
3932   sys::swapByteOrder(objc_category.protocols);
3933 }
3934 
3935 inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3936   sys::swapByteOrder(objc_ivar_list.ivar_count);
3937 }
3938 
3939 inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3940   sys::swapByteOrder(objc_ivar.ivar_name);
3941   sys::swapByteOrder(objc_ivar.ivar_type);
3942   sys::swapByteOrder(objc_ivar.ivar_offset);
3943 }
3944 
3945 inline void swapStruct(struct objc_method_list_t &method_list) {
3946   sys::swapByteOrder(method_list.obsolete);
3947   sys::swapByteOrder(method_list.method_count);
3948 }
3949 
3950 inline void swapStruct(struct objc_method_t &method) {
3951   sys::swapByteOrder(method.method_name);
3952   sys::swapByteOrder(method.method_types);
3953   sys::swapByteOrder(method.method_imp);
3954 }
3955 
3956 inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3957   sys::swapByteOrder(protocol_list.next);
3958   sys::swapByteOrder(protocol_list.count);
3959 }
3960 
3961 inline void swapStruct(struct objc_protocol_t &protocol) {
3962   sys::swapByteOrder(protocol.isa);
3963   sys::swapByteOrder(protocol.protocol_name);
3964   sys::swapByteOrder(protocol.protocol_list);
3965   sys::swapByteOrder(protocol.instance_methods);
3966   sys::swapByteOrder(protocol.class_methods);
3967 }
3968 
3969 inline void swapStruct(struct objc_method_description_list_t &mdl) {
3970   sys::swapByteOrder(mdl.count);
3971 }
3972 
3973 inline void swapStruct(struct objc_method_description_t &md) {
3974   sys::swapByteOrder(md.name);
3975   sys::swapByteOrder(md.types);
3976 }
3977 
3978 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3979                                                  struct DisassembleInfo *info);
3980 
3981 // get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3982 // to an Objective-C class and returns the class name.  It is also passed the
3983 // address of the pointer, so when the pointer is zero as it can be in an .o
3984 // file, that is used to look for an external relocation entry with a symbol
3985 // name.
3986 static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3987                                               uint64_t ReferenceValue,
3988                                               struct DisassembleInfo *info) {
3989   const char *r;
3990   uint32_t offset, left;
3991   SectionRef S;
3992 
3993   // The pointer_value can be 0 in an object file and have a relocation
3994   // entry for the class symbol at the ReferenceValue (the address of the
3995   // pointer).
3996   if (pointer_value == 0) {
3997     r = get_pointer_64(ReferenceValue, offset, left, S, info);
3998     if (r == nullptr || left < sizeof(uint64_t))
3999       return nullptr;
4000     uint64_t n_value;
4001     const char *symbol_name = get_symbol_64(offset, S, info, n_value);
4002     if (symbol_name == nullptr)
4003       return nullptr;
4004     const char *class_name = strrchr(symbol_name, '$');
4005     if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
4006       return class_name + 2;
4007     else
4008       return nullptr;
4009   }
4010 
4011   // The case were the pointer_value is non-zero and points to a class defined
4012   // in this Mach-O file.
4013   r = get_pointer_64(pointer_value, offset, left, S, info);
4014   if (r == nullptr || left < sizeof(struct class64_t))
4015     return nullptr;
4016   struct class64_t c;
4017   memcpy(&c, r, sizeof(struct class64_t));
4018   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4019     swapStruct(c);
4020   if (c.data == 0)
4021     return nullptr;
4022   r = get_pointer_64(c.data, offset, left, S, info);
4023   if (r == nullptr || left < sizeof(struct class_ro64_t))
4024     return nullptr;
4025   struct class_ro64_t cro;
4026   memcpy(&cro, r, sizeof(struct class_ro64_t));
4027   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4028     swapStruct(cro);
4029   if (cro.name == 0)
4030     return nullptr;
4031   const char *name = get_pointer_64(cro.name, offset, left, S, info);
4032   return name;
4033 }
4034 
4035 // get_objc2_64bit_cfstring_name is used for disassembly and is passed a
4036 // pointer to a cfstring and returns its name or nullptr.
4037 static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
4038                                                  struct DisassembleInfo *info) {
4039   const char *r, *name;
4040   uint32_t offset, left;
4041   SectionRef S;
4042   struct cfstring64_t cfs;
4043   uint64_t cfs_characters;
4044 
4045   r = get_pointer_64(ReferenceValue, offset, left, S, info);
4046   if (r == nullptr || left < sizeof(struct cfstring64_t))
4047     return nullptr;
4048   memcpy(&cfs, r, sizeof(struct cfstring64_t));
4049   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4050     swapStruct(cfs);
4051   if (cfs.characters == 0) {
4052     uint64_t n_value;
4053     const char *symbol_name = get_symbol_64(
4054         offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
4055     if (symbol_name == nullptr)
4056       return nullptr;
4057     cfs_characters = n_value;
4058   } else
4059     cfs_characters = cfs.characters;
4060   name = get_pointer_64(cfs_characters, offset, left, S, info);
4061 
4062   return name;
4063 }
4064 
4065 // get_objc2_64bit_selref() is used for disassembly and is passed a the address
4066 // of a pointer to an Objective-C selector reference when the pointer value is
4067 // zero as in a .o file and is likely to have a external relocation entry with
4068 // who's symbol's n_value is the real pointer to the selector name.  If that is
4069 // the case the real pointer to the selector name is returned else 0 is
4070 // returned
4071 static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
4072                                        struct DisassembleInfo *info) {
4073   uint32_t offset, left;
4074   SectionRef S;
4075 
4076   const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
4077   if (r == nullptr || left < sizeof(uint64_t))
4078     return 0;
4079   uint64_t n_value;
4080   const char *symbol_name = get_symbol_64(offset, S, info, n_value);
4081   if (symbol_name == nullptr)
4082     return 0;
4083   return n_value;
4084 }
4085 
4086 static const SectionRef get_section(MachOObjectFile *O, const char *segname,
4087                                     const char *sectname) {
4088   for (const SectionRef &Section : O->sections()) {
4089     StringRef SectName;
4090     Expected<StringRef> SecNameOrErr = Section.getName();
4091     if (SecNameOrErr)
4092       SectName = *SecNameOrErr;
4093     else
4094       consumeError(SecNameOrErr.takeError());
4095 
4096     DataRefImpl Ref = Section.getRawDataRefImpl();
4097     StringRef SegName = O->getSectionFinalSegmentName(Ref);
4098     if (SegName == segname && SectName == sectname)
4099       return Section;
4100   }
4101   return SectionRef();
4102 }
4103 
4104 static void
4105 walk_pointer_list_64(const char *listname, const SectionRef S,
4106                      MachOObjectFile *O, struct DisassembleInfo *info,
4107                      void (*func)(uint64_t, struct DisassembleInfo *info)) {
4108   if (S == SectionRef())
4109     return;
4110 
4111   StringRef SectName;
4112   Expected<StringRef> SecNameOrErr = S.getName();
4113   if (SecNameOrErr)
4114     SectName = *SecNameOrErr;
4115   else
4116     consumeError(SecNameOrErr.takeError());
4117 
4118   DataRefImpl Ref = S.getRawDataRefImpl();
4119   StringRef SegName = O->getSectionFinalSegmentName(Ref);
4120   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4121 
4122   StringRef BytesStr = unwrapOrError(S.getContents(), O->getFileName());
4123   const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
4124 
4125   for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
4126     uint32_t left = S.getSize() - i;
4127     uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
4128     uint64_t p = 0;
4129     memcpy(&p, Contents + i, size);
4130     if (i + sizeof(uint64_t) > S.getSize())
4131       outs() << listname << " list pointer extends past end of (" << SegName
4132              << "," << SectName << ") section\n";
4133     outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
4134 
4135     if (O->isLittleEndian() != sys::IsLittleEndianHost)
4136       sys::swapByteOrder(p);
4137 
4138     uint64_t n_value = 0;
4139     const char *name = get_symbol_64(i, S, info, n_value, p);
4140     if (name == nullptr)
4141       name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
4142 
4143     if (n_value != 0) {
4144       outs() << format("0x%" PRIx64, n_value);
4145       if (p != 0)
4146         outs() << " + " << format("0x%" PRIx64, p);
4147     } else
4148       outs() << format("0x%" PRIx64, p);
4149     if (name != nullptr)
4150       outs() << " " << name;
4151     outs() << "\n";
4152 
4153     p += n_value;
4154     if (func)
4155       func(p, info);
4156   }
4157 }
4158 
4159 static void
4160 walk_pointer_list_32(const char *listname, const SectionRef S,
4161                      MachOObjectFile *O, struct DisassembleInfo *info,
4162                      void (*func)(uint32_t, struct DisassembleInfo *info)) {
4163   if (S == SectionRef())
4164     return;
4165 
4166   StringRef SectName = unwrapOrError(S.getName(), O->getFileName());
4167   DataRefImpl Ref = S.getRawDataRefImpl();
4168   StringRef SegName = O->getSectionFinalSegmentName(Ref);
4169   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4170 
4171   StringRef BytesStr = unwrapOrError(S.getContents(), O->getFileName());
4172   const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
4173 
4174   for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
4175     uint32_t left = S.getSize() - i;
4176     uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
4177     uint32_t p = 0;
4178     memcpy(&p, Contents + i, size);
4179     if (i + sizeof(uint32_t) > S.getSize())
4180       outs() << listname << " list pointer extends past end of (" << SegName
4181              << "," << SectName << ") section\n";
4182     uint32_t Address = S.getAddress() + i;
4183     outs() << format("%08" PRIx32, Address) << " ";
4184 
4185     if (O->isLittleEndian() != sys::IsLittleEndianHost)
4186       sys::swapByteOrder(p);
4187     outs() << format("0x%" PRIx32, p);
4188 
4189     const char *name = get_symbol_32(i, S, info, p);
4190     if (name != nullptr)
4191       outs() << " " << name;
4192     outs() << "\n";
4193 
4194     if (func)
4195       func(p, info);
4196   }
4197 }
4198 
4199 static void print_layout_map(const char *layout_map, uint32_t left) {
4200   if (layout_map == nullptr)
4201     return;
4202   outs() << "                layout map: ";
4203   do {
4204     outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
4205     left--;
4206     layout_map++;
4207   } while (*layout_map != '\0' && left != 0);
4208   outs() << "\n";
4209 }
4210 
4211 static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
4212   uint32_t offset, left;
4213   SectionRef S;
4214   const char *layout_map;
4215 
4216   if (p == 0)
4217     return;
4218   layout_map = get_pointer_64(p, offset, left, S, info);
4219   print_layout_map(layout_map, left);
4220 }
4221 
4222 static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
4223   uint32_t offset, left;
4224   SectionRef S;
4225   const char *layout_map;
4226 
4227   if (p == 0)
4228     return;
4229   layout_map = get_pointer_32(p, offset, left, S, info);
4230   print_layout_map(layout_map, left);
4231 }
4232 
4233 static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
4234                                   const char *indent) {
4235   struct method_list64_t ml;
4236   struct method64_t m;
4237   const char *r;
4238   uint32_t offset, xoffset, left, i;
4239   SectionRef S, xS;
4240   const char *name, *sym_name;
4241   uint64_t n_value;
4242 
4243   r = get_pointer_64(p, offset, left, S, info);
4244   if (r == nullptr)
4245     return;
4246   memset(&ml, '\0', sizeof(struct method_list64_t));
4247   if (left < sizeof(struct method_list64_t)) {
4248     memcpy(&ml, r, left);
4249     outs() << "   (method_list_t entends past the end of the section)\n";
4250   } else
4251     memcpy(&ml, r, sizeof(struct method_list64_t));
4252   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4253     swapStruct(ml);
4254   outs() << indent << "\t\t   entsize " << ml.entsize << "\n";
4255   outs() << indent << "\t\t     count " << ml.count << "\n";
4256 
4257   p += sizeof(struct method_list64_t);
4258   offset += sizeof(struct method_list64_t);
4259   for (i = 0; i < ml.count; i++) {
4260     r = get_pointer_64(p, offset, left, S, info);
4261     if (r == nullptr)
4262       return;
4263     memset(&m, '\0', sizeof(struct method64_t));
4264     if (left < sizeof(struct method64_t)) {
4265       memcpy(&m, r, left);
4266       outs() << indent << "   (method_t extends past the end of the section)\n";
4267     } else
4268       memcpy(&m, r, sizeof(struct method64_t));
4269     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4270       swapStruct(m);
4271 
4272     outs() << indent << "\t\t      name ";
4273     sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
4274                              info, n_value, m.name);
4275     if (n_value != 0) {
4276       if (info->verbose && sym_name != nullptr)
4277         outs() << sym_name;
4278       else
4279         outs() << format("0x%" PRIx64, n_value);
4280       if (m.name != 0)
4281         outs() << " + " << format("0x%" PRIx64, m.name);
4282     } else
4283       outs() << format("0x%" PRIx64, m.name);
4284     name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
4285     if (name != nullptr)
4286       outs() << format(" %.*s", left, name);
4287     outs() << "\n";
4288 
4289     outs() << indent << "\t\t     types ";
4290     sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
4291                              info, n_value, m.types);
4292     if (n_value != 0) {
4293       if (info->verbose && sym_name != nullptr)
4294         outs() << sym_name;
4295       else
4296         outs() << format("0x%" PRIx64, n_value);
4297       if (m.types != 0)
4298         outs() << " + " << format("0x%" PRIx64, m.types);
4299     } else
4300       outs() << format("0x%" PRIx64, m.types);
4301     name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
4302     if (name != nullptr)
4303       outs() << format(" %.*s", left, name);
4304     outs() << "\n";
4305 
4306     outs() << indent << "\t\t       imp ";
4307     name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
4308                          n_value, m.imp);
4309     if (info->verbose && name == nullptr) {
4310       if (n_value != 0) {
4311         outs() << format("0x%" PRIx64, n_value) << " ";
4312         if (m.imp != 0)
4313           outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
4314       } else
4315         outs() << format("0x%" PRIx64, m.imp) << " ";
4316     }
4317     if (name != nullptr)
4318       outs() << name;
4319     outs() << "\n";
4320 
4321     p += sizeof(struct method64_t);
4322     offset += sizeof(struct method64_t);
4323   }
4324 }
4325 
4326 static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
4327                                   const char *indent) {
4328   struct method_list32_t ml;
4329   struct method32_t m;
4330   const char *r, *name;
4331   uint32_t offset, xoffset, left, i;
4332   SectionRef S, xS;
4333 
4334   r = get_pointer_32(p, offset, left, S, info);
4335   if (r == nullptr)
4336     return;
4337   memset(&ml, '\0', sizeof(struct method_list32_t));
4338   if (left < sizeof(struct method_list32_t)) {
4339     memcpy(&ml, r, left);
4340     outs() << "   (method_list_t entends past the end of the section)\n";
4341   } else
4342     memcpy(&ml, r, sizeof(struct method_list32_t));
4343   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4344     swapStruct(ml);
4345   outs() << indent << "\t\t   entsize " << ml.entsize << "\n";
4346   outs() << indent << "\t\t     count " << ml.count << "\n";
4347 
4348   p += sizeof(struct method_list32_t);
4349   offset += sizeof(struct method_list32_t);
4350   for (i = 0; i < ml.count; i++) {
4351     r = get_pointer_32(p, offset, left, S, info);
4352     if (r == nullptr)
4353       return;
4354     memset(&m, '\0', sizeof(struct method32_t));
4355     if (left < sizeof(struct method32_t)) {
4356       memcpy(&ml, r, left);
4357       outs() << indent << "   (method_t entends past the end of the section)\n";
4358     } else
4359       memcpy(&m, r, sizeof(struct method32_t));
4360     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4361       swapStruct(m);
4362 
4363     outs() << indent << "\t\t      name " << format("0x%" PRIx32, m.name);
4364     name = get_pointer_32(m.name, xoffset, left, xS, info);
4365     if (name != nullptr)
4366       outs() << format(" %.*s", left, name);
4367     outs() << "\n";
4368 
4369     outs() << indent << "\t\t     types " << format("0x%" PRIx32, m.types);
4370     name = get_pointer_32(m.types, xoffset, left, xS, info);
4371     if (name != nullptr)
4372       outs() << format(" %.*s", left, name);
4373     outs() << "\n";
4374 
4375     outs() << indent << "\t\t       imp " << format("0x%" PRIx32, m.imp);
4376     name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
4377                          m.imp);
4378     if (name != nullptr)
4379       outs() << " " << name;
4380     outs() << "\n";
4381 
4382     p += sizeof(struct method32_t);
4383     offset += sizeof(struct method32_t);
4384   }
4385 }
4386 
4387 static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
4388   uint32_t offset, left, xleft;
4389   SectionRef S;
4390   struct objc_method_list_t method_list;
4391   struct objc_method_t method;
4392   const char *r, *methods, *name, *SymbolName;
4393   int32_t i;
4394 
4395   r = get_pointer_32(p, offset, left, S, info, true);
4396   if (r == nullptr)
4397     return true;
4398 
4399   outs() << "\n";
4400   if (left > sizeof(struct objc_method_list_t)) {
4401     memcpy(&method_list, r, sizeof(struct objc_method_list_t));
4402   } else {
4403     outs() << "\t\t objc_method_list extends past end of the section\n";
4404     memset(&method_list, '\0', sizeof(struct objc_method_list_t));
4405     memcpy(&method_list, r, left);
4406   }
4407   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4408     swapStruct(method_list);
4409 
4410   outs() << "\t\t         obsolete "
4411          << format("0x%08" PRIx32, method_list.obsolete) << "\n";
4412   outs() << "\t\t     method_count " << method_list.method_count << "\n";
4413 
4414   methods = r + sizeof(struct objc_method_list_t);
4415   for (i = 0; i < method_list.method_count; i++) {
4416     if ((i + 1) * sizeof(struct objc_method_t) > left) {
4417       outs() << "\t\t remaining method's extend past the of the section\n";
4418       break;
4419     }
4420     memcpy(&method, methods + i * sizeof(struct objc_method_t),
4421            sizeof(struct objc_method_t));
4422     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4423       swapStruct(method);
4424 
4425     outs() << "\t\t      method_name "
4426            << format("0x%08" PRIx32, method.method_name);
4427     if (info->verbose) {
4428       name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
4429       if (name != nullptr)
4430         outs() << format(" %.*s", xleft, name);
4431       else
4432         outs() << " (not in an __OBJC section)";
4433     }
4434     outs() << "\n";
4435 
4436     outs() << "\t\t     method_types "
4437            << format("0x%08" PRIx32, method.method_types);
4438     if (info->verbose) {
4439       name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
4440       if (name != nullptr)
4441         outs() << format(" %.*s", xleft, name);
4442       else
4443         outs() << " (not in an __OBJC section)";
4444     }
4445     outs() << "\n";
4446 
4447     outs() << "\t\t       method_imp "
4448            << format("0x%08" PRIx32, method.method_imp) << " ";
4449     if (info->verbose) {
4450       SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
4451       if (SymbolName != nullptr)
4452         outs() << SymbolName;
4453     }
4454     outs() << "\n";
4455   }
4456   return false;
4457 }
4458 
4459 static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
4460   struct protocol_list64_t pl;
4461   uint64_t q, n_value;
4462   struct protocol64_t pc;
4463   const char *r;
4464   uint32_t offset, xoffset, left, i;
4465   SectionRef S, xS;
4466   const char *name, *sym_name;
4467 
4468   r = get_pointer_64(p, offset, left, S, info);
4469   if (r == nullptr)
4470     return;
4471   memset(&pl, '\0', sizeof(struct protocol_list64_t));
4472   if (left < sizeof(struct protocol_list64_t)) {
4473     memcpy(&pl, r, left);
4474     outs() << "   (protocol_list_t entends past the end of the section)\n";
4475   } else
4476     memcpy(&pl, r, sizeof(struct protocol_list64_t));
4477   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4478     swapStruct(pl);
4479   outs() << "                      count " << pl.count << "\n";
4480 
4481   p += sizeof(struct protocol_list64_t);
4482   offset += sizeof(struct protocol_list64_t);
4483   for (i = 0; i < pl.count; i++) {
4484     r = get_pointer_64(p, offset, left, S, info);
4485     if (r == nullptr)
4486       return;
4487     q = 0;
4488     if (left < sizeof(uint64_t)) {
4489       memcpy(&q, r, left);
4490       outs() << "   (protocol_t * entends past the end of the section)\n";
4491     } else
4492       memcpy(&q, r, sizeof(uint64_t));
4493     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4494       sys::swapByteOrder(q);
4495 
4496     outs() << "\t\t      list[" << i << "] ";
4497     sym_name = get_symbol_64(offset, S, info, n_value, q);
4498     if (n_value != 0) {
4499       if (info->verbose && sym_name != nullptr)
4500         outs() << sym_name;
4501       else
4502         outs() << format("0x%" PRIx64, n_value);
4503       if (q != 0)
4504         outs() << " + " << format("0x%" PRIx64, q);
4505     } else
4506       outs() << format("0x%" PRIx64, q);
4507     outs() << " (struct protocol_t *)\n";
4508 
4509     r = get_pointer_64(q + n_value, offset, left, S, info);
4510     if (r == nullptr)
4511       return;
4512     memset(&pc, '\0', sizeof(struct protocol64_t));
4513     if (left < sizeof(struct protocol64_t)) {
4514       memcpy(&pc, r, left);
4515       outs() << "   (protocol_t entends past the end of the section)\n";
4516     } else
4517       memcpy(&pc, r, sizeof(struct protocol64_t));
4518     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4519       swapStruct(pc);
4520 
4521     outs() << "\t\t\t      isa " << format("0x%" PRIx64, pc.isa) << "\n";
4522 
4523     outs() << "\t\t\t     name ";
4524     sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
4525                              info, n_value, pc.name);
4526     if (n_value != 0) {
4527       if (info->verbose && sym_name != nullptr)
4528         outs() << sym_name;
4529       else
4530         outs() << format("0x%" PRIx64, n_value);
4531       if (pc.name != 0)
4532         outs() << " + " << format("0x%" PRIx64, pc.name);
4533     } else
4534       outs() << format("0x%" PRIx64, pc.name);
4535     name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
4536     if (name != nullptr)
4537       outs() << format(" %.*s", left, name);
4538     outs() << "\n";
4539 
4540     outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
4541 
4542     outs() << "\t\t  instanceMethods ";
4543     sym_name =
4544         get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
4545                       S, info, n_value, pc.instanceMethods);
4546     if (n_value != 0) {
4547       if (info->verbose && sym_name != nullptr)
4548         outs() << sym_name;
4549       else
4550         outs() << format("0x%" PRIx64, n_value);
4551       if (pc.instanceMethods != 0)
4552         outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
4553     } else
4554       outs() << format("0x%" PRIx64, pc.instanceMethods);
4555     outs() << " (struct method_list_t *)\n";
4556     if (pc.instanceMethods + n_value != 0)
4557       print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
4558 
4559     outs() << "\t\t     classMethods ";
4560     sym_name =
4561         get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
4562                       info, n_value, pc.classMethods);
4563     if (n_value != 0) {
4564       if (info->verbose && sym_name != nullptr)
4565         outs() << sym_name;
4566       else
4567         outs() << format("0x%" PRIx64, n_value);
4568       if (pc.classMethods != 0)
4569         outs() << " + " << format("0x%" PRIx64, pc.classMethods);
4570     } else
4571       outs() << format("0x%" PRIx64, pc.classMethods);
4572     outs() << " (struct method_list_t *)\n";
4573     if (pc.classMethods + n_value != 0)
4574       print_method_list64_t(pc.classMethods + n_value, info, "\t");
4575 
4576     outs() << "\t  optionalInstanceMethods "
4577            << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
4578     outs() << "\t     optionalClassMethods "
4579            << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
4580     outs() << "\t       instanceProperties "
4581            << format("0x%" PRIx64, pc.instanceProperties) << "\n";
4582 
4583     p += sizeof(uint64_t);
4584     offset += sizeof(uint64_t);
4585   }
4586 }
4587 
4588 static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
4589   struct protocol_list32_t pl;
4590   uint32_t q;
4591   struct protocol32_t pc;
4592   const char *r;
4593   uint32_t offset, xoffset, left, i;
4594   SectionRef S, xS;
4595   const char *name;
4596 
4597   r = get_pointer_32(p, offset, left, S, info);
4598   if (r == nullptr)
4599     return;
4600   memset(&pl, '\0', sizeof(struct protocol_list32_t));
4601   if (left < sizeof(struct protocol_list32_t)) {
4602     memcpy(&pl, r, left);
4603     outs() << "   (protocol_list_t entends past the end of the section)\n";
4604   } else
4605     memcpy(&pl, r, sizeof(struct protocol_list32_t));
4606   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4607     swapStruct(pl);
4608   outs() << "                      count " << pl.count << "\n";
4609 
4610   p += sizeof(struct protocol_list32_t);
4611   offset += sizeof(struct protocol_list32_t);
4612   for (i = 0; i < pl.count; i++) {
4613     r = get_pointer_32(p, offset, left, S, info);
4614     if (r == nullptr)
4615       return;
4616     q = 0;
4617     if (left < sizeof(uint32_t)) {
4618       memcpy(&q, r, left);
4619       outs() << "   (protocol_t * entends past the end of the section)\n";
4620     } else
4621       memcpy(&q, r, sizeof(uint32_t));
4622     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4623       sys::swapByteOrder(q);
4624     outs() << "\t\t      list[" << i << "] " << format("0x%" PRIx32, q)
4625            << " (struct protocol_t *)\n";
4626     r = get_pointer_32(q, offset, left, S, info);
4627     if (r == nullptr)
4628       return;
4629     memset(&pc, '\0', sizeof(struct protocol32_t));
4630     if (left < sizeof(struct protocol32_t)) {
4631       memcpy(&pc, r, left);
4632       outs() << "   (protocol_t entends past the end of the section)\n";
4633     } else
4634       memcpy(&pc, r, sizeof(struct protocol32_t));
4635     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4636       swapStruct(pc);
4637     outs() << "\t\t\t      isa " << format("0x%" PRIx32, pc.isa) << "\n";
4638     outs() << "\t\t\t     name " << format("0x%" PRIx32, pc.name);
4639     name = get_pointer_32(pc.name, xoffset, left, xS, info);
4640     if (name != nullptr)
4641       outs() << format(" %.*s", left, name);
4642     outs() << "\n";
4643     outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
4644     outs() << "\t\t  instanceMethods "
4645            << format("0x%" PRIx32, pc.instanceMethods)
4646            << " (struct method_list_t *)\n";
4647     if (pc.instanceMethods != 0)
4648       print_method_list32_t(pc.instanceMethods, info, "\t");
4649     outs() << "\t\t     classMethods " << format("0x%" PRIx32, pc.classMethods)
4650            << " (struct method_list_t *)\n";
4651     if (pc.classMethods != 0)
4652       print_method_list32_t(pc.classMethods, info, "\t");
4653     outs() << "\t  optionalInstanceMethods "
4654            << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
4655     outs() << "\t     optionalClassMethods "
4656            << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
4657     outs() << "\t       instanceProperties "
4658            << format("0x%" PRIx32, pc.instanceProperties) << "\n";
4659     p += sizeof(uint32_t);
4660     offset += sizeof(uint32_t);
4661   }
4662 }
4663 
4664 static void print_indent(uint32_t indent) {
4665   for (uint32_t i = 0; i < indent;) {
4666     if (indent - i >= 8) {
4667       outs() << "\t";
4668       i += 8;
4669     } else {
4670       for (uint32_t j = i; j < indent; j++)
4671         outs() << " ";
4672       return;
4673     }
4674   }
4675 }
4676 
4677 static bool print_method_description_list(uint32_t p, uint32_t indent,
4678                                           struct DisassembleInfo *info) {
4679   uint32_t offset, left, xleft;
4680   SectionRef S;
4681   struct objc_method_description_list_t mdl;
4682   struct objc_method_description_t md;
4683   const char *r, *list, *name;
4684   int32_t i;
4685 
4686   r = get_pointer_32(p, offset, left, S, info, true);
4687   if (r == nullptr)
4688     return true;
4689 
4690   outs() << "\n";
4691   if (left > sizeof(struct objc_method_description_list_t)) {
4692     memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
4693   } else {
4694     print_indent(indent);
4695     outs() << " objc_method_description_list extends past end of the section\n";
4696     memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
4697     memcpy(&mdl, r, left);
4698   }
4699   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4700     swapStruct(mdl);
4701 
4702   print_indent(indent);
4703   outs() << "        count " << mdl.count << "\n";
4704 
4705   list = r + sizeof(struct objc_method_description_list_t);
4706   for (i = 0; i < mdl.count; i++) {
4707     if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
4708       print_indent(indent);
4709       outs() << " remaining list entries extend past the of the section\n";
4710       break;
4711     }
4712     print_indent(indent);
4713     outs() << "        list[" << i << "]\n";
4714     memcpy(&md, list + i * sizeof(struct objc_method_description_t),
4715            sizeof(struct objc_method_description_t));
4716     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4717       swapStruct(md);
4718 
4719     print_indent(indent);
4720     outs() << "             name " << format("0x%08" PRIx32, md.name);
4721     if (info->verbose) {
4722       name = get_pointer_32(md.name, offset, xleft, S, info, true);
4723       if (name != nullptr)
4724         outs() << format(" %.*s", xleft, name);
4725       else
4726         outs() << " (not in an __OBJC section)";
4727     }
4728     outs() << "\n";
4729 
4730     print_indent(indent);
4731     outs() << "            types " << format("0x%08" PRIx32, md.types);
4732     if (info->verbose) {
4733       name = get_pointer_32(md.types, offset, xleft, S, info, true);
4734       if (name != nullptr)
4735         outs() << format(" %.*s", xleft, name);
4736       else
4737         outs() << " (not in an __OBJC section)";
4738     }
4739     outs() << "\n";
4740   }
4741   return false;
4742 }
4743 
4744 static bool print_protocol_list(uint32_t p, uint32_t indent,
4745                                 struct DisassembleInfo *info);
4746 
4747 static bool print_protocol(uint32_t p, uint32_t indent,
4748                            struct DisassembleInfo *info) {
4749   uint32_t offset, left;
4750   SectionRef S;
4751   struct objc_protocol_t protocol;
4752   const char *r, *name;
4753 
4754   r = get_pointer_32(p, offset, left, S, info, true);
4755   if (r == nullptr)
4756     return true;
4757 
4758   outs() << "\n";
4759   if (left >= sizeof(struct objc_protocol_t)) {
4760     memcpy(&protocol, r, sizeof(struct objc_protocol_t));
4761   } else {
4762     print_indent(indent);
4763     outs() << "            Protocol extends past end of the section\n";
4764     memset(&protocol, '\0', sizeof(struct objc_protocol_t));
4765     memcpy(&protocol, r, left);
4766   }
4767   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4768     swapStruct(protocol);
4769 
4770   print_indent(indent);
4771   outs() << "              isa " << format("0x%08" PRIx32, protocol.isa)
4772          << "\n";
4773 
4774   print_indent(indent);
4775   outs() << "    protocol_name "
4776          << format("0x%08" PRIx32, protocol.protocol_name);
4777   if (info->verbose) {
4778     name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
4779     if (name != nullptr)
4780       outs() << format(" %.*s", left, name);
4781     else
4782       outs() << " (not in an __OBJC section)";
4783   }
4784   outs() << "\n";
4785 
4786   print_indent(indent);
4787   outs() << "    protocol_list "
4788          << format("0x%08" PRIx32, protocol.protocol_list);
4789   if (print_protocol_list(protocol.protocol_list, indent + 4, info))
4790     outs() << " (not in an __OBJC section)\n";
4791 
4792   print_indent(indent);
4793   outs() << " instance_methods "
4794          << format("0x%08" PRIx32, protocol.instance_methods);
4795   if (print_method_description_list(protocol.instance_methods, indent, info))
4796     outs() << " (not in an __OBJC section)\n";
4797 
4798   print_indent(indent);
4799   outs() << "    class_methods "
4800          << format("0x%08" PRIx32, protocol.class_methods);
4801   if (print_method_description_list(protocol.class_methods, indent, info))
4802     outs() << " (not in an __OBJC section)\n";
4803 
4804   return false;
4805 }
4806 
4807 static bool print_protocol_list(uint32_t p, uint32_t indent,
4808                                 struct DisassembleInfo *info) {
4809   uint32_t offset, left, l;
4810   SectionRef S;
4811   struct objc_protocol_list_t protocol_list;
4812   const char *r, *list;
4813   int32_t i;
4814 
4815   r = get_pointer_32(p, offset, left, S, info, true);
4816   if (r == nullptr)
4817     return true;
4818 
4819   outs() << "\n";
4820   if (left > sizeof(struct objc_protocol_list_t)) {
4821     memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
4822   } else {
4823     outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
4824     memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
4825     memcpy(&protocol_list, r, left);
4826   }
4827   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4828     swapStruct(protocol_list);
4829 
4830   print_indent(indent);
4831   outs() << "         next " << format("0x%08" PRIx32, protocol_list.next)
4832          << "\n";
4833   print_indent(indent);
4834   outs() << "        count " << protocol_list.count << "\n";
4835 
4836   list = r + sizeof(struct objc_protocol_list_t);
4837   for (i = 0; i < protocol_list.count; i++) {
4838     if ((i + 1) * sizeof(uint32_t) > left) {
4839       outs() << "\t\t remaining list entries extend past the of the section\n";
4840       break;
4841     }
4842     memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
4843     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4844       sys::swapByteOrder(l);
4845 
4846     print_indent(indent);
4847     outs() << "      list[" << i << "] " << format("0x%08" PRIx32, l);
4848     if (print_protocol(l, indent, info))
4849       outs() << "(not in an __OBJC section)\n";
4850   }
4851   return false;
4852 }
4853 
4854 static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
4855   struct ivar_list64_t il;
4856   struct ivar64_t i;
4857   const char *r;
4858   uint32_t offset, xoffset, left, j;
4859   SectionRef S, xS;
4860   const char *name, *sym_name, *ivar_offset_p;
4861   uint64_t ivar_offset, n_value;
4862 
4863   r = get_pointer_64(p, offset, left, S, info);
4864   if (r == nullptr)
4865     return;
4866   memset(&il, '\0', sizeof(struct ivar_list64_t));
4867   if (left < sizeof(struct ivar_list64_t)) {
4868     memcpy(&il, r, left);
4869     outs() << "   (ivar_list_t entends past the end of the section)\n";
4870   } else
4871     memcpy(&il, r, sizeof(struct ivar_list64_t));
4872   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4873     swapStruct(il);
4874   outs() << "                    entsize " << il.entsize << "\n";
4875   outs() << "                      count " << il.count << "\n";
4876 
4877   p += sizeof(struct ivar_list64_t);
4878   offset += sizeof(struct ivar_list64_t);
4879   for (j = 0; j < il.count; j++) {
4880     r = get_pointer_64(p, offset, left, S, info);
4881     if (r == nullptr)
4882       return;
4883     memset(&i, '\0', sizeof(struct ivar64_t));
4884     if (left < sizeof(struct ivar64_t)) {
4885       memcpy(&i, r, left);
4886       outs() << "   (ivar_t entends past the end of the section)\n";
4887     } else
4888       memcpy(&i, r, sizeof(struct ivar64_t));
4889     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4890       swapStruct(i);
4891 
4892     outs() << "\t\t\t   offset ";
4893     sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
4894                              info, n_value, i.offset);
4895     if (n_value != 0) {
4896       if (info->verbose && sym_name != nullptr)
4897         outs() << sym_name;
4898       else
4899         outs() << format("0x%" PRIx64, n_value);
4900       if (i.offset != 0)
4901         outs() << " + " << format("0x%" PRIx64, i.offset);
4902     } else
4903       outs() << format("0x%" PRIx64, i.offset);
4904     ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
4905     if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4906       memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4907       if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4908         sys::swapByteOrder(ivar_offset);
4909       outs() << " " << ivar_offset << "\n";
4910     } else
4911       outs() << "\n";
4912 
4913     outs() << "\t\t\t     name ";
4914     sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
4915                              n_value, i.name);
4916     if (n_value != 0) {
4917       if (info->verbose && sym_name != nullptr)
4918         outs() << sym_name;
4919       else
4920         outs() << format("0x%" PRIx64, n_value);
4921       if (i.name != 0)
4922         outs() << " + " << format("0x%" PRIx64, i.name);
4923     } else
4924       outs() << format("0x%" PRIx64, i.name);
4925     name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
4926     if (name != nullptr)
4927       outs() << format(" %.*s", left, name);
4928     outs() << "\n";
4929 
4930     outs() << "\t\t\t     type ";
4931     sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
4932                              n_value, i.name);
4933     name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
4934     if (n_value != 0) {
4935       if (info->verbose && sym_name != nullptr)
4936         outs() << sym_name;
4937       else
4938         outs() << format("0x%" PRIx64, n_value);
4939       if (i.type != 0)
4940         outs() << " + " << format("0x%" PRIx64, i.type);
4941     } else
4942       outs() << format("0x%" PRIx64, i.type);
4943     if (name != nullptr)
4944       outs() << format(" %.*s", left, name);
4945     outs() << "\n";
4946 
4947     outs() << "\t\t\talignment " << i.alignment << "\n";
4948     outs() << "\t\t\t     size " << i.size << "\n";
4949 
4950     p += sizeof(struct ivar64_t);
4951     offset += sizeof(struct ivar64_t);
4952   }
4953 }
4954 
4955 static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4956   struct ivar_list32_t il;
4957   struct ivar32_t i;
4958   const char *r;
4959   uint32_t offset, xoffset, left, j;
4960   SectionRef S, xS;
4961   const char *name, *ivar_offset_p;
4962   uint32_t ivar_offset;
4963 
4964   r = get_pointer_32(p, offset, left, S, info);
4965   if (r == nullptr)
4966     return;
4967   memset(&il, '\0', sizeof(struct ivar_list32_t));
4968   if (left < sizeof(struct ivar_list32_t)) {
4969     memcpy(&il, r, left);
4970     outs() << "   (ivar_list_t entends past the end of the section)\n";
4971   } else
4972     memcpy(&il, r, sizeof(struct ivar_list32_t));
4973   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4974     swapStruct(il);
4975   outs() << "                    entsize " << il.entsize << "\n";
4976   outs() << "                      count " << il.count << "\n";
4977 
4978   p += sizeof(struct ivar_list32_t);
4979   offset += sizeof(struct ivar_list32_t);
4980   for (j = 0; j < il.count; j++) {
4981     r = get_pointer_32(p, offset, left, S, info);
4982     if (r == nullptr)
4983       return;
4984     memset(&i, '\0', sizeof(struct ivar32_t));
4985     if (left < sizeof(struct ivar32_t)) {
4986       memcpy(&i, r, left);
4987       outs() << "   (ivar_t entends past the end of the section)\n";
4988     } else
4989       memcpy(&i, r, sizeof(struct ivar32_t));
4990     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4991       swapStruct(i);
4992 
4993     outs() << "\t\t\t   offset " << format("0x%" PRIx32, i.offset);
4994     ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4995     if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4996       memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4997       if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4998         sys::swapByteOrder(ivar_offset);
4999       outs() << " " << ivar_offset << "\n";
5000     } else
5001       outs() << "\n";
5002 
5003     outs() << "\t\t\t     name " << format("0x%" PRIx32, i.name);
5004     name = get_pointer_32(i.name, xoffset, left, xS, info);
5005     if (name != nullptr)
5006       outs() << format(" %.*s", left, name);
5007     outs() << "\n";
5008 
5009     outs() << "\t\t\t     type " << format("0x%" PRIx32, i.type);
5010     name = get_pointer_32(i.type, xoffset, left, xS, info);
5011     if (name != nullptr)
5012       outs() << format(" %.*s", left, name);
5013     outs() << "\n";
5014 
5015     outs() << "\t\t\talignment " << i.alignment << "\n";
5016     outs() << "\t\t\t     size " << i.size << "\n";
5017 
5018     p += sizeof(struct ivar32_t);
5019     offset += sizeof(struct ivar32_t);
5020   }
5021 }
5022 
5023 static void print_objc_property_list64(uint64_t p,
5024                                        struct DisassembleInfo *info) {
5025   struct objc_property_list64 opl;
5026   struct objc_property64 op;
5027   const char *r;
5028   uint32_t offset, xoffset, left, j;
5029   SectionRef S, xS;
5030   const char *name, *sym_name;
5031   uint64_t n_value;
5032 
5033   r = get_pointer_64(p, offset, left, S, info);
5034   if (r == nullptr)
5035     return;
5036   memset(&opl, '\0', sizeof(struct objc_property_list64));
5037   if (left < sizeof(struct objc_property_list64)) {
5038     memcpy(&opl, r, left);
5039     outs() << "   (objc_property_list entends past the end of the section)\n";
5040   } else
5041     memcpy(&opl, r, sizeof(struct objc_property_list64));
5042   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5043     swapStruct(opl);
5044   outs() << "                    entsize " << opl.entsize << "\n";
5045   outs() << "                      count " << opl.count << "\n";
5046 
5047   p += sizeof(struct objc_property_list64);
5048   offset += sizeof(struct objc_property_list64);
5049   for (j = 0; j < opl.count; j++) {
5050     r = get_pointer_64(p, offset, left, S, info);
5051     if (r == nullptr)
5052       return;
5053     memset(&op, '\0', sizeof(struct objc_property64));
5054     if (left < sizeof(struct objc_property64)) {
5055       memcpy(&op, r, left);
5056       outs() << "   (objc_property entends past the end of the section)\n";
5057     } else
5058       memcpy(&op, r, sizeof(struct objc_property64));
5059     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5060       swapStruct(op);
5061 
5062     outs() << "\t\t\t     name ";
5063     sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
5064                              info, n_value, op.name);
5065     if (n_value != 0) {
5066       if (info->verbose && sym_name != nullptr)
5067         outs() << sym_name;
5068       else
5069         outs() << format("0x%" PRIx64, n_value);
5070       if (op.name != 0)
5071         outs() << " + " << format("0x%" PRIx64, op.name);
5072     } else
5073       outs() << format("0x%" PRIx64, op.name);
5074     name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
5075     if (name != nullptr)
5076       outs() << format(" %.*s", left, name);
5077     outs() << "\n";
5078 
5079     outs() << "\t\t\tattributes ";
5080     sym_name =
5081         get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
5082                       info, n_value, op.attributes);
5083     if (n_value != 0) {
5084       if (info->verbose && sym_name != nullptr)
5085         outs() << sym_name;
5086       else
5087         outs() << format("0x%" PRIx64, n_value);
5088       if (op.attributes != 0)
5089         outs() << " + " << format("0x%" PRIx64, op.attributes);
5090     } else
5091       outs() << format("0x%" PRIx64, op.attributes);
5092     name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
5093     if (name != nullptr)
5094       outs() << format(" %.*s", left, name);
5095     outs() << "\n";
5096 
5097     p += sizeof(struct objc_property64);
5098     offset += sizeof(struct objc_property64);
5099   }
5100 }
5101 
5102 static void print_objc_property_list32(uint32_t p,
5103                                        struct DisassembleInfo *info) {
5104   struct objc_property_list32 opl;
5105   struct objc_property32 op;
5106   const char *r;
5107   uint32_t offset, xoffset, left, j;
5108   SectionRef S, xS;
5109   const char *name;
5110 
5111   r = get_pointer_32(p, offset, left, S, info);
5112   if (r == nullptr)
5113     return;
5114   memset(&opl, '\0', sizeof(struct objc_property_list32));
5115   if (left < sizeof(struct objc_property_list32)) {
5116     memcpy(&opl, r, left);
5117     outs() << "   (objc_property_list entends past the end of the section)\n";
5118   } else
5119     memcpy(&opl, r, sizeof(struct objc_property_list32));
5120   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5121     swapStruct(opl);
5122   outs() << "                    entsize " << opl.entsize << "\n";
5123   outs() << "                      count " << opl.count << "\n";
5124 
5125   p += sizeof(struct objc_property_list32);
5126   offset += sizeof(struct objc_property_list32);
5127   for (j = 0; j < opl.count; j++) {
5128     r = get_pointer_32(p, offset, left, S, info);
5129     if (r == nullptr)
5130       return;
5131     memset(&op, '\0', sizeof(struct objc_property32));
5132     if (left < sizeof(struct objc_property32)) {
5133       memcpy(&op, r, left);
5134       outs() << "   (objc_property entends past the end of the section)\n";
5135     } else
5136       memcpy(&op, r, sizeof(struct objc_property32));
5137     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5138       swapStruct(op);
5139 
5140     outs() << "\t\t\t     name " << format("0x%" PRIx32, op.name);
5141     name = get_pointer_32(op.name, xoffset, left, xS, info);
5142     if (name != nullptr)
5143       outs() << format(" %.*s", left, name);
5144     outs() << "\n";
5145 
5146     outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
5147     name = get_pointer_32(op.attributes, xoffset, left, xS, info);
5148     if (name != nullptr)
5149       outs() << format(" %.*s", left, name);
5150     outs() << "\n";
5151 
5152     p += sizeof(struct objc_property32);
5153     offset += sizeof(struct objc_property32);
5154   }
5155 }
5156 
5157 static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
5158                                bool &is_meta_class) {
5159   struct class_ro64_t cro;
5160   const char *r;
5161   uint32_t offset, xoffset, left;
5162   SectionRef S, xS;
5163   const char *name, *sym_name;
5164   uint64_t n_value;
5165 
5166   r = get_pointer_64(p, offset, left, S, info);
5167   if (r == nullptr || left < sizeof(struct class_ro64_t))
5168     return false;
5169   memcpy(&cro, r, sizeof(struct class_ro64_t));
5170   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5171     swapStruct(cro);
5172   outs() << "                    flags " << format("0x%" PRIx32, cro.flags);
5173   if (cro.flags & RO_META)
5174     outs() << " RO_META";
5175   if (cro.flags & RO_ROOT)
5176     outs() << " RO_ROOT";
5177   if (cro.flags & RO_HAS_CXX_STRUCTORS)
5178     outs() << " RO_HAS_CXX_STRUCTORS";
5179   outs() << "\n";
5180   outs() << "            instanceStart " << cro.instanceStart << "\n";
5181   outs() << "             instanceSize " << cro.instanceSize << "\n";
5182   outs() << "                 reserved " << format("0x%" PRIx32, cro.reserved)
5183          << "\n";
5184   outs() << "               ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
5185          << "\n";
5186   print_layout_map64(cro.ivarLayout, info);
5187 
5188   outs() << "                     name ";
5189   sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
5190                            info, n_value, cro.name);
5191   if (n_value != 0) {
5192     if (info->verbose && sym_name != nullptr)
5193       outs() << sym_name;
5194     else
5195       outs() << format("0x%" PRIx64, n_value);
5196     if (cro.name != 0)
5197       outs() << " + " << format("0x%" PRIx64, cro.name);
5198   } else
5199     outs() << format("0x%" PRIx64, cro.name);
5200   name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
5201   if (name != nullptr)
5202     outs() << format(" %.*s", left, name);
5203   outs() << "\n";
5204 
5205   outs() << "              baseMethods ";
5206   sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
5207                            S, info, n_value, cro.baseMethods);
5208   if (n_value != 0) {
5209     if (info->verbose && sym_name != nullptr)
5210       outs() << sym_name;
5211     else
5212       outs() << format("0x%" PRIx64, n_value);
5213     if (cro.baseMethods != 0)
5214       outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
5215   } else
5216     outs() << format("0x%" PRIx64, cro.baseMethods);
5217   outs() << " (struct method_list_t *)\n";
5218   if (cro.baseMethods + n_value != 0)
5219     print_method_list64_t(cro.baseMethods + n_value, info, "");
5220 
5221   outs() << "            baseProtocols ";
5222   sym_name =
5223       get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
5224                     info, n_value, cro.baseProtocols);
5225   if (n_value != 0) {
5226     if (info->verbose && sym_name != nullptr)
5227       outs() << sym_name;
5228     else
5229       outs() << format("0x%" PRIx64, n_value);
5230     if (cro.baseProtocols != 0)
5231       outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
5232   } else
5233     outs() << format("0x%" PRIx64, cro.baseProtocols);
5234   outs() << "\n";
5235   if (cro.baseProtocols + n_value != 0)
5236     print_protocol_list64_t(cro.baseProtocols + n_value, info);
5237 
5238   outs() << "                    ivars ";
5239   sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
5240                            info, n_value, cro.ivars);
5241   if (n_value != 0) {
5242     if (info->verbose && sym_name != nullptr)
5243       outs() << sym_name;
5244     else
5245       outs() << format("0x%" PRIx64, n_value);
5246     if (cro.ivars != 0)
5247       outs() << " + " << format("0x%" PRIx64, cro.ivars);
5248   } else
5249     outs() << format("0x%" PRIx64, cro.ivars);
5250   outs() << "\n";
5251   if (cro.ivars + n_value != 0)
5252     print_ivar_list64_t(cro.ivars + n_value, info);
5253 
5254   outs() << "           weakIvarLayout ";
5255   sym_name =
5256       get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
5257                     info, n_value, cro.weakIvarLayout);
5258   if (n_value != 0) {
5259     if (info->verbose && sym_name != nullptr)
5260       outs() << sym_name;
5261     else
5262       outs() << format("0x%" PRIx64, n_value);
5263     if (cro.weakIvarLayout != 0)
5264       outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
5265   } else
5266     outs() << format("0x%" PRIx64, cro.weakIvarLayout);
5267   outs() << "\n";
5268   print_layout_map64(cro.weakIvarLayout + n_value, info);
5269 
5270   outs() << "           baseProperties ";
5271   sym_name =
5272       get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
5273                     info, n_value, cro.baseProperties);
5274   if (n_value != 0) {
5275     if (info->verbose && sym_name != nullptr)
5276       outs() << sym_name;
5277     else
5278       outs() << format("0x%" PRIx64, n_value);
5279     if (cro.baseProperties != 0)
5280       outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
5281   } else
5282     outs() << format("0x%" PRIx64, cro.baseProperties);
5283   outs() << "\n";
5284   if (cro.baseProperties + n_value != 0)
5285     print_objc_property_list64(cro.baseProperties + n_value, info);
5286 
5287   is_meta_class = (cro.flags & RO_META) != 0;
5288   return true;
5289 }
5290 
5291 static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
5292                                bool &is_meta_class) {
5293   struct class_ro32_t cro;
5294   const char *r;
5295   uint32_t offset, xoffset, left;
5296   SectionRef S, xS;
5297   const char *name;
5298 
5299   r = get_pointer_32(p, offset, left, S, info);
5300   if (r == nullptr)
5301     return false;
5302   memset(&cro, '\0', sizeof(struct class_ro32_t));
5303   if (left < sizeof(struct class_ro32_t)) {
5304     memcpy(&cro, r, left);
5305     outs() << "   (class_ro_t entends past the end of the section)\n";
5306   } else
5307     memcpy(&cro, r, sizeof(struct class_ro32_t));
5308   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5309     swapStruct(cro);
5310   outs() << "                    flags " << format("0x%" PRIx32, cro.flags);
5311   if (cro.flags & RO_META)
5312     outs() << " RO_META";
5313   if (cro.flags & RO_ROOT)
5314     outs() << " RO_ROOT";
5315   if (cro.flags & RO_HAS_CXX_STRUCTORS)
5316     outs() << " RO_HAS_CXX_STRUCTORS";
5317   outs() << "\n";
5318   outs() << "            instanceStart " << cro.instanceStart << "\n";
5319   outs() << "             instanceSize " << cro.instanceSize << "\n";
5320   outs() << "               ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
5321          << "\n";
5322   print_layout_map32(cro.ivarLayout, info);
5323 
5324   outs() << "                     name " << format("0x%" PRIx32, cro.name);
5325   name = get_pointer_32(cro.name, xoffset, left, xS, info);
5326   if (name != nullptr)
5327     outs() << format(" %.*s", left, name);
5328   outs() << "\n";
5329 
5330   outs() << "              baseMethods "
5331          << format("0x%" PRIx32, cro.baseMethods)
5332          << " (struct method_list_t *)\n";
5333   if (cro.baseMethods != 0)
5334     print_method_list32_t(cro.baseMethods, info, "");
5335 
5336   outs() << "            baseProtocols "
5337          << format("0x%" PRIx32, cro.baseProtocols) << "\n";
5338   if (cro.baseProtocols != 0)
5339     print_protocol_list32_t(cro.baseProtocols, info);
5340   outs() << "                    ivars " << format("0x%" PRIx32, cro.ivars)
5341          << "\n";
5342   if (cro.ivars != 0)
5343     print_ivar_list32_t(cro.ivars, info);
5344   outs() << "           weakIvarLayout "
5345          << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
5346   print_layout_map32(cro.weakIvarLayout, info);
5347   outs() << "           baseProperties "
5348          << format("0x%" PRIx32, cro.baseProperties) << "\n";
5349   if (cro.baseProperties != 0)
5350     print_objc_property_list32(cro.baseProperties, info);
5351   is_meta_class = (cro.flags & RO_META) != 0;
5352   return true;
5353 }
5354 
5355 static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
5356   struct class64_t c;
5357   const char *r;
5358   uint32_t offset, left;
5359   SectionRef S;
5360   const char *name;
5361   uint64_t isa_n_value, n_value;
5362 
5363   r = get_pointer_64(p, offset, left, S, info);
5364   if (r == nullptr || left < sizeof(struct class64_t))
5365     return;
5366   memcpy(&c, r, sizeof(struct class64_t));
5367   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5368     swapStruct(c);
5369 
5370   outs() << "           isa " << format("0x%" PRIx64, c.isa);
5371   name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
5372                        isa_n_value, c.isa);
5373   if (name != nullptr)
5374     outs() << " " << name;
5375   outs() << "\n";
5376 
5377   outs() << "    superclass " << format("0x%" PRIx64, c.superclass);
5378   name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
5379                        n_value, c.superclass);
5380   if (name != nullptr)
5381     outs() << " " << name;
5382   else {
5383     name = get_dyld_bind_info_symbolname(S.getAddress() +
5384              offset + offsetof(struct class64_t, superclass), info);
5385     if (name != nullptr)
5386       outs() << " " << name;
5387   }
5388   outs() << "\n";
5389 
5390   outs() << "         cache " << format("0x%" PRIx64, c.cache);
5391   name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
5392                        n_value, c.cache);
5393   if (name != nullptr)
5394     outs() << " " << name;
5395   outs() << "\n";
5396 
5397   outs() << "        vtable " << format("0x%" PRIx64, c.vtable);
5398   name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
5399                        n_value, c.vtable);
5400   if (name != nullptr)
5401     outs() << " " << name;
5402   outs() << "\n";
5403 
5404   name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
5405                        n_value, c.data);
5406   outs() << "          data ";
5407   if (n_value != 0) {
5408     if (info->verbose && name != nullptr)
5409       outs() << name;
5410     else
5411       outs() << format("0x%" PRIx64, n_value);
5412     if (c.data != 0)
5413       outs() << " + " << format("0x%" PRIx64, c.data);
5414   } else
5415     outs() << format("0x%" PRIx64, c.data);
5416   outs() << " (struct class_ro_t *)";
5417 
5418   // This is a Swift class if some of the low bits of the pointer are set.
5419   if ((c.data + n_value) & 0x7)
5420     outs() << " Swift class";
5421   outs() << "\n";
5422   bool is_meta_class;
5423   if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
5424     return;
5425 
5426   if (!is_meta_class &&
5427       c.isa + isa_n_value != p &&
5428       c.isa + isa_n_value != 0 &&
5429       info->depth < 100) {
5430       info->depth++;
5431       outs() << "Meta Class\n";
5432       print_class64_t(c.isa + isa_n_value, info);
5433   }
5434 }
5435 
5436 static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
5437   struct class32_t c;
5438   const char *r;
5439   uint32_t offset, left;
5440   SectionRef S;
5441   const char *name;
5442 
5443   r = get_pointer_32(p, offset, left, S, info);
5444   if (r == nullptr)
5445     return;
5446   memset(&c, '\0', sizeof(struct class32_t));
5447   if (left < sizeof(struct class32_t)) {
5448     memcpy(&c, r, left);
5449     outs() << "   (class_t entends past the end of the section)\n";
5450   } else
5451     memcpy(&c, r, sizeof(struct class32_t));
5452   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5453     swapStruct(c);
5454 
5455   outs() << "           isa " << format("0x%" PRIx32, c.isa);
5456   name =
5457       get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
5458   if (name != nullptr)
5459     outs() << " " << name;
5460   outs() << "\n";
5461 
5462   outs() << "    superclass " << format("0x%" PRIx32, c.superclass);
5463   name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
5464                        c.superclass);
5465   if (name != nullptr)
5466     outs() << " " << name;
5467   outs() << "\n";
5468 
5469   outs() << "         cache " << format("0x%" PRIx32, c.cache);
5470   name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
5471                        c.cache);
5472   if (name != nullptr)
5473     outs() << " " << name;
5474   outs() << "\n";
5475 
5476   outs() << "        vtable " << format("0x%" PRIx32, c.vtable);
5477   name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
5478                        c.vtable);
5479   if (name != nullptr)
5480     outs() << " " << name;
5481   outs() << "\n";
5482 
5483   name =
5484       get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
5485   outs() << "          data " << format("0x%" PRIx32, c.data)
5486          << " (struct class_ro_t *)";
5487 
5488   // This is a Swift class if some of the low bits of the pointer are set.
5489   if (c.data & 0x3)
5490     outs() << " Swift class";
5491   outs() << "\n";
5492   bool is_meta_class;
5493   if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
5494     return;
5495 
5496   if (!is_meta_class) {
5497     outs() << "Meta Class\n";
5498     print_class32_t(c.isa, info);
5499   }
5500 }
5501 
5502 static void print_objc_class_t(struct objc_class_t *objc_class,
5503                                struct DisassembleInfo *info) {
5504   uint32_t offset, left, xleft;
5505   const char *name, *p, *ivar_list;
5506   SectionRef S;
5507   int32_t i;
5508   struct objc_ivar_list_t objc_ivar_list;
5509   struct objc_ivar_t ivar;
5510 
5511   outs() << "\t\t      isa " << format("0x%08" PRIx32, objc_class->isa);
5512   if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
5513     name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
5514     if (name != nullptr)
5515       outs() << format(" %.*s", left, name);
5516     else
5517       outs() << " (not in an __OBJC section)";
5518   }
5519   outs() << "\n";
5520 
5521   outs() << "\t      super_class "
5522          << format("0x%08" PRIx32, objc_class->super_class);
5523   if (info->verbose) {
5524     name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
5525     if (name != nullptr)
5526       outs() << format(" %.*s", left, name);
5527     else
5528       outs() << " (not in an __OBJC section)";
5529   }
5530   outs() << "\n";
5531 
5532   outs() << "\t\t     name " << format("0x%08" PRIx32, objc_class->name);
5533   if (info->verbose) {
5534     name = get_pointer_32(objc_class->name, offset, left, S, info, true);
5535     if (name != nullptr)
5536       outs() << format(" %.*s", left, name);
5537     else
5538       outs() << " (not in an __OBJC section)";
5539   }
5540   outs() << "\n";
5541 
5542   outs() << "\t\t  version " << format("0x%08" PRIx32, objc_class->version)
5543          << "\n";
5544 
5545   outs() << "\t\t     info " << format("0x%08" PRIx32, objc_class->info);
5546   if (info->verbose) {
5547     if (CLS_GETINFO(objc_class, CLS_CLASS))
5548       outs() << " CLS_CLASS";
5549     else if (CLS_GETINFO(objc_class, CLS_META))
5550       outs() << " CLS_META";
5551   }
5552   outs() << "\n";
5553 
5554   outs() << "\t    instance_size "
5555          << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
5556 
5557   p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
5558   outs() << "\t\t    ivars " << format("0x%08" PRIx32, objc_class->ivars);
5559   if (p != nullptr) {
5560     if (left > sizeof(struct objc_ivar_list_t)) {
5561       outs() << "\n";
5562       memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
5563     } else {
5564       outs() << " (entends past the end of the section)\n";
5565       memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
5566       memcpy(&objc_ivar_list, p, left);
5567     }
5568     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5569       swapStruct(objc_ivar_list);
5570     outs() << "\t\t       ivar_count " << objc_ivar_list.ivar_count << "\n";
5571     ivar_list = p + sizeof(struct objc_ivar_list_t);
5572     for (i = 0; i < objc_ivar_list.ivar_count; i++) {
5573       if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
5574         outs() << "\t\t remaining ivar's extend past the of the section\n";
5575         break;
5576       }
5577       memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
5578              sizeof(struct objc_ivar_t));
5579       if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5580         swapStruct(ivar);
5581 
5582       outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
5583       if (info->verbose) {
5584         name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
5585         if (name != nullptr)
5586           outs() << format(" %.*s", xleft, name);
5587         else
5588           outs() << " (not in an __OBJC section)";
5589       }
5590       outs() << "\n";
5591 
5592       outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
5593       if (info->verbose) {
5594         name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
5595         if (name != nullptr)
5596           outs() << format(" %.*s", xleft, name);
5597         else
5598           outs() << " (not in an __OBJC section)";
5599       }
5600       outs() << "\n";
5601 
5602       outs() << "\t\t      ivar_offset "
5603              << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
5604     }
5605   } else {
5606     outs() << " (not in an __OBJC section)\n";
5607   }
5608 
5609   outs() << "\t\t  methods " << format("0x%08" PRIx32, objc_class->methodLists);
5610   if (print_method_list(objc_class->methodLists, info))
5611     outs() << " (not in an __OBJC section)\n";
5612 
5613   outs() << "\t\t    cache " << format("0x%08" PRIx32, objc_class->cache)
5614          << "\n";
5615 
5616   outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
5617   if (print_protocol_list(objc_class->protocols, 16, info))
5618     outs() << " (not in an __OBJC section)\n";
5619 }
5620 
5621 static void print_objc_objc_category_t(struct objc_category_t *objc_category,
5622                                        struct DisassembleInfo *info) {
5623   uint32_t offset, left;
5624   const char *name;
5625   SectionRef S;
5626 
5627   outs() << "\t       category name "
5628          << format("0x%08" PRIx32, objc_category->category_name);
5629   if (info->verbose) {
5630     name = get_pointer_32(objc_category->category_name, offset, left, S, info,
5631                           true);
5632     if (name != nullptr)
5633       outs() << format(" %.*s", left, name);
5634     else
5635       outs() << " (not in an __OBJC section)";
5636   }
5637   outs() << "\n";
5638 
5639   outs() << "\t\t  class name "
5640          << format("0x%08" PRIx32, objc_category->class_name);
5641   if (info->verbose) {
5642     name =
5643         get_pointer_32(objc_category->class_name, offset, left, S, info, true);
5644     if (name != nullptr)
5645       outs() << format(" %.*s", left, name);
5646     else
5647       outs() << " (not in an __OBJC section)";
5648   }
5649   outs() << "\n";
5650 
5651   outs() << "\t    instance methods "
5652          << format("0x%08" PRIx32, objc_category->instance_methods);
5653   if (print_method_list(objc_category->instance_methods, info))
5654     outs() << " (not in an __OBJC section)\n";
5655 
5656   outs() << "\t       class methods "
5657          << format("0x%08" PRIx32, objc_category->class_methods);
5658   if (print_method_list(objc_category->class_methods, info))
5659     outs() << " (not in an __OBJC section)\n";
5660 }
5661 
5662 static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
5663   struct category64_t c;
5664   const char *r;
5665   uint32_t offset, xoffset, left;
5666   SectionRef S, xS;
5667   const char *name, *sym_name;
5668   uint64_t n_value;
5669 
5670   r = get_pointer_64(p, offset, left, S, info);
5671   if (r == nullptr)
5672     return;
5673   memset(&c, '\0', sizeof(struct category64_t));
5674   if (left < sizeof(struct category64_t)) {
5675     memcpy(&c, r, left);
5676     outs() << "   (category_t entends past the end of the section)\n";
5677   } else
5678     memcpy(&c, r, sizeof(struct category64_t));
5679   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5680     swapStruct(c);
5681 
5682   outs() << "              name ";
5683   sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
5684                            info, n_value, c.name);
5685   if (n_value != 0) {
5686     if (info->verbose && sym_name != nullptr)
5687       outs() << sym_name;
5688     else
5689       outs() << format("0x%" PRIx64, n_value);
5690     if (c.name != 0)
5691       outs() << " + " << format("0x%" PRIx64, c.name);
5692   } else
5693     outs() << format("0x%" PRIx64, c.name);
5694   name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
5695   if (name != nullptr)
5696     outs() << format(" %.*s", left, name);
5697   outs() << "\n";
5698 
5699   outs() << "               cls ";
5700   sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
5701                            n_value, c.cls);
5702   if (n_value != 0) {
5703     if (info->verbose && sym_name != nullptr)
5704       outs() << sym_name;
5705     else
5706       outs() << format("0x%" PRIx64, n_value);
5707     if (c.cls != 0)
5708       outs() << " + " << format("0x%" PRIx64, c.cls);
5709   } else
5710     outs() << format("0x%" PRIx64, c.cls);
5711   outs() << "\n";
5712   if (c.cls + n_value != 0)
5713     print_class64_t(c.cls + n_value, info);
5714 
5715   outs() << "   instanceMethods ";
5716   sym_name =
5717       get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
5718                     info, n_value, c.instanceMethods);
5719   if (n_value != 0) {
5720     if (info->verbose && sym_name != nullptr)
5721       outs() << sym_name;
5722     else
5723       outs() << format("0x%" PRIx64, n_value);
5724     if (c.instanceMethods != 0)
5725       outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
5726   } else
5727     outs() << format("0x%" PRIx64, c.instanceMethods);
5728   outs() << "\n";
5729   if (c.instanceMethods + n_value != 0)
5730     print_method_list64_t(c.instanceMethods + n_value, info, "");
5731 
5732   outs() << "      classMethods ";
5733   sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
5734                            S, info, n_value, c.classMethods);
5735   if (n_value != 0) {
5736     if (info->verbose && sym_name != nullptr)
5737       outs() << sym_name;
5738     else
5739       outs() << format("0x%" PRIx64, n_value);
5740     if (c.classMethods != 0)
5741       outs() << " + " << format("0x%" PRIx64, c.classMethods);
5742   } else
5743     outs() << format("0x%" PRIx64, c.classMethods);
5744   outs() << "\n";
5745   if (c.classMethods + n_value != 0)
5746     print_method_list64_t(c.classMethods + n_value, info, "");
5747 
5748   outs() << "         protocols ";
5749   sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
5750                            info, n_value, c.protocols);
5751   if (n_value != 0) {
5752     if (info->verbose && sym_name != nullptr)
5753       outs() << sym_name;
5754     else
5755       outs() << format("0x%" PRIx64, n_value);
5756     if (c.protocols != 0)
5757       outs() << " + " << format("0x%" PRIx64, c.protocols);
5758   } else
5759     outs() << format("0x%" PRIx64, c.protocols);
5760   outs() << "\n";
5761   if (c.protocols + n_value != 0)
5762     print_protocol_list64_t(c.protocols + n_value, info);
5763 
5764   outs() << "instanceProperties ";
5765   sym_name =
5766       get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
5767                     S, info, n_value, c.instanceProperties);
5768   if (n_value != 0) {
5769     if (info->verbose && sym_name != nullptr)
5770       outs() << sym_name;
5771     else
5772       outs() << format("0x%" PRIx64, n_value);
5773     if (c.instanceProperties != 0)
5774       outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
5775   } else
5776     outs() << format("0x%" PRIx64, c.instanceProperties);
5777   outs() << "\n";
5778   if (c.instanceProperties + n_value != 0)
5779     print_objc_property_list64(c.instanceProperties + n_value, info);
5780 }
5781 
5782 static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
5783   struct category32_t c;
5784   const char *r;
5785   uint32_t offset, left;
5786   SectionRef S, xS;
5787   const char *name;
5788 
5789   r = get_pointer_32(p, offset, left, S, info);
5790   if (r == nullptr)
5791     return;
5792   memset(&c, '\0', sizeof(struct category32_t));
5793   if (left < sizeof(struct category32_t)) {
5794     memcpy(&c, r, left);
5795     outs() << "   (category_t entends past the end of the section)\n";
5796   } else
5797     memcpy(&c, r, sizeof(struct category32_t));
5798   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5799     swapStruct(c);
5800 
5801   outs() << "              name " << format("0x%" PRIx32, c.name);
5802   name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
5803                        c.name);
5804   if (name)
5805     outs() << " " << name;
5806   outs() << "\n";
5807 
5808   outs() << "               cls " << format("0x%" PRIx32, c.cls) << "\n";
5809   if (c.cls != 0)
5810     print_class32_t(c.cls, info);
5811   outs() << "   instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
5812          << "\n";
5813   if (c.instanceMethods != 0)
5814     print_method_list32_t(c.instanceMethods, info, "");
5815   outs() << "      classMethods " << format("0x%" PRIx32, c.classMethods)
5816          << "\n";
5817   if (c.classMethods != 0)
5818     print_method_list32_t(c.classMethods, info, "");
5819   outs() << "         protocols " << format("0x%" PRIx32, c.protocols) << "\n";
5820   if (c.protocols != 0)
5821     print_protocol_list32_t(c.protocols, info);
5822   outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
5823          << "\n";
5824   if (c.instanceProperties != 0)
5825     print_objc_property_list32(c.instanceProperties, info);
5826 }
5827 
5828 static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
5829   uint32_t i, left, offset, xoffset;
5830   uint64_t p, n_value;
5831   struct message_ref64 mr;
5832   const char *name, *sym_name;
5833   const char *r;
5834   SectionRef xS;
5835 
5836   if (S == SectionRef())
5837     return;
5838 
5839   StringRef SectName;
5840   Expected<StringRef> SecNameOrErr = S.getName();
5841   if (SecNameOrErr)
5842     SectName = *SecNameOrErr;
5843   else
5844     consumeError(SecNameOrErr.takeError());
5845 
5846   DataRefImpl Ref = S.getRawDataRefImpl();
5847   StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5848   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5849   offset = 0;
5850   for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5851     p = S.getAddress() + i;
5852     r = get_pointer_64(p, offset, left, S, info);
5853     if (r == nullptr)
5854       return;
5855     memset(&mr, '\0', sizeof(struct message_ref64));
5856     if (left < sizeof(struct message_ref64)) {
5857       memcpy(&mr, r, left);
5858       outs() << "   (message_ref entends past the end of the section)\n";
5859     } else
5860       memcpy(&mr, r, sizeof(struct message_ref64));
5861     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5862       swapStruct(mr);
5863 
5864     outs() << "  imp ";
5865     name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
5866                          n_value, mr.imp);
5867     if (n_value != 0) {
5868       outs() << format("0x%" PRIx64, n_value) << " ";
5869       if (mr.imp != 0)
5870         outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
5871     } else
5872       outs() << format("0x%" PRIx64, mr.imp) << " ";
5873     if (name != nullptr)
5874       outs() << " " << name;
5875     outs() << "\n";
5876 
5877     outs() << "  sel ";
5878     sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
5879                              info, n_value, mr.sel);
5880     if (n_value != 0) {
5881       if (info->verbose && sym_name != nullptr)
5882         outs() << sym_name;
5883       else
5884         outs() << format("0x%" PRIx64, n_value);
5885       if (mr.sel != 0)
5886         outs() << " + " << format("0x%" PRIx64, mr.sel);
5887     } else
5888       outs() << format("0x%" PRIx64, mr.sel);
5889     name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
5890     if (name != nullptr)
5891       outs() << format(" %.*s", left, name);
5892     outs() << "\n";
5893 
5894     offset += sizeof(struct message_ref64);
5895   }
5896 }
5897 
5898 static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
5899   uint32_t i, left, offset, xoffset, p;
5900   struct message_ref32 mr;
5901   const char *name, *r;
5902   SectionRef xS;
5903 
5904   if (S == SectionRef())
5905     return;
5906 
5907   StringRef SectName;
5908   Expected<StringRef> SecNameOrErr = S.getName();
5909   if (SecNameOrErr)
5910     SectName = *SecNameOrErr;
5911   else
5912     consumeError(SecNameOrErr.takeError());
5913 
5914   DataRefImpl Ref = S.getRawDataRefImpl();
5915   StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5916   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5917   offset = 0;
5918   for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5919     p = S.getAddress() + i;
5920     r = get_pointer_32(p, offset, left, S, info);
5921     if (r == nullptr)
5922       return;
5923     memset(&mr, '\0', sizeof(struct message_ref32));
5924     if (left < sizeof(struct message_ref32)) {
5925       memcpy(&mr, r, left);
5926       outs() << "   (message_ref entends past the end of the section)\n";
5927     } else
5928       memcpy(&mr, r, sizeof(struct message_ref32));
5929     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5930       swapStruct(mr);
5931 
5932     outs() << "  imp " << format("0x%" PRIx32, mr.imp);
5933     name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
5934                          mr.imp);
5935     if (name != nullptr)
5936       outs() << " " << name;
5937     outs() << "\n";
5938 
5939     outs() << "  sel " << format("0x%" PRIx32, mr.sel);
5940     name = get_pointer_32(mr.sel, xoffset, left, xS, info);
5941     if (name != nullptr)
5942       outs() << " " << name;
5943     outs() << "\n";
5944 
5945     offset += sizeof(struct message_ref32);
5946   }
5947 }
5948 
5949 static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
5950   uint32_t left, offset, swift_version;
5951   uint64_t p;
5952   struct objc_image_info64 o;
5953   const char *r;
5954 
5955   if (S == SectionRef())
5956     return;
5957 
5958   StringRef SectName;
5959   Expected<StringRef> SecNameOrErr = S.getName();
5960   if (SecNameOrErr)
5961     SectName = *SecNameOrErr;
5962   else
5963     consumeError(SecNameOrErr.takeError());
5964 
5965   DataRefImpl Ref = S.getRawDataRefImpl();
5966   StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5967   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5968   p = S.getAddress();
5969   r = get_pointer_64(p, offset, left, S, info);
5970   if (r == nullptr)
5971     return;
5972   memset(&o, '\0', sizeof(struct objc_image_info64));
5973   if (left < sizeof(struct objc_image_info64)) {
5974     memcpy(&o, r, left);
5975     outs() << "   (objc_image_info entends past the end of the section)\n";
5976   } else
5977     memcpy(&o, r, sizeof(struct objc_image_info64));
5978   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5979     swapStruct(o);
5980   outs() << "  version " << o.version << "\n";
5981   outs() << "    flags " << format("0x%" PRIx32, o.flags);
5982   if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5983     outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5984   if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5985     outs() << " OBJC_IMAGE_SUPPORTS_GC";
5986   if (o.flags & OBJC_IMAGE_IS_SIMULATED)
5987     outs() << " OBJC_IMAGE_IS_SIMULATED";
5988   if (o.flags & OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES)
5989     outs() << " OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES";
5990   swift_version = (o.flags >> 8) & 0xff;
5991   if (swift_version != 0) {
5992     if (swift_version == 1)
5993       outs() << " Swift 1.0";
5994     else if (swift_version == 2)
5995       outs() << " Swift 1.1";
5996     else if(swift_version == 3)
5997       outs() << " Swift 2.0";
5998     else if(swift_version == 4)
5999       outs() << " Swift 3.0";
6000     else if(swift_version == 5)
6001       outs() << " Swift 4.0";
6002     else if(swift_version == 6)
6003       outs() << " Swift 4.1/Swift 4.2";
6004     else if(swift_version == 7)
6005       outs() << " Swift 5 or later";
6006     else
6007       outs() << " unknown future Swift version (" << swift_version << ")";
6008   }
6009   outs() << "\n";
6010 }
6011 
6012 static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
6013   uint32_t left, offset, swift_version, p;
6014   struct objc_image_info32 o;
6015   const char *r;
6016 
6017   if (S == SectionRef())
6018     return;
6019 
6020   StringRef SectName;
6021   Expected<StringRef> SecNameOrErr = S.getName();
6022   if (SecNameOrErr)
6023     SectName = *SecNameOrErr;
6024   else
6025     consumeError(SecNameOrErr.takeError());
6026 
6027   DataRefImpl Ref = S.getRawDataRefImpl();
6028   StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
6029   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
6030   p = S.getAddress();
6031   r = get_pointer_32(p, offset, left, S, info);
6032   if (r == nullptr)
6033     return;
6034   memset(&o, '\0', sizeof(struct objc_image_info32));
6035   if (left < sizeof(struct objc_image_info32)) {
6036     memcpy(&o, r, left);
6037     outs() << "   (objc_image_info entends past the end of the section)\n";
6038   } else
6039     memcpy(&o, r, sizeof(struct objc_image_info32));
6040   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
6041     swapStruct(o);
6042   outs() << "  version " << o.version << "\n";
6043   outs() << "    flags " << format("0x%" PRIx32, o.flags);
6044   if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
6045     outs() << " OBJC_IMAGE_IS_REPLACEMENT";
6046   if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
6047     outs() << " OBJC_IMAGE_SUPPORTS_GC";
6048   swift_version = (o.flags >> 8) & 0xff;
6049   if (swift_version != 0) {
6050     if (swift_version == 1)
6051       outs() << " Swift 1.0";
6052     else if (swift_version == 2)
6053       outs() << " Swift 1.1";
6054     else if(swift_version == 3)
6055       outs() << " Swift 2.0";
6056     else if(swift_version == 4)
6057       outs() << " Swift 3.0";
6058     else if(swift_version == 5)
6059       outs() << " Swift 4.0";
6060     else if(swift_version == 6)
6061       outs() << " Swift 4.1/Swift 4.2";
6062     else if(swift_version == 7)
6063       outs() << " Swift 5 or later";
6064     else
6065       outs() << " unknown future Swift version (" << swift_version << ")";
6066   }
6067   outs() << "\n";
6068 }
6069 
6070 static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
6071   uint32_t left, offset, p;
6072   struct imageInfo_t o;
6073   const char *r;
6074 
6075   StringRef SectName;
6076   Expected<StringRef> SecNameOrErr = S.getName();
6077   if (SecNameOrErr)
6078     SectName = *SecNameOrErr;
6079   else
6080     consumeError(SecNameOrErr.takeError());
6081 
6082   DataRefImpl Ref = S.getRawDataRefImpl();
6083   StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
6084   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
6085   p = S.getAddress();
6086   r = get_pointer_32(p, offset, left, S, info);
6087   if (r == nullptr)
6088     return;
6089   memset(&o, '\0', sizeof(struct imageInfo_t));
6090   if (left < sizeof(struct imageInfo_t)) {
6091     memcpy(&o, r, left);
6092     outs() << " (imageInfo entends past the end of the section)\n";
6093   } else
6094     memcpy(&o, r, sizeof(struct imageInfo_t));
6095   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
6096     swapStruct(o);
6097   outs() << "  version " << o.version << "\n";
6098   outs() << "    flags " << format("0x%" PRIx32, o.flags);
6099   if (o.flags & 0x1)
6100     outs() << "  F&C";
6101   if (o.flags & 0x2)
6102     outs() << " GC";
6103   if (o.flags & 0x4)
6104     outs() << " GC-only";
6105   else
6106     outs() << " RR";
6107   outs() << "\n";
6108 }
6109 
6110 static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
6111   SymbolAddressMap AddrMap;
6112   if (verbose)
6113     CreateSymbolAddressMap(O, &AddrMap);
6114 
6115   std::vector<SectionRef> Sections;
6116   for (const SectionRef &Section : O->sections())
6117     Sections.push_back(Section);
6118 
6119   struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
6120 
6121   SectionRef CL = get_section(O, "__OBJC2", "__class_list");
6122   if (CL == SectionRef())
6123     CL = get_section(O, "__DATA", "__objc_classlist");
6124   if (CL == SectionRef())
6125     CL = get_section(O, "__DATA_CONST", "__objc_classlist");
6126   if (CL == SectionRef())
6127     CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
6128   info.S = CL;
6129   walk_pointer_list_64("class", CL, O, &info, print_class64_t);
6130 
6131   SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
6132   if (CR == SectionRef())
6133     CR = get_section(O, "__DATA", "__objc_classrefs");
6134   if (CR == SectionRef())
6135     CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
6136   if (CR == SectionRef())
6137     CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
6138   info.S = CR;
6139   walk_pointer_list_64("class refs", CR, O, &info, nullptr);
6140 
6141   SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
6142   if (SR == SectionRef())
6143     SR = get_section(O, "__DATA", "__objc_superrefs");
6144   if (SR == SectionRef())
6145     SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
6146   if (SR == SectionRef())
6147     SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
6148   info.S = SR;
6149   walk_pointer_list_64("super refs", SR, O, &info, nullptr);
6150 
6151   SectionRef CA = get_section(O, "__OBJC2", "__category_list");
6152   if (CA == SectionRef())
6153     CA = get_section(O, "__DATA", "__objc_catlist");
6154   if (CA == SectionRef())
6155     CA = get_section(O, "__DATA_CONST", "__objc_catlist");
6156   if (CA == SectionRef())
6157     CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
6158   info.S = CA;
6159   walk_pointer_list_64("category", CA, O, &info, print_category64_t);
6160 
6161   SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
6162   if (PL == SectionRef())
6163     PL = get_section(O, "__DATA", "__objc_protolist");
6164   if (PL == SectionRef())
6165     PL = get_section(O, "__DATA_CONST", "__objc_protolist");
6166   if (PL == SectionRef())
6167     PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
6168   info.S = PL;
6169   walk_pointer_list_64("protocol", PL, O, &info, nullptr);
6170 
6171   SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
6172   if (MR == SectionRef())
6173     MR = get_section(O, "__DATA", "__objc_msgrefs");
6174   if (MR == SectionRef())
6175     MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
6176   if (MR == SectionRef())
6177     MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
6178   info.S = MR;
6179   print_message_refs64(MR, &info);
6180 
6181   SectionRef II = get_section(O, "__OBJC2", "__image_info");
6182   if (II == SectionRef())
6183     II = get_section(O, "__DATA", "__objc_imageinfo");
6184   if (II == SectionRef())
6185     II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
6186   if (II == SectionRef())
6187     II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
6188   info.S = II;
6189   print_image_info64(II, &info);
6190 }
6191 
6192 static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
6193   SymbolAddressMap AddrMap;
6194   if (verbose)
6195     CreateSymbolAddressMap(O, &AddrMap);
6196 
6197   std::vector<SectionRef> Sections;
6198   for (const SectionRef &Section : O->sections())
6199     Sections.push_back(Section);
6200 
6201   struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
6202 
6203   SectionRef CL = get_section(O, "__OBJC2", "__class_list");
6204   if (CL == SectionRef())
6205     CL = get_section(O, "__DATA", "__objc_classlist");
6206   if (CL == SectionRef())
6207     CL = get_section(O, "__DATA_CONST", "__objc_classlist");
6208   if (CL == SectionRef())
6209     CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
6210   info.S = CL;
6211   walk_pointer_list_32("class", CL, O, &info, print_class32_t);
6212 
6213   SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
6214   if (CR == SectionRef())
6215     CR = get_section(O, "__DATA", "__objc_classrefs");
6216   if (CR == SectionRef())
6217     CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
6218   if (CR == SectionRef())
6219     CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
6220   info.S = CR;
6221   walk_pointer_list_32("class refs", CR, O, &info, nullptr);
6222 
6223   SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
6224   if (SR == SectionRef())
6225     SR = get_section(O, "__DATA", "__objc_superrefs");
6226   if (SR == SectionRef())
6227     SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
6228   if (SR == SectionRef())
6229     SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
6230   info.S = SR;
6231   walk_pointer_list_32("super refs", SR, O, &info, nullptr);
6232 
6233   SectionRef CA = get_section(O, "__OBJC2", "__category_list");
6234   if (CA == SectionRef())
6235     CA = get_section(O, "__DATA", "__objc_catlist");
6236   if (CA == SectionRef())
6237     CA = get_section(O, "__DATA_CONST", "__objc_catlist");
6238   if (CA == SectionRef())
6239     CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
6240   info.S = CA;
6241   walk_pointer_list_32("category", CA, O, &info, print_category32_t);
6242 
6243   SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
6244   if (PL == SectionRef())
6245     PL = get_section(O, "__DATA", "__objc_protolist");
6246   if (PL == SectionRef())
6247     PL = get_section(O, "__DATA_CONST", "__objc_protolist");
6248   if (PL == SectionRef())
6249     PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
6250   info.S = PL;
6251   walk_pointer_list_32("protocol", PL, O, &info, nullptr);
6252 
6253   SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
6254   if (MR == SectionRef())
6255     MR = get_section(O, "__DATA", "__objc_msgrefs");
6256   if (MR == SectionRef())
6257     MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
6258   if (MR == SectionRef())
6259     MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
6260   info.S = MR;
6261   print_message_refs32(MR, &info);
6262 
6263   SectionRef II = get_section(O, "__OBJC2", "__image_info");
6264   if (II == SectionRef())
6265     II = get_section(O, "__DATA", "__objc_imageinfo");
6266   if (II == SectionRef())
6267     II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
6268   if (II == SectionRef())
6269     II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
6270   info.S = II;
6271   print_image_info32(II, &info);
6272 }
6273 
6274 static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
6275   uint32_t i, j, p, offset, xoffset, left, defs_left, def;
6276   const char *r, *name, *defs;
6277   struct objc_module_t module;
6278   SectionRef S, xS;
6279   struct objc_symtab_t symtab;
6280   struct objc_class_t objc_class;
6281   struct objc_category_t objc_category;
6282 
6283   outs() << "Objective-C segment\n";
6284   S = get_section(O, "__OBJC", "__module_info");
6285   if (S == SectionRef())
6286     return false;
6287 
6288   SymbolAddressMap AddrMap;
6289   if (verbose)
6290     CreateSymbolAddressMap(O, &AddrMap);
6291 
6292   std::vector<SectionRef> Sections;
6293   for (const SectionRef &Section : O->sections())
6294     Sections.push_back(Section);
6295 
6296   struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
6297 
6298   for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
6299     p = S.getAddress() + i;
6300     r = get_pointer_32(p, offset, left, S, &info, true);
6301     if (r == nullptr)
6302       return true;
6303     memset(&module, '\0', sizeof(struct objc_module_t));
6304     if (left < sizeof(struct objc_module_t)) {
6305       memcpy(&module, r, left);
6306       outs() << "   (module extends past end of __module_info section)\n";
6307     } else
6308       memcpy(&module, r, sizeof(struct objc_module_t));
6309     if (O->isLittleEndian() != sys::IsLittleEndianHost)
6310       swapStruct(module);
6311 
6312     outs() << "Module " << format("0x%" PRIx32, p) << "\n";
6313     outs() << "    version " << module.version << "\n";
6314     outs() << "       size " << module.size << "\n";
6315     outs() << "       name ";
6316     name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
6317     if (name != nullptr)
6318       outs() << format("%.*s", left, name);
6319     else
6320       outs() << format("0x%08" PRIx32, module.name)
6321              << "(not in an __OBJC section)";
6322     outs() << "\n";
6323 
6324     r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
6325     if (module.symtab == 0 || r == nullptr) {
6326       outs() << "     symtab " << format("0x%08" PRIx32, module.symtab)
6327              << " (not in an __OBJC section)\n";
6328       continue;
6329     }
6330     outs() << "     symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
6331     memset(&symtab, '\0', sizeof(struct objc_symtab_t));
6332     defs_left = 0;
6333     defs = nullptr;
6334     if (left < sizeof(struct objc_symtab_t)) {
6335       memcpy(&symtab, r, left);
6336       outs() << "\tsymtab extends past end of an __OBJC section)\n";
6337     } else {
6338       memcpy(&symtab, r, sizeof(struct objc_symtab_t));
6339       if (left > sizeof(struct objc_symtab_t)) {
6340         defs_left = left - sizeof(struct objc_symtab_t);
6341         defs = r + sizeof(struct objc_symtab_t);
6342       }
6343     }
6344     if (O->isLittleEndian() != sys::IsLittleEndianHost)
6345       swapStruct(symtab);
6346 
6347     outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
6348     r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
6349     outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
6350     if (r == nullptr)
6351       outs() << " (not in an __OBJC section)";
6352     outs() << "\n";
6353     outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
6354     outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
6355     if (symtab.cls_def_cnt > 0)
6356       outs() << "\tClass Definitions\n";
6357     for (j = 0; j < symtab.cls_def_cnt; j++) {
6358       if ((j + 1) * sizeof(uint32_t) > defs_left) {
6359         outs() << "\t(remaining class defs entries entends past the end of the "
6360                << "section)\n";
6361         break;
6362       }
6363       memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
6364       if (O->isLittleEndian() != sys::IsLittleEndianHost)
6365         sys::swapByteOrder(def);
6366 
6367       r = get_pointer_32(def, xoffset, left, xS, &info, true);
6368       outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
6369       if (r != nullptr) {
6370         if (left > sizeof(struct objc_class_t)) {
6371           outs() << "\n";
6372           memcpy(&objc_class, r, sizeof(struct objc_class_t));
6373         } else {
6374           outs() << " (entends past the end of the section)\n";
6375           memset(&objc_class, '\0', sizeof(struct objc_class_t));
6376           memcpy(&objc_class, r, left);
6377         }
6378         if (O->isLittleEndian() != sys::IsLittleEndianHost)
6379           swapStruct(objc_class);
6380         print_objc_class_t(&objc_class, &info);
6381       } else {
6382         outs() << "(not in an __OBJC section)\n";
6383       }
6384 
6385       if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
6386         outs() << "\tMeta Class";
6387         r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
6388         if (r != nullptr) {
6389           if (left > sizeof(struct objc_class_t)) {
6390             outs() << "\n";
6391             memcpy(&objc_class, r, sizeof(struct objc_class_t));
6392           } else {
6393             outs() << " (entends past the end of the section)\n";
6394             memset(&objc_class, '\0', sizeof(struct objc_class_t));
6395             memcpy(&objc_class, r, left);
6396           }
6397           if (O->isLittleEndian() != sys::IsLittleEndianHost)
6398             swapStruct(objc_class);
6399           print_objc_class_t(&objc_class, &info);
6400         } else {
6401           outs() << "(not in an __OBJC section)\n";
6402         }
6403       }
6404     }
6405     if (symtab.cat_def_cnt > 0)
6406       outs() << "\tCategory Definitions\n";
6407     for (j = 0; j < symtab.cat_def_cnt; j++) {
6408       if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
6409         outs() << "\t(remaining category defs entries entends past the end of "
6410                << "the section)\n";
6411         break;
6412       }
6413       memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
6414              sizeof(uint32_t));
6415       if (O->isLittleEndian() != sys::IsLittleEndianHost)
6416         sys::swapByteOrder(def);
6417 
6418       r = get_pointer_32(def, xoffset, left, xS, &info, true);
6419       outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
6420              << format("0x%08" PRIx32, def);
6421       if (r != nullptr) {
6422         if (left > sizeof(struct objc_category_t)) {
6423           outs() << "\n";
6424           memcpy(&objc_category, r, sizeof(struct objc_category_t));
6425         } else {
6426           outs() << " (entends past the end of the section)\n";
6427           memset(&objc_category, '\0', sizeof(struct objc_category_t));
6428           memcpy(&objc_category, r, left);
6429         }
6430         if (O->isLittleEndian() != sys::IsLittleEndianHost)
6431           swapStruct(objc_category);
6432         print_objc_objc_category_t(&objc_category, &info);
6433       } else {
6434         outs() << "(not in an __OBJC section)\n";
6435       }
6436     }
6437   }
6438   const SectionRef II = get_section(O, "__OBJC", "__image_info");
6439   if (II != SectionRef())
6440     print_image_info(II, &info);
6441 
6442   return true;
6443 }
6444 
6445 static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
6446                                 uint32_t size, uint32_t addr) {
6447   SymbolAddressMap AddrMap;
6448   CreateSymbolAddressMap(O, &AddrMap);
6449 
6450   std::vector<SectionRef> Sections;
6451   for (const SectionRef &Section : O->sections())
6452     Sections.push_back(Section);
6453 
6454   struct DisassembleInfo info(O, &AddrMap, &Sections, true);
6455 
6456   const char *p;
6457   struct objc_protocol_t protocol;
6458   uint32_t left, paddr;
6459   for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
6460     memset(&protocol, '\0', sizeof(struct objc_protocol_t));
6461     left = size - (p - sect);
6462     if (left < sizeof(struct objc_protocol_t)) {
6463       outs() << "Protocol extends past end of __protocol section\n";
6464       memcpy(&protocol, p, left);
6465     } else
6466       memcpy(&protocol, p, sizeof(struct objc_protocol_t));
6467     if (O->isLittleEndian() != sys::IsLittleEndianHost)
6468       swapStruct(protocol);
6469     paddr = addr + (p - sect);
6470     outs() << "Protocol " << format("0x%" PRIx32, paddr);
6471     if (print_protocol(paddr, 0, &info))
6472       outs() << "(not in an __OBJC section)\n";
6473   }
6474 }
6475 
6476 #ifdef HAVE_LIBXAR
6477 inline void swapStruct(struct xar_header &xar) {
6478   sys::swapByteOrder(xar.magic);
6479   sys::swapByteOrder(xar.size);
6480   sys::swapByteOrder(xar.version);
6481   sys::swapByteOrder(xar.toc_length_compressed);
6482   sys::swapByteOrder(xar.toc_length_uncompressed);
6483   sys::swapByteOrder(xar.cksum_alg);
6484 }
6485 
6486 static void PrintModeVerbose(uint32_t mode) {
6487   switch(mode & S_IFMT){
6488   case S_IFDIR:
6489     outs() << "d";
6490     break;
6491   case S_IFCHR:
6492     outs() << "c";
6493     break;
6494   case S_IFBLK:
6495     outs() << "b";
6496     break;
6497   case S_IFREG:
6498     outs() << "-";
6499     break;
6500   case S_IFLNK:
6501     outs() << "l";
6502     break;
6503   case S_IFSOCK:
6504     outs() << "s";
6505     break;
6506   default:
6507     outs() << "?";
6508     break;
6509   }
6510 
6511   /* owner permissions */
6512   if(mode & S_IREAD)
6513     outs() << "r";
6514   else
6515     outs() << "-";
6516   if(mode & S_IWRITE)
6517     outs() << "w";
6518   else
6519     outs() << "-";
6520   if(mode & S_ISUID)
6521     outs() << "s";
6522   else if(mode & S_IEXEC)
6523     outs() << "x";
6524   else
6525     outs() << "-";
6526 
6527   /* group permissions */
6528   if(mode & (S_IREAD >> 3))
6529     outs() << "r";
6530   else
6531     outs() << "-";
6532   if(mode & (S_IWRITE >> 3))
6533     outs() << "w";
6534   else
6535     outs() << "-";
6536   if(mode & S_ISGID)
6537     outs() << "s";
6538   else if(mode & (S_IEXEC >> 3))
6539     outs() << "x";
6540   else
6541     outs() << "-";
6542 
6543   /* other permissions */
6544   if(mode & (S_IREAD >> 6))
6545     outs() << "r";
6546   else
6547     outs() << "-";
6548   if(mode & (S_IWRITE >> 6))
6549     outs() << "w";
6550   else
6551     outs() << "-";
6552   if(mode & S_ISVTX)
6553     outs() << "t";
6554   else if(mode & (S_IEXEC >> 6))
6555     outs() << "x";
6556   else
6557     outs() << "-";
6558 }
6559 
6560 static void PrintXarFilesSummary(const char *XarFilename, xar_t xar) {
6561   xar_file_t xf;
6562   const char *key, *type, *mode, *user, *group, *size, *mtime, *name, *m;
6563   char *endp;
6564   uint32_t mode_value;
6565 
6566   ScopedXarIter xi;
6567   if (!xi) {
6568     WithColor::error(errs(), "llvm-objdump")
6569         << "can't obtain an xar iterator for xar archive " << XarFilename
6570         << "\n";
6571     return;
6572   }
6573 
6574   // Go through the xar's files.
6575   for (xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)) {
6576     ScopedXarIter xp;
6577     if(!xp){
6578       WithColor::error(errs(), "llvm-objdump")
6579           << "can't obtain an xar iterator for xar archive " << XarFilename
6580           << "\n";
6581       return;
6582     }
6583     type = nullptr;
6584     mode = nullptr;
6585     user = nullptr;
6586     group = nullptr;
6587     size = nullptr;
6588     mtime = nullptr;
6589     name = nullptr;
6590     for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
6591       const char *val = nullptr;
6592       xar_prop_get(xf, key, &val);
6593 #if 0 // Useful for debugging.
6594       outs() << "key: " << key << " value: " << val << "\n";
6595 #endif
6596       if(strcmp(key, "type") == 0)
6597         type = val;
6598       if(strcmp(key, "mode") == 0)
6599         mode = val;
6600       if(strcmp(key, "user") == 0)
6601         user = val;
6602       if(strcmp(key, "group") == 0)
6603         group = val;
6604       if(strcmp(key, "data/size") == 0)
6605         size = val;
6606       if(strcmp(key, "mtime") == 0)
6607         mtime = val;
6608       if(strcmp(key, "name") == 0)
6609         name = val;
6610     }
6611     if(mode != nullptr){
6612       mode_value = strtoul(mode, &endp, 8);
6613       if(*endp != '\0')
6614         outs() << "(mode: \"" << mode << "\" contains non-octal chars) ";
6615       if(strcmp(type, "file") == 0)
6616         mode_value |= S_IFREG;
6617       PrintModeVerbose(mode_value);
6618       outs() << " ";
6619     }
6620     if(user != nullptr)
6621       outs() << format("%10s/", user);
6622     if(group != nullptr)
6623       outs() << format("%-10s ", group);
6624     if(size != nullptr)
6625       outs() << format("%7s ", size);
6626     if(mtime != nullptr){
6627       for(m = mtime; *m != 'T' && *m != '\0'; m++)
6628         outs() << *m;
6629       if(*m == 'T')
6630         m++;
6631       outs() << " ";
6632       for( ; *m != 'Z' && *m != '\0'; m++)
6633         outs() << *m;
6634       outs() << " ";
6635     }
6636     if(name != nullptr)
6637       outs() << name;
6638     outs() << "\n";
6639   }
6640 }
6641 
6642 static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
6643                                 uint32_t size, bool verbose,
6644                                 bool PrintXarHeader, bool PrintXarFileHeaders,
6645                                 std::string XarMemberName) {
6646   if(size < sizeof(struct xar_header)) {
6647     outs() << "size of (__LLVM,__bundle) section too small (smaller than size "
6648               "of struct xar_header)\n";
6649     return;
6650   }
6651   struct xar_header XarHeader;
6652   memcpy(&XarHeader, sect, sizeof(struct xar_header));
6653   if (sys::IsLittleEndianHost)
6654     swapStruct(XarHeader);
6655   if (PrintXarHeader) {
6656     if (!XarMemberName.empty())
6657       outs() << "In xar member " << XarMemberName << ": ";
6658     else
6659       outs() << "For (__LLVM,__bundle) section: ";
6660     outs() << "xar header\n";
6661     if (XarHeader.magic == XAR_HEADER_MAGIC)
6662       outs() << "                  magic XAR_HEADER_MAGIC\n";
6663     else
6664       outs() << "                  magic "
6665              << format_hex(XarHeader.magic, 10, true)
6666              << " (not XAR_HEADER_MAGIC)\n";
6667     outs() << "                   size " << XarHeader.size << "\n";
6668     outs() << "                version " << XarHeader.version << "\n";
6669     outs() << "  toc_length_compressed " << XarHeader.toc_length_compressed
6670            << "\n";
6671     outs() << "toc_length_uncompressed " << XarHeader.toc_length_uncompressed
6672            << "\n";
6673     outs() << "              cksum_alg ";
6674     switch (XarHeader.cksum_alg) {
6675       case XAR_CKSUM_NONE:
6676         outs() << "XAR_CKSUM_NONE\n";
6677         break;
6678       case XAR_CKSUM_SHA1:
6679         outs() << "XAR_CKSUM_SHA1\n";
6680         break;
6681       case XAR_CKSUM_MD5:
6682         outs() << "XAR_CKSUM_MD5\n";
6683         break;
6684 #ifdef XAR_CKSUM_SHA256
6685       case XAR_CKSUM_SHA256:
6686         outs() << "XAR_CKSUM_SHA256\n";
6687         break;
6688 #endif
6689 #ifdef XAR_CKSUM_SHA512
6690       case XAR_CKSUM_SHA512:
6691         outs() << "XAR_CKSUM_SHA512\n";
6692         break;
6693 #endif
6694       default:
6695         outs() << XarHeader.cksum_alg << "\n";
6696     }
6697   }
6698 
6699   SmallString<128> XarFilename;
6700   int FD;
6701   std::error_code XarEC =
6702       sys::fs::createTemporaryFile("llvm-objdump", "xar", FD, XarFilename);
6703   if (XarEC) {
6704     WithColor::error(errs(), "llvm-objdump") << XarEC.message() << "\n";
6705     return;
6706   }
6707   ToolOutputFile XarFile(XarFilename, FD);
6708   raw_fd_ostream &XarOut = XarFile.os();
6709   StringRef XarContents(sect, size);
6710   XarOut << XarContents;
6711   XarOut.close();
6712   if (XarOut.has_error())
6713     return;
6714 
6715   ScopedXarFile xar(XarFilename.c_str(), READ);
6716   if (!xar) {
6717     WithColor::error(errs(), "llvm-objdump")
6718         << "can't create temporary xar archive " << XarFilename << "\n";
6719     return;
6720   }
6721 
6722   SmallString<128> TocFilename;
6723   std::error_code TocEC =
6724       sys::fs::createTemporaryFile("llvm-objdump", "toc", TocFilename);
6725   if (TocEC) {
6726     WithColor::error(errs(), "llvm-objdump") << TocEC.message() << "\n";
6727     return;
6728   }
6729   xar_serialize(xar, TocFilename.c_str());
6730 
6731   if (PrintXarFileHeaders) {
6732     if (!XarMemberName.empty())
6733       outs() << "In xar member " << XarMemberName << ": ";
6734     else
6735       outs() << "For (__LLVM,__bundle) section: ";
6736     outs() << "xar archive files:\n";
6737     PrintXarFilesSummary(XarFilename.c_str(), xar);
6738   }
6739 
6740   ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
6741     MemoryBuffer::getFileOrSTDIN(TocFilename.c_str());
6742   if (std::error_code EC = FileOrErr.getError()) {
6743     WithColor::error(errs(), "llvm-objdump") << EC.message() << "\n";
6744     return;
6745   }
6746   std::unique_ptr<MemoryBuffer> &Buffer = FileOrErr.get();
6747 
6748   if (!XarMemberName.empty())
6749     outs() << "In xar member " << XarMemberName << ": ";
6750   else
6751     outs() << "For (__LLVM,__bundle) section: ";
6752   outs() << "xar table of contents:\n";
6753   outs() << Buffer->getBuffer() << "\n";
6754 
6755   // TODO: Go through the xar's files.
6756   ScopedXarIter xi;
6757   if(!xi){
6758     WithColor::error(errs(), "llvm-objdump")
6759         << "can't obtain an xar iterator for xar archive "
6760         << XarFilename.c_str() << "\n";
6761     return;
6762   }
6763   for(xar_file_t xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)){
6764     const char *key;
6765     const char *member_name, *member_type, *member_size_string;
6766     size_t member_size;
6767 
6768     ScopedXarIter xp;
6769     if(!xp){
6770       WithColor::error(errs(), "llvm-objdump")
6771           << "can't obtain an xar iterator for xar archive "
6772           << XarFilename.c_str() << "\n";
6773       return;
6774     }
6775     member_name = NULL;
6776     member_type = NULL;
6777     member_size_string = NULL;
6778     for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
6779       const char *val = nullptr;
6780       xar_prop_get(xf, key, &val);
6781 #if 0 // Useful for debugging.
6782       outs() << "key: " << key << " value: " << val << "\n";
6783 #endif
6784       if (strcmp(key, "name") == 0)
6785         member_name = val;
6786       if (strcmp(key, "type") == 0)
6787         member_type = val;
6788       if (strcmp(key, "data/size") == 0)
6789         member_size_string = val;
6790     }
6791     /*
6792      * If we find a file with a name, date/size and type properties
6793      * and with the type being "file" see if that is a xar file.
6794      */
6795     if (member_name != NULL && member_type != NULL &&
6796         strcmp(member_type, "file") == 0 &&
6797         member_size_string != NULL){
6798       // Extract the file into a buffer.
6799       char *endptr;
6800       member_size = strtoul(member_size_string, &endptr, 10);
6801       if (*endptr == '\0' && member_size != 0) {
6802         char *buffer;
6803         if (xar_extract_tobuffersz(xar, xf, &buffer, &member_size) == 0) {
6804 #if 0 // Useful for debugging.
6805           outs() << "xar member: " << member_name << " extracted\n";
6806 #endif
6807           // Set the XarMemberName we want to see printed in the header.
6808           std::string OldXarMemberName;
6809           // If XarMemberName is already set this is nested. So
6810           // save the old name and create the nested name.
6811           if (!XarMemberName.empty()) {
6812             OldXarMemberName = XarMemberName;
6813             XarMemberName =
6814                 (Twine("[") + XarMemberName + "]" + member_name).str();
6815           } else {
6816             OldXarMemberName = "";
6817             XarMemberName = member_name;
6818           }
6819           // See if this is could be a xar file (nested).
6820           if (member_size >= sizeof(struct xar_header)) {
6821 #if 0 // Useful for debugging.
6822             outs() << "could be a xar file: " << member_name << "\n";
6823 #endif
6824             memcpy((char *)&XarHeader, buffer, sizeof(struct xar_header));
6825             if (sys::IsLittleEndianHost)
6826               swapStruct(XarHeader);
6827             if (XarHeader.magic == XAR_HEADER_MAGIC)
6828               DumpBitcodeSection(O, buffer, member_size, verbose,
6829                                  PrintXarHeader, PrintXarFileHeaders,
6830                                  XarMemberName);
6831           }
6832           XarMemberName = OldXarMemberName;
6833           delete buffer;
6834         }
6835       }
6836     }
6837   }
6838 }
6839 #endif // defined(HAVE_LIBXAR)
6840 
6841 static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
6842   if (O->is64Bit())
6843     printObjc2_64bit_MetaData(O, verbose);
6844   else {
6845     MachO::mach_header H;
6846     H = O->getHeader();
6847     if (H.cputype == MachO::CPU_TYPE_ARM)
6848       printObjc2_32bit_MetaData(O, verbose);
6849     else {
6850       // This is the 32-bit non-arm cputype case.  Which is normally
6851       // the first Objective-C ABI.  But it may be the case of a
6852       // binary for the iOS simulator which is the second Objective-C
6853       // ABI.  In that case printObjc1_32bit_MetaData() will determine that
6854       // and return false.
6855       if (!printObjc1_32bit_MetaData(O, verbose))
6856         printObjc2_32bit_MetaData(O, verbose);
6857     }
6858   }
6859 }
6860 
6861 // GuessLiteralPointer returns a string which for the item in the Mach-O file
6862 // for the address passed in as ReferenceValue for printing as a comment with
6863 // the instruction and also returns the corresponding type of that item
6864 // indirectly through ReferenceType.
6865 //
6866 // If ReferenceValue is an address of literal cstring then a pointer to the
6867 // cstring is returned and ReferenceType is set to
6868 // LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
6869 //
6870 // If ReferenceValue is an address of an Objective-C CFString, Selector ref or
6871 // Class ref that name is returned and the ReferenceType is set accordingly.
6872 //
6873 // Lastly, literals which are Symbol address in a literal pool are looked for
6874 // and if found the symbol name is returned and ReferenceType is set to
6875 // LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
6876 //
6877 // If there is no item in the Mach-O file for the address passed in as
6878 // ReferenceValue nullptr is returned and ReferenceType is unchanged.
6879 static const char *GuessLiteralPointer(uint64_t ReferenceValue,
6880                                        uint64_t ReferencePC,
6881                                        uint64_t *ReferenceType,
6882                                        struct DisassembleInfo *info) {
6883   // First see if there is an external relocation entry at the ReferencePC.
6884   if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
6885     uint64_t sect_addr = info->S.getAddress();
6886     uint64_t sect_offset = ReferencePC - sect_addr;
6887     bool reloc_found = false;
6888     DataRefImpl Rel;
6889     MachO::any_relocation_info RE;
6890     bool isExtern = false;
6891     SymbolRef Symbol;
6892     for (const RelocationRef &Reloc : info->S.relocations()) {
6893       uint64_t RelocOffset = Reloc.getOffset();
6894       if (RelocOffset == sect_offset) {
6895         Rel = Reloc.getRawDataRefImpl();
6896         RE = info->O->getRelocation(Rel);
6897         if (info->O->isRelocationScattered(RE))
6898           continue;
6899         isExtern = info->O->getPlainRelocationExternal(RE);
6900         if (isExtern) {
6901           symbol_iterator RelocSym = Reloc.getSymbol();
6902           Symbol = *RelocSym;
6903         }
6904         reloc_found = true;
6905         break;
6906       }
6907     }
6908     // If there is an external relocation entry for a symbol in a section
6909     // then used that symbol's value for the value of the reference.
6910     if (reloc_found && isExtern) {
6911       if (info->O->getAnyRelocationPCRel(RE)) {
6912         unsigned Type = info->O->getAnyRelocationType(RE);
6913         if (Type == MachO::X86_64_RELOC_SIGNED) {
6914           ReferenceValue = Symbol.getValue();
6915         }
6916       }
6917     }
6918   }
6919 
6920   // Look for literals such as Objective-C CFStrings refs, Selector refs,
6921   // Message refs and Class refs.
6922   bool classref, selref, msgref, cfstring;
6923   uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
6924                                                selref, msgref, cfstring);
6925   if (classref && pointer_value == 0) {
6926     // Note the ReferenceValue is a pointer into the __objc_classrefs section.
6927     // And the pointer_value in that section is typically zero as it will be
6928     // set by dyld as part of the "bind information".
6929     const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
6930     if (name != nullptr) {
6931       *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
6932       const char *class_name = strrchr(name, '$');
6933       if (class_name != nullptr && class_name[1] == '_' &&
6934           class_name[2] != '\0') {
6935         info->class_name = class_name + 2;
6936         return name;
6937       }
6938     }
6939   }
6940 
6941   if (classref) {
6942     *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
6943     const char *name =
6944         get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
6945     if (name != nullptr)
6946       info->class_name = name;
6947     else
6948       name = "bad class ref";
6949     return name;
6950   }
6951 
6952   if (cfstring) {
6953     *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
6954     const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
6955     return name;
6956   }
6957 
6958   if (selref && pointer_value == 0)
6959     pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
6960 
6961   if (pointer_value != 0)
6962     ReferenceValue = pointer_value;
6963 
6964   const char *name = GuessCstringPointer(ReferenceValue, info);
6965   if (name) {
6966     if (pointer_value != 0 && selref) {
6967       *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
6968       info->selector_name = name;
6969     } else if (pointer_value != 0 && msgref) {
6970       info->class_name = nullptr;
6971       *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
6972       info->selector_name = name;
6973     } else
6974       *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
6975     return name;
6976   }
6977 
6978   // Lastly look for an indirect symbol with this ReferenceValue which is in
6979   // a literal pool.  If found return that symbol name.
6980   name = GuessIndirectSymbol(ReferenceValue, info);
6981   if (name) {
6982     *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
6983     return name;
6984   }
6985 
6986   return nullptr;
6987 }
6988 
6989 // SymbolizerSymbolLookUp is the symbol lookup function passed when creating
6990 // the Symbolizer.  It looks up the ReferenceValue using the info passed via the
6991 // pointer to the struct DisassembleInfo that was passed when MCSymbolizer
6992 // is created and returns the symbol name that matches the ReferenceValue or
6993 // nullptr if none.  The ReferenceType is passed in for the IN type of
6994 // reference the instruction is making from the values in defined in the header
6995 // "llvm-c/Disassembler.h".  On return the ReferenceType can set to a specific
6996 // Out type and the ReferenceName will also be set which is added as a comment
6997 // to the disassembled instruction.
6998 //
6999 // If the symbol name is a C++ mangled name then the demangled name is
7000 // returned through ReferenceName and ReferenceType is set to
7001 // LLVMDisassembler_ReferenceType_DeMangled_Name .
7002 //
7003 // When this is called to get a symbol name for a branch target then the
7004 // ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
7005 // SymbolValue will be looked for in the indirect symbol table to determine if
7006 // it is an address for a symbol stub.  If so then the symbol name for that
7007 // stub is returned indirectly through ReferenceName and then ReferenceType is
7008 // set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
7009 //
7010 // When this is called with an value loaded via a PC relative load then
7011 // ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
7012 // SymbolValue is checked to be an address of literal pointer, symbol pointer,
7013 // or an Objective-C meta data reference.  If so the output ReferenceType is
7014 // set to correspond to that as well as setting the ReferenceName.
7015 static const char *SymbolizerSymbolLookUp(void *DisInfo,
7016                                           uint64_t ReferenceValue,
7017                                           uint64_t *ReferenceType,
7018                                           uint64_t ReferencePC,
7019                                           const char **ReferenceName) {
7020   struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
7021   // If no verbose symbolic information is wanted then just return nullptr.
7022   if (!info->verbose) {
7023     *ReferenceName = nullptr;
7024     *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7025     return nullptr;
7026   }
7027 
7028   const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
7029 
7030   if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
7031     *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
7032     if (*ReferenceName != nullptr) {
7033       method_reference(info, ReferenceType, ReferenceName);
7034       if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
7035         *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
7036     } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
7037       if (info->demangled_name != nullptr)
7038         free(info->demangled_name);
7039       int status;
7040       info->demangled_name =
7041           itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
7042       if (info->demangled_name != nullptr) {
7043         *ReferenceName = info->demangled_name;
7044         *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
7045       } else
7046         *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7047     } else
7048       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7049   } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
7050     *ReferenceName =
7051         GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7052     if (*ReferenceName)
7053       method_reference(info, ReferenceType, ReferenceName);
7054     else
7055       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7056     // If this is arm64 and the reference is an adrp instruction save the
7057     // instruction, passed in ReferenceValue and the address of the instruction
7058     // for use later if we see and add immediate instruction.
7059   } else if (info->O->getArch() == Triple::aarch64 &&
7060              *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
7061     info->adrp_inst = ReferenceValue;
7062     info->adrp_addr = ReferencePC;
7063     SymbolName = nullptr;
7064     *ReferenceName = nullptr;
7065     *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7066     // If this is arm64 and reference is an add immediate instruction and we
7067     // have
7068     // seen an adrp instruction just before it and the adrp's Xd register
7069     // matches
7070     // this add's Xn register reconstruct the value being referenced and look to
7071     // see if it is a literal pointer.  Note the add immediate instruction is
7072     // passed in ReferenceValue.
7073   } else if (info->O->getArch() == Triple::aarch64 &&
7074              *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
7075              ReferencePC - 4 == info->adrp_addr &&
7076              (info->adrp_inst & 0x9f000000) == 0x90000000 &&
7077              (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
7078     uint32_t addxri_inst;
7079     uint64_t adrp_imm, addxri_imm;
7080 
7081     adrp_imm =
7082         ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
7083     if (info->adrp_inst & 0x0200000)
7084       adrp_imm |= 0xfffffffffc000000LL;
7085 
7086     addxri_inst = ReferenceValue;
7087     addxri_imm = (addxri_inst >> 10) & 0xfff;
7088     if (((addxri_inst >> 22) & 0x3) == 1)
7089       addxri_imm <<= 12;
7090 
7091     ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
7092                      (adrp_imm << 12) + addxri_imm;
7093 
7094     *ReferenceName =
7095         GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7096     if (*ReferenceName == nullptr)
7097       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7098     // If this is arm64 and the reference is a load register instruction and we
7099     // have seen an adrp instruction just before it and the adrp's Xd register
7100     // matches this add's Xn register reconstruct the value being referenced and
7101     // look to see if it is a literal pointer.  Note the load register
7102     // instruction is passed in ReferenceValue.
7103   } else if (info->O->getArch() == Triple::aarch64 &&
7104              *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
7105              ReferencePC - 4 == info->adrp_addr &&
7106              (info->adrp_inst & 0x9f000000) == 0x90000000 &&
7107              (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
7108     uint32_t ldrxui_inst;
7109     uint64_t adrp_imm, ldrxui_imm;
7110 
7111     adrp_imm =
7112         ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
7113     if (info->adrp_inst & 0x0200000)
7114       adrp_imm |= 0xfffffffffc000000LL;
7115 
7116     ldrxui_inst = ReferenceValue;
7117     ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
7118 
7119     ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
7120                      (adrp_imm << 12) + (ldrxui_imm << 3);
7121 
7122     *ReferenceName =
7123         GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7124     if (*ReferenceName == nullptr)
7125       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7126   }
7127   // If this arm64 and is an load register (PC-relative) instruction the
7128   // ReferenceValue is the PC plus the immediate value.
7129   else if (info->O->getArch() == Triple::aarch64 &&
7130            (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
7131             *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
7132     *ReferenceName =
7133         GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7134     if (*ReferenceName == nullptr)
7135       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7136   } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
7137     if (info->demangled_name != nullptr)
7138       free(info->demangled_name);
7139     int status;
7140     info->demangled_name =
7141         itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
7142     if (info->demangled_name != nullptr) {
7143       *ReferenceName = info->demangled_name;
7144       *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
7145     }
7146   }
7147   else {
7148     *ReferenceName = nullptr;
7149     *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7150   }
7151 
7152   return SymbolName;
7153 }
7154 
7155 /// Emits the comments that are stored in the CommentStream.
7156 /// Each comment in the CommentStream must end with a newline.
7157 static void emitComments(raw_svector_ostream &CommentStream,
7158                          SmallString<128> &CommentsToEmit,
7159                          formatted_raw_ostream &FormattedOS,
7160                          const MCAsmInfo &MAI) {
7161   // Flush the stream before taking its content.
7162   StringRef Comments = CommentsToEmit.str();
7163   // Get the default information for printing a comment.
7164   StringRef CommentBegin = MAI.getCommentString();
7165   unsigned CommentColumn = MAI.getCommentColumn();
7166   bool IsFirst = true;
7167   while (!Comments.empty()) {
7168     if (!IsFirst)
7169       FormattedOS << '\n';
7170     // Emit a line of comments.
7171     FormattedOS.PadToColumn(CommentColumn);
7172     size_t Position = Comments.find('\n');
7173     FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
7174     // Move after the newline character.
7175     Comments = Comments.substr(Position + 1);
7176     IsFirst = false;
7177   }
7178   FormattedOS.flush();
7179 
7180   // Tell the comment stream that the vector changed underneath it.
7181   CommentsToEmit.clear();
7182 }
7183 
7184 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
7185                              StringRef DisSegName, StringRef DisSectName) {
7186   const char *McpuDefault = nullptr;
7187   const Target *ThumbTarget = nullptr;
7188   const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
7189   if (!TheTarget) {
7190     // GetTarget prints out stuff.
7191     return;
7192   }
7193   std::string MachOMCPU;
7194   if (MCPU.empty() && McpuDefault)
7195     MachOMCPU = McpuDefault;
7196   else
7197     MachOMCPU = MCPU;
7198 
7199   std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
7200   std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
7201   if (ThumbTarget)
7202     ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
7203 
7204   // Package up features to be passed to target/subtarget
7205   std::string FeaturesStr;
7206   if (!MAttrs.empty()) {
7207     SubtargetFeatures Features;
7208     for (unsigned i = 0; i != MAttrs.size(); ++i)
7209       Features.AddFeature(MAttrs[i]);
7210     FeaturesStr = Features.getString();
7211   }
7212 
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));
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));
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       ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
7346           MemoryBuffer::getFileOrSTDIN(DSYMFile);
7347       if (std::error_code EC = BufOrErr.getError()) {
7348         reportError(errorCodeToError(EC), DSYMFile);
7349         return;
7350       }
7351 
7352       // We need to keep the file alive, because we're replacing DbgObj with it.
7353       DSYMBuf = std::move(BufOrErr.get());
7354 
7355       Expected<std::unique_ptr<Binary>> BinaryOrErr =
7356       createBinary(DSYMBuf.get()->getMemBufferRef());
7357       if (!BinaryOrErr) {
7358         reportError(BinaryOrErr.takeError(), DSYMFile);
7359         return;
7360       }
7361 
7362       // We need to keep the Binary elive with the buffer
7363       DSYMBinary = std::move(BinaryOrErr.get());
7364 
7365       if (ObjectFile *O = dyn_cast<ObjectFile>(DSYMBinary.get())) {
7366         // this is a Mach-O object file, use it
7367         if (MachOObjectFile *MachDSYM = dyn_cast<MachOObjectFile>(&*O)) {
7368           DbgObj = MachDSYM;
7369         }
7370         else {
7371           WithColor::error(errs(), "llvm-objdump")
7372             << DSYMFile << " is not a Mach-O file type.\n";
7373           return;
7374         }
7375       }
7376       else if (auto UB = dyn_cast<MachOUniversalBinary>(DSYMBinary.get())){
7377         // this is a Universal Binary, find a Mach-O for this architecture
7378         uint32_t CPUType, CPUSubType;
7379         const char *ArchFlag;
7380         if (MachOOF->is64Bit()) {
7381           const MachO::mach_header_64 H_64 = MachOOF->getHeader64();
7382           CPUType = H_64.cputype;
7383           CPUSubType = H_64.cpusubtype;
7384         } else {
7385           const MachO::mach_header H = MachOOF->getHeader();
7386           CPUType = H.cputype;
7387           CPUSubType = H.cpusubtype;
7388         }
7389         Triple T = MachOObjectFile::getArchTriple(CPUType, CPUSubType, nullptr,
7390                                                   &ArchFlag);
7391         Expected<std::unique_ptr<MachOObjectFile>> MachDSYM =
7392             UB->getObjectForArch(ArchFlag);
7393         if (!MachDSYM) {
7394           reportError(MachDSYM.takeError(), DSYMFile);
7395           return;
7396         }
7397 
7398         // We need to keep the Binary elive with the buffer
7399         DbgObj = &*MachDSYM.get();
7400         DSYMBinary = std::move(*MachDSYM);
7401       }
7402       else {
7403         WithColor::error(errs(), "llvm-objdump")
7404           << DSYMFile << " is not a Mach-O or Universal file type.\n";
7405         return;
7406       }
7407     }
7408 
7409     // Setup the DIContext
7410     diContext = DWARFContext::create(*DbgObj);
7411   }
7412 
7413   if (FilterSections.empty())
7414     outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
7415 
7416   for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
7417     Expected<StringRef> SecNameOrErr = Sections[SectIdx].getName();
7418     if (!SecNameOrErr) {
7419       consumeError(SecNameOrErr.takeError());
7420       continue;
7421     }
7422     if (*SecNameOrErr != DisSectName)
7423       continue;
7424 
7425     DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
7426 
7427     StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
7428     if (SegmentName != DisSegName)
7429       continue;
7430 
7431     StringRef BytesStr =
7432         unwrapOrError(Sections[SectIdx].getContents(), Filename);
7433     ArrayRef<uint8_t> Bytes = arrayRefFromStringRef(BytesStr);
7434     uint64_t SectAddress = Sections[SectIdx].getAddress();
7435 
7436     bool symbolTableWorked = false;
7437 
7438     // Create a map of symbol addresses to symbol names for use by
7439     // the SymbolizerSymbolLookUp() routine.
7440     SymbolAddressMap AddrMap;
7441     bool DisSymNameFound = false;
7442     for (const SymbolRef &Symbol : MachOOF->symbols()) {
7443       SymbolRef::Type ST =
7444           unwrapOrError(Symbol.getType(), MachOOF->getFileName());
7445       if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
7446           ST == SymbolRef::ST_Other) {
7447         uint64_t Address = Symbol.getValue();
7448         StringRef SymName =
7449             unwrapOrError(Symbol.getName(), MachOOF->getFileName());
7450         AddrMap[Address] = SymName;
7451         if (!DisSymName.empty() && DisSymName == SymName)
7452           DisSymNameFound = true;
7453       }
7454     }
7455     if (!DisSymName.empty() && !DisSymNameFound) {
7456       outs() << "Can't find -dis-symname: " << DisSymName << "\n";
7457       return;
7458     }
7459     // Set up the block of info used by the Symbolizer call backs.
7460     SymbolizerInfo.verbose = !NoSymbolicOperands;
7461     SymbolizerInfo.O = MachOOF;
7462     SymbolizerInfo.S = Sections[SectIdx];
7463     SymbolizerInfo.AddrMap = &AddrMap;
7464     SymbolizerInfo.Sections = &Sections;
7465     // Same for the ThumbSymbolizer
7466     ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
7467     ThumbSymbolizerInfo.O = MachOOF;
7468     ThumbSymbolizerInfo.S = Sections[SectIdx];
7469     ThumbSymbolizerInfo.AddrMap = &AddrMap;
7470     ThumbSymbolizerInfo.Sections = &Sections;
7471 
7472     unsigned int Arch = MachOOF->getArch();
7473 
7474     // Skip all symbols if this is a stubs file.
7475     if (Bytes.empty())
7476       return;
7477 
7478     // If the section has symbols but no symbol at the start of the section
7479     // these are used to make sure the bytes before the first symbol are
7480     // disassembled.
7481     bool FirstSymbol = true;
7482     bool FirstSymbolAtSectionStart = true;
7483 
7484     // Disassemble symbol by symbol.
7485     for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
7486       StringRef SymName =
7487           unwrapOrError(Symbols[SymIdx].getName(), MachOOF->getFileName());
7488       SymbolRef::Type ST =
7489           unwrapOrError(Symbols[SymIdx].getType(), MachOOF->getFileName());
7490       if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
7491         continue;
7492 
7493       // Make sure the symbol is defined in this section.
7494       bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
7495       if (!containsSym) {
7496         if (!DisSymName.empty() && DisSymName == SymName) {
7497           outs() << "-dis-symname: " << DisSymName << " not in the section\n";
7498           return;
7499         }
7500         continue;
7501       }
7502       // The __mh_execute_header is special and we need to deal with that fact
7503       // this symbol is before the start of the (__TEXT,__text) section and at the
7504       // address of the start of the __TEXT segment.  This is because this symbol
7505       // is an N_SECT symbol in the (__TEXT,__text) but its address is before the
7506       // start of the section in a standard MH_EXECUTE filetype.
7507       if (!DisSymName.empty() && DisSymName == "__mh_execute_header") {
7508         outs() << "-dis-symname: __mh_execute_header not in any section\n";
7509         return;
7510       }
7511       // When this code is trying to disassemble a symbol at a time and in the
7512       // case there is only the __mh_execute_header symbol left as in a stripped
7513       // executable, we need to deal with this by ignoring this symbol so the
7514       // whole section is disassembled and this symbol is then not displayed.
7515       if (SymName == "__mh_execute_header" || SymName == "__mh_dylib_header" ||
7516           SymName == "__mh_bundle_header" || SymName == "__mh_object_header" ||
7517           SymName == "__mh_preload_header" || SymName == "__mh_dylinker_header")
7518         continue;
7519 
7520       // If we are only disassembling one symbol see if this is that symbol.
7521       if (!DisSymName.empty() && DisSymName != SymName)
7522         continue;
7523 
7524       // Start at the address of the symbol relative to the section's address.
7525       uint64_t SectSize = Sections[SectIdx].getSize();
7526       uint64_t Start = Symbols[SymIdx].getValue();
7527       uint64_t SectionAddress = Sections[SectIdx].getAddress();
7528       Start -= SectionAddress;
7529 
7530       if (Start > SectSize) {
7531         outs() << "section data ends, " << SymName
7532                << " lies outside valid range\n";
7533         return;
7534       }
7535 
7536       // Stop disassembling either at the beginning of the next symbol or at
7537       // the end of the section.
7538       bool containsNextSym = false;
7539       uint64_t NextSym = 0;
7540       uint64_t NextSymIdx = SymIdx + 1;
7541       while (Symbols.size() > NextSymIdx) {
7542         SymbolRef::Type NextSymType = unwrapOrError(
7543             Symbols[NextSymIdx].getType(), MachOOF->getFileName());
7544         if (NextSymType == SymbolRef::ST_Function) {
7545           containsNextSym =
7546               Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
7547           NextSym = Symbols[NextSymIdx].getValue();
7548           NextSym -= SectionAddress;
7549           break;
7550         }
7551         ++NextSymIdx;
7552       }
7553 
7554       uint64_t End = containsNextSym ? std::min(NextSym, SectSize) : SectSize;
7555       uint64_t Size;
7556 
7557       symbolTableWorked = true;
7558 
7559       DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
7560       bool IsThumb = MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb;
7561 
7562       // We only need the dedicated Thumb target if there's a real choice
7563       // (i.e. we're not targeting M-class) and the function is Thumb.
7564       bool UseThumbTarget = IsThumb && ThumbTarget;
7565 
7566       // If we are not specifying a symbol to start disassembly with and this
7567       // is the first symbol in the section but not at the start of the section
7568       // then move the disassembly index to the start of the section and
7569       // don't print the symbol name just yet.  This is so the bytes before the
7570       // first symbol are disassembled.
7571       uint64_t SymbolStart = Start;
7572       if (DisSymName.empty() && FirstSymbol && Start != 0) {
7573         FirstSymbolAtSectionStart = false;
7574         Start = 0;
7575       }
7576       else
7577         outs() << SymName << ":\n";
7578 
7579       DILineInfo lastLine;
7580       for (uint64_t Index = Start; Index < End; Index += Size) {
7581         MCInst Inst;
7582 
7583         // If this is the first symbol in the section and it was not at the
7584         // start of the section, see if we are at its Index now and if so print
7585         // the symbol name.
7586         if (FirstSymbol && !FirstSymbolAtSectionStart && Index == SymbolStart)
7587           outs() << SymName << ":\n";
7588 
7589         uint64_t PC = SectAddress + Index;
7590         if (!NoLeadingAddr) {
7591           if (FullLeadingAddr) {
7592             if (MachOOF->is64Bit())
7593               outs() << format("%016" PRIx64, PC);
7594             else
7595               outs() << format("%08" PRIx64, PC);
7596           } else {
7597             outs() << format("%8" PRIx64 ":", PC);
7598           }
7599         }
7600         if (!NoShowRawInsn || Arch == Triple::arm)
7601           outs() << "\t";
7602 
7603         if (DumpAndSkipDataInCode(PC, Bytes.data() + Index, Dices, Size))
7604           continue;
7605 
7606         SmallVector<char, 64> AnnotationsBytes;
7607         raw_svector_ostream Annotations(AnnotationsBytes);
7608 
7609         bool gotInst;
7610         if (UseThumbTarget)
7611           gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
7612                                                 PC, DebugOut, Annotations);
7613         else
7614           gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
7615                                            DebugOut, Annotations);
7616         if (gotInst) {
7617           if (!NoShowRawInsn || Arch == Triple::arm) {
7618             dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
7619           }
7620           formatted_raw_ostream FormattedOS(outs());
7621           StringRef AnnotationsStr = Annotations.str();
7622           if (UseThumbTarget)
7623             ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
7624           else
7625             IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
7626           emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
7627 
7628           // Print debug info.
7629           if (diContext) {
7630             DILineInfo dli = diContext->getLineInfoForAddress({PC, SectIdx});
7631             // Print valid line info if it changed.
7632             if (dli != lastLine && dli.Line != 0)
7633               outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
7634                      << dli.Column;
7635             lastLine = dli;
7636           }
7637           outs() << "\n";
7638         } else {
7639           unsigned int Arch = MachOOF->getArch();
7640           if (Arch == Triple::x86_64 || Arch == Triple::x86) {
7641             outs() << format("\t.byte 0x%02x #bad opcode\n",
7642                              *(Bytes.data() + Index) & 0xff);
7643             Size = 1; // skip exactly one illegible byte and move on.
7644           } else if (Arch == Triple::aarch64 ||
7645                      (Arch == Triple::arm && !IsThumb)) {
7646             uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7647                               (*(Bytes.data() + Index + 1) & 0xff) << 8 |
7648                               (*(Bytes.data() + Index + 2) & 0xff) << 16 |
7649                               (*(Bytes.data() + Index + 3) & 0xff) << 24;
7650             outs() << format("\t.long\t0x%08x\n", opcode);
7651             Size = 4;
7652           } else if (Arch == Triple::arm) {
7653             assert(IsThumb && "ARM mode should have been dealt with above");
7654             uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7655                               (*(Bytes.data() + Index + 1) & 0xff) << 8;
7656             outs() << format("\t.short\t0x%04x\n", opcode);
7657             Size = 2;
7658           } else{
7659             WithColor::warning(errs(), "llvm-objdump")
7660                 << "invalid instruction encoding\n";
7661             if (Size == 0)
7662               Size = 1; // skip illegible bytes
7663           }
7664         }
7665       }
7666       // Now that we are done disassembled the first symbol set the bool that
7667       // were doing this to false.
7668       FirstSymbol = false;
7669     }
7670     if (!symbolTableWorked) {
7671       // Reading the symbol table didn't work, disassemble the whole section.
7672       uint64_t SectAddress = Sections[SectIdx].getAddress();
7673       uint64_t SectSize = Sections[SectIdx].getSize();
7674       uint64_t InstSize;
7675       for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
7676         MCInst Inst;
7677 
7678         uint64_t PC = SectAddress + Index;
7679 
7680         if (DumpAndSkipDataInCode(PC, Bytes.data() + Index, Dices, InstSize))
7681           continue;
7682 
7683         SmallVector<char, 64> AnnotationsBytes;
7684         raw_svector_ostream Annotations(AnnotationsBytes);
7685         if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
7686                                    DebugOut, Annotations)) {
7687           if (!NoLeadingAddr) {
7688             if (FullLeadingAddr) {
7689               if (MachOOF->is64Bit())
7690                 outs() << format("%016" PRIx64, PC);
7691               else
7692                 outs() << format("%08" PRIx64, PC);
7693             } else {
7694               outs() << format("%8" PRIx64 ":", PC);
7695             }
7696           }
7697           if (!NoShowRawInsn || Arch == Triple::arm) {
7698             outs() << "\t";
7699             dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
7700           }
7701           StringRef AnnotationsStr = Annotations.str();
7702           IP->printInst(&Inst, outs(), AnnotationsStr, *STI);
7703           outs() << "\n";
7704         } else {
7705           unsigned int Arch = MachOOF->getArch();
7706           if (Arch == Triple::x86_64 || Arch == Triple::x86) {
7707             outs() << format("\t.byte 0x%02x #bad opcode\n",
7708                              *(Bytes.data() + Index) & 0xff);
7709             InstSize = 1; // skip exactly one illegible byte and move on.
7710           } else {
7711             WithColor::warning(errs(), "llvm-objdump")
7712                 << "invalid instruction encoding\n";
7713             if (InstSize == 0)
7714               InstSize = 1; // skip illegible bytes
7715           }
7716         }
7717       }
7718     }
7719     // The TripleName's need to be reset if we are called again for a different
7720     // archtecture.
7721     TripleName = "";
7722     ThumbTripleName = "";
7723 
7724     if (SymbolizerInfo.demangled_name != nullptr)
7725       free(SymbolizerInfo.demangled_name);
7726     if (ThumbSymbolizerInfo.demangled_name != nullptr)
7727       free(ThumbSymbolizerInfo.demangled_name);
7728   }
7729 }
7730 
7731 //===----------------------------------------------------------------------===//
7732 // __compact_unwind section dumping
7733 //===----------------------------------------------------------------------===//
7734 
7735 namespace {
7736 
7737 template <typename T>
7738 static uint64_t read(StringRef Contents, ptrdiff_t Offset) {
7739   using llvm::support::little;
7740   using llvm::support::unaligned;
7741 
7742   if (Offset + sizeof(T) > Contents.size()) {
7743     outs() << "warning: attempt to read past end of buffer\n";
7744     return T();
7745   }
7746 
7747   uint64_t Val =
7748       support::endian::read<T, little, unaligned>(Contents.data() + Offset);
7749   return Val;
7750 }
7751 
7752 template <typename T>
7753 static uint64_t readNext(StringRef Contents, ptrdiff_t &Offset) {
7754   T Val = read<T>(Contents, Offset);
7755   Offset += sizeof(T);
7756   return Val;
7757 }
7758 
7759 struct CompactUnwindEntry {
7760   uint32_t OffsetInSection;
7761 
7762   uint64_t FunctionAddr;
7763   uint32_t Length;
7764   uint32_t CompactEncoding;
7765   uint64_t PersonalityAddr;
7766   uint64_t LSDAAddr;
7767 
7768   RelocationRef FunctionReloc;
7769   RelocationRef PersonalityReloc;
7770   RelocationRef LSDAReloc;
7771 
7772   CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
7773       : OffsetInSection(Offset) {
7774     if (Is64)
7775       read<uint64_t>(Contents, Offset);
7776     else
7777       read<uint32_t>(Contents, Offset);
7778   }
7779 
7780 private:
7781   template <typename UIntPtr> void read(StringRef Contents, ptrdiff_t Offset) {
7782     FunctionAddr = readNext<UIntPtr>(Contents, Offset);
7783     Length = readNext<uint32_t>(Contents, Offset);
7784     CompactEncoding = readNext<uint32_t>(Contents, Offset);
7785     PersonalityAddr = readNext<UIntPtr>(Contents, Offset);
7786     LSDAAddr = readNext<UIntPtr>(Contents, Offset);
7787   }
7788 };
7789 }
7790 
7791 /// Given a relocation from __compact_unwind, consisting of the RelocationRef
7792 /// and data being relocated, determine the best base Name and Addend to use for
7793 /// display purposes.
7794 ///
7795 /// 1. An Extern relocation will directly reference a symbol (and the data is
7796 ///    then already an addend), so use that.
7797 /// 2. Otherwise the data is an offset in the object file's layout; try to find
7798 //     a symbol before it in the same section, and use the offset from there.
7799 /// 3. Finally, if all that fails, fall back to an offset from the start of the
7800 ///    referenced section.
7801 static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
7802                                       std::map<uint64_t, SymbolRef> &Symbols,
7803                                       const RelocationRef &Reloc, uint64_t Addr,
7804                                       StringRef &Name, uint64_t &Addend) {
7805   if (Reloc.getSymbol() != Obj->symbol_end()) {
7806     Name = unwrapOrError(Reloc.getSymbol()->getName(), Obj->getFileName());
7807     Addend = Addr;
7808     return;
7809   }
7810 
7811   auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
7812   SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
7813 
7814   uint64_t SectionAddr = RelocSection.getAddress();
7815 
7816   auto Sym = Symbols.upper_bound(Addr);
7817   if (Sym == Symbols.begin()) {
7818     // The first symbol in the object is after this reference, the best we can
7819     // do is section-relative notation.
7820     if (Expected<StringRef> NameOrErr = RelocSection.getName())
7821       Name = *NameOrErr;
7822     else
7823       consumeError(NameOrErr.takeError());
7824 
7825     Addend = Addr - SectionAddr;
7826     return;
7827   }
7828 
7829   // Go back one so that SymbolAddress <= Addr.
7830   --Sym;
7831 
7832   section_iterator SymSection =
7833       unwrapOrError(Sym->second.getSection(), Obj->getFileName());
7834   if (RelocSection == *SymSection) {
7835     // There's a valid symbol in the same section before this reference.
7836     Name = unwrapOrError(Sym->second.getName(), Obj->getFileName());
7837     Addend = Addr - Sym->first;
7838     return;
7839   }
7840 
7841   // There is a symbol before this reference, but it's in a different
7842   // section. Probably not helpful to mention it, so use the section name.
7843   if (Expected<StringRef> NameOrErr = RelocSection.getName())
7844     Name = *NameOrErr;
7845   else
7846     consumeError(NameOrErr.takeError());
7847 
7848   Addend = Addr - SectionAddr;
7849 }
7850 
7851 static void printUnwindRelocDest(const MachOObjectFile *Obj,
7852                                  std::map<uint64_t, SymbolRef> &Symbols,
7853                                  const RelocationRef &Reloc, uint64_t Addr) {
7854   StringRef Name;
7855   uint64_t Addend;
7856 
7857   if (!Reloc.getObject())
7858     return;
7859 
7860   findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
7861 
7862   outs() << Name;
7863   if (Addend)
7864     outs() << " + " << format("0x%" PRIx64, Addend);
7865 }
7866 
7867 static void
7868 printMachOCompactUnwindSection(const MachOObjectFile *Obj,
7869                                std::map<uint64_t, SymbolRef> &Symbols,
7870                                const SectionRef &CompactUnwind) {
7871 
7872   if (!Obj->isLittleEndian()) {
7873     outs() << "Skipping big-endian __compact_unwind section\n";
7874     return;
7875   }
7876 
7877   bool Is64 = Obj->is64Bit();
7878   uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
7879   uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
7880 
7881   StringRef Contents =
7882       unwrapOrError(CompactUnwind.getContents(), Obj->getFileName());
7883   SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
7884 
7885   // First populate the initial raw offsets, encodings and so on from the entry.
7886   for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
7887     CompactUnwindEntry Entry(Contents, Offset, Is64);
7888     CompactUnwinds.push_back(Entry);
7889   }
7890 
7891   // Next we need to look at the relocations to find out what objects are
7892   // actually being referred to.
7893   for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
7894     uint64_t RelocAddress = Reloc.getOffset();
7895 
7896     uint32_t EntryIdx = RelocAddress / EntrySize;
7897     uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
7898     CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
7899 
7900     if (OffsetInEntry == 0)
7901       Entry.FunctionReloc = Reloc;
7902     else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
7903       Entry.PersonalityReloc = Reloc;
7904     else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
7905       Entry.LSDAReloc = Reloc;
7906     else {
7907       outs() << "Invalid relocation in __compact_unwind section\n";
7908       return;
7909     }
7910   }
7911 
7912   // Finally, we're ready to print the data we've gathered.
7913   outs() << "Contents of __compact_unwind section:\n";
7914   for (auto &Entry : CompactUnwinds) {
7915     outs() << "  Entry at offset "
7916            << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
7917 
7918     // 1. Start of the region this entry applies to.
7919     outs() << "    start:                " << format("0x%" PRIx64,
7920                                                      Entry.FunctionAddr) << ' ';
7921     printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
7922     outs() << '\n';
7923 
7924     // 2. Length of the region this entry applies to.
7925     outs() << "    length:               " << format("0x%" PRIx32, Entry.Length)
7926            << '\n';
7927     // 3. The 32-bit compact encoding.
7928     outs() << "    compact encoding:     "
7929            << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
7930 
7931     // 4. The personality function, if present.
7932     if (Entry.PersonalityReloc.getObject()) {
7933       outs() << "    personality function: "
7934              << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
7935       printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
7936                            Entry.PersonalityAddr);
7937       outs() << '\n';
7938     }
7939 
7940     // 5. This entry's language-specific data area.
7941     if (Entry.LSDAReloc.getObject()) {
7942       outs() << "    LSDA:                 " << format("0x%" PRIx64,
7943                                                        Entry.LSDAAddr) << ' ';
7944       printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
7945       outs() << '\n';
7946     }
7947   }
7948 }
7949 
7950 //===----------------------------------------------------------------------===//
7951 // __unwind_info section dumping
7952 //===----------------------------------------------------------------------===//
7953 
7954 static void printRegularSecondLevelUnwindPage(StringRef PageData) {
7955   ptrdiff_t Pos = 0;
7956   uint32_t Kind = readNext<uint32_t>(PageData, Pos);
7957   (void)Kind;
7958   assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
7959 
7960   uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
7961   uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
7962 
7963   Pos = EntriesStart;
7964   for (unsigned i = 0; i < NumEntries; ++i) {
7965     uint32_t FunctionOffset = readNext<uint32_t>(PageData, Pos);
7966     uint32_t Encoding = readNext<uint32_t>(PageData, Pos);
7967 
7968     outs() << "      [" << i << "]: "
7969            << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7970            << ", "
7971            << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
7972   }
7973 }
7974 
7975 static void printCompressedSecondLevelUnwindPage(
7976     StringRef PageData, uint32_t FunctionBase,
7977     const SmallVectorImpl<uint32_t> &CommonEncodings) {
7978   ptrdiff_t Pos = 0;
7979   uint32_t Kind = readNext<uint32_t>(PageData, Pos);
7980   (void)Kind;
7981   assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
7982 
7983   uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
7984   uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
7985 
7986   uint16_t EncodingsStart = readNext<uint16_t>(PageData, Pos);
7987   readNext<uint16_t>(PageData, Pos);
7988   StringRef PageEncodings = PageData.substr(EncodingsStart, StringRef::npos);
7989 
7990   Pos = EntriesStart;
7991   for (unsigned i = 0; i < NumEntries; ++i) {
7992     uint32_t Entry = readNext<uint32_t>(PageData, Pos);
7993     uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
7994     uint32_t EncodingIdx = Entry >> 24;
7995 
7996     uint32_t Encoding;
7997     if (EncodingIdx < CommonEncodings.size())
7998       Encoding = CommonEncodings[EncodingIdx];
7999     else
8000       Encoding = read<uint32_t>(PageEncodings,
8001                                 sizeof(uint32_t) *
8002                                     (EncodingIdx - CommonEncodings.size()));
8003 
8004     outs() << "      [" << i << "]: "
8005            << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
8006            << ", "
8007            << "encoding[" << EncodingIdx
8008            << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
8009   }
8010 }
8011 
8012 static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
8013                                         std::map<uint64_t, SymbolRef> &Symbols,
8014                                         const SectionRef &UnwindInfo) {
8015 
8016   if (!Obj->isLittleEndian()) {
8017     outs() << "Skipping big-endian __unwind_info section\n";
8018     return;
8019   }
8020 
8021   outs() << "Contents of __unwind_info section:\n";
8022 
8023   StringRef Contents =
8024       unwrapOrError(UnwindInfo.getContents(), Obj->getFileName());
8025   ptrdiff_t Pos = 0;
8026 
8027   //===----------------------------------
8028   // Section header
8029   //===----------------------------------
8030 
8031   uint32_t Version = readNext<uint32_t>(Contents, Pos);
8032   outs() << "  Version:                                   "
8033          << format("0x%" PRIx32, Version) << '\n';
8034   if (Version != 1) {
8035     outs() << "    Skipping section with unknown version\n";
8036     return;
8037   }
8038 
8039   uint32_t CommonEncodingsStart = readNext<uint32_t>(Contents, Pos);
8040   outs() << "  Common encodings array section offset:     "
8041          << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
8042   uint32_t NumCommonEncodings = readNext<uint32_t>(Contents, Pos);
8043   outs() << "  Number of common encodings in array:       "
8044          << format("0x%" PRIx32, NumCommonEncodings) << '\n';
8045 
8046   uint32_t PersonalitiesStart = readNext<uint32_t>(Contents, Pos);
8047   outs() << "  Personality function array section offset: "
8048          << format("0x%" PRIx32, PersonalitiesStart) << '\n';
8049   uint32_t NumPersonalities = readNext<uint32_t>(Contents, Pos);
8050   outs() << "  Number of personality functions in array:  "
8051          << format("0x%" PRIx32, NumPersonalities) << '\n';
8052 
8053   uint32_t IndicesStart = readNext<uint32_t>(Contents, Pos);
8054   outs() << "  Index array section offset:                "
8055          << format("0x%" PRIx32, IndicesStart) << '\n';
8056   uint32_t NumIndices = readNext<uint32_t>(Contents, Pos);
8057   outs() << "  Number of indices in array:                "
8058          << format("0x%" PRIx32, NumIndices) << '\n';
8059 
8060   //===----------------------------------
8061   // A shared list of common encodings
8062   //===----------------------------------
8063 
8064   // These occupy indices in the range [0, N] whenever an encoding is referenced
8065   // from a compressed 2nd level index table. In practice the linker only
8066   // creates ~128 of these, so that indices are available to embed encodings in
8067   // the 2nd level index.
8068 
8069   SmallVector<uint32_t, 64> CommonEncodings;
8070   outs() << "  Common encodings: (count = " << NumCommonEncodings << ")\n";
8071   Pos = CommonEncodingsStart;
8072   for (unsigned i = 0; i < NumCommonEncodings; ++i) {
8073     uint32_t Encoding = readNext<uint32_t>(Contents, Pos);
8074     CommonEncodings.push_back(Encoding);
8075 
8076     outs() << "    encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
8077            << '\n';
8078   }
8079 
8080   //===----------------------------------
8081   // Personality functions used in this executable
8082   //===----------------------------------
8083 
8084   // There should be only a handful of these (one per source language,
8085   // roughly). Particularly since they only get 2 bits in the compact encoding.
8086 
8087   outs() << "  Personality functions: (count = " << NumPersonalities << ")\n";
8088   Pos = PersonalitiesStart;
8089   for (unsigned i = 0; i < NumPersonalities; ++i) {
8090     uint32_t PersonalityFn = readNext<uint32_t>(Contents, Pos);
8091     outs() << "    personality[" << i + 1
8092            << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
8093   }
8094 
8095   //===----------------------------------
8096   // The level 1 index entries
8097   //===----------------------------------
8098 
8099   // These specify an approximate place to start searching for the more detailed
8100   // information, sorted by PC.
8101 
8102   struct IndexEntry {
8103     uint32_t FunctionOffset;
8104     uint32_t SecondLevelPageStart;
8105     uint32_t LSDAStart;
8106   };
8107 
8108   SmallVector<IndexEntry, 4> IndexEntries;
8109 
8110   outs() << "  Top level indices: (count = " << NumIndices << ")\n";
8111   Pos = IndicesStart;
8112   for (unsigned i = 0; i < NumIndices; ++i) {
8113     IndexEntry Entry;
8114 
8115     Entry.FunctionOffset = readNext<uint32_t>(Contents, Pos);
8116     Entry.SecondLevelPageStart = readNext<uint32_t>(Contents, Pos);
8117     Entry.LSDAStart = readNext<uint32_t>(Contents, Pos);
8118     IndexEntries.push_back(Entry);
8119 
8120     outs() << "    [" << i << "]: "
8121            << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
8122            << ", "
8123            << "2nd level page offset="
8124            << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
8125            << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
8126   }
8127 
8128   //===----------------------------------
8129   // Next come the LSDA tables
8130   //===----------------------------------
8131 
8132   // The LSDA layout is rather implicit: it's a contiguous array of entries from
8133   // the first top-level index's LSDAOffset to the last (sentinel).
8134 
8135   outs() << "  LSDA descriptors:\n";
8136   Pos = IndexEntries[0].LSDAStart;
8137   const uint32_t LSDASize = 2 * sizeof(uint32_t);
8138   int NumLSDAs =
8139       (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) / LSDASize;
8140 
8141   for (int i = 0; i < NumLSDAs; ++i) {
8142     uint32_t FunctionOffset = readNext<uint32_t>(Contents, Pos);
8143     uint32_t LSDAOffset = readNext<uint32_t>(Contents, Pos);
8144     outs() << "    [" << i << "]: "
8145            << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
8146            << ", "
8147            << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
8148   }
8149 
8150   //===----------------------------------
8151   // Finally, the 2nd level indices
8152   //===----------------------------------
8153 
8154   // Generally these are 4K in size, and have 2 possible forms:
8155   //   + Regular stores up to 511 entries with disparate encodings
8156   //   + Compressed stores up to 1021 entries if few enough compact encoding
8157   //     values are used.
8158   outs() << "  Second level indices:\n";
8159   for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
8160     // The final sentinel top-level index has no associated 2nd level page
8161     if (IndexEntries[i].SecondLevelPageStart == 0)
8162       break;
8163 
8164     outs() << "    Second level index[" << i << "]: "
8165            << "offset in section="
8166            << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
8167            << ", "
8168            << "base function offset="
8169            << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
8170 
8171     Pos = IndexEntries[i].SecondLevelPageStart;
8172     if (Pos + sizeof(uint32_t) > Contents.size()) {
8173       outs() << "warning: invalid offset for second level page: " << Pos << '\n';
8174       continue;
8175     }
8176 
8177     uint32_t Kind =
8178         *reinterpret_cast<const support::ulittle32_t *>(Contents.data() + Pos);
8179     if (Kind == 2)
8180       printRegularSecondLevelUnwindPage(Contents.substr(Pos, 4096));
8181     else if (Kind == 3)
8182       printCompressedSecondLevelUnwindPage(Contents.substr(Pos, 4096),
8183                                            IndexEntries[i].FunctionOffset,
8184                                            CommonEncodings);
8185     else
8186       outs() << "    Skipping 2nd level page with unknown kind " << Kind
8187              << '\n';
8188   }
8189 }
8190 
8191 void printMachOUnwindInfo(const MachOObjectFile *Obj) {
8192   std::map<uint64_t, SymbolRef> Symbols;
8193   for (const SymbolRef &SymRef : Obj->symbols()) {
8194     // Discard any undefined or absolute symbols. They're not going to take part
8195     // in the convenience lookup for unwind info and just take up resources.
8196     auto SectOrErr = SymRef.getSection();
8197     if (!SectOrErr) {
8198       // TODO: Actually report errors helpfully.
8199       consumeError(SectOrErr.takeError());
8200       continue;
8201     }
8202     section_iterator Section = *SectOrErr;
8203     if (Section == Obj->section_end())
8204       continue;
8205 
8206     uint64_t Addr = SymRef.getValue();
8207     Symbols.insert(std::make_pair(Addr, SymRef));
8208   }
8209 
8210   for (const SectionRef &Section : Obj->sections()) {
8211     StringRef SectName;
8212     if (Expected<StringRef> NameOrErr = Section.getName())
8213       SectName = *NameOrErr;
8214     else
8215       consumeError(NameOrErr.takeError());
8216 
8217     if (SectName == "__compact_unwind")
8218       printMachOCompactUnwindSection(Obj, Symbols, Section);
8219     else if (SectName == "__unwind_info")
8220       printMachOUnwindInfoSection(Obj, Symbols, Section);
8221   }
8222 }
8223 
8224 static void PrintMachHeader(uint32_t magic, uint32_t cputype,
8225                             uint32_t cpusubtype, uint32_t filetype,
8226                             uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
8227                             bool verbose) {
8228   outs() << "Mach header\n";
8229   outs() << "      magic cputype cpusubtype  caps    filetype ncmds "
8230             "sizeofcmds      flags\n";
8231   if (verbose) {
8232     if (magic == MachO::MH_MAGIC)
8233       outs() << "   MH_MAGIC";
8234     else if (magic == MachO::MH_MAGIC_64)
8235       outs() << "MH_MAGIC_64";
8236     else
8237       outs() << format(" 0x%08" PRIx32, magic);
8238     switch (cputype) {
8239     case MachO::CPU_TYPE_I386:
8240       outs() << "    I386";
8241       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8242       case MachO::CPU_SUBTYPE_I386_ALL:
8243         outs() << "        ALL";
8244         break;
8245       default:
8246         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8247         break;
8248       }
8249       break;
8250     case MachO::CPU_TYPE_X86_64:
8251       outs() << "  X86_64";
8252       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8253       case MachO::CPU_SUBTYPE_X86_64_ALL:
8254         outs() << "        ALL";
8255         break;
8256       case MachO::CPU_SUBTYPE_X86_64_H:
8257         outs() << "    Haswell";
8258         break;
8259       default:
8260         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8261         break;
8262       }
8263       break;
8264     case MachO::CPU_TYPE_ARM:
8265       outs() << "     ARM";
8266       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8267       case MachO::CPU_SUBTYPE_ARM_ALL:
8268         outs() << "        ALL";
8269         break;
8270       case MachO::CPU_SUBTYPE_ARM_V4T:
8271         outs() << "        V4T";
8272         break;
8273       case MachO::CPU_SUBTYPE_ARM_V5TEJ:
8274         outs() << "      V5TEJ";
8275         break;
8276       case MachO::CPU_SUBTYPE_ARM_XSCALE:
8277         outs() << "     XSCALE";
8278         break;
8279       case MachO::CPU_SUBTYPE_ARM_V6:
8280         outs() << "         V6";
8281         break;
8282       case MachO::CPU_SUBTYPE_ARM_V6M:
8283         outs() << "        V6M";
8284         break;
8285       case MachO::CPU_SUBTYPE_ARM_V7:
8286         outs() << "         V7";
8287         break;
8288       case MachO::CPU_SUBTYPE_ARM_V7EM:
8289         outs() << "       V7EM";
8290         break;
8291       case MachO::CPU_SUBTYPE_ARM_V7K:
8292         outs() << "        V7K";
8293         break;
8294       case MachO::CPU_SUBTYPE_ARM_V7M:
8295         outs() << "        V7M";
8296         break;
8297       case MachO::CPU_SUBTYPE_ARM_V7S:
8298         outs() << "        V7S";
8299         break;
8300       default:
8301         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8302         break;
8303       }
8304       break;
8305     case MachO::CPU_TYPE_ARM64:
8306       outs() << "   ARM64";
8307       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8308       case MachO::CPU_SUBTYPE_ARM64_ALL:
8309         outs() << "        ALL";
8310         break;
8311       case MachO::CPU_SUBTYPE_ARM64E:
8312         outs() << "          E";
8313         break;
8314       default:
8315         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8316         break;
8317       }
8318       break;
8319     case MachO::CPU_TYPE_ARM64_32:
8320       outs() << " ARM64_32";
8321       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8322       case MachO::CPU_SUBTYPE_ARM64_32_V8:
8323         outs() << "        V8";
8324         break;
8325       default:
8326         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8327         break;
8328       }
8329       break;
8330     case MachO::CPU_TYPE_POWERPC:
8331       outs() << "     PPC";
8332       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8333       case MachO::CPU_SUBTYPE_POWERPC_ALL:
8334         outs() << "        ALL";
8335         break;
8336       default:
8337         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8338         break;
8339       }
8340       break;
8341     case MachO::CPU_TYPE_POWERPC64:
8342       outs() << "   PPC64";
8343       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8344       case MachO::CPU_SUBTYPE_POWERPC_ALL:
8345         outs() << "        ALL";
8346         break;
8347       default:
8348         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8349         break;
8350       }
8351       break;
8352     default:
8353       outs() << format(" %7d", cputype);
8354       outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8355       break;
8356     }
8357     if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
8358       outs() << " LIB64";
8359     } else {
8360       outs() << format("  0x%02" PRIx32,
8361                        (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
8362     }
8363     switch (filetype) {
8364     case MachO::MH_OBJECT:
8365       outs() << "      OBJECT";
8366       break;
8367     case MachO::MH_EXECUTE:
8368       outs() << "     EXECUTE";
8369       break;
8370     case MachO::MH_FVMLIB:
8371       outs() << "      FVMLIB";
8372       break;
8373     case MachO::MH_CORE:
8374       outs() << "        CORE";
8375       break;
8376     case MachO::MH_PRELOAD:
8377       outs() << "     PRELOAD";
8378       break;
8379     case MachO::MH_DYLIB:
8380       outs() << "       DYLIB";
8381       break;
8382     case MachO::MH_DYLIB_STUB:
8383       outs() << "  DYLIB_STUB";
8384       break;
8385     case MachO::MH_DYLINKER:
8386       outs() << "    DYLINKER";
8387       break;
8388     case MachO::MH_BUNDLE:
8389       outs() << "      BUNDLE";
8390       break;
8391     case MachO::MH_DSYM:
8392       outs() << "        DSYM";
8393       break;
8394     case MachO::MH_KEXT_BUNDLE:
8395       outs() << "  KEXTBUNDLE";
8396       break;
8397     default:
8398       outs() << format("  %10u", filetype);
8399       break;
8400     }
8401     outs() << format(" %5u", ncmds);
8402     outs() << format(" %10u", sizeofcmds);
8403     uint32_t f = flags;
8404     if (f & MachO::MH_NOUNDEFS) {
8405       outs() << "   NOUNDEFS";
8406       f &= ~MachO::MH_NOUNDEFS;
8407     }
8408     if (f & MachO::MH_INCRLINK) {
8409       outs() << " INCRLINK";
8410       f &= ~MachO::MH_INCRLINK;
8411     }
8412     if (f & MachO::MH_DYLDLINK) {
8413       outs() << " DYLDLINK";
8414       f &= ~MachO::MH_DYLDLINK;
8415     }
8416     if (f & MachO::MH_BINDATLOAD) {
8417       outs() << " BINDATLOAD";
8418       f &= ~MachO::MH_BINDATLOAD;
8419     }
8420     if (f & MachO::MH_PREBOUND) {
8421       outs() << " PREBOUND";
8422       f &= ~MachO::MH_PREBOUND;
8423     }
8424     if (f & MachO::MH_SPLIT_SEGS) {
8425       outs() << " SPLIT_SEGS";
8426       f &= ~MachO::MH_SPLIT_SEGS;
8427     }
8428     if (f & MachO::MH_LAZY_INIT) {
8429       outs() << " LAZY_INIT";
8430       f &= ~MachO::MH_LAZY_INIT;
8431     }
8432     if (f & MachO::MH_TWOLEVEL) {
8433       outs() << " TWOLEVEL";
8434       f &= ~MachO::MH_TWOLEVEL;
8435     }
8436     if (f & MachO::MH_FORCE_FLAT) {
8437       outs() << " FORCE_FLAT";
8438       f &= ~MachO::MH_FORCE_FLAT;
8439     }
8440     if (f & MachO::MH_NOMULTIDEFS) {
8441       outs() << " NOMULTIDEFS";
8442       f &= ~MachO::MH_NOMULTIDEFS;
8443     }
8444     if (f & MachO::MH_NOFIXPREBINDING) {
8445       outs() << " NOFIXPREBINDING";
8446       f &= ~MachO::MH_NOFIXPREBINDING;
8447     }
8448     if (f & MachO::MH_PREBINDABLE) {
8449       outs() << " PREBINDABLE";
8450       f &= ~MachO::MH_PREBINDABLE;
8451     }
8452     if (f & MachO::MH_ALLMODSBOUND) {
8453       outs() << " ALLMODSBOUND";
8454       f &= ~MachO::MH_ALLMODSBOUND;
8455     }
8456     if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
8457       outs() << " SUBSECTIONS_VIA_SYMBOLS";
8458       f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
8459     }
8460     if (f & MachO::MH_CANONICAL) {
8461       outs() << " CANONICAL";
8462       f &= ~MachO::MH_CANONICAL;
8463     }
8464     if (f & MachO::MH_WEAK_DEFINES) {
8465       outs() << " WEAK_DEFINES";
8466       f &= ~MachO::MH_WEAK_DEFINES;
8467     }
8468     if (f & MachO::MH_BINDS_TO_WEAK) {
8469       outs() << " BINDS_TO_WEAK";
8470       f &= ~MachO::MH_BINDS_TO_WEAK;
8471     }
8472     if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
8473       outs() << " ALLOW_STACK_EXECUTION";
8474       f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
8475     }
8476     if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
8477       outs() << " DEAD_STRIPPABLE_DYLIB";
8478       f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
8479     }
8480     if (f & MachO::MH_PIE) {
8481       outs() << " PIE";
8482       f &= ~MachO::MH_PIE;
8483     }
8484     if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
8485       outs() << " NO_REEXPORTED_DYLIBS";
8486       f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
8487     }
8488     if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
8489       outs() << " MH_HAS_TLV_DESCRIPTORS";
8490       f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
8491     }
8492     if (f & MachO::MH_NO_HEAP_EXECUTION) {
8493       outs() << " MH_NO_HEAP_EXECUTION";
8494       f &= ~MachO::MH_NO_HEAP_EXECUTION;
8495     }
8496     if (f & MachO::MH_APP_EXTENSION_SAFE) {
8497       outs() << " APP_EXTENSION_SAFE";
8498       f &= ~MachO::MH_APP_EXTENSION_SAFE;
8499     }
8500     if (f & MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO) {
8501       outs() << " NLIST_OUTOFSYNC_WITH_DYLDINFO";
8502       f &= ~MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO;
8503     }
8504     if (f != 0 || flags == 0)
8505       outs() << format(" 0x%08" PRIx32, f);
8506   } else {
8507     outs() << format(" 0x%08" PRIx32, magic);
8508     outs() << format(" %7d", cputype);
8509     outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8510     outs() << format("  0x%02" PRIx32,
8511                      (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
8512     outs() << format("  %10u", filetype);
8513     outs() << format(" %5u", ncmds);
8514     outs() << format(" %10u", sizeofcmds);
8515     outs() << format(" 0x%08" PRIx32, flags);
8516   }
8517   outs() << "\n";
8518 }
8519 
8520 static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
8521                                 StringRef SegName, uint64_t vmaddr,
8522                                 uint64_t vmsize, uint64_t fileoff,
8523                                 uint64_t filesize, uint32_t maxprot,
8524                                 uint32_t initprot, uint32_t nsects,
8525                                 uint32_t flags, uint32_t object_size,
8526                                 bool verbose) {
8527   uint64_t expected_cmdsize;
8528   if (cmd == MachO::LC_SEGMENT) {
8529     outs() << "      cmd LC_SEGMENT\n";
8530     expected_cmdsize = nsects;
8531     expected_cmdsize *= sizeof(struct MachO::section);
8532     expected_cmdsize += sizeof(struct MachO::segment_command);
8533   } else {
8534     outs() << "      cmd LC_SEGMENT_64\n";
8535     expected_cmdsize = nsects;
8536     expected_cmdsize *= sizeof(struct MachO::section_64);
8537     expected_cmdsize += sizeof(struct MachO::segment_command_64);
8538   }
8539   outs() << "  cmdsize " << cmdsize;
8540   if (cmdsize != expected_cmdsize)
8541     outs() << " Inconsistent size\n";
8542   else
8543     outs() << "\n";
8544   outs() << "  segname " << SegName << "\n";
8545   if (cmd == MachO::LC_SEGMENT_64) {
8546     outs() << "   vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
8547     outs() << "   vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
8548   } else {
8549     outs() << "   vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
8550     outs() << "   vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
8551   }
8552   outs() << "  fileoff " << fileoff;
8553   if (fileoff > object_size)
8554     outs() << " (past end of file)\n";
8555   else
8556     outs() << "\n";
8557   outs() << " filesize " << filesize;
8558   if (fileoff + filesize > object_size)
8559     outs() << " (past end of file)\n";
8560   else
8561     outs() << "\n";
8562   if (verbose) {
8563     if ((maxprot &
8564          ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8565            MachO::VM_PROT_EXECUTE)) != 0)
8566       outs() << "  maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
8567     else {
8568       outs() << "  maxprot ";
8569       outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
8570       outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8571       outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
8572     }
8573     if ((initprot &
8574          ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8575            MachO::VM_PROT_EXECUTE)) != 0)
8576       outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
8577     else {
8578       outs() << " initprot ";
8579       outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
8580       outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8581       outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
8582     }
8583   } else {
8584     outs() << "  maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
8585     outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
8586   }
8587   outs() << "   nsects " << nsects << "\n";
8588   if (verbose) {
8589     outs() << "    flags";
8590     if (flags == 0)
8591       outs() << " (none)\n";
8592     else {
8593       if (flags & MachO::SG_HIGHVM) {
8594         outs() << " HIGHVM";
8595         flags &= ~MachO::SG_HIGHVM;
8596       }
8597       if (flags & MachO::SG_FVMLIB) {
8598         outs() << " FVMLIB";
8599         flags &= ~MachO::SG_FVMLIB;
8600       }
8601       if (flags & MachO::SG_NORELOC) {
8602         outs() << " NORELOC";
8603         flags &= ~MachO::SG_NORELOC;
8604       }
8605       if (flags & MachO::SG_PROTECTED_VERSION_1) {
8606         outs() << " PROTECTED_VERSION_1";
8607         flags &= ~MachO::SG_PROTECTED_VERSION_1;
8608       }
8609       if (flags)
8610         outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
8611       else
8612         outs() << "\n";
8613     }
8614   } else {
8615     outs() << "    flags " << format("0x%" PRIx32, flags) << "\n";
8616   }
8617 }
8618 
8619 static void PrintSection(const char *sectname, const char *segname,
8620                          uint64_t addr, uint64_t size, uint32_t offset,
8621                          uint32_t align, uint32_t reloff, uint32_t nreloc,
8622                          uint32_t flags, uint32_t reserved1, uint32_t reserved2,
8623                          uint32_t cmd, const char *sg_segname,
8624                          uint32_t filetype, uint32_t object_size,
8625                          bool verbose) {
8626   outs() << "Section\n";
8627   outs() << "  sectname " << format("%.16s\n", sectname);
8628   outs() << "   segname " << format("%.16s", segname);
8629   if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
8630     outs() << " (does not match segment)\n";
8631   else
8632     outs() << "\n";
8633   if (cmd == MachO::LC_SEGMENT_64) {
8634     outs() << "      addr " << format("0x%016" PRIx64, addr) << "\n";
8635     outs() << "      size " << format("0x%016" PRIx64, size);
8636   } else {
8637     outs() << "      addr " << format("0x%08" PRIx64, addr) << "\n";
8638     outs() << "      size " << format("0x%08" PRIx64, size);
8639   }
8640   if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
8641     outs() << " (past end of file)\n";
8642   else
8643     outs() << "\n";
8644   outs() << "    offset " << offset;
8645   if (offset > object_size)
8646     outs() << " (past end of file)\n";
8647   else
8648     outs() << "\n";
8649   uint32_t align_shifted = 1 << align;
8650   outs() << "     align 2^" << align << " (" << align_shifted << ")\n";
8651   outs() << "    reloff " << reloff;
8652   if (reloff > object_size)
8653     outs() << " (past end of file)\n";
8654   else
8655     outs() << "\n";
8656   outs() << "    nreloc " << nreloc;
8657   if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
8658     outs() << " (past end of file)\n";
8659   else
8660     outs() << "\n";
8661   uint32_t section_type = flags & MachO::SECTION_TYPE;
8662   if (verbose) {
8663     outs() << "      type";
8664     if (section_type == MachO::S_REGULAR)
8665       outs() << " S_REGULAR\n";
8666     else if (section_type == MachO::S_ZEROFILL)
8667       outs() << " S_ZEROFILL\n";
8668     else if (section_type == MachO::S_CSTRING_LITERALS)
8669       outs() << " S_CSTRING_LITERALS\n";
8670     else if (section_type == MachO::S_4BYTE_LITERALS)
8671       outs() << " S_4BYTE_LITERALS\n";
8672     else if (section_type == MachO::S_8BYTE_LITERALS)
8673       outs() << " S_8BYTE_LITERALS\n";
8674     else if (section_type == MachO::S_16BYTE_LITERALS)
8675       outs() << " S_16BYTE_LITERALS\n";
8676     else if (section_type == MachO::S_LITERAL_POINTERS)
8677       outs() << " S_LITERAL_POINTERS\n";
8678     else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
8679       outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
8680     else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
8681       outs() << " S_LAZY_SYMBOL_POINTERS\n";
8682     else if (section_type == MachO::S_SYMBOL_STUBS)
8683       outs() << " S_SYMBOL_STUBS\n";
8684     else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
8685       outs() << " S_MOD_INIT_FUNC_POINTERS\n";
8686     else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
8687       outs() << " S_MOD_TERM_FUNC_POINTERS\n";
8688     else if (section_type == MachO::S_COALESCED)
8689       outs() << " S_COALESCED\n";
8690     else if (section_type == MachO::S_INTERPOSING)
8691       outs() << " S_INTERPOSING\n";
8692     else if (section_type == MachO::S_DTRACE_DOF)
8693       outs() << " S_DTRACE_DOF\n";
8694     else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
8695       outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
8696     else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
8697       outs() << " S_THREAD_LOCAL_REGULAR\n";
8698     else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
8699       outs() << " S_THREAD_LOCAL_ZEROFILL\n";
8700     else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
8701       outs() << " S_THREAD_LOCAL_VARIABLES\n";
8702     else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8703       outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
8704     else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
8705       outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
8706     else
8707       outs() << format("0x%08" PRIx32, section_type) << "\n";
8708     outs() << "attributes";
8709     uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
8710     if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
8711       outs() << " PURE_INSTRUCTIONS";
8712     if (section_attributes & MachO::S_ATTR_NO_TOC)
8713       outs() << " NO_TOC";
8714     if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
8715       outs() << " STRIP_STATIC_SYMS";
8716     if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
8717       outs() << " NO_DEAD_STRIP";
8718     if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
8719       outs() << " LIVE_SUPPORT";
8720     if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
8721       outs() << " SELF_MODIFYING_CODE";
8722     if (section_attributes & MachO::S_ATTR_DEBUG)
8723       outs() << " DEBUG";
8724     if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
8725       outs() << " SOME_INSTRUCTIONS";
8726     if (section_attributes & MachO::S_ATTR_EXT_RELOC)
8727       outs() << " EXT_RELOC";
8728     if (section_attributes & MachO::S_ATTR_LOC_RELOC)
8729       outs() << " LOC_RELOC";
8730     if (section_attributes == 0)
8731       outs() << " (none)";
8732     outs() << "\n";
8733   } else
8734     outs() << "     flags " << format("0x%08" PRIx32, flags) << "\n";
8735   outs() << " reserved1 " << reserved1;
8736   if (section_type == MachO::S_SYMBOL_STUBS ||
8737       section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
8738       section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
8739       section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
8740       section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8741     outs() << " (index into indirect symbol table)\n";
8742   else
8743     outs() << "\n";
8744   outs() << " reserved2 " << reserved2;
8745   if (section_type == MachO::S_SYMBOL_STUBS)
8746     outs() << " (size of stubs)\n";
8747   else
8748     outs() << "\n";
8749 }
8750 
8751 static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
8752                                    uint32_t object_size) {
8753   outs() << "     cmd LC_SYMTAB\n";
8754   outs() << " cmdsize " << st.cmdsize;
8755   if (st.cmdsize != sizeof(struct MachO::symtab_command))
8756     outs() << " Incorrect size\n";
8757   else
8758     outs() << "\n";
8759   outs() << "  symoff " << st.symoff;
8760   if (st.symoff > object_size)
8761     outs() << " (past end of file)\n";
8762   else
8763     outs() << "\n";
8764   outs() << "   nsyms " << st.nsyms;
8765   uint64_t big_size;
8766   if (Is64Bit) {
8767     big_size = st.nsyms;
8768     big_size *= sizeof(struct MachO::nlist_64);
8769     big_size += st.symoff;
8770     if (big_size > object_size)
8771       outs() << " (past end of file)\n";
8772     else
8773       outs() << "\n";
8774   } else {
8775     big_size = st.nsyms;
8776     big_size *= sizeof(struct MachO::nlist);
8777     big_size += st.symoff;
8778     if (big_size > object_size)
8779       outs() << " (past end of file)\n";
8780     else
8781       outs() << "\n";
8782   }
8783   outs() << "  stroff " << st.stroff;
8784   if (st.stroff > object_size)
8785     outs() << " (past end of file)\n";
8786   else
8787     outs() << "\n";
8788   outs() << " strsize " << st.strsize;
8789   big_size = st.stroff;
8790   big_size += st.strsize;
8791   if (big_size > object_size)
8792     outs() << " (past end of file)\n";
8793   else
8794     outs() << "\n";
8795 }
8796 
8797 static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
8798                                      uint32_t nsyms, uint32_t object_size,
8799                                      bool Is64Bit) {
8800   outs() << "            cmd LC_DYSYMTAB\n";
8801   outs() << "        cmdsize " << dyst.cmdsize;
8802   if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
8803     outs() << " Incorrect size\n";
8804   else
8805     outs() << "\n";
8806   outs() << "      ilocalsym " << dyst.ilocalsym;
8807   if (dyst.ilocalsym > nsyms)
8808     outs() << " (greater than the number of symbols)\n";
8809   else
8810     outs() << "\n";
8811   outs() << "      nlocalsym " << dyst.nlocalsym;
8812   uint64_t big_size;
8813   big_size = dyst.ilocalsym;
8814   big_size += dyst.nlocalsym;
8815   if (big_size > nsyms)
8816     outs() << " (past the end of the symbol table)\n";
8817   else
8818     outs() << "\n";
8819   outs() << "     iextdefsym " << dyst.iextdefsym;
8820   if (dyst.iextdefsym > nsyms)
8821     outs() << " (greater than the number of symbols)\n";
8822   else
8823     outs() << "\n";
8824   outs() << "     nextdefsym " << dyst.nextdefsym;
8825   big_size = dyst.iextdefsym;
8826   big_size += dyst.nextdefsym;
8827   if (big_size > nsyms)
8828     outs() << " (past the end of the symbol table)\n";
8829   else
8830     outs() << "\n";
8831   outs() << "      iundefsym " << dyst.iundefsym;
8832   if (dyst.iundefsym > nsyms)
8833     outs() << " (greater than the number of symbols)\n";
8834   else
8835     outs() << "\n";
8836   outs() << "      nundefsym " << dyst.nundefsym;
8837   big_size = dyst.iundefsym;
8838   big_size += dyst.nundefsym;
8839   if (big_size > nsyms)
8840     outs() << " (past the end of the symbol table)\n";
8841   else
8842     outs() << "\n";
8843   outs() << "         tocoff " << dyst.tocoff;
8844   if (dyst.tocoff > object_size)
8845     outs() << " (past end of file)\n";
8846   else
8847     outs() << "\n";
8848   outs() << "           ntoc " << dyst.ntoc;
8849   big_size = dyst.ntoc;
8850   big_size *= sizeof(struct MachO::dylib_table_of_contents);
8851   big_size += dyst.tocoff;
8852   if (big_size > object_size)
8853     outs() << " (past end of file)\n";
8854   else
8855     outs() << "\n";
8856   outs() << "      modtaboff " << dyst.modtaboff;
8857   if (dyst.modtaboff > object_size)
8858     outs() << " (past end of file)\n";
8859   else
8860     outs() << "\n";
8861   outs() << "        nmodtab " << dyst.nmodtab;
8862   uint64_t modtabend;
8863   if (Is64Bit) {
8864     modtabend = dyst.nmodtab;
8865     modtabend *= sizeof(struct MachO::dylib_module_64);
8866     modtabend += dyst.modtaboff;
8867   } else {
8868     modtabend = dyst.nmodtab;
8869     modtabend *= sizeof(struct MachO::dylib_module);
8870     modtabend += dyst.modtaboff;
8871   }
8872   if (modtabend > object_size)
8873     outs() << " (past end of file)\n";
8874   else
8875     outs() << "\n";
8876   outs() << "   extrefsymoff " << dyst.extrefsymoff;
8877   if (dyst.extrefsymoff > object_size)
8878     outs() << " (past end of file)\n";
8879   else
8880     outs() << "\n";
8881   outs() << "    nextrefsyms " << dyst.nextrefsyms;
8882   big_size = dyst.nextrefsyms;
8883   big_size *= sizeof(struct MachO::dylib_reference);
8884   big_size += dyst.extrefsymoff;
8885   if (big_size > object_size)
8886     outs() << " (past end of file)\n";
8887   else
8888     outs() << "\n";
8889   outs() << " indirectsymoff " << dyst.indirectsymoff;
8890   if (dyst.indirectsymoff > object_size)
8891     outs() << " (past end of file)\n";
8892   else
8893     outs() << "\n";
8894   outs() << "  nindirectsyms " << dyst.nindirectsyms;
8895   big_size = dyst.nindirectsyms;
8896   big_size *= sizeof(uint32_t);
8897   big_size += dyst.indirectsymoff;
8898   if (big_size > object_size)
8899     outs() << " (past end of file)\n";
8900   else
8901     outs() << "\n";
8902   outs() << "      extreloff " << dyst.extreloff;
8903   if (dyst.extreloff > object_size)
8904     outs() << " (past end of file)\n";
8905   else
8906     outs() << "\n";
8907   outs() << "        nextrel " << dyst.nextrel;
8908   big_size = dyst.nextrel;
8909   big_size *= sizeof(struct MachO::relocation_info);
8910   big_size += dyst.extreloff;
8911   if (big_size > object_size)
8912     outs() << " (past end of file)\n";
8913   else
8914     outs() << "\n";
8915   outs() << "      locreloff " << dyst.locreloff;
8916   if (dyst.locreloff > object_size)
8917     outs() << " (past end of file)\n";
8918   else
8919     outs() << "\n";
8920   outs() << "        nlocrel " << dyst.nlocrel;
8921   big_size = dyst.nlocrel;
8922   big_size *= sizeof(struct MachO::relocation_info);
8923   big_size += dyst.locreloff;
8924   if (big_size > object_size)
8925     outs() << " (past end of file)\n";
8926   else
8927     outs() << "\n";
8928 }
8929 
8930 static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
8931                                      uint32_t object_size) {
8932   if (dc.cmd == MachO::LC_DYLD_INFO)
8933     outs() << "            cmd LC_DYLD_INFO\n";
8934   else
8935     outs() << "            cmd LC_DYLD_INFO_ONLY\n";
8936   outs() << "        cmdsize " << dc.cmdsize;
8937   if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
8938     outs() << " Incorrect size\n";
8939   else
8940     outs() << "\n";
8941   outs() << "     rebase_off " << dc.rebase_off;
8942   if (dc.rebase_off > object_size)
8943     outs() << " (past end of file)\n";
8944   else
8945     outs() << "\n";
8946   outs() << "    rebase_size " << dc.rebase_size;
8947   uint64_t big_size;
8948   big_size = dc.rebase_off;
8949   big_size += dc.rebase_size;
8950   if (big_size > object_size)
8951     outs() << " (past end of file)\n";
8952   else
8953     outs() << "\n";
8954   outs() << "       bind_off " << dc.bind_off;
8955   if (dc.bind_off > object_size)
8956     outs() << " (past end of file)\n";
8957   else
8958     outs() << "\n";
8959   outs() << "      bind_size " << dc.bind_size;
8960   big_size = dc.bind_off;
8961   big_size += dc.bind_size;
8962   if (big_size > object_size)
8963     outs() << " (past end of file)\n";
8964   else
8965     outs() << "\n";
8966   outs() << "  weak_bind_off " << dc.weak_bind_off;
8967   if (dc.weak_bind_off > object_size)
8968     outs() << " (past end of file)\n";
8969   else
8970     outs() << "\n";
8971   outs() << " weak_bind_size " << dc.weak_bind_size;
8972   big_size = dc.weak_bind_off;
8973   big_size += dc.weak_bind_size;
8974   if (big_size > object_size)
8975     outs() << " (past end of file)\n";
8976   else
8977     outs() << "\n";
8978   outs() << "  lazy_bind_off " << dc.lazy_bind_off;
8979   if (dc.lazy_bind_off > object_size)
8980     outs() << " (past end of file)\n";
8981   else
8982     outs() << "\n";
8983   outs() << " lazy_bind_size " << dc.lazy_bind_size;
8984   big_size = dc.lazy_bind_off;
8985   big_size += dc.lazy_bind_size;
8986   if (big_size > object_size)
8987     outs() << " (past end of file)\n";
8988   else
8989     outs() << "\n";
8990   outs() << "     export_off " << dc.export_off;
8991   if (dc.export_off > object_size)
8992     outs() << " (past end of file)\n";
8993   else
8994     outs() << "\n";
8995   outs() << "    export_size " << dc.export_size;
8996   big_size = dc.export_off;
8997   big_size += dc.export_size;
8998   if (big_size > object_size)
8999     outs() << " (past end of file)\n";
9000   else
9001     outs() << "\n";
9002 }
9003 
9004 static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
9005                                  const char *Ptr) {
9006   if (dyld.cmd == MachO::LC_ID_DYLINKER)
9007     outs() << "          cmd LC_ID_DYLINKER\n";
9008   else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
9009     outs() << "          cmd LC_LOAD_DYLINKER\n";
9010   else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
9011     outs() << "          cmd LC_DYLD_ENVIRONMENT\n";
9012   else
9013     outs() << "          cmd ?(" << dyld.cmd << ")\n";
9014   outs() << "      cmdsize " << dyld.cmdsize;
9015   if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
9016     outs() << " Incorrect size\n";
9017   else
9018     outs() << "\n";
9019   if (dyld.name >= dyld.cmdsize)
9020     outs() << "         name ?(bad offset " << dyld.name << ")\n";
9021   else {
9022     const char *P = (const char *)(Ptr) + dyld.name;
9023     outs() << "         name " << P << " (offset " << dyld.name << ")\n";
9024   }
9025 }
9026 
9027 static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
9028   outs() << "     cmd LC_UUID\n";
9029   outs() << " cmdsize " << uuid.cmdsize;
9030   if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
9031     outs() << " Incorrect size\n";
9032   else
9033     outs() << "\n";
9034   outs() << "    uuid ";
9035   for (int i = 0; i < 16; ++i) {
9036     outs() << format("%02" PRIX32, uuid.uuid[i]);
9037     if (i == 3 || i == 5 || i == 7 || i == 9)
9038       outs() << "-";
9039   }
9040   outs() << "\n";
9041 }
9042 
9043 static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
9044   outs() << "          cmd LC_RPATH\n";
9045   outs() << "      cmdsize " << rpath.cmdsize;
9046   if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
9047     outs() << " Incorrect size\n";
9048   else
9049     outs() << "\n";
9050   if (rpath.path >= rpath.cmdsize)
9051     outs() << "         path ?(bad offset " << rpath.path << ")\n";
9052   else {
9053     const char *P = (const char *)(Ptr) + rpath.path;
9054     outs() << "         path " << P << " (offset " << rpath.path << ")\n";
9055   }
9056 }
9057 
9058 static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
9059   StringRef LoadCmdName;
9060   switch (vd.cmd) {
9061   case MachO::LC_VERSION_MIN_MACOSX:
9062     LoadCmdName = "LC_VERSION_MIN_MACOSX";
9063     break;
9064   case MachO::LC_VERSION_MIN_IPHONEOS:
9065     LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
9066     break;
9067   case MachO::LC_VERSION_MIN_TVOS:
9068     LoadCmdName = "LC_VERSION_MIN_TVOS";
9069     break;
9070   case MachO::LC_VERSION_MIN_WATCHOS:
9071     LoadCmdName = "LC_VERSION_MIN_WATCHOS";
9072     break;
9073   default:
9074     llvm_unreachable("Unknown version min load command");
9075   }
9076 
9077   outs() << "      cmd " << LoadCmdName << '\n';
9078   outs() << "  cmdsize " << vd.cmdsize;
9079   if (vd.cmdsize != sizeof(struct MachO::version_min_command))
9080     outs() << " Incorrect size\n";
9081   else
9082     outs() << "\n";
9083   outs() << "  version "
9084          << MachOObjectFile::getVersionMinMajor(vd, false) << "."
9085          << MachOObjectFile::getVersionMinMinor(vd, false);
9086   uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
9087   if (Update != 0)
9088     outs() << "." << Update;
9089   outs() << "\n";
9090   if (vd.sdk == 0)
9091     outs() << "      sdk n/a";
9092   else {
9093     outs() << "      sdk "
9094            << MachOObjectFile::getVersionMinMajor(vd, true) << "."
9095            << MachOObjectFile::getVersionMinMinor(vd, true);
9096   }
9097   Update = MachOObjectFile::getVersionMinUpdate(vd, true);
9098   if (Update != 0)
9099     outs() << "." << Update;
9100   outs() << "\n";
9101 }
9102 
9103 static void PrintNoteLoadCommand(MachO::note_command Nt) {
9104   outs() << "       cmd LC_NOTE\n";
9105   outs() << "   cmdsize " << Nt.cmdsize;
9106   if (Nt.cmdsize != sizeof(struct MachO::note_command))
9107     outs() << " Incorrect size\n";
9108   else
9109     outs() << "\n";
9110   const char *d = Nt.data_owner;
9111   outs() << "data_owner " << format("%.16s\n", d);
9112   outs() << "    offset " << Nt.offset << "\n";
9113   outs() << "      size " << Nt.size << "\n";
9114 }
9115 
9116 static void PrintBuildToolVersion(MachO::build_tool_version bv) {
9117   outs() << "      tool " << MachOObjectFile::getBuildTool(bv.tool) << "\n";
9118   outs() << "   version " << MachOObjectFile::getVersionString(bv.version)
9119          << "\n";
9120 }
9121 
9122 static void PrintBuildVersionLoadCommand(const MachOObjectFile *obj,
9123                                          MachO::build_version_command bd) {
9124   outs() << "       cmd LC_BUILD_VERSION\n";
9125   outs() << "   cmdsize " << bd.cmdsize;
9126   if (bd.cmdsize !=
9127       sizeof(struct MachO::build_version_command) +
9128           bd.ntools * sizeof(struct MachO::build_tool_version))
9129     outs() << " Incorrect size\n";
9130   else
9131     outs() << "\n";
9132   outs() << "  platform " << MachOObjectFile::getBuildPlatform(bd.platform)
9133          << "\n";
9134   if (bd.sdk)
9135     outs() << "       sdk " << MachOObjectFile::getVersionString(bd.sdk)
9136            << "\n";
9137   else
9138     outs() << "       sdk n/a\n";
9139   outs() << "     minos " << MachOObjectFile::getVersionString(bd.minos)
9140          << "\n";
9141   outs() << "    ntools " << bd.ntools << "\n";
9142   for (unsigned i = 0; i < bd.ntools; ++i) {
9143     MachO::build_tool_version bv = obj->getBuildToolVersion(i);
9144     PrintBuildToolVersion(bv);
9145   }
9146 }
9147 
9148 static void PrintSourceVersionCommand(MachO::source_version_command sd) {
9149   outs() << "      cmd LC_SOURCE_VERSION\n";
9150   outs() << "  cmdsize " << sd.cmdsize;
9151   if (sd.cmdsize != sizeof(struct MachO::source_version_command))
9152     outs() << " Incorrect size\n";
9153   else
9154     outs() << "\n";
9155   uint64_t a = (sd.version >> 40) & 0xffffff;
9156   uint64_t b = (sd.version >> 30) & 0x3ff;
9157   uint64_t c = (sd.version >> 20) & 0x3ff;
9158   uint64_t d = (sd.version >> 10) & 0x3ff;
9159   uint64_t e = sd.version & 0x3ff;
9160   outs() << "  version " << a << "." << b;
9161   if (e != 0)
9162     outs() << "." << c << "." << d << "." << e;
9163   else if (d != 0)
9164     outs() << "." << c << "." << d;
9165   else if (c != 0)
9166     outs() << "." << c;
9167   outs() << "\n";
9168 }
9169 
9170 static void PrintEntryPointCommand(MachO::entry_point_command ep) {
9171   outs() << "       cmd LC_MAIN\n";
9172   outs() << "   cmdsize " << ep.cmdsize;
9173   if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
9174     outs() << " Incorrect size\n";
9175   else
9176     outs() << "\n";
9177   outs() << "  entryoff " << ep.entryoff << "\n";
9178   outs() << " stacksize " << ep.stacksize << "\n";
9179 }
9180 
9181 static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
9182                                        uint32_t object_size) {
9183   outs() << "          cmd LC_ENCRYPTION_INFO\n";
9184   outs() << "      cmdsize " << ec.cmdsize;
9185   if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
9186     outs() << " Incorrect size\n";
9187   else
9188     outs() << "\n";
9189   outs() << "     cryptoff " << ec.cryptoff;
9190   if (ec.cryptoff > object_size)
9191     outs() << " (past end of file)\n";
9192   else
9193     outs() << "\n";
9194   outs() << "    cryptsize " << ec.cryptsize;
9195   if (ec.cryptsize > object_size)
9196     outs() << " (past end of file)\n";
9197   else
9198     outs() << "\n";
9199   outs() << "      cryptid " << ec.cryptid << "\n";
9200 }
9201 
9202 static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
9203                                          uint32_t object_size) {
9204   outs() << "          cmd LC_ENCRYPTION_INFO_64\n";
9205   outs() << "      cmdsize " << ec.cmdsize;
9206   if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
9207     outs() << " Incorrect size\n";
9208   else
9209     outs() << "\n";
9210   outs() << "     cryptoff " << ec.cryptoff;
9211   if (ec.cryptoff > object_size)
9212     outs() << " (past end of file)\n";
9213   else
9214     outs() << "\n";
9215   outs() << "    cryptsize " << ec.cryptsize;
9216   if (ec.cryptsize > object_size)
9217     outs() << " (past end of file)\n";
9218   else
9219     outs() << "\n";
9220   outs() << "      cryptid " << ec.cryptid << "\n";
9221   outs() << "          pad " << ec.pad << "\n";
9222 }
9223 
9224 static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
9225                                      const char *Ptr) {
9226   outs() << "     cmd LC_LINKER_OPTION\n";
9227   outs() << " cmdsize " << lo.cmdsize;
9228   if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
9229     outs() << " Incorrect size\n";
9230   else
9231     outs() << "\n";
9232   outs() << "   count " << lo.count << "\n";
9233   const char *string = Ptr + sizeof(struct MachO::linker_option_command);
9234   uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
9235   uint32_t i = 0;
9236   while (left > 0) {
9237     while (*string == '\0' && left > 0) {
9238       string++;
9239       left--;
9240     }
9241     if (left > 0) {
9242       i++;
9243       outs() << "  string #" << i << " " << format("%.*s\n", left, string);
9244       uint32_t NullPos = StringRef(string, left).find('\0');
9245       uint32_t len = std::min(NullPos, left) + 1;
9246       string += len;
9247       left -= len;
9248     }
9249   }
9250   if (lo.count != i)
9251     outs() << "   count " << lo.count << " does not match number of strings "
9252            << i << "\n";
9253 }
9254 
9255 static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
9256                                      const char *Ptr) {
9257   outs() << "          cmd LC_SUB_FRAMEWORK\n";
9258   outs() << "      cmdsize " << sub.cmdsize;
9259   if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
9260     outs() << " Incorrect size\n";
9261   else
9262     outs() << "\n";
9263   if (sub.umbrella < sub.cmdsize) {
9264     const char *P = Ptr + sub.umbrella;
9265     outs() << "     umbrella " << P << " (offset " << sub.umbrella << ")\n";
9266   } else {
9267     outs() << "     umbrella ?(bad offset " << sub.umbrella << ")\n";
9268   }
9269 }
9270 
9271 static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
9272                                     const char *Ptr) {
9273   outs() << "          cmd LC_SUB_UMBRELLA\n";
9274   outs() << "      cmdsize " << sub.cmdsize;
9275   if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
9276     outs() << " Incorrect size\n";
9277   else
9278     outs() << "\n";
9279   if (sub.sub_umbrella < sub.cmdsize) {
9280     const char *P = Ptr + sub.sub_umbrella;
9281     outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
9282   } else {
9283     outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
9284   }
9285 }
9286 
9287 static void PrintSubLibraryCommand(MachO::sub_library_command sub,
9288                                    const char *Ptr) {
9289   outs() << "          cmd LC_SUB_LIBRARY\n";
9290   outs() << "      cmdsize " << sub.cmdsize;
9291   if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
9292     outs() << " Incorrect size\n";
9293   else
9294     outs() << "\n";
9295   if (sub.sub_library < sub.cmdsize) {
9296     const char *P = Ptr + sub.sub_library;
9297     outs() << "  sub_library " << P << " (offset " << sub.sub_library << ")\n";
9298   } else {
9299     outs() << "  sub_library ?(bad offset " << sub.sub_library << ")\n";
9300   }
9301 }
9302 
9303 static void PrintSubClientCommand(MachO::sub_client_command sub,
9304                                   const char *Ptr) {
9305   outs() << "          cmd LC_SUB_CLIENT\n";
9306   outs() << "      cmdsize " << sub.cmdsize;
9307   if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
9308     outs() << " Incorrect size\n";
9309   else
9310     outs() << "\n";
9311   if (sub.client < sub.cmdsize) {
9312     const char *P = Ptr + sub.client;
9313     outs() << "       client " << P << " (offset " << sub.client << ")\n";
9314   } else {
9315     outs() << "       client ?(bad offset " << sub.client << ")\n";
9316   }
9317 }
9318 
9319 static void PrintRoutinesCommand(MachO::routines_command r) {
9320   outs() << "          cmd LC_ROUTINES\n";
9321   outs() << "      cmdsize " << r.cmdsize;
9322   if (r.cmdsize != sizeof(struct MachO::routines_command))
9323     outs() << " Incorrect size\n";
9324   else
9325     outs() << "\n";
9326   outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
9327   outs() << "  init_module " << r.init_module << "\n";
9328   outs() << "    reserved1 " << r.reserved1 << "\n";
9329   outs() << "    reserved2 " << r.reserved2 << "\n";
9330   outs() << "    reserved3 " << r.reserved3 << "\n";
9331   outs() << "    reserved4 " << r.reserved4 << "\n";
9332   outs() << "    reserved5 " << r.reserved5 << "\n";
9333   outs() << "    reserved6 " << r.reserved6 << "\n";
9334 }
9335 
9336 static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
9337   outs() << "          cmd LC_ROUTINES_64\n";
9338   outs() << "      cmdsize " << r.cmdsize;
9339   if (r.cmdsize != sizeof(struct MachO::routines_command_64))
9340     outs() << " Incorrect size\n";
9341   else
9342     outs() << "\n";
9343   outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
9344   outs() << "  init_module " << r.init_module << "\n";
9345   outs() << "    reserved1 " << r.reserved1 << "\n";
9346   outs() << "    reserved2 " << r.reserved2 << "\n";
9347   outs() << "    reserved3 " << r.reserved3 << "\n";
9348   outs() << "    reserved4 " << r.reserved4 << "\n";
9349   outs() << "    reserved5 " << r.reserved5 << "\n";
9350   outs() << "    reserved6 " << r.reserved6 << "\n";
9351 }
9352 
9353 static void Print_x86_thread_state32_t(MachO::x86_thread_state32_t &cpu32) {
9354   outs() << "\t    eax " << format("0x%08" PRIx32, cpu32.eax);
9355   outs() << " ebx    " << format("0x%08" PRIx32, cpu32.ebx);
9356   outs() << " ecx " << format("0x%08" PRIx32, cpu32.ecx);
9357   outs() << " edx " << format("0x%08" PRIx32, cpu32.edx) << "\n";
9358   outs() << "\t    edi " << format("0x%08" PRIx32, cpu32.edi);
9359   outs() << " esi    " << format("0x%08" PRIx32, cpu32.esi);
9360   outs() << " ebp " << format("0x%08" PRIx32, cpu32.ebp);
9361   outs() << " esp " << format("0x%08" PRIx32, cpu32.esp) << "\n";
9362   outs() << "\t    ss  " << format("0x%08" PRIx32, cpu32.ss);
9363   outs() << " eflags " << format("0x%08" PRIx32, cpu32.eflags);
9364   outs() << " eip " << format("0x%08" PRIx32, cpu32.eip);
9365   outs() << " cs  " << format("0x%08" PRIx32, cpu32.cs) << "\n";
9366   outs() << "\t    ds  " << format("0x%08" PRIx32, cpu32.ds);
9367   outs() << " es     " << format("0x%08" PRIx32, cpu32.es);
9368   outs() << " fs  " << format("0x%08" PRIx32, cpu32.fs);
9369   outs() << " gs  " << format("0x%08" PRIx32, cpu32.gs) << "\n";
9370 }
9371 
9372 static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
9373   outs() << "   rax  " << format("0x%016" PRIx64, cpu64.rax);
9374   outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
9375   outs() << " rcx  " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
9376   outs() << "   rdx  " << format("0x%016" PRIx64, cpu64.rdx);
9377   outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
9378   outs() << " rsi  " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
9379   outs() << "   rbp  " << format("0x%016" PRIx64, cpu64.rbp);
9380   outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
9381   outs() << " r8   " << format("0x%016" PRIx64, cpu64.r8) << "\n";
9382   outs() << "    r9  " << format("0x%016" PRIx64, cpu64.r9);
9383   outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
9384   outs() << " r11  " << format("0x%016" PRIx64, cpu64.r11) << "\n";
9385   outs() << "   r12  " << format("0x%016" PRIx64, cpu64.r12);
9386   outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
9387   outs() << " r14  " << format("0x%016" PRIx64, cpu64.r14) << "\n";
9388   outs() << "   r15  " << format("0x%016" PRIx64, cpu64.r15);
9389   outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
9390   outs() << "rflags  " << format("0x%016" PRIx64, cpu64.rflags);
9391   outs() << " cs  " << format("0x%016" PRIx64, cpu64.cs);
9392   outs() << " fs   " << format("0x%016" PRIx64, cpu64.fs) << "\n";
9393   outs() << "    gs  " << format("0x%016" PRIx64, cpu64.gs) << "\n";
9394 }
9395 
9396 static void Print_mmst_reg(MachO::mmst_reg_t &r) {
9397   uint32_t f;
9398   outs() << "\t      mmst_reg  ";
9399   for (f = 0; f < 10; f++)
9400     outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
9401   outs() << "\n";
9402   outs() << "\t      mmst_rsrv ";
9403   for (f = 0; f < 6; f++)
9404     outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
9405   outs() << "\n";
9406 }
9407 
9408 static void Print_xmm_reg(MachO::xmm_reg_t &r) {
9409   uint32_t f;
9410   outs() << "\t      xmm_reg ";
9411   for (f = 0; f < 16; f++)
9412     outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
9413   outs() << "\n";
9414 }
9415 
9416 static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
9417   outs() << "\t    fpu_reserved[0] " << fpu.fpu_reserved[0];
9418   outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
9419   outs() << "\t    control: invalid " << fpu.fpu_fcw.invalid;
9420   outs() << " denorm " << fpu.fpu_fcw.denorm;
9421   outs() << " zdiv " << fpu.fpu_fcw.zdiv;
9422   outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
9423   outs() << " undfl " << fpu.fpu_fcw.undfl;
9424   outs() << " precis " << fpu.fpu_fcw.precis << "\n";
9425   outs() << "\t\t     pc ";
9426   if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
9427     outs() << "FP_PREC_24B ";
9428   else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
9429     outs() << "FP_PREC_53B ";
9430   else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
9431     outs() << "FP_PREC_64B ";
9432   else
9433     outs() << fpu.fpu_fcw.pc << " ";
9434   outs() << "rc ";
9435   if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
9436     outs() << "FP_RND_NEAR ";
9437   else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
9438     outs() << "FP_RND_DOWN ";
9439   else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
9440     outs() << "FP_RND_UP ";
9441   else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
9442     outs() << "FP_CHOP ";
9443   outs() << "\n";
9444   outs() << "\t    status: invalid " << fpu.fpu_fsw.invalid;
9445   outs() << " denorm " << fpu.fpu_fsw.denorm;
9446   outs() << " zdiv " << fpu.fpu_fsw.zdiv;
9447   outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
9448   outs() << " undfl " << fpu.fpu_fsw.undfl;
9449   outs() << " precis " << fpu.fpu_fsw.precis;
9450   outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
9451   outs() << "\t            errsumm " << fpu.fpu_fsw.errsumm;
9452   outs() << " c0 " << fpu.fpu_fsw.c0;
9453   outs() << " c1 " << fpu.fpu_fsw.c1;
9454   outs() << " c2 " << fpu.fpu_fsw.c2;
9455   outs() << " tos " << fpu.fpu_fsw.tos;
9456   outs() << " c3 " << fpu.fpu_fsw.c3;
9457   outs() << " busy " << fpu.fpu_fsw.busy << "\n";
9458   outs() << "\t    fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
9459   outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
9460   outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
9461   outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
9462   outs() << "\t    fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
9463   outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
9464   outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
9465   outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
9466   outs() << "\t    fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
9467   outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
9468   outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
9469   outs() << "\n";
9470   outs() << "\t    fpu_stmm0:\n";
9471   Print_mmst_reg(fpu.fpu_stmm0);
9472   outs() << "\t    fpu_stmm1:\n";
9473   Print_mmst_reg(fpu.fpu_stmm1);
9474   outs() << "\t    fpu_stmm2:\n";
9475   Print_mmst_reg(fpu.fpu_stmm2);
9476   outs() << "\t    fpu_stmm3:\n";
9477   Print_mmst_reg(fpu.fpu_stmm3);
9478   outs() << "\t    fpu_stmm4:\n";
9479   Print_mmst_reg(fpu.fpu_stmm4);
9480   outs() << "\t    fpu_stmm5:\n";
9481   Print_mmst_reg(fpu.fpu_stmm5);
9482   outs() << "\t    fpu_stmm6:\n";
9483   Print_mmst_reg(fpu.fpu_stmm6);
9484   outs() << "\t    fpu_stmm7:\n";
9485   Print_mmst_reg(fpu.fpu_stmm7);
9486   outs() << "\t    fpu_xmm0:\n";
9487   Print_xmm_reg(fpu.fpu_xmm0);
9488   outs() << "\t    fpu_xmm1:\n";
9489   Print_xmm_reg(fpu.fpu_xmm1);
9490   outs() << "\t    fpu_xmm2:\n";
9491   Print_xmm_reg(fpu.fpu_xmm2);
9492   outs() << "\t    fpu_xmm3:\n";
9493   Print_xmm_reg(fpu.fpu_xmm3);
9494   outs() << "\t    fpu_xmm4:\n";
9495   Print_xmm_reg(fpu.fpu_xmm4);
9496   outs() << "\t    fpu_xmm5:\n";
9497   Print_xmm_reg(fpu.fpu_xmm5);
9498   outs() << "\t    fpu_xmm6:\n";
9499   Print_xmm_reg(fpu.fpu_xmm6);
9500   outs() << "\t    fpu_xmm7:\n";
9501   Print_xmm_reg(fpu.fpu_xmm7);
9502   outs() << "\t    fpu_xmm8:\n";
9503   Print_xmm_reg(fpu.fpu_xmm8);
9504   outs() << "\t    fpu_xmm9:\n";
9505   Print_xmm_reg(fpu.fpu_xmm9);
9506   outs() << "\t    fpu_xmm10:\n";
9507   Print_xmm_reg(fpu.fpu_xmm10);
9508   outs() << "\t    fpu_xmm11:\n";
9509   Print_xmm_reg(fpu.fpu_xmm11);
9510   outs() << "\t    fpu_xmm12:\n";
9511   Print_xmm_reg(fpu.fpu_xmm12);
9512   outs() << "\t    fpu_xmm13:\n";
9513   Print_xmm_reg(fpu.fpu_xmm13);
9514   outs() << "\t    fpu_xmm14:\n";
9515   Print_xmm_reg(fpu.fpu_xmm14);
9516   outs() << "\t    fpu_xmm15:\n";
9517   Print_xmm_reg(fpu.fpu_xmm15);
9518   outs() << "\t    fpu_rsrv4:\n";
9519   for (uint32_t f = 0; f < 6; f++) {
9520     outs() << "\t            ";
9521     for (uint32_t g = 0; g < 16; g++)
9522       outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
9523     outs() << "\n";
9524   }
9525   outs() << "\t    fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
9526   outs() << "\n";
9527 }
9528 
9529 static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
9530   outs() << "\t    trapno " << format("0x%08" PRIx32, exc64.trapno);
9531   outs() << " err " << format("0x%08" PRIx32, exc64.err);
9532   outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
9533 }
9534 
9535 static void Print_arm_thread_state32_t(MachO::arm_thread_state32_t &cpu32) {
9536   outs() << "\t    r0  " << format("0x%08" PRIx32, cpu32.r[0]);
9537   outs() << " r1     "   << format("0x%08" PRIx32, cpu32.r[1]);
9538   outs() << " r2  "      << format("0x%08" PRIx32, cpu32.r[2]);
9539   outs() << " r3  "      << format("0x%08" PRIx32, cpu32.r[3]) << "\n";
9540   outs() << "\t    r4  " << format("0x%08" PRIx32, cpu32.r[4]);
9541   outs() << " r5     "   << format("0x%08" PRIx32, cpu32.r[5]);
9542   outs() << " r6  "      << format("0x%08" PRIx32, cpu32.r[6]);
9543   outs() << " r7  "      << format("0x%08" PRIx32, cpu32.r[7]) << "\n";
9544   outs() << "\t    r8  " << format("0x%08" PRIx32, cpu32.r[8]);
9545   outs() << " r9     "   << format("0x%08" PRIx32, cpu32.r[9]);
9546   outs() << " r10 "      << format("0x%08" PRIx32, cpu32.r[10]);
9547   outs() << " r11 "      << format("0x%08" PRIx32, cpu32.r[11]) << "\n";
9548   outs() << "\t    r12 " << format("0x%08" PRIx32, cpu32.r[12]);
9549   outs() << " sp     "   << format("0x%08" PRIx32, cpu32.sp);
9550   outs() << " lr  "      << format("0x%08" PRIx32, cpu32.lr);
9551   outs() << " pc  "      << format("0x%08" PRIx32, cpu32.pc) << "\n";
9552   outs() << "\t   cpsr " << format("0x%08" PRIx32, cpu32.cpsr) << "\n";
9553 }
9554 
9555 static void Print_arm_thread_state64_t(MachO::arm_thread_state64_t &cpu64) {
9556   outs() << "\t    x0  " << format("0x%016" PRIx64, cpu64.x[0]);
9557   outs() << " x1  "      << format("0x%016" PRIx64, cpu64.x[1]);
9558   outs() << " x2  "      << format("0x%016" PRIx64, cpu64.x[2]) << "\n";
9559   outs() << "\t    x3  " << format("0x%016" PRIx64, cpu64.x[3]);
9560   outs() << " x4  "      << format("0x%016" PRIx64, cpu64.x[4]);
9561   outs() << " x5  "      << format("0x%016" PRIx64, cpu64.x[5]) << "\n";
9562   outs() << "\t    x6  " << format("0x%016" PRIx64, cpu64.x[6]);
9563   outs() << " x7  "      << format("0x%016" PRIx64, cpu64.x[7]);
9564   outs() << " x8  "      << format("0x%016" PRIx64, cpu64.x[8]) << "\n";
9565   outs() << "\t    x9  " << format("0x%016" PRIx64, cpu64.x[9]);
9566   outs() << " x10 "      << format("0x%016" PRIx64, cpu64.x[10]);
9567   outs() << " x11 "      << format("0x%016" PRIx64, cpu64.x[11]) << "\n";
9568   outs() << "\t    x12 " << format("0x%016" PRIx64, cpu64.x[12]);
9569   outs() << " x13 "      << format("0x%016" PRIx64, cpu64.x[13]);
9570   outs() << " x14 "      << format("0x%016" PRIx64, cpu64.x[14]) << "\n";
9571   outs() << "\t    x15 " << format("0x%016" PRIx64, cpu64.x[15]);
9572   outs() << " x16 "      << format("0x%016" PRIx64, cpu64.x[16]);
9573   outs() << " x17 "      << format("0x%016" PRIx64, cpu64.x[17]) << "\n";
9574   outs() << "\t    x18 " << format("0x%016" PRIx64, cpu64.x[18]);
9575   outs() << " x19 "      << format("0x%016" PRIx64, cpu64.x[19]);
9576   outs() << " x20 "      << format("0x%016" PRIx64, cpu64.x[20]) << "\n";
9577   outs() << "\t    x21 " << format("0x%016" PRIx64, cpu64.x[21]);
9578   outs() << " x22 "      << format("0x%016" PRIx64, cpu64.x[22]);
9579   outs() << " x23 "      << format("0x%016" PRIx64, cpu64.x[23]) << "\n";
9580   outs() << "\t    x24 " << format("0x%016" PRIx64, cpu64.x[24]);
9581   outs() << " x25 "      << format("0x%016" PRIx64, cpu64.x[25]);
9582   outs() << " x26 "      << format("0x%016" PRIx64, cpu64.x[26]) << "\n";
9583   outs() << "\t    x27 " << format("0x%016" PRIx64, cpu64.x[27]);
9584   outs() << " x28 "      << format("0x%016" PRIx64, cpu64.x[28]);
9585   outs() << "  fp "      << format("0x%016" PRIx64, cpu64.fp) << "\n";
9586   outs() << "\t     lr " << format("0x%016" PRIx64, cpu64.lr);
9587   outs() << " sp  "      << format("0x%016" PRIx64, cpu64.sp);
9588   outs() << "  pc "      << format("0x%016" PRIx64, cpu64.pc) << "\n";
9589   outs() << "\t   cpsr " << format("0x%08"  PRIx32, cpu64.cpsr) << "\n";
9590 }
9591 
9592 static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
9593                                bool isLittleEndian, uint32_t cputype) {
9594   if (t.cmd == MachO::LC_THREAD)
9595     outs() << "        cmd LC_THREAD\n";
9596   else if (t.cmd == MachO::LC_UNIXTHREAD)
9597     outs() << "        cmd LC_UNIXTHREAD\n";
9598   else
9599     outs() << "        cmd " << t.cmd << " (unknown)\n";
9600   outs() << "    cmdsize " << t.cmdsize;
9601   if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
9602     outs() << " Incorrect size\n";
9603   else
9604     outs() << "\n";
9605 
9606   const char *begin = Ptr + sizeof(struct MachO::thread_command);
9607   const char *end = Ptr + t.cmdsize;
9608   uint32_t flavor, count, left;
9609   if (cputype == MachO::CPU_TYPE_I386) {
9610     while (begin < end) {
9611       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9612         memcpy((char *)&flavor, begin, sizeof(uint32_t));
9613         begin += sizeof(uint32_t);
9614       } else {
9615         flavor = 0;
9616         begin = end;
9617       }
9618       if (isLittleEndian != sys::IsLittleEndianHost)
9619         sys::swapByteOrder(flavor);
9620       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9621         memcpy((char *)&count, begin, sizeof(uint32_t));
9622         begin += sizeof(uint32_t);
9623       } else {
9624         count = 0;
9625         begin = end;
9626       }
9627       if (isLittleEndian != sys::IsLittleEndianHost)
9628         sys::swapByteOrder(count);
9629       if (flavor == MachO::x86_THREAD_STATE32) {
9630         outs() << "     flavor i386_THREAD_STATE\n";
9631         if (count == MachO::x86_THREAD_STATE32_COUNT)
9632           outs() << "      count i386_THREAD_STATE_COUNT\n";
9633         else
9634           outs() << "      count " << count
9635                  << " (not x86_THREAD_STATE32_COUNT)\n";
9636         MachO::x86_thread_state32_t cpu32;
9637         left = end - begin;
9638         if (left >= sizeof(MachO::x86_thread_state32_t)) {
9639           memcpy(&cpu32, begin, sizeof(MachO::x86_thread_state32_t));
9640           begin += sizeof(MachO::x86_thread_state32_t);
9641         } else {
9642           memset(&cpu32, '\0', sizeof(MachO::x86_thread_state32_t));
9643           memcpy(&cpu32, begin, left);
9644           begin += left;
9645         }
9646         if (isLittleEndian != sys::IsLittleEndianHost)
9647           swapStruct(cpu32);
9648         Print_x86_thread_state32_t(cpu32);
9649       } else if (flavor == MachO::x86_THREAD_STATE) {
9650         outs() << "     flavor x86_THREAD_STATE\n";
9651         if (count == MachO::x86_THREAD_STATE_COUNT)
9652           outs() << "      count x86_THREAD_STATE_COUNT\n";
9653         else
9654           outs() << "      count " << count
9655                  << " (not x86_THREAD_STATE_COUNT)\n";
9656         struct MachO::x86_thread_state_t ts;
9657         left = end - begin;
9658         if (left >= sizeof(MachO::x86_thread_state_t)) {
9659           memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
9660           begin += sizeof(MachO::x86_thread_state_t);
9661         } else {
9662           memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
9663           memcpy(&ts, begin, left);
9664           begin += left;
9665         }
9666         if (isLittleEndian != sys::IsLittleEndianHost)
9667           swapStruct(ts);
9668         if (ts.tsh.flavor == MachO::x86_THREAD_STATE32) {
9669           outs() << "\t    tsh.flavor x86_THREAD_STATE32 ";
9670           if (ts.tsh.count == MachO::x86_THREAD_STATE32_COUNT)
9671             outs() << "tsh.count x86_THREAD_STATE32_COUNT\n";
9672           else
9673             outs() << "tsh.count " << ts.tsh.count
9674                    << " (not x86_THREAD_STATE32_COUNT\n";
9675           Print_x86_thread_state32_t(ts.uts.ts32);
9676         } else {
9677           outs() << "\t    tsh.flavor " << ts.tsh.flavor << "  tsh.count "
9678                  << ts.tsh.count << "\n";
9679         }
9680       } else {
9681         outs() << "     flavor " << flavor << " (unknown)\n";
9682         outs() << "      count " << count << "\n";
9683         outs() << "      state (unknown)\n";
9684         begin += count * sizeof(uint32_t);
9685       }
9686     }
9687   } else if (cputype == MachO::CPU_TYPE_X86_64) {
9688     while (begin < end) {
9689       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9690         memcpy((char *)&flavor, begin, sizeof(uint32_t));
9691         begin += sizeof(uint32_t);
9692       } else {
9693         flavor = 0;
9694         begin = end;
9695       }
9696       if (isLittleEndian != sys::IsLittleEndianHost)
9697         sys::swapByteOrder(flavor);
9698       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9699         memcpy((char *)&count, begin, sizeof(uint32_t));
9700         begin += sizeof(uint32_t);
9701       } else {
9702         count = 0;
9703         begin = end;
9704       }
9705       if (isLittleEndian != sys::IsLittleEndianHost)
9706         sys::swapByteOrder(count);
9707       if (flavor == MachO::x86_THREAD_STATE64) {
9708         outs() << "     flavor x86_THREAD_STATE64\n";
9709         if (count == MachO::x86_THREAD_STATE64_COUNT)
9710           outs() << "      count x86_THREAD_STATE64_COUNT\n";
9711         else
9712           outs() << "      count " << count
9713                  << " (not x86_THREAD_STATE64_COUNT)\n";
9714         MachO::x86_thread_state64_t cpu64;
9715         left = end - begin;
9716         if (left >= sizeof(MachO::x86_thread_state64_t)) {
9717           memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
9718           begin += sizeof(MachO::x86_thread_state64_t);
9719         } else {
9720           memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
9721           memcpy(&cpu64, begin, left);
9722           begin += left;
9723         }
9724         if (isLittleEndian != sys::IsLittleEndianHost)
9725           swapStruct(cpu64);
9726         Print_x86_thread_state64_t(cpu64);
9727       } else if (flavor == MachO::x86_THREAD_STATE) {
9728         outs() << "     flavor x86_THREAD_STATE\n";
9729         if (count == MachO::x86_THREAD_STATE_COUNT)
9730           outs() << "      count x86_THREAD_STATE_COUNT\n";
9731         else
9732           outs() << "      count " << count
9733                  << " (not x86_THREAD_STATE_COUNT)\n";
9734         struct MachO::x86_thread_state_t ts;
9735         left = end - begin;
9736         if (left >= sizeof(MachO::x86_thread_state_t)) {
9737           memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
9738           begin += sizeof(MachO::x86_thread_state_t);
9739         } else {
9740           memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
9741           memcpy(&ts, begin, left);
9742           begin += left;
9743         }
9744         if (isLittleEndian != sys::IsLittleEndianHost)
9745           swapStruct(ts);
9746         if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
9747           outs() << "\t    tsh.flavor x86_THREAD_STATE64 ";
9748           if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
9749             outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
9750           else
9751             outs() << "tsh.count " << ts.tsh.count
9752                    << " (not x86_THREAD_STATE64_COUNT\n";
9753           Print_x86_thread_state64_t(ts.uts.ts64);
9754         } else {
9755           outs() << "\t    tsh.flavor " << ts.tsh.flavor << "  tsh.count "
9756                  << ts.tsh.count << "\n";
9757         }
9758       } else if (flavor == MachO::x86_FLOAT_STATE) {
9759         outs() << "     flavor x86_FLOAT_STATE\n";
9760         if (count == MachO::x86_FLOAT_STATE_COUNT)
9761           outs() << "      count x86_FLOAT_STATE_COUNT\n";
9762         else
9763           outs() << "      count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
9764         struct MachO::x86_float_state_t fs;
9765         left = end - begin;
9766         if (left >= sizeof(MachO::x86_float_state_t)) {
9767           memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
9768           begin += sizeof(MachO::x86_float_state_t);
9769         } else {
9770           memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
9771           memcpy(&fs, begin, left);
9772           begin += left;
9773         }
9774         if (isLittleEndian != sys::IsLittleEndianHost)
9775           swapStruct(fs);
9776         if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
9777           outs() << "\t    fsh.flavor x86_FLOAT_STATE64 ";
9778           if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
9779             outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
9780           else
9781             outs() << "fsh.count " << fs.fsh.count
9782                    << " (not x86_FLOAT_STATE64_COUNT\n";
9783           Print_x86_float_state_t(fs.ufs.fs64);
9784         } else {
9785           outs() << "\t    fsh.flavor " << fs.fsh.flavor << "  fsh.count "
9786                  << fs.fsh.count << "\n";
9787         }
9788       } else if (flavor == MachO::x86_EXCEPTION_STATE) {
9789         outs() << "     flavor x86_EXCEPTION_STATE\n";
9790         if (count == MachO::x86_EXCEPTION_STATE_COUNT)
9791           outs() << "      count x86_EXCEPTION_STATE_COUNT\n";
9792         else
9793           outs() << "      count " << count
9794                  << " (not x86_EXCEPTION_STATE_COUNT)\n";
9795         struct MachO::x86_exception_state_t es;
9796         left = end - begin;
9797         if (left >= sizeof(MachO::x86_exception_state_t)) {
9798           memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
9799           begin += sizeof(MachO::x86_exception_state_t);
9800         } else {
9801           memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
9802           memcpy(&es, begin, left);
9803           begin += left;
9804         }
9805         if (isLittleEndian != sys::IsLittleEndianHost)
9806           swapStruct(es);
9807         if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
9808           outs() << "\t    esh.flavor x86_EXCEPTION_STATE64\n";
9809           if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
9810             outs() << "\t    esh.count x86_EXCEPTION_STATE64_COUNT\n";
9811           else
9812             outs() << "\t    esh.count " << es.esh.count
9813                    << " (not x86_EXCEPTION_STATE64_COUNT\n";
9814           Print_x86_exception_state_t(es.ues.es64);
9815         } else {
9816           outs() << "\t    esh.flavor " << es.esh.flavor << "  esh.count "
9817                  << es.esh.count << "\n";
9818         }
9819       } else if (flavor == MachO::x86_EXCEPTION_STATE64) {
9820         outs() << "     flavor x86_EXCEPTION_STATE64\n";
9821         if (count == MachO::x86_EXCEPTION_STATE64_COUNT)
9822           outs() << "      count x86_EXCEPTION_STATE64_COUNT\n";
9823         else
9824           outs() << "      count " << count
9825                  << " (not x86_EXCEPTION_STATE64_COUNT)\n";
9826         struct MachO::x86_exception_state64_t es64;
9827         left = end - begin;
9828         if (left >= sizeof(MachO::x86_exception_state64_t)) {
9829           memcpy(&es64, begin, sizeof(MachO::x86_exception_state64_t));
9830           begin += sizeof(MachO::x86_exception_state64_t);
9831         } else {
9832           memset(&es64, '\0', sizeof(MachO::x86_exception_state64_t));
9833           memcpy(&es64, begin, left);
9834           begin += left;
9835         }
9836         if (isLittleEndian != sys::IsLittleEndianHost)
9837           swapStruct(es64);
9838         Print_x86_exception_state_t(es64);
9839       } else {
9840         outs() << "     flavor " << flavor << " (unknown)\n";
9841         outs() << "      count " << count << "\n";
9842         outs() << "      state (unknown)\n";
9843         begin += count * sizeof(uint32_t);
9844       }
9845     }
9846   } else if (cputype == MachO::CPU_TYPE_ARM) {
9847     while (begin < end) {
9848       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9849         memcpy((char *)&flavor, begin, sizeof(uint32_t));
9850         begin += sizeof(uint32_t);
9851       } else {
9852         flavor = 0;
9853         begin = end;
9854       }
9855       if (isLittleEndian != sys::IsLittleEndianHost)
9856         sys::swapByteOrder(flavor);
9857       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9858         memcpy((char *)&count, begin, sizeof(uint32_t));
9859         begin += sizeof(uint32_t);
9860       } else {
9861         count = 0;
9862         begin = end;
9863       }
9864       if (isLittleEndian != sys::IsLittleEndianHost)
9865         sys::swapByteOrder(count);
9866       if (flavor == MachO::ARM_THREAD_STATE) {
9867         outs() << "     flavor ARM_THREAD_STATE\n";
9868         if (count == MachO::ARM_THREAD_STATE_COUNT)
9869           outs() << "      count ARM_THREAD_STATE_COUNT\n";
9870         else
9871           outs() << "      count " << count
9872                  << " (not ARM_THREAD_STATE_COUNT)\n";
9873         MachO::arm_thread_state32_t cpu32;
9874         left = end - begin;
9875         if (left >= sizeof(MachO::arm_thread_state32_t)) {
9876           memcpy(&cpu32, begin, sizeof(MachO::arm_thread_state32_t));
9877           begin += sizeof(MachO::arm_thread_state32_t);
9878         } else {
9879           memset(&cpu32, '\0', sizeof(MachO::arm_thread_state32_t));
9880           memcpy(&cpu32, begin, left);
9881           begin += left;
9882         }
9883         if (isLittleEndian != sys::IsLittleEndianHost)
9884           swapStruct(cpu32);
9885         Print_arm_thread_state32_t(cpu32);
9886       } else {
9887         outs() << "     flavor " << flavor << " (unknown)\n";
9888         outs() << "      count " << count << "\n";
9889         outs() << "      state (unknown)\n";
9890         begin += count * sizeof(uint32_t);
9891       }
9892     }
9893   } else if (cputype == MachO::CPU_TYPE_ARM64 ||
9894              cputype == MachO::CPU_TYPE_ARM64_32) {
9895     while (begin < end) {
9896       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9897         memcpy((char *)&flavor, begin, sizeof(uint32_t));
9898         begin += sizeof(uint32_t);
9899       } else {
9900         flavor = 0;
9901         begin = end;
9902       }
9903       if (isLittleEndian != sys::IsLittleEndianHost)
9904         sys::swapByteOrder(flavor);
9905       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9906         memcpy((char *)&count, begin, sizeof(uint32_t));
9907         begin += sizeof(uint32_t);
9908       } else {
9909         count = 0;
9910         begin = end;
9911       }
9912       if (isLittleEndian != sys::IsLittleEndianHost)
9913         sys::swapByteOrder(count);
9914       if (flavor == MachO::ARM_THREAD_STATE64) {
9915         outs() << "     flavor ARM_THREAD_STATE64\n";
9916         if (count == MachO::ARM_THREAD_STATE64_COUNT)
9917           outs() << "      count ARM_THREAD_STATE64_COUNT\n";
9918         else
9919           outs() << "      count " << count
9920                  << " (not ARM_THREAD_STATE64_COUNT)\n";
9921         MachO::arm_thread_state64_t cpu64;
9922         left = end - begin;
9923         if (left >= sizeof(MachO::arm_thread_state64_t)) {
9924           memcpy(&cpu64, begin, sizeof(MachO::arm_thread_state64_t));
9925           begin += sizeof(MachO::arm_thread_state64_t);
9926         } else {
9927           memset(&cpu64, '\0', sizeof(MachO::arm_thread_state64_t));
9928           memcpy(&cpu64, begin, left);
9929           begin += left;
9930         }
9931         if (isLittleEndian != sys::IsLittleEndianHost)
9932           swapStruct(cpu64);
9933         Print_arm_thread_state64_t(cpu64);
9934       } else {
9935         outs() << "     flavor " << flavor << " (unknown)\n";
9936         outs() << "      count " << count << "\n";
9937         outs() << "      state (unknown)\n";
9938         begin += count * sizeof(uint32_t);
9939       }
9940     }
9941   } else {
9942     while (begin < end) {
9943       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9944         memcpy((char *)&flavor, begin, sizeof(uint32_t));
9945         begin += sizeof(uint32_t);
9946       } else {
9947         flavor = 0;
9948         begin = end;
9949       }
9950       if (isLittleEndian != sys::IsLittleEndianHost)
9951         sys::swapByteOrder(flavor);
9952       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9953         memcpy((char *)&count, begin, sizeof(uint32_t));
9954         begin += sizeof(uint32_t);
9955       } else {
9956         count = 0;
9957         begin = end;
9958       }
9959       if (isLittleEndian != sys::IsLittleEndianHost)
9960         sys::swapByteOrder(count);
9961       outs() << "     flavor " << flavor << "\n";
9962       outs() << "      count " << count << "\n";
9963       outs() << "      state (Unknown cputype/cpusubtype)\n";
9964       begin += count * sizeof(uint32_t);
9965     }
9966   }
9967 }
9968 
9969 static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
9970   if (dl.cmd == MachO::LC_ID_DYLIB)
9971     outs() << "          cmd LC_ID_DYLIB\n";
9972   else if (dl.cmd == MachO::LC_LOAD_DYLIB)
9973     outs() << "          cmd LC_LOAD_DYLIB\n";
9974   else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
9975     outs() << "          cmd LC_LOAD_WEAK_DYLIB\n";
9976   else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
9977     outs() << "          cmd LC_REEXPORT_DYLIB\n";
9978   else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
9979     outs() << "          cmd LC_LAZY_LOAD_DYLIB\n";
9980   else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
9981     outs() << "          cmd LC_LOAD_UPWARD_DYLIB\n";
9982   else
9983     outs() << "          cmd " << dl.cmd << " (unknown)\n";
9984   outs() << "      cmdsize " << dl.cmdsize;
9985   if (dl.cmdsize < sizeof(struct MachO::dylib_command))
9986     outs() << " Incorrect size\n";
9987   else
9988     outs() << "\n";
9989   if (dl.dylib.name < dl.cmdsize) {
9990     const char *P = (const char *)(Ptr) + dl.dylib.name;
9991     outs() << "         name " << P << " (offset " << dl.dylib.name << ")\n";
9992   } else {
9993     outs() << "         name ?(bad offset " << dl.dylib.name << ")\n";
9994   }
9995   outs() << "   time stamp " << dl.dylib.timestamp << " ";
9996   time_t t = dl.dylib.timestamp;
9997   outs() << ctime(&t);
9998   outs() << "      current version ";
9999   if (dl.dylib.current_version == 0xffffffff)
10000     outs() << "n/a\n";
10001   else
10002     outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
10003            << ((dl.dylib.current_version >> 8) & 0xff) << "."
10004            << (dl.dylib.current_version & 0xff) << "\n";
10005   outs() << "compatibility version ";
10006   if (dl.dylib.compatibility_version == 0xffffffff)
10007     outs() << "n/a\n";
10008   else
10009     outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
10010            << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
10011            << (dl.dylib.compatibility_version & 0xff) << "\n";
10012 }
10013 
10014 static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
10015                                      uint32_t object_size) {
10016   if (ld.cmd == MachO::LC_CODE_SIGNATURE)
10017     outs() << "      cmd LC_CODE_SIGNATURE\n";
10018   else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
10019     outs() << "      cmd LC_SEGMENT_SPLIT_INFO\n";
10020   else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
10021     outs() << "      cmd LC_FUNCTION_STARTS\n";
10022   else if (ld.cmd == MachO::LC_DATA_IN_CODE)
10023     outs() << "      cmd LC_DATA_IN_CODE\n";
10024   else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
10025     outs() << "      cmd LC_DYLIB_CODE_SIGN_DRS\n";
10026   else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
10027     outs() << "      cmd LC_LINKER_OPTIMIZATION_HINT\n";
10028   else
10029     outs() << "      cmd " << ld.cmd << " (?)\n";
10030   outs() << "  cmdsize " << ld.cmdsize;
10031   if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
10032     outs() << " Incorrect size\n";
10033   else
10034     outs() << "\n";
10035   outs() << "  dataoff " << ld.dataoff;
10036   if (ld.dataoff > object_size)
10037     outs() << " (past end of file)\n";
10038   else
10039     outs() << "\n";
10040   outs() << " datasize " << ld.datasize;
10041   uint64_t big_size = ld.dataoff;
10042   big_size += ld.datasize;
10043   if (big_size > object_size)
10044     outs() << " (past end of file)\n";
10045   else
10046     outs() << "\n";
10047 }
10048 
10049 static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
10050                               uint32_t cputype, bool verbose) {
10051   StringRef Buf = Obj->getData();
10052   unsigned Index = 0;
10053   for (const auto &Command : Obj->load_commands()) {
10054     outs() << "Load command " << Index++ << "\n";
10055     if (Command.C.cmd == MachO::LC_SEGMENT) {
10056       MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
10057       const char *sg_segname = SLC.segname;
10058       PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
10059                           SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
10060                           SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
10061                           verbose);
10062       for (unsigned j = 0; j < SLC.nsects; j++) {
10063         MachO::section S = Obj->getSection(Command, j);
10064         PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
10065                      S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
10066                      SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
10067       }
10068     } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
10069       MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
10070       const char *sg_segname = SLC_64.segname;
10071       PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
10072                           SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
10073                           SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
10074                           SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
10075       for (unsigned j = 0; j < SLC_64.nsects; j++) {
10076         MachO::section_64 S_64 = Obj->getSection64(Command, j);
10077         PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
10078                      S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
10079                      S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
10080                      sg_segname, filetype, Buf.size(), verbose);
10081       }
10082     } else if (Command.C.cmd == MachO::LC_SYMTAB) {
10083       MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
10084       PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
10085     } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
10086       MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
10087       MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
10088       PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
10089                                Obj->is64Bit());
10090     } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
10091                Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
10092       MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
10093       PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
10094     } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
10095                Command.C.cmd == MachO::LC_ID_DYLINKER ||
10096                Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
10097       MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
10098       PrintDyldLoadCommand(Dyld, Command.Ptr);
10099     } else if (Command.C.cmd == MachO::LC_UUID) {
10100       MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
10101       PrintUuidLoadCommand(Uuid);
10102     } else if (Command.C.cmd == MachO::LC_RPATH) {
10103       MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
10104       PrintRpathLoadCommand(Rpath, Command.Ptr);
10105     } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
10106                Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
10107                Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
10108                Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
10109       MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
10110       PrintVersionMinLoadCommand(Vd);
10111     } else if (Command.C.cmd == MachO::LC_NOTE) {
10112       MachO::note_command Nt = Obj->getNoteLoadCommand(Command);
10113       PrintNoteLoadCommand(Nt);
10114     } else if (Command.C.cmd == MachO::LC_BUILD_VERSION) {
10115       MachO::build_version_command Bv =
10116           Obj->getBuildVersionLoadCommand(Command);
10117       PrintBuildVersionLoadCommand(Obj, Bv);
10118     } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
10119       MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
10120       PrintSourceVersionCommand(Sd);
10121     } else if (Command.C.cmd == MachO::LC_MAIN) {
10122       MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
10123       PrintEntryPointCommand(Ep);
10124     } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
10125       MachO::encryption_info_command Ei =
10126           Obj->getEncryptionInfoCommand(Command);
10127       PrintEncryptionInfoCommand(Ei, Buf.size());
10128     } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
10129       MachO::encryption_info_command_64 Ei =
10130           Obj->getEncryptionInfoCommand64(Command);
10131       PrintEncryptionInfoCommand64(Ei, Buf.size());
10132     } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
10133       MachO::linker_option_command Lo =
10134           Obj->getLinkerOptionLoadCommand(Command);
10135       PrintLinkerOptionCommand(Lo, Command.Ptr);
10136     } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
10137       MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
10138       PrintSubFrameworkCommand(Sf, Command.Ptr);
10139     } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
10140       MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
10141       PrintSubUmbrellaCommand(Sf, Command.Ptr);
10142     } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
10143       MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
10144       PrintSubLibraryCommand(Sl, Command.Ptr);
10145     } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
10146       MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
10147       PrintSubClientCommand(Sc, Command.Ptr);
10148     } else if (Command.C.cmd == MachO::LC_ROUTINES) {
10149       MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
10150       PrintRoutinesCommand(Rc);
10151     } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
10152       MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
10153       PrintRoutinesCommand64(Rc);
10154     } else if (Command.C.cmd == MachO::LC_THREAD ||
10155                Command.C.cmd == MachO::LC_UNIXTHREAD) {
10156       MachO::thread_command Tc = Obj->getThreadCommand(Command);
10157       PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
10158     } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
10159                Command.C.cmd == MachO::LC_ID_DYLIB ||
10160                Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
10161                Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
10162                Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
10163                Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
10164       MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
10165       PrintDylibCommand(Dl, Command.Ptr);
10166     } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
10167                Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
10168                Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
10169                Command.C.cmd == MachO::LC_DATA_IN_CODE ||
10170                Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
10171                Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
10172       MachO::linkedit_data_command Ld =
10173           Obj->getLinkeditDataLoadCommand(Command);
10174       PrintLinkEditDataCommand(Ld, Buf.size());
10175     } else {
10176       outs() << "      cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
10177              << ")\n";
10178       outs() << "  cmdsize " << Command.C.cmdsize << "\n";
10179       // TODO: get and print the raw bytes of the load command.
10180     }
10181     // TODO: print all the other kinds of load commands.
10182   }
10183 }
10184 
10185 static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
10186   if (Obj->is64Bit()) {
10187     MachO::mach_header_64 H_64;
10188     H_64 = Obj->getHeader64();
10189     PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
10190                     H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
10191   } else {
10192     MachO::mach_header H;
10193     H = Obj->getHeader();
10194     PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
10195                     H.sizeofcmds, H.flags, verbose);
10196   }
10197 }
10198 
10199 void printMachOFileHeader(const object::ObjectFile *Obj) {
10200   const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
10201   PrintMachHeader(file, !NonVerbose);
10202 }
10203 
10204 void printMachOLoadCommands(const object::ObjectFile *Obj) {
10205   const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
10206   uint32_t filetype = 0;
10207   uint32_t cputype = 0;
10208   if (file->is64Bit()) {
10209     MachO::mach_header_64 H_64;
10210     H_64 = file->getHeader64();
10211     filetype = H_64.filetype;
10212     cputype = H_64.cputype;
10213   } else {
10214     MachO::mach_header H;
10215     H = file->getHeader();
10216     filetype = H.filetype;
10217     cputype = H.cputype;
10218   }
10219   PrintLoadCommands(file, filetype, cputype, !NonVerbose);
10220 }
10221 
10222 //===----------------------------------------------------------------------===//
10223 // export trie dumping
10224 //===----------------------------------------------------------------------===//
10225 
10226 void printMachOExportsTrie(const object::MachOObjectFile *Obj) {
10227   uint64_t BaseSegmentAddress = 0;
10228   for (const auto &Command : Obj->load_commands()) {
10229     if (Command.C.cmd == MachO::LC_SEGMENT) {
10230       MachO::segment_command Seg = Obj->getSegmentLoadCommand(Command);
10231       if (Seg.fileoff == 0 && Seg.filesize != 0) {
10232         BaseSegmentAddress = Seg.vmaddr;
10233         break;
10234       }
10235     } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
10236       MachO::segment_command_64 Seg = Obj->getSegment64LoadCommand(Command);
10237       if (Seg.fileoff == 0 && Seg.filesize != 0) {
10238         BaseSegmentAddress = Seg.vmaddr;
10239         break;
10240       }
10241     }
10242   }
10243   Error Err = Error::success();
10244   for (const object::ExportEntry &Entry : Obj->exports(Err)) {
10245     uint64_t Flags = Entry.flags();
10246     bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
10247     bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
10248     bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
10249                         MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
10250     bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
10251                 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
10252     bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
10253     if (ReExport)
10254       outs() << "[re-export] ";
10255     else
10256       outs() << format("0x%08llX  ",
10257                        Entry.address() + BaseSegmentAddress);
10258     outs() << Entry.name();
10259     if (WeakDef || ThreadLocal || Resolver || Abs) {
10260       bool NeedsComma = false;
10261       outs() << " [";
10262       if (WeakDef) {
10263         outs() << "weak_def";
10264         NeedsComma = true;
10265       }
10266       if (ThreadLocal) {
10267         if (NeedsComma)
10268           outs() << ", ";
10269         outs() << "per-thread";
10270         NeedsComma = true;
10271       }
10272       if (Abs) {
10273         if (NeedsComma)
10274           outs() << ", ";
10275         outs() << "absolute";
10276         NeedsComma = true;
10277       }
10278       if (Resolver) {
10279         if (NeedsComma)
10280           outs() << ", ";
10281         outs() << format("resolver=0x%08llX", Entry.other());
10282         NeedsComma = true;
10283       }
10284       outs() << "]";
10285     }
10286     if (ReExport) {
10287       StringRef DylibName = "unknown";
10288       int Ordinal = Entry.other() - 1;
10289       Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
10290       if (Entry.otherName().empty())
10291         outs() << " (from " << DylibName << ")";
10292       else
10293         outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
10294     }
10295     outs() << "\n";
10296   }
10297   if (Err)
10298     reportError(std::move(Err), Obj->getFileName());
10299 }
10300 
10301 //===----------------------------------------------------------------------===//
10302 // rebase table dumping
10303 //===----------------------------------------------------------------------===//
10304 
10305 void printMachORebaseTable(object::MachOObjectFile *Obj) {
10306   outs() << "segment  section            address     type\n";
10307   Error Err = Error::success();
10308   for (const object::MachORebaseEntry &Entry : Obj->rebaseTable(Err)) {
10309     StringRef SegmentName = Entry.segmentName();
10310     StringRef SectionName = Entry.sectionName();
10311     uint64_t Address = Entry.address();
10312 
10313     // Table lines look like: __DATA  __nl_symbol_ptr  0x0000F00C  pointer
10314     outs() << format("%-8s %-18s 0x%08" PRIX64 "  %s\n",
10315                      SegmentName.str().c_str(), SectionName.str().c_str(),
10316                      Address, Entry.typeName().str().c_str());
10317   }
10318   if (Err)
10319     reportError(std::move(Err), Obj->getFileName());
10320 }
10321 
10322 static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
10323   StringRef DylibName;
10324   switch (Ordinal) {
10325   case MachO::BIND_SPECIAL_DYLIB_SELF:
10326     return "this-image";
10327   case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
10328     return "main-executable";
10329   case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
10330     return "flat-namespace";
10331   default:
10332     if (Ordinal > 0) {
10333       std::error_code EC =
10334           Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
10335       if (EC)
10336         return "<<bad library ordinal>>";
10337       return DylibName;
10338     }
10339   }
10340   return "<<unknown special ordinal>>";
10341 }
10342 
10343 //===----------------------------------------------------------------------===//
10344 // bind table dumping
10345 //===----------------------------------------------------------------------===//
10346 
10347 void printMachOBindTable(object::MachOObjectFile *Obj) {
10348   // Build table of sections so names can used in final output.
10349   outs() << "segment  section            address    type       "
10350             "addend dylib            symbol\n";
10351   Error Err = Error::success();
10352   for (const object::MachOBindEntry &Entry : Obj->bindTable(Err)) {
10353     StringRef SegmentName = Entry.segmentName();
10354     StringRef SectionName = Entry.sectionName();
10355     uint64_t Address = Entry.address();
10356 
10357     // Table lines look like:
10358     //  __DATA  __got  0x00012010    pointer   0 libSystem ___stack_chk_guard
10359     StringRef Attr;
10360     if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
10361       Attr = " (weak_import)";
10362     outs() << left_justify(SegmentName, 8) << " "
10363            << left_justify(SectionName, 18) << " "
10364            << format_hex(Address, 10, true) << " "
10365            << left_justify(Entry.typeName(), 8) << " "
10366            << format_decimal(Entry.addend(), 8) << " "
10367            << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
10368            << Entry.symbolName() << Attr << "\n";
10369   }
10370   if (Err)
10371     reportError(std::move(Err), Obj->getFileName());
10372 }
10373 
10374 //===----------------------------------------------------------------------===//
10375 // lazy bind table dumping
10376 //===----------------------------------------------------------------------===//
10377 
10378 void printMachOLazyBindTable(object::MachOObjectFile *Obj) {
10379   outs() << "segment  section            address     "
10380             "dylib            symbol\n";
10381   Error Err = Error::success();
10382   for (const object::MachOBindEntry &Entry : Obj->lazyBindTable(Err)) {
10383     StringRef SegmentName = Entry.segmentName();
10384     StringRef SectionName = Entry.sectionName();
10385     uint64_t Address = Entry.address();
10386 
10387     // Table lines look like:
10388     //  __DATA  __got  0x00012010 libSystem ___stack_chk_guard
10389     outs() << left_justify(SegmentName, 8) << " "
10390            << left_justify(SectionName, 18) << " "
10391            << format_hex(Address, 10, true) << " "
10392            << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
10393            << Entry.symbolName() << "\n";
10394   }
10395   if (Err)
10396     reportError(std::move(Err), Obj->getFileName());
10397 }
10398 
10399 //===----------------------------------------------------------------------===//
10400 // weak bind table dumping
10401 //===----------------------------------------------------------------------===//
10402 
10403 void printMachOWeakBindTable(object::MachOObjectFile *Obj) {
10404   outs() << "segment  section            address     "
10405             "type       addend   symbol\n";
10406   Error Err = Error::success();
10407   for (const object::MachOBindEntry &Entry : Obj->weakBindTable(Err)) {
10408     // Strong symbols don't have a location to update.
10409     if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
10410       outs() << "                                        strong              "
10411              << Entry.symbolName() << "\n";
10412       continue;
10413     }
10414     StringRef SegmentName = Entry.segmentName();
10415     StringRef SectionName = Entry.sectionName();
10416     uint64_t Address = Entry.address();
10417 
10418     // Table lines look like:
10419     // __DATA  __data  0x00001000  pointer    0   _foo
10420     outs() << left_justify(SegmentName, 8) << " "
10421            << left_justify(SectionName, 18) << " "
10422            << format_hex(Address, 10, true) << " "
10423            << left_justify(Entry.typeName(), 8) << " "
10424            << format_decimal(Entry.addend(), 8) << "   " << Entry.symbolName()
10425            << "\n";
10426   }
10427   if (Err)
10428     reportError(std::move(Err), Obj->getFileName());
10429 }
10430 
10431 // get_dyld_bind_info_symbolname() is used for disassembly and passed an
10432 // address, ReferenceValue, in the Mach-O file and looks in the dyld bind
10433 // information for that address. If the address is found its binding symbol
10434 // name is returned.  If not nullptr is returned.
10435 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
10436                                                  struct DisassembleInfo *info) {
10437   if (info->bindtable == nullptr) {
10438     info->bindtable = std::make_unique<SymbolAddressMap>();
10439     Error Err = Error::success();
10440     for (const object::MachOBindEntry &Entry : info->O->bindTable(Err)) {
10441       uint64_t Address = Entry.address();
10442       StringRef name = Entry.symbolName();
10443       if (!name.empty())
10444         (*info->bindtable)[Address] = name;
10445     }
10446     if (Err)
10447       reportError(std::move(Err), info->O->getFileName());
10448   }
10449   auto name = info->bindtable->lookup(ReferenceValue);
10450   return !name.empty() ? name.data() : nullptr;
10451 }
10452 
10453 void printLazyBindTable(ObjectFile *o) {
10454   outs() << "Lazy bind table:\n";
10455   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10456     printMachOLazyBindTable(MachO);
10457   else
10458     WithColor::error()
10459         << "This operation is only currently supported "
10460            "for Mach-O executable files.\n";
10461 }
10462 
10463 void printWeakBindTable(ObjectFile *o) {
10464   outs() << "Weak bind table:\n";
10465   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10466     printMachOWeakBindTable(MachO);
10467   else
10468     WithColor::error()
10469         << "This operation is only currently supported "
10470            "for Mach-O executable files.\n";
10471 }
10472 
10473 void printExportsTrie(const ObjectFile *o) {
10474   outs() << "Exports trie:\n";
10475   if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10476     printMachOExportsTrie(MachO);
10477   else
10478     WithColor::error()
10479         << "This operation is only currently supported "
10480            "for Mach-O executable files.\n";
10481 }
10482 
10483 void printRebaseTable(ObjectFile *o) {
10484   outs() << "Rebase table:\n";
10485   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10486     printMachORebaseTable(MachO);
10487   else
10488     WithColor::error()
10489         << "This operation is only currently supported "
10490            "for Mach-O executable files.\n";
10491 }
10492 
10493 void printBindTable(ObjectFile *o) {
10494   outs() << "Bind table:\n";
10495   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10496     printMachOBindTable(MachO);
10497   else
10498     WithColor::error()
10499         << "This operation is only currently supported "
10500            "for Mach-O executable files.\n";
10501 }
10502 } // namespace llvm
10503