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/ADT/Triple.h"
21 #include "llvm/BinaryFormat/MachO.h"
22 #include "llvm/Config/config.h"
23 #include "llvm/DebugInfo/DIContext.h"
24 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
25 #include "llvm/Demangle/Demangle.h"
26 #include "llvm/MC/MCAsmInfo.h"
27 #include "llvm/MC/MCContext.h"
28 #include "llvm/MC/MCDisassembler/MCDisassembler.h"
29 #include "llvm/MC/MCInst.h"
30 #include "llvm/MC/MCInstPrinter.h"
31 #include "llvm/MC/MCInstrDesc.h"
32 #include "llvm/MC/MCInstrInfo.h"
33 #include "llvm/MC/MCRegisterInfo.h"
34 #include "llvm/MC/MCSubtargetInfo.h"
35 #include "llvm/MC/MCTargetOptions.h"
36 #include "llvm/MC/TargetRegistry.h"
37 #include "llvm/Object/MachO.h"
38 #include "llvm/Object/MachOUniversal.h"
39 #include "llvm/Option/ArgList.h"
40 #include "llvm/Support/Casting.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/Endian.h"
43 #include "llvm/Support/Format.h"
44 #include "llvm/Support/FormattedStream.h"
45 #include "llvm/Support/GraphWriter.h"
46 #include "llvm/Support/LEB128.h"
47 #include "llvm/Support/MemoryBuffer.h"
48 #include "llvm/Support/TargetSelect.h"
49 #include "llvm/Support/ToolOutputFile.h"
50 #include "llvm/Support/WithColor.h"
51 #include "llvm/Support/raw_ostream.h"
52 #include <algorithm>
53 #include <cstring>
54 #include <system_error>
55 
56 #ifdef 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 bool objdump::FunctionStarts;
82 bool objdump::LinkOptHints;
83 bool objdump::InfoPlist;
84 bool objdump::DyldInfo;
85 bool objdump::DylibsUsed;
86 bool objdump::DylibId;
87 bool objdump::Verbose;
88 bool objdump::ObjcMetaData;
89 std::string objdump::DisSymName;
90 bool objdump::SymbolicOperands;
91 static std::vector<std::string> ArchFlags;
92 
93 static bool ArchAll = false;
94 static std::string ThumbTripleName;
95 
96 void objdump::parseMachOOptions(const llvm::opt::InputArgList &InputArgs) {
97   FirstPrivateHeader = InputArgs.hasArg(OBJDUMP_private_header);
98   ExportsTrie = InputArgs.hasArg(OBJDUMP_exports_trie);
99   Rebase = InputArgs.hasArg(OBJDUMP_rebase);
100   Rpaths = InputArgs.hasArg(OBJDUMP_rpaths);
101   Bind = InputArgs.hasArg(OBJDUMP_bind);
102   LazyBind = InputArgs.hasArg(OBJDUMP_lazy_bind);
103   WeakBind = InputArgs.hasArg(OBJDUMP_weak_bind);
104   UseDbg = InputArgs.hasArg(OBJDUMP_g);
105   DSYMFile = InputArgs.getLastArgValue(OBJDUMP_dsym_EQ).str();
106   FullLeadingAddr = InputArgs.hasArg(OBJDUMP_full_leading_addr);
107   LeadingHeaders = !InputArgs.hasArg(OBJDUMP_no_leading_headers);
108   UniversalHeaders = InputArgs.hasArg(OBJDUMP_universal_headers);
109   ArchiveMemberOffsets = InputArgs.hasArg(OBJDUMP_archive_member_offsets);
110   IndirectSymbols = InputArgs.hasArg(OBJDUMP_indirect_symbols);
111   DataInCode = InputArgs.hasArg(OBJDUMP_data_in_code);
112   FunctionStarts = InputArgs.hasArg(OBJDUMP_function_starts);
113   LinkOptHints = InputArgs.hasArg(OBJDUMP_link_opt_hints);
114   InfoPlist = InputArgs.hasArg(OBJDUMP_info_plist);
115   DyldInfo = InputArgs.hasArg(OBJDUMP_dyld_info);
116   DylibsUsed = InputArgs.hasArg(OBJDUMP_dylibs_used);
117   DylibId = InputArgs.hasArg(OBJDUMP_dylib_id);
118   Verbose = !InputArgs.hasArg(OBJDUMP_non_verbose);
119   ObjcMetaData = InputArgs.hasArg(OBJDUMP_objc_meta_data);
120   DisSymName = InputArgs.getLastArgValue(OBJDUMP_dis_symname).str();
121   SymbolicOperands = !InputArgs.hasArg(OBJDUMP_no_symbolic_operands);
122   ArchFlags = InputArgs.getAllArgValues(OBJDUMP_arch_EQ);
123 }
124 
125 static const Target *GetTarget(const MachOObjectFile *MachOObj,
126                                const char **McpuDefault,
127                                const Target **ThumbTarget) {
128   // Figure out the target triple.
129   Triple TT(TripleName);
130   if (TripleName.empty()) {
131     TT = MachOObj->getArchTriple(McpuDefault);
132     TripleName = TT.str();
133   }
134 
135   if (TT.getArch() == Triple::arm) {
136     // We've inferred a 32-bit ARM target from the object file. All MachO CPUs
137     // that support ARM are also capable of Thumb mode.
138     Triple ThumbTriple = TT;
139     std::string ThumbName = (Twine("thumb") + TT.getArchName().substr(3)).str();
140     ThumbTriple.setArchName(ThumbName);
141     ThumbTripleName = ThumbTriple.str();
142   }
143 
144   // Get the target specific parser.
145   std::string Error;
146   const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
147   if (TheTarget && ThumbTripleName.empty())
148     return TheTarget;
149 
150   *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
151   if (*ThumbTarget)
152     return TheTarget;
153 
154   WithColor::error(errs(), "llvm-objdump") << "unable to get target for '";
155   if (!TheTarget)
156     errs() << TripleName;
157   else
158     errs() << ThumbTripleName;
159   errs() << "', see --version and --triple.\n";
160   return nullptr;
161 }
162 
163 namespace {
164 struct SymbolSorter {
165   bool operator()(const SymbolRef &A, const SymbolRef &B) {
166     Expected<SymbolRef::Type> ATypeOrErr = A.getType();
167     if (!ATypeOrErr)
168       reportError(ATypeOrErr.takeError(), A.getObject()->getFileName());
169     SymbolRef::Type AType = *ATypeOrErr;
170     Expected<SymbolRef::Type> BTypeOrErr = B.getType();
171     if (!BTypeOrErr)
172       reportError(BTypeOrErr.takeError(), B.getObject()->getFileName());
173     SymbolRef::Type BType = *BTypeOrErr;
174     uint64_t AAddr =
175         (AType != SymbolRef::ST_Function) ? 0 : cantFail(A.getValue());
176     uint64_t BAddr =
177         (BType != SymbolRef::ST_Function) ? 0 : cantFail(B.getValue());
178     return AAddr < BAddr;
179   }
180 };
181 } // namespace
182 
183 // Types for the storted data in code table that is built before disassembly
184 // and the predicate function to sort them.
185 typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
186 typedef std::vector<DiceTableEntry> DiceTable;
187 typedef DiceTable::iterator dice_table_iterator;
188 
189 #ifdef LLVM_HAVE_LIBXAR
190 namespace {
191 struct ScopedXarFile {
192   xar_t xar;
193   ScopedXarFile(const char *filename, int32_t flags) {
194 #pragma clang diagnostic push
195 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
196     xar = xar_open(filename, flags);
197 #pragma clang diagnostic pop
198   }
199   ~ScopedXarFile() {
200     if (xar)
201       xar_close(xar);
202   }
203   ScopedXarFile(const ScopedXarFile &) = delete;
204   ScopedXarFile &operator=(const ScopedXarFile &) = delete;
205   operator xar_t() { return xar; }
206 };
207 
208 struct ScopedXarIter {
209   xar_iter_t iter;
210   ScopedXarIter() : iter(xar_iter_new()) {}
211   ~ScopedXarIter() {
212     if (iter)
213       xar_iter_free(iter);
214   }
215   ScopedXarIter(const ScopedXarIter &) = delete;
216   ScopedXarIter &operator=(const ScopedXarIter &) = delete;
217   operator xar_iter_t() { return iter; }
218 };
219 } // namespace
220 #endif // defined(LLVM_HAVE_LIBXAR)
221 
222 // This is used to search for a data in code table entry for the PC being
223 // disassembled.  The j parameter has the PC in j.first.  A single data in code
224 // table entry can cover many bytes for each of its Kind's.  So if the offset,
225 // aka the i.first value, of the data in code table entry plus its Length
226 // covers the PC being searched for this will return true.  If not it will
227 // return false.
228 static bool compareDiceTableEntries(const DiceTableEntry &i,
229                                     const DiceTableEntry &j) {
230   uint16_t Length;
231   i.second.getLength(Length);
232 
233   return j.first >= i.first && j.first < i.first + Length;
234 }
235 
236 static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
237                                unsigned short Kind) {
238   uint32_t Value, Size = 1;
239 
240   switch (Kind) {
241   default:
242   case MachO::DICE_KIND_DATA:
243     if (Length >= 4) {
244       if (ShowRawInsn)
245         dumpBytes(makeArrayRef(bytes, 4), outs());
246       Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
247       outs() << "\t.long " << Value;
248       Size = 4;
249     } else if (Length >= 2) {
250       if (ShowRawInsn)
251         dumpBytes(makeArrayRef(bytes, 2), outs());
252       Value = bytes[1] << 8 | bytes[0];
253       outs() << "\t.short " << Value;
254       Size = 2;
255     } else {
256       if (ShowRawInsn)
257         dumpBytes(makeArrayRef(bytes, 2), outs());
258       Value = bytes[0];
259       outs() << "\t.byte " << Value;
260       Size = 1;
261     }
262     if (Kind == MachO::DICE_KIND_DATA)
263       outs() << "\t@ KIND_DATA\n";
264     else
265       outs() << "\t@ data in code kind = " << Kind << "\n";
266     break;
267   case MachO::DICE_KIND_JUMP_TABLE8:
268     if (ShowRawInsn)
269       dumpBytes(makeArrayRef(bytes, 1), outs());
270     Value = bytes[0];
271     outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
272     Size = 1;
273     break;
274   case MachO::DICE_KIND_JUMP_TABLE16:
275     if (ShowRawInsn)
276       dumpBytes(makeArrayRef(bytes, 2), outs());
277     Value = bytes[1] << 8 | bytes[0];
278     outs() << "\t.short " << format("%5u", Value & 0xffff)
279            << "\t@ KIND_JUMP_TABLE16\n";
280     Size = 2;
281     break;
282   case MachO::DICE_KIND_JUMP_TABLE32:
283   case MachO::DICE_KIND_ABS_JUMP_TABLE32:
284     if (ShowRawInsn)
285       dumpBytes(makeArrayRef(bytes, 4), outs());
286     Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
287     outs() << "\t.long " << Value;
288     if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
289       outs() << "\t@ KIND_JUMP_TABLE32\n";
290     else
291       outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
292     Size = 4;
293     break;
294   }
295   return Size;
296 }
297 
298 static void getSectionsAndSymbols(MachOObjectFile *MachOObj,
299                                   std::vector<SectionRef> &Sections,
300                                   std::vector<SymbolRef> &Symbols,
301                                   SmallVectorImpl<uint64_t> &FoundFns,
302                                   uint64_t &BaseSegmentAddress) {
303   const StringRef FileName = MachOObj->getFileName();
304   for (const SymbolRef &Symbol : MachOObj->symbols()) {
305     StringRef SymName = unwrapOrError(Symbol.getName(), FileName);
306     if (!SymName.startswith("ltmp"))
307       Symbols.push_back(Symbol);
308   }
309 
310   append_range(Sections, MachOObj->sections());
311 
312   bool BaseSegmentAddressSet = false;
313   for (const auto &Command : MachOObj->load_commands()) {
314     if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
315       // We found a function starts segment, parse the addresses for later
316       // consumption.
317       MachO::linkedit_data_command LLC =
318           MachOObj->getLinkeditDataLoadCommand(Command);
319 
320       MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
321     } else if (Command.C.cmd == MachO::LC_SEGMENT) {
322       MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
323       StringRef SegName = SLC.segname;
324       if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
325         BaseSegmentAddressSet = true;
326         BaseSegmentAddress = SLC.vmaddr;
327       }
328     } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
329       MachO::segment_command_64 SLC = MachOObj->getSegment64LoadCommand(Command);
330       StringRef SegName = SLC.segname;
331       if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
332         BaseSegmentAddressSet = true;
333         BaseSegmentAddress = SLC.vmaddr;
334       }
335     }
336   }
337 }
338 
339 static bool DumpAndSkipDataInCode(uint64_t PC, const uint8_t *bytes,
340                                  DiceTable &Dices, uint64_t &InstSize) {
341   // Check the data in code table here to see if this is data not an
342   // instruction to be disassembled.
343   DiceTable Dice;
344   Dice.push_back(std::make_pair(PC, DiceRef()));
345   dice_table_iterator DTI =
346       std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
347                   compareDiceTableEntries);
348   if (DTI != Dices.end()) {
349     uint16_t Length;
350     DTI->second.getLength(Length);
351     uint16_t Kind;
352     DTI->second.getKind(Kind);
353     InstSize = DumpDataInCode(bytes, Length, Kind);
354     if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
355         (PC == (DTI->first + Length - 1)) && (Length & 1))
356       InstSize++;
357     return true;
358   }
359   return false;
360 }
361 
362 static void printRelocationTargetName(const MachOObjectFile *O,
363                                       const MachO::any_relocation_info &RE,
364                                       raw_string_ostream &Fmt) {
365   // Target of a scattered relocation is an address.  In the interest of
366   // generating pretty output, scan through the symbol table looking for a
367   // symbol that aligns with that address.  If we find one, print it.
368   // Otherwise, we just print the hex address of the target.
369   const StringRef FileName = O->getFileName();
370   if (O->isRelocationScattered(RE)) {
371     uint32_t Val = O->getPlainRelocationSymbolNum(RE);
372 
373     for (const SymbolRef &Symbol : O->symbols()) {
374       uint64_t Addr = unwrapOrError(Symbol.getAddress(), FileName);
375       if (Addr != Val)
376         continue;
377       Fmt << unwrapOrError(Symbol.getName(), FileName);
378       return;
379     }
380 
381     // If we couldn't find a symbol that this relocation refers to, try
382     // to find a section beginning instead.
383     for (const SectionRef &Section : ToolSectionFilter(*O)) {
384       uint64_t Addr = Section.getAddress();
385       if (Addr != Val)
386         continue;
387       StringRef NameOrErr = unwrapOrError(Section.getName(), O->getFileName());
388       Fmt << NameOrErr;
389       return;
390     }
391 
392     Fmt << format("0x%x", Val);
393     return;
394   }
395 
396   StringRef S;
397   bool isExtern = O->getPlainRelocationExternal(RE);
398   uint64_t Val = O->getPlainRelocationSymbolNum(RE);
399 
400   if (O->getAnyRelocationType(RE) == MachO::ARM64_RELOC_ADDEND &&
401       (O->getArch() == Triple::aarch64 || O->getArch() == Triple::aarch64_be)) {
402     Fmt << format("0x%0" PRIx64, Val);
403     return;
404   }
405 
406   if (isExtern) {
407     symbol_iterator SI = O->symbol_begin();
408     std::advance(SI, Val);
409     S = unwrapOrError(SI->getName(), FileName);
410   } else {
411     section_iterator SI = O->section_begin();
412     // Adjust for the fact that sections are 1-indexed.
413     if (Val == 0) {
414       Fmt << "0 (?,?)";
415       return;
416     }
417     uint32_t I = Val - 1;
418     while (I != 0 && SI != O->section_end()) {
419       --I;
420       std::advance(SI, 1);
421     }
422     if (SI == O->section_end()) {
423       Fmt << Val << " (?,?)";
424     } else {
425       if (Expected<StringRef> NameOrErr = SI->getName())
426         S = *NameOrErr;
427       else
428         consumeError(NameOrErr.takeError());
429     }
430   }
431 
432   Fmt << S;
433 }
434 
435 Error objdump::getMachORelocationValueString(const MachOObjectFile *Obj,
436                                              const RelocationRef &RelRef,
437                                              SmallVectorImpl<char> &Result) {
438   DataRefImpl Rel = RelRef.getRawDataRefImpl();
439   MachO::any_relocation_info RE = Obj->getRelocation(Rel);
440 
441   unsigned Arch = Obj->getArch();
442 
443   std::string FmtBuf;
444   raw_string_ostream Fmt(FmtBuf);
445   unsigned Type = Obj->getAnyRelocationType(RE);
446   bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
447 
448   // Determine any addends that should be displayed with the relocation.
449   // These require decoding the relocation type, which is triple-specific.
450 
451   // X86_64 has entirely custom relocation types.
452   if (Arch == Triple::x86_64) {
453     switch (Type) {
454     case MachO::X86_64_RELOC_GOT_LOAD:
455     case MachO::X86_64_RELOC_GOT: {
456       printRelocationTargetName(Obj, RE, Fmt);
457       Fmt << "@GOT";
458       if (IsPCRel)
459         Fmt << "PCREL";
460       break;
461     }
462     case MachO::X86_64_RELOC_SUBTRACTOR: {
463       DataRefImpl RelNext = Rel;
464       Obj->moveRelocationNext(RelNext);
465       MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
466 
467       // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
468       // X86_64_RELOC_UNSIGNED.
469       // NOTE: Scattered relocations don't exist on x86_64.
470       unsigned RType = Obj->getAnyRelocationType(RENext);
471       if (RType != MachO::X86_64_RELOC_UNSIGNED)
472         reportError(Obj->getFileName(), "Expected X86_64_RELOC_UNSIGNED after "
473                                         "X86_64_RELOC_SUBTRACTOR.");
474 
475       // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
476       // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
477       printRelocationTargetName(Obj, RENext, Fmt);
478       Fmt << "-";
479       printRelocationTargetName(Obj, RE, Fmt);
480       break;
481     }
482     case MachO::X86_64_RELOC_TLV:
483       printRelocationTargetName(Obj, RE, Fmt);
484       Fmt << "@TLV";
485       if (IsPCRel)
486         Fmt << "P";
487       break;
488     case MachO::X86_64_RELOC_SIGNED_1:
489       printRelocationTargetName(Obj, RE, Fmt);
490       Fmt << "-1";
491       break;
492     case MachO::X86_64_RELOC_SIGNED_2:
493       printRelocationTargetName(Obj, RE, Fmt);
494       Fmt << "-2";
495       break;
496     case MachO::X86_64_RELOC_SIGNED_4:
497       printRelocationTargetName(Obj, RE, Fmt);
498       Fmt << "-4";
499       break;
500     default:
501       printRelocationTargetName(Obj, RE, Fmt);
502       break;
503     }
504     // X86 and ARM share some relocation types in common.
505   } else if (Arch == Triple::x86 || Arch == Triple::arm ||
506              Arch == Triple::ppc) {
507     // Generic relocation types...
508     switch (Type) {
509     case MachO::GENERIC_RELOC_PAIR: // prints no info
510       return Error::success();
511     case MachO::GENERIC_RELOC_SECTDIFF: {
512       DataRefImpl RelNext = Rel;
513       Obj->moveRelocationNext(RelNext);
514       MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
515 
516       // X86 sect diff's must be followed by a relocation of type
517       // GENERIC_RELOC_PAIR.
518       unsigned RType = Obj->getAnyRelocationType(RENext);
519 
520       if (RType != MachO::GENERIC_RELOC_PAIR)
521         reportError(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
522                                         "GENERIC_RELOC_SECTDIFF.");
523 
524       printRelocationTargetName(Obj, RE, Fmt);
525       Fmt << "-";
526       printRelocationTargetName(Obj, RENext, Fmt);
527       break;
528     }
529     }
530 
531     if (Arch == Triple::x86 || Arch == Triple::ppc) {
532       switch (Type) {
533       case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
534         DataRefImpl RelNext = Rel;
535         Obj->moveRelocationNext(RelNext);
536         MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
537 
538         // X86 sect diff's must be followed by a relocation of type
539         // GENERIC_RELOC_PAIR.
540         unsigned RType = Obj->getAnyRelocationType(RENext);
541         if (RType != MachO::GENERIC_RELOC_PAIR)
542           reportError(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
543                                           "GENERIC_RELOC_LOCAL_SECTDIFF.");
544 
545         printRelocationTargetName(Obj, RE, Fmt);
546         Fmt << "-";
547         printRelocationTargetName(Obj, RENext, Fmt);
548         break;
549       }
550       case MachO::GENERIC_RELOC_TLV: {
551         printRelocationTargetName(Obj, RE, Fmt);
552         Fmt << "@TLV";
553         if (IsPCRel)
554           Fmt << "P";
555         break;
556       }
557       default:
558         printRelocationTargetName(Obj, RE, Fmt);
559       }
560     } else { // ARM-specific relocations
561       switch (Type) {
562       case MachO::ARM_RELOC_HALF:
563       case MachO::ARM_RELOC_HALF_SECTDIFF: {
564         // Half relocations steal a bit from the length field to encode
565         // whether this is an upper16 or a lower16 relocation.
566         bool isUpper = (Obj->getAnyRelocationLength(RE) & 0x1) == 1;
567 
568         if (isUpper)
569           Fmt << ":upper16:(";
570         else
571           Fmt << ":lower16:(";
572         printRelocationTargetName(Obj, RE, Fmt);
573 
574         DataRefImpl RelNext = Rel;
575         Obj->moveRelocationNext(RelNext);
576         MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
577 
578         // ARM half relocs must be followed by a relocation of type
579         // ARM_RELOC_PAIR.
580         unsigned RType = Obj->getAnyRelocationType(RENext);
581         if (RType != MachO::ARM_RELOC_PAIR)
582           reportError(Obj->getFileName(), "Expected ARM_RELOC_PAIR after "
583                                           "ARM_RELOC_HALF");
584 
585         // NOTE: The half of the target virtual address is stashed in the
586         // address field of the secondary relocation, but we can't reverse
587         // engineer the constant offset from it without decoding the movw/movt
588         // instruction to find the other half in its immediate field.
589 
590         // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
591         // symbol/section pointer of the follow-on relocation.
592         if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
593           Fmt << "-";
594           printRelocationTargetName(Obj, RENext, Fmt);
595         }
596 
597         Fmt << ")";
598         break;
599       }
600       default: {
601         printRelocationTargetName(Obj, RE, Fmt);
602       }
603       }
604     }
605   } else
606     printRelocationTargetName(Obj, RE, Fmt);
607 
608   Fmt.flush();
609   Result.append(FmtBuf.begin(), FmtBuf.end());
610   return Error::success();
611 }
612 
613 static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
614                                      uint32_t n, uint32_t count,
615                                      uint32_t stride, uint64_t addr) {
616   MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
617   uint32_t nindirectsyms = Dysymtab.nindirectsyms;
618   if (n > nindirectsyms)
619     outs() << " (entries start past the end of the indirect symbol "
620               "table) (reserved1 field greater than the table size)";
621   else if (n + count > nindirectsyms)
622     outs() << " (entries extends past the end of the indirect symbol "
623               "table)";
624   outs() << "\n";
625   uint32_t cputype = O->getHeader().cputype;
626   if (cputype & MachO::CPU_ARCH_ABI64)
627     outs() << "address            index";
628   else
629     outs() << "address    index";
630   if (verbose)
631     outs() << " name\n";
632   else
633     outs() << "\n";
634   for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
635     if (cputype & MachO::CPU_ARCH_ABI64)
636       outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
637     else
638       outs() << format("0x%08" PRIx32, (uint32_t)addr + j * stride) << " ";
639     MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
640     uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
641     if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
642       outs() << "LOCAL\n";
643       continue;
644     }
645     if (indirect_symbol ==
646         (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
647       outs() << "LOCAL ABSOLUTE\n";
648       continue;
649     }
650     if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
651       outs() << "ABSOLUTE\n";
652       continue;
653     }
654     outs() << format("%5u ", indirect_symbol);
655     if (verbose) {
656       MachO::symtab_command Symtab = O->getSymtabLoadCommand();
657       if (indirect_symbol < Symtab.nsyms) {
658         symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
659         SymbolRef Symbol = *Sym;
660         outs() << unwrapOrError(Symbol.getName(), O->getFileName());
661       } else {
662         outs() << "?";
663       }
664     }
665     outs() << "\n";
666   }
667 }
668 
669 static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
670   for (const auto &Load : O->load_commands()) {
671     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
672       MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
673       for (unsigned J = 0; J < Seg.nsects; ++J) {
674         MachO::section_64 Sec = O->getSection64(Load, J);
675         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
676         if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
677             section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
678             section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
679             section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
680             section_type == MachO::S_SYMBOL_STUBS) {
681           uint32_t stride;
682           if (section_type == MachO::S_SYMBOL_STUBS)
683             stride = Sec.reserved2;
684           else
685             stride = 8;
686           if (stride == 0) {
687             outs() << "Can't print indirect symbols for (" << Sec.segname << ","
688                    << Sec.sectname << ") "
689                    << "(size of stubs in reserved2 field is zero)\n";
690             continue;
691           }
692           uint32_t count = Sec.size / stride;
693           outs() << "Indirect symbols for (" << Sec.segname << ","
694                  << Sec.sectname << ") " << count << " entries";
695           uint32_t n = Sec.reserved1;
696           PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
697         }
698       }
699     } else if (Load.C.cmd == MachO::LC_SEGMENT) {
700       MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
701       for (unsigned J = 0; J < Seg.nsects; ++J) {
702         MachO::section Sec = O->getSection(Load, J);
703         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
704         if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
705             section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
706             section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
707             section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
708             section_type == MachO::S_SYMBOL_STUBS) {
709           uint32_t stride;
710           if (section_type == MachO::S_SYMBOL_STUBS)
711             stride = Sec.reserved2;
712           else
713             stride = 4;
714           if (stride == 0) {
715             outs() << "Can't print indirect symbols for (" << Sec.segname << ","
716                    << Sec.sectname << ") "
717                    << "(size of stubs in reserved2 field is zero)\n";
718             continue;
719           }
720           uint32_t count = Sec.size / stride;
721           outs() << "Indirect symbols for (" << Sec.segname << ","
722                  << Sec.sectname << ") " << count << " entries";
723           uint32_t n = Sec.reserved1;
724           PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
725         }
726       }
727     }
728   }
729 }
730 
731 static void PrintRType(const uint64_t cputype, const unsigned r_type) {
732   static char const *generic_r_types[] = {
733     "VANILLA ", "PAIR    ", "SECTDIF ", "PBLAPTR ", "LOCSDIF ", "TLV     ",
734     "  6 (?) ", "  7 (?) ", "  8 (?) ", "  9 (?) ", " 10 (?) ", " 11 (?) ",
735     " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
736   };
737   static char const *x86_64_r_types[] = {
738     "UNSIGND ", "SIGNED  ", "BRANCH  ", "GOT_LD  ", "GOT     ", "SUB     ",
739     "SIGNED1 ", "SIGNED2 ", "SIGNED4 ", "TLV     ", " 10 (?) ", " 11 (?) ",
740     " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
741   };
742   static char const *arm_r_types[] = {
743     "VANILLA ", "PAIR    ", "SECTDIFF", "LOCSDIF ", "PBLAPTR ",
744     "BR24    ", "T_BR22  ", "T_BR32  ", "HALF    ", "HALFDIF ",
745     " 10 (?) ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
746   };
747   static char const *arm64_r_types[] = {
748     "UNSIGND ", "SUB     ", "BR26    ", "PAGE21  ", "PAGOF12 ",
749     "GOTLDP  ", "GOTLDPOF", "PTRTGOT ", "TLVLDP  ", "TLVLDPOF",
750     "ADDEND  ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
751   };
752 
753   if (r_type > 0xf){
754     outs() << format("%-7u", r_type) << " ";
755     return;
756   }
757   switch (cputype) {
758     case MachO::CPU_TYPE_I386:
759       outs() << generic_r_types[r_type];
760       break;
761     case MachO::CPU_TYPE_X86_64:
762       outs() << x86_64_r_types[r_type];
763       break;
764     case MachO::CPU_TYPE_ARM:
765       outs() << arm_r_types[r_type];
766       break;
767     case MachO::CPU_TYPE_ARM64:
768     case MachO::CPU_TYPE_ARM64_32:
769       outs() << arm64_r_types[r_type];
770       break;
771     default:
772       outs() << format("%-7u ", r_type);
773   }
774 }
775 
776 static void PrintRLength(const uint64_t cputype, const unsigned r_type,
777                          const unsigned r_length, const bool previous_arm_half){
778   if (cputype == MachO::CPU_TYPE_ARM &&
779       (r_type == MachO::ARM_RELOC_HALF ||
780        r_type == MachO::ARM_RELOC_HALF_SECTDIFF || previous_arm_half == true)) {
781     if ((r_length & 0x1) == 0)
782       outs() << "lo/";
783     else
784       outs() << "hi/";
785     if ((r_length & 0x1) == 0)
786       outs() << "arm ";
787     else
788       outs() << "thm ";
789   } else {
790     switch (r_length) {
791       case 0:
792         outs() << "byte   ";
793         break;
794       case 1:
795         outs() << "word   ";
796         break;
797       case 2:
798         outs() << "long   ";
799         break;
800       case 3:
801         if (cputype == MachO::CPU_TYPE_X86_64)
802           outs() << "quad   ";
803         else
804           outs() << format("?(%2d)  ", r_length);
805         break;
806       default:
807         outs() << format("?(%2d)  ", r_length);
808     }
809   }
810 }
811 
812 static void PrintRelocationEntries(const MachOObjectFile *O,
813                                    const relocation_iterator Begin,
814                                    const relocation_iterator End,
815                                    const uint64_t cputype,
816                                    const bool verbose) {
817   const MachO::symtab_command Symtab = O->getSymtabLoadCommand();
818   bool previous_arm_half = false;
819   bool previous_sectdiff = false;
820   uint32_t sectdiff_r_type = 0;
821 
822   for (relocation_iterator Reloc = Begin; Reloc != End; ++Reloc) {
823     const DataRefImpl Rel = Reloc->getRawDataRefImpl();
824     const MachO::any_relocation_info RE = O->getRelocation(Rel);
825     const unsigned r_type = O->getAnyRelocationType(RE);
826     const bool r_scattered = O->isRelocationScattered(RE);
827     const unsigned r_pcrel = O->getAnyRelocationPCRel(RE);
828     const unsigned r_length = O->getAnyRelocationLength(RE);
829     const unsigned r_address = O->getAnyRelocationAddress(RE);
830     const bool r_extern = (r_scattered ? false :
831                            O->getPlainRelocationExternal(RE));
832     const uint32_t r_value = (r_scattered ?
833                               O->getScatteredRelocationValue(RE) : 0);
834     const unsigned r_symbolnum = (r_scattered ? 0 :
835                                   O->getPlainRelocationSymbolNum(RE));
836 
837     if (r_scattered && cputype != MachO::CPU_TYPE_X86_64) {
838       if (verbose) {
839         // scattered: address
840         if ((cputype == MachO::CPU_TYPE_I386 &&
841              r_type == MachO::GENERIC_RELOC_PAIR) ||
842             (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR))
843           outs() << "         ";
844         else
845           outs() << format("%08x ", (unsigned int)r_address);
846 
847         // scattered: pcrel
848         if (r_pcrel)
849           outs() << "True  ";
850         else
851           outs() << "False ";
852 
853         // scattered: length
854         PrintRLength(cputype, r_type, r_length, previous_arm_half);
855 
856         // scattered: extern & type
857         outs() << "n/a    ";
858         PrintRType(cputype, r_type);
859 
860         // scattered: scattered & value
861         outs() << format("True      0x%08x", (unsigned int)r_value);
862         if (previous_sectdiff == false) {
863           if ((cputype == MachO::CPU_TYPE_ARM &&
864                r_type == MachO::ARM_RELOC_PAIR))
865             outs() << format(" half = 0x%04x ", (unsigned int)r_address);
866         } else if (cputype == MachO::CPU_TYPE_ARM &&
867                    sectdiff_r_type == MachO::ARM_RELOC_HALF_SECTDIFF)
868           outs() << format(" other_half = 0x%04x ", (unsigned int)r_address);
869         if ((cputype == MachO::CPU_TYPE_I386 &&
870              (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
871               r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) ||
872             (cputype == MachO::CPU_TYPE_ARM &&
873              (sectdiff_r_type == MachO::ARM_RELOC_SECTDIFF ||
874               sectdiff_r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
875               sectdiff_r_type == MachO::ARM_RELOC_HALF_SECTDIFF))) {
876           previous_sectdiff = true;
877           sectdiff_r_type = r_type;
878         } else {
879           previous_sectdiff = false;
880           sectdiff_r_type = 0;
881         }
882         if (cputype == MachO::CPU_TYPE_ARM &&
883             (r_type == MachO::ARM_RELOC_HALF ||
884              r_type == MachO::ARM_RELOC_HALF_SECTDIFF))
885           previous_arm_half = true;
886         else
887           previous_arm_half = false;
888         outs() << "\n";
889       }
890       else {
891         // scattered: address pcrel length extern type scattered value
892         outs() << format("%08x %1d     %-2d     n/a    %-7d 1         0x%08x\n",
893                          (unsigned int)r_address, r_pcrel, r_length, r_type,
894                          (unsigned int)r_value);
895       }
896     }
897     else {
898       if (verbose) {
899         // plain: address
900         if (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR)
901           outs() << "         ";
902         else
903           outs() << format("%08x ", (unsigned int)r_address);
904 
905         // plain: pcrel
906         if (r_pcrel)
907           outs() << "True  ";
908         else
909           outs() << "False ";
910 
911         // plain: length
912         PrintRLength(cputype, r_type, r_length, previous_arm_half);
913 
914         if (r_extern) {
915           // plain: extern & type & scattered
916           outs() << "True   ";
917           PrintRType(cputype, r_type);
918           outs() << "False     ";
919 
920           // plain: symbolnum/value
921           if (r_symbolnum > Symtab.nsyms)
922             outs() << format("?(%d)\n", r_symbolnum);
923           else {
924             SymbolRef Symbol = *O->getSymbolByIndex(r_symbolnum);
925             Expected<StringRef> SymNameNext = Symbol.getName();
926             const char *name = nullptr;
927             if (SymNameNext)
928               name = SymNameNext->data();
929             if (name == nullptr)
930               outs() << format("?(%d)\n", r_symbolnum);
931             else
932               outs() << name << "\n";
933           }
934         }
935         else {
936           // plain: extern & type & scattered
937           outs() << "False  ";
938           PrintRType(cputype, r_type);
939           outs() << "False     ";
940 
941           // plain: symbolnum/value
942           if (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR)
943             outs() << format("other_half = 0x%04x\n", (unsigned int)r_address);
944           else if ((cputype == MachO::CPU_TYPE_ARM64 ||
945                     cputype == MachO::CPU_TYPE_ARM64_32) &&
946                    r_type == MachO::ARM64_RELOC_ADDEND)
947             outs() << format("addend = 0x%06x\n", (unsigned int)r_symbolnum);
948           else {
949             outs() << format("%d ", r_symbolnum);
950             if (r_symbolnum == MachO::R_ABS)
951               outs() << "R_ABS\n";
952             else {
953               // in this case, r_symbolnum is actually a 1-based section number
954               uint32_t nsects = O->section_end()->getRawDataRefImpl().d.a;
955               if (r_symbolnum > 0 && r_symbolnum <= nsects) {
956                 object::DataRefImpl DRI;
957                 DRI.d.a = r_symbolnum-1;
958                 StringRef SegName = O->getSectionFinalSegmentName(DRI);
959                 if (Expected<StringRef> NameOrErr = O->getSectionName(DRI))
960                   outs() << "(" << SegName << "," << *NameOrErr << ")\n";
961                 else
962                   outs() << "(?,?)\n";
963               }
964               else {
965                 outs() << "(?,?)\n";
966               }
967             }
968           }
969         }
970         if (cputype == MachO::CPU_TYPE_ARM &&
971             (r_type == MachO::ARM_RELOC_HALF ||
972              r_type == MachO::ARM_RELOC_HALF_SECTDIFF))
973           previous_arm_half = true;
974         else
975           previous_arm_half = false;
976       }
977       else {
978         // plain: address pcrel length extern type scattered symbolnum/section
979         outs() << format("%08x %1d     %-2d     %1d      %-7d 0         %d\n",
980                          (unsigned int)r_address, r_pcrel, r_length, r_extern,
981                          r_type, r_symbolnum);
982       }
983     }
984   }
985 }
986 
987 static void PrintRelocations(const MachOObjectFile *O, const bool verbose) {
988   const uint64_t cputype = O->getHeader().cputype;
989   const MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
990   if (Dysymtab.nextrel != 0) {
991     outs() << "External relocation information " << Dysymtab.nextrel
992            << " entries";
993     outs() << "\naddress  pcrel length extern type    scattered "
994               "symbolnum/value\n";
995     PrintRelocationEntries(O, O->extrel_begin(), O->extrel_end(), cputype,
996                            verbose);
997   }
998   if (Dysymtab.nlocrel != 0) {
999     outs() << format("Local relocation information %u entries",
1000                      Dysymtab.nlocrel);
1001     outs() << "\naddress  pcrel length extern type    scattered "
1002               "symbolnum/value\n";
1003     PrintRelocationEntries(O, O->locrel_begin(), O->locrel_end(), cputype,
1004                            verbose);
1005   }
1006   for (const auto &Load : O->load_commands()) {
1007     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
1008       const MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
1009       for (unsigned J = 0; J < Seg.nsects; ++J) {
1010         const MachO::section_64 Sec = O->getSection64(Load, J);
1011         if (Sec.nreloc != 0) {
1012           DataRefImpl DRI;
1013           DRI.d.a = J;
1014           const StringRef SegName = O->getSectionFinalSegmentName(DRI);
1015           if (Expected<StringRef> NameOrErr = O->getSectionName(DRI))
1016             outs() << "Relocation information (" << SegName << "," << *NameOrErr
1017                    << format(") %u entries", Sec.nreloc);
1018           else
1019             outs() << "Relocation information (" << SegName << ",?) "
1020                    << format("%u entries", Sec.nreloc);
1021           outs() << "\naddress  pcrel length extern type    scattered "
1022                     "symbolnum/value\n";
1023           PrintRelocationEntries(O, O->section_rel_begin(DRI),
1024                                  O->section_rel_end(DRI), cputype, verbose);
1025         }
1026       }
1027     } else if (Load.C.cmd == MachO::LC_SEGMENT) {
1028       const MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
1029       for (unsigned J = 0; J < Seg.nsects; ++J) {
1030         const MachO::section Sec = O->getSection(Load, J);
1031         if (Sec.nreloc != 0) {
1032           DataRefImpl DRI;
1033           DRI.d.a = J;
1034           const StringRef SegName = O->getSectionFinalSegmentName(DRI);
1035           if (Expected<StringRef> NameOrErr = O->getSectionName(DRI))
1036             outs() << "Relocation information (" << SegName << "," << *NameOrErr
1037                    << format(") %u entries", Sec.nreloc);
1038           else
1039             outs() << "Relocation information (" << SegName << ",?) "
1040                    << format("%u entries", Sec.nreloc);
1041           outs() << "\naddress  pcrel length extern type    scattered "
1042                     "symbolnum/value\n";
1043           PrintRelocationEntries(O, O->section_rel_begin(DRI),
1044                                  O->section_rel_end(DRI), cputype, verbose);
1045         }
1046       }
1047     }
1048   }
1049 }
1050 
1051 static void PrintFunctionStarts(MachOObjectFile *O) {
1052   uint64_t BaseSegmentAddress = 0;
1053   for (const MachOObjectFile::LoadCommandInfo &Command : O->load_commands()) {
1054     if (Command.C.cmd == MachO::LC_SEGMENT) {
1055       MachO::segment_command SLC = O->getSegmentLoadCommand(Command);
1056       if (StringRef(SLC.segname) == "__TEXT") {
1057         BaseSegmentAddress = SLC.vmaddr;
1058         break;
1059       }
1060     } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
1061       MachO::segment_command_64 SLC = O->getSegment64LoadCommand(Command);
1062       if (StringRef(SLC.segname) == "__TEXT") {
1063         BaseSegmentAddress = SLC.vmaddr;
1064         break;
1065       }
1066     }
1067   }
1068 
1069   SmallVector<uint64_t, 8> FunctionStarts;
1070   for (const MachOObjectFile::LoadCommandInfo &LC : O->load_commands()) {
1071     if (LC.C.cmd == MachO::LC_FUNCTION_STARTS) {
1072       MachO::linkedit_data_command FunctionStartsLC =
1073           O->getLinkeditDataLoadCommand(LC);
1074       O->ReadULEB128s(FunctionStartsLC.dataoff, FunctionStarts);
1075       break;
1076     }
1077   }
1078 
1079   for (uint64_t S : FunctionStarts) {
1080     uint64_t Addr = BaseSegmentAddress + S;
1081     if (O->is64Bit())
1082       outs() << format("%016" PRIx64, Addr) << "\n";
1083     else
1084       outs() << format("%08" PRIx32, static_cast<uint32_t>(Addr)) << "\n";
1085   }
1086 }
1087 
1088 static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
1089   MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
1090   uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
1091   outs() << "Data in code table (" << nentries << " entries)\n";
1092   outs() << "offset     length kind\n";
1093   for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
1094        ++DI) {
1095     uint32_t Offset;
1096     DI->getOffset(Offset);
1097     outs() << format("0x%08" PRIx32, Offset) << " ";
1098     uint16_t Length;
1099     DI->getLength(Length);
1100     outs() << format("%6u", Length) << " ";
1101     uint16_t Kind;
1102     DI->getKind(Kind);
1103     if (verbose) {
1104       switch (Kind) {
1105       case MachO::DICE_KIND_DATA:
1106         outs() << "DATA";
1107         break;
1108       case MachO::DICE_KIND_JUMP_TABLE8:
1109         outs() << "JUMP_TABLE8";
1110         break;
1111       case MachO::DICE_KIND_JUMP_TABLE16:
1112         outs() << "JUMP_TABLE16";
1113         break;
1114       case MachO::DICE_KIND_JUMP_TABLE32:
1115         outs() << "JUMP_TABLE32";
1116         break;
1117       case MachO::DICE_KIND_ABS_JUMP_TABLE32:
1118         outs() << "ABS_JUMP_TABLE32";
1119         break;
1120       default:
1121         outs() << format("0x%04" PRIx32, Kind);
1122         break;
1123       }
1124     } else
1125       outs() << format("0x%04" PRIx32, Kind);
1126     outs() << "\n";
1127   }
1128 }
1129 
1130 static void PrintLinkOptHints(MachOObjectFile *O) {
1131   MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
1132   const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
1133   uint32_t nloh = LohLC.datasize;
1134   outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
1135   for (uint32_t i = 0; i < nloh;) {
1136     unsigned n;
1137     uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
1138     i += n;
1139     outs() << "    identifier " << identifier << " ";
1140     if (i >= nloh)
1141       return;
1142     switch (identifier) {
1143     case 1:
1144       outs() << "AdrpAdrp\n";
1145       break;
1146     case 2:
1147       outs() << "AdrpLdr\n";
1148       break;
1149     case 3:
1150       outs() << "AdrpAddLdr\n";
1151       break;
1152     case 4:
1153       outs() << "AdrpLdrGotLdr\n";
1154       break;
1155     case 5:
1156       outs() << "AdrpAddStr\n";
1157       break;
1158     case 6:
1159       outs() << "AdrpLdrGotStr\n";
1160       break;
1161     case 7:
1162       outs() << "AdrpAdd\n";
1163       break;
1164     case 8:
1165       outs() << "AdrpLdrGot\n";
1166       break;
1167     default:
1168       outs() << "Unknown identifier value\n";
1169       break;
1170     }
1171     uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
1172     i += n;
1173     outs() << "    narguments " << narguments << "\n";
1174     if (i >= nloh)
1175       return;
1176 
1177     for (uint32_t j = 0; j < narguments; j++) {
1178       uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
1179       i += n;
1180       outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
1181       if (i >= nloh)
1182         return;
1183     }
1184   }
1185 }
1186 
1187 static void printMachOChainedFixups(object::MachOObjectFile *Obj) {
1188   Error Err = Error::success();
1189   for (const object::MachOChainedFixupEntry &Entry : Obj->fixupTable(Err)) {
1190     (void)Entry;
1191   }
1192   if (Err)
1193     reportError(std::move(Err), Obj->getFileName());
1194 }
1195 
1196 static void PrintDyldInfo(MachOObjectFile *O) {
1197   outs() << "dyld information:" << '\n';
1198   printMachOChainedFixups(O);
1199 }
1200 
1201 static void PrintDylibs(MachOObjectFile *O, bool JustId) {
1202   unsigned Index = 0;
1203   for (const auto &Load : O->load_commands()) {
1204     if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
1205         (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
1206                      Load.C.cmd == MachO::LC_LOAD_DYLIB ||
1207                      Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
1208                      Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
1209                      Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
1210                      Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
1211       MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
1212       if (dl.dylib.name < dl.cmdsize) {
1213         const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
1214         if (JustId)
1215           outs() << p << "\n";
1216         else {
1217           outs() << "\t" << p;
1218           outs() << " (compatibility version "
1219                  << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
1220                  << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
1221                  << (dl.dylib.compatibility_version & 0xff) << ",";
1222           outs() << " current version "
1223                  << ((dl.dylib.current_version >> 16) & 0xffff) << "."
1224                  << ((dl.dylib.current_version >> 8) & 0xff) << "."
1225                  << (dl.dylib.current_version & 0xff);
1226           if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
1227             outs() << ", weak";
1228           if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
1229             outs() << ", reexport";
1230           if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
1231             outs() << ", upward";
1232           if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
1233             outs() << ", lazy";
1234           outs() << ")\n";
1235         }
1236       } else {
1237         outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
1238         if (Load.C.cmd == MachO::LC_ID_DYLIB)
1239           outs() << "LC_ID_DYLIB ";
1240         else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
1241           outs() << "LC_LOAD_DYLIB ";
1242         else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
1243           outs() << "LC_LOAD_WEAK_DYLIB ";
1244         else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
1245           outs() << "LC_LAZY_LOAD_DYLIB ";
1246         else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
1247           outs() << "LC_REEXPORT_DYLIB ";
1248         else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
1249           outs() << "LC_LOAD_UPWARD_DYLIB ";
1250         else
1251           outs() << "LC_??? ";
1252         outs() << "command " << Index++ << "\n";
1253       }
1254     }
1255   }
1256 }
1257 
1258 static void printRpaths(MachOObjectFile *O) {
1259   for (const auto &Command : O->load_commands()) {
1260     if (Command.C.cmd == MachO::LC_RPATH) {
1261       auto Rpath = O->getRpathCommand(Command);
1262       const char *P = (const char *)(Command.Ptr) + Rpath.path;
1263       outs() << P << "\n";
1264     }
1265   }
1266 }
1267 
1268 typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
1269 
1270 static void CreateSymbolAddressMap(MachOObjectFile *O,
1271                                    SymbolAddressMap *AddrMap) {
1272   // Create a map of symbol addresses to symbol names.
1273   const StringRef FileName = O->getFileName();
1274   for (const SymbolRef &Symbol : O->symbols()) {
1275     SymbolRef::Type ST = unwrapOrError(Symbol.getType(), FileName);
1276     if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
1277         ST == SymbolRef::ST_Other) {
1278       uint64_t Address = cantFail(Symbol.getValue());
1279       StringRef SymName = unwrapOrError(Symbol.getName(), FileName);
1280       if (!SymName.startswith(".objc"))
1281         (*AddrMap)[Address] = SymName;
1282     }
1283   }
1284 }
1285 
1286 // GuessSymbolName is passed the address of what might be a symbol and a
1287 // pointer to the SymbolAddressMap.  It returns the name of a symbol
1288 // with that address or nullptr if no symbol is found with that address.
1289 static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
1290   const char *SymbolName = nullptr;
1291   // A DenseMap can't lookup up some values.
1292   if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
1293     StringRef name = AddrMap->lookup(value);
1294     if (!name.empty())
1295       SymbolName = name.data();
1296   }
1297   return SymbolName;
1298 }
1299 
1300 static void DumpCstringChar(const char c) {
1301   char p[2];
1302   p[0] = c;
1303   p[1] = '\0';
1304   outs().write_escaped(p);
1305 }
1306 
1307 static void DumpCstringSection(MachOObjectFile *O, const char *sect,
1308                                uint32_t sect_size, uint64_t sect_addr,
1309                                bool print_addresses) {
1310   for (uint32_t i = 0; i < sect_size; i++) {
1311     if (print_addresses) {
1312       if (O->is64Bit())
1313         outs() << format("%016" PRIx64, sect_addr + i) << "  ";
1314       else
1315         outs() << format("%08" PRIx64, sect_addr + i) << "  ";
1316     }
1317     for (; i < sect_size && sect[i] != '\0'; i++)
1318       DumpCstringChar(sect[i]);
1319     if (i < sect_size && sect[i] == '\0')
1320       outs() << "\n";
1321   }
1322 }
1323 
1324 static void DumpLiteral4(uint32_t l, float f) {
1325   outs() << format("0x%08" PRIx32, l);
1326   if ((l & 0x7f800000) != 0x7f800000)
1327     outs() << format(" (%.16e)\n", f);
1328   else {
1329     if (l == 0x7f800000)
1330       outs() << " (+Infinity)\n";
1331     else if (l == 0xff800000)
1332       outs() << " (-Infinity)\n";
1333     else if ((l & 0x00400000) == 0x00400000)
1334       outs() << " (non-signaling Not-a-Number)\n";
1335     else
1336       outs() << " (signaling Not-a-Number)\n";
1337   }
1338 }
1339 
1340 static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
1341                                 uint32_t sect_size, uint64_t sect_addr,
1342                                 bool print_addresses) {
1343   for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
1344     if (print_addresses) {
1345       if (O->is64Bit())
1346         outs() << format("%016" PRIx64, sect_addr + i) << "  ";
1347       else
1348         outs() << format("%08" PRIx64, sect_addr + i) << "  ";
1349     }
1350     float f;
1351     memcpy(&f, sect + i, sizeof(float));
1352     if (O->isLittleEndian() != sys::IsLittleEndianHost)
1353       sys::swapByteOrder(f);
1354     uint32_t l;
1355     memcpy(&l, sect + i, sizeof(uint32_t));
1356     if (O->isLittleEndian() != sys::IsLittleEndianHost)
1357       sys::swapByteOrder(l);
1358     DumpLiteral4(l, f);
1359   }
1360 }
1361 
1362 static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
1363                          double d) {
1364   outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
1365   uint32_t Hi, Lo;
1366   Hi = (O->isLittleEndian()) ? l1 : l0;
1367   Lo = (O->isLittleEndian()) ? l0 : l1;
1368 
1369   // Hi is the high word, so this is equivalent to if(isfinite(d))
1370   if ((Hi & 0x7ff00000) != 0x7ff00000)
1371     outs() << format(" (%.16e)\n", d);
1372   else {
1373     if (Hi == 0x7ff00000 && Lo == 0)
1374       outs() << " (+Infinity)\n";
1375     else if (Hi == 0xfff00000 && Lo == 0)
1376       outs() << " (-Infinity)\n";
1377     else if ((Hi & 0x00080000) == 0x00080000)
1378       outs() << " (non-signaling Not-a-Number)\n";
1379     else
1380       outs() << " (signaling Not-a-Number)\n";
1381   }
1382 }
1383 
1384 static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
1385                                 uint32_t sect_size, uint64_t sect_addr,
1386                                 bool print_addresses) {
1387   for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
1388     if (print_addresses) {
1389       if (O->is64Bit())
1390         outs() << format("%016" PRIx64, sect_addr + i) << "  ";
1391       else
1392         outs() << format("%08" PRIx64, sect_addr + i) << "  ";
1393     }
1394     double d;
1395     memcpy(&d, sect + i, sizeof(double));
1396     if (O->isLittleEndian() != sys::IsLittleEndianHost)
1397       sys::swapByteOrder(d);
1398     uint32_t l0, l1;
1399     memcpy(&l0, sect + i, sizeof(uint32_t));
1400     memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
1401     if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1402       sys::swapByteOrder(l0);
1403       sys::swapByteOrder(l1);
1404     }
1405     DumpLiteral8(O, l0, l1, d);
1406   }
1407 }
1408 
1409 static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
1410   outs() << format("0x%08" PRIx32, l0) << " ";
1411   outs() << format("0x%08" PRIx32, l1) << " ";
1412   outs() << format("0x%08" PRIx32, l2) << " ";
1413   outs() << format("0x%08" PRIx32, l3) << "\n";
1414 }
1415 
1416 static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
1417                                  uint32_t sect_size, uint64_t sect_addr,
1418                                  bool print_addresses) {
1419   for (uint32_t i = 0; i < sect_size; i += 16) {
1420     if (print_addresses) {
1421       if (O->is64Bit())
1422         outs() << format("%016" PRIx64, sect_addr + i) << "  ";
1423       else
1424         outs() << format("%08" PRIx64, sect_addr + i) << "  ";
1425     }
1426     uint32_t l0, l1, l2, l3;
1427     memcpy(&l0, sect + i, sizeof(uint32_t));
1428     memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
1429     memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
1430     memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
1431     if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1432       sys::swapByteOrder(l0);
1433       sys::swapByteOrder(l1);
1434       sys::swapByteOrder(l2);
1435       sys::swapByteOrder(l3);
1436     }
1437     DumpLiteral16(l0, l1, l2, l3);
1438   }
1439 }
1440 
1441 static void DumpLiteralPointerSection(MachOObjectFile *O,
1442                                       const SectionRef &Section,
1443                                       const char *sect, uint32_t sect_size,
1444                                       uint64_t sect_addr,
1445                                       bool print_addresses) {
1446   // Collect the literal sections in this Mach-O file.
1447   std::vector<SectionRef> LiteralSections;
1448   for (const SectionRef &Section : O->sections()) {
1449     DataRefImpl Ref = Section.getRawDataRefImpl();
1450     uint32_t section_type;
1451     if (O->is64Bit()) {
1452       const MachO::section_64 Sec = O->getSection64(Ref);
1453       section_type = Sec.flags & MachO::SECTION_TYPE;
1454     } else {
1455       const MachO::section Sec = O->getSection(Ref);
1456       section_type = Sec.flags & MachO::SECTION_TYPE;
1457     }
1458     if (section_type == MachO::S_CSTRING_LITERALS ||
1459         section_type == MachO::S_4BYTE_LITERALS ||
1460         section_type == MachO::S_8BYTE_LITERALS ||
1461         section_type == MachO::S_16BYTE_LITERALS)
1462       LiteralSections.push_back(Section);
1463   }
1464 
1465   // Set the size of the literal pointer.
1466   uint32_t lp_size = O->is64Bit() ? 8 : 4;
1467 
1468   // Collect the external relocation symbols for the literal pointers.
1469   std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1470   for (const RelocationRef &Reloc : Section.relocations()) {
1471     DataRefImpl Rel;
1472     MachO::any_relocation_info RE;
1473     bool isExtern = false;
1474     Rel = Reloc.getRawDataRefImpl();
1475     RE = O->getRelocation(Rel);
1476     isExtern = O->getPlainRelocationExternal(RE);
1477     if (isExtern) {
1478       uint64_t RelocOffset = Reloc.getOffset();
1479       symbol_iterator RelocSym = Reloc.getSymbol();
1480       Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
1481     }
1482   }
1483   array_pod_sort(Relocs.begin(), Relocs.end());
1484 
1485   // Dump each literal pointer.
1486   for (uint32_t i = 0; i < sect_size; i += lp_size) {
1487     if (print_addresses) {
1488       if (O->is64Bit())
1489         outs() << format("%016" PRIx64, sect_addr + i) << "  ";
1490       else
1491         outs() << format("%08" PRIx64, sect_addr + i) << "  ";
1492     }
1493     uint64_t lp;
1494     if (O->is64Bit()) {
1495       memcpy(&lp, sect + i, sizeof(uint64_t));
1496       if (O->isLittleEndian() != sys::IsLittleEndianHost)
1497         sys::swapByteOrder(lp);
1498     } else {
1499       uint32_t li;
1500       memcpy(&li, sect + i, sizeof(uint32_t));
1501       if (O->isLittleEndian() != sys::IsLittleEndianHost)
1502         sys::swapByteOrder(li);
1503       lp = li;
1504     }
1505 
1506     // First look for an external relocation entry for this literal pointer.
1507     auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
1508       return P.first == i;
1509     });
1510     if (Reloc != Relocs.end()) {
1511       symbol_iterator RelocSym = Reloc->second;
1512       StringRef SymName = unwrapOrError(RelocSym->getName(), O->getFileName());
1513       outs() << "external relocation entry for symbol:" << SymName << "\n";
1514       continue;
1515     }
1516 
1517     // For local references see what the section the literal pointer points to.
1518     auto Sect = find_if(LiteralSections, [&](const SectionRef &R) {
1519       return lp >= R.getAddress() && lp < R.getAddress() + R.getSize();
1520     });
1521     if (Sect == LiteralSections.end()) {
1522       outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
1523       continue;
1524     }
1525 
1526     uint64_t SectAddress = Sect->getAddress();
1527     uint64_t SectSize = Sect->getSize();
1528 
1529     StringRef SectName;
1530     Expected<StringRef> SectNameOrErr = Sect->getName();
1531     if (SectNameOrErr)
1532       SectName = *SectNameOrErr;
1533     else
1534       consumeError(SectNameOrErr.takeError());
1535 
1536     DataRefImpl Ref = Sect->getRawDataRefImpl();
1537     StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
1538     outs() << SegmentName << ":" << SectName << ":";
1539 
1540     uint32_t section_type;
1541     if (O->is64Bit()) {
1542       const MachO::section_64 Sec = O->getSection64(Ref);
1543       section_type = Sec.flags & MachO::SECTION_TYPE;
1544     } else {
1545       const MachO::section Sec = O->getSection(Ref);
1546       section_type = Sec.flags & MachO::SECTION_TYPE;
1547     }
1548 
1549     StringRef BytesStr = unwrapOrError(Sect->getContents(), O->getFileName());
1550 
1551     const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
1552 
1553     switch (section_type) {
1554     case MachO::S_CSTRING_LITERALS:
1555       for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
1556            i++) {
1557         DumpCstringChar(Contents[i]);
1558       }
1559       outs() << "\n";
1560       break;
1561     case MachO::S_4BYTE_LITERALS:
1562       float f;
1563       memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
1564       uint32_t l;
1565       memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
1566       if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1567         sys::swapByteOrder(f);
1568         sys::swapByteOrder(l);
1569       }
1570       DumpLiteral4(l, f);
1571       break;
1572     case MachO::S_8BYTE_LITERALS: {
1573       double d;
1574       memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
1575       uint32_t l0, l1;
1576       memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
1577       memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
1578              sizeof(uint32_t));
1579       if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1580         sys::swapByteOrder(f);
1581         sys::swapByteOrder(l0);
1582         sys::swapByteOrder(l1);
1583       }
1584       DumpLiteral8(O, l0, l1, d);
1585       break;
1586     }
1587     case MachO::S_16BYTE_LITERALS: {
1588       uint32_t l0, l1, l2, l3;
1589       memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
1590       memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
1591              sizeof(uint32_t));
1592       memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
1593              sizeof(uint32_t));
1594       memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
1595              sizeof(uint32_t));
1596       if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1597         sys::swapByteOrder(l0);
1598         sys::swapByteOrder(l1);
1599         sys::swapByteOrder(l2);
1600         sys::swapByteOrder(l3);
1601       }
1602       DumpLiteral16(l0, l1, l2, l3);
1603       break;
1604     }
1605     }
1606   }
1607 }
1608 
1609 static void DumpInitTermPointerSection(MachOObjectFile *O,
1610                                        const SectionRef &Section,
1611                                        const char *sect,
1612                                        uint32_t sect_size, uint64_t sect_addr,
1613                                        SymbolAddressMap *AddrMap,
1614                                        bool verbose) {
1615   uint32_t stride;
1616   stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t);
1617 
1618   // Collect the external relocation symbols for the pointers.
1619   std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1620   for (const RelocationRef &Reloc : Section.relocations()) {
1621     DataRefImpl Rel;
1622     MachO::any_relocation_info RE;
1623     bool isExtern = false;
1624     Rel = Reloc.getRawDataRefImpl();
1625     RE = O->getRelocation(Rel);
1626     isExtern = O->getPlainRelocationExternal(RE);
1627     if (isExtern) {
1628       uint64_t RelocOffset = Reloc.getOffset();
1629       symbol_iterator RelocSym = Reloc.getSymbol();
1630       Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
1631     }
1632   }
1633   array_pod_sort(Relocs.begin(), Relocs.end());
1634 
1635   for (uint32_t i = 0; i < sect_size; i += stride) {
1636     const char *SymbolName = nullptr;
1637     uint64_t p;
1638     if (O->is64Bit()) {
1639       outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
1640       uint64_t pointer_value;
1641       memcpy(&pointer_value, sect + i, stride);
1642       if (O->isLittleEndian() != sys::IsLittleEndianHost)
1643         sys::swapByteOrder(pointer_value);
1644       outs() << format("0x%016" PRIx64, pointer_value);
1645       p = pointer_value;
1646     } else {
1647       outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
1648       uint32_t pointer_value;
1649       memcpy(&pointer_value, sect + i, stride);
1650       if (O->isLittleEndian() != sys::IsLittleEndianHost)
1651         sys::swapByteOrder(pointer_value);
1652       outs() << format("0x%08" PRIx32, pointer_value);
1653       p = pointer_value;
1654     }
1655     if (verbose) {
1656       // First look for an external relocation entry for this pointer.
1657       auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
1658         return P.first == i;
1659       });
1660       if (Reloc != Relocs.end()) {
1661         symbol_iterator RelocSym = Reloc->second;
1662         outs() << " " << unwrapOrError(RelocSym->getName(), O->getFileName());
1663       } else {
1664         SymbolName = GuessSymbolName(p, AddrMap);
1665         if (SymbolName)
1666           outs() << " " << SymbolName;
1667       }
1668     }
1669     outs() << "\n";
1670   }
1671 }
1672 
1673 static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
1674                                    uint32_t size, uint64_t addr) {
1675   uint32_t cputype = O->getHeader().cputype;
1676   if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
1677     uint32_t j;
1678     for (uint32_t i = 0; i < size; i += j, addr += j) {
1679       if (O->is64Bit())
1680         outs() << format("%016" PRIx64, addr) << "\t";
1681       else
1682         outs() << format("%08" PRIx64, addr) << "\t";
1683       for (j = 0; j < 16 && i + j < size; j++) {
1684         uint8_t byte_word = *(sect + i + j);
1685         outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1686       }
1687       outs() << "\n";
1688     }
1689   } else {
1690     uint32_t j;
1691     for (uint32_t i = 0; i < size; i += j, addr += j) {
1692       if (O->is64Bit())
1693         outs() << format("%016" PRIx64, addr) << "\t";
1694       else
1695         outs() << format("%08" PRIx64, addr) << "\t";
1696       for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
1697            j += sizeof(int32_t)) {
1698         if (i + j + sizeof(int32_t) <= size) {
1699           uint32_t long_word;
1700           memcpy(&long_word, sect + i + j, sizeof(int32_t));
1701           if (O->isLittleEndian() != sys::IsLittleEndianHost)
1702             sys::swapByteOrder(long_word);
1703           outs() << format("%08" PRIx32, long_word) << " ";
1704         } else {
1705           for (uint32_t k = 0; i + j + k < size; k++) {
1706             uint8_t byte_word = *(sect + i + j + k);
1707             outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1708           }
1709         }
1710       }
1711       outs() << "\n";
1712     }
1713   }
1714 }
1715 
1716 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
1717                              StringRef DisSegName, StringRef DisSectName);
1718 static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
1719                                 uint32_t size, uint32_t addr);
1720 #ifdef LLVM_HAVE_LIBXAR
1721 static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
1722                                 uint32_t size, bool verbose,
1723                                 bool PrintXarHeader, bool PrintXarFileHeaders,
1724                                 std::string XarMemberName);
1725 #endif // defined(LLVM_HAVE_LIBXAR)
1726 
1727 static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
1728                                 bool verbose) {
1729   SymbolAddressMap AddrMap;
1730   if (verbose)
1731     CreateSymbolAddressMap(O, &AddrMap);
1732 
1733   for (unsigned i = 0; i < FilterSections.size(); ++i) {
1734     StringRef DumpSection = FilterSections[i];
1735     std::pair<StringRef, StringRef> DumpSegSectName;
1736     DumpSegSectName = DumpSection.split(',');
1737     StringRef DumpSegName, DumpSectName;
1738     if (!DumpSegSectName.second.empty()) {
1739       DumpSegName = DumpSegSectName.first;
1740       DumpSectName = DumpSegSectName.second;
1741     } else {
1742       DumpSegName = "";
1743       DumpSectName = DumpSegSectName.first;
1744     }
1745     for (const SectionRef &Section : O->sections()) {
1746       StringRef SectName;
1747       Expected<StringRef> SecNameOrErr = Section.getName();
1748       if (SecNameOrErr)
1749         SectName = *SecNameOrErr;
1750       else
1751         consumeError(SecNameOrErr.takeError());
1752 
1753       if (!DumpSection.empty())
1754         FoundSectionSet.insert(DumpSection);
1755 
1756       DataRefImpl Ref = Section.getRawDataRefImpl();
1757       StringRef SegName = O->getSectionFinalSegmentName(Ref);
1758       if ((DumpSegName.empty() || SegName == DumpSegName) &&
1759           (SectName == DumpSectName)) {
1760 
1761         uint32_t section_flags;
1762         if (O->is64Bit()) {
1763           const MachO::section_64 Sec = O->getSection64(Ref);
1764           section_flags = Sec.flags;
1765 
1766         } else {
1767           const MachO::section Sec = O->getSection(Ref);
1768           section_flags = Sec.flags;
1769         }
1770         uint32_t section_type = section_flags & MachO::SECTION_TYPE;
1771 
1772         StringRef BytesStr =
1773             unwrapOrError(Section.getContents(), O->getFileName());
1774         const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1775         uint32_t sect_size = BytesStr.size();
1776         uint64_t sect_addr = Section.getAddress();
1777 
1778         if (LeadingHeaders)
1779           outs() << "Contents of (" << SegName << "," << SectName
1780                  << ") section\n";
1781 
1782         if (verbose) {
1783           if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1784               (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1785             DisassembleMachO(Filename, O, SegName, SectName);
1786             continue;
1787           }
1788           if (SegName == "__TEXT" && SectName == "__info_plist") {
1789             outs() << sect;
1790             continue;
1791           }
1792           if (SegName == "__OBJC" && SectName == "__protocol") {
1793             DumpProtocolSection(O, sect, sect_size, sect_addr);
1794             continue;
1795           }
1796 #ifdef LLVM_HAVE_LIBXAR
1797           if (SegName == "__LLVM" && SectName == "__bundle") {
1798             DumpBitcodeSection(O, sect, sect_size, verbose, SymbolicOperands,
1799                                ArchiveHeaders, "");
1800             continue;
1801           }
1802 #endif // defined(LLVM_HAVE_LIBXAR)
1803           switch (section_type) {
1804           case MachO::S_REGULAR:
1805             DumpRawSectionContents(O, sect, sect_size, sect_addr);
1806             break;
1807           case MachO::S_ZEROFILL:
1808             outs() << "zerofill section and has no contents in the file\n";
1809             break;
1810           case MachO::S_CSTRING_LITERALS:
1811             DumpCstringSection(O, sect, sect_size, sect_addr, LeadingAddr);
1812             break;
1813           case MachO::S_4BYTE_LITERALS:
1814             DumpLiteral4Section(O, sect, sect_size, sect_addr, LeadingAddr);
1815             break;
1816           case MachO::S_8BYTE_LITERALS:
1817             DumpLiteral8Section(O, sect, sect_size, sect_addr, LeadingAddr);
1818             break;
1819           case MachO::S_16BYTE_LITERALS:
1820             DumpLiteral16Section(O, sect, sect_size, sect_addr, LeadingAddr);
1821             break;
1822           case MachO::S_LITERAL_POINTERS:
1823             DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
1824                                       LeadingAddr);
1825             break;
1826           case MachO::S_MOD_INIT_FUNC_POINTERS:
1827           case MachO::S_MOD_TERM_FUNC_POINTERS:
1828             DumpInitTermPointerSection(O, Section, sect, sect_size, sect_addr,
1829                                        &AddrMap, verbose);
1830             break;
1831           default:
1832             outs() << "Unknown section type ("
1833                    << format("0x%08" PRIx32, section_type) << ")\n";
1834             DumpRawSectionContents(O, sect, sect_size, sect_addr);
1835             break;
1836           }
1837         } else {
1838           if (section_type == MachO::S_ZEROFILL)
1839             outs() << "zerofill section and has no contents in the file\n";
1840           else
1841             DumpRawSectionContents(O, sect, sect_size, sect_addr);
1842         }
1843       }
1844     }
1845   }
1846 }
1847 
1848 static void DumpInfoPlistSectionContents(StringRef Filename,
1849                                          MachOObjectFile *O) {
1850   for (const SectionRef &Section : O->sections()) {
1851     StringRef SectName;
1852     Expected<StringRef> SecNameOrErr = Section.getName();
1853     if (SecNameOrErr)
1854       SectName = *SecNameOrErr;
1855     else
1856       consumeError(SecNameOrErr.takeError());
1857 
1858     DataRefImpl Ref = Section.getRawDataRefImpl();
1859     StringRef SegName = O->getSectionFinalSegmentName(Ref);
1860     if (SegName == "__TEXT" && SectName == "__info_plist") {
1861       if (LeadingHeaders)
1862         outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
1863       StringRef BytesStr =
1864           unwrapOrError(Section.getContents(), O->getFileName());
1865       const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1866       outs() << format("%.*s", BytesStr.size(), sect) << "\n";
1867       return;
1868     }
1869   }
1870 }
1871 
1872 // checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1873 // and if it is and there is a list of architecture flags is specified then
1874 // check to make sure this Mach-O file is one of those architectures or all
1875 // architectures were specified.  If not then an error is generated and this
1876 // routine returns false.  Else it returns true.
1877 static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
1878   auto *MachO = dyn_cast<MachOObjectFile>(O);
1879 
1880   if (!MachO || ArchAll || ArchFlags.empty())
1881     return true;
1882 
1883   MachO::mach_header H;
1884   MachO::mach_header_64 H_64;
1885   Triple T;
1886   const char *McpuDefault, *ArchFlag;
1887   if (MachO->is64Bit()) {
1888     H_64 = MachO->MachOObjectFile::getHeader64();
1889     T = MachOObjectFile::getArchTriple(H_64.cputype, H_64.cpusubtype,
1890                                        &McpuDefault, &ArchFlag);
1891   } else {
1892     H = MachO->MachOObjectFile::getHeader();
1893     T = MachOObjectFile::getArchTriple(H.cputype, H.cpusubtype,
1894                                        &McpuDefault, &ArchFlag);
1895   }
1896   const std::string ArchFlagName(ArchFlag);
1897   if (!llvm::is_contained(ArchFlags, ArchFlagName)) {
1898     WithColor::error(errs(), "llvm-objdump")
1899         << Filename << ": no architecture specified.\n";
1900     return false;
1901   }
1902   return true;
1903 }
1904 
1905 static void printObjcMetaData(MachOObjectFile *O, bool verbose);
1906 
1907 // ProcessMachO() is passed a single opened Mach-O file, which may be an
1908 // archive member and or in a slice of a universal file.  It prints the
1909 // the file name and header info and then processes it according to the
1910 // command line options.
1911 static void ProcessMachO(StringRef Name, MachOObjectFile *MachOOF,
1912                          StringRef ArchiveMemberName = StringRef(),
1913                          StringRef ArchitectureName = StringRef()) {
1914   // If we are doing some processing here on the Mach-O file print the header
1915   // info.  And don't print it otherwise like in the case of printing the
1916   // UniversalHeaders or ArchiveHeaders.
1917   if (Disassemble || Relocations || PrivateHeaders || ExportsTrie || Rebase ||
1918       Bind || SymbolTable || LazyBind || WeakBind || IndirectSymbols ||
1919       DataInCode || FunctionStarts || LinkOptHints || DyldInfo || DylibsUsed ||
1920       DylibId || Rpaths || ObjcMetaData || (!FilterSections.empty())) {
1921     if (LeadingHeaders) {
1922       outs() << Name;
1923       if (!ArchiveMemberName.empty())
1924         outs() << '(' << ArchiveMemberName << ')';
1925       if (!ArchitectureName.empty())
1926         outs() << " (architecture " << ArchitectureName << ")";
1927       outs() << ":\n";
1928     }
1929   }
1930   // To use the report_error() form with an ArchiveName and FileName set
1931   // these up based on what is passed for Name and ArchiveMemberName.
1932   StringRef ArchiveName;
1933   StringRef FileName;
1934   if (!ArchiveMemberName.empty()) {
1935     ArchiveName = Name;
1936     FileName = ArchiveMemberName;
1937   } else {
1938     ArchiveName = StringRef();
1939     FileName = Name;
1940   }
1941 
1942   // If we need the symbol table to do the operation then check it here to
1943   // produce a good error message as to where the Mach-O file comes from in
1944   // the error message.
1945   if (Disassemble || IndirectSymbols || !FilterSections.empty() || UnwindInfo)
1946     if (Error Err = MachOOF->checkSymbolTable())
1947       reportError(std::move(Err), FileName, ArchiveName, ArchitectureName);
1948 
1949   if (DisassembleAll) {
1950     for (const SectionRef &Section : MachOOF->sections()) {
1951       StringRef SectName;
1952       if (Expected<StringRef> NameOrErr = Section.getName())
1953         SectName = *NameOrErr;
1954       else
1955         consumeError(NameOrErr.takeError());
1956 
1957       if (SectName.equals("__text")) {
1958         DataRefImpl Ref = Section.getRawDataRefImpl();
1959         StringRef SegName = MachOOF->getSectionFinalSegmentName(Ref);
1960         DisassembleMachO(FileName, MachOOF, SegName, SectName);
1961       }
1962     }
1963   }
1964   else if (Disassemble) {
1965     if (MachOOF->getHeader().filetype == MachO::MH_KEXT_BUNDLE &&
1966         MachOOF->getHeader().cputype == MachO::CPU_TYPE_ARM64)
1967       DisassembleMachO(FileName, MachOOF, "__TEXT_EXEC", "__text");
1968     else
1969       DisassembleMachO(FileName, MachOOF, "__TEXT", "__text");
1970   }
1971   if (IndirectSymbols)
1972     PrintIndirectSymbols(MachOOF, Verbose);
1973   if (DataInCode)
1974     PrintDataInCodeTable(MachOOF, Verbose);
1975   if (FunctionStarts)
1976     PrintFunctionStarts(MachOOF);
1977   if (LinkOptHints)
1978     PrintLinkOptHints(MachOOF);
1979   if (Relocations)
1980     PrintRelocations(MachOOF, Verbose);
1981   if (SectionHeaders)
1982     printSectionHeaders(*MachOOF);
1983   if (SectionContents)
1984     printSectionContents(MachOOF);
1985   if (!FilterSections.empty())
1986     DumpSectionContents(FileName, MachOOF, Verbose);
1987   if (InfoPlist)
1988     DumpInfoPlistSectionContents(FileName, MachOOF);
1989   if (DyldInfo)
1990     PrintDyldInfo(MachOOF);
1991   if (DylibsUsed)
1992     PrintDylibs(MachOOF, false);
1993   if (DylibId)
1994     PrintDylibs(MachOOF, true);
1995   if (SymbolTable)
1996     printSymbolTable(*MachOOF, ArchiveName, ArchitectureName);
1997   if (UnwindInfo)
1998     printMachOUnwindInfo(MachOOF);
1999   if (PrivateHeaders) {
2000     printMachOFileHeader(MachOOF);
2001     printMachOLoadCommands(MachOOF);
2002   }
2003   if (FirstPrivateHeader)
2004     printMachOFileHeader(MachOOF);
2005   if (ObjcMetaData)
2006     printObjcMetaData(MachOOF, Verbose);
2007   if (ExportsTrie)
2008     printExportsTrie(MachOOF);
2009   if (Rebase)
2010     printRebaseTable(MachOOF);
2011   if (Rpaths)
2012     printRpaths(MachOOF);
2013   if (Bind)
2014     printBindTable(MachOOF);
2015   if (LazyBind)
2016     printLazyBindTable(MachOOF);
2017   if (WeakBind)
2018     printWeakBindTable(MachOOF);
2019 
2020   if (DwarfDumpType != DIDT_Null) {
2021     std::unique_ptr<DIContext> DICtx = DWARFContext::create(*MachOOF);
2022     // Dump the complete DWARF structure.
2023     DIDumpOptions DumpOpts;
2024     DumpOpts.DumpType = DwarfDumpType;
2025     DICtx->dump(outs(), DumpOpts);
2026   }
2027 }
2028 
2029 // printUnknownCPUType() helps print_fat_headers for unknown CPU's.
2030 static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
2031   outs() << "    cputype (" << cputype << ")\n";
2032   outs() << "    cpusubtype (" << cpusubtype << ")\n";
2033 }
2034 
2035 // printCPUType() helps print_fat_headers by printing the cputype and
2036 // pusubtype (symbolically for the one's it knows about).
2037 static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
2038   switch (cputype) {
2039   case MachO::CPU_TYPE_I386:
2040     switch (cpusubtype) {
2041     case MachO::CPU_SUBTYPE_I386_ALL:
2042       outs() << "    cputype CPU_TYPE_I386\n";
2043       outs() << "    cpusubtype CPU_SUBTYPE_I386_ALL\n";
2044       break;
2045     default:
2046       printUnknownCPUType(cputype, cpusubtype);
2047       break;
2048     }
2049     break;
2050   case MachO::CPU_TYPE_X86_64:
2051     switch (cpusubtype) {
2052     case MachO::CPU_SUBTYPE_X86_64_ALL:
2053       outs() << "    cputype CPU_TYPE_X86_64\n";
2054       outs() << "    cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
2055       break;
2056     case MachO::CPU_SUBTYPE_X86_64_H:
2057       outs() << "    cputype CPU_TYPE_X86_64\n";
2058       outs() << "    cpusubtype CPU_SUBTYPE_X86_64_H\n";
2059       break;
2060     default:
2061       printUnknownCPUType(cputype, cpusubtype);
2062       break;
2063     }
2064     break;
2065   case MachO::CPU_TYPE_ARM:
2066     switch (cpusubtype) {
2067     case MachO::CPU_SUBTYPE_ARM_ALL:
2068       outs() << "    cputype CPU_TYPE_ARM\n";
2069       outs() << "    cpusubtype CPU_SUBTYPE_ARM_ALL\n";
2070       break;
2071     case MachO::CPU_SUBTYPE_ARM_V4T:
2072       outs() << "    cputype CPU_TYPE_ARM\n";
2073       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V4T\n";
2074       break;
2075     case MachO::CPU_SUBTYPE_ARM_V5TEJ:
2076       outs() << "    cputype CPU_TYPE_ARM\n";
2077       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
2078       break;
2079     case MachO::CPU_SUBTYPE_ARM_XSCALE:
2080       outs() << "    cputype CPU_TYPE_ARM\n";
2081       outs() << "    cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
2082       break;
2083     case MachO::CPU_SUBTYPE_ARM_V6:
2084       outs() << "    cputype CPU_TYPE_ARM\n";
2085       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V6\n";
2086       break;
2087     case MachO::CPU_SUBTYPE_ARM_V6M:
2088       outs() << "    cputype CPU_TYPE_ARM\n";
2089       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V6M\n";
2090       break;
2091     case MachO::CPU_SUBTYPE_ARM_V7:
2092       outs() << "    cputype CPU_TYPE_ARM\n";
2093       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V7\n";
2094       break;
2095     case MachO::CPU_SUBTYPE_ARM_V7EM:
2096       outs() << "    cputype CPU_TYPE_ARM\n";
2097       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
2098       break;
2099     case MachO::CPU_SUBTYPE_ARM_V7K:
2100       outs() << "    cputype CPU_TYPE_ARM\n";
2101       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V7K\n";
2102       break;
2103     case MachO::CPU_SUBTYPE_ARM_V7M:
2104       outs() << "    cputype CPU_TYPE_ARM\n";
2105       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V7M\n";
2106       break;
2107     case MachO::CPU_SUBTYPE_ARM_V7S:
2108       outs() << "    cputype CPU_TYPE_ARM\n";
2109       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V7S\n";
2110       break;
2111     default:
2112       printUnknownCPUType(cputype, cpusubtype);
2113       break;
2114     }
2115     break;
2116   case MachO::CPU_TYPE_ARM64:
2117     switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2118     case MachO::CPU_SUBTYPE_ARM64_ALL:
2119       outs() << "    cputype CPU_TYPE_ARM64\n";
2120       outs() << "    cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
2121       break;
2122     case MachO::CPU_SUBTYPE_ARM64_V8:
2123       outs() << "    cputype CPU_TYPE_ARM64\n";
2124       outs() << "    cpusubtype CPU_SUBTYPE_ARM64_V8\n";
2125       break;
2126     case MachO::CPU_SUBTYPE_ARM64E:
2127       outs() << "    cputype CPU_TYPE_ARM64\n";
2128       outs() << "    cpusubtype CPU_SUBTYPE_ARM64E\n";
2129       break;
2130     default:
2131       printUnknownCPUType(cputype, cpusubtype);
2132       break;
2133     }
2134     break;
2135   case MachO::CPU_TYPE_ARM64_32:
2136     switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2137     case MachO::CPU_SUBTYPE_ARM64_32_V8:
2138       outs() << "    cputype CPU_TYPE_ARM64_32\n";
2139       outs() << "    cpusubtype CPU_SUBTYPE_ARM64_32_V8\n";
2140       break;
2141     default:
2142       printUnknownCPUType(cputype, cpusubtype);
2143       break;
2144     }
2145     break;
2146   default:
2147     printUnknownCPUType(cputype, cpusubtype);
2148     break;
2149   }
2150 }
2151 
2152 static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
2153                                        bool verbose) {
2154   outs() << "Fat headers\n";
2155   if (verbose) {
2156     if (UB->getMagic() == MachO::FAT_MAGIC)
2157       outs() << "fat_magic FAT_MAGIC\n";
2158     else // UB->getMagic() == MachO::FAT_MAGIC_64
2159       outs() << "fat_magic FAT_MAGIC_64\n";
2160   } else
2161     outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
2162 
2163   uint32_t nfat_arch = UB->getNumberOfObjects();
2164   StringRef Buf = UB->getData();
2165   uint64_t size = Buf.size();
2166   uint64_t big_size = sizeof(struct MachO::fat_header) +
2167                       nfat_arch * sizeof(struct MachO::fat_arch);
2168   outs() << "nfat_arch " << UB->getNumberOfObjects();
2169   if (nfat_arch == 0)
2170     outs() << " (malformed, contains zero architecture types)\n";
2171   else if (big_size > size)
2172     outs() << " (malformed, architectures past end of file)\n";
2173   else
2174     outs() << "\n";
2175 
2176   for (uint32_t i = 0; i < nfat_arch; ++i) {
2177     MachOUniversalBinary::ObjectForArch OFA(UB, i);
2178     uint32_t cputype = OFA.getCPUType();
2179     uint32_t cpusubtype = OFA.getCPUSubType();
2180     outs() << "architecture ";
2181     for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
2182       MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
2183       uint32_t other_cputype = other_OFA.getCPUType();
2184       uint32_t other_cpusubtype = other_OFA.getCPUSubType();
2185       if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
2186           (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
2187               (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
2188         outs() << "(illegal duplicate architecture) ";
2189         break;
2190       }
2191     }
2192     if (verbose) {
2193       outs() << OFA.getArchFlagName() << "\n";
2194       printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2195     } else {
2196       outs() << i << "\n";
2197       outs() << "    cputype " << cputype << "\n";
2198       outs() << "    cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
2199              << "\n";
2200     }
2201     if (verbose &&
2202         (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
2203       outs() << "    capabilities CPU_SUBTYPE_LIB64\n";
2204     else
2205       outs() << "    capabilities "
2206              << format("0x%" PRIx32,
2207                        (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
2208     outs() << "    offset " << OFA.getOffset();
2209     if (OFA.getOffset() > size)
2210       outs() << " (past end of file)";
2211     if (OFA.getOffset() % (1ull << OFA.getAlign()) != 0)
2212       outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
2213     outs() << "\n";
2214     outs() << "    size " << OFA.getSize();
2215     big_size = OFA.getOffset() + OFA.getSize();
2216     if (big_size > size)
2217       outs() << " (past end of file)";
2218     outs() << "\n";
2219     outs() << "    align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
2220            << ")\n";
2221   }
2222 }
2223 
2224 static void printArchiveChild(StringRef Filename, const Archive::Child &C,
2225                               size_t ChildIndex, bool verbose,
2226                               bool print_offset,
2227                               StringRef ArchitectureName = StringRef()) {
2228   if (print_offset)
2229     outs() << C.getChildOffset() << "\t";
2230   sys::fs::perms Mode =
2231       unwrapOrError(C.getAccessMode(), getFileNameForError(C, ChildIndex),
2232                     Filename, ArchitectureName);
2233   if (verbose) {
2234     // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
2235     // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
2236     outs() << "-";
2237     outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
2238     outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
2239     outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
2240     outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
2241     outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
2242     outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
2243     outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
2244     outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
2245     outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
2246   } else {
2247     outs() << format("0%o ", Mode);
2248   }
2249 
2250   outs() << format("%3d/%-3d %5" PRId64 " ",
2251                    unwrapOrError(C.getUID(), getFileNameForError(C, ChildIndex),
2252                                  Filename, ArchitectureName),
2253                    unwrapOrError(C.getGID(), getFileNameForError(C, ChildIndex),
2254                                  Filename, ArchitectureName),
2255                    unwrapOrError(C.getRawSize(),
2256                                  getFileNameForError(C, ChildIndex), Filename,
2257                                  ArchitectureName));
2258 
2259   StringRef RawLastModified = C.getRawLastModified();
2260   if (verbose) {
2261     unsigned Seconds;
2262     if (RawLastModified.getAsInteger(10, Seconds))
2263       outs() << "(date: \"" << RawLastModified
2264              << "\" contains non-decimal chars) ";
2265     else {
2266       // Since cime(3) returns a 26 character string of the form:
2267       // "Sun Sep 16 01:03:52 1973\n\0"
2268       // just print 24 characters.
2269       time_t t = Seconds;
2270       outs() << format("%.24s ", ctime(&t));
2271     }
2272   } else {
2273     outs() << RawLastModified << " ";
2274   }
2275 
2276   if (verbose) {
2277     Expected<StringRef> NameOrErr = C.getName();
2278     if (!NameOrErr) {
2279       consumeError(NameOrErr.takeError());
2280       outs() << unwrapOrError(C.getRawName(),
2281                               getFileNameForError(C, ChildIndex), Filename,
2282                               ArchitectureName)
2283              << "\n";
2284     } else {
2285       StringRef Name = NameOrErr.get();
2286       outs() << Name << "\n";
2287     }
2288   } else {
2289     outs() << unwrapOrError(C.getRawName(), getFileNameForError(C, ChildIndex),
2290                             Filename, ArchitectureName)
2291            << "\n";
2292   }
2293 }
2294 
2295 static void printArchiveHeaders(StringRef Filename, Archive *A, bool verbose,
2296                                 bool print_offset,
2297                                 StringRef ArchitectureName = StringRef()) {
2298   Error Err = Error::success();
2299   size_t I = 0;
2300   for (const auto &C : A->children(Err, false))
2301     printArchiveChild(Filename, C, I++, verbose, print_offset,
2302                       ArchitectureName);
2303 
2304   if (Err)
2305     reportError(std::move(Err), Filename, "", ArchitectureName);
2306 }
2307 
2308 static bool ValidateArchFlags() {
2309   // Check for -arch all and verifiy the -arch flags are valid.
2310   for (unsigned i = 0; i < ArchFlags.size(); ++i) {
2311     if (ArchFlags[i] == "all") {
2312       ArchAll = true;
2313     } else {
2314       if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
2315         WithColor::error(errs(), "llvm-objdump")
2316             << "unknown architecture named '" + ArchFlags[i] +
2317                    "'for the -arch option\n";
2318         return false;
2319       }
2320     }
2321   }
2322   return true;
2323 }
2324 
2325 // ParseInputMachO() parses the named Mach-O file in Filename and handles the
2326 // -arch flags selecting just those slices as specified by them and also parses
2327 // archive files.  Then for each individual Mach-O file ProcessMachO() is
2328 // called to process the file based on the command line options.
2329 void objdump::parseInputMachO(StringRef Filename) {
2330   if (!ValidateArchFlags())
2331     return;
2332 
2333   // Attempt to open the binary.
2334   Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
2335   if (!BinaryOrErr) {
2336     if (Error E = isNotObjectErrorInvalidFileType(BinaryOrErr.takeError()))
2337       reportError(std::move(E), Filename);
2338     else
2339       outs() << Filename << ": is not an object file\n";
2340     return;
2341   }
2342   Binary &Bin = *BinaryOrErr.get().getBinary();
2343 
2344   if (Archive *A = dyn_cast<Archive>(&Bin)) {
2345     outs() << "Archive : " << Filename << "\n";
2346     if (ArchiveHeaders)
2347       printArchiveHeaders(Filename, A, Verbose, ArchiveMemberOffsets);
2348 
2349     Error Err = Error::success();
2350     unsigned I = -1;
2351     for (auto &C : A->children(Err)) {
2352       ++I;
2353       Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2354       if (!ChildOrErr) {
2355         if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2356           reportError(std::move(E), getFileNameForError(C, I), Filename);
2357         continue;
2358       }
2359       if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
2360         if (!checkMachOAndArchFlags(O, Filename))
2361           return;
2362         ProcessMachO(Filename, O, O->getFileName());
2363       }
2364     }
2365     if (Err)
2366       reportError(std::move(Err), Filename);
2367     return;
2368   }
2369   if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
2370     parseInputMachO(UB);
2371     return;
2372   }
2373   if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
2374     if (!checkMachOAndArchFlags(O, Filename))
2375       return;
2376     if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O))
2377       ProcessMachO(Filename, MachOOF);
2378     else
2379       WithColor::error(errs(), "llvm-objdump")
2380           << Filename << "': "
2381           << "object is not a Mach-O file type.\n";
2382     return;
2383   }
2384   llvm_unreachable("Input object can't be invalid at this point");
2385 }
2386 
2387 void objdump::parseInputMachO(MachOUniversalBinary *UB) {
2388   if (!ValidateArchFlags())
2389     return;
2390 
2391   auto Filename = UB->getFileName();
2392 
2393   if (UniversalHeaders)
2394     printMachOUniversalHeaders(UB, Verbose);
2395 
2396   // If we have a list of architecture flags specified dump only those.
2397   if (!ArchAll && !ArchFlags.empty()) {
2398     // Look for a slice in the universal binary that matches each ArchFlag.
2399     bool ArchFound;
2400     for (unsigned i = 0; i < ArchFlags.size(); ++i) {
2401       ArchFound = false;
2402       for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2403                                                   E = UB->end_objects();
2404             I != E; ++I) {
2405         if (ArchFlags[i] == I->getArchFlagName()) {
2406           ArchFound = true;
2407           Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
2408               I->getAsObjectFile();
2409           std::string ArchitectureName;
2410           if (ArchFlags.size() > 1)
2411             ArchitectureName = I->getArchFlagName();
2412           if (ObjOrErr) {
2413             ObjectFile &O = *ObjOrErr.get();
2414             if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
2415               ProcessMachO(Filename, MachOOF, "", ArchitectureName);
2416           } else if (Error E = isNotObjectErrorInvalidFileType(
2417                          ObjOrErr.takeError())) {
2418             reportError(std::move(E), "", Filename, ArchitectureName);
2419             continue;
2420           } else if (Expected<std::unique_ptr<Archive>> AOrErr =
2421                          I->getAsArchive()) {
2422             std::unique_ptr<Archive> &A = *AOrErr;
2423             outs() << "Archive : " << Filename;
2424             if (!ArchitectureName.empty())
2425               outs() << " (architecture " << ArchitectureName << ")";
2426             outs() << "\n";
2427             if (ArchiveHeaders)
2428               printArchiveHeaders(Filename, A.get(), Verbose,
2429                                   ArchiveMemberOffsets, ArchitectureName);
2430             Error Err = Error::success();
2431             unsigned I = -1;
2432             for (auto &C : A->children(Err)) {
2433               ++I;
2434               Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2435               if (!ChildOrErr) {
2436                 if (Error E =
2437                         isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2438                   reportError(std::move(E), getFileNameForError(C, I), Filename,
2439                               ArchitectureName);
2440                 continue;
2441               }
2442               if (MachOObjectFile *O =
2443                       dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
2444                 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
2445             }
2446             if (Err)
2447               reportError(std::move(Err), Filename);
2448           } else {
2449             consumeError(AOrErr.takeError());
2450             reportError(Filename,
2451                         "Mach-O universal file for architecture " +
2452                             StringRef(I->getArchFlagName()) +
2453                             " is not a Mach-O file or an archive file");
2454           }
2455         }
2456       }
2457       if (!ArchFound) {
2458         WithColor::error(errs(), "llvm-objdump")
2459             << "file: " + Filename + " does not contain "
2460             << "architecture: " + ArchFlags[i] + "\n";
2461         return;
2462       }
2463     }
2464     return;
2465   }
2466   // No architecture flags were specified so if this contains a slice that
2467   // matches the host architecture dump only that.
2468   if (!ArchAll) {
2469     for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2470                                                 E = UB->end_objects();
2471           I != E; ++I) {
2472       if (MachOObjectFile::getHostArch().getArchName() ==
2473           I->getArchFlagName()) {
2474         Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2475         std::string ArchiveName;
2476         ArchiveName.clear();
2477         if (ObjOrErr) {
2478           ObjectFile &O = *ObjOrErr.get();
2479           if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
2480             ProcessMachO(Filename, MachOOF);
2481         } else if (Error E =
2482                        isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) {
2483           reportError(std::move(E), Filename);
2484         } else if (Expected<std::unique_ptr<Archive>> AOrErr =
2485                        I->getAsArchive()) {
2486           std::unique_ptr<Archive> &A = *AOrErr;
2487           outs() << "Archive : " << Filename << "\n";
2488           if (ArchiveHeaders)
2489             printArchiveHeaders(Filename, A.get(), Verbose,
2490                                 ArchiveMemberOffsets);
2491           Error Err = Error::success();
2492           unsigned I = -1;
2493           for (auto &C : A->children(Err)) {
2494             ++I;
2495             Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2496             if (!ChildOrErr) {
2497               if (Error E =
2498                       isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2499                 reportError(std::move(E), getFileNameForError(C, I), Filename);
2500               continue;
2501             }
2502             if (MachOObjectFile *O =
2503                     dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
2504               ProcessMachO(Filename, O, O->getFileName());
2505           }
2506           if (Err)
2507             reportError(std::move(Err), Filename);
2508         } else {
2509           consumeError(AOrErr.takeError());
2510           reportError(Filename, "Mach-O universal file for architecture " +
2511                                     StringRef(I->getArchFlagName()) +
2512                                     " is not a Mach-O file or an archive file");
2513         }
2514         return;
2515       }
2516     }
2517   }
2518   // Either all architectures have been specified or none have been specified
2519   // and this does not contain the host architecture so dump all the slices.
2520   bool moreThanOneArch = UB->getNumberOfObjects() > 1;
2521   for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2522                                               E = UB->end_objects();
2523         I != E; ++I) {
2524     Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2525     std::string ArchitectureName;
2526     if (moreThanOneArch)
2527       ArchitectureName = I->getArchFlagName();
2528     if (ObjOrErr) {
2529       ObjectFile &Obj = *ObjOrErr.get();
2530       if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
2531         ProcessMachO(Filename, MachOOF, "", ArchitectureName);
2532     } else if (Error E =
2533                    isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) {
2534       reportError(std::move(E), Filename, "", ArchitectureName);
2535     } else if (Expected<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
2536       std::unique_ptr<Archive> &A = *AOrErr;
2537       outs() << "Archive : " << Filename;
2538       if (!ArchitectureName.empty())
2539         outs() << " (architecture " << ArchitectureName << ")";
2540       outs() << "\n";
2541       if (ArchiveHeaders)
2542         printArchiveHeaders(Filename, A.get(), Verbose, ArchiveMemberOffsets,
2543                             ArchitectureName);
2544       Error Err = Error::success();
2545       unsigned I = -1;
2546       for (auto &C : A->children(Err)) {
2547         ++I;
2548         Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2549         if (!ChildOrErr) {
2550           if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2551             reportError(std::move(E), getFileNameForError(C, I), Filename,
2552                         ArchitectureName);
2553           continue;
2554         }
2555         if (MachOObjectFile *O =
2556                 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
2557           if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
2558             ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
2559                           ArchitectureName);
2560         }
2561       }
2562       if (Err)
2563         reportError(std::move(Err), Filename);
2564     } else {
2565       consumeError(AOrErr.takeError());
2566       reportError(Filename, "Mach-O universal file for architecture " +
2567                                 StringRef(I->getArchFlagName()) +
2568                                 " is not a Mach-O file or an archive file");
2569     }
2570   }
2571 }
2572 
2573 namespace {
2574 // The block of info used by the Symbolizer call backs.
2575 struct DisassembleInfo {
2576   DisassembleInfo(MachOObjectFile *O, SymbolAddressMap *AddrMap,
2577                   std::vector<SectionRef> *Sections, bool verbose)
2578     : verbose(verbose), O(O), AddrMap(AddrMap), Sections(Sections) {}
2579   bool verbose;
2580   MachOObjectFile *O;
2581   SectionRef S;
2582   SymbolAddressMap *AddrMap;
2583   std::vector<SectionRef> *Sections;
2584   const char *class_name = nullptr;
2585   const char *selector_name = nullptr;
2586   std::unique_ptr<char[]> method = nullptr;
2587   char *demangled_name = nullptr;
2588   uint64_t adrp_addr = 0;
2589   uint32_t adrp_inst = 0;
2590   std::unique_ptr<SymbolAddressMap> bindtable;
2591   uint32_t depth = 0;
2592 };
2593 } // namespace
2594 
2595 // SymbolizerGetOpInfo() is the operand information call back function.
2596 // This is called to get the symbolic information for operand(s) of an
2597 // instruction when it is being done.  This routine does this from
2598 // the relocation information, symbol table, etc. That block of information
2599 // is a pointer to the struct DisassembleInfo that was passed when the
2600 // disassembler context was created and passed to back to here when
2601 // called back by the disassembler for instruction operands that could have
2602 // relocation information. The address of the instruction containing operand is
2603 // at the Pc parameter.  The immediate value the operand has is passed in
2604 // op_info->Value and is at Offset past the start of the instruction and has a
2605 // byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
2606 // LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
2607 // names and addends of the symbolic expression to add for the operand.  The
2608 // value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
2609 // information is returned then this function returns 1 else it returns 0.
2610 static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
2611                                uint64_t OpSize, uint64_t InstSize, int TagType,
2612                                void *TagBuf) {
2613   struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
2614   struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
2615   uint64_t value = op_info->Value;
2616 
2617   // Make sure all fields returned are zero if we don't set them.
2618   memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
2619   op_info->Value = value;
2620 
2621   // If the TagType is not the value 1 which it code knows about or if no
2622   // verbose symbolic information is wanted then just return 0, indicating no
2623   // information is being returned.
2624   if (TagType != 1 || !info->verbose)
2625     return 0;
2626 
2627   unsigned int Arch = info->O->getArch();
2628   if (Arch == Triple::x86) {
2629     if (OpSize != 1 && OpSize != 2 && OpSize != 4 && OpSize != 0)
2630       return 0;
2631     if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2632       // TODO:
2633       // Search the external relocation entries of a fully linked image
2634       // (if any) for an entry that matches this segment offset.
2635       // uint32_t seg_offset = (Pc + Offset);
2636       return 0;
2637     }
2638     // In MH_OBJECT filetypes search the section's relocation entries (if any)
2639     // for an entry for this section offset.
2640     uint32_t sect_addr = info->S.getAddress();
2641     uint32_t sect_offset = (Pc + Offset) - sect_addr;
2642     bool reloc_found = false;
2643     DataRefImpl Rel;
2644     MachO::any_relocation_info RE;
2645     bool isExtern = false;
2646     SymbolRef Symbol;
2647     bool r_scattered = false;
2648     uint32_t r_value, pair_r_value, r_type;
2649     for (const RelocationRef &Reloc : info->S.relocations()) {
2650       uint64_t RelocOffset = Reloc.getOffset();
2651       if (RelocOffset == sect_offset) {
2652         Rel = Reloc.getRawDataRefImpl();
2653         RE = info->O->getRelocation(Rel);
2654         r_type = info->O->getAnyRelocationType(RE);
2655         r_scattered = info->O->isRelocationScattered(RE);
2656         if (r_scattered) {
2657           r_value = info->O->getScatteredRelocationValue(RE);
2658           if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2659               r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
2660             DataRefImpl RelNext = Rel;
2661             info->O->moveRelocationNext(RelNext);
2662             MachO::any_relocation_info RENext;
2663             RENext = info->O->getRelocation(RelNext);
2664             if (info->O->isRelocationScattered(RENext))
2665               pair_r_value = info->O->getScatteredRelocationValue(RENext);
2666             else
2667               return 0;
2668           }
2669         } else {
2670           isExtern = info->O->getPlainRelocationExternal(RE);
2671           if (isExtern) {
2672             symbol_iterator RelocSym = Reloc.getSymbol();
2673             Symbol = *RelocSym;
2674           }
2675         }
2676         reloc_found = true;
2677         break;
2678       }
2679     }
2680     if (reloc_found && isExtern) {
2681       op_info->AddSymbol.Present = 1;
2682       op_info->AddSymbol.Name =
2683           unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
2684       // For i386 extern relocation entries the value in the instruction is
2685       // the offset from the symbol, and value is already set in op_info->Value.
2686       return 1;
2687     }
2688     if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2689                         r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
2690       const char *add = GuessSymbolName(r_value, info->AddrMap);
2691       const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
2692       uint32_t offset = value - (r_value - pair_r_value);
2693       op_info->AddSymbol.Present = 1;
2694       if (add != nullptr)
2695         op_info->AddSymbol.Name = add;
2696       else
2697         op_info->AddSymbol.Value = r_value;
2698       op_info->SubtractSymbol.Present = 1;
2699       if (sub != nullptr)
2700         op_info->SubtractSymbol.Name = sub;
2701       else
2702         op_info->SubtractSymbol.Value = pair_r_value;
2703       op_info->Value = offset;
2704       return 1;
2705     }
2706     return 0;
2707   }
2708   if (Arch == Triple::x86_64) {
2709     if (OpSize != 1 && OpSize != 2 && OpSize != 4 && OpSize != 0)
2710       return 0;
2711     // For non MH_OBJECT types, like MH_KEXT_BUNDLE, Search the external
2712     // relocation entries of a linked image (if any) for an entry that matches
2713     // this segment offset.
2714     if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2715       uint64_t seg_offset = Pc + Offset;
2716       bool reloc_found = false;
2717       DataRefImpl Rel;
2718       MachO::any_relocation_info RE;
2719       bool isExtern = false;
2720       SymbolRef Symbol;
2721       for (const RelocationRef &Reloc : info->O->external_relocations()) {
2722         uint64_t RelocOffset = Reloc.getOffset();
2723         if (RelocOffset == seg_offset) {
2724           Rel = Reloc.getRawDataRefImpl();
2725           RE = info->O->getRelocation(Rel);
2726           // external relocation entries should always be external.
2727           isExtern = info->O->getPlainRelocationExternal(RE);
2728           if (isExtern) {
2729             symbol_iterator RelocSym = Reloc.getSymbol();
2730             Symbol = *RelocSym;
2731           }
2732           reloc_found = true;
2733           break;
2734         }
2735       }
2736       if (reloc_found && isExtern) {
2737         // The Value passed in will be adjusted by the Pc if the instruction
2738         // adds the Pc.  But for x86_64 external relocation entries the Value
2739         // is the offset from the external symbol.
2740         if (info->O->getAnyRelocationPCRel(RE))
2741           op_info->Value -= Pc + InstSize;
2742         const char *name =
2743             unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
2744         op_info->AddSymbol.Present = 1;
2745         op_info->AddSymbol.Name = name;
2746         return 1;
2747       }
2748       return 0;
2749     }
2750     // In MH_OBJECT filetypes search the section's relocation entries (if any)
2751     // for an entry for this section offset.
2752     uint64_t sect_addr = info->S.getAddress();
2753     uint64_t sect_offset = (Pc + Offset) - sect_addr;
2754     bool reloc_found = false;
2755     DataRefImpl Rel;
2756     MachO::any_relocation_info RE;
2757     bool isExtern = false;
2758     SymbolRef Symbol;
2759     for (const RelocationRef &Reloc : info->S.relocations()) {
2760       uint64_t RelocOffset = Reloc.getOffset();
2761       if (RelocOffset == sect_offset) {
2762         Rel = Reloc.getRawDataRefImpl();
2763         RE = info->O->getRelocation(Rel);
2764         // NOTE: Scattered relocations don't exist on x86_64.
2765         isExtern = info->O->getPlainRelocationExternal(RE);
2766         if (isExtern) {
2767           symbol_iterator RelocSym = Reloc.getSymbol();
2768           Symbol = *RelocSym;
2769         }
2770         reloc_found = true;
2771         break;
2772       }
2773     }
2774     if (reloc_found && isExtern) {
2775       // The Value passed in will be adjusted by the Pc if the instruction
2776       // adds the Pc.  But for x86_64 external relocation entries the Value
2777       // is the offset from the external symbol.
2778       if (info->O->getAnyRelocationPCRel(RE))
2779         op_info->Value -= Pc + InstSize;
2780       const char *name =
2781           unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
2782       unsigned Type = info->O->getAnyRelocationType(RE);
2783       if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
2784         DataRefImpl RelNext = Rel;
2785         info->O->moveRelocationNext(RelNext);
2786         MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2787         unsigned TypeNext = info->O->getAnyRelocationType(RENext);
2788         bool isExternNext = info->O->getPlainRelocationExternal(RENext);
2789         unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
2790         if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
2791           op_info->SubtractSymbol.Present = 1;
2792           op_info->SubtractSymbol.Name = name;
2793           symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
2794           Symbol = *RelocSymNext;
2795           name = unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
2796         }
2797       }
2798       // TODO: add the VariantKinds to op_info->VariantKind for relocation types
2799       // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
2800       op_info->AddSymbol.Present = 1;
2801       op_info->AddSymbol.Name = name;
2802       return 1;
2803     }
2804     return 0;
2805   }
2806   if (Arch == Triple::arm) {
2807     if (Offset != 0 || (InstSize != 4 && InstSize != 2))
2808       return 0;
2809     if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2810       // TODO:
2811       // Search the external relocation entries of a fully linked image
2812       // (if any) for an entry that matches this segment offset.
2813       // uint32_t seg_offset = (Pc + Offset);
2814       return 0;
2815     }
2816     // In MH_OBJECT filetypes search the section's relocation entries (if any)
2817     // for an entry for this section offset.
2818     uint32_t sect_addr = info->S.getAddress();
2819     uint32_t sect_offset = (Pc + Offset) - sect_addr;
2820     DataRefImpl Rel;
2821     MachO::any_relocation_info RE;
2822     bool isExtern = false;
2823     SymbolRef Symbol;
2824     bool r_scattered = false;
2825     uint32_t r_value, pair_r_value, r_type, r_length, other_half;
2826     auto Reloc =
2827         find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2828           uint64_t RelocOffset = Reloc.getOffset();
2829           return RelocOffset == sect_offset;
2830         });
2831 
2832     if (Reloc == info->S.relocations().end())
2833       return 0;
2834 
2835     Rel = Reloc->getRawDataRefImpl();
2836     RE = info->O->getRelocation(Rel);
2837     r_length = info->O->getAnyRelocationLength(RE);
2838     r_scattered = info->O->isRelocationScattered(RE);
2839     if (r_scattered) {
2840       r_value = info->O->getScatteredRelocationValue(RE);
2841       r_type = info->O->getScatteredRelocationType(RE);
2842     } else {
2843       r_type = info->O->getAnyRelocationType(RE);
2844       isExtern = info->O->getPlainRelocationExternal(RE);
2845       if (isExtern) {
2846         symbol_iterator RelocSym = Reloc->getSymbol();
2847         Symbol = *RelocSym;
2848       }
2849     }
2850     if (r_type == MachO::ARM_RELOC_HALF ||
2851         r_type == MachO::ARM_RELOC_SECTDIFF ||
2852         r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
2853         r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2854       DataRefImpl RelNext = Rel;
2855       info->O->moveRelocationNext(RelNext);
2856       MachO::any_relocation_info RENext;
2857       RENext = info->O->getRelocation(RelNext);
2858       other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
2859       if (info->O->isRelocationScattered(RENext))
2860         pair_r_value = info->O->getScatteredRelocationValue(RENext);
2861     }
2862 
2863     if (isExtern) {
2864       const char *name =
2865           unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
2866       op_info->AddSymbol.Present = 1;
2867       op_info->AddSymbol.Name = name;
2868       switch (r_type) {
2869       case MachO::ARM_RELOC_HALF:
2870         if ((r_length & 0x1) == 1) {
2871           op_info->Value = value << 16 | other_half;
2872           op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2873         } else {
2874           op_info->Value = other_half << 16 | value;
2875           op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
2876         }
2877         break;
2878       default:
2879         break;
2880       }
2881       return 1;
2882     }
2883     // If we have a branch that is not an external relocation entry then
2884     // return 0 so the code in tryAddingSymbolicOperand() can use the
2885     // SymbolLookUp call back with the branch target address to look up the
2886     // symbol and possibility add an annotation for a symbol stub.
2887     if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
2888                           r_type == MachO::ARM_THUMB_RELOC_BR22))
2889       return 0;
2890 
2891     uint32_t offset = 0;
2892     if (r_type == MachO::ARM_RELOC_HALF ||
2893         r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2894       if ((r_length & 0x1) == 1)
2895         value = value << 16 | other_half;
2896       else
2897         value = other_half << 16 | value;
2898     }
2899     if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
2900                         r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
2901       offset = value - r_value;
2902       value = r_value;
2903     }
2904 
2905     if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2906       if ((r_length & 0x1) == 1)
2907         op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2908       else
2909         op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
2910       const char *add = GuessSymbolName(r_value, info->AddrMap);
2911       const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
2912       int32_t offset = value - (r_value - pair_r_value);
2913       op_info->AddSymbol.Present = 1;
2914       if (add != nullptr)
2915         op_info->AddSymbol.Name = add;
2916       else
2917         op_info->AddSymbol.Value = r_value;
2918       op_info->SubtractSymbol.Present = 1;
2919       if (sub != nullptr)
2920         op_info->SubtractSymbol.Name = sub;
2921       else
2922         op_info->SubtractSymbol.Value = pair_r_value;
2923       op_info->Value = offset;
2924       return 1;
2925     }
2926 
2927     op_info->AddSymbol.Present = 1;
2928     op_info->Value = offset;
2929     if (r_type == MachO::ARM_RELOC_HALF) {
2930       if ((r_length & 0x1) == 1)
2931         op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2932       else
2933         op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
2934     }
2935     const char *add = GuessSymbolName(value, info->AddrMap);
2936     if (add != nullptr) {
2937       op_info->AddSymbol.Name = add;
2938       return 1;
2939     }
2940     op_info->AddSymbol.Value = value;
2941     return 1;
2942   }
2943   if (Arch == Triple::aarch64) {
2944     if (Offset != 0 || InstSize != 4)
2945       return 0;
2946     if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2947       // TODO:
2948       // Search the external relocation entries of a fully linked image
2949       // (if any) for an entry that matches this segment offset.
2950       // uint64_t seg_offset = (Pc + Offset);
2951       return 0;
2952     }
2953     // In MH_OBJECT filetypes search the section's relocation entries (if any)
2954     // for an entry for this section offset.
2955     uint64_t sect_addr = info->S.getAddress();
2956     uint64_t sect_offset = (Pc + Offset) - sect_addr;
2957     auto Reloc =
2958         find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2959           uint64_t RelocOffset = Reloc.getOffset();
2960           return RelocOffset == sect_offset;
2961         });
2962 
2963     if (Reloc == info->S.relocations().end())
2964       return 0;
2965 
2966     DataRefImpl Rel = Reloc->getRawDataRefImpl();
2967     MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2968     uint32_t r_type = info->O->getAnyRelocationType(RE);
2969     if (r_type == MachO::ARM64_RELOC_ADDEND) {
2970       DataRefImpl RelNext = Rel;
2971       info->O->moveRelocationNext(RelNext);
2972       MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2973       if (value == 0) {
2974         value = info->O->getPlainRelocationSymbolNum(RENext);
2975         op_info->Value = value;
2976       }
2977     }
2978     // NOTE: Scattered relocations don't exist on arm64.
2979     if (!info->O->getPlainRelocationExternal(RE))
2980       return 0;
2981     const char *name =
2982         unwrapOrError(Reloc->getSymbol()->getName(), info->O->getFileName())
2983             .data();
2984     op_info->AddSymbol.Present = 1;
2985     op_info->AddSymbol.Name = name;
2986 
2987     switch (r_type) {
2988     case MachO::ARM64_RELOC_PAGE21:
2989       /* @page */
2990       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2991       break;
2992     case MachO::ARM64_RELOC_PAGEOFF12:
2993       /* @pageoff */
2994       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2995       break;
2996     case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2997       /* @gotpage */
2998       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2999       break;
3000     case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
3001       /* @gotpageoff */
3002       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
3003       break;
3004     case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
3005       /* @tvlppage is not implemented in llvm-mc */
3006       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
3007       break;
3008     case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
3009       /* @tvlppageoff is not implemented in llvm-mc */
3010       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
3011       break;
3012     default:
3013     case MachO::ARM64_RELOC_BRANCH26:
3014       op_info->VariantKind = LLVMDisassembler_VariantKind_None;
3015       break;
3016     }
3017     return 1;
3018   }
3019   return 0;
3020 }
3021 
3022 // GuessCstringPointer is passed the address of what might be a pointer to a
3023 // literal string in a cstring section.  If that address is in a cstring section
3024 // it returns a pointer to that string.  Else it returns nullptr.
3025 static const char *GuessCstringPointer(uint64_t ReferenceValue,
3026                                        struct DisassembleInfo *info) {
3027   for (const auto &Load : info->O->load_commands()) {
3028     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
3029       MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
3030       for (unsigned J = 0; J < Seg.nsects; ++J) {
3031         MachO::section_64 Sec = info->O->getSection64(Load, J);
3032         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3033         if (section_type == MachO::S_CSTRING_LITERALS &&
3034             ReferenceValue >= Sec.addr &&
3035             ReferenceValue < Sec.addr + Sec.size) {
3036           uint64_t sect_offset = ReferenceValue - Sec.addr;
3037           uint64_t object_offset = Sec.offset + sect_offset;
3038           StringRef MachOContents = info->O->getData();
3039           uint64_t object_size = MachOContents.size();
3040           const char *object_addr = (const char *)MachOContents.data();
3041           if (object_offset < object_size) {
3042             const char *name = object_addr + object_offset;
3043             return name;
3044           } else {
3045             return nullptr;
3046           }
3047         }
3048       }
3049     } else if (Load.C.cmd == MachO::LC_SEGMENT) {
3050       MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
3051       for (unsigned J = 0; J < Seg.nsects; ++J) {
3052         MachO::section Sec = info->O->getSection(Load, J);
3053         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3054         if (section_type == MachO::S_CSTRING_LITERALS &&
3055             ReferenceValue >= Sec.addr &&
3056             ReferenceValue < Sec.addr + Sec.size) {
3057           uint64_t sect_offset = ReferenceValue - Sec.addr;
3058           uint64_t object_offset = Sec.offset + sect_offset;
3059           StringRef MachOContents = info->O->getData();
3060           uint64_t object_size = MachOContents.size();
3061           const char *object_addr = (const char *)MachOContents.data();
3062           if (object_offset < object_size) {
3063             const char *name = object_addr + object_offset;
3064             return name;
3065           } else {
3066             return nullptr;
3067           }
3068         }
3069       }
3070     }
3071   }
3072   return nullptr;
3073 }
3074 
3075 // GuessIndirectSymbol returns the name of the indirect symbol for the
3076 // ReferenceValue passed in or nullptr.  This is used when ReferenceValue maybe
3077 // an address of a symbol stub or a lazy or non-lazy pointer to associate the
3078 // symbol name being referenced by the stub or pointer.
3079 static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
3080                                        struct DisassembleInfo *info) {
3081   MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
3082   MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
3083   for (const auto &Load : info->O->load_commands()) {
3084     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
3085       MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
3086       for (unsigned J = 0; J < Seg.nsects; ++J) {
3087         MachO::section_64 Sec = info->O->getSection64(Load, J);
3088         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3089         if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
3090              section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
3091              section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
3092              section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
3093              section_type == MachO::S_SYMBOL_STUBS) &&
3094             ReferenceValue >= Sec.addr &&
3095             ReferenceValue < Sec.addr + Sec.size) {
3096           uint32_t stride;
3097           if (section_type == MachO::S_SYMBOL_STUBS)
3098             stride = Sec.reserved2;
3099           else
3100             stride = 8;
3101           if (stride == 0)
3102             return nullptr;
3103           uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
3104           if (index < Dysymtab.nindirectsyms) {
3105             uint32_t indirect_symbol =
3106                 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
3107             if (indirect_symbol < Symtab.nsyms) {
3108               symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
3109               return unwrapOrError(Sym->getName(), info->O->getFileName())
3110                   .data();
3111             }
3112           }
3113         }
3114       }
3115     } else if (Load.C.cmd == MachO::LC_SEGMENT) {
3116       MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
3117       for (unsigned J = 0; J < Seg.nsects; ++J) {
3118         MachO::section Sec = info->O->getSection(Load, J);
3119         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3120         if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
3121              section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
3122              section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
3123              section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
3124              section_type == MachO::S_SYMBOL_STUBS) &&
3125             ReferenceValue >= Sec.addr &&
3126             ReferenceValue < Sec.addr + Sec.size) {
3127           uint32_t stride;
3128           if (section_type == MachO::S_SYMBOL_STUBS)
3129             stride = Sec.reserved2;
3130           else
3131             stride = 4;
3132           if (stride == 0)
3133             return nullptr;
3134           uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
3135           if (index < Dysymtab.nindirectsyms) {
3136             uint32_t indirect_symbol =
3137                 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
3138             if (indirect_symbol < Symtab.nsyms) {
3139               symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
3140               return unwrapOrError(Sym->getName(), info->O->getFileName())
3141                   .data();
3142             }
3143           }
3144         }
3145       }
3146     }
3147   }
3148   return nullptr;
3149 }
3150 
3151 // method_reference() is called passing it the ReferenceName that might be
3152 // a reference it to an Objective-C method call.  If so then it allocates and
3153 // assembles a method call string with the values last seen and saved in
3154 // the DisassembleInfo's class_name and selector_name fields.  This is saved
3155 // into the method field of the info and any previous string is free'ed.
3156 // Then the class_name field in the info is set to nullptr.  The method call
3157 // string is set into ReferenceName and ReferenceType is set to
3158 // LLVMDisassembler_ReferenceType_Out_Objc_Message.  If this not a method call
3159 // then both ReferenceType and ReferenceName are left unchanged.
3160 static void method_reference(struct DisassembleInfo *info,
3161                              uint64_t *ReferenceType,
3162                              const char **ReferenceName) {
3163   unsigned int Arch = info->O->getArch();
3164   if (*ReferenceName != nullptr) {
3165     if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
3166       if (info->selector_name != nullptr) {
3167         if (info->class_name != nullptr) {
3168           info->method = std::make_unique<char[]>(
3169               5 + strlen(info->class_name) + strlen(info->selector_name));
3170           char *method = info->method.get();
3171           if (method != nullptr) {
3172             strcpy(method, "+[");
3173             strcat(method, info->class_name);
3174             strcat(method, " ");
3175             strcat(method, info->selector_name);
3176             strcat(method, "]");
3177             *ReferenceName = method;
3178             *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3179           }
3180         } else {
3181           info->method =
3182               std::make_unique<char[]>(9 + strlen(info->selector_name));
3183           char *method = info->method.get();
3184           if (method != nullptr) {
3185             if (Arch == Triple::x86_64)
3186               strcpy(method, "-[%rdi ");
3187             else if (Arch == Triple::aarch64)
3188               strcpy(method, "-[x0 ");
3189             else
3190               strcpy(method, "-[r? ");
3191             strcat(method, info->selector_name);
3192             strcat(method, "]");
3193             *ReferenceName = method;
3194             *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3195           }
3196         }
3197         info->class_name = nullptr;
3198       }
3199     } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
3200       if (info->selector_name != nullptr) {
3201         info->method =
3202             std::make_unique<char[]>(17 + strlen(info->selector_name));
3203         char *method = info->method.get();
3204         if (method != nullptr) {
3205           if (Arch == Triple::x86_64)
3206             strcpy(method, "-[[%rdi super] ");
3207           else if (Arch == Triple::aarch64)
3208             strcpy(method, "-[[x0 super] ");
3209           else
3210             strcpy(method, "-[[r? super] ");
3211           strcat(method, info->selector_name);
3212           strcat(method, "]");
3213           *ReferenceName = method;
3214           *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3215         }
3216         info->class_name = nullptr;
3217       }
3218     }
3219   }
3220 }
3221 
3222 // GuessPointerPointer() is passed the address of what might be a pointer to
3223 // a reference to an Objective-C class, selector, message ref or cfstring.
3224 // If so the value of the pointer is returned and one of the booleans are set
3225 // to true.  If not zero is returned and all the booleans are set to false.
3226 static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
3227                                     struct DisassembleInfo *info,
3228                                     bool &classref, bool &selref, bool &msgref,
3229                                     bool &cfstring) {
3230   classref = false;
3231   selref = false;
3232   msgref = false;
3233   cfstring = false;
3234   for (const auto &Load : info->O->load_commands()) {
3235     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
3236       MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
3237       for (unsigned J = 0; J < Seg.nsects; ++J) {
3238         MachO::section_64 Sec = info->O->getSection64(Load, J);
3239         if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
3240              strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
3241              strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
3242              strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
3243              strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
3244             ReferenceValue >= Sec.addr &&
3245             ReferenceValue < Sec.addr + Sec.size) {
3246           uint64_t sect_offset = ReferenceValue - Sec.addr;
3247           uint64_t object_offset = Sec.offset + sect_offset;
3248           StringRef MachOContents = info->O->getData();
3249           uint64_t object_size = MachOContents.size();
3250           const char *object_addr = (const char *)MachOContents.data();
3251           if (object_offset < object_size) {
3252             uint64_t pointer_value;
3253             memcpy(&pointer_value, object_addr + object_offset,
3254                    sizeof(uint64_t));
3255             if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3256               sys::swapByteOrder(pointer_value);
3257             if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
3258               selref = true;
3259             else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
3260                      strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
3261               classref = true;
3262             else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
3263                      ReferenceValue + 8 < Sec.addr + Sec.size) {
3264               msgref = true;
3265               memcpy(&pointer_value, object_addr + object_offset + 8,
3266                      sizeof(uint64_t));
3267               if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3268                 sys::swapByteOrder(pointer_value);
3269             } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
3270               cfstring = true;
3271             return pointer_value;
3272           } else {
3273             return 0;
3274           }
3275         }
3276       }
3277     }
3278     // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
3279   }
3280   return 0;
3281 }
3282 
3283 // get_pointer_64 returns a pointer to the bytes in the object file at the
3284 // Address from a section in the Mach-O file.  And indirectly returns the
3285 // offset into the section, number of bytes left in the section past the offset
3286 // and which section is was being referenced.  If the Address is not in a
3287 // section nullptr is returned.
3288 static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
3289                                   uint32_t &left, SectionRef &S,
3290                                   DisassembleInfo *info,
3291                                   bool objc_only = false) {
3292   offset = 0;
3293   left = 0;
3294   S = SectionRef();
3295   for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
3296     uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
3297     uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
3298     if (SectSize == 0)
3299       continue;
3300     if (objc_only) {
3301       StringRef SectName;
3302       Expected<StringRef> SecNameOrErr =
3303           ((*(info->Sections))[SectIdx]).getName();
3304       if (SecNameOrErr)
3305         SectName = *SecNameOrErr;
3306       else
3307         consumeError(SecNameOrErr.takeError());
3308 
3309       DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
3310       StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
3311       if (SegName != "__OBJC" && SectName != "__cstring")
3312         continue;
3313     }
3314     if (Address >= SectAddress && Address < SectAddress + SectSize) {
3315       S = (*(info->Sections))[SectIdx];
3316       offset = Address - SectAddress;
3317       left = SectSize - offset;
3318       StringRef SectContents = unwrapOrError(
3319           ((*(info->Sections))[SectIdx]).getContents(), info->O->getFileName());
3320       return SectContents.data() + offset;
3321     }
3322   }
3323   return nullptr;
3324 }
3325 
3326 static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
3327                                   uint32_t &left, SectionRef &S,
3328                                   DisassembleInfo *info,
3329                                   bool objc_only = false) {
3330   return get_pointer_64(Address, offset, left, S, info, objc_only);
3331 }
3332 
3333 // get_symbol_64() returns the name of a symbol (or nullptr) and the address of
3334 // the symbol indirectly through n_value. Based on the relocation information
3335 // for the specified section offset in the specified section reference.
3336 // If no relocation information is found and a non-zero ReferenceValue for the
3337 // symbol is passed, look up that address in the info's AddrMap.
3338 static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
3339                                  DisassembleInfo *info, uint64_t &n_value,
3340                                  uint64_t ReferenceValue = 0) {
3341   n_value = 0;
3342   if (!info->verbose)
3343     return nullptr;
3344 
3345   // See if there is an external relocation entry at the sect_offset.
3346   bool reloc_found = false;
3347   DataRefImpl Rel;
3348   MachO::any_relocation_info RE;
3349   bool isExtern = false;
3350   SymbolRef Symbol;
3351   for (const RelocationRef &Reloc : S.relocations()) {
3352     uint64_t RelocOffset = Reloc.getOffset();
3353     if (RelocOffset == sect_offset) {
3354       Rel = Reloc.getRawDataRefImpl();
3355       RE = info->O->getRelocation(Rel);
3356       if (info->O->isRelocationScattered(RE))
3357         continue;
3358       isExtern = info->O->getPlainRelocationExternal(RE);
3359       if (isExtern) {
3360         symbol_iterator RelocSym = Reloc.getSymbol();
3361         Symbol = *RelocSym;
3362       }
3363       reloc_found = true;
3364       break;
3365     }
3366   }
3367   // If there is an external relocation entry for a symbol in this section
3368   // at this section_offset then use that symbol's value for the n_value
3369   // and return its name.
3370   const char *SymbolName = nullptr;
3371   if (reloc_found && isExtern) {
3372     n_value = cantFail(Symbol.getValue());
3373     StringRef Name = unwrapOrError(Symbol.getName(), info->O->getFileName());
3374     if (!Name.empty()) {
3375       SymbolName = Name.data();
3376       return SymbolName;
3377     }
3378   }
3379 
3380   // TODO: For fully linked images, look through the external relocation
3381   // entries off the dynamic symtab command. For these the r_offset is from the
3382   // start of the first writeable segment in the Mach-O file.  So the offset
3383   // to this section from that segment is passed to this routine by the caller,
3384   // as the database_offset. Which is the difference of the section's starting
3385   // address and the first writable segment.
3386   //
3387   // NOTE: need add passing the database_offset to this routine.
3388 
3389   // We did not find an external relocation entry so look up the ReferenceValue
3390   // as an address of a symbol and if found return that symbol's name.
3391   SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
3392 
3393   return SymbolName;
3394 }
3395 
3396 static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
3397                                  DisassembleInfo *info,
3398                                  uint32_t ReferenceValue) {
3399   uint64_t n_value64;
3400   return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
3401 }
3402 
3403 namespace {
3404 
3405 // These are structs in the Objective-C meta data and read to produce the
3406 // comments for disassembly.  While these are part of the ABI they are no
3407 // public defintions.  So the are here not in include/llvm/BinaryFormat/MachO.h
3408 // .
3409 
3410 // The cfstring object in a 64-bit Mach-O file.
3411 struct cfstring64_t {
3412   uint64_t isa;        // class64_t * (64-bit pointer)
3413   uint64_t flags;      // flag bits
3414   uint64_t characters; // char * (64-bit pointer)
3415   uint64_t length;     // number of non-NULL characters in above
3416 };
3417 
3418 // The class object in a 64-bit Mach-O file.
3419 struct class64_t {
3420   uint64_t isa;        // class64_t * (64-bit pointer)
3421   uint64_t superclass; // class64_t * (64-bit pointer)
3422   uint64_t cache;      // Cache (64-bit pointer)
3423   uint64_t vtable;     // IMP * (64-bit pointer)
3424   uint64_t data;       // class_ro64_t * (64-bit pointer)
3425 };
3426 
3427 struct class32_t {
3428   uint32_t isa;        /* class32_t * (32-bit pointer) */
3429   uint32_t superclass; /* class32_t * (32-bit pointer) */
3430   uint32_t cache;      /* Cache (32-bit pointer) */
3431   uint32_t vtable;     /* IMP * (32-bit pointer) */
3432   uint32_t data;       /* class_ro32_t * (32-bit pointer) */
3433 };
3434 
3435 struct class_ro64_t {
3436   uint32_t flags;
3437   uint32_t instanceStart;
3438   uint32_t instanceSize;
3439   uint32_t reserved;
3440   uint64_t ivarLayout;     // const uint8_t * (64-bit pointer)
3441   uint64_t name;           // const char * (64-bit pointer)
3442   uint64_t baseMethods;    // const method_list_t * (64-bit pointer)
3443   uint64_t baseProtocols;  // const protocol_list_t * (64-bit pointer)
3444   uint64_t ivars;          // const ivar_list_t * (64-bit pointer)
3445   uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
3446   uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
3447 };
3448 
3449 struct class_ro32_t {
3450   uint32_t flags;
3451   uint32_t instanceStart;
3452   uint32_t instanceSize;
3453   uint32_t ivarLayout;     /* const uint8_t * (32-bit pointer) */
3454   uint32_t name;           /* const char * (32-bit pointer) */
3455   uint32_t baseMethods;    /* const method_list_t * (32-bit pointer) */
3456   uint32_t baseProtocols;  /* const protocol_list_t * (32-bit pointer) */
3457   uint32_t ivars;          /* const ivar_list_t * (32-bit pointer) */
3458   uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
3459   uint32_t baseProperties; /* const struct objc_property_list *
3460                                                    (32-bit pointer) */
3461 };
3462 
3463 /* Values for class_ro{64,32}_t->flags */
3464 #define RO_META (1 << 0)
3465 #define RO_ROOT (1 << 1)
3466 #define RO_HAS_CXX_STRUCTORS (1 << 2)
3467 
3468 struct method_list64_t {
3469   uint32_t entsize;
3470   uint32_t count;
3471   /* struct method64_t first;  These structures follow inline */
3472 };
3473 
3474 struct method_list32_t {
3475   uint32_t entsize;
3476   uint32_t count;
3477   /* struct method32_t first;  These structures follow inline */
3478 };
3479 
3480 struct method64_t {
3481   uint64_t name;  /* SEL (64-bit pointer) */
3482   uint64_t types; /* const char * (64-bit pointer) */
3483   uint64_t imp;   /* IMP (64-bit pointer) */
3484 };
3485 
3486 struct method32_t {
3487   uint32_t name;  /* SEL (32-bit pointer) */
3488   uint32_t types; /* const char * (32-bit pointer) */
3489   uint32_t imp;   /* IMP (32-bit pointer) */
3490 };
3491 
3492 struct protocol_list64_t {
3493   uint64_t count; /* uintptr_t (a 64-bit value) */
3494   /* struct protocol64_t * list[0];  These pointers follow inline */
3495 };
3496 
3497 struct protocol_list32_t {
3498   uint32_t count; /* uintptr_t (a 32-bit value) */
3499   /* struct protocol32_t * list[0];  These pointers follow inline */
3500 };
3501 
3502 struct protocol64_t {
3503   uint64_t isa;                     /* id * (64-bit pointer) */
3504   uint64_t name;                    /* const char * (64-bit pointer) */
3505   uint64_t protocols;               /* struct protocol_list64_t *
3506                                                     (64-bit pointer) */
3507   uint64_t instanceMethods;         /* method_list_t * (64-bit pointer) */
3508   uint64_t classMethods;            /* method_list_t * (64-bit pointer) */
3509   uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
3510   uint64_t optionalClassMethods;    /* method_list_t * (64-bit pointer) */
3511   uint64_t instanceProperties;      /* struct objc_property_list *
3512                                                        (64-bit pointer) */
3513 };
3514 
3515 struct protocol32_t {
3516   uint32_t isa;                     /* id * (32-bit pointer) */
3517   uint32_t name;                    /* const char * (32-bit pointer) */
3518   uint32_t protocols;               /* struct protocol_list_t *
3519                                                     (32-bit pointer) */
3520   uint32_t instanceMethods;         /* method_list_t * (32-bit pointer) */
3521   uint32_t classMethods;            /* method_list_t * (32-bit pointer) */
3522   uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
3523   uint32_t optionalClassMethods;    /* method_list_t * (32-bit pointer) */
3524   uint32_t instanceProperties;      /* struct objc_property_list *
3525                                                        (32-bit pointer) */
3526 };
3527 
3528 struct ivar_list64_t {
3529   uint32_t entsize;
3530   uint32_t count;
3531   /* struct ivar64_t first;  These structures follow inline */
3532 };
3533 
3534 struct ivar_list32_t {
3535   uint32_t entsize;
3536   uint32_t count;
3537   /* struct ivar32_t first;  These structures follow inline */
3538 };
3539 
3540 struct ivar64_t {
3541   uint64_t offset; /* uintptr_t * (64-bit pointer) */
3542   uint64_t name;   /* const char * (64-bit pointer) */
3543   uint64_t type;   /* const char * (64-bit pointer) */
3544   uint32_t alignment;
3545   uint32_t size;
3546 };
3547 
3548 struct ivar32_t {
3549   uint32_t offset; /* uintptr_t * (32-bit pointer) */
3550   uint32_t name;   /* const char * (32-bit pointer) */
3551   uint32_t type;   /* const char * (32-bit pointer) */
3552   uint32_t alignment;
3553   uint32_t size;
3554 };
3555 
3556 struct objc_property_list64 {
3557   uint32_t entsize;
3558   uint32_t count;
3559   /* struct objc_property64 first;  These structures follow inline */
3560 };
3561 
3562 struct objc_property_list32 {
3563   uint32_t entsize;
3564   uint32_t count;
3565   /* struct objc_property32 first;  These structures follow inline */
3566 };
3567 
3568 struct objc_property64 {
3569   uint64_t name;       /* const char * (64-bit pointer) */
3570   uint64_t attributes; /* const char * (64-bit pointer) */
3571 };
3572 
3573 struct objc_property32 {
3574   uint32_t name;       /* const char * (32-bit pointer) */
3575   uint32_t attributes; /* const char * (32-bit pointer) */
3576 };
3577 
3578 struct category64_t {
3579   uint64_t name;               /* const char * (64-bit pointer) */
3580   uint64_t cls;                /* struct class_t * (64-bit pointer) */
3581   uint64_t instanceMethods;    /* struct method_list_t * (64-bit pointer) */
3582   uint64_t classMethods;       /* struct method_list_t * (64-bit pointer) */
3583   uint64_t protocols;          /* struct protocol_list_t * (64-bit pointer) */
3584   uint64_t instanceProperties; /* struct objc_property_list *
3585                                   (64-bit pointer) */
3586 };
3587 
3588 struct category32_t {
3589   uint32_t name;               /* const char * (32-bit pointer) */
3590   uint32_t cls;                /* struct class_t * (32-bit pointer) */
3591   uint32_t instanceMethods;    /* struct method_list_t * (32-bit pointer) */
3592   uint32_t classMethods;       /* struct method_list_t * (32-bit pointer) */
3593   uint32_t protocols;          /* struct protocol_list_t * (32-bit pointer) */
3594   uint32_t instanceProperties; /* struct objc_property_list *
3595                                   (32-bit pointer) */
3596 };
3597 
3598 struct objc_image_info64 {
3599   uint32_t version;
3600   uint32_t flags;
3601 };
3602 struct objc_image_info32 {
3603   uint32_t version;
3604   uint32_t flags;
3605 };
3606 struct imageInfo_t {
3607   uint32_t version;
3608   uint32_t flags;
3609 };
3610 /* masks for objc_image_info.flags */
3611 #define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
3612 #define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
3613 #define OBJC_IMAGE_IS_SIMULATED (1 << 5)
3614 #define OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES (1 << 6)
3615 
3616 struct message_ref64 {
3617   uint64_t imp; /* IMP (64-bit pointer) */
3618   uint64_t sel; /* SEL (64-bit pointer) */
3619 };
3620 
3621 struct message_ref32 {
3622   uint32_t imp; /* IMP (32-bit pointer) */
3623   uint32_t sel; /* SEL (32-bit pointer) */
3624 };
3625 
3626 // Objective-C 1 (32-bit only) meta data structs.
3627 
3628 struct objc_module_t {
3629   uint32_t version;
3630   uint32_t size;
3631   uint32_t name;   /* char * (32-bit pointer) */
3632   uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
3633 };
3634 
3635 struct objc_symtab_t {
3636   uint32_t sel_ref_cnt;
3637   uint32_t refs; /* SEL * (32-bit pointer) */
3638   uint16_t cls_def_cnt;
3639   uint16_t cat_def_cnt;
3640   // uint32_t defs[1];        /* void * (32-bit pointer) variable size */
3641 };
3642 
3643 struct objc_class_t {
3644   uint32_t isa;         /* struct objc_class * (32-bit pointer) */
3645   uint32_t super_class; /* struct objc_class * (32-bit pointer) */
3646   uint32_t name;        /* const char * (32-bit pointer) */
3647   int32_t version;
3648   int32_t info;
3649   int32_t instance_size;
3650   uint32_t ivars;       /* struct objc_ivar_list * (32-bit pointer) */
3651   uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
3652   uint32_t cache;       /* struct objc_cache * (32-bit pointer) */
3653   uint32_t protocols;   /* struct objc_protocol_list * (32-bit pointer) */
3654 };
3655 
3656 #define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
3657 // class is not a metaclass
3658 #define CLS_CLASS 0x1
3659 // class is a metaclass
3660 #define CLS_META 0x2
3661 
3662 struct objc_category_t {
3663   uint32_t category_name;    /* char * (32-bit pointer) */
3664   uint32_t class_name;       /* char * (32-bit pointer) */
3665   uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
3666   uint32_t class_methods;    /* struct objc_method_list * (32-bit pointer) */
3667   uint32_t protocols;        /* struct objc_protocol_list * (32-bit ptr) */
3668 };
3669 
3670 struct objc_ivar_t {
3671   uint32_t ivar_name; /* char * (32-bit pointer) */
3672   uint32_t ivar_type; /* char * (32-bit pointer) */
3673   int32_t ivar_offset;
3674 };
3675 
3676 struct objc_ivar_list_t {
3677   int32_t ivar_count;
3678   // struct objc_ivar_t ivar_list[1];          /* variable length structure */
3679 };
3680 
3681 struct objc_method_list_t {
3682   uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
3683   int32_t method_count;
3684   // struct objc_method_t method_list[1];      /* variable length structure */
3685 };
3686 
3687 struct objc_method_t {
3688   uint32_t method_name;  /* SEL, aka struct objc_selector * (32-bit pointer) */
3689   uint32_t method_types; /* char * (32-bit pointer) */
3690   uint32_t method_imp;   /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
3691                             (32-bit pointer) */
3692 };
3693 
3694 struct objc_protocol_list_t {
3695   uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
3696   int32_t count;
3697   // uint32_t list[1];   /* Protocol *, aka struct objc_protocol_t *
3698   //                        (32-bit pointer) */
3699 };
3700 
3701 struct objc_protocol_t {
3702   uint32_t isa;              /* struct objc_class * (32-bit pointer) */
3703   uint32_t protocol_name;    /* char * (32-bit pointer) */
3704   uint32_t protocol_list;    /* struct objc_protocol_list * (32-bit pointer) */
3705   uint32_t instance_methods; /* struct objc_method_description_list *
3706                                 (32-bit pointer) */
3707   uint32_t class_methods;    /* struct objc_method_description_list *
3708                                 (32-bit pointer) */
3709 };
3710 
3711 struct objc_method_description_list_t {
3712   int32_t count;
3713   // struct objc_method_description_t list[1];
3714 };
3715 
3716 struct objc_method_description_t {
3717   uint32_t name;  /* SEL, aka struct objc_selector * (32-bit pointer) */
3718   uint32_t types; /* char * (32-bit pointer) */
3719 };
3720 
3721 inline void swapStruct(struct cfstring64_t &cfs) {
3722   sys::swapByteOrder(cfs.isa);
3723   sys::swapByteOrder(cfs.flags);
3724   sys::swapByteOrder(cfs.characters);
3725   sys::swapByteOrder(cfs.length);
3726 }
3727 
3728 inline void swapStruct(struct class64_t &c) {
3729   sys::swapByteOrder(c.isa);
3730   sys::swapByteOrder(c.superclass);
3731   sys::swapByteOrder(c.cache);
3732   sys::swapByteOrder(c.vtable);
3733   sys::swapByteOrder(c.data);
3734 }
3735 
3736 inline void swapStruct(struct class32_t &c) {
3737   sys::swapByteOrder(c.isa);
3738   sys::swapByteOrder(c.superclass);
3739   sys::swapByteOrder(c.cache);
3740   sys::swapByteOrder(c.vtable);
3741   sys::swapByteOrder(c.data);
3742 }
3743 
3744 inline void swapStruct(struct class_ro64_t &cro) {
3745   sys::swapByteOrder(cro.flags);
3746   sys::swapByteOrder(cro.instanceStart);
3747   sys::swapByteOrder(cro.instanceSize);
3748   sys::swapByteOrder(cro.reserved);
3749   sys::swapByteOrder(cro.ivarLayout);
3750   sys::swapByteOrder(cro.name);
3751   sys::swapByteOrder(cro.baseMethods);
3752   sys::swapByteOrder(cro.baseProtocols);
3753   sys::swapByteOrder(cro.ivars);
3754   sys::swapByteOrder(cro.weakIvarLayout);
3755   sys::swapByteOrder(cro.baseProperties);
3756 }
3757 
3758 inline void swapStruct(struct class_ro32_t &cro) {
3759   sys::swapByteOrder(cro.flags);
3760   sys::swapByteOrder(cro.instanceStart);
3761   sys::swapByteOrder(cro.instanceSize);
3762   sys::swapByteOrder(cro.ivarLayout);
3763   sys::swapByteOrder(cro.name);
3764   sys::swapByteOrder(cro.baseMethods);
3765   sys::swapByteOrder(cro.baseProtocols);
3766   sys::swapByteOrder(cro.ivars);
3767   sys::swapByteOrder(cro.weakIvarLayout);
3768   sys::swapByteOrder(cro.baseProperties);
3769 }
3770 
3771 inline void swapStruct(struct method_list64_t &ml) {
3772   sys::swapByteOrder(ml.entsize);
3773   sys::swapByteOrder(ml.count);
3774 }
3775 
3776 inline void swapStruct(struct method_list32_t &ml) {
3777   sys::swapByteOrder(ml.entsize);
3778   sys::swapByteOrder(ml.count);
3779 }
3780 
3781 inline void swapStruct(struct method64_t &m) {
3782   sys::swapByteOrder(m.name);
3783   sys::swapByteOrder(m.types);
3784   sys::swapByteOrder(m.imp);
3785 }
3786 
3787 inline void swapStruct(struct method32_t &m) {
3788   sys::swapByteOrder(m.name);
3789   sys::swapByteOrder(m.types);
3790   sys::swapByteOrder(m.imp);
3791 }
3792 
3793 inline void swapStruct(struct protocol_list64_t &pl) {
3794   sys::swapByteOrder(pl.count);
3795 }
3796 
3797 inline void swapStruct(struct protocol_list32_t &pl) {
3798   sys::swapByteOrder(pl.count);
3799 }
3800 
3801 inline void swapStruct(struct protocol64_t &p) {
3802   sys::swapByteOrder(p.isa);
3803   sys::swapByteOrder(p.name);
3804   sys::swapByteOrder(p.protocols);
3805   sys::swapByteOrder(p.instanceMethods);
3806   sys::swapByteOrder(p.classMethods);
3807   sys::swapByteOrder(p.optionalInstanceMethods);
3808   sys::swapByteOrder(p.optionalClassMethods);
3809   sys::swapByteOrder(p.instanceProperties);
3810 }
3811 
3812 inline void swapStruct(struct protocol32_t &p) {
3813   sys::swapByteOrder(p.isa);
3814   sys::swapByteOrder(p.name);
3815   sys::swapByteOrder(p.protocols);
3816   sys::swapByteOrder(p.instanceMethods);
3817   sys::swapByteOrder(p.classMethods);
3818   sys::swapByteOrder(p.optionalInstanceMethods);
3819   sys::swapByteOrder(p.optionalClassMethods);
3820   sys::swapByteOrder(p.instanceProperties);
3821 }
3822 
3823 inline void swapStruct(struct ivar_list64_t &il) {
3824   sys::swapByteOrder(il.entsize);
3825   sys::swapByteOrder(il.count);
3826 }
3827 
3828 inline void swapStruct(struct ivar_list32_t &il) {
3829   sys::swapByteOrder(il.entsize);
3830   sys::swapByteOrder(il.count);
3831 }
3832 
3833 inline void swapStruct(struct ivar64_t &i) {
3834   sys::swapByteOrder(i.offset);
3835   sys::swapByteOrder(i.name);
3836   sys::swapByteOrder(i.type);
3837   sys::swapByteOrder(i.alignment);
3838   sys::swapByteOrder(i.size);
3839 }
3840 
3841 inline void swapStruct(struct ivar32_t &i) {
3842   sys::swapByteOrder(i.offset);
3843   sys::swapByteOrder(i.name);
3844   sys::swapByteOrder(i.type);
3845   sys::swapByteOrder(i.alignment);
3846   sys::swapByteOrder(i.size);
3847 }
3848 
3849 inline void swapStruct(struct objc_property_list64 &pl) {
3850   sys::swapByteOrder(pl.entsize);
3851   sys::swapByteOrder(pl.count);
3852 }
3853 
3854 inline void swapStruct(struct objc_property_list32 &pl) {
3855   sys::swapByteOrder(pl.entsize);
3856   sys::swapByteOrder(pl.count);
3857 }
3858 
3859 inline void swapStruct(struct objc_property64 &op) {
3860   sys::swapByteOrder(op.name);
3861   sys::swapByteOrder(op.attributes);
3862 }
3863 
3864 inline void swapStruct(struct objc_property32 &op) {
3865   sys::swapByteOrder(op.name);
3866   sys::swapByteOrder(op.attributes);
3867 }
3868 
3869 inline void swapStruct(struct category64_t &c) {
3870   sys::swapByteOrder(c.name);
3871   sys::swapByteOrder(c.cls);
3872   sys::swapByteOrder(c.instanceMethods);
3873   sys::swapByteOrder(c.classMethods);
3874   sys::swapByteOrder(c.protocols);
3875   sys::swapByteOrder(c.instanceProperties);
3876 }
3877 
3878 inline void swapStruct(struct category32_t &c) {
3879   sys::swapByteOrder(c.name);
3880   sys::swapByteOrder(c.cls);
3881   sys::swapByteOrder(c.instanceMethods);
3882   sys::swapByteOrder(c.classMethods);
3883   sys::swapByteOrder(c.protocols);
3884   sys::swapByteOrder(c.instanceProperties);
3885 }
3886 
3887 inline void swapStruct(struct objc_image_info64 &o) {
3888   sys::swapByteOrder(o.version);
3889   sys::swapByteOrder(o.flags);
3890 }
3891 
3892 inline void swapStruct(struct objc_image_info32 &o) {
3893   sys::swapByteOrder(o.version);
3894   sys::swapByteOrder(o.flags);
3895 }
3896 
3897 inline void swapStruct(struct imageInfo_t &o) {
3898   sys::swapByteOrder(o.version);
3899   sys::swapByteOrder(o.flags);
3900 }
3901 
3902 inline void swapStruct(struct message_ref64 &mr) {
3903   sys::swapByteOrder(mr.imp);
3904   sys::swapByteOrder(mr.sel);
3905 }
3906 
3907 inline void swapStruct(struct message_ref32 &mr) {
3908   sys::swapByteOrder(mr.imp);
3909   sys::swapByteOrder(mr.sel);
3910 }
3911 
3912 inline void swapStruct(struct objc_module_t &module) {
3913   sys::swapByteOrder(module.version);
3914   sys::swapByteOrder(module.size);
3915   sys::swapByteOrder(module.name);
3916   sys::swapByteOrder(module.symtab);
3917 }
3918 
3919 inline void swapStruct(struct objc_symtab_t &symtab) {
3920   sys::swapByteOrder(symtab.sel_ref_cnt);
3921   sys::swapByteOrder(symtab.refs);
3922   sys::swapByteOrder(symtab.cls_def_cnt);
3923   sys::swapByteOrder(symtab.cat_def_cnt);
3924 }
3925 
3926 inline void swapStruct(struct objc_class_t &objc_class) {
3927   sys::swapByteOrder(objc_class.isa);
3928   sys::swapByteOrder(objc_class.super_class);
3929   sys::swapByteOrder(objc_class.name);
3930   sys::swapByteOrder(objc_class.version);
3931   sys::swapByteOrder(objc_class.info);
3932   sys::swapByteOrder(objc_class.instance_size);
3933   sys::swapByteOrder(objc_class.ivars);
3934   sys::swapByteOrder(objc_class.methodLists);
3935   sys::swapByteOrder(objc_class.cache);
3936   sys::swapByteOrder(objc_class.protocols);
3937 }
3938 
3939 inline void swapStruct(struct objc_category_t &objc_category) {
3940   sys::swapByteOrder(objc_category.category_name);
3941   sys::swapByteOrder(objc_category.class_name);
3942   sys::swapByteOrder(objc_category.instance_methods);
3943   sys::swapByteOrder(objc_category.class_methods);
3944   sys::swapByteOrder(objc_category.protocols);
3945 }
3946 
3947 inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3948   sys::swapByteOrder(objc_ivar_list.ivar_count);
3949 }
3950 
3951 inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3952   sys::swapByteOrder(objc_ivar.ivar_name);
3953   sys::swapByteOrder(objc_ivar.ivar_type);
3954   sys::swapByteOrder(objc_ivar.ivar_offset);
3955 }
3956 
3957 inline void swapStruct(struct objc_method_list_t &method_list) {
3958   sys::swapByteOrder(method_list.obsolete);
3959   sys::swapByteOrder(method_list.method_count);
3960 }
3961 
3962 inline void swapStruct(struct objc_method_t &method) {
3963   sys::swapByteOrder(method.method_name);
3964   sys::swapByteOrder(method.method_types);
3965   sys::swapByteOrder(method.method_imp);
3966 }
3967 
3968 inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3969   sys::swapByteOrder(protocol_list.next);
3970   sys::swapByteOrder(protocol_list.count);
3971 }
3972 
3973 inline void swapStruct(struct objc_protocol_t &protocol) {
3974   sys::swapByteOrder(protocol.isa);
3975   sys::swapByteOrder(protocol.protocol_name);
3976   sys::swapByteOrder(protocol.protocol_list);
3977   sys::swapByteOrder(protocol.instance_methods);
3978   sys::swapByteOrder(protocol.class_methods);
3979 }
3980 
3981 inline void swapStruct(struct objc_method_description_list_t &mdl) {
3982   sys::swapByteOrder(mdl.count);
3983 }
3984 
3985 inline void swapStruct(struct objc_method_description_t &md) {
3986   sys::swapByteOrder(md.name);
3987   sys::swapByteOrder(md.types);
3988 }
3989 
3990 } // namespace
3991 
3992 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3993                                                  struct DisassembleInfo *info);
3994 
3995 // get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3996 // to an Objective-C class and returns the class name.  It is also passed the
3997 // address of the pointer, so when the pointer is zero as it can be in an .o
3998 // file, that is used to look for an external relocation entry with a symbol
3999 // name.
4000 static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
4001                                               uint64_t ReferenceValue,
4002                                               struct DisassembleInfo *info) {
4003   const char *r;
4004   uint32_t offset, left;
4005   SectionRef S;
4006 
4007   // The pointer_value can be 0 in an object file and have a relocation
4008   // entry for the class symbol at the ReferenceValue (the address of the
4009   // pointer).
4010   if (pointer_value == 0) {
4011     r = get_pointer_64(ReferenceValue, offset, left, S, info);
4012     if (r == nullptr || left < sizeof(uint64_t))
4013       return nullptr;
4014     uint64_t n_value;
4015     const char *symbol_name = get_symbol_64(offset, S, info, n_value);
4016     if (symbol_name == nullptr)
4017       return nullptr;
4018     const char *class_name = strrchr(symbol_name, '$');
4019     if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
4020       return class_name + 2;
4021     else
4022       return nullptr;
4023   }
4024 
4025   // The case were the pointer_value is non-zero and points to a class defined
4026   // in this Mach-O file.
4027   r = get_pointer_64(pointer_value, offset, left, S, info);
4028   if (r == nullptr || left < sizeof(struct class64_t))
4029     return nullptr;
4030   struct class64_t c;
4031   memcpy(&c, r, sizeof(struct class64_t));
4032   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4033     swapStruct(c);
4034   if (c.data == 0)
4035     return nullptr;
4036   r = get_pointer_64(c.data, offset, left, S, info);
4037   if (r == nullptr || left < sizeof(struct class_ro64_t))
4038     return nullptr;
4039   struct class_ro64_t cro;
4040   memcpy(&cro, r, sizeof(struct class_ro64_t));
4041   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4042     swapStruct(cro);
4043   if (cro.name == 0)
4044     return nullptr;
4045   const char *name = get_pointer_64(cro.name, offset, left, S, info);
4046   return name;
4047 }
4048 
4049 // get_objc2_64bit_cfstring_name is used for disassembly and is passed a
4050 // pointer to a cfstring and returns its name or nullptr.
4051 static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
4052                                                  struct DisassembleInfo *info) {
4053   const char *r, *name;
4054   uint32_t offset, left;
4055   SectionRef S;
4056   struct cfstring64_t cfs;
4057   uint64_t cfs_characters;
4058 
4059   r = get_pointer_64(ReferenceValue, offset, left, S, info);
4060   if (r == nullptr || left < sizeof(struct cfstring64_t))
4061     return nullptr;
4062   memcpy(&cfs, r, sizeof(struct cfstring64_t));
4063   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4064     swapStruct(cfs);
4065   if (cfs.characters == 0) {
4066     uint64_t n_value;
4067     const char *symbol_name = get_symbol_64(
4068         offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
4069     if (symbol_name == nullptr)
4070       return nullptr;
4071     cfs_characters = n_value;
4072   } else
4073     cfs_characters = cfs.characters;
4074   name = get_pointer_64(cfs_characters, offset, left, S, info);
4075 
4076   return name;
4077 }
4078 
4079 // get_objc2_64bit_selref() is used for disassembly and is passed a the address
4080 // of a pointer to an Objective-C selector reference when the pointer value is
4081 // zero as in a .o file and is likely to have a external relocation entry with
4082 // who's symbol's n_value is the real pointer to the selector name.  If that is
4083 // the case the real pointer to the selector name is returned else 0 is
4084 // returned
4085 static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
4086                                        struct DisassembleInfo *info) {
4087   uint32_t offset, left;
4088   SectionRef S;
4089 
4090   const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
4091   if (r == nullptr || left < sizeof(uint64_t))
4092     return 0;
4093   uint64_t n_value;
4094   const char *symbol_name = get_symbol_64(offset, S, info, n_value);
4095   if (symbol_name == nullptr)
4096     return 0;
4097   return n_value;
4098 }
4099 
4100 static const SectionRef get_section(MachOObjectFile *O, const char *segname,
4101                                     const char *sectname) {
4102   for (const SectionRef &Section : O->sections()) {
4103     StringRef SectName;
4104     Expected<StringRef> SecNameOrErr = Section.getName();
4105     if (SecNameOrErr)
4106       SectName = *SecNameOrErr;
4107     else
4108       consumeError(SecNameOrErr.takeError());
4109 
4110     DataRefImpl Ref = Section.getRawDataRefImpl();
4111     StringRef SegName = O->getSectionFinalSegmentName(Ref);
4112     if (SegName == segname && SectName == sectname)
4113       return Section;
4114   }
4115   return SectionRef();
4116 }
4117 
4118 static void
4119 walk_pointer_list_64(const char *listname, const SectionRef S,
4120                      MachOObjectFile *O, struct DisassembleInfo *info,
4121                      void (*func)(uint64_t, struct DisassembleInfo *info)) {
4122   if (S == SectionRef())
4123     return;
4124 
4125   StringRef SectName;
4126   Expected<StringRef> SecNameOrErr = S.getName();
4127   if (SecNameOrErr)
4128     SectName = *SecNameOrErr;
4129   else
4130     consumeError(SecNameOrErr.takeError());
4131 
4132   DataRefImpl Ref = S.getRawDataRefImpl();
4133   StringRef SegName = O->getSectionFinalSegmentName(Ref);
4134   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4135 
4136   StringRef BytesStr = unwrapOrError(S.getContents(), O->getFileName());
4137   const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
4138 
4139   for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
4140     uint32_t left = S.getSize() - i;
4141     uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
4142     uint64_t p = 0;
4143     memcpy(&p, Contents + i, size);
4144     if (i + sizeof(uint64_t) > S.getSize())
4145       outs() << listname << " list pointer extends past end of (" << SegName
4146              << "," << SectName << ") section\n";
4147     outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
4148 
4149     if (O->isLittleEndian() != sys::IsLittleEndianHost)
4150       sys::swapByteOrder(p);
4151 
4152     uint64_t n_value = 0;
4153     const char *name = get_symbol_64(i, S, info, n_value, p);
4154     if (name == nullptr)
4155       name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
4156 
4157     if (n_value != 0) {
4158       outs() << format("0x%" PRIx64, n_value);
4159       if (p != 0)
4160         outs() << " + " << format("0x%" PRIx64, p);
4161     } else
4162       outs() << format("0x%" PRIx64, p);
4163     if (name != nullptr)
4164       outs() << " " << name;
4165     outs() << "\n";
4166 
4167     p += n_value;
4168     if (func)
4169       func(p, info);
4170   }
4171 }
4172 
4173 static void
4174 walk_pointer_list_32(const char *listname, const SectionRef S,
4175                      MachOObjectFile *O, struct DisassembleInfo *info,
4176                      void (*func)(uint32_t, struct DisassembleInfo *info)) {
4177   if (S == SectionRef())
4178     return;
4179 
4180   StringRef SectName = unwrapOrError(S.getName(), O->getFileName());
4181   DataRefImpl Ref = S.getRawDataRefImpl();
4182   StringRef SegName = O->getSectionFinalSegmentName(Ref);
4183   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4184 
4185   StringRef BytesStr = unwrapOrError(S.getContents(), O->getFileName());
4186   const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
4187 
4188   for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
4189     uint32_t left = S.getSize() - i;
4190     uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
4191     uint32_t p = 0;
4192     memcpy(&p, Contents + i, size);
4193     if (i + sizeof(uint32_t) > S.getSize())
4194       outs() << listname << " list pointer extends past end of (" << SegName
4195              << "," << SectName << ") section\n";
4196     uint32_t Address = S.getAddress() + i;
4197     outs() << format("%08" PRIx32, Address) << " ";
4198 
4199     if (O->isLittleEndian() != sys::IsLittleEndianHost)
4200       sys::swapByteOrder(p);
4201     outs() << format("0x%" PRIx32, p);
4202 
4203     const char *name = get_symbol_32(i, S, info, p);
4204     if (name != nullptr)
4205       outs() << " " << name;
4206     outs() << "\n";
4207 
4208     if (func)
4209       func(p, info);
4210   }
4211 }
4212 
4213 static void print_layout_map(const char *layout_map, uint32_t left) {
4214   if (layout_map == nullptr)
4215     return;
4216   outs() << "                layout map: ";
4217   do {
4218     outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
4219     left--;
4220     layout_map++;
4221   } while (*layout_map != '\0' && left != 0);
4222   outs() << "\n";
4223 }
4224 
4225 static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
4226   uint32_t offset, left;
4227   SectionRef S;
4228   const char *layout_map;
4229 
4230   if (p == 0)
4231     return;
4232   layout_map = get_pointer_64(p, offset, left, S, info);
4233   print_layout_map(layout_map, left);
4234 }
4235 
4236 static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
4237   uint32_t offset, left;
4238   SectionRef S;
4239   const char *layout_map;
4240 
4241   if (p == 0)
4242     return;
4243   layout_map = get_pointer_32(p, offset, left, S, info);
4244   print_layout_map(layout_map, left);
4245 }
4246 
4247 static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
4248                                   const char *indent) {
4249   struct method_list64_t ml;
4250   struct method64_t m;
4251   const char *r;
4252   uint32_t offset, xoffset, left, i;
4253   SectionRef S, xS;
4254   const char *name, *sym_name;
4255   uint64_t n_value;
4256 
4257   r = get_pointer_64(p, offset, left, S, info);
4258   if (r == nullptr)
4259     return;
4260   memset(&ml, '\0', sizeof(struct method_list64_t));
4261   if (left < sizeof(struct method_list64_t)) {
4262     memcpy(&ml, r, left);
4263     outs() << "   (method_list_t entends past the end of the section)\n";
4264   } else
4265     memcpy(&ml, r, sizeof(struct method_list64_t));
4266   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4267     swapStruct(ml);
4268   outs() << indent << "\t\t   entsize " << ml.entsize << "\n";
4269   outs() << indent << "\t\t     count " << ml.count << "\n";
4270 
4271   p += sizeof(struct method_list64_t);
4272   offset += sizeof(struct method_list64_t);
4273   for (i = 0; i < ml.count; i++) {
4274     r = get_pointer_64(p, offset, left, S, info);
4275     if (r == nullptr)
4276       return;
4277     memset(&m, '\0', sizeof(struct method64_t));
4278     if (left < sizeof(struct method64_t)) {
4279       memcpy(&m, r, left);
4280       outs() << indent << "   (method_t extends past the end of the section)\n";
4281     } else
4282       memcpy(&m, r, sizeof(struct method64_t));
4283     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4284       swapStruct(m);
4285 
4286     outs() << indent << "\t\t      name ";
4287     sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
4288                              info, n_value, m.name);
4289     if (n_value != 0) {
4290       if (info->verbose && sym_name != nullptr)
4291         outs() << sym_name;
4292       else
4293         outs() << format("0x%" PRIx64, n_value);
4294       if (m.name != 0)
4295         outs() << " + " << format("0x%" PRIx64, m.name);
4296     } else
4297       outs() << format("0x%" PRIx64, m.name);
4298     name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
4299     if (name != nullptr)
4300       outs() << format(" %.*s", left, name);
4301     outs() << "\n";
4302 
4303     outs() << indent << "\t\t     types ";
4304     sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
4305                              info, n_value, m.types);
4306     if (n_value != 0) {
4307       if (info->verbose && sym_name != nullptr)
4308         outs() << sym_name;
4309       else
4310         outs() << format("0x%" PRIx64, n_value);
4311       if (m.types != 0)
4312         outs() << " + " << format("0x%" PRIx64, m.types);
4313     } else
4314       outs() << format("0x%" PRIx64, m.types);
4315     name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
4316     if (name != nullptr)
4317       outs() << format(" %.*s", left, name);
4318     outs() << "\n";
4319 
4320     outs() << indent << "\t\t       imp ";
4321     name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
4322                          n_value, m.imp);
4323     if (info->verbose && name == nullptr) {
4324       if (n_value != 0) {
4325         outs() << format("0x%" PRIx64, n_value) << " ";
4326         if (m.imp != 0)
4327           outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
4328       } else
4329         outs() << format("0x%" PRIx64, m.imp) << " ";
4330     }
4331     if (name != nullptr)
4332       outs() << name;
4333     outs() << "\n";
4334 
4335     p += sizeof(struct method64_t);
4336     offset += sizeof(struct method64_t);
4337   }
4338 }
4339 
4340 static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
4341                                   const char *indent) {
4342   struct method_list32_t ml;
4343   struct method32_t m;
4344   const char *r, *name;
4345   uint32_t offset, xoffset, left, i;
4346   SectionRef S, xS;
4347 
4348   r = get_pointer_32(p, offset, left, S, info);
4349   if (r == nullptr)
4350     return;
4351   memset(&ml, '\0', sizeof(struct method_list32_t));
4352   if (left < sizeof(struct method_list32_t)) {
4353     memcpy(&ml, r, left);
4354     outs() << "   (method_list_t entends past the end of the section)\n";
4355   } else
4356     memcpy(&ml, r, sizeof(struct method_list32_t));
4357   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4358     swapStruct(ml);
4359   outs() << indent << "\t\t   entsize " << ml.entsize << "\n";
4360   outs() << indent << "\t\t     count " << ml.count << "\n";
4361 
4362   p += sizeof(struct method_list32_t);
4363   offset += sizeof(struct method_list32_t);
4364   for (i = 0; i < ml.count; i++) {
4365     r = get_pointer_32(p, offset, left, S, info);
4366     if (r == nullptr)
4367       return;
4368     memset(&m, '\0', sizeof(struct method32_t));
4369     if (left < sizeof(struct method32_t)) {
4370       memcpy(&ml, r, left);
4371       outs() << indent << "   (method_t entends past the end of the section)\n";
4372     } else
4373       memcpy(&m, r, sizeof(struct method32_t));
4374     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4375       swapStruct(m);
4376 
4377     outs() << indent << "\t\t      name " << format("0x%" PRIx32, m.name);
4378     name = get_pointer_32(m.name, xoffset, left, xS, info);
4379     if (name != nullptr)
4380       outs() << format(" %.*s", left, name);
4381     outs() << "\n";
4382 
4383     outs() << indent << "\t\t     types " << format("0x%" PRIx32, m.types);
4384     name = get_pointer_32(m.types, xoffset, left, xS, info);
4385     if (name != nullptr)
4386       outs() << format(" %.*s", left, name);
4387     outs() << "\n";
4388 
4389     outs() << indent << "\t\t       imp " << format("0x%" PRIx32, m.imp);
4390     name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
4391                          m.imp);
4392     if (name != nullptr)
4393       outs() << " " << name;
4394     outs() << "\n";
4395 
4396     p += sizeof(struct method32_t);
4397     offset += sizeof(struct method32_t);
4398   }
4399 }
4400 
4401 static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
4402   uint32_t offset, left, xleft;
4403   SectionRef S;
4404   struct objc_method_list_t method_list;
4405   struct objc_method_t method;
4406   const char *r, *methods, *name, *SymbolName;
4407   int32_t i;
4408 
4409   r = get_pointer_32(p, offset, left, S, info, true);
4410   if (r == nullptr)
4411     return true;
4412 
4413   outs() << "\n";
4414   if (left > sizeof(struct objc_method_list_t)) {
4415     memcpy(&method_list, r, sizeof(struct objc_method_list_t));
4416   } else {
4417     outs() << "\t\t objc_method_list extends past end of the section\n";
4418     memset(&method_list, '\0', sizeof(struct objc_method_list_t));
4419     memcpy(&method_list, r, left);
4420   }
4421   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4422     swapStruct(method_list);
4423 
4424   outs() << "\t\t         obsolete "
4425          << format("0x%08" PRIx32, method_list.obsolete) << "\n";
4426   outs() << "\t\t     method_count " << method_list.method_count << "\n";
4427 
4428   methods = r + sizeof(struct objc_method_list_t);
4429   for (i = 0; i < method_list.method_count; i++) {
4430     if ((i + 1) * sizeof(struct objc_method_t) > left) {
4431       outs() << "\t\t remaining method's extend past the of the section\n";
4432       break;
4433     }
4434     memcpy(&method, methods + i * sizeof(struct objc_method_t),
4435            sizeof(struct objc_method_t));
4436     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4437       swapStruct(method);
4438 
4439     outs() << "\t\t      method_name "
4440            << format("0x%08" PRIx32, method.method_name);
4441     if (info->verbose) {
4442       name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
4443       if (name != nullptr)
4444         outs() << format(" %.*s", xleft, name);
4445       else
4446         outs() << " (not in an __OBJC section)";
4447     }
4448     outs() << "\n";
4449 
4450     outs() << "\t\t     method_types "
4451            << format("0x%08" PRIx32, method.method_types);
4452     if (info->verbose) {
4453       name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
4454       if (name != nullptr)
4455         outs() << format(" %.*s", xleft, name);
4456       else
4457         outs() << " (not in an __OBJC section)";
4458     }
4459     outs() << "\n";
4460 
4461     outs() << "\t\t       method_imp "
4462            << format("0x%08" PRIx32, method.method_imp) << " ";
4463     if (info->verbose) {
4464       SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
4465       if (SymbolName != nullptr)
4466         outs() << SymbolName;
4467     }
4468     outs() << "\n";
4469   }
4470   return false;
4471 }
4472 
4473 static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
4474   struct protocol_list64_t pl;
4475   uint64_t q, n_value;
4476   struct protocol64_t pc;
4477   const char *r;
4478   uint32_t offset, xoffset, left, i;
4479   SectionRef S, xS;
4480   const char *name, *sym_name;
4481 
4482   r = get_pointer_64(p, offset, left, S, info);
4483   if (r == nullptr)
4484     return;
4485   memset(&pl, '\0', sizeof(struct protocol_list64_t));
4486   if (left < sizeof(struct protocol_list64_t)) {
4487     memcpy(&pl, r, left);
4488     outs() << "   (protocol_list_t entends past the end of the section)\n";
4489   } else
4490     memcpy(&pl, r, sizeof(struct protocol_list64_t));
4491   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4492     swapStruct(pl);
4493   outs() << "                      count " << pl.count << "\n";
4494 
4495   p += sizeof(struct protocol_list64_t);
4496   offset += sizeof(struct protocol_list64_t);
4497   for (i = 0; i < pl.count; i++) {
4498     r = get_pointer_64(p, offset, left, S, info);
4499     if (r == nullptr)
4500       return;
4501     q = 0;
4502     if (left < sizeof(uint64_t)) {
4503       memcpy(&q, r, left);
4504       outs() << "   (protocol_t * entends past the end of the section)\n";
4505     } else
4506       memcpy(&q, r, sizeof(uint64_t));
4507     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4508       sys::swapByteOrder(q);
4509 
4510     outs() << "\t\t      list[" << i << "] ";
4511     sym_name = get_symbol_64(offset, S, info, n_value, q);
4512     if (n_value != 0) {
4513       if (info->verbose && sym_name != nullptr)
4514         outs() << sym_name;
4515       else
4516         outs() << format("0x%" PRIx64, n_value);
4517       if (q != 0)
4518         outs() << " + " << format("0x%" PRIx64, q);
4519     } else
4520       outs() << format("0x%" PRIx64, q);
4521     outs() << " (struct protocol_t *)\n";
4522 
4523     r = get_pointer_64(q + n_value, offset, left, S, info);
4524     if (r == nullptr)
4525       return;
4526     memset(&pc, '\0', sizeof(struct protocol64_t));
4527     if (left < sizeof(struct protocol64_t)) {
4528       memcpy(&pc, r, left);
4529       outs() << "   (protocol_t entends past the end of the section)\n";
4530     } else
4531       memcpy(&pc, r, sizeof(struct protocol64_t));
4532     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4533       swapStruct(pc);
4534 
4535     outs() << "\t\t\t      isa " << format("0x%" PRIx64, pc.isa) << "\n";
4536 
4537     outs() << "\t\t\t     name ";
4538     sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
4539                              info, n_value, pc.name);
4540     if (n_value != 0) {
4541       if (info->verbose && sym_name != nullptr)
4542         outs() << sym_name;
4543       else
4544         outs() << format("0x%" PRIx64, n_value);
4545       if (pc.name != 0)
4546         outs() << " + " << format("0x%" PRIx64, pc.name);
4547     } else
4548       outs() << format("0x%" PRIx64, pc.name);
4549     name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
4550     if (name != nullptr)
4551       outs() << format(" %.*s", left, name);
4552     outs() << "\n";
4553 
4554     outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
4555 
4556     outs() << "\t\t  instanceMethods ";
4557     sym_name =
4558         get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
4559                       S, info, n_value, pc.instanceMethods);
4560     if (n_value != 0) {
4561       if (info->verbose && sym_name != nullptr)
4562         outs() << sym_name;
4563       else
4564         outs() << format("0x%" PRIx64, n_value);
4565       if (pc.instanceMethods != 0)
4566         outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
4567     } else
4568       outs() << format("0x%" PRIx64, pc.instanceMethods);
4569     outs() << " (struct method_list_t *)\n";
4570     if (pc.instanceMethods + n_value != 0)
4571       print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
4572 
4573     outs() << "\t\t     classMethods ";
4574     sym_name =
4575         get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
4576                       info, n_value, pc.classMethods);
4577     if (n_value != 0) {
4578       if (info->verbose && sym_name != nullptr)
4579         outs() << sym_name;
4580       else
4581         outs() << format("0x%" PRIx64, n_value);
4582       if (pc.classMethods != 0)
4583         outs() << " + " << format("0x%" PRIx64, pc.classMethods);
4584     } else
4585       outs() << format("0x%" PRIx64, pc.classMethods);
4586     outs() << " (struct method_list_t *)\n";
4587     if (pc.classMethods + n_value != 0)
4588       print_method_list64_t(pc.classMethods + n_value, info, "\t");
4589 
4590     outs() << "\t  optionalInstanceMethods "
4591            << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
4592     outs() << "\t     optionalClassMethods "
4593            << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
4594     outs() << "\t       instanceProperties "
4595            << format("0x%" PRIx64, pc.instanceProperties) << "\n";
4596 
4597     p += sizeof(uint64_t);
4598     offset += sizeof(uint64_t);
4599   }
4600 }
4601 
4602 static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
4603   struct protocol_list32_t pl;
4604   uint32_t q;
4605   struct protocol32_t pc;
4606   const char *r;
4607   uint32_t offset, xoffset, left, i;
4608   SectionRef S, xS;
4609   const char *name;
4610 
4611   r = get_pointer_32(p, offset, left, S, info);
4612   if (r == nullptr)
4613     return;
4614   memset(&pl, '\0', sizeof(struct protocol_list32_t));
4615   if (left < sizeof(struct protocol_list32_t)) {
4616     memcpy(&pl, r, left);
4617     outs() << "   (protocol_list_t entends past the end of the section)\n";
4618   } else
4619     memcpy(&pl, r, sizeof(struct protocol_list32_t));
4620   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4621     swapStruct(pl);
4622   outs() << "                      count " << pl.count << "\n";
4623 
4624   p += sizeof(struct protocol_list32_t);
4625   offset += sizeof(struct protocol_list32_t);
4626   for (i = 0; i < pl.count; i++) {
4627     r = get_pointer_32(p, offset, left, S, info);
4628     if (r == nullptr)
4629       return;
4630     q = 0;
4631     if (left < sizeof(uint32_t)) {
4632       memcpy(&q, r, left);
4633       outs() << "   (protocol_t * entends past the end of the section)\n";
4634     } else
4635       memcpy(&q, r, sizeof(uint32_t));
4636     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4637       sys::swapByteOrder(q);
4638     outs() << "\t\t      list[" << i << "] " << format("0x%" PRIx32, q)
4639            << " (struct protocol_t *)\n";
4640     r = get_pointer_32(q, offset, left, S, info);
4641     if (r == nullptr)
4642       return;
4643     memset(&pc, '\0', sizeof(struct protocol32_t));
4644     if (left < sizeof(struct protocol32_t)) {
4645       memcpy(&pc, r, left);
4646       outs() << "   (protocol_t entends past the end of the section)\n";
4647     } else
4648       memcpy(&pc, r, sizeof(struct protocol32_t));
4649     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4650       swapStruct(pc);
4651     outs() << "\t\t\t      isa " << format("0x%" PRIx32, pc.isa) << "\n";
4652     outs() << "\t\t\t     name " << format("0x%" PRIx32, pc.name);
4653     name = get_pointer_32(pc.name, xoffset, left, xS, info);
4654     if (name != nullptr)
4655       outs() << format(" %.*s", left, name);
4656     outs() << "\n";
4657     outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
4658     outs() << "\t\t  instanceMethods "
4659            << format("0x%" PRIx32, pc.instanceMethods)
4660            << " (struct method_list_t *)\n";
4661     if (pc.instanceMethods != 0)
4662       print_method_list32_t(pc.instanceMethods, info, "\t");
4663     outs() << "\t\t     classMethods " << format("0x%" PRIx32, pc.classMethods)
4664            << " (struct method_list_t *)\n";
4665     if (pc.classMethods != 0)
4666       print_method_list32_t(pc.classMethods, info, "\t");
4667     outs() << "\t  optionalInstanceMethods "
4668            << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
4669     outs() << "\t     optionalClassMethods "
4670            << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
4671     outs() << "\t       instanceProperties "
4672            << format("0x%" PRIx32, pc.instanceProperties) << "\n";
4673     p += sizeof(uint32_t);
4674     offset += sizeof(uint32_t);
4675   }
4676 }
4677 
4678 static void print_indent(uint32_t indent) {
4679   for (uint32_t i = 0; i < indent;) {
4680     if (indent - i >= 8) {
4681       outs() << "\t";
4682       i += 8;
4683     } else {
4684       for (uint32_t j = i; j < indent; j++)
4685         outs() << " ";
4686       return;
4687     }
4688   }
4689 }
4690 
4691 static bool print_method_description_list(uint32_t p, uint32_t indent,
4692                                           struct DisassembleInfo *info) {
4693   uint32_t offset, left, xleft;
4694   SectionRef S;
4695   struct objc_method_description_list_t mdl;
4696   struct objc_method_description_t md;
4697   const char *r, *list, *name;
4698   int32_t i;
4699 
4700   r = get_pointer_32(p, offset, left, S, info, true);
4701   if (r == nullptr)
4702     return true;
4703 
4704   outs() << "\n";
4705   if (left > sizeof(struct objc_method_description_list_t)) {
4706     memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
4707   } else {
4708     print_indent(indent);
4709     outs() << " objc_method_description_list extends past end of the section\n";
4710     memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
4711     memcpy(&mdl, r, left);
4712   }
4713   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4714     swapStruct(mdl);
4715 
4716   print_indent(indent);
4717   outs() << "        count " << mdl.count << "\n";
4718 
4719   list = r + sizeof(struct objc_method_description_list_t);
4720   for (i = 0; i < mdl.count; i++) {
4721     if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
4722       print_indent(indent);
4723       outs() << " remaining list entries extend past the of the section\n";
4724       break;
4725     }
4726     print_indent(indent);
4727     outs() << "        list[" << i << "]\n";
4728     memcpy(&md, list + i * sizeof(struct objc_method_description_t),
4729            sizeof(struct objc_method_description_t));
4730     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4731       swapStruct(md);
4732 
4733     print_indent(indent);
4734     outs() << "             name " << format("0x%08" PRIx32, md.name);
4735     if (info->verbose) {
4736       name = get_pointer_32(md.name, offset, xleft, S, info, true);
4737       if (name != nullptr)
4738         outs() << format(" %.*s", xleft, name);
4739       else
4740         outs() << " (not in an __OBJC section)";
4741     }
4742     outs() << "\n";
4743 
4744     print_indent(indent);
4745     outs() << "            types " << format("0x%08" PRIx32, md.types);
4746     if (info->verbose) {
4747       name = get_pointer_32(md.types, offset, xleft, S, info, true);
4748       if (name != nullptr)
4749         outs() << format(" %.*s", xleft, name);
4750       else
4751         outs() << " (not in an __OBJC section)";
4752     }
4753     outs() << "\n";
4754   }
4755   return false;
4756 }
4757 
4758 static bool print_protocol_list(uint32_t p, uint32_t indent,
4759                                 struct DisassembleInfo *info);
4760 
4761 static bool print_protocol(uint32_t p, uint32_t indent,
4762                            struct DisassembleInfo *info) {
4763   uint32_t offset, left;
4764   SectionRef S;
4765   struct objc_protocol_t protocol;
4766   const char *r, *name;
4767 
4768   r = get_pointer_32(p, offset, left, S, info, true);
4769   if (r == nullptr)
4770     return true;
4771 
4772   outs() << "\n";
4773   if (left >= sizeof(struct objc_protocol_t)) {
4774     memcpy(&protocol, r, sizeof(struct objc_protocol_t));
4775   } else {
4776     print_indent(indent);
4777     outs() << "            Protocol extends past end of the section\n";
4778     memset(&protocol, '\0', sizeof(struct objc_protocol_t));
4779     memcpy(&protocol, r, left);
4780   }
4781   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4782     swapStruct(protocol);
4783 
4784   print_indent(indent);
4785   outs() << "              isa " << format("0x%08" PRIx32, protocol.isa)
4786          << "\n";
4787 
4788   print_indent(indent);
4789   outs() << "    protocol_name "
4790          << format("0x%08" PRIx32, protocol.protocol_name);
4791   if (info->verbose) {
4792     name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
4793     if (name != nullptr)
4794       outs() << format(" %.*s", left, name);
4795     else
4796       outs() << " (not in an __OBJC section)";
4797   }
4798   outs() << "\n";
4799 
4800   print_indent(indent);
4801   outs() << "    protocol_list "
4802          << format("0x%08" PRIx32, protocol.protocol_list);
4803   if (print_protocol_list(protocol.protocol_list, indent + 4, info))
4804     outs() << " (not in an __OBJC section)\n";
4805 
4806   print_indent(indent);
4807   outs() << " instance_methods "
4808          << format("0x%08" PRIx32, protocol.instance_methods);
4809   if (print_method_description_list(protocol.instance_methods, indent, info))
4810     outs() << " (not in an __OBJC section)\n";
4811 
4812   print_indent(indent);
4813   outs() << "    class_methods "
4814          << format("0x%08" PRIx32, protocol.class_methods);
4815   if (print_method_description_list(protocol.class_methods, indent, info))
4816     outs() << " (not in an __OBJC section)\n";
4817 
4818   return false;
4819 }
4820 
4821 static bool print_protocol_list(uint32_t p, uint32_t indent,
4822                                 struct DisassembleInfo *info) {
4823   uint32_t offset, left, l;
4824   SectionRef S;
4825   struct objc_protocol_list_t protocol_list;
4826   const char *r, *list;
4827   int32_t i;
4828 
4829   r = get_pointer_32(p, offset, left, S, info, true);
4830   if (r == nullptr)
4831     return true;
4832 
4833   outs() << "\n";
4834   if (left > sizeof(struct objc_protocol_list_t)) {
4835     memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
4836   } else {
4837     outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
4838     memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
4839     memcpy(&protocol_list, r, left);
4840   }
4841   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4842     swapStruct(protocol_list);
4843 
4844   print_indent(indent);
4845   outs() << "         next " << format("0x%08" PRIx32, protocol_list.next)
4846          << "\n";
4847   print_indent(indent);
4848   outs() << "        count " << protocol_list.count << "\n";
4849 
4850   list = r + sizeof(struct objc_protocol_list_t);
4851   for (i = 0; i < protocol_list.count; i++) {
4852     if ((i + 1) * sizeof(uint32_t) > left) {
4853       outs() << "\t\t remaining list entries extend past the of the section\n";
4854       break;
4855     }
4856     memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
4857     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4858       sys::swapByteOrder(l);
4859 
4860     print_indent(indent);
4861     outs() << "      list[" << i << "] " << format("0x%08" PRIx32, l);
4862     if (print_protocol(l, indent, info))
4863       outs() << "(not in an __OBJC section)\n";
4864   }
4865   return false;
4866 }
4867 
4868 static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
4869   struct ivar_list64_t il;
4870   struct ivar64_t i;
4871   const char *r;
4872   uint32_t offset, xoffset, left, j;
4873   SectionRef S, xS;
4874   const char *name, *sym_name, *ivar_offset_p;
4875   uint64_t ivar_offset, n_value;
4876 
4877   r = get_pointer_64(p, offset, left, S, info);
4878   if (r == nullptr)
4879     return;
4880   memset(&il, '\0', sizeof(struct ivar_list64_t));
4881   if (left < sizeof(struct ivar_list64_t)) {
4882     memcpy(&il, r, left);
4883     outs() << "   (ivar_list_t entends past the end of the section)\n";
4884   } else
4885     memcpy(&il, r, sizeof(struct ivar_list64_t));
4886   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4887     swapStruct(il);
4888   outs() << "                    entsize " << il.entsize << "\n";
4889   outs() << "                      count " << il.count << "\n";
4890 
4891   p += sizeof(struct ivar_list64_t);
4892   offset += sizeof(struct ivar_list64_t);
4893   for (j = 0; j < il.count; j++) {
4894     r = get_pointer_64(p, offset, left, S, info);
4895     if (r == nullptr)
4896       return;
4897     memset(&i, '\0', sizeof(struct ivar64_t));
4898     if (left < sizeof(struct ivar64_t)) {
4899       memcpy(&i, r, left);
4900       outs() << "   (ivar_t entends past the end of the section)\n";
4901     } else
4902       memcpy(&i, r, sizeof(struct ivar64_t));
4903     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4904       swapStruct(i);
4905 
4906     outs() << "\t\t\t   offset ";
4907     sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
4908                              info, n_value, i.offset);
4909     if (n_value != 0) {
4910       if (info->verbose && sym_name != nullptr)
4911         outs() << sym_name;
4912       else
4913         outs() << format("0x%" PRIx64, n_value);
4914       if (i.offset != 0)
4915         outs() << " + " << format("0x%" PRIx64, i.offset);
4916     } else
4917       outs() << format("0x%" PRIx64, i.offset);
4918     ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
4919     if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4920       memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4921       if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4922         sys::swapByteOrder(ivar_offset);
4923       outs() << " " << ivar_offset << "\n";
4924     } else
4925       outs() << "\n";
4926 
4927     outs() << "\t\t\t     name ";
4928     sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
4929                              n_value, i.name);
4930     if (n_value != 0) {
4931       if (info->verbose && sym_name != nullptr)
4932         outs() << sym_name;
4933       else
4934         outs() << format("0x%" PRIx64, n_value);
4935       if (i.name != 0)
4936         outs() << " + " << format("0x%" PRIx64, i.name);
4937     } else
4938       outs() << format("0x%" PRIx64, i.name);
4939     name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
4940     if (name != nullptr)
4941       outs() << format(" %.*s", left, name);
4942     outs() << "\n";
4943 
4944     outs() << "\t\t\t     type ";
4945     sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
4946                              n_value, i.name);
4947     name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
4948     if (n_value != 0) {
4949       if (info->verbose && sym_name != nullptr)
4950         outs() << sym_name;
4951       else
4952         outs() << format("0x%" PRIx64, n_value);
4953       if (i.type != 0)
4954         outs() << " + " << format("0x%" PRIx64, i.type);
4955     } else
4956       outs() << format("0x%" PRIx64, i.type);
4957     if (name != nullptr)
4958       outs() << format(" %.*s", left, name);
4959     outs() << "\n";
4960 
4961     outs() << "\t\t\talignment " << i.alignment << "\n";
4962     outs() << "\t\t\t     size " << i.size << "\n";
4963 
4964     p += sizeof(struct ivar64_t);
4965     offset += sizeof(struct ivar64_t);
4966   }
4967 }
4968 
4969 static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4970   struct ivar_list32_t il;
4971   struct ivar32_t i;
4972   const char *r;
4973   uint32_t offset, xoffset, left, j;
4974   SectionRef S, xS;
4975   const char *name, *ivar_offset_p;
4976   uint32_t ivar_offset;
4977 
4978   r = get_pointer_32(p, offset, left, S, info);
4979   if (r == nullptr)
4980     return;
4981   memset(&il, '\0', sizeof(struct ivar_list32_t));
4982   if (left < sizeof(struct ivar_list32_t)) {
4983     memcpy(&il, r, left);
4984     outs() << "   (ivar_list_t entends past the end of the section)\n";
4985   } else
4986     memcpy(&il, r, sizeof(struct ivar_list32_t));
4987   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4988     swapStruct(il);
4989   outs() << "                    entsize " << il.entsize << "\n";
4990   outs() << "                      count " << il.count << "\n";
4991 
4992   p += sizeof(struct ivar_list32_t);
4993   offset += sizeof(struct ivar_list32_t);
4994   for (j = 0; j < il.count; j++) {
4995     r = get_pointer_32(p, offset, left, S, info);
4996     if (r == nullptr)
4997       return;
4998     memset(&i, '\0', sizeof(struct ivar32_t));
4999     if (left < sizeof(struct ivar32_t)) {
5000       memcpy(&i, r, left);
5001       outs() << "   (ivar_t entends past the end of the section)\n";
5002     } else
5003       memcpy(&i, r, sizeof(struct ivar32_t));
5004     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5005       swapStruct(i);
5006 
5007     outs() << "\t\t\t   offset " << format("0x%" PRIx32, i.offset);
5008     ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
5009     if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
5010       memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
5011       if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5012         sys::swapByteOrder(ivar_offset);
5013       outs() << " " << ivar_offset << "\n";
5014     } else
5015       outs() << "\n";
5016 
5017     outs() << "\t\t\t     name " << format("0x%" PRIx32, i.name);
5018     name = get_pointer_32(i.name, xoffset, left, xS, info);
5019     if (name != nullptr)
5020       outs() << format(" %.*s", left, name);
5021     outs() << "\n";
5022 
5023     outs() << "\t\t\t     type " << format("0x%" PRIx32, i.type);
5024     name = get_pointer_32(i.type, xoffset, left, xS, info);
5025     if (name != nullptr)
5026       outs() << format(" %.*s", left, name);
5027     outs() << "\n";
5028 
5029     outs() << "\t\t\talignment " << i.alignment << "\n";
5030     outs() << "\t\t\t     size " << i.size << "\n";
5031 
5032     p += sizeof(struct ivar32_t);
5033     offset += sizeof(struct ivar32_t);
5034   }
5035 }
5036 
5037 static void print_objc_property_list64(uint64_t p,
5038                                        struct DisassembleInfo *info) {
5039   struct objc_property_list64 opl;
5040   struct objc_property64 op;
5041   const char *r;
5042   uint32_t offset, xoffset, left, j;
5043   SectionRef S, xS;
5044   const char *name, *sym_name;
5045   uint64_t n_value;
5046 
5047   r = get_pointer_64(p, offset, left, S, info);
5048   if (r == nullptr)
5049     return;
5050   memset(&opl, '\0', sizeof(struct objc_property_list64));
5051   if (left < sizeof(struct objc_property_list64)) {
5052     memcpy(&opl, r, left);
5053     outs() << "   (objc_property_list entends past the end of the section)\n";
5054   } else
5055     memcpy(&opl, r, sizeof(struct objc_property_list64));
5056   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5057     swapStruct(opl);
5058   outs() << "                    entsize " << opl.entsize << "\n";
5059   outs() << "                      count " << opl.count << "\n";
5060 
5061   p += sizeof(struct objc_property_list64);
5062   offset += sizeof(struct objc_property_list64);
5063   for (j = 0; j < opl.count; j++) {
5064     r = get_pointer_64(p, offset, left, S, info);
5065     if (r == nullptr)
5066       return;
5067     memset(&op, '\0', sizeof(struct objc_property64));
5068     if (left < sizeof(struct objc_property64)) {
5069       memcpy(&op, r, left);
5070       outs() << "   (objc_property entends past the end of the section)\n";
5071     } else
5072       memcpy(&op, r, sizeof(struct objc_property64));
5073     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5074       swapStruct(op);
5075 
5076     outs() << "\t\t\t     name ";
5077     sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
5078                              info, n_value, op.name);
5079     if (n_value != 0) {
5080       if (info->verbose && sym_name != nullptr)
5081         outs() << sym_name;
5082       else
5083         outs() << format("0x%" PRIx64, n_value);
5084       if (op.name != 0)
5085         outs() << " + " << format("0x%" PRIx64, op.name);
5086     } else
5087       outs() << format("0x%" PRIx64, op.name);
5088     name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
5089     if (name != nullptr)
5090       outs() << format(" %.*s", left, name);
5091     outs() << "\n";
5092 
5093     outs() << "\t\t\tattributes ";
5094     sym_name =
5095         get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
5096                       info, n_value, op.attributes);
5097     if (n_value != 0) {
5098       if (info->verbose && sym_name != nullptr)
5099         outs() << sym_name;
5100       else
5101         outs() << format("0x%" PRIx64, n_value);
5102       if (op.attributes != 0)
5103         outs() << " + " << format("0x%" PRIx64, op.attributes);
5104     } else
5105       outs() << format("0x%" PRIx64, op.attributes);
5106     name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
5107     if (name != nullptr)
5108       outs() << format(" %.*s", left, name);
5109     outs() << "\n";
5110 
5111     p += sizeof(struct objc_property64);
5112     offset += sizeof(struct objc_property64);
5113   }
5114 }
5115 
5116 static void print_objc_property_list32(uint32_t p,
5117                                        struct DisassembleInfo *info) {
5118   struct objc_property_list32 opl;
5119   struct objc_property32 op;
5120   const char *r;
5121   uint32_t offset, xoffset, left, j;
5122   SectionRef S, xS;
5123   const char *name;
5124 
5125   r = get_pointer_32(p, offset, left, S, info);
5126   if (r == nullptr)
5127     return;
5128   memset(&opl, '\0', sizeof(struct objc_property_list32));
5129   if (left < sizeof(struct objc_property_list32)) {
5130     memcpy(&opl, r, left);
5131     outs() << "   (objc_property_list entends past the end of the section)\n";
5132   } else
5133     memcpy(&opl, r, sizeof(struct objc_property_list32));
5134   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5135     swapStruct(opl);
5136   outs() << "                    entsize " << opl.entsize << "\n";
5137   outs() << "                      count " << opl.count << "\n";
5138 
5139   p += sizeof(struct objc_property_list32);
5140   offset += sizeof(struct objc_property_list32);
5141   for (j = 0; j < opl.count; j++) {
5142     r = get_pointer_32(p, offset, left, S, info);
5143     if (r == nullptr)
5144       return;
5145     memset(&op, '\0', sizeof(struct objc_property32));
5146     if (left < sizeof(struct objc_property32)) {
5147       memcpy(&op, r, left);
5148       outs() << "   (objc_property entends past the end of the section)\n";
5149     } else
5150       memcpy(&op, r, sizeof(struct objc_property32));
5151     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5152       swapStruct(op);
5153 
5154     outs() << "\t\t\t     name " << format("0x%" PRIx32, op.name);
5155     name = get_pointer_32(op.name, xoffset, left, xS, info);
5156     if (name != nullptr)
5157       outs() << format(" %.*s", left, name);
5158     outs() << "\n";
5159 
5160     outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
5161     name = get_pointer_32(op.attributes, xoffset, left, xS, info);
5162     if (name != nullptr)
5163       outs() << format(" %.*s", left, name);
5164     outs() << "\n";
5165 
5166     p += sizeof(struct objc_property32);
5167     offset += sizeof(struct objc_property32);
5168   }
5169 }
5170 
5171 static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
5172                                bool &is_meta_class) {
5173   struct class_ro64_t cro;
5174   const char *r;
5175   uint32_t offset, xoffset, left;
5176   SectionRef S, xS;
5177   const char *name, *sym_name;
5178   uint64_t n_value;
5179 
5180   r = get_pointer_64(p, offset, left, S, info);
5181   if (r == nullptr || left < sizeof(struct class_ro64_t))
5182     return false;
5183   memcpy(&cro, r, sizeof(struct class_ro64_t));
5184   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5185     swapStruct(cro);
5186   outs() << "                    flags " << format("0x%" PRIx32, cro.flags);
5187   if (cro.flags & RO_META)
5188     outs() << " RO_META";
5189   if (cro.flags & RO_ROOT)
5190     outs() << " RO_ROOT";
5191   if (cro.flags & RO_HAS_CXX_STRUCTORS)
5192     outs() << " RO_HAS_CXX_STRUCTORS";
5193   outs() << "\n";
5194   outs() << "            instanceStart " << cro.instanceStart << "\n";
5195   outs() << "             instanceSize " << cro.instanceSize << "\n";
5196   outs() << "                 reserved " << format("0x%" PRIx32, cro.reserved)
5197          << "\n";
5198   outs() << "               ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
5199          << "\n";
5200   print_layout_map64(cro.ivarLayout, info);
5201 
5202   outs() << "                     name ";
5203   sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
5204                            info, n_value, cro.name);
5205   if (n_value != 0) {
5206     if (info->verbose && sym_name != nullptr)
5207       outs() << sym_name;
5208     else
5209       outs() << format("0x%" PRIx64, n_value);
5210     if (cro.name != 0)
5211       outs() << " + " << format("0x%" PRIx64, cro.name);
5212   } else
5213     outs() << format("0x%" PRIx64, cro.name);
5214   name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
5215   if (name != nullptr)
5216     outs() << format(" %.*s", left, name);
5217   outs() << "\n";
5218 
5219   outs() << "              baseMethods ";
5220   sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
5221                            S, info, n_value, cro.baseMethods);
5222   if (n_value != 0) {
5223     if (info->verbose && sym_name != nullptr)
5224       outs() << sym_name;
5225     else
5226       outs() << format("0x%" PRIx64, n_value);
5227     if (cro.baseMethods != 0)
5228       outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
5229   } else
5230     outs() << format("0x%" PRIx64, cro.baseMethods);
5231   outs() << " (struct method_list_t *)\n";
5232   if (cro.baseMethods + n_value != 0)
5233     print_method_list64_t(cro.baseMethods + n_value, info, "");
5234 
5235   outs() << "            baseProtocols ";
5236   sym_name =
5237       get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
5238                     info, n_value, cro.baseProtocols);
5239   if (n_value != 0) {
5240     if (info->verbose && sym_name != nullptr)
5241       outs() << sym_name;
5242     else
5243       outs() << format("0x%" PRIx64, n_value);
5244     if (cro.baseProtocols != 0)
5245       outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
5246   } else
5247     outs() << format("0x%" PRIx64, cro.baseProtocols);
5248   outs() << "\n";
5249   if (cro.baseProtocols + n_value != 0)
5250     print_protocol_list64_t(cro.baseProtocols + n_value, info);
5251 
5252   outs() << "                    ivars ";
5253   sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
5254                            info, n_value, cro.ivars);
5255   if (n_value != 0) {
5256     if (info->verbose && sym_name != nullptr)
5257       outs() << sym_name;
5258     else
5259       outs() << format("0x%" PRIx64, n_value);
5260     if (cro.ivars != 0)
5261       outs() << " + " << format("0x%" PRIx64, cro.ivars);
5262   } else
5263     outs() << format("0x%" PRIx64, cro.ivars);
5264   outs() << "\n";
5265   if (cro.ivars + n_value != 0)
5266     print_ivar_list64_t(cro.ivars + n_value, info);
5267 
5268   outs() << "           weakIvarLayout ";
5269   sym_name =
5270       get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
5271                     info, n_value, cro.weakIvarLayout);
5272   if (n_value != 0) {
5273     if (info->verbose && sym_name != nullptr)
5274       outs() << sym_name;
5275     else
5276       outs() << format("0x%" PRIx64, n_value);
5277     if (cro.weakIvarLayout != 0)
5278       outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
5279   } else
5280     outs() << format("0x%" PRIx64, cro.weakIvarLayout);
5281   outs() << "\n";
5282   print_layout_map64(cro.weakIvarLayout + n_value, info);
5283 
5284   outs() << "           baseProperties ";
5285   sym_name =
5286       get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
5287                     info, n_value, cro.baseProperties);
5288   if (n_value != 0) {
5289     if (info->verbose && sym_name != nullptr)
5290       outs() << sym_name;
5291     else
5292       outs() << format("0x%" PRIx64, n_value);
5293     if (cro.baseProperties != 0)
5294       outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
5295   } else
5296     outs() << format("0x%" PRIx64, cro.baseProperties);
5297   outs() << "\n";
5298   if (cro.baseProperties + n_value != 0)
5299     print_objc_property_list64(cro.baseProperties + n_value, info);
5300 
5301   is_meta_class = (cro.flags & RO_META) != 0;
5302   return true;
5303 }
5304 
5305 static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
5306                                bool &is_meta_class) {
5307   struct class_ro32_t cro;
5308   const char *r;
5309   uint32_t offset, xoffset, left;
5310   SectionRef S, xS;
5311   const char *name;
5312 
5313   r = get_pointer_32(p, offset, left, S, info);
5314   if (r == nullptr)
5315     return false;
5316   memset(&cro, '\0', sizeof(struct class_ro32_t));
5317   if (left < sizeof(struct class_ro32_t)) {
5318     memcpy(&cro, r, left);
5319     outs() << "   (class_ro_t entends past the end of the section)\n";
5320   } else
5321     memcpy(&cro, r, sizeof(struct class_ro32_t));
5322   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5323     swapStruct(cro);
5324   outs() << "                    flags " << format("0x%" PRIx32, cro.flags);
5325   if (cro.flags & RO_META)
5326     outs() << " RO_META";
5327   if (cro.flags & RO_ROOT)
5328     outs() << " RO_ROOT";
5329   if (cro.flags & RO_HAS_CXX_STRUCTORS)
5330     outs() << " RO_HAS_CXX_STRUCTORS";
5331   outs() << "\n";
5332   outs() << "            instanceStart " << cro.instanceStart << "\n";
5333   outs() << "             instanceSize " << cro.instanceSize << "\n";
5334   outs() << "               ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
5335          << "\n";
5336   print_layout_map32(cro.ivarLayout, info);
5337 
5338   outs() << "                     name " << format("0x%" PRIx32, cro.name);
5339   name = get_pointer_32(cro.name, xoffset, left, xS, info);
5340   if (name != nullptr)
5341     outs() << format(" %.*s", left, name);
5342   outs() << "\n";
5343 
5344   outs() << "              baseMethods "
5345          << format("0x%" PRIx32, cro.baseMethods)
5346          << " (struct method_list_t *)\n";
5347   if (cro.baseMethods != 0)
5348     print_method_list32_t(cro.baseMethods, info, "");
5349 
5350   outs() << "            baseProtocols "
5351          << format("0x%" PRIx32, cro.baseProtocols) << "\n";
5352   if (cro.baseProtocols != 0)
5353     print_protocol_list32_t(cro.baseProtocols, info);
5354   outs() << "                    ivars " << format("0x%" PRIx32, cro.ivars)
5355          << "\n";
5356   if (cro.ivars != 0)
5357     print_ivar_list32_t(cro.ivars, info);
5358   outs() << "           weakIvarLayout "
5359          << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
5360   print_layout_map32(cro.weakIvarLayout, info);
5361   outs() << "           baseProperties "
5362          << format("0x%" PRIx32, cro.baseProperties) << "\n";
5363   if (cro.baseProperties != 0)
5364     print_objc_property_list32(cro.baseProperties, info);
5365   is_meta_class = (cro.flags & RO_META) != 0;
5366   return true;
5367 }
5368 
5369 static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
5370   struct class64_t c;
5371   const char *r;
5372   uint32_t offset, left;
5373   SectionRef S;
5374   const char *name;
5375   uint64_t isa_n_value, n_value;
5376 
5377   r = get_pointer_64(p, offset, left, S, info);
5378   if (r == nullptr || left < sizeof(struct class64_t))
5379     return;
5380   memcpy(&c, r, sizeof(struct class64_t));
5381   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5382     swapStruct(c);
5383 
5384   outs() << "           isa " << format("0x%" PRIx64, c.isa);
5385   name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
5386                        isa_n_value, c.isa);
5387   if (name != nullptr)
5388     outs() << " " << name;
5389   outs() << "\n";
5390 
5391   outs() << "    superclass " << format("0x%" PRIx64, c.superclass);
5392   name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
5393                        n_value, c.superclass);
5394   if (name != nullptr)
5395     outs() << " " << name;
5396   else {
5397     name = get_dyld_bind_info_symbolname(S.getAddress() +
5398              offset + offsetof(struct class64_t, superclass), info);
5399     if (name != nullptr)
5400       outs() << " " << name;
5401   }
5402   outs() << "\n";
5403 
5404   outs() << "         cache " << format("0x%" PRIx64, c.cache);
5405   name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
5406                        n_value, c.cache);
5407   if (name != nullptr)
5408     outs() << " " << name;
5409   outs() << "\n";
5410 
5411   outs() << "        vtable " << format("0x%" PRIx64, c.vtable);
5412   name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
5413                        n_value, c.vtable);
5414   if (name != nullptr)
5415     outs() << " " << name;
5416   outs() << "\n";
5417 
5418   name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
5419                        n_value, c.data);
5420   outs() << "          data ";
5421   if (n_value != 0) {
5422     if (info->verbose && name != nullptr)
5423       outs() << name;
5424     else
5425       outs() << format("0x%" PRIx64, n_value);
5426     if (c.data != 0)
5427       outs() << " + " << format("0x%" PRIx64, c.data);
5428   } else
5429     outs() << format("0x%" PRIx64, c.data);
5430   outs() << " (struct class_ro_t *)";
5431 
5432   // This is a Swift class if some of the low bits of the pointer are set.
5433   if ((c.data + n_value) & 0x7)
5434     outs() << " Swift class";
5435   outs() << "\n";
5436   bool is_meta_class;
5437   if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
5438     return;
5439 
5440   if (!is_meta_class &&
5441       c.isa + isa_n_value != p &&
5442       c.isa + isa_n_value != 0 &&
5443       info->depth < 100) {
5444       info->depth++;
5445       outs() << "Meta Class\n";
5446       print_class64_t(c.isa + isa_n_value, info);
5447   }
5448 }
5449 
5450 static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
5451   struct class32_t c;
5452   const char *r;
5453   uint32_t offset, left;
5454   SectionRef S;
5455   const char *name;
5456 
5457   r = get_pointer_32(p, offset, left, S, info);
5458   if (r == nullptr)
5459     return;
5460   memset(&c, '\0', sizeof(struct class32_t));
5461   if (left < sizeof(struct class32_t)) {
5462     memcpy(&c, r, left);
5463     outs() << "   (class_t entends past the end of the section)\n";
5464   } else
5465     memcpy(&c, r, sizeof(struct class32_t));
5466   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5467     swapStruct(c);
5468 
5469   outs() << "           isa " << format("0x%" PRIx32, c.isa);
5470   name =
5471       get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
5472   if (name != nullptr)
5473     outs() << " " << name;
5474   outs() << "\n";
5475 
5476   outs() << "    superclass " << format("0x%" PRIx32, c.superclass);
5477   name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
5478                        c.superclass);
5479   if (name != nullptr)
5480     outs() << " " << name;
5481   outs() << "\n";
5482 
5483   outs() << "         cache " << format("0x%" PRIx32, c.cache);
5484   name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
5485                        c.cache);
5486   if (name != nullptr)
5487     outs() << " " << name;
5488   outs() << "\n";
5489 
5490   outs() << "        vtable " << format("0x%" PRIx32, c.vtable);
5491   name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
5492                        c.vtable);
5493   if (name != nullptr)
5494     outs() << " " << name;
5495   outs() << "\n";
5496 
5497   name =
5498       get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
5499   outs() << "          data " << format("0x%" PRIx32, c.data)
5500          << " (struct class_ro_t *)";
5501 
5502   // This is a Swift class if some of the low bits of the pointer are set.
5503   if (c.data & 0x3)
5504     outs() << " Swift class";
5505   outs() << "\n";
5506   bool is_meta_class;
5507   if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
5508     return;
5509 
5510   if (!is_meta_class) {
5511     outs() << "Meta Class\n";
5512     print_class32_t(c.isa, info);
5513   }
5514 }
5515 
5516 static void print_objc_class_t(struct objc_class_t *objc_class,
5517                                struct DisassembleInfo *info) {
5518   uint32_t offset, left, xleft;
5519   const char *name, *p, *ivar_list;
5520   SectionRef S;
5521   int32_t i;
5522   struct objc_ivar_list_t objc_ivar_list;
5523   struct objc_ivar_t ivar;
5524 
5525   outs() << "\t\t      isa " << format("0x%08" PRIx32, objc_class->isa);
5526   if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
5527     name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
5528     if (name != nullptr)
5529       outs() << format(" %.*s", left, name);
5530     else
5531       outs() << " (not in an __OBJC section)";
5532   }
5533   outs() << "\n";
5534 
5535   outs() << "\t      super_class "
5536          << format("0x%08" PRIx32, objc_class->super_class);
5537   if (info->verbose) {
5538     name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
5539     if (name != nullptr)
5540       outs() << format(" %.*s", left, name);
5541     else
5542       outs() << " (not in an __OBJC section)";
5543   }
5544   outs() << "\n";
5545 
5546   outs() << "\t\t     name " << format("0x%08" PRIx32, objc_class->name);
5547   if (info->verbose) {
5548     name = get_pointer_32(objc_class->name, offset, left, S, info, true);
5549     if (name != nullptr)
5550       outs() << format(" %.*s", left, name);
5551     else
5552       outs() << " (not in an __OBJC section)";
5553   }
5554   outs() << "\n";
5555 
5556   outs() << "\t\t  version " << format("0x%08" PRIx32, objc_class->version)
5557          << "\n";
5558 
5559   outs() << "\t\t     info " << format("0x%08" PRIx32, objc_class->info);
5560   if (info->verbose) {
5561     if (CLS_GETINFO(objc_class, CLS_CLASS))
5562       outs() << " CLS_CLASS";
5563     else if (CLS_GETINFO(objc_class, CLS_META))
5564       outs() << " CLS_META";
5565   }
5566   outs() << "\n";
5567 
5568   outs() << "\t    instance_size "
5569          << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
5570 
5571   p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
5572   outs() << "\t\t    ivars " << format("0x%08" PRIx32, objc_class->ivars);
5573   if (p != nullptr) {
5574     if (left > sizeof(struct objc_ivar_list_t)) {
5575       outs() << "\n";
5576       memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
5577     } else {
5578       outs() << " (entends past the end of the section)\n";
5579       memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
5580       memcpy(&objc_ivar_list, p, left);
5581     }
5582     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5583       swapStruct(objc_ivar_list);
5584     outs() << "\t\t       ivar_count " << objc_ivar_list.ivar_count << "\n";
5585     ivar_list = p + sizeof(struct objc_ivar_list_t);
5586     for (i = 0; i < objc_ivar_list.ivar_count; i++) {
5587       if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
5588         outs() << "\t\t remaining ivar's extend past the of the section\n";
5589         break;
5590       }
5591       memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
5592              sizeof(struct objc_ivar_t));
5593       if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5594         swapStruct(ivar);
5595 
5596       outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
5597       if (info->verbose) {
5598         name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
5599         if (name != nullptr)
5600           outs() << format(" %.*s", xleft, name);
5601         else
5602           outs() << " (not in an __OBJC section)";
5603       }
5604       outs() << "\n";
5605 
5606       outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
5607       if (info->verbose) {
5608         name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
5609         if (name != nullptr)
5610           outs() << format(" %.*s", xleft, name);
5611         else
5612           outs() << " (not in an __OBJC section)";
5613       }
5614       outs() << "\n";
5615 
5616       outs() << "\t\t      ivar_offset "
5617              << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
5618     }
5619   } else {
5620     outs() << " (not in an __OBJC section)\n";
5621   }
5622 
5623   outs() << "\t\t  methods " << format("0x%08" PRIx32, objc_class->methodLists);
5624   if (print_method_list(objc_class->methodLists, info))
5625     outs() << " (not in an __OBJC section)\n";
5626 
5627   outs() << "\t\t    cache " << format("0x%08" PRIx32, objc_class->cache)
5628          << "\n";
5629 
5630   outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
5631   if (print_protocol_list(objc_class->protocols, 16, info))
5632     outs() << " (not in an __OBJC section)\n";
5633 }
5634 
5635 static void print_objc_objc_category_t(struct objc_category_t *objc_category,
5636                                        struct DisassembleInfo *info) {
5637   uint32_t offset, left;
5638   const char *name;
5639   SectionRef S;
5640 
5641   outs() << "\t       category name "
5642          << format("0x%08" PRIx32, objc_category->category_name);
5643   if (info->verbose) {
5644     name = get_pointer_32(objc_category->category_name, offset, left, S, info,
5645                           true);
5646     if (name != nullptr)
5647       outs() << format(" %.*s", left, name);
5648     else
5649       outs() << " (not in an __OBJC section)";
5650   }
5651   outs() << "\n";
5652 
5653   outs() << "\t\t  class name "
5654          << format("0x%08" PRIx32, objc_category->class_name);
5655   if (info->verbose) {
5656     name =
5657         get_pointer_32(objc_category->class_name, offset, left, S, info, true);
5658     if (name != nullptr)
5659       outs() << format(" %.*s", left, name);
5660     else
5661       outs() << " (not in an __OBJC section)";
5662   }
5663   outs() << "\n";
5664 
5665   outs() << "\t    instance methods "
5666          << format("0x%08" PRIx32, objc_category->instance_methods);
5667   if (print_method_list(objc_category->instance_methods, info))
5668     outs() << " (not in an __OBJC section)\n";
5669 
5670   outs() << "\t       class methods "
5671          << format("0x%08" PRIx32, objc_category->class_methods);
5672   if (print_method_list(objc_category->class_methods, info))
5673     outs() << " (not in an __OBJC section)\n";
5674 }
5675 
5676 static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
5677   struct category64_t c;
5678   const char *r;
5679   uint32_t offset, xoffset, left;
5680   SectionRef S, xS;
5681   const char *name, *sym_name;
5682   uint64_t n_value;
5683 
5684   r = get_pointer_64(p, offset, left, S, info);
5685   if (r == nullptr)
5686     return;
5687   memset(&c, '\0', sizeof(struct category64_t));
5688   if (left < sizeof(struct category64_t)) {
5689     memcpy(&c, r, left);
5690     outs() << "   (category_t entends past the end of the section)\n";
5691   } else
5692     memcpy(&c, r, sizeof(struct category64_t));
5693   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5694     swapStruct(c);
5695 
5696   outs() << "              name ";
5697   sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
5698                            info, n_value, c.name);
5699   if (n_value != 0) {
5700     if (info->verbose && sym_name != nullptr)
5701       outs() << sym_name;
5702     else
5703       outs() << format("0x%" PRIx64, n_value);
5704     if (c.name != 0)
5705       outs() << " + " << format("0x%" PRIx64, c.name);
5706   } else
5707     outs() << format("0x%" PRIx64, c.name);
5708   name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
5709   if (name != nullptr)
5710     outs() << format(" %.*s", left, name);
5711   outs() << "\n";
5712 
5713   outs() << "               cls ";
5714   sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
5715                            n_value, c.cls);
5716   if (n_value != 0) {
5717     if (info->verbose && sym_name != nullptr)
5718       outs() << sym_name;
5719     else
5720       outs() << format("0x%" PRIx64, n_value);
5721     if (c.cls != 0)
5722       outs() << " + " << format("0x%" PRIx64, c.cls);
5723   } else
5724     outs() << format("0x%" PRIx64, c.cls);
5725   outs() << "\n";
5726   if (c.cls + n_value != 0)
5727     print_class64_t(c.cls + n_value, info);
5728 
5729   outs() << "   instanceMethods ";
5730   sym_name =
5731       get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
5732                     info, n_value, c.instanceMethods);
5733   if (n_value != 0) {
5734     if (info->verbose && sym_name != nullptr)
5735       outs() << sym_name;
5736     else
5737       outs() << format("0x%" PRIx64, n_value);
5738     if (c.instanceMethods != 0)
5739       outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
5740   } else
5741     outs() << format("0x%" PRIx64, c.instanceMethods);
5742   outs() << "\n";
5743   if (c.instanceMethods + n_value != 0)
5744     print_method_list64_t(c.instanceMethods + n_value, info, "");
5745 
5746   outs() << "      classMethods ";
5747   sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
5748                            S, info, n_value, c.classMethods);
5749   if (n_value != 0) {
5750     if (info->verbose && sym_name != nullptr)
5751       outs() << sym_name;
5752     else
5753       outs() << format("0x%" PRIx64, n_value);
5754     if (c.classMethods != 0)
5755       outs() << " + " << format("0x%" PRIx64, c.classMethods);
5756   } else
5757     outs() << format("0x%" PRIx64, c.classMethods);
5758   outs() << "\n";
5759   if (c.classMethods + n_value != 0)
5760     print_method_list64_t(c.classMethods + n_value, info, "");
5761 
5762   outs() << "         protocols ";
5763   sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
5764                            info, n_value, c.protocols);
5765   if (n_value != 0) {
5766     if (info->verbose && sym_name != nullptr)
5767       outs() << sym_name;
5768     else
5769       outs() << format("0x%" PRIx64, n_value);
5770     if (c.protocols != 0)
5771       outs() << " + " << format("0x%" PRIx64, c.protocols);
5772   } else
5773     outs() << format("0x%" PRIx64, c.protocols);
5774   outs() << "\n";
5775   if (c.protocols + n_value != 0)
5776     print_protocol_list64_t(c.protocols + n_value, info);
5777 
5778   outs() << "instanceProperties ";
5779   sym_name =
5780       get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
5781                     S, info, n_value, c.instanceProperties);
5782   if (n_value != 0) {
5783     if (info->verbose && sym_name != nullptr)
5784       outs() << sym_name;
5785     else
5786       outs() << format("0x%" PRIx64, n_value);
5787     if (c.instanceProperties != 0)
5788       outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
5789   } else
5790     outs() << format("0x%" PRIx64, c.instanceProperties);
5791   outs() << "\n";
5792   if (c.instanceProperties + n_value != 0)
5793     print_objc_property_list64(c.instanceProperties + n_value, info);
5794 }
5795 
5796 static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
5797   struct category32_t c;
5798   const char *r;
5799   uint32_t offset, left;
5800   SectionRef S, xS;
5801   const char *name;
5802 
5803   r = get_pointer_32(p, offset, left, S, info);
5804   if (r == nullptr)
5805     return;
5806   memset(&c, '\0', sizeof(struct category32_t));
5807   if (left < sizeof(struct category32_t)) {
5808     memcpy(&c, r, left);
5809     outs() << "   (category_t entends past the end of the section)\n";
5810   } else
5811     memcpy(&c, r, sizeof(struct category32_t));
5812   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5813     swapStruct(c);
5814 
5815   outs() << "              name " << format("0x%" PRIx32, c.name);
5816   name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
5817                        c.name);
5818   if (name)
5819     outs() << " " << name;
5820   outs() << "\n";
5821 
5822   outs() << "               cls " << format("0x%" PRIx32, c.cls) << "\n";
5823   if (c.cls != 0)
5824     print_class32_t(c.cls, info);
5825   outs() << "   instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
5826          << "\n";
5827   if (c.instanceMethods != 0)
5828     print_method_list32_t(c.instanceMethods, info, "");
5829   outs() << "      classMethods " << format("0x%" PRIx32, c.classMethods)
5830          << "\n";
5831   if (c.classMethods != 0)
5832     print_method_list32_t(c.classMethods, info, "");
5833   outs() << "         protocols " << format("0x%" PRIx32, c.protocols) << "\n";
5834   if (c.protocols != 0)
5835     print_protocol_list32_t(c.protocols, info);
5836   outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
5837          << "\n";
5838   if (c.instanceProperties != 0)
5839     print_objc_property_list32(c.instanceProperties, info);
5840 }
5841 
5842 static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
5843   uint32_t i, left, offset, xoffset;
5844   uint64_t p, n_value;
5845   struct message_ref64 mr;
5846   const char *name, *sym_name;
5847   const char *r;
5848   SectionRef xS;
5849 
5850   if (S == SectionRef())
5851     return;
5852 
5853   StringRef SectName;
5854   Expected<StringRef> SecNameOrErr = S.getName();
5855   if (SecNameOrErr)
5856     SectName = *SecNameOrErr;
5857   else
5858     consumeError(SecNameOrErr.takeError());
5859 
5860   DataRefImpl Ref = S.getRawDataRefImpl();
5861   StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5862   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5863   offset = 0;
5864   for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5865     p = S.getAddress() + i;
5866     r = get_pointer_64(p, offset, left, S, info);
5867     if (r == nullptr)
5868       return;
5869     memset(&mr, '\0', sizeof(struct message_ref64));
5870     if (left < sizeof(struct message_ref64)) {
5871       memcpy(&mr, r, left);
5872       outs() << "   (message_ref entends past the end of the section)\n";
5873     } else
5874       memcpy(&mr, r, sizeof(struct message_ref64));
5875     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5876       swapStruct(mr);
5877 
5878     outs() << "  imp ";
5879     name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
5880                          n_value, mr.imp);
5881     if (n_value != 0) {
5882       outs() << format("0x%" PRIx64, n_value) << " ";
5883       if (mr.imp != 0)
5884         outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
5885     } else
5886       outs() << format("0x%" PRIx64, mr.imp) << " ";
5887     if (name != nullptr)
5888       outs() << " " << name;
5889     outs() << "\n";
5890 
5891     outs() << "  sel ";
5892     sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
5893                              info, n_value, mr.sel);
5894     if (n_value != 0) {
5895       if (info->verbose && sym_name != nullptr)
5896         outs() << sym_name;
5897       else
5898         outs() << format("0x%" PRIx64, n_value);
5899       if (mr.sel != 0)
5900         outs() << " + " << format("0x%" PRIx64, mr.sel);
5901     } else
5902       outs() << format("0x%" PRIx64, mr.sel);
5903     name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
5904     if (name != nullptr)
5905       outs() << format(" %.*s", left, name);
5906     outs() << "\n";
5907 
5908     offset += sizeof(struct message_ref64);
5909   }
5910 }
5911 
5912 static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
5913   uint32_t i, left, offset, xoffset, p;
5914   struct message_ref32 mr;
5915   const char *name, *r;
5916   SectionRef xS;
5917 
5918   if (S == SectionRef())
5919     return;
5920 
5921   StringRef SectName;
5922   Expected<StringRef> SecNameOrErr = S.getName();
5923   if (SecNameOrErr)
5924     SectName = *SecNameOrErr;
5925   else
5926     consumeError(SecNameOrErr.takeError());
5927 
5928   DataRefImpl Ref = S.getRawDataRefImpl();
5929   StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5930   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5931   offset = 0;
5932   for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5933     p = S.getAddress() + i;
5934     r = get_pointer_32(p, offset, left, S, info);
5935     if (r == nullptr)
5936       return;
5937     memset(&mr, '\0', sizeof(struct message_ref32));
5938     if (left < sizeof(struct message_ref32)) {
5939       memcpy(&mr, r, left);
5940       outs() << "   (message_ref entends past the end of the section)\n";
5941     } else
5942       memcpy(&mr, r, sizeof(struct message_ref32));
5943     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5944       swapStruct(mr);
5945 
5946     outs() << "  imp " << format("0x%" PRIx32, mr.imp);
5947     name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
5948                          mr.imp);
5949     if (name != nullptr)
5950       outs() << " " << name;
5951     outs() << "\n";
5952 
5953     outs() << "  sel " << format("0x%" PRIx32, mr.sel);
5954     name = get_pointer_32(mr.sel, xoffset, left, xS, info);
5955     if (name != nullptr)
5956       outs() << " " << name;
5957     outs() << "\n";
5958 
5959     offset += sizeof(struct message_ref32);
5960   }
5961 }
5962 
5963 static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
5964   uint32_t left, offset, swift_version;
5965   uint64_t p;
5966   struct objc_image_info64 o;
5967   const char *r;
5968 
5969   if (S == SectionRef())
5970     return;
5971 
5972   StringRef SectName;
5973   Expected<StringRef> SecNameOrErr = S.getName();
5974   if (SecNameOrErr)
5975     SectName = *SecNameOrErr;
5976   else
5977     consumeError(SecNameOrErr.takeError());
5978 
5979   DataRefImpl Ref = S.getRawDataRefImpl();
5980   StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5981   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5982   p = S.getAddress();
5983   r = get_pointer_64(p, offset, left, S, info);
5984   if (r == nullptr)
5985     return;
5986   memset(&o, '\0', sizeof(struct objc_image_info64));
5987   if (left < sizeof(struct objc_image_info64)) {
5988     memcpy(&o, r, left);
5989     outs() << "   (objc_image_info entends past the end of the section)\n";
5990   } else
5991     memcpy(&o, r, sizeof(struct objc_image_info64));
5992   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5993     swapStruct(o);
5994   outs() << "  version " << o.version << "\n";
5995   outs() << "    flags " << format("0x%" PRIx32, o.flags);
5996   if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5997     outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5998   if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5999     outs() << " OBJC_IMAGE_SUPPORTS_GC";
6000   if (o.flags & OBJC_IMAGE_IS_SIMULATED)
6001     outs() << " OBJC_IMAGE_IS_SIMULATED";
6002   if (o.flags & OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES)
6003     outs() << " OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES";
6004   swift_version = (o.flags >> 8) & 0xff;
6005   if (swift_version != 0) {
6006     if (swift_version == 1)
6007       outs() << " Swift 1.0";
6008     else if (swift_version == 2)
6009       outs() << " Swift 1.1";
6010     else if(swift_version == 3)
6011       outs() << " Swift 2.0";
6012     else if(swift_version == 4)
6013       outs() << " Swift 3.0";
6014     else if(swift_version == 5)
6015       outs() << " Swift 4.0";
6016     else if(swift_version == 6)
6017       outs() << " Swift 4.1/Swift 4.2";
6018     else if(swift_version == 7)
6019       outs() << " Swift 5 or later";
6020     else
6021       outs() << " unknown future Swift version (" << swift_version << ")";
6022   }
6023   outs() << "\n";
6024 }
6025 
6026 static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
6027   uint32_t left, offset, swift_version, p;
6028   struct objc_image_info32 o;
6029   const char *r;
6030 
6031   if (S == SectionRef())
6032     return;
6033 
6034   StringRef SectName;
6035   Expected<StringRef> SecNameOrErr = S.getName();
6036   if (SecNameOrErr)
6037     SectName = *SecNameOrErr;
6038   else
6039     consumeError(SecNameOrErr.takeError());
6040 
6041   DataRefImpl Ref = S.getRawDataRefImpl();
6042   StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
6043   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
6044   p = S.getAddress();
6045   r = get_pointer_32(p, offset, left, S, info);
6046   if (r == nullptr)
6047     return;
6048   memset(&o, '\0', sizeof(struct objc_image_info32));
6049   if (left < sizeof(struct objc_image_info32)) {
6050     memcpy(&o, r, left);
6051     outs() << "   (objc_image_info entends past the end of the section)\n";
6052   } else
6053     memcpy(&o, r, sizeof(struct objc_image_info32));
6054   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
6055     swapStruct(o);
6056   outs() << "  version " << o.version << "\n";
6057   outs() << "    flags " << format("0x%" PRIx32, o.flags);
6058   if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
6059     outs() << " OBJC_IMAGE_IS_REPLACEMENT";
6060   if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
6061     outs() << " OBJC_IMAGE_SUPPORTS_GC";
6062   swift_version = (o.flags >> 8) & 0xff;
6063   if (swift_version != 0) {
6064     if (swift_version == 1)
6065       outs() << " Swift 1.0";
6066     else if (swift_version == 2)
6067       outs() << " Swift 1.1";
6068     else if(swift_version == 3)
6069       outs() << " Swift 2.0";
6070     else if(swift_version == 4)
6071       outs() << " Swift 3.0";
6072     else if(swift_version == 5)
6073       outs() << " Swift 4.0";
6074     else if(swift_version == 6)
6075       outs() << " Swift 4.1/Swift 4.2";
6076     else if(swift_version == 7)
6077       outs() << " Swift 5 or later";
6078     else
6079       outs() << " unknown future Swift version (" << swift_version << ")";
6080   }
6081   outs() << "\n";
6082 }
6083 
6084 static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
6085   uint32_t left, offset, p;
6086   struct imageInfo_t o;
6087   const char *r;
6088 
6089   StringRef SectName;
6090   Expected<StringRef> SecNameOrErr = S.getName();
6091   if (SecNameOrErr)
6092     SectName = *SecNameOrErr;
6093   else
6094     consumeError(SecNameOrErr.takeError());
6095 
6096   DataRefImpl Ref = S.getRawDataRefImpl();
6097   StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
6098   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
6099   p = S.getAddress();
6100   r = get_pointer_32(p, offset, left, S, info);
6101   if (r == nullptr)
6102     return;
6103   memset(&o, '\0', sizeof(struct imageInfo_t));
6104   if (left < sizeof(struct imageInfo_t)) {
6105     memcpy(&o, r, left);
6106     outs() << " (imageInfo entends past the end of the section)\n";
6107   } else
6108     memcpy(&o, r, sizeof(struct imageInfo_t));
6109   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
6110     swapStruct(o);
6111   outs() << "  version " << o.version << "\n";
6112   outs() << "    flags " << format("0x%" PRIx32, o.flags);
6113   if (o.flags & 0x1)
6114     outs() << "  F&C";
6115   if (o.flags & 0x2)
6116     outs() << " GC";
6117   if (o.flags & 0x4)
6118     outs() << " GC-only";
6119   else
6120     outs() << " RR";
6121   outs() << "\n";
6122 }
6123 
6124 static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
6125   SymbolAddressMap AddrMap;
6126   if (verbose)
6127     CreateSymbolAddressMap(O, &AddrMap);
6128 
6129   std::vector<SectionRef> Sections;
6130   append_range(Sections, O->sections());
6131 
6132   struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
6133 
6134   SectionRef CL = get_section(O, "__OBJC2", "__class_list");
6135   if (CL == SectionRef())
6136     CL = get_section(O, "__DATA", "__objc_classlist");
6137   if (CL == SectionRef())
6138     CL = get_section(O, "__DATA_CONST", "__objc_classlist");
6139   if (CL == SectionRef())
6140     CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
6141   info.S = CL;
6142   walk_pointer_list_64("class", CL, O, &info, print_class64_t);
6143 
6144   SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
6145   if (CR == SectionRef())
6146     CR = get_section(O, "__DATA", "__objc_classrefs");
6147   if (CR == SectionRef())
6148     CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
6149   if (CR == SectionRef())
6150     CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
6151   info.S = CR;
6152   walk_pointer_list_64("class refs", CR, O, &info, nullptr);
6153 
6154   SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
6155   if (SR == SectionRef())
6156     SR = get_section(O, "__DATA", "__objc_superrefs");
6157   if (SR == SectionRef())
6158     SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
6159   if (SR == SectionRef())
6160     SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
6161   info.S = SR;
6162   walk_pointer_list_64("super refs", SR, O, &info, nullptr);
6163 
6164   SectionRef CA = get_section(O, "__OBJC2", "__category_list");
6165   if (CA == SectionRef())
6166     CA = get_section(O, "__DATA", "__objc_catlist");
6167   if (CA == SectionRef())
6168     CA = get_section(O, "__DATA_CONST", "__objc_catlist");
6169   if (CA == SectionRef())
6170     CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
6171   info.S = CA;
6172   walk_pointer_list_64("category", CA, O, &info, print_category64_t);
6173 
6174   SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
6175   if (PL == SectionRef())
6176     PL = get_section(O, "__DATA", "__objc_protolist");
6177   if (PL == SectionRef())
6178     PL = get_section(O, "__DATA_CONST", "__objc_protolist");
6179   if (PL == SectionRef())
6180     PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
6181   info.S = PL;
6182   walk_pointer_list_64("protocol", PL, O, &info, nullptr);
6183 
6184   SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
6185   if (MR == SectionRef())
6186     MR = get_section(O, "__DATA", "__objc_msgrefs");
6187   if (MR == SectionRef())
6188     MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
6189   if (MR == SectionRef())
6190     MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
6191   info.S = MR;
6192   print_message_refs64(MR, &info);
6193 
6194   SectionRef II = get_section(O, "__OBJC2", "__image_info");
6195   if (II == SectionRef())
6196     II = get_section(O, "__DATA", "__objc_imageinfo");
6197   if (II == SectionRef())
6198     II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
6199   if (II == SectionRef())
6200     II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
6201   info.S = II;
6202   print_image_info64(II, &info);
6203 }
6204 
6205 static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
6206   SymbolAddressMap AddrMap;
6207   if (verbose)
6208     CreateSymbolAddressMap(O, &AddrMap);
6209 
6210   std::vector<SectionRef> Sections;
6211   append_range(Sections, O->sections());
6212 
6213   struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
6214 
6215   SectionRef CL = get_section(O, "__OBJC2", "__class_list");
6216   if (CL == SectionRef())
6217     CL = get_section(O, "__DATA", "__objc_classlist");
6218   if (CL == SectionRef())
6219     CL = get_section(O, "__DATA_CONST", "__objc_classlist");
6220   if (CL == SectionRef())
6221     CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
6222   info.S = CL;
6223   walk_pointer_list_32("class", CL, O, &info, print_class32_t);
6224 
6225   SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
6226   if (CR == SectionRef())
6227     CR = get_section(O, "__DATA", "__objc_classrefs");
6228   if (CR == SectionRef())
6229     CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
6230   if (CR == SectionRef())
6231     CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
6232   info.S = CR;
6233   walk_pointer_list_32("class refs", CR, O, &info, nullptr);
6234 
6235   SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
6236   if (SR == SectionRef())
6237     SR = get_section(O, "__DATA", "__objc_superrefs");
6238   if (SR == SectionRef())
6239     SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
6240   if (SR == SectionRef())
6241     SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
6242   info.S = SR;
6243   walk_pointer_list_32("super refs", SR, O, &info, nullptr);
6244 
6245   SectionRef CA = get_section(O, "__OBJC2", "__category_list");
6246   if (CA == SectionRef())
6247     CA = get_section(O, "__DATA", "__objc_catlist");
6248   if (CA == SectionRef())
6249     CA = get_section(O, "__DATA_CONST", "__objc_catlist");
6250   if (CA == SectionRef())
6251     CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
6252   info.S = CA;
6253   walk_pointer_list_32("category", CA, O, &info, print_category32_t);
6254 
6255   SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
6256   if (PL == SectionRef())
6257     PL = get_section(O, "__DATA", "__objc_protolist");
6258   if (PL == SectionRef())
6259     PL = get_section(O, "__DATA_CONST", "__objc_protolist");
6260   if (PL == SectionRef())
6261     PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
6262   info.S = PL;
6263   walk_pointer_list_32("protocol", PL, O, &info, nullptr);
6264 
6265   SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
6266   if (MR == SectionRef())
6267     MR = get_section(O, "__DATA", "__objc_msgrefs");
6268   if (MR == SectionRef())
6269     MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
6270   if (MR == SectionRef())
6271     MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
6272   info.S = MR;
6273   print_message_refs32(MR, &info);
6274 
6275   SectionRef II = get_section(O, "__OBJC2", "__image_info");
6276   if (II == SectionRef())
6277     II = get_section(O, "__DATA", "__objc_imageinfo");
6278   if (II == SectionRef())
6279     II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
6280   if (II == SectionRef())
6281     II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
6282   info.S = II;
6283   print_image_info32(II, &info);
6284 }
6285 
6286 static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
6287   uint32_t i, j, p, offset, xoffset, left, defs_left, def;
6288   const char *r, *name, *defs;
6289   struct objc_module_t module;
6290   SectionRef S, xS;
6291   struct objc_symtab_t symtab;
6292   struct objc_class_t objc_class;
6293   struct objc_category_t objc_category;
6294 
6295   outs() << "Objective-C segment\n";
6296   S = get_section(O, "__OBJC", "__module_info");
6297   if (S == SectionRef())
6298     return false;
6299 
6300   SymbolAddressMap AddrMap;
6301   if (verbose)
6302     CreateSymbolAddressMap(O, &AddrMap);
6303 
6304   std::vector<SectionRef> Sections;
6305   append_range(Sections, O->sections());
6306 
6307   struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
6308 
6309   for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
6310     p = S.getAddress() + i;
6311     r = get_pointer_32(p, offset, left, S, &info, true);
6312     if (r == nullptr)
6313       return true;
6314     memset(&module, '\0', sizeof(struct objc_module_t));
6315     if (left < sizeof(struct objc_module_t)) {
6316       memcpy(&module, r, left);
6317       outs() << "   (module extends past end of __module_info section)\n";
6318     } else
6319       memcpy(&module, r, sizeof(struct objc_module_t));
6320     if (O->isLittleEndian() != sys::IsLittleEndianHost)
6321       swapStruct(module);
6322 
6323     outs() << "Module " << format("0x%" PRIx32, p) << "\n";
6324     outs() << "    version " << module.version << "\n";
6325     outs() << "       size " << module.size << "\n";
6326     outs() << "       name ";
6327     name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
6328     if (name != nullptr)
6329       outs() << format("%.*s", left, name);
6330     else
6331       outs() << format("0x%08" PRIx32, module.name)
6332              << "(not in an __OBJC section)";
6333     outs() << "\n";
6334 
6335     r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
6336     if (module.symtab == 0 || r == nullptr) {
6337       outs() << "     symtab " << format("0x%08" PRIx32, module.symtab)
6338              << " (not in an __OBJC section)\n";
6339       continue;
6340     }
6341     outs() << "     symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
6342     memset(&symtab, '\0', sizeof(struct objc_symtab_t));
6343     defs_left = 0;
6344     defs = nullptr;
6345     if (left < sizeof(struct objc_symtab_t)) {
6346       memcpy(&symtab, r, left);
6347       outs() << "\tsymtab extends past end of an __OBJC section)\n";
6348     } else {
6349       memcpy(&symtab, r, sizeof(struct objc_symtab_t));
6350       if (left > sizeof(struct objc_symtab_t)) {
6351         defs_left = left - sizeof(struct objc_symtab_t);
6352         defs = r + sizeof(struct objc_symtab_t);
6353       }
6354     }
6355     if (O->isLittleEndian() != sys::IsLittleEndianHost)
6356       swapStruct(symtab);
6357 
6358     outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
6359     r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
6360     outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
6361     if (r == nullptr)
6362       outs() << " (not in an __OBJC section)";
6363     outs() << "\n";
6364     outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
6365     outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
6366     if (symtab.cls_def_cnt > 0)
6367       outs() << "\tClass Definitions\n";
6368     for (j = 0; j < symtab.cls_def_cnt; j++) {
6369       if ((j + 1) * sizeof(uint32_t) > defs_left) {
6370         outs() << "\t(remaining class defs entries entends past the end of the "
6371                << "section)\n";
6372         break;
6373       }
6374       memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
6375       if (O->isLittleEndian() != sys::IsLittleEndianHost)
6376         sys::swapByteOrder(def);
6377 
6378       r = get_pointer_32(def, xoffset, left, xS, &info, true);
6379       outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
6380       if (r != nullptr) {
6381         if (left > sizeof(struct objc_class_t)) {
6382           outs() << "\n";
6383           memcpy(&objc_class, r, sizeof(struct objc_class_t));
6384         } else {
6385           outs() << " (entends past the end of the section)\n";
6386           memset(&objc_class, '\0', sizeof(struct objc_class_t));
6387           memcpy(&objc_class, r, left);
6388         }
6389         if (O->isLittleEndian() != sys::IsLittleEndianHost)
6390           swapStruct(objc_class);
6391         print_objc_class_t(&objc_class, &info);
6392       } else {
6393         outs() << "(not in an __OBJC section)\n";
6394       }
6395 
6396       if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
6397         outs() << "\tMeta Class";
6398         r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
6399         if (r != nullptr) {
6400           if (left > sizeof(struct objc_class_t)) {
6401             outs() << "\n";
6402             memcpy(&objc_class, r, sizeof(struct objc_class_t));
6403           } else {
6404             outs() << " (entends past the end of the section)\n";
6405             memset(&objc_class, '\0', sizeof(struct objc_class_t));
6406             memcpy(&objc_class, r, left);
6407           }
6408           if (O->isLittleEndian() != sys::IsLittleEndianHost)
6409             swapStruct(objc_class);
6410           print_objc_class_t(&objc_class, &info);
6411         } else {
6412           outs() << "(not in an __OBJC section)\n";
6413         }
6414       }
6415     }
6416     if (symtab.cat_def_cnt > 0)
6417       outs() << "\tCategory Definitions\n";
6418     for (j = 0; j < symtab.cat_def_cnt; j++) {
6419       if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
6420         outs() << "\t(remaining category defs entries entends past the end of "
6421                << "the section)\n";
6422         break;
6423       }
6424       memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
6425              sizeof(uint32_t));
6426       if (O->isLittleEndian() != sys::IsLittleEndianHost)
6427         sys::swapByteOrder(def);
6428 
6429       r = get_pointer_32(def, xoffset, left, xS, &info, true);
6430       outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
6431              << format("0x%08" PRIx32, def);
6432       if (r != nullptr) {
6433         if (left > sizeof(struct objc_category_t)) {
6434           outs() << "\n";
6435           memcpy(&objc_category, r, sizeof(struct objc_category_t));
6436         } else {
6437           outs() << " (entends past the end of the section)\n";
6438           memset(&objc_category, '\0', sizeof(struct objc_category_t));
6439           memcpy(&objc_category, r, left);
6440         }
6441         if (O->isLittleEndian() != sys::IsLittleEndianHost)
6442           swapStruct(objc_category);
6443         print_objc_objc_category_t(&objc_category, &info);
6444       } else {
6445         outs() << "(not in an __OBJC section)\n";
6446       }
6447     }
6448   }
6449   const SectionRef II = get_section(O, "__OBJC", "__image_info");
6450   if (II != SectionRef())
6451     print_image_info(II, &info);
6452 
6453   return true;
6454 }
6455 
6456 static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
6457                                 uint32_t size, uint32_t addr) {
6458   SymbolAddressMap AddrMap;
6459   CreateSymbolAddressMap(O, &AddrMap);
6460 
6461   std::vector<SectionRef> Sections;
6462   append_range(Sections, O->sections());
6463 
6464   struct DisassembleInfo info(O, &AddrMap, &Sections, true);
6465 
6466   const char *p;
6467   struct objc_protocol_t protocol;
6468   uint32_t left, paddr;
6469   for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
6470     memset(&protocol, '\0', sizeof(struct objc_protocol_t));
6471     left = size - (p - sect);
6472     if (left < sizeof(struct objc_protocol_t)) {
6473       outs() << "Protocol extends past end of __protocol section\n";
6474       memcpy(&protocol, p, left);
6475     } else
6476       memcpy(&protocol, p, sizeof(struct objc_protocol_t));
6477     if (O->isLittleEndian() != sys::IsLittleEndianHost)
6478       swapStruct(protocol);
6479     paddr = addr + (p - sect);
6480     outs() << "Protocol " << format("0x%" PRIx32, paddr);
6481     if (print_protocol(paddr, 0, &info))
6482       outs() << "(not in an __OBJC section)\n";
6483   }
6484 }
6485 
6486 #ifdef LLVM_HAVE_LIBXAR
6487 static inline void swapStruct(struct xar_header &xar) {
6488   sys::swapByteOrder(xar.magic);
6489   sys::swapByteOrder(xar.size);
6490   sys::swapByteOrder(xar.version);
6491   sys::swapByteOrder(xar.toc_length_compressed);
6492   sys::swapByteOrder(xar.toc_length_uncompressed);
6493   sys::swapByteOrder(xar.cksum_alg);
6494 }
6495 
6496 static void PrintModeVerbose(uint32_t mode) {
6497   switch(mode & S_IFMT){
6498   case S_IFDIR:
6499     outs() << "d";
6500     break;
6501   case S_IFCHR:
6502     outs() << "c";
6503     break;
6504   case S_IFBLK:
6505     outs() << "b";
6506     break;
6507   case S_IFREG:
6508     outs() << "-";
6509     break;
6510   case S_IFLNK:
6511     outs() << "l";
6512     break;
6513   case S_IFSOCK:
6514     outs() << "s";
6515     break;
6516   default:
6517     outs() << "?";
6518     break;
6519   }
6520 
6521   /* owner permissions */
6522   if(mode & S_IREAD)
6523     outs() << "r";
6524   else
6525     outs() << "-";
6526   if(mode & S_IWRITE)
6527     outs() << "w";
6528   else
6529     outs() << "-";
6530   if(mode & S_ISUID)
6531     outs() << "s";
6532   else if(mode & S_IEXEC)
6533     outs() << "x";
6534   else
6535     outs() << "-";
6536 
6537   /* group permissions */
6538   if(mode & (S_IREAD >> 3))
6539     outs() << "r";
6540   else
6541     outs() << "-";
6542   if(mode & (S_IWRITE >> 3))
6543     outs() << "w";
6544   else
6545     outs() << "-";
6546   if(mode & S_ISGID)
6547     outs() << "s";
6548   else if(mode & (S_IEXEC >> 3))
6549     outs() << "x";
6550   else
6551     outs() << "-";
6552 
6553   /* other permissions */
6554   if(mode & (S_IREAD >> 6))
6555     outs() << "r";
6556   else
6557     outs() << "-";
6558   if(mode & (S_IWRITE >> 6))
6559     outs() << "w";
6560   else
6561     outs() << "-";
6562   if(mode & S_ISVTX)
6563     outs() << "t";
6564   else if(mode & (S_IEXEC >> 6))
6565     outs() << "x";
6566   else
6567     outs() << "-";
6568 }
6569 
6570 static void PrintXarFilesSummary(const char *XarFilename, xar_t xar) {
6571   xar_file_t xf;
6572   const char *key, *type, *mode, *user, *group, *size, *mtime, *name, *m;
6573   char *endp;
6574   uint32_t mode_value;
6575 
6576   ScopedXarIter xi;
6577   if (!xi) {
6578     WithColor::error(errs(), "llvm-objdump")
6579         << "can't obtain an xar iterator for xar archive " << XarFilename
6580         << "\n";
6581     return;
6582   }
6583 
6584   // Go through the xar's files.
6585   for (xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)) {
6586     ScopedXarIter xp;
6587     if(!xp){
6588       WithColor::error(errs(), "llvm-objdump")
6589           << "can't obtain an xar iterator for xar archive " << XarFilename
6590           << "\n";
6591       return;
6592     }
6593     type = nullptr;
6594     mode = nullptr;
6595     user = nullptr;
6596     group = nullptr;
6597     size = nullptr;
6598     mtime = nullptr;
6599     name = nullptr;
6600     for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
6601       const char *val = nullptr;
6602       xar_prop_get(xf, key, &val);
6603 #if 0 // Useful for debugging.
6604       outs() << "key: " << key << " value: " << val << "\n";
6605 #endif
6606       if(strcmp(key, "type") == 0)
6607         type = val;
6608       if(strcmp(key, "mode") == 0)
6609         mode = val;
6610       if(strcmp(key, "user") == 0)
6611         user = val;
6612       if(strcmp(key, "group") == 0)
6613         group = val;
6614       if(strcmp(key, "data/size") == 0)
6615         size = val;
6616       if(strcmp(key, "mtime") == 0)
6617         mtime = val;
6618       if(strcmp(key, "name") == 0)
6619         name = val;
6620     }
6621     if(mode != nullptr){
6622       mode_value = strtoul(mode, &endp, 8);
6623       if(*endp != '\0')
6624         outs() << "(mode: \"" << mode << "\" contains non-octal chars) ";
6625       if(strcmp(type, "file") == 0)
6626         mode_value |= S_IFREG;
6627       PrintModeVerbose(mode_value);
6628       outs() << " ";
6629     }
6630     if(user != nullptr)
6631       outs() << format("%10s/", user);
6632     if(group != nullptr)
6633       outs() << format("%-10s ", group);
6634     if(size != nullptr)
6635       outs() << format("%7s ", size);
6636     if(mtime != nullptr){
6637       for(m = mtime; *m != 'T' && *m != '\0'; m++)
6638         outs() << *m;
6639       if(*m == 'T')
6640         m++;
6641       outs() << " ";
6642       for( ; *m != 'Z' && *m != '\0'; m++)
6643         outs() << *m;
6644       outs() << " ";
6645     }
6646     if(name != nullptr)
6647       outs() << name;
6648     outs() << "\n";
6649   }
6650 }
6651 
6652 static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
6653                                 uint32_t size, bool verbose,
6654                                 bool PrintXarHeader, bool PrintXarFileHeaders,
6655                                 std::string XarMemberName) {
6656   if(size < sizeof(struct xar_header)) {
6657     outs() << "size of (__LLVM,__bundle) section too small (smaller than size "
6658               "of struct xar_header)\n";
6659     return;
6660   }
6661   struct xar_header XarHeader;
6662   memcpy(&XarHeader, sect, sizeof(struct xar_header));
6663   if (sys::IsLittleEndianHost)
6664     swapStruct(XarHeader);
6665   if (PrintXarHeader) {
6666     if (!XarMemberName.empty())
6667       outs() << "In xar member " << XarMemberName << ": ";
6668     else
6669       outs() << "For (__LLVM,__bundle) section: ";
6670     outs() << "xar header\n";
6671     if (XarHeader.magic == XAR_HEADER_MAGIC)
6672       outs() << "                  magic XAR_HEADER_MAGIC\n";
6673     else
6674       outs() << "                  magic "
6675              << format_hex(XarHeader.magic, 10, true)
6676              << " (not XAR_HEADER_MAGIC)\n";
6677     outs() << "                   size " << XarHeader.size << "\n";
6678     outs() << "                version " << XarHeader.version << "\n";
6679     outs() << "  toc_length_compressed " << XarHeader.toc_length_compressed
6680            << "\n";
6681     outs() << "toc_length_uncompressed " << XarHeader.toc_length_uncompressed
6682            << "\n";
6683     outs() << "              cksum_alg ";
6684     switch (XarHeader.cksum_alg) {
6685       case XAR_CKSUM_NONE:
6686         outs() << "XAR_CKSUM_NONE\n";
6687         break;
6688       case XAR_CKSUM_SHA1:
6689         outs() << "XAR_CKSUM_SHA1\n";
6690         break;
6691       case XAR_CKSUM_MD5:
6692         outs() << "XAR_CKSUM_MD5\n";
6693         break;
6694 #ifdef XAR_CKSUM_SHA256
6695       case XAR_CKSUM_SHA256:
6696         outs() << "XAR_CKSUM_SHA256\n";
6697         break;
6698 #endif
6699 #ifdef XAR_CKSUM_SHA512
6700       case XAR_CKSUM_SHA512:
6701         outs() << "XAR_CKSUM_SHA512\n";
6702         break;
6703 #endif
6704       default:
6705         outs() << XarHeader.cksum_alg << "\n";
6706     }
6707   }
6708 
6709   SmallString<128> XarFilename;
6710   int FD;
6711   std::error_code XarEC =
6712       sys::fs::createTemporaryFile("llvm-objdump", "xar", FD, XarFilename);
6713   if (XarEC) {
6714     WithColor::error(errs(), "llvm-objdump") << XarEC.message() << "\n";
6715     return;
6716   }
6717   ToolOutputFile XarFile(XarFilename, FD);
6718   raw_fd_ostream &XarOut = XarFile.os();
6719   StringRef XarContents(sect, size);
6720   XarOut << XarContents;
6721   XarOut.close();
6722   if (XarOut.has_error())
6723     return;
6724 
6725   ScopedXarFile xar(XarFilename.c_str(), READ);
6726   if (!xar) {
6727     WithColor::error(errs(), "llvm-objdump")
6728         << "can't create temporary xar archive " << XarFilename << "\n";
6729     return;
6730   }
6731 
6732   SmallString<128> TocFilename;
6733   std::error_code TocEC =
6734       sys::fs::createTemporaryFile("llvm-objdump", "toc", TocFilename);
6735   if (TocEC) {
6736     WithColor::error(errs(), "llvm-objdump") << TocEC.message() << "\n";
6737     return;
6738   }
6739   xar_serialize(xar, TocFilename.c_str());
6740 
6741   if (PrintXarFileHeaders) {
6742     if (!XarMemberName.empty())
6743       outs() << "In xar member " << XarMemberName << ": ";
6744     else
6745       outs() << "For (__LLVM,__bundle) section: ";
6746     outs() << "xar archive files:\n";
6747     PrintXarFilesSummary(XarFilename.c_str(), xar);
6748   }
6749 
6750   ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
6751     MemoryBuffer::getFileOrSTDIN(TocFilename.c_str());
6752   if (std::error_code EC = FileOrErr.getError()) {
6753     WithColor::error(errs(), "llvm-objdump") << EC.message() << "\n";
6754     return;
6755   }
6756   std::unique_ptr<MemoryBuffer> &Buffer = FileOrErr.get();
6757 
6758   if (!XarMemberName.empty())
6759     outs() << "In xar member " << XarMemberName << ": ";
6760   else
6761     outs() << "For (__LLVM,__bundle) section: ";
6762   outs() << "xar table of contents:\n";
6763   outs() << Buffer->getBuffer() << "\n";
6764 
6765   // TODO: Go through the xar's files.
6766   ScopedXarIter xi;
6767   if(!xi){
6768     WithColor::error(errs(), "llvm-objdump")
6769         << "can't obtain an xar iterator for xar archive "
6770         << XarFilename.c_str() << "\n";
6771     return;
6772   }
6773   for(xar_file_t xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)){
6774     const char *key;
6775     const char *member_name, *member_type, *member_size_string;
6776     size_t member_size;
6777 
6778     ScopedXarIter xp;
6779     if(!xp){
6780       WithColor::error(errs(), "llvm-objdump")
6781           << "can't obtain an xar iterator for xar archive "
6782           << XarFilename.c_str() << "\n";
6783       return;
6784     }
6785     member_name = NULL;
6786     member_type = NULL;
6787     member_size_string = NULL;
6788     for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
6789       const char *val = nullptr;
6790       xar_prop_get(xf, key, &val);
6791 #if 0 // Useful for debugging.
6792       outs() << "key: " << key << " value: " << val << "\n";
6793 #endif
6794       if (strcmp(key, "name") == 0)
6795         member_name = val;
6796       if (strcmp(key, "type") == 0)
6797         member_type = val;
6798       if (strcmp(key, "data/size") == 0)
6799         member_size_string = val;
6800     }
6801     /*
6802      * If we find a file with a name, date/size and type properties
6803      * and with the type being "file" see if that is a xar file.
6804      */
6805     if (member_name != NULL && member_type != NULL &&
6806         strcmp(member_type, "file") == 0 &&
6807         member_size_string != NULL){
6808       // Extract the file into a buffer.
6809       char *endptr;
6810       member_size = strtoul(member_size_string, &endptr, 10);
6811       if (*endptr == '\0' && member_size != 0) {
6812         char *buffer;
6813         if (xar_extract_tobuffersz(xar, xf, &buffer, &member_size) == 0) {
6814 #if 0 // Useful for debugging.
6815           outs() << "xar member: " << member_name << " extracted\n";
6816 #endif
6817           // Set the XarMemberName we want to see printed in the header.
6818           std::string OldXarMemberName;
6819           // If XarMemberName is already set this is nested. So
6820           // save the old name and create the nested name.
6821           if (!XarMemberName.empty()) {
6822             OldXarMemberName = XarMemberName;
6823             XarMemberName =
6824                 (Twine("[") + XarMemberName + "]" + member_name).str();
6825           } else {
6826             OldXarMemberName = "";
6827             XarMemberName = member_name;
6828           }
6829           // See if this is could be a xar file (nested).
6830           if (member_size >= sizeof(struct xar_header)) {
6831 #if 0 // Useful for debugging.
6832             outs() << "could be a xar file: " << member_name << "\n";
6833 #endif
6834             memcpy((char *)&XarHeader, buffer, sizeof(struct xar_header));
6835             if (sys::IsLittleEndianHost)
6836               swapStruct(XarHeader);
6837             if (XarHeader.magic == XAR_HEADER_MAGIC)
6838               DumpBitcodeSection(O, buffer, member_size, verbose,
6839                                  PrintXarHeader, PrintXarFileHeaders,
6840                                  XarMemberName);
6841           }
6842           XarMemberName = OldXarMemberName;
6843           delete buffer;
6844         }
6845       }
6846     }
6847   }
6848 }
6849 #endif // defined(LLVM_HAVE_LIBXAR)
6850 
6851 static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
6852   if (O->is64Bit())
6853     printObjc2_64bit_MetaData(O, verbose);
6854   else {
6855     MachO::mach_header H;
6856     H = O->getHeader();
6857     if (H.cputype == MachO::CPU_TYPE_ARM)
6858       printObjc2_32bit_MetaData(O, verbose);
6859     else {
6860       // This is the 32-bit non-arm cputype case.  Which is normally
6861       // the first Objective-C ABI.  But it may be the case of a
6862       // binary for the iOS simulator which is the second Objective-C
6863       // ABI.  In that case printObjc1_32bit_MetaData() will determine that
6864       // and return false.
6865       if (!printObjc1_32bit_MetaData(O, verbose))
6866         printObjc2_32bit_MetaData(O, verbose);
6867     }
6868   }
6869 }
6870 
6871 // GuessLiteralPointer returns a string which for the item in the Mach-O file
6872 // for the address passed in as ReferenceValue for printing as a comment with
6873 // the instruction and also returns the corresponding type of that item
6874 // indirectly through ReferenceType.
6875 //
6876 // If ReferenceValue is an address of literal cstring then a pointer to the
6877 // cstring is returned and ReferenceType is set to
6878 // LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
6879 //
6880 // If ReferenceValue is an address of an Objective-C CFString, Selector ref or
6881 // Class ref that name is returned and the ReferenceType is set accordingly.
6882 //
6883 // Lastly, literals which are Symbol address in a literal pool are looked for
6884 // and if found the symbol name is returned and ReferenceType is set to
6885 // LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
6886 //
6887 // If there is no item in the Mach-O file for the address passed in as
6888 // ReferenceValue nullptr is returned and ReferenceType is unchanged.
6889 static const char *GuessLiteralPointer(uint64_t ReferenceValue,
6890                                        uint64_t ReferencePC,
6891                                        uint64_t *ReferenceType,
6892                                        struct DisassembleInfo *info) {
6893   // First see if there is an external relocation entry at the ReferencePC.
6894   if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
6895     uint64_t sect_addr = info->S.getAddress();
6896     uint64_t sect_offset = ReferencePC - sect_addr;
6897     bool reloc_found = false;
6898     DataRefImpl Rel;
6899     MachO::any_relocation_info RE;
6900     bool isExtern = false;
6901     SymbolRef Symbol;
6902     for (const RelocationRef &Reloc : info->S.relocations()) {
6903       uint64_t RelocOffset = Reloc.getOffset();
6904       if (RelocOffset == sect_offset) {
6905         Rel = Reloc.getRawDataRefImpl();
6906         RE = info->O->getRelocation(Rel);
6907         if (info->O->isRelocationScattered(RE))
6908           continue;
6909         isExtern = info->O->getPlainRelocationExternal(RE);
6910         if (isExtern) {
6911           symbol_iterator RelocSym = Reloc.getSymbol();
6912           Symbol = *RelocSym;
6913         }
6914         reloc_found = true;
6915         break;
6916       }
6917     }
6918     // If there is an external relocation entry for a symbol in a section
6919     // then used that symbol's value for the value of the reference.
6920     if (reloc_found && isExtern) {
6921       if (info->O->getAnyRelocationPCRel(RE)) {
6922         unsigned Type = info->O->getAnyRelocationType(RE);
6923         if (Type == MachO::X86_64_RELOC_SIGNED) {
6924           ReferenceValue = cantFail(Symbol.getValue());
6925         }
6926       }
6927     }
6928   }
6929 
6930   // Look for literals such as Objective-C CFStrings refs, Selector refs,
6931   // Message refs and Class refs.
6932   bool classref, selref, msgref, cfstring;
6933   uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
6934                                                selref, msgref, cfstring);
6935   if (classref && pointer_value == 0) {
6936     // Note the ReferenceValue is a pointer into the __objc_classrefs section.
6937     // And the pointer_value in that section is typically zero as it will be
6938     // set by dyld as part of the "bind information".
6939     const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
6940     if (name != nullptr) {
6941       *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
6942       const char *class_name = strrchr(name, '$');
6943       if (class_name != nullptr && class_name[1] == '_' &&
6944           class_name[2] != '\0') {
6945         info->class_name = class_name + 2;
6946         return name;
6947       }
6948     }
6949   }
6950 
6951   if (classref) {
6952     *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
6953     const char *name =
6954         get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
6955     if (name != nullptr)
6956       info->class_name = name;
6957     else
6958       name = "bad class ref";
6959     return name;
6960   }
6961 
6962   if (cfstring) {
6963     *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
6964     const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
6965     return name;
6966   }
6967 
6968   if (selref && pointer_value == 0)
6969     pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
6970 
6971   if (pointer_value != 0)
6972     ReferenceValue = pointer_value;
6973 
6974   const char *name = GuessCstringPointer(ReferenceValue, info);
6975   if (name) {
6976     if (pointer_value != 0 && selref) {
6977       *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
6978       info->selector_name = name;
6979     } else if (pointer_value != 0 && msgref) {
6980       info->class_name = nullptr;
6981       *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
6982       info->selector_name = name;
6983     } else
6984       *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
6985     return name;
6986   }
6987 
6988   // Lastly look for an indirect symbol with this ReferenceValue which is in
6989   // a literal pool.  If found return that symbol name.
6990   name = GuessIndirectSymbol(ReferenceValue, info);
6991   if (name) {
6992     *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
6993     return name;
6994   }
6995 
6996   return nullptr;
6997 }
6998 
6999 // SymbolizerSymbolLookUp is the symbol lookup function passed when creating
7000 // the Symbolizer.  It looks up the ReferenceValue using the info passed via the
7001 // pointer to the struct DisassembleInfo that was passed when MCSymbolizer
7002 // is created and returns the symbol name that matches the ReferenceValue or
7003 // nullptr if none.  The ReferenceType is passed in for the IN type of
7004 // reference the instruction is making from the values in defined in the header
7005 // "llvm-c/Disassembler.h".  On return the ReferenceType can set to a specific
7006 // Out type and the ReferenceName will also be set which is added as a comment
7007 // to the disassembled instruction.
7008 //
7009 // If the symbol name is a C++ mangled name then the demangled name is
7010 // returned through ReferenceName and ReferenceType is set to
7011 // LLVMDisassembler_ReferenceType_DeMangled_Name .
7012 //
7013 // When this is called to get a symbol name for a branch target then the
7014 // ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
7015 // SymbolValue will be looked for in the indirect symbol table to determine if
7016 // it is an address for a symbol stub.  If so then the symbol name for that
7017 // stub is returned indirectly through ReferenceName and then ReferenceType is
7018 // set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
7019 //
7020 // When this is called with an value loaded via a PC relative load then
7021 // ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
7022 // SymbolValue is checked to be an address of literal pointer, symbol pointer,
7023 // or an Objective-C meta data reference.  If so the output ReferenceType is
7024 // set to correspond to that as well as setting the ReferenceName.
7025 static const char *SymbolizerSymbolLookUp(void *DisInfo,
7026                                           uint64_t ReferenceValue,
7027                                           uint64_t *ReferenceType,
7028                                           uint64_t ReferencePC,
7029                                           const char **ReferenceName) {
7030   struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
7031   // If no verbose symbolic information is wanted then just return nullptr.
7032   if (!info->verbose) {
7033     *ReferenceName = nullptr;
7034     *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7035     return nullptr;
7036   }
7037 
7038   const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
7039 
7040   if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
7041     *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
7042     if (*ReferenceName != nullptr) {
7043       method_reference(info, ReferenceType, ReferenceName);
7044       if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
7045         *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
7046     } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
7047       if (info->demangled_name != nullptr)
7048         free(info->demangled_name);
7049       int status;
7050       info->demangled_name =
7051           itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
7052       if (info->demangled_name != nullptr) {
7053         *ReferenceName = info->demangled_name;
7054         *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
7055       } else
7056         *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7057     } else
7058       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7059   } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
7060     *ReferenceName =
7061         GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7062     if (*ReferenceName)
7063       method_reference(info, ReferenceType, ReferenceName);
7064     else
7065       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7066     // If this is arm64 and the reference is an adrp instruction save the
7067     // instruction, passed in ReferenceValue and the address of the instruction
7068     // for use later if we see and add immediate instruction.
7069   } else if (info->O->getArch() == Triple::aarch64 &&
7070              *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
7071     info->adrp_inst = ReferenceValue;
7072     info->adrp_addr = ReferencePC;
7073     SymbolName = nullptr;
7074     *ReferenceName = nullptr;
7075     *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7076     // If this is arm64 and reference is an add immediate instruction and we
7077     // have
7078     // seen an adrp instruction just before it and the adrp's Xd register
7079     // matches
7080     // this add's Xn register reconstruct the value being referenced and look to
7081     // see if it is a literal pointer.  Note the add immediate instruction is
7082     // passed in ReferenceValue.
7083   } else if (info->O->getArch() == Triple::aarch64 &&
7084              *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
7085              ReferencePC - 4 == info->adrp_addr &&
7086              (info->adrp_inst & 0x9f000000) == 0x90000000 &&
7087              (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
7088     uint32_t addxri_inst;
7089     uint64_t adrp_imm, addxri_imm;
7090 
7091     adrp_imm =
7092         ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
7093     if (info->adrp_inst & 0x0200000)
7094       adrp_imm |= 0xfffffffffc000000LL;
7095 
7096     addxri_inst = ReferenceValue;
7097     addxri_imm = (addxri_inst >> 10) & 0xfff;
7098     if (((addxri_inst >> 22) & 0x3) == 1)
7099       addxri_imm <<= 12;
7100 
7101     ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
7102                      (adrp_imm << 12) + addxri_imm;
7103 
7104     *ReferenceName =
7105         GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7106     if (*ReferenceName == nullptr)
7107       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7108     // If this is arm64 and the reference is a load register instruction and we
7109     // have seen an adrp instruction just before it and the adrp's Xd register
7110     // matches this add's Xn register reconstruct the value being referenced and
7111     // look to see if it is a literal pointer.  Note the load register
7112     // instruction is passed in ReferenceValue.
7113   } else if (info->O->getArch() == Triple::aarch64 &&
7114              *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
7115              ReferencePC - 4 == info->adrp_addr &&
7116              (info->adrp_inst & 0x9f000000) == 0x90000000 &&
7117              (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
7118     uint32_t ldrxui_inst;
7119     uint64_t adrp_imm, ldrxui_imm;
7120 
7121     adrp_imm =
7122         ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
7123     if (info->adrp_inst & 0x0200000)
7124       adrp_imm |= 0xfffffffffc000000LL;
7125 
7126     ldrxui_inst = ReferenceValue;
7127     ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
7128 
7129     ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
7130                      (adrp_imm << 12) + (ldrxui_imm << 3);
7131 
7132     *ReferenceName =
7133         GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7134     if (*ReferenceName == nullptr)
7135       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7136   }
7137   // If this arm64 and is an load register (PC-relative) instruction the
7138   // ReferenceValue is the PC plus the immediate value.
7139   else if (info->O->getArch() == Triple::aarch64 &&
7140            (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
7141             *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
7142     *ReferenceName =
7143         GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7144     if (*ReferenceName == nullptr)
7145       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7146   } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
7147     if (info->demangled_name != nullptr)
7148       free(info->demangled_name);
7149     int status;
7150     info->demangled_name =
7151         itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
7152     if (info->demangled_name != nullptr) {
7153       *ReferenceName = info->demangled_name;
7154       *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
7155     }
7156   }
7157   else {
7158     *ReferenceName = nullptr;
7159     *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7160   }
7161 
7162   return SymbolName;
7163 }
7164 
7165 /// Emits the comments that are stored in the CommentStream.
7166 /// Each comment in the CommentStream must end with a newline.
7167 static void emitComments(raw_svector_ostream &CommentStream,
7168                          SmallString<128> &CommentsToEmit,
7169                          formatted_raw_ostream &FormattedOS,
7170                          const MCAsmInfo &MAI) {
7171   // Flush the stream before taking its content.
7172   StringRef Comments = CommentsToEmit.str();
7173   // Get the default information for printing a comment.
7174   StringRef CommentBegin = MAI.getCommentString();
7175   unsigned CommentColumn = MAI.getCommentColumn();
7176   ListSeparator LS("\n");
7177   while (!Comments.empty()) {
7178     FormattedOS << LS;
7179     // Emit a line of comments.
7180     FormattedOS.PadToColumn(CommentColumn);
7181     size_t Position = Comments.find('\n');
7182     FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
7183     // Move after the newline character.
7184     Comments = Comments.substr(Position + 1);
7185   }
7186   FormattedOS.flush();
7187 
7188   // Tell the comment stream that the vector changed underneath it.
7189   CommentsToEmit.clear();
7190 }
7191 
7192 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
7193                              StringRef DisSegName, StringRef DisSectName) {
7194   const char *McpuDefault = nullptr;
7195   const Target *ThumbTarget = nullptr;
7196   const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
7197   if (!TheTarget) {
7198     // GetTarget prints out stuff.
7199     return;
7200   }
7201   std::string MachOMCPU;
7202   if (MCPU.empty() && McpuDefault)
7203     MachOMCPU = McpuDefault;
7204   else
7205     MachOMCPU = MCPU;
7206 
7207 #define CHECK_TARGET_INFO_CREATION(NAME)                                       \
7208   do {                                                                         \
7209     if (!NAME) {                                                               \
7210       WithColor::error(errs(), "llvm-objdump")                                 \
7211           << "couldn't initialize disassembler for target " << TripleName      \
7212           << '\n';                                                             \
7213       return;                                                                  \
7214     }                                                                          \
7215   } while (false)
7216 #define CHECK_THUMB_TARGET_INFO_CREATION(NAME)                                 \
7217   do {                                                                         \
7218     if (!NAME) {                                                               \
7219       WithColor::error(errs(), "llvm-objdump")                                 \
7220           << "couldn't initialize disassembler for target " << ThumbTripleName \
7221           << '\n';                                                             \
7222       return;                                                                  \
7223     }                                                                          \
7224   } while (false)
7225 
7226   std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
7227   CHECK_TARGET_INFO_CREATION(InstrInfo);
7228   std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
7229   if (ThumbTarget) {
7230     ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
7231     CHECK_THUMB_TARGET_INFO_CREATION(ThumbInstrInfo);
7232   }
7233 
7234   // Package up features to be passed to target/subtarget
7235   std::string FeaturesStr;
7236   if (!MAttrs.empty()) {
7237     SubtargetFeatures Features;
7238     for (unsigned i = 0; i != MAttrs.size(); ++i)
7239       Features.AddFeature(MAttrs[i]);
7240     FeaturesStr = Features.getString();
7241   }
7242 
7243   MCTargetOptions MCOptions;
7244   // Set up disassembler.
7245   std::unique_ptr<const MCRegisterInfo> MRI(
7246       TheTarget->createMCRegInfo(TripleName));
7247   CHECK_TARGET_INFO_CREATION(MRI);
7248   std::unique_ptr<const MCAsmInfo> AsmInfo(
7249       TheTarget->createMCAsmInfo(*MRI, TripleName, MCOptions));
7250   CHECK_TARGET_INFO_CREATION(AsmInfo);
7251   std::unique_ptr<const MCSubtargetInfo> STI(
7252       TheTarget->createMCSubtargetInfo(TripleName, MachOMCPU, FeaturesStr));
7253   CHECK_TARGET_INFO_CREATION(STI);
7254   MCContext Ctx(Triple(TripleName), AsmInfo.get(), MRI.get(), STI.get());
7255   std::unique_ptr<MCDisassembler> DisAsm(
7256       TheTarget->createMCDisassembler(*STI, Ctx));
7257   CHECK_TARGET_INFO_CREATION(DisAsm);
7258   std::unique_ptr<MCSymbolizer> Symbolizer;
7259   struct DisassembleInfo SymbolizerInfo(nullptr, nullptr, nullptr, false);
7260   std::unique_ptr<MCRelocationInfo> RelInfo(
7261       TheTarget->createMCRelocationInfo(TripleName, Ctx));
7262   if (RelInfo) {
7263     Symbolizer.reset(TheTarget->createMCSymbolizer(
7264         TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
7265         &SymbolizerInfo, &Ctx, std::move(RelInfo)));
7266     DisAsm->setSymbolizer(std::move(Symbolizer));
7267   }
7268   int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
7269   std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
7270       Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
7271   CHECK_TARGET_INFO_CREATION(IP);
7272   // Set the display preference for hex vs. decimal immediates.
7273   IP->setPrintImmHex(PrintImmHex);
7274   // Comment stream and backing vector.
7275   SmallString<128> CommentsToEmit;
7276   raw_svector_ostream CommentStream(CommentsToEmit);
7277   // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
7278   // if it is done then arm64 comments for string literals don't get printed
7279   // and some constant get printed instead and not setting it causes intel
7280   // (32-bit and 64-bit) comments printed with different spacing before the
7281   // comment causing different diffs with the 'C' disassembler library API.
7282   // IP->setCommentStream(CommentStream);
7283 
7284   // Set up separate thumb disassembler if needed.
7285   std::unique_ptr<const MCRegisterInfo> ThumbMRI;
7286   std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
7287   std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
7288   std::unique_ptr<MCDisassembler> ThumbDisAsm;
7289   std::unique_ptr<MCInstPrinter> ThumbIP;
7290   std::unique_ptr<MCContext> ThumbCtx;
7291   std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
7292   struct DisassembleInfo ThumbSymbolizerInfo(nullptr, nullptr, nullptr, false);
7293   std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
7294   if (ThumbTarget) {
7295     ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
7296     CHECK_THUMB_TARGET_INFO_CREATION(ThumbMRI);
7297     ThumbAsmInfo.reset(
7298         ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName, MCOptions));
7299     CHECK_THUMB_TARGET_INFO_CREATION(ThumbAsmInfo);
7300     ThumbSTI.reset(
7301         ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MachOMCPU,
7302                                            FeaturesStr));
7303     CHECK_THUMB_TARGET_INFO_CREATION(ThumbSTI);
7304     ThumbCtx.reset(new MCContext(Triple(ThumbTripleName), ThumbAsmInfo.get(),
7305                                  ThumbMRI.get(), ThumbSTI.get()));
7306     ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
7307     CHECK_THUMB_TARGET_INFO_CREATION(ThumbDisAsm);
7308     MCContext *PtrThumbCtx = ThumbCtx.get();
7309     ThumbRelInfo.reset(
7310         ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
7311     if (ThumbRelInfo) {
7312       ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
7313           ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
7314           &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
7315       ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
7316     }
7317     int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
7318     ThumbIP.reset(ThumbTarget->createMCInstPrinter(
7319         Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
7320         *ThumbInstrInfo, *ThumbMRI));
7321     CHECK_THUMB_TARGET_INFO_CREATION(ThumbIP);
7322     // Set the display preference for hex vs. decimal immediates.
7323     ThumbIP->setPrintImmHex(PrintImmHex);
7324   }
7325 
7326 #undef CHECK_TARGET_INFO_CREATION
7327 #undef CHECK_THUMB_TARGET_INFO_CREATION
7328 
7329   MachO::mach_header Header = MachOOF->getHeader();
7330 
7331   // FIXME: Using the -cfg command line option, this code used to be able to
7332   // annotate relocations with the referenced symbol's name, and if this was
7333   // inside a __[cf]string section, the data it points to. This is now replaced
7334   // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
7335   std::vector<SectionRef> Sections;
7336   std::vector<SymbolRef> Symbols;
7337   SmallVector<uint64_t, 8> FoundFns;
7338   uint64_t BaseSegmentAddress = 0;
7339 
7340   getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
7341                         BaseSegmentAddress);
7342 
7343   // Sort the symbols by address, just in case they didn't come in that way.
7344   llvm::stable_sort(Symbols, SymbolSorter());
7345 
7346   // Build a data in code table that is sorted on by the address of each entry.
7347   uint64_t BaseAddress = 0;
7348   if (Header.filetype == MachO::MH_OBJECT)
7349     BaseAddress = Sections[0].getAddress();
7350   else
7351     BaseAddress = BaseSegmentAddress;
7352   DiceTable Dices;
7353   for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
7354        DI != DE; ++DI) {
7355     uint32_t Offset;
7356     DI->getOffset(Offset);
7357     Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
7358   }
7359   array_pod_sort(Dices.begin(), Dices.end());
7360 
7361   // Try to find debug info and set up the DIContext for it.
7362   std::unique_ptr<DIContext> diContext;
7363   std::unique_ptr<Binary> DSYMBinary;
7364   std::unique_ptr<MemoryBuffer> DSYMBuf;
7365   if (UseDbg) {
7366     ObjectFile *DbgObj = MachOOF;
7367 
7368     // A separate DSym file path was specified, parse it as a macho file,
7369     // get the sections and supply it to the section name parsing machinery.
7370     if (!DSYMFile.empty()) {
7371       std::string DSYMPath(DSYMFile);
7372 
7373       // If DSYMPath is a .dSYM directory, append the Mach-O file.
7374       if (llvm::sys::fs::is_directory(DSYMPath) &&
7375           llvm::sys::path::extension(DSYMPath) == ".dSYM") {
7376         SmallString<128> ShortName(llvm::sys::path::filename(DSYMPath));
7377         llvm::sys::path::replace_extension(ShortName, "");
7378         SmallString<1024> FullPath(DSYMPath);
7379         llvm::sys::path::append(FullPath, "Contents", "Resources", "DWARF",
7380                                 ShortName);
7381         DSYMPath = std::string(FullPath.str());
7382       }
7383 
7384       // Load the file.
7385       ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
7386           MemoryBuffer::getFileOrSTDIN(DSYMPath);
7387       if (std::error_code EC = BufOrErr.getError()) {
7388         reportError(errorCodeToError(EC), DSYMPath);
7389         return;
7390       }
7391 
7392       // We need to keep the file alive, because we're replacing DbgObj with it.
7393       DSYMBuf = std::move(BufOrErr.get());
7394 
7395       Expected<std::unique_ptr<Binary>> BinaryOrErr =
7396       createBinary(DSYMBuf.get()->getMemBufferRef());
7397       if (!BinaryOrErr) {
7398         reportError(BinaryOrErr.takeError(), DSYMPath);
7399         return;
7400       }
7401 
7402       // We need to keep the Binary alive with the buffer
7403       DSYMBinary = std::move(BinaryOrErr.get());
7404       if (ObjectFile *O = dyn_cast<ObjectFile>(DSYMBinary.get())) {
7405         // this is a Mach-O object file, use it
7406         if (MachOObjectFile *MachDSYM = dyn_cast<MachOObjectFile>(&*O)) {
7407           DbgObj = MachDSYM;
7408         }
7409         else {
7410           WithColor::error(errs(), "llvm-objdump")
7411             << DSYMPath << " is not a Mach-O file type.\n";
7412           return;
7413         }
7414       }
7415       else if (auto UB = dyn_cast<MachOUniversalBinary>(DSYMBinary.get())){
7416         // this is a Universal Binary, find a Mach-O for this architecture
7417         uint32_t CPUType, CPUSubType;
7418         const char *ArchFlag;
7419         if (MachOOF->is64Bit()) {
7420           const MachO::mach_header_64 H_64 = MachOOF->getHeader64();
7421           CPUType = H_64.cputype;
7422           CPUSubType = H_64.cpusubtype;
7423         } else {
7424           const MachO::mach_header H = MachOOF->getHeader();
7425           CPUType = H.cputype;
7426           CPUSubType = H.cpusubtype;
7427         }
7428         Triple T = MachOObjectFile::getArchTriple(CPUType, CPUSubType, nullptr,
7429                                                   &ArchFlag);
7430         Expected<std::unique_ptr<MachOObjectFile>> MachDSYM =
7431             UB->getMachOObjectForArch(ArchFlag);
7432         if (!MachDSYM) {
7433           reportError(MachDSYM.takeError(), DSYMPath);
7434           return;
7435         }
7436 
7437         // We need to keep the Binary alive with the buffer
7438         DbgObj = &*MachDSYM.get();
7439         DSYMBinary = std::move(*MachDSYM);
7440       }
7441       else {
7442         WithColor::error(errs(), "llvm-objdump")
7443           << DSYMPath << " is not a Mach-O or Universal file type.\n";
7444         return;
7445       }
7446     }
7447 
7448     // Setup the DIContext
7449     diContext = DWARFContext::create(*DbgObj);
7450   }
7451 
7452   if (FilterSections.empty())
7453     outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
7454 
7455   for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
7456     Expected<StringRef> SecNameOrErr = Sections[SectIdx].getName();
7457     if (!SecNameOrErr) {
7458       consumeError(SecNameOrErr.takeError());
7459       continue;
7460     }
7461     if (*SecNameOrErr != DisSectName)
7462       continue;
7463 
7464     DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
7465 
7466     StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
7467     if (SegmentName != DisSegName)
7468       continue;
7469 
7470     StringRef BytesStr =
7471         unwrapOrError(Sections[SectIdx].getContents(), Filename);
7472     ArrayRef<uint8_t> Bytes = arrayRefFromStringRef(BytesStr);
7473     uint64_t SectAddress = Sections[SectIdx].getAddress();
7474 
7475     bool symbolTableWorked = false;
7476 
7477     // Create a map of symbol addresses to symbol names for use by
7478     // the SymbolizerSymbolLookUp() routine.
7479     SymbolAddressMap AddrMap;
7480     bool DisSymNameFound = false;
7481     for (const SymbolRef &Symbol : MachOOF->symbols()) {
7482       SymbolRef::Type ST =
7483           unwrapOrError(Symbol.getType(), MachOOF->getFileName());
7484       if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
7485           ST == SymbolRef::ST_Other) {
7486         uint64_t Address = cantFail(Symbol.getValue());
7487         StringRef SymName =
7488             unwrapOrError(Symbol.getName(), MachOOF->getFileName());
7489         AddrMap[Address] = SymName;
7490         if (!DisSymName.empty() && DisSymName == SymName)
7491           DisSymNameFound = true;
7492       }
7493     }
7494     if (!DisSymName.empty() && !DisSymNameFound) {
7495       outs() << "Can't find -dis-symname: " << DisSymName << "\n";
7496       return;
7497     }
7498     // Set up the block of info used by the Symbolizer call backs.
7499     SymbolizerInfo.verbose = SymbolicOperands;
7500     SymbolizerInfo.O = MachOOF;
7501     SymbolizerInfo.S = Sections[SectIdx];
7502     SymbolizerInfo.AddrMap = &AddrMap;
7503     SymbolizerInfo.Sections = &Sections;
7504     // Same for the ThumbSymbolizer
7505     ThumbSymbolizerInfo.verbose = SymbolicOperands;
7506     ThumbSymbolizerInfo.O = MachOOF;
7507     ThumbSymbolizerInfo.S = Sections[SectIdx];
7508     ThumbSymbolizerInfo.AddrMap = &AddrMap;
7509     ThumbSymbolizerInfo.Sections = &Sections;
7510 
7511     unsigned int Arch = MachOOF->getArch();
7512 
7513     // Skip all symbols if this is a stubs file.
7514     if (Bytes.empty())
7515       return;
7516 
7517     // If the section has symbols but no symbol at the start of the section
7518     // these are used to make sure the bytes before the first symbol are
7519     // disassembled.
7520     bool FirstSymbol = true;
7521     bool FirstSymbolAtSectionStart = true;
7522 
7523     // Disassemble symbol by symbol.
7524     for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
7525       StringRef SymName =
7526           unwrapOrError(Symbols[SymIdx].getName(), MachOOF->getFileName());
7527       SymbolRef::Type ST =
7528           unwrapOrError(Symbols[SymIdx].getType(), MachOOF->getFileName());
7529       if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
7530         continue;
7531 
7532       // Make sure the symbol is defined in this section.
7533       bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
7534       if (!containsSym) {
7535         if (!DisSymName.empty() && DisSymName == SymName) {
7536           outs() << "-dis-symname: " << DisSymName << " not in the section\n";
7537           return;
7538         }
7539         continue;
7540       }
7541       // The __mh_execute_header is special and we need to deal with that fact
7542       // this symbol is before the start of the (__TEXT,__text) section and at the
7543       // address of the start of the __TEXT segment.  This is because this symbol
7544       // is an N_SECT symbol in the (__TEXT,__text) but its address is before the
7545       // start of the section in a standard MH_EXECUTE filetype.
7546       if (!DisSymName.empty() && DisSymName == "__mh_execute_header") {
7547         outs() << "-dis-symname: __mh_execute_header not in any section\n";
7548         return;
7549       }
7550       // When this code is trying to disassemble a symbol at a time and in the
7551       // case there is only the __mh_execute_header symbol left as in a stripped
7552       // executable, we need to deal with this by ignoring this symbol so the
7553       // whole section is disassembled and this symbol is then not displayed.
7554       if (SymName == "__mh_execute_header" || SymName == "__mh_dylib_header" ||
7555           SymName == "__mh_bundle_header" || SymName == "__mh_object_header" ||
7556           SymName == "__mh_preload_header" || SymName == "__mh_dylinker_header")
7557         continue;
7558 
7559       // If we are only disassembling one symbol see if this is that symbol.
7560       if (!DisSymName.empty() && DisSymName != SymName)
7561         continue;
7562 
7563       // Start at the address of the symbol relative to the section's address.
7564       uint64_t SectSize = Sections[SectIdx].getSize();
7565       uint64_t Start = cantFail(Symbols[SymIdx].getValue());
7566       uint64_t SectionAddress = Sections[SectIdx].getAddress();
7567       Start -= SectionAddress;
7568 
7569       if (Start > SectSize) {
7570         outs() << "section data ends, " << SymName
7571                << " lies outside valid range\n";
7572         return;
7573       }
7574 
7575       // Stop disassembling either at the beginning of the next symbol or at
7576       // the end of the section.
7577       bool containsNextSym = false;
7578       uint64_t NextSym = 0;
7579       uint64_t NextSymIdx = SymIdx + 1;
7580       while (Symbols.size() > NextSymIdx) {
7581         SymbolRef::Type NextSymType = unwrapOrError(
7582             Symbols[NextSymIdx].getType(), MachOOF->getFileName());
7583         if (NextSymType == SymbolRef::ST_Function) {
7584           containsNextSym =
7585               Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
7586           NextSym = cantFail(Symbols[NextSymIdx].getValue());
7587           NextSym -= SectionAddress;
7588           break;
7589         }
7590         ++NextSymIdx;
7591       }
7592 
7593       uint64_t End = containsNextSym ? std::min(NextSym, SectSize) : SectSize;
7594       uint64_t Size;
7595 
7596       symbolTableWorked = true;
7597 
7598       DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
7599       uint32_t SymbolFlags = cantFail(MachOOF->getSymbolFlags(Symb));
7600       bool IsThumb = SymbolFlags & SymbolRef::SF_Thumb;
7601 
7602       // We only need the dedicated Thumb target if there's a real choice
7603       // (i.e. we're not targeting M-class) and the function is Thumb.
7604       bool UseThumbTarget = IsThumb && ThumbTarget;
7605 
7606       // If we are not specifying a symbol to start disassembly with and this
7607       // is the first symbol in the section but not at the start of the section
7608       // then move the disassembly index to the start of the section and
7609       // don't print the symbol name just yet.  This is so the bytes before the
7610       // first symbol are disassembled.
7611       uint64_t SymbolStart = Start;
7612       if (DisSymName.empty() && FirstSymbol && Start != 0) {
7613         FirstSymbolAtSectionStart = false;
7614         Start = 0;
7615       }
7616       else
7617         outs() << SymName << ":\n";
7618 
7619       DILineInfo lastLine;
7620       for (uint64_t Index = Start; Index < End; Index += Size) {
7621         MCInst Inst;
7622 
7623         // If this is the first symbol in the section and it was not at the
7624         // start of the section, see if we are at its Index now and if so print
7625         // the symbol name.
7626         if (FirstSymbol && !FirstSymbolAtSectionStart && Index == SymbolStart)
7627           outs() << SymName << ":\n";
7628 
7629         uint64_t PC = SectAddress + Index;
7630         if (LeadingAddr) {
7631           if (FullLeadingAddr) {
7632             if (MachOOF->is64Bit())
7633               outs() << format("%016" PRIx64, PC);
7634             else
7635               outs() << format("%08" PRIx64, PC);
7636           } else {
7637             outs() << format("%8" PRIx64 ":", PC);
7638           }
7639         }
7640         if (ShowRawInsn || Arch == Triple::arm)
7641           outs() << "\t";
7642 
7643         if (DumpAndSkipDataInCode(PC, Bytes.data() + Index, Dices, Size))
7644           continue;
7645 
7646         SmallVector<char, 64> AnnotationsBytes;
7647         raw_svector_ostream Annotations(AnnotationsBytes);
7648 
7649         bool gotInst;
7650         if (UseThumbTarget)
7651           gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
7652                                                 PC, Annotations);
7653         else
7654           gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
7655                                            Annotations);
7656         if (gotInst) {
7657           if (ShowRawInsn || Arch == Triple::arm) {
7658             dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
7659           }
7660           formatted_raw_ostream FormattedOS(outs());
7661           StringRef AnnotationsStr = Annotations.str();
7662           if (UseThumbTarget)
7663             ThumbIP->printInst(&Inst, PC, AnnotationsStr, *ThumbSTI,
7664                                FormattedOS);
7665           else
7666             IP->printInst(&Inst, PC, AnnotationsStr, *STI, FormattedOS);
7667           emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
7668 
7669           // Print debug info.
7670           if (diContext) {
7671             DILineInfo dli = diContext->getLineInfoForAddress({PC, SectIdx});
7672             // Print valid line info if it changed.
7673             if (dli != lastLine && dli.Line != 0)
7674               outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
7675                      << dli.Column;
7676             lastLine = dli;
7677           }
7678           outs() << "\n";
7679         } else {
7680           if (MachOOF->getArchTriple().isX86()) {
7681             outs() << format("\t.byte 0x%02x #bad opcode\n",
7682                              *(Bytes.data() + Index) & 0xff);
7683             Size = 1; // skip exactly one illegible byte and move on.
7684           } else if (Arch == Triple::aarch64 ||
7685                      (Arch == Triple::arm && !IsThumb)) {
7686             uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7687                               (*(Bytes.data() + Index + 1) & 0xff) << 8 |
7688                               (*(Bytes.data() + Index + 2) & 0xff) << 16 |
7689                               (*(Bytes.data() + Index + 3) & 0xff) << 24;
7690             outs() << format("\t.long\t0x%08x\n", opcode);
7691             Size = 4;
7692           } else if (Arch == Triple::arm) {
7693             assert(IsThumb && "ARM mode should have been dealt with above");
7694             uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7695                               (*(Bytes.data() + Index + 1) & 0xff) << 8;
7696             outs() << format("\t.short\t0x%04x\n", opcode);
7697             Size = 2;
7698           } else{
7699             WithColor::warning(errs(), "llvm-objdump")
7700                 << "invalid instruction encoding\n";
7701             if (Size == 0)
7702               Size = 1; // skip illegible bytes
7703           }
7704         }
7705       }
7706       // Now that we are done disassembled the first symbol set the bool that
7707       // were doing this to false.
7708       FirstSymbol = false;
7709     }
7710     if (!symbolTableWorked) {
7711       // Reading the symbol table didn't work, disassemble the whole section.
7712       uint64_t SectAddress = Sections[SectIdx].getAddress();
7713       uint64_t SectSize = Sections[SectIdx].getSize();
7714       uint64_t InstSize;
7715       for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
7716         MCInst Inst;
7717 
7718         uint64_t PC = SectAddress + Index;
7719 
7720         if (DumpAndSkipDataInCode(PC, Bytes.data() + Index, Dices, InstSize))
7721           continue;
7722 
7723         SmallVector<char, 64> AnnotationsBytes;
7724         raw_svector_ostream Annotations(AnnotationsBytes);
7725         if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
7726                                    Annotations)) {
7727           if (LeadingAddr) {
7728             if (FullLeadingAddr) {
7729               if (MachOOF->is64Bit())
7730                 outs() << format("%016" PRIx64, PC);
7731               else
7732                 outs() << format("%08" PRIx64, PC);
7733             } else {
7734               outs() << format("%8" PRIx64 ":", PC);
7735             }
7736           }
7737           if (ShowRawInsn || Arch == Triple::arm) {
7738             outs() << "\t";
7739             dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
7740           }
7741           StringRef AnnotationsStr = Annotations.str();
7742           IP->printInst(&Inst, PC, AnnotationsStr, *STI, outs());
7743           outs() << "\n";
7744         } else {
7745           if (MachOOF->getArchTriple().isX86()) {
7746             outs() << format("\t.byte 0x%02x #bad opcode\n",
7747                              *(Bytes.data() + Index) & 0xff);
7748             InstSize = 1; // skip exactly one illegible byte and move on.
7749           } else {
7750             WithColor::warning(errs(), "llvm-objdump")
7751                 << "invalid instruction encoding\n";
7752             if (InstSize == 0)
7753               InstSize = 1; // skip illegible bytes
7754           }
7755         }
7756       }
7757     }
7758     // The TripleName's need to be reset if we are called again for a different
7759     // architecture.
7760     TripleName = "";
7761     ThumbTripleName = "";
7762 
7763     if (SymbolizerInfo.demangled_name != nullptr)
7764       free(SymbolizerInfo.demangled_name);
7765     if (ThumbSymbolizerInfo.demangled_name != nullptr)
7766       free(ThumbSymbolizerInfo.demangled_name);
7767   }
7768 }
7769 
7770 //===----------------------------------------------------------------------===//
7771 // __compact_unwind section dumping
7772 //===----------------------------------------------------------------------===//
7773 
7774 namespace {
7775 
7776 template <typename T>
7777 static uint64_t read(StringRef Contents, ptrdiff_t Offset) {
7778   using llvm::support::little;
7779   using llvm::support::unaligned;
7780 
7781   if (Offset + sizeof(T) > Contents.size()) {
7782     outs() << "warning: attempt to read past end of buffer\n";
7783     return T();
7784   }
7785 
7786   uint64_t Val =
7787       support::endian::read<T, little, unaligned>(Contents.data() + Offset);
7788   return Val;
7789 }
7790 
7791 template <typename T>
7792 static uint64_t readNext(StringRef Contents, ptrdiff_t &Offset) {
7793   T Val = read<T>(Contents, Offset);
7794   Offset += sizeof(T);
7795   return Val;
7796 }
7797 
7798 struct CompactUnwindEntry {
7799   uint32_t OffsetInSection;
7800 
7801   uint64_t FunctionAddr;
7802   uint32_t Length;
7803   uint32_t CompactEncoding;
7804   uint64_t PersonalityAddr;
7805   uint64_t LSDAAddr;
7806 
7807   RelocationRef FunctionReloc;
7808   RelocationRef PersonalityReloc;
7809   RelocationRef LSDAReloc;
7810 
7811   CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
7812       : OffsetInSection(Offset) {
7813     if (Is64)
7814       read<uint64_t>(Contents, Offset);
7815     else
7816       read<uint32_t>(Contents, Offset);
7817   }
7818 
7819 private:
7820   template <typename UIntPtr> void read(StringRef Contents, ptrdiff_t Offset) {
7821     FunctionAddr = readNext<UIntPtr>(Contents, Offset);
7822     Length = readNext<uint32_t>(Contents, Offset);
7823     CompactEncoding = readNext<uint32_t>(Contents, Offset);
7824     PersonalityAddr = readNext<UIntPtr>(Contents, Offset);
7825     LSDAAddr = readNext<UIntPtr>(Contents, Offset);
7826   }
7827 };
7828 }
7829 
7830 /// Given a relocation from __compact_unwind, consisting of the RelocationRef
7831 /// and data being relocated, determine the best base Name and Addend to use for
7832 /// display purposes.
7833 ///
7834 /// 1. An Extern relocation will directly reference a symbol (and the data is
7835 ///    then already an addend), so use that.
7836 /// 2. Otherwise the data is an offset in the object file's layout; try to find
7837 //     a symbol before it in the same section, and use the offset from there.
7838 /// 3. Finally, if all that fails, fall back to an offset from the start of the
7839 ///    referenced section.
7840 static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
7841                                       std::map<uint64_t, SymbolRef> &Symbols,
7842                                       const RelocationRef &Reloc, uint64_t Addr,
7843                                       StringRef &Name, uint64_t &Addend) {
7844   if (Reloc.getSymbol() != Obj->symbol_end()) {
7845     Name = unwrapOrError(Reloc.getSymbol()->getName(), Obj->getFileName());
7846     Addend = Addr;
7847     return;
7848   }
7849 
7850   auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
7851   SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
7852 
7853   uint64_t SectionAddr = RelocSection.getAddress();
7854 
7855   auto Sym = Symbols.upper_bound(Addr);
7856   if (Sym == Symbols.begin()) {
7857     // The first symbol in the object is after this reference, the best we can
7858     // do is section-relative notation.
7859     if (Expected<StringRef> NameOrErr = RelocSection.getName())
7860       Name = *NameOrErr;
7861     else
7862       consumeError(NameOrErr.takeError());
7863 
7864     Addend = Addr - SectionAddr;
7865     return;
7866   }
7867 
7868   // Go back one so that SymbolAddress <= Addr.
7869   --Sym;
7870 
7871   section_iterator SymSection =
7872       unwrapOrError(Sym->second.getSection(), Obj->getFileName());
7873   if (RelocSection == *SymSection) {
7874     // There's a valid symbol in the same section before this reference.
7875     Name = unwrapOrError(Sym->second.getName(), Obj->getFileName());
7876     Addend = Addr - Sym->first;
7877     return;
7878   }
7879 
7880   // There is a symbol before this reference, but it's in a different
7881   // section. Probably not helpful to mention it, so use the section name.
7882   if (Expected<StringRef> NameOrErr = RelocSection.getName())
7883     Name = *NameOrErr;
7884   else
7885     consumeError(NameOrErr.takeError());
7886 
7887   Addend = Addr - SectionAddr;
7888 }
7889 
7890 static void printUnwindRelocDest(const MachOObjectFile *Obj,
7891                                  std::map<uint64_t, SymbolRef> &Symbols,
7892                                  const RelocationRef &Reloc, uint64_t Addr) {
7893   StringRef Name;
7894   uint64_t Addend;
7895 
7896   if (!Reloc.getObject())
7897     return;
7898 
7899   findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
7900 
7901   outs() << Name;
7902   if (Addend)
7903     outs() << " + " << format("0x%" PRIx64, Addend);
7904 }
7905 
7906 static void
7907 printMachOCompactUnwindSection(const MachOObjectFile *Obj,
7908                                std::map<uint64_t, SymbolRef> &Symbols,
7909                                const SectionRef &CompactUnwind) {
7910 
7911   if (!Obj->isLittleEndian()) {
7912     outs() << "Skipping big-endian __compact_unwind section\n";
7913     return;
7914   }
7915 
7916   bool Is64 = Obj->is64Bit();
7917   uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
7918   uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
7919 
7920   StringRef Contents =
7921       unwrapOrError(CompactUnwind.getContents(), Obj->getFileName());
7922   SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
7923 
7924   // First populate the initial raw offsets, encodings and so on from the entry.
7925   for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
7926     CompactUnwindEntry Entry(Contents, Offset, Is64);
7927     CompactUnwinds.push_back(Entry);
7928   }
7929 
7930   // Next we need to look at the relocations to find out what objects are
7931   // actually being referred to.
7932   for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
7933     uint64_t RelocAddress = Reloc.getOffset();
7934 
7935     uint32_t EntryIdx = RelocAddress / EntrySize;
7936     uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
7937     CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
7938 
7939     if (OffsetInEntry == 0)
7940       Entry.FunctionReloc = Reloc;
7941     else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
7942       Entry.PersonalityReloc = Reloc;
7943     else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
7944       Entry.LSDAReloc = Reloc;
7945     else {
7946       outs() << "Invalid relocation in __compact_unwind section\n";
7947       return;
7948     }
7949   }
7950 
7951   // Finally, we're ready to print the data we've gathered.
7952   outs() << "Contents of __compact_unwind section:\n";
7953   for (auto &Entry : CompactUnwinds) {
7954     outs() << "  Entry at offset "
7955            << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
7956 
7957     // 1. Start of the region this entry applies to.
7958     outs() << "    start:                " << format("0x%" PRIx64,
7959                                                      Entry.FunctionAddr) << ' ';
7960     printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
7961     outs() << '\n';
7962 
7963     // 2. Length of the region this entry applies to.
7964     outs() << "    length:               " << format("0x%" PRIx32, Entry.Length)
7965            << '\n';
7966     // 3. The 32-bit compact encoding.
7967     outs() << "    compact encoding:     "
7968            << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
7969 
7970     // 4. The personality function, if present.
7971     if (Entry.PersonalityReloc.getObject()) {
7972       outs() << "    personality function: "
7973              << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
7974       printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
7975                            Entry.PersonalityAddr);
7976       outs() << '\n';
7977     }
7978 
7979     // 5. This entry's language-specific data area.
7980     if (Entry.LSDAReloc.getObject()) {
7981       outs() << "    LSDA:                 " << format("0x%" PRIx64,
7982                                                        Entry.LSDAAddr) << ' ';
7983       printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
7984       outs() << '\n';
7985     }
7986   }
7987 }
7988 
7989 //===----------------------------------------------------------------------===//
7990 // __unwind_info section dumping
7991 //===----------------------------------------------------------------------===//
7992 
7993 static void printRegularSecondLevelUnwindPage(StringRef PageData) {
7994   ptrdiff_t Pos = 0;
7995   uint32_t Kind = readNext<uint32_t>(PageData, Pos);
7996   (void)Kind;
7997   assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
7998 
7999   uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
8000   uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
8001 
8002   Pos = EntriesStart;
8003   for (unsigned i = 0; i < NumEntries; ++i) {
8004     uint32_t FunctionOffset = readNext<uint32_t>(PageData, Pos);
8005     uint32_t Encoding = readNext<uint32_t>(PageData, Pos);
8006 
8007     outs() << "      [" << i << "]: "
8008            << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
8009            << ", "
8010            << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
8011   }
8012 }
8013 
8014 static void printCompressedSecondLevelUnwindPage(
8015     StringRef PageData, uint32_t FunctionBase,
8016     const SmallVectorImpl<uint32_t> &CommonEncodings) {
8017   ptrdiff_t Pos = 0;
8018   uint32_t Kind = readNext<uint32_t>(PageData, Pos);
8019   (void)Kind;
8020   assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
8021 
8022   uint32_t NumCommonEncodings = CommonEncodings.size();
8023   uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
8024   uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
8025 
8026   uint16_t PageEncodingsStart = readNext<uint16_t>(PageData, Pos);
8027   uint16_t NumPageEncodings = readNext<uint16_t>(PageData, Pos);
8028   SmallVector<uint32_t, 64> PageEncodings;
8029   if (NumPageEncodings) {
8030     outs() << "      Page encodings: (count = " << NumPageEncodings << ")\n";
8031     Pos = PageEncodingsStart;
8032     for (unsigned i = 0; i < NumPageEncodings; ++i) {
8033       uint32_t Encoding = readNext<uint32_t>(PageData, Pos);
8034       PageEncodings.push_back(Encoding);
8035       outs() << "        encoding[" << (i + NumCommonEncodings)
8036              << "]: " << format("0x%08" PRIx32, Encoding) << '\n';
8037     }
8038   }
8039 
8040   Pos = EntriesStart;
8041   for (unsigned i = 0; i < NumEntries; ++i) {
8042     uint32_t Entry = readNext<uint32_t>(PageData, Pos);
8043     uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
8044     uint32_t EncodingIdx = Entry >> 24;
8045 
8046     uint32_t Encoding;
8047     if (EncodingIdx < NumCommonEncodings)
8048       Encoding = CommonEncodings[EncodingIdx];
8049     else
8050       Encoding = PageEncodings[EncodingIdx - NumCommonEncodings];
8051 
8052     outs() << "      [" << i << "]: "
8053            << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
8054            << ", "
8055            << "encoding[" << EncodingIdx
8056            << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
8057   }
8058 }
8059 
8060 static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
8061                                         std::map<uint64_t, SymbolRef> &Symbols,
8062                                         const SectionRef &UnwindInfo) {
8063 
8064   if (!Obj->isLittleEndian()) {
8065     outs() << "Skipping big-endian __unwind_info section\n";
8066     return;
8067   }
8068 
8069   outs() << "Contents of __unwind_info section:\n";
8070 
8071   StringRef Contents =
8072       unwrapOrError(UnwindInfo.getContents(), Obj->getFileName());
8073   ptrdiff_t Pos = 0;
8074 
8075   //===----------------------------------
8076   // Section header
8077   //===----------------------------------
8078 
8079   uint32_t Version = readNext<uint32_t>(Contents, Pos);
8080   outs() << "  Version:                                   "
8081          << format("0x%" PRIx32, Version) << '\n';
8082   if (Version != 1) {
8083     outs() << "    Skipping section with unknown version\n";
8084     return;
8085   }
8086 
8087   uint32_t CommonEncodingsStart = readNext<uint32_t>(Contents, Pos);
8088   outs() << "  Common encodings array section offset:     "
8089          << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
8090   uint32_t NumCommonEncodings = readNext<uint32_t>(Contents, Pos);
8091   outs() << "  Number of common encodings in array:       "
8092          << format("0x%" PRIx32, NumCommonEncodings) << '\n';
8093 
8094   uint32_t PersonalitiesStart = readNext<uint32_t>(Contents, Pos);
8095   outs() << "  Personality function array section offset: "
8096          << format("0x%" PRIx32, PersonalitiesStart) << '\n';
8097   uint32_t NumPersonalities = readNext<uint32_t>(Contents, Pos);
8098   outs() << "  Number of personality functions in array:  "
8099          << format("0x%" PRIx32, NumPersonalities) << '\n';
8100 
8101   uint32_t IndicesStart = readNext<uint32_t>(Contents, Pos);
8102   outs() << "  Index array section offset:                "
8103          << format("0x%" PRIx32, IndicesStart) << '\n';
8104   uint32_t NumIndices = readNext<uint32_t>(Contents, Pos);
8105   outs() << "  Number of indices in array:                "
8106          << format("0x%" PRIx32, NumIndices) << '\n';
8107 
8108   //===----------------------------------
8109   // A shared list of common encodings
8110   //===----------------------------------
8111 
8112   // These occupy indices in the range [0, N] whenever an encoding is referenced
8113   // from a compressed 2nd level index table. In practice the linker only
8114   // creates ~128 of these, so that indices are available to embed encodings in
8115   // the 2nd level index.
8116 
8117   SmallVector<uint32_t, 64> CommonEncodings;
8118   outs() << "  Common encodings: (count = " << NumCommonEncodings << ")\n";
8119   Pos = CommonEncodingsStart;
8120   for (unsigned i = 0; i < NumCommonEncodings; ++i) {
8121     uint32_t Encoding = readNext<uint32_t>(Contents, Pos);
8122     CommonEncodings.push_back(Encoding);
8123 
8124     outs() << "    encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
8125            << '\n';
8126   }
8127 
8128   //===----------------------------------
8129   // Personality functions used in this executable
8130   //===----------------------------------
8131 
8132   // There should be only a handful of these (one per source language,
8133   // roughly). Particularly since they only get 2 bits in the compact encoding.
8134 
8135   outs() << "  Personality functions: (count = " << NumPersonalities << ")\n";
8136   Pos = PersonalitiesStart;
8137   for (unsigned i = 0; i < NumPersonalities; ++i) {
8138     uint32_t PersonalityFn = readNext<uint32_t>(Contents, Pos);
8139     outs() << "    personality[" << i + 1
8140            << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
8141   }
8142 
8143   //===----------------------------------
8144   // The level 1 index entries
8145   //===----------------------------------
8146 
8147   // These specify an approximate place to start searching for the more detailed
8148   // information, sorted by PC.
8149 
8150   struct IndexEntry {
8151     uint32_t FunctionOffset;
8152     uint32_t SecondLevelPageStart;
8153     uint32_t LSDAStart;
8154   };
8155 
8156   SmallVector<IndexEntry, 4> IndexEntries;
8157 
8158   outs() << "  Top level indices: (count = " << NumIndices << ")\n";
8159   Pos = IndicesStart;
8160   for (unsigned i = 0; i < NumIndices; ++i) {
8161     IndexEntry Entry;
8162 
8163     Entry.FunctionOffset = readNext<uint32_t>(Contents, Pos);
8164     Entry.SecondLevelPageStart = readNext<uint32_t>(Contents, Pos);
8165     Entry.LSDAStart = readNext<uint32_t>(Contents, Pos);
8166     IndexEntries.push_back(Entry);
8167 
8168     outs() << "    [" << i << "]: "
8169            << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
8170            << ", "
8171            << "2nd level page offset="
8172            << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
8173            << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
8174   }
8175 
8176   //===----------------------------------
8177   // Next come the LSDA tables
8178   //===----------------------------------
8179 
8180   // The LSDA layout is rather implicit: it's a contiguous array of entries from
8181   // the first top-level index's LSDAOffset to the last (sentinel).
8182 
8183   outs() << "  LSDA descriptors:\n";
8184   Pos = IndexEntries[0].LSDAStart;
8185   const uint32_t LSDASize = 2 * sizeof(uint32_t);
8186   int NumLSDAs =
8187       (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) / LSDASize;
8188 
8189   for (int i = 0; i < NumLSDAs; ++i) {
8190     uint32_t FunctionOffset = readNext<uint32_t>(Contents, Pos);
8191     uint32_t LSDAOffset = readNext<uint32_t>(Contents, Pos);
8192     outs() << "    [" << i << "]: "
8193            << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
8194            << ", "
8195            << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
8196   }
8197 
8198   //===----------------------------------
8199   // Finally, the 2nd level indices
8200   //===----------------------------------
8201 
8202   // Generally these are 4K in size, and have 2 possible forms:
8203   //   + Regular stores up to 511 entries with disparate encodings
8204   //   + Compressed stores up to 1021 entries if few enough compact encoding
8205   //     values are used.
8206   outs() << "  Second level indices:\n";
8207   for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
8208     // The final sentinel top-level index has no associated 2nd level page
8209     if (IndexEntries[i].SecondLevelPageStart == 0)
8210       break;
8211 
8212     outs() << "    Second level index[" << i << "]: "
8213            << "offset in section="
8214            << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
8215            << ", "
8216            << "base function offset="
8217            << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
8218 
8219     Pos = IndexEntries[i].SecondLevelPageStart;
8220     if (Pos + sizeof(uint32_t) > Contents.size()) {
8221       outs() << "warning: invalid offset for second level page: " << Pos << '\n';
8222       continue;
8223     }
8224 
8225     uint32_t Kind =
8226         *reinterpret_cast<const support::ulittle32_t *>(Contents.data() + Pos);
8227     if (Kind == 2)
8228       printRegularSecondLevelUnwindPage(Contents.substr(Pos, 4096));
8229     else if (Kind == 3)
8230       printCompressedSecondLevelUnwindPage(Contents.substr(Pos, 4096),
8231                                            IndexEntries[i].FunctionOffset,
8232                                            CommonEncodings);
8233     else
8234       outs() << "    Skipping 2nd level page with unknown kind " << Kind
8235              << '\n';
8236   }
8237 }
8238 
8239 void objdump::printMachOUnwindInfo(const MachOObjectFile *Obj) {
8240   std::map<uint64_t, SymbolRef> Symbols;
8241   for (const SymbolRef &SymRef : Obj->symbols()) {
8242     // Discard any undefined or absolute symbols. They're not going to take part
8243     // in the convenience lookup for unwind info and just take up resources.
8244     auto SectOrErr = SymRef.getSection();
8245     if (!SectOrErr) {
8246       // TODO: Actually report errors helpfully.
8247       consumeError(SectOrErr.takeError());
8248       continue;
8249     }
8250     section_iterator Section = *SectOrErr;
8251     if (Section == Obj->section_end())
8252       continue;
8253 
8254     uint64_t Addr = cantFail(SymRef.getValue());
8255     Symbols.insert(std::make_pair(Addr, SymRef));
8256   }
8257 
8258   for (const SectionRef &Section : Obj->sections()) {
8259     StringRef SectName;
8260     if (Expected<StringRef> NameOrErr = Section.getName())
8261       SectName = *NameOrErr;
8262     else
8263       consumeError(NameOrErr.takeError());
8264 
8265     if (SectName == "__compact_unwind")
8266       printMachOCompactUnwindSection(Obj, Symbols, Section);
8267     else if (SectName == "__unwind_info")
8268       printMachOUnwindInfoSection(Obj, Symbols, Section);
8269   }
8270 }
8271 
8272 static void PrintMachHeader(uint32_t magic, uint32_t cputype,
8273                             uint32_t cpusubtype, uint32_t filetype,
8274                             uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
8275                             bool verbose) {
8276   outs() << "Mach header\n";
8277   outs() << "      magic cputype cpusubtype  caps    filetype ncmds "
8278             "sizeofcmds      flags\n";
8279   if (verbose) {
8280     if (magic == MachO::MH_MAGIC)
8281       outs() << "   MH_MAGIC";
8282     else if (magic == MachO::MH_MAGIC_64)
8283       outs() << "MH_MAGIC_64";
8284     else
8285       outs() << format(" 0x%08" PRIx32, magic);
8286     switch (cputype) {
8287     case MachO::CPU_TYPE_I386:
8288       outs() << "    I386";
8289       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8290       case MachO::CPU_SUBTYPE_I386_ALL:
8291         outs() << "        ALL";
8292         break;
8293       default:
8294         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8295         break;
8296       }
8297       break;
8298     case MachO::CPU_TYPE_X86_64:
8299       outs() << "  X86_64";
8300       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8301       case MachO::CPU_SUBTYPE_X86_64_ALL:
8302         outs() << "        ALL";
8303         break;
8304       case MachO::CPU_SUBTYPE_X86_64_H:
8305         outs() << "    Haswell";
8306         break;
8307       default:
8308         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8309         break;
8310       }
8311       break;
8312     case MachO::CPU_TYPE_ARM:
8313       outs() << "     ARM";
8314       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8315       case MachO::CPU_SUBTYPE_ARM_ALL:
8316         outs() << "        ALL";
8317         break;
8318       case MachO::CPU_SUBTYPE_ARM_V4T:
8319         outs() << "        V4T";
8320         break;
8321       case MachO::CPU_SUBTYPE_ARM_V5TEJ:
8322         outs() << "      V5TEJ";
8323         break;
8324       case MachO::CPU_SUBTYPE_ARM_XSCALE:
8325         outs() << "     XSCALE";
8326         break;
8327       case MachO::CPU_SUBTYPE_ARM_V6:
8328         outs() << "         V6";
8329         break;
8330       case MachO::CPU_SUBTYPE_ARM_V6M:
8331         outs() << "        V6M";
8332         break;
8333       case MachO::CPU_SUBTYPE_ARM_V7:
8334         outs() << "         V7";
8335         break;
8336       case MachO::CPU_SUBTYPE_ARM_V7EM:
8337         outs() << "       V7EM";
8338         break;
8339       case MachO::CPU_SUBTYPE_ARM_V7K:
8340         outs() << "        V7K";
8341         break;
8342       case MachO::CPU_SUBTYPE_ARM_V7M:
8343         outs() << "        V7M";
8344         break;
8345       case MachO::CPU_SUBTYPE_ARM_V7S:
8346         outs() << "        V7S";
8347         break;
8348       default:
8349         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8350         break;
8351       }
8352       break;
8353     case MachO::CPU_TYPE_ARM64:
8354       outs() << "   ARM64";
8355       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8356       case MachO::CPU_SUBTYPE_ARM64_ALL:
8357         outs() << "        ALL";
8358         break;
8359       case MachO::CPU_SUBTYPE_ARM64_V8:
8360         outs() << "         V8";
8361         break;
8362       case MachO::CPU_SUBTYPE_ARM64E:
8363         outs() << "          E";
8364         break;
8365       default:
8366         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8367         break;
8368       }
8369       break;
8370     case MachO::CPU_TYPE_ARM64_32:
8371       outs() << " ARM64_32";
8372       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8373       case MachO::CPU_SUBTYPE_ARM64_32_V8:
8374         outs() << "        V8";
8375         break;
8376       default:
8377         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8378         break;
8379       }
8380       break;
8381     case MachO::CPU_TYPE_POWERPC:
8382       outs() << "     PPC";
8383       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8384       case MachO::CPU_SUBTYPE_POWERPC_ALL:
8385         outs() << "        ALL";
8386         break;
8387       default:
8388         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8389         break;
8390       }
8391       break;
8392     case MachO::CPU_TYPE_POWERPC64:
8393       outs() << "   PPC64";
8394       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8395       case MachO::CPU_SUBTYPE_POWERPC_ALL:
8396         outs() << "        ALL";
8397         break;
8398       default:
8399         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8400         break;
8401       }
8402       break;
8403     default:
8404       outs() << format(" %7d", cputype);
8405       outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8406       break;
8407     }
8408     if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
8409       outs() << " LIB64";
8410     } else {
8411       outs() << format("  0x%02" PRIx32,
8412                        (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
8413     }
8414     switch (filetype) {
8415     case MachO::MH_OBJECT:
8416       outs() << "      OBJECT";
8417       break;
8418     case MachO::MH_EXECUTE:
8419       outs() << "     EXECUTE";
8420       break;
8421     case MachO::MH_FVMLIB:
8422       outs() << "      FVMLIB";
8423       break;
8424     case MachO::MH_CORE:
8425       outs() << "        CORE";
8426       break;
8427     case MachO::MH_PRELOAD:
8428       outs() << "     PRELOAD";
8429       break;
8430     case MachO::MH_DYLIB:
8431       outs() << "       DYLIB";
8432       break;
8433     case MachO::MH_DYLIB_STUB:
8434       outs() << "  DYLIB_STUB";
8435       break;
8436     case MachO::MH_DYLINKER:
8437       outs() << "    DYLINKER";
8438       break;
8439     case MachO::MH_BUNDLE:
8440       outs() << "      BUNDLE";
8441       break;
8442     case MachO::MH_DSYM:
8443       outs() << "        DSYM";
8444       break;
8445     case MachO::MH_KEXT_BUNDLE:
8446       outs() << "  KEXTBUNDLE";
8447       break;
8448     default:
8449       outs() << format("  %10u", filetype);
8450       break;
8451     }
8452     outs() << format(" %5u", ncmds);
8453     outs() << format(" %10u", sizeofcmds);
8454     uint32_t f = flags;
8455     if (f & MachO::MH_NOUNDEFS) {
8456       outs() << "   NOUNDEFS";
8457       f &= ~MachO::MH_NOUNDEFS;
8458     }
8459     if (f & MachO::MH_INCRLINK) {
8460       outs() << " INCRLINK";
8461       f &= ~MachO::MH_INCRLINK;
8462     }
8463     if (f & MachO::MH_DYLDLINK) {
8464       outs() << " DYLDLINK";
8465       f &= ~MachO::MH_DYLDLINK;
8466     }
8467     if (f & MachO::MH_BINDATLOAD) {
8468       outs() << " BINDATLOAD";
8469       f &= ~MachO::MH_BINDATLOAD;
8470     }
8471     if (f & MachO::MH_PREBOUND) {
8472       outs() << " PREBOUND";
8473       f &= ~MachO::MH_PREBOUND;
8474     }
8475     if (f & MachO::MH_SPLIT_SEGS) {
8476       outs() << " SPLIT_SEGS";
8477       f &= ~MachO::MH_SPLIT_SEGS;
8478     }
8479     if (f & MachO::MH_LAZY_INIT) {
8480       outs() << " LAZY_INIT";
8481       f &= ~MachO::MH_LAZY_INIT;
8482     }
8483     if (f & MachO::MH_TWOLEVEL) {
8484       outs() << " TWOLEVEL";
8485       f &= ~MachO::MH_TWOLEVEL;
8486     }
8487     if (f & MachO::MH_FORCE_FLAT) {
8488       outs() << " FORCE_FLAT";
8489       f &= ~MachO::MH_FORCE_FLAT;
8490     }
8491     if (f & MachO::MH_NOMULTIDEFS) {
8492       outs() << " NOMULTIDEFS";
8493       f &= ~MachO::MH_NOMULTIDEFS;
8494     }
8495     if (f & MachO::MH_NOFIXPREBINDING) {
8496       outs() << " NOFIXPREBINDING";
8497       f &= ~MachO::MH_NOFIXPREBINDING;
8498     }
8499     if (f & MachO::MH_PREBINDABLE) {
8500       outs() << " PREBINDABLE";
8501       f &= ~MachO::MH_PREBINDABLE;
8502     }
8503     if (f & MachO::MH_ALLMODSBOUND) {
8504       outs() << " ALLMODSBOUND";
8505       f &= ~MachO::MH_ALLMODSBOUND;
8506     }
8507     if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
8508       outs() << " SUBSECTIONS_VIA_SYMBOLS";
8509       f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
8510     }
8511     if (f & MachO::MH_CANONICAL) {
8512       outs() << " CANONICAL";
8513       f &= ~MachO::MH_CANONICAL;
8514     }
8515     if (f & MachO::MH_WEAK_DEFINES) {
8516       outs() << " WEAK_DEFINES";
8517       f &= ~MachO::MH_WEAK_DEFINES;
8518     }
8519     if (f & MachO::MH_BINDS_TO_WEAK) {
8520       outs() << " BINDS_TO_WEAK";
8521       f &= ~MachO::MH_BINDS_TO_WEAK;
8522     }
8523     if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
8524       outs() << " ALLOW_STACK_EXECUTION";
8525       f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
8526     }
8527     if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
8528       outs() << " DEAD_STRIPPABLE_DYLIB";
8529       f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
8530     }
8531     if (f & MachO::MH_PIE) {
8532       outs() << " PIE";
8533       f &= ~MachO::MH_PIE;
8534     }
8535     if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
8536       outs() << " NO_REEXPORTED_DYLIBS";
8537       f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
8538     }
8539     if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
8540       outs() << " MH_HAS_TLV_DESCRIPTORS";
8541       f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
8542     }
8543     if (f & MachO::MH_NO_HEAP_EXECUTION) {
8544       outs() << " MH_NO_HEAP_EXECUTION";
8545       f &= ~MachO::MH_NO_HEAP_EXECUTION;
8546     }
8547     if (f & MachO::MH_APP_EXTENSION_SAFE) {
8548       outs() << " APP_EXTENSION_SAFE";
8549       f &= ~MachO::MH_APP_EXTENSION_SAFE;
8550     }
8551     if (f & MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO) {
8552       outs() << " NLIST_OUTOFSYNC_WITH_DYLDINFO";
8553       f &= ~MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO;
8554     }
8555     if (f != 0 || flags == 0)
8556       outs() << format(" 0x%08" PRIx32, f);
8557   } else {
8558     outs() << format(" 0x%08" PRIx32, magic);
8559     outs() << format(" %7d", cputype);
8560     outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8561     outs() << format("  0x%02" PRIx32,
8562                      (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
8563     outs() << format("  %10u", filetype);
8564     outs() << format(" %5u", ncmds);
8565     outs() << format(" %10u", sizeofcmds);
8566     outs() << format(" 0x%08" PRIx32, flags);
8567   }
8568   outs() << "\n";
8569 }
8570 
8571 static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
8572                                 StringRef SegName, uint64_t vmaddr,
8573                                 uint64_t vmsize, uint64_t fileoff,
8574                                 uint64_t filesize, uint32_t maxprot,
8575                                 uint32_t initprot, uint32_t nsects,
8576                                 uint32_t flags, uint32_t object_size,
8577                                 bool verbose) {
8578   uint64_t expected_cmdsize;
8579   if (cmd == MachO::LC_SEGMENT) {
8580     outs() << "      cmd LC_SEGMENT\n";
8581     expected_cmdsize = nsects;
8582     expected_cmdsize *= sizeof(struct MachO::section);
8583     expected_cmdsize += sizeof(struct MachO::segment_command);
8584   } else {
8585     outs() << "      cmd LC_SEGMENT_64\n";
8586     expected_cmdsize = nsects;
8587     expected_cmdsize *= sizeof(struct MachO::section_64);
8588     expected_cmdsize += sizeof(struct MachO::segment_command_64);
8589   }
8590   outs() << "  cmdsize " << cmdsize;
8591   if (cmdsize != expected_cmdsize)
8592     outs() << " Inconsistent size\n";
8593   else
8594     outs() << "\n";
8595   outs() << "  segname " << SegName << "\n";
8596   if (cmd == MachO::LC_SEGMENT_64) {
8597     outs() << "   vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
8598     outs() << "   vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
8599   } else {
8600     outs() << "   vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
8601     outs() << "   vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
8602   }
8603   outs() << "  fileoff " << fileoff;
8604   if (fileoff > object_size)
8605     outs() << " (past end of file)\n";
8606   else
8607     outs() << "\n";
8608   outs() << " filesize " << filesize;
8609   if (fileoff + filesize > object_size)
8610     outs() << " (past end of file)\n";
8611   else
8612     outs() << "\n";
8613   if (verbose) {
8614     if ((maxprot &
8615          ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8616            MachO::VM_PROT_EXECUTE)) != 0)
8617       outs() << "  maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
8618     else {
8619       outs() << "  maxprot ";
8620       outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
8621       outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8622       outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
8623     }
8624     if ((initprot &
8625          ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8626            MachO::VM_PROT_EXECUTE)) != 0)
8627       outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
8628     else {
8629       outs() << " initprot ";
8630       outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
8631       outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8632       outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
8633     }
8634   } else {
8635     outs() << "  maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
8636     outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
8637   }
8638   outs() << "   nsects " << nsects << "\n";
8639   if (verbose) {
8640     outs() << "    flags";
8641     if (flags == 0)
8642       outs() << " (none)\n";
8643     else {
8644       if (flags & MachO::SG_HIGHVM) {
8645         outs() << " HIGHVM";
8646         flags &= ~MachO::SG_HIGHVM;
8647       }
8648       if (flags & MachO::SG_FVMLIB) {
8649         outs() << " FVMLIB";
8650         flags &= ~MachO::SG_FVMLIB;
8651       }
8652       if (flags & MachO::SG_NORELOC) {
8653         outs() << " NORELOC";
8654         flags &= ~MachO::SG_NORELOC;
8655       }
8656       if (flags & MachO::SG_PROTECTED_VERSION_1) {
8657         outs() << " PROTECTED_VERSION_1";
8658         flags &= ~MachO::SG_PROTECTED_VERSION_1;
8659       }
8660       if (flags)
8661         outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
8662       else
8663         outs() << "\n";
8664     }
8665   } else {
8666     outs() << "    flags " << format("0x%" PRIx32, flags) << "\n";
8667   }
8668 }
8669 
8670 static void PrintSection(const char *sectname, const char *segname,
8671                          uint64_t addr, uint64_t size, uint32_t offset,
8672                          uint32_t align, uint32_t reloff, uint32_t nreloc,
8673                          uint32_t flags, uint32_t reserved1, uint32_t reserved2,
8674                          uint32_t cmd, const char *sg_segname,
8675                          uint32_t filetype, uint32_t object_size,
8676                          bool verbose) {
8677   outs() << "Section\n";
8678   outs() << "  sectname " << format("%.16s\n", sectname);
8679   outs() << "   segname " << format("%.16s", segname);
8680   if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
8681     outs() << " (does not match segment)\n";
8682   else
8683     outs() << "\n";
8684   if (cmd == MachO::LC_SEGMENT_64) {
8685     outs() << "      addr " << format("0x%016" PRIx64, addr) << "\n";
8686     outs() << "      size " << format("0x%016" PRIx64, size);
8687   } else {
8688     outs() << "      addr " << format("0x%08" PRIx64, addr) << "\n";
8689     outs() << "      size " << format("0x%08" PRIx64, size);
8690   }
8691   if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
8692     outs() << " (past end of file)\n";
8693   else
8694     outs() << "\n";
8695   outs() << "    offset " << offset;
8696   if (offset > object_size)
8697     outs() << " (past end of file)\n";
8698   else
8699     outs() << "\n";
8700   uint32_t align_shifted = 1 << align;
8701   outs() << "     align 2^" << align << " (" << align_shifted << ")\n";
8702   outs() << "    reloff " << reloff;
8703   if (reloff > object_size)
8704     outs() << " (past end of file)\n";
8705   else
8706     outs() << "\n";
8707   outs() << "    nreloc " << nreloc;
8708   if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
8709     outs() << " (past end of file)\n";
8710   else
8711     outs() << "\n";
8712   uint32_t section_type = flags & MachO::SECTION_TYPE;
8713   if (verbose) {
8714     outs() << "      type";
8715     if (section_type == MachO::S_REGULAR)
8716       outs() << " S_REGULAR\n";
8717     else if (section_type == MachO::S_ZEROFILL)
8718       outs() << " S_ZEROFILL\n";
8719     else if (section_type == MachO::S_CSTRING_LITERALS)
8720       outs() << " S_CSTRING_LITERALS\n";
8721     else if (section_type == MachO::S_4BYTE_LITERALS)
8722       outs() << " S_4BYTE_LITERALS\n";
8723     else if (section_type == MachO::S_8BYTE_LITERALS)
8724       outs() << " S_8BYTE_LITERALS\n";
8725     else if (section_type == MachO::S_16BYTE_LITERALS)
8726       outs() << " S_16BYTE_LITERALS\n";
8727     else if (section_type == MachO::S_LITERAL_POINTERS)
8728       outs() << " S_LITERAL_POINTERS\n";
8729     else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
8730       outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
8731     else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
8732       outs() << " S_LAZY_SYMBOL_POINTERS\n";
8733     else if (section_type == MachO::S_SYMBOL_STUBS)
8734       outs() << " S_SYMBOL_STUBS\n";
8735     else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
8736       outs() << " S_MOD_INIT_FUNC_POINTERS\n";
8737     else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
8738       outs() << " S_MOD_TERM_FUNC_POINTERS\n";
8739     else if (section_type == MachO::S_COALESCED)
8740       outs() << " S_COALESCED\n";
8741     else if (section_type == MachO::S_INTERPOSING)
8742       outs() << " S_INTERPOSING\n";
8743     else if (section_type == MachO::S_DTRACE_DOF)
8744       outs() << " S_DTRACE_DOF\n";
8745     else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
8746       outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
8747     else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
8748       outs() << " S_THREAD_LOCAL_REGULAR\n";
8749     else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
8750       outs() << " S_THREAD_LOCAL_ZEROFILL\n";
8751     else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
8752       outs() << " S_THREAD_LOCAL_VARIABLES\n";
8753     else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8754       outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
8755     else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
8756       outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
8757     else
8758       outs() << format("0x%08" PRIx32, section_type) << "\n";
8759     outs() << "attributes";
8760     uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
8761     if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
8762       outs() << " PURE_INSTRUCTIONS";
8763     if (section_attributes & MachO::S_ATTR_NO_TOC)
8764       outs() << " NO_TOC";
8765     if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
8766       outs() << " STRIP_STATIC_SYMS";
8767     if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
8768       outs() << " NO_DEAD_STRIP";
8769     if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
8770       outs() << " LIVE_SUPPORT";
8771     if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
8772       outs() << " SELF_MODIFYING_CODE";
8773     if (section_attributes & MachO::S_ATTR_DEBUG)
8774       outs() << " DEBUG";
8775     if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
8776       outs() << " SOME_INSTRUCTIONS";
8777     if (section_attributes & MachO::S_ATTR_EXT_RELOC)
8778       outs() << " EXT_RELOC";
8779     if (section_attributes & MachO::S_ATTR_LOC_RELOC)
8780       outs() << " LOC_RELOC";
8781     if (section_attributes == 0)
8782       outs() << " (none)";
8783     outs() << "\n";
8784   } else
8785     outs() << "     flags " << format("0x%08" PRIx32, flags) << "\n";
8786   outs() << " reserved1 " << reserved1;
8787   if (section_type == MachO::S_SYMBOL_STUBS ||
8788       section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
8789       section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
8790       section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
8791       section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8792     outs() << " (index into indirect symbol table)\n";
8793   else
8794     outs() << "\n";
8795   outs() << " reserved2 " << reserved2;
8796   if (section_type == MachO::S_SYMBOL_STUBS)
8797     outs() << " (size of stubs)\n";
8798   else
8799     outs() << "\n";
8800 }
8801 
8802 static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
8803                                    uint32_t object_size) {
8804   outs() << "     cmd LC_SYMTAB\n";
8805   outs() << " cmdsize " << st.cmdsize;
8806   if (st.cmdsize != sizeof(struct MachO::symtab_command))
8807     outs() << " Incorrect size\n";
8808   else
8809     outs() << "\n";
8810   outs() << "  symoff " << st.symoff;
8811   if (st.symoff > object_size)
8812     outs() << " (past end of file)\n";
8813   else
8814     outs() << "\n";
8815   outs() << "   nsyms " << st.nsyms;
8816   uint64_t big_size;
8817   if (Is64Bit) {
8818     big_size = st.nsyms;
8819     big_size *= sizeof(struct MachO::nlist_64);
8820     big_size += st.symoff;
8821     if (big_size > object_size)
8822       outs() << " (past end of file)\n";
8823     else
8824       outs() << "\n";
8825   } else {
8826     big_size = st.nsyms;
8827     big_size *= sizeof(struct MachO::nlist);
8828     big_size += st.symoff;
8829     if (big_size > object_size)
8830       outs() << " (past end of file)\n";
8831     else
8832       outs() << "\n";
8833   }
8834   outs() << "  stroff " << st.stroff;
8835   if (st.stroff > object_size)
8836     outs() << " (past end of file)\n";
8837   else
8838     outs() << "\n";
8839   outs() << " strsize " << st.strsize;
8840   big_size = st.stroff;
8841   big_size += st.strsize;
8842   if (big_size > object_size)
8843     outs() << " (past end of file)\n";
8844   else
8845     outs() << "\n";
8846 }
8847 
8848 static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
8849                                      uint32_t nsyms, uint32_t object_size,
8850                                      bool Is64Bit) {
8851   outs() << "            cmd LC_DYSYMTAB\n";
8852   outs() << "        cmdsize " << dyst.cmdsize;
8853   if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
8854     outs() << " Incorrect size\n";
8855   else
8856     outs() << "\n";
8857   outs() << "      ilocalsym " << dyst.ilocalsym;
8858   if (dyst.ilocalsym > nsyms)
8859     outs() << " (greater than the number of symbols)\n";
8860   else
8861     outs() << "\n";
8862   outs() << "      nlocalsym " << dyst.nlocalsym;
8863   uint64_t big_size;
8864   big_size = dyst.ilocalsym;
8865   big_size += dyst.nlocalsym;
8866   if (big_size > nsyms)
8867     outs() << " (past the end of the symbol table)\n";
8868   else
8869     outs() << "\n";
8870   outs() << "     iextdefsym " << dyst.iextdefsym;
8871   if (dyst.iextdefsym > nsyms)
8872     outs() << " (greater than the number of symbols)\n";
8873   else
8874     outs() << "\n";
8875   outs() << "     nextdefsym " << dyst.nextdefsym;
8876   big_size = dyst.iextdefsym;
8877   big_size += dyst.nextdefsym;
8878   if (big_size > nsyms)
8879     outs() << " (past the end of the symbol table)\n";
8880   else
8881     outs() << "\n";
8882   outs() << "      iundefsym " << dyst.iundefsym;
8883   if (dyst.iundefsym > nsyms)
8884     outs() << " (greater than the number of symbols)\n";
8885   else
8886     outs() << "\n";
8887   outs() << "      nundefsym " << dyst.nundefsym;
8888   big_size = dyst.iundefsym;
8889   big_size += dyst.nundefsym;
8890   if (big_size > nsyms)
8891     outs() << " (past the end of the symbol table)\n";
8892   else
8893     outs() << "\n";
8894   outs() << "         tocoff " << dyst.tocoff;
8895   if (dyst.tocoff > object_size)
8896     outs() << " (past end of file)\n";
8897   else
8898     outs() << "\n";
8899   outs() << "           ntoc " << dyst.ntoc;
8900   big_size = dyst.ntoc;
8901   big_size *= sizeof(struct MachO::dylib_table_of_contents);
8902   big_size += dyst.tocoff;
8903   if (big_size > object_size)
8904     outs() << " (past end of file)\n";
8905   else
8906     outs() << "\n";
8907   outs() << "      modtaboff " << dyst.modtaboff;
8908   if (dyst.modtaboff > object_size)
8909     outs() << " (past end of file)\n";
8910   else
8911     outs() << "\n";
8912   outs() << "        nmodtab " << dyst.nmodtab;
8913   uint64_t modtabend;
8914   if (Is64Bit) {
8915     modtabend = dyst.nmodtab;
8916     modtabend *= sizeof(struct MachO::dylib_module_64);
8917     modtabend += dyst.modtaboff;
8918   } else {
8919     modtabend = dyst.nmodtab;
8920     modtabend *= sizeof(struct MachO::dylib_module);
8921     modtabend += dyst.modtaboff;
8922   }
8923   if (modtabend > object_size)
8924     outs() << " (past end of file)\n";
8925   else
8926     outs() << "\n";
8927   outs() << "   extrefsymoff " << dyst.extrefsymoff;
8928   if (dyst.extrefsymoff > object_size)
8929     outs() << " (past end of file)\n";
8930   else
8931     outs() << "\n";
8932   outs() << "    nextrefsyms " << dyst.nextrefsyms;
8933   big_size = dyst.nextrefsyms;
8934   big_size *= sizeof(struct MachO::dylib_reference);
8935   big_size += dyst.extrefsymoff;
8936   if (big_size > object_size)
8937     outs() << " (past end of file)\n";
8938   else
8939     outs() << "\n";
8940   outs() << " indirectsymoff " << dyst.indirectsymoff;
8941   if (dyst.indirectsymoff > object_size)
8942     outs() << " (past end of file)\n";
8943   else
8944     outs() << "\n";
8945   outs() << "  nindirectsyms " << dyst.nindirectsyms;
8946   big_size = dyst.nindirectsyms;
8947   big_size *= sizeof(uint32_t);
8948   big_size += dyst.indirectsymoff;
8949   if (big_size > object_size)
8950     outs() << " (past end of file)\n";
8951   else
8952     outs() << "\n";
8953   outs() << "      extreloff " << dyst.extreloff;
8954   if (dyst.extreloff > object_size)
8955     outs() << " (past end of file)\n";
8956   else
8957     outs() << "\n";
8958   outs() << "        nextrel " << dyst.nextrel;
8959   big_size = dyst.nextrel;
8960   big_size *= sizeof(struct MachO::relocation_info);
8961   big_size += dyst.extreloff;
8962   if (big_size > object_size)
8963     outs() << " (past end of file)\n";
8964   else
8965     outs() << "\n";
8966   outs() << "      locreloff " << dyst.locreloff;
8967   if (dyst.locreloff > object_size)
8968     outs() << " (past end of file)\n";
8969   else
8970     outs() << "\n";
8971   outs() << "        nlocrel " << dyst.nlocrel;
8972   big_size = dyst.nlocrel;
8973   big_size *= sizeof(struct MachO::relocation_info);
8974   big_size += dyst.locreloff;
8975   if (big_size > object_size)
8976     outs() << " (past end of file)\n";
8977   else
8978     outs() << "\n";
8979 }
8980 
8981 static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
8982                                      uint32_t object_size) {
8983   if (dc.cmd == MachO::LC_DYLD_INFO)
8984     outs() << "            cmd LC_DYLD_INFO\n";
8985   else
8986     outs() << "            cmd LC_DYLD_INFO_ONLY\n";
8987   outs() << "        cmdsize " << dc.cmdsize;
8988   if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
8989     outs() << " Incorrect size\n";
8990   else
8991     outs() << "\n";
8992   outs() << "     rebase_off " << dc.rebase_off;
8993   if (dc.rebase_off > object_size)
8994     outs() << " (past end of file)\n";
8995   else
8996     outs() << "\n";
8997   outs() << "    rebase_size " << dc.rebase_size;
8998   uint64_t big_size;
8999   big_size = dc.rebase_off;
9000   big_size += dc.rebase_size;
9001   if (big_size > object_size)
9002     outs() << " (past end of file)\n";
9003   else
9004     outs() << "\n";
9005   outs() << "       bind_off " << dc.bind_off;
9006   if (dc.bind_off > object_size)
9007     outs() << " (past end of file)\n";
9008   else
9009     outs() << "\n";
9010   outs() << "      bind_size " << dc.bind_size;
9011   big_size = dc.bind_off;
9012   big_size += dc.bind_size;
9013   if (big_size > object_size)
9014     outs() << " (past end of file)\n";
9015   else
9016     outs() << "\n";
9017   outs() << "  weak_bind_off " << dc.weak_bind_off;
9018   if (dc.weak_bind_off > object_size)
9019     outs() << " (past end of file)\n";
9020   else
9021     outs() << "\n";
9022   outs() << " weak_bind_size " << dc.weak_bind_size;
9023   big_size = dc.weak_bind_off;
9024   big_size += dc.weak_bind_size;
9025   if (big_size > object_size)
9026     outs() << " (past end of file)\n";
9027   else
9028     outs() << "\n";
9029   outs() << "  lazy_bind_off " << dc.lazy_bind_off;
9030   if (dc.lazy_bind_off > object_size)
9031     outs() << " (past end of file)\n";
9032   else
9033     outs() << "\n";
9034   outs() << " lazy_bind_size " << dc.lazy_bind_size;
9035   big_size = dc.lazy_bind_off;
9036   big_size += dc.lazy_bind_size;
9037   if (big_size > object_size)
9038     outs() << " (past end of file)\n";
9039   else
9040     outs() << "\n";
9041   outs() << "     export_off " << dc.export_off;
9042   if (dc.export_off > object_size)
9043     outs() << " (past end of file)\n";
9044   else
9045     outs() << "\n";
9046   outs() << "    export_size " << dc.export_size;
9047   big_size = dc.export_off;
9048   big_size += dc.export_size;
9049   if (big_size > object_size)
9050     outs() << " (past end of file)\n";
9051   else
9052     outs() << "\n";
9053 }
9054 
9055 static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
9056                                  const char *Ptr) {
9057   if (dyld.cmd == MachO::LC_ID_DYLINKER)
9058     outs() << "          cmd LC_ID_DYLINKER\n";
9059   else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
9060     outs() << "          cmd LC_LOAD_DYLINKER\n";
9061   else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
9062     outs() << "          cmd LC_DYLD_ENVIRONMENT\n";
9063   else
9064     outs() << "          cmd ?(" << dyld.cmd << ")\n";
9065   outs() << "      cmdsize " << dyld.cmdsize;
9066   if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
9067     outs() << " Incorrect size\n";
9068   else
9069     outs() << "\n";
9070   if (dyld.name >= dyld.cmdsize)
9071     outs() << "         name ?(bad offset " << dyld.name << ")\n";
9072   else {
9073     const char *P = (const char *)(Ptr) + dyld.name;
9074     outs() << "         name " << P << " (offset " << dyld.name << ")\n";
9075   }
9076 }
9077 
9078 static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
9079   outs() << "     cmd LC_UUID\n";
9080   outs() << " cmdsize " << uuid.cmdsize;
9081   if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
9082     outs() << " Incorrect size\n";
9083   else
9084     outs() << "\n";
9085   outs() << "    uuid ";
9086   for (int i = 0; i < 16; ++i) {
9087     outs() << format("%02" PRIX32, uuid.uuid[i]);
9088     if (i == 3 || i == 5 || i == 7 || i == 9)
9089       outs() << "-";
9090   }
9091   outs() << "\n";
9092 }
9093 
9094 static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
9095   outs() << "          cmd LC_RPATH\n";
9096   outs() << "      cmdsize " << rpath.cmdsize;
9097   if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
9098     outs() << " Incorrect size\n";
9099   else
9100     outs() << "\n";
9101   if (rpath.path >= rpath.cmdsize)
9102     outs() << "         path ?(bad offset " << rpath.path << ")\n";
9103   else {
9104     const char *P = (const char *)(Ptr) + rpath.path;
9105     outs() << "         path " << P << " (offset " << rpath.path << ")\n";
9106   }
9107 }
9108 
9109 static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
9110   StringRef LoadCmdName;
9111   switch (vd.cmd) {
9112   case MachO::LC_VERSION_MIN_MACOSX:
9113     LoadCmdName = "LC_VERSION_MIN_MACOSX";
9114     break;
9115   case MachO::LC_VERSION_MIN_IPHONEOS:
9116     LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
9117     break;
9118   case MachO::LC_VERSION_MIN_TVOS:
9119     LoadCmdName = "LC_VERSION_MIN_TVOS";
9120     break;
9121   case MachO::LC_VERSION_MIN_WATCHOS:
9122     LoadCmdName = "LC_VERSION_MIN_WATCHOS";
9123     break;
9124   default:
9125     llvm_unreachable("Unknown version min load command");
9126   }
9127 
9128   outs() << "      cmd " << LoadCmdName << '\n';
9129   outs() << "  cmdsize " << vd.cmdsize;
9130   if (vd.cmdsize != sizeof(struct MachO::version_min_command))
9131     outs() << " Incorrect size\n";
9132   else
9133     outs() << "\n";
9134   outs() << "  version "
9135          << MachOObjectFile::getVersionMinMajor(vd, false) << "."
9136          << MachOObjectFile::getVersionMinMinor(vd, false);
9137   uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
9138   if (Update != 0)
9139     outs() << "." << Update;
9140   outs() << "\n";
9141   if (vd.sdk == 0)
9142     outs() << "      sdk n/a";
9143   else {
9144     outs() << "      sdk "
9145            << MachOObjectFile::getVersionMinMajor(vd, true) << "."
9146            << MachOObjectFile::getVersionMinMinor(vd, true);
9147   }
9148   Update = MachOObjectFile::getVersionMinUpdate(vd, true);
9149   if (Update != 0)
9150     outs() << "." << Update;
9151   outs() << "\n";
9152 }
9153 
9154 static void PrintNoteLoadCommand(MachO::note_command Nt) {
9155   outs() << "       cmd LC_NOTE\n";
9156   outs() << "   cmdsize " << Nt.cmdsize;
9157   if (Nt.cmdsize != sizeof(struct MachO::note_command))
9158     outs() << " Incorrect size\n";
9159   else
9160     outs() << "\n";
9161   const char *d = Nt.data_owner;
9162   outs() << "data_owner " << format("%.16s\n", d);
9163   outs() << "    offset " << Nt.offset << "\n";
9164   outs() << "      size " << Nt.size << "\n";
9165 }
9166 
9167 static void PrintBuildToolVersion(MachO::build_tool_version bv, bool verbose) {
9168   outs() << "      tool ";
9169   if (verbose)
9170     outs() << MachOObjectFile::getBuildTool(bv.tool);
9171   else
9172     outs() << bv.tool;
9173   outs() << "\n";
9174   outs() << "   version " << MachOObjectFile::getVersionString(bv.version)
9175          << "\n";
9176 }
9177 
9178 static void PrintBuildVersionLoadCommand(const MachOObjectFile *obj,
9179                                          MachO::build_version_command bd,
9180                                          bool verbose) {
9181   outs() << "       cmd LC_BUILD_VERSION\n";
9182   outs() << "   cmdsize " << bd.cmdsize;
9183   if (bd.cmdsize !=
9184       sizeof(struct MachO::build_version_command) +
9185           bd.ntools * sizeof(struct MachO::build_tool_version))
9186     outs() << " Incorrect size\n";
9187   else
9188     outs() << "\n";
9189   outs() << "  platform ";
9190   if (verbose)
9191     outs() << MachOObjectFile::getBuildPlatform(bd.platform);
9192   else
9193     outs() << bd.platform;
9194   outs() << "\n";
9195   if (bd.sdk)
9196     outs() << "       sdk " << MachOObjectFile::getVersionString(bd.sdk)
9197            << "\n";
9198   else
9199     outs() << "       sdk n/a\n";
9200   outs() << "     minos " << MachOObjectFile::getVersionString(bd.minos)
9201          << "\n";
9202   outs() << "    ntools " << bd.ntools << "\n";
9203   for (unsigned i = 0; i < bd.ntools; ++i) {
9204     MachO::build_tool_version bv = obj->getBuildToolVersion(i);
9205     PrintBuildToolVersion(bv, verbose);
9206   }
9207 }
9208 
9209 static void PrintSourceVersionCommand(MachO::source_version_command sd) {
9210   outs() << "      cmd LC_SOURCE_VERSION\n";
9211   outs() << "  cmdsize " << sd.cmdsize;
9212   if (sd.cmdsize != sizeof(struct MachO::source_version_command))
9213     outs() << " Incorrect size\n";
9214   else
9215     outs() << "\n";
9216   uint64_t a = (sd.version >> 40) & 0xffffff;
9217   uint64_t b = (sd.version >> 30) & 0x3ff;
9218   uint64_t c = (sd.version >> 20) & 0x3ff;
9219   uint64_t d = (sd.version >> 10) & 0x3ff;
9220   uint64_t e = sd.version & 0x3ff;
9221   outs() << "  version " << a << "." << b;
9222   if (e != 0)
9223     outs() << "." << c << "." << d << "." << e;
9224   else if (d != 0)
9225     outs() << "." << c << "." << d;
9226   else if (c != 0)
9227     outs() << "." << c;
9228   outs() << "\n";
9229 }
9230 
9231 static void PrintEntryPointCommand(MachO::entry_point_command ep) {
9232   outs() << "       cmd LC_MAIN\n";
9233   outs() << "   cmdsize " << ep.cmdsize;
9234   if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
9235     outs() << " Incorrect size\n";
9236   else
9237     outs() << "\n";
9238   outs() << "  entryoff " << ep.entryoff << "\n";
9239   outs() << " stacksize " << ep.stacksize << "\n";
9240 }
9241 
9242 static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
9243                                        uint32_t object_size) {
9244   outs() << "          cmd LC_ENCRYPTION_INFO\n";
9245   outs() << "      cmdsize " << ec.cmdsize;
9246   if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
9247     outs() << " Incorrect size\n";
9248   else
9249     outs() << "\n";
9250   outs() << "     cryptoff " << ec.cryptoff;
9251   if (ec.cryptoff > object_size)
9252     outs() << " (past end of file)\n";
9253   else
9254     outs() << "\n";
9255   outs() << "    cryptsize " << ec.cryptsize;
9256   if (ec.cryptsize > object_size)
9257     outs() << " (past end of file)\n";
9258   else
9259     outs() << "\n";
9260   outs() << "      cryptid " << ec.cryptid << "\n";
9261 }
9262 
9263 static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
9264                                          uint32_t object_size) {
9265   outs() << "          cmd LC_ENCRYPTION_INFO_64\n";
9266   outs() << "      cmdsize " << ec.cmdsize;
9267   if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
9268     outs() << " Incorrect size\n";
9269   else
9270     outs() << "\n";
9271   outs() << "     cryptoff " << ec.cryptoff;
9272   if (ec.cryptoff > object_size)
9273     outs() << " (past end of file)\n";
9274   else
9275     outs() << "\n";
9276   outs() << "    cryptsize " << ec.cryptsize;
9277   if (ec.cryptsize > object_size)
9278     outs() << " (past end of file)\n";
9279   else
9280     outs() << "\n";
9281   outs() << "      cryptid " << ec.cryptid << "\n";
9282   outs() << "          pad " << ec.pad << "\n";
9283 }
9284 
9285 static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
9286                                      const char *Ptr) {
9287   outs() << "     cmd LC_LINKER_OPTION\n";
9288   outs() << " cmdsize " << lo.cmdsize;
9289   if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
9290     outs() << " Incorrect size\n";
9291   else
9292     outs() << "\n";
9293   outs() << "   count " << lo.count << "\n";
9294   const char *string = Ptr + sizeof(struct MachO::linker_option_command);
9295   uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
9296   uint32_t i = 0;
9297   while (left > 0) {
9298     while (*string == '\0' && left > 0) {
9299       string++;
9300       left--;
9301     }
9302     if (left > 0) {
9303       i++;
9304       outs() << "  string #" << i << " " << format("%.*s\n", left, string);
9305       uint32_t NullPos = StringRef(string, left).find('\0');
9306       uint32_t len = std::min(NullPos, left) + 1;
9307       string += len;
9308       left -= len;
9309     }
9310   }
9311   if (lo.count != i)
9312     outs() << "   count " << lo.count << " does not match number of strings "
9313            << i << "\n";
9314 }
9315 
9316 static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
9317                                      const char *Ptr) {
9318   outs() << "          cmd LC_SUB_FRAMEWORK\n";
9319   outs() << "      cmdsize " << sub.cmdsize;
9320   if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
9321     outs() << " Incorrect size\n";
9322   else
9323     outs() << "\n";
9324   if (sub.umbrella < sub.cmdsize) {
9325     const char *P = Ptr + sub.umbrella;
9326     outs() << "     umbrella " << P << " (offset " << sub.umbrella << ")\n";
9327   } else {
9328     outs() << "     umbrella ?(bad offset " << sub.umbrella << ")\n";
9329   }
9330 }
9331 
9332 static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
9333                                     const char *Ptr) {
9334   outs() << "          cmd LC_SUB_UMBRELLA\n";
9335   outs() << "      cmdsize " << sub.cmdsize;
9336   if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
9337     outs() << " Incorrect size\n";
9338   else
9339     outs() << "\n";
9340   if (sub.sub_umbrella < sub.cmdsize) {
9341     const char *P = Ptr + sub.sub_umbrella;
9342     outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
9343   } else {
9344     outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
9345   }
9346 }
9347 
9348 static void PrintSubLibraryCommand(MachO::sub_library_command sub,
9349                                    const char *Ptr) {
9350   outs() << "          cmd LC_SUB_LIBRARY\n";
9351   outs() << "      cmdsize " << sub.cmdsize;
9352   if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
9353     outs() << " Incorrect size\n";
9354   else
9355     outs() << "\n";
9356   if (sub.sub_library < sub.cmdsize) {
9357     const char *P = Ptr + sub.sub_library;
9358     outs() << "  sub_library " << P << " (offset " << sub.sub_library << ")\n";
9359   } else {
9360     outs() << "  sub_library ?(bad offset " << sub.sub_library << ")\n";
9361   }
9362 }
9363 
9364 static void PrintSubClientCommand(MachO::sub_client_command sub,
9365                                   const char *Ptr) {
9366   outs() << "          cmd LC_SUB_CLIENT\n";
9367   outs() << "      cmdsize " << sub.cmdsize;
9368   if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
9369     outs() << " Incorrect size\n";
9370   else
9371     outs() << "\n";
9372   if (sub.client < sub.cmdsize) {
9373     const char *P = Ptr + sub.client;
9374     outs() << "       client " << P << " (offset " << sub.client << ")\n";
9375   } else {
9376     outs() << "       client ?(bad offset " << sub.client << ")\n";
9377   }
9378 }
9379 
9380 static void PrintRoutinesCommand(MachO::routines_command r) {
9381   outs() << "          cmd LC_ROUTINES\n";
9382   outs() << "      cmdsize " << r.cmdsize;
9383   if (r.cmdsize != sizeof(struct MachO::routines_command))
9384     outs() << " Incorrect size\n";
9385   else
9386     outs() << "\n";
9387   outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
9388   outs() << "  init_module " << r.init_module << "\n";
9389   outs() << "    reserved1 " << r.reserved1 << "\n";
9390   outs() << "    reserved2 " << r.reserved2 << "\n";
9391   outs() << "    reserved3 " << r.reserved3 << "\n";
9392   outs() << "    reserved4 " << r.reserved4 << "\n";
9393   outs() << "    reserved5 " << r.reserved5 << "\n";
9394   outs() << "    reserved6 " << r.reserved6 << "\n";
9395 }
9396 
9397 static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
9398   outs() << "          cmd LC_ROUTINES_64\n";
9399   outs() << "      cmdsize " << r.cmdsize;
9400   if (r.cmdsize != sizeof(struct MachO::routines_command_64))
9401     outs() << " Incorrect size\n";
9402   else
9403     outs() << "\n";
9404   outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
9405   outs() << "  init_module " << r.init_module << "\n";
9406   outs() << "    reserved1 " << r.reserved1 << "\n";
9407   outs() << "    reserved2 " << r.reserved2 << "\n";
9408   outs() << "    reserved3 " << r.reserved3 << "\n";
9409   outs() << "    reserved4 " << r.reserved4 << "\n";
9410   outs() << "    reserved5 " << r.reserved5 << "\n";
9411   outs() << "    reserved6 " << r.reserved6 << "\n";
9412 }
9413 
9414 static void Print_x86_thread_state32_t(MachO::x86_thread_state32_t &cpu32) {
9415   outs() << "\t    eax " << format("0x%08" PRIx32, cpu32.eax);
9416   outs() << " ebx    " << format("0x%08" PRIx32, cpu32.ebx);
9417   outs() << " ecx " << format("0x%08" PRIx32, cpu32.ecx);
9418   outs() << " edx " << format("0x%08" PRIx32, cpu32.edx) << "\n";
9419   outs() << "\t    edi " << format("0x%08" PRIx32, cpu32.edi);
9420   outs() << " esi    " << format("0x%08" PRIx32, cpu32.esi);
9421   outs() << " ebp " << format("0x%08" PRIx32, cpu32.ebp);
9422   outs() << " esp " << format("0x%08" PRIx32, cpu32.esp) << "\n";
9423   outs() << "\t    ss  " << format("0x%08" PRIx32, cpu32.ss);
9424   outs() << " eflags " << format("0x%08" PRIx32, cpu32.eflags);
9425   outs() << " eip " << format("0x%08" PRIx32, cpu32.eip);
9426   outs() << " cs  " << format("0x%08" PRIx32, cpu32.cs) << "\n";
9427   outs() << "\t    ds  " << format("0x%08" PRIx32, cpu32.ds);
9428   outs() << " es     " << format("0x%08" PRIx32, cpu32.es);
9429   outs() << " fs  " << format("0x%08" PRIx32, cpu32.fs);
9430   outs() << " gs  " << format("0x%08" PRIx32, cpu32.gs) << "\n";
9431 }
9432 
9433 static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
9434   outs() << "   rax  " << format("0x%016" PRIx64, cpu64.rax);
9435   outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
9436   outs() << " rcx  " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
9437   outs() << "   rdx  " << format("0x%016" PRIx64, cpu64.rdx);
9438   outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
9439   outs() << " rsi  " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
9440   outs() << "   rbp  " << format("0x%016" PRIx64, cpu64.rbp);
9441   outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
9442   outs() << " r8   " << format("0x%016" PRIx64, cpu64.r8) << "\n";
9443   outs() << "    r9  " << format("0x%016" PRIx64, cpu64.r9);
9444   outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
9445   outs() << " r11  " << format("0x%016" PRIx64, cpu64.r11) << "\n";
9446   outs() << "   r12  " << format("0x%016" PRIx64, cpu64.r12);
9447   outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
9448   outs() << " r14  " << format("0x%016" PRIx64, cpu64.r14) << "\n";
9449   outs() << "   r15  " << format("0x%016" PRIx64, cpu64.r15);
9450   outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
9451   outs() << "rflags  " << format("0x%016" PRIx64, cpu64.rflags);
9452   outs() << " cs  " << format("0x%016" PRIx64, cpu64.cs);
9453   outs() << " fs   " << format("0x%016" PRIx64, cpu64.fs) << "\n";
9454   outs() << "    gs  " << format("0x%016" PRIx64, cpu64.gs) << "\n";
9455 }
9456 
9457 static void Print_mmst_reg(MachO::mmst_reg_t &r) {
9458   uint32_t f;
9459   outs() << "\t      mmst_reg  ";
9460   for (f = 0; f < 10; f++)
9461     outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
9462   outs() << "\n";
9463   outs() << "\t      mmst_rsrv ";
9464   for (f = 0; f < 6; f++)
9465     outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
9466   outs() << "\n";
9467 }
9468 
9469 static void Print_xmm_reg(MachO::xmm_reg_t &r) {
9470   uint32_t f;
9471   outs() << "\t      xmm_reg ";
9472   for (f = 0; f < 16; f++)
9473     outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
9474   outs() << "\n";
9475 }
9476 
9477 static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
9478   outs() << "\t    fpu_reserved[0] " << fpu.fpu_reserved[0];
9479   outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
9480   outs() << "\t    control: invalid " << fpu.fpu_fcw.invalid;
9481   outs() << " denorm " << fpu.fpu_fcw.denorm;
9482   outs() << " zdiv " << fpu.fpu_fcw.zdiv;
9483   outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
9484   outs() << " undfl " << fpu.fpu_fcw.undfl;
9485   outs() << " precis " << fpu.fpu_fcw.precis << "\n";
9486   outs() << "\t\t     pc ";
9487   if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
9488     outs() << "FP_PREC_24B ";
9489   else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
9490     outs() << "FP_PREC_53B ";
9491   else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
9492     outs() << "FP_PREC_64B ";
9493   else
9494     outs() << fpu.fpu_fcw.pc << " ";
9495   outs() << "rc ";
9496   if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
9497     outs() << "FP_RND_NEAR ";
9498   else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
9499     outs() << "FP_RND_DOWN ";
9500   else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
9501     outs() << "FP_RND_UP ";
9502   else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
9503     outs() << "FP_CHOP ";
9504   outs() << "\n";
9505   outs() << "\t    status: invalid " << fpu.fpu_fsw.invalid;
9506   outs() << " denorm " << fpu.fpu_fsw.denorm;
9507   outs() << " zdiv " << fpu.fpu_fsw.zdiv;
9508   outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
9509   outs() << " undfl " << fpu.fpu_fsw.undfl;
9510   outs() << " precis " << fpu.fpu_fsw.precis;
9511   outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
9512   outs() << "\t            errsumm " << fpu.fpu_fsw.errsumm;
9513   outs() << " c0 " << fpu.fpu_fsw.c0;
9514   outs() << " c1 " << fpu.fpu_fsw.c1;
9515   outs() << " c2 " << fpu.fpu_fsw.c2;
9516   outs() << " tos " << fpu.fpu_fsw.tos;
9517   outs() << " c3 " << fpu.fpu_fsw.c3;
9518   outs() << " busy " << fpu.fpu_fsw.busy << "\n";
9519   outs() << "\t    fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
9520   outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
9521   outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
9522   outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
9523   outs() << "\t    fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
9524   outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
9525   outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
9526   outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
9527   outs() << "\t    fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
9528   outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
9529   outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
9530   outs() << "\n";
9531   outs() << "\t    fpu_stmm0:\n";
9532   Print_mmst_reg(fpu.fpu_stmm0);
9533   outs() << "\t    fpu_stmm1:\n";
9534   Print_mmst_reg(fpu.fpu_stmm1);
9535   outs() << "\t    fpu_stmm2:\n";
9536   Print_mmst_reg(fpu.fpu_stmm2);
9537   outs() << "\t    fpu_stmm3:\n";
9538   Print_mmst_reg(fpu.fpu_stmm3);
9539   outs() << "\t    fpu_stmm4:\n";
9540   Print_mmst_reg(fpu.fpu_stmm4);
9541   outs() << "\t    fpu_stmm5:\n";
9542   Print_mmst_reg(fpu.fpu_stmm5);
9543   outs() << "\t    fpu_stmm6:\n";
9544   Print_mmst_reg(fpu.fpu_stmm6);
9545   outs() << "\t    fpu_stmm7:\n";
9546   Print_mmst_reg(fpu.fpu_stmm7);
9547   outs() << "\t    fpu_xmm0:\n";
9548   Print_xmm_reg(fpu.fpu_xmm0);
9549   outs() << "\t    fpu_xmm1:\n";
9550   Print_xmm_reg(fpu.fpu_xmm1);
9551   outs() << "\t    fpu_xmm2:\n";
9552   Print_xmm_reg(fpu.fpu_xmm2);
9553   outs() << "\t    fpu_xmm3:\n";
9554   Print_xmm_reg(fpu.fpu_xmm3);
9555   outs() << "\t    fpu_xmm4:\n";
9556   Print_xmm_reg(fpu.fpu_xmm4);
9557   outs() << "\t    fpu_xmm5:\n";
9558   Print_xmm_reg(fpu.fpu_xmm5);
9559   outs() << "\t    fpu_xmm6:\n";
9560   Print_xmm_reg(fpu.fpu_xmm6);
9561   outs() << "\t    fpu_xmm7:\n";
9562   Print_xmm_reg(fpu.fpu_xmm7);
9563   outs() << "\t    fpu_xmm8:\n";
9564   Print_xmm_reg(fpu.fpu_xmm8);
9565   outs() << "\t    fpu_xmm9:\n";
9566   Print_xmm_reg(fpu.fpu_xmm9);
9567   outs() << "\t    fpu_xmm10:\n";
9568   Print_xmm_reg(fpu.fpu_xmm10);
9569   outs() << "\t    fpu_xmm11:\n";
9570   Print_xmm_reg(fpu.fpu_xmm11);
9571   outs() << "\t    fpu_xmm12:\n";
9572   Print_xmm_reg(fpu.fpu_xmm12);
9573   outs() << "\t    fpu_xmm13:\n";
9574   Print_xmm_reg(fpu.fpu_xmm13);
9575   outs() << "\t    fpu_xmm14:\n";
9576   Print_xmm_reg(fpu.fpu_xmm14);
9577   outs() << "\t    fpu_xmm15:\n";
9578   Print_xmm_reg(fpu.fpu_xmm15);
9579   outs() << "\t    fpu_rsrv4:\n";
9580   for (uint32_t f = 0; f < 6; f++) {
9581     outs() << "\t            ";
9582     for (uint32_t g = 0; g < 16; g++)
9583       outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
9584     outs() << "\n";
9585   }
9586   outs() << "\t    fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
9587   outs() << "\n";
9588 }
9589 
9590 static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
9591   outs() << "\t    trapno " << format("0x%08" PRIx32, exc64.trapno);
9592   outs() << " err " << format("0x%08" PRIx32, exc64.err);
9593   outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
9594 }
9595 
9596 static void Print_arm_thread_state32_t(MachO::arm_thread_state32_t &cpu32) {
9597   outs() << "\t    r0  " << format("0x%08" PRIx32, cpu32.r[0]);
9598   outs() << " r1     "   << format("0x%08" PRIx32, cpu32.r[1]);
9599   outs() << " r2  "      << format("0x%08" PRIx32, cpu32.r[2]);
9600   outs() << " r3  "      << format("0x%08" PRIx32, cpu32.r[3]) << "\n";
9601   outs() << "\t    r4  " << format("0x%08" PRIx32, cpu32.r[4]);
9602   outs() << " r5     "   << format("0x%08" PRIx32, cpu32.r[5]);
9603   outs() << " r6  "      << format("0x%08" PRIx32, cpu32.r[6]);
9604   outs() << " r7  "      << format("0x%08" PRIx32, cpu32.r[7]) << "\n";
9605   outs() << "\t    r8  " << format("0x%08" PRIx32, cpu32.r[8]);
9606   outs() << " r9     "   << format("0x%08" PRIx32, cpu32.r[9]);
9607   outs() << " r10 "      << format("0x%08" PRIx32, cpu32.r[10]);
9608   outs() << " r11 "      << format("0x%08" PRIx32, cpu32.r[11]) << "\n";
9609   outs() << "\t    r12 " << format("0x%08" PRIx32, cpu32.r[12]);
9610   outs() << " sp     "   << format("0x%08" PRIx32, cpu32.sp);
9611   outs() << " lr  "      << format("0x%08" PRIx32, cpu32.lr);
9612   outs() << " pc  "      << format("0x%08" PRIx32, cpu32.pc) << "\n";
9613   outs() << "\t   cpsr " << format("0x%08" PRIx32, cpu32.cpsr) << "\n";
9614 }
9615 
9616 static void Print_arm_thread_state64_t(MachO::arm_thread_state64_t &cpu64) {
9617   outs() << "\t    x0  " << format("0x%016" PRIx64, cpu64.x[0]);
9618   outs() << " x1  "      << format("0x%016" PRIx64, cpu64.x[1]);
9619   outs() << " x2  "      << format("0x%016" PRIx64, cpu64.x[2]) << "\n";
9620   outs() << "\t    x3  " << format("0x%016" PRIx64, cpu64.x[3]);
9621   outs() << " x4  "      << format("0x%016" PRIx64, cpu64.x[4]);
9622   outs() << " x5  "      << format("0x%016" PRIx64, cpu64.x[5]) << "\n";
9623   outs() << "\t    x6  " << format("0x%016" PRIx64, cpu64.x[6]);
9624   outs() << " x7  "      << format("0x%016" PRIx64, cpu64.x[7]);
9625   outs() << " x8  "      << format("0x%016" PRIx64, cpu64.x[8]) << "\n";
9626   outs() << "\t    x9  " << format("0x%016" PRIx64, cpu64.x[9]);
9627   outs() << " x10 "      << format("0x%016" PRIx64, cpu64.x[10]);
9628   outs() << " x11 "      << format("0x%016" PRIx64, cpu64.x[11]) << "\n";
9629   outs() << "\t    x12 " << format("0x%016" PRIx64, cpu64.x[12]);
9630   outs() << " x13 "      << format("0x%016" PRIx64, cpu64.x[13]);
9631   outs() << " x14 "      << format("0x%016" PRIx64, cpu64.x[14]) << "\n";
9632   outs() << "\t    x15 " << format("0x%016" PRIx64, cpu64.x[15]);
9633   outs() << " x16 "      << format("0x%016" PRIx64, cpu64.x[16]);
9634   outs() << " x17 "      << format("0x%016" PRIx64, cpu64.x[17]) << "\n";
9635   outs() << "\t    x18 " << format("0x%016" PRIx64, cpu64.x[18]);
9636   outs() << " x19 "      << format("0x%016" PRIx64, cpu64.x[19]);
9637   outs() << " x20 "      << format("0x%016" PRIx64, cpu64.x[20]) << "\n";
9638   outs() << "\t    x21 " << format("0x%016" PRIx64, cpu64.x[21]);
9639   outs() << " x22 "      << format("0x%016" PRIx64, cpu64.x[22]);
9640   outs() << " x23 "      << format("0x%016" PRIx64, cpu64.x[23]) << "\n";
9641   outs() << "\t    x24 " << format("0x%016" PRIx64, cpu64.x[24]);
9642   outs() << " x25 "      << format("0x%016" PRIx64, cpu64.x[25]);
9643   outs() << " x26 "      << format("0x%016" PRIx64, cpu64.x[26]) << "\n";
9644   outs() << "\t    x27 " << format("0x%016" PRIx64, cpu64.x[27]);
9645   outs() << " x28 "      << format("0x%016" PRIx64, cpu64.x[28]);
9646   outs() << "  fp "      << format("0x%016" PRIx64, cpu64.fp) << "\n";
9647   outs() << "\t     lr " << format("0x%016" PRIx64, cpu64.lr);
9648   outs() << " sp  "      << format("0x%016" PRIx64, cpu64.sp);
9649   outs() << "  pc "      << format("0x%016" PRIx64, cpu64.pc) << "\n";
9650   outs() << "\t   cpsr " << format("0x%08"  PRIx32, cpu64.cpsr) << "\n";
9651 }
9652 
9653 static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
9654                                bool isLittleEndian, uint32_t cputype) {
9655   if (t.cmd == MachO::LC_THREAD)
9656     outs() << "        cmd LC_THREAD\n";
9657   else if (t.cmd == MachO::LC_UNIXTHREAD)
9658     outs() << "        cmd LC_UNIXTHREAD\n";
9659   else
9660     outs() << "        cmd " << t.cmd << " (unknown)\n";
9661   outs() << "    cmdsize " << t.cmdsize;
9662   if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
9663     outs() << " Incorrect size\n";
9664   else
9665     outs() << "\n";
9666 
9667   const char *begin = Ptr + sizeof(struct MachO::thread_command);
9668   const char *end = Ptr + t.cmdsize;
9669   uint32_t flavor, count, left;
9670   if (cputype == MachO::CPU_TYPE_I386) {
9671     while (begin < end) {
9672       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9673         memcpy((char *)&flavor, begin, sizeof(uint32_t));
9674         begin += sizeof(uint32_t);
9675       } else {
9676         flavor = 0;
9677         begin = end;
9678       }
9679       if (isLittleEndian != sys::IsLittleEndianHost)
9680         sys::swapByteOrder(flavor);
9681       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9682         memcpy((char *)&count, begin, sizeof(uint32_t));
9683         begin += sizeof(uint32_t);
9684       } else {
9685         count = 0;
9686         begin = end;
9687       }
9688       if (isLittleEndian != sys::IsLittleEndianHost)
9689         sys::swapByteOrder(count);
9690       if (flavor == MachO::x86_THREAD_STATE32) {
9691         outs() << "     flavor i386_THREAD_STATE\n";
9692         if (count == MachO::x86_THREAD_STATE32_COUNT)
9693           outs() << "      count i386_THREAD_STATE_COUNT\n";
9694         else
9695           outs() << "      count " << count
9696                  << " (not x86_THREAD_STATE32_COUNT)\n";
9697         MachO::x86_thread_state32_t cpu32;
9698         left = end - begin;
9699         if (left >= sizeof(MachO::x86_thread_state32_t)) {
9700           memcpy(&cpu32, begin, sizeof(MachO::x86_thread_state32_t));
9701           begin += sizeof(MachO::x86_thread_state32_t);
9702         } else {
9703           memset(&cpu32, '\0', sizeof(MachO::x86_thread_state32_t));
9704           memcpy(&cpu32, begin, left);
9705           begin += left;
9706         }
9707         if (isLittleEndian != sys::IsLittleEndianHost)
9708           swapStruct(cpu32);
9709         Print_x86_thread_state32_t(cpu32);
9710       } else if (flavor == MachO::x86_THREAD_STATE) {
9711         outs() << "     flavor x86_THREAD_STATE\n";
9712         if (count == MachO::x86_THREAD_STATE_COUNT)
9713           outs() << "      count x86_THREAD_STATE_COUNT\n";
9714         else
9715           outs() << "      count " << count
9716                  << " (not x86_THREAD_STATE_COUNT)\n";
9717         struct MachO::x86_thread_state_t ts;
9718         left = end - begin;
9719         if (left >= sizeof(MachO::x86_thread_state_t)) {
9720           memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
9721           begin += sizeof(MachO::x86_thread_state_t);
9722         } else {
9723           memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
9724           memcpy(&ts, begin, left);
9725           begin += left;
9726         }
9727         if (isLittleEndian != sys::IsLittleEndianHost)
9728           swapStruct(ts);
9729         if (ts.tsh.flavor == MachO::x86_THREAD_STATE32) {
9730           outs() << "\t    tsh.flavor x86_THREAD_STATE32 ";
9731           if (ts.tsh.count == MachO::x86_THREAD_STATE32_COUNT)
9732             outs() << "tsh.count x86_THREAD_STATE32_COUNT\n";
9733           else
9734             outs() << "tsh.count " << ts.tsh.count
9735                    << " (not x86_THREAD_STATE32_COUNT\n";
9736           Print_x86_thread_state32_t(ts.uts.ts32);
9737         } else {
9738           outs() << "\t    tsh.flavor " << ts.tsh.flavor << "  tsh.count "
9739                  << ts.tsh.count << "\n";
9740         }
9741       } else {
9742         outs() << "     flavor " << flavor << " (unknown)\n";
9743         outs() << "      count " << count << "\n";
9744         outs() << "      state (unknown)\n";
9745         begin += count * sizeof(uint32_t);
9746       }
9747     }
9748   } else if (cputype == MachO::CPU_TYPE_X86_64) {
9749     while (begin < end) {
9750       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9751         memcpy((char *)&flavor, begin, sizeof(uint32_t));
9752         begin += sizeof(uint32_t);
9753       } else {
9754         flavor = 0;
9755         begin = end;
9756       }
9757       if (isLittleEndian != sys::IsLittleEndianHost)
9758         sys::swapByteOrder(flavor);
9759       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9760         memcpy((char *)&count, begin, sizeof(uint32_t));
9761         begin += sizeof(uint32_t);
9762       } else {
9763         count = 0;
9764         begin = end;
9765       }
9766       if (isLittleEndian != sys::IsLittleEndianHost)
9767         sys::swapByteOrder(count);
9768       if (flavor == MachO::x86_THREAD_STATE64) {
9769         outs() << "     flavor x86_THREAD_STATE64\n";
9770         if (count == MachO::x86_THREAD_STATE64_COUNT)
9771           outs() << "      count x86_THREAD_STATE64_COUNT\n";
9772         else
9773           outs() << "      count " << count
9774                  << " (not x86_THREAD_STATE64_COUNT)\n";
9775         MachO::x86_thread_state64_t cpu64;
9776         left = end - begin;
9777         if (left >= sizeof(MachO::x86_thread_state64_t)) {
9778           memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
9779           begin += sizeof(MachO::x86_thread_state64_t);
9780         } else {
9781           memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
9782           memcpy(&cpu64, begin, left);
9783           begin += left;
9784         }
9785         if (isLittleEndian != sys::IsLittleEndianHost)
9786           swapStruct(cpu64);
9787         Print_x86_thread_state64_t(cpu64);
9788       } else if (flavor == MachO::x86_THREAD_STATE) {
9789         outs() << "     flavor x86_THREAD_STATE\n";
9790         if (count == MachO::x86_THREAD_STATE_COUNT)
9791           outs() << "      count x86_THREAD_STATE_COUNT\n";
9792         else
9793           outs() << "      count " << count
9794                  << " (not x86_THREAD_STATE_COUNT)\n";
9795         struct MachO::x86_thread_state_t ts;
9796         left = end - begin;
9797         if (left >= sizeof(MachO::x86_thread_state_t)) {
9798           memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
9799           begin += sizeof(MachO::x86_thread_state_t);
9800         } else {
9801           memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
9802           memcpy(&ts, begin, left);
9803           begin += left;
9804         }
9805         if (isLittleEndian != sys::IsLittleEndianHost)
9806           swapStruct(ts);
9807         if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
9808           outs() << "\t    tsh.flavor x86_THREAD_STATE64 ";
9809           if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
9810             outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
9811           else
9812             outs() << "tsh.count " << ts.tsh.count
9813                    << " (not x86_THREAD_STATE64_COUNT\n";
9814           Print_x86_thread_state64_t(ts.uts.ts64);
9815         } else {
9816           outs() << "\t    tsh.flavor " << ts.tsh.flavor << "  tsh.count "
9817                  << ts.tsh.count << "\n";
9818         }
9819       } else if (flavor == MachO::x86_FLOAT_STATE) {
9820         outs() << "     flavor x86_FLOAT_STATE\n";
9821         if (count == MachO::x86_FLOAT_STATE_COUNT)
9822           outs() << "      count x86_FLOAT_STATE_COUNT\n";
9823         else
9824           outs() << "      count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
9825         struct MachO::x86_float_state_t fs;
9826         left = end - begin;
9827         if (left >= sizeof(MachO::x86_float_state_t)) {
9828           memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
9829           begin += sizeof(MachO::x86_float_state_t);
9830         } else {
9831           memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
9832           memcpy(&fs, begin, left);
9833           begin += left;
9834         }
9835         if (isLittleEndian != sys::IsLittleEndianHost)
9836           swapStruct(fs);
9837         if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
9838           outs() << "\t    fsh.flavor x86_FLOAT_STATE64 ";
9839           if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
9840             outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
9841           else
9842             outs() << "fsh.count " << fs.fsh.count
9843                    << " (not x86_FLOAT_STATE64_COUNT\n";
9844           Print_x86_float_state_t(fs.ufs.fs64);
9845         } else {
9846           outs() << "\t    fsh.flavor " << fs.fsh.flavor << "  fsh.count "
9847                  << fs.fsh.count << "\n";
9848         }
9849       } else if (flavor == MachO::x86_EXCEPTION_STATE) {
9850         outs() << "     flavor x86_EXCEPTION_STATE\n";
9851         if (count == MachO::x86_EXCEPTION_STATE_COUNT)
9852           outs() << "      count x86_EXCEPTION_STATE_COUNT\n";
9853         else
9854           outs() << "      count " << count
9855                  << " (not x86_EXCEPTION_STATE_COUNT)\n";
9856         struct MachO::x86_exception_state_t es;
9857         left = end - begin;
9858         if (left >= sizeof(MachO::x86_exception_state_t)) {
9859           memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
9860           begin += sizeof(MachO::x86_exception_state_t);
9861         } else {
9862           memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
9863           memcpy(&es, begin, left);
9864           begin += left;
9865         }
9866         if (isLittleEndian != sys::IsLittleEndianHost)
9867           swapStruct(es);
9868         if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
9869           outs() << "\t    esh.flavor x86_EXCEPTION_STATE64\n";
9870           if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
9871             outs() << "\t    esh.count x86_EXCEPTION_STATE64_COUNT\n";
9872           else
9873             outs() << "\t    esh.count " << es.esh.count
9874                    << " (not x86_EXCEPTION_STATE64_COUNT\n";
9875           Print_x86_exception_state_t(es.ues.es64);
9876         } else {
9877           outs() << "\t    esh.flavor " << es.esh.flavor << "  esh.count "
9878                  << es.esh.count << "\n";
9879         }
9880       } else if (flavor == MachO::x86_EXCEPTION_STATE64) {
9881         outs() << "     flavor x86_EXCEPTION_STATE64\n";
9882         if (count == MachO::x86_EXCEPTION_STATE64_COUNT)
9883           outs() << "      count x86_EXCEPTION_STATE64_COUNT\n";
9884         else
9885           outs() << "      count " << count
9886                  << " (not x86_EXCEPTION_STATE64_COUNT)\n";
9887         struct MachO::x86_exception_state64_t es64;
9888         left = end - begin;
9889         if (left >= sizeof(MachO::x86_exception_state64_t)) {
9890           memcpy(&es64, begin, sizeof(MachO::x86_exception_state64_t));
9891           begin += sizeof(MachO::x86_exception_state64_t);
9892         } else {
9893           memset(&es64, '\0', sizeof(MachO::x86_exception_state64_t));
9894           memcpy(&es64, begin, left);
9895           begin += left;
9896         }
9897         if (isLittleEndian != sys::IsLittleEndianHost)
9898           swapStruct(es64);
9899         Print_x86_exception_state_t(es64);
9900       } else {
9901         outs() << "     flavor " << flavor << " (unknown)\n";
9902         outs() << "      count " << count << "\n";
9903         outs() << "      state (unknown)\n";
9904         begin += count * sizeof(uint32_t);
9905       }
9906     }
9907   } else if (cputype == MachO::CPU_TYPE_ARM) {
9908     while (begin < end) {
9909       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9910         memcpy((char *)&flavor, begin, sizeof(uint32_t));
9911         begin += sizeof(uint32_t);
9912       } else {
9913         flavor = 0;
9914         begin = end;
9915       }
9916       if (isLittleEndian != sys::IsLittleEndianHost)
9917         sys::swapByteOrder(flavor);
9918       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9919         memcpy((char *)&count, begin, sizeof(uint32_t));
9920         begin += sizeof(uint32_t);
9921       } else {
9922         count = 0;
9923         begin = end;
9924       }
9925       if (isLittleEndian != sys::IsLittleEndianHost)
9926         sys::swapByteOrder(count);
9927       if (flavor == MachO::ARM_THREAD_STATE) {
9928         outs() << "     flavor ARM_THREAD_STATE\n";
9929         if (count == MachO::ARM_THREAD_STATE_COUNT)
9930           outs() << "      count ARM_THREAD_STATE_COUNT\n";
9931         else
9932           outs() << "      count " << count
9933                  << " (not ARM_THREAD_STATE_COUNT)\n";
9934         MachO::arm_thread_state32_t cpu32;
9935         left = end - begin;
9936         if (left >= sizeof(MachO::arm_thread_state32_t)) {
9937           memcpy(&cpu32, begin, sizeof(MachO::arm_thread_state32_t));
9938           begin += sizeof(MachO::arm_thread_state32_t);
9939         } else {
9940           memset(&cpu32, '\0', sizeof(MachO::arm_thread_state32_t));
9941           memcpy(&cpu32, begin, left);
9942           begin += left;
9943         }
9944         if (isLittleEndian != sys::IsLittleEndianHost)
9945           swapStruct(cpu32);
9946         Print_arm_thread_state32_t(cpu32);
9947       } else {
9948         outs() << "     flavor " << flavor << " (unknown)\n";
9949         outs() << "      count " << count << "\n";
9950         outs() << "      state (unknown)\n";
9951         begin += count * sizeof(uint32_t);
9952       }
9953     }
9954   } else if (cputype == MachO::CPU_TYPE_ARM64 ||
9955              cputype == MachO::CPU_TYPE_ARM64_32) {
9956     while (begin < end) {
9957       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9958         memcpy((char *)&flavor, begin, sizeof(uint32_t));
9959         begin += sizeof(uint32_t);
9960       } else {
9961         flavor = 0;
9962         begin = end;
9963       }
9964       if (isLittleEndian != sys::IsLittleEndianHost)
9965         sys::swapByteOrder(flavor);
9966       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9967         memcpy((char *)&count, begin, sizeof(uint32_t));
9968         begin += sizeof(uint32_t);
9969       } else {
9970         count = 0;
9971         begin = end;
9972       }
9973       if (isLittleEndian != sys::IsLittleEndianHost)
9974         sys::swapByteOrder(count);
9975       if (flavor == MachO::ARM_THREAD_STATE64) {
9976         outs() << "     flavor ARM_THREAD_STATE64\n";
9977         if (count == MachO::ARM_THREAD_STATE64_COUNT)
9978           outs() << "      count ARM_THREAD_STATE64_COUNT\n";
9979         else
9980           outs() << "      count " << count
9981                  << " (not ARM_THREAD_STATE64_COUNT)\n";
9982         MachO::arm_thread_state64_t cpu64;
9983         left = end - begin;
9984         if (left >= sizeof(MachO::arm_thread_state64_t)) {
9985           memcpy(&cpu64, begin, sizeof(MachO::arm_thread_state64_t));
9986           begin += sizeof(MachO::arm_thread_state64_t);
9987         } else {
9988           memset(&cpu64, '\0', sizeof(MachO::arm_thread_state64_t));
9989           memcpy(&cpu64, begin, left);
9990           begin += left;
9991         }
9992         if (isLittleEndian != sys::IsLittleEndianHost)
9993           swapStruct(cpu64);
9994         Print_arm_thread_state64_t(cpu64);
9995       } else {
9996         outs() << "     flavor " << flavor << " (unknown)\n";
9997         outs() << "      count " << count << "\n";
9998         outs() << "      state (unknown)\n";
9999         begin += count * sizeof(uint32_t);
10000       }
10001     }
10002   } else {
10003     while (begin < end) {
10004       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
10005         memcpy((char *)&flavor, begin, sizeof(uint32_t));
10006         begin += sizeof(uint32_t);
10007       } else {
10008         flavor = 0;
10009         begin = end;
10010       }
10011       if (isLittleEndian != sys::IsLittleEndianHost)
10012         sys::swapByteOrder(flavor);
10013       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
10014         memcpy((char *)&count, begin, sizeof(uint32_t));
10015         begin += sizeof(uint32_t);
10016       } else {
10017         count = 0;
10018         begin = end;
10019       }
10020       if (isLittleEndian != sys::IsLittleEndianHost)
10021         sys::swapByteOrder(count);
10022       outs() << "     flavor " << flavor << "\n";
10023       outs() << "      count " << count << "\n";
10024       outs() << "      state (Unknown cputype/cpusubtype)\n";
10025       begin += count * sizeof(uint32_t);
10026     }
10027   }
10028 }
10029 
10030 static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
10031   if (dl.cmd == MachO::LC_ID_DYLIB)
10032     outs() << "          cmd LC_ID_DYLIB\n";
10033   else if (dl.cmd == MachO::LC_LOAD_DYLIB)
10034     outs() << "          cmd LC_LOAD_DYLIB\n";
10035   else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
10036     outs() << "          cmd LC_LOAD_WEAK_DYLIB\n";
10037   else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
10038     outs() << "          cmd LC_REEXPORT_DYLIB\n";
10039   else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
10040     outs() << "          cmd LC_LAZY_LOAD_DYLIB\n";
10041   else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
10042     outs() << "          cmd LC_LOAD_UPWARD_DYLIB\n";
10043   else
10044     outs() << "          cmd " << dl.cmd << " (unknown)\n";
10045   outs() << "      cmdsize " << dl.cmdsize;
10046   if (dl.cmdsize < sizeof(struct MachO::dylib_command))
10047     outs() << " Incorrect size\n";
10048   else
10049     outs() << "\n";
10050   if (dl.dylib.name < dl.cmdsize) {
10051     const char *P = (const char *)(Ptr) + dl.dylib.name;
10052     outs() << "         name " << P << " (offset " << dl.dylib.name << ")\n";
10053   } else {
10054     outs() << "         name ?(bad offset " << dl.dylib.name << ")\n";
10055   }
10056   outs() << "   time stamp " << dl.dylib.timestamp << " ";
10057   time_t t = dl.dylib.timestamp;
10058   outs() << ctime(&t);
10059   outs() << "      current version ";
10060   if (dl.dylib.current_version == 0xffffffff)
10061     outs() << "n/a\n";
10062   else
10063     outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
10064            << ((dl.dylib.current_version >> 8) & 0xff) << "."
10065            << (dl.dylib.current_version & 0xff) << "\n";
10066   outs() << "compatibility version ";
10067   if (dl.dylib.compatibility_version == 0xffffffff)
10068     outs() << "n/a\n";
10069   else
10070     outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
10071            << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
10072            << (dl.dylib.compatibility_version & 0xff) << "\n";
10073 }
10074 
10075 static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
10076                                      uint32_t object_size) {
10077   if (ld.cmd == MachO::LC_CODE_SIGNATURE)
10078     outs() << "      cmd LC_CODE_SIGNATURE\n";
10079   else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
10080     outs() << "      cmd LC_SEGMENT_SPLIT_INFO\n";
10081   else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
10082     outs() << "      cmd LC_FUNCTION_STARTS\n";
10083   else if (ld.cmd == MachO::LC_DATA_IN_CODE)
10084     outs() << "      cmd LC_DATA_IN_CODE\n";
10085   else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
10086     outs() << "      cmd LC_DYLIB_CODE_SIGN_DRS\n";
10087   else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
10088     outs() << "      cmd LC_LINKER_OPTIMIZATION_HINT\n";
10089   else if (ld.cmd == MachO::LC_DYLD_EXPORTS_TRIE)
10090     outs() << "      cmd LC_DYLD_EXPORTS_TRIE\n";
10091   else if (ld.cmd == MachO::LC_DYLD_CHAINED_FIXUPS)
10092     outs() << "      cmd LC_DYLD_CHAINED_FIXUPS\n";
10093   else
10094     outs() << "      cmd " << ld.cmd << " (?)\n";
10095   outs() << "  cmdsize " << ld.cmdsize;
10096   if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
10097     outs() << " Incorrect size\n";
10098   else
10099     outs() << "\n";
10100   outs() << "  dataoff " << ld.dataoff;
10101   if (ld.dataoff > object_size)
10102     outs() << " (past end of file)\n";
10103   else
10104     outs() << "\n";
10105   outs() << " datasize " << ld.datasize;
10106   uint64_t big_size = ld.dataoff;
10107   big_size += ld.datasize;
10108   if (big_size > object_size)
10109     outs() << " (past end of file)\n";
10110   else
10111     outs() << "\n";
10112 }
10113 
10114 static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
10115                               uint32_t cputype, bool verbose) {
10116   StringRef Buf = Obj->getData();
10117   unsigned Index = 0;
10118   for (const auto &Command : Obj->load_commands()) {
10119     outs() << "Load command " << Index++ << "\n";
10120     if (Command.C.cmd == MachO::LC_SEGMENT) {
10121       MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
10122       const char *sg_segname = SLC.segname;
10123       PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
10124                           SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
10125                           SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
10126                           verbose);
10127       for (unsigned j = 0; j < SLC.nsects; j++) {
10128         MachO::section S = Obj->getSection(Command, j);
10129         PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
10130                      S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
10131                      SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
10132       }
10133     } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
10134       MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
10135       const char *sg_segname = SLC_64.segname;
10136       PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
10137                           SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
10138                           SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
10139                           SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
10140       for (unsigned j = 0; j < SLC_64.nsects; j++) {
10141         MachO::section_64 S_64 = Obj->getSection64(Command, j);
10142         PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
10143                      S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
10144                      S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
10145                      sg_segname, filetype, Buf.size(), verbose);
10146       }
10147     } else if (Command.C.cmd == MachO::LC_SYMTAB) {
10148       MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
10149       PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
10150     } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
10151       MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
10152       MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
10153       PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
10154                                Obj->is64Bit());
10155     } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
10156                Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
10157       MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
10158       PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
10159     } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
10160                Command.C.cmd == MachO::LC_ID_DYLINKER ||
10161                Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
10162       MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
10163       PrintDyldLoadCommand(Dyld, Command.Ptr);
10164     } else if (Command.C.cmd == MachO::LC_UUID) {
10165       MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
10166       PrintUuidLoadCommand(Uuid);
10167     } else if (Command.C.cmd == MachO::LC_RPATH) {
10168       MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
10169       PrintRpathLoadCommand(Rpath, Command.Ptr);
10170     } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
10171                Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
10172                Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
10173                Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
10174       MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
10175       PrintVersionMinLoadCommand(Vd);
10176     } else if (Command.C.cmd == MachO::LC_NOTE) {
10177       MachO::note_command Nt = Obj->getNoteLoadCommand(Command);
10178       PrintNoteLoadCommand(Nt);
10179     } else if (Command.C.cmd == MachO::LC_BUILD_VERSION) {
10180       MachO::build_version_command Bv =
10181           Obj->getBuildVersionLoadCommand(Command);
10182       PrintBuildVersionLoadCommand(Obj, Bv, verbose);
10183     } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
10184       MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
10185       PrintSourceVersionCommand(Sd);
10186     } else if (Command.C.cmd == MachO::LC_MAIN) {
10187       MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
10188       PrintEntryPointCommand(Ep);
10189     } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
10190       MachO::encryption_info_command Ei =
10191           Obj->getEncryptionInfoCommand(Command);
10192       PrintEncryptionInfoCommand(Ei, Buf.size());
10193     } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
10194       MachO::encryption_info_command_64 Ei =
10195           Obj->getEncryptionInfoCommand64(Command);
10196       PrintEncryptionInfoCommand64(Ei, Buf.size());
10197     } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
10198       MachO::linker_option_command Lo =
10199           Obj->getLinkerOptionLoadCommand(Command);
10200       PrintLinkerOptionCommand(Lo, Command.Ptr);
10201     } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
10202       MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
10203       PrintSubFrameworkCommand(Sf, Command.Ptr);
10204     } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
10205       MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
10206       PrintSubUmbrellaCommand(Sf, Command.Ptr);
10207     } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
10208       MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
10209       PrintSubLibraryCommand(Sl, Command.Ptr);
10210     } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
10211       MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
10212       PrintSubClientCommand(Sc, Command.Ptr);
10213     } else if (Command.C.cmd == MachO::LC_ROUTINES) {
10214       MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
10215       PrintRoutinesCommand(Rc);
10216     } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
10217       MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
10218       PrintRoutinesCommand64(Rc);
10219     } else if (Command.C.cmd == MachO::LC_THREAD ||
10220                Command.C.cmd == MachO::LC_UNIXTHREAD) {
10221       MachO::thread_command Tc = Obj->getThreadCommand(Command);
10222       PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
10223     } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
10224                Command.C.cmd == MachO::LC_ID_DYLIB ||
10225                Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
10226                Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
10227                Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
10228                Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
10229       MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
10230       PrintDylibCommand(Dl, Command.Ptr);
10231     } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
10232                Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
10233                Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
10234                Command.C.cmd == MachO::LC_DATA_IN_CODE ||
10235                Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
10236                Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT ||
10237                Command.C.cmd == MachO::LC_DYLD_EXPORTS_TRIE ||
10238                Command.C.cmd == MachO::LC_DYLD_CHAINED_FIXUPS) {
10239       MachO::linkedit_data_command Ld =
10240           Obj->getLinkeditDataLoadCommand(Command);
10241       PrintLinkEditDataCommand(Ld, Buf.size());
10242     } else {
10243       outs() << "      cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
10244              << ")\n";
10245       outs() << "  cmdsize " << Command.C.cmdsize << "\n";
10246       // TODO: get and print the raw bytes of the load command.
10247     }
10248     // TODO: print all the other kinds of load commands.
10249   }
10250 }
10251 
10252 static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
10253   if (Obj->is64Bit()) {
10254     MachO::mach_header_64 H_64;
10255     H_64 = Obj->getHeader64();
10256     PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
10257                     H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
10258   } else {
10259     MachO::mach_header H;
10260     H = Obj->getHeader();
10261     PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
10262                     H.sizeofcmds, H.flags, verbose);
10263   }
10264 }
10265 
10266 void objdump::printMachOFileHeader(const object::ObjectFile *Obj) {
10267   const MachOObjectFile *file = cast<const MachOObjectFile>(Obj);
10268   PrintMachHeader(file, Verbose);
10269 }
10270 
10271 void objdump::printMachOLoadCommands(const object::ObjectFile *Obj) {
10272   const MachOObjectFile *file = cast<const MachOObjectFile>(Obj);
10273   uint32_t filetype = 0;
10274   uint32_t cputype = 0;
10275   if (file->is64Bit()) {
10276     MachO::mach_header_64 H_64;
10277     H_64 = file->getHeader64();
10278     filetype = H_64.filetype;
10279     cputype = H_64.cputype;
10280   } else {
10281     MachO::mach_header H;
10282     H = file->getHeader();
10283     filetype = H.filetype;
10284     cputype = H.cputype;
10285   }
10286   PrintLoadCommands(file, filetype, cputype, Verbose);
10287 }
10288 
10289 //===----------------------------------------------------------------------===//
10290 // export trie dumping
10291 //===----------------------------------------------------------------------===//
10292 
10293 static void printMachOExportsTrie(const object::MachOObjectFile *Obj) {
10294   uint64_t BaseSegmentAddress = 0;
10295   for (const auto &Command : Obj->load_commands()) {
10296     if (Command.C.cmd == MachO::LC_SEGMENT) {
10297       MachO::segment_command Seg = Obj->getSegmentLoadCommand(Command);
10298       if (Seg.fileoff == 0 && Seg.filesize != 0) {
10299         BaseSegmentAddress = Seg.vmaddr;
10300         break;
10301       }
10302     } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
10303       MachO::segment_command_64 Seg = Obj->getSegment64LoadCommand(Command);
10304       if (Seg.fileoff == 0 && Seg.filesize != 0) {
10305         BaseSegmentAddress = Seg.vmaddr;
10306         break;
10307       }
10308     }
10309   }
10310   Error Err = Error::success();
10311   for (const object::ExportEntry &Entry : Obj->exports(Err)) {
10312     uint64_t Flags = Entry.flags();
10313     bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
10314     bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
10315     bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
10316                         MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
10317     bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
10318                 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
10319     bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
10320     if (ReExport)
10321       outs() << "[re-export] ";
10322     else
10323       outs() << format("0x%08llX  ",
10324                        Entry.address() + BaseSegmentAddress);
10325     outs() << Entry.name();
10326     if (WeakDef || ThreadLocal || Resolver || Abs) {
10327       ListSeparator LS;
10328       outs() << " [";
10329       if (WeakDef)
10330         outs() << LS << "weak_def";
10331       if (ThreadLocal)
10332         outs() << LS << "per-thread";
10333       if (Abs)
10334         outs() << LS << "absolute";
10335       if (Resolver)
10336         outs() << LS << format("resolver=0x%08llX", Entry.other());
10337       outs() << "]";
10338     }
10339     if (ReExport) {
10340       StringRef DylibName = "unknown";
10341       int Ordinal = Entry.other() - 1;
10342       Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
10343       if (Entry.otherName().empty())
10344         outs() << " (from " << DylibName << ")";
10345       else
10346         outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
10347     }
10348     outs() << "\n";
10349   }
10350   if (Err)
10351     reportError(std::move(Err), Obj->getFileName());
10352 }
10353 
10354 //===----------------------------------------------------------------------===//
10355 // rebase table dumping
10356 //===----------------------------------------------------------------------===//
10357 
10358 static void printMachORebaseTable(object::MachOObjectFile *Obj) {
10359   outs() << "segment  section            address     type\n";
10360   Error Err = Error::success();
10361   for (const object::MachORebaseEntry &Entry : Obj->rebaseTable(Err)) {
10362     StringRef SegmentName = Entry.segmentName();
10363     StringRef SectionName = Entry.sectionName();
10364     uint64_t Address = Entry.address();
10365 
10366     // Table lines look like: __DATA  __nl_symbol_ptr  0x0000F00C  pointer
10367     outs() << format("%-8s %-18s 0x%08" PRIX64 "  %s\n",
10368                      SegmentName.str().c_str(), SectionName.str().c_str(),
10369                      Address, Entry.typeName().str().c_str());
10370   }
10371   if (Err)
10372     reportError(std::move(Err), Obj->getFileName());
10373 }
10374 
10375 static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
10376   StringRef DylibName;
10377   switch (Ordinal) {
10378   case MachO::BIND_SPECIAL_DYLIB_SELF:
10379     return "this-image";
10380   case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
10381     return "main-executable";
10382   case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
10383     return "flat-namespace";
10384   default:
10385     if (Ordinal > 0) {
10386       std::error_code EC =
10387           Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
10388       if (EC)
10389         return "<<bad library ordinal>>";
10390       return DylibName;
10391     }
10392   }
10393   return "<<unknown special ordinal>>";
10394 }
10395 
10396 //===----------------------------------------------------------------------===//
10397 // bind table dumping
10398 //===----------------------------------------------------------------------===//
10399 
10400 static void printMachOBindTable(object::MachOObjectFile *Obj) {
10401   // Build table of sections so names can used in final output.
10402   outs() << "segment  section            address    type       "
10403             "addend dylib            symbol\n";
10404   Error Err = Error::success();
10405   for (const object::MachOBindEntry &Entry : Obj->bindTable(Err)) {
10406     StringRef SegmentName = Entry.segmentName();
10407     StringRef SectionName = Entry.sectionName();
10408     uint64_t Address = Entry.address();
10409 
10410     // Table lines look like:
10411     //  __DATA  __got  0x00012010    pointer   0 libSystem ___stack_chk_guard
10412     StringRef Attr;
10413     if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
10414       Attr = " (weak_import)";
10415     outs() << left_justify(SegmentName, 8) << " "
10416            << left_justify(SectionName, 18) << " "
10417            << format_hex(Address, 10, true) << " "
10418            << left_justify(Entry.typeName(), 8) << " "
10419            << format_decimal(Entry.addend(), 8) << " "
10420            << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
10421            << Entry.symbolName() << Attr << "\n";
10422   }
10423   if (Err)
10424     reportError(std::move(Err), Obj->getFileName());
10425 }
10426 
10427 //===----------------------------------------------------------------------===//
10428 // lazy bind table dumping
10429 //===----------------------------------------------------------------------===//
10430 
10431 static void printMachOLazyBindTable(object::MachOObjectFile *Obj) {
10432   outs() << "segment  section            address     "
10433             "dylib            symbol\n";
10434   Error Err = Error::success();
10435   for (const object::MachOBindEntry &Entry : Obj->lazyBindTable(Err)) {
10436     StringRef SegmentName = Entry.segmentName();
10437     StringRef SectionName = Entry.sectionName();
10438     uint64_t Address = Entry.address();
10439 
10440     // Table lines look like:
10441     //  __DATA  __got  0x00012010 libSystem ___stack_chk_guard
10442     outs() << left_justify(SegmentName, 8) << " "
10443            << left_justify(SectionName, 18) << " "
10444            << format_hex(Address, 10, true) << " "
10445            << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
10446            << Entry.symbolName() << "\n";
10447   }
10448   if (Err)
10449     reportError(std::move(Err), Obj->getFileName());
10450 }
10451 
10452 //===----------------------------------------------------------------------===//
10453 // weak bind table dumping
10454 //===----------------------------------------------------------------------===//
10455 
10456 static void printMachOWeakBindTable(object::MachOObjectFile *Obj) {
10457   outs() << "segment  section            address     "
10458             "type       addend   symbol\n";
10459   Error Err = Error::success();
10460   for (const object::MachOBindEntry &Entry : Obj->weakBindTable(Err)) {
10461     // Strong symbols don't have a location to update.
10462     if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
10463       outs() << "                                        strong              "
10464              << Entry.symbolName() << "\n";
10465       continue;
10466     }
10467     StringRef SegmentName = Entry.segmentName();
10468     StringRef SectionName = Entry.sectionName();
10469     uint64_t Address = Entry.address();
10470 
10471     // Table lines look like:
10472     // __DATA  __data  0x00001000  pointer    0   _foo
10473     outs() << left_justify(SegmentName, 8) << " "
10474            << left_justify(SectionName, 18) << " "
10475            << format_hex(Address, 10, true) << " "
10476            << left_justify(Entry.typeName(), 8) << " "
10477            << format_decimal(Entry.addend(), 8) << "   " << Entry.symbolName()
10478            << "\n";
10479   }
10480   if (Err)
10481     reportError(std::move(Err), Obj->getFileName());
10482 }
10483 
10484 // get_dyld_bind_info_symbolname() is used for disassembly and passed an
10485 // address, ReferenceValue, in the Mach-O file and looks in the dyld bind
10486 // information for that address. If the address is found its binding symbol
10487 // name is returned.  If not nullptr is returned.
10488 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
10489                                                  struct DisassembleInfo *info) {
10490   if (info->bindtable == nullptr) {
10491     info->bindtable = std::make_unique<SymbolAddressMap>();
10492     Error Err = Error::success();
10493     for (const object::MachOBindEntry &Entry : info->O->bindTable(Err)) {
10494       uint64_t Address = Entry.address();
10495       StringRef name = Entry.symbolName();
10496       if (!name.empty())
10497         (*info->bindtable)[Address] = name;
10498     }
10499     if (Err)
10500       reportError(std::move(Err), info->O->getFileName());
10501   }
10502   auto name = info->bindtable->lookup(ReferenceValue);
10503   return !name.empty() ? name.data() : nullptr;
10504 }
10505 
10506 void objdump::printLazyBindTable(ObjectFile *o) {
10507   outs() << "\nLazy bind table:\n";
10508   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10509     printMachOLazyBindTable(MachO);
10510   else
10511     WithColor::error()
10512         << "This operation is only currently supported "
10513            "for Mach-O executable files.\n";
10514 }
10515 
10516 void objdump::printWeakBindTable(ObjectFile *o) {
10517   outs() << "\nWeak bind table:\n";
10518   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10519     printMachOWeakBindTable(MachO);
10520   else
10521     WithColor::error()
10522         << "This operation is only currently supported "
10523            "for Mach-O executable files.\n";
10524 }
10525 
10526 void objdump::printExportsTrie(const ObjectFile *o) {
10527   outs() << "\nExports trie:\n";
10528   if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10529     printMachOExportsTrie(MachO);
10530   else
10531     WithColor::error()
10532         << "This operation is only currently supported "
10533            "for Mach-O executable files.\n";
10534 }
10535 
10536 void objdump::printRebaseTable(ObjectFile *o) {
10537   outs() << "\nRebase table:\n";
10538   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10539     printMachORebaseTable(MachO);
10540   else
10541     WithColor::error()
10542         << "This operation is only currently supported "
10543            "for Mach-O executable files.\n";
10544 }
10545 
10546 void objdump::printBindTable(ObjectFile *o) {
10547   outs() << "\nBind table:\n";
10548   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10549     printMachOBindTable(MachO);
10550   else
10551     WithColor::error()
10552         << "This operation is only currently supported "
10553            "for Mach-O executable files.\n";
10554 }
10555