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 "ObjdumpOptID.h"
16 #include "llvm-objdump.h"
17 #include "llvm-c/Disassembler.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/StringExtras.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/MC/TargetRegistry.h"
36 #include "llvm/Object/MachO.h"
37 #include "llvm/Object/MachOUniversal.h"
38 #include "llvm/Option/ArgList.h"
39 #include "llvm/Support/Casting.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/Endian.h"
42 #include "llvm/Support/Format.h"
43 #include "llvm/Support/FormattedStream.h"
44 #include "llvm/Support/GraphWriter.h"
45 #include "llvm/Support/LEB128.h"
46 #include "llvm/Support/MemoryBuffer.h"
47 #include "llvm/Support/TargetSelect.h"
48 #include "llvm/Support/ToolOutputFile.h"
49 #include "llvm/Support/WithColor.h"
50 #include "llvm/Support/raw_ostream.h"
51 #include "llvm/TargetParser/Triple.h"
52 #include <algorithm>
53 #include <cstring>
54 #include <system_error>
55 
56 #ifdef LLVM_HAVE_LIBXAR
57 extern "C" {
58 #include <xar/xar.h>
59 }
60 #endif
61 
62 using namespace llvm;
63 using namespace llvm::object;
64 using namespace llvm::objdump;
65 
66 bool objdump::FirstPrivateHeader;
67 bool objdump::ExportsTrie;
68 bool objdump::Rebase;
69 bool objdump::Rpaths;
70 bool objdump::Bind;
71 bool objdump::LazyBind;
72 bool objdump::WeakBind;
73 static bool UseDbg;
74 static std::string DSYMFile;
75 bool objdump::FullLeadingAddr;
76 bool objdump::LeadingHeaders;
77 bool objdump::UniversalHeaders;
78 static bool ArchiveMemberOffsets;
79 bool objdump::IndirectSymbols;
80 bool objdump::DataInCode;
81 FunctionStartsMode objdump::FunctionStartsType =
82     objdump::FunctionStartsMode::None;
83 bool objdump::LinkOptHints;
84 bool objdump::InfoPlist;
85 bool objdump::ChainedFixups;
86 bool objdump::DyldInfo;
87 bool objdump::DylibsUsed;
88 bool objdump::DylibId;
89 bool objdump::Verbose;
90 bool objdump::ObjcMetaData;
91 std::string objdump::DisSymName;
92 bool objdump::SymbolicOperands;
93 static std::vector<std::string> ArchFlags;
94 
95 static bool ArchAll = false;
96 static std::string ThumbTripleName;
97 
98 static StringRef ordinalName(const object::MachOObjectFile *, int);
99 
100 void objdump::parseMachOOptions(const llvm::opt::InputArgList &InputArgs) {
101   FirstPrivateHeader = InputArgs.hasArg(OBJDUMP_private_header);
102   ExportsTrie = InputArgs.hasArg(OBJDUMP_exports_trie);
103   Rebase = InputArgs.hasArg(OBJDUMP_rebase);
104   Rpaths = InputArgs.hasArg(OBJDUMP_rpaths);
105   Bind = InputArgs.hasArg(OBJDUMP_bind);
106   LazyBind = InputArgs.hasArg(OBJDUMP_lazy_bind);
107   WeakBind = InputArgs.hasArg(OBJDUMP_weak_bind);
108   UseDbg = InputArgs.hasArg(OBJDUMP_g);
109   DSYMFile = InputArgs.getLastArgValue(OBJDUMP_dsym_EQ).str();
110   FullLeadingAddr = InputArgs.hasArg(OBJDUMP_full_leading_addr);
111   LeadingHeaders = !InputArgs.hasArg(OBJDUMP_no_leading_headers);
112   UniversalHeaders = InputArgs.hasArg(OBJDUMP_universal_headers);
113   ArchiveMemberOffsets = InputArgs.hasArg(OBJDUMP_archive_member_offsets);
114   IndirectSymbols = InputArgs.hasArg(OBJDUMP_indirect_symbols);
115   DataInCode = InputArgs.hasArg(OBJDUMP_data_in_code);
116   if (const opt::Arg *A = InputArgs.getLastArg(OBJDUMP_function_starts_EQ)) {
117     FunctionStartsType = StringSwitch<FunctionStartsMode>(A->getValue())
118                              .Case("addrs", FunctionStartsMode::Addrs)
119                              .Case("names", FunctionStartsMode::Names)
120                              .Case("both", FunctionStartsMode::Both)
121                              .Default(FunctionStartsMode::None);
122     if (FunctionStartsType == FunctionStartsMode::None)
123       invalidArgValue(A);
124   }
125   LinkOptHints = InputArgs.hasArg(OBJDUMP_link_opt_hints);
126   InfoPlist = InputArgs.hasArg(OBJDUMP_info_plist);
127   ChainedFixups = InputArgs.hasArg(OBJDUMP_chained_fixups);
128   DyldInfo = InputArgs.hasArg(OBJDUMP_dyld_info);
129   DylibsUsed = InputArgs.hasArg(OBJDUMP_dylibs_used);
130   DylibId = InputArgs.hasArg(OBJDUMP_dylib_id);
131   Verbose = !InputArgs.hasArg(OBJDUMP_non_verbose);
132   ObjcMetaData = InputArgs.hasArg(OBJDUMP_objc_meta_data);
133   DisSymName = InputArgs.getLastArgValue(OBJDUMP_dis_symname).str();
134   SymbolicOperands = !InputArgs.hasArg(OBJDUMP_no_symbolic_operands);
135   ArchFlags = InputArgs.getAllArgValues(OBJDUMP_arch_EQ);
136 }
137 
138 static const Target *GetTarget(const MachOObjectFile *MachOObj,
139                                const char **McpuDefault,
140                                const Target **ThumbTarget) {
141   // Figure out the target triple.
142   Triple TT(TripleName);
143   if (TripleName.empty()) {
144     TT = MachOObj->getArchTriple(McpuDefault);
145     TripleName = TT.str();
146   }
147 
148   if (TT.getArch() == Triple::arm) {
149     // We've inferred a 32-bit ARM target from the object file. All MachO CPUs
150     // that support ARM are also capable of Thumb mode.
151     Triple ThumbTriple = TT;
152     std::string ThumbName = (Twine("thumb") + TT.getArchName().substr(3)).str();
153     ThumbTriple.setArchName(ThumbName);
154     ThumbTripleName = ThumbTriple.str();
155   }
156 
157   // Get the target specific parser.
158   std::string Error;
159   const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
160   if (TheTarget && ThumbTripleName.empty())
161     return TheTarget;
162 
163   *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
164   if (*ThumbTarget)
165     return TheTarget;
166 
167   WithColor::error(errs(), "llvm-objdump") << "unable to get target for '";
168   if (!TheTarget)
169     errs() << TripleName;
170   else
171     errs() << ThumbTripleName;
172   errs() << "', see --version and --triple.\n";
173   return nullptr;
174 }
175 
176 namespace {
177 struct SymbolSorter {
178   bool operator()(const SymbolRef &A, const SymbolRef &B) {
179     Expected<SymbolRef::Type> ATypeOrErr = A.getType();
180     if (!ATypeOrErr)
181       reportError(ATypeOrErr.takeError(), A.getObject()->getFileName());
182     SymbolRef::Type AType = *ATypeOrErr;
183     Expected<SymbolRef::Type> BTypeOrErr = B.getType();
184     if (!BTypeOrErr)
185       reportError(BTypeOrErr.takeError(), B.getObject()->getFileName());
186     SymbolRef::Type BType = *BTypeOrErr;
187     uint64_t AAddr =
188         (AType != SymbolRef::ST_Function) ? 0 : cantFail(A.getValue());
189     uint64_t BAddr =
190         (BType != SymbolRef::ST_Function) ? 0 : cantFail(B.getValue());
191     return AAddr < BAddr;
192   }
193 };
194 
195 class MachODumper : public Dumper {
196   const object::MachOObjectFile &Obj;
197 
198 public:
199   MachODumper(const object::MachOObjectFile &O) : Dumper(O), Obj(O) {}
200   void printPrivateHeaders(bool OnlyFirst) override;
201 };
202 } // namespace
203 
204 std::unique_ptr<Dumper>
205 objdump::createMachODumper(const object::MachOObjectFile &Obj) {
206   return std::make_unique<MachODumper>(Obj);
207 }
208 
209 // Types for the storted data in code table that is built before disassembly
210 // and the predicate function to sort them.
211 typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
212 typedef std::vector<DiceTableEntry> DiceTable;
213 typedef DiceTable::iterator dice_table_iterator;
214 
215 #ifdef LLVM_HAVE_LIBXAR
216 namespace {
217 struct ScopedXarFile {
218   xar_t xar;
219   ScopedXarFile(const char *filename, int32_t flags) {
220 #pragma clang diagnostic push
221 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
222     xar = xar_open(filename, flags);
223 #pragma clang diagnostic pop
224   }
225   ~ScopedXarFile() {
226     if (xar)
227       xar_close(xar);
228   }
229   ScopedXarFile(const ScopedXarFile &) = delete;
230   ScopedXarFile &operator=(const ScopedXarFile &) = delete;
231   operator xar_t() { return xar; }
232 };
233 
234 struct ScopedXarIter {
235   xar_iter_t iter;
236   ScopedXarIter() : iter(xar_iter_new()) {}
237   ~ScopedXarIter() {
238     if (iter)
239       xar_iter_free(iter);
240   }
241   ScopedXarIter(const ScopedXarIter &) = delete;
242   ScopedXarIter &operator=(const ScopedXarIter &) = delete;
243   operator xar_iter_t() { return iter; }
244 };
245 } // namespace
246 #endif // defined(LLVM_HAVE_LIBXAR)
247 
248 // This is used to search for a data in code table entry for the PC being
249 // disassembled.  The j parameter has the PC in j.first.  A single data in code
250 // table entry can cover many bytes for each of its Kind's.  So if the offset,
251 // aka the i.first value, of the data in code table entry plus its Length
252 // covers the PC being searched for this will return true.  If not it will
253 // return false.
254 static bool compareDiceTableEntries(const DiceTableEntry &i,
255                                     const DiceTableEntry &j) {
256   uint16_t Length;
257   i.second.getLength(Length);
258 
259   return j.first >= i.first && j.first < i.first + Length;
260 }
261 
262 static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
263                                unsigned short Kind) {
264   uint32_t Value, Size = 1;
265 
266   switch (Kind) {
267   default:
268   case MachO::DICE_KIND_DATA:
269     if (Length >= 4) {
270       if (ShowRawInsn)
271         dumpBytes(ArrayRef(bytes, 4), outs());
272       Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
273       outs() << "\t.long " << Value;
274       Size = 4;
275     } else if (Length >= 2) {
276       if (ShowRawInsn)
277         dumpBytes(ArrayRef(bytes, 2), outs());
278       Value = bytes[1] << 8 | bytes[0];
279       outs() << "\t.short " << Value;
280       Size = 2;
281     } else {
282       if (ShowRawInsn)
283         dumpBytes(ArrayRef(bytes, 2), outs());
284       Value = bytes[0];
285       outs() << "\t.byte " << Value;
286       Size = 1;
287     }
288     if (Kind == MachO::DICE_KIND_DATA)
289       outs() << "\t@ KIND_DATA\n";
290     else
291       outs() << "\t@ data in code kind = " << Kind << "\n";
292     break;
293   case MachO::DICE_KIND_JUMP_TABLE8:
294     if (ShowRawInsn)
295       dumpBytes(ArrayRef(bytes, 1), outs());
296     Value = bytes[0];
297     outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
298     Size = 1;
299     break;
300   case MachO::DICE_KIND_JUMP_TABLE16:
301     if (ShowRawInsn)
302       dumpBytes(ArrayRef(bytes, 2), outs());
303     Value = bytes[1] << 8 | bytes[0];
304     outs() << "\t.short " << format("%5u", Value & 0xffff)
305            << "\t@ KIND_JUMP_TABLE16\n";
306     Size = 2;
307     break;
308   case MachO::DICE_KIND_JUMP_TABLE32:
309   case MachO::DICE_KIND_ABS_JUMP_TABLE32:
310     if (ShowRawInsn)
311       dumpBytes(ArrayRef(bytes, 4), outs());
312     Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
313     outs() << "\t.long " << Value;
314     if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
315       outs() << "\t@ KIND_JUMP_TABLE32\n";
316     else
317       outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
318     Size = 4;
319     break;
320   }
321   return Size;
322 }
323 
324 static void getSectionsAndSymbols(MachOObjectFile *MachOObj,
325                                   std::vector<SectionRef> &Sections,
326                                   std::vector<SymbolRef> &Symbols,
327                                   SmallVectorImpl<uint64_t> &FoundFns,
328                                   uint64_t &BaseSegmentAddress) {
329   const StringRef FileName = MachOObj->getFileName();
330   for (const SymbolRef &Symbol : MachOObj->symbols()) {
331     StringRef SymName = unwrapOrError(Symbol.getName(), FileName);
332     if (!SymName.startswith("ltmp"))
333       Symbols.push_back(Symbol);
334   }
335 
336   append_range(Sections, MachOObj->sections());
337 
338   bool BaseSegmentAddressSet = false;
339   for (const auto &Command : MachOObj->load_commands()) {
340     if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
341       // We found a function starts segment, parse the addresses for later
342       // consumption.
343       MachO::linkedit_data_command LLC =
344           MachOObj->getLinkeditDataLoadCommand(Command);
345 
346       MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
347     } else if (Command.C.cmd == MachO::LC_SEGMENT) {
348       MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
349       StringRef SegName = SLC.segname;
350       if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
351         BaseSegmentAddressSet = true;
352         BaseSegmentAddress = SLC.vmaddr;
353       }
354     } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
355       MachO::segment_command_64 SLC = MachOObj->getSegment64LoadCommand(Command);
356       StringRef SegName = SLC.segname;
357       if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
358         BaseSegmentAddressSet = true;
359         BaseSegmentAddress = SLC.vmaddr;
360       }
361     }
362   }
363 }
364 
365 static bool DumpAndSkipDataInCode(uint64_t PC, const uint8_t *bytes,
366                                  DiceTable &Dices, uint64_t &InstSize) {
367   // Check the data in code table here to see if this is data not an
368   // instruction to be disassembled.
369   DiceTable Dice;
370   Dice.push_back(std::make_pair(PC, DiceRef()));
371   dice_table_iterator DTI =
372       std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
373                   compareDiceTableEntries);
374   if (DTI != Dices.end()) {
375     uint16_t Length;
376     DTI->second.getLength(Length);
377     uint16_t Kind;
378     DTI->second.getKind(Kind);
379     InstSize = DumpDataInCode(bytes, Length, Kind);
380     if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
381         (PC == (DTI->first + Length - 1)) && (Length & 1))
382       InstSize++;
383     return true;
384   }
385   return false;
386 }
387 
388 static void printRelocationTargetName(const MachOObjectFile *O,
389                                       const MachO::any_relocation_info &RE,
390                                       raw_string_ostream &Fmt) {
391   // Target of a scattered relocation is an address.  In the interest of
392   // generating pretty output, scan through the symbol table looking for a
393   // symbol that aligns with that address.  If we find one, print it.
394   // Otherwise, we just print the hex address of the target.
395   const StringRef FileName = O->getFileName();
396   if (O->isRelocationScattered(RE)) {
397     uint32_t Val = O->getPlainRelocationSymbolNum(RE);
398 
399     for (const SymbolRef &Symbol : O->symbols()) {
400       uint64_t Addr = unwrapOrError(Symbol.getAddress(), FileName);
401       if (Addr != Val)
402         continue;
403       Fmt << unwrapOrError(Symbol.getName(), FileName);
404       return;
405     }
406 
407     // If we couldn't find a symbol that this relocation refers to, try
408     // to find a section beginning instead.
409     for (const SectionRef &Section : ToolSectionFilter(*O)) {
410       uint64_t Addr = Section.getAddress();
411       if (Addr != Val)
412         continue;
413       StringRef NameOrErr = unwrapOrError(Section.getName(), O->getFileName());
414       Fmt << NameOrErr;
415       return;
416     }
417 
418     Fmt << format("0x%x", Val);
419     return;
420   }
421 
422   StringRef S;
423   bool isExtern = O->getPlainRelocationExternal(RE);
424   uint64_t Val = O->getPlainRelocationSymbolNum(RE);
425 
426   if (O->getAnyRelocationType(RE) == MachO::ARM64_RELOC_ADDEND &&
427       (O->getArch() == Triple::aarch64 || O->getArch() == Triple::aarch64_be)) {
428     Fmt << format("0x%0" PRIx64, Val);
429     return;
430   }
431 
432   if (isExtern) {
433     symbol_iterator SI = O->symbol_begin();
434     std::advance(SI, Val);
435     S = unwrapOrError(SI->getName(), FileName);
436   } else {
437     section_iterator SI = O->section_begin();
438     // Adjust for the fact that sections are 1-indexed.
439     if (Val == 0) {
440       Fmt << "0 (?,?)";
441       return;
442     }
443     uint32_t I = Val - 1;
444     while (I != 0 && SI != O->section_end()) {
445       --I;
446       std::advance(SI, 1);
447     }
448     if (SI == O->section_end()) {
449       Fmt << Val << " (?,?)";
450     } else {
451       if (Expected<StringRef> NameOrErr = SI->getName())
452         S = *NameOrErr;
453       else
454         consumeError(NameOrErr.takeError());
455     }
456   }
457 
458   Fmt << S;
459 }
460 
461 Error objdump::getMachORelocationValueString(const MachOObjectFile *Obj,
462                                              const RelocationRef &RelRef,
463                                              SmallVectorImpl<char> &Result) {
464   DataRefImpl Rel = RelRef.getRawDataRefImpl();
465   MachO::any_relocation_info RE = Obj->getRelocation(Rel);
466 
467   unsigned Arch = Obj->getArch();
468 
469   std::string FmtBuf;
470   raw_string_ostream Fmt(FmtBuf);
471   unsigned Type = Obj->getAnyRelocationType(RE);
472   bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
473 
474   // Determine any addends that should be displayed with the relocation.
475   // These require decoding the relocation type, which is triple-specific.
476 
477   // X86_64 has entirely custom relocation types.
478   if (Arch == Triple::x86_64) {
479     switch (Type) {
480     case MachO::X86_64_RELOC_GOT_LOAD:
481     case MachO::X86_64_RELOC_GOT: {
482       printRelocationTargetName(Obj, RE, Fmt);
483       Fmt << "@GOT";
484       if (IsPCRel)
485         Fmt << "PCREL";
486       break;
487     }
488     case MachO::X86_64_RELOC_SUBTRACTOR: {
489       DataRefImpl RelNext = Rel;
490       Obj->moveRelocationNext(RelNext);
491       MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
492 
493       // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
494       // X86_64_RELOC_UNSIGNED.
495       // NOTE: Scattered relocations don't exist on x86_64.
496       unsigned RType = Obj->getAnyRelocationType(RENext);
497       if (RType != MachO::X86_64_RELOC_UNSIGNED)
498         reportError(Obj->getFileName(), "Expected X86_64_RELOC_UNSIGNED after "
499                                         "X86_64_RELOC_SUBTRACTOR.");
500 
501       // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
502       // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
503       printRelocationTargetName(Obj, RENext, Fmt);
504       Fmt << "-";
505       printRelocationTargetName(Obj, RE, Fmt);
506       break;
507     }
508     case MachO::X86_64_RELOC_TLV:
509       printRelocationTargetName(Obj, RE, Fmt);
510       Fmt << "@TLV";
511       if (IsPCRel)
512         Fmt << "P";
513       break;
514     case MachO::X86_64_RELOC_SIGNED_1:
515       printRelocationTargetName(Obj, RE, Fmt);
516       Fmt << "-1";
517       break;
518     case MachO::X86_64_RELOC_SIGNED_2:
519       printRelocationTargetName(Obj, RE, Fmt);
520       Fmt << "-2";
521       break;
522     case MachO::X86_64_RELOC_SIGNED_4:
523       printRelocationTargetName(Obj, RE, Fmt);
524       Fmt << "-4";
525       break;
526     default:
527       printRelocationTargetName(Obj, RE, Fmt);
528       break;
529     }
530     // X86 and ARM share some relocation types in common.
531   } else if (Arch == Triple::x86 || Arch == Triple::arm ||
532              Arch == Triple::ppc) {
533     // Generic relocation types...
534     switch (Type) {
535     case MachO::GENERIC_RELOC_PAIR: // prints no info
536       return Error::success();
537     case MachO::GENERIC_RELOC_SECTDIFF: {
538       DataRefImpl RelNext = Rel;
539       Obj->moveRelocationNext(RelNext);
540       MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
541 
542       // X86 sect diff's must be followed by a relocation of type
543       // GENERIC_RELOC_PAIR.
544       unsigned RType = Obj->getAnyRelocationType(RENext);
545 
546       if (RType != MachO::GENERIC_RELOC_PAIR)
547         reportError(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
548                                         "GENERIC_RELOC_SECTDIFF.");
549 
550       printRelocationTargetName(Obj, RE, Fmt);
551       Fmt << "-";
552       printRelocationTargetName(Obj, RENext, Fmt);
553       break;
554     }
555     }
556 
557     if (Arch == Triple::x86 || Arch == Triple::ppc) {
558       switch (Type) {
559       case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
560         DataRefImpl RelNext = Rel;
561         Obj->moveRelocationNext(RelNext);
562         MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
563 
564         // X86 sect diff's must be followed by a relocation of type
565         // GENERIC_RELOC_PAIR.
566         unsigned RType = Obj->getAnyRelocationType(RENext);
567         if (RType != MachO::GENERIC_RELOC_PAIR)
568           reportError(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
569                                           "GENERIC_RELOC_LOCAL_SECTDIFF.");
570 
571         printRelocationTargetName(Obj, RE, Fmt);
572         Fmt << "-";
573         printRelocationTargetName(Obj, RENext, Fmt);
574         break;
575       }
576       case MachO::GENERIC_RELOC_TLV: {
577         printRelocationTargetName(Obj, RE, Fmt);
578         Fmt << "@TLV";
579         if (IsPCRel)
580           Fmt << "P";
581         break;
582       }
583       default:
584         printRelocationTargetName(Obj, RE, Fmt);
585       }
586     } else { // ARM-specific relocations
587       switch (Type) {
588       case MachO::ARM_RELOC_HALF:
589       case MachO::ARM_RELOC_HALF_SECTDIFF: {
590         // Half relocations steal a bit from the length field to encode
591         // whether this is an upper16 or a lower16 relocation.
592         bool isUpper = (Obj->getAnyRelocationLength(RE) & 0x1) == 1;
593 
594         if (isUpper)
595           Fmt << ":upper16:(";
596         else
597           Fmt << ":lower16:(";
598         printRelocationTargetName(Obj, RE, Fmt);
599 
600         DataRefImpl RelNext = Rel;
601         Obj->moveRelocationNext(RelNext);
602         MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
603 
604         // ARM half relocs must be followed by a relocation of type
605         // ARM_RELOC_PAIR.
606         unsigned RType = Obj->getAnyRelocationType(RENext);
607         if (RType != MachO::ARM_RELOC_PAIR)
608           reportError(Obj->getFileName(), "Expected ARM_RELOC_PAIR after "
609                                           "ARM_RELOC_HALF");
610 
611         // NOTE: The half of the target virtual address is stashed in the
612         // address field of the secondary relocation, but we can't reverse
613         // engineer the constant offset from it without decoding the movw/movt
614         // instruction to find the other half in its immediate field.
615 
616         // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
617         // symbol/section pointer of the follow-on relocation.
618         if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
619           Fmt << "-";
620           printRelocationTargetName(Obj, RENext, Fmt);
621         }
622 
623         Fmt << ")";
624         break;
625       }
626       default: {
627         printRelocationTargetName(Obj, RE, Fmt);
628       }
629       }
630     }
631   } else
632     printRelocationTargetName(Obj, RE, Fmt);
633 
634   Fmt.flush();
635   Result.append(FmtBuf.begin(), FmtBuf.end());
636   return Error::success();
637 }
638 
639 static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
640                                      uint32_t n, uint32_t count,
641                                      uint32_t stride, uint64_t addr) {
642   MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
643   uint32_t nindirectsyms = Dysymtab.nindirectsyms;
644   if (n > nindirectsyms)
645     outs() << " (entries start past the end of the indirect symbol "
646               "table) (reserved1 field greater than the table size)";
647   else if (n + count > nindirectsyms)
648     outs() << " (entries extends past the end of the indirect symbol "
649               "table)";
650   outs() << "\n";
651   uint32_t cputype = O->getHeader().cputype;
652   if (cputype & MachO::CPU_ARCH_ABI64)
653     outs() << "address            index";
654   else
655     outs() << "address    index";
656   if (verbose)
657     outs() << " name\n";
658   else
659     outs() << "\n";
660   for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
661     if (cputype & MachO::CPU_ARCH_ABI64)
662       outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
663     else
664       outs() << format("0x%08" PRIx32, (uint32_t)addr + j * stride) << " ";
665     MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
666     uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
667     if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
668       outs() << "LOCAL\n";
669       continue;
670     }
671     if (indirect_symbol ==
672         (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
673       outs() << "LOCAL ABSOLUTE\n";
674       continue;
675     }
676     if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
677       outs() << "ABSOLUTE\n";
678       continue;
679     }
680     outs() << format("%5u ", indirect_symbol);
681     if (verbose) {
682       MachO::symtab_command Symtab = O->getSymtabLoadCommand();
683       if (indirect_symbol < Symtab.nsyms) {
684         symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
685         SymbolRef Symbol = *Sym;
686         outs() << unwrapOrError(Symbol.getName(), O->getFileName());
687       } else {
688         outs() << "?";
689       }
690     }
691     outs() << "\n";
692   }
693 }
694 
695 static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
696   for (const auto &Load : O->load_commands()) {
697     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
698       MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
699       for (unsigned J = 0; J < Seg.nsects; ++J) {
700         MachO::section_64 Sec = O->getSection64(Load, J);
701         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
702         if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
703             section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
704             section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
705             section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
706             section_type == MachO::S_SYMBOL_STUBS) {
707           uint32_t stride;
708           if (section_type == MachO::S_SYMBOL_STUBS)
709             stride = Sec.reserved2;
710           else
711             stride = 8;
712           if (stride == 0) {
713             outs() << "Can't print indirect symbols for (" << Sec.segname << ","
714                    << Sec.sectname << ") "
715                    << "(size of stubs in reserved2 field is zero)\n";
716             continue;
717           }
718           uint32_t count = Sec.size / stride;
719           outs() << "Indirect symbols for (" << Sec.segname << ","
720                  << Sec.sectname << ") " << count << " entries";
721           uint32_t n = Sec.reserved1;
722           PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
723         }
724       }
725     } else if (Load.C.cmd == MachO::LC_SEGMENT) {
726       MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
727       for (unsigned J = 0; J < Seg.nsects; ++J) {
728         MachO::section Sec = O->getSection(Load, J);
729         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
730         if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
731             section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
732             section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
733             section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
734             section_type == MachO::S_SYMBOL_STUBS) {
735           uint32_t stride;
736           if (section_type == MachO::S_SYMBOL_STUBS)
737             stride = Sec.reserved2;
738           else
739             stride = 4;
740           if (stride == 0) {
741             outs() << "Can't print indirect symbols for (" << Sec.segname << ","
742                    << Sec.sectname << ") "
743                    << "(size of stubs in reserved2 field is zero)\n";
744             continue;
745           }
746           uint32_t count = Sec.size / stride;
747           outs() << "Indirect symbols for (" << Sec.segname << ","
748                  << Sec.sectname << ") " << count << " entries";
749           uint32_t n = Sec.reserved1;
750           PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
751         }
752       }
753     }
754   }
755 }
756 
757 static void PrintRType(const uint64_t cputype, const unsigned r_type) {
758   static char const *generic_r_types[] = {
759     "VANILLA ", "PAIR    ", "SECTDIF ", "PBLAPTR ", "LOCSDIF ", "TLV     ",
760     "  6 (?) ", "  7 (?) ", "  8 (?) ", "  9 (?) ", " 10 (?) ", " 11 (?) ",
761     " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
762   };
763   static char const *x86_64_r_types[] = {
764     "UNSIGND ", "SIGNED  ", "BRANCH  ", "GOT_LD  ", "GOT     ", "SUB     ",
765     "SIGNED1 ", "SIGNED2 ", "SIGNED4 ", "TLV     ", " 10 (?) ", " 11 (?) ",
766     " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
767   };
768   static char const *arm_r_types[] = {
769     "VANILLA ", "PAIR    ", "SECTDIFF", "LOCSDIF ", "PBLAPTR ",
770     "BR24    ", "T_BR22  ", "T_BR32  ", "HALF    ", "HALFDIF ",
771     " 10 (?) ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
772   };
773   static char const *arm64_r_types[] = {
774     "UNSIGND ", "SUB     ", "BR26    ", "PAGE21  ", "PAGOF12 ",
775     "GOTLDP  ", "GOTLDPOF", "PTRTGOT ", "TLVLDP  ", "TLVLDPOF",
776     "ADDEND  ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
777   };
778 
779   if (r_type > 0xf){
780     outs() << format("%-7u", r_type) << " ";
781     return;
782   }
783   switch (cputype) {
784     case MachO::CPU_TYPE_I386:
785       outs() << generic_r_types[r_type];
786       break;
787     case MachO::CPU_TYPE_X86_64:
788       outs() << x86_64_r_types[r_type];
789       break;
790     case MachO::CPU_TYPE_ARM:
791       outs() << arm_r_types[r_type];
792       break;
793     case MachO::CPU_TYPE_ARM64:
794     case MachO::CPU_TYPE_ARM64_32:
795       outs() << arm64_r_types[r_type];
796       break;
797     default:
798       outs() << format("%-7u ", r_type);
799   }
800 }
801 
802 static void PrintRLength(const uint64_t cputype, const unsigned r_type,
803                          const unsigned r_length, const bool previous_arm_half){
804   if (cputype == MachO::CPU_TYPE_ARM &&
805       (r_type == MachO::ARM_RELOC_HALF ||
806        r_type == MachO::ARM_RELOC_HALF_SECTDIFF || previous_arm_half == true)) {
807     if ((r_length & 0x1) == 0)
808       outs() << "lo/";
809     else
810       outs() << "hi/";
811     if ((r_length & 0x1) == 0)
812       outs() << "arm ";
813     else
814       outs() << "thm ";
815   } else {
816     switch (r_length) {
817       case 0:
818         outs() << "byte   ";
819         break;
820       case 1:
821         outs() << "word   ";
822         break;
823       case 2:
824         outs() << "long   ";
825         break;
826       case 3:
827         if (cputype == MachO::CPU_TYPE_X86_64)
828           outs() << "quad   ";
829         else
830           outs() << format("?(%2d)  ", r_length);
831         break;
832       default:
833         outs() << format("?(%2d)  ", r_length);
834     }
835   }
836 }
837 
838 static void PrintRelocationEntries(const MachOObjectFile *O,
839                                    const relocation_iterator Begin,
840                                    const relocation_iterator End,
841                                    const uint64_t cputype,
842                                    const bool verbose) {
843   const MachO::symtab_command Symtab = O->getSymtabLoadCommand();
844   bool previous_arm_half = false;
845   bool previous_sectdiff = false;
846   uint32_t sectdiff_r_type = 0;
847 
848   for (relocation_iterator Reloc = Begin; Reloc != End; ++Reloc) {
849     const DataRefImpl Rel = Reloc->getRawDataRefImpl();
850     const MachO::any_relocation_info RE = O->getRelocation(Rel);
851     const unsigned r_type = O->getAnyRelocationType(RE);
852     const bool r_scattered = O->isRelocationScattered(RE);
853     const unsigned r_pcrel = O->getAnyRelocationPCRel(RE);
854     const unsigned r_length = O->getAnyRelocationLength(RE);
855     const unsigned r_address = O->getAnyRelocationAddress(RE);
856     const bool r_extern = (r_scattered ? false :
857                            O->getPlainRelocationExternal(RE));
858     const uint32_t r_value = (r_scattered ?
859                               O->getScatteredRelocationValue(RE) : 0);
860     const unsigned r_symbolnum = (r_scattered ? 0 :
861                                   O->getPlainRelocationSymbolNum(RE));
862 
863     if (r_scattered && cputype != MachO::CPU_TYPE_X86_64) {
864       if (verbose) {
865         // scattered: address
866         if ((cputype == MachO::CPU_TYPE_I386 &&
867              r_type == MachO::GENERIC_RELOC_PAIR) ||
868             (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR))
869           outs() << "         ";
870         else
871           outs() << format("%08x ", (unsigned int)r_address);
872 
873         // scattered: pcrel
874         if (r_pcrel)
875           outs() << "True  ";
876         else
877           outs() << "False ";
878 
879         // scattered: length
880         PrintRLength(cputype, r_type, r_length, previous_arm_half);
881 
882         // scattered: extern & type
883         outs() << "n/a    ";
884         PrintRType(cputype, r_type);
885 
886         // scattered: scattered & value
887         outs() << format("True      0x%08x", (unsigned int)r_value);
888         if (previous_sectdiff == false) {
889           if ((cputype == MachO::CPU_TYPE_ARM &&
890                r_type == MachO::ARM_RELOC_PAIR))
891             outs() << format(" half = 0x%04x ", (unsigned int)r_address);
892         } else if (cputype == MachO::CPU_TYPE_ARM &&
893                    sectdiff_r_type == MachO::ARM_RELOC_HALF_SECTDIFF)
894           outs() << format(" other_half = 0x%04x ", (unsigned int)r_address);
895         if ((cputype == MachO::CPU_TYPE_I386 &&
896              (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
897               r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) ||
898             (cputype == MachO::CPU_TYPE_ARM &&
899              (sectdiff_r_type == MachO::ARM_RELOC_SECTDIFF ||
900               sectdiff_r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
901               sectdiff_r_type == MachO::ARM_RELOC_HALF_SECTDIFF))) {
902           previous_sectdiff = true;
903           sectdiff_r_type = r_type;
904         } else {
905           previous_sectdiff = false;
906           sectdiff_r_type = 0;
907         }
908         if (cputype == MachO::CPU_TYPE_ARM &&
909             (r_type == MachO::ARM_RELOC_HALF ||
910              r_type == MachO::ARM_RELOC_HALF_SECTDIFF))
911           previous_arm_half = true;
912         else
913           previous_arm_half = false;
914         outs() << "\n";
915       }
916       else {
917         // scattered: address pcrel length extern type scattered value
918         outs() << format("%08x %1d     %-2d     n/a    %-7d 1         0x%08x\n",
919                          (unsigned int)r_address, r_pcrel, r_length, r_type,
920                          (unsigned int)r_value);
921       }
922     }
923     else {
924       if (verbose) {
925         // plain: address
926         if (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR)
927           outs() << "         ";
928         else
929           outs() << format("%08x ", (unsigned int)r_address);
930 
931         // plain: pcrel
932         if (r_pcrel)
933           outs() << "True  ";
934         else
935           outs() << "False ";
936 
937         // plain: length
938         PrintRLength(cputype, r_type, r_length, previous_arm_half);
939 
940         if (r_extern) {
941           // plain: extern & type & scattered
942           outs() << "True   ";
943           PrintRType(cputype, r_type);
944           outs() << "False     ";
945 
946           // plain: symbolnum/value
947           if (r_symbolnum > Symtab.nsyms)
948             outs() << format("?(%d)\n", r_symbolnum);
949           else {
950             SymbolRef Symbol = *O->getSymbolByIndex(r_symbolnum);
951             Expected<StringRef> SymNameNext = Symbol.getName();
952             const char *name = nullptr;
953             if (SymNameNext)
954               name = SymNameNext->data();
955             if (name == nullptr)
956               outs() << format("?(%d)\n", r_symbolnum);
957             else
958               outs() << name << "\n";
959           }
960         }
961         else {
962           // plain: extern & type & scattered
963           outs() << "False  ";
964           PrintRType(cputype, r_type);
965           outs() << "False     ";
966 
967           // plain: symbolnum/value
968           if (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR)
969             outs() << format("other_half = 0x%04x\n", (unsigned int)r_address);
970           else if ((cputype == MachO::CPU_TYPE_ARM64 ||
971                     cputype == MachO::CPU_TYPE_ARM64_32) &&
972                    r_type == MachO::ARM64_RELOC_ADDEND)
973             outs() << format("addend = 0x%06x\n", (unsigned int)r_symbolnum);
974           else {
975             outs() << format("%d ", r_symbolnum);
976             if (r_symbolnum == MachO::R_ABS)
977               outs() << "R_ABS\n";
978             else {
979               // in this case, r_symbolnum is actually a 1-based section number
980               uint32_t nsects = O->section_end()->getRawDataRefImpl().d.a;
981               if (r_symbolnum > 0 && r_symbolnum <= nsects) {
982                 object::DataRefImpl DRI;
983                 DRI.d.a = r_symbolnum-1;
984                 StringRef SegName = O->getSectionFinalSegmentName(DRI);
985                 if (Expected<StringRef> NameOrErr = O->getSectionName(DRI))
986                   outs() << "(" << SegName << "," << *NameOrErr << ")\n";
987                 else
988                   outs() << "(?,?)\n";
989               }
990               else {
991                 outs() << "(?,?)\n";
992               }
993             }
994           }
995         }
996         if (cputype == MachO::CPU_TYPE_ARM &&
997             (r_type == MachO::ARM_RELOC_HALF ||
998              r_type == MachO::ARM_RELOC_HALF_SECTDIFF))
999           previous_arm_half = true;
1000         else
1001           previous_arm_half = false;
1002       }
1003       else {
1004         // plain: address pcrel length extern type scattered symbolnum/section
1005         outs() << format("%08x %1d     %-2d     %1d      %-7d 0         %d\n",
1006                          (unsigned int)r_address, r_pcrel, r_length, r_extern,
1007                          r_type, r_symbolnum);
1008       }
1009     }
1010   }
1011 }
1012 
1013 static void PrintRelocations(const MachOObjectFile *O, const bool verbose) {
1014   const uint64_t cputype = O->getHeader().cputype;
1015   const MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
1016   if (Dysymtab.nextrel != 0) {
1017     outs() << "External relocation information " << Dysymtab.nextrel
1018            << " entries";
1019     outs() << "\naddress  pcrel length extern type    scattered "
1020               "symbolnum/value\n";
1021     PrintRelocationEntries(O, O->extrel_begin(), O->extrel_end(), cputype,
1022                            verbose);
1023   }
1024   if (Dysymtab.nlocrel != 0) {
1025     outs() << format("Local relocation information %u entries",
1026                      Dysymtab.nlocrel);
1027     outs() << "\naddress  pcrel length extern type    scattered "
1028               "symbolnum/value\n";
1029     PrintRelocationEntries(O, O->locrel_begin(), O->locrel_end(), cputype,
1030                            verbose);
1031   }
1032   for (const auto &Load : O->load_commands()) {
1033     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
1034       const MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
1035       for (unsigned J = 0; J < Seg.nsects; ++J) {
1036         const MachO::section_64 Sec = O->getSection64(Load, J);
1037         if (Sec.nreloc != 0) {
1038           DataRefImpl DRI;
1039           DRI.d.a = J;
1040           const StringRef SegName = O->getSectionFinalSegmentName(DRI);
1041           if (Expected<StringRef> NameOrErr = O->getSectionName(DRI))
1042             outs() << "Relocation information (" << SegName << "," << *NameOrErr
1043                    << format(") %u entries", Sec.nreloc);
1044           else
1045             outs() << "Relocation information (" << SegName << ",?) "
1046                    << format("%u entries", Sec.nreloc);
1047           outs() << "\naddress  pcrel length extern type    scattered "
1048                     "symbolnum/value\n";
1049           PrintRelocationEntries(O, O->section_rel_begin(DRI),
1050                                  O->section_rel_end(DRI), cputype, verbose);
1051         }
1052       }
1053     } else if (Load.C.cmd == MachO::LC_SEGMENT) {
1054       const MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
1055       for (unsigned J = 0; J < Seg.nsects; ++J) {
1056         const MachO::section Sec = O->getSection(Load, J);
1057         if (Sec.nreloc != 0) {
1058           DataRefImpl DRI;
1059           DRI.d.a = J;
1060           const StringRef SegName = O->getSectionFinalSegmentName(DRI);
1061           if (Expected<StringRef> NameOrErr = O->getSectionName(DRI))
1062             outs() << "Relocation information (" << SegName << "," << *NameOrErr
1063                    << format(") %u entries", Sec.nreloc);
1064           else
1065             outs() << "Relocation information (" << SegName << ",?) "
1066                    << format("%u entries", Sec.nreloc);
1067           outs() << "\naddress  pcrel length extern type    scattered "
1068                     "symbolnum/value\n";
1069           PrintRelocationEntries(O, O->section_rel_begin(DRI),
1070                                  O->section_rel_end(DRI), cputype, verbose);
1071         }
1072       }
1073     }
1074   }
1075 }
1076 
1077 static void PrintFunctionStarts(MachOObjectFile *O) {
1078   uint64_t BaseSegmentAddress = 0;
1079   for (const MachOObjectFile::LoadCommandInfo &Command : O->load_commands()) {
1080     if (Command.C.cmd == MachO::LC_SEGMENT) {
1081       MachO::segment_command SLC = O->getSegmentLoadCommand(Command);
1082       if (StringRef(SLC.segname) == "__TEXT") {
1083         BaseSegmentAddress = SLC.vmaddr;
1084         break;
1085       }
1086     } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
1087       MachO::segment_command_64 SLC = O->getSegment64LoadCommand(Command);
1088       if (StringRef(SLC.segname) == "__TEXT") {
1089         BaseSegmentAddress = SLC.vmaddr;
1090         break;
1091       }
1092     }
1093   }
1094 
1095   SmallVector<uint64_t, 8> FunctionStarts;
1096   for (const MachOObjectFile::LoadCommandInfo &LC : O->load_commands()) {
1097     if (LC.C.cmd == MachO::LC_FUNCTION_STARTS) {
1098       MachO::linkedit_data_command FunctionStartsLC =
1099           O->getLinkeditDataLoadCommand(LC);
1100       O->ReadULEB128s(FunctionStartsLC.dataoff, FunctionStarts);
1101       break;
1102     }
1103   }
1104 
1105   DenseMap<uint64_t, StringRef> SymbolNames;
1106   if (FunctionStartsType == FunctionStartsMode::Names ||
1107       FunctionStartsType == FunctionStartsMode::Both) {
1108     for (SymbolRef Sym : O->symbols()) {
1109       if (Expected<uint64_t> Addr = Sym.getAddress()) {
1110         if (Expected<StringRef> Name = Sym.getName()) {
1111           SymbolNames[*Addr] = *Name;
1112         }
1113       }
1114     }
1115   }
1116 
1117   for (uint64_t S : FunctionStarts) {
1118     uint64_t Addr = BaseSegmentAddress + S;
1119     if (FunctionStartsType == FunctionStartsMode::Names) {
1120       auto It = SymbolNames.find(Addr);
1121       if (It != SymbolNames.end())
1122         outs() << It->second << "\n";
1123     } else {
1124       if (O->is64Bit())
1125         outs() << format("%016" PRIx64, Addr);
1126       else
1127         outs() << format("%08" PRIx32, static_cast<uint32_t>(Addr));
1128 
1129       if (FunctionStartsType == FunctionStartsMode::Both) {
1130         auto It = SymbolNames.find(Addr);
1131         if (It != SymbolNames.end())
1132           outs() << " " << It->second;
1133         else
1134           outs() << " ?";
1135       }
1136       outs() << "\n";
1137     }
1138   }
1139 }
1140 
1141 static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
1142   MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
1143   uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
1144   outs() << "Data in code table (" << nentries << " entries)\n";
1145   outs() << "offset     length kind\n";
1146   for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
1147        ++DI) {
1148     uint32_t Offset;
1149     DI->getOffset(Offset);
1150     outs() << format("0x%08" PRIx32, Offset) << " ";
1151     uint16_t Length;
1152     DI->getLength(Length);
1153     outs() << format("%6u", Length) << " ";
1154     uint16_t Kind;
1155     DI->getKind(Kind);
1156     if (verbose) {
1157       switch (Kind) {
1158       case MachO::DICE_KIND_DATA:
1159         outs() << "DATA";
1160         break;
1161       case MachO::DICE_KIND_JUMP_TABLE8:
1162         outs() << "JUMP_TABLE8";
1163         break;
1164       case MachO::DICE_KIND_JUMP_TABLE16:
1165         outs() << "JUMP_TABLE16";
1166         break;
1167       case MachO::DICE_KIND_JUMP_TABLE32:
1168         outs() << "JUMP_TABLE32";
1169         break;
1170       case MachO::DICE_KIND_ABS_JUMP_TABLE32:
1171         outs() << "ABS_JUMP_TABLE32";
1172         break;
1173       default:
1174         outs() << format("0x%04" PRIx32, Kind);
1175         break;
1176       }
1177     } else
1178       outs() << format("0x%04" PRIx32, Kind);
1179     outs() << "\n";
1180   }
1181 }
1182 
1183 static void PrintLinkOptHints(MachOObjectFile *O) {
1184   MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
1185   const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
1186   uint32_t nloh = LohLC.datasize;
1187   outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
1188   for (uint32_t i = 0; i < nloh;) {
1189     unsigned n;
1190     uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
1191     i += n;
1192     outs() << "    identifier " << identifier << " ";
1193     if (i >= nloh)
1194       return;
1195     switch (identifier) {
1196     case 1:
1197       outs() << "AdrpAdrp\n";
1198       break;
1199     case 2:
1200       outs() << "AdrpLdr\n";
1201       break;
1202     case 3:
1203       outs() << "AdrpAddLdr\n";
1204       break;
1205     case 4:
1206       outs() << "AdrpLdrGotLdr\n";
1207       break;
1208     case 5:
1209       outs() << "AdrpAddStr\n";
1210       break;
1211     case 6:
1212       outs() << "AdrpLdrGotStr\n";
1213       break;
1214     case 7:
1215       outs() << "AdrpAdd\n";
1216       break;
1217     case 8:
1218       outs() << "AdrpLdrGot\n";
1219       break;
1220     default:
1221       outs() << "Unknown identifier value\n";
1222       break;
1223     }
1224     uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
1225     i += n;
1226     outs() << "    narguments " << narguments << "\n";
1227     if (i >= nloh)
1228       return;
1229 
1230     for (uint32_t j = 0; j < narguments; j++) {
1231       uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
1232       i += n;
1233       outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
1234       if (i >= nloh)
1235         return;
1236     }
1237   }
1238 }
1239 
1240 static SmallVector<std::string> GetSegmentNames(object::MachOObjectFile *O) {
1241   SmallVector<std::string> Ret;
1242   for (const MachOObjectFile::LoadCommandInfo &Command : O->load_commands()) {
1243     if (Command.C.cmd == MachO::LC_SEGMENT) {
1244       MachO::segment_command SLC = O->getSegmentLoadCommand(Command);
1245       Ret.push_back(SLC.segname);
1246     } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
1247       MachO::segment_command_64 SLC = O->getSegment64LoadCommand(Command);
1248       Ret.push_back(SLC.segname);
1249     }
1250   }
1251   return Ret;
1252 }
1253 
1254 static void
1255 PrintChainedFixupsHeader(const MachO::dyld_chained_fixups_header &H) {
1256   outs() << "chained fixups header (LC_DYLD_CHAINED_FIXUPS)\n";
1257   outs() << "  fixups_version = " << H.fixups_version << '\n';
1258   outs() << "  starts_offset  = " << H.starts_offset << '\n';
1259   outs() << "  imports_offset = " << H.imports_offset << '\n';
1260   outs() << "  symbols_offset = " << H.symbols_offset << '\n';
1261   outs() << "  imports_count  = " << H.imports_count << '\n';
1262 
1263   outs() << "  imports_format = " << H.imports_format;
1264   switch (H.imports_format) {
1265   case llvm::MachO::DYLD_CHAINED_IMPORT:
1266     outs() << " (DYLD_CHAINED_IMPORT)";
1267     break;
1268   case llvm::MachO::DYLD_CHAINED_IMPORT_ADDEND:
1269     outs() << " (DYLD_CHAINED_IMPORT_ADDEND)";
1270     break;
1271   case llvm::MachO::DYLD_CHAINED_IMPORT_ADDEND64:
1272     outs() << " (DYLD_CHAINED_IMPORT_ADDEND64)";
1273     break;
1274   }
1275   outs() << '\n';
1276 
1277   outs() << "  symbols_format = " << H.symbols_format;
1278   if (H.symbols_format == llvm::MachO::DYLD_CHAINED_SYMBOL_ZLIB)
1279     outs() << " (zlib compressed)";
1280   outs() << '\n';
1281 }
1282 
1283 static constexpr std::array<StringRef, 13> PointerFormats{
1284     "DYLD_CHAINED_PTR_ARM64E",
1285     "DYLD_CHAINED_PTR_64",
1286     "DYLD_CHAINED_PTR_32",
1287     "DYLD_CHAINED_PTR_32_CACHE",
1288     "DYLD_CHAINED_PTR_32_FIRMWARE",
1289     "DYLD_CHAINED_PTR_64_OFFSET",
1290     "DYLD_CHAINED_PTR_ARM64E_KERNEL",
1291     "DYLD_CHAINED_PTR_64_KERNEL_CACHE",
1292     "DYLD_CHAINED_PTR_ARM64E_USERLAND",
1293     "DYLD_CHAINED_PTR_ARM64E_FIRMWARE",
1294     "DYLD_CHAINED_PTR_X86_64_KERNEL_CACHE",
1295     "DYLD_CHAINED_PTR_ARM64E_USERLAND24",
1296 };
1297 
1298 static void PrintChainedFixupsSegment(const ChainedFixupsSegment &Segment,
1299                                       StringRef SegName) {
1300   outs() << "chained starts in segment " << Segment.SegIdx << " (" << SegName
1301          << ")\n";
1302   outs() << "  size = " << Segment.Header.size << '\n';
1303   outs() << "  page_size = " << format("0x%0" PRIx16, Segment.Header.page_size)
1304          << '\n';
1305 
1306   outs() << "  pointer_format = " << Segment.Header.pointer_format;
1307   if ((Segment.Header.pointer_format - 1) <
1308       MachO::DYLD_CHAINED_PTR_ARM64E_USERLAND24)
1309     outs() << " (" << PointerFormats[Segment.Header.pointer_format - 1] << ")";
1310   outs() << '\n';
1311 
1312   outs() << "  segment_offset = "
1313          << format("0x%0" PRIx64, Segment.Header.segment_offset) << '\n';
1314   outs() << "  max_valid_pointer = " << Segment.Header.max_valid_pointer
1315          << '\n';
1316   outs() << "  page_count = " << Segment.Header.page_count << '\n';
1317   for (auto [Index, PageStart] : enumerate(Segment.PageStarts)) {
1318     outs() << "    page_start[" << Index << "] = " << PageStart;
1319     // FIXME: Support DYLD_CHAINED_PTR_START_MULTI (32-bit only)
1320     if (PageStart == MachO::DYLD_CHAINED_PTR_START_NONE)
1321       outs() << " (DYLD_CHAINED_PTR_START_NONE)";
1322     outs() << '\n';
1323   }
1324 }
1325 
1326 static void PrintChainedFixupTarget(ChainedFixupTarget &Target, size_t Idx,
1327                                     int Format, MachOObjectFile *O) {
1328   if (Format == MachO::DYLD_CHAINED_IMPORT)
1329     outs() << "dyld chained import";
1330   else if (Format == MachO::DYLD_CHAINED_IMPORT_ADDEND)
1331     outs() << "dyld chained import addend";
1332   else if (Format == MachO::DYLD_CHAINED_IMPORT_ADDEND64)
1333     outs() << "dyld chained import addend64";
1334   // FIXME: otool prints the encoded value as well.
1335   outs() << '[' << Idx << "]\n";
1336 
1337   outs() << "  lib_ordinal = " << Target.libOrdinal() << " ("
1338          << ordinalName(O, Target.libOrdinal()) << ")\n";
1339   outs() << "  weak_import = " << Target.weakImport() << '\n';
1340   outs() << "  name_offset = " << Target.nameOffset() << " ("
1341          << Target.symbolName() << ")\n";
1342   if (Format != MachO::DYLD_CHAINED_IMPORT)
1343     outs() << "  addend      = " << (int64_t)Target.addend() << '\n';
1344 }
1345 
1346 static void PrintChainedFixups(MachOObjectFile *O) {
1347   // MachOObjectFile::getChainedFixupsHeader() reads LC_DYLD_CHAINED_FIXUPS.
1348   // FIXME: Support chained fixups in __TEXT,__chain_starts section too.
1349   auto ChainedFixupHeader =
1350       unwrapOrError(O->getChainedFixupsHeader(), O->getFileName());
1351   if (!ChainedFixupHeader)
1352     return;
1353 
1354   PrintChainedFixupsHeader(*ChainedFixupHeader);
1355 
1356   auto [SegCount, Segments] =
1357       unwrapOrError(O->getChainedFixupsSegments(), O->getFileName());
1358 
1359   auto SegNames = GetSegmentNames(O);
1360 
1361   size_t StartsIdx = 0;
1362   outs() << "chained starts in image\n";
1363   outs() << "  seg_count = " << SegCount << '\n';
1364   for (size_t I = 0; I < SegCount; ++I) {
1365     uint64_t SegOffset = 0;
1366     if (StartsIdx < Segments.size() && I == Segments[StartsIdx].SegIdx) {
1367       SegOffset = Segments[StartsIdx].Offset;
1368       ++StartsIdx;
1369     }
1370 
1371     outs() << "    seg_offset[" << I << "] = " << SegOffset << " ("
1372            << SegNames[I] << ")\n";
1373   }
1374 
1375   for (const ChainedFixupsSegment &S : Segments)
1376     PrintChainedFixupsSegment(S, SegNames[S.SegIdx]);
1377 
1378   auto FixupTargets =
1379       unwrapOrError(O->getDyldChainedFixupTargets(), O->getFileName());
1380 
1381   uint32_t ImportsFormat = ChainedFixupHeader->imports_format;
1382   for (auto [Idx, Target] : enumerate(FixupTargets))
1383     PrintChainedFixupTarget(Target, Idx, ImportsFormat, O);
1384 }
1385 
1386 static void PrintDyldInfo(MachOObjectFile *O) {
1387   Error Err = Error::success();
1388 
1389   size_t SegmentWidth = strlen("segment");
1390   size_t SectionWidth = strlen("section");
1391   size_t AddressWidth = strlen("address");
1392   size_t AddendWidth = strlen("addend");
1393   size_t DylibWidth = strlen("dylib");
1394   const size_t PointerWidth = 2 + O->getBytesInAddress() * 2;
1395 
1396   auto HexLength = [](uint64_t Num) {
1397     return Num ? (size_t)divideCeil(Log2_64(Num), 4) : 1;
1398   };
1399   for (const object::MachOChainedFixupEntry &Entry : O->fixupTable(Err)) {
1400     SegmentWidth = std::max(SegmentWidth, Entry.segmentName().size());
1401     SectionWidth = std::max(SectionWidth, Entry.sectionName().size());
1402     AddressWidth = std::max(AddressWidth, HexLength(Entry.address()) + 2);
1403     if (Entry.isBind()) {
1404       AddendWidth = std::max(AddendWidth, HexLength(Entry.addend()) + 2);
1405       DylibWidth = std::max(DylibWidth, Entry.symbolName().size());
1406     }
1407   }
1408   // Errors will be handled when printing the table.
1409   if (Err)
1410     consumeError(std::move(Err));
1411 
1412   outs() << "dyld information:\n";
1413   outs() << left_justify("segment", SegmentWidth) << ' '
1414          << left_justify("section", SectionWidth) << ' '
1415          << left_justify("address", AddressWidth) << ' '
1416          << left_justify("pointer", PointerWidth) << " type   "
1417          << left_justify("addend", AddendWidth) << ' '
1418          << left_justify("dylib", DylibWidth) << " symbol/vm address\n";
1419   for (const object::MachOChainedFixupEntry &Entry : O->fixupTable(Err)) {
1420     outs() << left_justify(Entry.segmentName(), SegmentWidth) << ' '
1421            << left_justify(Entry.sectionName(), SectionWidth) << ' ' << "0x"
1422            << left_justify(utohexstr(Entry.address()), AddressWidth - 2) << ' '
1423            << format_hex(Entry.rawValue(), PointerWidth, true) << ' ';
1424     if (Entry.isBind()) {
1425       outs() << "bind   "
1426              << "0x" << left_justify(utohexstr(Entry.addend()), AddendWidth - 2)
1427              << ' ' << left_justify(ordinalName(O, Entry.ordinal()), DylibWidth)
1428              << ' ' << Entry.symbolName();
1429       if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
1430         outs() << " (weak import)";
1431       outs() << '\n';
1432     } else {
1433       assert(Entry.isRebase());
1434       outs() << "rebase";
1435       outs().indent(AddendWidth + DylibWidth + 2);
1436       outs() << format("0x%" PRIX64, Entry.pointerValue()) << '\n';
1437     }
1438   }
1439   if (Err)
1440     reportError(std::move(Err), O->getFileName());
1441 
1442   // TODO: Print opcode-based fixups if the object uses those.
1443 }
1444 
1445 static void PrintDylibs(MachOObjectFile *O, bool JustId) {
1446   unsigned Index = 0;
1447   for (const auto &Load : O->load_commands()) {
1448     if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
1449         (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
1450                      Load.C.cmd == MachO::LC_LOAD_DYLIB ||
1451                      Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
1452                      Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
1453                      Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
1454                      Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
1455       MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
1456       if (dl.dylib.name < dl.cmdsize) {
1457         const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
1458         if (JustId)
1459           outs() << p << "\n";
1460         else {
1461           outs() << "\t" << p;
1462           outs() << " (compatibility version "
1463                  << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
1464                  << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
1465                  << (dl.dylib.compatibility_version & 0xff) << ",";
1466           outs() << " current version "
1467                  << ((dl.dylib.current_version >> 16) & 0xffff) << "."
1468                  << ((dl.dylib.current_version >> 8) & 0xff) << "."
1469                  << (dl.dylib.current_version & 0xff);
1470           if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
1471             outs() << ", weak";
1472           if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
1473             outs() << ", reexport";
1474           if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
1475             outs() << ", upward";
1476           if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
1477             outs() << ", lazy";
1478           outs() << ")\n";
1479         }
1480       } else {
1481         outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
1482         if (Load.C.cmd == MachO::LC_ID_DYLIB)
1483           outs() << "LC_ID_DYLIB ";
1484         else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
1485           outs() << "LC_LOAD_DYLIB ";
1486         else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
1487           outs() << "LC_LOAD_WEAK_DYLIB ";
1488         else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
1489           outs() << "LC_LAZY_LOAD_DYLIB ";
1490         else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
1491           outs() << "LC_REEXPORT_DYLIB ";
1492         else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
1493           outs() << "LC_LOAD_UPWARD_DYLIB ";
1494         else
1495           outs() << "LC_??? ";
1496         outs() << "command " << Index++ << "\n";
1497       }
1498     }
1499   }
1500 }
1501 
1502 static void printRpaths(MachOObjectFile *O) {
1503   for (const auto &Command : O->load_commands()) {
1504     if (Command.C.cmd == MachO::LC_RPATH) {
1505       auto Rpath = O->getRpathCommand(Command);
1506       const char *P = (const char *)(Command.Ptr) + Rpath.path;
1507       outs() << P << "\n";
1508     }
1509   }
1510 }
1511 
1512 typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
1513 
1514 static void CreateSymbolAddressMap(MachOObjectFile *O,
1515                                    SymbolAddressMap *AddrMap) {
1516   // Create a map of symbol addresses to symbol names.
1517   const StringRef FileName = O->getFileName();
1518   for (const SymbolRef &Symbol : O->symbols()) {
1519     SymbolRef::Type ST = unwrapOrError(Symbol.getType(), FileName);
1520     if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
1521         ST == SymbolRef::ST_Other) {
1522       uint64_t Address = cantFail(Symbol.getValue());
1523       StringRef SymName = unwrapOrError(Symbol.getName(), FileName);
1524       if (!SymName.startswith(".objc"))
1525         (*AddrMap)[Address] = SymName;
1526     }
1527   }
1528 }
1529 
1530 // GuessSymbolName is passed the address of what might be a symbol and a
1531 // pointer to the SymbolAddressMap.  It returns the name of a symbol
1532 // with that address or nullptr if no symbol is found with that address.
1533 static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
1534   const char *SymbolName = nullptr;
1535   // A DenseMap can't lookup up some values.
1536   if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
1537     StringRef name = AddrMap->lookup(value);
1538     if (!name.empty())
1539       SymbolName = name.data();
1540   }
1541   return SymbolName;
1542 }
1543 
1544 static void DumpCstringChar(const char c) {
1545   char p[2];
1546   p[0] = c;
1547   p[1] = '\0';
1548   outs().write_escaped(p);
1549 }
1550 
1551 static void DumpCstringSection(MachOObjectFile *O, const char *sect,
1552                                uint32_t sect_size, uint64_t sect_addr,
1553                                bool print_addresses) {
1554   for (uint32_t i = 0; i < sect_size; i++) {
1555     if (print_addresses) {
1556       if (O->is64Bit())
1557         outs() << format("%016" PRIx64, sect_addr + i) << "  ";
1558       else
1559         outs() << format("%08" PRIx64, sect_addr + i) << "  ";
1560     }
1561     for (; i < sect_size && sect[i] != '\0'; i++)
1562       DumpCstringChar(sect[i]);
1563     if (i < sect_size && sect[i] == '\0')
1564       outs() << "\n";
1565   }
1566 }
1567 
1568 static void DumpLiteral4(uint32_t l, float f) {
1569   outs() << format("0x%08" PRIx32, l);
1570   if ((l & 0x7f800000) != 0x7f800000)
1571     outs() << format(" (%.16e)\n", f);
1572   else {
1573     if (l == 0x7f800000)
1574       outs() << " (+Infinity)\n";
1575     else if (l == 0xff800000)
1576       outs() << " (-Infinity)\n";
1577     else if ((l & 0x00400000) == 0x00400000)
1578       outs() << " (non-signaling Not-a-Number)\n";
1579     else
1580       outs() << " (signaling Not-a-Number)\n";
1581   }
1582 }
1583 
1584 static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
1585                                 uint32_t sect_size, uint64_t sect_addr,
1586                                 bool print_addresses) {
1587   for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
1588     if (print_addresses) {
1589       if (O->is64Bit())
1590         outs() << format("%016" PRIx64, sect_addr + i) << "  ";
1591       else
1592         outs() << format("%08" PRIx64, sect_addr + i) << "  ";
1593     }
1594     float f;
1595     memcpy(&f, sect + i, sizeof(float));
1596     if (O->isLittleEndian() != sys::IsLittleEndianHost)
1597       sys::swapByteOrder(f);
1598     uint32_t l;
1599     memcpy(&l, sect + i, sizeof(uint32_t));
1600     if (O->isLittleEndian() != sys::IsLittleEndianHost)
1601       sys::swapByteOrder(l);
1602     DumpLiteral4(l, f);
1603   }
1604 }
1605 
1606 static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
1607                          double d) {
1608   outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
1609   uint32_t Hi, Lo;
1610   Hi = (O->isLittleEndian()) ? l1 : l0;
1611   Lo = (O->isLittleEndian()) ? l0 : l1;
1612 
1613   // Hi is the high word, so this is equivalent to if(isfinite(d))
1614   if ((Hi & 0x7ff00000) != 0x7ff00000)
1615     outs() << format(" (%.16e)\n", d);
1616   else {
1617     if (Hi == 0x7ff00000 && Lo == 0)
1618       outs() << " (+Infinity)\n";
1619     else if (Hi == 0xfff00000 && Lo == 0)
1620       outs() << " (-Infinity)\n";
1621     else if ((Hi & 0x00080000) == 0x00080000)
1622       outs() << " (non-signaling Not-a-Number)\n";
1623     else
1624       outs() << " (signaling Not-a-Number)\n";
1625   }
1626 }
1627 
1628 static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
1629                                 uint32_t sect_size, uint64_t sect_addr,
1630                                 bool print_addresses) {
1631   for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
1632     if (print_addresses) {
1633       if (O->is64Bit())
1634         outs() << format("%016" PRIx64, sect_addr + i) << "  ";
1635       else
1636         outs() << format("%08" PRIx64, sect_addr + i) << "  ";
1637     }
1638     double d;
1639     memcpy(&d, sect + i, sizeof(double));
1640     if (O->isLittleEndian() != sys::IsLittleEndianHost)
1641       sys::swapByteOrder(d);
1642     uint32_t l0, l1;
1643     memcpy(&l0, sect + i, sizeof(uint32_t));
1644     memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
1645     if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1646       sys::swapByteOrder(l0);
1647       sys::swapByteOrder(l1);
1648     }
1649     DumpLiteral8(O, l0, l1, d);
1650   }
1651 }
1652 
1653 static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
1654   outs() << format("0x%08" PRIx32, l0) << " ";
1655   outs() << format("0x%08" PRIx32, l1) << " ";
1656   outs() << format("0x%08" PRIx32, l2) << " ";
1657   outs() << format("0x%08" PRIx32, l3) << "\n";
1658 }
1659 
1660 static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
1661                                  uint32_t sect_size, uint64_t sect_addr,
1662                                  bool print_addresses) {
1663   for (uint32_t i = 0; i < sect_size; i += 16) {
1664     if (print_addresses) {
1665       if (O->is64Bit())
1666         outs() << format("%016" PRIx64, sect_addr + i) << "  ";
1667       else
1668         outs() << format("%08" PRIx64, sect_addr + i) << "  ";
1669     }
1670     uint32_t l0, l1, l2, l3;
1671     memcpy(&l0, sect + i, sizeof(uint32_t));
1672     memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
1673     memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
1674     memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
1675     if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1676       sys::swapByteOrder(l0);
1677       sys::swapByteOrder(l1);
1678       sys::swapByteOrder(l2);
1679       sys::swapByteOrder(l3);
1680     }
1681     DumpLiteral16(l0, l1, l2, l3);
1682   }
1683 }
1684 
1685 static void DumpLiteralPointerSection(MachOObjectFile *O,
1686                                       const SectionRef &Section,
1687                                       const char *sect, uint32_t sect_size,
1688                                       uint64_t sect_addr,
1689                                       bool print_addresses) {
1690   // Collect the literal sections in this Mach-O file.
1691   std::vector<SectionRef> LiteralSections;
1692   for (const SectionRef &Section : O->sections()) {
1693     DataRefImpl Ref = Section.getRawDataRefImpl();
1694     uint32_t section_type;
1695     if (O->is64Bit()) {
1696       const MachO::section_64 Sec = O->getSection64(Ref);
1697       section_type = Sec.flags & MachO::SECTION_TYPE;
1698     } else {
1699       const MachO::section Sec = O->getSection(Ref);
1700       section_type = Sec.flags & MachO::SECTION_TYPE;
1701     }
1702     if (section_type == MachO::S_CSTRING_LITERALS ||
1703         section_type == MachO::S_4BYTE_LITERALS ||
1704         section_type == MachO::S_8BYTE_LITERALS ||
1705         section_type == MachO::S_16BYTE_LITERALS)
1706       LiteralSections.push_back(Section);
1707   }
1708 
1709   // Set the size of the literal pointer.
1710   uint32_t lp_size = O->is64Bit() ? 8 : 4;
1711 
1712   // Collect the external relocation symbols for the literal pointers.
1713   std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1714   for (const RelocationRef &Reloc : Section.relocations()) {
1715     DataRefImpl Rel;
1716     MachO::any_relocation_info RE;
1717     bool isExtern = false;
1718     Rel = Reloc.getRawDataRefImpl();
1719     RE = O->getRelocation(Rel);
1720     isExtern = O->getPlainRelocationExternal(RE);
1721     if (isExtern) {
1722       uint64_t RelocOffset = Reloc.getOffset();
1723       symbol_iterator RelocSym = Reloc.getSymbol();
1724       Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
1725     }
1726   }
1727   array_pod_sort(Relocs.begin(), Relocs.end());
1728 
1729   // Dump each literal pointer.
1730   for (uint32_t i = 0; i < sect_size; i += lp_size) {
1731     if (print_addresses) {
1732       if (O->is64Bit())
1733         outs() << format("%016" PRIx64, sect_addr + i) << "  ";
1734       else
1735         outs() << format("%08" PRIx64, sect_addr + i) << "  ";
1736     }
1737     uint64_t lp;
1738     if (O->is64Bit()) {
1739       memcpy(&lp, sect + i, sizeof(uint64_t));
1740       if (O->isLittleEndian() != sys::IsLittleEndianHost)
1741         sys::swapByteOrder(lp);
1742     } else {
1743       uint32_t li;
1744       memcpy(&li, sect + i, sizeof(uint32_t));
1745       if (O->isLittleEndian() != sys::IsLittleEndianHost)
1746         sys::swapByteOrder(li);
1747       lp = li;
1748     }
1749 
1750     // First look for an external relocation entry for this literal pointer.
1751     auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
1752       return P.first == i;
1753     });
1754     if (Reloc != Relocs.end()) {
1755       symbol_iterator RelocSym = Reloc->second;
1756       StringRef SymName = unwrapOrError(RelocSym->getName(), O->getFileName());
1757       outs() << "external relocation entry for symbol:" << SymName << "\n";
1758       continue;
1759     }
1760 
1761     // For local references see what the section the literal pointer points to.
1762     auto Sect = find_if(LiteralSections, [&](const SectionRef &R) {
1763       return lp >= R.getAddress() && lp < R.getAddress() + R.getSize();
1764     });
1765     if (Sect == LiteralSections.end()) {
1766       outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
1767       continue;
1768     }
1769 
1770     uint64_t SectAddress = Sect->getAddress();
1771     uint64_t SectSize = Sect->getSize();
1772 
1773     StringRef SectName;
1774     Expected<StringRef> SectNameOrErr = Sect->getName();
1775     if (SectNameOrErr)
1776       SectName = *SectNameOrErr;
1777     else
1778       consumeError(SectNameOrErr.takeError());
1779 
1780     DataRefImpl Ref = Sect->getRawDataRefImpl();
1781     StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
1782     outs() << SegmentName << ":" << SectName << ":";
1783 
1784     uint32_t section_type;
1785     if (O->is64Bit()) {
1786       const MachO::section_64 Sec = O->getSection64(Ref);
1787       section_type = Sec.flags & MachO::SECTION_TYPE;
1788     } else {
1789       const MachO::section Sec = O->getSection(Ref);
1790       section_type = Sec.flags & MachO::SECTION_TYPE;
1791     }
1792 
1793     StringRef BytesStr = unwrapOrError(Sect->getContents(), O->getFileName());
1794 
1795     const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
1796 
1797     switch (section_type) {
1798     case MachO::S_CSTRING_LITERALS:
1799       for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
1800            i++) {
1801         DumpCstringChar(Contents[i]);
1802       }
1803       outs() << "\n";
1804       break;
1805     case MachO::S_4BYTE_LITERALS:
1806       float f;
1807       memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
1808       uint32_t l;
1809       memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
1810       if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1811         sys::swapByteOrder(f);
1812         sys::swapByteOrder(l);
1813       }
1814       DumpLiteral4(l, f);
1815       break;
1816     case MachO::S_8BYTE_LITERALS: {
1817       double d;
1818       memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
1819       uint32_t l0, l1;
1820       memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
1821       memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
1822              sizeof(uint32_t));
1823       if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1824         sys::swapByteOrder(f);
1825         sys::swapByteOrder(l0);
1826         sys::swapByteOrder(l1);
1827       }
1828       DumpLiteral8(O, l0, l1, d);
1829       break;
1830     }
1831     case MachO::S_16BYTE_LITERALS: {
1832       uint32_t l0, l1, l2, l3;
1833       memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
1834       memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
1835              sizeof(uint32_t));
1836       memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
1837              sizeof(uint32_t));
1838       memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
1839              sizeof(uint32_t));
1840       if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1841         sys::swapByteOrder(l0);
1842         sys::swapByteOrder(l1);
1843         sys::swapByteOrder(l2);
1844         sys::swapByteOrder(l3);
1845       }
1846       DumpLiteral16(l0, l1, l2, l3);
1847       break;
1848     }
1849     }
1850   }
1851 }
1852 
1853 static void DumpInitTermPointerSection(MachOObjectFile *O,
1854                                        const SectionRef &Section,
1855                                        const char *sect,
1856                                        uint32_t sect_size, uint64_t sect_addr,
1857                                        SymbolAddressMap *AddrMap,
1858                                        bool verbose) {
1859   uint32_t stride;
1860   stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t);
1861 
1862   // Collect the external relocation symbols for the pointers.
1863   std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1864   for (const RelocationRef &Reloc : Section.relocations()) {
1865     DataRefImpl Rel;
1866     MachO::any_relocation_info RE;
1867     bool isExtern = false;
1868     Rel = Reloc.getRawDataRefImpl();
1869     RE = O->getRelocation(Rel);
1870     isExtern = O->getPlainRelocationExternal(RE);
1871     if (isExtern) {
1872       uint64_t RelocOffset = Reloc.getOffset();
1873       symbol_iterator RelocSym = Reloc.getSymbol();
1874       Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
1875     }
1876   }
1877   array_pod_sort(Relocs.begin(), Relocs.end());
1878 
1879   for (uint32_t i = 0; i < sect_size; i += stride) {
1880     const char *SymbolName = nullptr;
1881     uint64_t p;
1882     if (O->is64Bit()) {
1883       outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
1884       uint64_t pointer_value;
1885       memcpy(&pointer_value, sect + i, stride);
1886       if (O->isLittleEndian() != sys::IsLittleEndianHost)
1887         sys::swapByteOrder(pointer_value);
1888       outs() << format("0x%016" PRIx64, pointer_value);
1889       p = pointer_value;
1890     } else {
1891       outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
1892       uint32_t pointer_value;
1893       memcpy(&pointer_value, sect + i, stride);
1894       if (O->isLittleEndian() != sys::IsLittleEndianHost)
1895         sys::swapByteOrder(pointer_value);
1896       outs() << format("0x%08" PRIx32, pointer_value);
1897       p = pointer_value;
1898     }
1899     if (verbose) {
1900       // First look for an external relocation entry for this pointer.
1901       auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
1902         return P.first == i;
1903       });
1904       if (Reloc != Relocs.end()) {
1905         symbol_iterator RelocSym = Reloc->second;
1906         outs() << " " << unwrapOrError(RelocSym->getName(), O->getFileName());
1907       } else {
1908         SymbolName = GuessSymbolName(p, AddrMap);
1909         if (SymbolName)
1910           outs() << " " << SymbolName;
1911       }
1912     }
1913     outs() << "\n";
1914   }
1915 }
1916 
1917 static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
1918                                    uint32_t size, uint64_t addr) {
1919   uint32_t cputype = O->getHeader().cputype;
1920   if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
1921     uint32_t j;
1922     for (uint32_t i = 0; i < size; i += j, addr += j) {
1923       if (O->is64Bit())
1924         outs() << format("%016" PRIx64, addr) << "\t";
1925       else
1926         outs() << format("%08" PRIx64, addr) << "\t";
1927       for (j = 0; j < 16 && i + j < size; j++) {
1928         uint8_t byte_word = *(sect + i + j);
1929         outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1930       }
1931       outs() << "\n";
1932     }
1933   } else {
1934     uint32_t j;
1935     for (uint32_t i = 0; i < size; i += j, addr += j) {
1936       if (O->is64Bit())
1937         outs() << format("%016" PRIx64, addr) << "\t";
1938       else
1939         outs() << format("%08" PRIx64, addr) << "\t";
1940       for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
1941            j += sizeof(int32_t)) {
1942         if (i + j + sizeof(int32_t) <= size) {
1943           uint32_t long_word;
1944           memcpy(&long_word, sect + i + j, sizeof(int32_t));
1945           if (O->isLittleEndian() != sys::IsLittleEndianHost)
1946             sys::swapByteOrder(long_word);
1947           outs() << format("%08" PRIx32, long_word) << " ";
1948         } else {
1949           for (uint32_t k = 0; i + j + k < size; k++) {
1950             uint8_t byte_word = *(sect + i + j + k);
1951             outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1952           }
1953         }
1954       }
1955       outs() << "\n";
1956     }
1957   }
1958 }
1959 
1960 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
1961                              StringRef DisSegName, StringRef DisSectName);
1962 static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
1963                                 uint32_t size, uint32_t addr);
1964 #ifdef LLVM_HAVE_LIBXAR
1965 static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
1966                                 uint32_t size, bool verbose,
1967                                 bool PrintXarHeader, bool PrintXarFileHeaders,
1968                                 std::string XarMemberName);
1969 #endif // defined(LLVM_HAVE_LIBXAR)
1970 
1971 static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
1972                                 bool verbose) {
1973   SymbolAddressMap AddrMap;
1974   if (verbose)
1975     CreateSymbolAddressMap(O, &AddrMap);
1976 
1977   for (unsigned i = 0; i < FilterSections.size(); ++i) {
1978     StringRef DumpSection = FilterSections[i];
1979     std::pair<StringRef, StringRef> DumpSegSectName;
1980     DumpSegSectName = DumpSection.split(',');
1981     StringRef DumpSegName, DumpSectName;
1982     if (!DumpSegSectName.second.empty()) {
1983       DumpSegName = DumpSegSectName.first;
1984       DumpSectName = DumpSegSectName.second;
1985     } else {
1986       DumpSegName = "";
1987       DumpSectName = DumpSegSectName.first;
1988     }
1989     for (const SectionRef &Section : O->sections()) {
1990       StringRef SectName;
1991       Expected<StringRef> SecNameOrErr = Section.getName();
1992       if (SecNameOrErr)
1993         SectName = *SecNameOrErr;
1994       else
1995         consumeError(SecNameOrErr.takeError());
1996 
1997       if (!DumpSection.empty())
1998         FoundSectionSet.insert(DumpSection);
1999 
2000       DataRefImpl Ref = Section.getRawDataRefImpl();
2001       StringRef SegName = O->getSectionFinalSegmentName(Ref);
2002       if ((DumpSegName.empty() || SegName == DumpSegName) &&
2003           (SectName == DumpSectName)) {
2004 
2005         uint32_t section_flags;
2006         if (O->is64Bit()) {
2007           const MachO::section_64 Sec = O->getSection64(Ref);
2008           section_flags = Sec.flags;
2009 
2010         } else {
2011           const MachO::section Sec = O->getSection(Ref);
2012           section_flags = Sec.flags;
2013         }
2014         uint32_t section_type = section_flags & MachO::SECTION_TYPE;
2015 
2016         StringRef BytesStr =
2017             unwrapOrError(Section.getContents(), O->getFileName());
2018         const char *sect = reinterpret_cast<const char *>(BytesStr.data());
2019         uint32_t sect_size = BytesStr.size();
2020         uint64_t sect_addr = Section.getAddress();
2021 
2022         if (LeadingHeaders)
2023           outs() << "Contents of (" << SegName << "," << SectName
2024                  << ") section\n";
2025 
2026         if (verbose) {
2027           if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
2028               (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
2029             DisassembleMachO(Filename, O, SegName, SectName);
2030             continue;
2031           }
2032           if (SegName == "__TEXT" && SectName == "__info_plist") {
2033             outs() << sect;
2034             continue;
2035           }
2036           if (SegName == "__OBJC" && SectName == "__protocol") {
2037             DumpProtocolSection(O, sect, sect_size, sect_addr);
2038             continue;
2039           }
2040 #ifdef LLVM_HAVE_LIBXAR
2041           if (SegName == "__LLVM" && SectName == "__bundle") {
2042             DumpBitcodeSection(O, sect, sect_size, verbose, SymbolicOperands,
2043                                ArchiveHeaders, "");
2044             continue;
2045           }
2046 #endif // defined(LLVM_HAVE_LIBXAR)
2047           switch (section_type) {
2048           case MachO::S_REGULAR:
2049             DumpRawSectionContents(O, sect, sect_size, sect_addr);
2050             break;
2051           case MachO::S_ZEROFILL:
2052             outs() << "zerofill section and has no contents in the file\n";
2053             break;
2054           case MachO::S_CSTRING_LITERALS:
2055             DumpCstringSection(O, sect, sect_size, sect_addr, LeadingAddr);
2056             break;
2057           case MachO::S_4BYTE_LITERALS:
2058             DumpLiteral4Section(O, sect, sect_size, sect_addr, LeadingAddr);
2059             break;
2060           case MachO::S_8BYTE_LITERALS:
2061             DumpLiteral8Section(O, sect, sect_size, sect_addr, LeadingAddr);
2062             break;
2063           case MachO::S_16BYTE_LITERALS:
2064             DumpLiteral16Section(O, sect, sect_size, sect_addr, LeadingAddr);
2065             break;
2066           case MachO::S_LITERAL_POINTERS:
2067             DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
2068                                       LeadingAddr);
2069             break;
2070           case MachO::S_MOD_INIT_FUNC_POINTERS:
2071           case MachO::S_MOD_TERM_FUNC_POINTERS:
2072             DumpInitTermPointerSection(O, Section, sect, sect_size, sect_addr,
2073                                        &AddrMap, verbose);
2074             break;
2075           default:
2076             outs() << "Unknown section type ("
2077                    << format("0x%08" PRIx32, section_type) << ")\n";
2078             DumpRawSectionContents(O, sect, sect_size, sect_addr);
2079             break;
2080           }
2081         } else {
2082           if (section_type == MachO::S_ZEROFILL)
2083             outs() << "zerofill section and has no contents in the file\n";
2084           else
2085             DumpRawSectionContents(O, sect, sect_size, sect_addr);
2086         }
2087       }
2088     }
2089   }
2090 }
2091 
2092 static void DumpInfoPlistSectionContents(StringRef Filename,
2093                                          MachOObjectFile *O) {
2094   for (const SectionRef &Section : O->sections()) {
2095     StringRef SectName;
2096     Expected<StringRef> SecNameOrErr = Section.getName();
2097     if (SecNameOrErr)
2098       SectName = *SecNameOrErr;
2099     else
2100       consumeError(SecNameOrErr.takeError());
2101 
2102     DataRefImpl Ref = Section.getRawDataRefImpl();
2103     StringRef SegName = O->getSectionFinalSegmentName(Ref);
2104     if (SegName == "__TEXT" && SectName == "__info_plist") {
2105       if (LeadingHeaders)
2106         outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
2107       StringRef BytesStr =
2108           unwrapOrError(Section.getContents(), O->getFileName());
2109       const char *sect = reinterpret_cast<const char *>(BytesStr.data());
2110       outs() << format("%.*s", BytesStr.size(), sect) << "\n";
2111       return;
2112     }
2113   }
2114 }
2115 
2116 // checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
2117 // and if it is and there is a list of architecture flags is specified then
2118 // check to make sure this Mach-O file is one of those architectures or all
2119 // architectures were specified.  If not then an error is generated and this
2120 // routine returns false.  Else it returns true.
2121 static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
2122   auto *MachO = dyn_cast<MachOObjectFile>(O);
2123 
2124   if (!MachO || ArchAll || ArchFlags.empty())
2125     return true;
2126 
2127   MachO::mach_header H;
2128   MachO::mach_header_64 H_64;
2129   Triple T;
2130   const char *McpuDefault, *ArchFlag;
2131   if (MachO->is64Bit()) {
2132     H_64 = MachO->MachOObjectFile::getHeader64();
2133     T = MachOObjectFile::getArchTriple(H_64.cputype, H_64.cpusubtype,
2134                                        &McpuDefault, &ArchFlag);
2135   } else {
2136     H = MachO->MachOObjectFile::getHeader();
2137     T = MachOObjectFile::getArchTriple(H.cputype, H.cpusubtype,
2138                                        &McpuDefault, &ArchFlag);
2139   }
2140   const std::string ArchFlagName(ArchFlag);
2141   if (!llvm::is_contained(ArchFlags, ArchFlagName)) {
2142     WithColor::error(errs(), "llvm-objdump")
2143         << Filename << ": no architecture specified.\n";
2144     return false;
2145   }
2146   return true;
2147 }
2148 
2149 static void printObjcMetaData(MachOObjectFile *O, bool verbose);
2150 
2151 // ProcessMachO() is passed a single opened Mach-O file, which may be an
2152 // archive member and or in a slice of a universal file.  It prints the
2153 // the file name and header info and then processes it according to the
2154 // command line options.
2155 static void ProcessMachO(StringRef Name, MachOObjectFile *MachOOF,
2156                          StringRef ArchiveMemberName = StringRef(),
2157                          StringRef ArchitectureName = StringRef()) {
2158   std::unique_ptr<Dumper> D = createMachODumper(*MachOOF);
2159 
2160   // If we are doing some processing here on the Mach-O file print the header
2161   // info.  And don't print it otherwise like in the case of printing the
2162   // UniversalHeaders or ArchiveHeaders.
2163   if (Disassemble || Relocations || PrivateHeaders || ExportsTrie || Rebase ||
2164       Bind || SymbolTable || LazyBind || WeakBind || IndirectSymbols ||
2165       DataInCode || FunctionStartsType != FunctionStartsMode::None ||
2166       LinkOptHints || ChainedFixups || DyldInfo || DylibsUsed || DylibId ||
2167       Rpaths || ObjcMetaData || (!FilterSections.empty())) {
2168     if (LeadingHeaders) {
2169       outs() << Name;
2170       if (!ArchiveMemberName.empty())
2171         outs() << '(' << ArchiveMemberName << ')';
2172       if (!ArchitectureName.empty())
2173         outs() << " (architecture " << ArchitectureName << ")";
2174       outs() << ":\n";
2175     }
2176   }
2177   // To use the report_error() form with an ArchiveName and FileName set
2178   // these up based on what is passed for Name and ArchiveMemberName.
2179   StringRef ArchiveName;
2180   StringRef FileName;
2181   if (!ArchiveMemberName.empty()) {
2182     ArchiveName = Name;
2183     FileName = ArchiveMemberName;
2184   } else {
2185     ArchiveName = StringRef();
2186     FileName = Name;
2187   }
2188 
2189   // If we need the symbol table to do the operation then check it here to
2190   // produce a good error message as to where the Mach-O file comes from in
2191   // the error message.
2192   if (Disassemble || IndirectSymbols || !FilterSections.empty() || UnwindInfo)
2193     if (Error Err = MachOOF->checkSymbolTable())
2194       reportError(std::move(Err), FileName, ArchiveName, ArchitectureName);
2195 
2196   if (DisassembleAll) {
2197     for (const SectionRef &Section : MachOOF->sections()) {
2198       StringRef SectName;
2199       if (Expected<StringRef> NameOrErr = Section.getName())
2200         SectName = *NameOrErr;
2201       else
2202         consumeError(NameOrErr.takeError());
2203 
2204       if (SectName.equals("__text")) {
2205         DataRefImpl Ref = Section.getRawDataRefImpl();
2206         StringRef SegName = MachOOF->getSectionFinalSegmentName(Ref);
2207         DisassembleMachO(FileName, MachOOF, SegName, SectName);
2208       }
2209     }
2210   }
2211   else if (Disassemble) {
2212     if (MachOOF->getHeader().filetype == MachO::MH_KEXT_BUNDLE &&
2213         MachOOF->getHeader().cputype == MachO::CPU_TYPE_ARM64)
2214       DisassembleMachO(FileName, MachOOF, "__TEXT_EXEC", "__text");
2215     else
2216       DisassembleMachO(FileName, MachOOF, "__TEXT", "__text");
2217   }
2218   if (IndirectSymbols)
2219     PrintIndirectSymbols(MachOOF, Verbose);
2220   if (DataInCode)
2221     PrintDataInCodeTable(MachOOF, Verbose);
2222   if (FunctionStartsType != FunctionStartsMode::None)
2223     PrintFunctionStarts(MachOOF);
2224   if (LinkOptHints)
2225     PrintLinkOptHints(MachOOF);
2226   if (Relocations)
2227     PrintRelocations(MachOOF, Verbose);
2228   if (SectionHeaders)
2229     printSectionHeaders(*MachOOF);
2230   if (SectionContents)
2231     printSectionContents(MachOOF);
2232   if (!FilterSections.empty())
2233     DumpSectionContents(FileName, MachOOF, Verbose);
2234   if (InfoPlist)
2235     DumpInfoPlistSectionContents(FileName, MachOOF);
2236   if (DyldInfo)
2237     PrintDyldInfo(MachOOF);
2238   if (ChainedFixups)
2239     PrintChainedFixups(MachOOF);
2240   if (DylibsUsed)
2241     PrintDylibs(MachOOF, false);
2242   if (DylibId)
2243     PrintDylibs(MachOOF, true);
2244   if (SymbolTable)
2245     D->printSymbolTable(ArchiveName, ArchitectureName);
2246   if (UnwindInfo)
2247     printMachOUnwindInfo(MachOOF);
2248   if (PrivateHeaders) {
2249     printMachOFileHeader(MachOOF);
2250     printMachOLoadCommands(MachOOF);
2251   }
2252   if (FirstPrivateHeader)
2253     printMachOFileHeader(MachOOF);
2254   if (ObjcMetaData)
2255     printObjcMetaData(MachOOF, Verbose);
2256   if (ExportsTrie)
2257     printExportsTrie(MachOOF);
2258   if (Rebase)
2259     printRebaseTable(MachOOF);
2260   if (Rpaths)
2261     printRpaths(MachOOF);
2262   if (Bind)
2263     printBindTable(MachOOF);
2264   if (LazyBind)
2265     printLazyBindTable(MachOOF);
2266   if (WeakBind)
2267     printWeakBindTable(MachOOF);
2268 
2269   if (DwarfDumpType != DIDT_Null) {
2270     std::unique_ptr<DIContext> DICtx = DWARFContext::create(*MachOOF);
2271     // Dump the complete DWARF structure.
2272     DIDumpOptions DumpOpts;
2273     DumpOpts.DumpType = DwarfDumpType;
2274     DICtx->dump(outs(), DumpOpts);
2275   }
2276 }
2277 
2278 // printUnknownCPUType() helps print_fat_headers for unknown CPU's.
2279 static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
2280   outs() << "    cputype (" << cputype << ")\n";
2281   outs() << "    cpusubtype (" << cpusubtype << ")\n";
2282 }
2283 
2284 // printCPUType() helps print_fat_headers by printing the cputype and
2285 // pusubtype (symbolically for the one's it knows about).
2286 static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
2287   switch (cputype) {
2288   case MachO::CPU_TYPE_I386:
2289     switch (cpusubtype) {
2290     case MachO::CPU_SUBTYPE_I386_ALL:
2291       outs() << "    cputype CPU_TYPE_I386\n";
2292       outs() << "    cpusubtype CPU_SUBTYPE_I386_ALL\n";
2293       break;
2294     default:
2295       printUnknownCPUType(cputype, cpusubtype);
2296       break;
2297     }
2298     break;
2299   case MachO::CPU_TYPE_X86_64:
2300     switch (cpusubtype) {
2301     case MachO::CPU_SUBTYPE_X86_64_ALL:
2302       outs() << "    cputype CPU_TYPE_X86_64\n";
2303       outs() << "    cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
2304       break;
2305     case MachO::CPU_SUBTYPE_X86_64_H:
2306       outs() << "    cputype CPU_TYPE_X86_64\n";
2307       outs() << "    cpusubtype CPU_SUBTYPE_X86_64_H\n";
2308       break;
2309     default:
2310       printUnknownCPUType(cputype, cpusubtype);
2311       break;
2312     }
2313     break;
2314   case MachO::CPU_TYPE_ARM:
2315     switch (cpusubtype) {
2316     case MachO::CPU_SUBTYPE_ARM_ALL:
2317       outs() << "    cputype CPU_TYPE_ARM\n";
2318       outs() << "    cpusubtype CPU_SUBTYPE_ARM_ALL\n";
2319       break;
2320     case MachO::CPU_SUBTYPE_ARM_V4T:
2321       outs() << "    cputype CPU_TYPE_ARM\n";
2322       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V4T\n";
2323       break;
2324     case MachO::CPU_SUBTYPE_ARM_V5TEJ:
2325       outs() << "    cputype CPU_TYPE_ARM\n";
2326       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
2327       break;
2328     case MachO::CPU_SUBTYPE_ARM_XSCALE:
2329       outs() << "    cputype CPU_TYPE_ARM\n";
2330       outs() << "    cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
2331       break;
2332     case MachO::CPU_SUBTYPE_ARM_V6:
2333       outs() << "    cputype CPU_TYPE_ARM\n";
2334       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V6\n";
2335       break;
2336     case MachO::CPU_SUBTYPE_ARM_V6M:
2337       outs() << "    cputype CPU_TYPE_ARM\n";
2338       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V6M\n";
2339       break;
2340     case MachO::CPU_SUBTYPE_ARM_V7:
2341       outs() << "    cputype CPU_TYPE_ARM\n";
2342       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V7\n";
2343       break;
2344     case MachO::CPU_SUBTYPE_ARM_V7EM:
2345       outs() << "    cputype CPU_TYPE_ARM\n";
2346       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
2347       break;
2348     case MachO::CPU_SUBTYPE_ARM_V7K:
2349       outs() << "    cputype CPU_TYPE_ARM\n";
2350       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V7K\n";
2351       break;
2352     case MachO::CPU_SUBTYPE_ARM_V7M:
2353       outs() << "    cputype CPU_TYPE_ARM\n";
2354       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V7M\n";
2355       break;
2356     case MachO::CPU_SUBTYPE_ARM_V7S:
2357       outs() << "    cputype CPU_TYPE_ARM\n";
2358       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V7S\n";
2359       break;
2360     default:
2361       printUnknownCPUType(cputype, cpusubtype);
2362       break;
2363     }
2364     break;
2365   case MachO::CPU_TYPE_ARM64:
2366     switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2367     case MachO::CPU_SUBTYPE_ARM64_ALL:
2368       outs() << "    cputype CPU_TYPE_ARM64\n";
2369       outs() << "    cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
2370       break;
2371     case MachO::CPU_SUBTYPE_ARM64_V8:
2372       outs() << "    cputype CPU_TYPE_ARM64\n";
2373       outs() << "    cpusubtype CPU_SUBTYPE_ARM64_V8\n";
2374       break;
2375     case MachO::CPU_SUBTYPE_ARM64E:
2376       outs() << "    cputype CPU_TYPE_ARM64\n";
2377       outs() << "    cpusubtype CPU_SUBTYPE_ARM64E\n";
2378       break;
2379     default:
2380       printUnknownCPUType(cputype, cpusubtype);
2381       break;
2382     }
2383     break;
2384   case MachO::CPU_TYPE_ARM64_32:
2385     switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2386     case MachO::CPU_SUBTYPE_ARM64_32_V8:
2387       outs() << "    cputype CPU_TYPE_ARM64_32\n";
2388       outs() << "    cpusubtype CPU_SUBTYPE_ARM64_32_V8\n";
2389       break;
2390     default:
2391       printUnknownCPUType(cputype, cpusubtype);
2392       break;
2393     }
2394     break;
2395   default:
2396     printUnknownCPUType(cputype, cpusubtype);
2397     break;
2398   }
2399 }
2400 
2401 static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
2402                                        bool verbose) {
2403   outs() << "Fat headers\n";
2404   if (verbose) {
2405     if (UB->getMagic() == MachO::FAT_MAGIC)
2406       outs() << "fat_magic FAT_MAGIC\n";
2407     else // UB->getMagic() == MachO::FAT_MAGIC_64
2408       outs() << "fat_magic FAT_MAGIC_64\n";
2409   } else
2410     outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
2411 
2412   uint32_t nfat_arch = UB->getNumberOfObjects();
2413   StringRef Buf = UB->getData();
2414   uint64_t size = Buf.size();
2415   uint64_t big_size = sizeof(struct MachO::fat_header) +
2416                       nfat_arch * sizeof(struct MachO::fat_arch);
2417   outs() << "nfat_arch " << UB->getNumberOfObjects();
2418   if (nfat_arch == 0)
2419     outs() << " (malformed, contains zero architecture types)\n";
2420   else if (big_size > size)
2421     outs() << " (malformed, architectures past end of file)\n";
2422   else
2423     outs() << "\n";
2424 
2425   for (uint32_t i = 0; i < nfat_arch; ++i) {
2426     MachOUniversalBinary::ObjectForArch OFA(UB, i);
2427     uint32_t cputype = OFA.getCPUType();
2428     uint32_t cpusubtype = OFA.getCPUSubType();
2429     outs() << "architecture ";
2430     for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
2431       MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
2432       uint32_t other_cputype = other_OFA.getCPUType();
2433       uint32_t other_cpusubtype = other_OFA.getCPUSubType();
2434       if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
2435           (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
2436               (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
2437         outs() << "(illegal duplicate architecture) ";
2438         break;
2439       }
2440     }
2441     if (verbose) {
2442       outs() << OFA.getArchFlagName() << "\n";
2443       printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2444     } else {
2445       outs() << i << "\n";
2446       outs() << "    cputype " << cputype << "\n";
2447       outs() << "    cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
2448              << "\n";
2449     }
2450     if (verbose &&
2451         (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
2452       outs() << "    capabilities CPU_SUBTYPE_LIB64\n";
2453     else
2454       outs() << "    capabilities "
2455              << format("0x%" PRIx32,
2456                        (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
2457     outs() << "    offset " << OFA.getOffset();
2458     if (OFA.getOffset() > size)
2459       outs() << " (past end of file)";
2460     if (OFA.getOffset() % (1ull << OFA.getAlign()) != 0)
2461       outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
2462     outs() << "\n";
2463     outs() << "    size " << OFA.getSize();
2464     big_size = OFA.getOffset() + OFA.getSize();
2465     if (big_size > size)
2466       outs() << " (past end of file)";
2467     outs() << "\n";
2468     outs() << "    align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
2469            << ")\n";
2470   }
2471 }
2472 
2473 static void printArchiveChild(StringRef Filename, const Archive::Child &C,
2474                               size_t ChildIndex, bool verbose,
2475                               bool print_offset,
2476                               StringRef ArchitectureName = StringRef()) {
2477   if (print_offset)
2478     outs() << C.getChildOffset() << "\t";
2479   sys::fs::perms Mode =
2480       unwrapOrError(C.getAccessMode(), getFileNameForError(C, ChildIndex),
2481                     Filename, ArchitectureName);
2482   if (verbose) {
2483     // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
2484     // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
2485     outs() << "-";
2486     outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
2487     outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
2488     outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
2489     outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
2490     outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
2491     outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
2492     outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
2493     outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
2494     outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
2495   } else {
2496     outs() << format("0%o ", Mode);
2497   }
2498 
2499   outs() << format("%3d/%-3d %5" PRId64 " ",
2500                    unwrapOrError(C.getUID(), getFileNameForError(C, ChildIndex),
2501                                  Filename, ArchitectureName),
2502                    unwrapOrError(C.getGID(), getFileNameForError(C, ChildIndex),
2503                                  Filename, ArchitectureName),
2504                    unwrapOrError(C.getRawSize(),
2505                                  getFileNameForError(C, ChildIndex), Filename,
2506                                  ArchitectureName));
2507 
2508   StringRef RawLastModified = C.getRawLastModified();
2509   if (verbose) {
2510     unsigned Seconds;
2511     if (RawLastModified.getAsInteger(10, Seconds))
2512       outs() << "(date: \"" << RawLastModified
2513              << "\" contains non-decimal chars) ";
2514     else {
2515       // Since cime(3) returns a 26 character string of the form:
2516       // "Sun Sep 16 01:03:52 1973\n\0"
2517       // just print 24 characters.
2518       time_t t = Seconds;
2519       outs() << format("%.24s ", ctime(&t));
2520     }
2521   } else {
2522     outs() << RawLastModified << " ";
2523   }
2524 
2525   if (verbose) {
2526     Expected<StringRef> NameOrErr = C.getName();
2527     if (!NameOrErr) {
2528       consumeError(NameOrErr.takeError());
2529       outs() << unwrapOrError(C.getRawName(),
2530                               getFileNameForError(C, ChildIndex), Filename,
2531                               ArchitectureName)
2532              << "\n";
2533     } else {
2534       StringRef Name = NameOrErr.get();
2535       outs() << Name << "\n";
2536     }
2537   } else {
2538     outs() << unwrapOrError(C.getRawName(), getFileNameForError(C, ChildIndex),
2539                             Filename, ArchitectureName)
2540            << "\n";
2541   }
2542 }
2543 
2544 static void printArchiveHeaders(StringRef Filename, Archive *A, bool verbose,
2545                                 bool print_offset,
2546                                 StringRef ArchitectureName = StringRef()) {
2547   Error Err = Error::success();
2548   size_t I = 0;
2549   for (const auto &C : A->children(Err, false))
2550     printArchiveChild(Filename, C, I++, verbose, print_offset,
2551                       ArchitectureName);
2552 
2553   if (Err)
2554     reportError(std::move(Err), Filename, "", ArchitectureName);
2555 }
2556 
2557 static bool ValidateArchFlags() {
2558   // Check for -arch all and verifiy the -arch flags are valid.
2559   for (unsigned i = 0; i < ArchFlags.size(); ++i) {
2560     if (ArchFlags[i] == "all") {
2561       ArchAll = true;
2562     } else {
2563       if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
2564         WithColor::error(errs(), "llvm-objdump")
2565             << "unknown architecture named '" + ArchFlags[i] +
2566                    "'for the -arch option\n";
2567         return false;
2568       }
2569     }
2570   }
2571   return true;
2572 }
2573 
2574 // ParseInputMachO() parses the named Mach-O file in Filename and handles the
2575 // -arch flags selecting just those slices as specified by them and also parses
2576 // archive files.  Then for each individual Mach-O file ProcessMachO() is
2577 // called to process the file based on the command line options.
2578 void objdump::parseInputMachO(StringRef Filename) {
2579   if (!ValidateArchFlags())
2580     return;
2581 
2582   // Attempt to open the binary.
2583   Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
2584   if (!BinaryOrErr) {
2585     if (Error E = isNotObjectErrorInvalidFileType(BinaryOrErr.takeError()))
2586       reportError(std::move(E), Filename);
2587     else
2588       outs() << Filename << ": is not an object file\n";
2589     return;
2590   }
2591   Binary &Bin = *BinaryOrErr.get().getBinary();
2592 
2593   if (Archive *A = dyn_cast<Archive>(&Bin)) {
2594     outs() << "Archive : " << Filename << "\n";
2595     if (ArchiveHeaders)
2596       printArchiveHeaders(Filename, A, Verbose, ArchiveMemberOffsets);
2597 
2598     Error Err = Error::success();
2599     unsigned I = -1;
2600     for (auto &C : A->children(Err)) {
2601       ++I;
2602       Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2603       if (!ChildOrErr) {
2604         if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2605           reportError(std::move(E), getFileNameForError(C, I), Filename);
2606         continue;
2607       }
2608       if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
2609         if (!checkMachOAndArchFlags(O, Filename))
2610           return;
2611         ProcessMachO(Filename, O, O->getFileName());
2612       }
2613     }
2614     if (Err)
2615       reportError(std::move(Err), Filename);
2616     return;
2617   }
2618   if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
2619     parseInputMachO(UB);
2620     return;
2621   }
2622   if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
2623     if (!checkMachOAndArchFlags(O, Filename))
2624       return;
2625     if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O))
2626       ProcessMachO(Filename, MachOOF);
2627     else
2628       WithColor::error(errs(), "llvm-objdump")
2629           << Filename << "': "
2630           << "object is not a Mach-O file type.\n";
2631     return;
2632   }
2633   llvm_unreachable("Input object can't be invalid at this point");
2634 }
2635 
2636 void objdump::parseInputMachO(MachOUniversalBinary *UB) {
2637   if (!ValidateArchFlags())
2638     return;
2639 
2640   auto Filename = UB->getFileName();
2641 
2642   if (UniversalHeaders)
2643     printMachOUniversalHeaders(UB, Verbose);
2644 
2645   // If we have a list of architecture flags specified dump only those.
2646   if (!ArchAll && !ArchFlags.empty()) {
2647     // Look for a slice in the universal binary that matches each ArchFlag.
2648     bool ArchFound;
2649     for (unsigned i = 0; i < ArchFlags.size(); ++i) {
2650       ArchFound = false;
2651       for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2652                                                   E = UB->end_objects();
2653             I != E; ++I) {
2654         if (ArchFlags[i] == I->getArchFlagName()) {
2655           ArchFound = true;
2656           Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
2657               I->getAsObjectFile();
2658           std::string ArchitectureName;
2659           if (ArchFlags.size() > 1)
2660             ArchitectureName = I->getArchFlagName();
2661           if (ObjOrErr) {
2662             ObjectFile &O = *ObjOrErr.get();
2663             if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
2664               ProcessMachO(Filename, MachOOF, "", ArchitectureName);
2665           } else if (Error E = isNotObjectErrorInvalidFileType(
2666                          ObjOrErr.takeError())) {
2667             reportError(std::move(E), "", Filename, ArchitectureName);
2668             continue;
2669           } else if (Expected<std::unique_ptr<Archive>> AOrErr =
2670                          I->getAsArchive()) {
2671             std::unique_ptr<Archive> &A = *AOrErr;
2672             outs() << "Archive : " << Filename;
2673             if (!ArchitectureName.empty())
2674               outs() << " (architecture " << ArchitectureName << ")";
2675             outs() << "\n";
2676             if (ArchiveHeaders)
2677               printArchiveHeaders(Filename, A.get(), Verbose,
2678                                   ArchiveMemberOffsets, ArchitectureName);
2679             Error Err = Error::success();
2680             unsigned I = -1;
2681             for (auto &C : A->children(Err)) {
2682               ++I;
2683               Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2684               if (!ChildOrErr) {
2685                 if (Error E =
2686                         isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2687                   reportError(std::move(E), getFileNameForError(C, I), Filename,
2688                               ArchitectureName);
2689                 continue;
2690               }
2691               if (MachOObjectFile *O =
2692                       dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
2693                 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
2694             }
2695             if (Err)
2696               reportError(std::move(Err), Filename);
2697           } else {
2698             consumeError(AOrErr.takeError());
2699             reportError(Filename,
2700                         "Mach-O universal file for architecture " +
2701                             StringRef(I->getArchFlagName()) +
2702                             " is not a Mach-O file or an archive file");
2703           }
2704         }
2705       }
2706       if (!ArchFound) {
2707         WithColor::error(errs(), "llvm-objdump")
2708             << "file: " + Filename + " does not contain "
2709             << "architecture: " + ArchFlags[i] + "\n";
2710         return;
2711       }
2712     }
2713     return;
2714   }
2715   // No architecture flags were specified so if this contains a slice that
2716   // matches the host architecture dump only that.
2717   if (!ArchAll) {
2718     for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2719                                                 E = UB->end_objects();
2720           I != E; ++I) {
2721       if (MachOObjectFile::getHostArch().getArchName() ==
2722           I->getArchFlagName()) {
2723         Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2724         std::string ArchiveName;
2725         ArchiveName.clear();
2726         if (ObjOrErr) {
2727           ObjectFile &O = *ObjOrErr.get();
2728           if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
2729             ProcessMachO(Filename, MachOOF);
2730         } else if (Error E =
2731                        isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) {
2732           reportError(std::move(E), Filename);
2733         } else if (Expected<std::unique_ptr<Archive>> AOrErr =
2734                        I->getAsArchive()) {
2735           std::unique_ptr<Archive> &A = *AOrErr;
2736           outs() << "Archive : " << Filename << "\n";
2737           if (ArchiveHeaders)
2738             printArchiveHeaders(Filename, A.get(), Verbose,
2739                                 ArchiveMemberOffsets);
2740           Error Err = Error::success();
2741           unsigned I = -1;
2742           for (auto &C : A->children(Err)) {
2743             ++I;
2744             Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2745             if (!ChildOrErr) {
2746               if (Error E =
2747                       isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2748                 reportError(std::move(E), getFileNameForError(C, I), Filename);
2749               continue;
2750             }
2751             if (MachOObjectFile *O =
2752                     dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
2753               ProcessMachO(Filename, O, O->getFileName());
2754           }
2755           if (Err)
2756             reportError(std::move(Err), Filename);
2757         } else {
2758           consumeError(AOrErr.takeError());
2759           reportError(Filename, "Mach-O universal file for architecture " +
2760                                     StringRef(I->getArchFlagName()) +
2761                                     " is not a Mach-O file or an archive file");
2762         }
2763         return;
2764       }
2765     }
2766   }
2767   // Either all architectures have been specified or none have been specified
2768   // and this does not contain the host architecture so dump all the slices.
2769   bool moreThanOneArch = UB->getNumberOfObjects() > 1;
2770   for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2771                                               E = UB->end_objects();
2772         I != E; ++I) {
2773     Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2774     std::string ArchitectureName;
2775     if (moreThanOneArch)
2776       ArchitectureName = I->getArchFlagName();
2777     if (ObjOrErr) {
2778       ObjectFile &Obj = *ObjOrErr.get();
2779       if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
2780         ProcessMachO(Filename, MachOOF, "", ArchitectureName);
2781     } else if (Error E =
2782                    isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) {
2783       reportError(std::move(E), Filename, "", ArchitectureName);
2784     } else if (Expected<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
2785       std::unique_ptr<Archive> &A = *AOrErr;
2786       outs() << "Archive : " << Filename;
2787       if (!ArchitectureName.empty())
2788         outs() << " (architecture " << ArchitectureName << ")";
2789       outs() << "\n";
2790       if (ArchiveHeaders)
2791         printArchiveHeaders(Filename, A.get(), Verbose, ArchiveMemberOffsets,
2792                             ArchitectureName);
2793       Error Err = Error::success();
2794       unsigned I = -1;
2795       for (auto &C : A->children(Err)) {
2796         ++I;
2797         Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2798         if (!ChildOrErr) {
2799           if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2800             reportError(std::move(E), getFileNameForError(C, I), Filename,
2801                         ArchitectureName);
2802           continue;
2803         }
2804         if (MachOObjectFile *O =
2805                 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
2806           if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
2807             ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
2808                           ArchitectureName);
2809         }
2810       }
2811       if (Err)
2812         reportError(std::move(Err), Filename);
2813     } else {
2814       consumeError(AOrErr.takeError());
2815       reportError(Filename, "Mach-O universal file for architecture " +
2816                                 StringRef(I->getArchFlagName()) +
2817                                 " is not a Mach-O file or an archive file");
2818     }
2819   }
2820 }
2821 
2822 namespace {
2823 // The block of info used by the Symbolizer call backs.
2824 struct DisassembleInfo {
2825   DisassembleInfo(MachOObjectFile *O, SymbolAddressMap *AddrMap,
2826                   std::vector<SectionRef> *Sections, bool verbose)
2827     : verbose(verbose), O(O), AddrMap(AddrMap), Sections(Sections) {}
2828   bool verbose;
2829   MachOObjectFile *O;
2830   SectionRef S;
2831   SymbolAddressMap *AddrMap;
2832   std::vector<SectionRef> *Sections;
2833   const char *class_name = nullptr;
2834   const char *selector_name = nullptr;
2835   std::unique_ptr<char[]> method = nullptr;
2836   char *demangled_name = nullptr;
2837   uint64_t adrp_addr = 0;
2838   uint32_t adrp_inst = 0;
2839   std::unique_ptr<SymbolAddressMap> bindtable;
2840   uint32_t depth = 0;
2841 };
2842 } // namespace
2843 
2844 // SymbolizerGetOpInfo() is the operand information call back function.
2845 // This is called to get the symbolic information for operand(s) of an
2846 // instruction when it is being done.  This routine does this from
2847 // the relocation information, symbol table, etc. That block of information
2848 // is a pointer to the struct DisassembleInfo that was passed when the
2849 // disassembler context was created and passed to back to here when
2850 // called back by the disassembler for instruction operands that could have
2851 // relocation information. The address of the instruction containing operand is
2852 // at the Pc parameter.  The immediate value the operand has is passed in
2853 // op_info->Value and is at Offset past the start of the instruction and has a
2854 // byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
2855 // LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
2856 // names and addends of the symbolic expression to add for the operand.  The
2857 // value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
2858 // information is returned then this function returns 1 else it returns 0.
2859 static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
2860                                uint64_t OpSize, uint64_t InstSize, int TagType,
2861                                void *TagBuf) {
2862   struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
2863   struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
2864   uint64_t value = op_info->Value;
2865 
2866   // Make sure all fields returned are zero if we don't set them.
2867   memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
2868   op_info->Value = value;
2869 
2870   // If the TagType is not the value 1 which it code knows about or if no
2871   // verbose symbolic information is wanted then just return 0, indicating no
2872   // information is being returned.
2873   if (TagType != 1 || !info->verbose)
2874     return 0;
2875 
2876   unsigned int Arch = info->O->getArch();
2877   if (Arch == Triple::x86) {
2878     if (OpSize != 1 && OpSize != 2 && OpSize != 4 && OpSize != 0)
2879       return 0;
2880     if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2881       // TODO:
2882       // Search the external relocation entries of a fully linked image
2883       // (if any) for an entry that matches this segment offset.
2884       // uint32_t seg_offset = (Pc + Offset);
2885       return 0;
2886     }
2887     // In MH_OBJECT filetypes search the section's relocation entries (if any)
2888     // for an entry for this section offset.
2889     uint32_t sect_addr = info->S.getAddress();
2890     uint32_t sect_offset = (Pc + Offset) - sect_addr;
2891     bool reloc_found = false;
2892     DataRefImpl Rel;
2893     MachO::any_relocation_info RE;
2894     bool isExtern = false;
2895     SymbolRef Symbol;
2896     bool r_scattered = false;
2897     uint32_t r_value, pair_r_value, r_type;
2898     for (const RelocationRef &Reloc : info->S.relocations()) {
2899       uint64_t RelocOffset = Reloc.getOffset();
2900       if (RelocOffset == sect_offset) {
2901         Rel = Reloc.getRawDataRefImpl();
2902         RE = info->O->getRelocation(Rel);
2903         r_type = info->O->getAnyRelocationType(RE);
2904         r_scattered = info->O->isRelocationScattered(RE);
2905         if (r_scattered) {
2906           r_value = info->O->getScatteredRelocationValue(RE);
2907           if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2908               r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
2909             DataRefImpl RelNext = Rel;
2910             info->O->moveRelocationNext(RelNext);
2911             MachO::any_relocation_info RENext;
2912             RENext = info->O->getRelocation(RelNext);
2913             if (info->O->isRelocationScattered(RENext))
2914               pair_r_value = info->O->getScatteredRelocationValue(RENext);
2915             else
2916               return 0;
2917           }
2918         } else {
2919           isExtern = info->O->getPlainRelocationExternal(RE);
2920           if (isExtern) {
2921             symbol_iterator RelocSym = Reloc.getSymbol();
2922             Symbol = *RelocSym;
2923           }
2924         }
2925         reloc_found = true;
2926         break;
2927       }
2928     }
2929     if (reloc_found && isExtern) {
2930       op_info->AddSymbol.Present = 1;
2931       op_info->AddSymbol.Name =
2932           unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
2933       // For i386 extern relocation entries the value in the instruction is
2934       // the offset from the symbol, and value is already set in op_info->Value.
2935       return 1;
2936     }
2937     if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2938                         r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
2939       const char *add = GuessSymbolName(r_value, info->AddrMap);
2940       const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
2941       uint32_t offset = value - (r_value - pair_r_value);
2942       op_info->AddSymbol.Present = 1;
2943       if (add != nullptr)
2944         op_info->AddSymbol.Name = add;
2945       else
2946         op_info->AddSymbol.Value = r_value;
2947       op_info->SubtractSymbol.Present = 1;
2948       if (sub != nullptr)
2949         op_info->SubtractSymbol.Name = sub;
2950       else
2951         op_info->SubtractSymbol.Value = pair_r_value;
2952       op_info->Value = offset;
2953       return 1;
2954     }
2955     return 0;
2956   }
2957   if (Arch == Triple::x86_64) {
2958     if (OpSize != 1 && OpSize != 2 && OpSize != 4 && OpSize != 0)
2959       return 0;
2960     // For non MH_OBJECT types, like MH_KEXT_BUNDLE, Search the external
2961     // relocation entries of a linked image (if any) for an entry that matches
2962     // this segment offset.
2963     if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2964       uint64_t seg_offset = Pc + Offset;
2965       bool reloc_found = false;
2966       DataRefImpl Rel;
2967       MachO::any_relocation_info RE;
2968       bool isExtern = false;
2969       SymbolRef Symbol;
2970       for (const RelocationRef &Reloc : info->O->external_relocations()) {
2971         uint64_t RelocOffset = Reloc.getOffset();
2972         if (RelocOffset == seg_offset) {
2973           Rel = Reloc.getRawDataRefImpl();
2974           RE = info->O->getRelocation(Rel);
2975           // external relocation entries should always be external.
2976           isExtern = info->O->getPlainRelocationExternal(RE);
2977           if (isExtern) {
2978             symbol_iterator RelocSym = Reloc.getSymbol();
2979             Symbol = *RelocSym;
2980           }
2981           reloc_found = true;
2982           break;
2983         }
2984       }
2985       if (reloc_found && isExtern) {
2986         // The Value passed in will be adjusted by the Pc if the instruction
2987         // adds the Pc.  But for x86_64 external relocation entries the Value
2988         // is the offset from the external symbol.
2989         if (info->O->getAnyRelocationPCRel(RE))
2990           op_info->Value -= Pc + InstSize;
2991         const char *name =
2992             unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
2993         op_info->AddSymbol.Present = 1;
2994         op_info->AddSymbol.Name = name;
2995         return 1;
2996       }
2997       return 0;
2998     }
2999     // In MH_OBJECT filetypes search the section's relocation entries (if any)
3000     // for an entry for this section offset.
3001     uint64_t sect_addr = info->S.getAddress();
3002     uint64_t sect_offset = (Pc + Offset) - sect_addr;
3003     bool reloc_found = false;
3004     DataRefImpl Rel;
3005     MachO::any_relocation_info RE;
3006     bool isExtern = false;
3007     SymbolRef Symbol;
3008     for (const RelocationRef &Reloc : info->S.relocations()) {
3009       uint64_t RelocOffset = Reloc.getOffset();
3010       if (RelocOffset == sect_offset) {
3011         Rel = Reloc.getRawDataRefImpl();
3012         RE = info->O->getRelocation(Rel);
3013         // NOTE: Scattered relocations don't exist on x86_64.
3014         isExtern = info->O->getPlainRelocationExternal(RE);
3015         if (isExtern) {
3016           symbol_iterator RelocSym = Reloc.getSymbol();
3017           Symbol = *RelocSym;
3018         }
3019         reloc_found = true;
3020         break;
3021       }
3022     }
3023     if (reloc_found && isExtern) {
3024       // The Value passed in will be adjusted by the Pc if the instruction
3025       // adds the Pc.  But for x86_64 external relocation entries the Value
3026       // is the offset from the external symbol.
3027       if (info->O->getAnyRelocationPCRel(RE))
3028         op_info->Value -= Pc + InstSize;
3029       const char *name =
3030           unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
3031       unsigned Type = info->O->getAnyRelocationType(RE);
3032       if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
3033         DataRefImpl RelNext = Rel;
3034         info->O->moveRelocationNext(RelNext);
3035         MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
3036         unsigned TypeNext = info->O->getAnyRelocationType(RENext);
3037         bool isExternNext = info->O->getPlainRelocationExternal(RENext);
3038         unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
3039         if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
3040           op_info->SubtractSymbol.Present = 1;
3041           op_info->SubtractSymbol.Name = name;
3042           symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
3043           Symbol = *RelocSymNext;
3044           name = unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
3045         }
3046       }
3047       // TODO: add the VariantKinds to op_info->VariantKind for relocation types
3048       // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
3049       op_info->AddSymbol.Present = 1;
3050       op_info->AddSymbol.Name = name;
3051       return 1;
3052     }
3053     return 0;
3054   }
3055   if (Arch == Triple::arm) {
3056     if (Offset != 0 || (InstSize != 4 && InstSize != 2))
3057       return 0;
3058     if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
3059       // TODO:
3060       // Search the external relocation entries of a fully linked image
3061       // (if any) for an entry that matches this segment offset.
3062       // uint32_t seg_offset = (Pc + Offset);
3063       return 0;
3064     }
3065     // In MH_OBJECT filetypes search the section's relocation entries (if any)
3066     // for an entry for this section offset.
3067     uint32_t sect_addr = info->S.getAddress();
3068     uint32_t sect_offset = (Pc + Offset) - sect_addr;
3069     DataRefImpl Rel;
3070     MachO::any_relocation_info RE;
3071     bool isExtern = false;
3072     SymbolRef Symbol;
3073     bool r_scattered = false;
3074     uint32_t r_value, pair_r_value, r_type, r_length, other_half;
3075     auto Reloc =
3076         find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
3077           uint64_t RelocOffset = Reloc.getOffset();
3078           return RelocOffset == sect_offset;
3079         });
3080 
3081     if (Reloc == info->S.relocations().end())
3082       return 0;
3083 
3084     Rel = Reloc->getRawDataRefImpl();
3085     RE = info->O->getRelocation(Rel);
3086     r_length = info->O->getAnyRelocationLength(RE);
3087     r_scattered = info->O->isRelocationScattered(RE);
3088     if (r_scattered) {
3089       r_value = info->O->getScatteredRelocationValue(RE);
3090       r_type = info->O->getScatteredRelocationType(RE);
3091     } else {
3092       r_type = info->O->getAnyRelocationType(RE);
3093       isExtern = info->O->getPlainRelocationExternal(RE);
3094       if (isExtern) {
3095         symbol_iterator RelocSym = Reloc->getSymbol();
3096         Symbol = *RelocSym;
3097       }
3098     }
3099     if (r_type == MachO::ARM_RELOC_HALF ||
3100         r_type == MachO::ARM_RELOC_SECTDIFF ||
3101         r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
3102         r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
3103       DataRefImpl RelNext = Rel;
3104       info->O->moveRelocationNext(RelNext);
3105       MachO::any_relocation_info RENext;
3106       RENext = info->O->getRelocation(RelNext);
3107       other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
3108       if (info->O->isRelocationScattered(RENext))
3109         pair_r_value = info->O->getScatteredRelocationValue(RENext);
3110     }
3111 
3112     if (isExtern) {
3113       const char *name =
3114           unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
3115       op_info->AddSymbol.Present = 1;
3116       op_info->AddSymbol.Name = name;
3117       switch (r_type) {
3118       case MachO::ARM_RELOC_HALF:
3119         if ((r_length & 0x1) == 1) {
3120           op_info->Value = value << 16 | other_half;
3121           op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
3122         } else {
3123           op_info->Value = other_half << 16 | value;
3124           op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
3125         }
3126         break;
3127       default:
3128         break;
3129       }
3130       return 1;
3131     }
3132     // If we have a branch that is not an external relocation entry then
3133     // return 0 so the code in tryAddingSymbolicOperand() can use the
3134     // SymbolLookUp call back with the branch target address to look up the
3135     // symbol and possibility add an annotation for a symbol stub.
3136     if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
3137                           r_type == MachO::ARM_THUMB_RELOC_BR22))
3138       return 0;
3139 
3140     uint32_t offset = 0;
3141     if (r_type == MachO::ARM_RELOC_HALF ||
3142         r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
3143       if ((r_length & 0x1) == 1)
3144         value = value << 16 | other_half;
3145       else
3146         value = other_half << 16 | value;
3147     }
3148     if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
3149                         r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
3150       offset = value - r_value;
3151       value = r_value;
3152     }
3153 
3154     if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
3155       if ((r_length & 0x1) == 1)
3156         op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
3157       else
3158         op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
3159       const char *add = GuessSymbolName(r_value, info->AddrMap);
3160       const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
3161       int32_t offset = value - (r_value - pair_r_value);
3162       op_info->AddSymbol.Present = 1;
3163       if (add != nullptr)
3164         op_info->AddSymbol.Name = add;
3165       else
3166         op_info->AddSymbol.Value = r_value;
3167       op_info->SubtractSymbol.Present = 1;
3168       if (sub != nullptr)
3169         op_info->SubtractSymbol.Name = sub;
3170       else
3171         op_info->SubtractSymbol.Value = pair_r_value;
3172       op_info->Value = offset;
3173       return 1;
3174     }
3175 
3176     op_info->AddSymbol.Present = 1;
3177     op_info->Value = offset;
3178     if (r_type == MachO::ARM_RELOC_HALF) {
3179       if ((r_length & 0x1) == 1)
3180         op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
3181       else
3182         op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
3183     }
3184     const char *add = GuessSymbolName(value, info->AddrMap);
3185     if (add != nullptr) {
3186       op_info->AddSymbol.Name = add;
3187       return 1;
3188     }
3189     op_info->AddSymbol.Value = value;
3190     return 1;
3191   }
3192   if (Arch == Triple::aarch64) {
3193     if (Offset != 0 || InstSize != 4)
3194       return 0;
3195     if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
3196       // TODO:
3197       // Search the external relocation entries of a fully linked image
3198       // (if any) for an entry that matches this segment offset.
3199       // uint64_t seg_offset = (Pc + Offset);
3200       return 0;
3201     }
3202     // In MH_OBJECT filetypes search the section's relocation entries (if any)
3203     // for an entry for this section offset.
3204     uint64_t sect_addr = info->S.getAddress();
3205     uint64_t sect_offset = (Pc + Offset) - sect_addr;
3206     auto Reloc =
3207         find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
3208           uint64_t RelocOffset = Reloc.getOffset();
3209           return RelocOffset == sect_offset;
3210         });
3211 
3212     if (Reloc == info->S.relocations().end())
3213       return 0;
3214 
3215     DataRefImpl Rel = Reloc->getRawDataRefImpl();
3216     MachO::any_relocation_info RE = info->O->getRelocation(Rel);
3217     uint32_t r_type = info->O->getAnyRelocationType(RE);
3218     if (r_type == MachO::ARM64_RELOC_ADDEND) {
3219       DataRefImpl RelNext = Rel;
3220       info->O->moveRelocationNext(RelNext);
3221       MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
3222       if (value == 0) {
3223         value = info->O->getPlainRelocationSymbolNum(RENext);
3224         op_info->Value = value;
3225       }
3226     }
3227     // NOTE: Scattered relocations don't exist on arm64.
3228     if (!info->O->getPlainRelocationExternal(RE))
3229       return 0;
3230     const char *name =
3231         unwrapOrError(Reloc->getSymbol()->getName(), info->O->getFileName())
3232             .data();
3233     op_info->AddSymbol.Present = 1;
3234     op_info->AddSymbol.Name = name;
3235 
3236     switch (r_type) {
3237     case MachO::ARM64_RELOC_PAGE21:
3238       /* @page */
3239       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
3240       break;
3241     case MachO::ARM64_RELOC_PAGEOFF12:
3242       /* @pageoff */
3243       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
3244       break;
3245     case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
3246       /* @gotpage */
3247       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
3248       break;
3249     case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
3250       /* @gotpageoff */
3251       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
3252       break;
3253     case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
3254       /* @tvlppage is not implemented in llvm-mc */
3255       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
3256       break;
3257     case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
3258       /* @tvlppageoff is not implemented in llvm-mc */
3259       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
3260       break;
3261     default:
3262     case MachO::ARM64_RELOC_BRANCH26:
3263       op_info->VariantKind = LLVMDisassembler_VariantKind_None;
3264       break;
3265     }
3266     return 1;
3267   }
3268   return 0;
3269 }
3270 
3271 // GuessCstringPointer is passed the address of what might be a pointer to a
3272 // literal string in a cstring section.  If that address is in a cstring section
3273 // it returns a pointer to that string.  Else it returns nullptr.
3274 static const char *GuessCstringPointer(uint64_t ReferenceValue,
3275                                        struct DisassembleInfo *info) {
3276   for (const auto &Load : info->O->load_commands()) {
3277     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
3278       MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
3279       for (unsigned J = 0; J < Seg.nsects; ++J) {
3280         MachO::section_64 Sec = info->O->getSection64(Load, J);
3281         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3282         if (section_type == MachO::S_CSTRING_LITERALS &&
3283             ReferenceValue >= Sec.addr &&
3284             ReferenceValue < Sec.addr + Sec.size) {
3285           uint64_t sect_offset = ReferenceValue - Sec.addr;
3286           uint64_t object_offset = Sec.offset + sect_offset;
3287           StringRef MachOContents = info->O->getData();
3288           uint64_t object_size = MachOContents.size();
3289           const char *object_addr = (const char *)MachOContents.data();
3290           if (object_offset < object_size) {
3291             const char *name = object_addr + object_offset;
3292             return name;
3293           } else {
3294             return nullptr;
3295           }
3296         }
3297       }
3298     } else if (Load.C.cmd == MachO::LC_SEGMENT) {
3299       MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
3300       for (unsigned J = 0; J < Seg.nsects; ++J) {
3301         MachO::section Sec = info->O->getSection(Load, J);
3302         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3303         if (section_type == MachO::S_CSTRING_LITERALS &&
3304             ReferenceValue >= Sec.addr &&
3305             ReferenceValue < Sec.addr + Sec.size) {
3306           uint64_t sect_offset = ReferenceValue - Sec.addr;
3307           uint64_t object_offset = Sec.offset + sect_offset;
3308           StringRef MachOContents = info->O->getData();
3309           uint64_t object_size = MachOContents.size();
3310           const char *object_addr = (const char *)MachOContents.data();
3311           if (object_offset < object_size) {
3312             const char *name = object_addr + object_offset;
3313             return name;
3314           } else {
3315             return nullptr;
3316           }
3317         }
3318       }
3319     }
3320   }
3321   return nullptr;
3322 }
3323 
3324 // GuessIndirectSymbol returns the name of the indirect symbol for the
3325 // ReferenceValue passed in or nullptr.  This is used when ReferenceValue maybe
3326 // an address of a symbol stub or a lazy or non-lazy pointer to associate the
3327 // symbol name being referenced by the stub or pointer.
3328 static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
3329                                        struct DisassembleInfo *info) {
3330   MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
3331   MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
3332   for (const auto &Load : info->O->load_commands()) {
3333     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
3334       MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
3335       for (unsigned J = 0; J < Seg.nsects; ++J) {
3336         MachO::section_64 Sec = info->O->getSection64(Load, J);
3337         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3338         if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
3339              section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
3340              section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
3341              section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
3342              section_type == MachO::S_SYMBOL_STUBS) &&
3343             ReferenceValue >= Sec.addr &&
3344             ReferenceValue < Sec.addr + Sec.size) {
3345           uint32_t stride;
3346           if (section_type == MachO::S_SYMBOL_STUBS)
3347             stride = Sec.reserved2;
3348           else
3349             stride = 8;
3350           if (stride == 0)
3351             return nullptr;
3352           uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
3353           if (index < Dysymtab.nindirectsyms) {
3354             uint32_t indirect_symbol =
3355                 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
3356             if (indirect_symbol < Symtab.nsyms) {
3357               symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
3358               return unwrapOrError(Sym->getName(), info->O->getFileName())
3359                   .data();
3360             }
3361           }
3362         }
3363       }
3364     } else if (Load.C.cmd == MachO::LC_SEGMENT) {
3365       MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
3366       for (unsigned J = 0; J < Seg.nsects; ++J) {
3367         MachO::section Sec = info->O->getSection(Load, J);
3368         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3369         if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
3370              section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
3371              section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
3372              section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
3373              section_type == MachO::S_SYMBOL_STUBS) &&
3374             ReferenceValue >= Sec.addr &&
3375             ReferenceValue < Sec.addr + Sec.size) {
3376           uint32_t stride;
3377           if (section_type == MachO::S_SYMBOL_STUBS)
3378             stride = Sec.reserved2;
3379           else
3380             stride = 4;
3381           if (stride == 0)
3382             return nullptr;
3383           uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
3384           if (index < Dysymtab.nindirectsyms) {
3385             uint32_t indirect_symbol =
3386                 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
3387             if (indirect_symbol < Symtab.nsyms) {
3388               symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
3389               return unwrapOrError(Sym->getName(), info->O->getFileName())
3390                   .data();
3391             }
3392           }
3393         }
3394       }
3395     }
3396   }
3397   return nullptr;
3398 }
3399 
3400 // method_reference() is called passing it the ReferenceName that might be
3401 // a reference it to an Objective-C method call.  If so then it allocates and
3402 // assembles a method call string with the values last seen and saved in
3403 // the DisassembleInfo's class_name and selector_name fields.  This is saved
3404 // into the method field of the info and any previous string is free'ed.
3405 // Then the class_name field in the info is set to nullptr.  The method call
3406 // string is set into ReferenceName and ReferenceType is set to
3407 // LLVMDisassembler_ReferenceType_Out_Objc_Message.  If this not a method call
3408 // then both ReferenceType and ReferenceName are left unchanged.
3409 static void method_reference(struct DisassembleInfo *info,
3410                              uint64_t *ReferenceType,
3411                              const char **ReferenceName) {
3412   unsigned int Arch = info->O->getArch();
3413   if (*ReferenceName != nullptr) {
3414     if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
3415       if (info->selector_name != nullptr) {
3416         if (info->class_name != nullptr) {
3417           info->method = std::make_unique<char[]>(
3418               5 + strlen(info->class_name) + strlen(info->selector_name));
3419           char *method = info->method.get();
3420           if (method != nullptr) {
3421             strcpy(method, "+[");
3422             strcat(method, info->class_name);
3423             strcat(method, " ");
3424             strcat(method, info->selector_name);
3425             strcat(method, "]");
3426             *ReferenceName = method;
3427             *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3428           }
3429         } else {
3430           info->method =
3431               std::make_unique<char[]>(9 + strlen(info->selector_name));
3432           char *method = info->method.get();
3433           if (method != nullptr) {
3434             if (Arch == Triple::x86_64)
3435               strcpy(method, "-[%rdi ");
3436             else if (Arch == Triple::aarch64)
3437               strcpy(method, "-[x0 ");
3438             else
3439               strcpy(method, "-[r? ");
3440             strcat(method, info->selector_name);
3441             strcat(method, "]");
3442             *ReferenceName = method;
3443             *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3444           }
3445         }
3446         info->class_name = nullptr;
3447       }
3448     } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
3449       if (info->selector_name != nullptr) {
3450         info->method =
3451             std::make_unique<char[]>(17 + strlen(info->selector_name));
3452         char *method = info->method.get();
3453         if (method != nullptr) {
3454           if (Arch == Triple::x86_64)
3455             strcpy(method, "-[[%rdi super] ");
3456           else if (Arch == Triple::aarch64)
3457             strcpy(method, "-[[x0 super] ");
3458           else
3459             strcpy(method, "-[[r? super] ");
3460           strcat(method, info->selector_name);
3461           strcat(method, "]");
3462           *ReferenceName = method;
3463           *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3464         }
3465         info->class_name = nullptr;
3466       }
3467     }
3468   }
3469 }
3470 
3471 // GuessPointerPointer() is passed the address of what might be a pointer to
3472 // a reference to an Objective-C class, selector, message ref or cfstring.
3473 // If so the value of the pointer is returned and one of the booleans are set
3474 // to true.  If not zero is returned and all the booleans are set to false.
3475 static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
3476                                     struct DisassembleInfo *info,
3477                                     bool &classref, bool &selref, bool &msgref,
3478                                     bool &cfstring) {
3479   classref = false;
3480   selref = false;
3481   msgref = false;
3482   cfstring = false;
3483   for (const auto &Load : info->O->load_commands()) {
3484     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
3485       MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
3486       for (unsigned J = 0; J < Seg.nsects; ++J) {
3487         MachO::section_64 Sec = info->O->getSection64(Load, J);
3488         if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
3489              strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
3490              strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
3491              strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
3492              strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
3493             ReferenceValue >= Sec.addr &&
3494             ReferenceValue < Sec.addr + Sec.size) {
3495           uint64_t sect_offset = ReferenceValue - Sec.addr;
3496           uint64_t object_offset = Sec.offset + sect_offset;
3497           StringRef MachOContents = info->O->getData();
3498           uint64_t object_size = MachOContents.size();
3499           const char *object_addr = (const char *)MachOContents.data();
3500           if (object_offset < object_size) {
3501             uint64_t pointer_value;
3502             memcpy(&pointer_value, object_addr + object_offset,
3503                    sizeof(uint64_t));
3504             if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3505               sys::swapByteOrder(pointer_value);
3506             if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
3507               selref = true;
3508             else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
3509                      strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
3510               classref = true;
3511             else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
3512                      ReferenceValue + 8 < Sec.addr + Sec.size) {
3513               msgref = true;
3514               memcpy(&pointer_value, object_addr + object_offset + 8,
3515                      sizeof(uint64_t));
3516               if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3517                 sys::swapByteOrder(pointer_value);
3518             } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
3519               cfstring = true;
3520             return pointer_value;
3521           } else {
3522             return 0;
3523           }
3524         }
3525       }
3526     }
3527     // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
3528   }
3529   return 0;
3530 }
3531 
3532 // get_pointer_64 returns a pointer to the bytes in the object file at the
3533 // Address from a section in the Mach-O file.  And indirectly returns the
3534 // offset into the section, number of bytes left in the section past the offset
3535 // and which section is was being referenced.  If the Address is not in a
3536 // section nullptr is returned.
3537 static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
3538                                   uint32_t &left, SectionRef &S,
3539                                   DisassembleInfo *info,
3540                                   bool objc_only = false) {
3541   offset = 0;
3542   left = 0;
3543   S = SectionRef();
3544   for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
3545     uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
3546     uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
3547     if (SectSize == 0)
3548       continue;
3549     if (objc_only) {
3550       StringRef SectName;
3551       Expected<StringRef> SecNameOrErr =
3552           ((*(info->Sections))[SectIdx]).getName();
3553       if (SecNameOrErr)
3554         SectName = *SecNameOrErr;
3555       else
3556         consumeError(SecNameOrErr.takeError());
3557 
3558       DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
3559       StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
3560       if (SegName != "__OBJC" && SectName != "__cstring")
3561         continue;
3562     }
3563     if (Address >= SectAddress && Address < SectAddress + SectSize) {
3564       S = (*(info->Sections))[SectIdx];
3565       offset = Address - SectAddress;
3566       left = SectSize - offset;
3567       StringRef SectContents = unwrapOrError(
3568           ((*(info->Sections))[SectIdx]).getContents(), info->O->getFileName());
3569       return SectContents.data() + offset;
3570     }
3571   }
3572   return nullptr;
3573 }
3574 
3575 static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
3576                                   uint32_t &left, SectionRef &S,
3577                                   DisassembleInfo *info,
3578                                   bool objc_only = false) {
3579   return get_pointer_64(Address, offset, left, S, info, objc_only);
3580 }
3581 
3582 // get_symbol_64() returns the name of a symbol (or nullptr) and the address of
3583 // the symbol indirectly through n_value. Based on the relocation information
3584 // for the specified section offset in the specified section reference.
3585 // If no relocation information is found and a non-zero ReferenceValue for the
3586 // symbol is passed, look up that address in the info's AddrMap.
3587 static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
3588                                  DisassembleInfo *info, uint64_t &n_value,
3589                                  uint64_t ReferenceValue = 0) {
3590   n_value = 0;
3591   if (!info->verbose)
3592     return nullptr;
3593 
3594   // See if there is an external relocation entry at the sect_offset.
3595   bool reloc_found = false;
3596   DataRefImpl Rel;
3597   MachO::any_relocation_info RE;
3598   bool isExtern = false;
3599   SymbolRef Symbol;
3600   for (const RelocationRef &Reloc : S.relocations()) {
3601     uint64_t RelocOffset = Reloc.getOffset();
3602     if (RelocOffset == sect_offset) {
3603       Rel = Reloc.getRawDataRefImpl();
3604       RE = info->O->getRelocation(Rel);
3605       if (info->O->isRelocationScattered(RE))
3606         continue;
3607       isExtern = info->O->getPlainRelocationExternal(RE);
3608       if (isExtern) {
3609         symbol_iterator RelocSym = Reloc.getSymbol();
3610         Symbol = *RelocSym;
3611       }
3612       reloc_found = true;
3613       break;
3614     }
3615   }
3616   // If there is an external relocation entry for a symbol in this section
3617   // at this section_offset then use that symbol's value for the n_value
3618   // and return its name.
3619   const char *SymbolName = nullptr;
3620   if (reloc_found && isExtern) {
3621     n_value = cantFail(Symbol.getValue());
3622     StringRef Name = unwrapOrError(Symbol.getName(), info->O->getFileName());
3623     if (!Name.empty()) {
3624       SymbolName = Name.data();
3625       return SymbolName;
3626     }
3627   }
3628 
3629   // TODO: For fully linked images, look through the external relocation
3630   // entries off the dynamic symtab command. For these the r_offset is from the
3631   // start of the first writeable segment in the Mach-O file.  So the offset
3632   // to this section from that segment is passed to this routine by the caller,
3633   // as the database_offset. Which is the difference of the section's starting
3634   // address and the first writable segment.
3635   //
3636   // NOTE: need add passing the database_offset to this routine.
3637 
3638   // We did not find an external relocation entry so look up the ReferenceValue
3639   // as an address of a symbol and if found return that symbol's name.
3640   SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
3641 
3642   return SymbolName;
3643 }
3644 
3645 static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
3646                                  DisassembleInfo *info,
3647                                  uint32_t ReferenceValue) {
3648   uint64_t n_value64;
3649   return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
3650 }
3651 
3652 namespace {
3653 
3654 // These are structs in the Objective-C meta data and read to produce the
3655 // comments for disassembly.  While these are part of the ABI they are no
3656 // public defintions.  So the are here not in include/llvm/BinaryFormat/MachO.h
3657 // .
3658 
3659 // The cfstring object in a 64-bit Mach-O file.
3660 struct cfstring64_t {
3661   uint64_t isa;        // class64_t * (64-bit pointer)
3662   uint64_t flags;      // flag bits
3663   uint64_t characters; // char * (64-bit pointer)
3664   uint64_t length;     // number of non-NULL characters in above
3665 };
3666 
3667 // The class object in a 64-bit Mach-O file.
3668 struct class64_t {
3669   uint64_t isa;        // class64_t * (64-bit pointer)
3670   uint64_t superclass; // class64_t * (64-bit pointer)
3671   uint64_t cache;      // Cache (64-bit pointer)
3672   uint64_t vtable;     // IMP * (64-bit pointer)
3673   uint64_t data;       // class_ro64_t * (64-bit pointer)
3674 };
3675 
3676 struct class32_t {
3677   uint32_t isa;        /* class32_t * (32-bit pointer) */
3678   uint32_t superclass; /* class32_t * (32-bit pointer) */
3679   uint32_t cache;      /* Cache (32-bit pointer) */
3680   uint32_t vtable;     /* IMP * (32-bit pointer) */
3681   uint32_t data;       /* class_ro32_t * (32-bit pointer) */
3682 };
3683 
3684 struct class_ro64_t {
3685   uint32_t flags;
3686   uint32_t instanceStart;
3687   uint32_t instanceSize;
3688   uint32_t reserved;
3689   uint64_t ivarLayout;     // const uint8_t * (64-bit pointer)
3690   uint64_t name;           // const char * (64-bit pointer)
3691   uint64_t baseMethods;    // const method_list_t * (64-bit pointer)
3692   uint64_t baseProtocols;  // const protocol_list_t * (64-bit pointer)
3693   uint64_t ivars;          // const ivar_list_t * (64-bit pointer)
3694   uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
3695   uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
3696 };
3697 
3698 struct class_ro32_t {
3699   uint32_t flags;
3700   uint32_t instanceStart;
3701   uint32_t instanceSize;
3702   uint32_t ivarLayout;     /* const uint8_t * (32-bit pointer) */
3703   uint32_t name;           /* const char * (32-bit pointer) */
3704   uint32_t baseMethods;    /* const method_list_t * (32-bit pointer) */
3705   uint32_t baseProtocols;  /* const protocol_list_t * (32-bit pointer) */
3706   uint32_t ivars;          /* const ivar_list_t * (32-bit pointer) */
3707   uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
3708   uint32_t baseProperties; /* const struct objc_property_list *
3709                                                    (32-bit pointer) */
3710 };
3711 
3712 /* Values for class_ro{64,32}_t->flags */
3713 #define RO_META (1 << 0)
3714 #define RO_ROOT (1 << 1)
3715 #define RO_HAS_CXX_STRUCTORS (1 << 2)
3716 
3717 struct method_list64_t {
3718   uint32_t entsize;
3719   uint32_t count;
3720   /* struct method64_t first;  These structures follow inline */
3721 };
3722 
3723 struct method_list32_t {
3724   uint32_t entsize;
3725   uint32_t count;
3726   /* struct method32_t first;  These structures follow inline */
3727 };
3728 
3729 struct method64_t {
3730   uint64_t name;  /* SEL (64-bit pointer) */
3731   uint64_t types; /* const char * (64-bit pointer) */
3732   uint64_t imp;   /* IMP (64-bit pointer) */
3733 };
3734 
3735 struct method32_t {
3736   uint32_t name;  /* SEL (32-bit pointer) */
3737   uint32_t types; /* const char * (32-bit pointer) */
3738   uint32_t imp;   /* IMP (32-bit pointer) */
3739 };
3740 
3741 struct protocol_list64_t {
3742   uint64_t count; /* uintptr_t (a 64-bit value) */
3743   /* struct protocol64_t * list[0];  These pointers follow inline */
3744 };
3745 
3746 struct protocol_list32_t {
3747   uint32_t count; /* uintptr_t (a 32-bit value) */
3748   /* struct protocol32_t * list[0];  These pointers follow inline */
3749 };
3750 
3751 struct protocol64_t {
3752   uint64_t isa;                     /* id * (64-bit pointer) */
3753   uint64_t name;                    /* const char * (64-bit pointer) */
3754   uint64_t protocols;               /* struct protocol_list64_t *
3755                                                     (64-bit pointer) */
3756   uint64_t instanceMethods;         /* method_list_t * (64-bit pointer) */
3757   uint64_t classMethods;            /* method_list_t * (64-bit pointer) */
3758   uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
3759   uint64_t optionalClassMethods;    /* method_list_t * (64-bit pointer) */
3760   uint64_t instanceProperties;      /* struct objc_property_list *
3761                                                        (64-bit pointer) */
3762 };
3763 
3764 struct protocol32_t {
3765   uint32_t isa;                     /* id * (32-bit pointer) */
3766   uint32_t name;                    /* const char * (32-bit pointer) */
3767   uint32_t protocols;               /* struct protocol_list_t *
3768                                                     (32-bit pointer) */
3769   uint32_t instanceMethods;         /* method_list_t * (32-bit pointer) */
3770   uint32_t classMethods;            /* method_list_t * (32-bit pointer) */
3771   uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
3772   uint32_t optionalClassMethods;    /* method_list_t * (32-bit pointer) */
3773   uint32_t instanceProperties;      /* struct objc_property_list *
3774                                                        (32-bit pointer) */
3775 };
3776 
3777 struct ivar_list64_t {
3778   uint32_t entsize;
3779   uint32_t count;
3780   /* struct ivar64_t first;  These structures follow inline */
3781 };
3782 
3783 struct ivar_list32_t {
3784   uint32_t entsize;
3785   uint32_t count;
3786   /* struct ivar32_t first;  These structures follow inline */
3787 };
3788 
3789 struct ivar64_t {
3790   uint64_t offset; /* uintptr_t * (64-bit pointer) */
3791   uint64_t name;   /* const char * (64-bit pointer) */
3792   uint64_t type;   /* const char * (64-bit pointer) */
3793   uint32_t alignment;
3794   uint32_t size;
3795 };
3796 
3797 struct ivar32_t {
3798   uint32_t offset; /* uintptr_t * (32-bit pointer) */
3799   uint32_t name;   /* const char * (32-bit pointer) */
3800   uint32_t type;   /* const char * (32-bit pointer) */
3801   uint32_t alignment;
3802   uint32_t size;
3803 };
3804 
3805 struct objc_property_list64 {
3806   uint32_t entsize;
3807   uint32_t count;
3808   /* struct objc_property64 first;  These structures follow inline */
3809 };
3810 
3811 struct objc_property_list32 {
3812   uint32_t entsize;
3813   uint32_t count;
3814   /* struct objc_property32 first;  These structures follow inline */
3815 };
3816 
3817 struct objc_property64 {
3818   uint64_t name;       /* const char * (64-bit pointer) */
3819   uint64_t attributes; /* const char * (64-bit pointer) */
3820 };
3821 
3822 struct objc_property32 {
3823   uint32_t name;       /* const char * (32-bit pointer) */
3824   uint32_t attributes; /* const char * (32-bit pointer) */
3825 };
3826 
3827 struct category64_t {
3828   uint64_t name;               /* const char * (64-bit pointer) */
3829   uint64_t cls;                /* struct class_t * (64-bit pointer) */
3830   uint64_t instanceMethods;    /* struct method_list_t * (64-bit pointer) */
3831   uint64_t classMethods;       /* struct method_list_t * (64-bit pointer) */
3832   uint64_t protocols;          /* struct protocol_list_t * (64-bit pointer) */
3833   uint64_t instanceProperties; /* struct objc_property_list *
3834                                   (64-bit pointer) */
3835 };
3836 
3837 struct category32_t {
3838   uint32_t name;               /* const char * (32-bit pointer) */
3839   uint32_t cls;                /* struct class_t * (32-bit pointer) */
3840   uint32_t instanceMethods;    /* struct method_list_t * (32-bit pointer) */
3841   uint32_t classMethods;       /* struct method_list_t * (32-bit pointer) */
3842   uint32_t protocols;          /* struct protocol_list_t * (32-bit pointer) */
3843   uint32_t instanceProperties; /* struct objc_property_list *
3844                                   (32-bit pointer) */
3845 };
3846 
3847 struct objc_image_info64 {
3848   uint32_t version;
3849   uint32_t flags;
3850 };
3851 struct objc_image_info32 {
3852   uint32_t version;
3853   uint32_t flags;
3854 };
3855 struct imageInfo_t {
3856   uint32_t version;
3857   uint32_t flags;
3858 };
3859 /* masks for objc_image_info.flags */
3860 #define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
3861 #define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
3862 #define OBJC_IMAGE_IS_SIMULATED (1 << 5)
3863 #define OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES (1 << 6)
3864 
3865 struct message_ref64 {
3866   uint64_t imp; /* IMP (64-bit pointer) */
3867   uint64_t sel; /* SEL (64-bit pointer) */
3868 };
3869 
3870 struct message_ref32 {
3871   uint32_t imp; /* IMP (32-bit pointer) */
3872   uint32_t sel; /* SEL (32-bit pointer) */
3873 };
3874 
3875 // Objective-C 1 (32-bit only) meta data structs.
3876 
3877 struct objc_module_t {
3878   uint32_t version;
3879   uint32_t size;
3880   uint32_t name;   /* char * (32-bit pointer) */
3881   uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
3882 };
3883 
3884 struct objc_symtab_t {
3885   uint32_t sel_ref_cnt;
3886   uint32_t refs; /* SEL * (32-bit pointer) */
3887   uint16_t cls_def_cnt;
3888   uint16_t cat_def_cnt;
3889   // uint32_t defs[1];        /* void * (32-bit pointer) variable size */
3890 };
3891 
3892 struct objc_class_t {
3893   uint32_t isa;         /* struct objc_class * (32-bit pointer) */
3894   uint32_t super_class; /* struct objc_class * (32-bit pointer) */
3895   uint32_t name;        /* const char * (32-bit pointer) */
3896   int32_t version;
3897   int32_t info;
3898   int32_t instance_size;
3899   uint32_t ivars;       /* struct objc_ivar_list * (32-bit pointer) */
3900   uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
3901   uint32_t cache;       /* struct objc_cache * (32-bit pointer) */
3902   uint32_t protocols;   /* struct objc_protocol_list * (32-bit pointer) */
3903 };
3904 
3905 #define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
3906 // class is not a metaclass
3907 #define CLS_CLASS 0x1
3908 // class is a metaclass
3909 #define CLS_META 0x2
3910 
3911 struct objc_category_t {
3912   uint32_t category_name;    /* char * (32-bit pointer) */
3913   uint32_t class_name;       /* char * (32-bit pointer) */
3914   uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
3915   uint32_t class_methods;    /* struct objc_method_list * (32-bit pointer) */
3916   uint32_t protocols;        /* struct objc_protocol_list * (32-bit ptr) */
3917 };
3918 
3919 struct objc_ivar_t {
3920   uint32_t ivar_name; /* char * (32-bit pointer) */
3921   uint32_t ivar_type; /* char * (32-bit pointer) */
3922   int32_t ivar_offset;
3923 };
3924 
3925 struct objc_ivar_list_t {
3926   int32_t ivar_count;
3927   // struct objc_ivar_t ivar_list[1];          /* variable length structure */
3928 };
3929 
3930 struct objc_method_list_t {
3931   uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
3932   int32_t method_count;
3933   // struct objc_method_t method_list[1];      /* variable length structure */
3934 };
3935 
3936 struct objc_method_t {
3937   uint32_t method_name;  /* SEL, aka struct objc_selector * (32-bit pointer) */
3938   uint32_t method_types; /* char * (32-bit pointer) */
3939   uint32_t method_imp;   /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
3940                             (32-bit pointer) */
3941 };
3942 
3943 struct objc_protocol_list_t {
3944   uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
3945   int32_t count;
3946   // uint32_t list[1];   /* Protocol *, aka struct objc_protocol_t *
3947   //                        (32-bit pointer) */
3948 };
3949 
3950 struct objc_protocol_t {
3951   uint32_t isa;              /* struct objc_class * (32-bit pointer) */
3952   uint32_t protocol_name;    /* char * (32-bit pointer) */
3953   uint32_t protocol_list;    /* struct objc_protocol_list * (32-bit pointer) */
3954   uint32_t instance_methods; /* struct objc_method_description_list *
3955                                 (32-bit pointer) */
3956   uint32_t class_methods;    /* struct objc_method_description_list *
3957                                 (32-bit pointer) */
3958 };
3959 
3960 struct objc_method_description_list_t {
3961   int32_t count;
3962   // struct objc_method_description_t list[1];
3963 };
3964 
3965 struct objc_method_description_t {
3966   uint32_t name;  /* SEL, aka struct objc_selector * (32-bit pointer) */
3967   uint32_t types; /* char * (32-bit pointer) */
3968 };
3969 
3970 inline void swapStruct(struct cfstring64_t &cfs) {
3971   sys::swapByteOrder(cfs.isa);
3972   sys::swapByteOrder(cfs.flags);
3973   sys::swapByteOrder(cfs.characters);
3974   sys::swapByteOrder(cfs.length);
3975 }
3976 
3977 inline void swapStruct(struct class64_t &c) {
3978   sys::swapByteOrder(c.isa);
3979   sys::swapByteOrder(c.superclass);
3980   sys::swapByteOrder(c.cache);
3981   sys::swapByteOrder(c.vtable);
3982   sys::swapByteOrder(c.data);
3983 }
3984 
3985 inline void swapStruct(struct class32_t &c) {
3986   sys::swapByteOrder(c.isa);
3987   sys::swapByteOrder(c.superclass);
3988   sys::swapByteOrder(c.cache);
3989   sys::swapByteOrder(c.vtable);
3990   sys::swapByteOrder(c.data);
3991 }
3992 
3993 inline void swapStruct(struct class_ro64_t &cro) {
3994   sys::swapByteOrder(cro.flags);
3995   sys::swapByteOrder(cro.instanceStart);
3996   sys::swapByteOrder(cro.instanceSize);
3997   sys::swapByteOrder(cro.reserved);
3998   sys::swapByteOrder(cro.ivarLayout);
3999   sys::swapByteOrder(cro.name);
4000   sys::swapByteOrder(cro.baseMethods);
4001   sys::swapByteOrder(cro.baseProtocols);
4002   sys::swapByteOrder(cro.ivars);
4003   sys::swapByteOrder(cro.weakIvarLayout);
4004   sys::swapByteOrder(cro.baseProperties);
4005 }
4006 
4007 inline void swapStruct(struct class_ro32_t &cro) {
4008   sys::swapByteOrder(cro.flags);
4009   sys::swapByteOrder(cro.instanceStart);
4010   sys::swapByteOrder(cro.instanceSize);
4011   sys::swapByteOrder(cro.ivarLayout);
4012   sys::swapByteOrder(cro.name);
4013   sys::swapByteOrder(cro.baseMethods);
4014   sys::swapByteOrder(cro.baseProtocols);
4015   sys::swapByteOrder(cro.ivars);
4016   sys::swapByteOrder(cro.weakIvarLayout);
4017   sys::swapByteOrder(cro.baseProperties);
4018 }
4019 
4020 inline void swapStruct(struct method_list64_t &ml) {
4021   sys::swapByteOrder(ml.entsize);
4022   sys::swapByteOrder(ml.count);
4023 }
4024 
4025 inline void swapStruct(struct method_list32_t &ml) {
4026   sys::swapByteOrder(ml.entsize);
4027   sys::swapByteOrder(ml.count);
4028 }
4029 
4030 inline void swapStruct(struct method64_t &m) {
4031   sys::swapByteOrder(m.name);
4032   sys::swapByteOrder(m.types);
4033   sys::swapByteOrder(m.imp);
4034 }
4035 
4036 inline void swapStruct(struct method32_t &m) {
4037   sys::swapByteOrder(m.name);
4038   sys::swapByteOrder(m.types);
4039   sys::swapByteOrder(m.imp);
4040 }
4041 
4042 inline void swapStruct(struct protocol_list64_t &pl) {
4043   sys::swapByteOrder(pl.count);
4044 }
4045 
4046 inline void swapStruct(struct protocol_list32_t &pl) {
4047   sys::swapByteOrder(pl.count);
4048 }
4049 
4050 inline void swapStruct(struct protocol64_t &p) {
4051   sys::swapByteOrder(p.isa);
4052   sys::swapByteOrder(p.name);
4053   sys::swapByteOrder(p.protocols);
4054   sys::swapByteOrder(p.instanceMethods);
4055   sys::swapByteOrder(p.classMethods);
4056   sys::swapByteOrder(p.optionalInstanceMethods);
4057   sys::swapByteOrder(p.optionalClassMethods);
4058   sys::swapByteOrder(p.instanceProperties);
4059 }
4060 
4061 inline void swapStruct(struct protocol32_t &p) {
4062   sys::swapByteOrder(p.isa);
4063   sys::swapByteOrder(p.name);
4064   sys::swapByteOrder(p.protocols);
4065   sys::swapByteOrder(p.instanceMethods);
4066   sys::swapByteOrder(p.classMethods);
4067   sys::swapByteOrder(p.optionalInstanceMethods);
4068   sys::swapByteOrder(p.optionalClassMethods);
4069   sys::swapByteOrder(p.instanceProperties);
4070 }
4071 
4072 inline void swapStruct(struct ivar_list64_t &il) {
4073   sys::swapByteOrder(il.entsize);
4074   sys::swapByteOrder(il.count);
4075 }
4076 
4077 inline void swapStruct(struct ivar_list32_t &il) {
4078   sys::swapByteOrder(il.entsize);
4079   sys::swapByteOrder(il.count);
4080 }
4081 
4082 inline void swapStruct(struct ivar64_t &i) {
4083   sys::swapByteOrder(i.offset);
4084   sys::swapByteOrder(i.name);
4085   sys::swapByteOrder(i.type);
4086   sys::swapByteOrder(i.alignment);
4087   sys::swapByteOrder(i.size);
4088 }
4089 
4090 inline void swapStruct(struct ivar32_t &i) {
4091   sys::swapByteOrder(i.offset);
4092   sys::swapByteOrder(i.name);
4093   sys::swapByteOrder(i.type);
4094   sys::swapByteOrder(i.alignment);
4095   sys::swapByteOrder(i.size);
4096 }
4097 
4098 inline void swapStruct(struct objc_property_list64 &pl) {
4099   sys::swapByteOrder(pl.entsize);
4100   sys::swapByteOrder(pl.count);
4101 }
4102 
4103 inline void swapStruct(struct objc_property_list32 &pl) {
4104   sys::swapByteOrder(pl.entsize);
4105   sys::swapByteOrder(pl.count);
4106 }
4107 
4108 inline void swapStruct(struct objc_property64 &op) {
4109   sys::swapByteOrder(op.name);
4110   sys::swapByteOrder(op.attributes);
4111 }
4112 
4113 inline void swapStruct(struct objc_property32 &op) {
4114   sys::swapByteOrder(op.name);
4115   sys::swapByteOrder(op.attributes);
4116 }
4117 
4118 inline void swapStruct(struct category64_t &c) {
4119   sys::swapByteOrder(c.name);
4120   sys::swapByteOrder(c.cls);
4121   sys::swapByteOrder(c.instanceMethods);
4122   sys::swapByteOrder(c.classMethods);
4123   sys::swapByteOrder(c.protocols);
4124   sys::swapByteOrder(c.instanceProperties);
4125 }
4126 
4127 inline void swapStruct(struct category32_t &c) {
4128   sys::swapByteOrder(c.name);
4129   sys::swapByteOrder(c.cls);
4130   sys::swapByteOrder(c.instanceMethods);
4131   sys::swapByteOrder(c.classMethods);
4132   sys::swapByteOrder(c.protocols);
4133   sys::swapByteOrder(c.instanceProperties);
4134 }
4135 
4136 inline void swapStruct(struct objc_image_info64 &o) {
4137   sys::swapByteOrder(o.version);
4138   sys::swapByteOrder(o.flags);
4139 }
4140 
4141 inline void swapStruct(struct objc_image_info32 &o) {
4142   sys::swapByteOrder(o.version);
4143   sys::swapByteOrder(o.flags);
4144 }
4145 
4146 inline void swapStruct(struct imageInfo_t &o) {
4147   sys::swapByteOrder(o.version);
4148   sys::swapByteOrder(o.flags);
4149 }
4150 
4151 inline void swapStruct(struct message_ref64 &mr) {
4152   sys::swapByteOrder(mr.imp);
4153   sys::swapByteOrder(mr.sel);
4154 }
4155 
4156 inline void swapStruct(struct message_ref32 &mr) {
4157   sys::swapByteOrder(mr.imp);
4158   sys::swapByteOrder(mr.sel);
4159 }
4160 
4161 inline void swapStruct(struct objc_module_t &module) {
4162   sys::swapByteOrder(module.version);
4163   sys::swapByteOrder(module.size);
4164   sys::swapByteOrder(module.name);
4165   sys::swapByteOrder(module.symtab);
4166 }
4167 
4168 inline void swapStruct(struct objc_symtab_t &symtab) {
4169   sys::swapByteOrder(symtab.sel_ref_cnt);
4170   sys::swapByteOrder(symtab.refs);
4171   sys::swapByteOrder(symtab.cls_def_cnt);
4172   sys::swapByteOrder(symtab.cat_def_cnt);
4173 }
4174 
4175 inline void swapStruct(struct objc_class_t &objc_class) {
4176   sys::swapByteOrder(objc_class.isa);
4177   sys::swapByteOrder(objc_class.super_class);
4178   sys::swapByteOrder(objc_class.name);
4179   sys::swapByteOrder(objc_class.version);
4180   sys::swapByteOrder(objc_class.info);
4181   sys::swapByteOrder(objc_class.instance_size);
4182   sys::swapByteOrder(objc_class.ivars);
4183   sys::swapByteOrder(objc_class.methodLists);
4184   sys::swapByteOrder(objc_class.cache);
4185   sys::swapByteOrder(objc_class.protocols);
4186 }
4187 
4188 inline void swapStruct(struct objc_category_t &objc_category) {
4189   sys::swapByteOrder(objc_category.category_name);
4190   sys::swapByteOrder(objc_category.class_name);
4191   sys::swapByteOrder(objc_category.instance_methods);
4192   sys::swapByteOrder(objc_category.class_methods);
4193   sys::swapByteOrder(objc_category.protocols);
4194 }
4195 
4196 inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
4197   sys::swapByteOrder(objc_ivar_list.ivar_count);
4198 }
4199 
4200 inline void swapStruct(struct objc_ivar_t &objc_ivar) {
4201   sys::swapByteOrder(objc_ivar.ivar_name);
4202   sys::swapByteOrder(objc_ivar.ivar_type);
4203   sys::swapByteOrder(objc_ivar.ivar_offset);
4204 }
4205 
4206 inline void swapStruct(struct objc_method_list_t &method_list) {
4207   sys::swapByteOrder(method_list.obsolete);
4208   sys::swapByteOrder(method_list.method_count);
4209 }
4210 
4211 inline void swapStruct(struct objc_method_t &method) {
4212   sys::swapByteOrder(method.method_name);
4213   sys::swapByteOrder(method.method_types);
4214   sys::swapByteOrder(method.method_imp);
4215 }
4216 
4217 inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
4218   sys::swapByteOrder(protocol_list.next);
4219   sys::swapByteOrder(protocol_list.count);
4220 }
4221 
4222 inline void swapStruct(struct objc_protocol_t &protocol) {
4223   sys::swapByteOrder(protocol.isa);
4224   sys::swapByteOrder(protocol.protocol_name);
4225   sys::swapByteOrder(protocol.protocol_list);
4226   sys::swapByteOrder(protocol.instance_methods);
4227   sys::swapByteOrder(protocol.class_methods);
4228 }
4229 
4230 inline void swapStruct(struct objc_method_description_list_t &mdl) {
4231   sys::swapByteOrder(mdl.count);
4232 }
4233 
4234 inline void swapStruct(struct objc_method_description_t &md) {
4235   sys::swapByteOrder(md.name);
4236   sys::swapByteOrder(md.types);
4237 }
4238 
4239 } // namespace
4240 
4241 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
4242                                                  struct DisassembleInfo *info);
4243 
4244 // get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
4245 // to an Objective-C class and returns the class name.  It is also passed the
4246 // address of the pointer, so when the pointer is zero as it can be in an .o
4247 // file, that is used to look for an external relocation entry with a symbol
4248 // name.
4249 static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
4250                                               uint64_t ReferenceValue,
4251                                               struct DisassembleInfo *info) {
4252   const char *r;
4253   uint32_t offset, left;
4254   SectionRef S;
4255 
4256   // The pointer_value can be 0 in an object file and have a relocation
4257   // entry for the class symbol at the ReferenceValue (the address of the
4258   // pointer).
4259   if (pointer_value == 0) {
4260     r = get_pointer_64(ReferenceValue, offset, left, S, info);
4261     if (r == nullptr || left < sizeof(uint64_t))
4262       return nullptr;
4263     uint64_t n_value;
4264     const char *symbol_name = get_symbol_64(offset, S, info, n_value);
4265     if (symbol_name == nullptr)
4266       return nullptr;
4267     const char *class_name = strrchr(symbol_name, '$');
4268     if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
4269       return class_name + 2;
4270     else
4271       return nullptr;
4272   }
4273 
4274   // The case were the pointer_value is non-zero and points to a class defined
4275   // in this Mach-O file.
4276   r = get_pointer_64(pointer_value, offset, left, S, info);
4277   if (r == nullptr || left < sizeof(struct class64_t))
4278     return nullptr;
4279   struct class64_t c;
4280   memcpy(&c, r, sizeof(struct class64_t));
4281   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4282     swapStruct(c);
4283   if (c.data == 0)
4284     return nullptr;
4285   r = get_pointer_64(c.data, offset, left, S, info);
4286   if (r == nullptr || left < sizeof(struct class_ro64_t))
4287     return nullptr;
4288   struct class_ro64_t cro;
4289   memcpy(&cro, r, sizeof(struct class_ro64_t));
4290   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4291     swapStruct(cro);
4292   if (cro.name == 0)
4293     return nullptr;
4294   const char *name = get_pointer_64(cro.name, offset, left, S, info);
4295   return name;
4296 }
4297 
4298 // get_objc2_64bit_cfstring_name is used for disassembly and is passed a
4299 // pointer to a cfstring and returns its name or nullptr.
4300 static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
4301                                                  struct DisassembleInfo *info) {
4302   const char *r, *name;
4303   uint32_t offset, left;
4304   SectionRef S;
4305   struct cfstring64_t cfs;
4306   uint64_t cfs_characters;
4307 
4308   r = get_pointer_64(ReferenceValue, offset, left, S, info);
4309   if (r == nullptr || left < sizeof(struct cfstring64_t))
4310     return nullptr;
4311   memcpy(&cfs, r, sizeof(struct cfstring64_t));
4312   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4313     swapStruct(cfs);
4314   if (cfs.characters == 0) {
4315     uint64_t n_value;
4316     const char *symbol_name = get_symbol_64(
4317         offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
4318     if (symbol_name == nullptr)
4319       return nullptr;
4320     cfs_characters = n_value;
4321   } else
4322     cfs_characters = cfs.characters;
4323   name = get_pointer_64(cfs_characters, offset, left, S, info);
4324 
4325   return name;
4326 }
4327 
4328 // get_objc2_64bit_selref() is used for disassembly and is passed a the address
4329 // of a pointer to an Objective-C selector reference when the pointer value is
4330 // zero as in a .o file and is likely to have a external relocation entry with
4331 // who's symbol's n_value is the real pointer to the selector name.  If that is
4332 // the case the real pointer to the selector name is returned else 0 is
4333 // returned
4334 static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
4335                                        struct DisassembleInfo *info) {
4336   uint32_t offset, left;
4337   SectionRef S;
4338 
4339   const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
4340   if (r == nullptr || left < sizeof(uint64_t))
4341     return 0;
4342   uint64_t n_value;
4343   const char *symbol_name = get_symbol_64(offset, S, info, n_value);
4344   if (symbol_name == nullptr)
4345     return 0;
4346   return n_value;
4347 }
4348 
4349 static const SectionRef get_section(MachOObjectFile *O, const char *segname,
4350                                     const char *sectname) {
4351   for (const SectionRef &Section : O->sections()) {
4352     StringRef SectName;
4353     Expected<StringRef> SecNameOrErr = Section.getName();
4354     if (SecNameOrErr)
4355       SectName = *SecNameOrErr;
4356     else
4357       consumeError(SecNameOrErr.takeError());
4358 
4359     DataRefImpl Ref = Section.getRawDataRefImpl();
4360     StringRef SegName = O->getSectionFinalSegmentName(Ref);
4361     if (SegName == segname && SectName == sectname)
4362       return Section;
4363   }
4364   return SectionRef();
4365 }
4366 
4367 static void
4368 walk_pointer_list_64(const char *listname, const SectionRef S,
4369                      MachOObjectFile *O, struct DisassembleInfo *info,
4370                      void (*func)(uint64_t, struct DisassembleInfo *info)) {
4371   if (S == SectionRef())
4372     return;
4373 
4374   StringRef SectName;
4375   Expected<StringRef> SecNameOrErr = S.getName();
4376   if (SecNameOrErr)
4377     SectName = *SecNameOrErr;
4378   else
4379     consumeError(SecNameOrErr.takeError());
4380 
4381   DataRefImpl Ref = S.getRawDataRefImpl();
4382   StringRef SegName = O->getSectionFinalSegmentName(Ref);
4383   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4384 
4385   StringRef BytesStr = unwrapOrError(S.getContents(), O->getFileName());
4386   const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
4387 
4388   for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
4389     uint32_t left = S.getSize() - i;
4390     uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
4391     uint64_t p = 0;
4392     memcpy(&p, Contents + i, size);
4393     if (i + sizeof(uint64_t) > S.getSize())
4394       outs() << listname << " list pointer extends past end of (" << SegName
4395              << "," << SectName << ") section\n";
4396     outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
4397 
4398     if (O->isLittleEndian() != sys::IsLittleEndianHost)
4399       sys::swapByteOrder(p);
4400 
4401     uint64_t n_value = 0;
4402     const char *name = get_symbol_64(i, S, info, n_value, p);
4403     if (name == nullptr)
4404       name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
4405 
4406     if (n_value != 0) {
4407       outs() << format("0x%" PRIx64, n_value);
4408       if (p != 0)
4409         outs() << " + " << format("0x%" PRIx64, p);
4410     } else
4411       outs() << format("0x%" PRIx64, p);
4412     if (name != nullptr)
4413       outs() << " " << name;
4414     outs() << "\n";
4415 
4416     p += n_value;
4417     if (func)
4418       func(p, info);
4419   }
4420 }
4421 
4422 static void
4423 walk_pointer_list_32(const char *listname, const SectionRef S,
4424                      MachOObjectFile *O, struct DisassembleInfo *info,
4425                      void (*func)(uint32_t, struct DisassembleInfo *info)) {
4426   if (S == SectionRef())
4427     return;
4428 
4429   StringRef SectName = unwrapOrError(S.getName(), O->getFileName());
4430   DataRefImpl Ref = S.getRawDataRefImpl();
4431   StringRef SegName = O->getSectionFinalSegmentName(Ref);
4432   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4433 
4434   StringRef BytesStr = unwrapOrError(S.getContents(), O->getFileName());
4435   const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
4436 
4437   for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
4438     uint32_t left = S.getSize() - i;
4439     uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
4440     uint32_t p = 0;
4441     memcpy(&p, Contents + i, size);
4442     if (i + sizeof(uint32_t) > S.getSize())
4443       outs() << listname << " list pointer extends past end of (" << SegName
4444              << "," << SectName << ") section\n";
4445     uint32_t Address = S.getAddress() + i;
4446     outs() << format("%08" PRIx32, Address) << " ";
4447 
4448     if (O->isLittleEndian() != sys::IsLittleEndianHost)
4449       sys::swapByteOrder(p);
4450     outs() << format("0x%" PRIx32, p);
4451 
4452     const char *name = get_symbol_32(i, S, info, p);
4453     if (name != nullptr)
4454       outs() << " " << name;
4455     outs() << "\n";
4456 
4457     if (func)
4458       func(p, info);
4459   }
4460 }
4461 
4462 static void print_layout_map(const char *layout_map, uint32_t left) {
4463   if (layout_map == nullptr)
4464     return;
4465   outs() << "                layout map: ";
4466   do {
4467     outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
4468     left--;
4469     layout_map++;
4470   } while (*layout_map != '\0' && left != 0);
4471   outs() << "\n";
4472 }
4473 
4474 static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
4475   uint32_t offset, left;
4476   SectionRef S;
4477   const char *layout_map;
4478 
4479   if (p == 0)
4480     return;
4481   layout_map = get_pointer_64(p, offset, left, S, info);
4482   print_layout_map(layout_map, left);
4483 }
4484 
4485 static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
4486   uint32_t offset, left;
4487   SectionRef S;
4488   const char *layout_map;
4489 
4490   if (p == 0)
4491     return;
4492   layout_map = get_pointer_32(p, offset, left, S, info);
4493   print_layout_map(layout_map, left);
4494 }
4495 
4496 static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
4497                                   const char *indent) {
4498   struct method_list64_t ml;
4499   struct method64_t m;
4500   const char *r;
4501   uint32_t offset, xoffset, left, i;
4502   SectionRef S, xS;
4503   const char *name, *sym_name;
4504   uint64_t n_value;
4505 
4506   r = get_pointer_64(p, offset, left, S, info);
4507   if (r == nullptr)
4508     return;
4509   memset(&ml, '\0', sizeof(struct method_list64_t));
4510   if (left < sizeof(struct method_list64_t)) {
4511     memcpy(&ml, r, left);
4512     outs() << "   (method_list_t entends past the end of the section)\n";
4513   } else
4514     memcpy(&ml, r, sizeof(struct method_list64_t));
4515   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4516     swapStruct(ml);
4517   outs() << indent << "\t\t   entsize " << ml.entsize << "\n";
4518   outs() << indent << "\t\t     count " << ml.count << "\n";
4519 
4520   p += sizeof(struct method_list64_t);
4521   offset += sizeof(struct method_list64_t);
4522   for (i = 0; i < ml.count; i++) {
4523     r = get_pointer_64(p, offset, left, S, info);
4524     if (r == nullptr)
4525       return;
4526     memset(&m, '\0', sizeof(struct method64_t));
4527     if (left < sizeof(struct method64_t)) {
4528       memcpy(&m, r, left);
4529       outs() << indent << "   (method_t extends past the end of the section)\n";
4530     } else
4531       memcpy(&m, r, sizeof(struct method64_t));
4532     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4533       swapStruct(m);
4534 
4535     outs() << indent << "\t\t      name ";
4536     sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
4537                              info, n_value, m.name);
4538     if (n_value != 0) {
4539       if (info->verbose && sym_name != nullptr)
4540         outs() << sym_name;
4541       else
4542         outs() << format("0x%" PRIx64, n_value);
4543       if (m.name != 0)
4544         outs() << " + " << format("0x%" PRIx64, m.name);
4545     } else
4546       outs() << format("0x%" PRIx64, m.name);
4547     name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
4548     if (name != nullptr)
4549       outs() << format(" %.*s", left, name);
4550     outs() << "\n";
4551 
4552     outs() << indent << "\t\t     types ";
4553     sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
4554                              info, n_value, m.types);
4555     if (n_value != 0) {
4556       if (info->verbose && sym_name != nullptr)
4557         outs() << sym_name;
4558       else
4559         outs() << format("0x%" PRIx64, n_value);
4560       if (m.types != 0)
4561         outs() << " + " << format("0x%" PRIx64, m.types);
4562     } else
4563       outs() << format("0x%" PRIx64, m.types);
4564     name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
4565     if (name != nullptr)
4566       outs() << format(" %.*s", left, name);
4567     outs() << "\n";
4568 
4569     outs() << indent << "\t\t       imp ";
4570     name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
4571                          n_value, m.imp);
4572     if (info->verbose && name == nullptr) {
4573       if (n_value != 0) {
4574         outs() << format("0x%" PRIx64, n_value) << " ";
4575         if (m.imp != 0)
4576           outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
4577       } else
4578         outs() << format("0x%" PRIx64, m.imp) << " ";
4579     }
4580     if (name != nullptr)
4581       outs() << name;
4582     outs() << "\n";
4583 
4584     p += sizeof(struct method64_t);
4585     offset += sizeof(struct method64_t);
4586   }
4587 }
4588 
4589 static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
4590                                   const char *indent) {
4591   struct method_list32_t ml;
4592   struct method32_t m;
4593   const char *r, *name;
4594   uint32_t offset, xoffset, left, i;
4595   SectionRef S, xS;
4596 
4597   r = get_pointer_32(p, offset, left, S, info);
4598   if (r == nullptr)
4599     return;
4600   memset(&ml, '\0', sizeof(struct method_list32_t));
4601   if (left < sizeof(struct method_list32_t)) {
4602     memcpy(&ml, r, left);
4603     outs() << "   (method_list_t entends past the end of the section)\n";
4604   } else
4605     memcpy(&ml, r, sizeof(struct method_list32_t));
4606   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4607     swapStruct(ml);
4608   outs() << indent << "\t\t   entsize " << ml.entsize << "\n";
4609   outs() << indent << "\t\t     count " << ml.count << "\n";
4610 
4611   p += sizeof(struct method_list32_t);
4612   offset += sizeof(struct method_list32_t);
4613   for (i = 0; i < ml.count; i++) {
4614     r = get_pointer_32(p, offset, left, S, info);
4615     if (r == nullptr)
4616       return;
4617     memset(&m, '\0', sizeof(struct method32_t));
4618     if (left < sizeof(struct method32_t)) {
4619       memcpy(&ml, r, left);
4620       outs() << indent << "   (method_t entends past the end of the section)\n";
4621     } else
4622       memcpy(&m, r, sizeof(struct method32_t));
4623     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4624       swapStruct(m);
4625 
4626     outs() << indent << "\t\t      name " << format("0x%" PRIx32, m.name);
4627     name = get_pointer_32(m.name, xoffset, left, xS, info);
4628     if (name != nullptr)
4629       outs() << format(" %.*s", left, name);
4630     outs() << "\n";
4631 
4632     outs() << indent << "\t\t     types " << format("0x%" PRIx32, m.types);
4633     name = get_pointer_32(m.types, xoffset, left, xS, info);
4634     if (name != nullptr)
4635       outs() << format(" %.*s", left, name);
4636     outs() << "\n";
4637 
4638     outs() << indent << "\t\t       imp " << format("0x%" PRIx32, m.imp);
4639     name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
4640                          m.imp);
4641     if (name != nullptr)
4642       outs() << " " << name;
4643     outs() << "\n";
4644 
4645     p += sizeof(struct method32_t);
4646     offset += sizeof(struct method32_t);
4647   }
4648 }
4649 
4650 static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
4651   uint32_t offset, left, xleft;
4652   SectionRef S;
4653   struct objc_method_list_t method_list;
4654   struct objc_method_t method;
4655   const char *r, *methods, *name, *SymbolName;
4656   int32_t i;
4657 
4658   r = get_pointer_32(p, offset, left, S, info, true);
4659   if (r == nullptr)
4660     return true;
4661 
4662   outs() << "\n";
4663   if (left > sizeof(struct objc_method_list_t)) {
4664     memcpy(&method_list, r, sizeof(struct objc_method_list_t));
4665   } else {
4666     outs() << "\t\t objc_method_list extends past end of the section\n";
4667     memset(&method_list, '\0', sizeof(struct objc_method_list_t));
4668     memcpy(&method_list, r, left);
4669   }
4670   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4671     swapStruct(method_list);
4672 
4673   outs() << "\t\t         obsolete "
4674          << format("0x%08" PRIx32, method_list.obsolete) << "\n";
4675   outs() << "\t\t     method_count " << method_list.method_count << "\n";
4676 
4677   methods = r + sizeof(struct objc_method_list_t);
4678   for (i = 0; i < method_list.method_count; i++) {
4679     if ((i + 1) * sizeof(struct objc_method_t) > left) {
4680       outs() << "\t\t remaining method's extend past the of the section\n";
4681       break;
4682     }
4683     memcpy(&method, methods + i * sizeof(struct objc_method_t),
4684            sizeof(struct objc_method_t));
4685     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4686       swapStruct(method);
4687 
4688     outs() << "\t\t      method_name "
4689            << format("0x%08" PRIx32, method.method_name);
4690     if (info->verbose) {
4691       name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
4692       if (name != nullptr)
4693         outs() << format(" %.*s", xleft, name);
4694       else
4695         outs() << " (not in an __OBJC section)";
4696     }
4697     outs() << "\n";
4698 
4699     outs() << "\t\t     method_types "
4700            << format("0x%08" PRIx32, method.method_types);
4701     if (info->verbose) {
4702       name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
4703       if (name != nullptr)
4704         outs() << format(" %.*s", xleft, name);
4705       else
4706         outs() << " (not in an __OBJC section)";
4707     }
4708     outs() << "\n";
4709 
4710     outs() << "\t\t       method_imp "
4711            << format("0x%08" PRIx32, method.method_imp) << " ";
4712     if (info->verbose) {
4713       SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
4714       if (SymbolName != nullptr)
4715         outs() << SymbolName;
4716     }
4717     outs() << "\n";
4718   }
4719   return false;
4720 }
4721 
4722 static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
4723   struct protocol_list64_t pl;
4724   uint64_t q, n_value;
4725   struct protocol64_t pc;
4726   const char *r;
4727   uint32_t offset, xoffset, left, i;
4728   SectionRef S, xS;
4729   const char *name, *sym_name;
4730 
4731   r = get_pointer_64(p, offset, left, S, info);
4732   if (r == nullptr)
4733     return;
4734   memset(&pl, '\0', sizeof(struct protocol_list64_t));
4735   if (left < sizeof(struct protocol_list64_t)) {
4736     memcpy(&pl, r, left);
4737     outs() << "   (protocol_list_t entends past the end of the section)\n";
4738   } else
4739     memcpy(&pl, r, sizeof(struct protocol_list64_t));
4740   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4741     swapStruct(pl);
4742   outs() << "                      count " << pl.count << "\n";
4743 
4744   p += sizeof(struct protocol_list64_t);
4745   offset += sizeof(struct protocol_list64_t);
4746   for (i = 0; i < pl.count; i++) {
4747     r = get_pointer_64(p, offset, left, S, info);
4748     if (r == nullptr)
4749       return;
4750     q = 0;
4751     if (left < sizeof(uint64_t)) {
4752       memcpy(&q, r, left);
4753       outs() << "   (protocol_t * entends past the end of the section)\n";
4754     } else
4755       memcpy(&q, r, sizeof(uint64_t));
4756     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4757       sys::swapByteOrder(q);
4758 
4759     outs() << "\t\t      list[" << i << "] ";
4760     sym_name = get_symbol_64(offset, S, info, n_value, q);
4761     if (n_value != 0) {
4762       if (info->verbose && sym_name != nullptr)
4763         outs() << sym_name;
4764       else
4765         outs() << format("0x%" PRIx64, n_value);
4766       if (q != 0)
4767         outs() << " + " << format("0x%" PRIx64, q);
4768     } else
4769       outs() << format("0x%" PRIx64, q);
4770     outs() << " (struct protocol_t *)\n";
4771 
4772     r = get_pointer_64(q + n_value, offset, left, S, info);
4773     if (r == nullptr)
4774       return;
4775     memset(&pc, '\0', sizeof(struct protocol64_t));
4776     if (left < sizeof(struct protocol64_t)) {
4777       memcpy(&pc, r, left);
4778       outs() << "   (protocol_t entends past the end of the section)\n";
4779     } else
4780       memcpy(&pc, r, sizeof(struct protocol64_t));
4781     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4782       swapStruct(pc);
4783 
4784     outs() << "\t\t\t      isa " << format("0x%" PRIx64, pc.isa) << "\n";
4785 
4786     outs() << "\t\t\t     name ";
4787     sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
4788                              info, n_value, pc.name);
4789     if (n_value != 0) {
4790       if (info->verbose && sym_name != nullptr)
4791         outs() << sym_name;
4792       else
4793         outs() << format("0x%" PRIx64, n_value);
4794       if (pc.name != 0)
4795         outs() << " + " << format("0x%" PRIx64, pc.name);
4796     } else
4797       outs() << format("0x%" PRIx64, pc.name);
4798     name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
4799     if (name != nullptr)
4800       outs() << format(" %.*s", left, name);
4801     outs() << "\n";
4802 
4803     outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
4804 
4805     outs() << "\t\t  instanceMethods ";
4806     sym_name =
4807         get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
4808                       S, info, n_value, pc.instanceMethods);
4809     if (n_value != 0) {
4810       if (info->verbose && sym_name != nullptr)
4811         outs() << sym_name;
4812       else
4813         outs() << format("0x%" PRIx64, n_value);
4814       if (pc.instanceMethods != 0)
4815         outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
4816     } else
4817       outs() << format("0x%" PRIx64, pc.instanceMethods);
4818     outs() << " (struct method_list_t *)\n";
4819     if (pc.instanceMethods + n_value != 0)
4820       print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
4821 
4822     outs() << "\t\t     classMethods ";
4823     sym_name =
4824         get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
4825                       info, n_value, pc.classMethods);
4826     if (n_value != 0) {
4827       if (info->verbose && sym_name != nullptr)
4828         outs() << sym_name;
4829       else
4830         outs() << format("0x%" PRIx64, n_value);
4831       if (pc.classMethods != 0)
4832         outs() << " + " << format("0x%" PRIx64, pc.classMethods);
4833     } else
4834       outs() << format("0x%" PRIx64, pc.classMethods);
4835     outs() << " (struct method_list_t *)\n";
4836     if (pc.classMethods + n_value != 0)
4837       print_method_list64_t(pc.classMethods + n_value, info, "\t");
4838 
4839     outs() << "\t  optionalInstanceMethods "
4840            << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
4841     outs() << "\t     optionalClassMethods "
4842            << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
4843     outs() << "\t       instanceProperties "
4844            << format("0x%" PRIx64, pc.instanceProperties) << "\n";
4845 
4846     p += sizeof(uint64_t);
4847     offset += sizeof(uint64_t);
4848   }
4849 }
4850 
4851 static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
4852   struct protocol_list32_t pl;
4853   uint32_t q;
4854   struct protocol32_t pc;
4855   const char *r;
4856   uint32_t offset, xoffset, left, i;
4857   SectionRef S, xS;
4858   const char *name;
4859 
4860   r = get_pointer_32(p, offset, left, S, info);
4861   if (r == nullptr)
4862     return;
4863   memset(&pl, '\0', sizeof(struct protocol_list32_t));
4864   if (left < sizeof(struct protocol_list32_t)) {
4865     memcpy(&pl, r, left);
4866     outs() << "   (protocol_list_t entends past the end of the section)\n";
4867   } else
4868     memcpy(&pl, r, sizeof(struct protocol_list32_t));
4869   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4870     swapStruct(pl);
4871   outs() << "                      count " << pl.count << "\n";
4872 
4873   p += sizeof(struct protocol_list32_t);
4874   offset += sizeof(struct protocol_list32_t);
4875   for (i = 0; i < pl.count; i++) {
4876     r = get_pointer_32(p, offset, left, S, info);
4877     if (r == nullptr)
4878       return;
4879     q = 0;
4880     if (left < sizeof(uint32_t)) {
4881       memcpy(&q, r, left);
4882       outs() << "   (protocol_t * entends past the end of the section)\n";
4883     } else
4884       memcpy(&q, r, sizeof(uint32_t));
4885     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4886       sys::swapByteOrder(q);
4887     outs() << "\t\t      list[" << i << "] " << format("0x%" PRIx32, q)
4888            << " (struct protocol_t *)\n";
4889     r = get_pointer_32(q, offset, left, S, info);
4890     if (r == nullptr)
4891       return;
4892     memset(&pc, '\0', sizeof(struct protocol32_t));
4893     if (left < sizeof(struct protocol32_t)) {
4894       memcpy(&pc, r, left);
4895       outs() << "   (protocol_t entends past the end of the section)\n";
4896     } else
4897       memcpy(&pc, r, sizeof(struct protocol32_t));
4898     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4899       swapStruct(pc);
4900     outs() << "\t\t\t      isa " << format("0x%" PRIx32, pc.isa) << "\n";
4901     outs() << "\t\t\t     name " << format("0x%" PRIx32, pc.name);
4902     name = get_pointer_32(pc.name, xoffset, left, xS, info);
4903     if (name != nullptr)
4904       outs() << format(" %.*s", left, name);
4905     outs() << "\n";
4906     outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
4907     outs() << "\t\t  instanceMethods "
4908            << format("0x%" PRIx32, pc.instanceMethods)
4909            << " (struct method_list_t *)\n";
4910     if (pc.instanceMethods != 0)
4911       print_method_list32_t(pc.instanceMethods, info, "\t");
4912     outs() << "\t\t     classMethods " << format("0x%" PRIx32, pc.classMethods)
4913            << " (struct method_list_t *)\n";
4914     if (pc.classMethods != 0)
4915       print_method_list32_t(pc.classMethods, info, "\t");
4916     outs() << "\t  optionalInstanceMethods "
4917            << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
4918     outs() << "\t     optionalClassMethods "
4919            << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
4920     outs() << "\t       instanceProperties "
4921            << format("0x%" PRIx32, pc.instanceProperties) << "\n";
4922     p += sizeof(uint32_t);
4923     offset += sizeof(uint32_t);
4924   }
4925 }
4926 
4927 static void print_indent(uint32_t indent) {
4928   for (uint32_t i = 0; i < indent;) {
4929     if (indent - i >= 8) {
4930       outs() << "\t";
4931       i += 8;
4932     } else {
4933       for (uint32_t j = i; j < indent; j++)
4934         outs() << " ";
4935       return;
4936     }
4937   }
4938 }
4939 
4940 static bool print_method_description_list(uint32_t p, uint32_t indent,
4941                                           struct DisassembleInfo *info) {
4942   uint32_t offset, left, xleft;
4943   SectionRef S;
4944   struct objc_method_description_list_t mdl;
4945   struct objc_method_description_t md;
4946   const char *r, *list, *name;
4947   int32_t i;
4948 
4949   r = get_pointer_32(p, offset, left, S, info, true);
4950   if (r == nullptr)
4951     return true;
4952 
4953   outs() << "\n";
4954   if (left > sizeof(struct objc_method_description_list_t)) {
4955     memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
4956   } else {
4957     print_indent(indent);
4958     outs() << " objc_method_description_list extends past end of the section\n";
4959     memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
4960     memcpy(&mdl, r, left);
4961   }
4962   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4963     swapStruct(mdl);
4964 
4965   print_indent(indent);
4966   outs() << "        count " << mdl.count << "\n";
4967 
4968   list = r + sizeof(struct objc_method_description_list_t);
4969   for (i = 0; i < mdl.count; i++) {
4970     if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
4971       print_indent(indent);
4972       outs() << " remaining list entries extend past the of the section\n";
4973       break;
4974     }
4975     print_indent(indent);
4976     outs() << "        list[" << i << "]\n";
4977     memcpy(&md, list + i * sizeof(struct objc_method_description_t),
4978            sizeof(struct objc_method_description_t));
4979     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4980       swapStruct(md);
4981 
4982     print_indent(indent);
4983     outs() << "             name " << format("0x%08" PRIx32, md.name);
4984     if (info->verbose) {
4985       name = get_pointer_32(md.name, offset, xleft, S, info, true);
4986       if (name != nullptr)
4987         outs() << format(" %.*s", xleft, name);
4988       else
4989         outs() << " (not in an __OBJC section)";
4990     }
4991     outs() << "\n";
4992 
4993     print_indent(indent);
4994     outs() << "            types " << format("0x%08" PRIx32, md.types);
4995     if (info->verbose) {
4996       name = get_pointer_32(md.types, offset, xleft, S, info, true);
4997       if (name != nullptr)
4998         outs() << format(" %.*s", xleft, name);
4999       else
5000         outs() << " (not in an __OBJC section)";
5001     }
5002     outs() << "\n";
5003   }
5004   return false;
5005 }
5006 
5007 static bool print_protocol_list(uint32_t p, uint32_t indent,
5008                                 struct DisassembleInfo *info);
5009 
5010 static bool print_protocol(uint32_t p, uint32_t indent,
5011                            struct DisassembleInfo *info) {
5012   uint32_t offset, left;
5013   SectionRef S;
5014   struct objc_protocol_t protocol;
5015   const char *r, *name;
5016 
5017   r = get_pointer_32(p, offset, left, S, info, true);
5018   if (r == nullptr)
5019     return true;
5020 
5021   outs() << "\n";
5022   if (left >= sizeof(struct objc_protocol_t)) {
5023     memcpy(&protocol, r, sizeof(struct objc_protocol_t));
5024   } else {
5025     print_indent(indent);
5026     outs() << "            Protocol extends past end of the section\n";
5027     memset(&protocol, '\0', sizeof(struct objc_protocol_t));
5028     memcpy(&protocol, r, left);
5029   }
5030   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5031     swapStruct(protocol);
5032 
5033   print_indent(indent);
5034   outs() << "              isa " << format("0x%08" PRIx32, protocol.isa)
5035          << "\n";
5036 
5037   print_indent(indent);
5038   outs() << "    protocol_name "
5039          << format("0x%08" PRIx32, protocol.protocol_name);
5040   if (info->verbose) {
5041     name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
5042     if (name != nullptr)
5043       outs() << format(" %.*s", left, name);
5044     else
5045       outs() << " (not in an __OBJC section)";
5046   }
5047   outs() << "\n";
5048 
5049   print_indent(indent);
5050   outs() << "    protocol_list "
5051          << format("0x%08" PRIx32, protocol.protocol_list);
5052   if (print_protocol_list(protocol.protocol_list, indent + 4, info))
5053     outs() << " (not in an __OBJC section)\n";
5054 
5055   print_indent(indent);
5056   outs() << " instance_methods "
5057          << format("0x%08" PRIx32, protocol.instance_methods);
5058   if (print_method_description_list(protocol.instance_methods, indent, info))
5059     outs() << " (not in an __OBJC section)\n";
5060 
5061   print_indent(indent);
5062   outs() << "    class_methods "
5063          << format("0x%08" PRIx32, protocol.class_methods);
5064   if (print_method_description_list(protocol.class_methods, indent, info))
5065     outs() << " (not in an __OBJC section)\n";
5066 
5067   return false;
5068 }
5069 
5070 static bool print_protocol_list(uint32_t p, uint32_t indent,
5071                                 struct DisassembleInfo *info) {
5072   uint32_t offset, left, l;
5073   SectionRef S;
5074   struct objc_protocol_list_t protocol_list;
5075   const char *r, *list;
5076   int32_t i;
5077 
5078   r = get_pointer_32(p, offset, left, S, info, true);
5079   if (r == nullptr)
5080     return true;
5081 
5082   outs() << "\n";
5083   if (left > sizeof(struct objc_protocol_list_t)) {
5084     memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
5085   } else {
5086     outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
5087     memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
5088     memcpy(&protocol_list, r, left);
5089   }
5090   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5091     swapStruct(protocol_list);
5092 
5093   print_indent(indent);
5094   outs() << "         next " << format("0x%08" PRIx32, protocol_list.next)
5095          << "\n";
5096   print_indent(indent);
5097   outs() << "        count " << protocol_list.count << "\n";
5098 
5099   list = r + sizeof(struct objc_protocol_list_t);
5100   for (i = 0; i < protocol_list.count; i++) {
5101     if ((i + 1) * sizeof(uint32_t) > left) {
5102       outs() << "\t\t remaining list entries extend past the of the section\n";
5103       break;
5104     }
5105     memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
5106     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5107       sys::swapByteOrder(l);
5108 
5109     print_indent(indent);
5110     outs() << "      list[" << i << "] " << format("0x%08" PRIx32, l);
5111     if (print_protocol(l, indent, info))
5112       outs() << "(not in an __OBJC section)\n";
5113   }
5114   return false;
5115 }
5116 
5117 static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
5118   struct ivar_list64_t il;
5119   struct ivar64_t i;
5120   const char *r;
5121   uint32_t offset, xoffset, left, j;
5122   SectionRef S, xS;
5123   const char *name, *sym_name, *ivar_offset_p;
5124   uint64_t ivar_offset, n_value;
5125 
5126   r = get_pointer_64(p, offset, left, S, info);
5127   if (r == nullptr)
5128     return;
5129   memset(&il, '\0', sizeof(struct ivar_list64_t));
5130   if (left < sizeof(struct ivar_list64_t)) {
5131     memcpy(&il, r, left);
5132     outs() << "   (ivar_list_t entends past the end of the section)\n";
5133   } else
5134     memcpy(&il, r, sizeof(struct ivar_list64_t));
5135   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5136     swapStruct(il);
5137   outs() << "                    entsize " << il.entsize << "\n";
5138   outs() << "                      count " << il.count << "\n";
5139 
5140   p += sizeof(struct ivar_list64_t);
5141   offset += sizeof(struct ivar_list64_t);
5142   for (j = 0; j < il.count; j++) {
5143     r = get_pointer_64(p, offset, left, S, info);
5144     if (r == nullptr)
5145       return;
5146     memset(&i, '\0', sizeof(struct ivar64_t));
5147     if (left < sizeof(struct ivar64_t)) {
5148       memcpy(&i, r, left);
5149       outs() << "   (ivar_t entends past the end of the section)\n";
5150     } else
5151       memcpy(&i, r, sizeof(struct ivar64_t));
5152     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5153       swapStruct(i);
5154 
5155     outs() << "\t\t\t   offset ";
5156     sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
5157                              info, n_value, i.offset);
5158     if (n_value != 0) {
5159       if (info->verbose && sym_name != nullptr)
5160         outs() << sym_name;
5161       else
5162         outs() << format("0x%" PRIx64, n_value);
5163       if (i.offset != 0)
5164         outs() << " + " << format("0x%" PRIx64, i.offset);
5165     } else
5166       outs() << format("0x%" PRIx64, i.offset);
5167     ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
5168     if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
5169       memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
5170       if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5171         sys::swapByteOrder(ivar_offset);
5172       outs() << " " << ivar_offset << "\n";
5173     } else
5174       outs() << "\n";
5175 
5176     outs() << "\t\t\t     name ";
5177     sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
5178                              n_value, i.name);
5179     if (n_value != 0) {
5180       if (info->verbose && sym_name != nullptr)
5181         outs() << sym_name;
5182       else
5183         outs() << format("0x%" PRIx64, n_value);
5184       if (i.name != 0)
5185         outs() << " + " << format("0x%" PRIx64, i.name);
5186     } else
5187       outs() << format("0x%" PRIx64, i.name);
5188     name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
5189     if (name != nullptr)
5190       outs() << format(" %.*s", left, name);
5191     outs() << "\n";
5192 
5193     outs() << "\t\t\t     type ";
5194     sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
5195                              n_value, i.name);
5196     name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
5197     if (n_value != 0) {
5198       if (info->verbose && sym_name != nullptr)
5199         outs() << sym_name;
5200       else
5201         outs() << format("0x%" PRIx64, n_value);
5202       if (i.type != 0)
5203         outs() << " + " << format("0x%" PRIx64, i.type);
5204     } else
5205       outs() << format("0x%" PRIx64, i.type);
5206     if (name != nullptr)
5207       outs() << format(" %.*s", left, name);
5208     outs() << "\n";
5209 
5210     outs() << "\t\t\talignment " << i.alignment << "\n";
5211     outs() << "\t\t\t     size " << i.size << "\n";
5212 
5213     p += sizeof(struct ivar64_t);
5214     offset += sizeof(struct ivar64_t);
5215   }
5216 }
5217 
5218 static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
5219   struct ivar_list32_t il;
5220   struct ivar32_t i;
5221   const char *r;
5222   uint32_t offset, xoffset, left, j;
5223   SectionRef S, xS;
5224   const char *name, *ivar_offset_p;
5225   uint32_t ivar_offset;
5226 
5227   r = get_pointer_32(p, offset, left, S, info);
5228   if (r == nullptr)
5229     return;
5230   memset(&il, '\0', sizeof(struct ivar_list32_t));
5231   if (left < sizeof(struct ivar_list32_t)) {
5232     memcpy(&il, r, left);
5233     outs() << "   (ivar_list_t entends past the end of the section)\n";
5234   } else
5235     memcpy(&il, r, sizeof(struct ivar_list32_t));
5236   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5237     swapStruct(il);
5238   outs() << "                    entsize " << il.entsize << "\n";
5239   outs() << "                      count " << il.count << "\n";
5240 
5241   p += sizeof(struct ivar_list32_t);
5242   offset += sizeof(struct ivar_list32_t);
5243   for (j = 0; j < il.count; j++) {
5244     r = get_pointer_32(p, offset, left, S, info);
5245     if (r == nullptr)
5246       return;
5247     memset(&i, '\0', sizeof(struct ivar32_t));
5248     if (left < sizeof(struct ivar32_t)) {
5249       memcpy(&i, r, left);
5250       outs() << "   (ivar_t entends past the end of the section)\n";
5251     } else
5252       memcpy(&i, r, sizeof(struct ivar32_t));
5253     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5254       swapStruct(i);
5255 
5256     outs() << "\t\t\t   offset " << format("0x%" PRIx32, i.offset);
5257     ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
5258     if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
5259       memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
5260       if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5261         sys::swapByteOrder(ivar_offset);
5262       outs() << " " << ivar_offset << "\n";
5263     } else
5264       outs() << "\n";
5265 
5266     outs() << "\t\t\t     name " << format("0x%" PRIx32, i.name);
5267     name = get_pointer_32(i.name, xoffset, left, xS, info);
5268     if (name != nullptr)
5269       outs() << format(" %.*s", left, name);
5270     outs() << "\n";
5271 
5272     outs() << "\t\t\t     type " << format("0x%" PRIx32, i.type);
5273     name = get_pointer_32(i.type, xoffset, left, xS, info);
5274     if (name != nullptr)
5275       outs() << format(" %.*s", left, name);
5276     outs() << "\n";
5277 
5278     outs() << "\t\t\talignment " << i.alignment << "\n";
5279     outs() << "\t\t\t     size " << i.size << "\n";
5280 
5281     p += sizeof(struct ivar32_t);
5282     offset += sizeof(struct ivar32_t);
5283   }
5284 }
5285 
5286 static void print_objc_property_list64(uint64_t p,
5287                                        struct DisassembleInfo *info) {
5288   struct objc_property_list64 opl;
5289   struct objc_property64 op;
5290   const char *r;
5291   uint32_t offset, xoffset, left, j;
5292   SectionRef S, xS;
5293   const char *name, *sym_name;
5294   uint64_t n_value;
5295 
5296   r = get_pointer_64(p, offset, left, S, info);
5297   if (r == nullptr)
5298     return;
5299   memset(&opl, '\0', sizeof(struct objc_property_list64));
5300   if (left < sizeof(struct objc_property_list64)) {
5301     memcpy(&opl, r, left);
5302     outs() << "   (objc_property_list entends past the end of the section)\n";
5303   } else
5304     memcpy(&opl, r, sizeof(struct objc_property_list64));
5305   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5306     swapStruct(opl);
5307   outs() << "                    entsize " << opl.entsize << "\n";
5308   outs() << "                      count " << opl.count << "\n";
5309 
5310   p += sizeof(struct objc_property_list64);
5311   offset += sizeof(struct objc_property_list64);
5312   for (j = 0; j < opl.count; j++) {
5313     r = get_pointer_64(p, offset, left, S, info);
5314     if (r == nullptr)
5315       return;
5316     memset(&op, '\0', sizeof(struct objc_property64));
5317     if (left < sizeof(struct objc_property64)) {
5318       memcpy(&op, r, left);
5319       outs() << "   (objc_property entends past the end of the section)\n";
5320     } else
5321       memcpy(&op, r, sizeof(struct objc_property64));
5322     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5323       swapStruct(op);
5324 
5325     outs() << "\t\t\t     name ";
5326     sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
5327                              info, n_value, op.name);
5328     if (n_value != 0) {
5329       if (info->verbose && sym_name != nullptr)
5330         outs() << sym_name;
5331       else
5332         outs() << format("0x%" PRIx64, n_value);
5333       if (op.name != 0)
5334         outs() << " + " << format("0x%" PRIx64, op.name);
5335     } else
5336       outs() << format("0x%" PRIx64, op.name);
5337     name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
5338     if (name != nullptr)
5339       outs() << format(" %.*s", left, name);
5340     outs() << "\n";
5341 
5342     outs() << "\t\t\tattributes ";
5343     sym_name =
5344         get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
5345                       info, n_value, op.attributes);
5346     if (n_value != 0) {
5347       if (info->verbose && sym_name != nullptr)
5348         outs() << sym_name;
5349       else
5350         outs() << format("0x%" PRIx64, n_value);
5351       if (op.attributes != 0)
5352         outs() << " + " << format("0x%" PRIx64, op.attributes);
5353     } else
5354       outs() << format("0x%" PRIx64, op.attributes);
5355     name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
5356     if (name != nullptr)
5357       outs() << format(" %.*s", left, name);
5358     outs() << "\n";
5359 
5360     p += sizeof(struct objc_property64);
5361     offset += sizeof(struct objc_property64);
5362   }
5363 }
5364 
5365 static void print_objc_property_list32(uint32_t p,
5366                                        struct DisassembleInfo *info) {
5367   struct objc_property_list32 opl;
5368   struct objc_property32 op;
5369   const char *r;
5370   uint32_t offset, xoffset, left, j;
5371   SectionRef S, xS;
5372   const char *name;
5373 
5374   r = get_pointer_32(p, offset, left, S, info);
5375   if (r == nullptr)
5376     return;
5377   memset(&opl, '\0', sizeof(struct objc_property_list32));
5378   if (left < sizeof(struct objc_property_list32)) {
5379     memcpy(&opl, r, left);
5380     outs() << "   (objc_property_list entends past the end of the section)\n";
5381   } else
5382     memcpy(&opl, r, sizeof(struct objc_property_list32));
5383   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5384     swapStruct(opl);
5385   outs() << "                    entsize " << opl.entsize << "\n";
5386   outs() << "                      count " << opl.count << "\n";
5387 
5388   p += sizeof(struct objc_property_list32);
5389   offset += sizeof(struct objc_property_list32);
5390   for (j = 0; j < opl.count; j++) {
5391     r = get_pointer_32(p, offset, left, S, info);
5392     if (r == nullptr)
5393       return;
5394     memset(&op, '\0', sizeof(struct objc_property32));
5395     if (left < sizeof(struct objc_property32)) {
5396       memcpy(&op, r, left);
5397       outs() << "   (objc_property entends past the end of the section)\n";
5398     } else
5399       memcpy(&op, r, sizeof(struct objc_property32));
5400     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5401       swapStruct(op);
5402 
5403     outs() << "\t\t\t     name " << format("0x%" PRIx32, op.name);
5404     name = get_pointer_32(op.name, xoffset, left, xS, info);
5405     if (name != nullptr)
5406       outs() << format(" %.*s", left, name);
5407     outs() << "\n";
5408 
5409     outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
5410     name = get_pointer_32(op.attributes, xoffset, left, xS, info);
5411     if (name != nullptr)
5412       outs() << format(" %.*s", left, name);
5413     outs() << "\n";
5414 
5415     p += sizeof(struct objc_property32);
5416     offset += sizeof(struct objc_property32);
5417   }
5418 }
5419 
5420 static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
5421                                bool &is_meta_class) {
5422   struct class_ro64_t cro;
5423   const char *r;
5424   uint32_t offset, xoffset, left;
5425   SectionRef S, xS;
5426   const char *name, *sym_name;
5427   uint64_t n_value;
5428 
5429   r = get_pointer_64(p, offset, left, S, info);
5430   if (r == nullptr || left < sizeof(struct class_ro64_t))
5431     return false;
5432   memcpy(&cro, r, sizeof(struct class_ro64_t));
5433   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5434     swapStruct(cro);
5435   outs() << "                    flags " << format("0x%" PRIx32, cro.flags);
5436   if (cro.flags & RO_META)
5437     outs() << " RO_META";
5438   if (cro.flags & RO_ROOT)
5439     outs() << " RO_ROOT";
5440   if (cro.flags & RO_HAS_CXX_STRUCTORS)
5441     outs() << " RO_HAS_CXX_STRUCTORS";
5442   outs() << "\n";
5443   outs() << "            instanceStart " << cro.instanceStart << "\n";
5444   outs() << "             instanceSize " << cro.instanceSize << "\n";
5445   outs() << "                 reserved " << format("0x%" PRIx32, cro.reserved)
5446          << "\n";
5447   outs() << "               ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
5448          << "\n";
5449   print_layout_map64(cro.ivarLayout, info);
5450 
5451   outs() << "                     name ";
5452   sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
5453                            info, n_value, cro.name);
5454   if (n_value != 0) {
5455     if (info->verbose && sym_name != nullptr)
5456       outs() << sym_name;
5457     else
5458       outs() << format("0x%" PRIx64, n_value);
5459     if (cro.name != 0)
5460       outs() << " + " << format("0x%" PRIx64, cro.name);
5461   } else
5462     outs() << format("0x%" PRIx64, cro.name);
5463   name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
5464   if (name != nullptr)
5465     outs() << format(" %.*s", left, name);
5466   outs() << "\n";
5467 
5468   outs() << "              baseMethods ";
5469   sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
5470                            S, info, n_value, cro.baseMethods);
5471   if (n_value != 0) {
5472     if (info->verbose && sym_name != nullptr)
5473       outs() << sym_name;
5474     else
5475       outs() << format("0x%" PRIx64, n_value);
5476     if (cro.baseMethods != 0)
5477       outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
5478   } else
5479     outs() << format("0x%" PRIx64, cro.baseMethods);
5480   outs() << " (struct method_list_t *)\n";
5481   if (cro.baseMethods + n_value != 0)
5482     print_method_list64_t(cro.baseMethods + n_value, info, "");
5483 
5484   outs() << "            baseProtocols ";
5485   sym_name =
5486       get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
5487                     info, n_value, cro.baseProtocols);
5488   if (n_value != 0) {
5489     if (info->verbose && sym_name != nullptr)
5490       outs() << sym_name;
5491     else
5492       outs() << format("0x%" PRIx64, n_value);
5493     if (cro.baseProtocols != 0)
5494       outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
5495   } else
5496     outs() << format("0x%" PRIx64, cro.baseProtocols);
5497   outs() << "\n";
5498   if (cro.baseProtocols + n_value != 0)
5499     print_protocol_list64_t(cro.baseProtocols + n_value, info);
5500 
5501   outs() << "                    ivars ";
5502   sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
5503                            info, n_value, cro.ivars);
5504   if (n_value != 0) {
5505     if (info->verbose && sym_name != nullptr)
5506       outs() << sym_name;
5507     else
5508       outs() << format("0x%" PRIx64, n_value);
5509     if (cro.ivars != 0)
5510       outs() << " + " << format("0x%" PRIx64, cro.ivars);
5511   } else
5512     outs() << format("0x%" PRIx64, cro.ivars);
5513   outs() << "\n";
5514   if (cro.ivars + n_value != 0)
5515     print_ivar_list64_t(cro.ivars + n_value, info);
5516 
5517   outs() << "           weakIvarLayout ";
5518   sym_name =
5519       get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
5520                     info, n_value, cro.weakIvarLayout);
5521   if (n_value != 0) {
5522     if (info->verbose && sym_name != nullptr)
5523       outs() << sym_name;
5524     else
5525       outs() << format("0x%" PRIx64, n_value);
5526     if (cro.weakIvarLayout != 0)
5527       outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
5528   } else
5529     outs() << format("0x%" PRIx64, cro.weakIvarLayout);
5530   outs() << "\n";
5531   print_layout_map64(cro.weakIvarLayout + n_value, info);
5532 
5533   outs() << "           baseProperties ";
5534   sym_name =
5535       get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
5536                     info, n_value, cro.baseProperties);
5537   if (n_value != 0) {
5538     if (info->verbose && sym_name != nullptr)
5539       outs() << sym_name;
5540     else
5541       outs() << format("0x%" PRIx64, n_value);
5542     if (cro.baseProperties != 0)
5543       outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
5544   } else
5545     outs() << format("0x%" PRIx64, cro.baseProperties);
5546   outs() << "\n";
5547   if (cro.baseProperties + n_value != 0)
5548     print_objc_property_list64(cro.baseProperties + n_value, info);
5549 
5550   is_meta_class = (cro.flags & RO_META) != 0;
5551   return true;
5552 }
5553 
5554 static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
5555                                bool &is_meta_class) {
5556   struct class_ro32_t cro;
5557   const char *r;
5558   uint32_t offset, xoffset, left;
5559   SectionRef S, xS;
5560   const char *name;
5561 
5562   r = get_pointer_32(p, offset, left, S, info);
5563   if (r == nullptr)
5564     return false;
5565   memset(&cro, '\0', sizeof(struct class_ro32_t));
5566   if (left < sizeof(struct class_ro32_t)) {
5567     memcpy(&cro, r, left);
5568     outs() << "   (class_ro_t entends past the end of the section)\n";
5569   } else
5570     memcpy(&cro, r, sizeof(struct class_ro32_t));
5571   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5572     swapStruct(cro);
5573   outs() << "                    flags " << format("0x%" PRIx32, cro.flags);
5574   if (cro.flags & RO_META)
5575     outs() << " RO_META";
5576   if (cro.flags & RO_ROOT)
5577     outs() << " RO_ROOT";
5578   if (cro.flags & RO_HAS_CXX_STRUCTORS)
5579     outs() << " RO_HAS_CXX_STRUCTORS";
5580   outs() << "\n";
5581   outs() << "            instanceStart " << cro.instanceStart << "\n";
5582   outs() << "             instanceSize " << cro.instanceSize << "\n";
5583   outs() << "               ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
5584          << "\n";
5585   print_layout_map32(cro.ivarLayout, info);
5586 
5587   outs() << "                     name " << format("0x%" PRIx32, cro.name);
5588   name = get_pointer_32(cro.name, xoffset, left, xS, info);
5589   if (name != nullptr)
5590     outs() << format(" %.*s", left, name);
5591   outs() << "\n";
5592 
5593   outs() << "              baseMethods "
5594          << format("0x%" PRIx32, cro.baseMethods)
5595          << " (struct method_list_t *)\n";
5596   if (cro.baseMethods != 0)
5597     print_method_list32_t(cro.baseMethods, info, "");
5598 
5599   outs() << "            baseProtocols "
5600          << format("0x%" PRIx32, cro.baseProtocols) << "\n";
5601   if (cro.baseProtocols != 0)
5602     print_protocol_list32_t(cro.baseProtocols, info);
5603   outs() << "                    ivars " << format("0x%" PRIx32, cro.ivars)
5604          << "\n";
5605   if (cro.ivars != 0)
5606     print_ivar_list32_t(cro.ivars, info);
5607   outs() << "           weakIvarLayout "
5608          << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
5609   print_layout_map32(cro.weakIvarLayout, info);
5610   outs() << "           baseProperties "
5611          << format("0x%" PRIx32, cro.baseProperties) << "\n";
5612   if (cro.baseProperties != 0)
5613     print_objc_property_list32(cro.baseProperties, info);
5614   is_meta_class = (cro.flags & RO_META) != 0;
5615   return true;
5616 }
5617 
5618 static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
5619   struct class64_t c;
5620   const char *r;
5621   uint32_t offset, left;
5622   SectionRef S;
5623   const char *name;
5624   uint64_t isa_n_value, n_value;
5625 
5626   r = get_pointer_64(p, offset, left, S, info);
5627   if (r == nullptr || left < sizeof(struct class64_t))
5628     return;
5629   memcpy(&c, r, sizeof(struct class64_t));
5630   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5631     swapStruct(c);
5632 
5633   outs() << "           isa " << format("0x%" PRIx64, c.isa);
5634   name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
5635                        isa_n_value, c.isa);
5636   if (name != nullptr)
5637     outs() << " " << name;
5638   outs() << "\n";
5639 
5640   outs() << "    superclass " << format("0x%" PRIx64, c.superclass);
5641   name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
5642                        n_value, c.superclass);
5643   if (name != nullptr)
5644     outs() << " " << name;
5645   else {
5646     name = get_dyld_bind_info_symbolname(S.getAddress() +
5647              offset + offsetof(struct class64_t, superclass), info);
5648     if (name != nullptr)
5649       outs() << " " << name;
5650   }
5651   outs() << "\n";
5652 
5653   outs() << "         cache " << format("0x%" PRIx64, c.cache);
5654   name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
5655                        n_value, c.cache);
5656   if (name != nullptr)
5657     outs() << " " << name;
5658   outs() << "\n";
5659 
5660   outs() << "        vtable " << format("0x%" PRIx64, c.vtable);
5661   name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
5662                        n_value, c.vtable);
5663   if (name != nullptr)
5664     outs() << " " << name;
5665   outs() << "\n";
5666 
5667   name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
5668                        n_value, c.data);
5669   outs() << "          data ";
5670   if (n_value != 0) {
5671     if (info->verbose && name != nullptr)
5672       outs() << name;
5673     else
5674       outs() << format("0x%" PRIx64, n_value);
5675     if (c.data != 0)
5676       outs() << " + " << format("0x%" PRIx64, c.data);
5677   } else
5678     outs() << format("0x%" PRIx64, c.data);
5679   outs() << " (struct class_ro_t *)";
5680 
5681   // This is a Swift class if some of the low bits of the pointer are set.
5682   if ((c.data + n_value) & 0x7)
5683     outs() << " Swift class";
5684   outs() << "\n";
5685   bool is_meta_class;
5686   if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
5687     return;
5688 
5689   if (!is_meta_class &&
5690       c.isa + isa_n_value != p &&
5691       c.isa + isa_n_value != 0 &&
5692       info->depth < 100) {
5693       info->depth++;
5694       outs() << "Meta Class\n";
5695       print_class64_t(c.isa + isa_n_value, info);
5696   }
5697 }
5698 
5699 static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
5700   struct class32_t c;
5701   const char *r;
5702   uint32_t offset, left;
5703   SectionRef S;
5704   const char *name;
5705 
5706   r = get_pointer_32(p, offset, left, S, info);
5707   if (r == nullptr)
5708     return;
5709   memset(&c, '\0', sizeof(struct class32_t));
5710   if (left < sizeof(struct class32_t)) {
5711     memcpy(&c, r, left);
5712     outs() << "   (class_t entends past the end of the section)\n";
5713   } else
5714     memcpy(&c, r, sizeof(struct class32_t));
5715   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5716     swapStruct(c);
5717 
5718   outs() << "           isa " << format("0x%" PRIx32, c.isa);
5719   name =
5720       get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
5721   if (name != nullptr)
5722     outs() << " " << name;
5723   outs() << "\n";
5724 
5725   outs() << "    superclass " << format("0x%" PRIx32, c.superclass);
5726   name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
5727                        c.superclass);
5728   if (name != nullptr)
5729     outs() << " " << name;
5730   outs() << "\n";
5731 
5732   outs() << "         cache " << format("0x%" PRIx32, c.cache);
5733   name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
5734                        c.cache);
5735   if (name != nullptr)
5736     outs() << " " << name;
5737   outs() << "\n";
5738 
5739   outs() << "        vtable " << format("0x%" PRIx32, c.vtable);
5740   name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
5741                        c.vtable);
5742   if (name != nullptr)
5743     outs() << " " << name;
5744   outs() << "\n";
5745 
5746   name =
5747       get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
5748   outs() << "          data " << format("0x%" PRIx32, c.data)
5749          << " (struct class_ro_t *)";
5750 
5751   // This is a Swift class if some of the low bits of the pointer are set.
5752   if (c.data & 0x3)
5753     outs() << " Swift class";
5754   outs() << "\n";
5755   bool is_meta_class;
5756   if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
5757     return;
5758 
5759   if (!is_meta_class) {
5760     outs() << "Meta Class\n";
5761     print_class32_t(c.isa, info);
5762   }
5763 }
5764 
5765 static void print_objc_class_t(struct objc_class_t *objc_class,
5766                                struct DisassembleInfo *info) {
5767   uint32_t offset, left, xleft;
5768   const char *name, *p, *ivar_list;
5769   SectionRef S;
5770   int32_t i;
5771   struct objc_ivar_list_t objc_ivar_list;
5772   struct objc_ivar_t ivar;
5773 
5774   outs() << "\t\t      isa " << format("0x%08" PRIx32, objc_class->isa);
5775   if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
5776     name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
5777     if (name != nullptr)
5778       outs() << format(" %.*s", left, name);
5779     else
5780       outs() << " (not in an __OBJC section)";
5781   }
5782   outs() << "\n";
5783 
5784   outs() << "\t      super_class "
5785          << format("0x%08" PRIx32, objc_class->super_class);
5786   if (info->verbose) {
5787     name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
5788     if (name != nullptr)
5789       outs() << format(" %.*s", left, name);
5790     else
5791       outs() << " (not in an __OBJC section)";
5792   }
5793   outs() << "\n";
5794 
5795   outs() << "\t\t     name " << format("0x%08" PRIx32, objc_class->name);
5796   if (info->verbose) {
5797     name = get_pointer_32(objc_class->name, offset, left, S, info, true);
5798     if (name != nullptr)
5799       outs() << format(" %.*s", left, name);
5800     else
5801       outs() << " (not in an __OBJC section)";
5802   }
5803   outs() << "\n";
5804 
5805   outs() << "\t\t  version " << format("0x%08" PRIx32, objc_class->version)
5806          << "\n";
5807 
5808   outs() << "\t\t     info " << format("0x%08" PRIx32, objc_class->info);
5809   if (info->verbose) {
5810     if (CLS_GETINFO(objc_class, CLS_CLASS))
5811       outs() << " CLS_CLASS";
5812     else if (CLS_GETINFO(objc_class, CLS_META))
5813       outs() << " CLS_META";
5814   }
5815   outs() << "\n";
5816 
5817   outs() << "\t    instance_size "
5818          << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
5819 
5820   p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
5821   outs() << "\t\t    ivars " << format("0x%08" PRIx32, objc_class->ivars);
5822   if (p != nullptr) {
5823     if (left > sizeof(struct objc_ivar_list_t)) {
5824       outs() << "\n";
5825       memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
5826     } else {
5827       outs() << " (entends past the end of the section)\n";
5828       memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
5829       memcpy(&objc_ivar_list, p, left);
5830     }
5831     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5832       swapStruct(objc_ivar_list);
5833     outs() << "\t\t       ivar_count " << objc_ivar_list.ivar_count << "\n";
5834     ivar_list = p + sizeof(struct objc_ivar_list_t);
5835     for (i = 0; i < objc_ivar_list.ivar_count; i++) {
5836       if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
5837         outs() << "\t\t remaining ivar's extend past the of the section\n";
5838         break;
5839       }
5840       memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
5841              sizeof(struct objc_ivar_t));
5842       if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5843         swapStruct(ivar);
5844 
5845       outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
5846       if (info->verbose) {
5847         name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
5848         if (name != nullptr)
5849           outs() << format(" %.*s", xleft, name);
5850         else
5851           outs() << " (not in an __OBJC section)";
5852       }
5853       outs() << "\n";
5854 
5855       outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
5856       if (info->verbose) {
5857         name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
5858         if (name != nullptr)
5859           outs() << format(" %.*s", xleft, name);
5860         else
5861           outs() << " (not in an __OBJC section)";
5862       }
5863       outs() << "\n";
5864 
5865       outs() << "\t\t      ivar_offset "
5866              << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
5867     }
5868   } else {
5869     outs() << " (not in an __OBJC section)\n";
5870   }
5871 
5872   outs() << "\t\t  methods " << format("0x%08" PRIx32, objc_class->methodLists);
5873   if (print_method_list(objc_class->methodLists, info))
5874     outs() << " (not in an __OBJC section)\n";
5875 
5876   outs() << "\t\t    cache " << format("0x%08" PRIx32, objc_class->cache)
5877          << "\n";
5878 
5879   outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
5880   if (print_protocol_list(objc_class->protocols, 16, info))
5881     outs() << " (not in an __OBJC section)\n";
5882 }
5883 
5884 static void print_objc_objc_category_t(struct objc_category_t *objc_category,
5885                                        struct DisassembleInfo *info) {
5886   uint32_t offset, left;
5887   const char *name;
5888   SectionRef S;
5889 
5890   outs() << "\t       category name "
5891          << format("0x%08" PRIx32, objc_category->category_name);
5892   if (info->verbose) {
5893     name = get_pointer_32(objc_category->category_name, offset, left, S, info,
5894                           true);
5895     if (name != nullptr)
5896       outs() << format(" %.*s", left, name);
5897     else
5898       outs() << " (not in an __OBJC section)";
5899   }
5900   outs() << "\n";
5901 
5902   outs() << "\t\t  class name "
5903          << format("0x%08" PRIx32, objc_category->class_name);
5904   if (info->verbose) {
5905     name =
5906         get_pointer_32(objc_category->class_name, offset, left, S, info, true);
5907     if (name != nullptr)
5908       outs() << format(" %.*s", left, name);
5909     else
5910       outs() << " (not in an __OBJC section)";
5911   }
5912   outs() << "\n";
5913 
5914   outs() << "\t    instance methods "
5915          << format("0x%08" PRIx32, objc_category->instance_methods);
5916   if (print_method_list(objc_category->instance_methods, info))
5917     outs() << " (not in an __OBJC section)\n";
5918 
5919   outs() << "\t       class methods "
5920          << format("0x%08" PRIx32, objc_category->class_methods);
5921   if (print_method_list(objc_category->class_methods, info))
5922     outs() << " (not in an __OBJC section)\n";
5923 }
5924 
5925 static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
5926   struct category64_t c;
5927   const char *r;
5928   uint32_t offset, xoffset, left;
5929   SectionRef S, xS;
5930   const char *name, *sym_name;
5931   uint64_t n_value;
5932 
5933   r = get_pointer_64(p, offset, left, S, info);
5934   if (r == nullptr)
5935     return;
5936   memset(&c, '\0', sizeof(struct category64_t));
5937   if (left < sizeof(struct category64_t)) {
5938     memcpy(&c, r, left);
5939     outs() << "   (category_t entends past the end of the section)\n";
5940   } else
5941     memcpy(&c, r, sizeof(struct category64_t));
5942   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5943     swapStruct(c);
5944 
5945   outs() << "              name ";
5946   sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
5947                            info, n_value, c.name);
5948   if (n_value != 0) {
5949     if (info->verbose && sym_name != nullptr)
5950       outs() << sym_name;
5951     else
5952       outs() << format("0x%" PRIx64, n_value);
5953     if (c.name != 0)
5954       outs() << " + " << format("0x%" PRIx64, c.name);
5955   } else
5956     outs() << format("0x%" PRIx64, c.name);
5957   name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
5958   if (name != nullptr)
5959     outs() << format(" %.*s", left, name);
5960   outs() << "\n";
5961 
5962   outs() << "               cls ";
5963   sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
5964                            n_value, c.cls);
5965   if (n_value != 0) {
5966     if (info->verbose && sym_name != nullptr)
5967       outs() << sym_name;
5968     else
5969       outs() << format("0x%" PRIx64, n_value);
5970     if (c.cls != 0)
5971       outs() << " + " << format("0x%" PRIx64, c.cls);
5972   } else
5973     outs() << format("0x%" PRIx64, c.cls);
5974   outs() << "\n";
5975   if (c.cls + n_value != 0)
5976     print_class64_t(c.cls + n_value, info);
5977 
5978   outs() << "   instanceMethods ";
5979   sym_name =
5980       get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
5981                     info, n_value, c.instanceMethods);
5982   if (n_value != 0) {
5983     if (info->verbose && sym_name != nullptr)
5984       outs() << sym_name;
5985     else
5986       outs() << format("0x%" PRIx64, n_value);
5987     if (c.instanceMethods != 0)
5988       outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
5989   } else
5990     outs() << format("0x%" PRIx64, c.instanceMethods);
5991   outs() << "\n";
5992   if (c.instanceMethods + n_value != 0)
5993     print_method_list64_t(c.instanceMethods + n_value, info, "");
5994 
5995   outs() << "      classMethods ";
5996   sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
5997                            S, info, n_value, c.classMethods);
5998   if (n_value != 0) {
5999     if (info->verbose && sym_name != nullptr)
6000       outs() << sym_name;
6001     else
6002       outs() << format("0x%" PRIx64, n_value);
6003     if (c.classMethods != 0)
6004       outs() << " + " << format("0x%" PRIx64, c.classMethods);
6005   } else
6006     outs() << format("0x%" PRIx64, c.classMethods);
6007   outs() << "\n";
6008   if (c.classMethods + n_value != 0)
6009     print_method_list64_t(c.classMethods + n_value, info, "");
6010 
6011   outs() << "         protocols ";
6012   sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
6013                            info, n_value, c.protocols);
6014   if (n_value != 0) {
6015     if (info->verbose && sym_name != nullptr)
6016       outs() << sym_name;
6017     else
6018       outs() << format("0x%" PRIx64, n_value);
6019     if (c.protocols != 0)
6020       outs() << " + " << format("0x%" PRIx64, c.protocols);
6021   } else
6022     outs() << format("0x%" PRIx64, c.protocols);
6023   outs() << "\n";
6024   if (c.protocols + n_value != 0)
6025     print_protocol_list64_t(c.protocols + n_value, info);
6026 
6027   outs() << "instanceProperties ";
6028   sym_name =
6029       get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
6030                     S, info, n_value, c.instanceProperties);
6031   if (n_value != 0) {
6032     if (info->verbose && sym_name != nullptr)
6033       outs() << sym_name;
6034     else
6035       outs() << format("0x%" PRIx64, n_value);
6036     if (c.instanceProperties != 0)
6037       outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
6038   } else
6039     outs() << format("0x%" PRIx64, c.instanceProperties);
6040   outs() << "\n";
6041   if (c.instanceProperties + n_value != 0)
6042     print_objc_property_list64(c.instanceProperties + n_value, info);
6043 }
6044 
6045 static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
6046   struct category32_t c;
6047   const char *r;
6048   uint32_t offset, left;
6049   SectionRef S, xS;
6050   const char *name;
6051 
6052   r = get_pointer_32(p, offset, left, S, info);
6053   if (r == nullptr)
6054     return;
6055   memset(&c, '\0', sizeof(struct category32_t));
6056   if (left < sizeof(struct category32_t)) {
6057     memcpy(&c, r, left);
6058     outs() << "   (category_t entends past the end of the section)\n";
6059   } else
6060     memcpy(&c, r, sizeof(struct category32_t));
6061   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
6062     swapStruct(c);
6063 
6064   outs() << "              name " << format("0x%" PRIx32, c.name);
6065   name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
6066                        c.name);
6067   if (name)
6068     outs() << " " << name;
6069   outs() << "\n";
6070 
6071   outs() << "               cls " << format("0x%" PRIx32, c.cls) << "\n";
6072   if (c.cls != 0)
6073     print_class32_t(c.cls, info);
6074   outs() << "   instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
6075          << "\n";
6076   if (c.instanceMethods != 0)
6077     print_method_list32_t(c.instanceMethods, info, "");
6078   outs() << "      classMethods " << format("0x%" PRIx32, c.classMethods)
6079          << "\n";
6080   if (c.classMethods != 0)
6081     print_method_list32_t(c.classMethods, info, "");
6082   outs() << "         protocols " << format("0x%" PRIx32, c.protocols) << "\n";
6083   if (c.protocols != 0)
6084     print_protocol_list32_t(c.protocols, info);
6085   outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
6086          << "\n";
6087   if (c.instanceProperties != 0)
6088     print_objc_property_list32(c.instanceProperties, info);
6089 }
6090 
6091 static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
6092   uint32_t i, left, offset, xoffset;
6093   uint64_t p, n_value;
6094   struct message_ref64 mr;
6095   const char *name, *sym_name;
6096   const char *r;
6097   SectionRef xS;
6098 
6099   if (S == SectionRef())
6100     return;
6101 
6102   StringRef SectName;
6103   Expected<StringRef> SecNameOrErr = S.getName();
6104   if (SecNameOrErr)
6105     SectName = *SecNameOrErr;
6106   else
6107     consumeError(SecNameOrErr.takeError());
6108 
6109   DataRefImpl Ref = S.getRawDataRefImpl();
6110   StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
6111   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
6112   offset = 0;
6113   for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
6114     p = S.getAddress() + i;
6115     r = get_pointer_64(p, offset, left, S, info);
6116     if (r == nullptr)
6117       return;
6118     memset(&mr, '\0', sizeof(struct message_ref64));
6119     if (left < sizeof(struct message_ref64)) {
6120       memcpy(&mr, r, left);
6121       outs() << "   (message_ref entends past the end of the section)\n";
6122     } else
6123       memcpy(&mr, r, sizeof(struct message_ref64));
6124     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
6125       swapStruct(mr);
6126 
6127     outs() << "  imp ";
6128     name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
6129                          n_value, mr.imp);
6130     if (n_value != 0) {
6131       outs() << format("0x%" PRIx64, n_value) << " ";
6132       if (mr.imp != 0)
6133         outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
6134     } else
6135       outs() << format("0x%" PRIx64, mr.imp) << " ";
6136     if (name != nullptr)
6137       outs() << " " << name;
6138     outs() << "\n";
6139 
6140     outs() << "  sel ";
6141     sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
6142                              info, n_value, mr.sel);
6143     if (n_value != 0) {
6144       if (info->verbose && sym_name != nullptr)
6145         outs() << sym_name;
6146       else
6147         outs() << format("0x%" PRIx64, n_value);
6148       if (mr.sel != 0)
6149         outs() << " + " << format("0x%" PRIx64, mr.sel);
6150     } else
6151       outs() << format("0x%" PRIx64, mr.sel);
6152     name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
6153     if (name != nullptr)
6154       outs() << format(" %.*s", left, name);
6155     outs() << "\n";
6156 
6157     offset += sizeof(struct message_ref64);
6158   }
6159 }
6160 
6161 static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
6162   uint32_t i, left, offset, xoffset, p;
6163   struct message_ref32 mr;
6164   const char *name, *r;
6165   SectionRef xS;
6166 
6167   if (S == SectionRef())
6168     return;
6169 
6170   StringRef SectName;
6171   Expected<StringRef> SecNameOrErr = S.getName();
6172   if (SecNameOrErr)
6173     SectName = *SecNameOrErr;
6174   else
6175     consumeError(SecNameOrErr.takeError());
6176 
6177   DataRefImpl Ref = S.getRawDataRefImpl();
6178   StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
6179   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
6180   offset = 0;
6181   for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
6182     p = S.getAddress() + i;
6183     r = get_pointer_32(p, offset, left, S, info);
6184     if (r == nullptr)
6185       return;
6186     memset(&mr, '\0', sizeof(struct message_ref32));
6187     if (left < sizeof(struct message_ref32)) {
6188       memcpy(&mr, r, left);
6189       outs() << "   (message_ref entends past the end of the section)\n";
6190     } else
6191       memcpy(&mr, r, sizeof(struct message_ref32));
6192     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
6193       swapStruct(mr);
6194 
6195     outs() << "  imp " << format("0x%" PRIx32, mr.imp);
6196     name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
6197                          mr.imp);
6198     if (name != nullptr)
6199       outs() << " " << name;
6200     outs() << "\n";
6201 
6202     outs() << "  sel " << format("0x%" PRIx32, mr.sel);
6203     name = get_pointer_32(mr.sel, xoffset, left, xS, info);
6204     if (name != nullptr)
6205       outs() << " " << name;
6206     outs() << "\n";
6207 
6208     offset += sizeof(struct message_ref32);
6209   }
6210 }
6211 
6212 static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
6213   uint32_t left, offset, swift_version;
6214   uint64_t p;
6215   struct objc_image_info64 o;
6216   const char *r;
6217 
6218   if (S == SectionRef())
6219     return;
6220 
6221   StringRef SectName;
6222   Expected<StringRef> SecNameOrErr = S.getName();
6223   if (SecNameOrErr)
6224     SectName = *SecNameOrErr;
6225   else
6226     consumeError(SecNameOrErr.takeError());
6227 
6228   DataRefImpl Ref = S.getRawDataRefImpl();
6229   StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
6230   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
6231   p = S.getAddress();
6232   r = get_pointer_64(p, offset, left, S, info);
6233   if (r == nullptr)
6234     return;
6235   memset(&o, '\0', sizeof(struct objc_image_info64));
6236   if (left < sizeof(struct objc_image_info64)) {
6237     memcpy(&o, r, left);
6238     outs() << "   (objc_image_info entends past the end of the section)\n";
6239   } else
6240     memcpy(&o, r, sizeof(struct objc_image_info64));
6241   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
6242     swapStruct(o);
6243   outs() << "  version " << o.version << "\n";
6244   outs() << "    flags " << format("0x%" PRIx32, o.flags);
6245   if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
6246     outs() << " OBJC_IMAGE_IS_REPLACEMENT";
6247   if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
6248     outs() << " OBJC_IMAGE_SUPPORTS_GC";
6249   if (o.flags & OBJC_IMAGE_IS_SIMULATED)
6250     outs() << " OBJC_IMAGE_IS_SIMULATED";
6251   if (o.flags & OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES)
6252     outs() << " OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES";
6253   swift_version = (o.flags >> 8) & 0xff;
6254   if (swift_version != 0) {
6255     if (swift_version == 1)
6256       outs() << " Swift 1.0";
6257     else if (swift_version == 2)
6258       outs() << " Swift 1.1";
6259     else if(swift_version == 3)
6260       outs() << " Swift 2.0";
6261     else if(swift_version == 4)
6262       outs() << " Swift 3.0";
6263     else if(swift_version == 5)
6264       outs() << " Swift 4.0";
6265     else if(swift_version == 6)
6266       outs() << " Swift 4.1/Swift 4.2";
6267     else if(swift_version == 7)
6268       outs() << " Swift 5 or later";
6269     else
6270       outs() << " unknown future Swift version (" << swift_version << ")";
6271   }
6272   outs() << "\n";
6273 }
6274 
6275 static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
6276   uint32_t left, offset, swift_version, p;
6277   struct objc_image_info32 o;
6278   const char *r;
6279 
6280   if (S == SectionRef())
6281     return;
6282 
6283   StringRef SectName;
6284   Expected<StringRef> SecNameOrErr = S.getName();
6285   if (SecNameOrErr)
6286     SectName = *SecNameOrErr;
6287   else
6288     consumeError(SecNameOrErr.takeError());
6289 
6290   DataRefImpl Ref = S.getRawDataRefImpl();
6291   StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
6292   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
6293   p = S.getAddress();
6294   r = get_pointer_32(p, offset, left, S, info);
6295   if (r == nullptr)
6296     return;
6297   memset(&o, '\0', sizeof(struct objc_image_info32));
6298   if (left < sizeof(struct objc_image_info32)) {
6299     memcpy(&o, r, left);
6300     outs() << "   (objc_image_info entends past the end of the section)\n";
6301   } else
6302     memcpy(&o, r, sizeof(struct objc_image_info32));
6303   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
6304     swapStruct(o);
6305   outs() << "  version " << o.version << "\n";
6306   outs() << "    flags " << format("0x%" PRIx32, o.flags);
6307   if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
6308     outs() << " OBJC_IMAGE_IS_REPLACEMENT";
6309   if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
6310     outs() << " OBJC_IMAGE_SUPPORTS_GC";
6311   swift_version = (o.flags >> 8) & 0xff;
6312   if (swift_version != 0) {
6313     if (swift_version == 1)
6314       outs() << " Swift 1.0";
6315     else if (swift_version == 2)
6316       outs() << " Swift 1.1";
6317     else if(swift_version == 3)
6318       outs() << " Swift 2.0";
6319     else if(swift_version == 4)
6320       outs() << " Swift 3.0";
6321     else if(swift_version == 5)
6322       outs() << " Swift 4.0";
6323     else if(swift_version == 6)
6324       outs() << " Swift 4.1/Swift 4.2";
6325     else if(swift_version == 7)
6326       outs() << " Swift 5 or later";
6327     else
6328       outs() << " unknown future Swift version (" << swift_version << ")";
6329   }
6330   outs() << "\n";
6331 }
6332 
6333 static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
6334   uint32_t left, offset, p;
6335   struct imageInfo_t o;
6336   const char *r;
6337 
6338   StringRef SectName;
6339   Expected<StringRef> SecNameOrErr = S.getName();
6340   if (SecNameOrErr)
6341     SectName = *SecNameOrErr;
6342   else
6343     consumeError(SecNameOrErr.takeError());
6344 
6345   DataRefImpl Ref = S.getRawDataRefImpl();
6346   StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
6347   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
6348   p = S.getAddress();
6349   r = get_pointer_32(p, offset, left, S, info);
6350   if (r == nullptr)
6351     return;
6352   memset(&o, '\0', sizeof(struct imageInfo_t));
6353   if (left < sizeof(struct imageInfo_t)) {
6354     memcpy(&o, r, left);
6355     outs() << " (imageInfo entends past the end of the section)\n";
6356   } else
6357     memcpy(&o, r, sizeof(struct imageInfo_t));
6358   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
6359     swapStruct(o);
6360   outs() << "  version " << o.version << "\n";
6361   outs() << "    flags " << format("0x%" PRIx32, o.flags);
6362   if (o.flags & 0x1)
6363     outs() << "  F&C";
6364   if (o.flags & 0x2)
6365     outs() << " GC";
6366   if (o.flags & 0x4)
6367     outs() << " GC-only";
6368   else
6369     outs() << " RR";
6370   outs() << "\n";
6371 }
6372 
6373 static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
6374   SymbolAddressMap AddrMap;
6375   if (verbose)
6376     CreateSymbolAddressMap(O, &AddrMap);
6377 
6378   std::vector<SectionRef> Sections;
6379   append_range(Sections, O->sections());
6380 
6381   struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
6382 
6383   SectionRef CL = get_section(O, "__OBJC2", "__class_list");
6384   if (CL == SectionRef())
6385     CL = get_section(O, "__DATA", "__objc_classlist");
6386   if (CL == SectionRef())
6387     CL = get_section(O, "__DATA_CONST", "__objc_classlist");
6388   if (CL == SectionRef())
6389     CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
6390   info.S = CL;
6391   walk_pointer_list_64("class", CL, O, &info, print_class64_t);
6392 
6393   SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
6394   if (CR == SectionRef())
6395     CR = get_section(O, "__DATA", "__objc_classrefs");
6396   if (CR == SectionRef())
6397     CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
6398   if (CR == SectionRef())
6399     CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
6400   info.S = CR;
6401   walk_pointer_list_64("class refs", CR, O, &info, nullptr);
6402 
6403   SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
6404   if (SR == SectionRef())
6405     SR = get_section(O, "__DATA", "__objc_superrefs");
6406   if (SR == SectionRef())
6407     SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
6408   if (SR == SectionRef())
6409     SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
6410   info.S = SR;
6411   walk_pointer_list_64("super refs", SR, O, &info, nullptr);
6412 
6413   SectionRef CA = get_section(O, "__OBJC2", "__category_list");
6414   if (CA == SectionRef())
6415     CA = get_section(O, "__DATA", "__objc_catlist");
6416   if (CA == SectionRef())
6417     CA = get_section(O, "__DATA_CONST", "__objc_catlist");
6418   if (CA == SectionRef())
6419     CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
6420   info.S = CA;
6421   walk_pointer_list_64("category", CA, O, &info, print_category64_t);
6422 
6423   SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
6424   if (PL == SectionRef())
6425     PL = get_section(O, "__DATA", "__objc_protolist");
6426   if (PL == SectionRef())
6427     PL = get_section(O, "__DATA_CONST", "__objc_protolist");
6428   if (PL == SectionRef())
6429     PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
6430   info.S = PL;
6431   walk_pointer_list_64("protocol", PL, O, &info, nullptr);
6432 
6433   SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
6434   if (MR == SectionRef())
6435     MR = get_section(O, "__DATA", "__objc_msgrefs");
6436   if (MR == SectionRef())
6437     MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
6438   if (MR == SectionRef())
6439     MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
6440   info.S = MR;
6441   print_message_refs64(MR, &info);
6442 
6443   SectionRef II = get_section(O, "__OBJC2", "__image_info");
6444   if (II == SectionRef())
6445     II = get_section(O, "__DATA", "__objc_imageinfo");
6446   if (II == SectionRef())
6447     II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
6448   if (II == SectionRef())
6449     II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
6450   info.S = II;
6451   print_image_info64(II, &info);
6452 }
6453 
6454 static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
6455   SymbolAddressMap AddrMap;
6456   if (verbose)
6457     CreateSymbolAddressMap(O, &AddrMap);
6458 
6459   std::vector<SectionRef> Sections;
6460   append_range(Sections, O->sections());
6461 
6462   struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
6463 
6464   SectionRef CL = get_section(O, "__OBJC2", "__class_list");
6465   if (CL == SectionRef())
6466     CL = get_section(O, "__DATA", "__objc_classlist");
6467   if (CL == SectionRef())
6468     CL = get_section(O, "__DATA_CONST", "__objc_classlist");
6469   if (CL == SectionRef())
6470     CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
6471   info.S = CL;
6472   walk_pointer_list_32("class", CL, O, &info, print_class32_t);
6473 
6474   SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
6475   if (CR == SectionRef())
6476     CR = get_section(O, "__DATA", "__objc_classrefs");
6477   if (CR == SectionRef())
6478     CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
6479   if (CR == SectionRef())
6480     CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
6481   info.S = CR;
6482   walk_pointer_list_32("class refs", CR, O, &info, nullptr);
6483 
6484   SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
6485   if (SR == SectionRef())
6486     SR = get_section(O, "__DATA", "__objc_superrefs");
6487   if (SR == SectionRef())
6488     SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
6489   if (SR == SectionRef())
6490     SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
6491   info.S = SR;
6492   walk_pointer_list_32("super refs", SR, O, &info, nullptr);
6493 
6494   SectionRef CA = get_section(O, "__OBJC2", "__category_list");
6495   if (CA == SectionRef())
6496     CA = get_section(O, "__DATA", "__objc_catlist");
6497   if (CA == SectionRef())
6498     CA = get_section(O, "__DATA_CONST", "__objc_catlist");
6499   if (CA == SectionRef())
6500     CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
6501   info.S = CA;
6502   walk_pointer_list_32("category", CA, O, &info, print_category32_t);
6503 
6504   SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
6505   if (PL == SectionRef())
6506     PL = get_section(O, "__DATA", "__objc_protolist");
6507   if (PL == SectionRef())
6508     PL = get_section(O, "__DATA_CONST", "__objc_protolist");
6509   if (PL == SectionRef())
6510     PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
6511   info.S = PL;
6512   walk_pointer_list_32("protocol", PL, O, &info, nullptr);
6513 
6514   SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
6515   if (MR == SectionRef())
6516     MR = get_section(O, "__DATA", "__objc_msgrefs");
6517   if (MR == SectionRef())
6518     MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
6519   if (MR == SectionRef())
6520     MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
6521   info.S = MR;
6522   print_message_refs32(MR, &info);
6523 
6524   SectionRef II = get_section(O, "__OBJC2", "__image_info");
6525   if (II == SectionRef())
6526     II = get_section(O, "__DATA", "__objc_imageinfo");
6527   if (II == SectionRef())
6528     II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
6529   if (II == SectionRef())
6530     II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
6531   info.S = II;
6532   print_image_info32(II, &info);
6533 }
6534 
6535 static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
6536   uint32_t i, j, p, offset, xoffset, left, defs_left, def;
6537   const char *r, *name, *defs;
6538   struct objc_module_t module;
6539   SectionRef S, xS;
6540   struct objc_symtab_t symtab;
6541   struct objc_class_t objc_class;
6542   struct objc_category_t objc_category;
6543 
6544   outs() << "Objective-C segment\n";
6545   S = get_section(O, "__OBJC", "__module_info");
6546   if (S == SectionRef())
6547     return false;
6548 
6549   SymbolAddressMap AddrMap;
6550   if (verbose)
6551     CreateSymbolAddressMap(O, &AddrMap);
6552 
6553   std::vector<SectionRef> Sections;
6554   append_range(Sections, O->sections());
6555 
6556   struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
6557 
6558   for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
6559     p = S.getAddress() + i;
6560     r = get_pointer_32(p, offset, left, S, &info, true);
6561     if (r == nullptr)
6562       return true;
6563     memset(&module, '\0', sizeof(struct objc_module_t));
6564     if (left < sizeof(struct objc_module_t)) {
6565       memcpy(&module, r, left);
6566       outs() << "   (module extends past end of __module_info section)\n";
6567     } else
6568       memcpy(&module, r, sizeof(struct objc_module_t));
6569     if (O->isLittleEndian() != sys::IsLittleEndianHost)
6570       swapStruct(module);
6571 
6572     outs() << "Module " << format("0x%" PRIx32, p) << "\n";
6573     outs() << "    version " << module.version << "\n";
6574     outs() << "       size " << module.size << "\n";
6575     outs() << "       name ";
6576     name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
6577     if (name != nullptr)
6578       outs() << format("%.*s", left, name);
6579     else
6580       outs() << format("0x%08" PRIx32, module.name)
6581              << "(not in an __OBJC section)";
6582     outs() << "\n";
6583 
6584     r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
6585     if (module.symtab == 0 || r == nullptr) {
6586       outs() << "     symtab " << format("0x%08" PRIx32, module.symtab)
6587              << " (not in an __OBJC section)\n";
6588       continue;
6589     }
6590     outs() << "     symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
6591     memset(&symtab, '\0', sizeof(struct objc_symtab_t));
6592     defs_left = 0;
6593     defs = nullptr;
6594     if (left < sizeof(struct objc_symtab_t)) {
6595       memcpy(&symtab, r, left);
6596       outs() << "\tsymtab extends past end of an __OBJC section)\n";
6597     } else {
6598       memcpy(&symtab, r, sizeof(struct objc_symtab_t));
6599       if (left > sizeof(struct objc_symtab_t)) {
6600         defs_left = left - sizeof(struct objc_symtab_t);
6601         defs = r + sizeof(struct objc_symtab_t);
6602       }
6603     }
6604     if (O->isLittleEndian() != sys::IsLittleEndianHost)
6605       swapStruct(symtab);
6606 
6607     outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
6608     r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
6609     outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
6610     if (r == nullptr)
6611       outs() << " (not in an __OBJC section)";
6612     outs() << "\n";
6613     outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
6614     outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
6615     if (symtab.cls_def_cnt > 0)
6616       outs() << "\tClass Definitions\n";
6617     for (j = 0; j < symtab.cls_def_cnt; j++) {
6618       if ((j + 1) * sizeof(uint32_t) > defs_left) {
6619         outs() << "\t(remaining class defs entries entends past the end of the "
6620                << "section)\n";
6621         break;
6622       }
6623       memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
6624       if (O->isLittleEndian() != sys::IsLittleEndianHost)
6625         sys::swapByteOrder(def);
6626 
6627       r = get_pointer_32(def, xoffset, left, xS, &info, true);
6628       outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
6629       if (r != nullptr) {
6630         if (left > sizeof(struct objc_class_t)) {
6631           outs() << "\n";
6632           memcpy(&objc_class, r, sizeof(struct objc_class_t));
6633         } else {
6634           outs() << " (entends past the end of the section)\n";
6635           memset(&objc_class, '\0', sizeof(struct objc_class_t));
6636           memcpy(&objc_class, r, left);
6637         }
6638         if (O->isLittleEndian() != sys::IsLittleEndianHost)
6639           swapStruct(objc_class);
6640         print_objc_class_t(&objc_class, &info);
6641       } else {
6642         outs() << "(not in an __OBJC section)\n";
6643       }
6644 
6645       if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
6646         outs() << "\tMeta Class";
6647         r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
6648         if (r != nullptr) {
6649           if (left > sizeof(struct objc_class_t)) {
6650             outs() << "\n";
6651             memcpy(&objc_class, r, sizeof(struct objc_class_t));
6652           } else {
6653             outs() << " (entends past the end of the section)\n";
6654             memset(&objc_class, '\0', sizeof(struct objc_class_t));
6655             memcpy(&objc_class, r, left);
6656           }
6657           if (O->isLittleEndian() != sys::IsLittleEndianHost)
6658             swapStruct(objc_class);
6659           print_objc_class_t(&objc_class, &info);
6660         } else {
6661           outs() << "(not in an __OBJC section)\n";
6662         }
6663       }
6664     }
6665     if (symtab.cat_def_cnt > 0)
6666       outs() << "\tCategory Definitions\n";
6667     for (j = 0; j < symtab.cat_def_cnt; j++) {
6668       if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
6669         outs() << "\t(remaining category defs entries entends past the end of "
6670                << "the section)\n";
6671         break;
6672       }
6673       memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
6674              sizeof(uint32_t));
6675       if (O->isLittleEndian() != sys::IsLittleEndianHost)
6676         sys::swapByteOrder(def);
6677 
6678       r = get_pointer_32(def, xoffset, left, xS, &info, true);
6679       outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
6680              << format("0x%08" PRIx32, def);
6681       if (r != nullptr) {
6682         if (left > sizeof(struct objc_category_t)) {
6683           outs() << "\n";
6684           memcpy(&objc_category, r, sizeof(struct objc_category_t));
6685         } else {
6686           outs() << " (entends past the end of the section)\n";
6687           memset(&objc_category, '\0', sizeof(struct objc_category_t));
6688           memcpy(&objc_category, r, left);
6689         }
6690         if (O->isLittleEndian() != sys::IsLittleEndianHost)
6691           swapStruct(objc_category);
6692         print_objc_objc_category_t(&objc_category, &info);
6693       } else {
6694         outs() << "(not in an __OBJC section)\n";
6695       }
6696     }
6697   }
6698   const SectionRef II = get_section(O, "__OBJC", "__image_info");
6699   if (II != SectionRef())
6700     print_image_info(II, &info);
6701 
6702   return true;
6703 }
6704 
6705 static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
6706                                 uint32_t size, uint32_t addr) {
6707   SymbolAddressMap AddrMap;
6708   CreateSymbolAddressMap(O, &AddrMap);
6709 
6710   std::vector<SectionRef> Sections;
6711   append_range(Sections, O->sections());
6712 
6713   struct DisassembleInfo info(O, &AddrMap, &Sections, true);
6714 
6715   const char *p;
6716   struct objc_protocol_t protocol;
6717   uint32_t left, paddr;
6718   for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
6719     memset(&protocol, '\0', sizeof(struct objc_protocol_t));
6720     left = size - (p - sect);
6721     if (left < sizeof(struct objc_protocol_t)) {
6722       outs() << "Protocol extends past end of __protocol section\n";
6723       memcpy(&protocol, p, left);
6724     } else
6725       memcpy(&protocol, p, sizeof(struct objc_protocol_t));
6726     if (O->isLittleEndian() != sys::IsLittleEndianHost)
6727       swapStruct(protocol);
6728     paddr = addr + (p - sect);
6729     outs() << "Protocol " << format("0x%" PRIx32, paddr);
6730     if (print_protocol(paddr, 0, &info))
6731       outs() << "(not in an __OBJC section)\n";
6732   }
6733 }
6734 
6735 #ifdef LLVM_HAVE_LIBXAR
6736 static inline void swapStruct(struct xar_header &xar) {
6737   sys::swapByteOrder(xar.magic);
6738   sys::swapByteOrder(xar.size);
6739   sys::swapByteOrder(xar.version);
6740   sys::swapByteOrder(xar.toc_length_compressed);
6741   sys::swapByteOrder(xar.toc_length_uncompressed);
6742   sys::swapByteOrder(xar.cksum_alg);
6743 }
6744 
6745 static void PrintModeVerbose(uint32_t mode) {
6746   switch(mode & S_IFMT){
6747   case S_IFDIR:
6748     outs() << "d";
6749     break;
6750   case S_IFCHR:
6751     outs() << "c";
6752     break;
6753   case S_IFBLK:
6754     outs() << "b";
6755     break;
6756   case S_IFREG:
6757     outs() << "-";
6758     break;
6759   case S_IFLNK:
6760     outs() << "l";
6761     break;
6762   case S_IFSOCK:
6763     outs() << "s";
6764     break;
6765   default:
6766     outs() << "?";
6767     break;
6768   }
6769 
6770   /* owner permissions */
6771   if(mode & S_IREAD)
6772     outs() << "r";
6773   else
6774     outs() << "-";
6775   if(mode & S_IWRITE)
6776     outs() << "w";
6777   else
6778     outs() << "-";
6779   if(mode & S_ISUID)
6780     outs() << "s";
6781   else if(mode & S_IEXEC)
6782     outs() << "x";
6783   else
6784     outs() << "-";
6785 
6786   /* group permissions */
6787   if(mode & (S_IREAD >> 3))
6788     outs() << "r";
6789   else
6790     outs() << "-";
6791   if(mode & (S_IWRITE >> 3))
6792     outs() << "w";
6793   else
6794     outs() << "-";
6795   if(mode & S_ISGID)
6796     outs() << "s";
6797   else if(mode & (S_IEXEC >> 3))
6798     outs() << "x";
6799   else
6800     outs() << "-";
6801 
6802   /* other permissions */
6803   if(mode & (S_IREAD >> 6))
6804     outs() << "r";
6805   else
6806     outs() << "-";
6807   if(mode & (S_IWRITE >> 6))
6808     outs() << "w";
6809   else
6810     outs() << "-";
6811   if(mode & S_ISVTX)
6812     outs() << "t";
6813   else if(mode & (S_IEXEC >> 6))
6814     outs() << "x";
6815   else
6816     outs() << "-";
6817 }
6818 
6819 static void PrintXarFilesSummary(const char *XarFilename, xar_t xar) {
6820   xar_file_t xf;
6821   const char *key, *type, *mode, *user, *group, *size, *mtime, *name, *m;
6822   char *endp;
6823   uint32_t mode_value;
6824 
6825   ScopedXarIter xi;
6826   if (!xi) {
6827     WithColor::error(errs(), "llvm-objdump")
6828         << "can't obtain an xar iterator for xar archive " << XarFilename
6829         << "\n";
6830     return;
6831   }
6832 
6833   // Go through the xar's files.
6834   for (xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)) {
6835     ScopedXarIter xp;
6836     if(!xp){
6837       WithColor::error(errs(), "llvm-objdump")
6838           << "can't obtain an xar iterator for xar archive " << XarFilename
6839           << "\n";
6840       return;
6841     }
6842     type = nullptr;
6843     mode = nullptr;
6844     user = nullptr;
6845     group = nullptr;
6846     size = nullptr;
6847     mtime = nullptr;
6848     name = nullptr;
6849     for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
6850       const char *val = nullptr;
6851       xar_prop_get(xf, key, &val);
6852 #if 0 // Useful for debugging.
6853       outs() << "key: " << key << " value: " << val << "\n";
6854 #endif
6855       if(strcmp(key, "type") == 0)
6856         type = val;
6857       if(strcmp(key, "mode") == 0)
6858         mode = val;
6859       if(strcmp(key, "user") == 0)
6860         user = val;
6861       if(strcmp(key, "group") == 0)
6862         group = val;
6863       if(strcmp(key, "data/size") == 0)
6864         size = val;
6865       if(strcmp(key, "mtime") == 0)
6866         mtime = val;
6867       if(strcmp(key, "name") == 0)
6868         name = val;
6869     }
6870     if(mode != nullptr){
6871       mode_value = strtoul(mode, &endp, 8);
6872       if(*endp != '\0')
6873         outs() << "(mode: \"" << mode << "\" contains non-octal chars) ";
6874       if(strcmp(type, "file") == 0)
6875         mode_value |= S_IFREG;
6876       PrintModeVerbose(mode_value);
6877       outs() << " ";
6878     }
6879     if(user != nullptr)
6880       outs() << format("%10s/", user);
6881     if(group != nullptr)
6882       outs() << format("%-10s ", group);
6883     if(size != nullptr)
6884       outs() << format("%7s ", size);
6885     if(mtime != nullptr){
6886       for(m = mtime; *m != 'T' && *m != '\0'; m++)
6887         outs() << *m;
6888       if(*m == 'T')
6889         m++;
6890       outs() << " ";
6891       for( ; *m != 'Z' && *m != '\0'; m++)
6892         outs() << *m;
6893       outs() << " ";
6894     }
6895     if(name != nullptr)
6896       outs() << name;
6897     outs() << "\n";
6898   }
6899 }
6900 
6901 static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
6902                                 uint32_t size, bool verbose,
6903                                 bool PrintXarHeader, bool PrintXarFileHeaders,
6904                                 std::string XarMemberName) {
6905   if(size < sizeof(struct xar_header)) {
6906     outs() << "size of (__LLVM,__bundle) section too small (smaller than size "
6907               "of struct xar_header)\n";
6908     return;
6909   }
6910   struct xar_header XarHeader;
6911   memcpy(&XarHeader, sect, sizeof(struct xar_header));
6912   if (sys::IsLittleEndianHost)
6913     swapStruct(XarHeader);
6914   if (PrintXarHeader) {
6915     if (!XarMemberName.empty())
6916       outs() << "In xar member " << XarMemberName << ": ";
6917     else
6918       outs() << "For (__LLVM,__bundle) section: ";
6919     outs() << "xar header\n";
6920     if (XarHeader.magic == XAR_HEADER_MAGIC)
6921       outs() << "                  magic XAR_HEADER_MAGIC\n";
6922     else
6923       outs() << "                  magic "
6924              << format_hex(XarHeader.magic, 10, true)
6925              << " (not XAR_HEADER_MAGIC)\n";
6926     outs() << "                   size " << XarHeader.size << "\n";
6927     outs() << "                version " << XarHeader.version << "\n";
6928     outs() << "  toc_length_compressed " << XarHeader.toc_length_compressed
6929            << "\n";
6930     outs() << "toc_length_uncompressed " << XarHeader.toc_length_uncompressed
6931            << "\n";
6932     outs() << "              cksum_alg ";
6933     switch (XarHeader.cksum_alg) {
6934       case XAR_CKSUM_NONE:
6935         outs() << "XAR_CKSUM_NONE\n";
6936         break;
6937       case XAR_CKSUM_SHA1:
6938         outs() << "XAR_CKSUM_SHA1\n";
6939         break;
6940       case XAR_CKSUM_MD5:
6941         outs() << "XAR_CKSUM_MD5\n";
6942         break;
6943 #ifdef XAR_CKSUM_SHA256
6944       case XAR_CKSUM_SHA256:
6945         outs() << "XAR_CKSUM_SHA256\n";
6946         break;
6947 #endif
6948 #ifdef XAR_CKSUM_SHA512
6949       case XAR_CKSUM_SHA512:
6950         outs() << "XAR_CKSUM_SHA512\n";
6951         break;
6952 #endif
6953       default:
6954         outs() << XarHeader.cksum_alg << "\n";
6955     }
6956   }
6957 
6958   SmallString<128> XarFilename;
6959   int FD;
6960   std::error_code XarEC =
6961       sys::fs::createTemporaryFile("llvm-objdump", "xar", FD, XarFilename);
6962   if (XarEC) {
6963     WithColor::error(errs(), "llvm-objdump") << XarEC.message() << "\n";
6964     return;
6965   }
6966   ToolOutputFile XarFile(XarFilename, FD);
6967   raw_fd_ostream &XarOut = XarFile.os();
6968   StringRef XarContents(sect, size);
6969   XarOut << XarContents;
6970   XarOut.close();
6971   if (XarOut.has_error())
6972     return;
6973 
6974   ScopedXarFile xar(XarFilename.c_str(), READ);
6975   if (!xar) {
6976     WithColor::error(errs(), "llvm-objdump")
6977         << "can't create temporary xar archive " << XarFilename << "\n";
6978     return;
6979   }
6980 
6981   SmallString<128> TocFilename;
6982   std::error_code TocEC =
6983       sys::fs::createTemporaryFile("llvm-objdump", "toc", TocFilename);
6984   if (TocEC) {
6985     WithColor::error(errs(), "llvm-objdump") << TocEC.message() << "\n";
6986     return;
6987   }
6988   xar_serialize(xar, TocFilename.c_str());
6989 
6990   if (PrintXarFileHeaders) {
6991     if (!XarMemberName.empty())
6992       outs() << "In xar member " << XarMemberName << ": ";
6993     else
6994       outs() << "For (__LLVM,__bundle) section: ";
6995     outs() << "xar archive files:\n";
6996     PrintXarFilesSummary(XarFilename.c_str(), xar);
6997   }
6998 
6999   ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
7000     MemoryBuffer::getFileOrSTDIN(TocFilename.c_str());
7001   if (std::error_code EC = FileOrErr.getError()) {
7002     WithColor::error(errs(), "llvm-objdump") << EC.message() << "\n";
7003     return;
7004   }
7005   std::unique_ptr<MemoryBuffer> &Buffer = FileOrErr.get();
7006 
7007   if (!XarMemberName.empty())
7008     outs() << "In xar member " << XarMemberName << ": ";
7009   else
7010     outs() << "For (__LLVM,__bundle) section: ";
7011   outs() << "xar table of contents:\n";
7012   outs() << Buffer->getBuffer() << "\n";
7013 
7014   // TODO: Go through the xar's files.
7015   ScopedXarIter xi;
7016   if(!xi){
7017     WithColor::error(errs(), "llvm-objdump")
7018         << "can't obtain an xar iterator for xar archive "
7019         << XarFilename.c_str() << "\n";
7020     return;
7021   }
7022   for(xar_file_t xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)){
7023     const char *key;
7024     const char *member_name, *member_type, *member_size_string;
7025     size_t member_size;
7026 
7027     ScopedXarIter xp;
7028     if(!xp){
7029       WithColor::error(errs(), "llvm-objdump")
7030           << "can't obtain an xar iterator for xar archive "
7031           << XarFilename.c_str() << "\n";
7032       return;
7033     }
7034     member_name = NULL;
7035     member_type = NULL;
7036     member_size_string = NULL;
7037     for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
7038       const char *val = nullptr;
7039       xar_prop_get(xf, key, &val);
7040 #if 0 // Useful for debugging.
7041       outs() << "key: " << key << " value: " << val << "\n";
7042 #endif
7043       if (strcmp(key, "name") == 0)
7044         member_name = val;
7045       if (strcmp(key, "type") == 0)
7046         member_type = val;
7047       if (strcmp(key, "data/size") == 0)
7048         member_size_string = val;
7049     }
7050     /*
7051      * If we find a file with a name, date/size and type properties
7052      * and with the type being "file" see if that is a xar file.
7053      */
7054     if (member_name != NULL && member_type != NULL &&
7055         strcmp(member_type, "file") == 0 &&
7056         member_size_string != NULL){
7057       // Extract the file into a buffer.
7058       char *endptr;
7059       member_size = strtoul(member_size_string, &endptr, 10);
7060       if (*endptr == '\0' && member_size != 0) {
7061         char *buffer;
7062         if (xar_extract_tobuffersz(xar, xf, &buffer, &member_size) == 0) {
7063 #if 0 // Useful for debugging.
7064           outs() << "xar member: " << member_name << " extracted\n";
7065 #endif
7066           // Set the XarMemberName we want to see printed in the header.
7067           std::string OldXarMemberName;
7068           // If XarMemberName is already set this is nested. So
7069           // save the old name and create the nested name.
7070           if (!XarMemberName.empty()) {
7071             OldXarMemberName = XarMemberName;
7072             XarMemberName =
7073                 (Twine("[") + XarMemberName + "]" + member_name).str();
7074           } else {
7075             OldXarMemberName = "";
7076             XarMemberName = member_name;
7077           }
7078           // See if this is could be a xar file (nested).
7079           if (member_size >= sizeof(struct xar_header)) {
7080 #if 0 // Useful for debugging.
7081             outs() << "could be a xar file: " << member_name << "\n";
7082 #endif
7083             memcpy((char *)&XarHeader, buffer, sizeof(struct xar_header));
7084             if (sys::IsLittleEndianHost)
7085               swapStruct(XarHeader);
7086             if (XarHeader.magic == XAR_HEADER_MAGIC)
7087               DumpBitcodeSection(O, buffer, member_size, verbose,
7088                                  PrintXarHeader, PrintXarFileHeaders,
7089                                  XarMemberName);
7090           }
7091           XarMemberName = OldXarMemberName;
7092           delete buffer;
7093         }
7094       }
7095     }
7096   }
7097 }
7098 #endif // defined(LLVM_HAVE_LIBXAR)
7099 
7100 static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
7101   if (O->is64Bit())
7102     printObjc2_64bit_MetaData(O, verbose);
7103   else {
7104     MachO::mach_header H;
7105     H = O->getHeader();
7106     if (H.cputype == MachO::CPU_TYPE_ARM)
7107       printObjc2_32bit_MetaData(O, verbose);
7108     else {
7109       // This is the 32-bit non-arm cputype case.  Which is normally
7110       // the first Objective-C ABI.  But it may be the case of a
7111       // binary for the iOS simulator which is the second Objective-C
7112       // ABI.  In that case printObjc1_32bit_MetaData() will determine that
7113       // and return false.
7114       if (!printObjc1_32bit_MetaData(O, verbose))
7115         printObjc2_32bit_MetaData(O, verbose);
7116     }
7117   }
7118 }
7119 
7120 // GuessLiteralPointer returns a string which for the item in the Mach-O file
7121 // for the address passed in as ReferenceValue for printing as a comment with
7122 // the instruction and also returns the corresponding type of that item
7123 // indirectly through ReferenceType.
7124 //
7125 // If ReferenceValue is an address of literal cstring then a pointer to the
7126 // cstring is returned and ReferenceType is set to
7127 // LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
7128 //
7129 // If ReferenceValue is an address of an Objective-C CFString, Selector ref or
7130 // Class ref that name is returned and the ReferenceType is set accordingly.
7131 //
7132 // Lastly, literals which are Symbol address in a literal pool are looked for
7133 // and if found the symbol name is returned and ReferenceType is set to
7134 // LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
7135 //
7136 // If there is no item in the Mach-O file for the address passed in as
7137 // ReferenceValue nullptr is returned and ReferenceType is unchanged.
7138 static const char *GuessLiteralPointer(uint64_t ReferenceValue,
7139                                        uint64_t ReferencePC,
7140                                        uint64_t *ReferenceType,
7141                                        struct DisassembleInfo *info) {
7142   // First see if there is an external relocation entry at the ReferencePC.
7143   if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
7144     uint64_t sect_addr = info->S.getAddress();
7145     uint64_t sect_offset = ReferencePC - sect_addr;
7146     bool reloc_found = false;
7147     DataRefImpl Rel;
7148     MachO::any_relocation_info RE;
7149     bool isExtern = false;
7150     SymbolRef Symbol;
7151     for (const RelocationRef &Reloc : info->S.relocations()) {
7152       uint64_t RelocOffset = Reloc.getOffset();
7153       if (RelocOffset == sect_offset) {
7154         Rel = Reloc.getRawDataRefImpl();
7155         RE = info->O->getRelocation(Rel);
7156         if (info->O->isRelocationScattered(RE))
7157           continue;
7158         isExtern = info->O->getPlainRelocationExternal(RE);
7159         if (isExtern) {
7160           symbol_iterator RelocSym = Reloc.getSymbol();
7161           Symbol = *RelocSym;
7162         }
7163         reloc_found = true;
7164         break;
7165       }
7166     }
7167     // If there is an external relocation entry for a symbol in a section
7168     // then used that symbol's value for the value of the reference.
7169     if (reloc_found && isExtern) {
7170       if (info->O->getAnyRelocationPCRel(RE)) {
7171         unsigned Type = info->O->getAnyRelocationType(RE);
7172         if (Type == MachO::X86_64_RELOC_SIGNED) {
7173           ReferenceValue = cantFail(Symbol.getValue());
7174         }
7175       }
7176     }
7177   }
7178 
7179   // Look for literals such as Objective-C CFStrings refs, Selector refs,
7180   // Message refs and Class refs.
7181   bool classref, selref, msgref, cfstring;
7182   uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
7183                                                selref, msgref, cfstring);
7184   if (classref && pointer_value == 0) {
7185     // Note the ReferenceValue is a pointer into the __objc_classrefs section.
7186     // And the pointer_value in that section is typically zero as it will be
7187     // set by dyld as part of the "bind information".
7188     const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
7189     if (name != nullptr) {
7190       *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
7191       const char *class_name = strrchr(name, '$');
7192       if (class_name != nullptr && class_name[1] == '_' &&
7193           class_name[2] != '\0') {
7194         info->class_name = class_name + 2;
7195         return name;
7196       }
7197     }
7198   }
7199 
7200   if (classref) {
7201     *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
7202     const char *name =
7203         get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
7204     if (name != nullptr)
7205       info->class_name = name;
7206     else
7207       name = "bad class ref";
7208     return name;
7209   }
7210 
7211   if (cfstring) {
7212     *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
7213     const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
7214     return name;
7215   }
7216 
7217   if (selref && pointer_value == 0)
7218     pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
7219 
7220   if (pointer_value != 0)
7221     ReferenceValue = pointer_value;
7222 
7223   const char *name = GuessCstringPointer(ReferenceValue, info);
7224   if (name) {
7225     if (pointer_value != 0 && selref) {
7226       *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
7227       info->selector_name = name;
7228     } else if (pointer_value != 0 && msgref) {
7229       info->class_name = nullptr;
7230       *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
7231       info->selector_name = name;
7232     } else
7233       *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
7234     return name;
7235   }
7236 
7237   // Lastly look for an indirect symbol with this ReferenceValue which is in
7238   // a literal pool.  If found return that symbol name.
7239   name = GuessIndirectSymbol(ReferenceValue, info);
7240   if (name) {
7241     *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
7242     return name;
7243   }
7244 
7245   return nullptr;
7246 }
7247 
7248 // SymbolizerSymbolLookUp is the symbol lookup function passed when creating
7249 // the Symbolizer.  It looks up the ReferenceValue using the info passed via the
7250 // pointer to the struct DisassembleInfo that was passed when MCSymbolizer
7251 // is created and returns the symbol name that matches the ReferenceValue or
7252 // nullptr if none.  The ReferenceType is passed in for the IN type of
7253 // reference the instruction is making from the values in defined in the header
7254 // "llvm-c/Disassembler.h".  On return the ReferenceType can set to a specific
7255 // Out type and the ReferenceName will also be set which is added as a comment
7256 // to the disassembled instruction.
7257 //
7258 // If the symbol name is a C++ mangled name then the demangled name is
7259 // returned through ReferenceName and ReferenceType is set to
7260 // LLVMDisassembler_ReferenceType_DeMangled_Name .
7261 //
7262 // When this is called to get a symbol name for a branch target then the
7263 // ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
7264 // SymbolValue will be looked for in the indirect symbol table to determine if
7265 // it is an address for a symbol stub.  If so then the symbol name for that
7266 // stub is returned indirectly through ReferenceName and then ReferenceType is
7267 // set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
7268 //
7269 // When this is called with an value loaded via a PC relative load then
7270 // ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
7271 // SymbolValue is checked to be an address of literal pointer, symbol pointer,
7272 // or an Objective-C meta data reference.  If so the output ReferenceType is
7273 // set to correspond to that as well as setting the ReferenceName.
7274 static const char *SymbolizerSymbolLookUp(void *DisInfo,
7275                                           uint64_t ReferenceValue,
7276                                           uint64_t *ReferenceType,
7277                                           uint64_t ReferencePC,
7278                                           const char **ReferenceName) {
7279   struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
7280   // If no verbose symbolic information is wanted then just return nullptr.
7281   if (!info->verbose) {
7282     *ReferenceName = nullptr;
7283     *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7284     return nullptr;
7285   }
7286 
7287   const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
7288 
7289   if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
7290     *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
7291     if (*ReferenceName != nullptr) {
7292       method_reference(info, ReferenceType, ReferenceName);
7293       if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
7294         *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
7295     } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
7296       if (info->demangled_name != nullptr)
7297         free(info->demangled_name);
7298       info->demangled_name = itaniumDemangle(SymbolName + 1);
7299       if (info->demangled_name != nullptr) {
7300         *ReferenceName = info->demangled_name;
7301         *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
7302       } else
7303         *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7304     } else
7305       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7306   } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
7307     *ReferenceName =
7308         GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7309     if (*ReferenceName)
7310       method_reference(info, ReferenceType, ReferenceName);
7311     else
7312       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7313     // If this is arm64 and the reference is an adrp instruction save the
7314     // instruction, passed in ReferenceValue and the address of the instruction
7315     // for use later if we see and add immediate instruction.
7316   } else if (info->O->getArch() == Triple::aarch64 &&
7317              *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
7318     info->adrp_inst = ReferenceValue;
7319     info->adrp_addr = ReferencePC;
7320     SymbolName = nullptr;
7321     *ReferenceName = nullptr;
7322     *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7323     // If this is arm64 and reference is an add immediate instruction and we
7324     // have
7325     // seen an adrp instruction just before it and the adrp's Xd register
7326     // matches
7327     // this add's Xn register reconstruct the value being referenced and look to
7328     // see if it is a literal pointer.  Note the add immediate instruction is
7329     // passed in ReferenceValue.
7330   } else if (info->O->getArch() == Triple::aarch64 &&
7331              *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
7332              ReferencePC - 4 == info->adrp_addr &&
7333              (info->adrp_inst & 0x9f000000) == 0x90000000 &&
7334              (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
7335     uint32_t addxri_inst;
7336     uint64_t adrp_imm, addxri_imm;
7337 
7338     adrp_imm =
7339         ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
7340     if (info->adrp_inst & 0x0200000)
7341       adrp_imm |= 0xfffffffffc000000LL;
7342 
7343     addxri_inst = ReferenceValue;
7344     addxri_imm = (addxri_inst >> 10) & 0xfff;
7345     if (((addxri_inst >> 22) & 0x3) == 1)
7346       addxri_imm <<= 12;
7347 
7348     ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
7349                      (adrp_imm << 12) + addxri_imm;
7350 
7351     *ReferenceName =
7352         GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7353     if (*ReferenceName == nullptr)
7354       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7355     // If this is arm64 and the reference is a load register instruction and we
7356     // have seen an adrp instruction just before it and the adrp's Xd register
7357     // matches this add's Xn register reconstruct the value being referenced and
7358     // look to see if it is a literal pointer.  Note the load register
7359     // instruction is passed in ReferenceValue.
7360   } else if (info->O->getArch() == Triple::aarch64 &&
7361              *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
7362              ReferencePC - 4 == info->adrp_addr &&
7363              (info->adrp_inst & 0x9f000000) == 0x90000000 &&
7364              (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
7365     uint32_t ldrxui_inst;
7366     uint64_t adrp_imm, ldrxui_imm;
7367 
7368     adrp_imm =
7369         ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
7370     if (info->adrp_inst & 0x0200000)
7371       adrp_imm |= 0xfffffffffc000000LL;
7372 
7373     ldrxui_inst = ReferenceValue;
7374     ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
7375 
7376     ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
7377                      (adrp_imm << 12) + (ldrxui_imm << 3);
7378 
7379     *ReferenceName =
7380         GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7381     if (*ReferenceName == nullptr)
7382       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7383   }
7384   // If this arm64 and is an load register (PC-relative) instruction the
7385   // ReferenceValue is the PC plus the immediate value.
7386   else if (info->O->getArch() == Triple::aarch64 &&
7387            (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
7388             *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
7389     *ReferenceName =
7390         GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7391     if (*ReferenceName == nullptr)
7392       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7393   } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
7394     if (info->demangled_name != nullptr)
7395       free(info->demangled_name);
7396     info->demangled_name = itaniumDemangle(SymbolName + 1);
7397     if (info->demangled_name != nullptr) {
7398       *ReferenceName = info->demangled_name;
7399       *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
7400     }
7401   }
7402   else {
7403     *ReferenceName = nullptr;
7404     *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7405   }
7406 
7407   return SymbolName;
7408 }
7409 
7410 /// Emits the comments that are stored in the CommentStream.
7411 /// Each comment in the CommentStream must end with a newline.
7412 static void emitComments(raw_svector_ostream &CommentStream,
7413                          SmallString<128> &CommentsToEmit,
7414                          formatted_raw_ostream &FormattedOS,
7415                          const MCAsmInfo &MAI) {
7416   // Flush the stream before taking its content.
7417   StringRef Comments = CommentsToEmit.str();
7418   // Get the default information for printing a comment.
7419   StringRef CommentBegin = MAI.getCommentString();
7420   unsigned CommentColumn = MAI.getCommentColumn();
7421   ListSeparator LS("\n");
7422   while (!Comments.empty()) {
7423     FormattedOS << LS;
7424     // Emit a line of comments.
7425     FormattedOS.PadToColumn(CommentColumn);
7426     size_t Position = Comments.find('\n');
7427     FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
7428     // Move after the newline character.
7429     Comments = Comments.substr(Position + 1);
7430   }
7431   FormattedOS.flush();
7432 
7433   // Tell the comment stream that the vector changed underneath it.
7434   CommentsToEmit.clear();
7435 }
7436 
7437 const MachOObjectFile *
7438 objdump::getMachODSymObject(const MachOObjectFile *MachOOF, StringRef Filename,
7439                             std::unique_ptr<Binary> &DSYMBinary,
7440                             std::unique_ptr<MemoryBuffer> &DSYMBuf) {
7441   const MachOObjectFile *DbgObj = MachOOF;
7442   std::string DSYMPath;
7443 
7444   // Auto-detect w/o --dsym.
7445   if (DSYMFile.empty()) {
7446     sys::fs::file_status DSYMStatus;
7447     Twine FilenameDSYM = Filename + ".dSYM";
7448     if (!status(FilenameDSYM, DSYMStatus)) {
7449       if (sys::fs::is_directory(DSYMStatus)) {
7450         SmallString<1024> Path;
7451         FilenameDSYM.toVector(Path);
7452         sys::path::append(Path, "Contents", "Resources", "DWARF",
7453                           sys::path::filename(Filename));
7454         DSYMPath = std::string(Path);
7455       } else if (sys::fs::is_regular_file(DSYMStatus)) {
7456         DSYMPath = FilenameDSYM.str();
7457       }
7458     }
7459   }
7460 
7461   if (DSYMPath.empty() && !DSYMFile.empty()) {
7462     // If DSYMPath is a .dSYM directory, append the Mach-O file.
7463     if (sys::fs::is_directory(DSYMFile) &&
7464         sys::path::extension(DSYMFile) == ".dSYM") {
7465       SmallString<128> ShortName(sys::path::filename(DSYMFile));
7466       sys::path::replace_extension(ShortName, "");
7467       SmallString<1024> FullPath(DSYMFile);
7468       sys::path::append(FullPath, "Contents", "Resources", "DWARF", ShortName);
7469       DSYMPath = FullPath.str();
7470     } else {
7471       DSYMPath = DSYMFile;
7472     }
7473   }
7474 
7475   if (!DSYMPath.empty()) {
7476     // Load the file.
7477     ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
7478         MemoryBuffer::getFileOrSTDIN(DSYMPath);
7479     if (std::error_code EC = BufOrErr.getError()) {
7480       reportError(errorCodeToError(EC), DSYMPath);
7481       return nullptr;
7482     }
7483 
7484     // We need to keep the file alive, because we're replacing DbgObj with it.
7485     DSYMBuf = std::move(BufOrErr.get());
7486 
7487     Expected<std::unique_ptr<Binary>> BinaryOrErr =
7488         createBinary(DSYMBuf.get()->getMemBufferRef());
7489     if (!BinaryOrErr) {
7490       reportError(BinaryOrErr.takeError(), DSYMPath);
7491       return nullptr;
7492     }
7493 
7494     // We need to keep the Binary alive with the buffer
7495     DSYMBinary = std::move(BinaryOrErr.get());
7496     if (ObjectFile *O = dyn_cast<ObjectFile>(DSYMBinary.get())) {
7497       // this is a Mach-O object file, use it
7498       if (MachOObjectFile *MachDSYM = dyn_cast<MachOObjectFile>(&*O)) {
7499         DbgObj = MachDSYM;
7500       } else {
7501         WithColor::error(errs(), "llvm-objdump")
7502             << DSYMPath << " is not a Mach-O file type.\n";
7503         return nullptr;
7504       }
7505     } else if (auto *UB = dyn_cast<MachOUniversalBinary>(DSYMBinary.get())) {
7506       // this is a Universal Binary, find a Mach-O for this architecture
7507       uint32_t CPUType, CPUSubType;
7508       const char *ArchFlag;
7509       if (MachOOF->is64Bit()) {
7510         const MachO::mach_header_64 H_64 = MachOOF->getHeader64();
7511         CPUType = H_64.cputype;
7512         CPUSubType = H_64.cpusubtype;
7513       } else {
7514         const MachO::mach_header H = MachOOF->getHeader();
7515         CPUType = H.cputype;
7516         CPUSubType = H.cpusubtype;
7517       }
7518       Triple T = MachOObjectFile::getArchTriple(CPUType, CPUSubType, nullptr,
7519                                                 &ArchFlag);
7520       Expected<std::unique_ptr<MachOObjectFile>> MachDSYM =
7521           UB->getMachOObjectForArch(ArchFlag);
7522       if (!MachDSYM) {
7523         reportError(MachDSYM.takeError(), DSYMPath);
7524         return nullptr;
7525       }
7526 
7527       // We need to keep the Binary alive with the buffer
7528       DbgObj = &*MachDSYM.get();
7529       DSYMBinary = std::move(*MachDSYM);
7530     } else {
7531       WithColor::error(errs(), "llvm-objdump")
7532           << DSYMPath << " is not a Mach-O or Universal file type.\n";
7533       return nullptr;
7534     }
7535   }
7536   return DbgObj;
7537 }
7538 
7539 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
7540                              StringRef DisSegName, StringRef DisSectName) {
7541   const char *McpuDefault = nullptr;
7542   const Target *ThumbTarget = nullptr;
7543   const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
7544   if (!TheTarget) {
7545     // GetTarget prints out stuff.
7546     return;
7547   }
7548   std::string MachOMCPU;
7549   if (MCPU.empty() && McpuDefault)
7550     MachOMCPU = McpuDefault;
7551   else
7552     MachOMCPU = MCPU;
7553 
7554 #define CHECK_TARGET_INFO_CREATION(NAME)                                       \
7555   do {                                                                         \
7556     if (!NAME) {                                                               \
7557       WithColor::error(errs(), "llvm-objdump")                                 \
7558           << "couldn't initialize disassembler for target " << TripleName      \
7559           << '\n';                                                             \
7560       return;                                                                  \
7561     }                                                                          \
7562   } while (false)
7563 #define CHECK_THUMB_TARGET_INFO_CREATION(NAME)                                 \
7564   do {                                                                         \
7565     if (!NAME) {                                                               \
7566       WithColor::error(errs(), "llvm-objdump")                                 \
7567           << "couldn't initialize disassembler for target " << ThumbTripleName \
7568           << '\n';                                                             \
7569       return;                                                                  \
7570     }                                                                          \
7571   } while (false)
7572 
7573   std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
7574   CHECK_TARGET_INFO_CREATION(InstrInfo);
7575   std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
7576   if (ThumbTarget) {
7577     ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
7578     CHECK_THUMB_TARGET_INFO_CREATION(ThumbInstrInfo);
7579   }
7580 
7581   // Package up features to be passed to target/subtarget
7582   std::string FeaturesStr;
7583   if (!MAttrs.empty()) {
7584     SubtargetFeatures Features;
7585     for (unsigned i = 0; i != MAttrs.size(); ++i)
7586       Features.AddFeature(MAttrs[i]);
7587     FeaturesStr = Features.getString();
7588   }
7589 
7590   MCTargetOptions MCOptions;
7591   // Set up disassembler.
7592   std::unique_ptr<const MCRegisterInfo> MRI(
7593       TheTarget->createMCRegInfo(TripleName));
7594   CHECK_TARGET_INFO_CREATION(MRI);
7595   std::unique_ptr<const MCAsmInfo> AsmInfo(
7596       TheTarget->createMCAsmInfo(*MRI, TripleName, MCOptions));
7597   CHECK_TARGET_INFO_CREATION(AsmInfo);
7598   std::unique_ptr<const MCSubtargetInfo> STI(
7599       TheTarget->createMCSubtargetInfo(TripleName, MachOMCPU, FeaturesStr));
7600   CHECK_TARGET_INFO_CREATION(STI);
7601   MCContext Ctx(Triple(TripleName), AsmInfo.get(), MRI.get(), STI.get());
7602   std::unique_ptr<MCDisassembler> DisAsm(
7603       TheTarget->createMCDisassembler(*STI, Ctx));
7604   CHECK_TARGET_INFO_CREATION(DisAsm);
7605   std::unique_ptr<MCSymbolizer> Symbolizer;
7606   struct DisassembleInfo SymbolizerInfo(nullptr, nullptr, nullptr, false);
7607   std::unique_ptr<MCRelocationInfo> RelInfo(
7608       TheTarget->createMCRelocationInfo(TripleName, Ctx));
7609   if (RelInfo) {
7610     Symbolizer.reset(TheTarget->createMCSymbolizer(
7611         TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
7612         &SymbolizerInfo, &Ctx, std::move(RelInfo)));
7613     DisAsm->setSymbolizer(std::move(Symbolizer));
7614   }
7615   int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
7616   std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
7617       Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
7618   CHECK_TARGET_INFO_CREATION(IP);
7619   // Set the display preference for hex vs. decimal immediates.
7620   IP->setPrintImmHex(PrintImmHex);
7621   // Comment stream and backing vector.
7622   SmallString<128> CommentsToEmit;
7623   raw_svector_ostream CommentStream(CommentsToEmit);
7624   // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
7625   // if it is done then arm64 comments for string literals don't get printed
7626   // and some constant get printed instead and not setting it causes intel
7627   // (32-bit and 64-bit) comments printed with different spacing before the
7628   // comment causing different diffs with the 'C' disassembler library API.
7629   // IP->setCommentStream(CommentStream);
7630 
7631   // Set up separate thumb disassembler if needed.
7632   std::unique_ptr<const MCRegisterInfo> ThumbMRI;
7633   std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
7634   std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
7635   std::unique_ptr<MCDisassembler> ThumbDisAsm;
7636   std::unique_ptr<MCInstPrinter> ThumbIP;
7637   std::unique_ptr<MCContext> ThumbCtx;
7638   std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
7639   struct DisassembleInfo ThumbSymbolizerInfo(nullptr, nullptr, nullptr, false);
7640   std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
7641   if (ThumbTarget) {
7642     ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
7643     CHECK_THUMB_TARGET_INFO_CREATION(ThumbMRI);
7644     ThumbAsmInfo.reset(
7645         ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName, MCOptions));
7646     CHECK_THUMB_TARGET_INFO_CREATION(ThumbAsmInfo);
7647     ThumbSTI.reset(
7648         ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MachOMCPU,
7649                                            FeaturesStr));
7650     CHECK_THUMB_TARGET_INFO_CREATION(ThumbSTI);
7651     ThumbCtx.reset(new MCContext(Triple(ThumbTripleName), ThumbAsmInfo.get(),
7652                                  ThumbMRI.get(), ThumbSTI.get()));
7653     ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
7654     CHECK_THUMB_TARGET_INFO_CREATION(ThumbDisAsm);
7655     MCContext *PtrThumbCtx = ThumbCtx.get();
7656     ThumbRelInfo.reset(
7657         ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
7658     if (ThumbRelInfo) {
7659       ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
7660           ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
7661           &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
7662       ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
7663     }
7664     int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
7665     ThumbIP.reset(ThumbTarget->createMCInstPrinter(
7666         Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
7667         *ThumbInstrInfo, *ThumbMRI));
7668     CHECK_THUMB_TARGET_INFO_CREATION(ThumbIP);
7669     // Set the display preference for hex vs. decimal immediates.
7670     ThumbIP->setPrintImmHex(PrintImmHex);
7671   }
7672 
7673 #undef CHECK_TARGET_INFO_CREATION
7674 #undef CHECK_THUMB_TARGET_INFO_CREATION
7675 
7676   MachO::mach_header Header = MachOOF->getHeader();
7677 
7678   // FIXME: Using the -cfg command line option, this code used to be able to
7679   // annotate relocations with the referenced symbol's name, and if this was
7680   // inside a __[cf]string section, the data it points to. This is now replaced
7681   // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
7682   std::vector<SectionRef> Sections;
7683   std::vector<SymbolRef> Symbols;
7684   SmallVector<uint64_t, 8> FoundFns;
7685   uint64_t BaseSegmentAddress = 0;
7686 
7687   getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
7688                         BaseSegmentAddress);
7689 
7690   // Sort the symbols by address, just in case they didn't come in that way.
7691   llvm::stable_sort(Symbols, SymbolSorter());
7692 
7693   // Build a data in code table that is sorted on by the address of each entry.
7694   uint64_t BaseAddress = 0;
7695   if (Header.filetype == MachO::MH_OBJECT)
7696     BaseAddress = Sections[0].getAddress();
7697   else
7698     BaseAddress = BaseSegmentAddress;
7699   DiceTable Dices;
7700   for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
7701        DI != DE; ++DI) {
7702     uint32_t Offset;
7703     DI->getOffset(Offset);
7704     Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
7705   }
7706   array_pod_sort(Dices.begin(), Dices.end());
7707 
7708   // Try to find debug info and set up the DIContext for it.
7709   std::unique_ptr<DIContext> diContext;
7710   std::unique_ptr<Binary> DSYMBinary;
7711   std::unique_ptr<MemoryBuffer> DSYMBuf;
7712   if (UseDbg) {
7713     // If separate DSym file path was specified, parse it as a macho file,
7714     // get the sections and supply it to the section name parsing machinery.
7715     if (const ObjectFile *DbgObj =
7716             getMachODSymObject(MachOOF, Filename, DSYMBinary, DSYMBuf)) {
7717       // Setup the DIContext
7718       diContext = DWARFContext::create(*DbgObj);
7719     } else {
7720       return;
7721     }
7722   }
7723 
7724   if (FilterSections.empty())
7725     outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
7726 
7727   for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
7728     Expected<StringRef> SecNameOrErr = Sections[SectIdx].getName();
7729     if (!SecNameOrErr) {
7730       consumeError(SecNameOrErr.takeError());
7731       continue;
7732     }
7733     if (*SecNameOrErr != DisSectName)
7734       continue;
7735 
7736     DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
7737 
7738     StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
7739     if (SegmentName != DisSegName)
7740       continue;
7741 
7742     StringRef BytesStr =
7743         unwrapOrError(Sections[SectIdx].getContents(), Filename);
7744     ArrayRef<uint8_t> Bytes = arrayRefFromStringRef(BytesStr);
7745     uint64_t SectAddress = Sections[SectIdx].getAddress();
7746 
7747     bool symbolTableWorked = false;
7748 
7749     // Create a map of symbol addresses to symbol names for use by
7750     // the SymbolizerSymbolLookUp() routine.
7751     SymbolAddressMap AddrMap;
7752     bool DisSymNameFound = false;
7753     for (const SymbolRef &Symbol : MachOOF->symbols()) {
7754       SymbolRef::Type ST =
7755           unwrapOrError(Symbol.getType(), MachOOF->getFileName());
7756       if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
7757           ST == SymbolRef::ST_Other) {
7758         uint64_t Address = cantFail(Symbol.getValue());
7759         StringRef SymName =
7760             unwrapOrError(Symbol.getName(), MachOOF->getFileName());
7761         AddrMap[Address] = SymName;
7762         if (!DisSymName.empty() && DisSymName == SymName)
7763           DisSymNameFound = true;
7764       }
7765     }
7766     if (!DisSymName.empty() && !DisSymNameFound) {
7767       outs() << "Can't find -dis-symname: " << DisSymName << "\n";
7768       return;
7769     }
7770     // Set up the block of info used by the Symbolizer call backs.
7771     SymbolizerInfo.verbose = SymbolicOperands;
7772     SymbolizerInfo.O = MachOOF;
7773     SymbolizerInfo.S = Sections[SectIdx];
7774     SymbolizerInfo.AddrMap = &AddrMap;
7775     SymbolizerInfo.Sections = &Sections;
7776     // Same for the ThumbSymbolizer
7777     ThumbSymbolizerInfo.verbose = SymbolicOperands;
7778     ThumbSymbolizerInfo.O = MachOOF;
7779     ThumbSymbolizerInfo.S = Sections[SectIdx];
7780     ThumbSymbolizerInfo.AddrMap = &AddrMap;
7781     ThumbSymbolizerInfo.Sections = &Sections;
7782 
7783     unsigned int Arch = MachOOF->getArch();
7784 
7785     // Skip all symbols if this is a stubs file.
7786     if (Bytes.empty())
7787       return;
7788 
7789     // If the section has symbols but no symbol at the start of the section
7790     // these are used to make sure the bytes before the first symbol are
7791     // disassembled.
7792     bool FirstSymbol = true;
7793     bool FirstSymbolAtSectionStart = true;
7794 
7795     // Disassemble symbol by symbol.
7796     for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
7797       StringRef SymName =
7798           unwrapOrError(Symbols[SymIdx].getName(), MachOOF->getFileName());
7799       SymbolRef::Type ST =
7800           unwrapOrError(Symbols[SymIdx].getType(), MachOOF->getFileName());
7801       if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
7802         continue;
7803 
7804       // Make sure the symbol is defined in this section.
7805       bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
7806       if (!containsSym) {
7807         if (!DisSymName.empty() && DisSymName == SymName) {
7808           outs() << "-dis-symname: " << DisSymName << " not in the section\n";
7809           return;
7810         }
7811         continue;
7812       }
7813       // The __mh_execute_header is special and we need to deal with that fact
7814       // this symbol is before the start of the (__TEXT,__text) section and at the
7815       // address of the start of the __TEXT segment.  This is because this symbol
7816       // is an N_SECT symbol in the (__TEXT,__text) but its address is before the
7817       // start of the section in a standard MH_EXECUTE filetype.
7818       if (!DisSymName.empty() && DisSymName == "__mh_execute_header") {
7819         outs() << "-dis-symname: __mh_execute_header not in any section\n";
7820         return;
7821       }
7822       // When this code is trying to disassemble a symbol at a time and in the
7823       // case there is only the __mh_execute_header symbol left as in a stripped
7824       // executable, we need to deal with this by ignoring this symbol so the
7825       // whole section is disassembled and this symbol is then not displayed.
7826       if (SymName == "__mh_execute_header" || SymName == "__mh_dylib_header" ||
7827           SymName == "__mh_bundle_header" || SymName == "__mh_object_header" ||
7828           SymName == "__mh_preload_header" || SymName == "__mh_dylinker_header")
7829         continue;
7830 
7831       // If we are only disassembling one symbol see if this is that symbol.
7832       if (!DisSymName.empty() && DisSymName != SymName)
7833         continue;
7834 
7835       // Start at the address of the symbol relative to the section's address.
7836       uint64_t SectSize = Sections[SectIdx].getSize();
7837       uint64_t Start = cantFail(Symbols[SymIdx].getValue());
7838       uint64_t SectionAddress = Sections[SectIdx].getAddress();
7839       Start -= SectionAddress;
7840 
7841       if (Start > SectSize) {
7842         outs() << "section data ends, " << SymName
7843                << " lies outside valid range\n";
7844         return;
7845       }
7846 
7847       // Stop disassembling either at the beginning of the next symbol or at
7848       // the end of the section.
7849       bool containsNextSym = false;
7850       uint64_t NextSym = 0;
7851       uint64_t NextSymIdx = SymIdx + 1;
7852       while (Symbols.size() > NextSymIdx) {
7853         SymbolRef::Type NextSymType = unwrapOrError(
7854             Symbols[NextSymIdx].getType(), MachOOF->getFileName());
7855         if (NextSymType == SymbolRef::ST_Function) {
7856           containsNextSym =
7857               Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
7858           NextSym = cantFail(Symbols[NextSymIdx].getValue());
7859           NextSym -= SectionAddress;
7860           break;
7861         }
7862         ++NextSymIdx;
7863       }
7864 
7865       uint64_t End = containsNextSym ? std::min(NextSym, SectSize) : SectSize;
7866       uint64_t Size;
7867 
7868       symbolTableWorked = true;
7869 
7870       DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
7871       uint32_t SymbolFlags = cantFail(MachOOF->getSymbolFlags(Symb));
7872       bool IsThumb = SymbolFlags & SymbolRef::SF_Thumb;
7873 
7874       // We only need the dedicated Thumb target if there's a real choice
7875       // (i.e. we're not targeting M-class) and the function is Thumb.
7876       bool UseThumbTarget = IsThumb && ThumbTarget;
7877 
7878       // If we are not specifying a symbol to start disassembly with and this
7879       // is the first symbol in the section but not at the start of the section
7880       // then move the disassembly index to the start of the section and
7881       // don't print the symbol name just yet.  This is so the bytes before the
7882       // first symbol are disassembled.
7883       uint64_t SymbolStart = Start;
7884       if (DisSymName.empty() && FirstSymbol && Start != 0) {
7885         FirstSymbolAtSectionStart = false;
7886         Start = 0;
7887       }
7888       else
7889         outs() << SymName << ":\n";
7890 
7891       DILineInfo lastLine;
7892       for (uint64_t Index = Start; Index < End; Index += Size) {
7893         MCInst Inst;
7894 
7895         // If this is the first symbol in the section and it was not at the
7896         // start of the section, see if we are at its Index now and if so print
7897         // the symbol name.
7898         if (FirstSymbol && !FirstSymbolAtSectionStart && Index == SymbolStart)
7899           outs() << SymName << ":\n";
7900 
7901         uint64_t PC = SectAddress + Index;
7902         if (LeadingAddr) {
7903           if (FullLeadingAddr) {
7904             if (MachOOF->is64Bit())
7905               outs() << format("%016" PRIx64, PC);
7906             else
7907               outs() << format("%08" PRIx64, PC);
7908           } else {
7909             outs() << format("%8" PRIx64 ":", PC);
7910           }
7911         }
7912         if (ShowRawInsn || Arch == Triple::arm)
7913           outs() << "\t";
7914 
7915         if (DumpAndSkipDataInCode(PC, Bytes.data() + Index, Dices, Size))
7916           continue;
7917 
7918         SmallVector<char, 64> AnnotationsBytes;
7919         raw_svector_ostream Annotations(AnnotationsBytes);
7920 
7921         bool gotInst;
7922         if (UseThumbTarget)
7923           gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
7924                                                 PC, Annotations);
7925         else
7926           gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
7927                                            Annotations);
7928         if (gotInst) {
7929           if (ShowRawInsn || Arch == Triple::arm) {
7930             dumpBytes(ArrayRef(Bytes.data() + Index, Size), outs());
7931           }
7932           formatted_raw_ostream FormattedOS(outs());
7933           StringRef AnnotationsStr = Annotations.str();
7934           if (UseThumbTarget)
7935             ThumbIP->printInst(&Inst, PC, AnnotationsStr, *ThumbSTI,
7936                                FormattedOS);
7937           else
7938             IP->printInst(&Inst, PC, AnnotationsStr, *STI, FormattedOS);
7939           emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
7940 
7941           // Print debug info.
7942           if (diContext) {
7943             DILineInfo dli = diContext->getLineInfoForAddress({PC, SectIdx});
7944             // Print valid line info if it changed.
7945             if (dli != lastLine && dli.Line != 0)
7946               outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
7947                      << dli.Column;
7948             lastLine = dli;
7949           }
7950           outs() << "\n";
7951         } else {
7952           if (MachOOF->getArchTriple().isX86()) {
7953             outs() << format("\t.byte 0x%02x #bad opcode\n",
7954                              *(Bytes.data() + Index) & 0xff);
7955             Size = 1; // skip exactly one illegible byte and move on.
7956           } else if (Arch == Triple::aarch64 ||
7957                      (Arch == Triple::arm && !IsThumb)) {
7958             uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7959                               (*(Bytes.data() + Index + 1) & 0xff) << 8 |
7960                               (*(Bytes.data() + Index + 2) & 0xff) << 16 |
7961                               (*(Bytes.data() + Index + 3) & 0xff) << 24;
7962             outs() << format("\t.long\t0x%08x\n", opcode);
7963             Size = 4;
7964           } else if (Arch == Triple::arm) {
7965             assert(IsThumb && "ARM mode should have been dealt with above");
7966             uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7967                               (*(Bytes.data() + Index + 1) & 0xff) << 8;
7968             outs() << format("\t.short\t0x%04x\n", opcode);
7969             Size = 2;
7970           } else{
7971             WithColor::warning(errs(), "llvm-objdump")
7972                 << "invalid instruction encoding\n";
7973             if (Size == 0)
7974               Size = 1; // skip illegible bytes
7975           }
7976         }
7977       }
7978       // Now that we are done disassembled the first symbol set the bool that
7979       // were doing this to false.
7980       FirstSymbol = false;
7981     }
7982     if (!symbolTableWorked) {
7983       // Reading the symbol table didn't work, disassemble the whole section.
7984       uint64_t SectAddress = Sections[SectIdx].getAddress();
7985       uint64_t SectSize = Sections[SectIdx].getSize();
7986       uint64_t InstSize;
7987       for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
7988         MCInst Inst;
7989 
7990         uint64_t PC = SectAddress + Index;
7991 
7992         if (DumpAndSkipDataInCode(PC, Bytes.data() + Index, Dices, InstSize))
7993           continue;
7994 
7995         SmallVector<char, 64> AnnotationsBytes;
7996         raw_svector_ostream Annotations(AnnotationsBytes);
7997         if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
7998                                    Annotations)) {
7999           if (LeadingAddr) {
8000             if (FullLeadingAddr) {
8001               if (MachOOF->is64Bit())
8002                 outs() << format("%016" PRIx64, PC);
8003               else
8004                 outs() << format("%08" PRIx64, PC);
8005             } else {
8006               outs() << format("%8" PRIx64 ":", PC);
8007             }
8008           }
8009           if (ShowRawInsn || Arch == Triple::arm) {
8010             outs() << "\t";
8011             dumpBytes(ArrayRef(Bytes.data() + Index, InstSize), outs());
8012           }
8013           StringRef AnnotationsStr = Annotations.str();
8014           IP->printInst(&Inst, PC, AnnotationsStr, *STI, outs());
8015           outs() << "\n";
8016         } else {
8017           if (MachOOF->getArchTriple().isX86()) {
8018             outs() << format("\t.byte 0x%02x #bad opcode\n",
8019                              *(Bytes.data() + Index) & 0xff);
8020             InstSize = 1; // skip exactly one illegible byte and move on.
8021           } else {
8022             WithColor::warning(errs(), "llvm-objdump")
8023                 << "invalid instruction encoding\n";
8024             if (InstSize == 0)
8025               InstSize = 1; // skip illegible bytes
8026           }
8027         }
8028       }
8029     }
8030     // The TripleName's need to be reset if we are called again for a different
8031     // architecture.
8032     TripleName = "";
8033     ThumbTripleName = "";
8034 
8035     if (SymbolizerInfo.demangled_name != nullptr)
8036       free(SymbolizerInfo.demangled_name);
8037     if (ThumbSymbolizerInfo.demangled_name != nullptr)
8038       free(ThumbSymbolizerInfo.demangled_name);
8039   }
8040 }
8041 
8042 //===----------------------------------------------------------------------===//
8043 // __compact_unwind section dumping
8044 //===----------------------------------------------------------------------===//
8045 
8046 namespace {
8047 
8048 template <typename T>
8049 static uint64_t read(StringRef Contents, ptrdiff_t Offset) {
8050   using llvm::support::little;
8051   using llvm::support::unaligned;
8052 
8053   if (Offset + sizeof(T) > Contents.size()) {
8054     outs() << "warning: attempt to read past end of buffer\n";
8055     return T();
8056   }
8057 
8058   uint64_t Val =
8059       support::endian::read<T, little, unaligned>(Contents.data() + Offset);
8060   return Val;
8061 }
8062 
8063 template <typename T>
8064 static uint64_t readNext(StringRef Contents, ptrdiff_t &Offset) {
8065   T Val = read<T>(Contents, Offset);
8066   Offset += sizeof(T);
8067   return Val;
8068 }
8069 
8070 struct CompactUnwindEntry {
8071   uint32_t OffsetInSection;
8072 
8073   uint64_t FunctionAddr;
8074   uint32_t Length;
8075   uint32_t CompactEncoding;
8076   uint64_t PersonalityAddr;
8077   uint64_t LSDAAddr;
8078 
8079   RelocationRef FunctionReloc;
8080   RelocationRef PersonalityReloc;
8081   RelocationRef LSDAReloc;
8082 
8083   CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
8084       : OffsetInSection(Offset) {
8085     if (Is64)
8086       read<uint64_t>(Contents, Offset);
8087     else
8088       read<uint32_t>(Contents, Offset);
8089   }
8090 
8091 private:
8092   template <typename UIntPtr> void read(StringRef Contents, ptrdiff_t Offset) {
8093     FunctionAddr = readNext<UIntPtr>(Contents, Offset);
8094     Length = readNext<uint32_t>(Contents, Offset);
8095     CompactEncoding = readNext<uint32_t>(Contents, Offset);
8096     PersonalityAddr = readNext<UIntPtr>(Contents, Offset);
8097     LSDAAddr = readNext<UIntPtr>(Contents, Offset);
8098   }
8099 };
8100 }
8101 
8102 /// Given a relocation from __compact_unwind, consisting of the RelocationRef
8103 /// and data being relocated, determine the best base Name and Addend to use for
8104 /// display purposes.
8105 ///
8106 /// 1. An Extern relocation will directly reference a symbol (and the data is
8107 ///    then already an addend), so use that.
8108 /// 2. Otherwise the data is an offset in the object file's layout; try to find
8109 //     a symbol before it in the same section, and use the offset from there.
8110 /// 3. Finally, if all that fails, fall back to an offset from the start of the
8111 ///    referenced section.
8112 static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
8113                                       std::map<uint64_t, SymbolRef> &Symbols,
8114                                       const RelocationRef &Reloc, uint64_t Addr,
8115                                       StringRef &Name, uint64_t &Addend) {
8116   if (Reloc.getSymbol() != Obj->symbol_end()) {
8117     Name = unwrapOrError(Reloc.getSymbol()->getName(), Obj->getFileName());
8118     Addend = Addr;
8119     return;
8120   }
8121 
8122   auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
8123   SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
8124 
8125   uint64_t SectionAddr = RelocSection.getAddress();
8126 
8127   auto Sym = Symbols.upper_bound(Addr);
8128   if (Sym == Symbols.begin()) {
8129     // The first symbol in the object is after this reference, the best we can
8130     // do is section-relative notation.
8131     if (Expected<StringRef> NameOrErr = RelocSection.getName())
8132       Name = *NameOrErr;
8133     else
8134       consumeError(NameOrErr.takeError());
8135 
8136     Addend = Addr - SectionAddr;
8137     return;
8138   }
8139 
8140   // Go back one so that SymbolAddress <= Addr.
8141   --Sym;
8142 
8143   section_iterator SymSection =
8144       unwrapOrError(Sym->second.getSection(), Obj->getFileName());
8145   if (RelocSection == *SymSection) {
8146     // There's a valid symbol in the same section before this reference.
8147     Name = unwrapOrError(Sym->second.getName(), Obj->getFileName());
8148     Addend = Addr - Sym->first;
8149     return;
8150   }
8151 
8152   // There is a symbol before this reference, but it's in a different
8153   // section. Probably not helpful to mention it, so use the section name.
8154   if (Expected<StringRef> NameOrErr = RelocSection.getName())
8155     Name = *NameOrErr;
8156   else
8157     consumeError(NameOrErr.takeError());
8158 
8159   Addend = Addr - SectionAddr;
8160 }
8161 
8162 static void printUnwindRelocDest(const MachOObjectFile *Obj,
8163                                  std::map<uint64_t, SymbolRef> &Symbols,
8164                                  const RelocationRef &Reloc, uint64_t Addr) {
8165   StringRef Name;
8166   uint64_t Addend;
8167 
8168   if (!Reloc.getObject())
8169     return;
8170 
8171   findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
8172 
8173   outs() << Name;
8174   if (Addend)
8175     outs() << " + " << format("0x%" PRIx64, Addend);
8176 }
8177 
8178 static void
8179 printMachOCompactUnwindSection(const MachOObjectFile *Obj,
8180                                std::map<uint64_t, SymbolRef> &Symbols,
8181                                const SectionRef &CompactUnwind) {
8182 
8183   if (!Obj->isLittleEndian()) {
8184     outs() << "Skipping big-endian __compact_unwind section\n";
8185     return;
8186   }
8187 
8188   bool Is64 = Obj->is64Bit();
8189   uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
8190   uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
8191 
8192   StringRef Contents =
8193       unwrapOrError(CompactUnwind.getContents(), Obj->getFileName());
8194   SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
8195 
8196   // First populate the initial raw offsets, encodings and so on from the entry.
8197   for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
8198     CompactUnwindEntry Entry(Contents, Offset, Is64);
8199     CompactUnwinds.push_back(Entry);
8200   }
8201 
8202   // Next we need to look at the relocations to find out what objects are
8203   // actually being referred to.
8204   for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
8205     uint64_t RelocAddress = Reloc.getOffset();
8206 
8207     uint32_t EntryIdx = RelocAddress / EntrySize;
8208     uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
8209     CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
8210 
8211     if (OffsetInEntry == 0)
8212       Entry.FunctionReloc = Reloc;
8213     else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
8214       Entry.PersonalityReloc = Reloc;
8215     else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
8216       Entry.LSDAReloc = Reloc;
8217     else {
8218       outs() << "Invalid relocation in __compact_unwind section\n";
8219       return;
8220     }
8221   }
8222 
8223   // Finally, we're ready to print the data we've gathered.
8224   outs() << "Contents of __compact_unwind section:\n";
8225   for (auto &Entry : CompactUnwinds) {
8226     outs() << "  Entry at offset "
8227            << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
8228 
8229     // 1. Start of the region this entry applies to.
8230     outs() << "    start:                " << format("0x%" PRIx64,
8231                                                      Entry.FunctionAddr) << ' ';
8232     printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
8233     outs() << '\n';
8234 
8235     // 2. Length of the region this entry applies to.
8236     outs() << "    length:               " << format("0x%" PRIx32, Entry.Length)
8237            << '\n';
8238     // 3. The 32-bit compact encoding.
8239     outs() << "    compact encoding:     "
8240            << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
8241 
8242     // 4. The personality function, if present.
8243     if (Entry.PersonalityReloc.getObject()) {
8244       outs() << "    personality function: "
8245              << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
8246       printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
8247                            Entry.PersonalityAddr);
8248       outs() << '\n';
8249     }
8250 
8251     // 5. This entry's language-specific data area.
8252     if (Entry.LSDAReloc.getObject()) {
8253       outs() << "    LSDA:                 " << format("0x%" PRIx64,
8254                                                        Entry.LSDAAddr) << ' ';
8255       printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
8256       outs() << '\n';
8257     }
8258   }
8259 }
8260 
8261 //===----------------------------------------------------------------------===//
8262 // __unwind_info section dumping
8263 //===----------------------------------------------------------------------===//
8264 
8265 static void printRegularSecondLevelUnwindPage(StringRef PageData) {
8266   ptrdiff_t Pos = 0;
8267   uint32_t Kind = readNext<uint32_t>(PageData, Pos);
8268   (void)Kind;
8269   assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
8270 
8271   uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
8272   uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
8273 
8274   Pos = EntriesStart;
8275   for (unsigned i = 0; i < NumEntries; ++i) {
8276     uint32_t FunctionOffset = readNext<uint32_t>(PageData, Pos);
8277     uint32_t Encoding = readNext<uint32_t>(PageData, Pos);
8278 
8279     outs() << "      [" << i << "]: "
8280            << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
8281            << ", "
8282            << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
8283   }
8284 }
8285 
8286 static void printCompressedSecondLevelUnwindPage(
8287     StringRef PageData, uint32_t FunctionBase,
8288     const SmallVectorImpl<uint32_t> &CommonEncodings) {
8289   ptrdiff_t Pos = 0;
8290   uint32_t Kind = readNext<uint32_t>(PageData, Pos);
8291   (void)Kind;
8292   assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
8293 
8294   uint32_t NumCommonEncodings = CommonEncodings.size();
8295   uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
8296   uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
8297 
8298   uint16_t PageEncodingsStart = readNext<uint16_t>(PageData, Pos);
8299   uint16_t NumPageEncodings = readNext<uint16_t>(PageData, Pos);
8300   SmallVector<uint32_t, 64> PageEncodings;
8301   if (NumPageEncodings) {
8302     outs() << "      Page encodings: (count = " << NumPageEncodings << ")\n";
8303     Pos = PageEncodingsStart;
8304     for (unsigned i = 0; i < NumPageEncodings; ++i) {
8305       uint32_t Encoding = readNext<uint32_t>(PageData, Pos);
8306       PageEncodings.push_back(Encoding);
8307       outs() << "        encoding[" << (i + NumCommonEncodings)
8308              << "]: " << format("0x%08" PRIx32, Encoding) << '\n';
8309     }
8310   }
8311 
8312   Pos = EntriesStart;
8313   for (unsigned i = 0; i < NumEntries; ++i) {
8314     uint32_t Entry = readNext<uint32_t>(PageData, Pos);
8315     uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
8316     uint32_t EncodingIdx = Entry >> 24;
8317 
8318     uint32_t Encoding;
8319     if (EncodingIdx < NumCommonEncodings)
8320       Encoding = CommonEncodings[EncodingIdx];
8321     else
8322       Encoding = PageEncodings[EncodingIdx - NumCommonEncodings];
8323 
8324     outs() << "      [" << i << "]: "
8325            << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
8326            << ", "
8327            << "encoding[" << EncodingIdx
8328            << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
8329   }
8330 }
8331 
8332 static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
8333                                         std::map<uint64_t, SymbolRef> &Symbols,
8334                                         const SectionRef &UnwindInfo) {
8335 
8336   if (!Obj->isLittleEndian()) {
8337     outs() << "Skipping big-endian __unwind_info section\n";
8338     return;
8339   }
8340 
8341   outs() << "Contents of __unwind_info section:\n";
8342 
8343   StringRef Contents =
8344       unwrapOrError(UnwindInfo.getContents(), Obj->getFileName());
8345   ptrdiff_t Pos = 0;
8346 
8347   //===----------------------------------
8348   // Section header
8349   //===----------------------------------
8350 
8351   uint32_t Version = readNext<uint32_t>(Contents, Pos);
8352   outs() << "  Version:                                   "
8353          << format("0x%" PRIx32, Version) << '\n';
8354   if (Version != 1) {
8355     outs() << "    Skipping section with unknown version\n";
8356     return;
8357   }
8358 
8359   uint32_t CommonEncodingsStart = readNext<uint32_t>(Contents, Pos);
8360   outs() << "  Common encodings array section offset:     "
8361          << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
8362   uint32_t NumCommonEncodings = readNext<uint32_t>(Contents, Pos);
8363   outs() << "  Number of common encodings in array:       "
8364          << format("0x%" PRIx32, NumCommonEncodings) << '\n';
8365 
8366   uint32_t PersonalitiesStart = readNext<uint32_t>(Contents, Pos);
8367   outs() << "  Personality function array section offset: "
8368          << format("0x%" PRIx32, PersonalitiesStart) << '\n';
8369   uint32_t NumPersonalities = readNext<uint32_t>(Contents, Pos);
8370   outs() << "  Number of personality functions in array:  "
8371          << format("0x%" PRIx32, NumPersonalities) << '\n';
8372 
8373   uint32_t IndicesStart = readNext<uint32_t>(Contents, Pos);
8374   outs() << "  Index array section offset:                "
8375          << format("0x%" PRIx32, IndicesStart) << '\n';
8376   uint32_t NumIndices = readNext<uint32_t>(Contents, Pos);
8377   outs() << "  Number of indices in array:                "
8378          << format("0x%" PRIx32, NumIndices) << '\n';
8379 
8380   //===----------------------------------
8381   // A shared list of common encodings
8382   //===----------------------------------
8383 
8384   // These occupy indices in the range [0, N] whenever an encoding is referenced
8385   // from a compressed 2nd level index table. In practice the linker only
8386   // creates ~128 of these, so that indices are available to embed encodings in
8387   // the 2nd level index.
8388 
8389   SmallVector<uint32_t, 64> CommonEncodings;
8390   outs() << "  Common encodings: (count = " << NumCommonEncodings << ")\n";
8391   Pos = CommonEncodingsStart;
8392   for (unsigned i = 0; i < NumCommonEncodings; ++i) {
8393     uint32_t Encoding = readNext<uint32_t>(Contents, Pos);
8394     CommonEncodings.push_back(Encoding);
8395 
8396     outs() << "    encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
8397            << '\n';
8398   }
8399 
8400   //===----------------------------------
8401   // Personality functions used in this executable
8402   //===----------------------------------
8403 
8404   // There should be only a handful of these (one per source language,
8405   // roughly). Particularly since they only get 2 bits in the compact encoding.
8406 
8407   outs() << "  Personality functions: (count = " << NumPersonalities << ")\n";
8408   Pos = PersonalitiesStart;
8409   for (unsigned i = 0; i < NumPersonalities; ++i) {
8410     uint32_t PersonalityFn = readNext<uint32_t>(Contents, Pos);
8411     outs() << "    personality[" << i + 1
8412            << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
8413   }
8414 
8415   //===----------------------------------
8416   // The level 1 index entries
8417   //===----------------------------------
8418 
8419   // These specify an approximate place to start searching for the more detailed
8420   // information, sorted by PC.
8421 
8422   struct IndexEntry {
8423     uint32_t FunctionOffset;
8424     uint32_t SecondLevelPageStart;
8425     uint32_t LSDAStart;
8426   };
8427 
8428   SmallVector<IndexEntry, 4> IndexEntries;
8429 
8430   outs() << "  Top level indices: (count = " << NumIndices << ")\n";
8431   Pos = IndicesStart;
8432   for (unsigned i = 0; i < NumIndices; ++i) {
8433     IndexEntry Entry;
8434 
8435     Entry.FunctionOffset = readNext<uint32_t>(Contents, Pos);
8436     Entry.SecondLevelPageStart = readNext<uint32_t>(Contents, Pos);
8437     Entry.LSDAStart = readNext<uint32_t>(Contents, Pos);
8438     IndexEntries.push_back(Entry);
8439 
8440     outs() << "    [" << i << "]: "
8441            << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
8442            << ", "
8443            << "2nd level page offset="
8444            << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
8445            << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
8446   }
8447 
8448   //===----------------------------------
8449   // Next come the LSDA tables
8450   //===----------------------------------
8451 
8452   // The LSDA layout is rather implicit: it's a contiguous array of entries from
8453   // the first top-level index's LSDAOffset to the last (sentinel).
8454 
8455   outs() << "  LSDA descriptors:\n";
8456   Pos = IndexEntries[0].LSDAStart;
8457   const uint32_t LSDASize = 2 * sizeof(uint32_t);
8458   int NumLSDAs =
8459       (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) / LSDASize;
8460 
8461   for (int i = 0; i < NumLSDAs; ++i) {
8462     uint32_t FunctionOffset = readNext<uint32_t>(Contents, Pos);
8463     uint32_t LSDAOffset = readNext<uint32_t>(Contents, Pos);
8464     outs() << "    [" << i << "]: "
8465            << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
8466            << ", "
8467            << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
8468   }
8469 
8470   //===----------------------------------
8471   // Finally, the 2nd level indices
8472   //===----------------------------------
8473 
8474   // Generally these are 4K in size, and have 2 possible forms:
8475   //   + Regular stores up to 511 entries with disparate encodings
8476   //   + Compressed stores up to 1021 entries if few enough compact encoding
8477   //     values are used.
8478   outs() << "  Second level indices:\n";
8479   for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
8480     // The final sentinel top-level index has no associated 2nd level page
8481     if (IndexEntries[i].SecondLevelPageStart == 0)
8482       break;
8483 
8484     outs() << "    Second level index[" << i << "]: "
8485            << "offset in section="
8486            << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
8487            << ", "
8488            << "base function offset="
8489            << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
8490 
8491     Pos = IndexEntries[i].SecondLevelPageStart;
8492     if (Pos + sizeof(uint32_t) > Contents.size()) {
8493       outs() << "warning: invalid offset for second level page: " << Pos << '\n';
8494       continue;
8495     }
8496 
8497     uint32_t Kind =
8498         *reinterpret_cast<const support::ulittle32_t *>(Contents.data() + Pos);
8499     if (Kind == 2)
8500       printRegularSecondLevelUnwindPage(Contents.substr(Pos, 4096));
8501     else if (Kind == 3)
8502       printCompressedSecondLevelUnwindPage(Contents.substr(Pos, 4096),
8503                                            IndexEntries[i].FunctionOffset,
8504                                            CommonEncodings);
8505     else
8506       outs() << "    Skipping 2nd level page with unknown kind " << Kind
8507              << '\n';
8508   }
8509 }
8510 
8511 void objdump::printMachOUnwindInfo(const MachOObjectFile *Obj) {
8512   std::map<uint64_t, SymbolRef> Symbols;
8513   for (const SymbolRef &SymRef : Obj->symbols()) {
8514     // Discard any undefined or absolute symbols. They're not going to take part
8515     // in the convenience lookup for unwind info and just take up resources.
8516     auto SectOrErr = SymRef.getSection();
8517     if (!SectOrErr) {
8518       // TODO: Actually report errors helpfully.
8519       consumeError(SectOrErr.takeError());
8520       continue;
8521     }
8522     section_iterator Section = *SectOrErr;
8523     if (Section == Obj->section_end())
8524       continue;
8525 
8526     uint64_t Addr = cantFail(SymRef.getValue());
8527     Symbols.insert(std::make_pair(Addr, SymRef));
8528   }
8529 
8530   for (const SectionRef &Section : Obj->sections()) {
8531     StringRef SectName;
8532     if (Expected<StringRef> NameOrErr = Section.getName())
8533       SectName = *NameOrErr;
8534     else
8535       consumeError(NameOrErr.takeError());
8536 
8537     if (SectName == "__compact_unwind")
8538       printMachOCompactUnwindSection(Obj, Symbols, Section);
8539     else if (SectName == "__unwind_info")
8540       printMachOUnwindInfoSection(Obj, Symbols, Section);
8541   }
8542 }
8543 
8544 static void PrintMachHeader(uint32_t magic, uint32_t cputype,
8545                             uint32_t cpusubtype, uint32_t filetype,
8546                             uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
8547                             bool verbose) {
8548   outs() << "Mach header\n";
8549   outs() << "      magic cputype cpusubtype  caps    filetype ncmds "
8550             "sizeofcmds      flags\n";
8551   if (verbose) {
8552     if (magic == MachO::MH_MAGIC)
8553       outs() << "   MH_MAGIC";
8554     else if (magic == MachO::MH_MAGIC_64)
8555       outs() << "MH_MAGIC_64";
8556     else
8557       outs() << format(" 0x%08" PRIx32, magic);
8558     switch (cputype) {
8559     case MachO::CPU_TYPE_I386:
8560       outs() << "    I386";
8561       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8562       case MachO::CPU_SUBTYPE_I386_ALL:
8563         outs() << "        ALL";
8564         break;
8565       default:
8566         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8567         break;
8568       }
8569       break;
8570     case MachO::CPU_TYPE_X86_64:
8571       outs() << "  X86_64";
8572       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8573       case MachO::CPU_SUBTYPE_X86_64_ALL:
8574         outs() << "        ALL";
8575         break;
8576       case MachO::CPU_SUBTYPE_X86_64_H:
8577         outs() << "    Haswell";
8578         break;
8579       default:
8580         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8581         break;
8582       }
8583       break;
8584     case MachO::CPU_TYPE_ARM:
8585       outs() << "     ARM";
8586       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8587       case MachO::CPU_SUBTYPE_ARM_ALL:
8588         outs() << "        ALL";
8589         break;
8590       case MachO::CPU_SUBTYPE_ARM_V4T:
8591         outs() << "        V4T";
8592         break;
8593       case MachO::CPU_SUBTYPE_ARM_V5TEJ:
8594         outs() << "      V5TEJ";
8595         break;
8596       case MachO::CPU_SUBTYPE_ARM_XSCALE:
8597         outs() << "     XSCALE";
8598         break;
8599       case MachO::CPU_SUBTYPE_ARM_V6:
8600         outs() << "         V6";
8601         break;
8602       case MachO::CPU_SUBTYPE_ARM_V6M:
8603         outs() << "        V6M";
8604         break;
8605       case MachO::CPU_SUBTYPE_ARM_V7:
8606         outs() << "         V7";
8607         break;
8608       case MachO::CPU_SUBTYPE_ARM_V7EM:
8609         outs() << "       V7EM";
8610         break;
8611       case MachO::CPU_SUBTYPE_ARM_V7K:
8612         outs() << "        V7K";
8613         break;
8614       case MachO::CPU_SUBTYPE_ARM_V7M:
8615         outs() << "        V7M";
8616         break;
8617       case MachO::CPU_SUBTYPE_ARM_V7S:
8618         outs() << "        V7S";
8619         break;
8620       default:
8621         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8622         break;
8623       }
8624       break;
8625     case MachO::CPU_TYPE_ARM64:
8626       outs() << "   ARM64";
8627       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8628       case MachO::CPU_SUBTYPE_ARM64_ALL:
8629         outs() << "        ALL";
8630         break;
8631       case MachO::CPU_SUBTYPE_ARM64_V8:
8632         outs() << "         V8";
8633         break;
8634       case MachO::CPU_SUBTYPE_ARM64E:
8635         outs() << "          E";
8636         break;
8637       default:
8638         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8639         break;
8640       }
8641       break;
8642     case MachO::CPU_TYPE_ARM64_32:
8643       outs() << " ARM64_32";
8644       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8645       case MachO::CPU_SUBTYPE_ARM64_32_V8:
8646         outs() << "        V8";
8647         break;
8648       default:
8649         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8650         break;
8651       }
8652       break;
8653     case MachO::CPU_TYPE_POWERPC:
8654       outs() << "     PPC";
8655       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8656       case MachO::CPU_SUBTYPE_POWERPC_ALL:
8657         outs() << "        ALL";
8658         break;
8659       default:
8660         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8661         break;
8662       }
8663       break;
8664     case MachO::CPU_TYPE_POWERPC64:
8665       outs() << "   PPC64";
8666       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8667       case MachO::CPU_SUBTYPE_POWERPC_ALL:
8668         outs() << "        ALL";
8669         break;
8670       default:
8671         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8672         break;
8673       }
8674       break;
8675     default:
8676       outs() << format(" %7d", cputype);
8677       outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8678       break;
8679     }
8680     if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
8681       outs() << " LIB64";
8682     } else {
8683       outs() << format("  0x%02" PRIx32,
8684                        (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
8685     }
8686     switch (filetype) {
8687     case MachO::MH_OBJECT:
8688       outs() << "      OBJECT";
8689       break;
8690     case MachO::MH_EXECUTE:
8691       outs() << "     EXECUTE";
8692       break;
8693     case MachO::MH_FVMLIB:
8694       outs() << "      FVMLIB";
8695       break;
8696     case MachO::MH_CORE:
8697       outs() << "        CORE";
8698       break;
8699     case MachO::MH_PRELOAD:
8700       outs() << "     PRELOAD";
8701       break;
8702     case MachO::MH_DYLIB:
8703       outs() << "       DYLIB";
8704       break;
8705     case MachO::MH_DYLIB_STUB:
8706       outs() << "  DYLIB_STUB";
8707       break;
8708     case MachO::MH_DYLINKER:
8709       outs() << "    DYLINKER";
8710       break;
8711     case MachO::MH_BUNDLE:
8712       outs() << "      BUNDLE";
8713       break;
8714     case MachO::MH_DSYM:
8715       outs() << "        DSYM";
8716       break;
8717     case MachO::MH_KEXT_BUNDLE:
8718       outs() << "  KEXTBUNDLE";
8719       break;
8720     case MachO::MH_FILESET:
8721       outs() << "     FILESET";
8722       break;
8723     default:
8724       outs() << format("  %10u", filetype);
8725       break;
8726     }
8727     outs() << format(" %5u", ncmds);
8728     outs() << format(" %10u", sizeofcmds);
8729     uint32_t f = flags;
8730     if (f & MachO::MH_NOUNDEFS) {
8731       outs() << "   NOUNDEFS";
8732       f &= ~MachO::MH_NOUNDEFS;
8733     }
8734     if (f & MachO::MH_INCRLINK) {
8735       outs() << " INCRLINK";
8736       f &= ~MachO::MH_INCRLINK;
8737     }
8738     if (f & MachO::MH_DYLDLINK) {
8739       outs() << " DYLDLINK";
8740       f &= ~MachO::MH_DYLDLINK;
8741     }
8742     if (f & MachO::MH_BINDATLOAD) {
8743       outs() << " BINDATLOAD";
8744       f &= ~MachO::MH_BINDATLOAD;
8745     }
8746     if (f & MachO::MH_PREBOUND) {
8747       outs() << " PREBOUND";
8748       f &= ~MachO::MH_PREBOUND;
8749     }
8750     if (f & MachO::MH_SPLIT_SEGS) {
8751       outs() << " SPLIT_SEGS";
8752       f &= ~MachO::MH_SPLIT_SEGS;
8753     }
8754     if (f & MachO::MH_LAZY_INIT) {
8755       outs() << " LAZY_INIT";
8756       f &= ~MachO::MH_LAZY_INIT;
8757     }
8758     if (f & MachO::MH_TWOLEVEL) {
8759       outs() << " TWOLEVEL";
8760       f &= ~MachO::MH_TWOLEVEL;
8761     }
8762     if (f & MachO::MH_FORCE_FLAT) {
8763       outs() << " FORCE_FLAT";
8764       f &= ~MachO::MH_FORCE_FLAT;
8765     }
8766     if (f & MachO::MH_NOMULTIDEFS) {
8767       outs() << " NOMULTIDEFS";
8768       f &= ~MachO::MH_NOMULTIDEFS;
8769     }
8770     if (f & MachO::MH_NOFIXPREBINDING) {
8771       outs() << " NOFIXPREBINDING";
8772       f &= ~MachO::MH_NOFIXPREBINDING;
8773     }
8774     if (f & MachO::MH_PREBINDABLE) {
8775       outs() << " PREBINDABLE";
8776       f &= ~MachO::MH_PREBINDABLE;
8777     }
8778     if (f & MachO::MH_ALLMODSBOUND) {
8779       outs() << " ALLMODSBOUND";
8780       f &= ~MachO::MH_ALLMODSBOUND;
8781     }
8782     if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
8783       outs() << " SUBSECTIONS_VIA_SYMBOLS";
8784       f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
8785     }
8786     if (f & MachO::MH_CANONICAL) {
8787       outs() << " CANONICAL";
8788       f &= ~MachO::MH_CANONICAL;
8789     }
8790     if (f & MachO::MH_WEAK_DEFINES) {
8791       outs() << " WEAK_DEFINES";
8792       f &= ~MachO::MH_WEAK_DEFINES;
8793     }
8794     if (f & MachO::MH_BINDS_TO_WEAK) {
8795       outs() << " BINDS_TO_WEAK";
8796       f &= ~MachO::MH_BINDS_TO_WEAK;
8797     }
8798     if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
8799       outs() << " ALLOW_STACK_EXECUTION";
8800       f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
8801     }
8802     if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
8803       outs() << " DEAD_STRIPPABLE_DYLIB";
8804       f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
8805     }
8806     if (f & MachO::MH_PIE) {
8807       outs() << " PIE";
8808       f &= ~MachO::MH_PIE;
8809     }
8810     if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
8811       outs() << " NO_REEXPORTED_DYLIBS";
8812       f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
8813     }
8814     if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
8815       outs() << " MH_HAS_TLV_DESCRIPTORS";
8816       f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
8817     }
8818     if (f & MachO::MH_NO_HEAP_EXECUTION) {
8819       outs() << " MH_NO_HEAP_EXECUTION";
8820       f &= ~MachO::MH_NO_HEAP_EXECUTION;
8821     }
8822     if (f & MachO::MH_APP_EXTENSION_SAFE) {
8823       outs() << " APP_EXTENSION_SAFE";
8824       f &= ~MachO::MH_APP_EXTENSION_SAFE;
8825     }
8826     if (f & MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO) {
8827       outs() << " NLIST_OUTOFSYNC_WITH_DYLDINFO";
8828       f &= ~MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO;
8829     }
8830     if (f != 0 || flags == 0)
8831       outs() << format(" 0x%08" PRIx32, f);
8832   } else {
8833     outs() << format(" 0x%08" PRIx32, magic);
8834     outs() << format(" %7d", cputype);
8835     outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8836     outs() << format("  0x%02" PRIx32,
8837                      (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
8838     outs() << format("  %10u", filetype);
8839     outs() << format(" %5u", ncmds);
8840     outs() << format(" %10u", sizeofcmds);
8841     outs() << format(" 0x%08" PRIx32, flags);
8842   }
8843   outs() << "\n";
8844 }
8845 
8846 static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
8847                                 StringRef SegName, uint64_t vmaddr,
8848                                 uint64_t vmsize, uint64_t fileoff,
8849                                 uint64_t filesize, uint32_t maxprot,
8850                                 uint32_t initprot, uint32_t nsects,
8851                                 uint32_t flags, uint32_t object_size,
8852                                 bool verbose) {
8853   uint64_t expected_cmdsize;
8854   if (cmd == MachO::LC_SEGMENT) {
8855     outs() << "      cmd LC_SEGMENT\n";
8856     expected_cmdsize = nsects;
8857     expected_cmdsize *= sizeof(struct MachO::section);
8858     expected_cmdsize += sizeof(struct MachO::segment_command);
8859   } else {
8860     outs() << "      cmd LC_SEGMENT_64\n";
8861     expected_cmdsize = nsects;
8862     expected_cmdsize *= sizeof(struct MachO::section_64);
8863     expected_cmdsize += sizeof(struct MachO::segment_command_64);
8864   }
8865   outs() << "  cmdsize " << cmdsize;
8866   if (cmdsize != expected_cmdsize)
8867     outs() << " Inconsistent size\n";
8868   else
8869     outs() << "\n";
8870   outs() << "  segname " << SegName << "\n";
8871   if (cmd == MachO::LC_SEGMENT_64) {
8872     outs() << "   vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
8873     outs() << "   vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
8874   } else {
8875     outs() << "   vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
8876     outs() << "   vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
8877   }
8878   outs() << "  fileoff " << fileoff;
8879   if (fileoff > object_size)
8880     outs() << " (past end of file)\n";
8881   else
8882     outs() << "\n";
8883   outs() << " filesize " << filesize;
8884   if (fileoff + filesize > object_size)
8885     outs() << " (past end of file)\n";
8886   else
8887     outs() << "\n";
8888   if (verbose) {
8889     if ((maxprot &
8890          ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8891            MachO::VM_PROT_EXECUTE)) != 0)
8892       outs() << "  maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
8893     else {
8894       outs() << "  maxprot ";
8895       outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
8896       outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8897       outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
8898     }
8899     if ((initprot &
8900          ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8901            MachO::VM_PROT_EXECUTE)) != 0)
8902       outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
8903     else {
8904       outs() << " initprot ";
8905       outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
8906       outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8907       outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
8908     }
8909   } else {
8910     outs() << "  maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
8911     outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
8912   }
8913   outs() << "   nsects " << nsects << "\n";
8914   if (verbose) {
8915     outs() << "    flags";
8916     if (flags == 0)
8917       outs() << " (none)\n";
8918     else {
8919       if (flags & MachO::SG_HIGHVM) {
8920         outs() << " HIGHVM";
8921         flags &= ~MachO::SG_HIGHVM;
8922       }
8923       if (flags & MachO::SG_FVMLIB) {
8924         outs() << " FVMLIB";
8925         flags &= ~MachO::SG_FVMLIB;
8926       }
8927       if (flags & MachO::SG_NORELOC) {
8928         outs() << " NORELOC";
8929         flags &= ~MachO::SG_NORELOC;
8930       }
8931       if (flags & MachO::SG_PROTECTED_VERSION_1) {
8932         outs() << " PROTECTED_VERSION_1";
8933         flags &= ~MachO::SG_PROTECTED_VERSION_1;
8934       }
8935       if (flags & MachO::SG_READ_ONLY) {
8936         // Apple's otool prints the SG_ prefix for this flag, but not for the
8937         // others.
8938         outs() << " SG_READ_ONLY";
8939         flags &= ~MachO::SG_READ_ONLY;
8940       }
8941       if (flags)
8942         outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
8943       else
8944         outs() << "\n";
8945     }
8946   } else {
8947     outs() << "    flags " << format("0x%" PRIx32, flags) << "\n";
8948   }
8949 }
8950 
8951 static void PrintSection(const char *sectname, const char *segname,
8952                          uint64_t addr, uint64_t size, uint32_t offset,
8953                          uint32_t align, uint32_t reloff, uint32_t nreloc,
8954                          uint32_t flags, uint32_t reserved1, uint32_t reserved2,
8955                          uint32_t cmd, const char *sg_segname,
8956                          uint32_t filetype, uint32_t object_size,
8957                          bool verbose) {
8958   outs() << "Section\n";
8959   outs() << "  sectname " << format("%.16s\n", sectname);
8960   outs() << "   segname " << format("%.16s", segname);
8961   if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
8962     outs() << " (does not match segment)\n";
8963   else
8964     outs() << "\n";
8965   if (cmd == MachO::LC_SEGMENT_64) {
8966     outs() << "      addr " << format("0x%016" PRIx64, addr) << "\n";
8967     outs() << "      size " << format("0x%016" PRIx64, size);
8968   } else {
8969     outs() << "      addr " << format("0x%08" PRIx64, addr) << "\n";
8970     outs() << "      size " << format("0x%08" PRIx64, size);
8971   }
8972   if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
8973     outs() << " (past end of file)\n";
8974   else
8975     outs() << "\n";
8976   outs() << "    offset " << offset;
8977   if (offset > object_size)
8978     outs() << " (past end of file)\n";
8979   else
8980     outs() << "\n";
8981   uint32_t align_shifted = 1 << align;
8982   outs() << "     align 2^" << align << " (" << align_shifted << ")\n";
8983   outs() << "    reloff " << reloff;
8984   if (reloff > object_size)
8985     outs() << " (past end of file)\n";
8986   else
8987     outs() << "\n";
8988   outs() << "    nreloc " << nreloc;
8989   if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
8990     outs() << " (past end of file)\n";
8991   else
8992     outs() << "\n";
8993   uint32_t section_type = flags & MachO::SECTION_TYPE;
8994   if (verbose) {
8995     outs() << "      type";
8996     if (section_type == MachO::S_REGULAR)
8997       outs() << " S_REGULAR\n";
8998     else if (section_type == MachO::S_ZEROFILL)
8999       outs() << " S_ZEROFILL\n";
9000     else if (section_type == MachO::S_CSTRING_LITERALS)
9001       outs() << " S_CSTRING_LITERALS\n";
9002     else if (section_type == MachO::S_4BYTE_LITERALS)
9003       outs() << " S_4BYTE_LITERALS\n";
9004     else if (section_type == MachO::S_8BYTE_LITERALS)
9005       outs() << " S_8BYTE_LITERALS\n";
9006     else if (section_type == MachO::S_16BYTE_LITERALS)
9007       outs() << " S_16BYTE_LITERALS\n";
9008     else if (section_type == MachO::S_LITERAL_POINTERS)
9009       outs() << " S_LITERAL_POINTERS\n";
9010     else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
9011       outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
9012     else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
9013       outs() << " S_LAZY_SYMBOL_POINTERS\n";
9014     else if (section_type == MachO::S_SYMBOL_STUBS)
9015       outs() << " S_SYMBOL_STUBS\n";
9016     else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
9017       outs() << " S_MOD_INIT_FUNC_POINTERS\n";
9018     else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
9019       outs() << " S_MOD_TERM_FUNC_POINTERS\n";
9020     else if (section_type == MachO::S_COALESCED)
9021       outs() << " S_COALESCED\n";
9022     else if (section_type == MachO::S_INTERPOSING)
9023       outs() << " S_INTERPOSING\n";
9024     else if (section_type == MachO::S_DTRACE_DOF)
9025       outs() << " S_DTRACE_DOF\n";
9026     else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
9027       outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
9028     else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
9029       outs() << " S_THREAD_LOCAL_REGULAR\n";
9030     else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
9031       outs() << " S_THREAD_LOCAL_ZEROFILL\n";
9032     else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
9033       outs() << " S_THREAD_LOCAL_VARIABLES\n";
9034     else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
9035       outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
9036     else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
9037       outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
9038     else if (section_type == MachO::S_INIT_FUNC_OFFSETS)
9039       outs() << " S_INIT_FUNC_OFFSETS\n";
9040     else
9041       outs() << format("0x%08" PRIx32, section_type) << "\n";
9042     outs() << "attributes";
9043     uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
9044     if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
9045       outs() << " PURE_INSTRUCTIONS";
9046     if (section_attributes & MachO::S_ATTR_NO_TOC)
9047       outs() << " NO_TOC";
9048     if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
9049       outs() << " STRIP_STATIC_SYMS";
9050     if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
9051       outs() << " NO_DEAD_STRIP";
9052     if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
9053       outs() << " LIVE_SUPPORT";
9054     if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
9055       outs() << " SELF_MODIFYING_CODE";
9056     if (section_attributes & MachO::S_ATTR_DEBUG)
9057       outs() << " DEBUG";
9058     if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
9059       outs() << " SOME_INSTRUCTIONS";
9060     if (section_attributes & MachO::S_ATTR_EXT_RELOC)
9061       outs() << " EXT_RELOC";
9062     if (section_attributes & MachO::S_ATTR_LOC_RELOC)
9063       outs() << " LOC_RELOC";
9064     if (section_attributes == 0)
9065       outs() << " (none)";
9066     outs() << "\n";
9067   } else
9068     outs() << "     flags " << format("0x%08" PRIx32, flags) << "\n";
9069   outs() << " reserved1 " << reserved1;
9070   if (section_type == MachO::S_SYMBOL_STUBS ||
9071       section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
9072       section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
9073       section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
9074       section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
9075     outs() << " (index into indirect symbol table)\n";
9076   else
9077     outs() << "\n";
9078   outs() << " reserved2 " << reserved2;
9079   if (section_type == MachO::S_SYMBOL_STUBS)
9080     outs() << " (size of stubs)\n";
9081   else
9082     outs() << "\n";
9083 }
9084 
9085 static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
9086                                    uint32_t object_size) {
9087   outs() << "     cmd LC_SYMTAB\n";
9088   outs() << " cmdsize " << st.cmdsize;
9089   if (st.cmdsize != sizeof(struct MachO::symtab_command))
9090     outs() << " Incorrect size\n";
9091   else
9092     outs() << "\n";
9093   outs() << "  symoff " << st.symoff;
9094   if (st.symoff > object_size)
9095     outs() << " (past end of file)\n";
9096   else
9097     outs() << "\n";
9098   outs() << "   nsyms " << st.nsyms;
9099   uint64_t big_size;
9100   if (Is64Bit) {
9101     big_size = st.nsyms;
9102     big_size *= sizeof(struct MachO::nlist_64);
9103     big_size += st.symoff;
9104     if (big_size > object_size)
9105       outs() << " (past end of file)\n";
9106     else
9107       outs() << "\n";
9108   } else {
9109     big_size = st.nsyms;
9110     big_size *= sizeof(struct MachO::nlist);
9111     big_size += st.symoff;
9112     if (big_size > object_size)
9113       outs() << " (past end of file)\n";
9114     else
9115       outs() << "\n";
9116   }
9117   outs() << "  stroff " << st.stroff;
9118   if (st.stroff > object_size)
9119     outs() << " (past end of file)\n";
9120   else
9121     outs() << "\n";
9122   outs() << " strsize " << st.strsize;
9123   big_size = st.stroff;
9124   big_size += st.strsize;
9125   if (big_size > object_size)
9126     outs() << " (past end of file)\n";
9127   else
9128     outs() << "\n";
9129 }
9130 
9131 static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
9132                                      uint32_t nsyms, uint32_t object_size,
9133                                      bool Is64Bit) {
9134   outs() << "            cmd LC_DYSYMTAB\n";
9135   outs() << "        cmdsize " << dyst.cmdsize;
9136   if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
9137     outs() << " Incorrect size\n";
9138   else
9139     outs() << "\n";
9140   outs() << "      ilocalsym " << dyst.ilocalsym;
9141   if (dyst.ilocalsym > nsyms)
9142     outs() << " (greater than the number of symbols)\n";
9143   else
9144     outs() << "\n";
9145   outs() << "      nlocalsym " << dyst.nlocalsym;
9146   uint64_t big_size;
9147   big_size = dyst.ilocalsym;
9148   big_size += dyst.nlocalsym;
9149   if (big_size > nsyms)
9150     outs() << " (past the end of the symbol table)\n";
9151   else
9152     outs() << "\n";
9153   outs() << "     iextdefsym " << dyst.iextdefsym;
9154   if (dyst.iextdefsym > nsyms)
9155     outs() << " (greater than the number of symbols)\n";
9156   else
9157     outs() << "\n";
9158   outs() << "     nextdefsym " << dyst.nextdefsym;
9159   big_size = dyst.iextdefsym;
9160   big_size += dyst.nextdefsym;
9161   if (big_size > nsyms)
9162     outs() << " (past the end of the symbol table)\n";
9163   else
9164     outs() << "\n";
9165   outs() << "      iundefsym " << dyst.iundefsym;
9166   if (dyst.iundefsym > nsyms)
9167     outs() << " (greater than the number of symbols)\n";
9168   else
9169     outs() << "\n";
9170   outs() << "      nundefsym " << dyst.nundefsym;
9171   big_size = dyst.iundefsym;
9172   big_size += dyst.nundefsym;
9173   if (big_size > nsyms)
9174     outs() << " (past the end of the symbol table)\n";
9175   else
9176     outs() << "\n";
9177   outs() << "         tocoff " << dyst.tocoff;
9178   if (dyst.tocoff > object_size)
9179     outs() << " (past end of file)\n";
9180   else
9181     outs() << "\n";
9182   outs() << "           ntoc " << dyst.ntoc;
9183   big_size = dyst.ntoc;
9184   big_size *= sizeof(struct MachO::dylib_table_of_contents);
9185   big_size += dyst.tocoff;
9186   if (big_size > object_size)
9187     outs() << " (past end of file)\n";
9188   else
9189     outs() << "\n";
9190   outs() << "      modtaboff " << dyst.modtaboff;
9191   if (dyst.modtaboff > object_size)
9192     outs() << " (past end of file)\n";
9193   else
9194     outs() << "\n";
9195   outs() << "        nmodtab " << dyst.nmodtab;
9196   uint64_t modtabend;
9197   if (Is64Bit) {
9198     modtabend = dyst.nmodtab;
9199     modtabend *= sizeof(struct MachO::dylib_module_64);
9200     modtabend += dyst.modtaboff;
9201   } else {
9202     modtabend = dyst.nmodtab;
9203     modtabend *= sizeof(struct MachO::dylib_module);
9204     modtabend += dyst.modtaboff;
9205   }
9206   if (modtabend > object_size)
9207     outs() << " (past end of file)\n";
9208   else
9209     outs() << "\n";
9210   outs() << "   extrefsymoff " << dyst.extrefsymoff;
9211   if (dyst.extrefsymoff > object_size)
9212     outs() << " (past end of file)\n";
9213   else
9214     outs() << "\n";
9215   outs() << "    nextrefsyms " << dyst.nextrefsyms;
9216   big_size = dyst.nextrefsyms;
9217   big_size *= sizeof(struct MachO::dylib_reference);
9218   big_size += dyst.extrefsymoff;
9219   if (big_size > object_size)
9220     outs() << " (past end of file)\n";
9221   else
9222     outs() << "\n";
9223   outs() << " indirectsymoff " << dyst.indirectsymoff;
9224   if (dyst.indirectsymoff > object_size)
9225     outs() << " (past end of file)\n";
9226   else
9227     outs() << "\n";
9228   outs() << "  nindirectsyms " << dyst.nindirectsyms;
9229   big_size = dyst.nindirectsyms;
9230   big_size *= sizeof(uint32_t);
9231   big_size += dyst.indirectsymoff;
9232   if (big_size > object_size)
9233     outs() << " (past end of file)\n";
9234   else
9235     outs() << "\n";
9236   outs() << "      extreloff " << dyst.extreloff;
9237   if (dyst.extreloff > object_size)
9238     outs() << " (past end of file)\n";
9239   else
9240     outs() << "\n";
9241   outs() << "        nextrel " << dyst.nextrel;
9242   big_size = dyst.nextrel;
9243   big_size *= sizeof(struct MachO::relocation_info);
9244   big_size += dyst.extreloff;
9245   if (big_size > object_size)
9246     outs() << " (past end of file)\n";
9247   else
9248     outs() << "\n";
9249   outs() << "      locreloff " << dyst.locreloff;
9250   if (dyst.locreloff > object_size)
9251     outs() << " (past end of file)\n";
9252   else
9253     outs() << "\n";
9254   outs() << "        nlocrel " << dyst.nlocrel;
9255   big_size = dyst.nlocrel;
9256   big_size *= sizeof(struct MachO::relocation_info);
9257   big_size += dyst.locreloff;
9258   if (big_size > object_size)
9259     outs() << " (past end of file)\n";
9260   else
9261     outs() << "\n";
9262 }
9263 
9264 static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
9265                                      uint32_t object_size) {
9266   if (dc.cmd == MachO::LC_DYLD_INFO)
9267     outs() << "            cmd LC_DYLD_INFO\n";
9268   else
9269     outs() << "            cmd LC_DYLD_INFO_ONLY\n";
9270   outs() << "        cmdsize " << dc.cmdsize;
9271   if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
9272     outs() << " Incorrect size\n";
9273   else
9274     outs() << "\n";
9275   outs() << "     rebase_off " << dc.rebase_off;
9276   if (dc.rebase_off > object_size)
9277     outs() << " (past end of file)\n";
9278   else
9279     outs() << "\n";
9280   outs() << "    rebase_size " << dc.rebase_size;
9281   uint64_t big_size;
9282   big_size = dc.rebase_off;
9283   big_size += dc.rebase_size;
9284   if (big_size > object_size)
9285     outs() << " (past end of file)\n";
9286   else
9287     outs() << "\n";
9288   outs() << "       bind_off " << dc.bind_off;
9289   if (dc.bind_off > object_size)
9290     outs() << " (past end of file)\n";
9291   else
9292     outs() << "\n";
9293   outs() << "      bind_size " << dc.bind_size;
9294   big_size = dc.bind_off;
9295   big_size += dc.bind_size;
9296   if (big_size > object_size)
9297     outs() << " (past end of file)\n";
9298   else
9299     outs() << "\n";
9300   outs() << "  weak_bind_off " << dc.weak_bind_off;
9301   if (dc.weak_bind_off > object_size)
9302     outs() << " (past end of file)\n";
9303   else
9304     outs() << "\n";
9305   outs() << " weak_bind_size " << dc.weak_bind_size;
9306   big_size = dc.weak_bind_off;
9307   big_size += dc.weak_bind_size;
9308   if (big_size > object_size)
9309     outs() << " (past end of file)\n";
9310   else
9311     outs() << "\n";
9312   outs() << "  lazy_bind_off " << dc.lazy_bind_off;
9313   if (dc.lazy_bind_off > object_size)
9314     outs() << " (past end of file)\n";
9315   else
9316     outs() << "\n";
9317   outs() << " lazy_bind_size " << dc.lazy_bind_size;
9318   big_size = dc.lazy_bind_off;
9319   big_size += dc.lazy_bind_size;
9320   if (big_size > object_size)
9321     outs() << " (past end of file)\n";
9322   else
9323     outs() << "\n";
9324   outs() << "     export_off " << dc.export_off;
9325   if (dc.export_off > object_size)
9326     outs() << " (past end of file)\n";
9327   else
9328     outs() << "\n";
9329   outs() << "    export_size " << dc.export_size;
9330   big_size = dc.export_off;
9331   big_size += dc.export_size;
9332   if (big_size > object_size)
9333     outs() << " (past end of file)\n";
9334   else
9335     outs() << "\n";
9336 }
9337 
9338 static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
9339                                  const char *Ptr) {
9340   if (dyld.cmd == MachO::LC_ID_DYLINKER)
9341     outs() << "          cmd LC_ID_DYLINKER\n";
9342   else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
9343     outs() << "          cmd LC_LOAD_DYLINKER\n";
9344   else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
9345     outs() << "          cmd LC_DYLD_ENVIRONMENT\n";
9346   else
9347     outs() << "          cmd ?(" << dyld.cmd << ")\n";
9348   outs() << "      cmdsize " << dyld.cmdsize;
9349   if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
9350     outs() << " Incorrect size\n";
9351   else
9352     outs() << "\n";
9353   if (dyld.name >= dyld.cmdsize)
9354     outs() << "         name ?(bad offset " << dyld.name << ")\n";
9355   else {
9356     const char *P = (const char *)(Ptr) + dyld.name;
9357     outs() << "         name " << P << " (offset " << dyld.name << ")\n";
9358   }
9359 }
9360 
9361 static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
9362   outs() << "     cmd LC_UUID\n";
9363   outs() << " cmdsize " << uuid.cmdsize;
9364   if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
9365     outs() << " Incorrect size\n";
9366   else
9367     outs() << "\n";
9368   outs() << "    uuid ";
9369   for (int i = 0; i < 16; ++i) {
9370     outs() << format("%02" PRIX32, uuid.uuid[i]);
9371     if (i == 3 || i == 5 || i == 7 || i == 9)
9372       outs() << "-";
9373   }
9374   outs() << "\n";
9375 }
9376 
9377 static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
9378   outs() << "          cmd LC_RPATH\n";
9379   outs() << "      cmdsize " << rpath.cmdsize;
9380   if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
9381     outs() << " Incorrect size\n";
9382   else
9383     outs() << "\n";
9384   if (rpath.path >= rpath.cmdsize)
9385     outs() << "         path ?(bad offset " << rpath.path << ")\n";
9386   else {
9387     const char *P = (const char *)(Ptr) + rpath.path;
9388     outs() << "         path " << P << " (offset " << rpath.path << ")\n";
9389   }
9390 }
9391 
9392 static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
9393   StringRef LoadCmdName;
9394   switch (vd.cmd) {
9395   case MachO::LC_VERSION_MIN_MACOSX:
9396     LoadCmdName = "LC_VERSION_MIN_MACOSX";
9397     break;
9398   case MachO::LC_VERSION_MIN_IPHONEOS:
9399     LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
9400     break;
9401   case MachO::LC_VERSION_MIN_TVOS:
9402     LoadCmdName = "LC_VERSION_MIN_TVOS";
9403     break;
9404   case MachO::LC_VERSION_MIN_WATCHOS:
9405     LoadCmdName = "LC_VERSION_MIN_WATCHOS";
9406     break;
9407   default:
9408     llvm_unreachable("Unknown version min load command");
9409   }
9410 
9411   outs() << "      cmd " << LoadCmdName << '\n';
9412   outs() << "  cmdsize " << vd.cmdsize;
9413   if (vd.cmdsize != sizeof(struct MachO::version_min_command))
9414     outs() << " Incorrect size\n";
9415   else
9416     outs() << "\n";
9417   outs() << "  version "
9418          << MachOObjectFile::getVersionMinMajor(vd, false) << "."
9419          << MachOObjectFile::getVersionMinMinor(vd, false);
9420   uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
9421   if (Update != 0)
9422     outs() << "." << Update;
9423   outs() << "\n";
9424   if (vd.sdk == 0)
9425     outs() << "      sdk n/a";
9426   else {
9427     outs() << "      sdk "
9428            << MachOObjectFile::getVersionMinMajor(vd, true) << "."
9429            << MachOObjectFile::getVersionMinMinor(vd, true);
9430   }
9431   Update = MachOObjectFile::getVersionMinUpdate(vd, true);
9432   if (Update != 0)
9433     outs() << "." << Update;
9434   outs() << "\n";
9435 }
9436 
9437 static void PrintNoteLoadCommand(MachO::note_command Nt) {
9438   outs() << "       cmd LC_NOTE\n";
9439   outs() << "   cmdsize " << Nt.cmdsize;
9440   if (Nt.cmdsize != sizeof(struct MachO::note_command))
9441     outs() << " Incorrect size\n";
9442   else
9443     outs() << "\n";
9444   const char *d = Nt.data_owner;
9445   outs() << "data_owner " << format("%.16s\n", d);
9446   outs() << "    offset " << Nt.offset << "\n";
9447   outs() << "      size " << Nt.size << "\n";
9448 }
9449 
9450 static void PrintBuildToolVersion(MachO::build_tool_version bv, bool verbose) {
9451   outs() << "      tool ";
9452   if (verbose)
9453     outs() << MachOObjectFile::getBuildTool(bv.tool);
9454   else
9455     outs() << bv.tool;
9456   outs() << "\n";
9457   outs() << "   version " << MachOObjectFile::getVersionString(bv.version)
9458          << "\n";
9459 }
9460 
9461 static void PrintBuildVersionLoadCommand(const MachOObjectFile *obj,
9462                                          MachO::build_version_command bd,
9463                                          bool verbose) {
9464   outs() << "       cmd LC_BUILD_VERSION\n";
9465   outs() << "   cmdsize " << bd.cmdsize;
9466   if (bd.cmdsize !=
9467       sizeof(struct MachO::build_version_command) +
9468           bd.ntools * sizeof(struct MachO::build_tool_version))
9469     outs() << " Incorrect size\n";
9470   else
9471     outs() << "\n";
9472   outs() << "  platform ";
9473   if (verbose)
9474     outs() << MachOObjectFile::getBuildPlatform(bd.platform);
9475   else
9476     outs() << bd.platform;
9477   outs() << "\n";
9478   if (bd.sdk)
9479     outs() << "       sdk " << MachOObjectFile::getVersionString(bd.sdk)
9480            << "\n";
9481   else
9482     outs() << "       sdk n/a\n";
9483   outs() << "     minos " << MachOObjectFile::getVersionString(bd.minos)
9484          << "\n";
9485   outs() << "    ntools " << bd.ntools << "\n";
9486   for (unsigned i = 0; i < bd.ntools; ++i) {
9487     MachO::build_tool_version bv = obj->getBuildToolVersion(i);
9488     PrintBuildToolVersion(bv, verbose);
9489   }
9490 }
9491 
9492 static void PrintSourceVersionCommand(MachO::source_version_command sd) {
9493   outs() << "      cmd LC_SOURCE_VERSION\n";
9494   outs() << "  cmdsize " << sd.cmdsize;
9495   if (sd.cmdsize != sizeof(struct MachO::source_version_command))
9496     outs() << " Incorrect size\n";
9497   else
9498     outs() << "\n";
9499   uint64_t a = (sd.version >> 40) & 0xffffff;
9500   uint64_t b = (sd.version >> 30) & 0x3ff;
9501   uint64_t c = (sd.version >> 20) & 0x3ff;
9502   uint64_t d = (sd.version >> 10) & 0x3ff;
9503   uint64_t e = sd.version & 0x3ff;
9504   outs() << "  version " << a << "." << b;
9505   if (e != 0)
9506     outs() << "." << c << "." << d << "." << e;
9507   else if (d != 0)
9508     outs() << "." << c << "." << d;
9509   else if (c != 0)
9510     outs() << "." << c;
9511   outs() << "\n";
9512 }
9513 
9514 static void PrintEntryPointCommand(MachO::entry_point_command ep) {
9515   outs() << "       cmd LC_MAIN\n";
9516   outs() << "   cmdsize " << ep.cmdsize;
9517   if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
9518     outs() << " Incorrect size\n";
9519   else
9520     outs() << "\n";
9521   outs() << "  entryoff " << ep.entryoff << "\n";
9522   outs() << " stacksize " << ep.stacksize << "\n";
9523 }
9524 
9525 static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
9526                                        uint32_t object_size) {
9527   outs() << "          cmd LC_ENCRYPTION_INFO\n";
9528   outs() << "      cmdsize " << ec.cmdsize;
9529   if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
9530     outs() << " Incorrect size\n";
9531   else
9532     outs() << "\n";
9533   outs() << "     cryptoff " << ec.cryptoff;
9534   if (ec.cryptoff > object_size)
9535     outs() << " (past end of file)\n";
9536   else
9537     outs() << "\n";
9538   outs() << "    cryptsize " << ec.cryptsize;
9539   if (ec.cryptsize > object_size)
9540     outs() << " (past end of file)\n";
9541   else
9542     outs() << "\n";
9543   outs() << "      cryptid " << ec.cryptid << "\n";
9544 }
9545 
9546 static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
9547                                          uint32_t object_size) {
9548   outs() << "          cmd LC_ENCRYPTION_INFO_64\n";
9549   outs() << "      cmdsize " << ec.cmdsize;
9550   if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
9551     outs() << " Incorrect size\n";
9552   else
9553     outs() << "\n";
9554   outs() << "     cryptoff " << ec.cryptoff;
9555   if (ec.cryptoff > object_size)
9556     outs() << " (past end of file)\n";
9557   else
9558     outs() << "\n";
9559   outs() << "    cryptsize " << ec.cryptsize;
9560   if (ec.cryptsize > object_size)
9561     outs() << " (past end of file)\n";
9562   else
9563     outs() << "\n";
9564   outs() << "      cryptid " << ec.cryptid << "\n";
9565   outs() << "          pad " << ec.pad << "\n";
9566 }
9567 
9568 static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
9569                                      const char *Ptr) {
9570   outs() << "     cmd LC_LINKER_OPTION\n";
9571   outs() << " cmdsize " << lo.cmdsize;
9572   if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
9573     outs() << " Incorrect size\n";
9574   else
9575     outs() << "\n";
9576   outs() << "   count " << lo.count << "\n";
9577   const char *string = Ptr + sizeof(struct MachO::linker_option_command);
9578   uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
9579   uint32_t i = 0;
9580   while (left > 0) {
9581     while (*string == '\0' && left > 0) {
9582       string++;
9583       left--;
9584     }
9585     if (left > 0) {
9586       i++;
9587       outs() << "  string #" << i << " " << format("%.*s\n", left, string);
9588       uint32_t NullPos = StringRef(string, left).find('\0');
9589       uint32_t len = std::min(NullPos, left) + 1;
9590       string += len;
9591       left -= len;
9592     }
9593   }
9594   if (lo.count != i)
9595     outs() << "   count " << lo.count << " does not match number of strings "
9596            << i << "\n";
9597 }
9598 
9599 static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
9600                                      const char *Ptr) {
9601   outs() << "          cmd LC_SUB_FRAMEWORK\n";
9602   outs() << "      cmdsize " << sub.cmdsize;
9603   if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
9604     outs() << " Incorrect size\n";
9605   else
9606     outs() << "\n";
9607   if (sub.umbrella < sub.cmdsize) {
9608     const char *P = Ptr + sub.umbrella;
9609     outs() << "     umbrella " << P << " (offset " << sub.umbrella << ")\n";
9610   } else {
9611     outs() << "     umbrella ?(bad offset " << sub.umbrella << ")\n";
9612   }
9613 }
9614 
9615 static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
9616                                     const char *Ptr) {
9617   outs() << "          cmd LC_SUB_UMBRELLA\n";
9618   outs() << "      cmdsize " << sub.cmdsize;
9619   if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
9620     outs() << " Incorrect size\n";
9621   else
9622     outs() << "\n";
9623   if (sub.sub_umbrella < sub.cmdsize) {
9624     const char *P = Ptr + sub.sub_umbrella;
9625     outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
9626   } else {
9627     outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
9628   }
9629 }
9630 
9631 static void PrintSubLibraryCommand(MachO::sub_library_command sub,
9632                                    const char *Ptr) {
9633   outs() << "          cmd LC_SUB_LIBRARY\n";
9634   outs() << "      cmdsize " << sub.cmdsize;
9635   if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
9636     outs() << " Incorrect size\n";
9637   else
9638     outs() << "\n";
9639   if (sub.sub_library < sub.cmdsize) {
9640     const char *P = Ptr + sub.sub_library;
9641     outs() << "  sub_library " << P << " (offset " << sub.sub_library << ")\n";
9642   } else {
9643     outs() << "  sub_library ?(bad offset " << sub.sub_library << ")\n";
9644   }
9645 }
9646 
9647 static void PrintSubClientCommand(MachO::sub_client_command sub,
9648                                   const char *Ptr) {
9649   outs() << "          cmd LC_SUB_CLIENT\n";
9650   outs() << "      cmdsize " << sub.cmdsize;
9651   if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
9652     outs() << " Incorrect size\n";
9653   else
9654     outs() << "\n";
9655   if (sub.client < sub.cmdsize) {
9656     const char *P = Ptr + sub.client;
9657     outs() << "       client " << P << " (offset " << sub.client << ")\n";
9658   } else {
9659     outs() << "       client ?(bad offset " << sub.client << ")\n";
9660   }
9661 }
9662 
9663 static void PrintRoutinesCommand(MachO::routines_command r) {
9664   outs() << "          cmd LC_ROUTINES\n";
9665   outs() << "      cmdsize " << r.cmdsize;
9666   if (r.cmdsize != sizeof(struct MachO::routines_command))
9667     outs() << " Incorrect size\n";
9668   else
9669     outs() << "\n";
9670   outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
9671   outs() << "  init_module " << r.init_module << "\n";
9672   outs() << "    reserved1 " << r.reserved1 << "\n";
9673   outs() << "    reserved2 " << r.reserved2 << "\n";
9674   outs() << "    reserved3 " << r.reserved3 << "\n";
9675   outs() << "    reserved4 " << r.reserved4 << "\n";
9676   outs() << "    reserved5 " << r.reserved5 << "\n";
9677   outs() << "    reserved6 " << r.reserved6 << "\n";
9678 }
9679 
9680 static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
9681   outs() << "          cmd LC_ROUTINES_64\n";
9682   outs() << "      cmdsize " << r.cmdsize;
9683   if (r.cmdsize != sizeof(struct MachO::routines_command_64))
9684     outs() << " Incorrect size\n";
9685   else
9686     outs() << "\n";
9687   outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
9688   outs() << "  init_module " << r.init_module << "\n";
9689   outs() << "    reserved1 " << r.reserved1 << "\n";
9690   outs() << "    reserved2 " << r.reserved2 << "\n";
9691   outs() << "    reserved3 " << r.reserved3 << "\n";
9692   outs() << "    reserved4 " << r.reserved4 << "\n";
9693   outs() << "    reserved5 " << r.reserved5 << "\n";
9694   outs() << "    reserved6 " << r.reserved6 << "\n";
9695 }
9696 
9697 static void Print_x86_thread_state32_t(MachO::x86_thread_state32_t &cpu32) {
9698   outs() << "\t    eax " << format("0x%08" PRIx32, cpu32.eax);
9699   outs() << " ebx    " << format("0x%08" PRIx32, cpu32.ebx);
9700   outs() << " ecx " << format("0x%08" PRIx32, cpu32.ecx);
9701   outs() << " edx " << format("0x%08" PRIx32, cpu32.edx) << "\n";
9702   outs() << "\t    edi " << format("0x%08" PRIx32, cpu32.edi);
9703   outs() << " esi    " << format("0x%08" PRIx32, cpu32.esi);
9704   outs() << " ebp " << format("0x%08" PRIx32, cpu32.ebp);
9705   outs() << " esp " << format("0x%08" PRIx32, cpu32.esp) << "\n";
9706   outs() << "\t    ss  " << format("0x%08" PRIx32, cpu32.ss);
9707   outs() << " eflags " << format("0x%08" PRIx32, cpu32.eflags);
9708   outs() << " eip " << format("0x%08" PRIx32, cpu32.eip);
9709   outs() << " cs  " << format("0x%08" PRIx32, cpu32.cs) << "\n";
9710   outs() << "\t    ds  " << format("0x%08" PRIx32, cpu32.ds);
9711   outs() << " es     " << format("0x%08" PRIx32, cpu32.es);
9712   outs() << " fs  " << format("0x%08" PRIx32, cpu32.fs);
9713   outs() << " gs  " << format("0x%08" PRIx32, cpu32.gs) << "\n";
9714 }
9715 
9716 static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
9717   outs() << "   rax  " << format("0x%016" PRIx64, cpu64.rax);
9718   outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
9719   outs() << " rcx  " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
9720   outs() << "   rdx  " << format("0x%016" PRIx64, cpu64.rdx);
9721   outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
9722   outs() << " rsi  " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
9723   outs() << "   rbp  " << format("0x%016" PRIx64, cpu64.rbp);
9724   outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
9725   outs() << " r8   " << format("0x%016" PRIx64, cpu64.r8) << "\n";
9726   outs() << "    r9  " << format("0x%016" PRIx64, cpu64.r9);
9727   outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
9728   outs() << " r11  " << format("0x%016" PRIx64, cpu64.r11) << "\n";
9729   outs() << "   r12  " << format("0x%016" PRIx64, cpu64.r12);
9730   outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
9731   outs() << " r14  " << format("0x%016" PRIx64, cpu64.r14) << "\n";
9732   outs() << "   r15  " << format("0x%016" PRIx64, cpu64.r15);
9733   outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
9734   outs() << "rflags  " << format("0x%016" PRIx64, cpu64.rflags);
9735   outs() << " cs  " << format("0x%016" PRIx64, cpu64.cs);
9736   outs() << " fs   " << format("0x%016" PRIx64, cpu64.fs) << "\n";
9737   outs() << "    gs  " << format("0x%016" PRIx64, cpu64.gs) << "\n";
9738 }
9739 
9740 static void Print_mmst_reg(MachO::mmst_reg_t &r) {
9741   uint32_t f;
9742   outs() << "\t      mmst_reg  ";
9743   for (f = 0; f < 10; f++)
9744     outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
9745   outs() << "\n";
9746   outs() << "\t      mmst_rsrv ";
9747   for (f = 0; f < 6; f++)
9748     outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
9749   outs() << "\n";
9750 }
9751 
9752 static void Print_xmm_reg(MachO::xmm_reg_t &r) {
9753   uint32_t f;
9754   outs() << "\t      xmm_reg ";
9755   for (f = 0; f < 16; f++)
9756     outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
9757   outs() << "\n";
9758 }
9759 
9760 static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
9761   outs() << "\t    fpu_reserved[0] " << fpu.fpu_reserved[0];
9762   outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
9763   outs() << "\t    control: invalid " << fpu.fpu_fcw.invalid;
9764   outs() << " denorm " << fpu.fpu_fcw.denorm;
9765   outs() << " zdiv " << fpu.fpu_fcw.zdiv;
9766   outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
9767   outs() << " undfl " << fpu.fpu_fcw.undfl;
9768   outs() << " precis " << fpu.fpu_fcw.precis << "\n";
9769   outs() << "\t\t     pc ";
9770   if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
9771     outs() << "FP_PREC_24B ";
9772   else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
9773     outs() << "FP_PREC_53B ";
9774   else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
9775     outs() << "FP_PREC_64B ";
9776   else
9777     outs() << fpu.fpu_fcw.pc << " ";
9778   outs() << "rc ";
9779   if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
9780     outs() << "FP_RND_NEAR ";
9781   else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
9782     outs() << "FP_RND_DOWN ";
9783   else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
9784     outs() << "FP_RND_UP ";
9785   else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
9786     outs() << "FP_CHOP ";
9787   outs() << "\n";
9788   outs() << "\t    status: invalid " << fpu.fpu_fsw.invalid;
9789   outs() << " denorm " << fpu.fpu_fsw.denorm;
9790   outs() << " zdiv " << fpu.fpu_fsw.zdiv;
9791   outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
9792   outs() << " undfl " << fpu.fpu_fsw.undfl;
9793   outs() << " precis " << fpu.fpu_fsw.precis;
9794   outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
9795   outs() << "\t            errsumm " << fpu.fpu_fsw.errsumm;
9796   outs() << " c0 " << fpu.fpu_fsw.c0;
9797   outs() << " c1 " << fpu.fpu_fsw.c1;
9798   outs() << " c2 " << fpu.fpu_fsw.c2;
9799   outs() << " tos " << fpu.fpu_fsw.tos;
9800   outs() << " c3 " << fpu.fpu_fsw.c3;
9801   outs() << " busy " << fpu.fpu_fsw.busy << "\n";
9802   outs() << "\t    fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
9803   outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
9804   outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
9805   outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
9806   outs() << "\t    fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
9807   outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
9808   outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
9809   outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
9810   outs() << "\t    fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
9811   outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
9812   outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
9813   outs() << "\n";
9814   outs() << "\t    fpu_stmm0:\n";
9815   Print_mmst_reg(fpu.fpu_stmm0);
9816   outs() << "\t    fpu_stmm1:\n";
9817   Print_mmst_reg(fpu.fpu_stmm1);
9818   outs() << "\t    fpu_stmm2:\n";
9819   Print_mmst_reg(fpu.fpu_stmm2);
9820   outs() << "\t    fpu_stmm3:\n";
9821   Print_mmst_reg(fpu.fpu_stmm3);
9822   outs() << "\t    fpu_stmm4:\n";
9823   Print_mmst_reg(fpu.fpu_stmm4);
9824   outs() << "\t    fpu_stmm5:\n";
9825   Print_mmst_reg(fpu.fpu_stmm5);
9826   outs() << "\t    fpu_stmm6:\n";
9827   Print_mmst_reg(fpu.fpu_stmm6);
9828   outs() << "\t    fpu_stmm7:\n";
9829   Print_mmst_reg(fpu.fpu_stmm7);
9830   outs() << "\t    fpu_xmm0:\n";
9831   Print_xmm_reg(fpu.fpu_xmm0);
9832   outs() << "\t    fpu_xmm1:\n";
9833   Print_xmm_reg(fpu.fpu_xmm1);
9834   outs() << "\t    fpu_xmm2:\n";
9835   Print_xmm_reg(fpu.fpu_xmm2);
9836   outs() << "\t    fpu_xmm3:\n";
9837   Print_xmm_reg(fpu.fpu_xmm3);
9838   outs() << "\t    fpu_xmm4:\n";
9839   Print_xmm_reg(fpu.fpu_xmm4);
9840   outs() << "\t    fpu_xmm5:\n";
9841   Print_xmm_reg(fpu.fpu_xmm5);
9842   outs() << "\t    fpu_xmm6:\n";
9843   Print_xmm_reg(fpu.fpu_xmm6);
9844   outs() << "\t    fpu_xmm7:\n";
9845   Print_xmm_reg(fpu.fpu_xmm7);
9846   outs() << "\t    fpu_xmm8:\n";
9847   Print_xmm_reg(fpu.fpu_xmm8);
9848   outs() << "\t    fpu_xmm9:\n";
9849   Print_xmm_reg(fpu.fpu_xmm9);
9850   outs() << "\t    fpu_xmm10:\n";
9851   Print_xmm_reg(fpu.fpu_xmm10);
9852   outs() << "\t    fpu_xmm11:\n";
9853   Print_xmm_reg(fpu.fpu_xmm11);
9854   outs() << "\t    fpu_xmm12:\n";
9855   Print_xmm_reg(fpu.fpu_xmm12);
9856   outs() << "\t    fpu_xmm13:\n";
9857   Print_xmm_reg(fpu.fpu_xmm13);
9858   outs() << "\t    fpu_xmm14:\n";
9859   Print_xmm_reg(fpu.fpu_xmm14);
9860   outs() << "\t    fpu_xmm15:\n";
9861   Print_xmm_reg(fpu.fpu_xmm15);
9862   outs() << "\t    fpu_rsrv4:\n";
9863   for (uint32_t f = 0; f < 6; f++) {
9864     outs() << "\t            ";
9865     for (uint32_t g = 0; g < 16; g++)
9866       outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
9867     outs() << "\n";
9868   }
9869   outs() << "\t    fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
9870   outs() << "\n";
9871 }
9872 
9873 static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
9874   outs() << "\t    trapno " << format("0x%08" PRIx32, exc64.trapno);
9875   outs() << " err " << format("0x%08" PRIx32, exc64.err);
9876   outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
9877 }
9878 
9879 static void Print_arm_thread_state32_t(MachO::arm_thread_state32_t &cpu32) {
9880   outs() << "\t    r0  " << format("0x%08" PRIx32, cpu32.r[0]);
9881   outs() << " r1     "   << format("0x%08" PRIx32, cpu32.r[1]);
9882   outs() << " r2  "      << format("0x%08" PRIx32, cpu32.r[2]);
9883   outs() << " r3  "      << format("0x%08" PRIx32, cpu32.r[3]) << "\n";
9884   outs() << "\t    r4  " << format("0x%08" PRIx32, cpu32.r[4]);
9885   outs() << " r5     "   << format("0x%08" PRIx32, cpu32.r[5]);
9886   outs() << " r6  "      << format("0x%08" PRIx32, cpu32.r[6]);
9887   outs() << " r7  "      << format("0x%08" PRIx32, cpu32.r[7]) << "\n";
9888   outs() << "\t    r8  " << format("0x%08" PRIx32, cpu32.r[8]);
9889   outs() << " r9     "   << format("0x%08" PRIx32, cpu32.r[9]);
9890   outs() << " r10 "      << format("0x%08" PRIx32, cpu32.r[10]);
9891   outs() << " r11 "      << format("0x%08" PRIx32, cpu32.r[11]) << "\n";
9892   outs() << "\t    r12 " << format("0x%08" PRIx32, cpu32.r[12]);
9893   outs() << " sp     "   << format("0x%08" PRIx32, cpu32.sp);
9894   outs() << " lr  "      << format("0x%08" PRIx32, cpu32.lr);
9895   outs() << " pc  "      << format("0x%08" PRIx32, cpu32.pc) << "\n";
9896   outs() << "\t   cpsr " << format("0x%08" PRIx32, cpu32.cpsr) << "\n";
9897 }
9898 
9899 static void Print_arm_thread_state64_t(MachO::arm_thread_state64_t &cpu64) {
9900   outs() << "\t    x0  " << format("0x%016" PRIx64, cpu64.x[0]);
9901   outs() << " x1  "      << format("0x%016" PRIx64, cpu64.x[1]);
9902   outs() << " x2  "      << format("0x%016" PRIx64, cpu64.x[2]) << "\n";
9903   outs() << "\t    x3  " << format("0x%016" PRIx64, cpu64.x[3]);
9904   outs() << " x4  "      << format("0x%016" PRIx64, cpu64.x[4]);
9905   outs() << " x5  "      << format("0x%016" PRIx64, cpu64.x[5]) << "\n";
9906   outs() << "\t    x6  " << format("0x%016" PRIx64, cpu64.x[6]);
9907   outs() << " x7  "      << format("0x%016" PRIx64, cpu64.x[7]);
9908   outs() << " x8  "      << format("0x%016" PRIx64, cpu64.x[8]) << "\n";
9909   outs() << "\t    x9  " << format("0x%016" PRIx64, cpu64.x[9]);
9910   outs() << " x10 "      << format("0x%016" PRIx64, cpu64.x[10]);
9911   outs() << " x11 "      << format("0x%016" PRIx64, cpu64.x[11]) << "\n";
9912   outs() << "\t    x12 " << format("0x%016" PRIx64, cpu64.x[12]);
9913   outs() << " x13 "      << format("0x%016" PRIx64, cpu64.x[13]);
9914   outs() << " x14 "      << format("0x%016" PRIx64, cpu64.x[14]) << "\n";
9915   outs() << "\t    x15 " << format("0x%016" PRIx64, cpu64.x[15]);
9916   outs() << " x16 "      << format("0x%016" PRIx64, cpu64.x[16]);
9917   outs() << " x17 "      << format("0x%016" PRIx64, cpu64.x[17]) << "\n";
9918   outs() << "\t    x18 " << format("0x%016" PRIx64, cpu64.x[18]);
9919   outs() << " x19 "      << format("0x%016" PRIx64, cpu64.x[19]);
9920   outs() << " x20 "      << format("0x%016" PRIx64, cpu64.x[20]) << "\n";
9921   outs() << "\t    x21 " << format("0x%016" PRIx64, cpu64.x[21]);
9922   outs() << " x22 "      << format("0x%016" PRIx64, cpu64.x[22]);
9923   outs() << " x23 "      << format("0x%016" PRIx64, cpu64.x[23]) << "\n";
9924   outs() << "\t    x24 " << format("0x%016" PRIx64, cpu64.x[24]);
9925   outs() << " x25 "      << format("0x%016" PRIx64, cpu64.x[25]);
9926   outs() << " x26 "      << format("0x%016" PRIx64, cpu64.x[26]) << "\n";
9927   outs() << "\t    x27 " << format("0x%016" PRIx64, cpu64.x[27]);
9928   outs() << " x28 "      << format("0x%016" PRIx64, cpu64.x[28]);
9929   outs() << "  fp "      << format("0x%016" PRIx64, cpu64.fp) << "\n";
9930   outs() << "\t     lr " << format("0x%016" PRIx64, cpu64.lr);
9931   outs() << " sp  "      << format("0x%016" PRIx64, cpu64.sp);
9932   outs() << "  pc "      << format("0x%016" PRIx64, cpu64.pc) << "\n";
9933   outs() << "\t   cpsr " << format("0x%08"  PRIx32, cpu64.cpsr) << "\n";
9934 }
9935 
9936 static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
9937                                bool isLittleEndian, uint32_t cputype) {
9938   if (t.cmd == MachO::LC_THREAD)
9939     outs() << "        cmd LC_THREAD\n";
9940   else if (t.cmd == MachO::LC_UNIXTHREAD)
9941     outs() << "        cmd LC_UNIXTHREAD\n";
9942   else
9943     outs() << "        cmd " << t.cmd << " (unknown)\n";
9944   outs() << "    cmdsize " << t.cmdsize;
9945   if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
9946     outs() << " Incorrect size\n";
9947   else
9948     outs() << "\n";
9949 
9950   const char *begin = Ptr + sizeof(struct MachO::thread_command);
9951   const char *end = Ptr + t.cmdsize;
9952   uint32_t flavor, count, left;
9953   if (cputype == MachO::CPU_TYPE_I386) {
9954     while (begin < end) {
9955       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9956         memcpy((char *)&flavor, begin, sizeof(uint32_t));
9957         begin += sizeof(uint32_t);
9958       } else {
9959         flavor = 0;
9960         begin = end;
9961       }
9962       if (isLittleEndian != sys::IsLittleEndianHost)
9963         sys::swapByteOrder(flavor);
9964       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9965         memcpy((char *)&count, begin, sizeof(uint32_t));
9966         begin += sizeof(uint32_t);
9967       } else {
9968         count = 0;
9969         begin = end;
9970       }
9971       if (isLittleEndian != sys::IsLittleEndianHost)
9972         sys::swapByteOrder(count);
9973       if (flavor == MachO::x86_THREAD_STATE32) {
9974         outs() << "     flavor i386_THREAD_STATE\n";
9975         if (count == MachO::x86_THREAD_STATE32_COUNT)
9976           outs() << "      count i386_THREAD_STATE_COUNT\n";
9977         else
9978           outs() << "      count " << count
9979                  << " (not x86_THREAD_STATE32_COUNT)\n";
9980         MachO::x86_thread_state32_t cpu32;
9981         left = end - begin;
9982         if (left >= sizeof(MachO::x86_thread_state32_t)) {
9983           memcpy(&cpu32, begin, sizeof(MachO::x86_thread_state32_t));
9984           begin += sizeof(MachO::x86_thread_state32_t);
9985         } else {
9986           memset(&cpu32, '\0', sizeof(MachO::x86_thread_state32_t));
9987           memcpy(&cpu32, begin, left);
9988           begin += left;
9989         }
9990         if (isLittleEndian != sys::IsLittleEndianHost)
9991           swapStruct(cpu32);
9992         Print_x86_thread_state32_t(cpu32);
9993       } else if (flavor == MachO::x86_THREAD_STATE) {
9994         outs() << "     flavor x86_THREAD_STATE\n";
9995         if (count == MachO::x86_THREAD_STATE_COUNT)
9996           outs() << "      count x86_THREAD_STATE_COUNT\n";
9997         else
9998           outs() << "      count " << count
9999                  << " (not x86_THREAD_STATE_COUNT)\n";
10000         struct MachO::x86_thread_state_t ts;
10001         left = end - begin;
10002         if (left >= sizeof(MachO::x86_thread_state_t)) {
10003           memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
10004           begin += sizeof(MachO::x86_thread_state_t);
10005         } else {
10006           memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
10007           memcpy(&ts, begin, left);
10008           begin += left;
10009         }
10010         if (isLittleEndian != sys::IsLittleEndianHost)
10011           swapStruct(ts);
10012         if (ts.tsh.flavor == MachO::x86_THREAD_STATE32) {
10013           outs() << "\t    tsh.flavor x86_THREAD_STATE32 ";
10014           if (ts.tsh.count == MachO::x86_THREAD_STATE32_COUNT)
10015             outs() << "tsh.count x86_THREAD_STATE32_COUNT\n";
10016           else
10017             outs() << "tsh.count " << ts.tsh.count
10018                    << " (not x86_THREAD_STATE32_COUNT\n";
10019           Print_x86_thread_state32_t(ts.uts.ts32);
10020         } else {
10021           outs() << "\t    tsh.flavor " << ts.tsh.flavor << "  tsh.count "
10022                  << ts.tsh.count << "\n";
10023         }
10024       } else {
10025         outs() << "     flavor " << flavor << " (unknown)\n";
10026         outs() << "      count " << count << "\n";
10027         outs() << "      state (unknown)\n";
10028         begin += count * sizeof(uint32_t);
10029       }
10030     }
10031   } else if (cputype == MachO::CPU_TYPE_X86_64) {
10032     while (begin < end) {
10033       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
10034         memcpy((char *)&flavor, begin, sizeof(uint32_t));
10035         begin += sizeof(uint32_t);
10036       } else {
10037         flavor = 0;
10038         begin = end;
10039       }
10040       if (isLittleEndian != sys::IsLittleEndianHost)
10041         sys::swapByteOrder(flavor);
10042       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
10043         memcpy((char *)&count, begin, sizeof(uint32_t));
10044         begin += sizeof(uint32_t);
10045       } else {
10046         count = 0;
10047         begin = end;
10048       }
10049       if (isLittleEndian != sys::IsLittleEndianHost)
10050         sys::swapByteOrder(count);
10051       if (flavor == MachO::x86_THREAD_STATE64) {
10052         outs() << "     flavor x86_THREAD_STATE64\n";
10053         if (count == MachO::x86_THREAD_STATE64_COUNT)
10054           outs() << "      count x86_THREAD_STATE64_COUNT\n";
10055         else
10056           outs() << "      count " << count
10057                  << " (not x86_THREAD_STATE64_COUNT)\n";
10058         MachO::x86_thread_state64_t cpu64;
10059         left = end - begin;
10060         if (left >= sizeof(MachO::x86_thread_state64_t)) {
10061           memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
10062           begin += sizeof(MachO::x86_thread_state64_t);
10063         } else {
10064           memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
10065           memcpy(&cpu64, begin, left);
10066           begin += left;
10067         }
10068         if (isLittleEndian != sys::IsLittleEndianHost)
10069           swapStruct(cpu64);
10070         Print_x86_thread_state64_t(cpu64);
10071       } else if (flavor == MachO::x86_THREAD_STATE) {
10072         outs() << "     flavor x86_THREAD_STATE\n";
10073         if (count == MachO::x86_THREAD_STATE_COUNT)
10074           outs() << "      count x86_THREAD_STATE_COUNT\n";
10075         else
10076           outs() << "      count " << count
10077                  << " (not x86_THREAD_STATE_COUNT)\n";
10078         struct MachO::x86_thread_state_t ts;
10079         left = end - begin;
10080         if (left >= sizeof(MachO::x86_thread_state_t)) {
10081           memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
10082           begin += sizeof(MachO::x86_thread_state_t);
10083         } else {
10084           memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
10085           memcpy(&ts, begin, left);
10086           begin += left;
10087         }
10088         if (isLittleEndian != sys::IsLittleEndianHost)
10089           swapStruct(ts);
10090         if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
10091           outs() << "\t    tsh.flavor x86_THREAD_STATE64 ";
10092           if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
10093             outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
10094           else
10095             outs() << "tsh.count " << ts.tsh.count
10096                    << " (not x86_THREAD_STATE64_COUNT\n";
10097           Print_x86_thread_state64_t(ts.uts.ts64);
10098         } else {
10099           outs() << "\t    tsh.flavor " << ts.tsh.flavor << "  tsh.count "
10100                  << ts.tsh.count << "\n";
10101         }
10102       } else if (flavor == MachO::x86_FLOAT_STATE) {
10103         outs() << "     flavor x86_FLOAT_STATE\n";
10104         if (count == MachO::x86_FLOAT_STATE_COUNT)
10105           outs() << "      count x86_FLOAT_STATE_COUNT\n";
10106         else
10107           outs() << "      count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
10108         struct MachO::x86_float_state_t fs;
10109         left = end - begin;
10110         if (left >= sizeof(MachO::x86_float_state_t)) {
10111           memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
10112           begin += sizeof(MachO::x86_float_state_t);
10113         } else {
10114           memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
10115           memcpy(&fs, begin, left);
10116           begin += left;
10117         }
10118         if (isLittleEndian != sys::IsLittleEndianHost)
10119           swapStruct(fs);
10120         if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
10121           outs() << "\t    fsh.flavor x86_FLOAT_STATE64 ";
10122           if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
10123             outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
10124           else
10125             outs() << "fsh.count " << fs.fsh.count
10126                    << " (not x86_FLOAT_STATE64_COUNT\n";
10127           Print_x86_float_state_t(fs.ufs.fs64);
10128         } else {
10129           outs() << "\t    fsh.flavor " << fs.fsh.flavor << "  fsh.count "
10130                  << fs.fsh.count << "\n";
10131         }
10132       } else if (flavor == MachO::x86_EXCEPTION_STATE) {
10133         outs() << "     flavor x86_EXCEPTION_STATE\n";
10134         if (count == MachO::x86_EXCEPTION_STATE_COUNT)
10135           outs() << "      count x86_EXCEPTION_STATE_COUNT\n";
10136         else
10137           outs() << "      count " << count
10138                  << " (not x86_EXCEPTION_STATE_COUNT)\n";
10139         struct MachO::x86_exception_state_t es;
10140         left = end - begin;
10141         if (left >= sizeof(MachO::x86_exception_state_t)) {
10142           memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
10143           begin += sizeof(MachO::x86_exception_state_t);
10144         } else {
10145           memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
10146           memcpy(&es, begin, left);
10147           begin += left;
10148         }
10149         if (isLittleEndian != sys::IsLittleEndianHost)
10150           swapStruct(es);
10151         if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
10152           outs() << "\t    esh.flavor x86_EXCEPTION_STATE64\n";
10153           if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
10154             outs() << "\t    esh.count x86_EXCEPTION_STATE64_COUNT\n";
10155           else
10156             outs() << "\t    esh.count " << es.esh.count
10157                    << " (not x86_EXCEPTION_STATE64_COUNT\n";
10158           Print_x86_exception_state_t(es.ues.es64);
10159         } else {
10160           outs() << "\t    esh.flavor " << es.esh.flavor << "  esh.count "
10161                  << es.esh.count << "\n";
10162         }
10163       } else if (flavor == MachO::x86_EXCEPTION_STATE64) {
10164         outs() << "     flavor x86_EXCEPTION_STATE64\n";
10165         if (count == MachO::x86_EXCEPTION_STATE64_COUNT)
10166           outs() << "      count x86_EXCEPTION_STATE64_COUNT\n";
10167         else
10168           outs() << "      count " << count
10169                  << " (not x86_EXCEPTION_STATE64_COUNT)\n";
10170         struct MachO::x86_exception_state64_t es64;
10171         left = end - begin;
10172         if (left >= sizeof(MachO::x86_exception_state64_t)) {
10173           memcpy(&es64, begin, sizeof(MachO::x86_exception_state64_t));
10174           begin += sizeof(MachO::x86_exception_state64_t);
10175         } else {
10176           memset(&es64, '\0', sizeof(MachO::x86_exception_state64_t));
10177           memcpy(&es64, begin, left);
10178           begin += left;
10179         }
10180         if (isLittleEndian != sys::IsLittleEndianHost)
10181           swapStruct(es64);
10182         Print_x86_exception_state_t(es64);
10183       } else {
10184         outs() << "     flavor " << flavor << " (unknown)\n";
10185         outs() << "      count " << count << "\n";
10186         outs() << "      state (unknown)\n";
10187         begin += count * sizeof(uint32_t);
10188       }
10189     }
10190   } else if (cputype == MachO::CPU_TYPE_ARM) {
10191     while (begin < end) {
10192       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
10193         memcpy((char *)&flavor, begin, sizeof(uint32_t));
10194         begin += sizeof(uint32_t);
10195       } else {
10196         flavor = 0;
10197         begin = end;
10198       }
10199       if (isLittleEndian != sys::IsLittleEndianHost)
10200         sys::swapByteOrder(flavor);
10201       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
10202         memcpy((char *)&count, begin, sizeof(uint32_t));
10203         begin += sizeof(uint32_t);
10204       } else {
10205         count = 0;
10206         begin = end;
10207       }
10208       if (isLittleEndian != sys::IsLittleEndianHost)
10209         sys::swapByteOrder(count);
10210       if (flavor == MachO::ARM_THREAD_STATE) {
10211         outs() << "     flavor ARM_THREAD_STATE\n";
10212         if (count == MachO::ARM_THREAD_STATE_COUNT)
10213           outs() << "      count ARM_THREAD_STATE_COUNT\n";
10214         else
10215           outs() << "      count " << count
10216                  << " (not ARM_THREAD_STATE_COUNT)\n";
10217         MachO::arm_thread_state32_t cpu32;
10218         left = end - begin;
10219         if (left >= sizeof(MachO::arm_thread_state32_t)) {
10220           memcpy(&cpu32, begin, sizeof(MachO::arm_thread_state32_t));
10221           begin += sizeof(MachO::arm_thread_state32_t);
10222         } else {
10223           memset(&cpu32, '\0', sizeof(MachO::arm_thread_state32_t));
10224           memcpy(&cpu32, begin, left);
10225           begin += left;
10226         }
10227         if (isLittleEndian != sys::IsLittleEndianHost)
10228           swapStruct(cpu32);
10229         Print_arm_thread_state32_t(cpu32);
10230       } else {
10231         outs() << "     flavor " << flavor << " (unknown)\n";
10232         outs() << "      count " << count << "\n";
10233         outs() << "      state (unknown)\n";
10234         begin += count * sizeof(uint32_t);
10235       }
10236     }
10237   } else if (cputype == MachO::CPU_TYPE_ARM64 ||
10238              cputype == MachO::CPU_TYPE_ARM64_32) {
10239     while (begin < end) {
10240       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
10241         memcpy((char *)&flavor, begin, sizeof(uint32_t));
10242         begin += sizeof(uint32_t);
10243       } else {
10244         flavor = 0;
10245         begin = end;
10246       }
10247       if (isLittleEndian != sys::IsLittleEndianHost)
10248         sys::swapByteOrder(flavor);
10249       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
10250         memcpy((char *)&count, begin, sizeof(uint32_t));
10251         begin += sizeof(uint32_t);
10252       } else {
10253         count = 0;
10254         begin = end;
10255       }
10256       if (isLittleEndian != sys::IsLittleEndianHost)
10257         sys::swapByteOrder(count);
10258       if (flavor == MachO::ARM_THREAD_STATE64) {
10259         outs() << "     flavor ARM_THREAD_STATE64\n";
10260         if (count == MachO::ARM_THREAD_STATE64_COUNT)
10261           outs() << "      count ARM_THREAD_STATE64_COUNT\n";
10262         else
10263           outs() << "      count " << count
10264                  << " (not ARM_THREAD_STATE64_COUNT)\n";
10265         MachO::arm_thread_state64_t cpu64;
10266         left = end - begin;
10267         if (left >= sizeof(MachO::arm_thread_state64_t)) {
10268           memcpy(&cpu64, begin, sizeof(MachO::arm_thread_state64_t));
10269           begin += sizeof(MachO::arm_thread_state64_t);
10270         } else {
10271           memset(&cpu64, '\0', sizeof(MachO::arm_thread_state64_t));
10272           memcpy(&cpu64, begin, left);
10273           begin += left;
10274         }
10275         if (isLittleEndian != sys::IsLittleEndianHost)
10276           swapStruct(cpu64);
10277         Print_arm_thread_state64_t(cpu64);
10278       } else {
10279         outs() << "     flavor " << flavor << " (unknown)\n";
10280         outs() << "      count " << count << "\n";
10281         outs() << "      state (unknown)\n";
10282         begin += count * sizeof(uint32_t);
10283       }
10284     }
10285   } else {
10286     while (begin < end) {
10287       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
10288         memcpy((char *)&flavor, begin, sizeof(uint32_t));
10289         begin += sizeof(uint32_t);
10290       } else {
10291         flavor = 0;
10292         begin = end;
10293       }
10294       if (isLittleEndian != sys::IsLittleEndianHost)
10295         sys::swapByteOrder(flavor);
10296       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
10297         memcpy((char *)&count, begin, sizeof(uint32_t));
10298         begin += sizeof(uint32_t);
10299       } else {
10300         count = 0;
10301         begin = end;
10302       }
10303       if (isLittleEndian != sys::IsLittleEndianHost)
10304         sys::swapByteOrder(count);
10305       outs() << "     flavor " << flavor << "\n";
10306       outs() << "      count " << count << "\n";
10307       outs() << "      state (Unknown cputype/cpusubtype)\n";
10308       begin += count * sizeof(uint32_t);
10309     }
10310   }
10311 }
10312 
10313 static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
10314   if (dl.cmd == MachO::LC_ID_DYLIB)
10315     outs() << "          cmd LC_ID_DYLIB\n";
10316   else if (dl.cmd == MachO::LC_LOAD_DYLIB)
10317     outs() << "          cmd LC_LOAD_DYLIB\n";
10318   else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
10319     outs() << "          cmd LC_LOAD_WEAK_DYLIB\n";
10320   else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
10321     outs() << "          cmd LC_REEXPORT_DYLIB\n";
10322   else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
10323     outs() << "          cmd LC_LAZY_LOAD_DYLIB\n";
10324   else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
10325     outs() << "          cmd LC_LOAD_UPWARD_DYLIB\n";
10326   else
10327     outs() << "          cmd " << dl.cmd << " (unknown)\n";
10328   outs() << "      cmdsize " << dl.cmdsize;
10329   if (dl.cmdsize < sizeof(struct MachO::dylib_command))
10330     outs() << " Incorrect size\n";
10331   else
10332     outs() << "\n";
10333   if (dl.dylib.name < dl.cmdsize) {
10334     const char *P = (const char *)(Ptr) + dl.dylib.name;
10335     outs() << "         name " << P << " (offset " << dl.dylib.name << ")\n";
10336   } else {
10337     outs() << "         name ?(bad offset " << dl.dylib.name << ")\n";
10338   }
10339   outs() << "   time stamp " << dl.dylib.timestamp << " ";
10340   time_t t = dl.dylib.timestamp;
10341   outs() << ctime(&t);
10342   outs() << "      current version ";
10343   if (dl.dylib.current_version == 0xffffffff)
10344     outs() << "n/a\n";
10345   else
10346     outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
10347            << ((dl.dylib.current_version >> 8) & 0xff) << "."
10348            << (dl.dylib.current_version & 0xff) << "\n";
10349   outs() << "compatibility version ";
10350   if (dl.dylib.compatibility_version == 0xffffffff)
10351     outs() << "n/a\n";
10352   else
10353     outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
10354            << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
10355            << (dl.dylib.compatibility_version & 0xff) << "\n";
10356 }
10357 
10358 static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
10359                                      uint32_t object_size) {
10360   if (ld.cmd == MachO::LC_CODE_SIGNATURE)
10361     outs() << "      cmd LC_CODE_SIGNATURE\n";
10362   else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
10363     outs() << "      cmd LC_SEGMENT_SPLIT_INFO\n";
10364   else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
10365     outs() << "      cmd LC_FUNCTION_STARTS\n";
10366   else if (ld.cmd == MachO::LC_DATA_IN_CODE)
10367     outs() << "      cmd LC_DATA_IN_CODE\n";
10368   else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
10369     outs() << "      cmd LC_DYLIB_CODE_SIGN_DRS\n";
10370   else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
10371     outs() << "      cmd LC_LINKER_OPTIMIZATION_HINT\n";
10372   else if (ld.cmd == MachO::LC_DYLD_EXPORTS_TRIE)
10373     outs() << "      cmd LC_DYLD_EXPORTS_TRIE\n";
10374   else if (ld.cmd == MachO::LC_DYLD_CHAINED_FIXUPS)
10375     outs() << "      cmd LC_DYLD_CHAINED_FIXUPS\n";
10376   else if (ld.cmd == MachO::LC_ATOM_INFO)
10377     outs() << "      cmd LC_ATOM_INFO\n";
10378   else
10379     outs() << "      cmd " << ld.cmd << " (?)\n";
10380   outs() << "  cmdsize " << ld.cmdsize;
10381   if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
10382     outs() << " Incorrect size\n";
10383   else
10384     outs() << "\n";
10385   outs() << "  dataoff " << ld.dataoff;
10386   if (ld.dataoff > object_size)
10387     outs() << " (past end of file)\n";
10388   else
10389     outs() << "\n";
10390   outs() << " datasize " << ld.datasize;
10391   uint64_t big_size = ld.dataoff;
10392   big_size += ld.datasize;
10393   if (big_size > object_size)
10394     outs() << " (past end of file)\n";
10395   else
10396     outs() << "\n";
10397 }
10398 
10399 static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
10400                               uint32_t cputype, bool verbose) {
10401   StringRef Buf = Obj->getData();
10402   unsigned Index = 0;
10403   for (const auto &Command : Obj->load_commands()) {
10404     outs() << "Load command " << Index++ << "\n";
10405     if (Command.C.cmd == MachO::LC_SEGMENT) {
10406       MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
10407       const char *sg_segname = SLC.segname;
10408       PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
10409                           SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
10410                           SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
10411                           verbose);
10412       for (unsigned j = 0; j < SLC.nsects; j++) {
10413         MachO::section S = Obj->getSection(Command, j);
10414         PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
10415                      S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
10416                      SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
10417       }
10418     } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
10419       MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
10420       const char *sg_segname = SLC_64.segname;
10421       PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
10422                           SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
10423                           SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
10424                           SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
10425       for (unsigned j = 0; j < SLC_64.nsects; j++) {
10426         MachO::section_64 S_64 = Obj->getSection64(Command, j);
10427         PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
10428                      S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
10429                      S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
10430                      sg_segname, filetype, Buf.size(), verbose);
10431       }
10432     } else if (Command.C.cmd == MachO::LC_SYMTAB) {
10433       MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
10434       PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
10435     } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
10436       MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
10437       MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
10438       PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
10439                                Obj->is64Bit());
10440     } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
10441                Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
10442       MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
10443       PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
10444     } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
10445                Command.C.cmd == MachO::LC_ID_DYLINKER ||
10446                Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
10447       MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
10448       PrintDyldLoadCommand(Dyld, Command.Ptr);
10449     } else if (Command.C.cmd == MachO::LC_UUID) {
10450       MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
10451       PrintUuidLoadCommand(Uuid);
10452     } else if (Command.C.cmd == MachO::LC_RPATH) {
10453       MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
10454       PrintRpathLoadCommand(Rpath, Command.Ptr);
10455     } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
10456                Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
10457                Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
10458                Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
10459       MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
10460       PrintVersionMinLoadCommand(Vd);
10461     } else if (Command.C.cmd == MachO::LC_NOTE) {
10462       MachO::note_command Nt = Obj->getNoteLoadCommand(Command);
10463       PrintNoteLoadCommand(Nt);
10464     } else if (Command.C.cmd == MachO::LC_BUILD_VERSION) {
10465       MachO::build_version_command Bv =
10466           Obj->getBuildVersionLoadCommand(Command);
10467       PrintBuildVersionLoadCommand(Obj, Bv, verbose);
10468     } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
10469       MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
10470       PrintSourceVersionCommand(Sd);
10471     } else if (Command.C.cmd == MachO::LC_MAIN) {
10472       MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
10473       PrintEntryPointCommand(Ep);
10474     } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
10475       MachO::encryption_info_command Ei =
10476           Obj->getEncryptionInfoCommand(Command);
10477       PrintEncryptionInfoCommand(Ei, Buf.size());
10478     } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
10479       MachO::encryption_info_command_64 Ei =
10480           Obj->getEncryptionInfoCommand64(Command);
10481       PrintEncryptionInfoCommand64(Ei, Buf.size());
10482     } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
10483       MachO::linker_option_command Lo =
10484           Obj->getLinkerOptionLoadCommand(Command);
10485       PrintLinkerOptionCommand(Lo, Command.Ptr);
10486     } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
10487       MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
10488       PrintSubFrameworkCommand(Sf, Command.Ptr);
10489     } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
10490       MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
10491       PrintSubUmbrellaCommand(Sf, Command.Ptr);
10492     } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
10493       MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
10494       PrintSubLibraryCommand(Sl, Command.Ptr);
10495     } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
10496       MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
10497       PrintSubClientCommand(Sc, Command.Ptr);
10498     } else if (Command.C.cmd == MachO::LC_ROUTINES) {
10499       MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
10500       PrintRoutinesCommand(Rc);
10501     } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
10502       MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
10503       PrintRoutinesCommand64(Rc);
10504     } else if (Command.C.cmd == MachO::LC_THREAD ||
10505                Command.C.cmd == MachO::LC_UNIXTHREAD) {
10506       MachO::thread_command Tc = Obj->getThreadCommand(Command);
10507       PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
10508     } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
10509                Command.C.cmd == MachO::LC_ID_DYLIB ||
10510                Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
10511                Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
10512                Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
10513                Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
10514       MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
10515       PrintDylibCommand(Dl, Command.Ptr);
10516     } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
10517                Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
10518                Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
10519                Command.C.cmd == MachO::LC_DATA_IN_CODE ||
10520                Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
10521                Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT ||
10522                Command.C.cmd == MachO::LC_DYLD_EXPORTS_TRIE ||
10523                Command.C.cmd == MachO::LC_DYLD_CHAINED_FIXUPS ||
10524                Command.C.cmd == MachO::LC_ATOM_INFO) {
10525       MachO::linkedit_data_command Ld =
10526           Obj->getLinkeditDataLoadCommand(Command);
10527       PrintLinkEditDataCommand(Ld, Buf.size());
10528     } else {
10529       outs() << "      cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
10530              << ")\n";
10531       outs() << "  cmdsize " << Command.C.cmdsize << "\n";
10532       // TODO: get and print the raw bytes of the load command.
10533     }
10534     // TODO: print all the other kinds of load commands.
10535   }
10536 }
10537 
10538 static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
10539   if (Obj->is64Bit()) {
10540     MachO::mach_header_64 H_64;
10541     H_64 = Obj->getHeader64();
10542     PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
10543                     H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
10544   } else {
10545     MachO::mach_header H;
10546     H = Obj->getHeader();
10547     PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
10548                     H.sizeofcmds, H.flags, verbose);
10549   }
10550 }
10551 
10552 void objdump::printMachOFileHeader(const object::ObjectFile *Obj) {
10553   const MachOObjectFile *file = cast<const MachOObjectFile>(Obj);
10554   PrintMachHeader(file, Verbose);
10555 }
10556 
10557 void MachODumper::printPrivateHeaders(bool OnlyFirst) {
10558   printMachOFileHeader(&Obj);
10559   if (!OnlyFirst)
10560     printMachOLoadCommands(&Obj);
10561 }
10562 
10563 void objdump::printMachOLoadCommands(const object::ObjectFile *Obj) {
10564   const MachOObjectFile *file = cast<const MachOObjectFile>(Obj);
10565   uint32_t filetype = 0;
10566   uint32_t cputype = 0;
10567   if (file->is64Bit()) {
10568     MachO::mach_header_64 H_64;
10569     H_64 = file->getHeader64();
10570     filetype = H_64.filetype;
10571     cputype = H_64.cputype;
10572   } else {
10573     MachO::mach_header H;
10574     H = file->getHeader();
10575     filetype = H.filetype;
10576     cputype = H.cputype;
10577   }
10578   PrintLoadCommands(file, filetype, cputype, Verbose);
10579 }
10580 
10581 //===----------------------------------------------------------------------===//
10582 // export trie dumping
10583 //===----------------------------------------------------------------------===//
10584 
10585 static void printMachOExportsTrie(const object::MachOObjectFile *Obj) {
10586   uint64_t BaseSegmentAddress = 0;
10587   for (const auto &Command : Obj->load_commands()) {
10588     if (Command.C.cmd == MachO::LC_SEGMENT) {
10589       MachO::segment_command Seg = Obj->getSegmentLoadCommand(Command);
10590       if (Seg.fileoff == 0 && Seg.filesize != 0) {
10591         BaseSegmentAddress = Seg.vmaddr;
10592         break;
10593       }
10594     } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
10595       MachO::segment_command_64 Seg = Obj->getSegment64LoadCommand(Command);
10596       if (Seg.fileoff == 0 && Seg.filesize != 0) {
10597         BaseSegmentAddress = Seg.vmaddr;
10598         break;
10599       }
10600     }
10601   }
10602   Error Err = Error::success();
10603   for (const object::ExportEntry &Entry : Obj->exports(Err)) {
10604     uint64_t Flags = Entry.flags();
10605     bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
10606     bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
10607     bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
10608                         MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
10609     bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
10610                 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
10611     bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
10612     if (ReExport)
10613       outs() << "[re-export] ";
10614     else
10615       outs() << format("0x%08llX  ",
10616                        Entry.address() + BaseSegmentAddress);
10617     outs() << Entry.name();
10618     if (WeakDef || ThreadLocal || Resolver || Abs) {
10619       ListSeparator LS;
10620       outs() << " [";
10621       if (WeakDef)
10622         outs() << LS << "weak_def";
10623       if (ThreadLocal)
10624         outs() << LS << "per-thread";
10625       if (Abs)
10626         outs() << LS << "absolute";
10627       if (Resolver)
10628         outs() << LS << format("resolver=0x%08llX", Entry.other());
10629       outs() << "]";
10630     }
10631     if (ReExport) {
10632       StringRef DylibName = "unknown";
10633       int Ordinal = Entry.other() - 1;
10634       Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
10635       if (Entry.otherName().empty())
10636         outs() << " (from " << DylibName << ")";
10637       else
10638         outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
10639     }
10640     outs() << "\n";
10641   }
10642   if (Err)
10643     reportError(std::move(Err), Obj->getFileName());
10644 }
10645 
10646 //===----------------------------------------------------------------------===//
10647 // rebase table dumping
10648 //===----------------------------------------------------------------------===//
10649 
10650 static void printMachORebaseTable(object::MachOObjectFile *Obj) {
10651   outs() << "segment  section            address     type\n";
10652   Error Err = Error::success();
10653   for (const object::MachORebaseEntry &Entry : Obj->rebaseTable(Err)) {
10654     StringRef SegmentName = Entry.segmentName();
10655     StringRef SectionName = Entry.sectionName();
10656     uint64_t Address = Entry.address();
10657 
10658     // Table lines look like: __DATA  __nl_symbol_ptr  0x0000F00C  pointer
10659     outs() << format("%-8s %-18s 0x%08" PRIX64 "  %s\n",
10660                      SegmentName.str().c_str(), SectionName.str().c_str(),
10661                      Address, Entry.typeName().str().c_str());
10662   }
10663   if (Err)
10664     reportError(std::move(Err), Obj->getFileName());
10665 }
10666 
10667 static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
10668   StringRef DylibName;
10669   switch (Ordinal) {
10670   case MachO::BIND_SPECIAL_DYLIB_SELF:
10671     return "this-image";
10672   case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
10673     return "main-executable";
10674   case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
10675     return "flat-namespace";
10676   case MachO::BIND_SPECIAL_DYLIB_WEAK_LOOKUP:
10677     return "weak";
10678   default:
10679     if (Ordinal > 0) {
10680       std::error_code EC =
10681           Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
10682       if (EC)
10683         return "<<bad library ordinal>>";
10684       return DylibName;
10685     }
10686   }
10687   return "<<unknown special ordinal>>";
10688 }
10689 
10690 //===----------------------------------------------------------------------===//
10691 // bind table dumping
10692 //===----------------------------------------------------------------------===//
10693 
10694 static void printMachOBindTable(object::MachOObjectFile *Obj) {
10695   // Build table of sections so names can used in final output.
10696   outs() << "segment  section            address    type       "
10697             "addend dylib            symbol\n";
10698   Error Err = Error::success();
10699   for (const object::MachOBindEntry &Entry : Obj->bindTable(Err)) {
10700     StringRef SegmentName = Entry.segmentName();
10701     StringRef SectionName = Entry.sectionName();
10702     uint64_t Address = Entry.address();
10703 
10704     // Table lines look like:
10705     //  __DATA  __got  0x00012010    pointer   0 libSystem ___stack_chk_guard
10706     StringRef Attr;
10707     if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
10708       Attr = " (weak_import)";
10709     outs() << left_justify(SegmentName, 8) << " "
10710            << left_justify(SectionName, 18) << " "
10711            << format_hex(Address, 10, true) << " "
10712            << left_justify(Entry.typeName(), 8) << " "
10713            << format_decimal(Entry.addend(), 8) << " "
10714            << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
10715            << Entry.symbolName() << Attr << "\n";
10716   }
10717   if (Err)
10718     reportError(std::move(Err), Obj->getFileName());
10719 }
10720 
10721 //===----------------------------------------------------------------------===//
10722 // lazy bind table dumping
10723 //===----------------------------------------------------------------------===//
10724 
10725 static void printMachOLazyBindTable(object::MachOObjectFile *Obj) {
10726   outs() << "segment  section            address     "
10727             "dylib            symbol\n";
10728   Error Err = Error::success();
10729   for (const object::MachOBindEntry &Entry : Obj->lazyBindTable(Err)) {
10730     StringRef SegmentName = Entry.segmentName();
10731     StringRef SectionName = Entry.sectionName();
10732     uint64_t Address = Entry.address();
10733 
10734     // Table lines look like:
10735     //  __DATA  __got  0x00012010 libSystem ___stack_chk_guard
10736     outs() << left_justify(SegmentName, 8) << " "
10737            << left_justify(SectionName, 18) << " "
10738            << format_hex(Address, 10, true) << " "
10739            << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
10740            << Entry.symbolName() << "\n";
10741   }
10742   if (Err)
10743     reportError(std::move(Err), Obj->getFileName());
10744 }
10745 
10746 //===----------------------------------------------------------------------===//
10747 // weak bind table dumping
10748 //===----------------------------------------------------------------------===//
10749 
10750 static void printMachOWeakBindTable(object::MachOObjectFile *Obj) {
10751   outs() << "segment  section            address     "
10752             "type       addend   symbol\n";
10753   Error Err = Error::success();
10754   for (const object::MachOBindEntry &Entry : Obj->weakBindTable(Err)) {
10755     // Strong symbols don't have a location to update.
10756     if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
10757       outs() << "                                        strong              "
10758              << Entry.symbolName() << "\n";
10759       continue;
10760     }
10761     StringRef SegmentName = Entry.segmentName();
10762     StringRef SectionName = Entry.sectionName();
10763     uint64_t Address = Entry.address();
10764 
10765     // Table lines look like:
10766     // __DATA  __data  0x00001000  pointer    0   _foo
10767     outs() << left_justify(SegmentName, 8) << " "
10768            << left_justify(SectionName, 18) << " "
10769            << format_hex(Address, 10, true) << " "
10770            << left_justify(Entry.typeName(), 8) << " "
10771            << format_decimal(Entry.addend(), 8) << "   " << Entry.symbolName()
10772            << "\n";
10773   }
10774   if (Err)
10775     reportError(std::move(Err), Obj->getFileName());
10776 }
10777 
10778 // get_dyld_bind_info_symbolname() is used for disassembly and passed an
10779 // address, ReferenceValue, in the Mach-O file and looks in the dyld bind
10780 // information for that address. If the address is found its binding symbol
10781 // name is returned.  If not nullptr is returned.
10782 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
10783                                                  struct DisassembleInfo *info) {
10784   if (info->bindtable == nullptr) {
10785     info->bindtable = std::make_unique<SymbolAddressMap>();
10786     Error Err = Error::success();
10787     for (const object::MachOBindEntry &Entry : info->O->bindTable(Err)) {
10788       uint64_t Address = Entry.address();
10789       StringRef name = Entry.symbolName();
10790       if (!name.empty())
10791         (*info->bindtable)[Address] = name;
10792     }
10793     if (Err)
10794       reportError(std::move(Err), info->O->getFileName());
10795   }
10796   auto name = info->bindtable->lookup(ReferenceValue);
10797   return !name.empty() ? name.data() : nullptr;
10798 }
10799 
10800 void objdump::printLazyBindTable(ObjectFile *o) {
10801   outs() << "\nLazy bind table:\n";
10802   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10803     printMachOLazyBindTable(MachO);
10804   else
10805     WithColor::error()
10806         << "This operation is only currently supported "
10807            "for Mach-O executable files.\n";
10808 }
10809 
10810 void objdump::printWeakBindTable(ObjectFile *o) {
10811   outs() << "\nWeak bind table:\n";
10812   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10813     printMachOWeakBindTable(MachO);
10814   else
10815     WithColor::error()
10816         << "This operation is only currently supported "
10817            "for Mach-O executable files.\n";
10818 }
10819 
10820 void objdump::printExportsTrie(const ObjectFile *o) {
10821   outs() << "\nExports trie:\n";
10822   if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10823     printMachOExportsTrie(MachO);
10824   else
10825     WithColor::error()
10826         << "This operation is only currently supported "
10827            "for Mach-O executable files.\n";
10828 }
10829 
10830 void objdump::printRebaseTable(ObjectFile *o) {
10831   outs() << "\nRebase table:\n";
10832   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10833     printMachORebaseTable(MachO);
10834   else
10835     WithColor::error()
10836         << "This operation is only currently supported "
10837            "for Mach-O executable files.\n";
10838 }
10839 
10840 void objdump::printBindTable(ObjectFile *o) {
10841   outs() << "\nBind table:\n";
10842   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10843     printMachOBindTable(MachO);
10844   else
10845     WithColor::error()
10846         << "This operation is only currently supported "
10847            "for Mach-O executable files.\n";
10848 }
10849