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 "MachODump.h"
14 
15 #include "llvm-objdump.h"
16 #include "llvm-c/Disassembler.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/StringSet.h"
20 #include "llvm/ADT/Triple.h"
21 #include "llvm/BinaryFormat/MachO.h"
22 #include "llvm/Config/config.h"
23 #include "llvm/DebugInfo/DIContext.h"
24 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
25 #include "llvm/Demangle/Demangle.h"
26 #include "llvm/MC/MCAsmInfo.h"
27 #include "llvm/MC/MCContext.h"
28 #include "llvm/MC/MCDisassembler/MCDisassembler.h"
29 #include "llvm/MC/MCInst.h"
30 #include "llvm/MC/MCInstPrinter.h"
31 #include "llvm/MC/MCInstrDesc.h"
32 #include "llvm/MC/MCInstrInfo.h"
33 #include "llvm/MC/MCRegisterInfo.h"
34 #include "llvm/MC/MCSubtargetInfo.h"
35 #include "llvm/MC/MCTargetOptions.h"
36 #include "llvm/Object/MachO.h"
37 #include "llvm/Object/MachOUniversal.h"
38 #include "llvm/Support/Casting.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/Endian.h"
42 #include "llvm/Support/Format.h"
43 #include "llvm/Support/FormattedStream.h"
44 #include "llvm/Support/GraphWriter.h"
45 #include "llvm/Support/LEB128.h"
46 #include "llvm/Support/MemoryBuffer.h"
47 #include "llvm/Support/TargetRegistry.h"
48 #include "llvm/Support/TargetSelect.h"
49 #include "llvm/Support/ToolOutputFile.h"
50 #include "llvm/Support/WithColor.h"
51 #include "llvm/Support/raw_ostream.h"
52 #include <algorithm>
53 #include <cstring>
54 #include <system_error>
55 
56 #ifdef HAVE_LIBXAR
57 extern "C" {
58 #include <xar/xar.h>
59 }
60 #endif
61 
62 using namespace llvm;
63 using namespace llvm::object;
64 using namespace llvm::objdump;
65 
66 cl::OptionCategory objdump::MachOCat("llvm-objdump MachO Specific Options");
67 
68 cl::opt<bool> objdump::FirstPrivateHeader(
69     "private-header",
70     cl::desc("Display only the first format specific file header"),
71     cl::cat(MachOCat));
72 
73 cl::opt<bool> objdump::ExportsTrie("exports-trie",
74                                    cl::desc("Display mach-o exported symbols"),
75                                    cl::cat(MachOCat));
76 
77 cl::opt<bool> objdump::Rebase("rebase",
78                               cl::desc("Display mach-o rebasing info"),
79                               cl::cat(MachOCat));
80 
81 cl::opt<bool> objdump::Bind("bind", cl::desc("Display mach-o binding info"),
82                             cl::cat(MachOCat));
83 
84 cl::opt<bool> objdump::LazyBind("lazy-bind",
85                                 cl::desc("Display mach-o lazy binding info"),
86                                 cl::cat(MachOCat));
87 
88 cl::opt<bool> objdump::WeakBind("weak-bind",
89                                 cl::desc("Display mach-o weak binding info"),
90                                 cl::cat(MachOCat));
91 
92 static cl::opt<bool>
93     UseDbg("g", cl::Grouping,
94            cl::desc("Print line information from debug info if available"),
95            cl::cat(MachOCat));
96 
97 static cl::opt<std::string> DSYMFile("dsym",
98                                      cl::desc("Use .dSYM file for debug info"),
99                                      cl::cat(MachOCat));
100 
101 static cl::opt<bool> FullLeadingAddr("full-leading-addr",
102                                      cl::desc("Print full leading address"),
103                                      cl::cat(MachOCat));
104 
105 static cl::opt<bool> NoLeadingHeaders("no-leading-headers",
106                                       cl::desc("Print no leading headers"),
107                                       cl::cat(MachOCat));
108 
109 cl::opt<bool> objdump::UniversalHeaders(
110     "universal-headers",
111     cl::desc("Print Mach-O universal headers (requires -macho)"),
112     cl::cat(MachOCat));
113 
114 static cl::opt<bool> ArchiveMemberOffsets(
115     "archive-member-offsets",
116     cl::desc("Print the offset to each archive member for Mach-O archives "
117              "(requires -macho and -archive-headers)"),
118     cl::cat(MachOCat));
119 
120 cl::opt<bool> objdump::IndirectSymbols(
121     "indirect-symbols",
122     cl::desc(
123         "Print indirect symbol table for Mach-O objects (requires -macho)"),
124     cl::cat(MachOCat));
125 
126 cl::opt<bool> objdump::DataInCode(
127     "data-in-code",
128     cl::desc(
129         "Print the data in code table for Mach-O objects (requires -macho)"),
130     cl::cat(MachOCat));
131 
132 cl::opt<bool>
133     objdump::LinkOptHints("link-opt-hints",
134                           cl::desc("Print the linker optimization hints for "
135                                    "Mach-O objects (requires -macho)"),
136                           cl::cat(MachOCat));
137 
138 cl::opt<bool>
139     objdump::InfoPlist("info-plist",
140                        cl::desc("Print the info plist section as strings for "
141                                 "Mach-O objects (requires -macho)"),
142                        cl::cat(MachOCat));
143 
144 cl::opt<bool>
145     objdump::DylibsUsed("dylibs-used",
146                         cl::desc("Print the shared libraries used for linked "
147                                  "Mach-O files (requires -macho)"),
148                         cl::cat(MachOCat));
149 
150 cl::opt<bool> objdump::DylibId("dylib-id",
151                                cl::desc("Print the shared library's id for the "
152                                         "dylib Mach-O file (requires -macho)"),
153                                cl::cat(MachOCat));
154 
155 static cl::opt<bool>
156     NonVerbose("non-verbose",
157                cl::desc("Print the info for Mach-O objects in non-verbose or "
158                         "numeric form (requires -macho)"),
159                cl::cat(MachOCat));
160 
161 cl::opt<bool>
162     objdump::ObjcMetaData("objc-meta-data",
163                           cl::desc("Print the Objective-C runtime meta data "
164                                    "for Mach-O files (requires -macho)"),
165                           cl::cat(MachOCat));
166 
167 static cl::opt<std::string> DisSymName(
168     "dis-symname",
169     cl::desc("disassemble just this symbol's instructions (requires -macho)"),
170     cl::cat(MachOCat));
171 
172 static cl::opt<bool> NoSymbolicOperands(
173     "no-symbolic-operands",
174     cl::desc("do not symbolic operands when disassembling (requires -macho)"),
175     cl::cat(MachOCat));
176 
177 static cl::list<std::string>
178     ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
179               cl::ZeroOrMore, cl::cat(MachOCat));
180 
181 namespace llvm {
182 
183 extern StringSet<> FoundSectionSet;
184 
185 bool ArchAll = false;
186 
187 static std::string ThumbTripleName;
188 
189 static const Target *GetTarget(const MachOObjectFile *MachOObj,
190                                const char **McpuDefault,
191                                const Target **ThumbTarget) {
192   // Figure out the target triple.
193   Triple TT(TripleName);
194   if (TripleName.empty()) {
195     TT = MachOObj->getArchTriple(McpuDefault);
196     TripleName = TT.str();
197   }
198 
199   if (TT.getArch() == Triple::arm) {
200     // We've inferred a 32-bit ARM target from the object file. All MachO CPUs
201     // that support ARM are also capable of Thumb mode.
202     Triple ThumbTriple = TT;
203     std::string ThumbName = (Twine("thumb") + TT.getArchName().substr(3)).str();
204     ThumbTriple.setArchName(ThumbName);
205     ThumbTripleName = ThumbTriple.str();
206   }
207 
208   // Get the target specific parser.
209   std::string Error;
210   const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
211   if (TheTarget && ThumbTripleName.empty())
212     return TheTarget;
213 
214   *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
215   if (*ThumbTarget)
216     return TheTarget;
217 
218   WithColor::error(errs(), "llvm-objdump") << "unable to get target for '";
219   if (!TheTarget)
220     errs() << TripleName;
221   else
222     errs() << ThumbTripleName;
223   errs() << "', see --version and --triple.\n";
224   return nullptr;
225 }
226 
227 struct SymbolSorter {
228   bool operator()(const SymbolRef &A, const SymbolRef &B) {
229     Expected<SymbolRef::Type> ATypeOrErr = A.getType();
230     if (!ATypeOrErr)
231       reportError(ATypeOrErr.takeError(), A.getObject()->getFileName());
232     SymbolRef::Type AType = *ATypeOrErr;
233     Expected<SymbolRef::Type> BTypeOrErr = B.getType();
234     if (!BTypeOrErr)
235       reportError(BTypeOrErr.takeError(), B.getObject()->getFileName());
236     SymbolRef::Type BType = *BTypeOrErr;
237     uint64_t AAddr = (AType != SymbolRef::ST_Function) ? 0 : A.getValue();
238     uint64_t BAddr = (BType != SymbolRef::ST_Function) ? 0 : B.getValue();
239     return AAddr < BAddr;
240   }
241 };
242 
243 // Types for the storted data in code table that is built before disassembly
244 // and the predicate function to sort them.
245 typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
246 typedef std::vector<DiceTableEntry> DiceTable;
247 typedef DiceTable::iterator dice_table_iterator;
248 
249 #ifdef HAVE_LIBXAR
250 namespace {
251 struct ScopedXarFile {
252   xar_t xar;
253   ScopedXarFile(const char *filename, int32_t flags)
254       : xar(xar_open(filename, flags)) {}
255   ~ScopedXarFile() {
256     if (xar)
257       xar_close(xar);
258   }
259   ScopedXarFile(const ScopedXarFile &) = delete;
260   ScopedXarFile &operator=(const ScopedXarFile &) = delete;
261   operator xar_t() { return xar; }
262 };
263 
264 struct ScopedXarIter {
265   xar_iter_t iter;
266   ScopedXarIter() : iter(xar_iter_new()) {}
267   ~ScopedXarIter() {
268     if (iter)
269       xar_iter_free(iter);
270   }
271   ScopedXarIter(const ScopedXarIter &) = delete;
272   ScopedXarIter &operator=(const ScopedXarIter &) = delete;
273   operator xar_iter_t() { return iter; }
274 };
275 } // namespace
276 #endif // defined(HAVE_LIBXAR)
277 
278 // This is used to search for a data in code table entry for the PC being
279 // disassembled.  The j parameter has the PC in j.first.  A single data in code
280 // table entry can cover many bytes for each of its Kind's.  So if the offset,
281 // aka the i.first value, of the data in code table entry plus its Length
282 // covers the PC being searched for this will return true.  If not it will
283 // return false.
284 static bool compareDiceTableEntries(const DiceTableEntry &i,
285                                     const DiceTableEntry &j) {
286   uint16_t Length;
287   i.second.getLength(Length);
288 
289   return j.first >= i.first && j.first < i.first + Length;
290 }
291 
292 static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
293                                unsigned short Kind) {
294   uint32_t Value, Size = 1;
295 
296   switch (Kind) {
297   default:
298   case MachO::DICE_KIND_DATA:
299     if (Length >= 4) {
300       if (!NoShowRawInsn)
301         dumpBytes(makeArrayRef(bytes, 4), outs());
302       Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
303       outs() << "\t.long " << Value;
304       Size = 4;
305     } else if (Length >= 2) {
306       if (!NoShowRawInsn)
307         dumpBytes(makeArrayRef(bytes, 2), outs());
308       Value = bytes[1] << 8 | bytes[0];
309       outs() << "\t.short " << Value;
310       Size = 2;
311     } else {
312       if (!NoShowRawInsn)
313         dumpBytes(makeArrayRef(bytes, 2), outs());
314       Value = bytes[0];
315       outs() << "\t.byte " << Value;
316       Size = 1;
317     }
318     if (Kind == MachO::DICE_KIND_DATA)
319       outs() << "\t@ KIND_DATA\n";
320     else
321       outs() << "\t@ data in code kind = " << Kind << "\n";
322     break;
323   case MachO::DICE_KIND_JUMP_TABLE8:
324     if (!NoShowRawInsn)
325       dumpBytes(makeArrayRef(bytes, 1), outs());
326     Value = bytes[0];
327     outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
328     Size = 1;
329     break;
330   case MachO::DICE_KIND_JUMP_TABLE16:
331     if (!NoShowRawInsn)
332       dumpBytes(makeArrayRef(bytes, 2), outs());
333     Value = bytes[1] << 8 | bytes[0];
334     outs() << "\t.short " << format("%5u", Value & 0xffff)
335            << "\t@ KIND_JUMP_TABLE16\n";
336     Size = 2;
337     break;
338   case MachO::DICE_KIND_JUMP_TABLE32:
339   case MachO::DICE_KIND_ABS_JUMP_TABLE32:
340     if (!NoShowRawInsn)
341       dumpBytes(makeArrayRef(bytes, 4), outs());
342     Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
343     outs() << "\t.long " << Value;
344     if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
345       outs() << "\t@ KIND_JUMP_TABLE32\n";
346     else
347       outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
348     Size = 4;
349     break;
350   }
351   return Size;
352 }
353 
354 static void getSectionsAndSymbols(MachOObjectFile *MachOObj,
355                                   std::vector<SectionRef> &Sections,
356                                   std::vector<SymbolRef> &Symbols,
357                                   SmallVectorImpl<uint64_t> &FoundFns,
358                                   uint64_t &BaseSegmentAddress) {
359   const StringRef FileName = MachOObj->getFileName();
360   for (const SymbolRef &Symbol : MachOObj->symbols()) {
361     StringRef SymName = unwrapOrError(Symbol.getName(), FileName);
362     if (!SymName.startswith("ltmp"))
363       Symbols.push_back(Symbol);
364   }
365 
366   for (const SectionRef &Section : MachOObj->sections())
367     Sections.push_back(Section);
368 
369   bool BaseSegmentAddressSet = false;
370   for (const auto &Command : MachOObj->load_commands()) {
371     if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
372       // We found a function starts segment, parse the addresses for later
373       // consumption.
374       MachO::linkedit_data_command LLC =
375           MachOObj->getLinkeditDataLoadCommand(Command);
376 
377       MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
378     } else if (Command.C.cmd == MachO::LC_SEGMENT) {
379       MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
380       StringRef SegName = SLC.segname;
381       if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
382         BaseSegmentAddressSet = true;
383         BaseSegmentAddress = SLC.vmaddr;
384       }
385     } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
386       MachO::segment_command_64 SLC = MachOObj->getSegment64LoadCommand(Command);
387       StringRef SegName = SLC.segname;
388       if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
389         BaseSegmentAddressSet = true;
390         BaseSegmentAddress = SLC.vmaddr;
391       }
392     }
393   }
394 }
395 
396 static bool DumpAndSkipDataInCode(uint64_t PC, const uint8_t *bytes,
397                                  DiceTable &Dices, uint64_t &InstSize) {
398   // Check the data in code table here to see if this is data not an
399   // instruction to be disassembled.
400   DiceTable Dice;
401   Dice.push_back(std::make_pair(PC, DiceRef()));
402   dice_table_iterator DTI =
403       std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
404                   compareDiceTableEntries);
405   if (DTI != Dices.end()) {
406     uint16_t Length;
407     DTI->second.getLength(Length);
408     uint16_t Kind;
409     DTI->second.getKind(Kind);
410     InstSize = DumpDataInCode(bytes, Length, Kind);
411     if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
412         (PC == (DTI->first + Length - 1)) && (Length & 1))
413       InstSize++;
414     return true;
415   }
416   return false;
417 }
418 
419 static void printRelocationTargetName(const MachOObjectFile *O,
420                                       const MachO::any_relocation_info &RE,
421                                       raw_string_ostream &Fmt) {
422   // Target of a scattered relocation is an address.  In the interest of
423   // generating pretty output, scan through the symbol table looking for a
424   // symbol that aligns with that address.  If we find one, print it.
425   // Otherwise, we just print the hex address of the target.
426   const StringRef FileName = O->getFileName();
427   if (O->isRelocationScattered(RE)) {
428     uint32_t Val = O->getPlainRelocationSymbolNum(RE);
429 
430     for (const SymbolRef &Symbol : O->symbols()) {
431       uint64_t Addr = unwrapOrError(Symbol.getAddress(), FileName);
432       if (Addr != Val)
433         continue;
434       Fmt << unwrapOrError(Symbol.getName(), FileName);
435       return;
436     }
437 
438     // If we couldn't find a symbol that this relocation refers to, try
439     // to find a section beginning instead.
440     for (const SectionRef &Section : ToolSectionFilter(*O)) {
441       uint64_t Addr = Section.getAddress();
442       if (Addr != Val)
443         continue;
444       StringRef NameOrErr = unwrapOrError(Section.getName(), O->getFileName());
445       Fmt << NameOrErr;
446       return;
447     }
448 
449     Fmt << format("0x%x", Val);
450     return;
451   }
452 
453   StringRef S;
454   bool isExtern = O->getPlainRelocationExternal(RE);
455   uint64_t Val = O->getPlainRelocationSymbolNum(RE);
456 
457   if (O->getAnyRelocationType(RE) == MachO::ARM64_RELOC_ADDEND) {
458     Fmt << format("0x%0" PRIx64, Val);
459     return;
460   }
461 
462   if (isExtern) {
463     symbol_iterator SI = O->symbol_begin();
464     advance(SI, Val);
465     S = unwrapOrError(SI->getName(), FileName);
466   } else {
467     section_iterator SI = O->section_begin();
468     // Adjust for the fact that sections are 1-indexed.
469     if (Val == 0) {
470       Fmt << "0 (?,?)";
471       return;
472     }
473     uint32_t I = Val - 1;
474     while (I != 0 && SI != O->section_end()) {
475       --I;
476       advance(SI, 1);
477     }
478     if (SI == O->section_end()) {
479       Fmt << Val << " (?,?)";
480     } else {
481       if (Expected<StringRef> NameOrErr = SI->getName())
482         S = *NameOrErr;
483       else
484         consumeError(NameOrErr.takeError());
485     }
486   }
487 
488   Fmt << S;
489 }
490 
491 Error getMachORelocationValueString(const MachOObjectFile *Obj,
492                                     const RelocationRef &RelRef,
493                                     SmallVectorImpl<char> &Result) {
494   DataRefImpl Rel = RelRef.getRawDataRefImpl();
495   MachO::any_relocation_info RE = Obj->getRelocation(Rel);
496 
497   unsigned Arch = Obj->getArch();
498 
499   std::string FmtBuf;
500   raw_string_ostream Fmt(FmtBuf);
501   unsigned Type = Obj->getAnyRelocationType(RE);
502   bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
503 
504   // Determine any addends that should be displayed with the relocation.
505   // These require decoding the relocation type, which is triple-specific.
506 
507   // X86_64 has entirely custom relocation types.
508   if (Arch == Triple::x86_64) {
509     switch (Type) {
510     case MachO::X86_64_RELOC_GOT_LOAD:
511     case MachO::X86_64_RELOC_GOT: {
512       printRelocationTargetName(Obj, RE, Fmt);
513       Fmt << "@GOT";
514       if (IsPCRel)
515         Fmt << "PCREL";
516       break;
517     }
518     case MachO::X86_64_RELOC_SUBTRACTOR: {
519       DataRefImpl RelNext = Rel;
520       Obj->moveRelocationNext(RelNext);
521       MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
522 
523       // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
524       // X86_64_RELOC_UNSIGNED.
525       // NOTE: Scattered relocations don't exist on x86_64.
526       unsigned RType = Obj->getAnyRelocationType(RENext);
527       if (RType != MachO::X86_64_RELOC_UNSIGNED)
528         reportError(Obj->getFileName(), "Expected X86_64_RELOC_UNSIGNED after "
529                                         "X86_64_RELOC_SUBTRACTOR.");
530 
531       // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
532       // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
533       printRelocationTargetName(Obj, RENext, Fmt);
534       Fmt << "-";
535       printRelocationTargetName(Obj, RE, Fmt);
536       break;
537     }
538     case MachO::X86_64_RELOC_TLV:
539       printRelocationTargetName(Obj, RE, Fmt);
540       Fmt << "@TLV";
541       if (IsPCRel)
542         Fmt << "P";
543       break;
544     case MachO::X86_64_RELOC_SIGNED_1:
545       printRelocationTargetName(Obj, RE, Fmt);
546       Fmt << "-1";
547       break;
548     case MachO::X86_64_RELOC_SIGNED_2:
549       printRelocationTargetName(Obj, RE, Fmt);
550       Fmt << "-2";
551       break;
552     case MachO::X86_64_RELOC_SIGNED_4:
553       printRelocationTargetName(Obj, RE, Fmt);
554       Fmt << "-4";
555       break;
556     default:
557       printRelocationTargetName(Obj, RE, Fmt);
558       break;
559     }
560     // X86 and ARM share some relocation types in common.
561   } else if (Arch == Triple::x86 || Arch == Triple::arm ||
562              Arch == Triple::ppc) {
563     // Generic relocation types...
564     switch (Type) {
565     case MachO::GENERIC_RELOC_PAIR: // prints no info
566       return Error::success();
567     case MachO::GENERIC_RELOC_SECTDIFF: {
568       DataRefImpl RelNext = Rel;
569       Obj->moveRelocationNext(RelNext);
570       MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
571 
572       // X86 sect diff's must be followed by a relocation of type
573       // GENERIC_RELOC_PAIR.
574       unsigned RType = Obj->getAnyRelocationType(RENext);
575 
576       if (RType != MachO::GENERIC_RELOC_PAIR)
577         reportError(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
578                                         "GENERIC_RELOC_SECTDIFF.");
579 
580       printRelocationTargetName(Obj, RE, Fmt);
581       Fmt << "-";
582       printRelocationTargetName(Obj, RENext, Fmt);
583       break;
584     }
585     }
586 
587     if (Arch == Triple::x86 || Arch == Triple::ppc) {
588       switch (Type) {
589       case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
590         DataRefImpl RelNext = Rel;
591         Obj->moveRelocationNext(RelNext);
592         MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
593 
594         // X86 sect diff's must be followed by a relocation of type
595         // GENERIC_RELOC_PAIR.
596         unsigned RType = Obj->getAnyRelocationType(RENext);
597         if (RType != MachO::GENERIC_RELOC_PAIR)
598           reportError(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
599                                           "GENERIC_RELOC_LOCAL_SECTDIFF.");
600 
601         printRelocationTargetName(Obj, RE, Fmt);
602         Fmt << "-";
603         printRelocationTargetName(Obj, RENext, Fmt);
604         break;
605       }
606       case MachO::GENERIC_RELOC_TLV: {
607         printRelocationTargetName(Obj, RE, Fmt);
608         Fmt << "@TLV";
609         if (IsPCRel)
610           Fmt << "P";
611         break;
612       }
613       default:
614         printRelocationTargetName(Obj, RE, Fmt);
615       }
616     } else { // ARM-specific relocations
617       switch (Type) {
618       case MachO::ARM_RELOC_HALF:
619       case MachO::ARM_RELOC_HALF_SECTDIFF: {
620         // Half relocations steal a bit from the length field to encode
621         // whether this is an upper16 or a lower16 relocation.
622         bool isUpper = (Obj->getAnyRelocationLength(RE) & 0x1) == 1;
623 
624         if (isUpper)
625           Fmt << ":upper16:(";
626         else
627           Fmt << ":lower16:(";
628         printRelocationTargetName(Obj, RE, Fmt);
629 
630         DataRefImpl RelNext = Rel;
631         Obj->moveRelocationNext(RelNext);
632         MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
633 
634         // ARM half relocs must be followed by a relocation of type
635         // ARM_RELOC_PAIR.
636         unsigned RType = Obj->getAnyRelocationType(RENext);
637         if (RType != MachO::ARM_RELOC_PAIR)
638           reportError(Obj->getFileName(), "Expected ARM_RELOC_PAIR after "
639                                           "ARM_RELOC_HALF");
640 
641         // NOTE: The half of the target virtual address is stashed in the
642         // address field of the secondary relocation, but we can't reverse
643         // engineer the constant offset from it without decoding the movw/movt
644         // instruction to find the other half in its immediate field.
645 
646         // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
647         // symbol/section pointer of the follow-on relocation.
648         if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
649           Fmt << "-";
650           printRelocationTargetName(Obj, RENext, Fmt);
651         }
652 
653         Fmt << ")";
654         break;
655       }
656       default: {
657         printRelocationTargetName(Obj, RE, Fmt);
658       }
659       }
660     }
661   } else
662     printRelocationTargetName(Obj, RE, Fmt);
663 
664   Fmt.flush();
665   Result.append(FmtBuf.begin(), FmtBuf.end());
666   return Error::success();
667 }
668 
669 static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
670                                      uint32_t n, uint32_t count,
671                                      uint32_t stride, uint64_t addr) {
672   MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
673   uint32_t nindirectsyms = Dysymtab.nindirectsyms;
674   if (n > nindirectsyms)
675     outs() << " (entries start past the end of the indirect symbol "
676               "table) (reserved1 field greater than the table size)";
677   else if (n + count > nindirectsyms)
678     outs() << " (entries extends past the end of the indirect symbol "
679               "table)";
680   outs() << "\n";
681   uint32_t cputype = O->getHeader().cputype;
682   if (cputype & MachO::CPU_ARCH_ABI64)
683     outs() << "address            index";
684   else
685     outs() << "address    index";
686   if (verbose)
687     outs() << " name\n";
688   else
689     outs() << "\n";
690   for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
691     if (cputype & MachO::CPU_ARCH_ABI64)
692       outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
693     else
694       outs() << format("0x%08" PRIx32, (uint32_t)addr + j * stride) << " ";
695     MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
696     uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
697     if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
698       outs() << "LOCAL\n";
699       continue;
700     }
701     if (indirect_symbol ==
702         (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
703       outs() << "LOCAL ABSOLUTE\n";
704       continue;
705     }
706     if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
707       outs() << "ABSOLUTE\n";
708       continue;
709     }
710     outs() << format("%5u ", indirect_symbol);
711     if (verbose) {
712       MachO::symtab_command Symtab = O->getSymtabLoadCommand();
713       if (indirect_symbol < Symtab.nsyms) {
714         symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
715         SymbolRef Symbol = *Sym;
716         outs() << unwrapOrError(Symbol.getName(), O->getFileName());
717       } else {
718         outs() << "?";
719       }
720     }
721     outs() << "\n";
722   }
723 }
724 
725 static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
726   for (const auto &Load : O->load_commands()) {
727     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
728       MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
729       for (unsigned J = 0; J < Seg.nsects; ++J) {
730         MachO::section_64 Sec = O->getSection64(Load, J);
731         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
732         if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
733             section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
734             section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
735             section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
736             section_type == MachO::S_SYMBOL_STUBS) {
737           uint32_t stride;
738           if (section_type == MachO::S_SYMBOL_STUBS)
739             stride = Sec.reserved2;
740           else
741             stride = 8;
742           if (stride == 0) {
743             outs() << "Can't print indirect symbols for (" << Sec.segname << ","
744                    << Sec.sectname << ") "
745                    << "(size of stubs in reserved2 field is zero)\n";
746             continue;
747           }
748           uint32_t count = Sec.size / stride;
749           outs() << "Indirect symbols for (" << Sec.segname << ","
750                  << Sec.sectname << ") " << count << " entries";
751           uint32_t n = Sec.reserved1;
752           PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
753         }
754       }
755     } else if (Load.C.cmd == MachO::LC_SEGMENT) {
756       MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
757       for (unsigned J = 0; J < Seg.nsects; ++J) {
758         MachO::section Sec = O->getSection(Load, J);
759         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
760         if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
761             section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
762             section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
763             section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
764             section_type == MachO::S_SYMBOL_STUBS) {
765           uint32_t stride;
766           if (section_type == MachO::S_SYMBOL_STUBS)
767             stride = Sec.reserved2;
768           else
769             stride = 4;
770           if (stride == 0) {
771             outs() << "Can't print indirect symbols for (" << Sec.segname << ","
772                    << Sec.sectname << ") "
773                    << "(size of stubs in reserved2 field is zero)\n";
774             continue;
775           }
776           uint32_t count = Sec.size / stride;
777           outs() << "Indirect symbols for (" << Sec.segname << ","
778                  << Sec.sectname << ") " << count << " entries";
779           uint32_t n = Sec.reserved1;
780           PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
781         }
782       }
783     }
784   }
785 }
786 
787 static void PrintRType(const uint64_t cputype, const unsigned r_type) {
788   static char const *generic_r_types[] = {
789     "VANILLA ", "PAIR    ", "SECTDIF ", "PBLAPTR ", "LOCSDIF ", "TLV     ",
790     "  6 (?) ", "  7 (?) ", "  8 (?) ", "  9 (?) ", " 10 (?) ", " 11 (?) ",
791     " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
792   };
793   static char const *x86_64_r_types[] = {
794     "UNSIGND ", "SIGNED  ", "BRANCH  ", "GOT_LD  ", "GOT     ", "SUB     ",
795     "SIGNED1 ", "SIGNED2 ", "SIGNED4 ", "TLV     ", " 10 (?) ", " 11 (?) ",
796     " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
797   };
798   static char const *arm_r_types[] = {
799     "VANILLA ", "PAIR    ", "SECTDIFF", "LOCSDIF ", "PBLAPTR ",
800     "BR24    ", "T_BR22  ", "T_BR32  ", "HALF    ", "HALFDIF ",
801     " 10 (?) ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
802   };
803   static char const *arm64_r_types[] = {
804     "UNSIGND ", "SUB     ", "BR26    ", "PAGE21  ", "PAGOF12 ",
805     "GOTLDP  ", "GOTLDPOF", "PTRTGOT ", "TLVLDP  ", "TLVLDPOF",
806     "ADDEND  ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
807   };
808 
809   if (r_type > 0xf){
810     outs() << format("%-7u", r_type) << " ";
811     return;
812   }
813   switch (cputype) {
814     case MachO::CPU_TYPE_I386:
815       outs() << generic_r_types[r_type];
816       break;
817     case MachO::CPU_TYPE_X86_64:
818       outs() << x86_64_r_types[r_type];
819       break;
820     case MachO::CPU_TYPE_ARM:
821       outs() << arm_r_types[r_type];
822       break;
823     case MachO::CPU_TYPE_ARM64:
824     case MachO::CPU_TYPE_ARM64_32:
825       outs() << arm64_r_types[r_type];
826       break;
827     default:
828       outs() << format("%-7u ", r_type);
829   }
830 }
831 
832 static void PrintRLength(const uint64_t cputype, const unsigned r_type,
833                          const unsigned r_length, const bool previous_arm_half){
834   if (cputype == MachO::CPU_TYPE_ARM &&
835       (r_type == MachO::ARM_RELOC_HALF ||
836        r_type == MachO::ARM_RELOC_HALF_SECTDIFF || previous_arm_half == true)) {
837     if ((r_length & 0x1) == 0)
838       outs() << "lo/";
839     else
840       outs() << "hi/";
841     if ((r_length & 0x1) == 0)
842       outs() << "arm ";
843     else
844       outs() << "thm ";
845   } else {
846     switch (r_length) {
847       case 0:
848         outs() << "byte   ";
849         break;
850       case 1:
851         outs() << "word   ";
852         break;
853       case 2:
854         outs() << "long   ";
855         break;
856       case 3:
857         if (cputype == MachO::CPU_TYPE_X86_64)
858           outs() << "quad   ";
859         else
860           outs() << format("?(%2d)  ", r_length);
861         break;
862       default:
863         outs() << format("?(%2d)  ", r_length);
864     }
865   }
866 }
867 
868 static void PrintRelocationEntries(const MachOObjectFile *O,
869                                    const relocation_iterator Begin,
870                                    const relocation_iterator End,
871                                    const uint64_t cputype,
872                                    const bool verbose) {
873   const MachO::symtab_command Symtab = O->getSymtabLoadCommand();
874   bool previous_arm_half = false;
875   bool previous_sectdiff = false;
876   uint32_t sectdiff_r_type = 0;
877 
878   for (relocation_iterator Reloc = Begin; Reloc != End; ++Reloc) {
879     const DataRefImpl Rel = Reloc->getRawDataRefImpl();
880     const MachO::any_relocation_info RE = O->getRelocation(Rel);
881     const unsigned r_type = O->getAnyRelocationType(RE);
882     const bool r_scattered = O->isRelocationScattered(RE);
883     const unsigned r_pcrel = O->getAnyRelocationPCRel(RE);
884     const unsigned r_length = O->getAnyRelocationLength(RE);
885     const unsigned r_address = O->getAnyRelocationAddress(RE);
886     const bool r_extern = (r_scattered ? false :
887                            O->getPlainRelocationExternal(RE));
888     const uint32_t r_value = (r_scattered ?
889                               O->getScatteredRelocationValue(RE) : 0);
890     const unsigned r_symbolnum = (r_scattered ? 0 :
891                                   O->getPlainRelocationSymbolNum(RE));
892 
893     if (r_scattered && cputype != MachO::CPU_TYPE_X86_64) {
894       if (verbose) {
895         // scattered: address
896         if ((cputype == MachO::CPU_TYPE_I386 &&
897              r_type == MachO::GENERIC_RELOC_PAIR) ||
898             (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR))
899           outs() << "         ";
900         else
901           outs() << format("%08x ", (unsigned int)r_address);
902 
903         // scattered: pcrel
904         if (r_pcrel)
905           outs() << "True  ";
906         else
907           outs() << "False ";
908 
909         // scattered: length
910         PrintRLength(cputype, r_type, r_length, previous_arm_half);
911 
912         // scattered: extern & type
913         outs() << "n/a    ";
914         PrintRType(cputype, r_type);
915 
916         // scattered: scattered & value
917         outs() << format("True      0x%08x", (unsigned int)r_value);
918         if (previous_sectdiff == false) {
919           if ((cputype == MachO::CPU_TYPE_ARM &&
920                r_type == MachO::ARM_RELOC_PAIR))
921             outs() << format(" half = 0x%04x ", (unsigned int)r_address);
922         } else if (cputype == MachO::CPU_TYPE_ARM &&
923                    sectdiff_r_type == MachO::ARM_RELOC_HALF_SECTDIFF)
924           outs() << format(" other_half = 0x%04x ", (unsigned int)r_address);
925         if ((cputype == MachO::CPU_TYPE_I386 &&
926              (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
927               r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) ||
928             (cputype == MachO::CPU_TYPE_ARM &&
929              (sectdiff_r_type == MachO::ARM_RELOC_SECTDIFF ||
930               sectdiff_r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
931               sectdiff_r_type == MachO::ARM_RELOC_HALF_SECTDIFF))) {
932           previous_sectdiff = true;
933           sectdiff_r_type = r_type;
934         } else {
935           previous_sectdiff = false;
936           sectdiff_r_type = 0;
937         }
938         if (cputype == MachO::CPU_TYPE_ARM &&
939             (r_type == MachO::ARM_RELOC_HALF ||
940              r_type == MachO::ARM_RELOC_HALF_SECTDIFF))
941           previous_arm_half = true;
942         else
943           previous_arm_half = false;
944         outs() << "\n";
945       }
946       else {
947         // scattered: address pcrel length extern type scattered value
948         outs() << format("%08x %1d     %-2d     n/a    %-7d 1         0x%08x\n",
949                          (unsigned int)r_address, r_pcrel, r_length, r_type,
950                          (unsigned int)r_value);
951       }
952     }
953     else {
954       if (verbose) {
955         // plain: address
956         if (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR)
957           outs() << "         ";
958         else
959           outs() << format("%08x ", (unsigned int)r_address);
960 
961         // plain: pcrel
962         if (r_pcrel)
963           outs() << "True  ";
964         else
965           outs() << "False ";
966 
967         // plain: length
968         PrintRLength(cputype, r_type, r_length, previous_arm_half);
969 
970         if (r_extern) {
971           // plain: extern & type & scattered
972           outs() << "True   ";
973           PrintRType(cputype, r_type);
974           outs() << "False     ";
975 
976           // plain: symbolnum/value
977           if (r_symbolnum > Symtab.nsyms)
978             outs() << format("?(%d)\n", r_symbolnum);
979           else {
980             SymbolRef Symbol = *O->getSymbolByIndex(r_symbolnum);
981             Expected<StringRef> SymNameNext = Symbol.getName();
982             const char *name = NULL;
983             if (SymNameNext)
984               name = SymNameNext->data();
985             if (name == NULL)
986               outs() << format("?(%d)\n", r_symbolnum);
987             else
988               outs() << name << "\n";
989           }
990         }
991         else {
992           // plain: extern & type & scattered
993           outs() << "False  ";
994           PrintRType(cputype, r_type);
995           outs() << "False     ";
996 
997           // plain: symbolnum/value
998           if (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR)
999             outs() << format("other_half = 0x%04x\n", (unsigned int)r_address);
1000           else if ((cputype == MachO::CPU_TYPE_ARM64 ||
1001                     cputype == MachO::CPU_TYPE_ARM64_32) &&
1002                    r_type == MachO::ARM64_RELOC_ADDEND)
1003             outs() << format("addend = 0x%06x\n", (unsigned int)r_symbolnum);
1004           else {
1005             outs() << format("%d ", r_symbolnum);
1006             if (r_symbolnum == MachO::R_ABS)
1007               outs() << "R_ABS\n";
1008             else {
1009               // in this case, r_symbolnum is actually a 1-based section number
1010               uint32_t nsects = O->section_end()->getRawDataRefImpl().d.a;
1011               if (r_symbolnum > 0 && r_symbolnum <= nsects) {
1012                 object::DataRefImpl DRI;
1013                 DRI.d.a = r_symbolnum-1;
1014                 StringRef SegName = O->getSectionFinalSegmentName(DRI);
1015                 if (Expected<StringRef> NameOrErr = O->getSectionName(DRI))
1016                   outs() << "(" << SegName << "," << *NameOrErr << ")\n";
1017                 else
1018                   outs() << "(?,?)\n";
1019               }
1020               else {
1021                 outs() << "(?,?)\n";
1022               }
1023             }
1024           }
1025         }
1026         if (cputype == MachO::CPU_TYPE_ARM &&
1027             (r_type == MachO::ARM_RELOC_HALF ||
1028              r_type == MachO::ARM_RELOC_HALF_SECTDIFF))
1029           previous_arm_half = true;
1030         else
1031           previous_arm_half = false;
1032       }
1033       else {
1034         // plain: address pcrel length extern type scattered symbolnum/section
1035         outs() << format("%08x %1d     %-2d     %1d      %-7d 0         %d\n",
1036                          (unsigned int)r_address, r_pcrel, r_length, r_extern,
1037                          r_type, r_symbolnum);
1038       }
1039     }
1040   }
1041 }
1042 
1043 static void PrintRelocations(const MachOObjectFile *O, const bool verbose) {
1044   const uint64_t cputype = O->getHeader().cputype;
1045   const MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
1046   if (Dysymtab.nextrel != 0) {
1047     outs() << "External relocation information " << Dysymtab.nextrel
1048            << " entries";
1049     outs() << "\naddress  pcrel length extern type    scattered "
1050               "symbolnum/value\n";
1051     PrintRelocationEntries(O, O->extrel_begin(), O->extrel_end(), cputype,
1052                            verbose);
1053   }
1054   if (Dysymtab.nlocrel != 0) {
1055     outs() << format("Local relocation information %u entries",
1056                      Dysymtab.nlocrel);
1057     outs() << "\naddress  pcrel length extern type    scattered "
1058               "symbolnum/value\n";
1059     PrintRelocationEntries(O, O->locrel_begin(), O->locrel_end(), cputype,
1060                            verbose);
1061   }
1062   for (const auto &Load : O->load_commands()) {
1063     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
1064       const MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
1065       for (unsigned J = 0; J < Seg.nsects; ++J) {
1066         const MachO::section_64 Sec = O->getSection64(Load, J);
1067         if (Sec.nreloc != 0) {
1068           DataRefImpl DRI;
1069           DRI.d.a = J;
1070           const StringRef SegName = O->getSectionFinalSegmentName(DRI);
1071           if (Expected<StringRef> NameOrErr = O->getSectionName(DRI))
1072             outs() << "Relocation information (" << SegName << "," << *NameOrErr
1073                    << format(") %u entries", Sec.nreloc);
1074           else
1075             outs() << "Relocation information (" << SegName << ",?) "
1076                    << format("%u entries", Sec.nreloc);
1077           outs() << "\naddress  pcrel length extern type    scattered "
1078                     "symbolnum/value\n";
1079           PrintRelocationEntries(O, O->section_rel_begin(DRI),
1080                                  O->section_rel_end(DRI), cputype, verbose);
1081         }
1082       }
1083     } else if (Load.C.cmd == MachO::LC_SEGMENT) {
1084       const MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
1085       for (unsigned J = 0; J < Seg.nsects; ++J) {
1086         const MachO::section Sec = O->getSection(Load, J);
1087         if (Sec.nreloc != 0) {
1088           DataRefImpl DRI;
1089           DRI.d.a = J;
1090           const StringRef SegName = O->getSectionFinalSegmentName(DRI);
1091           if (Expected<StringRef> NameOrErr = O->getSectionName(DRI))
1092             outs() << "Relocation information (" << SegName << "," << *NameOrErr
1093                    << format(") %u entries", Sec.nreloc);
1094           else
1095             outs() << "Relocation information (" << SegName << ",?) "
1096                    << format("%u entries", Sec.nreloc);
1097           outs() << "\naddress  pcrel length extern type    scattered "
1098                     "symbolnum/value\n";
1099           PrintRelocationEntries(O, O->section_rel_begin(DRI),
1100                                  O->section_rel_end(DRI), cputype, verbose);
1101         }
1102       }
1103     }
1104   }
1105 }
1106 
1107 static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
1108   MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
1109   uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
1110   outs() << "Data in code table (" << nentries << " entries)\n";
1111   outs() << "offset     length kind\n";
1112   for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
1113        ++DI) {
1114     uint32_t Offset;
1115     DI->getOffset(Offset);
1116     outs() << format("0x%08" PRIx32, Offset) << " ";
1117     uint16_t Length;
1118     DI->getLength(Length);
1119     outs() << format("%6u", Length) << " ";
1120     uint16_t Kind;
1121     DI->getKind(Kind);
1122     if (verbose) {
1123       switch (Kind) {
1124       case MachO::DICE_KIND_DATA:
1125         outs() << "DATA";
1126         break;
1127       case MachO::DICE_KIND_JUMP_TABLE8:
1128         outs() << "JUMP_TABLE8";
1129         break;
1130       case MachO::DICE_KIND_JUMP_TABLE16:
1131         outs() << "JUMP_TABLE16";
1132         break;
1133       case MachO::DICE_KIND_JUMP_TABLE32:
1134         outs() << "JUMP_TABLE32";
1135         break;
1136       case MachO::DICE_KIND_ABS_JUMP_TABLE32:
1137         outs() << "ABS_JUMP_TABLE32";
1138         break;
1139       default:
1140         outs() << format("0x%04" PRIx32, Kind);
1141         break;
1142       }
1143     } else
1144       outs() << format("0x%04" PRIx32, Kind);
1145     outs() << "\n";
1146   }
1147 }
1148 
1149 static void PrintLinkOptHints(MachOObjectFile *O) {
1150   MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
1151   const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
1152   uint32_t nloh = LohLC.datasize;
1153   outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
1154   for (uint32_t i = 0; i < nloh;) {
1155     unsigned n;
1156     uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
1157     i += n;
1158     outs() << "    identifier " << identifier << " ";
1159     if (i >= nloh)
1160       return;
1161     switch (identifier) {
1162     case 1:
1163       outs() << "AdrpAdrp\n";
1164       break;
1165     case 2:
1166       outs() << "AdrpLdr\n";
1167       break;
1168     case 3:
1169       outs() << "AdrpAddLdr\n";
1170       break;
1171     case 4:
1172       outs() << "AdrpLdrGotLdr\n";
1173       break;
1174     case 5:
1175       outs() << "AdrpAddStr\n";
1176       break;
1177     case 6:
1178       outs() << "AdrpLdrGotStr\n";
1179       break;
1180     case 7:
1181       outs() << "AdrpAdd\n";
1182       break;
1183     case 8:
1184       outs() << "AdrpLdrGot\n";
1185       break;
1186     default:
1187       outs() << "Unknown identifier value\n";
1188       break;
1189     }
1190     uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
1191     i += n;
1192     outs() << "    narguments " << narguments << "\n";
1193     if (i >= nloh)
1194       return;
1195 
1196     for (uint32_t j = 0; j < narguments; j++) {
1197       uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
1198       i += n;
1199       outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
1200       if (i >= nloh)
1201         return;
1202     }
1203   }
1204 }
1205 
1206 static void PrintDylibs(MachOObjectFile *O, bool JustId) {
1207   unsigned Index = 0;
1208   for (const auto &Load : O->load_commands()) {
1209     if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
1210         (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
1211                      Load.C.cmd == MachO::LC_LOAD_DYLIB ||
1212                      Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
1213                      Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
1214                      Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
1215                      Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
1216       MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
1217       if (dl.dylib.name < dl.cmdsize) {
1218         const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
1219         if (JustId)
1220           outs() << p << "\n";
1221         else {
1222           outs() << "\t" << p;
1223           outs() << " (compatibility version "
1224                  << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
1225                  << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
1226                  << (dl.dylib.compatibility_version & 0xff) << ",";
1227           outs() << " current version "
1228                  << ((dl.dylib.current_version >> 16) & 0xffff) << "."
1229                  << ((dl.dylib.current_version >> 8) & 0xff) << "."
1230                  << (dl.dylib.current_version & 0xff);
1231           if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
1232             outs() << ", weak";
1233           if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
1234             outs() << ", reexport";
1235           if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
1236             outs() << ", upward";
1237           if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
1238             outs() << ", lazy";
1239           outs() << ")\n";
1240         }
1241       } else {
1242         outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
1243         if (Load.C.cmd == MachO::LC_ID_DYLIB)
1244           outs() << "LC_ID_DYLIB ";
1245         else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
1246           outs() << "LC_LOAD_DYLIB ";
1247         else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
1248           outs() << "LC_LOAD_WEAK_DYLIB ";
1249         else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
1250           outs() << "LC_LAZY_LOAD_DYLIB ";
1251         else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
1252           outs() << "LC_REEXPORT_DYLIB ";
1253         else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
1254           outs() << "LC_LOAD_UPWARD_DYLIB ";
1255         else
1256           outs() << "LC_??? ";
1257         outs() << "command " << Index++ << "\n";
1258       }
1259     }
1260   }
1261 }
1262 
1263 typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
1264 
1265 static void CreateSymbolAddressMap(MachOObjectFile *O,
1266                                    SymbolAddressMap *AddrMap) {
1267   // Create a map of symbol addresses to symbol names.
1268   const StringRef FileName = O->getFileName();
1269   for (const SymbolRef &Symbol : O->symbols()) {
1270     SymbolRef::Type ST = unwrapOrError(Symbol.getType(), FileName);
1271     if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
1272         ST == SymbolRef::ST_Other) {
1273       uint64_t Address = Symbol.getValue();
1274       StringRef SymName = unwrapOrError(Symbol.getName(), FileName);
1275       if (!SymName.startswith(".objc"))
1276         (*AddrMap)[Address] = SymName;
1277     }
1278   }
1279 }
1280 
1281 // GuessSymbolName is passed the address of what might be a symbol and a
1282 // pointer to the SymbolAddressMap.  It returns the name of a symbol
1283 // with that address or nullptr if no symbol is found with that address.
1284 static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
1285   const char *SymbolName = nullptr;
1286   // A DenseMap can't lookup up some values.
1287   if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
1288     StringRef name = AddrMap->lookup(value);
1289     if (!name.empty())
1290       SymbolName = name.data();
1291   }
1292   return SymbolName;
1293 }
1294 
1295 static void DumpCstringChar(const char c) {
1296   char p[2];
1297   p[0] = c;
1298   p[1] = '\0';
1299   outs().write_escaped(p);
1300 }
1301 
1302 static void DumpCstringSection(MachOObjectFile *O, const char *sect,
1303                                uint32_t sect_size, uint64_t sect_addr,
1304                                bool print_addresses) {
1305   for (uint32_t i = 0; i < sect_size; i++) {
1306     if (print_addresses) {
1307       if (O->is64Bit())
1308         outs() << format("%016" PRIx64, sect_addr + i) << "  ";
1309       else
1310         outs() << format("%08" PRIx64, sect_addr + i) << "  ";
1311     }
1312     for (; i < sect_size && sect[i] != '\0'; i++)
1313       DumpCstringChar(sect[i]);
1314     if (i < sect_size && sect[i] == '\0')
1315       outs() << "\n";
1316   }
1317 }
1318 
1319 static void DumpLiteral4(uint32_t l, float f) {
1320   outs() << format("0x%08" PRIx32, l);
1321   if ((l & 0x7f800000) != 0x7f800000)
1322     outs() << format(" (%.16e)\n", f);
1323   else {
1324     if (l == 0x7f800000)
1325       outs() << " (+Infinity)\n";
1326     else if (l == 0xff800000)
1327       outs() << " (-Infinity)\n";
1328     else if ((l & 0x00400000) == 0x00400000)
1329       outs() << " (non-signaling Not-a-Number)\n";
1330     else
1331       outs() << " (signaling Not-a-Number)\n";
1332   }
1333 }
1334 
1335 static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
1336                                 uint32_t sect_size, uint64_t sect_addr,
1337                                 bool print_addresses) {
1338   for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
1339     if (print_addresses) {
1340       if (O->is64Bit())
1341         outs() << format("%016" PRIx64, sect_addr + i) << "  ";
1342       else
1343         outs() << format("%08" PRIx64, sect_addr + i) << "  ";
1344     }
1345     float f;
1346     memcpy(&f, sect + i, sizeof(float));
1347     if (O->isLittleEndian() != sys::IsLittleEndianHost)
1348       sys::swapByteOrder(f);
1349     uint32_t l;
1350     memcpy(&l, sect + i, sizeof(uint32_t));
1351     if (O->isLittleEndian() != sys::IsLittleEndianHost)
1352       sys::swapByteOrder(l);
1353     DumpLiteral4(l, f);
1354   }
1355 }
1356 
1357 static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
1358                          double d) {
1359   outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
1360   uint32_t Hi, Lo;
1361   Hi = (O->isLittleEndian()) ? l1 : l0;
1362   Lo = (O->isLittleEndian()) ? l0 : l1;
1363 
1364   // Hi is the high word, so this is equivalent to if(isfinite(d))
1365   if ((Hi & 0x7ff00000) != 0x7ff00000)
1366     outs() << format(" (%.16e)\n", d);
1367   else {
1368     if (Hi == 0x7ff00000 && Lo == 0)
1369       outs() << " (+Infinity)\n";
1370     else if (Hi == 0xfff00000 && Lo == 0)
1371       outs() << " (-Infinity)\n";
1372     else if ((Hi & 0x00080000) == 0x00080000)
1373       outs() << " (non-signaling Not-a-Number)\n";
1374     else
1375       outs() << " (signaling Not-a-Number)\n";
1376   }
1377 }
1378 
1379 static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
1380                                 uint32_t sect_size, uint64_t sect_addr,
1381                                 bool print_addresses) {
1382   for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
1383     if (print_addresses) {
1384       if (O->is64Bit())
1385         outs() << format("%016" PRIx64, sect_addr + i) << "  ";
1386       else
1387         outs() << format("%08" PRIx64, sect_addr + i) << "  ";
1388     }
1389     double d;
1390     memcpy(&d, sect + i, sizeof(double));
1391     if (O->isLittleEndian() != sys::IsLittleEndianHost)
1392       sys::swapByteOrder(d);
1393     uint32_t l0, l1;
1394     memcpy(&l0, sect + i, sizeof(uint32_t));
1395     memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
1396     if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1397       sys::swapByteOrder(l0);
1398       sys::swapByteOrder(l1);
1399     }
1400     DumpLiteral8(O, l0, l1, d);
1401   }
1402 }
1403 
1404 static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
1405   outs() << format("0x%08" PRIx32, l0) << " ";
1406   outs() << format("0x%08" PRIx32, l1) << " ";
1407   outs() << format("0x%08" PRIx32, l2) << " ";
1408   outs() << format("0x%08" PRIx32, l3) << "\n";
1409 }
1410 
1411 static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
1412                                  uint32_t sect_size, uint64_t sect_addr,
1413                                  bool print_addresses) {
1414   for (uint32_t i = 0; i < sect_size; i += 16) {
1415     if (print_addresses) {
1416       if (O->is64Bit())
1417         outs() << format("%016" PRIx64, sect_addr + i) << "  ";
1418       else
1419         outs() << format("%08" PRIx64, sect_addr + i) << "  ";
1420     }
1421     uint32_t l0, l1, l2, l3;
1422     memcpy(&l0, sect + i, sizeof(uint32_t));
1423     memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
1424     memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
1425     memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
1426     if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1427       sys::swapByteOrder(l0);
1428       sys::swapByteOrder(l1);
1429       sys::swapByteOrder(l2);
1430       sys::swapByteOrder(l3);
1431     }
1432     DumpLiteral16(l0, l1, l2, l3);
1433   }
1434 }
1435 
1436 static void DumpLiteralPointerSection(MachOObjectFile *O,
1437                                       const SectionRef &Section,
1438                                       const char *sect, uint32_t sect_size,
1439                                       uint64_t sect_addr,
1440                                       bool print_addresses) {
1441   // Collect the literal sections in this Mach-O file.
1442   std::vector<SectionRef> LiteralSections;
1443   for (const SectionRef &Section : O->sections()) {
1444     DataRefImpl Ref = Section.getRawDataRefImpl();
1445     uint32_t section_type;
1446     if (O->is64Bit()) {
1447       const MachO::section_64 Sec = O->getSection64(Ref);
1448       section_type = Sec.flags & MachO::SECTION_TYPE;
1449     } else {
1450       const MachO::section Sec = O->getSection(Ref);
1451       section_type = Sec.flags & MachO::SECTION_TYPE;
1452     }
1453     if (section_type == MachO::S_CSTRING_LITERALS ||
1454         section_type == MachO::S_4BYTE_LITERALS ||
1455         section_type == MachO::S_8BYTE_LITERALS ||
1456         section_type == MachO::S_16BYTE_LITERALS)
1457       LiteralSections.push_back(Section);
1458   }
1459 
1460   // Set the size of the literal pointer.
1461   uint32_t lp_size = O->is64Bit() ? 8 : 4;
1462 
1463   // Collect the external relocation symbols for the literal pointers.
1464   std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1465   for (const RelocationRef &Reloc : Section.relocations()) {
1466     DataRefImpl Rel;
1467     MachO::any_relocation_info RE;
1468     bool isExtern = false;
1469     Rel = Reloc.getRawDataRefImpl();
1470     RE = O->getRelocation(Rel);
1471     isExtern = O->getPlainRelocationExternal(RE);
1472     if (isExtern) {
1473       uint64_t RelocOffset = Reloc.getOffset();
1474       symbol_iterator RelocSym = Reloc.getSymbol();
1475       Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
1476     }
1477   }
1478   array_pod_sort(Relocs.begin(), Relocs.end());
1479 
1480   // Dump each literal pointer.
1481   for (uint32_t i = 0; i < sect_size; i += lp_size) {
1482     if (print_addresses) {
1483       if (O->is64Bit())
1484         outs() << format("%016" PRIx64, sect_addr + i) << "  ";
1485       else
1486         outs() << format("%08" PRIx64, sect_addr + i) << "  ";
1487     }
1488     uint64_t lp;
1489     if (O->is64Bit()) {
1490       memcpy(&lp, sect + i, sizeof(uint64_t));
1491       if (O->isLittleEndian() != sys::IsLittleEndianHost)
1492         sys::swapByteOrder(lp);
1493     } else {
1494       uint32_t li;
1495       memcpy(&li, sect + i, sizeof(uint32_t));
1496       if (O->isLittleEndian() != sys::IsLittleEndianHost)
1497         sys::swapByteOrder(li);
1498       lp = li;
1499     }
1500 
1501     // First look for an external relocation entry for this literal pointer.
1502     auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
1503       return P.first == i;
1504     });
1505     if (Reloc != Relocs.end()) {
1506       symbol_iterator RelocSym = Reloc->second;
1507       StringRef SymName = unwrapOrError(RelocSym->getName(), O->getFileName());
1508       outs() << "external relocation entry for symbol:" << SymName << "\n";
1509       continue;
1510     }
1511 
1512     // For local references see what the section the literal pointer points to.
1513     auto Sect = find_if(LiteralSections, [&](const SectionRef &R) {
1514       return lp >= R.getAddress() && lp < R.getAddress() + R.getSize();
1515     });
1516     if (Sect == LiteralSections.end()) {
1517       outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
1518       continue;
1519     }
1520 
1521     uint64_t SectAddress = Sect->getAddress();
1522     uint64_t SectSize = Sect->getSize();
1523 
1524     StringRef SectName;
1525     Expected<StringRef> SectNameOrErr = Sect->getName();
1526     if (SectNameOrErr)
1527       SectName = *SectNameOrErr;
1528     else
1529       consumeError(SectNameOrErr.takeError());
1530 
1531     DataRefImpl Ref = Sect->getRawDataRefImpl();
1532     StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
1533     outs() << SegmentName << ":" << SectName << ":";
1534 
1535     uint32_t section_type;
1536     if (O->is64Bit()) {
1537       const MachO::section_64 Sec = O->getSection64(Ref);
1538       section_type = Sec.flags & MachO::SECTION_TYPE;
1539     } else {
1540       const MachO::section Sec = O->getSection(Ref);
1541       section_type = Sec.flags & MachO::SECTION_TYPE;
1542     }
1543 
1544     StringRef BytesStr = unwrapOrError(Sect->getContents(), O->getFileName());
1545 
1546     const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
1547 
1548     switch (section_type) {
1549     case MachO::S_CSTRING_LITERALS:
1550       for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
1551            i++) {
1552         DumpCstringChar(Contents[i]);
1553       }
1554       outs() << "\n";
1555       break;
1556     case MachO::S_4BYTE_LITERALS:
1557       float f;
1558       memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
1559       uint32_t l;
1560       memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
1561       if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1562         sys::swapByteOrder(f);
1563         sys::swapByteOrder(l);
1564       }
1565       DumpLiteral4(l, f);
1566       break;
1567     case MachO::S_8BYTE_LITERALS: {
1568       double d;
1569       memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
1570       uint32_t l0, l1;
1571       memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
1572       memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
1573              sizeof(uint32_t));
1574       if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1575         sys::swapByteOrder(f);
1576         sys::swapByteOrder(l0);
1577         sys::swapByteOrder(l1);
1578       }
1579       DumpLiteral8(O, l0, l1, d);
1580       break;
1581     }
1582     case MachO::S_16BYTE_LITERALS: {
1583       uint32_t l0, l1, l2, l3;
1584       memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
1585       memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
1586              sizeof(uint32_t));
1587       memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
1588              sizeof(uint32_t));
1589       memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
1590              sizeof(uint32_t));
1591       if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1592         sys::swapByteOrder(l0);
1593         sys::swapByteOrder(l1);
1594         sys::swapByteOrder(l2);
1595         sys::swapByteOrder(l3);
1596       }
1597       DumpLiteral16(l0, l1, l2, l3);
1598       break;
1599     }
1600     }
1601   }
1602 }
1603 
1604 static void DumpInitTermPointerSection(MachOObjectFile *O,
1605                                        const SectionRef &Section,
1606                                        const char *sect,
1607                                        uint32_t sect_size, uint64_t sect_addr,
1608                                        SymbolAddressMap *AddrMap,
1609                                        bool verbose) {
1610   uint32_t stride;
1611   stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t);
1612 
1613   // Collect the external relocation symbols for the pointers.
1614   std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1615   for (const RelocationRef &Reloc : Section.relocations()) {
1616     DataRefImpl Rel;
1617     MachO::any_relocation_info RE;
1618     bool isExtern = false;
1619     Rel = Reloc.getRawDataRefImpl();
1620     RE = O->getRelocation(Rel);
1621     isExtern = O->getPlainRelocationExternal(RE);
1622     if (isExtern) {
1623       uint64_t RelocOffset = Reloc.getOffset();
1624       symbol_iterator RelocSym = Reloc.getSymbol();
1625       Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
1626     }
1627   }
1628   array_pod_sort(Relocs.begin(), Relocs.end());
1629 
1630   for (uint32_t i = 0; i < sect_size; i += stride) {
1631     const char *SymbolName = nullptr;
1632     uint64_t p;
1633     if (O->is64Bit()) {
1634       outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
1635       uint64_t pointer_value;
1636       memcpy(&pointer_value, sect + i, stride);
1637       if (O->isLittleEndian() != sys::IsLittleEndianHost)
1638         sys::swapByteOrder(pointer_value);
1639       outs() << format("0x%016" PRIx64, pointer_value);
1640       p = pointer_value;
1641     } else {
1642       outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
1643       uint32_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%08" PRIx32, pointer_value);
1648       p = pointer_value;
1649     }
1650     if (verbose) {
1651       // First look for an external relocation entry for this pointer.
1652       auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
1653         return P.first == i;
1654       });
1655       if (Reloc != Relocs.end()) {
1656         symbol_iterator RelocSym = Reloc->second;
1657         outs() << " " << unwrapOrError(RelocSym->getName(), O->getFileName());
1658       } else {
1659         SymbolName = GuessSymbolName(p, AddrMap);
1660         if (SymbolName)
1661           outs() << " " << SymbolName;
1662       }
1663     }
1664     outs() << "\n";
1665   }
1666 }
1667 
1668 static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
1669                                    uint32_t size, uint64_t addr) {
1670   uint32_t cputype = O->getHeader().cputype;
1671   if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
1672     uint32_t j;
1673     for (uint32_t i = 0; i < size; i += j, addr += j) {
1674       if (O->is64Bit())
1675         outs() << format("%016" PRIx64, addr) << "\t";
1676       else
1677         outs() << format("%08" PRIx64, addr) << "\t";
1678       for (j = 0; j < 16 && i + j < size; j++) {
1679         uint8_t byte_word = *(sect + i + j);
1680         outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1681       }
1682       outs() << "\n";
1683     }
1684   } else {
1685     uint32_t j;
1686     for (uint32_t i = 0; i < size; i += j, addr += j) {
1687       if (O->is64Bit())
1688         outs() << format("%016" PRIx64, addr) << "\t";
1689       else
1690         outs() << format("%08" PRIx64, addr) << "\t";
1691       for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
1692            j += sizeof(int32_t)) {
1693         if (i + j + sizeof(int32_t) <= size) {
1694           uint32_t long_word;
1695           memcpy(&long_word, sect + i + j, sizeof(int32_t));
1696           if (O->isLittleEndian() != sys::IsLittleEndianHost)
1697             sys::swapByteOrder(long_word);
1698           outs() << format("%08" PRIx32, long_word) << " ";
1699         } else {
1700           for (uint32_t k = 0; i + j + k < size; k++) {
1701             uint8_t byte_word = *(sect + i + j + k);
1702             outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1703           }
1704         }
1705       }
1706       outs() << "\n";
1707     }
1708   }
1709 }
1710 
1711 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
1712                              StringRef DisSegName, StringRef DisSectName);
1713 static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
1714                                 uint32_t size, uint32_t addr);
1715 #ifdef HAVE_LIBXAR
1716 static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
1717                                 uint32_t size, bool verbose,
1718                                 bool PrintXarHeader, bool PrintXarFileHeaders,
1719                                 std::string XarMemberName);
1720 #endif // defined(HAVE_LIBXAR)
1721 
1722 static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
1723                                 bool verbose) {
1724   SymbolAddressMap AddrMap;
1725   if (verbose)
1726     CreateSymbolAddressMap(O, &AddrMap);
1727 
1728   for (unsigned i = 0; i < FilterSections.size(); ++i) {
1729     StringRef DumpSection = FilterSections[i];
1730     std::pair<StringRef, StringRef> DumpSegSectName;
1731     DumpSegSectName = DumpSection.split(',');
1732     StringRef DumpSegName, DumpSectName;
1733     if (!DumpSegSectName.second.empty()) {
1734       DumpSegName = DumpSegSectName.first;
1735       DumpSectName = DumpSegSectName.second;
1736     } else {
1737       DumpSegName = "";
1738       DumpSectName = DumpSegSectName.first;
1739     }
1740     for (const SectionRef &Section : O->sections()) {
1741       StringRef SectName;
1742       Expected<StringRef> SecNameOrErr = Section.getName();
1743       if (SecNameOrErr)
1744         SectName = *SecNameOrErr;
1745       else
1746         consumeError(SecNameOrErr.takeError());
1747 
1748       if (!DumpSection.empty())
1749         FoundSectionSet.insert(DumpSection);
1750 
1751       DataRefImpl Ref = Section.getRawDataRefImpl();
1752       StringRef SegName = O->getSectionFinalSegmentName(Ref);
1753       if ((DumpSegName.empty() || SegName == DumpSegName) &&
1754           (SectName == DumpSectName)) {
1755 
1756         uint32_t section_flags;
1757         if (O->is64Bit()) {
1758           const MachO::section_64 Sec = O->getSection64(Ref);
1759           section_flags = Sec.flags;
1760 
1761         } else {
1762           const MachO::section Sec = O->getSection(Ref);
1763           section_flags = Sec.flags;
1764         }
1765         uint32_t section_type = section_flags & MachO::SECTION_TYPE;
1766 
1767         StringRef BytesStr =
1768             unwrapOrError(Section.getContents(), O->getFileName());
1769         const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1770         uint32_t sect_size = BytesStr.size();
1771         uint64_t sect_addr = Section.getAddress();
1772 
1773         if (!NoLeadingHeaders)
1774           outs() << "Contents of (" << SegName << "," << SectName
1775                  << ") section\n";
1776 
1777         if (verbose) {
1778           if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1779               (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1780             DisassembleMachO(Filename, O, SegName, SectName);
1781             continue;
1782           }
1783           if (SegName == "__TEXT" && SectName == "__info_plist") {
1784             outs() << sect;
1785             continue;
1786           }
1787           if (SegName == "__OBJC" && SectName == "__protocol") {
1788             DumpProtocolSection(O, sect, sect_size, sect_addr);
1789             continue;
1790           }
1791 #ifdef HAVE_LIBXAR
1792           if (SegName == "__LLVM" && SectName == "__bundle") {
1793             DumpBitcodeSection(O, sect, sect_size, verbose, !NoSymbolicOperands,
1794                                ArchiveHeaders, "");
1795             continue;
1796           }
1797 #endif // defined(HAVE_LIBXAR)
1798           switch (section_type) {
1799           case MachO::S_REGULAR:
1800             DumpRawSectionContents(O, sect, sect_size, sect_addr);
1801             break;
1802           case MachO::S_ZEROFILL:
1803             outs() << "zerofill section and has no contents in the file\n";
1804             break;
1805           case MachO::S_CSTRING_LITERALS:
1806             DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1807             break;
1808           case MachO::S_4BYTE_LITERALS:
1809             DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1810             break;
1811           case MachO::S_8BYTE_LITERALS:
1812             DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1813             break;
1814           case MachO::S_16BYTE_LITERALS:
1815             DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1816             break;
1817           case MachO::S_LITERAL_POINTERS:
1818             DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
1819                                       !NoLeadingAddr);
1820             break;
1821           case MachO::S_MOD_INIT_FUNC_POINTERS:
1822           case MachO::S_MOD_TERM_FUNC_POINTERS:
1823             DumpInitTermPointerSection(O, Section, sect, sect_size, sect_addr,
1824                                        &AddrMap, verbose);
1825             break;
1826           default:
1827             outs() << "Unknown section type ("
1828                    << format("0x%08" PRIx32, section_type) << ")\n";
1829             DumpRawSectionContents(O, sect, sect_size, sect_addr);
1830             break;
1831           }
1832         } else {
1833           if (section_type == MachO::S_ZEROFILL)
1834             outs() << "zerofill section and has no contents in the file\n";
1835           else
1836             DumpRawSectionContents(O, sect, sect_size, sect_addr);
1837         }
1838       }
1839     }
1840   }
1841 }
1842 
1843 static void DumpInfoPlistSectionContents(StringRef Filename,
1844                                          MachOObjectFile *O) {
1845   for (const SectionRef &Section : O->sections()) {
1846     StringRef SectName;
1847     Expected<StringRef> SecNameOrErr = Section.getName();
1848     if (SecNameOrErr)
1849       SectName = *SecNameOrErr;
1850     else
1851       consumeError(SecNameOrErr.takeError());
1852 
1853     DataRefImpl Ref = Section.getRawDataRefImpl();
1854     StringRef SegName = O->getSectionFinalSegmentName(Ref);
1855     if (SegName == "__TEXT" && SectName == "__info_plist") {
1856       if (!NoLeadingHeaders)
1857         outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
1858       StringRef BytesStr =
1859           unwrapOrError(Section.getContents(), O->getFileName());
1860       const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1861       outs() << format("%.*s", BytesStr.size(), sect) << "\n";
1862       return;
1863     }
1864   }
1865 }
1866 
1867 // checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1868 // and if it is and there is a list of architecture flags is specified then
1869 // check to make sure this Mach-O file is one of those architectures or all
1870 // architectures were specified.  If not then an error is generated and this
1871 // routine returns false.  Else it returns true.
1872 static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
1873   auto *MachO = dyn_cast<MachOObjectFile>(O);
1874 
1875   if (!MachO || ArchAll || ArchFlags.empty())
1876     return true;
1877 
1878   MachO::mach_header H;
1879   MachO::mach_header_64 H_64;
1880   Triple T;
1881   const char *McpuDefault, *ArchFlag;
1882   if (MachO->is64Bit()) {
1883     H_64 = MachO->MachOObjectFile::getHeader64();
1884     T = MachOObjectFile::getArchTriple(H_64.cputype, H_64.cpusubtype,
1885                                        &McpuDefault, &ArchFlag);
1886   } else {
1887     H = MachO->MachOObjectFile::getHeader();
1888     T = MachOObjectFile::getArchTriple(H.cputype, H.cpusubtype,
1889                                        &McpuDefault, &ArchFlag);
1890   }
1891   const std::string ArchFlagName(ArchFlag);
1892   if (none_of(ArchFlags, [&](const std::string &Name) {
1893         return Name == ArchFlagName;
1894       })) {
1895     WithColor::error(errs(), "llvm-objdump")
1896         << Filename << ": no architecture specified.\n";
1897     return false;
1898   }
1899   return true;
1900 }
1901 
1902 static void printObjcMetaData(MachOObjectFile *O, bool verbose);
1903 
1904 // ProcessMachO() is passed a single opened Mach-O file, which may be an
1905 // archive member and or in a slice of a universal file.  It prints the
1906 // the file name and header info and then processes it according to the
1907 // command line options.
1908 static void ProcessMachO(StringRef Name, MachOObjectFile *MachOOF,
1909                          StringRef ArchiveMemberName = StringRef(),
1910                          StringRef ArchitectureName = StringRef()) {
1911   // If we are doing some processing here on the Mach-O file print the header
1912   // info.  And don't print it otherwise like in the case of printing the
1913   // UniversalHeaders or ArchiveHeaders.
1914   if (Disassemble || Relocations || PrivateHeaders || ExportsTrie || Rebase ||
1915       Bind || SymbolTable || LazyBind || WeakBind || IndirectSymbols ||
1916       DataInCode || LinkOptHints || DylibsUsed || DylibId || ObjcMetaData ||
1917       (!FilterSections.empty())) {
1918     if (!NoLeadingHeaders) {
1919       outs() << Name;
1920       if (!ArchiveMemberName.empty())
1921         outs() << '(' << ArchiveMemberName << ')';
1922       if (!ArchitectureName.empty())
1923         outs() << " (architecture " << ArchitectureName << ")";
1924       outs() << ":\n";
1925     }
1926   }
1927   // To use the report_error() form with an ArchiveName and FileName set
1928   // these up based on what is passed for Name and ArchiveMemberName.
1929   StringRef ArchiveName;
1930   StringRef FileName;
1931   if (!ArchiveMemberName.empty()) {
1932     ArchiveName = Name;
1933     FileName = ArchiveMemberName;
1934   } else {
1935     ArchiveName = StringRef();
1936     FileName = Name;
1937   }
1938 
1939   // If we need the symbol table to do the operation then check it here to
1940   // produce a good error message as to where the Mach-O file comes from in
1941   // the error message.
1942   if (Disassemble || IndirectSymbols || !FilterSections.empty() || UnwindInfo)
1943     if (Error Err = MachOOF->checkSymbolTable())
1944       reportError(std::move(Err), FileName, ArchiveName, ArchitectureName);
1945 
1946   if (DisassembleAll) {
1947     for (const SectionRef &Section : MachOOF->sections()) {
1948       StringRef SectName;
1949       if (Expected<StringRef> NameOrErr = Section.getName())
1950         SectName = *NameOrErr;
1951       else
1952         consumeError(NameOrErr.takeError());
1953 
1954       if (SectName.equals("__text")) {
1955         DataRefImpl Ref = Section.getRawDataRefImpl();
1956         StringRef SegName = MachOOF->getSectionFinalSegmentName(Ref);
1957         DisassembleMachO(FileName, MachOOF, SegName, SectName);
1958       }
1959     }
1960   }
1961   else if (Disassemble) {
1962     if (MachOOF->getHeader().filetype == MachO::MH_KEXT_BUNDLE &&
1963         MachOOF->getHeader().cputype == MachO::CPU_TYPE_ARM64)
1964       DisassembleMachO(FileName, MachOOF, "__TEXT_EXEC", "__text");
1965     else
1966       DisassembleMachO(FileName, MachOOF, "__TEXT", "__text");
1967   }
1968   if (IndirectSymbols)
1969     PrintIndirectSymbols(MachOOF, !NonVerbose);
1970   if (DataInCode)
1971     PrintDataInCodeTable(MachOOF, !NonVerbose);
1972   if (LinkOptHints)
1973     PrintLinkOptHints(MachOOF);
1974   if (Relocations)
1975     PrintRelocations(MachOOF, !NonVerbose);
1976   if (SectionHeaders)
1977     printSectionHeaders(MachOOF);
1978   if (SectionContents)
1979     printSectionContents(MachOOF);
1980   if (!FilterSections.empty())
1981     DumpSectionContents(FileName, MachOOF, !NonVerbose);
1982   if (InfoPlist)
1983     DumpInfoPlistSectionContents(FileName, MachOOF);
1984   if (DylibsUsed)
1985     PrintDylibs(MachOOF, false);
1986   if (DylibId)
1987     PrintDylibs(MachOOF, true);
1988   if (SymbolTable)
1989     printSymbolTable(MachOOF, ArchiveName, ArchitectureName);
1990   if (UnwindInfo)
1991     printMachOUnwindInfo(MachOOF);
1992   if (PrivateHeaders) {
1993     printMachOFileHeader(MachOOF);
1994     printMachOLoadCommands(MachOOF);
1995   }
1996   if (FirstPrivateHeader)
1997     printMachOFileHeader(MachOOF);
1998   if (ObjcMetaData)
1999     printObjcMetaData(MachOOF, !NonVerbose);
2000   if (ExportsTrie)
2001     printExportsTrie(MachOOF);
2002   if (Rebase)
2003     printRebaseTable(MachOOF);
2004   if (Bind)
2005     printBindTable(MachOOF);
2006   if (LazyBind)
2007     printLazyBindTable(MachOOF);
2008   if (WeakBind)
2009     printWeakBindTable(MachOOF);
2010 
2011   if (DwarfDumpType != DIDT_Null) {
2012     std::unique_ptr<DIContext> DICtx = DWARFContext::create(*MachOOF);
2013     // Dump the complete DWARF structure.
2014     DIDumpOptions DumpOpts;
2015     DumpOpts.DumpType = DwarfDumpType;
2016     DICtx->dump(outs(), DumpOpts);
2017   }
2018 }
2019 
2020 // printUnknownCPUType() helps print_fat_headers for unknown CPU's.
2021 static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
2022   outs() << "    cputype (" << cputype << ")\n";
2023   outs() << "    cpusubtype (" << cpusubtype << ")\n";
2024 }
2025 
2026 // printCPUType() helps print_fat_headers by printing the cputype and
2027 // pusubtype (symbolically for the one's it knows about).
2028 static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
2029   switch (cputype) {
2030   case MachO::CPU_TYPE_I386:
2031     switch (cpusubtype) {
2032     case MachO::CPU_SUBTYPE_I386_ALL:
2033       outs() << "    cputype CPU_TYPE_I386\n";
2034       outs() << "    cpusubtype CPU_SUBTYPE_I386_ALL\n";
2035       break;
2036     default:
2037       printUnknownCPUType(cputype, cpusubtype);
2038       break;
2039     }
2040     break;
2041   case MachO::CPU_TYPE_X86_64:
2042     switch (cpusubtype) {
2043     case MachO::CPU_SUBTYPE_X86_64_ALL:
2044       outs() << "    cputype CPU_TYPE_X86_64\n";
2045       outs() << "    cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
2046       break;
2047     case MachO::CPU_SUBTYPE_X86_64_H:
2048       outs() << "    cputype CPU_TYPE_X86_64\n";
2049       outs() << "    cpusubtype CPU_SUBTYPE_X86_64_H\n";
2050       break;
2051     default:
2052       printUnknownCPUType(cputype, cpusubtype);
2053       break;
2054     }
2055     break;
2056   case MachO::CPU_TYPE_ARM:
2057     switch (cpusubtype) {
2058     case MachO::CPU_SUBTYPE_ARM_ALL:
2059       outs() << "    cputype CPU_TYPE_ARM\n";
2060       outs() << "    cpusubtype CPU_SUBTYPE_ARM_ALL\n";
2061       break;
2062     case MachO::CPU_SUBTYPE_ARM_V4T:
2063       outs() << "    cputype CPU_TYPE_ARM\n";
2064       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V4T\n";
2065       break;
2066     case MachO::CPU_SUBTYPE_ARM_V5TEJ:
2067       outs() << "    cputype CPU_TYPE_ARM\n";
2068       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
2069       break;
2070     case MachO::CPU_SUBTYPE_ARM_XSCALE:
2071       outs() << "    cputype CPU_TYPE_ARM\n";
2072       outs() << "    cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
2073       break;
2074     case MachO::CPU_SUBTYPE_ARM_V6:
2075       outs() << "    cputype CPU_TYPE_ARM\n";
2076       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V6\n";
2077       break;
2078     case MachO::CPU_SUBTYPE_ARM_V6M:
2079       outs() << "    cputype CPU_TYPE_ARM\n";
2080       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V6M\n";
2081       break;
2082     case MachO::CPU_SUBTYPE_ARM_V7:
2083       outs() << "    cputype CPU_TYPE_ARM\n";
2084       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V7\n";
2085       break;
2086     case MachO::CPU_SUBTYPE_ARM_V7EM:
2087       outs() << "    cputype CPU_TYPE_ARM\n";
2088       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
2089       break;
2090     case MachO::CPU_SUBTYPE_ARM_V7K:
2091       outs() << "    cputype CPU_TYPE_ARM\n";
2092       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V7K\n";
2093       break;
2094     case MachO::CPU_SUBTYPE_ARM_V7M:
2095       outs() << "    cputype CPU_TYPE_ARM\n";
2096       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V7M\n";
2097       break;
2098     case MachO::CPU_SUBTYPE_ARM_V7S:
2099       outs() << "    cputype CPU_TYPE_ARM\n";
2100       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V7S\n";
2101       break;
2102     default:
2103       printUnknownCPUType(cputype, cpusubtype);
2104       break;
2105     }
2106     break;
2107   case MachO::CPU_TYPE_ARM64:
2108     switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2109     case MachO::CPU_SUBTYPE_ARM64_ALL:
2110       outs() << "    cputype CPU_TYPE_ARM64\n";
2111       outs() << "    cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
2112       break;
2113     case MachO::CPU_SUBTYPE_ARM64E:
2114       outs() << "    cputype CPU_TYPE_ARM64\n";
2115       outs() << "    cpusubtype CPU_SUBTYPE_ARM64E\n";
2116       break;
2117     default:
2118       printUnknownCPUType(cputype, cpusubtype);
2119       break;
2120     }
2121     break;
2122   case MachO::CPU_TYPE_ARM64_32:
2123     switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2124     case MachO::CPU_SUBTYPE_ARM64_32_V8:
2125       outs() << "    cputype CPU_TYPE_ARM64_32\n";
2126       outs() << "    cpusubtype CPU_SUBTYPE_ARM64_32_V8\n";
2127       break;
2128     default:
2129       printUnknownCPUType(cputype, cpusubtype);
2130       break;
2131     }
2132     break;
2133   default:
2134     printUnknownCPUType(cputype, cpusubtype);
2135     break;
2136   }
2137 }
2138 
2139 static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
2140                                        bool verbose) {
2141   outs() << "Fat headers\n";
2142   if (verbose) {
2143     if (UB->getMagic() == MachO::FAT_MAGIC)
2144       outs() << "fat_magic FAT_MAGIC\n";
2145     else // UB->getMagic() == MachO::FAT_MAGIC_64
2146       outs() << "fat_magic FAT_MAGIC_64\n";
2147   } else
2148     outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
2149 
2150   uint32_t nfat_arch = UB->getNumberOfObjects();
2151   StringRef Buf = UB->getData();
2152   uint64_t size = Buf.size();
2153   uint64_t big_size = sizeof(struct MachO::fat_header) +
2154                       nfat_arch * sizeof(struct MachO::fat_arch);
2155   outs() << "nfat_arch " << UB->getNumberOfObjects();
2156   if (nfat_arch == 0)
2157     outs() << " (malformed, contains zero architecture types)\n";
2158   else if (big_size > size)
2159     outs() << " (malformed, architectures past end of file)\n";
2160   else
2161     outs() << "\n";
2162 
2163   for (uint32_t i = 0; i < nfat_arch; ++i) {
2164     MachOUniversalBinary::ObjectForArch OFA(UB, i);
2165     uint32_t cputype = OFA.getCPUType();
2166     uint32_t cpusubtype = OFA.getCPUSubType();
2167     outs() << "architecture ";
2168     for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
2169       MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
2170       uint32_t other_cputype = other_OFA.getCPUType();
2171       uint32_t other_cpusubtype = other_OFA.getCPUSubType();
2172       if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
2173           (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
2174               (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
2175         outs() << "(illegal duplicate architecture) ";
2176         break;
2177       }
2178     }
2179     if (verbose) {
2180       outs() << OFA.getArchFlagName() << "\n";
2181       printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2182     } else {
2183       outs() << i << "\n";
2184       outs() << "    cputype " << cputype << "\n";
2185       outs() << "    cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
2186              << "\n";
2187     }
2188     if (verbose &&
2189         (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
2190       outs() << "    capabilities CPU_SUBTYPE_LIB64\n";
2191     else
2192       outs() << "    capabilities "
2193              << format("0x%" PRIx32,
2194                        (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
2195     outs() << "    offset " << OFA.getOffset();
2196     if (OFA.getOffset() > size)
2197       outs() << " (past end of file)";
2198     if (OFA.getOffset() % (1ull << OFA.getAlign()) != 0)
2199       outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
2200     outs() << "\n";
2201     outs() << "    size " << OFA.getSize();
2202     big_size = OFA.getOffset() + OFA.getSize();
2203     if (big_size > size)
2204       outs() << " (past end of file)";
2205     outs() << "\n";
2206     outs() << "    align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
2207            << ")\n";
2208   }
2209 }
2210 
2211 static void printArchiveChild(StringRef Filename, const Archive::Child &C,
2212                               size_t ChildIndex, bool verbose,
2213                               bool print_offset,
2214                               StringRef ArchitectureName = StringRef()) {
2215   if (print_offset)
2216     outs() << C.getChildOffset() << "\t";
2217   sys::fs::perms Mode =
2218       unwrapOrError(C.getAccessMode(), getFileNameForError(C, ChildIndex),
2219                     Filename, ArchitectureName);
2220   if (verbose) {
2221     // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
2222     // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
2223     outs() << "-";
2224     outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
2225     outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
2226     outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
2227     outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
2228     outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
2229     outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
2230     outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
2231     outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
2232     outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
2233   } else {
2234     outs() << format("0%o ", Mode);
2235   }
2236 
2237   outs() << format("%3d/%-3d %5" PRId64 " ",
2238                    unwrapOrError(C.getUID(), getFileNameForError(C, ChildIndex),
2239                                  Filename, ArchitectureName),
2240                    unwrapOrError(C.getGID(), getFileNameForError(C, ChildIndex),
2241                                  Filename, ArchitectureName),
2242                    unwrapOrError(C.getRawSize(),
2243                                  getFileNameForError(C, ChildIndex), Filename,
2244                                  ArchitectureName));
2245 
2246   StringRef RawLastModified = C.getRawLastModified();
2247   if (verbose) {
2248     unsigned Seconds;
2249     if (RawLastModified.getAsInteger(10, Seconds))
2250       outs() << "(date: \"" << RawLastModified
2251              << "\" contains non-decimal chars) ";
2252     else {
2253       // Since cime(3) returns a 26 character string of the form:
2254       // "Sun Sep 16 01:03:52 1973\n\0"
2255       // just print 24 characters.
2256       time_t t = Seconds;
2257       outs() << format("%.24s ", ctime(&t));
2258     }
2259   } else {
2260     outs() << RawLastModified << " ";
2261   }
2262 
2263   if (verbose) {
2264     Expected<StringRef> NameOrErr = C.getName();
2265     if (!NameOrErr) {
2266       consumeError(NameOrErr.takeError());
2267       outs() << unwrapOrError(C.getRawName(),
2268                               getFileNameForError(C, ChildIndex), Filename,
2269                               ArchitectureName)
2270              << "\n";
2271     } else {
2272       StringRef Name = NameOrErr.get();
2273       outs() << Name << "\n";
2274     }
2275   } else {
2276     outs() << unwrapOrError(C.getRawName(), getFileNameForError(C, ChildIndex),
2277                             Filename, ArchitectureName)
2278            << "\n";
2279   }
2280 }
2281 
2282 static void printArchiveHeaders(StringRef Filename, Archive *A, bool verbose,
2283                                 bool print_offset,
2284                                 StringRef ArchitectureName = StringRef()) {
2285   Error Err = Error::success();
2286   size_t I = 0;
2287   for (const auto &C : A->children(Err, false))
2288     printArchiveChild(Filename, C, I++, verbose, print_offset,
2289                       ArchitectureName);
2290 
2291   if (Err)
2292     reportError(std::move(Err), Filename, "", ArchitectureName);
2293 }
2294 
2295 static bool ValidateArchFlags() {
2296   // Check for -arch all and verifiy the -arch flags are valid.
2297   for (unsigned i = 0; i < ArchFlags.size(); ++i) {
2298     if (ArchFlags[i] == "all") {
2299       ArchAll = true;
2300     } else {
2301       if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
2302         WithColor::error(errs(), "llvm-objdump")
2303             << "unknown architecture named '" + ArchFlags[i] +
2304                    "'for the -arch option\n";
2305         return false;
2306       }
2307     }
2308   }
2309   return true;
2310 }
2311 
2312 // ParseInputMachO() parses the named Mach-O file in Filename and handles the
2313 // -arch flags selecting just those slices as specified by them and also parses
2314 // archive files.  Then for each individual Mach-O file ProcessMachO() is
2315 // called to process the file based on the command line options.
2316 void parseInputMachO(StringRef Filename) {
2317   if (!ValidateArchFlags())
2318     return;
2319 
2320   // Attempt to open the binary.
2321   Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
2322   if (!BinaryOrErr) {
2323     if (Error E = isNotObjectErrorInvalidFileType(BinaryOrErr.takeError()))
2324       reportError(std::move(E), Filename);
2325     else
2326       outs() << Filename << ": is not an object file\n";
2327     return;
2328   }
2329   Binary &Bin = *BinaryOrErr.get().getBinary();
2330 
2331   if (Archive *A = dyn_cast<Archive>(&Bin)) {
2332     outs() << "Archive : " << Filename << "\n";
2333     if (ArchiveHeaders)
2334       printArchiveHeaders(Filename, A, !NonVerbose, ArchiveMemberOffsets);
2335 
2336     Error Err = Error::success();
2337     unsigned I = -1;
2338     for (auto &C : A->children(Err)) {
2339       ++I;
2340       Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2341       if (!ChildOrErr) {
2342         if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2343           reportError(std::move(E), getFileNameForError(C, I), Filename);
2344         continue;
2345       }
2346       if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
2347         if (!checkMachOAndArchFlags(O, Filename))
2348           return;
2349         ProcessMachO(Filename, O, O->getFileName());
2350       }
2351     }
2352     if (Err)
2353       reportError(std::move(Err), Filename);
2354     return;
2355   }
2356   if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
2357     parseInputMachO(UB);
2358     return;
2359   }
2360   if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
2361     if (!checkMachOAndArchFlags(O, Filename))
2362       return;
2363     if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O))
2364       ProcessMachO(Filename, MachOOF);
2365     else
2366       WithColor::error(errs(), "llvm-objdump")
2367           << Filename << "': "
2368           << "object is not a Mach-O file type.\n";
2369     return;
2370   }
2371   llvm_unreachable("Input object can't be invalid at this point");
2372 }
2373 
2374 void parseInputMachO(MachOUniversalBinary *UB) {
2375   if (!ValidateArchFlags())
2376     return;
2377 
2378   auto Filename = UB->getFileName();
2379 
2380   if (UniversalHeaders)
2381     printMachOUniversalHeaders(UB, !NonVerbose);
2382 
2383   // If we have a list of architecture flags specified dump only those.
2384   if (!ArchAll && !ArchFlags.empty()) {
2385     // Look for a slice in the universal binary that matches each ArchFlag.
2386     bool ArchFound;
2387     for (unsigned i = 0; i < ArchFlags.size(); ++i) {
2388       ArchFound = false;
2389       for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2390                                                   E = UB->end_objects();
2391             I != E; ++I) {
2392         if (ArchFlags[i] == I->getArchFlagName()) {
2393           ArchFound = true;
2394           Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
2395               I->getAsObjectFile();
2396           std::string ArchitectureName = "";
2397           if (ArchFlags.size() > 1)
2398             ArchitectureName = I->getArchFlagName();
2399           if (ObjOrErr) {
2400             ObjectFile &O = *ObjOrErr.get();
2401             if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
2402               ProcessMachO(Filename, MachOOF, "", ArchitectureName);
2403           } else if (Error E = isNotObjectErrorInvalidFileType(
2404                          ObjOrErr.takeError())) {
2405             reportError(std::move(E), "", Filename, ArchitectureName);
2406             continue;
2407           } else if (Expected<std::unique_ptr<Archive>> AOrErr =
2408                          I->getAsArchive()) {
2409             std::unique_ptr<Archive> &A = *AOrErr;
2410             outs() << "Archive : " << Filename;
2411             if (!ArchitectureName.empty())
2412               outs() << " (architecture " << ArchitectureName << ")";
2413             outs() << "\n";
2414             if (ArchiveHeaders)
2415               printArchiveHeaders(Filename, A.get(), !NonVerbose,
2416                                   ArchiveMemberOffsets, ArchitectureName);
2417             Error Err = Error::success();
2418             unsigned I = -1;
2419             for (auto &C : A->children(Err)) {
2420               ++I;
2421               Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2422               if (!ChildOrErr) {
2423                 if (Error E =
2424                         isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2425                   reportError(std::move(E), getFileNameForError(C, I), Filename,
2426                               ArchitectureName);
2427                 continue;
2428               }
2429               if (MachOObjectFile *O =
2430                       dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
2431                 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
2432             }
2433             if (Err)
2434               reportError(std::move(Err), Filename);
2435           } else {
2436             consumeError(AOrErr.takeError());
2437             reportError(Filename,
2438                         "Mach-O universal file for architecture " +
2439                             StringRef(I->getArchFlagName()) +
2440                             " is not a Mach-O file or an archive file");
2441           }
2442         }
2443       }
2444       if (!ArchFound) {
2445         WithColor::error(errs(), "llvm-objdump")
2446             << "file: " + Filename + " does not contain "
2447             << "architecture: " + ArchFlags[i] + "\n";
2448         return;
2449       }
2450     }
2451     return;
2452   }
2453   // No architecture flags were specified so if this contains a slice that
2454   // matches the host architecture dump only that.
2455   if (!ArchAll) {
2456     for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2457                                                 E = UB->end_objects();
2458           I != E; ++I) {
2459       if (MachOObjectFile::getHostArch().getArchName() ==
2460           I->getArchFlagName()) {
2461         Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2462         std::string ArchiveName;
2463         ArchiveName.clear();
2464         if (ObjOrErr) {
2465           ObjectFile &O = *ObjOrErr.get();
2466           if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
2467             ProcessMachO(Filename, MachOOF);
2468         } else if (Error E =
2469                        isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) {
2470           reportError(std::move(E), Filename);
2471         } else if (Expected<std::unique_ptr<Archive>> AOrErr =
2472                        I->getAsArchive()) {
2473           std::unique_ptr<Archive> &A = *AOrErr;
2474           outs() << "Archive : " << Filename << "\n";
2475           if (ArchiveHeaders)
2476             printArchiveHeaders(Filename, A.get(), !NonVerbose,
2477                                 ArchiveMemberOffsets);
2478           Error Err = Error::success();
2479           unsigned I = -1;
2480           for (auto &C : A->children(Err)) {
2481             ++I;
2482             Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2483             if (!ChildOrErr) {
2484               if (Error E =
2485                       isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2486                 reportError(std::move(E), getFileNameForError(C, I), Filename);
2487               continue;
2488             }
2489             if (MachOObjectFile *O =
2490                     dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
2491               ProcessMachO(Filename, O, O->getFileName());
2492           }
2493           if (Err)
2494             reportError(std::move(Err), Filename);
2495         } else {
2496           consumeError(AOrErr.takeError());
2497           reportError(Filename, "Mach-O universal file for architecture " +
2498                                     StringRef(I->getArchFlagName()) +
2499                                     " is not a Mach-O file or an archive file");
2500         }
2501         return;
2502       }
2503     }
2504   }
2505   // Either all architectures have been specified or none have been specified
2506   // and this does not contain the host architecture so dump all the slices.
2507   bool moreThanOneArch = UB->getNumberOfObjects() > 1;
2508   for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2509                                               E = UB->end_objects();
2510         I != E; ++I) {
2511     Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2512     std::string ArchitectureName = "";
2513     if (moreThanOneArch)
2514       ArchitectureName = I->getArchFlagName();
2515     if (ObjOrErr) {
2516       ObjectFile &Obj = *ObjOrErr.get();
2517       if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
2518         ProcessMachO(Filename, MachOOF, "", ArchitectureName);
2519     } else if (Error E =
2520                    isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) {
2521       reportError(std::move(E), Filename, "", ArchitectureName);
2522     } else if (Expected<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
2523       std::unique_ptr<Archive> &A = *AOrErr;
2524       outs() << "Archive : " << Filename;
2525       if (!ArchitectureName.empty())
2526         outs() << " (architecture " << ArchitectureName << ")";
2527       outs() << "\n";
2528       if (ArchiveHeaders)
2529         printArchiveHeaders(Filename, A.get(), !NonVerbose,
2530                             ArchiveMemberOffsets, ArchitectureName);
2531       Error Err = Error::success();
2532       unsigned I = -1;
2533       for (auto &C : A->children(Err)) {
2534         ++I;
2535         Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2536         if (!ChildOrErr) {
2537           if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2538             reportError(std::move(E), getFileNameForError(C, I), Filename,
2539                         ArchitectureName);
2540           continue;
2541         }
2542         if (MachOObjectFile *O =
2543                 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
2544           if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
2545             ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
2546                           ArchitectureName);
2547         }
2548       }
2549       if (Err)
2550         reportError(std::move(Err), Filename);
2551     } else {
2552       consumeError(AOrErr.takeError());
2553       reportError(Filename, "Mach-O universal file for architecture " +
2554                                 StringRef(I->getArchFlagName()) +
2555                                 " is not a Mach-O file or an archive file");
2556     }
2557   }
2558 }
2559 
2560 // The block of info used by the Symbolizer call backs.
2561 struct DisassembleInfo {
2562   DisassembleInfo(MachOObjectFile *O, SymbolAddressMap *AddrMap,
2563                   std::vector<SectionRef> *Sections, bool verbose)
2564     : verbose(verbose), O(O), AddrMap(AddrMap), Sections(Sections) {}
2565   bool verbose;
2566   MachOObjectFile *O;
2567   SectionRef S;
2568   SymbolAddressMap *AddrMap;
2569   std::vector<SectionRef> *Sections;
2570   const char *class_name = nullptr;
2571   const char *selector_name = nullptr;
2572   std::unique_ptr<char[]> method = nullptr;
2573   char *demangled_name = nullptr;
2574   uint64_t adrp_addr = 0;
2575   uint32_t adrp_inst = 0;
2576   std::unique_ptr<SymbolAddressMap> bindtable;
2577   uint32_t depth = 0;
2578 };
2579 
2580 // SymbolizerGetOpInfo() is the operand information call back function.
2581 // This is called to get the symbolic information for operand(s) of an
2582 // instruction when it is being done.  This routine does this from
2583 // the relocation information, symbol table, etc. That block of information
2584 // is a pointer to the struct DisassembleInfo that was passed when the
2585 // disassembler context was created and passed to back to here when
2586 // called back by the disassembler for instruction operands that could have
2587 // relocation information. The address of the instruction containing operand is
2588 // at the Pc parameter.  The immediate value the operand has is passed in
2589 // op_info->Value and is at Offset past the start of the instruction and has a
2590 // byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
2591 // LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
2592 // names and addends of the symbolic expression to add for the operand.  The
2593 // value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
2594 // information is returned then this function returns 1 else it returns 0.
2595 static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
2596                                uint64_t Size, int TagType, void *TagBuf) {
2597   struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
2598   struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
2599   uint64_t value = op_info->Value;
2600 
2601   // Make sure all fields returned are zero if we don't set them.
2602   memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
2603   op_info->Value = value;
2604 
2605   // If the TagType is not the value 1 which it code knows about or if no
2606   // verbose symbolic information is wanted then just return 0, indicating no
2607   // information is being returned.
2608   if (TagType != 1 || !info->verbose)
2609     return 0;
2610 
2611   unsigned int Arch = info->O->getArch();
2612   if (Arch == Triple::x86) {
2613     if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
2614       return 0;
2615     if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2616       // TODO:
2617       // Search the external relocation entries of a fully linked image
2618       // (if any) for an entry that matches this segment offset.
2619       // uint32_t seg_offset = (Pc + Offset);
2620       return 0;
2621     }
2622     // In MH_OBJECT filetypes search the section's relocation entries (if any)
2623     // for an entry for this section offset.
2624     uint32_t sect_addr = info->S.getAddress();
2625     uint32_t sect_offset = (Pc + Offset) - sect_addr;
2626     bool reloc_found = false;
2627     DataRefImpl Rel;
2628     MachO::any_relocation_info RE;
2629     bool isExtern = false;
2630     SymbolRef Symbol;
2631     bool r_scattered = false;
2632     uint32_t r_value, pair_r_value, r_type;
2633     for (const RelocationRef &Reloc : info->S.relocations()) {
2634       uint64_t RelocOffset = Reloc.getOffset();
2635       if (RelocOffset == sect_offset) {
2636         Rel = Reloc.getRawDataRefImpl();
2637         RE = info->O->getRelocation(Rel);
2638         r_type = info->O->getAnyRelocationType(RE);
2639         r_scattered = info->O->isRelocationScattered(RE);
2640         if (r_scattered) {
2641           r_value = info->O->getScatteredRelocationValue(RE);
2642           if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2643               r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
2644             DataRefImpl RelNext = Rel;
2645             info->O->moveRelocationNext(RelNext);
2646             MachO::any_relocation_info RENext;
2647             RENext = info->O->getRelocation(RelNext);
2648             if (info->O->isRelocationScattered(RENext))
2649               pair_r_value = info->O->getScatteredRelocationValue(RENext);
2650             else
2651               return 0;
2652           }
2653         } else {
2654           isExtern = info->O->getPlainRelocationExternal(RE);
2655           if (isExtern) {
2656             symbol_iterator RelocSym = Reloc.getSymbol();
2657             Symbol = *RelocSym;
2658           }
2659         }
2660         reloc_found = true;
2661         break;
2662       }
2663     }
2664     if (reloc_found && isExtern) {
2665       op_info->AddSymbol.Present = 1;
2666       op_info->AddSymbol.Name =
2667           unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
2668       // For i386 extern relocation entries the value in the instruction is
2669       // the offset from the symbol, and value is already set in op_info->Value.
2670       return 1;
2671     }
2672     if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2673                         r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
2674       const char *add = GuessSymbolName(r_value, info->AddrMap);
2675       const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
2676       uint32_t offset = value - (r_value - pair_r_value);
2677       op_info->AddSymbol.Present = 1;
2678       if (add != nullptr)
2679         op_info->AddSymbol.Name = add;
2680       else
2681         op_info->AddSymbol.Value = r_value;
2682       op_info->SubtractSymbol.Present = 1;
2683       if (sub != nullptr)
2684         op_info->SubtractSymbol.Name = sub;
2685       else
2686         op_info->SubtractSymbol.Value = pair_r_value;
2687       op_info->Value = offset;
2688       return 1;
2689     }
2690     return 0;
2691   }
2692   if (Arch == Triple::x86_64) {
2693     if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
2694       return 0;
2695     // For non MH_OBJECT types, like MH_KEXT_BUNDLE, Search the external
2696     // relocation entries of a linked image (if any) for an entry that matches
2697     // this segment offset.
2698     if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2699       uint64_t seg_offset = Pc + Offset;
2700       bool reloc_found = false;
2701       DataRefImpl Rel;
2702       MachO::any_relocation_info RE;
2703       bool isExtern = false;
2704       SymbolRef Symbol;
2705       for (const RelocationRef &Reloc : info->O->external_relocations()) {
2706         uint64_t RelocOffset = Reloc.getOffset();
2707         if (RelocOffset == seg_offset) {
2708           Rel = Reloc.getRawDataRefImpl();
2709           RE = info->O->getRelocation(Rel);
2710           // external relocation entries should always be external.
2711           isExtern = info->O->getPlainRelocationExternal(RE);
2712           if (isExtern) {
2713             symbol_iterator RelocSym = Reloc.getSymbol();
2714             Symbol = *RelocSym;
2715           }
2716           reloc_found = true;
2717           break;
2718         }
2719       }
2720       if (reloc_found && isExtern) {
2721         // The Value passed in will be adjusted by the Pc if the instruction
2722         // adds the Pc.  But for x86_64 external relocation entries the Value
2723         // is the offset from the external symbol.
2724         if (info->O->getAnyRelocationPCRel(RE))
2725           op_info->Value -= Pc + Offset + Size;
2726         const char *name =
2727             unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
2728         op_info->AddSymbol.Present = 1;
2729         op_info->AddSymbol.Name = name;
2730         return 1;
2731       }
2732       return 0;
2733     }
2734     // In MH_OBJECT filetypes search the section's relocation entries (if any)
2735     // for an entry for this section offset.
2736     uint64_t sect_addr = info->S.getAddress();
2737     uint64_t sect_offset = (Pc + Offset) - sect_addr;
2738     bool reloc_found = false;
2739     DataRefImpl Rel;
2740     MachO::any_relocation_info RE;
2741     bool isExtern = false;
2742     SymbolRef Symbol;
2743     for (const RelocationRef &Reloc : info->S.relocations()) {
2744       uint64_t RelocOffset = Reloc.getOffset();
2745       if (RelocOffset == sect_offset) {
2746         Rel = Reloc.getRawDataRefImpl();
2747         RE = info->O->getRelocation(Rel);
2748         // NOTE: Scattered relocations don't exist on x86_64.
2749         isExtern = info->O->getPlainRelocationExternal(RE);
2750         if (isExtern) {
2751           symbol_iterator RelocSym = Reloc.getSymbol();
2752           Symbol = *RelocSym;
2753         }
2754         reloc_found = true;
2755         break;
2756       }
2757     }
2758     if (reloc_found && isExtern) {
2759       // The Value passed in will be adjusted by the Pc if the instruction
2760       // adds the Pc.  But for x86_64 external relocation entries the Value
2761       // is the offset from the external symbol.
2762       if (info->O->getAnyRelocationPCRel(RE))
2763         op_info->Value -= Pc + Offset + Size;
2764       const char *name =
2765           unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
2766       unsigned Type = info->O->getAnyRelocationType(RE);
2767       if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
2768         DataRefImpl RelNext = Rel;
2769         info->O->moveRelocationNext(RelNext);
2770         MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2771         unsigned TypeNext = info->O->getAnyRelocationType(RENext);
2772         bool isExternNext = info->O->getPlainRelocationExternal(RENext);
2773         unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
2774         if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
2775           op_info->SubtractSymbol.Present = 1;
2776           op_info->SubtractSymbol.Name = name;
2777           symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
2778           Symbol = *RelocSymNext;
2779           name = unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
2780         }
2781       }
2782       // TODO: add the VariantKinds to op_info->VariantKind for relocation types
2783       // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
2784       op_info->AddSymbol.Present = 1;
2785       op_info->AddSymbol.Name = name;
2786       return 1;
2787     }
2788     return 0;
2789   }
2790   if (Arch == Triple::arm) {
2791     if (Offset != 0 || (Size != 4 && Size != 2))
2792       return 0;
2793     if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2794       // TODO:
2795       // Search the external relocation entries of a fully linked image
2796       // (if any) for an entry that matches this segment offset.
2797       // uint32_t seg_offset = (Pc + Offset);
2798       return 0;
2799     }
2800     // In MH_OBJECT filetypes search the section's relocation entries (if any)
2801     // for an entry for this section offset.
2802     uint32_t sect_addr = info->S.getAddress();
2803     uint32_t sect_offset = (Pc + Offset) - sect_addr;
2804     DataRefImpl Rel;
2805     MachO::any_relocation_info RE;
2806     bool isExtern = false;
2807     SymbolRef Symbol;
2808     bool r_scattered = false;
2809     uint32_t r_value, pair_r_value, r_type, r_length, other_half;
2810     auto Reloc =
2811         find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2812           uint64_t RelocOffset = Reloc.getOffset();
2813           return RelocOffset == sect_offset;
2814         });
2815 
2816     if (Reloc == info->S.relocations().end())
2817       return 0;
2818 
2819     Rel = Reloc->getRawDataRefImpl();
2820     RE = info->O->getRelocation(Rel);
2821     r_length = info->O->getAnyRelocationLength(RE);
2822     r_scattered = info->O->isRelocationScattered(RE);
2823     if (r_scattered) {
2824       r_value = info->O->getScatteredRelocationValue(RE);
2825       r_type = info->O->getScatteredRelocationType(RE);
2826     } else {
2827       r_type = info->O->getAnyRelocationType(RE);
2828       isExtern = info->O->getPlainRelocationExternal(RE);
2829       if (isExtern) {
2830         symbol_iterator RelocSym = Reloc->getSymbol();
2831         Symbol = *RelocSym;
2832       }
2833     }
2834     if (r_type == MachO::ARM_RELOC_HALF ||
2835         r_type == MachO::ARM_RELOC_SECTDIFF ||
2836         r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
2837         r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2838       DataRefImpl RelNext = Rel;
2839       info->O->moveRelocationNext(RelNext);
2840       MachO::any_relocation_info RENext;
2841       RENext = info->O->getRelocation(RelNext);
2842       other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
2843       if (info->O->isRelocationScattered(RENext))
2844         pair_r_value = info->O->getScatteredRelocationValue(RENext);
2845     }
2846 
2847     if (isExtern) {
2848       const char *name =
2849           unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
2850       op_info->AddSymbol.Present = 1;
2851       op_info->AddSymbol.Name = name;
2852       switch (r_type) {
2853       case MachO::ARM_RELOC_HALF:
2854         if ((r_length & 0x1) == 1) {
2855           op_info->Value = value << 16 | other_half;
2856           op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2857         } else {
2858           op_info->Value = other_half << 16 | value;
2859           op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
2860         }
2861         break;
2862       default:
2863         break;
2864       }
2865       return 1;
2866     }
2867     // If we have a branch that is not an external relocation entry then
2868     // return 0 so the code in tryAddingSymbolicOperand() can use the
2869     // SymbolLookUp call back with the branch target address to look up the
2870     // symbol and possibility add an annotation for a symbol stub.
2871     if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
2872                           r_type == MachO::ARM_THUMB_RELOC_BR22))
2873       return 0;
2874 
2875     uint32_t offset = 0;
2876     if (r_type == MachO::ARM_RELOC_HALF ||
2877         r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2878       if ((r_length & 0x1) == 1)
2879         value = value << 16 | other_half;
2880       else
2881         value = other_half << 16 | value;
2882     }
2883     if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
2884                         r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
2885       offset = value - r_value;
2886       value = r_value;
2887     }
2888 
2889     if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2890       if ((r_length & 0x1) == 1)
2891         op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2892       else
2893         op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
2894       const char *add = GuessSymbolName(r_value, info->AddrMap);
2895       const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
2896       int32_t offset = value - (r_value - pair_r_value);
2897       op_info->AddSymbol.Present = 1;
2898       if (add != nullptr)
2899         op_info->AddSymbol.Name = add;
2900       else
2901         op_info->AddSymbol.Value = r_value;
2902       op_info->SubtractSymbol.Present = 1;
2903       if (sub != nullptr)
2904         op_info->SubtractSymbol.Name = sub;
2905       else
2906         op_info->SubtractSymbol.Value = pair_r_value;
2907       op_info->Value = offset;
2908       return 1;
2909     }
2910 
2911     op_info->AddSymbol.Present = 1;
2912     op_info->Value = offset;
2913     if (r_type == MachO::ARM_RELOC_HALF) {
2914       if ((r_length & 0x1) == 1)
2915         op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2916       else
2917         op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
2918     }
2919     const char *add = GuessSymbolName(value, info->AddrMap);
2920     if (add != nullptr) {
2921       op_info->AddSymbol.Name = add;
2922       return 1;
2923     }
2924     op_info->AddSymbol.Value = value;
2925     return 1;
2926   }
2927   if (Arch == Triple::aarch64) {
2928     if (Offset != 0 || Size != 4)
2929       return 0;
2930     if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2931       // TODO:
2932       // Search the external relocation entries of a fully linked image
2933       // (if any) for an entry that matches this segment offset.
2934       // uint64_t seg_offset = (Pc + Offset);
2935       return 0;
2936     }
2937     // In MH_OBJECT filetypes search the section's relocation entries (if any)
2938     // for an entry for this section offset.
2939     uint64_t sect_addr = info->S.getAddress();
2940     uint64_t sect_offset = (Pc + Offset) - sect_addr;
2941     auto Reloc =
2942         find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2943           uint64_t RelocOffset = Reloc.getOffset();
2944           return RelocOffset == sect_offset;
2945         });
2946 
2947     if (Reloc == info->S.relocations().end())
2948       return 0;
2949 
2950     DataRefImpl Rel = Reloc->getRawDataRefImpl();
2951     MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2952     uint32_t r_type = info->O->getAnyRelocationType(RE);
2953     if (r_type == MachO::ARM64_RELOC_ADDEND) {
2954       DataRefImpl RelNext = Rel;
2955       info->O->moveRelocationNext(RelNext);
2956       MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2957       if (value == 0) {
2958         value = info->O->getPlainRelocationSymbolNum(RENext);
2959         op_info->Value = value;
2960       }
2961     }
2962     // NOTE: Scattered relocations don't exist on arm64.
2963     if (!info->O->getPlainRelocationExternal(RE))
2964       return 0;
2965     const char *name =
2966         unwrapOrError(Reloc->getSymbol()->getName(), info->O->getFileName())
2967             .data();
2968     op_info->AddSymbol.Present = 1;
2969     op_info->AddSymbol.Name = name;
2970 
2971     switch (r_type) {
2972     case MachO::ARM64_RELOC_PAGE21:
2973       /* @page */
2974       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2975       break;
2976     case MachO::ARM64_RELOC_PAGEOFF12:
2977       /* @pageoff */
2978       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2979       break;
2980     case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2981       /* @gotpage */
2982       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2983       break;
2984     case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2985       /* @gotpageoff */
2986       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2987       break;
2988     case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2989       /* @tvlppage is not implemented in llvm-mc */
2990       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2991       break;
2992     case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2993       /* @tvlppageoff is not implemented in llvm-mc */
2994       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2995       break;
2996     default:
2997     case MachO::ARM64_RELOC_BRANCH26:
2998       op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2999       break;
3000     }
3001     return 1;
3002   }
3003   return 0;
3004 }
3005 
3006 // GuessCstringPointer is passed the address of what might be a pointer to a
3007 // literal string in a cstring section.  If that address is in a cstring section
3008 // it returns a pointer to that string.  Else it returns nullptr.
3009 static const char *GuessCstringPointer(uint64_t ReferenceValue,
3010                                        struct DisassembleInfo *info) {
3011   for (const auto &Load : info->O->load_commands()) {
3012     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
3013       MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
3014       for (unsigned J = 0; J < Seg.nsects; ++J) {
3015         MachO::section_64 Sec = info->O->getSection64(Load, J);
3016         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3017         if (section_type == MachO::S_CSTRING_LITERALS &&
3018             ReferenceValue >= Sec.addr &&
3019             ReferenceValue < Sec.addr + Sec.size) {
3020           uint64_t sect_offset = ReferenceValue - Sec.addr;
3021           uint64_t object_offset = Sec.offset + sect_offset;
3022           StringRef MachOContents = info->O->getData();
3023           uint64_t object_size = MachOContents.size();
3024           const char *object_addr = (const char *)MachOContents.data();
3025           if (object_offset < object_size) {
3026             const char *name = object_addr + object_offset;
3027             return name;
3028           } else {
3029             return nullptr;
3030           }
3031         }
3032       }
3033     } else if (Load.C.cmd == MachO::LC_SEGMENT) {
3034       MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
3035       for (unsigned J = 0; J < Seg.nsects; ++J) {
3036         MachO::section Sec = info->O->getSection(Load, J);
3037         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3038         if (section_type == MachO::S_CSTRING_LITERALS &&
3039             ReferenceValue >= Sec.addr &&
3040             ReferenceValue < Sec.addr + Sec.size) {
3041           uint64_t sect_offset = ReferenceValue - Sec.addr;
3042           uint64_t object_offset = Sec.offset + sect_offset;
3043           StringRef MachOContents = info->O->getData();
3044           uint64_t object_size = MachOContents.size();
3045           const char *object_addr = (const char *)MachOContents.data();
3046           if (object_offset < object_size) {
3047             const char *name = object_addr + object_offset;
3048             return name;
3049           } else {
3050             return nullptr;
3051           }
3052         }
3053       }
3054     }
3055   }
3056   return nullptr;
3057 }
3058 
3059 // GuessIndirectSymbol returns the name of the indirect symbol for the
3060 // ReferenceValue passed in or nullptr.  This is used when ReferenceValue maybe
3061 // an address of a symbol stub or a lazy or non-lazy pointer to associate the
3062 // symbol name being referenced by the stub or pointer.
3063 static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
3064                                        struct DisassembleInfo *info) {
3065   MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
3066   MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
3067   for (const auto &Load : info->O->load_commands()) {
3068     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
3069       MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
3070       for (unsigned J = 0; J < Seg.nsects; ++J) {
3071         MachO::section_64 Sec = info->O->getSection64(Load, J);
3072         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3073         if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
3074              section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
3075              section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
3076              section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
3077              section_type == MachO::S_SYMBOL_STUBS) &&
3078             ReferenceValue >= Sec.addr &&
3079             ReferenceValue < Sec.addr + Sec.size) {
3080           uint32_t stride;
3081           if (section_type == MachO::S_SYMBOL_STUBS)
3082             stride = Sec.reserved2;
3083           else
3084             stride = 8;
3085           if (stride == 0)
3086             return nullptr;
3087           uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
3088           if (index < Dysymtab.nindirectsyms) {
3089             uint32_t indirect_symbol =
3090                 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
3091             if (indirect_symbol < Symtab.nsyms) {
3092               symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
3093               return unwrapOrError(Sym->getName(), info->O->getFileName())
3094                   .data();
3095             }
3096           }
3097         }
3098       }
3099     } else if (Load.C.cmd == MachO::LC_SEGMENT) {
3100       MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
3101       for (unsigned J = 0; J < Seg.nsects; ++J) {
3102         MachO::section Sec = info->O->getSection(Load, J);
3103         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3104         if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
3105              section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
3106              section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
3107              section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
3108              section_type == MachO::S_SYMBOL_STUBS) &&
3109             ReferenceValue >= Sec.addr &&
3110             ReferenceValue < Sec.addr + Sec.size) {
3111           uint32_t stride;
3112           if (section_type == MachO::S_SYMBOL_STUBS)
3113             stride = Sec.reserved2;
3114           else
3115             stride = 4;
3116           if (stride == 0)
3117             return nullptr;
3118           uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
3119           if (index < Dysymtab.nindirectsyms) {
3120             uint32_t indirect_symbol =
3121                 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
3122             if (indirect_symbol < Symtab.nsyms) {
3123               symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
3124               return unwrapOrError(Sym->getName(), info->O->getFileName())
3125                   .data();
3126             }
3127           }
3128         }
3129       }
3130     }
3131   }
3132   return nullptr;
3133 }
3134 
3135 // method_reference() is called passing it the ReferenceName that might be
3136 // a reference it to an Objective-C method call.  If so then it allocates and
3137 // assembles a method call string with the values last seen and saved in
3138 // the DisassembleInfo's class_name and selector_name fields.  This is saved
3139 // into the method field of the info and any previous string is free'ed.
3140 // Then the class_name field in the info is set to nullptr.  The method call
3141 // string is set into ReferenceName and ReferenceType is set to
3142 // LLVMDisassembler_ReferenceType_Out_Objc_Message.  If this not a method call
3143 // then both ReferenceType and ReferenceName are left unchanged.
3144 static void method_reference(struct DisassembleInfo *info,
3145                              uint64_t *ReferenceType,
3146                              const char **ReferenceName) {
3147   unsigned int Arch = info->O->getArch();
3148   if (*ReferenceName != nullptr) {
3149     if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
3150       if (info->selector_name != nullptr) {
3151         if (info->class_name != nullptr) {
3152           info->method = std::make_unique<char[]>(
3153               5 + strlen(info->class_name) + strlen(info->selector_name));
3154           char *method = info->method.get();
3155           if (method != nullptr) {
3156             strcpy(method, "+[");
3157             strcat(method, info->class_name);
3158             strcat(method, " ");
3159             strcat(method, info->selector_name);
3160             strcat(method, "]");
3161             *ReferenceName = method;
3162             *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3163           }
3164         } else {
3165           info->method =
3166               std::make_unique<char[]>(9 + strlen(info->selector_name));
3167           char *method = info->method.get();
3168           if (method != nullptr) {
3169             if (Arch == Triple::x86_64)
3170               strcpy(method, "-[%rdi ");
3171             else if (Arch == Triple::aarch64)
3172               strcpy(method, "-[x0 ");
3173             else
3174               strcpy(method, "-[r? ");
3175             strcat(method, info->selector_name);
3176             strcat(method, "]");
3177             *ReferenceName = method;
3178             *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3179           }
3180         }
3181         info->class_name = nullptr;
3182       }
3183     } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
3184       if (info->selector_name != nullptr) {
3185         info->method =
3186             std::make_unique<char[]>(17 + strlen(info->selector_name));
3187         char *method = info->method.get();
3188         if (method != nullptr) {
3189           if (Arch == Triple::x86_64)
3190             strcpy(method, "-[[%rdi super] ");
3191           else if (Arch == Triple::aarch64)
3192             strcpy(method, "-[[x0 super] ");
3193           else
3194             strcpy(method, "-[[r? super] ");
3195           strcat(method, info->selector_name);
3196           strcat(method, "]");
3197           *ReferenceName = method;
3198           *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3199         }
3200         info->class_name = nullptr;
3201       }
3202     }
3203   }
3204 }
3205 
3206 // GuessPointerPointer() is passed the address of what might be a pointer to
3207 // a reference to an Objective-C class, selector, message ref or cfstring.
3208 // If so the value of the pointer is returned and one of the booleans are set
3209 // to true.  If not zero is returned and all the booleans are set to false.
3210 static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
3211                                     struct DisassembleInfo *info,
3212                                     bool &classref, bool &selref, bool &msgref,
3213                                     bool &cfstring) {
3214   classref = false;
3215   selref = false;
3216   msgref = false;
3217   cfstring = false;
3218   for (const auto &Load : info->O->load_commands()) {
3219     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
3220       MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
3221       for (unsigned J = 0; J < Seg.nsects; ++J) {
3222         MachO::section_64 Sec = info->O->getSection64(Load, J);
3223         if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
3224              strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
3225              strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
3226              strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
3227              strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
3228             ReferenceValue >= Sec.addr &&
3229             ReferenceValue < Sec.addr + Sec.size) {
3230           uint64_t sect_offset = ReferenceValue - Sec.addr;
3231           uint64_t object_offset = Sec.offset + sect_offset;
3232           StringRef MachOContents = info->O->getData();
3233           uint64_t object_size = MachOContents.size();
3234           const char *object_addr = (const char *)MachOContents.data();
3235           if (object_offset < object_size) {
3236             uint64_t pointer_value;
3237             memcpy(&pointer_value, object_addr + object_offset,
3238                    sizeof(uint64_t));
3239             if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3240               sys::swapByteOrder(pointer_value);
3241             if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
3242               selref = true;
3243             else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
3244                      strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
3245               classref = true;
3246             else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
3247                      ReferenceValue + 8 < Sec.addr + Sec.size) {
3248               msgref = true;
3249               memcpy(&pointer_value, object_addr + object_offset + 8,
3250                      sizeof(uint64_t));
3251               if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3252                 sys::swapByteOrder(pointer_value);
3253             } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
3254               cfstring = true;
3255             return pointer_value;
3256           } else {
3257             return 0;
3258           }
3259         }
3260       }
3261     }
3262     // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
3263   }
3264   return 0;
3265 }
3266 
3267 // get_pointer_64 returns a pointer to the bytes in the object file at the
3268 // Address from a section in the Mach-O file.  And indirectly returns the
3269 // offset into the section, number of bytes left in the section past the offset
3270 // and which section is was being referenced.  If the Address is not in a
3271 // section nullptr is returned.
3272 static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
3273                                   uint32_t &left, SectionRef &S,
3274                                   DisassembleInfo *info,
3275                                   bool objc_only = false) {
3276   offset = 0;
3277   left = 0;
3278   S = SectionRef();
3279   for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
3280     uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
3281     uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
3282     if (SectSize == 0)
3283       continue;
3284     if (objc_only) {
3285       StringRef SectName;
3286       Expected<StringRef> SecNameOrErr =
3287           ((*(info->Sections))[SectIdx]).getName();
3288       if (SecNameOrErr)
3289         SectName = *SecNameOrErr;
3290       else
3291         consumeError(SecNameOrErr.takeError());
3292 
3293       DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
3294       StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
3295       if (SegName != "__OBJC" && SectName != "__cstring")
3296         continue;
3297     }
3298     if (Address >= SectAddress && Address < SectAddress + SectSize) {
3299       S = (*(info->Sections))[SectIdx];
3300       offset = Address - SectAddress;
3301       left = SectSize - offset;
3302       StringRef SectContents = unwrapOrError(
3303           ((*(info->Sections))[SectIdx]).getContents(), info->O->getFileName());
3304       return SectContents.data() + offset;
3305     }
3306   }
3307   return nullptr;
3308 }
3309 
3310 static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
3311                                   uint32_t &left, SectionRef &S,
3312                                   DisassembleInfo *info,
3313                                   bool objc_only = false) {
3314   return get_pointer_64(Address, offset, left, S, info, objc_only);
3315 }
3316 
3317 // get_symbol_64() returns the name of a symbol (or nullptr) and the address of
3318 // the symbol indirectly through n_value. Based on the relocation information
3319 // for the specified section offset in the specified section reference.
3320 // If no relocation information is found and a non-zero ReferenceValue for the
3321 // symbol is passed, look up that address in the info's AddrMap.
3322 static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
3323                                  DisassembleInfo *info, uint64_t &n_value,
3324                                  uint64_t ReferenceValue = 0) {
3325   n_value = 0;
3326   if (!info->verbose)
3327     return nullptr;
3328 
3329   // See if there is an external relocation entry at the sect_offset.
3330   bool reloc_found = false;
3331   DataRefImpl Rel;
3332   MachO::any_relocation_info RE;
3333   bool isExtern = false;
3334   SymbolRef Symbol;
3335   for (const RelocationRef &Reloc : S.relocations()) {
3336     uint64_t RelocOffset = Reloc.getOffset();
3337     if (RelocOffset == sect_offset) {
3338       Rel = Reloc.getRawDataRefImpl();
3339       RE = info->O->getRelocation(Rel);
3340       if (info->O->isRelocationScattered(RE))
3341         continue;
3342       isExtern = info->O->getPlainRelocationExternal(RE);
3343       if (isExtern) {
3344         symbol_iterator RelocSym = Reloc.getSymbol();
3345         Symbol = *RelocSym;
3346       }
3347       reloc_found = true;
3348       break;
3349     }
3350   }
3351   // If there is an external relocation entry for a symbol in this section
3352   // at this section_offset then use that symbol's value for the n_value
3353   // and return its name.
3354   const char *SymbolName = nullptr;
3355   if (reloc_found && isExtern) {
3356     n_value = Symbol.getValue();
3357     StringRef Name = unwrapOrError(Symbol.getName(), info->O->getFileName());
3358     if (!Name.empty()) {
3359       SymbolName = Name.data();
3360       return SymbolName;
3361     }
3362   }
3363 
3364   // TODO: For fully linked images, look through the external relocation
3365   // entries off the dynamic symtab command. For these the r_offset is from the
3366   // start of the first writeable segment in the Mach-O file.  So the offset
3367   // to this section from that segment is passed to this routine by the caller,
3368   // as the database_offset. Which is the difference of the section's starting
3369   // address and the first writable segment.
3370   //
3371   // NOTE: need add passing the database_offset to this routine.
3372 
3373   // We did not find an external relocation entry so look up the ReferenceValue
3374   // as an address of a symbol and if found return that symbol's name.
3375   SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
3376 
3377   return SymbolName;
3378 }
3379 
3380 static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
3381                                  DisassembleInfo *info,
3382                                  uint32_t ReferenceValue) {
3383   uint64_t n_value64;
3384   return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
3385 }
3386 
3387 // These are structs in the Objective-C meta data and read to produce the
3388 // comments for disassembly.  While these are part of the ABI they are no
3389 // public defintions.  So the are here not in include/llvm/BinaryFormat/MachO.h
3390 // .
3391 
3392 // The cfstring object in a 64-bit Mach-O file.
3393 struct cfstring64_t {
3394   uint64_t isa;        // class64_t * (64-bit pointer)
3395   uint64_t flags;      // flag bits
3396   uint64_t characters; // char * (64-bit pointer)
3397   uint64_t length;     // number of non-NULL characters in above
3398 };
3399 
3400 // The class object in a 64-bit Mach-O file.
3401 struct class64_t {
3402   uint64_t isa;        // class64_t * (64-bit pointer)
3403   uint64_t superclass; // class64_t * (64-bit pointer)
3404   uint64_t cache;      // Cache (64-bit pointer)
3405   uint64_t vtable;     // IMP * (64-bit pointer)
3406   uint64_t data;       // class_ro64_t * (64-bit pointer)
3407 };
3408 
3409 struct class32_t {
3410   uint32_t isa;        /* class32_t * (32-bit pointer) */
3411   uint32_t superclass; /* class32_t * (32-bit pointer) */
3412   uint32_t cache;      /* Cache (32-bit pointer) */
3413   uint32_t vtable;     /* IMP * (32-bit pointer) */
3414   uint32_t data;       /* class_ro32_t * (32-bit pointer) */
3415 };
3416 
3417 struct class_ro64_t {
3418   uint32_t flags;
3419   uint32_t instanceStart;
3420   uint32_t instanceSize;
3421   uint32_t reserved;
3422   uint64_t ivarLayout;     // const uint8_t * (64-bit pointer)
3423   uint64_t name;           // const char * (64-bit pointer)
3424   uint64_t baseMethods;    // const method_list_t * (64-bit pointer)
3425   uint64_t baseProtocols;  // const protocol_list_t * (64-bit pointer)
3426   uint64_t ivars;          // const ivar_list_t * (64-bit pointer)
3427   uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
3428   uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
3429 };
3430 
3431 struct class_ro32_t {
3432   uint32_t flags;
3433   uint32_t instanceStart;
3434   uint32_t instanceSize;
3435   uint32_t ivarLayout;     /* const uint8_t * (32-bit pointer) */
3436   uint32_t name;           /* const char * (32-bit pointer) */
3437   uint32_t baseMethods;    /* const method_list_t * (32-bit pointer) */
3438   uint32_t baseProtocols;  /* const protocol_list_t * (32-bit pointer) */
3439   uint32_t ivars;          /* const ivar_list_t * (32-bit pointer) */
3440   uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
3441   uint32_t baseProperties; /* const struct objc_property_list *
3442                                                    (32-bit pointer) */
3443 };
3444 
3445 /* Values for class_ro{64,32}_t->flags */
3446 #define RO_META (1 << 0)
3447 #define RO_ROOT (1 << 1)
3448 #define RO_HAS_CXX_STRUCTORS (1 << 2)
3449 
3450 struct method_list64_t {
3451   uint32_t entsize;
3452   uint32_t count;
3453   /* struct method64_t first;  These structures follow inline */
3454 };
3455 
3456 struct method_list32_t {
3457   uint32_t entsize;
3458   uint32_t count;
3459   /* struct method32_t first;  These structures follow inline */
3460 };
3461 
3462 struct method64_t {
3463   uint64_t name;  /* SEL (64-bit pointer) */
3464   uint64_t types; /* const char * (64-bit pointer) */
3465   uint64_t imp;   /* IMP (64-bit pointer) */
3466 };
3467 
3468 struct method32_t {
3469   uint32_t name;  /* SEL (32-bit pointer) */
3470   uint32_t types; /* const char * (32-bit pointer) */
3471   uint32_t imp;   /* IMP (32-bit pointer) */
3472 };
3473 
3474 struct protocol_list64_t {
3475   uint64_t count; /* uintptr_t (a 64-bit value) */
3476   /* struct protocol64_t * list[0];  These pointers follow inline */
3477 };
3478 
3479 struct protocol_list32_t {
3480   uint32_t count; /* uintptr_t (a 32-bit value) */
3481   /* struct protocol32_t * list[0];  These pointers follow inline */
3482 };
3483 
3484 struct protocol64_t {
3485   uint64_t isa;                     /* id * (64-bit pointer) */
3486   uint64_t name;                    /* const char * (64-bit pointer) */
3487   uint64_t protocols;               /* struct protocol_list64_t *
3488                                                     (64-bit pointer) */
3489   uint64_t instanceMethods;         /* method_list_t * (64-bit pointer) */
3490   uint64_t classMethods;            /* method_list_t * (64-bit pointer) */
3491   uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
3492   uint64_t optionalClassMethods;    /* method_list_t * (64-bit pointer) */
3493   uint64_t instanceProperties;      /* struct objc_property_list *
3494                                                        (64-bit pointer) */
3495 };
3496 
3497 struct protocol32_t {
3498   uint32_t isa;                     /* id * (32-bit pointer) */
3499   uint32_t name;                    /* const char * (32-bit pointer) */
3500   uint32_t protocols;               /* struct protocol_list_t *
3501                                                     (32-bit pointer) */
3502   uint32_t instanceMethods;         /* method_list_t * (32-bit pointer) */
3503   uint32_t classMethods;            /* method_list_t * (32-bit pointer) */
3504   uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
3505   uint32_t optionalClassMethods;    /* method_list_t * (32-bit pointer) */
3506   uint32_t instanceProperties;      /* struct objc_property_list *
3507                                                        (32-bit pointer) */
3508 };
3509 
3510 struct ivar_list64_t {
3511   uint32_t entsize;
3512   uint32_t count;
3513   /* struct ivar64_t first;  These structures follow inline */
3514 };
3515 
3516 struct ivar_list32_t {
3517   uint32_t entsize;
3518   uint32_t count;
3519   /* struct ivar32_t first;  These structures follow inline */
3520 };
3521 
3522 struct ivar64_t {
3523   uint64_t offset; /* uintptr_t * (64-bit pointer) */
3524   uint64_t name;   /* const char * (64-bit pointer) */
3525   uint64_t type;   /* const char * (64-bit pointer) */
3526   uint32_t alignment;
3527   uint32_t size;
3528 };
3529 
3530 struct ivar32_t {
3531   uint32_t offset; /* uintptr_t * (32-bit pointer) */
3532   uint32_t name;   /* const char * (32-bit pointer) */
3533   uint32_t type;   /* const char * (32-bit pointer) */
3534   uint32_t alignment;
3535   uint32_t size;
3536 };
3537 
3538 struct objc_property_list64 {
3539   uint32_t entsize;
3540   uint32_t count;
3541   /* struct objc_property64 first;  These structures follow inline */
3542 };
3543 
3544 struct objc_property_list32 {
3545   uint32_t entsize;
3546   uint32_t count;
3547   /* struct objc_property32 first;  These structures follow inline */
3548 };
3549 
3550 struct objc_property64 {
3551   uint64_t name;       /* const char * (64-bit pointer) */
3552   uint64_t attributes; /* const char * (64-bit pointer) */
3553 };
3554 
3555 struct objc_property32 {
3556   uint32_t name;       /* const char * (32-bit pointer) */
3557   uint32_t attributes; /* const char * (32-bit pointer) */
3558 };
3559 
3560 struct category64_t {
3561   uint64_t name;               /* const char * (64-bit pointer) */
3562   uint64_t cls;                /* struct class_t * (64-bit pointer) */
3563   uint64_t instanceMethods;    /* struct method_list_t * (64-bit pointer) */
3564   uint64_t classMethods;       /* struct method_list_t * (64-bit pointer) */
3565   uint64_t protocols;          /* struct protocol_list_t * (64-bit pointer) */
3566   uint64_t instanceProperties; /* struct objc_property_list *
3567                                   (64-bit pointer) */
3568 };
3569 
3570 struct category32_t {
3571   uint32_t name;               /* const char * (32-bit pointer) */
3572   uint32_t cls;                /* struct class_t * (32-bit pointer) */
3573   uint32_t instanceMethods;    /* struct method_list_t * (32-bit pointer) */
3574   uint32_t classMethods;       /* struct method_list_t * (32-bit pointer) */
3575   uint32_t protocols;          /* struct protocol_list_t * (32-bit pointer) */
3576   uint32_t instanceProperties; /* struct objc_property_list *
3577                                   (32-bit pointer) */
3578 };
3579 
3580 struct objc_image_info64 {
3581   uint32_t version;
3582   uint32_t flags;
3583 };
3584 struct objc_image_info32 {
3585   uint32_t version;
3586   uint32_t flags;
3587 };
3588 struct imageInfo_t {
3589   uint32_t version;
3590   uint32_t flags;
3591 };
3592 /* masks for objc_image_info.flags */
3593 #define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
3594 #define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
3595 #define OBJC_IMAGE_IS_SIMULATED (1 << 5)
3596 #define OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES (1 << 6)
3597 
3598 struct message_ref64 {
3599   uint64_t imp; /* IMP (64-bit pointer) */
3600   uint64_t sel; /* SEL (64-bit pointer) */
3601 };
3602 
3603 struct message_ref32 {
3604   uint32_t imp; /* IMP (32-bit pointer) */
3605   uint32_t sel; /* SEL (32-bit pointer) */
3606 };
3607 
3608 // Objective-C 1 (32-bit only) meta data structs.
3609 
3610 struct objc_module_t {
3611   uint32_t version;
3612   uint32_t size;
3613   uint32_t name;   /* char * (32-bit pointer) */
3614   uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
3615 };
3616 
3617 struct objc_symtab_t {
3618   uint32_t sel_ref_cnt;
3619   uint32_t refs; /* SEL * (32-bit pointer) */
3620   uint16_t cls_def_cnt;
3621   uint16_t cat_def_cnt;
3622   // uint32_t defs[1];        /* void * (32-bit pointer) variable size */
3623 };
3624 
3625 struct objc_class_t {
3626   uint32_t isa;         /* struct objc_class * (32-bit pointer) */
3627   uint32_t super_class; /* struct objc_class * (32-bit pointer) */
3628   uint32_t name;        /* const char * (32-bit pointer) */
3629   int32_t version;
3630   int32_t info;
3631   int32_t instance_size;
3632   uint32_t ivars;       /* struct objc_ivar_list * (32-bit pointer) */
3633   uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
3634   uint32_t cache;       /* struct objc_cache * (32-bit pointer) */
3635   uint32_t protocols;   /* struct objc_protocol_list * (32-bit pointer) */
3636 };
3637 
3638 #define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
3639 // class is not a metaclass
3640 #define CLS_CLASS 0x1
3641 // class is a metaclass
3642 #define CLS_META 0x2
3643 
3644 struct objc_category_t {
3645   uint32_t category_name;    /* char * (32-bit pointer) */
3646   uint32_t class_name;       /* char * (32-bit pointer) */
3647   uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
3648   uint32_t class_methods;    /* struct objc_method_list * (32-bit pointer) */
3649   uint32_t protocols;        /* struct objc_protocol_list * (32-bit ptr) */
3650 };
3651 
3652 struct objc_ivar_t {
3653   uint32_t ivar_name; /* char * (32-bit pointer) */
3654   uint32_t ivar_type; /* char * (32-bit pointer) */
3655   int32_t ivar_offset;
3656 };
3657 
3658 struct objc_ivar_list_t {
3659   int32_t ivar_count;
3660   // struct objc_ivar_t ivar_list[1];          /* variable length structure */
3661 };
3662 
3663 struct objc_method_list_t {
3664   uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
3665   int32_t method_count;
3666   // struct objc_method_t method_list[1];      /* variable length structure */
3667 };
3668 
3669 struct objc_method_t {
3670   uint32_t method_name;  /* SEL, aka struct objc_selector * (32-bit pointer) */
3671   uint32_t method_types; /* char * (32-bit pointer) */
3672   uint32_t method_imp;   /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
3673                             (32-bit pointer) */
3674 };
3675 
3676 struct objc_protocol_list_t {
3677   uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
3678   int32_t count;
3679   // uint32_t list[1];   /* Protocol *, aka struct objc_protocol_t *
3680   //                        (32-bit pointer) */
3681 };
3682 
3683 struct objc_protocol_t {
3684   uint32_t isa;              /* struct objc_class * (32-bit pointer) */
3685   uint32_t protocol_name;    /* char * (32-bit pointer) */
3686   uint32_t protocol_list;    /* struct objc_protocol_list * (32-bit pointer) */
3687   uint32_t instance_methods; /* struct objc_method_description_list *
3688                                 (32-bit pointer) */
3689   uint32_t class_methods;    /* struct objc_method_description_list *
3690                                 (32-bit pointer) */
3691 };
3692 
3693 struct objc_method_description_list_t {
3694   int32_t count;
3695   // struct objc_method_description_t list[1];
3696 };
3697 
3698 struct objc_method_description_t {
3699   uint32_t name;  /* SEL, aka struct objc_selector * (32-bit pointer) */
3700   uint32_t types; /* char * (32-bit pointer) */
3701 };
3702 
3703 inline void swapStruct(struct cfstring64_t &cfs) {
3704   sys::swapByteOrder(cfs.isa);
3705   sys::swapByteOrder(cfs.flags);
3706   sys::swapByteOrder(cfs.characters);
3707   sys::swapByteOrder(cfs.length);
3708 }
3709 
3710 inline void swapStruct(struct class64_t &c) {
3711   sys::swapByteOrder(c.isa);
3712   sys::swapByteOrder(c.superclass);
3713   sys::swapByteOrder(c.cache);
3714   sys::swapByteOrder(c.vtable);
3715   sys::swapByteOrder(c.data);
3716 }
3717 
3718 inline void swapStruct(struct class32_t &c) {
3719   sys::swapByteOrder(c.isa);
3720   sys::swapByteOrder(c.superclass);
3721   sys::swapByteOrder(c.cache);
3722   sys::swapByteOrder(c.vtable);
3723   sys::swapByteOrder(c.data);
3724 }
3725 
3726 inline void swapStruct(struct class_ro64_t &cro) {
3727   sys::swapByteOrder(cro.flags);
3728   sys::swapByteOrder(cro.instanceStart);
3729   sys::swapByteOrder(cro.instanceSize);
3730   sys::swapByteOrder(cro.reserved);
3731   sys::swapByteOrder(cro.ivarLayout);
3732   sys::swapByteOrder(cro.name);
3733   sys::swapByteOrder(cro.baseMethods);
3734   sys::swapByteOrder(cro.baseProtocols);
3735   sys::swapByteOrder(cro.ivars);
3736   sys::swapByteOrder(cro.weakIvarLayout);
3737   sys::swapByteOrder(cro.baseProperties);
3738 }
3739 
3740 inline void swapStruct(struct class_ro32_t &cro) {
3741   sys::swapByteOrder(cro.flags);
3742   sys::swapByteOrder(cro.instanceStart);
3743   sys::swapByteOrder(cro.instanceSize);
3744   sys::swapByteOrder(cro.ivarLayout);
3745   sys::swapByteOrder(cro.name);
3746   sys::swapByteOrder(cro.baseMethods);
3747   sys::swapByteOrder(cro.baseProtocols);
3748   sys::swapByteOrder(cro.ivars);
3749   sys::swapByteOrder(cro.weakIvarLayout);
3750   sys::swapByteOrder(cro.baseProperties);
3751 }
3752 
3753 inline void swapStruct(struct method_list64_t &ml) {
3754   sys::swapByteOrder(ml.entsize);
3755   sys::swapByteOrder(ml.count);
3756 }
3757 
3758 inline void swapStruct(struct method_list32_t &ml) {
3759   sys::swapByteOrder(ml.entsize);
3760   sys::swapByteOrder(ml.count);
3761 }
3762 
3763 inline void swapStruct(struct method64_t &m) {
3764   sys::swapByteOrder(m.name);
3765   sys::swapByteOrder(m.types);
3766   sys::swapByteOrder(m.imp);
3767 }
3768 
3769 inline void swapStruct(struct method32_t &m) {
3770   sys::swapByteOrder(m.name);
3771   sys::swapByteOrder(m.types);
3772   sys::swapByteOrder(m.imp);
3773 }
3774 
3775 inline void swapStruct(struct protocol_list64_t &pl) {
3776   sys::swapByteOrder(pl.count);
3777 }
3778 
3779 inline void swapStruct(struct protocol_list32_t &pl) {
3780   sys::swapByteOrder(pl.count);
3781 }
3782 
3783 inline void swapStruct(struct protocol64_t &p) {
3784   sys::swapByteOrder(p.isa);
3785   sys::swapByteOrder(p.name);
3786   sys::swapByteOrder(p.protocols);
3787   sys::swapByteOrder(p.instanceMethods);
3788   sys::swapByteOrder(p.classMethods);
3789   sys::swapByteOrder(p.optionalInstanceMethods);
3790   sys::swapByteOrder(p.optionalClassMethods);
3791   sys::swapByteOrder(p.instanceProperties);
3792 }
3793 
3794 inline void swapStruct(struct protocol32_t &p) {
3795   sys::swapByteOrder(p.isa);
3796   sys::swapByteOrder(p.name);
3797   sys::swapByteOrder(p.protocols);
3798   sys::swapByteOrder(p.instanceMethods);
3799   sys::swapByteOrder(p.classMethods);
3800   sys::swapByteOrder(p.optionalInstanceMethods);
3801   sys::swapByteOrder(p.optionalClassMethods);
3802   sys::swapByteOrder(p.instanceProperties);
3803 }
3804 
3805 inline void swapStruct(struct ivar_list64_t &il) {
3806   sys::swapByteOrder(il.entsize);
3807   sys::swapByteOrder(il.count);
3808 }
3809 
3810 inline void swapStruct(struct ivar_list32_t &il) {
3811   sys::swapByteOrder(il.entsize);
3812   sys::swapByteOrder(il.count);
3813 }
3814 
3815 inline void swapStruct(struct ivar64_t &i) {
3816   sys::swapByteOrder(i.offset);
3817   sys::swapByteOrder(i.name);
3818   sys::swapByteOrder(i.type);
3819   sys::swapByteOrder(i.alignment);
3820   sys::swapByteOrder(i.size);
3821 }
3822 
3823 inline void swapStruct(struct ivar32_t &i) {
3824   sys::swapByteOrder(i.offset);
3825   sys::swapByteOrder(i.name);
3826   sys::swapByteOrder(i.type);
3827   sys::swapByteOrder(i.alignment);
3828   sys::swapByteOrder(i.size);
3829 }
3830 
3831 inline void swapStruct(struct objc_property_list64 &pl) {
3832   sys::swapByteOrder(pl.entsize);
3833   sys::swapByteOrder(pl.count);
3834 }
3835 
3836 inline void swapStruct(struct objc_property_list32 &pl) {
3837   sys::swapByteOrder(pl.entsize);
3838   sys::swapByteOrder(pl.count);
3839 }
3840 
3841 inline void swapStruct(struct objc_property64 &op) {
3842   sys::swapByteOrder(op.name);
3843   sys::swapByteOrder(op.attributes);
3844 }
3845 
3846 inline void swapStruct(struct objc_property32 &op) {
3847   sys::swapByteOrder(op.name);
3848   sys::swapByteOrder(op.attributes);
3849 }
3850 
3851 inline void swapStruct(struct category64_t &c) {
3852   sys::swapByteOrder(c.name);
3853   sys::swapByteOrder(c.cls);
3854   sys::swapByteOrder(c.instanceMethods);
3855   sys::swapByteOrder(c.classMethods);
3856   sys::swapByteOrder(c.protocols);
3857   sys::swapByteOrder(c.instanceProperties);
3858 }
3859 
3860 inline void swapStruct(struct category32_t &c) {
3861   sys::swapByteOrder(c.name);
3862   sys::swapByteOrder(c.cls);
3863   sys::swapByteOrder(c.instanceMethods);
3864   sys::swapByteOrder(c.classMethods);
3865   sys::swapByteOrder(c.protocols);
3866   sys::swapByteOrder(c.instanceProperties);
3867 }
3868 
3869 inline void swapStruct(struct objc_image_info64 &o) {
3870   sys::swapByteOrder(o.version);
3871   sys::swapByteOrder(o.flags);
3872 }
3873 
3874 inline void swapStruct(struct objc_image_info32 &o) {
3875   sys::swapByteOrder(o.version);
3876   sys::swapByteOrder(o.flags);
3877 }
3878 
3879 inline void swapStruct(struct imageInfo_t &o) {
3880   sys::swapByteOrder(o.version);
3881   sys::swapByteOrder(o.flags);
3882 }
3883 
3884 inline void swapStruct(struct message_ref64 &mr) {
3885   sys::swapByteOrder(mr.imp);
3886   sys::swapByteOrder(mr.sel);
3887 }
3888 
3889 inline void swapStruct(struct message_ref32 &mr) {
3890   sys::swapByteOrder(mr.imp);
3891   sys::swapByteOrder(mr.sel);
3892 }
3893 
3894 inline void swapStruct(struct objc_module_t &module) {
3895   sys::swapByteOrder(module.version);
3896   sys::swapByteOrder(module.size);
3897   sys::swapByteOrder(module.name);
3898   sys::swapByteOrder(module.symtab);
3899 }
3900 
3901 inline void swapStruct(struct objc_symtab_t &symtab) {
3902   sys::swapByteOrder(symtab.sel_ref_cnt);
3903   sys::swapByteOrder(symtab.refs);
3904   sys::swapByteOrder(symtab.cls_def_cnt);
3905   sys::swapByteOrder(symtab.cat_def_cnt);
3906 }
3907 
3908 inline void swapStruct(struct objc_class_t &objc_class) {
3909   sys::swapByteOrder(objc_class.isa);
3910   sys::swapByteOrder(objc_class.super_class);
3911   sys::swapByteOrder(objc_class.name);
3912   sys::swapByteOrder(objc_class.version);
3913   sys::swapByteOrder(objc_class.info);
3914   sys::swapByteOrder(objc_class.instance_size);
3915   sys::swapByteOrder(objc_class.ivars);
3916   sys::swapByteOrder(objc_class.methodLists);
3917   sys::swapByteOrder(objc_class.cache);
3918   sys::swapByteOrder(objc_class.protocols);
3919 }
3920 
3921 inline void swapStruct(struct objc_category_t &objc_category) {
3922   sys::swapByteOrder(objc_category.category_name);
3923   sys::swapByteOrder(objc_category.class_name);
3924   sys::swapByteOrder(objc_category.instance_methods);
3925   sys::swapByteOrder(objc_category.class_methods);
3926   sys::swapByteOrder(objc_category.protocols);
3927 }
3928 
3929 inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3930   sys::swapByteOrder(objc_ivar_list.ivar_count);
3931 }
3932 
3933 inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3934   sys::swapByteOrder(objc_ivar.ivar_name);
3935   sys::swapByteOrder(objc_ivar.ivar_type);
3936   sys::swapByteOrder(objc_ivar.ivar_offset);
3937 }
3938 
3939 inline void swapStruct(struct objc_method_list_t &method_list) {
3940   sys::swapByteOrder(method_list.obsolete);
3941   sys::swapByteOrder(method_list.method_count);
3942 }
3943 
3944 inline void swapStruct(struct objc_method_t &method) {
3945   sys::swapByteOrder(method.method_name);
3946   sys::swapByteOrder(method.method_types);
3947   sys::swapByteOrder(method.method_imp);
3948 }
3949 
3950 inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3951   sys::swapByteOrder(protocol_list.next);
3952   sys::swapByteOrder(protocol_list.count);
3953 }
3954 
3955 inline void swapStruct(struct objc_protocol_t &protocol) {
3956   sys::swapByteOrder(protocol.isa);
3957   sys::swapByteOrder(protocol.protocol_name);
3958   sys::swapByteOrder(protocol.protocol_list);
3959   sys::swapByteOrder(protocol.instance_methods);
3960   sys::swapByteOrder(protocol.class_methods);
3961 }
3962 
3963 inline void swapStruct(struct objc_method_description_list_t &mdl) {
3964   sys::swapByteOrder(mdl.count);
3965 }
3966 
3967 inline void swapStruct(struct objc_method_description_t &md) {
3968   sys::swapByteOrder(md.name);
3969   sys::swapByteOrder(md.types);
3970 }
3971 
3972 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3973                                                  struct DisassembleInfo *info);
3974 
3975 // get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3976 // to an Objective-C class and returns the class name.  It is also passed the
3977 // address of the pointer, so when the pointer is zero as it can be in an .o
3978 // file, that is used to look for an external relocation entry with a symbol
3979 // name.
3980 static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3981                                               uint64_t ReferenceValue,
3982                                               struct DisassembleInfo *info) {
3983   const char *r;
3984   uint32_t offset, left;
3985   SectionRef S;
3986 
3987   // The pointer_value can be 0 in an object file and have a relocation
3988   // entry for the class symbol at the ReferenceValue (the address of the
3989   // pointer).
3990   if (pointer_value == 0) {
3991     r = get_pointer_64(ReferenceValue, offset, left, S, info);
3992     if (r == nullptr || left < sizeof(uint64_t))
3993       return nullptr;
3994     uint64_t n_value;
3995     const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3996     if (symbol_name == nullptr)
3997       return nullptr;
3998     const char *class_name = strrchr(symbol_name, '$');
3999     if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
4000       return class_name + 2;
4001     else
4002       return nullptr;
4003   }
4004 
4005   // The case were the pointer_value is non-zero and points to a class defined
4006   // in this Mach-O file.
4007   r = get_pointer_64(pointer_value, offset, left, S, info);
4008   if (r == nullptr || left < sizeof(struct class64_t))
4009     return nullptr;
4010   struct class64_t c;
4011   memcpy(&c, r, sizeof(struct class64_t));
4012   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4013     swapStruct(c);
4014   if (c.data == 0)
4015     return nullptr;
4016   r = get_pointer_64(c.data, offset, left, S, info);
4017   if (r == nullptr || left < sizeof(struct class_ro64_t))
4018     return nullptr;
4019   struct class_ro64_t cro;
4020   memcpy(&cro, r, sizeof(struct class_ro64_t));
4021   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4022     swapStruct(cro);
4023   if (cro.name == 0)
4024     return nullptr;
4025   const char *name = get_pointer_64(cro.name, offset, left, S, info);
4026   return name;
4027 }
4028 
4029 // get_objc2_64bit_cfstring_name is used for disassembly and is passed a
4030 // pointer to a cfstring and returns its name or nullptr.
4031 static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
4032                                                  struct DisassembleInfo *info) {
4033   const char *r, *name;
4034   uint32_t offset, left;
4035   SectionRef S;
4036   struct cfstring64_t cfs;
4037   uint64_t cfs_characters;
4038 
4039   r = get_pointer_64(ReferenceValue, offset, left, S, info);
4040   if (r == nullptr || left < sizeof(struct cfstring64_t))
4041     return nullptr;
4042   memcpy(&cfs, r, sizeof(struct cfstring64_t));
4043   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4044     swapStruct(cfs);
4045   if (cfs.characters == 0) {
4046     uint64_t n_value;
4047     const char *symbol_name = get_symbol_64(
4048         offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
4049     if (symbol_name == nullptr)
4050       return nullptr;
4051     cfs_characters = n_value;
4052   } else
4053     cfs_characters = cfs.characters;
4054   name = get_pointer_64(cfs_characters, offset, left, S, info);
4055 
4056   return name;
4057 }
4058 
4059 // get_objc2_64bit_selref() is used for disassembly and is passed a the address
4060 // of a pointer to an Objective-C selector reference when the pointer value is
4061 // zero as in a .o file and is likely to have a external relocation entry with
4062 // who's symbol's n_value is the real pointer to the selector name.  If that is
4063 // the case the real pointer to the selector name is returned else 0 is
4064 // returned
4065 static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
4066                                        struct DisassembleInfo *info) {
4067   uint32_t offset, left;
4068   SectionRef S;
4069 
4070   const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
4071   if (r == nullptr || left < sizeof(uint64_t))
4072     return 0;
4073   uint64_t n_value;
4074   const char *symbol_name = get_symbol_64(offset, S, info, n_value);
4075   if (symbol_name == nullptr)
4076     return 0;
4077   return n_value;
4078 }
4079 
4080 static const SectionRef get_section(MachOObjectFile *O, const char *segname,
4081                                     const char *sectname) {
4082   for (const SectionRef &Section : O->sections()) {
4083     StringRef SectName;
4084     Expected<StringRef> SecNameOrErr = Section.getName();
4085     if (SecNameOrErr)
4086       SectName = *SecNameOrErr;
4087     else
4088       consumeError(SecNameOrErr.takeError());
4089 
4090     DataRefImpl Ref = Section.getRawDataRefImpl();
4091     StringRef SegName = O->getSectionFinalSegmentName(Ref);
4092     if (SegName == segname && SectName == sectname)
4093       return Section;
4094   }
4095   return SectionRef();
4096 }
4097 
4098 static void
4099 walk_pointer_list_64(const char *listname, const SectionRef S,
4100                      MachOObjectFile *O, struct DisassembleInfo *info,
4101                      void (*func)(uint64_t, struct DisassembleInfo *info)) {
4102   if (S == SectionRef())
4103     return;
4104 
4105   StringRef SectName;
4106   Expected<StringRef> SecNameOrErr = S.getName();
4107   if (SecNameOrErr)
4108     SectName = *SecNameOrErr;
4109   else
4110     consumeError(SecNameOrErr.takeError());
4111 
4112   DataRefImpl Ref = S.getRawDataRefImpl();
4113   StringRef SegName = O->getSectionFinalSegmentName(Ref);
4114   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4115 
4116   StringRef BytesStr = unwrapOrError(S.getContents(), O->getFileName());
4117   const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
4118 
4119   for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
4120     uint32_t left = S.getSize() - i;
4121     uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
4122     uint64_t p = 0;
4123     memcpy(&p, Contents + i, size);
4124     if (i + sizeof(uint64_t) > S.getSize())
4125       outs() << listname << " list pointer extends past end of (" << SegName
4126              << "," << SectName << ") section\n";
4127     outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
4128 
4129     if (O->isLittleEndian() != sys::IsLittleEndianHost)
4130       sys::swapByteOrder(p);
4131 
4132     uint64_t n_value = 0;
4133     const char *name = get_symbol_64(i, S, info, n_value, p);
4134     if (name == nullptr)
4135       name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
4136 
4137     if (n_value != 0) {
4138       outs() << format("0x%" PRIx64, n_value);
4139       if (p != 0)
4140         outs() << " + " << format("0x%" PRIx64, p);
4141     } else
4142       outs() << format("0x%" PRIx64, p);
4143     if (name != nullptr)
4144       outs() << " " << name;
4145     outs() << "\n";
4146 
4147     p += n_value;
4148     if (func)
4149       func(p, info);
4150   }
4151 }
4152 
4153 static void
4154 walk_pointer_list_32(const char *listname, const SectionRef S,
4155                      MachOObjectFile *O, struct DisassembleInfo *info,
4156                      void (*func)(uint32_t, struct DisassembleInfo *info)) {
4157   if (S == SectionRef())
4158     return;
4159 
4160   StringRef SectName = unwrapOrError(S.getName(), O->getFileName());
4161   DataRefImpl Ref = S.getRawDataRefImpl();
4162   StringRef SegName = O->getSectionFinalSegmentName(Ref);
4163   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4164 
4165   StringRef BytesStr = unwrapOrError(S.getContents(), O->getFileName());
4166   const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
4167 
4168   for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
4169     uint32_t left = S.getSize() - i;
4170     uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
4171     uint32_t p = 0;
4172     memcpy(&p, Contents + i, size);
4173     if (i + sizeof(uint32_t) > S.getSize())
4174       outs() << listname << " list pointer extends past end of (" << SegName
4175              << "," << SectName << ") section\n";
4176     uint32_t Address = S.getAddress() + i;
4177     outs() << format("%08" PRIx32, Address) << " ";
4178 
4179     if (O->isLittleEndian() != sys::IsLittleEndianHost)
4180       sys::swapByteOrder(p);
4181     outs() << format("0x%" PRIx32, p);
4182 
4183     const char *name = get_symbol_32(i, S, info, p);
4184     if (name != nullptr)
4185       outs() << " " << name;
4186     outs() << "\n";
4187 
4188     if (func)
4189       func(p, info);
4190   }
4191 }
4192 
4193 static void print_layout_map(const char *layout_map, uint32_t left) {
4194   if (layout_map == nullptr)
4195     return;
4196   outs() << "                layout map: ";
4197   do {
4198     outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
4199     left--;
4200     layout_map++;
4201   } while (*layout_map != '\0' && left != 0);
4202   outs() << "\n";
4203 }
4204 
4205 static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
4206   uint32_t offset, left;
4207   SectionRef S;
4208   const char *layout_map;
4209 
4210   if (p == 0)
4211     return;
4212   layout_map = get_pointer_64(p, offset, left, S, info);
4213   print_layout_map(layout_map, left);
4214 }
4215 
4216 static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
4217   uint32_t offset, left;
4218   SectionRef S;
4219   const char *layout_map;
4220 
4221   if (p == 0)
4222     return;
4223   layout_map = get_pointer_32(p, offset, left, S, info);
4224   print_layout_map(layout_map, left);
4225 }
4226 
4227 static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
4228                                   const char *indent) {
4229   struct method_list64_t ml;
4230   struct method64_t m;
4231   const char *r;
4232   uint32_t offset, xoffset, left, i;
4233   SectionRef S, xS;
4234   const char *name, *sym_name;
4235   uint64_t n_value;
4236 
4237   r = get_pointer_64(p, offset, left, S, info);
4238   if (r == nullptr)
4239     return;
4240   memset(&ml, '\0', sizeof(struct method_list64_t));
4241   if (left < sizeof(struct method_list64_t)) {
4242     memcpy(&ml, r, left);
4243     outs() << "   (method_list_t entends past the end of the section)\n";
4244   } else
4245     memcpy(&ml, r, sizeof(struct method_list64_t));
4246   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4247     swapStruct(ml);
4248   outs() << indent << "\t\t   entsize " << ml.entsize << "\n";
4249   outs() << indent << "\t\t     count " << ml.count << "\n";
4250 
4251   p += sizeof(struct method_list64_t);
4252   offset += sizeof(struct method_list64_t);
4253   for (i = 0; i < ml.count; i++) {
4254     r = get_pointer_64(p, offset, left, S, info);
4255     if (r == nullptr)
4256       return;
4257     memset(&m, '\0', sizeof(struct method64_t));
4258     if (left < sizeof(struct method64_t)) {
4259       memcpy(&m, r, left);
4260       outs() << indent << "   (method_t extends past the end of the section)\n";
4261     } else
4262       memcpy(&m, r, sizeof(struct method64_t));
4263     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4264       swapStruct(m);
4265 
4266     outs() << indent << "\t\t      name ";
4267     sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
4268                              info, n_value, m.name);
4269     if (n_value != 0) {
4270       if (info->verbose && sym_name != nullptr)
4271         outs() << sym_name;
4272       else
4273         outs() << format("0x%" PRIx64, n_value);
4274       if (m.name != 0)
4275         outs() << " + " << format("0x%" PRIx64, m.name);
4276     } else
4277       outs() << format("0x%" PRIx64, m.name);
4278     name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
4279     if (name != nullptr)
4280       outs() << format(" %.*s", left, name);
4281     outs() << "\n";
4282 
4283     outs() << indent << "\t\t     types ";
4284     sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
4285                              info, n_value, m.types);
4286     if (n_value != 0) {
4287       if (info->verbose && sym_name != nullptr)
4288         outs() << sym_name;
4289       else
4290         outs() << format("0x%" PRIx64, n_value);
4291       if (m.types != 0)
4292         outs() << " + " << format("0x%" PRIx64, m.types);
4293     } else
4294       outs() << format("0x%" PRIx64, m.types);
4295     name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
4296     if (name != nullptr)
4297       outs() << format(" %.*s", left, name);
4298     outs() << "\n";
4299 
4300     outs() << indent << "\t\t       imp ";
4301     name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
4302                          n_value, m.imp);
4303     if (info->verbose && name == nullptr) {
4304       if (n_value != 0) {
4305         outs() << format("0x%" PRIx64, n_value) << " ";
4306         if (m.imp != 0)
4307           outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
4308       } else
4309         outs() << format("0x%" PRIx64, m.imp) << " ";
4310     }
4311     if (name != nullptr)
4312       outs() << name;
4313     outs() << "\n";
4314 
4315     p += sizeof(struct method64_t);
4316     offset += sizeof(struct method64_t);
4317   }
4318 }
4319 
4320 static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
4321                                   const char *indent) {
4322   struct method_list32_t ml;
4323   struct method32_t m;
4324   const char *r, *name;
4325   uint32_t offset, xoffset, left, i;
4326   SectionRef S, xS;
4327 
4328   r = get_pointer_32(p, offset, left, S, info);
4329   if (r == nullptr)
4330     return;
4331   memset(&ml, '\0', sizeof(struct method_list32_t));
4332   if (left < sizeof(struct method_list32_t)) {
4333     memcpy(&ml, r, left);
4334     outs() << "   (method_list_t entends past the end of the section)\n";
4335   } else
4336     memcpy(&ml, r, sizeof(struct method_list32_t));
4337   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4338     swapStruct(ml);
4339   outs() << indent << "\t\t   entsize " << ml.entsize << "\n";
4340   outs() << indent << "\t\t     count " << ml.count << "\n";
4341 
4342   p += sizeof(struct method_list32_t);
4343   offset += sizeof(struct method_list32_t);
4344   for (i = 0; i < ml.count; i++) {
4345     r = get_pointer_32(p, offset, left, S, info);
4346     if (r == nullptr)
4347       return;
4348     memset(&m, '\0', sizeof(struct method32_t));
4349     if (left < sizeof(struct method32_t)) {
4350       memcpy(&ml, r, left);
4351       outs() << indent << "   (method_t entends past the end of the section)\n";
4352     } else
4353       memcpy(&m, r, sizeof(struct method32_t));
4354     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4355       swapStruct(m);
4356 
4357     outs() << indent << "\t\t      name " << format("0x%" PRIx32, m.name);
4358     name = get_pointer_32(m.name, xoffset, left, xS, info);
4359     if (name != nullptr)
4360       outs() << format(" %.*s", left, name);
4361     outs() << "\n";
4362 
4363     outs() << indent << "\t\t     types " << format("0x%" PRIx32, m.types);
4364     name = get_pointer_32(m.types, xoffset, left, xS, info);
4365     if (name != nullptr)
4366       outs() << format(" %.*s", left, name);
4367     outs() << "\n";
4368 
4369     outs() << indent << "\t\t       imp " << format("0x%" PRIx32, m.imp);
4370     name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
4371                          m.imp);
4372     if (name != nullptr)
4373       outs() << " " << name;
4374     outs() << "\n";
4375 
4376     p += sizeof(struct method32_t);
4377     offset += sizeof(struct method32_t);
4378   }
4379 }
4380 
4381 static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
4382   uint32_t offset, left, xleft;
4383   SectionRef S;
4384   struct objc_method_list_t method_list;
4385   struct objc_method_t method;
4386   const char *r, *methods, *name, *SymbolName;
4387   int32_t i;
4388 
4389   r = get_pointer_32(p, offset, left, S, info, true);
4390   if (r == nullptr)
4391     return true;
4392 
4393   outs() << "\n";
4394   if (left > sizeof(struct objc_method_list_t)) {
4395     memcpy(&method_list, r, sizeof(struct objc_method_list_t));
4396   } else {
4397     outs() << "\t\t objc_method_list extends past end of the section\n";
4398     memset(&method_list, '\0', sizeof(struct objc_method_list_t));
4399     memcpy(&method_list, r, left);
4400   }
4401   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4402     swapStruct(method_list);
4403 
4404   outs() << "\t\t         obsolete "
4405          << format("0x%08" PRIx32, method_list.obsolete) << "\n";
4406   outs() << "\t\t     method_count " << method_list.method_count << "\n";
4407 
4408   methods = r + sizeof(struct objc_method_list_t);
4409   for (i = 0; i < method_list.method_count; i++) {
4410     if ((i + 1) * sizeof(struct objc_method_t) > left) {
4411       outs() << "\t\t remaining method's extend past the of the section\n";
4412       break;
4413     }
4414     memcpy(&method, methods + i * sizeof(struct objc_method_t),
4415            sizeof(struct objc_method_t));
4416     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4417       swapStruct(method);
4418 
4419     outs() << "\t\t      method_name "
4420            << format("0x%08" PRIx32, method.method_name);
4421     if (info->verbose) {
4422       name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
4423       if (name != nullptr)
4424         outs() << format(" %.*s", xleft, name);
4425       else
4426         outs() << " (not in an __OBJC section)";
4427     }
4428     outs() << "\n";
4429 
4430     outs() << "\t\t     method_types "
4431            << format("0x%08" PRIx32, method.method_types);
4432     if (info->verbose) {
4433       name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
4434       if (name != nullptr)
4435         outs() << format(" %.*s", xleft, name);
4436       else
4437         outs() << " (not in an __OBJC section)";
4438     }
4439     outs() << "\n";
4440 
4441     outs() << "\t\t       method_imp "
4442            << format("0x%08" PRIx32, method.method_imp) << " ";
4443     if (info->verbose) {
4444       SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
4445       if (SymbolName != nullptr)
4446         outs() << SymbolName;
4447     }
4448     outs() << "\n";
4449   }
4450   return false;
4451 }
4452 
4453 static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
4454   struct protocol_list64_t pl;
4455   uint64_t q, n_value;
4456   struct protocol64_t pc;
4457   const char *r;
4458   uint32_t offset, xoffset, left, i;
4459   SectionRef S, xS;
4460   const char *name, *sym_name;
4461 
4462   r = get_pointer_64(p, offset, left, S, info);
4463   if (r == nullptr)
4464     return;
4465   memset(&pl, '\0', sizeof(struct protocol_list64_t));
4466   if (left < sizeof(struct protocol_list64_t)) {
4467     memcpy(&pl, r, left);
4468     outs() << "   (protocol_list_t entends past the end of the section)\n";
4469   } else
4470     memcpy(&pl, r, sizeof(struct protocol_list64_t));
4471   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4472     swapStruct(pl);
4473   outs() << "                      count " << pl.count << "\n";
4474 
4475   p += sizeof(struct protocol_list64_t);
4476   offset += sizeof(struct protocol_list64_t);
4477   for (i = 0; i < pl.count; i++) {
4478     r = get_pointer_64(p, offset, left, S, info);
4479     if (r == nullptr)
4480       return;
4481     q = 0;
4482     if (left < sizeof(uint64_t)) {
4483       memcpy(&q, r, left);
4484       outs() << "   (protocol_t * entends past the end of the section)\n";
4485     } else
4486       memcpy(&q, r, sizeof(uint64_t));
4487     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4488       sys::swapByteOrder(q);
4489 
4490     outs() << "\t\t      list[" << i << "] ";
4491     sym_name = get_symbol_64(offset, S, info, n_value, q);
4492     if (n_value != 0) {
4493       if (info->verbose && sym_name != nullptr)
4494         outs() << sym_name;
4495       else
4496         outs() << format("0x%" PRIx64, n_value);
4497       if (q != 0)
4498         outs() << " + " << format("0x%" PRIx64, q);
4499     } else
4500       outs() << format("0x%" PRIx64, q);
4501     outs() << " (struct protocol_t *)\n";
4502 
4503     r = get_pointer_64(q + n_value, offset, left, S, info);
4504     if (r == nullptr)
4505       return;
4506     memset(&pc, '\0', sizeof(struct protocol64_t));
4507     if (left < sizeof(struct protocol64_t)) {
4508       memcpy(&pc, r, left);
4509       outs() << "   (protocol_t entends past the end of the section)\n";
4510     } else
4511       memcpy(&pc, r, sizeof(struct protocol64_t));
4512     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4513       swapStruct(pc);
4514 
4515     outs() << "\t\t\t      isa " << format("0x%" PRIx64, pc.isa) << "\n";
4516 
4517     outs() << "\t\t\t     name ";
4518     sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
4519                              info, n_value, pc.name);
4520     if (n_value != 0) {
4521       if (info->verbose && sym_name != nullptr)
4522         outs() << sym_name;
4523       else
4524         outs() << format("0x%" PRIx64, n_value);
4525       if (pc.name != 0)
4526         outs() << " + " << format("0x%" PRIx64, pc.name);
4527     } else
4528       outs() << format("0x%" PRIx64, pc.name);
4529     name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
4530     if (name != nullptr)
4531       outs() << format(" %.*s", left, name);
4532     outs() << "\n";
4533 
4534     outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
4535 
4536     outs() << "\t\t  instanceMethods ";
4537     sym_name =
4538         get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
4539                       S, info, n_value, pc.instanceMethods);
4540     if (n_value != 0) {
4541       if (info->verbose && sym_name != nullptr)
4542         outs() << sym_name;
4543       else
4544         outs() << format("0x%" PRIx64, n_value);
4545       if (pc.instanceMethods != 0)
4546         outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
4547     } else
4548       outs() << format("0x%" PRIx64, pc.instanceMethods);
4549     outs() << " (struct method_list_t *)\n";
4550     if (pc.instanceMethods + n_value != 0)
4551       print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
4552 
4553     outs() << "\t\t     classMethods ";
4554     sym_name =
4555         get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
4556                       info, n_value, pc.classMethods);
4557     if (n_value != 0) {
4558       if (info->verbose && sym_name != nullptr)
4559         outs() << sym_name;
4560       else
4561         outs() << format("0x%" PRIx64, n_value);
4562       if (pc.classMethods != 0)
4563         outs() << " + " << format("0x%" PRIx64, pc.classMethods);
4564     } else
4565       outs() << format("0x%" PRIx64, pc.classMethods);
4566     outs() << " (struct method_list_t *)\n";
4567     if (pc.classMethods + n_value != 0)
4568       print_method_list64_t(pc.classMethods + n_value, info, "\t");
4569 
4570     outs() << "\t  optionalInstanceMethods "
4571            << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
4572     outs() << "\t     optionalClassMethods "
4573            << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
4574     outs() << "\t       instanceProperties "
4575            << format("0x%" PRIx64, pc.instanceProperties) << "\n";
4576 
4577     p += sizeof(uint64_t);
4578     offset += sizeof(uint64_t);
4579   }
4580 }
4581 
4582 static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
4583   struct protocol_list32_t pl;
4584   uint32_t q;
4585   struct protocol32_t pc;
4586   const char *r;
4587   uint32_t offset, xoffset, left, i;
4588   SectionRef S, xS;
4589   const char *name;
4590 
4591   r = get_pointer_32(p, offset, left, S, info);
4592   if (r == nullptr)
4593     return;
4594   memset(&pl, '\0', sizeof(struct protocol_list32_t));
4595   if (left < sizeof(struct protocol_list32_t)) {
4596     memcpy(&pl, r, left);
4597     outs() << "   (protocol_list_t entends past the end of the section)\n";
4598   } else
4599     memcpy(&pl, r, sizeof(struct protocol_list32_t));
4600   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4601     swapStruct(pl);
4602   outs() << "                      count " << pl.count << "\n";
4603 
4604   p += sizeof(struct protocol_list32_t);
4605   offset += sizeof(struct protocol_list32_t);
4606   for (i = 0; i < pl.count; i++) {
4607     r = get_pointer_32(p, offset, left, S, info);
4608     if (r == nullptr)
4609       return;
4610     q = 0;
4611     if (left < sizeof(uint32_t)) {
4612       memcpy(&q, r, left);
4613       outs() << "   (protocol_t * entends past the end of the section)\n";
4614     } else
4615       memcpy(&q, r, sizeof(uint32_t));
4616     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4617       sys::swapByteOrder(q);
4618     outs() << "\t\t      list[" << i << "] " << format("0x%" PRIx32, q)
4619            << " (struct protocol_t *)\n";
4620     r = get_pointer_32(q, offset, left, S, info);
4621     if (r == nullptr)
4622       return;
4623     memset(&pc, '\0', sizeof(struct protocol32_t));
4624     if (left < sizeof(struct protocol32_t)) {
4625       memcpy(&pc, r, left);
4626       outs() << "   (protocol_t entends past the end of the section)\n";
4627     } else
4628       memcpy(&pc, r, sizeof(struct protocol32_t));
4629     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4630       swapStruct(pc);
4631     outs() << "\t\t\t      isa " << format("0x%" PRIx32, pc.isa) << "\n";
4632     outs() << "\t\t\t     name " << format("0x%" PRIx32, pc.name);
4633     name = get_pointer_32(pc.name, xoffset, left, xS, info);
4634     if (name != nullptr)
4635       outs() << format(" %.*s", left, name);
4636     outs() << "\n";
4637     outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
4638     outs() << "\t\t  instanceMethods "
4639            << format("0x%" PRIx32, pc.instanceMethods)
4640            << " (struct method_list_t *)\n";
4641     if (pc.instanceMethods != 0)
4642       print_method_list32_t(pc.instanceMethods, info, "\t");
4643     outs() << "\t\t     classMethods " << format("0x%" PRIx32, pc.classMethods)
4644            << " (struct method_list_t *)\n";
4645     if (pc.classMethods != 0)
4646       print_method_list32_t(pc.classMethods, info, "\t");
4647     outs() << "\t  optionalInstanceMethods "
4648            << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
4649     outs() << "\t     optionalClassMethods "
4650            << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
4651     outs() << "\t       instanceProperties "
4652            << format("0x%" PRIx32, pc.instanceProperties) << "\n";
4653     p += sizeof(uint32_t);
4654     offset += sizeof(uint32_t);
4655   }
4656 }
4657 
4658 static void print_indent(uint32_t indent) {
4659   for (uint32_t i = 0; i < indent;) {
4660     if (indent - i >= 8) {
4661       outs() << "\t";
4662       i += 8;
4663     } else {
4664       for (uint32_t j = i; j < indent; j++)
4665         outs() << " ";
4666       return;
4667     }
4668   }
4669 }
4670 
4671 static bool print_method_description_list(uint32_t p, uint32_t indent,
4672                                           struct DisassembleInfo *info) {
4673   uint32_t offset, left, xleft;
4674   SectionRef S;
4675   struct objc_method_description_list_t mdl;
4676   struct objc_method_description_t md;
4677   const char *r, *list, *name;
4678   int32_t i;
4679 
4680   r = get_pointer_32(p, offset, left, S, info, true);
4681   if (r == nullptr)
4682     return true;
4683 
4684   outs() << "\n";
4685   if (left > sizeof(struct objc_method_description_list_t)) {
4686     memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
4687   } else {
4688     print_indent(indent);
4689     outs() << " objc_method_description_list extends past end of the section\n";
4690     memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
4691     memcpy(&mdl, r, left);
4692   }
4693   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4694     swapStruct(mdl);
4695 
4696   print_indent(indent);
4697   outs() << "        count " << mdl.count << "\n";
4698 
4699   list = r + sizeof(struct objc_method_description_list_t);
4700   for (i = 0; i < mdl.count; i++) {
4701     if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
4702       print_indent(indent);
4703       outs() << " remaining list entries extend past the of the section\n";
4704       break;
4705     }
4706     print_indent(indent);
4707     outs() << "        list[" << i << "]\n";
4708     memcpy(&md, list + i * sizeof(struct objc_method_description_t),
4709            sizeof(struct objc_method_description_t));
4710     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4711       swapStruct(md);
4712 
4713     print_indent(indent);
4714     outs() << "             name " << format("0x%08" PRIx32, md.name);
4715     if (info->verbose) {
4716       name = get_pointer_32(md.name, offset, xleft, S, info, true);
4717       if (name != nullptr)
4718         outs() << format(" %.*s", xleft, name);
4719       else
4720         outs() << " (not in an __OBJC section)";
4721     }
4722     outs() << "\n";
4723 
4724     print_indent(indent);
4725     outs() << "            types " << format("0x%08" PRIx32, md.types);
4726     if (info->verbose) {
4727       name = get_pointer_32(md.types, offset, xleft, S, info, true);
4728       if (name != nullptr)
4729         outs() << format(" %.*s", xleft, name);
4730       else
4731         outs() << " (not in an __OBJC section)";
4732     }
4733     outs() << "\n";
4734   }
4735   return false;
4736 }
4737 
4738 static bool print_protocol_list(uint32_t p, uint32_t indent,
4739                                 struct DisassembleInfo *info);
4740 
4741 static bool print_protocol(uint32_t p, uint32_t indent,
4742                            struct DisassembleInfo *info) {
4743   uint32_t offset, left;
4744   SectionRef S;
4745   struct objc_protocol_t protocol;
4746   const char *r, *name;
4747 
4748   r = get_pointer_32(p, offset, left, S, info, true);
4749   if (r == nullptr)
4750     return true;
4751 
4752   outs() << "\n";
4753   if (left >= sizeof(struct objc_protocol_t)) {
4754     memcpy(&protocol, r, sizeof(struct objc_protocol_t));
4755   } else {
4756     print_indent(indent);
4757     outs() << "            Protocol extends past end of the section\n";
4758     memset(&protocol, '\0', sizeof(struct objc_protocol_t));
4759     memcpy(&protocol, r, left);
4760   }
4761   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4762     swapStruct(protocol);
4763 
4764   print_indent(indent);
4765   outs() << "              isa " << format("0x%08" PRIx32, protocol.isa)
4766          << "\n";
4767 
4768   print_indent(indent);
4769   outs() << "    protocol_name "
4770          << format("0x%08" PRIx32, protocol.protocol_name);
4771   if (info->verbose) {
4772     name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
4773     if (name != nullptr)
4774       outs() << format(" %.*s", left, name);
4775     else
4776       outs() << " (not in an __OBJC section)";
4777   }
4778   outs() << "\n";
4779 
4780   print_indent(indent);
4781   outs() << "    protocol_list "
4782          << format("0x%08" PRIx32, protocol.protocol_list);
4783   if (print_protocol_list(protocol.protocol_list, indent + 4, info))
4784     outs() << " (not in an __OBJC section)\n";
4785 
4786   print_indent(indent);
4787   outs() << " instance_methods "
4788          << format("0x%08" PRIx32, protocol.instance_methods);
4789   if (print_method_description_list(protocol.instance_methods, indent, info))
4790     outs() << " (not in an __OBJC section)\n";
4791 
4792   print_indent(indent);
4793   outs() << "    class_methods "
4794          << format("0x%08" PRIx32, protocol.class_methods);
4795   if (print_method_description_list(protocol.class_methods, indent, info))
4796     outs() << " (not in an __OBJC section)\n";
4797 
4798   return false;
4799 }
4800 
4801 static bool print_protocol_list(uint32_t p, uint32_t indent,
4802                                 struct DisassembleInfo *info) {
4803   uint32_t offset, left, l;
4804   SectionRef S;
4805   struct objc_protocol_list_t protocol_list;
4806   const char *r, *list;
4807   int32_t i;
4808 
4809   r = get_pointer_32(p, offset, left, S, info, true);
4810   if (r == nullptr)
4811     return true;
4812 
4813   outs() << "\n";
4814   if (left > sizeof(struct objc_protocol_list_t)) {
4815     memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
4816   } else {
4817     outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
4818     memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
4819     memcpy(&protocol_list, r, left);
4820   }
4821   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4822     swapStruct(protocol_list);
4823 
4824   print_indent(indent);
4825   outs() << "         next " << format("0x%08" PRIx32, protocol_list.next)
4826          << "\n";
4827   print_indent(indent);
4828   outs() << "        count " << protocol_list.count << "\n";
4829 
4830   list = r + sizeof(struct objc_protocol_list_t);
4831   for (i = 0; i < protocol_list.count; i++) {
4832     if ((i + 1) * sizeof(uint32_t) > left) {
4833       outs() << "\t\t remaining list entries extend past the of the section\n";
4834       break;
4835     }
4836     memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
4837     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4838       sys::swapByteOrder(l);
4839 
4840     print_indent(indent);
4841     outs() << "      list[" << i << "] " << format("0x%08" PRIx32, l);
4842     if (print_protocol(l, indent, info))
4843       outs() << "(not in an __OBJC section)\n";
4844   }
4845   return false;
4846 }
4847 
4848 static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
4849   struct ivar_list64_t il;
4850   struct ivar64_t i;
4851   const char *r;
4852   uint32_t offset, xoffset, left, j;
4853   SectionRef S, xS;
4854   const char *name, *sym_name, *ivar_offset_p;
4855   uint64_t ivar_offset, n_value;
4856 
4857   r = get_pointer_64(p, offset, left, S, info);
4858   if (r == nullptr)
4859     return;
4860   memset(&il, '\0', sizeof(struct ivar_list64_t));
4861   if (left < sizeof(struct ivar_list64_t)) {
4862     memcpy(&il, r, left);
4863     outs() << "   (ivar_list_t entends past the end of the section)\n";
4864   } else
4865     memcpy(&il, r, sizeof(struct ivar_list64_t));
4866   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4867     swapStruct(il);
4868   outs() << "                    entsize " << il.entsize << "\n";
4869   outs() << "                      count " << il.count << "\n";
4870 
4871   p += sizeof(struct ivar_list64_t);
4872   offset += sizeof(struct ivar_list64_t);
4873   for (j = 0; j < il.count; j++) {
4874     r = get_pointer_64(p, offset, left, S, info);
4875     if (r == nullptr)
4876       return;
4877     memset(&i, '\0', sizeof(struct ivar64_t));
4878     if (left < sizeof(struct ivar64_t)) {
4879       memcpy(&i, r, left);
4880       outs() << "   (ivar_t entends past the end of the section)\n";
4881     } else
4882       memcpy(&i, r, sizeof(struct ivar64_t));
4883     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4884       swapStruct(i);
4885 
4886     outs() << "\t\t\t   offset ";
4887     sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
4888                              info, n_value, i.offset);
4889     if (n_value != 0) {
4890       if (info->verbose && sym_name != nullptr)
4891         outs() << sym_name;
4892       else
4893         outs() << format("0x%" PRIx64, n_value);
4894       if (i.offset != 0)
4895         outs() << " + " << format("0x%" PRIx64, i.offset);
4896     } else
4897       outs() << format("0x%" PRIx64, i.offset);
4898     ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
4899     if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4900       memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4901       if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4902         sys::swapByteOrder(ivar_offset);
4903       outs() << " " << ivar_offset << "\n";
4904     } else
4905       outs() << "\n";
4906 
4907     outs() << "\t\t\t     name ";
4908     sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
4909                              n_value, i.name);
4910     if (n_value != 0) {
4911       if (info->verbose && sym_name != nullptr)
4912         outs() << sym_name;
4913       else
4914         outs() << format("0x%" PRIx64, n_value);
4915       if (i.name != 0)
4916         outs() << " + " << format("0x%" PRIx64, i.name);
4917     } else
4918       outs() << format("0x%" PRIx64, i.name);
4919     name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
4920     if (name != nullptr)
4921       outs() << format(" %.*s", left, name);
4922     outs() << "\n";
4923 
4924     outs() << "\t\t\t     type ";
4925     sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
4926                              n_value, i.name);
4927     name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
4928     if (n_value != 0) {
4929       if (info->verbose && sym_name != nullptr)
4930         outs() << sym_name;
4931       else
4932         outs() << format("0x%" PRIx64, n_value);
4933       if (i.type != 0)
4934         outs() << " + " << format("0x%" PRIx64, i.type);
4935     } else
4936       outs() << format("0x%" PRIx64, i.type);
4937     if (name != nullptr)
4938       outs() << format(" %.*s", left, name);
4939     outs() << "\n";
4940 
4941     outs() << "\t\t\talignment " << i.alignment << "\n";
4942     outs() << "\t\t\t     size " << i.size << "\n";
4943 
4944     p += sizeof(struct ivar64_t);
4945     offset += sizeof(struct ivar64_t);
4946   }
4947 }
4948 
4949 static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4950   struct ivar_list32_t il;
4951   struct ivar32_t i;
4952   const char *r;
4953   uint32_t offset, xoffset, left, j;
4954   SectionRef S, xS;
4955   const char *name, *ivar_offset_p;
4956   uint32_t ivar_offset;
4957 
4958   r = get_pointer_32(p, offset, left, S, info);
4959   if (r == nullptr)
4960     return;
4961   memset(&il, '\0', sizeof(struct ivar_list32_t));
4962   if (left < sizeof(struct ivar_list32_t)) {
4963     memcpy(&il, r, left);
4964     outs() << "   (ivar_list_t entends past the end of the section)\n";
4965   } else
4966     memcpy(&il, r, sizeof(struct ivar_list32_t));
4967   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4968     swapStruct(il);
4969   outs() << "                    entsize " << il.entsize << "\n";
4970   outs() << "                      count " << il.count << "\n";
4971 
4972   p += sizeof(struct ivar_list32_t);
4973   offset += sizeof(struct ivar_list32_t);
4974   for (j = 0; j < il.count; j++) {
4975     r = get_pointer_32(p, offset, left, S, info);
4976     if (r == nullptr)
4977       return;
4978     memset(&i, '\0', sizeof(struct ivar32_t));
4979     if (left < sizeof(struct ivar32_t)) {
4980       memcpy(&i, r, left);
4981       outs() << "   (ivar_t entends past the end of the section)\n";
4982     } else
4983       memcpy(&i, r, sizeof(struct ivar32_t));
4984     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4985       swapStruct(i);
4986 
4987     outs() << "\t\t\t   offset " << format("0x%" PRIx32, i.offset);
4988     ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4989     if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4990       memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4991       if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4992         sys::swapByteOrder(ivar_offset);
4993       outs() << " " << ivar_offset << "\n";
4994     } else
4995       outs() << "\n";
4996 
4997     outs() << "\t\t\t     name " << format("0x%" PRIx32, i.name);
4998     name = get_pointer_32(i.name, xoffset, left, xS, info);
4999     if (name != nullptr)
5000       outs() << format(" %.*s", left, name);
5001     outs() << "\n";
5002 
5003     outs() << "\t\t\t     type " << format("0x%" PRIx32, i.type);
5004     name = get_pointer_32(i.type, xoffset, left, xS, info);
5005     if (name != nullptr)
5006       outs() << format(" %.*s", left, name);
5007     outs() << "\n";
5008 
5009     outs() << "\t\t\talignment " << i.alignment << "\n";
5010     outs() << "\t\t\t     size " << i.size << "\n";
5011 
5012     p += sizeof(struct ivar32_t);
5013     offset += sizeof(struct ivar32_t);
5014   }
5015 }
5016 
5017 static void print_objc_property_list64(uint64_t p,
5018                                        struct DisassembleInfo *info) {
5019   struct objc_property_list64 opl;
5020   struct objc_property64 op;
5021   const char *r;
5022   uint32_t offset, xoffset, left, j;
5023   SectionRef S, xS;
5024   const char *name, *sym_name;
5025   uint64_t n_value;
5026 
5027   r = get_pointer_64(p, offset, left, S, info);
5028   if (r == nullptr)
5029     return;
5030   memset(&opl, '\0', sizeof(struct objc_property_list64));
5031   if (left < sizeof(struct objc_property_list64)) {
5032     memcpy(&opl, r, left);
5033     outs() << "   (objc_property_list entends past the end of the section)\n";
5034   } else
5035     memcpy(&opl, r, sizeof(struct objc_property_list64));
5036   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5037     swapStruct(opl);
5038   outs() << "                    entsize " << opl.entsize << "\n";
5039   outs() << "                      count " << opl.count << "\n";
5040 
5041   p += sizeof(struct objc_property_list64);
5042   offset += sizeof(struct objc_property_list64);
5043   for (j = 0; j < opl.count; j++) {
5044     r = get_pointer_64(p, offset, left, S, info);
5045     if (r == nullptr)
5046       return;
5047     memset(&op, '\0', sizeof(struct objc_property64));
5048     if (left < sizeof(struct objc_property64)) {
5049       memcpy(&op, r, left);
5050       outs() << "   (objc_property entends past the end of the section)\n";
5051     } else
5052       memcpy(&op, r, sizeof(struct objc_property64));
5053     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5054       swapStruct(op);
5055 
5056     outs() << "\t\t\t     name ";
5057     sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
5058                              info, n_value, op.name);
5059     if (n_value != 0) {
5060       if (info->verbose && sym_name != nullptr)
5061         outs() << sym_name;
5062       else
5063         outs() << format("0x%" PRIx64, n_value);
5064       if (op.name != 0)
5065         outs() << " + " << format("0x%" PRIx64, op.name);
5066     } else
5067       outs() << format("0x%" PRIx64, op.name);
5068     name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
5069     if (name != nullptr)
5070       outs() << format(" %.*s", left, name);
5071     outs() << "\n";
5072 
5073     outs() << "\t\t\tattributes ";
5074     sym_name =
5075         get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
5076                       info, n_value, op.attributes);
5077     if (n_value != 0) {
5078       if (info->verbose && sym_name != nullptr)
5079         outs() << sym_name;
5080       else
5081         outs() << format("0x%" PRIx64, n_value);
5082       if (op.attributes != 0)
5083         outs() << " + " << format("0x%" PRIx64, op.attributes);
5084     } else
5085       outs() << format("0x%" PRIx64, op.attributes);
5086     name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
5087     if (name != nullptr)
5088       outs() << format(" %.*s", left, name);
5089     outs() << "\n";
5090 
5091     p += sizeof(struct objc_property64);
5092     offset += sizeof(struct objc_property64);
5093   }
5094 }
5095 
5096 static void print_objc_property_list32(uint32_t p,
5097                                        struct DisassembleInfo *info) {
5098   struct objc_property_list32 opl;
5099   struct objc_property32 op;
5100   const char *r;
5101   uint32_t offset, xoffset, left, j;
5102   SectionRef S, xS;
5103   const char *name;
5104 
5105   r = get_pointer_32(p, offset, left, S, info);
5106   if (r == nullptr)
5107     return;
5108   memset(&opl, '\0', sizeof(struct objc_property_list32));
5109   if (left < sizeof(struct objc_property_list32)) {
5110     memcpy(&opl, r, left);
5111     outs() << "   (objc_property_list entends past the end of the section)\n";
5112   } else
5113     memcpy(&opl, r, sizeof(struct objc_property_list32));
5114   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5115     swapStruct(opl);
5116   outs() << "                    entsize " << opl.entsize << "\n";
5117   outs() << "                      count " << opl.count << "\n";
5118 
5119   p += sizeof(struct objc_property_list32);
5120   offset += sizeof(struct objc_property_list32);
5121   for (j = 0; j < opl.count; j++) {
5122     r = get_pointer_32(p, offset, left, S, info);
5123     if (r == nullptr)
5124       return;
5125     memset(&op, '\0', sizeof(struct objc_property32));
5126     if (left < sizeof(struct objc_property32)) {
5127       memcpy(&op, r, left);
5128       outs() << "   (objc_property entends past the end of the section)\n";
5129     } else
5130       memcpy(&op, r, sizeof(struct objc_property32));
5131     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5132       swapStruct(op);
5133 
5134     outs() << "\t\t\t     name " << format("0x%" PRIx32, op.name);
5135     name = get_pointer_32(op.name, xoffset, left, xS, info);
5136     if (name != nullptr)
5137       outs() << format(" %.*s", left, name);
5138     outs() << "\n";
5139 
5140     outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
5141     name = get_pointer_32(op.attributes, xoffset, left, xS, info);
5142     if (name != nullptr)
5143       outs() << format(" %.*s", left, name);
5144     outs() << "\n";
5145 
5146     p += sizeof(struct objc_property32);
5147     offset += sizeof(struct objc_property32);
5148   }
5149 }
5150 
5151 static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
5152                                bool &is_meta_class) {
5153   struct class_ro64_t cro;
5154   const char *r;
5155   uint32_t offset, xoffset, left;
5156   SectionRef S, xS;
5157   const char *name, *sym_name;
5158   uint64_t n_value;
5159 
5160   r = get_pointer_64(p, offset, left, S, info);
5161   if (r == nullptr || left < sizeof(struct class_ro64_t))
5162     return false;
5163   memcpy(&cro, r, sizeof(struct class_ro64_t));
5164   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5165     swapStruct(cro);
5166   outs() << "                    flags " << format("0x%" PRIx32, cro.flags);
5167   if (cro.flags & RO_META)
5168     outs() << " RO_META";
5169   if (cro.flags & RO_ROOT)
5170     outs() << " RO_ROOT";
5171   if (cro.flags & RO_HAS_CXX_STRUCTORS)
5172     outs() << " RO_HAS_CXX_STRUCTORS";
5173   outs() << "\n";
5174   outs() << "            instanceStart " << cro.instanceStart << "\n";
5175   outs() << "             instanceSize " << cro.instanceSize << "\n";
5176   outs() << "                 reserved " << format("0x%" PRIx32, cro.reserved)
5177          << "\n";
5178   outs() << "               ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
5179          << "\n";
5180   print_layout_map64(cro.ivarLayout, info);
5181 
5182   outs() << "                     name ";
5183   sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
5184                            info, n_value, cro.name);
5185   if (n_value != 0) {
5186     if (info->verbose && sym_name != nullptr)
5187       outs() << sym_name;
5188     else
5189       outs() << format("0x%" PRIx64, n_value);
5190     if (cro.name != 0)
5191       outs() << " + " << format("0x%" PRIx64, cro.name);
5192   } else
5193     outs() << format("0x%" PRIx64, cro.name);
5194   name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
5195   if (name != nullptr)
5196     outs() << format(" %.*s", left, name);
5197   outs() << "\n";
5198 
5199   outs() << "              baseMethods ";
5200   sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
5201                            S, info, n_value, cro.baseMethods);
5202   if (n_value != 0) {
5203     if (info->verbose && sym_name != nullptr)
5204       outs() << sym_name;
5205     else
5206       outs() << format("0x%" PRIx64, n_value);
5207     if (cro.baseMethods != 0)
5208       outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
5209   } else
5210     outs() << format("0x%" PRIx64, cro.baseMethods);
5211   outs() << " (struct method_list_t *)\n";
5212   if (cro.baseMethods + n_value != 0)
5213     print_method_list64_t(cro.baseMethods + n_value, info, "");
5214 
5215   outs() << "            baseProtocols ";
5216   sym_name =
5217       get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
5218                     info, n_value, cro.baseProtocols);
5219   if (n_value != 0) {
5220     if (info->verbose && sym_name != nullptr)
5221       outs() << sym_name;
5222     else
5223       outs() << format("0x%" PRIx64, n_value);
5224     if (cro.baseProtocols != 0)
5225       outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
5226   } else
5227     outs() << format("0x%" PRIx64, cro.baseProtocols);
5228   outs() << "\n";
5229   if (cro.baseProtocols + n_value != 0)
5230     print_protocol_list64_t(cro.baseProtocols + n_value, info);
5231 
5232   outs() << "                    ivars ";
5233   sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
5234                            info, n_value, cro.ivars);
5235   if (n_value != 0) {
5236     if (info->verbose && sym_name != nullptr)
5237       outs() << sym_name;
5238     else
5239       outs() << format("0x%" PRIx64, n_value);
5240     if (cro.ivars != 0)
5241       outs() << " + " << format("0x%" PRIx64, cro.ivars);
5242   } else
5243     outs() << format("0x%" PRIx64, cro.ivars);
5244   outs() << "\n";
5245   if (cro.ivars + n_value != 0)
5246     print_ivar_list64_t(cro.ivars + n_value, info);
5247 
5248   outs() << "           weakIvarLayout ";
5249   sym_name =
5250       get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
5251                     info, n_value, cro.weakIvarLayout);
5252   if (n_value != 0) {
5253     if (info->verbose && sym_name != nullptr)
5254       outs() << sym_name;
5255     else
5256       outs() << format("0x%" PRIx64, n_value);
5257     if (cro.weakIvarLayout != 0)
5258       outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
5259   } else
5260     outs() << format("0x%" PRIx64, cro.weakIvarLayout);
5261   outs() << "\n";
5262   print_layout_map64(cro.weakIvarLayout + n_value, info);
5263 
5264   outs() << "           baseProperties ";
5265   sym_name =
5266       get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
5267                     info, n_value, cro.baseProperties);
5268   if (n_value != 0) {
5269     if (info->verbose && sym_name != nullptr)
5270       outs() << sym_name;
5271     else
5272       outs() << format("0x%" PRIx64, n_value);
5273     if (cro.baseProperties != 0)
5274       outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
5275   } else
5276     outs() << format("0x%" PRIx64, cro.baseProperties);
5277   outs() << "\n";
5278   if (cro.baseProperties + n_value != 0)
5279     print_objc_property_list64(cro.baseProperties + n_value, info);
5280 
5281   is_meta_class = (cro.flags & RO_META) != 0;
5282   return true;
5283 }
5284 
5285 static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
5286                                bool &is_meta_class) {
5287   struct class_ro32_t cro;
5288   const char *r;
5289   uint32_t offset, xoffset, left;
5290   SectionRef S, xS;
5291   const char *name;
5292 
5293   r = get_pointer_32(p, offset, left, S, info);
5294   if (r == nullptr)
5295     return false;
5296   memset(&cro, '\0', sizeof(struct class_ro32_t));
5297   if (left < sizeof(struct class_ro32_t)) {
5298     memcpy(&cro, r, left);
5299     outs() << "   (class_ro_t entends past the end of the section)\n";
5300   } else
5301     memcpy(&cro, r, sizeof(struct class_ro32_t));
5302   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5303     swapStruct(cro);
5304   outs() << "                    flags " << format("0x%" PRIx32, cro.flags);
5305   if (cro.flags & RO_META)
5306     outs() << " RO_META";
5307   if (cro.flags & RO_ROOT)
5308     outs() << " RO_ROOT";
5309   if (cro.flags & RO_HAS_CXX_STRUCTORS)
5310     outs() << " RO_HAS_CXX_STRUCTORS";
5311   outs() << "\n";
5312   outs() << "            instanceStart " << cro.instanceStart << "\n";
5313   outs() << "             instanceSize " << cro.instanceSize << "\n";
5314   outs() << "               ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
5315          << "\n";
5316   print_layout_map32(cro.ivarLayout, info);
5317 
5318   outs() << "                     name " << format("0x%" PRIx32, cro.name);
5319   name = get_pointer_32(cro.name, xoffset, left, xS, info);
5320   if (name != nullptr)
5321     outs() << format(" %.*s", left, name);
5322   outs() << "\n";
5323 
5324   outs() << "              baseMethods "
5325          << format("0x%" PRIx32, cro.baseMethods)
5326          << " (struct method_list_t *)\n";
5327   if (cro.baseMethods != 0)
5328     print_method_list32_t(cro.baseMethods, info, "");
5329 
5330   outs() << "            baseProtocols "
5331          << format("0x%" PRIx32, cro.baseProtocols) << "\n";
5332   if (cro.baseProtocols != 0)
5333     print_protocol_list32_t(cro.baseProtocols, info);
5334   outs() << "                    ivars " << format("0x%" PRIx32, cro.ivars)
5335          << "\n";
5336   if (cro.ivars != 0)
5337     print_ivar_list32_t(cro.ivars, info);
5338   outs() << "           weakIvarLayout "
5339          << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
5340   print_layout_map32(cro.weakIvarLayout, info);
5341   outs() << "           baseProperties "
5342          << format("0x%" PRIx32, cro.baseProperties) << "\n";
5343   if (cro.baseProperties != 0)
5344     print_objc_property_list32(cro.baseProperties, info);
5345   is_meta_class = (cro.flags & RO_META) != 0;
5346   return true;
5347 }
5348 
5349 static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
5350   struct class64_t c;
5351   const char *r;
5352   uint32_t offset, left;
5353   SectionRef S;
5354   const char *name;
5355   uint64_t isa_n_value, n_value;
5356 
5357   r = get_pointer_64(p, offset, left, S, info);
5358   if (r == nullptr || left < sizeof(struct class64_t))
5359     return;
5360   memcpy(&c, r, sizeof(struct class64_t));
5361   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5362     swapStruct(c);
5363 
5364   outs() << "           isa " << format("0x%" PRIx64, c.isa);
5365   name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
5366                        isa_n_value, c.isa);
5367   if (name != nullptr)
5368     outs() << " " << name;
5369   outs() << "\n";
5370 
5371   outs() << "    superclass " << format("0x%" PRIx64, c.superclass);
5372   name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
5373                        n_value, c.superclass);
5374   if (name != nullptr)
5375     outs() << " " << name;
5376   else {
5377     name = get_dyld_bind_info_symbolname(S.getAddress() +
5378              offset + offsetof(struct class64_t, superclass), info);
5379     if (name != nullptr)
5380       outs() << " " << name;
5381   }
5382   outs() << "\n";
5383 
5384   outs() << "         cache " << format("0x%" PRIx64, c.cache);
5385   name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
5386                        n_value, c.cache);
5387   if (name != nullptr)
5388     outs() << " " << name;
5389   outs() << "\n";
5390 
5391   outs() << "        vtable " << format("0x%" PRIx64, c.vtable);
5392   name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
5393                        n_value, c.vtable);
5394   if (name != nullptr)
5395     outs() << " " << name;
5396   outs() << "\n";
5397 
5398   name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
5399                        n_value, c.data);
5400   outs() << "          data ";
5401   if (n_value != 0) {
5402     if (info->verbose && name != nullptr)
5403       outs() << name;
5404     else
5405       outs() << format("0x%" PRIx64, n_value);
5406     if (c.data != 0)
5407       outs() << " + " << format("0x%" PRIx64, c.data);
5408   } else
5409     outs() << format("0x%" PRIx64, c.data);
5410   outs() << " (struct class_ro_t *)";
5411 
5412   // This is a Swift class if some of the low bits of the pointer are set.
5413   if ((c.data + n_value) & 0x7)
5414     outs() << " Swift class";
5415   outs() << "\n";
5416   bool is_meta_class;
5417   if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
5418     return;
5419 
5420   if (!is_meta_class &&
5421       c.isa + isa_n_value != p &&
5422       c.isa + isa_n_value != 0 &&
5423       info->depth < 100) {
5424       info->depth++;
5425       outs() << "Meta Class\n";
5426       print_class64_t(c.isa + isa_n_value, info);
5427   }
5428 }
5429 
5430 static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
5431   struct class32_t c;
5432   const char *r;
5433   uint32_t offset, left;
5434   SectionRef S;
5435   const char *name;
5436 
5437   r = get_pointer_32(p, offset, left, S, info);
5438   if (r == nullptr)
5439     return;
5440   memset(&c, '\0', sizeof(struct class32_t));
5441   if (left < sizeof(struct class32_t)) {
5442     memcpy(&c, r, left);
5443     outs() << "   (class_t entends past the end of the section)\n";
5444   } else
5445     memcpy(&c, r, sizeof(struct class32_t));
5446   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5447     swapStruct(c);
5448 
5449   outs() << "           isa " << format("0x%" PRIx32, c.isa);
5450   name =
5451       get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
5452   if (name != nullptr)
5453     outs() << " " << name;
5454   outs() << "\n";
5455 
5456   outs() << "    superclass " << format("0x%" PRIx32, c.superclass);
5457   name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
5458                        c.superclass);
5459   if (name != nullptr)
5460     outs() << " " << name;
5461   outs() << "\n";
5462 
5463   outs() << "         cache " << format("0x%" PRIx32, c.cache);
5464   name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
5465                        c.cache);
5466   if (name != nullptr)
5467     outs() << " " << name;
5468   outs() << "\n";
5469 
5470   outs() << "        vtable " << format("0x%" PRIx32, c.vtable);
5471   name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
5472                        c.vtable);
5473   if (name != nullptr)
5474     outs() << " " << name;
5475   outs() << "\n";
5476 
5477   name =
5478       get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
5479   outs() << "          data " << format("0x%" PRIx32, c.data)
5480          << " (struct class_ro_t *)";
5481 
5482   // This is a Swift class if some of the low bits of the pointer are set.
5483   if (c.data & 0x3)
5484     outs() << " Swift class";
5485   outs() << "\n";
5486   bool is_meta_class;
5487   if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
5488     return;
5489 
5490   if (!is_meta_class) {
5491     outs() << "Meta Class\n";
5492     print_class32_t(c.isa, info);
5493   }
5494 }
5495 
5496 static void print_objc_class_t(struct objc_class_t *objc_class,
5497                                struct DisassembleInfo *info) {
5498   uint32_t offset, left, xleft;
5499   const char *name, *p, *ivar_list;
5500   SectionRef S;
5501   int32_t i;
5502   struct objc_ivar_list_t objc_ivar_list;
5503   struct objc_ivar_t ivar;
5504 
5505   outs() << "\t\t      isa " << format("0x%08" PRIx32, objc_class->isa);
5506   if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
5507     name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
5508     if (name != nullptr)
5509       outs() << format(" %.*s", left, name);
5510     else
5511       outs() << " (not in an __OBJC section)";
5512   }
5513   outs() << "\n";
5514 
5515   outs() << "\t      super_class "
5516          << format("0x%08" PRIx32, objc_class->super_class);
5517   if (info->verbose) {
5518     name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
5519     if (name != nullptr)
5520       outs() << format(" %.*s", left, name);
5521     else
5522       outs() << " (not in an __OBJC section)";
5523   }
5524   outs() << "\n";
5525 
5526   outs() << "\t\t     name " << format("0x%08" PRIx32, objc_class->name);
5527   if (info->verbose) {
5528     name = get_pointer_32(objc_class->name, offset, left, S, info, true);
5529     if (name != nullptr)
5530       outs() << format(" %.*s", left, name);
5531     else
5532       outs() << " (not in an __OBJC section)";
5533   }
5534   outs() << "\n";
5535 
5536   outs() << "\t\t  version " << format("0x%08" PRIx32, objc_class->version)
5537          << "\n";
5538 
5539   outs() << "\t\t     info " << format("0x%08" PRIx32, objc_class->info);
5540   if (info->verbose) {
5541     if (CLS_GETINFO(objc_class, CLS_CLASS))
5542       outs() << " CLS_CLASS";
5543     else if (CLS_GETINFO(objc_class, CLS_META))
5544       outs() << " CLS_META";
5545   }
5546   outs() << "\n";
5547 
5548   outs() << "\t    instance_size "
5549          << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
5550 
5551   p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
5552   outs() << "\t\t    ivars " << format("0x%08" PRIx32, objc_class->ivars);
5553   if (p != nullptr) {
5554     if (left > sizeof(struct objc_ivar_list_t)) {
5555       outs() << "\n";
5556       memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
5557     } else {
5558       outs() << " (entends past the end of the section)\n";
5559       memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
5560       memcpy(&objc_ivar_list, p, left);
5561     }
5562     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5563       swapStruct(objc_ivar_list);
5564     outs() << "\t\t       ivar_count " << objc_ivar_list.ivar_count << "\n";
5565     ivar_list = p + sizeof(struct objc_ivar_list_t);
5566     for (i = 0; i < objc_ivar_list.ivar_count; i++) {
5567       if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
5568         outs() << "\t\t remaining ivar's extend past the of the section\n";
5569         break;
5570       }
5571       memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
5572              sizeof(struct objc_ivar_t));
5573       if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5574         swapStruct(ivar);
5575 
5576       outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
5577       if (info->verbose) {
5578         name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
5579         if (name != nullptr)
5580           outs() << format(" %.*s", xleft, name);
5581         else
5582           outs() << " (not in an __OBJC section)";
5583       }
5584       outs() << "\n";
5585 
5586       outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
5587       if (info->verbose) {
5588         name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
5589         if (name != nullptr)
5590           outs() << format(" %.*s", xleft, name);
5591         else
5592           outs() << " (not in an __OBJC section)";
5593       }
5594       outs() << "\n";
5595 
5596       outs() << "\t\t      ivar_offset "
5597              << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
5598     }
5599   } else {
5600     outs() << " (not in an __OBJC section)\n";
5601   }
5602 
5603   outs() << "\t\t  methods " << format("0x%08" PRIx32, objc_class->methodLists);
5604   if (print_method_list(objc_class->methodLists, info))
5605     outs() << " (not in an __OBJC section)\n";
5606 
5607   outs() << "\t\t    cache " << format("0x%08" PRIx32, objc_class->cache)
5608          << "\n";
5609 
5610   outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
5611   if (print_protocol_list(objc_class->protocols, 16, info))
5612     outs() << " (not in an __OBJC section)\n";
5613 }
5614 
5615 static void print_objc_objc_category_t(struct objc_category_t *objc_category,
5616                                        struct DisassembleInfo *info) {
5617   uint32_t offset, left;
5618   const char *name;
5619   SectionRef S;
5620 
5621   outs() << "\t       category name "
5622          << format("0x%08" PRIx32, objc_category->category_name);
5623   if (info->verbose) {
5624     name = get_pointer_32(objc_category->category_name, offset, left, S, info,
5625                           true);
5626     if (name != nullptr)
5627       outs() << format(" %.*s", left, name);
5628     else
5629       outs() << " (not in an __OBJC section)";
5630   }
5631   outs() << "\n";
5632 
5633   outs() << "\t\t  class name "
5634          << format("0x%08" PRIx32, objc_category->class_name);
5635   if (info->verbose) {
5636     name =
5637         get_pointer_32(objc_category->class_name, offset, left, S, info, true);
5638     if (name != nullptr)
5639       outs() << format(" %.*s", left, name);
5640     else
5641       outs() << " (not in an __OBJC section)";
5642   }
5643   outs() << "\n";
5644 
5645   outs() << "\t    instance methods "
5646          << format("0x%08" PRIx32, objc_category->instance_methods);
5647   if (print_method_list(objc_category->instance_methods, info))
5648     outs() << " (not in an __OBJC section)\n";
5649 
5650   outs() << "\t       class methods "
5651          << format("0x%08" PRIx32, objc_category->class_methods);
5652   if (print_method_list(objc_category->class_methods, info))
5653     outs() << " (not in an __OBJC section)\n";
5654 }
5655 
5656 static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
5657   struct category64_t c;
5658   const char *r;
5659   uint32_t offset, xoffset, left;
5660   SectionRef S, xS;
5661   const char *name, *sym_name;
5662   uint64_t n_value;
5663 
5664   r = get_pointer_64(p, offset, left, S, info);
5665   if (r == nullptr)
5666     return;
5667   memset(&c, '\0', sizeof(struct category64_t));
5668   if (left < sizeof(struct category64_t)) {
5669     memcpy(&c, r, left);
5670     outs() << "   (category_t entends past the end of the section)\n";
5671   } else
5672     memcpy(&c, r, sizeof(struct category64_t));
5673   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5674     swapStruct(c);
5675 
5676   outs() << "              name ";
5677   sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
5678                            info, n_value, c.name);
5679   if (n_value != 0) {
5680     if (info->verbose && sym_name != nullptr)
5681       outs() << sym_name;
5682     else
5683       outs() << format("0x%" PRIx64, n_value);
5684     if (c.name != 0)
5685       outs() << " + " << format("0x%" PRIx64, c.name);
5686   } else
5687     outs() << format("0x%" PRIx64, c.name);
5688   name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
5689   if (name != nullptr)
5690     outs() << format(" %.*s", left, name);
5691   outs() << "\n";
5692 
5693   outs() << "               cls ";
5694   sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
5695                            n_value, c.cls);
5696   if (n_value != 0) {
5697     if (info->verbose && sym_name != nullptr)
5698       outs() << sym_name;
5699     else
5700       outs() << format("0x%" PRIx64, n_value);
5701     if (c.cls != 0)
5702       outs() << " + " << format("0x%" PRIx64, c.cls);
5703   } else
5704     outs() << format("0x%" PRIx64, c.cls);
5705   outs() << "\n";
5706   if (c.cls + n_value != 0)
5707     print_class64_t(c.cls + n_value, info);
5708 
5709   outs() << "   instanceMethods ";
5710   sym_name =
5711       get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
5712                     info, n_value, c.instanceMethods);
5713   if (n_value != 0) {
5714     if (info->verbose && sym_name != nullptr)
5715       outs() << sym_name;
5716     else
5717       outs() << format("0x%" PRIx64, n_value);
5718     if (c.instanceMethods != 0)
5719       outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
5720   } else
5721     outs() << format("0x%" PRIx64, c.instanceMethods);
5722   outs() << "\n";
5723   if (c.instanceMethods + n_value != 0)
5724     print_method_list64_t(c.instanceMethods + n_value, info, "");
5725 
5726   outs() << "      classMethods ";
5727   sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
5728                            S, info, n_value, c.classMethods);
5729   if (n_value != 0) {
5730     if (info->verbose && sym_name != nullptr)
5731       outs() << sym_name;
5732     else
5733       outs() << format("0x%" PRIx64, n_value);
5734     if (c.classMethods != 0)
5735       outs() << " + " << format("0x%" PRIx64, c.classMethods);
5736   } else
5737     outs() << format("0x%" PRIx64, c.classMethods);
5738   outs() << "\n";
5739   if (c.classMethods + n_value != 0)
5740     print_method_list64_t(c.classMethods + n_value, info, "");
5741 
5742   outs() << "         protocols ";
5743   sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
5744                            info, n_value, c.protocols);
5745   if (n_value != 0) {
5746     if (info->verbose && sym_name != nullptr)
5747       outs() << sym_name;
5748     else
5749       outs() << format("0x%" PRIx64, n_value);
5750     if (c.protocols != 0)
5751       outs() << " + " << format("0x%" PRIx64, c.protocols);
5752   } else
5753     outs() << format("0x%" PRIx64, c.protocols);
5754   outs() << "\n";
5755   if (c.protocols + n_value != 0)
5756     print_protocol_list64_t(c.protocols + n_value, info);
5757 
5758   outs() << "instanceProperties ";
5759   sym_name =
5760       get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
5761                     S, info, n_value, c.instanceProperties);
5762   if (n_value != 0) {
5763     if (info->verbose && sym_name != nullptr)
5764       outs() << sym_name;
5765     else
5766       outs() << format("0x%" PRIx64, n_value);
5767     if (c.instanceProperties != 0)
5768       outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
5769   } else
5770     outs() << format("0x%" PRIx64, c.instanceProperties);
5771   outs() << "\n";
5772   if (c.instanceProperties + n_value != 0)
5773     print_objc_property_list64(c.instanceProperties + n_value, info);
5774 }
5775 
5776 static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
5777   struct category32_t c;
5778   const char *r;
5779   uint32_t offset, left;
5780   SectionRef S, xS;
5781   const char *name;
5782 
5783   r = get_pointer_32(p, offset, left, S, info);
5784   if (r == nullptr)
5785     return;
5786   memset(&c, '\0', sizeof(struct category32_t));
5787   if (left < sizeof(struct category32_t)) {
5788     memcpy(&c, r, left);
5789     outs() << "   (category_t entends past the end of the section)\n";
5790   } else
5791     memcpy(&c, r, sizeof(struct category32_t));
5792   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5793     swapStruct(c);
5794 
5795   outs() << "              name " << format("0x%" PRIx32, c.name);
5796   name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
5797                        c.name);
5798   if (name)
5799     outs() << " " << name;
5800   outs() << "\n";
5801 
5802   outs() << "               cls " << format("0x%" PRIx32, c.cls) << "\n";
5803   if (c.cls != 0)
5804     print_class32_t(c.cls, info);
5805   outs() << "   instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
5806          << "\n";
5807   if (c.instanceMethods != 0)
5808     print_method_list32_t(c.instanceMethods, info, "");
5809   outs() << "      classMethods " << format("0x%" PRIx32, c.classMethods)
5810          << "\n";
5811   if (c.classMethods != 0)
5812     print_method_list32_t(c.classMethods, info, "");
5813   outs() << "         protocols " << format("0x%" PRIx32, c.protocols) << "\n";
5814   if (c.protocols != 0)
5815     print_protocol_list32_t(c.protocols, info);
5816   outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
5817          << "\n";
5818   if (c.instanceProperties != 0)
5819     print_objc_property_list32(c.instanceProperties, info);
5820 }
5821 
5822 static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
5823   uint32_t i, left, offset, xoffset;
5824   uint64_t p, n_value;
5825   struct message_ref64 mr;
5826   const char *name, *sym_name;
5827   const char *r;
5828   SectionRef xS;
5829 
5830   if (S == SectionRef())
5831     return;
5832 
5833   StringRef SectName;
5834   Expected<StringRef> SecNameOrErr = S.getName();
5835   if (SecNameOrErr)
5836     SectName = *SecNameOrErr;
5837   else
5838     consumeError(SecNameOrErr.takeError());
5839 
5840   DataRefImpl Ref = S.getRawDataRefImpl();
5841   StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5842   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5843   offset = 0;
5844   for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5845     p = S.getAddress() + i;
5846     r = get_pointer_64(p, offset, left, S, info);
5847     if (r == nullptr)
5848       return;
5849     memset(&mr, '\0', sizeof(struct message_ref64));
5850     if (left < sizeof(struct message_ref64)) {
5851       memcpy(&mr, r, left);
5852       outs() << "   (message_ref entends past the end of the section)\n";
5853     } else
5854       memcpy(&mr, r, sizeof(struct message_ref64));
5855     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5856       swapStruct(mr);
5857 
5858     outs() << "  imp ";
5859     name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
5860                          n_value, mr.imp);
5861     if (n_value != 0) {
5862       outs() << format("0x%" PRIx64, n_value) << " ";
5863       if (mr.imp != 0)
5864         outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
5865     } else
5866       outs() << format("0x%" PRIx64, mr.imp) << " ";
5867     if (name != nullptr)
5868       outs() << " " << name;
5869     outs() << "\n";
5870 
5871     outs() << "  sel ";
5872     sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
5873                              info, n_value, mr.sel);
5874     if (n_value != 0) {
5875       if (info->verbose && sym_name != nullptr)
5876         outs() << sym_name;
5877       else
5878         outs() << format("0x%" PRIx64, n_value);
5879       if (mr.sel != 0)
5880         outs() << " + " << format("0x%" PRIx64, mr.sel);
5881     } else
5882       outs() << format("0x%" PRIx64, mr.sel);
5883     name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
5884     if (name != nullptr)
5885       outs() << format(" %.*s", left, name);
5886     outs() << "\n";
5887 
5888     offset += sizeof(struct message_ref64);
5889   }
5890 }
5891 
5892 static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
5893   uint32_t i, left, offset, xoffset, p;
5894   struct message_ref32 mr;
5895   const char *name, *r;
5896   SectionRef xS;
5897 
5898   if (S == SectionRef())
5899     return;
5900 
5901   StringRef SectName;
5902   Expected<StringRef> SecNameOrErr = S.getName();
5903   if (SecNameOrErr)
5904     SectName = *SecNameOrErr;
5905   else
5906     consumeError(SecNameOrErr.takeError());
5907 
5908   DataRefImpl Ref = S.getRawDataRefImpl();
5909   StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5910   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5911   offset = 0;
5912   for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5913     p = S.getAddress() + i;
5914     r = get_pointer_32(p, offset, left, S, info);
5915     if (r == nullptr)
5916       return;
5917     memset(&mr, '\0', sizeof(struct message_ref32));
5918     if (left < sizeof(struct message_ref32)) {
5919       memcpy(&mr, r, left);
5920       outs() << "   (message_ref entends past the end of the section)\n";
5921     } else
5922       memcpy(&mr, r, sizeof(struct message_ref32));
5923     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5924       swapStruct(mr);
5925 
5926     outs() << "  imp " << format("0x%" PRIx32, mr.imp);
5927     name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
5928                          mr.imp);
5929     if (name != nullptr)
5930       outs() << " " << name;
5931     outs() << "\n";
5932 
5933     outs() << "  sel " << format("0x%" PRIx32, mr.sel);
5934     name = get_pointer_32(mr.sel, xoffset, left, xS, info);
5935     if (name != nullptr)
5936       outs() << " " << name;
5937     outs() << "\n";
5938 
5939     offset += sizeof(struct message_ref32);
5940   }
5941 }
5942 
5943 static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
5944   uint32_t left, offset, swift_version;
5945   uint64_t p;
5946   struct objc_image_info64 o;
5947   const char *r;
5948 
5949   if (S == SectionRef())
5950     return;
5951 
5952   StringRef SectName;
5953   Expected<StringRef> SecNameOrErr = S.getName();
5954   if (SecNameOrErr)
5955     SectName = *SecNameOrErr;
5956   else
5957     consumeError(SecNameOrErr.takeError());
5958 
5959   DataRefImpl Ref = S.getRawDataRefImpl();
5960   StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5961   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5962   p = S.getAddress();
5963   r = get_pointer_64(p, offset, left, S, info);
5964   if (r == nullptr)
5965     return;
5966   memset(&o, '\0', sizeof(struct objc_image_info64));
5967   if (left < sizeof(struct objc_image_info64)) {
5968     memcpy(&o, r, left);
5969     outs() << "   (objc_image_info entends past the end of the section)\n";
5970   } else
5971     memcpy(&o, r, sizeof(struct objc_image_info64));
5972   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5973     swapStruct(o);
5974   outs() << "  version " << o.version << "\n";
5975   outs() << "    flags " << format("0x%" PRIx32, o.flags);
5976   if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5977     outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5978   if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5979     outs() << " OBJC_IMAGE_SUPPORTS_GC";
5980   if (o.flags & OBJC_IMAGE_IS_SIMULATED)
5981     outs() << " OBJC_IMAGE_IS_SIMULATED";
5982   if (o.flags & OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES)
5983     outs() << " OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES";
5984   swift_version = (o.flags >> 8) & 0xff;
5985   if (swift_version != 0) {
5986     if (swift_version == 1)
5987       outs() << " Swift 1.0";
5988     else if (swift_version == 2)
5989       outs() << " Swift 1.1";
5990     else if(swift_version == 3)
5991       outs() << " Swift 2.0";
5992     else if(swift_version == 4)
5993       outs() << " Swift 3.0";
5994     else if(swift_version == 5)
5995       outs() << " Swift 4.0";
5996     else if(swift_version == 6)
5997       outs() << " Swift 4.1/Swift 4.2";
5998     else if(swift_version == 7)
5999       outs() << " Swift 5 or later";
6000     else
6001       outs() << " unknown future Swift version (" << swift_version << ")";
6002   }
6003   outs() << "\n";
6004 }
6005 
6006 static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
6007   uint32_t left, offset, swift_version, p;
6008   struct objc_image_info32 o;
6009   const char *r;
6010 
6011   if (S == SectionRef())
6012     return;
6013 
6014   StringRef SectName;
6015   Expected<StringRef> SecNameOrErr = S.getName();
6016   if (SecNameOrErr)
6017     SectName = *SecNameOrErr;
6018   else
6019     consumeError(SecNameOrErr.takeError());
6020 
6021   DataRefImpl Ref = S.getRawDataRefImpl();
6022   StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
6023   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
6024   p = S.getAddress();
6025   r = get_pointer_32(p, offset, left, S, info);
6026   if (r == nullptr)
6027     return;
6028   memset(&o, '\0', sizeof(struct objc_image_info32));
6029   if (left < sizeof(struct objc_image_info32)) {
6030     memcpy(&o, r, left);
6031     outs() << "   (objc_image_info entends past the end of the section)\n";
6032   } else
6033     memcpy(&o, r, sizeof(struct objc_image_info32));
6034   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
6035     swapStruct(o);
6036   outs() << "  version " << o.version << "\n";
6037   outs() << "    flags " << format("0x%" PRIx32, o.flags);
6038   if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
6039     outs() << " OBJC_IMAGE_IS_REPLACEMENT";
6040   if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
6041     outs() << " OBJC_IMAGE_SUPPORTS_GC";
6042   swift_version = (o.flags >> 8) & 0xff;
6043   if (swift_version != 0) {
6044     if (swift_version == 1)
6045       outs() << " Swift 1.0";
6046     else if (swift_version == 2)
6047       outs() << " Swift 1.1";
6048     else if(swift_version == 3)
6049       outs() << " Swift 2.0";
6050     else if(swift_version == 4)
6051       outs() << " Swift 3.0";
6052     else if(swift_version == 5)
6053       outs() << " Swift 4.0";
6054     else if(swift_version == 6)
6055       outs() << " Swift 4.1/Swift 4.2";
6056     else if(swift_version == 7)
6057       outs() << " Swift 5 or later";
6058     else
6059       outs() << " unknown future Swift version (" << swift_version << ")";
6060   }
6061   outs() << "\n";
6062 }
6063 
6064 static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
6065   uint32_t left, offset, p;
6066   struct imageInfo_t o;
6067   const char *r;
6068 
6069   StringRef SectName;
6070   Expected<StringRef> SecNameOrErr = S.getName();
6071   if (SecNameOrErr)
6072     SectName = *SecNameOrErr;
6073   else
6074     consumeError(SecNameOrErr.takeError());
6075 
6076   DataRefImpl Ref = S.getRawDataRefImpl();
6077   StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
6078   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
6079   p = S.getAddress();
6080   r = get_pointer_32(p, offset, left, S, info);
6081   if (r == nullptr)
6082     return;
6083   memset(&o, '\0', sizeof(struct imageInfo_t));
6084   if (left < sizeof(struct imageInfo_t)) {
6085     memcpy(&o, r, left);
6086     outs() << " (imageInfo entends past the end of the section)\n";
6087   } else
6088     memcpy(&o, r, sizeof(struct imageInfo_t));
6089   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
6090     swapStruct(o);
6091   outs() << "  version " << o.version << "\n";
6092   outs() << "    flags " << format("0x%" PRIx32, o.flags);
6093   if (o.flags & 0x1)
6094     outs() << "  F&C";
6095   if (o.flags & 0x2)
6096     outs() << " GC";
6097   if (o.flags & 0x4)
6098     outs() << " GC-only";
6099   else
6100     outs() << " RR";
6101   outs() << "\n";
6102 }
6103 
6104 static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
6105   SymbolAddressMap AddrMap;
6106   if (verbose)
6107     CreateSymbolAddressMap(O, &AddrMap);
6108 
6109   std::vector<SectionRef> Sections;
6110   for (const SectionRef &Section : O->sections())
6111     Sections.push_back(Section);
6112 
6113   struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
6114 
6115   SectionRef CL = get_section(O, "__OBJC2", "__class_list");
6116   if (CL == SectionRef())
6117     CL = get_section(O, "__DATA", "__objc_classlist");
6118   if (CL == SectionRef())
6119     CL = get_section(O, "__DATA_CONST", "__objc_classlist");
6120   if (CL == SectionRef())
6121     CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
6122   info.S = CL;
6123   walk_pointer_list_64("class", CL, O, &info, print_class64_t);
6124 
6125   SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
6126   if (CR == SectionRef())
6127     CR = get_section(O, "__DATA", "__objc_classrefs");
6128   if (CR == SectionRef())
6129     CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
6130   if (CR == SectionRef())
6131     CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
6132   info.S = CR;
6133   walk_pointer_list_64("class refs", CR, O, &info, nullptr);
6134 
6135   SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
6136   if (SR == SectionRef())
6137     SR = get_section(O, "__DATA", "__objc_superrefs");
6138   if (SR == SectionRef())
6139     SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
6140   if (SR == SectionRef())
6141     SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
6142   info.S = SR;
6143   walk_pointer_list_64("super refs", SR, O, &info, nullptr);
6144 
6145   SectionRef CA = get_section(O, "__OBJC2", "__category_list");
6146   if (CA == SectionRef())
6147     CA = get_section(O, "__DATA", "__objc_catlist");
6148   if (CA == SectionRef())
6149     CA = get_section(O, "__DATA_CONST", "__objc_catlist");
6150   if (CA == SectionRef())
6151     CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
6152   info.S = CA;
6153   walk_pointer_list_64("category", CA, O, &info, print_category64_t);
6154 
6155   SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
6156   if (PL == SectionRef())
6157     PL = get_section(O, "__DATA", "__objc_protolist");
6158   if (PL == SectionRef())
6159     PL = get_section(O, "__DATA_CONST", "__objc_protolist");
6160   if (PL == SectionRef())
6161     PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
6162   info.S = PL;
6163   walk_pointer_list_64("protocol", PL, O, &info, nullptr);
6164 
6165   SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
6166   if (MR == SectionRef())
6167     MR = get_section(O, "__DATA", "__objc_msgrefs");
6168   if (MR == SectionRef())
6169     MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
6170   if (MR == SectionRef())
6171     MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
6172   info.S = MR;
6173   print_message_refs64(MR, &info);
6174 
6175   SectionRef II = get_section(O, "__OBJC2", "__image_info");
6176   if (II == SectionRef())
6177     II = get_section(O, "__DATA", "__objc_imageinfo");
6178   if (II == SectionRef())
6179     II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
6180   if (II == SectionRef())
6181     II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
6182   info.S = II;
6183   print_image_info64(II, &info);
6184 }
6185 
6186 static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
6187   SymbolAddressMap AddrMap;
6188   if (verbose)
6189     CreateSymbolAddressMap(O, &AddrMap);
6190 
6191   std::vector<SectionRef> Sections;
6192   for (const SectionRef &Section : O->sections())
6193     Sections.push_back(Section);
6194 
6195   struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
6196 
6197   SectionRef CL = get_section(O, "__OBJC2", "__class_list");
6198   if (CL == SectionRef())
6199     CL = get_section(O, "__DATA", "__objc_classlist");
6200   if (CL == SectionRef())
6201     CL = get_section(O, "__DATA_CONST", "__objc_classlist");
6202   if (CL == SectionRef())
6203     CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
6204   info.S = CL;
6205   walk_pointer_list_32("class", CL, O, &info, print_class32_t);
6206 
6207   SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
6208   if (CR == SectionRef())
6209     CR = get_section(O, "__DATA", "__objc_classrefs");
6210   if (CR == SectionRef())
6211     CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
6212   if (CR == SectionRef())
6213     CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
6214   info.S = CR;
6215   walk_pointer_list_32("class refs", CR, O, &info, nullptr);
6216 
6217   SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
6218   if (SR == SectionRef())
6219     SR = get_section(O, "__DATA", "__objc_superrefs");
6220   if (SR == SectionRef())
6221     SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
6222   if (SR == SectionRef())
6223     SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
6224   info.S = SR;
6225   walk_pointer_list_32("super refs", SR, O, &info, nullptr);
6226 
6227   SectionRef CA = get_section(O, "__OBJC2", "__category_list");
6228   if (CA == SectionRef())
6229     CA = get_section(O, "__DATA", "__objc_catlist");
6230   if (CA == SectionRef())
6231     CA = get_section(O, "__DATA_CONST", "__objc_catlist");
6232   if (CA == SectionRef())
6233     CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
6234   info.S = CA;
6235   walk_pointer_list_32("category", CA, O, &info, print_category32_t);
6236 
6237   SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
6238   if (PL == SectionRef())
6239     PL = get_section(O, "__DATA", "__objc_protolist");
6240   if (PL == SectionRef())
6241     PL = get_section(O, "__DATA_CONST", "__objc_protolist");
6242   if (PL == SectionRef())
6243     PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
6244   info.S = PL;
6245   walk_pointer_list_32("protocol", PL, O, &info, nullptr);
6246 
6247   SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
6248   if (MR == SectionRef())
6249     MR = get_section(O, "__DATA", "__objc_msgrefs");
6250   if (MR == SectionRef())
6251     MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
6252   if (MR == SectionRef())
6253     MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
6254   info.S = MR;
6255   print_message_refs32(MR, &info);
6256 
6257   SectionRef II = get_section(O, "__OBJC2", "__image_info");
6258   if (II == SectionRef())
6259     II = get_section(O, "__DATA", "__objc_imageinfo");
6260   if (II == SectionRef())
6261     II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
6262   if (II == SectionRef())
6263     II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
6264   info.S = II;
6265   print_image_info32(II, &info);
6266 }
6267 
6268 static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
6269   uint32_t i, j, p, offset, xoffset, left, defs_left, def;
6270   const char *r, *name, *defs;
6271   struct objc_module_t module;
6272   SectionRef S, xS;
6273   struct objc_symtab_t symtab;
6274   struct objc_class_t objc_class;
6275   struct objc_category_t objc_category;
6276 
6277   outs() << "Objective-C segment\n";
6278   S = get_section(O, "__OBJC", "__module_info");
6279   if (S == SectionRef())
6280     return false;
6281 
6282   SymbolAddressMap AddrMap;
6283   if (verbose)
6284     CreateSymbolAddressMap(O, &AddrMap);
6285 
6286   std::vector<SectionRef> Sections;
6287   for (const SectionRef &Section : O->sections())
6288     Sections.push_back(Section);
6289 
6290   struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
6291 
6292   for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
6293     p = S.getAddress() + i;
6294     r = get_pointer_32(p, offset, left, S, &info, true);
6295     if (r == nullptr)
6296       return true;
6297     memset(&module, '\0', sizeof(struct objc_module_t));
6298     if (left < sizeof(struct objc_module_t)) {
6299       memcpy(&module, r, left);
6300       outs() << "   (module extends past end of __module_info section)\n";
6301     } else
6302       memcpy(&module, r, sizeof(struct objc_module_t));
6303     if (O->isLittleEndian() != sys::IsLittleEndianHost)
6304       swapStruct(module);
6305 
6306     outs() << "Module " << format("0x%" PRIx32, p) << "\n";
6307     outs() << "    version " << module.version << "\n";
6308     outs() << "       size " << module.size << "\n";
6309     outs() << "       name ";
6310     name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
6311     if (name != nullptr)
6312       outs() << format("%.*s", left, name);
6313     else
6314       outs() << format("0x%08" PRIx32, module.name)
6315              << "(not in an __OBJC section)";
6316     outs() << "\n";
6317 
6318     r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
6319     if (module.symtab == 0 || r == nullptr) {
6320       outs() << "     symtab " << format("0x%08" PRIx32, module.symtab)
6321              << " (not in an __OBJC section)\n";
6322       continue;
6323     }
6324     outs() << "     symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
6325     memset(&symtab, '\0', sizeof(struct objc_symtab_t));
6326     defs_left = 0;
6327     defs = nullptr;
6328     if (left < sizeof(struct objc_symtab_t)) {
6329       memcpy(&symtab, r, left);
6330       outs() << "\tsymtab extends past end of an __OBJC section)\n";
6331     } else {
6332       memcpy(&symtab, r, sizeof(struct objc_symtab_t));
6333       if (left > sizeof(struct objc_symtab_t)) {
6334         defs_left = left - sizeof(struct objc_symtab_t);
6335         defs = r + sizeof(struct objc_symtab_t);
6336       }
6337     }
6338     if (O->isLittleEndian() != sys::IsLittleEndianHost)
6339       swapStruct(symtab);
6340 
6341     outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
6342     r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
6343     outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
6344     if (r == nullptr)
6345       outs() << " (not in an __OBJC section)";
6346     outs() << "\n";
6347     outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
6348     outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
6349     if (symtab.cls_def_cnt > 0)
6350       outs() << "\tClass Definitions\n";
6351     for (j = 0; j < symtab.cls_def_cnt; j++) {
6352       if ((j + 1) * sizeof(uint32_t) > defs_left) {
6353         outs() << "\t(remaining class defs entries entends past the end of the "
6354                << "section)\n";
6355         break;
6356       }
6357       memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
6358       if (O->isLittleEndian() != sys::IsLittleEndianHost)
6359         sys::swapByteOrder(def);
6360 
6361       r = get_pointer_32(def, xoffset, left, xS, &info, true);
6362       outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
6363       if (r != nullptr) {
6364         if (left > sizeof(struct objc_class_t)) {
6365           outs() << "\n";
6366           memcpy(&objc_class, r, sizeof(struct objc_class_t));
6367         } else {
6368           outs() << " (entends past the end of the section)\n";
6369           memset(&objc_class, '\0', sizeof(struct objc_class_t));
6370           memcpy(&objc_class, r, left);
6371         }
6372         if (O->isLittleEndian() != sys::IsLittleEndianHost)
6373           swapStruct(objc_class);
6374         print_objc_class_t(&objc_class, &info);
6375       } else {
6376         outs() << "(not in an __OBJC section)\n";
6377       }
6378 
6379       if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
6380         outs() << "\tMeta Class";
6381         r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
6382         if (r != nullptr) {
6383           if (left > sizeof(struct objc_class_t)) {
6384             outs() << "\n";
6385             memcpy(&objc_class, r, sizeof(struct objc_class_t));
6386           } else {
6387             outs() << " (entends past the end of the section)\n";
6388             memset(&objc_class, '\0', sizeof(struct objc_class_t));
6389             memcpy(&objc_class, r, left);
6390           }
6391           if (O->isLittleEndian() != sys::IsLittleEndianHost)
6392             swapStruct(objc_class);
6393           print_objc_class_t(&objc_class, &info);
6394         } else {
6395           outs() << "(not in an __OBJC section)\n";
6396         }
6397       }
6398     }
6399     if (symtab.cat_def_cnt > 0)
6400       outs() << "\tCategory Definitions\n";
6401     for (j = 0; j < symtab.cat_def_cnt; j++) {
6402       if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
6403         outs() << "\t(remaining category defs entries entends past the end of "
6404                << "the section)\n";
6405         break;
6406       }
6407       memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
6408              sizeof(uint32_t));
6409       if (O->isLittleEndian() != sys::IsLittleEndianHost)
6410         sys::swapByteOrder(def);
6411 
6412       r = get_pointer_32(def, xoffset, left, xS, &info, true);
6413       outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
6414              << format("0x%08" PRIx32, def);
6415       if (r != nullptr) {
6416         if (left > sizeof(struct objc_category_t)) {
6417           outs() << "\n";
6418           memcpy(&objc_category, r, sizeof(struct objc_category_t));
6419         } else {
6420           outs() << " (entends past the end of the section)\n";
6421           memset(&objc_category, '\0', sizeof(struct objc_category_t));
6422           memcpy(&objc_category, r, left);
6423         }
6424         if (O->isLittleEndian() != sys::IsLittleEndianHost)
6425           swapStruct(objc_category);
6426         print_objc_objc_category_t(&objc_category, &info);
6427       } else {
6428         outs() << "(not in an __OBJC section)\n";
6429       }
6430     }
6431   }
6432   const SectionRef II = get_section(O, "__OBJC", "__image_info");
6433   if (II != SectionRef())
6434     print_image_info(II, &info);
6435 
6436   return true;
6437 }
6438 
6439 static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
6440                                 uint32_t size, uint32_t addr) {
6441   SymbolAddressMap AddrMap;
6442   CreateSymbolAddressMap(O, &AddrMap);
6443 
6444   std::vector<SectionRef> Sections;
6445   for (const SectionRef &Section : O->sections())
6446     Sections.push_back(Section);
6447 
6448   struct DisassembleInfo info(O, &AddrMap, &Sections, true);
6449 
6450   const char *p;
6451   struct objc_protocol_t protocol;
6452   uint32_t left, paddr;
6453   for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
6454     memset(&protocol, '\0', sizeof(struct objc_protocol_t));
6455     left = size - (p - sect);
6456     if (left < sizeof(struct objc_protocol_t)) {
6457       outs() << "Protocol extends past end of __protocol section\n";
6458       memcpy(&protocol, p, left);
6459     } else
6460       memcpy(&protocol, p, sizeof(struct objc_protocol_t));
6461     if (O->isLittleEndian() != sys::IsLittleEndianHost)
6462       swapStruct(protocol);
6463     paddr = addr + (p - sect);
6464     outs() << "Protocol " << format("0x%" PRIx32, paddr);
6465     if (print_protocol(paddr, 0, &info))
6466       outs() << "(not in an __OBJC section)\n";
6467   }
6468 }
6469 
6470 #ifdef HAVE_LIBXAR
6471 inline void swapStruct(struct xar_header &xar) {
6472   sys::swapByteOrder(xar.magic);
6473   sys::swapByteOrder(xar.size);
6474   sys::swapByteOrder(xar.version);
6475   sys::swapByteOrder(xar.toc_length_compressed);
6476   sys::swapByteOrder(xar.toc_length_uncompressed);
6477   sys::swapByteOrder(xar.cksum_alg);
6478 }
6479 
6480 static void PrintModeVerbose(uint32_t mode) {
6481   switch(mode & S_IFMT){
6482   case S_IFDIR:
6483     outs() << "d";
6484     break;
6485   case S_IFCHR:
6486     outs() << "c";
6487     break;
6488   case S_IFBLK:
6489     outs() << "b";
6490     break;
6491   case S_IFREG:
6492     outs() << "-";
6493     break;
6494   case S_IFLNK:
6495     outs() << "l";
6496     break;
6497   case S_IFSOCK:
6498     outs() << "s";
6499     break;
6500   default:
6501     outs() << "?";
6502     break;
6503   }
6504 
6505   /* owner permissions */
6506   if(mode & S_IREAD)
6507     outs() << "r";
6508   else
6509     outs() << "-";
6510   if(mode & S_IWRITE)
6511     outs() << "w";
6512   else
6513     outs() << "-";
6514   if(mode & S_ISUID)
6515     outs() << "s";
6516   else if(mode & S_IEXEC)
6517     outs() << "x";
6518   else
6519     outs() << "-";
6520 
6521   /* group permissions */
6522   if(mode & (S_IREAD >> 3))
6523     outs() << "r";
6524   else
6525     outs() << "-";
6526   if(mode & (S_IWRITE >> 3))
6527     outs() << "w";
6528   else
6529     outs() << "-";
6530   if(mode & S_ISGID)
6531     outs() << "s";
6532   else if(mode & (S_IEXEC >> 3))
6533     outs() << "x";
6534   else
6535     outs() << "-";
6536 
6537   /* other permissions */
6538   if(mode & (S_IREAD >> 6))
6539     outs() << "r";
6540   else
6541     outs() << "-";
6542   if(mode & (S_IWRITE >> 6))
6543     outs() << "w";
6544   else
6545     outs() << "-";
6546   if(mode & S_ISVTX)
6547     outs() << "t";
6548   else if(mode & (S_IEXEC >> 6))
6549     outs() << "x";
6550   else
6551     outs() << "-";
6552 }
6553 
6554 static void PrintXarFilesSummary(const char *XarFilename, xar_t xar) {
6555   xar_file_t xf;
6556   const char *key, *type, *mode, *user, *group, *size, *mtime, *name, *m;
6557   char *endp;
6558   uint32_t mode_value;
6559 
6560   ScopedXarIter xi;
6561   if (!xi) {
6562     WithColor::error(errs(), "llvm-objdump")
6563         << "can't obtain an xar iterator for xar archive " << XarFilename
6564         << "\n";
6565     return;
6566   }
6567 
6568   // Go through the xar's files.
6569   for (xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)) {
6570     ScopedXarIter xp;
6571     if(!xp){
6572       WithColor::error(errs(), "llvm-objdump")
6573           << "can't obtain an xar iterator for xar archive " << XarFilename
6574           << "\n";
6575       return;
6576     }
6577     type = nullptr;
6578     mode = nullptr;
6579     user = nullptr;
6580     group = nullptr;
6581     size = nullptr;
6582     mtime = nullptr;
6583     name = nullptr;
6584     for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
6585       const char *val = nullptr;
6586       xar_prop_get(xf, key, &val);
6587 #if 0 // Useful for debugging.
6588       outs() << "key: " << key << " value: " << val << "\n";
6589 #endif
6590       if(strcmp(key, "type") == 0)
6591         type = val;
6592       if(strcmp(key, "mode") == 0)
6593         mode = val;
6594       if(strcmp(key, "user") == 0)
6595         user = val;
6596       if(strcmp(key, "group") == 0)
6597         group = val;
6598       if(strcmp(key, "data/size") == 0)
6599         size = val;
6600       if(strcmp(key, "mtime") == 0)
6601         mtime = val;
6602       if(strcmp(key, "name") == 0)
6603         name = val;
6604     }
6605     if(mode != nullptr){
6606       mode_value = strtoul(mode, &endp, 8);
6607       if(*endp != '\0')
6608         outs() << "(mode: \"" << mode << "\" contains non-octal chars) ";
6609       if(strcmp(type, "file") == 0)
6610         mode_value |= S_IFREG;
6611       PrintModeVerbose(mode_value);
6612       outs() << " ";
6613     }
6614     if(user != nullptr)
6615       outs() << format("%10s/", user);
6616     if(group != nullptr)
6617       outs() << format("%-10s ", group);
6618     if(size != nullptr)
6619       outs() << format("%7s ", size);
6620     if(mtime != nullptr){
6621       for(m = mtime; *m != 'T' && *m != '\0'; m++)
6622         outs() << *m;
6623       if(*m == 'T')
6624         m++;
6625       outs() << " ";
6626       for( ; *m != 'Z' && *m != '\0'; m++)
6627         outs() << *m;
6628       outs() << " ";
6629     }
6630     if(name != nullptr)
6631       outs() << name;
6632     outs() << "\n";
6633   }
6634 }
6635 
6636 static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
6637                                 uint32_t size, bool verbose,
6638                                 bool PrintXarHeader, bool PrintXarFileHeaders,
6639                                 std::string XarMemberName) {
6640   if(size < sizeof(struct xar_header)) {
6641     outs() << "size of (__LLVM,__bundle) section too small (smaller than size "
6642               "of struct xar_header)\n";
6643     return;
6644   }
6645   struct xar_header XarHeader;
6646   memcpy(&XarHeader, sect, sizeof(struct xar_header));
6647   if (sys::IsLittleEndianHost)
6648     swapStruct(XarHeader);
6649   if (PrintXarHeader) {
6650     if (!XarMemberName.empty())
6651       outs() << "In xar member " << XarMemberName << ": ";
6652     else
6653       outs() << "For (__LLVM,__bundle) section: ";
6654     outs() << "xar header\n";
6655     if (XarHeader.magic == XAR_HEADER_MAGIC)
6656       outs() << "                  magic XAR_HEADER_MAGIC\n";
6657     else
6658       outs() << "                  magic "
6659              << format_hex(XarHeader.magic, 10, true)
6660              << " (not XAR_HEADER_MAGIC)\n";
6661     outs() << "                   size " << XarHeader.size << "\n";
6662     outs() << "                version " << XarHeader.version << "\n";
6663     outs() << "  toc_length_compressed " << XarHeader.toc_length_compressed
6664            << "\n";
6665     outs() << "toc_length_uncompressed " << XarHeader.toc_length_uncompressed
6666            << "\n";
6667     outs() << "              cksum_alg ";
6668     switch (XarHeader.cksum_alg) {
6669       case XAR_CKSUM_NONE:
6670         outs() << "XAR_CKSUM_NONE\n";
6671         break;
6672       case XAR_CKSUM_SHA1:
6673         outs() << "XAR_CKSUM_SHA1\n";
6674         break;
6675       case XAR_CKSUM_MD5:
6676         outs() << "XAR_CKSUM_MD5\n";
6677         break;
6678 #ifdef XAR_CKSUM_SHA256
6679       case XAR_CKSUM_SHA256:
6680         outs() << "XAR_CKSUM_SHA256\n";
6681         break;
6682 #endif
6683 #ifdef XAR_CKSUM_SHA512
6684       case XAR_CKSUM_SHA512:
6685         outs() << "XAR_CKSUM_SHA512\n";
6686         break;
6687 #endif
6688       default:
6689         outs() << XarHeader.cksum_alg << "\n";
6690     }
6691   }
6692 
6693   SmallString<128> XarFilename;
6694   int FD;
6695   std::error_code XarEC =
6696       sys::fs::createTemporaryFile("llvm-objdump", "xar", FD, XarFilename);
6697   if (XarEC) {
6698     WithColor::error(errs(), "llvm-objdump") << XarEC.message() << "\n";
6699     return;
6700   }
6701   ToolOutputFile XarFile(XarFilename, FD);
6702   raw_fd_ostream &XarOut = XarFile.os();
6703   StringRef XarContents(sect, size);
6704   XarOut << XarContents;
6705   XarOut.close();
6706   if (XarOut.has_error())
6707     return;
6708 
6709   ScopedXarFile xar(XarFilename.c_str(), READ);
6710   if (!xar) {
6711     WithColor::error(errs(), "llvm-objdump")
6712         << "can't create temporary xar archive " << XarFilename << "\n";
6713     return;
6714   }
6715 
6716   SmallString<128> TocFilename;
6717   std::error_code TocEC =
6718       sys::fs::createTemporaryFile("llvm-objdump", "toc", TocFilename);
6719   if (TocEC) {
6720     WithColor::error(errs(), "llvm-objdump") << TocEC.message() << "\n";
6721     return;
6722   }
6723   xar_serialize(xar, TocFilename.c_str());
6724 
6725   if (PrintXarFileHeaders) {
6726     if (!XarMemberName.empty())
6727       outs() << "In xar member " << XarMemberName << ": ";
6728     else
6729       outs() << "For (__LLVM,__bundle) section: ";
6730     outs() << "xar archive files:\n";
6731     PrintXarFilesSummary(XarFilename.c_str(), xar);
6732   }
6733 
6734   ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
6735     MemoryBuffer::getFileOrSTDIN(TocFilename.c_str());
6736   if (std::error_code EC = FileOrErr.getError()) {
6737     WithColor::error(errs(), "llvm-objdump") << EC.message() << "\n";
6738     return;
6739   }
6740   std::unique_ptr<MemoryBuffer> &Buffer = FileOrErr.get();
6741 
6742   if (!XarMemberName.empty())
6743     outs() << "In xar member " << XarMemberName << ": ";
6744   else
6745     outs() << "For (__LLVM,__bundle) section: ";
6746   outs() << "xar table of contents:\n";
6747   outs() << Buffer->getBuffer() << "\n";
6748 
6749   // TODO: Go through the xar's files.
6750   ScopedXarIter xi;
6751   if(!xi){
6752     WithColor::error(errs(), "llvm-objdump")
6753         << "can't obtain an xar iterator for xar archive "
6754         << XarFilename.c_str() << "\n";
6755     return;
6756   }
6757   for(xar_file_t xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)){
6758     const char *key;
6759     const char *member_name, *member_type, *member_size_string;
6760     size_t member_size;
6761 
6762     ScopedXarIter xp;
6763     if(!xp){
6764       WithColor::error(errs(), "llvm-objdump")
6765           << "can't obtain an xar iterator for xar archive "
6766           << XarFilename.c_str() << "\n";
6767       return;
6768     }
6769     member_name = NULL;
6770     member_type = NULL;
6771     member_size_string = NULL;
6772     for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
6773       const char *val = nullptr;
6774       xar_prop_get(xf, key, &val);
6775 #if 0 // Useful for debugging.
6776       outs() << "key: " << key << " value: " << val << "\n";
6777 #endif
6778       if (strcmp(key, "name") == 0)
6779         member_name = val;
6780       if (strcmp(key, "type") == 0)
6781         member_type = val;
6782       if (strcmp(key, "data/size") == 0)
6783         member_size_string = val;
6784     }
6785     /*
6786      * If we find a file with a name, date/size and type properties
6787      * and with the type being "file" see if that is a xar file.
6788      */
6789     if (member_name != NULL && member_type != NULL &&
6790         strcmp(member_type, "file") == 0 &&
6791         member_size_string != NULL){
6792       // Extract the file into a buffer.
6793       char *endptr;
6794       member_size = strtoul(member_size_string, &endptr, 10);
6795       if (*endptr == '\0' && member_size != 0) {
6796         char *buffer;
6797         if (xar_extract_tobuffersz(xar, xf, &buffer, &member_size) == 0) {
6798 #if 0 // Useful for debugging.
6799           outs() << "xar member: " << member_name << " extracted\n";
6800 #endif
6801           // Set the XarMemberName we want to see printed in the header.
6802           std::string OldXarMemberName;
6803           // If XarMemberName is already set this is nested. So
6804           // save the old name and create the nested name.
6805           if (!XarMemberName.empty()) {
6806             OldXarMemberName = XarMemberName;
6807             XarMemberName =
6808                 (Twine("[") + XarMemberName + "]" + member_name).str();
6809           } else {
6810             OldXarMemberName = "";
6811             XarMemberName = member_name;
6812           }
6813           // See if this is could be a xar file (nested).
6814           if (member_size >= sizeof(struct xar_header)) {
6815 #if 0 // Useful for debugging.
6816             outs() << "could be a xar file: " << member_name << "\n";
6817 #endif
6818             memcpy((char *)&XarHeader, buffer, sizeof(struct xar_header));
6819             if (sys::IsLittleEndianHost)
6820               swapStruct(XarHeader);
6821             if (XarHeader.magic == XAR_HEADER_MAGIC)
6822               DumpBitcodeSection(O, buffer, member_size, verbose,
6823                                  PrintXarHeader, PrintXarFileHeaders,
6824                                  XarMemberName);
6825           }
6826           XarMemberName = OldXarMemberName;
6827           delete buffer;
6828         }
6829       }
6830     }
6831   }
6832 }
6833 #endif // defined(HAVE_LIBXAR)
6834 
6835 static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
6836   if (O->is64Bit())
6837     printObjc2_64bit_MetaData(O, verbose);
6838   else {
6839     MachO::mach_header H;
6840     H = O->getHeader();
6841     if (H.cputype == MachO::CPU_TYPE_ARM)
6842       printObjc2_32bit_MetaData(O, verbose);
6843     else {
6844       // This is the 32-bit non-arm cputype case.  Which is normally
6845       // the first Objective-C ABI.  But it may be the case of a
6846       // binary for the iOS simulator which is the second Objective-C
6847       // ABI.  In that case printObjc1_32bit_MetaData() will determine that
6848       // and return false.
6849       if (!printObjc1_32bit_MetaData(O, verbose))
6850         printObjc2_32bit_MetaData(O, verbose);
6851     }
6852   }
6853 }
6854 
6855 // GuessLiteralPointer returns a string which for the item in the Mach-O file
6856 // for the address passed in as ReferenceValue for printing as a comment with
6857 // the instruction and also returns the corresponding type of that item
6858 // indirectly through ReferenceType.
6859 //
6860 // If ReferenceValue is an address of literal cstring then a pointer to the
6861 // cstring is returned and ReferenceType is set to
6862 // LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
6863 //
6864 // If ReferenceValue is an address of an Objective-C CFString, Selector ref or
6865 // Class ref that name is returned and the ReferenceType is set accordingly.
6866 //
6867 // Lastly, literals which are Symbol address in a literal pool are looked for
6868 // and if found the symbol name is returned and ReferenceType is set to
6869 // LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
6870 //
6871 // If there is no item in the Mach-O file for the address passed in as
6872 // ReferenceValue nullptr is returned and ReferenceType is unchanged.
6873 static const char *GuessLiteralPointer(uint64_t ReferenceValue,
6874                                        uint64_t ReferencePC,
6875                                        uint64_t *ReferenceType,
6876                                        struct DisassembleInfo *info) {
6877   // First see if there is an external relocation entry at the ReferencePC.
6878   if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
6879     uint64_t sect_addr = info->S.getAddress();
6880     uint64_t sect_offset = ReferencePC - sect_addr;
6881     bool reloc_found = false;
6882     DataRefImpl Rel;
6883     MachO::any_relocation_info RE;
6884     bool isExtern = false;
6885     SymbolRef Symbol;
6886     for (const RelocationRef &Reloc : info->S.relocations()) {
6887       uint64_t RelocOffset = Reloc.getOffset();
6888       if (RelocOffset == sect_offset) {
6889         Rel = Reloc.getRawDataRefImpl();
6890         RE = info->O->getRelocation(Rel);
6891         if (info->O->isRelocationScattered(RE))
6892           continue;
6893         isExtern = info->O->getPlainRelocationExternal(RE);
6894         if (isExtern) {
6895           symbol_iterator RelocSym = Reloc.getSymbol();
6896           Symbol = *RelocSym;
6897         }
6898         reloc_found = true;
6899         break;
6900       }
6901     }
6902     // If there is an external relocation entry for a symbol in a section
6903     // then used that symbol's value for the value of the reference.
6904     if (reloc_found && isExtern) {
6905       if (info->O->getAnyRelocationPCRel(RE)) {
6906         unsigned Type = info->O->getAnyRelocationType(RE);
6907         if (Type == MachO::X86_64_RELOC_SIGNED) {
6908           ReferenceValue = Symbol.getValue();
6909         }
6910       }
6911     }
6912   }
6913 
6914   // Look for literals such as Objective-C CFStrings refs, Selector refs,
6915   // Message refs and Class refs.
6916   bool classref, selref, msgref, cfstring;
6917   uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
6918                                                selref, msgref, cfstring);
6919   if (classref && pointer_value == 0) {
6920     // Note the ReferenceValue is a pointer into the __objc_classrefs section.
6921     // And the pointer_value in that section is typically zero as it will be
6922     // set by dyld as part of the "bind information".
6923     const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
6924     if (name != nullptr) {
6925       *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
6926       const char *class_name = strrchr(name, '$');
6927       if (class_name != nullptr && class_name[1] == '_' &&
6928           class_name[2] != '\0') {
6929         info->class_name = class_name + 2;
6930         return name;
6931       }
6932     }
6933   }
6934 
6935   if (classref) {
6936     *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
6937     const char *name =
6938         get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
6939     if (name != nullptr)
6940       info->class_name = name;
6941     else
6942       name = "bad class ref";
6943     return name;
6944   }
6945 
6946   if (cfstring) {
6947     *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
6948     const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
6949     return name;
6950   }
6951 
6952   if (selref && pointer_value == 0)
6953     pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
6954 
6955   if (pointer_value != 0)
6956     ReferenceValue = pointer_value;
6957 
6958   const char *name = GuessCstringPointer(ReferenceValue, info);
6959   if (name) {
6960     if (pointer_value != 0 && selref) {
6961       *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
6962       info->selector_name = name;
6963     } else if (pointer_value != 0 && msgref) {
6964       info->class_name = nullptr;
6965       *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
6966       info->selector_name = name;
6967     } else
6968       *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
6969     return name;
6970   }
6971 
6972   // Lastly look for an indirect symbol with this ReferenceValue which is in
6973   // a literal pool.  If found return that symbol name.
6974   name = GuessIndirectSymbol(ReferenceValue, info);
6975   if (name) {
6976     *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
6977     return name;
6978   }
6979 
6980   return nullptr;
6981 }
6982 
6983 // SymbolizerSymbolLookUp is the symbol lookup function passed when creating
6984 // the Symbolizer.  It looks up the ReferenceValue using the info passed via the
6985 // pointer to the struct DisassembleInfo that was passed when MCSymbolizer
6986 // is created and returns the symbol name that matches the ReferenceValue or
6987 // nullptr if none.  The ReferenceType is passed in for the IN type of
6988 // reference the instruction is making from the values in defined in the header
6989 // "llvm-c/Disassembler.h".  On return the ReferenceType can set to a specific
6990 // Out type and the ReferenceName will also be set which is added as a comment
6991 // to the disassembled instruction.
6992 //
6993 // If the symbol name is a C++ mangled name then the demangled name is
6994 // returned through ReferenceName and ReferenceType is set to
6995 // LLVMDisassembler_ReferenceType_DeMangled_Name .
6996 //
6997 // When this is called to get a symbol name for a branch target then the
6998 // ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
6999 // SymbolValue will be looked for in the indirect symbol table to determine if
7000 // it is an address for a symbol stub.  If so then the symbol name for that
7001 // stub is returned indirectly through ReferenceName and then ReferenceType is
7002 // set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
7003 //
7004 // When this is called with an value loaded via a PC relative load then
7005 // ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
7006 // SymbolValue is checked to be an address of literal pointer, symbol pointer,
7007 // or an Objective-C meta data reference.  If so the output ReferenceType is
7008 // set to correspond to that as well as setting the ReferenceName.
7009 static const char *SymbolizerSymbolLookUp(void *DisInfo,
7010                                           uint64_t ReferenceValue,
7011                                           uint64_t *ReferenceType,
7012                                           uint64_t ReferencePC,
7013                                           const char **ReferenceName) {
7014   struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
7015   // If no verbose symbolic information is wanted then just return nullptr.
7016   if (!info->verbose) {
7017     *ReferenceName = nullptr;
7018     *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7019     return nullptr;
7020   }
7021 
7022   const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
7023 
7024   if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
7025     *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
7026     if (*ReferenceName != nullptr) {
7027       method_reference(info, ReferenceType, ReferenceName);
7028       if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
7029         *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
7030     } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
7031       if (info->demangled_name != nullptr)
7032         free(info->demangled_name);
7033       int status;
7034       info->demangled_name =
7035           itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
7036       if (info->demangled_name != nullptr) {
7037         *ReferenceName = info->demangled_name;
7038         *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
7039       } else
7040         *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7041     } else
7042       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7043   } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
7044     *ReferenceName =
7045         GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7046     if (*ReferenceName)
7047       method_reference(info, ReferenceType, ReferenceName);
7048     else
7049       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7050     // If this is arm64 and the reference is an adrp instruction save the
7051     // instruction, passed in ReferenceValue and the address of the instruction
7052     // for use later if we see and add immediate instruction.
7053   } else if (info->O->getArch() == Triple::aarch64 &&
7054              *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
7055     info->adrp_inst = ReferenceValue;
7056     info->adrp_addr = ReferencePC;
7057     SymbolName = nullptr;
7058     *ReferenceName = nullptr;
7059     *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7060     // If this is arm64 and reference is an add immediate instruction and we
7061     // have
7062     // seen an adrp instruction just before it and the adrp's Xd register
7063     // matches
7064     // this add's Xn register reconstruct the value being referenced and look to
7065     // see if it is a literal pointer.  Note the add immediate instruction is
7066     // passed in ReferenceValue.
7067   } else if (info->O->getArch() == Triple::aarch64 &&
7068              *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
7069              ReferencePC - 4 == info->adrp_addr &&
7070              (info->adrp_inst & 0x9f000000) == 0x90000000 &&
7071              (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
7072     uint32_t addxri_inst;
7073     uint64_t adrp_imm, addxri_imm;
7074 
7075     adrp_imm =
7076         ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
7077     if (info->adrp_inst & 0x0200000)
7078       adrp_imm |= 0xfffffffffc000000LL;
7079 
7080     addxri_inst = ReferenceValue;
7081     addxri_imm = (addxri_inst >> 10) & 0xfff;
7082     if (((addxri_inst >> 22) & 0x3) == 1)
7083       addxri_imm <<= 12;
7084 
7085     ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
7086                      (adrp_imm << 12) + addxri_imm;
7087 
7088     *ReferenceName =
7089         GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7090     if (*ReferenceName == nullptr)
7091       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7092     // If this is arm64 and the reference is a load register instruction and we
7093     // have seen an adrp instruction just before it and the adrp's Xd register
7094     // matches this add's Xn register reconstruct the value being referenced and
7095     // look to see if it is a literal pointer.  Note the load register
7096     // instruction is passed in ReferenceValue.
7097   } else if (info->O->getArch() == Triple::aarch64 &&
7098              *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
7099              ReferencePC - 4 == info->adrp_addr &&
7100              (info->adrp_inst & 0x9f000000) == 0x90000000 &&
7101              (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
7102     uint32_t ldrxui_inst;
7103     uint64_t adrp_imm, ldrxui_imm;
7104 
7105     adrp_imm =
7106         ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
7107     if (info->adrp_inst & 0x0200000)
7108       adrp_imm |= 0xfffffffffc000000LL;
7109 
7110     ldrxui_inst = ReferenceValue;
7111     ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
7112 
7113     ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
7114                      (adrp_imm << 12) + (ldrxui_imm << 3);
7115 
7116     *ReferenceName =
7117         GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7118     if (*ReferenceName == nullptr)
7119       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7120   }
7121   // If this arm64 and is an load register (PC-relative) instruction the
7122   // ReferenceValue is the PC plus the immediate value.
7123   else if (info->O->getArch() == Triple::aarch64 &&
7124            (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
7125             *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
7126     *ReferenceName =
7127         GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7128     if (*ReferenceName == nullptr)
7129       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7130   } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
7131     if (info->demangled_name != nullptr)
7132       free(info->demangled_name);
7133     int status;
7134     info->demangled_name =
7135         itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
7136     if (info->demangled_name != nullptr) {
7137       *ReferenceName = info->demangled_name;
7138       *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
7139     }
7140   }
7141   else {
7142     *ReferenceName = nullptr;
7143     *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7144   }
7145 
7146   return SymbolName;
7147 }
7148 
7149 /// Emits the comments that are stored in the CommentStream.
7150 /// Each comment in the CommentStream must end with a newline.
7151 static void emitComments(raw_svector_ostream &CommentStream,
7152                          SmallString<128> &CommentsToEmit,
7153                          formatted_raw_ostream &FormattedOS,
7154                          const MCAsmInfo &MAI) {
7155   // Flush the stream before taking its content.
7156   StringRef Comments = CommentsToEmit.str();
7157   // Get the default information for printing a comment.
7158   StringRef CommentBegin = MAI.getCommentString();
7159   unsigned CommentColumn = MAI.getCommentColumn();
7160   bool IsFirst = true;
7161   while (!Comments.empty()) {
7162     if (!IsFirst)
7163       FormattedOS << '\n';
7164     // Emit a line of comments.
7165     FormattedOS.PadToColumn(CommentColumn);
7166     size_t Position = Comments.find('\n');
7167     FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
7168     // Move after the newline character.
7169     Comments = Comments.substr(Position + 1);
7170     IsFirst = false;
7171   }
7172   FormattedOS.flush();
7173 
7174   // Tell the comment stream that the vector changed underneath it.
7175   CommentsToEmit.clear();
7176 }
7177 
7178 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
7179                              StringRef DisSegName, StringRef DisSectName) {
7180   const char *McpuDefault = nullptr;
7181   const Target *ThumbTarget = nullptr;
7182   const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
7183   if (!TheTarget) {
7184     // GetTarget prints out stuff.
7185     return;
7186   }
7187   std::string MachOMCPU;
7188   if (MCPU.empty() && McpuDefault)
7189     MachOMCPU = McpuDefault;
7190   else
7191     MachOMCPU = MCPU;
7192 
7193   std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
7194   std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
7195   if (ThumbTarget)
7196     ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
7197 
7198   // Package up features to be passed to target/subtarget
7199   std::string FeaturesStr;
7200   if (!MAttrs.empty()) {
7201     SubtargetFeatures Features;
7202     for (unsigned i = 0; i != MAttrs.size(); ++i)
7203       Features.AddFeature(MAttrs[i]);
7204     FeaturesStr = Features.getString();
7205   }
7206 
7207   MCTargetOptions MCOptions;
7208   // Set up disassembler.
7209   std::unique_ptr<const MCRegisterInfo> MRI(
7210       TheTarget->createMCRegInfo(TripleName));
7211   std::unique_ptr<const MCAsmInfo> AsmInfo(
7212       TheTarget->createMCAsmInfo(*MRI, TripleName, MCOptions));
7213   std::unique_ptr<const MCSubtargetInfo> STI(
7214       TheTarget->createMCSubtargetInfo(TripleName, MachOMCPU, FeaturesStr));
7215   MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
7216   std::unique_ptr<MCDisassembler> DisAsm(
7217       TheTarget->createMCDisassembler(*STI, Ctx));
7218   std::unique_ptr<MCSymbolizer> Symbolizer;
7219   struct DisassembleInfo SymbolizerInfo(nullptr, nullptr, nullptr, false);
7220   std::unique_ptr<MCRelocationInfo> RelInfo(
7221       TheTarget->createMCRelocationInfo(TripleName, Ctx));
7222   if (RelInfo) {
7223     Symbolizer.reset(TheTarget->createMCSymbolizer(
7224         TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
7225         &SymbolizerInfo, &Ctx, std::move(RelInfo)));
7226     DisAsm->setSymbolizer(std::move(Symbolizer));
7227   }
7228   int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
7229   std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
7230       Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
7231   // Set the display preference for hex vs. decimal immediates.
7232   IP->setPrintImmHex(PrintImmHex);
7233   // Comment stream and backing vector.
7234   SmallString<128> CommentsToEmit;
7235   raw_svector_ostream CommentStream(CommentsToEmit);
7236   // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
7237   // if it is done then arm64 comments for string literals don't get printed
7238   // and some constant get printed instead and not setting it causes intel
7239   // (32-bit and 64-bit) comments printed with different spacing before the
7240   // comment causing different diffs with the 'C' disassembler library API.
7241   // IP->setCommentStream(CommentStream);
7242 
7243   if (!AsmInfo || !STI || !DisAsm || !IP) {
7244     WithColor::error(errs(), "llvm-objdump")
7245         << "couldn't initialize disassembler for target " << TripleName << '\n';
7246     return;
7247   }
7248 
7249   // Set up separate thumb disassembler if needed.
7250   std::unique_ptr<const MCRegisterInfo> ThumbMRI;
7251   std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
7252   std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
7253   std::unique_ptr<MCDisassembler> ThumbDisAsm;
7254   std::unique_ptr<MCInstPrinter> ThumbIP;
7255   std::unique_ptr<MCContext> ThumbCtx;
7256   std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
7257   struct DisassembleInfo ThumbSymbolizerInfo(nullptr, nullptr, nullptr, false);
7258   std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
7259   if (ThumbTarget) {
7260     ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
7261     ThumbAsmInfo.reset(
7262         ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName, MCOptions));
7263     ThumbSTI.reset(
7264         ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MachOMCPU,
7265                                            FeaturesStr));
7266     ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
7267     ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
7268     MCContext *PtrThumbCtx = ThumbCtx.get();
7269     ThumbRelInfo.reset(
7270         ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
7271     if (ThumbRelInfo) {
7272       ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
7273           ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
7274           &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
7275       ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
7276     }
7277     int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
7278     ThumbIP.reset(ThumbTarget->createMCInstPrinter(
7279         Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
7280         *ThumbInstrInfo, *ThumbMRI));
7281     // Set the display preference for hex vs. decimal immediates.
7282     ThumbIP->setPrintImmHex(PrintImmHex);
7283   }
7284 
7285   if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
7286     WithColor::error(errs(), "llvm-objdump")
7287         << "couldn't initialize disassembler for target " << ThumbTripleName
7288         << '\n';
7289     return;
7290   }
7291 
7292   MachO::mach_header Header = MachOOF->getHeader();
7293 
7294   // FIXME: Using the -cfg command line option, this code used to be able to
7295   // annotate relocations with the referenced symbol's name, and if this was
7296   // inside a __[cf]string section, the data it points to. This is now replaced
7297   // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
7298   std::vector<SectionRef> Sections;
7299   std::vector<SymbolRef> Symbols;
7300   SmallVector<uint64_t, 8> FoundFns;
7301   uint64_t BaseSegmentAddress = 0;
7302 
7303   getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
7304                         BaseSegmentAddress);
7305 
7306   // Sort the symbols by address, just in case they didn't come in that way.
7307   llvm::sort(Symbols, SymbolSorter());
7308 
7309   // Build a data in code table that is sorted on by the address of each entry.
7310   uint64_t BaseAddress = 0;
7311   if (Header.filetype == MachO::MH_OBJECT)
7312     BaseAddress = Sections[0].getAddress();
7313   else
7314     BaseAddress = BaseSegmentAddress;
7315   DiceTable Dices;
7316   for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
7317        DI != DE; ++DI) {
7318     uint32_t Offset;
7319     DI->getOffset(Offset);
7320     Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
7321   }
7322   array_pod_sort(Dices.begin(), Dices.end());
7323 
7324   // Try to find debug info and set up the DIContext for it.
7325   std::unique_ptr<DIContext> diContext;
7326   std::unique_ptr<Binary> DSYMBinary;
7327   std::unique_ptr<MemoryBuffer> DSYMBuf;
7328   if (UseDbg) {
7329     ObjectFile *DbgObj = MachOOF;
7330 
7331     // A separate DSym file path was specified, parse it as a macho file,
7332     // get the sections and supply it to the section name parsing machinery.
7333     if (!DSYMFile.empty()) {
7334       std::string DSYMPath(DSYMFile);
7335 
7336       // If DSYMPath is a .dSYM directory, append the Mach-O file.
7337       if (llvm::sys::fs::is_directory(DSYMPath) &&
7338           llvm::sys::path::extension(DSYMPath) == ".dSYM") {
7339         SmallString<128> ShortName(llvm::sys::path::filename(DSYMPath));
7340         llvm::sys::path::replace_extension(ShortName, "");
7341         SmallString<1024> FullPath(DSYMPath);
7342         llvm::sys::path::append(FullPath, "Contents", "Resources", "DWARF",
7343                                 ShortName);
7344         DSYMPath = std::string(FullPath.str());
7345       }
7346 
7347       // Load the file.
7348       ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
7349           MemoryBuffer::getFileOrSTDIN(DSYMPath);
7350       if (std::error_code EC = BufOrErr.getError()) {
7351         reportError(errorCodeToError(EC), DSYMPath);
7352         return;
7353       }
7354 
7355       // We need to keep the file alive, because we're replacing DbgObj with it.
7356       DSYMBuf = std::move(BufOrErr.get());
7357 
7358       Expected<std::unique_ptr<Binary>> BinaryOrErr =
7359       createBinary(DSYMBuf.get()->getMemBufferRef());
7360       if (!BinaryOrErr) {
7361         reportError(BinaryOrErr.takeError(), DSYMPath);
7362         return;
7363       }
7364 
7365       // We need to keep the Binary alive with the buffer
7366       DSYMBinary = std::move(BinaryOrErr.get());
7367       if (ObjectFile *O = dyn_cast<ObjectFile>(DSYMBinary.get())) {
7368         // this is a Mach-O object file, use it
7369         if (MachOObjectFile *MachDSYM = dyn_cast<MachOObjectFile>(&*O)) {
7370           DbgObj = MachDSYM;
7371         }
7372         else {
7373           WithColor::error(errs(), "llvm-objdump")
7374             << DSYMPath << " is not a Mach-O file type.\n";
7375           return;
7376         }
7377       }
7378       else if (auto UB = dyn_cast<MachOUniversalBinary>(DSYMBinary.get())){
7379         // this is a Universal Binary, find a Mach-O for this architecture
7380         uint32_t CPUType, CPUSubType;
7381         const char *ArchFlag;
7382         if (MachOOF->is64Bit()) {
7383           const MachO::mach_header_64 H_64 = MachOOF->getHeader64();
7384           CPUType = H_64.cputype;
7385           CPUSubType = H_64.cpusubtype;
7386         } else {
7387           const MachO::mach_header H = MachOOF->getHeader();
7388           CPUType = H.cputype;
7389           CPUSubType = H.cpusubtype;
7390         }
7391         Triple T = MachOObjectFile::getArchTriple(CPUType, CPUSubType, nullptr,
7392                                                   &ArchFlag);
7393         Expected<std::unique_ptr<MachOObjectFile>> MachDSYM =
7394             UB->getMachOObjectForArch(ArchFlag);
7395         if (!MachDSYM) {
7396           reportError(MachDSYM.takeError(), DSYMPath);
7397           return;
7398         }
7399 
7400         // We need to keep the Binary alive with the buffer
7401         DbgObj = &*MachDSYM.get();
7402         DSYMBinary = std::move(*MachDSYM);
7403       }
7404       else {
7405         WithColor::error(errs(), "llvm-objdump")
7406           << DSYMPath << " is not a Mach-O or Universal file type.\n";
7407         return;
7408       }
7409     }
7410 
7411     // Setup the DIContext
7412     diContext = DWARFContext::create(*DbgObj);
7413   }
7414 
7415   if (FilterSections.empty())
7416     outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
7417 
7418   for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
7419     Expected<StringRef> SecNameOrErr = Sections[SectIdx].getName();
7420     if (!SecNameOrErr) {
7421       consumeError(SecNameOrErr.takeError());
7422       continue;
7423     }
7424     if (*SecNameOrErr != DisSectName)
7425       continue;
7426 
7427     DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
7428 
7429     StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
7430     if (SegmentName != DisSegName)
7431       continue;
7432 
7433     StringRef BytesStr =
7434         unwrapOrError(Sections[SectIdx].getContents(), Filename);
7435     ArrayRef<uint8_t> Bytes = arrayRefFromStringRef(BytesStr);
7436     uint64_t SectAddress = Sections[SectIdx].getAddress();
7437 
7438     bool symbolTableWorked = false;
7439 
7440     // Create a map of symbol addresses to symbol names for use by
7441     // the SymbolizerSymbolLookUp() routine.
7442     SymbolAddressMap AddrMap;
7443     bool DisSymNameFound = false;
7444     for (const SymbolRef &Symbol : MachOOF->symbols()) {
7445       SymbolRef::Type ST =
7446           unwrapOrError(Symbol.getType(), MachOOF->getFileName());
7447       if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
7448           ST == SymbolRef::ST_Other) {
7449         uint64_t Address = Symbol.getValue();
7450         StringRef SymName =
7451             unwrapOrError(Symbol.getName(), MachOOF->getFileName());
7452         AddrMap[Address] = SymName;
7453         if (!DisSymName.empty() && DisSymName == SymName)
7454           DisSymNameFound = true;
7455       }
7456     }
7457     if (!DisSymName.empty() && !DisSymNameFound) {
7458       outs() << "Can't find -dis-symname: " << DisSymName << "\n";
7459       return;
7460     }
7461     // Set up the block of info used by the Symbolizer call backs.
7462     SymbolizerInfo.verbose = !NoSymbolicOperands;
7463     SymbolizerInfo.O = MachOOF;
7464     SymbolizerInfo.S = Sections[SectIdx];
7465     SymbolizerInfo.AddrMap = &AddrMap;
7466     SymbolizerInfo.Sections = &Sections;
7467     // Same for the ThumbSymbolizer
7468     ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
7469     ThumbSymbolizerInfo.O = MachOOF;
7470     ThumbSymbolizerInfo.S = Sections[SectIdx];
7471     ThumbSymbolizerInfo.AddrMap = &AddrMap;
7472     ThumbSymbolizerInfo.Sections = &Sections;
7473 
7474     unsigned int Arch = MachOOF->getArch();
7475 
7476     // Skip all symbols if this is a stubs file.
7477     if (Bytes.empty())
7478       return;
7479 
7480     // If the section has symbols but no symbol at the start of the section
7481     // these are used to make sure the bytes before the first symbol are
7482     // disassembled.
7483     bool FirstSymbol = true;
7484     bool FirstSymbolAtSectionStart = true;
7485 
7486     // Disassemble symbol by symbol.
7487     for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
7488       StringRef SymName =
7489           unwrapOrError(Symbols[SymIdx].getName(), MachOOF->getFileName());
7490       SymbolRef::Type ST =
7491           unwrapOrError(Symbols[SymIdx].getType(), MachOOF->getFileName());
7492       if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
7493         continue;
7494 
7495       // Make sure the symbol is defined in this section.
7496       bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
7497       if (!containsSym) {
7498         if (!DisSymName.empty() && DisSymName == SymName) {
7499           outs() << "-dis-symname: " << DisSymName << " not in the section\n";
7500           return;
7501         }
7502         continue;
7503       }
7504       // The __mh_execute_header is special and we need to deal with that fact
7505       // this symbol is before the start of the (__TEXT,__text) section and at the
7506       // address of the start of the __TEXT segment.  This is because this symbol
7507       // is an N_SECT symbol in the (__TEXT,__text) but its address is before the
7508       // start of the section in a standard MH_EXECUTE filetype.
7509       if (!DisSymName.empty() && DisSymName == "__mh_execute_header") {
7510         outs() << "-dis-symname: __mh_execute_header not in any section\n";
7511         return;
7512       }
7513       // When this code is trying to disassemble a symbol at a time and in the
7514       // case there is only the __mh_execute_header symbol left as in a stripped
7515       // executable, we need to deal with this by ignoring this symbol so the
7516       // whole section is disassembled and this symbol is then not displayed.
7517       if (SymName == "__mh_execute_header" || SymName == "__mh_dylib_header" ||
7518           SymName == "__mh_bundle_header" || SymName == "__mh_object_header" ||
7519           SymName == "__mh_preload_header" || SymName == "__mh_dylinker_header")
7520         continue;
7521 
7522       // If we are only disassembling one symbol see if this is that symbol.
7523       if (!DisSymName.empty() && DisSymName != SymName)
7524         continue;
7525 
7526       // Start at the address of the symbol relative to the section's address.
7527       uint64_t SectSize = Sections[SectIdx].getSize();
7528       uint64_t Start = Symbols[SymIdx].getValue();
7529       uint64_t SectionAddress = Sections[SectIdx].getAddress();
7530       Start -= SectionAddress;
7531 
7532       if (Start > SectSize) {
7533         outs() << "section data ends, " << SymName
7534                << " lies outside valid range\n";
7535         return;
7536       }
7537 
7538       // Stop disassembling either at the beginning of the next symbol or at
7539       // the end of the section.
7540       bool containsNextSym = false;
7541       uint64_t NextSym = 0;
7542       uint64_t NextSymIdx = SymIdx + 1;
7543       while (Symbols.size() > NextSymIdx) {
7544         SymbolRef::Type NextSymType = unwrapOrError(
7545             Symbols[NextSymIdx].getType(), MachOOF->getFileName());
7546         if (NextSymType == SymbolRef::ST_Function) {
7547           containsNextSym =
7548               Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
7549           NextSym = Symbols[NextSymIdx].getValue();
7550           NextSym -= SectionAddress;
7551           break;
7552         }
7553         ++NextSymIdx;
7554       }
7555 
7556       uint64_t End = containsNextSym ? std::min(NextSym, SectSize) : SectSize;
7557       uint64_t Size;
7558 
7559       symbolTableWorked = true;
7560 
7561       DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
7562       bool IsThumb = MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb;
7563 
7564       // We only need the dedicated Thumb target if there's a real choice
7565       // (i.e. we're not targeting M-class) and the function is Thumb.
7566       bool UseThumbTarget = IsThumb && ThumbTarget;
7567 
7568       // If we are not specifying a symbol to start disassembly with and this
7569       // is the first symbol in the section but not at the start of the section
7570       // then move the disassembly index to the start of the section and
7571       // don't print the symbol name just yet.  This is so the bytes before the
7572       // first symbol are disassembled.
7573       uint64_t SymbolStart = Start;
7574       if (DisSymName.empty() && FirstSymbol && Start != 0) {
7575         FirstSymbolAtSectionStart = false;
7576         Start = 0;
7577       }
7578       else
7579         outs() << SymName << ":\n";
7580 
7581       DILineInfo lastLine;
7582       for (uint64_t Index = Start; Index < End; Index += Size) {
7583         MCInst Inst;
7584 
7585         // If this is the first symbol in the section and it was not at the
7586         // start of the section, see if we are at its Index now and if so print
7587         // the symbol name.
7588         if (FirstSymbol && !FirstSymbolAtSectionStart && Index == SymbolStart)
7589           outs() << SymName << ":\n";
7590 
7591         uint64_t PC = SectAddress + Index;
7592         if (!NoLeadingAddr) {
7593           if (FullLeadingAddr) {
7594             if (MachOOF->is64Bit())
7595               outs() << format("%016" PRIx64, PC);
7596             else
7597               outs() << format("%08" PRIx64, PC);
7598           } else {
7599             outs() << format("%8" PRIx64 ":", PC);
7600           }
7601         }
7602         if (!NoShowRawInsn || Arch == Triple::arm)
7603           outs() << "\t";
7604 
7605         if (DumpAndSkipDataInCode(PC, Bytes.data() + Index, Dices, Size))
7606           continue;
7607 
7608         SmallVector<char, 64> AnnotationsBytes;
7609         raw_svector_ostream Annotations(AnnotationsBytes);
7610 
7611         bool gotInst;
7612         if (UseThumbTarget)
7613           gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
7614                                                 PC, Annotations);
7615         else
7616           gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
7617                                            Annotations);
7618         if (gotInst) {
7619           if (!NoShowRawInsn || Arch == Triple::arm) {
7620             dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
7621           }
7622           formatted_raw_ostream FormattedOS(outs());
7623           StringRef AnnotationsStr = Annotations.str();
7624           if (UseThumbTarget)
7625             ThumbIP->printInst(&Inst, PC, AnnotationsStr, *ThumbSTI,
7626                                FormattedOS);
7627           else
7628             IP->printInst(&Inst, PC, AnnotationsStr, *STI, FormattedOS);
7629           emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
7630 
7631           // Print debug info.
7632           if (diContext) {
7633             DILineInfo dli = diContext->getLineInfoForAddress({PC, SectIdx});
7634             // Print valid line info if it changed.
7635             if (dli != lastLine && dli.Line != 0)
7636               outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
7637                      << dli.Column;
7638             lastLine = dli;
7639           }
7640           outs() << "\n";
7641         } else {
7642           if (MachOOF->getArchTriple().isX86()) {
7643             outs() << format("\t.byte 0x%02x #bad opcode\n",
7644                              *(Bytes.data() + Index) & 0xff);
7645             Size = 1; // skip exactly one illegible byte and move on.
7646           } else if (Arch == Triple::aarch64 ||
7647                      (Arch == Triple::arm && !IsThumb)) {
7648             uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7649                               (*(Bytes.data() + Index + 1) & 0xff) << 8 |
7650                               (*(Bytes.data() + Index + 2) & 0xff) << 16 |
7651                               (*(Bytes.data() + Index + 3) & 0xff) << 24;
7652             outs() << format("\t.long\t0x%08x\n", opcode);
7653             Size = 4;
7654           } else if (Arch == Triple::arm) {
7655             assert(IsThumb && "ARM mode should have been dealt with above");
7656             uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7657                               (*(Bytes.data() + Index + 1) & 0xff) << 8;
7658             outs() << format("\t.short\t0x%04x\n", opcode);
7659             Size = 2;
7660           } else{
7661             WithColor::warning(errs(), "llvm-objdump")
7662                 << "invalid instruction encoding\n";
7663             if (Size == 0)
7664               Size = 1; // skip illegible bytes
7665           }
7666         }
7667       }
7668       // Now that we are done disassembled the first symbol set the bool that
7669       // were doing this to false.
7670       FirstSymbol = false;
7671     }
7672     if (!symbolTableWorked) {
7673       // Reading the symbol table didn't work, disassemble the whole section.
7674       uint64_t SectAddress = Sections[SectIdx].getAddress();
7675       uint64_t SectSize = Sections[SectIdx].getSize();
7676       uint64_t InstSize;
7677       for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
7678         MCInst Inst;
7679 
7680         uint64_t PC = SectAddress + Index;
7681 
7682         if (DumpAndSkipDataInCode(PC, Bytes.data() + Index, Dices, InstSize))
7683           continue;
7684 
7685         SmallVector<char, 64> AnnotationsBytes;
7686         raw_svector_ostream Annotations(AnnotationsBytes);
7687         if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
7688                                    Annotations)) {
7689           if (!NoLeadingAddr) {
7690             if (FullLeadingAddr) {
7691               if (MachOOF->is64Bit())
7692                 outs() << format("%016" PRIx64, PC);
7693               else
7694                 outs() << format("%08" PRIx64, PC);
7695             } else {
7696               outs() << format("%8" PRIx64 ":", PC);
7697             }
7698           }
7699           if (!NoShowRawInsn || Arch == Triple::arm) {
7700             outs() << "\t";
7701             dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
7702           }
7703           StringRef AnnotationsStr = Annotations.str();
7704           IP->printInst(&Inst, PC, AnnotationsStr, *STI, outs());
7705           outs() << "\n";
7706         } else {
7707           if (MachOOF->getArchTriple().isX86()) {
7708             outs() << format("\t.byte 0x%02x #bad opcode\n",
7709                              *(Bytes.data() + Index) & 0xff);
7710             InstSize = 1; // skip exactly one illegible byte and move on.
7711           } else {
7712             WithColor::warning(errs(), "llvm-objdump")
7713                 << "invalid instruction encoding\n";
7714             if (InstSize == 0)
7715               InstSize = 1; // skip illegible bytes
7716           }
7717         }
7718       }
7719     }
7720     // The TripleName's need to be reset if we are called again for a different
7721     // architecture.
7722     TripleName = "";
7723     ThumbTripleName = "";
7724 
7725     if (SymbolizerInfo.demangled_name != nullptr)
7726       free(SymbolizerInfo.demangled_name);
7727     if (ThumbSymbolizerInfo.demangled_name != nullptr)
7728       free(ThumbSymbolizerInfo.demangled_name);
7729   }
7730 }
7731 
7732 //===----------------------------------------------------------------------===//
7733 // __compact_unwind section dumping
7734 //===----------------------------------------------------------------------===//
7735 
7736 namespace {
7737 
7738 template <typename T>
7739 static uint64_t read(StringRef Contents, ptrdiff_t Offset) {
7740   using llvm::support::little;
7741   using llvm::support::unaligned;
7742 
7743   if (Offset + sizeof(T) > Contents.size()) {
7744     outs() << "warning: attempt to read past end of buffer\n";
7745     return T();
7746   }
7747 
7748   uint64_t Val =
7749       support::endian::read<T, little, unaligned>(Contents.data() + Offset);
7750   return Val;
7751 }
7752 
7753 template <typename T>
7754 static uint64_t readNext(StringRef Contents, ptrdiff_t &Offset) {
7755   T Val = read<T>(Contents, Offset);
7756   Offset += sizeof(T);
7757   return Val;
7758 }
7759 
7760 struct CompactUnwindEntry {
7761   uint32_t OffsetInSection;
7762 
7763   uint64_t FunctionAddr;
7764   uint32_t Length;
7765   uint32_t CompactEncoding;
7766   uint64_t PersonalityAddr;
7767   uint64_t LSDAAddr;
7768 
7769   RelocationRef FunctionReloc;
7770   RelocationRef PersonalityReloc;
7771   RelocationRef LSDAReloc;
7772 
7773   CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
7774       : OffsetInSection(Offset) {
7775     if (Is64)
7776       read<uint64_t>(Contents, Offset);
7777     else
7778       read<uint32_t>(Contents, Offset);
7779   }
7780 
7781 private:
7782   template <typename UIntPtr> void read(StringRef Contents, ptrdiff_t Offset) {
7783     FunctionAddr = readNext<UIntPtr>(Contents, Offset);
7784     Length = readNext<uint32_t>(Contents, Offset);
7785     CompactEncoding = readNext<uint32_t>(Contents, Offset);
7786     PersonalityAddr = readNext<UIntPtr>(Contents, Offset);
7787     LSDAAddr = readNext<UIntPtr>(Contents, Offset);
7788   }
7789 };
7790 }
7791 
7792 /// Given a relocation from __compact_unwind, consisting of the RelocationRef
7793 /// and data being relocated, determine the best base Name and Addend to use for
7794 /// display purposes.
7795 ///
7796 /// 1. An Extern relocation will directly reference a symbol (and the data is
7797 ///    then already an addend), so use that.
7798 /// 2. Otherwise the data is an offset in the object file's layout; try to find
7799 //     a symbol before it in the same section, and use the offset from there.
7800 /// 3. Finally, if all that fails, fall back to an offset from the start of the
7801 ///    referenced section.
7802 static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
7803                                       std::map<uint64_t, SymbolRef> &Symbols,
7804                                       const RelocationRef &Reloc, uint64_t Addr,
7805                                       StringRef &Name, uint64_t &Addend) {
7806   if (Reloc.getSymbol() != Obj->symbol_end()) {
7807     Name = unwrapOrError(Reloc.getSymbol()->getName(), Obj->getFileName());
7808     Addend = Addr;
7809     return;
7810   }
7811 
7812   auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
7813   SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
7814 
7815   uint64_t SectionAddr = RelocSection.getAddress();
7816 
7817   auto Sym = Symbols.upper_bound(Addr);
7818   if (Sym == Symbols.begin()) {
7819     // The first symbol in the object is after this reference, the best we can
7820     // do is section-relative notation.
7821     if (Expected<StringRef> NameOrErr = RelocSection.getName())
7822       Name = *NameOrErr;
7823     else
7824       consumeError(NameOrErr.takeError());
7825 
7826     Addend = Addr - SectionAddr;
7827     return;
7828   }
7829 
7830   // Go back one so that SymbolAddress <= Addr.
7831   --Sym;
7832 
7833   section_iterator SymSection =
7834       unwrapOrError(Sym->second.getSection(), Obj->getFileName());
7835   if (RelocSection == *SymSection) {
7836     // There's a valid symbol in the same section before this reference.
7837     Name = unwrapOrError(Sym->second.getName(), Obj->getFileName());
7838     Addend = Addr - Sym->first;
7839     return;
7840   }
7841 
7842   // There is a symbol before this reference, but it's in a different
7843   // section. Probably not helpful to mention it, so use the section name.
7844   if (Expected<StringRef> NameOrErr = RelocSection.getName())
7845     Name = *NameOrErr;
7846   else
7847     consumeError(NameOrErr.takeError());
7848 
7849   Addend = Addr - SectionAddr;
7850 }
7851 
7852 static void printUnwindRelocDest(const MachOObjectFile *Obj,
7853                                  std::map<uint64_t, SymbolRef> &Symbols,
7854                                  const RelocationRef &Reloc, uint64_t Addr) {
7855   StringRef Name;
7856   uint64_t Addend;
7857 
7858   if (!Reloc.getObject())
7859     return;
7860 
7861   findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
7862 
7863   outs() << Name;
7864   if (Addend)
7865     outs() << " + " << format("0x%" PRIx64, Addend);
7866 }
7867 
7868 static void
7869 printMachOCompactUnwindSection(const MachOObjectFile *Obj,
7870                                std::map<uint64_t, SymbolRef> &Symbols,
7871                                const SectionRef &CompactUnwind) {
7872 
7873   if (!Obj->isLittleEndian()) {
7874     outs() << "Skipping big-endian __compact_unwind section\n";
7875     return;
7876   }
7877 
7878   bool Is64 = Obj->is64Bit();
7879   uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
7880   uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
7881 
7882   StringRef Contents =
7883       unwrapOrError(CompactUnwind.getContents(), Obj->getFileName());
7884   SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
7885 
7886   // First populate the initial raw offsets, encodings and so on from the entry.
7887   for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
7888     CompactUnwindEntry Entry(Contents, Offset, Is64);
7889     CompactUnwinds.push_back(Entry);
7890   }
7891 
7892   // Next we need to look at the relocations to find out what objects are
7893   // actually being referred to.
7894   for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
7895     uint64_t RelocAddress = Reloc.getOffset();
7896 
7897     uint32_t EntryIdx = RelocAddress / EntrySize;
7898     uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
7899     CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
7900 
7901     if (OffsetInEntry == 0)
7902       Entry.FunctionReloc = Reloc;
7903     else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
7904       Entry.PersonalityReloc = Reloc;
7905     else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
7906       Entry.LSDAReloc = Reloc;
7907     else {
7908       outs() << "Invalid relocation in __compact_unwind section\n";
7909       return;
7910     }
7911   }
7912 
7913   // Finally, we're ready to print the data we've gathered.
7914   outs() << "Contents of __compact_unwind section:\n";
7915   for (auto &Entry : CompactUnwinds) {
7916     outs() << "  Entry at offset "
7917            << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
7918 
7919     // 1. Start of the region this entry applies to.
7920     outs() << "    start:                " << format("0x%" PRIx64,
7921                                                      Entry.FunctionAddr) << ' ';
7922     printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
7923     outs() << '\n';
7924 
7925     // 2. Length of the region this entry applies to.
7926     outs() << "    length:               " << format("0x%" PRIx32, Entry.Length)
7927            << '\n';
7928     // 3. The 32-bit compact encoding.
7929     outs() << "    compact encoding:     "
7930            << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
7931 
7932     // 4. The personality function, if present.
7933     if (Entry.PersonalityReloc.getObject()) {
7934       outs() << "    personality function: "
7935              << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
7936       printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
7937                            Entry.PersonalityAddr);
7938       outs() << '\n';
7939     }
7940 
7941     // 5. This entry's language-specific data area.
7942     if (Entry.LSDAReloc.getObject()) {
7943       outs() << "    LSDA:                 " << format("0x%" PRIx64,
7944                                                        Entry.LSDAAddr) << ' ';
7945       printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
7946       outs() << '\n';
7947     }
7948   }
7949 }
7950 
7951 //===----------------------------------------------------------------------===//
7952 // __unwind_info section dumping
7953 //===----------------------------------------------------------------------===//
7954 
7955 static void printRegularSecondLevelUnwindPage(StringRef PageData) {
7956   ptrdiff_t Pos = 0;
7957   uint32_t Kind = readNext<uint32_t>(PageData, Pos);
7958   (void)Kind;
7959   assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
7960 
7961   uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
7962   uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
7963 
7964   Pos = EntriesStart;
7965   for (unsigned i = 0; i < NumEntries; ++i) {
7966     uint32_t FunctionOffset = readNext<uint32_t>(PageData, Pos);
7967     uint32_t Encoding = readNext<uint32_t>(PageData, Pos);
7968 
7969     outs() << "      [" << i << "]: "
7970            << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7971            << ", "
7972            << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
7973   }
7974 }
7975 
7976 static void printCompressedSecondLevelUnwindPage(
7977     StringRef PageData, uint32_t FunctionBase,
7978     const SmallVectorImpl<uint32_t> &CommonEncodings) {
7979   ptrdiff_t Pos = 0;
7980   uint32_t Kind = readNext<uint32_t>(PageData, Pos);
7981   (void)Kind;
7982   assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
7983 
7984   uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
7985   uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
7986 
7987   uint16_t EncodingsStart = readNext<uint16_t>(PageData, Pos);
7988   readNext<uint16_t>(PageData, Pos);
7989   StringRef PageEncodings = PageData.substr(EncodingsStart, StringRef::npos);
7990 
7991   Pos = EntriesStart;
7992   for (unsigned i = 0; i < NumEntries; ++i) {
7993     uint32_t Entry = readNext<uint32_t>(PageData, Pos);
7994     uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
7995     uint32_t EncodingIdx = Entry >> 24;
7996 
7997     uint32_t Encoding;
7998     if (EncodingIdx < CommonEncodings.size())
7999       Encoding = CommonEncodings[EncodingIdx];
8000     else
8001       Encoding = read<uint32_t>(PageEncodings,
8002                                 sizeof(uint32_t) *
8003                                     (EncodingIdx - CommonEncodings.size()));
8004 
8005     outs() << "      [" << i << "]: "
8006            << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
8007            << ", "
8008            << "encoding[" << EncodingIdx
8009            << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
8010   }
8011 }
8012 
8013 static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
8014                                         std::map<uint64_t, SymbolRef> &Symbols,
8015                                         const SectionRef &UnwindInfo) {
8016 
8017   if (!Obj->isLittleEndian()) {
8018     outs() << "Skipping big-endian __unwind_info section\n";
8019     return;
8020   }
8021 
8022   outs() << "Contents of __unwind_info section:\n";
8023 
8024   StringRef Contents =
8025       unwrapOrError(UnwindInfo.getContents(), Obj->getFileName());
8026   ptrdiff_t Pos = 0;
8027 
8028   //===----------------------------------
8029   // Section header
8030   //===----------------------------------
8031 
8032   uint32_t Version = readNext<uint32_t>(Contents, Pos);
8033   outs() << "  Version:                                   "
8034          << format("0x%" PRIx32, Version) << '\n';
8035   if (Version != 1) {
8036     outs() << "    Skipping section with unknown version\n";
8037     return;
8038   }
8039 
8040   uint32_t CommonEncodingsStart = readNext<uint32_t>(Contents, Pos);
8041   outs() << "  Common encodings array section offset:     "
8042          << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
8043   uint32_t NumCommonEncodings = readNext<uint32_t>(Contents, Pos);
8044   outs() << "  Number of common encodings in array:       "
8045          << format("0x%" PRIx32, NumCommonEncodings) << '\n';
8046 
8047   uint32_t PersonalitiesStart = readNext<uint32_t>(Contents, Pos);
8048   outs() << "  Personality function array section offset: "
8049          << format("0x%" PRIx32, PersonalitiesStart) << '\n';
8050   uint32_t NumPersonalities = readNext<uint32_t>(Contents, Pos);
8051   outs() << "  Number of personality functions in array:  "
8052          << format("0x%" PRIx32, NumPersonalities) << '\n';
8053 
8054   uint32_t IndicesStart = readNext<uint32_t>(Contents, Pos);
8055   outs() << "  Index array section offset:                "
8056          << format("0x%" PRIx32, IndicesStart) << '\n';
8057   uint32_t NumIndices = readNext<uint32_t>(Contents, Pos);
8058   outs() << "  Number of indices in array:                "
8059          << format("0x%" PRIx32, NumIndices) << '\n';
8060 
8061   //===----------------------------------
8062   // A shared list of common encodings
8063   //===----------------------------------
8064 
8065   // These occupy indices in the range [0, N] whenever an encoding is referenced
8066   // from a compressed 2nd level index table. In practice the linker only
8067   // creates ~128 of these, so that indices are available to embed encodings in
8068   // the 2nd level index.
8069 
8070   SmallVector<uint32_t, 64> CommonEncodings;
8071   outs() << "  Common encodings: (count = " << NumCommonEncodings << ")\n";
8072   Pos = CommonEncodingsStart;
8073   for (unsigned i = 0; i < NumCommonEncodings; ++i) {
8074     uint32_t Encoding = readNext<uint32_t>(Contents, Pos);
8075     CommonEncodings.push_back(Encoding);
8076 
8077     outs() << "    encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
8078            << '\n';
8079   }
8080 
8081   //===----------------------------------
8082   // Personality functions used in this executable
8083   //===----------------------------------
8084 
8085   // There should be only a handful of these (one per source language,
8086   // roughly). Particularly since they only get 2 bits in the compact encoding.
8087 
8088   outs() << "  Personality functions: (count = " << NumPersonalities << ")\n";
8089   Pos = PersonalitiesStart;
8090   for (unsigned i = 0; i < NumPersonalities; ++i) {
8091     uint32_t PersonalityFn = readNext<uint32_t>(Contents, Pos);
8092     outs() << "    personality[" << i + 1
8093            << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
8094   }
8095 
8096   //===----------------------------------
8097   // The level 1 index entries
8098   //===----------------------------------
8099 
8100   // These specify an approximate place to start searching for the more detailed
8101   // information, sorted by PC.
8102 
8103   struct IndexEntry {
8104     uint32_t FunctionOffset;
8105     uint32_t SecondLevelPageStart;
8106     uint32_t LSDAStart;
8107   };
8108 
8109   SmallVector<IndexEntry, 4> IndexEntries;
8110 
8111   outs() << "  Top level indices: (count = " << NumIndices << ")\n";
8112   Pos = IndicesStart;
8113   for (unsigned i = 0; i < NumIndices; ++i) {
8114     IndexEntry Entry;
8115 
8116     Entry.FunctionOffset = readNext<uint32_t>(Contents, Pos);
8117     Entry.SecondLevelPageStart = readNext<uint32_t>(Contents, Pos);
8118     Entry.LSDAStart = readNext<uint32_t>(Contents, Pos);
8119     IndexEntries.push_back(Entry);
8120 
8121     outs() << "    [" << i << "]: "
8122            << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
8123            << ", "
8124            << "2nd level page offset="
8125            << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
8126            << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
8127   }
8128 
8129   //===----------------------------------
8130   // Next come the LSDA tables
8131   //===----------------------------------
8132 
8133   // The LSDA layout is rather implicit: it's a contiguous array of entries from
8134   // the first top-level index's LSDAOffset to the last (sentinel).
8135 
8136   outs() << "  LSDA descriptors:\n";
8137   Pos = IndexEntries[0].LSDAStart;
8138   const uint32_t LSDASize = 2 * sizeof(uint32_t);
8139   int NumLSDAs =
8140       (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) / LSDASize;
8141 
8142   for (int i = 0; i < NumLSDAs; ++i) {
8143     uint32_t FunctionOffset = readNext<uint32_t>(Contents, Pos);
8144     uint32_t LSDAOffset = readNext<uint32_t>(Contents, Pos);
8145     outs() << "    [" << i << "]: "
8146            << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
8147            << ", "
8148            << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
8149   }
8150 
8151   //===----------------------------------
8152   // Finally, the 2nd level indices
8153   //===----------------------------------
8154 
8155   // Generally these are 4K in size, and have 2 possible forms:
8156   //   + Regular stores up to 511 entries with disparate encodings
8157   //   + Compressed stores up to 1021 entries if few enough compact encoding
8158   //     values are used.
8159   outs() << "  Second level indices:\n";
8160   for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
8161     // The final sentinel top-level index has no associated 2nd level page
8162     if (IndexEntries[i].SecondLevelPageStart == 0)
8163       break;
8164 
8165     outs() << "    Second level index[" << i << "]: "
8166            << "offset in section="
8167            << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
8168            << ", "
8169            << "base function offset="
8170            << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
8171 
8172     Pos = IndexEntries[i].SecondLevelPageStart;
8173     if (Pos + sizeof(uint32_t) > Contents.size()) {
8174       outs() << "warning: invalid offset for second level page: " << Pos << '\n';
8175       continue;
8176     }
8177 
8178     uint32_t Kind =
8179         *reinterpret_cast<const support::ulittle32_t *>(Contents.data() + Pos);
8180     if (Kind == 2)
8181       printRegularSecondLevelUnwindPage(Contents.substr(Pos, 4096));
8182     else if (Kind == 3)
8183       printCompressedSecondLevelUnwindPage(Contents.substr(Pos, 4096),
8184                                            IndexEntries[i].FunctionOffset,
8185                                            CommonEncodings);
8186     else
8187       outs() << "    Skipping 2nd level page with unknown kind " << Kind
8188              << '\n';
8189   }
8190 }
8191 
8192 void printMachOUnwindInfo(const MachOObjectFile *Obj) {
8193   std::map<uint64_t, SymbolRef> Symbols;
8194   for (const SymbolRef &SymRef : Obj->symbols()) {
8195     // Discard any undefined or absolute symbols. They're not going to take part
8196     // in the convenience lookup for unwind info and just take up resources.
8197     auto SectOrErr = SymRef.getSection();
8198     if (!SectOrErr) {
8199       // TODO: Actually report errors helpfully.
8200       consumeError(SectOrErr.takeError());
8201       continue;
8202     }
8203     section_iterator Section = *SectOrErr;
8204     if (Section == Obj->section_end())
8205       continue;
8206 
8207     uint64_t Addr = SymRef.getValue();
8208     Symbols.insert(std::make_pair(Addr, SymRef));
8209   }
8210 
8211   for (const SectionRef &Section : Obj->sections()) {
8212     StringRef SectName;
8213     if (Expected<StringRef> NameOrErr = Section.getName())
8214       SectName = *NameOrErr;
8215     else
8216       consumeError(NameOrErr.takeError());
8217 
8218     if (SectName == "__compact_unwind")
8219       printMachOCompactUnwindSection(Obj, Symbols, Section);
8220     else if (SectName == "__unwind_info")
8221       printMachOUnwindInfoSection(Obj, Symbols, Section);
8222   }
8223 }
8224 
8225 static void PrintMachHeader(uint32_t magic, uint32_t cputype,
8226                             uint32_t cpusubtype, uint32_t filetype,
8227                             uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
8228                             bool verbose) {
8229   outs() << "Mach header\n";
8230   outs() << "      magic cputype cpusubtype  caps    filetype ncmds "
8231             "sizeofcmds      flags\n";
8232   if (verbose) {
8233     if (magic == MachO::MH_MAGIC)
8234       outs() << "   MH_MAGIC";
8235     else if (magic == MachO::MH_MAGIC_64)
8236       outs() << "MH_MAGIC_64";
8237     else
8238       outs() << format(" 0x%08" PRIx32, magic);
8239     switch (cputype) {
8240     case MachO::CPU_TYPE_I386:
8241       outs() << "    I386";
8242       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8243       case MachO::CPU_SUBTYPE_I386_ALL:
8244         outs() << "        ALL";
8245         break;
8246       default:
8247         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8248         break;
8249       }
8250       break;
8251     case MachO::CPU_TYPE_X86_64:
8252       outs() << "  X86_64";
8253       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8254       case MachO::CPU_SUBTYPE_X86_64_ALL:
8255         outs() << "        ALL";
8256         break;
8257       case MachO::CPU_SUBTYPE_X86_64_H:
8258         outs() << "    Haswell";
8259         break;
8260       default:
8261         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8262         break;
8263       }
8264       break;
8265     case MachO::CPU_TYPE_ARM:
8266       outs() << "     ARM";
8267       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8268       case MachO::CPU_SUBTYPE_ARM_ALL:
8269         outs() << "        ALL";
8270         break;
8271       case MachO::CPU_SUBTYPE_ARM_V4T:
8272         outs() << "        V4T";
8273         break;
8274       case MachO::CPU_SUBTYPE_ARM_V5TEJ:
8275         outs() << "      V5TEJ";
8276         break;
8277       case MachO::CPU_SUBTYPE_ARM_XSCALE:
8278         outs() << "     XSCALE";
8279         break;
8280       case MachO::CPU_SUBTYPE_ARM_V6:
8281         outs() << "         V6";
8282         break;
8283       case MachO::CPU_SUBTYPE_ARM_V6M:
8284         outs() << "        V6M";
8285         break;
8286       case MachO::CPU_SUBTYPE_ARM_V7:
8287         outs() << "         V7";
8288         break;
8289       case MachO::CPU_SUBTYPE_ARM_V7EM:
8290         outs() << "       V7EM";
8291         break;
8292       case MachO::CPU_SUBTYPE_ARM_V7K:
8293         outs() << "        V7K";
8294         break;
8295       case MachO::CPU_SUBTYPE_ARM_V7M:
8296         outs() << "        V7M";
8297         break;
8298       case MachO::CPU_SUBTYPE_ARM_V7S:
8299         outs() << "        V7S";
8300         break;
8301       default:
8302         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8303         break;
8304       }
8305       break;
8306     case MachO::CPU_TYPE_ARM64:
8307       outs() << "   ARM64";
8308       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8309       case MachO::CPU_SUBTYPE_ARM64_ALL:
8310         outs() << "        ALL";
8311         break;
8312       case MachO::CPU_SUBTYPE_ARM64E:
8313         outs() << "          E";
8314         break;
8315       default:
8316         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8317         break;
8318       }
8319       break;
8320     case MachO::CPU_TYPE_ARM64_32:
8321       outs() << " ARM64_32";
8322       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8323       case MachO::CPU_SUBTYPE_ARM64_32_V8:
8324         outs() << "        V8";
8325         break;
8326       default:
8327         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8328         break;
8329       }
8330       break;
8331     case MachO::CPU_TYPE_POWERPC:
8332       outs() << "     PPC";
8333       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8334       case MachO::CPU_SUBTYPE_POWERPC_ALL:
8335         outs() << "        ALL";
8336         break;
8337       default:
8338         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8339         break;
8340       }
8341       break;
8342     case MachO::CPU_TYPE_POWERPC64:
8343       outs() << "   PPC64";
8344       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8345       case MachO::CPU_SUBTYPE_POWERPC_ALL:
8346         outs() << "        ALL";
8347         break;
8348       default:
8349         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8350         break;
8351       }
8352       break;
8353     default:
8354       outs() << format(" %7d", cputype);
8355       outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8356       break;
8357     }
8358     if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
8359       outs() << " LIB64";
8360     } else {
8361       outs() << format("  0x%02" PRIx32,
8362                        (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
8363     }
8364     switch (filetype) {
8365     case MachO::MH_OBJECT:
8366       outs() << "      OBJECT";
8367       break;
8368     case MachO::MH_EXECUTE:
8369       outs() << "     EXECUTE";
8370       break;
8371     case MachO::MH_FVMLIB:
8372       outs() << "      FVMLIB";
8373       break;
8374     case MachO::MH_CORE:
8375       outs() << "        CORE";
8376       break;
8377     case MachO::MH_PRELOAD:
8378       outs() << "     PRELOAD";
8379       break;
8380     case MachO::MH_DYLIB:
8381       outs() << "       DYLIB";
8382       break;
8383     case MachO::MH_DYLIB_STUB:
8384       outs() << "  DYLIB_STUB";
8385       break;
8386     case MachO::MH_DYLINKER:
8387       outs() << "    DYLINKER";
8388       break;
8389     case MachO::MH_BUNDLE:
8390       outs() << "      BUNDLE";
8391       break;
8392     case MachO::MH_DSYM:
8393       outs() << "        DSYM";
8394       break;
8395     case MachO::MH_KEXT_BUNDLE:
8396       outs() << "  KEXTBUNDLE";
8397       break;
8398     default:
8399       outs() << format("  %10u", filetype);
8400       break;
8401     }
8402     outs() << format(" %5u", ncmds);
8403     outs() << format(" %10u", sizeofcmds);
8404     uint32_t f = flags;
8405     if (f & MachO::MH_NOUNDEFS) {
8406       outs() << "   NOUNDEFS";
8407       f &= ~MachO::MH_NOUNDEFS;
8408     }
8409     if (f & MachO::MH_INCRLINK) {
8410       outs() << " INCRLINK";
8411       f &= ~MachO::MH_INCRLINK;
8412     }
8413     if (f & MachO::MH_DYLDLINK) {
8414       outs() << " DYLDLINK";
8415       f &= ~MachO::MH_DYLDLINK;
8416     }
8417     if (f & MachO::MH_BINDATLOAD) {
8418       outs() << " BINDATLOAD";
8419       f &= ~MachO::MH_BINDATLOAD;
8420     }
8421     if (f & MachO::MH_PREBOUND) {
8422       outs() << " PREBOUND";
8423       f &= ~MachO::MH_PREBOUND;
8424     }
8425     if (f & MachO::MH_SPLIT_SEGS) {
8426       outs() << " SPLIT_SEGS";
8427       f &= ~MachO::MH_SPLIT_SEGS;
8428     }
8429     if (f & MachO::MH_LAZY_INIT) {
8430       outs() << " LAZY_INIT";
8431       f &= ~MachO::MH_LAZY_INIT;
8432     }
8433     if (f & MachO::MH_TWOLEVEL) {
8434       outs() << " TWOLEVEL";
8435       f &= ~MachO::MH_TWOLEVEL;
8436     }
8437     if (f & MachO::MH_FORCE_FLAT) {
8438       outs() << " FORCE_FLAT";
8439       f &= ~MachO::MH_FORCE_FLAT;
8440     }
8441     if (f & MachO::MH_NOMULTIDEFS) {
8442       outs() << " NOMULTIDEFS";
8443       f &= ~MachO::MH_NOMULTIDEFS;
8444     }
8445     if (f & MachO::MH_NOFIXPREBINDING) {
8446       outs() << " NOFIXPREBINDING";
8447       f &= ~MachO::MH_NOFIXPREBINDING;
8448     }
8449     if (f & MachO::MH_PREBINDABLE) {
8450       outs() << " PREBINDABLE";
8451       f &= ~MachO::MH_PREBINDABLE;
8452     }
8453     if (f & MachO::MH_ALLMODSBOUND) {
8454       outs() << " ALLMODSBOUND";
8455       f &= ~MachO::MH_ALLMODSBOUND;
8456     }
8457     if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
8458       outs() << " SUBSECTIONS_VIA_SYMBOLS";
8459       f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
8460     }
8461     if (f & MachO::MH_CANONICAL) {
8462       outs() << " CANONICAL";
8463       f &= ~MachO::MH_CANONICAL;
8464     }
8465     if (f & MachO::MH_WEAK_DEFINES) {
8466       outs() << " WEAK_DEFINES";
8467       f &= ~MachO::MH_WEAK_DEFINES;
8468     }
8469     if (f & MachO::MH_BINDS_TO_WEAK) {
8470       outs() << " BINDS_TO_WEAK";
8471       f &= ~MachO::MH_BINDS_TO_WEAK;
8472     }
8473     if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
8474       outs() << " ALLOW_STACK_EXECUTION";
8475       f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
8476     }
8477     if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
8478       outs() << " DEAD_STRIPPABLE_DYLIB";
8479       f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
8480     }
8481     if (f & MachO::MH_PIE) {
8482       outs() << " PIE";
8483       f &= ~MachO::MH_PIE;
8484     }
8485     if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
8486       outs() << " NO_REEXPORTED_DYLIBS";
8487       f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
8488     }
8489     if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
8490       outs() << " MH_HAS_TLV_DESCRIPTORS";
8491       f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
8492     }
8493     if (f & MachO::MH_NO_HEAP_EXECUTION) {
8494       outs() << " MH_NO_HEAP_EXECUTION";
8495       f &= ~MachO::MH_NO_HEAP_EXECUTION;
8496     }
8497     if (f & MachO::MH_APP_EXTENSION_SAFE) {
8498       outs() << " APP_EXTENSION_SAFE";
8499       f &= ~MachO::MH_APP_EXTENSION_SAFE;
8500     }
8501     if (f & MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO) {
8502       outs() << " NLIST_OUTOFSYNC_WITH_DYLDINFO";
8503       f &= ~MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO;
8504     }
8505     if (f != 0 || flags == 0)
8506       outs() << format(" 0x%08" PRIx32, f);
8507   } else {
8508     outs() << format(" 0x%08" PRIx32, magic);
8509     outs() << format(" %7d", cputype);
8510     outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8511     outs() << format("  0x%02" PRIx32,
8512                      (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
8513     outs() << format("  %10u", filetype);
8514     outs() << format(" %5u", ncmds);
8515     outs() << format(" %10u", sizeofcmds);
8516     outs() << format(" 0x%08" PRIx32, flags);
8517   }
8518   outs() << "\n";
8519 }
8520 
8521 static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
8522                                 StringRef SegName, uint64_t vmaddr,
8523                                 uint64_t vmsize, uint64_t fileoff,
8524                                 uint64_t filesize, uint32_t maxprot,
8525                                 uint32_t initprot, uint32_t nsects,
8526                                 uint32_t flags, uint32_t object_size,
8527                                 bool verbose) {
8528   uint64_t expected_cmdsize;
8529   if (cmd == MachO::LC_SEGMENT) {
8530     outs() << "      cmd LC_SEGMENT\n";
8531     expected_cmdsize = nsects;
8532     expected_cmdsize *= sizeof(struct MachO::section);
8533     expected_cmdsize += sizeof(struct MachO::segment_command);
8534   } else {
8535     outs() << "      cmd LC_SEGMENT_64\n";
8536     expected_cmdsize = nsects;
8537     expected_cmdsize *= sizeof(struct MachO::section_64);
8538     expected_cmdsize += sizeof(struct MachO::segment_command_64);
8539   }
8540   outs() << "  cmdsize " << cmdsize;
8541   if (cmdsize != expected_cmdsize)
8542     outs() << " Inconsistent size\n";
8543   else
8544     outs() << "\n";
8545   outs() << "  segname " << SegName << "\n";
8546   if (cmd == MachO::LC_SEGMENT_64) {
8547     outs() << "   vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
8548     outs() << "   vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
8549   } else {
8550     outs() << "   vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
8551     outs() << "   vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
8552   }
8553   outs() << "  fileoff " << fileoff;
8554   if (fileoff > object_size)
8555     outs() << " (past end of file)\n";
8556   else
8557     outs() << "\n";
8558   outs() << " filesize " << filesize;
8559   if (fileoff + filesize > object_size)
8560     outs() << " (past end of file)\n";
8561   else
8562     outs() << "\n";
8563   if (verbose) {
8564     if ((maxprot &
8565          ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8566            MachO::VM_PROT_EXECUTE)) != 0)
8567       outs() << "  maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
8568     else {
8569       outs() << "  maxprot ";
8570       outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
8571       outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8572       outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
8573     }
8574     if ((initprot &
8575          ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8576            MachO::VM_PROT_EXECUTE)) != 0)
8577       outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
8578     else {
8579       outs() << " initprot ";
8580       outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
8581       outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8582       outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
8583     }
8584   } else {
8585     outs() << "  maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
8586     outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
8587   }
8588   outs() << "   nsects " << nsects << "\n";
8589   if (verbose) {
8590     outs() << "    flags";
8591     if (flags == 0)
8592       outs() << " (none)\n";
8593     else {
8594       if (flags & MachO::SG_HIGHVM) {
8595         outs() << " HIGHVM";
8596         flags &= ~MachO::SG_HIGHVM;
8597       }
8598       if (flags & MachO::SG_FVMLIB) {
8599         outs() << " FVMLIB";
8600         flags &= ~MachO::SG_FVMLIB;
8601       }
8602       if (flags & MachO::SG_NORELOC) {
8603         outs() << " NORELOC";
8604         flags &= ~MachO::SG_NORELOC;
8605       }
8606       if (flags & MachO::SG_PROTECTED_VERSION_1) {
8607         outs() << " PROTECTED_VERSION_1";
8608         flags &= ~MachO::SG_PROTECTED_VERSION_1;
8609       }
8610       if (flags)
8611         outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
8612       else
8613         outs() << "\n";
8614     }
8615   } else {
8616     outs() << "    flags " << format("0x%" PRIx32, flags) << "\n";
8617   }
8618 }
8619 
8620 static void PrintSection(const char *sectname, const char *segname,
8621                          uint64_t addr, uint64_t size, uint32_t offset,
8622                          uint32_t align, uint32_t reloff, uint32_t nreloc,
8623                          uint32_t flags, uint32_t reserved1, uint32_t reserved2,
8624                          uint32_t cmd, const char *sg_segname,
8625                          uint32_t filetype, uint32_t object_size,
8626                          bool verbose) {
8627   outs() << "Section\n";
8628   outs() << "  sectname " << format("%.16s\n", sectname);
8629   outs() << "   segname " << format("%.16s", segname);
8630   if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
8631     outs() << " (does not match segment)\n";
8632   else
8633     outs() << "\n";
8634   if (cmd == MachO::LC_SEGMENT_64) {
8635     outs() << "      addr " << format("0x%016" PRIx64, addr) << "\n";
8636     outs() << "      size " << format("0x%016" PRIx64, size);
8637   } else {
8638     outs() << "      addr " << format("0x%08" PRIx64, addr) << "\n";
8639     outs() << "      size " << format("0x%08" PRIx64, size);
8640   }
8641   if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
8642     outs() << " (past end of file)\n";
8643   else
8644     outs() << "\n";
8645   outs() << "    offset " << offset;
8646   if (offset > object_size)
8647     outs() << " (past end of file)\n";
8648   else
8649     outs() << "\n";
8650   uint32_t align_shifted = 1 << align;
8651   outs() << "     align 2^" << align << " (" << align_shifted << ")\n";
8652   outs() << "    reloff " << reloff;
8653   if (reloff > object_size)
8654     outs() << " (past end of file)\n";
8655   else
8656     outs() << "\n";
8657   outs() << "    nreloc " << nreloc;
8658   if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
8659     outs() << " (past end of file)\n";
8660   else
8661     outs() << "\n";
8662   uint32_t section_type = flags & MachO::SECTION_TYPE;
8663   if (verbose) {
8664     outs() << "      type";
8665     if (section_type == MachO::S_REGULAR)
8666       outs() << " S_REGULAR\n";
8667     else if (section_type == MachO::S_ZEROFILL)
8668       outs() << " S_ZEROFILL\n";
8669     else if (section_type == MachO::S_CSTRING_LITERALS)
8670       outs() << " S_CSTRING_LITERALS\n";
8671     else if (section_type == MachO::S_4BYTE_LITERALS)
8672       outs() << " S_4BYTE_LITERALS\n";
8673     else if (section_type == MachO::S_8BYTE_LITERALS)
8674       outs() << " S_8BYTE_LITERALS\n";
8675     else if (section_type == MachO::S_16BYTE_LITERALS)
8676       outs() << " S_16BYTE_LITERALS\n";
8677     else if (section_type == MachO::S_LITERAL_POINTERS)
8678       outs() << " S_LITERAL_POINTERS\n";
8679     else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
8680       outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
8681     else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
8682       outs() << " S_LAZY_SYMBOL_POINTERS\n";
8683     else if (section_type == MachO::S_SYMBOL_STUBS)
8684       outs() << " S_SYMBOL_STUBS\n";
8685     else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
8686       outs() << " S_MOD_INIT_FUNC_POINTERS\n";
8687     else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
8688       outs() << " S_MOD_TERM_FUNC_POINTERS\n";
8689     else if (section_type == MachO::S_COALESCED)
8690       outs() << " S_COALESCED\n";
8691     else if (section_type == MachO::S_INTERPOSING)
8692       outs() << " S_INTERPOSING\n";
8693     else if (section_type == MachO::S_DTRACE_DOF)
8694       outs() << " S_DTRACE_DOF\n";
8695     else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
8696       outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
8697     else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
8698       outs() << " S_THREAD_LOCAL_REGULAR\n";
8699     else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
8700       outs() << " S_THREAD_LOCAL_ZEROFILL\n";
8701     else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
8702       outs() << " S_THREAD_LOCAL_VARIABLES\n";
8703     else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8704       outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
8705     else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
8706       outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
8707     else
8708       outs() << format("0x%08" PRIx32, section_type) << "\n";
8709     outs() << "attributes";
8710     uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
8711     if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
8712       outs() << " PURE_INSTRUCTIONS";
8713     if (section_attributes & MachO::S_ATTR_NO_TOC)
8714       outs() << " NO_TOC";
8715     if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
8716       outs() << " STRIP_STATIC_SYMS";
8717     if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
8718       outs() << " NO_DEAD_STRIP";
8719     if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
8720       outs() << " LIVE_SUPPORT";
8721     if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
8722       outs() << " SELF_MODIFYING_CODE";
8723     if (section_attributes & MachO::S_ATTR_DEBUG)
8724       outs() << " DEBUG";
8725     if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
8726       outs() << " SOME_INSTRUCTIONS";
8727     if (section_attributes & MachO::S_ATTR_EXT_RELOC)
8728       outs() << " EXT_RELOC";
8729     if (section_attributes & MachO::S_ATTR_LOC_RELOC)
8730       outs() << " LOC_RELOC";
8731     if (section_attributes == 0)
8732       outs() << " (none)";
8733     outs() << "\n";
8734   } else
8735     outs() << "     flags " << format("0x%08" PRIx32, flags) << "\n";
8736   outs() << " reserved1 " << reserved1;
8737   if (section_type == MachO::S_SYMBOL_STUBS ||
8738       section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
8739       section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
8740       section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
8741       section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8742     outs() << " (index into indirect symbol table)\n";
8743   else
8744     outs() << "\n";
8745   outs() << " reserved2 " << reserved2;
8746   if (section_type == MachO::S_SYMBOL_STUBS)
8747     outs() << " (size of stubs)\n";
8748   else
8749     outs() << "\n";
8750 }
8751 
8752 static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
8753                                    uint32_t object_size) {
8754   outs() << "     cmd LC_SYMTAB\n";
8755   outs() << " cmdsize " << st.cmdsize;
8756   if (st.cmdsize != sizeof(struct MachO::symtab_command))
8757     outs() << " Incorrect size\n";
8758   else
8759     outs() << "\n";
8760   outs() << "  symoff " << st.symoff;
8761   if (st.symoff > object_size)
8762     outs() << " (past end of file)\n";
8763   else
8764     outs() << "\n";
8765   outs() << "   nsyms " << st.nsyms;
8766   uint64_t big_size;
8767   if (Is64Bit) {
8768     big_size = st.nsyms;
8769     big_size *= sizeof(struct MachO::nlist_64);
8770     big_size += st.symoff;
8771     if (big_size > object_size)
8772       outs() << " (past end of file)\n";
8773     else
8774       outs() << "\n";
8775   } else {
8776     big_size = st.nsyms;
8777     big_size *= sizeof(struct MachO::nlist);
8778     big_size += st.symoff;
8779     if (big_size > object_size)
8780       outs() << " (past end of file)\n";
8781     else
8782       outs() << "\n";
8783   }
8784   outs() << "  stroff " << st.stroff;
8785   if (st.stroff > object_size)
8786     outs() << " (past end of file)\n";
8787   else
8788     outs() << "\n";
8789   outs() << " strsize " << st.strsize;
8790   big_size = st.stroff;
8791   big_size += st.strsize;
8792   if (big_size > object_size)
8793     outs() << " (past end of file)\n";
8794   else
8795     outs() << "\n";
8796 }
8797 
8798 static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
8799                                      uint32_t nsyms, uint32_t object_size,
8800                                      bool Is64Bit) {
8801   outs() << "            cmd LC_DYSYMTAB\n";
8802   outs() << "        cmdsize " << dyst.cmdsize;
8803   if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
8804     outs() << " Incorrect size\n";
8805   else
8806     outs() << "\n";
8807   outs() << "      ilocalsym " << dyst.ilocalsym;
8808   if (dyst.ilocalsym > nsyms)
8809     outs() << " (greater than the number of symbols)\n";
8810   else
8811     outs() << "\n";
8812   outs() << "      nlocalsym " << dyst.nlocalsym;
8813   uint64_t big_size;
8814   big_size = dyst.ilocalsym;
8815   big_size += dyst.nlocalsym;
8816   if (big_size > nsyms)
8817     outs() << " (past the end of the symbol table)\n";
8818   else
8819     outs() << "\n";
8820   outs() << "     iextdefsym " << dyst.iextdefsym;
8821   if (dyst.iextdefsym > nsyms)
8822     outs() << " (greater than the number of symbols)\n";
8823   else
8824     outs() << "\n";
8825   outs() << "     nextdefsym " << dyst.nextdefsym;
8826   big_size = dyst.iextdefsym;
8827   big_size += dyst.nextdefsym;
8828   if (big_size > nsyms)
8829     outs() << " (past the end of the symbol table)\n";
8830   else
8831     outs() << "\n";
8832   outs() << "      iundefsym " << dyst.iundefsym;
8833   if (dyst.iundefsym > nsyms)
8834     outs() << " (greater than the number of symbols)\n";
8835   else
8836     outs() << "\n";
8837   outs() << "      nundefsym " << dyst.nundefsym;
8838   big_size = dyst.iundefsym;
8839   big_size += dyst.nundefsym;
8840   if (big_size > nsyms)
8841     outs() << " (past the end of the symbol table)\n";
8842   else
8843     outs() << "\n";
8844   outs() << "         tocoff " << dyst.tocoff;
8845   if (dyst.tocoff > object_size)
8846     outs() << " (past end of file)\n";
8847   else
8848     outs() << "\n";
8849   outs() << "           ntoc " << dyst.ntoc;
8850   big_size = dyst.ntoc;
8851   big_size *= sizeof(struct MachO::dylib_table_of_contents);
8852   big_size += dyst.tocoff;
8853   if (big_size > object_size)
8854     outs() << " (past end of file)\n";
8855   else
8856     outs() << "\n";
8857   outs() << "      modtaboff " << dyst.modtaboff;
8858   if (dyst.modtaboff > object_size)
8859     outs() << " (past end of file)\n";
8860   else
8861     outs() << "\n";
8862   outs() << "        nmodtab " << dyst.nmodtab;
8863   uint64_t modtabend;
8864   if (Is64Bit) {
8865     modtabend = dyst.nmodtab;
8866     modtabend *= sizeof(struct MachO::dylib_module_64);
8867     modtabend += dyst.modtaboff;
8868   } else {
8869     modtabend = dyst.nmodtab;
8870     modtabend *= sizeof(struct MachO::dylib_module);
8871     modtabend += dyst.modtaboff;
8872   }
8873   if (modtabend > object_size)
8874     outs() << " (past end of file)\n";
8875   else
8876     outs() << "\n";
8877   outs() << "   extrefsymoff " << dyst.extrefsymoff;
8878   if (dyst.extrefsymoff > object_size)
8879     outs() << " (past end of file)\n";
8880   else
8881     outs() << "\n";
8882   outs() << "    nextrefsyms " << dyst.nextrefsyms;
8883   big_size = dyst.nextrefsyms;
8884   big_size *= sizeof(struct MachO::dylib_reference);
8885   big_size += dyst.extrefsymoff;
8886   if (big_size > object_size)
8887     outs() << " (past end of file)\n";
8888   else
8889     outs() << "\n";
8890   outs() << " indirectsymoff " << dyst.indirectsymoff;
8891   if (dyst.indirectsymoff > object_size)
8892     outs() << " (past end of file)\n";
8893   else
8894     outs() << "\n";
8895   outs() << "  nindirectsyms " << dyst.nindirectsyms;
8896   big_size = dyst.nindirectsyms;
8897   big_size *= sizeof(uint32_t);
8898   big_size += dyst.indirectsymoff;
8899   if (big_size > object_size)
8900     outs() << " (past end of file)\n";
8901   else
8902     outs() << "\n";
8903   outs() << "      extreloff " << dyst.extreloff;
8904   if (dyst.extreloff > object_size)
8905     outs() << " (past end of file)\n";
8906   else
8907     outs() << "\n";
8908   outs() << "        nextrel " << dyst.nextrel;
8909   big_size = dyst.nextrel;
8910   big_size *= sizeof(struct MachO::relocation_info);
8911   big_size += dyst.extreloff;
8912   if (big_size > object_size)
8913     outs() << " (past end of file)\n";
8914   else
8915     outs() << "\n";
8916   outs() << "      locreloff " << dyst.locreloff;
8917   if (dyst.locreloff > object_size)
8918     outs() << " (past end of file)\n";
8919   else
8920     outs() << "\n";
8921   outs() << "        nlocrel " << dyst.nlocrel;
8922   big_size = dyst.nlocrel;
8923   big_size *= sizeof(struct MachO::relocation_info);
8924   big_size += dyst.locreloff;
8925   if (big_size > object_size)
8926     outs() << " (past end of file)\n";
8927   else
8928     outs() << "\n";
8929 }
8930 
8931 static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
8932                                      uint32_t object_size) {
8933   if (dc.cmd == MachO::LC_DYLD_INFO)
8934     outs() << "            cmd LC_DYLD_INFO\n";
8935   else
8936     outs() << "            cmd LC_DYLD_INFO_ONLY\n";
8937   outs() << "        cmdsize " << dc.cmdsize;
8938   if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
8939     outs() << " Incorrect size\n";
8940   else
8941     outs() << "\n";
8942   outs() << "     rebase_off " << dc.rebase_off;
8943   if (dc.rebase_off > object_size)
8944     outs() << " (past end of file)\n";
8945   else
8946     outs() << "\n";
8947   outs() << "    rebase_size " << dc.rebase_size;
8948   uint64_t big_size;
8949   big_size = dc.rebase_off;
8950   big_size += dc.rebase_size;
8951   if (big_size > object_size)
8952     outs() << " (past end of file)\n";
8953   else
8954     outs() << "\n";
8955   outs() << "       bind_off " << dc.bind_off;
8956   if (dc.bind_off > object_size)
8957     outs() << " (past end of file)\n";
8958   else
8959     outs() << "\n";
8960   outs() << "      bind_size " << dc.bind_size;
8961   big_size = dc.bind_off;
8962   big_size += dc.bind_size;
8963   if (big_size > object_size)
8964     outs() << " (past end of file)\n";
8965   else
8966     outs() << "\n";
8967   outs() << "  weak_bind_off " << dc.weak_bind_off;
8968   if (dc.weak_bind_off > object_size)
8969     outs() << " (past end of file)\n";
8970   else
8971     outs() << "\n";
8972   outs() << " weak_bind_size " << dc.weak_bind_size;
8973   big_size = dc.weak_bind_off;
8974   big_size += dc.weak_bind_size;
8975   if (big_size > object_size)
8976     outs() << " (past end of file)\n";
8977   else
8978     outs() << "\n";
8979   outs() << "  lazy_bind_off " << dc.lazy_bind_off;
8980   if (dc.lazy_bind_off > object_size)
8981     outs() << " (past end of file)\n";
8982   else
8983     outs() << "\n";
8984   outs() << " lazy_bind_size " << dc.lazy_bind_size;
8985   big_size = dc.lazy_bind_off;
8986   big_size += dc.lazy_bind_size;
8987   if (big_size > object_size)
8988     outs() << " (past end of file)\n";
8989   else
8990     outs() << "\n";
8991   outs() << "     export_off " << dc.export_off;
8992   if (dc.export_off > object_size)
8993     outs() << " (past end of file)\n";
8994   else
8995     outs() << "\n";
8996   outs() << "    export_size " << dc.export_size;
8997   big_size = dc.export_off;
8998   big_size += dc.export_size;
8999   if (big_size > object_size)
9000     outs() << " (past end of file)\n";
9001   else
9002     outs() << "\n";
9003 }
9004 
9005 static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
9006                                  const char *Ptr) {
9007   if (dyld.cmd == MachO::LC_ID_DYLINKER)
9008     outs() << "          cmd LC_ID_DYLINKER\n";
9009   else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
9010     outs() << "          cmd LC_LOAD_DYLINKER\n";
9011   else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
9012     outs() << "          cmd LC_DYLD_ENVIRONMENT\n";
9013   else
9014     outs() << "          cmd ?(" << dyld.cmd << ")\n";
9015   outs() << "      cmdsize " << dyld.cmdsize;
9016   if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
9017     outs() << " Incorrect size\n";
9018   else
9019     outs() << "\n";
9020   if (dyld.name >= dyld.cmdsize)
9021     outs() << "         name ?(bad offset " << dyld.name << ")\n";
9022   else {
9023     const char *P = (const char *)(Ptr) + dyld.name;
9024     outs() << "         name " << P << " (offset " << dyld.name << ")\n";
9025   }
9026 }
9027 
9028 static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
9029   outs() << "     cmd LC_UUID\n";
9030   outs() << " cmdsize " << uuid.cmdsize;
9031   if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
9032     outs() << " Incorrect size\n";
9033   else
9034     outs() << "\n";
9035   outs() << "    uuid ";
9036   for (int i = 0; i < 16; ++i) {
9037     outs() << format("%02" PRIX32, uuid.uuid[i]);
9038     if (i == 3 || i == 5 || i == 7 || i == 9)
9039       outs() << "-";
9040   }
9041   outs() << "\n";
9042 }
9043 
9044 static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
9045   outs() << "          cmd LC_RPATH\n";
9046   outs() << "      cmdsize " << rpath.cmdsize;
9047   if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
9048     outs() << " Incorrect size\n";
9049   else
9050     outs() << "\n";
9051   if (rpath.path >= rpath.cmdsize)
9052     outs() << "         path ?(bad offset " << rpath.path << ")\n";
9053   else {
9054     const char *P = (const char *)(Ptr) + rpath.path;
9055     outs() << "         path " << P << " (offset " << rpath.path << ")\n";
9056   }
9057 }
9058 
9059 static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
9060   StringRef LoadCmdName;
9061   switch (vd.cmd) {
9062   case MachO::LC_VERSION_MIN_MACOSX:
9063     LoadCmdName = "LC_VERSION_MIN_MACOSX";
9064     break;
9065   case MachO::LC_VERSION_MIN_IPHONEOS:
9066     LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
9067     break;
9068   case MachO::LC_VERSION_MIN_TVOS:
9069     LoadCmdName = "LC_VERSION_MIN_TVOS";
9070     break;
9071   case MachO::LC_VERSION_MIN_WATCHOS:
9072     LoadCmdName = "LC_VERSION_MIN_WATCHOS";
9073     break;
9074   default:
9075     llvm_unreachable("Unknown version min load command");
9076   }
9077 
9078   outs() << "      cmd " << LoadCmdName << '\n';
9079   outs() << "  cmdsize " << vd.cmdsize;
9080   if (vd.cmdsize != sizeof(struct MachO::version_min_command))
9081     outs() << " Incorrect size\n";
9082   else
9083     outs() << "\n";
9084   outs() << "  version "
9085          << MachOObjectFile::getVersionMinMajor(vd, false) << "."
9086          << MachOObjectFile::getVersionMinMinor(vd, false);
9087   uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
9088   if (Update != 0)
9089     outs() << "." << Update;
9090   outs() << "\n";
9091   if (vd.sdk == 0)
9092     outs() << "      sdk n/a";
9093   else {
9094     outs() << "      sdk "
9095            << MachOObjectFile::getVersionMinMajor(vd, true) << "."
9096            << MachOObjectFile::getVersionMinMinor(vd, true);
9097   }
9098   Update = MachOObjectFile::getVersionMinUpdate(vd, true);
9099   if (Update != 0)
9100     outs() << "." << Update;
9101   outs() << "\n";
9102 }
9103 
9104 static void PrintNoteLoadCommand(MachO::note_command Nt) {
9105   outs() << "       cmd LC_NOTE\n";
9106   outs() << "   cmdsize " << Nt.cmdsize;
9107   if (Nt.cmdsize != sizeof(struct MachO::note_command))
9108     outs() << " Incorrect size\n";
9109   else
9110     outs() << "\n";
9111   const char *d = Nt.data_owner;
9112   outs() << "data_owner " << format("%.16s\n", d);
9113   outs() << "    offset " << Nt.offset << "\n";
9114   outs() << "      size " << Nt.size << "\n";
9115 }
9116 
9117 static void PrintBuildToolVersion(MachO::build_tool_version bv) {
9118   outs() << "      tool " << MachOObjectFile::getBuildTool(bv.tool) << "\n";
9119   outs() << "   version " << MachOObjectFile::getVersionString(bv.version)
9120          << "\n";
9121 }
9122 
9123 static void PrintBuildVersionLoadCommand(const MachOObjectFile *obj,
9124                                          MachO::build_version_command bd) {
9125   outs() << "       cmd LC_BUILD_VERSION\n";
9126   outs() << "   cmdsize " << bd.cmdsize;
9127   if (bd.cmdsize !=
9128       sizeof(struct MachO::build_version_command) +
9129           bd.ntools * sizeof(struct MachO::build_tool_version))
9130     outs() << " Incorrect size\n";
9131   else
9132     outs() << "\n";
9133   outs() << "  platform " << MachOObjectFile::getBuildPlatform(bd.platform)
9134          << "\n";
9135   if (bd.sdk)
9136     outs() << "       sdk " << MachOObjectFile::getVersionString(bd.sdk)
9137            << "\n";
9138   else
9139     outs() << "       sdk n/a\n";
9140   outs() << "     minos " << MachOObjectFile::getVersionString(bd.minos)
9141          << "\n";
9142   outs() << "    ntools " << bd.ntools << "\n";
9143   for (unsigned i = 0; i < bd.ntools; ++i) {
9144     MachO::build_tool_version bv = obj->getBuildToolVersion(i);
9145     PrintBuildToolVersion(bv);
9146   }
9147 }
9148 
9149 static void PrintSourceVersionCommand(MachO::source_version_command sd) {
9150   outs() << "      cmd LC_SOURCE_VERSION\n";
9151   outs() << "  cmdsize " << sd.cmdsize;
9152   if (sd.cmdsize != sizeof(struct MachO::source_version_command))
9153     outs() << " Incorrect size\n";
9154   else
9155     outs() << "\n";
9156   uint64_t a = (sd.version >> 40) & 0xffffff;
9157   uint64_t b = (sd.version >> 30) & 0x3ff;
9158   uint64_t c = (sd.version >> 20) & 0x3ff;
9159   uint64_t d = (sd.version >> 10) & 0x3ff;
9160   uint64_t e = sd.version & 0x3ff;
9161   outs() << "  version " << a << "." << b;
9162   if (e != 0)
9163     outs() << "." << c << "." << d << "." << e;
9164   else if (d != 0)
9165     outs() << "." << c << "." << d;
9166   else if (c != 0)
9167     outs() << "." << c;
9168   outs() << "\n";
9169 }
9170 
9171 static void PrintEntryPointCommand(MachO::entry_point_command ep) {
9172   outs() << "       cmd LC_MAIN\n";
9173   outs() << "   cmdsize " << ep.cmdsize;
9174   if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
9175     outs() << " Incorrect size\n";
9176   else
9177     outs() << "\n";
9178   outs() << "  entryoff " << ep.entryoff << "\n";
9179   outs() << " stacksize " << ep.stacksize << "\n";
9180 }
9181 
9182 static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
9183                                        uint32_t object_size) {
9184   outs() << "          cmd LC_ENCRYPTION_INFO\n";
9185   outs() << "      cmdsize " << ec.cmdsize;
9186   if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
9187     outs() << " Incorrect size\n";
9188   else
9189     outs() << "\n";
9190   outs() << "     cryptoff " << ec.cryptoff;
9191   if (ec.cryptoff > object_size)
9192     outs() << " (past end of file)\n";
9193   else
9194     outs() << "\n";
9195   outs() << "    cryptsize " << ec.cryptsize;
9196   if (ec.cryptsize > object_size)
9197     outs() << " (past end of file)\n";
9198   else
9199     outs() << "\n";
9200   outs() << "      cryptid " << ec.cryptid << "\n";
9201 }
9202 
9203 static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
9204                                          uint32_t object_size) {
9205   outs() << "          cmd LC_ENCRYPTION_INFO_64\n";
9206   outs() << "      cmdsize " << ec.cmdsize;
9207   if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
9208     outs() << " Incorrect size\n";
9209   else
9210     outs() << "\n";
9211   outs() << "     cryptoff " << ec.cryptoff;
9212   if (ec.cryptoff > object_size)
9213     outs() << " (past end of file)\n";
9214   else
9215     outs() << "\n";
9216   outs() << "    cryptsize " << ec.cryptsize;
9217   if (ec.cryptsize > object_size)
9218     outs() << " (past end of file)\n";
9219   else
9220     outs() << "\n";
9221   outs() << "      cryptid " << ec.cryptid << "\n";
9222   outs() << "          pad " << ec.pad << "\n";
9223 }
9224 
9225 static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
9226                                      const char *Ptr) {
9227   outs() << "     cmd LC_LINKER_OPTION\n";
9228   outs() << " cmdsize " << lo.cmdsize;
9229   if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
9230     outs() << " Incorrect size\n";
9231   else
9232     outs() << "\n";
9233   outs() << "   count " << lo.count << "\n";
9234   const char *string = Ptr + sizeof(struct MachO::linker_option_command);
9235   uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
9236   uint32_t i = 0;
9237   while (left > 0) {
9238     while (*string == '\0' && left > 0) {
9239       string++;
9240       left--;
9241     }
9242     if (left > 0) {
9243       i++;
9244       outs() << "  string #" << i << " " << format("%.*s\n", left, string);
9245       uint32_t NullPos = StringRef(string, left).find('\0');
9246       uint32_t len = std::min(NullPos, left) + 1;
9247       string += len;
9248       left -= len;
9249     }
9250   }
9251   if (lo.count != i)
9252     outs() << "   count " << lo.count << " does not match number of strings "
9253            << i << "\n";
9254 }
9255 
9256 static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
9257                                      const char *Ptr) {
9258   outs() << "          cmd LC_SUB_FRAMEWORK\n";
9259   outs() << "      cmdsize " << sub.cmdsize;
9260   if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
9261     outs() << " Incorrect size\n";
9262   else
9263     outs() << "\n";
9264   if (sub.umbrella < sub.cmdsize) {
9265     const char *P = Ptr + sub.umbrella;
9266     outs() << "     umbrella " << P << " (offset " << sub.umbrella << ")\n";
9267   } else {
9268     outs() << "     umbrella ?(bad offset " << sub.umbrella << ")\n";
9269   }
9270 }
9271 
9272 static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
9273                                     const char *Ptr) {
9274   outs() << "          cmd LC_SUB_UMBRELLA\n";
9275   outs() << "      cmdsize " << sub.cmdsize;
9276   if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
9277     outs() << " Incorrect size\n";
9278   else
9279     outs() << "\n";
9280   if (sub.sub_umbrella < sub.cmdsize) {
9281     const char *P = Ptr + sub.sub_umbrella;
9282     outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
9283   } else {
9284     outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
9285   }
9286 }
9287 
9288 static void PrintSubLibraryCommand(MachO::sub_library_command sub,
9289                                    const char *Ptr) {
9290   outs() << "          cmd LC_SUB_LIBRARY\n";
9291   outs() << "      cmdsize " << sub.cmdsize;
9292   if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
9293     outs() << " Incorrect size\n";
9294   else
9295     outs() << "\n";
9296   if (sub.sub_library < sub.cmdsize) {
9297     const char *P = Ptr + sub.sub_library;
9298     outs() << "  sub_library " << P << " (offset " << sub.sub_library << ")\n";
9299   } else {
9300     outs() << "  sub_library ?(bad offset " << sub.sub_library << ")\n";
9301   }
9302 }
9303 
9304 static void PrintSubClientCommand(MachO::sub_client_command sub,
9305                                   const char *Ptr) {
9306   outs() << "          cmd LC_SUB_CLIENT\n";
9307   outs() << "      cmdsize " << sub.cmdsize;
9308   if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
9309     outs() << " Incorrect size\n";
9310   else
9311     outs() << "\n";
9312   if (sub.client < sub.cmdsize) {
9313     const char *P = Ptr + sub.client;
9314     outs() << "       client " << P << " (offset " << sub.client << ")\n";
9315   } else {
9316     outs() << "       client ?(bad offset " << sub.client << ")\n";
9317   }
9318 }
9319 
9320 static void PrintRoutinesCommand(MachO::routines_command r) {
9321   outs() << "          cmd LC_ROUTINES\n";
9322   outs() << "      cmdsize " << r.cmdsize;
9323   if (r.cmdsize != sizeof(struct MachO::routines_command))
9324     outs() << " Incorrect size\n";
9325   else
9326     outs() << "\n";
9327   outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
9328   outs() << "  init_module " << r.init_module << "\n";
9329   outs() << "    reserved1 " << r.reserved1 << "\n";
9330   outs() << "    reserved2 " << r.reserved2 << "\n";
9331   outs() << "    reserved3 " << r.reserved3 << "\n";
9332   outs() << "    reserved4 " << r.reserved4 << "\n";
9333   outs() << "    reserved5 " << r.reserved5 << "\n";
9334   outs() << "    reserved6 " << r.reserved6 << "\n";
9335 }
9336 
9337 static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
9338   outs() << "          cmd LC_ROUTINES_64\n";
9339   outs() << "      cmdsize " << r.cmdsize;
9340   if (r.cmdsize != sizeof(struct MachO::routines_command_64))
9341     outs() << " Incorrect size\n";
9342   else
9343     outs() << "\n";
9344   outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
9345   outs() << "  init_module " << r.init_module << "\n";
9346   outs() << "    reserved1 " << r.reserved1 << "\n";
9347   outs() << "    reserved2 " << r.reserved2 << "\n";
9348   outs() << "    reserved3 " << r.reserved3 << "\n";
9349   outs() << "    reserved4 " << r.reserved4 << "\n";
9350   outs() << "    reserved5 " << r.reserved5 << "\n";
9351   outs() << "    reserved6 " << r.reserved6 << "\n";
9352 }
9353 
9354 static void Print_x86_thread_state32_t(MachO::x86_thread_state32_t &cpu32) {
9355   outs() << "\t    eax " << format("0x%08" PRIx32, cpu32.eax);
9356   outs() << " ebx    " << format("0x%08" PRIx32, cpu32.ebx);
9357   outs() << " ecx " << format("0x%08" PRIx32, cpu32.ecx);
9358   outs() << " edx " << format("0x%08" PRIx32, cpu32.edx) << "\n";
9359   outs() << "\t    edi " << format("0x%08" PRIx32, cpu32.edi);
9360   outs() << " esi    " << format("0x%08" PRIx32, cpu32.esi);
9361   outs() << " ebp " << format("0x%08" PRIx32, cpu32.ebp);
9362   outs() << " esp " << format("0x%08" PRIx32, cpu32.esp) << "\n";
9363   outs() << "\t    ss  " << format("0x%08" PRIx32, cpu32.ss);
9364   outs() << " eflags " << format("0x%08" PRIx32, cpu32.eflags);
9365   outs() << " eip " << format("0x%08" PRIx32, cpu32.eip);
9366   outs() << " cs  " << format("0x%08" PRIx32, cpu32.cs) << "\n";
9367   outs() << "\t    ds  " << format("0x%08" PRIx32, cpu32.ds);
9368   outs() << " es     " << format("0x%08" PRIx32, cpu32.es);
9369   outs() << " fs  " << format("0x%08" PRIx32, cpu32.fs);
9370   outs() << " gs  " << format("0x%08" PRIx32, cpu32.gs) << "\n";
9371 }
9372 
9373 static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
9374   outs() << "   rax  " << format("0x%016" PRIx64, cpu64.rax);
9375   outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
9376   outs() << " rcx  " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
9377   outs() << "   rdx  " << format("0x%016" PRIx64, cpu64.rdx);
9378   outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
9379   outs() << " rsi  " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
9380   outs() << "   rbp  " << format("0x%016" PRIx64, cpu64.rbp);
9381   outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
9382   outs() << " r8   " << format("0x%016" PRIx64, cpu64.r8) << "\n";
9383   outs() << "    r9  " << format("0x%016" PRIx64, cpu64.r9);
9384   outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
9385   outs() << " r11  " << format("0x%016" PRIx64, cpu64.r11) << "\n";
9386   outs() << "   r12  " << format("0x%016" PRIx64, cpu64.r12);
9387   outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
9388   outs() << " r14  " << format("0x%016" PRIx64, cpu64.r14) << "\n";
9389   outs() << "   r15  " << format("0x%016" PRIx64, cpu64.r15);
9390   outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
9391   outs() << "rflags  " << format("0x%016" PRIx64, cpu64.rflags);
9392   outs() << " cs  " << format("0x%016" PRIx64, cpu64.cs);
9393   outs() << " fs   " << format("0x%016" PRIx64, cpu64.fs) << "\n";
9394   outs() << "    gs  " << format("0x%016" PRIx64, cpu64.gs) << "\n";
9395 }
9396 
9397 static void Print_mmst_reg(MachO::mmst_reg_t &r) {
9398   uint32_t f;
9399   outs() << "\t      mmst_reg  ";
9400   for (f = 0; f < 10; f++)
9401     outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
9402   outs() << "\n";
9403   outs() << "\t      mmst_rsrv ";
9404   for (f = 0; f < 6; f++)
9405     outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
9406   outs() << "\n";
9407 }
9408 
9409 static void Print_xmm_reg(MachO::xmm_reg_t &r) {
9410   uint32_t f;
9411   outs() << "\t      xmm_reg ";
9412   for (f = 0; f < 16; f++)
9413     outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
9414   outs() << "\n";
9415 }
9416 
9417 static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
9418   outs() << "\t    fpu_reserved[0] " << fpu.fpu_reserved[0];
9419   outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
9420   outs() << "\t    control: invalid " << fpu.fpu_fcw.invalid;
9421   outs() << " denorm " << fpu.fpu_fcw.denorm;
9422   outs() << " zdiv " << fpu.fpu_fcw.zdiv;
9423   outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
9424   outs() << " undfl " << fpu.fpu_fcw.undfl;
9425   outs() << " precis " << fpu.fpu_fcw.precis << "\n";
9426   outs() << "\t\t     pc ";
9427   if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
9428     outs() << "FP_PREC_24B ";
9429   else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
9430     outs() << "FP_PREC_53B ";
9431   else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
9432     outs() << "FP_PREC_64B ";
9433   else
9434     outs() << fpu.fpu_fcw.pc << " ";
9435   outs() << "rc ";
9436   if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
9437     outs() << "FP_RND_NEAR ";
9438   else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
9439     outs() << "FP_RND_DOWN ";
9440   else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
9441     outs() << "FP_RND_UP ";
9442   else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
9443     outs() << "FP_CHOP ";
9444   outs() << "\n";
9445   outs() << "\t    status: invalid " << fpu.fpu_fsw.invalid;
9446   outs() << " denorm " << fpu.fpu_fsw.denorm;
9447   outs() << " zdiv " << fpu.fpu_fsw.zdiv;
9448   outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
9449   outs() << " undfl " << fpu.fpu_fsw.undfl;
9450   outs() << " precis " << fpu.fpu_fsw.precis;
9451   outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
9452   outs() << "\t            errsumm " << fpu.fpu_fsw.errsumm;
9453   outs() << " c0 " << fpu.fpu_fsw.c0;
9454   outs() << " c1 " << fpu.fpu_fsw.c1;
9455   outs() << " c2 " << fpu.fpu_fsw.c2;
9456   outs() << " tos " << fpu.fpu_fsw.tos;
9457   outs() << " c3 " << fpu.fpu_fsw.c3;
9458   outs() << " busy " << fpu.fpu_fsw.busy << "\n";
9459   outs() << "\t    fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
9460   outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
9461   outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
9462   outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
9463   outs() << "\t    fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
9464   outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
9465   outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
9466   outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
9467   outs() << "\t    fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
9468   outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
9469   outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
9470   outs() << "\n";
9471   outs() << "\t    fpu_stmm0:\n";
9472   Print_mmst_reg(fpu.fpu_stmm0);
9473   outs() << "\t    fpu_stmm1:\n";
9474   Print_mmst_reg(fpu.fpu_stmm1);
9475   outs() << "\t    fpu_stmm2:\n";
9476   Print_mmst_reg(fpu.fpu_stmm2);
9477   outs() << "\t    fpu_stmm3:\n";
9478   Print_mmst_reg(fpu.fpu_stmm3);
9479   outs() << "\t    fpu_stmm4:\n";
9480   Print_mmst_reg(fpu.fpu_stmm4);
9481   outs() << "\t    fpu_stmm5:\n";
9482   Print_mmst_reg(fpu.fpu_stmm5);
9483   outs() << "\t    fpu_stmm6:\n";
9484   Print_mmst_reg(fpu.fpu_stmm6);
9485   outs() << "\t    fpu_stmm7:\n";
9486   Print_mmst_reg(fpu.fpu_stmm7);
9487   outs() << "\t    fpu_xmm0:\n";
9488   Print_xmm_reg(fpu.fpu_xmm0);
9489   outs() << "\t    fpu_xmm1:\n";
9490   Print_xmm_reg(fpu.fpu_xmm1);
9491   outs() << "\t    fpu_xmm2:\n";
9492   Print_xmm_reg(fpu.fpu_xmm2);
9493   outs() << "\t    fpu_xmm3:\n";
9494   Print_xmm_reg(fpu.fpu_xmm3);
9495   outs() << "\t    fpu_xmm4:\n";
9496   Print_xmm_reg(fpu.fpu_xmm4);
9497   outs() << "\t    fpu_xmm5:\n";
9498   Print_xmm_reg(fpu.fpu_xmm5);
9499   outs() << "\t    fpu_xmm6:\n";
9500   Print_xmm_reg(fpu.fpu_xmm6);
9501   outs() << "\t    fpu_xmm7:\n";
9502   Print_xmm_reg(fpu.fpu_xmm7);
9503   outs() << "\t    fpu_xmm8:\n";
9504   Print_xmm_reg(fpu.fpu_xmm8);
9505   outs() << "\t    fpu_xmm9:\n";
9506   Print_xmm_reg(fpu.fpu_xmm9);
9507   outs() << "\t    fpu_xmm10:\n";
9508   Print_xmm_reg(fpu.fpu_xmm10);
9509   outs() << "\t    fpu_xmm11:\n";
9510   Print_xmm_reg(fpu.fpu_xmm11);
9511   outs() << "\t    fpu_xmm12:\n";
9512   Print_xmm_reg(fpu.fpu_xmm12);
9513   outs() << "\t    fpu_xmm13:\n";
9514   Print_xmm_reg(fpu.fpu_xmm13);
9515   outs() << "\t    fpu_xmm14:\n";
9516   Print_xmm_reg(fpu.fpu_xmm14);
9517   outs() << "\t    fpu_xmm15:\n";
9518   Print_xmm_reg(fpu.fpu_xmm15);
9519   outs() << "\t    fpu_rsrv4:\n";
9520   for (uint32_t f = 0; f < 6; f++) {
9521     outs() << "\t            ";
9522     for (uint32_t g = 0; g < 16; g++)
9523       outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
9524     outs() << "\n";
9525   }
9526   outs() << "\t    fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
9527   outs() << "\n";
9528 }
9529 
9530 static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
9531   outs() << "\t    trapno " << format("0x%08" PRIx32, exc64.trapno);
9532   outs() << " err " << format("0x%08" PRIx32, exc64.err);
9533   outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
9534 }
9535 
9536 static void Print_arm_thread_state32_t(MachO::arm_thread_state32_t &cpu32) {
9537   outs() << "\t    r0  " << format("0x%08" PRIx32, cpu32.r[0]);
9538   outs() << " r1     "   << format("0x%08" PRIx32, cpu32.r[1]);
9539   outs() << " r2  "      << format("0x%08" PRIx32, cpu32.r[2]);
9540   outs() << " r3  "      << format("0x%08" PRIx32, cpu32.r[3]) << "\n";
9541   outs() << "\t    r4  " << format("0x%08" PRIx32, cpu32.r[4]);
9542   outs() << " r5     "   << format("0x%08" PRIx32, cpu32.r[5]);
9543   outs() << " r6  "      << format("0x%08" PRIx32, cpu32.r[6]);
9544   outs() << " r7  "      << format("0x%08" PRIx32, cpu32.r[7]) << "\n";
9545   outs() << "\t    r8  " << format("0x%08" PRIx32, cpu32.r[8]);
9546   outs() << " r9     "   << format("0x%08" PRIx32, cpu32.r[9]);
9547   outs() << " r10 "      << format("0x%08" PRIx32, cpu32.r[10]);
9548   outs() << " r11 "      << format("0x%08" PRIx32, cpu32.r[11]) << "\n";
9549   outs() << "\t    r12 " << format("0x%08" PRIx32, cpu32.r[12]);
9550   outs() << " sp     "   << format("0x%08" PRIx32, cpu32.sp);
9551   outs() << " lr  "      << format("0x%08" PRIx32, cpu32.lr);
9552   outs() << " pc  "      << format("0x%08" PRIx32, cpu32.pc) << "\n";
9553   outs() << "\t   cpsr " << format("0x%08" PRIx32, cpu32.cpsr) << "\n";
9554 }
9555 
9556 static void Print_arm_thread_state64_t(MachO::arm_thread_state64_t &cpu64) {
9557   outs() << "\t    x0  " << format("0x%016" PRIx64, cpu64.x[0]);
9558   outs() << " x1  "      << format("0x%016" PRIx64, cpu64.x[1]);
9559   outs() << " x2  "      << format("0x%016" PRIx64, cpu64.x[2]) << "\n";
9560   outs() << "\t    x3  " << format("0x%016" PRIx64, cpu64.x[3]);
9561   outs() << " x4  "      << format("0x%016" PRIx64, cpu64.x[4]);
9562   outs() << " x5  "      << format("0x%016" PRIx64, cpu64.x[5]) << "\n";
9563   outs() << "\t    x6  " << format("0x%016" PRIx64, cpu64.x[6]);
9564   outs() << " x7  "      << format("0x%016" PRIx64, cpu64.x[7]);
9565   outs() << " x8  "      << format("0x%016" PRIx64, cpu64.x[8]) << "\n";
9566   outs() << "\t    x9  " << format("0x%016" PRIx64, cpu64.x[9]);
9567   outs() << " x10 "      << format("0x%016" PRIx64, cpu64.x[10]);
9568   outs() << " x11 "      << format("0x%016" PRIx64, cpu64.x[11]) << "\n";
9569   outs() << "\t    x12 " << format("0x%016" PRIx64, cpu64.x[12]);
9570   outs() << " x13 "      << format("0x%016" PRIx64, cpu64.x[13]);
9571   outs() << " x14 "      << format("0x%016" PRIx64, cpu64.x[14]) << "\n";
9572   outs() << "\t    x15 " << format("0x%016" PRIx64, cpu64.x[15]);
9573   outs() << " x16 "      << format("0x%016" PRIx64, cpu64.x[16]);
9574   outs() << " x17 "      << format("0x%016" PRIx64, cpu64.x[17]) << "\n";
9575   outs() << "\t    x18 " << format("0x%016" PRIx64, cpu64.x[18]);
9576   outs() << " x19 "      << format("0x%016" PRIx64, cpu64.x[19]);
9577   outs() << " x20 "      << format("0x%016" PRIx64, cpu64.x[20]) << "\n";
9578   outs() << "\t    x21 " << format("0x%016" PRIx64, cpu64.x[21]);
9579   outs() << " x22 "      << format("0x%016" PRIx64, cpu64.x[22]);
9580   outs() << " x23 "      << format("0x%016" PRIx64, cpu64.x[23]) << "\n";
9581   outs() << "\t    x24 " << format("0x%016" PRIx64, cpu64.x[24]);
9582   outs() << " x25 "      << format("0x%016" PRIx64, cpu64.x[25]);
9583   outs() << " x26 "      << format("0x%016" PRIx64, cpu64.x[26]) << "\n";
9584   outs() << "\t    x27 " << format("0x%016" PRIx64, cpu64.x[27]);
9585   outs() << " x28 "      << format("0x%016" PRIx64, cpu64.x[28]);
9586   outs() << "  fp "      << format("0x%016" PRIx64, cpu64.fp) << "\n";
9587   outs() << "\t     lr " << format("0x%016" PRIx64, cpu64.lr);
9588   outs() << " sp  "      << format("0x%016" PRIx64, cpu64.sp);
9589   outs() << "  pc "      << format("0x%016" PRIx64, cpu64.pc) << "\n";
9590   outs() << "\t   cpsr " << format("0x%08"  PRIx32, cpu64.cpsr) << "\n";
9591 }
9592 
9593 static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
9594                                bool isLittleEndian, uint32_t cputype) {
9595   if (t.cmd == MachO::LC_THREAD)
9596     outs() << "        cmd LC_THREAD\n";
9597   else if (t.cmd == MachO::LC_UNIXTHREAD)
9598     outs() << "        cmd LC_UNIXTHREAD\n";
9599   else
9600     outs() << "        cmd " << t.cmd << " (unknown)\n";
9601   outs() << "    cmdsize " << t.cmdsize;
9602   if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
9603     outs() << " Incorrect size\n";
9604   else
9605     outs() << "\n";
9606 
9607   const char *begin = Ptr + sizeof(struct MachO::thread_command);
9608   const char *end = Ptr + t.cmdsize;
9609   uint32_t flavor, count, left;
9610   if (cputype == MachO::CPU_TYPE_I386) {
9611     while (begin < end) {
9612       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9613         memcpy((char *)&flavor, begin, sizeof(uint32_t));
9614         begin += sizeof(uint32_t);
9615       } else {
9616         flavor = 0;
9617         begin = end;
9618       }
9619       if (isLittleEndian != sys::IsLittleEndianHost)
9620         sys::swapByteOrder(flavor);
9621       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9622         memcpy((char *)&count, begin, sizeof(uint32_t));
9623         begin += sizeof(uint32_t);
9624       } else {
9625         count = 0;
9626         begin = end;
9627       }
9628       if (isLittleEndian != sys::IsLittleEndianHost)
9629         sys::swapByteOrder(count);
9630       if (flavor == MachO::x86_THREAD_STATE32) {
9631         outs() << "     flavor i386_THREAD_STATE\n";
9632         if (count == MachO::x86_THREAD_STATE32_COUNT)
9633           outs() << "      count i386_THREAD_STATE_COUNT\n";
9634         else
9635           outs() << "      count " << count
9636                  << " (not x86_THREAD_STATE32_COUNT)\n";
9637         MachO::x86_thread_state32_t cpu32;
9638         left = end - begin;
9639         if (left >= sizeof(MachO::x86_thread_state32_t)) {
9640           memcpy(&cpu32, begin, sizeof(MachO::x86_thread_state32_t));
9641           begin += sizeof(MachO::x86_thread_state32_t);
9642         } else {
9643           memset(&cpu32, '\0', sizeof(MachO::x86_thread_state32_t));
9644           memcpy(&cpu32, begin, left);
9645           begin += left;
9646         }
9647         if (isLittleEndian != sys::IsLittleEndianHost)
9648           swapStruct(cpu32);
9649         Print_x86_thread_state32_t(cpu32);
9650       } else if (flavor == MachO::x86_THREAD_STATE) {
9651         outs() << "     flavor x86_THREAD_STATE\n";
9652         if (count == MachO::x86_THREAD_STATE_COUNT)
9653           outs() << "      count x86_THREAD_STATE_COUNT\n";
9654         else
9655           outs() << "      count " << count
9656                  << " (not x86_THREAD_STATE_COUNT)\n";
9657         struct MachO::x86_thread_state_t ts;
9658         left = end - begin;
9659         if (left >= sizeof(MachO::x86_thread_state_t)) {
9660           memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
9661           begin += sizeof(MachO::x86_thread_state_t);
9662         } else {
9663           memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
9664           memcpy(&ts, begin, left);
9665           begin += left;
9666         }
9667         if (isLittleEndian != sys::IsLittleEndianHost)
9668           swapStruct(ts);
9669         if (ts.tsh.flavor == MachO::x86_THREAD_STATE32) {
9670           outs() << "\t    tsh.flavor x86_THREAD_STATE32 ";
9671           if (ts.tsh.count == MachO::x86_THREAD_STATE32_COUNT)
9672             outs() << "tsh.count x86_THREAD_STATE32_COUNT\n";
9673           else
9674             outs() << "tsh.count " << ts.tsh.count
9675                    << " (not x86_THREAD_STATE32_COUNT\n";
9676           Print_x86_thread_state32_t(ts.uts.ts32);
9677         } else {
9678           outs() << "\t    tsh.flavor " << ts.tsh.flavor << "  tsh.count "
9679                  << ts.tsh.count << "\n";
9680         }
9681       } else {
9682         outs() << "     flavor " << flavor << " (unknown)\n";
9683         outs() << "      count " << count << "\n";
9684         outs() << "      state (unknown)\n";
9685         begin += count * sizeof(uint32_t);
9686       }
9687     }
9688   } else if (cputype == MachO::CPU_TYPE_X86_64) {
9689     while (begin < end) {
9690       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9691         memcpy((char *)&flavor, begin, sizeof(uint32_t));
9692         begin += sizeof(uint32_t);
9693       } else {
9694         flavor = 0;
9695         begin = end;
9696       }
9697       if (isLittleEndian != sys::IsLittleEndianHost)
9698         sys::swapByteOrder(flavor);
9699       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9700         memcpy((char *)&count, begin, sizeof(uint32_t));
9701         begin += sizeof(uint32_t);
9702       } else {
9703         count = 0;
9704         begin = end;
9705       }
9706       if (isLittleEndian != sys::IsLittleEndianHost)
9707         sys::swapByteOrder(count);
9708       if (flavor == MachO::x86_THREAD_STATE64) {
9709         outs() << "     flavor x86_THREAD_STATE64\n";
9710         if (count == MachO::x86_THREAD_STATE64_COUNT)
9711           outs() << "      count x86_THREAD_STATE64_COUNT\n";
9712         else
9713           outs() << "      count " << count
9714                  << " (not x86_THREAD_STATE64_COUNT)\n";
9715         MachO::x86_thread_state64_t cpu64;
9716         left = end - begin;
9717         if (left >= sizeof(MachO::x86_thread_state64_t)) {
9718           memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
9719           begin += sizeof(MachO::x86_thread_state64_t);
9720         } else {
9721           memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
9722           memcpy(&cpu64, begin, left);
9723           begin += left;
9724         }
9725         if (isLittleEndian != sys::IsLittleEndianHost)
9726           swapStruct(cpu64);
9727         Print_x86_thread_state64_t(cpu64);
9728       } else if (flavor == MachO::x86_THREAD_STATE) {
9729         outs() << "     flavor x86_THREAD_STATE\n";
9730         if (count == MachO::x86_THREAD_STATE_COUNT)
9731           outs() << "      count x86_THREAD_STATE_COUNT\n";
9732         else
9733           outs() << "      count " << count
9734                  << " (not x86_THREAD_STATE_COUNT)\n";
9735         struct MachO::x86_thread_state_t ts;
9736         left = end - begin;
9737         if (left >= sizeof(MachO::x86_thread_state_t)) {
9738           memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
9739           begin += sizeof(MachO::x86_thread_state_t);
9740         } else {
9741           memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
9742           memcpy(&ts, begin, left);
9743           begin += left;
9744         }
9745         if (isLittleEndian != sys::IsLittleEndianHost)
9746           swapStruct(ts);
9747         if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
9748           outs() << "\t    tsh.flavor x86_THREAD_STATE64 ";
9749           if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
9750             outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
9751           else
9752             outs() << "tsh.count " << ts.tsh.count
9753                    << " (not x86_THREAD_STATE64_COUNT\n";
9754           Print_x86_thread_state64_t(ts.uts.ts64);
9755         } else {
9756           outs() << "\t    tsh.flavor " << ts.tsh.flavor << "  tsh.count "
9757                  << ts.tsh.count << "\n";
9758         }
9759       } else if (flavor == MachO::x86_FLOAT_STATE) {
9760         outs() << "     flavor x86_FLOAT_STATE\n";
9761         if (count == MachO::x86_FLOAT_STATE_COUNT)
9762           outs() << "      count x86_FLOAT_STATE_COUNT\n";
9763         else
9764           outs() << "      count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
9765         struct MachO::x86_float_state_t fs;
9766         left = end - begin;
9767         if (left >= sizeof(MachO::x86_float_state_t)) {
9768           memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
9769           begin += sizeof(MachO::x86_float_state_t);
9770         } else {
9771           memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
9772           memcpy(&fs, begin, left);
9773           begin += left;
9774         }
9775         if (isLittleEndian != sys::IsLittleEndianHost)
9776           swapStruct(fs);
9777         if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
9778           outs() << "\t    fsh.flavor x86_FLOAT_STATE64 ";
9779           if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
9780             outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
9781           else
9782             outs() << "fsh.count " << fs.fsh.count
9783                    << " (not x86_FLOAT_STATE64_COUNT\n";
9784           Print_x86_float_state_t(fs.ufs.fs64);
9785         } else {
9786           outs() << "\t    fsh.flavor " << fs.fsh.flavor << "  fsh.count "
9787                  << fs.fsh.count << "\n";
9788         }
9789       } else if (flavor == MachO::x86_EXCEPTION_STATE) {
9790         outs() << "     flavor x86_EXCEPTION_STATE\n";
9791         if (count == MachO::x86_EXCEPTION_STATE_COUNT)
9792           outs() << "      count x86_EXCEPTION_STATE_COUNT\n";
9793         else
9794           outs() << "      count " << count
9795                  << " (not x86_EXCEPTION_STATE_COUNT)\n";
9796         struct MachO::x86_exception_state_t es;
9797         left = end - begin;
9798         if (left >= sizeof(MachO::x86_exception_state_t)) {
9799           memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
9800           begin += sizeof(MachO::x86_exception_state_t);
9801         } else {
9802           memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
9803           memcpy(&es, begin, left);
9804           begin += left;
9805         }
9806         if (isLittleEndian != sys::IsLittleEndianHost)
9807           swapStruct(es);
9808         if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
9809           outs() << "\t    esh.flavor x86_EXCEPTION_STATE64\n";
9810           if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
9811             outs() << "\t    esh.count x86_EXCEPTION_STATE64_COUNT\n";
9812           else
9813             outs() << "\t    esh.count " << es.esh.count
9814                    << " (not x86_EXCEPTION_STATE64_COUNT\n";
9815           Print_x86_exception_state_t(es.ues.es64);
9816         } else {
9817           outs() << "\t    esh.flavor " << es.esh.flavor << "  esh.count "
9818                  << es.esh.count << "\n";
9819         }
9820       } else if (flavor == MachO::x86_EXCEPTION_STATE64) {
9821         outs() << "     flavor x86_EXCEPTION_STATE64\n";
9822         if (count == MachO::x86_EXCEPTION_STATE64_COUNT)
9823           outs() << "      count x86_EXCEPTION_STATE64_COUNT\n";
9824         else
9825           outs() << "      count " << count
9826                  << " (not x86_EXCEPTION_STATE64_COUNT)\n";
9827         struct MachO::x86_exception_state64_t es64;
9828         left = end - begin;
9829         if (left >= sizeof(MachO::x86_exception_state64_t)) {
9830           memcpy(&es64, begin, sizeof(MachO::x86_exception_state64_t));
9831           begin += sizeof(MachO::x86_exception_state64_t);
9832         } else {
9833           memset(&es64, '\0', sizeof(MachO::x86_exception_state64_t));
9834           memcpy(&es64, begin, left);
9835           begin += left;
9836         }
9837         if (isLittleEndian != sys::IsLittleEndianHost)
9838           swapStruct(es64);
9839         Print_x86_exception_state_t(es64);
9840       } else {
9841         outs() << "     flavor " << flavor << " (unknown)\n";
9842         outs() << "      count " << count << "\n";
9843         outs() << "      state (unknown)\n";
9844         begin += count * sizeof(uint32_t);
9845       }
9846     }
9847   } else if (cputype == MachO::CPU_TYPE_ARM) {
9848     while (begin < end) {
9849       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9850         memcpy((char *)&flavor, begin, sizeof(uint32_t));
9851         begin += sizeof(uint32_t);
9852       } else {
9853         flavor = 0;
9854         begin = end;
9855       }
9856       if (isLittleEndian != sys::IsLittleEndianHost)
9857         sys::swapByteOrder(flavor);
9858       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9859         memcpy((char *)&count, begin, sizeof(uint32_t));
9860         begin += sizeof(uint32_t);
9861       } else {
9862         count = 0;
9863         begin = end;
9864       }
9865       if (isLittleEndian != sys::IsLittleEndianHost)
9866         sys::swapByteOrder(count);
9867       if (flavor == MachO::ARM_THREAD_STATE) {
9868         outs() << "     flavor ARM_THREAD_STATE\n";
9869         if (count == MachO::ARM_THREAD_STATE_COUNT)
9870           outs() << "      count ARM_THREAD_STATE_COUNT\n";
9871         else
9872           outs() << "      count " << count
9873                  << " (not ARM_THREAD_STATE_COUNT)\n";
9874         MachO::arm_thread_state32_t cpu32;
9875         left = end - begin;
9876         if (left >= sizeof(MachO::arm_thread_state32_t)) {
9877           memcpy(&cpu32, begin, sizeof(MachO::arm_thread_state32_t));
9878           begin += sizeof(MachO::arm_thread_state32_t);
9879         } else {
9880           memset(&cpu32, '\0', sizeof(MachO::arm_thread_state32_t));
9881           memcpy(&cpu32, begin, left);
9882           begin += left;
9883         }
9884         if (isLittleEndian != sys::IsLittleEndianHost)
9885           swapStruct(cpu32);
9886         Print_arm_thread_state32_t(cpu32);
9887       } else {
9888         outs() << "     flavor " << flavor << " (unknown)\n";
9889         outs() << "      count " << count << "\n";
9890         outs() << "      state (unknown)\n";
9891         begin += count * sizeof(uint32_t);
9892       }
9893     }
9894   } else if (cputype == MachO::CPU_TYPE_ARM64 ||
9895              cputype == MachO::CPU_TYPE_ARM64_32) {
9896     while (begin < end) {
9897       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9898         memcpy((char *)&flavor, begin, sizeof(uint32_t));
9899         begin += sizeof(uint32_t);
9900       } else {
9901         flavor = 0;
9902         begin = end;
9903       }
9904       if (isLittleEndian != sys::IsLittleEndianHost)
9905         sys::swapByteOrder(flavor);
9906       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9907         memcpy((char *)&count, begin, sizeof(uint32_t));
9908         begin += sizeof(uint32_t);
9909       } else {
9910         count = 0;
9911         begin = end;
9912       }
9913       if (isLittleEndian != sys::IsLittleEndianHost)
9914         sys::swapByteOrder(count);
9915       if (flavor == MachO::ARM_THREAD_STATE64) {
9916         outs() << "     flavor ARM_THREAD_STATE64\n";
9917         if (count == MachO::ARM_THREAD_STATE64_COUNT)
9918           outs() << "      count ARM_THREAD_STATE64_COUNT\n";
9919         else
9920           outs() << "      count " << count
9921                  << " (not ARM_THREAD_STATE64_COUNT)\n";
9922         MachO::arm_thread_state64_t cpu64;
9923         left = end - begin;
9924         if (left >= sizeof(MachO::arm_thread_state64_t)) {
9925           memcpy(&cpu64, begin, sizeof(MachO::arm_thread_state64_t));
9926           begin += sizeof(MachO::arm_thread_state64_t);
9927         } else {
9928           memset(&cpu64, '\0', sizeof(MachO::arm_thread_state64_t));
9929           memcpy(&cpu64, begin, left);
9930           begin += left;
9931         }
9932         if (isLittleEndian != sys::IsLittleEndianHost)
9933           swapStruct(cpu64);
9934         Print_arm_thread_state64_t(cpu64);
9935       } else {
9936         outs() << "     flavor " << flavor << " (unknown)\n";
9937         outs() << "      count " << count << "\n";
9938         outs() << "      state (unknown)\n";
9939         begin += count * sizeof(uint32_t);
9940       }
9941     }
9942   } else {
9943     while (begin < end) {
9944       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9945         memcpy((char *)&flavor, begin, sizeof(uint32_t));
9946         begin += sizeof(uint32_t);
9947       } else {
9948         flavor = 0;
9949         begin = end;
9950       }
9951       if (isLittleEndian != sys::IsLittleEndianHost)
9952         sys::swapByteOrder(flavor);
9953       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9954         memcpy((char *)&count, begin, sizeof(uint32_t));
9955         begin += sizeof(uint32_t);
9956       } else {
9957         count = 0;
9958         begin = end;
9959       }
9960       if (isLittleEndian != sys::IsLittleEndianHost)
9961         sys::swapByteOrder(count);
9962       outs() << "     flavor " << flavor << "\n";
9963       outs() << "      count " << count << "\n";
9964       outs() << "      state (Unknown cputype/cpusubtype)\n";
9965       begin += count * sizeof(uint32_t);
9966     }
9967   }
9968 }
9969 
9970 static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
9971   if (dl.cmd == MachO::LC_ID_DYLIB)
9972     outs() << "          cmd LC_ID_DYLIB\n";
9973   else if (dl.cmd == MachO::LC_LOAD_DYLIB)
9974     outs() << "          cmd LC_LOAD_DYLIB\n";
9975   else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
9976     outs() << "          cmd LC_LOAD_WEAK_DYLIB\n";
9977   else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
9978     outs() << "          cmd LC_REEXPORT_DYLIB\n";
9979   else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
9980     outs() << "          cmd LC_LAZY_LOAD_DYLIB\n";
9981   else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
9982     outs() << "          cmd LC_LOAD_UPWARD_DYLIB\n";
9983   else
9984     outs() << "          cmd " << dl.cmd << " (unknown)\n";
9985   outs() << "      cmdsize " << dl.cmdsize;
9986   if (dl.cmdsize < sizeof(struct MachO::dylib_command))
9987     outs() << " Incorrect size\n";
9988   else
9989     outs() << "\n";
9990   if (dl.dylib.name < dl.cmdsize) {
9991     const char *P = (const char *)(Ptr) + dl.dylib.name;
9992     outs() << "         name " << P << " (offset " << dl.dylib.name << ")\n";
9993   } else {
9994     outs() << "         name ?(bad offset " << dl.dylib.name << ")\n";
9995   }
9996   outs() << "   time stamp " << dl.dylib.timestamp << " ";
9997   time_t t = dl.dylib.timestamp;
9998   outs() << ctime(&t);
9999   outs() << "      current version ";
10000   if (dl.dylib.current_version == 0xffffffff)
10001     outs() << "n/a\n";
10002   else
10003     outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
10004            << ((dl.dylib.current_version >> 8) & 0xff) << "."
10005            << (dl.dylib.current_version & 0xff) << "\n";
10006   outs() << "compatibility version ";
10007   if (dl.dylib.compatibility_version == 0xffffffff)
10008     outs() << "n/a\n";
10009   else
10010     outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
10011            << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
10012            << (dl.dylib.compatibility_version & 0xff) << "\n";
10013 }
10014 
10015 static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
10016                                      uint32_t object_size) {
10017   if (ld.cmd == MachO::LC_CODE_SIGNATURE)
10018     outs() << "      cmd LC_CODE_SIGNATURE\n";
10019   else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
10020     outs() << "      cmd LC_SEGMENT_SPLIT_INFO\n";
10021   else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
10022     outs() << "      cmd LC_FUNCTION_STARTS\n";
10023   else if (ld.cmd == MachO::LC_DATA_IN_CODE)
10024     outs() << "      cmd LC_DATA_IN_CODE\n";
10025   else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
10026     outs() << "      cmd LC_DYLIB_CODE_SIGN_DRS\n";
10027   else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
10028     outs() << "      cmd LC_LINKER_OPTIMIZATION_HINT\n";
10029   else
10030     outs() << "      cmd " << ld.cmd << " (?)\n";
10031   outs() << "  cmdsize " << ld.cmdsize;
10032   if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
10033     outs() << " Incorrect size\n";
10034   else
10035     outs() << "\n";
10036   outs() << "  dataoff " << ld.dataoff;
10037   if (ld.dataoff > object_size)
10038     outs() << " (past end of file)\n";
10039   else
10040     outs() << "\n";
10041   outs() << " datasize " << ld.datasize;
10042   uint64_t big_size = ld.dataoff;
10043   big_size += ld.datasize;
10044   if (big_size > object_size)
10045     outs() << " (past end of file)\n";
10046   else
10047     outs() << "\n";
10048 }
10049 
10050 static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
10051                               uint32_t cputype, bool verbose) {
10052   StringRef Buf = Obj->getData();
10053   unsigned Index = 0;
10054   for (const auto &Command : Obj->load_commands()) {
10055     outs() << "Load command " << Index++ << "\n";
10056     if (Command.C.cmd == MachO::LC_SEGMENT) {
10057       MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
10058       const char *sg_segname = SLC.segname;
10059       PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
10060                           SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
10061                           SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
10062                           verbose);
10063       for (unsigned j = 0; j < SLC.nsects; j++) {
10064         MachO::section S = Obj->getSection(Command, j);
10065         PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
10066                      S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
10067                      SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
10068       }
10069     } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
10070       MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
10071       const char *sg_segname = SLC_64.segname;
10072       PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
10073                           SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
10074                           SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
10075                           SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
10076       for (unsigned j = 0; j < SLC_64.nsects; j++) {
10077         MachO::section_64 S_64 = Obj->getSection64(Command, j);
10078         PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
10079                      S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
10080                      S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
10081                      sg_segname, filetype, Buf.size(), verbose);
10082       }
10083     } else if (Command.C.cmd == MachO::LC_SYMTAB) {
10084       MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
10085       PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
10086     } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
10087       MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
10088       MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
10089       PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
10090                                Obj->is64Bit());
10091     } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
10092                Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
10093       MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
10094       PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
10095     } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
10096                Command.C.cmd == MachO::LC_ID_DYLINKER ||
10097                Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
10098       MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
10099       PrintDyldLoadCommand(Dyld, Command.Ptr);
10100     } else if (Command.C.cmd == MachO::LC_UUID) {
10101       MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
10102       PrintUuidLoadCommand(Uuid);
10103     } else if (Command.C.cmd == MachO::LC_RPATH) {
10104       MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
10105       PrintRpathLoadCommand(Rpath, Command.Ptr);
10106     } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
10107                Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
10108                Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
10109                Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
10110       MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
10111       PrintVersionMinLoadCommand(Vd);
10112     } else if (Command.C.cmd == MachO::LC_NOTE) {
10113       MachO::note_command Nt = Obj->getNoteLoadCommand(Command);
10114       PrintNoteLoadCommand(Nt);
10115     } else if (Command.C.cmd == MachO::LC_BUILD_VERSION) {
10116       MachO::build_version_command Bv =
10117           Obj->getBuildVersionLoadCommand(Command);
10118       PrintBuildVersionLoadCommand(Obj, Bv);
10119     } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
10120       MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
10121       PrintSourceVersionCommand(Sd);
10122     } else if (Command.C.cmd == MachO::LC_MAIN) {
10123       MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
10124       PrintEntryPointCommand(Ep);
10125     } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
10126       MachO::encryption_info_command Ei =
10127           Obj->getEncryptionInfoCommand(Command);
10128       PrintEncryptionInfoCommand(Ei, Buf.size());
10129     } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
10130       MachO::encryption_info_command_64 Ei =
10131           Obj->getEncryptionInfoCommand64(Command);
10132       PrintEncryptionInfoCommand64(Ei, Buf.size());
10133     } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
10134       MachO::linker_option_command Lo =
10135           Obj->getLinkerOptionLoadCommand(Command);
10136       PrintLinkerOptionCommand(Lo, Command.Ptr);
10137     } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
10138       MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
10139       PrintSubFrameworkCommand(Sf, Command.Ptr);
10140     } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
10141       MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
10142       PrintSubUmbrellaCommand(Sf, Command.Ptr);
10143     } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
10144       MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
10145       PrintSubLibraryCommand(Sl, Command.Ptr);
10146     } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
10147       MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
10148       PrintSubClientCommand(Sc, Command.Ptr);
10149     } else if (Command.C.cmd == MachO::LC_ROUTINES) {
10150       MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
10151       PrintRoutinesCommand(Rc);
10152     } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
10153       MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
10154       PrintRoutinesCommand64(Rc);
10155     } else if (Command.C.cmd == MachO::LC_THREAD ||
10156                Command.C.cmd == MachO::LC_UNIXTHREAD) {
10157       MachO::thread_command Tc = Obj->getThreadCommand(Command);
10158       PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
10159     } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
10160                Command.C.cmd == MachO::LC_ID_DYLIB ||
10161                Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
10162                Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
10163                Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
10164                Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
10165       MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
10166       PrintDylibCommand(Dl, Command.Ptr);
10167     } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
10168                Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
10169                Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
10170                Command.C.cmd == MachO::LC_DATA_IN_CODE ||
10171                Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
10172                Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
10173       MachO::linkedit_data_command Ld =
10174           Obj->getLinkeditDataLoadCommand(Command);
10175       PrintLinkEditDataCommand(Ld, Buf.size());
10176     } else {
10177       outs() << "      cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
10178              << ")\n";
10179       outs() << "  cmdsize " << Command.C.cmdsize << "\n";
10180       // TODO: get and print the raw bytes of the load command.
10181     }
10182     // TODO: print all the other kinds of load commands.
10183   }
10184 }
10185 
10186 static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
10187   if (Obj->is64Bit()) {
10188     MachO::mach_header_64 H_64;
10189     H_64 = Obj->getHeader64();
10190     PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
10191                     H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
10192   } else {
10193     MachO::mach_header H;
10194     H = Obj->getHeader();
10195     PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
10196                     H.sizeofcmds, H.flags, verbose);
10197   }
10198 }
10199 
10200 void printMachOFileHeader(const object::ObjectFile *Obj) {
10201   const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
10202   PrintMachHeader(file, !NonVerbose);
10203 }
10204 
10205 void printMachOLoadCommands(const object::ObjectFile *Obj) {
10206   const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
10207   uint32_t filetype = 0;
10208   uint32_t cputype = 0;
10209   if (file->is64Bit()) {
10210     MachO::mach_header_64 H_64;
10211     H_64 = file->getHeader64();
10212     filetype = H_64.filetype;
10213     cputype = H_64.cputype;
10214   } else {
10215     MachO::mach_header H;
10216     H = file->getHeader();
10217     filetype = H.filetype;
10218     cputype = H.cputype;
10219   }
10220   PrintLoadCommands(file, filetype, cputype, !NonVerbose);
10221 }
10222 
10223 //===----------------------------------------------------------------------===//
10224 // export trie dumping
10225 //===----------------------------------------------------------------------===//
10226 
10227 void printMachOExportsTrie(const object::MachOObjectFile *Obj) {
10228   uint64_t BaseSegmentAddress = 0;
10229   for (const auto &Command : Obj->load_commands()) {
10230     if (Command.C.cmd == MachO::LC_SEGMENT) {
10231       MachO::segment_command Seg = Obj->getSegmentLoadCommand(Command);
10232       if (Seg.fileoff == 0 && Seg.filesize != 0) {
10233         BaseSegmentAddress = Seg.vmaddr;
10234         break;
10235       }
10236     } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
10237       MachO::segment_command_64 Seg = Obj->getSegment64LoadCommand(Command);
10238       if (Seg.fileoff == 0 && Seg.filesize != 0) {
10239         BaseSegmentAddress = Seg.vmaddr;
10240         break;
10241       }
10242     }
10243   }
10244   Error Err = Error::success();
10245   for (const object::ExportEntry &Entry : Obj->exports(Err)) {
10246     uint64_t Flags = Entry.flags();
10247     bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
10248     bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
10249     bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
10250                         MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
10251     bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
10252                 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
10253     bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
10254     if (ReExport)
10255       outs() << "[re-export] ";
10256     else
10257       outs() << format("0x%08llX  ",
10258                        Entry.address() + BaseSegmentAddress);
10259     outs() << Entry.name();
10260     if (WeakDef || ThreadLocal || Resolver || Abs) {
10261       bool NeedsComma = false;
10262       outs() << " [";
10263       if (WeakDef) {
10264         outs() << "weak_def";
10265         NeedsComma = true;
10266       }
10267       if (ThreadLocal) {
10268         if (NeedsComma)
10269           outs() << ", ";
10270         outs() << "per-thread";
10271         NeedsComma = true;
10272       }
10273       if (Abs) {
10274         if (NeedsComma)
10275           outs() << ", ";
10276         outs() << "absolute";
10277         NeedsComma = true;
10278       }
10279       if (Resolver) {
10280         if (NeedsComma)
10281           outs() << ", ";
10282         outs() << format("resolver=0x%08llX", Entry.other());
10283         NeedsComma = true;
10284       }
10285       outs() << "]";
10286     }
10287     if (ReExport) {
10288       StringRef DylibName = "unknown";
10289       int Ordinal = Entry.other() - 1;
10290       Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
10291       if (Entry.otherName().empty())
10292         outs() << " (from " << DylibName << ")";
10293       else
10294         outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
10295     }
10296     outs() << "\n";
10297   }
10298   if (Err)
10299     reportError(std::move(Err), Obj->getFileName());
10300 }
10301 
10302 //===----------------------------------------------------------------------===//
10303 // rebase table dumping
10304 //===----------------------------------------------------------------------===//
10305 
10306 void printMachORebaseTable(object::MachOObjectFile *Obj) {
10307   outs() << "segment  section            address     type\n";
10308   Error Err = Error::success();
10309   for (const object::MachORebaseEntry &Entry : Obj->rebaseTable(Err)) {
10310     StringRef SegmentName = Entry.segmentName();
10311     StringRef SectionName = Entry.sectionName();
10312     uint64_t Address = Entry.address();
10313 
10314     // Table lines look like: __DATA  __nl_symbol_ptr  0x0000F00C  pointer
10315     outs() << format("%-8s %-18s 0x%08" PRIX64 "  %s\n",
10316                      SegmentName.str().c_str(), SectionName.str().c_str(),
10317                      Address, Entry.typeName().str().c_str());
10318   }
10319   if (Err)
10320     reportError(std::move(Err), Obj->getFileName());
10321 }
10322 
10323 static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
10324   StringRef DylibName;
10325   switch (Ordinal) {
10326   case MachO::BIND_SPECIAL_DYLIB_SELF:
10327     return "this-image";
10328   case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
10329     return "main-executable";
10330   case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
10331     return "flat-namespace";
10332   default:
10333     if (Ordinal > 0) {
10334       std::error_code EC =
10335           Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
10336       if (EC)
10337         return "<<bad library ordinal>>";
10338       return DylibName;
10339     }
10340   }
10341   return "<<unknown special ordinal>>";
10342 }
10343 
10344 //===----------------------------------------------------------------------===//
10345 // bind table dumping
10346 //===----------------------------------------------------------------------===//
10347 
10348 void printMachOBindTable(object::MachOObjectFile *Obj) {
10349   // Build table of sections so names can used in final output.
10350   outs() << "segment  section            address    type       "
10351             "addend dylib            symbol\n";
10352   Error Err = Error::success();
10353   for (const object::MachOBindEntry &Entry : Obj->bindTable(Err)) {
10354     StringRef SegmentName = Entry.segmentName();
10355     StringRef SectionName = Entry.sectionName();
10356     uint64_t Address = Entry.address();
10357 
10358     // Table lines look like:
10359     //  __DATA  __got  0x00012010    pointer   0 libSystem ___stack_chk_guard
10360     StringRef Attr;
10361     if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
10362       Attr = " (weak_import)";
10363     outs() << left_justify(SegmentName, 8) << " "
10364            << left_justify(SectionName, 18) << " "
10365            << format_hex(Address, 10, true) << " "
10366            << left_justify(Entry.typeName(), 8) << " "
10367            << format_decimal(Entry.addend(), 8) << " "
10368            << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
10369            << Entry.symbolName() << Attr << "\n";
10370   }
10371   if (Err)
10372     reportError(std::move(Err), Obj->getFileName());
10373 }
10374 
10375 //===----------------------------------------------------------------------===//
10376 // lazy bind table dumping
10377 //===----------------------------------------------------------------------===//
10378 
10379 void printMachOLazyBindTable(object::MachOObjectFile *Obj) {
10380   outs() << "segment  section            address     "
10381             "dylib            symbol\n";
10382   Error Err = Error::success();
10383   for (const object::MachOBindEntry &Entry : Obj->lazyBindTable(Err)) {
10384     StringRef SegmentName = Entry.segmentName();
10385     StringRef SectionName = Entry.sectionName();
10386     uint64_t Address = Entry.address();
10387 
10388     // Table lines look like:
10389     //  __DATA  __got  0x00012010 libSystem ___stack_chk_guard
10390     outs() << left_justify(SegmentName, 8) << " "
10391            << left_justify(SectionName, 18) << " "
10392            << format_hex(Address, 10, true) << " "
10393            << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
10394            << Entry.symbolName() << "\n";
10395   }
10396   if (Err)
10397     reportError(std::move(Err), Obj->getFileName());
10398 }
10399 
10400 //===----------------------------------------------------------------------===//
10401 // weak bind table dumping
10402 //===----------------------------------------------------------------------===//
10403 
10404 void printMachOWeakBindTable(object::MachOObjectFile *Obj) {
10405   outs() << "segment  section            address     "
10406             "type       addend   symbol\n";
10407   Error Err = Error::success();
10408   for (const object::MachOBindEntry &Entry : Obj->weakBindTable(Err)) {
10409     // Strong symbols don't have a location to update.
10410     if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
10411       outs() << "                                        strong              "
10412              << Entry.symbolName() << "\n";
10413       continue;
10414     }
10415     StringRef SegmentName = Entry.segmentName();
10416     StringRef SectionName = Entry.sectionName();
10417     uint64_t Address = Entry.address();
10418 
10419     // Table lines look like:
10420     // __DATA  __data  0x00001000  pointer    0   _foo
10421     outs() << left_justify(SegmentName, 8) << " "
10422            << left_justify(SectionName, 18) << " "
10423            << format_hex(Address, 10, true) << " "
10424            << left_justify(Entry.typeName(), 8) << " "
10425            << format_decimal(Entry.addend(), 8) << "   " << Entry.symbolName()
10426            << "\n";
10427   }
10428   if (Err)
10429     reportError(std::move(Err), Obj->getFileName());
10430 }
10431 
10432 // get_dyld_bind_info_symbolname() is used for disassembly and passed an
10433 // address, ReferenceValue, in the Mach-O file and looks in the dyld bind
10434 // information for that address. If the address is found its binding symbol
10435 // name is returned.  If not nullptr is returned.
10436 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
10437                                                  struct DisassembleInfo *info) {
10438   if (info->bindtable == nullptr) {
10439     info->bindtable = std::make_unique<SymbolAddressMap>();
10440     Error Err = Error::success();
10441     for (const object::MachOBindEntry &Entry : info->O->bindTable(Err)) {
10442       uint64_t Address = Entry.address();
10443       StringRef name = Entry.symbolName();
10444       if (!name.empty())
10445         (*info->bindtable)[Address] = name;
10446     }
10447     if (Err)
10448       reportError(std::move(Err), info->O->getFileName());
10449   }
10450   auto name = info->bindtable->lookup(ReferenceValue);
10451   return !name.empty() ? name.data() : nullptr;
10452 }
10453 
10454 void printLazyBindTable(ObjectFile *o) {
10455   outs() << "Lazy bind table:\n";
10456   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10457     printMachOLazyBindTable(MachO);
10458   else
10459     WithColor::error()
10460         << "This operation is only currently supported "
10461            "for Mach-O executable files.\n";
10462 }
10463 
10464 void printWeakBindTable(ObjectFile *o) {
10465   outs() << "Weak bind table:\n";
10466   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10467     printMachOWeakBindTable(MachO);
10468   else
10469     WithColor::error()
10470         << "This operation is only currently supported "
10471            "for Mach-O executable files.\n";
10472 }
10473 
10474 void printExportsTrie(const ObjectFile *o) {
10475   outs() << "Exports trie:\n";
10476   if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10477     printMachOExportsTrie(MachO);
10478   else
10479     WithColor::error()
10480         << "This operation is only currently supported "
10481            "for Mach-O executable files.\n";
10482 }
10483 
10484 void printRebaseTable(ObjectFile *o) {
10485   outs() << "Rebase table:\n";
10486   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10487     printMachORebaseTable(MachO);
10488   else
10489     WithColor::error()
10490         << "This operation is only currently supported "
10491            "for Mach-O executable files.\n";
10492 }
10493 
10494 void printBindTable(ObjectFile *o) {
10495   outs() << "Bind table:\n";
10496   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10497     printMachOBindTable(MachO);
10498   else
10499     WithColor::error()
10500         << "This operation is only currently supported "
10501            "for Mach-O executable files.\n";
10502 }
10503 } // namespace llvm
10504