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   ListSeparator LS("\n");
7164   while (!Comments.empty()) {
7165     FormattedOS << LS;
7166     // Emit a line of comments.
7167     FormattedOS.PadToColumn(CommentColumn);
7168     size_t Position = Comments.find('\n');
7169     FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
7170     // Move after the newline character.
7171     Comments = Comments.substr(Position + 1);
7172   }
7173   FormattedOS.flush();
7174 
7175   // Tell the comment stream that the vector changed underneath it.
7176   CommentsToEmit.clear();
7177 }
7178 
7179 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
7180                              StringRef DisSegName, StringRef DisSectName) {
7181   const char *McpuDefault = nullptr;
7182   const Target *ThumbTarget = nullptr;
7183   const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
7184   if (!TheTarget) {
7185     // GetTarget prints out stuff.
7186     return;
7187   }
7188   std::string MachOMCPU;
7189   if (MCPU.empty() && McpuDefault)
7190     MachOMCPU = McpuDefault;
7191   else
7192     MachOMCPU = MCPU;
7193 
7194 #define CHECK_TARGET_INFO_CREATION(NAME)                                       \
7195   do {                                                                         \
7196     if (!NAME) {                                                               \
7197       WithColor::error(errs(), "llvm-objdump")                                 \
7198           << "couldn't initialize disassembler for target " << TripleName      \
7199           << '\n';                                                             \
7200       return;                                                                  \
7201     }                                                                          \
7202   } while (false)
7203 #define CHECK_THUMB_TARGET_INFO_CREATION(NAME)                                 \
7204   do {                                                                         \
7205     if (!NAME) {                                                               \
7206       WithColor::error(errs(), "llvm-objdump")                                 \
7207           << "couldn't initialize disassembler for target " << ThumbTripleName \
7208           << '\n';                                                             \
7209       return;                                                                  \
7210     }                                                                          \
7211   } while (false)
7212 
7213   std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
7214   CHECK_TARGET_INFO_CREATION(InstrInfo);
7215   std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
7216   if (ThumbTarget) {
7217     ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
7218     CHECK_THUMB_TARGET_INFO_CREATION(ThumbInstrInfo);
7219   }
7220 
7221   // Package up features to be passed to target/subtarget
7222   std::string FeaturesStr;
7223   if (!MAttrs.empty()) {
7224     SubtargetFeatures Features;
7225     for (unsigned i = 0; i != MAttrs.size(); ++i)
7226       Features.AddFeature(MAttrs[i]);
7227     FeaturesStr = Features.getString();
7228   }
7229 
7230   MCTargetOptions MCOptions;
7231   // Set up disassembler.
7232   std::unique_ptr<const MCRegisterInfo> MRI(
7233       TheTarget->createMCRegInfo(TripleName));
7234   CHECK_TARGET_INFO_CREATION(MRI);
7235   std::unique_ptr<const MCAsmInfo> AsmInfo(
7236       TheTarget->createMCAsmInfo(*MRI, TripleName, MCOptions));
7237   CHECK_TARGET_INFO_CREATION(AsmInfo);
7238   std::unique_ptr<const MCSubtargetInfo> STI(
7239       TheTarget->createMCSubtargetInfo(TripleName, MachOMCPU, FeaturesStr));
7240   CHECK_TARGET_INFO_CREATION(STI);
7241   MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
7242   std::unique_ptr<MCDisassembler> DisAsm(
7243       TheTarget->createMCDisassembler(*STI, Ctx));
7244   CHECK_TARGET_INFO_CREATION(DisAsm);
7245   std::unique_ptr<MCSymbolizer> Symbolizer;
7246   struct DisassembleInfo SymbolizerInfo(nullptr, nullptr, nullptr, false);
7247   std::unique_ptr<MCRelocationInfo> RelInfo(
7248       TheTarget->createMCRelocationInfo(TripleName, Ctx));
7249   if (RelInfo) {
7250     Symbolizer.reset(TheTarget->createMCSymbolizer(
7251         TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
7252         &SymbolizerInfo, &Ctx, std::move(RelInfo)));
7253     DisAsm->setSymbolizer(std::move(Symbolizer));
7254   }
7255   int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
7256   std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
7257       Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
7258   CHECK_TARGET_INFO_CREATION(IP);
7259   // Set the display preference for hex vs. decimal immediates.
7260   IP->setPrintImmHex(PrintImmHex);
7261   // Comment stream and backing vector.
7262   SmallString<128> CommentsToEmit;
7263   raw_svector_ostream CommentStream(CommentsToEmit);
7264   // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
7265   // if it is done then arm64 comments for string literals don't get printed
7266   // and some constant get printed instead and not setting it causes intel
7267   // (32-bit and 64-bit) comments printed with different spacing before the
7268   // comment causing different diffs with the 'C' disassembler library API.
7269   // IP->setCommentStream(CommentStream);
7270 
7271   // Set up separate thumb disassembler if needed.
7272   std::unique_ptr<const MCRegisterInfo> ThumbMRI;
7273   std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
7274   std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
7275   std::unique_ptr<MCDisassembler> ThumbDisAsm;
7276   std::unique_ptr<MCInstPrinter> ThumbIP;
7277   std::unique_ptr<MCContext> ThumbCtx;
7278   std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
7279   struct DisassembleInfo ThumbSymbolizerInfo(nullptr, nullptr, nullptr, false);
7280   std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
7281   if (ThumbTarget) {
7282     ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
7283     CHECK_THUMB_TARGET_INFO_CREATION(ThumbMRI);
7284     ThumbAsmInfo.reset(
7285         ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName, MCOptions));
7286     CHECK_THUMB_TARGET_INFO_CREATION(ThumbAsmInfo);
7287     ThumbSTI.reset(
7288         ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MachOMCPU,
7289                                            FeaturesStr));
7290     CHECK_THUMB_TARGET_INFO_CREATION(ThumbSTI);
7291     ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
7292     ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
7293     CHECK_THUMB_TARGET_INFO_CREATION(ThumbDisAsm);
7294     MCContext *PtrThumbCtx = ThumbCtx.get();
7295     ThumbRelInfo.reset(
7296         ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
7297     if (ThumbRelInfo) {
7298       ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
7299           ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
7300           &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
7301       ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
7302     }
7303     int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
7304     ThumbIP.reset(ThumbTarget->createMCInstPrinter(
7305         Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
7306         *ThumbInstrInfo, *ThumbMRI));
7307     CHECK_THUMB_TARGET_INFO_CREATION(ThumbIP);
7308     // Set the display preference for hex vs. decimal immediates.
7309     ThumbIP->setPrintImmHex(PrintImmHex);
7310   }
7311 
7312 #undef CHECK_TARGET_INFO_CREATION
7313 #undef CHECK_THUMB_TARGET_INFO_CREATION
7314 
7315   MachO::mach_header Header = MachOOF->getHeader();
7316 
7317   // FIXME: Using the -cfg command line option, this code used to be able to
7318   // annotate relocations with the referenced symbol's name, and if this was
7319   // inside a __[cf]string section, the data it points to. This is now replaced
7320   // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
7321   std::vector<SectionRef> Sections;
7322   std::vector<SymbolRef> Symbols;
7323   SmallVector<uint64_t, 8> FoundFns;
7324   uint64_t BaseSegmentAddress = 0;
7325 
7326   getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
7327                         BaseSegmentAddress);
7328 
7329   // Sort the symbols by address, just in case they didn't come in that way.
7330   llvm::sort(Symbols, SymbolSorter());
7331 
7332   // Build a data in code table that is sorted on by the address of each entry.
7333   uint64_t BaseAddress = 0;
7334   if (Header.filetype == MachO::MH_OBJECT)
7335     BaseAddress = Sections[0].getAddress();
7336   else
7337     BaseAddress = BaseSegmentAddress;
7338   DiceTable Dices;
7339   for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
7340        DI != DE; ++DI) {
7341     uint32_t Offset;
7342     DI->getOffset(Offset);
7343     Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
7344   }
7345   array_pod_sort(Dices.begin(), Dices.end());
7346 
7347   // Try to find debug info and set up the DIContext for it.
7348   std::unique_ptr<DIContext> diContext;
7349   std::unique_ptr<Binary> DSYMBinary;
7350   std::unique_ptr<MemoryBuffer> DSYMBuf;
7351   if (UseDbg) {
7352     ObjectFile *DbgObj = MachOOF;
7353 
7354     // A separate DSym file path was specified, parse it as a macho file,
7355     // get the sections and supply it to the section name parsing machinery.
7356     if (!DSYMFile.empty()) {
7357       std::string DSYMPath(DSYMFile);
7358 
7359       // If DSYMPath is a .dSYM directory, append the Mach-O file.
7360       if (llvm::sys::fs::is_directory(DSYMPath) &&
7361           llvm::sys::path::extension(DSYMPath) == ".dSYM") {
7362         SmallString<128> ShortName(llvm::sys::path::filename(DSYMPath));
7363         llvm::sys::path::replace_extension(ShortName, "");
7364         SmallString<1024> FullPath(DSYMPath);
7365         llvm::sys::path::append(FullPath, "Contents", "Resources", "DWARF",
7366                                 ShortName);
7367         DSYMPath = std::string(FullPath.str());
7368       }
7369 
7370       // Load the file.
7371       ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
7372           MemoryBuffer::getFileOrSTDIN(DSYMPath);
7373       if (std::error_code EC = BufOrErr.getError()) {
7374         reportError(errorCodeToError(EC), DSYMPath);
7375         return;
7376       }
7377 
7378       // We need to keep the file alive, because we're replacing DbgObj with it.
7379       DSYMBuf = std::move(BufOrErr.get());
7380 
7381       Expected<std::unique_ptr<Binary>> BinaryOrErr =
7382       createBinary(DSYMBuf.get()->getMemBufferRef());
7383       if (!BinaryOrErr) {
7384         reportError(BinaryOrErr.takeError(), DSYMPath);
7385         return;
7386       }
7387 
7388       // We need to keep the Binary alive with the buffer
7389       DSYMBinary = std::move(BinaryOrErr.get());
7390       if (ObjectFile *O = dyn_cast<ObjectFile>(DSYMBinary.get())) {
7391         // this is a Mach-O object file, use it
7392         if (MachOObjectFile *MachDSYM = dyn_cast<MachOObjectFile>(&*O)) {
7393           DbgObj = MachDSYM;
7394         }
7395         else {
7396           WithColor::error(errs(), "llvm-objdump")
7397             << DSYMPath << " is not a Mach-O file type.\n";
7398           return;
7399         }
7400       }
7401       else if (auto UB = dyn_cast<MachOUniversalBinary>(DSYMBinary.get())){
7402         // this is a Universal Binary, find a Mach-O for this architecture
7403         uint32_t CPUType, CPUSubType;
7404         const char *ArchFlag;
7405         if (MachOOF->is64Bit()) {
7406           const MachO::mach_header_64 H_64 = MachOOF->getHeader64();
7407           CPUType = H_64.cputype;
7408           CPUSubType = H_64.cpusubtype;
7409         } else {
7410           const MachO::mach_header H = MachOOF->getHeader();
7411           CPUType = H.cputype;
7412           CPUSubType = H.cpusubtype;
7413         }
7414         Triple T = MachOObjectFile::getArchTriple(CPUType, CPUSubType, nullptr,
7415                                                   &ArchFlag);
7416         Expected<std::unique_ptr<MachOObjectFile>> MachDSYM =
7417             UB->getMachOObjectForArch(ArchFlag);
7418         if (!MachDSYM) {
7419           reportError(MachDSYM.takeError(), DSYMPath);
7420           return;
7421         }
7422 
7423         // We need to keep the Binary alive with the buffer
7424         DbgObj = &*MachDSYM.get();
7425         DSYMBinary = std::move(*MachDSYM);
7426       }
7427       else {
7428         WithColor::error(errs(), "llvm-objdump")
7429           << DSYMPath << " is not a Mach-O or Universal file type.\n";
7430         return;
7431       }
7432     }
7433 
7434     // Setup the DIContext
7435     diContext = DWARFContext::create(*DbgObj);
7436   }
7437 
7438   if (FilterSections.empty())
7439     outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
7440 
7441   for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
7442     Expected<StringRef> SecNameOrErr = Sections[SectIdx].getName();
7443     if (!SecNameOrErr) {
7444       consumeError(SecNameOrErr.takeError());
7445       continue;
7446     }
7447     if (*SecNameOrErr != DisSectName)
7448       continue;
7449 
7450     DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
7451 
7452     StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
7453     if (SegmentName != DisSegName)
7454       continue;
7455 
7456     StringRef BytesStr =
7457         unwrapOrError(Sections[SectIdx].getContents(), Filename);
7458     ArrayRef<uint8_t> Bytes = arrayRefFromStringRef(BytesStr);
7459     uint64_t SectAddress = Sections[SectIdx].getAddress();
7460 
7461     bool symbolTableWorked = false;
7462 
7463     // Create a map of symbol addresses to symbol names for use by
7464     // the SymbolizerSymbolLookUp() routine.
7465     SymbolAddressMap AddrMap;
7466     bool DisSymNameFound = false;
7467     for (const SymbolRef &Symbol : MachOOF->symbols()) {
7468       SymbolRef::Type ST =
7469           unwrapOrError(Symbol.getType(), MachOOF->getFileName());
7470       if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
7471           ST == SymbolRef::ST_Other) {
7472         uint64_t Address = cantFail(Symbol.getValue());
7473         StringRef SymName =
7474             unwrapOrError(Symbol.getName(), MachOOF->getFileName());
7475         AddrMap[Address] = SymName;
7476         if (!DisSymName.empty() && DisSymName == SymName)
7477           DisSymNameFound = true;
7478       }
7479     }
7480     if (!DisSymName.empty() && !DisSymNameFound) {
7481       outs() << "Can't find -dis-symname: " << DisSymName << "\n";
7482       return;
7483     }
7484     // Set up the block of info used by the Symbolizer call backs.
7485     SymbolizerInfo.verbose = !NoSymbolicOperands;
7486     SymbolizerInfo.O = MachOOF;
7487     SymbolizerInfo.S = Sections[SectIdx];
7488     SymbolizerInfo.AddrMap = &AddrMap;
7489     SymbolizerInfo.Sections = &Sections;
7490     // Same for the ThumbSymbolizer
7491     ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
7492     ThumbSymbolizerInfo.O = MachOOF;
7493     ThumbSymbolizerInfo.S = Sections[SectIdx];
7494     ThumbSymbolizerInfo.AddrMap = &AddrMap;
7495     ThumbSymbolizerInfo.Sections = &Sections;
7496 
7497     unsigned int Arch = MachOOF->getArch();
7498 
7499     // Skip all symbols if this is a stubs file.
7500     if (Bytes.empty())
7501       return;
7502 
7503     // If the section has symbols but no symbol at the start of the section
7504     // these are used to make sure the bytes before the first symbol are
7505     // disassembled.
7506     bool FirstSymbol = true;
7507     bool FirstSymbolAtSectionStart = true;
7508 
7509     // Disassemble symbol by symbol.
7510     for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
7511       StringRef SymName =
7512           unwrapOrError(Symbols[SymIdx].getName(), MachOOF->getFileName());
7513       SymbolRef::Type ST =
7514           unwrapOrError(Symbols[SymIdx].getType(), MachOOF->getFileName());
7515       if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
7516         continue;
7517 
7518       // Make sure the symbol is defined in this section.
7519       bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
7520       if (!containsSym) {
7521         if (!DisSymName.empty() && DisSymName == SymName) {
7522           outs() << "-dis-symname: " << DisSymName << " not in the section\n";
7523           return;
7524         }
7525         continue;
7526       }
7527       // The __mh_execute_header is special and we need to deal with that fact
7528       // this symbol is before the start of the (__TEXT,__text) section and at the
7529       // address of the start of the __TEXT segment.  This is because this symbol
7530       // is an N_SECT symbol in the (__TEXT,__text) but its address is before the
7531       // start of the section in a standard MH_EXECUTE filetype.
7532       if (!DisSymName.empty() && DisSymName == "__mh_execute_header") {
7533         outs() << "-dis-symname: __mh_execute_header not in any section\n";
7534         return;
7535       }
7536       // When this code is trying to disassemble a symbol at a time and in the
7537       // case there is only the __mh_execute_header symbol left as in a stripped
7538       // executable, we need to deal with this by ignoring this symbol so the
7539       // whole section is disassembled and this symbol is then not displayed.
7540       if (SymName == "__mh_execute_header" || SymName == "__mh_dylib_header" ||
7541           SymName == "__mh_bundle_header" || SymName == "__mh_object_header" ||
7542           SymName == "__mh_preload_header" || SymName == "__mh_dylinker_header")
7543         continue;
7544 
7545       // If we are only disassembling one symbol see if this is that symbol.
7546       if (!DisSymName.empty() && DisSymName != SymName)
7547         continue;
7548 
7549       // Start at the address of the symbol relative to the section's address.
7550       uint64_t SectSize = Sections[SectIdx].getSize();
7551       uint64_t Start = cantFail(Symbols[SymIdx].getValue());
7552       uint64_t SectionAddress = Sections[SectIdx].getAddress();
7553       Start -= SectionAddress;
7554 
7555       if (Start > SectSize) {
7556         outs() << "section data ends, " << SymName
7557                << " lies outside valid range\n";
7558         return;
7559       }
7560 
7561       // Stop disassembling either at the beginning of the next symbol or at
7562       // the end of the section.
7563       bool containsNextSym = false;
7564       uint64_t NextSym = 0;
7565       uint64_t NextSymIdx = SymIdx + 1;
7566       while (Symbols.size() > NextSymIdx) {
7567         SymbolRef::Type NextSymType = unwrapOrError(
7568             Symbols[NextSymIdx].getType(), MachOOF->getFileName());
7569         if (NextSymType == SymbolRef::ST_Function) {
7570           containsNextSym =
7571               Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
7572           NextSym = cantFail(Symbols[NextSymIdx].getValue());
7573           NextSym -= SectionAddress;
7574           break;
7575         }
7576         ++NextSymIdx;
7577       }
7578 
7579       uint64_t End = containsNextSym ? std::min(NextSym, SectSize) : SectSize;
7580       uint64_t Size;
7581 
7582       symbolTableWorked = true;
7583 
7584       DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
7585       uint32_t SymbolFlags = cantFail(MachOOF->getSymbolFlags(Symb));
7586       bool IsThumb = SymbolFlags & SymbolRef::SF_Thumb;
7587 
7588       // We only need the dedicated Thumb target if there's a real choice
7589       // (i.e. we're not targeting M-class) and the function is Thumb.
7590       bool UseThumbTarget = IsThumb && ThumbTarget;
7591 
7592       // If we are not specifying a symbol to start disassembly with and this
7593       // is the first symbol in the section but not at the start of the section
7594       // then move the disassembly index to the start of the section and
7595       // don't print the symbol name just yet.  This is so the bytes before the
7596       // first symbol are disassembled.
7597       uint64_t SymbolStart = Start;
7598       if (DisSymName.empty() && FirstSymbol && Start != 0) {
7599         FirstSymbolAtSectionStart = false;
7600         Start = 0;
7601       }
7602       else
7603         outs() << SymName << ":\n";
7604 
7605       DILineInfo lastLine;
7606       for (uint64_t Index = Start; Index < End; Index += Size) {
7607         MCInst Inst;
7608 
7609         // If this is the first symbol in the section and it was not at the
7610         // start of the section, see if we are at its Index now and if so print
7611         // the symbol name.
7612         if (FirstSymbol && !FirstSymbolAtSectionStart && Index == SymbolStart)
7613           outs() << SymName << ":\n";
7614 
7615         uint64_t PC = SectAddress + Index;
7616         if (!NoLeadingAddr) {
7617           if (FullLeadingAddr) {
7618             if (MachOOF->is64Bit())
7619               outs() << format("%016" PRIx64, PC);
7620             else
7621               outs() << format("%08" PRIx64, PC);
7622           } else {
7623             outs() << format("%8" PRIx64 ":", PC);
7624           }
7625         }
7626         if (!NoShowRawInsn || Arch == Triple::arm)
7627           outs() << "\t";
7628 
7629         if (DumpAndSkipDataInCode(PC, Bytes.data() + Index, Dices, Size))
7630           continue;
7631 
7632         SmallVector<char, 64> AnnotationsBytes;
7633         raw_svector_ostream Annotations(AnnotationsBytes);
7634 
7635         bool gotInst;
7636         if (UseThumbTarget)
7637           gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
7638                                                 PC, Annotations);
7639         else
7640           gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
7641                                            Annotations);
7642         if (gotInst) {
7643           if (!NoShowRawInsn || Arch == Triple::arm) {
7644             dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
7645           }
7646           formatted_raw_ostream FormattedOS(outs());
7647           StringRef AnnotationsStr = Annotations.str();
7648           if (UseThumbTarget)
7649             ThumbIP->printInst(&Inst, PC, AnnotationsStr, *ThumbSTI,
7650                                FormattedOS);
7651           else
7652             IP->printInst(&Inst, PC, AnnotationsStr, *STI, FormattedOS);
7653           emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
7654 
7655           // Print debug info.
7656           if (diContext) {
7657             DILineInfo dli = diContext->getLineInfoForAddress({PC, SectIdx});
7658             // Print valid line info if it changed.
7659             if (dli != lastLine && dli.Line != 0)
7660               outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
7661                      << dli.Column;
7662             lastLine = dli;
7663           }
7664           outs() << "\n";
7665         } else {
7666           if (MachOOF->getArchTriple().isX86()) {
7667             outs() << format("\t.byte 0x%02x #bad opcode\n",
7668                              *(Bytes.data() + Index) & 0xff);
7669             Size = 1; // skip exactly one illegible byte and move on.
7670           } else if (Arch == Triple::aarch64 ||
7671                      (Arch == Triple::arm && !IsThumb)) {
7672             uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7673                               (*(Bytes.data() + Index + 1) & 0xff) << 8 |
7674                               (*(Bytes.data() + Index + 2) & 0xff) << 16 |
7675                               (*(Bytes.data() + Index + 3) & 0xff) << 24;
7676             outs() << format("\t.long\t0x%08x\n", opcode);
7677             Size = 4;
7678           } else if (Arch == Triple::arm) {
7679             assert(IsThumb && "ARM mode should have been dealt with above");
7680             uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7681                               (*(Bytes.data() + Index + 1) & 0xff) << 8;
7682             outs() << format("\t.short\t0x%04x\n", opcode);
7683             Size = 2;
7684           } else{
7685             WithColor::warning(errs(), "llvm-objdump")
7686                 << "invalid instruction encoding\n";
7687             if (Size == 0)
7688               Size = 1; // skip illegible bytes
7689           }
7690         }
7691       }
7692       // Now that we are done disassembled the first symbol set the bool that
7693       // were doing this to false.
7694       FirstSymbol = false;
7695     }
7696     if (!symbolTableWorked) {
7697       // Reading the symbol table didn't work, disassemble the whole section.
7698       uint64_t SectAddress = Sections[SectIdx].getAddress();
7699       uint64_t SectSize = Sections[SectIdx].getSize();
7700       uint64_t InstSize;
7701       for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
7702         MCInst Inst;
7703 
7704         uint64_t PC = SectAddress + Index;
7705 
7706         if (DumpAndSkipDataInCode(PC, Bytes.data() + Index, Dices, InstSize))
7707           continue;
7708 
7709         SmallVector<char, 64> AnnotationsBytes;
7710         raw_svector_ostream Annotations(AnnotationsBytes);
7711         if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
7712                                    Annotations)) {
7713           if (!NoLeadingAddr) {
7714             if (FullLeadingAddr) {
7715               if (MachOOF->is64Bit())
7716                 outs() << format("%016" PRIx64, PC);
7717               else
7718                 outs() << format("%08" PRIx64, PC);
7719             } else {
7720               outs() << format("%8" PRIx64 ":", PC);
7721             }
7722           }
7723           if (!NoShowRawInsn || Arch == Triple::arm) {
7724             outs() << "\t";
7725             dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
7726           }
7727           StringRef AnnotationsStr = Annotations.str();
7728           IP->printInst(&Inst, PC, AnnotationsStr, *STI, outs());
7729           outs() << "\n";
7730         } else {
7731           if (MachOOF->getArchTriple().isX86()) {
7732             outs() << format("\t.byte 0x%02x #bad opcode\n",
7733                              *(Bytes.data() + Index) & 0xff);
7734             InstSize = 1; // skip exactly one illegible byte and move on.
7735           } else {
7736             WithColor::warning(errs(), "llvm-objdump")
7737                 << "invalid instruction encoding\n";
7738             if (InstSize == 0)
7739               InstSize = 1; // skip illegible bytes
7740           }
7741         }
7742       }
7743     }
7744     // The TripleName's need to be reset if we are called again for a different
7745     // architecture.
7746     TripleName = "";
7747     ThumbTripleName = "";
7748 
7749     if (SymbolizerInfo.demangled_name != nullptr)
7750       free(SymbolizerInfo.demangled_name);
7751     if (ThumbSymbolizerInfo.demangled_name != nullptr)
7752       free(ThumbSymbolizerInfo.demangled_name);
7753   }
7754 }
7755 
7756 //===----------------------------------------------------------------------===//
7757 // __compact_unwind section dumping
7758 //===----------------------------------------------------------------------===//
7759 
7760 namespace {
7761 
7762 template <typename T>
7763 static uint64_t read(StringRef Contents, ptrdiff_t Offset) {
7764   using llvm::support::little;
7765   using llvm::support::unaligned;
7766 
7767   if (Offset + sizeof(T) > Contents.size()) {
7768     outs() << "warning: attempt to read past end of buffer\n";
7769     return T();
7770   }
7771 
7772   uint64_t Val =
7773       support::endian::read<T, little, unaligned>(Contents.data() + Offset);
7774   return Val;
7775 }
7776 
7777 template <typename T>
7778 static uint64_t readNext(StringRef Contents, ptrdiff_t &Offset) {
7779   T Val = read<T>(Contents, Offset);
7780   Offset += sizeof(T);
7781   return Val;
7782 }
7783 
7784 struct CompactUnwindEntry {
7785   uint32_t OffsetInSection;
7786 
7787   uint64_t FunctionAddr;
7788   uint32_t Length;
7789   uint32_t CompactEncoding;
7790   uint64_t PersonalityAddr;
7791   uint64_t LSDAAddr;
7792 
7793   RelocationRef FunctionReloc;
7794   RelocationRef PersonalityReloc;
7795   RelocationRef LSDAReloc;
7796 
7797   CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
7798       : OffsetInSection(Offset) {
7799     if (Is64)
7800       read<uint64_t>(Contents, Offset);
7801     else
7802       read<uint32_t>(Contents, Offset);
7803   }
7804 
7805 private:
7806   template <typename UIntPtr> void read(StringRef Contents, ptrdiff_t Offset) {
7807     FunctionAddr = readNext<UIntPtr>(Contents, Offset);
7808     Length = readNext<uint32_t>(Contents, Offset);
7809     CompactEncoding = readNext<uint32_t>(Contents, Offset);
7810     PersonalityAddr = readNext<UIntPtr>(Contents, Offset);
7811     LSDAAddr = readNext<UIntPtr>(Contents, Offset);
7812   }
7813 };
7814 }
7815 
7816 /// Given a relocation from __compact_unwind, consisting of the RelocationRef
7817 /// and data being relocated, determine the best base Name and Addend to use for
7818 /// display purposes.
7819 ///
7820 /// 1. An Extern relocation will directly reference a symbol (and the data is
7821 ///    then already an addend), so use that.
7822 /// 2. Otherwise the data is an offset in the object file's layout; try to find
7823 //     a symbol before it in the same section, and use the offset from there.
7824 /// 3. Finally, if all that fails, fall back to an offset from the start of the
7825 ///    referenced section.
7826 static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
7827                                       std::map<uint64_t, SymbolRef> &Symbols,
7828                                       const RelocationRef &Reloc, uint64_t Addr,
7829                                       StringRef &Name, uint64_t &Addend) {
7830   if (Reloc.getSymbol() != Obj->symbol_end()) {
7831     Name = unwrapOrError(Reloc.getSymbol()->getName(), Obj->getFileName());
7832     Addend = Addr;
7833     return;
7834   }
7835 
7836   auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
7837   SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
7838 
7839   uint64_t SectionAddr = RelocSection.getAddress();
7840 
7841   auto Sym = Symbols.upper_bound(Addr);
7842   if (Sym == Symbols.begin()) {
7843     // The first symbol in the object is after this reference, the best we can
7844     // do is section-relative notation.
7845     if (Expected<StringRef> NameOrErr = RelocSection.getName())
7846       Name = *NameOrErr;
7847     else
7848       consumeError(NameOrErr.takeError());
7849 
7850     Addend = Addr - SectionAddr;
7851     return;
7852   }
7853 
7854   // Go back one so that SymbolAddress <= Addr.
7855   --Sym;
7856 
7857   section_iterator SymSection =
7858       unwrapOrError(Sym->second.getSection(), Obj->getFileName());
7859   if (RelocSection == *SymSection) {
7860     // There's a valid symbol in the same section before this reference.
7861     Name = unwrapOrError(Sym->second.getName(), Obj->getFileName());
7862     Addend = Addr - Sym->first;
7863     return;
7864   }
7865 
7866   // There is a symbol before this reference, but it's in a different
7867   // section. Probably not helpful to mention it, so use the section name.
7868   if (Expected<StringRef> NameOrErr = RelocSection.getName())
7869     Name = *NameOrErr;
7870   else
7871     consumeError(NameOrErr.takeError());
7872 
7873   Addend = Addr - SectionAddr;
7874 }
7875 
7876 static void printUnwindRelocDest(const MachOObjectFile *Obj,
7877                                  std::map<uint64_t, SymbolRef> &Symbols,
7878                                  const RelocationRef &Reloc, uint64_t Addr) {
7879   StringRef Name;
7880   uint64_t Addend;
7881 
7882   if (!Reloc.getObject())
7883     return;
7884 
7885   findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
7886 
7887   outs() << Name;
7888   if (Addend)
7889     outs() << " + " << format("0x%" PRIx64, Addend);
7890 }
7891 
7892 static void
7893 printMachOCompactUnwindSection(const MachOObjectFile *Obj,
7894                                std::map<uint64_t, SymbolRef> &Symbols,
7895                                const SectionRef &CompactUnwind) {
7896 
7897   if (!Obj->isLittleEndian()) {
7898     outs() << "Skipping big-endian __compact_unwind section\n";
7899     return;
7900   }
7901 
7902   bool Is64 = Obj->is64Bit();
7903   uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
7904   uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
7905 
7906   StringRef Contents =
7907       unwrapOrError(CompactUnwind.getContents(), Obj->getFileName());
7908   SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
7909 
7910   // First populate the initial raw offsets, encodings and so on from the entry.
7911   for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
7912     CompactUnwindEntry Entry(Contents, Offset, Is64);
7913     CompactUnwinds.push_back(Entry);
7914   }
7915 
7916   // Next we need to look at the relocations to find out what objects are
7917   // actually being referred to.
7918   for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
7919     uint64_t RelocAddress = Reloc.getOffset();
7920 
7921     uint32_t EntryIdx = RelocAddress / EntrySize;
7922     uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
7923     CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
7924 
7925     if (OffsetInEntry == 0)
7926       Entry.FunctionReloc = Reloc;
7927     else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
7928       Entry.PersonalityReloc = Reloc;
7929     else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
7930       Entry.LSDAReloc = Reloc;
7931     else {
7932       outs() << "Invalid relocation in __compact_unwind section\n";
7933       return;
7934     }
7935   }
7936 
7937   // Finally, we're ready to print the data we've gathered.
7938   outs() << "Contents of __compact_unwind section:\n";
7939   for (auto &Entry : CompactUnwinds) {
7940     outs() << "  Entry at offset "
7941            << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
7942 
7943     // 1. Start of the region this entry applies to.
7944     outs() << "    start:                " << format("0x%" PRIx64,
7945                                                      Entry.FunctionAddr) << ' ';
7946     printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
7947     outs() << '\n';
7948 
7949     // 2. Length of the region this entry applies to.
7950     outs() << "    length:               " << format("0x%" PRIx32, Entry.Length)
7951            << '\n';
7952     // 3. The 32-bit compact encoding.
7953     outs() << "    compact encoding:     "
7954            << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
7955 
7956     // 4. The personality function, if present.
7957     if (Entry.PersonalityReloc.getObject()) {
7958       outs() << "    personality function: "
7959              << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
7960       printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
7961                            Entry.PersonalityAddr);
7962       outs() << '\n';
7963     }
7964 
7965     // 5. This entry's language-specific data area.
7966     if (Entry.LSDAReloc.getObject()) {
7967       outs() << "    LSDA:                 " << format("0x%" PRIx64,
7968                                                        Entry.LSDAAddr) << ' ';
7969       printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
7970       outs() << '\n';
7971     }
7972   }
7973 }
7974 
7975 //===----------------------------------------------------------------------===//
7976 // __unwind_info section dumping
7977 //===----------------------------------------------------------------------===//
7978 
7979 static void printRegularSecondLevelUnwindPage(StringRef PageData) {
7980   ptrdiff_t Pos = 0;
7981   uint32_t Kind = readNext<uint32_t>(PageData, Pos);
7982   (void)Kind;
7983   assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
7984 
7985   uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
7986   uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
7987 
7988   Pos = EntriesStart;
7989   for (unsigned i = 0; i < NumEntries; ++i) {
7990     uint32_t FunctionOffset = readNext<uint32_t>(PageData, Pos);
7991     uint32_t Encoding = readNext<uint32_t>(PageData, Pos);
7992 
7993     outs() << "      [" << i << "]: "
7994            << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7995            << ", "
7996            << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
7997   }
7998 }
7999 
8000 static void printCompressedSecondLevelUnwindPage(
8001     StringRef PageData, uint32_t FunctionBase,
8002     const SmallVectorImpl<uint32_t> &CommonEncodings) {
8003   ptrdiff_t Pos = 0;
8004   uint32_t Kind = readNext<uint32_t>(PageData, Pos);
8005   (void)Kind;
8006   assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
8007 
8008   uint32_t NumCommonEncodings = CommonEncodings.size();
8009   uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
8010   uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
8011 
8012   uint16_t PageEncodingsStart = readNext<uint16_t>(PageData, Pos);
8013   uint16_t NumPageEncodings = readNext<uint16_t>(PageData, Pos);
8014   SmallVector<uint32_t, 64> PageEncodings;
8015   if (NumPageEncodings) {
8016     outs() << "      Page encodings: (count = " << NumPageEncodings << ")\n";
8017     Pos = PageEncodingsStart;
8018     for (unsigned i = 0; i < NumPageEncodings; ++i) {
8019       uint32_t Encoding = readNext<uint32_t>(PageData, Pos);
8020       PageEncodings.push_back(Encoding);
8021       outs() << "        encoding[" << (i + NumCommonEncodings)
8022              << "]: " << format("0x%08" PRIx32, Encoding) << '\n';
8023     }
8024   }
8025 
8026   Pos = EntriesStart;
8027   for (unsigned i = 0; i < NumEntries; ++i) {
8028     uint32_t Entry = readNext<uint32_t>(PageData, Pos);
8029     uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
8030     uint32_t EncodingIdx = Entry >> 24;
8031 
8032     uint32_t Encoding;
8033     if (EncodingIdx < NumCommonEncodings)
8034       Encoding = CommonEncodings[EncodingIdx];
8035     else
8036       Encoding = PageEncodings[EncodingIdx - NumCommonEncodings];
8037 
8038     outs() << "      [" << i << "]: "
8039            << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
8040            << ", "
8041            << "encoding[" << EncodingIdx
8042            << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
8043   }
8044 }
8045 
8046 static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
8047                                         std::map<uint64_t, SymbolRef> &Symbols,
8048                                         const SectionRef &UnwindInfo) {
8049 
8050   if (!Obj->isLittleEndian()) {
8051     outs() << "Skipping big-endian __unwind_info section\n";
8052     return;
8053   }
8054 
8055   outs() << "Contents of __unwind_info section:\n";
8056 
8057   StringRef Contents =
8058       unwrapOrError(UnwindInfo.getContents(), Obj->getFileName());
8059   ptrdiff_t Pos = 0;
8060 
8061   //===----------------------------------
8062   // Section header
8063   //===----------------------------------
8064 
8065   uint32_t Version = readNext<uint32_t>(Contents, Pos);
8066   outs() << "  Version:                                   "
8067          << format("0x%" PRIx32, Version) << '\n';
8068   if (Version != 1) {
8069     outs() << "    Skipping section with unknown version\n";
8070     return;
8071   }
8072 
8073   uint32_t CommonEncodingsStart = readNext<uint32_t>(Contents, Pos);
8074   outs() << "  Common encodings array section offset:     "
8075          << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
8076   uint32_t NumCommonEncodings = readNext<uint32_t>(Contents, Pos);
8077   outs() << "  Number of common encodings in array:       "
8078          << format("0x%" PRIx32, NumCommonEncodings) << '\n';
8079 
8080   uint32_t PersonalitiesStart = readNext<uint32_t>(Contents, Pos);
8081   outs() << "  Personality function array section offset: "
8082          << format("0x%" PRIx32, PersonalitiesStart) << '\n';
8083   uint32_t NumPersonalities = readNext<uint32_t>(Contents, Pos);
8084   outs() << "  Number of personality functions in array:  "
8085          << format("0x%" PRIx32, NumPersonalities) << '\n';
8086 
8087   uint32_t IndicesStart = readNext<uint32_t>(Contents, Pos);
8088   outs() << "  Index array section offset:                "
8089          << format("0x%" PRIx32, IndicesStart) << '\n';
8090   uint32_t NumIndices = readNext<uint32_t>(Contents, Pos);
8091   outs() << "  Number of indices in array:                "
8092          << format("0x%" PRIx32, NumIndices) << '\n';
8093 
8094   //===----------------------------------
8095   // A shared list of common encodings
8096   //===----------------------------------
8097 
8098   // These occupy indices in the range [0, N] whenever an encoding is referenced
8099   // from a compressed 2nd level index table. In practice the linker only
8100   // creates ~128 of these, so that indices are available to embed encodings in
8101   // the 2nd level index.
8102 
8103   SmallVector<uint32_t, 64> CommonEncodings;
8104   outs() << "  Common encodings: (count = " << NumCommonEncodings << ")\n";
8105   Pos = CommonEncodingsStart;
8106   for (unsigned i = 0; i < NumCommonEncodings; ++i) {
8107     uint32_t Encoding = readNext<uint32_t>(Contents, Pos);
8108     CommonEncodings.push_back(Encoding);
8109 
8110     outs() << "    encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
8111            << '\n';
8112   }
8113 
8114   //===----------------------------------
8115   // Personality functions used in this executable
8116   //===----------------------------------
8117 
8118   // There should be only a handful of these (one per source language,
8119   // roughly). Particularly since they only get 2 bits in the compact encoding.
8120 
8121   outs() << "  Personality functions: (count = " << NumPersonalities << ")\n";
8122   Pos = PersonalitiesStart;
8123   for (unsigned i = 0; i < NumPersonalities; ++i) {
8124     uint32_t PersonalityFn = readNext<uint32_t>(Contents, Pos);
8125     outs() << "    personality[" << i + 1
8126            << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
8127   }
8128 
8129   //===----------------------------------
8130   // The level 1 index entries
8131   //===----------------------------------
8132 
8133   // These specify an approximate place to start searching for the more detailed
8134   // information, sorted by PC.
8135 
8136   struct IndexEntry {
8137     uint32_t FunctionOffset;
8138     uint32_t SecondLevelPageStart;
8139     uint32_t LSDAStart;
8140   };
8141 
8142   SmallVector<IndexEntry, 4> IndexEntries;
8143 
8144   outs() << "  Top level indices: (count = " << NumIndices << ")\n";
8145   Pos = IndicesStart;
8146   for (unsigned i = 0; i < NumIndices; ++i) {
8147     IndexEntry Entry;
8148 
8149     Entry.FunctionOffset = readNext<uint32_t>(Contents, Pos);
8150     Entry.SecondLevelPageStart = readNext<uint32_t>(Contents, Pos);
8151     Entry.LSDAStart = readNext<uint32_t>(Contents, Pos);
8152     IndexEntries.push_back(Entry);
8153 
8154     outs() << "    [" << i << "]: "
8155            << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
8156            << ", "
8157            << "2nd level page offset="
8158            << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
8159            << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
8160   }
8161 
8162   //===----------------------------------
8163   // Next come the LSDA tables
8164   //===----------------------------------
8165 
8166   // The LSDA layout is rather implicit: it's a contiguous array of entries from
8167   // the first top-level index's LSDAOffset to the last (sentinel).
8168 
8169   outs() << "  LSDA descriptors:\n";
8170   Pos = IndexEntries[0].LSDAStart;
8171   const uint32_t LSDASize = 2 * sizeof(uint32_t);
8172   int NumLSDAs =
8173       (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) / LSDASize;
8174 
8175   for (int i = 0; i < NumLSDAs; ++i) {
8176     uint32_t FunctionOffset = readNext<uint32_t>(Contents, Pos);
8177     uint32_t LSDAOffset = readNext<uint32_t>(Contents, Pos);
8178     outs() << "    [" << i << "]: "
8179            << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
8180            << ", "
8181            << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
8182   }
8183 
8184   //===----------------------------------
8185   // Finally, the 2nd level indices
8186   //===----------------------------------
8187 
8188   // Generally these are 4K in size, and have 2 possible forms:
8189   //   + Regular stores up to 511 entries with disparate encodings
8190   //   + Compressed stores up to 1021 entries if few enough compact encoding
8191   //     values are used.
8192   outs() << "  Second level indices:\n";
8193   for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
8194     // The final sentinel top-level index has no associated 2nd level page
8195     if (IndexEntries[i].SecondLevelPageStart == 0)
8196       break;
8197 
8198     outs() << "    Second level index[" << i << "]: "
8199            << "offset in section="
8200            << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
8201            << ", "
8202            << "base function offset="
8203            << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
8204 
8205     Pos = IndexEntries[i].SecondLevelPageStart;
8206     if (Pos + sizeof(uint32_t) > Contents.size()) {
8207       outs() << "warning: invalid offset for second level page: " << Pos << '\n';
8208       continue;
8209     }
8210 
8211     uint32_t Kind =
8212         *reinterpret_cast<const support::ulittle32_t *>(Contents.data() + Pos);
8213     if (Kind == 2)
8214       printRegularSecondLevelUnwindPage(Contents.substr(Pos, 4096));
8215     else if (Kind == 3)
8216       printCompressedSecondLevelUnwindPage(Contents.substr(Pos, 4096),
8217                                            IndexEntries[i].FunctionOffset,
8218                                            CommonEncodings);
8219     else
8220       outs() << "    Skipping 2nd level page with unknown kind " << Kind
8221              << '\n';
8222   }
8223 }
8224 
8225 void objdump::printMachOUnwindInfo(const MachOObjectFile *Obj) {
8226   std::map<uint64_t, SymbolRef> Symbols;
8227   for (const SymbolRef &SymRef : Obj->symbols()) {
8228     // Discard any undefined or absolute symbols. They're not going to take part
8229     // in the convenience lookup for unwind info and just take up resources.
8230     auto SectOrErr = SymRef.getSection();
8231     if (!SectOrErr) {
8232       // TODO: Actually report errors helpfully.
8233       consumeError(SectOrErr.takeError());
8234       continue;
8235     }
8236     section_iterator Section = *SectOrErr;
8237     if (Section == Obj->section_end())
8238       continue;
8239 
8240     uint64_t Addr = cantFail(SymRef.getValue());
8241     Symbols.insert(std::make_pair(Addr, SymRef));
8242   }
8243 
8244   for (const SectionRef &Section : Obj->sections()) {
8245     StringRef SectName;
8246     if (Expected<StringRef> NameOrErr = Section.getName())
8247       SectName = *NameOrErr;
8248     else
8249       consumeError(NameOrErr.takeError());
8250 
8251     if (SectName == "__compact_unwind")
8252       printMachOCompactUnwindSection(Obj, Symbols, Section);
8253     else if (SectName == "__unwind_info")
8254       printMachOUnwindInfoSection(Obj, Symbols, Section);
8255   }
8256 }
8257 
8258 static void PrintMachHeader(uint32_t magic, uint32_t cputype,
8259                             uint32_t cpusubtype, uint32_t filetype,
8260                             uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
8261                             bool verbose) {
8262   outs() << "Mach header\n";
8263   outs() << "      magic cputype cpusubtype  caps    filetype ncmds "
8264             "sizeofcmds      flags\n";
8265   if (verbose) {
8266     if (magic == MachO::MH_MAGIC)
8267       outs() << "   MH_MAGIC";
8268     else if (magic == MachO::MH_MAGIC_64)
8269       outs() << "MH_MAGIC_64";
8270     else
8271       outs() << format(" 0x%08" PRIx32, magic);
8272     switch (cputype) {
8273     case MachO::CPU_TYPE_I386:
8274       outs() << "    I386";
8275       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8276       case MachO::CPU_SUBTYPE_I386_ALL:
8277         outs() << "        ALL";
8278         break;
8279       default:
8280         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8281         break;
8282       }
8283       break;
8284     case MachO::CPU_TYPE_X86_64:
8285       outs() << "  X86_64";
8286       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8287       case MachO::CPU_SUBTYPE_X86_64_ALL:
8288         outs() << "        ALL";
8289         break;
8290       case MachO::CPU_SUBTYPE_X86_64_H:
8291         outs() << "    Haswell";
8292         break;
8293       default:
8294         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8295         break;
8296       }
8297       break;
8298     case MachO::CPU_TYPE_ARM:
8299       outs() << "     ARM";
8300       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8301       case MachO::CPU_SUBTYPE_ARM_ALL:
8302         outs() << "        ALL";
8303         break;
8304       case MachO::CPU_SUBTYPE_ARM_V4T:
8305         outs() << "        V4T";
8306         break;
8307       case MachO::CPU_SUBTYPE_ARM_V5TEJ:
8308         outs() << "      V5TEJ";
8309         break;
8310       case MachO::CPU_SUBTYPE_ARM_XSCALE:
8311         outs() << "     XSCALE";
8312         break;
8313       case MachO::CPU_SUBTYPE_ARM_V6:
8314         outs() << "         V6";
8315         break;
8316       case MachO::CPU_SUBTYPE_ARM_V6M:
8317         outs() << "        V6M";
8318         break;
8319       case MachO::CPU_SUBTYPE_ARM_V7:
8320         outs() << "         V7";
8321         break;
8322       case MachO::CPU_SUBTYPE_ARM_V7EM:
8323         outs() << "       V7EM";
8324         break;
8325       case MachO::CPU_SUBTYPE_ARM_V7K:
8326         outs() << "        V7K";
8327         break;
8328       case MachO::CPU_SUBTYPE_ARM_V7M:
8329         outs() << "        V7M";
8330         break;
8331       case MachO::CPU_SUBTYPE_ARM_V7S:
8332         outs() << "        V7S";
8333         break;
8334       default:
8335         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8336         break;
8337       }
8338       break;
8339     case MachO::CPU_TYPE_ARM64:
8340       outs() << "   ARM64";
8341       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8342       case MachO::CPU_SUBTYPE_ARM64_ALL:
8343         outs() << "        ALL";
8344         break;
8345       case MachO::CPU_SUBTYPE_ARM64_V8:
8346         outs() << "         V8";
8347         break;
8348       case MachO::CPU_SUBTYPE_ARM64E:
8349         outs() << "          E";
8350         break;
8351       default:
8352         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8353         break;
8354       }
8355       break;
8356     case MachO::CPU_TYPE_ARM64_32:
8357       outs() << " ARM64_32";
8358       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8359       case MachO::CPU_SUBTYPE_ARM64_32_V8:
8360         outs() << "        V8";
8361         break;
8362       default:
8363         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8364         break;
8365       }
8366       break;
8367     case MachO::CPU_TYPE_POWERPC:
8368       outs() << "     PPC";
8369       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8370       case MachO::CPU_SUBTYPE_POWERPC_ALL:
8371         outs() << "        ALL";
8372         break;
8373       default:
8374         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8375         break;
8376       }
8377       break;
8378     case MachO::CPU_TYPE_POWERPC64:
8379       outs() << "   PPC64";
8380       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8381       case MachO::CPU_SUBTYPE_POWERPC_ALL:
8382         outs() << "        ALL";
8383         break;
8384       default:
8385         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8386         break;
8387       }
8388       break;
8389     default:
8390       outs() << format(" %7d", cputype);
8391       outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8392       break;
8393     }
8394     if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
8395       outs() << " LIB64";
8396     } else {
8397       outs() << format("  0x%02" PRIx32,
8398                        (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
8399     }
8400     switch (filetype) {
8401     case MachO::MH_OBJECT:
8402       outs() << "      OBJECT";
8403       break;
8404     case MachO::MH_EXECUTE:
8405       outs() << "     EXECUTE";
8406       break;
8407     case MachO::MH_FVMLIB:
8408       outs() << "      FVMLIB";
8409       break;
8410     case MachO::MH_CORE:
8411       outs() << "        CORE";
8412       break;
8413     case MachO::MH_PRELOAD:
8414       outs() << "     PRELOAD";
8415       break;
8416     case MachO::MH_DYLIB:
8417       outs() << "       DYLIB";
8418       break;
8419     case MachO::MH_DYLIB_STUB:
8420       outs() << "  DYLIB_STUB";
8421       break;
8422     case MachO::MH_DYLINKER:
8423       outs() << "    DYLINKER";
8424       break;
8425     case MachO::MH_BUNDLE:
8426       outs() << "      BUNDLE";
8427       break;
8428     case MachO::MH_DSYM:
8429       outs() << "        DSYM";
8430       break;
8431     case MachO::MH_KEXT_BUNDLE:
8432       outs() << "  KEXTBUNDLE";
8433       break;
8434     default:
8435       outs() << format("  %10u", filetype);
8436       break;
8437     }
8438     outs() << format(" %5u", ncmds);
8439     outs() << format(" %10u", sizeofcmds);
8440     uint32_t f = flags;
8441     if (f & MachO::MH_NOUNDEFS) {
8442       outs() << "   NOUNDEFS";
8443       f &= ~MachO::MH_NOUNDEFS;
8444     }
8445     if (f & MachO::MH_INCRLINK) {
8446       outs() << " INCRLINK";
8447       f &= ~MachO::MH_INCRLINK;
8448     }
8449     if (f & MachO::MH_DYLDLINK) {
8450       outs() << " DYLDLINK";
8451       f &= ~MachO::MH_DYLDLINK;
8452     }
8453     if (f & MachO::MH_BINDATLOAD) {
8454       outs() << " BINDATLOAD";
8455       f &= ~MachO::MH_BINDATLOAD;
8456     }
8457     if (f & MachO::MH_PREBOUND) {
8458       outs() << " PREBOUND";
8459       f &= ~MachO::MH_PREBOUND;
8460     }
8461     if (f & MachO::MH_SPLIT_SEGS) {
8462       outs() << " SPLIT_SEGS";
8463       f &= ~MachO::MH_SPLIT_SEGS;
8464     }
8465     if (f & MachO::MH_LAZY_INIT) {
8466       outs() << " LAZY_INIT";
8467       f &= ~MachO::MH_LAZY_INIT;
8468     }
8469     if (f & MachO::MH_TWOLEVEL) {
8470       outs() << " TWOLEVEL";
8471       f &= ~MachO::MH_TWOLEVEL;
8472     }
8473     if (f & MachO::MH_FORCE_FLAT) {
8474       outs() << " FORCE_FLAT";
8475       f &= ~MachO::MH_FORCE_FLAT;
8476     }
8477     if (f & MachO::MH_NOMULTIDEFS) {
8478       outs() << " NOMULTIDEFS";
8479       f &= ~MachO::MH_NOMULTIDEFS;
8480     }
8481     if (f & MachO::MH_NOFIXPREBINDING) {
8482       outs() << " NOFIXPREBINDING";
8483       f &= ~MachO::MH_NOFIXPREBINDING;
8484     }
8485     if (f & MachO::MH_PREBINDABLE) {
8486       outs() << " PREBINDABLE";
8487       f &= ~MachO::MH_PREBINDABLE;
8488     }
8489     if (f & MachO::MH_ALLMODSBOUND) {
8490       outs() << " ALLMODSBOUND";
8491       f &= ~MachO::MH_ALLMODSBOUND;
8492     }
8493     if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
8494       outs() << " SUBSECTIONS_VIA_SYMBOLS";
8495       f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
8496     }
8497     if (f & MachO::MH_CANONICAL) {
8498       outs() << " CANONICAL";
8499       f &= ~MachO::MH_CANONICAL;
8500     }
8501     if (f & MachO::MH_WEAK_DEFINES) {
8502       outs() << " WEAK_DEFINES";
8503       f &= ~MachO::MH_WEAK_DEFINES;
8504     }
8505     if (f & MachO::MH_BINDS_TO_WEAK) {
8506       outs() << " BINDS_TO_WEAK";
8507       f &= ~MachO::MH_BINDS_TO_WEAK;
8508     }
8509     if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
8510       outs() << " ALLOW_STACK_EXECUTION";
8511       f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
8512     }
8513     if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
8514       outs() << " DEAD_STRIPPABLE_DYLIB";
8515       f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
8516     }
8517     if (f & MachO::MH_PIE) {
8518       outs() << " PIE";
8519       f &= ~MachO::MH_PIE;
8520     }
8521     if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
8522       outs() << " NO_REEXPORTED_DYLIBS";
8523       f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
8524     }
8525     if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
8526       outs() << " MH_HAS_TLV_DESCRIPTORS";
8527       f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
8528     }
8529     if (f & MachO::MH_NO_HEAP_EXECUTION) {
8530       outs() << " MH_NO_HEAP_EXECUTION";
8531       f &= ~MachO::MH_NO_HEAP_EXECUTION;
8532     }
8533     if (f & MachO::MH_APP_EXTENSION_SAFE) {
8534       outs() << " APP_EXTENSION_SAFE";
8535       f &= ~MachO::MH_APP_EXTENSION_SAFE;
8536     }
8537     if (f & MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO) {
8538       outs() << " NLIST_OUTOFSYNC_WITH_DYLDINFO";
8539       f &= ~MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO;
8540     }
8541     if (f != 0 || flags == 0)
8542       outs() << format(" 0x%08" PRIx32, f);
8543   } else {
8544     outs() << format(" 0x%08" PRIx32, magic);
8545     outs() << format(" %7d", cputype);
8546     outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8547     outs() << format("  0x%02" PRIx32,
8548                      (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
8549     outs() << format("  %10u", filetype);
8550     outs() << format(" %5u", ncmds);
8551     outs() << format(" %10u", sizeofcmds);
8552     outs() << format(" 0x%08" PRIx32, flags);
8553   }
8554   outs() << "\n";
8555 }
8556 
8557 static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
8558                                 StringRef SegName, uint64_t vmaddr,
8559                                 uint64_t vmsize, uint64_t fileoff,
8560                                 uint64_t filesize, uint32_t maxprot,
8561                                 uint32_t initprot, uint32_t nsects,
8562                                 uint32_t flags, uint32_t object_size,
8563                                 bool verbose) {
8564   uint64_t expected_cmdsize;
8565   if (cmd == MachO::LC_SEGMENT) {
8566     outs() << "      cmd LC_SEGMENT\n";
8567     expected_cmdsize = nsects;
8568     expected_cmdsize *= sizeof(struct MachO::section);
8569     expected_cmdsize += sizeof(struct MachO::segment_command);
8570   } else {
8571     outs() << "      cmd LC_SEGMENT_64\n";
8572     expected_cmdsize = nsects;
8573     expected_cmdsize *= sizeof(struct MachO::section_64);
8574     expected_cmdsize += sizeof(struct MachO::segment_command_64);
8575   }
8576   outs() << "  cmdsize " << cmdsize;
8577   if (cmdsize != expected_cmdsize)
8578     outs() << " Inconsistent size\n";
8579   else
8580     outs() << "\n";
8581   outs() << "  segname " << SegName << "\n";
8582   if (cmd == MachO::LC_SEGMENT_64) {
8583     outs() << "   vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
8584     outs() << "   vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
8585   } else {
8586     outs() << "   vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
8587     outs() << "   vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
8588   }
8589   outs() << "  fileoff " << fileoff;
8590   if (fileoff > object_size)
8591     outs() << " (past end of file)\n";
8592   else
8593     outs() << "\n";
8594   outs() << " filesize " << filesize;
8595   if (fileoff + filesize > object_size)
8596     outs() << " (past end of file)\n";
8597   else
8598     outs() << "\n";
8599   if (verbose) {
8600     if ((maxprot &
8601          ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8602            MachO::VM_PROT_EXECUTE)) != 0)
8603       outs() << "  maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
8604     else {
8605       outs() << "  maxprot ";
8606       outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
8607       outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8608       outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
8609     }
8610     if ((initprot &
8611          ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8612            MachO::VM_PROT_EXECUTE)) != 0)
8613       outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
8614     else {
8615       outs() << " initprot ";
8616       outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
8617       outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8618       outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
8619     }
8620   } else {
8621     outs() << "  maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
8622     outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
8623   }
8624   outs() << "   nsects " << nsects << "\n";
8625   if (verbose) {
8626     outs() << "    flags";
8627     if (flags == 0)
8628       outs() << " (none)\n";
8629     else {
8630       if (flags & MachO::SG_HIGHVM) {
8631         outs() << " HIGHVM";
8632         flags &= ~MachO::SG_HIGHVM;
8633       }
8634       if (flags & MachO::SG_FVMLIB) {
8635         outs() << " FVMLIB";
8636         flags &= ~MachO::SG_FVMLIB;
8637       }
8638       if (flags & MachO::SG_NORELOC) {
8639         outs() << " NORELOC";
8640         flags &= ~MachO::SG_NORELOC;
8641       }
8642       if (flags & MachO::SG_PROTECTED_VERSION_1) {
8643         outs() << " PROTECTED_VERSION_1";
8644         flags &= ~MachO::SG_PROTECTED_VERSION_1;
8645       }
8646       if (flags)
8647         outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
8648       else
8649         outs() << "\n";
8650     }
8651   } else {
8652     outs() << "    flags " << format("0x%" PRIx32, flags) << "\n";
8653   }
8654 }
8655 
8656 static void PrintSection(const char *sectname, const char *segname,
8657                          uint64_t addr, uint64_t size, uint32_t offset,
8658                          uint32_t align, uint32_t reloff, uint32_t nreloc,
8659                          uint32_t flags, uint32_t reserved1, uint32_t reserved2,
8660                          uint32_t cmd, const char *sg_segname,
8661                          uint32_t filetype, uint32_t object_size,
8662                          bool verbose) {
8663   outs() << "Section\n";
8664   outs() << "  sectname " << format("%.16s\n", sectname);
8665   outs() << "   segname " << format("%.16s", segname);
8666   if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
8667     outs() << " (does not match segment)\n";
8668   else
8669     outs() << "\n";
8670   if (cmd == MachO::LC_SEGMENT_64) {
8671     outs() << "      addr " << format("0x%016" PRIx64, addr) << "\n";
8672     outs() << "      size " << format("0x%016" PRIx64, size);
8673   } else {
8674     outs() << "      addr " << format("0x%08" PRIx64, addr) << "\n";
8675     outs() << "      size " << format("0x%08" PRIx64, size);
8676   }
8677   if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
8678     outs() << " (past end of file)\n";
8679   else
8680     outs() << "\n";
8681   outs() << "    offset " << offset;
8682   if (offset > object_size)
8683     outs() << " (past end of file)\n";
8684   else
8685     outs() << "\n";
8686   uint32_t align_shifted = 1 << align;
8687   outs() << "     align 2^" << align << " (" << align_shifted << ")\n";
8688   outs() << "    reloff " << reloff;
8689   if (reloff > object_size)
8690     outs() << " (past end of file)\n";
8691   else
8692     outs() << "\n";
8693   outs() << "    nreloc " << nreloc;
8694   if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
8695     outs() << " (past end of file)\n";
8696   else
8697     outs() << "\n";
8698   uint32_t section_type = flags & MachO::SECTION_TYPE;
8699   if (verbose) {
8700     outs() << "      type";
8701     if (section_type == MachO::S_REGULAR)
8702       outs() << " S_REGULAR\n";
8703     else if (section_type == MachO::S_ZEROFILL)
8704       outs() << " S_ZEROFILL\n";
8705     else if (section_type == MachO::S_CSTRING_LITERALS)
8706       outs() << " S_CSTRING_LITERALS\n";
8707     else if (section_type == MachO::S_4BYTE_LITERALS)
8708       outs() << " S_4BYTE_LITERALS\n";
8709     else if (section_type == MachO::S_8BYTE_LITERALS)
8710       outs() << " S_8BYTE_LITERALS\n";
8711     else if (section_type == MachO::S_16BYTE_LITERALS)
8712       outs() << " S_16BYTE_LITERALS\n";
8713     else if (section_type == MachO::S_LITERAL_POINTERS)
8714       outs() << " S_LITERAL_POINTERS\n";
8715     else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
8716       outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
8717     else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
8718       outs() << " S_LAZY_SYMBOL_POINTERS\n";
8719     else if (section_type == MachO::S_SYMBOL_STUBS)
8720       outs() << " S_SYMBOL_STUBS\n";
8721     else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
8722       outs() << " S_MOD_INIT_FUNC_POINTERS\n";
8723     else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
8724       outs() << " S_MOD_TERM_FUNC_POINTERS\n";
8725     else if (section_type == MachO::S_COALESCED)
8726       outs() << " S_COALESCED\n";
8727     else if (section_type == MachO::S_INTERPOSING)
8728       outs() << " S_INTERPOSING\n";
8729     else if (section_type == MachO::S_DTRACE_DOF)
8730       outs() << " S_DTRACE_DOF\n";
8731     else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
8732       outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
8733     else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
8734       outs() << " S_THREAD_LOCAL_REGULAR\n";
8735     else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
8736       outs() << " S_THREAD_LOCAL_ZEROFILL\n";
8737     else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
8738       outs() << " S_THREAD_LOCAL_VARIABLES\n";
8739     else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8740       outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
8741     else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
8742       outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
8743     else
8744       outs() << format("0x%08" PRIx32, section_type) << "\n";
8745     outs() << "attributes";
8746     uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
8747     if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
8748       outs() << " PURE_INSTRUCTIONS";
8749     if (section_attributes & MachO::S_ATTR_NO_TOC)
8750       outs() << " NO_TOC";
8751     if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
8752       outs() << " STRIP_STATIC_SYMS";
8753     if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
8754       outs() << " NO_DEAD_STRIP";
8755     if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
8756       outs() << " LIVE_SUPPORT";
8757     if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
8758       outs() << " SELF_MODIFYING_CODE";
8759     if (section_attributes & MachO::S_ATTR_DEBUG)
8760       outs() << " DEBUG";
8761     if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
8762       outs() << " SOME_INSTRUCTIONS";
8763     if (section_attributes & MachO::S_ATTR_EXT_RELOC)
8764       outs() << " EXT_RELOC";
8765     if (section_attributes & MachO::S_ATTR_LOC_RELOC)
8766       outs() << " LOC_RELOC";
8767     if (section_attributes == 0)
8768       outs() << " (none)";
8769     outs() << "\n";
8770   } else
8771     outs() << "     flags " << format("0x%08" PRIx32, flags) << "\n";
8772   outs() << " reserved1 " << reserved1;
8773   if (section_type == MachO::S_SYMBOL_STUBS ||
8774       section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
8775       section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
8776       section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
8777       section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8778     outs() << " (index into indirect symbol table)\n";
8779   else
8780     outs() << "\n";
8781   outs() << " reserved2 " << reserved2;
8782   if (section_type == MachO::S_SYMBOL_STUBS)
8783     outs() << " (size of stubs)\n";
8784   else
8785     outs() << "\n";
8786 }
8787 
8788 static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
8789                                    uint32_t object_size) {
8790   outs() << "     cmd LC_SYMTAB\n";
8791   outs() << " cmdsize " << st.cmdsize;
8792   if (st.cmdsize != sizeof(struct MachO::symtab_command))
8793     outs() << " Incorrect size\n";
8794   else
8795     outs() << "\n";
8796   outs() << "  symoff " << st.symoff;
8797   if (st.symoff > object_size)
8798     outs() << " (past end of file)\n";
8799   else
8800     outs() << "\n";
8801   outs() << "   nsyms " << st.nsyms;
8802   uint64_t big_size;
8803   if (Is64Bit) {
8804     big_size = st.nsyms;
8805     big_size *= sizeof(struct MachO::nlist_64);
8806     big_size += st.symoff;
8807     if (big_size > object_size)
8808       outs() << " (past end of file)\n";
8809     else
8810       outs() << "\n";
8811   } else {
8812     big_size = st.nsyms;
8813     big_size *= sizeof(struct MachO::nlist);
8814     big_size += st.symoff;
8815     if (big_size > object_size)
8816       outs() << " (past end of file)\n";
8817     else
8818       outs() << "\n";
8819   }
8820   outs() << "  stroff " << st.stroff;
8821   if (st.stroff > object_size)
8822     outs() << " (past end of file)\n";
8823   else
8824     outs() << "\n";
8825   outs() << " strsize " << st.strsize;
8826   big_size = st.stroff;
8827   big_size += st.strsize;
8828   if (big_size > object_size)
8829     outs() << " (past end of file)\n";
8830   else
8831     outs() << "\n";
8832 }
8833 
8834 static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
8835                                      uint32_t nsyms, uint32_t object_size,
8836                                      bool Is64Bit) {
8837   outs() << "            cmd LC_DYSYMTAB\n";
8838   outs() << "        cmdsize " << dyst.cmdsize;
8839   if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
8840     outs() << " Incorrect size\n";
8841   else
8842     outs() << "\n";
8843   outs() << "      ilocalsym " << dyst.ilocalsym;
8844   if (dyst.ilocalsym > nsyms)
8845     outs() << " (greater than the number of symbols)\n";
8846   else
8847     outs() << "\n";
8848   outs() << "      nlocalsym " << dyst.nlocalsym;
8849   uint64_t big_size;
8850   big_size = dyst.ilocalsym;
8851   big_size += dyst.nlocalsym;
8852   if (big_size > nsyms)
8853     outs() << " (past the end of the symbol table)\n";
8854   else
8855     outs() << "\n";
8856   outs() << "     iextdefsym " << dyst.iextdefsym;
8857   if (dyst.iextdefsym > nsyms)
8858     outs() << " (greater than the number of symbols)\n";
8859   else
8860     outs() << "\n";
8861   outs() << "     nextdefsym " << dyst.nextdefsym;
8862   big_size = dyst.iextdefsym;
8863   big_size += dyst.nextdefsym;
8864   if (big_size > nsyms)
8865     outs() << " (past the end of the symbol table)\n";
8866   else
8867     outs() << "\n";
8868   outs() << "      iundefsym " << dyst.iundefsym;
8869   if (dyst.iundefsym > nsyms)
8870     outs() << " (greater than the number of symbols)\n";
8871   else
8872     outs() << "\n";
8873   outs() << "      nundefsym " << dyst.nundefsym;
8874   big_size = dyst.iundefsym;
8875   big_size += dyst.nundefsym;
8876   if (big_size > nsyms)
8877     outs() << " (past the end of the symbol table)\n";
8878   else
8879     outs() << "\n";
8880   outs() << "         tocoff " << dyst.tocoff;
8881   if (dyst.tocoff > object_size)
8882     outs() << " (past end of file)\n";
8883   else
8884     outs() << "\n";
8885   outs() << "           ntoc " << dyst.ntoc;
8886   big_size = dyst.ntoc;
8887   big_size *= sizeof(struct MachO::dylib_table_of_contents);
8888   big_size += dyst.tocoff;
8889   if (big_size > object_size)
8890     outs() << " (past end of file)\n";
8891   else
8892     outs() << "\n";
8893   outs() << "      modtaboff " << dyst.modtaboff;
8894   if (dyst.modtaboff > object_size)
8895     outs() << " (past end of file)\n";
8896   else
8897     outs() << "\n";
8898   outs() << "        nmodtab " << dyst.nmodtab;
8899   uint64_t modtabend;
8900   if (Is64Bit) {
8901     modtabend = dyst.nmodtab;
8902     modtabend *= sizeof(struct MachO::dylib_module_64);
8903     modtabend += dyst.modtaboff;
8904   } else {
8905     modtabend = dyst.nmodtab;
8906     modtabend *= sizeof(struct MachO::dylib_module);
8907     modtabend += dyst.modtaboff;
8908   }
8909   if (modtabend > object_size)
8910     outs() << " (past end of file)\n";
8911   else
8912     outs() << "\n";
8913   outs() << "   extrefsymoff " << dyst.extrefsymoff;
8914   if (dyst.extrefsymoff > object_size)
8915     outs() << " (past end of file)\n";
8916   else
8917     outs() << "\n";
8918   outs() << "    nextrefsyms " << dyst.nextrefsyms;
8919   big_size = dyst.nextrefsyms;
8920   big_size *= sizeof(struct MachO::dylib_reference);
8921   big_size += dyst.extrefsymoff;
8922   if (big_size > object_size)
8923     outs() << " (past end of file)\n";
8924   else
8925     outs() << "\n";
8926   outs() << " indirectsymoff " << dyst.indirectsymoff;
8927   if (dyst.indirectsymoff > object_size)
8928     outs() << " (past end of file)\n";
8929   else
8930     outs() << "\n";
8931   outs() << "  nindirectsyms " << dyst.nindirectsyms;
8932   big_size = dyst.nindirectsyms;
8933   big_size *= sizeof(uint32_t);
8934   big_size += dyst.indirectsymoff;
8935   if (big_size > object_size)
8936     outs() << " (past end of file)\n";
8937   else
8938     outs() << "\n";
8939   outs() << "      extreloff " << dyst.extreloff;
8940   if (dyst.extreloff > object_size)
8941     outs() << " (past end of file)\n";
8942   else
8943     outs() << "\n";
8944   outs() << "        nextrel " << dyst.nextrel;
8945   big_size = dyst.nextrel;
8946   big_size *= sizeof(struct MachO::relocation_info);
8947   big_size += dyst.extreloff;
8948   if (big_size > object_size)
8949     outs() << " (past end of file)\n";
8950   else
8951     outs() << "\n";
8952   outs() << "      locreloff " << dyst.locreloff;
8953   if (dyst.locreloff > object_size)
8954     outs() << " (past end of file)\n";
8955   else
8956     outs() << "\n";
8957   outs() << "        nlocrel " << dyst.nlocrel;
8958   big_size = dyst.nlocrel;
8959   big_size *= sizeof(struct MachO::relocation_info);
8960   big_size += dyst.locreloff;
8961   if (big_size > object_size)
8962     outs() << " (past end of file)\n";
8963   else
8964     outs() << "\n";
8965 }
8966 
8967 static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
8968                                      uint32_t object_size) {
8969   if (dc.cmd == MachO::LC_DYLD_INFO)
8970     outs() << "            cmd LC_DYLD_INFO\n";
8971   else
8972     outs() << "            cmd LC_DYLD_INFO_ONLY\n";
8973   outs() << "        cmdsize " << dc.cmdsize;
8974   if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
8975     outs() << " Incorrect size\n";
8976   else
8977     outs() << "\n";
8978   outs() << "     rebase_off " << dc.rebase_off;
8979   if (dc.rebase_off > object_size)
8980     outs() << " (past end of file)\n";
8981   else
8982     outs() << "\n";
8983   outs() << "    rebase_size " << dc.rebase_size;
8984   uint64_t big_size;
8985   big_size = dc.rebase_off;
8986   big_size += dc.rebase_size;
8987   if (big_size > object_size)
8988     outs() << " (past end of file)\n";
8989   else
8990     outs() << "\n";
8991   outs() << "       bind_off " << dc.bind_off;
8992   if (dc.bind_off > object_size)
8993     outs() << " (past end of file)\n";
8994   else
8995     outs() << "\n";
8996   outs() << "      bind_size " << dc.bind_size;
8997   big_size = dc.bind_off;
8998   big_size += dc.bind_size;
8999   if (big_size > object_size)
9000     outs() << " (past end of file)\n";
9001   else
9002     outs() << "\n";
9003   outs() << "  weak_bind_off " << dc.weak_bind_off;
9004   if (dc.weak_bind_off > object_size)
9005     outs() << " (past end of file)\n";
9006   else
9007     outs() << "\n";
9008   outs() << " weak_bind_size " << dc.weak_bind_size;
9009   big_size = dc.weak_bind_off;
9010   big_size += dc.weak_bind_size;
9011   if (big_size > object_size)
9012     outs() << " (past end of file)\n";
9013   else
9014     outs() << "\n";
9015   outs() << "  lazy_bind_off " << dc.lazy_bind_off;
9016   if (dc.lazy_bind_off > object_size)
9017     outs() << " (past end of file)\n";
9018   else
9019     outs() << "\n";
9020   outs() << " lazy_bind_size " << dc.lazy_bind_size;
9021   big_size = dc.lazy_bind_off;
9022   big_size += dc.lazy_bind_size;
9023   if (big_size > object_size)
9024     outs() << " (past end of file)\n";
9025   else
9026     outs() << "\n";
9027   outs() << "     export_off " << dc.export_off;
9028   if (dc.export_off > object_size)
9029     outs() << " (past end of file)\n";
9030   else
9031     outs() << "\n";
9032   outs() << "    export_size " << dc.export_size;
9033   big_size = dc.export_off;
9034   big_size += dc.export_size;
9035   if (big_size > object_size)
9036     outs() << " (past end of file)\n";
9037   else
9038     outs() << "\n";
9039 }
9040 
9041 static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
9042                                  const char *Ptr) {
9043   if (dyld.cmd == MachO::LC_ID_DYLINKER)
9044     outs() << "          cmd LC_ID_DYLINKER\n";
9045   else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
9046     outs() << "          cmd LC_LOAD_DYLINKER\n";
9047   else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
9048     outs() << "          cmd LC_DYLD_ENVIRONMENT\n";
9049   else
9050     outs() << "          cmd ?(" << dyld.cmd << ")\n";
9051   outs() << "      cmdsize " << dyld.cmdsize;
9052   if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
9053     outs() << " Incorrect size\n";
9054   else
9055     outs() << "\n";
9056   if (dyld.name >= dyld.cmdsize)
9057     outs() << "         name ?(bad offset " << dyld.name << ")\n";
9058   else {
9059     const char *P = (const char *)(Ptr) + dyld.name;
9060     outs() << "         name " << P << " (offset " << dyld.name << ")\n";
9061   }
9062 }
9063 
9064 static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
9065   outs() << "     cmd LC_UUID\n";
9066   outs() << " cmdsize " << uuid.cmdsize;
9067   if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
9068     outs() << " Incorrect size\n";
9069   else
9070     outs() << "\n";
9071   outs() << "    uuid ";
9072   for (int i = 0; i < 16; ++i) {
9073     outs() << format("%02" PRIX32, uuid.uuid[i]);
9074     if (i == 3 || i == 5 || i == 7 || i == 9)
9075       outs() << "-";
9076   }
9077   outs() << "\n";
9078 }
9079 
9080 static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
9081   outs() << "          cmd LC_RPATH\n";
9082   outs() << "      cmdsize " << rpath.cmdsize;
9083   if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
9084     outs() << " Incorrect size\n";
9085   else
9086     outs() << "\n";
9087   if (rpath.path >= rpath.cmdsize)
9088     outs() << "         path ?(bad offset " << rpath.path << ")\n";
9089   else {
9090     const char *P = (const char *)(Ptr) + rpath.path;
9091     outs() << "         path " << P << " (offset " << rpath.path << ")\n";
9092   }
9093 }
9094 
9095 static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
9096   StringRef LoadCmdName;
9097   switch (vd.cmd) {
9098   case MachO::LC_VERSION_MIN_MACOSX:
9099     LoadCmdName = "LC_VERSION_MIN_MACOSX";
9100     break;
9101   case MachO::LC_VERSION_MIN_IPHONEOS:
9102     LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
9103     break;
9104   case MachO::LC_VERSION_MIN_TVOS:
9105     LoadCmdName = "LC_VERSION_MIN_TVOS";
9106     break;
9107   case MachO::LC_VERSION_MIN_WATCHOS:
9108     LoadCmdName = "LC_VERSION_MIN_WATCHOS";
9109     break;
9110   default:
9111     llvm_unreachable("Unknown version min load command");
9112   }
9113 
9114   outs() << "      cmd " << LoadCmdName << '\n';
9115   outs() << "  cmdsize " << vd.cmdsize;
9116   if (vd.cmdsize != sizeof(struct MachO::version_min_command))
9117     outs() << " Incorrect size\n";
9118   else
9119     outs() << "\n";
9120   outs() << "  version "
9121          << MachOObjectFile::getVersionMinMajor(vd, false) << "."
9122          << MachOObjectFile::getVersionMinMinor(vd, false);
9123   uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
9124   if (Update != 0)
9125     outs() << "." << Update;
9126   outs() << "\n";
9127   if (vd.sdk == 0)
9128     outs() << "      sdk n/a";
9129   else {
9130     outs() << "      sdk "
9131            << MachOObjectFile::getVersionMinMajor(vd, true) << "."
9132            << MachOObjectFile::getVersionMinMinor(vd, true);
9133   }
9134   Update = MachOObjectFile::getVersionMinUpdate(vd, true);
9135   if (Update != 0)
9136     outs() << "." << Update;
9137   outs() << "\n";
9138 }
9139 
9140 static void PrintNoteLoadCommand(MachO::note_command Nt) {
9141   outs() << "       cmd LC_NOTE\n";
9142   outs() << "   cmdsize " << Nt.cmdsize;
9143   if (Nt.cmdsize != sizeof(struct MachO::note_command))
9144     outs() << " Incorrect size\n";
9145   else
9146     outs() << "\n";
9147   const char *d = Nt.data_owner;
9148   outs() << "data_owner " << format("%.16s\n", d);
9149   outs() << "    offset " << Nt.offset << "\n";
9150   outs() << "      size " << Nt.size << "\n";
9151 }
9152 
9153 static void PrintBuildToolVersion(MachO::build_tool_version bv) {
9154   outs() << "      tool " << MachOObjectFile::getBuildTool(bv.tool) << "\n";
9155   outs() << "   version " << MachOObjectFile::getVersionString(bv.version)
9156          << "\n";
9157 }
9158 
9159 static void PrintBuildVersionLoadCommand(const MachOObjectFile *obj,
9160                                          MachO::build_version_command bd) {
9161   outs() << "       cmd LC_BUILD_VERSION\n";
9162   outs() << "   cmdsize " << bd.cmdsize;
9163   if (bd.cmdsize !=
9164       sizeof(struct MachO::build_version_command) +
9165           bd.ntools * sizeof(struct MachO::build_tool_version))
9166     outs() << " Incorrect size\n";
9167   else
9168     outs() << "\n";
9169   outs() << "  platform " << MachOObjectFile::getBuildPlatform(bd.platform)
9170          << "\n";
9171   if (bd.sdk)
9172     outs() << "       sdk " << MachOObjectFile::getVersionString(bd.sdk)
9173            << "\n";
9174   else
9175     outs() << "       sdk n/a\n";
9176   outs() << "     minos " << MachOObjectFile::getVersionString(bd.minos)
9177          << "\n";
9178   outs() << "    ntools " << bd.ntools << "\n";
9179   for (unsigned i = 0; i < bd.ntools; ++i) {
9180     MachO::build_tool_version bv = obj->getBuildToolVersion(i);
9181     PrintBuildToolVersion(bv);
9182   }
9183 }
9184 
9185 static void PrintSourceVersionCommand(MachO::source_version_command sd) {
9186   outs() << "      cmd LC_SOURCE_VERSION\n";
9187   outs() << "  cmdsize " << sd.cmdsize;
9188   if (sd.cmdsize != sizeof(struct MachO::source_version_command))
9189     outs() << " Incorrect size\n";
9190   else
9191     outs() << "\n";
9192   uint64_t a = (sd.version >> 40) & 0xffffff;
9193   uint64_t b = (sd.version >> 30) & 0x3ff;
9194   uint64_t c = (sd.version >> 20) & 0x3ff;
9195   uint64_t d = (sd.version >> 10) & 0x3ff;
9196   uint64_t e = sd.version & 0x3ff;
9197   outs() << "  version " << a << "." << b;
9198   if (e != 0)
9199     outs() << "." << c << "." << d << "." << e;
9200   else if (d != 0)
9201     outs() << "." << c << "." << d;
9202   else if (c != 0)
9203     outs() << "." << c;
9204   outs() << "\n";
9205 }
9206 
9207 static void PrintEntryPointCommand(MachO::entry_point_command ep) {
9208   outs() << "       cmd LC_MAIN\n";
9209   outs() << "   cmdsize " << ep.cmdsize;
9210   if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
9211     outs() << " Incorrect size\n";
9212   else
9213     outs() << "\n";
9214   outs() << "  entryoff " << ep.entryoff << "\n";
9215   outs() << " stacksize " << ep.stacksize << "\n";
9216 }
9217 
9218 static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
9219                                        uint32_t object_size) {
9220   outs() << "          cmd LC_ENCRYPTION_INFO\n";
9221   outs() << "      cmdsize " << ec.cmdsize;
9222   if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
9223     outs() << " Incorrect size\n";
9224   else
9225     outs() << "\n";
9226   outs() << "     cryptoff " << ec.cryptoff;
9227   if (ec.cryptoff > object_size)
9228     outs() << " (past end of file)\n";
9229   else
9230     outs() << "\n";
9231   outs() << "    cryptsize " << ec.cryptsize;
9232   if (ec.cryptsize > object_size)
9233     outs() << " (past end of file)\n";
9234   else
9235     outs() << "\n";
9236   outs() << "      cryptid " << ec.cryptid << "\n";
9237 }
9238 
9239 static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
9240                                          uint32_t object_size) {
9241   outs() << "          cmd LC_ENCRYPTION_INFO_64\n";
9242   outs() << "      cmdsize " << ec.cmdsize;
9243   if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
9244     outs() << " Incorrect size\n";
9245   else
9246     outs() << "\n";
9247   outs() << "     cryptoff " << ec.cryptoff;
9248   if (ec.cryptoff > object_size)
9249     outs() << " (past end of file)\n";
9250   else
9251     outs() << "\n";
9252   outs() << "    cryptsize " << ec.cryptsize;
9253   if (ec.cryptsize > object_size)
9254     outs() << " (past end of file)\n";
9255   else
9256     outs() << "\n";
9257   outs() << "      cryptid " << ec.cryptid << "\n";
9258   outs() << "          pad " << ec.pad << "\n";
9259 }
9260 
9261 static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
9262                                      const char *Ptr) {
9263   outs() << "     cmd LC_LINKER_OPTION\n";
9264   outs() << " cmdsize " << lo.cmdsize;
9265   if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
9266     outs() << " Incorrect size\n";
9267   else
9268     outs() << "\n";
9269   outs() << "   count " << lo.count << "\n";
9270   const char *string = Ptr + sizeof(struct MachO::linker_option_command);
9271   uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
9272   uint32_t i = 0;
9273   while (left > 0) {
9274     while (*string == '\0' && left > 0) {
9275       string++;
9276       left--;
9277     }
9278     if (left > 0) {
9279       i++;
9280       outs() << "  string #" << i << " " << format("%.*s\n", left, string);
9281       uint32_t NullPos = StringRef(string, left).find('\0');
9282       uint32_t len = std::min(NullPos, left) + 1;
9283       string += len;
9284       left -= len;
9285     }
9286   }
9287   if (lo.count != i)
9288     outs() << "   count " << lo.count << " does not match number of strings "
9289            << i << "\n";
9290 }
9291 
9292 static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
9293                                      const char *Ptr) {
9294   outs() << "          cmd LC_SUB_FRAMEWORK\n";
9295   outs() << "      cmdsize " << sub.cmdsize;
9296   if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
9297     outs() << " Incorrect size\n";
9298   else
9299     outs() << "\n";
9300   if (sub.umbrella < sub.cmdsize) {
9301     const char *P = Ptr + sub.umbrella;
9302     outs() << "     umbrella " << P << " (offset " << sub.umbrella << ")\n";
9303   } else {
9304     outs() << "     umbrella ?(bad offset " << sub.umbrella << ")\n";
9305   }
9306 }
9307 
9308 static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
9309                                     const char *Ptr) {
9310   outs() << "          cmd LC_SUB_UMBRELLA\n";
9311   outs() << "      cmdsize " << sub.cmdsize;
9312   if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
9313     outs() << " Incorrect size\n";
9314   else
9315     outs() << "\n";
9316   if (sub.sub_umbrella < sub.cmdsize) {
9317     const char *P = Ptr + sub.sub_umbrella;
9318     outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
9319   } else {
9320     outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
9321   }
9322 }
9323 
9324 static void PrintSubLibraryCommand(MachO::sub_library_command sub,
9325                                    const char *Ptr) {
9326   outs() << "          cmd LC_SUB_LIBRARY\n";
9327   outs() << "      cmdsize " << sub.cmdsize;
9328   if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
9329     outs() << " Incorrect size\n";
9330   else
9331     outs() << "\n";
9332   if (sub.sub_library < sub.cmdsize) {
9333     const char *P = Ptr + sub.sub_library;
9334     outs() << "  sub_library " << P << " (offset " << sub.sub_library << ")\n";
9335   } else {
9336     outs() << "  sub_library ?(bad offset " << sub.sub_library << ")\n";
9337   }
9338 }
9339 
9340 static void PrintSubClientCommand(MachO::sub_client_command sub,
9341                                   const char *Ptr) {
9342   outs() << "          cmd LC_SUB_CLIENT\n";
9343   outs() << "      cmdsize " << sub.cmdsize;
9344   if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
9345     outs() << " Incorrect size\n";
9346   else
9347     outs() << "\n";
9348   if (sub.client < sub.cmdsize) {
9349     const char *P = Ptr + sub.client;
9350     outs() << "       client " << P << " (offset " << sub.client << ")\n";
9351   } else {
9352     outs() << "       client ?(bad offset " << sub.client << ")\n";
9353   }
9354 }
9355 
9356 static void PrintRoutinesCommand(MachO::routines_command r) {
9357   outs() << "          cmd LC_ROUTINES\n";
9358   outs() << "      cmdsize " << r.cmdsize;
9359   if (r.cmdsize != sizeof(struct MachO::routines_command))
9360     outs() << " Incorrect size\n";
9361   else
9362     outs() << "\n";
9363   outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
9364   outs() << "  init_module " << r.init_module << "\n";
9365   outs() << "    reserved1 " << r.reserved1 << "\n";
9366   outs() << "    reserved2 " << r.reserved2 << "\n";
9367   outs() << "    reserved3 " << r.reserved3 << "\n";
9368   outs() << "    reserved4 " << r.reserved4 << "\n";
9369   outs() << "    reserved5 " << r.reserved5 << "\n";
9370   outs() << "    reserved6 " << r.reserved6 << "\n";
9371 }
9372 
9373 static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
9374   outs() << "          cmd LC_ROUTINES_64\n";
9375   outs() << "      cmdsize " << r.cmdsize;
9376   if (r.cmdsize != sizeof(struct MachO::routines_command_64))
9377     outs() << " Incorrect size\n";
9378   else
9379     outs() << "\n";
9380   outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
9381   outs() << "  init_module " << r.init_module << "\n";
9382   outs() << "    reserved1 " << r.reserved1 << "\n";
9383   outs() << "    reserved2 " << r.reserved2 << "\n";
9384   outs() << "    reserved3 " << r.reserved3 << "\n";
9385   outs() << "    reserved4 " << r.reserved4 << "\n";
9386   outs() << "    reserved5 " << r.reserved5 << "\n";
9387   outs() << "    reserved6 " << r.reserved6 << "\n";
9388 }
9389 
9390 static void Print_x86_thread_state32_t(MachO::x86_thread_state32_t &cpu32) {
9391   outs() << "\t    eax " << format("0x%08" PRIx32, cpu32.eax);
9392   outs() << " ebx    " << format("0x%08" PRIx32, cpu32.ebx);
9393   outs() << " ecx " << format("0x%08" PRIx32, cpu32.ecx);
9394   outs() << " edx " << format("0x%08" PRIx32, cpu32.edx) << "\n";
9395   outs() << "\t    edi " << format("0x%08" PRIx32, cpu32.edi);
9396   outs() << " esi    " << format("0x%08" PRIx32, cpu32.esi);
9397   outs() << " ebp " << format("0x%08" PRIx32, cpu32.ebp);
9398   outs() << " esp " << format("0x%08" PRIx32, cpu32.esp) << "\n";
9399   outs() << "\t    ss  " << format("0x%08" PRIx32, cpu32.ss);
9400   outs() << " eflags " << format("0x%08" PRIx32, cpu32.eflags);
9401   outs() << " eip " << format("0x%08" PRIx32, cpu32.eip);
9402   outs() << " cs  " << format("0x%08" PRIx32, cpu32.cs) << "\n";
9403   outs() << "\t    ds  " << format("0x%08" PRIx32, cpu32.ds);
9404   outs() << " es     " << format("0x%08" PRIx32, cpu32.es);
9405   outs() << " fs  " << format("0x%08" PRIx32, cpu32.fs);
9406   outs() << " gs  " << format("0x%08" PRIx32, cpu32.gs) << "\n";
9407 }
9408 
9409 static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
9410   outs() << "   rax  " << format("0x%016" PRIx64, cpu64.rax);
9411   outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
9412   outs() << " rcx  " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
9413   outs() << "   rdx  " << format("0x%016" PRIx64, cpu64.rdx);
9414   outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
9415   outs() << " rsi  " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
9416   outs() << "   rbp  " << format("0x%016" PRIx64, cpu64.rbp);
9417   outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
9418   outs() << " r8   " << format("0x%016" PRIx64, cpu64.r8) << "\n";
9419   outs() << "    r9  " << format("0x%016" PRIx64, cpu64.r9);
9420   outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
9421   outs() << " r11  " << format("0x%016" PRIx64, cpu64.r11) << "\n";
9422   outs() << "   r12  " << format("0x%016" PRIx64, cpu64.r12);
9423   outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
9424   outs() << " r14  " << format("0x%016" PRIx64, cpu64.r14) << "\n";
9425   outs() << "   r15  " << format("0x%016" PRIx64, cpu64.r15);
9426   outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
9427   outs() << "rflags  " << format("0x%016" PRIx64, cpu64.rflags);
9428   outs() << " cs  " << format("0x%016" PRIx64, cpu64.cs);
9429   outs() << " fs   " << format("0x%016" PRIx64, cpu64.fs) << "\n";
9430   outs() << "    gs  " << format("0x%016" PRIx64, cpu64.gs) << "\n";
9431 }
9432 
9433 static void Print_mmst_reg(MachO::mmst_reg_t &r) {
9434   uint32_t f;
9435   outs() << "\t      mmst_reg  ";
9436   for (f = 0; f < 10; f++)
9437     outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
9438   outs() << "\n";
9439   outs() << "\t      mmst_rsrv ";
9440   for (f = 0; f < 6; f++)
9441     outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
9442   outs() << "\n";
9443 }
9444 
9445 static void Print_xmm_reg(MachO::xmm_reg_t &r) {
9446   uint32_t f;
9447   outs() << "\t      xmm_reg ";
9448   for (f = 0; f < 16; f++)
9449     outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
9450   outs() << "\n";
9451 }
9452 
9453 static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
9454   outs() << "\t    fpu_reserved[0] " << fpu.fpu_reserved[0];
9455   outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
9456   outs() << "\t    control: invalid " << fpu.fpu_fcw.invalid;
9457   outs() << " denorm " << fpu.fpu_fcw.denorm;
9458   outs() << " zdiv " << fpu.fpu_fcw.zdiv;
9459   outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
9460   outs() << " undfl " << fpu.fpu_fcw.undfl;
9461   outs() << " precis " << fpu.fpu_fcw.precis << "\n";
9462   outs() << "\t\t     pc ";
9463   if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
9464     outs() << "FP_PREC_24B ";
9465   else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
9466     outs() << "FP_PREC_53B ";
9467   else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
9468     outs() << "FP_PREC_64B ";
9469   else
9470     outs() << fpu.fpu_fcw.pc << " ";
9471   outs() << "rc ";
9472   if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
9473     outs() << "FP_RND_NEAR ";
9474   else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
9475     outs() << "FP_RND_DOWN ";
9476   else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
9477     outs() << "FP_RND_UP ";
9478   else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
9479     outs() << "FP_CHOP ";
9480   outs() << "\n";
9481   outs() << "\t    status: invalid " << fpu.fpu_fsw.invalid;
9482   outs() << " denorm " << fpu.fpu_fsw.denorm;
9483   outs() << " zdiv " << fpu.fpu_fsw.zdiv;
9484   outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
9485   outs() << " undfl " << fpu.fpu_fsw.undfl;
9486   outs() << " precis " << fpu.fpu_fsw.precis;
9487   outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
9488   outs() << "\t            errsumm " << fpu.fpu_fsw.errsumm;
9489   outs() << " c0 " << fpu.fpu_fsw.c0;
9490   outs() << " c1 " << fpu.fpu_fsw.c1;
9491   outs() << " c2 " << fpu.fpu_fsw.c2;
9492   outs() << " tos " << fpu.fpu_fsw.tos;
9493   outs() << " c3 " << fpu.fpu_fsw.c3;
9494   outs() << " busy " << fpu.fpu_fsw.busy << "\n";
9495   outs() << "\t    fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
9496   outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
9497   outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
9498   outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
9499   outs() << "\t    fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
9500   outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
9501   outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
9502   outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
9503   outs() << "\t    fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
9504   outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
9505   outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
9506   outs() << "\n";
9507   outs() << "\t    fpu_stmm0:\n";
9508   Print_mmst_reg(fpu.fpu_stmm0);
9509   outs() << "\t    fpu_stmm1:\n";
9510   Print_mmst_reg(fpu.fpu_stmm1);
9511   outs() << "\t    fpu_stmm2:\n";
9512   Print_mmst_reg(fpu.fpu_stmm2);
9513   outs() << "\t    fpu_stmm3:\n";
9514   Print_mmst_reg(fpu.fpu_stmm3);
9515   outs() << "\t    fpu_stmm4:\n";
9516   Print_mmst_reg(fpu.fpu_stmm4);
9517   outs() << "\t    fpu_stmm5:\n";
9518   Print_mmst_reg(fpu.fpu_stmm5);
9519   outs() << "\t    fpu_stmm6:\n";
9520   Print_mmst_reg(fpu.fpu_stmm6);
9521   outs() << "\t    fpu_stmm7:\n";
9522   Print_mmst_reg(fpu.fpu_stmm7);
9523   outs() << "\t    fpu_xmm0:\n";
9524   Print_xmm_reg(fpu.fpu_xmm0);
9525   outs() << "\t    fpu_xmm1:\n";
9526   Print_xmm_reg(fpu.fpu_xmm1);
9527   outs() << "\t    fpu_xmm2:\n";
9528   Print_xmm_reg(fpu.fpu_xmm2);
9529   outs() << "\t    fpu_xmm3:\n";
9530   Print_xmm_reg(fpu.fpu_xmm3);
9531   outs() << "\t    fpu_xmm4:\n";
9532   Print_xmm_reg(fpu.fpu_xmm4);
9533   outs() << "\t    fpu_xmm5:\n";
9534   Print_xmm_reg(fpu.fpu_xmm5);
9535   outs() << "\t    fpu_xmm6:\n";
9536   Print_xmm_reg(fpu.fpu_xmm6);
9537   outs() << "\t    fpu_xmm7:\n";
9538   Print_xmm_reg(fpu.fpu_xmm7);
9539   outs() << "\t    fpu_xmm8:\n";
9540   Print_xmm_reg(fpu.fpu_xmm8);
9541   outs() << "\t    fpu_xmm9:\n";
9542   Print_xmm_reg(fpu.fpu_xmm9);
9543   outs() << "\t    fpu_xmm10:\n";
9544   Print_xmm_reg(fpu.fpu_xmm10);
9545   outs() << "\t    fpu_xmm11:\n";
9546   Print_xmm_reg(fpu.fpu_xmm11);
9547   outs() << "\t    fpu_xmm12:\n";
9548   Print_xmm_reg(fpu.fpu_xmm12);
9549   outs() << "\t    fpu_xmm13:\n";
9550   Print_xmm_reg(fpu.fpu_xmm13);
9551   outs() << "\t    fpu_xmm14:\n";
9552   Print_xmm_reg(fpu.fpu_xmm14);
9553   outs() << "\t    fpu_xmm15:\n";
9554   Print_xmm_reg(fpu.fpu_xmm15);
9555   outs() << "\t    fpu_rsrv4:\n";
9556   for (uint32_t f = 0; f < 6; f++) {
9557     outs() << "\t            ";
9558     for (uint32_t g = 0; g < 16; g++)
9559       outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
9560     outs() << "\n";
9561   }
9562   outs() << "\t    fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
9563   outs() << "\n";
9564 }
9565 
9566 static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
9567   outs() << "\t    trapno " << format("0x%08" PRIx32, exc64.trapno);
9568   outs() << " err " << format("0x%08" PRIx32, exc64.err);
9569   outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
9570 }
9571 
9572 static void Print_arm_thread_state32_t(MachO::arm_thread_state32_t &cpu32) {
9573   outs() << "\t    r0  " << format("0x%08" PRIx32, cpu32.r[0]);
9574   outs() << " r1     "   << format("0x%08" PRIx32, cpu32.r[1]);
9575   outs() << " r2  "      << format("0x%08" PRIx32, cpu32.r[2]);
9576   outs() << " r3  "      << format("0x%08" PRIx32, cpu32.r[3]) << "\n";
9577   outs() << "\t    r4  " << format("0x%08" PRIx32, cpu32.r[4]);
9578   outs() << " r5     "   << format("0x%08" PRIx32, cpu32.r[5]);
9579   outs() << " r6  "      << format("0x%08" PRIx32, cpu32.r[6]);
9580   outs() << " r7  "      << format("0x%08" PRIx32, cpu32.r[7]) << "\n";
9581   outs() << "\t    r8  " << format("0x%08" PRIx32, cpu32.r[8]);
9582   outs() << " r9     "   << format("0x%08" PRIx32, cpu32.r[9]);
9583   outs() << " r10 "      << format("0x%08" PRIx32, cpu32.r[10]);
9584   outs() << " r11 "      << format("0x%08" PRIx32, cpu32.r[11]) << "\n";
9585   outs() << "\t    r12 " << format("0x%08" PRIx32, cpu32.r[12]);
9586   outs() << " sp     "   << format("0x%08" PRIx32, cpu32.sp);
9587   outs() << " lr  "      << format("0x%08" PRIx32, cpu32.lr);
9588   outs() << " pc  "      << format("0x%08" PRIx32, cpu32.pc) << "\n";
9589   outs() << "\t   cpsr " << format("0x%08" PRIx32, cpu32.cpsr) << "\n";
9590 }
9591 
9592 static void Print_arm_thread_state64_t(MachO::arm_thread_state64_t &cpu64) {
9593   outs() << "\t    x0  " << format("0x%016" PRIx64, cpu64.x[0]);
9594   outs() << " x1  "      << format("0x%016" PRIx64, cpu64.x[1]);
9595   outs() << " x2  "      << format("0x%016" PRIx64, cpu64.x[2]) << "\n";
9596   outs() << "\t    x3  " << format("0x%016" PRIx64, cpu64.x[3]);
9597   outs() << " x4  "      << format("0x%016" PRIx64, cpu64.x[4]);
9598   outs() << " x5  "      << format("0x%016" PRIx64, cpu64.x[5]) << "\n";
9599   outs() << "\t    x6  " << format("0x%016" PRIx64, cpu64.x[6]);
9600   outs() << " x7  "      << format("0x%016" PRIx64, cpu64.x[7]);
9601   outs() << " x8  "      << format("0x%016" PRIx64, cpu64.x[8]) << "\n";
9602   outs() << "\t    x9  " << format("0x%016" PRIx64, cpu64.x[9]);
9603   outs() << " x10 "      << format("0x%016" PRIx64, cpu64.x[10]);
9604   outs() << " x11 "      << format("0x%016" PRIx64, cpu64.x[11]) << "\n";
9605   outs() << "\t    x12 " << format("0x%016" PRIx64, cpu64.x[12]);
9606   outs() << " x13 "      << format("0x%016" PRIx64, cpu64.x[13]);
9607   outs() << " x14 "      << format("0x%016" PRIx64, cpu64.x[14]) << "\n";
9608   outs() << "\t    x15 " << format("0x%016" PRIx64, cpu64.x[15]);
9609   outs() << " x16 "      << format("0x%016" PRIx64, cpu64.x[16]);
9610   outs() << " x17 "      << format("0x%016" PRIx64, cpu64.x[17]) << "\n";
9611   outs() << "\t    x18 " << format("0x%016" PRIx64, cpu64.x[18]);
9612   outs() << " x19 "      << format("0x%016" PRIx64, cpu64.x[19]);
9613   outs() << " x20 "      << format("0x%016" PRIx64, cpu64.x[20]) << "\n";
9614   outs() << "\t    x21 " << format("0x%016" PRIx64, cpu64.x[21]);
9615   outs() << " x22 "      << format("0x%016" PRIx64, cpu64.x[22]);
9616   outs() << " x23 "      << format("0x%016" PRIx64, cpu64.x[23]) << "\n";
9617   outs() << "\t    x24 " << format("0x%016" PRIx64, cpu64.x[24]);
9618   outs() << " x25 "      << format("0x%016" PRIx64, cpu64.x[25]);
9619   outs() << " x26 "      << format("0x%016" PRIx64, cpu64.x[26]) << "\n";
9620   outs() << "\t    x27 " << format("0x%016" PRIx64, cpu64.x[27]);
9621   outs() << " x28 "      << format("0x%016" PRIx64, cpu64.x[28]);
9622   outs() << "  fp "      << format("0x%016" PRIx64, cpu64.fp) << "\n";
9623   outs() << "\t     lr " << format("0x%016" PRIx64, cpu64.lr);
9624   outs() << " sp  "      << format("0x%016" PRIx64, cpu64.sp);
9625   outs() << "  pc "      << format("0x%016" PRIx64, cpu64.pc) << "\n";
9626   outs() << "\t   cpsr " << format("0x%08"  PRIx32, cpu64.cpsr) << "\n";
9627 }
9628 
9629 static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
9630                                bool isLittleEndian, uint32_t cputype) {
9631   if (t.cmd == MachO::LC_THREAD)
9632     outs() << "        cmd LC_THREAD\n";
9633   else if (t.cmd == MachO::LC_UNIXTHREAD)
9634     outs() << "        cmd LC_UNIXTHREAD\n";
9635   else
9636     outs() << "        cmd " << t.cmd << " (unknown)\n";
9637   outs() << "    cmdsize " << t.cmdsize;
9638   if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
9639     outs() << " Incorrect size\n";
9640   else
9641     outs() << "\n";
9642 
9643   const char *begin = Ptr + sizeof(struct MachO::thread_command);
9644   const char *end = Ptr + t.cmdsize;
9645   uint32_t flavor, count, left;
9646   if (cputype == MachO::CPU_TYPE_I386) {
9647     while (begin < end) {
9648       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9649         memcpy((char *)&flavor, begin, sizeof(uint32_t));
9650         begin += sizeof(uint32_t);
9651       } else {
9652         flavor = 0;
9653         begin = end;
9654       }
9655       if (isLittleEndian != sys::IsLittleEndianHost)
9656         sys::swapByteOrder(flavor);
9657       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9658         memcpy((char *)&count, begin, sizeof(uint32_t));
9659         begin += sizeof(uint32_t);
9660       } else {
9661         count = 0;
9662         begin = end;
9663       }
9664       if (isLittleEndian != sys::IsLittleEndianHost)
9665         sys::swapByteOrder(count);
9666       if (flavor == MachO::x86_THREAD_STATE32) {
9667         outs() << "     flavor i386_THREAD_STATE\n";
9668         if (count == MachO::x86_THREAD_STATE32_COUNT)
9669           outs() << "      count i386_THREAD_STATE_COUNT\n";
9670         else
9671           outs() << "      count " << count
9672                  << " (not x86_THREAD_STATE32_COUNT)\n";
9673         MachO::x86_thread_state32_t cpu32;
9674         left = end - begin;
9675         if (left >= sizeof(MachO::x86_thread_state32_t)) {
9676           memcpy(&cpu32, begin, sizeof(MachO::x86_thread_state32_t));
9677           begin += sizeof(MachO::x86_thread_state32_t);
9678         } else {
9679           memset(&cpu32, '\0', sizeof(MachO::x86_thread_state32_t));
9680           memcpy(&cpu32, begin, left);
9681           begin += left;
9682         }
9683         if (isLittleEndian != sys::IsLittleEndianHost)
9684           swapStruct(cpu32);
9685         Print_x86_thread_state32_t(cpu32);
9686       } else if (flavor == MachO::x86_THREAD_STATE) {
9687         outs() << "     flavor x86_THREAD_STATE\n";
9688         if (count == MachO::x86_THREAD_STATE_COUNT)
9689           outs() << "      count x86_THREAD_STATE_COUNT\n";
9690         else
9691           outs() << "      count " << count
9692                  << " (not x86_THREAD_STATE_COUNT)\n";
9693         struct MachO::x86_thread_state_t ts;
9694         left = end - begin;
9695         if (left >= sizeof(MachO::x86_thread_state_t)) {
9696           memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
9697           begin += sizeof(MachO::x86_thread_state_t);
9698         } else {
9699           memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
9700           memcpy(&ts, begin, left);
9701           begin += left;
9702         }
9703         if (isLittleEndian != sys::IsLittleEndianHost)
9704           swapStruct(ts);
9705         if (ts.tsh.flavor == MachO::x86_THREAD_STATE32) {
9706           outs() << "\t    tsh.flavor x86_THREAD_STATE32 ";
9707           if (ts.tsh.count == MachO::x86_THREAD_STATE32_COUNT)
9708             outs() << "tsh.count x86_THREAD_STATE32_COUNT\n";
9709           else
9710             outs() << "tsh.count " << ts.tsh.count
9711                    << " (not x86_THREAD_STATE32_COUNT\n";
9712           Print_x86_thread_state32_t(ts.uts.ts32);
9713         } else {
9714           outs() << "\t    tsh.flavor " << ts.tsh.flavor << "  tsh.count "
9715                  << ts.tsh.count << "\n";
9716         }
9717       } else {
9718         outs() << "     flavor " << flavor << " (unknown)\n";
9719         outs() << "      count " << count << "\n";
9720         outs() << "      state (unknown)\n";
9721         begin += count * sizeof(uint32_t);
9722       }
9723     }
9724   } else if (cputype == MachO::CPU_TYPE_X86_64) {
9725     while (begin < end) {
9726       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9727         memcpy((char *)&flavor, begin, sizeof(uint32_t));
9728         begin += sizeof(uint32_t);
9729       } else {
9730         flavor = 0;
9731         begin = end;
9732       }
9733       if (isLittleEndian != sys::IsLittleEndianHost)
9734         sys::swapByteOrder(flavor);
9735       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9736         memcpy((char *)&count, begin, sizeof(uint32_t));
9737         begin += sizeof(uint32_t);
9738       } else {
9739         count = 0;
9740         begin = end;
9741       }
9742       if (isLittleEndian != sys::IsLittleEndianHost)
9743         sys::swapByteOrder(count);
9744       if (flavor == MachO::x86_THREAD_STATE64) {
9745         outs() << "     flavor x86_THREAD_STATE64\n";
9746         if (count == MachO::x86_THREAD_STATE64_COUNT)
9747           outs() << "      count x86_THREAD_STATE64_COUNT\n";
9748         else
9749           outs() << "      count " << count
9750                  << " (not x86_THREAD_STATE64_COUNT)\n";
9751         MachO::x86_thread_state64_t cpu64;
9752         left = end - begin;
9753         if (left >= sizeof(MachO::x86_thread_state64_t)) {
9754           memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
9755           begin += sizeof(MachO::x86_thread_state64_t);
9756         } else {
9757           memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
9758           memcpy(&cpu64, begin, left);
9759           begin += left;
9760         }
9761         if (isLittleEndian != sys::IsLittleEndianHost)
9762           swapStruct(cpu64);
9763         Print_x86_thread_state64_t(cpu64);
9764       } else if (flavor == MachO::x86_THREAD_STATE) {
9765         outs() << "     flavor x86_THREAD_STATE\n";
9766         if (count == MachO::x86_THREAD_STATE_COUNT)
9767           outs() << "      count x86_THREAD_STATE_COUNT\n";
9768         else
9769           outs() << "      count " << count
9770                  << " (not x86_THREAD_STATE_COUNT)\n";
9771         struct MachO::x86_thread_state_t ts;
9772         left = end - begin;
9773         if (left >= sizeof(MachO::x86_thread_state_t)) {
9774           memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
9775           begin += sizeof(MachO::x86_thread_state_t);
9776         } else {
9777           memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
9778           memcpy(&ts, begin, left);
9779           begin += left;
9780         }
9781         if (isLittleEndian != sys::IsLittleEndianHost)
9782           swapStruct(ts);
9783         if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
9784           outs() << "\t    tsh.flavor x86_THREAD_STATE64 ";
9785           if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
9786             outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
9787           else
9788             outs() << "tsh.count " << ts.tsh.count
9789                    << " (not x86_THREAD_STATE64_COUNT\n";
9790           Print_x86_thread_state64_t(ts.uts.ts64);
9791         } else {
9792           outs() << "\t    tsh.flavor " << ts.tsh.flavor << "  tsh.count "
9793                  << ts.tsh.count << "\n";
9794         }
9795       } else if (flavor == MachO::x86_FLOAT_STATE) {
9796         outs() << "     flavor x86_FLOAT_STATE\n";
9797         if (count == MachO::x86_FLOAT_STATE_COUNT)
9798           outs() << "      count x86_FLOAT_STATE_COUNT\n";
9799         else
9800           outs() << "      count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
9801         struct MachO::x86_float_state_t fs;
9802         left = end - begin;
9803         if (left >= sizeof(MachO::x86_float_state_t)) {
9804           memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
9805           begin += sizeof(MachO::x86_float_state_t);
9806         } else {
9807           memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
9808           memcpy(&fs, begin, left);
9809           begin += left;
9810         }
9811         if (isLittleEndian != sys::IsLittleEndianHost)
9812           swapStruct(fs);
9813         if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
9814           outs() << "\t    fsh.flavor x86_FLOAT_STATE64 ";
9815           if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
9816             outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
9817           else
9818             outs() << "fsh.count " << fs.fsh.count
9819                    << " (not x86_FLOAT_STATE64_COUNT\n";
9820           Print_x86_float_state_t(fs.ufs.fs64);
9821         } else {
9822           outs() << "\t    fsh.flavor " << fs.fsh.flavor << "  fsh.count "
9823                  << fs.fsh.count << "\n";
9824         }
9825       } else if (flavor == MachO::x86_EXCEPTION_STATE) {
9826         outs() << "     flavor x86_EXCEPTION_STATE\n";
9827         if (count == MachO::x86_EXCEPTION_STATE_COUNT)
9828           outs() << "      count x86_EXCEPTION_STATE_COUNT\n";
9829         else
9830           outs() << "      count " << count
9831                  << " (not x86_EXCEPTION_STATE_COUNT)\n";
9832         struct MachO::x86_exception_state_t es;
9833         left = end - begin;
9834         if (left >= sizeof(MachO::x86_exception_state_t)) {
9835           memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
9836           begin += sizeof(MachO::x86_exception_state_t);
9837         } else {
9838           memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
9839           memcpy(&es, begin, left);
9840           begin += left;
9841         }
9842         if (isLittleEndian != sys::IsLittleEndianHost)
9843           swapStruct(es);
9844         if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
9845           outs() << "\t    esh.flavor x86_EXCEPTION_STATE64\n";
9846           if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
9847             outs() << "\t    esh.count x86_EXCEPTION_STATE64_COUNT\n";
9848           else
9849             outs() << "\t    esh.count " << es.esh.count
9850                    << " (not x86_EXCEPTION_STATE64_COUNT\n";
9851           Print_x86_exception_state_t(es.ues.es64);
9852         } else {
9853           outs() << "\t    esh.flavor " << es.esh.flavor << "  esh.count "
9854                  << es.esh.count << "\n";
9855         }
9856       } else if (flavor == MachO::x86_EXCEPTION_STATE64) {
9857         outs() << "     flavor x86_EXCEPTION_STATE64\n";
9858         if (count == MachO::x86_EXCEPTION_STATE64_COUNT)
9859           outs() << "      count x86_EXCEPTION_STATE64_COUNT\n";
9860         else
9861           outs() << "      count " << count
9862                  << " (not x86_EXCEPTION_STATE64_COUNT)\n";
9863         struct MachO::x86_exception_state64_t es64;
9864         left = end - begin;
9865         if (left >= sizeof(MachO::x86_exception_state64_t)) {
9866           memcpy(&es64, begin, sizeof(MachO::x86_exception_state64_t));
9867           begin += sizeof(MachO::x86_exception_state64_t);
9868         } else {
9869           memset(&es64, '\0', sizeof(MachO::x86_exception_state64_t));
9870           memcpy(&es64, begin, left);
9871           begin += left;
9872         }
9873         if (isLittleEndian != sys::IsLittleEndianHost)
9874           swapStruct(es64);
9875         Print_x86_exception_state_t(es64);
9876       } else {
9877         outs() << "     flavor " << flavor << " (unknown)\n";
9878         outs() << "      count " << count << "\n";
9879         outs() << "      state (unknown)\n";
9880         begin += count * sizeof(uint32_t);
9881       }
9882     }
9883   } else if (cputype == MachO::CPU_TYPE_ARM) {
9884     while (begin < end) {
9885       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9886         memcpy((char *)&flavor, begin, sizeof(uint32_t));
9887         begin += sizeof(uint32_t);
9888       } else {
9889         flavor = 0;
9890         begin = end;
9891       }
9892       if (isLittleEndian != sys::IsLittleEndianHost)
9893         sys::swapByteOrder(flavor);
9894       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9895         memcpy((char *)&count, begin, sizeof(uint32_t));
9896         begin += sizeof(uint32_t);
9897       } else {
9898         count = 0;
9899         begin = end;
9900       }
9901       if (isLittleEndian != sys::IsLittleEndianHost)
9902         sys::swapByteOrder(count);
9903       if (flavor == MachO::ARM_THREAD_STATE) {
9904         outs() << "     flavor ARM_THREAD_STATE\n";
9905         if (count == MachO::ARM_THREAD_STATE_COUNT)
9906           outs() << "      count ARM_THREAD_STATE_COUNT\n";
9907         else
9908           outs() << "      count " << count
9909                  << " (not ARM_THREAD_STATE_COUNT)\n";
9910         MachO::arm_thread_state32_t cpu32;
9911         left = end - begin;
9912         if (left >= sizeof(MachO::arm_thread_state32_t)) {
9913           memcpy(&cpu32, begin, sizeof(MachO::arm_thread_state32_t));
9914           begin += sizeof(MachO::arm_thread_state32_t);
9915         } else {
9916           memset(&cpu32, '\0', sizeof(MachO::arm_thread_state32_t));
9917           memcpy(&cpu32, begin, left);
9918           begin += left;
9919         }
9920         if (isLittleEndian != sys::IsLittleEndianHost)
9921           swapStruct(cpu32);
9922         Print_arm_thread_state32_t(cpu32);
9923       } else {
9924         outs() << "     flavor " << flavor << " (unknown)\n";
9925         outs() << "      count " << count << "\n";
9926         outs() << "      state (unknown)\n";
9927         begin += count * sizeof(uint32_t);
9928       }
9929     }
9930   } else if (cputype == MachO::CPU_TYPE_ARM64 ||
9931              cputype == MachO::CPU_TYPE_ARM64_32) {
9932     while (begin < end) {
9933       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9934         memcpy((char *)&flavor, begin, sizeof(uint32_t));
9935         begin += sizeof(uint32_t);
9936       } else {
9937         flavor = 0;
9938         begin = end;
9939       }
9940       if (isLittleEndian != sys::IsLittleEndianHost)
9941         sys::swapByteOrder(flavor);
9942       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9943         memcpy((char *)&count, begin, sizeof(uint32_t));
9944         begin += sizeof(uint32_t);
9945       } else {
9946         count = 0;
9947         begin = end;
9948       }
9949       if (isLittleEndian != sys::IsLittleEndianHost)
9950         sys::swapByteOrder(count);
9951       if (flavor == MachO::ARM_THREAD_STATE64) {
9952         outs() << "     flavor ARM_THREAD_STATE64\n";
9953         if (count == MachO::ARM_THREAD_STATE64_COUNT)
9954           outs() << "      count ARM_THREAD_STATE64_COUNT\n";
9955         else
9956           outs() << "      count " << count
9957                  << " (not ARM_THREAD_STATE64_COUNT)\n";
9958         MachO::arm_thread_state64_t cpu64;
9959         left = end - begin;
9960         if (left >= sizeof(MachO::arm_thread_state64_t)) {
9961           memcpy(&cpu64, begin, sizeof(MachO::arm_thread_state64_t));
9962           begin += sizeof(MachO::arm_thread_state64_t);
9963         } else {
9964           memset(&cpu64, '\0', sizeof(MachO::arm_thread_state64_t));
9965           memcpy(&cpu64, begin, left);
9966           begin += left;
9967         }
9968         if (isLittleEndian != sys::IsLittleEndianHost)
9969           swapStruct(cpu64);
9970         Print_arm_thread_state64_t(cpu64);
9971       } else {
9972         outs() << "     flavor " << flavor << " (unknown)\n";
9973         outs() << "      count " << count << "\n";
9974         outs() << "      state (unknown)\n";
9975         begin += count * sizeof(uint32_t);
9976       }
9977     }
9978   } else {
9979     while (begin < end) {
9980       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9981         memcpy((char *)&flavor, begin, sizeof(uint32_t));
9982         begin += sizeof(uint32_t);
9983       } else {
9984         flavor = 0;
9985         begin = end;
9986       }
9987       if (isLittleEndian != sys::IsLittleEndianHost)
9988         sys::swapByteOrder(flavor);
9989       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9990         memcpy((char *)&count, begin, sizeof(uint32_t));
9991         begin += sizeof(uint32_t);
9992       } else {
9993         count = 0;
9994         begin = end;
9995       }
9996       if (isLittleEndian != sys::IsLittleEndianHost)
9997         sys::swapByteOrder(count);
9998       outs() << "     flavor " << flavor << "\n";
9999       outs() << "      count " << count << "\n";
10000       outs() << "      state (Unknown cputype/cpusubtype)\n";
10001       begin += count * sizeof(uint32_t);
10002     }
10003   }
10004 }
10005 
10006 static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
10007   if (dl.cmd == MachO::LC_ID_DYLIB)
10008     outs() << "          cmd LC_ID_DYLIB\n";
10009   else if (dl.cmd == MachO::LC_LOAD_DYLIB)
10010     outs() << "          cmd LC_LOAD_DYLIB\n";
10011   else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
10012     outs() << "          cmd LC_LOAD_WEAK_DYLIB\n";
10013   else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
10014     outs() << "          cmd LC_REEXPORT_DYLIB\n";
10015   else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
10016     outs() << "          cmd LC_LAZY_LOAD_DYLIB\n";
10017   else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
10018     outs() << "          cmd LC_LOAD_UPWARD_DYLIB\n";
10019   else
10020     outs() << "          cmd " << dl.cmd << " (unknown)\n";
10021   outs() << "      cmdsize " << dl.cmdsize;
10022   if (dl.cmdsize < sizeof(struct MachO::dylib_command))
10023     outs() << " Incorrect size\n";
10024   else
10025     outs() << "\n";
10026   if (dl.dylib.name < dl.cmdsize) {
10027     const char *P = (const char *)(Ptr) + dl.dylib.name;
10028     outs() << "         name " << P << " (offset " << dl.dylib.name << ")\n";
10029   } else {
10030     outs() << "         name ?(bad offset " << dl.dylib.name << ")\n";
10031   }
10032   outs() << "   time stamp " << dl.dylib.timestamp << " ";
10033   time_t t = dl.dylib.timestamp;
10034   outs() << ctime(&t);
10035   outs() << "      current version ";
10036   if (dl.dylib.current_version == 0xffffffff)
10037     outs() << "n/a\n";
10038   else
10039     outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
10040            << ((dl.dylib.current_version >> 8) & 0xff) << "."
10041            << (dl.dylib.current_version & 0xff) << "\n";
10042   outs() << "compatibility version ";
10043   if (dl.dylib.compatibility_version == 0xffffffff)
10044     outs() << "n/a\n";
10045   else
10046     outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
10047            << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
10048            << (dl.dylib.compatibility_version & 0xff) << "\n";
10049 }
10050 
10051 static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
10052                                      uint32_t object_size) {
10053   if (ld.cmd == MachO::LC_CODE_SIGNATURE)
10054     outs() << "      cmd LC_CODE_SIGNATURE\n";
10055   else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
10056     outs() << "      cmd LC_SEGMENT_SPLIT_INFO\n";
10057   else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
10058     outs() << "      cmd LC_FUNCTION_STARTS\n";
10059   else if (ld.cmd == MachO::LC_DATA_IN_CODE)
10060     outs() << "      cmd LC_DATA_IN_CODE\n";
10061   else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
10062     outs() << "      cmd LC_DYLIB_CODE_SIGN_DRS\n";
10063   else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
10064     outs() << "      cmd LC_LINKER_OPTIMIZATION_HINT\n";
10065   else
10066     outs() << "      cmd " << ld.cmd << " (?)\n";
10067   outs() << "  cmdsize " << ld.cmdsize;
10068   if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
10069     outs() << " Incorrect size\n";
10070   else
10071     outs() << "\n";
10072   outs() << "  dataoff " << ld.dataoff;
10073   if (ld.dataoff > object_size)
10074     outs() << " (past end of file)\n";
10075   else
10076     outs() << "\n";
10077   outs() << " datasize " << ld.datasize;
10078   uint64_t big_size = ld.dataoff;
10079   big_size += ld.datasize;
10080   if (big_size > object_size)
10081     outs() << " (past end of file)\n";
10082   else
10083     outs() << "\n";
10084 }
10085 
10086 static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
10087                               uint32_t cputype, bool verbose) {
10088   StringRef Buf = Obj->getData();
10089   unsigned Index = 0;
10090   for (const auto &Command : Obj->load_commands()) {
10091     outs() << "Load command " << Index++ << "\n";
10092     if (Command.C.cmd == MachO::LC_SEGMENT) {
10093       MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
10094       const char *sg_segname = SLC.segname;
10095       PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
10096                           SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
10097                           SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
10098                           verbose);
10099       for (unsigned j = 0; j < SLC.nsects; j++) {
10100         MachO::section S = Obj->getSection(Command, j);
10101         PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
10102                      S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
10103                      SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
10104       }
10105     } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
10106       MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
10107       const char *sg_segname = SLC_64.segname;
10108       PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
10109                           SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
10110                           SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
10111                           SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
10112       for (unsigned j = 0; j < SLC_64.nsects; j++) {
10113         MachO::section_64 S_64 = Obj->getSection64(Command, j);
10114         PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
10115                      S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
10116                      S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
10117                      sg_segname, filetype, Buf.size(), verbose);
10118       }
10119     } else if (Command.C.cmd == MachO::LC_SYMTAB) {
10120       MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
10121       PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
10122     } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
10123       MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
10124       MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
10125       PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
10126                                Obj->is64Bit());
10127     } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
10128                Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
10129       MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
10130       PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
10131     } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
10132                Command.C.cmd == MachO::LC_ID_DYLINKER ||
10133                Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
10134       MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
10135       PrintDyldLoadCommand(Dyld, Command.Ptr);
10136     } else if (Command.C.cmd == MachO::LC_UUID) {
10137       MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
10138       PrintUuidLoadCommand(Uuid);
10139     } else if (Command.C.cmd == MachO::LC_RPATH) {
10140       MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
10141       PrintRpathLoadCommand(Rpath, Command.Ptr);
10142     } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
10143                Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
10144                Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
10145                Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
10146       MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
10147       PrintVersionMinLoadCommand(Vd);
10148     } else if (Command.C.cmd == MachO::LC_NOTE) {
10149       MachO::note_command Nt = Obj->getNoteLoadCommand(Command);
10150       PrintNoteLoadCommand(Nt);
10151     } else if (Command.C.cmd == MachO::LC_BUILD_VERSION) {
10152       MachO::build_version_command Bv =
10153           Obj->getBuildVersionLoadCommand(Command);
10154       PrintBuildVersionLoadCommand(Obj, Bv);
10155     } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
10156       MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
10157       PrintSourceVersionCommand(Sd);
10158     } else if (Command.C.cmd == MachO::LC_MAIN) {
10159       MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
10160       PrintEntryPointCommand(Ep);
10161     } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
10162       MachO::encryption_info_command Ei =
10163           Obj->getEncryptionInfoCommand(Command);
10164       PrintEncryptionInfoCommand(Ei, Buf.size());
10165     } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
10166       MachO::encryption_info_command_64 Ei =
10167           Obj->getEncryptionInfoCommand64(Command);
10168       PrintEncryptionInfoCommand64(Ei, Buf.size());
10169     } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
10170       MachO::linker_option_command Lo =
10171           Obj->getLinkerOptionLoadCommand(Command);
10172       PrintLinkerOptionCommand(Lo, Command.Ptr);
10173     } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
10174       MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
10175       PrintSubFrameworkCommand(Sf, Command.Ptr);
10176     } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
10177       MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
10178       PrintSubUmbrellaCommand(Sf, Command.Ptr);
10179     } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
10180       MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
10181       PrintSubLibraryCommand(Sl, Command.Ptr);
10182     } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
10183       MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
10184       PrintSubClientCommand(Sc, Command.Ptr);
10185     } else if (Command.C.cmd == MachO::LC_ROUTINES) {
10186       MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
10187       PrintRoutinesCommand(Rc);
10188     } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
10189       MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
10190       PrintRoutinesCommand64(Rc);
10191     } else if (Command.C.cmd == MachO::LC_THREAD ||
10192                Command.C.cmd == MachO::LC_UNIXTHREAD) {
10193       MachO::thread_command Tc = Obj->getThreadCommand(Command);
10194       PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
10195     } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
10196                Command.C.cmd == MachO::LC_ID_DYLIB ||
10197                Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
10198                Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
10199                Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
10200                Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
10201       MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
10202       PrintDylibCommand(Dl, Command.Ptr);
10203     } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
10204                Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
10205                Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
10206                Command.C.cmd == MachO::LC_DATA_IN_CODE ||
10207                Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
10208                Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
10209       MachO::linkedit_data_command Ld =
10210           Obj->getLinkeditDataLoadCommand(Command);
10211       PrintLinkEditDataCommand(Ld, Buf.size());
10212     } else {
10213       outs() << "      cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
10214              << ")\n";
10215       outs() << "  cmdsize " << Command.C.cmdsize << "\n";
10216       // TODO: get and print the raw bytes of the load command.
10217     }
10218     // TODO: print all the other kinds of load commands.
10219   }
10220 }
10221 
10222 static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
10223   if (Obj->is64Bit()) {
10224     MachO::mach_header_64 H_64;
10225     H_64 = Obj->getHeader64();
10226     PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
10227                     H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
10228   } else {
10229     MachO::mach_header H;
10230     H = Obj->getHeader();
10231     PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
10232                     H.sizeofcmds, H.flags, verbose);
10233   }
10234 }
10235 
10236 void objdump::printMachOFileHeader(const object::ObjectFile *Obj) {
10237   const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
10238   PrintMachHeader(file, !NonVerbose);
10239 }
10240 
10241 void objdump::printMachOLoadCommands(const object::ObjectFile *Obj) {
10242   const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
10243   uint32_t filetype = 0;
10244   uint32_t cputype = 0;
10245   if (file->is64Bit()) {
10246     MachO::mach_header_64 H_64;
10247     H_64 = file->getHeader64();
10248     filetype = H_64.filetype;
10249     cputype = H_64.cputype;
10250   } else {
10251     MachO::mach_header H;
10252     H = file->getHeader();
10253     filetype = H.filetype;
10254     cputype = H.cputype;
10255   }
10256   PrintLoadCommands(file, filetype, cputype, !NonVerbose);
10257 }
10258 
10259 //===----------------------------------------------------------------------===//
10260 // export trie dumping
10261 //===----------------------------------------------------------------------===//
10262 
10263 static void printMachOExportsTrie(const object::MachOObjectFile *Obj) {
10264   uint64_t BaseSegmentAddress = 0;
10265   for (const auto &Command : Obj->load_commands()) {
10266     if (Command.C.cmd == MachO::LC_SEGMENT) {
10267       MachO::segment_command Seg = Obj->getSegmentLoadCommand(Command);
10268       if (Seg.fileoff == 0 && Seg.filesize != 0) {
10269         BaseSegmentAddress = Seg.vmaddr;
10270         break;
10271       }
10272     } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
10273       MachO::segment_command_64 Seg = Obj->getSegment64LoadCommand(Command);
10274       if (Seg.fileoff == 0 && Seg.filesize != 0) {
10275         BaseSegmentAddress = Seg.vmaddr;
10276         break;
10277       }
10278     }
10279   }
10280   Error Err = Error::success();
10281   for (const object::ExportEntry &Entry : Obj->exports(Err)) {
10282     uint64_t Flags = Entry.flags();
10283     bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
10284     bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
10285     bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
10286                         MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
10287     bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
10288                 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
10289     bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
10290     if (ReExport)
10291       outs() << "[re-export] ";
10292     else
10293       outs() << format("0x%08llX  ",
10294                        Entry.address() + BaseSegmentAddress);
10295     outs() << Entry.name();
10296     if (WeakDef || ThreadLocal || Resolver || Abs) {
10297       ListSeparator LS;
10298       outs() << " [";
10299       if (WeakDef)
10300         outs() << LS << "weak_def";
10301       if (ThreadLocal)
10302         outs() << LS << "per-thread";
10303       if (Abs)
10304         outs() << LS << "absolute";
10305       if (Resolver)
10306         outs() << LS << format("resolver=0x%08llX", Entry.other());
10307       outs() << "]";
10308     }
10309     if (ReExport) {
10310       StringRef DylibName = "unknown";
10311       int Ordinal = Entry.other() - 1;
10312       Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
10313       if (Entry.otherName().empty())
10314         outs() << " (from " << DylibName << ")";
10315       else
10316         outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
10317     }
10318     outs() << "\n";
10319   }
10320   if (Err)
10321     reportError(std::move(Err), Obj->getFileName());
10322 }
10323 
10324 //===----------------------------------------------------------------------===//
10325 // rebase table dumping
10326 //===----------------------------------------------------------------------===//
10327 
10328 static void printMachORebaseTable(object::MachOObjectFile *Obj) {
10329   outs() << "segment  section            address     type\n";
10330   Error Err = Error::success();
10331   for (const object::MachORebaseEntry &Entry : Obj->rebaseTable(Err)) {
10332     StringRef SegmentName = Entry.segmentName();
10333     StringRef SectionName = Entry.sectionName();
10334     uint64_t Address = Entry.address();
10335 
10336     // Table lines look like: __DATA  __nl_symbol_ptr  0x0000F00C  pointer
10337     outs() << format("%-8s %-18s 0x%08" PRIX64 "  %s\n",
10338                      SegmentName.str().c_str(), SectionName.str().c_str(),
10339                      Address, Entry.typeName().str().c_str());
10340   }
10341   if (Err)
10342     reportError(std::move(Err), Obj->getFileName());
10343 }
10344 
10345 static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
10346   StringRef DylibName;
10347   switch (Ordinal) {
10348   case MachO::BIND_SPECIAL_DYLIB_SELF:
10349     return "this-image";
10350   case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
10351     return "main-executable";
10352   case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
10353     return "flat-namespace";
10354   default:
10355     if (Ordinal > 0) {
10356       std::error_code EC =
10357           Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
10358       if (EC)
10359         return "<<bad library ordinal>>";
10360       return DylibName;
10361     }
10362   }
10363   return "<<unknown special ordinal>>";
10364 }
10365 
10366 //===----------------------------------------------------------------------===//
10367 // bind table dumping
10368 //===----------------------------------------------------------------------===//
10369 
10370 static void printMachOBindTable(object::MachOObjectFile *Obj) {
10371   // Build table of sections so names can used in final output.
10372   outs() << "segment  section            address    type       "
10373             "addend dylib            symbol\n";
10374   Error Err = Error::success();
10375   for (const object::MachOBindEntry &Entry : Obj->bindTable(Err)) {
10376     StringRef SegmentName = Entry.segmentName();
10377     StringRef SectionName = Entry.sectionName();
10378     uint64_t Address = Entry.address();
10379 
10380     // Table lines look like:
10381     //  __DATA  __got  0x00012010    pointer   0 libSystem ___stack_chk_guard
10382     StringRef Attr;
10383     if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
10384       Attr = " (weak_import)";
10385     outs() << left_justify(SegmentName, 8) << " "
10386            << left_justify(SectionName, 18) << " "
10387            << format_hex(Address, 10, true) << " "
10388            << left_justify(Entry.typeName(), 8) << " "
10389            << format_decimal(Entry.addend(), 8) << " "
10390            << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
10391            << Entry.symbolName() << Attr << "\n";
10392   }
10393   if (Err)
10394     reportError(std::move(Err), Obj->getFileName());
10395 }
10396 
10397 //===----------------------------------------------------------------------===//
10398 // lazy bind table dumping
10399 //===----------------------------------------------------------------------===//
10400 
10401 static void printMachOLazyBindTable(object::MachOObjectFile *Obj) {
10402   outs() << "segment  section            address     "
10403             "dylib            symbol\n";
10404   Error Err = Error::success();
10405   for (const object::MachOBindEntry &Entry : Obj->lazyBindTable(Err)) {
10406     StringRef SegmentName = Entry.segmentName();
10407     StringRef SectionName = Entry.sectionName();
10408     uint64_t Address = Entry.address();
10409 
10410     // Table lines look like:
10411     //  __DATA  __got  0x00012010 libSystem ___stack_chk_guard
10412     outs() << left_justify(SegmentName, 8) << " "
10413            << left_justify(SectionName, 18) << " "
10414            << format_hex(Address, 10, true) << " "
10415            << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
10416            << Entry.symbolName() << "\n";
10417   }
10418   if (Err)
10419     reportError(std::move(Err), Obj->getFileName());
10420 }
10421 
10422 //===----------------------------------------------------------------------===//
10423 // weak bind table dumping
10424 //===----------------------------------------------------------------------===//
10425 
10426 static void printMachOWeakBindTable(object::MachOObjectFile *Obj) {
10427   outs() << "segment  section            address     "
10428             "type       addend   symbol\n";
10429   Error Err = Error::success();
10430   for (const object::MachOBindEntry &Entry : Obj->weakBindTable(Err)) {
10431     // Strong symbols don't have a location to update.
10432     if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
10433       outs() << "                                        strong              "
10434              << Entry.symbolName() << "\n";
10435       continue;
10436     }
10437     StringRef SegmentName = Entry.segmentName();
10438     StringRef SectionName = Entry.sectionName();
10439     uint64_t Address = Entry.address();
10440 
10441     // Table lines look like:
10442     // __DATA  __data  0x00001000  pointer    0   _foo
10443     outs() << left_justify(SegmentName, 8) << " "
10444            << left_justify(SectionName, 18) << " "
10445            << format_hex(Address, 10, true) << " "
10446            << left_justify(Entry.typeName(), 8) << " "
10447            << format_decimal(Entry.addend(), 8) << "   " << Entry.symbolName()
10448            << "\n";
10449   }
10450   if (Err)
10451     reportError(std::move(Err), Obj->getFileName());
10452 }
10453 
10454 // get_dyld_bind_info_symbolname() is used for disassembly and passed an
10455 // address, ReferenceValue, in the Mach-O file and looks in the dyld bind
10456 // information for that address. If the address is found its binding symbol
10457 // name is returned.  If not nullptr is returned.
10458 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
10459                                                  struct DisassembleInfo *info) {
10460   if (info->bindtable == nullptr) {
10461     info->bindtable = std::make_unique<SymbolAddressMap>();
10462     Error Err = Error::success();
10463     for (const object::MachOBindEntry &Entry : info->O->bindTable(Err)) {
10464       uint64_t Address = Entry.address();
10465       StringRef name = Entry.symbolName();
10466       if (!name.empty())
10467         (*info->bindtable)[Address] = name;
10468     }
10469     if (Err)
10470       reportError(std::move(Err), info->O->getFileName());
10471   }
10472   auto name = info->bindtable->lookup(ReferenceValue);
10473   return !name.empty() ? name.data() : nullptr;
10474 }
10475 
10476 void objdump::printLazyBindTable(ObjectFile *o) {
10477   outs() << "Lazy bind table:\n";
10478   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10479     printMachOLazyBindTable(MachO);
10480   else
10481     WithColor::error()
10482         << "This operation is only currently supported "
10483            "for Mach-O executable files.\n";
10484 }
10485 
10486 void objdump::printWeakBindTable(ObjectFile *o) {
10487   outs() << "Weak bind table:\n";
10488   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10489     printMachOWeakBindTable(MachO);
10490   else
10491     WithColor::error()
10492         << "This operation is only currently supported "
10493            "for Mach-O executable files.\n";
10494 }
10495 
10496 void objdump::printExportsTrie(const ObjectFile *o) {
10497   outs() << "Exports trie:\n";
10498   if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10499     printMachOExportsTrie(MachO);
10500   else
10501     WithColor::error()
10502         << "This operation is only currently supported "
10503            "for Mach-O executable files.\n";
10504 }
10505 
10506 void objdump::printRebaseTable(ObjectFile *o) {
10507   outs() << "Rebase table:\n";
10508   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10509     printMachORebaseTable(MachO);
10510   else
10511     WithColor::error()
10512         << "This operation is only currently supported "
10513            "for Mach-O executable files.\n";
10514 }
10515 
10516 void objdump::printBindTable(ObjectFile *o) {
10517   outs() << "Bind table:\n";
10518   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10519     printMachOBindTable(MachO);
10520   else
10521     WithColor::error()
10522         << "This operation is only currently supported "
10523            "for Mach-O executable files.\n";
10524 }
10525