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