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   for (const SectionRef &Section : sections()) {
1990     auto NameOrErr = Section.getName();
1991     if (!NameOrErr)
1992       return NameOrErr.takeError();
1993     if (*NameOrErr == SectionName)
1994       return Section;
1995   }
1996   return errorCodeToError(object_error::parse_failed);
1997 }
1998 
1999 bool MachOObjectFile::isSectionCompressed(DataRefImpl Sec) const {
2000   return false;
2001 }
2002 
2003 bool MachOObjectFile::isSectionText(DataRefImpl Sec) const {
2004   uint32_t Flags = getSectionFlags(*this, Sec);
2005   return Flags & MachO::S_ATTR_PURE_INSTRUCTIONS;
2006 }
2007 
2008 bool MachOObjectFile::isSectionData(DataRefImpl Sec) const {
2009   uint32_t Flags = getSectionFlags(*this, Sec);
2010   unsigned SectionType = Flags & MachO::SECTION_TYPE;
2011   return !(Flags & MachO::S_ATTR_PURE_INSTRUCTIONS) &&
2012          !(SectionType == MachO::S_ZEROFILL ||
2013            SectionType == MachO::S_GB_ZEROFILL);
2014 }
2015 
2016 bool MachOObjectFile::isSectionBSS(DataRefImpl Sec) const {
2017   uint32_t Flags = getSectionFlags(*this, Sec);
2018   unsigned SectionType = Flags & MachO::SECTION_TYPE;
2019   return !(Flags & MachO::S_ATTR_PURE_INSTRUCTIONS) &&
2020          (SectionType == MachO::S_ZEROFILL ||
2021           SectionType == MachO::S_GB_ZEROFILL);
2022 }
2023 
2024 unsigned MachOObjectFile::getSectionID(SectionRef Sec) const {
2025   return Sec.getRawDataRefImpl().d.a;
2026 }
2027 
2028 bool MachOObjectFile::isSectionVirtual(DataRefImpl Sec) const {
2029   uint32_t Flags = getSectionFlags(*this, Sec);
2030   unsigned SectionType = Flags & MachO::SECTION_TYPE;
2031   return SectionType == MachO::S_ZEROFILL ||
2032          SectionType == MachO::S_GB_ZEROFILL;
2033 }
2034 
2035 bool MachOObjectFile::isSectionBitcode(DataRefImpl Sec) const {
2036   StringRef SegmentName = getSectionFinalSegmentName(Sec);
2037   if (Expected<StringRef> NameOrErr = getSectionName(Sec))
2038     return (SegmentName == "__LLVM" && *NameOrErr == "__bitcode");
2039   return false;
2040 }
2041 
2042 bool MachOObjectFile::isSectionStripped(DataRefImpl Sec) const {
2043   if (is64Bit())
2044     return getSection64(Sec).offset == 0;
2045   return getSection(Sec).offset == 0;
2046 }
2047 
2048 relocation_iterator MachOObjectFile::section_rel_begin(DataRefImpl Sec) const {
2049   DataRefImpl Ret;
2050   Ret.d.a = Sec.d.a;
2051   Ret.d.b = 0;
2052   return relocation_iterator(RelocationRef(Ret, this));
2053 }
2054 
2055 relocation_iterator
2056 MachOObjectFile::section_rel_end(DataRefImpl Sec) const {
2057   uint32_t Num;
2058   if (is64Bit()) {
2059     MachO::section_64 Sect = getSection64(Sec);
2060     Num = Sect.nreloc;
2061   } else {
2062     MachO::section Sect = getSection(Sec);
2063     Num = Sect.nreloc;
2064   }
2065 
2066   DataRefImpl Ret;
2067   Ret.d.a = Sec.d.a;
2068   Ret.d.b = Num;
2069   return relocation_iterator(RelocationRef(Ret, this));
2070 }
2071 
2072 relocation_iterator MachOObjectFile::extrel_begin() const {
2073   DataRefImpl Ret;
2074   // for DYSYMTAB symbols, Ret.d.a == 0 for external relocations
2075   Ret.d.a = 0; // Would normally be a section index.
2076   Ret.d.b = 0; // Index into the external relocations
2077   return relocation_iterator(RelocationRef(Ret, this));
2078 }
2079 
2080 relocation_iterator MachOObjectFile::extrel_end() const {
2081   MachO::dysymtab_command DysymtabLoadCmd = getDysymtabLoadCommand();
2082   DataRefImpl Ret;
2083   // for DYSYMTAB symbols, Ret.d.a == 0 for external relocations
2084   Ret.d.a = 0; // Would normally be a section index.
2085   Ret.d.b = DysymtabLoadCmd.nextrel; // Index into the external relocations
2086   return relocation_iterator(RelocationRef(Ret, this));
2087 }
2088 
2089 relocation_iterator MachOObjectFile::locrel_begin() const {
2090   DataRefImpl Ret;
2091   // for DYSYMTAB symbols, Ret.d.a == 1 for local relocations
2092   Ret.d.a = 1; // Would normally be a section index.
2093   Ret.d.b = 0; // Index into the local relocations
2094   return relocation_iterator(RelocationRef(Ret, this));
2095 }
2096 
2097 relocation_iterator MachOObjectFile::locrel_end() const {
2098   MachO::dysymtab_command DysymtabLoadCmd = getDysymtabLoadCommand();
2099   DataRefImpl Ret;
2100   // for DYSYMTAB symbols, Ret.d.a == 1 for local relocations
2101   Ret.d.a = 1; // Would normally be a section index.
2102   Ret.d.b = DysymtabLoadCmd.nlocrel; // Index into the local relocations
2103   return relocation_iterator(RelocationRef(Ret, this));
2104 }
2105 
2106 void MachOObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
2107   ++Rel.d.b;
2108 }
2109 
2110 uint64_t MachOObjectFile::getRelocationOffset(DataRefImpl Rel) const {
2111   assert((getHeader().filetype == MachO::MH_OBJECT ||
2112           getHeader().filetype == MachO::MH_KEXT_BUNDLE) &&
2113          "Only implemented for MH_OBJECT && MH_KEXT_BUNDLE");
2114   MachO::any_relocation_info RE = getRelocation(Rel);
2115   return getAnyRelocationAddress(RE);
2116 }
2117 
2118 symbol_iterator
2119 MachOObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
2120   MachO::any_relocation_info RE = getRelocation(Rel);
2121   if (isRelocationScattered(RE))
2122     return symbol_end();
2123 
2124   uint32_t SymbolIdx = getPlainRelocationSymbolNum(RE);
2125   bool isExtern = getPlainRelocationExternal(RE);
2126   if (!isExtern)
2127     return symbol_end();
2128 
2129   MachO::symtab_command S = getSymtabLoadCommand();
2130   unsigned SymbolTableEntrySize = is64Bit() ?
2131     sizeof(MachO::nlist_64) :
2132     sizeof(MachO::nlist);
2133   uint64_t Offset = S.symoff + SymbolIdx * SymbolTableEntrySize;
2134   DataRefImpl Sym;
2135   Sym.p = reinterpret_cast<uintptr_t>(getPtr(*this, Offset));
2136   return symbol_iterator(SymbolRef(Sym, this));
2137 }
2138 
2139 section_iterator
2140 MachOObjectFile::getRelocationSection(DataRefImpl Rel) const {
2141   return section_iterator(getAnyRelocationSection(getRelocation(Rel)));
2142 }
2143 
2144 uint64_t MachOObjectFile::getRelocationType(DataRefImpl Rel) const {
2145   MachO::any_relocation_info RE = getRelocation(Rel);
2146   return getAnyRelocationType(RE);
2147 }
2148 
2149 void MachOObjectFile::getRelocationTypeName(
2150     DataRefImpl Rel, SmallVectorImpl<char> &Result) const {
2151   StringRef res;
2152   uint64_t RType = getRelocationType(Rel);
2153 
2154   unsigned Arch = this->getArch();
2155 
2156   switch (Arch) {
2157     case Triple::x86: {
2158       static const char *const Table[] =  {
2159         "GENERIC_RELOC_VANILLA",
2160         "GENERIC_RELOC_PAIR",
2161         "GENERIC_RELOC_SECTDIFF",
2162         "GENERIC_RELOC_PB_LA_PTR",
2163         "GENERIC_RELOC_LOCAL_SECTDIFF",
2164         "GENERIC_RELOC_TLV" };
2165 
2166       if (RType > 5)
2167         res = "Unknown";
2168       else
2169         res = Table[RType];
2170       break;
2171     }
2172     case Triple::x86_64: {
2173       static const char *const Table[] =  {
2174         "X86_64_RELOC_UNSIGNED",
2175         "X86_64_RELOC_SIGNED",
2176         "X86_64_RELOC_BRANCH",
2177         "X86_64_RELOC_GOT_LOAD",
2178         "X86_64_RELOC_GOT",
2179         "X86_64_RELOC_SUBTRACTOR",
2180         "X86_64_RELOC_SIGNED_1",
2181         "X86_64_RELOC_SIGNED_2",
2182         "X86_64_RELOC_SIGNED_4",
2183         "X86_64_RELOC_TLV" };
2184 
2185       if (RType > 9)
2186         res = "Unknown";
2187       else
2188         res = Table[RType];
2189       break;
2190     }
2191     case Triple::arm: {
2192       static const char *const Table[] =  {
2193         "ARM_RELOC_VANILLA",
2194         "ARM_RELOC_PAIR",
2195         "ARM_RELOC_SECTDIFF",
2196         "ARM_RELOC_LOCAL_SECTDIFF",
2197         "ARM_RELOC_PB_LA_PTR",
2198         "ARM_RELOC_BR24",
2199         "ARM_THUMB_RELOC_BR22",
2200         "ARM_THUMB_32BIT_BRANCH",
2201         "ARM_RELOC_HALF",
2202         "ARM_RELOC_HALF_SECTDIFF" };
2203 
2204       if (RType > 9)
2205         res = "Unknown";
2206       else
2207         res = Table[RType];
2208       break;
2209     }
2210     case Triple::aarch64:
2211     case Triple::aarch64_32: {
2212       static const char *const Table[] = {
2213         "ARM64_RELOC_UNSIGNED",           "ARM64_RELOC_SUBTRACTOR",
2214         "ARM64_RELOC_BRANCH26",           "ARM64_RELOC_PAGE21",
2215         "ARM64_RELOC_PAGEOFF12",          "ARM64_RELOC_GOT_LOAD_PAGE21",
2216         "ARM64_RELOC_GOT_LOAD_PAGEOFF12", "ARM64_RELOC_POINTER_TO_GOT",
2217         "ARM64_RELOC_TLVP_LOAD_PAGE21",   "ARM64_RELOC_TLVP_LOAD_PAGEOFF12",
2218         "ARM64_RELOC_ADDEND"
2219       };
2220 
2221       if (RType >= array_lengthof(Table))
2222         res = "Unknown";
2223       else
2224         res = Table[RType];
2225       break;
2226     }
2227     case Triple::ppc: {
2228       static const char *const Table[] =  {
2229         "PPC_RELOC_VANILLA",
2230         "PPC_RELOC_PAIR",
2231         "PPC_RELOC_BR14",
2232         "PPC_RELOC_BR24",
2233         "PPC_RELOC_HI16",
2234         "PPC_RELOC_LO16",
2235         "PPC_RELOC_HA16",
2236         "PPC_RELOC_LO14",
2237         "PPC_RELOC_SECTDIFF",
2238         "PPC_RELOC_PB_LA_PTR",
2239         "PPC_RELOC_HI16_SECTDIFF",
2240         "PPC_RELOC_LO16_SECTDIFF",
2241         "PPC_RELOC_HA16_SECTDIFF",
2242         "PPC_RELOC_JBSR",
2243         "PPC_RELOC_LO14_SECTDIFF",
2244         "PPC_RELOC_LOCAL_SECTDIFF" };
2245 
2246       if (RType > 15)
2247         res = "Unknown";
2248       else
2249         res = Table[RType];
2250       break;
2251     }
2252     case Triple::UnknownArch:
2253       res = "Unknown";
2254       break;
2255   }
2256   Result.append(res.begin(), res.end());
2257 }
2258 
2259 uint8_t MachOObjectFile::getRelocationLength(DataRefImpl Rel) const {
2260   MachO::any_relocation_info RE = getRelocation(Rel);
2261   return getAnyRelocationLength(RE);
2262 }
2263 
2264 //
2265 // guessLibraryShortName() is passed a name of a dynamic library and returns a
2266 // guess on what the short name is.  Then name is returned as a substring of the
2267 // StringRef Name passed in.  The name of the dynamic library is recognized as
2268 // a framework if it has one of the two following forms:
2269 //      Foo.framework/Versions/A/Foo
2270 //      Foo.framework/Foo
2271 // Where A and Foo can be any string.  And may contain a trailing suffix
2272 // starting with an underbar.  If the Name is recognized as a framework then
2273 // isFramework is set to true else it is set to false.  If the Name has a
2274 // suffix then Suffix is set to the substring in Name that contains the suffix
2275 // else it is set to a NULL StringRef.
2276 //
2277 // The Name of the dynamic library is recognized as a library name if it has
2278 // one of the two following forms:
2279 //      libFoo.A.dylib
2280 //      libFoo.dylib
2281 //
2282 // The library may have a suffix trailing the name Foo of the form:
2283 //      libFoo_profile.A.dylib
2284 //      libFoo_profile.dylib
2285 // These dyld image suffixes are separated from the short name by a '_'
2286 // character. Because the '_' character is commonly used to separate words in
2287 // filenames guessLibraryShortName() cannot reliably separate a dylib's short
2288 // name from an arbitrary image suffix; imagine if both the short name and the
2289 // suffix contains an '_' character! To better deal with this ambiguity,
2290 // guessLibraryShortName() will recognize only "_debug" and "_profile" as valid
2291 // Suffix values. Calling code needs to be tolerant of guessLibraryShortName()
2292 // guessing incorrectly.
2293 //
2294 // The Name of the dynamic library is also recognized as a library name if it
2295 // has the following form:
2296 //      Foo.qtx
2297 //
2298 // If the Name of the dynamic library is none of the forms above then a NULL
2299 // StringRef is returned.
2300 StringRef MachOObjectFile::guessLibraryShortName(StringRef Name,
2301                                                  bool &isFramework,
2302                                                  StringRef &Suffix) {
2303   StringRef Foo, F, DotFramework, V, Dylib, Lib, Dot, Qtx;
2304   size_t a, b, c, d, Idx;
2305 
2306   isFramework = false;
2307   Suffix = StringRef();
2308 
2309   // Pull off the last component and make Foo point to it
2310   a = Name.rfind('/');
2311   if (a == Name.npos || a == 0)
2312     goto guess_library;
2313   Foo = Name.slice(a+1, Name.npos);
2314 
2315   // Look for a suffix starting with a '_'
2316   Idx = Foo.rfind('_');
2317   if (Idx != Foo.npos && Foo.size() >= 2) {
2318     Suffix = Foo.slice(Idx, Foo.npos);
2319     if (Suffix != "_debug" && Suffix != "_profile")
2320       Suffix = StringRef();
2321     else
2322       Foo = Foo.slice(0, Idx);
2323   }
2324 
2325   // First look for the form Foo.framework/Foo
2326   b = Name.rfind('/', a);
2327   if (b == Name.npos)
2328     Idx = 0;
2329   else
2330     Idx = b+1;
2331   F = Name.slice(Idx, Idx + Foo.size());
2332   DotFramework = Name.slice(Idx + Foo.size(),
2333                             Idx + Foo.size() + sizeof(".framework/")-1);
2334   if (F == Foo && DotFramework == ".framework/") {
2335     isFramework = true;
2336     return Foo;
2337   }
2338 
2339   // Next look for the form Foo.framework/Versions/A/Foo
2340   if (b == Name.npos)
2341     goto guess_library;
2342   c =  Name.rfind('/', b);
2343   if (c == Name.npos || c == 0)
2344     goto guess_library;
2345   V = Name.slice(c+1, Name.npos);
2346   if (!V.startswith("Versions/"))
2347     goto guess_library;
2348   d =  Name.rfind('/', c);
2349   if (d == Name.npos)
2350     Idx = 0;
2351   else
2352     Idx = d+1;
2353   F = Name.slice(Idx, Idx + Foo.size());
2354   DotFramework = Name.slice(Idx + Foo.size(),
2355                             Idx + Foo.size() + sizeof(".framework/")-1);
2356   if (F == Foo && DotFramework == ".framework/") {
2357     isFramework = true;
2358     return Foo;
2359   }
2360 
2361 guess_library:
2362   // pull off the suffix after the "." and make a point to it
2363   a = Name.rfind('.');
2364   if (a == Name.npos || a == 0)
2365     return StringRef();
2366   Dylib = Name.slice(a, Name.npos);
2367   if (Dylib != ".dylib")
2368     goto guess_qtx;
2369 
2370   // First pull off the version letter for the form Foo.A.dylib if any.
2371   if (a >= 3) {
2372     Dot = Name.slice(a-2, a-1);
2373     if (Dot == ".")
2374       a = a - 2;
2375   }
2376 
2377   b = Name.rfind('/', a);
2378   if (b == Name.npos)
2379     b = 0;
2380   else
2381     b = b+1;
2382   // ignore any suffix after an underbar like Foo_profile.A.dylib
2383   Idx = Name.rfind('_');
2384   if (Idx != Name.npos && Idx != b) {
2385     Lib = Name.slice(b, Idx);
2386     Suffix = Name.slice(Idx, a);
2387     if (Suffix != "_debug" && Suffix != "_profile") {
2388       Suffix = StringRef();
2389       Lib = Name.slice(b, a);
2390     }
2391   }
2392   else
2393     Lib = Name.slice(b, a);
2394   // There are incorrect library names of the form:
2395   // libATS.A_profile.dylib so check for these.
2396   if (Lib.size() >= 3) {
2397     Dot = Lib.slice(Lib.size()-2, Lib.size()-1);
2398     if (Dot == ".")
2399       Lib = Lib.slice(0, Lib.size()-2);
2400   }
2401   return Lib;
2402 
2403 guess_qtx:
2404   Qtx = Name.slice(a, Name.npos);
2405   if (Qtx != ".qtx")
2406     return StringRef();
2407   b = Name.rfind('/', a);
2408   if (b == Name.npos)
2409     Lib = Name.slice(0, a);
2410   else
2411     Lib = Name.slice(b+1, a);
2412   // There are library names of the form: QT.A.qtx so check for these.
2413   if (Lib.size() >= 3) {
2414     Dot = Lib.slice(Lib.size()-2, Lib.size()-1);
2415     if (Dot == ".")
2416       Lib = Lib.slice(0, Lib.size()-2);
2417   }
2418   return Lib;
2419 }
2420 
2421 // getLibraryShortNameByIndex() is used to get the short name of the library
2422 // for an undefined symbol in a linked Mach-O binary that was linked with the
2423 // normal two-level namespace default (that is MH_TWOLEVEL in the header).
2424 // It is passed the index (0 - based) of the library as translated from
2425 // GET_LIBRARY_ORDINAL (1 - based).
2426 std::error_code MachOObjectFile::getLibraryShortNameByIndex(unsigned Index,
2427                                                          StringRef &Res) const {
2428   if (Index >= Libraries.size())
2429     return object_error::parse_failed;
2430 
2431   // If the cache of LibrariesShortNames is not built up do that first for
2432   // all the Libraries.
2433   if (LibrariesShortNames.size() == 0) {
2434     for (unsigned i = 0; i < Libraries.size(); i++) {
2435       auto CommandOrErr =
2436         getStructOrErr<MachO::dylib_command>(*this, Libraries[i]);
2437       if (!CommandOrErr)
2438         return object_error::parse_failed;
2439       MachO::dylib_command D = CommandOrErr.get();
2440       if (D.dylib.name >= D.cmdsize)
2441         return object_error::parse_failed;
2442       const char *P = (const char *)(Libraries[i]) + D.dylib.name;
2443       StringRef Name = StringRef(P);
2444       if (D.dylib.name+Name.size() >= D.cmdsize)
2445         return object_error::parse_failed;
2446       StringRef Suffix;
2447       bool isFramework;
2448       StringRef shortName = guessLibraryShortName(Name, isFramework, Suffix);
2449       if (shortName.empty())
2450         LibrariesShortNames.push_back(Name);
2451       else
2452         LibrariesShortNames.push_back(shortName);
2453     }
2454   }
2455 
2456   Res = LibrariesShortNames[Index];
2457   return std::error_code();
2458 }
2459 
2460 uint32_t MachOObjectFile::getLibraryCount() const {
2461   return Libraries.size();
2462 }
2463 
2464 section_iterator
2465 MachOObjectFile::getRelocationRelocatedSection(relocation_iterator Rel) const {
2466   DataRefImpl Sec;
2467   Sec.d.a = Rel->getRawDataRefImpl().d.a;
2468   return section_iterator(SectionRef(Sec, this));
2469 }
2470 
2471 basic_symbol_iterator MachOObjectFile::symbol_begin() const {
2472   DataRefImpl DRI;
2473   MachO::symtab_command Symtab = getSymtabLoadCommand();
2474   if (!SymtabLoadCmd || Symtab.nsyms == 0)
2475     return basic_symbol_iterator(SymbolRef(DRI, this));
2476 
2477   return getSymbolByIndex(0);
2478 }
2479 
2480 basic_symbol_iterator MachOObjectFile::symbol_end() const {
2481   DataRefImpl DRI;
2482   MachO::symtab_command Symtab = getSymtabLoadCommand();
2483   if (!SymtabLoadCmd || Symtab.nsyms == 0)
2484     return basic_symbol_iterator(SymbolRef(DRI, this));
2485 
2486   unsigned SymbolTableEntrySize = is64Bit() ?
2487     sizeof(MachO::nlist_64) :
2488     sizeof(MachO::nlist);
2489   unsigned Offset = Symtab.symoff +
2490     Symtab.nsyms * SymbolTableEntrySize;
2491   DRI.p = reinterpret_cast<uintptr_t>(getPtr(*this, Offset));
2492   return basic_symbol_iterator(SymbolRef(DRI, this));
2493 }
2494 
2495 symbol_iterator MachOObjectFile::getSymbolByIndex(unsigned Index) const {
2496   MachO::symtab_command Symtab = getSymtabLoadCommand();
2497   if (!SymtabLoadCmd || Index >= Symtab.nsyms)
2498     report_fatal_error("Requested symbol index is out of range.");
2499   unsigned SymbolTableEntrySize =
2500     is64Bit() ? sizeof(MachO::nlist_64) : sizeof(MachO::nlist);
2501   DataRefImpl DRI;
2502   DRI.p = reinterpret_cast<uintptr_t>(getPtr(*this, Symtab.symoff));
2503   DRI.p += Index * SymbolTableEntrySize;
2504   return basic_symbol_iterator(SymbolRef(DRI, this));
2505 }
2506 
2507 uint64_t MachOObjectFile::getSymbolIndex(DataRefImpl Symb) const {
2508   MachO::symtab_command Symtab = getSymtabLoadCommand();
2509   if (!SymtabLoadCmd)
2510     report_fatal_error("getSymbolIndex() called with no symbol table symbol");
2511   unsigned SymbolTableEntrySize =
2512     is64Bit() ? sizeof(MachO::nlist_64) : sizeof(MachO::nlist);
2513   DataRefImpl DRIstart;
2514   DRIstart.p = reinterpret_cast<uintptr_t>(getPtr(*this, Symtab.symoff));
2515   uint64_t Index = (Symb.p - DRIstart.p) / SymbolTableEntrySize;
2516   return Index;
2517 }
2518 
2519 section_iterator MachOObjectFile::section_begin() const {
2520   DataRefImpl DRI;
2521   return section_iterator(SectionRef(DRI, this));
2522 }
2523 
2524 section_iterator MachOObjectFile::section_end() const {
2525   DataRefImpl DRI;
2526   DRI.d.a = Sections.size();
2527   return section_iterator(SectionRef(DRI, this));
2528 }
2529 
2530 uint8_t MachOObjectFile::getBytesInAddress() const {
2531   return is64Bit() ? 8 : 4;
2532 }
2533 
2534 StringRef MachOObjectFile::getFileFormatName() const {
2535   unsigned CPUType = getCPUType(*this);
2536   if (!is64Bit()) {
2537     switch (CPUType) {
2538     case MachO::CPU_TYPE_I386:
2539       return "Mach-O 32-bit i386";
2540     case MachO::CPU_TYPE_ARM:
2541       return "Mach-O arm";
2542     case MachO::CPU_TYPE_ARM64_32:
2543       return "Mach-O arm64 (ILP32)";
2544     case MachO::CPU_TYPE_POWERPC:
2545       return "Mach-O 32-bit ppc";
2546     default:
2547       return "Mach-O 32-bit unknown";
2548     }
2549   }
2550 
2551   switch (CPUType) {
2552   case MachO::CPU_TYPE_X86_64:
2553     return "Mach-O 64-bit x86-64";
2554   case MachO::CPU_TYPE_ARM64:
2555     return "Mach-O arm64";
2556   case MachO::CPU_TYPE_POWERPC64:
2557     return "Mach-O 64-bit ppc64";
2558   default:
2559     return "Mach-O 64-bit unknown";
2560   }
2561 }
2562 
2563 Triple::ArchType MachOObjectFile::getArch(uint32_t CPUType) {
2564   switch (CPUType) {
2565   case MachO::CPU_TYPE_I386:
2566     return Triple::x86;
2567   case MachO::CPU_TYPE_X86_64:
2568     return Triple::x86_64;
2569   case MachO::CPU_TYPE_ARM:
2570     return Triple::arm;
2571   case MachO::CPU_TYPE_ARM64:
2572     return Triple::aarch64;
2573   case MachO::CPU_TYPE_ARM64_32:
2574     return Triple::aarch64_32;
2575   case MachO::CPU_TYPE_POWERPC:
2576     return Triple::ppc;
2577   case MachO::CPU_TYPE_POWERPC64:
2578     return Triple::ppc64;
2579   default:
2580     return Triple::UnknownArch;
2581   }
2582 }
2583 
2584 Triple MachOObjectFile::getArchTriple(uint32_t CPUType, uint32_t CPUSubType,
2585                                       const char **McpuDefault,
2586                                       const char **ArchFlag) {
2587   if (McpuDefault)
2588     *McpuDefault = nullptr;
2589   if (ArchFlag)
2590     *ArchFlag = nullptr;
2591 
2592   switch (CPUType) {
2593   case MachO::CPU_TYPE_I386:
2594     switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2595     case MachO::CPU_SUBTYPE_I386_ALL:
2596       if (ArchFlag)
2597         *ArchFlag = "i386";
2598       return Triple("i386-apple-darwin");
2599     default:
2600       return Triple();
2601     }
2602   case MachO::CPU_TYPE_X86_64:
2603     switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2604     case MachO::CPU_SUBTYPE_X86_64_ALL:
2605       if (ArchFlag)
2606         *ArchFlag = "x86_64";
2607       return Triple("x86_64-apple-darwin");
2608     case MachO::CPU_SUBTYPE_X86_64_H:
2609       if (ArchFlag)
2610         *ArchFlag = "x86_64h";
2611       return Triple("x86_64h-apple-darwin");
2612     default:
2613       return Triple();
2614     }
2615   case MachO::CPU_TYPE_ARM:
2616     switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2617     case MachO::CPU_SUBTYPE_ARM_V4T:
2618       if (ArchFlag)
2619         *ArchFlag = "armv4t";
2620       return Triple("armv4t-apple-darwin");
2621     case MachO::CPU_SUBTYPE_ARM_V5TEJ:
2622       if (ArchFlag)
2623         *ArchFlag = "armv5e";
2624       return Triple("armv5e-apple-darwin");
2625     case MachO::CPU_SUBTYPE_ARM_XSCALE:
2626       if (ArchFlag)
2627         *ArchFlag = "xscale";
2628       return Triple("xscale-apple-darwin");
2629     case MachO::CPU_SUBTYPE_ARM_V6:
2630       if (ArchFlag)
2631         *ArchFlag = "armv6";
2632       return Triple("armv6-apple-darwin");
2633     case MachO::CPU_SUBTYPE_ARM_V6M:
2634       if (McpuDefault)
2635         *McpuDefault = "cortex-m0";
2636       if (ArchFlag)
2637         *ArchFlag = "armv6m";
2638       return Triple("armv6m-apple-darwin");
2639     case MachO::CPU_SUBTYPE_ARM_V7:
2640       if (ArchFlag)
2641         *ArchFlag = "armv7";
2642       return Triple("armv7-apple-darwin");
2643     case MachO::CPU_SUBTYPE_ARM_V7EM:
2644       if (McpuDefault)
2645         *McpuDefault = "cortex-m4";
2646       if (ArchFlag)
2647         *ArchFlag = "armv7em";
2648       return Triple("thumbv7em-apple-darwin");
2649     case MachO::CPU_SUBTYPE_ARM_V7K:
2650       if (McpuDefault)
2651         *McpuDefault = "cortex-a7";
2652       if (ArchFlag)
2653         *ArchFlag = "armv7k";
2654       return Triple("armv7k-apple-darwin");
2655     case MachO::CPU_SUBTYPE_ARM_V7M:
2656       if (McpuDefault)
2657         *McpuDefault = "cortex-m3";
2658       if (ArchFlag)
2659         *ArchFlag = "armv7m";
2660       return Triple("thumbv7m-apple-darwin");
2661     case MachO::CPU_SUBTYPE_ARM_V7S:
2662       if (McpuDefault)
2663         *McpuDefault = "cortex-a7";
2664       if (ArchFlag)
2665         *ArchFlag = "armv7s";
2666       return Triple("armv7s-apple-darwin");
2667     default:
2668       return Triple();
2669     }
2670   case MachO::CPU_TYPE_ARM64:
2671     switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2672     case MachO::CPU_SUBTYPE_ARM64_ALL:
2673       if (McpuDefault)
2674         *McpuDefault = "cyclone";
2675       if (ArchFlag)
2676         *ArchFlag = "arm64";
2677       return Triple("arm64-apple-darwin");
2678     default:
2679       return Triple();
2680     }
2681   case MachO::CPU_TYPE_ARM64_32:
2682     switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2683     case MachO::CPU_SUBTYPE_ARM64_32_V8:
2684       if (McpuDefault)
2685         *McpuDefault = "cyclone";
2686       if (ArchFlag)
2687         *ArchFlag = "arm64_32";
2688       return Triple("arm64_32-apple-darwin");
2689     default:
2690       return Triple();
2691     }
2692   case MachO::CPU_TYPE_POWERPC:
2693     switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2694     case MachO::CPU_SUBTYPE_POWERPC_ALL:
2695       if (ArchFlag)
2696         *ArchFlag = "ppc";
2697       return Triple("ppc-apple-darwin");
2698     default:
2699       return Triple();
2700     }
2701   case MachO::CPU_TYPE_POWERPC64:
2702     switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2703     case MachO::CPU_SUBTYPE_POWERPC_ALL:
2704       if (ArchFlag)
2705         *ArchFlag = "ppc64";
2706       return Triple("ppc64-apple-darwin");
2707     default:
2708       return Triple();
2709     }
2710   default:
2711     return Triple();
2712   }
2713 }
2714 
2715 Triple MachOObjectFile::getHostArch() {
2716   return Triple(sys::getDefaultTargetTriple());
2717 }
2718 
2719 bool MachOObjectFile::isValidArch(StringRef ArchFlag) {
2720   auto validArchs = getValidArchs();
2721   return llvm::find(validArchs, ArchFlag) != validArchs.end();
2722 }
2723 
2724 ArrayRef<StringRef> MachOObjectFile::getValidArchs() {
2725   static const std::array<StringRef, 17> validArchs = {
2726       "i386",   "x86_64", "x86_64h",  "armv4t",  "arm",    "armv5e",
2727       "armv6",  "armv6m", "armv7",    "armv7em", "armv7k", "armv7m",
2728       "armv7s", "arm64",  "arm64_32", "ppc",     "ppc64",
2729   };
2730 
2731   return validArchs;
2732 }
2733 
2734 Triple::ArchType MachOObjectFile::getArch() const {
2735   return getArch(getCPUType(*this));
2736 }
2737 
2738 Triple MachOObjectFile::getArchTriple(const char **McpuDefault) const {
2739   return getArchTriple(Header.cputype, Header.cpusubtype, McpuDefault);
2740 }
2741 
2742 relocation_iterator MachOObjectFile::section_rel_begin(unsigned Index) const {
2743   DataRefImpl DRI;
2744   DRI.d.a = Index;
2745   return section_rel_begin(DRI);
2746 }
2747 
2748 relocation_iterator MachOObjectFile::section_rel_end(unsigned Index) const {
2749   DataRefImpl DRI;
2750   DRI.d.a = Index;
2751   return section_rel_end(DRI);
2752 }
2753 
2754 dice_iterator MachOObjectFile::begin_dices() const {
2755   DataRefImpl DRI;
2756   if (!DataInCodeLoadCmd)
2757     return dice_iterator(DiceRef(DRI, this));
2758 
2759   MachO::linkedit_data_command DicLC = getDataInCodeLoadCommand();
2760   DRI.p = reinterpret_cast<uintptr_t>(getPtr(*this, DicLC.dataoff));
2761   return dice_iterator(DiceRef(DRI, this));
2762 }
2763 
2764 dice_iterator MachOObjectFile::end_dices() const {
2765   DataRefImpl DRI;
2766   if (!DataInCodeLoadCmd)
2767     return dice_iterator(DiceRef(DRI, this));
2768 
2769   MachO::linkedit_data_command DicLC = getDataInCodeLoadCommand();
2770   unsigned Offset = DicLC.dataoff + DicLC.datasize;
2771   DRI.p = reinterpret_cast<uintptr_t>(getPtr(*this, Offset));
2772   return dice_iterator(DiceRef(DRI, this));
2773 }
2774 
2775 ExportEntry::ExportEntry(Error *E, const MachOObjectFile *O,
2776                          ArrayRef<uint8_t> T) : E(E), O(O), Trie(T) {}
2777 
2778 void ExportEntry::moveToFirst() {
2779   ErrorAsOutParameter ErrAsOutParam(E);
2780   pushNode(0);
2781   if (*E)
2782     return;
2783   pushDownUntilBottom();
2784 }
2785 
2786 void ExportEntry::moveToEnd() {
2787   Stack.clear();
2788   Done = true;
2789 }
2790 
2791 bool ExportEntry::operator==(const ExportEntry &Other) const {
2792   // Common case, one at end, other iterating from begin.
2793   if (Done || Other.Done)
2794     return (Done == Other.Done);
2795   // Not equal if different stack sizes.
2796   if (Stack.size() != Other.Stack.size())
2797     return false;
2798   // Not equal if different cumulative strings.
2799   if (!CumulativeString.equals(Other.CumulativeString))
2800     return false;
2801   // Equal if all nodes in both stacks match.
2802   for (unsigned i=0; i < Stack.size(); ++i) {
2803     if (Stack[i].Start != Other.Stack[i].Start)
2804       return false;
2805   }
2806   return true;
2807 }
2808 
2809 uint64_t ExportEntry::readULEB128(const uint8_t *&Ptr, const char **error) {
2810   unsigned Count;
2811   uint64_t Result = decodeULEB128(Ptr, &Count, Trie.end(), error);
2812   Ptr += Count;
2813   if (Ptr > Trie.end())
2814     Ptr = Trie.end();
2815   return Result;
2816 }
2817 
2818 StringRef ExportEntry::name() const {
2819   return CumulativeString;
2820 }
2821 
2822 uint64_t ExportEntry::flags() const {
2823   return Stack.back().Flags;
2824 }
2825 
2826 uint64_t ExportEntry::address() const {
2827   return Stack.back().Address;
2828 }
2829 
2830 uint64_t ExportEntry::other() const {
2831   return Stack.back().Other;
2832 }
2833 
2834 StringRef ExportEntry::otherName() const {
2835   const char* ImportName = Stack.back().ImportName;
2836   if (ImportName)
2837     return StringRef(ImportName);
2838   return StringRef();
2839 }
2840 
2841 uint32_t ExportEntry::nodeOffset() const {
2842   return Stack.back().Start - Trie.begin();
2843 }
2844 
2845 ExportEntry::NodeState::NodeState(const uint8_t *Ptr)
2846     : Start(Ptr), Current(Ptr) {}
2847 
2848 void ExportEntry::pushNode(uint64_t offset) {
2849   ErrorAsOutParameter ErrAsOutParam(E);
2850   const uint8_t *Ptr = Trie.begin() + offset;
2851   NodeState State(Ptr);
2852   const char *error;
2853   uint64_t ExportInfoSize = readULEB128(State.Current, &error);
2854   if (error) {
2855     *E = malformedError("export info size " + Twine(error) +
2856                         " in export trie data at node: 0x" +
2857                         Twine::utohexstr(offset));
2858     moveToEnd();
2859     return;
2860   }
2861   State.IsExportNode = (ExportInfoSize != 0);
2862   const uint8_t* Children = State.Current + ExportInfoSize;
2863   if (Children > Trie.end()) {
2864     *E = malformedError(
2865         "export info size: 0x" + Twine::utohexstr(ExportInfoSize) +
2866         " in export trie data at node: 0x" + Twine::utohexstr(offset) +
2867         " too big and extends past end of trie data");
2868     moveToEnd();
2869     return;
2870   }
2871   if (State.IsExportNode) {
2872     const uint8_t *ExportStart = State.Current;
2873     State.Flags = readULEB128(State.Current, &error);
2874     if (error) {
2875       *E = malformedError("flags " + Twine(error) +
2876                           " in export trie data at node: 0x" +
2877                           Twine::utohexstr(offset));
2878       moveToEnd();
2879       return;
2880     }
2881     uint64_t Kind = State.Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK;
2882     if (State.Flags != 0 &&
2883         (Kind != MachO::EXPORT_SYMBOL_FLAGS_KIND_REGULAR &&
2884          Kind != MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE &&
2885          Kind != MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL)) {
2886       *E = malformedError(
2887           "unsupported exported symbol kind: " + Twine((int)Kind) +
2888           " in flags: 0x" + Twine::utohexstr(State.Flags) +
2889           " in export trie data at node: 0x" + Twine::utohexstr(offset));
2890       moveToEnd();
2891       return;
2892     }
2893     if (State.Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT) {
2894       State.Address = 0;
2895       State.Other = readULEB128(State.Current, &error); // dylib ordinal
2896       if (error) {
2897         *E = malformedError("dylib ordinal of re-export " + Twine(error) +
2898                             " in export trie data at node: 0x" +
2899                             Twine::utohexstr(offset));
2900         moveToEnd();
2901         return;
2902       }
2903       if (O != nullptr) {
2904         if (State.Other > O->getLibraryCount()) {
2905           *E = malformedError(
2906               "bad library ordinal: " + Twine((int)State.Other) + " (max " +
2907               Twine((int)O->getLibraryCount()) +
2908               ") in export trie data at node: 0x" + Twine::utohexstr(offset));
2909           moveToEnd();
2910           return;
2911         }
2912       }
2913       State.ImportName = reinterpret_cast<const char*>(State.Current);
2914       if (*State.ImportName == '\0') {
2915         State.Current++;
2916       } else {
2917         const uint8_t *End = State.Current + 1;
2918         if (End >= Trie.end()) {
2919           *E = malformedError("import name of re-export in export trie data at "
2920                               "node: 0x" +
2921                               Twine::utohexstr(offset) +
2922                               " starts past end of trie data");
2923           moveToEnd();
2924           return;
2925         }
2926         while(*End != '\0' && End < Trie.end())
2927           End++;
2928         if (*End != '\0') {
2929           *E = malformedError("import name of re-export in export trie data at "
2930                               "node: 0x" +
2931                               Twine::utohexstr(offset) +
2932                               " extends past end of trie data");
2933           moveToEnd();
2934           return;
2935         }
2936         State.Current = End + 1;
2937       }
2938     } else {
2939       State.Address = readULEB128(State.Current, &error);
2940       if (error) {
2941         *E = malformedError("address " + Twine(error) +
2942                             " in export trie data at node: 0x" +
2943                             Twine::utohexstr(offset));
2944         moveToEnd();
2945         return;
2946       }
2947       if (State.Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER) {
2948         State.Other = readULEB128(State.Current, &error);
2949         if (error) {
2950           *E = malformedError("resolver of stub and resolver " + Twine(error) +
2951                               " in export trie data at node: 0x" +
2952                               Twine::utohexstr(offset));
2953           moveToEnd();
2954           return;
2955         }
2956       }
2957     }
2958     if(ExportStart + ExportInfoSize != State.Current) {
2959       *E = malformedError(
2960           "inconsistant export info size: 0x" +
2961           Twine::utohexstr(ExportInfoSize) + " where actual size was: 0x" +
2962           Twine::utohexstr(State.Current - ExportStart) +
2963           " in export trie data at node: 0x" + Twine::utohexstr(offset));
2964       moveToEnd();
2965       return;
2966     }
2967   }
2968   State.ChildCount = *Children;
2969   if (State.ChildCount != 0 && Children + 1 >= Trie.end()) {
2970     *E = malformedError("byte for count of childern in export trie data at "
2971                         "node: 0x" +
2972                         Twine::utohexstr(offset) +
2973                         " extends past end of trie data");
2974     moveToEnd();
2975     return;
2976   }
2977   State.Current = Children + 1;
2978   State.NextChildIndex = 0;
2979   State.ParentStringLength = CumulativeString.size();
2980   Stack.push_back(State);
2981 }
2982 
2983 void ExportEntry::pushDownUntilBottom() {
2984   ErrorAsOutParameter ErrAsOutParam(E);
2985   const char *error;
2986   while (Stack.back().NextChildIndex < Stack.back().ChildCount) {
2987     NodeState &Top = Stack.back();
2988     CumulativeString.resize(Top.ParentStringLength);
2989     for (;*Top.Current != 0 && Top.Current < Trie.end(); Top.Current++) {
2990       char C = *Top.Current;
2991       CumulativeString.push_back(C);
2992     }
2993     if (Top.Current >= Trie.end()) {
2994       *E = malformedError("edge sub-string in export trie data at node: 0x" +
2995                           Twine::utohexstr(Top.Start - Trie.begin()) +
2996                           " for child #" + Twine((int)Top.NextChildIndex) +
2997                           " extends past end of trie data");
2998       moveToEnd();
2999       return;
3000     }
3001     Top.Current += 1;
3002     uint64_t childNodeIndex = readULEB128(Top.Current, &error);
3003     if (error) {
3004       *E = malformedError("child node offset " + Twine(error) +
3005                           " in export trie data at node: 0x" +
3006                           Twine::utohexstr(Top.Start - Trie.begin()));
3007       moveToEnd();
3008       return;
3009     }
3010     for (const NodeState &node : nodes()) {
3011       if (node.Start == Trie.begin() + childNodeIndex){
3012         *E = malformedError("loop in childern in export trie data at node: 0x" +
3013                             Twine::utohexstr(Top.Start - Trie.begin()) +
3014                             " back to node: 0x" +
3015                             Twine::utohexstr(childNodeIndex));
3016         moveToEnd();
3017         return;
3018       }
3019     }
3020     Top.NextChildIndex += 1;
3021     pushNode(childNodeIndex);
3022     if (*E)
3023       return;
3024   }
3025   if (!Stack.back().IsExportNode) {
3026     *E = malformedError("node is not an export node in export trie data at "
3027                         "node: 0x" +
3028                         Twine::utohexstr(Stack.back().Start - Trie.begin()));
3029     moveToEnd();
3030     return;
3031   }
3032 }
3033 
3034 // We have a trie data structure and need a way to walk it that is compatible
3035 // with the C++ iterator model. The solution is a non-recursive depth first
3036 // traversal where the iterator contains a stack of parent nodes along with a
3037 // string that is the accumulation of all edge strings along the parent chain
3038 // to this point.
3039 //
3040 // There is one "export" node for each exported symbol.  But because some
3041 // symbols may be a prefix of another symbol (e.g. _dup and _dup2), an export
3042 // node may have child nodes too.
3043 //
3044 // The algorithm for moveNext() is to keep moving down the leftmost unvisited
3045 // child until hitting a node with no children (which is an export node or
3046 // else the trie is malformed). On the way down, each node is pushed on the
3047 // stack ivar.  If there is no more ways down, it pops up one and tries to go
3048 // down a sibling path until a childless node is reached.
3049 void ExportEntry::moveNext() {
3050   assert(!Stack.empty() && "ExportEntry::moveNext() with empty node stack");
3051   if (!Stack.back().IsExportNode) {
3052     *E = malformedError("node is not an export node in export trie data at "
3053                         "node: 0x" +
3054                         Twine::utohexstr(Stack.back().Start - Trie.begin()));
3055     moveToEnd();
3056     return;
3057   }
3058 
3059   Stack.pop_back();
3060   while (!Stack.empty()) {
3061     NodeState &Top = Stack.back();
3062     if (Top.NextChildIndex < Top.ChildCount) {
3063       pushDownUntilBottom();
3064       // Now at the next export node.
3065       return;
3066     } else {
3067       if (Top.IsExportNode) {
3068         // This node has no children but is itself an export node.
3069         CumulativeString.resize(Top.ParentStringLength);
3070         return;
3071       }
3072       Stack.pop_back();
3073     }
3074   }
3075   Done = true;
3076 }
3077 
3078 iterator_range<export_iterator>
3079 MachOObjectFile::exports(Error &E, ArrayRef<uint8_t> Trie,
3080                          const MachOObjectFile *O) {
3081   ExportEntry Start(&E, O, Trie);
3082   if (Trie.empty())
3083     Start.moveToEnd();
3084   else
3085     Start.moveToFirst();
3086 
3087   ExportEntry Finish(&E, O, Trie);
3088   Finish.moveToEnd();
3089 
3090   return make_range(export_iterator(Start), export_iterator(Finish));
3091 }
3092 
3093 iterator_range<export_iterator> MachOObjectFile::exports(Error &Err) const {
3094   return exports(Err, getDyldInfoExportsTrie(), this);
3095 }
3096 
3097 MachORebaseEntry::MachORebaseEntry(Error *E, const MachOObjectFile *O,
3098                                    ArrayRef<uint8_t> Bytes, bool is64Bit)
3099     : E(E), O(O), Opcodes(Bytes), Ptr(Bytes.begin()),
3100       PointerSize(is64Bit ? 8 : 4) {}
3101 
3102 void MachORebaseEntry::moveToFirst() {
3103   Ptr = Opcodes.begin();
3104   moveNext();
3105 }
3106 
3107 void MachORebaseEntry::moveToEnd() {
3108   Ptr = Opcodes.end();
3109   RemainingLoopCount = 0;
3110   Done = true;
3111 }
3112 
3113 void MachORebaseEntry::moveNext() {
3114   ErrorAsOutParameter ErrAsOutParam(E);
3115   // If in the middle of some loop, move to next rebasing in loop.
3116   SegmentOffset += AdvanceAmount;
3117   if (RemainingLoopCount) {
3118     --RemainingLoopCount;
3119     return;
3120   }
3121   // REBASE_OPCODE_DONE is only used for padding if we are not aligned to
3122   // pointer size. Therefore it is possible to reach the end without ever having
3123   // seen REBASE_OPCODE_DONE.
3124   if (Ptr == Opcodes.end()) {
3125     Done = true;
3126     return;
3127   }
3128   bool More = true;
3129   while (More) {
3130     // Parse next opcode and set up next loop.
3131     const uint8_t *OpcodeStart = Ptr;
3132     uint8_t Byte = *Ptr++;
3133     uint8_t ImmValue = Byte & MachO::REBASE_IMMEDIATE_MASK;
3134     uint8_t Opcode = Byte & MachO::REBASE_OPCODE_MASK;
3135     uint32_t Count, Skip;
3136     const char *error = nullptr;
3137     switch (Opcode) {
3138     case MachO::REBASE_OPCODE_DONE:
3139       More = false;
3140       Done = true;
3141       moveToEnd();
3142       DEBUG_WITH_TYPE("mach-o-rebase", dbgs() << "REBASE_OPCODE_DONE\n");
3143       break;
3144     case MachO::REBASE_OPCODE_SET_TYPE_IMM:
3145       RebaseType = ImmValue;
3146       if (RebaseType > MachO::REBASE_TYPE_TEXT_PCREL32) {
3147         *E = malformedError("for REBASE_OPCODE_SET_TYPE_IMM bad bind type: " +
3148                             Twine((int)RebaseType) + " for opcode at: 0x" +
3149                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3150         moveToEnd();
3151         return;
3152       }
3153       DEBUG_WITH_TYPE(
3154           "mach-o-rebase",
3155           dbgs() << "REBASE_OPCODE_SET_TYPE_IMM: "
3156                  << "RebaseType=" << (int) RebaseType << "\n");
3157       break;
3158     case MachO::REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:
3159       SegmentIndex = ImmValue;
3160       SegmentOffset = readULEB128(&error);
3161       if (error) {
3162         *E = malformedError("for REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB " +
3163                             Twine(error) + " for opcode at: 0x" +
3164                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3165         moveToEnd();
3166         return;
3167       }
3168       error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3169                                                PointerSize);
3170       if (error) {
3171         *E = malformedError("for REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB " +
3172                             Twine(error) + " for opcode at: 0x" +
3173                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3174         moveToEnd();
3175         return;
3176       }
3177       DEBUG_WITH_TYPE(
3178           "mach-o-rebase",
3179           dbgs() << "REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: "
3180                  << "SegmentIndex=" << SegmentIndex << ", "
3181                  << format("SegmentOffset=0x%06X", SegmentOffset)
3182                  << "\n");
3183       break;
3184     case MachO::REBASE_OPCODE_ADD_ADDR_ULEB:
3185       SegmentOffset += readULEB128(&error);
3186       if (error) {
3187         *E = malformedError("for REBASE_OPCODE_ADD_ADDR_ULEB " + Twine(error) +
3188                             " for opcode at: 0x" +
3189                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3190         moveToEnd();
3191         return;
3192       }
3193       error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3194                                                PointerSize);
3195       if (error) {
3196         *E = malformedError("for REBASE_OPCODE_ADD_ADDR_ULEB " + Twine(error) +
3197                             " for opcode at: 0x" +
3198                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3199         moveToEnd();
3200         return;
3201       }
3202       DEBUG_WITH_TYPE("mach-o-rebase",
3203                       dbgs() << "REBASE_OPCODE_ADD_ADDR_ULEB: "
3204                              << format("SegmentOffset=0x%06X",
3205                                        SegmentOffset) << "\n");
3206       break;
3207     case MachO::REBASE_OPCODE_ADD_ADDR_IMM_SCALED:
3208       error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3209                                                PointerSize);
3210       if (error) {
3211         *E = malformedError("for REBASE_OPCODE_ADD_ADDR_IMM_SCALED " +
3212                             Twine(error) + " for opcode at: 0x" +
3213                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3214         moveToEnd();
3215         return;
3216       }
3217       SegmentOffset += ImmValue * PointerSize;
3218       error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3219                                                PointerSize);
3220       if (error) {
3221         *E =
3222             malformedError("for REBASE_OPCODE_ADD_ADDR_IMM_SCALED "
3223                            " (after adding immediate times the pointer size) " +
3224                            Twine(error) + " for opcode at: 0x" +
3225                            Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3226         moveToEnd();
3227         return;
3228       }
3229       DEBUG_WITH_TYPE("mach-o-rebase",
3230                       dbgs() << "REBASE_OPCODE_ADD_ADDR_IMM_SCALED: "
3231                              << format("SegmentOffset=0x%06X",
3232                                        SegmentOffset) << "\n");
3233       break;
3234     case MachO::REBASE_OPCODE_DO_REBASE_IMM_TIMES:
3235       AdvanceAmount = PointerSize;
3236       Skip = 0;
3237       Count = ImmValue;
3238       if (ImmValue != 0)
3239         RemainingLoopCount = ImmValue - 1;
3240       else
3241         RemainingLoopCount = 0;
3242       error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3243                                                PointerSize, Count, Skip);
3244       if (error) {
3245         *E = malformedError("for REBASE_OPCODE_DO_REBASE_IMM_TIMES " +
3246                             Twine(error) + " for opcode at: 0x" +
3247                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3248         moveToEnd();
3249         return;
3250       }
3251       DEBUG_WITH_TYPE(
3252           "mach-o-rebase",
3253           dbgs() << "REBASE_OPCODE_DO_REBASE_IMM_TIMES: "
3254                  << format("SegmentOffset=0x%06X", SegmentOffset)
3255                  << ", AdvanceAmount=" << AdvanceAmount
3256                  << ", RemainingLoopCount=" << RemainingLoopCount
3257                  << "\n");
3258       return;
3259     case MachO::REBASE_OPCODE_DO_REBASE_ULEB_TIMES:
3260       AdvanceAmount = PointerSize;
3261       Skip = 0;
3262       Count = readULEB128(&error);
3263       if (error) {
3264         *E = malformedError("for REBASE_OPCODE_DO_REBASE_ULEB_TIMES " +
3265                             Twine(error) + " for opcode at: 0x" +
3266                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3267         moveToEnd();
3268         return;
3269       }
3270       if (Count != 0)
3271         RemainingLoopCount = Count - 1;
3272       else
3273         RemainingLoopCount = 0;
3274       error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3275                                                PointerSize, Count, Skip);
3276       if (error) {
3277         *E = malformedError("for REBASE_OPCODE_DO_REBASE_ULEB_TIMES " +
3278                             Twine(error) + " for opcode at: 0x" +
3279                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3280         moveToEnd();
3281         return;
3282       }
3283       DEBUG_WITH_TYPE(
3284           "mach-o-rebase",
3285           dbgs() << "REBASE_OPCODE_DO_REBASE_ULEB_TIMES: "
3286                  << format("SegmentOffset=0x%06X", SegmentOffset)
3287                  << ", AdvanceAmount=" << AdvanceAmount
3288                  << ", RemainingLoopCount=" << RemainingLoopCount
3289                  << "\n");
3290       return;
3291     case MachO::REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB:
3292       Skip = readULEB128(&error);
3293       if (error) {
3294         *E = malformedError("for REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB " +
3295                             Twine(error) + " for opcode at: 0x" +
3296                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3297         moveToEnd();
3298         return;
3299       }
3300       AdvanceAmount = Skip + PointerSize;
3301       Count = 1;
3302       RemainingLoopCount = 0;
3303       error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3304                                                PointerSize, Count, Skip);
3305       if (error) {
3306         *E = malformedError("for REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB " +
3307                             Twine(error) + " for opcode at: 0x" +
3308                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3309         moveToEnd();
3310         return;
3311       }
3312       DEBUG_WITH_TYPE(
3313           "mach-o-rebase",
3314           dbgs() << "REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB: "
3315                  << format("SegmentOffset=0x%06X", SegmentOffset)
3316                  << ", AdvanceAmount=" << AdvanceAmount
3317                  << ", RemainingLoopCount=" << RemainingLoopCount
3318                  << "\n");
3319       return;
3320     case MachO::REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB:
3321       Count = readULEB128(&error);
3322       if (error) {
3323         *E = malformedError("for REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_"
3324                             "ULEB " +
3325                             Twine(error) + " for opcode at: 0x" +
3326                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3327         moveToEnd();
3328         return;
3329       }
3330       if (Count != 0)
3331         RemainingLoopCount = Count - 1;
3332       else
3333         RemainingLoopCount = 0;
3334       Skip = readULEB128(&error);
3335       if (error) {
3336         *E = malformedError("for REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_"
3337                             "ULEB " +
3338                             Twine(error) + " for opcode at: 0x" +
3339                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3340         moveToEnd();
3341         return;
3342       }
3343       AdvanceAmount = Skip + PointerSize;
3344 
3345       error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3346                                                PointerSize, Count, Skip);
3347       if (error) {
3348         *E = malformedError("for REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_"
3349                             "ULEB " +
3350                             Twine(error) + " for opcode at: 0x" +
3351                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3352         moveToEnd();
3353         return;
3354       }
3355       DEBUG_WITH_TYPE(
3356           "mach-o-rebase",
3357           dbgs() << "REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB: "
3358                  << format("SegmentOffset=0x%06X", SegmentOffset)
3359                  << ", AdvanceAmount=" << AdvanceAmount
3360                  << ", RemainingLoopCount=" << RemainingLoopCount
3361                  << "\n");
3362       return;
3363     default:
3364       *E = malformedError("bad rebase info (bad opcode value 0x" +
3365                           Twine::utohexstr(Opcode) + " for opcode at: 0x" +
3366                           Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3367       moveToEnd();
3368       return;
3369     }
3370   }
3371 }
3372 
3373 uint64_t MachORebaseEntry::readULEB128(const char **error) {
3374   unsigned Count;
3375   uint64_t Result = decodeULEB128(Ptr, &Count, Opcodes.end(), error);
3376   Ptr += Count;
3377   if (Ptr > Opcodes.end())
3378     Ptr = Opcodes.end();
3379   return Result;
3380 }
3381 
3382 int32_t MachORebaseEntry::segmentIndex() const { return SegmentIndex; }
3383 
3384 uint64_t MachORebaseEntry::segmentOffset() const { return SegmentOffset; }
3385 
3386 StringRef MachORebaseEntry::typeName() const {
3387   switch (RebaseType) {
3388   case MachO::REBASE_TYPE_POINTER:
3389     return "pointer";
3390   case MachO::REBASE_TYPE_TEXT_ABSOLUTE32:
3391     return "text abs32";
3392   case MachO::REBASE_TYPE_TEXT_PCREL32:
3393     return "text rel32";
3394   }
3395   return "unknown";
3396 }
3397 
3398 // For use with the SegIndex of a checked Mach-O Rebase entry
3399 // to get the segment name.
3400 StringRef MachORebaseEntry::segmentName() const {
3401   return O->BindRebaseSegmentName(SegmentIndex);
3402 }
3403 
3404 // For use with a SegIndex,SegOffset pair from a checked Mach-O Rebase entry
3405 // to get the section name.
3406 StringRef MachORebaseEntry::sectionName() const {
3407   return O->BindRebaseSectionName(SegmentIndex, SegmentOffset);
3408 }
3409 
3410 // For use with a SegIndex,SegOffset pair from a checked Mach-O Rebase entry
3411 // to get the address.
3412 uint64_t MachORebaseEntry::address() const {
3413   return O->BindRebaseAddress(SegmentIndex, SegmentOffset);
3414 }
3415 
3416 bool MachORebaseEntry::operator==(const MachORebaseEntry &Other) const {
3417 #ifdef EXPENSIVE_CHECKS
3418   assert(Opcodes == Other.Opcodes && "compare iterators of different files");
3419 #else
3420   assert(Opcodes.data() == Other.Opcodes.data() && "compare iterators of different files");
3421 #endif
3422   return (Ptr == Other.Ptr) &&
3423          (RemainingLoopCount == Other.RemainingLoopCount) &&
3424          (Done == Other.Done);
3425 }
3426 
3427 iterator_range<rebase_iterator>
3428 MachOObjectFile::rebaseTable(Error &Err, MachOObjectFile *O,
3429                              ArrayRef<uint8_t> Opcodes, bool is64) {
3430   if (O->BindRebaseSectionTable == nullptr)
3431     O->BindRebaseSectionTable = llvm::make_unique<BindRebaseSegInfo>(O);
3432   MachORebaseEntry Start(&Err, O, Opcodes, is64);
3433   Start.moveToFirst();
3434 
3435   MachORebaseEntry Finish(&Err, O, Opcodes, is64);
3436   Finish.moveToEnd();
3437 
3438   return make_range(rebase_iterator(Start), rebase_iterator(Finish));
3439 }
3440 
3441 iterator_range<rebase_iterator> MachOObjectFile::rebaseTable(Error &Err) {
3442   return rebaseTable(Err, this, getDyldInfoRebaseOpcodes(), is64Bit());
3443 }
3444 
3445 MachOBindEntry::MachOBindEntry(Error *E, const MachOObjectFile *O,
3446                                ArrayRef<uint8_t> Bytes, bool is64Bit, Kind BK)
3447     : E(E), O(O), Opcodes(Bytes), Ptr(Bytes.begin()),
3448       PointerSize(is64Bit ? 8 : 4), TableKind(BK) {}
3449 
3450 void MachOBindEntry::moveToFirst() {
3451   Ptr = Opcodes.begin();
3452   moveNext();
3453 }
3454 
3455 void MachOBindEntry::moveToEnd() {
3456   Ptr = Opcodes.end();
3457   RemainingLoopCount = 0;
3458   Done = true;
3459 }
3460 
3461 void MachOBindEntry::moveNext() {
3462   ErrorAsOutParameter ErrAsOutParam(E);
3463   // If in the middle of some loop, move to next binding in loop.
3464   SegmentOffset += AdvanceAmount;
3465   if (RemainingLoopCount) {
3466     --RemainingLoopCount;
3467     return;
3468   }
3469   // BIND_OPCODE_DONE is only used for padding if we are not aligned to
3470   // pointer size. Therefore it is possible to reach the end without ever having
3471   // seen BIND_OPCODE_DONE.
3472   if (Ptr == Opcodes.end()) {
3473     Done = true;
3474     return;
3475   }
3476   bool More = true;
3477   while (More) {
3478     // Parse next opcode and set up next loop.
3479     const uint8_t *OpcodeStart = Ptr;
3480     uint8_t Byte = *Ptr++;
3481     uint8_t ImmValue = Byte & MachO::BIND_IMMEDIATE_MASK;
3482     uint8_t Opcode = Byte & MachO::BIND_OPCODE_MASK;
3483     int8_t SignExtended;
3484     const uint8_t *SymStart;
3485     uint32_t Count, Skip;
3486     const char *error = nullptr;
3487     switch (Opcode) {
3488     case MachO::BIND_OPCODE_DONE:
3489       if (TableKind == Kind::Lazy) {
3490         // Lazying bindings have a DONE opcode between entries.  Need to ignore
3491         // it to advance to next entry.  But need not if this is last entry.
3492         bool NotLastEntry = false;
3493         for (const uint8_t *P = Ptr; P < Opcodes.end(); ++P) {
3494           if (*P) {
3495             NotLastEntry = true;
3496           }
3497         }
3498         if (NotLastEntry)
3499           break;
3500       }
3501       More = false;
3502       moveToEnd();
3503       DEBUG_WITH_TYPE("mach-o-bind", dbgs() << "BIND_OPCODE_DONE\n");
3504       break;
3505     case MachO::BIND_OPCODE_SET_DYLIB_ORDINAL_IMM:
3506       if (TableKind == Kind::Weak) {
3507         *E = malformedError("BIND_OPCODE_SET_DYLIB_ORDINAL_IMM not allowed in "
3508                             "weak bind table for opcode at: 0x" +
3509                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3510         moveToEnd();
3511         return;
3512       }
3513       Ordinal = ImmValue;
3514       LibraryOrdinalSet = true;
3515       if (ImmValue > O->getLibraryCount()) {
3516         *E = malformedError("for BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB bad "
3517                             "library ordinal: " +
3518                             Twine((int)ImmValue) + " (max " +
3519                             Twine((int)O->getLibraryCount()) +
3520                             ") for opcode at: 0x" +
3521                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3522         moveToEnd();
3523         return;
3524       }
3525       DEBUG_WITH_TYPE(
3526           "mach-o-bind",
3527           dbgs() << "BIND_OPCODE_SET_DYLIB_ORDINAL_IMM: "
3528                  << "Ordinal=" << Ordinal << "\n");
3529       break;
3530     case MachO::BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB:
3531       if (TableKind == Kind::Weak) {
3532         *E = malformedError("BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB not allowed in "
3533                             "weak bind table for opcode at: 0x" +
3534                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3535         moveToEnd();
3536         return;
3537       }
3538       Ordinal = readULEB128(&error);
3539       LibraryOrdinalSet = true;
3540       if (error) {
3541         *E = malformedError("for BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB " +
3542                             Twine(error) + " for opcode at: 0x" +
3543                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3544         moveToEnd();
3545         return;
3546       }
3547       if (Ordinal > (int)O->getLibraryCount()) {
3548         *E = malformedError("for BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB bad "
3549                             "library ordinal: " +
3550                             Twine((int)Ordinal) + " (max " +
3551                             Twine((int)O->getLibraryCount()) +
3552                             ") for opcode at: 0x" +
3553                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3554         moveToEnd();
3555         return;
3556       }
3557       DEBUG_WITH_TYPE(
3558           "mach-o-bind",
3559           dbgs() << "BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB: "
3560                  << "Ordinal=" << Ordinal << "\n");
3561       break;
3562     case MachO::BIND_OPCODE_SET_DYLIB_SPECIAL_IMM:
3563       if (TableKind == Kind::Weak) {
3564         *E = malformedError("BIND_OPCODE_SET_DYLIB_SPECIAL_IMM not allowed in "
3565                             "weak bind table for opcode at: 0x" +
3566                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3567         moveToEnd();
3568         return;
3569       }
3570       if (ImmValue) {
3571         SignExtended = MachO::BIND_OPCODE_MASK | ImmValue;
3572         Ordinal = SignExtended;
3573         if (Ordinal < MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP) {
3574           *E = malformedError("for BIND_OPCODE_SET_DYLIB_SPECIAL_IMM unknown "
3575                               "special ordinal: " +
3576                               Twine((int)Ordinal) + " for opcode at: 0x" +
3577                               Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3578           moveToEnd();
3579           return;
3580         }
3581       } else
3582         Ordinal = 0;
3583       LibraryOrdinalSet = true;
3584       DEBUG_WITH_TYPE(
3585           "mach-o-bind",
3586           dbgs() << "BIND_OPCODE_SET_DYLIB_SPECIAL_IMM: "
3587                  << "Ordinal=" << Ordinal << "\n");
3588       break;
3589     case MachO::BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM:
3590       Flags = ImmValue;
3591       SymStart = Ptr;
3592       while (*Ptr && (Ptr < Opcodes.end())) {
3593         ++Ptr;
3594       }
3595       if (Ptr == Opcodes.end()) {
3596         *E = malformedError(
3597             "for BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM "
3598             "symbol name extends past opcodes for opcode at: 0x" +
3599             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3600         moveToEnd();
3601         return;
3602       }
3603       SymbolName = StringRef(reinterpret_cast<const char*>(SymStart),
3604                              Ptr-SymStart);
3605       ++Ptr;
3606       DEBUG_WITH_TYPE(
3607           "mach-o-bind",
3608           dbgs() << "BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM: "
3609                  << "SymbolName=" << SymbolName << "\n");
3610       if (TableKind == Kind::Weak) {
3611         if (ImmValue & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION)
3612           return;
3613       }
3614       break;
3615     case MachO::BIND_OPCODE_SET_TYPE_IMM:
3616       BindType = ImmValue;
3617       if (ImmValue > MachO::BIND_TYPE_TEXT_PCREL32) {
3618         *E = malformedError("for BIND_OPCODE_SET_TYPE_IMM bad bind type: " +
3619                             Twine((int)ImmValue) + " for opcode at: 0x" +
3620                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3621         moveToEnd();
3622         return;
3623       }
3624       DEBUG_WITH_TYPE(
3625           "mach-o-bind",
3626           dbgs() << "BIND_OPCODE_SET_TYPE_IMM: "
3627                  << "BindType=" << (int)BindType << "\n");
3628       break;
3629     case MachO::BIND_OPCODE_SET_ADDEND_SLEB:
3630       Addend = readSLEB128(&error);
3631       if (error) {
3632         *E = malformedError("for BIND_OPCODE_SET_ADDEND_SLEB " + Twine(error) +
3633                             " for opcode at: 0x" +
3634                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3635         moveToEnd();
3636         return;
3637       }
3638       DEBUG_WITH_TYPE(
3639           "mach-o-bind",
3640           dbgs() << "BIND_OPCODE_SET_ADDEND_SLEB: "
3641                  << "Addend=" << Addend << "\n");
3642       break;
3643     case MachO::BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:
3644       SegmentIndex = ImmValue;
3645       SegmentOffset = readULEB128(&error);
3646       if (error) {
3647         *E = malformedError("for BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB " +
3648                             Twine(error) + " for opcode at: 0x" +
3649                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3650         moveToEnd();
3651         return;
3652       }
3653       error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3654                                              PointerSize);
3655       if (error) {
3656         *E = malformedError("for BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB " +
3657                             Twine(error) + " for opcode at: 0x" +
3658                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3659         moveToEnd();
3660         return;
3661       }
3662       DEBUG_WITH_TYPE(
3663           "mach-o-bind",
3664           dbgs() << "BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: "
3665                  << "SegmentIndex=" << SegmentIndex << ", "
3666                  << format("SegmentOffset=0x%06X", SegmentOffset)
3667                  << "\n");
3668       break;
3669     case MachO::BIND_OPCODE_ADD_ADDR_ULEB:
3670       SegmentOffset += readULEB128(&error);
3671       if (error) {
3672         *E = malformedError("for BIND_OPCODE_ADD_ADDR_ULEB " + Twine(error) +
3673                             " for opcode at: 0x" +
3674                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3675         moveToEnd();
3676         return;
3677       }
3678       error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3679                                              PointerSize);
3680       if (error) {
3681         *E = malformedError("for BIND_OPCODE_ADD_ADDR_ULEB " + Twine(error) +
3682                             " for opcode at: 0x" +
3683                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3684         moveToEnd();
3685         return;
3686       }
3687       DEBUG_WITH_TYPE("mach-o-bind",
3688                       dbgs() << "BIND_OPCODE_ADD_ADDR_ULEB: "
3689                              << format("SegmentOffset=0x%06X",
3690                                        SegmentOffset) << "\n");
3691       break;
3692     case MachO::BIND_OPCODE_DO_BIND:
3693       AdvanceAmount = PointerSize;
3694       RemainingLoopCount = 0;
3695       error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3696                                              PointerSize);
3697       if (error) {
3698         *E = malformedError("for BIND_OPCODE_DO_BIND " + Twine(error) +
3699                             " for opcode at: 0x" +
3700                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3701         moveToEnd();
3702         return;
3703       }
3704       if (SymbolName == StringRef()) {
3705         *E = malformedError(
3706             "for BIND_OPCODE_DO_BIND missing preceding "
3707             "BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM for opcode at: 0x" +
3708             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3709         moveToEnd();
3710         return;
3711       }
3712       if (!LibraryOrdinalSet && TableKind != Kind::Weak) {
3713         *E =
3714             malformedError("for BIND_OPCODE_DO_BIND missing preceding "
3715                            "BIND_OPCODE_SET_DYLIB_ORDINAL_* for opcode at: 0x" +
3716                            Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3717         moveToEnd();
3718         return;
3719       }
3720       DEBUG_WITH_TYPE("mach-o-bind",
3721                       dbgs() << "BIND_OPCODE_DO_BIND: "
3722                              << format("SegmentOffset=0x%06X",
3723                                        SegmentOffset) << "\n");
3724       return;
3725      case MachO::BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB:
3726       if (TableKind == Kind::Lazy) {
3727         *E = malformedError("BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB not allowed in "
3728                             "lazy bind table for opcode at: 0x" +
3729                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3730         moveToEnd();
3731         return;
3732       }
3733       error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3734                                              PointerSize);
3735       if (error) {
3736         *E = malformedError("for BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB " +
3737                             Twine(error) + " for opcode at: 0x" +
3738                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3739         moveToEnd();
3740         return;
3741       }
3742       if (SymbolName == StringRef()) {
3743         *E = malformedError(
3744             "for BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB missing "
3745             "preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM for opcode "
3746             "at: 0x" +
3747             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3748         moveToEnd();
3749         return;
3750       }
3751       if (!LibraryOrdinalSet && TableKind != Kind::Weak) {
3752         *E = malformedError(
3753             "for BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB missing "
3754             "preceding BIND_OPCODE_SET_DYLIB_ORDINAL_* for opcode at: 0x" +
3755             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3756         moveToEnd();
3757         return;
3758       }
3759       AdvanceAmount = readULEB128(&error) + PointerSize;
3760       if (error) {
3761         *E = malformedError("for BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB " +
3762                             Twine(error) + " for opcode at: 0x" +
3763                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3764         moveToEnd();
3765         return;
3766       }
3767       // Note, this is not really an error until the next bind but make no sense
3768       // for a BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB to not be followed by another
3769       // bind operation.
3770       error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset +
3771                                             AdvanceAmount, PointerSize);
3772       if (error) {
3773         *E = malformedError("for BIND_OPCODE_ADD_ADDR_ULEB (after adding "
3774                             "ULEB) " +
3775                             Twine(error) + " for opcode at: 0x" +
3776                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3777         moveToEnd();
3778         return;
3779       }
3780       RemainingLoopCount = 0;
3781       DEBUG_WITH_TYPE(
3782           "mach-o-bind",
3783           dbgs() << "BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB: "
3784                  << format("SegmentOffset=0x%06X", SegmentOffset)
3785                  << ", AdvanceAmount=" << AdvanceAmount
3786                  << ", RemainingLoopCount=" << RemainingLoopCount
3787                  << "\n");
3788       return;
3789     case MachO::BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED:
3790       if (TableKind == Kind::Lazy) {
3791         *E = malformedError("BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED not "
3792                             "allowed in lazy bind table for opcode at: 0x" +
3793                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3794         moveToEnd();
3795         return;
3796       }
3797       error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3798                                              PointerSize);
3799       if (error) {
3800         *E = malformedError("for BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED " +
3801                             Twine(error) + " for opcode at: 0x" +
3802                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3803         moveToEnd();
3804         return;
3805       }
3806       if (SymbolName == StringRef()) {
3807         *E = malformedError(
3808             "for BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED "
3809             "missing preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM for "
3810             "opcode at: 0x" +
3811             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3812         moveToEnd();
3813         return;
3814       }
3815       if (!LibraryOrdinalSet && TableKind != Kind::Weak) {
3816         *E = malformedError(
3817             "for BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED "
3818             "missing preceding BIND_OPCODE_SET_DYLIB_ORDINAL_* for opcode "
3819             "at: 0x" +
3820             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3821         moveToEnd();
3822         return;
3823       }
3824       AdvanceAmount = ImmValue * PointerSize + PointerSize;
3825       RemainingLoopCount = 0;
3826       error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset +
3827                                              AdvanceAmount, PointerSize);
3828       if (error) {
3829         *E =
3830             malformedError("for BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED "
3831                            " (after adding immediate times the pointer size) " +
3832                            Twine(error) + " for opcode at: 0x" +
3833                            Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3834         moveToEnd();
3835         return;
3836       }
3837       DEBUG_WITH_TYPE("mach-o-bind",
3838                       dbgs()
3839                       << "BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED: "
3840                       << format("SegmentOffset=0x%06X", SegmentOffset) << "\n");
3841       return;
3842     case MachO::BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB:
3843       if (TableKind == Kind::Lazy) {
3844         *E = malformedError("BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB not "
3845                             "allowed in lazy bind table for opcode at: 0x" +
3846                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3847         moveToEnd();
3848         return;
3849       }
3850       Count = readULEB128(&error);
3851       if (Count != 0)
3852         RemainingLoopCount = Count - 1;
3853       else
3854         RemainingLoopCount = 0;
3855       if (error) {
3856         *E = malformedError("for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB "
3857                             " (count value) " +
3858                             Twine(error) + " for opcode at: 0x" +
3859                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3860         moveToEnd();
3861         return;
3862       }
3863       Skip = readULEB128(&error);
3864       AdvanceAmount = Skip + PointerSize;
3865       if (error) {
3866         *E = malformedError("for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB "
3867                             " (skip value) " +
3868                             Twine(error) + " for opcode at: 0x" +
3869                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3870         moveToEnd();
3871         return;
3872       }
3873       if (SymbolName == StringRef()) {
3874         *E = malformedError(
3875             "for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB "
3876             "missing preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM for "
3877             "opcode at: 0x" +
3878             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3879         moveToEnd();
3880         return;
3881       }
3882       if (!LibraryOrdinalSet && TableKind != Kind::Weak) {
3883         *E = malformedError(
3884             "for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB "
3885             "missing preceding BIND_OPCODE_SET_DYLIB_ORDINAL_* for opcode "
3886             "at: 0x" +
3887             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3888         moveToEnd();
3889         return;
3890       }
3891       error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3892                                              PointerSize, Count, Skip);
3893       if (error) {
3894         *E =
3895             malformedError("for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB " +
3896                            Twine(error) + " for opcode at: 0x" +
3897                            Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3898         moveToEnd();
3899         return;
3900       }
3901       DEBUG_WITH_TYPE(
3902           "mach-o-bind",
3903           dbgs() << "BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB: "
3904                  << format("SegmentOffset=0x%06X", SegmentOffset)
3905                  << ", AdvanceAmount=" << AdvanceAmount
3906                  << ", RemainingLoopCount=" << RemainingLoopCount
3907                  << "\n");
3908       return;
3909     default:
3910       *E = malformedError("bad bind info (bad opcode value 0x" +
3911                           Twine::utohexstr(Opcode) + " for opcode at: 0x" +
3912                           Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3913       moveToEnd();
3914       return;
3915     }
3916   }
3917 }
3918 
3919 uint64_t MachOBindEntry::readULEB128(const char **error) {
3920   unsigned Count;
3921   uint64_t Result = decodeULEB128(Ptr, &Count, Opcodes.end(), error);
3922   Ptr += Count;
3923   if (Ptr > Opcodes.end())
3924     Ptr = Opcodes.end();
3925   return Result;
3926 }
3927 
3928 int64_t MachOBindEntry::readSLEB128(const char **error) {
3929   unsigned Count;
3930   int64_t Result = decodeSLEB128(Ptr, &Count, Opcodes.end(), error);
3931   Ptr += Count;
3932   if (Ptr > Opcodes.end())
3933     Ptr = Opcodes.end();
3934   return Result;
3935 }
3936 
3937 int32_t MachOBindEntry::segmentIndex() const { return SegmentIndex; }
3938 
3939 uint64_t MachOBindEntry::segmentOffset() const { return SegmentOffset; }
3940 
3941 StringRef MachOBindEntry::typeName() const {
3942   switch (BindType) {
3943   case MachO::BIND_TYPE_POINTER:
3944     return "pointer";
3945   case MachO::BIND_TYPE_TEXT_ABSOLUTE32:
3946     return "text abs32";
3947   case MachO::BIND_TYPE_TEXT_PCREL32:
3948     return "text rel32";
3949   }
3950   return "unknown";
3951 }
3952 
3953 StringRef MachOBindEntry::symbolName() const { return SymbolName; }
3954 
3955 int64_t MachOBindEntry::addend() const { return Addend; }
3956 
3957 uint32_t MachOBindEntry::flags() const { return Flags; }
3958 
3959 int MachOBindEntry::ordinal() const { return Ordinal; }
3960 
3961 // For use with the SegIndex of a checked Mach-O Bind entry
3962 // to get the segment name.
3963 StringRef MachOBindEntry::segmentName() const {
3964   return O->BindRebaseSegmentName(SegmentIndex);
3965 }
3966 
3967 // For use with a SegIndex,SegOffset pair from a checked Mach-O Bind entry
3968 // to get the section name.
3969 StringRef MachOBindEntry::sectionName() const {
3970   return O->BindRebaseSectionName(SegmentIndex, SegmentOffset);
3971 }
3972 
3973 // For use with a SegIndex,SegOffset pair from a checked Mach-O Bind entry
3974 // to get the address.
3975 uint64_t MachOBindEntry::address() const {
3976   return O->BindRebaseAddress(SegmentIndex, SegmentOffset);
3977 }
3978 
3979 bool MachOBindEntry::operator==(const MachOBindEntry &Other) const {
3980 #ifdef EXPENSIVE_CHECKS
3981   assert(Opcodes == Other.Opcodes && "compare iterators of different files");
3982 #else
3983   assert(Opcodes.data() == Other.Opcodes.data() && "compare iterators of different files");
3984 #endif
3985   return (Ptr == Other.Ptr) &&
3986          (RemainingLoopCount == Other.RemainingLoopCount) &&
3987          (Done == Other.Done);
3988 }
3989 
3990 // Build table of sections so SegIndex/SegOffset pairs can be translated.
3991 BindRebaseSegInfo::BindRebaseSegInfo(const object::MachOObjectFile *Obj) {
3992   uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
3993   StringRef CurSegName;
3994   uint64_t CurSegAddress;
3995   for (const SectionRef &Section : Obj->sections()) {
3996     SectionInfo Info;
3997     Expected<StringRef> NameOrErr = Section.getName();
3998     if (!NameOrErr)
3999       consumeError(NameOrErr.takeError());
4000     else
4001       Info.SectionName = *NameOrErr;
4002     Info.Address = Section.getAddress();
4003     Info.Size = Section.getSize();
4004     Info.SegmentName =
4005         Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
4006     if (!Info.SegmentName.equals(CurSegName)) {
4007       ++CurSegIndex;
4008       CurSegName = Info.SegmentName;
4009       CurSegAddress = Info.Address;
4010     }
4011     Info.SegmentIndex = CurSegIndex - 1;
4012     Info.OffsetInSegment = Info.Address - CurSegAddress;
4013     Info.SegmentStartAddress = CurSegAddress;
4014     Sections.push_back(Info);
4015   }
4016   MaxSegIndex = CurSegIndex;
4017 }
4018 
4019 // For use with a SegIndex, SegOffset, and PointerSize triple in
4020 // MachOBindEntry::moveNext() to validate a MachOBindEntry or MachORebaseEntry.
4021 //
4022 // Given a SegIndex, SegOffset, and PointerSize, verify a valid section exists
4023 // that fully contains a pointer at that location. Multiple fixups in a bind
4024 // (such as with the BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB opcode) can
4025 // be tested via the Count and Skip parameters.
4026 const char * BindRebaseSegInfo::checkSegAndOffsets(int32_t SegIndex,
4027                                                    uint64_t SegOffset,
4028                                                    uint8_t PointerSize,
4029                                                    uint32_t Count,
4030                                                    uint32_t Skip) {
4031   if (SegIndex == -1)
4032     return "missing preceding *_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB";
4033   if (SegIndex >= MaxSegIndex)
4034     return "bad segIndex (too large)";
4035   for (uint32_t i = 0; i < Count; ++i) {
4036     uint32_t Start = SegOffset + i * (PointerSize + Skip);
4037     uint32_t End = Start + PointerSize;
4038     bool Found = false;
4039     for (const SectionInfo &SI : Sections) {
4040       if (SI.SegmentIndex != SegIndex)
4041         continue;
4042       if ((SI.OffsetInSegment<=Start) && (Start<(SI.OffsetInSegment+SI.Size))) {
4043         if (End <= SI.OffsetInSegment + SI.Size) {
4044           Found = true;
4045           break;
4046         }
4047         else
4048           return "bad offset, extends beyond section boundary";
4049       }
4050     }
4051     if (!Found)
4052       return "bad offset, not in section";
4053   }
4054   return nullptr;
4055 }
4056 
4057 // For use with the SegIndex of a checked Mach-O Bind or Rebase entry
4058 // to get the segment name.
4059 StringRef BindRebaseSegInfo::segmentName(int32_t SegIndex) {
4060   for (const SectionInfo &SI : Sections) {
4061     if (SI.SegmentIndex == SegIndex)
4062       return SI.SegmentName;
4063   }
4064   llvm_unreachable("invalid SegIndex");
4065 }
4066 
4067 // For use with a SegIndex,SegOffset pair from a checked Mach-O Bind or Rebase
4068 // to get the SectionInfo.
4069 const BindRebaseSegInfo::SectionInfo &BindRebaseSegInfo::findSection(
4070                                      int32_t SegIndex, uint64_t SegOffset) {
4071   for (const SectionInfo &SI : Sections) {
4072     if (SI.SegmentIndex != SegIndex)
4073       continue;
4074     if (SI.OffsetInSegment > SegOffset)
4075       continue;
4076     if (SegOffset >= (SI.OffsetInSegment + SI.Size))
4077       continue;
4078     return SI;
4079   }
4080   llvm_unreachable("SegIndex and SegOffset not in any section");
4081 }
4082 
4083 // For use with a SegIndex,SegOffset pair from a checked Mach-O Bind or Rebase
4084 // entry to get the section name.
4085 StringRef BindRebaseSegInfo::sectionName(int32_t SegIndex,
4086                                          uint64_t SegOffset) {
4087   return findSection(SegIndex, SegOffset).SectionName;
4088 }
4089 
4090 // For use with a SegIndex,SegOffset pair from a checked Mach-O Bind or Rebase
4091 // entry to get the address.
4092 uint64_t BindRebaseSegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
4093   const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
4094   return SI.SegmentStartAddress + OffsetInSeg;
4095 }
4096 
4097 iterator_range<bind_iterator>
4098 MachOObjectFile::bindTable(Error &Err, MachOObjectFile *O,
4099                            ArrayRef<uint8_t> Opcodes, bool is64,
4100                            MachOBindEntry::Kind BKind) {
4101   if (O->BindRebaseSectionTable == nullptr)
4102     O->BindRebaseSectionTable = llvm::make_unique<BindRebaseSegInfo>(O);
4103   MachOBindEntry Start(&Err, O, Opcodes, is64, BKind);
4104   Start.moveToFirst();
4105 
4106   MachOBindEntry Finish(&Err, O, Opcodes, is64, BKind);
4107   Finish.moveToEnd();
4108 
4109   return make_range(bind_iterator(Start), bind_iterator(Finish));
4110 }
4111 
4112 iterator_range<bind_iterator> MachOObjectFile::bindTable(Error &Err) {
4113   return bindTable(Err, this, getDyldInfoBindOpcodes(), is64Bit(),
4114                    MachOBindEntry::Kind::Regular);
4115 }
4116 
4117 iterator_range<bind_iterator> MachOObjectFile::lazyBindTable(Error &Err) {
4118   return bindTable(Err, this, getDyldInfoLazyBindOpcodes(), is64Bit(),
4119                    MachOBindEntry::Kind::Lazy);
4120 }
4121 
4122 iterator_range<bind_iterator> MachOObjectFile::weakBindTable(Error &Err) {
4123   return bindTable(Err, this, getDyldInfoWeakBindOpcodes(), is64Bit(),
4124                    MachOBindEntry::Kind::Weak);
4125 }
4126 
4127 MachOObjectFile::load_command_iterator
4128 MachOObjectFile::begin_load_commands() const {
4129   return LoadCommands.begin();
4130 }
4131 
4132 MachOObjectFile::load_command_iterator
4133 MachOObjectFile::end_load_commands() const {
4134   return LoadCommands.end();
4135 }
4136 
4137 iterator_range<MachOObjectFile::load_command_iterator>
4138 MachOObjectFile::load_commands() const {
4139   return make_range(begin_load_commands(), end_load_commands());
4140 }
4141 
4142 StringRef
4143 MachOObjectFile::getSectionFinalSegmentName(DataRefImpl Sec) const {
4144   ArrayRef<char> Raw = getSectionRawFinalSegmentName(Sec);
4145   return parseSegmentOrSectionName(Raw.data());
4146 }
4147 
4148 ArrayRef<char>
4149 MachOObjectFile::getSectionRawName(DataRefImpl Sec) const {
4150   assert(Sec.d.a < Sections.size() && "Should have detected this earlier");
4151   const section_base *Base =
4152     reinterpret_cast<const section_base *>(Sections[Sec.d.a]);
4153   return makeArrayRef(Base->sectname);
4154 }
4155 
4156 ArrayRef<char>
4157 MachOObjectFile::getSectionRawFinalSegmentName(DataRefImpl Sec) const {
4158   assert(Sec.d.a < Sections.size() && "Should have detected this earlier");
4159   const section_base *Base =
4160     reinterpret_cast<const section_base *>(Sections[Sec.d.a]);
4161   return makeArrayRef(Base->segname);
4162 }
4163 
4164 bool
4165 MachOObjectFile::isRelocationScattered(const MachO::any_relocation_info &RE)
4166   const {
4167   if (getCPUType(*this) == MachO::CPU_TYPE_X86_64)
4168     return false;
4169   return getPlainRelocationAddress(RE) & MachO::R_SCATTERED;
4170 }
4171 
4172 unsigned MachOObjectFile::getPlainRelocationSymbolNum(
4173     const MachO::any_relocation_info &RE) const {
4174   if (isLittleEndian())
4175     return RE.r_word1 & 0xffffff;
4176   return RE.r_word1 >> 8;
4177 }
4178 
4179 bool MachOObjectFile::getPlainRelocationExternal(
4180     const MachO::any_relocation_info &RE) const {
4181   if (isLittleEndian())
4182     return (RE.r_word1 >> 27) & 1;
4183   return (RE.r_word1 >> 4) & 1;
4184 }
4185 
4186 bool MachOObjectFile::getScatteredRelocationScattered(
4187     const MachO::any_relocation_info &RE) const {
4188   return RE.r_word0 >> 31;
4189 }
4190 
4191 uint32_t MachOObjectFile::getScatteredRelocationValue(
4192     const MachO::any_relocation_info &RE) const {
4193   return RE.r_word1;
4194 }
4195 
4196 uint32_t MachOObjectFile::getScatteredRelocationType(
4197     const MachO::any_relocation_info &RE) const {
4198   return (RE.r_word0 >> 24) & 0xf;
4199 }
4200 
4201 unsigned MachOObjectFile::getAnyRelocationAddress(
4202     const MachO::any_relocation_info &RE) const {
4203   if (isRelocationScattered(RE))
4204     return getScatteredRelocationAddress(RE);
4205   return getPlainRelocationAddress(RE);
4206 }
4207 
4208 unsigned MachOObjectFile::getAnyRelocationPCRel(
4209     const MachO::any_relocation_info &RE) const {
4210   if (isRelocationScattered(RE))
4211     return getScatteredRelocationPCRel(RE);
4212   return getPlainRelocationPCRel(*this, RE);
4213 }
4214 
4215 unsigned MachOObjectFile::getAnyRelocationLength(
4216     const MachO::any_relocation_info &RE) const {
4217   if (isRelocationScattered(RE))
4218     return getScatteredRelocationLength(RE);
4219   return getPlainRelocationLength(*this, RE);
4220 }
4221 
4222 unsigned
4223 MachOObjectFile::getAnyRelocationType(
4224                                    const MachO::any_relocation_info &RE) const {
4225   if (isRelocationScattered(RE))
4226     return getScatteredRelocationType(RE);
4227   return getPlainRelocationType(*this, RE);
4228 }
4229 
4230 SectionRef
4231 MachOObjectFile::getAnyRelocationSection(
4232                                    const MachO::any_relocation_info &RE) const {
4233   if (isRelocationScattered(RE) || getPlainRelocationExternal(RE))
4234     return *section_end();
4235   unsigned SecNum = getPlainRelocationSymbolNum(RE);
4236   if (SecNum == MachO::R_ABS || SecNum > Sections.size())
4237     return *section_end();
4238   DataRefImpl DRI;
4239   DRI.d.a = SecNum - 1;
4240   return SectionRef(DRI, this);
4241 }
4242 
4243 MachO::section MachOObjectFile::getSection(DataRefImpl DRI) const {
4244   assert(DRI.d.a < Sections.size() && "Should have detected this earlier");
4245   return getStruct<MachO::section>(*this, Sections[DRI.d.a]);
4246 }
4247 
4248 MachO::section_64 MachOObjectFile::getSection64(DataRefImpl DRI) const {
4249   assert(DRI.d.a < Sections.size() && "Should have detected this earlier");
4250   return getStruct<MachO::section_64>(*this, Sections[DRI.d.a]);
4251 }
4252 
4253 MachO::section MachOObjectFile::getSection(const LoadCommandInfo &L,
4254                                            unsigned Index) const {
4255   const char *Sec = getSectionPtr(*this, L, Index);
4256   return getStruct<MachO::section>(*this, Sec);
4257 }
4258 
4259 MachO::section_64 MachOObjectFile::getSection64(const LoadCommandInfo &L,
4260                                                 unsigned Index) const {
4261   const char *Sec = getSectionPtr(*this, L, Index);
4262   return getStruct<MachO::section_64>(*this, Sec);
4263 }
4264 
4265 MachO::nlist
4266 MachOObjectFile::getSymbolTableEntry(DataRefImpl DRI) const {
4267   const char *P = reinterpret_cast<const char *>(DRI.p);
4268   return getStruct<MachO::nlist>(*this, P);
4269 }
4270 
4271 MachO::nlist_64
4272 MachOObjectFile::getSymbol64TableEntry(DataRefImpl DRI) const {
4273   const char *P = reinterpret_cast<const char *>(DRI.p);
4274   return getStruct<MachO::nlist_64>(*this, P);
4275 }
4276 
4277 MachO::linkedit_data_command
4278 MachOObjectFile::getLinkeditDataLoadCommand(const LoadCommandInfo &L) const {
4279   return getStruct<MachO::linkedit_data_command>(*this, L.Ptr);
4280 }
4281 
4282 MachO::segment_command
4283 MachOObjectFile::getSegmentLoadCommand(const LoadCommandInfo &L) const {
4284   return getStruct<MachO::segment_command>(*this, L.Ptr);
4285 }
4286 
4287 MachO::segment_command_64
4288 MachOObjectFile::getSegment64LoadCommand(const LoadCommandInfo &L) const {
4289   return getStruct<MachO::segment_command_64>(*this, L.Ptr);
4290 }
4291 
4292 MachO::linker_option_command
4293 MachOObjectFile::getLinkerOptionLoadCommand(const LoadCommandInfo &L) const {
4294   return getStruct<MachO::linker_option_command>(*this, L.Ptr);
4295 }
4296 
4297 MachO::version_min_command
4298 MachOObjectFile::getVersionMinLoadCommand(const LoadCommandInfo &L) const {
4299   return getStruct<MachO::version_min_command>(*this, L.Ptr);
4300 }
4301 
4302 MachO::note_command
4303 MachOObjectFile::getNoteLoadCommand(const LoadCommandInfo &L) const {
4304   return getStruct<MachO::note_command>(*this, L.Ptr);
4305 }
4306 
4307 MachO::build_version_command
4308 MachOObjectFile::getBuildVersionLoadCommand(const LoadCommandInfo &L) const {
4309   return getStruct<MachO::build_version_command>(*this, L.Ptr);
4310 }
4311 
4312 MachO::build_tool_version
4313 MachOObjectFile::getBuildToolVersion(unsigned index) const {
4314   return getStruct<MachO::build_tool_version>(*this, BuildTools[index]);
4315 }
4316 
4317 MachO::dylib_command
4318 MachOObjectFile::getDylibIDLoadCommand(const LoadCommandInfo &L) const {
4319   return getStruct<MachO::dylib_command>(*this, L.Ptr);
4320 }
4321 
4322 MachO::dyld_info_command
4323 MachOObjectFile::getDyldInfoLoadCommand(const LoadCommandInfo &L) const {
4324   return getStruct<MachO::dyld_info_command>(*this, L.Ptr);
4325 }
4326 
4327 MachO::dylinker_command
4328 MachOObjectFile::getDylinkerCommand(const LoadCommandInfo &L) const {
4329   return getStruct<MachO::dylinker_command>(*this, L.Ptr);
4330 }
4331 
4332 MachO::uuid_command
4333 MachOObjectFile::getUuidCommand(const LoadCommandInfo &L) const {
4334   return getStruct<MachO::uuid_command>(*this, L.Ptr);
4335 }
4336 
4337 MachO::rpath_command
4338 MachOObjectFile::getRpathCommand(const LoadCommandInfo &L) const {
4339   return getStruct<MachO::rpath_command>(*this, L.Ptr);
4340 }
4341 
4342 MachO::source_version_command
4343 MachOObjectFile::getSourceVersionCommand(const LoadCommandInfo &L) const {
4344   return getStruct<MachO::source_version_command>(*this, L.Ptr);
4345 }
4346 
4347 MachO::entry_point_command
4348 MachOObjectFile::getEntryPointCommand(const LoadCommandInfo &L) const {
4349   return getStruct<MachO::entry_point_command>(*this, L.Ptr);
4350 }
4351 
4352 MachO::encryption_info_command
4353 MachOObjectFile::getEncryptionInfoCommand(const LoadCommandInfo &L) const {
4354   return getStruct<MachO::encryption_info_command>(*this, L.Ptr);
4355 }
4356 
4357 MachO::encryption_info_command_64
4358 MachOObjectFile::getEncryptionInfoCommand64(const LoadCommandInfo &L) const {
4359   return getStruct<MachO::encryption_info_command_64>(*this, L.Ptr);
4360 }
4361 
4362 MachO::sub_framework_command
4363 MachOObjectFile::getSubFrameworkCommand(const LoadCommandInfo &L) const {
4364   return getStruct<MachO::sub_framework_command>(*this, L.Ptr);
4365 }
4366 
4367 MachO::sub_umbrella_command
4368 MachOObjectFile::getSubUmbrellaCommand(const LoadCommandInfo &L) const {
4369   return getStruct<MachO::sub_umbrella_command>(*this, L.Ptr);
4370 }
4371 
4372 MachO::sub_library_command
4373 MachOObjectFile::getSubLibraryCommand(const LoadCommandInfo &L) const {
4374   return getStruct<MachO::sub_library_command>(*this, L.Ptr);
4375 }
4376 
4377 MachO::sub_client_command
4378 MachOObjectFile::getSubClientCommand(const LoadCommandInfo &L) const {
4379   return getStruct<MachO::sub_client_command>(*this, L.Ptr);
4380 }
4381 
4382 MachO::routines_command
4383 MachOObjectFile::getRoutinesCommand(const LoadCommandInfo &L) const {
4384   return getStruct<MachO::routines_command>(*this, L.Ptr);
4385 }
4386 
4387 MachO::routines_command_64
4388 MachOObjectFile::getRoutinesCommand64(const LoadCommandInfo &L) const {
4389   return getStruct<MachO::routines_command_64>(*this, L.Ptr);
4390 }
4391 
4392 MachO::thread_command
4393 MachOObjectFile::getThreadCommand(const LoadCommandInfo &L) const {
4394   return getStruct<MachO::thread_command>(*this, L.Ptr);
4395 }
4396 
4397 MachO::any_relocation_info
4398 MachOObjectFile::getRelocation(DataRefImpl Rel) const {
4399   uint32_t Offset;
4400   if (getHeader().filetype == MachO::MH_OBJECT) {
4401     DataRefImpl Sec;
4402     Sec.d.a = Rel.d.a;
4403     if (is64Bit()) {
4404       MachO::section_64 Sect = getSection64(Sec);
4405       Offset = Sect.reloff;
4406     } else {
4407       MachO::section Sect = getSection(Sec);
4408       Offset = Sect.reloff;
4409     }
4410   } else {
4411     MachO::dysymtab_command DysymtabLoadCmd = getDysymtabLoadCommand();
4412     if (Rel.d.a == 0)
4413       Offset = DysymtabLoadCmd.extreloff; // Offset to the external relocations
4414     else
4415       Offset = DysymtabLoadCmd.locreloff; // Offset to the local relocations
4416   }
4417 
4418   auto P = reinterpret_cast<const MachO::any_relocation_info *>(
4419       getPtr(*this, Offset)) + Rel.d.b;
4420   return getStruct<MachO::any_relocation_info>(
4421       *this, reinterpret_cast<const char *>(P));
4422 }
4423 
4424 MachO::data_in_code_entry
4425 MachOObjectFile::getDice(DataRefImpl Rel) const {
4426   const char *P = reinterpret_cast<const char *>(Rel.p);
4427   return getStruct<MachO::data_in_code_entry>(*this, P);
4428 }
4429 
4430 const MachO::mach_header &MachOObjectFile::getHeader() const {
4431   return Header;
4432 }
4433 
4434 const MachO::mach_header_64 &MachOObjectFile::getHeader64() const {
4435   assert(is64Bit());
4436   return Header64;
4437 }
4438 
4439 uint32_t MachOObjectFile::getIndirectSymbolTableEntry(
4440                                              const MachO::dysymtab_command &DLC,
4441                                              unsigned Index) const {
4442   uint64_t Offset = DLC.indirectsymoff + Index * sizeof(uint32_t);
4443   return getStruct<uint32_t>(*this, getPtr(*this, Offset));
4444 }
4445 
4446 MachO::data_in_code_entry
4447 MachOObjectFile::getDataInCodeTableEntry(uint32_t DataOffset,
4448                                          unsigned Index) const {
4449   uint64_t Offset = DataOffset + Index * sizeof(MachO::data_in_code_entry);
4450   return getStruct<MachO::data_in_code_entry>(*this, getPtr(*this, Offset));
4451 }
4452 
4453 MachO::symtab_command MachOObjectFile::getSymtabLoadCommand() const {
4454   if (SymtabLoadCmd)
4455     return getStruct<MachO::symtab_command>(*this, SymtabLoadCmd);
4456 
4457   // If there is no SymtabLoadCmd return a load command with zero'ed fields.
4458   MachO::symtab_command Cmd;
4459   Cmd.cmd = MachO::LC_SYMTAB;
4460   Cmd.cmdsize = sizeof(MachO::symtab_command);
4461   Cmd.symoff = 0;
4462   Cmd.nsyms = 0;
4463   Cmd.stroff = 0;
4464   Cmd.strsize = 0;
4465   return Cmd;
4466 }
4467 
4468 MachO::dysymtab_command MachOObjectFile::getDysymtabLoadCommand() const {
4469   if (DysymtabLoadCmd)
4470     return getStruct<MachO::dysymtab_command>(*this, DysymtabLoadCmd);
4471 
4472   // If there is no DysymtabLoadCmd return a load command with zero'ed fields.
4473   MachO::dysymtab_command Cmd;
4474   Cmd.cmd = MachO::LC_DYSYMTAB;
4475   Cmd.cmdsize = sizeof(MachO::dysymtab_command);
4476   Cmd.ilocalsym = 0;
4477   Cmd.nlocalsym = 0;
4478   Cmd.iextdefsym = 0;
4479   Cmd.nextdefsym = 0;
4480   Cmd.iundefsym = 0;
4481   Cmd.nundefsym = 0;
4482   Cmd.tocoff = 0;
4483   Cmd.ntoc = 0;
4484   Cmd.modtaboff = 0;
4485   Cmd.nmodtab = 0;
4486   Cmd.extrefsymoff = 0;
4487   Cmd.nextrefsyms = 0;
4488   Cmd.indirectsymoff = 0;
4489   Cmd.nindirectsyms = 0;
4490   Cmd.extreloff = 0;
4491   Cmd.nextrel = 0;
4492   Cmd.locreloff = 0;
4493   Cmd.nlocrel = 0;
4494   return Cmd;
4495 }
4496 
4497 MachO::linkedit_data_command
4498 MachOObjectFile::getDataInCodeLoadCommand() const {
4499   if (DataInCodeLoadCmd)
4500     return getStruct<MachO::linkedit_data_command>(*this, DataInCodeLoadCmd);
4501 
4502   // If there is no DataInCodeLoadCmd return a load command with zero'ed fields.
4503   MachO::linkedit_data_command Cmd;
4504   Cmd.cmd = MachO::LC_DATA_IN_CODE;
4505   Cmd.cmdsize = sizeof(MachO::linkedit_data_command);
4506   Cmd.dataoff = 0;
4507   Cmd.datasize = 0;
4508   return Cmd;
4509 }
4510 
4511 MachO::linkedit_data_command
4512 MachOObjectFile::getLinkOptHintsLoadCommand() const {
4513   if (LinkOptHintsLoadCmd)
4514     return getStruct<MachO::linkedit_data_command>(*this, LinkOptHintsLoadCmd);
4515 
4516   // If there is no LinkOptHintsLoadCmd return a load command with zero'ed
4517   // fields.
4518   MachO::linkedit_data_command Cmd;
4519   Cmd.cmd = MachO::LC_LINKER_OPTIMIZATION_HINT;
4520   Cmd.cmdsize = sizeof(MachO::linkedit_data_command);
4521   Cmd.dataoff = 0;
4522   Cmd.datasize = 0;
4523   return Cmd;
4524 }
4525 
4526 ArrayRef<uint8_t> MachOObjectFile::getDyldInfoRebaseOpcodes() const {
4527   if (!DyldInfoLoadCmd)
4528     return None;
4529 
4530   auto DyldInfoOrErr =
4531     getStructOrErr<MachO::dyld_info_command>(*this, DyldInfoLoadCmd);
4532   if (!DyldInfoOrErr)
4533     return None;
4534   MachO::dyld_info_command DyldInfo = DyldInfoOrErr.get();
4535   const uint8_t *Ptr =
4536       reinterpret_cast<const uint8_t *>(getPtr(*this, DyldInfo.rebase_off));
4537   return makeArrayRef(Ptr, DyldInfo.rebase_size);
4538 }
4539 
4540 ArrayRef<uint8_t> MachOObjectFile::getDyldInfoBindOpcodes() const {
4541   if (!DyldInfoLoadCmd)
4542     return None;
4543 
4544   auto DyldInfoOrErr =
4545     getStructOrErr<MachO::dyld_info_command>(*this, DyldInfoLoadCmd);
4546   if (!DyldInfoOrErr)
4547     return None;
4548   MachO::dyld_info_command DyldInfo = DyldInfoOrErr.get();
4549   const uint8_t *Ptr =
4550       reinterpret_cast<const uint8_t *>(getPtr(*this, DyldInfo.bind_off));
4551   return makeArrayRef(Ptr, DyldInfo.bind_size);
4552 }
4553 
4554 ArrayRef<uint8_t> MachOObjectFile::getDyldInfoWeakBindOpcodes() const {
4555   if (!DyldInfoLoadCmd)
4556     return None;
4557 
4558   auto DyldInfoOrErr =
4559     getStructOrErr<MachO::dyld_info_command>(*this, DyldInfoLoadCmd);
4560   if (!DyldInfoOrErr)
4561     return None;
4562   MachO::dyld_info_command DyldInfo = DyldInfoOrErr.get();
4563   const uint8_t *Ptr =
4564       reinterpret_cast<const uint8_t *>(getPtr(*this, DyldInfo.weak_bind_off));
4565   return makeArrayRef(Ptr, DyldInfo.weak_bind_size);
4566 }
4567 
4568 ArrayRef<uint8_t> MachOObjectFile::getDyldInfoLazyBindOpcodes() const {
4569   if (!DyldInfoLoadCmd)
4570     return None;
4571 
4572   auto DyldInfoOrErr =
4573     getStructOrErr<MachO::dyld_info_command>(*this, DyldInfoLoadCmd);
4574   if (!DyldInfoOrErr)
4575     return None;
4576   MachO::dyld_info_command DyldInfo = DyldInfoOrErr.get();
4577   const uint8_t *Ptr =
4578       reinterpret_cast<const uint8_t *>(getPtr(*this, DyldInfo.lazy_bind_off));
4579   return makeArrayRef(Ptr, DyldInfo.lazy_bind_size);
4580 }
4581 
4582 ArrayRef<uint8_t> MachOObjectFile::getDyldInfoExportsTrie() const {
4583   if (!DyldInfoLoadCmd)
4584     return None;
4585 
4586   auto DyldInfoOrErr =
4587     getStructOrErr<MachO::dyld_info_command>(*this, DyldInfoLoadCmd);
4588   if (!DyldInfoOrErr)
4589     return None;
4590   MachO::dyld_info_command DyldInfo = DyldInfoOrErr.get();
4591   const uint8_t *Ptr =
4592       reinterpret_cast<const uint8_t *>(getPtr(*this, DyldInfo.export_off));
4593   return makeArrayRef(Ptr, DyldInfo.export_size);
4594 }
4595 
4596 ArrayRef<uint8_t> MachOObjectFile::getUuid() const {
4597   if (!UuidLoadCmd)
4598     return None;
4599   // Returning a pointer is fine as uuid doesn't need endian swapping.
4600   const char *Ptr = UuidLoadCmd + offsetof(MachO::uuid_command, uuid);
4601   return makeArrayRef(reinterpret_cast<const uint8_t *>(Ptr), 16);
4602 }
4603 
4604 StringRef MachOObjectFile::getStringTableData() const {
4605   MachO::symtab_command S = getSymtabLoadCommand();
4606   return getData().substr(S.stroff, S.strsize);
4607 }
4608 
4609 bool MachOObjectFile::is64Bit() const {
4610   return getType() == getMachOType(false, true) ||
4611     getType() == getMachOType(true, true);
4612 }
4613 
4614 void MachOObjectFile::ReadULEB128s(uint64_t Index,
4615                                    SmallVectorImpl<uint64_t> &Out) const {
4616   DataExtractor extractor(ObjectFile::getData(), true, 0);
4617 
4618   uint64_t offset = Index;
4619   uint64_t data = 0;
4620   while (uint64_t delta = extractor.getULEB128(&offset)) {
4621     data += delta;
4622     Out.push_back(data);
4623   }
4624 }
4625 
4626 bool MachOObjectFile::isRelocatableObject() const {
4627   return getHeader().filetype == MachO::MH_OBJECT;
4628 }
4629 
4630 Expected<std::unique_ptr<MachOObjectFile>>
4631 ObjectFile::createMachOObjectFile(MemoryBufferRef Buffer,
4632                                   uint32_t UniversalCputype,
4633                                   uint32_t UniversalIndex) {
4634   StringRef Magic = Buffer.getBuffer().slice(0, 4);
4635   if (Magic == "\xFE\xED\xFA\xCE")
4636     return MachOObjectFile::create(Buffer, false, false,
4637                                    UniversalCputype, UniversalIndex);
4638   if (Magic == "\xCE\xFA\xED\xFE")
4639     return MachOObjectFile::create(Buffer, true, false,
4640                                    UniversalCputype, UniversalIndex);
4641   if (Magic == "\xFE\xED\xFA\xCF")
4642     return MachOObjectFile::create(Buffer, false, true,
4643                                    UniversalCputype, UniversalIndex);
4644   if (Magic == "\xCF\xFA\xED\xFE")
4645     return MachOObjectFile::create(Buffer, true, true,
4646                                    UniversalCputype, UniversalIndex);
4647   return make_error<GenericBinaryError>("Unrecognized MachO magic number",
4648                                         object_error::invalid_file_type);
4649 }
4650 
4651 StringRef MachOObjectFile::mapDebugSectionName(StringRef Name) const {
4652   return StringSwitch<StringRef>(Name)
4653       .Case("debug_str_offs", "debug_str_offsets")
4654       .Default(Name);
4655 }
4656