1 //===-- MachODump.cpp - Object file dumping utility for llvm --------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the MachO-specific dumper for llvm-objdump.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "MachODump.h"
14 
15 #include "llvm-objdump.h"
16 #include "llvm-c/Disassembler.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/Triple.h"
20 #include "llvm/BinaryFormat/MachO.h"
21 #include "llvm/Config/config.h"
22 #include "llvm/DebugInfo/DIContext.h"
23 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
24 #include "llvm/Demangle/Demangle.h"
25 #include "llvm/MC/MCAsmInfo.h"
26 #include "llvm/MC/MCContext.h"
27 #include "llvm/MC/MCDisassembler/MCDisassembler.h"
28 #include "llvm/MC/MCInst.h"
29 #include "llvm/MC/MCInstPrinter.h"
30 #include "llvm/MC/MCInstrDesc.h"
31 #include "llvm/MC/MCInstrInfo.h"
32 #include "llvm/MC/MCRegisterInfo.h"
33 #include "llvm/MC/MCSubtargetInfo.h"
34 #include "llvm/MC/MCTargetOptions.h"
35 #include "llvm/Object/MachO.h"
36 #include "llvm/Object/MachOUniversal.h"
37 #include "llvm/Support/Casting.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/Endian.h"
41 #include "llvm/Support/Format.h"
42 #include "llvm/Support/FormattedStream.h"
43 #include "llvm/Support/GraphWriter.h"
44 #include "llvm/Support/LEB128.h"
45 #include "llvm/Support/MemoryBuffer.h"
46 #include "llvm/Support/TargetRegistry.h"
47 #include "llvm/Support/TargetSelect.h"
48 #include "llvm/Support/ToolOutputFile.h"
49 #include "llvm/Support/WithColor.h"
50 #include "llvm/Support/raw_ostream.h"
51 #include <algorithm>
52 #include <cstring>
53 #include <system_error>
54 
55 #ifdef HAVE_LIBXAR
56 extern "C" {
57 #include <xar/xar.h>
58 }
59 #endif
60 
61 using namespace llvm;
62 using namespace llvm::object;
63 using namespace llvm::objdump;
64 
65 cl::OptionCategory objdump::MachOCat("llvm-objdump MachO Specific Options");
66 
67 cl::opt<bool> objdump::FirstPrivateHeader(
68     "private-header",
69     cl::desc("Display only the first format specific file header"),
70     cl::cat(MachOCat));
71 
72 cl::opt<bool> objdump::ExportsTrie("exports-trie",
73                                    cl::desc("Display mach-o exported symbols"),
74                                    cl::cat(MachOCat));
75 
76 cl::opt<bool> objdump::Rebase("rebase",
77                               cl::desc("Display mach-o rebasing info"),
78                               cl::cat(MachOCat));
79 
80 cl::opt<bool> objdump::Bind("bind", cl::desc("Display mach-o binding info"),
81                             cl::cat(MachOCat));
82 
83 cl::opt<bool> objdump::LazyBind("lazy-bind",
84                                 cl::desc("Display mach-o lazy binding info"),
85                                 cl::cat(MachOCat));
86 
87 cl::opt<bool> objdump::WeakBind("weak-bind",
88                                 cl::desc("Display mach-o weak binding info"),
89                                 cl::cat(MachOCat));
90 
91 static cl::opt<bool>
92     UseDbg("g", cl::Grouping,
93            cl::desc("Print line information from debug info if available"),
94            cl::cat(MachOCat));
95 
96 static cl::opt<std::string> DSYMFile("dsym",
97                                      cl::desc("Use .dSYM file for debug info"),
98                                      cl::cat(MachOCat));
99 
100 static cl::opt<bool> FullLeadingAddr("full-leading-addr",
101                                      cl::desc("Print full leading address"),
102                                      cl::cat(MachOCat));
103 
104 static cl::opt<bool> NoLeadingHeaders("no-leading-headers",
105                                       cl::desc("Print no leading headers"),
106                                       cl::cat(MachOCat));
107 
108 cl::opt<bool> objdump::UniversalHeaders(
109     "universal-headers",
110     cl::desc("Print Mach-O universal headers (requires --macho)"),
111     cl::cat(MachOCat));
112 
113 static cl::opt<bool> ArchiveMemberOffsets(
114     "archive-member-offsets",
115     cl::desc("Print the offset to each archive member for Mach-O archives "
116              "(requires --macho and --archive-headers)"),
117     cl::cat(MachOCat));
118 
119 cl::opt<bool> objdump::IndirectSymbols(
120     "indirect-symbols",
121     cl::desc(
122         "Print indirect symbol table for Mach-O objects (requires --macho)"),
123     cl::cat(MachOCat));
124 
125 cl::opt<bool> objdump::DataInCode(
126     "data-in-code",
127     cl::desc(
128         "Print the data in code table for Mach-O objects (requires --macho)"),
129     cl::cat(MachOCat));
130 
131 cl::opt<bool>
132     objdump::LinkOptHints("link-opt-hints",
133                           cl::desc("Print the linker optimization hints for "
134                                    "Mach-O objects (requires --macho)"),
135                           cl::cat(MachOCat));
136 
137 cl::opt<bool>
138     objdump::InfoPlist("info-plist",
139                        cl::desc("Print the info plist section as strings for "
140                                 "Mach-O objects (requires --macho)"),
141                        cl::cat(MachOCat));
142 
143 cl::opt<bool>
144     objdump::DylibsUsed("dylibs-used",
145                         cl::desc("Print the shared libraries used for linked "
146                                  "Mach-O files (requires --macho)"),
147                         cl::cat(MachOCat));
148 
149 cl::opt<bool> objdump::DylibId("dylib-id",
150                                cl::desc("Print the shared library's id for the "
151                                         "dylib Mach-O file (requires --macho)"),
152                                cl::cat(MachOCat));
153 
154 static cl::opt<bool>
155     NonVerbose("non-verbose",
156                cl::desc("Print the info for Mach-O objects in non-verbose or "
157                         "numeric form (requires --macho)"),
158                cl::cat(MachOCat));
159 
160 cl::opt<bool>
161     objdump::ObjcMetaData("objc-meta-data",
162                           cl::desc("Print the Objective-C runtime meta data "
163                                    "for Mach-O files (requires --macho)"),
164                           cl::cat(MachOCat));
165 
166 static cl::opt<std::string> DisSymName(
167     "dis-symname",
168     cl::desc("disassemble just this symbol's instructions (requires --macho)"),
169     cl::cat(MachOCat));
170 
171 static cl::opt<bool> NoSymbolicOperands(
172     "no-symbolic-operands",
173     cl::desc("do not symbolic operands when disassembling (requires --macho)"),
174     cl::cat(MachOCat));
175 
176 static cl::list<std::string>
177     ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
178               cl::ZeroOrMore, cl::cat(MachOCat));
179 
180 static bool ArchAll = false;
181 
182 static std::string ThumbTripleName;
183 
184 static const Target *GetTarget(const MachOObjectFile *MachOObj,
185                                const char **McpuDefault,
186                                const Target **ThumbTarget) {
187   // Figure out the target triple.
188   Triple TT(TripleName);
189   if (TripleName.empty()) {
190     TT = MachOObj->getArchTriple(McpuDefault);
191     TripleName = TT.str();
192   }
193 
194   if (TT.getArch() == Triple::arm) {
195     // We've inferred a 32-bit ARM target from the object file. All MachO CPUs
196     // that support ARM are also capable of Thumb mode.
197     Triple ThumbTriple = TT;
198     std::string ThumbName = (Twine("thumb") + TT.getArchName().substr(3)).str();
199     ThumbTriple.setArchName(ThumbName);
200     ThumbTripleName = ThumbTriple.str();
201   }
202 
203   // Get the target specific parser.
204   std::string Error;
205   const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
206   if (TheTarget && ThumbTripleName.empty())
207     return TheTarget;
208 
209   *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
210   if (*ThumbTarget)
211     return TheTarget;
212 
213   WithColor::error(errs(), "llvm-objdump") << "unable to get target for '";
214   if (!TheTarget)
215     errs() << TripleName;
216   else
217     errs() << ThumbTripleName;
218   errs() << "', see --version and --triple.\n";
219   return nullptr;
220 }
221 
222 namespace {
223 struct SymbolSorter {
224   bool operator()(const SymbolRef &A, const SymbolRef &B) {
225     Expected<SymbolRef::Type> ATypeOrErr = A.getType();
226     if (!ATypeOrErr)
227       reportError(ATypeOrErr.takeError(), A.getObject()->getFileName());
228     SymbolRef::Type AType = *ATypeOrErr;
229     Expected<SymbolRef::Type> BTypeOrErr = B.getType();
230     if (!BTypeOrErr)
231       reportError(BTypeOrErr.takeError(), B.getObject()->getFileName());
232     SymbolRef::Type BType = *BTypeOrErr;
233     uint64_t AAddr =
234         (AType != SymbolRef::ST_Function) ? 0 : cantFail(A.getValue());
235     uint64_t BAddr =
236         (BType != SymbolRef::ST_Function) ? 0 : cantFail(B.getValue());
237     return AAddr < BAddr;
238   }
239 };
240 } // namespace
241 
242 // Types for the storted data in code table that is built before disassembly
243 // and the predicate function to sort them.
244 typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
245 typedef std::vector<DiceTableEntry> DiceTable;
246 typedef DiceTable::iterator dice_table_iterator;
247 
248 #ifdef HAVE_LIBXAR
249 namespace {
250 struct ScopedXarFile {
251   xar_t xar;
252   ScopedXarFile(const char *filename, int32_t flags)
253       : xar(xar_open(filename, flags)) {}
254   ~ScopedXarFile() {
255     if (xar)
256       xar_close(xar);
257   }
258   ScopedXarFile(const ScopedXarFile &) = delete;
259   ScopedXarFile &operator=(const ScopedXarFile &) = delete;
260   operator xar_t() { return xar; }
261 };
262 
263 struct ScopedXarIter {
264   xar_iter_t iter;
265   ScopedXarIter() : iter(xar_iter_new()) {}
266   ~ScopedXarIter() {
267     if (iter)
268       xar_iter_free(iter);
269   }
270   ScopedXarIter(const ScopedXarIter &) = delete;
271   ScopedXarIter &operator=(const ScopedXarIter &) = delete;
272   operator xar_iter_t() { return iter; }
273 };
274 } // namespace
275 #endif // defined(HAVE_LIBXAR)
276 
277 // This is used to search for a data in code table entry for the PC being
278 // disassembled.  The j parameter has the PC in j.first.  A single data in code
279 // table entry can cover many bytes for each of its Kind's.  So if the offset,
280 // aka the i.first value, of the data in code table entry plus its Length
281 // covers the PC being searched for this will return true.  If not it will
282 // return false.
283 static bool compareDiceTableEntries(const DiceTableEntry &i,
284                                     const DiceTableEntry &j) {
285   uint16_t Length;
286   i.second.getLength(Length);
287 
288   return j.first >= i.first && j.first < i.first + Length;
289 }
290 
291 static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
292                                unsigned short Kind) {
293   uint32_t Value, Size = 1;
294 
295   switch (Kind) {
296   default:
297   case MachO::DICE_KIND_DATA:
298     if (Length >= 4) {
299       if (!NoShowRawInsn)
300         dumpBytes(makeArrayRef(bytes, 4), outs());
301       Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
302       outs() << "\t.long " << Value;
303       Size = 4;
304     } else if (Length >= 2) {
305       if (!NoShowRawInsn)
306         dumpBytes(makeArrayRef(bytes, 2), outs());
307       Value = bytes[1] << 8 | bytes[0];
308       outs() << "\t.short " << Value;
309       Size = 2;
310     } else {
311       if (!NoShowRawInsn)
312         dumpBytes(makeArrayRef(bytes, 2), outs());
313       Value = bytes[0];
314       outs() << "\t.byte " << Value;
315       Size = 1;
316     }
317     if (Kind == MachO::DICE_KIND_DATA)
318       outs() << "\t@ KIND_DATA\n";
319     else
320       outs() << "\t@ data in code kind = " << Kind << "\n";
321     break;
322   case MachO::DICE_KIND_JUMP_TABLE8:
323     if (!NoShowRawInsn)
324       dumpBytes(makeArrayRef(bytes, 1), outs());
325     Value = bytes[0];
326     outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
327     Size = 1;
328     break;
329   case MachO::DICE_KIND_JUMP_TABLE16:
330     if (!NoShowRawInsn)
331       dumpBytes(makeArrayRef(bytes, 2), outs());
332     Value = bytes[1] << 8 | bytes[0];
333     outs() << "\t.short " << format("%5u", Value & 0xffff)
334            << "\t@ KIND_JUMP_TABLE16\n";
335     Size = 2;
336     break;
337   case MachO::DICE_KIND_JUMP_TABLE32:
338   case MachO::DICE_KIND_ABS_JUMP_TABLE32:
339     if (!NoShowRawInsn)
340       dumpBytes(makeArrayRef(bytes, 4), outs());
341     Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
342     outs() << "\t.long " << Value;
343     if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
344       outs() << "\t@ KIND_JUMP_TABLE32\n";
345     else
346       outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
347     Size = 4;
348     break;
349   }
350   return Size;
351 }
352 
353 static void getSectionsAndSymbols(MachOObjectFile *MachOObj,
354                                   std::vector<SectionRef> &Sections,
355                                   std::vector<SymbolRef> &Symbols,
356                                   SmallVectorImpl<uint64_t> &FoundFns,
357                                   uint64_t &BaseSegmentAddress) {
358   const StringRef FileName = MachOObj->getFileName();
359   for (const SymbolRef &Symbol : MachOObj->symbols()) {
360     StringRef SymName = unwrapOrError(Symbol.getName(), FileName);
361     if (!SymName.startswith("ltmp"))
362       Symbols.push_back(Symbol);
363   }
364 
365   append_range(Sections, MachOObj->sections());
366 
367   bool BaseSegmentAddressSet = false;
368   for (const auto &Command : MachOObj->load_commands()) {
369     if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
370       // We found a function starts segment, parse the addresses for later
371       // consumption.
372       MachO::linkedit_data_command LLC =
373           MachOObj->getLinkeditDataLoadCommand(Command);
374 
375       MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
376     } else if (Command.C.cmd == MachO::LC_SEGMENT) {
377       MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
378       StringRef SegName = SLC.segname;
379       if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
380         BaseSegmentAddressSet = true;
381         BaseSegmentAddress = SLC.vmaddr;
382       }
383     } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
384       MachO::segment_command_64 SLC = MachOObj->getSegment64LoadCommand(Command);
385       StringRef SegName = SLC.segname;
386       if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
387         BaseSegmentAddressSet = true;
388         BaseSegmentAddress = SLC.vmaddr;
389       }
390     }
391   }
392 }
393 
394 static bool DumpAndSkipDataInCode(uint64_t PC, const uint8_t *bytes,
395                                  DiceTable &Dices, uint64_t &InstSize) {
396   // Check the data in code table here to see if this is data not an
397   // instruction to be disassembled.
398   DiceTable Dice;
399   Dice.push_back(std::make_pair(PC, DiceRef()));
400   dice_table_iterator DTI =
401       std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
402                   compareDiceTableEntries);
403   if (DTI != Dices.end()) {
404     uint16_t Length;
405     DTI->second.getLength(Length);
406     uint16_t Kind;
407     DTI->second.getKind(Kind);
408     InstSize = DumpDataInCode(bytes, Length, Kind);
409     if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
410         (PC == (DTI->first + Length - 1)) && (Length & 1))
411       InstSize++;
412     return true;
413   }
414   return false;
415 }
416 
417 static void printRelocationTargetName(const MachOObjectFile *O,
418                                       const MachO::any_relocation_info &RE,
419                                       raw_string_ostream &Fmt) {
420   // Target of a scattered relocation is an address.  In the interest of
421   // generating pretty output, scan through the symbol table looking for a
422   // symbol that aligns with that address.  If we find one, print it.
423   // Otherwise, we just print the hex address of the target.
424   const StringRef FileName = O->getFileName();
425   if (O->isRelocationScattered(RE)) {
426     uint32_t Val = O->getPlainRelocationSymbolNum(RE);
427 
428     for (const SymbolRef &Symbol : O->symbols()) {
429       uint64_t Addr = unwrapOrError(Symbol.getAddress(), FileName);
430       if (Addr != Val)
431         continue;
432       Fmt << unwrapOrError(Symbol.getName(), FileName);
433       return;
434     }
435 
436     // If we couldn't find a symbol that this relocation refers to, try
437     // to find a section beginning instead.
438     for (const SectionRef &Section : ToolSectionFilter(*O)) {
439       uint64_t Addr = Section.getAddress();
440       if (Addr != Val)
441         continue;
442       StringRef NameOrErr = unwrapOrError(Section.getName(), O->getFileName());
443       Fmt << NameOrErr;
444       return;
445     }
446 
447     Fmt << format("0x%x", Val);
448     return;
449   }
450 
451   StringRef S;
452   bool isExtern = O->getPlainRelocationExternal(RE);
453   uint64_t Val = O->getPlainRelocationSymbolNum(RE);
454 
455   if (O->getAnyRelocationType(RE) == MachO::ARM64_RELOC_ADDEND &&
456       (O->getArch() == Triple::aarch64 || O->getArch() == Triple::aarch64_be)) {
457     Fmt << format("0x%0" PRIx64, Val);
458     return;
459   }
460 
461   if (isExtern) {
462     symbol_iterator SI = O->symbol_begin();
463     advance(SI, Val);
464     S = unwrapOrError(SI->getName(), FileName);
465   } else {
466     section_iterator SI = O->section_begin();
467     // Adjust for the fact that sections are 1-indexed.
468     if (Val == 0) {
469       Fmt << "0 (?,?)";
470       return;
471     }
472     uint32_t I = Val - 1;
473     while (I != 0 && SI != O->section_end()) {
474       --I;
475       advance(SI, 1);
476     }
477     if (SI == O->section_end()) {
478       Fmt << Val << " (?,?)";
479     } else {
480       if (Expected<StringRef> NameOrErr = SI->getName())
481         S = *NameOrErr;
482       else
483         consumeError(NameOrErr.takeError());
484     }
485   }
486 
487   Fmt << S;
488 }
489 
490 Error objdump::getMachORelocationValueString(const MachOObjectFile *Obj,
491                                              const RelocationRef &RelRef,
492                                              SmallVectorImpl<char> &Result) {
493   DataRefImpl Rel = RelRef.getRawDataRefImpl();
494   MachO::any_relocation_info RE = Obj->getRelocation(Rel);
495 
496   unsigned Arch = Obj->getArch();
497 
498   std::string FmtBuf;
499   raw_string_ostream Fmt(FmtBuf);
500   unsigned Type = Obj->getAnyRelocationType(RE);
501   bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
502 
503   // Determine any addends that should be displayed with the relocation.
504   // These require decoding the relocation type, which is triple-specific.
505 
506   // X86_64 has entirely custom relocation types.
507   if (Arch == Triple::x86_64) {
508     switch (Type) {
509     case MachO::X86_64_RELOC_GOT_LOAD:
510     case MachO::X86_64_RELOC_GOT: {
511       printRelocationTargetName(Obj, RE, Fmt);
512       Fmt << "@GOT";
513       if (IsPCRel)
514         Fmt << "PCREL";
515       break;
516     }
517     case MachO::X86_64_RELOC_SUBTRACTOR: {
518       DataRefImpl RelNext = Rel;
519       Obj->moveRelocationNext(RelNext);
520       MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
521 
522       // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
523       // X86_64_RELOC_UNSIGNED.
524       // NOTE: Scattered relocations don't exist on x86_64.
525       unsigned RType = Obj->getAnyRelocationType(RENext);
526       if (RType != MachO::X86_64_RELOC_UNSIGNED)
527         reportError(Obj->getFileName(), "Expected X86_64_RELOC_UNSIGNED after "
528                                         "X86_64_RELOC_SUBTRACTOR.");
529 
530       // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
531       // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
532       printRelocationTargetName(Obj, RENext, Fmt);
533       Fmt << "-";
534       printRelocationTargetName(Obj, RE, Fmt);
535       break;
536     }
537     case MachO::X86_64_RELOC_TLV:
538       printRelocationTargetName(Obj, RE, Fmt);
539       Fmt << "@TLV";
540       if (IsPCRel)
541         Fmt << "P";
542       break;
543     case MachO::X86_64_RELOC_SIGNED_1:
544       printRelocationTargetName(Obj, RE, Fmt);
545       Fmt << "-1";
546       break;
547     case MachO::X86_64_RELOC_SIGNED_2:
548       printRelocationTargetName(Obj, RE, Fmt);
549       Fmt << "-2";
550       break;
551     case MachO::X86_64_RELOC_SIGNED_4:
552       printRelocationTargetName(Obj, RE, Fmt);
553       Fmt << "-4";
554       break;
555     default:
556       printRelocationTargetName(Obj, RE, Fmt);
557       break;
558     }
559     // X86 and ARM share some relocation types in common.
560   } else if (Arch == Triple::x86 || Arch == Triple::arm ||
561              Arch == Triple::ppc) {
562     // Generic relocation types...
563     switch (Type) {
564     case MachO::GENERIC_RELOC_PAIR: // prints no info
565       return Error::success();
566     case MachO::GENERIC_RELOC_SECTDIFF: {
567       DataRefImpl RelNext = Rel;
568       Obj->moveRelocationNext(RelNext);
569       MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
570 
571       // X86 sect diff's must be followed by a relocation of type
572       // GENERIC_RELOC_PAIR.
573       unsigned RType = Obj->getAnyRelocationType(RENext);
574 
575       if (RType != MachO::GENERIC_RELOC_PAIR)
576         reportError(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
577                                         "GENERIC_RELOC_SECTDIFF.");
578 
579       printRelocationTargetName(Obj, RE, Fmt);
580       Fmt << "-";
581       printRelocationTargetName(Obj, RENext, Fmt);
582       break;
583     }
584     }
585 
586     if (Arch == Triple::x86 || Arch == Triple::ppc) {
587       switch (Type) {
588       case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
589         DataRefImpl RelNext = Rel;
590         Obj->moveRelocationNext(RelNext);
591         MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
592 
593         // X86 sect diff's must be followed by a relocation of type
594         // GENERIC_RELOC_PAIR.
595         unsigned RType = Obj->getAnyRelocationType(RENext);
596         if (RType != MachO::GENERIC_RELOC_PAIR)
597           reportError(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
598                                           "GENERIC_RELOC_LOCAL_SECTDIFF.");
599 
600         printRelocationTargetName(Obj, RE, Fmt);
601         Fmt << "-";
602         printRelocationTargetName(Obj, RENext, Fmt);
603         break;
604       }
605       case MachO::GENERIC_RELOC_TLV: {
606         printRelocationTargetName(Obj, RE, Fmt);
607         Fmt << "@TLV";
608         if (IsPCRel)
609           Fmt << "P";
610         break;
611       }
612       default:
613         printRelocationTargetName(Obj, RE, Fmt);
614       }
615     } else { // ARM-specific relocations
616       switch (Type) {
617       case MachO::ARM_RELOC_HALF:
618       case MachO::ARM_RELOC_HALF_SECTDIFF: {
619         // Half relocations steal a bit from the length field to encode
620         // whether this is an upper16 or a lower16 relocation.
621         bool isUpper = (Obj->getAnyRelocationLength(RE) & 0x1) == 1;
622 
623         if (isUpper)
624           Fmt << ":upper16:(";
625         else
626           Fmt << ":lower16:(";
627         printRelocationTargetName(Obj, RE, Fmt);
628 
629         DataRefImpl RelNext = Rel;
630         Obj->moveRelocationNext(RelNext);
631         MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
632 
633         // ARM half relocs must be followed by a relocation of type
634         // ARM_RELOC_PAIR.
635         unsigned RType = Obj->getAnyRelocationType(RENext);
636         if (RType != MachO::ARM_RELOC_PAIR)
637           reportError(Obj->getFileName(), "Expected ARM_RELOC_PAIR after "
638                                           "ARM_RELOC_HALF");
639 
640         // NOTE: The half of the target virtual address is stashed in the
641         // address field of the secondary relocation, but we can't reverse
642         // engineer the constant offset from it without decoding the movw/movt
643         // instruction to find the other half in its immediate field.
644 
645         // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
646         // symbol/section pointer of the follow-on relocation.
647         if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
648           Fmt << "-";
649           printRelocationTargetName(Obj, RENext, Fmt);
650         }
651 
652         Fmt << ")";
653         break;
654       }
655       default: {
656         printRelocationTargetName(Obj, RE, Fmt);
657       }
658       }
659     }
660   } else
661     printRelocationTargetName(Obj, RE, Fmt);
662 
663   Fmt.flush();
664   Result.append(FmtBuf.begin(), FmtBuf.end());
665   return Error::success();
666 }
667 
668 static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
669                                      uint32_t n, uint32_t count,
670                                      uint32_t stride, uint64_t addr) {
671   MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
672   uint32_t nindirectsyms = Dysymtab.nindirectsyms;
673   if (n > nindirectsyms)
674     outs() << " (entries start past the end of the indirect symbol "
675               "table) (reserved1 field greater than the table size)";
676   else if (n + count > nindirectsyms)
677     outs() << " (entries extends past the end of the indirect symbol "
678               "table)";
679   outs() << "\n";
680   uint32_t cputype = O->getHeader().cputype;
681   if (cputype & MachO::CPU_ARCH_ABI64)
682     outs() << "address            index";
683   else
684     outs() << "address    index";
685   if (verbose)
686     outs() << " name\n";
687   else
688     outs() << "\n";
689   for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
690     if (cputype & MachO::CPU_ARCH_ABI64)
691       outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
692     else
693       outs() << format("0x%08" PRIx32, (uint32_t)addr + j * stride) << " ";
694     MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
695     uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
696     if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
697       outs() << "LOCAL\n";
698       continue;
699     }
700     if (indirect_symbol ==
701         (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
702       outs() << "LOCAL ABSOLUTE\n";
703       continue;
704     }
705     if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
706       outs() << "ABSOLUTE\n";
707       continue;
708     }
709     outs() << format("%5u ", indirect_symbol);
710     if (verbose) {
711       MachO::symtab_command Symtab = O->getSymtabLoadCommand();
712       if (indirect_symbol < Symtab.nsyms) {
713         symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
714         SymbolRef Symbol = *Sym;
715         outs() << unwrapOrError(Symbol.getName(), O->getFileName());
716       } else {
717         outs() << "?";
718       }
719     }
720     outs() << "\n";
721   }
722 }
723 
724 static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
725   for (const auto &Load : O->load_commands()) {
726     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
727       MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
728       for (unsigned J = 0; J < Seg.nsects; ++J) {
729         MachO::section_64 Sec = O->getSection64(Load, J);
730         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
731         if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
732             section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
733             section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
734             section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
735             section_type == MachO::S_SYMBOL_STUBS) {
736           uint32_t stride;
737           if (section_type == MachO::S_SYMBOL_STUBS)
738             stride = Sec.reserved2;
739           else
740             stride = 8;
741           if (stride == 0) {
742             outs() << "Can't print indirect symbols for (" << Sec.segname << ","
743                    << Sec.sectname << ") "
744                    << "(size of stubs in reserved2 field is zero)\n";
745             continue;
746           }
747           uint32_t count = Sec.size / stride;
748           outs() << "Indirect symbols for (" << Sec.segname << ","
749                  << Sec.sectname << ") " << count << " entries";
750           uint32_t n = Sec.reserved1;
751           PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
752         }
753       }
754     } else if (Load.C.cmd == MachO::LC_SEGMENT) {
755       MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
756       for (unsigned J = 0; J < Seg.nsects; ++J) {
757         MachO::section Sec = O->getSection(Load, J);
758         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
759         if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
760             section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
761             section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
762             section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
763             section_type == MachO::S_SYMBOL_STUBS) {
764           uint32_t stride;
765           if (section_type == MachO::S_SYMBOL_STUBS)
766             stride = Sec.reserved2;
767           else
768             stride = 4;
769           if (stride == 0) {
770             outs() << "Can't print indirect symbols for (" << Sec.segname << ","
771                    << Sec.sectname << ") "
772                    << "(size of stubs in reserved2 field is zero)\n";
773             continue;
774           }
775           uint32_t count = Sec.size / stride;
776           outs() << "Indirect symbols for (" << Sec.segname << ","
777                  << Sec.sectname << ") " << count << " entries";
778           uint32_t n = Sec.reserved1;
779           PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
780         }
781       }
782     }
783   }
784 }
785 
786 static void PrintRType(const uint64_t cputype, const unsigned r_type) {
787   static char const *generic_r_types[] = {
788     "VANILLA ", "PAIR    ", "SECTDIF ", "PBLAPTR ", "LOCSDIF ", "TLV     ",
789     "  6 (?) ", "  7 (?) ", "  8 (?) ", "  9 (?) ", " 10 (?) ", " 11 (?) ",
790     " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
791   };
792   static char const *x86_64_r_types[] = {
793     "UNSIGND ", "SIGNED  ", "BRANCH  ", "GOT_LD  ", "GOT     ", "SUB     ",
794     "SIGNED1 ", "SIGNED2 ", "SIGNED4 ", "TLV     ", " 10 (?) ", " 11 (?) ",
795     " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
796   };
797   static char const *arm_r_types[] = {
798     "VANILLA ", "PAIR    ", "SECTDIFF", "LOCSDIF ", "PBLAPTR ",
799     "BR24    ", "T_BR22  ", "T_BR32  ", "HALF    ", "HALFDIF ",
800     " 10 (?) ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
801   };
802   static char const *arm64_r_types[] = {
803     "UNSIGND ", "SUB     ", "BR26    ", "PAGE21  ", "PAGOF12 ",
804     "GOTLDP  ", "GOTLDPOF", "PTRTGOT ", "TLVLDP  ", "TLVLDPOF",
805     "ADDEND  ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
806   };
807 
808   if (r_type > 0xf){
809     outs() << format("%-7u", r_type) << " ";
810     return;
811   }
812   switch (cputype) {
813     case MachO::CPU_TYPE_I386:
814       outs() << generic_r_types[r_type];
815       break;
816     case MachO::CPU_TYPE_X86_64:
817       outs() << x86_64_r_types[r_type];
818       break;
819     case MachO::CPU_TYPE_ARM:
820       outs() << arm_r_types[r_type];
821       break;
822     case MachO::CPU_TYPE_ARM64:
823     case MachO::CPU_TYPE_ARM64_32:
824       outs() << arm64_r_types[r_type];
825       break;
826     default:
827       outs() << format("%-7u ", r_type);
828   }
829 }
830 
831 static void PrintRLength(const uint64_t cputype, const unsigned r_type,
832                          const unsigned r_length, const bool previous_arm_half){
833   if (cputype == MachO::CPU_TYPE_ARM &&
834       (r_type == MachO::ARM_RELOC_HALF ||
835        r_type == MachO::ARM_RELOC_HALF_SECTDIFF || previous_arm_half == true)) {
836     if ((r_length & 0x1) == 0)
837       outs() << "lo/";
838     else
839       outs() << "hi/";
840     if ((r_length & 0x1) == 0)
841       outs() << "arm ";
842     else
843       outs() << "thm ";
844   } else {
845     switch (r_length) {
846       case 0:
847         outs() << "byte   ";
848         break;
849       case 1:
850         outs() << "word   ";
851         break;
852       case 2:
853         outs() << "long   ";
854         break;
855       case 3:
856         if (cputype == MachO::CPU_TYPE_X86_64)
857           outs() << "quad   ";
858         else
859           outs() << format("?(%2d)  ", r_length);
860         break;
861       default:
862         outs() << format("?(%2d)  ", r_length);
863     }
864   }
865 }
866 
867 static void PrintRelocationEntries(const MachOObjectFile *O,
868                                    const relocation_iterator Begin,
869                                    const relocation_iterator End,
870                                    const uint64_t cputype,
871                                    const bool verbose) {
872   const MachO::symtab_command Symtab = O->getSymtabLoadCommand();
873   bool previous_arm_half = false;
874   bool previous_sectdiff = false;
875   uint32_t sectdiff_r_type = 0;
876 
877   for (relocation_iterator Reloc = Begin; Reloc != End; ++Reloc) {
878     const DataRefImpl Rel = Reloc->getRawDataRefImpl();
879     const MachO::any_relocation_info RE = O->getRelocation(Rel);
880     const unsigned r_type = O->getAnyRelocationType(RE);
881     const bool r_scattered = O->isRelocationScattered(RE);
882     const unsigned r_pcrel = O->getAnyRelocationPCRel(RE);
883     const unsigned r_length = O->getAnyRelocationLength(RE);
884     const unsigned r_address = O->getAnyRelocationAddress(RE);
885     const bool r_extern = (r_scattered ? false :
886                            O->getPlainRelocationExternal(RE));
887     const uint32_t r_value = (r_scattered ?
888                               O->getScatteredRelocationValue(RE) : 0);
889     const unsigned r_symbolnum = (r_scattered ? 0 :
890                                   O->getPlainRelocationSymbolNum(RE));
891 
892     if (r_scattered && cputype != MachO::CPU_TYPE_X86_64) {
893       if (verbose) {
894         // scattered: address
895         if ((cputype == MachO::CPU_TYPE_I386 &&
896              r_type == MachO::GENERIC_RELOC_PAIR) ||
897             (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR))
898           outs() << "         ";
899         else
900           outs() << format("%08x ", (unsigned int)r_address);
901 
902         // scattered: pcrel
903         if (r_pcrel)
904           outs() << "True  ";
905         else
906           outs() << "False ";
907 
908         // scattered: length
909         PrintRLength(cputype, r_type, r_length, previous_arm_half);
910 
911         // scattered: extern & type
912         outs() << "n/a    ";
913         PrintRType(cputype, r_type);
914 
915         // scattered: scattered & value
916         outs() << format("True      0x%08x", (unsigned int)r_value);
917         if (previous_sectdiff == false) {
918           if ((cputype == MachO::CPU_TYPE_ARM &&
919                r_type == MachO::ARM_RELOC_PAIR))
920             outs() << format(" half = 0x%04x ", (unsigned int)r_address);
921         } else if (cputype == MachO::CPU_TYPE_ARM &&
922                    sectdiff_r_type == MachO::ARM_RELOC_HALF_SECTDIFF)
923           outs() << format(" other_half = 0x%04x ", (unsigned int)r_address);
924         if ((cputype == MachO::CPU_TYPE_I386 &&
925              (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
926               r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) ||
927             (cputype == MachO::CPU_TYPE_ARM &&
928              (sectdiff_r_type == MachO::ARM_RELOC_SECTDIFF ||
929               sectdiff_r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
930               sectdiff_r_type == MachO::ARM_RELOC_HALF_SECTDIFF))) {
931           previous_sectdiff = true;
932           sectdiff_r_type = r_type;
933         } else {
934           previous_sectdiff = false;
935           sectdiff_r_type = 0;
936         }
937         if (cputype == MachO::CPU_TYPE_ARM &&
938             (r_type == MachO::ARM_RELOC_HALF ||
939              r_type == MachO::ARM_RELOC_HALF_SECTDIFF))
940           previous_arm_half = true;
941         else
942           previous_arm_half = false;
943         outs() << "\n";
944       }
945       else {
946         // scattered: address pcrel length extern type scattered value
947         outs() << format("%08x %1d     %-2d     n/a    %-7d 1         0x%08x\n",
948                          (unsigned int)r_address, r_pcrel, r_length, r_type,
949                          (unsigned int)r_value);
950       }
951     }
952     else {
953       if (verbose) {
954         // plain: address
955         if (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR)
956           outs() << "         ";
957         else
958           outs() << format("%08x ", (unsigned int)r_address);
959 
960         // plain: pcrel
961         if (r_pcrel)
962           outs() << "True  ";
963         else
964           outs() << "False ";
965 
966         // plain: length
967         PrintRLength(cputype, r_type, r_length, previous_arm_half);
968 
969         if (r_extern) {
970           // plain: extern & type & scattered
971           outs() << "True   ";
972           PrintRType(cputype, r_type);
973           outs() << "False     ";
974 
975           // plain: symbolnum/value
976           if (r_symbolnum > Symtab.nsyms)
977             outs() << format("?(%d)\n", r_symbolnum);
978           else {
979             SymbolRef Symbol = *O->getSymbolByIndex(r_symbolnum);
980             Expected<StringRef> SymNameNext = Symbol.getName();
981             const char *name = NULL;
982             if (SymNameNext)
983               name = SymNameNext->data();
984             if (name == NULL)
985               outs() << format("?(%d)\n", r_symbolnum);
986             else
987               outs() << name << "\n";
988           }
989         }
990         else {
991           // plain: extern & type & scattered
992           outs() << "False  ";
993           PrintRType(cputype, r_type);
994           outs() << "False     ";
995 
996           // plain: symbolnum/value
997           if (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR)
998             outs() << format("other_half = 0x%04x\n", (unsigned int)r_address);
999           else if ((cputype == MachO::CPU_TYPE_ARM64 ||
1000                     cputype == MachO::CPU_TYPE_ARM64_32) &&
1001                    r_type == MachO::ARM64_RELOC_ADDEND)
1002             outs() << format("addend = 0x%06x\n", (unsigned int)r_symbolnum);
1003           else {
1004             outs() << format("%d ", r_symbolnum);
1005             if (r_symbolnum == MachO::R_ABS)
1006               outs() << "R_ABS\n";
1007             else {
1008               // in this case, r_symbolnum is actually a 1-based section number
1009               uint32_t nsects = O->section_end()->getRawDataRefImpl().d.a;
1010               if (r_symbolnum > 0 && r_symbolnum <= nsects) {
1011                 object::DataRefImpl DRI;
1012                 DRI.d.a = r_symbolnum-1;
1013                 StringRef SegName = O->getSectionFinalSegmentName(DRI);
1014                 if (Expected<StringRef> NameOrErr = O->getSectionName(DRI))
1015                   outs() << "(" << SegName << "," << *NameOrErr << ")\n";
1016                 else
1017                   outs() << "(?,?)\n";
1018               }
1019               else {
1020                 outs() << "(?,?)\n";
1021               }
1022             }
1023           }
1024         }
1025         if (cputype == MachO::CPU_TYPE_ARM &&
1026             (r_type == MachO::ARM_RELOC_HALF ||
1027              r_type == MachO::ARM_RELOC_HALF_SECTDIFF))
1028           previous_arm_half = true;
1029         else
1030           previous_arm_half = false;
1031       }
1032       else {
1033         // plain: address pcrel length extern type scattered symbolnum/section
1034         outs() << format("%08x %1d     %-2d     %1d      %-7d 0         %d\n",
1035                          (unsigned int)r_address, r_pcrel, r_length, r_extern,
1036                          r_type, r_symbolnum);
1037       }
1038     }
1039   }
1040 }
1041 
1042 static void PrintRelocations(const MachOObjectFile *O, const bool verbose) {
1043   const uint64_t cputype = O->getHeader().cputype;
1044   const MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
1045   if (Dysymtab.nextrel != 0) {
1046     outs() << "External relocation information " << Dysymtab.nextrel
1047            << " entries";
1048     outs() << "\naddress  pcrel length extern type    scattered "
1049               "symbolnum/value\n";
1050     PrintRelocationEntries(O, O->extrel_begin(), O->extrel_end(), cputype,
1051                            verbose);
1052   }
1053   if (Dysymtab.nlocrel != 0) {
1054     outs() << format("Local relocation information %u entries",
1055                      Dysymtab.nlocrel);
1056     outs() << "\naddress  pcrel length extern type    scattered "
1057               "symbolnum/value\n";
1058     PrintRelocationEntries(O, O->locrel_begin(), O->locrel_end(), cputype,
1059                            verbose);
1060   }
1061   for (const auto &Load : O->load_commands()) {
1062     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
1063       const MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
1064       for (unsigned J = 0; J < Seg.nsects; ++J) {
1065         const MachO::section_64 Sec = O->getSection64(Load, J);
1066         if (Sec.nreloc != 0) {
1067           DataRefImpl DRI;
1068           DRI.d.a = J;
1069           const StringRef SegName = O->getSectionFinalSegmentName(DRI);
1070           if (Expected<StringRef> NameOrErr = O->getSectionName(DRI))
1071             outs() << "Relocation information (" << SegName << "," << *NameOrErr
1072                    << format(") %u entries", Sec.nreloc);
1073           else
1074             outs() << "Relocation information (" << SegName << ",?) "
1075                    << format("%u entries", Sec.nreloc);
1076           outs() << "\naddress  pcrel length extern type    scattered "
1077                     "symbolnum/value\n";
1078           PrintRelocationEntries(O, O->section_rel_begin(DRI),
1079                                  O->section_rel_end(DRI), cputype, verbose);
1080         }
1081       }
1082     } else if (Load.C.cmd == MachO::LC_SEGMENT) {
1083       const MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
1084       for (unsigned J = 0; J < Seg.nsects; ++J) {
1085         const MachO::section Sec = O->getSection(Load, J);
1086         if (Sec.nreloc != 0) {
1087           DataRefImpl DRI;
1088           DRI.d.a = J;
1089           const StringRef SegName = O->getSectionFinalSegmentName(DRI);
1090           if (Expected<StringRef> NameOrErr = O->getSectionName(DRI))
1091             outs() << "Relocation information (" << SegName << "," << *NameOrErr
1092                    << format(") %u entries", Sec.nreloc);
1093           else
1094             outs() << "Relocation information (" << SegName << ",?) "
1095                    << format("%u entries", Sec.nreloc);
1096           outs() << "\naddress  pcrel length extern type    scattered "
1097                     "symbolnum/value\n";
1098           PrintRelocationEntries(O, O->section_rel_begin(DRI),
1099                                  O->section_rel_end(DRI), cputype, verbose);
1100         }
1101       }
1102     }
1103   }
1104 }
1105 
1106 static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
1107   MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
1108   uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
1109   outs() << "Data in code table (" << nentries << " entries)\n";
1110   outs() << "offset     length kind\n";
1111   for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
1112        ++DI) {
1113     uint32_t Offset;
1114     DI->getOffset(Offset);
1115     outs() << format("0x%08" PRIx32, Offset) << " ";
1116     uint16_t Length;
1117     DI->getLength(Length);
1118     outs() << format("%6u", Length) << " ";
1119     uint16_t Kind;
1120     DI->getKind(Kind);
1121     if (verbose) {
1122       switch (Kind) {
1123       case MachO::DICE_KIND_DATA:
1124         outs() << "DATA";
1125         break;
1126       case MachO::DICE_KIND_JUMP_TABLE8:
1127         outs() << "JUMP_TABLE8";
1128         break;
1129       case MachO::DICE_KIND_JUMP_TABLE16:
1130         outs() << "JUMP_TABLE16";
1131         break;
1132       case MachO::DICE_KIND_JUMP_TABLE32:
1133         outs() << "JUMP_TABLE32";
1134         break;
1135       case MachO::DICE_KIND_ABS_JUMP_TABLE32:
1136         outs() << "ABS_JUMP_TABLE32";
1137         break;
1138       default:
1139         outs() << format("0x%04" PRIx32, Kind);
1140         break;
1141       }
1142     } else
1143       outs() << format("0x%04" PRIx32, Kind);
1144     outs() << "\n";
1145   }
1146 }
1147 
1148 static void PrintLinkOptHints(MachOObjectFile *O) {
1149   MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
1150   const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
1151   uint32_t nloh = LohLC.datasize;
1152   outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
1153   for (uint32_t i = 0; i < nloh;) {
1154     unsigned n;
1155     uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
1156     i += n;
1157     outs() << "    identifier " << identifier << " ";
1158     if (i >= nloh)
1159       return;
1160     switch (identifier) {
1161     case 1:
1162       outs() << "AdrpAdrp\n";
1163       break;
1164     case 2:
1165       outs() << "AdrpLdr\n";
1166       break;
1167     case 3:
1168       outs() << "AdrpAddLdr\n";
1169       break;
1170     case 4:
1171       outs() << "AdrpLdrGotLdr\n";
1172       break;
1173     case 5:
1174       outs() << "AdrpAddStr\n";
1175       break;
1176     case 6:
1177       outs() << "AdrpLdrGotStr\n";
1178       break;
1179     case 7:
1180       outs() << "AdrpAdd\n";
1181       break;
1182     case 8:
1183       outs() << "AdrpLdrGot\n";
1184       break;
1185     default:
1186       outs() << "Unknown identifier value\n";
1187       break;
1188     }
1189     uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
1190     i += n;
1191     outs() << "    narguments " << narguments << "\n";
1192     if (i >= nloh)
1193       return;
1194 
1195     for (uint32_t j = 0; j < narguments; j++) {
1196       uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
1197       i += n;
1198       outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
1199       if (i >= nloh)
1200         return;
1201     }
1202   }
1203 }
1204 
1205 static void PrintDylibs(MachOObjectFile *O, bool JustId) {
1206   unsigned Index = 0;
1207   for (const auto &Load : O->load_commands()) {
1208     if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
1209         (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
1210                      Load.C.cmd == MachO::LC_LOAD_DYLIB ||
1211                      Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
1212                      Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
1213                      Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
1214                      Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
1215       MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
1216       if (dl.dylib.name < dl.cmdsize) {
1217         const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
1218         if (JustId)
1219           outs() << p << "\n";
1220         else {
1221           outs() << "\t" << p;
1222           outs() << " (compatibility version "
1223                  << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
1224                  << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
1225                  << (dl.dylib.compatibility_version & 0xff) << ",";
1226           outs() << " current version "
1227                  << ((dl.dylib.current_version >> 16) & 0xffff) << "."
1228                  << ((dl.dylib.current_version >> 8) & 0xff) << "."
1229                  << (dl.dylib.current_version & 0xff);
1230           if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
1231             outs() << ", weak";
1232           if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
1233             outs() << ", reexport";
1234           if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
1235             outs() << ", upward";
1236           if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
1237             outs() << ", lazy";
1238           outs() << ")\n";
1239         }
1240       } else {
1241         outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
1242         if (Load.C.cmd == MachO::LC_ID_DYLIB)
1243           outs() << "LC_ID_DYLIB ";
1244         else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
1245           outs() << "LC_LOAD_DYLIB ";
1246         else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
1247           outs() << "LC_LOAD_WEAK_DYLIB ";
1248         else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
1249           outs() << "LC_LAZY_LOAD_DYLIB ";
1250         else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
1251           outs() << "LC_REEXPORT_DYLIB ";
1252         else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
1253           outs() << "LC_LOAD_UPWARD_DYLIB ";
1254         else
1255           outs() << "LC_??? ";
1256         outs() << "command " << Index++ << "\n";
1257       }
1258     }
1259   }
1260 }
1261 
1262 typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
1263 
1264 static void CreateSymbolAddressMap(MachOObjectFile *O,
1265                                    SymbolAddressMap *AddrMap) {
1266   // Create a map of symbol addresses to symbol names.
1267   const StringRef FileName = O->getFileName();
1268   for (const SymbolRef &Symbol : O->symbols()) {
1269     SymbolRef::Type ST = unwrapOrError(Symbol.getType(), FileName);
1270     if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
1271         ST == SymbolRef::ST_Other) {
1272       uint64_t Address = cantFail(Symbol.getValue());
1273       StringRef SymName = unwrapOrError(Symbol.getName(), FileName);
1274       if (!SymName.startswith(".objc"))
1275         (*AddrMap)[Address] = SymName;
1276     }
1277   }
1278 }
1279 
1280 // GuessSymbolName is passed the address of what might be a symbol and a
1281 // pointer to the SymbolAddressMap.  It returns the name of a symbol
1282 // with that address or nullptr if no symbol is found with that address.
1283 static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
1284   const char *SymbolName = nullptr;
1285   // A DenseMap can't lookup up some values.
1286   if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
1287     StringRef name = AddrMap->lookup(value);
1288     if (!name.empty())
1289       SymbolName = name.data();
1290   }
1291   return SymbolName;
1292 }
1293 
1294 static void DumpCstringChar(const char c) {
1295   char p[2];
1296   p[0] = c;
1297   p[1] = '\0';
1298   outs().write_escaped(p);
1299 }
1300 
1301 static void DumpCstringSection(MachOObjectFile *O, const char *sect,
1302                                uint32_t sect_size, uint64_t sect_addr,
1303                                bool print_addresses) {
1304   for (uint32_t i = 0; i < sect_size; i++) {
1305     if (print_addresses) {
1306       if (O->is64Bit())
1307         outs() << format("%016" PRIx64, sect_addr + i) << "  ";
1308       else
1309         outs() << format("%08" PRIx64, sect_addr + i) << "  ";
1310     }
1311     for (; i < sect_size && sect[i] != '\0'; i++)
1312       DumpCstringChar(sect[i]);
1313     if (i < sect_size && sect[i] == '\0')
1314       outs() << "\n";
1315   }
1316 }
1317 
1318 static void DumpLiteral4(uint32_t l, float f) {
1319   outs() << format("0x%08" PRIx32, l);
1320   if ((l & 0x7f800000) != 0x7f800000)
1321     outs() << format(" (%.16e)\n", f);
1322   else {
1323     if (l == 0x7f800000)
1324       outs() << " (+Infinity)\n";
1325     else if (l == 0xff800000)
1326       outs() << " (-Infinity)\n";
1327     else if ((l & 0x00400000) == 0x00400000)
1328       outs() << " (non-signaling Not-a-Number)\n";
1329     else
1330       outs() << " (signaling Not-a-Number)\n";
1331   }
1332 }
1333 
1334 static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
1335                                 uint32_t sect_size, uint64_t sect_addr,
1336                                 bool print_addresses) {
1337   for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
1338     if (print_addresses) {
1339       if (O->is64Bit())
1340         outs() << format("%016" PRIx64, sect_addr + i) << "  ";
1341       else
1342         outs() << format("%08" PRIx64, sect_addr + i) << "  ";
1343     }
1344     float f;
1345     memcpy(&f, sect + i, sizeof(float));
1346     if (O->isLittleEndian() != sys::IsLittleEndianHost)
1347       sys::swapByteOrder(f);
1348     uint32_t l;
1349     memcpy(&l, sect + i, sizeof(uint32_t));
1350     if (O->isLittleEndian() != sys::IsLittleEndianHost)
1351       sys::swapByteOrder(l);
1352     DumpLiteral4(l, f);
1353   }
1354 }
1355 
1356 static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
1357                          double d) {
1358   outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
1359   uint32_t Hi, Lo;
1360   Hi = (O->isLittleEndian()) ? l1 : l0;
1361   Lo = (O->isLittleEndian()) ? l0 : l1;
1362 
1363   // Hi is the high word, so this is equivalent to if(isfinite(d))
1364   if ((Hi & 0x7ff00000) != 0x7ff00000)
1365     outs() << format(" (%.16e)\n", d);
1366   else {
1367     if (Hi == 0x7ff00000 && Lo == 0)
1368       outs() << " (+Infinity)\n";
1369     else if (Hi == 0xfff00000 && Lo == 0)
1370       outs() << " (-Infinity)\n";
1371     else if ((Hi & 0x00080000) == 0x00080000)
1372       outs() << " (non-signaling Not-a-Number)\n";
1373     else
1374       outs() << " (signaling Not-a-Number)\n";
1375   }
1376 }
1377 
1378 static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
1379                                 uint32_t sect_size, uint64_t sect_addr,
1380                                 bool print_addresses) {
1381   for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
1382     if (print_addresses) {
1383       if (O->is64Bit())
1384         outs() << format("%016" PRIx64, sect_addr + i) << "  ";
1385       else
1386         outs() << format("%08" PRIx64, sect_addr + i) << "  ";
1387     }
1388     double d;
1389     memcpy(&d, sect + i, sizeof(double));
1390     if (O->isLittleEndian() != sys::IsLittleEndianHost)
1391       sys::swapByteOrder(d);
1392     uint32_t l0, l1;
1393     memcpy(&l0, sect + i, sizeof(uint32_t));
1394     memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
1395     if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1396       sys::swapByteOrder(l0);
1397       sys::swapByteOrder(l1);
1398     }
1399     DumpLiteral8(O, l0, l1, d);
1400   }
1401 }
1402 
1403 static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
1404   outs() << format("0x%08" PRIx32, l0) << " ";
1405   outs() << format("0x%08" PRIx32, l1) << " ";
1406   outs() << format("0x%08" PRIx32, l2) << " ";
1407   outs() << format("0x%08" PRIx32, l3) << "\n";
1408 }
1409 
1410 static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
1411                                  uint32_t sect_size, uint64_t sect_addr,
1412                                  bool print_addresses) {
1413   for (uint32_t i = 0; i < sect_size; i += 16) {
1414     if (print_addresses) {
1415       if (O->is64Bit())
1416         outs() << format("%016" PRIx64, sect_addr + i) << "  ";
1417       else
1418         outs() << format("%08" PRIx64, sect_addr + i) << "  ";
1419     }
1420     uint32_t l0, l1, l2, l3;
1421     memcpy(&l0, sect + i, sizeof(uint32_t));
1422     memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
1423     memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
1424     memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
1425     if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1426       sys::swapByteOrder(l0);
1427       sys::swapByteOrder(l1);
1428       sys::swapByteOrder(l2);
1429       sys::swapByteOrder(l3);
1430     }
1431     DumpLiteral16(l0, l1, l2, l3);
1432   }
1433 }
1434 
1435 static void DumpLiteralPointerSection(MachOObjectFile *O,
1436                                       const SectionRef &Section,
1437                                       const char *sect, uint32_t sect_size,
1438                                       uint64_t sect_addr,
1439                                       bool print_addresses) {
1440   // Collect the literal sections in this Mach-O file.
1441   std::vector<SectionRef> LiteralSections;
1442   for (const SectionRef &Section : O->sections()) {
1443     DataRefImpl Ref = Section.getRawDataRefImpl();
1444     uint32_t section_type;
1445     if (O->is64Bit()) {
1446       const MachO::section_64 Sec = O->getSection64(Ref);
1447       section_type = Sec.flags & MachO::SECTION_TYPE;
1448     } else {
1449       const MachO::section Sec = O->getSection(Ref);
1450       section_type = Sec.flags & MachO::SECTION_TYPE;
1451     }
1452     if (section_type == MachO::S_CSTRING_LITERALS ||
1453         section_type == MachO::S_4BYTE_LITERALS ||
1454         section_type == MachO::S_8BYTE_LITERALS ||
1455         section_type == MachO::S_16BYTE_LITERALS)
1456       LiteralSections.push_back(Section);
1457   }
1458 
1459   // Set the size of the literal pointer.
1460   uint32_t lp_size = O->is64Bit() ? 8 : 4;
1461 
1462   // Collect the external relocation symbols for the literal pointers.
1463   std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1464   for (const RelocationRef &Reloc : Section.relocations()) {
1465     DataRefImpl Rel;
1466     MachO::any_relocation_info RE;
1467     bool isExtern = false;
1468     Rel = Reloc.getRawDataRefImpl();
1469     RE = O->getRelocation(Rel);
1470     isExtern = O->getPlainRelocationExternal(RE);
1471     if (isExtern) {
1472       uint64_t RelocOffset = Reloc.getOffset();
1473       symbol_iterator RelocSym = Reloc.getSymbol();
1474       Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
1475     }
1476   }
1477   array_pod_sort(Relocs.begin(), Relocs.end());
1478 
1479   // Dump each literal pointer.
1480   for (uint32_t i = 0; i < sect_size; i += lp_size) {
1481     if (print_addresses) {
1482       if (O->is64Bit())
1483         outs() << format("%016" PRIx64, sect_addr + i) << "  ";
1484       else
1485         outs() << format("%08" PRIx64, sect_addr + i) << "  ";
1486     }
1487     uint64_t lp;
1488     if (O->is64Bit()) {
1489       memcpy(&lp, sect + i, sizeof(uint64_t));
1490       if (O->isLittleEndian() != sys::IsLittleEndianHost)
1491         sys::swapByteOrder(lp);
1492     } else {
1493       uint32_t li;
1494       memcpy(&li, sect + i, sizeof(uint32_t));
1495       if (O->isLittleEndian() != sys::IsLittleEndianHost)
1496         sys::swapByteOrder(li);
1497       lp = li;
1498     }
1499 
1500     // First look for an external relocation entry for this literal pointer.
1501     auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
1502       return P.first == i;
1503     });
1504     if (Reloc != Relocs.end()) {
1505       symbol_iterator RelocSym = Reloc->second;
1506       StringRef SymName = unwrapOrError(RelocSym->getName(), O->getFileName());
1507       outs() << "external relocation entry for symbol:" << SymName << "\n";
1508       continue;
1509     }
1510 
1511     // For local references see what the section the literal pointer points to.
1512     auto Sect = find_if(LiteralSections, [&](const SectionRef &R) {
1513       return lp >= R.getAddress() && lp < R.getAddress() + R.getSize();
1514     });
1515     if (Sect == LiteralSections.end()) {
1516       outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
1517       continue;
1518     }
1519 
1520     uint64_t SectAddress = Sect->getAddress();
1521     uint64_t SectSize = Sect->getSize();
1522 
1523     StringRef SectName;
1524     Expected<StringRef> SectNameOrErr = Sect->getName();
1525     if (SectNameOrErr)
1526       SectName = *SectNameOrErr;
1527     else
1528       consumeError(SectNameOrErr.takeError());
1529 
1530     DataRefImpl Ref = Sect->getRawDataRefImpl();
1531     StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
1532     outs() << SegmentName << ":" << SectName << ":";
1533 
1534     uint32_t section_type;
1535     if (O->is64Bit()) {
1536       const MachO::section_64 Sec = O->getSection64(Ref);
1537       section_type = Sec.flags & MachO::SECTION_TYPE;
1538     } else {
1539       const MachO::section Sec = O->getSection(Ref);
1540       section_type = Sec.flags & MachO::SECTION_TYPE;
1541     }
1542 
1543     StringRef BytesStr = unwrapOrError(Sect->getContents(), O->getFileName());
1544 
1545     const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
1546 
1547     switch (section_type) {
1548     case MachO::S_CSTRING_LITERALS:
1549       for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
1550            i++) {
1551         DumpCstringChar(Contents[i]);
1552       }
1553       outs() << "\n";
1554       break;
1555     case MachO::S_4BYTE_LITERALS:
1556       float f;
1557       memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
1558       uint32_t l;
1559       memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
1560       if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1561         sys::swapByteOrder(f);
1562         sys::swapByteOrder(l);
1563       }
1564       DumpLiteral4(l, f);
1565       break;
1566     case MachO::S_8BYTE_LITERALS: {
1567       double d;
1568       memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
1569       uint32_t l0, l1;
1570       memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
1571       memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
1572              sizeof(uint32_t));
1573       if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1574         sys::swapByteOrder(f);
1575         sys::swapByteOrder(l0);
1576         sys::swapByteOrder(l1);
1577       }
1578       DumpLiteral8(O, l0, l1, d);
1579       break;
1580     }
1581     case MachO::S_16BYTE_LITERALS: {
1582       uint32_t l0, l1, l2, l3;
1583       memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
1584       memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
1585              sizeof(uint32_t));
1586       memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
1587              sizeof(uint32_t));
1588       memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
1589              sizeof(uint32_t));
1590       if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1591         sys::swapByteOrder(l0);
1592         sys::swapByteOrder(l1);
1593         sys::swapByteOrder(l2);
1594         sys::swapByteOrder(l3);
1595       }
1596       DumpLiteral16(l0, l1, l2, l3);
1597       break;
1598     }
1599     }
1600   }
1601 }
1602 
1603 static void DumpInitTermPointerSection(MachOObjectFile *O,
1604                                        const SectionRef &Section,
1605                                        const char *sect,
1606                                        uint32_t sect_size, uint64_t sect_addr,
1607                                        SymbolAddressMap *AddrMap,
1608                                        bool verbose) {
1609   uint32_t stride;
1610   stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t);
1611 
1612   // Collect the external relocation symbols for the pointers.
1613   std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1614   for (const RelocationRef &Reloc : Section.relocations()) {
1615     DataRefImpl Rel;
1616     MachO::any_relocation_info RE;
1617     bool isExtern = false;
1618     Rel = Reloc.getRawDataRefImpl();
1619     RE = O->getRelocation(Rel);
1620     isExtern = O->getPlainRelocationExternal(RE);
1621     if (isExtern) {
1622       uint64_t RelocOffset = Reloc.getOffset();
1623       symbol_iterator RelocSym = Reloc.getSymbol();
1624       Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
1625     }
1626   }
1627   array_pod_sort(Relocs.begin(), Relocs.end());
1628 
1629   for (uint32_t i = 0; i < sect_size; i += stride) {
1630     const char *SymbolName = nullptr;
1631     uint64_t p;
1632     if (O->is64Bit()) {
1633       outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
1634       uint64_t pointer_value;
1635       memcpy(&pointer_value, sect + i, stride);
1636       if (O->isLittleEndian() != sys::IsLittleEndianHost)
1637         sys::swapByteOrder(pointer_value);
1638       outs() << format("0x%016" PRIx64, pointer_value);
1639       p = pointer_value;
1640     } else {
1641       outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
1642       uint32_t pointer_value;
1643       memcpy(&pointer_value, sect + i, stride);
1644       if (O->isLittleEndian() != sys::IsLittleEndianHost)
1645         sys::swapByteOrder(pointer_value);
1646       outs() << format("0x%08" PRIx32, pointer_value);
1647       p = pointer_value;
1648     }
1649     if (verbose) {
1650       // First look for an external relocation entry for this pointer.
1651       auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
1652         return P.first == i;
1653       });
1654       if (Reloc != Relocs.end()) {
1655         symbol_iterator RelocSym = Reloc->second;
1656         outs() << " " << unwrapOrError(RelocSym->getName(), O->getFileName());
1657       } else {
1658         SymbolName = GuessSymbolName(p, AddrMap);
1659         if (SymbolName)
1660           outs() << " " << SymbolName;
1661       }
1662     }
1663     outs() << "\n";
1664   }
1665 }
1666 
1667 static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
1668                                    uint32_t size, uint64_t addr) {
1669   uint32_t cputype = O->getHeader().cputype;
1670   if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
1671     uint32_t j;
1672     for (uint32_t i = 0; i < size; i += j, addr += j) {
1673       if (O->is64Bit())
1674         outs() << format("%016" PRIx64, addr) << "\t";
1675       else
1676         outs() << format("%08" PRIx64, addr) << "\t";
1677       for (j = 0; j < 16 && i + j < size; j++) {
1678         uint8_t byte_word = *(sect + i + j);
1679         outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1680       }
1681       outs() << "\n";
1682     }
1683   } else {
1684     uint32_t j;
1685     for (uint32_t i = 0; i < size; i += j, addr += j) {
1686       if (O->is64Bit())
1687         outs() << format("%016" PRIx64, addr) << "\t";
1688       else
1689         outs() << format("%08" PRIx64, addr) << "\t";
1690       for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
1691            j += sizeof(int32_t)) {
1692         if (i + j + sizeof(int32_t) <= size) {
1693           uint32_t long_word;
1694           memcpy(&long_word, sect + i + j, sizeof(int32_t));
1695           if (O->isLittleEndian() != sys::IsLittleEndianHost)
1696             sys::swapByteOrder(long_word);
1697           outs() << format("%08" PRIx32, long_word) << " ";
1698         } else {
1699           for (uint32_t k = 0; i + j + k < size; k++) {
1700             uint8_t byte_word = *(sect + i + j + k);
1701             outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1702           }
1703         }
1704       }
1705       outs() << "\n";
1706     }
1707   }
1708 }
1709 
1710 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
1711                              StringRef DisSegName, StringRef DisSectName);
1712 static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
1713                                 uint32_t size, uint32_t addr);
1714 #ifdef HAVE_LIBXAR
1715 static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
1716                                 uint32_t size, bool verbose,
1717                                 bool PrintXarHeader, bool PrintXarFileHeaders,
1718                                 std::string XarMemberName);
1719 #endif // defined(HAVE_LIBXAR)
1720 
1721 static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
1722                                 bool verbose) {
1723   SymbolAddressMap AddrMap;
1724   if (verbose)
1725     CreateSymbolAddressMap(O, &AddrMap);
1726 
1727   for (unsigned i = 0; i < FilterSections.size(); ++i) {
1728     StringRef DumpSection = FilterSections[i];
1729     std::pair<StringRef, StringRef> DumpSegSectName;
1730     DumpSegSectName = DumpSection.split(',');
1731     StringRef DumpSegName, DumpSectName;
1732     if (!DumpSegSectName.second.empty()) {
1733       DumpSegName = DumpSegSectName.first;
1734       DumpSectName = DumpSegSectName.second;
1735     } else {
1736       DumpSegName = "";
1737       DumpSectName = DumpSegSectName.first;
1738     }
1739     for (const SectionRef &Section : O->sections()) {
1740       StringRef SectName;
1741       Expected<StringRef> SecNameOrErr = Section.getName();
1742       if (SecNameOrErr)
1743         SectName = *SecNameOrErr;
1744       else
1745         consumeError(SecNameOrErr.takeError());
1746 
1747       if (!DumpSection.empty())
1748         FoundSectionSet.insert(DumpSection);
1749 
1750       DataRefImpl Ref = Section.getRawDataRefImpl();
1751       StringRef SegName = O->getSectionFinalSegmentName(Ref);
1752       if ((DumpSegName.empty() || SegName == DumpSegName) &&
1753           (SectName == DumpSectName)) {
1754 
1755         uint32_t section_flags;
1756         if (O->is64Bit()) {
1757           const MachO::section_64 Sec = O->getSection64(Ref);
1758           section_flags = Sec.flags;
1759 
1760         } else {
1761           const MachO::section Sec = O->getSection(Ref);
1762           section_flags = Sec.flags;
1763         }
1764         uint32_t section_type = section_flags & MachO::SECTION_TYPE;
1765 
1766         StringRef BytesStr =
1767             unwrapOrError(Section.getContents(), O->getFileName());
1768         const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1769         uint32_t sect_size = BytesStr.size();
1770         uint64_t sect_addr = Section.getAddress();
1771 
1772         if (!NoLeadingHeaders)
1773           outs() << "Contents of (" << SegName << "," << SectName
1774                  << ") section\n";
1775 
1776         if (verbose) {
1777           if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1778               (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1779             DisassembleMachO(Filename, O, SegName, SectName);
1780             continue;
1781           }
1782           if (SegName == "__TEXT" && SectName == "__info_plist") {
1783             outs() << sect;
1784             continue;
1785           }
1786           if (SegName == "__OBJC" && SectName == "__protocol") {
1787             DumpProtocolSection(O, sect, sect_size, sect_addr);
1788             continue;
1789           }
1790 #ifdef HAVE_LIBXAR
1791           if (SegName == "__LLVM" && SectName == "__bundle") {
1792             DumpBitcodeSection(O, sect, sect_size, verbose, !NoSymbolicOperands,
1793                                ArchiveHeaders, "");
1794             continue;
1795           }
1796 #endif // defined(HAVE_LIBXAR)
1797           switch (section_type) {
1798           case MachO::S_REGULAR:
1799             DumpRawSectionContents(O, sect, sect_size, sect_addr);
1800             break;
1801           case MachO::S_ZEROFILL:
1802             outs() << "zerofill section and has no contents in the file\n";
1803             break;
1804           case MachO::S_CSTRING_LITERALS:
1805             DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1806             break;
1807           case MachO::S_4BYTE_LITERALS:
1808             DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1809             break;
1810           case MachO::S_8BYTE_LITERALS:
1811             DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1812             break;
1813           case MachO::S_16BYTE_LITERALS:
1814             DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1815             break;
1816           case MachO::S_LITERAL_POINTERS:
1817             DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
1818                                       !NoLeadingAddr);
1819             break;
1820           case MachO::S_MOD_INIT_FUNC_POINTERS:
1821           case MachO::S_MOD_TERM_FUNC_POINTERS:
1822             DumpInitTermPointerSection(O, Section, sect, sect_size, sect_addr,
1823                                        &AddrMap, verbose);
1824             break;
1825           default:
1826             outs() << "Unknown section type ("
1827                    << format("0x%08" PRIx32, section_type) << ")\n";
1828             DumpRawSectionContents(O, sect, sect_size, sect_addr);
1829             break;
1830           }
1831         } else {
1832           if (section_type == MachO::S_ZEROFILL)
1833             outs() << "zerofill section and has no contents in the file\n";
1834           else
1835             DumpRawSectionContents(O, sect, sect_size, sect_addr);
1836         }
1837       }
1838     }
1839   }
1840 }
1841 
1842 static void DumpInfoPlistSectionContents(StringRef Filename,
1843                                          MachOObjectFile *O) {
1844   for (const SectionRef &Section : O->sections()) {
1845     StringRef SectName;
1846     Expected<StringRef> SecNameOrErr = Section.getName();
1847     if (SecNameOrErr)
1848       SectName = *SecNameOrErr;
1849     else
1850       consumeError(SecNameOrErr.takeError());
1851 
1852     DataRefImpl Ref = Section.getRawDataRefImpl();
1853     StringRef SegName = O->getSectionFinalSegmentName(Ref);
1854     if (SegName == "__TEXT" && SectName == "__info_plist") {
1855       if (!NoLeadingHeaders)
1856         outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
1857       StringRef BytesStr =
1858           unwrapOrError(Section.getContents(), O->getFileName());
1859       const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1860       outs() << format("%.*s", BytesStr.size(), sect) << "\n";
1861       return;
1862     }
1863   }
1864 }
1865 
1866 // checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1867 // and if it is and there is a list of architecture flags is specified then
1868 // check to make sure this Mach-O file is one of those architectures or all
1869 // architectures were specified.  If not then an error is generated and this
1870 // routine returns false.  Else it returns true.
1871 static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
1872   auto *MachO = dyn_cast<MachOObjectFile>(O);
1873 
1874   if (!MachO || ArchAll || ArchFlags.empty())
1875     return true;
1876 
1877   MachO::mach_header H;
1878   MachO::mach_header_64 H_64;
1879   Triple T;
1880   const char *McpuDefault, *ArchFlag;
1881   if (MachO->is64Bit()) {
1882     H_64 = MachO->MachOObjectFile::getHeader64();
1883     T = MachOObjectFile::getArchTriple(H_64.cputype, H_64.cpusubtype,
1884                                        &McpuDefault, &ArchFlag);
1885   } else {
1886     H = MachO->MachOObjectFile::getHeader();
1887     T = MachOObjectFile::getArchTriple(H.cputype, H.cpusubtype,
1888                                        &McpuDefault, &ArchFlag);
1889   }
1890   const std::string ArchFlagName(ArchFlag);
1891   if (!llvm::is_contained(ArchFlags, ArchFlagName)) {
1892     WithColor::error(errs(), "llvm-objdump")
1893         << Filename << ": no architecture specified.\n";
1894     return false;
1895   }
1896   return true;
1897 }
1898 
1899 static void printObjcMetaData(MachOObjectFile *O, bool verbose);
1900 
1901 // ProcessMachO() is passed a single opened Mach-O file, which may be an
1902 // archive member and or in a slice of a universal file.  It prints the
1903 // the file name and header info and then processes it according to the
1904 // command line options.
1905 static void ProcessMachO(StringRef Name, MachOObjectFile *MachOOF,
1906                          StringRef ArchiveMemberName = StringRef(),
1907                          StringRef ArchitectureName = StringRef()) {
1908   // If we are doing some processing here on the Mach-O file print the header
1909   // info.  And don't print it otherwise like in the case of printing the
1910   // UniversalHeaders or ArchiveHeaders.
1911   if (Disassemble || Relocations || PrivateHeaders || ExportsTrie || Rebase ||
1912       Bind || SymbolTable || LazyBind || WeakBind || IndirectSymbols ||
1913       DataInCode || LinkOptHints || DylibsUsed || DylibId || ObjcMetaData ||
1914       (!FilterSections.empty())) {
1915     if (!NoLeadingHeaders) {
1916       outs() << Name;
1917       if (!ArchiveMemberName.empty())
1918         outs() << '(' << ArchiveMemberName << ')';
1919       if (!ArchitectureName.empty())
1920         outs() << " (architecture " << ArchitectureName << ")";
1921       outs() << ":\n";
1922     }
1923   }
1924   // To use the report_error() form with an ArchiveName and FileName set
1925   // these up based on what is passed for Name and ArchiveMemberName.
1926   StringRef ArchiveName;
1927   StringRef FileName;
1928   if (!ArchiveMemberName.empty()) {
1929     ArchiveName = Name;
1930     FileName = ArchiveMemberName;
1931   } else {
1932     ArchiveName = StringRef();
1933     FileName = Name;
1934   }
1935 
1936   // If we need the symbol table to do the operation then check it here to
1937   // produce a good error message as to where the Mach-O file comes from in
1938   // the error message.
1939   if (Disassemble || IndirectSymbols || !FilterSections.empty() || UnwindInfo)
1940     if (Error Err = MachOOF->checkSymbolTable())
1941       reportError(std::move(Err), FileName, ArchiveName, ArchitectureName);
1942 
1943   if (DisassembleAll) {
1944     for (const SectionRef &Section : MachOOF->sections()) {
1945       StringRef SectName;
1946       if (Expected<StringRef> NameOrErr = Section.getName())
1947         SectName = *NameOrErr;
1948       else
1949         consumeError(NameOrErr.takeError());
1950 
1951       if (SectName.equals("__text")) {
1952         DataRefImpl Ref = Section.getRawDataRefImpl();
1953         StringRef SegName = MachOOF->getSectionFinalSegmentName(Ref);
1954         DisassembleMachO(FileName, MachOOF, SegName, SectName);
1955       }
1956     }
1957   }
1958   else if (Disassemble) {
1959     if (MachOOF->getHeader().filetype == MachO::MH_KEXT_BUNDLE &&
1960         MachOOF->getHeader().cputype == MachO::CPU_TYPE_ARM64)
1961       DisassembleMachO(FileName, MachOOF, "__TEXT_EXEC", "__text");
1962     else
1963       DisassembleMachO(FileName, MachOOF, "__TEXT", "__text");
1964   }
1965   if (IndirectSymbols)
1966     PrintIndirectSymbols(MachOOF, !NonVerbose);
1967   if (DataInCode)
1968     PrintDataInCodeTable(MachOOF, !NonVerbose);
1969   if (LinkOptHints)
1970     PrintLinkOptHints(MachOOF);
1971   if (Relocations)
1972     PrintRelocations(MachOOF, !NonVerbose);
1973   if (SectionHeaders)
1974     printSectionHeaders(MachOOF);
1975   if (SectionContents)
1976     printSectionContents(MachOOF);
1977   if (!FilterSections.empty())
1978     DumpSectionContents(FileName, MachOOF, !NonVerbose);
1979   if (InfoPlist)
1980     DumpInfoPlistSectionContents(FileName, MachOOF);
1981   if (DylibsUsed)
1982     PrintDylibs(MachOOF, false);
1983   if (DylibId)
1984     PrintDylibs(MachOOF, true);
1985   if (SymbolTable)
1986     printSymbolTable(MachOOF, ArchiveName, ArchitectureName);
1987   if (UnwindInfo)
1988     printMachOUnwindInfo(MachOOF);
1989   if (PrivateHeaders) {
1990     printMachOFileHeader(MachOOF);
1991     printMachOLoadCommands(MachOOF);
1992   }
1993   if (FirstPrivateHeader)
1994     printMachOFileHeader(MachOOF);
1995   if (ObjcMetaData)
1996     printObjcMetaData(MachOOF, !NonVerbose);
1997   if (ExportsTrie)
1998     printExportsTrie(MachOOF);
1999   if (Rebase)
2000     printRebaseTable(MachOOF);
2001   if (Bind)
2002     printBindTable(MachOOF);
2003   if (LazyBind)
2004     printLazyBindTable(MachOOF);
2005   if (WeakBind)
2006     printWeakBindTable(MachOOF);
2007 
2008   if (DwarfDumpType != DIDT_Null) {
2009     std::unique_ptr<DIContext> DICtx = DWARFContext::create(*MachOOF);
2010     // Dump the complete DWARF structure.
2011     DIDumpOptions DumpOpts;
2012     DumpOpts.DumpType = DwarfDumpType;
2013     DICtx->dump(outs(), DumpOpts);
2014   }
2015 }
2016 
2017 // printUnknownCPUType() helps print_fat_headers for unknown CPU's.
2018 static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
2019   outs() << "    cputype (" << cputype << ")\n";
2020   outs() << "    cpusubtype (" << cpusubtype << ")\n";
2021 }
2022 
2023 // printCPUType() helps print_fat_headers by printing the cputype and
2024 // pusubtype (symbolically for the one's it knows about).
2025 static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
2026   switch (cputype) {
2027   case MachO::CPU_TYPE_I386:
2028     switch (cpusubtype) {
2029     case MachO::CPU_SUBTYPE_I386_ALL:
2030       outs() << "    cputype CPU_TYPE_I386\n";
2031       outs() << "    cpusubtype CPU_SUBTYPE_I386_ALL\n";
2032       break;
2033     default:
2034       printUnknownCPUType(cputype, cpusubtype);
2035       break;
2036     }
2037     break;
2038   case MachO::CPU_TYPE_X86_64:
2039     switch (cpusubtype) {
2040     case MachO::CPU_SUBTYPE_X86_64_ALL:
2041       outs() << "    cputype CPU_TYPE_X86_64\n";
2042       outs() << "    cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
2043       break;
2044     case MachO::CPU_SUBTYPE_X86_64_H:
2045       outs() << "    cputype CPU_TYPE_X86_64\n";
2046       outs() << "    cpusubtype CPU_SUBTYPE_X86_64_H\n";
2047       break;
2048     default:
2049       printUnknownCPUType(cputype, cpusubtype);
2050       break;
2051     }
2052     break;
2053   case MachO::CPU_TYPE_ARM:
2054     switch (cpusubtype) {
2055     case MachO::CPU_SUBTYPE_ARM_ALL:
2056       outs() << "    cputype CPU_TYPE_ARM\n";
2057       outs() << "    cpusubtype CPU_SUBTYPE_ARM_ALL\n";
2058       break;
2059     case MachO::CPU_SUBTYPE_ARM_V4T:
2060       outs() << "    cputype CPU_TYPE_ARM\n";
2061       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V4T\n";
2062       break;
2063     case MachO::CPU_SUBTYPE_ARM_V5TEJ:
2064       outs() << "    cputype CPU_TYPE_ARM\n";
2065       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
2066       break;
2067     case MachO::CPU_SUBTYPE_ARM_XSCALE:
2068       outs() << "    cputype CPU_TYPE_ARM\n";
2069       outs() << "    cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
2070       break;
2071     case MachO::CPU_SUBTYPE_ARM_V6:
2072       outs() << "    cputype CPU_TYPE_ARM\n";
2073       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V6\n";
2074       break;
2075     case MachO::CPU_SUBTYPE_ARM_V6M:
2076       outs() << "    cputype CPU_TYPE_ARM\n";
2077       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V6M\n";
2078       break;
2079     case MachO::CPU_SUBTYPE_ARM_V7:
2080       outs() << "    cputype CPU_TYPE_ARM\n";
2081       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V7\n";
2082       break;
2083     case MachO::CPU_SUBTYPE_ARM_V7EM:
2084       outs() << "    cputype CPU_TYPE_ARM\n";
2085       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
2086       break;
2087     case MachO::CPU_SUBTYPE_ARM_V7K:
2088       outs() << "    cputype CPU_TYPE_ARM\n";
2089       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V7K\n";
2090       break;
2091     case MachO::CPU_SUBTYPE_ARM_V7M:
2092       outs() << "    cputype CPU_TYPE_ARM\n";
2093       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V7M\n";
2094       break;
2095     case MachO::CPU_SUBTYPE_ARM_V7S:
2096       outs() << "    cputype CPU_TYPE_ARM\n";
2097       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V7S\n";
2098       break;
2099     default:
2100       printUnknownCPUType(cputype, cpusubtype);
2101       break;
2102     }
2103     break;
2104   case MachO::CPU_TYPE_ARM64:
2105     switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2106     case MachO::CPU_SUBTYPE_ARM64_ALL:
2107       outs() << "    cputype CPU_TYPE_ARM64\n";
2108       outs() << "    cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
2109       break;
2110     case MachO::CPU_SUBTYPE_ARM64_V8:
2111       outs() << "    cputype CPU_TYPE_ARM64\n";
2112       outs() << "    cpusubtype CPU_SUBTYPE_ARM64_V8\n";
2113       break;
2114     case MachO::CPU_SUBTYPE_ARM64E:
2115       outs() << "    cputype CPU_TYPE_ARM64\n";
2116       outs() << "    cpusubtype CPU_SUBTYPE_ARM64E\n";
2117       break;
2118     default:
2119       printUnknownCPUType(cputype, cpusubtype);
2120       break;
2121     }
2122     break;
2123   case MachO::CPU_TYPE_ARM64_32:
2124     switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2125     case MachO::CPU_SUBTYPE_ARM64_32_V8:
2126       outs() << "    cputype CPU_TYPE_ARM64_32\n";
2127       outs() << "    cpusubtype CPU_SUBTYPE_ARM64_32_V8\n";
2128       break;
2129     default:
2130       printUnknownCPUType(cputype, cpusubtype);
2131       break;
2132     }
2133     break;
2134   default:
2135     printUnknownCPUType(cputype, cpusubtype);
2136     break;
2137   }
2138 }
2139 
2140 static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
2141                                        bool verbose) {
2142   outs() << "Fat headers\n";
2143   if (verbose) {
2144     if (UB->getMagic() == MachO::FAT_MAGIC)
2145       outs() << "fat_magic FAT_MAGIC\n";
2146     else // UB->getMagic() == MachO::FAT_MAGIC_64
2147       outs() << "fat_magic FAT_MAGIC_64\n";
2148   } else
2149     outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
2150 
2151   uint32_t nfat_arch = UB->getNumberOfObjects();
2152   StringRef Buf = UB->getData();
2153   uint64_t size = Buf.size();
2154   uint64_t big_size = sizeof(struct MachO::fat_header) +
2155                       nfat_arch * sizeof(struct MachO::fat_arch);
2156   outs() << "nfat_arch " << UB->getNumberOfObjects();
2157   if (nfat_arch == 0)
2158     outs() << " (malformed, contains zero architecture types)\n";
2159   else if (big_size > size)
2160     outs() << " (malformed, architectures past end of file)\n";
2161   else
2162     outs() << "\n";
2163 
2164   for (uint32_t i = 0; i < nfat_arch; ++i) {
2165     MachOUniversalBinary::ObjectForArch OFA(UB, i);
2166     uint32_t cputype = OFA.getCPUType();
2167     uint32_t cpusubtype = OFA.getCPUSubType();
2168     outs() << "architecture ";
2169     for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
2170       MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
2171       uint32_t other_cputype = other_OFA.getCPUType();
2172       uint32_t other_cpusubtype = other_OFA.getCPUSubType();
2173       if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
2174           (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
2175               (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
2176         outs() << "(illegal duplicate architecture) ";
2177         break;
2178       }
2179     }
2180     if (verbose) {
2181       outs() << OFA.getArchFlagName() << "\n";
2182       printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2183     } else {
2184       outs() << i << "\n";
2185       outs() << "    cputype " << cputype << "\n";
2186       outs() << "    cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
2187              << "\n";
2188     }
2189     if (verbose &&
2190         (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
2191       outs() << "    capabilities CPU_SUBTYPE_LIB64\n";
2192     else
2193       outs() << "    capabilities "
2194              << format("0x%" PRIx32,
2195                        (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
2196     outs() << "    offset " << OFA.getOffset();
2197     if (OFA.getOffset() > size)
2198       outs() << " (past end of file)";
2199     if (OFA.getOffset() % (1ull << OFA.getAlign()) != 0)
2200       outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
2201     outs() << "\n";
2202     outs() << "    size " << OFA.getSize();
2203     big_size = OFA.getOffset() + OFA.getSize();
2204     if (big_size > size)
2205       outs() << " (past end of file)";
2206     outs() << "\n";
2207     outs() << "    align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
2208            << ")\n";
2209   }
2210 }
2211 
2212 static void printArchiveChild(StringRef Filename, const Archive::Child &C,
2213                               size_t ChildIndex, bool verbose,
2214                               bool print_offset,
2215                               StringRef ArchitectureName = StringRef()) {
2216   if (print_offset)
2217     outs() << C.getChildOffset() << "\t";
2218   sys::fs::perms Mode =
2219       unwrapOrError(C.getAccessMode(), getFileNameForError(C, ChildIndex),
2220                     Filename, ArchitectureName);
2221   if (verbose) {
2222     // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
2223     // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
2224     outs() << "-";
2225     outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
2226     outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
2227     outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
2228     outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
2229     outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
2230     outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
2231     outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
2232     outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
2233     outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
2234   } else {
2235     outs() << format("0%o ", Mode);
2236   }
2237 
2238   outs() << format("%3d/%-3d %5" PRId64 " ",
2239                    unwrapOrError(C.getUID(), getFileNameForError(C, ChildIndex),
2240                                  Filename, ArchitectureName),
2241                    unwrapOrError(C.getGID(), getFileNameForError(C, ChildIndex),
2242                                  Filename, ArchitectureName),
2243                    unwrapOrError(C.getRawSize(),
2244                                  getFileNameForError(C, ChildIndex), Filename,
2245                                  ArchitectureName));
2246 
2247   StringRef RawLastModified = C.getRawLastModified();
2248   if (verbose) {
2249     unsigned Seconds;
2250     if (RawLastModified.getAsInteger(10, Seconds))
2251       outs() << "(date: \"" << RawLastModified
2252              << "\" contains non-decimal chars) ";
2253     else {
2254       // Since cime(3) returns a 26 character string of the form:
2255       // "Sun Sep 16 01:03:52 1973\n\0"
2256       // just print 24 characters.
2257       time_t t = Seconds;
2258       outs() << format("%.24s ", ctime(&t));
2259     }
2260   } else {
2261     outs() << RawLastModified << " ";
2262   }
2263 
2264   if (verbose) {
2265     Expected<StringRef> NameOrErr = C.getName();
2266     if (!NameOrErr) {
2267       consumeError(NameOrErr.takeError());
2268       outs() << unwrapOrError(C.getRawName(),
2269                               getFileNameForError(C, ChildIndex), Filename,
2270                               ArchitectureName)
2271              << "\n";
2272     } else {
2273       StringRef Name = NameOrErr.get();
2274       outs() << Name << "\n";
2275     }
2276   } else {
2277     outs() << unwrapOrError(C.getRawName(), getFileNameForError(C, ChildIndex),
2278                             Filename, ArchitectureName)
2279            << "\n";
2280   }
2281 }
2282 
2283 static void printArchiveHeaders(StringRef Filename, Archive *A, bool verbose,
2284                                 bool print_offset,
2285                                 StringRef ArchitectureName = StringRef()) {
2286   Error Err = Error::success();
2287   size_t I = 0;
2288   for (const auto &C : A->children(Err, false))
2289     printArchiveChild(Filename, C, I++, verbose, print_offset,
2290                       ArchitectureName);
2291 
2292   if (Err)
2293     reportError(std::move(Err), Filename, "", ArchitectureName);
2294 }
2295 
2296 static bool ValidateArchFlags() {
2297   // Check for -arch all and verifiy the -arch flags are valid.
2298   for (unsigned i = 0; i < ArchFlags.size(); ++i) {
2299     if (ArchFlags[i] == "all") {
2300       ArchAll = true;
2301     } else {
2302       if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
2303         WithColor::error(errs(), "llvm-objdump")
2304             << "unknown architecture named '" + ArchFlags[i] +
2305                    "'for the -arch option\n";
2306         return false;
2307       }
2308     }
2309   }
2310   return true;
2311 }
2312 
2313 // ParseInputMachO() parses the named Mach-O file in Filename and handles the
2314 // -arch flags selecting just those slices as specified by them and also parses
2315 // archive files.  Then for each individual Mach-O file ProcessMachO() is
2316 // called to process the file based on the command line options.
2317 void objdump::parseInputMachO(StringRef Filename) {
2318   if (!ValidateArchFlags())
2319     return;
2320 
2321   // Attempt to open the binary.
2322   Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
2323   if (!BinaryOrErr) {
2324     if (Error E = isNotObjectErrorInvalidFileType(BinaryOrErr.takeError()))
2325       reportError(std::move(E), Filename);
2326     else
2327       outs() << Filename << ": is not an object file\n";
2328     return;
2329   }
2330   Binary &Bin = *BinaryOrErr.get().getBinary();
2331 
2332   if (Archive *A = dyn_cast<Archive>(&Bin)) {
2333     outs() << "Archive : " << Filename << "\n";
2334     if (ArchiveHeaders)
2335       printArchiveHeaders(Filename, A, !NonVerbose, ArchiveMemberOffsets);
2336 
2337     Error Err = Error::success();
2338     unsigned I = -1;
2339     for (auto &C : A->children(Err)) {
2340       ++I;
2341       Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2342       if (!ChildOrErr) {
2343         if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2344           reportError(std::move(E), getFileNameForError(C, I), Filename);
2345         continue;
2346       }
2347       if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
2348         if (!checkMachOAndArchFlags(O, Filename))
2349           return;
2350         ProcessMachO(Filename, O, O->getFileName());
2351       }
2352     }
2353     if (Err)
2354       reportError(std::move(Err), Filename);
2355     return;
2356   }
2357   if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
2358     parseInputMachO(UB);
2359     return;
2360   }
2361   if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
2362     if (!checkMachOAndArchFlags(O, Filename))
2363       return;
2364     if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O))
2365       ProcessMachO(Filename, MachOOF);
2366     else
2367       WithColor::error(errs(), "llvm-objdump")
2368           << Filename << "': "
2369           << "object is not a Mach-O file type.\n";
2370     return;
2371   }
2372   llvm_unreachable("Input object can't be invalid at this point");
2373 }
2374 
2375 void objdump::parseInputMachO(MachOUniversalBinary *UB) {
2376   if (!ValidateArchFlags())
2377     return;
2378 
2379   auto Filename = UB->getFileName();
2380 
2381   if (UniversalHeaders)
2382     printMachOUniversalHeaders(UB, !NonVerbose);
2383 
2384   // If we have a list of architecture flags specified dump only those.
2385   if (!ArchAll && !ArchFlags.empty()) {
2386     // Look for a slice in the universal binary that matches each ArchFlag.
2387     bool ArchFound;
2388     for (unsigned i = 0; i < ArchFlags.size(); ++i) {
2389       ArchFound = false;
2390       for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2391                                                   E = UB->end_objects();
2392             I != E; ++I) {
2393         if (ArchFlags[i] == I->getArchFlagName()) {
2394           ArchFound = true;
2395           Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
2396               I->getAsObjectFile();
2397           std::string ArchitectureName;
2398           if (ArchFlags.size() > 1)
2399             ArchitectureName = I->getArchFlagName();
2400           if (ObjOrErr) {
2401             ObjectFile &O = *ObjOrErr.get();
2402             if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
2403               ProcessMachO(Filename, MachOOF, "", ArchitectureName);
2404           } else if (Error E = isNotObjectErrorInvalidFileType(
2405                          ObjOrErr.takeError())) {
2406             reportError(std::move(E), "", Filename, ArchitectureName);
2407             continue;
2408           } else if (Expected<std::unique_ptr<Archive>> AOrErr =
2409                          I->getAsArchive()) {
2410             std::unique_ptr<Archive> &A = *AOrErr;
2411             outs() << "Archive : " << Filename;
2412             if (!ArchitectureName.empty())
2413               outs() << " (architecture " << ArchitectureName << ")";
2414             outs() << "\n";
2415             if (ArchiveHeaders)
2416               printArchiveHeaders(Filename, A.get(), !NonVerbose,
2417                                   ArchiveMemberOffsets, ArchitectureName);
2418             Error Err = Error::success();
2419             unsigned I = -1;
2420             for (auto &C : A->children(Err)) {
2421               ++I;
2422               Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2423               if (!ChildOrErr) {
2424                 if (Error E =
2425                         isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2426                   reportError(std::move(E), getFileNameForError(C, I), Filename,
2427                               ArchitectureName);
2428                 continue;
2429               }
2430               if (MachOObjectFile *O =
2431                       dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
2432                 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
2433             }
2434             if (Err)
2435               reportError(std::move(Err), Filename);
2436           } else {
2437             consumeError(AOrErr.takeError());
2438             reportError(Filename,
2439                         "Mach-O universal file for architecture " +
2440                             StringRef(I->getArchFlagName()) +
2441                             " is not a Mach-O file or an archive file");
2442           }
2443         }
2444       }
2445       if (!ArchFound) {
2446         WithColor::error(errs(), "llvm-objdump")
2447             << "file: " + Filename + " does not contain "
2448             << "architecture: " + ArchFlags[i] + "\n";
2449         return;
2450       }
2451     }
2452     return;
2453   }
2454   // No architecture flags were specified so if this contains a slice that
2455   // matches the host architecture dump only that.
2456   if (!ArchAll) {
2457     for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2458                                                 E = UB->end_objects();
2459           I != E; ++I) {
2460       if (MachOObjectFile::getHostArch().getArchName() ==
2461           I->getArchFlagName()) {
2462         Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2463         std::string ArchiveName;
2464         ArchiveName.clear();
2465         if (ObjOrErr) {
2466           ObjectFile &O = *ObjOrErr.get();
2467           if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
2468             ProcessMachO(Filename, MachOOF);
2469         } else if (Error E =
2470                        isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) {
2471           reportError(std::move(E), Filename);
2472         } else if (Expected<std::unique_ptr<Archive>> AOrErr =
2473                        I->getAsArchive()) {
2474           std::unique_ptr<Archive> &A = *AOrErr;
2475           outs() << "Archive : " << Filename << "\n";
2476           if (ArchiveHeaders)
2477             printArchiveHeaders(Filename, A.get(), !NonVerbose,
2478                                 ArchiveMemberOffsets);
2479           Error Err = Error::success();
2480           unsigned I = -1;
2481           for (auto &C : A->children(Err)) {
2482             ++I;
2483             Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2484             if (!ChildOrErr) {
2485               if (Error E =
2486                       isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2487                 reportError(std::move(E), getFileNameForError(C, I), Filename);
2488               continue;
2489             }
2490             if (MachOObjectFile *O =
2491                     dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
2492               ProcessMachO(Filename, O, O->getFileName());
2493           }
2494           if (Err)
2495             reportError(std::move(Err), Filename);
2496         } else {
2497           consumeError(AOrErr.takeError());
2498           reportError(Filename, "Mach-O universal file for architecture " +
2499                                     StringRef(I->getArchFlagName()) +
2500                                     " is not a Mach-O file or an archive file");
2501         }
2502         return;
2503       }
2504     }
2505   }
2506   // Either all architectures have been specified or none have been specified
2507   // and this does not contain the host architecture so dump all the slices.
2508   bool moreThanOneArch = UB->getNumberOfObjects() > 1;
2509   for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2510                                               E = UB->end_objects();
2511         I != E; ++I) {
2512     Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2513     std::string ArchitectureName;
2514     if (moreThanOneArch)
2515       ArchitectureName = I->getArchFlagName();
2516     if (ObjOrErr) {
2517       ObjectFile &Obj = *ObjOrErr.get();
2518       if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
2519         ProcessMachO(Filename, MachOOF, "", ArchitectureName);
2520     } else if (Error E =
2521                    isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) {
2522       reportError(std::move(E), Filename, "", ArchitectureName);
2523     } else if (Expected<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
2524       std::unique_ptr<Archive> &A = *AOrErr;
2525       outs() << "Archive : " << Filename;
2526       if (!ArchitectureName.empty())
2527         outs() << " (architecture " << ArchitectureName << ")";
2528       outs() << "\n";
2529       if (ArchiveHeaders)
2530         printArchiveHeaders(Filename, A.get(), !NonVerbose,
2531                             ArchiveMemberOffsets, ArchitectureName);
2532       Error Err = Error::success();
2533       unsigned I = -1;
2534       for (auto &C : A->children(Err)) {
2535         ++I;
2536         Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2537         if (!ChildOrErr) {
2538           if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2539             reportError(std::move(E), getFileNameForError(C, I), Filename,
2540                         ArchitectureName);
2541           continue;
2542         }
2543         if (MachOObjectFile *O =
2544                 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
2545           if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
2546             ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
2547                           ArchitectureName);
2548         }
2549       }
2550       if (Err)
2551         reportError(std::move(Err), Filename);
2552     } else {
2553       consumeError(AOrErr.takeError());
2554       reportError(Filename, "Mach-O universal file for architecture " +
2555                                 StringRef(I->getArchFlagName()) +
2556                                 " is not a Mach-O file or an archive file");
2557     }
2558   }
2559 }
2560 
2561 namespace {
2562 // The block of info used by the Symbolizer call backs.
2563 struct DisassembleInfo {
2564   DisassembleInfo(MachOObjectFile *O, SymbolAddressMap *AddrMap,
2565                   std::vector<SectionRef> *Sections, bool verbose)
2566     : verbose(verbose), O(O), AddrMap(AddrMap), Sections(Sections) {}
2567   bool verbose;
2568   MachOObjectFile *O;
2569   SectionRef S;
2570   SymbolAddressMap *AddrMap;
2571   std::vector<SectionRef> *Sections;
2572   const char *class_name = nullptr;
2573   const char *selector_name = nullptr;
2574   std::unique_ptr<char[]> method = nullptr;
2575   char *demangled_name = nullptr;
2576   uint64_t adrp_addr = 0;
2577   uint32_t adrp_inst = 0;
2578   std::unique_ptr<SymbolAddressMap> bindtable;
2579   uint32_t depth = 0;
2580 };
2581 } // namespace
2582 
2583 // SymbolizerGetOpInfo() is the operand information call back function.
2584 // This is called to get the symbolic information for operand(s) of an
2585 // instruction when it is being done.  This routine does this from
2586 // the relocation information, symbol table, etc. That block of information
2587 // is a pointer to the struct DisassembleInfo that was passed when the
2588 // disassembler context was created and passed to back to here when
2589 // called back by the disassembler for instruction operands that could have
2590 // relocation information. The address of the instruction containing operand is
2591 // at the Pc parameter.  The immediate value the operand has is passed in
2592 // op_info->Value and is at Offset past the start of the instruction and has a
2593 // byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
2594 // LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
2595 // names and addends of the symbolic expression to add for the operand.  The
2596 // value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
2597 // information is returned then this function returns 1 else it returns 0.
2598 static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
2599                                uint64_t Size, int TagType, void *TagBuf) {
2600   struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
2601   struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
2602   uint64_t value = op_info->Value;
2603 
2604   // Make sure all fields returned are zero if we don't set them.
2605   memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
2606   op_info->Value = value;
2607 
2608   // If the TagType is not the value 1 which it code knows about or if no
2609   // verbose symbolic information is wanted then just return 0, indicating no
2610   // information is being returned.
2611   if (TagType != 1 || !info->verbose)
2612     return 0;
2613 
2614   unsigned int Arch = info->O->getArch();
2615   if (Arch == Triple::x86) {
2616     if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
2617       return 0;
2618     if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2619       // TODO:
2620       // Search the external relocation entries of a fully linked image
2621       // (if any) for an entry that matches this segment offset.
2622       // uint32_t seg_offset = (Pc + Offset);
2623       return 0;
2624     }
2625     // In MH_OBJECT filetypes search the section's relocation entries (if any)
2626     // for an entry for this section offset.
2627     uint32_t sect_addr = info->S.getAddress();
2628     uint32_t sect_offset = (Pc + Offset) - sect_addr;
2629     bool reloc_found = false;
2630     DataRefImpl Rel;
2631     MachO::any_relocation_info RE;
2632     bool isExtern = false;
2633     SymbolRef Symbol;
2634     bool r_scattered = false;
2635     uint32_t r_value, pair_r_value, r_type;
2636     for (const RelocationRef &Reloc : info->S.relocations()) {
2637       uint64_t RelocOffset = Reloc.getOffset();
2638       if (RelocOffset == sect_offset) {
2639         Rel = Reloc.getRawDataRefImpl();
2640         RE = info->O->getRelocation(Rel);
2641         r_type = info->O->getAnyRelocationType(RE);
2642         r_scattered = info->O->isRelocationScattered(RE);
2643         if (r_scattered) {
2644           r_value = info->O->getScatteredRelocationValue(RE);
2645           if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2646               r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
2647             DataRefImpl RelNext = Rel;
2648             info->O->moveRelocationNext(RelNext);
2649             MachO::any_relocation_info RENext;
2650             RENext = info->O->getRelocation(RelNext);
2651             if (info->O->isRelocationScattered(RENext))
2652               pair_r_value = info->O->getScatteredRelocationValue(RENext);
2653             else
2654               return 0;
2655           }
2656         } else {
2657           isExtern = info->O->getPlainRelocationExternal(RE);
2658           if (isExtern) {
2659             symbol_iterator RelocSym = Reloc.getSymbol();
2660             Symbol = *RelocSym;
2661           }
2662         }
2663         reloc_found = true;
2664         break;
2665       }
2666     }
2667     if (reloc_found && isExtern) {
2668       op_info->AddSymbol.Present = 1;
2669       op_info->AddSymbol.Name =
2670           unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
2671       // For i386 extern relocation entries the value in the instruction is
2672       // the offset from the symbol, and value is already set in op_info->Value.
2673       return 1;
2674     }
2675     if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2676                         r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
2677       const char *add = GuessSymbolName(r_value, info->AddrMap);
2678       const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
2679       uint32_t offset = value - (r_value - pair_r_value);
2680       op_info->AddSymbol.Present = 1;
2681       if (add != nullptr)
2682         op_info->AddSymbol.Name = add;
2683       else
2684         op_info->AddSymbol.Value = r_value;
2685       op_info->SubtractSymbol.Present = 1;
2686       if (sub != nullptr)
2687         op_info->SubtractSymbol.Name = sub;
2688       else
2689         op_info->SubtractSymbol.Value = pair_r_value;
2690       op_info->Value = offset;
2691       return 1;
2692     }
2693     return 0;
2694   }
2695   if (Arch == Triple::x86_64) {
2696     if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
2697       return 0;
2698     // For non MH_OBJECT types, like MH_KEXT_BUNDLE, Search the external
2699     // relocation entries of a linked image (if any) for an entry that matches
2700     // this segment offset.
2701     if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2702       uint64_t seg_offset = Pc + Offset;
2703       bool reloc_found = false;
2704       DataRefImpl Rel;
2705       MachO::any_relocation_info RE;
2706       bool isExtern = false;
2707       SymbolRef Symbol;
2708       for (const RelocationRef &Reloc : info->O->external_relocations()) {
2709         uint64_t RelocOffset = Reloc.getOffset();
2710         if (RelocOffset == seg_offset) {
2711           Rel = Reloc.getRawDataRefImpl();
2712           RE = info->O->getRelocation(Rel);
2713           // external relocation entries should always be external.
2714           isExtern = info->O->getPlainRelocationExternal(RE);
2715           if (isExtern) {
2716             symbol_iterator RelocSym = Reloc.getSymbol();
2717             Symbol = *RelocSym;
2718           }
2719           reloc_found = true;
2720           break;
2721         }
2722       }
2723       if (reloc_found && isExtern) {
2724         // The Value passed in will be adjusted by the Pc if the instruction
2725         // adds the Pc.  But for x86_64 external relocation entries the Value
2726         // is the offset from the external symbol.
2727         if (info->O->getAnyRelocationPCRel(RE))
2728           op_info->Value -= Pc + Offset + Size;
2729         const char *name =
2730             unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
2731         op_info->AddSymbol.Present = 1;
2732         op_info->AddSymbol.Name = name;
2733         return 1;
2734       }
2735       return 0;
2736     }
2737     // In MH_OBJECT filetypes search the section's relocation entries (if any)
2738     // for an entry for this section offset.
2739     uint64_t sect_addr = info->S.getAddress();
2740     uint64_t sect_offset = (Pc + Offset) - sect_addr;
2741     bool reloc_found = false;
2742     DataRefImpl Rel;
2743     MachO::any_relocation_info RE;
2744     bool isExtern = false;
2745     SymbolRef Symbol;
2746     for (const RelocationRef &Reloc : info->S.relocations()) {
2747       uint64_t RelocOffset = Reloc.getOffset();
2748       if (RelocOffset == sect_offset) {
2749         Rel = Reloc.getRawDataRefImpl();
2750         RE = info->O->getRelocation(Rel);
2751         // NOTE: Scattered relocations don't exist on x86_64.
2752         isExtern = info->O->getPlainRelocationExternal(RE);
2753         if (isExtern) {
2754           symbol_iterator RelocSym = Reloc.getSymbol();
2755           Symbol = *RelocSym;
2756         }
2757         reloc_found = true;
2758         break;
2759       }
2760     }
2761     if (reloc_found && isExtern) {
2762       // The Value passed in will be adjusted by the Pc if the instruction
2763       // adds the Pc.  But for x86_64 external relocation entries the Value
2764       // is the offset from the external symbol.
2765       if (info->O->getAnyRelocationPCRel(RE))
2766         op_info->Value -= Pc + Offset + Size;
2767       const char *name =
2768           unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
2769       unsigned Type = info->O->getAnyRelocationType(RE);
2770       if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
2771         DataRefImpl RelNext = Rel;
2772         info->O->moveRelocationNext(RelNext);
2773         MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2774         unsigned TypeNext = info->O->getAnyRelocationType(RENext);
2775         bool isExternNext = info->O->getPlainRelocationExternal(RENext);
2776         unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
2777         if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
2778           op_info->SubtractSymbol.Present = 1;
2779           op_info->SubtractSymbol.Name = name;
2780           symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
2781           Symbol = *RelocSymNext;
2782           name = unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
2783         }
2784       }
2785       // TODO: add the VariantKinds to op_info->VariantKind for relocation types
2786       // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
2787       op_info->AddSymbol.Present = 1;
2788       op_info->AddSymbol.Name = name;
2789       return 1;
2790     }
2791     return 0;
2792   }
2793   if (Arch == Triple::arm) {
2794     if (Offset != 0 || (Size != 4 && Size != 2))
2795       return 0;
2796     if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2797       // TODO:
2798       // Search the external relocation entries of a fully linked image
2799       // (if any) for an entry that matches this segment offset.
2800       // uint32_t seg_offset = (Pc + Offset);
2801       return 0;
2802     }
2803     // In MH_OBJECT filetypes search the section's relocation entries (if any)
2804     // for an entry for this section offset.
2805     uint32_t sect_addr = info->S.getAddress();
2806     uint32_t sect_offset = (Pc + Offset) - sect_addr;
2807     DataRefImpl Rel;
2808     MachO::any_relocation_info RE;
2809     bool isExtern = false;
2810     SymbolRef Symbol;
2811     bool r_scattered = false;
2812     uint32_t r_value, pair_r_value, r_type, r_length, other_half;
2813     auto Reloc =
2814         find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2815           uint64_t RelocOffset = Reloc.getOffset();
2816           return RelocOffset == sect_offset;
2817         });
2818 
2819     if (Reloc == info->S.relocations().end())
2820       return 0;
2821 
2822     Rel = Reloc->getRawDataRefImpl();
2823     RE = info->O->getRelocation(Rel);
2824     r_length = info->O->getAnyRelocationLength(RE);
2825     r_scattered = info->O->isRelocationScattered(RE);
2826     if (r_scattered) {
2827       r_value = info->O->getScatteredRelocationValue(RE);
2828       r_type = info->O->getScatteredRelocationType(RE);
2829     } else {
2830       r_type = info->O->getAnyRelocationType(RE);
2831       isExtern = info->O->getPlainRelocationExternal(RE);
2832       if (isExtern) {
2833         symbol_iterator RelocSym = Reloc->getSymbol();
2834         Symbol = *RelocSym;
2835       }
2836     }
2837     if (r_type == MachO::ARM_RELOC_HALF ||
2838         r_type == MachO::ARM_RELOC_SECTDIFF ||
2839         r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
2840         r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2841       DataRefImpl RelNext = Rel;
2842       info->O->moveRelocationNext(RelNext);
2843       MachO::any_relocation_info RENext;
2844       RENext = info->O->getRelocation(RelNext);
2845       other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
2846       if (info->O->isRelocationScattered(RENext))
2847         pair_r_value = info->O->getScatteredRelocationValue(RENext);
2848     }
2849 
2850     if (isExtern) {
2851       const char *name =
2852           unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
2853       op_info->AddSymbol.Present = 1;
2854       op_info->AddSymbol.Name = name;
2855       switch (r_type) {
2856       case MachO::ARM_RELOC_HALF:
2857         if ((r_length & 0x1) == 1) {
2858           op_info->Value = value << 16 | other_half;
2859           op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2860         } else {
2861           op_info->Value = other_half << 16 | value;
2862           op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
2863         }
2864         break;
2865       default:
2866         break;
2867       }
2868       return 1;
2869     }
2870     // If we have a branch that is not an external relocation entry then
2871     // return 0 so the code in tryAddingSymbolicOperand() can use the
2872     // SymbolLookUp call back with the branch target address to look up the
2873     // symbol and possibility add an annotation for a symbol stub.
2874     if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
2875                           r_type == MachO::ARM_THUMB_RELOC_BR22))
2876       return 0;
2877 
2878     uint32_t offset = 0;
2879     if (r_type == MachO::ARM_RELOC_HALF ||
2880         r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2881       if ((r_length & 0x1) == 1)
2882         value = value << 16 | other_half;
2883       else
2884         value = other_half << 16 | value;
2885     }
2886     if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
2887                         r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
2888       offset = value - r_value;
2889       value = r_value;
2890     }
2891 
2892     if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2893       if ((r_length & 0x1) == 1)
2894         op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2895       else
2896         op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
2897       const char *add = GuessSymbolName(r_value, info->AddrMap);
2898       const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
2899       int32_t offset = value - (r_value - pair_r_value);
2900       op_info->AddSymbol.Present = 1;
2901       if (add != nullptr)
2902         op_info->AddSymbol.Name = add;
2903       else
2904         op_info->AddSymbol.Value = r_value;
2905       op_info->SubtractSymbol.Present = 1;
2906       if (sub != nullptr)
2907         op_info->SubtractSymbol.Name = sub;
2908       else
2909         op_info->SubtractSymbol.Value = pair_r_value;
2910       op_info->Value = offset;
2911       return 1;
2912     }
2913 
2914     op_info->AddSymbol.Present = 1;
2915     op_info->Value = offset;
2916     if (r_type == MachO::ARM_RELOC_HALF) {
2917       if ((r_length & 0x1) == 1)
2918         op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2919       else
2920         op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
2921     }
2922     const char *add = GuessSymbolName(value, info->AddrMap);
2923     if (add != nullptr) {
2924       op_info->AddSymbol.Name = add;
2925       return 1;
2926     }
2927     op_info->AddSymbol.Value = value;
2928     return 1;
2929   }
2930   if (Arch == Triple::aarch64) {
2931     if (Offset != 0 || Size != 4)
2932       return 0;
2933     if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2934       // TODO:
2935       // Search the external relocation entries of a fully linked image
2936       // (if any) for an entry that matches this segment offset.
2937       // uint64_t seg_offset = (Pc + Offset);
2938       return 0;
2939     }
2940     // In MH_OBJECT filetypes search the section's relocation entries (if any)
2941     // for an entry for this section offset.
2942     uint64_t sect_addr = info->S.getAddress();
2943     uint64_t sect_offset = (Pc + Offset) - sect_addr;
2944     auto Reloc =
2945         find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2946           uint64_t RelocOffset = Reloc.getOffset();
2947           return RelocOffset == sect_offset;
2948         });
2949 
2950     if (Reloc == info->S.relocations().end())
2951       return 0;
2952 
2953     DataRefImpl Rel = Reloc->getRawDataRefImpl();
2954     MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2955     uint32_t r_type = info->O->getAnyRelocationType(RE);
2956     if (r_type == MachO::ARM64_RELOC_ADDEND) {
2957       DataRefImpl RelNext = Rel;
2958       info->O->moveRelocationNext(RelNext);
2959       MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2960       if (value == 0) {
2961         value = info->O->getPlainRelocationSymbolNum(RENext);
2962         op_info->Value = value;
2963       }
2964     }
2965     // NOTE: Scattered relocations don't exist on arm64.
2966     if (!info->O->getPlainRelocationExternal(RE))
2967       return 0;
2968     const char *name =
2969         unwrapOrError(Reloc->getSymbol()->getName(), info->O->getFileName())
2970             .data();
2971     op_info->AddSymbol.Present = 1;
2972     op_info->AddSymbol.Name = name;
2973 
2974     switch (r_type) {
2975     case MachO::ARM64_RELOC_PAGE21:
2976       /* @page */
2977       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2978       break;
2979     case MachO::ARM64_RELOC_PAGEOFF12:
2980       /* @pageoff */
2981       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2982       break;
2983     case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2984       /* @gotpage */
2985       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2986       break;
2987     case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2988       /* @gotpageoff */
2989       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2990       break;
2991     case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2992       /* @tvlppage is not implemented in llvm-mc */
2993       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2994       break;
2995     case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2996       /* @tvlppageoff is not implemented in llvm-mc */
2997       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2998       break;
2999     default:
3000     case MachO::ARM64_RELOC_BRANCH26:
3001       op_info->VariantKind = LLVMDisassembler_VariantKind_None;
3002       break;
3003     }
3004     return 1;
3005   }
3006   return 0;
3007 }
3008 
3009 // GuessCstringPointer is passed the address of what might be a pointer to a
3010 // literal string in a cstring section.  If that address is in a cstring section
3011 // it returns a pointer to that string.  Else it returns nullptr.
3012 static const char *GuessCstringPointer(uint64_t ReferenceValue,
3013                                        struct DisassembleInfo *info) {
3014   for (const auto &Load : info->O->load_commands()) {
3015     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
3016       MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
3017       for (unsigned J = 0; J < Seg.nsects; ++J) {
3018         MachO::section_64 Sec = info->O->getSection64(Load, J);
3019         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3020         if (section_type == MachO::S_CSTRING_LITERALS &&
3021             ReferenceValue >= Sec.addr &&
3022             ReferenceValue < Sec.addr + Sec.size) {
3023           uint64_t sect_offset = ReferenceValue - Sec.addr;
3024           uint64_t object_offset = Sec.offset + sect_offset;
3025           StringRef MachOContents = info->O->getData();
3026           uint64_t object_size = MachOContents.size();
3027           const char *object_addr = (const char *)MachOContents.data();
3028           if (object_offset < object_size) {
3029             const char *name = object_addr + object_offset;
3030             return name;
3031           } else {
3032             return nullptr;
3033           }
3034         }
3035       }
3036     } else if (Load.C.cmd == MachO::LC_SEGMENT) {
3037       MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
3038       for (unsigned J = 0; J < Seg.nsects; ++J) {
3039         MachO::section Sec = info->O->getSection(Load, J);
3040         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3041         if (section_type == MachO::S_CSTRING_LITERALS &&
3042             ReferenceValue >= Sec.addr &&
3043             ReferenceValue < Sec.addr + Sec.size) {
3044           uint64_t sect_offset = ReferenceValue - Sec.addr;
3045           uint64_t object_offset = Sec.offset + sect_offset;
3046           StringRef MachOContents = info->O->getData();
3047           uint64_t object_size = MachOContents.size();
3048           const char *object_addr = (const char *)MachOContents.data();
3049           if (object_offset < object_size) {
3050             const char *name = object_addr + object_offset;
3051             return name;
3052           } else {
3053             return nullptr;
3054           }
3055         }
3056       }
3057     }
3058   }
3059   return nullptr;
3060 }
3061 
3062 // GuessIndirectSymbol returns the name of the indirect symbol for the
3063 // ReferenceValue passed in or nullptr.  This is used when ReferenceValue maybe
3064 // an address of a symbol stub or a lazy or non-lazy pointer to associate the
3065 // symbol name being referenced by the stub or pointer.
3066 static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
3067                                        struct DisassembleInfo *info) {
3068   MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
3069   MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
3070   for (const auto &Load : info->O->load_commands()) {
3071     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
3072       MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
3073       for (unsigned J = 0; J < Seg.nsects; ++J) {
3074         MachO::section_64 Sec = info->O->getSection64(Load, J);
3075         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3076         if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
3077              section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
3078              section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
3079              section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
3080              section_type == MachO::S_SYMBOL_STUBS) &&
3081             ReferenceValue >= Sec.addr &&
3082             ReferenceValue < Sec.addr + Sec.size) {
3083           uint32_t stride;
3084           if (section_type == MachO::S_SYMBOL_STUBS)
3085             stride = Sec.reserved2;
3086           else
3087             stride = 8;
3088           if (stride == 0)
3089             return nullptr;
3090           uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
3091           if (index < Dysymtab.nindirectsyms) {
3092             uint32_t indirect_symbol =
3093                 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
3094             if (indirect_symbol < Symtab.nsyms) {
3095               symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
3096               return unwrapOrError(Sym->getName(), info->O->getFileName())
3097                   .data();
3098             }
3099           }
3100         }
3101       }
3102     } else if (Load.C.cmd == MachO::LC_SEGMENT) {
3103       MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
3104       for (unsigned J = 0; J < Seg.nsects; ++J) {
3105         MachO::section Sec = info->O->getSection(Load, J);
3106         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3107         if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
3108              section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
3109              section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
3110              section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
3111              section_type == MachO::S_SYMBOL_STUBS) &&
3112             ReferenceValue >= Sec.addr &&
3113             ReferenceValue < Sec.addr + Sec.size) {
3114           uint32_t stride;
3115           if (section_type == MachO::S_SYMBOL_STUBS)
3116             stride = Sec.reserved2;
3117           else
3118             stride = 4;
3119           if (stride == 0)
3120             return nullptr;
3121           uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
3122           if (index < Dysymtab.nindirectsyms) {
3123             uint32_t indirect_symbol =
3124                 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
3125             if (indirect_symbol < Symtab.nsyms) {
3126               symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
3127               return unwrapOrError(Sym->getName(), info->O->getFileName())
3128                   .data();
3129             }
3130           }
3131         }
3132       }
3133     }
3134   }
3135   return nullptr;
3136 }
3137 
3138 // method_reference() is called passing it the ReferenceName that might be
3139 // a reference it to an Objective-C method call.  If so then it allocates and
3140 // assembles a method call string with the values last seen and saved in
3141 // the DisassembleInfo's class_name and selector_name fields.  This is saved
3142 // into the method field of the info and any previous string is free'ed.
3143 // Then the class_name field in the info is set to nullptr.  The method call
3144 // string is set into ReferenceName and ReferenceType is set to
3145 // LLVMDisassembler_ReferenceType_Out_Objc_Message.  If this not a method call
3146 // then both ReferenceType and ReferenceName are left unchanged.
3147 static void method_reference(struct DisassembleInfo *info,
3148                              uint64_t *ReferenceType,
3149                              const char **ReferenceName) {
3150   unsigned int Arch = info->O->getArch();
3151   if (*ReferenceName != nullptr) {
3152     if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
3153       if (info->selector_name != nullptr) {
3154         if (info->class_name != nullptr) {
3155           info->method = std::make_unique<char[]>(
3156               5 + strlen(info->class_name) + strlen(info->selector_name));
3157           char *method = info->method.get();
3158           if (method != nullptr) {
3159             strcpy(method, "+[");
3160             strcat(method, info->class_name);
3161             strcat(method, " ");
3162             strcat(method, info->selector_name);
3163             strcat(method, "]");
3164             *ReferenceName = method;
3165             *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3166           }
3167         } else {
3168           info->method =
3169               std::make_unique<char[]>(9 + strlen(info->selector_name));
3170           char *method = info->method.get();
3171           if (method != nullptr) {
3172             if (Arch == Triple::x86_64)
3173               strcpy(method, "-[%rdi ");
3174             else if (Arch == Triple::aarch64)
3175               strcpy(method, "-[x0 ");
3176             else
3177               strcpy(method, "-[r? ");
3178             strcat(method, info->selector_name);
3179             strcat(method, "]");
3180             *ReferenceName = method;
3181             *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3182           }
3183         }
3184         info->class_name = nullptr;
3185       }
3186     } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
3187       if (info->selector_name != nullptr) {
3188         info->method =
3189             std::make_unique<char[]>(17 + strlen(info->selector_name));
3190         char *method = info->method.get();
3191         if (method != nullptr) {
3192           if (Arch == Triple::x86_64)
3193             strcpy(method, "-[[%rdi super] ");
3194           else if (Arch == Triple::aarch64)
3195             strcpy(method, "-[[x0 super] ");
3196           else
3197             strcpy(method, "-[[r? super] ");
3198           strcat(method, info->selector_name);
3199           strcat(method, "]");
3200           *ReferenceName = method;
3201           *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3202         }
3203         info->class_name = nullptr;
3204       }
3205     }
3206   }
3207 }
3208 
3209 // GuessPointerPointer() is passed the address of what might be a pointer to
3210 // a reference to an Objective-C class, selector, message ref or cfstring.
3211 // If so the value of the pointer is returned and one of the booleans are set
3212 // to true.  If not zero is returned and all the booleans are set to false.
3213 static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
3214                                     struct DisassembleInfo *info,
3215                                     bool &classref, bool &selref, bool &msgref,
3216                                     bool &cfstring) {
3217   classref = false;
3218   selref = false;
3219   msgref = false;
3220   cfstring = false;
3221   for (const auto &Load : info->O->load_commands()) {
3222     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
3223       MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
3224       for (unsigned J = 0; J < Seg.nsects; ++J) {
3225         MachO::section_64 Sec = info->O->getSection64(Load, J);
3226         if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
3227              strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
3228              strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
3229              strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
3230              strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
3231             ReferenceValue >= Sec.addr &&
3232             ReferenceValue < Sec.addr + Sec.size) {
3233           uint64_t sect_offset = ReferenceValue - Sec.addr;
3234           uint64_t object_offset = Sec.offset + sect_offset;
3235           StringRef MachOContents = info->O->getData();
3236           uint64_t object_size = MachOContents.size();
3237           const char *object_addr = (const char *)MachOContents.data();
3238           if (object_offset < object_size) {
3239             uint64_t pointer_value;
3240             memcpy(&pointer_value, object_addr + object_offset,
3241                    sizeof(uint64_t));
3242             if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3243               sys::swapByteOrder(pointer_value);
3244             if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
3245               selref = true;
3246             else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
3247                      strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
3248               classref = true;
3249             else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
3250                      ReferenceValue + 8 < Sec.addr + Sec.size) {
3251               msgref = true;
3252               memcpy(&pointer_value, object_addr + object_offset + 8,
3253                      sizeof(uint64_t));
3254               if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3255                 sys::swapByteOrder(pointer_value);
3256             } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
3257               cfstring = true;
3258             return pointer_value;
3259           } else {
3260             return 0;
3261           }
3262         }
3263       }
3264     }
3265     // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
3266   }
3267   return 0;
3268 }
3269 
3270 // get_pointer_64 returns a pointer to the bytes in the object file at the
3271 // Address from a section in the Mach-O file.  And indirectly returns the
3272 // offset into the section, number of bytes left in the section past the offset
3273 // and which section is was being referenced.  If the Address is not in a
3274 // section nullptr is returned.
3275 static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
3276                                   uint32_t &left, SectionRef &S,
3277                                   DisassembleInfo *info,
3278                                   bool objc_only = false) {
3279   offset = 0;
3280   left = 0;
3281   S = SectionRef();
3282   for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
3283     uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
3284     uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
3285     if (SectSize == 0)
3286       continue;
3287     if (objc_only) {
3288       StringRef SectName;
3289       Expected<StringRef> SecNameOrErr =
3290           ((*(info->Sections))[SectIdx]).getName();
3291       if (SecNameOrErr)
3292         SectName = *SecNameOrErr;
3293       else
3294         consumeError(SecNameOrErr.takeError());
3295 
3296       DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
3297       StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
3298       if (SegName != "__OBJC" && SectName != "__cstring")
3299         continue;
3300     }
3301     if (Address >= SectAddress && Address < SectAddress + SectSize) {
3302       S = (*(info->Sections))[SectIdx];
3303       offset = Address - SectAddress;
3304       left = SectSize - offset;
3305       StringRef SectContents = unwrapOrError(
3306           ((*(info->Sections))[SectIdx]).getContents(), info->O->getFileName());
3307       return SectContents.data() + offset;
3308     }
3309   }
3310   return nullptr;
3311 }
3312 
3313 static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
3314                                   uint32_t &left, SectionRef &S,
3315                                   DisassembleInfo *info,
3316                                   bool objc_only = false) {
3317   return get_pointer_64(Address, offset, left, S, info, objc_only);
3318 }
3319 
3320 // get_symbol_64() returns the name of a symbol (or nullptr) and the address of
3321 // the symbol indirectly through n_value. Based on the relocation information
3322 // for the specified section offset in the specified section reference.
3323 // If no relocation information is found and a non-zero ReferenceValue for the
3324 // symbol is passed, look up that address in the info's AddrMap.
3325 static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
3326                                  DisassembleInfo *info, uint64_t &n_value,
3327                                  uint64_t ReferenceValue = 0) {
3328   n_value = 0;
3329   if (!info->verbose)
3330     return nullptr;
3331 
3332   // See if there is an external relocation entry at the sect_offset.
3333   bool reloc_found = false;
3334   DataRefImpl Rel;
3335   MachO::any_relocation_info RE;
3336   bool isExtern = false;
3337   SymbolRef Symbol;
3338   for (const RelocationRef &Reloc : S.relocations()) {
3339     uint64_t RelocOffset = Reloc.getOffset();
3340     if (RelocOffset == sect_offset) {
3341       Rel = Reloc.getRawDataRefImpl();
3342       RE = info->O->getRelocation(Rel);
3343       if (info->O->isRelocationScattered(RE))
3344         continue;
3345       isExtern = info->O->getPlainRelocationExternal(RE);
3346       if (isExtern) {
3347         symbol_iterator RelocSym = Reloc.getSymbol();
3348         Symbol = *RelocSym;
3349       }
3350       reloc_found = true;
3351       break;
3352     }
3353   }
3354   // If there is an external relocation entry for a symbol in this section
3355   // at this section_offset then use that symbol's value for the n_value
3356   // and return its name.
3357   const char *SymbolName = nullptr;
3358   if (reloc_found && isExtern) {
3359     n_value = cantFail(Symbol.getValue());
3360     StringRef Name = unwrapOrError(Symbol.getName(), info->O->getFileName());
3361     if (!Name.empty()) {
3362       SymbolName = Name.data();
3363       return SymbolName;
3364     }
3365   }
3366 
3367   // TODO: For fully linked images, look through the external relocation
3368   // entries off the dynamic symtab command. For these the r_offset is from the
3369   // start of the first writeable segment in the Mach-O file.  So the offset
3370   // to this section from that segment is passed to this routine by the caller,
3371   // as the database_offset. Which is the difference of the section's starting
3372   // address and the first writable segment.
3373   //
3374   // NOTE: need add passing the database_offset to this routine.
3375 
3376   // We did not find an external relocation entry so look up the ReferenceValue
3377   // as an address of a symbol and if found return that symbol's name.
3378   SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
3379 
3380   return SymbolName;
3381 }
3382 
3383 static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
3384                                  DisassembleInfo *info,
3385                                  uint32_t ReferenceValue) {
3386   uint64_t n_value64;
3387   return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
3388 }
3389 
3390 namespace {
3391 
3392 // These are structs in the Objective-C meta data and read to produce the
3393 // comments for disassembly.  While these are part of the ABI they are no
3394 // public defintions.  So the are here not in include/llvm/BinaryFormat/MachO.h
3395 // .
3396 
3397 // The cfstring object in a 64-bit Mach-O file.
3398 struct cfstring64_t {
3399   uint64_t isa;        // class64_t * (64-bit pointer)
3400   uint64_t flags;      // flag bits
3401   uint64_t characters; // char * (64-bit pointer)
3402   uint64_t length;     // number of non-NULL characters in above
3403 };
3404 
3405 // The class object in a 64-bit Mach-O file.
3406 struct class64_t {
3407   uint64_t isa;        // class64_t * (64-bit pointer)
3408   uint64_t superclass; // class64_t * (64-bit pointer)
3409   uint64_t cache;      // Cache (64-bit pointer)
3410   uint64_t vtable;     // IMP * (64-bit pointer)
3411   uint64_t data;       // class_ro64_t * (64-bit pointer)
3412 };
3413 
3414 struct class32_t {
3415   uint32_t isa;        /* class32_t * (32-bit pointer) */
3416   uint32_t superclass; /* class32_t * (32-bit pointer) */
3417   uint32_t cache;      /* Cache (32-bit pointer) */
3418   uint32_t vtable;     /* IMP * (32-bit pointer) */
3419   uint32_t data;       /* class_ro32_t * (32-bit pointer) */
3420 };
3421 
3422 struct class_ro64_t {
3423   uint32_t flags;
3424   uint32_t instanceStart;
3425   uint32_t instanceSize;
3426   uint32_t reserved;
3427   uint64_t ivarLayout;     // const uint8_t * (64-bit pointer)
3428   uint64_t name;           // const char * (64-bit pointer)
3429   uint64_t baseMethods;    // const method_list_t * (64-bit pointer)
3430   uint64_t baseProtocols;  // const protocol_list_t * (64-bit pointer)
3431   uint64_t ivars;          // const ivar_list_t * (64-bit pointer)
3432   uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
3433   uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
3434 };
3435 
3436 struct class_ro32_t {
3437   uint32_t flags;
3438   uint32_t instanceStart;
3439   uint32_t instanceSize;
3440   uint32_t ivarLayout;     /* const uint8_t * (32-bit pointer) */
3441   uint32_t name;           /* const char * (32-bit pointer) */
3442   uint32_t baseMethods;    /* const method_list_t * (32-bit pointer) */
3443   uint32_t baseProtocols;  /* const protocol_list_t * (32-bit pointer) */
3444   uint32_t ivars;          /* const ivar_list_t * (32-bit pointer) */
3445   uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
3446   uint32_t baseProperties; /* const struct objc_property_list *
3447                                                    (32-bit pointer) */
3448 };
3449 
3450 /* Values for class_ro{64,32}_t->flags */
3451 #define RO_META (1 << 0)
3452 #define RO_ROOT (1 << 1)
3453 #define RO_HAS_CXX_STRUCTORS (1 << 2)
3454 
3455 struct method_list64_t {
3456   uint32_t entsize;
3457   uint32_t count;
3458   /* struct method64_t first;  These structures follow inline */
3459 };
3460 
3461 struct method_list32_t {
3462   uint32_t entsize;
3463   uint32_t count;
3464   /* struct method32_t first;  These structures follow inline */
3465 };
3466 
3467 struct method64_t {
3468   uint64_t name;  /* SEL (64-bit pointer) */
3469   uint64_t types; /* const char * (64-bit pointer) */
3470   uint64_t imp;   /* IMP (64-bit pointer) */
3471 };
3472 
3473 struct method32_t {
3474   uint32_t name;  /* SEL (32-bit pointer) */
3475   uint32_t types; /* const char * (32-bit pointer) */
3476   uint32_t imp;   /* IMP (32-bit pointer) */
3477 };
3478 
3479 struct protocol_list64_t {
3480   uint64_t count; /* uintptr_t (a 64-bit value) */
3481   /* struct protocol64_t * list[0];  These pointers follow inline */
3482 };
3483 
3484 struct protocol_list32_t {
3485   uint32_t count; /* uintptr_t (a 32-bit value) */
3486   /* struct protocol32_t * list[0];  These pointers follow inline */
3487 };
3488 
3489 struct protocol64_t {
3490   uint64_t isa;                     /* id * (64-bit pointer) */
3491   uint64_t name;                    /* const char * (64-bit pointer) */
3492   uint64_t protocols;               /* struct protocol_list64_t *
3493                                                     (64-bit pointer) */
3494   uint64_t instanceMethods;         /* method_list_t * (64-bit pointer) */
3495   uint64_t classMethods;            /* method_list_t * (64-bit pointer) */
3496   uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
3497   uint64_t optionalClassMethods;    /* method_list_t * (64-bit pointer) */
3498   uint64_t instanceProperties;      /* struct objc_property_list *
3499                                                        (64-bit pointer) */
3500 };
3501 
3502 struct protocol32_t {
3503   uint32_t isa;                     /* id * (32-bit pointer) */
3504   uint32_t name;                    /* const char * (32-bit pointer) */
3505   uint32_t protocols;               /* struct protocol_list_t *
3506                                                     (32-bit pointer) */
3507   uint32_t instanceMethods;         /* method_list_t * (32-bit pointer) */
3508   uint32_t classMethods;            /* method_list_t * (32-bit pointer) */
3509   uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
3510   uint32_t optionalClassMethods;    /* method_list_t * (32-bit pointer) */
3511   uint32_t instanceProperties;      /* struct objc_property_list *
3512                                                        (32-bit pointer) */
3513 };
3514 
3515 struct ivar_list64_t {
3516   uint32_t entsize;
3517   uint32_t count;
3518   /* struct ivar64_t first;  These structures follow inline */
3519 };
3520 
3521 struct ivar_list32_t {
3522   uint32_t entsize;
3523   uint32_t count;
3524   /* struct ivar32_t first;  These structures follow inline */
3525 };
3526 
3527 struct ivar64_t {
3528   uint64_t offset; /* uintptr_t * (64-bit pointer) */
3529   uint64_t name;   /* const char * (64-bit pointer) */
3530   uint64_t type;   /* const char * (64-bit pointer) */
3531   uint32_t alignment;
3532   uint32_t size;
3533 };
3534 
3535 struct ivar32_t {
3536   uint32_t offset; /* uintptr_t * (32-bit pointer) */
3537   uint32_t name;   /* const char * (32-bit pointer) */
3538   uint32_t type;   /* const char * (32-bit pointer) */
3539   uint32_t alignment;
3540   uint32_t size;
3541 };
3542 
3543 struct objc_property_list64 {
3544   uint32_t entsize;
3545   uint32_t count;
3546   /* struct objc_property64 first;  These structures follow inline */
3547 };
3548 
3549 struct objc_property_list32 {
3550   uint32_t entsize;
3551   uint32_t count;
3552   /* struct objc_property32 first;  These structures follow inline */
3553 };
3554 
3555 struct objc_property64 {
3556   uint64_t name;       /* const char * (64-bit pointer) */
3557   uint64_t attributes; /* const char * (64-bit pointer) */
3558 };
3559 
3560 struct objc_property32 {
3561   uint32_t name;       /* const char * (32-bit pointer) */
3562   uint32_t attributes; /* const char * (32-bit pointer) */
3563 };
3564 
3565 struct category64_t {
3566   uint64_t name;               /* const char * (64-bit pointer) */
3567   uint64_t cls;                /* struct class_t * (64-bit pointer) */
3568   uint64_t instanceMethods;    /* struct method_list_t * (64-bit pointer) */
3569   uint64_t classMethods;       /* struct method_list_t * (64-bit pointer) */
3570   uint64_t protocols;          /* struct protocol_list_t * (64-bit pointer) */
3571   uint64_t instanceProperties; /* struct objc_property_list *
3572                                   (64-bit pointer) */
3573 };
3574 
3575 struct category32_t {
3576   uint32_t name;               /* const char * (32-bit pointer) */
3577   uint32_t cls;                /* struct class_t * (32-bit pointer) */
3578   uint32_t instanceMethods;    /* struct method_list_t * (32-bit pointer) */
3579   uint32_t classMethods;       /* struct method_list_t * (32-bit pointer) */
3580   uint32_t protocols;          /* struct protocol_list_t * (32-bit pointer) */
3581   uint32_t instanceProperties; /* struct objc_property_list *
3582                                   (32-bit pointer) */
3583 };
3584 
3585 struct objc_image_info64 {
3586   uint32_t version;
3587   uint32_t flags;
3588 };
3589 struct objc_image_info32 {
3590   uint32_t version;
3591   uint32_t flags;
3592 };
3593 struct imageInfo_t {
3594   uint32_t version;
3595   uint32_t flags;
3596 };
3597 /* masks for objc_image_info.flags */
3598 #define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
3599 #define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
3600 #define OBJC_IMAGE_IS_SIMULATED (1 << 5)
3601 #define OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES (1 << 6)
3602 
3603 struct message_ref64 {
3604   uint64_t imp; /* IMP (64-bit pointer) */
3605   uint64_t sel; /* SEL (64-bit pointer) */
3606 };
3607 
3608 struct message_ref32 {
3609   uint32_t imp; /* IMP (32-bit pointer) */
3610   uint32_t sel; /* SEL (32-bit pointer) */
3611 };
3612 
3613 // Objective-C 1 (32-bit only) meta data structs.
3614 
3615 struct objc_module_t {
3616   uint32_t version;
3617   uint32_t size;
3618   uint32_t name;   /* char * (32-bit pointer) */
3619   uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
3620 };
3621 
3622 struct objc_symtab_t {
3623   uint32_t sel_ref_cnt;
3624   uint32_t refs; /* SEL * (32-bit pointer) */
3625   uint16_t cls_def_cnt;
3626   uint16_t cat_def_cnt;
3627   // uint32_t defs[1];        /* void * (32-bit pointer) variable size */
3628 };
3629 
3630 struct objc_class_t {
3631   uint32_t isa;         /* struct objc_class * (32-bit pointer) */
3632   uint32_t super_class; /* struct objc_class * (32-bit pointer) */
3633   uint32_t name;        /* const char * (32-bit pointer) */
3634   int32_t version;
3635   int32_t info;
3636   int32_t instance_size;
3637   uint32_t ivars;       /* struct objc_ivar_list * (32-bit pointer) */
3638   uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
3639   uint32_t cache;       /* struct objc_cache * (32-bit pointer) */
3640   uint32_t protocols;   /* struct objc_protocol_list * (32-bit pointer) */
3641 };
3642 
3643 #define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
3644 // class is not a metaclass
3645 #define CLS_CLASS 0x1
3646 // class is a metaclass
3647 #define CLS_META 0x2
3648 
3649 struct objc_category_t {
3650   uint32_t category_name;    /* char * (32-bit pointer) */
3651   uint32_t class_name;       /* char * (32-bit pointer) */
3652   uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
3653   uint32_t class_methods;    /* struct objc_method_list * (32-bit pointer) */
3654   uint32_t protocols;        /* struct objc_protocol_list * (32-bit ptr) */
3655 };
3656 
3657 struct objc_ivar_t {
3658   uint32_t ivar_name; /* char * (32-bit pointer) */
3659   uint32_t ivar_type; /* char * (32-bit pointer) */
3660   int32_t ivar_offset;
3661 };
3662 
3663 struct objc_ivar_list_t {
3664   int32_t ivar_count;
3665   // struct objc_ivar_t ivar_list[1];          /* variable length structure */
3666 };
3667 
3668 struct objc_method_list_t {
3669   uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
3670   int32_t method_count;
3671   // struct objc_method_t method_list[1];      /* variable length structure */
3672 };
3673 
3674 struct objc_method_t {
3675   uint32_t method_name;  /* SEL, aka struct objc_selector * (32-bit pointer) */
3676   uint32_t method_types; /* char * (32-bit pointer) */
3677   uint32_t method_imp;   /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
3678                             (32-bit pointer) */
3679 };
3680 
3681 struct objc_protocol_list_t {
3682   uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
3683   int32_t count;
3684   // uint32_t list[1];   /* Protocol *, aka struct objc_protocol_t *
3685   //                        (32-bit pointer) */
3686 };
3687 
3688 struct objc_protocol_t {
3689   uint32_t isa;              /* struct objc_class * (32-bit pointer) */
3690   uint32_t protocol_name;    /* char * (32-bit pointer) */
3691   uint32_t protocol_list;    /* struct objc_protocol_list * (32-bit pointer) */
3692   uint32_t instance_methods; /* struct objc_method_description_list *
3693                                 (32-bit pointer) */
3694   uint32_t class_methods;    /* struct objc_method_description_list *
3695                                 (32-bit pointer) */
3696 };
3697 
3698 struct objc_method_description_list_t {
3699   int32_t count;
3700   // struct objc_method_description_t list[1];
3701 };
3702 
3703 struct objc_method_description_t {
3704   uint32_t name;  /* SEL, aka struct objc_selector * (32-bit pointer) */
3705   uint32_t types; /* char * (32-bit pointer) */
3706 };
3707 
3708 inline void swapStruct(struct cfstring64_t &cfs) {
3709   sys::swapByteOrder(cfs.isa);
3710   sys::swapByteOrder(cfs.flags);
3711   sys::swapByteOrder(cfs.characters);
3712   sys::swapByteOrder(cfs.length);
3713 }
3714 
3715 inline void swapStruct(struct class64_t &c) {
3716   sys::swapByteOrder(c.isa);
3717   sys::swapByteOrder(c.superclass);
3718   sys::swapByteOrder(c.cache);
3719   sys::swapByteOrder(c.vtable);
3720   sys::swapByteOrder(c.data);
3721 }
3722 
3723 inline void swapStruct(struct class32_t &c) {
3724   sys::swapByteOrder(c.isa);
3725   sys::swapByteOrder(c.superclass);
3726   sys::swapByteOrder(c.cache);
3727   sys::swapByteOrder(c.vtable);
3728   sys::swapByteOrder(c.data);
3729 }
3730 
3731 inline void swapStruct(struct class_ro64_t &cro) {
3732   sys::swapByteOrder(cro.flags);
3733   sys::swapByteOrder(cro.instanceStart);
3734   sys::swapByteOrder(cro.instanceSize);
3735   sys::swapByteOrder(cro.reserved);
3736   sys::swapByteOrder(cro.ivarLayout);
3737   sys::swapByteOrder(cro.name);
3738   sys::swapByteOrder(cro.baseMethods);
3739   sys::swapByteOrder(cro.baseProtocols);
3740   sys::swapByteOrder(cro.ivars);
3741   sys::swapByteOrder(cro.weakIvarLayout);
3742   sys::swapByteOrder(cro.baseProperties);
3743 }
3744 
3745 inline void swapStruct(struct class_ro32_t &cro) {
3746   sys::swapByteOrder(cro.flags);
3747   sys::swapByteOrder(cro.instanceStart);
3748   sys::swapByteOrder(cro.instanceSize);
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 method_list64_t &ml) {
3759   sys::swapByteOrder(ml.entsize);
3760   sys::swapByteOrder(ml.count);
3761 }
3762 
3763 inline void swapStruct(struct method_list32_t &ml) {
3764   sys::swapByteOrder(ml.entsize);
3765   sys::swapByteOrder(ml.count);
3766 }
3767 
3768 inline void swapStruct(struct method64_t &m) {
3769   sys::swapByteOrder(m.name);
3770   sys::swapByteOrder(m.types);
3771   sys::swapByteOrder(m.imp);
3772 }
3773 
3774 inline void swapStruct(struct method32_t &m) {
3775   sys::swapByteOrder(m.name);
3776   sys::swapByteOrder(m.types);
3777   sys::swapByteOrder(m.imp);
3778 }
3779 
3780 inline void swapStruct(struct protocol_list64_t &pl) {
3781   sys::swapByteOrder(pl.count);
3782 }
3783 
3784 inline void swapStruct(struct protocol_list32_t &pl) {
3785   sys::swapByteOrder(pl.count);
3786 }
3787 
3788 inline void swapStruct(struct protocol64_t &p) {
3789   sys::swapByteOrder(p.isa);
3790   sys::swapByteOrder(p.name);
3791   sys::swapByteOrder(p.protocols);
3792   sys::swapByteOrder(p.instanceMethods);
3793   sys::swapByteOrder(p.classMethods);
3794   sys::swapByteOrder(p.optionalInstanceMethods);
3795   sys::swapByteOrder(p.optionalClassMethods);
3796   sys::swapByteOrder(p.instanceProperties);
3797 }
3798 
3799 inline void swapStruct(struct protocol32_t &p) {
3800   sys::swapByteOrder(p.isa);
3801   sys::swapByteOrder(p.name);
3802   sys::swapByteOrder(p.protocols);
3803   sys::swapByteOrder(p.instanceMethods);
3804   sys::swapByteOrder(p.classMethods);
3805   sys::swapByteOrder(p.optionalInstanceMethods);
3806   sys::swapByteOrder(p.optionalClassMethods);
3807   sys::swapByteOrder(p.instanceProperties);
3808 }
3809 
3810 inline void swapStruct(struct ivar_list64_t &il) {
3811   sys::swapByteOrder(il.entsize);
3812   sys::swapByteOrder(il.count);
3813 }
3814 
3815 inline void swapStruct(struct ivar_list32_t &il) {
3816   sys::swapByteOrder(il.entsize);
3817   sys::swapByteOrder(il.count);
3818 }
3819 
3820 inline void swapStruct(struct ivar64_t &i) {
3821   sys::swapByteOrder(i.offset);
3822   sys::swapByteOrder(i.name);
3823   sys::swapByteOrder(i.type);
3824   sys::swapByteOrder(i.alignment);
3825   sys::swapByteOrder(i.size);
3826 }
3827 
3828 inline void swapStruct(struct ivar32_t &i) {
3829   sys::swapByteOrder(i.offset);
3830   sys::swapByteOrder(i.name);
3831   sys::swapByteOrder(i.type);
3832   sys::swapByteOrder(i.alignment);
3833   sys::swapByteOrder(i.size);
3834 }
3835 
3836 inline void swapStruct(struct objc_property_list64 &pl) {
3837   sys::swapByteOrder(pl.entsize);
3838   sys::swapByteOrder(pl.count);
3839 }
3840 
3841 inline void swapStruct(struct objc_property_list32 &pl) {
3842   sys::swapByteOrder(pl.entsize);
3843   sys::swapByteOrder(pl.count);
3844 }
3845 
3846 inline void swapStruct(struct objc_property64 &op) {
3847   sys::swapByteOrder(op.name);
3848   sys::swapByteOrder(op.attributes);
3849 }
3850 
3851 inline void swapStruct(struct objc_property32 &op) {
3852   sys::swapByteOrder(op.name);
3853   sys::swapByteOrder(op.attributes);
3854 }
3855 
3856 inline void swapStruct(struct category64_t &c) {
3857   sys::swapByteOrder(c.name);
3858   sys::swapByteOrder(c.cls);
3859   sys::swapByteOrder(c.instanceMethods);
3860   sys::swapByteOrder(c.classMethods);
3861   sys::swapByteOrder(c.protocols);
3862   sys::swapByteOrder(c.instanceProperties);
3863 }
3864 
3865 inline void swapStruct(struct category32_t &c) {
3866   sys::swapByteOrder(c.name);
3867   sys::swapByteOrder(c.cls);
3868   sys::swapByteOrder(c.instanceMethods);
3869   sys::swapByteOrder(c.classMethods);
3870   sys::swapByteOrder(c.protocols);
3871   sys::swapByteOrder(c.instanceProperties);
3872 }
3873 
3874 inline void swapStruct(struct objc_image_info64 &o) {
3875   sys::swapByteOrder(o.version);
3876   sys::swapByteOrder(o.flags);
3877 }
3878 
3879 inline void swapStruct(struct objc_image_info32 &o) {
3880   sys::swapByteOrder(o.version);
3881   sys::swapByteOrder(o.flags);
3882 }
3883 
3884 inline void swapStruct(struct imageInfo_t &o) {
3885   sys::swapByteOrder(o.version);
3886   sys::swapByteOrder(o.flags);
3887 }
3888 
3889 inline void swapStruct(struct message_ref64 &mr) {
3890   sys::swapByteOrder(mr.imp);
3891   sys::swapByteOrder(mr.sel);
3892 }
3893 
3894 inline void swapStruct(struct message_ref32 &mr) {
3895   sys::swapByteOrder(mr.imp);
3896   sys::swapByteOrder(mr.sel);
3897 }
3898 
3899 inline void swapStruct(struct objc_module_t &module) {
3900   sys::swapByteOrder(module.version);
3901   sys::swapByteOrder(module.size);
3902   sys::swapByteOrder(module.name);
3903   sys::swapByteOrder(module.symtab);
3904 }
3905 
3906 inline void swapStruct(struct objc_symtab_t &symtab) {
3907   sys::swapByteOrder(symtab.sel_ref_cnt);
3908   sys::swapByteOrder(symtab.refs);
3909   sys::swapByteOrder(symtab.cls_def_cnt);
3910   sys::swapByteOrder(symtab.cat_def_cnt);
3911 }
3912 
3913 inline void swapStruct(struct objc_class_t &objc_class) {
3914   sys::swapByteOrder(objc_class.isa);
3915   sys::swapByteOrder(objc_class.super_class);
3916   sys::swapByteOrder(objc_class.name);
3917   sys::swapByteOrder(objc_class.version);
3918   sys::swapByteOrder(objc_class.info);
3919   sys::swapByteOrder(objc_class.instance_size);
3920   sys::swapByteOrder(objc_class.ivars);
3921   sys::swapByteOrder(objc_class.methodLists);
3922   sys::swapByteOrder(objc_class.cache);
3923   sys::swapByteOrder(objc_class.protocols);
3924 }
3925 
3926 inline void swapStruct(struct objc_category_t &objc_category) {
3927   sys::swapByteOrder(objc_category.category_name);
3928   sys::swapByteOrder(objc_category.class_name);
3929   sys::swapByteOrder(objc_category.instance_methods);
3930   sys::swapByteOrder(objc_category.class_methods);
3931   sys::swapByteOrder(objc_category.protocols);
3932 }
3933 
3934 inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3935   sys::swapByteOrder(objc_ivar_list.ivar_count);
3936 }
3937 
3938 inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3939   sys::swapByteOrder(objc_ivar.ivar_name);
3940   sys::swapByteOrder(objc_ivar.ivar_type);
3941   sys::swapByteOrder(objc_ivar.ivar_offset);
3942 }
3943 
3944 inline void swapStruct(struct objc_method_list_t &method_list) {
3945   sys::swapByteOrder(method_list.obsolete);
3946   sys::swapByteOrder(method_list.method_count);
3947 }
3948 
3949 inline void swapStruct(struct objc_method_t &method) {
3950   sys::swapByteOrder(method.method_name);
3951   sys::swapByteOrder(method.method_types);
3952   sys::swapByteOrder(method.method_imp);
3953 }
3954 
3955 inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3956   sys::swapByteOrder(protocol_list.next);
3957   sys::swapByteOrder(protocol_list.count);
3958 }
3959 
3960 inline void swapStruct(struct objc_protocol_t &protocol) {
3961   sys::swapByteOrder(protocol.isa);
3962   sys::swapByteOrder(protocol.protocol_name);
3963   sys::swapByteOrder(protocol.protocol_list);
3964   sys::swapByteOrder(protocol.instance_methods);
3965   sys::swapByteOrder(protocol.class_methods);
3966 }
3967 
3968 inline void swapStruct(struct objc_method_description_list_t &mdl) {
3969   sys::swapByteOrder(mdl.count);
3970 }
3971 
3972 inline void swapStruct(struct objc_method_description_t &md) {
3973   sys::swapByteOrder(md.name);
3974   sys::swapByteOrder(md.types);
3975 }
3976 
3977 } // namespace
3978 
3979 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3980                                                  struct DisassembleInfo *info);
3981 
3982 // get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3983 // to an Objective-C class and returns the class name.  It is also passed the
3984 // address of the pointer, so when the pointer is zero as it can be in an .o
3985 // file, that is used to look for an external relocation entry with a symbol
3986 // name.
3987 static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3988                                               uint64_t ReferenceValue,
3989                                               struct DisassembleInfo *info) {
3990   const char *r;
3991   uint32_t offset, left;
3992   SectionRef S;
3993 
3994   // The pointer_value can be 0 in an object file and have a relocation
3995   // entry for the class symbol at the ReferenceValue (the address of the
3996   // pointer).
3997   if (pointer_value == 0) {
3998     r = get_pointer_64(ReferenceValue, offset, left, S, info);
3999     if (r == nullptr || left < sizeof(uint64_t))
4000       return nullptr;
4001     uint64_t n_value;
4002     const char *symbol_name = get_symbol_64(offset, S, info, n_value);
4003     if (symbol_name == nullptr)
4004       return nullptr;
4005     const char *class_name = strrchr(symbol_name, '$');
4006     if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
4007       return class_name + 2;
4008     else
4009       return nullptr;
4010   }
4011 
4012   // The case were the pointer_value is non-zero and points to a class defined
4013   // in this Mach-O file.
4014   r = get_pointer_64(pointer_value, offset, left, S, info);
4015   if (r == nullptr || left < sizeof(struct class64_t))
4016     return nullptr;
4017   struct class64_t c;
4018   memcpy(&c, r, sizeof(struct class64_t));
4019   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4020     swapStruct(c);
4021   if (c.data == 0)
4022     return nullptr;
4023   r = get_pointer_64(c.data, offset, left, S, info);
4024   if (r == nullptr || left < sizeof(struct class_ro64_t))
4025     return nullptr;
4026   struct class_ro64_t cro;
4027   memcpy(&cro, r, sizeof(struct class_ro64_t));
4028   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4029     swapStruct(cro);
4030   if (cro.name == 0)
4031     return nullptr;
4032   const char *name = get_pointer_64(cro.name, offset, left, S, info);
4033   return name;
4034 }
4035 
4036 // get_objc2_64bit_cfstring_name is used for disassembly and is passed a
4037 // pointer to a cfstring and returns its name or nullptr.
4038 static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
4039                                                  struct DisassembleInfo *info) {
4040   const char *r, *name;
4041   uint32_t offset, left;
4042   SectionRef S;
4043   struct cfstring64_t cfs;
4044   uint64_t cfs_characters;
4045 
4046   r = get_pointer_64(ReferenceValue, offset, left, S, info);
4047   if (r == nullptr || left < sizeof(struct cfstring64_t))
4048     return nullptr;
4049   memcpy(&cfs, r, sizeof(struct cfstring64_t));
4050   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4051     swapStruct(cfs);
4052   if (cfs.characters == 0) {
4053     uint64_t n_value;
4054     const char *symbol_name = get_symbol_64(
4055         offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
4056     if (symbol_name == nullptr)
4057       return nullptr;
4058     cfs_characters = n_value;
4059   } else
4060     cfs_characters = cfs.characters;
4061   name = get_pointer_64(cfs_characters, offset, left, S, info);
4062 
4063   return name;
4064 }
4065 
4066 // get_objc2_64bit_selref() is used for disassembly and is passed a the address
4067 // of a pointer to an Objective-C selector reference when the pointer value is
4068 // zero as in a .o file and is likely to have a external relocation entry with
4069 // who's symbol's n_value is the real pointer to the selector name.  If that is
4070 // the case the real pointer to the selector name is returned else 0 is
4071 // returned
4072 static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
4073                                        struct DisassembleInfo *info) {
4074   uint32_t offset, left;
4075   SectionRef S;
4076 
4077   const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
4078   if (r == nullptr || left < sizeof(uint64_t))
4079     return 0;
4080   uint64_t n_value;
4081   const char *symbol_name = get_symbol_64(offset, S, info, n_value);
4082   if (symbol_name == nullptr)
4083     return 0;
4084   return n_value;
4085 }
4086 
4087 static const SectionRef get_section(MachOObjectFile *O, const char *segname,
4088                                     const char *sectname) {
4089   for (const SectionRef &Section : O->sections()) {
4090     StringRef SectName;
4091     Expected<StringRef> SecNameOrErr = Section.getName();
4092     if (SecNameOrErr)
4093       SectName = *SecNameOrErr;
4094     else
4095       consumeError(SecNameOrErr.takeError());
4096 
4097     DataRefImpl Ref = Section.getRawDataRefImpl();
4098     StringRef SegName = O->getSectionFinalSegmentName(Ref);
4099     if (SegName == segname && SectName == sectname)
4100       return Section;
4101   }
4102   return SectionRef();
4103 }
4104 
4105 static void
4106 walk_pointer_list_64(const char *listname, const SectionRef S,
4107                      MachOObjectFile *O, struct DisassembleInfo *info,
4108                      void (*func)(uint64_t, struct DisassembleInfo *info)) {
4109   if (S == SectionRef())
4110     return;
4111 
4112   StringRef SectName;
4113   Expected<StringRef> SecNameOrErr = S.getName();
4114   if (SecNameOrErr)
4115     SectName = *SecNameOrErr;
4116   else
4117     consumeError(SecNameOrErr.takeError());
4118 
4119   DataRefImpl Ref = S.getRawDataRefImpl();
4120   StringRef SegName = O->getSectionFinalSegmentName(Ref);
4121   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4122 
4123   StringRef BytesStr = unwrapOrError(S.getContents(), O->getFileName());
4124   const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
4125 
4126   for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
4127     uint32_t left = S.getSize() - i;
4128     uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
4129     uint64_t p = 0;
4130     memcpy(&p, Contents + i, size);
4131     if (i + sizeof(uint64_t) > S.getSize())
4132       outs() << listname << " list pointer extends past end of (" << SegName
4133              << "," << SectName << ") section\n";
4134     outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
4135 
4136     if (O->isLittleEndian() != sys::IsLittleEndianHost)
4137       sys::swapByteOrder(p);
4138 
4139     uint64_t n_value = 0;
4140     const char *name = get_symbol_64(i, S, info, n_value, p);
4141     if (name == nullptr)
4142       name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
4143 
4144     if (n_value != 0) {
4145       outs() << format("0x%" PRIx64, n_value);
4146       if (p != 0)
4147         outs() << " + " << format("0x%" PRIx64, p);
4148     } else
4149       outs() << format("0x%" PRIx64, p);
4150     if (name != nullptr)
4151       outs() << " " << name;
4152     outs() << "\n";
4153 
4154     p += n_value;
4155     if (func)
4156       func(p, info);
4157   }
4158 }
4159 
4160 static void
4161 walk_pointer_list_32(const char *listname, const SectionRef S,
4162                      MachOObjectFile *O, struct DisassembleInfo *info,
4163                      void (*func)(uint32_t, struct DisassembleInfo *info)) {
4164   if (S == SectionRef())
4165     return;
4166 
4167   StringRef SectName = unwrapOrError(S.getName(), O->getFileName());
4168   DataRefImpl Ref = S.getRawDataRefImpl();
4169   StringRef SegName = O->getSectionFinalSegmentName(Ref);
4170   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4171 
4172   StringRef BytesStr = unwrapOrError(S.getContents(), O->getFileName());
4173   const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
4174 
4175   for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
4176     uint32_t left = S.getSize() - i;
4177     uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
4178     uint32_t p = 0;
4179     memcpy(&p, Contents + i, size);
4180     if (i + sizeof(uint32_t) > S.getSize())
4181       outs() << listname << " list pointer extends past end of (" << SegName
4182              << "," << SectName << ") section\n";
4183     uint32_t Address = S.getAddress() + i;
4184     outs() << format("%08" PRIx32, Address) << " ";
4185 
4186     if (O->isLittleEndian() != sys::IsLittleEndianHost)
4187       sys::swapByteOrder(p);
4188     outs() << format("0x%" PRIx32, p);
4189 
4190     const char *name = get_symbol_32(i, S, info, p);
4191     if (name != nullptr)
4192       outs() << " " << name;
4193     outs() << "\n";
4194 
4195     if (func)
4196       func(p, info);
4197   }
4198 }
4199 
4200 static void print_layout_map(const char *layout_map, uint32_t left) {
4201   if (layout_map == nullptr)
4202     return;
4203   outs() << "                layout map: ";
4204   do {
4205     outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
4206     left--;
4207     layout_map++;
4208   } while (*layout_map != '\0' && left != 0);
4209   outs() << "\n";
4210 }
4211 
4212 static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
4213   uint32_t offset, left;
4214   SectionRef S;
4215   const char *layout_map;
4216 
4217   if (p == 0)
4218     return;
4219   layout_map = get_pointer_64(p, offset, left, S, info);
4220   print_layout_map(layout_map, left);
4221 }
4222 
4223 static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
4224   uint32_t offset, left;
4225   SectionRef S;
4226   const char *layout_map;
4227 
4228   if (p == 0)
4229     return;
4230   layout_map = get_pointer_32(p, offset, left, S, info);
4231   print_layout_map(layout_map, left);
4232 }
4233 
4234 static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
4235                                   const char *indent) {
4236   struct method_list64_t ml;
4237   struct method64_t m;
4238   const char *r;
4239   uint32_t offset, xoffset, left, i;
4240   SectionRef S, xS;
4241   const char *name, *sym_name;
4242   uint64_t n_value;
4243 
4244   r = get_pointer_64(p, offset, left, S, info);
4245   if (r == nullptr)
4246     return;
4247   memset(&ml, '\0', sizeof(struct method_list64_t));
4248   if (left < sizeof(struct method_list64_t)) {
4249     memcpy(&ml, r, left);
4250     outs() << "   (method_list_t entends past the end of the section)\n";
4251   } else
4252     memcpy(&ml, r, sizeof(struct method_list64_t));
4253   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4254     swapStruct(ml);
4255   outs() << indent << "\t\t   entsize " << ml.entsize << "\n";
4256   outs() << indent << "\t\t     count " << ml.count << "\n";
4257 
4258   p += sizeof(struct method_list64_t);
4259   offset += sizeof(struct method_list64_t);
4260   for (i = 0; i < ml.count; i++) {
4261     r = get_pointer_64(p, offset, left, S, info);
4262     if (r == nullptr)
4263       return;
4264     memset(&m, '\0', sizeof(struct method64_t));
4265     if (left < sizeof(struct method64_t)) {
4266       memcpy(&m, r, left);
4267       outs() << indent << "   (method_t extends past the end of the section)\n";
4268     } else
4269       memcpy(&m, r, sizeof(struct method64_t));
4270     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4271       swapStruct(m);
4272 
4273     outs() << indent << "\t\t      name ";
4274     sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
4275                              info, n_value, m.name);
4276     if (n_value != 0) {
4277       if (info->verbose && sym_name != nullptr)
4278         outs() << sym_name;
4279       else
4280         outs() << format("0x%" PRIx64, n_value);
4281       if (m.name != 0)
4282         outs() << " + " << format("0x%" PRIx64, m.name);
4283     } else
4284       outs() << format("0x%" PRIx64, m.name);
4285     name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
4286     if (name != nullptr)
4287       outs() << format(" %.*s", left, name);
4288     outs() << "\n";
4289 
4290     outs() << indent << "\t\t     types ";
4291     sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
4292                              info, n_value, m.types);
4293     if (n_value != 0) {
4294       if (info->verbose && sym_name != nullptr)
4295         outs() << sym_name;
4296       else
4297         outs() << format("0x%" PRIx64, n_value);
4298       if (m.types != 0)
4299         outs() << " + " << format("0x%" PRIx64, m.types);
4300     } else
4301       outs() << format("0x%" PRIx64, m.types);
4302     name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
4303     if (name != nullptr)
4304       outs() << format(" %.*s", left, name);
4305     outs() << "\n";
4306 
4307     outs() << indent << "\t\t       imp ";
4308     name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
4309                          n_value, m.imp);
4310     if (info->verbose && name == nullptr) {
4311       if (n_value != 0) {
4312         outs() << format("0x%" PRIx64, n_value) << " ";
4313         if (m.imp != 0)
4314           outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
4315       } else
4316         outs() << format("0x%" PRIx64, m.imp) << " ";
4317     }
4318     if (name != nullptr)
4319       outs() << name;
4320     outs() << "\n";
4321 
4322     p += sizeof(struct method64_t);
4323     offset += sizeof(struct method64_t);
4324   }
4325 }
4326 
4327 static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
4328                                   const char *indent) {
4329   struct method_list32_t ml;
4330   struct method32_t m;
4331   const char *r, *name;
4332   uint32_t offset, xoffset, left, i;
4333   SectionRef S, xS;
4334 
4335   r = get_pointer_32(p, offset, left, S, info);
4336   if (r == nullptr)
4337     return;
4338   memset(&ml, '\0', sizeof(struct method_list32_t));
4339   if (left < sizeof(struct method_list32_t)) {
4340     memcpy(&ml, r, left);
4341     outs() << "   (method_list_t entends past the end of the section)\n";
4342   } else
4343     memcpy(&ml, r, sizeof(struct method_list32_t));
4344   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4345     swapStruct(ml);
4346   outs() << indent << "\t\t   entsize " << ml.entsize << "\n";
4347   outs() << indent << "\t\t     count " << ml.count << "\n";
4348 
4349   p += sizeof(struct method_list32_t);
4350   offset += sizeof(struct method_list32_t);
4351   for (i = 0; i < ml.count; i++) {
4352     r = get_pointer_32(p, offset, left, S, info);
4353     if (r == nullptr)
4354       return;
4355     memset(&m, '\0', sizeof(struct method32_t));
4356     if (left < sizeof(struct method32_t)) {
4357       memcpy(&ml, r, left);
4358       outs() << indent << "   (method_t entends past the end of the section)\n";
4359     } else
4360       memcpy(&m, r, sizeof(struct method32_t));
4361     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4362       swapStruct(m);
4363 
4364     outs() << indent << "\t\t      name " << format("0x%" PRIx32, m.name);
4365     name = get_pointer_32(m.name, xoffset, left, xS, info);
4366     if (name != nullptr)
4367       outs() << format(" %.*s", left, name);
4368     outs() << "\n";
4369 
4370     outs() << indent << "\t\t     types " << format("0x%" PRIx32, m.types);
4371     name = get_pointer_32(m.types, xoffset, left, xS, info);
4372     if (name != nullptr)
4373       outs() << format(" %.*s", left, name);
4374     outs() << "\n";
4375 
4376     outs() << indent << "\t\t       imp " << format("0x%" PRIx32, m.imp);
4377     name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
4378                          m.imp);
4379     if (name != nullptr)
4380       outs() << " " << name;
4381     outs() << "\n";
4382 
4383     p += sizeof(struct method32_t);
4384     offset += sizeof(struct method32_t);
4385   }
4386 }
4387 
4388 static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
4389   uint32_t offset, left, xleft;
4390   SectionRef S;
4391   struct objc_method_list_t method_list;
4392   struct objc_method_t method;
4393   const char *r, *methods, *name, *SymbolName;
4394   int32_t i;
4395 
4396   r = get_pointer_32(p, offset, left, S, info, true);
4397   if (r == nullptr)
4398     return true;
4399 
4400   outs() << "\n";
4401   if (left > sizeof(struct objc_method_list_t)) {
4402     memcpy(&method_list, r, sizeof(struct objc_method_list_t));
4403   } else {
4404     outs() << "\t\t objc_method_list extends past end of the section\n";
4405     memset(&method_list, '\0', sizeof(struct objc_method_list_t));
4406     memcpy(&method_list, r, left);
4407   }
4408   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4409     swapStruct(method_list);
4410 
4411   outs() << "\t\t         obsolete "
4412          << format("0x%08" PRIx32, method_list.obsolete) << "\n";
4413   outs() << "\t\t     method_count " << method_list.method_count << "\n";
4414 
4415   methods = r + sizeof(struct objc_method_list_t);
4416   for (i = 0; i < method_list.method_count; i++) {
4417     if ((i + 1) * sizeof(struct objc_method_t) > left) {
4418       outs() << "\t\t remaining method's extend past the of the section\n";
4419       break;
4420     }
4421     memcpy(&method, methods + i * sizeof(struct objc_method_t),
4422            sizeof(struct objc_method_t));
4423     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4424       swapStruct(method);
4425 
4426     outs() << "\t\t      method_name "
4427            << format("0x%08" PRIx32, method.method_name);
4428     if (info->verbose) {
4429       name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
4430       if (name != nullptr)
4431         outs() << format(" %.*s", xleft, name);
4432       else
4433         outs() << " (not in an __OBJC section)";
4434     }
4435     outs() << "\n";
4436 
4437     outs() << "\t\t     method_types "
4438            << format("0x%08" PRIx32, method.method_types);
4439     if (info->verbose) {
4440       name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
4441       if (name != nullptr)
4442         outs() << format(" %.*s", xleft, name);
4443       else
4444         outs() << " (not in an __OBJC section)";
4445     }
4446     outs() << "\n";
4447 
4448     outs() << "\t\t       method_imp "
4449            << format("0x%08" PRIx32, method.method_imp) << " ";
4450     if (info->verbose) {
4451       SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
4452       if (SymbolName != nullptr)
4453         outs() << SymbolName;
4454     }
4455     outs() << "\n";
4456   }
4457   return false;
4458 }
4459 
4460 static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
4461   struct protocol_list64_t pl;
4462   uint64_t q, n_value;
4463   struct protocol64_t pc;
4464   const char *r;
4465   uint32_t offset, xoffset, left, i;
4466   SectionRef S, xS;
4467   const char *name, *sym_name;
4468 
4469   r = get_pointer_64(p, offset, left, S, info);
4470   if (r == nullptr)
4471     return;
4472   memset(&pl, '\0', sizeof(struct protocol_list64_t));
4473   if (left < sizeof(struct protocol_list64_t)) {
4474     memcpy(&pl, r, left);
4475     outs() << "   (protocol_list_t entends past the end of the section)\n";
4476   } else
4477     memcpy(&pl, r, sizeof(struct protocol_list64_t));
4478   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4479     swapStruct(pl);
4480   outs() << "                      count " << pl.count << "\n";
4481 
4482   p += sizeof(struct protocol_list64_t);
4483   offset += sizeof(struct protocol_list64_t);
4484   for (i = 0; i < pl.count; i++) {
4485     r = get_pointer_64(p, offset, left, S, info);
4486     if (r == nullptr)
4487       return;
4488     q = 0;
4489     if (left < sizeof(uint64_t)) {
4490       memcpy(&q, r, left);
4491       outs() << "   (protocol_t * entends past the end of the section)\n";
4492     } else
4493       memcpy(&q, r, sizeof(uint64_t));
4494     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4495       sys::swapByteOrder(q);
4496 
4497     outs() << "\t\t      list[" << i << "] ";
4498     sym_name = get_symbol_64(offset, S, info, n_value, q);
4499     if (n_value != 0) {
4500       if (info->verbose && sym_name != nullptr)
4501         outs() << sym_name;
4502       else
4503         outs() << format("0x%" PRIx64, n_value);
4504       if (q != 0)
4505         outs() << " + " << format("0x%" PRIx64, q);
4506     } else
4507       outs() << format("0x%" PRIx64, q);
4508     outs() << " (struct protocol_t *)\n";
4509 
4510     r = get_pointer_64(q + n_value, offset, left, S, info);
4511     if (r == nullptr)
4512       return;
4513     memset(&pc, '\0', sizeof(struct protocol64_t));
4514     if (left < sizeof(struct protocol64_t)) {
4515       memcpy(&pc, r, left);
4516       outs() << "   (protocol_t entends past the end of the section)\n";
4517     } else
4518       memcpy(&pc, r, sizeof(struct protocol64_t));
4519     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4520       swapStruct(pc);
4521 
4522     outs() << "\t\t\t      isa " << format("0x%" PRIx64, pc.isa) << "\n";
4523 
4524     outs() << "\t\t\t     name ";
4525     sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
4526                              info, n_value, pc.name);
4527     if (n_value != 0) {
4528       if (info->verbose && sym_name != nullptr)
4529         outs() << sym_name;
4530       else
4531         outs() << format("0x%" PRIx64, n_value);
4532       if (pc.name != 0)
4533         outs() << " + " << format("0x%" PRIx64, pc.name);
4534     } else
4535       outs() << format("0x%" PRIx64, pc.name);
4536     name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
4537     if (name != nullptr)
4538       outs() << format(" %.*s", left, name);
4539     outs() << "\n";
4540 
4541     outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
4542 
4543     outs() << "\t\t  instanceMethods ";
4544     sym_name =
4545         get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
4546                       S, info, n_value, pc.instanceMethods);
4547     if (n_value != 0) {
4548       if (info->verbose && sym_name != nullptr)
4549         outs() << sym_name;
4550       else
4551         outs() << format("0x%" PRIx64, n_value);
4552       if (pc.instanceMethods != 0)
4553         outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
4554     } else
4555       outs() << format("0x%" PRIx64, pc.instanceMethods);
4556     outs() << " (struct method_list_t *)\n";
4557     if (pc.instanceMethods + n_value != 0)
4558       print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
4559 
4560     outs() << "\t\t     classMethods ";
4561     sym_name =
4562         get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
4563                       info, n_value, pc.classMethods);
4564     if (n_value != 0) {
4565       if (info->verbose && sym_name != nullptr)
4566         outs() << sym_name;
4567       else
4568         outs() << format("0x%" PRIx64, n_value);
4569       if (pc.classMethods != 0)
4570         outs() << " + " << format("0x%" PRIx64, pc.classMethods);
4571     } else
4572       outs() << format("0x%" PRIx64, pc.classMethods);
4573     outs() << " (struct method_list_t *)\n";
4574     if (pc.classMethods + n_value != 0)
4575       print_method_list64_t(pc.classMethods + n_value, info, "\t");
4576 
4577     outs() << "\t  optionalInstanceMethods "
4578            << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
4579     outs() << "\t     optionalClassMethods "
4580            << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
4581     outs() << "\t       instanceProperties "
4582            << format("0x%" PRIx64, pc.instanceProperties) << "\n";
4583 
4584     p += sizeof(uint64_t);
4585     offset += sizeof(uint64_t);
4586   }
4587 }
4588 
4589 static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
4590   struct protocol_list32_t pl;
4591   uint32_t q;
4592   struct protocol32_t pc;
4593   const char *r;
4594   uint32_t offset, xoffset, left, i;
4595   SectionRef S, xS;
4596   const char *name;
4597 
4598   r = get_pointer_32(p, offset, left, S, info);
4599   if (r == nullptr)
4600     return;
4601   memset(&pl, '\0', sizeof(struct protocol_list32_t));
4602   if (left < sizeof(struct protocol_list32_t)) {
4603     memcpy(&pl, r, left);
4604     outs() << "   (protocol_list_t entends past the end of the section)\n";
4605   } else
4606     memcpy(&pl, r, sizeof(struct protocol_list32_t));
4607   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4608     swapStruct(pl);
4609   outs() << "                      count " << pl.count << "\n";
4610 
4611   p += sizeof(struct protocol_list32_t);
4612   offset += sizeof(struct protocol_list32_t);
4613   for (i = 0; i < pl.count; i++) {
4614     r = get_pointer_32(p, offset, left, S, info);
4615     if (r == nullptr)
4616       return;
4617     q = 0;
4618     if (left < sizeof(uint32_t)) {
4619       memcpy(&q, r, left);
4620       outs() << "   (protocol_t * entends past the end of the section)\n";
4621     } else
4622       memcpy(&q, r, sizeof(uint32_t));
4623     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4624       sys::swapByteOrder(q);
4625     outs() << "\t\t      list[" << i << "] " << format("0x%" PRIx32, q)
4626            << " (struct protocol_t *)\n";
4627     r = get_pointer_32(q, offset, left, S, info);
4628     if (r == nullptr)
4629       return;
4630     memset(&pc, '\0', sizeof(struct protocol32_t));
4631     if (left < sizeof(struct protocol32_t)) {
4632       memcpy(&pc, r, left);
4633       outs() << "   (protocol_t entends past the end of the section)\n";
4634     } else
4635       memcpy(&pc, r, sizeof(struct protocol32_t));
4636     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4637       swapStruct(pc);
4638     outs() << "\t\t\t      isa " << format("0x%" PRIx32, pc.isa) << "\n";
4639     outs() << "\t\t\t     name " << format("0x%" PRIx32, pc.name);
4640     name = get_pointer_32(pc.name, xoffset, left, xS, info);
4641     if (name != nullptr)
4642       outs() << format(" %.*s", left, name);
4643     outs() << "\n";
4644     outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
4645     outs() << "\t\t  instanceMethods "
4646            << format("0x%" PRIx32, pc.instanceMethods)
4647            << " (struct method_list_t *)\n";
4648     if (pc.instanceMethods != 0)
4649       print_method_list32_t(pc.instanceMethods, info, "\t");
4650     outs() << "\t\t     classMethods " << format("0x%" PRIx32, pc.classMethods)
4651            << " (struct method_list_t *)\n";
4652     if (pc.classMethods != 0)
4653       print_method_list32_t(pc.classMethods, info, "\t");
4654     outs() << "\t  optionalInstanceMethods "
4655            << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
4656     outs() << "\t     optionalClassMethods "
4657            << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
4658     outs() << "\t       instanceProperties "
4659            << format("0x%" PRIx32, pc.instanceProperties) << "\n";
4660     p += sizeof(uint32_t);
4661     offset += sizeof(uint32_t);
4662   }
4663 }
4664 
4665 static void print_indent(uint32_t indent) {
4666   for (uint32_t i = 0; i < indent;) {
4667     if (indent - i >= 8) {
4668       outs() << "\t";
4669       i += 8;
4670     } else {
4671       for (uint32_t j = i; j < indent; j++)
4672         outs() << " ";
4673       return;
4674     }
4675   }
4676 }
4677 
4678 static bool print_method_description_list(uint32_t p, uint32_t indent,
4679                                           struct DisassembleInfo *info) {
4680   uint32_t offset, left, xleft;
4681   SectionRef S;
4682   struct objc_method_description_list_t mdl;
4683   struct objc_method_description_t md;
4684   const char *r, *list, *name;
4685   int32_t i;
4686 
4687   r = get_pointer_32(p, offset, left, S, info, true);
4688   if (r == nullptr)
4689     return true;
4690 
4691   outs() << "\n";
4692   if (left > sizeof(struct objc_method_description_list_t)) {
4693     memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
4694   } else {
4695     print_indent(indent);
4696     outs() << " objc_method_description_list extends past end of the section\n";
4697     memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
4698     memcpy(&mdl, r, left);
4699   }
4700   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4701     swapStruct(mdl);
4702 
4703   print_indent(indent);
4704   outs() << "        count " << mdl.count << "\n";
4705 
4706   list = r + sizeof(struct objc_method_description_list_t);
4707   for (i = 0; i < mdl.count; i++) {
4708     if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
4709       print_indent(indent);
4710       outs() << " remaining list entries extend past the of the section\n";
4711       break;
4712     }
4713     print_indent(indent);
4714     outs() << "        list[" << i << "]\n";
4715     memcpy(&md, list + i * sizeof(struct objc_method_description_t),
4716            sizeof(struct objc_method_description_t));
4717     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4718       swapStruct(md);
4719 
4720     print_indent(indent);
4721     outs() << "             name " << format("0x%08" PRIx32, md.name);
4722     if (info->verbose) {
4723       name = get_pointer_32(md.name, offset, xleft, S, info, true);
4724       if (name != nullptr)
4725         outs() << format(" %.*s", xleft, name);
4726       else
4727         outs() << " (not in an __OBJC section)";
4728     }
4729     outs() << "\n";
4730 
4731     print_indent(indent);
4732     outs() << "            types " << format("0x%08" PRIx32, md.types);
4733     if (info->verbose) {
4734       name = get_pointer_32(md.types, offset, xleft, S, info, true);
4735       if (name != nullptr)
4736         outs() << format(" %.*s", xleft, name);
4737       else
4738         outs() << " (not in an __OBJC section)";
4739     }
4740     outs() << "\n";
4741   }
4742   return false;
4743 }
4744 
4745 static bool print_protocol_list(uint32_t p, uint32_t indent,
4746                                 struct DisassembleInfo *info);
4747 
4748 static bool print_protocol(uint32_t p, uint32_t indent,
4749                            struct DisassembleInfo *info) {
4750   uint32_t offset, left;
4751   SectionRef S;
4752   struct objc_protocol_t protocol;
4753   const char *r, *name;
4754 
4755   r = get_pointer_32(p, offset, left, S, info, true);
4756   if (r == nullptr)
4757     return true;
4758 
4759   outs() << "\n";
4760   if (left >= sizeof(struct objc_protocol_t)) {
4761     memcpy(&protocol, r, sizeof(struct objc_protocol_t));
4762   } else {
4763     print_indent(indent);
4764     outs() << "            Protocol extends past end of the section\n";
4765     memset(&protocol, '\0', sizeof(struct objc_protocol_t));
4766     memcpy(&protocol, r, left);
4767   }
4768   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4769     swapStruct(protocol);
4770 
4771   print_indent(indent);
4772   outs() << "              isa " << format("0x%08" PRIx32, protocol.isa)
4773          << "\n";
4774 
4775   print_indent(indent);
4776   outs() << "    protocol_name "
4777          << format("0x%08" PRIx32, protocol.protocol_name);
4778   if (info->verbose) {
4779     name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
4780     if (name != nullptr)
4781       outs() << format(" %.*s", left, name);
4782     else
4783       outs() << " (not in an __OBJC section)";
4784   }
4785   outs() << "\n";
4786 
4787   print_indent(indent);
4788   outs() << "    protocol_list "
4789          << format("0x%08" PRIx32, protocol.protocol_list);
4790   if (print_protocol_list(protocol.protocol_list, indent + 4, info))
4791     outs() << " (not in an __OBJC section)\n";
4792 
4793   print_indent(indent);
4794   outs() << " instance_methods "
4795          << format("0x%08" PRIx32, protocol.instance_methods);
4796   if (print_method_description_list(protocol.instance_methods, indent, info))
4797     outs() << " (not in an __OBJC section)\n";
4798 
4799   print_indent(indent);
4800   outs() << "    class_methods "
4801          << format("0x%08" PRIx32, protocol.class_methods);
4802   if (print_method_description_list(protocol.class_methods, indent, info))
4803     outs() << " (not in an __OBJC section)\n";
4804 
4805   return false;
4806 }
4807 
4808 static bool print_protocol_list(uint32_t p, uint32_t indent,
4809                                 struct DisassembleInfo *info) {
4810   uint32_t offset, left, l;
4811   SectionRef S;
4812   struct objc_protocol_list_t protocol_list;
4813   const char *r, *list;
4814   int32_t i;
4815 
4816   r = get_pointer_32(p, offset, left, S, info, true);
4817   if (r == nullptr)
4818     return true;
4819 
4820   outs() << "\n";
4821   if (left > sizeof(struct objc_protocol_list_t)) {
4822     memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
4823   } else {
4824     outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
4825     memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
4826     memcpy(&protocol_list, r, left);
4827   }
4828   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4829     swapStruct(protocol_list);
4830 
4831   print_indent(indent);
4832   outs() << "         next " << format("0x%08" PRIx32, protocol_list.next)
4833          << "\n";
4834   print_indent(indent);
4835   outs() << "        count " << protocol_list.count << "\n";
4836 
4837   list = r + sizeof(struct objc_protocol_list_t);
4838   for (i = 0; i < protocol_list.count; i++) {
4839     if ((i + 1) * sizeof(uint32_t) > left) {
4840       outs() << "\t\t remaining list entries extend past the of the section\n";
4841       break;
4842     }
4843     memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
4844     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4845       sys::swapByteOrder(l);
4846 
4847     print_indent(indent);
4848     outs() << "      list[" << i << "] " << format("0x%08" PRIx32, l);
4849     if (print_protocol(l, indent, info))
4850       outs() << "(not in an __OBJC section)\n";
4851   }
4852   return false;
4853 }
4854 
4855 static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
4856   struct ivar_list64_t il;
4857   struct ivar64_t i;
4858   const char *r;
4859   uint32_t offset, xoffset, left, j;
4860   SectionRef S, xS;
4861   const char *name, *sym_name, *ivar_offset_p;
4862   uint64_t ivar_offset, n_value;
4863 
4864   r = get_pointer_64(p, offset, left, S, info);
4865   if (r == nullptr)
4866     return;
4867   memset(&il, '\0', sizeof(struct ivar_list64_t));
4868   if (left < sizeof(struct ivar_list64_t)) {
4869     memcpy(&il, r, left);
4870     outs() << "   (ivar_list_t entends past the end of the section)\n";
4871   } else
4872     memcpy(&il, r, sizeof(struct ivar_list64_t));
4873   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4874     swapStruct(il);
4875   outs() << "                    entsize " << il.entsize << "\n";
4876   outs() << "                      count " << il.count << "\n";
4877 
4878   p += sizeof(struct ivar_list64_t);
4879   offset += sizeof(struct ivar_list64_t);
4880   for (j = 0; j < il.count; j++) {
4881     r = get_pointer_64(p, offset, left, S, info);
4882     if (r == nullptr)
4883       return;
4884     memset(&i, '\0', sizeof(struct ivar64_t));
4885     if (left < sizeof(struct ivar64_t)) {
4886       memcpy(&i, r, left);
4887       outs() << "   (ivar_t entends past the end of the section)\n";
4888     } else
4889       memcpy(&i, r, sizeof(struct ivar64_t));
4890     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4891       swapStruct(i);
4892 
4893     outs() << "\t\t\t   offset ";
4894     sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
4895                              info, n_value, i.offset);
4896     if (n_value != 0) {
4897       if (info->verbose && sym_name != nullptr)
4898         outs() << sym_name;
4899       else
4900         outs() << format("0x%" PRIx64, n_value);
4901       if (i.offset != 0)
4902         outs() << " + " << format("0x%" PRIx64, i.offset);
4903     } else
4904       outs() << format("0x%" PRIx64, i.offset);
4905     ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
4906     if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4907       memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4908       if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4909         sys::swapByteOrder(ivar_offset);
4910       outs() << " " << ivar_offset << "\n";
4911     } else
4912       outs() << "\n";
4913 
4914     outs() << "\t\t\t     name ";
4915     sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
4916                              n_value, i.name);
4917     if (n_value != 0) {
4918       if (info->verbose && sym_name != nullptr)
4919         outs() << sym_name;
4920       else
4921         outs() << format("0x%" PRIx64, n_value);
4922       if (i.name != 0)
4923         outs() << " + " << format("0x%" PRIx64, i.name);
4924     } else
4925       outs() << format("0x%" PRIx64, i.name);
4926     name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
4927     if (name != nullptr)
4928       outs() << format(" %.*s", left, name);
4929     outs() << "\n";
4930 
4931     outs() << "\t\t\t     type ";
4932     sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
4933                              n_value, i.name);
4934     name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
4935     if (n_value != 0) {
4936       if (info->verbose && sym_name != nullptr)
4937         outs() << sym_name;
4938       else
4939         outs() << format("0x%" PRIx64, n_value);
4940       if (i.type != 0)
4941         outs() << " + " << format("0x%" PRIx64, i.type);
4942     } else
4943       outs() << format("0x%" PRIx64, i.type);
4944     if (name != nullptr)
4945       outs() << format(" %.*s", left, name);
4946     outs() << "\n";
4947 
4948     outs() << "\t\t\talignment " << i.alignment << "\n";
4949     outs() << "\t\t\t     size " << i.size << "\n";
4950 
4951     p += sizeof(struct ivar64_t);
4952     offset += sizeof(struct ivar64_t);
4953   }
4954 }
4955 
4956 static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4957   struct ivar_list32_t il;
4958   struct ivar32_t i;
4959   const char *r;
4960   uint32_t offset, xoffset, left, j;
4961   SectionRef S, xS;
4962   const char *name, *ivar_offset_p;
4963   uint32_t ivar_offset;
4964 
4965   r = get_pointer_32(p, offset, left, S, info);
4966   if (r == nullptr)
4967     return;
4968   memset(&il, '\0', sizeof(struct ivar_list32_t));
4969   if (left < sizeof(struct ivar_list32_t)) {
4970     memcpy(&il, r, left);
4971     outs() << "   (ivar_list_t entends past the end of the section)\n";
4972   } else
4973     memcpy(&il, r, sizeof(struct ivar_list32_t));
4974   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4975     swapStruct(il);
4976   outs() << "                    entsize " << il.entsize << "\n";
4977   outs() << "                      count " << il.count << "\n";
4978 
4979   p += sizeof(struct ivar_list32_t);
4980   offset += sizeof(struct ivar_list32_t);
4981   for (j = 0; j < il.count; j++) {
4982     r = get_pointer_32(p, offset, left, S, info);
4983     if (r == nullptr)
4984       return;
4985     memset(&i, '\0', sizeof(struct ivar32_t));
4986     if (left < sizeof(struct ivar32_t)) {
4987       memcpy(&i, r, left);
4988       outs() << "   (ivar_t entends past the end of the section)\n";
4989     } else
4990       memcpy(&i, r, sizeof(struct ivar32_t));
4991     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4992       swapStruct(i);
4993 
4994     outs() << "\t\t\t   offset " << format("0x%" PRIx32, i.offset);
4995     ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4996     if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4997       memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4998       if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4999         sys::swapByteOrder(ivar_offset);
5000       outs() << " " << ivar_offset << "\n";
5001     } else
5002       outs() << "\n";
5003 
5004     outs() << "\t\t\t     name " << format("0x%" PRIx32, i.name);
5005     name = get_pointer_32(i.name, xoffset, left, xS, info);
5006     if (name != nullptr)
5007       outs() << format(" %.*s", left, name);
5008     outs() << "\n";
5009 
5010     outs() << "\t\t\t     type " << format("0x%" PRIx32, i.type);
5011     name = get_pointer_32(i.type, xoffset, left, xS, info);
5012     if (name != nullptr)
5013       outs() << format(" %.*s", left, name);
5014     outs() << "\n";
5015 
5016     outs() << "\t\t\talignment " << i.alignment << "\n";
5017     outs() << "\t\t\t     size " << i.size << "\n";
5018 
5019     p += sizeof(struct ivar32_t);
5020     offset += sizeof(struct ivar32_t);
5021   }
5022 }
5023 
5024 static void print_objc_property_list64(uint64_t p,
5025                                        struct DisassembleInfo *info) {
5026   struct objc_property_list64 opl;
5027   struct objc_property64 op;
5028   const char *r;
5029   uint32_t offset, xoffset, left, j;
5030   SectionRef S, xS;
5031   const char *name, *sym_name;
5032   uint64_t n_value;
5033 
5034   r = get_pointer_64(p, offset, left, S, info);
5035   if (r == nullptr)
5036     return;
5037   memset(&opl, '\0', sizeof(struct objc_property_list64));
5038   if (left < sizeof(struct objc_property_list64)) {
5039     memcpy(&opl, r, left);
5040     outs() << "   (objc_property_list entends past the end of the section)\n";
5041   } else
5042     memcpy(&opl, r, sizeof(struct objc_property_list64));
5043   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5044     swapStruct(opl);
5045   outs() << "                    entsize " << opl.entsize << "\n";
5046   outs() << "                      count " << opl.count << "\n";
5047 
5048   p += sizeof(struct objc_property_list64);
5049   offset += sizeof(struct objc_property_list64);
5050   for (j = 0; j < opl.count; j++) {
5051     r = get_pointer_64(p, offset, left, S, info);
5052     if (r == nullptr)
5053       return;
5054     memset(&op, '\0', sizeof(struct objc_property64));
5055     if (left < sizeof(struct objc_property64)) {
5056       memcpy(&op, r, left);
5057       outs() << "   (objc_property entends past the end of the section)\n";
5058     } else
5059       memcpy(&op, r, sizeof(struct objc_property64));
5060     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5061       swapStruct(op);
5062 
5063     outs() << "\t\t\t     name ";
5064     sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
5065                              info, n_value, op.name);
5066     if (n_value != 0) {
5067       if (info->verbose && sym_name != nullptr)
5068         outs() << sym_name;
5069       else
5070         outs() << format("0x%" PRIx64, n_value);
5071       if (op.name != 0)
5072         outs() << " + " << format("0x%" PRIx64, op.name);
5073     } else
5074       outs() << format("0x%" PRIx64, op.name);
5075     name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
5076     if (name != nullptr)
5077       outs() << format(" %.*s", left, name);
5078     outs() << "\n";
5079 
5080     outs() << "\t\t\tattributes ";
5081     sym_name =
5082         get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
5083                       info, n_value, op.attributes);
5084     if (n_value != 0) {
5085       if (info->verbose && sym_name != nullptr)
5086         outs() << sym_name;
5087       else
5088         outs() << format("0x%" PRIx64, n_value);
5089       if (op.attributes != 0)
5090         outs() << " + " << format("0x%" PRIx64, op.attributes);
5091     } else
5092       outs() << format("0x%" PRIx64, op.attributes);
5093     name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
5094     if (name != nullptr)
5095       outs() << format(" %.*s", left, name);
5096     outs() << "\n";
5097 
5098     p += sizeof(struct objc_property64);
5099     offset += sizeof(struct objc_property64);
5100   }
5101 }
5102 
5103 static void print_objc_property_list32(uint32_t p,
5104                                        struct DisassembleInfo *info) {
5105   struct objc_property_list32 opl;
5106   struct objc_property32 op;
5107   const char *r;
5108   uint32_t offset, xoffset, left, j;
5109   SectionRef S, xS;
5110   const char *name;
5111 
5112   r = get_pointer_32(p, offset, left, S, info);
5113   if (r == nullptr)
5114     return;
5115   memset(&opl, '\0', sizeof(struct objc_property_list32));
5116   if (left < sizeof(struct objc_property_list32)) {
5117     memcpy(&opl, r, left);
5118     outs() << "   (objc_property_list entends past the end of the section)\n";
5119   } else
5120     memcpy(&opl, r, sizeof(struct objc_property_list32));
5121   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5122     swapStruct(opl);
5123   outs() << "                    entsize " << opl.entsize << "\n";
5124   outs() << "                      count " << opl.count << "\n";
5125 
5126   p += sizeof(struct objc_property_list32);
5127   offset += sizeof(struct objc_property_list32);
5128   for (j = 0; j < opl.count; j++) {
5129     r = get_pointer_32(p, offset, left, S, info);
5130     if (r == nullptr)
5131       return;
5132     memset(&op, '\0', sizeof(struct objc_property32));
5133     if (left < sizeof(struct objc_property32)) {
5134       memcpy(&op, r, left);
5135       outs() << "   (objc_property entends past the end of the section)\n";
5136     } else
5137       memcpy(&op, r, sizeof(struct objc_property32));
5138     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5139       swapStruct(op);
5140 
5141     outs() << "\t\t\t     name " << format("0x%" PRIx32, op.name);
5142     name = get_pointer_32(op.name, xoffset, left, xS, info);
5143     if (name != nullptr)
5144       outs() << format(" %.*s", left, name);
5145     outs() << "\n";
5146 
5147     outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
5148     name = get_pointer_32(op.attributes, xoffset, left, xS, info);
5149     if (name != nullptr)
5150       outs() << format(" %.*s", left, name);
5151     outs() << "\n";
5152 
5153     p += sizeof(struct objc_property32);
5154     offset += sizeof(struct objc_property32);
5155   }
5156 }
5157 
5158 static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
5159                                bool &is_meta_class) {
5160   struct class_ro64_t cro;
5161   const char *r;
5162   uint32_t offset, xoffset, left;
5163   SectionRef S, xS;
5164   const char *name, *sym_name;
5165   uint64_t n_value;
5166 
5167   r = get_pointer_64(p, offset, left, S, info);
5168   if (r == nullptr || left < sizeof(struct class_ro64_t))
5169     return false;
5170   memcpy(&cro, r, sizeof(struct class_ro64_t));
5171   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5172     swapStruct(cro);
5173   outs() << "                    flags " << format("0x%" PRIx32, cro.flags);
5174   if (cro.flags & RO_META)
5175     outs() << " RO_META";
5176   if (cro.flags & RO_ROOT)
5177     outs() << " RO_ROOT";
5178   if (cro.flags & RO_HAS_CXX_STRUCTORS)
5179     outs() << " RO_HAS_CXX_STRUCTORS";
5180   outs() << "\n";
5181   outs() << "            instanceStart " << cro.instanceStart << "\n";
5182   outs() << "             instanceSize " << cro.instanceSize << "\n";
5183   outs() << "                 reserved " << format("0x%" PRIx32, cro.reserved)
5184          << "\n";
5185   outs() << "               ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
5186          << "\n";
5187   print_layout_map64(cro.ivarLayout, info);
5188 
5189   outs() << "                     name ";
5190   sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
5191                            info, n_value, cro.name);
5192   if (n_value != 0) {
5193     if (info->verbose && sym_name != nullptr)
5194       outs() << sym_name;
5195     else
5196       outs() << format("0x%" PRIx64, n_value);
5197     if (cro.name != 0)
5198       outs() << " + " << format("0x%" PRIx64, cro.name);
5199   } else
5200     outs() << format("0x%" PRIx64, cro.name);
5201   name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
5202   if (name != nullptr)
5203     outs() << format(" %.*s", left, name);
5204   outs() << "\n";
5205 
5206   outs() << "              baseMethods ";
5207   sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
5208                            S, info, n_value, cro.baseMethods);
5209   if (n_value != 0) {
5210     if (info->verbose && sym_name != nullptr)
5211       outs() << sym_name;
5212     else
5213       outs() << format("0x%" PRIx64, n_value);
5214     if (cro.baseMethods != 0)
5215       outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
5216   } else
5217     outs() << format("0x%" PRIx64, cro.baseMethods);
5218   outs() << " (struct method_list_t *)\n";
5219   if (cro.baseMethods + n_value != 0)
5220     print_method_list64_t(cro.baseMethods + n_value, info, "");
5221 
5222   outs() << "            baseProtocols ";
5223   sym_name =
5224       get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
5225                     info, n_value, cro.baseProtocols);
5226   if (n_value != 0) {
5227     if (info->verbose && sym_name != nullptr)
5228       outs() << sym_name;
5229     else
5230       outs() << format("0x%" PRIx64, n_value);
5231     if (cro.baseProtocols != 0)
5232       outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
5233   } else
5234     outs() << format("0x%" PRIx64, cro.baseProtocols);
5235   outs() << "\n";
5236   if (cro.baseProtocols + n_value != 0)
5237     print_protocol_list64_t(cro.baseProtocols + n_value, info);
5238 
5239   outs() << "                    ivars ";
5240   sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
5241                            info, n_value, cro.ivars);
5242   if (n_value != 0) {
5243     if (info->verbose && sym_name != nullptr)
5244       outs() << sym_name;
5245     else
5246       outs() << format("0x%" PRIx64, n_value);
5247     if (cro.ivars != 0)
5248       outs() << " + " << format("0x%" PRIx64, cro.ivars);
5249   } else
5250     outs() << format("0x%" PRIx64, cro.ivars);
5251   outs() << "\n";
5252   if (cro.ivars + n_value != 0)
5253     print_ivar_list64_t(cro.ivars + n_value, info);
5254 
5255   outs() << "           weakIvarLayout ";
5256   sym_name =
5257       get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
5258                     info, n_value, cro.weakIvarLayout);
5259   if (n_value != 0) {
5260     if (info->verbose && sym_name != nullptr)
5261       outs() << sym_name;
5262     else
5263       outs() << format("0x%" PRIx64, n_value);
5264     if (cro.weakIvarLayout != 0)
5265       outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
5266   } else
5267     outs() << format("0x%" PRIx64, cro.weakIvarLayout);
5268   outs() << "\n";
5269   print_layout_map64(cro.weakIvarLayout + n_value, info);
5270 
5271   outs() << "           baseProperties ";
5272   sym_name =
5273       get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
5274                     info, n_value, cro.baseProperties);
5275   if (n_value != 0) {
5276     if (info->verbose && sym_name != nullptr)
5277       outs() << sym_name;
5278     else
5279       outs() << format("0x%" PRIx64, n_value);
5280     if (cro.baseProperties != 0)
5281       outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
5282   } else
5283     outs() << format("0x%" PRIx64, cro.baseProperties);
5284   outs() << "\n";
5285   if (cro.baseProperties + n_value != 0)
5286     print_objc_property_list64(cro.baseProperties + n_value, info);
5287 
5288   is_meta_class = (cro.flags & RO_META) != 0;
5289   return true;
5290 }
5291 
5292 static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
5293                                bool &is_meta_class) {
5294   struct class_ro32_t cro;
5295   const char *r;
5296   uint32_t offset, xoffset, left;
5297   SectionRef S, xS;
5298   const char *name;
5299 
5300   r = get_pointer_32(p, offset, left, S, info);
5301   if (r == nullptr)
5302     return false;
5303   memset(&cro, '\0', sizeof(struct class_ro32_t));
5304   if (left < sizeof(struct class_ro32_t)) {
5305     memcpy(&cro, r, left);
5306     outs() << "   (class_ro_t entends past the end of the section)\n";
5307   } else
5308     memcpy(&cro, r, sizeof(struct class_ro32_t));
5309   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5310     swapStruct(cro);
5311   outs() << "                    flags " << format("0x%" PRIx32, cro.flags);
5312   if (cro.flags & RO_META)
5313     outs() << " RO_META";
5314   if (cro.flags & RO_ROOT)
5315     outs() << " RO_ROOT";
5316   if (cro.flags & RO_HAS_CXX_STRUCTORS)
5317     outs() << " RO_HAS_CXX_STRUCTORS";
5318   outs() << "\n";
5319   outs() << "            instanceStart " << cro.instanceStart << "\n";
5320   outs() << "             instanceSize " << cro.instanceSize << "\n";
5321   outs() << "               ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
5322          << "\n";
5323   print_layout_map32(cro.ivarLayout, info);
5324 
5325   outs() << "                     name " << format("0x%" PRIx32, cro.name);
5326   name = get_pointer_32(cro.name, xoffset, left, xS, info);
5327   if (name != nullptr)
5328     outs() << format(" %.*s", left, name);
5329   outs() << "\n";
5330 
5331   outs() << "              baseMethods "
5332          << format("0x%" PRIx32, cro.baseMethods)
5333          << " (struct method_list_t *)\n";
5334   if (cro.baseMethods != 0)
5335     print_method_list32_t(cro.baseMethods, info, "");
5336 
5337   outs() << "            baseProtocols "
5338          << format("0x%" PRIx32, cro.baseProtocols) << "\n";
5339   if (cro.baseProtocols != 0)
5340     print_protocol_list32_t(cro.baseProtocols, info);
5341   outs() << "                    ivars " << format("0x%" PRIx32, cro.ivars)
5342          << "\n";
5343   if (cro.ivars != 0)
5344     print_ivar_list32_t(cro.ivars, info);
5345   outs() << "           weakIvarLayout "
5346          << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
5347   print_layout_map32(cro.weakIvarLayout, info);
5348   outs() << "           baseProperties "
5349          << format("0x%" PRIx32, cro.baseProperties) << "\n";
5350   if (cro.baseProperties != 0)
5351     print_objc_property_list32(cro.baseProperties, info);
5352   is_meta_class = (cro.flags & RO_META) != 0;
5353   return true;
5354 }
5355 
5356 static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
5357   struct class64_t c;
5358   const char *r;
5359   uint32_t offset, left;
5360   SectionRef S;
5361   const char *name;
5362   uint64_t isa_n_value, n_value;
5363 
5364   r = get_pointer_64(p, offset, left, S, info);
5365   if (r == nullptr || left < sizeof(struct class64_t))
5366     return;
5367   memcpy(&c, r, sizeof(struct class64_t));
5368   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5369     swapStruct(c);
5370 
5371   outs() << "           isa " << format("0x%" PRIx64, c.isa);
5372   name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
5373                        isa_n_value, c.isa);
5374   if (name != nullptr)
5375     outs() << " " << name;
5376   outs() << "\n";
5377 
5378   outs() << "    superclass " << format("0x%" PRIx64, c.superclass);
5379   name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
5380                        n_value, c.superclass);
5381   if (name != nullptr)
5382     outs() << " " << name;
5383   else {
5384     name = get_dyld_bind_info_symbolname(S.getAddress() +
5385              offset + offsetof(struct class64_t, superclass), info);
5386     if (name != nullptr)
5387       outs() << " " << name;
5388   }
5389   outs() << "\n";
5390 
5391   outs() << "         cache " << format("0x%" PRIx64, c.cache);
5392   name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
5393                        n_value, c.cache);
5394   if (name != nullptr)
5395     outs() << " " << name;
5396   outs() << "\n";
5397 
5398   outs() << "        vtable " << format("0x%" PRIx64, c.vtable);
5399   name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
5400                        n_value, c.vtable);
5401   if (name != nullptr)
5402     outs() << " " << name;
5403   outs() << "\n";
5404 
5405   name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
5406                        n_value, c.data);
5407   outs() << "          data ";
5408   if (n_value != 0) {
5409     if (info->verbose && name != nullptr)
5410       outs() << name;
5411     else
5412       outs() << format("0x%" PRIx64, n_value);
5413     if (c.data != 0)
5414       outs() << " + " << format("0x%" PRIx64, c.data);
5415   } else
5416     outs() << format("0x%" PRIx64, c.data);
5417   outs() << " (struct class_ro_t *)";
5418 
5419   // This is a Swift class if some of the low bits of the pointer are set.
5420   if ((c.data + n_value) & 0x7)
5421     outs() << " Swift class";
5422   outs() << "\n";
5423   bool is_meta_class;
5424   if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
5425     return;
5426 
5427   if (!is_meta_class &&
5428       c.isa + isa_n_value != p &&
5429       c.isa + isa_n_value != 0 &&
5430       info->depth < 100) {
5431       info->depth++;
5432       outs() << "Meta Class\n";
5433       print_class64_t(c.isa + isa_n_value, info);
5434   }
5435 }
5436 
5437 static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
5438   struct class32_t c;
5439   const char *r;
5440   uint32_t offset, left;
5441   SectionRef S;
5442   const char *name;
5443 
5444   r = get_pointer_32(p, offset, left, S, info);
5445   if (r == nullptr)
5446     return;
5447   memset(&c, '\0', sizeof(struct class32_t));
5448   if (left < sizeof(struct class32_t)) {
5449     memcpy(&c, r, left);
5450     outs() << "   (class_t entends past the end of the section)\n";
5451   } else
5452     memcpy(&c, r, sizeof(struct class32_t));
5453   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5454     swapStruct(c);
5455 
5456   outs() << "           isa " << format("0x%" PRIx32, c.isa);
5457   name =
5458       get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
5459   if (name != nullptr)
5460     outs() << " " << name;
5461   outs() << "\n";
5462 
5463   outs() << "    superclass " << format("0x%" PRIx32, c.superclass);
5464   name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
5465                        c.superclass);
5466   if (name != nullptr)
5467     outs() << " " << name;
5468   outs() << "\n";
5469 
5470   outs() << "         cache " << format("0x%" PRIx32, c.cache);
5471   name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
5472                        c.cache);
5473   if (name != nullptr)
5474     outs() << " " << name;
5475   outs() << "\n";
5476 
5477   outs() << "        vtable " << format("0x%" PRIx32, c.vtable);
5478   name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
5479                        c.vtable);
5480   if (name != nullptr)
5481     outs() << " " << name;
5482   outs() << "\n";
5483 
5484   name =
5485       get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
5486   outs() << "          data " << format("0x%" PRIx32, c.data)
5487          << " (struct class_ro_t *)";
5488 
5489   // This is a Swift class if some of the low bits of the pointer are set.
5490   if (c.data & 0x3)
5491     outs() << " Swift class";
5492   outs() << "\n";
5493   bool is_meta_class;
5494   if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
5495     return;
5496 
5497   if (!is_meta_class) {
5498     outs() << "Meta Class\n";
5499     print_class32_t(c.isa, info);
5500   }
5501 }
5502 
5503 static void print_objc_class_t(struct objc_class_t *objc_class,
5504                                struct DisassembleInfo *info) {
5505   uint32_t offset, left, xleft;
5506   const char *name, *p, *ivar_list;
5507   SectionRef S;
5508   int32_t i;
5509   struct objc_ivar_list_t objc_ivar_list;
5510   struct objc_ivar_t ivar;
5511 
5512   outs() << "\t\t      isa " << format("0x%08" PRIx32, objc_class->isa);
5513   if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
5514     name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
5515     if (name != nullptr)
5516       outs() << format(" %.*s", left, name);
5517     else
5518       outs() << " (not in an __OBJC section)";
5519   }
5520   outs() << "\n";
5521 
5522   outs() << "\t      super_class "
5523          << format("0x%08" PRIx32, objc_class->super_class);
5524   if (info->verbose) {
5525     name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
5526     if (name != nullptr)
5527       outs() << format(" %.*s", left, name);
5528     else
5529       outs() << " (not in an __OBJC section)";
5530   }
5531   outs() << "\n";
5532 
5533   outs() << "\t\t     name " << format("0x%08" PRIx32, objc_class->name);
5534   if (info->verbose) {
5535     name = get_pointer_32(objc_class->name, offset, left, S, info, true);
5536     if (name != nullptr)
5537       outs() << format(" %.*s", left, name);
5538     else
5539       outs() << " (not in an __OBJC section)";
5540   }
5541   outs() << "\n";
5542 
5543   outs() << "\t\t  version " << format("0x%08" PRIx32, objc_class->version)
5544          << "\n";
5545 
5546   outs() << "\t\t     info " << format("0x%08" PRIx32, objc_class->info);
5547   if (info->verbose) {
5548     if (CLS_GETINFO(objc_class, CLS_CLASS))
5549       outs() << " CLS_CLASS";
5550     else if (CLS_GETINFO(objc_class, CLS_META))
5551       outs() << " CLS_META";
5552   }
5553   outs() << "\n";
5554 
5555   outs() << "\t    instance_size "
5556          << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
5557 
5558   p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
5559   outs() << "\t\t    ivars " << format("0x%08" PRIx32, objc_class->ivars);
5560   if (p != nullptr) {
5561     if (left > sizeof(struct objc_ivar_list_t)) {
5562       outs() << "\n";
5563       memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
5564     } else {
5565       outs() << " (entends past the end of the section)\n";
5566       memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
5567       memcpy(&objc_ivar_list, p, left);
5568     }
5569     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5570       swapStruct(objc_ivar_list);
5571     outs() << "\t\t       ivar_count " << objc_ivar_list.ivar_count << "\n";
5572     ivar_list = p + sizeof(struct objc_ivar_list_t);
5573     for (i = 0; i < objc_ivar_list.ivar_count; i++) {
5574       if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
5575         outs() << "\t\t remaining ivar's extend past the of the section\n";
5576         break;
5577       }
5578       memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
5579              sizeof(struct objc_ivar_t));
5580       if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5581         swapStruct(ivar);
5582 
5583       outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
5584       if (info->verbose) {
5585         name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
5586         if (name != nullptr)
5587           outs() << format(" %.*s", xleft, name);
5588         else
5589           outs() << " (not in an __OBJC section)";
5590       }
5591       outs() << "\n";
5592 
5593       outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
5594       if (info->verbose) {
5595         name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
5596         if (name != nullptr)
5597           outs() << format(" %.*s", xleft, name);
5598         else
5599           outs() << " (not in an __OBJC section)";
5600       }
5601       outs() << "\n";
5602 
5603       outs() << "\t\t      ivar_offset "
5604              << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
5605     }
5606   } else {
5607     outs() << " (not in an __OBJC section)\n";
5608   }
5609 
5610   outs() << "\t\t  methods " << format("0x%08" PRIx32, objc_class->methodLists);
5611   if (print_method_list(objc_class->methodLists, info))
5612     outs() << " (not in an __OBJC section)\n";
5613 
5614   outs() << "\t\t    cache " << format("0x%08" PRIx32, objc_class->cache)
5615          << "\n";
5616 
5617   outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
5618   if (print_protocol_list(objc_class->protocols, 16, info))
5619     outs() << " (not in an __OBJC section)\n";
5620 }
5621 
5622 static void print_objc_objc_category_t(struct objc_category_t *objc_category,
5623                                        struct DisassembleInfo *info) {
5624   uint32_t offset, left;
5625   const char *name;
5626   SectionRef S;
5627 
5628   outs() << "\t       category name "
5629          << format("0x%08" PRIx32, objc_category->category_name);
5630   if (info->verbose) {
5631     name = get_pointer_32(objc_category->category_name, offset, left, S, info,
5632                           true);
5633     if (name != nullptr)
5634       outs() << format(" %.*s", left, name);
5635     else
5636       outs() << " (not in an __OBJC section)";
5637   }
5638   outs() << "\n";
5639 
5640   outs() << "\t\t  class name "
5641          << format("0x%08" PRIx32, objc_category->class_name);
5642   if (info->verbose) {
5643     name =
5644         get_pointer_32(objc_category->class_name, offset, left, S, info, true);
5645     if (name != nullptr)
5646       outs() << format(" %.*s", left, name);
5647     else
5648       outs() << " (not in an __OBJC section)";
5649   }
5650   outs() << "\n";
5651 
5652   outs() << "\t    instance methods "
5653          << format("0x%08" PRIx32, objc_category->instance_methods);
5654   if (print_method_list(objc_category->instance_methods, info))
5655     outs() << " (not in an __OBJC section)\n";
5656 
5657   outs() << "\t       class methods "
5658          << format("0x%08" PRIx32, objc_category->class_methods);
5659   if (print_method_list(objc_category->class_methods, info))
5660     outs() << " (not in an __OBJC section)\n";
5661 }
5662 
5663 static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
5664   struct category64_t c;
5665   const char *r;
5666   uint32_t offset, xoffset, left;
5667   SectionRef S, xS;
5668   const char *name, *sym_name;
5669   uint64_t n_value;
5670 
5671   r = get_pointer_64(p, offset, left, S, info);
5672   if (r == nullptr)
5673     return;
5674   memset(&c, '\0', sizeof(struct category64_t));
5675   if (left < sizeof(struct category64_t)) {
5676     memcpy(&c, r, left);
5677     outs() << "   (category_t entends past the end of the section)\n";
5678   } else
5679     memcpy(&c, r, sizeof(struct category64_t));
5680   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5681     swapStruct(c);
5682 
5683   outs() << "              name ";
5684   sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
5685                            info, n_value, c.name);
5686   if (n_value != 0) {
5687     if (info->verbose && sym_name != nullptr)
5688       outs() << sym_name;
5689     else
5690       outs() << format("0x%" PRIx64, n_value);
5691     if (c.name != 0)
5692       outs() << " + " << format("0x%" PRIx64, c.name);
5693   } else
5694     outs() << format("0x%" PRIx64, c.name);
5695   name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
5696   if (name != nullptr)
5697     outs() << format(" %.*s", left, name);
5698   outs() << "\n";
5699 
5700   outs() << "               cls ";
5701   sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
5702                            n_value, c.cls);
5703   if (n_value != 0) {
5704     if (info->verbose && sym_name != nullptr)
5705       outs() << sym_name;
5706     else
5707       outs() << format("0x%" PRIx64, n_value);
5708     if (c.cls != 0)
5709       outs() << " + " << format("0x%" PRIx64, c.cls);
5710   } else
5711     outs() << format("0x%" PRIx64, c.cls);
5712   outs() << "\n";
5713   if (c.cls + n_value != 0)
5714     print_class64_t(c.cls + n_value, info);
5715 
5716   outs() << "   instanceMethods ";
5717   sym_name =
5718       get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
5719                     info, n_value, c.instanceMethods);
5720   if (n_value != 0) {
5721     if (info->verbose && sym_name != nullptr)
5722       outs() << sym_name;
5723     else
5724       outs() << format("0x%" PRIx64, n_value);
5725     if (c.instanceMethods != 0)
5726       outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
5727   } else
5728     outs() << format("0x%" PRIx64, c.instanceMethods);
5729   outs() << "\n";
5730   if (c.instanceMethods + n_value != 0)
5731     print_method_list64_t(c.instanceMethods + n_value, info, "");
5732 
5733   outs() << "      classMethods ";
5734   sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
5735                            S, info, n_value, c.classMethods);
5736   if (n_value != 0) {
5737     if (info->verbose && sym_name != nullptr)
5738       outs() << sym_name;
5739     else
5740       outs() << format("0x%" PRIx64, n_value);
5741     if (c.classMethods != 0)
5742       outs() << " + " << format("0x%" PRIx64, c.classMethods);
5743   } else
5744     outs() << format("0x%" PRIx64, c.classMethods);
5745   outs() << "\n";
5746   if (c.classMethods + n_value != 0)
5747     print_method_list64_t(c.classMethods + n_value, info, "");
5748 
5749   outs() << "         protocols ";
5750   sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
5751                            info, n_value, c.protocols);
5752   if (n_value != 0) {
5753     if (info->verbose && sym_name != nullptr)
5754       outs() << sym_name;
5755     else
5756       outs() << format("0x%" PRIx64, n_value);
5757     if (c.protocols != 0)
5758       outs() << " + " << format("0x%" PRIx64, c.protocols);
5759   } else
5760     outs() << format("0x%" PRIx64, c.protocols);
5761   outs() << "\n";
5762   if (c.protocols + n_value != 0)
5763     print_protocol_list64_t(c.protocols + n_value, info);
5764 
5765   outs() << "instanceProperties ";
5766   sym_name =
5767       get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
5768                     S, info, n_value, c.instanceProperties);
5769   if (n_value != 0) {
5770     if (info->verbose && sym_name != nullptr)
5771       outs() << sym_name;
5772     else
5773       outs() << format("0x%" PRIx64, n_value);
5774     if (c.instanceProperties != 0)
5775       outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
5776   } else
5777     outs() << format("0x%" PRIx64, c.instanceProperties);
5778   outs() << "\n";
5779   if (c.instanceProperties + n_value != 0)
5780     print_objc_property_list64(c.instanceProperties + n_value, info);
5781 }
5782 
5783 static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
5784   struct category32_t c;
5785   const char *r;
5786   uint32_t offset, left;
5787   SectionRef S, xS;
5788   const char *name;
5789 
5790   r = get_pointer_32(p, offset, left, S, info);
5791   if (r == nullptr)
5792     return;
5793   memset(&c, '\0', sizeof(struct category32_t));
5794   if (left < sizeof(struct category32_t)) {
5795     memcpy(&c, r, left);
5796     outs() << "   (category_t entends past the end of the section)\n";
5797   } else
5798     memcpy(&c, r, sizeof(struct category32_t));
5799   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5800     swapStruct(c);
5801 
5802   outs() << "              name " << format("0x%" PRIx32, c.name);
5803   name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
5804                        c.name);
5805   if (name)
5806     outs() << " " << name;
5807   outs() << "\n";
5808 
5809   outs() << "               cls " << format("0x%" PRIx32, c.cls) << "\n";
5810   if (c.cls != 0)
5811     print_class32_t(c.cls, info);
5812   outs() << "   instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
5813          << "\n";
5814   if (c.instanceMethods != 0)
5815     print_method_list32_t(c.instanceMethods, info, "");
5816   outs() << "      classMethods " << format("0x%" PRIx32, c.classMethods)
5817          << "\n";
5818   if (c.classMethods != 0)
5819     print_method_list32_t(c.classMethods, info, "");
5820   outs() << "         protocols " << format("0x%" PRIx32, c.protocols) << "\n";
5821   if (c.protocols != 0)
5822     print_protocol_list32_t(c.protocols, info);
5823   outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
5824          << "\n";
5825   if (c.instanceProperties != 0)
5826     print_objc_property_list32(c.instanceProperties, info);
5827 }
5828 
5829 static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
5830   uint32_t i, left, offset, xoffset;
5831   uint64_t p, n_value;
5832   struct message_ref64 mr;
5833   const char *name, *sym_name;
5834   const char *r;
5835   SectionRef xS;
5836 
5837   if (S == SectionRef())
5838     return;
5839 
5840   StringRef SectName;
5841   Expected<StringRef> SecNameOrErr = S.getName();
5842   if (SecNameOrErr)
5843     SectName = *SecNameOrErr;
5844   else
5845     consumeError(SecNameOrErr.takeError());
5846 
5847   DataRefImpl Ref = S.getRawDataRefImpl();
5848   StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5849   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5850   offset = 0;
5851   for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5852     p = S.getAddress() + i;
5853     r = get_pointer_64(p, offset, left, S, info);
5854     if (r == nullptr)
5855       return;
5856     memset(&mr, '\0', sizeof(struct message_ref64));
5857     if (left < sizeof(struct message_ref64)) {
5858       memcpy(&mr, r, left);
5859       outs() << "   (message_ref entends past the end of the section)\n";
5860     } else
5861       memcpy(&mr, r, sizeof(struct message_ref64));
5862     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5863       swapStruct(mr);
5864 
5865     outs() << "  imp ";
5866     name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
5867                          n_value, mr.imp);
5868     if (n_value != 0) {
5869       outs() << format("0x%" PRIx64, n_value) << " ";
5870       if (mr.imp != 0)
5871         outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
5872     } else
5873       outs() << format("0x%" PRIx64, mr.imp) << " ";
5874     if (name != nullptr)
5875       outs() << " " << name;
5876     outs() << "\n";
5877 
5878     outs() << "  sel ";
5879     sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
5880                              info, n_value, mr.sel);
5881     if (n_value != 0) {
5882       if (info->verbose && sym_name != nullptr)
5883         outs() << sym_name;
5884       else
5885         outs() << format("0x%" PRIx64, n_value);
5886       if (mr.sel != 0)
5887         outs() << " + " << format("0x%" PRIx64, mr.sel);
5888     } else
5889       outs() << format("0x%" PRIx64, mr.sel);
5890     name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
5891     if (name != nullptr)
5892       outs() << format(" %.*s", left, name);
5893     outs() << "\n";
5894 
5895     offset += sizeof(struct message_ref64);
5896   }
5897 }
5898 
5899 static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
5900   uint32_t i, left, offset, xoffset, p;
5901   struct message_ref32 mr;
5902   const char *name, *r;
5903   SectionRef xS;
5904 
5905   if (S == SectionRef())
5906     return;
5907 
5908   StringRef SectName;
5909   Expected<StringRef> SecNameOrErr = S.getName();
5910   if (SecNameOrErr)
5911     SectName = *SecNameOrErr;
5912   else
5913     consumeError(SecNameOrErr.takeError());
5914 
5915   DataRefImpl Ref = S.getRawDataRefImpl();
5916   StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5917   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5918   offset = 0;
5919   for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5920     p = S.getAddress() + i;
5921     r = get_pointer_32(p, offset, left, S, info);
5922     if (r == nullptr)
5923       return;
5924     memset(&mr, '\0', sizeof(struct message_ref32));
5925     if (left < sizeof(struct message_ref32)) {
5926       memcpy(&mr, r, left);
5927       outs() << "   (message_ref entends past the end of the section)\n";
5928     } else
5929       memcpy(&mr, r, sizeof(struct message_ref32));
5930     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5931       swapStruct(mr);
5932 
5933     outs() << "  imp " << format("0x%" PRIx32, mr.imp);
5934     name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
5935                          mr.imp);
5936     if (name != nullptr)
5937       outs() << " " << name;
5938     outs() << "\n";
5939 
5940     outs() << "  sel " << format("0x%" PRIx32, mr.sel);
5941     name = get_pointer_32(mr.sel, xoffset, left, xS, info);
5942     if (name != nullptr)
5943       outs() << " " << name;
5944     outs() << "\n";
5945 
5946     offset += sizeof(struct message_ref32);
5947   }
5948 }
5949 
5950 static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
5951   uint32_t left, offset, swift_version;
5952   uint64_t p;
5953   struct objc_image_info64 o;
5954   const char *r;
5955 
5956   if (S == SectionRef())
5957     return;
5958 
5959   StringRef SectName;
5960   Expected<StringRef> SecNameOrErr = S.getName();
5961   if (SecNameOrErr)
5962     SectName = *SecNameOrErr;
5963   else
5964     consumeError(SecNameOrErr.takeError());
5965 
5966   DataRefImpl Ref = S.getRawDataRefImpl();
5967   StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5968   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5969   p = S.getAddress();
5970   r = get_pointer_64(p, offset, left, S, info);
5971   if (r == nullptr)
5972     return;
5973   memset(&o, '\0', sizeof(struct objc_image_info64));
5974   if (left < sizeof(struct objc_image_info64)) {
5975     memcpy(&o, r, left);
5976     outs() << "   (objc_image_info entends past the end of the section)\n";
5977   } else
5978     memcpy(&o, r, sizeof(struct objc_image_info64));
5979   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5980     swapStruct(o);
5981   outs() << "  version " << o.version << "\n";
5982   outs() << "    flags " << format("0x%" PRIx32, o.flags);
5983   if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5984     outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5985   if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5986     outs() << " OBJC_IMAGE_SUPPORTS_GC";
5987   if (o.flags & OBJC_IMAGE_IS_SIMULATED)
5988     outs() << " OBJC_IMAGE_IS_SIMULATED";
5989   if (o.flags & OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES)
5990     outs() << " OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES";
5991   swift_version = (o.flags >> 8) & 0xff;
5992   if (swift_version != 0) {
5993     if (swift_version == 1)
5994       outs() << " Swift 1.0";
5995     else if (swift_version == 2)
5996       outs() << " Swift 1.1";
5997     else if(swift_version == 3)
5998       outs() << " Swift 2.0";
5999     else if(swift_version == 4)
6000       outs() << " Swift 3.0";
6001     else if(swift_version == 5)
6002       outs() << " Swift 4.0";
6003     else if(swift_version == 6)
6004       outs() << " Swift 4.1/Swift 4.2";
6005     else if(swift_version == 7)
6006       outs() << " Swift 5 or later";
6007     else
6008       outs() << " unknown future Swift version (" << swift_version << ")";
6009   }
6010   outs() << "\n";
6011 }
6012 
6013 static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
6014   uint32_t left, offset, swift_version, p;
6015   struct objc_image_info32 o;
6016   const char *r;
6017 
6018   if (S == SectionRef())
6019     return;
6020 
6021   StringRef SectName;
6022   Expected<StringRef> SecNameOrErr = S.getName();
6023   if (SecNameOrErr)
6024     SectName = *SecNameOrErr;
6025   else
6026     consumeError(SecNameOrErr.takeError());
6027 
6028   DataRefImpl Ref = S.getRawDataRefImpl();
6029   StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
6030   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
6031   p = S.getAddress();
6032   r = get_pointer_32(p, offset, left, S, info);
6033   if (r == nullptr)
6034     return;
6035   memset(&o, '\0', sizeof(struct objc_image_info32));
6036   if (left < sizeof(struct objc_image_info32)) {
6037     memcpy(&o, r, left);
6038     outs() << "   (objc_image_info entends past the end of the section)\n";
6039   } else
6040     memcpy(&o, r, sizeof(struct objc_image_info32));
6041   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
6042     swapStruct(o);
6043   outs() << "  version " << o.version << "\n";
6044   outs() << "    flags " << format("0x%" PRIx32, o.flags);
6045   if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
6046     outs() << " OBJC_IMAGE_IS_REPLACEMENT";
6047   if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
6048     outs() << " OBJC_IMAGE_SUPPORTS_GC";
6049   swift_version = (o.flags >> 8) & 0xff;
6050   if (swift_version != 0) {
6051     if (swift_version == 1)
6052       outs() << " Swift 1.0";
6053     else if (swift_version == 2)
6054       outs() << " Swift 1.1";
6055     else if(swift_version == 3)
6056       outs() << " Swift 2.0";
6057     else if(swift_version == 4)
6058       outs() << " Swift 3.0";
6059     else if(swift_version == 5)
6060       outs() << " Swift 4.0";
6061     else if(swift_version == 6)
6062       outs() << " Swift 4.1/Swift 4.2";
6063     else if(swift_version == 7)
6064       outs() << " Swift 5 or later";
6065     else
6066       outs() << " unknown future Swift version (" << swift_version << ")";
6067   }
6068   outs() << "\n";
6069 }
6070 
6071 static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
6072   uint32_t left, offset, p;
6073   struct imageInfo_t o;
6074   const char *r;
6075 
6076   StringRef SectName;
6077   Expected<StringRef> SecNameOrErr = S.getName();
6078   if (SecNameOrErr)
6079     SectName = *SecNameOrErr;
6080   else
6081     consumeError(SecNameOrErr.takeError());
6082 
6083   DataRefImpl Ref = S.getRawDataRefImpl();
6084   StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
6085   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
6086   p = S.getAddress();
6087   r = get_pointer_32(p, offset, left, S, info);
6088   if (r == nullptr)
6089     return;
6090   memset(&o, '\0', sizeof(struct imageInfo_t));
6091   if (left < sizeof(struct imageInfo_t)) {
6092     memcpy(&o, r, left);
6093     outs() << " (imageInfo entends past the end of the section)\n";
6094   } else
6095     memcpy(&o, r, sizeof(struct imageInfo_t));
6096   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
6097     swapStruct(o);
6098   outs() << "  version " << o.version << "\n";
6099   outs() << "    flags " << format("0x%" PRIx32, o.flags);
6100   if (o.flags & 0x1)
6101     outs() << "  F&C";
6102   if (o.flags & 0x2)
6103     outs() << " GC";
6104   if (o.flags & 0x4)
6105     outs() << " GC-only";
6106   else
6107     outs() << " RR";
6108   outs() << "\n";
6109 }
6110 
6111 static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
6112   SymbolAddressMap AddrMap;
6113   if (verbose)
6114     CreateSymbolAddressMap(O, &AddrMap);
6115 
6116   std::vector<SectionRef> Sections;
6117   append_range(Sections, O->sections());
6118 
6119   struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
6120 
6121   SectionRef CL = get_section(O, "__OBJC2", "__class_list");
6122   if (CL == SectionRef())
6123     CL = get_section(O, "__DATA", "__objc_classlist");
6124   if (CL == SectionRef())
6125     CL = get_section(O, "__DATA_CONST", "__objc_classlist");
6126   if (CL == SectionRef())
6127     CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
6128   info.S = CL;
6129   walk_pointer_list_64("class", CL, O, &info, print_class64_t);
6130 
6131   SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
6132   if (CR == SectionRef())
6133     CR = get_section(O, "__DATA", "__objc_classrefs");
6134   if (CR == SectionRef())
6135     CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
6136   if (CR == SectionRef())
6137     CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
6138   info.S = CR;
6139   walk_pointer_list_64("class refs", CR, O, &info, nullptr);
6140 
6141   SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
6142   if (SR == SectionRef())
6143     SR = get_section(O, "__DATA", "__objc_superrefs");
6144   if (SR == SectionRef())
6145     SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
6146   if (SR == SectionRef())
6147     SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
6148   info.S = SR;
6149   walk_pointer_list_64("super refs", SR, O, &info, nullptr);
6150 
6151   SectionRef CA = get_section(O, "__OBJC2", "__category_list");
6152   if (CA == SectionRef())
6153     CA = get_section(O, "__DATA", "__objc_catlist");
6154   if (CA == SectionRef())
6155     CA = get_section(O, "__DATA_CONST", "__objc_catlist");
6156   if (CA == SectionRef())
6157     CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
6158   info.S = CA;
6159   walk_pointer_list_64("category", CA, O, &info, print_category64_t);
6160 
6161   SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
6162   if (PL == SectionRef())
6163     PL = get_section(O, "__DATA", "__objc_protolist");
6164   if (PL == SectionRef())
6165     PL = get_section(O, "__DATA_CONST", "__objc_protolist");
6166   if (PL == SectionRef())
6167     PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
6168   info.S = PL;
6169   walk_pointer_list_64("protocol", PL, O, &info, nullptr);
6170 
6171   SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
6172   if (MR == SectionRef())
6173     MR = get_section(O, "__DATA", "__objc_msgrefs");
6174   if (MR == SectionRef())
6175     MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
6176   if (MR == SectionRef())
6177     MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
6178   info.S = MR;
6179   print_message_refs64(MR, &info);
6180 
6181   SectionRef II = get_section(O, "__OBJC2", "__image_info");
6182   if (II == SectionRef())
6183     II = get_section(O, "__DATA", "__objc_imageinfo");
6184   if (II == SectionRef())
6185     II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
6186   if (II == SectionRef())
6187     II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
6188   info.S = II;
6189   print_image_info64(II, &info);
6190 }
6191 
6192 static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
6193   SymbolAddressMap AddrMap;
6194   if (verbose)
6195     CreateSymbolAddressMap(O, &AddrMap);
6196 
6197   std::vector<SectionRef> Sections;
6198   append_range(Sections, O->sections());
6199 
6200   struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
6201 
6202   SectionRef CL = get_section(O, "__OBJC2", "__class_list");
6203   if (CL == SectionRef())
6204     CL = get_section(O, "__DATA", "__objc_classlist");
6205   if (CL == SectionRef())
6206     CL = get_section(O, "__DATA_CONST", "__objc_classlist");
6207   if (CL == SectionRef())
6208     CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
6209   info.S = CL;
6210   walk_pointer_list_32("class", CL, O, &info, print_class32_t);
6211 
6212   SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
6213   if (CR == SectionRef())
6214     CR = get_section(O, "__DATA", "__objc_classrefs");
6215   if (CR == SectionRef())
6216     CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
6217   if (CR == SectionRef())
6218     CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
6219   info.S = CR;
6220   walk_pointer_list_32("class refs", CR, O, &info, nullptr);
6221 
6222   SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
6223   if (SR == SectionRef())
6224     SR = get_section(O, "__DATA", "__objc_superrefs");
6225   if (SR == SectionRef())
6226     SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
6227   if (SR == SectionRef())
6228     SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
6229   info.S = SR;
6230   walk_pointer_list_32("super refs", SR, O, &info, nullptr);
6231 
6232   SectionRef CA = get_section(O, "__OBJC2", "__category_list");
6233   if (CA == SectionRef())
6234     CA = get_section(O, "__DATA", "__objc_catlist");
6235   if (CA == SectionRef())
6236     CA = get_section(O, "__DATA_CONST", "__objc_catlist");
6237   if (CA == SectionRef())
6238     CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
6239   info.S = CA;
6240   walk_pointer_list_32("category", CA, O, &info, print_category32_t);
6241 
6242   SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
6243   if (PL == SectionRef())
6244     PL = get_section(O, "__DATA", "__objc_protolist");
6245   if (PL == SectionRef())
6246     PL = get_section(O, "__DATA_CONST", "__objc_protolist");
6247   if (PL == SectionRef())
6248     PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
6249   info.S = PL;
6250   walk_pointer_list_32("protocol", PL, O, &info, nullptr);
6251 
6252   SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
6253   if (MR == SectionRef())
6254     MR = get_section(O, "__DATA", "__objc_msgrefs");
6255   if (MR == SectionRef())
6256     MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
6257   if (MR == SectionRef())
6258     MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
6259   info.S = MR;
6260   print_message_refs32(MR, &info);
6261 
6262   SectionRef II = get_section(O, "__OBJC2", "__image_info");
6263   if (II == SectionRef())
6264     II = get_section(O, "__DATA", "__objc_imageinfo");
6265   if (II == SectionRef())
6266     II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
6267   if (II == SectionRef())
6268     II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
6269   info.S = II;
6270   print_image_info32(II, &info);
6271 }
6272 
6273 static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
6274   uint32_t i, j, p, offset, xoffset, left, defs_left, def;
6275   const char *r, *name, *defs;
6276   struct objc_module_t module;
6277   SectionRef S, xS;
6278   struct objc_symtab_t symtab;
6279   struct objc_class_t objc_class;
6280   struct objc_category_t objc_category;
6281 
6282   outs() << "Objective-C segment\n";
6283   S = get_section(O, "__OBJC", "__module_info");
6284   if (S == SectionRef())
6285     return false;
6286 
6287   SymbolAddressMap AddrMap;
6288   if (verbose)
6289     CreateSymbolAddressMap(O, &AddrMap);
6290 
6291   std::vector<SectionRef> Sections;
6292   append_range(Sections, O->sections());
6293 
6294   struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
6295 
6296   for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
6297     p = S.getAddress() + i;
6298     r = get_pointer_32(p, offset, left, S, &info, true);
6299     if (r == nullptr)
6300       return true;
6301     memset(&module, '\0', sizeof(struct objc_module_t));
6302     if (left < sizeof(struct objc_module_t)) {
6303       memcpy(&module, r, left);
6304       outs() << "   (module extends past end of __module_info section)\n";
6305     } else
6306       memcpy(&module, r, sizeof(struct objc_module_t));
6307     if (O->isLittleEndian() != sys::IsLittleEndianHost)
6308       swapStruct(module);
6309 
6310     outs() << "Module " << format("0x%" PRIx32, p) << "\n";
6311     outs() << "    version " << module.version << "\n";
6312     outs() << "       size " << module.size << "\n";
6313     outs() << "       name ";
6314     name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
6315     if (name != nullptr)
6316       outs() << format("%.*s", left, name);
6317     else
6318       outs() << format("0x%08" PRIx32, module.name)
6319              << "(not in an __OBJC section)";
6320     outs() << "\n";
6321 
6322     r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
6323     if (module.symtab == 0 || r == nullptr) {
6324       outs() << "     symtab " << format("0x%08" PRIx32, module.symtab)
6325              << " (not in an __OBJC section)\n";
6326       continue;
6327     }
6328     outs() << "     symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
6329     memset(&symtab, '\0', sizeof(struct objc_symtab_t));
6330     defs_left = 0;
6331     defs = nullptr;
6332     if (left < sizeof(struct objc_symtab_t)) {
6333       memcpy(&symtab, r, left);
6334       outs() << "\tsymtab extends past end of an __OBJC section)\n";
6335     } else {
6336       memcpy(&symtab, r, sizeof(struct objc_symtab_t));
6337       if (left > sizeof(struct objc_symtab_t)) {
6338         defs_left = left - sizeof(struct objc_symtab_t);
6339         defs = r + sizeof(struct objc_symtab_t);
6340       }
6341     }
6342     if (O->isLittleEndian() != sys::IsLittleEndianHost)
6343       swapStruct(symtab);
6344 
6345     outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
6346     r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
6347     outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
6348     if (r == nullptr)
6349       outs() << " (not in an __OBJC section)";
6350     outs() << "\n";
6351     outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
6352     outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
6353     if (symtab.cls_def_cnt > 0)
6354       outs() << "\tClass Definitions\n";
6355     for (j = 0; j < symtab.cls_def_cnt; j++) {
6356       if ((j + 1) * sizeof(uint32_t) > defs_left) {
6357         outs() << "\t(remaining class defs entries entends past the end of the "
6358                << "section)\n";
6359         break;
6360       }
6361       memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
6362       if (O->isLittleEndian() != sys::IsLittleEndianHost)
6363         sys::swapByteOrder(def);
6364 
6365       r = get_pointer_32(def, xoffset, left, xS, &info, true);
6366       outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
6367       if (r != nullptr) {
6368         if (left > sizeof(struct objc_class_t)) {
6369           outs() << "\n";
6370           memcpy(&objc_class, r, sizeof(struct objc_class_t));
6371         } else {
6372           outs() << " (entends past the end of the section)\n";
6373           memset(&objc_class, '\0', sizeof(struct objc_class_t));
6374           memcpy(&objc_class, r, left);
6375         }
6376         if (O->isLittleEndian() != sys::IsLittleEndianHost)
6377           swapStruct(objc_class);
6378         print_objc_class_t(&objc_class, &info);
6379       } else {
6380         outs() << "(not in an __OBJC section)\n";
6381       }
6382 
6383       if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
6384         outs() << "\tMeta Class";
6385         r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
6386         if (r != nullptr) {
6387           if (left > sizeof(struct objc_class_t)) {
6388             outs() << "\n";
6389             memcpy(&objc_class, r, sizeof(struct objc_class_t));
6390           } else {
6391             outs() << " (entends past the end of the section)\n";
6392             memset(&objc_class, '\0', sizeof(struct objc_class_t));
6393             memcpy(&objc_class, r, left);
6394           }
6395           if (O->isLittleEndian() != sys::IsLittleEndianHost)
6396             swapStruct(objc_class);
6397           print_objc_class_t(&objc_class, &info);
6398         } else {
6399           outs() << "(not in an __OBJC section)\n";
6400         }
6401       }
6402     }
6403     if (symtab.cat_def_cnt > 0)
6404       outs() << "\tCategory Definitions\n";
6405     for (j = 0; j < symtab.cat_def_cnt; j++) {
6406       if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
6407         outs() << "\t(remaining category defs entries entends past the end of "
6408                << "the section)\n";
6409         break;
6410       }
6411       memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
6412              sizeof(uint32_t));
6413       if (O->isLittleEndian() != sys::IsLittleEndianHost)
6414         sys::swapByteOrder(def);
6415 
6416       r = get_pointer_32(def, xoffset, left, xS, &info, true);
6417       outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
6418              << format("0x%08" PRIx32, def);
6419       if (r != nullptr) {
6420         if (left > sizeof(struct objc_category_t)) {
6421           outs() << "\n";
6422           memcpy(&objc_category, r, sizeof(struct objc_category_t));
6423         } else {
6424           outs() << " (entends past the end of the section)\n";
6425           memset(&objc_category, '\0', sizeof(struct objc_category_t));
6426           memcpy(&objc_category, r, left);
6427         }
6428         if (O->isLittleEndian() != sys::IsLittleEndianHost)
6429           swapStruct(objc_category);
6430         print_objc_objc_category_t(&objc_category, &info);
6431       } else {
6432         outs() << "(not in an __OBJC section)\n";
6433       }
6434     }
6435   }
6436   const SectionRef II = get_section(O, "__OBJC", "__image_info");
6437   if (II != SectionRef())
6438     print_image_info(II, &info);
6439 
6440   return true;
6441 }
6442 
6443 static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
6444                                 uint32_t size, uint32_t addr) {
6445   SymbolAddressMap AddrMap;
6446   CreateSymbolAddressMap(O, &AddrMap);
6447 
6448   std::vector<SectionRef> Sections;
6449   append_range(Sections, O->sections());
6450 
6451   struct DisassembleInfo info(O, &AddrMap, &Sections, true);
6452 
6453   const char *p;
6454   struct objc_protocol_t protocol;
6455   uint32_t left, paddr;
6456   for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
6457     memset(&protocol, '\0', sizeof(struct objc_protocol_t));
6458     left = size - (p - sect);
6459     if (left < sizeof(struct objc_protocol_t)) {
6460       outs() << "Protocol extends past end of __protocol section\n";
6461       memcpy(&protocol, p, left);
6462     } else
6463       memcpy(&protocol, p, sizeof(struct objc_protocol_t));
6464     if (O->isLittleEndian() != sys::IsLittleEndianHost)
6465       swapStruct(protocol);
6466     paddr = addr + (p - sect);
6467     outs() << "Protocol " << format("0x%" PRIx32, paddr);
6468     if (print_protocol(paddr, 0, &info))
6469       outs() << "(not in an __OBJC section)\n";
6470   }
6471 }
6472 
6473 #ifdef HAVE_LIBXAR
6474 static inline void swapStruct(struct xar_header &xar) {
6475   sys::swapByteOrder(xar.magic);
6476   sys::swapByteOrder(xar.size);
6477   sys::swapByteOrder(xar.version);
6478   sys::swapByteOrder(xar.toc_length_compressed);
6479   sys::swapByteOrder(xar.toc_length_uncompressed);
6480   sys::swapByteOrder(xar.cksum_alg);
6481 }
6482 
6483 static void PrintModeVerbose(uint32_t mode) {
6484   switch(mode & S_IFMT){
6485   case S_IFDIR:
6486     outs() << "d";
6487     break;
6488   case S_IFCHR:
6489     outs() << "c";
6490     break;
6491   case S_IFBLK:
6492     outs() << "b";
6493     break;
6494   case S_IFREG:
6495     outs() << "-";
6496     break;
6497   case S_IFLNK:
6498     outs() << "l";
6499     break;
6500   case S_IFSOCK:
6501     outs() << "s";
6502     break;
6503   default:
6504     outs() << "?";
6505     break;
6506   }
6507 
6508   /* owner permissions */
6509   if(mode & S_IREAD)
6510     outs() << "r";
6511   else
6512     outs() << "-";
6513   if(mode & S_IWRITE)
6514     outs() << "w";
6515   else
6516     outs() << "-";
6517   if(mode & S_ISUID)
6518     outs() << "s";
6519   else if(mode & S_IEXEC)
6520     outs() << "x";
6521   else
6522     outs() << "-";
6523 
6524   /* group permissions */
6525   if(mode & (S_IREAD >> 3))
6526     outs() << "r";
6527   else
6528     outs() << "-";
6529   if(mode & (S_IWRITE >> 3))
6530     outs() << "w";
6531   else
6532     outs() << "-";
6533   if(mode & S_ISGID)
6534     outs() << "s";
6535   else if(mode & (S_IEXEC >> 3))
6536     outs() << "x";
6537   else
6538     outs() << "-";
6539 
6540   /* other permissions */
6541   if(mode & (S_IREAD >> 6))
6542     outs() << "r";
6543   else
6544     outs() << "-";
6545   if(mode & (S_IWRITE >> 6))
6546     outs() << "w";
6547   else
6548     outs() << "-";
6549   if(mode & S_ISVTX)
6550     outs() << "t";
6551   else if(mode & (S_IEXEC >> 6))
6552     outs() << "x";
6553   else
6554     outs() << "-";
6555 }
6556 
6557 static void PrintXarFilesSummary(const char *XarFilename, xar_t xar) {
6558   xar_file_t xf;
6559   const char *key, *type, *mode, *user, *group, *size, *mtime, *name, *m;
6560   char *endp;
6561   uint32_t mode_value;
6562 
6563   ScopedXarIter xi;
6564   if (!xi) {
6565     WithColor::error(errs(), "llvm-objdump")
6566         << "can't obtain an xar iterator for xar archive " << XarFilename
6567         << "\n";
6568     return;
6569   }
6570 
6571   // Go through the xar's files.
6572   for (xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)) {
6573     ScopedXarIter xp;
6574     if(!xp){
6575       WithColor::error(errs(), "llvm-objdump")
6576           << "can't obtain an xar iterator for xar archive " << XarFilename
6577           << "\n";
6578       return;
6579     }
6580     type = nullptr;
6581     mode = nullptr;
6582     user = nullptr;
6583     group = nullptr;
6584     size = nullptr;
6585     mtime = nullptr;
6586     name = nullptr;
6587     for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
6588       const char *val = nullptr;
6589       xar_prop_get(xf, key, &val);
6590 #if 0 // Useful for debugging.
6591       outs() << "key: " << key << " value: " << val << "\n";
6592 #endif
6593       if(strcmp(key, "type") == 0)
6594         type = val;
6595       if(strcmp(key, "mode") == 0)
6596         mode = val;
6597       if(strcmp(key, "user") == 0)
6598         user = val;
6599       if(strcmp(key, "group") == 0)
6600         group = val;
6601       if(strcmp(key, "data/size") == 0)
6602         size = val;
6603       if(strcmp(key, "mtime") == 0)
6604         mtime = val;
6605       if(strcmp(key, "name") == 0)
6606         name = val;
6607     }
6608     if(mode != nullptr){
6609       mode_value = strtoul(mode, &endp, 8);
6610       if(*endp != '\0')
6611         outs() << "(mode: \"" << mode << "\" contains non-octal chars) ";
6612       if(strcmp(type, "file") == 0)
6613         mode_value |= S_IFREG;
6614       PrintModeVerbose(mode_value);
6615       outs() << " ";
6616     }
6617     if(user != nullptr)
6618       outs() << format("%10s/", user);
6619     if(group != nullptr)
6620       outs() << format("%-10s ", group);
6621     if(size != nullptr)
6622       outs() << format("%7s ", size);
6623     if(mtime != nullptr){
6624       for(m = mtime; *m != 'T' && *m != '\0'; m++)
6625         outs() << *m;
6626       if(*m == 'T')
6627         m++;
6628       outs() << " ";
6629       for( ; *m != 'Z' && *m != '\0'; m++)
6630         outs() << *m;
6631       outs() << " ";
6632     }
6633     if(name != nullptr)
6634       outs() << name;
6635     outs() << "\n";
6636   }
6637 }
6638 
6639 static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
6640                                 uint32_t size, bool verbose,
6641                                 bool PrintXarHeader, bool PrintXarFileHeaders,
6642                                 std::string XarMemberName) {
6643   if(size < sizeof(struct xar_header)) {
6644     outs() << "size of (__LLVM,__bundle) section too small (smaller than size "
6645               "of struct xar_header)\n";
6646     return;
6647   }
6648   struct xar_header XarHeader;
6649   memcpy(&XarHeader, sect, sizeof(struct xar_header));
6650   if (sys::IsLittleEndianHost)
6651     swapStruct(XarHeader);
6652   if (PrintXarHeader) {
6653     if (!XarMemberName.empty())
6654       outs() << "In xar member " << XarMemberName << ": ";
6655     else
6656       outs() << "For (__LLVM,__bundle) section: ";
6657     outs() << "xar header\n";
6658     if (XarHeader.magic == XAR_HEADER_MAGIC)
6659       outs() << "                  magic XAR_HEADER_MAGIC\n";
6660     else
6661       outs() << "                  magic "
6662              << format_hex(XarHeader.magic, 10, true)
6663              << " (not XAR_HEADER_MAGIC)\n";
6664     outs() << "                   size " << XarHeader.size << "\n";
6665     outs() << "                version " << XarHeader.version << "\n";
6666     outs() << "  toc_length_compressed " << XarHeader.toc_length_compressed
6667            << "\n";
6668     outs() << "toc_length_uncompressed " << XarHeader.toc_length_uncompressed
6669            << "\n";
6670     outs() << "              cksum_alg ";
6671     switch (XarHeader.cksum_alg) {
6672       case XAR_CKSUM_NONE:
6673         outs() << "XAR_CKSUM_NONE\n";
6674         break;
6675       case XAR_CKSUM_SHA1:
6676         outs() << "XAR_CKSUM_SHA1\n";
6677         break;
6678       case XAR_CKSUM_MD5:
6679         outs() << "XAR_CKSUM_MD5\n";
6680         break;
6681 #ifdef XAR_CKSUM_SHA256
6682       case XAR_CKSUM_SHA256:
6683         outs() << "XAR_CKSUM_SHA256\n";
6684         break;
6685 #endif
6686 #ifdef XAR_CKSUM_SHA512
6687       case XAR_CKSUM_SHA512:
6688         outs() << "XAR_CKSUM_SHA512\n";
6689         break;
6690 #endif
6691       default:
6692         outs() << XarHeader.cksum_alg << "\n";
6693     }
6694   }
6695 
6696   SmallString<128> XarFilename;
6697   int FD;
6698   std::error_code XarEC =
6699       sys::fs::createTemporaryFile("llvm-objdump", "xar", FD, XarFilename);
6700   if (XarEC) {
6701     WithColor::error(errs(), "llvm-objdump") << XarEC.message() << "\n";
6702     return;
6703   }
6704   ToolOutputFile XarFile(XarFilename, FD);
6705   raw_fd_ostream &XarOut = XarFile.os();
6706   StringRef XarContents(sect, size);
6707   XarOut << XarContents;
6708   XarOut.close();
6709   if (XarOut.has_error())
6710     return;
6711 
6712   ScopedXarFile xar(XarFilename.c_str(), READ);
6713   if (!xar) {
6714     WithColor::error(errs(), "llvm-objdump")
6715         << "can't create temporary xar archive " << XarFilename << "\n";
6716     return;
6717   }
6718 
6719   SmallString<128> TocFilename;
6720   std::error_code TocEC =
6721       sys::fs::createTemporaryFile("llvm-objdump", "toc", TocFilename);
6722   if (TocEC) {
6723     WithColor::error(errs(), "llvm-objdump") << TocEC.message() << "\n";
6724     return;
6725   }
6726   xar_serialize(xar, TocFilename.c_str());
6727 
6728   if (PrintXarFileHeaders) {
6729     if (!XarMemberName.empty())
6730       outs() << "In xar member " << XarMemberName << ": ";
6731     else
6732       outs() << "For (__LLVM,__bundle) section: ";
6733     outs() << "xar archive files:\n";
6734     PrintXarFilesSummary(XarFilename.c_str(), xar);
6735   }
6736 
6737   ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
6738     MemoryBuffer::getFileOrSTDIN(TocFilename.c_str());
6739   if (std::error_code EC = FileOrErr.getError()) {
6740     WithColor::error(errs(), "llvm-objdump") << EC.message() << "\n";
6741     return;
6742   }
6743   std::unique_ptr<MemoryBuffer> &Buffer = FileOrErr.get();
6744 
6745   if (!XarMemberName.empty())
6746     outs() << "In xar member " << XarMemberName << ": ";
6747   else
6748     outs() << "For (__LLVM,__bundle) section: ";
6749   outs() << "xar table of contents:\n";
6750   outs() << Buffer->getBuffer() << "\n";
6751 
6752   // TODO: Go through the xar's files.
6753   ScopedXarIter xi;
6754   if(!xi){
6755     WithColor::error(errs(), "llvm-objdump")
6756         << "can't obtain an xar iterator for xar archive "
6757         << XarFilename.c_str() << "\n";
6758     return;
6759   }
6760   for(xar_file_t xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)){
6761     const char *key;
6762     const char *member_name, *member_type, *member_size_string;
6763     size_t member_size;
6764 
6765     ScopedXarIter xp;
6766     if(!xp){
6767       WithColor::error(errs(), "llvm-objdump")
6768           << "can't obtain an xar iterator for xar archive "
6769           << XarFilename.c_str() << "\n";
6770       return;
6771     }
6772     member_name = NULL;
6773     member_type = NULL;
6774     member_size_string = NULL;
6775     for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
6776       const char *val = nullptr;
6777       xar_prop_get(xf, key, &val);
6778 #if 0 // Useful for debugging.
6779       outs() << "key: " << key << " value: " << val << "\n";
6780 #endif
6781       if (strcmp(key, "name") == 0)
6782         member_name = val;
6783       if (strcmp(key, "type") == 0)
6784         member_type = val;
6785       if (strcmp(key, "data/size") == 0)
6786         member_size_string = val;
6787     }
6788     /*
6789      * If we find a file with a name, date/size and type properties
6790      * and with the type being "file" see if that is a xar file.
6791      */
6792     if (member_name != NULL && member_type != NULL &&
6793         strcmp(member_type, "file") == 0 &&
6794         member_size_string != NULL){
6795       // Extract the file into a buffer.
6796       char *endptr;
6797       member_size = strtoul(member_size_string, &endptr, 10);
6798       if (*endptr == '\0' && member_size != 0) {
6799         char *buffer;
6800         if (xar_extract_tobuffersz(xar, xf, &buffer, &member_size) == 0) {
6801 #if 0 // Useful for debugging.
6802           outs() << "xar member: " << member_name << " extracted\n";
6803 #endif
6804           // Set the XarMemberName we want to see printed in the header.
6805           std::string OldXarMemberName;
6806           // If XarMemberName is already set this is nested. So
6807           // save the old name and create the nested name.
6808           if (!XarMemberName.empty()) {
6809             OldXarMemberName = XarMemberName;
6810             XarMemberName =
6811                 (Twine("[") + XarMemberName + "]" + member_name).str();
6812           } else {
6813             OldXarMemberName = "";
6814             XarMemberName = member_name;
6815           }
6816           // See if this is could be a xar file (nested).
6817           if (member_size >= sizeof(struct xar_header)) {
6818 #if 0 // Useful for debugging.
6819             outs() << "could be a xar file: " << member_name << "\n";
6820 #endif
6821             memcpy((char *)&XarHeader, buffer, sizeof(struct xar_header));
6822             if (sys::IsLittleEndianHost)
6823               swapStruct(XarHeader);
6824             if (XarHeader.magic == XAR_HEADER_MAGIC)
6825               DumpBitcodeSection(O, buffer, member_size, verbose,
6826                                  PrintXarHeader, PrintXarFileHeaders,
6827                                  XarMemberName);
6828           }
6829           XarMemberName = OldXarMemberName;
6830           delete buffer;
6831         }
6832       }
6833     }
6834   }
6835 }
6836 #endif // defined(HAVE_LIBXAR)
6837 
6838 static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
6839   if (O->is64Bit())
6840     printObjc2_64bit_MetaData(O, verbose);
6841   else {
6842     MachO::mach_header H;
6843     H = O->getHeader();
6844     if (H.cputype == MachO::CPU_TYPE_ARM)
6845       printObjc2_32bit_MetaData(O, verbose);
6846     else {
6847       // This is the 32-bit non-arm cputype case.  Which is normally
6848       // the first Objective-C ABI.  But it may be the case of a
6849       // binary for the iOS simulator which is the second Objective-C
6850       // ABI.  In that case printObjc1_32bit_MetaData() will determine that
6851       // and return false.
6852       if (!printObjc1_32bit_MetaData(O, verbose))
6853         printObjc2_32bit_MetaData(O, verbose);
6854     }
6855   }
6856 }
6857 
6858 // GuessLiteralPointer returns a string which for the item in the Mach-O file
6859 // for the address passed in as ReferenceValue for printing as a comment with
6860 // the instruction and also returns the corresponding type of that item
6861 // indirectly through ReferenceType.
6862 //
6863 // If ReferenceValue is an address of literal cstring then a pointer to the
6864 // cstring is returned and ReferenceType is set to
6865 // LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
6866 //
6867 // If ReferenceValue is an address of an Objective-C CFString, Selector ref or
6868 // Class ref that name is returned and the ReferenceType is set accordingly.
6869 //
6870 // Lastly, literals which are Symbol address in a literal pool are looked for
6871 // and if found the symbol name is returned and ReferenceType is set to
6872 // LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
6873 //
6874 // If there is no item in the Mach-O file for the address passed in as
6875 // ReferenceValue nullptr is returned and ReferenceType is unchanged.
6876 static const char *GuessLiteralPointer(uint64_t ReferenceValue,
6877                                        uint64_t ReferencePC,
6878                                        uint64_t *ReferenceType,
6879                                        struct DisassembleInfo *info) {
6880   // First see if there is an external relocation entry at the ReferencePC.
6881   if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
6882     uint64_t sect_addr = info->S.getAddress();
6883     uint64_t sect_offset = ReferencePC - sect_addr;
6884     bool reloc_found = false;
6885     DataRefImpl Rel;
6886     MachO::any_relocation_info RE;
6887     bool isExtern = false;
6888     SymbolRef Symbol;
6889     for (const RelocationRef &Reloc : info->S.relocations()) {
6890       uint64_t RelocOffset = Reloc.getOffset();
6891       if (RelocOffset == sect_offset) {
6892         Rel = Reloc.getRawDataRefImpl();
6893         RE = info->O->getRelocation(Rel);
6894         if (info->O->isRelocationScattered(RE))
6895           continue;
6896         isExtern = info->O->getPlainRelocationExternal(RE);
6897         if (isExtern) {
6898           symbol_iterator RelocSym = Reloc.getSymbol();
6899           Symbol = *RelocSym;
6900         }
6901         reloc_found = true;
6902         break;
6903       }
6904     }
6905     // If there is an external relocation entry for a symbol in a section
6906     // then used that symbol's value for the value of the reference.
6907     if (reloc_found && isExtern) {
6908       if (info->O->getAnyRelocationPCRel(RE)) {
6909         unsigned Type = info->O->getAnyRelocationType(RE);
6910         if (Type == MachO::X86_64_RELOC_SIGNED) {
6911           ReferenceValue = cantFail(Symbol.getValue());
6912         }
6913       }
6914     }
6915   }
6916 
6917   // Look for literals such as Objective-C CFStrings refs, Selector refs,
6918   // Message refs and Class refs.
6919   bool classref, selref, msgref, cfstring;
6920   uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
6921                                                selref, msgref, cfstring);
6922   if (classref && pointer_value == 0) {
6923     // Note the ReferenceValue is a pointer into the __objc_classrefs section.
6924     // And the pointer_value in that section is typically zero as it will be
6925     // set by dyld as part of the "bind information".
6926     const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
6927     if (name != nullptr) {
6928       *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
6929       const char *class_name = strrchr(name, '$');
6930       if (class_name != nullptr && class_name[1] == '_' &&
6931           class_name[2] != '\0') {
6932         info->class_name = class_name + 2;
6933         return name;
6934       }
6935     }
6936   }
6937 
6938   if (classref) {
6939     *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
6940     const char *name =
6941         get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
6942     if (name != nullptr)
6943       info->class_name = name;
6944     else
6945       name = "bad class ref";
6946     return name;
6947   }
6948 
6949   if (cfstring) {
6950     *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
6951     const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
6952     return name;
6953   }
6954 
6955   if (selref && pointer_value == 0)
6956     pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
6957 
6958   if (pointer_value != 0)
6959     ReferenceValue = pointer_value;
6960 
6961   const char *name = GuessCstringPointer(ReferenceValue, info);
6962   if (name) {
6963     if (pointer_value != 0 && selref) {
6964       *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
6965       info->selector_name = name;
6966     } else if (pointer_value != 0 && msgref) {
6967       info->class_name = nullptr;
6968       *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
6969       info->selector_name = name;
6970     } else
6971       *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
6972     return name;
6973   }
6974 
6975   // Lastly look for an indirect symbol with this ReferenceValue which is in
6976   // a literal pool.  If found return that symbol name.
6977   name = GuessIndirectSymbol(ReferenceValue, info);
6978   if (name) {
6979     *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
6980     return name;
6981   }
6982 
6983   return nullptr;
6984 }
6985 
6986 // SymbolizerSymbolLookUp is the symbol lookup function passed when creating
6987 // the Symbolizer.  It looks up the ReferenceValue using the info passed via the
6988 // pointer to the struct DisassembleInfo that was passed when MCSymbolizer
6989 // is created and returns the symbol name that matches the ReferenceValue or
6990 // nullptr if none.  The ReferenceType is passed in for the IN type of
6991 // reference the instruction is making from the values in defined in the header
6992 // "llvm-c/Disassembler.h".  On return the ReferenceType can set to a specific
6993 // Out type and the ReferenceName will also be set which is added as a comment
6994 // to the disassembled instruction.
6995 //
6996 // If the symbol name is a C++ mangled name then the demangled name is
6997 // returned through ReferenceName and ReferenceType is set to
6998 // LLVMDisassembler_ReferenceType_DeMangled_Name .
6999 //
7000 // When this is called to get a symbol name for a branch target then the
7001 // ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
7002 // SymbolValue will be looked for in the indirect symbol table to determine if
7003 // it is an address for a symbol stub.  If so then the symbol name for that
7004 // stub is returned indirectly through ReferenceName and then ReferenceType is
7005 // set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
7006 //
7007 // When this is called with an value loaded via a PC relative load then
7008 // ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
7009 // SymbolValue is checked to be an address of literal pointer, symbol pointer,
7010 // or an Objective-C meta data reference.  If so the output ReferenceType is
7011 // set to correspond to that as well as setting the ReferenceName.
7012 static const char *SymbolizerSymbolLookUp(void *DisInfo,
7013                                           uint64_t ReferenceValue,
7014                                           uint64_t *ReferenceType,
7015                                           uint64_t ReferencePC,
7016                                           const char **ReferenceName) {
7017   struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
7018   // If no verbose symbolic information is wanted then just return nullptr.
7019   if (!info->verbose) {
7020     *ReferenceName = nullptr;
7021     *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7022     return nullptr;
7023   }
7024 
7025   const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
7026 
7027   if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
7028     *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
7029     if (*ReferenceName != nullptr) {
7030       method_reference(info, ReferenceType, ReferenceName);
7031       if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
7032         *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
7033     } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
7034       if (info->demangled_name != nullptr)
7035         free(info->demangled_name);
7036       int status;
7037       info->demangled_name =
7038           itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
7039       if (info->demangled_name != nullptr) {
7040         *ReferenceName = info->demangled_name;
7041         *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
7042       } else
7043         *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7044     } else
7045       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7046   } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
7047     *ReferenceName =
7048         GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7049     if (*ReferenceName)
7050       method_reference(info, ReferenceType, ReferenceName);
7051     else
7052       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7053     // If this is arm64 and the reference is an adrp instruction save the
7054     // instruction, passed in ReferenceValue and the address of the instruction
7055     // for use later if we see and add immediate instruction.
7056   } else if (info->O->getArch() == Triple::aarch64 &&
7057              *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
7058     info->adrp_inst = ReferenceValue;
7059     info->adrp_addr = ReferencePC;
7060     SymbolName = nullptr;
7061     *ReferenceName = nullptr;
7062     *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7063     // If this is arm64 and reference is an add immediate instruction and we
7064     // have
7065     // seen an adrp instruction just before it and the adrp's Xd register
7066     // matches
7067     // this add's Xn register reconstruct the value being referenced and look to
7068     // see if it is a literal pointer.  Note the add immediate instruction is
7069     // passed in ReferenceValue.
7070   } else if (info->O->getArch() == Triple::aarch64 &&
7071              *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
7072              ReferencePC - 4 == info->adrp_addr &&
7073              (info->adrp_inst & 0x9f000000) == 0x90000000 &&
7074              (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
7075     uint32_t addxri_inst;
7076     uint64_t adrp_imm, addxri_imm;
7077 
7078     adrp_imm =
7079         ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
7080     if (info->adrp_inst & 0x0200000)
7081       adrp_imm |= 0xfffffffffc000000LL;
7082 
7083     addxri_inst = ReferenceValue;
7084     addxri_imm = (addxri_inst >> 10) & 0xfff;
7085     if (((addxri_inst >> 22) & 0x3) == 1)
7086       addxri_imm <<= 12;
7087 
7088     ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
7089                      (adrp_imm << 12) + addxri_imm;
7090 
7091     *ReferenceName =
7092         GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7093     if (*ReferenceName == nullptr)
7094       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7095     // If this is arm64 and the reference is a load register instruction and we
7096     // have seen an adrp instruction just before it and the adrp's Xd register
7097     // matches this add's Xn register reconstruct the value being referenced and
7098     // look to see if it is a literal pointer.  Note the load register
7099     // instruction is passed in ReferenceValue.
7100   } else if (info->O->getArch() == Triple::aarch64 &&
7101              *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
7102              ReferencePC - 4 == info->adrp_addr &&
7103              (info->adrp_inst & 0x9f000000) == 0x90000000 &&
7104              (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
7105     uint32_t ldrxui_inst;
7106     uint64_t adrp_imm, ldrxui_imm;
7107 
7108     adrp_imm =
7109         ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
7110     if (info->adrp_inst & 0x0200000)
7111       adrp_imm |= 0xfffffffffc000000LL;
7112 
7113     ldrxui_inst = ReferenceValue;
7114     ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
7115 
7116     ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
7117                      (adrp_imm << 12) + (ldrxui_imm << 3);
7118 
7119     *ReferenceName =
7120         GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7121     if (*ReferenceName == nullptr)
7122       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7123   }
7124   // If this arm64 and is an load register (PC-relative) instruction the
7125   // ReferenceValue is the PC plus the immediate value.
7126   else if (info->O->getArch() == Triple::aarch64 &&
7127            (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
7128             *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
7129     *ReferenceName =
7130         GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7131     if (*ReferenceName == nullptr)
7132       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7133   } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
7134     if (info->demangled_name != nullptr)
7135       free(info->demangled_name);
7136     int status;
7137     info->demangled_name =
7138         itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
7139     if (info->demangled_name != nullptr) {
7140       *ReferenceName = info->demangled_name;
7141       *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
7142     }
7143   }
7144   else {
7145     *ReferenceName = nullptr;
7146     *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7147   }
7148 
7149   return SymbolName;
7150 }
7151 
7152 /// Emits the comments that are stored in the CommentStream.
7153 /// Each comment in the CommentStream must end with a newline.
7154 static void emitComments(raw_svector_ostream &CommentStream,
7155                          SmallString<128> &CommentsToEmit,
7156                          formatted_raw_ostream &FormattedOS,
7157                          const MCAsmInfo &MAI) {
7158   // Flush the stream before taking its content.
7159   StringRef Comments = CommentsToEmit.str();
7160   // Get the default information for printing a comment.
7161   StringRef CommentBegin = MAI.getCommentString();
7162   unsigned CommentColumn = MAI.getCommentColumn();
7163   bool IsFirst = true;
7164   while (!Comments.empty()) {
7165     if (!IsFirst)
7166       FormattedOS << '\n';
7167     // Emit a line of comments.
7168     FormattedOS.PadToColumn(CommentColumn);
7169     size_t Position = Comments.find('\n');
7170     FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
7171     // Move after the newline character.
7172     Comments = Comments.substr(Position + 1);
7173     IsFirst = false;
7174   }
7175   FormattedOS.flush();
7176 
7177   // Tell the comment stream that the vector changed underneath it.
7178   CommentsToEmit.clear();
7179 }
7180 
7181 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
7182                              StringRef DisSegName, StringRef DisSectName) {
7183   const char *McpuDefault = nullptr;
7184   const Target *ThumbTarget = nullptr;
7185   const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
7186   if (!TheTarget) {
7187     // GetTarget prints out stuff.
7188     return;
7189   }
7190   std::string MachOMCPU;
7191   if (MCPU.empty() && McpuDefault)
7192     MachOMCPU = McpuDefault;
7193   else
7194     MachOMCPU = MCPU;
7195 
7196 #define CHECK_TARGET_INFO_CREATION(NAME)                                       \
7197   do {                                                                         \
7198     if (!NAME) {                                                               \
7199       WithColor::error(errs(), "llvm-objdump")                                 \
7200           << "couldn't initialize disassembler for target " << TripleName      \
7201           << '\n';                                                             \
7202       return;                                                                  \
7203     }                                                                          \
7204   } while (false)
7205 #define CHECK_THUMB_TARGET_INFO_CREATION(NAME)                                 \
7206   do {                                                                         \
7207     if (!NAME) {                                                               \
7208       WithColor::error(errs(), "llvm-objdump")                                 \
7209           << "couldn't initialize disassembler for target " << ThumbTripleName \
7210           << '\n';                                                             \
7211       return;                                                                  \
7212     }                                                                          \
7213   } while (false)
7214 
7215   std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
7216   CHECK_TARGET_INFO_CREATION(InstrInfo);
7217   std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
7218   if (ThumbTarget) {
7219     ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
7220     CHECK_THUMB_TARGET_INFO_CREATION(ThumbInstrInfo);
7221   }
7222 
7223   // Package up features to be passed to target/subtarget
7224   std::string FeaturesStr;
7225   if (!MAttrs.empty()) {
7226     SubtargetFeatures Features;
7227     for (unsigned i = 0; i != MAttrs.size(); ++i)
7228       Features.AddFeature(MAttrs[i]);
7229     FeaturesStr = Features.getString();
7230   }
7231 
7232   MCTargetOptions MCOptions;
7233   // Set up disassembler.
7234   std::unique_ptr<const MCRegisterInfo> MRI(
7235       TheTarget->createMCRegInfo(TripleName));
7236   CHECK_TARGET_INFO_CREATION(MRI);
7237   std::unique_ptr<const MCAsmInfo> AsmInfo(
7238       TheTarget->createMCAsmInfo(*MRI, TripleName, MCOptions));
7239   CHECK_TARGET_INFO_CREATION(AsmInfo);
7240   std::unique_ptr<const MCSubtargetInfo> STI(
7241       TheTarget->createMCSubtargetInfo(TripleName, MachOMCPU, FeaturesStr));
7242   CHECK_TARGET_INFO_CREATION(STI);
7243   MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
7244   std::unique_ptr<MCDisassembler> DisAsm(
7245       TheTarget->createMCDisassembler(*STI, Ctx));
7246   CHECK_TARGET_INFO_CREATION(DisAsm);
7247   std::unique_ptr<MCSymbolizer> Symbolizer;
7248   struct DisassembleInfo SymbolizerInfo(nullptr, nullptr, nullptr, false);
7249   std::unique_ptr<MCRelocationInfo> RelInfo(
7250       TheTarget->createMCRelocationInfo(TripleName, Ctx));
7251   if (RelInfo) {
7252     Symbolizer.reset(TheTarget->createMCSymbolizer(
7253         TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
7254         &SymbolizerInfo, &Ctx, std::move(RelInfo)));
7255     DisAsm->setSymbolizer(std::move(Symbolizer));
7256   }
7257   int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
7258   std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
7259       Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
7260   CHECK_TARGET_INFO_CREATION(IP);
7261   // Set the display preference for hex vs. decimal immediates.
7262   IP->setPrintImmHex(PrintImmHex);
7263   // Comment stream and backing vector.
7264   SmallString<128> CommentsToEmit;
7265   raw_svector_ostream CommentStream(CommentsToEmit);
7266   // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
7267   // if it is done then arm64 comments for string literals don't get printed
7268   // and some constant get printed instead and not setting it causes intel
7269   // (32-bit and 64-bit) comments printed with different spacing before the
7270   // comment causing different diffs with the 'C' disassembler library API.
7271   // IP->setCommentStream(CommentStream);
7272 
7273   // Set up separate thumb disassembler if needed.
7274   std::unique_ptr<const MCRegisterInfo> ThumbMRI;
7275   std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
7276   std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
7277   std::unique_ptr<MCDisassembler> ThumbDisAsm;
7278   std::unique_ptr<MCInstPrinter> ThumbIP;
7279   std::unique_ptr<MCContext> ThumbCtx;
7280   std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
7281   struct DisassembleInfo ThumbSymbolizerInfo(nullptr, nullptr, nullptr, false);
7282   std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
7283   if (ThumbTarget) {
7284     ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
7285     CHECK_THUMB_TARGET_INFO_CREATION(ThumbMRI);
7286     ThumbAsmInfo.reset(
7287         ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName, MCOptions));
7288     CHECK_THUMB_TARGET_INFO_CREATION(ThumbAsmInfo);
7289     ThumbSTI.reset(
7290         ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MachOMCPU,
7291                                            FeaturesStr));
7292     CHECK_THUMB_TARGET_INFO_CREATION(ThumbSTI);
7293     ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
7294     ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
7295     CHECK_THUMB_TARGET_INFO_CREATION(ThumbDisAsm);
7296     MCContext *PtrThumbCtx = ThumbCtx.get();
7297     ThumbRelInfo.reset(
7298         ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
7299     if (ThumbRelInfo) {
7300       ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
7301           ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
7302           &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
7303       ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
7304     }
7305     int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
7306     ThumbIP.reset(ThumbTarget->createMCInstPrinter(
7307         Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
7308         *ThumbInstrInfo, *ThumbMRI));
7309     CHECK_THUMB_TARGET_INFO_CREATION(ThumbIP);
7310     // Set the display preference for hex vs. decimal immediates.
7311     ThumbIP->setPrintImmHex(PrintImmHex);
7312   }
7313 
7314 #undef CHECK_TARGET_INFO_CREATION
7315 #undef CHECK_THUMB_TARGET_INFO_CREATION
7316 
7317   MachO::mach_header Header = MachOOF->getHeader();
7318 
7319   // FIXME: Using the -cfg command line option, this code used to be able to
7320   // annotate relocations with the referenced symbol's name, and if this was
7321   // inside a __[cf]string section, the data it points to. This is now replaced
7322   // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
7323   std::vector<SectionRef> Sections;
7324   std::vector<SymbolRef> Symbols;
7325   SmallVector<uint64_t, 8> FoundFns;
7326   uint64_t BaseSegmentAddress = 0;
7327 
7328   getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
7329                         BaseSegmentAddress);
7330 
7331   // Sort the symbols by address, just in case they didn't come in that way.
7332   llvm::sort(Symbols, SymbolSorter());
7333 
7334   // Build a data in code table that is sorted on by the address of each entry.
7335   uint64_t BaseAddress = 0;
7336   if (Header.filetype == MachO::MH_OBJECT)
7337     BaseAddress = Sections[0].getAddress();
7338   else
7339     BaseAddress = BaseSegmentAddress;
7340   DiceTable Dices;
7341   for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
7342        DI != DE; ++DI) {
7343     uint32_t Offset;
7344     DI->getOffset(Offset);
7345     Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
7346   }
7347   array_pod_sort(Dices.begin(), Dices.end());
7348 
7349   // Try to find debug info and set up the DIContext for it.
7350   std::unique_ptr<DIContext> diContext;
7351   std::unique_ptr<Binary> DSYMBinary;
7352   std::unique_ptr<MemoryBuffer> DSYMBuf;
7353   if (UseDbg) {
7354     ObjectFile *DbgObj = MachOOF;
7355 
7356     // A separate DSym file path was specified, parse it as a macho file,
7357     // get the sections and supply it to the section name parsing machinery.
7358     if (!DSYMFile.empty()) {
7359       std::string DSYMPath(DSYMFile);
7360 
7361       // If DSYMPath is a .dSYM directory, append the Mach-O file.
7362       if (llvm::sys::fs::is_directory(DSYMPath) &&
7363           llvm::sys::path::extension(DSYMPath) == ".dSYM") {
7364         SmallString<128> ShortName(llvm::sys::path::filename(DSYMPath));
7365         llvm::sys::path::replace_extension(ShortName, "");
7366         SmallString<1024> FullPath(DSYMPath);
7367         llvm::sys::path::append(FullPath, "Contents", "Resources", "DWARF",
7368                                 ShortName);
7369         DSYMPath = std::string(FullPath.str());
7370       }
7371 
7372       // Load the file.
7373       ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
7374           MemoryBuffer::getFileOrSTDIN(DSYMPath);
7375       if (std::error_code EC = BufOrErr.getError()) {
7376         reportError(errorCodeToError(EC), DSYMPath);
7377         return;
7378       }
7379 
7380       // We need to keep the file alive, because we're replacing DbgObj with it.
7381       DSYMBuf = std::move(BufOrErr.get());
7382 
7383       Expected<std::unique_ptr<Binary>> BinaryOrErr =
7384       createBinary(DSYMBuf.get()->getMemBufferRef());
7385       if (!BinaryOrErr) {
7386         reportError(BinaryOrErr.takeError(), DSYMPath);
7387         return;
7388       }
7389 
7390       // We need to keep the Binary alive with the buffer
7391       DSYMBinary = std::move(BinaryOrErr.get());
7392       if (ObjectFile *O = dyn_cast<ObjectFile>(DSYMBinary.get())) {
7393         // this is a Mach-O object file, use it
7394         if (MachOObjectFile *MachDSYM = dyn_cast<MachOObjectFile>(&*O)) {
7395           DbgObj = MachDSYM;
7396         }
7397         else {
7398           WithColor::error(errs(), "llvm-objdump")
7399             << DSYMPath << " is not a Mach-O file type.\n";
7400           return;
7401         }
7402       }
7403       else if (auto UB = dyn_cast<MachOUniversalBinary>(DSYMBinary.get())){
7404         // this is a Universal Binary, find a Mach-O for this architecture
7405         uint32_t CPUType, CPUSubType;
7406         const char *ArchFlag;
7407         if (MachOOF->is64Bit()) {
7408           const MachO::mach_header_64 H_64 = MachOOF->getHeader64();
7409           CPUType = H_64.cputype;
7410           CPUSubType = H_64.cpusubtype;
7411         } else {
7412           const MachO::mach_header H = MachOOF->getHeader();
7413           CPUType = H.cputype;
7414           CPUSubType = H.cpusubtype;
7415         }
7416         Triple T = MachOObjectFile::getArchTriple(CPUType, CPUSubType, nullptr,
7417                                                   &ArchFlag);
7418         Expected<std::unique_ptr<MachOObjectFile>> MachDSYM =
7419             UB->getMachOObjectForArch(ArchFlag);
7420         if (!MachDSYM) {
7421           reportError(MachDSYM.takeError(), DSYMPath);
7422           return;
7423         }
7424 
7425         // We need to keep the Binary alive with the buffer
7426         DbgObj = &*MachDSYM.get();
7427         DSYMBinary = std::move(*MachDSYM);
7428       }
7429       else {
7430         WithColor::error(errs(), "llvm-objdump")
7431           << DSYMPath << " is not a Mach-O or Universal file type.\n";
7432         return;
7433       }
7434     }
7435 
7436     // Setup the DIContext
7437     diContext = DWARFContext::create(*DbgObj);
7438   }
7439 
7440   if (FilterSections.empty())
7441     outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
7442 
7443   for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
7444     Expected<StringRef> SecNameOrErr = Sections[SectIdx].getName();
7445     if (!SecNameOrErr) {
7446       consumeError(SecNameOrErr.takeError());
7447       continue;
7448     }
7449     if (*SecNameOrErr != DisSectName)
7450       continue;
7451 
7452     DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
7453 
7454     StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
7455     if (SegmentName != DisSegName)
7456       continue;
7457 
7458     StringRef BytesStr =
7459         unwrapOrError(Sections[SectIdx].getContents(), Filename);
7460     ArrayRef<uint8_t> Bytes = arrayRefFromStringRef(BytesStr);
7461     uint64_t SectAddress = Sections[SectIdx].getAddress();
7462 
7463     bool symbolTableWorked = false;
7464 
7465     // Create a map of symbol addresses to symbol names for use by
7466     // the SymbolizerSymbolLookUp() routine.
7467     SymbolAddressMap AddrMap;
7468     bool DisSymNameFound = false;
7469     for (const SymbolRef &Symbol : MachOOF->symbols()) {
7470       SymbolRef::Type ST =
7471           unwrapOrError(Symbol.getType(), MachOOF->getFileName());
7472       if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
7473           ST == SymbolRef::ST_Other) {
7474         uint64_t Address = cantFail(Symbol.getValue());
7475         StringRef SymName =
7476             unwrapOrError(Symbol.getName(), MachOOF->getFileName());
7477         AddrMap[Address] = SymName;
7478         if (!DisSymName.empty() && DisSymName == SymName)
7479           DisSymNameFound = true;
7480       }
7481     }
7482     if (!DisSymName.empty() && !DisSymNameFound) {
7483       outs() << "Can't find -dis-symname: " << DisSymName << "\n";
7484       return;
7485     }
7486     // Set up the block of info used by the Symbolizer call backs.
7487     SymbolizerInfo.verbose = !NoSymbolicOperands;
7488     SymbolizerInfo.O = MachOOF;
7489     SymbolizerInfo.S = Sections[SectIdx];
7490     SymbolizerInfo.AddrMap = &AddrMap;
7491     SymbolizerInfo.Sections = &Sections;
7492     // Same for the ThumbSymbolizer
7493     ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
7494     ThumbSymbolizerInfo.O = MachOOF;
7495     ThumbSymbolizerInfo.S = Sections[SectIdx];
7496     ThumbSymbolizerInfo.AddrMap = &AddrMap;
7497     ThumbSymbolizerInfo.Sections = &Sections;
7498 
7499     unsigned int Arch = MachOOF->getArch();
7500 
7501     // Skip all symbols if this is a stubs file.
7502     if (Bytes.empty())
7503       return;
7504 
7505     // If the section has symbols but no symbol at the start of the section
7506     // these are used to make sure the bytes before the first symbol are
7507     // disassembled.
7508     bool FirstSymbol = true;
7509     bool FirstSymbolAtSectionStart = true;
7510 
7511     // Disassemble symbol by symbol.
7512     for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
7513       StringRef SymName =
7514           unwrapOrError(Symbols[SymIdx].getName(), MachOOF->getFileName());
7515       SymbolRef::Type ST =
7516           unwrapOrError(Symbols[SymIdx].getType(), MachOOF->getFileName());
7517       if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
7518         continue;
7519 
7520       // Make sure the symbol is defined in this section.
7521       bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
7522       if (!containsSym) {
7523         if (!DisSymName.empty() && DisSymName == SymName) {
7524           outs() << "-dis-symname: " << DisSymName << " not in the section\n";
7525           return;
7526         }
7527         continue;
7528       }
7529       // The __mh_execute_header is special and we need to deal with that fact
7530       // this symbol is before the start of the (__TEXT,__text) section and at the
7531       // address of the start of the __TEXT segment.  This is because this symbol
7532       // is an N_SECT symbol in the (__TEXT,__text) but its address is before the
7533       // start of the section in a standard MH_EXECUTE filetype.
7534       if (!DisSymName.empty() && DisSymName == "__mh_execute_header") {
7535         outs() << "-dis-symname: __mh_execute_header not in any section\n";
7536         return;
7537       }
7538       // When this code is trying to disassemble a symbol at a time and in the
7539       // case there is only the __mh_execute_header symbol left as in a stripped
7540       // executable, we need to deal with this by ignoring this symbol so the
7541       // whole section is disassembled and this symbol is then not displayed.
7542       if (SymName == "__mh_execute_header" || SymName == "__mh_dylib_header" ||
7543           SymName == "__mh_bundle_header" || SymName == "__mh_object_header" ||
7544           SymName == "__mh_preload_header" || SymName == "__mh_dylinker_header")
7545         continue;
7546 
7547       // If we are only disassembling one symbol see if this is that symbol.
7548       if (!DisSymName.empty() && DisSymName != SymName)
7549         continue;
7550 
7551       // Start at the address of the symbol relative to the section's address.
7552       uint64_t SectSize = Sections[SectIdx].getSize();
7553       uint64_t Start = cantFail(Symbols[SymIdx].getValue());
7554       uint64_t SectionAddress = Sections[SectIdx].getAddress();
7555       Start -= SectionAddress;
7556 
7557       if (Start > SectSize) {
7558         outs() << "section data ends, " << SymName
7559                << " lies outside valid range\n";
7560         return;
7561       }
7562 
7563       // Stop disassembling either at the beginning of the next symbol or at
7564       // the end of the section.
7565       bool containsNextSym = false;
7566       uint64_t NextSym = 0;
7567       uint64_t NextSymIdx = SymIdx + 1;
7568       while (Symbols.size() > NextSymIdx) {
7569         SymbolRef::Type NextSymType = unwrapOrError(
7570             Symbols[NextSymIdx].getType(), MachOOF->getFileName());
7571         if (NextSymType == SymbolRef::ST_Function) {
7572           containsNextSym =
7573               Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
7574           NextSym = cantFail(Symbols[NextSymIdx].getValue());
7575           NextSym -= SectionAddress;
7576           break;
7577         }
7578         ++NextSymIdx;
7579       }
7580 
7581       uint64_t End = containsNextSym ? std::min(NextSym, SectSize) : SectSize;
7582       uint64_t Size;
7583 
7584       symbolTableWorked = true;
7585 
7586       DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
7587       uint32_t SymbolFlags = cantFail(MachOOF->getSymbolFlags(Symb));
7588       bool IsThumb = SymbolFlags & SymbolRef::SF_Thumb;
7589 
7590       // We only need the dedicated Thumb target if there's a real choice
7591       // (i.e. we're not targeting M-class) and the function is Thumb.
7592       bool UseThumbTarget = IsThumb && ThumbTarget;
7593 
7594       // If we are not specifying a symbol to start disassembly with and this
7595       // is the first symbol in the section but not at the start of the section
7596       // then move the disassembly index to the start of the section and
7597       // don't print the symbol name just yet.  This is so the bytes before the
7598       // first symbol are disassembled.
7599       uint64_t SymbolStart = Start;
7600       if (DisSymName.empty() && FirstSymbol && Start != 0) {
7601         FirstSymbolAtSectionStart = false;
7602         Start = 0;
7603       }
7604       else
7605         outs() << SymName << ":\n";
7606 
7607       DILineInfo lastLine;
7608       for (uint64_t Index = Start; Index < End; Index += Size) {
7609         MCInst Inst;
7610 
7611         // If this is the first symbol in the section and it was not at the
7612         // start of the section, see if we are at its Index now and if so print
7613         // the symbol name.
7614         if (FirstSymbol && !FirstSymbolAtSectionStart && Index == SymbolStart)
7615           outs() << SymName << ":\n";
7616 
7617         uint64_t PC = SectAddress + Index;
7618         if (!NoLeadingAddr) {
7619           if (FullLeadingAddr) {
7620             if (MachOOF->is64Bit())
7621               outs() << format("%016" PRIx64, PC);
7622             else
7623               outs() << format("%08" PRIx64, PC);
7624           } else {
7625             outs() << format("%8" PRIx64 ":", PC);
7626           }
7627         }
7628         if (!NoShowRawInsn || Arch == Triple::arm)
7629           outs() << "\t";
7630 
7631         if (DumpAndSkipDataInCode(PC, Bytes.data() + Index, Dices, Size))
7632           continue;
7633 
7634         SmallVector<char, 64> AnnotationsBytes;
7635         raw_svector_ostream Annotations(AnnotationsBytes);
7636 
7637         bool gotInst;
7638         if (UseThumbTarget)
7639           gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
7640                                                 PC, Annotations);
7641         else
7642           gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
7643                                            Annotations);
7644         if (gotInst) {
7645           if (!NoShowRawInsn || Arch == Triple::arm) {
7646             dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
7647           }
7648           formatted_raw_ostream FormattedOS(outs());
7649           StringRef AnnotationsStr = Annotations.str();
7650           if (UseThumbTarget)
7651             ThumbIP->printInst(&Inst, PC, AnnotationsStr, *ThumbSTI,
7652                                FormattedOS);
7653           else
7654             IP->printInst(&Inst, PC, AnnotationsStr, *STI, FormattedOS);
7655           emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
7656 
7657           // Print debug info.
7658           if (diContext) {
7659             DILineInfo dli = diContext->getLineInfoForAddress({PC, SectIdx});
7660             // Print valid line info if it changed.
7661             if (dli != lastLine && dli.Line != 0)
7662               outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
7663                      << dli.Column;
7664             lastLine = dli;
7665           }
7666           outs() << "\n";
7667         } else {
7668           if (MachOOF->getArchTriple().isX86()) {
7669             outs() << format("\t.byte 0x%02x #bad opcode\n",
7670                              *(Bytes.data() + Index) & 0xff);
7671             Size = 1; // skip exactly one illegible byte and move on.
7672           } else if (Arch == Triple::aarch64 ||
7673                      (Arch == Triple::arm && !IsThumb)) {
7674             uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7675                               (*(Bytes.data() + Index + 1) & 0xff) << 8 |
7676                               (*(Bytes.data() + Index + 2) & 0xff) << 16 |
7677                               (*(Bytes.data() + Index + 3) & 0xff) << 24;
7678             outs() << format("\t.long\t0x%08x\n", opcode);
7679             Size = 4;
7680           } else if (Arch == Triple::arm) {
7681             assert(IsThumb && "ARM mode should have been dealt with above");
7682             uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7683                               (*(Bytes.data() + Index + 1) & 0xff) << 8;
7684             outs() << format("\t.short\t0x%04x\n", opcode);
7685             Size = 2;
7686           } else{
7687             WithColor::warning(errs(), "llvm-objdump")
7688                 << "invalid instruction encoding\n";
7689             if (Size == 0)
7690               Size = 1; // skip illegible bytes
7691           }
7692         }
7693       }
7694       // Now that we are done disassembled the first symbol set the bool that
7695       // were doing this to false.
7696       FirstSymbol = false;
7697     }
7698     if (!symbolTableWorked) {
7699       // Reading the symbol table didn't work, disassemble the whole section.
7700       uint64_t SectAddress = Sections[SectIdx].getAddress();
7701       uint64_t SectSize = Sections[SectIdx].getSize();
7702       uint64_t InstSize;
7703       for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
7704         MCInst Inst;
7705 
7706         uint64_t PC = SectAddress + Index;
7707 
7708         if (DumpAndSkipDataInCode(PC, Bytes.data() + Index, Dices, InstSize))
7709           continue;
7710 
7711         SmallVector<char, 64> AnnotationsBytes;
7712         raw_svector_ostream Annotations(AnnotationsBytes);
7713         if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
7714                                    Annotations)) {
7715           if (!NoLeadingAddr) {
7716             if (FullLeadingAddr) {
7717               if (MachOOF->is64Bit())
7718                 outs() << format("%016" PRIx64, PC);
7719               else
7720                 outs() << format("%08" PRIx64, PC);
7721             } else {
7722               outs() << format("%8" PRIx64 ":", PC);
7723             }
7724           }
7725           if (!NoShowRawInsn || Arch == Triple::arm) {
7726             outs() << "\t";
7727             dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
7728           }
7729           StringRef AnnotationsStr = Annotations.str();
7730           IP->printInst(&Inst, PC, AnnotationsStr, *STI, outs());
7731           outs() << "\n";
7732         } else {
7733           if (MachOOF->getArchTriple().isX86()) {
7734             outs() << format("\t.byte 0x%02x #bad opcode\n",
7735                              *(Bytes.data() + Index) & 0xff);
7736             InstSize = 1; // skip exactly one illegible byte and move on.
7737           } else {
7738             WithColor::warning(errs(), "llvm-objdump")
7739                 << "invalid instruction encoding\n";
7740             if (InstSize == 0)
7741               InstSize = 1; // skip illegible bytes
7742           }
7743         }
7744       }
7745     }
7746     // The TripleName's need to be reset if we are called again for a different
7747     // architecture.
7748     TripleName = "";
7749     ThumbTripleName = "";
7750 
7751     if (SymbolizerInfo.demangled_name != nullptr)
7752       free(SymbolizerInfo.demangled_name);
7753     if (ThumbSymbolizerInfo.demangled_name != nullptr)
7754       free(ThumbSymbolizerInfo.demangled_name);
7755   }
7756 }
7757 
7758 //===----------------------------------------------------------------------===//
7759 // __compact_unwind section dumping
7760 //===----------------------------------------------------------------------===//
7761 
7762 namespace {
7763 
7764 template <typename T>
7765 static uint64_t read(StringRef Contents, ptrdiff_t Offset) {
7766   using llvm::support::little;
7767   using llvm::support::unaligned;
7768 
7769   if (Offset + sizeof(T) > Contents.size()) {
7770     outs() << "warning: attempt to read past end of buffer\n";
7771     return T();
7772   }
7773 
7774   uint64_t Val =
7775       support::endian::read<T, little, unaligned>(Contents.data() + Offset);
7776   return Val;
7777 }
7778 
7779 template <typename T>
7780 static uint64_t readNext(StringRef Contents, ptrdiff_t &Offset) {
7781   T Val = read<T>(Contents, Offset);
7782   Offset += sizeof(T);
7783   return Val;
7784 }
7785 
7786 struct CompactUnwindEntry {
7787   uint32_t OffsetInSection;
7788 
7789   uint64_t FunctionAddr;
7790   uint32_t Length;
7791   uint32_t CompactEncoding;
7792   uint64_t PersonalityAddr;
7793   uint64_t LSDAAddr;
7794 
7795   RelocationRef FunctionReloc;
7796   RelocationRef PersonalityReloc;
7797   RelocationRef LSDAReloc;
7798 
7799   CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
7800       : OffsetInSection(Offset) {
7801     if (Is64)
7802       read<uint64_t>(Contents, Offset);
7803     else
7804       read<uint32_t>(Contents, Offset);
7805   }
7806 
7807 private:
7808   template <typename UIntPtr> void read(StringRef Contents, ptrdiff_t Offset) {
7809     FunctionAddr = readNext<UIntPtr>(Contents, Offset);
7810     Length = readNext<uint32_t>(Contents, Offset);
7811     CompactEncoding = readNext<uint32_t>(Contents, Offset);
7812     PersonalityAddr = readNext<UIntPtr>(Contents, Offset);
7813     LSDAAddr = readNext<UIntPtr>(Contents, Offset);
7814   }
7815 };
7816 }
7817 
7818 /// Given a relocation from __compact_unwind, consisting of the RelocationRef
7819 /// and data being relocated, determine the best base Name and Addend to use for
7820 /// display purposes.
7821 ///
7822 /// 1. An Extern relocation will directly reference a symbol (and the data is
7823 ///    then already an addend), so use that.
7824 /// 2. Otherwise the data is an offset in the object file's layout; try to find
7825 //     a symbol before it in the same section, and use the offset from there.
7826 /// 3. Finally, if all that fails, fall back to an offset from the start of the
7827 ///    referenced section.
7828 static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
7829                                       std::map<uint64_t, SymbolRef> &Symbols,
7830                                       const RelocationRef &Reloc, uint64_t Addr,
7831                                       StringRef &Name, uint64_t &Addend) {
7832   if (Reloc.getSymbol() != Obj->symbol_end()) {
7833     Name = unwrapOrError(Reloc.getSymbol()->getName(), Obj->getFileName());
7834     Addend = Addr;
7835     return;
7836   }
7837 
7838   auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
7839   SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
7840 
7841   uint64_t SectionAddr = RelocSection.getAddress();
7842 
7843   auto Sym = Symbols.upper_bound(Addr);
7844   if (Sym == Symbols.begin()) {
7845     // The first symbol in the object is after this reference, the best we can
7846     // do is section-relative notation.
7847     if (Expected<StringRef> NameOrErr = RelocSection.getName())
7848       Name = *NameOrErr;
7849     else
7850       consumeError(NameOrErr.takeError());
7851 
7852     Addend = Addr - SectionAddr;
7853     return;
7854   }
7855 
7856   // Go back one so that SymbolAddress <= Addr.
7857   --Sym;
7858 
7859   section_iterator SymSection =
7860       unwrapOrError(Sym->second.getSection(), Obj->getFileName());
7861   if (RelocSection == *SymSection) {
7862     // There's a valid symbol in the same section before this reference.
7863     Name = unwrapOrError(Sym->second.getName(), Obj->getFileName());
7864     Addend = Addr - Sym->first;
7865     return;
7866   }
7867 
7868   // There is a symbol before this reference, but it's in a different
7869   // section. Probably not helpful to mention it, so use the section name.
7870   if (Expected<StringRef> NameOrErr = RelocSection.getName())
7871     Name = *NameOrErr;
7872   else
7873     consumeError(NameOrErr.takeError());
7874 
7875   Addend = Addr - SectionAddr;
7876 }
7877 
7878 static void printUnwindRelocDest(const MachOObjectFile *Obj,
7879                                  std::map<uint64_t, SymbolRef> &Symbols,
7880                                  const RelocationRef &Reloc, uint64_t Addr) {
7881   StringRef Name;
7882   uint64_t Addend;
7883 
7884   if (!Reloc.getObject())
7885     return;
7886 
7887   findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
7888 
7889   outs() << Name;
7890   if (Addend)
7891     outs() << " + " << format("0x%" PRIx64, Addend);
7892 }
7893 
7894 static void
7895 printMachOCompactUnwindSection(const MachOObjectFile *Obj,
7896                                std::map<uint64_t, SymbolRef> &Symbols,
7897                                const SectionRef &CompactUnwind) {
7898 
7899   if (!Obj->isLittleEndian()) {
7900     outs() << "Skipping big-endian __compact_unwind section\n";
7901     return;
7902   }
7903 
7904   bool Is64 = Obj->is64Bit();
7905   uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
7906   uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
7907 
7908   StringRef Contents =
7909       unwrapOrError(CompactUnwind.getContents(), Obj->getFileName());
7910   SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
7911 
7912   // First populate the initial raw offsets, encodings and so on from the entry.
7913   for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
7914     CompactUnwindEntry Entry(Contents, Offset, Is64);
7915     CompactUnwinds.push_back(Entry);
7916   }
7917 
7918   // Next we need to look at the relocations to find out what objects are
7919   // actually being referred to.
7920   for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
7921     uint64_t RelocAddress = Reloc.getOffset();
7922 
7923     uint32_t EntryIdx = RelocAddress / EntrySize;
7924     uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
7925     CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
7926 
7927     if (OffsetInEntry == 0)
7928       Entry.FunctionReloc = Reloc;
7929     else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
7930       Entry.PersonalityReloc = Reloc;
7931     else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
7932       Entry.LSDAReloc = Reloc;
7933     else {
7934       outs() << "Invalid relocation in __compact_unwind section\n";
7935       return;
7936     }
7937   }
7938 
7939   // Finally, we're ready to print the data we've gathered.
7940   outs() << "Contents of __compact_unwind section:\n";
7941   for (auto &Entry : CompactUnwinds) {
7942     outs() << "  Entry at offset "
7943            << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
7944 
7945     // 1. Start of the region this entry applies to.
7946     outs() << "    start:                " << format("0x%" PRIx64,
7947                                                      Entry.FunctionAddr) << ' ';
7948     printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
7949     outs() << '\n';
7950 
7951     // 2. Length of the region this entry applies to.
7952     outs() << "    length:               " << format("0x%" PRIx32, Entry.Length)
7953            << '\n';
7954     // 3. The 32-bit compact encoding.
7955     outs() << "    compact encoding:     "
7956            << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
7957 
7958     // 4. The personality function, if present.
7959     if (Entry.PersonalityReloc.getObject()) {
7960       outs() << "    personality function: "
7961              << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
7962       printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
7963                            Entry.PersonalityAddr);
7964       outs() << '\n';
7965     }
7966 
7967     // 5. This entry's language-specific data area.
7968     if (Entry.LSDAReloc.getObject()) {
7969       outs() << "    LSDA:                 " << format("0x%" PRIx64,
7970                                                        Entry.LSDAAddr) << ' ';
7971       printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
7972       outs() << '\n';
7973     }
7974   }
7975 }
7976 
7977 //===----------------------------------------------------------------------===//
7978 // __unwind_info section dumping
7979 //===----------------------------------------------------------------------===//
7980 
7981 static void printRegularSecondLevelUnwindPage(StringRef PageData) {
7982   ptrdiff_t Pos = 0;
7983   uint32_t Kind = readNext<uint32_t>(PageData, Pos);
7984   (void)Kind;
7985   assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
7986 
7987   uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
7988   uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
7989 
7990   Pos = EntriesStart;
7991   for (unsigned i = 0; i < NumEntries; ++i) {
7992     uint32_t FunctionOffset = readNext<uint32_t>(PageData, Pos);
7993     uint32_t Encoding = readNext<uint32_t>(PageData, Pos);
7994 
7995     outs() << "      [" << i << "]: "
7996            << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7997            << ", "
7998            << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
7999   }
8000 }
8001 
8002 static void printCompressedSecondLevelUnwindPage(
8003     StringRef PageData, uint32_t FunctionBase,
8004     const SmallVectorImpl<uint32_t> &CommonEncodings) {
8005   ptrdiff_t Pos = 0;
8006   uint32_t Kind = readNext<uint32_t>(PageData, Pos);
8007   (void)Kind;
8008   assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
8009 
8010   uint32_t NumCommonEncodings = CommonEncodings.size();
8011   uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
8012   uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
8013 
8014   uint16_t PageEncodingsStart = readNext<uint16_t>(PageData, Pos);
8015   uint16_t NumPageEncodings = readNext<uint16_t>(PageData, Pos);
8016   SmallVector<uint32_t, 64> PageEncodings;
8017   if (NumPageEncodings) {
8018     outs() << "      Page encodings: (count = " << NumPageEncodings << ")\n";
8019     Pos = PageEncodingsStart;
8020     for (unsigned i = 0; i < NumPageEncodings; ++i) {
8021       uint32_t Encoding = readNext<uint32_t>(PageData, Pos);
8022       PageEncodings.push_back(Encoding);
8023       outs() << "        encoding[" << (i + NumCommonEncodings)
8024              << "]: " << format("0x%08" PRIx32, Encoding) << '\n';
8025     }
8026   }
8027 
8028   Pos = EntriesStart;
8029   for (unsigned i = 0; i < NumEntries; ++i) {
8030     uint32_t Entry = readNext<uint32_t>(PageData, Pos);
8031     uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
8032     uint32_t EncodingIdx = Entry >> 24;
8033 
8034     uint32_t Encoding;
8035     if (EncodingIdx < NumCommonEncodings)
8036       Encoding = CommonEncodings[EncodingIdx];
8037     else
8038       Encoding = PageEncodings[EncodingIdx - NumCommonEncodings];
8039 
8040     outs() << "      [" << i << "]: "
8041            << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
8042            << ", "
8043            << "encoding[" << EncodingIdx
8044            << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
8045   }
8046 }
8047 
8048 static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
8049                                         std::map<uint64_t, SymbolRef> &Symbols,
8050                                         const SectionRef &UnwindInfo) {
8051 
8052   if (!Obj->isLittleEndian()) {
8053     outs() << "Skipping big-endian __unwind_info section\n";
8054     return;
8055   }
8056 
8057   outs() << "Contents of __unwind_info section:\n";
8058 
8059   StringRef Contents =
8060       unwrapOrError(UnwindInfo.getContents(), Obj->getFileName());
8061   ptrdiff_t Pos = 0;
8062 
8063   //===----------------------------------
8064   // Section header
8065   //===----------------------------------
8066 
8067   uint32_t Version = readNext<uint32_t>(Contents, Pos);
8068   outs() << "  Version:                                   "
8069          << format("0x%" PRIx32, Version) << '\n';
8070   if (Version != 1) {
8071     outs() << "    Skipping section with unknown version\n";
8072     return;
8073   }
8074 
8075   uint32_t CommonEncodingsStart = readNext<uint32_t>(Contents, Pos);
8076   outs() << "  Common encodings array section offset:     "
8077          << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
8078   uint32_t NumCommonEncodings = readNext<uint32_t>(Contents, Pos);
8079   outs() << "  Number of common encodings in array:       "
8080          << format("0x%" PRIx32, NumCommonEncodings) << '\n';
8081 
8082   uint32_t PersonalitiesStart = readNext<uint32_t>(Contents, Pos);
8083   outs() << "  Personality function array section offset: "
8084          << format("0x%" PRIx32, PersonalitiesStart) << '\n';
8085   uint32_t NumPersonalities = readNext<uint32_t>(Contents, Pos);
8086   outs() << "  Number of personality functions in array:  "
8087          << format("0x%" PRIx32, NumPersonalities) << '\n';
8088 
8089   uint32_t IndicesStart = readNext<uint32_t>(Contents, Pos);
8090   outs() << "  Index array section offset:                "
8091          << format("0x%" PRIx32, IndicesStart) << '\n';
8092   uint32_t NumIndices = readNext<uint32_t>(Contents, Pos);
8093   outs() << "  Number of indices in array:                "
8094          << format("0x%" PRIx32, NumIndices) << '\n';
8095 
8096   //===----------------------------------
8097   // A shared list of common encodings
8098   //===----------------------------------
8099 
8100   // These occupy indices in the range [0, N] whenever an encoding is referenced
8101   // from a compressed 2nd level index table. In practice the linker only
8102   // creates ~128 of these, so that indices are available to embed encodings in
8103   // the 2nd level index.
8104 
8105   SmallVector<uint32_t, 64> CommonEncodings;
8106   outs() << "  Common encodings: (count = " << NumCommonEncodings << ")\n";
8107   Pos = CommonEncodingsStart;
8108   for (unsigned i = 0; i < NumCommonEncodings; ++i) {
8109     uint32_t Encoding = readNext<uint32_t>(Contents, Pos);
8110     CommonEncodings.push_back(Encoding);
8111 
8112     outs() << "    encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
8113            << '\n';
8114   }
8115 
8116   //===----------------------------------
8117   // Personality functions used in this executable
8118   //===----------------------------------
8119 
8120   // There should be only a handful of these (one per source language,
8121   // roughly). Particularly since they only get 2 bits in the compact encoding.
8122 
8123   outs() << "  Personality functions: (count = " << NumPersonalities << ")\n";
8124   Pos = PersonalitiesStart;
8125   for (unsigned i = 0; i < NumPersonalities; ++i) {
8126     uint32_t PersonalityFn = readNext<uint32_t>(Contents, Pos);
8127     outs() << "    personality[" << i + 1
8128            << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
8129   }
8130 
8131   //===----------------------------------
8132   // The level 1 index entries
8133   //===----------------------------------
8134 
8135   // These specify an approximate place to start searching for the more detailed
8136   // information, sorted by PC.
8137 
8138   struct IndexEntry {
8139     uint32_t FunctionOffset;
8140     uint32_t SecondLevelPageStart;
8141     uint32_t LSDAStart;
8142   };
8143 
8144   SmallVector<IndexEntry, 4> IndexEntries;
8145 
8146   outs() << "  Top level indices: (count = " << NumIndices << ")\n";
8147   Pos = IndicesStart;
8148   for (unsigned i = 0; i < NumIndices; ++i) {
8149     IndexEntry Entry;
8150 
8151     Entry.FunctionOffset = readNext<uint32_t>(Contents, Pos);
8152     Entry.SecondLevelPageStart = readNext<uint32_t>(Contents, Pos);
8153     Entry.LSDAStart = readNext<uint32_t>(Contents, Pos);
8154     IndexEntries.push_back(Entry);
8155 
8156     outs() << "    [" << i << "]: "
8157            << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
8158            << ", "
8159            << "2nd level page offset="
8160            << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
8161            << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
8162   }
8163 
8164   //===----------------------------------
8165   // Next come the LSDA tables
8166   //===----------------------------------
8167 
8168   // The LSDA layout is rather implicit: it's a contiguous array of entries from
8169   // the first top-level index's LSDAOffset to the last (sentinel).
8170 
8171   outs() << "  LSDA descriptors:\n";
8172   Pos = IndexEntries[0].LSDAStart;
8173   const uint32_t LSDASize = 2 * sizeof(uint32_t);
8174   int NumLSDAs =
8175       (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) / LSDASize;
8176 
8177   for (int i = 0; i < NumLSDAs; ++i) {
8178     uint32_t FunctionOffset = readNext<uint32_t>(Contents, Pos);
8179     uint32_t LSDAOffset = readNext<uint32_t>(Contents, Pos);
8180     outs() << "    [" << i << "]: "
8181            << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
8182            << ", "
8183            << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
8184   }
8185 
8186   //===----------------------------------
8187   // Finally, the 2nd level indices
8188   //===----------------------------------
8189 
8190   // Generally these are 4K in size, and have 2 possible forms:
8191   //   + Regular stores up to 511 entries with disparate encodings
8192   //   + Compressed stores up to 1021 entries if few enough compact encoding
8193   //     values are used.
8194   outs() << "  Second level indices:\n";
8195   for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
8196     // The final sentinel top-level index has no associated 2nd level page
8197     if (IndexEntries[i].SecondLevelPageStart == 0)
8198       break;
8199 
8200     outs() << "    Second level index[" << i << "]: "
8201            << "offset in section="
8202            << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
8203            << ", "
8204            << "base function offset="
8205            << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
8206 
8207     Pos = IndexEntries[i].SecondLevelPageStart;
8208     if (Pos + sizeof(uint32_t) > Contents.size()) {
8209       outs() << "warning: invalid offset for second level page: " << Pos << '\n';
8210       continue;
8211     }
8212 
8213     uint32_t Kind =
8214         *reinterpret_cast<const support::ulittle32_t *>(Contents.data() + Pos);
8215     if (Kind == 2)
8216       printRegularSecondLevelUnwindPage(Contents.substr(Pos, 4096));
8217     else if (Kind == 3)
8218       printCompressedSecondLevelUnwindPage(Contents.substr(Pos, 4096),
8219                                            IndexEntries[i].FunctionOffset,
8220                                            CommonEncodings);
8221     else
8222       outs() << "    Skipping 2nd level page with unknown kind " << Kind
8223              << '\n';
8224   }
8225 }
8226 
8227 void objdump::printMachOUnwindInfo(const MachOObjectFile *Obj) {
8228   std::map<uint64_t, SymbolRef> Symbols;
8229   for (const SymbolRef &SymRef : Obj->symbols()) {
8230     // Discard any undefined or absolute symbols. They're not going to take part
8231     // in the convenience lookup for unwind info and just take up resources.
8232     auto SectOrErr = SymRef.getSection();
8233     if (!SectOrErr) {
8234       // TODO: Actually report errors helpfully.
8235       consumeError(SectOrErr.takeError());
8236       continue;
8237     }
8238     section_iterator Section = *SectOrErr;
8239     if (Section == Obj->section_end())
8240       continue;
8241 
8242     uint64_t Addr = cantFail(SymRef.getValue());
8243     Symbols.insert(std::make_pair(Addr, SymRef));
8244   }
8245 
8246   for (const SectionRef &Section : Obj->sections()) {
8247     StringRef SectName;
8248     if (Expected<StringRef> NameOrErr = Section.getName())
8249       SectName = *NameOrErr;
8250     else
8251       consumeError(NameOrErr.takeError());
8252 
8253     if (SectName == "__compact_unwind")
8254       printMachOCompactUnwindSection(Obj, Symbols, Section);
8255     else if (SectName == "__unwind_info")
8256       printMachOUnwindInfoSection(Obj, Symbols, Section);
8257   }
8258 }
8259 
8260 static void PrintMachHeader(uint32_t magic, uint32_t cputype,
8261                             uint32_t cpusubtype, uint32_t filetype,
8262                             uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
8263                             bool verbose) {
8264   outs() << "Mach header\n";
8265   outs() << "      magic cputype cpusubtype  caps    filetype ncmds "
8266             "sizeofcmds      flags\n";
8267   if (verbose) {
8268     if (magic == MachO::MH_MAGIC)
8269       outs() << "   MH_MAGIC";
8270     else if (magic == MachO::MH_MAGIC_64)
8271       outs() << "MH_MAGIC_64";
8272     else
8273       outs() << format(" 0x%08" PRIx32, magic);
8274     switch (cputype) {
8275     case MachO::CPU_TYPE_I386:
8276       outs() << "    I386";
8277       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8278       case MachO::CPU_SUBTYPE_I386_ALL:
8279         outs() << "        ALL";
8280         break;
8281       default:
8282         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8283         break;
8284       }
8285       break;
8286     case MachO::CPU_TYPE_X86_64:
8287       outs() << "  X86_64";
8288       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8289       case MachO::CPU_SUBTYPE_X86_64_ALL:
8290         outs() << "        ALL";
8291         break;
8292       case MachO::CPU_SUBTYPE_X86_64_H:
8293         outs() << "    Haswell";
8294         break;
8295       default:
8296         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8297         break;
8298       }
8299       break;
8300     case MachO::CPU_TYPE_ARM:
8301       outs() << "     ARM";
8302       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8303       case MachO::CPU_SUBTYPE_ARM_ALL:
8304         outs() << "        ALL";
8305         break;
8306       case MachO::CPU_SUBTYPE_ARM_V4T:
8307         outs() << "        V4T";
8308         break;
8309       case MachO::CPU_SUBTYPE_ARM_V5TEJ:
8310         outs() << "      V5TEJ";
8311         break;
8312       case MachO::CPU_SUBTYPE_ARM_XSCALE:
8313         outs() << "     XSCALE";
8314         break;
8315       case MachO::CPU_SUBTYPE_ARM_V6:
8316         outs() << "         V6";
8317         break;
8318       case MachO::CPU_SUBTYPE_ARM_V6M:
8319         outs() << "        V6M";
8320         break;
8321       case MachO::CPU_SUBTYPE_ARM_V7:
8322         outs() << "         V7";
8323         break;
8324       case MachO::CPU_SUBTYPE_ARM_V7EM:
8325         outs() << "       V7EM";
8326         break;
8327       case MachO::CPU_SUBTYPE_ARM_V7K:
8328         outs() << "        V7K";
8329         break;
8330       case MachO::CPU_SUBTYPE_ARM_V7M:
8331         outs() << "        V7M";
8332         break;
8333       case MachO::CPU_SUBTYPE_ARM_V7S:
8334         outs() << "        V7S";
8335         break;
8336       default:
8337         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8338         break;
8339       }
8340       break;
8341     case MachO::CPU_TYPE_ARM64:
8342       outs() << "   ARM64";
8343       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8344       case MachO::CPU_SUBTYPE_ARM64_ALL:
8345         outs() << "        ALL";
8346         break;
8347       case MachO::CPU_SUBTYPE_ARM64_V8:
8348         outs() << "         V8";
8349         break;
8350       case MachO::CPU_SUBTYPE_ARM64E:
8351         outs() << "          E";
8352         break;
8353       default:
8354         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8355         break;
8356       }
8357       break;
8358     case MachO::CPU_TYPE_ARM64_32:
8359       outs() << " ARM64_32";
8360       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8361       case MachO::CPU_SUBTYPE_ARM64_32_V8:
8362         outs() << "        V8";
8363         break;
8364       default:
8365         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8366         break;
8367       }
8368       break;
8369     case MachO::CPU_TYPE_POWERPC:
8370       outs() << "     PPC";
8371       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8372       case MachO::CPU_SUBTYPE_POWERPC_ALL:
8373         outs() << "        ALL";
8374         break;
8375       default:
8376         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8377         break;
8378       }
8379       break;
8380     case MachO::CPU_TYPE_POWERPC64:
8381       outs() << "   PPC64";
8382       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8383       case MachO::CPU_SUBTYPE_POWERPC_ALL:
8384         outs() << "        ALL";
8385         break;
8386       default:
8387         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8388         break;
8389       }
8390       break;
8391     default:
8392       outs() << format(" %7d", cputype);
8393       outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8394       break;
8395     }
8396     if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
8397       outs() << " LIB64";
8398     } else {
8399       outs() << format("  0x%02" PRIx32,
8400                        (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
8401     }
8402     switch (filetype) {
8403     case MachO::MH_OBJECT:
8404       outs() << "      OBJECT";
8405       break;
8406     case MachO::MH_EXECUTE:
8407       outs() << "     EXECUTE";
8408       break;
8409     case MachO::MH_FVMLIB:
8410       outs() << "      FVMLIB";
8411       break;
8412     case MachO::MH_CORE:
8413       outs() << "        CORE";
8414       break;
8415     case MachO::MH_PRELOAD:
8416       outs() << "     PRELOAD";
8417       break;
8418     case MachO::MH_DYLIB:
8419       outs() << "       DYLIB";
8420       break;
8421     case MachO::MH_DYLIB_STUB:
8422       outs() << "  DYLIB_STUB";
8423       break;
8424     case MachO::MH_DYLINKER:
8425       outs() << "    DYLINKER";
8426       break;
8427     case MachO::MH_BUNDLE:
8428       outs() << "      BUNDLE";
8429       break;
8430     case MachO::MH_DSYM:
8431       outs() << "        DSYM";
8432       break;
8433     case MachO::MH_KEXT_BUNDLE:
8434       outs() << "  KEXTBUNDLE";
8435       break;
8436     default:
8437       outs() << format("  %10u", filetype);
8438       break;
8439     }
8440     outs() << format(" %5u", ncmds);
8441     outs() << format(" %10u", sizeofcmds);
8442     uint32_t f = flags;
8443     if (f & MachO::MH_NOUNDEFS) {
8444       outs() << "   NOUNDEFS";
8445       f &= ~MachO::MH_NOUNDEFS;
8446     }
8447     if (f & MachO::MH_INCRLINK) {
8448       outs() << " INCRLINK";
8449       f &= ~MachO::MH_INCRLINK;
8450     }
8451     if (f & MachO::MH_DYLDLINK) {
8452       outs() << " DYLDLINK";
8453       f &= ~MachO::MH_DYLDLINK;
8454     }
8455     if (f & MachO::MH_BINDATLOAD) {
8456       outs() << " BINDATLOAD";
8457       f &= ~MachO::MH_BINDATLOAD;
8458     }
8459     if (f & MachO::MH_PREBOUND) {
8460       outs() << " PREBOUND";
8461       f &= ~MachO::MH_PREBOUND;
8462     }
8463     if (f & MachO::MH_SPLIT_SEGS) {
8464       outs() << " SPLIT_SEGS";
8465       f &= ~MachO::MH_SPLIT_SEGS;
8466     }
8467     if (f & MachO::MH_LAZY_INIT) {
8468       outs() << " LAZY_INIT";
8469       f &= ~MachO::MH_LAZY_INIT;
8470     }
8471     if (f & MachO::MH_TWOLEVEL) {
8472       outs() << " TWOLEVEL";
8473       f &= ~MachO::MH_TWOLEVEL;
8474     }
8475     if (f & MachO::MH_FORCE_FLAT) {
8476       outs() << " FORCE_FLAT";
8477       f &= ~MachO::MH_FORCE_FLAT;
8478     }
8479     if (f & MachO::MH_NOMULTIDEFS) {
8480       outs() << " NOMULTIDEFS";
8481       f &= ~MachO::MH_NOMULTIDEFS;
8482     }
8483     if (f & MachO::MH_NOFIXPREBINDING) {
8484       outs() << " NOFIXPREBINDING";
8485       f &= ~MachO::MH_NOFIXPREBINDING;
8486     }
8487     if (f & MachO::MH_PREBINDABLE) {
8488       outs() << " PREBINDABLE";
8489       f &= ~MachO::MH_PREBINDABLE;
8490     }
8491     if (f & MachO::MH_ALLMODSBOUND) {
8492       outs() << " ALLMODSBOUND";
8493       f &= ~MachO::MH_ALLMODSBOUND;
8494     }
8495     if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
8496       outs() << " SUBSECTIONS_VIA_SYMBOLS";
8497       f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
8498     }
8499     if (f & MachO::MH_CANONICAL) {
8500       outs() << " CANONICAL";
8501       f &= ~MachO::MH_CANONICAL;
8502     }
8503     if (f & MachO::MH_WEAK_DEFINES) {
8504       outs() << " WEAK_DEFINES";
8505       f &= ~MachO::MH_WEAK_DEFINES;
8506     }
8507     if (f & MachO::MH_BINDS_TO_WEAK) {
8508       outs() << " BINDS_TO_WEAK";
8509       f &= ~MachO::MH_BINDS_TO_WEAK;
8510     }
8511     if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
8512       outs() << " ALLOW_STACK_EXECUTION";
8513       f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
8514     }
8515     if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
8516       outs() << " DEAD_STRIPPABLE_DYLIB";
8517       f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
8518     }
8519     if (f & MachO::MH_PIE) {
8520       outs() << " PIE";
8521       f &= ~MachO::MH_PIE;
8522     }
8523     if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
8524       outs() << " NO_REEXPORTED_DYLIBS";
8525       f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
8526     }
8527     if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
8528       outs() << " MH_HAS_TLV_DESCRIPTORS";
8529       f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
8530     }
8531     if (f & MachO::MH_NO_HEAP_EXECUTION) {
8532       outs() << " MH_NO_HEAP_EXECUTION";
8533       f &= ~MachO::MH_NO_HEAP_EXECUTION;
8534     }
8535     if (f & MachO::MH_APP_EXTENSION_SAFE) {
8536       outs() << " APP_EXTENSION_SAFE";
8537       f &= ~MachO::MH_APP_EXTENSION_SAFE;
8538     }
8539     if (f & MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO) {
8540       outs() << " NLIST_OUTOFSYNC_WITH_DYLDINFO";
8541       f &= ~MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO;
8542     }
8543     if (f != 0 || flags == 0)
8544       outs() << format(" 0x%08" PRIx32, f);
8545   } else {
8546     outs() << format(" 0x%08" PRIx32, magic);
8547     outs() << format(" %7d", cputype);
8548     outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8549     outs() << format("  0x%02" PRIx32,
8550                      (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
8551     outs() << format("  %10u", filetype);
8552     outs() << format(" %5u", ncmds);
8553     outs() << format(" %10u", sizeofcmds);
8554     outs() << format(" 0x%08" PRIx32, flags);
8555   }
8556   outs() << "\n";
8557 }
8558 
8559 static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
8560                                 StringRef SegName, uint64_t vmaddr,
8561                                 uint64_t vmsize, uint64_t fileoff,
8562                                 uint64_t filesize, uint32_t maxprot,
8563                                 uint32_t initprot, uint32_t nsects,
8564                                 uint32_t flags, uint32_t object_size,
8565                                 bool verbose) {
8566   uint64_t expected_cmdsize;
8567   if (cmd == MachO::LC_SEGMENT) {
8568     outs() << "      cmd LC_SEGMENT\n";
8569     expected_cmdsize = nsects;
8570     expected_cmdsize *= sizeof(struct MachO::section);
8571     expected_cmdsize += sizeof(struct MachO::segment_command);
8572   } else {
8573     outs() << "      cmd LC_SEGMENT_64\n";
8574     expected_cmdsize = nsects;
8575     expected_cmdsize *= sizeof(struct MachO::section_64);
8576     expected_cmdsize += sizeof(struct MachO::segment_command_64);
8577   }
8578   outs() << "  cmdsize " << cmdsize;
8579   if (cmdsize != expected_cmdsize)
8580     outs() << " Inconsistent size\n";
8581   else
8582     outs() << "\n";
8583   outs() << "  segname " << SegName << "\n";
8584   if (cmd == MachO::LC_SEGMENT_64) {
8585     outs() << "   vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
8586     outs() << "   vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
8587   } else {
8588     outs() << "   vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
8589     outs() << "   vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
8590   }
8591   outs() << "  fileoff " << fileoff;
8592   if (fileoff > object_size)
8593     outs() << " (past end of file)\n";
8594   else
8595     outs() << "\n";
8596   outs() << " filesize " << filesize;
8597   if (fileoff + filesize > object_size)
8598     outs() << " (past end of file)\n";
8599   else
8600     outs() << "\n";
8601   if (verbose) {
8602     if ((maxprot &
8603          ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8604            MachO::VM_PROT_EXECUTE)) != 0)
8605       outs() << "  maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
8606     else {
8607       outs() << "  maxprot ";
8608       outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
8609       outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8610       outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
8611     }
8612     if ((initprot &
8613          ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8614            MachO::VM_PROT_EXECUTE)) != 0)
8615       outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
8616     else {
8617       outs() << " initprot ";
8618       outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
8619       outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8620       outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
8621     }
8622   } else {
8623     outs() << "  maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
8624     outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
8625   }
8626   outs() << "   nsects " << nsects << "\n";
8627   if (verbose) {
8628     outs() << "    flags";
8629     if (flags == 0)
8630       outs() << " (none)\n";
8631     else {
8632       if (flags & MachO::SG_HIGHVM) {
8633         outs() << " HIGHVM";
8634         flags &= ~MachO::SG_HIGHVM;
8635       }
8636       if (flags & MachO::SG_FVMLIB) {
8637         outs() << " FVMLIB";
8638         flags &= ~MachO::SG_FVMLIB;
8639       }
8640       if (flags & MachO::SG_NORELOC) {
8641         outs() << " NORELOC";
8642         flags &= ~MachO::SG_NORELOC;
8643       }
8644       if (flags & MachO::SG_PROTECTED_VERSION_1) {
8645         outs() << " PROTECTED_VERSION_1";
8646         flags &= ~MachO::SG_PROTECTED_VERSION_1;
8647       }
8648       if (flags)
8649         outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
8650       else
8651         outs() << "\n";
8652     }
8653   } else {
8654     outs() << "    flags " << format("0x%" PRIx32, flags) << "\n";
8655   }
8656 }
8657 
8658 static void PrintSection(const char *sectname, const char *segname,
8659                          uint64_t addr, uint64_t size, uint32_t offset,
8660                          uint32_t align, uint32_t reloff, uint32_t nreloc,
8661                          uint32_t flags, uint32_t reserved1, uint32_t reserved2,
8662                          uint32_t cmd, const char *sg_segname,
8663                          uint32_t filetype, uint32_t object_size,
8664                          bool verbose) {
8665   outs() << "Section\n";
8666   outs() << "  sectname " << format("%.16s\n", sectname);
8667   outs() << "   segname " << format("%.16s", segname);
8668   if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
8669     outs() << " (does not match segment)\n";
8670   else
8671     outs() << "\n";
8672   if (cmd == MachO::LC_SEGMENT_64) {
8673     outs() << "      addr " << format("0x%016" PRIx64, addr) << "\n";
8674     outs() << "      size " << format("0x%016" PRIx64, size);
8675   } else {
8676     outs() << "      addr " << format("0x%08" PRIx64, addr) << "\n";
8677     outs() << "      size " << format("0x%08" PRIx64, size);
8678   }
8679   if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
8680     outs() << " (past end of file)\n";
8681   else
8682     outs() << "\n";
8683   outs() << "    offset " << offset;
8684   if (offset > object_size)
8685     outs() << " (past end of file)\n";
8686   else
8687     outs() << "\n";
8688   uint32_t align_shifted = 1 << align;
8689   outs() << "     align 2^" << align << " (" << align_shifted << ")\n";
8690   outs() << "    reloff " << reloff;
8691   if (reloff > object_size)
8692     outs() << " (past end of file)\n";
8693   else
8694     outs() << "\n";
8695   outs() << "    nreloc " << nreloc;
8696   if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
8697     outs() << " (past end of file)\n";
8698   else
8699     outs() << "\n";
8700   uint32_t section_type = flags & MachO::SECTION_TYPE;
8701   if (verbose) {
8702     outs() << "      type";
8703     if (section_type == MachO::S_REGULAR)
8704       outs() << " S_REGULAR\n";
8705     else if (section_type == MachO::S_ZEROFILL)
8706       outs() << " S_ZEROFILL\n";
8707     else if (section_type == MachO::S_CSTRING_LITERALS)
8708       outs() << " S_CSTRING_LITERALS\n";
8709     else if (section_type == MachO::S_4BYTE_LITERALS)
8710       outs() << " S_4BYTE_LITERALS\n";
8711     else if (section_type == MachO::S_8BYTE_LITERALS)
8712       outs() << " S_8BYTE_LITERALS\n";
8713     else if (section_type == MachO::S_16BYTE_LITERALS)
8714       outs() << " S_16BYTE_LITERALS\n";
8715     else if (section_type == MachO::S_LITERAL_POINTERS)
8716       outs() << " S_LITERAL_POINTERS\n";
8717     else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
8718       outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
8719     else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
8720       outs() << " S_LAZY_SYMBOL_POINTERS\n";
8721     else if (section_type == MachO::S_SYMBOL_STUBS)
8722       outs() << " S_SYMBOL_STUBS\n";
8723     else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
8724       outs() << " S_MOD_INIT_FUNC_POINTERS\n";
8725     else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
8726       outs() << " S_MOD_TERM_FUNC_POINTERS\n";
8727     else if (section_type == MachO::S_COALESCED)
8728       outs() << " S_COALESCED\n";
8729     else if (section_type == MachO::S_INTERPOSING)
8730       outs() << " S_INTERPOSING\n";
8731     else if (section_type == MachO::S_DTRACE_DOF)
8732       outs() << " S_DTRACE_DOF\n";
8733     else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
8734       outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
8735     else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
8736       outs() << " S_THREAD_LOCAL_REGULAR\n";
8737     else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
8738       outs() << " S_THREAD_LOCAL_ZEROFILL\n";
8739     else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
8740       outs() << " S_THREAD_LOCAL_VARIABLES\n";
8741     else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8742       outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
8743     else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
8744       outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
8745     else
8746       outs() << format("0x%08" PRIx32, section_type) << "\n";
8747     outs() << "attributes";
8748     uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
8749     if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
8750       outs() << " PURE_INSTRUCTIONS";
8751     if (section_attributes & MachO::S_ATTR_NO_TOC)
8752       outs() << " NO_TOC";
8753     if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
8754       outs() << " STRIP_STATIC_SYMS";
8755     if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
8756       outs() << " NO_DEAD_STRIP";
8757     if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
8758       outs() << " LIVE_SUPPORT";
8759     if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
8760       outs() << " SELF_MODIFYING_CODE";
8761     if (section_attributes & MachO::S_ATTR_DEBUG)
8762       outs() << " DEBUG";
8763     if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
8764       outs() << " SOME_INSTRUCTIONS";
8765     if (section_attributes & MachO::S_ATTR_EXT_RELOC)
8766       outs() << " EXT_RELOC";
8767     if (section_attributes & MachO::S_ATTR_LOC_RELOC)
8768       outs() << " LOC_RELOC";
8769     if (section_attributes == 0)
8770       outs() << " (none)";
8771     outs() << "\n";
8772   } else
8773     outs() << "     flags " << format("0x%08" PRIx32, flags) << "\n";
8774   outs() << " reserved1 " << reserved1;
8775   if (section_type == MachO::S_SYMBOL_STUBS ||
8776       section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
8777       section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
8778       section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
8779       section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8780     outs() << " (index into indirect symbol table)\n";
8781   else
8782     outs() << "\n";
8783   outs() << " reserved2 " << reserved2;
8784   if (section_type == MachO::S_SYMBOL_STUBS)
8785     outs() << " (size of stubs)\n";
8786   else
8787     outs() << "\n";
8788 }
8789 
8790 static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
8791                                    uint32_t object_size) {
8792   outs() << "     cmd LC_SYMTAB\n";
8793   outs() << " cmdsize " << st.cmdsize;
8794   if (st.cmdsize != sizeof(struct MachO::symtab_command))
8795     outs() << " Incorrect size\n";
8796   else
8797     outs() << "\n";
8798   outs() << "  symoff " << st.symoff;
8799   if (st.symoff > object_size)
8800     outs() << " (past end of file)\n";
8801   else
8802     outs() << "\n";
8803   outs() << "   nsyms " << st.nsyms;
8804   uint64_t big_size;
8805   if (Is64Bit) {
8806     big_size = st.nsyms;
8807     big_size *= sizeof(struct MachO::nlist_64);
8808     big_size += st.symoff;
8809     if (big_size > object_size)
8810       outs() << " (past end of file)\n";
8811     else
8812       outs() << "\n";
8813   } else {
8814     big_size = st.nsyms;
8815     big_size *= sizeof(struct MachO::nlist);
8816     big_size += st.symoff;
8817     if (big_size > object_size)
8818       outs() << " (past end of file)\n";
8819     else
8820       outs() << "\n";
8821   }
8822   outs() << "  stroff " << st.stroff;
8823   if (st.stroff > object_size)
8824     outs() << " (past end of file)\n";
8825   else
8826     outs() << "\n";
8827   outs() << " strsize " << st.strsize;
8828   big_size = st.stroff;
8829   big_size += st.strsize;
8830   if (big_size > object_size)
8831     outs() << " (past end of file)\n";
8832   else
8833     outs() << "\n";
8834 }
8835 
8836 static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
8837                                      uint32_t nsyms, uint32_t object_size,
8838                                      bool Is64Bit) {
8839   outs() << "            cmd LC_DYSYMTAB\n";
8840   outs() << "        cmdsize " << dyst.cmdsize;
8841   if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
8842     outs() << " Incorrect size\n";
8843   else
8844     outs() << "\n";
8845   outs() << "      ilocalsym " << dyst.ilocalsym;
8846   if (dyst.ilocalsym > nsyms)
8847     outs() << " (greater than the number of symbols)\n";
8848   else
8849     outs() << "\n";
8850   outs() << "      nlocalsym " << dyst.nlocalsym;
8851   uint64_t big_size;
8852   big_size = dyst.ilocalsym;
8853   big_size += dyst.nlocalsym;
8854   if (big_size > nsyms)
8855     outs() << " (past the end of the symbol table)\n";
8856   else
8857     outs() << "\n";
8858   outs() << "     iextdefsym " << dyst.iextdefsym;
8859   if (dyst.iextdefsym > nsyms)
8860     outs() << " (greater than the number of symbols)\n";
8861   else
8862     outs() << "\n";
8863   outs() << "     nextdefsym " << dyst.nextdefsym;
8864   big_size = dyst.iextdefsym;
8865   big_size += dyst.nextdefsym;
8866   if (big_size > nsyms)
8867     outs() << " (past the end of the symbol table)\n";
8868   else
8869     outs() << "\n";
8870   outs() << "      iundefsym " << dyst.iundefsym;
8871   if (dyst.iundefsym > nsyms)
8872     outs() << " (greater than the number of symbols)\n";
8873   else
8874     outs() << "\n";
8875   outs() << "      nundefsym " << dyst.nundefsym;
8876   big_size = dyst.iundefsym;
8877   big_size += dyst.nundefsym;
8878   if (big_size > nsyms)
8879     outs() << " (past the end of the symbol table)\n";
8880   else
8881     outs() << "\n";
8882   outs() << "         tocoff " << dyst.tocoff;
8883   if (dyst.tocoff > object_size)
8884     outs() << " (past end of file)\n";
8885   else
8886     outs() << "\n";
8887   outs() << "           ntoc " << dyst.ntoc;
8888   big_size = dyst.ntoc;
8889   big_size *= sizeof(struct MachO::dylib_table_of_contents);
8890   big_size += dyst.tocoff;
8891   if (big_size > object_size)
8892     outs() << " (past end of file)\n";
8893   else
8894     outs() << "\n";
8895   outs() << "      modtaboff " << dyst.modtaboff;
8896   if (dyst.modtaboff > object_size)
8897     outs() << " (past end of file)\n";
8898   else
8899     outs() << "\n";
8900   outs() << "        nmodtab " << dyst.nmodtab;
8901   uint64_t modtabend;
8902   if (Is64Bit) {
8903     modtabend = dyst.nmodtab;
8904     modtabend *= sizeof(struct MachO::dylib_module_64);
8905     modtabend += dyst.modtaboff;
8906   } else {
8907     modtabend = dyst.nmodtab;
8908     modtabend *= sizeof(struct MachO::dylib_module);
8909     modtabend += dyst.modtaboff;
8910   }
8911   if (modtabend > object_size)
8912     outs() << " (past end of file)\n";
8913   else
8914     outs() << "\n";
8915   outs() << "   extrefsymoff " << dyst.extrefsymoff;
8916   if (dyst.extrefsymoff > object_size)
8917     outs() << " (past end of file)\n";
8918   else
8919     outs() << "\n";
8920   outs() << "    nextrefsyms " << dyst.nextrefsyms;
8921   big_size = dyst.nextrefsyms;
8922   big_size *= sizeof(struct MachO::dylib_reference);
8923   big_size += dyst.extrefsymoff;
8924   if (big_size > object_size)
8925     outs() << " (past end of file)\n";
8926   else
8927     outs() << "\n";
8928   outs() << " indirectsymoff " << dyst.indirectsymoff;
8929   if (dyst.indirectsymoff > object_size)
8930     outs() << " (past end of file)\n";
8931   else
8932     outs() << "\n";
8933   outs() << "  nindirectsyms " << dyst.nindirectsyms;
8934   big_size = dyst.nindirectsyms;
8935   big_size *= sizeof(uint32_t);
8936   big_size += dyst.indirectsymoff;
8937   if (big_size > object_size)
8938     outs() << " (past end of file)\n";
8939   else
8940     outs() << "\n";
8941   outs() << "      extreloff " << dyst.extreloff;
8942   if (dyst.extreloff > object_size)
8943     outs() << " (past end of file)\n";
8944   else
8945     outs() << "\n";
8946   outs() << "        nextrel " << dyst.nextrel;
8947   big_size = dyst.nextrel;
8948   big_size *= sizeof(struct MachO::relocation_info);
8949   big_size += dyst.extreloff;
8950   if (big_size > object_size)
8951     outs() << " (past end of file)\n";
8952   else
8953     outs() << "\n";
8954   outs() << "      locreloff " << dyst.locreloff;
8955   if (dyst.locreloff > object_size)
8956     outs() << " (past end of file)\n";
8957   else
8958     outs() << "\n";
8959   outs() << "        nlocrel " << dyst.nlocrel;
8960   big_size = dyst.nlocrel;
8961   big_size *= sizeof(struct MachO::relocation_info);
8962   big_size += dyst.locreloff;
8963   if (big_size > object_size)
8964     outs() << " (past end of file)\n";
8965   else
8966     outs() << "\n";
8967 }
8968 
8969 static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
8970                                      uint32_t object_size) {
8971   if (dc.cmd == MachO::LC_DYLD_INFO)
8972     outs() << "            cmd LC_DYLD_INFO\n";
8973   else
8974     outs() << "            cmd LC_DYLD_INFO_ONLY\n";
8975   outs() << "        cmdsize " << dc.cmdsize;
8976   if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
8977     outs() << " Incorrect size\n";
8978   else
8979     outs() << "\n";
8980   outs() << "     rebase_off " << dc.rebase_off;
8981   if (dc.rebase_off > object_size)
8982     outs() << " (past end of file)\n";
8983   else
8984     outs() << "\n";
8985   outs() << "    rebase_size " << dc.rebase_size;
8986   uint64_t big_size;
8987   big_size = dc.rebase_off;
8988   big_size += dc.rebase_size;
8989   if (big_size > object_size)
8990     outs() << " (past end of file)\n";
8991   else
8992     outs() << "\n";
8993   outs() << "       bind_off " << dc.bind_off;
8994   if (dc.bind_off > object_size)
8995     outs() << " (past end of file)\n";
8996   else
8997     outs() << "\n";
8998   outs() << "      bind_size " << dc.bind_size;
8999   big_size = dc.bind_off;
9000   big_size += dc.bind_size;
9001   if (big_size > object_size)
9002     outs() << " (past end of file)\n";
9003   else
9004     outs() << "\n";
9005   outs() << "  weak_bind_off " << dc.weak_bind_off;
9006   if (dc.weak_bind_off > object_size)
9007     outs() << " (past end of file)\n";
9008   else
9009     outs() << "\n";
9010   outs() << " weak_bind_size " << dc.weak_bind_size;
9011   big_size = dc.weak_bind_off;
9012   big_size += dc.weak_bind_size;
9013   if (big_size > object_size)
9014     outs() << " (past end of file)\n";
9015   else
9016     outs() << "\n";
9017   outs() << "  lazy_bind_off " << dc.lazy_bind_off;
9018   if (dc.lazy_bind_off > object_size)
9019     outs() << " (past end of file)\n";
9020   else
9021     outs() << "\n";
9022   outs() << " lazy_bind_size " << dc.lazy_bind_size;
9023   big_size = dc.lazy_bind_off;
9024   big_size += dc.lazy_bind_size;
9025   if (big_size > object_size)
9026     outs() << " (past end of file)\n";
9027   else
9028     outs() << "\n";
9029   outs() << "     export_off " << dc.export_off;
9030   if (dc.export_off > object_size)
9031     outs() << " (past end of file)\n";
9032   else
9033     outs() << "\n";
9034   outs() << "    export_size " << dc.export_size;
9035   big_size = dc.export_off;
9036   big_size += dc.export_size;
9037   if (big_size > object_size)
9038     outs() << " (past end of file)\n";
9039   else
9040     outs() << "\n";
9041 }
9042 
9043 static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
9044                                  const char *Ptr) {
9045   if (dyld.cmd == MachO::LC_ID_DYLINKER)
9046     outs() << "          cmd LC_ID_DYLINKER\n";
9047   else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
9048     outs() << "          cmd LC_LOAD_DYLINKER\n";
9049   else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
9050     outs() << "          cmd LC_DYLD_ENVIRONMENT\n";
9051   else
9052     outs() << "          cmd ?(" << dyld.cmd << ")\n";
9053   outs() << "      cmdsize " << dyld.cmdsize;
9054   if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
9055     outs() << " Incorrect size\n";
9056   else
9057     outs() << "\n";
9058   if (dyld.name >= dyld.cmdsize)
9059     outs() << "         name ?(bad offset " << dyld.name << ")\n";
9060   else {
9061     const char *P = (const char *)(Ptr) + dyld.name;
9062     outs() << "         name " << P << " (offset " << dyld.name << ")\n";
9063   }
9064 }
9065 
9066 static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
9067   outs() << "     cmd LC_UUID\n";
9068   outs() << " cmdsize " << uuid.cmdsize;
9069   if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
9070     outs() << " Incorrect size\n";
9071   else
9072     outs() << "\n";
9073   outs() << "    uuid ";
9074   for (int i = 0; i < 16; ++i) {
9075     outs() << format("%02" PRIX32, uuid.uuid[i]);
9076     if (i == 3 || i == 5 || i == 7 || i == 9)
9077       outs() << "-";
9078   }
9079   outs() << "\n";
9080 }
9081 
9082 static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
9083   outs() << "          cmd LC_RPATH\n";
9084   outs() << "      cmdsize " << rpath.cmdsize;
9085   if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
9086     outs() << " Incorrect size\n";
9087   else
9088     outs() << "\n";
9089   if (rpath.path >= rpath.cmdsize)
9090     outs() << "         path ?(bad offset " << rpath.path << ")\n";
9091   else {
9092     const char *P = (const char *)(Ptr) + rpath.path;
9093     outs() << "         path " << P << " (offset " << rpath.path << ")\n";
9094   }
9095 }
9096 
9097 static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
9098   StringRef LoadCmdName;
9099   switch (vd.cmd) {
9100   case MachO::LC_VERSION_MIN_MACOSX:
9101     LoadCmdName = "LC_VERSION_MIN_MACOSX";
9102     break;
9103   case MachO::LC_VERSION_MIN_IPHONEOS:
9104     LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
9105     break;
9106   case MachO::LC_VERSION_MIN_TVOS:
9107     LoadCmdName = "LC_VERSION_MIN_TVOS";
9108     break;
9109   case MachO::LC_VERSION_MIN_WATCHOS:
9110     LoadCmdName = "LC_VERSION_MIN_WATCHOS";
9111     break;
9112   default:
9113     llvm_unreachable("Unknown version min load command");
9114   }
9115 
9116   outs() << "      cmd " << LoadCmdName << '\n';
9117   outs() << "  cmdsize " << vd.cmdsize;
9118   if (vd.cmdsize != sizeof(struct MachO::version_min_command))
9119     outs() << " Incorrect size\n";
9120   else
9121     outs() << "\n";
9122   outs() << "  version "
9123          << MachOObjectFile::getVersionMinMajor(vd, false) << "."
9124          << MachOObjectFile::getVersionMinMinor(vd, false);
9125   uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
9126   if (Update != 0)
9127     outs() << "." << Update;
9128   outs() << "\n";
9129   if (vd.sdk == 0)
9130     outs() << "      sdk n/a";
9131   else {
9132     outs() << "      sdk "
9133            << MachOObjectFile::getVersionMinMajor(vd, true) << "."
9134            << MachOObjectFile::getVersionMinMinor(vd, true);
9135   }
9136   Update = MachOObjectFile::getVersionMinUpdate(vd, true);
9137   if (Update != 0)
9138     outs() << "." << Update;
9139   outs() << "\n";
9140 }
9141 
9142 static void PrintNoteLoadCommand(MachO::note_command Nt) {
9143   outs() << "       cmd LC_NOTE\n";
9144   outs() << "   cmdsize " << Nt.cmdsize;
9145   if (Nt.cmdsize != sizeof(struct MachO::note_command))
9146     outs() << " Incorrect size\n";
9147   else
9148     outs() << "\n";
9149   const char *d = Nt.data_owner;
9150   outs() << "data_owner " << format("%.16s\n", d);
9151   outs() << "    offset " << Nt.offset << "\n";
9152   outs() << "      size " << Nt.size << "\n";
9153 }
9154 
9155 static void PrintBuildToolVersion(MachO::build_tool_version bv) {
9156   outs() << "      tool " << MachOObjectFile::getBuildTool(bv.tool) << "\n";
9157   outs() << "   version " << MachOObjectFile::getVersionString(bv.version)
9158          << "\n";
9159 }
9160 
9161 static void PrintBuildVersionLoadCommand(const MachOObjectFile *obj,
9162                                          MachO::build_version_command bd) {
9163   outs() << "       cmd LC_BUILD_VERSION\n";
9164   outs() << "   cmdsize " << bd.cmdsize;
9165   if (bd.cmdsize !=
9166       sizeof(struct MachO::build_version_command) +
9167           bd.ntools * sizeof(struct MachO::build_tool_version))
9168     outs() << " Incorrect size\n";
9169   else
9170     outs() << "\n";
9171   outs() << "  platform " << MachOObjectFile::getBuildPlatform(bd.platform)
9172          << "\n";
9173   if (bd.sdk)
9174     outs() << "       sdk " << MachOObjectFile::getVersionString(bd.sdk)
9175            << "\n";
9176   else
9177     outs() << "       sdk n/a\n";
9178   outs() << "     minos " << MachOObjectFile::getVersionString(bd.minos)
9179          << "\n";
9180   outs() << "    ntools " << bd.ntools << "\n";
9181   for (unsigned i = 0; i < bd.ntools; ++i) {
9182     MachO::build_tool_version bv = obj->getBuildToolVersion(i);
9183     PrintBuildToolVersion(bv);
9184   }
9185 }
9186 
9187 static void PrintSourceVersionCommand(MachO::source_version_command sd) {
9188   outs() << "      cmd LC_SOURCE_VERSION\n";
9189   outs() << "  cmdsize " << sd.cmdsize;
9190   if (sd.cmdsize != sizeof(struct MachO::source_version_command))
9191     outs() << " Incorrect size\n";
9192   else
9193     outs() << "\n";
9194   uint64_t a = (sd.version >> 40) & 0xffffff;
9195   uint64_t b = (sd.version >> 30) & 0x3ff;
9196   uint64_t c = (sd.version >> 20) & 0x3ff;
9197   uint64_t d = (sd.version >> 10) & 0x3ff;
9198   uint64_t e = sd.version & 0x3ff;
9199   outs() << "  version " << a << "." << b;
9200   if (e != 0)
9201     outs() << "." << c << "." << d << "." << e;
9202   else if (d != 0)
9203     outs() << "." << c << "." << d;
9204   else if (c != 0)
9205     outs() << "." << c;
9206   outs() << "\n";
9207 }
9208 
9209 static void PrintEntryPointCommand(MachO::entry_point_command ep) {
9210   outs() << "       cmd LC_MAIN\n";
9211   outs() << "   cmdsize " << ep.cmdsize;
9212   if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
9213     outs() << " Incorrect size\n";
9214   else
9215     outs() << "\n";
9216   outs() << "  entryoff " << ep.entryoff << "\n";
9217   outs() << " stacksize " << ep.stacksize << "\n";
9218 }
9219 
9220 static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
9221                                        uint32_t object_size) {
9222   outs() << "          cmd LC_ENCRYPTION_INFO\n";
9223   outs() << "      cmdsize " << ec.cmdsize;
9224   if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
9225     outs() << " Incorrect size\n";
9226   else
9227     outs() << "\n";
9228   outs() << "     cryptoff " << ec.cryptoff;
9229   if (ec.cryptoff > object_size)
9230     outs() << " (past end of file)\n";
9231   else
9232     outs() << "\n";
9233   outs() << "    cryptsize " << ec.cryptsize;
9234   if (ec.cryptsize > object_size)
9235     outs() << " (past end of file)\n";
9236   else
9237     outs() << "\n";
9238   outs() << "      cryptid " << ec.cryptid << "\n";
9239 }
9240 
9241 static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
9242                                          uint32_t object_size) {
9243   outs() << "          cmd LC_ENCRYPTION_INFO_64\n";
9244   outs() << "      cmdsize " << ec.cmdsize;
9245   if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
9246     outs() << " Incorrect size\n";
9247   else
9248     outs() << "\n";
9249   outs() << "     cryptoff " << ec.cryptoff;
9250   if (ec.cryptoff > object_size)
9251     outs() << " (past end of file)\n";
9252   else
9253     outs() << "\n";
9254   outs() << "    cryptsize " << ec.cryptsize;
9255   if (ec.cryptsize > object_size)
9256     outs() << " (past end of file)\n";
9257   else
9258     outs() << "\n";
9259   outs() << "      cryptid " << ec.cryptid << "\n";
9260   outs() << "          pad " << ec.pad << "\n";
9261 }
9262 
9263 static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
9264                                      const char *Ptr) {
9265   outs() << "     cmd LC_LINKER_OPTION\n";
9266   outs() << " cmdsize " << lo.cmdsize;
9267   if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
9268     outs() << " Incorrect size\n";
9269   else
9270     outs() << "\n";
9271   outs() << "   count " << lo.count << "\n";
9272   const char *string = Ptr + sizeof(struct MachO::linker_option_command);
9273   uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
9274   uint32_t i = 0;
9275   while (left > 0) {
9276     while (*string == '\0' && left > 0) {
9277       string++;
9278       left--;
9279     }
9280     if (left > 0) {
9281       i++;
9282       outs() << "  string #" << i << " " << format("%.*s\n", left, string);
9283       uint32_t NullPos = StringRef(string, left).find('\0');
9284       uint32_t len = std::min(NullPos, left) + 1;
9285       string += len;
9286       left -= len;
9287     }
9288   }
9289   if (lo.count != i)
9290     outs() << "   count " << lo.count << " does not match number of strings "
9291            << i << "\n";
9292 }
9293 
9294 static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
9295                                      const char *Ptr) {
9296   outs() << "          cmd LC_SUB_FRAMEWORK\n";
9297   outs() << "      cmdsize " << sub.cmdsize;
9298   if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
9299     outs() << " Incorrect size\n";
9300   else
9301     outs() << "\n";
9302   if (sub.umbrella < sub.cmdsize) {
9303     const char *P = Ptr + sub.umbrella;
9304     outs() << "     umbrella " << P << " (offset " << sub.umbrella << ")\n";
9305   } else {
9306     outs() << "     umbrella ?(bad offset " << sub.umbrella << ")\n";
9307   }
9308 }
9309 
9310 static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
9311                                     const char *Ptr) {
9312   outs() << "          cmd LC_SUB_UMBRELLA\n";
9313   outs() << "      cmdsize " << sub.cmdsize;
9314   if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
9315     outs() << " Incorrect size\n";
9316   else
9317     outs() << "\n";
9318   if (sub.sub_umbrella < sub.cmdsize) {
9319     const char *P = Ptr + sub.sub_umbrella;
9320     outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
9321   } else {
9322     outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
9323   }
9324 }
9325 
9326 static void PrintSubLibraryCommand(MachO::sub_library_command sub,
9327                                    const char *Ptr) {
9328   outs() << "          cmd LC_SUB_LIBRARY\n";
9329   outs() << "      cmdsize " << sub.cmdsize;
9330   if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
9331     outs() << " Incorrect size\n";
9332   else
9333     outs() << "\n";
9334   if (sub.sub_library < sub.cmdsize) {
9335     const char *P = Ptr + sub.sub_library;
9336     outs() << "  sub_library " << P << " (offset " << sub.sub_library << ")\n";
9337   } else {
9338     outs() << "  sub_library ?(bad offset " << sub.sub_library << ")\n";
9339   }
9340 }
9341 
9342 static void PrintSubClientCommand(MachO::sub_client_command sub,
9343                                   const char *Ptr) {
9344   outs() << "          cmd LC_SUB_CLIENT\n";
9345   outs() << "      cmdsize " << sub.cmdsize;
9346   if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
9347     outs() << " Incorrect size\n";
9348   else
9349     outs() << "\n";
9350   if (sub.client < sub.cmdsize) {
9351     const char *P = Ptr + sub.client;
9352     outs() << "       client " << P << " (offset " << sub.client << ")\n";
9353   } else {
9354     outs() << "       client ?(bad offset " << sub.client << ")\n";
9355   }
9356 }
9357 
9358 static void PrintRoutinesCommand(MachO::routines_command r) {
9359   outs() << "          cmd LC_ROUTINES\n";
9360   outs() << "      cmdsize " << r.cmdsize;
9361   if (r.cmdsize != sizeof(struct MachO::routines_command))
9362     outs() << " Incorrect size\n";
9363   else
9364     outs() << "\n";
9365   outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
9366   outs() << "  init_module " << r.init_module << "\n";
9367   outs() << "    reserved1 " << r.reserved1 << "\n";
9368   outs() << "    reserved2 " << r.reserved2 << "\n";
9369   outs() << "    reserved3 " << r.reserved3 << "\n";
9370   outs() << "    reserved4 " << r.reserved4 << "\n";
9371   outs() << "    reserved5 " << r.reserved5 << "\n";
9372   outs() << "    reserved6 " << r.reserved6 << "\n";
9373 }
9374 
9375 static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
9376   outs() << "          cmd LC_ROUTINES_64\n";
9377   outs() << "      cmdsize " << r.cmdsize;
9378   if (r.cmdsize != sizeof(struct MachO::routines_command_64))
9379     outs() << " Incorrect size\n";
9380   else
9381     outs() << "\n";
9382   outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
9383   outs() << "  init_module " << r.init_module << "\n";
9384   outs() << "    reserved1 " << r.reserved1 << "\n";
9385   outs() << "    reserved2 " << r.reserved2 << "\n";
9386   outs() << "    reserved3 " << r.reserved3 << "\n";
9387   outs() << "    reserved4 " << r.reserved4 << "\n";
9388   outs() << "    reserved5 " << r.reserved5 << "\n";
9389   outs() << "    reserved6 " << r.reserved6 << "\n";
9390 }
9391 
9392 static void Print_x86_thread_state32_t(MachO::x86_thread_state32_t &cpu32) {
9393   outs() << "\t    eax " << format("0x%08" PRIx32, cpu32.eax);
9394   outs() << " ebx    " << format("0x%08" PRIx32, cpu32.ebx);
9395   outs() << " ecx " << format("0x%08" PRIx32, cpu32.ecx);
9396   outs() << " edx " << format("0x%08" PRIx32, cpu32.edx) << "\n";
9397   outs() << "\t    edi " << format("0x%08" PRIx32, cpu32.edi);
9398   outs() << " esi    " << format("0x%08" PRIx32, cpu32.esi);
9399   outs() << " ebp " << format("0x%08" PRIx32, cpu32.ebp);
9400   outs() << " esp " << format("0x%08" PRIx32, cpu32.esp) << "\n";
9401   outs() << "\t    ss  " << format("0x%08" PRIx32, cpu32.ss);
9402   outs() << " eflags " << format("0x%08" PRIx32, cpu32.eflags);
9403   outs() << " eip " << format("0x%08" PRIx32, cpu32.eip);
9404   outs() << " cs  " << format("0x%08" PRIx32, cpu32.cs) << "\n";
9405   outs() << "\t    ds  " << format("0x%08" PRIx32, cpu32.ds);
9406   outs() << " es     " << format("0x%08" PRIx32, cpu32.es);
9407   outs() << " fs  " << format("0x%08" PRIx32, cpu32.fs);
9408   outs() << " gs  " << format("0x%08" PRIx32, cpu32.gs) << "\n";
9409 }
9410 
9411 static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
9412   outs() << "   rax  " << format("0x%016" PRIx64, cpu64.rax);
9413   outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
9414   outs() << " rcx  " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
9415   outs() << "   rdx  " << format("0x%016" PRIx64, cpu64.rdx);
9416   outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
9417   outs() << " rsi  " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
9418   outs() << "   rbp  " << format("0x%016" PRIx64, cpu64.rbp);
9419   outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
9420   outs() << " r8   " << format("0x%016" PRIx64, cpu64.r8) << "\n";
9421   outs() << "    r9  " << format("0x%016" PRIx64, cpu64.r9);
9422   outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
9423   outs() << " r11  " << format("0x%016" PRIx64, cpu64.r11) << "\n";
9424   outs() << "   r12  " << format("0x%016" PRIx64, cpu64.r12);
9425   outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
9426   outs() << " r14  " << format("0x%016" PRIx64, cpu64.r14) << "\n";
9427   outs() << "   r15  " << format("0x%016" PRIx64, cpu64.r15);
9428   outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
9429   outs() << "rflags  " << format("0x%016" PRIx64, cpu64.rflags);
9430   outs() << " cs  " << format("0x%016" PRIx64, cpu64.cs);
9431   outs() << " fs   " << format("0x%016" PRIx64, cpu64.fs) << "\n";
9432   outs() << "    gs  " << format("0x%016" PRIx64, cpu64.gs) << "\n";
9433 }
9434 
9435 static void Print_mmst_reg(MachO::mmst_reg_t &r) {
9436   uint32_t f;
9437   outs() << "\t      mmst_reg  ";
9438   for (f = 0; f < 10; f++)
9439     outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
9440   outs() << "\n";
9441   outs() << "\t      mmst_rsrv ";
9442   for (f = 0; f < 6; f++)
9443     outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
9444   outs() << "\n";
9445 }
9446 
9447 static void Print_xmm_reg(MachO::xmm_reg_t &r) {
9448   uint32_t f;
9449   outs() << "\t      xmm_reg ";
9450   for (f = 0; f < 16; f++)
9451     outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
9452   outs() << "\n";
9453 }
9454 
9455 static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
9456   outs() << "\t    fpu_reserved[0] " << fpu.fpu_reserved[0];
9457   outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
9458   outs() << "\t    control: invalid " << fpu.fpu_fcw.invalid;
9459   outs() << " denorm " << fpu.fpu_fcw.denorm;
9460   outs() << " zdiv " << fpu.fpu_fcw.zdiv;
9461   outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
9462   outs() << " undfl " << fpu.fpu_fcw.undfl;
9463   outs() << " precis " << fpu.fpu_fcw.precis << "\n";
9464   outs() << "\t\t     pc ";
9465   if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
9466     outs() << "FP_PREC_24B ";
9467   else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
9468     outs() << "FP_PREC_53B ";
9469   else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
9470     outs() << "FP_PREC_64B ";
9471   else
9472     outs() << fpu.fpu_fcw.pc << " ";
9473   outs() << "rc ";
9474   if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
9475     outs() << "FP_RND_NEAR ";
9476   else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
9477     outs() << "FP_RND_DOWN ";
9478   else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
9479     outs() << "FP_RND_UP ";
9480   else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
9481     outs() << "FP_CHOP ";
9482   outs() << "\n";
9483   outs() << "\t    status: invalid " << fpu.fpu_fsw.invalid;
9484   outs() << " denorm " << fpu.fpu_fsw.denorm;
9485   outs() << " zdiv " << fpu.fpu_fsw.zdiv;
9486   outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
9487   outs() << " undfl " << fpu.fpu_fsw.undfl;
9488   outs() << " precis " << fpu.fpu_fsw.precis;
9489   outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
9490   outs() << "\t            errsumm " << fpu.fpu_fsw.errsumm;
9491   outs() << " c0 " << fpu.fpu_fsw.c0;
9492   outs() << " c1 " << fpu.fpu_fsw.c1;
9493   outs() << " c2 " << fpu.fpu_fsw.c2;
9494   outs() << " tos " << fpu.fpu_fsw.tos;
9495   outs() << " c3 " << fpu.fpu_fsw.c3;
9496   outs() << " busy " << fpu.fpu_fsw.busy << "\n";
9497   outs() << "\t    fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
9498   outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
9499   outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
9500   outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
9501   outs() << "\t    fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
9502   outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
9503   outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
9504   outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
9505   outs() << "\t    fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
9506   outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
9507   outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
9508   outs() << "\n";
9509   outs() << "\t    fpu_stmm0:\n";
9510   Print_mmst_reg(fpu.fpu_stmm0);
9511   outs() << "\t    fpu_stmm1:\n";
9512   Print_mmst_reg(fpu.fpu_stmm1);
9513   outs() << "\t    fpu_stmm2:\n";
9514   Print_mmst_reg(fpu.fpu_stmm2);
9515   outs() << "\t    fpu_stmm3:\n";
9516   Print_mmst_reg(fpu.fpu_stmm3);
9517   outs() << "\t    fpu_stmm4:\n";
9518   Print_mmst_reg(fpu.fpu_stmm4);
9519   outs() << "\t    fpu_stmm5:\n";
9520   Print_mmst_reg(fpu.fpu_stmm5);
9521   outs() << "\t    fpu_stmm6:\n";
9522   Print_mmst_reg(fpu.fpu_stmm6);
9523   outs() << "\t    fpu_stmm7:\n";
9524   Print_mmst_reg(fpu.fpu_stmm7);
9525   outs() << "\t    fpu_xmm0:\n";
9526   Print_xmm_reg(fpu.fpu_xmm0);
9527   outs() << "\t    fpu_xmm1:\n";
9528   Print_xmm_reg(fpu.fpu_xmm1);
9529   outs() << "\t    fpu_xmm2:\n";
9530   Print_xmm_reg(fpu.fpu_xmm2);
9531   outs() << "\t    fpu_xmm3:\n";
9532   Print_xmm_reg(fpu.fpu_xmm3);
9533   outs() << "\t    fpu_xmm4:\n";
9534   Print_xmm_reg(fpu.fpu_xmm4);
9535   outs() << "\t    fpu_xmm5:\n";
9536   Print_xmm_reg(fpu.fpu_xmm5);
9537   outs() << "\t    fpu_xmm6:\n";
9538   Print_xmm_reg(fpu.fpu_xmm6);
9539   outs() << "\t    fpu_xmm7:\n";
9540   Print_xmm_reg(fpu.fpu_xmm7);
9541   outs() << "\t    fpu_xmm8:\n";
9542   Print_xmm_reg(fpu.fpu_xmm8);
9543   outs() << "\t    fpu_xmm9:\n";
9544   Print_xmm_reg(fpu.fpu_xmm9);
9545   outs() << "\t    fpu_xmm10:\n";
9546   Print_xmm_reg(fpu.fpu_xmm10);
9547   outs() << "\t    fpu_xmm11:\n";
9548   Print_xmm_reg(fpu.fpu_xmm11);
9549   outs() << "\t    fpu_xmm12:\n";
9550   Print_xmm_reg(fpu.fpu_xmm12);
9551   outs() << "\t    fpu_xmm13:\n";
9552   Print_xmm_reg(fpu.fpu_xmm13);
9553   outs() << "\t    fpu_xmm14:\n";
9554   Print_xmm_reg(fpu.fpu_xmm14);
9555   outs() << "\t    fpu_xmm15:\n";
9556   Print_xmm_reg(fpu.fpu_xmm15);
9557   outs() << "\t    fpu_rsrv4:\n";
9558   for (uint32_t f = 0; f < 6; f++) {
9559     outs() << "\t            ";
9560     for (uint32_t g = 0; g < 16; g++)
9561       outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
9562     outs() << "\n";
9563   }
9564   outs() << "\t    fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
9565   outs() << "\n";
9566 }
9567 
9568 static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
9569   outs() << "\t    trapno " << format("0x%08" PRIx32, exc64.trapno);
9570   outs() << " err " << format("0x%08" PRIx32, exc64.err);
9571   outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
9572 }
9573 
9574 static void Print_arm_thread_state32_t(MachO::arm_thread_state32_t &cpu32) {
9575   outs() << "\t    r0  " << format("0x%08" PRIx32, cpu32.r[0]);
9576   outs() << " r1     "   << format("0x%08" PRIx32, cpu32.r[1]);
9577   outs() << " r2  "      << format("0x%08" PRIx32, cpu32.r[2]);
9578   outs() << " r3  "      << format("0x%08" PRIx32, cpu32.r[3]) << "\n";
9579   outs() << "\t    r4  " << format("0x%08" PRIx32, cpu32.r[4]);
9580   outs() << " r5     "   << format("0x%08" PRIx32, cpu32.r[5]);
9581   outs() << " r6  "      << format("0x%08" PRIx32, cpu32.r[6]);
9582   outs() << " r7  "      << format("0x%08" PRIx32, cpu32.r[7]) << "\n";
9583   outs() << "\t    r8  " << format("0x%08" PRIx32, cpu32.r[8]);
9584   outs() << " r9     "   << format("0x%08" PRIx32, cpu32.r[9]);
9585   outs() << " r10 "      << format("0x%08" PRIx32, cpu32.r[10]);
9586   outs() << " r11 "      << format("0x%08" PRIx32, cpu32.r[11]) << "\n";
9587   outs() << "\t    r12 " << format("0x%08" PRIx32, cpu32.r[12]);
9588   outs() << " sp     "   << format("0x%08" PRIx32, cpu32.sp);
9589   outs() << " lr  "      << format("0x%08" PRIx32, cpu32.lr);
9590   outs() << " pc  "      << format("0x%08" PRIx32, cpu32.pc) << "\n";
9591   outs() << "\t   cpsr " << format("0x%08" PRIx32, cpu32.cpsr) << "\n";
9592 }
9593 
9594 static void Print_arm_thread_state64_t(MachO::arm_thread_state64_t &cpu64) {
9595   outs() << "\t    x0  " << format("0x%016" PRIx64, cpu64.x[0]);
9596   outs() << " x1  "      << format("0x%016" PRIx64, cpu64.x[1]);
9597   outs() << " x2  "      << format("0x%016" PRIx64, cpu64.x[2]) << "\n";
9598   outs() << "\t    x3  " << format("0x%016" PRIx64, cpu64.x[3]);
9599   outs() << " x4  "      << format("0x%016" PRIx64, cpu64.x[4]);
9600   outs() << " x5  "      << format("0x%016" PRIx64, cpu64.x[5]) << "\n";
9601   outs() << "\t    x6  " << format("0x%016" PRIx64, cpu64.x[6]);
9602   outs() << " x7  "      << format("0x%016" PRIx64, cpu64.x[7]);
9603   outs() << " x8  "      << format("0x%016" PRIx64, cpu64.x[8]) << "\n";
9604   outs() << "\t    x9  " << format("0x%016" PRIx64, cpu64.x[9]);
9605   outs() << " x10 "      << format("0x%016" PRIx64, cpu64.x[10]);
9606   outs() << " x11 "      << format("0x%016" PRIx64, cpu64.x[11]) << "\n";
9607   outs() << "\t    x12 " << format("0x%016" PRIx64, cpu64.x[12]);
9608   outs() << " x13 "      << format("0x%016" PRIx64, cpu64.x[13]);
9609   outs() << " x14 "      << format("0x%016" PRIx64, cpu64.x[14]) << "\n";
9610   outs() << "\t    x15 " << format("0x%016" PRIx64, cpu64.x[15]);
9611   outs() << " x16 "      << format("0x%016" PRIx64, cpu64.x[16]);
9612   outs() << " x17 "      << format("0x%016" PRIx64, cpu64.x[17]) << "\n";
9613   outs() << "\t    x18 " << format("0x%016" PRIx64, cpu64.x[18]);
9614   outs() << " x19 "      << format("0x%016" PRIx64, cpu64.x[19]);
9615   outs() << " x20 "      << format("0x%016" PRIx64, cpu64.x[20]) << "\n";
9616   outs() << "\t    x21 " << format("0x%016" PRIx64, cpu64.x[21]);
9617   outs() << " x22 "      << format("0x%016" PRIx64, cpu64.x[22]);
9618   outs() << " x23 "      << format("0x%016" PRIx64, cpu64.x[23]) << "\n";
9619   outs() << "\t    x24 " << format("0x%016" PRIx64, cpu64.x[24]);
9620   outs() << " x25 "      << format("0x%016" PRIx64, cpu64.x[25]);
9621   outs() << " x26 "      << format("0x%016" PRIx64, cpu64.x[26]) << "\n";
9622   outs() << "\t    x27 " << format("0x%016" PRIx64, cpu64.x[27]);
9623   outs() << " x28 "      << format("0x%016" PRIx64, cpu64.x[28]);
9624   outs() << "  fp "      << format("0x%016" PRIx64, cpu64.fp) << "\n";
9625   outs() << "\t     lr " << format("0x%016" PRIx64, cpu64.lr);
9626   outs() << " sp  "      << format("0x%016" PRIx64, cpu64.sp);
9627   outs() << "  pc "      << format("0x%016" PRIx64, cpu64.pc) << "\n";
9628   outs() << "\t   cpsr " << format("0x%08"  PRIx32, cpu64.cpsr) << "\n";
9629 }
9630 
9631 static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
9632                                bool isLittleEndian, uint32_t cputype) {
9633   if (t.cmd == MachO::LC_THREAD)
9634     outs() << "        cmd LC_THREAD\n";
9635   else if (t.cmd == MachO::LC_UNIXTHREAD)
9636     outs() << "        cmd LC_UNIXTHREAD\n";
9637   else
9638     outs() << "        cmd " << t.cmd << " (unknown)\n";
9639   outs() << "    cmdsize " << t.cmdsize;
9640   if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
9641     outs() << " Incorrect size\n";
9642   else
9643     outs() << "\n";
9644 
9645   const char *begin = Ptr + sizeof(struct MachO::thread_command);
9646   const char *end = Ptr + t.cmdsize;
9647   uint32_t flavor, count, left;
9648   if (cputype == MachO::CPU_TYPE_I386) {
9649     while (begin < end) {
9650       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9651         memcpy((char *)&flavor, begin, sizeof(uint32_t));
9652         begin += sizeof(uint32_t);
9653       } else {
9654         flavor = 0;
9655         begin = end;
9656       }
9657       if (isLittleEndian != sys::IsLittleEndianHost)
9658         sys::swapByteOrder(flavor);
9659       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9660         memcpy((char *)&count, begin, sizeof(uint32_t));
9661         begin += sizeof(uint32_t);
9662       } else {
9663         count = 0;
9664         begin = end;
9665       }
9666       if (isLittleEndian != sys::IsLittleEndianHost)
9667         sys::swapByteOrder(count);
9668       if (flavor == MachO::x86_THREAD_STATE32) {
9669         outs() << "     flavor i386_THREAD_STATE\n";
9670         if (count == MachO::x86_THREAD_STATE32_COUNT)
9671           outs() << "      count i386_THREAD_STATE_COUNT\n";
9672         else
9673           outs() << "      count " << count
9674                  << " (not x86_THREAD_STATE32_COUNT)\n";
9675         MachO::x86_thread_state32_t cpu32;
9676         left = end - begin;
9677         if (left >= sizeof(MachO::x86_thread_state32_t)) {
9678           memcpy(&cpu32, begin, sizeof(MachO::x86_thread_state32_t));
9679           begin += sizeof(MachO::x86_thread_state32_t);
9680         } else {
9681           memset(&cpu32, '\0', sizeof(MachO::x86_thread_state32_t));
9682           memcpy(&cpu32, begin, left);
9683           begin += left;
9684         }
9685         if (isLittleEndian != sys::IsLittleEndianHost)
9686           swapStruct(cpu32);
9687         Print_x86_thread_state32_t(cpu32);
9688       } else if (flavor == MachO::x86_THREAD_STATE) {
9689         outs() << "     flavor x86_THREAD_STATE\n";
9690         if (count == MachO::x86_THREAD_STATE_COUNT)
9691           outs() << "      count x86_THREAD_STATE_COUNT\n";
9692         else
9693           outs() << "      count " << count
9694                  << " (not x86_THREAD_STATE_COUNT)\n";
9695         struct MachO::x86_thread_state_t ts;
9696         left = end - begin;
9697         if (left >= sizeof(MachO::x86_thread_state_t)) {
9698           memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
9699           begin += sizeof(MachO::x86_thread_state_t);
9700         } else {
9701           memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
9702           memcpy(&ts, begin, left);
9703           begin += left;
9704         }
9705         if (isLittleEndian != sys::IsLittleEndianHost)
9706           swapStruct(ts);
9707         if (ts.tsh.flavor == MachO::x86_THREAD_STATE32) {
9708           outs() << "\t    tsh.flavor x86_THREAD_STATE32 ";
9709           if (ts.tsh.count == MachO::x86_THREAD_STATE32_COUNT)
9710             outs() << "tsh.count x86_THREAD_STATE32_COUNT\n";
9711           else
9712             outs() << "tsh.count " << ts.tsh.count
9713                    << " (not x86_THREAD_STATE32_COUNT\n";
9714           Print_x86_thread_state32_t(ts.uts.ts32);
9715         } else {
9716           outs() << "\t    tsh.flavor " << ts.tsh.flavor << "  tsh.count "
9717                  << ts.tsh.count << "\n";
9718         }
9719       } else {
9720         outs() << "     flavor " << flavor << " (unknown)\n";
9721         outs() << "      count " << count << "\n";
9722         outs() << "      state (unknown)\n";
9723         begin += count * sizeof(uint32_t);
9724       }
9725     }
9726   } else if (cputype == MachO::CPU_TYPE_X86_64) {
9727     while (begin < end) {
9728       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9729         memcpy((char *)&flavor, begin, sizeof(uint32_t));
9730         begin += sizeof(uint32_t);
9731       } else {
9732         flavor = 0;
9733         begin = end;
9734       }
9735       if (isLittleEndian != sys::IsLittleEndianHost)
9736         sys::swapByteOrder(flavor);
9737       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9738         memcpy((char *)&count, begin, sizeof(uint32_t));
9739         begin += sizeof(uint32_t);
9740       } else {
9741         count = 0;
9742         begin = end;
9743       }
9744       if (isLittleEndian != sys::IsLittleEndianHost)
9745         sys::swapByteOrder(count);
9746       if (flavor == MachO::x86_THREAD_STATE64) {
9747         outs() << "     flavor x86_THREAD_STATE64\n";
9748         if (count == MachO::x86_THREAD_STATE64_COUNT)
9749           outs() << "      count x86_THREAD_STATE64_COUNT\n";
9750         else
9751           outs() << "      count " << count
9752                  << " (not x86_THREAD_STATE64_COUNT)\n";
9753         MachO::x86_thread_state64_t cpu64;
9754         left = end - begin;
9755         if (left >= sizeof(MachO::x86_thread_state64_t)) {
9756           memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
9757           begin += sizeof(MachO::x86_thread_state64_t);
9758         } else {
9759           memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
9760           memcpy(&cpu64, begin, left);
9761           begin += left;
9762         }
9763         if (isLittleEndian != sys::IsLittleEndianHost)
9764           swapStruct(cpu64);
9765         Print_x86_thread_state64_t(cpu64);
9766       } else if (flavor == MachO::x86_THREAD_STATE) {
9767         outs() << "     flavor x86_THREAD_STATE\n";
9768         if (count == MachO::x86_THREAD_STATE_COUNT)
9769           outs() << "      count x86_THREAD_STATE_COUNT\n";
9770         else
9771           outs() << "      count " << count
9772                  << " (not x86_THREAD_STATE_COUNT)\n";
9773         struct MachO::x86_thread_state_t ts;
9774         left = end - begin;
9775         if (left >= sizeof(MachO::x86_thread_state_t)) {
9776           memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
9777           begin += sizeof(MachO::x86_thread_state_t);
9778         } else {
9779           memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
9780           memcpy(&ts, begin, left);
9781           begin += left;
9782         }
9783         if (isLittleEndian != sys::IsLittleEndianHost)
9784           swapStruct(ts);
9785         if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
9786           outs() << "\t    tsh.flavor x86_THREAD_STATE64 ";
9787           if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
9788             outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
9789           else
9790             outs() << "tsh.count " << ts.tsh.count
9791                    << " (not x86_THREAD_STATE64_COUNT\n";
9792           Print_x86_thread_state64_t(ts.uts.ts64);
9793         } else {
9794           outs() << "\t    tsh.flavor " << ts.tsh.flavor << "  tsh.count "
9795                  << ts.tsh.count << "\n";
9796         }
9797       } else if (flavor == MachO::x86_FLOAT_STATE) {
9798         outs() << "     flavor x86_FLOAT_STATE\n";
9799         if (count == MachO::x86_FLOAT_STATE_COUNT)
9800           outs() << "      count x86_FLOAT_STATE_COUNT\n";
9801         else
9802           outs() << "      count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
9803         struct MachO::x86_float_state_t fs;
9804         left = end - begin;
9805         if (left >= sizeof(MachO::x86_float_state_t)) {
9806           memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
9807           begin += sizeof(MachO::x86_float_state_t);
9808         } else {
9809           memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
9810           memcpy(&fs, begin, left);
9811           begin += left;
9812         }
9813         if (isLittleEndian != sys::IsLittleEndianHost)
9814           swapStruct(fs);
9815         if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
9816           outs() << "\t    fsh.flavor x86_FLOAT_STATE64 ";
9817           if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
9818             outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
9819           else
9820             outs() << "fsh.count " << fs.fsh.count
9821                    << " (not x86_FLOAT_STATE64_COUNT\n";
9822           Print_x86_float_state_t(fs.ufs.fs64);
9823         } else {
9824           outs() << "\t    fsh.flavor " << fs.fsh.flavor << "  fsh.count "
9825                  << fs.fsh.count << "\n";
9826         }
9827       } else if (flavor == MachO::x86_EXCEPTION_STATE) {
9828         outs() << "     flavor x86_EXCEPTION_STATE\n";
9829         if (count == MachO::x86_EXCEPTION_STATE_COUNT)
9830           outs() << "      count x86_EXCEPTION_STATE_COUNT\n";
9831         else
9832           outs() << "      count " << count
9833                  << " (not x86_EXCEPTION_STATE_COUNT)\n";
9834         struct MachO::x86_exception_state_t es;
9835         left = end - begin;
9836         if (left >= sizeof(MachO::x86_exception_state_t)) {
9837           memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
9838           begin += sizeof(MachO::x86_exception_state_t);
9839         } else {
9840           memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
9841           memcpy(&es, begin, left);
9842           begin += left;
9843         }
9844         if (isLittleEndian != sys::IsLittleEndianHost)
9845           swapStruct(es);
9846         if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
9847           outs() << "\t    esh.flavor x86_EXCEPTION_STATE64\n";
9848           if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
9849             outs() << "\t    esh.count x86_EXCEPTION_STATE64_COUNT\n";
9850           else
9851             outs() << "\t    esh.count " << es.esh.count
9852                    << " (not x86_EXCEPTION_STATE64_COUNT\n";
9853           Print_x86_exception_state_t(es.ues.es64);
9854         } else {
9855           outs() << "\t    esh.flavor " << es.esh.flavor << "  esh.count "
9856                  << es.esh.count << "\n";
9857         }
9858       } else if (flavor == MachO::x86_EXCEPTION_STATE64) {
9859         outs() << "     flavor x86_EXCEPTION_STATE64\n";
9860         if (count == MachO::x86_EXCEPTION_STATE64_COUNT)
9861           outs() << "      count x86_EXCEPTION_STATE64_COUNT\n";
9862         else
9863           outs() << "      count " << count
9864                  << " (not x86_EXCEPTION_STATE64_COUNT)\n";
9865         struct MachO::x86_exception_state64_t es64;
9866         left = end - begin;
9867         if (left >= sizeof(MachO::x86_exception_state64_t)) {
9868           memcpy(&es64, begin, sizeof(MachO::x86_exception_state64_t));
9869           begin += sizeof(MachO::x86_exception_state64_t);
9870         } else {
9871           memset(&es64, '\0', sizeof(MachO::x86_exception_state64_t));
9872           memcpy(&es64, begin, left);
9873           begin += left;
9874         }
9875         if (isLittleEndian != sys::IsLittleEndianHost)
9876           swapStruct(es64);
9877         Print_x86_exception_state_t(es64);
9878       } else {
9879         outs() << "     flavor " << flavor << " (unknown)\n";
9880         outs() << "      count " << count << "\n";
9881         outs() << "      state (unknown)\n";
9882         begin += count * sizeof(uint32_t);
9883       }
9884     }
9885   } else if (cputype == MachO::CPU_TYPE_ARM) {
9886     while (begin < end) {
9887       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9888         memcpy((char *)&flavor, begin, sizeof(uint32_t));
9889         begin += sizeof(uint32_t);
9890       } else {
9891         flavor = 0;
9892         begin = end;
9893       }
9894       if (isLittleEndian != sys::IsLittleEndianHost)
9895         sys::swapByteOrder(flavor);
9896       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9897         memcpy((char *)&count, begin, sizeof(uint32_t));
9898         begin += sizeof(uint32_t);
9899       } else {
9900         count = 0;
9901         begin = end;
9902       }
9903       if (isLittleEndian != sys::IsLittleEndianHost)
9904         sys::swapByteOrder(count);
9905       if (flavor == MachO::ARM_THREAD_STATE) {
9906         outs() << "     flavor ARM_THREAD_STATE\n";
9907         if (count == MachO::ARM_THREAD_STATE_COUNT)
9908           outs() << "      count ARM_THREAD_STATE_COUNT\n";
9909         else
9910           outs() << "      count " << count
9911                  << " (not ARM_THREAD_STATE_COUNT)\n";
9912         MachO::arm_thread_state32_t cpu32;
9913         left = end - begin;
9914         if (left >= sizeof(MachO::arm_thread_state32_t)) {
9915           memcpy(&cpu32, begin, sizeof(MachO::arm_thread_state32_t));
9916           begin += sizeof(MachO::arm_thread_state32_t);
9917         } else {
9918           memset(&cpu32, '\0', sizeof(MachO::arm_thread_state32_t));
9919           memcpy(&cpu32, begin, left);
9920           begin += left;
9921         }
9922         if (isLittleEndian != sys::IsLittleEndianHost)
9923           swapStruct(cpu32);
9924         Print_arm_thread_state32_t(cpu32);
9925       } else {
9926         outs() << "     flavor " << flavor << " (unknown)\n";
9927         outs() << "      count " << count << "\n";
9928         outs() << "      state (unknown)\n";
9929         begin += count * sizeof(uint32_t);
9930       }
9931     }
9932   } else if (cputype == MachO::CPU_TYPE_ARM64 ||
9933              cputype == MachO::CPU_TYPE_ARM64_32) {
9934     while (begin < end) {
9935       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9936         memcpy((char *)&flavor, begin, sizeof(uint32_t));
9937         begin += sizeof(uint32_t);
9938       } else {
9939         flavor = 0;
9940         begin = end;
9941       }
9942       if (isLittleEndian != sys::IsLittleEndianHost)
9943         sys::swapByteOrder(flavor);
9944       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9945         memcpy((char *)&count, begin, sizeof(uint32_t));
9946         begin += sizeof(uint32_t);
9947       } else {
9948         count = 0;
9949         begin = end;
9950       }
9951       if (isLittleEndian != sys::IsLittleEndianHost)
9952         sys::swapByteOrder(count);
9953       if (flavor == MachO::ARM_THREAD_STATE64) {
9954         outs() << "     flavor ARM_THREAD_STATE64\n";
9955         if (count == MachO::ARM_THREAD_STATE64_COUNT)
9956           outs() << "      count ARM_THREAD_STATE64_COUNT\n";
9957         else
9958           outs() << "      count " << count
9959                  << " (not ARM_THREAD_STATE64_COUNT)\n";
9960         MachO::arm_thread_state64_t cpu64;
9961         left = end - begin;
9962         if (left >= sizeof(MachO::arm_thread_state64_t)) {
9963           memcpy(&cpu64, begin, sizeof(MachO::arm_thread_state64_t));
9964           begin += sizeof(MachO::arm_thread_state64_t);
9965         } else {
9966           memset(&cpu64, '\0', sizeof(MachO::arm_thread_state64_t));
9967           memcpy(&cpu64, begin, left);
9968           begin += left;
9969         }
9970         if (isLittleEndian != sys::IsLittleEndianHost)
9971           swapStruct(cpu64);
9972         Print_arm_thread_state64_t(cpu64);
9973       } else {
9974         outs() << "     flavor " << flavor << " (unknown)\n";
9975         outs() << "      count " << count << "\n";
9976         outs() << "      state (unknown)\n";
9977         begin += count * sizeof(uint32_t);
9978       }
9979     }
9980   } else {
9981     while (begin < end) {
9982       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9983         memcpy((char *)&flavor, begin, sizeof(uint32_t));
9984         begin += sizeof(uint32_t);
9985       } else {
9986         flavor = 0;
9987         begin = end;
9988       }
9989       if (isLittleEndian != sys::IsLittleEndianHost)
9990         sys::swapByteOrder(flavor);
9991       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9992         memcpy((char *)&count, begin, sizeof(uint32_t));
9993         begin += sizeof(uint32_t);
9994       } else {
9995         count = 0;
9996         begin = end;
9997       }
9998       if (isLittleEndian != sys::IsLittleEndianHost)
9999         sys::swapByteOrder(count);
10000       outs() << "     flavor " << flavor << "\n";
10001       outs() << "      count " << count << "\n";
10002       outs() << "      state (Unknown cputype/cpusubtype)\n";
10003       begin += count * sizeof(uint32_t);
10004     }
10005   }
10006 }
10007 
10008 static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
10009   if (dl.cmd == MachO::LC_ID_DYLIB)
10010     outs() << "          cmd LC_ID_DYLIB\n";
10011   else if (dl.cmd == MachO::LC_LOAD_DYLIB)
10012     outs() << "          cmd LC_LOAD_DYLIB\n";
10013   else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
10014     outs() << "          cmd LC_LOAD_WEAK_DYLIB\n";
10015   else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
10016     outs() << "          cmd LC_REEXPORT_DYLIB\n";
10017   else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
10018     outs() << "          cmd LC_LAZY_LOAD_DYLIB\n";
10019   else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
10020     outs() << "          cmd LC_LOAD_UPWARD_DYLIB\n";
10021   else
10022     outs() << "          cmd " << dl.cmd << " (unknown)\n";
10023   outs() << "      cmdsize " << dl.cmdsize;
10024   if (dl.cmdsize < sizeof(struct MachO::dylib_command))
10025     outs() << " Incorrect size\n";
10026   else
10027     outs() << "\n";
10028   if (dl.dylib.name < dl.cmdsize) {
10029     const char *P = (const char *)(Ptr) + dl.dylib.name;
10030     outs() << "         name " << P << " (offset " << dl.dylib.name << ")\n";
10031   } else {
10032     outs() << "         name ?(bad offset " << dl.dylib.name << ")\n";
10033   }
10034   outs() << "   time stamp " << dl.dylib.timestamp << " ";
10035   time_t t = dl.dylib.timestamp;
10036   outs() << ctime(&t);
10037   outs() << "      current version ";
10038   if (dl.dylib.current_version == 0xffffffff)
10039     outs() << "n/a\n";
10040   else
10041     outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
10042            << ((dl.dylib.current_version >> 8) & 0xff) << "."
10043            << (dl.dylib.current_version & 0xff) << "\n";
10044   outs() << "compatibility version ";
10045   if (dl.dylib.compatibility_version == 0xffffffff)
10046     outs() << "n/a\n";
10047   else
10048     outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
10049            << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
10050            << (dl.dylib.compatibility_version & 0xff) << "\n";
10051 }
10052 
10053 static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
10054                                      uint32_t object_size) {
10055   if (ld.cmd == MachO::LC_CODE_SIGNATURE)
10056     outs() << "      cmd LC_CODE_SIGNATURE\n";
10057   else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
10058     outs() << "      cmd LC_SEGMENT_SPLIT_INFO\n";
10059   else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
10060     outs() << "      cmd LC_FUNCTION_STARTS\n";
10061   else if (ld.cmd == MachO::LC_DATA_IN_CODE)
10062     outs() << "      cmd LC_DATA_IN_CODE\n";
10063   else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
10064     outs() << "      cmd LC_DYLIB_CODE_SIGN_DRS\n";
10065   else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
10066     outs() << "      cmd LC_LINKER_OPTIMIZATION_HINT\n";
10067   else
10068     outs() << "      cmd " << ld.cmd << " (?)\n";
10069   outs() << "  cmdsize " << ld.cmdsize;
10070   if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
10071     outs() << " Incorrect size\n";
10072   else
10073     outs() << "\n";
10074   outs() << "  dataoff " << ld.dataoff;
10075   if (ld.dataoff > object_size)
10076     outs() << " (past end of file)\n";
10077   else
10078     outs() << "\n";
10079   outs() << " datasize " << ld.datasize;
10080   uint64_t big_size = ld.dataoff;
10081   big_size += ld.datasize;
10082   if (big_size > object_size)
10083     outs() << " (past end of file)\n";
10084   else
10085     outs() << "\n";
10086 }
10087 
10088 static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
10089                               uint32_t cputype, bool verbose) {
10090   StringRef Buf = Obj->getData();
10091   unsigned Index = 0;
10092   for (const auto &Command : Obj->load_commands()) {
10093     outs() << "Load command " << Index++ << "\n";
10094     if (Command.C.cmd == MachO::LC_SEGMENT) {
10095       MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
10096       const char *sg_segname = SLC.segname;
10097       PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
10098                           SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
10099                           SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
10100                           verbose);
10101       for (unsigned j = 0; j < SLC.nsects; j++) {
10102         MachO::section S = Obj->getSection(Command, j);
10103         PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
10104                      S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
10105                      SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
10106       }
10107     } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
10108       MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
10109       const char *sg_segname = SLC_64.segname;
10110       PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
10111                           SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
10112                           SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
10113                           SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
10114       for (unsigned j = 0; j < SLC_64.nsects; j++) {
10115         MachO::section_64 S_64 = Obj->getSection64(Command, j);
10116         PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
10117                      S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
10118                      S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
10119                      sg_segname, filetype, Buf.size(), verbose);
10120       }
10121     } else if (Command.C.cmd == MachO::LC_SYMTAB) {
10122       MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
10123       PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
10124     } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
10125       MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
10126       MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
10127       PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
10128                                Obj->is64Bit());
10129     } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
10130                Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
10131       MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
10132       PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
10133     } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
10134                Command.C.cmd == MachO::LC_ID_DYLINKER ||
10135                Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
10136       MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
10137       PrintDyldLoadCommand(Dyld, Command.Ptr);
10138     } else if (Command.C.cmd == MachO::LC_UUID) {
10139       MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
10140       PrintUuidLoadCommand(Uuid);
10141     } else if (Command.C.cmd == MachO::LC_RPATH) {
10142       MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
10143       PrintRpathLoadCommand(Rpath, Command.Ptr);
10144     } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
10145                Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
10146                Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
10147                Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
10148       MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
10149       PrintVersionMinLoadCommand(Vd);
10150     } else if (Command.C.cmd == MachO::LC_NOTE) {
10151       MachO::note_command Nt = Obj->getNoteLoadCommand(Command);
10152       PrintNoteLoadCommand(Nt);
10153     } else if (Command.C.cmd == MachO::LC_BUILD_VERSION) {
10154       MachO::build_version_command Bv =
10155           Obj->getBuildVersionLoadCommand(Command);
10156       PrintBuildVersionLoadCommand(Obj, Bv);
10157     } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
10158       MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
10159       PrintSourceVersionCommand(Sd);
10160     } else if (Command.C.cmd == MachO::LC_MAIN) {
10161       MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
10162       PrintEntryPointCommand(Ep);
10163     } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
10164       MachO::encryption_info_command Ei =
10165           Obj->getEncryptionInfoCommand(Command);
10166       PrintEncryptionInfoCommand(Ei, Buf.size());
10167     } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
10168       MachO::encryption_info_command_64 Ei =
10169           Obj->getEncryptionInfoCommand64(Command);
10170       PrintEncryptionInfoCommand64(Ei, Buf.size());
10171     } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
10172       MachO::linker_option_command Lo =
10173           Obj->getLinkerOptionLoadCommand(Command);
10174       PrintLinkerOptionCommand(Lo, Command.Ptr);
10175     } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
10176       MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
10177       PrintSubFrameworkCommand(Sf, Command.Ptr);
10178     } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
10179       MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
10180       PrintSubUmbrellaCommand(Sf, Command.Ptr);
10181     } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
10182       MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
10183       PrintSubLibraryCommand(Sl, Command.Ptr);
10184     } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
10185       MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
10186       PrintSubClientCommand(Sc, Command.Ptr);
10187     } else if (Command.C.cmd == MachO::LC_ROUTINES) {
10188       MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
10189       PrintRoutinesCommand(Rc);
10190     } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
10191       MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
10192       PrintRoutinesCommand64(Rc);
10193     } else if (Command.C.cmd == MachO::LC_THREAD ||
10194                Command.C.cmd == MachO::LC_UNIXTHREAD) {
10195       MachO::thread_command Tc = Obj->getThreadCommand(Command);
10196       PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
10197     } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
10198                Command.C.cmd == MachO::LC_ID_DYLIB ||
10199                Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
10200                Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
10201                Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
10202                Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
10203       MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
10204       PrintDylibCommand(Dl, Command.Ptr);
10205     } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
10206                Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
10207                Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
10208                Command.C.cmd == MachO::LC_DATA_IN_CODE ||
10209                Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
10210                Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
10211       MachO::linkedit_data_command Ld =
10212           Obj->getLinkeditDataLoadCommand(Command);
10213       PrintLinkEditDataCommand(Ld, Buf.size());
10214     } else {
10215       outs() << "      cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
10216              << ")\n";
10217       outs() << "  cmdsize " << Command.C.cmdsize << "\n";
10218       // TODO: get and print the raw bytes of the load command.
10219     }
10220     // TODO: print all the other kinds of load commands.
10221   }
10222 }
10223 
10224 static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
10225   if (Obj->is64Bit()) {
10226     MachO::mach_header_64 H_64;
10227     H_64 = Obj->getHeader64();
10228     PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
10229                     H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
10230   } else {
10231     MachO::mach_header H;
10232     H = Obj->getHeader();
10233     PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
10234                     H.sizeofcmds, H.flags, verbose);
10235   }
10236 }
10237 
10238 void objdump::printMachOFileHeader(const object::ObjectFile *Obj) {
10239   const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
10240   PrintMachHeader(file, !NonVerbose);
10241 }
10242 
10243 void objdump::printMachOLoadCommands(const object::ObjectFile *Obj) {
10244   const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
10245   uint32_t filetype = 0;
10246   uint32_t cputype = 0;
10247   if (file->is64Bit()) {
10248     MachO::mach_header_64 H_64;
10249     H_64 = file->getHeader64();
10250     filetype = H_64.filetype;
10251     cputype = H_64.cputype;
10252   } else {
10253     MachO::mach_header H;
10254     H = file->getHeader();
10255     filetype = H.filetype;
10256     cputype = H.cputype;
10257   }
10258   PrintLoadCommands(file, filetype, cputype, !NonVerbose);
10259 }
10260 
10261 //===----------------------------------------------------------------------===//
10262 // export trie dumping
10263 //===----------------------------------------------------------------------===//
10264 
10265 static void printMachOExportsTrie(const object::MachOObjectFile *Obj) {
10266   uint64_t BaseSegmentAddress = 0;
10267   for (const auto &Command : Obj->load_commands()) {
10268     if (Command.C.cmd == MachO::LC_SEGMENT) {
10269       MachO::segment_command Seg = Obj->getSegmentLoadCommand(Command);
10270       if (Seg.fileoff == 0 && Seg.filesize != 0) {
10271         BaseSegmentAddress = Seg.vmaddr;
10272         break;
10273       }
10274     } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
10275       MachO::segment_command_64 Seg = Obj->getSegment64LoadCommand(Command);
10276       if (Seg.fileoff == 0 && Seg.filesize != 0) {
10277         BaseSegmentAddress = Seg.vmaddr;
10278         break;
10279       }
10280     }
10281   }
10282   Error Err = Error::success();
10283   for (const object::ExportEntry &Entry : Obj->exports(Err)) {
10284     uint64_t Flags = Entry.flags();
10285     bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
10286     bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
10287     bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
10288                         MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
10289     bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
10290                 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
10291     bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
10292     if (ReExport)
10293       outs() << "[re-export] ";
10294     else
10295       outs() << format("0x%08llX  ",
10296                        Entry.address() + BaseSegmentAddress);
10297     outs() << Entry.name();
10298     if (WeakDef || ThreadLocal || Resolver || Abs) {
10299       bool NeedsComma = false;
10300       outs() << " [";
10301       if (WeakDef) {
10302         outs() << "weak_def";
10303         NeedsComma = true;
10304       }
10305       if (ThreadLocal) {
10306         if (NeedsComma)
10307           outs() << ", ";
10308         outs() << "per-thread";
10309         NeedsComma = true;
10310       }
10311       if (Abs) {
10312         if (NeedsComma)
10313           outs() << ", ";
10314         outs() << "absolute";
10315         NeedsComma = true;
10316       }
10317       if (Resolver) {
10318         if (NeedsComma)
10319           outs() << ", ";
10320         outs() << format("resolver=0x%08llX", Entry.other());
10321         NeedsComma = true;
10322       }
10323       outs() << "]";
10324     }
10325     if (ReExport) {
10326       StringRef DylibName = "unknown";
10327       int Ordinal = Entry.other() - 1;
10328       Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
10329       if (Entry.otherName().empty())
10330         outs() << " (from " << DylibName << ")";
10331       else
10332         outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
10333     }
10334     outs() << "\n";
10335   }
10336   if (Err)
10337     reportError(std::move(Err), Obj->getFileName());
10338 }
10339 
10340 //===----------------------------------------------------------------------===//
10341 // rebase table dumping
10342 //===----------------------------------------------------------------------===//
10343 
10344 static void printMachORebaseTable(object::MachOObjectFile *Obj) {
10345   outs() << "segment  section            address     type\n";
10346   Error Err = Error::success();
10347   for (const object::MachORebaseEntry &Entry : Obj->rebaseTable(Err)) {
10348     StringRef SegmentName = Entry.segmentName();
10349     StringRef SectionName = Entry.sectionName();
10350     uint64_t Address = Entry.address();
10351 
10352     // Table lines look like: __DATA  __nl_symbol_ptr  0x0000F00C  pointer
10353     outs() << format("%-8s %-18s 0x%08" PRIX64 "  %s\n",
10354                      SegmentName.str().c_str(), SectionName.str().c_str(),
10355                      Address, Entry.typeName().str().c_str());
10356   }
10357   if (Err)
10358     reportError(std::move(Err), Obj->getFileName());
10359 }
10360 
10361 static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
10362   StringRef DylibName;
10363   switch (Ordinal) {
10364   case MachO::BIND_SPECIAL_DYLIB_SELF:
10365     return "this-image";
10366   case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
10367     return "main-executable";
10368   case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
10369     return "flat-namespace";
10370   default:
10371     if (Ordinal > 0) {
10372       std::error_code EC =
10373           Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
10374       if (EC)
10375         return "<<bad library ordinal>>";
10376       return DylibName;
10377     }
10378   }
10379   return "<<unknown special ordinal>>";
10380 }
10381 
10382 //===----------------------------------------------------------------------===//
10383 // bind table dumping
10384 //===----------------------------------------------------------------------===//
10385 
10386 static void printMachOBindTable(object::MachOObjectFile *Obj) {
10387   // Build table of sections so names can used in final output.
10388   outs() << "segment  section            address    type       "
10389             "addend dylib            symbol\n";
10390   Error Err = Error::success();
10391   for (const object::MachOBindEntry &Entry : Obj->bindTable(Err)) {
10392     StringRef SegmentName = Entry.segmentName();
10393     StringRef SectionName = Entry.sectionName();
10394     uint64_t Address = Entry.address();
10395 
10396     // Table lines look like:
10397     //  __DATA  __got  0x00012010    pointer   0 libSystem ___stack_chk_guard
10398     StringRef Attr;
10399     if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
10400       Attr = " (weak_import)";
10401     outs() << left_justify(SegmentName, 8) << " "
10402            << left_justify(SectionName, 18) << " "
10403            << format_hex(Address, 10, true) << " "
10404            << left_justify(Entry.typeName(), 8) << " "
10405            << format_decimal(Entry.addend(), 8) << " "
10406            << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
10407            << Entry.symbolName() << Attr << "\n";
10408   }
10409   if (Err)
10410     reportError(std::move(Err), Obj->getFileName());
10411 }
10412 
10413 //===----------------------------------------------------------------------===//
10414 // lazy bind table dumping
10415 //===----------------------------------------------------------------------===//
10416 
10417 static void printMachOLazyBindTable(object::MachOObjectFile *Obj) {
10418   outs() << "segment  section            address     "
10419             "dylib            symbol\n";
10420   Error Err = Error::success();
10421   for (const object::MachOBindEntry &Entry : Obj->lazyBindTable(Err)) {
10422     StringRef SegmentName = Entry.segmentName();
10423     StringRef SectionName = Entry.sectionName();
10424     uint64_t Address = Entry.address();
10425 
10426     // Table lines look like:
10427     //  __DATA  __got  0x00012010 libSystem ___stack_chk_guard
10428     outs() << left_justify(SegmentName, 8) << " "
10429            << left_justify(SectionName, 18) << " "
10430            << format_hex(Address, 10, true) << " "
10431            << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
10432            << Entry.symbolName() << "\n";
10433   }
10434   if (Err)
10435     reportError(std::move(Err), Obj->getFileName());
10436 }
10437 
10438 //===----------------------------------------------------------------------===//
10439 // weak bind table dumping
10440 //===----------------------------------------------------------------------===//
10441 
10442 static void printMachOWeakBindTable(object::MachOObjectFile *Obj) {
10443   outs() << "segment  section            address     "
10444             "type       addend   symbol\n";
10445   Error Err = Error::success();
10446   for (const object::MachOBindEntry &Entry : Obj->weakBindTable(Err)) {
10447     // Strong symbols don't have a location to update.
10448     if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
10449       outs() << "                                        strong              "
10450              << Entry.symbolName() << "\n";
10451       continue;
10452     }
10453     StringRef SegmentName = Entry.segmentName();
10454     StringRef SectionName = Entry.sectionName();
10455     uint64_t Address = Entry.address();
10456 
10457     // Table lines look like:
10458     // __DATA  __data  0x00001000  pointer    0   _foo
10459     outs() << left_justify(SegmentName, 8) << " "
10460            << left_justify(SectionName, 18) << " "
10461            << format_hex(Address, 10, true) << " "
10462            << left_justify(Entry.typeName(), 8) << " "
10463            << format_decimal(Entry.addend(), 8) << "   " << Entry.symbolName()
10464            << "\n";
10465   }
10466   if (Err)
10467     reportError(std::move(Err), Obj->getFileName());
10468 }
10469 
10470 // get_dyld_bind_info_symbolname() is used for disassembly and passed an
10471 // address, ReferenceValue, in the Mach-O file and looks in the dyld bind
10472 // information for that address. If the address is found its binding symbol
10473 // name is returned.  If not nullptr is returned.
10474 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
10475                                                  struct DisassembleInfo *info) {
10476   if (info->bindtable == nullptr) {
10477     info->bindtable = std::make_unique<SymbolAddressMap>();
10478     Error Err = Error::success();
10479     for (const object::MachOBindEntry &Entry : info->O->bindTable(Err)) {
10480       uint64_t Address = Entry.address();
10481       StringRef name = Entry.symbolName();
10482       if (!name.empty())
10483         (*info->bindtable)[Address] = name;
10484     }
10485     if (Err)
10486       reportError(std::move(Err), info->O->getFileName());
10487   }
10488   auto name = info->bindtable->lookup(ReferenceValue);
10489   return !name.empty() ? name.data() : nullptr;
10490 }
10491 
10492 void objdump::printLazyBindTable(ObjectFile *o) {
10493   outs() << "Lazy bind table:\n";
10494   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10495     printMachOLazyBindTable(MachO);
10496   else
10497     WithColor::error()
10498         << "This operation is only currently supported "
10499            "for Mach-O executable files.\n";
10500 }
10501 
10502 void objdump::printWeakBindTable(ObjectFile *o) {
10503   outs() << "Weak bind table:\n";
10504   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10505     printMachOWeakBindTable(MachO);
10506   else
10507     WithColor::error()
10508         << "This operation is only currently supported "
10509            "for Mach-O executable files.\n";
10510 }
10511 
10512 void objdump::printExportsTrie(const ObjectFile *o) {
10513   outs() << "Exports trie:\n";
10514   if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10515     printMachOExportsTrie(MachO);
10516   else
10517     WithColor::error()
10518         << "This operation is only currently supported "
10519            "for Mach-O executable files.\n";
10520 }
10521 
10522 void objdump::printRebaseTable(ObjectFile *o) {
10523   outs() << "Rebase table:\n";
10524   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10525     printMachORebaseTable(MachO);
10526   else
10527     WithColor::error()
10528         << "This operation is only currently supported "
10529            "for Mach-O executable files.\n";
10530 }
10531 
10532 void objdump::printBindTable(ObjectFile *o) {
10533   outs() << "Bind table:\n";
10534   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10535     printMachOBindTable(MachO);
10536   else
10537     WithColor::error()
10538         << "This operation is only currently supported "
10539            "for Mach-O executable files.\n";
10540 }
10541