1 //===- MachOObjectFile.cpp - Mach-O object file binding -------------------===//
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 defines the MachOObjectFile class, which binds the MachOObject
10 // class to the generic ObjectFile wrapper.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/ADT/ArrayRef.h"
15 #include "llvm/ADT/None.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/ADT/StringSwitch.h"
20 #include "llvm/ADT/Triple.h"
21 #include "llvm/ADT/Twine.h"
22 #include "llvm/BinaryFormat/MachO.h"
23 #include "llvm/Object/Error.h"
24 #include "llvm/Object/MachO.h"
25 #include "llvm/Object/ObjectFile.h"
26 #include "llvm/Object/SymbolicFile.h"
27 #include "llvm/Support/DataExtractor.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/Error.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/Format.h"
32 #include "llvm/Support/Host.h"
33 #include "llvm/Support/LEB128.h"
34 #include "llvm/Support/MemoryBuffer.h"
35 #include "llvm/Support/SwapByteOrder.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include <algorithm>
38 #include <cassert>
39 #include <cstddef>
40 #include <cstdint>
41 #include <cstring>
42 #include <limits>
43 #include <list>
44 #include <memory>
45 #include <string>
46 #include <system_error>
47 
48 using namespace llvm;
49 using namespace object;
50 
51 namespace {
52 
53   struct section_base {
54     char sectname[16];
55     char segname[16];
56   };
57 
58 } // end anonymous namespace
59 
60 static Error malformedError(const Twine &Msg) {
61   return make_error<GenericBinaryError>("truncated or malformed object (" +
62                                             Msg + ")",
63                                         object_error::parse_failed);
64 }
65 
66 // FIXME: Replace all uses of this function with getStructOrErr.
67 template <typename T>
68 static T getStruct(const MachOObjectFile &O, const char *P) {
69   // Don't read before the beginning or past the end of the file
70   if (P < O.getData().begin() || P + sizeof(T) > O.getData().end())
71     report_fatal_error("Malformed MachO file.");
72 
73   T Cmd;
74   memcpy(&Cmd, P, sizeof(T));
75   if (O.isLittleEndian() != sys::IsLittleEndianHost)
76     MachO::swapStruct(Cmd);
77   return Cmd;
78 }
79 
80 template <typename T>
81 static Expected<T> getStructOrErr(const MachOObjectFile &O, const char *P) {
82   // Don't read before the beginning or past the end of the file
83   if (P < O.getData().begin() || P + sizeof(T) > O.getData().end())
84     return malformedError("Structure read out-of-range");
85 
86   T Cmd;
87   memcpy(&Cmd, P, sizeof(T));
88   if (O.isLittleEndian() != sys::IsLittleEndianHost)
89     MachO::swapStruct(Cmd);
90   return Cmd;
91 }
92 
93 static const char *
94 getSectionPtr(const MachOObjectFile &O, MachOObjectFile::LoadCommandInfo L,
95               unsigned Sec) {
96   uintptr_t CommandAddr = reinterpret_cast<uintptr_t>(L.Ptr);
97 
98   bool Is64 = O.is64Bit();
99   unsigned SegmentLoadSize = Is64 ? sizeof(MachO::segment_command_64) :
100                                     sizeof(MachO::segment_command);
101   unsigned SectionSize = Is64 ? sizeof(MachO::section_64) :
102                                 sizeof(MachO::section);
103 
104   uintptr_t SectionAddr = CommandAddr + SegmentLoadSize + Sec * SectionSize;
105   return reinterpret_cast<const char*>(SectionAddr);
106 }
107 
108 static const char *getPtr(const MachOObjectFile &O, size_t Offset) {
109   assert(Offset <= O.getData().size());
110   return O.getData().data() + Offset;
111 }
112 
113 static MachO::nlist_base
114 getSymbolTableEntryBase(const MachOObjectFile &O, DataRefImpl DRI) {
115   const char *P = reinterpret_cast<const char *>(DRI.p);
116   return getStruct<MachO::nlist_base>(O, P);
117 }
118 
119 static StringRef parseSegmentOrSectionName(const char *P) {
120   if (P[15] == 0)
121     // Null terminated.
122     return P;
123   // Not null terminated, so this is a 16 char string.
124   return StringRef(P, 16);
125 }
126 
127 static unsigned getCPUType(const MachOObjectFile &O) {
128   return O.getHeader().cputype;
129 }
130 
131 static uint32_t
132 getPlainRelocationAddress(const MachO::any_relocation_info &RE) {
133   return RE.r_word0;
134 }
135 
136 static unsigned
137 getScatteredRelocationAddress(const MachO::any_relocation_info &RE) {
138   return RE.r_word0 & 0xffffff;
139 }
140 
141 static bool getPlainRelocationPCRel(const MachOObjectFile &O,
142                                     const MachO::any_relocation_info &RE) {
143   if (O.isLittleEndian())
144     return (RE.r_word1 >> 24) & 1;
145   return (RE.r_word1 >> 7) & 1;
146 }
147 
148 static bool
149 getScatteredRelocationPCRel(const MachO::any_relocation_info &RE) {
150   return (RE.r_word0 >> 30) & 1;
151 }
152 
153 static unsigned getPlainRelocationLength(const MachOObjectFile &O,
154                                          const MachO::any_relocation_info &RE) {
155   if (O.isLittleEndian())
156     return (RE.r_word1 >> 25) & 3;
157   return (RE.r_word1 >> 5) & 3;
158 }
159 
160 static unsigned
161 getScatteredRelocationLength(const MachO::any_relocation_info &RE) {
162   return (RE.r_word0 >> 28) & 3;
163 }
164 
165 static unsigned getPlainRelocationType(const MachOObjectFile &O,
166                                        const MachO::any_relocation_info &RE) {
167   if (O.isLittleEndian())
168     return RE.r_word1 >> 28;
169   return RE.r_word1 & 0xf;
170 }
171 
172 static uint32_t getSectionFlags(const MachOObjectFile &O,
173                                 DataRefImpl Sec) {
174   if (O.is64Bit()) {
175     MachO::section_64 Sect = O.getSection64(Sec);
176     return Sect.flags;
177   }
178   MachO::section Sect = O.getSection(Sec);
179   return Sect.flags;
180 }
181 
182 static Expected<MachOObjectFile::LoadCommandInfo>
183 getLoadCommandInfo(const MachOObjectFile &Obj, const char *Ptr,
184                    uint32_t LoadCommandIndex) {
185   if (auto CmdOrErr = getStructOrErr<MachO::load_command>(Obj, Ptr)) {
186     if (CmdOrErr->cmdsize + Ptr > Obj.getData().end())
187       return malformedError("load command " + Twine(LoadCommandIndex) +
188                             " extends past end of file");
189     if (CmdOrErr->cmdsize < 8)
190       return malformedError("load command " + Twine(LoadCommandIndex) +
191                             " with size less than 8 bytes");
192     return MachOObjectFile::LoadCommandInfo({Ptr, *CmdOrErr});
193   } else
194     return CmdOrErr.takeError();
195 }
196 
197 static Expected<MachOObjectFile::LoadCommandInfo>
198 getFirstLoadCommandInfo(const MachOObjectFile &Obj) {
199   unsigned HeaderSize = Obj.is64Bit() ? sizeof(MachO::mach_header_64)
200                                       : sizeof(MachO::mach_header);
201   if (sizeof(MachO::load_command) > Obj.getHeader().sizeofcmds)
202     return malformedError("load command 0 extends past the end all load "
203                           "commands in the file");
204   return getLoadCommandInfo(Obj, getPtr(Obj, HeaderSize), 0);
205 }
206 
207 static Expected<MachOObjectFile::LoadCommandInfo>
208 getNextLoadCommandInfo(const MachOObjectFile &Obj, uint32_t LoadCommandIndex,
209                        const MachOObjectFile::LoadCommandInfo &L) {
210   unsigned HeaderSize = Obj.is64Bit() ? sizeof(MachO::mach_header_64)
211                                       : sizeof(MachO::mach_header);
212   if (L.Ptr + L.C.cmdsize + sizeof(MachO::load_command) >
213       Obj.getData().data() + HeaderSize + Obj.getHeader().sizeofcmds)
214     return malformedError("load command " + Twine(LoadCommandIndex + 1) +
215                           " extends past the end all load commands in the file");
216   return getLoadCommandInfo(Obj, L.Ptr + L.C.cmdsize, LoadCommandIndex + 1);
217 }
218 
219 template <typename T>
220 static void parseHeader(const MachOObjectFile &Obj, T &Header,
221                         Error &Err) {
222   if (sizeof(T) > Obj.getData().size()) {
223     Err = malformedError("the mach header extends past the end of the "
224                          "file");
225     return;
226   }
227   if (auto HeaderOrErr = getStructOrErr<T>(Obj, getPtr(Obj, 0)))
228     Header = *HeaderOrErr;
229   else
230     Err = HeaderOrErr.takeError();
231 }
232 
233 // This is used to check for overlapping of Mach-O elements.
234 struct MachOElement {
235   uint64_t Offset;
236   uint64_t Size;
237   const char *Name;
238 };
239 
240 static Error checkOverlappingElement(std::list<MachOElement> &Elements,
241                                      uint64_t Offset, uint64_t Size,
242                                      const char *Name) {
243   if (Size == 0)
244     return Error::success();
245 
246   for (auto it=Elements.begin() ; it != Elements.end(); ++it) {
247     auto E = *it;
248     if ((Offset >= E.Offset && Offset < E.Offset + E.Size) ||
249         (Offset + Size > E.Offset && Offset + Size < E.Offset + E.Size) ||
250         (Offset <= E.Offset && Offset + Size >= E.Offset + E.Size))
251       return malformedError(Twine(Name) + " at offset " + Twine(Offset) +
252                             " with a size of " + Twine(Size) + ", overlaps " +
253                             E.Name + " at offset " + Twine(E.Offset) + " with "
254                             "a size of " + Twine(E.Size));
255     auto nt = it;
256     nt++;
257     if (nt != Elements.end()) {
258       auto N = *nt;
259       if (Offset + Size <= N.Offset) {
260         Elements.insert(nt, {Offset, Size, Name});
261         return Error::success();
262       }
263     }
264   }
265   Elements.push_back({Offset, Size, Name});
266   return Error::success();
267 }
268 
269 // Parses LC_SEGMENT or LC_SEGMENT_64 load command, adds addresses of all
270 // sections to \param Sections, and optionally sets
271 // \param IsPageZeroSegment to true.
272 template <typename Segment, typename Section>
273 static Error parseSegmentLoadCommand(
274     const MachOObjectFile &Obj, const MachOObjectFile::LoadCommandInfo &Load,
275     SmallVectorImpl<const char *> &Sections, bool &IsPageZeroSegment,
276     uint32_t LoadCommandIndex, const char *CmdName, uint64_t SizeOfHeaders,
277     std::list<MachOElement> &Elements) {
278   const unsigned SegmentLoadSize = sizeof(Segment);
279   if (Load.C.cmdsize < SegmentLoadSize)
280     return malformedError("load command " + Twine(LoadCommandIndex) +
281                           " " + CmdName + " cmdsize too small");
282   if (auto SegOrErr = getStructOrErr<Segment>(Obj, Load.Ptr)) {
283     Segment S = SegOrErr.get();
284     const unsigned SectionSize = sizeof(Section);
285     uint64_t FileSize = Obj.getData().size();
286     if (S.nsects > std::numeric_limits<uint32_t>::max() / SectionSize ||
287         S.nsects * SectionSize > Load.C.cmdsize - SegmentLoadSize)
288       return malformedError("load command " + Twine(LoadCommandIndex) +
289                             " inconsistent cmdsize in " + CmdName +
290                             " for the number of sections");
291     for (unsigned J = 0; J < S.nsects; ++J) {
292       const char *Sec = getSectionPtr(Obj, Load, J);
293       Sections.push_back(Sec);
294       auto SectionOrErr = getStructOrErr<Section>(Obj, Sec);
295       if (!SectionOrErr)
296         return SectionOrErr.takeError();
297       Section s = SectionOrErr.get();
298       if (Obj.getHeader().filetype != MachO::MH_DYLIB_STUB &&
299           Obj.getHeader().filetype != MachO::MH_DSYM &&
300           s.flags != MachO::S_ZEROFILL &&
301           s.flags != MachO::S_THREAD_LOCAL_ZEROFILL &&
302           s.offset > FileSize)
303         return malformedError("offset field of section " + Twine(J) + " in " +
304                               CmdName + " command " + Twine(LoadCommandIndex) +
305                               " extends past the end of the file");
306       if (Obj.getHeader().filetype != MachO::MH_DYLIB_STUB &&
307           Obj.getHeader().filetype != MachO::MH_DSYM &&
308           s.flags != MachO::S_ZEROFILL &&
309           s.flags != MachO::S_THREAD_LOCAL_ZEROFILL && S.fileoff == 0 &&
310           s.offset < SizeOfHeaders && s.size != 0)
311         return malformedError("offset field of section " + Twine(J) + " in " +
312                               CmdName + " command " + Twine(LoadCommandIndex) +
313                               " not past the headers of the file");
314       uint64_t BigSize = s.offset;
315       BigSize += s.size;
316       if (Obj.getHeader().filetype != MachO::MH_DYLIB_STUB &&
317           Obj.getHeader().filetype != MachO::MH_DSYM &&
318           s.flags != MachO::S_ZEROFILL &&
319           s.flags != MachO::S_THREAD_LOCAL_ZEROFILL &&
320           BigSize > FileSize)
321         return malformedError("offset field plus size field of section " +
322                               Twine(J) + " in " + CmdName + " command " +
323                               Twine(LoadCommandIndex) +
324                               " extends past the end of the file");
325       if (Obj.getHeader().filetype != MachO::MH_DYLIB_STUB &&
326           Obj.getHeader().filetype != MachO::MH_DSYM &&
327           s.flags != MachO::S_ZEROFILL &&
328           s.flags != MachO::S_THREAD_LOCAL_ZEROFILL &&
329           s.size > S.filesize)
330         return malformedError("size field of section " +
331                               Twine(J) + " in " + CmdName + " command " +
332                               Twine(LoadCommandIndex) +
333                               " greater than the segment");
334       if (Obj.getHeader().filetype != MachO::MH_DYLIB_STUB &&
335           Obj.getHeader().filetype != MachO::MH_DSYM && s.size != 0 &&
336           s.addr < S.vmaddr)
337         return malformedError("addr field of section " + Twine(J) + " in " +
338                               CmdName + " command " + Twine(LoadCommandIndex) +
339                               " less than the segment's vmaddr");
340       BigSize = s.addr;
341       BigSize += s.size;
342       uint64_t BigEnd = S.vmaddr;
343       BigEnd += S.vmsize;
344       if (S.vmsize != 0 && s.size != 0 && BigSize > BigEnd)
345         return malformedError("addr field plus size of section " + Twine(J) +
346                               " in " + CmdName + " command " +
347                               Twine(LoadCommandIndex) +
348                               " greater than than "
349                               "the segment's vmaddr plus vmsize");
350       if (Obj.getHeader().filetype != MachO::MH_DYLIB_STUB &&
351           Obj.getHeader().filetype != MachO::MH_DSYM &&
352           s.flags != MachO::S_ZEROFILL &&
353           s.flags != MachO::S_THREAD_LOCAL_ZEROFILL)
354         if (Error Err = checkOverlappingElement(Elements, s.offset, s.size,
355                                                 "section contents"))
356           return Err;
357       if (s.reloff > FileSize)
358         return malformedError("reloff field of section " + Twine(J) + " in " +
359                               CmdName + " command " + Twine(LoadCommandIndex) +
360                               " extends past the end of the file");
361       BigSize = s.nreloc;
362       BigSize *= sizeof(struct MachO::relocation_info);
363       BigSize += s.reloff;
364       if (BigSize > FileSize)
365         return malformedError("reloff field plus nreloc field times sizeof("
366                               "struct relocation_info) of section " +
367                               Twine(J) + " in " + CmdName + " command " +
368                               Twine(LoadCommandIndex) +
369                               " extends past the end of the file");
370       if (Error Err = checkOverlappingElement(Elements, s.reloff, s.nreloc *
371                                               sizeof(struct
372                                               MachO::relocation_info),
373                                               "section relocation entries"))
374         return Err;
375     }
376     if (S.fileoff > FileSize)
377       return malformedError("load command " + Twine(LoadCommandIndex) +
378                             " fileoff field in " + CmdName +
379                             " extends past the end of the file");
380     uint64_t BigSize = S.fileoff;
381     BigSize += S.filesize;
382     if (BigSize > FileSize)
383       return malformedError("load command " + Twine(LoadCommandIndex) +
384                             " fileoff field plus filesize field in " +
385                             CmdName + " extends past the end of the file");
386     if (S.vmsize != 0 && S.filesize > S.vmsize)
387       return malformedError("load command " + Twine(LoadCommandIndex) +
388                             " filesize field in " + CmdName +
389                             " greater than vmsize field");
390     IsPageZeroSegment |= StringRef("__PAGEZERO").equals(S.segname);
391   } else
392     return SegOrErr.takeError();
393 
394   return Error::success();
395 }
396 
397 static Error checkSymtabCommand(const MachOObjectFile &Obj,
398                                 const MachOObjectFile::LoadCommandInfo &Load,
399                                 uint32_t LoadCommandIndex,
400                                 const char **SymtabLoadCmd,
401                                 std::list<MachOElement> &Elements) {
402   if (Load.C.cmdsize < sizeof(MachO::symtab_command))
403     return malformedError("load command " + Twine(LoadCommandIndex) +
404                           " LC_SYMTAB cmdsize too small");
405   if (*SymtabLoadCmd != nullptr)
406     return malformedError("more than one LC_SYMTAB command");
407   auto SymtabOrErr = getStructOrErr<MachO::symtab_command>(Obj, Load.Ptr);
408   if (!SymtabOrErr)
409     return SymtabOrErr.takeError();
410   MachO::symtab_command Symtab = SymtabOrErr.get();
411   if (Symtab.cmdsize != sizeof(MachO::symtab_command))
412     return malformedError("LC_SYMTAB command " + Twine(LoadCommandIndex) +
413                           " has incorrect cmdsize");
414   uint64_t FileSize = Obj.getData().size();
415   if (Symtab.symoff > FileSize)
416     return malformedError("symoff field of LC_SYMTAB command " +
417                           Twine(LoadCommandIndex) + " extends past the end "
418                           "of the file");
419   uint64_t SymtabSize = Symtab.nsyms;
420   const char *struct_nlist_name;
421   if (Obj.is64Bit()) {
422     SymtabSize *= sizeof(MachO::nlist_64);
423     struct_nlist_name = "struct nlist_64";
424   } else {
425     SymtabSize *= sizeof(MachO::nlist);
426     struct_nlist_name = "struct nlist";
427   }
428   uint64_t BigSize = SymtabSize;
429   BigSize += Symtab.symoff;
430   if (BigSize > FileSize)
431     return malformedError("symoff field plus nsyms field times sizeof(" +
432                           Twine(struct_nlist_name) + ") of LC_SYMTAB command " +
433                           Twine(LoadCommandIndex) + " extends past the end "
434                           "of the file");
435   if (Error Err = checkOverlappingElement(Elements, Symtab.symoff, SymtabSize,
436                                           "symbol table"))
437     return Err;
438   if (Symtab.stroff > FileSize)
439     return malformedError("stroff field of LC_SYMTAB command " +
440                           Twine(LoadCommandIndex) + " extends past the end "
441                           "of the file");
442   BigSize = Symtab.stroff;
443   BigSize += Symtab.strsize;
444   if (BigSize > FileSize)
445     return malformedError("stroff field plus strsize field of LC_SYMTAB "
446                           "command " + Twine(LoadCommandIndex) + " extends "
447                           "past the end of the file");
448   if (Error Err = checkOverlappingElement(Elements, Symtab.stroff,
449                                           Symtab.strsize, "string table"))
450     return Err;
451   *SymtabLoadCmd = Load.Ptr;
452   return Error::success();
453 }
454 
455 static Error checkDysymtabCommand(const MachOObjectFile &Obj,
456                                   const MachOObjectFile::LoadCommandInfo &Load,
457                                   uint32_t LoadCommandIndex,
458                                   const char **DysymtabLoadCmd,
459                                   std::list<MachOElement> &Elements) {
460   if (Load.C.cmdsize < sizeof(MachO::dysymtab_command))
461     return malformedError("load command " + Twine(LoadCommandIndex) +
462                           " LC_DYSYMTAB cmdsize too small");
463   if (*DysymtabLoadCmd != nullptr)
464     return malformedError("more than one LC_DYSYMTAB command");
465   auto DysymtabOrErr =
466     getStructOrErr<MachO::dysymtab_command>(Obj, Load.Ptr);
467   if (!DysymtabOrErr)
468     return DysymtabOrErr.takeError();
469   MachO::dysymtab_command Dysymtab = DysymtabOrErr.get();
470   if (Dysymtab.cmdsize != sizeof(MachO::dysymtab_command))
471     return malformedError("LC_DYSYMTAB command " + Twine(LoadCommandIndex) +
472                           " has incorrect cmdsize");
473   uint64_t FileSize = Obj.getData().size();
474   if (Dysymtab.tocoff > FileSize)
475     return malformedError("tocoff field of LC_DYSYMTAB command " +
476                           Twine(LoadCommandIndex) + " extends past the end of "
477                           "the file");
478   uint64_t BigSize = Dysymtab.ntoc;
479   BigSize *= sizeof(MachO::dylib_table_of_contents);
480   BigSize += Dysymtab.tocoff;
481   if (BigSize > FileSize)
482     return malformedError("tocoff field plus ntoc field times sizeof(struct "
483                           "dylib_table_of_contents) of LC_DYSYMTAB command " +
484                           Twine(LoadCommandIndex) + " extends past the end of "
485                           "the file");
486   if (Error Err = checkOverlappingElement(Elements, Dysymtab.tocoff,
487                                           Dysymtab.ntoc * sizeof(struct
488                                           MachO::dylib_table_of_contents),
489                                           "table of contents"))
490     return Err;
491   if (Dysymtab.modtaboff > FileSize)
492     return malformedError("modtaboff field of LC_DYSYMTAB command " +
493                           Twine(LoadCommandIndex) + " extends past the end of "
494                           "the file");
495   BigSize = Dysymtab.nmodtab;
496   const char *struct_dylib_module_name;
497   uint64_t sizeof_modtab;
498   if (Obj.is64Bit()) {
499     sizeof_modtab = sizeof(MachO::dylib_module_64);
500     struct_dylib_module_name = "struct dylib_module_64";
501   } else {
502     sizeof_modtab = sizeof(MachO::dylib_module);
503     struct_dylib_module_name = "struct dylib_module";
504   }
505   BigSize *= sizeof_modtab;
506   BigSize += Dysymtab.modtaboff;
507   if (BigSize > FileSize)
508     return malformedError("modtaboff field plus nmodtab field times sizeof(" +
509                           Twine(struct_dylib_module_name) + ") of LC_DYSYMTAB "
510                           "command " + Twine(LoadCommandIndex) + " extends "
511                           "past the end of the file");
512   if (Error Err = checkOverlappingElement(Elements, Dysymtab.modtaboff,
513                                           Dysymtab.nmodtab * sizeof_modtab,
514                                           "module table"))
515     return Err;
516   if (Dysymtab.extrefsymoff > FileSize)
517     return malformedError("extrefsymoff field of LC_DYSYMTAB command " +
518                           Twine(LoadCommandIndex) + " extends past the end of "
519                           "the file");
520   BigSize = Dysymtab.nextrefsyms;
521   BigSize *= sizeof(MachO::dylib_reference);
522   BigSize += Dysymtab.extrefsymoff;
523   if (BigSize > FileSize)
524     return malformedError("extrefsymoff field plus nextrefsyms field times "
525                           "sizeof(struct dylib_reference) of LC_DYSYMTAB "
526                           "command " + Twine(LoadCommandIndex) + " extends "
527                           "past the end of the file");
528   if (Error Err = checkOverlappingElement(Elements, Dysymtab.extrefsymoff,
529                                           Dysymtab.nextrefsyms *
530                                               sizeof(MachO::dylib_reference),
531                                           "reference table"))
532     return Err;
533   if (Dysymtab.indirectsymoff > FileSize)
534     return malformedError("indirectsymoff field of LC_DYSYMTAB command " +
535                           Twine(LoadCommandIndex) + " extends past the end of "
536                           "the file");
537   BigSize = Dysymtab.nindirectsyms;
538   BigSize *= sizeof(uint32_t);
539   BigSize += Dysymtab.indirectsymoff;
540   if (BigSize > FileSize)
541     return malformedError("indirectsymoff field plus nindirectsyms field times "
542                           "sizeof(uint32_t) of LC_DYSYMTAB command " +
543                           Twine(LoadCommandIndex) + " extends past the end of "
544                           "the file");
545   if (Error Err = checkOverlappingElement(Elements, Dysymtab.indirectsymoff,
546                                           Dysymtab.nindirectsyms *
547                                           sizeof(uint32_t),
548                                           "indirect table"))
549     return Err;
550   if (Dysymtab.extreloff > FileSize)
551     return malformedError("extreloff field of LC_DYSYMTAB command " +
552                           Twine(LoadCommandIndex) + " extends past the end of "
553                           "the file");
554   BigSize = Dysymtab.nextrel;
555   BigSize *= sizeof(MachO::relocation_info);
556   BigSize += Dysymtab.extreloff;
557   if (BigSize > FileSize)
558     return malformedError("extreloff field plus nextrel field times sizeof"
559                           "(struct relocation_info) of LC_DYSYMTAB command " +
560                           Twine(LoadCommandIndex) + " extends past the end of "
561                           "the file");
562   if (Error Err = checkOverlappingElement(Elements, Dysymtab.extreloff,
563                                           Dysymtab.nextrel *
564                                               sizeof(MachO::relocation_info),
565                                           "external relocation table"))
566     return Err;
567   if (Dysymtab.locreloff > FileSize)
568     return malformedError("locreloff field of LC_DYSYMTAB command " +
569                           Twine(LoadCommandIndex) + " extends past the end of "
570                           "the file");
571   BigSize = Dysymtab.nlocrel;
572   BigSize *= sizeof(MachO::relocation_info);
573   BigSize += Dysymtab.locreloff;
574   if (BigSize > FileSize)
575     return malformedError("locreloff field plus nlocrel field times sizeof"
576                           "(struct relocation_info) of LC_DYSYMTAB command " +
577                           Twine(LoadCommandIndex) + " extends past the end of "
578                           "the file");
579   if (Error Err = checkOverlappingElement(Elements, Dysymtab.locreloff,
580                                           Dysymtab.nlocrel *
581                                               sizeof(MachO::relocation_info),
582                                           "local relocation table"))
583     return Err;
584   *DysymtabLoadCmd = Load.Ptr;
585   return Error::success();
586 }
587 
588 static Error checkLinkeditDataCommand(const MachOObjectFile &Obj,
589                                  const MachOObjectFile::LoadCommandInfo &Load,
590                                  uint32_t LoadCommandIndex,
591                                  const char **LoadCmd, const char *CmdName,
592                                  std::list<MachOElement> &Elements,
593                                  const char *ElementName) {
594   if (Load.C.cmdsize < sizeof(MachO::linkedit_data_command))
595     return malformedError("load command " + Twine(LoadCommandIndex) + " " +
596                           CmdName + " cmdsize too small");
597   if (*LoadCmd != nullptr)
598     return malformedError("more than one " + Twine(CmdName) + " command");
599   auto LinkDataOrError =
600     getStructOrErr<MachO::linkedit_data_command>(Obj, Load.Ptr);
601   if (!LinkDataOrError)
602     return LinkDataOrError.takeError();
603   MachO::linkedit_data_command LinkData = LinkDataOrError.get();
604   if (LinkData.cmdsize != sizeof(MachO::linkedit_data_command))
605     return malformedError(Twine(CmdName) + " command " +
606                           Twine(LoadCommandIndex) + " has incorrect cmdsize");
607   uint64_t FileSize = Obj.getData().size();
608   if (LinkData.dataoff > FileSize)
609     return malformedError("dataoff field of " + Twine(CmdName) + " command " +
610                           Twine(LoadCommandIndex) + " extends past the end of "
611                           "the file");
612   uint64_t BigSize = LinkData.dataoff;
613   BigSize += LinkData.datasize;
614   if (BigSize > FileSize)
615     return malformedError("dataoff field plus datasize field of " +
616                           Twine(CmdName) + " command " +
617                           Twine(LoadCommandIndex) + " extends past the end of "
618                           "the file");
619   if (Error Err = checkOverlappingElement(Elements, LinkData.dataoff,
620                                           LinkData.datasize, ElementName))
621     return Err;
622   *LoadCmd = Load.Ptr;
623   return Error::success();
624 }
625 
626 static Error checkDyldInfoCommand(const MachOObjectFile &Obj,
627                                   const MachOObjectFile::LoadCommandInfo &Load,
628                                   uint32_t LoadCommandIndex,
629                                   const char **LoadCmd, const char *CmdName,
630                                   std::list<MachOElement> &Elements) {
631   if (Load.C.cmdsize < sizeof(MachO::dyld_info_command))
632     return malformedError("load command " + Twine(LoadCommandIndex) + " " +
633                           CmdName + " cmdsize too small");
634   if (*LoadCmd != nullptr)
635     return malformedError("more than one LC_DYLD_INFO and or LC_DYLD_INFO_ONLY "
636                           "command");
637   auto DyldInfoOrErr =
638     getStructOrErr<MachO::dyld_info_command>(Obj, Load.Ptr);
639   if (!DyldInfoOrErr)
640     return DyldInfoOrErr.takeError();
641   MachO::dyld_info_command DyldInfo = DyldInfoOrErr.get();
642   if (DyldInfo.cmdsize != sizeof(MachO::dyld_info_command))
643     return malformedError(Twine(CmdName) + " command " +
644                           Twine(LoadCommandIndex) + " has incorrect cmdsize");
645   uint64_t FileSize = Obj.getData().size();
646   if (DyldInfo.rebase_off > FileSize)
647     return malformedError("rebase_off field of " + Twine(CmdName) +
648                           " command " + Twine(LoadCommandIndex) + " extends "
649                           "past the end of the file");
650   uint64_t BigSize = DyldInfo.rebase_off;
651   BigSize += DyldInfo.rebase_size;
652   if (BigSize > FileSize)
653     return malformedError("rebase_off field plus rebase_size field of " +
654                           Twine(CmdName) + " command " +
655                           Twine(LoadCommandIndex) + " extends past the end of "
656                           "the file");
657   if (Error Err = checkOverlappingElement(Elements, DyldInfo.rebase_off,
658                                           DyldInfo.rebase_size,
659                                           "dyld rebase info"))
660     return Err;
661   if (DyldInfo.bind_off > FileSize)
662     return malformedError("bind_off field of " + Twine(CmdName) +
663                           " command " + Twine(LoadCommandIndex) + " extends "
664                           "past the end of the file");
665   BigSize = DyldInfo.bind_off;
666   BigSize += DyldInfo.bind_size;
667   if (BigSize > FileSize)
668     return malformedError("bind_off field plus bind_size field of " +
669                           Twine(CmdName) + " command " +
670                           Twine(LoadCommandIndex) + " extends past the end of "
671                           "the file");
672   if (Error Err = checkOverlappingElement(Elements, DyldInfo.bind_off,
673                                           DyldInfo.bind_size,
674                                           "dyld bind info"))
675     return Err;
676   if (DyldInfo.weak_bind_off > FileSize)
677     return malformedError("weak_bind_off field of " + Twine(CmdName) +
678                           " command " + Twine(LoadCommandIndex) + " extends "
679                           "past the end of the file");
680   BigSize = DyldInfo.weak_bind_off;
681   BigSize += DyldInfo.weak_bind_size;
682   if (BigSize > FileSize)
683     return malformedError("weak_bind_off field plus weak_bind_size field of " +
684                           Twine(CmdName) + " command " +
685                           Twine(LoadCommandIndex) + " extends past the end of "
686                           "the file");
687   if (Error Err = checkOverlappingElement(Elements, DyldInfo.weak_bind_off,
688                                           DyldInfo.weak_bind_size,
689                                           "dyld weak bind info"))
690     return Err;
691   if (DyldInfo.lazy_bind_off > FileSize)
692     return malformedError("lazy_bind_off field of " + Twine(CmdName) +
693                           " command " + Twine(LoadCommandIndex) + " extends "
694                           "past the end of the file");
695   BigSize = DyldInfo.lazy_bind_off;
696   BigSize += DyldInfo.lazy_bind_size;
697   if (BigSize > FileSize)
698     return malformedError("lazy_bind_off field plus lazy_bind_size field of " +
699                           Twine(CmdName) + " command " +
700                           Twine(LoadCommandIndex) + " extends past the end of "
701                           "the file");
702   if (Error Err = checkOverlappingElement(Elements, DyldInfo.lazy_bind_off,
703                                           DyldInfo.lazy_bind_size,
704                                           "dyld lazy bind info"))
705     return Err;
706   if (DyldInfo.export_off > FileSize)
707     return malformedError("export_off field of " + Twine(CmdName) +
708                           " command " + Twine(LoadCommandIndex) + " extends "
709                           "past the end of the file");
710   BigSize = DyldInfo.export_off;
711   BigSize += DyldInfo.export_size;
712   if (BigSize > FileSize)
713     return malformedError("export_off field plus export_size field of " +
714                           Twine(CmdName) + " command " +
715                           Twine(LoadCommandIndex) + " extends past the end of "
716                           "the file");
717   if (Error Err = checkOverlappingElement(Elements, DyldInfo.export_off,
718                                           DyldInfo.export_size,
719                                           "dyld export info"))
720     return Err;
721   *LoadCmd = Load.Ptr;
722   return Error::success();
723 }
724 
725 static Error checkDylibCommand(const MachOObjectFile &Obj,
726                                const MachOObjectFile::LoadCommandInfo &Load,
727                                uint32_t LoadCommandIndex, const char *CmdName) {
728   if (Load.C.cmdsize < sizeof(MachO::dylib_command))
729     return malformedError("load command " + Twine(LoadCommandIndex) + " " +
730                           CmdName + " cmdsize too small");
731   auto CommandOrErr = getStructOrErr<MachO::dylib_command>(Obj, Load.Ptr);
732   if (!CommandOrErr)
733     return CommandOrErr.takeError();
734   MachO::dylib_command D = CommandOrErr.get();
735   if (D.dylib.name < sizeof(MachO::dylib_command))
736     return malformedError("load command " + Twine(LoadCommandIndex) + " " +
737                           CmdName + " name.offset field too small, not past "
738                           "the end of the dylib_command struct");
739   if (D.dylib.name >= D.cmdsize)
740     return malformedError("load command " + Twine(LoadCommandIndex) + " " +
741                           CmdName + " name.offset field extends past the end "
742                           "of the load command");
743   // Make sure there is a null between the starting offset of the name and
744   // the end of the load command.
745   uint32_t i;
746   const char *P = (const char *)Load.Ptr;
747   for (i = D.dylib.name; i < D.cmdsize; i++)
748     if (P[i] == '\0')
749       break;
750   if (i >= D.cmdsize)
751     return malformedError("load command " + Twine(LoadCommandIndex) + " " +
752                           CmdName + " library name extends past the end of the "
753                           "load command");
754   return Error::success();
755 }
756 
757 static Error checkDylibIdCommand(const MachOObjectFile &Obj,
758                                  const MachOObjectFile::LoadCommandInfo &Load,
759                                  uint32_t LoadCommandIndex,
760                                  const char **LoadCmd) {
761   if (Error Err = checkDylibCommand(Obj, Load, LoadCommandIndex,
762                                      "LC_ID_DYLIB"))
763     return Err;
764   if (*LoadCmd != nullptr)
765     return malformedError("more than one LC_ID_DYLIB command");
766   if (Obj.getHeader().filetype != MachO::MH_DYLIB &&
767       Obj.getHeader().filetype != MachO::MH_DYLIB_STUB)
768     return malformedError("LC_ID_DYLIB load command in non-dynamic library "
769                           "file type");
770   *LoadCmd = Load.Ptr;
771   return Error::success();
772 }
773 
774 static Error checkDyldCommand(const MachOObjectFile &Obj,
775                               const MachOObjectFile::LoadCommandInfo &Load,
776                               uint32_t LoadCommandIndex, const char *CmdName) {
777   if (Load.C.cmdsize < sizeof(MachO::dylinker_command))
778     return malformedError("load command " + Twine(LoadCommandIndex) + " " +
779                           CmdName + " cmdsize too small");
780   auto CommandOrErr = getStructOrErr<MachO::dylinker_command>(Obj, Load.Ptr);
781   if (!CommandOrErr)
782     return CommandOrErr.takeError();
783   MachO::dylinker_command D = CommandOrErr.get();
784   if (D.name < sizeof(MachO::dylinker_command))
785     return malformedError("load command " + Twine(LoadCommandIndex) + " " +
786                           CmdName + " name.offset field too small, not past "
787                           "the end of the dylinker_command struct");
788   if (D.name >= D.cmdsize)
789     return malformedError("load command " + Twine(LoadCommandIndex) + " " +
790                           CmdName + " name.offset field extends past the end "
791                           "of the load command");
792   // Make sure there is a null between the starting offset of the name and
793   // the end of the load command.
794   uint32_t i;
795   const char *P = (const char *)Load.Ptr;
796   for (i = D.name; i < D.cmdsize; i++)
797     if (P[i] == '\0')
798       break;
799   if (i >= D.cmdsize)
800     return malformedError("load command " + Twine(LoadCommandIndex) + " " +
801                           CmdName + " dyld name extends past the end of the "
802                           "load command");
803   return Error::success();
804 }
805 
806 static Error checkVersCommand(const MachOObjectFile &Obj,
807                               const MachOObjectFile::LoadCommandInfo &Load,
808                               uint32_t LoadCommandIndex,
809                               const char **LoadCmd, const char *CmdName) {
810   if (Load.C.cmdsize != sizeof(MachO::version_min_command))
811     return malformedError("load command " + Twine(LoadCommandIndex) + " " +
812                           CmdName + " has incorrect cmdsize");
813   if (*LoadCmd != nullptr)
814     return malformedError("more than one LC_VERSION_MIN_MACOSX, "
815                           "LC_VERSION_MIN_IPHONEOS, LC_VERSION_MIN_TVOS or "
816                           "LC_VERSION_MIN_WATCHOS command");
817   *LoadCmd = Load.Ptr;
818   return Error::success();
819 }
820 
821 static Error checkNoteCommand(const MachOObjectFile &Obj,
822                               const MachOObjectFile::LoadCommandInfo &Load,
823                               uint32_t LoadCommandIndex,
824                               std::list<MachOElement> &Elements) {
825   if (Load.C.cmdsize != sizeof(MachO::note_command))
826     return malformedError("load command " + Twine(LoadCommandIndex) +
827                           " LC_NOTE has incorrect cmdsize");
828   auto NoteCmdOrErr = getStructOrErr<MachO::note_command>(Obj, Load.Ptr);
829   if (!NoteCmdOrErr)
830     return NoteCmdOrErr.takeError();
831   MachO::note_command Nt = NoteCmdOrErr.get();
832   uint64_t FileSize = Obj.getData().size();
833   if (Nt.offset > FileSize)
834     return malformedError("offset field of LC_NOTE command " +
835                           Twine(LoadCommandIndex) + " extends "
836                           "past the end of the file");
837   uint64_t BigSize = Nt.offset;
838   BigSize += Nt.size;
839   if (BigSize > FileSize)
840     return malformedError("size field plus offset field of LC_NOTE command " +
841                           Twine(LoadCommandIndex) + " extends past the end of "
842                           "the file");
843   if (Error Err = checkOverlappingElement(Elements, Nt.offset, Nt.size,
844                                           "LC_NOTE data"))
845     return Err;
846   return Error::success();
847 }
848 
849 static Error
850 parseBuildVersionCommand(const MachOObjectFile &Obj,
851                          const MachOObjectFile::LoadCommandInfo &Load,
852                          SmallVectorImpl<const char*> &BuildTools,
853                          uint32_t LoadCommandIndex) {
854   auto BVCOrErr =
855     getStructOrErr<MachO::build_version_command>(Obj, Load.Ptr);
856   if (!BVCOrErr)
857     return BVCOrErr.takeError();
858   MachO::build_version_command BVC = BVCOrErr.get();
859   if (Load.C.cmdsize !=
860       sizeof(MachO::build_version_command) +
861           BVC.ntools * sizeof(MachO::build_tool_version))
862     return malformedError("load command " + Twine(LoadCommandIndex) +
863                           " LC_BUILD_VERSION_COMMAND has incorrect cmdsize");
864 
865   auto Start = Load.Ptr + sizeof(MachO::build_version_command);
866   BuildTools.resize(BVC.ntools);
867   for (unsigned i = 0; i < BVC.ntools; ++i)
868     BuildTools[i] = Start + i * sizeof(MachO::build_tool_version);
869 
870   return Error::success();
871 }
872 
873 static Error checkRpathCommand(const MachOObjectFile &Obj,
874                                const MachOObjectFile::LoadCommandInfo &Load,
875                                uint32_t LoadCommandIndex) {
876   if (Load.C.cmdsize < sizeof(MachO::rpath_command))
877     return malformedError("load command " + Twine(LoadCommandIndex) +
878                           " LC_RPATH cmdsize too small");
879   auto ROrErr = getStructOrErr<MachO::rpath_command>(Obj, Load.Ptr);
880   if (!ROrErr)
881     return ROrErr.takeError();
882   MachO::rpath_command R = ROrErr.get();
883   if (R.path < sizeof(MachO::rpath_command))
884     return malformedError("load command " + Twine(LoadCommandIndex) +
885                           " LC_RPATH path.offset field too small, not past "
886                           "the end of the rpath_command struct");
887   if (R.path >= R.cmdsize)
888     return malformedError("load command " + Twine(LoadCommandIndex) +
889                           " LC_RPATH path.offset field extends past the end "
890                           "of the load command");
891   // Make sure there is a null between the starting offset of the path and
892   // the end of the load command.
893   uint32_t i;
894   const char *P = (const char *)Load.Ptr;
895   for (i = R.path; i < R.cmdsize; i++)
896     if (P[i] == '\0')
897       break;
898   if (i >= R.cmdsize)
899     return malformedError("load command " + Twine(LoadCommandIndex) +
900                           " LC_RPATH library name extends past the end of the "
901                           "load command");
902   return Error::success();
903 }
904 
905 static Error checkEncryptCommand(const MachOObjectFile &Obj,
906                                  const MachOObjectFile::LoadCommandInfo &Load,
907                                  uint32_t LoadCommandIndex,
908                                  uint64_t cryptoff, uint64_t cryptsize,
909                                  const char **LoadCmd, const char *CmdName) {
910   if (*LoadCmd != nullptr)
911     return malformedError("more than one LC_ENCRYPTION_INFO and or "
912                           "LC_ENCRYPTION_INFO_64 command");
913   uint64_t FileSize = Obj.getData().size();
914   if (cryptoff > FileSize)
915     return malformedError("cryptoff field of " + Twine(CmdName) +
916                           " command " + Twine(LoadCommandIndex) + " extends "
917                           "past the end of the file");
918   uint64_t BigSize = cryptoff;
919   BigSize += cryptsize;
920   if (BigSize > FileSize)
921     return malformedError("cryptoff field plus cryptsize field of " +
922                           Twine(CmdName) + " command " +
923                           Twine(LoadCommandIndex) + " extends past the end of "
924                           "the file");
925   *LoadCmd = Load.Ptr;
926   return Error::success();
927 }
928 
929 static Error checkLinkerOptCommand(const MachOObjectFile &Obj,
930                                    const MachOObjectFile::LoadCommandInfo &Load,
931                                    uint32_t LoadCommandIndex) {
932   if (Load.C.cmdsize < sizeof(MachO::linker_option_command))
933     return malformedError("load command " + Twine(LoadCommandIndex) +
934                           " LC_LINKER_OPTION cmdsize too small");
935   auto LinkOptionOrErr =
936     getStructOrErr<MachO::linker_option_command>(Obj, Load.Ptr);
937   if (!LinkOptionOrErr)
938     return LinkOptionOrErr.takeError();
939   MachO::linker_option_command L = LinkOptionOrErr.get();
940   // Make sure the count of strings is correct.
941   const char *string = (const char *)Load.Ptr +
942                        sizeof(struct MachO::linker_option_command);
943   uint32_t left = L.cmdsize - sizeof(struct MachO::linker_option_command);
944   uint32_t i = 0;
945   while (left > 0) {
946     while (*string == '\0' && left > 0) {
947       string++;
948       left--;
949     }
950     if (left > 0) {
951       i++;
952       uint32_t NullPos = StringRef(string, left).find('\0');
953       if (0xffffffff == NullPos)
954         return malformedError("load command " + Twine(LoadCommandIndex) +
955                               " LC_LINKER_OPTION string #" + Twine(i) +
956                               " is not NULL terminated");
957       uint32_t len = std::min(NullPos, left) + 1;
958       string += len;
959       left -= len;
960     }
961   }
962   if (L.count != i)
963     return malformedError("load command " + Twine(LoadCommandIndex) +
964                           " LC_LINKER_OPTION string count " + Twine(L.count) +
965                           " does not match number of strings");
966   return Error::success();
967 }
968 
969 static Error checkSubCommand(const MachOObjectFile &Obj,
970                              const MachOObjectFile::LoadCommandInfo &Load,
971                              uint32_t LoadCommandIndex, const char *CmdName,
972                              size_t SizeOfCmd, const char *CmdStructName,
973                              uint32_t PathOffset, const char *PathFieldName) {
974   if (PathOffset < SizeOfCmd)
975     return malformedError("load command " + Twine(LoadCommandIndex) + " " +
976                           CmdName + " " + PathFieldName + ".offset field too "
977                           "small, not past the end of the " + CmdStructName);
978   if (PathOffset >= Load.C.cmdsize)
979     return malformedError("load command " + Twine(LoadCommandIndex) + " " +
980                           CmdName + " " + PathFieldName + ".offset field "
981                           "extends past the end of the load command");
982   // Make sure there is a null between the starting offset of the path and
983   // the end of the load command.
984   uint32_t i;
985   const char *P = (const char *)Load.Ptr;
986   for (i = PathOffset; i < Load.C.cmdsize; i++)
987     if (P[i] == '\0')
988       break;
989   if (i >= Load.C.cmdsize)
990     return malformedError("load command " + Twine(LoadCommandIndex) + " " +
991                           CmdName + " " + PathFieldName + " name extends past "
992                           "the end of the load command");
993   return Error::success();
994 }
995 
996 static Error checkThreadCommand(const MachOObjectFile &Obj,
997                                 const MachOObjectFile::LoadCommandInfo &Load,
998                                 uint32_t LoadCommandIndex,
999                                 const char *CmdName) {
1000   if (Load.C.cmdsize < sizeof(MachO::thread_command))
1001     return malformedError("load command " + Twine(LoadCommandIndex) +
1002                           CmdName + " cmdsize too small");
1003   auto ThreadCommandOrErr =
1004     getStructOrErr<MachO::thread_command>(Obj, Load.Ptr);
1005   if (!ThreadCommandOrErr)
1006     return ThreadCommandOrErr.takeError();
1007   MachO::thread_command T = ThreadCommandOrErr.get();
1008   const char *state = Load.Ptr + sizeof(MachO::thread_command);
1009   const char *end = Load.Ptr + T.cmdsize;
1010   uint32_t nflavor = 0;
1011   uint32_t cputype = getCPUType(Obj);
1012   while (state < end) {
1013     if(state + sizeof(uint32_t) > end)
1014       return malformedError("load command " + Twine(LoadCommandIndex) +
1015                             "flavor in " + CmdName + " extends past end of "
1016                             "command");
1017     uint32_t flavor;
1018     memcpy(&flavor, state, sizeof(uint32_t));
1019     if (Obj.isLittleEndian() != sys::IsLittleEndianHost)
1020       sys::swapByteOrder(flavor);
1021     state += sizeof(uint32_t);
1022 
1023     if(state + sizeof(uint32_t) > end)
1024       return malformedError("load command " + Twine(LoadCommandIndex) +
1025                             " count in " + CmdName + " extends past end of "
1026                             "command");
1027     uint32_t count;
1028     memcpy(&count, state, sizeof(uint32_t));
1029     if (Obj.isLittleEndian() != sys::IsLittleEndianHost)
1030       sys::swapByteOrder(count);
1031     state += sizeof(uint32_t);
1032 
1033     if (cputype == MachO::CPU_TYPE_I386) {
1034       if (flavor == MachO::x86_THREAD_STATE32) {
1035         if (count != MachO::x86_THREAD_STATE32_COUNT)
1036           return malformedError("load command " + Twine(LoadCommandIndex) +
1037                                 " count not x86_THREAD_STATE32_COUNT for "
1038                                 "flavor number " + Twine(nflavor) + " which is "
1039                                 "a x86_THREAD_STATE32 flavor in " + CmdName +
1040                                 " command");
1041         if (state + sizeof(MachO::x86_thread_state32_t) > end)
1042           return malformedError("load command " + Twine(LoadCommandIndex) +
1043                                 " x86_THREAD_STATE32 extends past end of "
1044                                 "command in " + CmdName + " command");
1045         state += sizeof(MachO::x86_thread_state32_t);
1046       } else {
1047         return malformedError("load command " + Twine(LoadCommandIndex) +
1048                               " unknown flavor (" + Twine(flavor) + ") for "
1049                               "flavor number " + Twine(nflavor) + " in " +
1050                               CmdName + " command");
1051       }
1052     } else if (cputype == MachO::CPU_TYPE_X86_64) {
1053       if (flavor == MachO::x86_THREAD_STATE) {
1054         if (count != MachO::x86_THREAD_STATE_COUNT)
1055           return malformedError("load command " + Twine(LoadCommandIndex) +
1056                                 " count not x86_THREAD_STATE_COUNT for "
1057                                 "flavor number " + Twine(nflavor) + " which is "
1058                                 "a x86_THREAD_STATE flavor in " + CmdName +
1059                                 " command");
1060         if (state + sizeof(MachO::x86_thread_state_t) > end)
1061           return malformedError("load command " + Twine(LoadCommandIndex) +
1062                                 " x86_THREAD_STATE extends past end of "
1063                                 "command in " + CmdName + " command");
1064         state += sizeof(MachO::x86_thread_state_t);
1065       } else if (flavor == MachO::x86_FLOAT_STATE) {
1066         if (count != MachO::x86_FLOAT_STATE_COUNT)
1067           return malformedError("load command " + Twine(LoadCommandIndex) +
1068                                 " count not x86_FLOAT_STATE_COUNT for "
1069                                 "flavor number " + Twine(nflavor) + " which is "
1070                                 "a x86_FLOAT_STATE flavor in " + CmdName +
1071                                 " command");
1072         if (state + sizeof(MachO::x86_float_state_t) > end)
1073           return malformedError("load command " + Twine(LoadCommandIndex) +
1074                                 " x86_FLOAT_STATE extends past end of "
1075                                 "command in " + CmdName + " command");
1076         state += sizeof(MachO::x86_float_state_t);
1077       } else if (flavor == MachO::x86_EXCEPTION_STATE) {
1078         if (count != MachO::x86_EXCEPTION_STATE_COUNT)
1079           return malformedError("load command " + Twine(LoadCommandIndex) +
1080                                 " count not x86_EXCEPTION_STATE_COUNT for "
1081                                 "flavor number " + Twine(nflavor) + " which is "
1082                                 "a x86_EXCEPTION_STATE flavor in " + CmdName +
1083                                 " command");
1084         if (state + sizeof(MachO::x86_exception_state_t) > end)
1085           return malformedError("load command " + Twine(LoadCommandIndex) +
1086                                 " x86_EXCEPTION_STATE extends past end of "
1087                                 "command in " + CmdName + " command");
1088         state += sizeof(MachO::x86_exception_state_t);
1089       } else if (flavor == MachO::x86_THREAD_STATE64) {
1090         if (count != MachO::x86_THREAD_STATE64_COUNT)
1091           return malformedError("load command " + Twine(LoadCommandIndex) +
1092                                 " count not x86_THREAD_STATE64_COUNT for "
1093                                 "flavor number " + Twine(nflavor) + " which is "
1094                                 "a x86_THREAD_STATE64 flavor in " + CmdName +
1095                                 " command");
1096         if (state + sizeof(MachO::x86_thread_state64_t) > end)
1097           return malformedError("load command " + Twine(LoadCommandIndex) +
1098                                 " x86_THREAD_STATE64 extends past end of "
1099                                 "command in " + CmdName + " command");
1100         state += sizeof(MachO::x86_thread_state64_t);
1101       } else if (flavor == MachO::x86_EXCEPTION_STATE64) {
1102         if (count != MachO::x86_EXCEPTION_STATE64_COUNT)
1103           return malformedError("load command " + Twine(LoadCommandIndex) +
1104                                 " count not x86_EXCEPTION_STATE64_COUNT for "
1105                                 "flavor number " + Twine(nflavor) + " which is "
1106                                 "a x86_EXCEPTION_STATE64 flavor in " + CmdName +
1107                                 " command");
1108         if (state + sizeof(MachO::x86_exception_state64_t) > end)
1109           return malformedError("load command " + Twine(LoadCommandIndex) +
1110                                 " x86_EXCEPTION_STATE64 extends past end of "
1111                                 "command in " + CmdName + " command");
1112         state += sizeof(MachO::x86_exception_state64_t);
1113       } else {
1114         return malformedError("load command " + Twine(LoadCommandIndex) +
1115                               " unknown flavor (" + Twine(flavor) + ") for "
1116                               "flavor number " + Twine(nflavor) + " in " +
1117                               CmdName + " command");
1118       }
1119     } else if (cputype == MachO::CPU_TYPE_ARM) {
1120       if (flavor == MachO::ARM_THREAD_STATE) {
1121         if (count != MachO::ARM_THREAD_STATE_COUNT)
1122           return malformedError("load command " + Twine(LoadCommandIndex) +
1123                                 " count not ARM_THREAD_STATE_COUNT for "
1124                                 "flavor number " + Twine(nflavor) + " which is "
1125                                 "a ARM_THREAD_STATE flavor in " + CmdName +
1126                                 " command");
1127         if (state + sizeof(MachO::arm_thread_state32_t) > end)
1128           return malformedError("load command " + Twine(LoadCommandIndex) +
1129                                 " ARM_THREAD_STATE extends past end of "
1130                                 "command in " + CmdName + " command");
1131         state += sizeof(MachO::arm_thread_state32_t);
1132       } else {
1133         return malformedError("load command " + Twine(LoadCommandIndex) +
1134                               " unknown flavor (" + Twine(flavor) + ") for "
1135                               "flavor number " + Twine(nflavor) + " in " +
1136                               CmdName + " command");
1137       }
1138     } else if (cputype == MachO::CPU_TYPE_ARM64 ||
1139                cputype == MachO::CPU_TYPE_ARM64_32) {
1140       if (flavor == MachO::ARM_THREAD_STATE64) {
1141         if (count != MachO::ARM_THREAD_STATE64_COUNT)
1142           return malformedError("load command " + Twine(LoadCommandIndex) +
1143                                 " count not ARM_THREAD_STATE64_COUNT for "
1144                                 "flavor number " + Twine(nflavor) + " which is "
1145                                 "a ARM_THREAD_STATE64 flavor in " + CmdName +
1146                                 " command");
1147         if (state + sizeof(MachO::arm_thread_state64_t) > end)
1148           return malformedError("load command " + Twine(LoadCommandIndex) +
1149                                 " ARM_THREAD_STATE64 extends past end of "
1150                                 "command in " + CmdName + " command");
1151         state += sizeof(MachO::arm_thread_state64_t);
1152       } else {
1153         return malformedError("load command " + Twine(LoadCommandIndex) +
1154                               " unknown flavor (" + Twine(flavor) + ") for "
1155                               "flavor number " + Twine(nflavor) + " in " +
1156                               CmdName + " command");
1157       }
1158     } else if (cputype == MachO::CPU_TYPE_POWERPC) {
1159       if (flavor == MachO::PPC_THREAD_STATE) {
1160         if (count != MachO::PPC_THREAD_STATE_COUNT)
1161           return malformedError("load command " + Twine(LoadCommandIndex) +
1162                                 " count not PPC_THREAD_STATE_COUNT for "
1163                                 "flavor number " + Twine(nflavor) + " which is "
1164                                 "a PPC_THREAD_STATE flavor in " + CmdName +
1165                                 " command");
1166         if (state + sizeof(MachO::ppc_thread_state32_t) > end)
1167           return malformedError("load command " + Twine(LoadCommandIndex) +
1168                                 " PPC_THREAD_STATE extends past end of "
1169                                 "command in " + CmdName + " command");
1170         state += sizeof(MachO::ppc_thread_state32_t);
1171       } else {
1172         return malformedError("load command " + Twine(LoadCommandIndex) +
1173                               " unknown flavor (" + Twine(flavor) + ") for "
1174                               "flavor number " + Twine(nflavor) + " in " +
1175                               CmdName + " command");
1176       }
1177     } else {
1178       return malformedError("unknown cputype (" + Twine(cputype) + ") load "
1179                             "command " + Twine(LoadCommandIndex) + " for " +
1180                             CmdName + " command can't be checked");
1181     }
1182     nflavor++;
1183   }
1184   return Error::success();
1185 }
1186 
1187 static Error checkTwoLevelHintsCommand(const MachOObjectFile &Obj,
1188                                        const MachOObjectFile::LoadCommandInfo
1189                                          &Load,
1190                                        uint32_t LoadCommandIndex,
1191                                        const char **LoadCmd,
1192                                        std::list<MachOElement> &Elements) {
1193   if (Load.C.cmdsize != sizeof(MachO::twolevel_hints_command))
1194     return malformedError("load command " + Twine(LoadCommandIndex) +
1195                           " LC_TWOLEVEL_HINTS has incorrect cmdsize");
1196   if (*LoadCmd != nullptr)
1197     return malformedError("more than one LC_TWOLEVEL_HINTS command");
1198   auto HintsOrErr = getStructOrErr<MachO::twolevel_hints_command>(Obj, Load.Ptr);
1199   if(!HintsOrErr)
1200     return HintsOrErr.takeError();
1201   MachO::twolevel_hints_command Hints = HintsOrErr.get();
1202   uint64_t FileSize = Obj.getData().size();
1203   if (Hints.offset > FileSize)
1204     return malformedError("offset field of LC_TWOLEVEL_HINTS command " +
1205                           Twine(LoadCommandIndex) + " extends past the end of "
1206                           "the file");
1207   uint64_t BigSize = Hints.nhints;
1208   BigSize *= sizeof(MachO::twolevel_hint);
1209   BigSize += Hints.offset;
1210   if (BigSize > FileSize)
1211     return malformedError("offset field plus nhints times sizeof(struct "
1212                           "twolevel_hint) field of LC_TWOLEVEL_HINTS command " +
1213                           Twine(LoadCommandIndex) + " extends past the end of "
1214                           "the file");
1215   if (Error Err = checkOverlappingElement(Elements, Hints.offset, Hints.nhints *
1216                                           sizeof(MachO::twolevel_hint),
1217                                           "two level hints"))
1218     return Err;
1219   *LoadCmd = Load.Ptr;
1220   return Error::success();
1221 }
1222 
1223 // Returns true if the libObject code does not support the load command and its
1224 // contents.  The cmd value it is treated as an unknown load command but with
1225 // an error message that says the cmd value is obsolete.
1226 static bool isLoadCommandObsolete(uint32_t cmd) {
1227   if (cmd == MachO::LC_SYMSEG ||
1228       cmd == MachO::LC_LOADFVMLIB ||
1229       cmd == MachO::LC_IDFVMLIB ||
1230       cmd == MachO::LC_IDENT ||
1231       cmd == MachO::LC_FVMFILE ||
1232       cmd == MachO::LC_PREPAGE ||
1233       cmd == MachO::LC_PREBOUND_DYLIB ||
1234       cmd == MachO::LC_TWOLEVEL_HINTS ||
1235       cmd == MachO::LC_PREBIND_CKSUM)
1236     return true;
1237   return false;
1238 }
1239 
1240 Expected<std::unique_ptr<MachOObjectFile>>
1241 MachOObjectFile::create(MemoryBufferRef Object, bool IsLittleEndian,
1242                         bool Is64Bits, uint32_t UniversalCputype,
1243                         uint32_t UniversalIndex) {
1244   Error Err = Error::success();
1245   std::unique_ptr<MachOObjectFile> Obj(
1246       new MachOObjectFile(std::move(Object), IsLittleEndian,
1247                           Is64Bits, Err, UniversalCputype,
1248                           UniversalIndex));
1249   if (Err)
1250     return std::move(Err);
1251   return std::move(Obj);
1252 }
1253 
1254 MachOObjectFile::MachOObjectFile(MemoryBufferRef Object, bool IsLittleEndian,
1255                                  bool Is64bits, Error &Err,
1256                                  uint32_t UniversalCputype,
1257                                  uint32_t UniversalIndex)
1258     : ObjectFile(getMachOType(IsLittleEndian, Is64bits), Object) {
1259   ErrorAsOutParameter ErrAsOutParam(&Err);
1260   uint64_t SizeOfHeaders;
1261   uint32_t cputype;
1262   if (is64Bit()) {
1263     parseHeader(*this, Header64, Err);
1264     SizeOfHeaders = sizeof(MachO::mach_header_64);
1265     cputype = Header64.cputype;
1266   } else {
1267     parseHeader(*this, Header, Err);
1268     SizeOfHeaders = sizeof(MachO::mach_header);
1269     cputype = Header.cputype;
1270   }
1271   if (Err)
1272     return;
1273   SizeOfHeaders += getHeader().sizeofcmds;
1274   if (getData().data() + SizeOfHeaders > getData().end()) {
1275     Err = malformedError("load commands extend past the end of the file");
1276     return;
1277   }
1278   if (UniversalCputype != 0 && cputype != UniversalCputype) {
1279     Err = malformedError("universal header architecture: " +
1280                          Twine(UniversalIndex) + "'s cputype does not match "
1281                          "object file's mach header");
1282     return;
1283   }
1284   std::list<MachOElement> Elements;
1285   Elements.push_back({0, SizeOfHeaders, "Mach-O headers"});
1286 
1287   uint32_t LoadCommandCount = getHeader().ncmds;
1288   LoadCommandInfo Load;
1289   if (LoadCommandCount != 0) {
1290     if (auto LoadOrErr = getFirstLoadCommandInfo(*this))
1291       Load = *LoadOrErr;
1292     else {
1293       Err = LoadOrErr.takeError();
1294       return;
1295     }
1296   }
1297 
1298   const char *DyldIdLoadCmd = nullptr;
1299   const char *FuncStartsLoadCmd = nullptr;
1300   const char *SplitInfoLoadCmd = nullptr;
1301   const char *CodeSignDrsLoadCmd = nullptr;
1302   const char *CodeSignLoadCmd = nullptr;
1303   const char *VersLoadCmd = nullptr;
1304   const char *SourceLoadCmd = nullptr;
1305   const char *EntryPointLoadCmd = nullptr;
1306   const char *EncryptLoadCmd = nullptr;
1307   const char *RoutinesLoadCmd = nullptr;
1308   const char *UnixThreadLoadCmd = nullptr;
1309   const char *TwoLevelHintsLoadCmd = nullptr;
1310   for (unsigned I = 0; I < LoadCommandCount; ++I) {
1311     if (is64Bit()) {
1312       if (Load.C.cmdsize % 8 != 0) {
1313         // We have a hack here to allow 64-bit Mach-O core files to have
1314         // LC_THREAD commands that are only a multiple of 4 and not 8 to be
1315         // allowed since the macOS kernel produces them.
1316         if (getHeader().filetype != MachO::MH_CORE ||
1317             Load.C.cmd != MachO::LC_THREAD || Load.C.cmdsize % 4) {
1318           Err = malformedError("load command " + Twine(I) + " cmdsize not a "
1319                                "multiple of 8");
1320           return;
1321         }
1322       }
1323     } else {
1324       if (Load.C.cmdsize % 4 != 0) {
1325         Err = malformedError("load command " + Twine(I) + " cmdsize not a "
1326                              "multiple of 4");
1327         return;
1328       }
1329     }
1330     LoadCommands.push_back(Load);
1331     if (Load.C.cmd == MachO::LC_SYMTAB) {
1332       if ((Err = checkSymtabCommand(*this, Load, I, &SymtabLoadCmd, Elements)))
1333         return;
1334     } else if (Load.C.cmd == MachO::LC_DYSYMTAB) {
1335       if ((Err = checkDysymtabCommand(*this, Load, I, &DysymtabLoadCmd,
1336                                       Elements)))
1337         return;
1338     } else if (Load.C.cmd == MachO::LC_DATA_IN_CODE) {
1339       if ((Err = checkLinkeditDataCommand(*this, Load, I, &DataInCodeLoadCmd,
1340                                           "LC_DATA_IN_CODE", Elements,
1341                                           "data in code info")))
1342         return;
1343     } else if (Load.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
1344       if ((Err = checkLinkeditDataCommand(*this, Load, I, &LinkOptHintsLoadCmd,
1345                                           "LC_LINKER_OPTIMIZATION_HINT",
1346                                           Elements, "linker optimization "
1347                                           "hints")))
1348         return;
1349     } else if (Load.C.cmd == MachO::LC_FUNCTION_STARTS) {
1350       if ((Err = checkLinkeditDataCommand(*this, Load, I, &FuncStartsLoadCmd,
1351                                           "LC_FUNCTION_STARTS", Elements,
1352                                           "function starts data")))
1353         return;
1354     } else if (Load.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO) {
1355       if ((Err = checkLinkeditDataCommand(*this, Load, I, &SplitInfoLoadCmd,
1356                                           "LC_SEGMENT_SPLIT_INFO", Elements,
1357                                           "split info data")))
1358         return;
1359     } else if (Load.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS) {
1360       if ((Err = checkLinkeditDataCommand(*this, Load, I, &CodeSignDrsLoadCmd,
1361                                           "LC_DYLIB_CODE_SIGN_DRS", Elements,
1362                                           "code signing RDs data")))
1363         return;
1364     } else if (Load.C.cmd == MachO::LC_CODE_SIGNATURE) {
1365       if ((Err = checkLinkeditDataCommand(*this, Load, I, &CodeSignLoadCmd,
1366                                           "LC_CODE_SIGNATURE", Elements,
1367                                           "code signature data")))
1368         return;
1369     } else if (Load.C.cmd == MachO::LC_DYLD_INFO) {
1370       if ((Err = checkDyldInfoCommand(*this, Load, I, &DyldInfoLoadCmd,
1371                                       "LC_DYLD_INFO", Elements)))
1372         return;
1373     } else if (Load.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
1374       if ((Err = checkDyldInfoCommand(*this, Load, I, &DyldInfoLoadCmd,
1375                                       "LC_DYLD_INFO_ONLY", Elements)))
1376         return;
1377     } else if (Load.C.cmd == MachO::LC_UUID) {
1378       if (Load.C.cmdsize != sizeof(MachO::uuid_command)) {
1379         Err = malformedError("LC_UUID command " + Twine(I) + " has incorrect "
1380                              "cmdsize");
1381         return;
1382       }
1383       if (UuidLoadCmd) {
1384         Err = malformedError("more than one LC_UUID command");
1385         return;
1386       }
1387       UuidLoadCmd = Load.Ptr;
1388     } else if (Load.C.cmd == MachO::LC_SEGMENT_64) {
1389       if ((Err = parseSegmentLoadCommand<MachO::segment_command_64,
1390                                          MachO::section_64>(
1391                    *this, Load, Sections, HasPageZeroSegment, I,
1392                    "LC_SEGMENT_64", SizeOfHeaders, Elements)))
1393         return;
1394     } else if (Load.C.cmd == MachO::LC_SEGMENT) {
1395       if ((Err = parseSegmentLoadCommand<MachO::segment_command,
1396                                          MachO::section>(
1397                    *this, Load, Sections, HasPageZeroSegment, I,
1398                    "LC_SEGMENT", SizeOfHeaders, Elements)))
1399         return;
1400     } else if (Load.C.cmd == MachO::LC_ID_DYLIB) {
1401       if ((Err = checkDylibIdCommand(*this, Load, I, &DyldIdLoadCmd)))
1402         return;
1403     } else if (Load.C.cmd == MachO::LC_LOAD_DYLIB) {
1404       if ((Err = checkDylibCommand(*this, Load, I, "LC_LOAD_DYLIB")))
1405         return;
1406       Libraries.push_back(Load.Ptr);
1407     } else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB) {
1408       if ((Err = checkDylibCommand(*this, Load, I, "LC_LOAD_WEAK_DYLIB")))
1409         return;
1410       Libraries.push_back(Load.Ptr);
1411     } else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB) {
1412       if ((Err = checkDylibCommand(*this, Load, I, "LC_LAZY_LOAD_DYLIB")))
1413         return;
1414       Libraries.push_back(Load.Ptr);
1415     } else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB) {
1416       if ((Err = checkDylibCommand(*this, Load, I, "LC_REEXPORT_DYLIB")))
1417         return;
1418       Libraries.push_back(Load.Ptr);
1419     } else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
1420       if ((Err = checkDylibCommand(*this, Load, I, "LC_LOAD_UPWARD_DYLIB")))
1421         return;
1422       Libraries.push_back(Load.Ptr);
1423     } else if (Load.C.cmd == MachO::LC_ID_DYLINKER) {
1424       if ((Err = checkDyldCommand(*this, Load, I, "LC_ID_DYLINKER")))
1425         return;
1426     } else if (Load.C.cmd == MachO::LC_LOAD_DYLINKER) {
1427       if ((Err = checkDyldCommand(*this, Load, I, "LC_LOAD_DYLINKER")))
1428         return;
1429     } else if (Load.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
1430       if ((Err = checkDyldCommand(*this, Load, I, "LC_DYLD_ENVIRONMENT")))
1431         return;
1432     } else if (Load.C.cmd == MachO::LC_VERSION_MIN_MACOSX) {
1433       if ((Err = checkVersCommand(*this, Load, I, &VersLoadCmd,
1434                                   "LC_VERSION_MIN_MACOSX")))
1435         return;
1436     } else if (Load.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS) {
1437       if ((Err = checkVersCommand(*this, Load, I, &VersLoadCmd,
1438                                   "LC_VERSION_MIN_IPHONEOS")))
1439         return;
1440     } else if (Load.C.cmd == MachO::LC_VERSION_MIN_TVOS) {
1441       if ((Err = checkVersCommand(*this, Load, I, &VersLoadCmd,
1442                                   "LC_VERSION_MIN_TVOS")))
1443         return;
1444     } else if (Load.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
1445       if ((Err = checkVersCommand(*this, Load, I, &VersLoadCmd,
1446                                   "LC_VERSION_MIN_WATCHOS")))
1447         return;
1448     } else if (Load.C.cmd == MachO::LC_NOTE) {
1449       if ((Err = checkNoteCommand(*this, Load, I, Elements)))
1450         return;
1451     } else if (Load.C.cmd == MachO::LC_BUILD_VERSION) {
1452       if ((Err = parseBuildVersionCommand(*this, Load, BuildTools, I)))
1453         return;
1454     } else if (Load.C.cmd == MachO::LC_RPATH) {
1455       if ((Err = checkRpathCommand(*this, Load, I)))
1456         return;
1457     } else if (Load.C.cmd == MachO::LC_SOURCE_VERSION) {
1458       if (Load.C.cmdsize != sizeof(MachO::source_version_command)) {
1459         Err = malformedError("LC_SOURCE_VERSION command " + Twine(I) +
1460                              " has incorrect cmdsize");
1461         return;
1462       }
1463       if (SourceLoadCmd) {
1464         Err = malformedError("more than one LC_SOURCE_VERSION command");
1465         return;
1466       }
1467       SourceLoadCmd = Load.Ptr;
1468     } else if (Load.C.cmd == MachO::LC_MAIN) {
1469       if (Load.C.cmdsize != sizeof(MachO::entry_point_command)) {
1470         Err = malformedError("LC_MAIN command " + Twine(I) +
1471                              " has incorrect cmdsize");
1472         return;
1473       }
1474       if (EntryPointLoadCmd) {
1475         Err = malformedError("more than one LC_MAIN command");
1476         return;
1477       }
1478       EntryPointLoadCmd = Load.Ptr;
1479     } else if (Load.C.cmd == MachO::LC_ENCRYPTION_INFO) {
1480       if (Load.C.cmdsize != sizeof(MachO::encryption_info_command)) {
1481         Err = malformedError("LC_ENCRYPTION_INFO command " + Twine(I) +
1482                              " has incorrect cmdsize");
1483         return;
1484       }
1485       MachO::encryption_info_command E =
1486         getStruct<MachO::encryption_info_command>(*this, Load.Ptr);
1487       if ((Err = checkEncryptCommand(*this, Load, I, E.cryptoff, E.cryptsize,
1488                                      &EncryptLoadCmd, "LC_ENCRYPTION_INFO")))
1489         return;
1490     } else if (Load.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
1491       if (Load.C.cmdsize != sizeof(MachO::encryption_info_command_64)) {
1492         Err = malformedError("LC_ENCRYPTION_INFO_64 command " + Twine(I) +
1493                              " has incorrect cmdsize");
1494         return;
1495       }
1496       MachO::encryption_info_command_64 E =
1497         getStruct<MachO::encryption_info_command_64>(*this, Load.Ptr);
1498       if ((Err = checkEncryptCommand(*this, Load, I, E.cryptoff, E.cryptsize,
1499                                      &EncryptLoadCmd, "LC_ENCRYPTION_INFO_64")))
1500         return;
1501     } else if (Load.C.cmd == MachO::LC_LINKER_OPTION) {
1502       if ((Err = checkLinkerOptCommand(*this, Load, I)))
1503         return;
1504     } else if (Load.C.cmd == MachO::LC_SUB_FRAMEWORK) {
1505       if (Load.C.cmdsize < sizeof(MachO::sub_framework_command)) {
1506         Err =  malformedError("load command " + Twine(I) +
1507                               " LC_SUB_FRAMEWORK cmdsize too small");
1508         return;
1509       }
1510       MachO::sub_framework_command S =
1511         getStruct<MachO::sub_framework_command>(*this, Load.Ptr);
1512       if ((Err = checkSubCommand(*this, Load, I, "LC_SUB_FRAMEWORK",
1513                                  sizeof(MachO::sub_framework_command),
1514                                  "sub_framework_command", S.umbrella,
1515                                  "umbrella")))
1516         return;
1517     } else if (Load.C.cmd == MachO::LC_SUB_UMBRELLA) {
1518       if (Load.C.cmdsize < sizeof(MachO::sub_umbrella_command)) {
1519         Err =  malformedError("load command " + Twine(I) +
1520                               " LC_SUB_UMBRELLA cmdsize too small");
1521         return;
1522       }
1523       MachO::sub_umbrella_command S =
1524         getStruct<MachO::sub_umbrella_command>(*this, Load.Ptr);
1525       if ((Err = checkSubCommand(*this, Load, I, "LC_SUB_UMBRELLA",
1526                                  sizeof(MachO::sub_umbrella_command),
1527                                  "sub_umbrella_command", S.sub_umbrella,
1528                                  "sub_umbrella")))
1529         return;
1530     } else if (Load.C.cmd == MachO::LC_SUB_LIBRARY) {
1531       if (Load.C.cmdsize < sizeof(MachO::sub_library_command)) {
1532         Err =  malformedError("load command " + Twine(I) +
1533                               " LC_SUB_LIBRARY cmdsize too small");
1534         return;
1535       }
1536       MachO::sub_library_command S =
1537         getStruct<MachO::sub_library_command>(*this, Load.Ptr);
1538       if ((Err = checkSubCommand(*this, Load, I, "LC_SUB_LIBRARY",
1539                                  sizeof(MachO::sub_library_command),
1540                                  "sub_library_command", S.sub_library,
1541                                  "sub_library")))
1542         return;
1543     } else if (Load.C.cmd == MachO::LC_SUB_CLIENT) {
1544       if (Load.C.cmdsize < sizeof(MachO::sub_client_command)) {
1545         Err =  malformedError("load command " + Twine(I) +
1546                               " LC_SUB_CLIENT cmdsize too small");
1547         return;
1548       }
1549       MachO::sub_client_command S =
1550         getStruct<MachO::sub_client_command>(*this, Load.Ptr);
1551       if ((Err = checkSubCommand(*this, Load, I, "LC_SUB_CLIENT",
1552                                  sizeof(MachO::sub_client_command),
1553                                  "sub_client_command", S.client, "client")))
1554         return;
1555     } else if (Load.C.cmd == MachO::LC_ROUTINES) {
1556       if (Load.C.cmdsize != sizeof(MachO::routines_command)) {
1557         Err = malformedError("LC_ROUTINES command " + Twine(I) +
1558                              " has incorrect cmdsize");
1559         return;
1560       }
1561       if (RoutinesLoadCmd) {
1562         Err = malformedError("more than one LC_ROUTINES and or LC_ROUTINES_64 "
1563                              "command");
1564         return;
1565       }
1566       RoutinesLoadCmd = Load.Ptr;
1567     } else if (Load.C.cmd == MachO::LC_ROUTINES_64) {
1568       if (Load.C.cmdsize != sizeof(MachO::routines_command_64)) {
1569         Err = malformedError("LC_ROUTINES_64 command " + Twine(I) +
1570                              " has incorrect cmdsize");
1571         return;
1572       }
1573       if (RoutinesLoadCmd) {
1574         Err = malformedError("more than one LC_ROUTINES_64 and or LC_ROUTINES "
1575                              "command");
1576         return;
1577       }
1578       RoutinesLoadCmd = Load.Ptr;
1579     } else if (Load.C.cmd == MachO::LC_UNIXTHREAD) {
1580       if ((Err = checkThreadCommand(*this, Load, I, "LC_UNIXTHREAD")))
1581         return;
1582       if (UnixThreadLoadCmd) {
1583         Err = malformedError("more than one LC_UNIXTHREAD command");
1584         return;
1585       }
1586       UnixThreadLoadCmd = Load.Ptr;
1587     } else if (Load.C.cmd == MachO::LC_THREAD) {
1588       if ((Err = checkThreadCommand(*this, Load, I, "LC_THREAD")))
1589         return;
1590     // Note: LC_TWOLEVEL_HINTS is really obsolete and is not supported.
1591     } else if (Load.C.cmd == MachO::LC_TWOLEVEL_HINTS) {
1592        if ((Err = checkTwoLevelHintsCommand(*this, Load, I,
1593                                             &TwoLevelHintsLoadCmd, Elements)))
1594          return;
1595     } else if (isLoadCommandObsolete(Load.C.cmd)) {
1596       Err = malformedError("load command " + Twine(I) + " for cmd value of: " +
1597                            Twine(Load.C.cmd) + " is obsolete and not "
1598                            "supported");
1599       return;
1600     }
1601     // TODO: generate a error for unknown load commands by default.  But still
1602     // need work out an approach to allow or not allow unknown values like this
1603     // as an option for some uses like lldb.
1604     if (I < LoadCommandCount - 1) {
1605       if (auto LoadOrErr = getNextLoadCommandInfo(*this, I, Load))
1606         Load = *LoadOrErr;
1607       else {
1608         Err = LoadOrErr.takeError();
1609         return;
1610       }
1611     }
1612   }
1613   if (!SymtabLoadCmd) {
1614     if (DysymtabLoadCmd) {
1615       Err = malformedError("contains LC_DYSYMTAB load command without a "
1616                            "LC_SYMTAB load command");
1617       return;
1618     }
1619   } else if (DysymtabLoadCmd) {
1620     MachO::symtab_command Symtab =
1621       getStruct<MachO::symtab_command>(*this, SymtabLoadCmd);
1622     MachO::dysymtab_command Dysymtab =
1623       getStruct<MachO::dysymtab_command>(*this, DysymtabLoadCmd);
1624     if (Dysymtab.nlocalsym != 0 && Dysymtab.ilocalsym > Symtab.nsyms) {
1625       Err = malformedError("ilocalsym in LC_DYSYMTAB load command "
1626                            "extends past the end of the symbol table");
1627       return;
1628     }
1629     uint64_t BigSize = Dysymtab.ilocalsym;
1630     BigSize += Dysymtab.nlocalsym;
1631     if (Dysymtab.nlocalsym != 0 && BigSize > Symtab.nsyms) {
1632       Err = malformedError("ilocalsym plus nlocalsym in LC_DYSYMTAB load "
1633                            "command extends past the end of the symbol table");
1634       return;
1635     }
1636     if (Dysymtab.nextdefsym != 0 && Dysymtab.iextdefsym > Symtab.nsyms) {
1637       Err = malformedError("iextdefsym in LC_DYSYMTAB load command "
1638                            "extends past the end of the symbol table");
1639       return;
1640     }
1641     BigSize = Dysymtab.iextdefsym;
1642     BigSize += Dysymtab.nextdefsym;
1643     if (Dysymtab.nextdefsym != 0 && BigSize > Symtab.nsyms) {
1644       Err = malformedError("iextdefsym plus nextdefsym in LC_DYSYMTAB "
1645                            "load command extends past the end of the symbol "
1646                            "table");
1647       return;
1648     }
1649     if (Dysymtab.nundefsym != 0 && Dysymtab.iundefsym > Symtab.nsyms) {
1650       Err = malformedError("iundefsym in LC_DYSYMTAB load command "
1651                            "extends past the end of the symbol table");
1652       return;
1653     }
1654     BigSize = Dysymtab.iundefsym;
1655     BigSize += Dysymtab.nundefsym;
1656     if (Dysymtab.nundefsym != 0 && BigSize > Symtab.nsyms) {
1657       Err = malformedError("iundefsym plus nundefsym in LC_DYSYMTAB load "
1658                            " command extends past the end of the symbol table");
1659       return;
1660     }
1661   }
1662   if ((getHeader().filetype == MachO::MH_DYLIB ||
1663        getHeader().filetype == MachO::MH_DYLIB_STUB) &&
1664        DyldIdLoadCmd == nullptr) {
1665     Err = malformedError("no LC_ID_DYLIB load command in dynamic library "
1666                          "filetype");
1667     return;
1668   }
1669   assert(LoadCommands.size() == LoadCommandCount);
1670 
1671   Err = Error::success();
1672 }
1673 
1674 Error MachOObjectFile::checkSymbolTable() const {
1675   uint32_t Flags = 0;
1676   if (is64Bit()) {
1677     MachO::mach_header_64 H_64 = MachOObjectFile::getHeader64();
1678     Flags = H_64.flags;
1679   } else {
1680     MachO::mach_header H = MachOObjectFile::getHeader();
1681     Flags = H.flags;
1682   }
1683   uint8_t NType = 0;
1684   uint8_t NSect = 0;
1685   uint16_t NDesc = 0;
1686   uint32_t NStrx = 0;
1687   uint64_t NValue = 0;
1688   uint32_t SymbolIndex = 0;
1689   MachO::symtab_command S = getSymtabLoadCommand();
1690   for (const SymbolRef &Symbol : symbols()) {
1691     DataRefImpl SymDRI = Symbol.getRawDataRefImpl();
1692     if (is64Bit()) {
1693       MachO::nlist_64 STE_64 = getSymbol64TableEntry(SymDRI);
1694       NType = STE_64.n_type;
1695       NSect = STE_64.n_sect;
1696       NDesc = STE_64.n_desc;
1697       NStrx = STE_64.n_strx;
1698       NValue = STE_64.n_value;
1699     } else {
1700       MachO::nlist STE = getSymbolTableEntry(SymDRI);
1701       NType = STE.n_type;
1702       NSect = STE.n_sect;
1703       NDesc = STE.n_desc;
1704       NStrx = STE.n_strx;
1705       NValue = STE.n_value;
1706     }
1707     if ((NType & MachO::N_STAB) == 0) {
1708       if ((NType & MachO::N_TYPE) == MachO::N_SECT) {
1709         if (NSect == 0 || NSect > Sections.size())
1710           return malformedError("bad section index: " + Twine((int)NSect) +
1711                                 " for symbol at index " + Twine(SymbolIndex));
1712       }
1713       if ((NType & MachO::N_TYPE) == MachO::N_INDR) {
1714         if (NValue >= S.strsize)
1715           return malformedError("bad n_value: " + Twine((int)NValue) + " past "
1716                                 "the end of string table, for N_INDR symbol at "
1717                                 "index " + Twine(SymbolIndex));
1718       }
1719       if ((Flags & MachO::MH_TWOLEVEL) == MachO::MH_TWOLEVEL &&
1720           (((NType & MachO::N_TYPE) == MachO::N_UNDF && NValue == 0) ||
1721            (NType & MachO::N_TYPE) == MachO::N_PBUD)) {
1722             uint32_t LibraryOrdinal = MachO::GET_LIBRARY_ORDINAL(NDesc);
1723             if (LibraryOrdinal != 0 &&
1724                 LibraryOrdinal != MachO::EXECUTABLE_ORDINAL &&
1725                 LibraryOrdinal != MachO::DYNAMIC_LOOKUP_ORDINAL &&
1726                 LibraryOrdinal - 1 >= Libraries.size() ) {
1727               return malformedError("bad library ordinal: " + Twine(LibraryOrdinal) +
1728                                     " for symbol at index " + Twine(SymbolIndex));
1729             }
1730           }
1731     }
1732     if (NStrx >= S.strsize)
1733       return malformedError("bad string table index: " + Twine((int)NStrx) +
1734                             " past the end of string table, for symbol at "
1735                             "index " + Twine(SymbolIndex));
1736     SymbolIndex++;
1737   }
1738   return Error::success();
1739 }
1740 
1741 void MachOObjectFile::moveSymbolNext(DataRefImpl &Symb) const {
1742   unsigned SymbolTableEntrySize = is64Bit() ?
1743     sizeof(MachO::nlist_64) :
1744     sizeof(MachO::nlist);
1745   Symb.p += SymbolTableEntrySize;
1746 }
1747 
1748 Expected<StringRef> MachOObjectFile::getSymbolName(DataRefImpl Symb) const {
1749   StringRef StringTable = getStringTableData();
1750   MachO::nlist_base Entry = getSymbolTableEntryBase(*this, Symb);
1751   if (Entry.n_strx == 0)
1752     // A n_strx value of 0 indicates that no name is associated with a
1753     // particular symbol table entry.
1754     return StringRef();
1755   const char *Start = &StringTable.data()[Entry.n_strx];
1756   if (Start < getData().begin() || Start >= getData().end()) {
1757     return malformedError("bad string index: " + Twine(Entry.n_strx) +
1758                           " for symbol at index " + Twine(getSymbolIndex(Symb)));
1759   }
1760   return StringRef(Start);
1761 }
1762 
1763 unsigned MachOObjectFile::getSectionType(SectionRef Sec) const {
1764   DataRefImpl DRI = Sec.getRawDataRefImpl();
1765   uint32_t Flags = getSectionFlags(*this, DRI);
1766   return Flags & MachO::SECTION_TYPE;
1767 }
1768 
1769 uint64_t MachOObjectFile::getNValue(DataRefImpl Sym) const {
1770   if (is64Bit()) {
1771     MachO::nlist_64 Entry = getSymbol64TableEntry(Sym);
1772     return Entry.n_value;
1773   }
1774   MachO::nlist Entry = getSymbolTableEntry(Sym);
1775   return Entry.n_value;
1776 }
1777 
1778 // getIndirectName() returns the name of the alias'ed symbol who's string table
1779 // index is in the n_value field.
1780 std::error_code MachOObjectFile::getIndirectName(DataRefImpl Symb,
1781                                                  StringRef &Res) const {
1782   StringRef StringTable = getStringTableData();
1783   MachO::nlist_base Entry = getSymbolTableEntryBase(*this, Symb);
1784   if ((Entry.n_type & MachO::N_TYPE) != MachO::N_INDR)
1785     return object_error::parse_failed;
1786   uint64_t NValue = getNValue(Symb);
1787   if (NValue >= StringTable.size())
1788     return object_error::parse_failed;
1789   const char *Start = &StringTable.data()[NValue];
1790   Res = StringRef(Start);
1791   return std::error_code();
1792 }
1793 
1794 uint64_t MachOObjectFile::getSymbolValueImpl(DataRefImpl Sym) const {
1795   return getNValue(Sym);
1796 }
1797 
1798 Expected<uint64_t> MachOObjectFile::getSymbolAddress(DataRefImpl Sym) const {
1799   return getSymbolValue(Sym);
1800 }
1801 
1802 uint32_t MachOObjectFile::getSymbolAlignment(DataRefImpl DRI) const {
1803   uint32_t flags = getSymbolFlags(DRI);
1804   if (flags & SymbolRef::SF_Common) {
1805     MachO::nlist_base Entry = getSymbolTableEntryBase(*this, DRI);
1806     return 1 << MachO::GET_COMM_ALIGN(Entry.n_desc);
1807   }
1808   return 0;
1809 }
1810 
1811 uint64_t MachOObjectFile::getCommonSymbolSizeImpl(DataRefImpl DRI) const {
1812   return getNValue(DRI);
1813 }
1814 
1815 Expected<SymbolRef::Type>
1816 MachOObjectFile::getSymbolType(DataRefImpl Symb) const {
1817   MachO::nlist_base Entry = getSymbolTableEntryBase(*this, Symb);
1818   uint8_t n_type = Entry.n_type;
1819 
1820   // If this is a STAB debugging symbol, we can do nothing more.
1821   if (n_type & MachO::N_STAB)
1822     return SymbolRef::ST_Debug;
1823 
1824   switch (n_type & MachO::N_TYPE) {
1825     case MachO::N_UNDF :
1826       return SymbolRef::ST_Unknown;
1827     case MachO::N_SECT :
1828       Expected<section_iterator> SecOrError = getSymbolSection(Symb);
1829       if (!SecOrError)
1830         return SecOrError.takeError();
1831       section_iterator Sec = *SecOrError;
1832       if (Sec->isData() || Sec->isBSS())
1833         return SymbolRef::ST_Data;
1834       return SymbolRef::ST_Function;
1835   }
1836   return SymbolRef::ST_Other;
1837 }
1838 
1839 uint32_t MachOObjectFile::getSymbolFlags(DataRefImpl DRI) const {
1840   MachO::nlist_base Entry = getSymbolTableEntryBase(*this, DRI);
1841 
1842   uint8_t MachOType = Entry.n_type;
1843   uint16_t MachOFlags = Entry.n_desc;
1844 
1845   uint32_t Result = SymbolRef::SF_None;
1846 
1847   if ((MachOType & MachO::N_TYPE) == MachO::N_INDR)
1848     Result |= SymbolRef::SF_Indirect;
1849 
1850   if (MachOType & MachO::N_STAB)
1851     Result |= SymbolRef::SF_FormatSpecific;
1852 
1853   if (MachOType & MachO::N_EXT) {
1854     Result |= SymbolRef::SF_Global;
1855     if ((MachOType & MachO::N_TYPE) == MachO::N_UNDF) {
1856       if (getNValue(DRI))
1857         Result |= SymbolRef::SF_Common;
1858       else
1859         Result |= SymbolRef::SF_Undefined;
1860     }
1861 
1862     if (!(MachOType & MachO::N_PEXT))
1863       Result |= SymbolRef::SF_Exported;
1864   }
1865 
1866   if (MachOFlags & (MachO::N_WEAK_REF | MachO::N_WEAK_DEF))
1867     Result |= SymbolRef::SF_Weak;
1868 
1869   if (MachOFlags & (MachO::N_ARM_THUMB_DEF))
1870     Result |= SymbolRef::SF_Thumb;
1871 
1872   if ((MachOType & MachO::N_TYPE) == MachO::N_ABS)
1873     Result |= SymbolRef::SF_Absolute;
1874 
1875   return Result;
1876 }
1877 
1878 Expected<section_iterator>
1879 MachOObjectFile::getSymbolSection(DataRefImpl Symb) const {
1880   MachO::nlist_base Entry = getSymbolTableEntryBase(*this, Symb);
1881   uint8_t index = Entry.n_sect;
1882 
1883   if (index == 0)
1884     return section_end();
1885   DataRefImpl DRI;
1886   DRI.d.a = index - 1;
1887   if (DRI.d.a >= Sections.size()){
1888     return malformedError("bad section index: " + Twine((int)index) +
1889                           " for symbol at index " + Twine(getSymbolIndex(Symb)));
1890   }
1891   return section_iterator(SectionRef(DRI, this));
1892 }
1893 
1894 unsigned MachOObjectFile::getSymbolSectionID(SymbolRef Sym) const {
1895   MachO::nlist_base Entry =
1896       getSymbolTableEntryBase(*this, Sym.getRawDataRefImpl());
1897   return Entry.n_sect - 1;
1898 }
1899 
1900 void MachOObjectFile::moveSectionNext(DataRefImpl &Sec) const {
1901   Sec.d.a++;
1902 }
1903 
1904 Expected<StringRef> MachOObjectFile::getSectionName(DataRefImpl Sec) const {
1905   ArrayRef<char> Raw = getSectionRawName(Sec);
1906   return parseSegmentOrSectionName(Raw.data());
1907 }
1908 
1909 uint64_t MachOObjectFile::getSectionAddress(DataRefImpl Sec) const {
1910   if (is64Bit())
1911     return getSection64(Sec).addr;
1912   return getSection(Sec).addr;
1913 }
1914 
1915 uint64_t MachOObjectFile::getSectionIndex(DataRefImpl Sec) const {
1916   return Sec.d.a;
1917 }
1918 
1919 uint64_t MachOObjectFile::getSectionSize(DataRefImpl Sec) const {
1920   // In the case if a malformed Mach-O file where the section offset is past
1921   // the end of the file or some part of the section size is past the end of
1922   // the file return a size of zero or a size that covers the rest of the file
1923   // but does not extend past the end of the file.
1924   uint32_t SectOffset, SectType;
1925   uint64_t SectSize;
1926 
1927   if (is64Bit()) {
1928     MachO::section_64 Sect = getSection64(Sec);
1929     SectOffset = Sect.offset;
1930     SectSize = Sect.size;
1931     SectType = Sect.flags & MachO::SECTION_TYPE;
1932   } else {
1933     MachO::section Sect = getSection(Sec);
1934     SectOffset = Sect.offset;
1935     SectSize = Sect.size;
1936     SectType = Sect.flags & MachO::SECTION_TYPE;
1937   }
1938   if (SectType == MachO::S_ZEROFILL || SectType == MachO::S_GB_ZEROFILL)
1939     return SectSize;
1940   uint64_t FileSize = getData().size();
1941   if (SectOffset > FileSize)
1942     return 0;
1943   if (FileSize - SectOffset < SectSize)
1944     return FileSize - SectOffset;
1945   return SectSize;
1946 }
1947 
1948 Expected<ArrayRef<uint8_t>>
1949 MachOObjectFile::getSectionContents(DataRefImpl Sec) const {
1950   uint32_t Offset;
1951   uint64_t Size;
1952 
1953   if (is64Bit()) {
1954     MachO::section_64 Sect = getSection64(Sec);
1955     Offset = Sect.offset;
1956     Size = Sect.size;
1957   } else {
1958     MachO::section Sect = getSection(Sec);
1959     Offset = Sect.offset;
1960     Size = Sect.size;
1961   }
1962 
1963   return arrayRefFromStringRef(getData().substr(Offset, Size));
1964 }
1965 
1966 uint64_t MachOObjectFile::getSectionAlignment(DataRefImpl Sec) const {
1967   uint32_t Align;
1968   if (is64Bit()) {
1969     MachO::section_64 Sect = getSection64(Sec);
1970     Align = Sect.align;
1971   } else {
1972     MachO::section Sect = getSection(Sec);
1973     Align = Sect.align;
1974   }
1975 
1976   return uint64_t(1) << Align;
1977 }
1978 
1979 Expected<SectionRef> MachOObjectFile::getSection(unsigned SectionIndex) const {
1980   if (SectionIndex < 1 || SectionIndex > Sections.size())
1981     return malformedError("bad section index: " + Twine((int)SectionIndex));
1982 
1983   DataRefImpl DRI;
1984   DRI.d.a = SectionIndex - 1;
1985   return SectionRef(DRI, this);
1986 }
1987 
1988 Expected<SectionRef> MachOObjectFile::getSection(StringRef SectionName) const {
1989   StringRef SecName;
1990   for (const SectionRef &Section : sections()) {
1991     if (std::error_code E = Section.getName(SecName))
1992       return errorCodeToError(E);
1993     if (SecName == SectionName) {
1994       return Section;
1995     }
1996   }
1997   return errorCodeToError(object_error::parse_failed);
1998 }
1999 
2000 bool MachOObjectFile::isSectionCompressed(DataRefImpl Sec) const {
2001   return false;
2002 }
2003 
2004 bool MachOObjectFile::isSectionText(DataRefImpl Sec) const {
2005   uint32_t Flags = getSectionFlags(*this, Sec);
2006   return Flags & MachO::S_ATTR_PURE_INSTRUCTIONS;
2007 }
2008 
2009 bool MachOObjectFile::isSectionData(DataRefImpl Sec) const {
2010   uint32_t Flags = getSectionFlags(*this, Sec);
2011   unsigned SectionType = Flags & MachO::SECTION_TYPE;
2012   return !(Flags & MachO::S_ATTR_PURE_INSTRUCTIONS) &&
2013          !(SectionType == MachO::S_ZEROFILL ||
2014            SectionType == MachO::S_GB_ZEROFILL);
2015 }
2016 
2017 bool MachOObjectFile::isSectionBSS(DataRefImpl Sec) const {
2018   uint32_t Flags = getSectionFlags(*this, Sec);
2019   unsigned SectionType = Flags & MachO::SECTION_TYPE;
2020   return !(Flags & MachO::S_ATTR_PURE_INSTRUCTIONS) &&
2021          (SectionType == MachO::S_ZEROFILL ||
2022           SectionType == MachO::S_GB_ZEROFILL);
2023 }
2024 
2025 unsigned MachOObjectFile::getSectionID(SectionRef Sec) const {
2026   return Sec.getRawDataRefImpl().d.a;
2027 }
2028 
2029 bool MachOObjectFile::isSectionVirtual(DataRefImpl Sec) const {
2030   uint32_t Flags = getSectionFlags(*this, Sec);
2031   unsigned SectionType = Flags & MachO::SECTION_TYPE;
2032   return SectionType == MachO::S_ZEROFILL ||
2033          SectionType == MachO::S_GB_ZEROFILL;
2034 }
2035 
2036 bool MachOObjectFile::isSectionBitcode(DataRefImpl Sec) const {
2037   StringRef SegmentName = getSectionFinalSegmentName(Sec);
2038   if (Expected<StringRef> NameOrErr = getSectionName(Sec))
2039     return (SegmentName == "__LLVM" && *NameOrErr == "__bitcode");
2040   return false;
2041 }
2042 
2043 bool MachOObjectFile::isSectionStripped(DataRefImpl Sec) const {
2044   if (is64Bit())
2045     return getSection64(Sec).offset == 0;
2046   return getSection(Sec).offset == 0;
2047 }
2048 
2049 relocation_iterator MachOObjectFile::section_rel_begin(DataRefImpl Sec) const {
2050   DataRefImpl Ret;
2051   Ret.d.a = Sec.d.a;
2052   Ret.d.b = 0;
2053   return relocation_iterator(RelocationRef(Ret, this));
2054 }
2055 
2056 relocation_iterator
2057 MachOObjectFile::section_rel_end(DataRefImpl Sec) const {
2058   uint32_t Num;
2059   if (is64Bit()) {
2060     MachO::section_64 Sect = getSection64(Sec);
2061     Num = Sect.nreloc;
2062   } else {
2063     MachO::section Sect = getSection(Sec);
2064     Num = Sect.nreloc;
2065   }
2066 
2067   DataRefImpl Ret;
2068   Ret.d.a = Sec.d.a;
2069   Ret.d.b = Num;
2070   return relocation_iterator(RelocationRef(Ret, this));
2071 }
2072 
2073 relocation_iterator MachOObjectFile::extrel_begin() const {
2074   DataRefImpl Ret;
2075   // for DYSYMTAB symbols, Ret.d.a == 0 for external relocations
2076   Ret.d.a = 0; // Would normally be a section index.
2077   Ret.d.b = 0; // Index into the external relocations
2078   return relocation_iterator(RelocationRef(Ret, this));
2079 }
2080 
2081 relocation_iterator MachOObjectFile::extrel_end() const {
2082   MachO::dysymtab_command DysymtabLoadCmd = getDysymtabLoadCommand();
2083   DataRefImpl Ret;
2084   // for DYSYMTAB symbols, Ret.d.a == 0 for external relocations
2085   Ret.d.a = 0; // Would normally be a section index.
2086   Ret.d.b = DysymtabLoadCmd.nextrel; // Index into the external relocations
2087   return relocation_iterator(RelocationRef(Ret, this));
2088 }
2089 
2090 relocation_iterator MachOObjectFile::locrel_begin() const {
2091   DataRefImpl Ret;
2092   // for DYSYMTAB symbols, Ret.d.a == 1 for local relocations
2093   Ret.d.a = 1; // Would normally be a section index.
2094   Ret.d.b = 0; // Index into the local relocations
2095   return relocation_iterator(RelocationRef(Ret, this));
2096 }
2097 
2098 relocation_iterator MachOObjectFile::locrel_end() const {
2099   MachO::dysymtab_command DysymtabLoadCmd = getDysymtabLoadCommand();
2100   DataRefImpl Ret;
2101   // for DYSYMTAB symbols, Ret.d.a == 1 for local relocations
2102   Ret.d.a = 1; // Would normally be a section index.
2103   Ret.d.b = DysymtabLoadCmd.nlocrel; // Index into the local relocations
2104   return relocation_iterator(RelocationRef(Ret, this));
2105 }
2106 
2107 void MachOObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
2108   ++Rel.d.b;
2109 }
2110 
2111 uint64_t MachOObjectFile::getRelocationOffset(DataRefImpl Rel) const {
2112   assert((getHeader().filetype == MachO::MH_OBJECT ||
2113           getHeader().filetype == MachO::MH_KEXT_BUNDLE) &&
2114          "Only implemented for MH_OBJECT && MH_KEXT_BUNDLE");
2115   MachO::any_relocation_info RE = getRelocation(Rel);
2116   return getAnyRelocationAddress(RE);
2117 }
2118 
2119 symbol_iterator
2120 MachOObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
2121   MachO::any_relocation_info RE = getRelocation(Rel);
2122   if (isRelocationScattered(RE))
2123     return symbol_end();
2124 
2125   uint32_t SymbolIdx = getPlainRelocationSymbolNum(RE);
2126   bool isExtern = getPlainRelocationExternal(RE);
2127   if (!isExtern)
2128     return symbol_end();
2129 
2130   MachO::symtab_command S = getSymtabLoadCommand();
2131   unsigned SymbolTableEntrySize = is64Bit() ?
2132     sizeof(MachO::nlist_64) :
2133     sizeof(MachO::nlist);
2134   uint64_t Offset = S.symoff + SymbolIdx * SymbolTableEntrySize;
2135   DataRefImpl Sym;
2136   Sym.p = reinterpret_cast<uintptr_t>(getPtr(*this, Offset));
2137   return symbol_iterator(SymbolRef(Sym, this));
2138 }
2139 
2140 section_iterator
2141 MachOObjectFile::getRelocationSection(DataRefImpl Rel) const {
2142   return section_iterator(getAnyRelocationSection(getRelocation(Rel)));
2143 }
2144 
2145 uint64_t MachOObjectFile::getRelocationType(DataRefImpl Rel) const {
2146   MachO::any_relocation_info RE = getRelocation(Rel);
2147   return getAnyRelocationType(RE);
2148 }
2149 
2150 void MachOObjectFile::getRelocationTypeName(
2151     DataRefImpl Rel, SmallVectorImpl<char> &Result) const {
2152   StringRef res;
2153   uint64_t RType = getRelocationType(Rel);
2154 
2155   unsigned Arch = this->getArch();
2156 
2157   switch (Arch) {
2158     case Triple::x86: {
2159       static const char *const Table[] =  {
2160         "GENERIC_RELOC_VANILLA",
2161         "GENERIC_RELOC_PAIR",
2162         "GENERIC_RELOC_SECTDIFF",
2163         "GENERIC_RELOC_PB_LA_PTR",
2164         "GENERIC_RELOC_LOCAL_SECTDIFF",
2165         "GENERIC_RELOC_TLV" };
2166 
2167       if (RType > 5)
2168         res = "Unknown";
2169       else
2170         res = Table[RType];
2171       break;
2172     }
2173     case Triple::x86_64: {
2174       static const char *const Table[] =  {
2175         "X86_64_RELOC_UNSIGNED",
2176         "X86_64_RELOC_SIGNED",
2177         "X86_64_RELOC_BRANCH",
2178         "X86_64_RELOC_GOT_LOAD",
2179         "X86_64_RELOC_GOT",
2180         "X86_64_RELOC_SUBTRACTOR",
2181         "X86_64_RELOC_SIGNED_1",
2182         "X86_64_RELOC_SIGNED_2",
2183         "X86_64_RELOC_SIGNED_4",
2184         "X86_64_RELOC_TLV" };
2185 
2186       if (RType > 9)
2187         res = "Unknown";
2188       else
2189         res = Table[RType];
2190       break;
2191     }
2192     case Triple::arm: {
2193       static const char *const Table[] =  {
2194         "ARM_RELOC_VANILLA",
2195         "ARM_RELOC_PAIR",
2196         "ARM_RELOC_SECTDIFF",
2197         "ARM_RELOC_LOCAL_SECTDIFF",
2198         "ARM_RELOC_PB_LA_PTR",
2199         "ARM_RELOC_BR24",
2200         "ARM_THUMB_RELOC_BR22",
2201         "ARM_THUMB_32BIT_BRANCH",
2202         "ARM_RELOC_HALF",
2203         "ARM_RELOC_HALF_SECTDIFF" };
2204 
2205       if (RType > 9)
2206         res = "Unknown";
2207       else
2208         res = Table[RType];
2209       break;
2210     }
2211     case Triple::aarch64:
2212     case Triple::aarch64_32: {
2213       static const char *const Table[] = {
2214         "ARM64_RELOC_UNSIGNED",           "ARM64_RELOC_SUBTRACTOR",
2215         "ARM64_RELOC_BRANCH26",           "ARM64_RELOC_PAGE21",
2216         "ARM64_RELOC_PAGEOFF12",          "ARM64_RELOC_GOT_LOAD_PAGE21",
2217         "ARM64_RELOC_GOT_LOAD_PAGEOFF12", "ARM64_RELOC_POINTER_TO_GOT",
2218         "ARM64_RELOC_TLVP_LOAD_PAGE21",   "ARM64_RELOC_TLVP_LOAD_PAGEOFF12",
2219         "ARM64_RELOC_ADDEND"
2220       };
2221 
2222       if (RType >= array_lengthof(Table))
2223         res = "Unknown";
2224       else
2225         res = Table[RType];
2226       break;
2227     }
2228     case Triple::ppc: {
2229       static const char *const Table[] =  {
2230         "PPC_RELOC_VANILLA",
2231         "PPC_RELOC_PAIR",
2232         "PPC_RELOC_BR14",
2233         "PPC_RELOC_BR24",
2234         "PPC_RELOC_HI16",
2235         "PPC_RELOC_LO16",
2236         "PPC_RELOC_HA16",
2237         "PPC_RELOC_LO14",
2238         "PPC_RELOC_SECTDIFF",
2239         "PPC_RELOC_PB_LA_PTR",
2240         "PPC_RELOC_HI16_SECTDIFF",
2241         "PPC_RELOC_LO16_SECTDIFF",
2242         "PPC_RELOC_HA16_SECTDIFF",
2243         "PPC_RELOC_JBSR",
2244         "PPC_RELOC_LO14_SECTDIFF",
2245         "PPC_RELOC_LOCAL_SECTDIFF" };
2246 
2247       if (RType > 15)
2248         res = "Unknown";
2249       else
2250         res = Table[RType];
2251       break;
2252     }
2253     case Triple::UnknownArch:
2254       res = "Unknown";
2255       break;
2256   }
2257   Result.append(res.begin(), res.end());
2258 }
2259 
2260 uint8_t MachOObjectFile::getRelocationLength(DataRefImpl Rel) const {
2261   MachO::any_relocation_info RE = getRelocation(Rel);
2262   return getAnyRelocationLength(RE);
2263 }
2264 
2265 //
2266 // guessLibraryShortName() is passed a name of a dynamic library and returns a
2267 // guess on what the short name is.  Then name is returned as a substring of the
2268 // StringRef Name passed in.  The name of the dynamic library is recognized as
2269 // a framework if it has one of the two following forms:
2270 //      Foo.framework/Versions/A/Foo
2271 //      Foo.framework/Foo
2272 // Where A and Foo can be any string.  And may contain a trailing suffix
2273 // starting with an underbar.  If the Name is recognized as a framework then
2274 // isFramework is set to true else it is set to false.  If the Name has a
2275 // suffix then Suffix is set to the substring in Name that contains the suffix
2276 // else it is set to a NULL StringRef.
2277 //
2278 // The Name of the dynamic library is recognized as a library name if it has
2279 // one of the two following forms:
2280 //      libFoo.A.dylib
2281 //      libFoo.dylib
2282 //
2283 // The library may have a suffix trailing the name Foo of the form:
2284 //      libFoo_profile.A.dylib
2285 //      libFoo_profile.dylib
2286 // These dyld image suffixes are separated from the short name by a '_'
2287 // character. Because the '_' character is commonly used to separate words in
2288 // filenames guessLibraryShortName() cannot reliably separate a dylib's short
2289 // name from an arbitrary image suffix; imagine if both the short name and the
2290 // suffix contains an '_' character! To better deal with this ambiguity,
2291 // guessLibraryShortName() will recognize only "_debug" and "_profile" as valid
2292 // Suffix values. Calling code needs to be tolerant of guessLibraryShortName()
2293 // guessing incorrectly.
2294 //
2295 // The Name of the dynamic library is also recognized as a library name if it
2296 // has the following form:
2297 //      Foo.qtx
2298 //
2299 // If the Name of the dynamic library is none of the forms above then a NULL
2300 // StringRef is returned.
2301 StringRef MachOObjectFile::guessLibraryShortName(StringRef Name,
2302                                                  bool &isFramework,
2303                                                  StringRef &Suffix) {
2304   StringRef Foo, F, DotFramework, V, Dylib, Lib, Dot, Qtx;
2305   size_t a, b, c, d, Idx;
2306 
2307   isFramework = false;
2308   Suffix = StringRef();
2309 
2310   // Pull off the last component and make Foo point to it
2311   a = Name.rfind('/');
2312   if (a == Name.npos || a == 0)
2313     goto guess_library;
2314   Foo = Name.slice(a+1, Name.npos);
2315 
2316   // Look for a suffix starting with a '_'
2317   Idx = Foo.rfind('_');
2318   if (Idx != Foo.npos && Foo.size() >= 2) {
2319     Suffix = Foo.slice(Idx, Foo.npos);
2320     if (Suffix != "_debug" && Suffix != "_profile")
2321       Suffix = StringRef();
2322     else
2323       Foo = Foo.slice(0, Idx);
2324   }
2325 
2326   // First look for the form Foo.framework/Foo
2327   b = Name.rfind('/', a);
2328   if (b == Name.npos)
2329     Idx = 0;
2330   else
2331     Idx = b+1;
2332   F = Name.slice(Idx, Idx + Foo.size());
2333   DotFramework = Name.slice(Idx + Foo.size(),
2334                             Idx + Foo.size() + sizeof(".framework/")-1);
2335   if (F == Foo && DotFramework == ".framework/") {
2336     isFramework = true;
2337     return Foo;
2338   }
2339 
2340   // Next look for the form Foo.framework/Versions/A/Foo
2341   if (b == Name.npos)
2342     goto guess_library;
2343   c =  Name.rfind('/', b);
2344   if (c == Name.npos || c == 0)
2345     goto guess_library;
2346   V = Name.slice(c+1, Name.npos);
2347   if (!V.startswith("Versions/"))
2348     goto guess_library;
2349   d =  Name.rfind('/', c);
2350   if (d == Name.npos)
2351     Idx = 0;
2352   else
2353     Idx = d+1;
2354   F = Name.slice(Idx, Idx + Foo.size());
2355   DotFramework = Name.slice(Idx + Foo.size(),
2356                             Idx + Foo.size() + sizeof(".framework/")-1);
2357   if (F == Foo && DotFramework == ".framework/") {
2358     isFramework = true;
2359     return Foo;
2360   }
2361 
2362 guess_library:
2363   // pull off the suffix after the "." and make a point to it
2364   a = Name.rfind('.');
2365   if (a == Name.npos || a == 0)
2366     return StringRef();
2367   Dylib = Name.slice(a, Name.npos);
2368   if (Dylib != ".dylib")
2369     goto guess_qtx;
2370 
2371   // First pull off the version letter for the form Foo.A.dylib if any.
2372   if (a >= 3) {
2373     Dot = Name.slice(a-2, a-1);
2374     if (Dot == ".")
2375       a = a - 2;
2376   }
2377 
2378   b = Name.rfind('/', a);
2379   if (b == Name.npos)
2380     b = 0;
2381   else
2382     b = b+1;
2383   // ignore any suffix after an underbar like Foo_profile.A.dylib
2384   Idx = Name.rfind('_');
2385   if (Idx != Name.npos && Idx != b) {
2386     Lib = Name.slice(b, Idx);
2387     Suffix = Name.slice(Idx, a);
2388     if (Suffix != "_debug" && Suffix != "_profile") {
2389       Suffix = StringRef();
2390       Lib = Name.slice(b, a);
2391     }
2392   }
2393   else
2394     Lib = Name.slice(b, a);
2395   // There are incorrect library names of the form:
2396   // libATS.A_profile.dylib so check for these.
2397   if (Lib.size() >= 3) {
2398     Dot = Lib.slice(Lib.size()-2, Lib.size()-1);
2399     if (Dot == ".")
2400       Lib = Lib.slice(0, Lib.size()-2);
2401   }
2402   return Lib;
2403 
2404 guess_qtx:
2405   Qtx = Name.slice(a, Name.npos);
2406   if (Qtx != ".qtx")
2407     return StringRef();
2408   b = Name.rfind('/', a);
2409   if (b == Name.npos)
2410     Lib = Name.slice(0, a);
2411   else
2412     Lib = Name.slice(b+1, a);
2413   // There are library names of the form: QT.A.qtx so check for these.
2414   if (Lib.size() >= 3) {
2415     Dot = Lib.slice(Lib.size()-2, Lib.size()-1);
2416     if (Dot == ".")
2417       Lib = Lib.slice(0, Lib.size()-2);
2418   }
2419   return Lib;
2420 }
2421 
2422 // getLibraryShortNameByIndex() is used to get the short name of the library
2423 // for an undefined symbol in a linked Mach-O binary that was linked with the
2424 // normal two-level namespace default (that is MH_TWOLEVEL in the header).
2425 // It is passed the index (0 - based) of the library as translated from
2426 // GET_LIBRARY_ORDINAL (1 - based).
2427 std::error_code MachOObjectFile::getLibraryShortNameByIndex(unsigned Index,
2428                                                          StringRef &Res) const {
2429   if (Index >= Libraries.size())
2430     return object_error::parse_failed;
2431 
2432   // If the cache of LibrariesShortNames is not built up do that first for
2433   // all the Libraries.
2434   if (LibrariesShortNames.size() == 0) {
2435     for (unsigned i = 0; i < Libraries.size(); i++) {
2436       auto CommandOrErr =
2437         getStructOrErr<MachO::dylib_command>(*this, Libraries[i]);
2438       if (!CommandOrErr)
2439         return object_error::parse_failed;
2440       MachO::dylib_command D = CommandOrErr.get();
2441       if (D.dylib.name >= D.cmdsize)
2442         return object_error::parse_failed;
2443       const char *P = (const char *)(Libraries[i]) + D.dylib.name;
2444       StringRef Name = StringRef(P);
2445       if (D.dylib.name+Name.size() >= D.cmdsize)
2446         return object_error::parse_failed;
2447       StringRef Suffix;
2448       bool isFramework;
2449       StringRef shortName = guessLibraryShortName(Name, isFramework, Suffix);
2450       if (shortName.empty())
2451         LibrariesShortNames.push_back(Name);
2452       else
2453         LibrariesShortNames.push_back(shortName);
2454     }
2455   }
2456 
2457   Res = LibrariesShortNames[Index];
2458   return std::error_code();
2459 }
2460 
2461 uint32_t MachOObjectFile::getLibraryCount() const {
2462   return Libraries.size();
2463 }
2464 
2465 section_iterator
2466 MachOObjectFile::getRelocationRelocatedSection(relocation_iterator Rel) const {
2467   DataRefImpl Sec;
2468   Sec.d.a = Rel->getRawDataRefImpl().d.a;
2469   return section_iterator(SectionRef(Sec, this));
2470 }
2471 
2472 basic_symbol_iterator MachOObjectFile::symbol_begin() const {
2473   DataRefImpl DRI;
2474   MachO::symtab_command Symtab = getSymtabLoadCommand();
2475   if (!SymtabLoadCmd || Symtab.nsyms == 0)
2476     return basic_symbol_iterator(SymbolRef(DRI, this));
2477 
2478   return getSymbolByIndex(0);
2479 }
2480 
2481 basic_symbol_iterator MachOObjectFile::symbol_end() const {
2482   DataRefImpl DRI;
2483   MachO::symtab_command Symtab = getSymtabLoadCommand();
2484   if (!SymtabLoadCmd || Symtab.nsyms == 0)
2485     return basic_symbol_iterator(SymbolRef(DRI, this));
2486 
2487   unsigned SymbolTableEntrySize = is64Bit() ?
2488     sizeof(MachO::nlist_64) :
2489     sizeof(MachO::nlist);
2490   unsigned Offset = Symtab.symoff +
2491     Symtab.nsyms * SymbolTableEntrySize;
2492   DRI.p = reinterpret_cast<uintptr_t>(getPtr(*this, Offset));
2493   return basic_symbol_iterator(SymbolRef(DRI, this));
2494 }
2495 
2496 symbol_iterator MachOObjectFile::getSymbolByIndex(unsigned Index) const {
2497   MachO::symtab_command Symtab = getSymtabLoadCommand();
2498   if (!SymtabLoadCmd || Index >= Symtab.nsyms)
2499     report_fatal_error("Requested symbol index is out of range.");
2500   unsigned SymbolTableEntrySize =
2501     is64Bit() ? sizeof(MachO::nlist_64) : sizeof(MachO::nlist);
2502   DataRefImpl DRI;
2503   DRI.p = reinterpret_cast<uintptr_t>(getPtr(*this, Symtab.symoff));
2504   DRI.p += Index * SymbolTableEntrySize;
2505   return basic_symbol_iterator(SymbolRef(DRI, this));
2506 }
2507 
2508 uint64_t MachOObjectFile::getSymbolIndex(DataRefImpl Symb) const {
2509   MachO::symtab_command Symtab = getSymtabLoadCommand();
2510   if (!SymtabLoadCmd)
2511     report_fatal_error("getSymbolIndex() called with no symbol table symbol");
2512   unsigned SymbolTableEntrySize =
2513     is64Bit() ? sizeof(MachO::nlist_64) : sizeof(MachO::nlist);
2514   DataRefImpl DRIstart;
2515   DRIstart.p = reinterpret_cast<uintptr_t>(getPtr(*this, Symtab.symoff));
2516   uint64_t Index = (Symb.p - DRIstart.p) / SymbolTableEntrySize;
2517   return Index;
2518 }
2519 
2520 section_iterator MachOObjectFile::section_begin() const {
2521   DataRefImpl DRI;
2522   return section_iterator(SectionRef(DRI, this));
2523 }
2524 
2525 section_iterator MachOObjectFile::section_end() const {
2526   DataRefImpl DRI;
2527   DRI.d.a = Sections.size();
2528   return section_iterator(SectionRef(DRI, this));
2529 }
2530 
2531 uint8_t MachOObjectFile::getBytesInAddress() const {
2532   return is64Bit() ? 8 : 4;
2533 }
2534 
2535 StringRef MachOObjectFile::getFileFormatName() const {
2536   unsigned CPUType = getCPUType(*this);
2537   if (!is64Bit()) {
2538     switch (CPUType) {
2539     case MachO::CPU_TYPE_I386:
2540       return "Mach-O 32-bit i386";
2541     case MachO::CPU_TYPE_ARM:
2542       return "Mach-O arm";
2543     case MachO::CPU_TYPE_ARM64_32:
2544       return "Mach-O arm64 (ILP32)";
2545     case MachO::CPU_TYPE_POWERPC:
2546       return "Mach-O 32-bit ppc";
2547     default:
2548       return "Mach-O 32-bit unknown";
2549     }
2550   }
2551 
2552   switch (CPUType) {
2553   case MachO::CPU_TYPE_X86_64:
2554     return "Mach-O 64-bit x86-64";
2555   case MachO::CPU_TYPE_ARM64:
2556     return "Mach-O arm64";
2557   case MachO::CPU_TYPE_POWERPC64:
2558     return "Mach-O 64-bit ppc64";
2559   default:
2560     return "Mach-O 64-bit unknown";
2561   }
2562 }
2563 
2564 Triple::ArchType MachOObjectFile::getArch(uint32_t CPUType) {
2565   switch (CPUType) {
2566   case MachO::CPU_TYPE_I386:
2567     return Triple::x86;
2568   case MachO::CPU_TYPE_X86_64:
2569     return Triple::x86_64;
2570   case MachO::CPU_TYPE_ARM:
2571     return Triple::arm;
2572   case MachO::CPU_TYPE_ARM64:
2573     return Triple::aarch64;
2574   case MachO::CPU_TYPE_ARM64_32:
2575     return Triple::aarch64_32;
2576   case MachO::CPU_TYPE_POWERPC:
2577     return Triple::ppc;
2578   case MachO::CPU_TYPE_POWERPC64:
2579     return Triple::ppc64;
2580   default:
2581     return Triple::UnknownArch;
2582   }
2583 }
2584 
2585 Triple MachOObjectFile::getArchTriple(uint32_t CPUType, uint32_t CPUSubType,
2586                                       const char **McpuDefault,
2587                                       const char **ArchFlag) {
2588   if (McpuDefault)
2589     *McpuDefault = nullptr;
2590   if (ArchFlag)
2591     *ArchFlag = nullptr;
2592 
2593   switch (CPUType) {
2594   case MachO::CPU_TYPE_I386:
2595     switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2596     case MachO::CPU_SUBTYPE_I386_ALL:
2597       if (ArchFlag)
2598         *ArchFlag = "i386";
2599       return Triple("i386-apple-darwin");
2600     default:
2601       return Triple();
2602     }
2603   case MachO::CPU_TYPE_X86_64:
2604     switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2605     case MachO::CPU_SUBTYPE_X86_64_ALL:
2606       if (ArchFlag)
2607         *ArchFlag = "x86_64";
2608       return Triple("x86_64-apple-darwin");
2609     case MachO::CPU_SUBTYPE_X86_64_H:
2610       if (ArchFlag)
2611         *ArchFlag = "x86_64h";
2612       return Triple("x86_64h-apple-darwin");
2613     default:
2614       return Triple();
2615     }
2616   case MachO::CPU_TYPE_ARM:
2617     switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2618     case MachO::CPU_SUBTYPE_ARM_V4T:
2619       if (ArchFlag)
2620         *ArchFlag = "armv4t";
2621       return Triple("armv4t-apple-darwin");
2622     case MachO::CPU_SUBTYPE_ARM_V5TEJ:
2623       if (ArchFlag)
2624         *ArchFlag = "armv5e";
2625       return Triple("armv5e-apple-darwin");
2626     case MachO::CPU_SUBTYPE_ARM_XSCALE:
2627       if (ArchFlag)
2628         *ArchFlag = "xscale";
2629       return Triple("xscale-apple-darwin");
2630     case MachO::CPU_SUBTYPE_ARM_V6:
2631       if (ArchFlag)
2632         *ArchFlag = "armv6";
2633       return Triple("armv6-apple-darwin");
2634     case MachO::CPU_SUBTYPE_ARM_V6M:
2635       if (McpuDefault)
2636         *McpuDefault = "cortex-m0";
2637       if (ArchFlag)
2638         *ArchFlag = "armv6m";
2639       return Triple("armv6m-apple-darwin");
2640     case MachO::CPU_SUBTYPE_ARM_V7:
2641       if (ArchFlag)
2642         *ArchFlag = "armv7";
2643       return Triple("armv7-apple-darwin");
2644     case MachO::CPU_SUBTYPE_ARM_V7EM:
2645       if (McpuDefault)
2646         *McpuDefault = "cortex-m4";
2647       if (ArchFlag)
2648         *ArchFlag = "armv7em";
2649       return Triple("thumbv7em-apple-darwin");
2650     case MachO::CPU_SUBTYPE_ARM_V7K:
2651       if (McpuDefault)
2652         *McpuDefault = "cortex-a7";
2653       if (ArchFlag)
2654         *ArchFlag = "armv7k";
2655       return Triple("armv7k-apple-darwin");
2656     case MachO::CPU_SUBTYPE_ARM_V7M:
2657       if (McpuDefault)
2658         *McpuDefault = "cortex-m3";
2659       if (ArchFlag)
2660         *ArchFlag = "armv7m";
2661       return Triple("thumbv7m-apple-darwin");
2662     case MachO::CPU_SUBTYPE_ARM_V7S:
2663       if (McpuDefault)
2664         *McpuDefault = "cortex-a7";
2665       if (ArchFlag)
2666         *ArchFlag = "armv7s";
2667       return Triple("armv7s-apple-darwin");
2668     default:
2669       return Triple();
2670     }
2671   case MachO::CPU_TYPE_ARM64:
2672     switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2673     case MachO::CPU_SUBTYPE_ARM64_ALL:
2674       if (McpuDefault)
2675         *McpuDefault = "cyclone";
2676       if (ArchFlag)
2677         *ArchFlag = "arm64";
2678       return Triple("arm64-apple-darwin");
2679     default:
2680       return Triple();
2681     }
2682   case MachO::CPU_TYPE_ARM64_32:
2683     switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2684     case MachO::CPU_SUBTYPE_ARM64_32_V8:
2685       if (McpuDefault)
2686         *McpuDefault = "cyclone";
2687       if (ArchFlag)
2688         *ArchFlag = "arm64_32";
2689       return Triple("arm64_32-apple-darwin");
2690     default:
2691       return Triple();
2692     }
2693   case MachO::CPU_TYPE_POWERPC:
2694     switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2695     case MachO::CPU_SUBTYPE_POWERPC_ALL:
2696       if (ArchFlag)
2697         *ArchFlag = "ppc";
2698       return Triple("ppc-apple-darwin");
2699     default:
2700       return Triple();
2701     }
2702   case MachO::CPU_TYPE_POWERPC64:
2703     switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2704     case MachO::CPU_SUBTYPE_POWERPC_ALL:
2705       if (ArchFlag)
2706         *ArchFlag = "ppc64";
2707       return Triple("ppc64-apple-darwin");
2708     default:
2709       return Triple();
2710     }
2711   default:
2712     return Triple();
2713   }
2714 }
2715 
2716 Triple MachOObjectFile::getHostArch() {
2717   return Triple(sys::getDefaultTargetTriple());
2718 }
2719 
2720 bool MachOObjectFile::isValidArch(StringRef ArchFlag) {
2721   auto validArchs = getValidArchs();
2722   return llvm::find(validArchs, ArchFlag) != validArchs.end();
2723 }
2724 
2725 ArrayRef<StringRef> MachOObjectFile::getValidArchs() {
2726   static const std::array<StringRef, 17> validArchs = {
2727       "i386",   "x86_64", "x86_64h",  "armv4t",  "arm",    "armv5e",
2728       "armv6",  "armv6m", "armv7",    "armv7em", "armv7k", "armv7m",
2729       "armv7s", "arm64",  "arm64_32", "ppc",     "ppc64",
2730   };
2731 
2732   return validArchs;
2733 }
2734 
2735 Triple::ArchType MachOObjectFile::getArch() const {
2736   return getArch(getCPUType(*this));
2737 }
2738 
2739 Triple MachOObjectFile::getArchTriple(const char **McpuDefault) const {
2740   return getArchTriple(Header.cputype, Header.cpusubtype, McpuDefault);
2741 }
2742 
2743 relocation_iterator MachOObjectFile::section_rel_begin(unsigned Index) const {
2744   DataRefImpl DRI;
2745   DRI.d.a = Index;
2746   return section_rel_begin(DRI);
2747 }
2748 
2749 relocation_iterator MachOObjectFile::section_rel_end(unsigned Index) const {
2750   DataRefImpl DRI;
2751   DRI.d.a = Index;
2752   return section_rel_end(DRI);
2753 }
2754 
2755 dice_iterator MachOObjectFile::begin_dices() const {
2756   DataRefImpl DRI;
2757   if (!DataInCodeLoadCmd)
2758     return dice_iterator(DiceRef(DRI, this));
2759 
2760   MachO::linkedit_data_command DicLC = getDataInCodeLoadCommand();
2761   DRI.p = reinterpret_cast<uintptr_t>(getPtr(*this, DicLC.dataoff));
2762   return dice_iterator(DiceRef(DRI, this));
2763 }
2764 
2765 dice_iterator MachOObjectFile::end_dices() const {
2766   DataRefImpl DRI;
2767   if (!DataInCodeLoadCmd)
2768     return dice_iterator(DiceRef(DRI, this));
2769 
2770   MachO::linkedit_data_command DicLC = getDataInCodeLoadCommand();
2771   unsigned Offset = DicLC.dataoff + DicLC.datasize;
2772   DRI.p = reinterpret_cast<uintptr_t>(getPtr(*this, Offset));
2773   return dice_iterator(DiceRef(DRI, this));
2774 }
2775 
2776 ExportEntry::ExportEntry(Error *E, const MachOObjectFile *O,
2777                          ArrayRef<uint8_t> T) : E(E), O(O), Trie(T) {}
2778 
2779 void ExportEntry::moveToFirst() {
2780   ErrorAsOutParameter ErrAsOutParam(E);
2781   pushNode(0);
2782   if (*E)
2783     return;
2784   pushDownUntilBottom();
2785 }
2786 
2787 void ExportEntry::moveToEnd() {
2788   Stack.clear();
2789   Done = true;
2790 }
2791 
2792 bool ExportEntry::operator==(const ExportEntry &Other) const {
2793   // Common case, one at end, other iterating from begin.
2794   if (Done || Other.Done)
2795     return (Done == Other.Done);
2796   // Not equal if different stack sizes.
2797   if (Stack.size() != Other.Stack.size())
2798     return false;
2799   // Not equal if different cumulative strings.
2800   if (!CumulativeString.equals(Other.CumulativeString))
2801     return false;
2802   // Equal if all nodes in both stacks match.
2803   for (unsigned i=0; i < Stack.size(); ++i) {
2804     if (Stack[i].Start != Other.Stack[i].Start)
2805       return false;
2806   }
2807   return true;
2808 }
2809 
2810 uint64_t ExportEntry::readULEB128(const uint8_t *&Ptr, const char **error) {
2811   unsigned Count;
2812   uint64_t Result = decodeULEB128(Ptr, &Count, Trie.end(), error);
2813   Ptr += Count;
2814   if (Ptr > Trie.end())
2815     Ptr = Trie.end();
2816   return Result;
2817 }
2818 
2819 StringRef ExportEntry::name() const {
2820   return CumulativeString;
2821 }
2822 
2823 uint64_t ExportEntry::flags() const {
2824   return Stack.back().Flags;
2825 }
2826 
2827 uint64_t ExportEntry::address() const {
2828   return Stack.back().Address;
2829 }
2830 
2831 uint64_t ExportEntry::other() const {
2832   return Stack.back().Other;
2833 }
2834 
2835 StringRef ExportEntry::otherName() const {
2836   const char* ImportName = Stack.back().ImportName;
2837   if (ImportName)
2838     return StringRef(ImportName);
2839   return StringRef();
2840 }
2841 
2842 uint32_t ExportEntry::nodeOffset() const {
2843   return Stack.back().Start - Trie.begin();
2844 }
2845 
2846 ExportEntry::NodeState::NodeState(const uint8_t *Ptr)
2847     : Start(Ptr), Current(Ptr) {}
2848 
2849 void ExportEntry::pushNode(uint64_t offset) {
2850   ErrorAsOutParameter ErrAsOutParam(E);
2851   const uint8_t *Ptr = Trie.begin() + offset;
2852   NodeState State(Ptr);
2853   const char *error;
2854   uint64_t ExportInfoSize = readULEB128(State.Current, &error);
2855   if (error) {
2856     *E = malformedError("export info size " + Twine(error) +
2857                         " in export trie data at node: 0x" +
2858                         Twine::utohexstr(offset));
2859     moveToEnd();
2860     return;
2861   }
2862   State.IsExportNode = (ExportInfoSize != 0);
2863   const uint8_t* Children = State.Current + ExportInfoSize;
2864   if (Children > Trie.end()) {
2865     *E = malformedError(
2866         "export info size: 0x" + Twine::utohexstr(ExportInfoSize) +
2867         " in export trie data at node: 0x" + Twine::utohexstr(offset) +
2868         " too big and extends past end of trie data");
2869     moveToEnd();
2870     return;
2871   }
2872   if (State.IsExportNode) {
2873     const uint8_t *ExportStart = State.Current;
2874     State.Flags = readULEB128(State.Current, &error);
2875     if (error) {
2876       *E = malformedError("flags " + Twine(error) +
2877                           " in export trie data at node: 0x" +
2878                           Twine::utohexstr(offset));
2879       moveToEnd();
2880       return;
2881     }
2882     uint64_t Kind = State.Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK;
2883     if (State.Flags != 0 &&
2884         (Kind != MachO::EXPORT_SYMBOL_FLAGS_KIND_REGULAR &&
2885          Kind != MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE &&
2886          Kind != MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL)) {
2887       *E = malformedError(
2888           "unsupported exported symbol kind: " + Twine((int)Kind) +
2889           " in flags: 0x" + Twine::utohexstr(State.Flags) +
2890           " in export trie data at node: 0x" + Twine::utohexstr(offset));
2891       moveToEnd();
2892       return;
2893     }
2894     if (State.Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT) {
2895       State.Address = 0;
2896       State.Other = readULEB128(State.Current, &error); // dylib ordinal
2897       if (error) {
2898         *E = malformedError("dylib ordinal of re-export " + Twine(error) +
2899                             " in export trie data at node: 0x" +
2900                             Twine::utohexstr(offset));
2901         moveToEnd();
2902         return;
2903       }
2904       if (O != nullptr) {
2905         if (State.Other > O->getLibraryCount()) {
2906           *E = malformedError(
2907               "bad library ordinal: " + Twine((int)State.Other) + " (max " +
2908               Twine((int)O->getLibraryCount()) +
2909               ") in export trie data at node: 0x" + Twine::utohexstr(offset));
2910           moveToEnd();
2911           return;
2912         }
2913       }
2914       State.ImportName = reinterpret_cast<const char*>(State.Current);
2915       if (*State.ImportName == '\0') {
2916         State.Current++;
2917       } else {
2918         const uint8_t *End = State.Current + 1;
2919         if (End >= Trie.end()) {
2920           *E = malformedError("import name of re-export in export trie data at "
2921                               "node: 0x" +
2922                               Twine::utohexstr(offset) +
2923                               " starts past end of trie data");
2924           moveToEnd();
2925           return;
2926         }
2927         while(*End != '\0' && End < Trie.end())
2928           End++;
2929         if (*End != '\0') {
2930           *E = malformedError("import name of re-export in export trie data at "
2931                               "node: 0x" +
2932                               Twine::utohexstr(offset) +
2933                               " extends past end of trie data");
2934           moveToEnd();
2935           return;
2936         }
2937         State.Current = End + 1;
2938       }
2939     } else {
2940       State.Address = readULEB128(State.Current, &error);
2941       if (error) {
2942         *E = malformedError("address " + Twine(error) +
2943                             " in export trie data at node: 0x" +
2944                             Twine::utohexstr(offset));
2945         moveToEnd();
2946         return;
2947       }
2948       if (State.Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER) {
2949         State.Other = readULEB128(State.Current, &error);
2950         if (error) {
2951           *E = malformedError("resolver of stub and resolver " + Twine(error) +
2952                               " in export trie data at node: 0x" +
2953                               Twine::utohexstr(offset));
2954           moveToEnd();
2955           return;
2956         }
2957       }
2958     }
2959     if(ExportStart + ExportInfoSize != State.Current) {
2960       *E = malformedError(
2961           "inconsistant export info size: 0x" +
2962           Twine::utohexstr(ExportInfoSize) + " where actual size was: 0x" +
2963           Twine::utohexstr(State.Current - ExportStart) +
2964           " in export trie data at node: 0x" + Twine::utohexstr(offset));
2965       moveToEnd();
2966       return;
2967     }
2968   }
2969   State.ChildCount = *Children;
2970   if (State.ChildCount != 0 && Children + 1 >= Trie.end()) {
2971     *E = malformedError("byte for count of childern in export trie data at "
2972                         "node: 0x" +
2973                         Twine::utohexstr(offset) +
2974                         " extends past end of trie data");
2975     moveToEnd();
2976     return;
2977   }
2978   State.Current = Children + 1;
2979   State.NextChildIndex = 0;
2980   State.ParentStringLength = CumulativeString.size();
2981   Stack.push_back(State);
2982 }
2983 
2984 void ExportEntry::pushDownUntilBottom() {
2985   ErrorAsOutParameter ErrAsOutParam(E);
2986   const char *error;
2987   while (Stack.back().NextChildIndex < Stack.back().ChildCount) {
2988     NodeState &Top = Stack.back();
2989     CumulativeString.resize(Top.ParentStringLength);
2990     for (;*Top.Current != 0 && Top.Current < Trie.end(); Top.Current++) {
2991       char C = *Top.Current;
2992       CumulativeString.push_back(C);
2993     }
2994     if (Top.Current >= Trie.end()) {
2995       *E = malformedError("edge sub-string in export trie data at node: 0x" +
2996                           Twine::utohexstr(Top.Start - Trie.begin()) +
2997                           " for child #" + Twine((int)Top.NextChildIndex) +
2998                           " extends past end of trie data");
2999       moveToEnd();
3000       return;
3001     }
3002     Top.Current += 1;
3003     uint64_t childNodeIndex = readULEB128(Top.Current, &error);
3004     if (error) {
3005       *E = malformedError("child node offset " + Twine(error) +
3006                           " in export trie data at node: 0x" +
3007                           Twine::utohexstr(Top.Start - Trie.begin()));
3008       moveToEnd();
3009       return;
3010     }
3011     for (const NodeState &node : nodes()) {
3012       if (node.Start == Trie.begin() + childNodeIndex){
3013         *E = malformedError("loop in childern in export trie data at node: 0x" +
3014                             Twine::utohexstr(Top.Start - Trie.begin()) +
3015                             " back to node: 0x" +
3016                             Twine::utohexstr(childNodeIndex));
3017         moveToEnd();
3018         return;
3019       }
3020     }
3021     Top.NextChildIndex += 1;
3022     pushNode(childNodeIndex);
3023     if (*E)
3024       return;
3025   }
3026   if (!Stack.back().IsExportNode) {
3027     *E = malformedError("node is not an export node in export trie data at "
3028                         "node: 0x" +
3029                         Twine::utohexstr(Stack.back().Start - Trie.begin()));
3030     moveToEnd();
3031     return;
3032   }
3033 }
3034 
3035 // We have a trie data structure and need a way to walk it that is compatible
3036 // with the C++ iterator model. The solution is a non-recursive depth first
3037 // traversal where the iterator contains a stack of parent nodes along with a
3038 // string that is the accumulation of all edge strings along the parent chain
3039 // to this point.
3040 //
3041 // There is one "export" node for each exported symbol.  But because some
3042 // symbols may be a prefix of another symbol (e.g. _dup and _dup2), an export
3043 // node may have child nodes too.
3044 //
3045 // The algorithm for moveNext() is to keep moving down the leftmost unvisited
3046 // child until hitting a node with no children (which is an export node or
3047 // else the trie is malformed). On the way down, each node is pushed on the
3048 // stack ivar.  If there is no more ways down, it pops up one and tries to go
3049 // down a sibling path until a childless node is reached.
3050 void ExportEntry::moveNext() {
3051   assert(!Stack.empty() && "ExportEntry::moveNext() with empty node stack");
3052   if (!Stack.back().IsExportNode) {
3053     *E = malformedError("node is not an export node in export trie data at "
3054                         "node: 0x" +
3055                         Twine::utohexstr(Stack.back().Start - Trie.begin()));
3056     moveToEnd();
3057     return;
3058   }
3059 
3060   Stack.pop_back();
3061   while (!Stack.empty()) {
3062     NodeState &Top = Stack.back();
3063     if (Top.NextChildIndex < Top.ChildCount) {
3064       pushDownUntilBottom();
3065       // Now at the next export node.
3066       return;
3067     } else {
3068       if (Top.IsExportNode) {
3069         // This node has no children but is itself an export node.
3070         CumulativeString.resize(Top.ParentStringLength);
3071         return;
3072       }
3073       Stack.pop_back();
3074     }
3075   }
3076   Done = true;
3077 }
3078 
3079 iterator_range<export_iterator>
3080 MachOObjectFile::exports(Error &E, ArrayRef<uint8_t> Trie,
3081                          const MachOObjectFile *O) {
3082   ExportEntry Start(&E, O, Trie);
3083   if (Trie.empty())
3084     Start.moveToEnd();
3085   else
3086     Start.moveToFirst();
3087 
3088   ExportEntry Finish(&E, O, Trie);
3089   Finish.moveToEnd();
3090 
3091   return make_range(export_iterator(Start), export_iterator(Finish));
3092 }
3093 
3094 iterator_range<export_iterator> MachOObjectFile::exports(Error &Err) const {
3095   return exports(Err, getDyldInfoExportsTrie(), this);
3096 }
3097 
3098 MachORebaseEntry::MachORebaseEntry(Error *E, const MachOObjectFile *O,
3099                                    ArrayRef<uint8_t> Bytes, bool is64Bit)
3100     : E(E), O(O), Opcodes(Bytes), Ptr(Bytes.begin()),
3101       PointerSize(is64Bit ? 8 : 4) {}
3102 
3103 void MachORebaseEntry::moveToFirst() {
3104   Ptr = Opcodes.begin();
3105   moveNext();
3106 }
3107 
3108 void MachORebaseEntry::moveToEnd() {
3109   Ptr = Opcodes.end();
3110   RemainingLoopCount = 0;
3111   Done = true;
3112 }
3113 
3114 void MachORebaseEntry::moveNext() {
3115   ErrorAsOutParameter ErrAsOutParam(E);
3116   // If in the middle of some loop, move to next rebasing in loop.
3117   SegmentOffset += AdvanceAmount;
3118   if (RemainingLoopCount) {
3119     --RemainingLoopCount;
3120     return;
3121   }
3122   // REBASE_OPCODE_DONE is only used for padding if we are not aligned to
3123   // pointer size. Therefore it is possible to reach the end without ever having
3124   // seen REBASE_OPCODE_DONE.
3125   if (Ptr == Opcodes.end()) {
3126     Done = true;
3127     return;
3128   }
3129   bool More = true;
3130   while (More) {
3131     // Parse next opcode and set up next loop.
3132     const uint8_t *OpcodeStart = Ptr;
3133     uint8_t Byte = *Ptr++;
3134     uint8_t ImmValue = Byte & MachO::REBASE_IMMEDIATE_MASK;
3135     uint8_t Opcode = Byte & MachO::REBASE_OPCODE_MASK;
3136     uint32_t Count, Skip;
3137     const char *error = nullptr;
3138     switch (Opcode) {
3139     case MachO::REBASE_OPCODE_DONE:
3140       More = false;
3141       Done = true;
3142       moveToEnd();
3143       DEBUG_WITH_TYPE("mach-o-rebase", dbgs() << "REBASE_OPCODE_DONE\n");
3144       break;
3145     case MachO::REBASE_OPCODE_SET_TYPE_IMM:
3146       RebaseType = ImmValue;
3147       if (RebaseType > MachO::REBASE_TYPE_TEXT_PCREL32) {
3148         *E = malformedError("for REBASE_OPCODE_SET_TYPE_IMM bad bind type: " +
3149                             Twine((int)RebaseType) + " for opcode at: 0x" +
3150                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3151         moveToEnd();
3152         return;
3153       }
3154       DEBUG_WITH_TYPE(
3155           "mach-o-rebase",
3156           dbgs() << "REBASE_OPCODE_SET_TYPE_IMM: "
3157                  << "RebaseType=" << (int) RebaseType << "\n");
3158       break;
3159     case MachO::REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:
3160       SegmentIndex = ImmValue;
3161       SegmentOffset = readULEB128(&error);
3162       if (error) {
3163         *E = malformedError("for REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB " +
3164                             Twine(error) + " for opcode at: 0x" +
3165                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3166         moveToEnd();
3167         return;
3168       }
3169       error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3170                                                PointerSize);
3171       if (error) {
3172         *E = malformedError("for REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB " +
3173                             Twine(error) + " for opcode at: 0x" +
3174                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3175         moveToEnd();
3176         return;
3177       }
3178       DEBUG_WITH_TYPE(
3179           "mach-o-rebase",
3180           dbgs() << "REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: "
3181                  << "SegmentIndex=" << SegmentIndex << ", "
3182                  << format("SegmentOffset=0x%06X", SegmentOffset)
3183                  << "\n");
3184       break;
3185     case MachO::REBASE_OPCODE_ADD_ADDR_ULEB:
3186       SegmentOffset += readULEB128(&error);
3187       if (error) {
3188         *E = malformedError("for REBASE_OPCODE_ADD_ADDR_ULEB " + Twine(error) +
3189                             " for opcode at: 0x" +
3190                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3191         moveToEnd();
3192         return;
3193       }
3194       error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3195                                                PointerSize);
3196       if (error) {
3197         *E = malformedError("for REBASE_OPCODE_ADD_ADDR_ULEB " + Twine(error) +
3198                             " for opcode at: 0x" +
3199                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3200         moveToEnd();
3201         return;
3202       }
3203       DEBUG_WITH_TYPE("mach-o-rebase",
3204                       dbgs() << "REBASE_OPCODE_ADD_ADDR_ULEB: "
3205                              << format("SegmentOffset=0x%06X",
3206                                        SegmentOffset) << "\n");
3207       break;
3208     case MachO::REBASE_OPCODE_ADD_ADDR_IMM_SCALED:
3209       error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3210                                                PointerSize);
3211       if (error) {
3212         *E = malformedError("for REBASE_OPCODE_ADD_ADDR_IMM_SCALED " +
3213                             Twine(error) + " for opcode at: 0x" +
3214                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3215         moveToEnd();
3216         return;
3217       }
3218       SegmentOffset += ImmValue * PointerSize;
3219       error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3220                                                PointerSize);
3221       if (error) {
3222         *E =
3223             malformedError("for REBASE_OPCODE_ADD_ADDR_IMM_SCALED "
3224                            " (after adding immediate times the pointer size) " +
3225                            Twine(error) + " for opcode at: 0x" +
3226                            Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3227         moveToEnd();
3228         return;
3229       }
3230       DEBUG_WITH_TYPE("mach-o-rebase",
3231                       dbgs() << "REBASE_OPCODE_ADD_ADDR_IMM_SCALED: "
3232                              << format("SegmentOffset=0x%06X",
3233                                        SegmentOffset) << "\n");
3234       break;
3235     case MachO::REBASE_OPCODE_DO_REBASE_IMM_TIMES:
3236       AdvanceAmount = PointerSize;
3237       Skip = 0;
3238       Count = ImmValue;
3239       if (ImmValue != 0)
3240         RemainingLoopCount = ImmValue - 1;
3241       else
3242         RemainingLoopCount = 0;
3243       error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3244                                                PointerSize, Count, Skip);
3245       if (error) {
3246         *E = malformedError("for REBASE_OPCODE_DO_REBASE_IMM_TIMES " +
3247                             Twine(error) + " for opcode at: 0x" +
3248                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3249         moveToEnd();
3250         return;
3251       }
3252       DEBUG_WITH_TYPE(
3253           "mach-o-rebase",
3254           dbgs() << "REBASE_OPCODE_DO_REBASE_IMM_TIMES: "
3255                  << format("SegmentOffset=0x%06X", SegmentOffset)
3256                  << ", AdvanceAmount=" << AdvanceAmount
3257                  << ", RemainingLoopCount=" << RemainingLoopCount
3258                  << "\n");
3259       return;
3260     case MachO::REBASE_OPCODE_DO_REBASE_ULEB_TIMES:
3261       AdvanceAmount = PointerSize;
3262       Skip = 0;
3263       Count = readULEB128(&error);
3264       if (error) {
3265         *E = malformedError("for REBASE_OPCODE_DO_REBASE_ULEB_TIMES " +
3266                             Twine(error) + " for opcode at: 0x" +
3267                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3268         moveToEnd();
3269         return;
3270       }
3271       if (Count != 0)
3272         RemainingLoopCount = Count - 1;
3273       else
3274         RemainingLoopCount = 0;
3275       error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3276                                                PointerSize, Count, Skip);
3277       if (error) {
3278         *E = malformedError("for REBASE_OPCODE_DO_REBASE_ULEB_TIMES " +
3279                             Twine(error) + " for opcode at: 0x" +
3280                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3281         moveToEnd();
3282         return;
3283       }
3284       DEBUG_WITH_TYPE(
3285           "mach-o-rebase",
3286           dbgs() << "REBASE_OPCODE_DO_REBASE_ULEB_TIMES: "
3287                  << format("SegmentOffset=0x%06X", SegmentOffset)
3288                  << ", AdvanceAmount=" << AdvanceAmount
3289                  << ", RemainingLoopCount=" << RemainingLoopCount
3290                  << "\n");
3291       return;
3292     case MachO::REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB:
3293       Skip = readULEB128(&error);
3294       if (error) {
3295         *E = malformedError("for REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB " +
3296                             Twine(error) + " for opcode at: 0x" +
3297                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3298         moveToEnd();
3299         return;
3300       }
3301       AdvanceAmount = Skip + PointerSize;
3302       Count = 1;
3303       RemainingLoopCount = 0;
3304       error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3305                                                PointerSize, Count, Skip);
3306       if (error) {
3307         *E = malformedError("for REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB " +
3308                             Twine(error) + " for opcode at: 0x" +
3309                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3310         moveToEnd();
3311         return;
3312       }
3313       DEBUG_WITH_TYPE(
3314           "mach-o-rebase",
3315           dbgs() << "REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB: "
3316                  << format("SegmentOffset=0x%06X", SegmentOffset)
3317                  << ", AdvanceAmount=" << AdvanceAmount
3318                  << ", RemainingLoopCount=" << RemainingLoopCount
3319                  << "\n");
3320       return;
3321     case MachO::REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB:
3322       Count = readULEB128(&error);
3323       if (error) {
3324         *E = malformedError("for REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_"
3325                             "ULEB " +
3326                             Twine(error) + " for opcode at: 0x" +
3327                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3328         moveToEnd();
3329         return;
3330       }
3331       if (Count != 0)
3332         RemainingLoopCount = Count - 1;
3333       else
3334         RemainingLoopCount = 0;
3335       Skip = readULEB128(&error);
3336       if (error) {
3337         *E = malformedError("for REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_"
3338                             "ULEB " +
3339                             Twine(error) + " for opcode at: 0x" +
3340                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3341         moveToEnd();
3342         return;
3343       }
3344       AdvanceAmount = Skip + PointerSize;
3345 
3346       error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3347                                                PointerSize, Count, Skip);
3348       if (error) {
3349         *E = malformedError("for REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_"
3350                             "ULEB " +
3351                             Twine(error) + " for opcode at: 0x" +
3352                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3353         moveToEnd();
3354         return;
3355       }
3356       DEBUG_WITH_TYPE(
3357           "mach-o-rebase",
3358           dbgs() << "REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB: "
3359                  << format("SegmentOffset=0x%06X", SegmentOffset)
3360                  << ", AdvanceAmount=" << AdvanceAmount
3361                  << ", RemainingLoopCount=" << RemainingLoopCount
3362                  << "\n");
3363       return;
3364     default:
3365       *E = malformedError("bad rebase info (bad opcode value 0x" +
3366                           Twine::utohexstr(Opcode) + " for opcode at: 0x" +
3367                           Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3368       moveToEnd();
3369       return;
3370     }
3371   }
3372 }
3373 
3374 uint64_t MachORebaseEntry::readULEB128(const char **error) {
3375   unsigned Count;
3376   uint64_t Result = decodeULEB128(Ptr, &Count, Opcodes.end(), error);
3377   Ptr += Count;
3378   if (Ptr > Opcodes.end())
3379     Ptr = Opcodes.end();
3380   return Result;
3381 }
3382 
3383 int32_t MachORebaseEntry::segmentIndex() const { return SegmentIndex; }
3384 
3385 uint64_t MachORebaseEntry::segmentOffset() const { return SegmentOffset; }
3386 
3387 StringRef MachORebaseEntry::typeName() const {
3388   switch (RebaseType) {
3389   case MachO::REBASE_TYPE_POINTER:
3390     return "pointer";
3391   case MachO::REBASE_TYPE_TEXT_ABSOLUTE32:
3392     return "text abs32";
3393   case MachO::REBASE_TYPE_TEXT_PCREL32:
3394     return "text rel32";
3395   }
3396   return "unknown";
3397 }
3398 
3399 // For use with the SegIndex of a checked Mach-O Rebase entry
3400 // to get the segment name.
3401 StringRef MachORebaseEntry::segmentName() const {
3402   return O->BindRebaseSegmentName(SegmentIndex);
3403 }
3404 
3405 // For use with a SegIndex,SegOffset pair from a checked Mach-O Rebase entry
3406 // to get the section name.
3407 StringRef MachORebaseEntry::sectionName() const {
3408   return O->BindRebaseSectionName(SegmentIndex, SegmentOffset);
3409 }
3410 
3411 // For use with a SegIndex,SegOffset pair from a checked Mach-O Rebase entry
3412 // to get the address.
3413 uint64_t MachORebaseEntry::address() const {
3414   return O->BindRebaseAddress(SegmentIndex, SegmentOffset);
3415 }
3416 
3417 bool MachORebaseEntry::operator==(const MachORebaseEntry &Other) const {
3418 #ifdef EXPENSIVE_CHECKS
3419   assert(Opcodes == Other.Opcodes && "compare iterators of different files");
3420 #else
3421   assert(Opcodes.data() == Other.Opcodes.data() && "compare iterators of different files");
3422 #endif
3423   return (Ptr == Other.Ptr) &&
3424          (RemainingLoopCount == Other.RemainingLoopCount) &&
3425          (Done == Other.Done);
3426 }
3427 
3428 iterator_range<rebase_iterator>
3429 MachOObjectFile::rebaseTable(Error &Err, MachOObjectFile *O,
3430                              ArrayRef<uint8_t> Opcodes, bool is64) {
3431   if (O->BindRebaseSectionTable == nullptr)
3432     O->BindRebaseSectionTable = llvm::make_unique<BindRebaseSegInfo>(O);
3433   MachORebaseEntry Start(&Err, O, Opcodes, is64);
3434   Start.moveToFirst();
3435 
3436   MachORebaseEntry Finish(&Err, O, Opcodes, is64);
3437   Finish.moveToEnd();
3438 
3439   return make_range(rebase_iterator(Start), rebase_iterator(Finish));
3440 }
3441 
3442 iterator_range<rebase_iterator> MachOObjectFile::rebaseTable(Error &Err) {
3443   return rebaseTable(Err, this, getDyldInfoRebaseOpcodes(), is64Bit());
3444 }
3445 
3446 MachOBindEntry::MachOBindEntry(Error *E, const MachOObjectFile *O,
3447                                ArrayRef<uint8_t> Bytes, bool is64Bit, Kind BK)
3448     : E(E), O(O), Opcodes(Bytes), Ptr(Bytes.begin()),
3449       PointerSize(is64Bit ? 8 : 4), TableKind(BK) {}
3450 
3451 void MachOBindEntry::moveToFirst() {
3452   Ptr = Opcodes.begin();
3453   moveNext();
3454 }
3455 
3456 void MachOBindEntry::moveToEnd() {
3457   Ptr = Opcodes.end();
3458   RemainingLoopCount = 0;
3459   Done = true;
3460 }
3461 
3462 void MachOBindEntry::moveNext() {
3463   ErrorAsOutParameter ErrAsOutParam(E);
3464   // If in the middle of some loop, move to next binding in loop.
3465   SegmentOffset += AdvanceAmount;
3466   if (RemainingLoopCount) {
3467     --RemainingLoopCount;
3468     return;
3469   }
3470   // BIND_OPCODE_DONE is only used for padding if we are not aligned to
3471   // pointer size. Therefore it is possible to reach the end without ever having
3472   // seen BIND_OPCODE_DONE.
3473   if (Ptr == Opcodes.end()) {
3474     Done = true;
3475     return;
3476   }
3477   bool More = true;
3478   while (More) {
3479     // Parse next opcode and set up next loop.
3480     const uint8_t *OpcodeStart = Ptr;
3481     uint8_t Byte = *Ptr++;
3482     uint8_t ImmValue = Byte & MachO::BIND_IMMEDIATE_MASK;
3483     uint8_t Opcode = Byte & MachO::BIND_OPCODE_MASK;
3484     int8_t SignExtended;
3485     const uint8_t *SymStart;
3486     uint32_t Count, Skip;
3487     const char *error = nullptr;
3488     switch (Opcode) {
3489     case MachO::BIND_OPCODE_DONE:
3490       if (TableKind == Kind::Lazy) {
3491         // Lazying bindings have a DONE opcode between entries.  Need to ignore
3492         // it to advance to next entry.  But need not if this is last entry.
3493         bool NotLastEntry = false;
3494         for (const uint8_t *P = Ptr; P < Opcodes.end(); ++P) {
3495           if (*P) {
3496             NotLastEntry = true;
3497           }
3498         }
3499         if (NotLastEntry)
3500           break;
3501       }
3502       More = false;
3503       moveToEnd();
3504       DEBUG_WITH_TYPE("mach-o-bind", dbgs() << "BIND_OPCODE_DONE\n");
3505       break;
3506     case MachO::BIND_OPCODE_SET_DYLIB_ORDINAL_IMM:
3507       if (TableKind == Kind::Weak) {
3508         *E = malformedError("BIND_OPCODE_SET_DYLIB_ORDINAL_IMM not allowed in "
3509                             "weak bind table for opcode at: 0x" +
3510                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3511         moveToEnd();
3512         return;
3513       }
3514       Ordinal = ImmValue;
3515       LibraryOrdinalSet = true;
3516       if (ImmValue > O->getLibraryCount()) {
3517         *E = malformedError("for BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB bad "
3518                             "library ordinal: " +
3519                             Twine((int)ImmValue) + " (max " +
3520                             Twine((int)O->getLibraryCount()) +
3521                             ") for opcode at: 0x" +
3522                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3523         moveToEnd();
3524         return;
3525       }
3526       DEBUG_WITH_TYPE(
3527           "mach-o-bind",
3528           dbgs() << "BIND_OPCODE_SET_DYLIB_ORDINAL_IMM: "
3529                  << "Ordinal=" << Ordinal << "\n");
3530       break;
3531     case MachO::BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB:
3532       if (TableKind == Kind::Weak) {
3533         *E = malformedError("BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB not allowed in "
3534                             "weak bind table for opcode at: 0x" +
3535                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3536         moveToEnd();
3537         return;
3538       }
3539       Ordinal = readULEB128(&error);
3540       LibraryOrdinalSet = true;
3541       if (error) {
3542         *E = malformedError("for BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB " +
3543                             Twine(error) + " for opcode at: 0x" +
3544                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3545         moveToEnd();
3546         return;
3547       }
3548       if (Ordinal > (int)O->getLibraryCount()) {
3549         *E = malformedError("for BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB bad "
3550                             "library ordinal: " +
3551                             Twine((int)Ordinal) + " (max " +
3552                             Twine((int)O->getLibraryCount()) +
3553                             ") for opcode at: 0x" +
3554                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3555         moveToEnd();
3556         return;
3557       }
3558       DEBUG_WITH_TYPE(
3559           "mach-o-bind",
3560           dbgs() << "BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB: "
3561                  << "Ordinal=" << Ordinal << "\n");
3562       break;
3563     case MachO::BIND_OPCODE_SET_DYLIB_SPECIAL_IMM:
3564       if (TableKind == Kind::Weak) {
3565         *E = malformedError("BIND_OPCODE_SET_DYLIB_SPECIAL_IMM not allowed in "
3566                             "weak bind table for opcode at: 0x" +
3567                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3568         moveToEnd();
3569         return;
3570       }
3571       if (ImmValue) {
3572         SignExtended = MachO::BIND_OPCODE_MASK | ImmValue;
3573         Ordinal = SignExtended;
3574         if (Ordinal < MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP) {
3575           *E = malformedError("for BIND_OPCODE_SET_DYLIB_SPECIAL_IMM unknown "
3576                               "special ordinal: " +
3577                               Twine((int)Ordinal) + " for opcode at: 0x" +
3578                               Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3579           moveToEnd();
3580           return;
3581         }
3582       } else
3583         Ordinal = 0;
3584       LibraryOrdinalSet = true;
3585       DEBUG_WITH_TYPE(
3586           "mach-o-bind",
3587           dbgs() << "BIND_OPCODE_SET_DYLIB_SPECIAL_IMM: "
3588                  << "Ordinal=" << Ordinal << "\n");
3589       break;
3590     case MachO::BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM:
3591       Flags = ImmValue;
3592       SymStart = Ptr;
3593       while (*Ptr && (Ptr < Opcodes.end())) {
3594         ++Ptr;
3595       }
3596       if (Ptr == Opcodes.end()) {
3597         *E = malformedError(
3598             "for BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM "
3599             "symbol name extends past opcodes for opcode at: 0x" +
3600             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3601         moveToEnd();
3602         return;
3603       }
3604       SymbolName = StringRef(reinterpret_cast<const char*>(SymStart),
3605                              Ptr-SymStart);
3606       ++Ptr;
3607       DEBUG_WITH_TYPE(
3608           "mach-o-bind",
3609           dbgs() << "BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM: "
3610                  << "SymbolName=" << SymbolName << "\n");
3611       if (TableKind == Kind::Weak) {
3612         if (ImmValue & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION)
3613           return;
3614       }
3615       break;
3616     case MachO::BIND_OPCODE_SET_TYPE_IMM:
3617       BindType = ImmValue;
3618       if (ImmValue > MachO::BIND_TYPE_TEXT_PCREL32) {
3619         *E = malformedError("for BIND_OPCODE_SET_TYPE_IMM bad bind type: " +
3620                             Twine((int)ImmValue) + " for opcode at: 0x" +
3621                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3622         moveToEnd();
3623         return;
3624       }
3625       DEBUG_WITH_TYPE(
3626           "mach-o-bind",
3627           dbgs() << "BIND_OPCODE_SET_TYPE_IMM: "
3628                  << "BindType=" << (int)BindType << "\n");
3629       break;
3630     case MachO::BIND_OPCODE_SET_ADDEND_SLEB:
3631       Addend = readSLEB128(&error);
3632       if (error) {
3633         *E = malformedError("for BIND_OPCODE_SET_ADDEND_SLEB " + Twine(error) +
3634                             " for opcode at: 0x" +
3635                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3636         moveToEnd();
3637         return;
3638       }
3639       DEBUG_WITH_TYPE(
3640           "mach-o-bind",
3641           dbgs() << "BIND_OPCODE_SET_ADDEND_SLEB: "
3642                  << "Addend=" << Addend << "\n");
3643       break;
3644     case MachO::BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:
3645       SegmentIndex = ImmValue;
3646       SegmentOffset = readULEB128(&error);
3647       if (error) {
3648         *E = malformedError("for BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB " +
3649                             Twine(error) + " for opcode at: 0x" +
3650                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3651         moveToEnd();
3652         return;
3653       }
3654       error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3655                                              PointerSize);
3656       if (error) {
3657         *E = malformedError("for BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB " +
3658                             Twine(error) + " for opcode at: 0x" +
3659                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3660         moveToEnd();
3661         return;
3662       }
3663       DEBUG_WITH_TYPE(
3664           "mach-o-bind",
3665           dbgs() << "BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: "
3666                  << "SegmentIndex=" << SegmentIndex << ", "
3667                  << format("SegmentOffset=0x%06X", SegmentOffset)
3668                  << "\n");
3669       break;
3670     case MachO::BIND_OPCODE_ADD_ADDR_ULEB:
3671       SegmentOffset += readULEB128(&error);
3672       if (error) {
3673         *E = malformedError("for BIND_OPCODE_ADD_ADDR_ULEB " + Twine(error) +
3674                             " for opcode at: 0x" +
3675                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3676         moveToEnd();
3677         return;
3678       }
3679       error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3680                                              PointerSize);
3681       if (error) {
3682         *E = malformedError("for BIND_OPCODE_ADD_ADDR_ULEB " + Twine(error) +
3683                             " for opcode at: 0x" +
3684                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3685         moveToEnd();
3686         return;
3687       }
3688       DEBUG_WITH_TYPE("mach-o-bind",
3689                       dbgs() << "BIND_OPCODE_ADD_ADDR_ULEB: "
3690                              << format("SegmentOffset=0x%06X",
3691                                        SegmentOffset) << "\n");
3692       break;
3693     case MachO::BIND_OPCODE_DO_BIND:
3694       AdvanceAmount = PointerSize;
3695       RemainingLoopCount = 0;
3696       error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3697                                              PointerSize);
3698       if (error) {
3699         *E = malformedError("for BIND_OPCODE_DO_BIND " + Twine(error) +
3700                             " for opcode at: 0x" +
3701                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3702         moveToEnd();
3703         return;
3704       }
3705       if (SymbolName == StringRef()) {
3706         *E = malformedError(
3707             "for BIND_OPCODE_DO_BIND missing preceding "
3708             "BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM for opcode at: 0x" +
3709             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3710         moveToEnd();
3711         return;
3712       }
3713       if (!LibraryOrdinalSet && TableKind != Kind::Weak) {
3714         *E =
3715             malformedError("for BIND_OPCODE_DO_BIND missing preceding "
3716                            "BIND_OPCODE_SET_DYLIB_ORDINAL_* for opcode at: 0x" +
3717                            Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3718         moveToEnd();
3719         return;
3720       }
3721       DEBUG_WITH_TYPE("mach-o-bind",
3722                       dbgs() << "BIND_OPCODE_DO_BIND: "
3723                              << format("SegmentOffset=0x%06X",
3724                                        SegmentOffset) << "\n");
3725       return;
3726      case MachO::BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB:
3727       if (TableKind == Kind::Lazy) {
3728         *E = malformedError("BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB not allowed in "
3729                             "lazy bind table for opcode at: 0x" +
3730                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3731         moveToEnd();
3732         return;
3733       }
3734       error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3735                                              PointerSize);
3736       if (error) {
3737         *E = malformedError("for BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB " +
3738                             Twine(error) + " for opcode at: 0x" +
3739                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3740         moveToEnd();
3741         return;
3742       }
3743       if (SymbolName == StringRef()) {
3744         *E = malformedError(
3745             "for BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB missing "
3746             "preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM for opcode "
3747             "at: 0x" +
3748             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3749         moveToEnd();
3750         return;
3751       }
3752       if (!LibraryOrdinalSet && TableKind != Kind::Weak) {
3753         *E = malformedError(
3754             "for BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB missing "
3755             "preceding BIND_OPCODE_SET_DYLIB_ORDINAL_* for opcode at: 0x" +
3756             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3757         moveToEnd();
3758         return;
3759       }
3760       AdvanceAmount = readULEB128(&error) + PointerSize;
3761       if (error) {
3762         *E = malformedError("for BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB " +
3763                             Twine(error) + " for opcode at: 0x" +
3764                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3765         moveToEnd();
3766         return;
3767       }
3768       // Note, this is not really an error until the next bind but make no sense
3769       // for a BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB to not be followed by another
3770       // bind operation.
3771       error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset +
3772                                             AdvanceAmount, PointerSize);
3773       if (error) {
3774         *E = malformedError("for BIND_OPCODE_ADD_ADDR_ULEB (after adding "
3775                             "ULEB) " +
3776                             Twine(error) + " for opcode at: 0x" +
3777                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3778         moveToEnd();
3779         return;
3780       }
3781       RemainingLoopCount = 0;
3782       DEBUG_WITH_TYPE(
3783           "mach-o-bind",
3784           dbgs() << "BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB: "
3785                  << format("SegmentOffset=0x%06X", SegmentOffset)
3786                  << ", AdvanceAmount=" << AdvanceAmount
3787                  << ", RemainingLoopCount=" << RemainingLoopCount
3788                  << "\n");
3789       return;
3790     case MachO::BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED:
3791       if (TableKind == Kind::Lazy) {
3792         *E = malformedError("BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED not "
3793                             "allowed in lazy bind table for opcode at: 0x" +
3794                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3795         moveToEnd();
3796         return;
3797       }
3798       error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3799                                              PointerSize);
3800       if (error) {
3801         *E = malformedError("for BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED " +
3802                             Twine(error) + " for opcode at: 0x" +
3803                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3804         moveToEnd();
3805         return;
3806       }
3807       if (SymbolName == StringRef()) {
3808         *E = malformedError(
3809             "for BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED "
3810             "missing preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM for "
3811             "opcode at: 0x" +
3812             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3813         moveToEnd();
3814         return;
3815       }
3816       if (!LibraryOrdinalSet && TableKind != Kind::Weak) {
3817         *E = malformedError(
3818             "for BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED "
3819             "missing preceding BIND_OPCODE_SET_DYLIB_ORDINAL_* for opcode "
3820             "at: 0x" +
3821             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3822         moveToEnd();
3823         return;
3824       }
3825       AdvanceAmount = ImmValue * PointerSize + PointerSize;
3826       RemainingLoopCount = 0;
3827       error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset +
3828                                              AdvanceAmount, PointerSize);
3829       if (error) {
3830         *E =
3831             malformedError("for BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED "
3832                            " (after adding immediate times the pointer size) " +
3833                            Twine(error) + " for opcode at: 0x" +
3834                            Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3835         moveToEnd();
3836         return;
3837       }
3838       DEBUG_WITH_TYPE("mach-o-bind",
3839                       dbgs()
3840                       << "BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED: "
3841                       << format("SegmentOffset=0x%06X", SegmentOffset) << "\n");
3842       return;
3843     case MachO::BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB:
3844       if (TableKind == Kind::Lazy) {
3845         *E = malformedError("BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB not "
3846                             "allowed in lazy bind table for opcode at: 0x" +
3847                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3848         moveToEnd();
3849         return;
3850       }
3851       Count = readULEB128(&error);
3852       if (Count != 0)
3853         RemainingLoopCount = Count - 1;
3854       else
3855         RemainingLoopCount = 0;
3856       if (error) {
3857         *E = malformedError("for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB "
3858                             " (count value) " +
3859                             Twine(error) + " for opcode at: 0x" +
3860                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3861         moveToEnd();
3862         return;
3863       }
3864       Skip = readULEB128(&error);
3865       AdvanceAmount = Skip + PointerSize;
3866       if (error) {
3867         *E = malformedError("for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB "
3868                             " (skip value) " +
3869                             Twine(error) + " for opcode at: 0x" +
3870                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3871         moveToEnd();
3872         return;
3873       }
3874       if (SymbolName == StringRef()) {
3875         *E = malformedError(
3876             "for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB "
3877             "missing preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM for "
3878             "opcode at: 0x" +
3879             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3880         moveToEnd();
3881         return;
3882       }
3883       if (!LibraryOrdinalSet && TableKind != Kind::Weak) {
3884         *E = malformedError(
3885             "for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB "
3886             "missing preceding BIND_OPCODE_SET_DYLIB_ORDINAL_* for opcode "
3887             "at: 0x" +
3888             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3889         moveToEnd();
3890         return;
3891       }
3892       error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3893                                              PointerSize, Count, Skip);
3894       if (error) {
3895         *E =
3896             malformedError("for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB " +
3897                            Twine(error) + " for opcode at: 0x" +
3898                            Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3899         moveToEnd();
3900         return;
3901       }
3902       DEBUG_WITH_TYPE(
3903           "mach-o-bind",
3904           dbgs() << "BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB: "
3905                  << format("SegmentOffset=0x%06X", SegmentOffset)
3906                  << ", AdvanceAmount=" << AdvanceAmount
3907                  << ", RemainingLoopCount=" << RemainingLoopCount
3908                  << "\n");
3909       return;
3910     default:
3911       *E = malformedError("bad bind info (bad opcode value 0x" +
3912                           Twine::utohexstr(Opcode) + " for opcode at: 0x" +
3913                           Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3914       moveToEnd();
3915       return;
3916     }
3917   }
3918 }
3919 
3920 uint64_t MachOBindEntry::readULEB128(const char **error) {
3921   unsigned Count;
3922   uint64_t Result = decodeULEB128(Ptr, &Count, Opcodes.end(), error);
3923   Ptr += Count;
3924   if (Ptr > Opcodes.end())
3925     Ptr = Opcodes.end();
3926   return Result;
3927 }
3928 
3929 int64_t MachOBindEntry::readSLEB128(const char **error) {
3930   unsigned Count;
3931   int64_t Result = decodeSLEB128(Ptr, &Count, Opcodes.end(), error);
3932   Ptr += Count;
3933   if (Ptr > Opcodes.end())
3934     Ptr = Opcodes.end();
3935   return Result;
3936 }
3937 
3938 int32_t MachOBindEntry::segmentIndex() const { return SegmentIndex; }
3939 
3940 uint64_t MachOBindEntry::segmentOffset() const { return SegmentOffset; }
3941 
3942 StringRef MachOBindEntry::typeName() const {
3943   switch (BindType) {
3944   case MachO::BIND_TYPE_POINTER:
3945     return "pointer";
3946   case MachO::BIND_TYPE_TEXT_ABSOLUTE32:
3947     return "text abs32";
3948   case MachO::BIND_TYPE_TEXT_PCREL32:
3949     return "text rel32";
3950   }
3951   return "unknown";
3952 }
3953 
3954 StringRef MachOBindEntry::symbolName() const { return SymbolName; }
3955 
3956 int64_t MachOBindEntry::addend() const { return Addend; }
3957 
3958 uint32_t MachOBindEntry::flags() const { return Flags; }
3959 
3960 int MachOBindEntry::ordinal() const { return Ordinal; }
3961 
3962 // For use with the SegIndex of a checked Mach-O Bind entry
3963 // to get the segment name.
3964 StringRef MachOBindEntry::segmentName() const {
3965   return O->BindRebaseSegmentName(SegmentIndex);
3966 }
3967 
3968 // For use with a SegIndex,SegOffset pair from a checked Mach-O Bind entry
3969 // to get the section name.
3970 StringRef MachOBindEntry::sectionName() const {
3971   return O->BindRebaseSectionName(SegmentIndex, SegmentOffset);
3972 }
3973 
3974 // For use with a SegIndex,SegOffset pair from a checked Mach-O Bind entry
3975 // to get the address.
3976 uint64_t MachOBindEntry::address() const {
3977   return O->BindRebaseAddress(SegmentIndex, SegmentOffset);
3978 }
3979 
3980 bool MachOBindEntry::operator==(const MachOBindEntry &Other) const {
3981 #ifdef EXPENSIVE_CHECKS
3982   assert(Opcodes == Other.Opcodes && "compare iterators of different files");
3983 #else
3984   assert(Opcodes.data() == Other.Opcodes.data() && "compare iterators of different files");
3985 #endif
3986   return (Ptr == Other.Ptr) &&
3987          (RemainingLoopCount == Other.RemainingLoopCount) &&
3988          (Done == Other.Done);
3989 }
3990 
3991 // Build table of sections so SegIndex/SegOffset pairs can be translated.
3992 BindRebaseSegInfo::BindRebaseSegInfo(const object::MachOObjectFile *Obj) {
3993   uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
3994   StringRef CurSegName;
3995   uint64_t CurSegAddress;
3996   for (const SectionRef &Section : Obj->sections()) {
3997     SectionInfo Info;
3998     Section.getName(Info.SectionName);
3999     Info.Address = Section.getAddress();
4000     Info.Size = Section.getSize();
4001     Info.SegmentName =
4002         Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
4003     if (!Info.SegmentName.equals(CurSegName)) {
4004       ++CurSegIndex;
4005       CurSegName = Info.SegmentName;
4006       CurSegAddress = Info.Address;
4007     }
4008     Info.SegmentIndex = CurSegIndex - 1;
4009     Info.OffsetInSegment = Info.Address - CurSegAddress;
4010     Info.SegmentStartAddress = CurSegAddress;
4011     Sections.push_back(Info);
4012   }
4013   MaxSegIndex = CurSegIndex;
4014 }
4015 
4016 // For use with a SegIndex, SegOffset, and PointerSize triple in
4017 // MachOBindEntry::moveNext() to validate a MachOBindEntry or MachORebaseEntry.
4018 //
4019 // Given a SegIndex, SegOffset, and PointerSize, verify a valid section exists
4020 // that fully contains a pointer at that location. Multiple fixups in a bind
4021 // (such as with the BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB opcode) can
4022 // be tested via the Count and Skip parameters.
4023 const char * BindRebaseSegInfo::checkSegAndOffsets(int32_t SegIndex,
4024                                                    uint64_t SegOffset,
4025                                                    uint8_t PointerSize,
4026                                                    uint32_t Count,
4027                                                    uint32_t Skip) {
4028   if (SegIndex == -1)
4029     return "missing preceding *_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB";
4030   if (SegIndex >= MaxSegIndex)
4031     return "bad segIndex (too large)";
4032   for (uint32_t i = 0; i < Count; ++i) {
4033     uint32_t Start = SegOffset + i * (PointerSize + Skip);
4034     uint32_t End = Start + PointerSize;
4035     bool Found = false;
4036     for (const SectionInfo &SI : Sections) {
4037       if (SI.SegmentIndex != SegIndex)
4038         continue;
4039       if ((SI.OffsetInSegment<=Start) && (Start<(SI.OffsetInSegment+SI.Size))) {
4040         if (End <= SI.OffsetInSegment + SI.Size) {
4041           Found = true;
4042           break;
4043         }
4044         else
4045           return "bad offset, extends beyond section boundary";
4046       }
4047     }
4048     if (!Found)
4049       return "bad offset, not in section";
4050   }
4051   return nullptr;
4052 }
4053 
4054 // For use with the SegIndex of a checked Mach-O Bind or Rebase entry
4055 // to get the segment name.
4056 StringRef BindRebaseSegInfo::segmentName(int32_t SegIndex) {
4057   for (const SectionInfo &SI : Sections) {
4058     if (SI.SegmentIndex == SegIndex)
4059       return SI.SegmentName;
4060   }
4061   llvm_unreachable("invalid SegIndex");
4062 }
4063 
4064 // For use with a SegIndex,SegOffset pair from a checked Mach-O Bind or Rebase
4065 // to get the SectionInfo.
4066 const BindRebaseSegInfo::SectionInfo &BindRebaseSegInfo::findSection(
4067                                      int32_t SegIndex, uint64_t SegOffset) {
4068   for (const SectionInfo &SI : Sections) {
4069     if (SI.SegmentIndex != SegIndex)
4070       continue;
4071     if (SI.OffsetInSegment > SegOffset)
4072       continue;
4073     if (SegOffset >= (SI.OffsetInSegment + SI.Size))
4074       continue;
4075     return SI;
4076   }
4077   llvm_unreachable("SegIndex and SegOffset not in any section");
4078 }
4079 
4080 // For use with a SegIndex,SegOffset pair from a checked Mach-O Bind or Rebase
4081 // entry to get the section name.
4082 StringRef BindRebaseSegInfo::sectionName(int32_t SegIndex,
4083                                          uint64_t SegOffset) {
4084   return findSection(SegIndex, SegOffset).SectionName;
4085 }
4086 
4087 // For use with a SegIndex,SegOffset pair from a checked Mach-O Bind or Rebase
4088 // entry to get the address.
4089 uint64_t BindRebaseSegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
4090   const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
4091   return SI.SegmentStartAddress + OffsetInSeg;
4092 }
4093 
4094 iterator_range<bind_iterator>
4095 MachOObjectFile::bindTable(Error &Err, MachOObjectFile *O,
4096                            ArrayRef<uint8_t> Opcodes, bool is64,
4097                            MachOBindEntry::Kind BKind) {
4098   if (O->BindRebaseSectionTable == nullptr)
4099     O->BindRebaseSectionTable = llvm::make_unique<BindRebaseSegInfo>(O);
4100   MachOBindEntry Start(&Err, O, Opcodes, is64, BKind);
4101   Start.moveToFirst();
4102 
4103   MachOBindEntry Finish(&Err, O, Opcodes, is64, BKind);
4104   Finish.moveToEnd();
4105 
4106   return make_range(bind_iterator(Start), bind_iterator(Finish));
4107 }
4108 
4109 iterator_range<bind_iterator> MachOObjectFile::bindTable(Error &Err) {
4110   return bindTable(Err, this, getDyldInfoBindOpcodes(), is64Bit(),
4111                    MachOBindEntry::Kind::Regular);
4112 }
4113 
4114 iterator_range<bind_iterator> MachOObjectFile::lazyBindTable(Error &Err) {
4115   return bindTable(Err, this, getDyldInfoLazyBindOpcodes(), is64Bit(),
4116                    MachOBindEntry::Kind::Lazy);
4117 }
4118 
4119 iterator_range<bind_iterator> MachOObjectFile::weakBindTable(Error &Err) {
4120   return bindTable(Err, this, getDyldInfoWeakBindOpcodes(), is64Bit(),
4121                    MachOBindEntry::Kind::Weak);
4122 }
4123 
4124 MachOObjectFile::load_command_iterator
4125 MachOObjectFile::begin_load_commands() const {
4126   return LoadCommands.begin();
4127 }
4128 
4129 MachOObjectFile::load_command_iterator
4130 MachOObjectFile::end_load_commands() const {
4131   return LoadCommands.end();
4132 }
4133 
4134 iterator_range<MachOObjectFile::load_command_iterator>
4135 MachOObjectFile::load_commands() const {
4136   return make_range(begin_load_commands(), end_load_commands());
4137 }
4138 
4139 StringRef
4140 MachOObjectFile::getSectionFinalSegmentName(DataRefImpl Sec) const {
4141   ArrayRef<char> Raw = getSectionRawFinalSegmentName(Sec);
4142   return parseSegmentOrSectionName(Raw.data());
4143 }
4144 
4145 ArrayRef<char>
4146 MachOObjectFile::getSectionRawName(DataRefImpl Sec) const {
4147   assert(Sec.d.a < Sections.size() && "Should have detected this earlier");
4148   const section_base *Base =
4149     reinterpret_cast<const section_base *>(Sections[Sec.d.a]);
4150   return makeArrayRef(Base->sectname);
4151 }
4152 
4153 ArrayRef<char>
4154 MachOObjectFile::getSectionRawFinalSegmentName(DataRefImpl Sec) const {
4155   assert(Sec.d.a < Sections.size() && "Should have detected this earlier");
4156   const section_base *Base =
4157     reinterpret_cast<const section_base *>(Sections[Sec.d.a]);
4158   return makeArrayRef(Base->segname);
4159 }
4160 
4161 bool
4162 MachOObjectFile::isRelocationScattered(const MachO::any_relocation_info &RE)
4163   const {
4164   if (getCPUType(*this) == MachO::CPU_TYPE_X86_64)
4165     return false;
4166   return getPlainRelocationAddress(RE) & MachO::R_SCATTERED;
4167 }
4168 
4169 unsigned MachOObjectFile::getPlainRelocationSymbolNum(
4170     const MachO::any_relocation_info &RE) const {
4171   if (isLittleEndian())
4172     return RE.r_word1 & 0xffffff;
4173   return RE.r_word1 >> 8;
4174 }
4175 
4176 bool MachOObjectFile::getPlainRelocationExternal(
4177     const MachO::any_relocation_info &RE) const {
4178   if (isLittleEndian())
4179     return (RE.r_word1 >> 27) & 1;
4180   return (RE.r_word1 >> 4) & 1;
4181 }
4182 
4183 bool MachOObjectFile::getScatteredRelocationScattered(
4184     const MachO::any_relocation_info &RE) const {
4185   return RE.r_word0 >> 31;
4186 }
4187 
4188 uint32_t MachOObjectFile::getScatteredRelocationValue(
4189     const MachO::any_relocation_info &RE) const {
4190   return RE.r_word1;
4191 }
4192 
4193 uint32_t MachOObjectFile::getScatteredRelocationType(
4194     const MachO::any_relocation_info &RE) const {
4195   return (RE.r_word0 >> 24) & 0xf;
4196 }
4197 
4198 unsigned MachOObjectFile::getAnyRelocationAddress(
4199     const MachO::any_relocation_info &RE) const {
4200   if (isRelocationScattered(RE))
4201     return getScatteredRelocationAddress(RE);
4202   return getPlainRelocationAddress(RE);
4203 }
4204 
4205 unsigned MachOObjectFile::getAnyRelocationPCRel(
4206     const MachO::any_relocation_info &RE) const {
4207   if (isRelocationScattered(RE))
4208     return getScatteredRelocationPCRel(RE);
4209   return getPlainRelocationPCRel(*this, RE);
4210 }
4211 
4212 unsigned MachOObjectFile::getAnyRelocationLength(
4213     const MachO::any_relocation_info &RE) const {
4214   if (isRelocationScattered(RE))
4215     return getScatteredRelocationLength(RE);
4216   return getPlainRelocationLength(*this, RE);
4217 }
4218 
4219 unsigned
4220 MachOObjectFile::getAnyRelocationType(
4221                                    const MachO::any_relocation_info &RE) const {
4222   if (isRelocationScattered(RE))
4223     return getScatteredRelocationType(RE);
4224   return getPlainRelocationType(*this, RE);
4225 }
4226 
4227 SectionRef
4228 MachOObjectFile::getAnyRelocationSection(
4229                                    const MachO::any_relocation_info &RE) const {
4230   if (isRelocationScattered(RE) || getPlainRelocationExternal(RE))
4231     return *section_end();
4232   unsigned SecNum = getPlainRelocationSymbolNum(RE);
4233   if (SecNum == MachO::R_ABS || SecNum > Sections.size())
4234     return *section_end();
4235   DataRefImpl DRI;
4236   DRI.d.a = SecNum - 1;
4237   return SectionRef(DRI, this);
4238 }
4239 
4240 MachO::section MachOObjectFile::getSection(DataRefImpl DRI) const {
4241   assert(DRI.d.a < Sections.size() && "Should have detected this earlier");
4242   return getStruct<MachO::section>(*this, Sections[DRI.d.a]);
4243 }
4244 
4245 MachO::section_64 MachOObjectFile::getSection64(DataRefImpl DRI) const {
4246   assert(DRI.d.a < Sections.size() && "Should have detected this earlier");
4247   return getStruct<MachO::section_64>(*this, Sections[DRI.d.a]);
4248 }
4249 
4250 MachO::section MachOObjectFile::getSection(const LoadCommandInfo &L,
4251                                            unsigned Index) const {
4252   const char *Sec = getSectionPtr(*this, L, Index);
4253   return getStruct<MachO::section>(*this, Sec);
4254 }
4255 
4256 MachO::section_64 MachOObjectFile::getSection64(const LoadCommandInfo &L,
4257                                                 unsigned Index) const {
4258   const char *Sec = getSectionPtr(*this, L, Index);
4259   return getStruct<MachO::section_64>(*this, Sec);
4260 }
4261 
4262 MachO::nlist
4263 MachOObjectFile::getSymbolTableEntry(DataRefImpl DRI) const {
4264   const char *P = reinterpret_cast<const char *>(DRI.p);
4265   return getStruct<MachO::nlist>(*this, P);
4266 }
4267 
4268 MachO::nlist_64
4269 MachOObjectFile::getSymbol64TableEntry(DataRefImpl DRI) const {
4270   const char *P = reinterpret_cast<const char *>(DRI.p);
4271   return getStruct<MachO::nlist_64>(*this, P);
4272 }
4273 
4274 MachO::linkedit_data_command
4275 MachOObjectFile::getLinkeditDataLoadCommand(const LoadCommandInfo &L) const {
4276   return getStruct<MachO::linkedit_data_command>(*this, L.Ptr);
4277 }
4278 
4279 MachO::segment_command
4280 MachOObjectFile::getSegmentLoadCommand(const LoadCommandInfo &L) const {
4281   return getStruct<MachO::segment_command>(*this, L.Ptr);
4282 }
4283 
4284 MachO::segment_command_64
4285 MachOObjectFile::getSegment64LoadCommand(const LoadCommandInfo &L) const {
4286   return getStruct<MachO::segment_command_64>(*this, L.Ptr);
4287 }
4288 
4289 MachO::linker_option_command
4290 MachOObjectFile::getLinkerOptionLoadCommand(const LoadCommandInfo &L) const {
4291   return getStruct<MachO::linker_option_command>(*this, L.Ptr);
4292 }
4293 
4294 MachO::version_min_command
4295 MachOObjectFile::getVersionMinLoadCommand(const LoadCommandInfo &L) const {
4296   return getStruct<MachO::version_min_command>(*this, L.Ptr);
4297 }
4298 
4299 MachO::note_command
4300 MachOObjectFile::getNoteLoadCommand(const LoadCommandInfo &L) const {
4301   return getStruct<MachO::note_command>(*this, L.Ptr);
4302 }
4303 
4304 MachO::build_version_command
4305 MachOObjectFile::getBuildVersionLoadCommand(const LoadCommandInfo &L) const {
4306   return getStruct<MachO::build_version_command>(*this, L.Ptr);
4307 }
4308 
4309 MachO::build_tool_version
4310 MachOObjectFile::getBuildToolVersion(unsigned index) const {
4311   return getStruct<MachO::build_tool_version>(*this, BuildTools[index]);
4312 }
4313 
4314 MachO::dylib_command
4315 MachOObjectFile::getDylibIDLoadCommand(const LoadCommandInfo &L) const {
4316   return getStruct<MachO::dylib_command>(*this, L.Ptr);
4317 }
4318 
4319 MachO::dyld_info_command
4320 MachOObjectFile::getDyldInfoLoadCommand(const LoadCommandInfo &L) const {
4321   return getStruct<MachO::dyld_info_command>(*this, L.Ptr);
4322 }
4323 
4324 MachO::dylinker_command
4325 MachOObjectFile::getDylinkerCommand(const LoadCommandInfo &L) const {
4326   return getStruct<MachO::dylinker_command>(*this, L.Ptr);
4327 }
4328 
4329 MachO::uuid_command
4330 MachOObjectFile::getUuidCommand(const LoadCommandInfo &L) const {
4331   return getStruct<MachO::uuid_command>(*this, L.Ptr);
4332 }
4333 
4334 MachO::rpath_command
4335 MachOObjectFile::getRpathCommand(const LoadCommandInfo &L) const {
4336   return getStruct<MachO::rpath_command>(*this, L.Ptr);
4337 }
4338 
4339 MachO::source_version_command
4340 MachOObjectFile::getSourceVersionCommand(const LoadCommandInfo &L) const {
4341   return getStruct<MachO::source_version_command>(*this, L.Ptr);
4342 }
4343 
4344 MachO::entry_point_command
4345 MachOObjectFile::getEntryPointCommand(const LoadCommandInfo &L) const {
4346   return getStruct<MachO::entry_point_command>(*this, L.Ptr);
4347 }
4348 
4349 MachO::encryption_info_command
4350 MachOObjectFile::getEncryptionInfoCommand(const LoadCommandInfo &L) const {
4351   return getStruct<MachO::encryption_info_command>(*this, L.Ptr);
4352 }
4353 
4354 MachO::encryption_info_command_64
4355 MachOObjectFile::getEncryptionInfoCommand64(const LoadCommandInfo &L) const {
4356   return getStruct<MachO::encryption_info_command_64>(*this, L.Ptr);
4357 }
4358 
4359 MachO::sub_framework_command
4360 MachOObjectFile::getSubFrameworkCommand(const LoadCommandInfo &L) const {
4361   return getStruct<MachO::sub_framework_command>(*this, L.Ptr);
4362 }
4363 
4364 MachO::sub_umbrella_command
4365 MachOObjectFile::getSubUmbrellaCommand(const LoadCommandInfo &L) const {
4366   return getStruct<MachO::sub_umbrella_command>(*this, L.Ptr);
4367 }
4368 
4369 MachO::sub_library_command
4370 MachOObjectFile::getSubLibraryCommand(const LoadCommandInfo &L) const {
4371   return getStruct<MachO::sub_library_command>(*this, L.Ptr);
4372 }
4373 
4374 MachO::sub_client_command
4375 MachOObjectFile::getSubClientCommand(const LoadCommandInfo &L) const {
4376   return getStruct<MachO::sub_client_command>(*this, L.Ptr);
4377 }
4378 
4379 MachO::routines_command
4380 MachOObjectFile::getRoutinesCommand(const LoadCommandInfo &L) const {
4381   return getStruct<MachO::routines_command>(*this, L.Ptr);
4382 }
4383 
4384 MachO::routines_command_64
4385 MachOObjectFile::getRoutinesCommand64(const LoadCommandInfo &L) const {
4386   return getStruct<MachO::routines_command_64>(*this, L.Ptr);
4387 }
4388 
4389 MachO::thread_command
4390 MachOObjectFile::getThreadCommand(const LoadCommandInfo &L) const {
4391   return getStruct<MachO::thread_command>(*this, L.Ptr);
4392 }
4393 
4394 MachO::any_relocation_info
4395 MachOObjectFile::getRelocation(DataRefImpl Rel) const {
4396   uint32_t Offset;
4397   if (getHeader().filetype == MachO::MH_OBJECT) {
4398     DataRefImpl Sec;
4399     Sec.d.a = Rel.d.a;
4400     if (is64Bit()) {
4401       MachO::section_64 Sect = getSection64(Sec);
4402       Offset = Sect.reloff;
4403     } else {
4404       MachO::section Sect = getSection(Sec);
4405       Offset = Sect.reloff;
4406     }
4407   } else {
4408     MachO::dysymtab_command DysymtabLoadCmd = getDysymtabLoadCommand();
4409     if (Rel.d.a == 0)
4410       Offset = DysymtabLoadCmd.extreloff; // Offset to the external relocations
4411     else
4412       Offset = DysymtabLoadCmd.locreloff; // Offset to the local relocations
4413   }
4414 
4415   auto P = reinterpret_cast<const MachO::any_relocation_info *>(
4416       getPtr(*this, Offset)) + Rel.d.b;
4417   return getStruct<MachO::any_relocation_info>(
4418       *this, reinterpret_cast<const char *>(P));
4419 }
4420 
4421 MachO::data_in_code_entry
4422 MachOObjectFile::getDice(DataRefImpl Rel) const {
4423   const char *P = reinterpret_cast<const char *>(Rel.p);
4424   return getStruct<MachO::data_in_code_entry>(*this, P);
4425 }
4426 
4427 const MachO::mach_header &MachOObjectFile::getHeader() const {
4428   return Header;
4429 }
4430 
4431 const MachO::mach_header_64 &MachOObjectFile::getHeader64() const {
4432   assert(is64Bit());
4433   return Header64;
4434 }
4435 
4436 uint32_t MachOObjectFile::getIndirectSymbolTableEntry(
4437                                              const MachO::dysymtab_command &DLC,
4438                                              unsigned Index) const {
4439   uint64_t Offset = DLC.indirectsymoff + Index * sizeof(uint32_t);
4440   return getStruct<uint32_t>(*this, getPtr(*this, Offset));
4441 }
4442 
4443 MachO::data_in_code_entry
4444 MachOObjectFile::getDataInCodeTableEntry(uint32_t DataOffset,
4445                                          unsigned Index) const {
4446   uint64_t Offset = DataOffset + Index * sizeof(MachO::data_in_code_entry);
4447   return getStruct<MachO::data_in_code_entry>(*this, getPtr(*this, Offset));
4448 }
4449 
4450 MachO::symtab_command MachOObjectFile::getSymtabLoadCommand() const {
4451   if (SymtabLoadCmd)
4452     return getStruct<MachO::symtab_command>(*this, SymtabLoadCmd);
4453 
4454   // If there is no SymtabLoadCmd return a load command with zero'ed fields.
4455   MachO::symtab_command Cmd;
4456   Cmd.cmd = MachO::LC_SYMTAB;
4457   Cmd.cmdsize = sizeof(MachO::symtab_command);
4458   Cmd.symoff = 0;
4459   Cmd.nsyms = 0;
4460   Cmd.stroff = 0;
4461   Cmd.strsize = 0;
4462   return Cmd;
4463 }
4464 
4465 MachO::dysymtab_command MachOObjectFile::getDysymtabLoadCommand() const {
4466   if (DysymtabLoadCmd)
4467     return getStruct<MachO::dysymtab_command>(*this, DysymtabLoadCmd);
4468 
4469   // If there is no DysymtabLoadCmd return a load command with zero'ed fields.
4470   MachO::dysymtab_command Cmd;
4471   Cmd.cmd = MachO::LC_DYSYMTAB;
4472   Cmd.cmdsize = sizeof(MachO::dysymtab_command);
4473   Cmd.ilocalsym = 0;
4474   Cmd.nlocalsym = 0;
4475   Cmd.iextdefsym = 0;
4476   Cmd.nextdefsym = 0;
4477   Cmd.iundefsym = 0;
4478   Cmd.nundefsym = 0;
4479   Cmd.tocoff = 0;
4480   Cmd.ntoc = 0;
4481   Cmd.modtaboff = 0;
4482   Cmd.nmodtab = 0;
4483   Cmd.extrefsymoff = 0;
4484   Cmd.nextrefsyms = 0;
4485   Cmd.indirectsymoff = 0;
4486   Cmd.nindirectsyms = 0;
4487   Cmd.extreloff = 0;
4488   Cmd.nextrel = 0;
4489   Cmd.locreloff = 0;
4490   Cmd.nlocrel = 0;
4491   return Cmd;
4492 }
4493 
4494 MachO::linkedit_data_command
4495 MachOObjectFile::getDataInCodeLoadCommand() const {
4496   if (DataInCodeLoadCmd)
4497     return getStruct<MachO::linkedit_data_command>(*this, DataInCodeLoadCmd);
4498 
4499   // If there is no DataInCodeLoadCmd return a load command with zero'ed fields.
4500   MachO::linkedit_data_command Cmd;
4501   Cmd.cmd = MachO::LC_DATA_IN_CODE;
4502   Cmd.cmdsize = sizeof(MachO::linkedit_data_command);
4503   Cmd.dataoff = 0;
4504   Cmd.datasize = 0;
4505   return Cmd;
4506 }
4507 
4508 MachO::linkedit_data_command
4509 MachOObjectFile::getLinkOptHintsLoadCommand() const {
4510   if (LinkOptHintsLoadCmd)
4511     return getStruct<MachO::linkedit_data_command>(*this, LinkOptHintsLoadCmd);
4512 
4513   // If there is no LinkOptHintsLoadCmd return a load command with zero'ed
4514   // fields.
4515   MachO::linkedit_data_command Cmd;
4516   Cmd.cmd = MachO::LC_LINKER_OPTIMIZATION_HINT;
4517   Cmd.cmdsize = sizeof(MachO::linkedit_data_command);
4518   Cmd.dataoff = 0;
4519   Cmd.datasize = 0;
4520   return Cmd;
4521 }
4522 
4523 ArrayRef<uint8_t> MachOObjectFile::getDyldInfoRebaseOpcodes() const {
4524   if (!DyldInfoLoadCmd)
4525     return None;
4526 
4527   auto DyldInfoOrErr =
4528     getStructOrErr<MachO::dyld_info_command>(*this, DyldInfoLoadCmd);
4529   if (!DyldInfoOrErr)
4530     return None;
4531   MachO::dyld_info_command DyldInfo = DyldInfoOrErr.get();
4532   const uint8_t *Ptr =
4533       reinterpret_cast<const uint8_t *>(getPtr(*this, DyldInfo.rebase_off));
4534   return makeArrayRef(Ptr, DyldInfo.rebase_size);
4535 }
4536 
4537 ArrayRef<uint8_t> MachOObjectFile::getDyldInfoBindOpcodes() const {
4538   if (!DyldInfoLoadCmd)
4539     return None;
4540 
4541   auto DyldInfoOrErr =
4542     getStructOrErr<MachO::dyld_info_command>(*this, DyldInfoLoadCmd);
4543   if (!DyldInfoOrErr)
4544     return None;
4545   MachO::dyld_info_command DyldInfo = DyldInfoOrErr.get();
4546   const uint8_t *Ptr =
4547       reinterpret_cast<const uint8_t *>(getPtr(*this, DyldInfo.bind_off));
4548   return makeArrayRef(Ptr, DyldInfo.bind_size);
4549 }
4550 
4551 ArrayRef<uint8_t> MachOObjectFile::getDyldInfoWeakBindOpcodes() const {
4552   if (!DyldInfoLoadCmd)
4553     return None;
4554 
4555   auto DyldInfoOrErr =
4556     getStructOrErr<MachO::dyld_info_command>(*this, DyldInfoLoadCmd);
4557   if (!DyldInfoOrErr)
4558     return None;
4559   MachO::dyld_info_command DyldInfo = DyldInfoOrErr.get();
4560   const uint8_t *Ptr =
4561       reinterpret_cast<const uint8_t *>(getPtr(*this, DyldInfo.weak_bind_off));
4562   return makeArrayRef(Ptr, DyldInfo.weak_bind_size);
4563 }
4564 
4565 ArrayRef<uint8_t> MachOObjectFile::getDyldInfoLazyBindOpcodes() const {
4566   if (!DyldInfoLoadCmd)
4567     return None;
4568 
4569   auto DyldInfoOrErr =
4570     getStructOrErr<MachO::dyld_info_command>(*this, DyldInfoLoadCmd);
4571   if (!DyldInfoOrErr)
4572     return None;
4573   MachO::dyld_info_command DyldInfo = DyldInfoOrErr.get();
4574   const uint8_t *Ptr =
4575       reinterpret_cast<const uint8_t *>(getPtr(*this, DyldInfo.lazy_bind_off));
4576   return makeArrayRef(Ptr, DyldInfo.lazy_bind_size);
4577 }
4578 
4579 ArrayRef<uint8_t> MachOObjectFile::getDyldInfoExportsTrie() const {
4580   if (!DyldInfoLoadCmd)
4581     return None;
4582 
4583   auto DyldInfoOrErr =
4584     getStructOrErr<MachO::dyld_info_command>(*this, DyldInfoLoadCmd);
4585   if (!DyldInfoOrErr)
4586     return None;
4587   MachO::dyld_info_command DyldInfo = DyldInfoOrErr.get();
4588   const uint8_t *Ptr =
4589       reinterpret_cast<const uint8_t *>(getPtr(*this, DyldInfo.export_off));
4590   return makeArrayRef(Ptr, DyldInfo.export_size);
4591 }
4592 
4593 ArrayRef<uint8_t> MachOObjectFile::getUuid() const {
4594   if (!UuidLoadCmd)
4595     return None;
4596   // Returning a pointer is fine as uuid doesn't need endian swapping.
4597   const char *Ptr = UuidLoadCmd + offsetof(MachO::uuid_command, uuid);
4598   return makeArrayRef(reinterpret_cast<const uint8_t *>(Ptr), 16);
4599 }
4600 
4601 StringRef MachOObjectFile::getStringTableData() const {
4602   MachO::symtab_command S = getSymtabLoadCommand();
4603   return getData().substr(S.stroff, S.strsize);
4604 }
4605 
4606 bool MachOObjectFile::is64Bit() const {
4607   return getType() == getMachOType(false, true) ||
4608     getType() == getMachOType(true, true);
4609 }
4610 
4611 void MachOObjectFile::ReadULEB128s(uint64_t Index,
4612                                    SmallVectorImpl<uint64_t> &Out) const {
4613   DataExtractor extractor(ObjectFile::getData(), true, 0);
4614 
4615   uint32_t offset = Index;
4616   uint64_t data = 0;
4617   while (uint64_t delta = extractor.getULEB128(&offset)) {
4618     data += delta;
4619     Out.push_back(data);
4620   }
4621 }
4622 
4623 bool MachOObjectFile::isRelocatableObject() const {
4624   return getHeader().filetype == MachO::MH_OBJECT;
4625 }
4626 
4627 Expected<std::unique_ptr<MachOObjectFile>>
4628 ObjectFile::createMachOObjectFile(MemoryBufferRef Buffer,
4629                                   uint32_t UniversalCputype,
4630                                   uint32_t UniversalIndex) {
4631   StringRef Magic = Buffer.getBuffer().slice(0, 4);
4632   if (Magic == "\xFE\xED\xFA\xCE")
4633     return MachOObjectFile::create(Buffer, false, false,
4634                                    UniversalCputype, UniversalIndex);
4635   if (Magic == "\xCE\xFA\xED\xFE")
4636     return MachOObjectFile::create(Buffer, true, false,
4637                                    UniversalCputype, UniversalIndex);
4638   if (Magic == "\xFE\xED\xFA\xCF")
4639     return MachOObjectFile::create(Buffer, false, true,
4640                                    UniversalCputype, UniversalIndex);
4641   if (Magic == "\xCF\xFA\xED\xFE")
4642     return MachOObjectFile::create(Buffer, true, true,
4643                                    UniversalCputype, UniversalIndex);
4644   return make_error<GenericBinaryError>("Unrecognized MachO magic number",
4645                                         object_error::invalid_file_type);
4646 }
4647 
4648 StringRef MachOObjectFile::mapDebugSectionName(StringRef Name) const {
4649   return StringSwitch<StringRef>(Name)
4650       .Case("debug_str_offs", "debug_str_offsets")
4651       .Default(Name);
4652 }
4653