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/Triple.h"
20 #include "llvm/BinaryFormat/MachO.h"
21 #include "llvm/Config/config.h"
22 #include "llvm/DebugInfo/DIContext.h"
23 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
24 #include "llvm/Demangle/Demangle.h"
25 #include "llvm/MC/MCAsmInfo.h"
26 #include "llvm/MC/MCContext.h"
27 #include "llvm/MC/MCDisassembler/MCDisassembler.h"
28 #include "llvm/MC/MCInst.h"
29 #include "llvm/MC/MCInstPrinter.h"
30 #include "llvm/MC/MCInstrDesc.h"
31 #include "llvm/MC/MCInstrInfo.h"
32 #include "llvm/MC/MCRegisterInfo.h"
33 #include "llvm/MC/MCSubtargetInfo.h"
34 #include "llvm/MC/MCTargetOptions.h"
35 #include "llvm/Object/MachO.h"
36 #include "llvm/Object/MachOUniversal.h"
37 #include "llvm/Support/Casting.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/Endian.h"
41 #include "llvm/Support/Format.h"
42 #include "llvm/Support/FormattedStream.h"
43 #include "llvm/Support/GraphWriter.h"
44 #include "llvm/Support/LEB128.h"
45 #include "llvm/Support/MemoryBuffer.h"
46 #include "llvm/Support/TargetRegistry.h"
47 #include "llvm/Support/TargetSelect.h"
48 #include "llvm/Support/ToolOutputFile.h"
49 #include "llvm/Support/WithColor.h"
50 #include "llvm/Support/raw_ostream.h"
51 #include <algorithm>
52 #include <cstring>
53 #include <system_error>
54 
55 #ifdef HAVE_LIBXAR
56 extern "C" {
57 #include <xar/xar.h>
58 }
59 #endif
60 
61 using namespace llvm;
62 using namespace llvm::object;
63 using namespace llvm::objdump;
64 
65 cl::OptionCategory objdump::MachOCat("llvm-objdump MachO Specific Options");
66 
67 cl::opt<bool> objdump::FirstPrivateHeader(
68     "private-header",
69     cl::desc("Display only the first format specific file header"),
70     cl::cat(MachOCat));
71 
72 cl::opt<bool> objdump::ExportsTrie("exports-trie",
73                                    cl::desc("Display mach-o exported symbols"),
74                                    cl::cat(MachOCat));
75 
76 cl::opt<bool> objdump::Rebase("rebase",
77                               cl::desc("Display mach-o rebasing info"),
78                               cl::cat(MachOCat));
79 
80 cl::opt<bool> objdump::Bind("bind", cl::desc("Display mach-o binding info"),
81                             cl::cat(MachOCat));
82 
83 cl::opt<bool> objdump::LazyBind("lazy-bind",
84                                 cl::desc("Display mach-o lazy binding info"),
85                                 cl::cat(MachOCat));
86 
87 cl::opt<bool> objdump::WeakBind("weak-bind",
88                                 cl::desc("Display mach-o weak binding info"),
89                                 cl::cat(MachOCat));
90 
91 static cl::opt<bool>
92     UseDbg("g", cl::Grouping,
93            cl::desc("Print line information from debug info if available"),
94            cl::cat(MachOCat));
95 
96 static cl::opt<std::string> DSYMFile("dsym",
97                                      cl::desc("Use .dSYM file for debug info"),
98                                      cl::cat(MachOCat));
99 
100 static cl::opt<bool> FullLeadingAddr("full-leading-addr",
101                                      cl::desc("Print full leading address"),
102                                      cl::cat(MachOCat));
103 
104 static cl::opt<bool> NoLeadingHeaders("no-leading-headers",
105                                       cl::desc("Print no leading headers"),
106                                       cl::cat(MachOCat));
107 
108 cl::opt<bool> objdump::UniversalHeaders(
109     "universal-headers",
110     cl::desc("Print Mach-O universal headers (requires -macho)"),
111     cl::cat(MachOCat));
112 
113 static cl::opt<bool> ArchiveMemberOffsets(
114     "archive-member-offsets",
115     cl::desc("Print the offset to each archive member for Mach-O archives "
116              "(requires -macho and -archive-headers)"),
117     cl::cat(MachOCat));
118 
119 cl::opt<bool> objdump::IndirectSymbols(
120     "indirect-symbols",
121     cl::desc(
122         "Print indirect symbol table for Mach-O objects (requires -macho)"),
123     cl::cat(MachOCat));
124 
125 cl::opt<bool> objdump::DataInCode(
126     "data-in-code",
127     cl::desc(
128         "Print the data in code table for Mach-O objects (requires -macho)"),
129     cl::cat(MachOCat));
130 
131 cl::opt<bool>
132     objdump::LinkOptHints("link-opt-hints",
133                           cl::desc("Print the linker optimization hints for "
134                                    "Mach-O objects (requires -macho)"),
135                           cl::cat(MachOCat));
136 
137 cl::opt<bool>
138     objdump::InfoPlist("info-plist",
139                        cl::desc("Print the info plist section as strings for "
140                                 "Mach-O objects (requires -macho)"),
141                        cl::cat(MachOCat));
142 
143 cl::opt<bool>
144     objdump::DylibsUsed("dylibs-used",
145                         cl::desc("Print the shared libraries used for linked "
146                                  "Mach-O files (requires -macho)"),
147                         cl::cat(MachOCat));
148 
149 cl::opt<bool> objdump::DylibId("dylib-id",
150                                cl::desc("Print the shared library's id for the "
151                                         "dylib Mach-O file (requires -macho)"),
152                                cl::cat(MachOCat));
153 
154 static cl::opt<bool>
155     NonVerbose("non-verbose",
156                cl::desc("Print the info for Mach-O objects in non-verbose or "
157                         "numeric form (requires -macho)"),
158                cl::cat(MachOCat));
159 
160 cl::opt<bool>
161     objdump::ObjcMetaData("objc-meta-data",
162                           cl::desc("Print the Objective-C runtime meta data "
163                                    "for Mach-O files (requires -macho)"),
164                           cl::cat(MachOCat));
165 
166 static cl::opt<std::string> DisSymName(
167     "dis-symname",
168     cl::desc("disassemble just this symbol's instructions (requires -macho)"),
169     cl::cat(MachOCat));
170 
171 static cl::opt<bool> NoSymbolicOperands(
172     "no-symbolic-operands",
173     cl::desc("do not symbolic operands when disassembling (requires -macho)"),
174     cl::cat(MachOCat));
175 
176 static cl::list<std::string>
177     ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
178               cl::ZeroOrMore, cl::cat(MachOCat));
179 
180 static bool ArchAll = false;
181 
182 static std::string ThumbTripleName;
183 
184 static const Target *GetTarget(const MachOObjectFile *MachOObj,
185                                const char **McpuDefault,
186                                const Target **ThumbTarget) {
187   // Figure out the target triple.
188   Triple TT(TripleName);
189   if (TripleName.empty()) {
190     TT = MachOObj->getArchTriple(McpuDefault);
191     TripleName = TT.str();
192   }
193 
194   if (TT.getArch() == Triple::arm) {
195     // We've inferred a 32-bit ARM target from the object file. All MachO CPUs
196     // that support ARM are also capable of Thumb mode.
197     Triple ThumbTriple = TT;
198     std::string ThumbName = (Twine("thumb") + TT.getArchName().substr(3)).str();
199     ThumbTriple.setArchName(ThumbName);
200     ThumbTripleName = ThumbTriple.str();
201   }
202 
203   // Get the target specific parser.
204   std::string Error;
205   const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
206   if (TheTarget && ThumbTripleName.empty())
207     return TheTarget;
208 
209   *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
210   if (*ThumbTarget)
211     return TheTarget;
212 
213   WithColor::error(errs(), "llvm-objdump") << "unable to get target for '";
214   if (!TheTarget)
215     errs() << TripleName;
216   else
217     errs() << ThumbTripleName;
218   errs() << "', see --version and --triple.\n";
219   return nullptr;
220 }
221 
222 namespace {
223 struct SymbolSorter {
224   bool operator()(const SymbolRef &A, const SymbolRef &B) {
225     Expected<SymbolRef::Type> ATypeOrErr = A.getType();
226     if (!ATypeOrErr)
227       reportError(ATypeOrErr.takeError(), A.getObject()->getFileName());
228     SymbolRef::Type AType = *ATypeOrErr;
229     Expected<SymbolRef::Type> BTypeOrErr = B.getType();
230     if (!BTypeOrErr)
231       reportError(BTypeOrErr.takeError(), B.getObject()->getFileName());
232     SymbolRef::Type BType = *BTypeOrErr;
233     uint64_t AAddr = (AType != SymbolRef::ST_Function) ? 0 : A.getValue();
234     uint64_t BAddr = (BType != SymbolRef::ST_Function) ? 0 : B.getValue();
235     return AAddr < BAddr;
236   }
237 };
238 } // namespace
239 
240 // Types for the storted data in code table that is built before disassembly
241 // and the predicate function to sort them.
242 typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
243 typedef std::vector<DiceTableEntry> DiceTable;
244 typedef DiceTable::iterator dice_table_iterator;
245 
246 #ifdef HAVE_LIBXAR
247 namespace {
248 struct ScopedXarFile {
249   xar_t xar;
250   ScopedXarFile(const char *filename, int32_t flags)
251       : xar(xar_open(filename, flags)) {}
252   ~ScopedXarFile() {
253     if (xar)
254       xar_close(xar);
255   }
256   ScopedXarFile(const ScopedXarFile &) = delete;
257   ScopedXarFile &operator=(const ScopedXarFile &) = delete;
258   operator xar_t() { return xar; }
259 };
260 
261 struct ScopedXarIter {
262   xar_iter_t iter;
263   ScopedXarIter() : iter(xar_iter_new()) {}
264   ~ScopedXarIter() {
265     if (iter)
266       xar_iter_free(iter);
267   }
268   ScopedXarIter(const ScopedXarIter &) = delete;
269   ScopedXarIter &operator=(const ScopedXarIter &) = delete;
270   operator xar_iter_t() { return iter; }
271 };
272 } // namespace
273 #endif // defined(HAVE_LIBXAR)
274 
275 // This is used to search for a data in code table entry for the PC being
276 // disassembled.  The j parameter has the PC in j.first.  A single data in code
277 // table entry can cover many bytes for each of its Kind's.  So if the offset,
278 // aka the i.first value, of the data in code table entry plus its Length
279 // covers the PC being searched for this will return true.  If not it will
280 // return false.
281 static bool compareDiceTableEntries(const DiceTableEntry &i,
282                                     const DiceTableEntry &j) {
283   uint16_t Length;
284   i.second.getLength(Length);
285 
286   return j.first >= i.first && j.first < i.first + Length;
287 }
288 
289 static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
290                                unsigned short Kind) {
291   uint32_t Value, Size = 1;
292 
293   switch (Kind) {
294   default:
295   case MachO::DICE_KIND_DATA:
296     if (Length >= 4) {
297       if (!NoShowRawInsn)
298         dumpBytes(makeArrayRef(bytes, 4), outs());
299       Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
300       outs() << "\t.long " << Value;
301       Size = 4;
302     } else if (Length >= 2) {
303       if (!NoShowRawInsn)
304         dumpBytes(makeArrayRef(bytes, 2), outs());
305       Value = bytes[1] << 8 | bytes[0];
306       outs() << "\t.short " << Value;
307       Size = 2;
308     } else {
309       if (!NoShowRawInsn)
310         dumpBytes(makeArrayRef(bytes, 2), outs());
311       Value = bytes[0];
312       outs() << "\t.byte " << Value;
313       Size = 1;
314     }
315     if (Kind == MachO::DICE_KIND_DATA)
316       outs() << "\t@ KIND_DATA\n";
317     else
318       outs() << "\t@ data in code kind = " << Kind << "\n";
319     break;
320   case MachO::DICE_KIND_JUMP_TABLE8:
321     if (!NoShowRawInsn)
322       dumpBytes(makeArrayRef(bytes, 1), outs());
323     Value = bytes[0];
324     outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
325     Size = 1;
326     break;
327   case MachO::DICE_KIND_JUMP_TABLE16:
328     if (!NoShowRawInsn)
329       dumpBytes(makeArrayRef(bytes, 2), outs());
330     Value = bytes[1] << 8 | bytes[0];
331     outs() << "\t.short " << format("%5u", Value & 0xffff)
332            << "\t@ KIND_JUMP_TABLE16\n";
333     Size = 2;
334     break;
335   case MachO::DICE_KIND_JUMP_TABLE32:
336   case MachO::DICE_KIND_ABS_JUMP_TABLE32:
337     if (!NoShowRawInsn)
338       dumpBytes(makeArrayRef(bytes, 4), outs());
339     Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
340     outs() << "\t.long " << Value;
341     if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
342       outs() << "\t@ KIND_JUMP_TABLE32\n";
343     else
344       outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
345     Size = 4;
346     break;
347   }
348   return Size;
349 }
350 
351 static void getSectionsAndSymbols(MachOObjectFile *MachOObj,
352                                   std::vector<SectionRef> &Sections,
353                                   std::vector<SymbolRef> &Symbols,
354                                   SmallVectorImpl<uint64_t> &FoundFns,
355                                   uint64_t &BaseSegmentAddress) {
356   const StringRef FileName = MachOObj->getFileName();
357   for (const SymbolRef &Symbol : MachOObj->symbols()) {
358     StringRef SymName = unwrapOrError(Symbol.getName(), FileName);
359     if (!SymName.startswith("ltmp"))
360       Symbols.push_back(Symbol);
361   }
362 
363   for (const SectionRef &Section : MachOObj->sections())
364     Sections.push_back(Section);
365 
366   bool BaseSegmentAddressSet = false;
367   for (const auto &Command : MachOObj->load_commands()) {
368     if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
369       // We found a function starts segment, parse the addresses for later
370       // consumption.
371       MachO::linkedit_data_command LLC =
372           MachOObj->getLinkeditDataLoadCommand(Command);
373 
374       MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
375     } else if (Command.C.cmd == MachO::LC_SEGMENT) {
376       MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
377       StringRef SegName = SLC.segname;
378       if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
379         BaseSegmentAddressSet = true;
380         BaseSegmentAddress = SLC.vmaddr;
381       }
382     } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
383       MachO::segment_command_64 SLC = MachOObj->getSegment64LoadCommand(Command);
384       StringRef SegName = SLC.segname;
385       if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
386         BaseSegmentAddressSet = true;
387         BaseSegmentAddress = SLC.vmaddr;
388       }
389     }
390   }
391 }
392 
393 static bool DumpAndSkipDataInCode(uint64_t PC, const uint8_t *bytes,
394                                  DiceTable &Dices, uint64_t &InstSize) {
395   // Check the data in code table here to see if this is data not an
396   // instruction to be disassembled.
397   DiceTable Dice;
398   Dice.push_back(std::make_pair(PC, DiceRef()));
399   dice_table_iterator DTI =
400       std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
401                   compareDiceTableEntries);
402   if (DTI != Dices.end()) {
403     uint16_t Length;
404     DTI->second.getLength(Length);
405     uint16_t Kind;
406     DTI->second.getKind(Kind);
407     InstSize = DumpDataInCode(bytes, Length, Kind);
408     if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
409         (PC == (DTI->first + Length - 1)) && (Length & 1))
410       InstSize++;
411     return true;
412   }
413   return false;
414 }
415 
416 static void printRelocationTargetName(const MachOObjectFile *O,
417                                       const MachO::any_relocation_info &RE,
418                                       raw_string_ostream &Fmt) {
419   // Target of a scattered relocation is an address.  In the interest of
420   // generating pretty output, scan through the symbol table looking for a
421   // symbol that aligns with that address.  If we find one, print it.
422   // Otherwise, we just print the hex address of the target.
423   const StringRef FileName = O->getFileName();
424   if (O->isRelocationScattered(RE)) {
425     uint32_t Val = O->getPlainRelocationSymbolNum(RE);
426 
427     for (const SymbolRef &Symbol : O->symbols()) {
428       uint64_t Addr = unwrapOrError(Symbol.getAddress(), FileName);
429       if (Addr != Val)
430         continue;
431       Fmt << unwrapOrError(Symbol.getName(), FileName);
432       return;
433     }
434 
435     // If we couldn't find a symbol that this relocation refers to, try
436     // to find a section beginning instead.
437     for (const SectionRef &Section : ToolSectionFilter(*O)) {
438       uint64_t Addr = Section.getAddress();
439       if (Addr != Val)
440         continue;
441       StringRef NameOrErr = unwrapOrError(Section.getName(), O->getFileName());
442       Fmt << NameOrErr;
443       return;
444     }
445 
446     Fmt << format("0x%x", Val);
447     return;
448   }
449 
450   StringRef S;
451   bool isExtern = O->getPlainRelocationExternal(RE);
452   uint64_t Val = O->getPlainRelocationSymbolNum(RE);
453 
454   if (O->getAnyRelocationType(RE) == MachO::ARM64_RELOC_ADDEND) {
455     Fmt << format("0x%0" PRIx64, Val);
456     return;
457   }
458 
459   if (isExtern) {
460     symbol_iterator SI = O->symbol_begin();
461     advance(SI, Val);
462     S = unwrapOrError(SI->getName(), FileName);
463   } else {
464     section_iterator SI = O->section_begin();
465     // Adjust for the fact that sections are 1-indexed.
466     if (Val == 0) {
467       Fmt << "0 (?,?)";
468       return;
469     }
470     uint32_t I = Val - 1;
471     while (I != 0 && SI != O->section_end()) {
472       --I;
473       advance(SI, 1);
474     }
475     if (SI == O->section_end()) {
476       Fmt << Val << " (?,?)";
477     } else {
478       if (Expected<StringRef> NameOrErr = SI->getName())
479         S = *NameOrErr;
480       else
481         consumeError(NameOrErr.takeError());
482     }
483   }
484 
485   Fmt << S;
486 }
487 
488 Error objdump::getMachORelocationValueString(const MachOObjectFile *Obj,
489                                              const RelocationRef &RelRef,
490                                              SmallVectorImpl<char> &Result) {
491   DataRefImpl Rel = RelRef.getRawDataRefImpl();
492   MachO::any_relocation_info RE = Obj->getRelocation(Rel);
493 
494   unsigned Arch = Obj->getArch();
495 
496   std::string FmtBuf;
497   raw_string_ostream Fmt(FmtBuf);
498   unsigned Type = Obj->getAnyRelocationType(RE);
499   bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
500 
501   // Determine any addends that should be displayed with the relocation.
502   // These require decoding the relocation type, which is triple-specific.
503 
504   // X86_64 has entirely custom relocation types.
505   if (Arch == Triple::x86_64) {
506     switch (Type) {
507     case MachO::X86_64_RELOC_GOT_LOAD:
508     case MachO::X86_64_RELOC_GOT: {
509       printRelocationTargetName(Obj, RE, Fmt);
510       Fmt << "@GOT";
511       if (IsPCRel)
512         Fmt << "PCREL";
513       break;
514     }
515     case MachO::X86_64_RELOC_SUBTRACTOR: {
516       DataRefImpl RelNext = Rel;
517       Obj->moveRelocationNext(RelNext);
518       MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
519 
520       // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
521       // X86_64_RELOC_UNSIGNED.
522       // NOTE: Scattered relocations don't exist on x86_64.
523       unsigned RType = Obj->getAnyRelocationType(RENext);
524       if (RType != MachO::X86_64_RELOC_UNSIGNED)
525         reportError(Obj->getFileName(), "Expected X86_64_RELOC_UNSIGNED after "
526                                         "X86_64_RELOC_SUBTRACTOR.");
527 
528       // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
529       // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
530       printRelocationTargetName(Obj, RENext, Fmt);
531       Fmt << "-";
532       printRelocationTargetName(Obj, RE, Fmt);
533       break;
534     }
535     case MachO::X86_64_RELOC_TLV:
536       printRelocationTargetName(Obj, RE, Fmt);
537       Fmt << "@TLV";
538       if (IsPCRel)
539         Fmt << "P";
540       break;
541     case MachO::X86_64_RELOC_SIGNED_1:
542       printRelocationTargetName(Obj, RE, Fmt);
543       Fmt << "-1";
544       break;
545     case MachO::X86_64_RELOC_SIGNED_2:
546       printRelocationTargetName(Obj, RE, Fmt);
547       Fmt << "-2";
548       break;
549     case MachO::X86_64_RELOC_SIGNED_4:
550       printRelocationTargetName(Obj, RE, Fmt);
551       Fmt << "-4";
552       break;
553     default:
554       printRelocationTargetName(Obj, RE, Fmt);
555       break;
556     }
557     // X86 and ARM share some relocation types in common.
558   } else if (Arch == Triple::x86 || Arch == Triple::arm ||
559              Arch == Triple::ppc) {
560     // Generic relocation types...
561     switch (Type) {
562     case MachO::GENERIC_RELOC_PAIR: // prints no info
563       return Error::success();
564     case MachO::GENERIC_RELOC_SECTDIFF: {
565       DataRefImpl RelNext = Rel;
566       Obj->moveRelocationNext(RelNext);
567       MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
568 
569       // X86 sect diff's must be followed by a relocation of type
570       // GENERIC_RELOC_PAIR.
571       unsigned RType = Obj->getAnyRelocationType(RENext);
572 
573       if (RType != MachO::GENERIC_RELOC_PAIR)
574         reportError(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
575                                         "GENERIC_RELOC_SECTDIFF.");
576 
577       printRelocationTargetName(Obj, RE, Fmt);
578       Fmt << "-";
579       printRelocationTargetName(Obj, RENext, Fmt);
580       break;
581     }
582     }
583 
584     if (Arch == Triple::x86 || Arch == Triple::ppc) {
585       switch (Type) {
586       case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
587         DataRefImpl RelNext = Rel;
588         Obj->moveRelocationNext(RelNext);
589         MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
590 
591         // X86 sect diff's must be followed by a relocation of type
592         // GENERIC_RELOC_PAIR.
593         unsigned RType = Obj->getAnyRelocationType(RENext);
594         if (RType != MachO::GENERIC_RELOC_PAIR)
595           reportError(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
596                                           "GENERIC_RELOC_LOCAL_SECTDIFF.");
597 
598         printRelocationTargetName(Obj, RE, Fmt);
599         Fmt << "-";
600         printRelocationTargetName(Obj, RENext, Fmt);
601         break;
602       }
603       case MachO::GENERIC_RELOC_TLV: {
604         printRelocationTargetName(Obj, RE, Fmt);
605         Fmt << "@TLV";
606         if (IsPCRel)
607           Fmt << "P";
608         break;
609       }
610       default:
611         printRelocationTargetName(Obj, RE, Fmt);
612       }
613     } else { // ARM-specific relocations
614       switch (Type) {
615       case MachO::ARM_RELOC_HALF:
616       case MachO::ARM_RELOC_HALF_SECTDIFF: {
617         // Half relocations steal a bit from the length field to encode
618         // whether this is an upper16 or a lower16 relocation.
619         bool isUpper = (Obj->getAnyRelocationLength(RE) & 0x1) == 1;
620 
621         if (isUpper)
622           Fmt << ":upper16:(";
623         else
624           Fmt << ":lower16:(";
625         printRelocationTargetName(Obj, RE, Fmt);
626 
627         DataRefImpl RelNext = Rel;
628         Obj->moveRelocationNext(RelNext);
629         MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
630 
631         // ARM half relocs must be followed by a relocation of type
632         // ARM_RELOC_PAIR.
633         unsigned RType = Obj->getAnyRelocationType(RENext);
634         if (RType != MachO::ARM_RELOC_PAIR)
635           reportError(Obj->getFileName(), "Expected ARM_RELOC_PAIR after "
636                                           "ARM_RELOC_HALF");
637 
638         // NOTE: The half of the target virtual address is stashed in the
639         // address field of the secondary relocation, but we can't reverse
640         // engineer the constant offset from it without decoding the movw/movt
641         // instruction to find the other half in its immediate field.
642 
643         // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
644         // symbol/section pointer of the follow-on relocation.
645         if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
646           Fmt << "-";
647           printRelocationTargetName(Obj, RENext, Fmt);
648         }
649 
650         Fmt << ")";
651         break;
652       }
653       default: {
654         printRelocationTargetName(Obj, RE, Fmt);
655       }
656       }
657     }
658   } else
659     printRelocationTargetName(Obj, RE, Fmt);
660 
661   Fmt.flush();
662   Result.append(FmtBuf.begin(), FmtBuf.end());
663   return Error::success();
664 }
665 
666 static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
667                                      uint32_t n, uint32_t count,
668                                      uint32_t stride, uint64_t addr) {
669   MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
670   uint32_t nindirectsyms = Dysymtab.nindirectsyms;
671   if (n > nindirectsyms)
672     outs() << " (entries start past the end of the indirect symbol "
673               "table) (reserved1 field greater than the table size)";
674   else if (n + count > nindirectsyms)
675     outs() << " (entries extends past the end of the indirect symbol "
676               "table)";
677   outs() << "\n";
678   uint32_t cputype = O->getHeader().cputype;
679   if (cputype & MachO::CPU_ARCH_ABI64)
680     outs() << "address            index";
681   else
682     outs() << "address    index";
683   if (verbose)
684     outs() << " name\n";
685   else
686     outs() << "\n";
687   for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
688     if (cputype & MachO::CPU_ARCH_ABI64)
689       outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
690     else
691       outs() << format("0x%08" PRIx32, (uint32_t)addr + j * stride) << " ";
692     MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
693     uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
694     if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
695       outs() << "LOCAL\n";
696       continue;
697     }
698     if (indirect_symbol ==
699         (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
700       outs() << "LOCAL ABSOLUTE\n";
701       continue;
702     }
703     if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
704       outs() << "ABSOLUTE\n";
705       continue;
706     }
707     outs() << format("%5u ", indirect_symbol);
708     if (verbose) {
709       MachO::symtab_command Symtab = O->getSymtabLoadCommand();
710       if (indirect_symbol < Symtab.nsyms) {
711         symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
712         SymbolRef Symbol = *Sym;
713         outs() << unwrapOrError(Symbol.getName(), O->getFileName());
714       } else {
715         outs() << "?";
716       }
717     }
718     outs() << "\n";
719   }
720 }
721 
722 static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
723   for (const auto &Load : O->load_commands()) {
724     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
725       MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
726       for (unsigned J = 0; J < Seg.nsects; ++J) {
727         MachO::section_64 Sec = O->getSection64(Load, J);
728         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
729         if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
730             section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
731             section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
732             section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
733             section_type == MachO::S_SYMBOL_STUBS) {
734           uint32_t stride;
735           if (section_type == MachO::S_SYMBOL_STUBS)
736             stride = Sec.reserved2;
737           else
738             stride = 8;
739           if (stride == 0) {
740             outs() << "Can't print indirect symbols for (" << Sec.segname << ","
741                    << Sec.sectname << ") "
742                    << "(size of stubs in reserved2 field is zero)\n";
743             continue;
744           }
745           uint32_t count = Sec.size / stride;
746           outs() << "Indirect symbols for (" << Sec.segname << ","
747                  << Sec.sectname << ") " << count << " entries";
748           uint32_t n = Sec.reserved1;
749           PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
750         }
751       }
752     } else if (Load.C.cmd == MachO::LC_SEGMENT) {
753       MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
754       for (unsigned J = 0; J < Seg.nsects; ++J) {
755         MachO::section Sec = O->getSection(Load, J);
756         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
757         if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
758             section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
759             section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
760             section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
761             section_type == MachO::S_SYMBOL_STUBS) {
762           uint32_t stride;
763           if (section_type == MachO::S_SYMBOL_STUBS)
764             stride = Sec.reserved2;
765           else
766             stride = 4;
767           if (stride == 0) {
768             outs() << "Can't print indirect symbols for (" << Sec.segname << ","
769                    << Sec.sectname << ") "
770                    << "(size of stubs in reserved2 field is zero)\n";
771             continue;
772           }
773           uint32_t count = Sec.size / stride;
774           outs() << "Indirect symbols for (" << Sec.segname << ","
775                  << Sec.sectname << ") " << count << " entries";
776           uint32_t n = Sec.reserved1;
777           PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
778         }
779       }
780     }
781   }
782 }
783 
784 static void PrintRType(const uint64_t cputype, const unsigned r_type) {
785   static char const *generic_r_types[] = {
786     "VANILLA ", "PAIR    ", "SECTDIF ", "PBLAPTR ", "LOCSDIF ", "TLV     ",
787     "  6 (?) ", "  7 (?) ", "  8 (?) ", "  9 (?) ", " 10 (?) ", " 11 (?) ",
788     " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
789   };
790   static char const *x86_64_r_types[] = {
791     "UNSIGND ", "SIGNED  ", "BRANCH  ", "GOT_LD  ", "GOT     ", "SUB     ",
792     "SIGNED1 ", "SIGNED2 ", "SIGNED4 ", "TLV     ", " 10 (?) ", " 11 (?) ",
793     " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
794   };
795   static char const *arm_r_types[] = {
796     "VANILLA ", "PAIR    ", "SECTDIFF", "LOCSDIF ", "PBLAPTR ",
797     "BR24    ", "T_BR22  ", "T_BR32  ", "HALF    ", "HALFDIF ",
798     " 10 (?) ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
799   };
800   static char const *arm64_r_types[] = {
801     "UNSIGND ", "SUB     ", "BR26    ", "PAGE21  ", "PAGOF12 ",
802     "GOTLDP  ", "GOTLDPOF", "PTRTGOT ", "TLVLDP  ", "TLVLDPOF",
803     "ADDEND  ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
804   };
805 
806   if (r_type > 0xf){
807     outs() << format("%-7u", r_type) << " ";
808     return;
809   }
810   switch (cputype) {
811     case MachO::CPU_TYPE_I386:
812       outs() << generic_r_types[r_type];
813       break;
814     case MachO::CPU_TYPE_X86_64:
815       outs() << x86_64_r_types[r_type];
816       break;
817     case MachO::CPU_TYPE_ARM:
818       outs() << arm_r_types[r_type];
819       break;
820     case MachO::CPU_TYPE_ARM64:
821     case MachO::CPU_TYPE_ARM64_32:
822       outs() << arm64_r_types[r_type];
823       break;
824     default:
825       outs() << format("%-7u ", r_type);
826   }
827 }
828 
829 static void PrintRLength(const uint64_t cputype, const unsigned r_type,
830                          const unsigned r_length, const bool previous_arm_half){
831   if (cputype == MachO::CPU_TYPE_ARM &&
832       (r_type == MachO::ARM_RELOC_HALF ||
833        r_type == MachO::ARM_RELOC_HALF_SECTDIFF || previous_arm_half == true)) {
834     if ((r_length & 0x1) == 0)
835       outs() << "lo/";
836     else
837       outs() << "hi/";
838     if ((r_length & 0x1) == 0)
839       outs() << "arm ";
840     else
841       outs() << "thm ";
842   } else {
843     switch (r_length) {
844       case 0:
845         outs() << "byte   ";
846         break;
847       case 1:
848         outs() << "word   ";
849         break;
850       case 2:
851         outs() << "long   ";
852         break;
853       case 3:
854         if (cputype == MachO::CPU_TYPE_X86_64)
855           outs() << "quad   ";
856         else
857           outs() << format("?(%2d)  ", r_length);
858         break;
859       default:
860         outs() << format("?(%2d)  ", r_length);
861     }
862   }
863 }
864 
865 static void PrintRelocationEntries(const MachOObjectFile *O,
866                                    const relocation_iterator Begin,
867                                    const relocation_iterator End,
868                                    const uint64_t cputype,
869                                    const bool verbose) {
870   const MachO::symtab_command Symtab = O->getSymtabLoadCommand();
871   bool previous_arm_half = false;
872   bool previous_sectdiff = false;
873   uint32_t sectdiff_r_type = 0;
874 
875   for (relocation_iterator Reloc = Begin; Reloc != End; ++Reloc) {
876     const DataRefImpl Rel = Reloc->getRawDataRefImpl();
877     const MachO::any_relocation_info RE = O->getRelocation(Rel);
878     const unsigned r_type = O->getAnyRelocationType(RE);
879     const bool r_scattered = O->isRelocationScattered(RE);
880     const unsigned r_pcrel = O->getAnyRelocationPCRel(RE);
881     const unsigned r_length = O->getAnyRelocationLength(RE);
882     const unsigned r_address = O->getAnyRelocationAddress(RE);
883     const bool r_extern = (r_scattered ? false :
884                            O->getPlainRelocationExternal(RE));
885     const uint32_t r_value = (r_scattered ?
886                               O->getScatteredRelocationValue(RE) : 0);
887     const unsigned r_symbolnum = (r_scattered ? 0 :
888                                   O->getPlainRelocationSymbolNum(RE));
889 
890     if (r_scattered && cputype != MachO::CPU_TYPE_X86_64) {
891       if (verbose) {
892         // scattered: address
893         if ((cputype == MachO::CPU_TYPE_I386 &&
894              r_type == MachO::GENERIC_RELOC_PAIR) ||
895             (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR))
896           outs() << "         ";
897         else
898           outs() << format("%08x ", (unsigned int)r_address);
899 
900         // scattered: pcrel
901         if (r_pcrel)
902           outs() << "True  ";
903         else
904           outs() << "False ";
905 
906         // scattered: length
907         PrintRLength(cputype, r_type, r_length, previous_arm_half);
908 
909         // scattered: extern & type
910         outs() << "n/a    ";
911         PrintRType(cputype, r_type);
912 
913         // scattered: scattered & value
914         outs() << format("True      0x%08x", (unsigned int)r_value);
915         if (previous_sectdiff == false) {
916           if ((cputype == MachO::CPU_TYPE_ARM &&
917                r_type == MachO::ARM_RELOC_PAIR))
918             outs() << format(" half = 0x%04x ", (unsigned int)r_address);
919         } else if (cputype == MachO::CPU_TYPE_ARM &&
920                    sectdiff_r_type == MachO::ARM_RELOC_HALF_SECTDIFF)
921           outs() << format(" other_half = 0x%04x ", (unsigned int)r_address);
922         if ((cputype == MachO::CPU_TYPE_I386 &&
923              (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
924               r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) ||
925             (cputype == MachO::CPU_TYPE_ARM &&
926              (sectdiff_r_type == MachO::ARM_RELOC_SECTDIFF ||
927               sectdiff_r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
928               sectdiff_r_type == MachO::ARM_RELOC_HALF_SECTDIFF))) {
929           previous_sectdiff = true;
930           sectdiff_r_type = r_type;
931         } else {
932           previous_sectdiff = false;
933           sectdiff_r_type = 0;
934         }
935         if (cputype == MachO::CPU_TYPE_ARM &&
936             (r_type == MachO::ARM_RELOC_HALF ||
937              r_type == MachO::ARM_RELOC_HALF_SECTDIFF))
938           previous_arm_half = true;
939         else
940           previous_arm_half = false;
941         outs() << "\n";
942       }
943       else {
944         // scattered: address pcrel length extern type scattered value
945         outs() << format("%08x %1d     %-2d     n/a    %-7d 1         0x%08x\n",
946                          (unsigned int)r_address, r_pcrel, r_length, r_type,
947                          (unsigned int)r_value);
948       }
949     }
950     else {
951       if (verbose) {
952         // plain: address
953         if (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR)
954           outs() << "         ";
955         else
956           outs() << format("%08x ", (unsigned int)r_address);
957 
958         // plain: pcrel
959         if (r_pcrel)
960           outs() << "True  ";
961         else
962           outs() << "False ";
963 
964         // plain: length
965         PrintRLength(cputype, r_type, r_length, previous_arm_half);
966 
967         if (r_extern) {
968           // plain: extern & type & scattered
969           outs() << "True   ";
970           PrintRType(cputype, r_type);
971           outs() << "False     ";
972 
973           // plain: symbolnum/value
974           if (r_symbolnum > Symtab.nsyms)
975             outs() << format("?(%d)\n", r_symbolnum);
976           else {
977             SymbolRef Symbol = *O->getSymbolByIndex(r_symbolnum);
978             Expected<StringRef> SymNameNext = Symbol.getName();
979             const char *name = NULL;
980             if (SymNameNext)
981               name = SymNameNext->data();
982             if (name == NULL)
983               outs() << format("?(%d)\n", r_symbolnum);
984             else
985               outs() << name << "\n";
986           }
987         }
988         else {
989           // plain: extern & type & scattered
990           outs() << "False  ";
991           PrintRType(cputype, r_type);
992           outs() << "False     ";
993 
994           // plain: symbolnum/value
995           if (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR)
996             outs() << format("other_half = 0x%04x\n", (unsigned int)r_address);
997           else if ((cputype == MachO::CPU_TYPE_ARM64 ||
998                     cputype == MachO::CPU_TYPE_ARM64_32) &&
999                    r_type == MachO::ARM64_RELOC_ADDEND)
1000             outs() << format("addend = 0x%06x\n", (unsigned int)r_symbolnum);
1001           else {
1002             outs() << format("%d ", r_symbolnum);
1003             if (r_symbolnum == MachO::R_ABS)
1004               outs() << "R_ABS\n";
1005             else {
1006               // in this case, r_symbolnum is actually a 1-based section number
1007               uint32_t nsects = O->section_end()->getRawDataRefImpl().d.a;
1008               if (r_symbolnum > 0 && r_symbolnum <= nsects) {
1009                 object::DataRefImpl DRI;
1010                 DRI.d.a = r_symbolnum-1;
1011                 StringRef SegName = O->getSectionFinalSegmentName(DRI);
1012                 if (Expected<StringRef> NameOrErr = O->getSectionName(DRI))
1013                   outs() << "(" << SegName << "," << *NameOrErr << ")\n";
1014                 else
1015                   outs() << "(?,?)\n";
1016               }
1017               else {
1018                 outs() << "(?,?)\n";
1019               }
1020             }
1021           }
1022         }
1023         if (cputype == MachO::CPU_TYPE_ARM &&
1024             (r_type == MachO::ARM_RELOC_HALF ||
1025              r_type == MachO::ARM_RELOC_HALF_SECTDIFF))
1026           previous_arm_half = true;
1027         else
1028           previous_arm_half = false;
1029       }
1030       else {
1031         // plain: address pcrel length extern type scattered symbolnum/section
1032         outs() << format("%08x %1d     %-2d     %1d      %-7d 0         %d\n",
1033                          (unsigned int)r_address, r_pcrel, r_length, r_extern,
1034                          r_type, r_symbolnum);
1035       }
1036     }
1037   }
1038 }
1039 
1040 static void PrintRelocations(const MachOObjectFile *O, const bool verbose) {
1041   const uint64_t cputype = O->getHeader().cputype;
1042   const MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
1043   if (Dysymtab.nextrel != 0) {
1044     outs() << "External relocation information " << Dysymtab.nextrel
1045            << " entries";
1046     outs() << "\naddress  pcrel length extern type    scattered "
1047               "symbolnum/value\n";
1048     PrintRelocationEntries(O, O->extrel_begin(), O->extrel_end(), cputype,
1049                            verbose);
1050   }
1051   if (Dysymtab.nlocrel != 0) {
1052     outs() << format("Local relocation information %u entries",
1053                      Dysymtab.nlocrel);
1054     outs() << "\naddress  pcrel length extern type    scattered "
1055               "symbolnum/value\n";
1056     PrintRelocationEntries(O, O->locrel_begin(), O->locrel_end(), cputype,
1057                            verbose);
1058   }
1059   for (const auto &Load : O->load_commands()) {
1060     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
1061       const MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
1062       for (unsigned J = 0; J < Seg.nsects; ++J) {
1063         const MachO::section_64 Sec = O->getSection64(Load, J);
1064         if (Sec.nreloc != 0) {
1065           DataRefImpl DRI;
1066           DRI.d.a = J;
1067           const StringRef SegName = O->getSectionFinalSegmentName(DRI);
1068           if (Expected<StringRef> NameOrErr = O->getSectionName(DRI))
1069             outs() << "Relocation information (" << SegName << "," << *NameOrErr
1070                    << format(") %u entries", Sec.nreloc);
1071           else
1072             outs() << "Relocation information (" << SegName << ",?) "
1073                    << format("%u entries", Sec.nreloc);
1074           outs() << "\naddress  pcrel length extern type    scattered "
1075                     "symbolnum/value\n";
1076           PrintRelocationEntries(O, O->section_rel_begin(DRI),
1077                                  O->section_rel_end(DRI), cputype, verbose);
1078         }
1079       }
1080     } else if (Load.C.cmd == MachO::LC_SEGMENT) {
1081       const MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
1082       for (unsigned J = 0; J < Seg.nsects; ++J) {
1083         const MachO::section Sec = O->getSection(Load, J);
1084         if (Sec.nreloc != 0) {
1085           DataRefImpl DRI;
1086           DRI.d.a = J;
1087           const StringRef SegName = O->getSectionFinalSegmentName(DRI);
1088           if (Expected<StringRef> NameOrErr = O->getSectionName(DRI))
1089             outs() << "Relocation information (" << SegName << "," << *NameOrErr
1090                    << format(") %u entries", Sec.nreloc);
1091           else
1092             outs() << "Relocation information (" << SegName << ",?) "
1093                    << format("%u entries", Sec.nreloc);
1094           outs() << "\naddress  pcrel length extern type    scattered "
1095                     "symbolnum/value\n";
1096           PrintRelocationEntries(O, O->section_rel_begin(DRI),
1097                                  O->section_rel_end(DRI), cputype, verbose);
1098         }
1099       }
1100     }
1101   }
1102 }
1103 
1104 static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
1105   MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
1106   uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
1107   outs() << "Data in code table (" << nentries << " entries)\n";
1108   outs() << "offset     length kind\n";
1109   for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
1110        ++DI) {
1111     uint32_t Offset;
1112     DI->getOffset(Offset);
1113     outs() << format("0x%08" PRIx32, Offset) << " ";
1114     uint16_t Length;
1115     DI->getLength(Length);
1116     outs() << format("%6u", Length) << " ";
1117     uint16_t Kind;
1118     DI->getKind(Kind);
1119     if (verbose) {
1120       switch (Kind) {
1121       case MachO::DICE_KIND_DATA:
1122         outs() << "DATA";
1123         break;
1124       case MachO::DICE_KIND_JUMP_TABLE8:
1125         outs() << "JUMP_TABLE8";
1126         break;
1127       case MachO::DICE_KIND_JUMP_TABLE16:
1128         outs() << "JUMP_TABLE16";
1129         break;
1130       case MachO::DICE_KIND_JUMP_TABLE32:
1131         outs() << "JUMP_TABLE32";
1132         break;
1133       case MachO::DICE_KIND_ABS_JUMP_TABLE32:
1134         outs() << "ABS_JUMP_TABLE32";
1135         break;
1136       default:
1137         outs() << format("0x%04" PRIx32, Kind);
1138         break;
1139       }
1140     } else
1141       outs() << format("0x%04" PRIx32, Kind);
1142     outs() << "\n";
1143   }
1144 }
1145 
1146 static void PrintLinkOptHints(MachOObjectFile *O) {
1147   MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
1148   const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
1149   uint32_t nloh = LohLC.datasize;
1150   outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
1151   for (uint32_t i = 0; i < nloh;) {
1152     unsigned n;
1153     uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
1154     i += n;
1155     outs() << "    identifier " << identifier << " ";
1156     if (i >= nloh)
1157       return;
1158     switch (identifier) {
1159     case 1:
1160       outs() << "AdrpAdrp\n";
1161       break;
1162     case 2:
1163       outs() << "AdrpLdr\n";
1164       break;
1165     case 3:
1166       outs() << "AdrpAddLdr\n";
1167       break;
1168     case 4:
1169       outs() << "AdrpLdrGotLdr\n";
1170       break;
1171     case 5:
1172       outs() << "AdrpAddStr\n";
1173       break;
1174     case 6:
1175       outs() << "AdrpLdrGotStr\n";
1176       break;
1177     case 7:
1178       outs() << "AdrpAdd\n";
1179       break;
1180     case 8:
1181       outs() << "AdrpLdrGot\n";
1182       break;
1183     default:
1184       outs() << "Unknown identifier value\n";
1185       break;
1186     }
1187     uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
1188     i += n;
1189     outs() << "    narguments " << narguments << "\n";
1190     if (i >= nloh)
1191       return;
1192 
1193     for (uint32_t j = 0; j < narguments; j++) {
1194       uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
1195       i += n;
1196       outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
1197       if (i >= nloh)
1198         return;
1199     }
1200   }
1201 }
1202 
1203 static void PrintDylibs(MachOObjectFile *O, bool JustId) {
1204   unsigned Index = 0;
1205   for (const auto &Load : O->load_commands()) {
1206     if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
1207         (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
1208                      Load.C.cmd == MachO::LC_LOAD_DYLIB ||
1209                      Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
1210                      Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
1211                      Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
1212                      Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
1213       MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
1214       if (dl.dylib.name < dl.cmdsize) {
1215         const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
1216         if (JustId)
1217           outs() << p << "\n";
1218         else {
1219           outs() << "\t" << p;
1220           outs() << " (compatibility version "
1221                  << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
1222                  << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
1223                  << (dl.dylib.compatibility_version & 0xff) << ",";
1224           outs() << " current version "
1225                  << ((dl.dylib.current_version >> 16) & 0xffff) << "."
1226                  << ((dl.dylib.current_version >> 8) & 0xff) << "."
1227                  << (dl.dylib.current_version & 0xff);
1228           if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
1229             outs() << ", weak";
1230           if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
1231             outs() << ", reexport";
1232           if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
1233             outs() << ", upward";
1234           if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
1235             outs() << ", lazy";
1236           outs() << ")\n";
1237         }
1238       } else {
1239         outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
1240         if (Load.C.cmd == MachO::LC_ID_DYLIB)
1241           outs() << "LC_ID_DYLIB ";
1242         else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
1243           outs() << "LC_LOAD_DYLIB ";
1244         else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
1245           outs() << "LC_LOAD_WEAK_DYLIB ";
1246         else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
1247           outs() << "LC_LAZY_LOAD_DYLIB ";
1248         else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
1249           outs() << "LC_REEXPORT_DYLIB ";
1250         else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
1251           outs() << "LC_LOAD_UPWARD_DYLIB ";
1252         else
1253           outs() << "LC_??? ";
1254         outs() << "command " << Index++ << "\n";
1255       }
1256     }
1257   }
1258 }
1259 
1260 typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
1261 
1262 static void CreateSymbolAddressMap(MachOObjectFile *O,
1263                                    SymbolAddressMap *AddrMap) {
1264   // Create a map of symbol addresses to symbol names.
1265   const StringRef FileName = O->getFileName();
1266   for (const SymbolRef &Symbol : O->symbols()) {
1267     SymbolRef::Type ST = unwrapOrError(Symbol.getType(), FileName);
1268     if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
1269         ST == SymbolRef::ST_Other) {
1270       uint64_t Address = Symbol.getValue();
1271       StringRef SymName = unwrapOrError(Symbol.getName(), FileName);
1272       if (!SymName.startswith(".objc"))
1273         (*AddrMap)[Address] = SymName;
1274     }
1275   }
1276 }
1277 
1278 // GuessSymbolName is passed the address of what might be a symbol and a
1279 // pointer to the SymbolAddressMap.  It returns the name of a symbol
1280 // with that address or nullptr if no symbol is found with that address.
1281 static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
1282   const char *SymbolName = nullptr;
1283   // A DenseMap can't lookup up some values.
1284   if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
1285     StringRef name = AddrMap->lookup(value);
1286     if (!name.empty())
1287       SymbolName = name.data();
1288   }
1289   return SymbolName;
1290 }
1291 
1292 static void DumpCstringChar(const char c) {
1293   char p[2];
1294   p[0] = c;
1295   p[1] = '\0';
1296   outs().write_escaped(p);
1297 }
1298 
1299 static void DumpCstringSection(MachOObjectFile *O, const char *sect,
1300                                uint32_t sect_size, uint64_t sect_addr,
1301                                bool print_addresses) {
1302   for (uint32_t i = 0; i < sect_size; i++) {
1303     if (print_addresses) {
1304       if (O->is64Bit())
1305         outs() << format("%016" PRIx64, sect_addr + i) << "  ";
1306       else
1307         outs() << format("%08" PRIx64, sect_addr + i) << "  ";
1308     }
1309     for (; i < sect_size && sect[i] != '\0'; i++)
1310       DumpCstringChar(sect[i]);
1311     if (i < sect_size && sect[i] == '\0')
1312       outs() << "\n";
1313   }
1314 }
1315 
1316 static void DumpLiteral4(uint32_t l, float f) {
1317   outs() << format("0x%08" PRIx32, l);
1318   if ((l & 0x7f800000) != 0x7f800000)
1319     outs() << format(" (%.16e)\n", f);
1320   else {
1321     if (l == 0x7f800000)
1322       outs() << " (+Infinity)\n";
1323     else if (l == 0xff800000)
1324       outs() << " (-Infinity)\n";
1325     else if ((l & 0x00400000) == 0x00400000)
1326       outs() << " (non-signaling Not-a-Number)\n";
1327     else
1328       outs() << " (signaling Not-a-Number)\n";
1329   }
1330 }
1331 
1332 static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
1333                                 uint32_t sect_size, uint64_t sect_addr,
1334                                 bool print_addresses) {
1335   for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
1336     if (print_addresses) {
1337       if (O->is64Bit())
1338         outs() << format("%016" PRIx64, sect_addr + i) << "  ";
1339       else
1340         outs() << format("%08" PRIx64, sect_addr + i) << "  ";
1341     }
1342     float f;
1343     memcpy(&f, sect + i, sizeof(float));
1344     if (O->isLittleEndian() != sys::IsLittleEndianHost)
1345       sys::swapByteOrder(f);
1346     uint32_t l;
1347     memcpy(&l, sect + i, sizeof(uint32_t));
1348     if (O->isLittleEndian() != sys::IsLittleEndianHost)
1349       sys::swapByteOrder(l);
1350     DumpLiteral4(l, f);
1351   }
1352 }
1353 
1354 static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
1355                          double d) {
1356   outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
1357   uint32_t Hi, Lo;
1358   Hi = (O->isLittleEndian()) ? l1 : l0;
1359   Lo = (O->isLittleEndian()) ? l0 : l1;
1360 
1361   // Hi is the high word, so this is equivalent to if(isfinite(d))
1362   if ((Hi & 0x7ff00000) != 0x7ff00000)
1363     outs() << format(" (%.16e)\n", d);
1364   else {
1365     if (Hi == 0x7ff00000 && Lo == 0)
1366       outs() << " (+Infinity)\n";
1367     else if (Hi == 0xfff00000 && Lo == 0)
1368       outs() << " (-Infinity)\n";
1369     else if ((Hi & 0x00080000) == 0x00080000)
1370       outs() << " (non-signaling Not-a-Number)\n";
1371     else
1372       outs() << " (signaling Not-a-Number)\n";
1373   }
1374 }
1375 
1376 static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
1377                                 uint32_t sect_size, uint64_t sect_addr,
1378                                 bool print_addresses) {
1379   for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
1380     if (print_addresses) {
1381       if (O->is64Bit())
1382         outs() << format("%016" PRIx64, sect_addr + i) << "  ";
1383       else
1384         outs() << format("%08" PRIx64, sect_addr + i) << "  ";
1385     }
1386     double d;
1387     memcpy(&d, sect + i, sizeof(double));
1388     if (O->isLittleEndian() != sys::IsLittleEndianHost)
1389       sys::swapByteOrder(d);
1390     uint32_t l0, l1;
1391     memcpy(&l0, sect + i, sizeof(uint32_t));
1392     memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
1393     if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1394       sys::swapByteOrder(l0);
1395       sys::swapByteOrder(l1);
1396     }
1397     DumpLiteral8(O, l0, l1, d);
1398   }
1399 }
1400 
1401 static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
1402   outs() << format("0x%08" PRIx32, l0) << " ";
1403   outs() << format("0x%08" PRIx32, l1) << " ";
1404   outs() << format("0x%08" PRIx32, l2) << " ";
1405   outs() << format("0x%08" PRIx32, l3) << "\n";
1406 }
1407 
1408 static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
1409                                  uint32_t sect_size, uint64_t sect_addr,
1410                                  bool print_addresses) {
1411   for (uint32_t i = 0; i < sect_size; i += 16) {
1412     if (print_addresses) {
1413       if (O->is64Bit())
1414         outs() << format("%016" PRIx64, sect_addr + i) << "  ";
1415       else
1416         outs() << format("%08" PRIx64, sect_addr + i) << "  ";
1417     }
1418     uint32_t l0, l1, l2, l3;
1419     memcpy(&l0, sect + i, sizeof(uint32_t));
1420     memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
1421     memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
1422     memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
1423     if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1424       sys::swapByteOrder(l0);
1425       sys::swapByteOrder(l1);
1426       sys::swapByteOrder(l2);
1427       sys::swapByteOrder(l3);
1428     }
1429     DumpLiteral16(l0, l1, l2, l3);
1430   }
1431 }
1432 
1433 static void DumpLiteralPointerSection(MachOObjectFile *O,
1434                                       const SectionRef &Section,
1435                                       const char *sect, uint32_t sect_size,
1436                                       uint64_t sect_addr,
1437                                       bool print_addresses) {
1438   // Collect the literal sections in this Mach-O file.
1439   std::vector<SectionRef> LiteralSections;
1440   for (const SectionRef &Section : O->sections()) {
1441     DataRefImpl Ref = Section.getRawDataRefImpl();
1442     uint32_t section_type;
1443     if (O->is64Bit()) {
1444       const MachO::section_64 Sec = O->getSection64(Ref);
1445       section_type = Sec.flags & MachO::SECTION_TYPE;
1446     } else {
1447       const MachO::section Sec = O->getSection(Ref);
1448       section_type = Sec.flags & MachO::SECTION_TYPE;
1449     }
1450     if (section_type == MachO::S_CSTRING_LITERALS ||
1451         section_type == MachO::S_4BYTE_LITERALS ||
1452         section_type == MachO::S_8BYTE_LITERALS ||
1453         section_type == MachO::S_16BYTE_LITERALS)
1454       LiteralSections.push_back(Section);
1455   }
1456 
1457   // Set the size of the literal pointer.
1458   uint32_t lp_size = O->is64Bit() ? 8 : 4;
1459 
1460   // Collect the external relocation symbols for the literal pointers.
1461   std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1462   for (const RelocationRef &Reloc : Section.relocations()) {
1463     DataRefImpl Rel;
1464     MachO::any_relocation_info RE;
1465     bool isExtern = false;
1466     Rel = Reloc.getRawDataRefImpl();
1467     RE = O->getRelocation(Rel);
1468     isExtern = O->getPlainRelocationExternal(RE);
1469     if (isExtern) {
1470       uint64_t RelocOffset = Reloc.getOffset();
1471       symbol_iterator RelocSym = Reloc.getSymbol();
1472       Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
1473     }
1474   }
1475   array_pod_sort(Relocs.begin(), Relocs.end());
1476 
1477   // Dump each literal pointer.
1478   for (uint32_t i = 0; i < sect_size; i += lp_size) {
1479     if (print_addresses) {
1480       if (O->is64Bit())
1481         outs() << format("%016" PRIx64, sect_addr + i) << "  ";
1482       else
1483         outs() << format("%08" PRIx64, sect_addr + i) << "  ";
1484     }
1485     uint64_t lp;
1486     if (O->is64Bit()) {
1487       memcpy(&lp, sect + i, sizeof(uint64_t));
1488       if (O->isLittleEndian() != sys::IsLittleEndianHost)
1489         sys::swapByteOrder(lp);
1490     } else {
1491       uint32_t li;
1492       memcpy(&li, sect + i, sizeof(uint32_t));
1493       if (O->isLittleEndian() != sys::IsLittleEndianHost)
1494         sys::swapByteOrder(li);
1495       lp = li;
1496     }
1497 
1498     // First look for an external relocation entry for this literal pointer.
1499     auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
1500       return P.first == i;
1501     });
1502     if (Reloc != Relocs.end()) {
1503       symbol_iterator RelocSym = Reloc->second;
1504       StringRef SymName = unwrapOrError(RelocSym->getName(), O->getFileName());
1505       outs() << "external relocation entry for symbol:" << SymName << "\n";
1506       continue;
1507     }
1508 
1509     // For local references see what the section the literal pointer points to.
1510     auto Sect = find_if(LiteralSections, [&](const SectionRef &R) {
1511       return lp >= R.getAddress() && lp < R.getAddress() + R.getSize();
1512     });
1513     if (Sect == LiteralSections.end()) {
1514       outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
1515       continue;
1516     }
1517 
1518     uint64_t SectAddress = Sect->getAddress();
1519     uint64_t SectSize = Sect->getSize();
1520 
1521     StringRef SectName;
1522     Expected<StringRef> SectNameOrErr = Sect->getName();
1523     if (SectNameOrErr)
1524       SectName = *SectNameOrErr;
1525     else
1526       consumeError(SectNameOrErr.takeError());
1527 
1528     DataRefImpl Ref = Sect->getRawDataRefImpl();
1529     StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
1530     outs() << SegmentName << ":" << SectName << ":";
1531 
1532     uint32_t section_type;
1533     if (O->is64Bit()) {
1534       const MachO::section_64 Sec = O->getSection64(Ref);
1535       section_type = Sec.flags & MachO::SECTION_TYPE;
1536     } else {
1537       const MachO::section Sec = O->getSection(Ref);
1538       section_type = Sec.flags & MachO::SECTION_TYPE;
1539     }
1540 
1541     StringRef BytesStr = unwrapOrError(Sect->getContents(), O->getFileName());
1542 
1543     const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
1544 
1545     switch (section_type) {
1546     case MachO::S_CSTRING_LITERALS:
1547       for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
1548            i++) {
1549         DumpCstringChar(Contents[i]);
1550       }
1551       outs() << "\n";
1552       break;
1553     case MachO::S_4BYTE_LITERALS:
1554       float f;
1555       memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
1556       uint32_t l;
1557       memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
1558       if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1559         sys::swapByteOrder(f);
1560         sys::swapByteOrder(l);
1561       }
1562       DumpLiteral4(l, f);
1563       break;
1564     case MachO::S_8BYTE_LITERALS: {
1565       double d;
1566       memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
1567       uint32_t l0, l1;
1568       memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
1569       memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
1570              sizeof(uint32_t));
1571       if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1572         sys::swapByteOrder(f);
1573         sys::swapByteOrder(l0);
1574         sys::swapByteOrder(l1);
1575       }
1576       DumpLiteral8(O, l0, l1, d);
1577       break;
1578     }
1579     case MachO::S_16BYTE_LITERALS: {
1580       uint32_t l0, l1, l2, l3;
1581       memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
1582       memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
1583              sizeof(uint32_t));
1584       memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
1585              sizeof(uint32_t));
1586       memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
1587              sizeof(uint32_t));
1588       if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1589         sys::swapByteOrder(l0);
1590         sys::swapByteOrder(l1);
1591         sys::swapByteOrder(l2);
1592         sys::swapByteOrder(l3);
1593       }
1594       DumpLiteral16(l0, l1, l2, l3);
1595       break;
1596     }
1597     }
1598   }
1599 }
1600 
1601 static void DumpInitTermPointerSection(MachOObjectFile *O,
1602                                        const SectionRef &Section,
1603                                        const char *sect,
1604                                        uint32_t sect_size, uint64_t sect_addr,
1605                                        SymbolAddressMap *AddrMap,
1606                                        bool verbose) {
1607   uint32_t stride;
1608   stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t);
1609 
1610   // Collect the external relocation symbols for the pointers.
1611   std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1612   for (const RelocationRef &Reloc : Section.relocations()) {
1613     DataRefImpl Rel;
1614     MachO::any_relocation_info RE;
1615     bool isExtern = false;
1616     Rel = Reloc.getRawDataRefImpl();
1617     RE = O->getRelocation(Rel);
1618     isExtern = O->getPlainRelocationExternal(RE);
1619     if (isExtern) {
1620       uint64_t RelocOffset = Reloc.getOffset();
1621       symbol_iterator RelocSym = Reloc.getSymbol();
1622       Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
1623     }
1624   }
1625   array_pod_sort(Relocs.begin(), Relocs.end());
1626 
1627   for (uint32_t i = 0; i < sect_size; i += stride) {
1628     const char *SymbolName = nullptr;
1629     uint64_t p;
1630     if (O->is64Bit()) {
1631       outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
1632       uint64_t pointer_value;
1633       memcpy(&pointer_value, sect + i, stride);
1634       if (O->isLittleEndian() != sys::IsLittleEndianHost)
1635         sys::swapByteOrder(pointer_value);
1636       outs() << format("0x%016" PRIx64, pointer_value);
1637       p = pointer_value;
1638     } else {
1639       outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
1640       uint32_t pointer_value;
1641       memcpy(&pointer_value, sect + i, stride);
1642       if (O->isLittleEndian() != sys::IsLittleEndianHost)
1643         sys::swapByteOrder(pointer_value);
1644       outs() << format("0x%08" PRIx32, pointer_value);
1645       p = pointer_value;
1646     }
1647     if (verbose) {
1648       // First look for an external relocation entry for this pointer.
1649       auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
1650         return P.first == i;
1651       });
1652       if (Reloc != Relocs.end()) {
1653         symbol_iterator RelocSym = Reloc->second;
1654         outs() << " " << unwrapOrError(RelocSym->getName(), O->getFileName());
1655       } else {
1656         SymbolName = GuessSymbolName(p, AddrMap);
1657         if (SymbolName)
1658           outs() << " " << SymbolName;
1659       }
1660     }
1661     outs() << "\n";
1662   }
1663 }
1664 
1665 static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
1666                                    uint32_t size, uint64_t addr) {
1667   uint32_t cputype = O->getHeader().cputype;
1668   if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
1669     uint32_t j;
1670     for (uint32_t i = 0; i < size; i += j, addr += j) {
1671       if (O->is64Bit())
1672         outs() << format("%016" PRIx64, addr) << "\t";
1673       else
1674         outs() << format("%08" PRIx64, addr) << "\t";
1675       for (j = 0; j < 16 && i + j < size; j++) {
1676         uint8_t byte_word = *(sect + i + j);
1677         outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1678       }
1679       outs() << "\n";
1680     }
1681   } else {
1682     uint32_t j;
1683     for (uint32_t i = 0; i < size; i += j, addr += j) {
1684       if (O->is64Bit())
1685         outs() << format("%016" PRIx64, addr) << "\t";
1686       else
1687         outs() << format("%08" PRIx64, addr) << "\t";
1688       for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
1689            j += sizeof(int32_t)) {
1690         if (i + j + sizeof(int32_t) <= size) {
1691           uint32_t long_word;
1692           memcpy(&long_word, sect + i + j, sizeof(int32_t));
1693           if (O->isLittleEndian() != sys::IsLittleEndianHost)
1694             sys::swapByteOrder(long_word);
1695           outs() << format("%08" PRIx32, long_word) << " ";
1696         } else {
1697           for (uint32_t k = 0; i + j + k < size; k++) {
1698             uint8_t byte_word = *(sect + i + j + k);
1699             outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1700           }
1701         }
1702       }
1703       outs() << "\n";
1704     }
1705   }
1706 }
1707 
1708 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
1709                              StringRef DisSegName, StringRef DisSectName);
1710 static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
1711                                 uint32_t size, uint32_t addr);
1712 #ifdef HAVE_LIBXAR
1713 static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
1714                                 uint32_t size, bool verbose,
1715                                 bool PrintXarHeader, bool PrintXarFileHeaders,
1716                                 std::string XarMemberName);
1717 #endif // defined(HAVE_LIBXAR)
1718 
1719 static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
1720                                 bool verbose) {
1721   SymbolAddressMap AddrMap;
1722   if (verbose)
1723     CreateSymbolAddressMap(O, &AddrMap);
1724 
1725   for (unsigned i = 0; i < FilterSections.size(); ++i) {
1726     StringRef DumpSection = FilterSections[i];
1727     std::pair<StringRef, StringRef> DumpSegSectName;
1728     DumpSegSectName = DumpSection.split(',');
1729     StringRef DumpSegName, DumpSectName;
1730     if (!DumpSegSectName.second.empty()) {
1731       DumpSegName = DumpSegSectName.first;
1732       DumpSectName = DumpSegSectName.second;
1733     } else {
1734       DumpSegName = "";
1735       DumpSectName = DumpSegSectName.first;
1736     }
1737     for (const SectionRef &Section : O->sections()) {
1738       StringRef SectName;
1739       Expected<StringRef> SecNameOrErr = Section.getName();
1740       if (SecNameOrErr)
1741         SectName = *SecNameOrErr;
1742       else
1743         consumeError(SecNameOrErr.takeError());
1744 
1745       if (!DumpSection.empty())
1746         FoundSectionSet.insert(DumpSection);
1747 
1748       DataRefImpl Ref = Section.getRawDataRefImpl();
1749       StringRef SegName = O->getSectionFinalSegmentName(Ref);
1750       if ((DumpSegName.empty() || SegName == DumpSegName) &&
1751           (SectName == DumpSectName)) {
1752 
1753         uint32_t section_flags;
1754         if (O->is64Bit()) {
1755           const MachO::section_64 Sec = O->getSection64(Ref);
1756           section_flags = Sec.flags;
1757 
1758         } else {
1759           const MachO::section Sec = O->getSection(Ref);
1760           section_flags = Sec.flags;
1761         }
1762         uint32_t section_type = section_flags & MachO::SECTION_TYPE;
1763 
1764         StringRef BytesStr =
1765             unwrapOrError(Section.getContents(), O->getFileName());
1766         const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1767         uint32_t sect_size = BytesStr.size();
1768         uint64_t sect_addr = Section.getAddress();
1769 
1770         if (!NoLeadingHeaders)
1771           outs() << "Contents of (" << SegName << "," << SectName
1772                  << ") section\n";
1773 
1774         if (verbose) {
1775           if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1776               (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1777             DisassembleMachO(Filename, O, SegName, SectName);
1778             continue;
1779           }
1780           if (SegName == "__TEXT" && SectName == "__info_plist") {
1781             outs() << sect;
1782             continue;
1783           }
1784           if (SegName == "__OBJC" && SectName == "__protocol") {
1785             DumpProtocolSection(O, sect, sect_size, sect_addr);
1786             continue;
1787           }
1788 #ifdef HAVE_LIBXAR
1789           if (SegName == "__LLVM" && SectName == "__bundle") {
1790             DumpBitcodeSection(O, sect, sect_size, verbose, !NoSymbolicOperands,
1791                                ArchiveHeaders, "");
1792             continue;
1793           }
1794 #endif // defined(HAVE_LIBXAR)
1795           switch (section_type) {
1796           case MachO::S_REGULAR:
1797             DumpRawSectionContents(O, sect, sect_size, sect_addr);
1798             break;
1799           case MachO::S_ZEROFILL:
1800             outs() << "zerofill section and has no contents in the file\n";
1801             break;
1802           case MachO::S_CSTRING_LITERALS:
1803             DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1804             break;
1805           case MachO::S_4BYTE_LITERALS:
1806             DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1807             break;
1808           case MachO::S_8BYTE_LITERALS:
1809             DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1810             break;
1811           case MachO::S_16BYTE_LITERALS:
1812             DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1813             break;
1814           case MachO::S_LITERAL_POINTERS:
1815             DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
1816                                       !NoLeadingAddr);
1817             break;
1818           case MachO::S_MOD_INIT_FUNC_POINTERS:
1819           case MachO::S_MOD_TERM_FUNC_POINTERS:
1820             DumpInitTermPointerSection(O, Section, sect, sect_size, sect_addr,
1821                                        &AddrMap, verbose);
1822             break;
1823           default:
1824             outs() << "Unknown section type ("
1825                    << format("0x%08" PRIx32, section_type) << ")\n";
1826             DumpRawSectionContents(O, sect, sect_size, sect_addr);
1827             break;
1828           }
1829         } else {
1830           if (section_type == MachO::S_ZEROFILL)
1831             outs() << "zerofill section and has no contents in the file\n";
1832           else
1833             DumpRawSectionContents(O, sect, sect_size, sect_addr);
1834         }
1835       }
1836     }
1837   }
1838 }
1839 
1840 static void DumpInfoPlistSectionContents(StringRef Filename,
1841                                          MachOObjectFile *O) {
1842   for (const SectionRef &Section : O->sections()) {
1843     StringRef SectName;
1844     Expected<StringRef> SecNameOrErr = Section.getName();
1845     if (SecNameOrErr)
1846       SectName = *SecNameOrErr;
1847     else
1848       consumeError(SecNameOrErr.takeError());
1849 
1850     DataRefImpl Ref = Section.getRawDataRefImpl();
1851     StringRef SegName = O->getSectionFinalSegmentName(Ref);
1852     if (SegName == "__TEXT" && SectName == "__info_plist") {
1853       if (!NoLeadingHeaders)
1854         outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
1855       StringRef BytesStr =
1856           unwrapOrError(Section.getContents(), O->getFileName());
1857       const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1858       outs() << format("%.*s", BytesStr.size(), sect) << "\n";
1859       return;
1860     }
1861   }
1862 }
1863 
1864 // checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1865 // and if it is and there is a list of architecture flags is specified then
1866 // check to make sure this Mach-O file is one of those architectures or all
1867 // architectures were specified.  If not then an error is generated and this
1868 // routine returns false.  Else it returns true.
1869 static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
1870   auto *MachO = dyn_cast<MachOObjectFile>(O);
1871 
1872   if (!MachO || ArchAll || ArchFlags.empty())
1873     return true;
1874 
1875   MachO::mach_header H;
1876   MachO::mach_header_64 H_64;
1877   Triple T;
1878   const char *McpuDefault, *ArchFlag;
1879   if (MachO->is64Bit()) {
1880     H_64 = MachO->MachOObjectFile::getHeader64();
1881     T = MachOObjectFile::getArchTriple(H_64.cputype, H_64.cpusubtype,
1882                                        &McpuDefault, &ArchFlag);
1883   } else {
1884     H = MachO->MachOObjectFile::getHeader();
1885     T = MachOObjectFile::getArchTriple(H.cputype, H.cpusubtype,
1886                                        &McpuDefault, &ArchFlag);
1887   }
1888   const std::string ArchFlagName(ArchFlag);
1889   if (none_of(ArchFlags, [&](const std::string &Name) {
1890         return Name == ArchFlagName;
1891       })) {
1892     WithColor::error(errs(), "llvm-objdump")
1893         << Filename << ": no architecture specified.\n";
1894     return false;
1895   }
1896   return true;
1897 }
1898 
1899 static void printObjcMetaData(MachOObjectFile *O, bool verbose);
1900 
1901 // ProcessMachO() is passed a single opened Mach-O file, which may be an
1902 // archive member and or in a slice of a universal file.  It prints the
1903 // the file name and header info and then processes it according to the
1904 // command line options.
1905 static void ProcessMachO(StringRef Name, MachOObjectFile *MachOOF,
1906                          StringRef ArchiveMemberName = StringRef(),
1907                          StringRef ArchitectureName = StringRef()) {
1908   // If we are doing some processing here on the Mach-O file print the header
1909   // info.  And don't print it otherwise like in the case of printing the
1910   // UniversalHeaders or ArchiveHeaders.
1911   if (Disassemble || Relocations || PrivateHeaders || ExportsTrie || Rebase ||
1912       Bind || SymbolTable || LazyBind || WeakBind || IndirectSymbols ||
1913       DataInCode || LinkOptHints || DylibsUsed || DylibId || ObjcMetaData ||
1914       (!FilterSections.empty())) {
1915     if (!NoLeadingHeaders) {
1916       outs() << Name;
1917       if (!ArchiveMemberName.empty())
1918         outs() << '(' << ArchiveMemberName << ')';
1919       if (!ArchitectureName.empty())
1920         outs() << " (architecture " << ArchitectureName << ")";
1921       outs() << ":\n";
1922     }
1923   }
1924   // To use the report_error() form with an ArchiveName and FileName set
1925   // these up based on what is passed for Name and ArchiveMemberName.
1926   StringRef ArchiveName;
1927   StringRef FileName;
1928   if (!ArchiveMemberName.empty()) {
1929     ArchiveName = Name;
1930     FileName = ArchiveMemberName;
1931   } else {
1932     ArchiveName = StringRef();
1933     FileName = Name;
1934   }
1935 
1936   // If we need the symbol table to do the operation then check it here to
1937   // produce a good error message as to where the Mach-O file comes from in
1938   // the error message.
1939   if (Disassemble || IndirectSymbols || !FilterSections.empty() || UnwindInfo)
1940     if (Error Err = MachOOF->checkSymbolTable())
1941       reportError(std::move(Err), FileName, ArchiveName, ArchitectureName);
1942 
1943   if (DisassembleAll) {
1944     for (const SectionRef &Section : MachOOF->sections()) {
1945       StringRef SectName;
1946       if (Expected<StringRef> NameOrErr = Section.getName())
1947         SectName = *NameOrErr;
1948       else
1949         consumeError(NameOrErr.takeError());
1950 
1951       if (SectName.equals("__text")) {
1952         DataRefImpl Ref = Section.getRawDataRefImpl();
1953         StringRef SegName = MachOOF->getSectionFinalSegmentName(Ref);
1954         DisassembleMachO(FileName, MachOOF, SegName, SectName);
1955       }
1956     }
1957   }
1958   else if (Disassemble) {
1959     if (MachOOF->getHeader().filetype == MachO::MH_KEXT_BUNDLE &&
1960         MachOOF->getHeader().cputype == MachO::CPU_TYPE_ARM64)
1961       DisassembleMachO(FileName, MachOOF, "__TEXT_EXEC", "__text");
1962     else
1963       DisassembleMachO(FileName, MachOOF, "__TEXT", "__text");
1964   }
1965   if (IndirectSymbols)
1966     PrintIndirectSymbols(MachOOF, !NonVerbose);
1967   if (DataInCode)
1968     PrintDataInCodeTable(MachOOF, !NonVerbose);
1969   if (LinkOptHints)
1970     PrintLinkOptHints(MachOOF);
1971   if (Relocations)
1972     PrintRelocations(MachOOF, !NonVerbose);
1973   if (SectionHeaders)
1974     printSectionHeaders(MachOOF);
1975   if (SectionContents)
1976     printSectionContents(MachOOF);
1977   if (!FilterSections.empty())
1978     DumpSectionContents(FileName, MachOOF, !NonVerbose);
1979   if (InfoPlist)
1980     DumpInfoPlistSectionContents(FileName, MachOOF);
1981   if (DylibsUsed)
1982     PrintDylibs(MachOOF, false);
1983   if (DylibId)
1984     PrintDylibs(MachOOF, true);
1985   if (SymbolTable)
1986     printSymbolTable(MachOOF, ArchiveName, ArchitectureName);
1987   if (UnwindInfo)
1988     printMachOUnwindInfo(MachOOF);
1989   if (PrivateHeaders) {
1990     printMachOFileHeader(MachOOF);
1991     printMachOLoadCommands(MachOOF);
1992   }
1993   if (FirstPrivateHeader)
1994     printMachOFileHeader(MachOOF);
1995   if (ObjcMetaData)
1996     printObjcMetaData(MachOOF, !NonVerbose);
1997   if (ExportsTrie)
1998     printExportsTrie(MachOOF);
1999   if (Rebase)
2000     printRebaseTable(MachOOF);
2001   if (Bind)
2002     printBindTable(MachOOF);
2003   if (LazyBind)
2004     printLazyBindTable(MachOOF);
2005   if (WeakBind)
2006     printWeakBindTable(MachOOF);
2007 
2008   if (DwarfDumpType != DIDT_Null) {
2009     std::unique_ptr<DIContext> DICtx = DWARFContext::create(*MachOOF);
2010     // Dump the complete DWARF structure.
2011     DIDumpOptions DumpOpts;
2012     DumpOpts.DumpType = DwarfDumpType;
2013     DICtx->dump(outs(), DumpOpts);
2014   }
2015 }
2016 
2017 // printUnknownCPUType() helps print_fat_headers for unknown CPU's.
2018 static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
2019   outs() << "    cputype (" << cputype << ")\n";
2020   outs() << "    cpusubtype (" << cpusubtype << ")\n";
2021 }
2022 
2023 // printCPUType() helps print_fat_headers by printing the cputype and
2024 // pusubtype (symbolically for the one's it knows about).
2025 static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
2026   switch (cputype) {
2027   case MachO::CPU_TYPE_I386:
2028     switch (cpusubtype) {
2029     case MachO::CPU_SUBTYPE_I386_ALL:
2030       outs() << "    cputype CPU_TYPE_I386\n";
2031       outs() << "    cpusubtype CPU_SUBTYPE_I386_ALL\n";
2032       break;
2033     default:
2034       printUnknownCPUType(cputype, cpusubtype);
2035       break;
2036     }
2037     break;
2038   case MachO::CPU_TYPE_X86_64:
2039     switch (cpusubtype) {
2040     case MachO::CPU_SUBTYPE_X86_64_ALL:
2041       outs() << "    cputype CPU_TYPE_X86_64\n";
2042       outs() << "    cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
2043       break;
2044     case MachO::CPU_SUBTYPE_X86_64_H:
2045       outs() << "    cputype CPU_TYPE_X86_64\n";
2046       outs() << "    cpusubtype CPU_SUBTYPE_X86_64_H\n";
2047       break;
2048     default:
2049       printUnknownCPUType(cputype, cpusubtype);
2050       break;
2051     }
2052     break;
2053   case MachO::CPU_TYPE_ARM:
2054     switch (cpusubtype) {
2055     case MachO::CPU_SUBTYPE_ARM_ALL:
2056       outs() << "    cputype CPU_TYPE_ARM\n";
2057       outs() << "    cpusubtype CPU_SUBTYPE_ARM_ALL\n";
2058       break;
2059     case MachO::CPU_SUBTYPE_ARM_V4T:
2060       outs() << "    cputype CPU_TYPE_ARM\n";
2061       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V4T\n";
2062       break;
2063     case MachO::CPU_SUBTYPE_ARM_V5TEJ:
2064       outs() << "    cputype CPU_TYPE_ARM\n";
2065       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
2066       break;
2067     case MachO::CPU_SUBTYPE_ARM_XSCALE:
2068       outs() << "    cputype CPU_TYPE_ARM\n";
2069       outs() << "    cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
2070       break;
2071     case MachO::CPU_SUBTYPE_ARM_V6:
2072       outs() << "    cputype CPU_TYPE_ARM\n";
2073       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V6\n";
2074       break;
2075     case MachO::CPU_SUBTYPE_ARM_V6M:
2076       outs() << "    cputype CPU_TYPE_ARM\n";
2077       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V6M\n";
2078       break;
2079     case MachO::CPU_SUBTYPE_ARM_V7:
2080       outs() << "    cputype CPU_TYPE_ARM\n";
2081       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V7\n";
2082       break;
2083     case MachO::CPU_SUBTYPE_ARM_V7EM:
2084       outs() << "    cputype CPU_TYPE_ARM\n";
2085       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
2086       break;
2087     case MachO::CPU_SUBTYPE_ARM_V7K:
2088       outs() << "    cputype CPU_TYPE_ARM\n";
2089       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V7K\n";
2090       break;
2091     case MachO::CPU_SUBTYPE_ARM_V7M:
2092       outs() << "    cputype CPU_TYPE_ARM\n";
2093       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V7M\n";
2094       break;
2095     case MachO::CPU_SUBTYPE_ARM_V7S:
2096       outs() << "    cputype CPU_TYPE_ARM\n";
2097       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V7S\n";
2098       break;
2099     default:
2100       printUnknownCPUType(cputype, cpusubtype);
2101       break;
2102     }
2103     break;
2104   case MachO::CPU_TYPE_ARM64:
2105     switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2106     case MachO::CPU_SUBTYPE_ARM64_ALL:
2107       outs() << "    cputype CPU_TYPE_ARM64\n";
2108       outs() << "    cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
2109       break;
2110     case MachO::CPU_SUBTYPE_ARM64E:
2111       outs() << "    cputype CPU_TYPE_ARM64\n";
2112       outs() << "    cpusubtype CPU_SUBTYPE_ARM64E\n";
2113       break;
2114     default:
2115       printUnknownCPUType(cputype, cpusubtype);
2116       break;
2117     }
2118     break;
2119   case MachO::CPU_TYPE_ARM64_32:
2120     switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2121     case MachO::CPU_SUBTYPE_ARM64_32_V8:
2122       outs() << "    cputype CPU_TYPE_ARM64_32\n";
2123       outs() << "    cpusubtype CPU_SUBTYPE_ARM64_32_V8\n";
2124       break;
2125     default:
2126       printUnknownCPUType(cputype, cpusubtype);
2127       break;
2128     }
2129     break;
2130   default:
2131     printUnknownCPUType(cputype, cpusubtype);
2132     break;
2133   }
2134 }
2135 
2136 static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
2137                                        bool verbose) {
2138   outs() << "Fat headers\n";
2139   if (verbose) {
2140     if (UB->getMagic() == MachO::FAT_MAGIC)
2141       outs() << "fat_magic FAT_MAGIC\n";
2142     else // UB->getMagic() == MachO::FAT_MAGIC_64
2143       outs() << "fat_magic FAT_MAGIC_64\n";
2144   } else
2145     outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
2146 
2147   uint32_t nfat_arch = UB->getNumberOfObjects();
2148   StringRef Buf = UB->getData();
2149   uint64_t size = Buf.size();
2150   uint64_t big_size = sizeof(struct MachO::fat_header) +
2151                       nfat_arch * sizeof(struct MachO::fat_arch);
2152   outs() << "nfat_arch " << UB->getNumberOfObjects();
2153   if (nfat_arch == 0)
2154     outs() << " (malformed, contains zero architecture types)\n";
2155   else if (big_size > size)
2156     outs() << " (malformed, architectures past end of file)\n";
2157   else
2158     outs() << "\n";
2159 
2160   for (uint32_t i = 0; i < nfat_arch; ++i) {
2161     MachOUniversalBinary::ObjectForArch OFA(UB, i);
2162     uint32_t cputype = OFA.getCPUType();
2163     uint32_t cpusubtype = OFA.getCPUSubType();
2164     outs() << "architecture ";
2165     for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
2166       MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
2167       uint32_t other_cputype = other_OFA.getCPUType();
2168       uint32_t other_cpusubtype = other_OFA.getCPUSubType();
2169       if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
2170           (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
2171               (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
2172         outs() << "(illegal duplicate architecture) ";
2173         break;
2174       }
2175     }
2176     if (verbose) {
2177       outs() << OFA.getArchFlagName() << "\n";
2178       printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2179     } else {
2180       outs() << i << "\n";
2181       outs() << "    cputype " << cputype << "\n";
2182       outs() << "    cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
2183              << "\n";
2184     }
2185     if (verbose &&
2186         (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
2187       outs() << "    capabilities CPU_SUBTYPE_LIB64\n";
2188     else
2189       outs() << "    capabilities "
2190              << format("0x%" PRIx32,
2191                        (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
2192     outs() << "    offset " << OFA.getOffset();
2193     if (OFA.getOffset() > size)
2194       outs() << " (past end of file)";
2195     if (OFA.getOffset() % (1ull << OFA.getAlign()) != 0)
2196       outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
2197     outs() << "\n";
2198     outs() << "    size " << OFA.getSize();
2199     big_size = OFA.getOffset() + OFA.getSize();
2200     if (big_size > size)
2201       outs() << " (past end of file)";
2202     outs() << "\n";
2203     outs() << "    align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
2204            << ")\n";
2205   }
2206 }
2207 
2208 static void printArchiveChild(StringRef Filename, const Archive::Child &C,
2209                               size_t ChildIndex, bool verbose,
2210                               bool print_offset,
2211                               StringRef ArchitectureName = StringRef()) {
2212   if (print_offset)
2213     outs() << C.getChildOffset() << "\t";
2214   sys::fs::perms Mode =
2215       unwrapOrError(C.getAccessMode(), getFileNameForError(C, ChildIndex),
2216                     Filename, ArchitectureName);
2217   if (verbose) {
2218     // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
2219     // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
2220     outs() << "-";
2221     outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
2222     outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
2223     outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
2224     outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
2225     outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
2226     outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
2227     outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
2228     outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
2229     outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
2230   } else {
2231     outs() << format("0%o ", Mode);
2232   }
2233 
2234   outs() << format("%3d/%-3d %5" PRId64 " ",
2235                    unwrapOrError(C.getUID(), getFileNameForError(C, ChildIndex),
2236                                  Filename, ArchitectureName),
2237                    unwrapOrError(C.getGID(), getFileNameForError(C, ChildIndex),
2238                                  Filename, ArchitectureName),
2239                    unwrapOrError(C.getRawSize(),
2240                                  getFileNameForError(C, ChildIndex), Filename,
2241                                  ArchitectureName));
2242 
2243   StringRef RawLastModified = C.getRawLastModified();
2244   if (verbose) {
2245     unsigned Seconds;
2246     if (RawLastModified.getAsInteger(10, Seconds))
2247       outs() << "(date: \"" << RawLastModified
2248              << "\" contains non-decimal chars) ";
2249     else {
2250       // Since cime(3) returns a 26 character string of the form:
2251       // "Sun Sep 16 01:03:52 1973\n\0"
2252       // just print 24 characters.
2253       time_t t = Seconds;
2254       outs() << format("%.24s ", ctime(&t));
2255     }
2256   } else {
2257     outs() << RawLastModified << " ";
2258   }
2259 
2260   if (verbose) {
2261     Expected<StringRef> NameOrErr = C.getName();
2262     if (!NameOrErr) {
2263       consumeError(NameOrErr.takeError());
2264       outs() << unwrapOrError(C.getRawName(),
2265                               getFileNameForError(C, ChildIndex), Filename,
2266                               ArchitectureName)
2267              << "\n";
2268     } else {
2269       StringRef Name = NameOrErr.get();
2270       outs() << Name << "\n";
2271     }
2272   } else {
2273     outs() << unwrapOrError(C.getRawName(), getFileNameForError(C, ChildIndex),
2274                             Filename, ArchitectureName)
2275            << "\n";
2276   }
2277 }
2278 
2279 static void printArchiveHeaders(StringRef Filename, Archive *A, bool verbose,
2280                                 bool print_offset,
2281                                 StringRef ArchitectureName = StringRef()) {
2282   Error Err = Error::success();
2283   size_t I = 0;
2284   for (const auto &C : A->children(Err, false))
2285     printArchiveChild(Filename, C, I++, verbose, print_offset,
2286                       ArchitectureName);
2287 
2288   if (Err)
2289     reportError(std::move(Err), Filename, "", ArchitectureName);
2290 }
2291 
2292 static bool ValidateArchFlags() {
2293   // Check for -arch all and verifiy the -arch flags are valid.
2294   for (unsigned i = 0; i < ArchFlags.size(); ++i) {
2295     if (ArchFlags[i] == "all") {
2296       ArchAll = true;
2297     } else {
2298       if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
2299         WithColor::error(errs(), "llvm-objdump")
2300             << "unknown architecture named '" + ArchFlags[i] +
2301                    "'for the -arch option\n";
2302         return false;
2303       }
2304     }
2305   }
2306   return true;
2307 }
2308 
2309 // ParseInputMachO() parses the named Mach-O file in Filename and handles the
2310 // -arch flags selecting just those slices as specified by them and also parses
2311 // archive files.  Then for each individual Mach-O file ProcessMachO() is
2312 // called to process the file based on the command line options.
2313 void objdump::parseInputMachO(StringRef Filename) {
2314   if (!ValidateArchFlags())
2315     return;
2316 
2317   // Attempt to open the binary.
2318   Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
2319   if (!BinaryOrErr) {
2320     if (Error E = isNotObjectErrorInvalidFileType(BinaryOrErr.takeError()))
2321       reportError(std::move(E), Filename);
2322     else
2323       outs() << Filename << ": is not an object file\n";
2324     return;
2325   }
2326   Binary &Bin = *BinaryOrErr.get().getBinary();
2327 
2328   if (Archive *A = dyn_cast<Archive>(&Bin)) {
2329     outs() << "Archive : " << Filename << "\n";
2330     if (ArchiveHeaders)
2331       printArchiveHeaders(Filename, A, !NonVerbose, ArchiveMemberOffsets);
2332 
2333     Error Err = Error::success();
2334     unsigned I = -1;
2335     for (auto &C : A->children(Err)) {
2336       ++I;
2337       Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2338       if (!ChildOrErr) {
2339         if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2340           reportError(std::move(E), getFileNameForError(C, I), Filename);
2341         continue;
2342       }
2343       if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
2344         if (!checkMachOAndArchFlags(O, Filename))
2345           return;
2346         ProcessMachO(Filename, O, O->getFileName());
2347       }
2348     }
2349     if (Err)
2350       reportError(std::move(Err), Filename);
2351     return;
2352   }
2353   if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
2354     parseInputMachO(UB);
2355     return;
2356   }
2357   if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
2358     if (!checkMachOAndArchFlags(O, Filename))
2359       return;
2360     if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O))
2361       ProcessMachO(Filename, MachOOF);
2362     else
2363       WithColor::error(errs(), "llvm-objdump")
2364           << Filename << "': "
2365           << "object is not a Mach-O file type.\n";
2366     return;
2367   }
2368   llvm_unreachable("Input object can't be invalid at this point");
2369 }
2370 
2371 void objdump::parseInputMachO(MachOUniversalBinary *UB) {
2372   if (!ValidateArchFlags())
2373     return;
2374 
2375   auto Filename = UB->getFileName();
2376 
2377   if (UniversalHeaders)
2378     printMachOUniversalHeaders(UB, !NonVerbose);
2379 
2380   // If we have a list of architecture flags specified dump only those.
2381   if (!ArchAll && !ArchFlags.empty()) {
2382     // Look for a slice in the universal binary that matches each ArchFlag.
2383     bool ArchFound;
2384     for (unsigned i = 0; i < ArchFlags.size(); ++i) {
2385       ArchFound = false;
2386       for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2387                                                   E = UB->end_objects();
2388             I != E; ++I) {
2389         if (ArchFlags[i] == I->getArchFlagName()) {
2390           ArchFound = true;
2391           Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
2392               I->getAsObjectFile();
2393           std::string ArchitectureName = "";
2394           if (ArchFlags.size() > 1)
2395             ArchitectureName = I->getArchFlagName();
2396           if (ObjOrErr) {
2397             ObjectFile &O = *ObjOrErr.get();
2398             if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
2399               ProcessMachO(Filename, MachOOF, "", ArchitectureName);
2400           } else if (Error E = isNotObjectErrorInvalidFileType(
2401                          ObjOrErr.takeError())) {
2402             reportError(std::move(E), "", Filename, ArchitectureName);
2403             continue;
2404           } else if (Expected<std::unique_ptr<Archive>> AOrErr =
2405                          I->getAsArchive()) {
2406             std::unique_ptr<Archive> &A = *AOrErr;
2407             outs() << "Archive : " << Filename;
2408             if (!ArchitectureName.empty())
2409               outs() << " (architecture " << ArchitectureName << ")";
2410             outs() << "\n";
2411             if (ArchiveHeaders)
2412               printArchiveHeaders(Filename, A.get(), !NonVerbose,
2413                                   ArchiveMemberOffsets, ArchitectureName);
2414             Error Err = Error::success();
2415             unsigned I = -1;
2416             for (auto &C : A->children(Err)) {
2417               ++I;
2418               Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2419               if (!ChildOrErr) {
2420                 if (Error E =
2421                         isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2422                   reportError(std::move(E), getFileNameForError(C, I), Filename,
2423                               ArchitectureName);
2424                 continue;
2425               }
2426               if (MachOObjectFile *O =
2427                       dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
2428                 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
2429             }
2430             if (Err)
2431               reportError(std::move(Err), Filename);
2432           } else {
2433             consumeError(AOrErr.takeError());
2434             reportError(Filename,
2435                         "Mach-O universal file for architecture " +
2436                             StringRef(I->getArchFlagName()) +
2437                             " is not a Mach-O file or an archive file");
2438           }
2439         }
2440       }
2441       if (!ArchFound) {
2442         WithColor::error(errs(), "llvm-objdump")
2443             << "file: " + Filename + " does not contain "
2444             << "architecture: " + ArchFlags[i] + "\n";
2445         return;
2446       }
2447     }
2448     return;
2449   }
2450   // No architecture flags were specified so if this contains a slice that
2451   // matches the host architecture dump only that.
2452   if (!ArchAll) {
2453     for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2454                                                 E = UB->end_objects();
2455           I != E; ++I) {
2456       if (MachOObjectFile::getHostArch().getArchName() ==
2457           I->getArchFlagName()) {
2458         Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2459         std::string ArchiveName;
2460         ArchiveName.clear();
2461         if (ObjOrErr) {
2462           ObjectFile &O = *ObjOrErr.get();
2463           if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
2464             ProcessMachO(Filename, MachOOF);
2465         } else if (Error E =
2466                        isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) {
2467           reportError(std::move(E), Filename);
2468         } else if (Expected<std::unique_ptr<Archive>> AOrErr =
2469                        I->getAsArchive()) {
2470           std::unique_ptr<Archive> &A = *AOrErr;
2471           outs() << "Archive : " << Filename << "\n";
2472           if (ArchiveHeaders)
2473             printArchiveHeaders(Filename, A.get(), !NonVerbose,
2474                                 ArchiveMemberOffsets);
2475           Error Err = Error::success();
2476           unsigned I = -1;
2477           for (auto &C : A->children(Err)) {
2478             ++I;
2479             Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2480             if (!ChildOrErr) {
2481               if (Error E =
2482                       isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2483                 reportError(std::move(E), getFileNameForError(C, I), Filename);
2484               continue;
2485             }
2486             if (MachOObjectFile *O =
2487                     dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
2488               ProcessMachO(Filename, O, O->getFileName());
2489           }
2490           if (Err)
2491             reportError(std::move(Err), Filename);
2492         } else {
2493           consumeError(AOrErr.takeError());
2494           reportError(Filename, "Mach-O universal file for architecture " +
2495                                     StringRef(I->getArchFlagName()) +
2496                                     " is not a Mach-O file or an archive file");
2497         }
2498         return;
2499       }
2500     }
2501   }
2502   // Either all architectures have been specified or none have been specified
2503   // and this does not contain the host architecture so dump all the slices.
2504   bool moreThanOneArch = UB->getNumberOfObjects() > 1;
2505   for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2506                                               E = UB->end_objects();
2507         I != E; ++I) {
2508     Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2509     std::string ArchitectureName = "";
2510     if (moreThanOneArch)
2511       ArchitectureName = I->getArchFlagName();
2512     if (ObjOrErr) {
2513       ObjectFile &Obj = *ObjOrErr.get();
2514       if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
2515         ProcessMachO(Filename, MachOOF, "", ArchitectureName);
2516     } else if (Error E =
2517                    isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) {
2518       reportError(std::move(E), Filename, "", ArchitectureName);
2519     } else if (Expected<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
2520       std::unique_ptr<Archive> &A = *AOrErr;
2521       outs() << "Archive : " << Filename;
2522       if (!ArchitectureName.empty())
2523         outs() << " (architecture " << ArchitectureName << ")";
2524       outs() << "\n";
2525       if (ArchiveHeaders)
2526         printArchiveHeaders(Filename, A.get(), !NonVerbose,
2527                             ArchiveMemberOffsets, ArchitectureName);
2528       Error Err = Error::success();
2529       unsigned I = -1;
2530       for (auto &C : A->children(Err)) {
2531         ++I;
2532         Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2533         if (!ChildOrErr) {
2534           if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2535             reportError(std::move(E), getFileNameForError(C, I), Filename,
2536                         ArchitectureName);
2537           continue;
2538         }
2539         if (MachOObjectFile *O =
2540                 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
2541           if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
2542             ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
2543                           ArchitectureName);
2544         }
2545       }
2546       if (Err)
2547         reportError(std::move(Err), Filename);
2548     } else {
2549       consumeError(AOrErr.takeError());
2550       reportError(Filename, "Mach-O universal file for architecture " +
2551                                 StringRef(I->getArchFlagName()) +
2552                                 " is not a Mach-O file or an archive file");
2553     }
2554   }
2555 }
2556 
2557 namespace {
2558 // The block of info used by the Symbolizer call backs.
2559 struct DisassembleInfo {
2560   DisassembleInfo(MachOObjectFile *O, SymbolAddressMap *AddrMap,
2561                   std::vector<SectionRef> *Sections, bool verbose)
2562     : verbose(verbose), O(O), AddrMap(AddrMap), Sections(Sections) {}
2563   bool verbose;
2564   MachOObjectFile *O;
2565   SectionRef S;
2566   SymbolAddressMap *AddrMap;
2567   std::vector<SectionRef> *Sections;
2568   const char *class_name = nullptr;
2569   const char *selector_name = nullptr;
2570   std::unique_ptr<char[]> method = nullptr;
2571   char *demangled_name = nullptr;
2572   uint64_t adrp_addr = 0;
2573   uint32_t adrp_inst = 0;
2574   std::unique_ptr<SymbolAddressMap> bindtable;
2575   uint32_t depth = 0;
2576 };
2577 } // namespace
2578 
2579 // SymbolizerGetOpInfo() is the operand information call back function.
2580 // This is called to get the symbolic information for operand(s) of an
2581 // instruction when it is being done.  This routine does this from
2582 // the relocation information, symbol table, etc. That block of information
2583 // is a pointer to the struct DisassembleInfo that was passed when the
2584 // disassembler context was created and passed to back to here when
2585 // called back by the disassembler for instruction operands that could have
2586 // relocation information. The address of the instruction containing operand is
2587 // at the Pc parameter.  The immediate value the operand has is passed in
2588 // op_info->Value and is at Offset past the start of the instruction and has a
2589 // byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
2590 // LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
2591 // names and addends of the symbolic expression to add for the operand.  The
2592 // value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
2593 // information is returned then this function returns 1 else it returns 0.
2594 static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
2595                                uint64_t Size, int TagType, void *TagBuf) {
2596   struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
2597   struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
2598   uint64_t value = op_info->Value;
2599 
2600   // Make sure all fields returned are zero if we don't set them.
2601   memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
2602   op_info->Value = value;
2603 
2604   // If the TagType is not the value 1 which it code knows about or if no
2605   // verbose symbolic information is wanted then just return 0, indicating no
2606   // information is being returned.
2607   if (TagType != 1 || !info->verbose)
2608     return 0;
2609 
2610   unsigned int Arch = info->O->getArch();
2611   if (Arch == Triple::x86) {
2612     if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
2613       return 0;
2614     if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2615       // TODO:
2616       // Search the external relocation entries of a fully linked image
2617       // (if any) for an entry that matches this segment offset.
2618       // uint32_t seg_offset = (Pc + Offset);
2619       return 0;
2620     }
2621     // In MH_OBJECT filetypes search the section's relocation entries (if any)
2622     // for an entry for this section offset.
2623     uint32_t sect_addr = info->S.getAddress();
2624     uint32_t sect_offset = (Pc + Offset) - sect_addr;
2625     bool reloc_found = false;
2626     DataRefImpl Rel;
2627     MachO::any_relocation_info RE;
2628     bool isExtern = false;
2629     SymbolRef Symbol;
2630     bool r_scattered = false;
2631     uint32_t r_value, pair_r_value, r_type;
2632     for (const RelocationRef &Reloc : info->S.relocations()) {
2633       uint64_t RelocOffset = Reloc.getOffset();
2634       if (RelocOffset == sect_offset) {
2635         Rel = Reloc.getRawDataRefImpl();
2636         RE = info->O->getRelocation(Rel);
2637         r_type = info->O->getAnyRelocationType(RE);
2638         r_scattered = info->O->isRelocationScattered(RE);
2639         if (r_scattered) {
2640           r_value = info->O->getScatteredRelocationValue(RE);
2641           if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2642               r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
2643             DataRefImpl RelNext = Rel;
2644             info->O->moveRelocationNext(RelNext);
2645             MachO::any_relocation_info RENext;
2646             RENext = info->O->getRelocation(RelNext);
2647             if (info->O->isRelocationScattered(RENext))
2648               pair_r_value = info->O->getScatteredRelocationValue(RENext);
2649             else
2650               return 0;
2651           }
2652         } else {
2653           isExtern = info->O->getPlainRelocationExternal(RE);
2654           if (isExtern) {
2655             symbol_iterator RelocSym = Reloc.getSymbol();
2656             Symbol = *RelocSym;
2657           }
2658         }
2659         reloc_found = true;
2660         break;
2661       }
2662     }
2663     if (reloc_found && isExtern) {
2664       op_info->AddSymbol.Present = 1;
2665       op_info->AddSymbol.Name =
2666           unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
2667       // For i386 extern relocation entries the value in the instruction is
2668       // the offset from the symbol, and value is already set in op_info->Value.
2669       return 1;
2670     }
2671     if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2672                         r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
2673       const char *add = GuessSymbolName(r_value, info->AddrMap);
2674       const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
2675       uint32_t offset = value - (r_value - pair_r_value);
2676       op_info->AddSymbol.Present = 1;
2677       if (add != nullptr)
2678         op_info->AddSymbol.Name = add;
2679       else
2680         op_info->AddSymbol.Value = r_value;
2681       op_info->SubtractSymbol.Present = 1;
2682       if (sub != nullptr)
2683         op_info->SubtractSymbol.Name = sub;
2684       else
2685         op_info->SubtractSymbol.Value = pair_r_value;
2686       op_info->Value = offset;
2687       return 1;
2688     }
2689     return 0;
2690   }
2691   if (Arch == Triple::x86_64) {
2692     if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
2693       return 0;
2694     // For non MH_OBJECT types, like MH_KEXT_BUNDLE, Search the external
2695     // relocation entries of a linked image (if any) for an entry that matches
2696     // this segment offset.
2697     if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2698       uint64_t seg_offset = Pc + Offset;
2699       bool reloc_found = false;
2700       DataRefImpl Rel;
2701       MachO::any_relocation_info RE;
2702       bool isExtern = false;
2703       SymbolRef Symbol;
2704       for (const RelocationRef &Reloc : info->O->external_relocations()) {
2705         uint64_t RelocOffset = Reloc.getOffset();
2706         if (RelocOffset == seg_offset) {
2707           Rel = Reloc.getRawDataRefImpl();
2708           RE = info->O->getRelocation(Rel);
2709           // external relocation entries should always be external.
2710           isExtern = info->O->getPlainRelocationExternal(RE);
2711           if (isExtern) {
2712             symbol_iterator RelocSym = Reloc.getSymbol();
2713             Symbol = *RelocSym;
2714           }
2715           reloc_found = true;
2716           break;
2717         }
2718       }
2719       if (reloc_found && isExtern) {
2720         // The Value passed in will be adjusted by the Pc if the instruction
2721         // adds the Pc.  But for x86_64 external relocation entries the Value
2722         // is the offset from the external symbol.
2723         if (info->O->getAnyRelocationPCRel(RE))
2724           op_info->Value -= Pc + Offset + Size;
2725         const char *name =
2726             unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
2727         op_info->AddSymbol.Present = 1;
2728         op_info->AddSymbol.Name = name;
2729         return 1;
2730       }
2731       return 0;
2732     }
2733     // In MH_OBJECT filetypes search the section's relocation entries (if any)
2734     // for an entry for this section offset.
2735     uint64_t sect_addr = info->S.getAddress();
2736     uint64_t sect_offset = (Pc + Offset) - sect_addr;
2737     bool reloc_found = false;
2738     DataRefImpl Rel;
2739     MachO::any_relocation_info RE;
2740     bool isExtern = false;
2741     SymbolRef Symbol;
2742     for (const RelocationRef &Reloc : info->S.relocations()) {
2743       uint64_t RelocOffset = Reloc.getOffset();
2744       if (RelocOffset == sect_offset) {
2745         Rel = Reloc.getRawDataRefImpl();
2746         RE = info->O->getRelocation(Rel);
2747         // NOTE: Scattered relocations don't exist on x86_64.
2748         isExtern = info->O->getPlainRelocationExternal(RE);
2749         if (isExtern) {
2750           symbol_iterator RelocSym = Reloc.getSymbol();
2751           Symbol = *RelocSym;
2752         }
2753         reloc_found = true;
2754         break;
2755       }
2756     }
2757     if (reloc_found && isExtern) {
2758       // The Value passed in will be adjusted by the Pc if the instruction
2759       // adds the Pc.  But for x86_64 external relocation entries the Value
2760       // is the offset from the external symbol.
2761       if (info->O->getAnyRelocationPCRel(RE))
2762         op_info->Value -= Pc + Offset + Size;
2763       const char *name =
2764           unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
2765       unsigned Type = info->O->getAnyRelocationType(RE);
2766       if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
2767         DataRefImpl RelNext = Rel;
2768         info->O->moveRelocationNext(RelNext);
2769         MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2770         unsigned TypeNext = info->O->getAnyRelocationType(RENext);
2771         bool isExternNext = info->O->getPlainRelocationExternal(RENext);
2772         unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
2773         if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
2774           op_info->SubtractSymbol.Present = 1;
2775           op_info->SubtractSymbol.Name = name;
2776           symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
2777           Symbol = *RelocSymNext;
2778           name = unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
2779         }
2780       }
2781       // TODO: add the VariantKinds to op_info->VariantKind for relocation types
2782       // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
2783       op_info->AddSymbol.Present = 1;
2784       op_info->AddSymbol.Name = name;
2785       return 1;
2786     }
2787     return 0;
2788   }
2789   if (Arch == Triple::arm) {
2790     if (Offset != 0 || (Size != 4 && Size != 2))
2791       return 0;
2792     if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2793       // TODO:
2794       // Search the external relocation entries of a fully linked image
2795       // (if any) for an entry that matches this segment offset.
2796       // uint32_t seg_offset = (Pc + Offset);
2797       return 0;
2798     }
2799     // In MH_OBJECT filetypes search the section's relocation entries (if any)
2800     // for an entry for this section offset.
2801     uint32_t sect_addr = info->S.getAddress();
2802     uint32_t sect_offset = (Pc + Offset) - sect_addr;
2803     DataRefImpl Rel;
2804     MachO::any_relocation_info RE;
2805     bool isExtern = false;
2806     SymbolRef Symbol;
2807     bool r_scattered = false;
2808     uint32_t r_value, pair_r_value, r_type, r_length, other_half;
2809     auto Reloc =
2810         find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2811           uint64_t RelocOffset = Reloc.getOffset();
2812           return RelocOffset == sect_offset;
2813         });
2814 
2815     if (Reloc == info->S.relocations().end())
2816       return 0;
2817 
2818     Rel = Reloc->getRawDataRefImpl();
2819     RE = info->O->getRelocation(Rel);
2820     r_length = info->O->getAnyRelocationLength(RE);
2821     r_scattered = info->O->isRelocationScattered(RE);
2822     if (r_scattered) {
2823       r_value = info->O->getScatteredRelocationValue(RE);
2824       r_type = info->O->getScatteredRelocationType(RE);
2825     } else {
2826       r_type = info->O->getAnyRelocationType(RE);
2827       isExtern = info->O->getPlainRelocationExternal(RE);
2828       if (isExtern) {
2829         symbol_iterator RelocSym = Reloc->getSymbol();
2830         Symbol = *RelocSym;
2831       }
2832     }
2833     if (r_type == MachO::ARM_RELOC_HALF ||
2834         r_type == MachO::ARM_RELOC_SECTDIFF ||
2835         r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
2836         r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2837       DataRefImpl RelNext = Rel;
2838       info->O->moveRelocationNext(RelNext);
2839       MachO::any_relocation_info RENext;
2840       RENext = info->O->getRelocation(RelNext);
2841       other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
2842       if (info->O->isRelocationScattered(RENext))
2843         pair_r_value = info->O->getScatteredRelocationValue(RENext);
2844     }
2845 
2846     if (isExtern) {
2847       const char *name =
2848           unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
2849       op_info->AddSymbol.Present = 1;
2850       op_info->AddSymbol.Name = name;
2851       switch (r_type) {
2852       case MachO::ARM_RELOC_HALF:
2853         if ((r_length & 0x1) == 1) {
2854           op_info->Value = value << 16 | other_half;
2855           op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2856         } else {
2857           op_info->Value = other_half << 16 | value;
2858           op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
2859         }
2860         break;
2861       default:
2862         break;
2863       }
2864       return 1;
2865     }
2866     // If we have a branch that is not an external relocation entry then
2867     // return 0 so the code in tryAddingSymbolicOperand() can use the
2868     // SymbolLookUp call back with the branch target address to look up the
2869     // symbol and possibility add an annotation for a symbol stub.
2870     if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
2871                           r_type == MachO::ARM_THUMB_RELOC_BR22))
2872       return 0;
2873 
2874     uint32_t offset = 0;
2875     if (r_type == MachO::ARM_RELOC_HALF ||
2876         r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2877       if ((r_length & 0x1) == 1)
2878         value = value << 16 | other_half;
2879       else
2880         value = other_half << 16 | value;
2881     }
2882     if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
2883                         r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
2884       offset = value - r_value;
2885       value = r_value;
2886     }
2887 
2888     if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2889       if ((r_length & 0x1) == 1)
2890         op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2891       else
2892         op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
2893       const char *add = GuessSymbolName(r_value, info->AddrMap);
2894       const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
2895       int32_t offset = value - (r_value - pair_r_value);
2896       op_info->AddSymbol.Present = 1;
2897       if (add != nullptr)
2898         op_info->AddSymbol.Name = add;
2899       else
2900         op_info->AddSymbol.Value = r_value;
2901       op_info->SubtractSymbol.Present = 1;
2902       if (sub != nullptr)
2903         op_info->SubtractSymbol.Name = sub;
2904       else
2905         op_info->SubtractSymbol.Value = pair_r_value;
2906       op_info->Value = offset;
2907       return 1;
2908     }
2909 
2910     op_info->AddSymbol.Present = 1;
2911     op_info->Value = offset;
2912     if (r_type == MachO::ARM_RELOC_HALF) {
2913       if ((r_length & 0x1) == 1)
2914         op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2915       else
2916         op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
2917     }
2918     const char *add = GuessSymbolName(value, info->AddrMap);
2919     if (add != nullptr) {
2920       op_info->AddSymbol.Name = add;
2921       return 1;
2922     }
2923     op_info->AddSymbol.Value = value;
2924     return 1;
2925   }
2926   if (Arch == Triple::aarch64) {
2927     if (Offset != 0 || Size != 4)
2928       return 0;
2929     if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2930       // TODO:
2931       // Search the external relocation entries of a fully linked image
2932       // (if any) for an entry that matches this segment offset.
2933       // uint64_t seg_offset = (Pc + Offset);
2934       return 0;
2935     }
2936     // In MH_OBJECT filetypes search the section's relocation entries (if any)
2937     // for an entry for this section offset.
2938     uint64_t sect_addr = info->S.getAddress();
2939     uint64_t sect_offset = (Pc + Offset) - sect_addr;
2940     auto Reloc =
2941         find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2942           uint64_t RelocOffset = Reloc.getOffset();
2943           return RelocOffset == sect_offset;
2944         });
2945 
2946     if (Reloc == info->S.relocations().end())
2947       return 0;
2948 
2949     DataRefImpl Rel = Reloc->getRawDataRefImpl();
2950     MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2951     uint32_t r_type = info->O->getAnyRelocationType(RE);
2952     if (r_type == MachO::ARM64_RELOC_ADDEND) {
2953       DataRefImpl RelNext = Rel;
2954       info->O->moveRelocationNext(RelNext);
2955       MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2956       if (value == 0) {
2957         value = info->O->getPlainRelocationSymbolNum(RENext);
2958         op_info->Value = value;
2959       }
2960     }
2961     // NOTE: Scattered relocations don't exist on arm64.
2962     if (!info->O->getPlainRelocationExternal(RE))
2963       return 0;
2964     const char *name =
2965         unwrapOrError(Reloc->getSymbol()->getName(), info->O->getFileName())
2966             .data();
2967     op_info->AddSymbol.Present = 1;
2968     op_info->AddSymbol.Name = name;
2969 
2970     switch (r_type) {
2971     case MachO::ARM64_RELOC_PAGE21:
2972       /* @page */
2973       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2974       break;
2975     case MachO::ARM64_RELOC_PAGEOFF12:
2976       /* @pageoff */
2977       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2978       break;
2979     case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2980       /* @gotpage */
2981       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2982       break;
2983     case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2984       /* @gotpageoff */
2985       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2986       break;
2987     case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2988       /* @tvlppage is not implemented in llvm-mc */
2989       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2990       break;
2991     case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2992       /* @tvlppageoff is not implemented in llvm-mc */
2993       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2994       break;
2995     default:
2996     case MachO::ARM64_RELOC_BRANCH26:
2997       op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2998       break;
2999     }
3000     return 1;
3001   }
3002   return 0;
3003 }
3004 
3005 // GuessCstringPointer is passed the address of what might be a pointer to a
3006 // literal string in a cstring section.  If that address is in a cstring section
3007 // it returns a pointer to that string.  Else it returns nullptr.
3008 static const char *GuessCstringPointer(uint64_t ReferenceValue,
3009                                        struct DisassembleInfo *info) {
3010   for (const auto &Load : info->O->load_commands()) {
3011     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
3012       MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
3013       for (unsigned J = 0; J < Seg.nsects; ++J) {
3014         MachO::section_64 Sec = info->O->getSection64(Load, J);
3015         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3016         if (section_type == MachO::S_CSTRING_LITERALS &&
3017             ReferenceValue >= Sec.addr &&
3018             ReferenceValue < Sec.addr + Sec.size) {
3019           uint64_t sect_offset = ReferenceValue - Sec.addr;
3020           uint64_t object_offset = Sec.offset + sect_offset;
3021           StringRef MachOContents = info->O->getData();
3022           uint64_t object_size = MachOContents.size();
3023           const char *object_addr = (const char *)MachOContents.data();
3024           if (object_offset < object_size) {
3025             const char *name = object_addr + object_offset;
3026             return name;
3027           } else {
3028             return nullptr;
3029           }
3030         }
3031       }
3032     } else if (Load.C.cmd == MachO::LC_SEGMENT) {
3033       MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
3034       for (unsigned J = 0; J < Seg.nsects; ++J) {
3035         MachO::section Sec = info->O->getSection(Load, J);
3036         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3037         if (section_type == MachO::S_CSTRING_LITERALS &&
3038             ReferenceValue >= Sec.addr &&
3039             ReferenceValue < Sec.addr + Sec.size) {
3040           uint64_t sect_offset = ReferenceValue - Sec.addr;
3041           uint64_t object_offset = Sec.offset + sect_offset;
3042           StringRef MachOContents = info->O->getData();
3043           uint64_t object_size = MachOContents.size();
3044           const char *object_addr = (const char *)MachOContents.data();
3045           if (object_offset < object_size) {
3046             const char *name = object_addr + object_offset;
3047             return name;
3048           } else {
3049             return nullptr;
3050           }
3051         }
3052       }
3053     }
3054   }
3055   return nullptr;
3056 }
3057 
3058 // GuessIndirectSymbol returns the name of the indirect symbol for the
3059 // ReferenceValue passed in or nullptr.  This is used when ReferenceValue maybe
3060 // an address of a symbol stub or a lazy or non-lazy pointer to associate the
3061 // symbol name being referenced by the stub or pointer.
3062 static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
3063                                        struct DisassembleInfo *info) {
3064   MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
3065   MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
3066   for (const auto &Load : info->O->load_commands()) {
3067     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
3068       MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
3069       for (unsigned J = 0; J < Seg.nsects; ++J) {
3070         MachO::section_64 Sec = info->O->getSection64(Load, J);
3071         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3072         if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
3073              section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
3074              section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
3075              section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
3076              section_type == MachO::S_SYMBOL_STUBS) &&
3077             ReferenceValue >= Sec.addr &&
3078             ReferenceValue < Sec.addr + Sec.size) {
3079           uint32_t stride;
3080           if (section_type == MachO::S_SYMBOL_STUBS)
3081             stride = Sec.reserved2;
3082           else
3083             stride = 8;
3084           if (stride == 0)
3085             return nullptr;
3086           uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
3087           if (index < Dysymtab.nindirectsyms) {
3088             uint32_t indirect_symbol =
3089                 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
3090             if (indirect_symbol < Symtab.nsyms) {
3091               symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
3092               return unwrapOrError(Sym->getName(), info->O->getFileName())
3093                   .data();
3094             }
3095           }
3096         }
3097       }
3098     } else if (Load.C.cmd == MachO::LC_SEGMENT) {
3099       MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
3100       for (unsigned J = 0; J < Seg.nsects; ++J) {
3101         MachO::section Sec = info->O->getSection(Load, J);
3102         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3103         if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
3104              section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
3105              section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
3106              section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
3107              section_type == MachO::S_SYMBOL_STUBS) &&
3108             ReferenceValue >= Sec.addr &&
3109             ReferenceValue < Sec.addr + Sec.size) {
3110           uint32_t stride;
3111           if (section_type == MachO::S_SYMBOL_STUBS)
3112             stride = Sec.reserved2;
3113           else
3114             stride = 4;
3115           if (stride == 0)
3116             return nullptr;
3117           uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
3118           if (index < Dysymtab.nindirectsyms) {
3119             uint32_t indirect_symbol =
3120                 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
3121             if (indirect_symbol < Symtab.nsyms) {
3122               symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
3123               return unwrapOrError(Sym->getName(), info->O->getFileName())
3124                   .data();
3125             }
3126           }
3127         }
3128       }
3129     }
3130   }
3131   return nullptr;
3132 }
3133 
3134 // method_reference() is called passing it the ReferenceName that might be
3135 // a reference it to an Objective-C method call.  If so then it allocates and
3136 // assembles a method call string with the values last seen and saved in
3137 // the DisassembleInfo's class_name and selector_name fields.  This is saved
3138 // into the method field of the info and any previous string is free'ed.
3139 // Then the class_name field in the info is set to nullptr.  The method call
3140 // string is set into ReferenceName and ReferenceType is set to
3141 // LLVMDisassembler_ReferenceType_Out_Objc_Message.  If this not a method call
3142 // then both ReferenceType and ReferenceName are left unchanged.
3143 static void method_reference(struct DisassembleInfo *info,
3144                              uint64_t *ReferenceType,
3145                              const char **ReferenceName) {
3146   unsigned int Arch = info->O->getArch();
3147   if (*ReferenceName != nullptr) {
3148     if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
3149       if (info->selector_name != nullptr) {
3150         if (info->class_name != nullptr) {
3151           info->method = std::make_unique<char[]>(
3152               5 + strlen(info->class_name) + strlen(info->selector_name));
3153           char *method = info->method.get();
3154           if (method != nullptr) {
3155             strcpy(method, "+[");
3156             strcat(method, info->class_name);
3157             strcat(method, " ");
3158             strcat(method, info->selector_name);
3159             strcat(method, "]");
3160             *ReferenceName = method;
3161             *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3162           }
3163         } else {
3164           info->method =
3165               std::make_unique<char[]>(9 + strlen(info->selector_name));
3166           char *method = info->method.get();
3167           if (method != nullptr) {
3168             if (Arch == Triple::x86_64)
3169               strcpy(method, "-[%rdi ");
3170             else if (Arch == Triple::aarch64)
3171               strcpy(method, "-[x0 ");
3172             else
3173               strcpy(method, "-[r? ");
3174             strcat(method, info->selector_name);
3175             strcat(method, "]");
3176             *ReferenceName = method;
3177             *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3178           }
3179         }
3180         info->class_name = nullptr;
3181       }
3182     } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
3183       if (info->selector_name != nullptr) {
3184         info->method =
3185             std::make_unique<char[]>(17 + strlen(info->selector_name));
3186         char *method = info->method.get();
3187         if (method != nullptr) {
3188           if (Arch == Triple::x86_64)
3189             strcpy(method, "-[[%rdi super] ");
3190           else if (Arch == Triple::aarch64)
3191             strcpy(method, "-[[x0 super] ");
3192           else
3193             strcpy(method, "-[[r? super] ");
3194           strcat(method, info->selector_name);
3195           strcat(method, "]");
3196           *ReferenceName = method;
3197           *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3198         }
3199         info->class_name = nullptr;
3200       }
3201     }
3202   }
3203 }
3204 
3205 // GuessPointerPointer() is passed the address of what might be a pointer to
3206 // a reference to an Objective-C class, selector, message ref or cfstring.
3207 // If so the value of the pointer is returned and one of the booleans are set
3208 // to true.  If not zero is returned and all the booleans are set to false.
3209 static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
3210                                     struct DisassembleInfo *info,
3211                                     bool &classref, bool &selref, bool &msgref,
3212                                     bool &cfstring) {
3213   classref = false;
3214   selref = false;
3215   msgref = false;
3216   cfstring = false;
3217   for (const auto &Load : info->O->load_commands()) {
3218     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
3219       MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
3220       for (unsigned J = 0; J < Seg.nsects; ++J) {
3221         MachO::section_64 Sec = info->O->getSection64(Load, J);
3222         if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
3223              strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
3224              strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
3225              strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
3226              strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
3227             ReferenceValue >= Sec.addr &&
3228             ReferenceValue < Sec.addr + Sec.size) {
3229           uint64_t sect_offset = ReferenceValue - Sec.addr;
3230           uint64_t object_offset = Sec.offset + sect_offset;
3231           StringRef MachOContents = info->O->getData();
3232           uint64_t object_size = MachOContents.size();
3233           const char *object_addr = (const char *)MachOContents.data();
3234           if (object_offset < object_size) {
3235             uint64_t pointer_value;
3236             memcpy(&pointer_value, object_addr + object_offset,
3237                    sizeof(uint64_t));
3238             if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3239               sys::swapByteOrder(pointer_value);
3240             if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
3241               selref = true;
3242             else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
3243                      strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
3244               classref = true;
3245             else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
3246                      ReferenceValue + 8 < Sec.addr + Sec.size) {
3247               msgref = true;
3248               memcpy(&pointer_value, object_addr + object_offset + 8,
3249                      sizeof(uint64_t));
3250               if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3251                 sys::swapByteOrder(pointer_value);
3252             } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
3253               cfstring = true;
3254             return pointer_value;
3255           } else {
3256             return 0;
3257           }
3258         }
3259       }
3260     }
3261     // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
3262   }
3263   return 0;
3264 }
3265 
3266 // get_pointer_64 returns a pointer to the bytes in the object file at the
3267 // Address from a section in the Mach-O file.  And indirectly returns the
3268 // offset into the section, number of bytes left in the section past the offset
3269 // and which section is was being referenced.  If the Address is not in a
3270 // section nullptr is returned.
3271 static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
3272                                   uint32_t &left, SectionRef &S,
3273                                   DisassembleInfo *info,
3274                                   bool objc_only = false) {
3275   offset = 0;
3276   left = 0;
3277   S = SectionRef();
3278   for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
3279     uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
3280     uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
3281     if (SectSize == 0)
3282       continue;
3283     if (objc_only) {
3284       StringRef SectName;
3285       Expected<StringRef> SecNameOrErr =
3286           ((*(info->Sections))[SectIdx]).getName();
3287       if (SecNameOrErr)
3288         SectName = *SecNameOrErr;
3289       else
3290         consumeError(SecNameOrErr.takeError());
3291 
3292       DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
3293       StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
3294       if (SegName != "__OBJC" && SectName != "__cstring")
3295         continue;
3296     }
3297     if (Address >= SectAddress && Address < SectAddress + SectSize) {
3298       S = (*(info->Sections))[SectIdx];
3299       offset = Address - SectAddress;
3300       left = SectSize - offset;
3301       StringRef SectContents = unwrapOrError(
3302           ((*(info->Sections))[SectIdx]).getContents(), info->O->getFileName());
3303       return SectContents.data() + offset;
3304     }
3305   }
3306   return nullptr;
3307 }
3308 
3309 static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
3310                                   uint32_t &left, SectionRef &S,
3311                                   DisassembleInfo *info,
3312                                   bool objc_only = false) {
3313   return get_pointer_64(Address, offset, left, S, info, objc_only);
3314 }
3315 
3316 // get_symbol_64() returns the name of a symbol (or nullptr) and the address of
3317 // the symbol indirectly through n_value. Based on the relocation information
3318 // for the specified section offset in the specified section reference.
3319 // If no relocation information is found and a non-zero ReferenceValue for the
3320 // symbol is passed, look up that address in the info's AddrMap.
3321 static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
3322                                  DisassembleInfo *info, uint64_t &n_value,
3323                                  uint64_t ReferenceValue = 0) {
3324   n_value = 0;
3325   if (!info->verbose)
3326     return nullptr;
3327 
3328   // See if there is an external relocation entry at the sect_offset.
3329   bool reloc_found = false;
3330   DataRefImpl Rel;
3331   MachO::any_relocation_info RE;
3332   bool isExtern = false;
3333   SymbolRef Symbol;
3334   for (const RelocationRef &Reloc : S.relocations()) {
3335     uint64_t RelocOffset = Reloc.getOffset();
3336     if (RelocOffset == sect_offset) {
3337       Rel = Reloc.getRawDataRefImpl();
3338       RE = info->O->getRelocation(Rel);
3339       if (info->O->isRelocationScattered(RE))
3340         continue;
3341       isExtern = info->O->getPlainRelocationExternal(RE);
3342       if (isExtern) {
3343         symbol_iterator RelocSym = Reloc.getSymbol();
3344         Symbol = *RelocSym;
3345       }
3346       reloc_found = true;
3347       break;
3348     }
3349   }
3350   // If there is an external relocation entry for a symbol in this section
3351   // at this section_offset then use that symbol's value for the n_value
3352   // and return its name.
3353   const char *SymbolName = nullptr;
3354   if (reloc_found && isExtern) {
3355     n_value = Symbol.getValue();
3356     StringRef Name = unwrapOrError(Symbol.getName(), info->O->getFileName());
3357     if (!Name.empty()) {
3358       SymbolName = Name.data();
3359       return SymbolName;
3360     }
3361   }
3362 
3363   // TODO: For fully linked images, look through the external relocation
3364   // entries off the dynamic symtab command. For these the r_offset is from the
3365   // start of the first writeable segment in the Mach-O file.  So the offset
3366   // to this section from that segment is passed to this routine by the caller,
3367   // as the database_offset. Which is the difference of the section's starting
3368   // address and the first writable segment.
3369   //
3370   // NOTE: need add passing the database_offset to this routine.
3371 
3372   // We did not find an external relocation entry so look up the ReferenceValue
3373   // as an address of a symbol and if found return that symbol's name.
3374   SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
3375 
3376   return SymbolName;
3377 }
3378 
3379 static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
3380                                  DisassembleInfo *info,
3381                                  uint32_t ReferenceValue) {
3382   uint64_t n_value64;
3383   return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
3384 }
3385 
3386 namespace {
3387 
3388 // These are structs in the Objective-C meta data and read to produce the
3389 // comments for disassembly.  While these are part of the ABI they are no
3390 // public defintions.  So the are here not in include/llvm/BinaryFormat/MachO.h
3391 // .
3392 
3393 // The cfstring object in a 64-bit Mach-O file.
3394 struct cfstring64_t {
3395   uint64_t isa;        // class64_t * (64-bit pointer)
3396   uint64_t flags;      // flag bits
3397   uint64_t characters; // char * (64-bit pointer)
3398   uint64_t length;     // number of non-NULL characters in above
3399 };
3400 
3401 // The class object in a 64-bit Mach-O file.
3402 struct class64_t {
3403   uint64_t isa;        // class64_t * (64-bit pointer)
3404   uint64_t superclass; // class64_t * (64-bit pointer)
3405   uint64_t cache;      // Cache (64-bit pointer)
3406   uint64_t vtable;     // IMP * (64-bit pointer)
3407   uint64_t data;       // class_ro64_t * (64-bit pointer)
3408 };
3409 
3410 struct class32_t {
3411   uint32_t isa;        /* class32_t * (32-bit pointer) */
3412   uint32_t superclass; /* class32_t * (32-bit pointer) */
3413   uint32_t cache;      /* Cache (32-bit pointer) */
3414   uint32_t vtable;     /* IMP * (32-bit pointer) */
3415   uint32_t data;       /* class_ro32_t * (32-bit pointer) */
3416 };
3417 
3418 struct class_ro64_t {
3419   uint32_t flags;
3420   uint32_t instanceStart;
3421   uint32_t instanceSize;
3422   uint32_t reserved;
3423   uint64_t ivarLayout;     // const uint8_t * (64-bit pointer)
3424   uint64_t name;           // const char * (64-bit pointer)
3425   uint64_t baseMethods;    // const method_list_t * (64-bit pointer)
3426   uint64_t baseProtocols;  // const protocol_list_t * (64-bit pointer)
3427   uint64_t ivars;          // const ivar_list_t * (64-bit pointer)
3428   uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
3429   uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
3430 };
3431 
3432 struct class_ro32_t {
3433   uint32_t flags;
3434   uint32_t instanceStart;
3435   uint32_t instanceSize;
3436   uint32_t ivarLayout;     /* const uint8_t * (32-bit pointer) */
3437   uint32_t name;           /* const char * (32-bit pointer) */
3438   uint32_t baseMethods;    /* const method_list_t * (32-bit pointer) */
3439   uint32_t baseProtocols;  /* const protocol_list_t * (32-bit pointer) */
3440   uint32_t ivars;          /* const ivar_list_t * (32-bit pointer) */
3441   uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
3442   uint32_t baseProperties; /* const struct objc_property_list *
3443                                                    (32-bit pointer) */
3444 };
3445 
3446 /* Values for class_ro{64,32}_t->flags */
3447 #define RO_META (1 << 0)
3448 #define RO_ROOT (1 << 1)
3449 #define RO_HAS_CXX_STRUCTORS (1 << 2)
3450 
3451 struct method_list64_t {
3452   uint32_t entsize;
3453   uint32_t count;
3454   /* struct method64_t first;  These structures follow inline */
3455 };
3456 
3457 struct method_list32_t {
3458   uint32_t entsize;
3459   uint32_t count;
3460   /* struct method32_t first;  These structures follow inline */
3461 };
3462 
3463 struct method64_t {
3464   uint64_t name;  /* SEL (64-bit pointer) */
3465   uint64_t types; /* const char * (64-bit pointer) */
3466   uint64_t imp;   /* IMP (64-bit pointer) */
3467 };
3468 
3469 struct method32_t {
3470   uint32_t name;  /* SEL (32-bit pointer) */
3471   uint32_t types; /* const char * (32-bit pointer) */
3472   uint32_t imp;   /* IMP (32-bit pointer) */
3473 };
3474 
3475 struct protocol_list64_t {
3476   uint64_t count; /* uintptr_t (a 64-bit value) */
3477   /* struct protocol64_t * list[0];  These pointers follow inline */
3478 };
3479 
3480 struct protocol_list32_t {
3481   uint32_t count; /* uintptr_t (a 32-bit value) */
3482   /* struct protocol32_t * list[0];  These pointers follow inline */
3483 };
3484 
3485 struct protocol64_t {
3486   uint64_t isa;                     /* id * (64-bit pointer) */
3487   uint64_t name;                    /* const char * (64-bit pointer) */
3488   uint64_t protocols;               /* struct protocol_list64_t *
3489                                                     (64-bit pointer) */
3490   uint64_t instanceMethods;         /* method_list_t * (64-bit pointer) */
3491   uint64_t classMethods;            /* method_list_t * (64-bit pointer) */
3492   uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
3493   uint64_t optionalClassMethods;    /* method_list_t * (64-bit pointer) */
3494   uint64_t instanceProperties;      /* struct objc_property_list *
3495                                                        (64-bit pointer) */
3496 };
3497 
3498 struct protocol32_t {
3499   uint32_t isa;                     /* id * (32-bit pointer) */
3500   uint32_t name;                    /* const char * (32-bit pointer) */
3501   uint32_t protocols;               /* struct protocol_list_t *
3502                                                     (32-bit pointer) */
3503   uint32_t instanceMethods;         /* method_list_t * (32-bit pointer) */
3504   uint32_t classMethods;            /* method_list_t * (32-bit pointer) */
3505   uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
3506   uint32_t optionalClassMethods;    /* method_list_t * (32-bit pointer) */
3507   uint32_t instanceProperties;      /* struct objc_property_list *
3508                                                        (32-bit pointer) */
3509 };
3510 
3511 struct ivar_list64_t {
3512   uint32_t entsize;
3513   uint32_t count;
3514   /* struct ivar64_t first;  These structures follow inline */
3515 };
3516 
3517 struct ivar_list32_t {
3518   uint32_t entsize;
3519   uint32_t count;
3520   /* struct ivar32_t first;  These structures follow inline */
3521 };
3522 
3523 struct ivar64_t {
3524   uint64_t offset; /* uintptr_t * (64-bit pointer) */
3525   uint64_t name;   /* const char * (64-bit pointer) */
3526   uint64_t type;   /* const char * (64-bit pointer) */
3527   uint32_t alignment;
3528   uint32_t size;
3529 };
3530 
3531 struct ivar32_t {
3532   uint32_t offset; /* uintptr_t * (32-bit pointer) */
3533   uint32_t name;   /* const char * (32-bit pointer) */
3534   uint32_t type;   /* const char * (32-bit pointer) */
3535   uint32_t alignment;
3536   uint32_t size;
3537 };
3538 
3539 struct objc_property_list64 {
3540   uint32_t entsize;
3541   uint32_t count;
3542   /* struct objc_property64 first;  These structures follow inline */
3543 };
3544 
3545 struct objc_property_list32 {
3546   uint32_t entsize;
3547   uint32_t count;
3548   /* struct objc_property32 first;  These structures follow inline */
3549 };
3550 
3551 struct objc_property64 {
3552   uint64_t name;       /* const char * (64-bit pointer) */
3553   uint64_t attributes; /* const char * (64-bit pointer) */
3554 };
3555 
3556 struct objc_property32 {
3557   uint32_t name;       /* const char * (32-bit pointer) */
3558   uint32_t attributes; /* const char * (32-bit pointer) */
3559 };
3560 
3561 struct category64_t {
3562   uint64_t name;               /* const char * (64-bit pointer) */
3563   uint64_t cls;                /* struct class_t * (64-bit pointer) */
3564   uint64_t instanceMethods;    /* struct method_list_t * (64-bit pointer) */
3565   uint64_t classMethods;       /* struct method_list_t * (64-bit pointer) */
3566   uint64_t protocols;          /* struct protocol_list_t * (64-bit pointer) */
3567   uint64_t instanceProperties; /* struct objc_property_list *
3568                                   (64-bit pointer) */
3569 };
3570 
3571 struct category32_t {
3572   uint32_t name;               /* const char * (32-bit pointer) */
3573   uint32_t cls;                /* struct class_t * (32-bit pointer) */
3574   uint32_t instanceMethods;    /* struct method_list_t * (32-bit pointer) */
3575   uint32_t classMethods;       /* struct method_list_t * (32-bit pointer) */
3576   uint32_t protocols;          /* struct protocol_list_t * (32-bit pointer) */
3577   uint32_t instanceProperties; /* struct objc_property_list *
3578                                   (32-bit pointer) */
3579 };
3580 
3581 struct objc_image_info64 {
3582   uint32_t version;
3583   uint32_t flags;
3584 };
3585 struct objc_image_info32 {
3586   uint32_t version;
3587   uint32_t flags;
3588 };
3589 struct imageInfo_t {
3590   uint32_t version;
3591   uint32_t flags;
3592 };
3593 /* masks for objc_image_info.flags */
3594 #define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
3595 #define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
3596 #define OBJC_IMAGE_IS_SIMULATED (1 << 5)
3597 #define OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES (1 << 6)
3598 
3599 struct message_ref64 {
3600   uint64_t imp; /* IMP (64-bit pointer) */
3601   uint64_t sel; /* SEL (64-bit pointer) */
3602 };
3603 
3604 struct message_ref32 {
3605   uint32_t imp; /* IMP (32-bit pointer) */
3606   uint32_t sel; /* SEL (32-bit pointer) */
3607 };
3608 
3609 // Objective-C 1 (32-bit only) meta data structs.
3610 
3611 struct objc_module_t {
3612   uint32_t version;
3613   uint32_t size;
3614   uint32_t name;   /* char * (32-bit pointer) */
3615   uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
3616 };
3617 
3618 struct objc_symtab_t {
3619   uint32_t sel_ref_cnt;
3620   uint32_t refs; /* SEL * (32-bit pointer) */
3621   uint16_t cls_def_cnt;
3622   uint16_t cat_def_cnt;
3623   // uint32_t defs[1];        /* void * (32-bit pointer) variable size */
3624 };
3625 
3626 struct objc_class_t {
3627   uint32_t isa;         /* struct objc_class * (32-bit pointer) */
3628   uint32_t super_class; /* struct objc_class * (32-bit pointer) */
3629   uint32_t name;        /* const char * (32-bit pointer) */
3630   int32_t version;
3631   int32_t info;
3632   int32_t instance_size;
3633   uint32_t ivars;       /* struct objc_ivar_list * (32-bit pointer) */
3634   uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
3635   uint32_t cache;       /* struct objc_cache * (32-bit pointer) */
3636   uint32_t protocols;   /* struct objc_protocol_list * (32-bit pointer) */
3637 };
3638 
3639 #define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
3640 // class is not a metaclass
3641 #define CLS_CLASS 0x1
3642 // class is a metaclass
3643 #define CLS_META 0x2
3644 
3645 struct objc_category_t {
3646   uint32_t category_name;    /* char * (32-bit pointer) */
3647   uint32_t class_name;       /* char * (32-bit pointer) */
3648   uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
3649   uint32_t class_methods;    /* struct objc_method_list * (32-bit pointer) */
3650   uint32_t protocols;        /* struct objc_protocol_list * (32-bit ptr) */
3651 };
3652 
3653 struct objc_ivar_t {
3654   uint32_t ivar_name; /* char * (32-bit pointer) */
3655   uint32_t ivar_type; /* char * (32-bit pointer) */
3656   int32_t ivar_offset;
3657 };
3658 
3659 struct objc_ivar_list_t {
3660   int32_t ivar_count;
3661   // struct objc_ivar_t ivar_list[1];          /* variable length structure */
3662 };
3663 
3664 struct objc_method_list_t {
3665   uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
3666   int32_t method_count;
3667   // struct objc_method_t method_list[1];      /* variable length structure */
3668 };
3669 
3670 struct objc_method_t {
3671   uint32_t method_name;  /* SEL, aka struct objc_selector * (32-bit pointer) */
3672   uint32_t method_types; /* char * (32-bit pointer) */
3673   uint32_t method_imp;   /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
3674                             (32-bit pointer) */
3675 };
3676 
3677 struct objc_protocol_list_t {
3678   uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
3679   int32_t count;
3680   // uint32_t list[1];   /* Protocol *, aka struct objc_protocol_t *
3681   //                        (32-bit pointer) */
3682 };
3683 
3684 struct objc_protocol_t {
3685   uint32_t isa;              /* struct objc_class * (32-bit pointer) */
3686   uint32_t protocol_name;    /* char * (32-bit pointer) */
3687   uint32_t protocol_list;    /* struct objc_protocol_list * (32-bit pointer) */
3688   uint32_t instance_methods; /* struct objc_method_description_list *
3689                                 (32-bit pointer) */
3690   uint32_t class_methods;    /* struct objc_method_description_list *
3691                                 (32-bit pointer) */
3692 };
3693 
3694 struct objc_method_description_list_t {
3695   int32_t count;
3696   // struct objc_method_description_t list[1];
3697 };
3698 
3699 struct objc_method_description_t {
3700   uint32_t name;  /* SEL, aka struct objc_selector * (32-bit pointer) */
3701   uint32_t types; /* char * (32-bit pointer) */
3702 };
3703 
3704 inline void swapStruct(struct cfstring64_t &cfs) {
3705   sys::swapByteOrder(cfs.isa);
3706   sys::swapByteOrder(cfs.flags);
3707   sys::swapByteOrder(cfs.characters);
3708   sys::swapByteOrder(cfs.length);
3709 }
3710 
3711 inline void swapStruct(struct class64_t &c) {
3712   sys::swapByteOrder(c.isa);
3713   sys::swapByteOrder(c.superclass);
3714   sys::swapByteOrder(c.cache);
3715   sys::swapByteOrder(c.vtable);
3716   sys::swapByteOrder(c.data);
3717 }
3718 
3719 inline void swapStruct(struct class32_t &c) {
3720   sys::swapByteOrder(c.isa);
3721   sys::swapByteOrder(c.superclass);
3722   sys::swapByteOrder(c.cache);
3723   sys::swapByteOrder(c.vtable);
3724   sys::swapByteOrder(c.data);
3725 }
3726 
3727 inline void swapStruct(struct class_ro64_t &cro) {
3728   sys::swapByteOrder(cro.flags);
3729   sys::swapByteOrder(cro.instanceStart);
3730   sys::swapByteOrder(cro.instanceSize);
3731   sys::swapByteOrder(cro.reserved);
3732   sys::swapByteOrder(cro.ivarLayout);
3733   sys::swapByteOrder(cro.name);
3734   sys::swapByteOrder(cro.baseMethods);
3735   sys::swapByteOrder(cro.baseProtocols);
3736   sys::swapByteOrder(cro.ivars);
3737   sys::swapByteOrder(cro.weakIvarLayout);
3738   sys::swapByteOrder(cro.baseProperties);
3739 }
3740 
3741 inline void swapStruct(struct class_ro32_t &cro) {
3742   sys::swapByteOrder(cro.flags);
3743   sys::swapByteOrder(cro.instanceStart);
3744   sys::swapByteOrder(cro.instanceSize);
3745   sys::swapByteOrder(cro.ivarLayout);
3746   sys::swapByteOrder(cro.name);
3747   sys::swapByteOrder(cro.baseMethods);
3748   sys::swapByteOrder(cro.baseProtocols);
3749   sys::swapByteOrder(cro.ivars);
3750   sys::swapByteOrder(cro.weakIvarLayout);
3751   sys::swapByteOrder(cro.baseProperties);
3752 }
3753 
3754 inline void swapStruct(struct method_list64_t &ml) {
3755   sys::swapByteOrder(ml.entsize);
3756   sys::swapByteOrder(ml.count);
3757 }
3758 
3759 inline void swapStruct(struct method_list32_t &ml) {
3760   sys::swapByteOrder(ml.entsize);
3761   sys::swapByteOrder(ml.count);
3762 }
3763 
3764 inline void swapStruct(struct method64_t &m) {
3765   sys::swapByteOrder(m.name);
3766   sys::swapByteOrder(m.types);
3767   sys::swapByteOrder(m.imp);
3768 }
3769 
3770 inline void swapStruct(struct method32_t &m) {
3771   sys::swapByteOrder(m.name);
3772   sys::swapByteOrder(m.types);
3773   sys::swapByteOrder(m.imp);
3774 }
3775 
3776 inline void swapStruct(struct protocol_list64_t &pl) {
3777   sys::swapByteOrder(pl.count);
3778 }
3779 
3780 inline void swapStruct(struct protocol_list32_t &pl) {
3781   sys::swapByteOrder(pl.count);
3782 }
3783 
3784 inline void swapStruct(struct protocol64_t &p) {
3785   sys::swapByteOrder(p.isa);
3786   sys::swapByteOrder(p.name);
3787   sys::swapByteOrder(p.protocols);
3788   sys::swapByteOrder(p.instanceMethods);
3789   sys::swapByteOrder(p.classMethods);
3790   sys::swapByteOrder(p.optionalInstanceMethods);
3791   sys::swapByteOrder(p.optionalClassMethods);
3792   sys::swapByteOrder(p.instanceProperties);
3793 }
3794 
3795 inline void swapStruct(struct protocol32_t &p) {
3796   sys::swapByteOrder(p.isa);
3797   sys::swapByteOrder(p.name);
3798   sys::swapByteOrder(p.protocols);
3799   sys::swapByteOrder(p.instanceMethods);
3800   sys::swapByteOrder(p.classMethods);
3801   sys::swapByteOrder(p.optionalInstanceMethods);
3802   sys::swapByteOrder(p.optionalClassMethods);
3803   sys::swapByteOrder(p.instanceProperties);
3804 }
3805 
3806 inline void swapStruct(struct ivar_list64_t &il) {
3807   sys::swapByteOrder(il.entsize);
3808   sys::swapByteOrder(il.count);
3809 }
3810 
3811 inline void swapStruct(struct ivar_list32_t &il) {
3812   sys::swapByteOrder(il.entsize);
3813   sys::swapByteOrder(il.count);
3814 }
3815 
3816 inline void swapStruct(struct ivar64_t &i) {
3817   sys::swapByteOrder(i.offset);
3818   sys::swapByteOrder(i.name);
3819   sys::swapByteOrder(i.type);
3820   sys::swapByteOrder(i.alignment);
3821   sys::swapByteOrder(i.size);
3822 }
3823 
3824 inline void swapStruct(struct ivar32_t &i) {
3825   sys::swapByteOrder(i.offset);
3826   sys::swapByteOrder(i.name);
3827   sys::swapByteOrder(i.type);
3828   sys::swapByteOrder(i.alignment);
3829   sys::swapByteOrder(i.size);
3830 }
3831 
3832 inline void swapStruct(struct objc_property_list64 &pl) {
3833   sys::swapByteOrder(pl.entsize);
3834   sys::swapByteOrder(pl.count);
3835 }
3836 
3837 inline void swapStruct(struct objc_property_list32 &pl) {
3838   sys::swapByteOrder(pl.entsize);
3839   sys::swapByteOrder(pl.count);
3840 }
3841 
3842 inline void swapStruct(struct objc_property64 &op) {
3843   sys::swapByteOrder(op.name);
3844   sys::swapByteOrder(op.attributes);
3845 }
3846 
3847 inline void swapStruct(struct objc_property32 &op) {
3848   sys::swapByteOrder(op.name);
3849   sys::swapByteOrder(op.attributes);
3850 }
3851 
3852 inline void swapStruct(struct category64_t &c) {
3853   sys::swapByteOrder(c.name);
3854   sys::swapByteOrder(c.cls);
3855   sys::swapByteOrder(c.instanceMethods);
3856   sys::swapByteOrder(c.classMethods);
3857   sys::swapByteOrder(c.protocols);
3858   sys::swapByteOrder(c.instanceProperties);
3859 }
3860 
3861 inline void swapStruct(struct category32_t &c) {
3862   sys::swapByteOrder(c.name);
3863   sys::swapByteOrder(c.cls);
3864   sys::swapByteOrder(c.instanceMethods);
3865   sys::swapByteOrder(c.classMethods);
3866   sys::swapByteOrder(c.protocols);
3867   sys::swapByteOrder(c.instanceProperties);
3868 }
3869 
3870 inline void swapStruct(struct objc_image_info64 &o) {
3871   sys::swapByteOrder(o.version);
3872   sys::swapByteOrder(o.flags);
3873 }
3874 
3875 inline void swapStruct(struct objc_image_info32 &o) {
3876   sys::swapByteOrder(o.version);
3877   sys::swapByteOrder(o.flags);
3878 }
3879 
3880 inline void swapStruct(struct imageInfo_t &o) {
3881   sys::swapByteOrder(o.version);
3882   sys::swapByteOrder(o.flags);
3883 }
3884 
3885 inline void swapStruct(struct message_ref64 &mr) {
3886   sys::swapByteOrder(mr.imp);
3887   sys::swapByteOrder(mr.sel);
3888 }
3889 
3890 inline void swapStruct(struct message_ref32 &mr) {
3891   sys::swapByteOrder(mr.imp);
3892   sys::swapByteOrder(mr.sel);
3893 }
3894 
3895 inline void swapStruct(struct objc_module_t &module) {
3896   sys::swapByteOrder(module.version);
3897   sys::swapByteOrder(module.size);
3898   sys::swapByteOrder(module.name);
3899   sys::swapByteOrder(module.symtab);
3900 }
3901 
3902 inline void swapStruct(struct objc_symtab_t &symtab) {
3903   sys::swapByteOrder(symtab.sel_ref_cnt);
3904   sys::swapByteOrder(symtab.refs);
3905   sys::swapByteOrder(symtab.cls_def_cnt);
3906   sys::swapByteOrder(symtab.cat_def_cnt);
3907 }
3908 
3909 inline void swapStruct(struct objc_class_t &objc_class) {
3910   sys::swapByteOrder(objc_class.isa);
3911   sys::swapByteOrder(objc_class.super_class);
3912   sys::swapByteOrder(objc_class.name);
3913   sys::swapByteOrder(objc_class.version);
3914   sys::swapByteOrder(objc_class.info);
3915   sys::swapByteOrder(objc_class.instance_size);
3916   sys::swapByteOrder(objc_class.ivars);
3917   sys::swapByteOrder(objc_class.methodLists);
3918   sys::swapByteOrder(objc_class.cache);
3919   sys::swapByteOrder(objc_class.protocols);
3920 }
3921 
3922 inline void swapStruct(struct objc_category_t &objc_category) {
3923   sys::swapByteOrder(objc_category.category_name);
3924   sys::swapByteOrder(objc_category.class_name);
3925   sys::swapByteOrder(objc_category.instance_methods);
3926   sys::swapByteOrder(objc_category.class_methods);
3927   sys::swapByteOrder(objc_category.protocols);
3928 }
3929 
3930 inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3931   sys::swapByteOrder(objc_ivar_list.ivar_count);
3932 }
3933 
3934 inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3935   sys::swapByteOrder(objc_ivar.ivar_name);
3936   sys::swapByteOrder(objc_ivar.ivar_type);
3937   sys::swapByteOrder(objc_ivar.ivar_offset);
3938 }
3939 
3940 inline void swapStruct(struct objc_method_list_t &method_list) {
3941   sys::swapByteOrder(method_list.obsolete);
3942   sys::swapByteOrder(method_list.method_count);
3943 }
3944 
3945 inline void swapStruct(struct objc_method_t &method) {
3946   sys::swapByteOrder(method.method_name);
3947   sys::swapByteOrder(method.method_types);
3948   sys::swapByteOrder(method.method_imp);
3949 }
3950 
3951 inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3952   sys::swapByteOrder(protocol_list.next);
3953   sys::swapByteOrder(protocol_list.count);
3954 }
3955 
3956 inline void swapStruct(struct objc_protocol_t &protocol) {
3957   sys::swapByteOrder(protocol.isa);
3958   sys::swapByteOrder(protocol.protocol_name);
3959   sys::swapByteOrder(protocol.protocol_list);
3960   sys::swapByteOrder(protocol.instance_methods);
3961   sys::swapByteOrder(protocol.class_methods);
3962 }
3963 
3964 inline void swapStruct(struct objc_method_description_list_t &mdl) {
3965   sys::swapByteOrder(mdl.count);
3966 }
3967 
3968 inline void swapStruct(struct objc_method_description_t &md) {
3969   sys::swapByteOrder(md.name);
3970   sys::swapByteOrder(md.types);
3971 }
3972 
3973 } // namespace
3974 
3975 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3976                                                  struct DisassembleInfo *info);
3977 
3978 // get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3979 // to an Objective-C class and returns the class name.  It is also passed the
3980 // address of the pointer, so when the pointer is zero as it can be in an .o
3981 // file, that is used to look for an external relocation entry with a symbol
3982 // name.
3983 static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3984                                               uint64_t ReferenceValue,
3985                                               struct DisassembleInfo *info) {
3986   const char *r;
3987   uint32_t offset, left;
3988   SectionRef S;
3989 
3990   // The pointer_value can be 0 in an object file and have a relocation
3991   // entry for the class symbol at the ReferenceValue (the address of the
3992   // pointer).
3993   if (pointer_value == 0) {
3994     r = get_pointer_64(ReferenceValue, offset, left, S, info);
3995     if (r == nullptr || left < sizeof(uint64_t))
3996       return nullptr;
3997     uint64_t n_value;
3998     const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3999     if (symbol_name == nullptr)
4000       return nullptr;
4001     const char *class_name = strrchr(symbol_name, '$');
4002     if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
4003       return class_name + 2;
4004     else
4005       return nullptr;
4006   }
4007 
4008   // The case were the pointer_value is non-zero and points to a class defined
4009   // in this Mach-O file.
4010   r = get_pointer_64(pointer_value, offset, left, S, info);
4011   if (r == nullptr || left < sizeof(struct class64_t))
4012     return nullptr;
4013   struct class64_t c;
4014   memcpy(&c, r, sizeof(struct class64_t));
4015   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4016     swapStruct(c);
4017   if (c.data == 0)
4018     return nullptr;
4019   r = get_pointer_64(c.data, offset, left, S, info);
4020   if (r == nullptr || left < sizeof(struct class_ro64_t))
4021     return nullptr;
4022   struct class_ro64_t cro;
4023   memcpy(&cro, r, sizeof(struct class_ro64_t));
4024   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4025     swapStruct(cro);
4026   if (cro.name == 0)
4027     return nullptr;
4028   const char *name = get_pointer_64(cro.name, offset, left, S, info);
4029   return name;
4030 }
4031 
4032 // get_objc2_64bit_cfstring_name is used for disassembly and is passed a
4033 // pointer to a cfstring and returns its name or nullptr.
4034 static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
4035                                                  struct DisassembleInfo *info) {
4036   const char *r, *name;
4037   uint32_t offset, left;
4038   SectionRef S;
4039   struct cfstring64_t cfs;
4040   uint64_t cfs_characters;
4041 
4042   r = get_pointer_64(ReferenceValue, offset, left, S, info);
4043   if (r == nullptr || left < sizeof(struct cfstring64_t))
4044     return nullptr;
4045   memcpy(&cfs, r, sizeof(struct cfstring64_t));
4046   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4047     swapStruct(cfs);
4048   if (cfs.characters == 0) {
4049     uint64_t n_value;
4050     const char *symbol_name = get_symbol_64(
4051         offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
4052     if (symbol_name == nullptr)
4053       return nullptr;
4054     cfs_characters = n_value;
4055   } else
4056     cfs_characters = cfs.characters;
4057   name = get_pointer_64(cfs_characters, offset, left, S, info);
4058 
4059   return name;
4060 }
4061 
4062 // get_objc2_64bit_selref() is used for disassembly and is passed a the address
4063 // of a pointer to an Objective-C selector reference when the pointer value is
4064 // zero as in a .o file and is likely to have a external relocation entry with
4065 // who's symbol's n_value is the real pointer to the selector name.  If that is
4066 // the case the real pointer to the selector name is returned else 0 is
4067 // returned
4068 static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
4069                                        struct DisassembleInfo *info) {
4070   uint32_t offset, left;
4071   SectionRef S;
4072 
4073   const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
4074   if (r == nullptr || left < sizeof(uint64_t))
4075     return 0;
4076   uint64_t n_value;
4077   const char *symbol_name = get_symbol_64(offset, S, info, n_value);
4078   if (symbol_name == nullptr)
4079     return 0;
4080   return n_value;
4081 }
4082 
4083 static const SectionRef get_section(MachOObjectFile *O, const char *segname,
4084                                     const char *sectname) {
4085   for (const SectionRef &Section : O->sections()) {
4086     StringRef SectName;
4087     Expected<StringRef> SecNameOrErr = Section.getName();
4088     if (SecNameOrErr)
4089       SectName = *SecNameOrErr;
4090     else
4091       consumeError(SecNameOrErr.takeError());
4092 
4093     DataRefImpl Ref = Section.getRawDataRefImpl();
4094     StringRef SegName = O->getSectionFinalSegmentName(Ref);
4095     if (SegName == segname && SectName == sectname)
4096       return Section;
4097   }
4098   return SectionRef();
4099 }
4100 
4101 static void
4102 walk_pointer_list_64(const char *listname, const SectionRef S,
4103                      MachOObjectFile *O, struct DisassembleInfo *info,
4104                      void (*func)(uint64_t, struct DisassembleInfo *info)) {
4105   if (S == SectionRef())
4106     return;
4107 
4108   StringRef SectName;
4109   Expected<StringRef> SecNameOrErr = S.getName();
4110   if (SecNameOrErr)
4111     SectName = *SecNameOrErr;
4112   else
4113     consumeError(SecNameOrErr.takeError());
4114 
4115   DataRefImpl Ref = S.getRawDataRefImpl();
4116   StringRef SegName = O->getSectionFinalSegmentName(Ref);
4117   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4118 
4119   StringRef BytesStr = unwrapOrError(S.getContents(), O->getFileName());
4120   const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
4121 
4122   for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
4123     uint32_t left = S.getSize() - i;
4124     uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
4125     uint64_t p = 0;
4126     memcpy(&p, Contents + i, size);
4127     if (i + sizeof(uint64_t) > S.getSize())
4128       outs() << listname << " list pointer extends past end of (" << SegName
4129              << "," << SectName << ") section\n";
4130     outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
4131 
4132     if (O->isLittleEndian() != sys::IsLittleEndianHost)
4133       sys::swapByteOrder(p);
4134 
4135     uint64_t n_value = 0;
4136     const char *name = get_symbol_64(i, S, info, n_value, p);
4137     if (name == nullptr)
4138       name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
4139 
4140     if (n_value != 0) {
4141       outs() << format("0x%" PRIx64, n_value);
4142       if (p != 0)
4143         outs() << " + " << format("0x%" PRIx64, p);
4144     } else
4145       outs() << format("0x%" PRIx64, p);
4146     if (name != nullptr)
4147       outs() << " " << name;
4148     outs() << "\n";
4149 
4150     p += n_value;
4151     if (func)
4152       func(p, info);
4153   }
4154 }
4155 
4156 static void
4157 walk_pointer_list_32(const char *listname, const SectionRef S,
4158                      MachOObjectFile *O, struct DisassembleInfo *info,
4159                      void (*func)(uint32_t, struct DisassembleInfo *info)) {
4160   if (S == SectionRef())
4161     return;
4162 
4163   StringRef SectName = unwrapOrError(S.getName(), O->getFileName());
4164   DataRefImpl Ref = S.getRawDataRefImpl();
4165   StringRef SegName = O->getSectionFinalSegmentName(Ref);
4166   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4167 
4168   StringRef BytesStr = unwrapOrError(S.getContents(), O->getFileName());
4169   const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
4170 
4171   for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
4172     uint32_t left = S.getSize() - i;
4173     uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
4174     uint32_t p = 0;
4175     memcpy(&p, Contents + i, size);
4176     if (i + sizeof(uint32_t) > S.getSize())
4177       outs() << listname << " list pointer extends past end of (" << SegName
4178              << "," << SectName << ") section\n";
4179     uint32_t Address = S.getAddress() + i;
4180     outs() << format("%08" PRIx32, Address) << " ";
4181 
4182     if (O->isLittleEndian() != sys::IsLittleEndianHost)
4183       sys::swapByteOrder(p);
4184     outs() << format("0x%" PRIx32, p);
4185 
4186     const char *name = get_symbol_32(i, S, info, p);
4187     if (name != nullptr)
4188       outs() << " " << name;
4189     outs() << "\n";
4190 
4191     if (func)
4192       func(p, info);
4193   }
4194 }
4195 
4196 static void print_layout_map(const char *layout_map, uint32_t left) {
4197   if (layout_map == nullptr)
4198     return;
4199   outs() << "                layout map: ";
4200   do {
4201     outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
4202     left--;
4203     layout_map++;
4204   } while (*layout_map != '\0' && left != 0);
4205   outs() << "\n";
4206 }
4207 
4208 static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
4209   uint32_t offset, left;
4210   SectionRef S;
4211   const char *layout_map;
4212 
4213   if (p == 0)
4214     return;
4215   layout_map = get_pointer_64(p, offset, left, S, info);
4216   print_layout_map(layout_map, left);
4217 }
4218 
4219 static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
4220   uint32_t offset, left;
4221   SectionRef S;
4222   const char *layout_map;
4223 
4224   if (p == 0)
4225     return;
4226   layout_map = get_pointer_32(p, offset, left, S, info);
4227   print_layout_map(layout_map, left);
4228 }
4229 
4230 static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
4231                                   const char *indent) {
4232   struct method_list64_t ml;
4233   struct method64_t m;
4234   const char *r;
4235   uint32_t offset, xoffset, left, i;
4236   SectionRef S, xS;
4237   const char *name, *sym_name;
4238   uint64_t n_value;
4239 
4240   r = get_pointer_64(p, offset, left, S, info);
4241   if (r == nullptr)
4242     return;
4243   memset(&ml, '\0', sizeof(struct method_list64_t));
4244   if (left < sizeof(struct method_list64_t)) {
4245     memcpy(&ml, r, left);
4246     outs() << "   (method_list_t entends past the end of the section)\n";
4247   } else
4248     memcpy(&ml, r, sizeof(struct method_list64_t));
4249   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4250     swapStruct(ml);
4251   outs() << indent << "\t\t   entsize " << ml.entsize << "\n";
4252   outs() << indent << "\t\t     count " << ml.count << "\n";
4253 
4254   p += sizeof(struct method_list64_t);
4255   offset += sizeof(struct method_list64_t);
4256   for (i = 0; i < ml.count; i++) {
4257     r = get_pointer_64(p, offset, left, S, info);
4258     if (r == nullptr)
4259       return;
4260     memset(&m, '\0', sizeof(struct method64_t));
4261     if (left < sizeof(struct method64_t)) {
4262       memcpy(&m, r, left);
4263       outs() << indent << "   (method_t extends past the end of the section)\n";
4264     } else
4265       memcpy(&m, r, sizeof(struct method64_t));
4266     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4267       swapStruct(m);
4268 
4269     outs() << indent << "\t\t      name ";
4270     sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
4271                              info, n_value, m.name);
4272     if (n_value != 0) {
4273       if (info->verbose && sym_name != nullptr)
4274         outs() << sym_name;
4275       else
4276         outs() << format("0x%" PRIx64, n_value);
4277       if (m.name != 0)
4278         outs() << " + " << format("0x%" PRIx64, m.name);
4279     } else
4280       outs() << format("0x%" PRIx64, m.name);
4281     name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
4282     if (name != nullptr)
4283       outs() << format(" %.*s", left, name);
4284     outs() << "\n";
4285 
4286     outs() << indent << "\t\t     types ";
4287     sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
4288                              info, n_value, m.types);
4289     if (n_value != 0) {
4290       if (info->verbose && sym_name != nullptr)
4291         outs() << sym_name;
4292       else
4293         outs() << format("0x%" PRIx64, n_value);
4294       if (m.types != 0)
4295         outs() << " + " << format("0x%" PRIx64, m.types);
4296     } else
4297       outs() << format("0x%" PRIx64, m.types);
4298     name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
4299     if (name != nullptr)
4300       outs() << format(" %.*s", left, name);
4301     outs() << "\n";
4302 
4303     outs() << indent << "\t\t       imp ";
4304     name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
4305                          n_value, m.imp);
4306     if (info->verbose && name == nullptr) {
4307       if (n_value != 0) {
4308         outs() << format("0x%" PRIx64, n_value) << " ";
4309         if (m.imp != 0)
4310           outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
4311       } else
4312         outs() << format("0x%" PRIx64, m.imp) << " ";
4313     }
4314     if (name != nullptr)
4315       outs() << name;
4316     outs() << "\n";
4317 
4318     p += sizeof(struct method64_t);
4319     offset += sizeof(struct method64_t);
4320   }
4321 }
4322 
4323 static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
4324                                   const char *indent) {
4325   struct method_list32_t ml;
4326   struct method32_t m;
4327   const char *r, *name;
4328   uint32_t offset, xoffset, left, i;
4329   SectionRef S, xS;
4330 
4331   r = get_pointer_32(p, offset, left, S, info);
4332   if (r == nullptr)
4333     return;
4334   memset(&ml, '\0', sizeof(struct method_list32_t));
4335   if (left < sizeof(struct method_list32_t)) {
4336     memcpy(&ml, r, left);
4337     outs() << "   (method_list_t entends past the end of the section)\n";
4338   } else
4339     memcpy(&ml, r, sizeof(struct method_list32_t));
4340   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4341     swapStruct(ml);
4342   outs() << indent << "\t\t   entsize " << ml.entsize << "\n";
4343   outs() << indent << "\t\t     count " << ml.count << "\n";
4344 
4345   p += sizeof(struct method_list32_t);
4346   offset += sizeof(struct method_list32_t);
4347   for (i = 0; i < ml.count; i++) {
4348     r = get_pointer_32(p, offset, left, S, info);
4349     if (r == nullptr)
4350       return;
4351     memset(&m, '\0', sizeof(struct method32_t));
4352     if (left < sizeof(struct method32_t)) {
4353       memcpy(&ml, r, left);
4354       outs() << indent << "   (method_t entends past the end of the section)\n";
4355     } else
4356       memcpy(&m, r, sizeof(struct method32_t));
4357     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4358       swapStruct(m);
4359 
4360     outs() << indent << "\t\t      name " << format("0x%" PRIx32, m.name);
4361     name = get_pointer_32(m.name, xoffset, left, xS, info);
4362     if (name != nullptr)
4363       outs() << format(" %.*s", left, name);
4364     outs() << "\n";
4365 
4366     outs() << indent << "\t\t     types " << format("0x%" PRIx32, m.types);
4367     name = get_pointer_32(m.types, xoffset, left, xS, info);
4368     if (name != nullptr)
4369       outs() << format(" %.*s", left, name);
4370     outs() << "\n";
4371 
4372     outs() << indent << "\t\t       imp " << format("0x%" PRIx32, m.imp);
4373     name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
4374                          m.imp);
4375     if (name != nullptr)
4376       outs() << " " << name;
4377     outs() << "\n";
4378 
4379     p += sizeof(struct method32_t);
4380     offset += sizeof(struct method32_t);
4381   }
4382 }
4383 
4384 static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
4385   uint32_t offset, left, xleft;
4386   SectionRef S;
4387   struct objc_method_list_t method_list;
4388   struct objc_method_t method;
4389   const char *r, *methods, *name, *SymbolName;
4390   int32_t i;
4391 
4392   r = get_pointer_32(p, offset, left, S, info, true);
4393   if (r == nullptr)
4394     return true;
4395 
4396   outs() << "\n";
4397   if (left > sizeof(struct objc_method_list_t)) {
4398     memcpy(&method_list, r, sizeof(struct objc_method_list_t));
4399   } else {
4400     outs() << "\t\t objc_method_list extends past end of the section\n";
4401     memset(&method_list, '\0', sizeof(struct objc_method_list_t));
4402     memcpy(&method_list, r, left);
4403   }
4404   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4405     swapStruct(method_list);
4406 
4407   outs() << "\t\t         obsolete "
4408          << format("0x%08" PRIx32, method_list.obsolete) << "\n";
4409   outs() << "\t\t     method_count " << method_list.method_count << "\n";
4410 
4411   methods = r + sizeof(struct objc_method_list_t);
4412   for (i = 0; i < method_list.method_count; i++) {
4413     if ((i + 1) * sizeof(struct objc_method_t) > left) {
4414       outs() << "\t\t remaining method's extend past the of the section\n";
4415       break;
4416     }
4417     memcpy(&method, methods + i * sizeof(struct objc_method_t),
4418            sizeof(struct objc_method_t));
4419     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4420       swapStruct(method);
4421 
4422     outs() << "\t\t      method_name "
4423            << format("0x%08" PRIx32, method.method_name);
4424     if (info->verbose) {
4425       name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
4426       if (name != nullptr)
4427         outs() << format(" %.*s", xleft, name);
4428       else
4429         outs() << " (not in an __OBJC section)";
4430     }
4431     outs() << "\n";
4432 
4433     outs() << "\t\t     method_types "
4434            << format("0x%08" PRIx32, method.method_types);
4435     if (info->verbose) {
4436       name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
4437       if (name != nullptr)
4438         outs() << format(" %.*s", xleft, name);
4439       else
4440         outs() << " (not in an __OBJC section)";
4441     }
4442     outs() << "\n";
4443 
4444     outs() << "\t\t       method_imp "
4445            << format("0x%08" PRIx32, method.method_imp) << " ";
4446     if (info->verbose) {
4447       SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
4448       if (SymbolName != nullptr)
4449         outs() << SymbolName;
4450     }
4451     outs() << "\n";
4452   }
4453   return false;
4454 }
4455 
4456 static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
4457   struct protocol_list64_t pl;
4458   uint64_t q, n_value;
4459   struct protocol64_t pc;
4460   const char *r;
4461   uint32_t offset, xoffset, left, i;
4462   SectionRef S, xS;
4463   const char *name, *sym_name;
4464 
4465   r = get_pointer_64(p, offset, left, S, info);
4466   if (r == nullptr)
4467     return;
4468   memset(&pl, '\0', sizeof(struct protocol_list64_t));
4469   if (left < sizeof(struct protocol_list64_t)) {
4470     memcpy(&pl, r, left);
4471     outs() << "   (protocol_list_t entends past the end of the section)\n";
4472   } else
4473     memcpy(&pl, r, sizeof(struct protocol_list64_t));
4474   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4475     swapStruct(pl);
4476   outs() << "                      count " << pl.count << "\n";
4477 
4478   p += sizeof(struct protocol_list64_t);
4479   offset += sizeof(struct protocol_list64_t);
4480   for (i = 0; i < pl.count; i++) {
4481     r = get_pointer_64(p, offset, left, S, info);
4482     if (r == nullptr)
4483       return;
4484     q = 0;
4485     if (left < sizeof(uint64_t)) {
4486       memcpy(&q, r, left);
4487       outs() << "   (protocol_t * entends past the end of the section)\n";
4488     } else
4489       memcpy(&q, r, sizeof(uint64_t));
4490     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4491       sys::swapByteOrder(q);
4492 
4493     outs() << "\t\t      list[" << i << "] ";
4494     sym_name = get_symbol_64(offset, S, info, n_value, q);
4495     if (n_value != 0) {
4496       if (info->verbose && sym_name != nullptr)
4497         outs() << sym_name;
4498       else
4499         outs() << format("0x%" PRIx64, n_value);
4500       if (q != 0)
4501         outs() << " + " << format("0x%" PRIx64, q);
4502     } else
4503       outs() << format("0x%" PRIx64, q);
4504     outs() << " (struct protocol_t *)\n";
4505 
4506     r = get_pointer_64(q + n_value, offset, left, S, info);
4507     if (r == nullptr)
4508       return;
4509     memset(&pc, '\0', sizeof(struct protocol64_t));
4510     if (left < sizeof(struct protocol64_t)) {
4511       memcpy(&pc, r, left);
4512       outs() << "   (protocol_t entends past the end of the section)\n";
4513     } else
4514       memcpy(&pc, r, sizeof(struct protocol64_t));
4515     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4516       swapStruct(pc);
4517 
4518     outs() << "\t\t\t      isa " << format("0x%" PRIx64, pc.isa) << "\n";
4519 
4520     outs() << "\t\t\t     name ";
4521     sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
4522                              info, n_value, pc.name);
4523     if (n_value != 0) {
4524       if (info->verbose && sym_name != nullptr)
4525         outs() << sym_name;
4526       else
4527         outs() << format("0x%" PRIx64, n_value);
4528       if (pc.name != 0)
4529         outs() << " + " << format("0x%" PRIx64, pc.name);
4530     } else
4531       outs() << format("0x%" PRIx64, pc.name);
4532     name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
4533     if (name != nullptr)
4534       outs() << format(" %.*s", left, name);
4535     outs() << "\n";
4536 
4537     outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
4538 
4539     outs() << "\t\t  instanceMethods ";
4540     sym_name =
4541         get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
4542                       S, info, n_value, pc.instanceMethods);
4543     if (n_value != 0) {
4544       if (info->verbose && sym_name != nullptr)
4545         outs() << sym_name;
4546       else
4547         outs() << format("0x%" PRIx64, n_value);
4548       if (pc.instanceMethods != 0)
4549         outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
4550     } else
4551       outs() << format("0x%" PRIx64, pc.instanceMethods);
4552     outs() << " (struct method_list_t *)\n";
4553     if (pc.instanceMethods + n_value != 0)
4554       print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
4555 
4556     outs() << "\t\t     classMethods ";
4557     sym_name =
4558         get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
4559                       info, n_value, pc.classMethods);
4560     if (n_value != 0) {
4561       if (info->verbose && sym_name != nullptr)
4562         outs() << sym_name;
4563       else
4564         outs() << format("0x%" PRIx64, n_value);
4565       if (pc.classMethods != 0)
4566         outs() << " + " << format("0x%" PRIx64, pc.classMethods);
4567     } else
4568       outs() << format("0x%" PRIx64, pc.classMethods);
4569     outs() << " (struct method_list_t *)\n";
4570     if (pc.classMethods + n_value != 0)
4571       print_method_list64_t(pc.classMethods + n_value, info, "\t");
4572 
4573     outs() << "\t  optionalInstanceMethods "
4574            << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
4575     outs() << "\t     optionalClassMethods "
4576            << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
4577     outs() << "\t       instanceProperties "
4578            << format("0x%" PRIx64, pc.instanceProperties) << "\n";
4579 
4580     p += sizeof(uint64_t);
4581     offset += sizeof(uint64_t);
4582   }
4583 }
4584 
4585 static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
4586   struct protocol_list32_t pl;
4587   uint32_t q;
4588   struct protocol32_t pc;
4589   const char *r;
4590   uint32_t offset, xoffset, left, i;
4591   SectionRef S, xS;
4592   const char *name;
4593 
4594   r = get_pointer_32(p, offset, left, S, info);
4595   if (r == nullptr)
4596     return;
4597   memset(&pl, '\0', sizeof(struct protocol_list32_t));
4598   if (left < sizeof(struct protocol_list32_t)) {
4599     memcpy(&pl, r, left);
4600     outs() << "   (protocol_list_t entends past the end of the section)\n";
4601   } else
4602     memcpy(&pl, r, sizeof(struct protocol_list32_t));
4603   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4604     swapStruct(pl);
4605   outs() << "                      count " << pl.count << "\n";
4606 
4607   p += sizeof(struct protocol_list32_t);
4608   offset += sizeof(struct protocol_list32_t);
4609   for (i = 0; i < pl.count; i++) {
4610     r = get_pointer_32(p, offset, left, S, info);
4611     if (r == nullptr)
4612       return;
4613     q = 0;
4614     if (left < sizeof(uint32_t)) {
4615       memcpy(&q, r, left);
4616       outs() << "   (protocol_t * entends past the end of the section)\n";
4617     } else
4618       memcpy(&q, r, sizeof(uint32_t));
4619     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4620       sys::swapByteOrder(q);
4621     outs() << "\t\t      list[" << i << "] " << format("0x%" PRIx32, q)
4622            << " (struct protocol_t *)\n";
4623     r = get_pointer_32(q, offset, left, S, info);
4624     if (r == nullptr)
4625       return;
4626     memset(&pc, '\0', sizeof(struct protocol32_t));
4627     if (left < sizeof(struct protocol32_t)) {
4628       memcpy(&pc, r, left);
4629       outs() << "   (protocol_t entends past the end of the section)\n";
4630     } else
4631       memcpy(&pc, r, sizeof(struct protocol32_t));
4632     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4633       swapStruct(pc);
4634     outs() << "\t\t\t      isa " << format("0x%" PRIx32, pc.isa) << "\n";
4635     outs() << "\t\t\t     name " << format("0x%" PRIx32, pc.name);
4636     name = get_pointer_32(pc.name, xoffset, left, xS, info);
4637     if (name != nullptr)
4638       outs() << format(" %.*s", left, name);
4639     outs() << "\n";
4640     outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
4641     outs() << "\t\t  instanceMethods "
4642            << format("0x%" PRIx32, pc.instanceMethods)
4643            << " (struct method_list_t *)\n";
4644     if (pc.instanceMethods != 0)
4645       print_method_list32_t(pc.instanceMethods, info, "\t");
4646     outs() << "\t\t     classMethods " << format("0x%" PRIx32, pc.classMethods)
4647            << " (struct method_list_t *)\n";
4648     if (pc.classMethods != 0)
4649       print_method_list32_t(pc.classMethods, info, "\t");
4650     outs() << "\t  optionalInstanceMethods "
4651            << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
4652     outs() << "\t     optionalClassMethods "
4653            << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
4654     outs() << "\t       instanceProperties "
4655            << format("0x%" PRIx32, pc.instanceProperties) << "\n";
4656     p += sizeof(uint32_t);
4657     offset += sizeof(uint32_t);
4658   }
4659 }
4660 
4661 static void print_indent(uint32_t indent) {
4662   for (uint32_t i = 0; i < indent;) {
4663     if (indent - i >= 8) {
4664       outs() << "\t";
4665       i += 8;
4666     } else {
4667       for (uint32_t j = i; j < indent; j++)
4668         outs() << " ";
4669       return;
4670     }
4671   }
4672 }
4673 
4674 static bool print_method_description_list(uint32_t p, uint32_t indent,
4675                                           struct DisassembleInfo *info) {
4676   uint32_t offset, left, xleft;
4677   SectionRef S;
4678   struct objc_method_description_list_t mdl;
4679   struct objc_method_description_t md;
4680   const char *r, *list, *name;
4681   int32_t i;
4682 
4683   r = get_pointer_32(p, offset, left, S, info, true);
4684   if (r == nullptr)
4685     return true;
4686 
4687   outs() << "\n";
4688   if (left > sizeof(struct objc_method_description_list_t)) {
4689     memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
4690   } else {
4691     print_indent(indent);
4692     outs() << " objc_method_description_list extends past end of the section\n";
4693     memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
4694     memcpy(&mdl, r, left);
4695   }
4696   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4697     swapStruct(mdl);
4698 
4699   print_indent(indent);
4700   outs() << "        count " << mdl.count << "\n";
4701 
4702   list = r + sizeof(struct objc_method_description_list_t);
4703   for (i = 0; i < mdl.count; i++) {
4704     if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
4705       print_indent(indent);
4706       outs() << " remaining list entries extend past the of the section\n";
4707       break;
4708     }
4709     print_indent(indent);
4710     outs() << "        list[" << i << "]\n";
4711     memcpy(&md, list + i * sizeof(struct objc_method_description_t),
4712            sizeof(struct objc_method_description_t));
4713     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4714       swapStruct(md);
4715 
4716     print_indent(indent);
4717     outs() << "             name " << format("0x%08" PRIx32, md.name);
4718     if (info->verbose) {
4719       name = get_pointer_32(md.name, offset, xleft, S, info, true);
4720       if (name != nullptr)
4721         outs() << format(" %.*s", xleft, name);
4722       else
4723         outs() << " (not in an __OBJC section)";
4724     }
4725     outs() << "\n";
4726 
4727     print_indent(indent);
4728     outs() << "            types " << format("0x%08" PRIx32, md.types);
4729     if (info->verbose) {
4730       name = get_pointer_32(md.types, offset, xleft, S, info, true);
4731       if (name != nullptr)
4732         outs() << format(" %.*s", xleft, name);
4733       else
4734         outs() << " (not in an __OBJC section)";
4735     }
4736     outs() << "\n";
4737   }
4738   return false;
4739 }
4740 
4741 static bool print_protocol_list(uint32_t p, uint32_t indent,
4742                                 struct DisassembleInfo *info);
4743 
4744 static bool print_protocol(uint32_t p, uint32_t indent,
4745                            struct DisassembleInfo *info) {
4746   uint32_t offset, left;
4747   SectionRef S;
4748   struct objc_protocol_t protocol;
4749   const char *r, *name;
4750 
4751   r = get_pointer_32(p, offset, left, S, info, true);
4752   if (r == nullptr)
4753     return true;
4754 
4755   outs() << "\n";
4756   if (left >= sizeof(struct objc_protocol_t)) {
4757     memcpy(&protocol, r, sizeof(struct objc_protocol_t));
4758   } else {
4759     print_indent(indent);
4760     outs() << "            Protocol extends past end of the section\n";
4761     memset(&protocol, '\0', sizeof(struct objc_protocol_t));
4762     memcpy(&protocol, r, left);
4763   }
4764   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4765     swapStruct(protocol);
4766 
4767   print_indent(indent);
4768   outs() << "              isa " << format("0x%08" PRIx32, protocol.isa)
4769          << "\n";
4770 
4771   print_indent(indent);
4772   outs() << "    protocol_name "
4773          << format("0x%08" PRIx32, protocol.protocol_name);
4774   if (info->verbose) {
4775     name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
4776     if (name != nullptr)
4777       outs() << format(" %.*s", left, name);
4778     else
4779       outs() << " (not in an __OBJC section)";
4780   }
4781   outs() << "\n";
4782 
4783   print_indent(indent);
4784   outs() << "    protocol_list "
4785          << format("0x%08" PRIx32, protocol.protocol_list);
4786   if (print_protocol_list(protocol.protocol_list, indent + 4, info))
4787     outs() << " (not in an __OBJC section)\n";
4788 
4789   print_indent(indent);
4790   outs() << " instance_methods "
4791          << format("0x%08" PRIx32, protocol.instance_methods);
4792   if (print_method_description_list(protocol.instance_methods, indent, info))
4793     outs() << " (not in an __OBJC section)\n";
4794 
4795   print_indent(indent);
4796   outs() << "    class_methods "
4797          << format("0x%08" PRIx32, protocol.class_methods);
4798   if (print_method_description_list(protocol.class_methods, indent, info))
4799     outs() << " (not in an __OBJC section)\n";
4800 
4801   return false;
4802 }
4803 
4804 static bool print_protocol_list(uint32_t p, uint32_t indent,
4805                                 struct DisassembleInfo *info) {
4806   uint32_t offset, left, l;
4807   SectionRef S;
4808   struct objc_protocol_list_t protocol_list;
4809   const char *r, *list;
4810   int32_t i;
4811 
4812   r = get_pointer_32(p, offset, left, S, info, true);
4813   if (r == nullptr)
4814     return true;
4815 
4816   outs() << "\n";
4817   if (left > sizeof(struct objc_protocol_list_t)) {
4818     memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
4819   } else {
4820     outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
4821     memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
4822     memcpy(&protocol_list, r, left);
4823   }
4824   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4825     swapStruct(protocol_list);
4826 
4827   print_indent(indent);
4828   outs() << "         next " << format("0x%08" PRIx32, protocol_list.next)
4829          << "\n";
4830   print_indent(indent);
4831   outs() << "        count " << protocol_list.count << "\n";
4832 
4833   list = r + sizeof(struct objc_protocol_list_t);
4834   for (i = 0; i < protocol_list.count; i++) {
4835     if ((i + 1) * sizeof(uint32_t) > left) {
4836       outs() << "\t\t remaining list entries extend past the of the section\n";
4837       break;
4838     }
4839     memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
4840     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4841       sys::swapByteOrder(l);
4842 
4843     print_indent(indent);
4844     outs() << "      list[" << i << "] " << format("0x%08" PRIx32, l);
4845     if (print_protocol(l, indent, info))
4846       outs() << "(not in an __OBJC section)\n";
4847   }
4848   return false;
4849 }
4850 
4851 static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
4852   struct ivar_list64_t il;
4853   struct ivar64_t i;
4854   const char *r;
4855   uint32_t offset, xoffset, left, j;
4856   SectionRef S, xS;
4857   const char *name, *sym_name, *ivar_offset_p;
4858   uint64_t ivar_offset, n_value;
4859 
4860   r = get_pointer_64(p, offset, left, S, info);
4861   if (r == nullptr)
4862     return;
4863   memset(&il, '\0', sizeof(struct ivar_list64_t));
4864   if (left < sizeof(struct ivar_list64_t)) {
4865     memcpy(&il, r, left);
4866     outs() << "   (ivar_list_t entends past the end of the section)\n";
4867   } else
4868     memcpy(&il, r, sizeof(struct ivar_list64_t));
4869   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4870     swapStruct(il);
4871   outs() << "                    entsize " << il.entsize << "\n";
4872   outs() << "                      count " << il.count << "\n";
4873 
4874   p += sizeof(struct ivar_list64_t);
4875   offset += sizeof(struct ivar_list64_t);
4876   for (j = 0; j < il.count; j++) {
4877     r = get_pointer_64(p, offset, left, S, info);
4878     if (r == nullptr)
4879       return;
4880     memset(&i, '\0', sizeof(struct ivar64_t));
4881     if (left < sizeof(struct ivar64_t)) {
4882       memcpy(&i, r, left);
4883       outs() << "   (ivar_t entends past the end of the section)\n";
4884     } else
4885       memcpy(&i, r, sizeof(struct ivar64_t));
4886     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4887       swapStruct(i);
4888 
4889     outs() << "\t\t\t   offset ";
4890     sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
4891                              info, n_value, i.offset);
4892     if (n_value != 0) {
4893       if (info->verbose && sym_name != nullptr)
4894         outs() << sym_name;
4895       else
4896         outs() << format("0x%" PRIx64, n_value);
4897       if (i.offset != 0)
4898         outs() << " + " << format("0x%" PRIx64, i.offset);
4899     } else
4900       outs() << format("0x%" PRIx64, i.offset);
4901     ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
4902     if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4903       memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4904       if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4905         sys::swapByteOrder(ivar_offset);
4906       outs() << " " << ivar_offset << "\n";
4907     } else
4908       outs() << "\n";
4909 
4910     outs() << "\t\t\t     name ";
4911     sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
4912                              n_value, i.name);
4913     if (n_value != 0) {
4914       if (info->verbose && sym_name != nullptr)
4915         outs() << sym_name;
4916       else
4917         outs() << format("0x%" PRIx64, n_value);
4918       if (i.name != 0)
4919         outs() << " + " << format("0x%" PRIx64, i.name);
4920     } else
4921       outs() << format("0x%" PRIx64, i.name);
4922     name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
4923     if (name != nullptr)
4924       outs() << format(" %.*s", left, name);
4925     outs() << "\n";
4926 
4927     outs() << "\t\t\t     type ";
4928     sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
4929                              n_value, i.name);
4930     name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
4931     if (n_value != 0) {
4932       if (info->verbose && sym_name != nullptr)
4933         outs() << sym_name;
4934       else
4935         outs() << format("0x%" PRIx64, n_value);
4936       if (i.type != 0)
4937         outs() << " + " << format("0x%" PRIx64, i.type);
4938     } else
4939       outs() << format("0x%" PRIx64, i.type);
4940     if (name != nullptr)
4941       outs() << format(" %.*s", left, name);
4942     outs() << "\n";
4943 
4944     outs() << "\t\t\talignment " << i.alignment << "\n";
4945     outs() << "\t\t\t     size " << i.size << "\n";
4946 
4947     p += sizeof(struct ivar64_t);
4948     offset += sizeof(struct ivar64_t);
4949   }
4950 }
4951 
4952 static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4953   struct ivar_list32_t il;
4954   struct ivar32_t i;
4955   const char *r;
4956   uint32_t offset, xoffset, left, j;
4957   SectionRef S, xS;
4958   const char *name, *ivar_offset_p;
4959   uint32_t ivar_offset;
4960 
4961   r = get_pointer_32(p, offset, left, S, info);
4962   if (r == nullptr)
4963     return;
4964   memset(&il, '\0', sizeof(struct ivar_list32_t));
4965   if (left < sizeof(struct ivar_list32_t)) {
4966     memcpy(&il, r, left);
4967     outs() << "   (ivar_list_t entends past the end of the section)\n";
4968   } else
4969     memcpy(&il, r, sizeof(struct ivar_list32_t));
4970   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4971     swapStruct(il);
4972   outs() << "                    entsize " << il.entsize << "\n";
4973   outs() << "                      count " << il.count << "\n";
4974 
4975   p += sizeof(struct ivar_list32_t);
4976   offset += sizeof(struct ivar_list32_t);
4977   for (j = 0; j < il.count; j++) {
4978     r = get_pointer_32(p, offset, left, S, info);
4979     if (r == nullptr)
4980       return;
4981     memset(&i, '\0', sizeof(struct ivar32_t));
4982     if (left < sizeof(struct ivar32_t)) {
4983       memcpy(&i, r, left);
4984       outs() << "   (ivar_t entends past the end of the section)\n";
4985     } else
4986       memcpy(&i, r, sizeof(struct ivar32_t));
4987     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4988       swapStruct(i);
4989 
4990     outs() << "\t\t\t   offset " << format("0x%" PRIx32, i.offset);
4991     ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4992     if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4993       memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4994       if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4995         sys::swapByteOrder(ivar_offset);
4996       outs() << " " << ivar_offset << "\n";
4997     } else
4998       outs() << "\n";
4999 
5000     outs() << "\t\t\t     name " << format("0x%" PRIx32, i.name);
5001     name = get_pointer_32(i.name, xoffset, left, xS, info);
5002     if (name != nullptr)
5003       outs() << format(" %.*s", left, name);
5004     outs() << "\n";
5005 
5006     outs() << "\t\t\t     type " << format("0x%" PRIx32, i.type);
5007     name = get_pointer_32(i.type, xoffset, left, xS, info);
5008     if (name != nullptr)
5009       outs() << format(" %.*s", left, name);
5010     outs() << "\n";
5011 
5012     outs() << "\t\t\talignment " << i.alignment << "\n";
5013     outs() << "\t\t\t     size " << i.size << "\n";
5014 
5015     p += sizeof(struct ivar32_t);
5016     offset += sizeof(struct ivar32_t);
5017   }
5018 }
5019 
5020 static void print_objc_property_list64(uint64_t p,
5021                                        struct DisassembleInfo *info) {
5022   struct objc_property_list64 opl;
5023   struct objc_property64 op;
5024   const char *r;
5025   uint32_t offset, xoffset, left, j;
5026   SectionRef S, xS;
5027   const char *name, *sym_name;
5028   uint64_t n_value;
5029 
5030   r = get_pointer_64(p, offset, left, S, info);
5031   if (r == nullptr)
5032     return;
5033   memset(&opl, '\0', sizeof(struct objc_property_list64));
5034   if (left < sizeof(struct objc_property_list64)) {
5035     memcpy(&opl, r, left);
5036     outs() << "   (objc_property_list entends past the end of the section)\n";
5037   } else
5038     memcpy(&opl, r, sizeof(struct objc_property_list64));
5039   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5040     swapStruct(opl);
5041   outs() << "                    entsize " << opl.entsize << "\n";
5042   outs() << "                      count " << opl.count << "\n";
5043 
5044   p += sizeof(struct objc_property_list64);
5045   offset += sizeof(struct objc_property_list64);
5046   for (j = 0; j < opl.count; j++) {
5047     r = get_pointer_64(p, offset, left, S, info);
5048     if (r == nullptr)
5049       return;
5050     memset(&op, '\0', sizeof(struct objc_property64));
5051     if (left < sizeof(struct objc_property64)) {
5052       memcpy(&op, r, left);
5053       outs() << "   (objc_property entends past the end of the section)\n";
5054     } else
5055       memcpy(&op, r, sizeof(struct objc_property64));
5056     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5057       swapStruct(op);
5058 
5059     outs() << "\t\t\t     name ";
5060     sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
5061                              info, n_value, op.name);
5062     if (n_value != 0) {
5063       if (info->verbose && sym_name != nullptr)
5064         outs() << sym_name;
5065       else
5066         outs() << format("0x%" PRIx64, n_value);
5067       if (op.name != 0)
5068         outs() << " + " << format("0x%" PRIx64, op.name);
5069     } else
5070       outs() << format("0x%" PRIx64, op.name);
5071     name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
5072     if (name != nullptr)
5073       outs() << format(" %.*s", left, name);
5074     outs() << "\n";
5075 
5076     outs() << "\t\t\tattributes ";
5077     sym_name =
5078         get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
5079                       info, n_value, op.attributes);
5080     if (n_value != 0) {
5081       if (info->verbose && sym_name != nullptr)
5082         outs() << sym_name;
5083       else
5084         outs() << format("0x%" PRIx64, n_value);
5085       if (op.attributes != 0)
5086         outs() << " + " << format("0x%" PRIx64, op.attributes);
5087     } else
5088       outs() << format("0x%" PRIx64, op.attributes);
5089     name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
5090     if (name != nullptr)
5091       outs() << format(" %.*s", left, name);
5092     outs() << "\n";
5093 
5094     p += sizeof(struct objc_property64);
5095     offset += sizeof(struct objc_property64);
5096   }
5097 }
5098 
5099 static void print_objc_property_list32(uint32_t p,
5100                                        struct DisassembleInfo *info) {
5101   struct objc_property_list32 opl;
5102   struct objc_property32 op;
5103   const char *r;
5104   uint32_t offset, xoffset, left, j;
5105   SectionRef S, xS;
5106   const char *name;
5107 
5108   r = get_pointer_32(p, offset, left, S, info);
5109   if (r == nullptr)
5110     return;
5111   memset(&opl, '\0', sizeof(struct objc_property_list32));
5112   if (left < sizeof(struct objc_property_list32)) {
5113     memcpy(&opl, r, left);
5114     outs() << "   (objc_property_list entends past the end of the section)\n";
5115   } else
5116     memcpy(&opl, r, sizeof(struct objc_property_list32));
5117   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5118     swapStruct(opl);
5119   outs() << "                    entsize " << opl.entsize << "\n";
5120   outs() << "                      count " << opl.count << "\n";
5121 
5122   p += sizeof(struct objc_property_list32);
5123   offset += sizeof(struct objc_property_list32);
5124   for (j = 0; j < opl.count; j++) {
5125     r = get_pointer_32(p, offset, left, S, info);
5126     if (r == nullptr)
5127       return;
5128     memset(&op, '\0', sizeof(struct objc_property32));
5129     if (left < sizeof(struct objc_property32)) {
5130       memcpy(&op, r, left);
5131       outs() << "   (objc_property entends past the end of the section)\n";
5132     } else
5133       memcpy(&op, r, sizeof(struct objc_property32));
5134     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5135       swapStruct(op);
5136 
5137     outs() << "\t\t\t     name " << format("0x%" PRIx32, op.name);
5138     name = get_pointer_32(op.name, xoffset, left, xS, info);
5139     if (name != nullptr)
5140       outs() << format(" %.*s", left, name);
5141     outs() << "\n";
5142 
5143     outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
5144     name = get_pointer_32(op.attributes, xoffset, left, xS, info);
5145     if (name != nullptr)
5146       outs() << format(" %.*s", left, name);
5147     outs() << "\n";
5148 
5149     p += sizeof(struct objc_property32);
5150     offset += sizeof(struct objc_property32);
5151   }
5152 }
5153 
5154 static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
5155                                bool &is_meta_class) {
5156   struct class_ro64_t cro;
5157   const char *r;
5158   uint32_t offset, xoffset, left;
5159   SectionRef S, xS;
5160   const char *name, *sym_name;
5161   uint64_t n_value;
5162 
5163   r = get_pointer_64(p, offset, left, S, info);
5164   if (r == nullptr || left < sizeof(struct class_ro64_t))
5165     return false;
5166   memcpy(&cro, r, sizeof(struct class_ro64_t));
5167   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5168     swapStruct(cro);
5169   outs() << "                    flags " << format("0x%" PRIx32, cro.flags);
5170   if (cro.flags & RO_META)
5171     outs() << " RO_META";
5172   if (cro.flags & RO_ROOT)
5173     outs() << " RO_ROOT";
5174   if (cro.flags & RO_HAS_CXX_STRUCTORS)
5175     outs() << " RO_HAS_CXX_STRUCTORS";
5176   outs() << "\n";
5177   outs() << "            instanceStart " << cro.instanceStart << "\n";
5178   outs() << "             instanceSize " << cro.instanceSize << "\n";
5179   outs() << "                 reserved " << format("0x%" PRIx32, cro.reserved)
5180          << "\n";
5181   outs() << "               ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
5182          << "\n";
5183   print_layout_map64(cro.ivarLayout, info);
5184 
5185   outs() << "                     name ";
5186   sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
5187                            info, n_value, cro.name);
5188   if (n_value != 0) {
5189     if (info->verbose && sym_name != nullptr)
5190       outs() << sym_name;
5191     else
5192       outs() << format("0x%" PRIx64, n_value);
5193     if (cro.name != 0)
5194       outs() << " + " << format("0x%" PRIx64, cro.name);
5195   } else
5196     outs() << format("0x%" PRIx64, cro.name);
5197   name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
5198   if (name != nullptr)
5199     outs() << format(" %.*s", left, name);
5200   outs() << "\n";
5201 
5202   outs() << "              baseMethods ";
5203   sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
5204                            S, info, n_value, cro.baseMethods);
5205   if (n_value != 0) {
5206     if (info->verbose && sym_name != nullptr)
5207       outs() << sym_name;
5208     else
5209       outs() << format("0x%" PRIx64, n_value);
5210     if (cro.baseMethods != 0)
5211       outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
5212   } else
5213     outs() << format("0x%" PRIx64, cro.baseMethods);
5214   outs() << " (struct method_list_t *)\n";
5215   if (cro.baseMethods + n_value != 0)
5216     print_method_list64_t(cro.baseMethods + n_value, info, "");
5217 
5218   outs() << "            baseProtocols ";
5219   sym_name =
5220       get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
5221                     info, n_value, cro.baseProtocols);
5222   if (n_value != 0) {
5223     if (info->verbose && sym_name != nullptr)
5224       outs() << sym_name;
5225     else
5226       outs() << format("0x%" PRIx64, n_value);
5227     if (cro.baseProtocols != 0)
5228       outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
5229   } else
5230     outs() << format("0x%" PRIx64, cro.baseProtocols);
5231   outs() << "\n";
5232   if (cro.baseProtocols + n_value != 0)
5233     print_protocol_list64_t(cro.baseProtocols + n_value, info);
5234 
5235   outs() << "                    ivars ";
5236   sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
5237                            info, n_value, cro.ivars);
5238   if (n_value != 0) {
5239     if (info->verbose && sym_name != nullptr)
5240       outs() << sym_name;
5241     else
5242       outs() << format("0x%" PRIx64, n_value);
5243     if (cro.ivars != 0)
5244       outs() << " + " << format("0x%" PRIx64, cro.ivars);
5245   } else
5246     outs() << format("0x%" PRIx64, cro.ivars);
5247   outs() << "\n";
5248   if (cro.ivars + n_value != 0)
5249     print_ivar_list64_t(cro.ivars + n_value, info);
5250 
5251   outs() << "           weakIvarLayout ";
5252   sym_name =
5253       get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
5254                     info, n_value, cro.weakIvarLayout);
5255   if (n_value != 0) {
5256     if (info->verbose && sym_name != nullptr)
5257       outs() << sym_name;
5258     else
5259       outs() << format("0x%" PRIx64, n_value);
5260     if (cro.weakIvarLayout != 0)
5261       outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
5262   } else
5263     outs() << format("0x%" PRIx64, cro.weakIvarLayout);
5264   outs() << "\n";
5265   print_layout_map64(cro.weakIvarLayout + n_value, info);
5266 
5267   outs() << "           baseProperties ";
5268   sym_name =
5269       get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
5270                     info, n_value, cro.baseProperties);
5271   if (n_value != 0) {
5272     if (info->verbose && sym_name != nullptr)
5273       outs() << sym_name;
5274     else
5275       outs() << format("0x%" PRIx64, n_value);
5276     if (cro.baseProperties != 0)
5277       outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
5278   } else
5279     outs() << format("0x%" PRIx64, cro.baseProperties);
5280   outs() << "\n";
5281   if (cro.baseProperties + n_value != 0)
5282     print_objc_property_list64(cro.baseProperties + n_value, info);
5283 
5284   is_meta_class = (cro.flags & RO_META) != 0;
5285   return true;
5286 }
5287 
5288 static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
5289                                bool &is_meta_class) {
5290   struct class_ro32_t cro;
5291   const char *r;
5292   uint32_t offset, xoffset, left;
5293   SectionRef S, xS;
5294   const char *name;
5295 
5296   r = get_pointer_32(p, offset, left, S, info);
5297   if (r == nullptr)
5298     return false;
5299   memset(&cro, '\0', sizeof(struct class_ro32_t));
5300   if (left < sizeof(struct class_ro32_t)) {
5301     memcpy(&cro, r, left);
5302     outs() << "   (class_ro_t entends past the end of the section)\n";
5303   } else
5304     memcpy(&cro, r, sizeof(struct class_ro32_t));
5305   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5306     swapStruct(cro);
5307   outs() << "                    flags " << format("0x%" PRIx32, cro.flags);
5308   if (cro.flags & RO_META)
5309     outs() << " RO_META";
5310   if (cro.flags & RO_ROOT)
5311     outs() << " RO_ROOT";
5312   if (cro.flags & RO_HAS_CXX_STRUCTORS)
5313     outs() << " RO_HAS_CXX_STRUCTORS";
5314   outs() << "\n";
5315   outs() << "            instanceStart " << cro.instanceStart << "\n";
5316   outs() << "             instanceSize " << cro.instanceSize << "\n";
5317   outs() << "               ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
5318          << "\n";
5319   print_layout_map32(cro.ivarLayout, info);
5320 
5321   outs() << "                     name " << format("0x%" PRIx32, cro.name);
5322   name = get_pointer_32(cro.name, xoffset, left, xS, info);
5323   if (name != nullptr)
5324     outs() << format(" %.*s", left, name);
5325   outs() << "\n";
5326 
5327   outs() << "              baseMethods "
5328          << format("0x%" PRIx32, cro.baseMethods)
5329          << " (struct method_list_t *)\n";
5330   if (cro.baseMethods != 0)
5331     print_method_list32_t(cro.baseMethods, info, "");
5332 
5333   outs() << "            baseProtocols "
5334          << format("0x%" PRIx32, cro.baseProtocols) << "\n";
5335   if (cro.baseProtocols != 0)
5336     print_protocol_list32_t(cro.baseProtocols, info);
5337   outs() << "                    ivars " << format("0x%" PRIx32, cro.ivars)
5338          << "\n";
5339   if (cro.ivars != 0)
5340     print_ivar_list32_t(cro.ivars, info);
5341   outs() << "           weakIvarLayout "
5342          << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
5343   print_layout_map32(cro.weakIvarLayout, info);
5344   outs() << "           baseProperties "
5345          << format("0x%" PRIx32, cro.baseProperties) << "\n";
5346   if (cro.baseProperties != 0)
5347     print_objc_property_list32(cro.baseProperties, info);
5348   is_meta_class = (cro.flags & RO_META) != 0;
5349   return true;
5350 }
5351 
5352 static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
5353   struct class64_t c;
5354   const char *r;
5355   uint32_t offset, left;
5356   SectionRef S;
5357   const char *name;
5358   uint64_t isa_n_value, n_value;
5359 
5360   r = get_pointer_64(p, offset, left, S, info);
5361   if (r == nullptr || left < sizeof(struct class64_t))
5362     return;
5363   memcpy(&c, r, sizeof(struct class64_t));
5364   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5365     swapStruct(c);
5366 
5367   outs() << "           isa " << format("0x%" PRIx64, c.isa);
5368   name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
5369                        isa_n_value, c.isa);
5370   if (name != nullptr)
5371     outs() << " " << name;
5372   outs() << "\n";
5373 
5374   outs() << "    superclass " << format("0x%" PRIx64, c.superclass);
5375   name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
5376                        n_value, c.superclass);
5377   if (name != nullptr)
5378     outs() << " " << name;
5379   else {
5380     name = get_dyld_bind_info_symbolname(S.getAddress() +
5381              offset + offsetof(struct class64_t, superclass), info);
5382     if (name != nullptr)
5383       outs() << " " << name;
5384   }
5385   outs() << "\n";
5386 
5387   outs() << "         cache " << format("0x%" PRIx64, c.cache);
5388   name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
5389                        n_value, c.cache);
5390   if (name != nullptr)
5391     outs() << " " << name;
5392   outs() << "\n";
5393 
5394   outs() << "        vtable " << format("0x%" PRIx64, c.vtable);
5395   name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
5396                        n_value, c.vtable);
5397   if (name != nullptr)
5398     outs() << " " << name;
5399   outs() << "\n";
5400 
5401   name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
5402                        n_value, c.data);
5403   outs() << "          data ";
5404   if (n_value != 0) {
5405     if (info->verbose && name != nullptr)
5406       outs() << name;
5407     else
5408       outs() << format("0x%" PRIx64, n_value);
5409     if (c.data != 0)
5410       outs() << " + " << format("0x%" PRIx64, c.data);
5411   } else
5412     outs() << format("0x%" PRIx64, c.data);
5413   outs() << " (struct class_ro_t *)";
5414 
5415   // This is a Swift class if some of the low bits of the pointer are set.
5416   if ((c.data + n_value) & 0x7)
5417     outs() << " Swift class";
5418   outs() << "\n";
5419   bool is_meta_class;
5420   if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
5421     return;
5422 
5423   if (!is_meta_class &&
5424       c.isa + isa_n_value != p &&
5425       c.isa + isa_n_value != 0 &&
5426       info->depth < 100) {
5427       info->depth++;
5428       outs() << "Meta Class\n";
5429       print_class64_t(c.isa + isa_n_value, info);
5430   }
5431 }
5432 
5433 static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
5434   struct class32_t c;
5435   const char *r;
5436   uint32_t offset, left;
5437   SectionRef S;
5438   const char *name;
5439 
5440   r = get_pointer_32(p, offset, left, S, info);
5441   if (r == nullptr)
5442     return;
5443   memset(&c, '\0', sizeof(struct class32_t));
5444   if (left < sizeof(struct class32_t)) {
5445     memcpy(&c, r, left);
5446     outs() << "   (class_t entends past the end of the section)\n";
5447   } else
5448     memcpy(&c, r, sizeof(struct class32_t));
5449   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5450     swapStruct(c);
5451 
5452   outs() << "           isa " << format("0x%" PRIx32, c.isa);
5453   name =
5454       get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
5455   if (name != nullptr)
5456     outs() << " " << name;
5457   outs() << "\n";
5458 
5459   outs() << "    superclass " << format("0x%" PRIx32, c.superclass);
5460   name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
5461                        c.superclass);
5462   if (name != nullptr)
5463     outs() << " " << name;
5464   outs() << "\n";
5465 
5466   outs() << "         cache " << format("0x%" PRIx32, c.cache);
5467   name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
5468                        c.cache);
5469   if (name != nullptr)
5470     outs() << " " << name;
5471   outs() << "\n";
5472 
5473   outs() << "        vtable " << format("0x%" PRIx32, c.vtable);
5474   name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
5475                        c.vtable);
5476   if (name != nullptr)
5477     outs() << " " << name;
5478   outs() << "\n";
5479 
5480   name =
5481       get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
5482   outs() << "          data " << format("0x%" PRIx32, c.data)
5483          << " (struct class_ro_t *)";
5484 
5485   // This is a Swift class if some of the low bits of the pointer are set.
5486   if (c.data & 0x3)
5487     outs() << " Swift class";
5488   outs() << "\n";
5489   bool is_meta_class;
5490   if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
5491     return;
5492 
5493   if (!is_meta_class) {
5494     outs() << "Meta Class\n";
5495     print_class32_t(c.isa, info);
5496   }
5497 }
5498 
5499 static void print_objc_class_t(struct objc_class_t *objc_class,
5500                                struct DisassembleInfo *info) {
5501   uint32_t offset, left, xleft;
5502   const char *name, *p, *ivar_list;
5503   SectionRef S;
5504   int32_t i;
5505   struct objc_ivar_list_t objc_ivar_list;
5506   struct objc_ivar_t ivar;
5507 
5508   outs() << "\t\t      isa " << format("0x%08" PRIx32, objc_class->isa);
5509   if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
5510     name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
5511     if (name != nullptr)
5512       outs() << format(" %.*s", left, name);
5513     else
5514       outs() << " (not in an __OBJC section)";
5515   }
5516   outs() << "\n";
5517 
5518   outs() << "\t      super_class "
5519          << format("0x%08" PRIx32, objc_class->super_class);
5520   if (info->verbose) {
5521     name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
5522     if (name != nullptr)
5523       outs() << format(" %.*s", left, name);
5524     else
5525       outs() << " (not in an __OBJC section)";
5526   }
5527   outs() << "\n";
5528 
5529   outs() << "\t\t     name " << format("0x%08" PRIx32, objc_class->name);
5530   if (info->verbose) {
5531     name = get_pointer_32(objc_class->name, offset, left, S, info, true);
5532     if (name != nullptr)
5533       outs() << format(" %.*s", left, name);
5534     else
5535       outs() << " (not in an __OBJC section)";
5536   }
5537   outs() << "\n";
5538 
5539   outs() << "\t\t  version " << format("0x%08" PRIx32, objc_class->version)
5540          << "\n";
5541 
5542   outs() << "\t\t     info " << format("0x%08" PRIx32, objc_class->info);
5543   if (info->verbose) {
5544     if (CLS_GETINFO(objc_class, CLS_CLASS))
5545       outs() << " CLS_CLASS";
5546     else if (CLS_GETINFO(objc_class, CLS_META))
5547       outs() << " CLS_META";
5548   }
5549   outs() << "\n";
5550 
5551   outs() << "\t    instance_size "
5552          << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
5553 
5554   p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
5555   outs() << "\t\t    ivars " << format("0x%08" PRIx32, objc_class->ivars);
5556   if (p != nullptr) {
5557     if (left > sizeof(struct objc_ivar_list_t)) {
5558       outs() << "\n";
5559       memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
5560     } else {
5561       outs() << " (entends past the end of the section)\n";
5562       memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
5563       memcpy(&objc_ivar_list, p, left);
5564     }
5565     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5566       swapStruct(objc_ivar_list);
5567     outs() << "\t\t       ivar_count " << objc_ivar_list.ivar_count << "\n";
5568     ivar_list = p + sizeof(struct objc_ivar_list_t);
5569     for (i = 0; i < objc_ivar_list.ivar_count; i++) {
5570       if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
5571         outs() << "\t\t remaining ivar's extend past the of the section\n";
5572         break;
5573       }
5574       memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
5575              sizeof(struct objc_ivar_t));
5576       if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5577         swapStruct(ivar);
5578 
5579       outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
5580       if (info->verbose) {
5581         name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
5582         if (name != nullptr)
5583           outs() << format(" %.*s", xleft, name);
5584         else
5585           outs() << " (not in an __OBJC section)";
5586       }
5587       outs() << "\n";
5588 
5589       outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
5590       if (info->verbose) {
5591         name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
5592         if (name != nullptr)
5593           outs() << format(" %.*s", xleft, name);
5594         else
5595           outs() << " (not in an __OBJC section)";
5596       }
5597       outs() << "\n";
5598 
5599       outs() << "\t\t      ivar_offset "
5600              << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
5601     }
5602   } else {
5603     outs() << " (not in an __OBJC section)\n";
5604   }
5605 
5606   outs() << "\t\t  methods " << format("0x%08" PRIx32, objc_class->methodLists);
5607   if (print_method_list(objc_class->methodLists, info))
5608     outs() << " (not in an __OBJC section)\n";
5609 
5610   outs() << "\t\t    cache " << format("0x%08" PRIx32, objc_class->cache)
5611          << "\n";
5612 
5613   outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
5614   if (print_protocol_list(objc_class->protocols, 16, info))
5615     outs() << " (not in an __OBJC section)\n";
5616 }
5617 
5618 static void print_objc_objc_category_t(struct objc_category_t *objc_category,
5619                                        struct DisassembleInfo *info) {
5620   uint32_t offset, left;
5621   const char *name;
5622   SectionRef S;
5623 
5624   outs() << "\t       category name "
5625          << format("0x%08" PRIx32, objc_category->category_name);
5626   if (info->verbose) {
5627     name = get_pointer_32(objc_category->category_name, offset, left, S, info,
5628                           true);
5629     if (name != nullptr)
5630       outs() << format(" %.*s", left, name);
5631     else
5632       outs() << " (not in an __OBJC section)";
5633   }
5634   outs() << "\n";
5635 
5636   outs() << "\t\t  class name "
5637          << format("0x%08" PRIx32, objc_category->class_name);
5638   if (info->verbose) {
5639     name =
5640         get_pointer_32(objc_category->class_name, offset, left, S, info, true);
5641     if (name != nullptr)
5642       outs() << format(" %.*s", left, name);
5643     else
5644       outs() << " (not in an __OBJC section)";
5645   }
5646   outs() << "\n";
5647 
5648   outs() << "\t    instance methods "
5649          << format("0x%08" PRIx32, objc_category->instance_methods);
5650   if (print_method_list(objc_category->instance_methods, info))
5651     outs() << " (not in an __OBJC section)\n";
5652 
5653   outs() << "\t       class methods "
5654          << format("0x%08" PRIx32, objc_category->class_methods);
5655   if (print_method_list(objc_category->class_methods, info))
5656     outs() << " (not in an __OBJC section)\n";
5657 }
5658 
5659 static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
5660   struct category64_t c;
5661   const char *r;
5662   uint32_t offset, xoffset, left;
5663   SectionRef S, xS;
5664   const char *name, *sym_name;
5665   uint64_t n_value;
5666 
5667   r = get_pointer_64(p, offset, left, S, info);
5668   if (r == nullptr)
5669     return;
5670   memset(&c, '\0', sizeof(struct category64_t));
5671   if (left < sizeof(struct category64_t)) {
5672     memcpy(&c, r, left);
5673     outs() << "   (category_t entends past the end of the section)\n";
5674   } else
5675     memcpy(&c, r, sizeof(struct category64_t));
5676   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5677     swapStruct(c);
5678 
5679   outs() << "              name ";
5680   sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
5681                            info, n_value, c.name);
5682   if (n_value != 0) {
5683     if (info->verbose && sym_name != nullptr)
5684       outs() << sym_name;
5685     else
5686       outs() << format("0x%" PRIx64, n_value);
5687     if (c.name != 0)
5688       outs() << " + " << format("0x%" PRIx64, c.name);
5689   } else
5690     outs() << format("0x%" PRIx64, c.name);
5691   name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
5692   if (name != nullptr)
5693     outs() << format(" %.*s", left, name);
5694   outs() << "\n";
5695 
5696   outs() << "               cls ";
5697   sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
5698                            n_value, c.cls);
5699   if (n_value != 0) {
5700     if (info->verbose && sym_name != nullptr)
5701       outs() << sym_name;
5702     else
5703       outs() << format("0x%" PRIx64, n_value);
5704     if (c.cls != 0)
5705       outs() << " + " << format("0x%" PRIx64, c.cls);
5706   } else
5707     outs() << format("0x%" PRIx64, c.cls);
5708   outs() << "\n";
5709   if (c.cls + n_value != 0)
5710     print_class64_t(c.cls + n_value, info);
5711 
5712   outs() << "   instanceMethods ";
5713   sym_name =
5714       get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
5715                     info, n_value, c.instanceMethods);
5716   if (n_value != 0) {
5717     if (info->verbose && sym_name != nullptr)
5718       outs() << sym_name;
5719     else
5720       outs() << format("0x%" PRIx64, n_value);
5721     if (c.instanceMethods != 0)
5722       outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
5723   } else
5724     outs() << format("0x%" PRIx64, c.instanceMethods);
5725   outs() << "\n";
5726   if (c.instanceMethods + n_value != 0)
5727     print_method_list64_t(c.instanceMethods + n_value, info, "");
5728 
5729   outs() << "      classMethods ";
5730   sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
5731                            S, info, n_value, c.classMethods);
5732   if (n_value != 0) {
5733     if (info->verbose && sym_name != nullptr)
5734       outs() << sym_name;
5735     else
5736       outs() << format("0x%" PRIx64, n_value);
5737     if (c.classMethods != 0)
5738       outs() << " + " << format("0x%" PRIx64, c.classMethods);
5739   } else
5740     outs() << format("0x%" PRIx64, c.classMethods);
5741   outs() << "\n";
5742   if (c.classMethods + n_value != 0)
5743     print_method_list64_t(c.classMethods + n_value, info, "");
5744 
5745   outs() << "         protocols ";
5746   sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
5747                            info, n_value, c.protocols);
5748   if (n_value != 0) {
5749     if (info->verbose && sym_name != nullptr)
5750       outs() << sym_name;
5751     else
5752       outs() << format("0x%" PRIx64, n_value);
5753     if (c.protocols != 0)
5754       outs() << " + " << format("0x%" PRIx64, c.protocols);
5755   } else
5756     outs() << format("0x%" PRIx64, c.protocols);
5757   outs() << "\n";
5758   if (c.protocols + n_value != 0)
5759     print_protocol_list64_t(c.protocols + n_value, info);
5760 
5761   outs() << "instanceProperties ";
5762   sym_name =
5763       get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
5764                     S, info, n_value, c.instanceProperties);
5765   if (n_value != 0) {
5766     if (info->verbose && sym_name != nullptr)
5767       outs() << sym_name;
5768     else
5769       outs() << format("0x%" PRIx64, n_value);
5770     if (c.instanceProperties != 0)
5771       outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
5772   } else
5773     outs() << format("0x%" PRIx64, c.instanceProperties);
5774   outs() << "\n";
5775   if (c.instanceProperties + n_value != 0)
5776     print_objc_property_list64(c.instanceProperties + n_value, info);
5777 }
5778 
5779 static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
5780   struct category32_t c;
5781   const char *r;
5782   uint32_t offset, left;
5783   SectionRef S, xS;
5784   const char *name;
5785 
5786   r = get_pointer_32(p, offset, left, S, info);
5787   if (r == nullptr)
5788     return;
5789   memset(&c, '\0', sizeof(struct category32_t));
5790   if (left < sizeof(struct category32_t)) {
5791     memcpy(&c, r, left);
5792     outs() << "   (category_t entends past the end of the section)\n";
5793   } else
5794     memcpy(&c, r, sizeof(struct category32_t));
5795   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5796     swapStruct(c);
5797 
5798   outs() << "              name " << format("0x%" PRIx32, c.name);
5799   name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
5800                        c.name);
5801   if (name)
5802     outs() << " " << name;
5803   outs() << "\n";
5804 
5805   outs() << "               cls " << format("0x%" PRIx32, c.cls) << "\n";
5806   if (c.cls != 0)
5807     print_class32_t(c.cls, info);
5808   outs() << "   instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
5809          << "\n";
5810   if (c.instanceMethods != 0)
5811     print_method_list32_t(c.instanceMethods, info, "");
5812   outs() << "      classMethods " << format("0x%" PRIx32, c.classMethods)
5813          << "\n";
5814   if (c.classMethods != 0)
5815     print_method_list32_t(c.classMethods, info, "");
5816   outs() << "         protocols " << format("0x%" PRIx32, c.protocols) << "\n";
5817   if (c.protocols != 0)
5818     print_protocol_list32_t(c.protocols, info);
5819   outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
5820          << "\n";
5821   if (c.instanceProperties != 0)
5822     print_objc_property_list32(c.instanceProperties, info);
5823 }
5824 
5825 static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
5826   uint32_t i, left, offset, xoffset;
5827   uint64_t p, n_value;
5828   struct message_ref64 mr;
5829   const char *name, *sym_name;
5830   const char *r;
5831   SectionRef xS;
5832 
5833   if (S == SectionRef())
5834     return;
5835 
5836   StringRef SectName;
5837   Expected<StringRef> SecNameOrErr = S.getName();
5838   if (SecNameOrErr)
5839     SectName = *SecNameOrErr;
5840   else
5841     consumeError(SecNameOrErr.takeError());
5842 
5843   DataRefImpl Ref = S.getRawDataRefImpl();
5844   StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5845   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5846   offset = 0;
5847   for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5848     p = S.getAddress() + i;
5849     r = get_pointer_64(p, offset, left, S, info);
5850     if (r == nullptr)
5851       return;
5852     memset(&mr, '\0', sizeof(struct message_ref64));
5853     if (left < sizeof(struct message_ref64)) {
5854       memcpy(&mr, r, left);
5855       outs() << "   (message_ref entends past the end of the section)\n";
5856     } else
5857       memcpy(&mr, r, sizeof(struct message_ref64));
5858     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5859       swapStruct(mr);
5860 
5861     outs() << "  imp ";
5862     name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
5863                          n_value, mr.imp);
5864     if (n_value != 0) {
5865       outs() << format("0x%" PRIx64, n_value) << " ";
5866       if (mr.imp != 0)
5867         outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
5868     } else
5869       outs() << format("0x%" PRIx64, mr.imp) << " ";
5870     if (name != nullptr)
5871       outs() << " " << name;
5872     outs() << "\n";
5873 
5874     outs() << "  sel ";
5875     sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
5876                              info, n_value, mr.sel);
5877     if (n_value != 0) {
5878       if (info->verbose && sym_name != nullptr)
5879         outs() << sym_name;
5880       else
5881         outs() << format("0x%" PRIx64, n_value);
5882       if (mr.sel != 0)
5883         outs() << " + " << format("0x%" PRIx64, mr.sel);
5884     } else
5885       outs() << format("0x%" PRIx64, mr.sel);
5886     name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
5887     if (name != nullptr)
5888       outs() << format(" %.*s", left, name);
5889     outs() << "\n";
5890 
5891     offset += sizeof(struct message_ref64);
5892   }
5893 }
5894 
5895 static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
5896   uint32_t i, left, offset, xoffset, p;
5897   struct message_ref32 mr;
5898   const char *name, *r;
5899   SectionRef xS;
5900 
5901   if (S == SectionRef())
5902     return;
5903 
5904   StringRef SectName;
5905   Expected<StringRef> SecNameOrErr = S.getName();
5906   if (SecNameOrErr)
5907     SectName = *SecNameOrErr;
5908   else
5909     consumeError(SecNameOrErr.takeError());
5910 
5911   DataRefImpl Ref = S.getRawDataRefImpl();
5912   StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5913   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5914   offset = 0;
5915   for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5916     p = S.getAddress() + i;
5917     r = get_pointer_32(p, offset, left, S, info);
5918     if (r == nullptr)
5919       return;
5920     memset(&mr, '\0', sizeof(struct message_ref32));
5921     if (left < sizeof(struct message_ref32)) {
5922       memcpy(&mr, r, left);
5923       outs() << "   (message_ref entends past the end of the section)\n";
5924     } else
5925       memcpy(&mr, r, sizeof(struct message_ref32));
5926     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5927       swapStruct(mr);
5928 
5929     outs() << "  imp " << format("0x%" PRIx32, mr.imp);
5930     name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
5931                          mr.imp);
5932     if (name != nullptr)
5933       outs() << " " << name;
5934     outs() << "\n";
5935 
5936     outs() << "  sel " << format("0x%" PRIx32, mr.sel);
5937     name = get_pointer_32(mr.sel, xoffset, left, xS, info);
5938     if (name != nullptr)
5939       outs() << " " << name;
5940     outs() << "\n";
5941 
5942     offset += sizeof(struct message_ref32);
5943   }
5944 }
5945 
5946 static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
5947   uint32_t left, offset, swift_version;
5948   uint64_t p;
5949   struct objc_image_info64 o;
5950   const char *r;
5951 
5952   if (S == SectionRef())
5953     return;
5954 
5955   StringRef SectName;
5956   Expected<StringRef> SecNameOrErr = S.getName();
5957   if (SecNameOrErr)
5958     SectName = *SecNameOrErr;
5959   else
5960     consumeError(SecNameOrErr.takeError());
5961 
5962   DataRefImpl Ref = S.getRawDataRefImpl();
5963   StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5964   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5965   p = S.getAddress();
5966   r = get_pointer_64(p, offset, left, S, info);
5967   if (r == nullptr)
5968     return;
5969   memset(&o, '\0', sizeof(struct objc_image_info64));
5970   if (left < sizeof(struct objc_image_info64)) {
5971     memcpy(&o, r, left);
5972     outs() << "   (objc_image_info entends past the end of the section)\n";
5973   } else
5974     memcpy(&o, r, sizeof(struct objc_image_info64));
5975   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5976     swapStruct(o);
5977   outs() << "  version " << o.version << "\n";
5978   outs() << "    flags " << format("0x%" PRIx32, o.flags);
5979   if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5980     outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5981   if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5982     outs() << " OBJC_IMAGE_SUPPORTS_GC";
5983   if (o.flags & OBJC_IMAGE_IS_SIMULATED)
5984     outs() << " OBJC_IMAGE_IS_SIMULATED";
5985   if (o.flags & OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES)
5986     outs() << " OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES";
5987   swift_version = (o.flags >> 8) & 0xff;
5988   if (swift_version != 0) {
5989     if (swift_version == 1)
5990       outs() << " Swift 1.0";
5991     else if (swift_version == 2)
5992       outs() << " Swift 1.1";
5993     else if(swift_version == 3)
5994       outs() << " Swift 2.0";
5995     else if(swift_version == 4)
5996       outs() << " Swift 3.0";
5997     else if(swift_version == 5)
5998       outs() << " Swift 4.0";
5999     else if(swift_version == 6)
6000       outs() << " Swift 4.1/Swift 4.2";
6001     else if(swift_version == 7)
6002       outs() << " Swift 5 or later";
6003     else
6004       outs() << " unknown future Swift version (" << swift_version << ")";
6005   }
6006   outs() << "\n";
6007 }
6008 
6009 static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
6010   uint32_t left, offset, swift_version, p;
6011   struct objc_image_info32 o;
6012   const char *r;
6013 
6014   if (S == SectionRef())
6015     return;
6016 
6017   StringRef SectName;
6018   Expected<StringRef> SecNameOrErr = S.getName();
6019   if (SecNameOrErr)
6020     SectName = *SecNameOrErr;
6021   else
6022     consumeError(SecNameOrErr.takeError());
6023 
6024   DataRefImpl Ref = S.getRawDataRefImpl();
6025   StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
6026   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
6027   p = S.getAddress();
6028   r = get_pointer_32(p, offset, left, S, info);
6029   if (r == nullptr)
6030     return;
6031   memset(&o, '\0', sizeof(struct objc_image_info32));
6032   if (left < sizeof(struct objc_image_info32)) {
6033     memcpy(&o, r, left);
6034     outs() << "   (objc_image_info entends past the end of the section)\n";
6035   } else
6036     memcpy(&o, r, sizeof(struct objc_image_info32));
6037   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
6038     swapStruct(o);
6039   outs() << "  version " << o.version << "\n";
6040   outs() << "    flags " << format("0x%" PRIx32, o.flags);
6041   if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
6042     outs() << " OBJC_IMAGE_IS_REPLACEMENT";
6043   if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
6044     outs() << " OBJC_IMAGE_SUPPORTS_GC";
6045   swift_version = (o.flags >> 8) & 0xff;
6046   if (swift_version != 0) {
6047     if (swift_version == 1)
6048       outs() << " Swift 1.0";
6049     else if (swift_version == 2)
6050       outs() << " Swift 1.1";
6051     else if(swift_version == 3)
6052       outs() << " Swift 2.0";
6053     else if(swift_version == 4)
6054       outs() << " Swift 3.0";
6055     else if(swift_version == 5)
6056       outs() << " Swift 4.0";
6057     else if(swift_version == 6)
6058       outs() << " Swift 4.1/Swift 4.2";
6059     else if(swift_version == 7)
6060       outs() << " Swift 5 or later";
6061     else
6062       outs() << " unknown future Swift version (" << swift_version << ")";
6063   }
6064   outs() << "\n";
6065 }
6066 
6067 static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
6068   uint32_t left, offset, p;
6069   struct imageInfo_t o;
6070   const char *r;
6071 
6072   StringRef SectName;
6073   Expected<StringRef> SecNameOrErr = S.getName();
6074   if (SecNameOrErr)
6075     SectName = *SecNameOrErr;
6076   else
6077     consumeError(SecNameOrErr.takeError());
6078 
6079   DataRefImpl Ref = S.getRawDataRefImpl();
6080   StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
6081   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
6082   p = S.getAddress();
6083   r = get_pointer_32(p, offset, left, S, info);
6084   if (r == nullptr)
6085     return;
6086   memset(&o, '\0', sizeof(struct imageInfo_t));
6087   if (left < sizeof(struct imageInfo_t)) {
6088     memcpy(&o, r, left);
6089     outs() << " (imageInfo entends past the end of the section)\n";
6090   } else
6091     memcpy(&o, r, sizeof(struct imageInfo_t));
6092   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
6093     swapStruct(o);
6094   outs() << "  version " << o.version << "\n";
6095   outs() << "    flags " << format("0x%" PRIx32, o.flags);
6096   if (o.flags & 0x1)
6097     outs() << "  F&C";
6098   if (o.flags & 0x2)
6099     outs() << " GC";
6100   if (o.flags & 0x4)
6101     outs() << " GC-only";
6102   else
6103     outs() << " RR";
6104   outs() << "\n";
6105 }
6106 
6107 static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
6108   SymbolAddressMap AddrMap;
6109   if (verbose)
6110     CreateSymbolAddressMap(O, &AddrMap);
6111 
6112   std::vector<SectionRef> Sections;
6113   for (const SectionRef &Section : O->sections())
6114     Sections.push_back(Section);
6115 
6116   struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
6117 
6118   SectionRef CL = get_section(O, "__OBJC2", "__class_list");
6119   if (CL == SectionRef())
6120     CL = get_section(O, "__DATA", "__objc_classlist");
6121   if (CL == SectionRef())
6122     CL = get_section(O, "__DATA_CONST", "__objc_classlist");
6123   if (CL == SectionRef())
6124     CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
6125   info.S = CL;
6126   walk_pointer_list_64("class", CL, O, &info, print_class64_t);
6127 
6128   SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
6129   if (CR == SectionRef())
6130     CR = get_section(O, "__DATA", "__objc_classrefs");
6131   if (CR == SectionRef())
6132     CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
6133   if (CR == SectionRef())
6134     CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
6135   info.S = CR;
6136   walk_pointer_list_64("class refs", CR, O, &info, nullptr);
6137 
6138   SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
6139   if (SR == SectionRef())
6140     SR = get_section(O, "__DATA", "__objc_superrefs");
6141   if (SR == SectionRef())
6142     SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
6143   if (SR == SectionRef())
6144     SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
6145   info.S = SR;
6146   walk_pointer_list_64("super refs", SR, O, &info, nullptr);
6147 
6148   SectionRef CA = get_section(O, "__OBJC2", "__category_list");
6149   if (CA == SectionRef())
6150     CA = get_section(O, "__DATA", "__objc_catlist");
6151   if (CA == SectionRef())
6152     CA = get_section(O, "__DATA_CONST", "__objc_catlist");
6153   if (CA == SectionRef())
6154     CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
6155   info.S = CA;
6156   walk_pointer_list_64("category", CA, O, &info, print_category64_t);
6157 
6158   SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
6159   if (PL == SectionRef())
6160     PL = get_section(O, "__DATA", "__objc_protolist");
6161   if (PL == SectionRef())
6162     PL = get_section(O, "__DATA_CONST", "__objc_protolist");
6163   if (PL == SectionRef())
6164     PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
6165   info.S = PL;
6166   walk_pointer_list_64("protocol", PL, O, &info, nullptr);
6167 
6168   SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
6169   if (MR == SectionRef())
6170     MR = get_section(O, "__DATA", "__objc_msgrefs");
6171   if (MR == SectionRef())
6172     MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
6173   if (MR == SectionRef())
6174     MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
6175   info.S = MR;
6176   print_message_refs64(MR, &info);
6177 
6178   SectionRef II = get_section(O, "__OBJC2", "__image_info");
6179   if (II == SectionRef())
6180     II = get_section(O, "__DATA", "__objc_imageinfo");
6181   if (II == SectionRef())
6182     II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
6183   if (II == SectionRef())
6184     II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
6185   info.S = II;
6186   print_image_info64(II, &info);
6187 }
6188 
6189 static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
6190   SymbolAddressMap AddrMap;
6191   if (verbose)
6192     CreateSymbolAddressMap(O, &AddrMap);
6193 
6194   std::vector<SectionRef> Sections;
6195   for (const SectionRef &Section : O->sections())
6196     Sections.push_back(Section);
6197 
6198   struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
6199 
6200   SectionRef CL = get_section(O, "__OBJC2", "__class_list");
6201   if (CL == SectionRef())
6202     CL = get_section(O, "__DATA", "__objc_classlist");
6203   if (CL == SectionRef())
6204     CL = get_section(O, "__DATA_CONST", "__objc_classlist");
6205   if (CL == SectionRef())
6206     CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
6207   info.S = CL;
6208   walk_pointer_list_32("class", CL, O, &info, print_class32_t);
6209 
6210   SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
6211   if (CR == SectionRef())
6212     CR = get_section(O, "__DATA", "__objc_classrefs");
6213   if (CR == SectionRef())
6214     CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
6215   if (CR == SectionRef())
6216     CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
6217   info.S = CR;
6218   walk_pointer_list_32("class refs", CR, O, &info, nullptr);
6219 
6220   SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
6221   if (SR == SectionRef())
6222     SR = get_section(O, "__DATA", "__objc_superrefs");
6223   if (SR == SectionRef())
6224     SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
6225   if (SR == SectionRef())
6226     SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
6227   info.S = SR;
6228   walk_pointer_list_32("super refs", SR, O, &info, nullptr);
6229 
6230   SectionRef CA = get_section(O, "__OBJC2", "__category_list");
6231   if (CA == SectionRef())
6232     CA = get_section(O, "__DATA", "__objc_catlist");
6233   if (CA == SectionRef())
6234     CA = get_section(O, "__DATA_CONST", "__objc_catlist");
6235   if (CA == SectionRef())
6236     CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
6237   info.S = CA;
6238   walk_pointer_list_32("category", CA, O, &info, print_category32_t);
6239 
6240   SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
6241   if (PL == SectionRef())
6242     PL = get_section(O, "__DATA", "__objc_protolist");
6243   if (PL == SectionRef())
6244     PL = get_section(O, "__DATA_CONST", "__objc_protolist");
6245   if (PL == SectionRef())
6246     PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
6247   info.S = PL;
6248   walk_pointer_list_32("protocol", PL, O, &info, nullptr);
6249 
6250   SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
6251   if (MR == SectionRef())
6252     MR = get_section(O, "__DATA", "__objc_msgrefs");
6253   if (MR == SectionRef())
6254     MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
6255   if (MR == SectionRef())
6256     MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
6257   info.S = MR;
6258   print_message_refs32(MR, &info);
6259 
6260   SectionRef II = get_section(O, "__OBJC2", "__image_info");
6261   if (II == SectionRef())
6262     II = get_section(O, "__DATA", "__objc_imageinfo");
6263   if (II == SectionRef())
6264     II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
6265   if (II == SectionRef())
6266     II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
6267   info.S = II;
6268   print_image_info32(II, &info);
6269 }
6270 
6271 static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
6272   uint32_t i, j, p, offset, xoffset, left, defs_left, def;
6273   const char *r, *name, *defs;
6274   struct objc_module_t module;
6275   SectionRef S, xS;
6276   struct objc_symtab_t symtab;
6277   struct objc_class_t objc_class;
6278   struct objc_category_t objc_category;
6279 
6280   outs() << "Objective-C segment\n";
6281   S = get_section(O, "__OBJC", "__module_info");
6282   if (S == SectionRef())
6283     return false;
6284 
6285   SymbolAddressMap AddrMap;
6286   if (verbose)
6287     CreateSymbolAddressMap(O, &AddrMap);
6288 
6289   std::vector<SectionRef> Sections;
6290   for (const SectionRef &Section : O->sections())
6291     Sections.push_back(Section);
6292 
6293   struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
6294 
6295   for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
6296     p = S.getAddress() + i;
6297     r = get_pointer_32(p, offset, left, S, &info, true);
6298     if (r == nullptr)
6299       return true;
6300     memset(&module, '\0', sizeof(struct objc_module_t));
6301     if (left < sizeof(struct objc_module_t)) {
6302       memcpy(&module, r, left);
6303       outs() << "   (module extends past end of __module_info section)\n";
6304     } else
6305       memcpy(&module, r, sizeof(struct objc_module_t));
6306     if (O->isLittleEndian() != sys::IsLittleEndianHost)
6307       swapStruct(module);
6308 
6309     outs() << "Module " << format("0x%" PRIx32, p) << "\n";
6310     outs() << "    version " << module.version << "\n";
6311     outs() << "       size " << module.size << "\n";
6312     outs() << "       name ";
6313     name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
6314     if (name != nullptr)
6315       outs() << format("%.*s", left, name);
6316     else
6317       outs() << format("0x%08" PRIx32, module.name)
6318              << "(not in an __OBJC section)";
6319     outs() << "\n";
6320 
6321     r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
6322     if (module.symtab == 0 || r == nullptr) {
6323       outs() << "     symtab " << format("0x%08" PRIx32, module.symtab)
6324              << " (not in an __OBJC section)\n";
6325       continue;
6326     }
6327     outs() << "     symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
6328     memset(&symtab, '\0', sizeof(struct objc_symtab_t));
6329     defs_left = 0;
6330     defs = nullptr;
6331     if (left < sizeof(struct objc_symtab_t)) {
6332       memcpy(&symtab, r, left);
6333       outs() << "\tsymtab extends past end of an __OBJC section)\n";
6334     } else {
6335       memcpy(&symtab, r, sizeof(struct objc_symtab_t));
6336       if (left > sizeof(struct objc_symtab_t)) {
6337         defs_left = left - sizeof(struct objc_symtab_t);
6338         defs = r + sizeof(struct objc_symtab_t);
6339       }
6340     }
6341     if (O->isLittleEndian() != sys::IsLittleEndianHost)
6342       swapStruct(symtab);
6343 
6344     outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
6345     r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
6346     outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
6347     if (r == nullptr)
6348       outs() << " (not in an __OBJC section)";
6349     outs() << "\n";
6350     outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
6351     outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
6352     if (symtab.cls_def_cnt > 0)
6353       outs() << "\tClass Definitions\n";
6354     for (j = 0; j < symtab.cls_def_cnt; j++) {
6355       if ((j + 1) * sizeof(uint32_t) > defs_left) {
6356         outs() << "\t(remaining class defs entries entends past the end of the "
6357                << "section)\n";
6358         break;
6359       }
6360       memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
6361       if (O->isLittleEndian() != sys::IsLittleEndianHost)
6362         sys::swapByteOrder(def);
6363 
6364       r = get_pointer_32(def, xoffset, left, xS, &info, true);
6365       outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
6366       if (r != nullptr) {
6367         if (left > sizeof(struct objc_class_t)) {
6368           outs() << "\n";
6369           memcpy(&objc_class, r, sizeof(struct objc_class_t));
6370         } else {
6371           outs() << " (entends past the end of the section)\n";
6372           memset(&objc_class, '\0', sizeof(struct objc_class_t));
6373           memcpy(&objc_class, r, left);
6374         }
6375         if (O->isLittleEndian() != sys::IsLittleEndianHost)
6376           swapStruct(objc_class);
6377         print_objc_class_t(&objc_class, &info);
6378       } else {
6379         outs() << "(not in an __OBJC section)\n";
6380       }
6381 
6382       if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
6383         outs() << "\tMeta Class";
6384         r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
6385         if (r != nullptr) {
6386           if (left > sizeof(struct objc_class_t)) {
6387             outs() << "\n";
6388             memcpy(&objc_class, r, sizeof(struct objc_class_t));
6389           } else {
6390             outs() << " (entends past the end of the section)\n";
6391             memset(&objc_class, '\0', sizeof(struct objc_class_t));
6392             memcpy(&objc_class, r, left);
6393           }
6394           if (O->isLittleEndian() != sys::IsLittleEndianHost)
6395             swapStruct(objc_class);
6396           print_objc_class_t(&objc_class, &info);
6397         } else {
6398           outs() << "(not in an __OBJC section)\n";
6399         }
6400       }
6401     }
6402     if (symtab.cat_def_cnt > 0)
6403       outs() << "\tCategory Definitions\n";
6404     for (j = 0; j < symtab.cat_def_cnt; j++) {
6405       if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
6406         outs() << "\t(remaining category defs entries entends past the end of "
6407                << "the section)\n";
6408         break;
6409       }
6410       memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
6411              sizeof(uint32_t));
6412       if (O->isLittleEndian() != sys::IsLittleEndianHost)
6413         sys::swapByteOrder(def);
6414 
6415       r = get_pointer_32(def, xoffset, left, xS, &info, true);
6416       outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
6417              << format("0x%08" PRIx32, def);
6418       if (r != nullptr) {
6419         if (left > sizeof(struct objc_category_t)) {
6420           outs() << "\n";
6421           memcpy(&objc_category, r, sizeof(struct objc_category_t));
6422         } else {
6423           outs() << " (entends past the end of the section)\n";
6424           memset(&objc_category, '\0', sizeof(struct objc_category_t));
6425           memcpy(&objc_category, r, left);
6426         }
6427         if (O->isLittleEndian() != sys::IsLittleEndianHost)
6428           swapStruct(objc_category);
6429         print_objc_objc_category_t(&objc_category, &info);
6430       } else {
6431         outs() << "(not in an __OBJC section)\n";
6432       }
6433     }
6434   }
6435   const SectionRef II = get_section(O, "__OBJC", "__image_info");
6436   if (II != SectionRef())
6437     print_image_info(II, &info);
6438 
6439   return true;
6440 }
6441 
6442 static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
6443                                 uint32_t size, uint32_t addr) {
6444   SymbolAddressMap AddrMap;
6445   CreateSymbolAddressMap(O, &AddrMap);
6446 
6447   std::vector<SectionRef> Sections;
6448   for (const SectionRef &Section : O->sections())
6449     Sections.push_back(Section);
6450 
6451   struct DisassembleInfo info(O, &AddrMap, &Sections, true);
6452 
6453   const char *p;
6454   struct objc_protocol_t protocol;
6455   uint32_t left, paddr;
6456   for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
6457     memset(&protocol, '\0', sizeof(struct objc_protocol_t));
6458     left = size - (p - sect);
6459     if (left < sizeof(struct objc_protocol_t)) {
6460       outs() << "Protocol extends past end of __protocol section\n";
6461       memcpy(&protocol, p, left);
6462     } else
6463       memcpy(&protocol, p, sizeof(struct objc_protocol_t));
6464     if (O->isLittleEndian() != sys::IsLittleEndianHost)
6465       swapStruct(protocol);
6466     paddr = addr + (p - sect);
6467     outs() << "Protocol " << format("0x%" PRIx32, paddr);
6468     if (print_protocol(paddr, 0, &info))
6469       outs() << "(not in an __OBJC section)\n";
6470   }
6471 }
6472 
6473 #ifdef HAVE_LIBXAR
6474 static inline void swapStruct(struct xar_header &xar) {
6475   sys::swapByteOrder(xar.magic);
6476   sys::swapByteOrder(xar.size);
6477   sys::swapByteOrder(xar.version);
6478   sys::swapByteOrder(xar.toc_length_compressed);
6479   sys::swapByteOrder(xar.toc_length_uncompressed);
6480   sys::swapByteOrder(xar.cksum_alg);
6481 }
6482 
6483 static void PrintModeVerbose(uint32_t mode) {
6484   switch(mode & S_IFMT){
6485   case S_IFDIR:
6486     outs() << "d";
6487     break;
6488   case S_IFCHR:
6489     outs() << "c";
6490     break;
6491   case S_IFBLK:
6492     outs() << "b";
6493     break;
6494   case S_IFREG:
6495     outs() << "-";
6496     break;
6497   case S_IFLNK:
6498     outs() << "l";
6499     break;
6500   case S_IFSOCK:
6501     outs() << "s";
6502     break;
6503   default:
6504     outs() << "?";
6505     break;
6506   }
6507 
6508   /* owner permissions */
6509   if(mode & S_IREAD)
6510     outs() << "r";
6511   else
6512     outs() << "-";
6513   if(mode & S_IWRITE)
6514     outs() << "w";
6515   else
6516     outs() << "-";
6517   if(mode & S_ISUID)
6518     outs() << "s";
6519   else if(mode & S_IEXEC)
6520     outs() << "x";
6521   else
6522     outs() << "-";
6523 
6524   /* group permissions */
6525   if(mode & (S_IREAD >> 3))
6526     outs() << "r";
6527   else
6528     outs() << "-";
6529   if(mode & (S_IWRITE >> 3))
6530     outs() << "w";
6531   else
6532     outs() << "-";
6533   if(mode & S_ISGID)
6534     outs() << "s";
6535   else if(mode & (S_IEXEC >> 3))
6536     outs() << "x";
6537   else
6538     outs() << "-";
6539 
6540   /* other permissions */
6541   if(mode & (S_IREAD >> 6))
6542     outs() << "r";
6543   else
6544     outs() << "-";
6545   if(mode & (S_IWRITE >> 6))
6546     outs() << "w";
6547   else
6548     outs() << "-";
6549   if(mode & S_ISVTX)
6550     outs() << "t";
6551   else if(mode & (S_IEXEC >> 6))
6552     outs() << "x";
6553   else
6554     outs() << "-";
6555 }
6556 
6557 static void PrintXarFilesSummary(const char *XarFilename, xar_t xar) {
6558   xar_file_t xf;
6559   const char *key, *type, *mode, *user, *group, *size, *mtime, *name, *m;
6560   char *endp;
6561   uint32_t mode_value;
6562 
6563   ScopedXarIter xi;
6564   if (!xi) {
6565     WithColor::error(errs(), "llvm-objdump")
6566         << "can't obtain an xar iterator for xar archive " << XarFilename
6567         << "\n";
6568     return;
6569   }
6570 
6571   // Go through the xar's files.
6572   for (xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)) {
6573     ScopedXarIter xp;
6574     if(!xp){
6575       WithColor::error(errs(), "llvm-objdump")
6576           << "can't obtain an xar iterator for xar archive " << XarFilename
6577           << "\n";
6578       return;
6579     }
6580     type = nullptr;
6581     mode = nullptr;
6582     user = nullptr;
6583     group = nullptr;
6584     size = nullptr;
6585     mtime = nullptr;
6586     name = nullptr;
6587     for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
6588       const char *val = nullptr;
6589       xar_prop_get(xf, key, &val);
6590 #if 0 // Useful for debugging.
6591       outs() << "key: " << key << " value: " << val << "\n";
6592 #endif
6593       if(strcmp(key, "type") == 0)
6594         type = val;
6595       if(strcmp(key, "mode") == 0)
6596         mode = val;
6597       if(strcmp(key, "user") == 0)
6598         user = val;
6599       if(strcmp(key, "group") == 0)
6600         group = val;
6601       if(strcmp(key, "data/size") == 0)
6602         size = val;
6603       if(strcmp(key, "mtime") == 0)
6604         mtime = val;
6605       if(strcmp(key, "name") == 0)
6606         name = val;
6607     }
6608     if(mode != nullptr){
6609       mode_value = strtoul(mode, &endp, 8);
6610       if(*endp != '\0')
6611         outs() << "(mode: \"" << mode << "\" contains non-octal chars) ";
6612       if(strcmp(type, "file") == 0)
6613         mode_value |= S_IFREG;
6614       PrintModeVerbose(mode_value);
6615       outs() << " ";
6616     }
6617     if(user != nullptr)
6618       outs() << format("%10s/", user);
6619     if(group != nullptr)
6620       outs() << format("%-10s ", group);
6621     if(size != nullptr)
6622       outs() << format("%7s ", size);
6623     if(mtime != nullptr){
6624       for(m = mtime; *m != 'T' && *m != '\0'; m++)
6625         outs() << *m;
6626       if(*m == 'T')
6627         m++;
6628       outs() << " ";
6629       for( ; *m != 'Z' && *m != '\0'; m++)
6630         outs() << *m;
6631       outs() << " ";
6632     }
6633     if(name != nullptr)
6634       outs() << name;
6635     outs() << "\n";
6636   }
6637 }
6638 
6639 static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
6640                                 uint32_t size, bool verbose,
6641                                 bool PrintXarHeader, bool PrintXarFileHeaders,
6642                                 std::string XarMemberName) {
6643   if(size < sizeof(struct xar_header)) {
6644     outs() << "size of (__LLVM,__bundle) section too small (smaller than size "
6645               "of struct xar_header)\n";
6646     return;
6647   }
6648   struct xar_header XarHeader;
6649   memcpy(&XarHeader, sect, sizeof(struct xar_header));
6650   if (sys::IsLittleEndianHost)
6651     swapStruct(XarHeader);
6652   if (PrintXarHeader) {
6653     if (!XarMemberName.empty())
6654       outs() << "In xar member " << XarMemberName << ": ";
6655     else
6656       outs() << "For (__LLVM,__bundle) section: ";
6657     outs() << "xar header\n";
6658     if (XarHeader.magic == XAR_HEADER_MAGIC)
6659       outs() << "                  magic XAR_HEADER_MAGIC\n";
6660     else
6661       outs() << "                  magic "
6662              << format_hex(XarHeader.magic, 10, true)
6663              << " (not XAR_HEADER_MAGIC)\n";
6664     outs() << "                   size " << XarHeader.size << "\n";
6665     outs() << "                version " << XarHeader.version << "\n";
6666     outs() << "  toc_length_compressed " << XarHeader.toc_length_compressed
6667            << "\n";
6668     outs() << "toc_length_uncompressed " << XarHeader.toc_length_uncompressed
6669            << "\n";
6670     outs() << "              cksum_alg ";
6671     switch (XarHeader.cksum_alg) {
6672       case XAR_CKSUM_NONE:
6673         outs() << "XAR_CKSUM_NONE\n";
6674         break;
6675       case XAR_CKSUM_SHA1:
6676         outs() << "XAR_CKSUM_SHA1\n";
6677         break;
6678       case XAR_CKSUM_MD5:
6679         outs() << "XAR_CKSUM_MD5\n";
6680         break;
6681 #ifdef XAR_CKSUM_SHA256
6682       case XAR_CKSUM_SHA256:
6683         outs() << "XAR_CKSUM_SHA256\n";
6684         break;
6685 #endif
6686 #ifdef XAR_CKSUM_SHA512
6687       case XAR_CKSUM_SHA512:
6688         outs() << "XAR_CKSUM_SHA512\n";
6689         break;
6690 #endif
6691       default:
6692         outs() << XarHeader.cksum_alg << "\n";
6693     }
6694   }
6695 
6696   SmallString<128> XarFilename;
6697   int FD;
6698   std::error_code XarEC =
6699       sys::fs::createTemporaryFile("llvm-objdump", "xar", FD, XarFilename);
6700   if (XarEC) {
6701     WithColor::error(errs(), "llvm-objdump") << XarEC.message() << "\n";
6702     return;
6703   }
6704   ToolOutputFile XarFile(XarFilename, FD);
6705   raw_fd_ostream &XarOut = XarFile.os();
6706   StringRef XarContents(sect, size);
6707   XarOut << XarContents;
6708   XarOut.close();
6709   if (XarOut.has_error())
6710     return;
6711 
6712   ScopedXarFile xar(XarFilename.c_str(), READ);
6713   if (!xar) {
6714     WithColor::error(errs(), "llvm-objdump")
6715         << "can't create temporary xar archive " << XarFilename << "\n";
6716     return;
6717   }
6718 
6719   SmallString<128> TocFilename;
6720   std::error_code TocEC =
6721       sys::fs::createTemporaryFile("llvm-objdump", "toc", TocFilename);
6722   if (TocEC) {
6723     WithColor::error(errs(), "llvm-objdump") << TocEC.message() << "\n";
6724     return;
6725   }
6726   xar_serialize(xar, TocFilename.c_str());
6727 
6728   if (PrintXarFileHeaders) {
6729     if (!XarMemberName.empty())
6730       outs() << "In xar member " << XarMemberName << ": ";
6731     else
6732       outs() << "For (__LLVM,__bundle) section: ";
6733     outs() << "xar archive files:\n";
6734     PrintXarFilesSummary(XarFilename.c_str(), xar);
6735   }
6736 
6737   ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
6738     MemoryBuffer::getFileOrSTDIN(TocFilename.c_str());
6739   if (std::error_code EC = FileOrErr.getError()) {
6740     WithColor::error(errs(), "llvm-objdump") << EC.message() << "\n";
6741     return;
6742   }
6743   std::unique_ptr<MemoryBuffer> &Buffer = FileOrErr.get();
6744 
6745   if (!XarMemberName.empty())
6746     outs() << "In xar member " << XarMemberName << ": ";
6747   else
6748     outs() << "For (__LLVM,__bundle) section: ";
6749   outs() << "xar table of contents:\n";
6750   outs() << Buffer->getBuffer() << "\n";
6751 
6752   // TODO: Go through the xar's files.
6753   ScopedXarIter xi;
6754   if(!xi){
6755     WithColor::error(errs(), "llvm-objdump")
6756         << "can't obtain an xar iterator for xar archive "
6757         << XarFilename.c_str() << "\n";
6758     return;
6759   }
6760   for(xar_file_t xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)){
6761     const char *key;
6762     const char *member_name, *member_type, *member_size_string;
6763     size_t member_size;
6764 
6765     ScopedXarIter xp;
6766     if(!xp){
6767       WithColor::error(errs(), "llvm-objdump")
6768           << "can't obtain an xar iterator for xar archive "
6769           << XarFilename.c_str() << "\n";
6770       return;
6771     }
6772     member_name = NULL;
6773     member_type = NULL;
6774     member_size_string = NULL;
6775     for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
6776       const char *val = nullptr;
6777       xar_prop_get(xf, key, &val);
6778 #if 0 // Useful for debugging.
6779       outs() << "key: " << key << " value: " << val << "\n";
6780 #endif
6781       if (strcmp(key, "name") == 0)
6782         member_name = val;
6783       if (strcmp(key, "type") == 0)
6784         member_type = val;
6785       if (strcmp(key, "data/size") == 0)
6786         member_size_string = val;
6787     }
6788     /*
6789      * If we find a file with a name, date/size and type properties
6790      * and with the type being "file" see if that is a xar file.
6791      */
6792     if (member_name != NULL && member_type != NULL &&
6793         strcmp(member_type, "file") == 0 &&
6794         member_size_string != NULL){
6795       // Extract the file into a buffer.
6796       char *endptr;
6797       member_size = strtoul(member_size_string, &endptr, 10);
6798       if (*endptr == '\0' && member_size != 0) {
6799         char *buffer;
6800         if (xar_extract_tobuffersz(xar, xf, &buffer, &member_size) == 0) {
6801 #if 0 // Useful for debugging.
6802           outs() << "xar member: " << member_name << " extracted\n";
6803 #endif
6804           // Set the XarMemberName we want to see printed in the header.
6805           std::string OldXarMemberName;
6806           // If XarMemberName is already set this is nested. So
6807           // save the old name and create the nested name.
6808           if (!XarMemberName.empty()) {
6809             OldXarMemberName = XarMemberName;
6810             XarMemberName =
6811                 (Twine("[") + XarMemberName + "]" + member_name).str();
6812           } else {
6813             OldXarMemberName = "";
6814             XarMemberName = member_name;
6815           }
6816           // See if this is could be a xar file (nested).
6817           if (member_size >= sizeof(struct xar_header)) {
6818 #if 0 // Useful for debugging.
6819             outs() << "could be a xar file: " << member_name << "\n";
6820 #endif
6821             memcpy((char *)&XarHeader, buffer, sizeof(struct xar_header));
6822             if (sys::IsLittleEndianHost)
6823               swapStruct(XarHeader);
6824             if (XarHeader.magic == XAR_HEADER_MAGIC)
6825               DumpBitcodeSection(O, buffer, member_size, verbose,
6826                                  PrintXarHeader, PrintXarFileHeaders,
6827                                  XarMemberName);
6828           }
6829           XarMemberName = OldXarMemberName;
6830           delete buffer;
6831         }
6832       }
6833     }
6834   }
6835 }
6836 #endif // defined(HAVE_LIBXAR)
6837 
6838 static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
6839   if (O->is64Bit())
6840     printObjc2_64bit_MetaData(O, verbose);
6841   else {
6842     MachO::mach_header H;
6843     H = O->getHeader();
6844     if (H.cputype == MachO::CPU_TYPE_ARM)
6845       printObjc2_32bit_MetaData(O, verbose);
6846     else {
6847       // This is the 32-bit non-arm cputype case.  Which is normally
6848       // the first Objective-C ABI.  But it may be the case of a
6849       // binary for the iOS simulator which is the second Objective-C
6850       // ABI.  In that case printObjc1_32bit_MetaData() will determine that
6851       // and return false.
6852       if (!printObjc1_32bit_MetaData(O, verbose))
6853         printObjc2_32bit_MetaData(O, verbose);
6854     }
6855   }
6856 }
6857 
6858 // GuessLiteralPointer returns a string which for the item in the Mach-O file
6859 // for the address passed in as ReferenceValue for printing as a comment with
6860 // the instruction and also returns the corresponding type of that item
6861 // indirectly through ReferenceType.
6862 //
6863 // If ReferenceValue is an address of literal cstring then a pointer to the
6864 // cstring is returned and ReferenceType is set to
6865 // LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
6866 //
6867 // If ReferenceValue is an address of an Objective-C CFString, Selector ref or
6868 // Class ref that name is returned and the ReferenceType is set accordingly.
6869 //
6870 // Lastly, literals which are Symbol address in a literal pool are looked for
6871 // and if found the symbol name is returned and ReferenceType is set to
6872 // LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
6873 //
6874 // If there is no item in the Mach-O file for the address passed in as
6875 // ReferenceValue nullptr is returned and ReferenceType is unchanged.
6876 static const char *GuessLiteralPointer(uint64_t ReferenceValue,
6877                                        uint64_t ReferencePC,
6878                                        uint64_t *ReferenceType,
6879                                        struct DisassembleInfo *info) {
6880   // First see if there is an external relocation entry at the ReferencePC.
6881   if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
6882     uint64_t sect_addr = info->S.getAddress();
6883     uint64_t sect_offset = ReferencePC - sect_addr;
6884     bool reloc_found = false;
6885     DataRefImpl Rel;
6886     MachO::any_relocation_info RE;
6887     bool isExtern = false;
6888     SymbolRef Symbol;
6889     for (const RelocationRef &Reloc : info->S.relocations()) {
6890       uint64_t RelocOffset = Reloc.getOffset();
6891       if (RelocOffset == sect_offset) {
6892         Rel = Reloc.getRawDataRefImpl();
6893         RE = info->O->getRelocation(Rel);
6894         if (info->O->isRelocationScattered(RE))
6895           continue;
6896         isExtern = info->O->getPlainRelocationExternal(RE);
6897         if (isExtern) {
6898           symbol_iterator RelocSym = Reloc.getSymbol();
6899           Symbol = *RelocSym;
6900         }
6901         reloc_found = true;
6902         break;
6903       }
6904     }
6905     // If there is an external relocation entry for a symbol in a section
6906     // then used that symbol's value for the value of the reference.
6907     if (reloc_found && isExtern) {
6908       if (info->O->getAnyRelocationPCRel(RE)) {
6909         unsigned Type = info->O->getAnyRelocationType(RE);
6910         if (Type == MachO::X86_64_RELOC_SIGNED) {
6911           ReferenceValue = Symbol.getValue();
6912         }
6913       }
6914     }
6915   }
6916 
6917   // Look for literals such as Objective-C CFStrings refs, Selector refs,
6918   // Message refs and Class refs.
6919   bool classref, selref, msgref, cfstring;
6920   uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
6921                                                selref, msgref, cfstring);
6922   if (classref && pointer_value == 0) {
6923     // Note the ReferenceValue is a pointer into the __objc_classrefs section.
6924     // And the pointer_value in that section is typically zero as it will be
6925     // set by dyld as part of the "bind information".
6926     const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
6927     if (name != nullptr) {
6928       *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
6929       const char *class_name = strrchr(name, '$');
6930       if (class_name != nullptr && class_name[1] == '_' &&
6931           class_name[2] != '\0') {
6932         info->class_name = class_name + 2;
6933         return name;
6934       }
6935     }
6936   }
6937 
6938   if (classref) {
6939     *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
6940     const char *name =
6941         get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
6942     if (name != nullptr)
6943       info->class_name = name;
6944     else
6945       name = "bad class ref";
6946     return name;
6947   }
6948 
6949   if (cfstring) {
6950     *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
6951     const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
6952     return name;
6953   }
6954 
6955   if (selref && pointer_value == 0)
6956     pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
6957 
6958   if (pointer_value != 0)
6959     ReferenceValue = pointer_value;
6960 
6961   const char *name = GuessCstringPointer(ReferenceValue, info);
6962   if (name) {
6963     if (pointer_value != 0 && selref) {
6964       *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
6965       info->selector_name = name;
6966     } else if (pointer_value != 0 && msgref) {
6967       info->class_name = nullptr;
6968       *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
6969       info->selector_name = name;
6970     } else
6971       *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
6972     return name;
6973   }
6974 
6975   // Lastly look for an indirect symbol with this ReferenceValue which is in
6976   // a literal pool.  If found return that symbol name.
6977   name = GuessIndirectSymbol(ReferenceValue, info);
6978   if (name) {
6979     *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
6980     return name;
6981   }
6982 
6983   return nullptr;
6984 }
6985 
6986 // SymbolizerSymbolLookUp is the symbol lookup function passed when creating
6987 // the Symbolizer.  It looks up the ReferenceValue using the info passed via the
6988 // pointer to the struct DisassembleInfo that was passed when MCSymbolizer
6989 // is created and returns the symbol name that matches the ReferenceValue or
6990 // nullptr if none.  The ReferenceType is passed in for the IN type of
6991 // reference the instruction is making from the values in defined in the header
6992 // "llvm-c/Disassembler.h".  On return the ReferenceType can set to a specific
6993 // Out type and the ReferenceName will also be set which is added as a comment
6994 // to the disassembled instruction.
6995 //
6996 // If the symbol name is a C++ mangled name then the demangled name is
6997 // returned through ReferenceName and ReferenceType is set to
6998 // LLVMDisassembler_ReferenceType_DeMangled_Name .
6999 //
7000 // When this is called to get a symbol name for a branch target then the
7001 // ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
7002 // SymbolValue will be looked for in the indirect symbol table to determine if
7003 // it is an address for a symbol stub.  If so then the symbol name for that
7004 // stub is returned indirectly through ReferenceName and then ReferenceType is
7005 // set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
7006 //
7007 // When this is called with an value loaded via a PC relative load then
7008 // ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
7009 // SymbolValue is checked to be an address of literal pointer, symbol pointer,
7010 // or an Objective-C meta data reference.  If so the output ReferenceType is
7011 // set to correspond to that as well as setting the ReferenceName.
7012 static const char *SymbolizerSymbolLookUp(void *DisInfo,
7013                                           uint64_t ReferenceValue,
7014                                           uint64_t *ReferenceType,
7015                                           uint64_t ReferencePC,
7016                                           const char **ReferenceName) {
7017   struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
7018   // If no verbose symbolic information is wanted then just return nullptr.
7019   if (!info->verbose) {
7020     *ReferenceName = nullptr;
7021     *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7022     return nullptr;
7023   }
7024 
7025   const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
7026 
7027   if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
7028     *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
7029     if (*ReferenceName != nullptr) {
7030       method_reference(info, ReferenceType, ReferenceName);
7031       if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
7032         *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
7033     } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
7034       if (info->demangled_name != nullptr)
7035         free(info->demangled_name);
7036       int status;
7037       info->demangled_name =
7038           itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
7039       if (info->demangled_name != nullptr) {
7040         *ReferenceName = info->demangled_name;
7041         *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
7042       } else
7043         *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7044     } else
7045       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7046   } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
7047     *ReferenceName =
7048         GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7049     if (*ReferenceName)
7050       method_reference(info, ReferenceType, ReferenceName);
7051     else
7052       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7053     // If this is arm64 and the reference is an adrp instruction save the
7054     // instruction, passed in ReferenceValue and the address of the instruction
7055     // for use later if we see and add immediate instruction.
7056   } else if (info->O->getArch() == Triple::aarch64 &&
7057              *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
7058     info->adrp_inst = ReferenceValue;
7059     info->adrp_addr = ReferencePC;
7060     SymbolName = nullptr;
7061     *ReferenceName = nullptr;
7062     *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7063     // If this is arm64 and reference is an add immediate instruction and we
7064     // have
7065     // seen an adrp instruction just before it and the adrp's Xd register
7066     // matches
7067     // this add's Xn register reconstruct the value being referenced and look to
7068     // see if it is a literal pointer.  Note the add immediate instruction is
7069     // passed in ReferenceValue.
7070   } else if (info->O->getArch() == Triple::aarch64 &&
7071              *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
7072              ReferencePC - 4 == info->adrp_addr &&
7073              (info->adrp_inst & 0x9f000000) == 0x90000000 &&
7074              (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
7075     uint32_t addxri_inst;
7076     uint64_t adrp_imm, addxri_imm;
7077 
7078     adrp_imm =
7079         ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
7080     if (info->adrp_inst & 0x0200000)
7081       adrp_imm |= 0xfffffffffc000000LL;
7082 
7083     addxri_inst = ReferenceValue;
7084     addxri_imm = (addxri_inst >> 10) & 0xfff;
7085     if (((addxri_inst >> 22) & 0x3) == 1)
7086       addxri_imm <<= 12;
7087 
7088     ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
7089                      (adrp_imm << 12) + addxri_imm;
7090 
7091     *ReferenceName =
7092         GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7093     if (*ReferenceName == nullptr)
7094       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7095     // If this is arm64 and the reference is a load register instruction and we
7096     // have seen an adrp instruction just before it and the adrp's Xd register
7097     // matches this add's Xn register reconstruct the value being referenced and
7098     // look to see if it is a literal pointer.  Note the load register
7099     // instruction is passed in ReferenceValue.
7100   } else if (info->O->getArch() == Triple::aarch64 &&
7101              *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
7102              ReferencePC - 4 == info->adrp_addr &&
7103              (info->adrp_inst & 0x9f000000) == 0x90000000 &&
7104              (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
7105     uint32_t ldrxui_inst;
7106     uint64_t adrp_imm, ldrxui_imm;
7107 
7108     adrp_imm =
7109         ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
7110     if (info->adrp_inst & 0x0200000)
7111       adrp_imm |= 0xfffffffffc000000LL;
7112 
7113     ldrxui_inst = ReferenceValue;
7114     ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
7115 
7116     ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
7117                      (adrp_imm << 12) + (ldrxui_imm << 3);
7118 
7119     *ReferenceName =
7120         GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7121     if (*ReferenceName == nullptr)
7122       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7123   }
7124   // If this arm64 and is an load register (PC-relative) instruction the
7125   // ReferenceValue is the PC plus the immediate value.
7126   else if (info->O->getArch() == Triple::aarch64 &&
7127            (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
7128             *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
7129     *ReferenceName =
7130         GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7131     if (*ReferenceName == nullptr)
7132       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7133   } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
7134     if (info->demangled_name != nullptr)
7135       free(info->demangled_name);
7136     int status;
7137     info->demangled_name =
7138         itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
7139     if (info->demangled_name != nullptr) {
7140       *ReferenceName = info->demangled_name;
7141       *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
7142     }
7143   }
7144   else {
7145     *ReferenceName = nullptr;
7146     *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7147   }
7148 
7149   return SymbolName;
7150 }
7151 
7152 /// Emits the comments that are stored in the CommentStream.
7153 /// Each comment in the CommentStream must end with a newline.
7154 static void emitComments(raw_svector_ostream &CommentStream,
7155                          SmallString<128> &CommentsToEmit,
7156                          formatted_raw_ostream &FormattedOS,
7157                          const MCAsmInfo &MAI) {
7158   // Flush the stream before taking its content.
7159   StringRef Comments = CommentsToEmit.str();
7160   // Get the default information for printing a comment.
7161   StringRef CommentBegin = MAI.getCommentString();
7162   unsigned CommentColumn = MAI.getCommentColumn();
7163   bool IsFirst = true;
7164   while (!Comments.empty()) {
7165     if (!IsFirst)
7166       FormattedOS << '\n';
7167     // Emit a line of comments.
7168     FormattedOS.PadToColumn(CommentColumn);
7169     size_t Position = Comments.find('\n');
7170     FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
7171     // Move after the newline character.
7172     Comments = Comments.substr(Position + 1);
7173     IsFirst = false;
7174   }
7175   FormattedOS.flush();
7176 
7177   // Tell the comment stream that the vector changed underneath it.
7178   CommentsToEmit.clear();
7179 }
7180 
7181 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
7182                              StringRef DisSegName, StringRef DisSectName) {
7183   const char *McpuDefault = nullptr;
7184   const Target *ThumbTarget = nullptr;
7185   const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
7186   if (!TheTarget) {
7187     // GetTarget prints out stuff.
7188     return;
7189   }
7190   std::string MachOMCPU;
7191   if (MCPU.empty() && McpuDefault)
7192     MachOMCPU = McpuDefault;
7193   else
7194     MachOMCPU = MCPU;
7195 
7196   std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
7197   std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
7198   if (ThumbTarget)
7199     ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
7200 
7201   // Package up features to be passed to target/subtarget
7202   std::string FeaturesStr;
7203   if (!MAttrs.empty()) {
7204     SubtargetFeatures Features;
7205     for (unsigned i = 0; i != MAttrs.size(); ++i)
7206       Features.AddFeature(MAttrs[i]);
7207     FeaturesStr = Features.getString();
7208   }
7209 
7210   MCTargetOptions MCOptions;
7211   // Set up disassembler.
7212   std::unique_ptr<const MCRegisterInfo> MRI(
7213       TheTarget->createMCRegInfo(TripleName));
7214   std::unique_ptr<const MCAsmInfo> AsmInfo(
7215       TheTarget->createMCAsmInfo(*MRI, TripleName, MCOptions));
7216   std::unique_ptr<const MCSubtargetInfo> STI(
7217       TheTarget->createMCSubtargetInfo(TripleName, MachOMCPU, FeaturesStr));
7218   MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
7219   std::unique_ptr<MCDisassembler> DisAsm(
7220       TheTarget->createMCDisassembler(*STI, Ctx));
7221   std::unique_ptr<MCSymbolizer> Symbolizer;
7222   struct DisassembleInfo SymbolizerInfo(nullptr, nullptr, nullptr, false);
7223   std::unique_ptr<MCRelocationInfo> RelInfo(
7224       TheTarget->createMCRelocationInfo(TripleName, Ctx));
7225   if (RelInfo) {
7226     Symbolizer.reset(TheTarget->createMCSymbolizer(
7227         TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
7228         &SymbolizerInfo, &Ctx, std::move(RelInfo)));
7229     DisAsm->setSymbolizer(std::move(Symbolizer));
7230   }
7231   int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
7232   std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
7233       Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
7234   // Set the display preference for hex vs. decimal immediates.
7235   IP->setPrintImmHex(PrintImmHex);
7236   // Comment stream and backing vector.
7237   SmallString<128> CommentsToEmit;
7238   raw_svector_ostream CommentStream(CommentsToEmit);
7239   // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
7240   // if it is done then arm64 comments for string literals don't get printed
7241   // and some constant get printed instead and not setting it causes intel
7242   // (32-bit and 64-bit) comments printed with different spacing before the
7243   // comment causing different diffs with the 'C' disassembler library API.
7244   // IP->setCommentStream(CommentStream);
7245 
7246   if (!AsmInfo || !STI || !DisAsm || !IP) {
7247     WithColor::error(errs(), "llvm-objdump")
7248         << "couldn't initialize disassembler for target " << TripleName << '\n';
7249     return;
7250   }
7251 
7252   // Set up separate thumb disassembler if needed.
7253   std::unique_ptr<const MCRegisterInfo> ThumbMRI;
7254   std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
7255   std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
7256   std::unique_ptr<MCDisassembler> ThumbDisAsm;
7257   std::unique_ptr<MCInstPrinter> ThumbIP;
7258   std::unique_ptr<MCContext> ThumbCtx;
7259   std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
7260   struct DisassembleInfo ThumbSymbolizerInfo(nullptr, nullptr, nullptr, false);
7261   std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
7262   if (ThumbTarget) {
7263     ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
7264     ThumbAsmInfo.reset(
7265         ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName, MCOptions));
7266     ThumbSTI.reset(
7267         ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MachOMCPU,
7268                                            FeaturesStr));
7269     ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
7270     ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
7271     MCContext *PtrThumbCtx = ThumbCtx.get();
7272     ThumbRelInfo.reset(
7273         ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
7274     if (ThumbRelInfo) {
7275       ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
7276           ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
7277           &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
7278       ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
7279     }
7280     int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
7281     ThumbIP.reset(ThumbTarget->createMCInstPrinter(
7282         Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
7283         *ThumbInstrInfo, *ThumbMRI));
7284     // Set the display preference for hex vs. decimal immediates.
7285     ThumbIP->setPrintImmHex(PrintImmHex);
7286   }
7287 
7288   if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
7289     WithColor::error(errs(), "llvm-objdump")
7290         << "couldn't initialize disassembler for target " << ThumbTripleName
7291         << '\n';
7292     return;
7293   }
7294 
7295   MachO::mach_header Header = MachOOF->getHeader();
7296 
7297   // FIXME: Using the -cfg command line option, this code used to be able to
7298   // annotate relocations with the referenced symbol's name, and if this was
7299   // inside a __[cf]string section, the data it points to. This is now replaced
7300   // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
7301   std::vector<SectionRef> Sections;
7302   std::vector<SymbolRef> Symbols;
7303   SmallVector<uint64_t, 8> FoundFns;
7304   uint64_t BaseSegmentAddress = 0;
7305 
7306   getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
7307                         BaseSegmentAddress);
7308 
7309   // Sort the symbols by address, just in case they didn't come in that way.
7310   llvm::sort(Symbols, SymbolSorter());
7311 
7312   // Build a data in code table that is sorted on by the address of each entry.
7313   uint64_t BaseAddress = 0;
7314   if (Header.filetype == MachO::MH_OBJECT)
7315     BaseAddress = Sections[0].getAddress();
7316   else
7317     BaseAddress = BaseSegmentAddress;
7318   DiceTable Dices;
7319   for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
7320        DI != DE; ++DI) {
7321     uint32_t Offset;
7322     DI->getOffset(Offset);
7323     Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
7324   }
7325   array_pod_sort(Dices.begin(), Dices.end());
7326 
7327   // Try to find debug info and set up the DIContext for it.
7328   std::unique_ptr<DIContext> diContext;
7329   std::unique_ptr<Binary> DSYMBinary;
7330   std::unique_ptr<MemoryBuffer> DSYMBuf;
7331   if (UseDbg) {
7332     ObjectFile *DbgObj = MachOOF;
7333 
7334     // A separate DSym file path was specified, parse it as a macho file,
7335     // get the sections and supply it to the section name parsing machinery.
7336     if (!DSYMFile.empty()) {
7337       std::string DSYMPath(DSYMFile);
7338 
7339       // If DSYMPath is a .dSYM directory, append the Mach-O file.
7340       if (llvm::sys::fs::is_directory(DSYMPath) &&
7341           llvm::sys::path::extension(DSYMPath) == ".dSYM") {
7342         SmallString<128> ShortName(llvm::sys::path::filename(DSYMPath));
7343         llvm::sys::path::replace_extension(ShortName, "");
7344         SmallString<1024> FullPath(DSYMPath);
7345         llvm::sys::path::append(FullPath, "Contents", "Resources", "DWARF",
7346                                 ShortName);
7347         DSYMPath = std::string(FullPath.str());
7348       }
7349 
7350       // Load the file.
7351       ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
7352           MemoryBuffer::getFileOrSTDIN(DSYMPath);
7353       if (std::error_code EC = BufOrErr.getError()) {
7354         reportError(errorCodeToError(EC), DSYMPath);
7355         return;
7356       }
7357 
7358       // We need to keep the file alive, because we're replacing DbgObj with it.
7359       DSYMBuf = std::move(BufOrErr.get());
7360 
7361       Expected<std::unique_ptr<Binary>> BinaryOrErr =
7362       createBinary(DSYMBuf.get()->getMemBufferRef());
7363       if (!BinaryOrErr) {
7364         reportError(BinaryOrErr.takeError(), DSYMPath);
7365         return;
7366       }
7367 
7368       // We need to keep the Binary alive with the buffer
7369       DSYMBinary = std::move(BinaryOrErr.get());
7370       if (ObjectFile *O = dyn_cast<ObjectFile>(DSYMBinary.get())) {
7371         // this is a Mach-O object file, use it
7372         if (MachOObjectFile *MachDSYM = dyn_cast<MachOObjectFile>(&*O)) {
7373           DbgObj = MachDSYM;
7374         }
7375         else {
7376           WithColor::error(errs(), "llvm-objdump")
7377             << DSYMPath << " is not a Mach-O file type.\n";
7378           return;
7379         }
7380       }
7381       else if (auto UB = dyn_cast<MachOUniversalBinary>(DSYMBinary.get())){
7382         // this is a Universal Binary, find a Mach-O for this architecture
7383         uint32_t CPUType, CPUSubType;
7384         const char *ArchFlag;
7385         if (MachOOF->is64Bit()) {
7386           const MachO::mach_header_64 H_64 = MachOOF->getHeader64();
7387           CPUType = H_64.cputype;
7388           CPUSubType = H_64.cpusubtype;
7389         } else {
7390           const MachO::mach_header H = MachOOF->getHeader();
7391           CPUType = H.cputype;
7392           CPUSubType = H.cpusubtype;
7393         }
7394         Triple T = MachOObjectFile::getArchTriple(CPUType, CPUSubType, nullptr,
7395                                                   &ArchFlag);
7396         Expected<std::unique_ptr<MachOObjectFile>> MachDSYM =
7397             UB->getMachOObjectForArch(ArchFlag);
7398         if (!MachDSYM) {
7399           reportError(MachDSYM.takeError(), DSYMPath);
7400           return;
7401         }
7402 
7403         // We need to keep the Binary alive with the buffer
7404         DbgObj = &*MachDSYM.get();
7405         DSYMBinary = std::move(*MachDSYM);
7406       }
7407       else {
7408         WithColor::error(errs(), "llvm-objdump")
7409           << DSYMPath << " is not a Mach-O or Universal file type.\n";
7410         return;
7411       }
7412     }
7413 
7414     // Setup the DIContext
7415     diContext = DWARFContext::create(*DbgObj);
7416   }
7417 
7418   if (FilterSections.empty())
7419     outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
7420 
7421   for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
7422     Expected<StringRef> SecNameOrErr = Sections[SectIdx].getName();
7423     if (!SecNameOrErr) {
7424       consumeError(SecNameOrErr.takeError());
7425       continue;
7426     }
7427     if (*SecNameOrErr != DisSectName)
7428       continue;
7429 
7430     DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
7431 
7432     StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
7433     if (SegmentName != DisSegName)
7434       continue;
7435 
7436     StringRef BytesStr =
7437         unwrapOrError(Sections[SectIdx].getContents(), Filename);
7438     ArrayRef<uint8_t> Bytes = arrayRefFromStringRef(BytesStr);
7439     uint64_t SectAddress = Sections[SectIdx].getAddress();
7440 
7441     bool symbolTableWorked = false;
7442 
7443     // Create a map of symbol addresses to symbol names for use by
7444     // the SymbolizerSymbolLookUp() routine.
7445     SymbolAddressMap AddrMap;
7446     bool DisSymNameFound = false;
7447     for (const SymbolRef &Symbol : MachOOF->symbols()) {
7448       SymbolRef::Type ST =
7449           unwrapOrError(Symbol.getType(), MachOOF->getFileName());
7450       if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
7451           ST == SymbolRef::ST_Other) {
7452         uint64_t Address = Symbol.getValue();
7453         StringRef SymName =
7454             unwrapOrError(Symbol.getName(), MachOOF->getFileName());
7455         AddrMap[Address] = SymName;
7456         if (!DisSymName.empty() && DisSymName == SymName)
7457           DisSymNameFound = true;
7458       }
7459     }
7460     if (!DisSymName.empty() && !DisSymNameFound) {
7461       outs() << "Can't find -dis-symname: " << DisSymName << "\n";
7462       return;
7463     }
7464     // Set up the block of info used by the Symbolizer call backs.
7465     SymbolizerInfo.verbose = !NoSymbolicOperands;
7466     SymbolizerInfo.O = MachOOF;
7467     SymbolizerInfo.S = Sections[SectIdx];
7468     SymbolizerInfo.AddrMap = &AddrMap;
7469     SymbolizerInfo.Sections = &Sections;
7470     // Same for the ThumbSymbolizer
7471     ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
7472     ThumbSymbolizerInfo.O = MachOOF;
7473     ThumbSymbolizerInfo.S = Sections[SectIdx];
7474     ThumbSymbolizerInfo.AddrMap = &AddrMap;
7475     ThumbSymbolizerInfo.Sections = &Sections;
7476 
7477     unsigned int Arch = MachOOF->getArch();
7478 
7479     // Skip all symbols if this is a stubs file.
7480     if (Bytes.empty())
7481       return;
7482 
7483     // If the section has symbols but no symbol at the start of the section
7484     // these are used to make sure the bytes before the first symbol are
7485     // disassembled.
7486     bool FirstSymbol = true;
7487     bool FirstSymbolAtSectionStart = true;
7488 
7489     // Disassemble symbol by symbol.
7490     for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
7491       StringRef SymName =
7492           unwrapOrError(Symbols[SymIdx].getName(), MachOOF->getFileName());
7493       SymbolRef::Type ST =
7494           unwrapOrError(Symbols[SymIdx].getType(), MachOOF->getFileName());
7495       if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
7496         continue;
7497 
7498       // Make sure the symbol is defined in this section.
7499       bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
7500       if (!containsSym) {
7501         if (!DisSymName.empty() && DisSymName == SymName) {
7502           outs() << "-dis-symname: " << DisSymName << " not in the section\n";
7503           return;
7504         }
7505         continue;
7506       }
7507       // The __mh_execute_header is special and we need to deal with that fact
7508       // this symbol is before the start of the (__TEXT,__text) section and at the
7509       // address of the start of the __TEXT segment.  This is because this symbol
7510       // is an N_SECT symbol in the (__TEXT,__text) but its address is before the
7511       // start of the section in a standard MH_EXECUTE filetype.
7512       if (!DisSymName.empty() && DisSymName == "__mh_execute_header") {
7513         outs() << "-dis-symname: __mh_execute_header not in any section\n";
7514         return;
7515       }
7516       // When this code is trying to disassemble a symbol at a time and in the
7517       // case there is only the __mh_execute_header symbol left as in a stripped
7518       // executable, we need to deal with this by ignoring this symbol so the
7519       // whole section is disassembled and this symbol is then not displayed.
7520       if (SymName == "__mh_execute_header" || SymName == "__mh_dylib_header" ||
7521           SymName == "__mh_bundle_header" || SymName == "__mh_object_header" ||
7522           SymName == "__mh_preload_header" || SymName == "__mh_dylinker_header")
7523         continue;
7524 
7525       // If we are only disassembling one symbol see if this is that symbol.
7526       if (!DisSymName.empty() && DisSymName != SymName)
7527         continue;
7528 
7529       // Start at the address of the symbol relative to the section's address.
7530       uint64_t SectSize = Sections[SectIdx].getSize();
7531       uint64_t Start = Symbols[SymIdx].getValue();
7532       uint64_t SectionAddress = Sections[SectIdx].getAddress();
7533       Start -= SectionAddress;
7534 
7535       if (Start > SectSize) {
7536         outs() << "section data ends, " << SymName
7537                << " lies outside valid range\n";
7538         return;
7539       }
7540 
7541       // Stop disassembling either at the beginning of the next symbol or at
7542       // the end of the section.
7543       bool containsNextSym = false;
7544       uint64_t NextSym = 0;
7545       uint64_t NextSymIdx = SymIdx + 1;
7546       while (Symbols.size() > NextSymIdx) {
7547         SymbolRef::Type NextSymType = unwrapOrError(
7548             Symbols[NextSymIdx].getType(), MachOOF->getFileName());
7549         if (NextSymType == SymbolRef::ST_Function) {
7550           containsNextSym =
7551               Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
7552           NextSym = Symbols[NextSymIdx].getValue();
7553           NextSym -= SectionAddress;
7554           break;
7555         }
7556         ++NextSymIdx;
7557       }
7558 
7559       uint64_t End = containsNextSym ? std::min(NextSym, SectSize) : SectSize;
7560       uint64_t Size;
7561 
7562       symbolTableWorked = true;
7563 
7564       DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
7565       uint32_t SymbolFlags = cantFail(MachOOF->getSymbolFlags(Symb));
7566       bool IsThumb = SymbolFlags & SymbolRef::SF_Thumb;
7567 
7568       // We only need the dedicated Thumb target if there's a real choice
7569       // (i.e. we're not targeting M-class) and the function is Thumb.
7570       bool UseThumbTarget = IsThumb && ThumbTarget;
7571 
7572       // If we are not specifying a symbol to start disassembly with and this
7573       // is the first symbol in the section but not at the start of the section
7574       // then move the disassembly index to the start of the section and
7575       // don't print the symbol name just yet.  This is so the bytes before the
7576       // first symbol are disassembled.
7577       uint64_t SymbolStart = Start;
7578       if (DisSymName.empty() && FirstSymbol && Start != 0) {
7579         FirstSymbolAtSectionStart = false;
7580         Start = 0;
7581       }
7582       else
7583         outs() << SymName << ":\n";
7584 
7585       DILineInfo lastLine;
7586       for (uint64_t Index = Start; Index < End; Index += Size) {
7587         MCInst Inst;
7588 
7589         // If this is the first symbol in the section and it was not at the
7590         // start of the section, see if we are at its Index now and if so print
7591         // the symbol name.
7592         if (FirstSymbol && !FirstSymbolAtSectionStart && Index == SymbolStart)
7593           outs() << SymName << ":\n";
7594 
7595         uint64_t PC = SectAddress + Index;
7596         if (!NoLeadingAddr) {
7597           if (FullLeadingAddr) {
7598             if (MachOOF->is64Bit())
7599               outs() << format("%016" PRIx64, PC);
7600             else
7601               outs() << format("%08" PRIx64, PC);
7602           } else {
7603             outs() << format("%8" PRIx64 ":", PC);
7604           }
7605         }
7606         if (!NoShowRawInsn || Arch == Triple::arm)
7607           outs() << "\t";
7608 
7609         if (DumpAndSkipDataInCode(PC, Bytes.data() + Index, Dices, Size))
7610           continue;
7611 
7612         SmallVector<char, 64> AnnotationsBytes;
7613         raw_svector_ostream Annotations(AnnotationsBytes);
7614 
7615         bool gotInst;
7616         if (UseThumbTarget)
7617           gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
7618                                                 PC, Annotations);
7619         else
7620           gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
7621                                            Annotations);
7622         if (gotInst) {
7623           if (!NoShowRawInsn || Arch == Triple::arm) {
7624             dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
7625           }
7626           formatted_raw_ostream FormattedOS(outs());
7627           StringRef AnnotationsStr = Annotations.str();
7628           if (UseThumbTarget)
7629             ThumbIP->printInst(&Inst, PC, AnnotationsStr, *ThumbSTI,
7630                                FormattedOS);
7631           else
7632             IP->printInst(&Inst, PC, AnnotationsStr, *STI, FormattedOS);
7633           emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
7634 
7635           // Print debug info.
7636           if (diContext) {
7637             DILineInfo dli = diContext->getLineInfoForAddress({PC, SectIdx});
7638             // Print valid line info if it changed.
7639             if (dli != lastLine && dli.Line != 0)
7640               outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
7641                      << dli.Column;
7642             lastLine = dli;
7643           }
7644           outs() << "\n";
7645         } else {
7646           if (MachOOF->getArchTriple().isX86()) {
7647             outs() << format("\t.byte 0x%02x #bad opcode\n",
7648                              *(Bytes.data() + Index) & 0xff);
7649             Size = 1; // skip exactly one illegible byte and move on.
7650           } else if (Arch == Triple::aarch64 ||
7651                      (Arch == Triple::arm && !IsThumb)) {
7652             uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7653                               (*(Bytes.data() + Index + 1) & 0xff) << 8 |
7654                               (*(Bytes.data() + Index + 2) & 0xff) << 16 |
7655                               (*(Bytes.data() + Index + 3) & 0xff) << 24;
7656             outs() << format("\t.long\t0x%08x\n", opcode);
7657             Size = 4;
7658           } else if (Arch == Triple::arm) {
7659             assert(IsThumb && "ARM mode should have been dealt with above");
7660             uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7661                               (*(Bytes.data() + Index + 1) & 0xff) << 8;
7662             outs() << format("\t.short\t0x%04x\n", opcode);
7663             Size = 2;
7664           } else{
7665             WithColor::warning(errs(), "llvm-objdump")
7666                 << "invalid instruction encoding\n";
7667             if (Size == 0)
7668               Size = 1; // skip illegible bytes
7669           }
7670         }
7671       }
7672       // Now that we are done disassembled the first symbol set the bool that
7673       // were doing this to false.
7674       FirstSymbol = false;
7675     }
7676     if (!symbolTableWorked) {
7677       // Reading the symbol table didn't work, disassemble the whole section.
7678       uint64_t SectAddress = Sections[SectIdx].getAddress();
7679       uint64_t SectSize = Sections[SectIdx].getSize();
7680       uint64_t InstSize;
7681       for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
7682         MCInst Inst;
7683 
7684         uint64_t PC = SectAddress + Index;
7685 
7686         if (DumpAndSkipDataInCode(PC, Bytes.data() + Index, Dices, InstSize))
7687           continue;
7688 
7689         SmallVector<char, 64> AnnotationsBytes;
7690         raw_svector_ostream Annotations(AnnotationsBytes);
7691         if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
7692                                    Annotations)) {
7693           if (!NoLeadingAddr) {
7694             if (FullLeadingAddr) {
7695               if (MachOOF->is64Bit())
7696                 outs() << format("%016" PRIx64, PC);
7697               else
7698                 outs() << format("%08" PRIx64, PC);
7699             } else {
7700               outs() << format("%8" PRIx64 ":", PC);
7701             }
7702           }
7703           if (!NoShowRawInsn || Arch == Triple::arm) {
7704             outs() << "\t";
7705             dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
7706           }
7707           StringRef AnnotationsStr = Annotations.str();
7708           IP->printInst(&Inst, PC, AnnotationsStr, *STI, outs());
7709           outs() << "\n";
7710         } else {
7711           if (MachOOF->getArchTriple().isX86()) {
7712             outs() << format("\t.byte 0x%02x #bad opcode\n",
7713                              *(Bytes.data() + Index) & 0xff);
7714             InstSize = 1; // skip exactly one illegible byte and move on.
7715           } else {
7716             WithColor::warning(errs(), "llvm-objdump")
7717                 << "invalid instruction encoding\n";
7718             if (InstSize == 0)
7719               InstSize = 1; // skip illegible bytes
7720           }
7721         }
7722       }
7723     }
7724     // The TripleName's need to be reset if we are called again for a different
7725     // architecture.
7726     TripleName = "";
7727     ThumbTripleName = "";
7728 
7729     if (SymbolizerInfo.demangled_name != nullptr)
7730       free(SymbolizerInfo.demangled_name);
7731     if (ThumbSymbolizerInfo.demangled_name != nullptr)
7732       free(ThumbSymbolizerInfo.demangled_name);
7733   }
7734 }
7735 
7736 //===----------------------------------------------------------------------===//
7737 // __compact_unwind section dumping
7738 //===----------------------------------------------------------------------===//
7739 
7740 namespace {
7741 
7742 template <typename T>
7743 static uint64_t read(StringRef Contents, ptrdiff_t Offset) {
7744   using llvm::support::little;
7745   using llvm::support::unaligned;
7746 
7747   if (Offset + sizeof(T) > Contents.size()) {
7748     outs() << "warning: attempt to read past end of buffer\n";
7749     return T();
7750   }
7751 
7752   uint64_t Val =
7753       support::endian::read<T, little, unaligned>(Contents.data() + Offset);
7754   return Val;
7755 }
7756 
7757 template <typename T>
7758 static uint64_t readNext(StringRef Contents, ptrdiff_t &Offset) {
7759   T Val = read<T>(Contents, Offset);
7760   Offset += sizeof(T);
7761   return Val;
7762 }
7763 
7764 struct CompactUnwindEntry {
7765   uint32_t OffsetInSection;
7766 
7767   uint64_t FunctionAddr;
7768   uint32_t Length;
7769   uint32_t CompactEncoding;
7770   uint64_t PersonalityAddr;
7771   uint64_t LSDAAddr;
7772 
7773   RelocationRef FunctionReloc;
7774   RelocationRef PersonalityReloc;
7775   RelocationRef LSDAReloc;
7776 
7777   CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
7778       : OffsetInSection(Offset) {
7779     if (Is64)
7780       read<uint64_t>(Contents, Offset);
7781     else
7782       read<uint32_t>(Contents, Offset);
7783   }
7784 
7785 private:
7786   template <typename UIntPtr> void read(StringRef Contents, ptrdiff_t Offset) {
7787     FunctionAddr = readNext<UIntPtr>(Contents, Offset);
7788     Length = readNext<uint32_t>(Contents, Offset);
7789     CompactEncoding = readNext<uint32_t>(Contents, Offset);
7790     PersonalityAddr = readNext<UIntPtr>(Contents, Offset);
7791     LSDAAddr = readNext<UIntPtr>(Contents, Offset);
7792   }
7793 };
7794 }
7795 
7796 /// Given a relocation from __compact_unwind, consisting of the RelocationRef
7797 /// and data being relocated, determine the best base Name and Addend to use for
7798 /// display purposes.
7799 ///
7800 /// 1. An Extern relocation will directly reference a symbol (and the data is
7801 ///    then already an addend), so use that.
7802 /// 2. Otherwise the data is an offset in the object file's layout; try to find
7803 //     a symbol before it in the same section, and use the offset from there.
7804 /// 3. Finally, if all that fails, fall back to an offset from the start of the
7805 ///    referenced section.
7806 static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
7807                                       std::map<uint64_t, SymbolRef> &Symbols,
7808                                       const RelocationRef &Reloc, uint64_t Addr,
7809                                       StringRef &Name, uint64_t &Addend) {
7810   if (Reloc.getSymbol() != Obj->symbol_end()) {
7811     Name = unwrapOrError(Reloc.getSymbol()->getName(), Obj->getFileName());
7812     Addend = Addr;
7813     return;
7814   }
7815 
7816   auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
7817   SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
7818 
7819   uint64_t SectionAddr = RelocSection.getAddress();
7820 
7821   auto Sym = Symbols.upper_bound(Addr);
7822   if (Sym == Symbols.begin()) {
7823     // The first symbol in the object is after this reference, the best we can
7824     // do is section-relative notation.
7825     if (Expected<StringRef> NameOrErr = RelocSection.getName())
7826       Name = *NameOrErr;
7827     else
7828       consumeError(NameOrErr.takeError());
7829 
7830     Addend = Addr - SectionAddr;
7831     return;
7832   }
7833 
7834   // Go back one so that SymbolAddress <= Addr.
7835   --Sym;
7836 
7837   section_iterator SymSection =
7838       unwrapOrError(Sym->second.getSection(), Obj->getFileName());
7839   if (RelocSection == *SymSection) {
7840     // There's a valid symbol in the same section before this reference.
7841     Name = unwrapOrError(Sym->second.getName(), Obj->getFileName());
7842     Addend = Addr - Sym->first;
7843     return;
7844   }
7845 
7846   // There is a symbol before this reference, but it's in a different
7847   // section. Probably not helpful to mention it, so use the section name.
7848   if (Expected<StringRef> NameOrErr = RelocSection.getName())
7849     Name = *NameOrErr;
7850   else
7851     consumeError(NameOrErr.takeError());
7852 
7853   Addend = Addr - SectionAddr;
7854 }
7855 
7856 static void printUnwindRelocDest(const MachOObjectFile *Obj,
7857                                  std::map<uint64_t, SymbolRef> &Symbols,
7858                                  const RelocationRef &Reloc, uint64_t Addr) {
7859   StringRef Name;
7860   uint64_t Addend;
7861 
7862   if (!Reloc.getObject())
7863     return;
7864 
7865   findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
7866 
7867   outs() << Name;
7868   if (Addend)
7869     outs() << " + " << format("0x%" PRIx64, Addend);
7870 }
7871 
7872 static void
7873 printMachOCompactUnwindSection(const MachOObjectFile *Obj,
7874                                std::map<uint64_t, SymbolRef> &Symbols,
7875                                const SectionRef &CompactUnwind) {
7876 
7877   if (!Obj->isLittleEndian()) {
7878     outs() << "Skipping big-endian __compact_unwind section\n";
7879     return;
7880   }
7881 
7882   bool Is64 = Obj->is64Bit();
7883   uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
7884   uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
7885 
7886   StringRef Contents =
7887       unwrapOrError(CompactUnwind.getContents(), Obj->getFileName());
7888   SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
7889 
7890   // First populate the initial raw offsets, encodings and so on from the entry.
7891   for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
7892     CompactUnwindEntry Entry(Contents, Offset, Is64);
7893     CompactUnwinds.push_back(Entry);
7894   }
7895 
7896   // Next we need to look at the relocations to find out what objects are
7897   // actually being referred to.
7898   for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
7899     uint64_t RelocAddress = Reloc.getOffset();
7900 
7901     uint32_t EntryIdx = RelocAddress / EntrySize;
7902     uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
7903     CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
7904 
7905     if (OffsetInEntry == 0)
7906       Entry.FunctionReloc = Reloc;
7907     else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
7908       Entry.PersonalityReloc = Reloc;
7909     else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
7910       Entry.LSDAReloc = Reloc;
7911     else {
7912       outs() << "Invalid relocation in __compact_unwind section\n";
7913       return;
7914     }
7915   }
7916 
7917   // Finally, we're ready to print the data we've gathered.
7918   outs() << "Contents of __compact_unwind section:\n";
7919   for (auto &Entry : CompactUnwinds) {
7920     outs() << "  Entry at offset "
7921            << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
7922 
7923     // 1. Start of the region this entry applies to.
7924     outs() << "    start:                " << format("0x%" PRIx64,
7925                                                      Entry.FunctionAddr) << ' ';
7926     printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
7927     outs() << '\n';
7928 
7929     // 2. Length of the region this entry applies to.
7930     outs() << "    length:               " << format("0x%" PRIx32, Entry.Length)
7931            << '\n';
7932     // 3. The 32-bit compact encoding.
7933     outs() << "    compact encoding:     "
7934            << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
7935 
7936     // 4. The personality function, if present.
7937     if (Entry.PersonalityReloc.getObject()) {
7938       outs() << "    personality function: "
7939              << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
7940       printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
7941                            Entry.PersonalityAddr);
7942       outs() << '\n';
7943     }
7944 
7945     // 5. This entry's language-specific data area.
7946     if (Entry.LSDAReloc.getObject()) {
7947       outs() << "    LSDA:                 " << format("0x%" PRIx64,
7948                                                        Entry.LSDAAddr) << ' ';
7949       printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
7950       outs() << '\n';
7951     }
7952   }
7953 }
7954 
7955 //===----------------------------------------------------------------------===//
7956 // __unwind_info section dumping
7957 //===----------------------------------------------------------------------===//
7958 
7959 static void printRegularSecondLevelUnwindPage(StringRef PageData) {
7960   ptrdiff_t Pos = 0;
7961   uint32_t Kind = readNext<uint32_t>(PageData, Pos);
7962   (void)Kind;
7963   assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
7964 
7965   uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
7966   uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
7967 
7968   Pos = EntriesStart;
7969   for (unsigned i = 0; i < NumEntries; ++i) {
7970     uint32_t FunctionOffset = readNext<uint32_t>(PageData, Pos);
7971     uint32_t Encoding = readNext<uint32_t>(PageData, Pos);
7972 
7973     outs() << "      [" << i << "]: "
7974            << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7975            << ", "
7976            << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
7977   }
7978 }
7979 
7980 static void printCompressedSecondLevelUnwindPage(
7981     StringRef PageData, uint32_t FunctionBase,
7982     const SmallVectorImpl<uint32_t> &CommonEncodings) {
7983   ptrdiff_t Pos = 0;
7984   uint32_t Kind = readNext<uint32_t>(PageData, Pos);
7985   (void)Kind;
7986   assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
7987 
7988   uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
7989   uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
7990 
7991   uint16_t EncodingsStart = readNext<uint16_t>(PageData, Pos);
7992   readNext<uint16_t>(PageData, Pos);
7993   StringRef PageEncodings = PageData.substr(EncodingsStart, StringRef::npos);
7994 
7995   Pos = EntriesStart;
7996   for (unsigned i = 0; i < NumEntries; ++i) {
7997     uint32_t Entry = readNext<uint32_t>(PageData, Pos);
7998     uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
7999     uint32_t EncodingIdx = Entry >> 24;
8000 
8001     uint32_t Encoding;
8002     if (EncodingIdx < CommonEncodings.size())
8003       Encoding = CommonEncodings[EncodingIdx];
8004     else
8005       Encoding = read<uint32_t>(PageEncodings,
8006                                 sizeof(uint32_t) *
8007                                     (EncodingIdx - CommonEncodings.size()));
8008 
8009     outs() << "      [" << i << "]: "
8010            << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
8011            << ", "
8012            << "encoding[" << EncodingIdx
8013            << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
8014   }
8015 }
8016 
8017 static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
8018                                         std::map<uint64_t, SymbolRef> &Symbols,
8019                                         const SectionRef &UnwindInfo) {
8020 
8021   if (!Obj->isLittleEndian()) {
8022     outs() << "Skipping big-endian __unwind_info section\n";
8023     return;
8024   }
8025 
8026   outs() << "Contents of __unwind_info section:\n";
8027 
8028   StringRef Contents =
8029       unwrapOrError(UnwindInfo.getContents(), Obj->getFileName());
8030   ptrdiff_t Pos = 0;
8031 
8032   //===----------------------------------
8033   // Section header
8034   //===----------------------------------
8035 
8036   uint32_t Version = readNext<uint32_t>(Contents, Pos);
8037   outs() << "  Version:                                   "
8038          << format("0x%" PRIx32, Version) << '\n';
8039   if (Version != 1) {
8040     outs() << "    Skipping section with unknown version\n";
8041     return;
8042   }
8043 
8044   uint32_t CommonEncodingsStart = readNext<uint32_t>(Contents, Pos);
8045   outs() << "  Common encodings array section offset:     "
8046          << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
8047   uint32_t NumCommonEncodings = readNext<uint32_t>(Contents, Pos);
8048   outs() << "  Number of common encodings in array:       "
8049          << format("0x%" PRIx32, NumCommonEncodings) << '\n';
8050 
8051   uint32_t PersonalitiesStart = readNext<uint32_t>(Contents, Pos);
8052   outs() << "  Personality function array section offset: "
8053          << format("0x%" PRIx32, PersonalitiesStart) << '\n';
8054   uint32_t NumPersonalities = readNext<uint32_t>(Contents, Pos);
8055   outs() << "  Number of personality functions in array:  "
8056          << format("0x%" PRIx32, NumPersonalities) << '\n';
8057 
8058   uint32_t IndicesStart = readNext<uint32_t>(Contents, Pos);
8059   outs() << "  Index array section offset:                "
8060          << format("0x%" PRIx32, IndicesStart) << '\n';
8061   uint32_t NumIndices = readNext<uint32_t>(Contents, Pos);
8062   outs() << "  Number of indices in array:                "
8063          << format("0x%" PRIx32, NumIndices) << '\n';
8064 
8065   //===----------------------------------
8066   // A shared list of common encodings
8067   //===----------------------------------
8068 
8069   // These occupy indices in the range [0, N] whenever an encoding is referenced
8070   // from a compressed 2nd level index table. In practice the linker only
8071   // creates ~128 of these, so that indices are available to embed encodings in
8072   // the 2nd level index.
8073 
8074   SmallVector<uint32_t, 64> CommonEncodings;
8075   outs() << "  Common encodings: (count = " << NumCommonEncodings << ")\n";
8076   Pos = CommonEncodingsStart;
8077   for (unsigned i = 0; i < NumCommonEncodings; ++i) {
8078     uint32_t Encoding = readNext<uint32_t>(Contents, Pos);
8079     CommonEncodings.push_back(Encoding);
8080 
8081     outs() << "    encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
8082            << '\n';
8083   }
8084 
8085   //===----------------------------------
8086   // Personality functions used in this executable
8087   //===----------------------------------
8088 
8089   // There should be only a handful of these (one per source language,
8090   // roughly). Particularly since they only get 2 bits in the compact encoding.
8091 
8092   outs() << "  Personality functions: (count = " << NumPersonalities << ")\n";
8093   Pos = PersonalitiesStart;
8094   for (unsigned i = 0; i < NumPersonalities; ++i) {
8095     uint32_t PersonalityFn = readNext<uint32_t>(Contents, Pos);
8096     outs() << "    personality[" << i + 1
8097            << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
8098   }
8099 
8100   //===----------------------------------
8101   // The level 1 index entries
8102   //===----------------------------------
8103 
8104   // These specify an approximate place to start searching for the more detailed
8105   // information, sorted by PC.
8106 
8107   struct IndexEntry {
8108     uint32_t FunctionOffset;
8109     uint32_t SecondLevelPageStart;
8110     uint32_t LSDAStart;
8111   };
8112 
8113   SmallVector<IndexEntry, 4> IndexEntries;
8114 
8115   outs() << "  Top level indices: (count = " << NumIndices << ")\n";
8116   Pos = IndicesStart;
8117   for (unsigned i = 0; i < NumIndices; ++i) {
8118     IndexEntry Entry;
8119 
8120     Entry.FunctionOffset = readNext<uint32_t>(Contents, Pos);
8121     Entry.SecondLevelPageStart = readNext<uint32_t>(Contents, Pos);
8122     Entry.LSDAStart = readNext<uint32_t>(Contents, Pos);
8123     IndexEntries.push_back(Entry);
8124 
8125     outs() << "    [" << i << "]: "
8126            << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
8127            << ", "
8128            << "2nd level page offset="
8129            << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
8130            << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
8131   }
8132 
8133   //===----------------------------------
8134   // Next come the LSDA tables
8135   //===----------------------------------
8136 
8137   // The LSDA layout is rather implicit: it's a contiguous array of entries from
8138   // the first top-level index's LSDAOffset to the last (sentinel).
8139 
8140   outs() << "  LSDA descriptors:\n";
8141   Pos = IndexEntries[0].LSDAStart;
8142   const uint32_t LSDASize = 2 * sizeof(uint32_t);
8143   int NumLSDAs =
8144       (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) / LSDASize;
8145 
8146   for (int i = 0; i < NumLSDAs; ++i) {
8147     uint32_t FunctionOffset = readNext<uint32_t>(Contents, Pos);
8148     uint32_t LSDAOffset = readNext<uint32_t>(Contents, Pos);
8149     outs() << "    [" << i << "]: "
8150            << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
8151            << ", "
8152            << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
8153   }
8154 
8155   //===----------------------------------
8156   // Finally, the 2nd level indices
8157   //===----------------------------------
8158 
8159   // Generally these are 4K in size, and have 2 possible forms:
8160   //   + Regular stores up to 511 entries with disparate encodings
8161   //   + Compressed stores up to 1021 entries if few enough compact encoding
8162   //     values are used.
8163   outs() << "  Second level indices:\n";
8164   for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
8165     // The final sentinel top-level index has no associated 2nd level page
8166     if (IndexEntries[i].SecondLevelPageStart == 0)
8167       break;
8168 
8169     outs() << "    Second level index[" << i << "]: "
8170            << "offset in section="
8171            << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
8172            << ", "
8173            << "base function offset="
8174            << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
8175 
8176     Pos = IndexEntries[i].SecondLevelPageStart;
8177     if (Pos + sizeof(uint32_t) > Contents.size()) {
8178       outs() << "warning: invalid offset for second level page: " << Pos << '\n';
8179       continue;
8180     }
8181 
8182     uint32_t Kind =
8183         *reinterpret_cast<const support::ulittle32_t *>(Contents.data() + Pos);
8184     if (Kind == 2)
8185       printRegularSecondLevelUnwindPage(Contents.substr(Pos, 4096));
8186     else if (Kind == 3)
8187       printCompressedSecondLevelUnwindPage(Contents.substr(Pos, 4096),
8188                                            IndexEntries[i].FunctionOffset,
8189                                            CommonEncodings);
8190     else
8191       outs() << "    Skipping 2nd level page with unknown kind " << Kind
8192              << '\n';
8193   }
8194 }
8195 
8196 void objdump::printMachOUnwindInfo(const MachOObjectFile *Obj) {
8197   std::map<uint64_t, SymbolRef> Symbols;
8198   for (const SymbolRef &SymRef : Obj->symbols()) {
8199     // Discard any undefined or absolute symbols. They're not going to take part
8200     // in the convenience lookup for unwind info and just take up resources.
8201     auto SectOrErr = SymRef.getSection();
8202     if (!SectOrErr) {
8203       // TODO: Actually report errors helpfully.
8204       consumeError(SectOrErr.takeError());
8205       continue;
8206     }
8207     section_iterator Section = *SectOrErr;
8208     if (Section == Obj->section_end())
8209       continue;
8210 
8211     uint64_t Addr = SymRef.getValue();
8212     Symbols.insert(std::make_pair(Addr, SymRef));
8213   }
8214 
8215   for (const SectionRef &Section : Obj->sections()) {
8216     StringRef SectName;
8217     if (Expected<StringRef> NameOrErr = Section.getName())
8218       SectName = *NameOrErr;
8219     else
8220       consumeError(NameOrErr.takeError());
8221 
8222     if (SectName == "__compact_unwind")
8223       printMachOCompactUnwindSection(Obj, Symbols, Section);
8224     else if (SectName == "__unwind_info")
8225       printMachOUnwindInfoSection(Obj, Symbols, Section);
8226   }
8227 }
8228 
8229 static void PrintMachHeader(uint32_t magic, uint32_t cputype,
8230                             uint32_t cpusubtype, uint32_t filetype,
8231                             uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
8232                             bool verbose) {
8233   outs() << "Mach header\n";
8234   outs() << "      magic cputype cpusubtype  caps    filetype ncmds "
8235             "sizeofcmds      flags\n";
8236   if (verbose) {
8237     if (magic == MachO::MH_MAGIC)
8238       outs() << "   MH_MAGIC";
8239     else if (magic == MachO::MH_MAGIC_64)
8240       outs() << "MH_MAGIC_64";
8241     else
8242       outs() << format(" 0x%08" PRIx32, magic);
8243     switch (cputype) {
8244     case MachO::CPU_TYPE_I386:
8245       outs() << "    I386";
8246       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8247       case MachO::CPU_SUBTYPE_I386_ALL:
8248         outs() << "        ALL";
8249         break;
8250       default:
8251         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8252         break;
8253       }
8254       break;
8255     case MachO::CPU_TYPE_X86_64:
8256       outs() << "  X86_64";
8257       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8258       case MachO::CPU_SUBTYPE_X86_64_ALL:
8259         outs() << "        ALL";
8260         break;
8261       case MachO::CPU_SUBTYPE_X86_64_H:
8262         outs() << "    Haswell";
8263         break;
8264       default:
8265         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8266         break;
8267       }
8268       break;
8269     case MachO::CPU_TYPE_ARM:
8270       outs() << "     ARM";
8271       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8272       case MachO::CPU_SUBTYPE_ARM_ALL:
8273         outs() << "        ALL";
8274         break;
8275       case MachO::CPU_SUBTYPE_ARM_V4T:
8276         outs() << "        V4T";
8277         break;
8278       case MachO::CPU_SUBTYPE_ARM_V5TEJ:
8279         outs() << "      V5TEJ";
8280         break;
8281       case MachO::CPU_SUBTYPE_ARM_XSCALE:
8282         outs() << "     XSCALE";
8283         break;
8284       case MachO::CPU_SUBTYPE_ARM_V6:
8285         outs() << "         V6";
8286         break;
8287       case MachO::CPU_SUBTYPE_ARM_V6M:
8288         outs() << "        V6M";
8289         break;
8290       case MachO::CPU_SUBTYPE_ARM_V7:
8291         outs() << "         V7";
8292         break;
8293       case MachO::CPU_SUBTYPE_ARM_V7EM:
8294         outs() << "       V7EM";
8295         break;
8296       case MachO::CPU_SUBTYPE_ARM_V7K:
8297         outs() << "        V7K";
8298         break;
8299       case MachO::CPU_SUBTYPE_ARM_V7M:
8300         outs() << "        V7M";
8301         break;
8302       case MachO::CPU_SUBTYPE_ARM_V7S:
8303         outs() << "        V7S";
8304         break;
8305       default:
8306         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8307         break;
8308       }
8309       break;
8310     case MachO::CPU_TYPE_ARM64:
8311       outs() << "   ARM64";
8312       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8313       case MachO::CPU_SUBTYPE_ARM64_ALL:
8314         outs() << "        ALL";
8315         break;
8316       case MachO::CPU_SUBTYPE_ARM64E:
8317         outs() << "          E";
8318         break;
8319       default:
8320         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8321         break;
8322       }
8323       break;
8324     case MachO::CPU_TYPE_ARM64_32:
8325       outs() << " ARM64_32";
8326       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8327       case MachO::CPU_SUBTYPE_ARM64_32_V8:
8328         outs() << "        V8";
8329         break;
8330       default:
8331         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8332         break;
8333       }
8334       break;
8335     case MachO::CPU_TYPE_POWERPC:
8336       outs() << "     PPC";
8337       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8338       case MachO::CPU_SUBTYPE_POWERPC_ALL:
8339         outs() << "        ALL";
8340         break;
8341       default:
8342         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8343         break;
8344       }
8345       break;
8346     case MachO::CPU_TYPE_POWERPC64:
8347       outs() << "   PPC64";
8348       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8349       case MachO::CPU_SUBTYPE_POWERPC_ALL:
8350         outs() << "        ALL";
8351         break;
8352       default:
8353         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8354         break;
8355       }
8356       break;
8357     default:
8358       outs() << format(" %7d", cputype);
8359       outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8360       break;
8361     }
8362     if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
8363       outs() << " LIB64";
8364     } else {
8365       outs() << format("  0x%02" PRIx32,
8366                        (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
8367     }
8368     switch (filetype) {
8369     case MachO::MH_OBJECT:
8370       outs() << "      OBJECT";
8371       break;
8372     case MachO::MH_EXECUTE:
8373       outs() << "     EXECUTE";
8374       break;
8375     case MachO::MH_FVMLIB:
8376       outs() << "      FVMLIB";
8377       break;
8378     case MachO::MH_CORE:
8379       outs() << "        CORE";
8380       break;
8381     case MachO::MH_PRELOAD:
8382       outs() << "     PRELOAD";
8383       break;
8384     case MachO::MH_DYLIB:
8385       outs() << "       DYLIB";
8386       break;
8387     case MachO::MH_DYLIB_STUB:
8388       outs() << "  DYLIB_STUB";
8389       break;
8390     case MachO::MH_DYLINKER:
8391       outs() << "    DYLINKER";
8392       break;
8393     case MachO::MH_BUNDLE:
8394       outs() << "      BUNDLE";
8395       break;
8396     case MachO::MH_DSYM:
8397       outs() << "        DSYM";
8398       break;
8399     case MachO::MH_KEXT_BUNDLE:
8400       outs() << "  KEXTBUNDLE";
8401       break;
8402     default:
8403       outs() << format("  %10u", filetype);
8404       break;
8405     }
8406     outs() << format(" %5u", ncmds);
8407     outs() << format(" %10u", sizeofcmds);
8408     uint32_t f = flags;
8409     if (f & MachO::MH_NOUNDEFS) {
8410       outs() << "   NOUNDEFS";
8411       f &= ~MachO::MH_NOUNDEFS;
8412     }
8413     if (f & MachO::MH_INCRLINK) {
8414       outs() << " INCRLINK";
8415       f &= ~MachO::MH_INCRLINK;
8416     }
8417     if (f & MachO::MH_DYLDLINK) {
8418       outs() << " DYLDLINK";
8419       f &= ~MachO::MH_DYLDLINK;
8420     }
8421     if (f & MachO::MH_BINDATLOAD) {
8422       outs() << " BINDATLOAD";
8423       f &= ~MachO::MH_BINDATLOAD;
8424     }
8425     if (f & MachO::MH_PREBOUND) {
8426       outs() << " PREBOUND";
8427       f &= ~MachO::MH_PREBOUND;
8428     }
8429     if (f & MachO::MH_SPLIT_SEGS) {
8430       outs() << " SPLIT_SEGS";
8431       f &= ~MachO::MH_SPLIT_SEGS;
8432     }
8433     if (f & MachO::MH_LAZY_INIT) {
8434       outs() << " LAZY_INIT";
8435       f &= ~MachO::MH_LAZY_INIT;
8436     }
8437     if (f & MachO::MH_TWOLEVEL) {
8438       outs() << " TWOLEVEL";
8439       f &= ~MachO::MH_TWOLEVEL;
8440     }
8441     if (f & MachO::MH_FORCE_FLAT) {
8442       outs() << " FORCE_FLAT";
8443       f &= ~MachO::MH_FORCE_FLAT;
8444     }
8445     if (f & MachO::MH_NOMULTIDEFS) {
8446       outs() << " NOMULTIDEFS";
8447       f &= ~MachO::MH_NOMULTIDEFS;
8448     }
8449     if (f & MachO::MH_NOFIXPREBINDING) {
8450       outs() << " NOFIXPREBINDING";
8451       f &= ~MachO::MH_NOFIXPREBINDING;
8452     }
8453     if (f & MachO::MH_PREBINDABLE) {
8454       outs() << " PREBINDABLE";
8455       f &= ~MachO::MH_PREBINDABLE;
8456     }
8457     if (f & MachO::MH_ALLMODSBOUND) {
8458       outs() << " ALLMODSBOUND";
8459       f &= ~MachO::MH_ALLMODSBOUND;
8460     }
8461     if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
8462       outs() << " SUBSECTIONS_VIA_SYMBOLS";
8463       f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
8464     }
8465     if (f & MachO::MH_CANONICAL) {
8466       outs() << " CANONICAL";
8467       f &= ~MachO::MH_CANONICAL;
8468     }
8469     if (f & MachO::MH_WEAK_DEFINES) {
8470       outs() << " WEAK_DEFINES";
8471       f &= ~MachO::MH_WEAK_DEFINES;
8472     }
8473     if (f & MachO::MH_BINDS_TO_WEAK) {
8474       outs() << " BINDS_TO_WEAK";
8475       f &= ~MachO::MH_BINDS_TO_WEAK;
8476     }
8477     if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
8478       outs() << " ALLOW_STACK_EXECUTION";
8479       f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
8480     }
8481     if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
8482       outs() << " DEAD_STRIPPABLE_DYLIB";
8483       f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
8484     }
8485     if (f & MachO::MH_PIE) {
8486       outs() << " PIE";
8487       f &= ~MachO::MH_PIE;
8488     }
8489     if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
8490       outs() << " NO_REEXPORTED_DYLIBS";
8491       f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
8492     }
8493     if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
8494       outs() << " MH_HAS_TLV_DESCRIPTORS";
8495       f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
8496     }
8497     if (f & MachO::MH_NO_HEAP_EXECUTION) {
8498       outs() << " MH_NO_HEAP_EXECUTION";
8499       f &= ~MachO::MH_NO_HEAP_EXECUTION;
8500     }
8501     if (f & MachO::MH_APP_EXTENSION_SAFE) {
8502       outs() << " APP_EXTENSION_SAFE";
8503       f &= ~MachO::MH_APP_EXTENSION_SAFE;
8504     }
8505     if (f & MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO) {
8506       outs() << " NLIST_OUTOFSYNC_WITH_DYLDINFO";
8507       f &= ~MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO;
8508     }
8509     if (f != 0 || flags == 0)
8510       outs() << format(" 0x%08" PRIx32, f);
8511   } else {
8512     outs() << format(" 0x%08" PRIx32, magic);
8513     outs() << format(" %7d", cputype);
8514     outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8515     outs() << format("  0x%02" PRIx32,
8516                      (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
8517     outs() << format("  %10u", filetype);
8518     outs() << format(" %5u", ncmds);
8519     outs() << format(" %10u", sizeofcmds);
8520     outs() << format(" 0x%08" PRIx32, flags);
8521   }
8522   outs() << "\n";
8523 }
8524 
8525 static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
8526                                 StringRef SegName, uint64_t vmaddr,
8527                                 uint64_t vmsize, uint64_t fileoff,
8528                                 uint64_t filesize, uint32_t maxprot,
8529                                 uint32_t initprot, uint32_t nsects,
8530                                 uint32_t flags, uint32_t object_size,
8531                                 bool verbose) {
8532   uint64_t expected_cmdsize;
8533   if (cmd == MachO::LC_SEGMENT) {
8534     outs() << "      cmd LC_SEGMENT\n";
8535     expected_cmdsize = nsects;
8536     expected_cmdsize *= sizeof(struct MachO::section);
8537     expected_cmdsize += sizeof(struct MachO::segment_command);
8538   } else {
8539     outs() << "      cmd LC_SEGMENT_64\n";
8540     expected_cmdsize = nsects;
8541     expected_cmdsize *= sizeof(struct MachO::section_64);
8542     expected_cmdsize += sizeof(struct MachO::segment_command_64);
8543   }
8544   outs() << "  cmdsize " << cmdsize;
8545   if (cmdsize != expected_cmdsize)
8546     outs() << " Inconsistent size\n";
8547   else
8548     outs() << "\n";
8549   outs() << "  segname " << SegName << "\n";
8550   if (cmd == MachO::LC_SEGMENT_64) {
8551     outs() << "   vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
8552     outs() << "   vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
8553   } else {
8554     outs() << "   vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
8555     outs() << "   vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
8556   }
8557   outs() << "  fileoff " << fileoff;
8558   if (fileoff > object_size)
8559     outs() << " (past end of file)\n";
8560   else
8561     outs() << "\n";
8562   outs() << " filesize " << filesize;
8563   if (fileoff + filesize > object_size)
8564     outs() << " (past end of file)\n";
8565   else
8566     outs() << "\n";
8567   if (verbose) {
8568     if ((maxprot &
8569          ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8570            MachO::VM_PROT_EXECUTE)) != 0)
8571       outs() << "  maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
8572     else {
8573       outs() << "  maxprot ";
8574       outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
8575       outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8576       outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
8577     }
8578     if ((initprot &
8579          ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8580            MachO::VM_PROT_EXECUTE)) != 0)
8581       outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
8582     else {
8583       outs() << " initprot ";
8584       outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
8585       outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8586       outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
8587     }
8588   } else {
8589     outs() << "  maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
8590     outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
8591   }
8592   outs() << "   nsects " << nsects << "\n";
8593   if (verbose) {
8594     outs() << "    flags";
8595     if (flags == 0)
8596       outs() << " (none)\n";
8597     else {
8598       if (flags & MachO::SG_HIGHVM) {
8599         outs() << " HIGHVM";
8600         flags &= ~MachO::SG_HIGHVM;
8601       }
8602       if (flags & MachO::SG_FVMLIB) {
8603         outs() << " FVMLIB";
8604         flags &= ~MachO::SG_FVMLIB;
8605       }
8606       if (flags & MachO::SG_NORELOC) {
8607         outs() << " NORELOC";
8608         flags &= ~MachO::SG_NORELOC;
8609       }
8610       if (flags & MachO::SG_PROTECTED_VERSION_1) {
8611         outs() << " PROTECTED_VERSION_1";
8612         flags &= ~MachO::SG_PROTECTED_VERSION_1;
8613       }
8614       if (flags)
8615         outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
8616       else
8617         outs() << "\n";
8618     }
8619   } else {
8620     outs() << "    flags " << format("0x%" PRIx32, flags) << "\n";
8621   }
8622 }
8623 
8624 static void PrintSection(const char *sectname, const char *segname,
8625                          uint64_t addr, uint64_t size, uint32_t offset,
8626                          uint32_t align, uint32_t reloff, uint32_t nreloc,
8627                          uint32_t flags, uint32_t reserved1, uint32_t reserved2,
8628                          uint32_t cmd, const char *sg_segname,
8629                          uint32_t filetype, uint32_t object_size,
8630                          bool verbose) {
8631   outs() << "Section\n";
8632   outs() << "  sectname " << format("%.16s\n", sectname);
8633   outs() << "   segname " << format("%.16s", segname);
8634   if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
8635     outs() << " (does not match segment)\n";
8636   else
8637     outs() << "\n";
8638   if (cmd == MachO::LC_SEGMENT_64) {
8639     outs() << "      addr " << format("0x%016" PRIx64, addr) << "\n";
8640     outs() << "      size " << format("0x%016" PRIx64, size);
8641   } else {
8642     outs() << "      addr " << format("0x%08" PRIx64, addr) << "\n";
8643     outs() << "      size " << format("0x%08" PRIx64, size);
8644   }
8645   if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
8646     outs() << " (past end of file)\n";
8647   else
8648     outs() << "\n";
8649   outs() << "    offset " << offset;
8650   if (offset > object_size)
8651     outs() << " (past end of file)\n";
8652   else
8653     outs() << "\n";
8654   uint32_t align_shifted = 1 << align;
8655   outs() << "     align 2^" << align << " (" << align_shifted << ")\n";
8656   outs() << "    reloff " << reloff;
8657   if (reloff > object_size)
8658     outs() << " (past end of file)\n";
8659   else
8660     outs() << "\n";
8661   outs() << "    nreloc " << nreloc;
8662   if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
8663     outs() << " (past end of file)\n";
8664   else
8665     outs() << "\n";
8666   uint32_t section_type = flags & MachO::SECTION_TYPE;
8667   if (verbose) {
8668     outs() << "      type";
8669     if (section_type == MachO::S_REGULAR)
8670       outs() << " S_REGULAR\n";
8671     else if (section_type == MachO::S_ZEROFILL)
8672       outs() << " S_ZEROFILL\n";
8673     else if (section_type == MachO::S_CSTRING_LITERALS)
8674       outs() << " S_CSTRING_LITERALS\n";
8675     else if (section_type == MachO::S_4BYTE_LITERALS)
8676       outs() << " S_4BYTE_LITERALS\n";
8677     else if (section_type == MachO::S_8BYTE_LITERALS)
8678       outs() << " S_8BYTE_LITERALS\n";
8679     else if (section_type == MachO::S_16BYTE_LITERALS)
8680       outs() << " S_16BYTE_LITERALS\n";
8681     else if (section_type == MachO::S_LITERAL_POINTERS)
8682       outs() << " S_LITERAL_POINTERS\n";
8683     else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
8684       outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
8685     else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
8686       outs() << " S_LAZY_SYMBOL_POINTERS\n";
8687     else if (section_type == MachO::S_SYMBOL_STUBS)
8688       outs() << " S_SYMBOL_STUBS\n";
8689     else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
8690       outs() << " S_MOD_INIT_FUNC_POINTERS\n";
8691     else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
8692       outs() << " S_MOD_TERM_FUNC_POINTERS\n";
8693     else if (section_type == MachO::S_COALESCED)
8694       outs() << " S_COALESCED\n";
8695     else if (section_type == MachO::S_INTERPOSING)
8696       outs() << " S_INTERPOSING\n";
8697     else if (section_type == MachO::S_DTRACE_DOF)
8698       outs() << " S_DTRACE_DOF\n";
8699     else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
8700       outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
8701     else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
8702       outs() << " S_THREAD_LOCAL_REGULAR\n";
8703     else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
8704       outs() << " S_THREAD_LOCAL_ZEROFILL\n";
8705     else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
8706       outs() << " S_THREAD_LOCAL_VARIABLES\n";
8707     else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8708       outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
8709     else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
8710       outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
8711     else
8712       outs() << format("0x%08" PRIx32, section_type) << "\n";
8713     outs() << "attributes";
8714     uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
8715     if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
8716       outs() << " PURE_INSTRUCTIONS";
8717     if (section_attributes & MachO::S_ATTR_NO_TOC)
8718       outs() << " NO_TOC";
8719     if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
8720       outs() << " STRIP_STATIC_SYMS";
8721     if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
8722       outs() << " NO_DEAD_STRIP";
8723     if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
8724       outs() << " LIVE_SUPPORT";
8725     if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
8726       outs() << " SELF_MODIFYING_CODE";
8727     if (section_attributes & MachO::S_ATTR_DEBUG)
8728       outs() << " DEBUG";
8729     if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
8730       outs() << " SOME_INSTRUCTIONS";
8731     if (section_attributes & MachO::S_ATTR_EXT_RELOC)
8732       outs() << " EXT_RELOC";
8733     if (section_attributes & MachO::S_ATTR_LOC_RELOC)
8734       outs() << " LOC_RELOC";
8735     if (section_attributes == 0)
8736       outs() << " (none)";
8737     outs() << "\n";
8738   } else
8739     outs() << "     flags " << format("0x%08" PRIx32, flags) << "\n";
8740   outs() << " reserved1 " << reserved1;
8741   if (section_type == MachO::S_SYMBOL_STUBS ||
8742       section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
8743       section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
8744       section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
8745       section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8746     outs() << " (index into indirect symbol table)\n";
8747   else
8748     outs() << "\n";
8749   outs() << " reserved2 " << reserved2;
8750   if (section_type == MachO::S_SYMBOL_STUBS)
8751     outs() << " (size of stubs)\n";
8752   else
8753     outs() << "\n";
8754 }
8755 
8756 static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
8757                                    uint32_t object_size) {
8758   outs() << "     cmd LC_SYMTAB\n";
8759   outs() << " cmdsize " << st.cmdsize;
8760   if (st.cmdsize != sizeof(struct MachO::symtab_command))
8761     outs() << " Incorrect size\n";
8762   else
8763     outs() << "\n";
8764   outs() << "  symoff " << st.symoff;
8765   if (st.symoff > object_size)
8766     outs() << " (past end of file)\n";
8767   else
8768     outs() << "\n";
8769   outs() << "   nsyms " << st.nsyms;
8770   uint64_t big_size;
8771   if (Is64Bit) {
8772     big_size = st.nsyms;
8773     big_size *= sizeof(struct MachO::nlist_64);
8774     big_size += st.symoff;
8775     if (big_size > object_size)
8776       outs() << " (past end of file)\n";
8777     else
8778       outs() << "\n";
8779   } else {
8780     big_size = st.nsyms;
8781     big_size *= sizeof(struct MachO::nlist);
8782     big_size += st.symoff;
8783     if (big_size > object_size)
8784       outs() << " (past end of file)\n";
8785     else
8786       outs() << "\n";
8787   }
8788   outs() << "  stroff " << st.stroff;
8789   if (st.stroff > object_size)
8790     outs() << " (past end of file)\n";
8791   else
8792     outs() << "\n";
8793   outs() << " strsize " << st.strsize;
8794   big_size = st.stroff;
8795   big_size += st.strsize;
8796   if (big_size > object_size)
8797     outs() << " (past end of file)\n";
8798   else
8799     outs() << "\n";
8800 }
8801 
8802 static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
8803                                      uint32_t nsyms, uint32_t object_size,
8804                                      bool Is64Bit) {
8805   outs() << "            cmd LC_DYSYMTAB\n";
8806   outs() << "        cmdsize " << dyst.cmdsize;
8807   if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
8808     outs() << " Incorrect size\n";
8809   else
8810     outs() << "\n";
8811   outs() << "      ilocalsym " << dyst.ilocalsym;
8812   if (dyst.ilocalsym > nsyms)
8813     outs() << " (greater than the number of symbols)\n";
8814   else
8815     outs() << "\n";
8816   outs() << "      nlocalsym " << dyst.nlocalsym;
8817   uint64_t big_size;
8818   big_size = dyst.ilocalsym;
8819   big_size += dyst.nlocalsym;
8820   if (big_size > nsyms)
8821     outs() << " (past the end of the symbol table)\n";
8822   else
8823     outs() << "\n";
8824   outs() << "     iextdefsym " << dyst.iextdefsym;
8825   if (dyst.iextdefsym > nsyms)
8826     outs() << " (greater than the number of symbols)\n";
8827   else
8828     outs() << "\n";
8829   outs() << "     nextdefsym " << dyst.nextdefsym;
8830   big_size = dyst.iextdefsym;
8831   big_size += dyst.nextdefsym;
8832   if (big_size > nsyms)
8833     outs() << " (past the end of the symbol table)\n";
8834   else
8835     outs() << "\n";
8836   outs() << "      iundefsym " << dyst.iundefsym;
8837   if (dyst.iundefsym > nsyms)
8838     outs() << " (greater than the number of symbols)\n";
8839   else
8840     outs() << "\n";
8841   outs() << "      nundefsym " << dyst.nundefsym;
8842   big_size = dyst.iundefsym;
8843   big_size += dyst.nundefsym;
8844   if (big_size > nsyms)
8845     outs() << " (past the end of the symbol table)\n";
8846   else
8847     outs() << "\n";
8848   outs() << "         tocoff " << dyst.tocoff;
8849   if (dyst.tocoff > object_size)
8850     outs() << " (past end of file)\n";
8851   else
8852     outs() << "\n";
8853   outs() << "           ntoc " << dyst.ntoc;
8854   big_size = dyst.ntoc;
8855   big_size *= sizeof(struct MachO::dylib_table_of_contents);
8856   big_size += dyst.tocoff;
8857   if (big_size > object_size)
8858     outs() << " (past end of file)\n";
8859   else
8860     outs() << "\n";
8861   outs() << "      modtaboff " << dyst.modtaboff;
8862   if (dyst.modtaboff > object_size)
8863     outs() << " (past end of file)\n";
8864   else
8865     outs() << "\n";
8866   outs() << "        nmodtab " << dyst.nmodtab;
8867   uint64_t modtabend;
8868   if (Is64Bit) {
8869     modtabend = dyst.nmodtab;
8870     modtabend *= sizeof(struct MachO::dylib_module_64);
8871     modtabend += dyst.modtaboff;
8872   } else {
8873     modtabend = dyst.nmodtab;
8874     modtabend *= sizeof(struct MachO::dylib_module);
8875     modtabend += dyst.modtaboff;
8876   }
8877   if (modtabend > object_size)
8878     outs() << " (past end of file)\n";
8879   else
8880     outs() << "\n";
8881   outs() << "   extrefsymoff " << dyst.extrefsymoff;
8882   if (dyst.extrefsymoff > object_size)
8883     outs() << " (past end of file)\n";
8884   else
8885     outs() << "\n";
8886   outs() << "    nextrefsyms " << dyst.nextrefsyms;
8887   big_size = dyst.nextrefsyms;
8888   big_size *= sizeof(struct MachO::dylib_reference);
8889   big_size += dyst.extrefsymoff;
8890   if (big_size > object_size)
8891     outs() << " (past end of file)\n";
8892   else
8893     outs() << "\n";
8894   outs() << " indirectsymoff " << dyst.indirectsymoff;
8895   if (dyst.indirectsymoff > object_size)
8896     outs() << " (past end of file)\n";
8897   else
8898     outs() << "\n";
8899   outs() << "  nindirectsyms " << dyst.nindirectsyms;
8900   big_size = dyst.nindirectsyms;
8901   big_size *= sizeof(uint32_t);
8902   big_size += dyst.indirectsymoff;
8903   if (big_size > object_size)
8904     outs() << " (past end of file)\n";
8905   else
8906     outs() << "\n";
8907   outs() << "      extreloff " << dyst.extreloff;
8908   if (dyst.extreloff > object_size)
8909     outs() << " (past end of file)\n";
8910   else
8911     outs() << "\n";
8912   outs() << "        nextrel " << dyst.nextrel;
8913   big_size = dyst.nextrel;
8914   big_size *= sizeof(struct MachO::relocation_info);
8915   big_size += dyst.extreloff;
8916   if (big_size > object_size)
8917     outs() << " (past end of file)\n";
8918   else
8919     outs() << "\n";
8920   outs() << "      locreloff " << dyst.locreloff;
8921   if (dyst.locreloff > object_size)
8922     outs() << " (past end of file)\n";
8923   else
8924     outs() << "\n";
8925   outs() << "        nlocrel " << dyst.nlocrel;
8926   big_size = dyst.nlocrel;
8927   big_size *= sizeof(struct MachO::relocation_info);
8928   big_size += dyst.locreloff;
8929   if (big_size > object_size)
8930     outs() << " (past end of file)\n";
8931   else
8932     outs() << "\n";
8933 }
8934 
8935 static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
8936                                      uint32_t object_size) {
8937   if (dc.cmd == MachO::LC_DYLD_INFO)
8938     outs() << "            cmd LC_DYLD_INFO\n";
8939   else
8940     outs() << "            cmd LC_DYLD_INFO_ONLY\n";
8941   outs() << "        cmdsize " << dc.cmdsize;
8942   if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
8943     outs() << " Incorrect size\n";
8944   else
8945     outs() << "\n";
8946   outs() << "     rebase_off " << dc.rebase_off;
8947   if (dc.rebase_off > object_size)
8948     outs() << " (past end of file)\n";
8949   else
8950     outs() << "\n";
8951   outs() << "    rebase_size " << dc.rebase_size;
8952   uint64_t big_size;
8953   big_size = dc.rebase_off;
8954   big_size += dc.rebase_size;
8955   if (big_size > object_size)
8956     outs() << " (past end of file)\n";
8957   else
8958     outs() << "\n";
8959   outs() << "       bind_off " << dc.bind_off;
8960   if (dc.bind_off > object_size)
8961     outs() << " (past end of file)\n";
8962   else
8963     outs() << "\n";
8964   outs() << "      bind_size " << dc.bind_size;
8965   big_size = dc.bind_off;
8966   big_size += dc.bind_size;
8967   if (big_size > object_size)
8968     outs() << " (past end of file)\n";
8969   else
8970     outs() << "\n";
8971   outs() << "  weak_bind_off " << dc.weak_bind_off;
8972   if (dc.weak_bind_off > object_size)
8973     outs() << " (past end of file)\n";
8974   else
8975     outs() << "\n";
8976   outs() << " weak_bind_size " << dc.weak_bind_size;
8977   big_size = dc.weak_bind_off;
8978   big_size += dc.weak_bind_size;
8979   if (big_size > object_size)
8980     outs() << " (past end of file)\n";
8981   else
8982     outs() << "\n";
8983   outs() << "  lazy_bind_off " << dc.lazy_bind_off;
8984   if (dc.lazy_bind_off > object_size)
8985     outs() << " (past end of file)\n";
8986   else
8987     outs() << "\n";
8988   outs() << " lazy_bind_size " << dc.lazy_bind_size;
8989   big_size = dc.lazy_bind_off;
8990   big_size += dc.lazy_bind_size;
8991   if (big_size > object_size)
8992     outs() << " (past end of file)\n";
8993   else
8994     outs() << "\n";
8995   outs() << "     export_off " << dc.export_off;
8996   if (dc.export_off > object_size)
8997     outs() << " (past end of file)\n";
8998   else
8999     outs() << "\n";
9000   outs() << "    export_size " << dc.export_size;
9001   big_size = dc.export_off;
9002   big_size += dc.export_size;
9003   if (big_size > object_size)
9004     outs() << " (past end of file)\n";
9005   else
9006     outs() << "\n";
9007 }
9008 
9009 static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
9010                                  const char *Ptr) {
9011   if (dyld.cmd == MachO::LC_ID_DYLINKER)
9012     outs() << "          cmd LC_ID_DYLINKER\n";
9013   else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
9014     outs() << "          cmd LC_LOAD_DYLINKER\n";
9015   else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
9016     outs() << "          cmd LC_DYLD_ENVIRONMENT\n";
9017   else
9018     outs() << "          cmd ?(" << dyld.cmd << ")\n";
9019   outs() << "      cmdsize " << dyld.cmdsize;
9020   if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
9021     outs() << " Incorrect size\n";
9022   else
9023     outs() << "\n";
9024   if (dyld.name >= dyld.cmdsize)
9025     outs() << "         name ?(bad offset " << dyld.name << ")\n";
9026   else {
9027     const char *P = (const char *)(Ptr) + dyld.name;
9028     outs() << "         name " << P << " (offset " << dyld.name << ")\n";
9029   }
9030 }
9031 
9032 static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
9033   outs() << "     cmd LC_UUID\n";
9034   outs() << " cmdsize " << uuid.cmdsize;
9035   if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
9036     outs() << " Incorrect size\n";
9037   else
9038     outs() << "\n";
9039   outs() << "    uuid ";
9040   for (int i = 0; i < 16; ++i) {
9041     outs() << format("%02" PRIX32, uuid.uuid[i]);
9042     if (i == 3 || i == 5 || i == 7 || i == 9)
9043       outs() << "-";
9044   }
9045   outs() << "\n";
9046 }
9047 
9048 static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
9049   outs() << "          cmd LC_RPATH\n";
9050   outs() << "      cmdsize " << rpath.cmdsize;
9051   if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
9052     outs() << " Incorrect size\n";
9053   else
9054     outs() << "\n";
9055   if (rpath.path >= rpath.cmdsize)
9056     outs() << "         path ?(bad offset " << rpath.path << ")\n";
9057   else {
9058     const char *P = (const char *)(Ptr) + rpath.path;
9059     outs() << "         path " << P << " (offset " << rpath.path << ")\n";
9060   }
9061 }
9062 
9063 static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
9064   StringRef LoadCmdName;
9065   switch (vd.cmd) {
9066   case MachO::LC_VERSION_MIN_MACOSX:
9067     LoadCmdName = "LC_VERSION_MIN_MACOSX";
9068     break;
9069   case MachO::LC_VERSION_MIN_IPHONEOS:
9070     LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
9071     break;
9072   case MachO::LC_VERSION_MIN_TVOS:
9073     LoadCmdName = "LC_VERSION_MIN_TVOS";
9074     break;
9075   case MachO::LC_VERSION_MIN_WATCHOS:
9076     LoadCmdName = "LC_VERSION_MIN_WATCHOS";
9077     break;
9078   default:
9079     llvm_unreachable("Unknown version min load command");
9080   }
9081 
9082   outs() << "      cmd " << LoadCmdName << '\n';
9083   outs() << "  cmdsize " << vd.cmdsize;
9084   if (vd.cmdsize != sizeof(struct MachO::version_min_command))
9085     outs() << " Incorrect size\n";
9086   else
9087     outs() << "\n";
9088   outs() << "  version "
9089          << MachOObjectFile::getVersionMinMajor(vd, false) << "."
9090          << MachOObjectFile::getVersionMinMinor(vd, false);
9091   uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
9092   if (Update != 0)
9093     outs() << "." << Update;
9094   outs() << "\n";
9095   if (vd.sdk == 0)
9096     outs() << "      sdk n/a";
9097   else {
9098     outs() << "      sdk "
9099            << MachOObjectFile::getVersionMinMajor(vd, true) << "."
9100            << MachOObjectFile::getVersionMinMinor(vd, true);
9101   }
9102   Update = MachOObjectFile::getVersionMinUpdate(vd, true);
9103   if (Update != 0)
9104     outs() << "." << Update;
9105   outs() << "\n";
9106 }
9107 
9108 static void PrintNoteLoadCommand(MachO::note_command Nt) {
9109   outs() << "       cmd LC_NOTE\n";
9110   outs() << "   cmdsize " << Nt.cmdsize;
9111   if (Nt.cmdsize != sizeof(struct MachO::note_command))
9112     outs() << " Incorrect size\n";
9113   else
9114     outs() << "\n";
9115   const char *d = Nt.data_owner;
9116   outs() << "data_owner " << format("%.16s\n", d);
9117   outs() << "    offset " << Nt.offset << "\n";
9118   outs() << "      size " << Nt.size << "\n";
9119 }
9120 
9121 static void PrintBuildToolVersion(MachO::build_tool_version bv) {
9122   outs() << "      tool " << MachOObjectFile::getBuildTool(bv.tool) << "\n";
9123   outs() << "   version " << MachOObjectFile::getVersionString(bv.version)
9124          << "\n";
9125 }
9126 
9127 static void PrintBuildVersionLoadCommand(const MachOObjectFile *obj,
9128                                          MachO::build_version_command bd) {
9129   outs() << "       cmd LC_BUILD_VERSION\n";
9130   outs() << "   cmdsize " << bd.cmdsize;
9131   if (bd.cmdsize !=
9132       sizeof(struct MachO::build_version_command) +
9133           bd.ntools * sizeof(struct MachO::build_tool_version))
9134     outs() << " Incorrect size\n";
9135   else
9136     outs() << "\n";
9137   outs() << "  platform " << MachOObjectFile::getBuildPlatform(bd.platform)
9138          << "\n";
9139   if (bd.sdk)
9140     outs() << "       sdk " << MachOObjectFile::getVersionString(bd.sdk)
9141            << "\n";
9142   else
9143     outs() << "       sdk n/a\n";
9144   outs() << "     minos " << MachOObjectFile::getVersionString(bd.minos)
9145          << "\n";
9146   outs() << "    ntools " << bd.ntools << "\n";
9147   for (unsigned i = 0; i < bd.ntools; ++i) {
9148     MachO::build_tool_version bv = obj->getBuildToolVersion(i);
9149     PrintBuildToolVersion(bv);
9150   }
9151 }
9152 
9153 static void PrintSourceVersionCommand(MachO::source_version_command sd) {
9154   outs() << "      cmd LC_SOURCE_VERSION\n";
9155   outs() << "  cmdsize " << sd.cmdsize;
9156   if (sd.cmdsize != sizeof(struct MachO::source_version_command))
9157     outs() << " Incorrect size\n";
9158   else
9159     outs() << "\n";
9160   uint64_t a = (sd.version >> 40) & 0xffffff;
9161   uint64_t b = (sd.version >> 30) & 0x3ff;
9162   uint64_t c = (sd.version >> 20) & 0x3ff;
9163   uint64_t d = (sd.version >> 10) & 0x3ff;
9164   uint64_t e = sd.version & 0x3ff;
9165   outs() << "  version " << a << "." << b;
9166   if (e != 0)
9167     outs() << "." << c << "." << d << "." << e;
9168   else if (d != 0)
9169     outs() << "." << c << "." << d;
9170   else if (c != 0)
9171     outs() << "." << c;
9172   outs() << "\n";
9173 }
9174 
9175 static void PrintEntryPointCommand(MachO::entry_point_command ep) {
9176   outs() << "       cmd LC_MAIN\n";
9177   outs() << "   cmdsize " << ep.cmdsize;
9178   if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
9179     outs() << " Incorrect size\n";
9180   else
9181     outs() << "\n";
9182   outs() << "  entryoff " << ep.entryoff << "\n";
9183   outs() << " stacksize " << ep.stacksize << "\n";
9184 }
9185 
9186 static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
9187                                        uint32_t object_size) {
9188   outs() << "          cmd LC_ENCRYPTION_INFO\n";
9189   outs() << "      cmdsize " << ec.cmdsize;
9190   if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
9191     outs() << " Incorrect size\n";
9192   else
9193     outs() << "\n";
9194   outs() << "     cryptoff " << ec.cryptoff;
9195   if (ec.cryptoff > object_size)
9196     outs() << " (past end of file)\n";
9197   else
9198     outs() << "\n";
9199   outs() << "    cryptsize " << ec.cryptsize;
9200   if (ec.cryptsize > object_size)
9201     outs() << " (past end of file)\n";
9202   else
9203     outs() << "\n";
9204   outs() << "      cryptid " << ec.cryptid << "\n";
9205 }
9206 
9207 static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
9208                                          uint32_t object_size) {
9209   outs() << "          cmd LC_ENCRYPTION_INFO_64\n";
9210   outs() << "      cmdsize " << ec.cmdsize;
9211   if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
9212     outs() << " Incorrect size\n";
9213   else
9214     outs() << "\n";
9215   outs() << "     cryptoff " << ec.cryptoff;
9216   if (ec.cryptoff > object_size)
9217     outs() << " (past end of file)\n";
9218   else
9219     outs() << "\n";
9220   outs() << "    cryptsize " << ec.cryptsize;
9221   if (ec.cryptsize > object_size)
9222     outs() << " (past end of file)\n";
9223   else
9224     outs() << "\n";
9225   outs() << "      cryptid " << ec.cryptid << "\n";
9226   outs() << "          pad " << ec.pad << "\n";
9227 }
9228 
9229 static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
9230                                      const char *Ptr) {
9231   outs() << "     cmd LC_LINKER_OPTION\n";
9232   outs() << " cmdsize " << lo.cmdsize;
9233   if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
9234     outs() << " Incorrect size\n";
9235   else
9236     outs() << "\n";
9237   outs() << "   count " << lo.count << "\n";
9238   const char *string = Ptr + sizeof(struct MachO::linker_option_command);
9239   uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
9240   uint32_t i = 0;
9241   while (left > 0) {
9242     while (*string == '\0' && left > 0) {
9243       string++;
9244       left--;
9245     }
9246     if (left > 0) {
9247       i++;
9248       outs() << "  string #" << i << " " << format("%.*s\n", left, string);
9249       uint32_t NullPos = StringRef(string, left).find('\0');
9250       uint32_t len = std::min(NullPos, left) + 1;
9251       string += len;
9252       left -= len;
9253     }
9254   }
9255   if (lo.count != i)
9256     outs() << "   count " << lo.count << " does not match number of strings "
9257            << i << "\n";
9258 }
9259 
9260 static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
9261                                      const char *Ptr) {
9262   outs() << "          cmd LC_SUB_FRAMEWORK\n";
9263   outs() << "      cmdsize " << sub.cmdsize;
9264   if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
9265     outs() << " Incorrect size\n";
9266   else
9267     outs() << "\n";
9268   if (sub.umbrella < sub.cmdsize) {
9269     const char *P = Ptr + sub.umbrella;
9270     outs() << "     umbrella " << P << " (offset " << sub.umbrella << ")\n";
9271   } else {
9272     outs() << "     umbrella ?(bad offset " << sub.umbrella << ")\n";
9273   }
9274 }
9275 
9276 static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
9277                                     const char *Ptr) {
9278   outs() << "          cmd LC_SUB_UMBRELLA\n";
9279   outs() << "      cmdsize " << sub.cmdsize;
9280   if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
9281     outs() << " Incorrect size\n";
9282   else
9283     outs() << "\n";
9284   if (sub.sub_umbrella < sub.cmdsize) {
9285     const char *P = Ptr + sub.sub_umbrella;
9286     outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
9287   } else {
9288     outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
9289   }
9290 }
9291 
9292 static void PrintSubLibraryCommand(MachO::sub_library_command sub,
9293                                    const char *Ptr) {
9294   outs() << "          cmd LC_SUB_LIBRARY\n";
9295   outs() << "      cmdsize " << sub.cmdsize;
9296   if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
9297     outs() << " Incorrect size\n";
9298   else
9299     outs() << "\n";
9300   if (sub.sub_library < sub.cmdsize) {
9301     const char *P = Ptr + sub.sub_library;
9302     outs() << "  sub_library " << P << " (offset " << sub.sub_library << ")\n";
9303   } else {
9304     outs() << "  sub_library ?(bad offset " << sub.sub_library << ")\n";
9305   }
9306 }
9307 
9308 static void PrintSubClientCommand(MachO::sub_client_command sub,
9309                                   const char *Ptr) {
9310   outs() << "          cmd LC_SUB_CLIENT\n";
9311   outs() << "      cmdsize " << sub.cmdsize;
9312   if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
9313     outs() << " Incorrect size\n";
9314   else
9315     outs() << "\n";
9316   if (sub.client < sub.cmdsize) {
9317     const char *P = Ptr + sub.client;
9318     outs() << "       client " << P << " (offset " << sub.client << ")\n";
9319   } else {
9320     outs() << "       client ?(bad offset " << sub.client << ")\n";
9321   }
9322 }
9323 
9324 static void PrintRoutinesCommand(MachO::routines_command r) {
9325   outs() << "          cmd LC_ROUTINES\n";
9326   outs() << "      cmdsize " << r.cmdsize;
9327   if (r.cmdsize != sizeof(struct MachO::routines_command))
9328     outs() << " Incorrect size\n";
9329   else
9330     outs() << "\n";
9331   outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
9332   outs() << "  init_module " << r.init_module << "\n";
9333   outs() << "    reserved1 " << r.reserved1 << "\n";
9334   outs() << "    reserved2 " << r.reserved2 << "\n";
9335   outs() << "    reserved3 " << r.reserved3 << "\n";
9336   outs() << "    reserved4 " << r.reserved4 << "\n";
9337   outs() << "    reserved5 " << r.reserved5 << "\n";
9338   outs() << "    reserved6 " << r.reserved6 << "\n";
9339 }
9340 
9341 static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
9342   outs() << "          cmd LC_ROUTINES_64\n";
9343   outs() << "      cmdsize " << r.cmdsize;
9344   if (r.cmdsize != sizeof(struct MachO::routines_command_64))
9345     outs() << " Incorrect size\n";
9346   else
9347     outs() << "\n";
9348   outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
9349   outs() << "  init_module " << r.init_module << "\n";
9350   outs() << "    reserved1 " << r.reserved1 << "\n";
9351   outs() << "    reserved2 " << r.reserved2 << "\n";
9352   outs() << "    reserved3 " << r.reserved3 << "\n";
9353   outs() << "    reserved4 " << r.reserved4 << "\n";
9354   outs() << "    reserved5 " << r.reserved5 << "\n";
9355   outs() << "    reserved6 " << r.reserved6 << "\n";
9356 }
9357 
9358 static void Print_x86_thread_state32_t(MachO::x86_thread_state32_t &cpu32) {
9359   outs() << "\t    eax " << format("0x%08" PRIx32, cpu32.eax);
9360   outs() << " ebx    " << format("0x%08" PRIx32, cpu32.ebx);
9361   outs() << " ecx " << format("0x%08" PRIx32, cpu32.ecx);
9362   outs() << " edx " << format("0x%08" PRIx32, cpu32.edx) << "\n";
9363   outs() << "\t    edi " << format("0x%08" PRIx32, cpu32.edi);
9364   outs() << " esi    " << format("0x%08" PRIx32, cpu32.esi);
9365   outs() << " ebp " << format("0x%08" PRIx32, cpu32.ebp);
9366   outs() << " esp " << format("0x%08" PRIx32, cpu32.esp) << "\n";
9367   outs() << "\t    ss  " << format("0x%08" PRIx32, cpu32.ss);
9368   outs() << " eflags " << format("0x%08" PRIx32, cpu32.eflags);
9369   outs() << " eip " << format("0x%08" PRIx32, cpu32.eip);
9370   outs() << " cs  " << format("0x%08" PRIx32, cpu32.cs) << "\n";
9371   outs() << "\t    ds  " << format("0x%08" PRIx32, cpu32.ds);
9372   outs() << " es     " << format("0x%08" PRIx32, cpu32.es);
9373   outs() << " fs  " << format("0x%08" PRIx32, cpu32.fs);
9374   outs() << " gs  " << format("0x%08" PRIx32, cpu32.gs) << "\n";
9375 }
9376 
9377 static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
9378   outs() << "   rax  " << format("0x%016" PRIx64, cpu64.rax);
9379   outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
9380   outs() << " rcx  " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
9381   outs() << "   rdx  " << format("0x%016" PRIx64, cpu64.rdx);
9382   outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
9383   outs() << " rsi  " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
9384   outs() << "   rbp  " << format("0x%016" PRIx64, cpu64.rbp);
9385   outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
9386   outs() << " r8   " << format("0x%016" PRIx64, cpu64.r8) << "\n";
9387   outs() << "    r9  " << format("0x%016" PRIx64, cpu64.r9);
9388   outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
9389   outs() << " r11  " << format("0x%016" PRIx64, cpu64.r11) << "\n";
9390   outs() << "   r12  " << format("0x%016" PRIx64, cpu64.r12);
9391   outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
9392   outs() << " r14  " << format("0x%016" PRIx64, cpu64.r14) << "\n";
9393   outs() << "   r15  " << format("0x%016" PRIx64, cpu64.r15);
9394   outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
9395   outs() << "rflags  " << format("0x%016" PRIx64, cpu64.rflags);
9396   outs() << " cs  " << format("0x%016" PRIx64, cpu64.cs);
9397   outs() << " fs   " << format("0x%016" PRIx64, cpu64.fs) << "\n";
9398   outs() << "    gs  " << format("0x%016" PRIx64, cpu64.gs) << "\n";
9399 }
9400 
9401 static void Print_mmst_reg(MachO::mmst_reg_t &r) {
9402   uint32_t f;
9403   outs() << "\t      mmst_reg  ";
9404   for (f = 0; f < 10; f++)
9405     outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
9406   outs() << "\n";
9407   outs() << "\t      mmst_rsrv ";
9408   for (f = 0; f < 6; f++)
9409     outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
9410   outs() << "\n";
9411 }
9412 
9413 static void Print_xmm_reg(MachO::xmm_reg_t &r) {
9414   uint32_t f;
9415   outs() << "\t      xmm_reg ";
9416   for (f = 0; f < 16; f++)
9417     outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
9418   outs() << "\n";
9419 }
9420 
9421 static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
9422   outs() << "\t    fpu_reserved[0] " << fpu.fpu_reserved[0];
9423   outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
9424   outs() << "\t    control: invalid " << fpu.fpu_fcw.invalid;
9425   outs() << " denorm " << fpu.fpu_fcw.denorm;
9426   outs() << " zdiv " << fpu.fpu_fcw.zdiv;
9427   outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
9428   outs() << " undfl " << fpu.fpu_fcw.undfl;
9429   outs() << " precis " << fpu.fpu_fcw.precis << "\n";
9430   outs() << "\t\t     pc ";
9431   if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
9432     outs() << "FP_PREC_24B ";
9433   else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
9434     outs() << "FP_PREC_53B ";
9435   else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
9436     outs() << "FP_PREC_64B ";
9437   else
9438     outs() << fpu.fpu_fcw.pc << " ";
9439   outs() << "rc ";
9440   if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
9441     outs() << "FP_RND_NEAR ";
9442   else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
9443     outs() << "FP_RND_DOWN ";
9444   else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
9445     outs() << "FP_RND_UP ";
9446   else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
9447     outs() << "FP_CHOP ";
9448   outs() << "\n";
9449   outs() << "\t    status: invalid " << fpu.fpu_fsw.invalid;
9450   outs() << " denorm " << fpu.fpu_fsw.denorm;
9451   outs() << " zdiv " << fpu.fpu_fsw.zdiv;
9452   outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
9453   outs() << " undfl " << fpu.fpu_fsw.undfl;
9454   outs() << " precis " << fpu.fpu_fsw.precis;
9455   outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
9456   outs() << "\t            errsumm " << fpu.fpu_fsw.errsumm;
9457   outs() << " c0 " << fpu.fpu_fsw.c0;
9458   outs() << " c1 " << fpu.fpu_fsw.c1;
9459   outs() << " c2 " << fpu.fpu_fsw.c2;
9460   outs() << " tos " << fpu.fpu_fsw.tos;
9461   outs() << " c3 " << fpu.fpu_fsw.c3;
9462   outs() << " busy " << fpu.fpu_fsw.busy << "\n";
9463   outs() << "\t    fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
9464   outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
9465   outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
9466   outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
9467   outs() << "\t    fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
9468   outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
9469   outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
9470   outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
9471   outs() << "\t    fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
9472   outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
9473   outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
9474   outs() << "\n";
9475   outs() << "\t    fpu_stmm0:\n";
9476   Print_mmst_reg(fpu.fpu_stmm0);
9477   outs() << "\t    fpu_stmm1:\n";
9478   Print_mmst_reg(fpu.fpu_stmm1);
9479   outs() << "\t    fpu_stmm2:\n";
9480   Print_mmst_reg(fpu.fpu_stmm2);
9481   outs() << "\t    fpu_stmm3:\n";
9482   Print_mmst_reg(fpu.fpu_stmm3);
9483   outs() << "\t    fpu_stmm4:\n";
9484   Print_mmst_reg(fpu.fpu_stmm4);
9485   outs() << "\t    fpu_stmm5:\n";
9486   Print_mmst_reg(fpu.fpu_stmm5);
9487   outs() << "\t    fpu_stmm6:\n";
9488   Print_mmst_reg(fpu.fpu_stmm6);
9489   outs() << "\t    fpu_stmm7:\n";
9490   Print_mmst_reg(fpu.fpu_stmm7);
9491   outs() << "\t    fpu_xmm0:\n";
9492   Print_xmm_reg(fpu.fpu_xmm0);
9493   outs() << "\t    fpu_xmm1:\n";
9494   Print_xmm_reg(fpu.fpu_xmm1);
9495   outs() << "\t    fpu_xmm2:\n";
9496   Print_xmm_reg(fpu.fpu_xmm2);
9497   outs() << "\t    fpu_xmm3:\n";
9498   Print_xmm_reg(fpu.fpu_xmm3);
9499   outs() << "\t    fpu_xmm4:\n";
9500   Print_xmm_reg(fpu.fpu_xmm4);
9501   outs() << "\t    fpu_xmm5:\n";
9502   Print_xmm_reg(fpu.fpu_xmm5);
9503   outs() << "\t    fpu_xmm6:\n";
9504   Print_xmm_reg(fpu.fpu_xmm6);
9505   outs() << "\t    fpu_xmm7:\n";
9506   Print_xmm_reg(fpu.fpu_xmm7);
9507   outs() << "\t    fpu_xmm8:\n";
9508   Print_xmm_reg(fpu.fpu_xmm8);
9509   outs() << "\t    fpu_xmm9:\n";
9510   Print_xmm_reg(fpu.fpu_xmm9);
9511   outs() << "\t    fpu_xmm10:\n";
9512   Print_xmm_reg(fpu.fpu_xmm10);
9513   outs() << "\t    fpu_xmm11:\n";
9514   Print_xmm_reg(fpu.fpu_xmm11);
9515   outs() << "\t    fpu_xmm12:\n";
9516   Print_xmm_reg(fpu.fpu_xmm12);
9517   outs() << "\t    fpu_xmm13:\n";
9518   Print_xmm_reg(fpu.fpu_xmm13);
9519   outs() << "\t    fpu_xmm14:\n";
9520   Print_xmm_reg(fpu.fpu_xmm14);
9521   outs() << "\t    fpu_xmm15:\n";
9522   Print_xmm_reg(fpu.fpu_xmm15);
9523   outs() << "\t    fpu_rsrv4:\n";
9524   for (uint32_t f = 0; f < 6; f++) {
9525     outs() << "\t            ";
9526     for (uint32_t g = 0; g < 16; g++)
9527       outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
9528     outs() << "\n";
9529   }
9530   outs() << "\t    fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
9531   outs() << "\n";
9532 }
9533 
9534 static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
9535   outs() << "\t    trapno " << format("0x%08" PRIx32, exc64.trapno);
9536   outs() << " err " << format("0x%08" PRIx32, exc64.err);
9537   outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
9538 }
9539 
9540 static void Print_arm_thread_state32_t(MachO::arm_thread_state32_t &cpu32) {
9541   outs() << "\t    r0  " << format("0x%08" PRIx32, cpu32.r[0]);
9542   outs() << " r1     "   << format("0x%08" PRIx32, cpu32.r[1]);
9543   outs() << " r2  "      << format("0x%08" PRIx32, cpu32.r[2]);
9544   outs() << " r3  "      << format("0x%08" PRIx32, cpu32.r[3]) << "\n";
9545   outs() << "\t    r4  " << format("0x%08" PRIx32, cpu32.r[4]);
9546   outs() << " r5     "   << format("0x%08" PRIx32, cpu32.r[5]);
9547   outs() << " r6  "      << format("0x%08" PRIx32, cpu32.r[6]);
9548   outs() << " r7  "      << format("0x%08" PRIx32, cpu32.r[7]) << "\n";
9549   outs() << "\t    r8  " << format("0x%08" PRIx32, cpu32.r[8]);
9550   outs() << " r9     "   << format("0x%08" PRIx32, cpu32.r[9]);
9551   outs() << " r10 "      << format("0x%08" PRIx32, cpu32.r[10]);
9552   outs() << " r11 "      << format("0x%08" PRIx32, cpu32.r[11]) << "\n";
9553   outs() << "\t    r12 " << format("0x%08" PRIx32, cpu32.r[12]);
9554   outs() << " sp     "   << format("0x%08" PRIx32, cpu32.sp);
9555   outs() << " lr  "      << format("0x%08" PRIx32, cpu32.lr);
9556   outs() << " pc  "      << format("0x%08" PRIx32, cpu32.pc) << "\n";
9557   outs() << "\t   cpsr " << format("0x%08" PRIx32, cpu32.cpsr) << "\n";
9558 }
9559 
9560 static void Print_arm_thread_state64_t(MachO::arm_thread_state64_t &cpu64) {
9561   outs() << "\t    x0  " << format("0x%016" PRIx64, cpu64.x[0]);
9562   outs() << " x1  "      << format("0x%016" PRIx64, cpu64.x[1]);
9563   outs() << " x2  "      << format("0x%016" PRIx64, cpu64.x[2]) << "\n";
9564   outs() << "\t    x3  " << format("0x%016" PRIx64, cpu64.x[3]);
9565   outs() << " x4  "      << format("0x%016" PRIx64, cpu64.x[4]);
9566   outs() << " x5  "      << format("0x%016" PRIx64, cpu64.x[5]) << "\n";
9567   outs() << "\t    x6  " << format("0x%016" PRIx64, cpu64.x[6]);
9568   outs() << " x7  "      << format("0x%016" PRIx64, cpu64.x[7]);
9569   outs() << " x8  "      << format("0x%016" PRIx64, cpu64.x[8]) << "\n";
9570   outs() << "\t    x9  " << format("0x%016" PRIx64, cpu64.x[9]);
9571   outs() << " x10 "      << format("0x%016" PRIx64, cpu64.x[10]);
9572   outs() << " x11 "      << format("0x%016" PRIx64, cpu64.x[11]) << "\n";
9573   outs() << "\t    x12 " << format("0x%016" PRIx64, cpu64.x[12]);
9574   outs() << " x13 "      << format("0x%016" PRIx64, cpu64.x[13]);
9575   outs() << " x14 "      << format("0x%016" PRIx64, cpu64.x[14]) << "\n";
9576   outs() << "\t    x15 " << format("0x%016" PRIx64, cpu64.x[15]);
9577   outs() << " x16 "      << format("0x%016" PRIx64, cpu64.x[16]);
9578   outs() << " x17 "      << format("0x%016" PRIx64, cpu64.x[17]) << "\n";
9579   outs() << "\t    x18 " << format("0x%016" PRIx64, cpu64.x[18]);
9580   outs() << " x19 "      << format("0x%016" PRIx64, cpu64.x[19]);
9581   outs() << " x20 "      << format("0x%016" PRIx64, cpu64.x[20]) << "\n";
9582   outs() << "\t    x21 " << format("0x%016" PRIx64, cpu64.x[21]);
9583   outs() << " x22 "      << format("0x%016" PRIx64, cpu64.x[22]);
9584   outs() << " x23 "      << format("0x%016" PRIx64, cpu64.x[23]) << "\n";
9585   outs() << "\t    x24 " << format("0x%016" PRIx64, cpu64.x[24]);
9586   outs() << " x25 "      << format("0x%016" PRIx64, cpu64.x[25]);
9587   outs() << " x26 "      << format("0x%016" PRIx64, cpu64.x[26]) << "\n";
9588   outs() << "\t    x27 " << format("0x%016" PRIx64, cpu64.x[27]);
9589   outs() << " x28 "      << format("0x%016" PRIx64, cpu64.x[28]);
9590   outs() << "  fp "      << format("0x%016" PRIx64, cpu64.fp) << "\n";
9591   outs() << "\t     lr " << format("0x%016" PRIx64, cpu64.lr);
9592   outs() << " sp  "      << format("0x%016" PRIx64, cpu64.sp);
9593   outs() << "  pc "      << format("0x%016" PRIx64, cpu64.pc) << "\n";
9594   outs() << "\t   cpsr " << format("0x%08"  PRIx32, cpu64.cpsr) << "\n";
9595 }
9596 
9597 static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
9598                                bool isLittleEndian, uint32_t cputype) {
9599   if (t.cmd == MachO::LC_THREAD)
9600     outs() << "        cmd LC_THREAD\n";
9601   else if (t.cmd == MachO::LC_UNIXTHREAD)
9602     outs() << "        cmd LC_UNIXTHREAD\n";
9603   else
9604     outs() << "        cmd " << t.cmd << " (unknown)\n";
9605   outs() << "    cmdsize " << t.cmdsize;
9606   if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
9607     outs() << " Incorrect size\n";
9608   else
9609     outs() << "\n";
9610 
9611   const char *begin = Ptr + sizeof(struct MachO::thread_command);
9612   const char *end = Ptr + t.cmdsize;
9613   uint32_t flavor, count, left;
9614   if (cputype == MachO::CPU_TYPE_I386) {
9615     while (begin < end) {
9616       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9617         memcpy((char *)&flavor, begin, sizeof(uint32_t));
9618         begin += sizeof(uint32_t);
9619       } else {
9620         flavor = 0;
9621         begin = end;
9622       }
9623       if (isLittleEndian != sys::IsLittleEndianHost)
9624         sys::swapByteOrder(flavor);
9625       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9626         memcpy((char *)&count, begin, sizeof(uint32_t));
9627         begin += sizeof(uint32_t);
9628       } else {
9629         count = 0;
9630         begin = end;
9631       }
9632       if (isLittleEndian != sys::IsLittleEndianHost)
9633         sys::swapByteOrder(count);
9634       if (flavor == MachO::x86_THREAD_STATE32) {
9635         outs() << "     flavor i386_THREAD_STATE\n";
9636         if (count == MachO::x86_THREAD_STATE32_COUNT)
9637           outs() << "      count i386_THREAD_STATE_COUNT\n";
9638         else
9639           outs() << "      count " << count
9640                  << " (not x86_THREAD_STATE32_COUNT)\n";
9641         MachO::x86_thread_state32_t cpu32;
9642         left = end - begin;
9643         if (left >= sizeof(MachO::x86_thread_state32_t)) {
9644           memcpy(&cpu32, begin, sizeof(MachO::x86_thread_state32_t));
9645           begin += sizeof(MachO::x86_thread_state32_t);
9646         } else {
9647           memset(&cpu32, '\0', sizeof(MachO::x86_thread_state32_t));
9648           memcpy(&cpu32, begin, left);
9649           begin += left;
9650         }
9651         if (isLittleEndian != sys::IsLittleEndianHost)
9652           swapStruct(cpu32);
9653         Print_x86_thread_state32_t(cpu32);
9654       } else if (flavor == MachO::x86_THREAD_STATE) {
9655         outs() << "     flavor x86_THREAD_STATE\n";
9656         if (count == MachO::x86_THREAD_STATE_COUNT)
9657           outs() << "      count x86_THREAD_STATE_COUNT\n";
9658         else
9659           outs() << "      count " << count
9660                  << " (not x86_THREAD_STATE_COUNT)\n";
9661         struct MachO::x86_thread_state_t ts;
9662         left = end - begin;
9663         if (left >= sizeof(MachO::x86_thread_state_t)) {
9664           memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
9665           begin += sizeof(MachO::x86_thread_state_t);
9666         } else {
9667           memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
9668           memcpy(&ts, begin, left);
9669           begin += left;
9670         }
9671         if (isLittleEndian != sys::IsLittleEndianHost)
9672           swapStruct(ts);
9673         if (ts.tsh.flavor == MachO::x86_THREAD_STATE32) {
9674           outs() << "\t    tsh.flavor x86_THREAD_STATE32 ";
9675           if (ts.tsh.count == MachO::x86_THREAD_STATE32_COUNT)
9676             outs() << "tsh.count x86_THREAD_STATE32_COUNT\n";
9677           else
9678             outs() << "tsh.count " << ts.tsh.count
9679                    << " (not x86_THREAD_STATE32_COUNT\n";
9680           Print_x86_thread_state32_t(ts.uts.ts32);
9681         } else {
9682           outs() << "\t    tsh.flavor " << ts.tsh.flavor << "  tsh.count "
9683                  << ts.tsh.count << "\n";
9684         }
9685       } else {
9686         outs() << "     flavor " << flavor << " (unknown)\n";
9687         outs() << "      count " << count << "\n";
9688         outs() << "      state (unknown)\n";
9689         begin += count * sizeof(uint32_t);
9690       }
9691     }
9692   } else if (cputype == MachO::CPU_TYPE_X86_64) {
9693     while (begin < end) {
9694       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9695         memcpy((char *)&flavor, begin, sizeof(uint32_t));
9696         begin += sizeof(uint32_t);
9697       } else {
9698         flavor = 0;
9699         begin = end;
9700       }
9701       if (isLittleEndian != sys::IsLittleEndianHost)
9702         sys::swapByteOrder(flavor);
9703       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9704         memcpy((char *)&count, begin, sizeof(uint32_t));
9705         begin += sizeof(uint32_t);
9706       } else {
9707         count = 0;
9708         begin = end;
9709       }
9710       if (isLittleEndian != sys::IsLittleEndianHost)
9711         sys::swapByteOrder(count);
9712       if (flavor == MachO::x86_THREAD_STATE64) {
9713         outs() << "     flavor x86_THREAD_STATE64\n";
9714         if (count == MachO::x86_THREAD_STATE64_COUNT)
9715           outs() << "      count x86_THREAD_STATE64_COUNT\n";
9716         else
9717           outs() << "      count " << count
9718                  << " (not x86_THREAD_STATE64_COUNT)\n";
9719         MachO::x86_thread_state64_t cpu64;
9720         left = end - begin;
9721         if (left >= sizeof(MachO::x86_thread_state64_t)) {
9722           memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
9723           begin += sizeof(MachO::x86_thread_state64_t);
9724         } else {
9725           memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
9726           memcpy(&cpu64, begin, left);
9727           begin += left;
9728         }
9729         if (isLittleEndian != sys::IsLittleEndianHost)
9730           swapStruct(cpu64);
9731         Print_x86_thread_state64_t(cpu64);
9732       } else if (flavor == MachO::x86_THREAD_STATE) {
9733         outs() << "     flavor x86_THREAD_STATE\n";
9734         if (count == MachO::x86_THREAD_STATE_COUNT)
9735           outs() << "      count x86_THREAD_STATE_COUNT\n";
9736         else
9737           outs() << "      count " << count
9738                  << " (not x86_THREAD_STATE_COUNT)\n";
9739         struct MachO::x86_thread_state_t ts;
9740         left = end - begin;
9741         if (left >= sizeof(MachO::x86_thread_state_t)) {
9742           memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
9743           begin += sizeof(MachO::x86_thread_state_t);
9744         } else {
9745           memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
9746           memcpy(&ts, begin, left);
9747           begin += left;
9748         }
9749         if (isLittleEndian != sys::IsLittleEndianHost)
9750           swapStruct(ts);
9751         if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
9752           outs() << "\t    tsh.flavor x86_THREAD_STATE64 ";
9753           if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
9754             outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
9755           else
9756             outs() << "tsh.count " << ts.tsh.count
9757                    << " (not x86_THREAD_STATE64_COUNT\n";
9758           Print_x86_thread_state64_t(ts.uts.ts64);
9759         } else {
9760           outs() << "\t    tsh.flavor " << ts.tsh.flavor << "  tsh.count "
9761                  << ts.tsh.count << "\n";
9762         }
9763       } else if (flavor == MachO::x86_FLOAT_STATE) {
9764         outs() << "     flavor x86_FLOAT_STATE\n";
9765         if (count == MachO::x86_FLOAT_STATE_COUNT)
9766           outs() << "      count x86_FLOAT_STATE_COUNT\n";
9767         else
9768           outs() << "      count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
9769         struct MachO::x86_float_state_t fs;
9770         left = end - begin;
9771         if (left >= sizeof(MachO::x86_float_state_t)) {
9772           memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
9773           begin += sizeof(MachO::x86_float_state_t);
9774         } else {
9775           memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
9776           memcpy(&fs, begin, left);
9777           begin += left;
9778         }
9779         if (isLittleEndian != sys::IsLittleEndianHost)
9780           swapStruct(fs);
9781         if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
9782           outs() << "\t    fsh.flavor x86_FLOAT_STATE64 ";
9783           if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
9784             outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
9785           else
9786             outs() << "fsh.count " << fs.fsh.count
9787                    << " (not x86_FLOAT_STATE64_COUNT\n";
9788           Print_x86_float_state_t(fs.ufs.fs64);
9789         } else {
9790           outs() << "\t    fsh.flavor " << fs.fsh.flavor << "  fsh.count "
9791                  << fs.fsh.count << "\n";
9792         }
9793       } else if (flavor == MachO::x86_EXCEPTION_STATE) {
9794         outs() << "     flavor x86_EXCEPTION_STATE\n";
9795         if (count == MachO::x86_EXCEPTION_STATE_COUNT)
9796           outs() << "      count x86_EXCEPTION_STATE_COUNT\n";
9797         else
9798           outs() << "      count " << count
9799                  << " (not x86_EXCEPTION_STATE_COUNT)\n";
9800         struct MachO::x86_exception_state_t es;
9801         left = end - begin;
9802         if (left >= sizeof(MachO::x86_exception_state_t)) {
9803           memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
9804           begin += sizeof(MachO::x86_exception_state_t);
9805         } else {
9806           memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
9807           memcpy(&es, begin, left);
9808           begin += left;
9809         }
9810         if (isLittleEndian != sys::IsLittleEndianHost)
9811           swapStruct(es);
9812         if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
9813           outs() << "\t    esh.flavor x86_EXCEPTION_STATE64\n";
9814           if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
9815             outs() << "\t    esh.count x86_EXCEPTION_STATE64_COUNT\n";
9816           else
9817             outs() << "\t    esh.count " << es.esh.count
9818                    << " (not x86_EXCEPTION_STATE64_COUNT\n";
9819           Print_x86_exception_state_t(es.ues.es64);
9820         } else {
9821           outs() << "\t    esh.flavor " << es.esh.flavor << "  esh.count "
9822                  << es.esh.count << "\n";
9823         }
9824       } else if (flavor == MachO::x86_EXCEPTION_STATE64) {
9825         outs() << "     flavor x86_EXCEPTION_STATE64\n";
9826         if (count == MachO::x86_EXCEPTION_STATE64_COUNT)
9827           outs() << "      count x86_EXCEPTION_STATE64_COUNT\n";
9828         else
9829           outs() << "      count " << count
9830                  << " (not x86_EXCEPTION_STATE64_COUNT)\n";
9831         struct MachO::x86_exception_state64_t es64;
9832         left = end - begin;
9833         if (left >= sizeof(MachO::x86_exception_state64_t)) {
9834           memcpy(&es64, begin, sizeof(MachO::x86_exception_state64_t));
9835           begin += sizeof(MachO::x86_exception_state64_t);
9836         } else {
9837           memset(&es64, '\0', sizeof(MachO::x86_exception_state64_t));
9838           memcpy(&es64, begin, left);
9839           begin += left;
9840         }
9841         if (isLittleEndian != sys::IsLittleEndianHost)
9842           swapStruct(es64);
9843         Print_x86_exception_state_t(es64);
9844       } else {
9845         outs() << "     flavor " << flavor << " (unknown)\n";
9846         outs() << "      count " << count << "\n";
9847         outs() << "      state (unknown)\n";
9848         begin += count * sizeof(uint32_t);
9849       }
9850     }
9851   } else if (cputype == MachO::CPU_TYPE_ARM) {
9852     while (begin < end) {
9853       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9854         memcpy((char *)&flavor, begin, sizeof(uint32_t));
9855         begin += sizeof(uint32_t);
9856       } else {
9857         flavor = 0;
9858         begin = end;
9859       }
9860       if (isLittleEndian != sys::IsLittleEndianHost)
9861         sys::swapByteOrder(flavor);
9862       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9863         memcpy((char *)&count, begin, sizeof(uint32_t));
9864         begin += sizeof(uint32_t);
9865       } else {
9866         count = 0;
9867         begin = end;
9868       }
9869       if (isLittleEndian != sys::IsLittleEndianHost)
9870         sys::swapByteOrder(count);
9871       if (flavor == MachO::ARM_THREAD_STATE) {
9872         outs() << "     flavor ARM_THREAD_STATE\n";
9873         if (count == MachO::ARM_THREAD_STATE_COUNT)
9874           outs() << "      count ARM_THREAD_STATE_COUNT\n";
9875         else
9876           outs() << "      count " << count
9877                  << " (not ARM_THREAD_STATE_COUNT)\n";
9878         MachO::arm_thread_state32_t cpu32;
9879         left = end - begin;
9880         if (left >= sizeof(MachO::arm_thread_state32_t)) {
9881           memcpy(&cpu32, begin, sizeof(MachO::arm_thread_state32_t));
9882           begin += sizeof(MachO::arm_thread_state32_t);
9883         } else {
9884           memset(&cpu32, '\0', sizeof(MachO::arm_thread_state32_t));
9885           memcpy(&cpu32, begin, left);
9886           begin += left;
9887         }
9888         if (isLittleEndian != sys::IsLittleEndianHost)
9889           swapStruct(cpu32);
9890         Print_arm_thread_state32_t(cpu32);
9891       } else {
9892         outs() << "     flavor " << flavor << " (unknown)\n";
9893         outs() << "      count " << count << "\n";
9894         outs() << "      state (unknown)\n";
9895         begin += count * sizeof(uint32_t);
9896       }
9897     }
9898   } else if (cputype == MachO::CPU_TYPE_ARM64 ||
9899              cputype == MachO::CPU_TYPE_ARM64_32) {
9900     while (begin < end) {
9901       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9902         memcpy((char *)&flavor, begin, sizeof(uint32_t));
9903         begin += sizeof(uint32_t);
9904       } else {
9905         flavor = 0;
9906         begin = end;
9907       }
9908       if (isLittleEndian != sys::IsLittleEndianHost)
9909         sys::swapByteOrder(flavor);
9910       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9911         memcpy((char *)&count, begin, sizeof(uint32_t));
9912         begin += sizeof(uint32_t);
9913       } else {
9914         count = 0;
9915         begin = end;
9916       }
9917       if (isLittleEndian != sys::IsLittleEndianHost)
9918         sys::swapByteOrder(count);
9919       if (flavor == MachO::ARM_THREAD_STATE64) {
9920         outs() << "     flavor ARM_THREAD_STATE64\n";
9921         if (count == MachO::ARM_THREAD_STATE64_COUNT)
9922           outs() << "      count ARM_THREAD_STATE64_COUNT\n";
9923         else
9924           outs() << "      count " << count
9925                  << " (not ARM_THREAD_STATE64_COUNT)\n";
9926         MachO::arm_thread_state64_t cpu64;
9927         left = end - begin;
9928         if (left >= sizeof(MachO::arm_thread_state64_t)) {
9929           memcpy(&cpu64, begin, sizeof(MachO::arm_thread_state64_t));
9930           begin += sizeof(MachO::arm_thread_state64_t);
9931         } else {
9932           memset(&cpu64, '\0', sizeof(MachO::arm_thread_state64_t));
9933           memcpy(&cpu64, begin, left);
9934           begin += left;
9935         }
9936         if (isLittleEndian != sys::IsLittleEndianHost)
9937           swapStruct(cpu64);
9938         Print_arm_thread_state64_t(cpu64);
9939       } else {
9940         outs() << "     flavor " << flavor << " (unknown)\n";
9941         outs() << "      count " << count << "\n";
9942         outs() << "      state (unknown)\n";
9943         begin += count * sizeof(uint32_t);
9944       }
9945     }
9946   } else {
9947     while (begin < end) {
9948       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9949         memcpy((char *)&flavor, begin, sizeof(uint32_t));
9950         begin += sizeof(uint32_t);
9951       } else {
9952         flavor = 0;
9953         begin = end;
9954       }
9955       if (isLittleEndian != sys::IsLittleEndianHost)
9956         sys::swapByteOrder(flavor);
9957       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9958         memcpy((char *)&count, begin, sizeof(uint32_t));
9959         begin += sizeof(uint32_t);
9960       } else {
9961         count = 0;
9962         begin = end;
9963       }
9964       if (isLittleEndian != sys::IsLittleEndianHost)
9965         sys::swapByteOrder(count);
9966       outs() << "     flavor " << flavor << "\n";
9967       outs() << "      count " << count << "\n";
9968       outs() << "      state (Unknown cputype/cpusubtype)\n";
9969       begin += count * sizeof(uint32_t);
9970     }
9971   }
9972 }
9973 
9974 static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
9975   if (dl.cmd == MachO::LC_ID_DYLIB)
9976     outs() << "          cmd LC_ID_DYLIB\n";
9977   else if (dl.cmd == MachO::LC_LOAD_DYLIB)
9978     outs() << "          cmd LC_LOAD_DYLIB\n";
9979   else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
9980     outs() << "          cmd LC_LOAD_WEAK_DYLIB\n";
9981   else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
9982     outs() << "          cmd LC_REEXPORT_DYLIB\n";
9983   else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
9984     outs() << "          cmd LC_LAZY_LOAD_DYLIB\n";
9985   else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
9986     outs() << "          cmd LC_LOAD_UPWARD_DYLIB\n";
9987   else
9988     outs() << "          cmd " << dl.cmd << " (unknown)\n";
9989   outs() << "      cmdsize " << dl.cmdsize;
9990   if (dl.cmdsize < sizeof(struct MachO::dylib_command))
9991     outs() << " Incorrect size\n";
9992   else
9993     outs() << "\n";
9994   if (dl.dylib.name < dl.cmdsize) {
9995     const char *P = (const char *)(Ptr) + dl.dylib.name;
9996     outs() << "         name " << P << " (offset " << dl.dylib.name << ")\n";
9997   } else {
9998     outs() << "         name ?(bad offset " << dl.dylib.name << ")\n";
9999   }
10000   outs() << "   time stamp " << dl.dylib.timestamp << " ";
10001   time_t t = dl.dylib.timestamp;
10002   outs() << ctime(&t);
10003   outs() << "      current version ";
10004   if (dl.dylib.current_version == 0xffffffff)
10005     outs() << "n/a\n";
10006   else
10007     outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
10008            << ((dl.dylib.current_version >> 8) & 0xff) << "."
10009            << (dl.dylib.current_version & 0xff) << "\n";
10010   outs() << "compatibility version ";
10011   if (dl.dylib.compatibility_version == 0xffffffff)
10012     outs() << "n/a\n";
10013   else
10014     outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
10015            << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
10016            << (dl.dylib.compatibility_version & 0xff) << "\n";
10017 }
10018 
10019 static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
10020                                      uint32_t object_size) {
10021   if (ld.cmd == MachO::LC_CODE_SIGNATURE)
10022     outs() << "      cmd LC_CODE_SIGNATURE\n";
10023   else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
10024     outs() << "      cmd LC_SEGMENT_SPLIT_INFO\n";
10025   else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
10026     outs() << "      cmd LC_FUNCTION_STARTS\n";
10027   else if (ld.cmd == MachO::LC_DATA_IN_CODE)
10028     outs() << "      cmd LC_DATA_IN_CODE\n";
10029   else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
10030     outs() << "      cmd LC_DYLIB_CODE_SIGN_DRS\n";
10031   else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
10032     outs() << "      cmd LC_LINKER_OPTIMIZATION_HINT\n";
10033   else
10034     outs() << "      cmd " << ld.cmd << " (?)\n";
10035   outs() << "  cmdsize " << ld.cmdsize;
10036   if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
10037     outs() << " Incorrect size\n";
10038   else
10039     outs() << "\n";
10040   outs() << "  dataoff " << ld.dataoff;
10041   if (ld.dataoff > object_size)
10042     outs() << " (past end of file)\n";
10043   else
10044     outs() << "\n";
10045   outs() << " datasize " << ld.datasize;
10046   uint64_t big_size = ld.dataoff;
10047   big_size += ld.datasize;
10048   if (big_size > object_size)
10049     outs() << " (past end of file)\n";
10050   else
10051     outs() << "\n";
10052 }
10053 
10054 static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
10055                               uint32_t cputype, bool verbose) {
10056   StringRef Buf = Obj->getData();
10057   unsigned Index = 0;
10058   for (const auto &Command : Obj->load_commands()) {
10059     outs() << "Load command " << Index++ << "\n";
10060     if (Command.C.cmd == MachO::LC_SEGMENT) {
10061       MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
10062       const char *sg_segname = SLC.segname;
10063       PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
10064                           SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
10065                           SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
10066                           verbose);
10067       for (unsigned j = 0; j < SLC.nsects; j++) {
10068         MachO::section S = Obj->getSection(Command, j);
10069         PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
10070                      S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
10071                      SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
10072       }
10073     } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
10074       MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
10075       const char *sg_segname = SLC_64.segname;
10076       PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
10077                           SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
10078                           SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
10079                           SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
10080       for (unsigned j = 0; j < SLC_64.nsects; j++) {
10081         MachO::section_64 S_64 = Obj->getSection64(Command, j);
10082         PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
10083                      S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
10084                      S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
10085                      sg_segname, filetype, Buf.size(), verbose);
10086       }
10087     } else if (Command.C.cmd == MachO::LC_SYMTAB) {
10088       MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
10089       PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
10090     } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
10091       MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
10092       MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
10093       PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
10094                                Obj->is64Bit());
10095     } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
10096                Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
10097       MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
10098       PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
10099     } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
10100                Command.C.cmd == MachO::LC_ID_DYLINKER ||
10101                Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
10102       MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
10103       PrintDyldLoadCommand(Dyld, Command.Ptr);
10104     } else if (Command.C.cmd == MachO::LC_UUID) {
10105       MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
10106       PrintUuidLoadCommand(Uuid);
10107     } else if (Command.C.cmd == MachO::LC_RPATH) {
10108       MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
10109       PrintRpathLoadCommand(Rpath, Command.Ptr);
10110     } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
10111                Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
10112                Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
10113                Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
10114       MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
10115       PrintVersionMinLoadCommand(Vd);
10116     } else if (Command.C.cmd == MachO::LC_NOTE) {
10117       MachO::note_command Nt = Obj->getNoteLoadCommand(Command);
10118       PrintNoteLoadCommand(Nt);
10119     } else if (Command.C.cmd == MachO::LC_BUILD_VERSION) {
10120       MachO::build_version_command Bv =
10121           Obj->getBuildVersionLoadCommand(Command);
10122       PrintBuildVersionLoadCommand(Obj, Bv);
10123     } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
10124       MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
10125       PrintSourceVersionCommand(Sd);
10126     } else if (Command.C.cmd == MachO::LC_MAIN) {
10127       MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
10128       PrintEntryPointCommand(Ep);
10129     } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
10130       MachO::encryption_info_command Ei =
10131           Obj->getEncryptionInfoCommand(Command);
10132       PrintEncryptionInfoCommand(Ei, Buf.size());
10133     } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
10134       MachO::encryption_info_command_64 Ei =
10135           Obj->getEncryptionInfoCommand64(Command);
10136       PrintEncryptionInfoCommand64(Ei, Buf.size());
10137     } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
10138       MachO::linker_option_command Lo =
10139           Obj->getLinkerOptionLoadCommand(Command);
10140       PrintLinkerOptionCommand(Lo, Command.Ptr);
10141     } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
10142       MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
10143       PrintSubFrameworkCommand(Sf, Command.Ptr);
10144     } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
10145       MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
10146       PrintSubUmbrellaCommand(Sf, Command.Ptr);
10147     } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
10148       MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
10149       PrintSubLibraryCommand(Sl, Command.Ptr);
10150     } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
10151       MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
10152       PrintSubClientCommand(Sc, Command.Ptr);
10153     } else if (Command.C.cmd == MachO::LC_ROUTINES) {
10154       MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
10155       PrintRoutinesCommand(Rc);
10156     } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
10157       MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
10158       PrintRoutinesCommand64(Rc);
10159     } else if (Command.C.cmd == MachO::LC_THREAD ||
10160                Command.C.cmd == MachO::LC_UNIXTHREAD) {
10161       MachO::thread_command Tc = Obj->getThreadCommand(Command);
10162       PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
10163     } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
10164                Command.C.cmd == MachO::LC_ID_DYLIB ||
10165                Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
10166                Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
10167                Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
10168                Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
10169       MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
10170       PrintDylibCommand(Dl, Command.Ptr);
10171     } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
10172                Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
10173                Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
10174                Command.C.cmd == MachO::LC_DATA_IN_CODE ||
10175                Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
10176                Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
10177       MachO::linkedit_data_command Ld =
10178           Obj->getLinkeditDataLoadCommand(Command);
10179       PrintLinkEditDataCommand(Ld, Buf.size());
10180     } else {
10181       outs() << "      cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
10182              << ")\n";
10183       outs() << "  cmdsize " << Command.C.cmdsize << "\n";
10184       // TODO: get and print the raw bytes of the load command.
10185     }
10186     // TODO: print all the other kinds of load commands.
10187   }
10188 }
10189 
10190 static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
10191   if (Obj->is64Bit()) {
10192     MachO::mach_header_64 H_64;
10193     H_64 = Obj->getHeader64();
10194     PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
10195                     H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
10196   } else {
10197     MachO::mach_header H;
10198     H = Obj->getHeader();
10199     PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
10200                     H.sizeofcmds, H.flags, verbose);
10201   }
10202 }
10203 
10204 void objdump::printMachOFileHeader(const object::ObjectFile *Obj) {
10205   const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
10206   PrintMachHeader(file, !NonVerbose);
10207 }
10208 
10209 void objdump::printMachOLoadCommands(const object::ObjectFile *Obj) {
10210   const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
10211   uint32_t filetype = 0;
10212   uint32_t cputype = 0;
10213   if (file->is64Bit()) {
10214     MachO::mach_header_64 H_64;
10215     H_64 = file->getHeader64();
10216     filetype = H_64.filetype;
10217     cputype = H_64.cputype;
10218   } else {
10219     MachO::mach_header H;
10220     H = file->getHeader();
10221     filetype = H.filetype;
10222     cputype = H.cputype;
10223   }
10224   PrintLoadCommands(file, filetype, cputype, !NonVerbose);
10225 }
10226 
10227 //===----------------------------------------------------------------------===//
10228 // export trie dumping
10229 //===----------------------------------------------------------------------===//
10230 
10231 static void printMachOExportsTrie(const object::MachOObjectFile *Obj) {
10232   uint64_t BaseSegmentAddress = 0;
10233   for (const auto &Command : Obj->load_commands()) {
10234     if (Command.C.cmd == MachO::LC_SEGMENT) {
10235       MachO::segment_command Seg = Obj->getSegmentLoadCommand(Command);
10236       if (Seg.fileoff == 0 && Seg.filesize != 0) {
10237         BaseSegmentAddress = Seg.vmaddr;
10238         break;
10239       }
10240     } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
10241       MachO::segment_command_64 Seg = Obj->getSegment64LoadCommand(Command);
10242       if (Seg.fileoff == 0 && Seg.filesize != 0) {
10243         BaseSegmentAddress = Seg.vmaddr;
10244         break;
10245       }
10246     }
10247   }
10248   Error Err = Error::success();
10249   for (const object::ExportEntry &Entry : Obj->exports(Err)) {
10250     uint64_t Flags = Entry.flags();
10251     bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
10252     bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
10253     bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
10254                         MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
10255     bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
10256                 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
10257     bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
10258     if (ReExport)
10259       outs() << "[re-export] ";
10260     else
10261       outs() << format("0x%08llX  ",
10262                        Entry.address() + BaseSegmentAddress);
10263     outs() << Entry.name();
10264     if (WeakDef || ThreadLocal || Resolver || Abs) {
10265       bool NeedsComma = false;
10266       outs() << " [";
10267       if (WeakDef) {
10268         outs() << "weak_def";
10269         NeedsComma = true;
10270       }
10271       if (ThreadLocal) {
10272         if (NeedsComma)
10273           outs() << ", ";
10274         outs() << "per-thread";
10275         NeedsComma = true;
10276       }
10277       if (Abs) {
10278         if (NeedsComma)
10279           outs() << ", ";
10280         outs() << "absolute";
10281         NeedsComma = true;
10282       }
10283       if (Resolver) {
10284         if (NeedsComma)
10285           outs() << ", ";
10286         outs() << format("resolver=0x%08llX", Entry.other());
10287         NeedsComma = true;
10288       }
10289       outs() << "]";
10290     }
10291     if (ReExport) {
10292       StringRef DylibName = "unknown";
10293       int Ordinal = Entry.other() - 1;
10294       Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
10295       if (Entry.otherName().empty())
10296         outs() << " (from " << DylibName << ")";
10297       else
10298         outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
10299     }
10300     outs() << "\n";
10301   }
10302   if (Err)
10303     reportError(std::move(Err), Obj->getFileName());
10304 }
10305 
10306 //===----------------------------------------------------------------------===//
10307 // rebase table dumping
10308 //===----------------------------------------------------------------------===//
10309 
10310 static void printMachORebaseTable(object::MachOObjectFile *Obj) {
10311   outs() << "segment  section            address     type\n";
10312   Error Err = Error::success();
10313   for (const object::MachORebaseEntry &Entry : Obj->rebaseTable(Err)) {
10314     StringRef SegmentName = Entry.segmentName();
10315     StringRef SectionName = Entry.sectionName();
10316     uint64_t Address = Entry.address();
10317 
10318     // Table lines look like: __DATA  __nl_symbol_ptr  0x0000F00C  pointer
10319     outs() << format("%-8s %-18s 0x%08" PRIX64 "  %s\n",
10320                      SegmentName.str().c_str(), SectionName.str().c_str(),
10321                      Address, Entry.typeName().str().c_str());
10322   }
10323   if (Err)
10324     reportError(std::move(Err), Obj->getFileName());
10325 }
10326 
10327 static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
10328   StringRef DylibName;
10329   switch (Ordinal) {
10330   case MachO::BIND_SPECIAL_DYLIB_SELF:
10331     return "this-image";
10332   case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
10333     return "main-executable";
10334   case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
10335     return "flat-namespace";
10336   default:
10337     if (Ordinal > 0) {
10338       std::error_code EC =
10339           Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
10340       if (EC)
10341         return "<<bad library ordinal>>";
10342       return DylibName;
10343     }
10344   }
10345   return "<<unknown special ordinal>>";
10346 }
10347 
10348 //===----------------------------------------------------------------------===//
10349 // bind table dumping
10350 //===----------------------------------------------------------------------===//
10351 
10352 static void printMachOBindTable(object::MachOObjectFile *Obj) {
10353   // Build table of sections so names can used in final output.
10354   outs() << "segment  section            address    type       "
10355             "addend dylib            symbol\n";
10356   Error Err = Error::success();
10357   for (const object::MachOBindEntry &Entry : Obj->bindTable(Err)) {
10358     StringRef SegmentName = Entry.segmentName();
10359     StringRef SectionName = Entry.sectionName();
10360     uint64_t Address = Entry.address();
10361 
10362     // Table lines look like:
10363     //  __DATA  __got  0x00012010    pointer   0 libSystem ___stack_chk_guard
10364     StringRef Attr;
10365     if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
10366       Attr = " (weak_import)";
10367     outs() << left_justify(SegmentName, 8) << " "
10368            << left_justify(SectionName, 18) << " "
10369            << format_hex(Address, 10, true) << " "
10370            << left_justify(Entry.typeName(), 8) << " "
10371            << format_decimal(Entry.addend(), 8) << " "
10372            << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
10373            << Entry.symbolName() << Attr << "\n";
10374   }
10375   if (Err)
10376     reportError(std::move(Err), Obj->getFileName());
10377 }
10378 
10379 //===----------------------------------------------------------------------===//
10380 // lazy bind table dumping
10381 //===----------------------------------------------------------------------===//
10382 
10383 static void printMachOLazyBindTable(object::MachOObjectFile *Obj) {
10384   outs() << "segment  section            address     "
10385             "dylib            symbol\n";
10386   Error Err = Error::success();
10387   for (const object::MachOBindEntry &Entry : Obj->lazyBindTable(Err)) {
10388     StringRef SegmentName = Entry.segmentName();
10389     StringRef SectionName = Entry.sectionName();
10390     uint64_t Address = Entry.address();
10391 
10392     // Table lines look like:
10393     //  __DATA  __got  0x00012010 libSystem ___stack_chk_guard
10394     outs() << left_justify(SegmentName, 8) << " "
10395            << left_justify(SectionName, 18) << " "
10396            << format_hex(Address, 10, true) << " "
10397            << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
10398            << Entry.symbolName() << "\n";
10399   }
10400   if (Err)
10401     reportError(std::move(Err), Obj->getFileName());
10402 }
10403 
10404 //===----------------------------------------------------------------------===//
10405 // weak bind table dumping
10406 //===----------------------------------------------------------------------===//
10407 
10408 static void printMachOWeakBindTable(object::MachOObjectFile *Obj) {
10409   outs() << "segment  section            address     "
10410             "type       addend   symbol\n";
10411   Error Err = Error::success();
10412   for (const object::MachOBindEntry &Entry : Obj->weakBindTable(Err)) {
10413     // Strong symbols don't have a location to update.
10414     if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
10415       outs() << "                                        strong              "
10416              << Entry.symbolName() << "\n";
10417       continue;
10418     }
10419     StringRef SegmentName = Entry.segmentName();
10420     StringRef SectionName = Entry.sectionName();
10421     uint64_t Address = Entry.address();
10422 
10423     // Table lines look like:
10424     // __DATA  __data  0x00001000  pointer    0   _foo
10425     outs() << left_justify(SegmentName, 8) << " "
10426            << left_justify(SectionName, 18) << " "
10427            << format_hex(Address, 10, true) << " "
10428            << left_justify(Entry.typeName(), 8) << " "
10429            << format_decimal(Entry.addend(), 8) << "   " << Entry.symbolName()
10430            << "\n";
10431   }
10432   if (Err)
10433     reportError(std::move(Err), Obj->getFileName());
10434 }
10435 
10436 // get_dyld_bind_info_symbolname() is used for disassembly and passed an
10437 // address, ReferenceValue, in the Mach-O file and looks in the dyld bind
10438 // information for that address. If the address is found its binding symbol
10439 // name is returned.  If not nullptr is returned.
10440 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
10441                                                  struct DisassembleInfo *info) {
10442   if (info->bindtable == nullptr) {
10443     info->bindtable = std::make_unique<SymbolAddressMap>();
10444     Error Err = Error::success();
10445     for (const object::MachOBindEntry &Entry : info->O->bindTable(Err)) {
10446       uint64_t Address = Entry.address();
10447       StringRef name = Entry.symbolName();
10448       if (!name.empty())
10449         (*info->bindtable)[Address] = name;
10450     }
10451     if (Err)
10452       reportError(std::move(Err), info->O->getFileName());
10453   }
10454   auto name = info->bindtable->lookup(ReferenceValue);
10455   return !name.empty() ? name.data() : nullptr;
10456 }
10457 
10458 void objdump::printLazyBindTable(ObjectFile *o) {
10459   outs() << "Lazy bind table:\n";
10460   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10461     printMachOLazyBindTable(MachO);
10462   else
10463     WithColor::error()
10464         << "This operation is only currently supported "
10465            "for Mach-O executable files.\n";
10466 }
10467 
10468 void objdump::printWeakBindTable(ObjectFile *o) {
10469   outs() << "Weak bind table:\n";
10470   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10471     printMachOWeakBindTable(MachO);
10472   else
10473     WithColor::error()
10474         << "This operation is only currently supported "
10475            "for Mach-O executable files.\n";
10476 }
10477 
10478 void objdump::printExportsTrie(const ObjectFile *o) {
10479   outs() << "Exports trie:\n";
10480   if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10481     printMachOExportsTrie(MachO);
10482   else
10483     WithColor::error()
10484         << "This operation is only currently supported "
10485            "for Mach-O executable files.\n";
10486 }
10487 
10488 void objdump::printRebaseTable(ObjectFile *o) {
10489   outs() << "Rebase table:\n";
10490   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10491     printMachORebaseTable(MachO);
10492   else
10493     WithColor::error()
10494         << "This operation is only currently supported "
10495            "for Mach-O executable files.\n";
10496 }
10497 
10498 void objdump::printBindTable(ObjectFile *o) {
10499   outs() << "Bind table:\n";
10500   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10501     printMachOBindTable(MachO);
10502   else
10503     WithColor::error()
10504         << "This operation is only currently supported "
10505            "for Mach-O executable files.\n";
10506 }
10507