]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm-project/llvm/tools/llvm-objdump/MachODump.cpp
Move all sources from the llvm project into contrib/llvm-project.
[FreeBSD/FreeBSD.git] / contrib / llvm-project / llvm / tools / llvm-objdump / MachODump.cpp
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 "llvm-objdump.h"
14 #include "llvm-c/Disassembler.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/ADT/Triple.h"
18 #include "llvm/BinaryFormat/MachO.h"
19 #include "llvm/Config/config.h"
20 #include "llvm/DebugInfo/DIContext.h"
21 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
22 #include "llvm/Demangle/Demangle.h"
23 #include "llvm/MC/MCAsmInfo.h"
24 #include "llvm/MC/MCContext.h"
25 #include "llvm/MC/MCDisassembler/MCDisassembler.h"
26 #include "llvm/MC/MCInst.h"
27 #include "llvm/MC/MCInstPrinter.h"
28 #include "llvm/MC/MCInstrDesc.h"
29 #include "llvm/MC/MCInstrInfo.h"
30 #include "llvm/MC/MCRegisterInfo.h"
31 #include "llvm/MC/MCSubtargetInfo.h"
32 #include "llvm/Object/MachO.h"
33 #include "llvm/Object/MachOUniversal.h"
34 #include "llvm/Support/Casting.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/Endian.h"
38 #include "llvm/Support/Format.h"
39 #include "llvm/Support/FormattedStream.h"
40 #include "llvm/Support/GraphWriter.h"
41 #include "llvm/Support/LEB128.h"
42 #include "llvm/Support/MemoryBuffer.h"
43 #include "llvm/Support/TargetRegistry.h"
44 #include "llvm/Support/TargetSelect.h"
45 #include "llvm/Support/ToolOutputFile.h"
46 #include "llvm/Support/WithColor.h"
47 #include "llvm/Support/raw_ostream.h"
48 #include <algorithm>
49 #include <cstring>
50 #include <system_error>
51
52 #ifdef HAVE_LIBXAR
53 extern "C" {
54 #include <xar/xar.h>
55 }
56 #endif
57
58 using namespace llvm::object;
59
60 namespace llvm {
61
62 cl::OptionCategory MachOCat("llvm-objdump MachO Specific Options");
63
64 extern cl::opt<bool> ArchiveHeaders;
65 extern cl::opt<bool> Disassemble;
66 extern cl::opt<bool> DisassembleAll;
67 extern cl::opt<DIDumpType> DwarfDumpType;
68 extern cl::list<std::string> FilterSections;
69 extern cl::list<std::string> MAttrs;
70 extern cl::opt<std::string> MCPU;
71 extern cl::opt<bool> NoShowRawInsn;
72 extern cl::opt<bool> NoLeadingAddr;
73 extern cl::opt<bool> PrintImmHex;
74 extern cl::opt<bool> PrivateHeaders;
75 extern cl::opt<bool> Relocations;
76 extern cl::opt<bool> SectionHeaders;
77 extern cl::opt<bool> SectionContents;
78 extern cl::opt<bool> SymbolTable;
79 extern cl::opt<std::string> TripleName;
80 extern cl::opt<bool> UnwindInfo;
81
82 cl::opt<bool>
83     FirstPrivateHeader("private-header",
84                        cl::desc("Display only the first format specific file "
85                                 "header"),
86                        cl::cat(MachOCat));
87
88 cl::opt<bool> ExportsTrie("exports-trie",
89                           cl::desc("Display mach-o exported symbols"),
90                           cl::cat(MachOCat));
91
92 cl::opt<bool> Rebase("rebase", cl::desc("Display mach-o rebasing info"),
93                      cl::cat(MachOCat));
94
95 cl::opt<bool> Bind("bind", cl::desc("Display mach-o binding info"),
96                    cl::cat(MachOCat));
97
98 cl::opt<bool> LazyBind("lazy-bind",
99                        cl::desc("Display mach-o lazy binding info"),
100                        cl::cat(MachOCat));
101
102 cl::opt<bool> WeakBind("weak-bind",
103                        cl::desc("Display mach-o weak binding info"),
104                        cl::cat(MachOCat));
105
106 static cl::opt<bool>
107     UseDbg("g", cl::Grouping,
108            cl::desc("Print line information from debug info if available"),
109            cl::cat(MachOCat));
110
111 static cl::opt<std::string> DSYMFile("dsym",
112                                      cl::desc("Use .dSYM file for debug info"),
113                                      cl::cat(MachOCat));
114
115 static cl::opt<bool> FullLeadingAddr("full-leading-addr",
116                                      cl::desc("Print full leading address"),
117                                      cl::cat(MachOCat));
118
119 static cl::opt<bool> NoLeadingHeaders("no-leading-headers",
120                                       cl::desc("Print no leading headers"),
121                                       cl::cat(MachOCat));
122
123 cl::opt<bool> UniversalHeaders("universal-headers",
124                                cl::desc("Print Mach-O universal headers "
125                                         "(requires -macho)"),
126                                cl::cat(MachOCat));
127
128 cl::opt<bool>
129     ArchiveMemberOffsets("archive-member-offsets",
130                          cl::desc("Print the offset to each archive member for "
131                                   "Mach-O archives (requires -macho and "
132                                   "-archive-headers)"),
133                          cl::cat(MachOCat));
134
135 cl::opt<bool> IndirectSymbols("indirect-symbols",
136                               cl::desc("Print indirect symbol table for Mach-O "
137                                        "objects (requires -macho)"),
138                               cl::cat(MachOCat));
139
140 cl::opt<bool>
141     DataInCode("data-in-code",
142                cl::desc("Print the data in code table for Mach-O objects "
143                         "(requires -macho)"),
144                cl::cat(MachOCat));
145
146 cl::opt<bool> LinkOptHints("link-opt-hints",
147                            cl::desc("Print the linker optimization hints for "
148                                     "Mach-O objects (requires -macho)"),
149                            cl::cat(MachOCat));
150
151 cl::opt<bool> InfoPlist("info-plist",
152                         cl::desc("Print the info plist section as strings for "
153                                  "Mach-O objects (requires -macho)"),
154                         cl::cat(MachOCat));
155
156 cl::opt<bool> DylibsUsed("dylibs-used",
157                          cl::desc("Print the shared libraries used for linked "
158                                   "Mach-O files (requires -macho)"),
159                          cl::cat(MachOCat));
160
161 cl::opt<bool>
162     DylibId("dylib-id",
163             cl::desc("Print the shared library's id for the dylib Mach-O "
164                      "file (requires -macho)"),
165             cl::cat(MachOCat));
166
167 cl::opt<bool>
168     NonVerbose("non-verbose",
169                cl::desc("Print the info for Mach-O objects in "
170                         "non-verbose or numeric form (requires -macho)"),
171                cl::cat(MachOCat));
172
173 cl::opt<bool>
174     ObjcMetaData("objc-meta-data",
175                  cl::desc("Print the Objective-C runtime meta data for "
176                           "Mach-O files (requires -macho)"),
177                  cl::cat(MachOCat));
178
179 cl::opt<std::string> DisSymName(
180     "dis-symname",
181     cl::desc("disassemble just this symbol's instructions (requires -macho)"),
182     cl::cat(MachOCat));
183
184 static cl::opt<bool> NoSymbolicOperands(
185     "no-symbolic-operands",
186     cl::desc("do not symbolic operands when disassembling (requires -macho)"),
187     cl::cat(MachOCat));
188
189 static cl::list<std::string>
190     ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
191               cl::ZeroOrMore, cl::cat(MachOCat));
192
193 bool ArchAll = false;
194
195 static std::string ThumbTripleName;
196
197 static const Target *GetTarget(const MachOObjectFile *MachOObj,
198                                const char **McpuDefault,
199                                const Target **ThumbTarget) {
200   // Figure out the target triple.
201   Triple TT(TripleName);
202   if (TripleName.empty()) {
203     TT = MachOObj->getArchTriple(McpuDefault);
204     TripleName = TT.str();
205   }
206
207   if (TT.getArch() == Triple::arm) {
208     // We've inferred a 32-bit ARM target from the object file. All MachO CPUs
209     // that support ARM are also capable of Thumb mode.
210     Triple ThumbTriple = TT;
211     std::string ThumbName = (Twine("thumb") + TT.getArchName().substr(3)).str();
212     ThumbTriple.setArchName(ThumbName);
213     ThumbTripleName = ThumbTriple.str();
214   }
215
216   // Get the target specific parser.
217   std::string Error;
218   const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
219   if (TheTarget && ThumbTripleName.empty())
220     return TheTarget;
221
222   *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
223   if (*ThumbTarget)
224     return TheTarget;
225
226   WithColor::error(errs(), "llvm-objdump") << "unable to get target for '";
227   if (!TheTarget)
228     errs() << TripleName;
229   else
230     errs() << ThumbTripleName;
231   errs() << "', see --version and --triple.\n";
232   return nullptr;
233 }
234
235 struct SymbolSorter {
236   bool operator()(const SymbolRef &A, const SymbolRef &B) {
237     Expected<SymbolRef::Type> ATypeOrErr = A.getType();
238     if (!ATypeOrErr)
239       report_error(ATypeOrErr.takeError(), A.getObject()->getFileName());
240     SymbolRef::Type AType = *ATypeOrErr;
241     Expected<SymbolRef::Type> BTypeOrErr = B.getType();
242     if (!BTypeOrErr)
243       report_error(BTypeOrErr.takeError(), B.getObject()->getFileName());
244     SymbolRef::Type BType = *BTypeOrErr;
245     uint64_t AAddr = (AType != SymbolRef::ST_Function) ? 0 : A.getValue();
246     uint64_t BAddr = (BType != SymbolRef::ST_Function) ? 0 : B.getValue();
247     return AAddr < BAddr;
248   }
249 };
250
251 // Types for the storted data in code table that is built before disassembly
252 // and the predicate function to sort them.
253 typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
254 typedef std::vector<DiceTableEntry> DiceTable;
255 typedef DiceTable::iterator dice_table_iterator;
256
257 #ifdef HAVE_LIBXAR
258 namespace {
259 struct ScopedXarFile {
260   xar_t xar;
261   ScopedXarFile(const char *filename, int32_t flags)
262       : xar(xar_open(filename, flags)) {}
263   ~ScopedXarFile() {
264     if (xar)
265       xar_close(xar);
266   }
267   ScopedXarFile(const ScopedXarFile &) = delete;
268   ScopedXarFile &operator=(const ScopedXarFile &) = delete;
269   operator xar_t() { return xar; }
270 };
271
272 struct ScopedXarIter {
273   xar_iter_t iter;
274   ScopedXarIter() : iter(xar_iter_new()) {}
275   ~ScopedXarIter() {
276     if (iter)
277       xar_iter_free(iter);
278   }
279   ScopedXarIter(const ScopedXarIter &) = delete;
280   ScopedXarIter &operator=(const ScopedXarIter &) = delete;
281   operator xar_iter_t() { return iter; }
282 };
283 } // namespace
284 #endif // defined(HAVE_LIBXAR)
285
286 // This is used to search for a data in code table entry for the PC being
287 // disassembled.  The j parameter has the PC in j.first.  A single data in code
288 // table entry can cover many bytes for each of its Kind's.  So if the offset,
289 // aka the i.first value, of the data in code table entry plus its Length
290 // covers the PC being searched for this will return true.  If not it will
291 // return false.
292 static bool compareDiceTableEntries(const DiceTableEntry &i,
293                                     const DiceTableEntry &j) {
294   uint16_t Length;
295   i.second.getLength(Length);
296
297   return j.first >= i.first && j.first < i.first + Length;
298 }
299
300 static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
301                                unsigned short Kind) {
302   uint32_t Value, Size = 1;
303
304   switch (Kind) {
305   default:
306   case MachO::DICE_KIND_DATA:
307     if (Length >= 4) {
308       if (!NoShowRawInsn)
309         dumpBytes(makeArrayRef(bytes, 4), outs());
310       Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
311       outs() << "\t.long " << Value;
312       Size = 4;
313     } else if (Length >= 2) {
314       if (!NoShowRawInsn)
315         dumpBytes(makeArrayRef(bytes, 2), outs());
316       Value = bytes[1] << 8 | bytes[0];
317       outs() << "\t.short " << Value;
318       Size = 2;
319     } else {
320       if (!NoShowRawInsn)
321         dumpBytes(makeArrayRef(bytes, 2), outs());
322       Value = bytes[0];
323       outs() << "\t.byte " << Value;
324       Size = 1;
325     }
326     if (Kind == MachO::DICE_KIND_DATA)
327       outs() << "\t@ KIND_DATA\n";
328     else
329       outs() << "\t@ data in code kind = " << Kind << "\n";
330     break;
331   case MachO::DICE_KIND_JUMP_TABLE8:
332     if (!NoShowRawInsn)
333       dumpBytes(makeArrayRef(bytes, 1), outs());
334     Value = bytes[0];
335     outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
336     Size = 1;
337     break;
338   case MachO::DICE_KIND_JUMP_TABLE16:
339     if (!NoShowRawInsn)
340       dumpBytes(makeArrayRef(bytes, 2), outs());
341     Value = bytes[1] << 8 | bytes[0];
342     outs() << "\t.short " << format("%5u", Value & 0xffff)
343            << "\t@ KIND_JUMP_TABLE16\n";
344     Size = 2;
345     break;
346   case MachO::DICE_KIND_JUMP_TABLE32:
347   case MachO::DICE_KIND_ABS_JUMP_TABLE32:
348     if (!NoShowRawInsn)
349       dumpBytes(makeArrayRef(bytes, 4), outs());
350     Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
351     outs() << "\t.long " << Value;
352     if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
353       outs() << "\t@ KIND_JUMP_TABLE32\n";
354     else
355       outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
356     Size = 4;
357     break;
358   }
359   return Size;
360 }
361
362 static void getSectionsAndSymbols(MachOObjectFile *MachOObj,
363                                   std::vector<SectionRef> &Sections,
364                                   std::vector<SymbolRef> &Symbols,
365                                   SmallVectorImpl<uint64_t> &FoundFns,
366                                   uint64_t &BaseSegmentAddress) {
367   const StringRef FileName = MachOObj->getFileName();
368   for (const SymbolRef &Symbol : MachOObj->symbols()) {
369     StringRef SymName = unwrapOrError(Symbol.getName(), FileName);
370     if (!SymName.startswith("ltmp"))
371       Symbols.push_back(Symbol);
372   }
373
374   for (const SectionRef &Section : MachOObj->sections()) {
375     StringRef SectName;
376     Section.getName(SectName);
377     Sections.push_back(Section);
378   }
379
380   bool BaseSegmentAddressSet = false;
381   for (const auto &Command : MachOObj->load_commands()) {
382     if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
383       // We found a function starts segment, parse the addresses for later
384       // consumption.
385       MachO::linkedit_data_command LLC =
386           MachOObj->getLinkeditDataLoadCommand(Command);
387
388       MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
389     } else if (Command.C.cmd == MachO::LC_SEGMENT) {
390       MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
391       StringRef SegName = SLC.segname;
392       if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
393         BaseSegmentAddressSet = true;
394         BaseSegmentAddress = SLC.vmaddr;
395       }
396     }
397   }
398 }
399
400 static void printRelocationTargetName(const MachOObjectFile *O,
401                                       const MachO::any_relocation_info &RE,
402                                       raw_string_ostream &Fmt) {
403   // Target of a scattered relocation is an address.  In the interest of
404   // generating pretty output, scan through the symbol table looking for a
405   // symbol that aligns with that address.  If we find one, print it.
406   // Otherwise, we just print the hex address of the target.
407   const StringRef FileName = O->getFileName();
408   if (O->isRelocationScattered(RE)) {
409     uint32_t Val = O->getPlainRelocationSymbolNum(RE);
410
411     for (const SymbolRef &Symbol : O->symbols()) {
412       uint64_t Addr = unwrapOrError(Symbol.getAddress(), FileName);
413       if (Addr != Val)
414         continue;
415       Fmt << unwrapOrError(Symbol.getName(), FileName);
416       return;
417     }
418
419     // If we couldn't find a symbol that this relocation refers to, try
420     // to find a section beginning instead.
421     for (const SectionRef &Section : ToolSectionFilter(*O)) {
422       StringRef Name;
423       uint64_t Addr = Section.getAddress();
424       if (Addr != Val)
425         continue;
426       if (std::error_code EC = Section.getName(Name))
427         report_error(errorCodeToError(EC), O->getFileName());
428       Fmt << Name;
429       return;
430     }
431
432     Fmt << format("0x%x", Val);
433     return;
434   }
435
436   StringRef S;
437   bool isExtern = O->getPlainRelocationExternal(RE);
438   uint64_t Val = O->getPlainRelocationSymbolNum(RE);
439
440   if (O->getAnyRelocationType(RE) == MachO::ARM64_RELOC_ADDEND) {
441     Fmt << format("0x%0" PRIx64, Val);
442     return;
443   }
444
445   if (isExtern) {
446     symbol_iterator SI = O->symbol_begin();
447     advance(SI, Val);
448     S = unwrapOrError(SI->getName(), FileName);
449   } else {
450     section_iterator SI = O->section_begin();
451     // Adjust for the fact that sections are 1-indexed.
452     if (Val == 0) {
453       Fmt << "0 (?,?)";
454       return;
455     }
456     uint32_t I = Val - 1;
457     while (I != 0 && SI != O->section_end()) {
458       --I;
459       advance(SI, 1);
460     }
461     if (SI == O->section_end())
462       Fmt << Val << " (?,?)";
463     else
464       SI->getName(S);
465   }
466
467   Fmt << S;
468 }
469
470 Error getMachORelocationValueString(const MachOObjectFile *Obj,
471                                     const RelocationRef &RelRef,
472                                     SmallVectorImpl<char> &Result) {
473   DataRefImpl Rel = RelRef.getRawDataRefImpl();
474   MachO::any_relocation_info RE = Obj->getRelocation(Rel);
475
476   unsigned Arch = Obj->getArch();
477
478   std::string FmtBuf;
479   raw_string_ostream Fmt(FmtBuf);
480   unsigned Type = Obj->getAnyRelocationType(RE);
481   bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
482
483   // Determine any addends that should be displayed with the relocation.
484   // These require decoding the relocation type, which is triple-specific.
485
486   // X86_64 has entirely custom relocation types.
487   if (Arch == Triple::x86_64) {
488     switch (Type) {
489     case MachO::X86_64_RELOC_GOT_LOAD:
490     case MachO::X86_64_RELOC_GOT: {
491       printRelocationTargetName(Obj, RE, Fmt);
492       Fmt << "@GOT";
493       if (IsPCRel)
494         Fmt << "PCREL";
495       break;
496     }
497     case MachO::X86_64_RELOC_SUBTRACTOR: {
498       DataRefImpl RelNext = Rel;
499       Obj->moveRelocationNext(RelNext);
500       MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
501
502       // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
503       // X86_64_RELOC_UNSIGNED.
504       // NOTE: Scattered relocations don't exist on x86_64.
505       unsigned RType = Obj->getAnyRelocationType(RENext);
506       if (RType != MachO::X86_64_RELOC_UNSIGNED)
507         report_error(Obj->getFileName(), "Expected X86_64_RELOC_UNSIGNED after "
508                                          "X86_64_RELOC_SUBTRACTOR.");
509
510       // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
511       // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
512       printRelocationTargetName(Obj, RENext, Fmt);
513       Fmt << "-";
514       printRelocationTargetName(Obj, RE, Fmt);
515       break;
516     }
517     case MachO::X86_64_RELOC_TLV:
518       printRelocationTargetName(Obj, RE, Fmt);
519       Fmt << "@TLV";
520       if (IsPCRel)
521         Fmt << "P";
522       break;
523     case MachO::X86_64_RELOC_SIGNED_1:
524       printRelocationTargetName(Obj, RE, Fmt);
525       Fmt << "-1";
526       break;
527     case MachO::X86_64_RELOC_SIGNED_2:
528       printRelocationTargetName(Obj, RE, Fmt);
529       Fmt << "-2";
530       break;
531     case MachO::X86_64_RELOC_SIGNED_4:
532       printRelocationTargetName(Obj, RE, Fmt);
533       Fmt << "-4";
534       break;
535     default:
536       printRelocationTargetName(Obj, RE, Fmt);
537       break;
538     }
539     // X86 and ARM share some relocation types in common.
540   } else if (Arch == Triple::x86 || Arch == Triple::arm ||
541              Arch == Triple::ppc) {
542     // Generic relocation types...
543     switch (Type) {
544     case MachO::GENERIC_RELOC_PAIR: // prints no info
545       return Error::success();
546     case MachO::GENERIC_RELOC_SECTDIFF: {
547       DataRefImpl RelNext = Rel;
548       Obj->moveRelocationNext(RelNext);
549       MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
550
551       // X86 sect diff's must be followed by a relocation of type
552       // GENERIC_RELOC_PAIR.
553       unsigned RType = Obj->getAnyRelocationType(RENext);
554
555       if (RType != MachO::GENERIC_RELOC_PAIR)
556         report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
557                                          "GENERIC_RELOC_SECTDIFF.");
558
559       printRelocationTargetName(Obj, RE, Fmt);
560       Fmt << "-";
561       printRelocationTargetName(Obj, RENext, Fmt);
562       break;
563     }
564     }
565
566     if (Arch == Triple::x86 || Arch == Triple::ppc) {
567       switch (Type) {
568       case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
569         DataRefImpl RelNext = Rel;
570         Obj->moveRelocationNext(RelNext);
571         MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
572
573         // X86 sect diff's must be followed by a relocation of type
574         // GENERIC_RELOC_PAIR.
575         unsigned RType = Obj->getAnyRelocationType(RENext);
576         if (RType != MachO::GENERIC_RELOC_PAIR)
577           report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
578                                            "GENERIC_RELOC_LOCAL_SECTDIFF.");
579
580         printRelocationTargetName(Obj, RE, Fmt);
581         Fmt << "-";
582         printRelocationTargetName(Obj, RENext, Fmt);
583         break;
584       }
585       case MachO::GENERIC_RELOC_TLV: {
586         printRelocationTargetName(Obj, RE, Fmt);
587         Fmt << "@TLV";
588         if (IsPCRel)
589           Fmt << "P";
590         break;
591       }
592       default:
593         printRelocationTargetName(Obj, RE, Fmt);
594       }
595     } else { // ARM-specific relocations
596       switch (Type) {
597       case MachO::ARM_RELOC_HALF:
598       case MachO::ARM_RELOC_HALF_SECTDIFF: {
599         // Half relocations steal a bit from the length field to encode
600         // whether this is an upper16 or a lower16 relocation.
601         bool isUpper = (Obj->getAnyRelocationLength(RE) & 0x1) == 1;
602
603         if (isUpper)
604           Fmt << ":upper16:(";
605         else
606           Fmt << ":lower16:(";
607         printRelocationTargetName(Obj, RE, Fmt);
608
609         DataRefImpl RelNext = Rel;
610         Obj->moveRelocationNext(RelNext);
611         MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
612
613         // ARM half relocs must be followed by a relocation of type
614         // ARM_RELOC_PAIR.
615         unsigned RType = Obj->getAnyRelocationType(RENext);
616         if (RType != MachO::ARM_RELOC_PAIR)
617           report_error(Obj->getFileName(), "Expected ARM_RELOC_PAIR after "
618                                            "ARM_RELOC_HALF");
619
620         // NOTE: The half of the target virtual address is stashed in the
621         // address field of the secondary relocation, but we can't reverse
622         // engineer the constant offset from it without decoding the movw/movt
623         // instruction to find the other half in its immediate field.
624
625         // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
626         // symbol/section pointer of the follow-on relocation.
627         if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
628           Fmt << "-";
629           printRelocationTargetName(Obj, RENext, Fmt);
630         }
631
632         Fmt << ")";
633         break;
634       }
635       default: {
636         printRelocationTargetName(Obj, RE, Fmt);
637       }
638       }
639     }
640   } else
641     printRelocationTargetName(Obj, RE, Fmt);
642
643   Fmt.flush();
644   Result.append(FmtBuf.begin(), FmtBuf.end());
645   return Error::success();
646 }
647
648 static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
649                                      uint32_t n, uint32_t count,
650                                      uint32_t stride, uint64_t addr) {
651   MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
652   uint32_t nindirectsyms = Dysymtab.nindirectsyms;
653   if (n > nindirectsyms)
654     outs() << " (entries start past the end of the indirect symbol "
655               "table) (reserved1 field greater than the table size)";
656   else if (n + count > nindirectsyms)
657     outs() << " (entries extends past the end of the indirect symbol "
658               "table)";
659   outs() << "\n";
660   uint32_t cputype = O->getHeader().cputype;
661   if (cputype & MachO::CPU_ARCH_ABI64)
662     outs() << "address            index";
663   else
664     outs() << "address    index";
665   if (verbose)
666     outs() << " name\n";
667   else
668     outs() << "\n";
669   for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
670     if (cputype & MachO::CPU_ARCH_ABI64)
671       outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
672     else
673       outs() << format("0x%08" PRIx32, (uint32_t)addr + j * stride) << " ";
674     MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
675     uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
676     if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
677       outs() << "LOCAL\n";
678       continue;
679     }
680     if (indirect_symbol ==
681         (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
682       outs() << "LOCAL ABSOLUTE\n";
683       continue;
684     }
685     if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
686       outs() << "ABSOLUTE\n";
687       continue;
688     }
689     outs() << format("%5u ", indirect_symbol);
690     if (verbose) {
691       MachO::symtab_command Symtab = O->getSymtabLoadCommand();
692       if (indirect_symbol < Symtab.nsyms) {
693         symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
694         SymbolRef Symbol = *Sym;
695         outs() << unwrapOrError(Symbol.getName(), O->getFileName());
696       } else {
697         outs() << "?";
698       }
699     }
700     outs() << "\n";
701   }
702 }
703
704 static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
705   for (const auto &Load : O->load_commands()) {
706     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
707       MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
708       for (unsigned J = 0; J < Seg.nsects; ++J) {
709         MachO::section_64 Sec = O->getSection64(Load, J);
710         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
711         if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
712             section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
713             section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
714             section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
715             section_type == MachO::S_SYMBOL_STUBS) {
716           uint32_t stride;
717           if (section_type == MachO::S_SYMBOL_STUBS)
718             stride = Sec.reserved2;
719           else
720             stride = 8;
721           if (stride == 0) {
722             outs() << "Can't print indirect symbols for (" << Sec.segname << ","
723                    << Sec.sectname << ") "
724                    << "(size of stubs in reserved2 field is zero)\n";
725             continue;
726           }
727           uint32_t count = Sec.size / stride;
728           outs() << "Indirect symbols for (" << Sec.segname << ","
729                  << Sec.sectname << ") " << count << " entries";
730           uint32_t n = Sec.reserved1;
731           PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
732         }
733       }
734     } else if (Load.C.cmd == MachO::LC_SEGMENT) {
735       MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
736       for (unsigned J = 0; J < Seg.nsects; ++J) {
737         MachO::section Sec = O->getSection(Load, J);
738         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
739         if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
740             section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
741             section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
742             section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
743             section_type == MachO::S_SYMBOL_STUBS) {
744           uint32_t stride;
745           if (section_type == MachO::S_SYMBOL_STUBS)
746             stride = Sec.reserved2;
747           else
748             stride = 4;
749           if (stride == 0) {
750             outs() << "Can't print indirect symbols for (" << Sec.segname << ","
751                    << Sec.sectname << ") "
752                    << "(size of stubs in reserved2 field is zero)\n";
753             continue;
754           }
755           uint32_t count = Sec.size / stride;
756           outs() << "Indirect symbols for (" << Sec.segname << ","
757                  << Sec.sectname << ") " << count << " entries";
758           uint32_t n = Sec.reserved1;
759           PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
760         }
761       }
762     }
763   }
764 }
765
766 static void PrintRType(const uint64_t cputype, const unsigned r_type) {
767   static char const *generic_r_types[] = {
768     "VANILLA ", "PAIR    ", "SECTDIF ", "PBLAPTR ", "LOCSDIF ", "TLV     ",
769     "  6 (?) ", "  7 (?) ", "  8 (?) ", "  9 (?) ", " 10 (?) ", " 11 (?) ",
770     " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
771   };
772   static char const *x86_64_r_types[] = {
773     "UNSIGND ", "SIGNED  ", "BRANCH  ", "GOT_LD  ", "GOT     ", "SUB     ",
774     "SIGNED1 ", "SIGNED2 ", "SIGNED4 ", "TLV     ", " 10 (?) ", " 11 (?) ",
775     " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
776   };
777   static char const *arm_r_types[] = {
778     "VANILLA ", "PAIR    ", "SECTDIFF", "LOCSDIF ", "PBLAPTR ",
779     "BR24    ", "T_BR22  ", "T_BR32  ", "HALF    ", "HALFDIF ",
780     " 10 (?) ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
781   };
782   static char const *arm64_r_types[] = {
783     "UNSIGND ", "SUB     ", "BR26    ", "PAGE21  ", "PAGOF12 ",
784     "GOTLDP  ", "GOTLDPOF", "PTRTGOT ", "TLVLDP  ", "TLVLDPOF",
785     "ADDEND  ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
786   };
787
788   if (r_type > 0xf){
789     outs() << format("%-7u", r_type) << " ";
790     return;
791   }
792   switch (cputype) {
793     case MachO::CPU_TYPE_I386:
794       outs() << generic_r_types[r_type];
795       break;
796     case MachO::CPU_TYPE_X86_64:
797       outs() << x86_64_r_types[r_type];
798       break;
799     case MachO::CPU_TYPE_ARM:
800       outs() << arm_r_types[r_type];
801       break;
802     case MachO::CPU_TYPE_ARM64:
803     case MachO::CPU_TYPE_ARM64_32:
804       outs() << arm64_r_types[r_type];
805       break;
806     default:
807       outs() << format("%-7u ", r_type);
808   }
809 }
810
811 static void PrintRLength(const uint64_t cputype, const unsigned r_type,
812                          const unsigned r_length, const bool previous_arm_half){
813   if (cputype == MachO::CPU_TYPE_ARM &&
814       (r_type == MachO::ARM_RELOC_HALF ||
815        r_type == MachO::ARM_RELOC_HALF_SECTDIFF || previous_arm_half == true)) {
816     if ((r_length & 0x1) == 0)
817       outs() << "lo/";
818     else
819       outs() << "hi/";
820     if ((r_length & 0x1) == 0)
821       outs() << "arm ";
822     else
823       outs() << "thm ";
824   } else {
825     switch (r_length) {
826       case 0:
827         outs() << "byte   ";
828         break;
829       case 1:
830         outs() << "word   ";
831         break;
832       case 2:
833         outs() << "long   ";
834         break;
835       case 3:
836         if (cputype == MachO::CPU_TYPE_X86_64)
837           outs() << "quad   ";
838         else
839           outs() << format("?(%2d)  ", r_length);
840         break;
841       default:
842         outs() << format("?(%2d)  ", r_length);
843     }
844   }
845 }
846
847 static void PrintRelocationEntries(const MachOObjectFile *O,
848                                    const relocation_iterator Begin,
849                                    const relocation_iterator End,
850                                    const uint64_t cputype,
851                                    const bool verbose) {
852   const MachO::symtab_command Symtab = O->getSymtabLoadCommand();
853   bool previous_arm_half = false;
854   bool previous_sectdiff = false;
855   uint32_t sectdiff_r_type = 0;
856
857   for (relocation_iterator Reloc = Begin; Reloc != End; ++Reloc) {
858     const DataRefImpl Rel = Reloc->getRawDataRefImpl();
859     const MachO::any_relocation_info RE = O->getRelocation(Rel);
860     const unsigned r_type = O->getAnyRelocationType(RE);
861     const bool r_scattered = O->isRelocationScattered(RE);
862     const unsigned r_pcrel = O->getAnyRelocationPCRel(RE);
863     const unsigned r_length = O->getAnyRelocationLength(RE);
864     const unsigned r_address = O->getAnyRelocationAddress(RE);
865     const bool r_extern = (r_scattered ? false :
866                            O->getPlainRelocationExternal(RE));
867     const uint32_t r_value = (r_scattered ?
868                               O->getScatteredRelocationValue(RE) : 0);
869     const unsigned r_symbolnum = (r_scattered ? 0 :
870                                   O->getPlainRelocationSymbolNum(RE));
871
872     if (r_scattered && cputype != MachO::CPU_TYPE_X86_64) {
873       if (verbose) {
874         // scattered: address
875         if ((cputype == MachO::CPU_TYPE_I386 &&
876              r_type == MachO::GENERIC_RELOC_PAIR) ||
877             (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR))
878           outs() << "         ";
879         else
880           outs() << format("%08x ", (unsigned int)r_address);
881
882         // scattered: pcrel
883         if (r_pcrel)
884           outs() << "True  ";
885         else
886           outs() << "False ";
887
888         // scattered: length
889         PrintRLength(cputype, r_type, r_length, previous_arm_half);
890
891         // scattered: extern & type
892         outs() << "n/a    ";
893         PrintRType(cputype, r_type);
894
895         // scattered: scattered & value
896         outs() << format("True      0x%08x", (unsigned int)r_value);
897         if (previous_sectdiff == false) {
898           if ((cputype == MachO::CPU_TYPE_ARM &&
899                r_type == MachO::ARM_RELOC_PAIR))
900             outs() << format(" half = 0x%04x ", (unsigned int)r_address);
901         } else if (cputype == MachO::CPU_TYPE_ARM &&
902                    sectdiff_r_type == MachO::ARM_RELOC_HALF_SECTDIFF)
903           outs() << format(" other_half = 0x%04x ", (unsigned int)r_address);
904         if ((cputype == MachO::CPU_TYPE_I386 &&
905              (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
906               r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) ||
907             (cputype == MachO::CPU_TYPE_ARM &&
908              (sectdiff_r_type == MachO::ARM_RELOC_SECTDIFF ||
909               sectdiff_r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
910               sectdiff_r_type == MachO::ARM_RELOC_HALF_SECTDIFF))) {
911           previous_sectdiff = true;
912           sectdiff_r_type = r_type;
913         } else {
914           previous_sectdiff = false;
915           sectdiff_r_type = 0;
916         }
917         if (cputype == MachO::CPU_TYPE_ARM &&
918             (r_type == MachO::ARM_RELOC_HALF ||
919              r_type == MachO::ARM_RELOC_HALF_SECTDIFF))
920           previous_arm_half = true;
921         else
922           previous_arm_half = false;
923         outs() << "\n";
924       }
925       else {
926         // scattered: address pcrel length extern type scattered value
927         outs() << format("%08x %1d     %-2d     n/a    %-7d 1         0x%08x\n",
928                          (unsigned int)r_address, r_pcrel, r_length, r_type,
929                          (unsigned int)r_value);
930       }
931     }
932     else {
933       if (verbose) {
934         // plain: address
935         if (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR)
936           outs() << "         ";
937         else
938           outs() << format("%08x ", (unsigned int)r_address);
939
940         // plain: pcrel
941         if (r_pcrel)
942           outs() << "True  ";
943         else
944           outs() << "False ";
945
946         // plain: length
947         PrintRLength(cputype, r_type, r_length, previous_arm_half);
948
949         if (r_extern) {
950           // plain: extern & type & scattered
951           outs() << "True   ";
952           PrintRType(cputype, r_type);
953           outs() << "False     ";
954
955           // plain: symbolnum/value
956           if (r_symbolnum > Symtab.nsyms)
957             outs() << format("?(%d)\n", r_symbolnum);
958           else {
959             SymbolRef Symbol = *O->getSymbolByIndex(r_symbolnum);
960             Expected<StringRef> SymNameNext = Symbol.getName();
961             const char *name = NULL;
962             if (SymNameNext)
963               name = SymNameNext->data();
964             if (name == NULL)
965               outs() << format("?(%d)\n", r_symbolnum);
966             else
967               outs() << name << "\n";
968           }
969         }
970         else {
971           // plain: extern & type & scattered
972           outs() << "False  ";
973           PrintRType(cputype, r_type);
974           outs() << "False     ";
975
976           // plain: symbolnum/value
977           if (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR)
978             outs() << format("other_half = 0x%04x\n", (unsigned int)r_address);
979           else if ((cputype == MachO::CPU_TYPE_ARM64 ||
980                     cputype == MachO::CPU_TYPE_ARM64_32) &&
981                    r_type == MachO::ARM64_RELOC_ADDEND)
982             outs() << format("addend = 0x%06x\n", (unsigned int)r_symbolnum);
983           else {
984             outs() << format("%d ", r_symbolnum);
985             if (r_symbolnum == MachO::R_ABS)
986               outs() << "R_ABS\n";
987             else {
988               // in this case, r_symbolnum is actually a 1-based section number
989               uint32_t nsects = O->section_end()->getRawDataRefImpl().d.a;
990               if (r_symbolnum > 0 && r_symbolnum <= nsects) {
991                 object::DataRefImpl DRI;
992                 DRI.d.a = r_symbolnum-1;
993                 StringRef SegName = O->getSectionFinalSegmentName(DRI);
994                 if (Expected<StringRef> NameOrErr = O->getSectionName(DRI))
995                   outs() << "(" << SegName << "," << *NameOrErr << ")\n";
996                 else
997                   outs() << "(?,?)\n";
998               }
999               else {
1000                 outs() << "(?,?)\n";
1001               }
1002             }
1003           }
1004         }
1005         if (cputype == MachO::CPU_TYPE_ARM &&
1006             (r_type == MachO::ARM_RELOC_HALF ||
1007              r_type == MachO::ARM_RELOC_HALF_SECTDIFF))
1008           previous_arm_half = true;
1009         else
1010           previous_arm_half = false;
1011       }
1012       else {
1013         // plain: address pcrel length extern type scattered symbolnum/section
1014         outs() << format("%08x %1d     %-2d     %1d      %-7d 0         %d\n",
1015                          (unsigned int)r_address, r_pcrel, r_length, r_extern,
1016                          r_type, r_symbolnum);
1017       }
1018     }
1019   }
1020 }
1021
1022 static void PrintRelocations(const MachOObjectFile *O, const bool verbose) {
1023   const uint64_t cputype = O->getHeader().cputype;
1024   const MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
1025   if (Dysymtab.nextrel != 0) {
1026     outs() << "External relocation information " << Dysymtab.nextrel
1027            << " entries";
1028     outs() << "\naddress  pcrel length extern type    scattered "
1029               "symbolnum/value\n";
1030     PrintRelocationEntries(O, O->extrel_begin(), O->extrel_end(), cputype,
1031                            verbose);
1032   }
1033   if (Dysymtab.nlocrel != 0) {
1034     outs() << format("Local relocation information %u entries",
1035                      Dysymtab.nlocrel);
1036     outs() << "\naddress  pcrel length extern type    scattered "
1037               "symbolnum/value\n";
1038     PrintRelocationEntries(O, O->locrel_begin(), O->locrel_end(), cputype,
1039                            verbose);
1040   }
1041   for (const auto &Load : O->load_commands()) {
1042     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
1043       const MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
1044       for (unsigned J = 0; J < Seg.nsects; ++J) {
1045         const MachO::section_64 Sec = O->getSection64(Load, J);
1046         if (Sec.nreloc != 0) {
1047           DataRefImpl DRI;
1048           DRI.d.a = J;
1049           const StringRef SegName = O->getSectionFinalSegmentName(DRI);
1050           if (Expected<StringRef> NameOrErr = O->getSectionName(DRI))
1051             outs() << "Relocation information (" << SegName << "," << *NameOrErr
1052                    << format(") %u entries", Sec.nreloc);
1053           else
1054             outs() << "Relocation information (" << SegName << ",?) "
1055                    << format("%u entries", Sec.nreloc);
1056           outs() << "\naddress  pcrel length extern type    scattered "
1057                     "symbolnum/value\n";
1058           PrintRelocationEntries(O, O->section_rel_begin(DRI),
1059                                  O->section_rel_end(DRI), cputype, verbose);
1060         }
1061       }
1062     } else if (Load.C.cmd == MachO::LC_SEGMENT) {
1063       const MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
1064       for (unsigned J = 0; J < Seg.nsects; ++J) {
1065         const MachO::section Sec = O->getSection(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     }
1083   }
1084 }
1085
1086 static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
1087   MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
1088   uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
1089   outs() << "Data in code table (" << nentries << " entries)\n";
1090   outs() << "offset     length kind\n";
1091   for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
1092        ++DI) {
1093     uint32_t Offset;
1094     DI->getOffset(Offset);
1095     outs() << format("0x%08" PRIx32, Offset) << " ";
1096     uint16_t Length;
1097     DI->getLength(Length);
1098     outs() << format("%6u", Length) << " ";
1099     uint16_t Kind;
1100     DI->getKind(Kind);
1101     if (verbose) {
1102       switch (Kind) {
1103       case MachO::DICE_KIND_DATA:
1104         outs() << "DATA";
1105         break;
1106       case MachO::DICE_KIND_JUMP_TABLE8:
1107         outs() << "JUMP_TABLE8";
1108         break;
1109       case MachO::DICE_KIND_JUMP_TABLE16:
1110         outs() << "JUMP_TABLE16";
1111         break;
1112       case MachO::DICE_KIND_JUMP_TABLE32:
1113         outs() << "JUMP_TABLE32";
1114         break;
1115       case MachO::DICE_KIND_ABS_JUMP_TABLE32:
1116         outs() << "ABS_JUMP_TABLE32";
1117         break;
1118       default:
1119         outs() << format("0x%04" PRIx32, Kind);
1120         break;
1121       }
1122     } else
1123       outs() << format("0x%04" PRIx32, Kind);
1124     outs() << "\n";
1125   }
1126 }
1127
1128 static void PrintLinkOptHints(MachOObjectFile *O) {
1129   MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
1130   const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
1131   uint32_t nloh = LohLC.datasize;
1132   outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
1133   for (uint32_t i = 0; i < nloh;) {
1134     unsigned n;
1135     uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
1136     i += n;
1137     outs() << "    identifier " << identifier << " ";
1138     if (i >= nloh)
1139       return;
1140     switch (identifier) {
1141     case 1:
1142       outs() << "AdrpAdrp\n";
1143       break;
1144     case 2:
1145       outs() << "AdrpLdr\n";
1146       break;
1147     case 3:
1148       outs() << "AdrpAddLdr\n";
1149       break;
1150     case 4:
1151       outs() << "AdrpLdrGotLdr\n";
1152       break;
1153     case 5:
1154       outs() << "AdrpAddStr\n";
1155       break;
1156     case 6:
1157       outs() << "AdrpLdrGotStr\n";
1158       break;
1159     case 7:
1160       outs() << "AdrpAdd\n";
1161       break;
1162     case 8:
1163       outs() << "AdrpLdrGot\n";
1164       break;
1165     default:
1166       outs() << "Unknown identifier value\n";
1167       break;
1168     }
1169     uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
1170     i += n;
1171     outs() << "    narguments " << narguments << "\n";
1172     if (i >= nloh)
1173       return;
1174
1175     for (uint32_t j = 0; j < narguments; j++) {
1176       uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
1177       i += n;
1178       outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
1179       if (i >= nloh)
1180         return;
1181     }
1182   }
1183 }
1184
1185 static void PrintDylibs(MachOObjectFile *O, bool JustId) {
1186   unsigned Index = 0;
1187   for (const auto &Load : O->load_commands()) {
1188     if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
1189         (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
1190                      Load.C.cmd == MachO::LC_LOAD_DYLIB ||
1191                      Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
1192                      Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
1193                      Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
1194                      Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
1195       MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
1196       if (dl.dylib.name < dl.cmdsize) {
1197         const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
1198         if (JustId)
1199           outs() << p << "\n";
1200         else {
1201           outs() << "\t" << p;
1202           outs() << " (compatibility version "
1203                  << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
1204                  << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
1205                  << (dl.dylib.compatibility_version & 0xff) << ",";
1206           outs() << " current version "
1207                  << ((dl.dylib.current_version >> 16) & 0xffff) << "."
1208                  << ((dl.dylib.current_version >> 8) & 0xff) << "."
1209                  << (dl.dylib.current_version & 0xff);
1210           if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
1211             outs() << ", weak";
1212           if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
1213             outs() << ", reexport";
1214           if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
1215             outs() << ", upward";
1216           if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
1217             outs() << ", lazy";
1218           outs() << ")\n";
1219         }
1220       } else {
1221         outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
1222         if (Load.C.cmd == MachO::LC_ID_DYLIB)
1223           outs() << "LC_ID_DYLIB ";
1224         else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
1225           outs() << "LC_LOAD_DYLIB ";
1226         else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
1227           outs() << "LC_LOAD_WEAK_DYLIB ";
1228         else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
1229           outs() << "LC_LAZY_LOAD_DYLIB ";
1230         else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
1231           outs() << "LC_REEXPORT_DYLIB ";
1232         else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
1233           outs() << "LC_LOAD_UPWARD_DYLIB ";
1234         else
1235           outs() << "LC_??? ";
1236         outs() << "command " << Index++ << "\n";
1237       }
1238     }
1239   }
1240 }
1241
1242 typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
1243
1244 static void CreateSymbolAddressMap(MachOObjectFile *O,
1245                                    SymbolAddressMap *AddrMap) {
1246   // Create a map of symbol addresses to symbol names.
1247   const StringRef FileName = O->getFileName();
1248   for (const SymbolRef &Symbol : O->symbols()) {
1249     SymbolRef::Type ST = unwrapOrError(Symbol.getType(), FileName);
1250     if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
1251         ST == SymbolRef::ST_Other) {
1252       uint64_t Address = Symbol.getValue();
1253       StringRef SymName = unwrapOrError(Symbol.getName(), FileName);
1254       if (!SymName.startswith(".objc"))
1255         (*AddrMap)[Address] = SymName;
1256     }
1257   }
1258 }
1259
1260 // GuessSymbolName is passed the address of what might be a symbol and a
1261 // pointer to the SymbolAddressMap.  It returns the name of a symbol
1262 // with that address or nullptr if no symbol is found with that address.
1263 static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
1264   const char *SymbolName = nullptr;
1265   // A DenseMap can't lookup up some values.
1266   if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
1267     StringRef name = AddrMap->lookup(value);
1268     if (!name.empty())
1269       SymbolName = name.data();
1270   }
1271   return SymbolName;
1272 }
1273
1274 static void DumpCstringChar(const char c) {
1275   char p[2];
1276   p[0] = c;
1277   p[1] = '\0';
1278   outs().write_escaped(p);
1279 }
1280
1281 static void DumpCstringSection(MachOObjectFile *O, const char *sect,
1282                                uint32_t sect_size, uint64_t sect_addr,
1283                                bool print_addresses) {
1284   for (uint32_t i = 0; i < sect_size; i++) {
1285     if (print_addresses) {
1286       if (O->is64Bit())
1287         outs() << format("%016" PRIx64, sect_addr + i) << "  ";
1288       else
1289         outs() << format("%08" PRIx64, sect_addr + i) << "  ";
1290     }
1291     for (; i < sect_size && sect[i] != '\0'; i++)
1292       DumpCstringChar(sect[i]);
1293     if (i < sect_size && sect[i] == '\0')
1294       outs() << "\n";
1295   }
1296 }
1297
1298 static void DumpLiteral4(uint32_t l, float f) {
1299   outs() << format("0x%08" PRIx32, l);
1300   if ((l & 0x7f800000) != 0x7f800000)
1301     outs() << format(" (%.16e)\n", f);
1302   else {
1303     if (l == 0x7f800000)
1304       outs() << " (+Infinity)\n";
1305     else if (l == 0xff800000)
1306       outs() << " (-Infinity)\n";
1307     else if ((l & 0x00400000) == 0x00400000)
1308       outs() << " (non-signaling Not-a-Number)\n";
1309     else
1310       outs() << " (signaling Not-a-Number)\n";
1311   }
1312 }
1313
1314 static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
1315                                 uint32_t sect_size, uint64_t sect_addr,
1316                                 bool print_addresses) {
1317   for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
1318     if (print_addresses) {
1319       if (O->is64Bit())
1320         outs() << format("%016" PRIx64, sect_addr + i) << "  ";
1321       else
1322         outs() << format("%08" PRIx64, sect_addr + i) << "  ";
1323     }
1324     float f;
1325     memcpy(&f, sect + i, sizeof(float));
1326     if (O->isLittleEndian() != sys::IsLittleEndianHost)
1327       sys::swapByteOrder(f);
1328     uint32_t l;
1329     memcpy(&l, sect + i, sizeof(uint32_t));
1330     if (O->isLittleEndian() != sys::IsLittleEndianHost)
1331       sys::swapByteOrder(l);
1332     DumpLiteral4(l, f);
1333   }
1334 }
1335
1336 static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
1337                          double d) {
1338   outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
1339   uint32_t Hi, Lo;
1340   Hi = (O->isLittleEndian()) ? l1 : l0;
1341   Lo = (O->isLittleEndian()) ? l0 : l1;
1342
1343   // Hi is the high word, so this is equivalent to if(isfinite(d))
1344   if ((Hi & 0x7ff00000) != 0x7ff00000)
1345     outs() << format(" (%.16e)\n", d);
1346   else {
1347     if (Hi == 0x7ff00000 && Lo == 0)
1348       outs() << " (+Infinity)\n";
1349     else if (Hi == 0xfff00000 && Lo == 0)
1350       outs() << " (-Infinity)\n";
1351     else if ((Hi & 0x00080000) == 0x00080000)
1352       outs() << " (non-signaling Not-a-Number)\n";
1353     else
1354       outs() << " (signaling Not-a-Number)\n";
1355   }
1356 }
1357
1358 static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
1359                                 uint32_t sect_size, uint64_t sect_addr,
1360                                 bool print_addresses) {
1361   for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
1362     if (print_addresses) {
1363       if (O->is64Bit())
1364         outs() << format("%016" PRIx64, sect_addr + i) << "  ";
1365       else
1366         outs() << format("%08" PRIx64, sect_addr + i) << "  ";
1367     }
1368     double d;
1369     memcpy(&d, sect + i, sizeof(double));
1370     if (O->isLittleEndian() != sys::IsLittleEndianHost)
1371       sys::swapByteOrder(d);
1372     uint32_t l0, l1;
1373     memcpy(&l0, sect + i, sizeof(uint32_t));
1374     memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
1375     if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1376       sys::swapByteOrder(l0);
1377       sys::swapByteOrder(l1);
1378     }
1379     DumpLiteral8(O, l0, l1, d);
1380   }
1381 }
1382
1383 static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
1384   outs() << format("0x%08" PRIx32, l0) << " ";
1385   outs() << format("0x%08" PRIx32, l1) << " ";
1386   outs() << format("0x%08" PRIx32, l2) << " ";
1387   outs() << format("0x%08" PRIx32, l3) << "\n";
1388 }
1389
1390 static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
1391                                  uint32_t sect_size, uint64_t sect_addr,
1392                                  bool print_addresses) {
1393   for (uint32_t i = 0; i < sect_size; i += 16) {
1394     if (print_addresses) {
1395       if (O->is64Bit())
1396         outs() << format("%016" PRIx64, sect_addr + i) << "  ";
1397       else
1398         outs() << format("%08" PRIx64, sect_addr + i) << "  ";
1399     }
1400     uint32_t l0, l1, l2, l3;
1401     memcpy(&l0, sect + i, sizeof(uint32_t));
1402     memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
1403     memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
1404     memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
1405     if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1406       sys::swapByteOrder(l0);
1407       sys::swapByteOrder(l1);
1408       sys::swapByteOrder(l2);
1409       sys::swapByteOrder(l3);
1410     }
1411     DumpLiteral16(l0, l1, l2, l3);
1412   }
1413 }
1414
1415 static void DumpLiteralPointerSection(MachOObjectFile *O,
1416                                       const SectionRef &Section,
1417                                       const char *sect, uint32_t sect_size,
1418                                       uint64_t sect_addr,
1419                                       bool print_addresses) {
1420   // Collect the literal sections in this Mach-O file.
1421   std::vector<SectionRef> LiteralSections;
1422   for (const SectionRef &Section : O->sections()) {
1423     DataRefImpl Ref = Section.getRawDataRefImpl();
1424     uint32_t section_type;
1425     if (O->is64Bit()) {
1426       const MachO::section_64 Sec = O->getSection64(Ref);
1427       section_type = Sec.flags & MachO::SECTION_TYPE;
1428     } else {
1429       const MachO::section Sec = O->getSection(Ref);
1430       section_type = Sec.flags & MachO::SECTION_TYPE;
1431     }
1432     if (section_type == MachO::S_CSTRING_LITERALS ||
1433         section_type == MachO::S_4BYTE_LITERALS ||
1434         section_type == MachO::S_8BYTE_LITERALS ||
1435         section_type == MachO::S_16BYTE_LITERALS)
1436       LiteralSections.push_back(Section);
1437   }
1438
1439   // Set the size of the literal pointer.
1440   uint32_t lp_size = O->is64Bit() ? 8 : 4;
1441
1442   // Collect the external relocation symbols for the literal pointers.
1443   std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1444   for (const RelocationRef &Reloc : Section.relocations()) {
1445     DataRefImpl Rel;
1446     MachO::any_relocation_info RE;
1447     bool isExtern = false;
1448     Rel = Reloc.getRawDataRefImpl();
1449     RE = O->getRelocation(Rel);
1450     isExtern = O->getPlainRelocationExternal(RE);
1451     if (isExtern) {
1452       uint64_t RelocOffset = Reloc.getOffset();
1453       symbol_iterator RelocSym = Reloc.getSymbol();
1454       Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
1455     }
1456   }
1457   array_pod_sort(Relocs.begin(), Relocs.end());
1458
1459   // Dump each literal pointer.
1460   for (uint32_t i = 0; i < sect_size; i += lp_size) {
1461     if (print_addresses) {
1462       if (O->is64Bit())
1463         outs() << format("%016" PRIx64, sect_addr + i) << "  ";
1464       else
1465         outs() << format("%08" PRIx64, sect_addr + i) << "  ";
1466     }
1467     uint64_t lp;
1468     if (O->is64Bit()) {
1469       memcpy(&lp, sect + i, sizeof(uint64_t));
1470       if (O->isLittleEndian() != sys::IsLittleEndianHost)
1471         sys::swapByteOrder(lp);
1472     } else {
1473       uint32_t li;
1474       memcpy(&li, sect + i, sizeof(uint32_t));
1475       if (O->isLittleEndian() != sys::IsLittleEndianHost)
1476         sys::swapByteOrder(li);
1477       lp = li;
1478     }
1479
1480     // First look for an external relocation entry for this literal pointer.
1481     auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
1482       return P.first == i;
1483     });
1484     if (Reloc != Relocs.end()) {
1485       symbol_iterator RelocSym = Reloc->second;
1486       StringRef SymName = unwrapOrError(RelocSym->getName(), O->getFileName());
1487       outs() << "external relocation entry for symbol:" << SymName << "\n";
1488       continue;
1489     }
1490
1491     // For local references see what the section the literal pointer points to.
1492     auto Sect = find_if(LiteralSections, [&](const SectionRef &R) {
1493       return lp >= R.getAddress() && lp < R.getAddress() + R.getSize();
1494     });
1495     if (Sect == LiteralSections.end()) {
1496       outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
1497       continue;
1498     }
1499
1500     uint64_t SectAddress = Sect->getAddress();
1501     uint64_t SectSize = Sect->getSize();
1502
1503     StringRef SectName;
1504     Sect->getName(SectName);
1505     DataRefImpl Ref = Sect->getRawDataRefImpl();
1506     StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
1507     outs() << SegmentName << ":" << SectName << ":";
1508
1509     uint32_t section_type;
1510     if (O->is64Bit()) {
1511       const MachO::section_64 Sec = O->getSection64(Ref);
1512       section_type = Sec.flags & MachO::SECTION_TYPE;
1513     } else {
1514       const MachO::section Sec = O->getSection(Ref);
1515       section_type = Sec.flags & MachO::SECTION_TYPE;
1516     }
1517
1518     StringRef BytesStr = unwrapOrError(Sect->getContents(), O->getFileName());
1519
1520     const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
1521
1522     switch (section_type) {
1523     case MachO::S_CSTRING_LITERALS:
1524       for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
1525            i++) {
1526         DumpCstringChar(Contents[i]);
1527       }
1528       outs() << "\n";
1529       break;
1530     case MachO::S_4BYTE_LITERALS:
1531       float f;
1532       memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
1533       uint32_t l;
1534       memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
1535       if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1536         sys::swapByteOrder(f);
1537         sys::swapByteOrder(l);
1538       }
1539       DumpLiteral4(l, f);
1540       break;
1541     case MachO::S_8BYTE_LITERALS: {
1542       double d;
1543       memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
1544       uint32_t l0, l1;
1545       memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
1546       memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
1547              sizeof(uint32_t));
1548       if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1549         sys::swapByteOrder(f);
1550         sys::swapByteOrder(l0);
1551         sys::swapByteOrder(l1);
1552       }
1553       DumpLiteral8(O, l0, l1, d);
1554       break;
1555     }
1556     case MachO::S_16BYTE_LITERALS: {
1557       uint32_t l0, l1, l2, l3;
1558       memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
1559       memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
1560              sizeof(uint32_t));
1561       memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
1562              sizeof(uint32_t));
1563       memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
1564              sizeof(uint32_t));
1565       if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1566         sys::swapByteOrder(l0);
1567         sys::swapByteOrder(l1);
1568         sys::swapByteOrder(l2);
1569         sys::swapByteOrder(l3);
1570       }
1571       DumpLiteral16(l0, l1, l2, l3);
1572       break;
1573     }
1574     }
1575   }
1576 }
1577
1578 static void DumpInitTermPointerSection(MachOObjectFile *O,
1579                                        const SectionRef &Section,
1580                                        const char *sect,
1581                                        uint32_t sect_size, uint64_t sect_addr,
1582                                        SymbolAddressMap *AddrMap,
1583                                        bool verbose) {
1584   uint32_t stride;
1585   stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t);
1586
1587   // Collect the external relocation symbols for the pointers.
1588   std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1589   for (const RelocationRef &Reloc : Section.relocations()) {
1590     DataRefImpl Rel;
1591     MachO::any_relocation_info RE;
1592     bool isExtern = false;
1593     Rel = Reloc.getRawDataRefImpl();
1594     RE = O->getRelocation(Rel);
1595     isExtern = O->getPlainRelocationExternal(RE);
1596     if (isExtern) {
1597       uint64_t RelocOffset = Reloc.getOffset();
1598       symbol_iterator RelocSym = Reloc.getSymbol();
1599       Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
1600     }
1601   }
1602   array_pod_sort(Relocs.begin(), Relocs.end());
1603
1604   for (uint32_t i = 0; i < sect_size; i += stride) {
1605     const char *SymbolName = nullptr;
1606     uint64_t p;
1607     if (O->is64Bit()) {
1608       outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
1609       uint64_t pointer_value;
1610       memcpy(&pointer_value, sect + i, stride);
1611       if (O->isLittleEndian() != sys::IsLittleEndianHost)
1612         sys::swapByteOrder(pointer_value);
1613       outs() << format("0x%016" PRIx64, pointer_value);
1614       p = pointer_value;
1615     } else {
1616       outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
1617       uint32_t pointer_value;
1618       memcpy(&pointer_value, sect + i, stride);
1619       if (O->isLittleEndian() != sys::IsLittleEndianHost)
1620         sys::swapByteOrder(pointer_value);
1621       outs() << format("0x%08" PRIx32, pointer_value);
1622       p = pointer_value;
1623     }
1624     if (verbose) {
1625       // First look for an external relocation entry for this pointer.
1626       auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
1627         return P.first == i;
1628       });
1629       if (Reloc != Relocs.end()) {
1630         symbol_iterator RelocSym = Reloc->second;
1631         outs() << " " << unwrapOrError(RelocSym->getName(), O->getFileName());
1632       } else {
1633         SymbolName = GuessSymbolName(p, AddrMap);
1634         if (SymbolName)
1635           outs() << " " << SymbolName;
1636       }
1637     }
1638     outs() << "\n";
1639   }
1640 }
1641
1642 static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
1643                                    uint32_t size, uint64_t addr) {
1644   uint32_t cputype = O->getHeader().cputype;
1645   if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
1646     uint32_t j;
1647     for (uint32_t i = 0; i < size; i += j, addr += j) {
1648       if (O->is64Bit())
1649         outs() << format("%016" PRIx64, addr) << "\t";
1650       else
1651         outs() << format("%08" PRIx64, addr) << "\t";
1652       for (j = 0; j < 16 && i + j < size; j++) {
1653         uint8_t byte_word = *(sect + i + j);
1654         outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1655       }
1656       outs() << "\n";
1657     }
1658   } else {
1659     uint32_t j;
1660     for (uint32_t i = 0; i < size; i += j, addr += j) {
1661       if (O->is64Bit())
1662         outs() << format("%016" PRIx64, addr) << "\t";
1663       else
1664         outs() << format("%08" PRIx64, addr) << "\t";
1665       for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
1666            j += sizeof(int32_t)) {
1667         if (i + j + sizeof(int32_t) <= size) {
1668           uint32_t long_word;
1669           memcpy(&long_word, sect + i + j, sizeof(int32_t));
1670           if (O->isLittleEndian() != sys::IsLittleEndianHost)
1671             sys::swapByteOrder(long_word);
1672           outs() << format("%08" PRIx32, long_word) << " ";
1673         } else {
1674           for (uint32_t k = 0; i + j + k < size; k++) {
1675             uint8_t byte_word = *(sect + i + j + k);
1676             outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1677           }
1678         }
1679       }
1680       outs() << "\n";
1681     }
1682   }
1683 }
1684
1685 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
1686                              StringRef DisSegName, StringRef DisSectName);
1687 static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
1688                                 uint32_t size, uint32_t addr);
1689 #ifdef HAVE_LIBXAR
1690 static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
1691                                 uint32_t size, bool verbose,
1692                                 bool PrintXarHeader, bool PrintXarFileHeaders,
1693                                 std::string XarMemberName);
1694 #endif // defined(HAVE_LIBXAR)
1695
1696 static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
1697                                 bool verbose) {
1698   SymbolAddressMap AddrMap;
1699   if (verbose)
1700     CreateSymbolAddressMap(O, &AddrMap);
1701
1702   for (unsigned i = 0; i < FilterSections.size(); ++i) {
1703     StringRef DumpSection = FilterSections[i];
1704     std::pair<StringRef, StringRef> DumpSegSectName;
1705     DumpSegSectName = DumpSection.split(',');
1706     StringRef DumpSegName, DumpSectName;
1707     if (!DumpSegSectName.second.empty()) {
1708       DumpSegName = DumpSegSectName.first;
1709       DumpSectName = DumpSegSectName.second;
1710     } else {
1711       DumpSegName = "";
1712       DumpSectName = DumpSegSectName.first;
1713     }
1714     for (const SectionRef &Section : O->sections()) {
1715       StringRef SectName;
1716       Section.getName(SectName);
1717       DataRefImpl Ref = Section.getRawDataRefImpl();
1718       StringRef SegName = O->getSectionFinalSegmentName(Ref);
1719       if ((DumpSegName.empty() || SegName == DumpSegName) &&
1720           (SectName == DumpSectName)) {
1721
1722         uint32_t section_flags;
1723         if (O->is64Bit()) {
1724           const MachO::section_64 Sec = O->getSection64(Ref);
1725           section_flags = Sec.flags;
1726
1727         } else {
1728           const MachO::section Sec = O->getSection(Ref);
1729           section_flags = Sec.flags;
1730         }
1731         uint32_t section_type = section_flags & MachO::SECTION_TYPE;
1732
1733         StringRef BytesStr =
1734             unwrapOrError(Section.getContents(), O->getFileName());
1735         const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1736         uint32_t sect_size = BytesStr.size();
1737         uint64_t sect_addr = Section.getAddress();
1738
1739         outs() << "Contents of (" << SegName << "," << SectName
1740                << ") section\n";
1741
1742         if (verbose) {
1743           if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1744               (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1745             DisassembleMachO(Filename, O, SegName, SectName);
1746             continue;
1747           }
1748           if (SegName == "__TEXT" && SectName == "__info_plist") {
1749             outs() << sect;
1750             continue;
1751           }
1752           if (SegName == "__OBJC" && SectName == "__protocol") {
1753             DumpProtocolSection(O, sect, sect_size, sect_addr);
1754             continue;
1755           }
1756 #ifdef HAVE_LIBXAR
1757           if (SegName == "__LLVM" && SectName == "__bundle") {
1758             DumpBitcodeSection(O, sect, sect_size, verbose, !NoSymbolicOperands,
1759                                ArchiveHeaders, "");
1760             continue;
1761           }
1762 #endif // defined(HAVE_LIBXAR)
1763           switch (section_type) {
1764           case MachO::S_REGULAR:
1765             DumpRawSectionContents(O, sect, sect_size, sect_addr);
1766             break;
1767           case MachO::S_ZEROFILL:
1768             outs() << "zerofill section and has no contents in the file\n";
1769             break;
1770           case MachO::S_CSTRING_LITERALS:
1771             DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1772             break;
1773           case MachO::S_4BYTE_LITERALS:
1774             DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1775             break;
1776           case MachO::S_8BYTE_LITERALS:
1777             DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1778             break;
1779           case MachO::S_16BYTE_LITERALS:
1780             DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1781             break;
1782           case MachO::S_LITERAL_POINTERS:
1783             DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
1784                                       !NoLeadingAddr);
1785             break;
1786           case MachO::S_MOD_INIT_FUNC_POINTERS:
1787           case MachO::S_MOD_TERM_FUNC_POINTERS:
1788             DumpInitTermPointerSection(O, Section, sect, sect_size, sect_addr,
1789                                        &AddrMap, verbose);
1790             break;
1791           default:
1792             outs() << "Unknown section type ("
1793                    << format("0x%08" PRIx32, section_type) << ")\n";
1794             DumpRawSectionContents(O, sect, sect_size, sect_addr);
1795             break;
1796           }
1797         } else {
1798           if (section_type == MachO::S_ZEROFILL)
1799             outs() << "zerofill section and has no contents in the file\n";
1800           else
1801             DumpRawSectionContents(O, sect, sect_size, sect_addr);
1802         }
1803       }
1804     }
1805   }
1806 }
1807
1808 static void DumpInfoPlistSectionContents(StringRef Filename,
1809                                          MachOObjectFile *O) {
1810   for (const SectionRef &Section : O->sections()) {
1811     StringRef SectName;
1812     Section.getName(SectName);
1813     DataRefImpl Ref = Section.getRawDataRefImpl();
1814     StringRef SegName = O->getSectionFinalSegmentName(Ref);
1815     if (SegName == "__TEXT" && SectName == "__info_plist") {
1816       if (!NoLeadingHeaders)
1817         outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
1818       StringRef BytesStr =
1819           unwrapOrError(Section.getContents(), O->getFileName());
1820       const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1821       outs() << format("%.*s", BytesStr.size(), sect) << "\n";
1822       return;
1823     }
1824   }
1825 }
1826
1827 // checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1828 // and if it is and there is a list of architecture flags is specified then
1829 // check to make sure this Mach-O file is one of those architectures or all
1830 // architectures were specified.  If not then an error is generated and this
1831 // routine returns false.  Else it returns true.
1832 static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
1833   auto *MachO = dyn_cast<MachOObjectFile>(O);
1834
1835   if (!MachO || ArchAll || ArchFlags.empty())
1836     return true;
1837
1838   MachO::mach_header H;
1839   MachO::mach_header_64 H_64;
1840   Triple T;
1841   const char *McpuDefault, *ArchFlag;
1842   if (MachO->is64Bit()) {
1843     H_64 = MachO->MachOObjectFile::getHeader64();
1844     T = MachOObjectFile::getArchTriple(H_64.cputype, H_64.cpusubtype,
1845                                        &McpuDefault, &ArchFlag);
1846   } else {
1847     H = MachO->MachOObjectFile::getHeader();
1848     T = MachOObjectFile::getArchTriple(H.cputype, H.cpusubtype,
1849                                        &McpuDefault, &ArchFlag);
1850   }
1851   const std::string ArchFlagName(ArchFlag);
1852   if (none_of(ArchFlags, [&](const std::string &Name) {
1853         return Name == ArchFlagName;
1854       })) {
1855     WithColor::error(errs(), "llvm-objdump")
1856         << Filename << ": no architecture specified.\n";
1857     return false;
1858   }
1859   return true;
1860 }
1861
1862 static void printObjcMetaData(MachOObjectFile *O, bool verbose);
1863
1864 // ProcessMachO() is passed a single opened Mach-O file, which may be an
1865 // archive member and or in a slice of a universal file.  It prints the
1866 // the file name and header info and then processes it according to the
1867 // command line options.
1868 static void ProcessMachO(StringRef Name, MachOObjectFile *MachOOF,
1869                          StringRef ArchiveMemberName = StringRef(),
1870                          StringRef ArchitectureName = StringRef()) {
1871   // If we are doing some processing here on the Mach-O file print the header
1872   // info.  And don't print it otherwise like in the case of printing the
1873   // UniversalHeaders or ArchiveHeaders.
1874   if (Disassemble || Relocations || PrivateHeaders || ExportsTrie || Rebase ||
1875       Bind || SymbolTable || LazyBind || WeakBind || IndirectSymbols ||
1876       DataInCode || LinkOptHints || DylibsUsed || DylibId || ObjcMetaData ||
1877       (!FilterSections.empty())) {
1878     if (!NoLeadingHeaders) {
1879       outs() << Name;
1880       if (!ArchiveMemberName.empty())
1881         outs() << '(' << ArchiveMemberName << ')';
1882       if (!ArchitectureName.empty())
1883         outs() << " (architecture " << ArchitectureName << ")";
1884       outs() << ":\n";
1885     }
1886   }
1887   // To use the report_error() form with an ArchiveName and FileName set
1888   // these up based on what is passed for Name and ArchiveMemberName.
1889   StringRef ArchiveName;
1890   StringRef FileName;
1891   if (!ArchiveMemberName.empty()) {
1892     ArchiveName = Name;
1893     FileName = ArchiveMemberName;
1894   } else {
1895     ArchiveName = StringRef();
1896     FileName = Name;
1897   }
1898
1899   // If we need the symbol table to do the operation then check it here to
1900   // produce a good error message as to where the Mach-O file comes from in
1901   // the error message.
1902   if (Disassemble || IndirectSymbols || !FilterSections.empty() || UnwindInfo)
1903     if (Error Err = MachOOF->checkSymbolTable())
1904       report_error(std::move(Err), ArchiveName, FileName, ArchitectureName);
1905
1906   if (DisassembleAll) {
1907     for (const SectionRef &Section : MachOOF->sections()) {
1908       StringRef SectName;
1909       Section.getName(SectName);
1910       if (SectName.equals("__text")) {
1911         DataRefImpl Ref = Section.getRawDataRefImpl();
1912         StringRef SegName = MachOOF->getSectionFinalSegmentName(Ref);
1913         DisassembleMachO(FileName, MachOOF, SegName, SectName);
1914       }
1915     }
1916   }
1917   else if (Disassemble) {
1918     if (MachOOF->getHeader().filetype == MachO::MH_KEXT_BUNDLE &&
1919         MachOOF->getHeader().cputype == MachO::CPU_TYPE_ARM64)
1920       DisassembleMachO(FileName, MachOOF, "__TEXT_EXEC", "__text");
1921     else
1922       DisassembleMachO(FileName, MachOOF, "__TEXT", "__text");
1923   }
1924   if (IndirectSymbols)
1925     PrintIndirectSymbols(MachOOF, !NonVerbose);
1926   if (DataInCode)
1927     PrintDataInCodeTable(MachOOF, !NonVerbose);
1928   if (LinkOptHints)
1929     PrintLinkOptHints(MachOOF);
1930   if (Relocations)
1931     PrintRelocations(MachOOF, !NonVerbose);
1932   if (SectionHeaders)
1933     printSectionHeaders(MachOOF);
1934   if (SectionContents)
1935     printSectionContents(MachOOF);
1936   if (!FilterSections.empty())
1937     DumpSectionContents(FileName, MachOOF, !NonVerbose);
1938   if (InfoPlist)
1939     DumpInfoPlistSectionContents(FileName, MachOOF);
1940   if (DylibsUsed)
1941     PrintDylibs(MachOOF, false);
1942   if (DylibId)
1943     PrintDylibs(MachOOF, true);
1944   if (SymbolTable)
1945     printSymbolTable(MachOOF, ArchiveName, ArchitectureName);
1946   if (UnwindInfo)
1947     printMachOUnwindInfo(MachOOF);
1948   if (PrivateHeaders) {
1949     printMachOFileHeader(MachOOF);
1950     printMachOLoadCommands(MachOOF);
1951   }
1952   if (FirstPrivateHeader)
1953     printMachOFileHeader(MachOOF);
1954   if (ObjcMetaData)
1955     printObjcMetaData(MachOOF, !NonVerbose);
1956   if (ExportsTrie)
1957     printExportsTrie(MachOOF);
1958   if (Rebase)
1959     printRebaseTable(MachOOF);
1960   if (Bind)
1961     printBindTable(MachOOF);
1962   if (LazyBind)
1963     printLazyBindTable(MachOOF);
1964   if (WeakBind)
1965     printWeakBindTable(MachOOF);
1966
1967   if (DwarfDumpType != DIDT_Null) {
1968     std::unique_ptr<DIContext> DICtx = DWARFContext::create(*MachOOF);
1969     // Dump the complete DWARF structure.
1970     DIDumpOptions DumpOpts;
1971     DumpOpts.DumpType = DwarfDumpType;
1972     DICtx->dump(outs(), DumpOpts);
1973   }
1974 }
1975
1976 // printUnknownCPUType() helps print_fat_headers for unknown CPU's.
1977 static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
1978   outs() << "    cputype (" << cputype << ")\n";
1979   outs() << "    cpusubtype (" << cpusubtype << ")\n";
1980 }
1981
1982 // printCPUType() helps print_fat_headers by printing the cputype and
1983 // pusubtype (symbolically for the one's it knows about).
1984 static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
1985   switch (cputype) {
1986   case MachO::CPU_TYPE_I386:
1987     switch (cpusubtype) {
1988     case MachO::CPU_SUBTYPE_I386_ALL:
1989       outs() << "    cputype CPU_TYPE_I386\n";
1990       outs() << "    cpusubtype CPU_SUBTYPE_I386_ALL\n";
1991       break;
1992     default:
1993       printUnknownCPUType(cputype, cpusubtype);
1994       break;
1995     }
1996     break;
1997   case MachO::CPU_TYPE_X86_64:
1998     switch (cpusubtype) {
1999     case MachO::CPU_SUBTYPE_X86_64_ALL:
2000       outs() << "    cputype CPU_TYPE_X86_64\n";
2001       outs() << "    cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
2002       break;
2003     case MachO::CPU_SUBTYPE_X86_64_H:
2004       outs() << "    cputype CPU_TYPE_X86_64\n";
2005       outs() << "    cpusubtype CPU_SUBTYPE_X86_64_H\n";
2006       break;
2007     default:
2008       printUnknownCPUType(cputype, cpusubtype);
2009       break;
2010     }
2011     break;
2012   case MachO::CPU_TYPE_ARM:
2013     switch (cpusubtype) {
2014     case MachO::CPU_SUBTYPE_ARM_ALL:
2015       outs() << "    cputype CPU_TYPE_ARM\n";
2016       outs() << "    cpusubtype CPU_SUBTYPE_ARM_ALL\n";
2017       break;
2018     case MachO::CPU_SUBTYPE_ARM_V4T:
2019       outs() << "    cputype CPU_TYPE_ARM\n";
2020       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V4T\n";
2021       break;
2022     case MachO::CPU_SUBTYPE_ARM_V5TEJ:
2023       outs() << "    cputype CPU_TYPE_ARM\n";
2024       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
2025       break;
2026     case MachO::CPU_SUBTYPE_ARM_XSCALE:
2027       outs() << "    cputype CPU_TYPE_ARM\n";
2028       outs() << "    cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
2029       break;
2030     case MachO::CPU_SUBTYPE_ARM_V6:
2031       outs() << "    cputype CPU_TYPE_ARM\n";
2032       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V6\n";
2033       break;
2034     case MachO::CPU_SUBTYPE_ARM_V6M:
2035       outs() << "    cputype CPU_TYPE_ARM\n";
2036       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V6M\n";
2037       break;
2038     case MachO::CPU_SUBTYPE_ARM_V7:
2039       outs() << "    cputype CPU_TYPE_ARM\n";
2040       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V7\n";
2041       break;
2042     case MachO::CPU_SUBTYPE_ARM_V7EM:
2043       outs() << "    cputype CPU_TYPE_ARM\n";
2044       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
2045       break;
2046     case MachO::CPU_SUBTYPE_ARM_V7K:
2047       outs() << "    cputype CPU_TYPE_ARM\n";
2048       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V7K\n";
2049       break;
2050     case MachO::CPU_SUBTYPE_ARM_V7M:
2051       outs() << "    cputype CPU_TYPE_ARM\n";
2052       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V7M\n";
2053       break;
2054     case MachO::CPU_SUBTYPE_ARM_V7S:
2055       outs() << "    cputype CPU_TYPE_ARM\n";
2056       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V7S\n";
2057       break;
2058     default:
2059       printUnknownCPUType(cputype, cpusubtype);
2060       break;
2061     }
2062     break;
2063   case MachO::CPU_TYPE_ARM64:
2064     switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2065     case MachO::CPU_SUBTYPE_ARM64_ALL:
2066       outs() << "    cputype CPU_TYPE_ARM64\n";
2067       outs() << "    cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
2068       break;
2069     case MachO::CPU_SUBTYPE_ARM64E:
2070       outs() << "    cputype CPU_TYPE_ARM64\n";
2071       outs() << "    cpusubtype CPU_SUBTYPE_ARM64E\n";
2072       break;
2073     default:
2074       printUnknownCPUType(cputype, cpusubtype);
2075       break;
2076     }
2077     break;
2078   case MachO::CPU_TYPE_ARM64_32:
2079     switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2080     case MachO::CPU_SUBTYPE_ARM64_32_V8:
2081       outs() << "    cputype CPU_TYPE_ARM64_32\n";
2082       outs() << "    cpusubtype CPU_SUBTYPE_ARM64_32_V8\n";
2083       break;
2084     default:
2085       printUnknownCPUType(cputype, cpusubtype);
2086       break;
2087     }
2088     break;
2089   default:
2090     printUnknownCPUType(cputype, cpusubtype);
2091     break;
2092   }
2093 }
2094
2095 static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
2096                                        bool verbose) {
2097   outs() << "Fat headers\n";
2098   if (verbose) {
2099     if (UB->getMagic() == MachO::FAT_MAGIC)
2100       outs() << "fat_magic FAT_MAGIC\n";
2101     else // UB->getMagic() == MachO::FAT_MAGIC_64
2102       outs() << "fat_magic FAT_MAGIC_64\n";
2103   } else
2104     outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
2105
2106   uint32_t nfat_arch = UB->getNumberOfObjects();
2107   StringRef Buf = UB->getData();
2108   uint64_t size = Buf.size();
2109   uint64_t big_size = sizeof(struct MachO::fat_header) +
2110                       nfat_arch * sizeof(struct MachO::fat_arch);
2111   outs() << "nfat_arch " << UB->getNumberOfObjects();
2112   if (nfat_arch == 0)
2113     outs() << " (malformed, contains zero architecture types)\n";
2114   else if (big_size > size)
2115     outs() << " (malformed, architectures past end of file)\n";
2116   else
2117     outs() << "\n";
2118
2119   for (uint32_t i = 0; i < nfat_arch; ++i) {
2120     MachOUniversalBinary::ObjectForArch OFA(UB, i);
2121     uint32_t cputype = OFA.getCPUType();
2122     uint32_t cpusubtype = OFA.getCPUSubType();
2123     outs() << "architecture ";
2124     for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
2125       MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
2126       uint32_t other_cputype = other_OFA.getCPUType();
2127       uint32_t other_cpusubtype = other_OFA.getCPUSubType();
2128       if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
2129           (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
2130               (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
2131         outs() << "(illegal duplicate architecture) ";
2132         break;
2133       }
2134     }
2135     if (verbose) {
2136       outs() << OFA.getArchFlagName() << "\n";
2137       printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2138     } else {
2139       outs() << i << "\n";
2140       outs() << "    cputype " << cputype << "\n";
2141       outs() << "    cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
2142              << "\n";
2143     }
2144     if (verbose &&
2145         (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
2146       outs() << "    capabilities CPU_SUBTYPE_LIB64\n";
2147     else
2148       outs() << "    capabilities "
2149              << format("0x%" PRIx32,
2150                        (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
2151     outs() << "    offset " << OFA.getOffset();
2152     if (OFA.getOffset() > size)
2153       outs() << " (past end of file)";
2154     if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
2155       outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
2156     outs() << "\n";
2157     outs() << "    size " << OFA.getSize();
2158     big_size = OFA.getOffset() + OFA.getSize();
2159     if (big_size > size)
2160       outs() << " (past end of file)";
2161     outs() << "\n";
2162     outs() << "    align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
2163            << ")\n";
2164   }
2165 }
2166
2167 static void printArchiveChild(StringRef Filename, const Archive::Child &C,
2168                               bool verbose, bool print_offset,
2169                               StringRef ArchitectureName = StringRef()) {
2170   if (print_offset)
2171     outs() << C.getChildOffset() << "\t";
2172   sys::fs::perms Mode =
2173       unwrapOrError(C.getAccessMode(), Filename, C, ArchitectureName);
2174   if (verbose) {
2175     // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
2176     // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
2177     outs() << "-";
2178     outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
2179     outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
2180     outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
2181     outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
2182     outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
2183     outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
2184     outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
2185     outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
2186     outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
2187   } else {
2188     outs() << format("0%o ", Mode);
2189   }
2190
2191   outs() << format(
2192       "%3d/%-3d %5" PRId64 " ",
2193       unwrapOrError(C.getUID(), Filename, C, ArchitectureName),
2194       unwrapOrError(C.getGID(), Filename, C, ArchitectureName),
2195       unwrapOrError(C.getRawSize(), Filename, C, ArchitectureName));
2196
2197   StringRef RawLastModified = C.getRawLastModified();
2198   if (verbose) {
2199     unsigned Seconds;
2200     if (RawLastModified.getAsInteger(10, Seconds))
2201       outs() << "(date: \"" << RawLastModified
2202              << "\" contains non-decimal chars) ";
2203     else {
2204       // Since cime(3) returns a 26 character string of the form:
2205       // "Sun Sep 16 01:03:52 1973\n\0"
2206       // just print 24 characters.
2207       time_t t = Seconds;
2208       outs() << format("%.24s ", ctime(&t));
2209     }
2210   } else {
2211     outs() << RawLastModified << " ";
2212   }
2213
2214   if (verbose) {
2215     Expected<StringRef> NameOrErr = C.getName();
2216     if (!NameOrErr) {
2217       consumeError(NameOrErr.takeError());
2218       outs() << unwrapOrError(C.getRawName(), Filename, C, ArchitectureName)
2219              << "\n";
2220     } else {
2221       StringRef Name = NameOrErr.get();
2222       outs() << Name << "\n";
2223     }
2224   } else {
2225     outs() << unwrapOrError(C.getRawName(), Filename, C, ArchitectureName)
2226            << "\n";
2227   }
2228 }
2229
2230 static void printArchiveHeaders(StringRef Filename, Archive *A, bool verbose,
2231                                 bool print_offset,
2232                                 StringRef ArchitectureName = StringRef()) {
2233   Error Err = Error::success();
2234   for (const auto &C : A->children(Err, false))
2235     printArchiveChild(Filename, C, verbose, print_offset, ArchitectureName);
2236
2237   if (Err)
2238     report_error(std::move(Err), StringRef(), Filename, ArchitectureName);
2239 }
2240
2241 static bool ValidateArchFlags() {
2242   // Check for -arch all and verifiy the -arch flags are valid.
2243   for (unsigned i = 0; i < ArchFlags.size(); ++i) {
2244     if (ArchFlags[i] == "all") {
2245       ArchAll = true;
2246     } else {
2247       if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
2248         WithColor::error(errs(), "llvm-objdump")
2249             << "unknown architecture named '" + ArchFlags[i] +
2250                    "'for the -arch option\n";
2251         return false;
2252       }
2253     }
2254   }
2255   return true;
2256 }
2257
2258 // ParseInputMachO() parses the named Mach-O file in Filename and handles the
2259 // -arch flags selecting just those slices as specified by them and also parses
2260 // archive files.  Then for each individual Mach-O file ProcessMachO() is
2261 // called to process the file based on the command line options.
2262 void parseInputMachO(StringRef Filename) {
2263   if (!ValidateArchFlags())
2264     return;
2265
2266   // Attempt to open the binary.
2267   Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
2268   if (!BinaryOrErr) {
2269     if (Error E = isNotObjectErrorInvalidFileType(BinaryOrErr.takeError()))
2270       report_error(std::move(E), Filename);
2271     else
2272       outs() << Filename << ": is not an object file\n";
2273     return;
2274   }
2275   Binary &Bin = *BinaryOrErr.get().getBinary();
2276
2277   if (Archive *A = dyn_cast<Archive>(&Bin)) {
2278     outs() << "Archive : " << Filename << "\n";
2279     if (ArchiveHeaders)
2280       printArchiveHeaders(Filename, A, !NonVerbose, ArchiveMemberOffsets);
2281
2282     Error Err = Error::success();
2283     for (auto &C : A->children(Err)) {
2284       Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2285       if (!ChildOrErr) {
2286         if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2287           report_error(std::move(E), Filename, C);
2288         continue;
2289       }
2290       if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
2291         if (!checkMachOAndArchFlags(O, Filename))
2292           return;
2293         ProcessMachO(Filename, O, O->getFileName());
2294       }
2295     }
2296     if (Err)
2297       report_error(std::move(Err), Filename);
2298     return;
2299   }
2300   if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
2301     parseInputMachO(UB);
2302     return;
2303   }
2304   if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
2305     if (!checkMachOAndArchFlags(O, Filename))
2306       return;
2307     if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O))
2308       ProcessMachO(Filename, MachOOF);
2309     else
2310       WithColor::error(errs(), "llvm-objdump")
2311           << Filename << "': "
2312           << "object is not a Mach-O file type.\n";
2313     return;
2314   }
2315   llvm_unreachable("Input object can't be invalid at this point");
2316 }
2317
2318 void parseInputMachO(MachOUniversalBinary *UB) {
2319   if (!ValidateArchFlags())
2320     return;
2321
2322   auto Filename = UB->getFileName();
2323
2324   if (UniversalHeaders)
2325     printMachOUniversalHeaders(UB, !NonVerbose);
2326
2327   // If we have a list of architecture flags specified dump only those.
2328   if (!ArchAll && !ArchFlags.empty()) {
2329     // Look for a slice in the universal binary that matches each ArchFlag.
2330     bool ArchFound;
2331     for (unsigned i = 0; i < ArchFlags.size(); ++i) {
2332       ArchFound = false;
2333       for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2334                                                   E = UB->end_objects();
2335             I != E; ++I) {
2336         if (ArchFlags[i] == I->getArchFlagName()) {
2337           ArchFound = true;
2338           Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
2339               I->getAsObjectFile();
2340           std::string ArchitectureName = "";
2341           if (ArchFlags.size() > 1)
2342             ArchitectureName = I->getArchFlagName();
2343           if (ObjOrErr) {
2344             ObjectFile &O = *ObjOrErr.get();
2345             if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
2346               ProcessMachO(Filename, MachOOF, "", ArchitectureName);
2347           } else if (Error E = isNotObjectErrorInvalidFileType(
2348                          ObjOrErr.takeError())) {
2349             report_error(std::move(E), Filename, StringRef(), ArchitectureName);
2350             continue;
2351           } else if (Expected<std::unique_ptr<Archive>> AOrErr =
2352                          I->getAsArchive()) {
2353             std::unique_ptr<Archive> &A = *AOrErr;
2354             outs() << "Archive : " << Filename;
2355             if (!ArchitectureName.empty())
2356               outs() << " (architecture " << ArchitectureName << ")";
2357             outs() << "\n";
2358             if (ArchiveHeaders)
2359               printArchiveHeaders(Filename, A.get(), !NonVerbose,
2360                                   ArchiveMemberOffsets, ArchitectureName);
2361             Error Err = Error::success();
2362             for (auto &C : A->children(Err)) {
2363               Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2364               if (!ChildOrErr) {
2365                 if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2366                   report_error(std::move(E), Filename, C, ArchitectureName);
2367                 continue;
2368               }
2369               if (MachOObjectFile *O =
2370                       dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
2371                 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
2372             }
2373             if (Err)
2374               report_error(std::move(Err), Filename);
2375           } else {
2376             consumeError(AOrErr.takeError());
2377             error("Mach-O universal file: " + Filename + " for " +
2378                   "architecture " + StringRef(I->getArchFlagName()) +
2379                   " is not a Mach-O file or an archive file");
2380           }
2381         }
2382       }
2383       if (!ArchFound) {
2384         WithColor::error(errs(), "llvm-objdump")
2385             << "file: " + Filename + " does not contain "
2386             << "architecture: " + ArchFlags[i] + "\n";
2387         return;
2388       }
2389     }
2390     return;
2391   }
2392   // No architecture flags were specified so if this contains a slice that
2393   // matches the host architecture dump only that.
2394   if (!ArchAll) {
2395     for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2396                                                 E = UB->end_objects();
2397           I != E; ++I) {
2398       if (MachOObjectFile::getHostArch().getArchName() ==
2399           I->getArchFlagName()) {
2400         Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2401         std::string ArchiveName;
2402         ArchiveName.clear();
2403         if (ObjOrErr) {
2404           ObjectFile &O = *ObjOrErr.get();
2405           if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
2406             ProcessMachO(Filename, MachOOF);
2407         } else if (Error E =
2408                        isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) {
2409           report_error(std::move(E), Filename);
2410         } else if (Expected<std::unique_ptr<Archive>> AOrErr =
2411                        I->getAsArchive()) {
2412           std::unique_ptr<Archive> &A = *AOrErr;
2413           outs() << "Archive : " << Filename << "\n";
2414           if (ArchiveHeaders)
2415             printArchiveHeaders(Filename, A.get(), !NonVerbose,
2416                                 ArchiveMemberOffsets);
2417           Error Err = Error::success();
2418           for (auto &C : A->children(Err)) {
2419             Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2420             if (!ChildOrErr) {
2421               if (Error E =
2422                       isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2423                 report_error(std::move(E), Filename, C);
2424               continue;
2425             }
2426             if (MachOObjectFile *O =
2427                     dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
2428               ProcessMachO(Filename, O, O->getFileName());
2429           }
2430           if (Err)
2431             report_error(std::move(Err), Filename);
2432         } else {
2433           consumeError(AOrErr.takeError());
2434           error("Mach-O universal file: " + Filename + " for architecture " +
2435                 StringRef(I->getArchFlagName()) +
2436                 " is not a Mach-O file or an archive file");
2437         }
2438         return;
2439       }
2440     }
2441   }
2442   // Either all architectures have been specified or none have been specified
2443   // and this does not contain the host architecture so dump all the slices.
2444   bool moreThanOneArch = UB->getNumberOfObjects() > 1;
2445   for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2446                                               E = UB->end_objects();
2447         I != E; ++I) {
2448     Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2449     std::string ArchitectureName = "";
2450     if (moreThanOneArch)
2451       ArchitectureName = I->getArchFlagName();
2452     if (ObjOrErr) {
2453       ObjectFile &Obj = *ObjOrErr.get();
2454       if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
2455         ProcessMachO(Filename, MachOOF, "", ArchitectureName);
2456     } else if (Error E =
2457                    isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) {
2458       report_error(std::move(E), StringRef(), Filename, ArchitectureName);
2459     } else if (Expected<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
2460       std::unique_ptr<Archive> &A = *AOrErr;
2461       outs() << "Archive : " << Filename;
2462       if (!ArchitectureName.empty())
2463         outs() << " (architecture " << ArchitectureName << ")";
2464       outs() << "\n";
2465       if (ArchiveHeaders)
2466         printArchiveHeaders(Filename, A.get(), !NonVerbose,
2467                             ArchiveMemberOffsets, ArchitectureName);
2468       Error Err = Error::success();
2469       for (auto &C : A->children(Err)) {
2470         Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2471         if (!ChildOrErr) {
2472           if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2473             report_error(std::move(E), Filename, C, ArchitectureName);
2474           continue;
2475         }
2476         if (MachOObjectFile *O =
2477                 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
2478           if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
2479             ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
2480                           ArchitectureName);
2481         }
2482       }
2483       if (Err)
2484         report_error(std::move(Err), Filename);
2485     } else {
2486       consumeError(AOrErr.takeError());
2487       error("Mach-O universal file: " + Filename + " for architecture " +
2488             StringRef(I->getArchFlagName()) +
2489             " is not a Mach-O file or an archive file");
2490     }
2491   }
2492 }
2493
2494 // The block of info used by the Symbolizer call backs.
2495 struct DisassembleInfo {
2496   DisassembleInfo(MachOObjectFile *O, SymbolAddressMap *AddrMap,
2497                   std::vector<SectionRef> *Sections, bool verbose)
2498     : verbose(verbose), O(O), AddrMap(AddrMap), Sections(Sections) {}
2499   bool verbose;
2500   MachOObjectFile *O;
2501   SectionRef S;
2502   SymbolAddressMap *AddrMap;
2503   std::vector<SectionRef> *Sections;
2504   const char *class_name = nullptr;
2505   const char *selector_name = nullptr;
2506   std::unique_ptr<char[]> method = nullptr;
2507   char *demangled_name = nullptr;
2508   uint64_t adrp_addr = 0;
2509   uint32_t adrp_inst = 0;
2510   std::unique_ptr<SymbolAddressMap> bindtable;
2511   uint32_t depth = 0;
2512 };
2513
2514 // SymbolizerGetOpInfo() is the operand information call back function.
2515 // This is called to get the symbolic information for operand(s) of an
2516 // instruction when it is being done.  This routine does this from
2517 // the relocation information, symbol table, etc. That block of information
2518 // is a pointer to the struct DisassembleInfo that was passed when the
2519 // disassembler context was created and passed to back to here when
2520 // called back by the disassembler for instruction operands that could have
2521 // relocation information. The address of the instruction containing operand is
2522 // at the Pc parameter.  The immediate value the operand has is passed in
2523 // op_info->Value and is at Offset past the start of the instruction and has a
2524 // byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
2525 // LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
2526 // names and addends of the symbolic expression to add for the operand.  The
2527 // value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
2528 // information is returned then this function returns 1 else it returns 0.
2529 static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
2530                                uint64_t Size, int TagType, void *TagBuf) {
2531   struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
2532   struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
2533   uint64_t value = op_info->Value;
2534
2535   // Make sure all fields returned are zero if we don't set them.
2536   memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
2537   op_info->Value = value;
2538
2539   // If the TagType is not the value 1 which it code knows about or if no
2540   // verbose symbolic information is wanted then just return 0, indicating no
2541   // information is being returned.
2542   if (TagType != 1 || !info->verbose)
2543     return 0;
2544
2545   unsigned int Arch = info->O->getArch();
2546   if (Arch == Triple::x86) {
2547     if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
2548       return 0;
2549     if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2550       // TODO:
2551       // Search the external relocation entries of a fully linked image
2552       // (if any) for an entry that matches this segment offset.
2553       // uint32_t seg_offset = (Pc + Offset);
2554       return 0;
2555     }
2556     // In MH_OBJECT filetypes search the section's relocation entries (if any)
2557     // for an entry for this section offset.
2558     uint32_t sect_addr = info->S.getAddress();
2559     uint32_t sect_offset = (Pc + Offset) - sect_addr;
2560     bool reloc_found = false;
2561     DataRefImpl Rel;
2562     MachO::any_relocation_info RE;
2563     bool isExtern = false;
2564     SymbolRef Symbol;
2565     bool r_scattered = false;
2566     uint32_t r_value, pair_r_value, r_type;
2567     for (const RelocationRef &Reloc : info->S.relocations()) {
2568       uint64_t RelocOffset = Reloc.getOffset();
2569       if (RelocOffset == sect_offset) {
2570         Rel = Reloc.getRawDataRefImpl();
2571         RE = info->O->getRelocation(Rel);
2572         r_type = info->O->getAnyRelocationType(RE);
2573         r_scattered = info->O->isRelocationScattered(RE);
2574         if (r_scattered) {
2575           r_value = info->O->getScatteredRelocationValue(RE);
2576           if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2577               r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
2578             DataRefImpl RelNext = Rel;
2579             info->O->moveRelocationNext(RelNext);
2580             MachO::any_relocation_info RENext;
2581             RENext = info->O->getRelocation(RelNext);
2582             if (info->O->isRelocationScattered(RENext))
2583               pair_r_value = info->O->getScatteredRelocationValue(RENext);
2584             else
2585               return 0;
2586           }
2587         } else {
2588           isExtern = info->O->getPlainRelocationExternal(RE);
2589           if (isExtern) {
2590             symbol_iterator RelocSym = Reloc.getSymbol();
2591             Symbol = *RelocSym;
2592           }
2593         }
2594         reloc_found = true;
2595         break;
2596       }
2597     }
2598     if (reloc_found && isExtern) {
2599       op_info->AddSymbol.Present = 1;
2600       op_info->AddSymbol.Name =
2601           unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
2602       // For i386 extern relocation entries the value in the instruction is
2603       // the offset from the symbol, and value is already set in op_info->Value.
2604       return 1;
2605     }
2606     if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2607                         r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
2608       const char *add = GuessSymbolName(r_value, info->AddrMap);
2609       const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
2610       uint32_t offset = value - (r_value - pair_r_value);
2611       op_info->AddSymbol.Present = 1;
2612       if (add != nullptr)
2613         op_info->AddSymbol.Name = add;
2614       else
2615         op_info->AddSymbol.Value = r_value;
2616       op_info->SubtractSymbol.Present = 1;
2617       if (sub != nullptr)
2618         op_info->SubtractSymbol.Name = sub;
2619       else
2620         op_info->SubtractSymbol.Value = pair_r_value;
2621       op_info->Value = offset;
2622       return 1;
2623     }
2624     return 0;
2625   }
2626   if (Arch == Triple::x86_64) {
2627     if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
2628       return 0;
2629     // For non MH_OBJECT types, like MH_KEXT_BUNDLE, Search the external
2630     // relocation entries of a linked image (if any) for an entry that matches
2631     // this segment offset.
2632     if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2633       uint64_t seg_offset = Pc + Offset;
2634       bool reloc_found = false;
2635       DataRefImpl Rel;
2636       MachO::any_relocation_info RE;
2637       bool isExtern = false;
2638       SymbolRef Symbol;
2639       for (const RelocationRef &Reloc : info->O->external_relocations()) {
2640         uint64_t RelocOffset = Reloc.getOffset();
2641         if (RelocOffset == seg_offset) {
2642           Rel = Reloc.getRawDataRefImpl();
2643           RE = info->O->getRelocation(Rel);
2644           // external relocation entries should always be external.
2645           isExtern = info->O->getPlainRelocationExternal(RE);
2646           if (isExtern) {
2647             symbol_iterator RelocSym = Reloc.getSymbol();
2648             Symbol = *RelocSym;
2649           }
2650           reloc_found = true;
2651           break;
2652         }
2653       }
2654       if (reloc_found && isExtern) {
2655         // The Value passed in will be adjusted by the Pc if the instruction
2656         // adds the Pc.  But for x86_64 external relocation entries the Value
2657         // is the offset from the external symbol.
2658         if (info->O->getAnyRelocationPCRel(RE))
2659           op_info->Value -= Pc + Offset + Size;
2660         const char *name =
2661             unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
2662         op_info->AddSymbol.Present = 1;
2663         op_info->AddSymbol.Name = name;
2664         return 1;
2665       }
2666       return 0;
2667     }
2668     // In MH_OBJECT filetypes search the section's relocation entries (if any)
2669     // for an entry for this section offset.
2670     uint64_t sect_addr = info->S.getAddress();
2671     uint64_t sect_offset = (Pc + Offset) - sect_addr;
2672     bool reloc_found = false;
2673     DataRefImpl Rel;
2674     MachO::any_relocation_info RE;
2675     bool isExtern = false;
2676     SymbolRef Symbol;
2677     for (const RelocationRef &Reloc : info->S.relocations()) {
2678       uint64_t RelocOffset = Reloc.getOffset();
2679       if (RelocOffset == sect_offset) {
2680         Rel = Reloc.getRawDataRefImpl();
2681         RE = info->O->getRelocation(Rel);
2682         // NOTE: Scattered relocations don't exist on x86_64.
2683         isExtern = info->O->getPlainRelocationExternal(RE);
2684         if (isExtern) {
2685           symbol_iterator RelocSym = Reloc.getSymbol();
2686           Symbol = *RelocSym;
2687         }
2688         reloc_found = true;
2689         break;
2690       }
2691     }
2692     if (reloc_found && isExtern) {
2693       // The Value passed in will be adjusted by the Pc if the instruction
2694       // adds the Pc.  But for x86_64 external relocation entries the Value
2695       // is the offset from the external symbol.
2696       if (info->O->getAnyRelocationPCRel(RE))
2697         op_info->Value -= Pc + Offset + Size;
2698       const char *name =
2699           unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
2700       unsigned Type = info->O->getAnyRelocationType(RE);
2701       if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
2702         DataRefImpl RelNext = Rel;
2703         info->O->moveRelocationNext(RelNext);
2704         MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2705         unsigned TypeNext = info->O->getAnyRelocationType(RENext);
2706         bool isExternNext = info->O->getPlainRelocationExternal(RENext);
2707         unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
2708         if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
2709           op_info->SubtractSymbol.Present = 1;
2710           op_info->SubtractSymbol.Name = name;
2711           symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
2712           Symbol = *RelocSymNext;
2713           name = unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
2714         }
2715       }
2716       // TODO: add the VariantKinds to op_info->VariantKind for relocation types
2717       // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
2718       op_info->AddSymbol.Present = 1;
2719       op_info->AddSymbol.Name = name;
2720       return 1;
2721     }
2722     return 0;
2723   }
2724   if (Arch == Triple::arm) {
2725     if (Offset != 0 || (Size != 4 && Size != 2))
2726       return 0;
2727     if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2728       // TODO:
2729       // Search the external relocation entries of a fully linked image
2730       // (if any) for an entry that matches this segment offset.
2731       // uint32_t seg_offset = (Pc + Offset);
2732       return 0;
2733     }
2734     // In MH_OBJECT filetypes search the section's relocation entries (if any)
2735     // for an entry for this section offset.
2736     uint32_t sect_addr = info->S.getAddress();
2737     uint32_t sect_offset = (Pc + Offset) - sect_addr;
2738     DataRefImpl Rel;
2739     MachO::any_relocation_info RE;
2740     bool isExtern = false;
2741     SymbolRef Symbol;
2742     bool r_scattered = false;
2743     uint32_t r_value, pair_r_value, r_type, r_length, other_half;
2744     auto Reloc =
2745         find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2746           uint64_t RelocOffset = Reloc.getOffset();
2747           return RelocOffset == sect_offset;
2748         });
2749
2750     if (Reloc == info->S.relocations().end())
2751       return 0;
2752
2753     Rel = Reloc->getRawDataRefImpl();
2754     RE = info->O->getRelocation(Rel);
2755     r_length = info->O->getAnyRelocationLength(RE);
2756     r_scattered = info->O->isRelocationScattered(RE);
2757     if (r_scattered) {
2758       r_value = info->O->getScatteredRelocationValue(RE);
2759       r_type = info->O->getScatteredRelocationType(RE);
2760     } else {
2761       r_type = info->O->getAnyRelocationType(RE);
2762       isExtern = info->O->getPlainRelocationExternal(RE);
2763       if (isExtern) {
2764         symbol_iterator RelocSym = Reloc->getSymbol();
2765         Symbol = *RelocSym;
2766       }
2767     }
2768     if (r_type == MachO::ARM_RELOC_HALF ||
2769         r_type == MachO::ARM_RELOC_SECTDIFF ||
2770         r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
2771         r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2772       DataRefImpl RelNext = Rel;
2773       info->O->moveRelocationNext(RelNext);
2774       MachO::any_relocation_info RENext;
2775       RENext = info->O->getRelocation(RelNext);
2776       other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
2777       if (info->O->isRelocationScattered(RENext))
2778         pair_r_value = info->O->getScatteredRelocationValue(RENext);
2779     }
2780
2781     if (isExtern) {
2782       const char *name =
2783           unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
2784       op_info->AddSymbol.Present = 1;
2785       op_info->AddSymbol.Name = name;
2786       switch (r_type) {
2787       case MachO::ARM_RELOC_HALF:
2788         if ((r_length & 0x1) == 1) {
2789           op_info->Value = value << 16 | other_half;
2790           op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2791         } else {
2792           op_info->Value = other_half << 16 | value;
2793           op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
2794         }
2795         break;
2796       default:
2797         break;
2798       }
2799       return 1;
2800     }
2801     // If we have a branch that is not an external relocation entry then
2802     // return 0 so the code in tryAddingSymbolicOperand() can use the
2803     // SymbolLookUp call back with the branch target address to look up the
2804     // symbol and possibility add an annotation for a symbol stub.
2805     if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
2806                           r_type == MachO::ARM_THUMB_RELOC_BR22))
2807       return 0;
2808
2809     uint32_t offset = 0;
2810     if (r_type == MachO::ARM_RELOC_HALF ||
2811         r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2812       if ((r_length & 0x1) == 1)
2813         value = value << 16 | other_half;
2814       else
2815         value = other_half << 16 | value;
2816     }
2817     if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
2818                         r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
2819       offset = value - r_value;
2820       value = r_value;
2821     }
2822
2823     if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2824       if ((r_length & 0x1) == 1)
2825         op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2826       else
2827         op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
2828       const char *add = GuessSymbolName(r_value, info->AddrMap);
2829       const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
2830       int32_t offset = value - (r_value - pair_r_value);
2831       op_info->AddSymbol.Present = 1;
2832       if (add != nullptr)
2833         op_info->AddSymbol.Name = add;
2834       else
2835         op_info->AddSymbol.Value = r_value;
2836       op_info->SubtractSymbol.Present = 1;
2837       if (sub != nullptr)
2838         op_info->SubtractSymbol.Name = sub;
2839       else
2840         op_info->SubtractSymbol.Value = pair_r_value;
2841       op_info->Value = offset;
2842       return 1;
2843     }
2844
2845     op_info->AddSymbol.Present = 1;
2846     op_info->Value = offset;
2847     if (r_type == MachO::ARM_RELOC_HALF) {
2848       if ((r_length & 0x1) == 1)
2849         op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2850       else
2851         op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
2852     }
2853     const char *add = GuessSymbolName(value, info->AddrMap);
2854     if (add != nullptr) {
2855       op_info->AddSymbol.Name = add;
2856       return 1;
2857     }
2858     op_info->AddSymbol.Value = value;
2859     return 1;
2860   }
2861   if (Arch == Triple::aarch64) {
2862     if (Offset != 0 || Size != 4)
2863       return 0;
2864     if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2865       // TODO:
2866       // Search the external relocation entries of a fully linked image
2867       // (if any) for an entry that matches this segment offset.
2868       // uint64_t seg_offset = (Pc + Offset);
2869       return 0;
2870     }
2871     // In MH_OBJECT filetypes search the section's relocation entries (if any)
2872     // for an entry for this section offset.
2873     uint64_t sect_addr = info->S.getAddress();
2874     uint64_t sect_offset = (Pc + Offset) - sect_addr;
2875     auto Reloc =
2876         find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2877           uint64_t RelocOffset = Reloc.getOffset();
2878           return RelocOffset == sect_offset;
2879         });
2880
2881     if (Reloc == info->S.relocations().end())
2882       return 0;
2883
2884     DataRefImpl Rel = Reloc->getRawDataRefImpl();
2885     MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2886     uint32_t r_type = info->O->getAnyRelocationType(RE);
2887     if (r_type == MachO::ARM64_RELOC_ADDEND) {
2888       DataRefImpl RelNext = Rel;
2889       info->O->moveRelocationNext(RelNext);
2890       MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2891       if (value == 0) {
2892         value = info->O->getPlainRelocationSymbolNum(RENext);
2893         op_info->Value = value;
2894       }
2895     }
2896     // NOTE: Scattered relocations don't exist on arm64.
2897     if (!info->O->getPlainRelocationExternal(RE))
2898       return 0;
2899     const char *name =
2900         unwrapOrError(Reloc->getSymbol()->getName(), info->O->getFileName())
2901             .data();
2902     op_info->AddSymbol.Present = 1;
2903     op_info->AddSymbol.Name = name;
2904
2905     switch (r_type) {
2906     case MachO::ARM64_RELOC_PAGE21:
2907       /* @page */
2908       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2909       break;
2910     case MachO::ARM64_RELOC_PAGEOFF12:
2911       /* @pageoff */
2912       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2913       break;
2914     case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2915       /* @gotpage */
2916       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2917       break;
2918     case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2919       /* @gotpageoff */
2920       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2921       break;
2922     case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2923       /* @tvlppage is not implemented in llvm-mc */
2924       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2925       break;
2926     case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2927       /* @tvlppageoff is not implemented in llvm-mc */
2928       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2929       break;
2930     default:
2931     case MachO::ARM64_RELOC_BRANCH26:
2932       op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2933       break;
2934     }
2935     return 1;
2936   }
2937   return 0;
2938 }
2939
2940 // GuessCstringPointer is passed the address of what might be a pointer to a
2941 // literal string in a cstring section.  If that address is in a cstring section
2942 // it returns a pointer to that string.  Else it returns nullptr.
2943 static const char *GuessCstringPointer(uint64_t ReferenceValue,
2944                                        struct DisassembleInfo *info) {
2945   for (const auto &Load : info->O->load_commands()) {
2946     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2947       MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2948       for (unsigned J = 0; J < Seg.nsects; ++J) {
2949         MachO::section_64 Sec = info->O->getSection64(Load, J);
2950         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2951         if (section_type == MachO::S_CSTRING_LITERALS &&
2952             ReferenceValue >= Sec.addr &&
2953             ReferenceValue < Sec.addr + Sec.size) {
2954           uint64_t sect_offset = ReferenceValue - Sec.addr;
2955           uint64_t object_offset = Sec.offset + sect_offset;
2956           StringRef MachOContents = info->O->getData();
2957           uint64_t object_size = MachOContents.size();
2958           const char *object_addr = (const char *)MachOContents.data();
2959           if (object_offset < object_size) {
2960             const char *name = object_addr + object_offset;
2961             return name;
2962           } else {
2963             return nullptr;
2964           }
2965         }
2966       }
2967     } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2968       MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2969       for (unsigned J = 0; J < Seg.nsects; ++J) {
2970         MachO::section Sec = info->O->getSection(Load, J);
2971         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2972         if (section_type == MachO::S_CSTRING_LITERALS &&
2973             ReferenceValue >= Sec.addr &&
2974             ReferenceValue < Sec.addr + Sec.size) {
2975           uint64_t sect_offset = ReferenceValue - Sec.addr;
2976           uint64_t object_offset = Sec.offset + sect_offset;
2977           StringRef MachOContents = info->O->getData();
2978           uint64_t object_size = MachOContents.size();
2979           const char *object_addr = (const char *)MachOContents.data();
2980           if (object_offset < object_size) {
2981             const char *name = object_addr + object_offset;
2982             return name;
2983           } else {
2984             return nullptr;
2985           }
2986         }
2987       }
2988     }
2989   }
2990   return nullptr;
2991 }
2992
2993 // GuessIndirectSymbol returns the name of the indirect symbol for the
2994 // ReferenceValue passed in or nullptr.  This is used when ReferenceValue maybe
2995 // an address of a symbol stub or a lazy or non-lazy pointer to associate the
2996 // symbol name being referenced by the stub or pointer.
2997 static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2998                                        struct DisassembleInfo *info) {
2999   MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
3000   MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
3001   for (const auto &Load : info->O->load_commands()) {
3002     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
3003       MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
3004       for (unsigned J = 0; J < Seg.nsects; ++J) {
3005         MachO::section_64 Sec = info->O->getSection64(Load, J);
3006         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3007         if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
3008              section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
3009              section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
3010              section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
3011              section_type == MachO::S_SYMBOL_STUBS) &&
3012             ReferenceValue >= Sec.addr &&
3013             ReferenceValue < Sec.addr + Sec.size) {
3014           uint32_t stride;
3015           if (section_type == MachO::S_SYMBOL_STUBS)
3016             stride = Sec.reserved2;
3017           else
3018             stride = 8;
3019           if (stride == 0)
3020             return nullptr;
3021           uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
3022           if (index < Dysymtab.nindirectsyms) {
3023             uint32_t indirect_symbol =
3024                 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
3025             if (indirect_symbol < Symtab.nsyms) {
3026               symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
3027               return unwrapOrError(Sym->getName(), info->O->getFileName())
3028                   .data();
3029             }
3030           }
3031         }
3032       }
3033     } else if (Load.C.cmd == MachO::LC_SEGMENT) {
3034       MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
3035       for (unsigned J = 0; J < Seg.nsects; ++J) {
3036         MachO::section Sec = info->O->getSection(Load, J);
3037         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3038         if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
3039              section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
3040              section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
3041              section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
3042              section_type == MachO::S_SYMBOL_STUBS) &&
3043             ReferenceValue >= Sec.addr &&
3044             ReferenceValue < Sec.addr + Sec.size) {
3045           uint32_t stride;
3046           if (section_type == MachO::S_SYMBOL_STUBS)
3047             stride = Sec.reserved2;
3048           else
3049             stride = 4;
3050           if (stride == 0)
3051             return nullptr;
3052           uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
3053           if (index < Dysymtab.nindirectsyms) {
3054             uint32_t indirect_symbol =
3055                 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
3056             if (indirect_symbol < Symtab.nsyms) {
3057               symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
3058               return unwrapOrError(Sym->getName(), info->O->getFileName())
3059                   .data();
3060             }
3061           }
3062         }
3063       }
3064     }
3065   }
3066   return nullptr;
3067 }
3068
3069 // method_reference() is called passing it the ReferenceName that might be
3070 // a reference it to an Objective-C method call.  If so then it allocates and
3071 // assembles a method call string with the values last seen and saved in
3072 // the DisassembleInfo's class_name and selector_name fields.  This is saved
3073 // into the method field of the info and any previous string is free'ed.
3074 // Then the class_name field in the info is set to nullptr.  The method call
3075 // string is set into ReferenceName and ReferenceType is set to
3076 // LLVMDisassembler_ReferenceType_Out_Objc_Message.  If this not a method call
3077 // then both ReferenceType and ReferenceName are left unchanged.
3078 static void method_reference(struct DisassembleInfo *info,
3079                              uint64_t *ReferenceType,
3080                              const char **ReferenceName) {
3081   unsigned int Arch = info->O->getArch();
3082   if (*ReferenceName != nullptr) {
3083     if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
3084       if (info->selector_name != nullptr) {
3085         if (info->class_name != nullptr) {
3086           info->method = llvm::make_unique<char[]>(
3087               5 + strlen(info->class_name) + strlen(info->selector_name));
3088           char *method = info->method.get();
3089           if (method != nullptr) {
3090             strcpy(method, "+[");
3091             strcat(method, info->class_name);
3092             strcat(method, " ");
3093             strcat(method, info->selector_name);
3094             strcat(method, "]");
3095             *ReferenceName = method;
3096             *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3097           }
3098         } else {
3099           info->method =
3100               llvm::make_unique<char[]>(9 + strlen(info->selector_name));
3101           char *method = info->method.get();
3102           if (method != nullptr) {
3103             if (Arch == Triple::x86_64)
3104               strcpy(method, "-[%rdi ");
3105             else if (Arch == Triple::aarch64)
3106               strcpy(method, "-[x0 ");
3107             else
3108               strcpy(method, "-[r? ");
3109             strcat(method, info->selector_name);
3110             strcat(method, "]");
3111             *ReferenceName = method;
3112             *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3113           }
3114         }
3115         info->class_name = nullptr;
3116       }
3117     } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
3118       if (info->selector_name != nullptr) {
3119         info->method =
3120             llvm::make_unique<char[]>(17 + strlen(info->selector_name));
3121         char *method = info->method.get();
3122         if (method != nullptr) {
3123           if (Arch == Triple::x86_64)
3124             strcpy(method, "-[[%rdi super] ");
3125           else if (Arch == Triple::aarch64)
3126             strcpy(method, "-[[x0 super] ");
3127           else
3128             strcpy(method, "-[[r? super] ");
3129           strcat(method, info->selector_name);
3130           strcat(method, "]");
3131           *ReferenceName = method;
3132           *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3133         }
3134         info->class_name = nullptr;
3135       }
3136     }
3137   }
3138 }
3139
3140 // GuessPointerPointer() is passed the address of what might be a pointer to
3141 // a reference to an Objective-C class, selector, message ref or cfstring.
3142 // If so the value of the pointer is returned and one of the booleans are set
3143 // to true.  If not zero is returned and all the booleans are set to false.
3144 static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
3145                                     struct DisassembleInfo *info,
3146                                     bool &classref, bool &selref, bool &msgref,
3147                                     bool &cfstring) {
3148   classref = false;
3149   selref = false;
3150   msgref = false;
3151   cfstring = false;
3152   for (const auto &Load : info->O->load_commands()) {
3153     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
3154       MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
3155       for (unsigned J = 0; J < Seg.nsects; ++J) {
3156         MachO::section_64 Sec = info->O->getSection64(Load, J);
3157         if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
3158              strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
3159              strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
3160              strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
3161              strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
3162             ReferenceValue >= Sec.addr &&
3163             ReferenceValue < Sec.addr + Sec.size) {
3164           uint64_t sect_offset = ReferenceValue - Sec.addr;
3165           uint64_t object_offset = Sec.offset + sect_offset;
3166           StringRef MachOContents = info->O->getData();
3167           uint64_t object_size = MachOContents.size();
3168           const char *object_addr = (const char *)MachOContents.data();
3169           if (object_offset < object_size) {
3170             uint64_t pointer_value;
3171             memcpy(&pointer_value, object_addr + object_offset,
3172                    sizeof(uint64_t));
3173             if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3174               sys::swapByteOrder(pointer_value);
3175             if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
3176               selref = true;
3177             else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
3178                      strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
3179               classref = true;
3180             else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
3181                      ReferenceValue + 8 < Sec.addr + Sec.size) {
3182               msgref = true;
3183               memcpy(&pointer_value, object_addr + object_offset + 8,
3184                      sizeof(uint64_t));
3185               if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3186                 sys::swapByteOrder(pointer_value);
3187             } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
3188               cfstring = true;
3189             return pointer_value;
3190           } else {
3191             return 0;
3192           }
3193         }
3194       }
3195     }
3196     // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
3197   }
3198   return 0;
3199 }
3200
3201 // get_pointer_64 returns a pointer to the bytes in the object file at the
3202 // Address from a section in the Mach-O file.  And indirectly returns the
3203 // offset into the section, number of bytes left in the section past the offset
3204 // and which section is was being referenced.  If the Address is not in a
3205 // section nullptr is returned.
3206 static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
3207                                   uint32_t &left, SectionRef &S,
3208                                   DisassembleInfo *info,
3209                                   bool objc_only = false) {
3210   offset = 0;
3211   left = 0;
3212   S = SectionRef();
3213   for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
3214     uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
3215     uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
3216     if (SectSize == 0)
3217       continue;
3218     if (objc_only) {
3219       StringRef SectName;
3220       ((*(info->Sections))[SectIdx]).getName(SectName);
3221       DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
3222       StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
3223       if (SegName != "__OBJC" && SectName != "__cstring")
3224         continue;
3225     }
3226     if (Address >= SectAddress && Address < SectAddress + SectSize) {
3227       S = (*(info->Sections))[SectIdx];
3228       offset = Address - SectAddress;
3229       left = SectSize - offset;
3230       StringRef SectContents = unwrapOrError(
3231           ((*(info->Sections))[SectIdx]).getContents(), info->O->getFileName());
3232       return SectContents.data() + offset;
3233     }
3234   }
3235   return nullptr;
3236 }
3237
3238 static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
3239                                   uint32_t &left, SectionRef &S,
3240                                   DisassembleInfo *info,
3241                                   bool objc_only = false) {
3242   return get_pointer_64(Address, offset, left, S, info, objc_only);
3243 }
3244
3245 // get_symbol_64() returns the name of a symbol (or nullptr) and the address of
3246 // the symbol indirectly through n_value. Based on the relocation information
3247 // for the specified section offset in the specified section reference.
3248 // If no relocation information is found and a non-zero ReferenceValue for the
3249 // symbol is passed, look up that address in the info's AddrMap.
3250 static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
3251                                  DisassembleInfo *info, uint64_t &n_value,
3252                                  uint64_t ReferenceValue = 0) {
3253   n_value = 0;
3254   if (!info->verbose)
3255     return nullptr;
3256
3257   // See if there is an external relocation entry at the sect_offset.
3258   bool reloc_found = false;
3259   DataRefImpl Rel;
3260   MachO::any_relocation_info RE;
3261   bool isExtern = false;
3262   SymbolRef Symbol;
3263   for (const RelocationRef &Reloc : S.relocations()) {
3264     uint64_t RelocOffset = Reloc.getOffset();
3265     if (RelocOffset == sect_offset) {
3266       Rel = Reloc.getRawDataRefImpl();
3267       RE = info->O->getRelocation(Rel);
3268       if (info->O->isRelocationScattered(RE))
3269         continue;
3270       isExtern = info->O->getPlainRelocationExternal(RE);
3271       if (isExtern) {
3272         symbol_iterator RelocSym = Reloc.getSymbol();
3273         Symbol = *RelocSym;
3274       }
3275       reloc_found = true;
3276       break;
3277     }
3278   }
3279   // If there is an external relocation entry for a symbol in this section
3280   // at this section_offset then use that symbol's value for the n_value
3281   // and return its name.
3282   const char *SymbolName = nullptr;
3283   if (reloc_found && isExtern) {
3284     n_value = Symbol.getValue();
3285     StringRef Name = unwrapOrError(Symbol.getName(), info->O->getFileName());
3286     if (!Name.empty()) {
3287       SymbolName = Name.data();
3288       return SymbolName;
3289     }
3290   }
3291
3292   // TODO: For fully linked images, look through the external relocation
3293   // entries off the dynamic symtab command. For these the r_offset is from the
3294   // start of the first writeable segment in the Mach-O file.  So the offset
3295   // to this section from that segment is passed to this routine by the caller,
3296   // as the database_offset. Which is the difference of the section's starting
3297   // address and the first writable segment.
3298   //
3299   // NOTE: need add passing the database_offset to this routine.
3300
3301   // We did not find an external relocation entry so look up the ReferenceValue
3302   // as an address of a symbol and if found return that symbol's name.
3303   SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
3304
3305   return SymbolName;
3306 }
3307
3308 static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
3309                                  DisassembleInfo *info,
3310                                  uint32_t ReferenceValue) {
3311   uint64_t n_value64;
3312   return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
3313 }
3314
3315 // These are structs in the Objective-C meta data and read to produce the
3316 // comments for disassembly.  While these are part of the ABI they are no
3317 // public defintions.  So the are here not in include/llvm/BinaryFormat/MachO.h
3318 // .
3319
3320 // The cfstring object in a 64-bit Mach-O file.
3321 struct cfstring64_t {
3322   uint64_t isa;        // class64_t * (64-bit pointer)
3323   uint64_t flags;      // flag bits
3324   uint64_t characters; // char * (64-bit pointer)
3325   uint64_t length;     // number of non-NULL characters in above
3326 };
3327
3328 // The class object in a 64-bit Mach-O file.
3329 struct class64_t {
3330   uint64_t isa;        // class64_t * (64-bit pointer)
3331   uint64_t superclass; // class64_t * (64-bit pointer)
3332   uint64_t cache;      // Cache (64-bit pointer)
3333   uint64_t vtable;     // IMP * (64-bit pointer)
3334   uint64_t data;       // class_ro64_t * (64-bit pointer)
3335 };
3336
3337 struct class32_t {
3338   uint32_t isa;        /* class32_t * (32-bit pointer) */
3339   uint32_t superclass; /* class32_t * (32-bit pointer) */
3340   uint32_t cache;      /* Cache (32-bit pointer) */
3341   uint32_t vtable;     /* IMP * (32-bit pointer) */
3342   uint32_t data;       /* class_ro32_t * (32-bit pointer) */
3343 };
3344
3345 struct class_ro64_t {
3346   uint32_t flags;
3347   uint32_t instanceStart;
3348   uint32_t instanceSize;
3349   uint32_t reserved;
3350   uint64_t ivarLayout;     // const uint8_t * (64-bit pointer)
3351   uint64_t name;           // const char * (64-bit pointer)
3352   uint64_t baseMethods;    // const method_list_t * (64-bit pointer)
3353   uint64_t baseProtocols;  // const protocol_list_t * (64-bit pointer)
3354   uint64_t ivars;          // const ivar_list_t * (64-bit pointer)
3355   uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
3356   uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
3357 };
3358
3359 struct class_ro32_t {
3360   uint32_t flags;
3361   uint32_t instanceStart;
3362   uint32_t instanceSize;
3363   uint32_t ivarLayout;     /* const uint8_t * (32-bit pointer) */
3364   uint32_t name;           /* const char * (32-bit pointer) */
3365   uint32_t baseMethods;    /* const method_list_t * (32-bit pointer) */
3366   uint32_t baseProtocols;  /* const protocol_list_t * (32-bit pointer) */
3367   uint32_t ivars;          /* const ivar_list_t * (32-bit pointer) */
3368   uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
3369   uint32_t baseProperties; /* const struct objc_property_list *
3370                                                    (32-bit pointer) */
3371 };
3372
3373 /* Values for class_ro{64,32}_t->flags */
3374 #define RO_META (1 << 0)
3375 #define RO_ROOT (1 << 1)
3376 #define RO_HAS_CXX_STRUCTORS (1 << 2)
3377
3378 struct method_list64_t {
3379   uint32_t entsize;
3380   uint32_t count;
3381   /* struct method64_t first;  These structures follow inline */
3382 };
3383
3384 struct method_list32_t {
3385   uint32_t entsize;
3386   uint32_t count;
3387   /* struct method32_t first;  These structures follow inline */
3388 };
3389
3390 struct method64_t {
3391   uint64_t name;  /* SEL (64-bit pointer) */
3392   uint64_t types; /* const char * (64-bit pointer) */
3393   uint64_t imp;   /* IMP (64-bit pointer) */
3394 };
3395
3396 struct method32_t {
3397   uint32_t name;  /* SEL (32-bit pointer) */
3398   uint32_t types; /* const char * (32-bit pointer) */
3399   uint32_t imp;   /* IMP (32-bit pointer) */
3400 };
3401
3402 struct protocol_list64_t {
3403   uint64_t count; /* uintptr_t (a 64-bit value) */
3404   /* struct protocol64_t * list[0];  These pointers follow inline */
3405 };
3406
3407 struct protocol_list32_t {
3408   uint32_t count; /* uintptr_t (a 32-bit value) */
3409   /* struct protocol32_t * list[0];  These pointers follow inline */
3410 };
3411
3412 struct protocol64_t {
3413   uint64_t isa;                     /* id * (64-bit pointer) */
3414   uint64_t name;                    /* const char * (64-bit pointer) */
3415   uint64_t protocols;               /* struct protocol_list64_t *
3416                                                     (64-bit pointer) */
3417   uint64_t instanceMethods;         /* method_list_t * (64-bit pointer) */
3418   uint64_t classMethods;            /* method_list_t * (64-bit pointer) */
3419   uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
3420   uint64_t optionalClassMethods;    /* method_list_t * (64-bit pointer) */
3421   uint64_t instanceProperties;      /* struct objc_property_list *
3422                                                        (64-bit pointer) */
3423 };
3424
3425 struct protocol32_t {
3426   uint32_t isa;                     /* id * (32-bit pointer) */
3427   uint32_t name;                    /* const char * (32-bit pointer) */
3428   uint32_t protocols;               /* struct protocol_list_t *
3429                                                     (32-bit pointer) */
3430   uint32_t instanceMethods;         /* method_list_t * (32-bit pointer) */
3431   uint32_t classMethods;            /* method_list_t * (32-bit pointer) */
3432   uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
3433   uint32_t optionalClassMethods;    /* method_list_t * (32-bit pointer) */
3434   uint32_t instanceProperties;      /* struct objc_property_list *
3435                                                        (32-bit pointer) */
3436 };
3437
3438 struct ivar_list64_t {
3439   uint32_t entsize;
3440   uint32_t count;
3441   /* struct ivar64_t first;  These structures follow inline */
3442 };
3443
3444 struct ivar_list32_t {
3445   uint32_t entsize;
3446   uint32_t count;
3447   /* struct ivar32_t first;  These structures follow inline */
3448 };
3449
3450 struct ivar64_t {
3451   uint64_t offset; /* uintptr_t * (64-bit pointer) */
3452   uint64_t name;   /* const char * (64-bit pointer) */
3453   uint64_t type;   /* const char * (64-bit pointer) */
3454   uint32_t alignment;
3455   uint32_t size;
3456 };
3457
3458 struct ivar32_t {
3459   uint32_t offset; /* uintptr_t * (32-bit pointer) */
3460   uint32_t name;   /* const char * (32-bit pointer) */
3461   uint32_t type;   /* const char * (32-bit pointer) */
3462   uint32_t alignment;
3463   uint32_t size;
3464 };
3465
3466 struct objc_property_list64 {
3467   uint32_t entsize;
3468   uint32_t count;
3469   /* struct objc_property64 first;  These structures follow inline */
3470 };
3471
3472 struct objc_property_list32 {
3473   uint32_t entsize;
3474   uint32_t count;
3475   /* struct objc_property32 first;  These structures follow inline */
3476 };
3477
3478 struct objc_property64 {
3479   uint64_t name;       /* const char * (64-bit pointer) */
3480   uint64_t attributes; /* const char * (64-bit pointer) */
3481 };
3482
3483 struct objc_property32 {
3484   uint32_t name;       /* const char * (32-bit pointer) */
3485   uint32_t attributes; /* const char * (32-bit pointer) */
3486 };
3487
3488 struct category64_t {
3489   uint64_t name;               /* const char * (64-bit pointer) */
3490   uint64_t cls;                /* struct class_t * (64-bit pointer) */
3491   uint64_t instanceMethods;    /* struct method_list_t * (64-bit pointer) */
3492   uint64_t classMethods;       /* struct method_list_t * (64-bit pointer) */
3493   uint64_t protocols;          /* struct protocol_list_t * (64-bit pointer) */
3494   uint64_t instanceProperties; /* struct objc_property_list *
3495                                   (64-bit pointer) */
3496 };
3497
3498 struct category32_t {
3499   uint32_t name;               /* const char * (32-bit pointer) */
3500   uint32_t cls;                /* struct class_t * (32-bit pointer) */
3501   uint32_t instanceMethods;    /* struct method_list_t * (32-bit pointer) */
3502   uint32_t classMethods;       /* struct method_list_t * (32-bit pointer) */
3503   uint32_t protocols;          /* struct protocol_list_t * (32-bit pointer) */
3504   uint32_t instanceProperties; /* struct objc_property_list *
3505                                   (32-bit pointer) */
3506 };
3507
3508 struct objc_image_info64 {
3509   uint32_t version;
3510   uint32_t flags;
3511 };
3512 struct objc_image_info32 {
3513   uint32_t version;
3514   uint32_t flags;
3515 };
3516 struct imageInfo_t {
3517   uint32_t version;
3518   uint32_t flags;
3519 };
3520 /* masks for objc_image_info.flags */
3521 #define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
3522 #define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
3523 #define OBJC_IMAGE_IS_SIMULATED (1 << 5)
3524 #define OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES (1 << 6)
3525
3526 struct message_ref64 {
3527   uint64_t imp; /* IMP (64-bit pointer) */
3528   uint64_t sel; /* SEL (64-bit pointer) */
3529 };
3530
3531 struct message_ref32 {
3532   uint32_t imp; /* IMP (32-bit pointer) */
3533   uint32_t sel; /* SEL (32-bit pointer) */
3534 };
3535
3536 // Objective-C 1 (32-bit only) meta data structs.
3537
3538 struct objc_module_t {
3539   uint32_t version;
3540   uint32_t size;
3541   uint32_t name;   /* char * (32-bit pointer) */
3542   uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
3543 };
3544
3545 struct objc_symtab_t {
3546   uint32_t sel_ref_cnt;
3547   uint32_t refs; /* SEL * (32-bit pointer) */
3548   uint16_t cls_def_cnt;
3549   uint16_t cat_def_cnt;
3550   // uint32_t defs[1];        /* void * (32-bit pointer) variable size */
3551 };
3552
3553 struct objc_class_t {
3554   uint32_t isa;         /* struct objc_class * (32-bit pointer) */
3555   uint32_t super_class; /* struct objc_class * (32-bit pointer) */
3556   uint32_t name;        /* const char * (32-bit pointer) */
3557   int32_t version;
3558   int32_t info;
3559   int32_t instance_size;
3560   uint32_t ivars;       /* struct objc_ivar_list * (32-bit pointer) */
3561   uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
3562   uint32_t cache;       /* struct objc_cache * (32-bit pointer) */
3563   uint32_t protocols;   /* struct objc_protocol_list * (32-bit pointer) */
3564 };
3565
3566 #define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
3567 // class is not a metaclass
3568 #define CLS_CLASS 0x1
3569 // class is a metaclass
3570 #define CLS_META 0x2
3571
3572 struct objc_category_t {
3573   uint32_t category_name;    /* char * (32-bit pointer) */
3574   uint32_t class_name;       /* char * (32-bit pointer) */
3575   uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
3576   uint32_t class_methods;    /* struct objc_method_list * (32-bit pointer) */
3577   uint32_t protocols;        /* struct objc_protocol_list * (32-bit ptr) */
3578 };
3579
3580 struct objc_ivar_t {
3581   uint32_t ivar_name; /* char * (32-bit pointer) */
3582   uint32_t ivar_type; /* char * (32-bit pointer) */
3583   int32_t ivar_offset;
3584 };
3585
3586 struct objc_ivar_list_t {
3587   int32_t ivar_count;
3588   // struct objc_ivar_t ivar_list[1];          /* variable length structure */
3589 };
3590
3591 struct objc_method_list_t {
3592   uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
3593   int32_t method_count;
3594   // struct objc_method_t method_list[1];      /* variable length structure */
3595 };
3596
3597 struct objc_method_t {
3598   uint32_t method_name;  /* SEL, aka struct objc_selector * (32-bit pointer) */
3599   uint32_t method_types; /* char * (32-bit pointer) */
3600   uint32_t method_imp;   /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
3601                             (32-bit pointer) */
3602 };
3603
3604 struct objc_protocol_list_t {
3605   uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
3606   int32_t count;
3607   // uint32_t list[1];   /* Protocol *, aka struct objc_protocol_t *
3608   //                        (32-bit pointer) */
3609 };
3610
3611 struct objc_protocol_t {
3612   uint32_t isa;              /* struct objc_class * (32-bit pointer) */
3613   uint32_t protocol_name;    /* char * (32-bit pointer) */
3614   uint32_t protocol_list;    /* struct objc_protocol_list * (32-bit pointer) */
3615   uint32_t instance_methods; /* struct objc_method_description_list *
3616                                 (32-bit pointer) */
3617   uint32_t class_methods;    /* struct objc_method_description_list *
3618                                 (32-bit pointer) */
3619 };
3620
3621 struct objc_method_description_list_t {
3622   int32_t count;
3623   // struct objc_method_description_t list[1];
3624 };
3625
3626 struct objc_method_description_t {
3627   uint32_t name;  /* SEL, aka struct objc_selector * (32-bit pointer) */
3628   uint32_t types; /* char * (32-bit pointer) */
3629 };
3630
3631 inline void swapStruct(struct cfstring64_t &cfs) {
3632   sys::swapByteOrder(cfs.isa);
3633   sys::swapByteOrder(cfs.flags);
3634   sys::swapByteOrder(cfs.characters);
3635   sys::swapByteOrder(cfs.length);
3636 }
3637
3638 inline void swapStruct(struct class64_t &c) {
3639   sys::swapByteOrder(c.isa);
3640   sys::swapByteOrder(c.superclass);
3641   sys::swapByteOrder(c.cache);
3642   sys::swapByteOrder(c.vtable);
3643   sys::swapByteOrder(c.data);
3644 }
3645
3646 inline void swapStruct(struct class32_t &c) {
3647   sys::swapByteOrder(c.isa);
3648   sys::swapByteOrder(c.superclass);
3649   sys::swapByteOrder(c.cache);
3650   sys::swapByteOrder(c.vtable);
3651   sys::swapByteOrder(c.data);
3652 }
3653
3654 inline void swapStruct(struct class_ro64_t &cro) {
3655   sys::swapByteOrder(cro.flags);
3656   sys::swapByteOrder(cro.instanceStart);
3657   sys::swapByteOrder(cro.instanceSize);
3658   sys::swapByteOrder(cro.reserved);
3659   sys::swapByteOrder(cro.ivarLayout);
3660   sys::swapByteOrder(cro.name);
3661   sys::swapByteOrder(cro.baseMethods);
3662   sys::swapByteOrder(cro.baseProtocols);
3663   sys::swapByteOrder(cro.ivars);
3664   sys::swapByteOrder(cro.weakIvarLayout);
3665   sys::swapByteOrder(cro.baseProperties);
3666 }
3667
3668 inline void swapStruct(struct class_ro32_t &cro) {
3669   sys::swapByteOrder(cro.flags);
3670   sys::swapByteOrder(cro.instanceStart);
3671   sys::swapByteOrder(cro.instanceSize);
3672   sys::swapByteOrder(cro.ivarLayout);
3673   sys::swapByteOrder(cro.name);
3674   sys::swapByteOrder(cro.baseMethods);
3675   sys::swapByteOrder(cro.baseProtocols);
3676   sys::swapByteOrder(cro.ivars);
3677   sys::swapByteOrder(cro.weakIvarLayout);
3678   sys::swapByteOrder(cro.baseProperties);
3679 }
3680
3681 inline void swapStruct(struct method_list64_t &ml) {
3682   sys::swapByteOrder(ml.entsize);
3683   sys::swapByteOrder(ml.count);
3684 }
3685
3686 inline void swapStruct(struct method_list32_t &ml) {
3687   sys::swapByteOrder(ml.entsize);
3688   sys::swapByteOrder(ml.count);
3689 }
3690
3691 inline void swapStruct(struct method64_t &m) {
3692   sys::swapByteOrder(m.name);
3693   sys::swapByteOrder(m.types);
3694   sys::swapByteOrder(m.imp);
3695 }
3696
3697 inline void swapStruct(struct method32_t &m) {
3698   sys::swapByteOrder(m.name);
3699   sys::swapByteOrder(m.types);
3700   sys::swapByteOrder(m.imp);
3701 }
3702
3703 inline void swapStruct(struct protocol_list64_t &pl) {
3704   sys::swapByteOrder(pl.count);
3705 }
3706
3707 inline void swapStruct(struct protocol_list32_t &pl) {
3708   sys::swapByteOrder(pl.count);
3709 }
3710
3711 inline void swapStruct(struct protocol64_t &p) {
3712   sys::swapByteOrder(p.isa);
3713   sys::swapByteOrder(p.name);
3714   sys::swapByteOrder(p.protocols);
3715   sys::swapByteOrder(p.instanceMethods);
3716   sys::swapByteOrder(p.classMethods);
3717   sys::swapByteOrder(p.optionalInstanceMethods);
3718   sys::swapByteOrder(p.optionalClassMethods);
3719   sys::swapByteOrder(p.instanceProperties);
3720 }
3721
3722 inline void swapStruct(struct protocol32_t &p) {
3723   sys::swapByteOrder(p.isa);
3724   sys::swapByteOrder(p.name);
3725   sys::swapByteOrder(p.protocols);
3726   sys::swapByteOrder(p.instanceMethods);
3727   sys::swapByteOrder(p.classMethods);
3728   sys::swapByteOrder(p.optionalInstanceMethods);
3729   sys::swapByteOrder(p.optionalClassMethods);
3730   sys::swapByteOrder(p.instanceProperties);
3731 }
3732
3733 inline void swapStruct(struct ivar_list64_t &il) {
3734   sys::swapByteOrder(il.entsize);
3735   sys::swapByteOrder(il.count);
3736 }
3737
3738 inline void swapStruct(struct ivar_list32_t &il) {
3739   sys::swapByteOrder(il.entsize);
3740   sys::swapByteOrder(il.count);
3741 }
3742
3743 inline void swapStruct(struct ivar64_t &i) {
3744   sys::swapByteOrder(i.offset);
3745   sys::swapByteOrder(i.name);
3746   sys::swapByteOrder(i.type);
3747   sys::swapByteOrder(i.alignment);
3748   sys::swapByteOrder(i.size);
3749 }
3750
3751 inline void swapStruct(struct ivar32_t &i) {
3752   sys::swapByteOrder(i.offset);
3753   sys::swapByteOrder(i.name);
3754   sys::swapByteOrder(i.type);
3755   sys::swapByteOrder(i.alignment);
3756   sys::swapByteOrder(i.size);
3757 }
3758
3759 inline void swapStruct(struct objc_property_list64 &pl) {
3760   sys::swapByteOrder(pl.entsize);
3761   sys::swapByteOrder(pl.count);
3762 }
3763
3764 inline void swapStruct(struct objc_property_list32 &pl) {
3765   sys::swapByteOrder(pl.entsize);
3766   sys::swapByteOrder(pl.count);
3767 }
3768
3769 inline void swapStruct(struct objc_property64 &op) {
3770   sys::swapByteOrder(op.name);
3771   sys::swapByteOrder(op.attributes);
3772 }
3773
3774 inline void swapStruct(struct objc_property32 &op) {
3775   sys::swapByteOrder(op.name);
3776   sys::swapByteOrder(op.attributes);
3777 }
3778
3779 inline void swapStruct(struct category64_t &c) {
3780   sys::swapByteOrder(c.name);
3781   sys::swapByteOrder(c.cls);
3782   sys::swapByteOrder(c.instanceMethods);
3783   sys::swapByteOrder(c.classMethods);
3784   sys::swapByteOrder(c.protocols);
3785   sys::swapByteOrder(c.instanceProperties);
3786 }
3787
3788 inline void swapStruct(struct category32_t &c) {
3789   sys::swapByteOrder(c.name);
3790   sys::swapByteOrder(c.cls);
3791   sys::swapByteOrder(c.instanceMethods);
3792   sys::swapByteOrder(c.classMethods);
3793   sys::swapByteOrder(c.protocols);
3794   sys::swapByteOrder(c.instanceProperties);
3795 }
3796
3797 inline void swapStruct(struct objc_image_info64 &o) {
3798   sys::swapByteOrder(o.version);
3799   sys::swapByteOrder(o.flags);
3800 }
3801
3802 inline void swapStruct(struct objc_image_info32 &o) {
3803   sys::swapByteOrder(o.version);
3804   sys::swapByteOrder(o.flags);
3805 }
3806
3807 inline void swapStruct(struct imageInfo_t &o) {
3808   sys::swapByteOrder(o.version);
3809   sys::swapByteOrder(o.flags);
3810 }
3811
3812 inline void swapStruct(struct message_ref64 &mr) {
3813   sys::swapByteOrder(mr.imp);
3814   sys::swapByteOrder(mr.sel);
3815 }
3816
3817 inline void swapStruct(struct message_ref32 &mr) {
3818   sys::swapByteOrder(mr.imp);
3819   sys::swapByteOrder(mr.sel);
3820 }
3821
3822 inline void swapStruct(struct objc_module_t &module) {
3823   sys::swapByteOrder(module.version);
3824   sys::swapByteOrder(module.size);
3825   sys::swapByteOrder(module.name);
3826   sys::swapByteOrder(module.symtab);
3827 }
3828
3829 inline void swapStruct(struct objc_symtab_t &symtab) {
3830   sys::swapByteOrder(symtab.sel_ref_cnt);
3831   sys::swapByteOrder(symtab.refs);
3832   sys::swapByteOrder(symtab.cls_def_cnt);
3833   sys::swapByteOrder(symtab.cat_def_cnt);
3834 }
3835
3836 inline void swapStruct(struct objc_class_t &objc_class) {
3837   sys::swapByteOrder(objc_class.isa);
3838   sys::swapByteOrder(objc_class.super_class);
3839   sys::swapByteOrder(objc_class.name);
3840   sys::swapByteOrder(objc_class.version);
3841   sys::swapByteOrder(objc_class.info);
3842   sys::swapByteOrder(objc_class.instance_size);
3843   sys::swapByteOrder(objc_class.ivars);
3844   sys::swapByteOrder(objc_class.methodLists);
3845   sys::swapByteOrder(objc_class.cache);
3846   sys::swapByteOrder(objc_class.protocols);
3847 }
3848
3849 inline void swapStruct(struct objc_category_t &objc_category) {
3850   sys::swapByteOrder(objc_category.category_name);
3851   sys::swapByteOrder(objc_category.class_name);
3852   sys::swapByteOrder(objc_category.instance_methods);
3853   sys::swapByteOrder(objc_category.class_methods);
3854   sys::swapByteOrder(objc_category.protocols);
3855 }
3856
3857 inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3858   sys::swapByteOrder(objc_ivar_list.ivar_count);
3859 }
3860
3861 inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3862   sys::swapByteOrder(objc_ivar.ivar_name);
3863   sys::swapByteOrder(objc_ivar.ivar_type);
3864   sys::swapByteOrder(objc_ivar.ivar_offset);
3865 }
3866
3867 inline void swapStruct(struct objc_method_list_t &method_list) {
3868   sys::swapByteOrder(method_list.obsolete);
3869   sys::swapByteOrder(method_list.method_count);
3870 }
3871
3872 inline void swapStruct(struct objc_method_t &method) {
3873   sys::swapByteOrder(method.method_name);
3874   sys::swapByteOrder(method.method_types);
3875   sys::swapByteOrder(method.method_imp);
3876 }
3877
3878 inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3879   sys::swapByteOrder(protocol_list.next);
3880   sys::swapByteOrder(protocol_list.count);
3881 }
3882
3883 inline void swapStruct(struct objc_protocol_t &protocol) {
3884   sys::swapByteOrder(protocol.isa);
3885   sys::swapByteOrder(protocol.protocol_name);
3886   sys::swapByteOrder(protocol.protocol_list);
3887   sys::swapByteOrder(protocol.instance_methods);
3888   sys::swapByteOrder(protocol.class_methods);
3889 }
3890
3891 inline void swapStruct(struct objc_method_description_list_t &mdl) {
3892   sys::swapByteOrder(mdl.count);
3893 }
3894
3895 inline void swapStruct(struct objc_method_description_t &md) {
3896   sys::swapByteOrder(md.name);
3897   sys::swapByteOrder(md.types);
3898 }
3899
3900 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3901                                                  struct DisassembleInfo *info);
3902
3903 // get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3904 // to an Objective-C class and returns the class name.  It is also passed the
3905 // address of the pointer, so when the pointer is zero as it can be in an .o
3906 // file, that is used to look for an external relocation entry with a symbol
3907 // name.
3908 static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3909                                               uint64_t ReferenceValue,
3910                                               struct DisassembleInfo *info) {
3911   const char *r;
3912   uint32_t offset, left;
3913   SectionRef S;
3914
3915   // The pointer_value can be 0 in an object file and have a relocation
3916   // entry for the class symbol at the ReferenceValue (the address of the
3917   // pointer).
3918   if (pointer_value == 0) {
3919     r = get_pointer_64(ReferenceValue, offset, left, S, info);
3920     if (r == nullptr || left < sizeof(uint64_t))
3921       return nullptr;
3922     uint64_t n_value;
3923     const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3924     if (symbol_name == nullptr)
3925       return nullptr;
3926     const char *class_name = strrchr(symbol_name, '$');
3927     if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
3928       return class_name + 2;
3929     else
3930       return nullptr;
3931   }
3932
3933   // The case were the pointer_value is non-zero and points to a class defined
3934   // in this Mach-O file.
3935   r = get_pointer_64(pointer_value, offset, left, S, info);
3936   if (r == nullptr || left < sizeof(struct class64_t))
3937     return nullptr;
3938   struct class64_t c;
3939   memcpy(&c, r, sizeof(struct class64_t));
3940   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3941     swapStruct(c);
3942   if (c.data == 0)
3943     return nullptr;
3944   r = get_pointer_64(c.data, offset, left, S, info);
3945   if (r == nullptr || left < sizeof(struct class_ro64_t))
3946     return nullptr;
3947   struct class_ro64_t cro;
3948   memcpy(&cro, r, sizeof(struct class_ro64_t));
3949   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3950     swapStruct(cro);
3951   if (cro.name == 0)
3952     return nullptr;
3953   const char *name = get_pointer_64(cro.name, offset, left, S, info);
3954   return name;
3955 }
3956
3957 // get_objc2_64bit_cfstring_name is used for disassembly and is passed a
3958 // pointer to a cfstring and returns its name or nullptr.
3959 static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
3960                                                  struct DisassembleInfo *info) {
3961   const char *r, *name;
3962   uint32_t offset, left;
3963   SectionRef S;
3964   struct cfstring64_t cfs;
3965   uint64_t cfs_characters;
3966
3967   r = get_pointer_64(ReferenceValue, offset, left, S, info);
3968   if (r == nullptr || left < sizeof(struct cfstring64_t))
3969     return nullptr;
3970   memcpy(&cfs, r, sizeof(struct cfstring64_t));
3971   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3972     swapStruct(cfs);
3973   if (cfs.characters == 0) {
3974     uint64_t n_value;
3975     const char *symbol_name = get_symbol_64(
3976         offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
3977     if (symbol_name == nullptr)
3978       return nullptr;
3979     cfs_characters = n_value;
3980   } else
3981     cfs_characters = cfs.characters;
3982   name = get_pointer_64(cfs_characters, offset, left, S, info);
3983
3984   return name;
3985 }
3986
3987 // get_objc2_64bit_selref() is used for disassembly and is passed a the address
3988 // of a pointer to an Objective-C selector reference when the pointer value is
3989 // zero as in a .o file and is likely to have a external relocation entry with
3990 // who's symbol's n_value is the real pointer to the selector name.  If that is
3991 // the case the real pointer to the selector name is returned else 0 is
3992 // returned
3993 static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
3994                                        struct DisassembleInfo *info) {
3995   uint32_t offset, left;
3996   SectionRef S;
3997
3998   const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
3999   if (r == nullptr || left < sizeof(uint64_t))
4000     return 0;
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 0;
4005   return n_value;
4006 }
4007
4008 static const SectionRef get_section(MachOObjectFile *O, const char *segname,
4009                                     const char *sectname) {
4010   for (const SectionRef &Section : O->sections()) {
4011     StringRef SectName;
4012     Section.getName(SectName);
4013     DataRefImpl Ref = Section.getRawDataRefImpl();
4014     StringRef SegName = O->getSectionFinalSegmentName(Ref);
4015     if (SegName == segname && SectName == sectname)
4016       return Section;
4017   }
4018   return SectionRef();
4019 }
4020
4021 static void
4022 walk_pointer_list_64(const char *listname, const SectionRef S,
4023                      MachOObjectFile *O, struct DisassembleInfo *info,
4024                      void (*func)(uint64_t, struct DisassembleInfo *info)) {
4025   if (S == SectionRef())
4026     return;
4027
4028   StringRef SectName;
4029   S.getName(SectName);
4030   DataRefImpl Ref = S.getRawDataRefImpl();
4031   StringRef SegName = O->getSectionFinalSegmentName(Ref);
4032   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4033
4034   StringRef BytesStr = unwrapOrError(S.getContents(), O->getFileName());
4035   const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
4036
4037   for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
4038     uint32_t left = S.getSize() - i;
4039     uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
4040     uint64_t p = 0;
4041     memcpy(&p, Contents + i, size);
4042     if (i + sizeof(uint64_t) > S.getSize())
4043       outs() << listname << " list pointer extends past end of (" << SegName
4044              << "," << SectName << ") section\n";
4045     outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
4046
4047     if (O->isLittleEndian() != sys::IsLittleEndianHost)
4048       sys::swapByteOrder(p);
4049
4050     uint64_t n_value = 0;
4051     const char *name = get_symbol_64(i, S, info, n_value, p);
4052     if (name == nullptr)
4053       name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
4054
4055     if (n_value != 0) {
4056       outs() << format("0x%" PRIx64, n_value);
4057       if (p != 0)
4058         outs() << " + " << format("0x%" PRIx64, p);
4059     } else
4060       outs() << format("0x%" PRIx64, p);
4061     if (name != nullptr)
4062       outs() << " " << name;
4063     outs() << "\n";
4064
4065     p += n_value;
4066     if (func)
4067       func(p, info);
4068   }
4069 }
4070
4071 static void
4072 walk_pointer_list_32(const char *listname, const SectionRef S,
4073                      MachOObjectFile *O, struct DisassembleInfo *info,
4074                      void (*func)(uint32_t, struct DisassembleInfo *info)) {
4075   if (S == SectionRef())
4076     return;
4077
4078   StringRef SectName;
4079   S.getName(SectName);
4080   DataRefImpl Ref = S.getRawDataRefImpl();
4081   StringRef SegName = O->getSectionFinalSegmentName(Ref);
4082   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4083
4084   StringRef BytesStr = unwrapOrError(S.getContents(), O->getFileName());
4085   const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
4086
4087   for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
4088     uint32_t left = S.getSize() - i;
4089     uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
4090     uint32_t p = 0;
4091     memcpy(&p, Contents + i, size);
4092     if (i + sizeof(uint32_t) > S.getSize())
4093       outs() << listname << " list pointer extends past end of (" << SegName
4094              << "," << SectName << ") section\n";
4095     uint32_t Address = S.getAddress() + i;
4096     outs() << format("%08" PRIx32, Address) << " ";
4097
4098     if (O->isLittleEndian() != sys::IsLittleEndianHost)
4099       sys::swapByteOrder(p);
4100     outs() << format("0x%" PRIx32, p);
4101
4102     const char *name = get_symbol_32(i, S, info, p);
4103     if (name != nullptr)
4104       outs() << " " << name;
4105     outs() << "\n";
4106
4107     if (func)
4108       func(p, info);
4109   }
4110 }
4111
4112 static void print_layout_map(const char *layout_map, uint32_t left) {
4113   if (layout_map == nullptr)
4114     return;
4115   outs() << "                layout map: ";
4116   do {
4117     outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
4118     left--;
4119     layout_map++;
4120   } while (*layout_map != '\0' && left != 0);
4121   outs() << "\n";
4122 }
4123
4124 static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
4125   uint32_t offset, left;
4126   SectionRef S;
4127   const char *layout_map;
4128
4129   if (p == 0)
4130     return;
4131   layout_map = get_pointer_64(p, offset, left, S, info);
4132   print_layout_map(layout_map, left);
4133 }
4134
4135 static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
4136   uint32_t offset, left;
4137   SectionRef S;
4138   const char *layout_map;
4139
4140   if (p == 0)
4141     return;
4142   layout_map = get_pointer_32(p, offset, left, S, info);
4143   print_layout_map(layout_map, left);
4144 }
4145
4146 static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
4147                                   const char *indent) {
4148   struct method_list64_t ml;
4149   struct method64_t m;
4150   const char *r;
4151   uint32_t offset, xoffset, left, i;
4152   SectionRef S, xS;
4153   const char *name, *sym_name;
4154   uint64_t n_value;
4155
4156   r = get_pointer_64(p, offset, left, S, info);
4157   if (r == nullptr)
4158     return;
4159   memset(&ml, '\0', sizeof(struct method_list64_t));
4160   if (left < sizeof(struct method_list64_t)) {
4161     memcpy(&ml, r, left);
4162     outs() << "   (method_list_t entends past the end of the section)\n";
4163   } else
4164     memcpy(&ml, r, sizeof(struct method_list64_t));
4165   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4166     swapStruct(ml);
4167   outs() << indent << "\t\t   entsize " << ml.entsize << "\n";
4168   outs() << indent << "\t\t     count " << ml.count << "\n";
4169
4170   p += sizeof(struct method_list64_t);
4171   offset += sizeof(struct method_list64_t);
4172   for (i = 0; i < ml.count; i++) {
4173     r = get_pointer_64(p, offset, left, S, info);
4174     if (r == nullptr)
4175       return;
4176     memset(&m, '\0', sizeof(struct method64_t));
4177     if (left < sizeof(struct method64_t)) {
4178       memcpy(&m, r, left);
4179       outs() << indent << "   (method_t extends past the end of the section)\n";
4180     } else
4181       memcpy(&m, r, sizeof(struct method64_t));
4182     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4183       swapStruct(m);
4184
4185     outs() << indent << "\t\t      name ";
4186     sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
4187                              info, n_value, m.name);
4188     if (n_value != 0) {
4189       if (info->verbose && sym_name != nullptr)
4190         outs() << sym_name;
4191       else
4192         outs() << format("0x%" PRIx64, n_value);
4193       if (m.name != 0)
4194         outs() << " + " << format("0x%" PRIx64, m.name);
4195     } else
4196       outs() << format("0x%" PRIx64, m.name);
4197     name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
4198     if (name != nullptr)
4199       outs() << format(" %.*s", left, name);
4200     outs() << "\n";
4201
4202     outs() << indent << "\t\t     types ";
4203     sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
4204                              info, n_value, m.types);
4205     if (n_value != 0) {
4206       if (info->verbose && sym_name != nullptr)
4207         outs() << sym_name;
4208       else
4209         outs() << format("0x%" PRIx64, n_value);
4210       if (m.types != 0)
4211         outs() << " + " << format("0x%" PRIx64, m.types);
4212     } else
4213       outs() << format("0x%" PRIx64, m.types);
4214     name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
4215     if (name != nullptr)
4216       outs() << format(" %.*s", left, name);
4217     outs() << "\n";
4218
4219     outs() << indent << "\t\t       imp ";
4220     name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
4221                          n_value, m.imp);
4222     if (info->verbose && name == nullptr) {
4223       if (n_value != 0) {
4224         outs() << format("0x%" PRIx64, n_value) << " ";
4225         if (m.imp != 0)
4226           outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
4227       } else
4228         outs() << format("0x%" PRIx64, m.imp) << " ";
4229     }
4230     if (name != nullptr)
4231       outs() << name;
4232     outs() << "\n";
4233
4234     p += sizeof(struct method64_t);
4235     offset += sizeof(struct method64_t);
4236   }
4237 }
4238
4239 static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
4240                                   const char *indent) {
4241   struct method_list32_t ml;
4242   struct method32_t m;
4243   const char *r, *name;
4244   uint32_t offset, xoffset, left, i;
4245   SectionRef S, xS;
4246
4247   r = get_pointer_32(p, offset, left, S, info);
4248   if (r == nullptr)
4249     return;
4250   memset(&ml, '\0', sizeof(struct method_list32_t));
4251   if (left < sizeof(struct method_list32_t)) {
4252     memcpy(&ml, r, left);
4253     outs() << "   (method_list_t entends past the end of the section)\n";
4254   } else
4255     memcpy(&ml, r, sizeof(struct method_list32_t));
4256   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4257     swapStruct(ml);
4258   outs() << indent << "\t\t   entsize " << ml.entsize << "\n";
4259   outs() << indent << "\t\t     count " << ml.count << "\n";
4260
4261   p += sizeof(struct method_list32_t);
4262   offset += sizeof(struct method_list32_t);
4263   for (i = 0; i < ml.count; i++) {
4264     r = get_pointer_32(p, offset, left, S, info);
4265     if (r == nullptr)
4266       return;
4267     memset(&m, '\0', sizeof(struct method32_t));
4268     if (left < sizeof(struct method32_t)) {
4269       memcpy(&ml, r, left);
4270       outs() << indent << "   (method_t entends past the end of the section)\n";
4271     } else
4272       memcpy(&m, r, sizeof(struct method32_t));
4273     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4274       swapStruct(m);
4275
4276     outs() << indent << "\t\t      name " << format("0x%" PRIx32, m.name);
4277     name = get_pointer_32(m.name, xoffset, left, xS, info);
4278     if (name != nullptr)
4279       outs() << format(" %.*s", left, name);
4280     outs() << "\n";
4281
4282     outs() << indent << "\t\t     types " << format("0x%" PRIx32, m.types);
4283     name = get_pointer_32(m.types, xoffset, left, xS, info);
4284     if (name != nullptr)
4285       outs() << format(" %.*s", left, name);
4286     outs() << "\n";
4287
4288     outs() << indent << "\t\t       imp " << format("0x%" PRIx32, m.imp);
4289     name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
4290                          m.imp);
4291     if (name != nullptr)
4292       outs() << " " << name;
4293     outs() << "\n";
4294
4295     p += sizeof(struct method32_t);
4296     offset += sizeof(struct method32_t);
4297   }
4298 }
4299
4300 static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
4301   uint32_t offset, left, xleft;
4302   SectionRef S;
4303   struct objc_method_list_t method_list;
4304   struct objc_method_t method;
4305   const char *r, *methods, *name, *SymbolName;
4306   int32_t i;
4307
4308   r = get_pointer_32(p, offset, left, S, info, true);
4309   if (r == nullptr)
4310     return true;
4311
4312   outs() << "\n";
4313   if (left > sizeof(struct objc_method_list_t)) {
4314     memcpy(&method_list, r, sizeof(struct objc_method_list_t));
4315   } else {
4316     outs() << "\t\t objc_method_list extends past end of the section\n";
4317     memset(&method_list, '\0', sizeof(struct objc_method_list_t));
4318     memcpy(&method_list, r, left);
4319   }
4320   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4321     swapStruct(method_list);
4322
4323   outs() << "\t\t         obsolete "
4324          << format("0x%08" PRIx32, method_list.obsolete) << "\n";
4325   outs() << "\t\t     method_count " << method_list.method_count << "\n";
4326
4327   methods = r + sizeof(struct objc_method_list_t);
4328   for (i = 0; i < method_list.method_count; i++) {
4329     if ((i + 1) * sizeof(struct objc_method_t) > left) {
4330       outs() << "\t\t remaining method's extend past the of the section\n";
4331       break;
4332     }
4333     memcpy(&method, methods + i * sizeof(struct objc_method_t),
4334            sizeof(struct objc_method_t));
4335     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4336       swapStruct(method);
4337
4338     outs() << "\t\t      method_name "
4339            << format("0x%08" PRIx32, method.method_name);
4340     if (info->verbose) {
4341       name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
4342       if (name != nullptr)
4343         outs() << format(" %.*s", xleft, name);
4344       else
4345         outs() << " (not in an __OBJC section)";
4346     }
4347     outs() << "\n";
4348
4349     outs() << "\t\t     method_types "
4350            << format("0x%08" PRIx32, method.method_types);
4351     if (info->verbose) {
4352       name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
4353       if (name != nullptr)
4354         outs() << format(" %.*s", xleft, name);
4355       else
4356         outs() << " (not in an __OBJC section)";
4357     }
4358     outs() << "\n";
4359
4360     outs() << "\t\t       method_imp "
4361            << format("0x%08" PRIx32, method.method_imp) << " ";
4362     if (info->verbose) {
4363       SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
4364       if (SymbolName != nullptr)
4365         outs() << SymbolName;
4366     }
4367     outs() << "\n";
4368   }
4369   return false;
4370 }
4371
4372 static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
4373   struct protocol_list64_t pl;
4374   uint64_t q, n_value;
4375   struct protocol64_t pc;
4376   const char *r;
4377   uint32_t offset, xoffset, left, i;
4378   SectionRef S, xS;
4379   const char *name, *sym_name;
4380
4381   r = get_pointer_64(p, offset, left, S, info);
4382   if (r == nullptr)
4383     return;
4384   memset(&pl, '\0', sizeof(struct protocol_list64_t));
4385   if (left < sizeof(struct protocol_list64_t)) {
4386     memcpy(&pl, r, left);
4387     outs() << "   (protocol_list_t entends past the end of the section)\n";
4388   } else
4389     memcpy(&pl, r, sizeof(struct protocol_list64_t));
4390   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4391     swapStruct(pl);
4392   outs() << "                      count " << pl.count << "\n";
4393
4394   p += sizeof(struct protocol_list64_t);
4395   offset += sizeof(struct protocol_list64_t);
4396   for (i = 0; i < pl.count; i++) {
4397     r = get_pointer_64(p, offset, left, S, info);
4398     if (r == nullptr)
4399       return;
4400     q = 0;
4401     if (left < sizeof(uint64_t)) {
4402       memcpy(&q, r, left);
4403       outs() << "   (protocol_t * entends past the end of the section)\n";
4404     } else
4405       memcpy(&q, r, sizeof(uint64_t));
4406     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4407       sys::swapByteOrder(q);
4408
4409     outs() << "\t\t      list[" << i << "] ";
4410     sym_name = get_symbol_64(offset, S, info, n_value, q);
4411     if (n_value != 0) {
4412       if (info->verbose && sym_name != nullptr)
4413         outs() << sym_name;
4414       else
4415         outs() << format("0x%" PRIx64, n_value);
4416       if (q != 0)
4417         outs() << " + " << format("0x%" PRIx64, q);
4418     } else
4419       outs() << format("0x%" PRIx64, q);
4420     outs() << " (struct protocol_t *)\n";
4421
4422     r = get_pointer_64(q + n_value, offset, left, S, info);
4423     if (r == nullptr)
4424       return;
4425     memset(&pc, '\0', sizeof(struct protocol64_t));
4426     if (left < sizeof(struct protocol64_t)) {
4427       memcpy(&pc, r, left);
4428       outs() << "   (protocol_t entends past the end of the section)\n";
4429     } else
4430       memcpy(&pc, r, sizeof(struct protocol64_t));
4431     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4432       swapStruct(pc);
4433
4434     outs() << "\t\t\t      isa " << format("0x%" PRIx64, pc.isa) << "\n";
4435
4436     outs() << "\t\t\t     name ";
4437     sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
4438                              info, n_value, pc.name);
4439     if (n_value != 0) {
4440       if (info->verbose && sym_name != nullptr)
4441         outs() << sym_name;
4442       else
4443         outs() << format("0x%" PRIx64, n_value);
4444       if (pc.name != 0)
4445         outs() << " + " << format("0x%" PRIx64, pc.name);
4446     } else
4447       outs() << format("0x%" PRIx64, pc.name);
4448     name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
4449     if (name != nullptr)
4450       outs() << format(" %.*s", left, name);
4451     outs() << "\n";
4452
4453     outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
4454
4455     outs() << "\t\t  instanceMethods ";
4456     sym_name =
4457         get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
4458                       S, info, n_value, pc.instanceMethods);
4459     if (n_value != 0) {
4460       if (info->verbose && sym_name != nullptr)
4461         outs() << sym_name;
4462       else
4463         outs() << format("0x%" PRIx64, n_value);
4464       if (pc.instanceMethods != 0)
4465         outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
4466     } else
4467       outs() << format("0x%" PRIx64, pc.instanceMethods);
4468     outs() << " (struct method_list_t *)\n";
4469     if (pc.instanceMethods + n_value != 0)
4470       print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
4471
4472     outs() << "\t\t     classMethods ";
4473     sym_name =
4474         get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
4475                       info, n_value, pc.classMethods);
4476     if (n_value != 0) {
4477       if (info->verbose && sym_name != nullptr)
4478         outs() << sym_name;
4479       else
4480         outs() << format("0x%" PRIx64, n_value);
4481       if (pc.classMethods != 0)
4482         outs() << " + " << format("0x%" PRIx64, pc.classMethods);
4483     } else
4484       outs() << format("0x%" PRIx64, pc.classMethods);
4485     outs() << " (struct method_list_t *)\n";
4486     if (pc.classMethods + n_value != 0)
4487       print_method_list64_t(pc.classMethods + n_value, info, "\t");
4488
4489     outs() << "\t  optionalInstanceMethods "
4490            << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
4491     outs() << "\t     optionalClassMethods "
4492            << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
4493     outs() << "\t       instanceProperties "
4494            << format("0x%" PRIx64, pc.instanceProperties) << "\n";
4495
4496     p += sizeof(uint64_t);
4497     offset += sizeof(uint64_t);
4498   }
4499 }
4500
4501 static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
4502   struct protocol_list32_t pl;
4503   uint32_t q;
4504   struct protocol32_t pc;
4505   const char *r;
4506   uint32_t offset, xoffset, left, i;
4507   SectionRef S, xS;
4508   const char *name;
4509
4510   r = get_pointer_32(p, offset, left, S, info);
4511   if (r == nullptr)
4512     return;
4513   memset(&pl, '\0', sizeof(struct protocol_list32_t));
4514   if (left < sizeof(struct protocol_list32_t)) {
4515     memcpy(&pl, r, left);
4516     outs() << "   (protocol_list_t entends past the end of the section)\n";
4517   } else
4518     memcpy(&pl, r, sizeof(struct protocol_list32_t));
4519   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4520     swapStruct(pl);
4521   outs() << "                      count " << pl.count << "\n";
4522
4523   p += sizeof(struct protocol_list32_t);
4524   offset += sizeof(struct protocol_list32_t);
4525   for (i = 0; i < pl.count; i++) {
4526     r = get_pointer_32(p, offset, left, S, info);
4527     if (r == nullptr)
4528       return;
4529     q = 0;
4530     if (left < sizeof(uint32_t)) {
4531       memcpy(&q, r, left);
4532       outs() << "   (protocol_t * entends past the end of the section)\n";
4533     } else
4534       memcpy(&q, r, sizeof(uint32_t));
4535     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4536       sys::swapByteOrder(q);
4537     outs() << "\t\t      list[" << i << "] " << format("0x%" PRIx32, q)
4538            << " (struct protocol_t *)\n";
4539     r = get_pointer_32(q, offset, left, S, info);
4540     if (r == nullptr)
4541       return;
4542     memset(&pc, '\0', sizeof(struct protocol32_t));
4543     if (left < sizeof(struct protocol32_t)) {
4544       memcpy(&pc, r, left);
4545       outs() << "   (protocol_t entends past the end of the section)\n";
4546     } else
4547       memcpy(&pc, r, sizeof(struct protocol32_t));
4548     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4549       swapStruct(pc);
4550     outs() << "\t\t\t      isa " << format("0x%" PRIx32, pc.isa) << "\n";
4551     outs() << "\t\t\t     name " << format("0x%" PRIx32, pc.name);
4552     name = get_pointer_32(pc.name, xoffset, left, xS, info);
4553     if (name != nullptr)
4554       outs() << format(" %.*s", left, name);
4555     outs() << "\n";
4556     outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
4557     outs() << "\t\t  instanceMethods "
4558            << format("0x%" PRIx32, pc.instanceMethods)
4559            << " (struct method_list_t *)\n";
4560     if (pc.instanceMethods != 0)
4561       print_method_list32_t(pc.instanceMethods, info, "\t");
4562     outs() << "\t\t     classMethods " << format("0x%" PRIx32, pc.classMethods)
4563            << " (struct method_list_t *)\n";
4564     if (pc.classMethods != 0)
4565       print_method_list32_t(pc.classMethods, info, "\t");
4566     outs() << "\t  optionalInstanceMethods "
4567            << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
4568     outs() << "\t     optionalClassMethods "
4569            << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
4570     outs() << "\t       instanceProperties "
4571            << format("0x%" PRIx32, pc.instanceProperties) << "\n";
4572     p += sizeof(uint32_t);
4573     offset += sizeof(uint32_t);
4574   }
4575 }
4576
4577 static void print_indent(uint32_t indent) {
4578   for (uint32_t i = 0; i < indent;) {
4579     if (indent - i >= 8) {
4580       outs() << "\t";
4581       i += 8;
4582     } else {
4583       for (uint32_t j = i; j < indent; j++)
4584         outs() << " ";
4585       return;
4586     }
4587   }
4588 }
4589
4590 static bool print_method_description_list(uint32_t p, uint32_t indent,
4591                                           struct DisassembleInfo *info) {
4592   uint32_t offset, left, xleft;
4593   SectionRef S;
4594   struct objc_method_description_list_t mdl;
4595   struct objc_method_description_t md;
4596   const char *r, *list, *name;
4597   int32_t i;
4598
4599   r = get_pointer_32(p, offset, left, S, info, true);
4600   if (r == nullptr)
4601     return true;
4602
4603   outs() << "\n";
4604   if (left > sizeof(struct objc_method_description_list_t)) {
4605     memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
4606   } else {
4607     print_indent(indent);
4608     outs() << " objc_method_description_list extends past end of the section\n";
4609     memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
4610     memcpy(&mdl, r, left);
4611   }
4612   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4613     swapStruct(mdl);
4614
4615   print_indent(indent);
4616   outs() << "        count " << mdl.count << "\n";
4617
4618   list = r + sizeof(struct objc_method_description_list_t);
4619   for (i = 0; i < mdl.count; i++) {
4620     if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
4621       print_indent(indent);
4622       outs() << " remaining list entries extend past the of the section\n";
4623       break;
4624     }
4625     print_indent(indent);
4626     outs() << "        list[" << i << "]\n";
4627     memcpy(&md, list + i * sizeof(struct objc_method_description_t),
4628            sizeof(struct objc_method_description_t));
4629     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4630       swapStruct(md);
4631
4632     print_indent(indent);
4633     outs() << "             name " << format("0x%08" PRIx32, md.name);
4634     if (info->verbose) {
4635       name = get_pointer_32(md.name, offset, xleft, S, info, true);
4636       if (name != nullptr)
4637         outs() << format(" %.*s", xleft, name);
4638       else
4639         outs() << " (not in an __OBJC section)";
4640     }
4641     outs() << "\n";
4642
4643     print_indent(indent);
4644     outs() << "            types " << format("0x%08" PRIx32, md.types);
4645     if (info->verbose) {
4646       name = get_pointer_32(md.types, offset, xleft, S, info, true);
4647       if (name != nullptr)
4648         outs() << format(" %.*s", xleft, name);
4649       else
4650         outs() << " (not in an __OBJC section)";
4651     }
4652     outs() << "\n";
4653   }
4654   return false;
4655 }
4656
4657 static bool print_protocol_list(uint32_t p, uint32_t indent,
4658                                 struct DisassembleInfo *info);
4659
4660 static bool print_protocol(uint32_t p, uint32_t indent,
4661                            struct DisassembleInfo *info) {
4662   uint32_t offset, left;
4663   SectionRef S;
4664   struct objc_protocol_t protocol;
4665   const char *r, *name;
4666
4667   r = get_pointer_32(p, offset, left, S, info, true);
4668   if (r == nullptr)
4669     return true;
4670
4671   outs() << "\n";
4672   if (left >= sizeof(struct objc_protocol_t)) {
4673     memcpy(&protocol, r, sizeof(struct objc_protocol_t));
4674   } else {
4675     print_indent(indent);
4676     outs() << "            Protocol extends past end of the section\n";
4677     memset(&protocol, '\0', sizeof(struct objc_protocol_t));
4678     memcpy(&protocol, r, left);
4679   }
4680   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4681     swapStruct(protocol);
4682
4683   print_indent(indent);
4684   outs() << "              isa " << format("0x%08" PRIx32, protocol.isa)
4685          << "\n";
4686
4687   print_indent(indent);
4688   outs() << "    protocol_name "
4689          << format("0x%08" PRIx32, protocol.protocol_name);
4690   if (info->verbose) {
4691     name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
4692     if (name != nullptr)
4693       outs() << format(" %.*s", left, name);
4694     else
4695       outs() << " (not in an __OBJC section)";
4696   }
4697   outs() << "\n";
4698
4699   print_indent(indent);
4700   outs() << "    protocol_list "
4701          << format("0x%08" PRIx32, protocol.protocol_list);
4702   if (print_protocol_list(protocol.protocol_list, indent + 4, info))
4703     outs() << " (not in an __OBJC section)\n";
4704
4705   print_indent(indent);
4706   outs() << " instance_methods "
4707          << format("0x%08" PRIx32, protocol.instance_methods);
4708   if (print_method_description_list(protocol.instance_methods, indent, info))
4709     outs() << " (not in an __OBJC section)\n";
4710
4711   print_indent(indent);
4712   outs() << "    class_methods "
4713          << format("0x%08" PRIx32, protocol.class_methods);
4714   if (print_method_description_list(protocol.class_methods, indent, info))
4715     outs() << " (not in an __OBJC section)\n";
4716
4717   return false;
4718 }
4719
4720 static bool print_protocol_list(uint32_t p, uint32_t indent,
4721                                 struct DisassembleInfo *info) {
4722   uint32_t offset, left, l;
4723   SectionRef S;
4724   struct objc_protocol_list_t protocol_list;
4725   const char *r, *list;
4726   int32_t i;
4727
4728   r = get_pointer_32(p, offset, left, S, info, true);
4729   if (r == nullptr)
4730     return true;
4731
4732   outs() << "\n";
4733   if (left > sizeof(struct objc_protocol_list_t)) {
4734     memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
4735   } else {
4736     outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
4737     memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
4738     memcpy(&protocol_list, r, left);
4739   }
4740   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4741     swapStruct(protocol_list);
4742
4743   print_indent(indent);
4744   outs() << "         next " << format("0x%08" PRIx32, protocol_list.next)
4745          << "\n";
4746   print_indent(indent);
4747   outs() << "        count " << protocol_list.count << "\n";
4748
4749   list = r + sizeof(struct objc_protocol_list_t);
4750   for (i = 0; i < protocol_list.count; i++) {
4751     if ((i + 1) * sizeof(uint32_t) > left) {
4752       outs() << "\t\t remaining list entries extend past the of the section\n";
4753       break;
4754     }
4755     memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
4756     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4757       sys::swapByteOrder(l);
4758
4759     print_indent(indent);
4760     outs() << "      list[" << i << "] " << format("0x%08" PRIx32, l);
4761     if (print_protocol(l, indent, info))
4762       outs() << "(not in an __OBJC section)\n";
4763   }
4764   return false;
4765 }
4766
4767 static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
4768   struct ivar_list64_t il;
4769   struct ivar64_t i;
4770   const char *r;
4771   uint32_t offset, xoffset, left, j;
4772   SectionRef S, xS;
4773   const char *name, *sym_name, *ivar_offset_p;
4774   uint64_t ivar_offset, n_value;
4775
4776   r = get_pointer_64(p, offset, left, S, info);
4777   if (r == nullptr)
4778     return;
4779   memset(&il, '\0', sizeof(struct ivar_list64_t));
4780   if (left < sizeof(struct ivar_list64_t)) {
4781     memcpy(&il, r, left);
4782     outs() << "   (ivar_list_t entends past the end of the section)\n";
4783   } else
4784     memcpy(&il, r, sizeof(struct ivar_list64_t));
4785   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4786     swapStruct(il);
4787   outs() << "                    entsize " << il.entsize << "\n";
4788   outs() << "                      count " << il.count << "\n";
4789
4790   p += sizeof(struct ivar_list64_t);
4791   offset += sizeof(struct ivar_list64_t);
4792   for (j = 0; j < il.count; j++) {
4793     r = get_pointer_64(p, offset, left, S, info);
4794     if (r == nullptr)
4795       return;
4796     memset(&i, '\0', sizeof(struct ivar64_t));
4797     if (left < sizeof(struct ivar64_t)) {
4798       memcpy(&i, r, left);
4799       outs() << "   (ivar_t entends past the end of the section)\n";
4800     } else
4801       memcpy(&i, r, sizeof(struct ivar64_t));
4802     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4803       swapStruct(i);
4804
4805     outs() << "\t\t\t   offset ";
4806     sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
4807                              info, n_value, i.offset);
4808     if (n_value != 0) {
4809       if (info->verbose && sym_name != nullptr)
4810         outs() << sym_name;
4811       else
4812         outs() << format("0x%" PRIx64, n_value);
4813       if (i.offset != 0)
4814         outs() << " + " << format("0x%" PRIx64, i.offset);
4815     } else
4816       outs() << format("0x%" PRIx64, i.offset);
4817     ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
4818     if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4819       memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4820       if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4821         sys::swapByteOrder(ivar_offset);
4822       outs() << " " << ivar_offset << "\n";
4823     } else
4824       outs() << "\n";
4825
4826     outs() << "\t\t\t     name ";
4827     sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
4828                              n_value, i.name);
4829     if (n_value != 0) {
4830       if (info->verbose && sym_name != nullptr)
4831         outs() << sym_name;
4832       else
4833         outs() << format("0x%" PRIx64, n_value);
4834       if (i.name != 0)
4835         outs() << " + " << format("0x%" PRIx64, i.name);
4836     } else
4837       outs() << format("0x%" PRIx64, i.name);
4838     name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
4839     if (name != nullptr)
4840       outs() << format(" %.*s", left, name);
4841     outs() << "\n";
4842
4843     outs() << "\t\t\t     type ";
4844     sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
4845                              n_value, i.name);
4846     name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
4847     if (n_value != 0) {
4848       if (info->verbose && sym_name != nullptr)
4849         outs() << sym_name;
4850       else
4851         outs() << format("0x%" PRIx64, n_value);
4852       if (i.type != 0)
4853         outs() << " + " << format("0x%" PRIx64, i.type);
4854     } else
4855       outs() << format("0x%" PRIx64, i.type);
4856     if (name != nullptr)
4857       outs() << format(" %.*s", left, name);
4858     outs() << "\n";
4859
4860     outs() << "\t\t\talignment " << i.alignment << "\n";
4861     outs() << "\t\t\t     size " << i.size << "\n";
4862
4863     p += sizeof(struct ivar64_t);
4864     offset += sizeof(struct ivar64_t);
4865   }
4866 }
4867
4868 static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4869   struct ivar_list32_t il;
4870   struct ivar32_t i;
4871   const char *r;
4872   uint32_t offset, xoffset, left, j;
4873   SectionRef S, xS;
4874   const char *name, *ivar_offset_p;
4875   uint32_t ivar_offset;
4876
4877   r = get_pointer_32(p, offset, left, S, info);
4878   if (r == nullptr)
4879     return;
4880   memset(&il, '\0', sizeof(struct ivar_list32_t));
4881   if (left < sizeof(struct ivar_list32_t)) {
4882     memcpy(&il, r, left);
4883     outs() << "   (ivar_list_t entends past the end of the section)\n";
4884   } else
4885     memcpy(&il, r, sizeof(struct ivar_list32_t));
4886   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4887     swapStruct(il);
4888   outs() << "                    entsize " << il.entsize << "\n";
4889   outs() << "                      count " << il.count << "\n";
4890
4891   p += sizeof(struct ivar_list32_t);
4892   offset += sizeof(struct ivar_list32_t);
4893   for (j = 0; j < il.count; j++) {
4894     r = get_pointer_32(p, offset, left, S, info);
4895     if (r == nullptr)
4896       return;
4897     memset(&i, '\0', sizeof(struct ivar32_t));
4898     if (left < sizeof(struct ivar32_t)) {
4899       memcpy(&i, r, left);
4900       outs() << "   (ivar_t entends past the end of the section)\n";
4901     } else
4902       memcpy(&i, r, sizeof(struct ivar32_t));
4903     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4904       swapStruct(i);
4905
4906     outs() << "\t\t\t   offset " << format("0x%" PRIx32, i.offset);
4907     ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4908     if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4909       memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4910       if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4911         sys::swapByteOrder(ivar_offset);
4912       outs() << " " << ivar_offset << "\n";
4913     } else
4914       outs() << "\n";
4915
4916     outs() << "\t\t\t     name " << format("0x%" PRIx32, i.name);
4917     name = get_pointer_32(i.name, xoffset, left, xS, info);
4918     if (name != nullptr)
4919       outs() << format(" %.*s", left, name);
4920     outs() << "\n";
4921
4922     outs() << "\t\t\t     type " << format("0x%" PRIx32, i.type);
4923     name = get_pointer_32(i.type, xoffset, left, xS, info);
4924     if (name != nullptr)
4925       outs() << format(" %.*s", left, name);
4926     outs() << "\n";
4927
4928     outs() << "\t\t\talignment " << i.alignment << "\n";
4929     outs() << "\t\t\t     size " << i.size << "\n";
4930
4931     p += sizeof(struct ivar32_t);
4932     offset += sizeof(struct ivar32_t);
4933   }
4934 }
4935
4936 static void print_objc_property_list64(uint64_t p,
4937                                        struct DisassembleInfo *info) {
4938   struct objc_property_list64 opl;
4939   struct objc_property64 op;
4940   const char *r;
4941   uint32_t offset, xoffset, left, j;
4942   SectionRef S, xS;
4943   const char *name, *sym_name;
4944   uint64_t n_value;
4945
4946   r = get_pointer_64(p, offset, left, S, info);
4947   if (r == nullptr)
4948     return;
4949   memset(&opl, '\0', sizeof(struct objc_property_list64));
4950   if (left < sizeof(struct objc_property_list64)) {
4951     memcpy(&opl, r, left);
4952     outs() << "   (objc_property_list entends past the end of the section)\n";
4953   } else
4954     memcpy(&opl, r, sizeof(struct objc_property_list64));
4955   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4956     swapStruct(opl);
4957   outs() << "                    entsize " << opl.entsize << "\n";
4958   outs() << "                      count " << opl.count << "\n";
4959
4960   p += sizeof(struct objc_property_list64);
4961   offset += sizeof(struct objc_property_list64);
4962   for (j = 0; j < opl.count; j++) {
4963     r = get_pointer_64(p, offset, left, S, info);
4964     if (r == nullptr)
4965       return;
4966     memset(&op, '\0', sizeof(struct objc_property64));
4967     if (left < sizeof(struct objc_property64)) {
4968       memcpy(&op, r, left);
4969       outs() << "   (objc_property entends past the end of the section)\n";
4970     } else
4971       memcpy(&op, r, sizeof(struct objc_property64));
4972     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4973       swapStruct(op);
4974
4975     outs() << "\t\t\t     name ";
4976     sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
4977                              info, n_value, op.name);
4978     if (n_value != 0) {
4979       if (info->verbose && sym_name != nullptr)
4980         outs() << sym_name;
4981       else
4982         outs() << format("0x%" PRIx64, n_value);
4983       if (op.name != 0)
4984         outs() << " + " << format("0x%" PRIx64, op.name);
4985     } else
4986       outs() << format("0x%" PRIx64, op.name);
4987     name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
4988     if (name != nullptr)
4989       outs() << format(" %.*s", left, name);
4990     outs() << "\n";
4991
4992     outs() << "\t\t\tattributes ";
4993     sym_name =
4994         get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
4995                       info, n_value, op.attributes);
4996     if (n_value != 0) {
4997       if (info->verbose && sym_name != nullptr)
4998         outs() << sym_name;
4999       else
5000         outs() << format("0x%" PRIx64, n_value);
5001       if (op.attributes != 0)
5002         outs() << " + " << format("0x%" PRIx64, op.attributes);
5003     } else
5004       outs() << format("0x%" PRIx64, op.attributes);
5005     name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
5006     if (name != nullptr)
5007       outs() << format(" %.*s", left, name);
5008     outs() << "\n";
5009
5010     p += sizeof(struct objc_property64);
5011     offset += sizeof(struct objc_property64);
5012   }
5013 }
5014
5015 static void print_objc_property_list32(uint32_t p,
5016                                        struct DisassembleInfo *info) {
5017   struct objc_property_list32 opl;
5018   struct objc_property32 op;
5019   const char *r;
5020   uint32_t offset, xoffset, left, j;
5021   SectionRef S, xS;
5022   const char *name;
5023
5024   r = get_pointer_32(p, offset, left, S, info);
5025   if (r == nullptr)
5026     return;
5027   memset(&opl, '\0', sizeof(struct objc_property_list32));
5028   if (left < sizeof(struct objc_property_list32)) {
5029     memcpy(&opl, r, left);
5030     outs() << "   (objc_property_list entends past the end of the section)\n";
5031   } else
5032     memcpy(&opl, r, sizeof(struct objc_property_list32));
5033   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5034     swapStruct(opl);
5035   outs() << "                    entsize " << opl.entsize << "\n";
5036   outs() << "                      count " << opl.count << "\n";
5037
5038   p += sizeof(struct objc_property_list32);
5039   offset += sizeof(struct objc_property_list32);
5040   for (j = 0; j < opl.count; j++) {
5041     r = get_pointer_32(p, offset, left, S, info);
5042     if (r == nullptr)
5043       return;
5044     memset(&op, '\0', sizeof(struct objc_property32));
5045     if (left < sizeof(struct objc_property32)) {
5046       memcpy(&op, r, left);
5047       outs() << "   (objc_property entends past the end of the section)\n";
5048     } else
5049       memcpy(&op, r, sizeof(struct objc_property32));
5050     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5051       swapStruct(op);
5052
5053     outs() << "\t\t\t     name " << format("0x%" PRIx32, op.name);
5054     name = get_pointer_32(op.name, xoffset, left, xS, info);
5055     if (name != nullptr)
5056       outs() << format(" %.*s", left, name);
5057     outs() << "\n";
5058
5059     outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
5060     name = get_pointer_32(op.attributes, xoffset, left, xS, info);
5061     if (name != nullptr)
5062       outs() << format(" %.*s", left, name);
5063     outs() << "\n";
5064
5065     p += sizeof(struct objc_property32);
5066     offset += sizeof(struct objc_property32);
5067   }
5068 }
5069
5070 static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
5071                                bool &is_meta_class) {
5072   struct class_ro64_t cro;
5073   const char *r;
5074   uint32_t offset, xoffset, left;
5075   SectionRef S, xS;
5076   const char *name, *sym_name;
5077   uint64_t n_value;
5078
5079   r = get_pointer_64(p, offset, left, S, info);
5080   if (r == nullptr || left < sizeof(struct class_ro64_t))
5081     return false;
5082   memcpy(&cro, r, sizeof(struct class_ro64_t));
5083   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5084     swapStruct(cro);
5085   outs() << "                    flags " << format("0x%" PRIx32, cro.flags);
5086   if (cro.flags & RO_META)
5087     outs() << " RO_META";
5088   if (cro.flags & RO_ROOT)
5089     outs() << " RO_ROOT";
5090   if (cro.flags & RO_HAS_CXX_STRUCTORS)
5091     outs() << " RO_HAS_CXX_STRUCTORS";
5092   outs() << "\n";
5093   outs() << "            instanceStart " << cro.instanceStart << "\n";
5094   outs() << "             instanceSize " << cro.instanceSize << "\n";
5095   outs() << "                 reserved " << format("0x%" PRIx32, cro.reserved)
5096          << "\n";
5097   outs() << "               ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
5098          << "\n";
5099   print_layout_map64(cro.ivarLayout, info);
5100
5101   outs() << "                     name ";
5102   sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
5103                            info, n_value, cro.name);
5104   if (n_value != 0) {
5105     if (info->verbose && sym_name != nullptr)
5106       outs() << sym_name;
5107     else
5108       outs() << format("0x%" PRIx64, n_value);
5109     if (cro.name != 0)
5110       outs() << " + " << format("0x%" PRIx64, cro.name);
5111   } else
5112     outs() << format("0x%" PRIx64, cro.name);
5113   name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
5114   if (name != nullptr)
5115     outs() << format(" %.*s", left, name);
5116   outs() << "\n";
5117
5118   outs() << "              baseMethods ";
5119   sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
5120                            S, info, n_value, cro.baseMethods);
5121   if (n_value != 0) {
5122     if (info->verbose && sym_name != nullptr)
5123       outs() << sym_name;
5124     else
5125       outs() << format("0x%" PRIx64, n_value);
5126     if (cro.baseMethods != 0)
5127       outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
5128   } else
5129     outs() << format("0x%" PRIx64, cro.baseMethods);
5130   outs() << " (struct method_list_t *)\n";
5131   if (cro.baseMethods + n_value != 0)
5132     print_method_list64_t(cro.baseMethods + n_value, info, "");
5133
5134   outs() << "            baseProtocols ";
5135   sym_name =
5136       get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
5137                     info, n_value, cro.baseProtocols);
5138   if (n_value != 0) {
5139     if (info->verbose && sym_name != nullptr)
5140       outs() << sym_name;
5141     else
5142       outs() << format("0x%" PRIx64, n_value);
5143     if (cro.baseProtocols != 0)
5144       outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
5145   } else
5146     outs() << format("0x%" PRIx64, cro.baseProtocols);
5147   outs() << "\n";
5148   if (cro.baseProtocols + n_value != 0)
5149     print_protocol_list64_t(cro.baseProtocols + n_value, info);
5150
5151   outs() << "                    ivars ";
5152   sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
5153                            info, n_value, cro.ivars);
5154   if (n_value != 0) {
5155     if (info->verbose && sym_name != nullptr)
5156       outs() << sym_name;
5157     else
5158       outs() << format("0x%" PRIx64, n_value);
5159     if (cro.ivars != 0)
5160       outs() << " + " << format("0x%" PRIx64, cro.ivars);
5161   } else
5162     outs() << format("0x%" PRIx64, cro.ivars);
5163   outs() << "\n";
5164   if (cro.ivars + n_value != 0)
5165     print_ivar_list64_t(cro.ivars + n_value, info);
5166
5167   outs() << "           weakIvarLayout ";
5168   sym_name =
5169       get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
5170                     info, n_value, cro.weakIvarLayout);
5171   if (n_value != 0) {
5172     if (info->verbose && sym_name != nullptr)
5173       outs() << sym_name;
5174     else
5175       outs() << format("0x%" PRIx64, n_value);
5176     if (cro.weakIvarLayout != 0)
5177       outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
5178   } else
5179     outs() << format("0x%" PRIx64, cro.weakIvarLayout);
5180   outs() << "\n";
5181   print_layout_map64(cro.weakIvarLayout + n_value, info);
5182
5183   outs() << "           baseProperties ";
5184   sym_name =
5185       get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
5186                     info, n_value, cro.baseProperties);
5187   if (n_value != 0) {
5188     if (info->verbose && sym_name != nullptr)
5189       outs() << sym_name;
5190     else
5191       outs() << format("0x%" PRIx64, n_value);
5192     if (cro.baseProperties != 0)
5193       outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
5194   } else
5195     outs() << format("0x%" PRIx64, cro.baseProperties);
5196   outs() << "\n";
5197   if (cro.baseProperties + n_value != 0)
5198     print_objc_property_list64(cro.baseProperties + n_value, info);
5199
5200   is_meta_class = (cro.flags & RO_META) != 0;
5201   return true;
5202 }
5203
5204 static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
5205                                bool &is_meta_class) {
5206   struct class_ro32_t cro;
5207   const char *r;
5208   uint32_t offset, xoffset, left;
5209   SectionRef S, xS;
5210   const char *name;
5211
5212   r = get_pointer_32(p, offset, left, S, info);
5213   if (r == nullptr)
5214     return false;
5215   memset(&cro, '\0', sizeof(struct class_ro32_t));
5216   if (left < sizeof(struct class_ro32_t)) {
5217     memcpy(&cro, r, left);
5218     outs() << "   (class_ro_t entends past the end of the section)\n";
5219   } else
5220     memcpy(&cro, r, sizeof(struct class_ro32_t));
5221   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5222     swapStruct(cro);
5223   outs() << "                    flags " << format("0x%" PRIx32, cro.flags);
5224   if (cro.flags & RO_META)
5225     outs() << " RO_META";
5226   if (cro.flags & RO_ROOT)
5227     outs() << " RO_ROOT";
5228   if (cro.flags & RO_HAS_CXX_STRUCTORS)
5229     outs() << " RO_HAS_CXX_STRUCTORS";
5230   outs() << "\n";
5231   outs() << "            instanceStart " << cro.instanceStart << "\n";
5232   outs() << "             instanceSize " << cro.instanceSize << "\n";
5233   outs() << "               ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
5234          << "\n";
5235   print_layout_map32(cro.ivarLayout, info);
5236
5237   outs() << "                     name " << format("0x%" PRIx32, cro.name);
5238   name = get_pointer_32(cro.name, xoffset, left, xS, info);
5239   if (name != nullptr)
5240     outs() << format(" %.*s", left, name);
5241   outs() << "\n";
5242
5243   outs() << "              baseMethods "
5244          << format("0x%" PRIx32, cro.baseMethods)
5245          << " (struct method_list_t *)\n";
5246   if (cro.baseMethods != 0)
5247     print_method_list32_t(cro.baseMethods, info, "");
5248
5249   outs() << "            baseProtocols "
5250          << format("0x%" PRIx32, cro.baseProtocols) << "\n";
5251   if (cro.baseProtocols != 0)
5252     print_protocol_list32_t(cro.baseProtocols, info);
5253   outs() << "                    ivars " << format("0x%" PRIx32, cro.ivars)
5254          << "\n";
5255   if (cro.ivars != 0)
5256     print_ivar_list32_t(cro.ivars, info);
5257   outs() << "           weakIvarLayout "
5258          << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
5259   print_layout_map32(cro.weakIvarLayout, info);
5260   outs() << "           baseProperties "
5261          << format("0x%" PRIx32, cro.baseProperties) << "\n";
5262   if (cro.baseProperties != 0)
5263     print_objc_property_list32(cro.baseProperties, info);
5264   is_meta_class = (cro.flags & RO_META) != 0;
5265   return true;
5266 }
5267
5268 static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
5269   struct class64_t c;
5270   const char *r;
5271   uint32_t offset, left;
5272   SectionRef S;
5273   const char *name;
5274   uint64_t isa_n_value, n_value;
5275
5276   r = get_pointer_64(p, offset, left, S, info);
5277   if (r == nullptr || left < sizeof(struct class64_t))
5278     return;
5279   memcpy(&c, r, sizeof(struct class64_t));
5280   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5281     swapStruct(c);
5282
5283   outs() << "           isa " << format("0x%" PRIx64, c.isa);
5284   name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
5285                        isa_n_value, c.isa);
5286   if (name != nullptr)
5287     outs() << " " << name;
5288   outs() << "\n";
5289
5290   outs() << "    superclass " << format("0x%" PRIx64, c.superclass);
5291   name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
5292                        n_value, c.superclass);
5293   if (name != nullptr)
5294     outs() << " " << name;
5295   else {
5296     name = get_dyld_bind_info_symbolname(S.getAddress() +
5297              offset + offsetof(struct class64_t, superclass), info);
5298     if (name != nullptr)
5299       outs() << " " << name;
5300   }
5301   outs() << "\n";
5302
5303   outs() << "         cache " << format("0x%" PRIx64, c.cache);
5304   name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
5305                        n_value, c.cache);
5306   if (name != nullptr)
5307     outs() << " " << name;
5308   outs() << "\n";
5309
5310   outs() << "        vtable " << format("0x%" PRIx64, c.vtable);
5311   name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
5312                        n_value, c.vtable);
5313   if (name != nullptr)
5314     outs() << " " << name;
5315   outs() << "\n";
5316
5317   name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
5318                        n_value, c.data);
5319   outs() << "          data ";
5320   if (n_value != 0) {
5321     if (info->verbose && name != nullptr)
5322       outs() << name;
5323     else
5324       outs() << format("0x%" PRIx64, n_value);
5325     if (c.data != 0)
5326       outs() << " + " << format("0x%" PRIx64, c.data);
5327   } else
5328     outs() << format("0x%" PRIx64, c.data);
5329   outs() << " (struct class_ro_t *)";
5330
5331   // This is a Swift class if some of the low bits of the pointer are set.
5332   if ((c.data + n_value) & 0x7)
5333     outs() << " Swift class";
5334   outs() << "\n";
5335   bool is_meta_class;
5336   if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
5337     return;
5338
5339   if (!is_meta_class &&
5340       c.isa + isa_n_value != p &&
5341       c.isa + isa_n_value != 0 &&
5342       info->depth < 100) {
5343       info->depth++;
5344       outs() << "Meta Class\n";
5345       print_class64_t(c.isa + isa_n_value, info);
5346   }
5347 }
5348
5349 static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
5350   struct class32_t c;
5351   const char *r;
5352   uint32_t offset, left;
5353   SectionRef S;
5354   const char *name;
5355
5356   r = get_pointer_32(p, offset, left, S, info);
5357   if (r == nullptr)
5358     return;
5359   memset(&c, '\0', sizeof(struct class32_t));
5360   if (left < sizeof(struct class32_t)) {
5361     memcpy(&c, r, left);
5362     outs() << "   (class_t entends past the end of the section)\n";
5363   } else
5364     memcpy(&c, r, sizeof(struct class32_t));
5365   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5366     swapStruct(c);
5367
5368   outs() << "           isa " << format("0x%" PRIx32, c.isa);
5369   name =
5370       get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
5371   if (name != nullptr)
5372     outs() << " " << name;
5373   outs() << "\n";
5374
5375   outs() << "    superclass " << format("0x%" PRIx32, c.superclass);
5376   name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
5377                        c.superclass);
5378   if (name != nullptr)
5379     outs() << " " << name;
5380   outs() << "\n";
5381
5382   outs() << "         cache " << format("0x%" PRIx32, c.cache);
5383   name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
5384                        c.cache);
5385   if (name != nullptr)
5386     outs() << " " << name;
5387   outs() << "\n";
5388
5389   outs() << "        vtable " << format("0x%" PRIx32, c.vtable);
5390   name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
5391                        c.vtable);
5392   if (name != nullptr)
5393     outs() << " " << name;
5394   outs() << "\n";
5395
5396   name =
5397       get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
5398   outs() << "          data " << format("0x%" PRIx32, c.data)
5399          << " (struct class_ro_t *)";
5400
5401   // This is a Swift class if some of the low bits of the pointer are set.
5402   if (c.data & 0x3)
5403     outs() << " Swift class";
5404   outs() << "\n";
5405   bool is_meta_class;
5406   if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
5407     return;
5408
5409   if (!is_meta_class) {
5410     outs() << "Meta Class\n";
5411     print_class32_t(c.isa, info);
5412   }
5413 }
5414
5415 static void print_objc_class_t(struct objc_class_t *objc_class,
5416                                struct DisassembleInfo *info) {
5417   uint32_t offset, left, xleft;
5418   const char *name, *p, *ivar_list;
5419   SectionRef S;
5420   int32_t i;
5421   struct objc_ivar_list_t objc_ivar_list;
5422   struct objc_ivar_t ivar;
5423
5424   outs() << "\t\t      isa " << format("0x%08" PRIx32, objc_class->isa);
5425   if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
5426     name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
5427     if (name != nullptr)
5428       outs() << format(" %.*s", left, name);
5429     else
5430       outs() << " (not in an __OBJC section)";
5431   }
5432   outs() << "\n";
5433
5434   outs() << "\t      super_class "
5435          << format("0x%08" PRIx32, objc_class->super_class);
5436   if (info->verbose) {
5437     name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
5438     if (name != nullptr)
5439       outs() << format(" %.*s", left, name);
5440     else
5441       outs() << " (not in an __OBJC section)";
5442   }
5443   outs() << "\n";
5444
5445   outs() << "\t\t     name " << format("0x%08" PRIx32, objc_class->name);
5446   if (info->verbose) {
5447     name = get_pointer_32(objc_class->name, offset, left, S, info, true);
5448     if (name != nullptr)
5449       outs() << format(" %.*s", left, name);
5450     else
5451       outs() << " (not in an __OBJC section)";
5452   }
5453   outs() << "\n";
5454
5455   outs() << "\t\t  version " << format("0x%08" PRIx32, objc_class->version)
5456          << "\n";
5457
5458   outs() << "\t\t     info " << format("0x%08" PRIx32, objc_class->info);
5459   if (info->verbose) {
5460     if (CLS_GETINFO(objc_class, CLS_CLASS))
5461       outs() << " CLS_CLASS";
5462     else if (CLS_GETINFO(objc_class, CLS_META))
5463       outs() << " CLS_META";
5464   }
5465   outs() << "\n";
5466
5467   outs() << "\t    instance_size "
5468          << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
5469
5470   p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
5471   outs() << "\t\t    ivars " << format("0x%08" PRIx32, objc_class->ivars);
5472   if (p != nullptr) {
5473     if (left > sizeof(struct objc_ivar_list_t)) {
5474       outs() << "\n";
5475       memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
5476     } else {
5477       outs() << " (entends past the end of the section)\n";
5478       memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
5479       memcpy(&objc_ivar_list, p, left);
5480     }
5481     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5482       swapStruct(objc_ivar_list);
5483     outs() << "\t\t       ivar_count " << objc_ivar_list.ivar_count << "\n";
5484     ivar_list = p + sizeof(struct objc_ivar_list_t);
5485     for (i = 0; i < objc_ivar_list.ivar_count; i++) {
5486       if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
5487         outs() << "\t\t remaining ivar's extend past the of the section\n";
5488         break;
5489       }
5490       memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
5491              sizeof(struct objc_ivar_t));
5492       if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5493         swapStruct(ivar);
5494
5495       outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
5496       if (info->verbose) {
5497         name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
5498         if (name != nullptr)
5499           outs() << format(" %.*s", xleft, name);
5500         else
5501           outs() << " (not in an __OBJC section)";
5502       }
5503       outs() << "\n";
5504
5505       outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
5506       if (info->verbose) {
5507         name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
5508         if (name != nullptr)
5509           outs() << format(" %.*s", xleft, name);
5510         else
5511           outs() << " (not in an __OBJC section)";
5512       }
5513       outs() << "\n";
5514
5515       outs() << "\t\t      ivar_offset "
5516              << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
5517     }
5518   } else {
5519     outs() << " (not in an __OBJC section)\n";
5520   }
5521
5522   outs() << "\t\t  methods " << format("0x%08" PRIx32, objc_class->methodLists);
5523   if (print_method_list(objc_class->methodLists, info))
5524     outs() << " (not in an __OBJC section)\n";
5525
5526   outs() << "\t\t    cache " << format("0x%08" PRIx32, objc_class->cache)
5527          << "\n";
5528
5529   outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
5530   if (print_protocol_list(objc_class->protocols, 16, info))
5531     outs() << " (not in an __OBJC section)\n";
5532 }
5533
5534 static void print_objc_objc_category_t(struct objc_category_t *objc_category,
5535                                        struct DisassembleInfo *info) {
5536   uint32_t offset, left;
5537   const char *name;
5538   SectionRef S;
5539
5540   outs() << "\t       category name "
5541          << format("0x%08" PRIx32, objc_category->category_name);
5542   if (info->verbose) {
5543     name = get_pointer_32(objc_category->category_name, offset, left, S, info,
5544                           true);
5545     if (name != nullptr)
5546       outs() << format(" %.*s", left, name);
5547     else
5548       outs() << " (not in an __OBJC section)";
5549   }
5550   outs() << "\n";
5551
5552   outs() << "\t\t  class name "
5553          << format("0x%08" PRIx32, objc_category->class_name);
5554   if (info->verbose) {
5555     name =
5556         get_pointer_32(objc_category->class_name, offset, left, S, info, true);
5557     if (name != nullptr)
5558       outs() << format(" %.*s", left, name);
5559     else
5560       outs() << " (not in an __OBJC section)";
5561   }
5562   outs() << "\n";
5563
5564   outs() << "\t    instance methods "
5565          << format("0x%08" PRIx32, objc_category->instance_methods);
5566   if (print_method_list(objc_category->instance_methods, info))
5567     outs() << " (not in an __OBJC section)\n";
5568
5569   outs() << "\t       class methods "
5570          << format("0x%08" PRIx32, objc_category->class_methods);
5571   if (print_method_list(objc_category->class_methods, info))
5572     outs() << " (not in an __OBJC section)\n";
5573 }
5574
5575 static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
5576   struct category64_t c;
5577   const char *r;
5578   uint32_t offset, xoffset, left;
5579   SectionRef S, xS;
5580   const char *name, *sym_name;
5581   uint64_t n_value;
5582
5583   r = get_pointer_64(p, offset, left, S, info);
5584   if (r == nullptr)
5585     return;
5586   memset(&c, '\0', sizeof(struct category64_t));
5587   if (left < sizeof(struct category64_t)) {
5588     memcpy(&c, r, left);
5589     outs() << "   (category_t entends past the end of the section)\n";
5590   } else
5591     memcpy(&c, r, sizeof(struct category64_t));
5592   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5593     swapStruct(c);
5594
5595   outs() << "              name ";
5596   sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
5597                            info, n_value, c.name);
5598   if (n_value != 0) {
5599     if (info->verbose && sym_name != nullptr)
5600       outs() << sym_name;
5601     else
5602       outs() << format("0x%" PRIx64, n_value);
5603     if (c.name != 0)
5604       outs() << " + " << format("0x%" PRIx64, c.name);
5605   } else
5606     outs() << format("0x%" PRIx64, c.name);
5607   name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
5608   if (name != nullptr)
5609     outs() << format(" %.*s", left, name);
5610   outs() << "\n";
5611
5612   outs() << "               cls ";
5613   sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
5614                            n_value, c.cls);
5615   if (n_value != 0) {
5616     if (info->verbose && sym_name != nullptr)
5617       outs() << sym_name;
5618     else
5619       outs() << format("0x%" PRIx64, n_value);
5620     if (c.cls != 0)
5621       outs() << " + " << format("0x%" PRIx64, c.cls);
5622   } else
5623     outs() << format("0x%" PRIx64, c.cls);
5624   outs() << "\n";
5625   if (c.cls + n_value != 0)
5626     print_class64_t(c.cls + n_value, info);
5627
5628   outs() << "   instanceMethods ";
5629   sym_name =
5630       get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
5631                     info, n_value, c.instanceMethods);
5632   if (n_value != 0) {
5633     if (info->verbose && sym_name != nullptr)
5634       outs() << sym_name;
5635     else
5636       outs() << format("0x%" PRIx64, n_value);
5637     if (c.instanceMethods != 0)
5638       outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
5639   } else
5640     outs() << format("0x%" PRIx64, c.instanceMethods);
5641   outs() << "\n";
5642   if (c.instanceMethods + n_value != 0)
5643     print_method_list64_t(c.instanceMethods + n_value, info, "");
5644
5645   outs() << "      classMethods ";
5646   sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
5647                            S, info, n_value, c.classMethods);
5648   if (n_value != 0) {
5649     if (info->verbose && sym_name != nullptr)
5650       outs() << sym_name;
5651     else
5652       outs() << format("0x%" PRIx64, n_value);
5653     if (c.classMethods != 0)
5654       outs() << " + " << format("0x%" PRIx64, c.classMethods);
5655   } else
5656     outs() << format("0x%" PRIx64, c.classMethods);
5657   outs() << "\n";
5658   if (c.classMethods + n_value != 0)
5659     print_method_list64_t(c.classMethods + n_value, info, "");
5660
5661   outs() << "         protocols ";
5662   sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
5663                            info, n_value, c.protocols);
5664   if (n_value != 0) {
5665     if (info->verbose && sym_name != nullptr)
5666       outs() << sym_name;
5667     else
5668       outs() << format("0x%" PRIx64, n_value);
5669     if (c.protocols != 0)
5670       outs() << " + " << format("0x%" PRIx64, c.protocols);
5671   } else
5672     outs() << format("0x%" PRIx64, c.protocols);
5673   outs() << "\n";
5674   if (c.protocols + n_value != 0)
5675     print_protocol_list64_t(c.protocols + n_value, info);
5676
5677   outs() << "instanceProperties ";
5678   sym_name =
5679       get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
5680                     S, info, n_value, c.instanceProperties);
5681   if (n_value != 0) {
5682     if (info->verbose && sym_name != nullptr)
5683       outs() << sym_name;
5684     else
5685       outs() << format("0x%" PRIx64, n_value);
5686     if (c.instanceProperties != 0)
5687       outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
5688   } else
5689     outs() << format("0x%" PRIx64, c.instanceProperties);
5690   outs() << "\n";
5691   if (c.instanceProperties + n_value != 0)
5692     print_objc_property_list64(c.instanceProperties + n_value, info);
5693 }
5694
5695 static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
5696   struct category32_t c;
5697   const char *r;
5698   uint32_t offset, left;
5699   SectionRef S, xS;
5700   const char *name;
5701
5702   r = get_pointer_32(p, offset, left, S, info);
5703   if (r == nullptr)
5704     return;
5705   memset(&c, '\0', sizeof(struct category32_t));
5706   if (left < sizeof(struct category32_t)) {
5707     memcpy(&c, r, left);
5708     outs() << "   (category_t entends past the end of the section)\n";
5709   } else
5710     memcpy(&c, r, sizeof(struct category32_t));
5711   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5712     swapStruct(c);
5713
5714   outs() << "              name " << format("0x%" PRIx32, c.name);
5715   name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
5716                        c.name);
5717   if (name)
5718     outs() << " " << name;
5719   outs() << "\n";
5720
5721   outs() << "               cls " << format("0x%" PRIx32, c.cls) << "\n";
5722   if (c.cls != 0)
5723     print_class32_t(c.cls, info);
5724   outs() << "   instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
5725          << "\n";
5726   if (c.instanceMethods != 0)
5727     print_method_list32_t(c.instanceMethods, info, "");
5728   outs() << "      classMethods " << format("0x%" PRIx32, c.classMethods)
5729          << "\n";
5730   if (c.classMethods != 0)
5731     print_method_list32_t(c.classMethods, info, "");
5732   outs() << "         protocols " << format("0x%" PRIx32, c.protocols) << "\n";
5733   if (c.protocols != 0)
5734     print_protocol_list32_t(c.protocols, info);
5735   outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
5736          << "\n";
5737   if (c.instanceProperties != 0)
5738     print_objc_property_list32(c.instanceProperties, info);
5739 }
5740
5741 static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
5742   uint32_t i, left, offset, xoffset;
5743   uint64_t p, n_value;
5744   struct message_ref64 mr;
5745   const char *name, *sym_name;
5746   const char *r;
5747   SectionRef xS;
5748
5749   if (S == SectionRef())
5750     return;
5751
5752   StringRef SectName;
5753   S.getName(SectName);
5754   DataRefImpl Ref = S.getRawDataRefImpl();
5755   StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5756   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5757   offset = 0;
5758   for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5759     p = S.getAddress() + i;
5760     r = get_pointer_64(p, offset, left, S, info);
5761     if (r == nullptr)
5762       return;
5763     memset(&mr, '\0', sizeof(struct message_ref64));
5764     if (left < sizeof(struct message_ref64)) {
5765       memcpy(&mr, r, left);
5766       outs() << "   (message_ref entends past the end of the section)\n";
5767     } else
5768       memcpy(&mr, r, sizeof(struct message_ref64));
5769     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5770       swapStruct(mr);
5771
5772     outs() << "  imp ";
5773     name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
5774                          n_value, mr.imp);
5775     if (n_value != 0) {
5776       outs() << format("0x%" PRIx64, n_value) << " ";
5777       if (mr.imp != 0)
5778         outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
5779     } else
5780       outs() << format("0x%" PRIx64, mr.imp) << " ";
5781     if (name != nullptr)
5782       outs() << " " << name;
5783     outs() << "\n";
5784
5785     outs() << "  sel ";
5786     sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
5787                              info, n_value, mr.sel);
5788     if (n_value != 0) {
5789       if (info->verbose && sym_name != nullptr)
5790         outs() << sym_name;
5791       else
5792         outs() << format("0x%" PRIx64, n_value);
5793       if (mr.sel != 0)
5794         outs() << " + " << format("0x%" PRIx64, mr.sel);
5795     } else
5796       outs() << format("0x%" PRIx64, mr.sel);
5797     name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
5798     if (name != nullptr)
5799       outs() << format(" %.*s", left, name);
5800     outs() << "\n";
5801
5802     offset += sizeof(struct message_ref64);
5803   }
5804 }
5805
5806 static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
5807   uint32_t i, left, offset, xoffset, p;
5808   struct message_ref32 mr;
5809   const char *name, *r;
5810   SectionRef xS;
5811
5812   if (S == SectionRef())
5813     return;
5814
5815   StringRef SectName;
5816   S.getName(SectName);
5817   DataRefImpl Ref = S.getRawDataRefImpl();
5818   StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5819   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5820   offset = 0;
5821   for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5822     p = S.getAddress() + i;
5823     r = get_pointer_32(p, offset, left, S, info);
5824     if (r == nullptr)
5825       return;
5826     memset(&mr, '\0', sizeof(struct message_ref32));
5827     if (left < sizeof(struct message_ref32)) {
5828       memcpy(&mr, r, left);
5829       outs() << "   (message_ref entends past the end of the section)\n";
5830     } else
5831       memcpy(&mr, r, sizeof(struct message_ref32));
5832     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5833       swapStruct(mr);
5834
5835     outs() << "  imp " << format("0x%" PRIx32, mr.imp);
5836     name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
5837                          mr.imp);
5838     if (name != nullptr)
5839       outs() << " " << name;
5840     outs() << "\n";
5841
5842     outs() << "  sel " << format("0x%" PRIx32, mr.sel);
5843     name = get_pointer_32(mr.sel, xoffset, left, xS, info);
5844     if (name != nullptr)
5845       outs() << " " << name;
5846     outs() << "\n";
5847
5848     offset += sizeof(struct message_ref32);
5849   }
5850 }
5851
5852 static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
5853   uint32_t left, offset, swift_version;
5854   uint64_t p;
5855   struct objc_image_info64 o;
5856   const char *r;
5857
5858   if (S == SectionRef())
5859     return;
5860
5861   StringRef SectName;
5862   S.getName(SectName);
5863   DataRefImpl Ref = S.getRawDataRefImpl();
5864   StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5865   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5866   p = S.getAddress();
5867   r = get_pointer_64(p, offset, left, S, info);
5868   if (r == nullptr)
5869     return;
5870   memset(&o, '\0', sizeof(struct objc_image_info64));
5871   if (left < sizeof(struct objc_image_info64)) {
5872     memcpy(&o, r, left);
5873     outs() << "   (objc_image_info entends past the end of the section)\n";
5874   } else
5875     memcpy(&o, r, sizeof(struct objc_image_info64));
5876   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5877     swapStruct(o);
5878   outs() << "  version " << o.version << "\n";
5879   outs() << "    flags " << format("0x%" PRIx32, o.flags);
5880   if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5881     outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5882   if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5883     outs() << " OBJC_IMAGE_SUPPORTS_GC";
5884   if (o.flags & OBJC_IMAGE_IS_SIMULATED)
5885     outs() << " OBJC_IMAGE_IS_SIMULATED";
5886   if (o.flags & OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES)
5887     outs() << " OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES";
5888   swift_version = (o.flags >> 8) & 0xff;
5889   if (swift_version != 0) {
5890     if (swift_version == 1)
5891       outs() << " Swift 1.0";
5892     else if (swift_version == 2)
5893       outs() << " Swift 1.1";
5894     else if(swift_version == 3)
5895       outs() << " Swift 2.0";
5896     else if(swift_version == 4)
5897       outs() << " Swift 3.0";
5898     else if(swift_version == 5)
5899       outs() << " Swift 4.0";
5900     else if(swift_version == 6)
5901       outs() << " Swift 4.1/Swift 4.2";
5902     else if(swift_version == 7)
5903       outs() << " Swift 5 or later";
5904     else
5905       outs() << " unknown future Swift version (" << swift_version << ")";
5906   }
5907   outs() << "\n";
5908 }
5909
5910 static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
5911   uint32_t left, offset, swift_version, p;
5912   struct objc_image_info32 o;
5913   const char *r;
5914
5915   if (S == SectionRef())
5916     return;
5917
5918   StringRef SectName;
5919   S.getName(SectName);
5920   DataRefImpl Ref = S.getRawDataRefImpl();
5921   StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5922   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5923   p = S.getAddress();
5924   r = get_pointer_32(p, offset, left, S, info);
5925   if (r == nullptr)
5926     return;
5927   memset(&o, '\0', sizeof(struct objc_image_info32));
5928   if (left < sizeof(struct objc_image_info32)) {
5929     memcpy(&o, r, left);
5930     outs() << "   (objc_image_info entends past the end of the section)\n";
5931   } else
5932     memcpy(&o, r, sizeof(struct objc_image_info32));
5933   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5934     swapStruct(o);
5935   outs() << "  version " << o.version << "\n";
5936   outs() << "    flags " << format("0x%" PRIx32, o.flags);
5937   if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5938     outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5939   if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5940     outs() << " OBJC_IMAGE_SUPPORTS_GC";
5941   swift_version = (o.flags >> 8) & 0xff;
5942   if (swift_version != 0) {
5943     if (swift_version == 1)
5944       outs() << " Swift 1.0";
5945     else if (swift_version == 2)
5946       outs() << " Swift 1.1";
5947     else if(swift_version == 3)
5948       outs() << " Swift 2.0";
5949     else if(swift_version == 4)
5950       outs() << " Swift 3.0";
5951     else if(swift_version == 5)
5952       outs() << " Swift 4.0";
5953     else if(swift_version == 6)
5954       outs() << " Swift 4.1/Swift 4.2";
5955     else if(swift_version == 7)
5956       outs() << " Swift 5 or later";
5957     else
5958       outs() << " unknown future Swift version (" << swift_version << ")";
5959   }
5960   outs() << "\n";
5961 }
5962
5963 static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
5964   uint32_t left, offset, p;
5965   struct imageInfo_t o;
5966   const char *r;
5967
5968   StringRef SectName;
5969   S.getName(SectName);
5970   DataRefImpl Ref = S.getRawDataRefImpl();
5971   StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5972   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5973   p = S.getAddress();
5974   r = get_pointer_32(p, offset, left, S, info);
5975   if (r == nullptr)
5976     return;
5977   memset(&o, '\0', sizeof(struct imageInfo_t));
5978   if (left < sizeof(struct imageInfo_t)) {
5979     memcpy(&o, r, left);
5980     outs() << " (imageInfo entends past the end of the section)\n";
5981   } else
5982     memcpy(&o, r, sizeof(struct imageInfo_t));
5983   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5984     swapStruct(o);
5985   outs() << "  version " << o.version << "\n";
5986   outs() << "    flags " << format("0x%" PRIx32, o.flags);
5987   if (o.flags & 0x1)
5988     outs() << "  F&C";
5989   if (o.flags & 0x2)
5990     outs() << " GC";
5991   if (o.flags & 0x4)
5992     outs() << " GC-only";
5993   else
5994     outs() << " RR";
5995   outs() << "\n";
5996 }
5997
5998 static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
5999   SymbolAddressMap AddrMap;
6000   if (verbose)
6001     CreateSymbolAddressMap(O, &AddrMap);
6002
6003   std::vector<SectionRef> Sections;
6004   for (const SectionRef &Section : O->sections()) {
6005     StringRef SectName;
6006     Section.getName(SectName);
6007     Sections.push_back(Section);
6008   }
6009
6010   struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
6011
6012   SectionRef CL = get_section(O, "__OBJC2", "__class_list");
6013   if (CL == SectionRef())
6014     CL = get_section(O, "__DATA", "__objc_classlist");
6015   if (CL == SectionRef())
6016     CL = get_section(O, "__DATA_CONST", "__objc_classlist");
6017   if (CL == SectionRef())
6018     CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
6019   info.S = CL;
6020   walk_pointer_list_64("class", CL, O, &info, print_class64_t);
6021
6022   SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
6023   if (CR == SectionRef())
6024     CR = get_section(O, "__DATA", "__objc_classrefs");
6025   if (CR == SectionRef())
6026     CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
6027   if (CR == SectionRef())
6028     CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
6029   info.S = CR;
6030   walk_pointer_list_64("class refs", CR, O, &info, nullptr);
6031
6032   SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
6033   if (SR == SectionRef())
6034     SR = get_section(O, "__DATA", "__objc_superrefs");
6035   if (SR == SectionRef())
6036     SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
6037   if (SR == SectionRef())
6038     SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
6039   info.S = SR;
6040   walk_pointer_list_64("super refs", SR, O, &info, nullptr);
6041
6042   SectionRef CA = get_section(O, "__OBJC2", "__category_list");
6043   if (CA == SectionRef())
6044     CA = get_section(O, "__DATA", "__objc_catlist");
6045   if (CA == SectionRef())
6046     CA = get_section(O, "__DATA_CONST", "__objc_catlist");
6047   if (CA == SectionRef())
6048     CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
6049   info.S = CA;
6050   walk_pointer_list_64("category", CA, O, &info, print_category64_t);
6051
6052   SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
6053   if (PL == SectionRef())
6054     PL = get_section(O, "__DATA", "__objc_protolist");
6055   if (PL == SectionRef())
6056     PL = get_section(O, "__DATA_CONST", "__objc_protolist");
6057   if (PL == SectionRef())
6058     PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
6059   info.S = PL;
6060   walk_pointer_list_64("protocol", PL, O, &info, nullptr);
6061
6062   SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
6063   if (MR == SectionRef())
6064     MR = get_section(O, "__DATA", "__objc_msgrefs");
6065   if (MR == SectionRef())
6066     MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
6067   if (MR == SectionRef())
6068     MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
6069   info.S = MR;
6070   print_message_refs64(MR, &info);
6071
6072   SectionRef II = get_section(O, "__OBJC2", "__image_info");
6073   if (II == SectionRef())
6074     II = get_section(O, "__DATA", "__objc_imageinfo");
6075   if (II == SectionRef())
6076     II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
6077   if (II == SectionRef())
6078     II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
6079   info.S = II;
6080   print_image_info64(II, &info);
6081 }
6082
6083 static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
6084   SymbolAddressMap AddrMap;
6085   if (verbose)
6086     CreateSymbolAddressMap(O, &AddrMap);
6087
6088   std::vector<SectionRef> Sections;
6089   for (const SectionRef &Section : O->sections()) {
6090     StringRef SectName;
6091     Section.getName(SectName);
6092     Sections.push_back(Section);
6093   }
6094
6095   struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
6096
6097   SectionRef CL = get_section(O, "__OBJC2", "__class_list");
6098   if (CL == SectionRef())
6099     CL = get_section(O, "__DATA", "__objc_classlist");
6100   if (CL == SectionRef())
6101     CL = get_section(O, "__DATA_CONST", "__objc_classlist");
6102   if (CL == SectionRef())
6103     CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
6104   info.S = CL;
6105   walk_pointer_list_32("class", CL, O, &info, print_class32_t);
6106
6107   SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
6108   if (CR == SectionRef())
6109     CR = get_section(O, "__DATA", "__objc_classrefs");
6110   if (CR == SectionRef())
6111     CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
6112   if (CR == SectionRef())
6113     CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
6114   info.S = CR;
6115   walk_pointer_list_32("class refs", CR, O, &info, nullptr);
6116
6117   SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
6118   if (SR == SectionRef())
6119     SR = get_section(O, "__DATA", "__objc_superrefs");
6120   if (SR == SectionRef())
6121     SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
6122   if (SR == SectionRef())
6123     SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
6124   info.S = SR;
6125   walk_pointer_list_32("super refs", SR, O, &info, nullptr);
6126
6127   SectionRef CA = get_section(O, "__OBJC2", "__category_list");
6128   if (CA == SectionRef())
6129     CA = get_section(O, "__DATA", "__objc_catlist");
6130   if (CA == SectionRef())
6131     CA = get_section(O, "__DATA_CONST", "__objc_catlist");
6132   if (CA == SectionRef())
6133     CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
6134   info.S = CA;
6135   walk_pointer_list_32("category", CA, O, &info, print_category32_t);
6136
6137   SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
6138   if (PL == SectionRef())
6139     PL = get_section(O, "__DATA", "__objc_protolist");
6140   if (PL == SectionRef())
6141     PL = get_section(O, "__DATA_CONST", "__objc_protolist");
6142   if (PL == SectionRef())
6143     PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
6144   info.S = PL;
6145   walk_pointer_list_32("protocol", PL, O, &info, nullptr);
6146
6147   SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
6148   if (MR == SectionRef())
6149     MR = get_section(O, "__DATA", "__objc_msgrefs");
6150   if (MR == SectionRef())
6151     MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
6152   if (MR == SectionRef())
6153     MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
6154   info.S = MR;
6155   print_message_refs32(MR, &info);
6156
6157   SectionRef II = get_section(O, "__OBJC2", "__image_info");
6158   if (II == SectionRef())
6159     II = get_section(O, "__DATA", "__objc_imageinfo");
6160   if (II == SectionRef())
6161     II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
6162   if (II == SectionRef())
6163     II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
6164   info.S = II;
6165   print_image_info32(II, &info);
6166 }
6167
6168 static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
6169   uint32_t i, j, p, offset, xoffset, left, defs_left, def;
6170   const char *r, *name, *defs;
6171   struct objc_module_t module;
6172   SectionRef S, xS;
6173   struct objc_symtab_t symtab;
6174   struct objc_class_t objc_class;
6175   struct objc_category_t objc_category;
6176
6177   outs() << "Objective-C segment\n";
6178   S = get_section(O, "__OBJC", "__module_info");
6179   if (S == SectionRef())
6180     return false;
6181
6182   SymbolAddressMap AddrMap;
6183   if (verbose)
6184     CreateSymbolAddressMap(O, &AddrMap);
6185
6186   std::vector<SectionRef> Sections;
6187   for (const SectionRef &Section : O->sections()) {
6188     StringRef SectName;
6189     Section.getName(SectName);
6190     Sections.push_back(Section);
6191   }
6192
6193   struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
6194
6195   for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
6196     p = S.getAddress() + i;
6197     r = get_pointer_32(p, offset, left, S, &info, true);
6198     if (r == nullptr)
6199       return true;
6200     memset(&module, '\0', sizeof(struct objc_module_t));
6201     if (left < sizeof(struct objc_module_t)) {
6202       memcpy(&module, r, left);
6203       outs() << "   (module extends past end of __module_info section)\n";
6204     } else
6205       memcpy(&module, r, sizeof(struct objc_module_t));
6206     if (O->isLittleEndian() != sys::IsLittleEndianHost)
6207       swapStruct(module);
6208
6209     outs() << "Module " << format("0x%" PRIx32, p) << "\n";
6210     outs() << "    version " << module.version << "\n";
6211     outs() << "       size " << module.size << "\n";
6212     outs() << "       name ";
6213     name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
6214     if (name != nullptr)
6215       outs() << format("%.*s", left, name);
6216     else
6217       outs() << format("0x%08" PRIx32, module.name)
6218              << "(not in an __OBJC section)";
6219     outs() << "\n";
6220
6221     r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
6222     if (module.symtab == 0 || r == nullptr) {
6223       outs() << "     symtab " << format("0x%08" PRIx32, module.symtab)
6224              << " (not in an __OBJC section)\n";
6225       continue;
6226     }
6227     outs() << "     symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
6228     memset(&symtab, '\0', sizeof(struct objc_symtab_t));
6229     defs_left = 0;
6230     defs = nullptr;
6231     if (left < sizeof(struct objc_symtab_t)) {
6232       memcpy(&symtab, r, left);
6233       outs() << "\tsymtab extends past end of an __OBJC section)\n";
6234     } else {
6235       memcpy(&symtab, r, sizeof(struct objc_symtab_t));
6236       if (left > sizeof(struct objc_symtab_t)) {
6237         defs_left = left - sizeof(struct objc_symtab_t);
6238         defs = r + sizeof(struct objc_symtab_t);
6239       }
6240     }
6241     if (O->isLittleEndian() != sys::IsLittleEndianHost)
6242       swapStruct(symtab);
6243
6244     outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
6245     r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
6246     outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
6247     if (r == nullptr)
6248       outs() << " (not in an __OBJC section)";
6249     outs() << "\n";
6250     outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
6251     outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
6252     if (symtab.cls_def_cnt > 0)
6253       outs() << "\tClass Definitions\n";
6254     for (j = 0; j < symtab.cls_def_cnt; j++) {
6255       if ((j + 1) * sizeof(uint32_t) > defs_left) {
6256         outs() << "\t(remaining class defs entries entends past the end of the "
6257                << "section)\n";
6258         break;
6259       }
6260       memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
6261       if (O->isLittleEndian() != sys::IsLittleEndianHost)
6262         sys::swapByteOrder(def);
6263
6264       r = get_pointer_32(def, xoffset, left, xS, &info, true);
6265       outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
6266       if (r != nullptr) {
6267         if (left > sizeof(struct objc_class_t)) {
6268           outs() << "\n";
6269           memcpy(&objc_class, r, sizeof(struct objc_class_t));
6270         } else {
6271           outs() << " (entends past the end of the section)\n";
6272           memset(&objc_class, '\0', sizeof(struct objc_class_t));
6273           memcpy(&objc_class, r, left);
6274         }
6275         if (O->isLittleEndian() != sys::IsLittleEndianHost)
6276           swapStruct(objc_class);
6277         print_objc_class_t(&objc_class, &info);
6278       } else {
6279         outs() << "(not in an __OBJC section)\n";
6280       }
6281
6282       if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
6283         outs() << "\tMeta Class";
6284         r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
6285         if (r != nullptr) {
6286           if (left > sizeof(struct objc_class_t)) {
6287             outs() << "\n";
6288             memcpy(&objc_class, r, sizeof(struct objc_class_t));
6289           } else {
6290             outs() << " (entends past the end of the section)\n";
6291             memset(&objc_class, '\0', sizeof(struct objc_class_t));
6292             memcpy(&objc_class, r, left);
6293           }
6294           if (O->isLittleEndian() != sys::IsLittleEndianHost)
6295             swapStruct(objc_class);
6296           print_objc_class_t(&objc_class, &info);
6297         } else {
6298           outs() << "(not in an __OBJC section)\n";
6299         }
6300       }
6301     }
6302     if (symtab.cat_def_cnt > 0)
6303       outs() << "\tCategory Definitions\n";
6304     for (j = 0; j < symtab.cat_def_cnt; j++) {
6305       if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
6306         outs() << "\t(remaining category defs entries entends past the end of "
6307                << "the section)\n";
6308         break;
6309       }
6310       memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
6311              sizeof(uint32_t));
6312       if (O->isLittleEndian() != sys::IsLittleEndianHost)
6313         sys::swapByteOrder(def);
6314
6315       r = get_pointer_32(def, xoffset, left, xS, &info, true);
6316       outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
6317              << format("0x%08" PRIx32, def);
6318       if (r != nullptr) {
6319         if (left > sizeof(struct objc_category_t)) {
6320           outs() << "\n";
6321           memcpy(&objc_category, r, sizeof(struct objc_category_t));
6322         } else {
6323           outs() << " (entends past the end of the section)\n";
6324           memset(&objc_category, '\0', sizeof(struct objc_category_t));
6325           memcpy(&objc_category, r, left);
6326         }
6327         if (O->isLittleEndian() != sys::IsLittleEndianHost)
6328           swapStruct(objc_category);
6329         print_objc_objc_category_t(&objc_category, &info);
6330       } else {
6331         outs() << "(not in an __OBJC section)\n";
6332       }
6333     }
6334   }
6335   const SectionRef II = get_section(O, "__OBJC", "__image_info");
6336   if (II != SectionRef())
6337     print_image_info(II, &info);
6338
6339   return true;
6340 }
6341
6342 static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
6343                                 uint32_t size, uint32_t addr) {
6344   SymbolAddressMap AddrMap;
6345   CreateSymbolAddressMap(O, &AddrMap);
6346
6347   std::vector<SectionRef> Sections;
6348   for (const SectionRef &Section : O->sections()) {
6349     StringRef SectName;
6350     Section.getName(SectName);
6351     Sections.push_back(Section);
6352   }
6353
6354   struct DisassembleInfo info(O, &AddrMap, &Sections, true);
6355
6356   const char *p;
6357   struct objc_protocol_t protocol;
6358   uint32_t left, paddr;
6359   for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
6360     memset(&protocol, '\0', sizeof(struct objc_protocol_t));
6361     left = size - (p - sect);
6362     if (left < sizeof(struct objc_protocol_t)) {
6363       outs() << "Protocol extends past end of __protocol section\n";
6364       memcpy(&protocol, p, left);
6365     } else
6366       memcpy(&protocol, p, sizeof(struct objc_protocol_t));
6367     if (O->isLittleEndian() != sys::IsLittleEndianHost)
6368       swapStruct(protocol);
6369     paddr = addr + (p - sect);
6370     outs() << "Protocol " << format("0x%" PRIx32, paddr);
6371     if (print_protocol(paddr, 0, &info))
6372       outs() << "(not in an __OBJC section)\n";
6373   }
6374 }
6375
6376 #ifdef HAVE_LIBXAR
6377 inline void swapStruct(struct xar_header &xar) {
6378   sys::swapByteOrder(xar.magic);
6379   sys::swapByteOrder(xar.size);
6380   sys::swapByteOrder(xar.version);
6381   sys::swapByteOrder(xar.toc_length_compressed);
6382   sys::swapByteOrder(xar.toc_length_uncompressed);
6383   sys::swapByteOrder(xar.cksum_alg);
6384 }
6385
6386 static void PrintModeVerbose(uint32_t mode) {
6387   switch(mode & S_IFMT){
6388   case S_IFDIR:
6389     outs() << "d";
6390     break;
6391   case S_IFCHR:
6392     outs() << "c";
6393     break;
6394   case S_IFBLK:
6395     outs() << "b";
6396     break;
6397   case S_IFREG:
6398     outs() << "-";
6399     break;
6400   case S_IFLNK:
6401     outs() << "l";
6402     break;
6403   case S_IFSOCK:
6404     outs() << "s";
6405     break;
6406   default:
6407     outs() << "?";
6408     break;
6409   }
6410
6411   /* owner permissions */
6412   if(mode & S_IREAD)
6413     outs() << "r";
6414   else
6415     outs() << "-";
6416   if(mode & S_IWRITE)
6417     outs() << "w";
6418   else
6419     outs() << "-";
6420   if(mode & S_ISUID)
6421     outs() << "s";
6422   else if(mode & S_IEXEC)
6423     outs() << "x";
6424   else
6425     outs() << "-";
6426
6427   /* group permissions */
6428   if(mode & (S_IREAD >> 3))
6429     outs() << "r";
6430   else
6431     outs() << "-";
6432   if(mode & (S_IWRITE >> 3))
6433     outs() << "w";
6434   else
6435     outs() << "-";
6436   if(mode & S_ISGID)
6437     outs() << "s";
6438   else if(mode & (S_IEXEC >> 3))
6439     outs() << "x";
6440   else
6441     outs() << "-";
6442
6443   /* other permissions */
6444   if(mode & (S_IREAD >> 6))
6445     outs() << "r";
6446   else
6447     outs() << "-";
6448   if(mode & (S_IWRITE >> 6))
6449     outs() << "w";
6450   else
6451     outs() << "-";
6452   if(mode & S_ISVTX)
6453     outs() << "t";
6454   else if(mode & (S_IEXEC >> 6))
6455     outs() << "x";
6456   else
6457     outs() << "-";
6458 }
6459
6460 static void PrintXarFilesSummary(const char *XarFilename, xar_t xar) {
6461   xar_file_t xf;
6462   const char *key, *type, *mode, *user, *group, *size, *mtime, *name, *m;
6463   char *endp;
6464   uint32_t mode_value;
6465
6466   ScopedXarIter xi;
6467   if (!xi) {
6468     WithColor::error(errs(), "llvm-objdump")
6469         << "can't obtain an xar iterator for xar archive " << XarFilename
6470         << "\n";
6471     return;
6472   }
6473
6474   // Go through the xar's files.
6475   for (xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)) {
6476     ScopedXarIter xp;
6477     if(!xp){
6478       WithColor::error(errs(), "llvm-objdump")
6479           << "can't obtain an xar iterator for xar archive " << XarFilename
6480           << "\n";
6481       return;
6482     }
6483     type = nullptr;
6484     mode = nullptr;
6485     user = nullptr;
6486     group = nullptr;
6487     size = nullptr;
6488     mtime = nullptr;
6489     name = nullptr;
6490     for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
6491       const char *val = nullptr;
6492       xar_prop_get(xf, key, &val);
6493 #if 0 // Useful for debugging.
6494       outs() << "key: " << key << " value: " << val << "\n";
6495 #endif
6496       if(strcmp(key, "type") == 0)
6497         type = val;
6498       if(strcmp(key, "mode") == 0)
6499         mode = val;
6500       if(strcmp(key, "user") == 0)
6501         user = val;
6502       if(strcmp(key, "group") == 0)
6503         group = val;
6504       if(strcmp(key, "data/size") == 0)
6505         size = val;
6506       if(strcmp(key, "mtime") == 0)
6507         mtime = val;
6508       if(strcmp(key, "name") == 0)
6509         name = val;
6510     }
6511     if(mode != nullptr){
6512       mode_value = strtoul(mode, &endp, 8);
6513       if(*endp != '\0')
6514         outs() << "(mode: \"" << mode << "\" contains non-octal chars) ";
6515       if(strcmp(type, "file") == 0)
6516         mode_value |= S_IFREG;
6517       PrintModeVerbose(mode_value);
6518       outs() << " ";
6519     }
6520     if(user != nullptr)
6521       outs() << format("%10s/", user);
6522     if(group != nullptr)
6523       outs() << format("%-10s ", group);
6524     if(size != nullptr)
6525       outs() << format("%7s ", size);
6526     if(mtime != nullptr){
6527       for(m = mtime; *m != 'T' && *m != '\0'; m++)
6528         outs() << *m;
6529       if(*m == 'T')
6530         m++;
6531       outs() << " ";
6532       for( ; *m != 'Z' && *m != '\0'; m++)
6533         outs() << *m;
6534       outs() << " ";
6535     }
6536     if(name != nullptr)
6537       outs() << name;
6538     outs() << "\n";
6539   }
6540 }
6541
6542 static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
6543                                 uint32_t size, bool verbose,
6544                                 bool PrintXarHeader, bool PrintXarFileHeaders,
6545                                 std::string XarMemberName) {
6546   if(size < sizeof(struct xar_header)) {
6547     outs() << "size of (__LLVM,__bundle) section too small (smaller than size "
6548               "of struct xar_header)\n";
6549     return;
6550   }
6551   struct xar_header XarHeader;
6552   memcpy(&XarHeader, sect, sizeof(struct xar_header));
6553   if (sys::IsLittleEndianHost)
6554     swapStruct(XarHeader);
6555   if (PrintXarHeader) {
6556     if (!XarMemberName.empty())
6557       outs() << "In xar member " << XarMemberName << ": ";
6558     else
6559       outs() << "For (__LLVM,__bundle) section: ";
6560     outs() << "xar header\n";
6561     if (XarHeader.magic == XAR_HEADER_MAGIC)
6562       outs() << "                  magic XAR_HEADER_MAGIC\n";
6563     else
6564       outs() << "                  magic "
6565              << format_hex(XarHeader.magic, 10, true)
6566              << " (not XAR_HEADER_MAGIC)\n";
6567     outs() << "                   size " << XarHeader.size << "\n";
6568     outs() << "                version " << XarHeader.version << "\n";
6569     outs() << "  toc_length_compressed " << XarHeader.toc_length_compressed
6570            << "\n";
6571     outs() << "toc_length_uncompressed " << XarHeader.toc_length_uncompressed
6572            << "\n";
6573     outs() << "              cksum_alg ";
6574     switch (XarHeader.cksum_alg) {
6575       case XAR_CKSUM_NONE:
6576         outs() << "XAR_CKSUM_NONE\n";
6577         break;
6578       case XAR_CKSUM_SHA1:
6579         outs() << "XAR_CKSUM_SHA1\n";
6580         break;
6581       case XAR_CKSUM_MD5:
6582         outs() << "XAR_CKSUM_MD5\n";
6583         break;
6584 #ifdef XAR_CKSUM_SHA256
6585       case XAR_CKSUM_SHA256:
6586         outs() << "XAR_CKSUM_SHA256\n";
6587         break;
6588 #endif
6589 #ifdef XAR_CKSUM_SHA512
6590       case XAR_CKSUM_SHA512:
6591         outs() << "XAR_CKSUM_SHA512\n";
6592         break;
6593 #endif
6594       default:
6595         outs() << XarHeader.cksum_alg << "\n";
6596     }
6597   }
6598
6599   SmallString<128> XarFilename;
6600   int FD;
6601   std::error_code XarEC =
6602       sys::fs::createTemporaryFile("llvm-objdump", "xar", FD, XarFilename);
6603   if (XarEC) {
6604     WithColor::error(errs(), "llvm-objdump") << XarEC.message() << "\n";
6605     return;
6606   }
6607   ToolOutputFile XarFile(XarFilename, FD);
6608   raw_fd_ostream &XarOut = XarFile.os();
6609   StringRef XarContents(sect, size);
6610   XarOut << XarContents;
6611   XarOut.close();
6612   if (XarOut.has_error())
6613     return;
6614
6615   ScopedXarFile xar(XarFilename.c_str(), READ);
6616   if (!xar) {
6617     WithColor::error(errs(), "llvm-objdump")
6618         << "can't create temporary xar archive " << XarFilename << "\n";
6619     return;
6620   }
6621
6622   SmallString<128> TocFilename;
6623   std::error_code TocEC =
6624       sys::fs::createTemporaryFile("llvm-objdump", "toc", TocFilename);
6625   if (TocEC) {
6626     WithColor::error(errs(), "llvm-objdump") << TocEC.message() << "\n";
6627     return;
6628   }
6629   xar_serialize(xar, TocFilename.c_str());
6630
6631   if (PrintXarFileHeaders) {
6632     if (!XarMemberName.empty())
6633       outs() << "In xar member " << XarMemberName << ": ";
6634     else
6635       outs() << "For (__LLVM,__bundle) section: ";
6636     outs() << "xar archive files:\n";
6637     PrintXarFilesSummary(XarFilename.c_str(), xar);
6638   }
6639
6640   ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
6641     MemoryBuffer::getFileOrSTDIN(TocFilename.c_str());
6642   if (std::error_code EC = FileOrErr.getError()) {
6643     WithColor::error(errs(), "llvm-objdump") << EC.message() << "\n";
6644     return;
6645   }
6646   std::unique_ptr<MemoryBuffer> &Buffer = FileOrErr.get();
6647
6648   if (!XarMemberName.empty())
6649     outs() << "In xar member " << XarMemberName << ": ";
6650   else
6651     outs() << "For (__LLVM,__bundle) section: ";
6652   outs() << "xar table of contents:\n";
6653   outs() << Buffer->getBuffer() << "\n";
6654
6655   // TODO: Go through the xar's files.
6656   ScopedXarIter xi;
6657   if(!xi){
6658     WithColor::error(errs(), "llvm-objdump")
6659         << "can't obtain an xar iterator for xar archive "
6660         << XarFilename.c_str() << "\n";
6661     return;
6662   }
6663   for(xar_file_t xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)){
6664     const char *key;
6665     const char *member_name, *member_type, *member_size_string;
6666     size_t member_size;
6667
6668     ScopedXarIter xp;
6669     if(!xp){
6670       WithColor::error(errs(), "llvm-objdump")
6671           << "can't obtain an xar iterator for xar archive "
6672           << XarFilename.c_str() << "\n";
6673       return;
6674     }
6675     member_name = NULL;
6676     member_type = NULL;
6677     member_size_string = NULL;
6678     for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
6679       const char *val = nullptr;
6680       xar_prop_get(xf, key, &val);
6681 #if 0 // Useful for debugging.
6682       outs() << "key: " << key << " value: " << val << "\n";
6683 #endif
6684       if (strcmp(key, "name") == 0)
6685         member_name = val;
6686       if (strcmp(key, "type") == 0)
6687         member_type = val;
6688       if (strcmp(key, "data/size") == 0)
6689         member_size_string = val;
6690     }
6691     /*
6692      * If we find a file with a name, date/size and type properties
6693      * and with the type being "file" see if that is a xar file.
6694      */
6695     if (member_name != NULL && member_type != NULL &&
6696         strcmp(member_type, "file") == 0 &&
6697         member_size_string != NULL){
6698       // Extract the file into a buffer.
6699       char *endptr;
6700       member_size = strtoul(member_size_string, &endptr, 10);
6701       if (*endptr == '\0' && member_size != 0) {
6702         char *buffer;
6703         if (xar_extract_tobuffersz(xar, xf, &buffer, &member_size) == 0) {
6704 #if 0 // Useful for debugging.
6705           outs() << "xar member: " << member_name << " extracted\n";
6706 #endif
6707           // Set the XarMemberName we want to see printed in the header.
6708           std::string OldXarMemberName;
6709           // If XarMemberName is already set this is nested. So
6710           // save the old name and create the nested name.
6711           if (!XarMemberName.empty()) {
6712             OldXarMemberName = XarMemberName;
6713             XarMemberName =
6714                 (Twine("[") + XarMemberName + "]" + member_name).str();
6715           } else {
6716             OldXarMemberName = "";
6717             XarMemberName = member_name;
6718           }
6719           // See if this is could be a xar file (nested).
6720           if (member_size >= sizeof(struct xar_header)) {
6721 #if 0 // Useful for debugging.
6722             outs() << "could be a xar file: " << member_name << "\n";
6723 #endif
6724             memcpy((char *)&XarHeader, buffer, sizeof(struct xar_header));
6725             if (sys::IsLittleEndianHost)
6726               swapStruct(XarHeader);
6727             if (XarHeader.magic == XAR_HEADER_MAGIC)
6728               DumpBitcodeSection(O, buffer, member_size, verbose,
6729                                  PrintXarHeader, PrintXarFileHeaders,
6730                                  XarMemberName);
6731           }
6732           XarMemberName = OldXarMemberName;
6733           delete buffer;
6734         }
6735       }
6736     }
6737   }
6738 }
6739 #endif // defined(HAVE_LIBXAR)
6740
6741 static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
6742   if (O->is64Bit())
6743     printObjc2_64bit_MetaData(O, verbose);
6744   else {
6745     MachO::mach_header H;
6746     H = O->getHeader();
6747     if (H.cputype == MachO::CPU_TYPE_ARM)
6748       printObjc2_32bit_MetaData(O, verbose);
6749     else {
6750       // This is the 32-bit non-arm cputype case.  Which is normally
6751       // the first Objective-C ABI.  But it may be the case of a
6752       // binary for the iOS simulator which is the second Objective-C
6753       // ABI.  In that case printObjc1_32bit_MetaData() will determine that
6754       // and return false.
6755       if (!printObjc1_32bit_MetaData(O, verbose))
6756         printObjc2_32bit_MetaData(O, verbose);
6757     }
6758   }
6759 }
6760
6761 // GuessLiteralPointer returns a string which for the item in the Mach-O file
6762 // for the address passed in as ReferenceValue for printing as a comment with
6763 // the instruction and also returns the corresponding type of that item
6764 // indirectly through ReferenceType.
6765 //
6766 // If ReferenceValue is an address of literal cstring then a pointer to the
6767 // cstring is returned and ReferenceType is set to
6768 // LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
6769 //
6770 // If ReferenceValue is an address of an Objective-C CFString, Selector ref or
6771 // Class ref that name is returned and the ReferenceType is set accordingly.
6772 //
6773 // Lastly, literals which are Symbol address in a literal pool are looked for
6774 // and if found the symbol name is returned and ReferenceType is set to
6775 // LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
6776 //
6777 // If there is no item in the Mach-O file for the address passed in as
6778 // ReferenceValue nullptr is returned and ReferenceType is unchanged.
6779 static const char *GuessLiteralPointer(uint64_t ReferenceValue,
6780                                        uint64_t ReferencePC,
6781                                        uint64_t *ReferenceType,
6782                                        struct DisassembleInfo *info) {
6783   // First see if there is an external relocation entry at the ReferencePC.
6784   if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
6785     uint64_t sect_addr = info->S.getAddress();
6786     uint64_t sect_offset = ReferencePC - sect_addr;
6787     bool reloc_found = false;
6788     DataRefImpl Rel;
6789     MachO::any_relocation_info RE;
6790     bool isExtern = false;
6791     SymbolRef Symbol;
6792     for (const RelocationRef &Reloc : info->S.relocations()) {
6793       uint64_t RelocOffset = Reloc.getOffset();
6794       if (RelocOffset == sect_offset) {
6795         Rel = Reloc.getRawDataRefImpl();
6796         RE = info->O->getRelocation(Rel);
6797         if (info->O->isRelocationScattered(RE))
6798           continue;
6799         isExtern = info->O->getPlainRelocationExternal(RE);
6800         if (isExtern) {
6801           symbol_iterator RelocSym = Reloc.getSymbol();
6802           Symbol = *RelocSym;
6803         }
6804         reloc_found = true;
6805         break;
6806       }
6807     }
6808     // If there is an external relocation entry for a symbol in a section
6809     // then used that symbol's value for the value of the reference.
6810     if (reloc_found && isExtern) {
6811       if (info->O->getAnyRelocationPCRel(RE)) {
6812         unsigned Type = info->O->getAnyRelocationType(RE);
6813         if (Type == MachO::X86_64_RELOC_SIGNED) {
6814           ReferenceValue = Symbol.getValue();
6815         }
6816       }
6817     }
6818   }
6819
6820   // Look for literals such as Objective-C CFStrings refs, Selector refs,
6821   // Message refs and Class refs.
6822   bool classref, selref, msgref, cfstring;
6823   uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
6824                                                selref, msgref, cfstring);
6825   if (classref && pointer_value == 0) {
6826     // Note the ReferenceValue is a pointer into the __objc_classrefs section.
6827     // And the pointer_value in that section is typically zero as it will be
6828     // set by dyld as part of the "bind information".
6829     const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
6830     if (name != nullptr) {
6831       *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
6832       const char *class_name = strrchr(name, '$');
6833       if (class_name != nullptr && class_name[1] == '_' &&
6834           class_name[2] != '\0') {
6835         info->class_name = class_name + 2;
6836         return name;
6837       }
6838     }
6839   }
6840
6841   if (classref) {
6842     *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
6843     const char *name =
6844         get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
6845     if (name != nullptr)
6846       info->class_name = name;
6847     else
6848       name = "bad class ref";
6849     return name;
6850   }
6851
6852   if (cfstring) {
6853     *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
6854     const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
6855     return name;
6856   }
6857
6858   if (selref && pointer_value == 0)
6859     pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
6860
6861   if (pointer_value != 0)
6862     ReferenceValue = pointer_value;
6863
6864   const char *name = GuessCstringPointer(ReferenceValue, info);
6865   if (name) {
6866     if (pointer_value != 0 && selref) {
6867       *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
6868       info->selector_name = name;
6869     } else if (pointer_value != 0 && msgref) {
6870       info->class_name = nullptr;
6871       *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
6872       info->selector_name = name;
6873     } else
6874       *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
6875     return name;
6876   }
6877
6878   // Lastly look for an indirect symbol with this ReferenceValue which is in
6879   // a literal pool.  If found return that symbol name.
6880   name = GuessIndirectSymbol(ReferenceValue, info);
6881   if (name) {
6882     *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
6883     return name;
6884   }
6885
6886   return nullptr;
6887 }
6888
6889 // SymbolizerSymbolLookUp is the symbol lookup function passed when creating
6890 // the Symbolizer.  It looks up the ReferenceValue using the info passed via the
6891 // pointer to the struct DisassembleInfo that was passed when MCSymbolizer
6892 // is created and returns the symbol name that matches the ReferenceValue or
6893 // nullptr if none.  The ReferenceType is passed in for the IN type of
6894 // reference the instruction is making from the values in defined in the header
6895 // "llvm-c/Disassembler.h".  On return the ReferenceType can set to a specific
6896 // Out type and the ReferenceName will also be set which is added as a comment
6897 // to the disassembled instruction.
6898 //
6899 // If the symbol name is a C++ mangled name then the demangled name is
6900 // returned through ReferenceName and ReferenceType is set to
6901 // LLVMDisassembler_ReferenceType_DeMangled_Name .
6902 //
6903 // When this is called to get a symbol name for a branch target then the
6904 // ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
6905 // SymbolValue will be looked for in the indirect symbol table to determine if
6906 // it is an address for a symbol stub.  If so then the symbol name for that
6907 // stub is returned indirectly through ReferenceName and then ReferenceType is
6908 // set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
6909 //
6910 // When this is called with an value loaded via a PC relative load then
6911 // ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
6912 // SymbolValue is checked to be an address of literal pointer, symbol pointer,
6913 // or an Objective-C meta data reference.  If so the output ReferenceType is
6914 // set to correspond to that as well as setting the ReferenceName.
6915 static const char *SymbolizerSymbolLookUp(void *DisInfo,
6916                                           uint64_t ReferenceValue,
6917                                           uint64_t *ReferenceType,
6918                                           uint64_t ReferencePC,
6919                                           const char **ReferenceName) {
6920   struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
6921   // If no verbose symbolic information is wanted then just return nullptr.
6922   if (!info->verbose) {
6923     *ReferenceName = nullptr;
6924     *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6925     return nullptr;
6926   }
6927
6928   const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
6929
6930   if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
6931     *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
6932     if (*ReferenceName != nullptr) {
6933       method_reference(info, ReferenceType, ReferenceName);
6934       if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
6935         *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
6936     } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
6937       if (info->demangled_name != nullptr)
6938         free(info->demangled_name);
6939       int status;
6940       info->demangled_name =
6941           itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
6942       if (info->demangled_name != nullptr) {
6943         *ReferenceName = info->demangled_name;
6944         *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
6945       } else
6946         *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6947     } else
6948       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6949   } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
6950     *ReferenceName =
6951         GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6952     if (*ReferenceName)
6953       method_reference(info, ReferenceType, ReferenceName);
6954     else
6955       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6956     // If this is arm64 and the reference is an adrp instruction save the
6957     // instruction, passed in ReferenceValue and the address of the instruction
6958     // for use later if we see and add immediate instruction.
6959   } else if (info->O->getArch() == Triple::aarch64 &&
6960              *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
6961     info->adrp_inst = ReferenceValue;
6962     info->adrp_addr = ReferencePC;
6963     SymbolName = nullptr;
6964     *ReferenceName = nullptr;
6965     *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6966     // If this is arm64 and reference is an add immediate instruction and we
6967     // have
6968     // seen an adrp instruction just before it and the adrp's Xd register
6969     // matches
6970     // this add's Xn register reconstruct the value being referenced and look to
6971     // see if it is a literal pointer.  Note the add immediate instruction is
6972     // passed in ReferenceValue.
6973   } else if (info->O->getArch() == Triple::aarch64 &&
6974              *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
6975              ReferencePC - 4 == info->adrp_addr &&
6976              (info->adrp_inst & 0x9f000000) == 0x90000000 &&
6977              (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
6978     uint32_t addxri_inst;
6979     uint64_t adrp_imm, addxri_imm;
6980
6981     adrp_imm =
6982         ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
6983     if (info->adrp_inst & 0x0200000)
6984       adrp_imm |= 0xfffffffffc000000LL;
6985
6986     addxri_inst = ReferenceValue;
6987     addxri_imm = (addxri_inst >> 10) & 0xfff;
6988     if (((addxri_inst >> 22) & 0x3) == 1)
6989       addxri_imm <<= 12;
6990
6991     ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
6992                      (adrp_imm << 12) + addxri_imm;
6993
6994     *ReferenceName =
6995         GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6996     if (*ReferenceName == nullptr)
6997       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6998     // If this is arm64 and the reference is a load register instruction and we
6999     // have seen an adrp instruction just before it and the adrp's Xd register
7000     // matches this add's Xn register reconstruct the value being referenced and
7001     // look to see if it is a literal pointer.  Note the load register
7002     // instruction is passed in ReferenceValue.
7003   } else if (info->O->getArch() == Triple::aarch64 &&
7004              *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
7005              ReferencePC - 4 == info->adrp_addr &&
7006              (info->adrp_inst & 0x9f000000) == 0x90000000 &&
7007              (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
7008     uint32_t ldrxui_inst;
7009     uint64_t adrp_imm, ldrxui_imm;
7010
7011     adrp_imm =
7012         ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
7013     if (info->adrp_inst & 0x0200000)
7014       adrp_imm |= 0xfffffffffc000000LL;
7015
7016     ldrxui_inst = ReferenceValue;
7017     ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
7018
7019     ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
7020                      (adrp_imm << 12) + (ldrxui_imm << 3);
7021
7022     *ReferenceName =
7023         GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7024     if (*ReferenceName == nullptr)
7025       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7026   }
7027   // If this arm64 and is an load register (PC-relative) instruction the
7028   // ReferenceValue is the PC plus the immediate value.
7029   else if (info->O->getArch() == Triple::aarch64 &&
7030            (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
7031             *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
7032     *ReferenceName =
7033         GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7034     if (*ReferenceName == nullptr)
7035       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7036   } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
7037     if (info->demangled_name != nullptr)
7038       free(info->demangled_name);
7039     int status;
7040     info->demangled_name =
7041         itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
7042     if (info->demangled_name != nullptr) {
7043       *ReferenceName = info->demangled_name;
7044       *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
7045     }
7046   }
7047   else {
7048     *ReferenceName = nullptr;
7049     *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7050   }
7051
7052   return SymbolName;
7053 }
7054
7055 /// Emits the comments that are stored in the CommentStream.
7056 /// Each comment in the CommentStream must end with a newline.
7057 static void emitComments(raw_svector_ostream &CommentStream,
7058                          SmallString<128> &CommentsToEmit,
7059                          formatted_raw_ostream &FormattedOS,
7060                          const MCAsmInfo &MAI) {
7061   // Flush the stream before taking its content.
7062   StringRef Comments = CommentsToEmit.str();
7063   // Get the default information for printing a comment.
7064   StringRef CommentBegin = MAI.getCommentString();
7065   unsigned CommentColumn = MAI.getCommentColumn();
7066   bool IsFirst = true;
7067   while (!Comments.empty()) {
7068     if (!IsFirst)
7069       FormattedOS << '\n';
7070     // Emit a line of comments.
7071     FormattedOS.PadToColumn(CommentColumn);
7072     size_t Position = Comments.find('\n');
7073     FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
7074     // Move after the newline character.
7075     Comments = Comments.substr(Position + 1);
7076     IsFirst = false;
7077   }
7078   FormattedOS.flush();
7079
7080   // Tell the comment stream that the vector changed underneath it.
7081   CommentsToEmit.clear();
7082 }
7083
7084 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
7085                              StringRef DisSegName, StringRef DisSectName) {
7086   const char *McpuDefault = nullptr;
7087   const Target *ThumbTarget = nullptr;
7088   const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
7089   if (!TheTarget) {
7090     // GetTarget prints out stuff.
7091     return;
7092   }
7093   std::string MachOMCPU;
7094   if (MCPU.empty() && McpuDefault)
7095     MachOMCPU = McpuDefault;
7096   else
7097     MachOMCPU = MCPU;
7098
7099   std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
7100   std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
7101   if (ThumbTarget)
7102     ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
7103
7104   // Package up features to be passed to target/subtarget
7105   std::string FeaturesStr;
7106   if (!MAttrs.empty()) {
7107     SubtargetFeatures Features;
7108     for (unsigned i = 0; i != MAttrs.size(); ++i)
7109       Features.AddFeature(MAttrs[i]);
7110     FeaturesStr = Features.getString();
7111   }
7112
7113   // Set up disassembler.
7114   std::unique_ptr<const MCRegisterInfo> MRI(
7115       TheTarget->createMCRegInfo(TripleName));
7116   std::unique_ptr<const MCAsmInfo> AsmInfo(
7117       TheTarget->createMCAsmInfo(*MRI, TripleName));
7118   std::unique_ptr<const MCSubtargetInfo> STI(
7119       TheTarget->createMCSubtargetInfo(TripleName, MachOMCPU, FeaturesStr));
7120   MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
7121   std::unique_ptr<MCDisassembler> DisAsm(
7122       TheTarget->createMCDisassembler(*STI, Ctx));
7123   std::unique_ptr<MCSymbolizer> Symbolizer;
7124   struct DisassembleInfo SymbolizerInfo(nullptr, nullptr, nullptr, false);
7125   std::unique_ptr<MCRelocationInfo> RelInfo(
7126       TheTarget->createMCRelocationInfo(TripleName, Ctx));
7127   if (RelInfo) {
7128     Symbolizer.reset(TheTarget->createMCSymbolizer(
7129         TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
7130         &SymbolizerInfo, &Ctx, std::move(RelInfo)));
7131     DisAsm->setSymbolizer(std::move(Symbolizer));
7132   }
7133   int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
7134   std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
7135       Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
7136   // Set the display preference for hex vs. decimal immediates.
7137   IP->setPrintImmHex(PrintImmHex);
7138   // Comment stream and backing vector.
7139   SmallString<128> CommentsToEmit;
7140   raw_svector_ostream CommentStream(CommentsToEmit);
7141   // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
7142   // if it is done then arm64 comments for string literals don't get printed
7143   // and some constant get printed instead and not setting it causes intel
7144   // (32-bit and 64-bit) comments printed with different spacing before the
7145   // comment causing different diffs with the 'C' disassembler library API.
7146   // IP->setCommentStream(CommentStream);
7147
7148   if (!AsmInfo || !STI || !DisAsm || !IP) {
7149     WithColor::error(errs(), "llvm-objdump")
7150         << "couldn't initialize disassembler for target " << TripleName << '\n';
7151     return;
7152   }
7153
7154   // Set up separate thumb disassembler if needed.
7155   std::unique_ptr<const MCRegisterInfo> ThumbMRI;
7156   std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
7157   std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
7158   std::unique_ptr<MCDisassembler> ThumbDisAsm;
7159   std::unique_ptr<MCInstPrinter> ThumbIP;
7160   std::unique_ptr<MCContext> ThumbCtx;
7161   std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
7162   struct DisassembleInfo ThumbSymbolizerInfo(nullptr, nullptr, nullptr, false);
7163   std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
7164   if (ThumbTarget) {
7165     ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
7166     ThumbAsmInfo.reset(
7167         ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
7168     ThumbSTI.reset(
7169         ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MachOMCPU,
7170                                            FeaturesStr));
7171     ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
7172     ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
7173     MCContext *PtrThumbCtx = ThumbCtx.get();
7174     ThumbRelInfo.reset(
7175         ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
7176     if (ThumbRelInfo) {
7177       ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
7178           ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
7179           &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
7180       ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
7181     }
7182     int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
7183     ThumbIP.reset(ThumbTarget->createMCInstPrinter(
7184         Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
7185         *ThumbInstrInfo, *ThumbMRI));
7186     // Set the display preference for hex vs. decimal immediates.
7187     ThumbIP->setPrintImmHex(PrintImmHex);
7188   }
7189
7190   if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
7191     WithColor::error(errs(), "llvm-objdump")
7192         << "couldn't initialize disassembler for target " << ThumbTripleName
7193         << '\n';
7194     return;
7195   }
7196
7197   MachO::mach_header Header = MachOOF->getHeader();
7198
7199   // FIXME: Using the -cfg command line option, this code used to be able to
7200   // annotate relocations with the referenced symbol's name, and if this was
7201   // inside a __[cf]string section, the data it points to. This is now replaced
7202   // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
7203   std::vector<SectionRef> Sections;
7204   std::vector<SymbolRef> Symbols;
7205   SmallVector<uint64_t, 8> FoundFns;
7206   uint64_t BaseSegmentAddress;
7207
7208   getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
7209                         BaseSegmentAddress);
7210
7211   // Sort the symbols by address, just in case they didn't come in that way.
7212   llvm::sort(Symbols, SymbolSorter());
7213
7214   // Build a data in code table that is sorted on by the address of each entry.
7215   uint64_t BaseAddress = 0;
7216   if (Header.filetype == MachO::MH_OBJECT)
7217     BaseAddress = Sections[0].getAddress();
7218   else
7219     BaseAddress = BaseSegmentAddress;
7220   DiceTable Dices;
7221   for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
7222        DI != DE; ++DI) {
7223     uint32_t Offset;
7224     DI->getOffset(Offset);
7225     Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
7226   }
7227   array_pod_sort(Dices.begin(), Dices.end());
7228
7229 #ifndef NDEBUG
7230   raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
7231 #else
7232   raw_ostream &DebugOut = nulls();
7233 #endif
7234
7235   // Try to find debug info and set up the DIContext for it.
7236   std::unique_ptr<DIContext> diContext;
7237   std::unique_ptr<Binary> DSYMBinary;
7238   std::unique_ptr<MemoryBuffer> DSYMBuf;
7239   if (UseDbg) {
7240     ObjectFile *DbgObj = MachOOF;
7241
7242     // A separate DSym file path was specified, parse it as a macho file,
7243     // get the sections and supply it to the section name parsing machinery.
7244     if (!DSYMFile.empty()) {
7245       ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
7246           MemoryBuffer::getFileOrSTDIN(DSYMFile);
7247       if (std::error_code EC = BufOrErr.getError()) {
7248         report_error(errorCodeToError(EC), DSYMFile);
7249         return;
7250       }
7251
7252       // We need to keep the file alive, because we're replacing DbgObj with it.
7253       DSYMBuf = std::move(BufOrErr.get());
7254
7255       Expected<std::unique_ptr<Binary>> BinaryOrErr =
7256       createBinary(DSYMBuf.get()->getMemBufferRef());
7257       if (!BinaryOrErr) {
7258         report_error(BinaryOrErr.takeError(), DSYMFile);
7259         return;
7260       }
7261
7262       // We need to keep the Binary elive with the buffer
7263       DSYMBinary = std::move(BinaryOrErr.get());
7264     
7265       if (ObjectFile *O = dyn_cast<ObjectFile>(DSYMBinary.get())) {
7266         // this is a Mach-O object file, use it
7267         if (MachOObjectFile *MachDSYM = dyn_cast<MachOObjectFile>(&*O)) {
7268           DbgObj = MachDSYM;
7269         }
7270         else {
7271           WithColor::error(errs(), "llvm-objdump")
7272             << DSYMFile << " is not a Mach-O file type.\n";
7273           return;
7274         }
7275       }
7276       else if (auto UB = dyn_cast<MachOUniversalBinary>(DSYMBinary.get())){
7277         // this is a Universal Binary, find a Mach-O for this architecture
7278         uint32_t CPUType, CPUSubType;
7279         const char *ArchFlag;
7280         if (MachOOF->is64Bit()) {
7281           const MachO::mach_header_64 H_64 = MachOOF->getHeader64();
7282           CPUType = H_64.cputype;
7283           CPUSubType = H_64.cpusubtype;
7284         } else {
7285           const MachO::mach_header H = MachOOF->getHeader();
7286           CPUType = H.cputype;
7287           CPUSubType = H.cpusubtype;
7288         }
7289         Triple T = MachOObjectFile::getArchTriple(CPUType, CPUSubType, nullptr,
7290                                                   &ArchFlag);
7291         Expected<std::unique_ptr<MachOObjectFile>> MachDSYM =
7292             UB->getObjectForArch(ArchFlag);
7293         if (!MachDSYM) {
7294           report_error(MachDSYM.takeError(), DSYMFile);
7295           return;
7296         }
7297     
7298         // We need to keep the Binary elive with the buffer
7299         DbgObj = &*MachDSYM.get();
7300         DSYMBinary = std::move(*MachDSYM);
7301       }
7302       else {
7303         WithColor::error(errs(), "llvm-objdump")
7304           << DSYMFile << " is not a Mach-O or Universal file type.\n";
7305         return;
7306       }
7307     }
7308
7309     // Setup the DIContext
7310     diContext = DWARFContext::create(*DbgObj);
7311   }
7312
7313   if (FilterSections.empty())
7314     outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
7315
7316   for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
7317     StringRef SectName;
7318     if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
7319       continue;
7320
7321     DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
7322
7323     StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
7324     if (SegmentName != DisSegName)
7325       continue;
7326
7327     StringRef BytesStr =
7328         unwrapOrError(Sections[SectIdx].getContents(), Filename);
7329     ArrayRef<uint8_t> Bytes = arrayRefFromStringRef(BytesStr);
7330     uint64_t SectAddress = Sections[SectIdx].getAddress();
7331
7332     bool symbolTableWorked = false;
7333
7334     // Create a map of symbol addresses to symbol names for use by
7335     // the SymbolizerSymbolLookUp() routine.
7336     SymbolAddressMap AddrMap;
7337     bool DisSymNameFound = false;
7338     for (const SymbolRef &Symbol : MachOOF->symbols()) {
7339       SymbolRef::Type ST =
7340           unwrapOrError(Symbol.getType(), MachOOF->getFileName());
7341       if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
7342           ST == SymbolRef::ST_Other) {
7343         uint64_t Address = Symbol.getValue();
7344         StringRef SymName =
7345             unwrapOrError(Symbol.getName(), MachOOF->getFileName());
7346         AddrMap[Address] = SymName;
7347         if (!DisSymName.empty() && DisSymName == SymName)
7348           DisSymNameFound = true;
7349       }
7350     }
7351     if (!DisSymName.empty() && !DisSymNameFound) {
7352       outs() << "Can't find -dis-symname: " << DisSymName << "\n";
7353       return;
7354     }
7355     // Set up the block of info used by the Symbolizer call backs.
7356     SymbolizerInfo.verbose = !NoSymbolicOperands;
7357     SymbolizerInfo.O = MachOOF;
7358     SymbolizerInfo.S = Sections[SectIdx];
7359     SymbolizerInfo.AddrMap = &AddrMap;
7360     SymbolizerInfo.Sections = &Sections;
7361     // Same for the ThumbSymbolizer
7362     ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
7363     ThumbSymbolizerInfo.O = MachOOF;
7364     ThumbSymbolizerInfo.S = Sections[SectIdx];
7365     ThumbSymbolizerInfo.AddrMap = &AddrMap;
7366     ThumbSymbolizerInfo.Sections = &Sections;
7367
7368     unsigned int Arch = MachOOF->getArch();
7369
7370     // Skip all symbols if this is a stubs file.
7371     if (Bytes.empty())
7372       return;
7373
7374     // If the section has symbols but no symbol at the start of the section
7375     // these are used to make sure the bytes before the first symbol are
7376     // disassembled.
7377     bool FirstSymbol = true;
7378     bool FirstSymbolAtSectionStart = true;
7379
7380     // Disassemble symbol by symbol.
7381     for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
7382       StringRef SymName =
7383           unwrapOrError(Symbols[SymIdx].getName(), MachOOF->getFileName());
7384       SymbolRef::Type ST =
7385           unwrapOrError(Symbols[SymIdx].getType(), MachOOF->getFileName());
7386       if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
7387         continue;
7388
7389       // Make sure the symbol is defined in this section.
7390       bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
7391       if (!containsSym) {
7392         if (!DisSymName.empty() && DisSymName == SymName) {
7393           outs() << "-dis-symname: " << DisSymName << " not in the section\n";
7394           return;
7395         }
7396         continue;
7397       }
7398       // The __mh_execute_header is special and we need to deal with that fact
7399       // this symbol is before the start of the (__TEXT,__text) section and at the
7400       // address of the start of the __TEXT segment.  This is because this symbol
7401       // is an N_SECT symbol in the (__TEXT,__text) but its address is before the
7402       // start of the section in a standard MH_EXECUTE filetype.
7403       if (!DisSymName.empty() && DisSymName == "__mh_execute_header") {
7404         outs() << "-dis-symname: __mh_execute_header not in any section\n";
7405         return;
7406       }
7407       // When this code is trying to disassemble a symbol at a time and in the
7408       // case there is only the __mh_execute_header symbol left as in a stripped
7409       // executable, we need to deal with this by ignoring this symbol so the
7410       // whole section is disassembled and this symbol is then not displayed.
7411       if (SymName == "__mh_execute_header" || SymName == "__mh_dylib_header" ||
7412           SymName == "__mh_bundle_header" || SymName == "__mh_object_header" ||
7413           SymName == "__mh_preload_header" || SymName == "__mh_dylinker_header")
7414         continue;
7415
7416       // If we are only disassembling one symbol see if this is that symbol.
7417       if (!DisSymName.empty() && DisSymName != SymName)
7418         continue;
7419
7420       // Start at the address of the symbol relative to the section's address.
7421       uint64_t SectSize = Sections[SectIdx].getSize();
7422       uint64_t Start = Symbols[SymIdx].getValue();
7423       uint64_t SectionAddress = Sections[SectIdx].getAddress();
7424       Start -= SectionAddress;
7425
7426       if (Start > SectSize) {
7427         outs() << "section data ends, " << SymName
7428                << " lies outside valid range\n";
7429         return;
7430       }
7431
7432       // Stop disassembling either at the beginning of the next symbol or at
7433       // the end of the section.
7434       bool containsNextSym = false;
7435       uint64_t NextSym = 0;
7436       uint64_t NextSymIdx = SymIdx + 1;
7437       while (Symbols.size() > NextSymIdx) {
7438         SymbolRef::Type NextSymType = unwrapOrError(
7439             Symbols[NextSymIdx].getType(), MachOOF->getFileName());
7440         if (NextSymType == SymbolRef::ST_Function) {
7441           containsNextSym =
7442               Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
7443           NextSym = Symbols[NextSymIdx].getValue();
7444           NextSym -= SectionAddress;
7445           break;
7446         }
7447         ++NextSymIdx;
7448       }
7449
7450       uint64_t End = containsNextSym ? std::min(NextSym, SectSize) : SectSize;
7451       uint64_t Size;
7452
7453       symbolTableWorked = true;
7454
7455       DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
7456       bool IsThumb = MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb;
7457
7458       // We only need the dedicated Thumb target if there's a real choice
7459       // (i.e. we're not targeting M-class) and the function is Thumb.
7460       bool UseThumbTarget = IsThumb && ThumbTarget;
7461
7462       // If we are not specifying a symbol to start disassembly with and this
7463       // is the first symbol in the section but not at the start of the section
7464       // then move the disassembly index to the start of the section and
7465       // don't print the symbol name just yet.  This is so the bytes before the
7466       // first symbol are disassembled.
7467       uint64_t SymbolStart = Start;
7468       if (DisSymName.empty() && FirstSymbol && Start != 0) {
7469         FirstSymbolAtSectionStart = false;
7470         Start = 0;
7471       }
7472       else
7473         outs() << SymName << ":\n";
7474
7475       DILineInfo lastLine;
7476       for (uint64_t Index = Start; Index < End; Index += Size) {
7477         MCInst Inst;
7478
7479         // If this is the first symbol in the section and it was not at the
7480         // start of the section, see if we are at its Index now and if so print
7481         // the symbol name.
7482         if (FirstSymbol && !FirstSymbolAtSectionStart && Index == SymbolStart)
7483           outs() << SymName << ":\n";
7484
7485         uint64_t PC = SectAddress + Index;
7486         if (!NoLeadingAddr) {
7487           if (FullLeadingAddr) {
7488             if (MachOOF->is64Bit())
7489               outs() << format("%016" PRIx64, PC);
7490             else
7491               outs() << format("%08" PRIx64, PC);
7492           } else {
7493             outs() << format("%8" PRIx64 ":", PC);
7494           }
7495         }
7496         if (!NoShowRawInsn || Arch == Triple::arm)
7497           outs() << "\t";
7498
7499         // Check the data in code table here to see if this is data not an
7500         // instruction to be disassembled.
7501         DiceTable Dice;
7502         Dice.push_back(std::make_pair(PC, DiceRef()));
7503         dice_table_iterator DTI =
7504             std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
7505                         compareDiceTableEntries);
7506         if (DTI != Dices.end()) {
7507           uint16_t Length;
7508           DTI->second.getLength(Length);
7509           uint16_t Kind;
7510           DTI->second.getKind(Kind);
7511           Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
7512           if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
7513               (PC == (DTI->first + Length - 1)) && (Length & 1))
7514             Size++;
7515           continue;
7516         }
7517
7518         SmallVector<char, 64> AnnotationsBytes;
7519         raw_svector_ostream Annotations(AnnotationsBytes);
7520
7521         bool gotInst;
7522         if (UseThumbTarget)
7523           gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
7524                                                 PC, DebugOut, Annotations);
7525         else
7526           gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
7527                                            DebugOut, Annotations);
7528         if (gotInst) {
7529           if (!NoShowRawInsn || Arch == Triple::arm) {
7530             dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
7531           }
7532           formatted_raw_ostream FormattedOS(outs());
7533           StringRef AnnotationsStr = Annotations.str();
7534           if (UseThumbTarget)
7535             ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
7536           else
7537             IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
7538           emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
7539
7540           // Print debug info.
7541           if (diContext) {
7542             DILineInfo dli = diContext->getLineInfoForAddress({PC, SectIdx});
7543             // Print valid line info if it changed.
7544             if (dli != lastLine && dli.Line != 0)
7545               outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
7546                      << dli.Column;
7547             lastLine = dli;
7548           }
7549           outs() << "\n";
7550         } else {
7551           unsigned int Arch = MachOOF->getArch();
7552           if (Arch == Triple::x86_64 || Arch == Triple::x86) {
7553             outs() << format("\t.byte 0x%02x #bad opcode\n",
7554                              *(Bytes.data() + Index) & 0xff);
7555             Size = 1; // skip exactly one illegible byte and move on.
7556           } else if (Arch == Triple::aarch64 ||
7557                      (Arch == Triple::arm && !IsThumb)) {
7558             uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7559                               (*(Bytes.data() + Index + 1) & 0xff) << 8 |
7560                               (*(Bytes.data() + Index + 2) & 0xff) << 16 |
7561                               (*(Bytes.data() + Index + 3) & 0xff) << 24;
7562             outs() << format("\t.long\t0x%08x\n", opcode);
7563             Size = 4;
7564           } else if (Arch == Triple::arm) {
7565             assert(IsThumb && "ARM mode should have been dealt with above");
7566             uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7567                               (*(Bytes.data() + Index + 1) & 0xff) << 8;
7568             outs() << format("\t.short\t0x%04x\n", opcode);
7569             Size = 2;
7570           } else{
7571             WithColor::warning(errs(), "llvm-objdump")
7572                 << "invalid instruction encoding\n";
7573             if (Size == 0)
7574               Size = 1; // skip illegible bytes
7575           }
7576         }
7577       }
7578       // Now that we are done disassembled the first symbol set the bool that
7579       // were doing this to false.
7580       FirstSymbol = false;
7581     }
7582     if (!symbolTableWorked) {
7583       // Reading the symbol table didn't work, disassemble the whole section.
7584       uint64_t SectAddress = Sections[SectIdx].getAddress();
7585       uint64_t SectSize = Sections[SectIdx].getSize();
7586       uint64_t InstSize;
7587       for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
7588         MCInst Inst;
7589
7590         uint64_t PC = SectAddress + Index;
7591         SmallVector<char, 64> AnnotationsBytes;
7592         raw_svector_ostream Annotations(AnnotationsBytes);
7593         if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
7594                                    DebugOut, Annotations)) {
7595           if (!NoLeadingAddr) {
7596             if (FullLeadingAddr) {
7597               if (MachOOF->is64Bit())
7598                 outs() << format("%016" PRIx64, PC);
7599               else
7600                 outs() << format("%08" PRIx64, PC);
7601             } else {
7602               outs() << format("%8" PRIx64 ":", PC);
7603             }
7604           }
7605           if (!NoShowRawInsn || Arch == Triple::arm) {
7606             outs() << "\t";
7607             dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
7608           }
7609           StringRef AnnotationsStr = Annotations.str();
7610           IP->printInst(&Inst, outs(), AnnotationsStr, *STI);
7611           outs() << "\n";
7612         } else {
7613           unsigned int Arch = MachOOF->getArch();
7614           if (Arch == Triple::x86_64 || Arch == Triple::x86) {
7615             outs() << format("\t.byte 0x%02x #bad opcode\n",
7616                              *(Bytes.data() + Index) & 0xff);
7617             InstSize = 1; // skip exactly one illegible byte and move on.
7618           } else {
7619             WithColor::warning(errs(), "llvm-objdump")
7620                 << "invalid instruction encoding\n";
7621             if (InstSize == 0)
7622               InstSize = 1; // skip illegible bytes
7623           }
7624         }
7625       }
7626     }
7627     // The TripleName's need to be reset if we are called again for a different
7628     // archtecture.
7629     TripleName = "";
7630     ThumbTripleName = "";
7631
7632     if (SymbolizerInfo.demangled_name != nullptr)
7633       free(SymbolizerInfo.demangled_name);
7634     if (ThumbSymbolizerInfo.demangled_name != nullptr)
7635       free(ThumbSymbolizerInfo.demangled_name);
7636   }
7637 }
7638
7639 //===----------------------------------------------------------------------===//
7640 // __compact_unwind section dumping
7641 //===----------------------------------------------------------------------===//
7642
7643 namespace {
7644
7645 template <typename T>
7646 static uint64_t read(StringRef Contents, ptrdiff_t Offset) {
7647   using llvm::support::little;
7648   using llvm::support::unaligned;
7649
7650   if (Offset + sizeof(T) > Contents.size()) {
7651     outs() << "warning: attempt to read past end of buffer\n";
7652     return T();
7653   }
7654
7655   uint64_t Val =
7656       support::endian::read<T, little, unaligned>(Contents.data() + Offset);
7657   return Val;
7658 }
7659
7660 template <typename T>
7661 static uint64_t readNext(StringRef Contents, ptrdiff_t &Offset) {
7662   T Val = read<T>(Contents, Offset);
7663   Offset += sizeof(T);
7664   return Val;
7665 }
7666
7667 struct CompactUnwindEntry {
7668   uint32_t OffsetInSection;
7669
7670   uint64_t FunctionAddr;
7671   uint32_t Length;
7672   uint32_t CompactEncoding;
7673   uint64_t PersonalityAddr;
7674   uint64_t LSDAAddr;
7675
7676   RelocationRef FunctionReloc;
7677   RelocationRef PersonalityReloc;
7678   RelocationRef LSDAReloc;
7679
7680   CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
7681       : OffsetInSection(Offset) {
7682     if (Is64)
7683       read<uint64_t>(Contents, Offset);
7684     else
7685       read<uint32_t>(Contents, Offset);
7686   }
7687
7688 private:
7689   template <typename UIntPtr> void read(StringRef Contents, ptrdiff_t Offset) {
7690     FunctionAddr = readNext<UIntPtr>(Contents, Offset);
7691     Length = readNext<uint32_t>(Contents, Offset);
7692     CompactEncoding = readNext<uint32_t>(Contents, Offset);
7693     PersonalityAddr = readNext<UIntPtr>(Contents, Offset);
7694     LSDAAddr = readNext<UIntPtr>(Contents, Offset);
7695   }
7696 };
7697 }
7698
7699 /// Given a relocation from __compact_unwind, consisting of the RelocationRef
7700 /// and data being relocated, determine the best base Name and Addend to use for
7701 /// display purposes.
7702 ///
7703 /// 1. An Extern relocation will directly reference a symbol (and the data is
7704 ///    then already an addend), so use that.
7705 /// 2. Otherwise the data is an offset in the object file's layout; try to find
7706 //     a symbol before it in the same section, and use the offset from there.
7707 /// 3. Finally, if all that fails, fall back to an offset from the start of the
7708 ///    referenced section.
7709 static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
7710                                       std::map<uint64_t, SymbolRef> &Symbols,
7711                                       const RelocationRef &Reloc, uint64_t Addr,
7712                                       StringRef &Name, uint64_t &Addend) {
7713   if (Reloc.getSymbol() != Obj->symbol_end()) {
7714     Name = unwrapOrError(Reloc.getSymbol()->getName(), Obj->getFileName());
7715     Addend = Addr;
7716     return;
7717   }
7718
7719   auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
7720   SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
7721
7722   uint64_t SectionAddr = RelocSection.getAddress();
7723
7724   auto Sym = Symbols.upper_bound(Addr);
7725   if (Sym == Symbols.begin()) {
7726     // The first symbol in the object is after this reference, the best we can
7727     // do is section-relative notation.
7728     RelocSection.getName(Name);
7729     Addend = Addr - SectionAddr;
7730     return;
7731   }
7732
7733   // Go back one so that SymbolAddress <= Addr.
7734   --Sym;
7735
7736   section_iterator SymSection =
7737       unwrapOrError(Sym->second.getSection(), Obj->getFileName());
7738   if (RelocSection == *SymSection) {
7739     // There's a valid symbol in the same section before this reference.
7740     Name = unwrapOrError(Sym->second.getName(), Obj->getFileName());
7741     Addend = Addr - Sym->first;
7742     return;
7743   }
7744
7745   // There is a symbol before this reference, but it's in a different
7746   // section. Probably not helpful to mention it, so use the section name.
7747   RelocSection.getName(Name);
7748   Addend = Addr - SectionAddr;
7749 }
7750
7751 static void printUnwindRelocDest(const MachOObjectFile *Obj,
7752                                  std::map<uint64_t, SymbolRef> &Symbols,
7753                                  const RelocationRef &Reloc, uint64_t Addr) {
7754   StringRef Name;
7755   uint64_t Addend;
7756
7757   if (!Reloc.getObject())
7758     return;
7759
7760   findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
7761
7762   outs() << Name;
7763   if (Addend)
7764     outs() << " + " << format("0x%" PRIx64, Addend);
7765 }
7766
7767 static void
7768 printMachOCompactUnwindSection(const MachOObjectFile *Obj,
7769                                std::map<uint64_t, SymbolRef> &Symbols,
7770                                const SectionRef &CompactUnwind) {
7771
7772   if (!Obj->isLittleEndian()) {
7773     outs() << "Skipping big-endian __compact_unwind section\n";
7774     return;
7775   }
7776
7777   bool Is64 = Obj->is64Bit();
7778   uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
7779   uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
7780
7781   StringRef Contents =
7782       unwrapOrError(CompactUnwind.getContents(), Obj->getFileName());
7783   SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
7784
7785   // First populate the initial raw offsets, encodings and so on from the entry.
7786   for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
7787     CompactUnwindEntry Entry(Contents, Offset, Is64);
7788     CompactUnwinds.push_back(Entry);
7789   }
7790
7791   // Next we need to look at the relocations to find out what objects are
7792   // actually being referred to.
7793   for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
7794     uint64_t RelocAddress = Reloc.getOffset();
7795
7796     uint32_t EntryIdx = RelocAddress / EntrySize;
7797     uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
7798     CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
7799
7800     if (OffsetInEntry == 0)
7801       Entry.FunctionReloc = Reloc;
7802     else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
7803       Entry.PersonalityReloc = Reloc;
7804     else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
7805       Entry.LSDAReloc = Reloc;
7806     else {
7807       outs() << "Invalid relocation in __compact_unwind section\n";
7808       return;
7809     }
7810   }
7811
7812   // Finally, we're ready to print the data we've gathered.
7813   outs() << "Contents of __compact_unwind section:\n";
7814   for (auto &Entry : CompactUnwinds) {
7815     outs() << "  Entry at offset "
7816            << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
7817
7818     // 1. Start of the region this entry applies to.
7819     outs() << "    start:                " << format("0x%" PRIx64,
7820                                                      Entry.FunctionAddr) << ' ';
7821     printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
7822     outs() << '\n';
7823
7824     // 2. Length of the region this entry applies to.
7825     outs() << "    length:               " << format("0x%" PRIx32, Entry.Length)
7826            << '\n';
7827     // 3. The 32-bit compact encoding.
7828     outs() << "    compact encoding:     "
7829            << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
7830
7831     // 4. The personality function, if present.
7832     if (Entry.PersonalityReloc.getObject()) {
7833       outs() << "    personality function: "
7834              << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
7835       printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
7836                            Entry.PersonalityAddr);
7837       outs() << '\n';
7838     }
7839
7840     // 5. This entry's language-specific data area.
7841     if (Entry.LSDAReloc.getObject()) {
7842       outs() << "    LSDA:                 " << format("0x%" PRIx64,
7843                                                        Entry.LSDAAddr) << ' ';
7844       printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
7845       outs() << '\n';
7846     }
7847   }
7848 }
7849
7850 //===----------------------------------------------------------------------===//
7851 // __unwind_info section dumping
7852 //===----------------------------------------------------------------------===//
7853
7854 static void printRegularSecondLevelUnwindPage(StringRef PageData) {
7855   ptrdiff_t Pos = 0;
7856   uint32_t Kind = readNext<uint32_t>(PageData, Pos);
7857   (void)Kind;
7858   assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
7859
7860   uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
7861   uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
7862
7863   Pos = EntriesStart;
7864   for (unsigned i = 0; i < NumEntries; ++i) {
7865     uint32_t FunctionOffset = readNext<uint32_t>(PageData, Pos);
7866     uint32_t Encoding = readNext<uint32_t>(PageData, Pos);
7867
7868     outs() << "      [" << i << "]: "
7869            << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7870            << ", "
7871            << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
7872   }
7873 }
7874
7875 static void printCompressedSecondLevelUnwindPage(
7876     StringRef PageData, uint32_t FunctionBase,
7877     const SmallVectorImpl<uint32_t> &CommonEncodings) {
7878   ptrdiff_t Pos = 0;
7879   uint32_t Kind = readNext<uint32_t>(PageData, Pos);
7880   (void)Kind;
7881   assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
7882
7883   uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
7884   uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
7885
7886   uint16_t EncodingsStart = readNext<uint16_t>(PageData, Pos);
7887   readNext<uint16_t>(PageData, Pos);
7888   StringRef PageEncodings = PageData.substr(EncodingsStart, StringRef::npos);
7889
7890   Pos = EntriesStart;
7891   for (unsigned i = 0; i < NumEntries; ++i) {
7892     uint32_t Entry = readNext<uint32_t>(PageData, Pos);
7893     uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
7894     uint32_t EncodingIdx = Entry >> 24;
7895
7896     uint32_t Encoding;
7897     if (EncodingIdx < CommonEncodings.size())
7898       Encoding = CommonEncodings[EncodingIdx];
7899     else
7900       Encoding = read<uint32_t>(PageEncodings,
7901                                 sizeof(uint32_t) *
7902                                     (EncodingIdx - CommonEncodings.size()));
7903
7904     outs() << "      [" << i << "]: "
7905            << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7906            << ", "
7907            << "encoding[" << EncodingIdx
7908            << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
7909   }
7910 }
7911
7912 static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
7913                                         std::map<uint64_t, SymbolRef> &Symbols,
7914                                         const SectionRef &UnwindInfo) {
7915
7916   if (!Obj->isLittleEndian()) {
7917     outs() << "Skipping big-endian __unwind_info section\n";
7918     return;
7919   }
7920
7921   outs() << "Contents of __unwind_info section:\n";
7922
7923   StringRef Contents =
7924       unwrapOrError(UnwindInfo.getContents(), Obj->getFileName());
7925   ptrdiff_t Pos = 0;
7926
7927   //===----------------------------------
7928   // Section header
7929   //===----------------------------------
7930
7931   uint32_t Version = readNext<uint32_t>(Contents, Pos);
7932   outs() << "  Version:                                   "
7933          << format("0x%" PRIx32, Version) << '\n';
7934   if (Version != 1) {
7935     outs() << "    Skipping section with unknown version\n";
7936     return;
7937   }
7938
7939   uint32_t CommonEncodingsStart = readNext<uint32_t>(Contents, Pos);
7940   outs() << "  Common encodings array section offset:     "
7941          << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
7942   uint32_t NumCommonEncodings = readNext<uint32_t>(Contents, Pos);
7943   outs() << "  Number of common encodings in array:       "
7944          << format("0x%" PRIx32, NumCommonEncodings) << '\n';
7945
7946   uint32_t PersonalitiesStart = readNext<uint32_t>(Contents, Pos);
7947   outs() << "  Personality function array section offset: "
7948          << format("0x%" PRIx32, PersonalitiesStart) << '\n';
7949   uint32_t NumPersonalities = readNext<uint32_t>(Contents, Pos);
7950   outs() << "  Number of personality functions in array:  "
7951          << format("0x%" PRIx32, NumPersonalities) << '\n';
7952
7953   uint32_t IndicesStart = readNext<uint32_t>(Contents, Pos);
7954   outs() << "  Index array section offset:                "
7955          << format("0x%" PRIx32, IndicesStart) << '\n';
7956   uint32_t NumIndices = readNext<uint32_t>(Contents, Pos);
7957   outs() << "  Number of indices in array:                "
7958          << format("0x%" PRIx32, NumIndices) << '\n';
7959
7960   //===----------------------------------
7961   // A shared list of common encodings
7962   //===----------------------------------
7963
7964   // These occupy indices in the range [0, N] whenever an encoding is referenced
7965   // from a compressed 2nd level index table. In practice the linker only
7966   // creates ~128 of these, so that indices are available to embed encodings in
7967   // the 2nd level index.
7968
7969   SmallVector<uint32_t, 64> CommonEncodings;
7970   outs() << "  Common encodings: (count = " << NumCommonEncodings << ")\n";
7971   Pos = CommonEncodingsStart;
7972   for (unsigned i = 0; i < NumCommonEncodings; ++i) {
7973     uint32_t Encoding = readNext<uint32_t>(Contents, Pos);
7974     CommonEncodings.push_back(Encoding);
7975
7976     outs() << "    encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
7977            << '\n';
7978   }
7979
7980   //===----------------------------------
7981   // Personality functions used in this executable
7982   //===----------------------------------
7983
7984   // There should be only a handful of these (one per source language,
7985   // roughly). Particularly since they only get 2 bits in the compact encoding.
7986
7987   outs() << "  Personality functions: (count = " << NumPersonalities << ")\n";
7988   Pos = PersonalitiesStart;
7989   for (unsigned i = 0; i < NumPersonalities; ++i) {
7990     uint32_t PersonalityFn = readNext<uint32_t>(Contents, Pos);
7991     outs() << "    personality[" << i + 1
7992            << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
7993   }
7994
7995   //===----------------------------------
7996   // The level 1 index entries
7997   //===----------------------------------
7998
7999   // These specify an approximate place to start searching for the more detailed
8000   // information, sorted by PC.
8001
8002   struct IndexEntry {
8003     uint32_t FunctionOffset;
8004     uint32_t SecondLevelPageStart;
8005     uint32_t LSDAStart;
8006   };
8007
8008   SmallVector<IndexEntry, 4> IndexEntries;
8009
8010   outs() << "  Top level indices: (count = " << NumIndices << ")\n";
8011   Pos = IndicesStart;
8012   for (unsigned i = 0; i < NumIndices; ++i) {
8013     IndexEntry Entry;
8014
8015     Entry.FunctionOffset = readNext<uint32_t>(Contents, Pos);
8016     Entry.SecondLevelPageStart = readNext<uint32_t>(Contents, Pos);
8017     Entry.LSDAStart = readNext<uint32_t>(Contents, Pos);
8018     IndexEntries.push_back(Entry);
8019
8020     outs() << "    [" << i << "]: "
8021            << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
8022            << ", "
8023            << "2nd level page offset="
8024            << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
8025            << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
8026   }
8027
8028   //===----------------------------------
8029   // Next come the LSDA tables
8030   //===----------------------------------
8031
8032   // The LSDA layout is rather implicit: it's a contiguous array of entries from
8033   // the first top-level index's LSDAOffset to the last (sentinel).
8034
8035   outs() << "  LSDA descriptors:\n";
8036   Pos = IndexEntries[0].LSDAStart;
8037   const uint32_t LSDASize = 2 * sizeof(uint32_t);
8038   int NumLSDAs =
8039       (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) / LSDASize;
8040
8041   for (int i = 0; i < NumLSDAs; ++i) {
8042     uint32_t FunctionOffset = readNext<uint32_t>(Contents, Pos);
8043     uint32_t LSDAOffset = readNext<uint32_t>(Contents, Pos);
8044     outs() << "    [" << i << "]: "
8045            << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
8046            << ", "
8047            << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
8048   }
8049
8050   //===----------------------------------
8051   // Finally, the 2nd level indices
8052   //===----------------------------------
8053
8054   // Generally these are 4K in size, and have 2 possible forms:
8055   //   + Regular stores up to 511 entries with disparate encodings
8056   //   + Compressed stores up to 1021 entries if few enough compact encoding
8057   //     values are used.
8058   outs() << "  Second level indices:\n";
8059   for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
8060     // The final sentinel top-level index has no associated 2nd level page
8061     if (IndexEntries[i].SecondLevelPageStart == 0)
8062       break;
8063
8064     outs() << "    Second level index[" << i << "]: "
8065            << "offset in section="
8066            << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
8067            << ", "
8068            << "base function offset="
8069            << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
8070
8071     Pos = IndexEntries[i].SecondLevelPageStart;
8072     if (Pos + sizeof(uint32_t) > Contents.size()) {
8073       outs() << "warning: invalid offset for second level page: " << Pos << '\n';
8074       continue;
8075     }
8076
8077     uint32_t Kind =
8078         *reinterpret_cast<const support::ulittle32_t *>(Contents.data() + Pos);
8079     if (Kind == 2)
8080       printRegularSecondLevelUnwindPage(Contents.substr(Pos, 4096));
8081     else if (Kind == 3)
8082       printCompressedSecondLevelUnwindPage(Contents.substr(Pos, 4096),
8083                                            IndexEntries[i].FunctionOffset,
8084                                            CommonEncodings);
8085     else
8086       outs() << "    Skipping 2nd level page with unknown kind " << Kind
8087              << '\n';
8088   }
8089 }
8090
8091 void printMachOUnwindInfo(const MachOObjectFile *Obj) {
8092   std::map<uint64_t, SymbolRef> Symbols;
8093   for (const SymbolRef &SymRef : Obj->symbols()) {
8094     // Discard any undefined or absolute symbols. They're not going to take part
8095     // in the convenience lookup for unwind info and just take up resources.
8096     auto SectOrErr = SymRef.getSection();
8097     if (!SectOrErr) {
8098       // TODO: Actually report errors helpfully.
8099       consumeError(SectOrErr.takeError());
8100       continue;
8101     }
8102     section_iterator Section = *SectOrErr;
8103     if (Section == Obj->section_end())
8104       continue;
8105
8106     uint64_t Addr = SymRef.getValue();
8107     Symbols.insert(std::make_pair(Addr, SymRef));
8108   }
8109
8110   for (const SectionRef &Section : Obj->sections()) {
8111     StringRef SectName;
8112     Section.getName(SectName);
8113     if (SectName == "__compact_unwind")
8114       printMachOCompactUnwindSection(Obj, Symbols, Section);
8115     else if (SectName == "__unwind_info")
8116       printMachOUnwindInfoSection(Obj, Symbols, Section);
8117   }
8118 }
8119
8120 static void PrintMachHeader(uint32_t magic, uint32_t cputype,
8121                             uint32_t cpusubtype, uint32_t filetype,
8122                             uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
8123                             bool verbose) {
8124   outs() << "Mach header\n";
8125   outs() << "      magic cputype cpusubtype  caps    filetype ncmds "
8126             "sizeofcmds      flags\n";
8127   if (verbose) {
8128     if (magic == MachO::MH_MAGIC)
8129       outs() << "   MH_MAGIC";
8130     else if (magic == MachO::MH_MAGIC_64)
8131       outs() << "MH_MAGIC_64";
8132     else
8133       outs() << format(" 0x%08" PRIx32, magic);
8134     switch (cputype) {
8135     case MachO::CPU_TYPE_I386:
8136       outs() << "    I386";
8137       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8138       case MachO::CPU_SUBTYPE_I386_ALL:
8139         outs() << "        ALL";
8140         break;
8141       default:
8142         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8143         break;
8144       }
8145       break;
8146     case MachO::CPU_TYPE_X86_64:
8147       outs() << "  X86_64";
8148       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8149       case MachO::CPU_SUBTYPE_X86_64_ALL:
8150         outs() << "        ALL";
8151         break;
8152       case MachO::CPU_SUBTYPE_X86_64_H:
8153         outs() << "    Haswell";
8154         break;
8155       default:
8156         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8157         break;
8158       }
8159       break;
8160     case MachO::CPU_TYPE_ARM:
8161       outs() << "     ARM";
8162       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8163       case MachO::CPU_SUBTYPE_ARM_ALL:
8164         outs() << "        ALL";
8165         break;
8166       case MachO::CPU_SUBTYPE_ARM_V4T:
8167         outs() << "        V4T";
8168         break;
8169       case MachO::CPU_SUBTYPE_ARM_V5TEJ:
8170         outs() << "      V5TEJ";
8171         break;
8172       case MachO::CPU_SUBTYPE_ARM_XSCALE:
8173         outs() << "     XSCALE";
8174         break;
8175       case MachO::CPU_SUBTYPE_ARM_V6:
8176         outs() << "         V6";
8177         break;
8178       case MachO::CPU_SUBTYPE_ARM_V6M:
8179         outs() << "        V6M";
8180         break;
8181       case MachO::CPU_SUBTYPE_ARM_V7:
8182         outs() << "         V7";
8183         break;
8184       case MachO::CPU_SUBTYPE_ARM_V7EM:
8185         outs() << "       V7EM";
8186         break;
8187       case MachO::CPU_SUBTYPE_ARM_V7K:
8188         outs() << "        V7K";
8189         break;
8190       case MachO::CPU_SUBTYPE_ARM_V7M:
8191         outs() << "        V7M";
8192         break;
8193       case MachO::CPU_SUBTYPE_ARM_V7S:
8194         outs() << "        V7S";
8195         break;
8196       default:
8197         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8198         break;
8199       }
8200       break;
8201     case MachO::CPU_TYPE_ARM64:
8202       outs() << "   ARM64";
8203       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8204       case MachO::CPU_SUBTYPE_ARM64_ALL:
8205         outs() << "        ALL";
8206         break;
8207       case MachO::CPU_SUBTYPE_ARM64E:
8208         outs() << "          E";
8209         break;
8210       default:
8211         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8212         break;
8213       }
8214       break;
8215     case MachO::CPU_TYPE_ARM64_32:
8216       outs() << " ARM64_32";
8217       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8218       case MachO::CPU_SUBTYPE_ARM64_32_V8:
8219         outs() << "        V8";
8220         break;
8221       default:
8222         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8223         break;
8224       }
8225       break;
8226     case MachO::CPU_TYPE_POWERPC:
8227       outs() << "     PPC";
8228       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8229       case MachO::CPU_SUBTYPE_POWERPC_ALL:
8230         outs() << "        ALL";
8231         break;
8232       default:
8233         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8234         break;
8235       }
8236       break;
8237     case MachO::CPU_TYPE_POWERPC64:
8238       outs() << "   PPC64";
8239       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8240       case MachO::CPU_SUBTYPE_POWERPC_ALL:
8241         outs() << "        ALL";
8242         break;
8243       default:
8244         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8245         break;
8246       }
8247       break;
8248     default:
8249       outs() << format(" %7d", cputype);
8250       outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8251       break;
8252     }
8253     if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
8254       outs() << " LIB64";
8255     } else {
8256       outs() << format("  0x%02" PRIx32,
8257                        (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
8258     }
8259     switch (filetype) {
8260     case MachO::MH_OBJECT:
8261       outs() << "      OBJECT";
8262       break;
8263     case MachO::MH_EXECUTE:
8264       outs() << "     EXECUTE";
8265       break;
8266     case MachO::MH_FVMLIB:
8267       outs() << "      FVMLIB";
8268       break;
8269     case MachO::MH_CORE:
8270       outs() << "        CORE";
8271       break;
8272     case MachO::MH_PRELOAD:
8273       outs() << "     PRELOAD";
8274       break;
8275     case MachO::MH_DYLIB:
8276       outs() << "       DYLIB";
8277       break;
8278     case MachO::MH_DYLIB_STUB:
8279       outs() << "  DYLIB_STUB";
8280       break;
8281     case MachO::MH_DYLINKER:
8282       outs() << "    DYLINKER";
8283       break;
8284     case MachO::MH_BUNDLE:
8285       outs() << "      BUNDLE";
8286       break;
8287     case MachO::MH_DSYM:
8288       outs() << "        DSYM";
8289       break;
8290     case MachO::MH_KEXT_BUNDLE:
8291       outs() << "  KEXTBUNDLE";
8292       break;
8293     default:
8294       outs() << format("  %10u", filetype);
8295       break;
8296     }
8297     outs() << format(" %5u", ncmds);
8298     outs() << format(" %10u", sizeofcmds);
8299     uint32_t f = flags;
8300     if (f & MachO::MH_NOUNDEFS) {
8301       outs() << "   NOUNDEFS";
8302       f &= ~MachO::MH_NOUNDEFS;
8303     }
8304     if (f & MachO::MH_INCRLINK) {
8305       outs() << " INCRLINK";
8306       f &= ~MachO::MH_INCRLINK;
8307     }
8308     if (f & MachO::MH_DYLDLINK) {
8309       outs() << " DYLDLINK";
8310       f &= ~MachO::MH_DYLDLINK;
8311     }
8312     if (f & MachO::MH_BINDATLOAD) {
8313       outs() << " BINDATLOAD";
8314       f &= ~MachO::MH_BINDATLOAD;
8315     }
8316     if (f & MachO::MH_PREBOUND) {
8317       outs() << " PREBOUND";
8318       f &= ~MachO::MH_PREBOUND;
8319     }
8320     if (f & MachO::MH_SPLIT_SEGS) {
8321       outs() << " SPLIT_SEGS";
8322       f &= ~MachO::MH_SPLIT_SEGS;
8323     }
8324     if (f & MachO::MH_LAZY_INIT) {
8325       outs() << " LAZY_INIT";
8326       f &= ~MachO::MH_LAZY_INIT;
8327     }
8328     if (f & MachO::MH_TWOLEVEL) {
8329       outs() << " TWOLEVEL";
8330       f &= ~MachO::MH_TWOLEVEL;
8331     }
8332     if (f & MachO::MH_FORCE_FLAT) {
8333       outs() << " FORCE_FLAT";
8334       f &= ~MachO::MH_FORCE_FLAT;
8335     }
8336     if (f & MachO::MH_NOMULTIDEFS) {
8337       outs() << " NOMULTIDEFS";
8338       f &= ~MachO::MH_NOMULTIDEFS;
8339     }
8340     if (f & MachO::MH_NOFIXPREBINDING) {
8341       outs() << " NOFIXPREBINDING";
8342       f &= ~MachO::MH_NOFIXPREBINDING;
8343     }
8344     if (f & MachO::MH_PREBINDABLE) {
8345       outs() << " PREBINDABLE";
8346       f &= ~MachO::MH_PREBINDABLE;
8347     }
8348     if (f & MachO::MH_ALLMODSBOUND) {
8349       outs() << " ALLMODSBOUND";
8350       f &= ~MachO::MH_ALLMODSBOUND;
8351     }
8352     if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
8353       outs() << " SUBSECTIONS_VIA_SYMBOLS";
8354       f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
8355     }
8356     if (f & MachO::MH_CANONICAL) {
8357       outs() << " CANONICAL";
8358       f &= ~MachO::MH_CANONICAL;
8359     }
8360     if (f & MachO::MH_WEAK_DEFINES) {
8361       outs() << " WEAK_DEFINES";
8362       f &= ~MachO::MH_WEAK_DEFINES;
8363     }
8364     if (f & MachO::MH_BINDS_TO_WEAK) {
8365       outs() << " BINDS_TO_WEAK";
8366       f &= ~MachO::MH_BINDS_TO_WEAK;
8367     }
8368     if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
8369       outs() << " ALLOW_STACK_EXECUTION";
8370       f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
8371     }
8372     if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
8373       outs() << " DEAD_STRIPPABLE_DYLIB";
8374       f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
8375     }
8376     if (f & MachO::MH_PIE) {
8377       outs() << " PIE";
8378       f &= ~MachO::MH_PIE;
8379     }
8380     if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
8381       outs() << " NO_REEXPORTED_DYLIBS";
8382       f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
8383     }
8384     if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
8385       outs() << " MH_HAS_TLV_DESCRIPTORS";
8386       f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
8387     }
8388     if (f & MachO::MH_NO_HEAP_EXECUTION) {
8389       outs() << " MH_NO_HEAP_EXECUTION";
8390       f &= ~MachO::MH_NO_HEAP_EXECUTION;
8391     }
8392     if (f & MachO::MH_APP_EXTENSION_SAFE) {
8393       outs() << " APP_EXTENSION_SAFE";
8394       f &= ~MachO::MH_APP_EXTENSION_SAFE;
8395     }
8396     if (f & MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO) {
8397       outs() << " NLIST_OUTOFSYNC_WITH_DYLDINFO";
8398       f &= ~MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO;
8399     }
8400     if (f != 0 || flags == 0)
8401       outs() << format(" 0x%08" PRIx32, f);
8402   } else {
8403     outs() << format(" 0x%08" PRIx32, magic);
8404     outs() << format(" %7d", cputype);
8405     outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8406     outs() << format("  0x%02" PRIx32,
8407                      (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
8408     outs() << format("  %10u", filetype);
8409     outs() << format(" %5u", ncmds);
8410     outs() << format(" %10u", sizeofcmds);
8411     outs() << format(" 0x%08" PRIx32, flags);
8412   }
8413   outs() << "\n";
8414 }
8415
8416 static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
8417                                 StringRef SegName, uint64_t vmaddr,
8418                                 uint64_t vmsize, uint64_t fileoff,
8419                                 uint64_t filesize, uint32_t maxprot,
8420                                 uint32_t initprot, uint32_t nsects,
8421                                 uint32_t flags, uint32_t object_size,
8422                                 bool verbose) {
8423   uint64_t expected_cmdsize;
8424   if (cmd == MachO::LC_SEGMENT) {
8425     outs() << "      cmd LC_SEGMENT\n";
8426     expected_cmdsize = nsects;
8427     expected_cmdsize *= sizeof(struct MachO::section);
8428     expected_cmdsize += sizeof(struct MachO::segment_command);
8429   } else {
8430     outs() << "      cmd LC_SEGMENT_64\n";
8431     expected_cmdsize = nsects;
8432     expected_cmdsize *= sizeof(struct MachO::section_64);
8433     expected_cmdsize += sizeof(struct MachO::segment_command_64);
8434   }
8435   outs() << "  cmdsize " << cmdsize;
8436   if (cmdsize != expected_cmdsize)
8437     outs() << " Inconsistent size\n";
8438   else
8439     outs() << "\n";
8440   outs() << "  segname " << SegName << "\n";
8441   if (cmd == MachO::LC_SEGMENT_64) {
8442     outs() << "   vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
8443     outs() << "   vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
8444   } else {
8445     outs() << "   vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
8446     outs() << "   vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
8447   }
8448   outs() << "  fileoff " << fileoff;
8449   if (fileoff > object_size)
8450     outs() << " (past end of file)\n";
8451   else
8452     outs() << "\n";
8453   outs() << " filesize " << filesize;
8454   if (fileoff + filesize > object_size)
8455     outs() << " (past end of file)\n";
8456   else
8457     outs() << "\n";
8458   if (verbose) {
8459     if ((maxprot &
8460          ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8461            MachO::VM_PROT_EXECUTE)) != 0)
8462       outs() << "  maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
8463     else {
8464       outs() << "  maxprot ";
8465       outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
8466       outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8467       outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
8468     }
8469     if ((initprot &
8470          ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8471            MachO::VM_PROT_EXECUTE)) != 0)
8472       outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
8473     else {
8474       outs() << " initprot ";
8475       outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
8476       outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8477       outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
8478     }
8479   } else {
8480     outs() << "  maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
8481     outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
8482   }
8483   outs() << "   nsects " << nsects << "\n";
8484   if (verbose) {
8485     outs() << "    flags";
8486     if (flags == 0)
8487       outs() << " (none)\n";
8488     else {
8489       if (flags & MachO::SG_HIGHVM) {
8490         outs() << " HIGHVM";
8491         flags &= ~MachO::SG_HIGHVM;
8492       }
8493       if (flags & MachO::SG_FVMLIB) {
8494         outs() << " FVMLIB";
8495         flags &= ~MachO::SG_FVMLIB;
8496       }
8497       if (flags & MachO::SG_NORELOC) {
8498         outs() << " NORELOC";
8499         flags &= ~MachO::SG_NORELOC;
8500       }
8501       if (flags & MachO::SG_PROTECTED_VERSION_1) {
8502         outs() << " PROTECTED_VERSION_1";
8503         flags &= ~MachO::SG_PROTECTED_VERSION_1;
8504       }
8505       if (flags)
8506         outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
8507       else
8508         outs() << "\n";
8509     }
8510   } else {
8511     outs() << "    flags " << format("0x%" PRIx32, flags) << "\n";
8512   }
8513 }
8514
8515 static void PrintSection(const char *sectname, const char *segname,
8516                          uint64_t addr, uint64_t size, uint32_t offset,
8517                          uint32_t align, uint32_t reloff, uint32_t nreloc,
8518                          uint32_t flags, uint32_t reserved1, uint32_t reserved2,
8519                          uint32_t cmd, const char *sg_segname,
8520                          uint32_t filetype, uint32_t object_size,
8521                          bool verbose) {
8522   outs() << "Section\n";
8523   outs() << "  sectname " << format("%.16s\n", sectname);
8524   outs() << "   segname " << format("%.16s", segname);
8525   if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
8526     outs() << " (does not match segment)\n";
8527   else
8528     outs() << "\n";
8529   if (cmd == MachO::LC_SEGMENT_64) {
8530     outs() << "      addr " << format("0x%016" PRIx64, addr) << "\n";
8531     outs() << "      size " << format("0x%016" PRIx64, size);
8532   } else {
8533     outs() << "      addr " << format("0x%08" PRIx64, addr) << "\n";
8534     outs() << "      size " << format("0x%08" PRIx64, size);
8535   }
8536   if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
8537     outs() << " (past end of file)\n";
8538   else
8539     outs() << "\n";
8540   outs() << "    offset " << offset;
8541   if (offset > object_size)
8542     outs() << " (past end of file)\n";
8543   else
8544     outs() << "\n";
8545   uint32_t align_shifted = 1 << align;
8546   outs() << "     align 2^" << align << " (" << align_shifted << ")\n";
8547   outs() << "    reloff " << reloff;
8548   if (reloff > object_size)
8549     outs() << " (past end of file)\n";
8550   else
8551     outs() << "\n";
8552   outs() << "    nreloc " << nreloc;
8553   if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
8554     outs() << " (past end of file)\n";
8555   else
8556     outs() << "\n";
8557   uint32_t section_type = flags & MachO::SECTION_TYPE;
8558   if (verbose) {
8559     outs() << "      type";
8560     if (section_type == MachO::S_REGULAR)
8561       outs() << " S_REGULAR\n";
8562     else if (section_type == MachO::S_ZEROFILL)
8563       outs() << " S_ZEROFILL\n";
8564     else if (section_type == MachO::S_CSTRING_LITERALS)
8565       outs() << " S_CSTRING_LITERALS\n";
8566     else if (section_type == MachO::S_4BYTE_LITERALS)
8567       outs() << " S_4BYTE_LITERALS\n";
8568     else if (section_type == MachO::S_8BYTE_LITERALS)
8569       outs() << " S_8BYTE_LITERALS\n";
8570     else if (section_type == MachO::S_16BYTE_LITERALS)
8571       outs() << " S_16BYTE_LITERALS\n";
8572     else if (section_type == MachO::S_LITERAL_POINTERS)
8573       outs() << " S_LITERAL_POINTERS\n";
8574     else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
8575       outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
8576     else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
8577       outs() << " S_LAZY_SYMBOL_POINTERS\n";
8578     else if (section_type == MachO::S_SYMBOL_STUBS)
8579       outs() << " S_SYMBOL_STUBS\n";
8580     else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
8581       outs() << " S_MOD_INIT_FUNC_POINTERS\n";
8582     else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
8583       outs() << " S_MOD_TERM_FUNC_POINTERS\n";
8584     else if (section_type == MachO::S_COALESCED)
8585       outs() << " S_COALESCED\n";
8586     else if (section_type == MachO::S_INTERPOSING)
8587       outs() << " S_INTERPOSING\n";
8588     else if (section_type == MachO::S_DTRACE_DOF)
8589       outs() << " S_DTRACE_DOF\n";
8590     else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
8591       outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
8592     else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
8593       outs() << " S_THREAD_LOCAL_REGULAR\n";
8594     else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
8595       outs() << " S_THREAD_LOCAL_ZEROFILL\n";
8596     else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
8597       outs() << " S_THREAD_LOCAL_VARIABLES\n";
8598     else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8599       outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
8600     else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
8601       outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
8602     else
8603       outs() << format("0x%08" PRIx32, section_type) << "\n";
8604     outs() << "attributes";
8605     uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
8606     if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
8607       outs() << " PURE_INSTRUCTIONS";
8608     if (section_attributes & MachO::S_ATTR_NO_TOC)
8609       outs() << " NO_TOC";
8610     if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
8611       outs() << " STRIP_STATIC_SYMS";
8612     if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
8613       outs() << " NO_DEAD_STRIP";
8614     if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
8615       outs() << " LIVE_SUPPORT";
8616     if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
8617       outs() << " SELF_MODIFYING_CODE";
8618     if (section_attributes & MachO::S_ATTR_DEBUG)
8619       outs() << " DEBUG";
8620     if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
8621       outs() << " SOME_INSTRUCTIONS";
8622     if (section_attributes & MachO::S_ATTR_EXT_RELOC)
8623       outs() << " EXT_RELOC";
8624     if (section_attributes & MachO::S_ATTR_LOC_RELOC)
8625       outs() << " LOC_RELOC";
8626     if (section_attributes == 0)
8627       outs() << " (none)";
8628     outs() << "\n";
8629   } else
8630     outs() << "     flags " << format("0x%08" PRIx32, flags) << "\n";
8631   outs() << " reserved1 " << reserved1;
8632   if (section_type == MachO::S_SYMBOL_STUBS ||
8633       section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
8634       section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
8635       section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
8636       section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8637     outs() << " (index into indirect symbol table)\n";
8638   else
8639     outs() << "\n";
8640   outs() << " reserved2 " << reserved2;
8641   if (section_type == MachO::S_SYMBOL_STUBS)
8642     outs() << " (size of stubs)\n";
8643   else
8644     outs() << "\n";
8645 }
8646
8647 static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
8648                                    uint32_t object_size) {
8649   outs() << "     cmd LC_SYMTAB\n";
8650   outs() << " cmdsize " << st.cmdsize;
8651   if (st.cmdsize != sizeof(struct MachO::symtab_command))
8652     outs() << " Incorrect size\n";
8653   else
8654     outs() << "\n";
8655   outs() << "  symoff " << st.symoff;
8656   if (st.symoff > object_size)
8657     outs() << " (past end of file)\n";
8658   else
8659     outs() << "\n";
8660   outs() << "   nsyms " << st.nsyms;
8661   uint64_t big_size;
8662   if (Is64Bit) {
8663     big_size = st.nsyms;
8664     big_size *= sizeof(struct MachO::nlist_64);
8665     big_size += st.symoff;
8666     if (big_size > object_size)
8667       outs() << " (past end of file)\n";
8668     else
8669       outs() << "\n";
8670   } else {
8671     big_size = st.nsyms;
8672     big_size *= sizeof(struct MachO::nlist);
8673     big_size += st.symoff;
8674     if (big_size > object_size)
8675       outs() << " (past end of file)\n";
8676     else
8677       outs() << "\n";
8678   }
8679   outs() << "  stroff " << st.stroff;
8680   if (st.stroff > object_size)
8681     outs() << " (past end of file)\n";
8682   else
8683     outs() << "\n";
8684   outs() << " strsize " << st.strsize;
8685   big_size = st.stroff;
8686   big_size += st.strsize;
8687   if (big_size > object_size)
8688     outs() << " (past end of file)\n";
8689   else
8690     outs() << "\n";
8691 }
8692
8693 static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
8694                                      uint32_t nsyms, uint32_t object_size,
8695                                      bool Is64Bit) {
8696   outs() << "            cmd LC_DYSYMTAB\n";
8697   outs() << "        cmdsize " << dyst.cmdsize;
8698   if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
8699     outs() << " Incorrect size\n";
8700   else
8701     outs() << "\n";
8702   outs() << "      ilocalsym " << dyst.ilocalsym;
8703   if (dyst.ilocalsym > nsyms)
8704     outs() << " (greater than the number of symbols)\n";
8705   else
8706     outs() << "\n";
8707   outs() << "      nlocalsym " << dyst.nlocalsym;
8708   uint64_t big_size;
8709   big_size = dyst.ilocalsym;
8710   big_size += dyst.nlocalsym;
8711   if (big_size > nsyms)
8712     outs() << " (past the end of the symbol table)\n";
8713   else
8714     outs() << "\n";
8715   outs() << "     iextdefsym " << dyst.iextdefsym;
8716   if (dyst.iextdefsym > nsyms)
8717     outs() << " (greater than the number of symbols)\n";
8718   else
8719     outs() << "\n";
8720   outs() << "     nextdefsym " << dyst.nextdefsym;
8721   big_size = dyst.iextdefsym;
8722   big_size += dyst.nextdefsym;
8723   if (big_size > nsyms)
8724     outs() << " (past the end of the symbol table)\n";
8725   else
8726     outs() << "\n";
8727   outs() << "      iundefsym " << dyst.iundefsym;
8728   if (dyst.iundefsym > nsyms)
8729     outs() << " (greater than the number of symbols)\n";
8730   else
8731     outs() << "\n";
8732   outs() << "      nundefsym " << dyst.nundefsym;
8733   big_size = dyst.iundefsym;
8734   big_size += dyst.nundefsym;
8735   if (big_size > nsyms)
8736     outs() << " (past the end of the symbol table)\n";
8737   else
8738     outs() << "\n";
8739   outs() << "         tocoff " << dyst.tocoff;
8740   if (dyst.tocoff > object_size)
8741     outs() << " (past end of file)\n";
8742   else
8743     outs() << "\n";
8744   outs() << "           ntoc " << dyst.ntoc;
8745   big_size = dyst.ntoc;
8746   big_size *= sizeof(struct MachO::dylib_table_of_contents);
8747   big_size += dyst.tocoff;
8748   if (big_size > object_size)
8749     outs() << " (past end of file)\n";
8750   else
8751     outs() << "\n";
8752   outs() << "      modtaboff " << dyst.modtaboff;
8753   if (dyst.modtaboff > object_size)
8754     outs() << " (past end of file)\n";
8755   else
8756     outs() << "\n";
8757   outs() << "        nmodtab " << dyst.nmodtab;
8758   uint64_t modtabend;
8759   if (Is64Bit) {
8760     modtabend = dyst.nmodtab;
8761     modtabend *= sizeof(struct MachO::dylib_module_64);
8762     modtabend += dyst.modtaboff;
8763   } else {
8764     modtabend = dyst.nmodtab;
8765     modtabend *= sizeof(struct MachO::dylib_module);
8766     modtabend += dyst.modtaboff;
8767   }
8768   if (modtabend > object_size)
8769     outs() << " (past end of file)\n";
8770   else
8771     outs() << "\n";
8772   outs() << "   extrefsymoff " << dyst.extrefsymoff;
8773   if (dyst.extrefsymoff > object_size)
8774     outs() << " (past end of file)\n";
8775   else
8776     outs() << "\n";
8777   outs() << "    nextrefsyms " << dyst.nextrefsyms;
8778   big_size = dyst.nextrefsyms;
8779   big_size *= sizeof(struct MachO::dylib_reference);
8780   big_size += dyst.extrefsymoff;
8781   if (big_size > object_size)
8782     outs() << " (past end of file)\n";
8783   else
8784     outs() << "\n";
8785   outs() << " indirectsymoff " << dyst.indirectsymoff;
8786   if (dyst.indirectsymoff > object_size)
8787     outs() << " (past end of file)\n";
8788   else
8789     outs() << "\n";
8790   outs() << "  nindirectsyms " << dyst.nindirectsyms;
8791   big_size = dyst.nindirectsyms;
8792   big_size *= sizeof(uint32_t);
8793   big_size += dyst.indirectsymoff;
8794   if (big_size > object_size)
8795     outs() << " (past end of file)\n";
8796   else
8797     outs() << "\n";
8798   outs() << "      extreloff " << dyst.extreloff;
8799   if (dyst.extreloff > object_size)
8800     outs() << " (past end of file)\n";
8801   else
8802     outs() << "\n";
8803   outs() << "        nextrel " << dyst.nextrel;
8804   big_size = dyst.nextrel;
8805   big_size *= sizeof(struct MachO::relocation_info);
8806   big_size += dyst.extreloff;
8807   if (big_size > object_size)
8808     outs() << " (past end of file)\n";
8809   else
8810     outs() << "\n";
8811   outs() << "      locreloff " << dyst.locreloff;
8812   if (dyst.locreloff > object_size)
8813     outs() << " (past end of file)\n";
8814   else
8815     outs() << "\n";
8816   outs() << "        nlocrel " << dyst.nlocrel;
8817   big_size = dyst.nlocrel;
8818   big_size *= sizeof(struct MachO::relocation_info);
8819   big_size += dyst.locreloff;
8820   if (big_size > object_size)
8821     outs() << " (past end of file)\n";
8822   else
8823     outs() << "\n";
8824 }
8825
8826 static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
8827                                      uint32_t object_size) {
8828   if (dc.cmd == MachO::LC_DYLD_INFO)
8829     outs() << "            cmd LC_DYLD_INFO\n";
8830   else
8831     outs() << "            cmd LC_DYLD_INFO_ONLY\n";
8832   outs() << "        cmdsize " << dc.cmdsize;
8833   if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
8834     outs() << " Incorrect size\n";
8835   else
8836     outs() << "\n";
8837   outs() << "     rebase_off " << dc.rebase_off;
8838   if (dc.rebase_off > object_size)
8839     outs() << " (past end of file)\n";
8840   else
8841     outs() << "\n";
8842   outs() << "    rebase_size " << dc.rebase_size;
8843   uint64_t big_size;
8844   big_size = dc.rebase_off;
8845   big_size += dc.rebase_size;
8846   if (big_size > object_size)
8847     outs() << " (past end of file)\n";
8848   else
8849     outs() << "\n";
8850   outs() << "       bind_off " << dc.bind_off;
8851   if (dc.bind_off > object_size)
8852     outs() << " (past end of file)\n";
8853   else
8854     outs() << "\n";
8855   outs() << "      bind_size " << dc.bind_size;
8856   big_size = dc.bind_off;
8857   big_size += dc.bind_size;
8858   if (big_size > object_size)
8859     outs() << " (past end of file)\n";
8860   else
8861     outs() << "\n";
8862   outs() << "  weak_bind_off " << dc.weak_bind_off;
8863   if (dc.weak_bind_off > object_size)
8864     outs() << " (past end of file)\n";
8865   else
8866     outs() << "\n";
8867   outs() << " weak_bind_size " << dc.weak_bind_size;
8868   big_size = dc.weak_bind_off;
8869   big_size += dc.weak_bind_size;
8870   if (big_size > object_size)
8871     outs() << " (past end of file)\n";
8872   else
8873     outs() << "\n";
8874   outs() << "  lazy_bind_off " << dc.lazy_bind_off;
8875   if (dc.lazy_bind_off > object_size)
8876     outs() << " (past end of file)\n";
8877   else
8878     outs() << "\n";
8879   outs() << " lazy_bind_size " << dc.lazy_bind_size;
8880   big_size = dc.lazy_bind_off;
8881   big_size += dc.lazy_bind_size;
8882   if (big_size > object_size)
8883     outs() << " (past end of file)\n";
8884   else
8885     outs() << "\n";
8886   outs() << "     export_off " << dc.export_off;
8887   if (dc.export_off > object_size)
8888     outs() << " (past end of file)\n";
8889   else
8890     outs() << "\n";
8891   outs() << "    export_size " << dc.export_size;
8892   big_size = dc.export_off;
8893   big_size += dc.export_size;
8894   if (big_size > object_size)
8895     outs() << " (past end of file)\n";
8896   else
8897     outs() << "\n";
8898 }
8899
8900 static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
8901                                  const char *Ptr) {
8902   if (dyld.cmd == MachO::LC_ID_DYLINKER)
8903     outs() << "          cmd LC_ID_DYLINKER\n";
8904   else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
8905     outs() << "          cmd LC_LOAD_DYLINKER\n";
8906   else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
8907     outs() << "          cmd LC_DYLD_ENVIRONMENT\n";
8908   else
8909     outs() << "          cmd ?(" << dyld.cmd << ")\n";
8910   outs() << "      cmdsize " << dyld.cmdsize;
8911   if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
8912     outs() << " Incorrect size\n";
8913   else
8914     outs() << "\n";
8915   if (dyld.name >= dyld.cmdsize)
8916     outs() << "         name ?(bad offset " << dyld.name << ")\n";
8917   else {
8918     const char *P = (const char *)(Ptr) + dyld.name;
8919     outs() << "         name " << P << " (offset " << dyld.name << ")\n";
8920   }
8921 }
8922
8923 static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
8924   outs() << "     cmd LC_UUID\n";
8925   outs() << " cmdsize " << uuid.cmdsize;
8926   if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
8927     outs() << " Incorrect size\n";
8928   else
8929     outs() << "\n";
8930   outs() << "    uuid ";
8931   for (int i = 0; i < 16; ++i) {
8932     outs() << format("%02" PRIX32, uuid.uuid[i]);
8933     if (i == 3 || i == 5 || i == 7 || i == 9)
8934       outs() << "-";
8935   }
8936   outs() << "\n";
8937 }
8938
8939 static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
8940   outs() << "          cmd LC_RPATH\n";
8941   outs() << "      cmdsize " << rpath.cmdsize;
8942   if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
8943     outs() << " Incorrect size\n";
8944   else
8945     outs() << "\n";
8946   if (rpath.path >= rpath.cmdsize)
8947     outs() << "         path ?(bad offset " << rpath.path << ")\n";
8948   else {
8949     const char *P = (const char *)(Ptr) + rpath.path;
8950     outs() << "         path " << P << " (offset " << rpath.path << ")\n";
8951   }
8952 }
8953
8954 static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
8955   StringRef LoadCmdName;
8956   switch (vd.cmd) {
8957   case MachO::LC_VERSION_MIN_MACOSX:
8958     LoadCmdName = "LC_VERSION_MIN_MACOSX";
8959     break;
8960   case MachO::LC_VERSION_MIN_IPHONEOS:
8961     LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
8962     break;
8963   case MachO::LC_VERSION_MIN_TVOS:
8964     LoadCmdName = "LC_VERSION_MIN_TVOS";
8965     break;
8966   case MachO::LC_VERSION_MIN_WATCHOS:
8967     LoadCmdName = "LC_VERSION_MIN_WATCHOS";
8968     break;
8969   default:
8970     llvm_unreachable("Unknown version min load command");
8971   }
8972
8973   outs() << "      cmd " << LoadCmdName << '\n';
8974   outs() << "  cmdsize " << vd.cmdsize;
8975   if (vd.cmdsize != sizeof(struct MachO::version_min_command))
8976     outs() << " Incorrect size\n";
8977   else
8978     outs() << "\n";
8979   outs() << "  version "
8980          << MachOObjectFile::getVersionMinMajor(vd, false) << "."
8981          << MachOObjectFile::getVersionMinMinor(vd, false);
8982   uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
8983   if (Update != 0)
8984     outs() << "." << Update;
8985   outs() << "\n";
8986   if (vd.sdk == 0)
8987     outs() << "      sdk n/a";
8988   else {
8989     outs() << "      sdk "
8990            << MachOObjectFile::getVersionMinMajor(vd, true) << "."
8991            << MachOObjectFile::getVersionMinMinor(vd, true);
8992   }
8993   Update = MachOObjectFile::getVersionMinUpdate(vd, true);
8994   if (Update != 0)
8995     outs() << "." << Update;
8996   outs() << "\n";
8997 }
8998
8999 static void PrintNoteLoadCommand(MachO::note_command Nt) {
9000   outs() << "       cmd LC_NOTE\n";
9001   outs() << "   cmdsize " << Nt.cmdsize;
9002   if (Nt.cmdsize != sizeof(struct MachO::note_command))
9003     outs() << " Incorrect size\n";
9004   else
9005     outs() << "\n";
9006   const char *d = Nt.data_owner;
9007   outs() << "data_owner " << format("%.16s\n", d);
9008   outs() << "    offset " << Nt.offset << "\n";
9009   outs() << "      size " << Nt.size << "\n";
9010 }
9011
9012 static void PrintBuildToolVersion(MachO::build_tool_version bv) {
9013   outs() << "      tool " << MachOObjectFile::getBuildTool(bv.tool) << "\n";
9014   outs() << "   version " << MachOObjectFile::getVersionString(bv.version)
9015          << "\n";
9016 }
9017
9018 static void PrintBuildVersionLoadCommand(const MachOObjectFile *obj,
9019                                          MachO::build_version_command bd) {
9020   outs() << "       cmd LC_BUILD_VERSION\n";
9021   outs() << "   cmdsize " << bd.cmdsize;
9022   if (bd.cmdsize !=
9023       sizeof(struct MachO::build_version_command) +
9024           bd.ntools * sizeof(struct MachO::build_tool_version))
9025     outs() << " Incorrect size\n";
9026   else
9027     outs() << "\n";
9028   outs() << "  platform " << MachOObjectFile::getBuildPlatform(bd.platform)
9029          << "\n";
9030   if (bd.sdk)
9031     outs() << "       sdk " << MachOObjectFile::getVersionString(bd.sdk)
9032            << "\n";
9033   else
9034     outs() << "       sdk n/a\n";
9035   outs() << "     minos " << MachOObjectFile::getVersionString(bd.minos)
9036          << "\n";
9037   outs() << "    ntools " << bd.ntools << "\n";
9038   for (unsigned i = 0; i < bd.ntools; ++i) {
9039     MachO::build_tool_version bv = obj->getBuildToolVersion(i);
9040     PrintBuildToolVersion(bv);
9041   }
9042 }
9043
9044 static void PrintSourceVersionCommand(MachO::source_version_command sd) {
9045   outs() << "      cmd LC_SOURCE_VERSION\n";
9046   outs() << "  cmdsize " << sd.cmdsize;
9047   if (sd.cmdsize != sizeof(struct MachO::source_version_command))
9048     outs() << " Incorrect size\n";
9049   else
9050     outs() << "\n";
9051   uint64_t a = (sd.version >> 40) & 0xffffff;
9052   uint64_t b = (sd.version >> 30) & 0x3ff;
9053   uint64_t c = (sd.version >> 20) & 0x3ff;
9054   uint64_t d = (sd.version >> 10) & 0x3ff;
9055   uint64_t e = sd.version & 0x3ff;
9056   outs() << "  version " << a << "." << b;
9057   if (e != 0)
9058     outs() << "." << c << "." << d << "." << e;
9059   else if (d != 0)
9060     outs() << "." << c << "." << d;
9061   else if (c != 0)
9062     outs() << "." << c;
9063   outs() << "\n";
9064 }
9065
9066 static void PrintEntryPointCommand(MachO::entry_point_command ep) {
9067   outs() << "       cmd LC_MAIN\n";
9068   outs() << "   cmdsize " << ep.cmdsize;
9069   if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
9070     outs() << " Incorrect size\n";
9071   else
9072     outs() << "\n";
9073   outs() << "  entryoff " << ep.entryoff << "\n";
9074   outs() << " stacksize " << ep.stacksize << "\n";
9075 }
9076
9077 static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
9078                                        uint32_t object_size) {
9079   outs() << "          cmd LC_ENCRYPTION_INFO\n";
9080   outs() << "      cmdsize " << ec.cmdsize;
9081   if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
9082     outs() << " Incorrect size\n";
9083   else
9084     outs() << "\n";
9085   outs() << "     cryptoff " << ec.cryptoff;
9086   if (ec.cryptoff > object_size)
9087     outs() << " (past end of file)\n";
9088   else
9089     outs() << "\n";
9090   outs() << "    cryptsize " << ec.cryptsize;
9091   if (ec.cryptsize > object_size)
9092     outs() << " (past end of file)\n";
9093   else
9094     outs() << "\n";
9095   outs() << "      cryptid " << ec.cryptid << "\n";
9096 }
9097
9098 static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
9099                                          uint32_t object_size) {
9100   outs() << "          cmd LC_ENCRYPTION_INFO_64\n";
9101   outs() << "      cmdsize " << ec.cmdsize;
9102   if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
9103     outs() << " Incorrect size\n";
9104   else
9105     outs() << "\n";
9106   outs() << "     cryptoff " << ec.cryptoff;
9107   if (ec.cryptoff > object_size)
9108     outs() << " (past end of file)\n";
9109   else
9110     outs() << "\n";
9111   outs() << "    cryptsize " << ec.cryptsize;
9112   if (ec.cryptsize > object_size)
9113     outs() << " (past end of file)\n";
9114   else
9115     outs() << "\n";
9116   outs() << "      cryptid " << ec.cryptid << "\n";
9117   outs() << "          pad " << ec.pad << "\n";
9118 }
9119
9120 static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
9121                                      const char *Ptr) {
9122   outs() << "     cmd LC_LINKER_OPTION\n";
9123   outs() << " cmdsize " << lo.cmdsize;
9124   if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
9125     outs() << " Incorrect size\n";
9126   else
9127     outs() << "\n";
9128   outs() << "   count " << lo.count << "\n";
9129   const char *string = Ptr + sizeof(struct MachO::linker_option_command);
9130   uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
9131   uint32_t i = 0;
9132   while (left > 0) {
9133     while (*string == '\0' && left > 0) {
9134       string++;
9135       left--;
9136     }
9137     if (left > 0) {
9138       i++;
9139       outs() << "  string #" << i << " " << format("%.*s\n", left, string);
9140       uint32_t NullPos = StringRef(string, left).find('\0');
9141       uint32_t len = std::min(NullPos, left) + 1;
9142       string += len;
9143       left -= len;
9144     }
9145   }
9146   if (lo.count != i)
9147     outs() << "   count " << lo.count << " does not match number of strings "
9148            << i << "\n";
9149 }
9150
9151 static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
9152                                      const char *Ptr) {
9153   outs() << "          cmd LC_SUB_FRAMEWORK\n";
9154   outs() << "      cmdsize " << sub.cmdsize;
9155   if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
9156     outs() << " Incorrect size\n";
9157   else
9158     outs() << "\n";
9159   if (sub.umbrella < sub.cmdsize) {
9160     const char *P = Ptr + sub.umbrella;
9161     outs() << "     umbrella " << P << " (offset " << sub.umbrella << ")\n";
9162   } else {
9163     outs() << "     umbrella ?(bad offset " << sub.umbrella << ")\n";
9164   }
9165 }
9166
9167 static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
9168                                     const char *Ptr) {
9169   outs() << "          cmd LC_SUB_UMBRELLA\n";
9170   outs() << "      cmdsize " << sub.cmdsize;
9171   if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
9172     outs() << " Incorrect size\n";
9173   else
9174     outs() << "\n";
9175   if (sub.sub_umbrella < sub.cmdsize) {
9176     const char *P = Ptr + sub.sub_umbrella;
9177     outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
9178   } else {
9179     outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
9180   }
9181 }
9182
9183 static void PrintSubLibraryCommand(MachO::sub_library_command sub,
9184                                    const char *Ptr) {
9185   outs() << "          cmd LC_SUB_LIBRARY\n";
9186   outs() << "      cmdsize " << sub.cmdsize;
9187   if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
9188     outs() << " Incorrect size\n";
9189   else
9190     outs() << "\n";
9191   if (sub.sub_library < sub.cmdsize) {
9192     const char *P = Ptr + sub.sub_library;
9193     outs() << "  sub_library " << P << " (offset " << sub.sub_library << ")\n";
9194   } else {
9195     outs() << "  sub_library ?(bad offset " << sub.sub_library << ")\n";
9196   }
9197 }
9198
9199 static void PrintSubClientCommand(MachO::sub_client_command sub,
9200                                   const char *Ptr) {
9201   outs() << "          cmd LC_SUB_CLIENT\n";
9202   outs() << "      cmdsize " << sub.cmdsize;
9203   if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
9204     outs() << " Incorrect size\n";
9205   else
9206     outs() << "\n";
9207   if (sub.client < sub.cmdsize) {
9208     const char *P = Ptr + sub.client;
9209     outs() << "       client " << P << " (offset " << sub.client << ")\n";
9210   } else {
9211     outs() << "       client ?(bad offset " << sub.client << ")\n";
9212   }
9213 }
9214
9215 static void PrintRoutinesCommand(MachO::routines_command r) {
9216   outs() << "          cmd LC_ROUTINES\n";
9217   outs() << "      cmdsize " << r.cmdsize;
9218   if (r.cmdsize != sizeof(struct MachO::routines_command))
9219     outs() << " Incorrect size\n";
9220   else
9221     outs() << "\n";
9222   outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
9223   outs() << "  init_module " << r.init_module << "\n";
9224   outs() << "    reserved1 " << r.reserved1 << "\n";
9225   outs() << "    reserved2 " << r.reserved2 << "\n";
9226   outs() << "    reserved3 " << r.reserved3 << "\n";
9227   outs() << "    reserved4 " << r.reserved4 << "\n";
9228   outs() << "    reserved5 " << r.reserved5 << "\n";
9229   outs() << "    reserved6 " << r.reserved6 << "\n";
9230 }
9231
9232 static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
9233   outs() << "          cmd LC_ROUTINES_64\n";
9234   outs() << "      cmdsize " << r.cmdsize;
9235   if (r.cmdsize != sizeof(struct MachO::routines_command_64))
9236     outs() << " Incorrect size\n";
9237   else
9238     outs() << "\n";
9239   outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
9240   outs() << "  init_module " << r.init_module << "\n";
9241   outs() << "    reserved1 " << r.reserved1 << "\n";
9242   outs() << "    reserved2 " << r.reserved2 << "\n";
9243   outs() << "    reserved3 " << r.reserved3 << "\n";
9244   outs() << "    reserved4 " << r.reserved4 << "\n";
9245   outs() << "    reserved5 " << r.reserved5 << "\n";
9246   outs() << "    reserved6 " << r.reserved6 << "\n";
9247 }
9248
9249 static void Print_x86_thread_state32_t(MachO::x86_thread_state32_t &cpu32) {
9250   outs() << "\t    eax " << format("0x%08" PRIx32, cpu32.eax);
9251   outs() << " ebx    " << format("0x%08" PRIx32, cpu32.ebx);
9252   outs() << " ecx " << format("0x%08" PRIx32, cpu32.ecx);
9253   outs() << " edx " << format("0x%08" PRIx32, cpu32.edx) << "\n";
9254   outs() << "\t    edi " << format("0x%08" PRIx32, cpu32.edi);
9255   outs() << " esi    " << format("0x%08" PRIx32, cpu32.esi);
9256   outs() << " ebp " << format("0x%08" PRIx32, cpu32.ebp);
9257   outs() << " esp " << format("0x%08" PRIx32, cpu32.esp) << "\n";
9258   outs() << "\t    ss  " << format("0x%08" PRIx32, cpu32.ss);
9259   outs() << " eflags " << format("0x%08" PRIx32, cpu32.eflags);
9260   outs() << " eip " << format("0x%08" PRIx32, cpu32.eip);
9261   outs() << " cs  " << format("0x%08" PRIx32, cpu32.cs) << "\n";
9262   outs() << "\t    ds  " << format("0x%08" PRIx32, cpu32.ds);
9263   outs() << " es     " << format("0x%08" PRIx32, cpu32.es);
9264   outs() << " fs  " << format("0x%08" PRIx32, cpu32.fs);
9265   outs() << " gs  " << format("0x%08" PRIx32, cpu32.gs) << "\n";
9266 }
9267
9268 static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
9269   outs() << "   rax  " << format("0x%016" PRIx64, cpu64.rax);
9270   outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
9271   outs() << " rcx  " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
9272   outs() << "   rdx  " << format("0x%016" PRIx64, cpu64.rdx);
9273   outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
9274   outs() << " rsi  " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
9275   outs() << "   rbp  " << format("0x%016" PRIx64, cpu64.rbp);
9276   outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
9277   outs() << " r8   " << format("0x%016" PRIx64, cpu64.r8) << "\n";
9278   outs() << "    r9  " << format("0x%016" PRIx64, cpu64.r9);
9279   outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
9280   outs() << " r11  " << format("0x%016" PRIx64, cpu64.r11) << "\n";
9281   outs() << "   r12  " << format("0x%016" PRIx64, cpu64.r12);
9282   outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
9283   outs() << " r14  " << format("0x%016" PRIx64, cpu64.r14) << "\n";
9284   outs() << "   r15  " << format("0x%016" PRIx64, cpu64.r15);
9285   outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
9286   outs() << "rflags  " << format("0x%016" PRIx64, cpu64.rflags);
9287   outs() << " cs  " << format("0x%016" PRIx64, cpu64.cs);
9288   outs() << " fs   " << format("0x%016" PRIx64, cpu64.fs) << "\n";
9289   outs() << "    gs  " << format("0x%016" PRIx64, cpu64.gs) << "\n";
9290 }
9291
9292 static void Print_mmst_reg(MachO::mmst_reg_t &r) {
9293   uint32_t f;
9294   outs() << "\t      mmst_reg  ";
9295   for (f = 0; f < 10; f++)
9296     outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
9297   outs() << "\n";
9298   outs() << "\t      mmst_rsrv ";
9299   for (f = 0; f < 6; f++)
9300     outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
9301   outs() << "\n";
9302 }
9303
9304 static void Print_xmm_reg(MachO::xmm_reg_t &r) {
9305   uint32_t f;
9306   outs() << "\t      xmm_reg ";
9307   for (f = 0; f < 16; f++)
9308     outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
9309   outs() << "\n";
9310 }
9311
9312 static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
9313   outs() << "\t    fpu_reserved[0] " << fpu.fpu_reserved[0];
9314   outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
9315   outs() << "\t    control: invalid " << fpu.fpu_fcw.invalid;
9316   outs() << " denorm " << fpu.fpu_fcw.denorm;
9317   outs() << " zdiv " << fpu.fpu_fcw.zdiv;
9318   outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
9319   outs() << " undfl " << fpu.fpu_fcw.undfl;
9320   outs() << " precis " << fpu.fpu_fcw.precis << "\n";
9321   outs() << "\t\t     pc ";
9322   if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
9323     outs() << "FP_PREC_24B ";
9324   else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
9325     outs() << "FP_PREC_53B ";
9326   else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
9327     outs() << "FP_PREC_64B ";
9328   else
9329     outs() << fpu.fpu_fcw.pc << " ";
9330   outs() << "rc ";
9331   if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
9332     outs() << "FP_RND_NEAR ";
9333   else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
9334     outs() << "FP_RND_DOWN ";
9335   else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
9336     outs() << "FP_RND_UP ";
9337   else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
9338     outs() << "FP_CHOP ";
9339   outs() << "\n";
9340   outs() << "\t    status: invalid " << fpu.fpu_fsw.invalid;
9341   outs() << " denorm " << fpu.fpu_fsw.denorm;
9342   outs() << " zdiv " << fpu.fpu_fsw.zdiv;
9343   outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
9344   outs() << " undfl " << fpu.fpu_fsw.undfl;
9345   outs() << " precis " << fpu.fpu_fsw.precis;
9346   outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
9347   outs() << "\t            errsumm " << fpu.fpu_fsw.errsumm;
9348   outs() << " c0 " << fpu.fpu_fsw.c0;
9349   outs() << " c1 " << fpu.fpu_fsw.c1;
9350   outs() << " c2 " << fpu.fpu_fsw.c2;
9351   outs() << " tos " << fpu.fpu_fsw.tos;
9352   outs() << " c3 " << fpu.fpu_fsw.c3;
9353   outs() << " busy " << fpu.fpu_fsw.busy << "\n";
9354   outs() << "\t    fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
9355   outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
9356   outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
9357   outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
9358   outs() << "\t    fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
9359   outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
9360   outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
9361   outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
9362   outs() << "\t    fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
9363   outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
9364   outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
9365   outs() << "\n";
9366   outs() << "\t    fpu_stmm0:\n";
9367   Print_mmst_reg(fpu.fpu_stmm0);
9368   outs() << "\t    fpu_stmm1:\n";
9369   Print_mmst_reg(fpu.fpu_stmm1);
9370   outs() << "\t    fpu_stmm2:\n";
9371   Print_mmst_reg(fpu.fpu_stmm2);
9372   outs() << "\t    fpu_stmm3:\n";
9373   Print_mmst_reg(fpu.fpu_stmm3);
9374   outs() << "\t    fpu_stmm4:\n";
9375   Print_mmst_reg(fpu.fpu_stmm4);
9376   outs() << "\t    fpu_stmm5:\n";
9377   Print_mmst_reg(fpu.fpu_stmm5);
9378   outs() << "\t    fpu_stmm6:\n";
9379   Print_mmst_reg(fpu.fpu_stmm6);
9380   outs() << "\t    fpu_stmm7:\n";
9381   Print_mmst_reg(fpu.fpu_stmm7);
9382   outs() << "\t    fpu_xmm0:\n";
9383   Print_xmm_reg(fpu.fpu_xmm0);
9384   outs() << "\t    fpu_xmm1:\n";
9385   Print_xmm_reg(fpu.fpu_xmm1);
9386   outs() << "\t    fpu_xmm2:\n";
9387   Print_xmm_reg(fpu.fpu_xmm2);
9388   outs() << "\t    fpu_xmm3:\n";
9389   Print_xmm_reg(fpu.fpu_xmm3);
9390   outs() << "\t    fpu_xmm4:\n";
9391   Print_xmm_reg(fpu.fpu_xmm4);
9392   outs() << "\t    fpu_xmm5:\n";
9393   Print_xmm_reg(fpu.fpu_xmm5);
9394   outs() << "\t    fpu_xmm6:\n";
9395   Print_xmm_reg(fpu.fpu_xmm6);
9396   outs() << "\t    fpu_xmm7:\n";
9397   Print_xmm_reg(fpu.fpu_xmm7);
9398   outs() << "\t    fpu_xmm8:\n";
9399   Print_xmm_reg(fpu.fpu_xmm8);
9400   outs() << "\t    fpu_xmm9:\n";
9401   Print_xmm_reg(fpu.fpu_xmm9);
9402   outs() << "\t    fpu_xmm10:\n";
9403   Print_xmm_reg(fpu.fpu_xmm10);
9404   outs() << "\t    fpu_xmm11:\n";
9405   Print_xmm_reg(fpu.fpu_xmm11);
9406   outs() << "\t    fpu_xmm12:\n";
9407   Print_xmm_reg(fpu.fpu_xmm12);
9408   outs() << "\t    fpu_xmm13:\n";
9409   Print_xmm_reg(fpu.fpu_xmm13);
9410   outs() << "\t    fpu_xmm14:\n";
9411   Print_xmm_reg(fpu.fpu_xmm14);
9412   outs() << "\t    fpu_xmm15:\n";
9413   Print_xmm_reg(fpu.fpu_xmm15);
9414   outs() << "\t    fpu_rsrv4:\n";
9415   for (uint32_t f = 0; f < 6; f++) {
9416     outs() << "\t            ";
9417     for (uint32_t g = 0; g < 16; g++)
9418       outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
9419     outs() << "\n";
9420   }
9421   outs() << "\t    fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
9422   outs() << "\n";
9423 }
9424
9425 static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
9426   outs() << "\t    trapno " << format("0x%08" PRIx32, exc64.trapno);
9427   outs() << " err " << format("0x%08" PRIx32, exc64.err);
9428   outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
9429 }
9430
9431 static void Print_arm_thread_state32_t(MachO::arm_thread_state32_t &cpu32) {
9432   outs() << "\t    r0  " << format("0x%08" PRIx32, cpu32.r[0]);
9433   outs() << " r1     "   << format("0x%08" PRIx32, cpu32.r[1]);
9434   outs() << " r2  "      << format("0x%08" PRIx32, cpu32.r[2]);
9435   outs() << " r3  "      << format("0x%08" PRIx32, cpu32.r[3]) << "\n";
9436   outs() << "\t    r4  " << format("0x%08" PRIx32, cpu32.r[4]);
9437   outs() << " r5     "   << format("0x%08" PRIx32, cpu32.r[5]);
9438   outs() << " r6  "      << format("0x%08" PRIx32, cpu32.r[6]);
9439   outs() << " r7  "      << format("0x%08" PRIx32, cpu32.r[7]) << "\n";
9440   outs() << "\t    r8  " << format("0x%08" PRIx32, cpu32.r[8]);
9441   outs() << " r9     "   << format("0x%08" PRIx32, cpu32.r[9]);
9442   outs() << " r10 "      << format("0x%08" PRIx32, cpu32.r[10]);
9443   outs() << " r11 "      << format("0x%08" PRIx32, cpu32.r[11]) << "\n";
9444   outs() << "\t    r12 " << format("0x%08" PRIx32, cpu32.r[12]);
9445   outs() << " sp     "   << format("0x%08" PRIx32, cpu32.sp);
9446   outs() << " lr  "      << format("0x%08" PRIx32, cpu32.lr);
9447   outs() << " pc  "      << format("0x%08" PRIx32, cpu32.pc) << "\n";
9448   outs() << "\t   cpsr " << format("0x%08" PRIx32, cpu32.cpsr) << "\n";
9449 }
9450
9451 static void Print_arm_thread_state64_t(MachO::arm_thread_state64_t &cpu64) {
9452   outs() << "\t    x0  " << format("0x%016" PRIx64, cpu64.x[0]);
9453   outs() << " x1  "      << format("0x%016" PRIx64, cpu64.x[1]);
9454   outs() << " x2  "      << format("0x%016" PRIx64, cpu64.x[2]) << "\n";
9455   outs() << "\t    x3  " << format("0x%016" PRIx64, cpu64.x[3]);
9456   outs() << " x4  "      << format("0x%016" PRIx64, cpu64.x[4]);
9457   outs() << " x5  "      << format("0x%016" PRIx64, cpu64.x[5]) << "\n";
9458   outs() << "\t    x6  " << format("0x%016" PRIx64, cpu64.x[6]);
9459   outs() << " x7  "      << format("0x%016" PRIx64, cpu64.x[7]);
9460   outs() << " x8  "      << format("0x%016" PRIx64, cpu64.x[8]) << "\n";
9461   outs() << "\t    x9  " << format("0x%016" PRIx64, cpu64.x[9]);
9462   outs() << " x10 "      << format("0x%016" PRIx64, cpu64.x[10]);
9463   outs() << " x11 "      << format("0x%016" PRIx64, cpu64.x[11]) << "\n";
9464   outs() << "\t    x12 " << format("0x%016" PRIx64, cpu64.x[12]);
9465   outs() << " x13 "      << format("0x%016" PRIx64, cpu64.x[13]);
9466   outs() << " x14 "      << format("0x%016" PRIx64, cpu64.x[14]) << "\n";
9467   outs() << "\t    x15 " << format("0x%016" PRIx64, cpu64.x[15]);
9468   outs() << " x16 "      << format("0x%016" PRIx64, cpu64.x[16]);
9469   outs() << " x17 "      << format("0x%016" PRIx64, cpu64.x[17]) << "\n";
9470   outs() << "\t    x18 " << format("0x%016" PRIx64, cpu64.x[18]);
9471   outs() << " x19 "      << format("0x%016" PRIx64, cpu64.x[19]);
9472   outs() << " x20 "      << format("0x%016" PRIx64, cpu64.x[20]) << "\n";
9473   outs() << "\t    x21 " << format("0x%016" PRIx64, cpu64.x[21]);
9474   outs() << " x22 "      << format("0x%016" PRIx64, cpu64.x[22]);
9475   outs() << " x23 "      << format("0x%016" PRIx64, cpu64.x[23]) << "\n";
9476   outs() << "\t    x24 " << format("0x%016" PRIx64, cpu64.x[24]);
9477   outs() << " x25 "      << format("0x%016" PRIx64, cpu64.x[25]);
9478   outs() << " x26 "      << format("0x%016" PRIx64, cpu64.x[26]) << "\n";
9479   outs() << "\t    x27 " << format("0x%016" PRIx64, cpu64.x[27]);
9480   outs() << " x28 "      << format("0x%016" PRIx64, cpu64.x[28]);
9481   outs() << "  fp "      << format("0x%016" PRIx64, cpu64.fp) << "\n";
9482   outs() << "\t     lr " << format("0x%016" PRIx64, cpu64.lr);
9483   outs() << " sp  "      << format("0x%016" PRIx64, cpu64.sp);
9484   outs() << "  pc "      << format("0x%016" PRIx64, cpu64.pc) << "\n";
9485   outs() << "\t   cpsr " << format("0x%08"  PRIx32, cpu64.cpsr) << "\n";
9486 }
9487
9488 static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
9489                                bool isLittleEndian, uint32_t cputype) {
9490   if (t.cmd == MachO::LC_THREAD)
9491     outs() << "        cmd LC_THREAD\n";
9492   else if (t.cmd == MachO::LC_UNIXTHREAD)
9493     outs() << "        cmd LC_UNIXTHREAD\n";
9494   else
9495     outs() << "        cmd " << t.cmd << " (unknown)\n";
9496   outs() << "    cmdsize " << t.cmdsize;
9497   if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
9498     outs() << " Incorrect size\n";
9499   else
9500     outs() << "\n";
9501
9502   const char *begin = Ptr + sizeof(struct MachO::thread_command);
9503   const char *end = Ptr + t.cmdsize;
9504   uint32_t flavor, count, left;
9505   if (cputype == MachO::CPU_TYPE_I386) {
9506     while (begin < end) {
9507       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9508         memcpy((char *)&flavor, begin, sizeof(uint32_t));
9509         begin += sizeof(uint32_t);
9510       } else {
9511         flavor = 0;
9512         begin = end;
9513       }
9514       if (isLittleEndian != sys::IsLittleEndianHost)
9515         sys::swapByteOrder(flavor);
9516       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9517         memcpy((char *)&count, begin, sizeof(uint32_t));
9518         begin += sizeof(uint32_t);
9519       } else {
9520         count = 0;
9521         begin = end;
9522       }
9523       if (isLittleEndian != sys::IsLittleEndianHost)
9524         sys::swapByteOrder(count);
9525       if (flavor == MachO::x86_THREAD_STATE32) {
9526         outs() << "     flavor i386_THREAD_STATE\n";
9527         if (count == MachO::x86_THREAD_STATE32_COUNT)
9528           outs() << "      count i386_THREAD_STATE_COUNT\n";
9529         else
9530           outs() << "      count " << count
9531                  << " (not x86_THREAD_STATE32_COUNT)\n";
9532         MachO::x86_thread_state32_t cpu32;
9533         left = end - begin;
9534         if (left >= sizeof(MachO::x86_thread_state32_t)) {
9535           memcpy(&cpu32, begin, sizeof(MachO::x86_thread_state32_t));
9536           begin += sizeof(MachO::x86_thread_state32_t);
9537         } else {
9538           memset(&cpu32, '\0', sizeof(MachO::x86_thread_state32_t));
9539           memcpy(&cpu32, begin, left);
9540           begin += left;
9541         }
9542         if (isLittleEndian != sys::IsLittleEndianHost)
9543           swapStruct(cpu32);
9544         Print_x86_thread_state32_t(cpu32);
9545       } else if (flavor == MachO::x86_THREAD_STATE) {
9546         outs() << "     flavor x86_THREAD_STATE\n";
9547         if (count == MachO::x86_THREAD_STATE_COUNT)
9548           outs() << "      count x86_THREAD_STATE_COUNT\n";
9549         else
9550           outs() << "      count " << count
9551                  << " (not x86_THREAD_STATE_COUNT)\n";
9552         struct MachO::x86_thread_state_t ts;
9553         left = end - begin;
9554         if (left >= sizeof(MachO::x86_thread_state_t)) {
9555           memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
9556           begin += sizeof(MachO::x86_thread_state_t);
9557         } else {
9558           memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
9559           memcpy(&ts, begin, left);
9560           begin += left;
9561         }
9562         if (isLittleEndian != sys::IsLittleEndianHost)
9563           swapStruct(ts);
9564         if (ts.tsh.flavor == MachO::x86_THREAD_STATE32) {
9565           outs() << "\t    tsh.flavor x86_THREAD_STATE32 ";
9566           if (ts.tsh.count == MachO::x86_THREAD_STATE32_COUNT)
9567             outs() << "tsh.count x86_THREAD_STATE32_COUNT\n";
9568           else
9569             outs() << "tsh.count " << ts.tsh.count
9570                    << " (not x86_THREAD_STATE32_COUNT\n";
9571           Print_x86_thread_state32_t(ts.uts.ts32);
9572         } else {
9573           outs() << "\t    tsh.flavor " << ts.tsh.flavor << "  tsh.count "
9574                  << ts.tsh.count << "\n";
9575         }
9576       } else {
9577         outs() << "     flavor " << flavor << " (unknown)\n";
9578         outs() << "      count " << count << "\n";
9579         outs() << "      state (unknown)\n";
9580         begin += count * sizeof(uint32_t);
9581       }
9582     }
9583   } else if (cputype == MachO::CPU_TYPE_X86_64) {
9584     while (begin < end) {
9585       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9586         memcpy((char *)&flavor, begin, sizeof(uint32_t));
9587         begin += sizeof(uint32_t);
9588       } else {
9589         flavor = 0;
9590         begin = end;
9591       }
9592       if (isLittleEndian != sys::IsLittleEndianHost)
9593         sys::swapByteOrder(flavor);
9594       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9595         memcpy((char *)&count, begin, sizeof(uint32_t));
9596         begin += sizeof(uint32_t);
9597       } else {
9598         count = 0;
9599         begin = end;
9600       }
9601       if (isLittleEndian != sys::IsLittleEndianHost)
9602         sys::swapByteOrder(count);
9603       if (flavor == MachO::x86_THREAD_STATE64) {
9604         outs() << "     flavor x86_THREAD_STATE64\n";
9605         if (count == MachO::x86_THREAD_STATE64_COUNT)
9606           outs() << "      count x86_THREAD_STATE64_COUNT\n";
9607         else
9608           outs() << "      count " << count
9609                  << " (not x86_THREAD_STATE64_COUNT)\n";
9610         MachO::x86_thread_state64_t cpu64;
9611         left = end - begin;
9612         if (left >= sizeof(MachO::x86_thread_state64_t)) {
9613           memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
9614           begin += sizeof(MachO::x86_thread_state64_t);
9615         } else {
9616           memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
9617           memcpy(&cpu64, begin, left);
9618           begin += left;
9619         }
9620         if (isLittleEndian != sys::IsLittleEndianHost)
9621           swapStruct(cpu64);
9622         Print_x86_thread_state64_t(cpu64);
9623       } else if (flavor == MachO::x86_THREAD_STATE) {
9624         outs() << "     flavor x86_THREAD_STATE\n";
9625         if (count == MachO::x86_THREAD_STATE_COUNT)
9626           outs() << "      count x86_THREAD_STATE_COUNT\n";
9627         else
9628           outs() << "      count " << count
9629                  << " (not x86_THREAD_STATE_COUNT)\n";
9630         struct MachO::x86_thread_state_t ts;
9631         left = end - begin;
9632         if (left >= sizeof(MachO::x86_thread_state_t)) {
9633           memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
9634           begin += sizeof(MachO::x86_thread_state_t);
9635         } else {
9636           memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
9637           memcpy(&ts, begin, left);
9638           begin += left;
9639         }
9640         if (isLittleEndian != sys::IsLittleEndianHost)
9641           swapStruct(ts);
9642         if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
9643           outs() << "\t    tsh.flavor x86_THREAD_STATE64 ";
9644           if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
9645             outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
9646           else
9647             outs() << "tsh.count " << ts.tsh.count
9648                    << " (not x86_THREAD_STATE64_COUNT\n";
9649           Print_x86_thread_state64_t(ts.uts.ts64);
9650         } else {
9651           outs() << "\t    tsh.flavor " << ts.tsh.flavor << "  tsh.count "
9652                  << ts.tsh.count << "\n";
9653         }
9654       } else if (flavor == MachO::x86_FLOAT_STATE) {
9655         outs() << "     flavor x86_FLOAT_STATE\n";
9656         if (count == MachO::x86_FLOAT_STATE_COUNT)
9657           outs() << "      count x86_FLOAT_STATE_COUNT\n";
9658         else
9659           outs() << "      count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
9660         struct MachO::x86_float_state_t fs;
9661         left = end - begin;
9662         if (left >= sizeof(MachO::x86_float_state_t)) {
9663           memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
9664           begin += sizeof(MachO::x86_float_state_t);
9665         } else {
9666           memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
9667           memcpy(&fs, begin, left);
9668           begin += left;
9669         }
9670         if (isLittleEndian != sys::IsLittleEndianHost)
9671           swapStruct(fs);
9672         if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
9673           outs() << "\t    fsh.flavor x86_FLOAT_STATE64 ";
9674           if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
9675             outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
9676           else
9677             outs() << "fsh.count " << fs.fsh.count
9678                    << " (not x86_FLOAT_STATE64_COUNT\n";
9679           Print_x86_float_state_t(fs.ufs.fs64);
9680         } else {
9681           outs() << "\t    fsh.flavor " << fs.fsh.flavor << "  fsh.count "
9682                  << fs.fsh.count << "\n";
9683         }
9684       } else if (flavor == MachO::x86_EXCEPTION_STATE) {
9685         outs() << "     flavor x86_EXCEPTION_STATE\n";
9686         if (count == MachO::x86_EXCEPTION_STATE_COUNT)
9687           outs() << "      count x86_EXCEPTION_STATE_COUNT\n";
9688         else
9689           outs() << "      count " << count
9690                  << " (not x86_EXCEPTION_STATE_COUNT)\n";
9691         struct MachO::x86_exception_state_t es;
9692         left = end - begin;
9693         if (left >= sizeof(MachO::x86_exception_state_t)) {
9694           memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
9695           begin += sizeof(MachO::x86_exception_state_t);
9696         } else {
9697           memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
9698           memcpy(&es, begin, left);
9699           begin += left;
9700         }
9701         if (isLittleEndian != sys::IsLittleEndianHost)
9702           swapStruct(es);
9703         if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
9704           outs() << "\t    esh.flavor x86_EXCEPTION_STATE64\n";
9705           if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
9706             outs() << "\t    esh.count x86_EXCEPTION_STATE64_COUNT\n";
9707           else
9708             outs() << "\t    esh.count " << es.esh.count
9709                    << " (not x86_EXCEPTION_STATE64_COUNT\n";
9710           Print_x86_exception_state_t(es.ues.es64);
9711         } else {
9712           outs() << "\t    esh.flavor " << es.esh.flavor << "  esh.count "
9713                  << es.esh.count << "\n";
9714         }
9715       } else if (flavor == MachO::x86_EXCEPTION_STATE64) {
9716         outs() << "     flavor x86_EXCEPTION_STATE64\n";
9717         if (count == MachO::x86_EXCEPTION_STATE64_COUNT)
9718           outs() << "      count x86_EXCEPTION_STATE64_COUNT\n";
9719         else
9720           outs() << "      count " << count
9721                  << " (not x86_EXCEPTION_STATE64_COUNT)\n";
9722         struct MachO::x86_exception_state64_t es64;
9723         left = end - begin;
9724         if (left >= sizeof(MachO::x86_exception_state64_t)) {
9725           memcpy(&es64, begin, sizeof(MachO::x86_exception_state64_t));
9726           begin += sizeof(MachO::x86_exception_state64_t);
9727         } else {
9728           memset(&es64, '\0', sizeof(MachO::x86_exception_state64_t));
9729           memcpy(&es64, begin, left);
9730           begin += left;
9731         }
9732         if (isLittleEndian != sys::IsLittleEndianHost)
9733           swapStruct(es64);
9734         Print_x86_exception_state_t(es64);
9735       } else {
9736         outs() << "     flavor " << flavor << " (unknown)\n";
9737         outs() << "      count " << count << "\n";
9738         outs() << "      state (unknown)\n";
9739         begin += count * sizeof(uint32_t);
9740       }
9741     }
9742   } else if (cputype == MachO::CPU_TYPE_ARM) {
9743     while (begin < end) {
9744       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9745         memcpy((char *)&flavor, begin, sizeof(uint32_t));
9746         begin += sizeof(uint32_t);
9747       } else {
9748         flavor = 0;
9749         begin = end;
9750       }
9751       if (isLittleEndian != sys::IsLittleEndianHost)
9752         sys::swapByteOrder(flavor);
9753       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9754         memcpy((char *)&count, begin, sizeof(uint32_t));
9755         begin += sizeof(uint32_t);
9756       } else {
9757         count = 0;
9758         begin = end;
9759       }
9760       if (isLittleEndian != sys::IsLittleEndianHost)
9761         sys::swapByteOrder(count);
9762       if (flavor == MachO::ARM_THREAD_STATE) {
9763         outs() << "     flavor ARM_THREAD_STATE\n";
9764         if (count == MachO::ARM_THREAD_STATE_COUNT)
9765           outs() << "      count ARM_THREAD_STATE_COUNT\n";
9766         else
9767           outs() << "      count " << count
9768                  << " (not ARM_THREAD_STATE_COUNT)\n";
9769         MachO::arm_thread_state32_t cpu32;
9770         left = end - begin;
9771         if (left >= sizeof(MachO::arm_thread_state32_t)) {
9772           memcpy(&cpu32, begin, sizeof(MachO::arm_thread_state32_t));
9773           begin += sizeof(MachO::arm_thread_state32_t);
9774         } else {
9775           memset(&cpu32, '\0', sizeof(MachO::arm_thread_state32_t));
9776           memcpy(&cpu32, begin, left);
9777           begin += left;
9778         }
9779         if (isLittleEndian != sys::IsLittleEndianHost)
9780           swapStruct(cpu32);
9781         Print_arm_thread_state32_t(cpu32);
9782       } else {
9783         outs() << "     flavor " << flavor << " (unknown)\n";
9784         outs() << "      count " << count << "\n";
9785         outs() << "      state (unknown)\n";
9786         begin += count * sizeof(uint32_t);
9787       }
9788     }
9789   } else if (cputype == MachO::CPU_TYPE_ARM64 ||
9790              cputype == MachO::CPU_TYPE_ARM64_32) {
9791     while (begin < end) {
9792       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9793         memcpy((char *)&flavor, begin, sizeof(uint32_t));
9794         begin += sizeof(uint32_t);
9795       } else {
9796         flavor = 0;
9797         begin = end;
9798       }
9799       if (isLittleEndian != sys::IsLittleEndianHost)
9800         sys::swapByteOrder(flavor);
9801       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9802         memcpy((char *)&count, begin, sizeof(uint32_t));
9803         begin += sizeof(uint32_t);
9804       } else {
9805         count = 0;
9806         begin = end;
9807       }
9808       if (isLittleEndian != sys::IsLittleEndianHost)
9809         sys::swapByteOrder(count);
9810       if (flavor == MachO::ARM_THREAD_STATE64) {
9811         outs() << "     flavor ARM_THREAD_STATE64\n";
9812         if (count == MachO::ARM_THREAD_STATE64_COUNT)
9813           outs() << "      count ARM_THREAD_STATE64_COUNT\n";
9814         else
9815           outs() << "      count " << count
9816                  << " (not ARM_THREAD_STATE64_COUNT)\n";
9817         MachO::arm_thread_state64_t cpu64;
9818         left = end - begin;
9819         if (left >= sizeof(MachO::arm_thread_state64_t)) {
9820           memcpy(&cpu64, begin, sizeof(MachO::arm_thread_state64_t));
9821           begin += sizeof(MachO::arm_thread_state64_t);
9822         } else {
9823           memset(&cpu64, '\0', sizeof(MachO::arm_thread_state64_t));
9824           memcpy(&cpu64, begin, left);
9825           begin += left;
9826         }
9827         if (isLittleEndian != sys::IsLittleEndianHost)
9828           swapStruct(cpu64);
9829         Print_arm_thread_state64_t(cpu64);
9830       } else {
9831         outs() << "     flavor " << flavor << " (unknown)\n";
9832         outs() << "      count " << count << "\n";
9833         outs() << "      state (unknown)\n";
9834         begin += count * sizeof(uint32_t);
9835       }
9836     }
9837   } else {
9838     while (begin < end) {
9839       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9840         memcpy((char *)&flavor, begin, sizeof(uint32_t));
9841         begin += sizeof(uint32_t);
9842       } else {
9843         flavor = 0;
9844         begin = end;
9845       }
9846       if (isLittleEndian != sys::IsLittleEndianHost)
9847         sys::swapByteOrder(flavor);
9848       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9849         memcpy((char *)&count, begin, sizeof(uint32_t));
9850         begin += sizeof(uint32_t);
9851       } else {
9852         count = 0;
9853         begin = end;
9854       }
9855       if (isLittleEndian != sys::IsLittleEndianHost)
9856         sys::swapByteOrder(count);
9857       outs() << "     flavor " << flavor << "\n";
9858       outs() << "      count " << count << "\n";
9859       outs() << "      state (Unknown cputype/cpusubtype)\n";
9860       begin += count * sizeof(uint32_t);
9861     }
9862   }
9863 }
9864
9865 static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
9866   if (dl.cmd == MachO::LC_ID_DYLIB)
9867     outs() << "          cmd LC_ID_DYLIB\n";
9868   else if (dl.cmd == MachO::LC_LOAD_DYLIB)
9869     outs() << "          cmd LC_LOAD_DYLIB\n";
9870   else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
9871     outs() << "          cmd LC_LOAD_WEAK_DYLIB\n";
9872   else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
9873     outs() << "          cmd LC_REEXPORT_DYLIB\n";
9874   else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
9875     outs() << "          cmd LC_LAZY_LOAD_DYLIB\n";
9876   else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
9877     outs() << "          cmd LC_LOAD_UPWARD_DYLIB\n";
9878   else
9879     outs() << "          cmd " << dl.cmd << " (unknown)\n";
9880   outs() << "      cmdsize " << dl.cmdsize;
9881   if (dl.cmdsize < sizeof(struct MachO::dylib_command))
9882     outs() << " Incorrect size\n";
9883   else
9884     outs() << "\n";
9885   if (dl.dylib.name < dl.cmdsize) {
9886     const char *P = (const char *)(Ptr) + dl.dylib.name;
9887     outs() << "         name " << P << " (offset " << dl.dylib.name << ")\n";
9888   } else {
9889     outs() << "         name ?(bad offset " << dl.dylib.name << ")\n";
9890   }
9891   outs() << "   time stamp " << dl.dylib.timestamp << " ";
9892   time_t t = dl.dylib.timestamp;
9893   outs() << ctime(&t);
9894   outs() << "      current version ";
9895   if (dl.dylib.current_version == 0xffffffff)
9896     outs() << "n/a\n";
9897   else
9898     outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
9899            << ((dl.dylib.current_version >> 8) & 0xff) << "."
9900            << (dl.dylib.current_version & 0xff) << "\n";
9901   outs() << "compatibility version ";
9902   if (dl.dylib.compatibility_version == 0xffffffff)
9903     outs() << "n/a\n";
9904   else
9905     outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
9906            << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
9907            << (dl.dylib.compatibility_version & 0xff) << "\n";
9908 }
9909
9910 static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
9911                                      uint32_t object_size) {
9912   if (ld.cmd == MachO::LC_CODE_SIGNATURE)
9913     outs() << "      cmd LC_CODE_SIGNATURE\n";
9914   else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
9915     outs() << "      cmd LC_SEGMENT_SPLIT_INFO\n";
9916   else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
9917     outs() << "      cmd LC_FUNCTION_STARTS\n";
9918   else if (ld.cmd == MachO::LC_DATA_IN_CODE)
9919     outs() << "      cmd LC_DATA_IN_CODE\n";
9920   else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
9921     outs() << "      cmd LC_DYLIB_CODE_SIGN_DRS\n";
9922   else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
9923     outs() << "      cmd LC_LINKER_OPTIMIZATION_HINT\n";
9924   else
9925     outs() << "      cmd " << ld.cmd << " (?)\n";
9926   outs() << "  cmdsize " << ld.cmdsize;
9927   if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
9928     outs() << " Incorrect size\n";
9929   else
9930     outs() << "\n";
9931   outs() << "  dataoff " << ld.dataoff;
9932   if (ld.dataoff > object_size)
9933     outs() << " (past end of file)\n";
9934   else
9935     outs() << "\n";
9936   outs() << " datasize " << ld.datasize;
9937   uint64_t big_size = ld.dataoff;
9938   big_size += ld.datasize;
9939   if (big_size > object_size)
9940     outs() << " (past end of file)\n";
9941   else
9942     outs() << "\n";
9943 }
9944
9945 static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
9946                               uint32_t cputype, bool verbose) {
9947   StringRef Buf = Obj->getData();
9948   unsigned Index = 0;
9949   for (const auto &Command : Obj->load_commands()) {
9950     outs() << "Load command " << Index++ << "\n";
9951     if (Command.C.cmd == MachO::LC_SEGMENT) {
9952       MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
9953       const char *sg_segname = SLC.segname;
9954       PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
9955                           SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
9956                           SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
9957                           verbose);
9958       for (unsigned j = 0; j < SLC.nsects; j++) {
9959         MachO::section S = Obj->getSection(Command, j);
9960         PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
9961                      S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
9962                      SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
9963       }
9964     } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
9965       MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
9966       const char *sg_segname = SLC_64.segname;
9967       PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
9968                           SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
9969                           SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
9970                           SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
9971       for (unsigned j = 0; j < SLC_64.nsects; j++) {
9972         MachO::section_64 S_64 = Obj->getSection64(Command, j);
9973         PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
9974                      S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
9975                      S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
9976                      sg_segname, filetype, Buf.size(), verbose);
9977       }
9978     } else if (Command.C.cmd == MachO::LC_SYMTAB) {
9979       MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
9980       PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
9981     } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
9982       MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
9983       MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
9984       PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
9985                                Obj->is64Bit());
9986     } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
9987                Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
9988       MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
9989       PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
9990     } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
9991                Command.C.cmd == MachO::LC_ID_DYLINKER ||
9992                Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
9993       MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
9994       PrintDyldLoadCommand(Dyld, Command.Ptr);
9995     } else if (Command.C.cmd == MachO::LC_UUID) {
9996       MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
9997       PrintUuidLoadCommand(Uuid);
9998     } else if (Command.C.cmd == MachO::LC_RPATH) {
9999       MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
10000       PrintRpathLoadCommand(Rpath, Command.Ptr);
10001     } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
10002                Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
10003                Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
10004                Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
10005       MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
10006       PrintVersionMinLoadCommand(Vd);
10007     } else if (Command.C.cmd == MachO::LC_NOTE) {
10008       MachO::note_command Nt = Obj->getNoteLoadCommand(Command);
10009       PrintNoteLoadCommand(Nt);
10010     } else if (Command.C.cmd == MachO::LC_BUILD_VERSION) {
10011       MachO::build_version_command Bv =
10012           Obj->getBuildVersionLoadCommand(Command);
10013       PrintBuildVersionLoadCommand(Obj, Bv);
10014     } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
10015       MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
10016       PrintSourceVersionCommand(Sd);
10017     } else if (Command.C.cmd == MachO::LC_MAIN) {
10018       MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
10019       PrintEntryPointCommand(Ep);
10020     } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
10021       MachO::encryption_info_command Ei =
10022           Obj->getEncryptionInfoCommand(Command);
10023       PrintEncryptionInfoCommand(Ei, Buf.size());
10024     } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
10025       MachO::encryption_info_command_64 Ei =
10026           Obj->getEncryptionInfoCommand64(Command);
10027       PrintEncryptionInfoCommand64(Ei, Buf.size());
10028     } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
10029       MachO::linker_option_command Lo =
10030           Obj->getLinkerOptionLoadCommand(Command);
10031       PrintLinkerOptionCommand(Lo, Command.Ptr);
10032     } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
10033       MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
10034       PrintSubFrameworkCommand(Sf, Command.Ptr);
10035     } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
10036       MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
10037       PrintSubUmbrellaCommand(Sf, Command.Ptr);
10038     } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
10039       MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
10040       PrintSubLibraryCommand(Sl, Command.Ptr);
10041     } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
10042       MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
10043       PrintSubClientCommand(Sc, Command.Ptr);
10044     } else if (Command.C.cmd == MachO::LC_ROUTINES) {
10045       MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
10046       PrintRoutinesCommand(Rc);
10047     } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
10048       MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
10049       PrintRoutinesCommand64(Rc);
10050     } else if (Command.C.cmd == MachO::LC_THREAD ||
10051                Command.C.cmd == MachO::LC_UNIXTHREAD) {
10052       MachO::thread_command Tc = Obj->getThreadCommand(Command);
10053       PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
10054     } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
10055                Command.C.cmd == MachO::LC_ID_DYLIB ||
10056                Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
10057                Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
10058                Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
10059                Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
10060       MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
10061       PrintDylibCommand(Dl, Command.Ptr);
10062     } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
10063                Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
10064                Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
10065                Command.C.cmd == MachO::LC_DATA_IN_CODE ||
10066                Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
10067                Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
10068       MachO::linkedit_data_command Ld =
10069           Obj->getLinkeditDataLoadCommand(Command);
10070       PrintLinkEditDataCommand(Ld, Buf.size());
10071     } else {
10072       outs() << "      cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
10073              << ")\n";
10074       outs() << "  cmdsize " << Command.C.cmdsize << "\n";
10075       // TODO: get and print the raw bytes of the load command.
10076     }
10077     // TODO: print all the other kinds of load commands.
10078   }
10079 }
10080
10081 static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
10082   if (Obj->is64Bit()) {
10083     MachO::mach_header_64 H_64;
10084     H_64 = Obj->getHeader64();
10085     PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
10086                     H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
10087   } else {
10088     MachO::mach_header H;
10089     H = Obj->getHeader();
10090     PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
10091                     H.sizeofcmds, H.flags, verbose);
10092   }
10093 }
10094
10095 void printMachOFileHeader(const object::ObjectFile *Obj) {
10096   const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
10097   PrintMachHeader(file, !NonVerbose);
10098 }
10099
10100 void printMachOLoadCommands(const object::ObjectFile *Obj) {
10101   const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
10102   uint32_t filetype = 0;
10103   uint32_t cputype = 0;
10104   if (file->is64Bit()) {
10105     MachO::mach_header_64 H_64;
10106     H_64 = file->getHeader64();
10107     filetype = H_64.filetype;
10108     cputype = H_64.cputype;
10109   } else {
10110     MachO::mach_header H;
10111     H = file->getHeader();
10112     filetype = H.filetype;
10113     cputype = H.cputype;
10114   }
10115   PrintLoadCommands(file, filetype, cputype, !NonVerbose);
10116 }
10117
10118 //===----------------------------------------------------------------------===//
10119 // export trie dumping
10120 //===----------------------------------------------------------------------===//
10121
10122 void printMachOExportsTrie(const object::MachOObjectFile *Obj) {
10123   uint64_t BaseSegmentAddress = 0;
10124   for (const auto &Command : Obj->load_commands()) {
10125     if (Command.C.cmd == MachO::LC_SEGMENT) {
10126       MachO::segment_command Seg = Obj->getSegmentLoadCommand(Command);
10127       if (Seg.fileoff == 0 && Seg.filesize != 0) {
10128         BaseSegmentAddress = Seg.vmaddr;
10129         break;
10130       }
10131     } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
10132       MachO::segment_command_64 Seg = Obj->getSegment64LoadCommand(Command);
10133       if (Seg.fileoff == 0 && Seg.filesize != 0) {
10134         BaseSegmentAddress = Seg.vmaddr;
10135         break;
10136       }
10137     }
10138   }
10139   Error Err = Error::success();
10140   for (const object::ExportEntry &Entry : Obj->exports(Err)) {
10141     uint64_t Flags = Entry.flags();
10142     bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
10143     bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
10144     bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
10145                         MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
10146     bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
10147                 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
10148     bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
10149     if (ReExport)
10150       outs() << "[re-export] ";
10151     else
10152       outs() << format("0x%08llX  ",
10153                        Entry.address() + BaseSegmentAddress);
10154     outs() << Entry.name();
10155     if (WeakDef || ThreadLocal || Resolver || Abs) {
10156       bool NeedsComma = false;
10157       outs() << " [";
10158       if (WeakDef) {
10159         outs() << "weak_def";
10160         NeedsComma = true;
10161       }
10162       if (ThreadLocal) {
10163         if (NeedsComma)
10164           outs() << ", ";
10165         outs() << "per-thread";
10166         NeedsComma = true;
10167       }
10168       if (Abs) {
10169         if (NeedsComma)
10170           outs() << ", ";
10171         outs() << "absolute";
10172         NeedsComma = true;
10173       }
10174       if (Resolver) {
10175         if (NeedsComma)
10176           outs() << ", ";
10177         outs() << format("resolver=0x%08llX", Entry.other());
10178         NeedsComma = true;
10179       }
10180       outs() << "]";
10181     }
10182     if (ReExport) {
10183       StringRef DylibName = "unknown";
10184       int Ordinal = Entry.other() - 1;
10185       Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
10186       if (Entry.otherName().empty())
10187         outs() << " (from " << DylibName << ")";
10188       else
10189         outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
10190     }
10191     outs() << "\n";
10192   }
10193   if (Err)
10194     report_error(std::move(Err), Obj->getFileName());
10195 }
10196
10197 //===----------------------------------------------------------------------===//
10198 // rebase table dumping
10199 //===----------------------------------------------------------------------===//
10200
10201 void printMachORebaseTable(object::MachOObjectFile *Obj) {
10202   outs() << "segment  section            address     type\n";
10203   Error Err = Error::success();
10204   for (const object::MachORebaseEntry &Entry : Obj->rebaseTable(Err)) {
10205     StringRef SegmentName = Entry.segmentName();
10206     StringRef SectionName = Entry.sectionName();
10207     uint64_t Address = Entry.address();
10208
10209     // Table lines look like: __DATA  __nl_symbol_ptr  0x0000F00C  pointer
10210     outs() << format("%-8s %-18s 0x%08" PRIX64 "  %s\n",
10211                      SegmentName.str().c_str(), SectionName.str().c_str(),
10212                      Address, Entry.typeName().str().c_str());
10213   }
10214   if (Err)
10215     report_error(std::move(Err), Obj->getFileName());
10216 }
10217
10218 static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
10219   StringRef DylibName;
10220   switch (Ordinal) {
10221   case MachO::BIND_SPECIAL_DYLIB_SELF:
10222     return "this-image";
10223   case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
10224     return "main-executable";
10225   case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
10226     return "flat-namespace";
10227   default:
10228     if (Ordinal > 0) {
10229       std::error_code EC =
10230           Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
10231       if (EC)
10232         return "<<bad library ordinal>>";
10233       return DylibName;
10234     }
10235   }
10236   return "<<unknown special ordinal>>";
10237 }
10238
10239 //===----------------------------------------------------------------------===//
10240 // bind table dumping
10241 //===----------------------------------------------------------------------===//
10242
10243 void printMachOBindTable(object::MachOObjectFile *Obj) {
10244   // Build table of sections so names can used in final output.
10245   outs() << "segment  section            address    type       "
10246             "addend dylib            symbol\n";
10247   Error Err = Error::success();
10248   for (const object::MachOBindEntry &Entry : Obj->bindTable(Err)) {
10249     StringRef SegmentName = Entry.segmentName();
10250     StringRef SectionName = Entry.sectionName();
10251     uint64_t Address = Entry.address();
10252
10253     // Table lines look like:
10254     //  __DATA  __got  0x00012010    pointer   0 libSystem ___stack_chk_guard
10255     StringRef Attr;
10256     if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
10257       Attr = " (weak_import)";
10258     outs() << left_justify(SegmentName, 8) << " "
10259            << left_justify(SectionName, 18) << " "
10260            << format_hex(Address, 10, true) << " "
10261            << left_justify(Entry.typeName(), 8) << " "
10262            << format_decimal(Entry.addend(), 8) << " "
10263            << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
10264            << Entry.symbolName() << Attr << "\n";
10265   }
10266   if (Err)
10267     report_error(std::move(Err), Obj->getFileName());
10268 }
10269
10270 //===----------------------------------------------------------------------===//
10271 // lazy bind table dumping
10272 //===----------------------------------------------------------------------===//
10273
10274 void printMachOLazyBindTable(object::MachOObjectFile *Obj) {
10275   outs() << "segment  section            address     "
10276             "dylib            symbol\n";
10277   Error Err = Error::success();
10278   for (const object::MachOBindEntry &Entry : Obj->lazyBindTable(Err)) {
10279     StringRef SegmentName = Entry.segmentName();
10280     StringRef SectionName = Entry.sectionName();
10281     uint64_t Address = Entry.address();
10282
10283     // Table lines look like:
10284     //  __DATA  __got  0x00012010 libSystem ___stack_chk_guard
10285     outs() << left_justify(SegmentName, 8) << " "
10286            << left_justify(SectionName, 18) << " "
10287            << format_hex(Address, 10, true) << " "
10288            << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
10289            << Entry.symbolName() << "\n";
10290   }
10291   if (Err)
10292     report_error(std::move(Err), Obj->getFileName());
10293 }
10294
10295 //===----------------------------------------------------------------------===//
10296 // weak bind table dumping
10297 //===----------------------------------------------------------------------===//
10298
10299 void printMachOWeakBindTable(object::MachOObjectFile *Obj) {
10300   outs() << "segment  section            address     "
10301             "type       addend   symbol\n";
10302   Error Err = Error::success();
10303   for (const object::MachOBindEntry &Entry : Obj->weakBindTable(Err)) {
10304     // Strong symbols don't have a location to update.
10305     if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
10306       outs() << "                                        strong              "
10307              << Entry.symbolName() << "\n";
10308       continue;
10309     }
10310     StringRef SegmentName = Entry.segmentName();
10311     StringRef SectionName = Entry.sectionName();
10312     uint64_t Address = Entry.address();
10313
10314     // Table lines look like:
10315     // __DATA  __data  0x00001000  pointer    0   _foo
10316     outs() << left_justify(SegmentName, 8) << " "
10317            << left_justify(SectionName, 18) << " "
10318            << format_hex(Address, 10, true) << " "
10319            << left_justify(Entry.typeName(), 8) << " "
10320            << format_decimal(Entry.addend(), 8) << "   " << Entry.symbolName()
10321            << "\n";
10322   }
10323   if (Err)
10324     report_error(std::move(Err), Obj->getFileName());
10325 }
10326
10327 // get_dyld_bind_info_symbolname() is used for disassembly and passed an
10328 // address, ReferenceValue, in the Mach-O file and looks in the dyld bind
10329 // information for that address. If the address is found its binding symbol
10330 // name is returned.  If not nullptr is returned.
10331 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
10332                                                  struct DisassembleInfo *info) {
10333   if (info->bindtable == nullptr) {
10334     info->bindtable = llvm::make_unique<SymbolAddressMap>();
10335     Error Err = Error::success();
10336     for (const object::MachOBindEntry &Entry : info->O->bindTable(Err)) {
10337       uint64_t Address = Entry.address();
10338       StringRef name = Entry.symbolName();
10339       if (!name.empty())
10340         (*info->bindtable)[Address] = name;
10341     }
10342     if (Err)
10343       report_error(std::move(Err), info->O->getFileName());
10344   }
10345   auto name = info->bindtable->lookup(ReferenceValue);
10346   return !name.empty() ? name.data() : nullptr;
10347 }
10348
10349 void printLazyBindTable(ObjectFile *o) {
10350   outs() << "Lazy bind table:\n";
10351   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10352     printMachOLazyBindTable(MachO);
10353   else
10354     WithColor::error()
10355         << "This operation is only currently supported "
10356            "for Mach-O executable files.\n";
10357 }
10358
10359 void printWeakBindTable(ObjectFile *o) {
10360   outs() << "Weak bind table:\n";
10361   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10362     printMachOWeakBindTable(MachO);
10363   else
10364     WithColor::error()
10365         << "This operation is only currently supported "
10366            "for Mach-O executable files.\n";
10367 }
10368
10369 void printExportsTrie(const ObjectFile *o) {
10370   outs() << "Exports trie:\n";
10371   if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10372     printMachOExportsTrie(MachO);
10373   else
10374     WithColor::error()
10375         << "This operation is only currently supported "
10376            "for Mach-O executable files.\n";
10377 }
10378
10379 void printRebaseTable(ObjectFile *o) {
10380   outs() << "Rebase table:\n";
10381   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10382     printMachORebaseTable(MachO);
10383   else
10384     WithColor::error()
10385         << "This operation is only currently supported "
10386            "for Mach-O executable files.\n";
10387 }
10388
10389 void printBindTable(ObjectFile *o) {
10390   outs() << "Bind table:\n";
10391   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10392     printMachOBindTable(MachO);
10393   else
10394     WithColor::error()
10395         << "This operation is only currently supported "
10396            "for Mach-O executable files.\n";
10397 }
10398 } // namespace llvm