xref: /freebsd/contrib/llvm-project/llvm/lib/Object/MachOObjectFile.cpp (revision 9f23cbd6cae82fd77edfad7173432fa8dccd0a95)
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_Hidden;
1885     else
1886       Result |= SymbolRef::SF_Exported;
1887 
1888   } else if (MachOType & MachO::N_PEXT)
1889     Result |= SymbolRef::SF_Hidden;
1890 
1891   if (MachOFlags & (MachO::N_WEAK_REF | MachO::N_WEAK_DEF))
1892     Result |= SymbolRef::SF_Weak;
1893 
1894   if (MachOFlags & (MachO::N_ARM_THUMB_DEF))
1895     Result |= SymbolRef::SF_Thumb;
1896 
1897   if ((MachOType & MachO::N_TYPE) == MachO::N_ABS)
1898     Result |= SymbolRef::SF_Absolute;
1899 
1900   return Result;
1901 }
1902 
1903 Expected<section_iterator>
1904 MachOObjectFile::getSymbolSection(DataRefImpl Symb) const {
1905   MachO::nlist_base Entry = getSymbolTableEntryBase(*this, Symb);
1906   uint8_t index = Entry.n_sect;
1907 
1908   if (index == 0)
1909     return section_end();
1910   DataRefImpl DRI;
1911   DRI.d.a = index - 1;
1912   if (DRI.d.a >= Sections.size()){
1913     return malformedError("bad section index: " + Twine((int)index) +
1914                           " for symbol at index " + Twine(getSymbolIndex(Symb)));
1915   }
1916   return section_iterator(SectionRef(DRI, this));
1917 }
1918 
1919 unsigned MachOObjectFile::getSymbolSectionID(SymbolRef Sym) const {
1920   MachO::nlist_base Entry =
1921       getSymbolTableEntryBase(*this, Sym.getRawDataRefImpl());
1922   return Entry.n_sect - 1;
1923 }
1924 
1925 void MachOObjectFile::moveSectionNext(DataRefImpl &Sec) const {
1926   Sec.d.a++;
1927 }
1928 
1929 Expected<StringRef> MachOObjectFile::getSectionName(DataRefImpl Sec) const {
1930   ArrayRef<char> Raw = getSectionRawName(Sec);
1931   return parseSegmentOrSectionName(Raw.data());
1932 }
1933 
1934 uint64_t MachOObjectFile::getSectionAddress(DataRefImpl Sec) const {
1935   if (is64Bit())
1936     return getSection64(Sec).addr;
1937   return getSection(Sec).addr;
1938 }
1939 
1940 uint64_t MachOObjectFile::getSectionIndex(DataRefImpl Sec) const {
1941   return Sec.d.a;
1942 }
1943 
1944 uint64_t MachOObjectFile::getSectionSize(DataRefImpl Sec) const {
1945   // In the case if a malformed Mach-O file where the section offset is past
1946   // the end of the file or some part of the section size is past the end of
1947   // the file return a size of zero or a size that covers the rest of the file
1948   // but does not extend past the end of the file.
1949   uint32_t SectOffset, SectType;
1950   uint64_t SectSize;
1951 
1952   if (is64Bit()) {
1953     MachO::section_64 Sect = getSection64(Sec);
1954     SectOffset = Sect.offset;
1955     SectSize = Sect.size;
1956     SectType = Sect.flags & MachO::SECTION_TYPE;
1957   } else {
1958     MachO::section Sect = getSection(Sec);
1959     SectOffset = Sect.offset;
1960     SectSize = Sect.size;
1961     SectType = Sect.flags & MachO::SECTION_TYPE;
1962   }
1963   if (SectType == MachO::S_ZEROFILL || SectType == MachO::S_GB_ZEROFILL)
1964     return SectSize;
1965   uint64_t FileSize = getData().size();
1966   if (SectOffset > FileSize)
1967     return 0;
1968   if (FileSize - SectOffset < SectSize)
1969     return FileSize - SectOffset;
1970   return SectSize;
1971 }
1972 
1973 ArrayRef<uint8_t> MachOObjectFile::getSectionContents(uint32_t Offset,
1974                                                       uint64_t Size) const {
1975   return arrayRefFromStringRef(getData().substr(Offset, Size));
1976 }
1977 
1978 Expected<ArrayRef<uint8_t>>
1979 MachOObjectFile::getSectionContents(DataRefImpl Sec) const {
1980   uint32_t Offset;
1981   uint64_t Size;
1982 
1983   if (is64Bit()) {
1984     MachO::section_64 Sect = getSection64(Sec);
1985     Offset = Sect.offset;
1986     Size = Sect.size;
1987   } else {
1988     MachO::section Sect = getSection(Sec);
1989     Offset = Sect.offset;
1990     Size = Sect.size;
1991   }
1992 
1993   return getSectionContents(Offset, Size);
1994 }
1995 
1996 uint64_t MachOObjectFile::getSectionAlignment(DataRefImpl Sec) const {
1997   uint32_t Align;
1998   if (is64Bit()) {
1999     MachO::section_64 Sect = getSection64(Sec);
2000     Align = Sect.align;
2001   } else {
2002     MachO::section Sect = getSection(Sec);
2003     Align = Sect.align;
2004   }
2005 
2006   return uint64_t(1) << Align;
2007 }
2008 
2009 Expected<SectionRef> MachOObjectFile::getSection(unsigned SectionIndex) const {
2010   if (SectionIndex < 1 || SectionIndex > Sections.size())
2011     return malformedError("bad section index: " + Twine((int)SectionIndex));
2012 
2013   DataRefImpl DRI;
2014   DRI.d.a = SectionIndex - 1;
2015   return SectionRef(DRI, this);
2016 }
2017 
2018 Expected<SectionRef> MachOObjectFile::getSection(StringRef SectionName) const {
2019   for (const SectionRef &Section : sections()) {
2020     auto NameOrErr = Section.getName();
2021     if (!NameOrErr)
2022       return NameOrErr.takeError();
2023     if (*NameOrErr == SectionName)
2024       return Section;
2025   }
2026   return errorCodeToError(object_error::parse_failed);
2027 }
2028 
2029 bool MachOObjectFile::isSectionCompressed(DataRefImpl Sec) const {
2030   return false;
2031 }
2032 
2033 bool MachOObjectFile::isSectionText(DataRefImpl Sec) const {
2034   uint32_t Flags = getSectionFlags(*this, Sec);
2035   return Flags & MachO::S_ATTR_PURE_INSTRUCTIONS;
2036 }
2037 
2038 bool MachOObjectFile::isSectionData(DataRefImpl Sec) const {
2039   uint32_t Flags = getSectionFlags(*this, Sec);
2040   unsigned SectionType = Flags & MachO::SECTION_TYPE;
2041   return !(Flags & MachO::S_ATTR_PURE_INSTRUCTIONS) &&
2042          !(SectionType == MachO::S_ZEROFILL ||
2043            SectionType == MachO::S_GB_ZEROFILL);
2044 }
2045 
2046 bool MachOObjectFile::isSectionBSS(DataRefImpl Sec) const {
2047   uint32_t Flags = getSectionFlags(*this, Sec);
2048   unsigned SectionType = Flags & MachO::SECTION_TYPE;
2049   return !(Flags & MachO::S_ATTR_PURE_INSTRUCTIONS) &&
2050          (SectionType == MachO::S_ZEROFILL ||
2051           SectionType == MachO::S_GB_ZEROFILL);
2052 }
2053 
2054 bool MachOObjectFile::isDebugSection(DataRefImpl Sec) const {
2055   Expected<StringRef> SectionNameOrErr = getSectionName(Sec);
2056   if (!SectionNameOrErr) {
2057     // TODO: Report the error message properly.
2058     consumeError(SectionNameOrErr.takeError());
2059     return false;
2060   }
2061   StringRef SectionName = SectionNameOrErr.get();
2062   return SectionName.startswith("__debug") ||
2063          SectionName.startswith("__zdebug") ||
2064          SectionName.startswith("__apple") || SectionName == "__gdb_index" ||
2065          SectionName == "__swift_ast";
2066 }
2067 
2068 namespace {
2069 template <typename LoadCommandType>
2070 ArrayRef<uint8_t> getSegmentContents(const MachOObjectFile &Obj,
2071                                      MachOObjectFile::LoadCommandInfo LoadCmd,
2072                                      StringRef SegmentName) {
2073   auto SegmentOrErr = getStructOrErr<LoadCommandType>(Obj, LoadCmd.Ptr);
2074   if (!SegmentOrErr) {
2075     consumeError(SegmentOrErr.takeError());
2076     return {};
2077   }
2078   auto &Segment = SegmentOrErr.get();
2079   if (StringRef(Segment.segname, 16).startswith(SegmentName))
2080     return arrayRefFromStringRef(Obj.getData().slice(
2081         Segment.fileoff, Segment.fileoff + Segment.filesize));
2082   return {};
2083 }
2084 
2085 template <typename LoadCommandType>
2086 ArrayRef<uint8_t> getSegmentContents(const MachOObjectFile &Obj,
2087                                      MachOObjectFile::LoadCommandInfo LoadCmd) {
2088   auto SegmentOrErr = getStructOrErr<LoadCommandType>(Obj, LoadCmd.Ptr);
2089   if (!SegmentOrErr) {
2090     consumeError(SegmentOrErr.takeError());
2091     return {};
2092   }
2093   auto &Segment = SegmentOrErr.get();
2094   return arrayRefFromStringRef(
2095       Obj.getData().slice(Segment.fileoff, Segment.fileoff + Segment.filesize));
2096 }
2097 } // namespace
2098 
2099 ArrayRef<uint8_t>
2100 MachOObjectFile::getSegmentContents(StringRef SegmentName) const {
2101   for (auto LoadCmd : load_commands()) {
2102     ArrayRef<uint8_t> Contents;
2103     switch (LoadCmd.C.cmd) {
2104     case MachO::LC_SEGMENT:
2105       Contents = ::getSegmentContents<MachO::segment_command>(*this, LoadCmd,
2106                                                               SegmentName);
2107       break;
2108     case MachO::LC_SEGMENT_64:
2109       Contents = ::getSegmentContents<MachO::segment_command_64>(*this, LoadCmd,
2110                                                                  SegmentName);
2111       break;
2112     default:
2113       continue;
2114     }
2115     if (!Contents.empty())
2116       return Contents;
2117   }
2118   return {};
2119 }
2120 
2121 ArrayRef<uint8_t>
2122 MachOObjectFile::getSegmentContents(size_t SegmentIndex) const {
2123   size_t Idx = 0;
2124   for (auto LoadCmd : load_commands()) {
2125     switch (LoadCmd.C.cmd) {
2126     case MachO::LC_SEGMENT:
2127       if (Idx == SegmentIndex)
2128         return ::getSegmentContents<MachO::segment_command>(*this, LoadCmd);
2129       ++Idx;
2130       break;
2131     case MachO::LC_SEGMENT_64:
2132       if (Idx == SegmentIndex)
2133         return ::getSegmentContents<MachO::segment_command_64>(*this, LoadCmd);
2134       ++Idx;
2135       break;
2136     default:
2137       continue;
2138     }
2139   }
2140   return {};
2141 }
2142 
2143 unsigned MachOObjectFile::getSectionID(SectionRef Sec) const {
2144   return Sec.getRawDataRefImpl().d.a;
2145 }
2146 
2147 bool MachOObjectFile::isSectionVirtual(DataRefImpl Sec) const {
2148   uint32_t Flags = getSectionFlags(*this, Sec);
2149   unsigned SectionType = Flags & MachO::SECTION_TYPE;
2150   return SectionType == MachO::S_ZEROFILL ||
2151          SectionType == MachO::S_GB_ZEROFILL;
2152 }
2153 
2154 bool MachOObjectFile::isSectionBitcode(DataRefImpl Sec) const {
2155   StringRef SegmentName = getSectionFinalSegmentName(Sec);
2156   if (Expected<StringRef> NameOrErr = getSectionName(Sec))
2157     return (SegmentName == "__LLVM" && *NameOrErr == "__bitcode");
2158   return false;
2159 }
2160 
2161 bool MachOObjectFile::isSectionStripped(DataRefImpl Sec) const {
2162   if (is64Bit())
2163     return getSection64(Sec).offset == 0;
2164   return getSection(Sec).offset == 0;
2165 }
2166 
2167 relocation_iterator MachOObjectFile::section_rel_begin(DataRefImpl Sec) const {
2168   DataRefImpl Ret;
2169   Ret.d.a = Sec.d.a;
2170   Ret.d.b = 0;
2171   return relocation_iterator(RelocationRef(Ret, this));
2172 }
2173 
2174 relocation_iterator
2175 MachOObjectFile::section_rel_end(DataRefImpl Sec) const {
2176   uint32_t Num;
2177   if (is64Bit()) {
2178     MachO::section_64 Sect = getSection64(Sec);
2179     Num = Sect.nreloc;
2180   } else {
2181     MachO::section Sect = getSection(Sec);
2182     Num = Sect.nreloc;
2183   }
2184 
2185   DataRefImpl Ret;
2186   Ret.d.a = Sec.d.a;
2187   Ret.d.b = Num;
2188   return relocation_iterator(RelocationRef(Ret, this));
2189 }
2190 
2191 relocation_iterator MachOObjectFile::extrel_begin() const {
2192   DataRefImpl Ret;
2193   // for DYSYMTAB symbols, Ret.d.a == 0 for external relocations
2194   Ret.d.a = 0; // Would normally be a section index.
2195   Ret.d.b = 0; // Index into the external relocations
2196   return relocation_iterator(RelocationRef(Ret, this));
2197 }
2198 
2199 relocation_iterator MachOObjectFile::extrel_end() const {
2200   MachO::dysymtab_command DysymtabLoadCmd = getDysymtabLoadCommand();
2201   DataRefImpl Ret;
2202   // for DYSYMTAB symbols, Ret.d.a == 0 for external relocations
2203   Ret.d.a = 0; // Would normally be a section index.
2204   Ret.d.b = DysymtabLoadCmd.nextrel; // Index into the external relocations
2205   return relocation_iterator(RelocationRef(Ret, this));
2206 }
2207 
2208 relocation_iterator MachOObjectFile::locrel_begin() const {
2209   DataRefImpl Ret;
2210   // for DYSYMTAB symbols, Ret.d.a == 1 for local relocations
2211   Ret.d.a = 1; // Would normally be a section index.
2212   Ret.d.b = 0; // Index into the local relocations
2213   return relocation_iterator(RelocationRef(Ret, this));
2214 }
2215 
2216 relocation_iterator MachOObjectFile::locrel_end() const {
2217   MachO::dysymtab_command DysymtabLoadCmd = getDysymtabLoadCommand();
2218   DataRefImpl Ret;
2219   // for DYSYMTAB symbols, Ret.d.a == 1 for local relocations
2220   Ret.d.a = 1; // Would normally be a section index.
2221   Ret.d.b = DysymtabLoadCmd.nlocrel; // Index into the local relocations
2222   return relocation_iterator(RelocationRef(Ret, this));
2223 }
2224 
2225 void MachOObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
2226   ++Rel.d.b;
2227 }
2228 
2229 uint64_t MachOObjectFile::getRelocationOffset(DataRefImpl Rel) const {
2230   assert((getHeader().filetype == MachO::MH_OBJECT ||
2231           getHeader().filetype == MachO::MH_KEXT_BUNDLE) &&
2232          "Only implemented for MH_OBJECT && MH_KEXT_BUNDLE");
2233   MachO::any_relocation_info RE = getRelocation(Rel);
2234   return getAnyRelocationAddress(RE);
2235 }
2236 
2237 symbol_iterator
2238 MachOObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
2239   MachO::any_relocation_info RE = getRelocation(Rel);
2240   if (isRelocationScattered(RE))
2241     return symbol_end();
2242 
2243   uint32_t SymbolIdx = getPlainRelocationSymbolNum(RE);
2244   bool isExtern = getPlainRelocationExternal(RE);
2245   if (!isExtern)
2246     return symbol_end();
2247 
2248   MachO::symtab_command S = getSymtabLoadCommand();
2249   unsigned SymbolTableEntrySize = is64Bit() ?
2250     sizeof(MachO::nlist_64) :
2251     sizeof(MachO::nlist);
2252   uint64_t Offset = S.symoff + SymbolIdx * SymbolTableEntrySize;
2253   DataRefImpl Sym;
2254   Sym.p = reinterpret_cast<uintptr_t>(getPtr(*this, Offset));
2255   return symbol_iterator(SymbolRef(Sym, this));
2256 }
2257 
2258 section_iterator
2259 MachOObjectFile::getRelocationSection(DataRefImpl Rel) const {
2260   return section_iterator(getAnyRelocationSection(getRelocation(Rel)));
2261 }
2262 
2263 uint64_t MachOObjectFile::getRelocationType(DataRefImpl Rel) const {
2264   MachO::any_relocation_info RE = getRelocation(Rel);
2265   return getAnyRelocationType(RE);
2266 }
2267 
2268 void MachOObjectFile::getRelocationTypeName(
2269     DataRefImpl Rel, SmallVectorImpl<char> &Result) const {
2270   StringRef res;
2271   uint64_t RType = getRelocationType(Rel);
2272 
2273   unsigned Arch = this->getArch();
2274 
2275   switch (Arch) {
2276     case Triple::x86: {
2277       static const char *const Table[] =  {
2278         "GENERIC_RELOC_VANILLA",
2279         "GENERIC_RELOC_PAIR",
2280         "GENERIC_RELOC_SECTDIFF",
2281         "GENERIC_RELOC_PB_LA_PTR",
2282         "GENERIC_RELOC_LOCAL_SECTDIFF",
2283         "GENERIC_RELOC_TLV" };
2284 
2285       if (RType > 5)
2286         res = "Unknown";
2287       else
2288         res = Table[RType];
2289       break;
2290     }
2291     case Triple::x86_64: {
2292       static const char *const Table[] =  {
2293         "X86_64_RELOC_UNSIGNED",
2294         "X86_64_RELOC_SIGNED",
2295         "X86_64_RELOC_BRANCH",
2296         "X86_64_RELOC_GOT_LOAD",
2297         "X86_64_RELOC_GOT",
2298         "X86_64_RELOC_SUBTRACTOR",
2299         "X86_64_RELOC_SIGNED_1",
2300         "X86_64_RELOC_SIGNED_2",
2301         "X86_64_RELOC_SIGNED_4",
2302         "X86_64_RELOC_TLV" };
2303 
2304       if (RType > 9)
2305         res = "Unknown";
2306       else
2307         res = Table[RType];
2308       break;
2309     }
2310     case Triple::arm: {
2311       static const char *const Table[] =  {
2312         "ARM_RELOC_VANILLA",
2313         "ARM_RELOC_PAIR",
2314         "ARM_RELOC_SECTDIFF",
2315         "ARM_RELOC_LOCAL_SECTDIFF",
2316         "ARM_RELOC_PB_LA_PTR",
2317         "ARM_RELOC_BR24",
2318         "ARM_THUMB_RELOC_BR22",
2319         "ARM_THUMB_32BIT_BRANCH",
2320         "ARM_RELOC_HALF",
2321         "ARM_RELOC_HALF_SECTDIFF" };
2322 
2323       if (RType > 9)
2324         res = "Unknown";
2325       else
2326         res = Table[RType];
2327       break;
2328     }
2329     case Triple::aarch64:
2330     case Triple::aarch64_32: {
2331       static const char *const Table[] = {
2332         "ARM64_RELOC_UNSIGNED",           "ARM64_RELOC_SUBTRACTOR",
2333         "ARM64_RELOC_BRANCH26",           "ARM64_RELOC_PAGE21",
2334         "ARM64_RELOC_PAGEOFF12",          "ARM64_RELOC_GOT_LOAD_PAGE21",
2335         "ARM64_RELOC_GOT_LOAD_PAGEOFF12", "ARM64_RELOC_POINTER_TO_GOT",
2336         "ARM64_RELOC_TLVP_LOAD_PAGE21",   "ARM64_RELOC_TLVP_LOAD_PAGEOFF12",
2337         "ARM64_RELOC_ADDEND"
2338       };
2339 
2340       if (RType >= std::size(Table))
2341         res = "Unknown";
2342       else
2343         res = Table[RType];
2344       break;
2345     }
2346     case Triple::ppc: {
2347       static const char *const Table[] =  {
2348         "PPC_RELOC_VANILLA",
2349         "PPC_RELOC_PAIR",
2350         "PPC_RELOC_BR14",
2351         "PPC_RELOC_BR24",
2352         "PPC_RELOC_HI16",
2353         "PPC_RELOC_LO16",
2354         "PPC_RELOC_HA16",
2355         "PPC_RELOC_LO14",
2356         "PPC_RELOC_SECTDIFF",
2357         "PPC_RELOC_PB_LA_PTR",
2358         "PPC_RELOC_HI16_SECTDIFF",
2359         "PPC_RELOC_LO16_SECTDIFF",
2360         "PPC_RELOC_HA16_SECTDIFF",
2361         "PPC_RELOC_JBSR",
2362         "PPC_RELOC_LO14_SECTDIFF",
2363         "PPC_RELOC_LOCAL_SECTDIFF" };
2364 
2365       if (RType > 15)
2366         res = "Unknown";
2367       else
2368         res = Table[RType];
2369       break;
2370     }
2371     case Triple::UnknownArch:
2372       res = "Unknown";
2373       break;
2374   }
2375   Result.append(res.begin(), res.end());
2376 }
2377 
2378 uint8_t MachOObjectFile::getRelocationLength(DataRefImpl Rel) const {
2379   MachO::any_relocation_info RE = getRelocation(Rel);
2380   return getAnyRelocationLength(RE);
2381 }
2382 
2383 //
2384 // guessLibraryShortName() is passed a name of a dynamic library and returns a
2385 // guess on what the short name is.  Then name is returned as a substring of the
2386 // StringRef Name passed in.  The name of the dynamic library is recognized as
2387 // a framework if it has one of the two following forms:
2388 //      Foo.framework/Versions/A/Foo
2389 //      Foo.framework/Foo
2390 // Where A and Foo can be any string.  And may contain a trailing suffix
2391 // starting with an underbar.  If the Name is recognized as a framework then
2392 // isFramework is set to true else it is set to false.  If the Name has a
2393 // suffix then Suffix is set to the substring in Name that contains the suffix
2394 // else it is set to a NULL StringRef.
2395 //
2396 // The Name of the dynamic library is recognized as a library name if it has
2397 // one of the two following forms:
2398 //      libFoo.A.dylib
2399 //      libFoo.dylib
2400 //
2401 // The library may have a suffix trailing the name Foo of the form:
2402 //      libFoo_profile.A.dylib
2403 //      libFoo_profile.dylib
2404 // These dyld image suffixes are separated from the short name by a '_'
2405 // character. Because the '_' character is commonly used to separate words in
2406 // filenames guessLibraryShortName() cannot reliably separate a dylib's short
2407 // name from an arbitrary image suffix; imagine if both the short name and the
2408 // suffix contains an '_' character! To better deal with this ambiguity,
2409 // guessLibraryShortName() will recognize only "_debug" and "_profile" as valid
2410 // Suffix values. Calling code needs to be tolerant of guessLibraryShortName()
2411 // guessing incorrectly.
2412 //
2413 // The Name of the dynamic library is also recognized as a library name if it
2414 // has the following form:
2415 //      Foo.qtx
2416 //
2417 // If the Name of the dynamic library is none of the forms above then a NULL
2418 // StringRef is returned.
2419 StringRef MachOObjectFile::guessLibraryShortName(StringRef Name,
2420                                                  bool &isFramework,
2421                                                  StringRef &Suffix) {
2422   StringRef Foo, F, DotFramework, V, Dylib, Lib, Dot, Qtx;
2423   size_t a, b, c, d, Idx;
2424 
2425   isFramework = false;
2426   Suffix = StringRef();
2427 
2428   // Pull off the last component and make Foo point to it
2429   a = Name.rfind('/');
2430   if (a == Name.npos || a == 0)
2431     goto guess_library;
2432   Foo = Name.slice(a+1, Name.npos);
2433 
2434   // Look for a suffix starting with a '_'
2435   Idx = Foo.rfind('_');
2436   if (Idx != Foo.npos && Foo.size() >= 2) {
2437     Suffix = Foo.slice(Idx, Foo.npos);
2438     if (Suffix != "_debug" && Suffix != "_profile")
2439       Suffix = StringRef();
2440     else
2441       Foo = Foo.slice(0, Idx);
2442   }
2443 
2444   // First look for the form Foo.framework/Foo
2445   b = Name.rfind('/', a);
2446   if (b == Name.npos)
2447     Idx = 0;
2448   else
2449     Idx = b+1;
2450   F = Name.slice(Idx, Idx + Foo.size());
2451   DotFramework = Name.slice(Idx + Foo.size(),
2452                             Idx + Foo.size() + sizeof(".framework/")-1);
2453   if (F == Foo && DotFramework == ".framework/") {
2454     isFramework = true;
2455     return Foo;
2456   }
2457 
2458   // Next look for the form Foo.framework/Versions/A/Foo
2459   if (b == Name.npos)
2460     goto guess_library;
2461   c =  Name.rfind('/', b);
2462   if (c == Name.npos || c == 0)
2463     goto guess_library;
2464   V = Name.slice(c+1, Name.npos);
2465   if (!V.startswith("Versions/"))
2466     goto guess_library;
2467   d =  Name.rfind('/', c);
2468   if (d == Name.npos)
2469     Idx = 0;
2470   else
2471     Idx = d+1;
2472   F = Name.slice(Idx, Idx + Foo.size());
2473   DotFramework = Name.slice(Idx + Foo.size(),
2474                             Idx + Foo.size() + sizeof(".framework/")-1);
2475   if (F == Foo && DotFramework == ".framework/") {
2476     isFramework = true;
2477     return Foo;
2478   }
2479 
2480 guess_library:
2481   // pull off the suffix after the "." and make a point to it
2482   a = Name.rfind('.');
2483   if (a == Name.npos || a == 0)
2484     return StringRef();
2485   Dylib = Name.slice(a, Name.npos);
2486   if (Dylib != ".dylib")
2487     goto guess_qtx;
2488 
2489   // First pull off the version letter for the form Foo.A.dylib if any.
2490   if (a >= 3) {
2491     Dot = Name.slice(a-2, a-1);
2492     if (Dot == ".")
2493       a = a - 2;
2494   }
2495 
2496   b = Name.rfind('/', a);
2497   if (b == Name.npos)
2498     b = 0;
2499   else
2500     b = b+1;
2501   // ignore any suffix after an underbar like Foo_profile.A.dylib
2502   Idx = Name.rfind('_');
2503   if (Idx != Name.npos && Idx != b) {
2504     Lib = Name.slice(b, Idx);
2505     Suffix = Name.slice(Idx, a);
2506     if (Suffix != "_debug" && Suffix != "_profile") {
2507       Suffix = StringRef();
2508       Lib = Name.slice(b, a);
2509     }
2510   }
2511   else
2512     Lib = Name.slice(b, a);
2513   // There are incorrect library names of the form:
2514   // libATS.A_profile.dylib so check for these.
2515   if (Lib.size() >= 3) {
2516     Dot = Lib.slice(Lib.size()-2, Lib.size()-1);
2517     if (Dot == ".")
2518       Lib = Lib.slice(0, Lib.size()-2);
2519   }
2520   return Lib;
2521 
2522 guess_qtx:
2523   Qtx = Name.slice(a, Name.npos);
2524   if (Qtx != ".qtx")
2525     return StringRef();
2526   b = Name.rfind('/', a);
2527   if (b == Name.npos)
2528     Lib = Name.slice(0, a);
2529   else
2530     Lib = Name.slice(b+1, a);
2531   // There are library names of the form: QT.A.qtx so check for these.
2532   if (Lib.size() >= 3) {
2533     Dot = Lib.slice(Lib.size()-2, Lib.size()-1);
2534     if (Dot == ".")
2535       Lib = Lib.slice(0, Lib.size()-2);
2536   }
2537   return Lib;
2538 }
2539 
2540 // getLibraryShortNameByIndex() is used to get the short name of the library
2541 // for an undefined symbol in a linked Mach-O binary that was linked with the
2542 // normal two-level namespace default (that is MH_TWOLEVEL in the header).
2543 // It is passed the index (0 - based) of the library as translated from
2544 // GET_LIBRARY_ORDINAL (1 - based).
2545 std::error_code MachOObjectFile::getLibraryShortNameByIndex(unsigned Index,
2546                                                          StringRef &Res) const {
2547   if (Index >= Libraries.size())
2548     return object_error::parse_failed;
2549 
2550   // If the cache of LibrariesShortNames is not built up do that first for
2551   // all the Libraries.
2552   if (LibrariesShortNames.size() == 0) {
2553     for (unsigned i = 0; i < Libraries.size(); i++) {
2554       auto CommandOrErr =
2555         getStructOrErr<MachO::dylib_command>(*this, Libraries[i]);
2556       if (!CommandOrErr)
2557         return object_error::parse_failed;
2558       MachO::dylib_command D = CommandOrErr.get();
2559       if (D.dylib.name >= D.cmdsize)
2560         return object_error::parse_failed;
2561       const char *P = (const char *)(Libraries[i]) + D.dylib.name;
2562       StringRef Name = StringRef(P);
2563       if (D.dylib.name+Name.size() >= D.cmdsize)
2564         return object_error::parse_failed;
2565       StringRef Suffix;
2566       bool isFramework;
2567       StringRef shortName = guessLibraryShortName(Name, isFramework, Suffix);
2568       if (shortName.empty())
2569         LibrariesShortNames.push_back(Name);
2570       else
2571         LibrariesShortNames.push_back(shortName);
2572     }
2573   }
2574 
2575   Res = LibrariesShortNames[Index];
2576   return std::error_code();
2577 }
2578 
2579 uint32_t MachOObjectFile::getLibraryCount() const {
2580   return Libraries.size();
2581 }
2582 
2583 section_iterator
2584 MachOObjectFile::getRelocationRelocatedSection(relocation_iterator Rel) const {
2585   DataRefImpl Sec;
2586   Sec.d.a = Rel->getRawDataRefImpl().d.a;
2587   return section_iterator(SectionRef(Sec, this));
2588 }
2589 
2590 basic_symbol_iterator MachOObjectFile::symbol_begin() const {
2591   DataRefImpl DRI;
2592   MachO::symtab_command Symtab = getSymtabLoadCommand();
2593   if (!SymtabLoadCmd || Symtab.nsyms == 0)
2594     return basic_symbol_iterator(SymbolRef(DRI, this));
2595 
2596   return getSymbolByIndex(0);
2597 }
2598 
2599 basic_symbol_iterator MachOObjectFile::symbol_end() const {
2600   DataRefImpl DRI;
2601   MachO::symtab_command Symtab = getSymtabLoadCommand();
2602   if (!SymtabLoadCmd || Symtab.nsyms == 0)
2603     return basic_symbol_iterator(SymbolRef(DRI, this));
2604 
2605   unsigned SymbolTableEntrySize = is64Bit() ?
2606     sizeof(MachO::nlist_64) :
2607     sizeof(MachO::nlist);
2608   unsigned Offset = Symtab.symoff +
2609     Symtab.nsyms * SymbolTableEntrySize;
2610   DRI.p = reinterpret_cast<uintptr_t>(getPtr(*this, Offset));
2611   return basic_symbol_iterator(SymbolRef(DRI, this));
2612 }
2613 
2614 symbol_iterator MachOObjectFile::getSymbolByIndex(unsigned Index) const {
2615   MachO::symtab_command Symtab = getSymtabLoadCommand();
2616   if (!SymtabLoadCmd || Index >= Symtab.nsyms)
2617     report_fatal_error("Requested symbol index is out of range.");
2618   unsigned SymbolTableEntrySize =
2619     is64Bit() ? sizeof(MachO::nlist_64) : sizeof(MachO::nlist);
2620   DataRefImpl DRI;
2621   DRI.p = reinterpret_cast<uintptr_t>(getPtr(*this, Symtab.symoff));
2622   DRI.p += Index * SymbolTableEntrySize;
2623   return basic_symbol_iterator(SymbolRef(DRI, this));
2624 }
2625 
2626 uint64_t MachOObjectFile::getSymbolIndex(DataRefImpl Symb) const {
2627   MachO::symtab_command Symtab = getSymtabLoadCommand();
2628   if (!SymtabLoadCmd)
2629     report_fatal_error("getSymbolIndex() called with no symbol table symbol");
2630   unsigned SymbolTableEntrySize =
2631     is64Bit() ? sizeof(MachO::nlist_64) : sizeof(MachO::nlist);
2632   DataRefImpl DRIstart;
2633   DRIstart.p = reinterpret_cast<uintptr_t>(getPtr(*this, Symtab.symoff));
2634   uint64_t Index = (Symb.p - DRIstart.p) / SymbolTableEntrySize;
2635   return Index;
2636 }
2637 
2638 section_iterator MachOObjectFile::section_begin() const {
2639   DataRefImpl DRI;
2640   return section_iterator(SectionRef(DRI, this));
2641 }
2642 
2643 section_iterator MachOObjectFile::section_end() const {
2644   DataRefImpl DRI;
2645   DRI.d.a = Sections.size();
2646   return section_iterator(SectionRef(DRI, this));
2647 }
2648 
2649 uint8_t MachOObjectFile::getBytesInAddress() const {
2650   return is64Bit() ? 8 : 4;
2651 }
2652 
2653 StringRef MachOObjectFile::getFileFormatName() const {
2654   unsigned CPUType = getCPUType(*this);
2655   if (!is64Bit()) {
2656     switch (CPUType) {
2657     case MachO::CPU_TYPE_I386:
2658       return "Mach-O 32-bit i386";
2659     case MachO::CPU_TYPE_ARM:
2660       return "Mach-O arm";
2661     case MachO::CPU_TYPE_ARM64_32:
2662       return "Mach-O arm64 (ILP32)";
2663     case MachO::CPU_TYPE_POWERPC:
2664       return "Mach-O 32-bit ppc";
2665     default:
2666       return "Mach-O 32-bit unknown";
2667     }
2668   }
2669 
2670   switch (CPUType) {
2671   case MachO::CPU_TYPE_X86_64:
2672     return "Mach-O 64-bit x86-64";
2673   case MachO::CPU_TYPE_ARM64:
2674     return "Mach-O arm64";
2675   case MachO::CPU_TYPE_POWERPC64:
2676     return "Mach-O 64-bit ppc64";
2677   default:
2678     return "Mach-O 64-bit unknown";
2679   }
2680 }
2681 
2682 Triple::ArchType MachOObjectFile::getArch(uint32_t CPUType, uint32_t CPUSubType) {
2683   switch (CPUType) {
2684   case MachO::CPU_TYPE_I386:
2685     return Triple::x86;
2686   case MachO::CPU_TYPE_X86_64:
2687     return Triple::x86_64;
2688   case MachO::CPU_TYPE_ARM:
2689     return Triple::arm;
2690   case MachO::CPU_TYPE_ARM64:
2691     return Triple::aarch64;
2692   case MachO::CPU_TYPE_ARM64_32:
2693     return Triple::aarch64_32;
2694   case MachO::CPU_TYPE_POWERPC:
2695     return Triple::ppc;
2696   case MachO::CPU_TYPE_POWERPC64:
2697     return Triple::ppc64;
2698   default:
2699     return Triple::UnknownArch;
2700   }
2701 }
2702 
2703 Triple MachOObjectFile::getArchTriple(uint32_t CPUType, uint32_t CPUSubType,
2704                                       const char **McpuDefault,
2705                                       const char **ArchFlag) {
2706   if (McpuDefault)
2707     *McpuDefault = nullptr;
2708   if (ArchFlag)
2709     *ArchFlag = nullptr;
2710 
2711   switch (CPUType) {
2712   case MachO::CPU_TYPE_I386:
2713     switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2714     case MachO::CPU_SUBTYPE_I386_ALL:
2715       if (ArchFlag)
2716         *ArchFlag = "i386";
2717       return Triple("i386-apple-darwin");
2718     default:
2719       return Triple();
2720     }
2721   case MachO::CPU_TYPE_X86_64:
2722     switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2723     case MachO::CPU_SUBTYPE_X86_64_ALL:
2724       if (ArchFlag)
2725         *ArchFlag = "x86_64";
2726       return Triple("x86_64-apple-darwin");
2727     case MachO::CPU_SUBTYPE_X86_64_H:
2728       if (ArchFlag)
2729         *ArchFlag = "x86_64h";
2730       return Triple("x86_64h-apple-darwin");
2731     default:
2732       return Triple();
2733     }
2734   case MachO::CPU_TYPE_ARM:
2735     switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2736     case MachO::CPU_SUBTYPE_ARM_V4T:
2737       if (ArchFlag)
2738         *ArchFlag = "armv4t";
2739       return Triple("armv4t-apple-darwin");
2740     case MachO::CPU_SUBTYPE_ARM_V5TEJ:
2741       if (ArchFlag)
2742         *ArchFlag = "armv5e";
2743       return Triple("armv5e-apple-darwin");
2744     case MachO::CPU_SUBTYPE_ARM_XSCALE:
2745       if (ArchFlag)
2746         *ArchFlag = "xscale";
2747       return Triple("xscale-apple-darwin");
2748     case MachO::CPU_SUBTYPE_ARM_V6:
2749       if (ArchFlag)
2750         *ArchFlag = "armv6";
2751       return Triple("armv6-apple-darwin");
2752     case MachO::CPU_SUBTYPE_ARM_V6M:
2753       if (McpuDefault)
2754         *McpuDefault = "cortex-m0";
2755       if (ArchFlag)
2756         *ArchFlag = "armv6m";
2757       return Triple("armv6m-apple-darwin");
2758     case MachO::CPU_SUBTYPE_ARM_V7:
2759       if (ArchFlag)
2760         *ArchFlag = "armv7";
2761       return Triple("armv7-apple-darwin");
2762     case MachO::CPU_SUBTYPE_ARM_V7EM:
2763       if (McpuDefault)
2764         *McpuDefault = "cortex-m4";
2765       if (ArchFlag)
2766         *ArchFlag = "armv7em";
2767       return Triple("thumbv7em-apple-darwin");
2768     case MachO::CPU_SUBTYPE_ARM_V7K:
2769       if (McpuDefault)
2770         *McpuDefault = "cortex-a7";
2771       if (ArchFlag)
2772         *ArchFlag = "armv7k";
2773       return Triple("armv7k-apple-darwin");
2774     case MachO::CPU_SUBTYPE_ARM_V7M:
2775       if (McpuDefault)
2776         *McpuDefault = "cortex-m3";
2777       if (ArchFlag)
2778         *ArchFlag = "armv7m";
2779       return Triple("thumbv7m-apple-darwin");
2780     case MachO::CPU_SUBTYPE_ARM_V7S:
2781       if (McpuDefault)
2782         *McpuDefault = "cortex-a7";
2783       if (ArchFlag)
2784         *ArchFlag = "armv7s";
2785       return Triple("armv7s-apple-darwin");
2786     default:
2787       return Triple();
2788     }
2789   case MachO::CPU_TYPE_ARM64:
2790     switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2791     case MachO::CPU_SUBTYPE_ARM64_ALL:
2792       if (McpuDefault)
2793         *McpuDefault = "cyclone";
2794       if (ArchFlag)
2795         *ArchFlag = "arm64";
2796       return Triple("arm64-apple-darwin");
2797     case MachO::CPU_SUBTYPE_ARM64E:
2798       if (McpuDefault)
2799         *McpuDefault = "apple-a12";
2800       if (ArchFlag)
2801         *ArchFlag = "arm64e";
2802       return Triple("arm64e-apple-darwin");
2803     default:
2804       return Triple();
2805     }
2806   case MachO::CPU_TYPE_ARM64_32:
2807     switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2808     case MachO::CPU_SUBTYPE_ARM64_32_V8:
2809       if (McpuDefault)
2810         *McpuDefault = "cyclone";
2811       if (ArchFlag)
2812         *ArchFlag = "arm64_32";
2813       return Triple("arm64_32-apple-darwin");
2814     default:
2815       return Triple();
2816     }
2817   case MachO::CPU_TYPE_POWERPC:
2818     switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2819     case MachO::CPU_SUBTYPE_POWERPC_ALL:
2820       if (ArchFlag)
2821         *ArchFlag = "ppc";
2822       return Triple("ppc-apple-darwin");
2823     default:
2824       return Triple();
2825     }
2826   case MachO::CPU_TYPE_POWERPC64:
2827     switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2828     case MachO::CPU_SUBTYPE_POWERPC_ALL:
2829       if (ArchFlag)
2830         *ArchFlag = "ppc64";
2831       return Triple("ppc64-apple-darwin");
2832     default:
2833       return Triple();
2834     }
2835   default:
2836     return Triple();
2837   }
2838 }
2839 
2840 Triple MachOObjectFile::getHostArch() {
2841   return Triple(sys::getDefaultTargetTriple());
2842 }
2843 
2844 bool MachOObjectFile::isValidArch(StringRef ArchFlag) {
2845   auto validArchs = getValidArchs();
2846   return llvm::is_contained(validArchs, ArchFlag);
2847 }
2848 
2849 ArrayRef<StringRef> MachOObjectFile::getValidArchs() {
2850   static const std::array<StringRef, 18> ValidArchs = {{
2851       "i386",
2852       "x86_64",
2853       "x86_64h",
2854       "armv4t",
2855       "arm",
2856       "armv5e",
2857       "armv6",
2858       "armv6m",
2859       "armv7",
2860       "armv7em",
2861       "armv7k",
2862       "armv7m",
2863       "armv7s",
2864       "arm64",
2865       "arm64e",
2866       "arm64_32",
2867       "ppc",
2868       "ppc64",
2869   }};
2870 
2871   return ValidArchs;
2872 }
2873 
2874 Triple::ArchType MachOObjectFile::getArch() const {
2875   return getArch(getCPUType(*this), getCPUSubType(*this));
2876 }
2877 
2878 Triple MachOObjectFile::getArchTriple(const char **McpuDefault) const {
2879   return getArchTriple(Header.cputype, Header.cpusubtype, McpuDefault);
2880 }
2881 
2882 relocation_iterator MachOObjectFile::section_rel_begin(unsigned Index) const {
2883   DataRefImpl DRI;
2884   DRI.d.a = Index;
2885   return section_rel_begin(DRI);
2886 }
2887 
2888 relocation_iterator MachOObjectFile::section_rel_end(unsigned Index) const {
2889   DataRefImpl DRI;
2890   DRI.d.a = Index;
2891   return section_rel_end(DRI);
2892 }
2893 
2894 dice_iterator MachOObjectFile::begin_dices() const {
2895   DataRefImpl DRI;
2896   if (!DataInCodeLoadCmd)
2897     return dice_iterator(DiceRef(DRI, this));
2898 
2899   MachO::linkedit_data_command DicLC = getDataInCodeLoadCommand();
2900   DRI.p = reinterpret_cast<uintptr_t>(getPtr(*this, DicLC.dataoff));
2901   return dice_iterator(DiceRef(DRI, this));
2902 }
2903 
2904 dice_iterator MachOObjectFile::end_dices() const {
2905   DataRefImpl DRI;
2906   if (!DataInCodeLoadCmd)
2907     return dice_iterator(DiceRef(DRI, this));
2908 
2909   MachO::linkedit_data_command DicLC = getDataInCodeLoadCommand();
2910   unsigned Offset = DicLC.dataoff + DicLC.datasize;
2911   DRI.p = reinterpret_cast<uintptr_t>(getPtr(*this, Offset));
2912   return dice_iterator(DiceRef(DRI, this));
2913 }
2914 
2915 ExportEntry::ExportEntry(Error *E, const MachOObjectFile *O,
2916                          ArrayRef<uint8_t> T) : E(E), O(O), Trie(T) {}
2917 
2918 void ExportEntry::moveToFirst() {
2919   ErrorAsOutParameter ErrAsOutParam(E);
2920   pushNode(0);
2921   if (*E)
2922     return;
2923   pushDownUntilBottom();
2924 }
2925 
2926 void ExportEntry::moveToEnd() {
2927   Stack.clear();
2928   Done = true;
2929 }
2930 
2931 bool ExportEntry::operator==(const ExportEntry &Other) const {
2932   // Common case, one at end, other iterating from begin.
2933   if (Done || Other.Done)
2934     return (Done == Other.Done);
2935   // Not equal if different stack sizes.
2936   if (Stack.size() != Other.Stack.size())
2937     return false;
2938   // Not equal if different cumulative strings.
2939   if (!CumulativeString.equals(Other.CumulativeString))
2940     return false;
2941   // Equal if all nodes in both stacks match.
2942   for (unsigned i=0; i < Stack.size(); ++i) {
2943     if (Stack[i].Start != Other.Stack[i].Start)
2944       return false;
2945   }
2946   return true;
2947 }
2948 
2949 uint64_t ExportEntry::readULEB128(const uint8_t *&Ptr, const char **error) {
2950   unsigned Count;
2951   uint64_t Result = decodeULEB128(Ptr, &Count, Trie.end(), error);
2952   Ptr += Count;
2953   if (Ptr > Trie.end())
2954     Ptr = Trie.end();
2955   return Result;
2956 }
2957 
2958 StringRef ExportEntry::name() const {
2959   return CumulativeString;
2960 }
2961 
2962 uint64_t ExportEntry::flags() const {
2963   return Stack.back().Flags;
2964 }
2965 
2966 uint64_t ExportEntry::address() const {
2967   return Stack.back().Address;
2968 }
2969 
2970 uint64_t ExportEntry::other() const {
2971   return Stack.back().Other;
2972 }
2973 
2974 StringRef ExportEntry::otherName() const {
2975   const char* ImportName = Stack.back().ImportName;
2976   if (ImportName)
2977     return StringRef(ImportName);
2978   return StringRef();
2979 }
2980 
2981 uint32_t ExportEntry::nodeOffset() const {
2982   return Stack.back().Start - Trie.begin();
2983 }
2984 
2985 ExportEntry::NodeState::NodeState(const uint8_t *Ptr)
2986     : Start(Ptr), Current(Ptr) {}
2987 
2988 void ExportEntry::pushNode(uint64_t offset) {
2989   ErrorAsOutParameter ErrAsOutParam(E);
2990   const uint8_t *Ptr = Trie.begin() + offset;
2991   NodeState State(Ptr);
2992   const char *error;
2993   uint64_t ExportInfoSize = readULEB128(State.Current, &error);
2994   if (error) {
2995     *E = malformedError("export info size " + Twine(error) +
2996                         " in export trie data at node: 0x" +
2997                         Twine::utohexstr(offset));
2998     moveToEnd();
2999     return;
3000   }
3001   State.IsExportNode = (ExportInfoSize != 0);
3002   const uint8_t* Children = State.Current + ExportInfoSize;
3003   if (Children > Trie.end()) {
3004     *E = malformedError(
3005         "export info size: 0x" + Twine::utohexstr(ExportInfoSize) +
3006         " in export trie data at node: 0x" + Twine::utohexstr(offset) +
3007         " too big and extends past end of trie data");
3008     moveToEnd();
3009     return;
3010   }
3011   if (State.IsExportNode) {
3012     const uint8_t *ExportStart = State.Current;
3013     State.Flags = readULEB128(State.Current, &error);
3014     if (error) {
3015       *E = malformedError("flags " + Twine(error) +
3016                           " in export trie data at node: 0x" +
3017                           Twine::utohexstr(offset));
3018       moveToEnd();
3019       return;
3020     }
3021     uint64_t Kind = State.Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK;
3022     if (State.Flags != 0 &&
3023         (Kind != MachO::EXPORT_SYMBOL_FLAGS_KIND_REGULAR &&
3024          Kind != MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE &&
3025          Kind != MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL)) {
3026       *E = malformedError(
3027           "unsupported exported symbol kind: " + Twine((int)Kind) +
3028           " in flags: 0x" + Twine::utohexstr(State.Flags) +
3029           " in export trie data at node: 0x" + Twine::utohexstr(offset));
3030       moveToEnd();
3031       return;
3032     }
3033     if (State.Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT) {
3034       State.Address = 0;
3035       State.Other = readULEB128(State.Current, &error); // dylib ordinal
3036       if (error) {
3037         *E = malformedError("dylib ordinal of re-export " + Twine(error) +
3038                             " in export trie data at node: 0x" +
3039                             Twine::utohexstr(offset));
3040         moveToEnd();
3041         return;
3042       }
3043       if (O != nullptr) {
3044         // Only positive numbers represent library ordinals. Zero and negative
3045         // numbers have special meaning (see BindSpecialDylib).
3046         if ((int64_t)State.Other > 0 && State.Other > O->getLibraryCount()) {
3047           *E = malformedError(
3048               "bad library ordinal: " + Twine((int)State.Other) + " (max " +
3049               Twine((int)O->getLibraryCount()) +
3050               ") in export trie data at node: 0x" + Twine::utohexstr(offset));
3051           moveToEnd();
3052           return;
3053         }
3054       }
3055       State.ImportName = reinterpret_cast<const char*>(State.Current);
3056       if (*State.ImportName == '\0') {
3057         State.Current++;
3058       } else {
3059         const uint8_t *End = State.Current + 1;
3060         if (End >= Trie.end()) {
3061           *E = malformedError("import name of re-export in export trie data at "
3062                               "node: 0x" +
3063                               Twine::utohexstr(offset) +
3064                               " starts past end of trie data");
3065           moveToEnd();
3066           return;
3067         }
3068         while(*End != '\0' && End < Trie.end())
3069           End++;
3070         if (*End != '\0') {
3071           *E = malformedError("import name of re-export in export trie data at "
3072                               "node: 0x" +
3073                               Twine::utohexstr(offset) +
3074                               " extends past end of trie data");
3075           moveToEnd();
3076           return;
3077         }
3078         State.Current = End + 1;
3079       }
3080     } else {
3081       State.Address = readULEB128(State.Current, &error);
3082       if (error) {
3083         *E = malformedError("address " + Twine(error) +
3084                             " in export trie data at node: 0x" +
3085                             Twine::utohexstr(offset));
3086         moveToEnd();
3087         return;
3088       }
3089       if (State.Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER) {
3090         State.Other = readULEB128(State.Current, &error);
3091         if (error) {
3092           *E = malformedError("resolver of stub and resolver " + Twine(error) +
3093                               " in export trie data at node: 0x" +
3094                               Twine::utohexstr(offset));
3095           moveToEnd();
3096           return;
3097         }
3098       }
3099     }
3100     if(ExportStart + ExportInfoSize != State.Current) {
3101       *E = malformedError(
3102           "inconsistent export info size: 0x" +
3103           Twine::utohexstr(ExportInfoSize) + " where actual size was: 0x" +
3104           Twine::utohexstr(State.Current - ExportStart) +
3105           " in export trie data at node: 0x" + Twine::utohexstr(offset));
3106       moveToEnd();
3107       return;
3108     }
3109   }
3110   State.ChildCount = *Children;
3111   if (State.ChildCount != 0 && Children + 1 >= Trie.end()) {
3112     *E = malformedError("byte for count of childern in export trie data at "
3113                         "node: 0x" +
3114                         Twine::utohexstr(offset) +
3115                         " extends past end of trie data");
3116     moveToEnd();
3117     return;
3118   }
3119   State.Current = Children + 1;
3120   State.NextChildIndex = 0;
3121   State.ParentStringLength = CumulativeString.size();
3122   Stack.push_back(State);
3123 }
3124 
3125 void ExportEntry::pushDownUntilBottom() {
3126   ErrorAsOutParameter ErrAsOutParam(E);
3127   const char *error;
3128   while (Stack.back().NextChildIndex < Stack.back().ChildCount) {
3129     NodeState &Top = Stack.back();
3130     CumulativeString.resize(Top.ParentStringLength);
3131     for (;*Top.Current != 0 && Top.Current < Trie.end(); Top.Current++) {
3132       char C = *Top.Current;
3133       CumulativeString.push_back(C);
3134     }
3135     if (Top.Current >= Trie.end()) {
3136       *E = malformedError("edge sub-string in export trie data at node: 0x" +
3137                           Twine::utohexstr(Top.Start - Trie.begin()) +
3138                           " for child #" + Twine((int)Top.NextChildIndex) +
3139                           " extends past end of trie data");
3140       moveToEnd();
3141       return;
3142     }
3143     Top.Current += 1;
3144     uint64_t childNodeIndex = readULEB128(Top.Current, &error);
3145     if (error) {
3146       *E = malformedError("child node offset " + Twine(error) +
3147                           " in export trie data at node: 0x" +
3148                           Twine::utohexstr(Top.Start - Trie.begin()));
3149       moveToEnd();
3150       return;
3151     }
3152     for (const NodeState &node : nodes()) {
3153       if (node.Start == Trie.begin() + childNodeIndex){
3154         *E = malformedError("loop in childern in export trie data at node: 0x" +
3155                             Twine::utohexstr(Top.Start - Trie.begin()) +
3156                             " back to node: 0x" +
3157                             Twine::utohexstr(childNodeIndex));
3158         moveToEnd();
3159         return;
3160       }
3161     }
3162     Top.NextChildIndex += 1;
3163     pushNode(childNodeIndex);
3164     if (*E)
3165       return;
3166   }
3167   if (!Stack.back().IsExportNode) {
3168     *E = malformedError("node is not an export node in export trie data at "
3169                         "node: 0x" +
3170                         Twine::utohexstr(Stack.back().Start - Trie.begin()));
3171     moveToEnd();
3172     return;
3173   }
3174 }
3175 
3176 // We have a trie data structure and need a way to walk it that is compatible
3177 // with the C++ iterator model. The solution is a non-recursive depth first
3178 // traversal where the iterator contains a stack of parent nodes along with a
3179 // string that is the accumulation of all edge strings along the parent chain
3180 // to this point.
3181 //
3182 // There is one "export" node for each exported symbol.  But because some
3183 // symbols may be a prefix of another symbol (e.g. _dup and _dup2), an export
3184 // node may have child nodes too.
3185 //
3186 // The algorithm for moveNext() is to keep moving down the leftmost unvisited
3187 // child until hitting a node with no children (which is an export node or
3188 // else the trie is malformed). On the way down, each node is pushed on the
3189 // stack ivar.  If there is no more ways down, it pops up one and tries to go
3190 // down a sibling path until a childless node is reached.
3191 void ExportEntry::moveNext() {
3192   assert(!Stack.empty() && "ExportEntry::moveNext() with empty node stack");
3193   if (!Stack.back().IsExportNode) {
3194     *E = malformedError("node is not an export node in export trie data at "
3195                         "node: 0x" +
3196                         Twine::utohexstr(Stack.back().Start - Trie.begin()));
3197     moveToEnd();
3198     return;
3199   }
3200 
3201   Stack.pop_back();
3202   while (!Stack.empty()) {
3203     NodeState &Top = Stack.back();
3204     if (Top.NextChildIndex < Top.ChildCount) {
3205       pushDownUntilBottom();
3206       // Now at the next export node.
3207       return;
3208     } else {
3209       if (Top.IsExportNode) {
3210         // This node has no children but is itself an export node.
3211         CumulativeString.resize(Top.ParentStringLength);
3212         return;
3213       }
3214       Stack.pop_back();
3215     }
3216   }
3217   Done = true;
3218 }
3219 
3220 iterator_range<export_iterator>
3221 MachOObjectFile::exports(Error &E, ArrayRef<uint8_t> Trie,
3222                          const MachOObjectFile *O) {
3223   ExportEntry Start(&E, O, Trie);
3224   if (Trie.empty())
3225     Start.moveToEnd();
3226   else
3227     Start.moveToFirst();
3228 
3229   ExportEntry Finish(&E, O, Trie);
3230   Finish.moveToEnd();
3231 
3232   return make_range(export_iterator(Start), export_iterator(Finish));
3233 }
3234 
3235 iterator_range<export_iterator> MachOObjectFile::exports(Error &Err) const {
3236   ArrayRef<uint8_t> Trie;
3237   if (DyldInfoLoadCmd)
3238     Trie = getDyldInfoExportsTrie();
3239   else if (DyldExportsTrieLoadCmd)
3240     Trie = getDyldExportsTrie();
3241 
3242   return exports(Err, Trie, this);
3243 }
3244 
3245 MachOAbstractFixupEntry::MachOAbstractFixupEntry(Error *E,
3246                                                  const MachOObjectFile *O)
3247     : E(E), O(O) {
3248   // Cache the vmaddress of __TEXT
3249   for (const auto &Command : O->load_commands()) {
3250     if (Command.C.cmd == MachO::LC_SEGMENT) {
3251       MachO::segment_command SLC = O->getSegmentLoadCommand(Command);
3252       if (StringRef(SLC.segname) == StringRef("__TEXT")) {
3253         TextAddress = SLC.vmaddr;
3254         break;
3255       }
3256     } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
3257       MachO::segment_command_64 SLC_64 = O->getSegment64LoadCommand(Command);
3258       if (StringRef(SLC_64.segname) == StringRef("__TEXT")) {
3259         TextAddress = SLC_64.vmaddr;
3260         break;
3261       }
3262     }
3263   }
3264 }
3265 
3266 int32_t MachOAbstractFixupEntry::segmentIndex() const { return SegmentIndex; }
3267 
3268 uint64_t MachOAbstractFixupEntry::segmentOffset() const {
3269   return SegmentOffset;
3270 }
3271 
3272 uint64_t MachOAbstractFixupEntry::segmentAddress() const {
3273   return O->BindRebaseAddress(SegmentIndex, 0);
3274 }
3275 
3276 StringRef MachOAbstractFixupEntry::segmentName() const {
3277   return O->BindRebaseSegmentName(SegmentIndex);
3278 }
3279 
3280 StringRef MachOAbstractFixupEntry::sectionName() const {
3281   return O->BindRebaseSectionName(SegmentIndex, SegmentOffset);
3282 }
3283 
3284 uint64_t MachOAbstractFixupEntry::address() const {
3285   return O->BindRebaseAddress(SegmentIndex, SegmentOffset);
3286 }
3287 
3288 StringRef MachOAbstractFixupEntry::symbolName() const { return SymbolName; }
3289 
3290 int64_t MachOAbstractFixupEntry::addend() const { return Addend; }
3291 
3292 uint32_t MachOAbstractFixupEntry::flags() const { return Flags; }
3293 
3294 int MachOAbstractFixupEntry::ordinal() const { return Ordinal; }
3295 
3296 StringRef MachOAbstractFixupEntry::typeName() const { return "unknown"; }
3297 
3298 void MachOAbstractFixupEntry::moveToFirst() {
3299   SegmentOffset = 0;
3300   SegmentIndex = -1;
3301   Ordinal = 0;
3302   Flags = 0;
3303   Addend = 0;
3304   Done = false;
3305 }
3306 
3307 void MachOAbstractFixupEntry::moveToEnd() { Done = true; }
3308 
3309 void MachOAbstractFixupEntry::moveNext() {}
3310 
3311 MachOChainedFixupEntry::MachOChainedFixupEntry(Error *E,
3312                                                const MachOObjectFile *O,
3313                                                bool Parse)
3314     : MachOAbstractFixupEntry(E, O) {
3315   ErrorAsOutParameter e(E);
3316   if (!Parse)
3317     return;
3318 
3319   if (auto FixupTargetsOrErr = O->getDyldChainedFixupTargets()) {
3320     FixupTargets = *FixupTargetsOrErr;
3321   } else {
3322     *E = FixupTargetsOrErr.takeError();
3323     return;
3324   }
3325 
3326   if (auto SegmentsOrErr = O->getChainedFixupsSegments()) {
3327     Segments = std::move(SegmentsOrErr->second);
3328   } else {
3329     *E = SegmentsOrErr.takeError();
3330     return;
3331   }
3332 }
3333 
3334 void MachOChainedFixupEntry::findNextPageWithFixups() {
3335   auto FindInSegment = [this]() {
3336     const ChainedFixupsSegment &SegInfo = Segments[InfoSegIndex];
3337     while (PageIndex < SegInfo.PageStarts.size() &&
3338            SegInfo.PageStarts[PageIndex] == MachO::DYLD_CHAINED_PTR_START_NONE)
3339       ++PageIndex;
3340     return PageIndex < SegInfo.PageStarts.size();
3341   };
3342 
3343   while (InfoSegIndex < Segments.size()) {
3344     if (FindInSegment()) {
3345       PageOffset = Segments[InfoSegIndex].PageStarts[PageIndex];
3346       SegmentData = O->getSegmentContents(Segments[InfoSegIndex].SegIdx);
3347       return;
3348     }
3349 
3350     InfoSegIndex++;
3351     PageIndex = 0;
3352   }
3353 }
3354 
3355 void MachOChainedFixupEntry::moveToFirst() {
3356   MachOAbstractFixupEntry::moveToFirst();
3357   if (Segments.empty()) {
3358     Done = true;
3359     return;
3360   }
3361 
3362   InfoSegIndex = 0;
3363   PageIndex = 0;
3364 
3365   findNextPageWithFixups();
3366   moveNext();
3367 }
3368 
3369 void MachOChainedFixupEntry::moveToEnd() {
3370   MachOAbstractFixupEntry::moveToEnd();
3371 }
3372 
3373 void MachOChainedFixupEntry::moveNext() {
3374   ErrorAsOutParameter ErrAsOutParam(E);
3375 
3376   if (InfoSegIndex == Segments.size()) {
3377     Done = true;
3378     return;
3379   }
3380 
3381   const ChainedFixupsSegment &SegInfo = Segments[InfoSegIndex];
3382   SegmentIndex = SegInfo.SegIdx;
3383   SegmentOffset = SegInfo.Header.page_size * PageIndex + PageOffset;
3384 
3385   // FIXME: Handle other pointer formats.
3386   uint16_t PointerFormat = SegInfo.Header.pointer_format;
3387   if (PointerFormat != MachO::DYLD_CHAINED_PTR_64 &&
3388       PointerFormat != MachO::DYLD_CHAINED_PTR_64_OFFSET) {
3389     *E = createError("segment " + Twine(SegmentIndex) +
3390                      " has unsupported chained fixup pointer_format " +
3391                      Twine(PointerFormat));
3392     moveToEnd();
3393     return;
3394   }
3395 
3396   Ordinal = 0;
3397   Flags = 0;
3398   Addend = 0;
3399   PointerValue = 0;
3400   SymbolName = {};
3401 
3402   if (SegmentOffset + sizeof(RawValue) > SegmentData.size()) {
3403     *E = malformedError("fixup in segment " + Twine(SegmentIndex) +
3404                         " at offset " + Twine(SegmentOffset) +
3405                         " extends past segment's end");
3406     moveToEnd();
3407     return;
3408   }
3409 
3410   static_assert(sizeof(RawValue) == sizeof(MachO::dyld_chained_import_addend));
3411   memcpy(&RawValue, SegmentData.data() + SegmentOffset, sizeof(RawValue));
3412   if (O->isLittleEndian() != sys::IsLittleEndianHost)
3413     sys::swapByteOrder(RawValue);
3414 
3415   // The bit extraction below assumes little-endian fixup entries.
3416   assert(O->isLittleEndian() && "big-endian object should have been rejected "
3417                                 "by getDyldChainedFixupTargets()");
3418   auto Field = [this](uint8_t Right, uint8_t Count) {
3419     return (RawValue >> Right) & ((1ULL << Count) - 1);
3420   };
3421 
3422   // The `bind` field (most significant bit) of the encoded fixup determines
3423   // whether it is dyld_chained_ptr_64_bind or dyld_chained_ptr_64_rebase.
3424   bool IsBind = Field(63, 1);
3425   Kind = IsBind ? FixupKind::Bind : FixupKind::Rebase;
3426   uint32_t Next = Field(51, 12);
3427   if (IsBind) {
3428     uint32_t ImportOrdinal = Field(0, 24);
3429     uint8_t InlineAddend = Field(24, 8);
3430 
3431     if (ImportOrdinal >= FixupTargets.size()) {
3432       *E = malformedError("fixup in segment " + Twine(SegmentIndex) +
3433                           " at offset " + Twine(SegmentOffset) +
3434                           "  has out-of range import ordinal " +
3435                           Twine(ImportOrdinal));
3436       moveToEnd();
3437       return;
3438     }
3439 
3440     ChainedFixupTarget &Target = FixupTargets[ImportOrdinal];
3441     Ordinal = Target.libOrdinal();
3442     Addend = InlineAddend ? InlineAddend : Target.addend();
3443     Flags = Target.weakImport() ? MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT : 0;
3444     SymbolName = Target.symbolName();
3445   } else {
3446     uint64_t Target = Field(0, 36);
3447     uint64_t High8 = Field(36, 8);
3448 
3449     PointerValue = Target | (High8 << 56);
3450     if (PointerFormat == MachO::DYLD_CHAINED_PTR_64_OFFSET)
3451       PointerValue += textAddress();
3452   }
3453 
3454   // The stride is 4 bytes for DYLD_CHAINED_PTR_64(_OFFSET).
3455   if (Next != 0) {
3456     PageOffset += 4 * Next;
3457   } else {
3458     ++PageIndex;
3459     findNextPageWithFixups();
3460   }
3461 }
3462 
3463 bool MachOChainedFixupEntry::operator==(
3464     const MachOChainedFixupEntry &Other) const {
3465   if (Done && Other.Done)
3466     return true;
3467   if (Done != Other.Done)
3468     return false;
3469   return InfoSegIndex == Other.InfoSegIndex && PageIndex == Other.PageIndex &&
3470          PageOffset == Other.PageOffset;
3471 }
3472 
3473 MachORebaseEntry::MachORebaseEntry(Error *E, const MachOObjectFile *O,
3474                                    ArrayRef<uint8_t> Bytes, bool is64Bit)
3475     : E(E), O(O), Opcodes(Bytes), Ptr(Bytes.begin()),
3476       PointerSize(is64Bit ? 8 : 4) {}
3477 
3478 void MachORebaseEntry::moveToFirst() {
3479   Ptr = Opcodes.begin();
3480   moveNext();
3481 }
3482 
3483 void MachORebaseEntry::moveToEnd() {
3484   Ptr = Opcodes.end();
3485   RemainingLoopCount = 0;
3486   Done = true;
3487 }
3488 
3489 void MachORebaseEntry::moveNext() {
3490   ErrorAsOutParameter ErrAsOutParam(E);
3491   // If in the middle of some loop, move to next rebasing in loop.
3492   SegmentOffset += AdvanceAmount;
3493   if (RemainingLoopCount) {
3494     --RemainingLoopCount;
3495     return;
3496   }
3497   // REBASE_OPCODE_DONE is only used for padding if we are not aligned to
3498   // pointer size. Therefore it is possible to reach the end without ever having
3499   // seen REBASE_OPCODE_DONE.
3500   if (Ptr == Opcodes.end()) {
3501     Done = true;
3502     return;
3503   }
3504   bool More = true;
3505   while (More) {
3506     // Parse next opcode and set up next loop.
3507     const uint8_t *OpcodeStart = Ptr;
3508     uint8_t Byte = *Ptr++;
3509     uint8_t ImmValue = Byte & MachO::REBASE_IMMEDIATE_MASK;
3510     uint8_t Opcode = Byte & MachO::REBASE_OPCODE_MASK;
3511     uint32_t Count, Skip;
3512     const char *error = nullptr;
3513     switch (Opcode) {
3514     case MachO::REBASE_OPCODE_DONE:
3515       More = false;
3516       Done = true;
3517       moveToEnd();
3518       DEBUG_WITH_TYPE("mach-o-rebase", dbgs() << "REBASE_OPCODE_DONE\n");
3519       break;
3520     case MachO::REBASE_OPCODE_SET_TYPE_IMM:
3521       RebaseType = ImmValue;
3522       if (RebaseType > MachO::REBASE_TYPE_TEXT_PCREL32) {
3523         *E = malformedError("for REBASE_OPCODE_SET_TYPE_IMM bad bind type: " +
3524                             Twine((int)RebaseType) + " for opcode at: 0x" +
3525                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3526         moveToEnd();
3527         return;
3528       }
3529       DEBUG_WITH_TYPE(
3530           "mach-o-rebase",
3531           dbgs() << "REBASE_OPCODE_SET_TYPE_IMM: "
3532                  << "RebaseType=" << (int) RebaseType << "\n");
3533       break;
3534     case MachO::REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:
3535       SegmentIndex = ImmValue;
3536       SegmentOffset = readULEB128(&error);
3537       if (error) {
3538         *E = malformedError("for REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB " +
3539                             Twine(error) + " for opcode at: 0x" +
3540                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3541         moveToEnd();
3542         return;
3543       }
3544       error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3545                                                PointerSize);
3546       if (error) {
3547         *E = malformedError("for REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB " +
3548                             Twine(error) + " for opcode at: 0x" +
3549                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3550         moveToEnd();
3551         return;
3552       }
3553       DEBUG_WITH_TYPE(
3554           "mach-o-rebase",
3555           dbgs() << "REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: "
3556                  << "SegmentIndex=" << SegmentIndex << ", "
3557                  << format("SegmentOffset=0x%06X", SegmentOffset)
3558                  << "\n");
3559       break;
3560     case MachO::REBASE_OPCODE_ADD_ADDR_ULEB:
3561       SegmentOffset += readULEB128(&error);
3562       if (error) {
3563         *E = malformedError("for REBASE_OPCODE_ADD_ADDR_ULEB " + Twine(error) +
3564                             " for opcode at: 0x" +
3565                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3566         moveToEnd();
3567         return;
3568       }
3569       error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3570                                                PointerSize);
3571       if (error) {
3572         *E = malformedError("for REBASE_OPCODE_ADD_ADDR_ULEB " + Twine(error) +
3573                             " for opcode at: 0x" +
3574                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3575         moveToEnd();
3576         return;
3577       }
3578       DEBUG_WITH_TYPE("mach-o-rebase",
3579                       dbgs() << "REBASE_OPCODE_ADD_ADDR_ULEB: "
3580                              << format("SegmentOffset=0x%06X",
3581                                        SegmentOffset) << "\n");
3582       break;
3583     case MachO::REBASE_OPCODE_ADD_ADDR_IMM_SCALED:
3584       SegmentOffset += ImmValue * PointerSize;
3585       error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3586                                                PointerSize);
3587       if (error) {
3588         *E = malformedError("for REBASE_OPCODE_ADD_ADDR_IMM_SCALED " +
3589                             Twine(error) + " for opcode at: 0x" +
3590                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3591         moveToEnd();
3592         return;
3593       }
3594       DEBUG_WITH_TYPE("mach-o-rebase",
3595                       dbgs() << "REBASE_OPCODE_ADD_ADDR_IMM_SCALED: "
3596                              << format("SegmentOffset=0x%06X",
3597                                        SegmentOffset) << "\n");
3598       break;
3599     case MachO::REBASE_OPCODE_DO_REBASE_IMM_TIMES:
3600       AdvanceAmount = PointerSize;
3601       Skip = 0;
3602       Count = ImmValue;
3603       if (ImmValue != 0)
3604         RemainingLoopCount = ImmValue - 1;
3605       else
3606         RemainingLoopCount = 0;
3607       error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3608                                                PointerSize, Count, Skip);
3609       if (error) {
3610         *E = malformedError("for REBASE_OPCODE_DO_REBASE_IMM_TIMES " +
3611                             Twine(error) + " for opcode at: 0x" +
3612                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3613         moveToEnd();
3614         return;
3615       }
3616       DEBUG_WITH_TYPE(
3617           "mach-o-rebase",
3618           dbgs() << "REBASE_OPCODE_DO_REBASE_IMM_TIMES: "
3619                  << format("SegmentOffset=0x%06X", SegmentOffset)
3620                  << ", AdvanceAmount=" << AdvanceAmount
3621                  << ", RemainingLoopCount=" << RemainingLoopCount
3622                  << "\n");
3623       return;
3624     case MachO::REBASE_OPCODE_DO_REBASE_ULEB_TIMES:
3625       AdvanceAmount = PointerSize;
3626       Skip = 0;
3627       Count = readULEB128(&error);
3628       if (error) {
3629         *E = malformedError("for REBASE_OPCODE_DO_REBASE_ULEB_TIMES " +
3630                             Twine(error) + " for opcode at: 0x" +
3631                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3632         moveToEnd();
3633         return;
3634       }
3635       if (Count != 0)
3636         RemainingLoopCount = Count - 1;
3637       else
3638         RemainingLoopCount = 0;
3639       error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3640                                                PointerSize, Count, Skip);
3641       if (error) {
3642         *E = malformedError("for REBASE_OPCODE_DO_REBASE_ULEB_TIMES " +
3643                             Twine(error) + " for opcode at: 0x" +
3644                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3645         moveToEnd();
3646         return;
3647       }
3648       DEBUG_WITH_TYPE(
3649           "mach-o-rebase",
3650           dbgs() << "REBASE_OPCODE_DO_REBASE_ULEB_TIMES: "
3651                  << format("SegmentOffset=0x%06X", SegmentOffset)
3652                  << ", AdvanceAmount=" << AdvanceAmount
3653                  << ", RemainingLoopCount=" << RemainingLoopCount
3654                  << "\n");
3655       return;
3656     case MachO::REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB:
3657       Skip = readULEB128(&error);
3658       if (error) {
3659         *E = malformedError("for REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB " +
3660                             Twine(error) + " for opcode at: 0x" +
3661                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3662         moveToEnd();
3663         return;
3664       }
3665       AdvanceAmount = Skip + PointerSize;
3666       Count = 1;
3667       RemainingLoopCount = 0;
3668       error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3669                                                PointerSize, Count, Skip);
3670       if (error) {
3671         *E = malformedError("for REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB " +
3672                             Twine(error) + " for opcode at: 0x" +
3673                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3674         moveToEnd();
3675         return;
3676       }
3677       DEBUG_WITH_TYPE(
3678           "mach-o-rebase",
3679           dbgs() << "REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB: "
3680                  << format("SegmentOffset=0x%06X", SegmentOffset)
3681                  << ", AdvanceAmount=" << AdvanceAmount
3682                  << ", RemainingLoopCount=" << RemainingLoopCount
3683                  << "\n");
3684       return;
3685     case MachO::REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB:
3686       Count = readULEB128(&error);
3687       if (error) {
3688         *E = malformedError("for REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_"
3689                             "ULEB " +
3690                             Twine(error) + " for opcode at: 0x" +
3691                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3692         moveToEnd();
3693         return;
3694       }
3695       if (Count != 0)
3696         RemainingLoopCount = Count - 1;
3697       else
3698         RemainingLoopCount = 0;
3699       Skip = readULEB128(&error);
3700       if (error) {
3701         *E = malformedError("for REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_"
3702                             "ULEB " +
3703                             Twine(error) + " for opcode at: 0x" +
3704                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3705         moveToEnd();
3706         return;
3707       }
3708       AdvanceAmount = Skip + PointerSize;
3709 
3710       error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3711                                                PointerSize, Count, Skip);
3712       if (error) {
3713         *E = malformedError("for REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_"
3714                             "ULEB " +
3715                             Twine(error) + " for opcode at: 0x" +
3716                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3717         moveToEnd();
3718         return;
3719       }
3720       DEBUG_WITH_TYPE(
3721           "mach-o-rebase",
3722           dbgs() << "REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB: "
3723                  << format("SegmentOffset=0x%06X", SegmentOffset)
3724                  << ", AdvanceAmount=" << AdvanceAmount
3725                  << ", RemainingLoopCount=" << RemainingLoopCount
3726                  << "\n");
3727       return;
3728     default:
3729       *E = malformedError("bad rebase info (bad opcode value 0x" +
3730                           Twine::utohexstr(Opcode) + " for opcode at: 0x" +
3731                           Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3732       moveToEnd();
3733       return;
3734     }
3735   }
3736 }
3737 
3738 uint64_t MachORebaseEntry::readULEB128(const char **error) {
3739   unsigned Count;
3740   uint64_t Result = decodeULEB128(Ptr, &Count, Opcodes.end(), error);
3741   Ptr += Count;
3742   if (Ptr > Opcodes.end())
3743     Ptr = Opcodes.end();
3744   return Result;
3745 }
3746 
3747 int32_t MachORebaseEntry::segmentIndex() const { return SegmentIndex; }
3748 
3749 uint64_t MachORebaseEntry::segmentOffset() const { return SegmentOffset; }
3750 
3751 StringRef MachORebaseEntry::typeName() const {
3752   switch (RebaseType) {
3753   case MachO::REBASE_TYPE_POINTER:
3754     return "pointer";
3755   case MachO::REBASE_TYPE_TEXT_ABSOLUTE32:
3756     return "text abs32";
3757   case MachO::REBASE_TYPE_TEXT_PCREL32:
3758     return "text rel32";
3759   }
3760   return "unknown";
3761 }
3762 
3763 // For use with the SegIndex of a checked Mach-O Rebase entry
3764 // to get the segment name.
3765 StringRef MachORebaseEntry::segmentName() const {
3766   return O->BindRebaseSegmentName(SegmentIndex);
3767 }
3768 
3769 // For use with a SegIndex,SegOffset pair from a checked Mach-O Rebase entry
3770 // to get the section name.
3771 StringRef MachORebaseEntry::sectionName() const {
3772   return O->BindRebaseSectionName(SegmentIndex, SegmentOffset);
3773 }
3774 
3775 // For use with a SegIndex,SegOffset pair from a checked Mach-O Rebase entry
3776 // to get the address.
3777 uint64_t MachORebaseEntry::address() const {
3778   return O->BindRebaseAddress(SegmentIndex, SegmentOffset);
3779 }
3780 
3781 bool MachORebaseEntry::operator==(const MachORebaseEntry &Other) const {
3782 #ifdef EXPENSIVE_CHECKS
3783   assert(Opcodes == Other.Opcodes && "compare iterators of different files");
3784 #else
3785   assert(Opcodes.data() == Other.Opcodes.data() && "compare iterators of different files");
3786 #endif
3787   return (Ptr == Other.Ptr) &&
3788          (RemainingLoopCount == Other.RemainingLoopCount) &&
3789          (Done == Other.Done);
3790 }
3791 
3792 iterator_range<rebase_iterator>
3793 MachOObjectFile::rebaseTable(Error &Err, MachOObjectFile *O,
3794                              ArrayRef<uint8_t> Opcodes, bool is64) {
3795   if (O->BindRebaseSectionTable == nullptr)
3796     O->BindRebaseSectionTable = std::make_unique<BindRebaseSegInfo>(O);
3797   MachORebaseEntry Start(&Err, O, Opcodes, is64);
3798   Start.moveToFirst();
3799 
3800   MachORebaseEntry Finish(&Err, O, Opcodes, is64);
3801   Finish.moveToEnd();
3802 
3803   return make_range(rebase_iterator(Start), rebase_iterator(Finish));
3804 }
3805 
3806 iterator_range<rebase_iterator> MachOObjectFile::rebaseTable(Error &Err) {
3807   return rebaseTable(Err, this, getDyldInfoRebaseOpcodes(), is64Bit());
3808 }
3809 
3810 MachOBindEntry::MachOBindEntry(Error *E, const MachOObjectFile *O,
3811                                ArrayRef<uint8_t> Bytes, bool is64Bit, Kind BK)
3812     : E(E), O(O), Opcodes(Bytes), Ptr(Bytes.begin()),
3813       PointerSize(is64Bit ? 8 : 4), TableKind(BK) {}
3814 
3815 void MachOBindEntry::moveToFirst() {
3816   Ptr = Opcodes.begin();
3817   moveNext();
3818 }
3819 
3820 void MachOBindEntry::moveToEnd() {
3821   Ptr = Opcodes.end();
3822   RemainingLoopCount = 0;
3823   Done = true;
3824 }
3825 
3826 void MachOBindEntry::moveNext() {
3827   ErrorAsOutParameter ErrAsOutParam(E);
3828   // If in the middle of some loop, move to next binding in loop.
3829   SegmentOffset += AdvanceAmount;
3830   if (RemainingLoopCount) {
3831     --RemainingLoopCount;
3832     return;
3833   }
3834   // BIND_OPCODE_DONE is only used for padding if we are not aligned to
3835   // pointer size. Therefore it is possible to reach the end without ever having
3836   // seen BIND_OPCODE_DONE.
3837   if (Ptr == Opcodes.end()) {
3838     Done = true;
3839     return;
3840   }
3841   bool More = true;
3842   while (More) {
3843     // Parse next opcode and set up next loop.
3844     const uint8_t *OpcodeStart = Ptr;
3845     uint8_t Byte = *Ptr++;
3846     uint8_t ImmValue = Byte & MachO::BIND_IMMEDIATE_MASK;
3847     uint8_t Opcode = Byte & MachO::BIND_OPCODE_MASK;
3848     int8_t SignExtended;
3849     const uint8_t *SymStart;
3850     uint32_t Count, Skip;
3851     const char *error = nullptr;
3852     switch (Opcode) {
3853     case MachO::BIND_OPCODE_DONE:
3854       if (TableKind == Kind::Lazy) {
3855         // Lazying bindings have a DONE opcode between entries.  Need to ignore
3856         // it to advance to next entry.  But need not if this is last entry.
3857         bool NotLastEntry = false;
3858         for (const uint8_t *P = Ptr; P < Opcodes.end(); ++P) {
3859           if (*P) {
3860             NotLastEntry = true;
3861           }
3862         }
3863         if (NotLastEntry)
3864           break;
3865       }
3866       More = false;
3867       moveToEnd();
3868       DEBUG_WITH_TYPE("mach-o-bind", dbgs() << "BIND_OPCODE_DONE\n");
3869       break;
3870     case MachO::BIND_OPCODE_SET_DYLIB_ORDINAL_IMM:
3871       if (TableKind == Kind::Weak) {
3872         *E = malformedError("BIND_OPCODE_SET_DYLIB_ORDINAL_IMM not allowed in "
3873                             "weak bind table for opcode at: 0x" +
3874                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3875         moveToEnd();
3876         return;
3877       }
3878       Ordinal = ImmValue;
3879       LibraryOrdinalSet = true;
3880       if (ImmValue > O->getLibraryCount()) {
3881         *E = malformedError("for BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB bad "
3882                             "library ordinal: " +
3883                             Twine((int)ImmValue) + " (max " +
3884                             Twine((int)O->getLibraryCount()) +
3885                             ") for opcode at: 0x" +
3886                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3887         moveToEnd();
3888         return;
3889       }
3890       DEBUG_WITH_TYPE(
3891           "mach-o-bind",
3892           dbgs() << "BIND_OPCODE_SET_DYLIB_ORDINAL_IMM: "
3893                  << "Ordinal=" << Ordinal << "\n");
3894       break;
3895     case MachO::BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB:
3896       if (TableKind == Kind::Weak) {
3897         *E = malformedError("BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB not allowed in "
3898                             "weak bind table for opcode at: 0x" +
3899                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3900         moveToEnd();
3901         return;
3902       }
3903       Ordinal = readULEB128(&error);
3904       LibraryOrdinalSet = true;
3905       if (error) {
3906         *E = malformedError("for BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB " +
3907                             Twine(error) + " for opcode at: 0x" +
3908                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3909         moveToEnd();
3910         return;
3911       }
3912       if (Ordinal > (int)O->getLibraryCount()) {
3913         *E = malformedError("for BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB bad "
3914                             "library ordinal: " +
3915                             Twine((int)Ordinal) + " (max " +
3916                             Twine((int)O->getLibraryCount()) +
3917                             ") for opcode at: 0x" +
3918                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3919         moveToEnd();
3920         return;
3921       }
3922       DEBUG_WITH_TYPE(
3923           "mach-o-bind",
3924           dbgs() << "BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB: "
3925                  << "Ordinal=" << Ordinal << "\n");
3926       break;
3927     case MachO::BIND_OPCODE_SET_DYLIB_SPECIAL_IMM:
3928       if (TableKind == Kind::Weak) {
3929         *E = malformedError("BIND_OPCODE_SET_DYLIB_SPECIAL_IMM not allowed in "
3930                             "weak bind table for opcode at: 0x" +
3931                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3932         moveToEnd();
3933         return;
3934       }
3935       if (ImmValue) {
3936         SignExtended = MachO::BIND_OPCODE_MASK | ImmValue;
3937         Ordinal = SignExtended;
3938         if (Ordinal < MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP) {
3939           *E = malformedError("for BIND_OPCODE_SET_DYLIB_SPECIAL_IMM unknown "
3940                               "special ordinal: " +
3941                               Twine((int)Ordinal) + " for opcode at: 0x" +
3942                               Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3943           moveToEnd();
3944           return;
3945         }
3946       } else
3947         Ordinal = 0;
3948       LibraryOrdinalSet = true;
3949       DEBUG_WITH_TYPE(
3950           "mach-o-bind",
3951           dbgs() << "BIND_OPCODE_SET_DYLIB_SPECIAL_IMM: "
3952                  << "Ordinal=" << Ordinal << "\n");
3953       break;
3954     case MachO::BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM:
3955       Flags = ImmValue;
3956       SymStart = Ptr;
3957       while (*Ptr && (Ptr < Opcodes.end())) {
3958         ++Ptr;
3959       }
3960       if (Ptr == Opcodes.end()) {
3961         *E = malformedError(
3962             "for BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM "
3963             "symbol name extends past opcodes for opcode at: 0x" +
3964             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3965         moveToEnd();
3966         return;
3967       }
3968       SymbolName = StringRef(reinterpret_cast<const char*>(SymStart),
3969                              Ptr-SymStart);
3970       ++Ptr;
3971       DEBUG_WITH_TYPE(
3972           "mach-o-bind",
3973           dbgs() << "BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM: "
3974                  << "SymbolName=" << SymbolName << "\n");
3975       if (TableKind == Kind::Weak) {
3976         if (ImmValue & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION)
3977           return;
3978       }
3979       break;
3980     case MachO::BIND_OPCODE_SET_TYPE_IMM:
3981       BindType = ImmValue;
3982       if (ImmValue > MachO::BIND_TYPE_TEXT_PCREL32) {
3983         *E = malformedError("for BIND_OPCODE_SET_TYPE_IMM bad bind type: " +
3984                             Twine((int)ImmValue) + " for opcode at: 0x" +
3985                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3986         moveToEnd();
3987         return;
3988       }
3989       DEBUG_WITH_TYPE(
3990           "mach-o-bind",
3991           dbgs() << "BIND_OPCODE_SET_TYPE_IMM: "
3992                  << "BindType=" << (int)BindType << "\n");
3993       break;
3994     case MachO::BIND_OPCODE_SET_ADDEND_SLEB:
3995       Addend = readSLEB128(&error);
3996       if (error) {
3997         *E = malformedError("for BIND_OPCODE_SET_ADDEND_SLEB " + Twine(error) +
3998                             " for opcode at: 0x" +
3999                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4000         moveToEnd();
4001         return;
4002       }
4003       DEBUG_WITH_TYPE(
4004           "mach-o-bind",
4005           dbgs() << "BIND_OPCODE_SET_ADDEND_SLEB: "
4006                  << "Addend=" << Addend << "\n");
4007       break;
4008     case MachO::BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:
4009       SegmentIndex = ImmValue;
4010       SegmentOffset = readULEB128(&error);
4011       if (error) {
4012         *E = malformedError("for BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB " +
4013                             Twine(error) + " for opcode at: 0x" +
4014                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4015         moveToEnd();
4016         return;
4017       }
4018       error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
4019                                              PointerSize);
4020       if (error) {
4021         *E = malformedError("for BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB " +
4022                             Twine(error) + " for opcode at: 0x" +
4023                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4024         moveToEnd();
4025         return;
4026       }
4027       DEBUG_WITH_TYPE(
4028           "mach-o-bind",
4029           dbgs() << "BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: "
4030                  << "SegmentIndex=" << SegmentIndex << ", "
4031                  << format("SegmentOffset=0x%06X", SegmentOffset)
4032                  << "\n");
4033       break;
4034     case MachO::BIND_OPCODE_ADD_ADDR_ULEB:
4035       SegmentOffset += readULEB128(&error);
4036       if (error) {
4037         *E = malformedError("for BIND_OPCODE_ADD_ADDR_ULEB " + Twine(error) +
4038                             " for opcode at: 0x" +
4039                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4040         moveToEnd();
4041         return;
4042       }
4043       error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
4044                                              PointerSize);
4045       if (error) {
4046         *E = malformedError("for BIND_OPCODE_ADD_ADDR_ULEB " + Twine(error) +
4047                             " for opcode at: 0x" +
4048                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4049         moveToEnd();
4050         return;
4051       }
4052       DEBUG_WITH_TYPE("mach-o-bind",
4053                       dbgs() << "BIND_OPCODE_ADD_ADDR_ULEB: "
4054                              << format("SegmentOffset=0x%06X",
4055                                        SegmentOffset) << "\n");
4056       break;
4057     case MachO::BIND_OPCODE_DO_BIND:
4058       AdvanceAmount = PointerSize;
4059       RemainingLoopCount = 0;
4060       error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
4061                                              PointerSize);
4062       if (error) {
4063         *E = malformedError("for BIND_OPCODE_DO_BIND " + Twine(error) +
4064                             " for opcode at: 0x" +
4065                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4066         moveToEnd();
4067         return;
4068       }
4069       if (SymbolName == StringRef()) {
4070         *E = malformedError(
4071             "for BIND_OPCODE_DO_BIND missing preceding "
4072             "BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM for opcode at: 0x" +
4073             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4074         moveToEnd();
4075         return;
4076       }
4077       if (!LibraryOrdinalSet && TableKind != Kind::Weak) {
4078         *E =
4079             malformedError("for BIND_OPCODE_DO_BIND missing preceding "
4080                            "BIND_OPCODE_SET_DYLIB_ORDINAL_* for opcode at: 0x" +
4081                            Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4082         moveToEnd();
4083         return;
4084       }
4085       DEBUG_WITH_TYPE("mach-o-bind",
4086                       dbgs() << "BIND_OPCODE_DO_BIND: "
4087                              << format("SegmentOffset=0x%06X",
4088                                        SegmentOffset) << "\n");
4089       return;
4090      case MachO::BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB:
4091       if (TableKind == Kind::Lazy) {
4092         *E = malformedError("BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB not allowed in "
4093                             "lazy bind table for opcode at: 0x" +
4094                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4095         moveToEnd();
4096         return;
4097       }
4098       error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
4099                                              PointerSize);
4100       if (error) {
4101         *E = malformedError("for BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB " +
4102                             Twine(error) + " for opcode at: 0x" +
4103                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4104         moveToEnd();
4105         return;
4106       }
4107       if (SymbolName == StringRef()) {
4108         *E = malformedError(
4109             "for BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB missing "
4110             "preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM for opcode "
4111             "at: 0x" +
4112             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4113         moveToEnd();
4114         return;
4115       }
4116       if (!LibraryOrdinalSet && TableKind != Kind::Weak) {
4117         *E = malformedError(
4118             "for BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB missing "
4119             "preceding BIND_OPCODE_SET_DYLIB_ORDINAL_* for opcode at: 0x" +
4120             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4121         moveToEnd();
4122         return;
4123       }
4124       AdvanceAmount = readULEB128(&error) + PointerSize;
4125       if (error) {
4126         *E = malformedError("for BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB " +
4127                             Twine(error) + " for opcode at: 0x" +
4128                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4129         moveToEnd();
4130         return;
4131       }
4132       // Note, this is not really an error until the next bind but make no sense
4133       // for a BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB to not be followed by another
4134       // bind operation.
4135       error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset +
4136                                             AdvanceAmount, PointerSize);
4137       if (error) {
4138         *E = malformedError("for BIND_OPCODE_ADD_ADDR_ULEB (after adding "
4139                             "ULEB) " +
4140                             Twine(error) + " for opcode at: 0x" +
4141                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4142         moveToEnd();
4143         return;
4144       }
4145       RemainingLoopCount = 0;
4146       DEBUG_WITH_TYPE(
4147           "mach-o-bind",
4148           dbgs() << "BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB: "
4149                  << format("SegmentOffset=0x%06X", SegmentOffset)
4150                  << ", AdvanceAmount=" << AdvanceAmount
4151                  << ", RemainingLoopCount=" << RemainingLoopCount
4152                  << "\n");
4153       return;
4154     case MachO::BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED:
4155       if (TableKind == Kind::Lazy) {
4156         *E = malformedError("BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED not "
4157                             "allowed in lazy bind table for opcode at: 0x" +
4158                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4159         moveToEnd();
4160         return;
4161       }
4162       if (SymbolName == StringRef()) {
4163         *E = malformedError(
4164             "for BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED "
4165             "missing preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM for "
4166             "opcode at: 0x" +
4167             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4168         moveToEnd();
4169         return;
4170       }
4171       if (!LibraryOrdinalSet && TableKind != Kind::Weak) {
4172         *E = malformedError(
4173             "for BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED "
4174             "missing preceding BIND_OPCODE_SET_DYLIB_ORDINAL_* for opcode "
4175             "at: 0x" +
4176             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4177         moveToEnd();
4178         return;
4179       }
4180       AdvanceAmount = ImmValue * PointerSize + PointerSize;
4181       RemainingLoopCount = 0;
4182       error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset +
4183                                              AdvanceAmount, PointerSize);
4184       if (error) {
4185         *E = malformedError("for BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED " +
4186                             Twine(error) + " for opcode at: 0x" +
4187                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4188         moveToEnd();
4189         return;
4190       }
4191       DEBUG_WITH_TYPE("mach-o-bind",
4192                       dbgs()
4193                       << "BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED: "
4194                       << format("SegmentOffset=0x%06X", SegmentOffset) << "\n");
4195       return;
4196     case MachO::BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB:
4197       if (TableKind == Kind::Lazy) {
4198         *E = malformedError("BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB not "
4199                             "allowed in lazy bind table for opcode at: 0x" +
4200                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4201         moveToEnd();
4202         return;
4203       }
4204       Count = readULEB128(&error);
4205       if (Count != 0)
4206         RemainingLoopCount = Count - 1;
4207       else
4208         RemainingLoopCount = 0;
4209       if (error) {
4210         *E = malformedError("for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB "
4211                             " (count value) " +
4212                             Twine(error) + " for opcode at: 0x" +
4213                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4214         moveToEnd();
4215         return;
4216       }
4217       Skip = readULEB128(&error);
4218       AdvanceAmount = Skip + PointerSize;
4219       if (error) {
4220         *E = malformedError("for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB "
4221                             " (skip value) " +
4222                             Twine(error) + " for opcode at: 0x" +
4223                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4224         moveToEnd();
4225         return;
4226       }
4227       if (SymbolName == StringRef()) {
4228         *E = malformedError(
4229             "for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB "
4230             "missing preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM for "
4231             "opcode at: 0x" +
4232             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4233         moveToEnd();
4234         return;
4235       }
4236       if (!LibraryOrdinalSet && TableKind != Kind::Weak) {
4237         *E = malformedError(
4238             "for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB "
4239             "missing preceding BIND_OPCODE_SET_DYLIB_ORDINAL_* for opcode "
4240             "at: 0x" +
4241             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4242         moveToEnd();
4243         return;
4244       }
4245       error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
4246                                              PointerSize, Count, Skip);
4247       if (error) {
4248         *E =
4249             malformedError("for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB " +
4250                            Twine(error) + " for opcode at: 0x" +
4251                            Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4252         moveToEnd();
4253         return;
4254       }
4255       DEBUG_WITH_TYPE(
4256           "mach-o-bind",
4257           dbgs() << "BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB: "
4258                  << format("SegmentOffset=0x%06X", SegmentOffset)
4259                  << ", AdvanceAmount=" << AdvanceAmount
4260                  << ", RemainingLoopCount=" << RemainingLoopCount
4261                  << "\n");
4262       return;
4263     default:
4264       *E = malformedError("bad bind info (bad opcode value 0x" +
4265                           Twine::utohexstr(Opcode) + " for opcode at: 0x" +
4266                           Twine::utohexstr(OpcodeStart - Opcodes.begin()));
4267       moveToEnd();
4268       return;
4269     }
4270   }
4271 }
4272 
4273 uint64_t MachOBindEntry::readULEB128(const char **error) {
4274   unsigned Count;
4275   uint64_t Result = decodeULEB128(Ptr, &Count, Opcodes.end(), error);
4276   Ptr += Count;
4277   if (Ptr > Opcodes.end())
4278     Ptr = Opcodes.end();
4279   return Result;
4280 }
4281 
4282 int64_t MachOBindEntry::readSLEB128(const char **error) {
4283   unsigned Count;
4284   int64_t Result = decodeSLEB128(Ptr, &Count, Opcodes.end(), error);
4285   Ptr += Count;
4286   if (Ptr > Opcodes.end())
4287     Ptr = Opcodes.end();
4288   return Result;
4289 }
4290 
4291 int32_t MachOBindEntry::segmentIndex() const { return SegmentIndex; }
4292 
4293 uint64_t MachOBindEntry::segmentOffset() const { return SegmentOffset; }
4294 
4295 StringRef MachOBindEntry::typeName() const {
4296   switch (BindType) {
4297   case MachO::BIND_TYPE_POINTER:
4298     return "pointer";
4299   case MachO::BIND_TYPE_TEXT_ABSOLUTE32:
4300     return "text abs32";
4301   case MachO::BIND_TYPE_TEXT_PCREL32:
4302     return "text rel32";
4303   }
4304   return "unknown";
4305 }
4306 
4307 StringRef MachOBindEntry::symbolName() const { return SymbolName; }
4308 
4309 int64_t MachOBindEntry::addend() const { return Addend; }
4310 
4311 uint32_t MachOBindEntry::flags() const { return Flags; }
4312 
4313 int MachOBindEntry::ordinal() const { return Ordinal; }
4314 
4315 // For use with the SegIndex of a checked Mach-O Bind entry
4316 // to get the segment name.
4317 StringRef MachOBindEntry::segmentName() const {
4318   return O->BindRebaseSegmentName(SegmentIndex);
4319 }
4320 
4321 // For use with a SegIndex,SegOffset pair from a checked Mach-O Bind entry
4322 // to get the section name.
4323 StringRef MachOBindEntry::sectionName() const {
4324   return O->BindRebaseSectionName(SegmentIndex, SegmentOffset);
4325 }
4326 
4327 // For use with a SegIndex,SegOffset pair from a checked Mach-O Bind entry
4328 // to get the address.
4329 uint64_t MachOBindEntry::address() const {
4330   return O->BindRebaseAddress(SegmentIndex, SegmentOffset);
4331 }
4332 
4333 bool MachOBindEntry::operator==(const MachOBindEntry &Other) const {
4334 #ifdef EXPENSIVE_CHECKS
4335   assert(Opcodes == Other.Opcodes && "compare iterators of different files");
4336 #else
4337   assert(Opcodes.data() == Other.Opcodes.data() && "compare iterators of different files");
4338 #endif
4339   return (Ptr == Other.Ptr) &&
4340          (RemainingLoopCount == Other.RemainingLoopCount) &&
4341          (Done == Other.Done);
4342 }
4343 
4344 // Build table of sections so SegIndex/SegOffset pairs can be translated.
4345 BindRebaseSegInfo::BindRebaseSegInfo(const object::MachOObjectFile *Obj) {
4346   uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
4347   StringRef CurSegName;
4348   uint64_t CurSegAddress;
4349   for (const SectionRef &Section : Obj->sections()) {
4350     SectionInfo Info;
4351     Expected<StringRef> NameOrErr = Section.getName();
4352     if (!NameOrErr)
4353       consumeError(NameOrErr.takeError());
4354     else
4355       Info.SectionName = *NameOrErr;
4356     Info.Address = Section.getAddress();
4357     Info.Size = Section.getSize();
4358     Info.SegmentName =
4359         Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
4360     if (!Info.SegmentName.equals(CurSegName)) {
4361       ++CurSegIndex;
4362       CurSegName = Info.SegmentName;
4363       CurSegAddress = Info.Address;
4364     }
4365     Info.SegmentIndex = CurSegIndex - 1;
4366     Info.OffsetInSegment = Info.Address - CurSegAddress;
4367     Info.SegmentStartAddress = CurSegAddress;
4368     Sections.push_back(Info);
4369   }
4370   MaxSegIndex = CurSegIndex;
4371 }
4372 
4373 // For use with a SegIndex, SegOffset, and PointerSize triple in
4374 // MachOBindEntry::moveNext() to validate a MachOBindEntry or MachORebaseEntry.
4375 //
4376 // Given a SegIndex, SegOffset, and PointerSize, verify a valid section exists
4377 // that fully contains a pointer at that location. Multiple fixups in a bind
4378 // (such as with the BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB opcode) can
4379 // be tested via the Count and Skip parameters.
4380 const char * BindRebaseSegInfo::checkSegAndOffsets(int32_t SegIndex,
4381                                                    uint64_t SegOffset,
4382                                                    uint8_t PointerSize,
4383                                                    uint32_t Count,
4384                                                    uint32_t Skip) {
4385   if (SegIndex == -1)
4386     return "missing preceding *_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB";
4387   if (SegIndex >= MaxSegIndex)
4388     return "bad segIndex (too large)";
4389   for (uint32_t i = 0; i < Count; ++i) {
4390     uint32_t Start = SegOffset + i * (PointerSize + Skip);
4391     uint32_t End = Start + PointerSize;
4392     bool Found = false;
4393     for (const SectionInfo &SI : Sections) {
4394       if (SI.SegmentIndex != SegIndex)
4395         continue;
4396       if ((SI.OffsetInSegment<=Start) && (Start<(SI.OffsetInSegment+SI.Size))) {
4397         if (End <= SI.OffsetInSegment + SI.Size) {
4398           Found = true;
4399           break;
4400         }
4401         else
4402           return "bad offset, extends beyond section boundary";
4403       }
4404     }
4405     if (!Found)
4406       return "bad offset, not in section";
4407   }
4408   return nullptr;
4409 }
4410 
4411 // For use with the SegIndex of a checked Mach-O Bind or Rebase entry
4412 // to get the segment name.
4413 StringRef BindRebaseSegInfo::segmentName(int32_t SegIndex) {
4414   for (const SectionInfo &SI : Sections) {
4415     if (SI.SegmentIndex == SegIndex)
4416       return SI.SegmentName;
4417   }
4418   llvm_unreachable("invalid SegIndex");
4419 }
4420 
4421 // For use with a SegIndex,SegOffset pair from a checked Mach-O Bind or Rebase
4422 // to get the SectionInfo.
4423 const BindRebaseSegInfo::SectionInfo &BindRebaseSegInfo::findSection(
4424                                      int32_t SegIndex, uint64_t SegOffset) {
4425   for (const SectionInfo &SI : Sections) {
4426     if (SI.SegmentIndex != SegIndex)
4427       continue;
4428     if (SI.OffsetInSegment > SegOffset)
4429       continue;
4430     if (SegOffset >= (SI.OffsetInSegment + SI.Size))
4431       continue;
4432     return SI;
4433   }
4434   llvm_unreachable("SegIndex and SegOffset not in any section");
4435 }
4436 
4437 // For use with a SegIndex,SegOffset pair from a checked Mach-O Bind or Rebase
4438 // entry to get the section name.
4439 StringRef BindRebaseSegInfo::sectionName(int32_t SegIndex,
4440                                          uint64_t SegOffset) {
4441   return findSection(SegIndex, SegOffset).SectionName;
4442 }
4443 
4444 // For use with a SegIndex,SegOffset pair from a checked Mach-O Bind or Rebase
4445 // entry to get the address.
4446 uint64_t BindRebaseSegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
4447   const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
4448   return SI.SegmentStartAddress + OffsetInSeg;
4449 }
4450 
4451 iterator_range<bind_iterator>
4452 MachOObjectFile::bindTable(Error &Err, MachOObjectFile *O,
4453                            ArrayRef<uint8_t> Opcodes, bool is64,
4454                            MachOBindEntry::Kind BKind) {
4455   if (O->BindRebaseSectionTable == nullptr)
4456     O->BindRebaseSectionTable = std::make_unique<BindRebaseSegInfo>(O);
4457   MachOBindEntry Start(&Err, O, Opcodes, is64, BKind);
4458   Start.moveToFirst();
4459 
4460   MachOBindEntry Finish(&Err, O, Opcodes, is64, BKind);
4461   Finish.moveToEnd();
4462 
4463   return make_range(bind_iterator(Start), bind_iterator(Finish));
4464 }
4465 
4466 iterator_range<bind_iterator> MachOObjectFile::bindTable(Error &Err) {
4467   return bindTable(Err, this, getDyldInfoBindOpcodes(), is64Bit(),
4468                    MachOBindEntry::Kind::Regular);
4469 }
4470 
4471 iterator_range<bind_iterator> MachOObjectFile::lazyBindTable(Error &Err) {
4472   return bindTable(Err, this, getDyldInfoLazyBindOpcodes(), is64Bit(),
4473                    MachOBindEntry::Kind::Lazy);
4474 }
4475 
4476 iterator_range<bind_iterator> MachOObjectFile::weakBindTable(Error &Err) {
4477   return bindTable(Err, this, getDyldInfoWeakBindOpcodes(), is64Bit(),
4478                    MachOBindEntry::Kind::Weak);
4479 }
4480 
4481 iterator_range<fixup_iterator> MachOObjectFile::fixupTable(Error &Err) {
4482   if (BindRebaseSectionTable == nullptr)
4483     BindRebaseSectionTable = std::make_unique<BindRebaseSegInfo>(this);
4484 
4485   MachOChainedFixupEntry Start(&Err, this, true);
4486   Start.moveToFirst();
4487 
4488   MachOChainedFixupEntry Finish(&Err, this, false);
4489   Finish.moveToEnd();
4490 
4491   return make_range(fixup_iterator(Start), fixup_iterator(Finish));
4492 }
4493 
4494 MachOObjectFile::load_command_iterator
4495 MachOObjectFile::begin_load_commands() const {
4496   return LoadCommands.begin();
4497 }
4498 
4499 MachOObjectFile::load_command_iterator
4500 MachOObjectFile::end_load_commands() const {
4501   return LoadCommands.end();
4502 }
4503 
4504 iterator_range<MachOObjectFile::load_command_iterator>
4505 MachOObjectFile::load_commands() const {
4506   return make_range(begin_load_commands(), end_load_commands());
4507 }
4508 
4509 StringRef
4510 MachOObjectFile::getSectionFinalSegmentName(DataRefImpl Sec) const {
4511   ArrayRef<char> Raw = getSectionRawFinalSegmentName(Sec);
4512   return parseSegmentOrSectionName(Raw.data());
4513 }
4514 
4515 ArrayRef<char>
4516 MachOObjectFile::getSectionRawName(DataRefImpl Sec) const {
4517   assert(Sec.d.a < Sections.size() && "Should have detected this earlier");
4518   const section_base *Base =
4519     reinterpret_cast<const section_base *>(Sections[Sec.d.a]);
4520   return ArrayRef(Base->sectname);
4521 }
4522 
4523 ArrayRef<char>
4524 MachOObjectFile::getSectionRawFinalSegmentName(DataRefImpl Sec) const {
4525   assert(Sec.d.a < Sections.size() && "Should have detected this earlier");
4526   const section_base *Base =
4527     reinterpret_cast<const section_base *>(Sections[Sec.d.a]);
4528   return ArrayRef(Base->segname);
4529 }
4530 
4531 bool
4532 MachOObjectFile::isRelocationScattered(const MachO::any_relocation_info &RE)
4533   const {
4534   if (getCPUType(*this) == MachO::CPU_TYPE_X86_64)
4535     return false;
4536   return getPlainRelocationAddress(RE) & MachO::R_SCATTERED;
4537 }
4538 
4539 unsigned MachOObjectFile::getPlainRelocationSymbolNum(
4540     const MachO::any_relocation_info &RE) const {
4541   if (isLittleEndian())
4542     return RE.r_word1 & 0xffffff;
4543   return RE.r_word1 >> 8;
4544 }
4545 
4546 bool MachOObjectFile::getPlainRelocationExternal(
4547     const MachO::any_relocation_info &RE) const {
4548   if (isLittleEndian())
4549     return (RE.r_word1 >> 27) & 1;
4550   return (RE.r_word1 >> 4) & 1;
4551 }
4552 
4553 bool MachOObjectFile::getScatteredRelocationScattered(
4554     const MachO::any_relocation_info &RE) const {
4555   return RE.r_word0 >> 31;
4556 }
4557 
4558 uint32_t MachOObjectFile::getScatteredRelocationValue(
4559     const MachO::any_relocation_info &RE) const {
4560   return RE.r_word1;
4561 }
4562 
4563 uint32_t MachOObjectFile::getScatteredRelocationType(
4564     const MachO::any_relocation_info &RE) const {
4565   return (RE.r_word0 >> 24) & 0xf;
4566 }
4567 
4568 unsigned MachOObjectFile::getAnyRelocationAddress(
4569     const MachO::any_relocation_info &RE) const {
4570   if (isRelocationScattered(RE))
4571     return getScatteredRelocationAddress(RE);
4572   return getPlainRelocationAddress(RE);
4573 }
4574 
4575 unsigned MachOObjectFile::getAnyRelocationPCRel(
4576     const MachO::any_relocation_info &RE) const {
4577   if (isRelocationScattered(RE))
4578     return getScatteredRelocationPCRel(RE);
4579   return getPlainRelocationPCRel(*this, RE);
4580 }
4581 
4582 unsigned MachOObjectFile::getAnyRelocationLength(
4583     const MachO::any_relocation_info &RE) const {
4584   if (isRelocationScattered(RE))
4585     return getScatteredRelocationLength(RE);
4586   return getPlainRelocationLength(*this, RE);
4587 }
4588 
4589 unsigned
4590 MachOObjectFile::getAnyRelocationType(
4591                                    const MachO::any_relocation_info &RE) const {
4592   if (isRelocationScattered(RE))
4593     return getScatteredRelocationType(RE);
4594   return getPlainRelocationType(*this, RE);
4595 }
4596 
4597 SectionRef
4598 MachOObjectFile::getAnyRelocationSection(
4599                                    const MachO::any_relocation_info &RE) const {
4600   if (isRelocationScattered(RE) || getPlainRelocationExternal(RE))
4601     return *section_end();
4602   unsigned SecNum = getPlainRelocationSymbolNum(RE);
4603   if (SecNum == MachO::R_ABS || SecNum > Sections.size())
4604     return *section_end();
4605   DataRefImpl DRI;
4606   DRI.d.a = SecNum - 1;
4607   return SectionRef(DRI, this);
4608 }
4609 
4610 MachO::section MachOObjectFile::getSection(DataRefImpl DRI) const {
4611   assert(DRI.d.a < Sections.size() && "Should have detected this earlier");
4612   return getStruct<MachO::section>(*this, Sections[DRI.d.a]);
4613 }
4614 
4615 MachO::section_64 MachOObjectFile::getSection64(DataRefImpl DRI) const {
4616   assert(DRI.d.a < Sections.size() && "Should have detected this earlier");
4617   return getStruct<MachO::section_64>(*this, Sections[DRI.d.a]);
4618 }
4619 
4620 MachO::section MachOObjectFile::getSection(const LoadCommandInfo &L,
4621                                            unsigned Index) const {
4622   const char *Sec = getSectionPtr(*this, L, Index);
4623   return getStruct<MachO::section>(*this, Sec);
4624 }
4625 
4626 MachO::section_64 MachOObjectFile::getSection64(const LoadCommandInfo &L,
4627                                                 unsigned Index) const {
4628   const char *Sec = getSectionPtr(*this, L, Index);
4629   return getStruct<MachO::section_64>(*this, Sec);
4630 }
4631 
4632 MachO::nlist
4633 MachOObjectFile::getSymbolTableEntry(DataRefImpl DRI) const {
4634   const char *P = reinterpret_cast<const char *>(DRI.p);
4635   return getStruct<MachO::nlist>(*this, P);
4636 }
4637 
4638 MachO::nlist_64
4639 MachOObjectFile::getSymbol64TableEntry(DataRefImpl DRI) const {
4640   const char *P = reinterpret_cast<const char *>(DRI.p);
4641   return getStruct<MachO::nlist_64>(*this, P);
4642 }
4643 
4644 MachO::linkedit_data_command
4645 MachOObjectFile::getLinkeditDataLoadCommand(const LoadCommandInfo &L) const {
4646   return getStruct<MachO::linkedit_data_command>(*this, L.Ptr);
4647 }
4648 
4649 MachO::segment_command
4650 MachOObjectFile::getSegmentLoadCommand(const LoadCommandInfo &L) const {
4651   return getStruct<MachO::segment_command>(*this, L.Ptr);
4652 }
4653 
4654 MachO::segment_command_64
4655 MachOObjectFile::getSegment64LoadCommand(const LoadCommandInfo &L) const {
4656   return getStruct<MachO::segment_command_64>(*this, L.Ptr);
4657 }
4658 
4659 MachO::linker_option_command
4660 MachOObjectFile::getLinkerOptionLoadCommand(const LoadCommandInfo &L) const {
4661   return getStruct<MachO::linker_option_command>(*this, L.Ptr);
4662 }
4663 
4664 MachO::version_min_command
4665 MachOObjectFile::getVersionMinLoadCommand(const LoadCommandInfo &L) const {
4666   return getStruct<MachO::version_min_command>(*this, L.Ptr);
4667 }
4668 
4669 MachO::note_command
4670 MachOObjectFile::getNoteLoadCommand(const LoadCommandInfo &L) const {
4671   return getStruct<MachO::note_command>(*this, L.Ptr);
4672 }
4673 
4674 MachO::build_version_command
4675 MachOObjectFile::getBuildVersionLoadCommand(const LoadCommandInfo &L) const {
4676   return getStruct<MachO::build_version_command>(*this, L.Ptr);
4677 }
4678 
4679 MachO::build_tool_version
4680 MachOObjectFile::getBuildToolVersion(unsigned index) const {
4681   return getStruct<MachO::build_tool_version>(*this, BuildTools[index]);
4682 }
4683 
4684 MachO::dylib_command
4685 MachOObjectFile::getDylibIDLoadCommand(const LoadCommandInfo &L) const {
4686   return getStruct<MachO::dylib_command>(*this, L.Ptr);
4687 }
4688 
4689 MachO::dyld_info_command
4690 MachOObjectFile::getDyldInfoLoadCommand(const LoadCommandInfo &L) const {
4691   return getStruct<MachO::dyld_info_command>(*this, L.Ptr);
4692 }
4693 
4694 MachO::dylinker_command
4695 MachOObjectFile::getDylinkerCommand(const LoadCommandInfo &L) const {
4696   return getStruct<MachO::dylinker_command>(*this, L.Ptr);
4697 }
4698 
4699 MachO::uuid_command
4700 MachOObjectFile::getUuidCommand(const LoadCommandInfo &L) const {
4701   return getStruct<MachO::uuid_command>(*this, L.Ptr);
4702 }
4703 
4704 MachO::rpath_command
4705 MachOObjectFile::getRpathCommand(const LoadCommandInfo &L) const {
4706   return getStruct<MachO::rpath_command>(*this, L.Ptr);
4707 }
4708 
4709 MachO::source_version_command
4710 MachOObjectFile::getSourceVersionCommand(const LoadCommandInfo &L) const {
4711   return getStruct<MachO::source_version_command>(*this, L.Ptr);
4712 }
4713 
4714 MachO::entry_point_command
4715 MachOObjectFile::getEntryPointCommand(const LoadCommandInfo &L) const {
4716   return getStruct<MachO::entry_point_command>(*this, L.Ptr);
4717 }
4718 
4719 MachO::encryption_info_command
4720 MachOObjectFile::getEncryptionInfoCommand(const LoadCommandInfo &L) const {
4721   return getStruct<MachO::encryption_info_command>(*this, L.Ptr);
4722 }
4723 
4724 MachO::encryption_info_command_64
4725 MachOObjectFile::getEncryptionInfoCommand64(const LoadCommandInfo &L) const {
4726   return getStruct<MachO::encryption_info_command_64>(*this, L.Ptr);
4727 }
4728 
4729 MachO::sub_framework_command
4730 MachOObjectFile::getSubFrameworkCommand(const LoadCommandInfo &L) const {
4731   return getStruct<MachO::sub_framework_command>(*this, L.Ptr);
4732 }
4733 
4734 MachO::sub_umbrella_command
4735 MachOObjectFile::getSubUmbrellaCommand(const LoadCommandInfo &L) const {
4736   return getStruct<MachO::sub_umbrella_command>(*this, L.Ptr);
4737 }
4738 
4739 MachO::sub_library_command
4740 MachOObjectFile::getSubLibraryCommand(const LoadCommandInfo &L) const {
4741   return getStruct<MachO::sub_library_command>(*this, L.Ptr);
4742 }
4743 
4744 MachO::sub_client_command
4745 MachOObjectFile::getSubClientCommand(const LoadCommandInfo &L) const {
4746   return getStruct<MachO::sub_client_command>(*this, L.Ptr);
4747 }
4748 
4749 MachO::routines_command
4750 MachOObjectFile::getRoutinesCommand(const LoadCommandInfo &L) const {
4751   return getStruct<MachO::routines_command>(*this, L.Ptr);
4752 }
4753 
4754 MachO::routines_command_64
4755 MachOObjectFile::getRoutinesCommand64(const LoadCommandInfo &L) const {
4756   return getStruct<MachO::routines_command_64>(*this, L.Ptr);
4757 }
4758 
4759 MachO::thread_command
4760 MachOObjectFile::getThreadCommand(const LoadCommandInfo &L) const {
4761   return getStruct<MachO::thread_command>(*this, L.Ptr);
4762 }
4763 
4764 MachO::any_relocation_info
4765 MachOObjectFile::getRelocation(DataRefImpl Rel) const {
4766   uint32_t Offset;
4767   if (getHeader().filetype == MachO::MH_OBJECT) {
4768     DataRefImpl Sec;
4769     Sec.d.a = Rel.d.a;
4770     if (is64Bit()) {
4771       MachO::section_64 Sect = getSection64(Sec);
4772       Offset = Sect.reloff;
4773     } else {
4774       MachO::section Sect = getSection(Sec);
4775       Offset = Sect.reloff;
4776     }
4777   } else {
4778     MachO::dysymtab_command DysymtabLoadCmd = getDysymtabLoadCommand();
4779     if (Rel.d.a == 0)
4780       Offset = DysymtabLoadCmd.extreloff; // Offset to the external relocations
4781     else
4782       Offset = DysymtabLoadCmd.locreloff; // Offset to the local relocations
4783   }
4784 
4785   auto P = reinterpret_cast<const MachO::any_relocation_info *>(
4786       getPtr(*this, Offset)) + Rel.d.b;
4787   return getStruct<MachO::any_relocation_info>(
4788       *this, reinterpret_cast<const char *>(P));
4789 }
4790 
4791 MachO::data_in_code_entry
4792 MachOObjectFile::getDice(DataRefImpl Rel) const {
4793   const char *P = reinterpret_cast<const char *>(Rel.p);
4794   return getStruct<MachO::data_in_code_entry>(*this, P);
4795 }
4796 
4797 const MachO::mach_header &MachOObjectFile::getHeader() const {
4798   return Header;
4799 }
4800 
4801 const MachO::mach_header_64 &MachOObjectFile::getHeader64() const {
4802   assert(is64Bit());
4803   return Header64;
4804 }
4805 
4806 uint32_t MachOObjectFile::getIndirectSymbolTableEntry(
4807                                              const MachO::dysymtab_command &DLC,
4808                                              unsigned Index) const {
4809   uint64_t Offset = DLC.indirectsymoff + Index * sizeof(uint32_t);
4810   return getStruct<uint32_t>(*this, getPtr(*this, Offset));
4811 }
4812 
4813 MachO::data_in_code_entry
4814 MachOObjectFile::getDataInCodeTableEntry(uint32_t DataOffset,
4815                                          unsigned Index) const {
4816   uint64_t Offset = DataOffset + Index * sizeof(MachO::data_in_code_entry);
4817   return getStruct<MachO::data_in_code_entry>(*this, getPtr(*this, Offset));
4818 }
4819 
4820 MachO::symtab_command MachOObjectFile::getSymtabLoadCommand() const {
4821   if (SymtabLoadCmd)
4822     return getStruct<MachO::symtab_command>(*this, SymtabLoadCmd);
4823 
4824   // If there is no SymtabLoadCmd return a load command with zero'ed fields.
4825   MachO::symtab_command Cmd;
4826   Cmd.cmd = MachO::LC_SYMTAB;
4827   Cmd.cmdsize = sizeof(MachO::symtab_command);
4828   Cmd.symoff = 0;
4829   Cmd.nsyms = 0;
4830   Cmd.stroff = 0;
4831   Cmd.strsize = 0;
4832   return Cmd;
4833 }
4834 
4835 MachO::dysymtab_command MachOObjectFile::getDysymtabLoadCommand() const {
4836   if (DysymtabLoadCmd)
4837     return getStruct<MachO::dysymtab_command>(*this, DysymtabLoadCmd);
4838 
4839   // If there is no DysymtabLoadCmd return a load command with zero'ed fields.
4840   MachO::dysymtab_command Cmd;
4841   Cmd.cmd = MachO::LC_DYSYMTAB;
4842   Cmd.cmdsize = sizeof(MachO::dysymtab_command);
4843   Cmd.ilocalsym = 0;
4844   Cmd.nlocalsym = 0;
4845   Cmd.iextdefsym = 0;
4846   Cmd.nextdefsym = 0;
4847   Cmd.iundefsym = 0;
4848   Cmd.nundefsym = 0;
4849   Cmd.tocoff = 0;
4850   Cmd.ntoc = 0;
4851   Cmd.modtaboff = 0;
4852   Cmd.nmodtab = 0;
4853   Cmd.extrefsymoff = 0;
4854   Cmd.nextrefsyms = 0;
4855   Cmd.indirectsymoff = 0;
4856   Cmd.nindirectsyms = 0;
4857   Cmd.extreloff = 0;
4858   Cmd.nextrel = 0;
4859   Cmd.locreloff = 0;
4860   Cmd.nlocrel = 0;
4861   return Cmd;
4862 }
4863 
4864 MachO::linkedit_data_command
4865 MachOObjectFile::getDataInCodeLoadCommand() const {
4866   if (DataInCodeLoadCmd)
4867     return getStruct<MachO::linkedit_data_command>(*this, DataInCodeLoadCmd);
4868 
4869   // If there is no DataInCodeLoadCmd return a load command with zero'ed fields.
4870   MachO::linkedit_data_command Cmd;
4871   Cmd.cmd = MachO::LC_DATA_IN_CODE;
4872   Cmd.cmdsize = sizeof(MachO::linkedit_data_command);
4873   Cmd.dataoff = 0;
4874   Cmd.datasize = 0;
4875   return Cmd;
4876 }
4877 
4878 MachO::linkedit_data_command
4879 MachOObjectFile::getLinkOptHintsLoadCommand() const {
4880   if (LinkOptHintsLoadCmd)
4881     return getStruct<MachO::linkedit_data_command>(*this, LinkOptHintsLoadCmd);
4882 
4883   // If there is no LinkOptHintsLoadCmd return a load command with zero'ed
4884   // fields.
4885   MachO::linkedit_data_command Cmd;
4886   Cmd.cmd = MachO::LC_LINKER_OPTIMIZATION_HINT;
4887   Cmd.cmdsize = sizeof(MachO::linkedit_data_command);
4888   Cmd.dataoff = 0;
4889   Cmd.datasize = 0;
4890   return Cmd;
4891 }
4892 
4893 ArrayRef<uint8_t> MachOObjectFile::getDyldInfoRebaseOpcodes() const {
4894   if (!DyldInfoLoadCmd)
4895     return std::nullopt;
4896 
4897   auto DyldInfoOrErr =
4898     getStructOrErr<MachO::dyld_info_command>(*this, DyldInfoLoadCmd);
4899   if (!DyldInfoOrErr)
4900     return std::nullopt;
4901   MachO::dyld_info_command DyldInfo = DyldInfoOrErr.get();
4902   const uint8_t *Ptr =
4903       reinterpret_cast<const uint8_t *>(getPtr(*this, DyldInfo.rebase_off));
4904   return ArrayRef(Ptr, DyldInfo.rebase_size);
4905 }
4906 
4907 ArrayRef<uint8_t> MachOObjectFile::getDyldInfoBindOpcodes() const {
4908   if (!DyldInfoLoadCmd)
4909     return std::nullopt;
4910 
4911   auto DyldInfoOrErr =
4912     getStructOrErr<MachO::dyld_info_command>(*this, DyldInfoLoadCmd);
4913   if (!DyldInfoOrErr)
4914     return std::nullopt;
4915   MachO::dyld_info_command DyldInfo = DyldInfoOrErr.get();
4916   const uint8_t *Ptr =
4917       reinterpret_cast<const uint8_t *>(getPtr(*this, DyldInfo.bind_off));
4918   return ArrayRef(Ptr, DyldInfo.bind_size);
4919 }
4920 
4921 ArrayRef<uint8_t> MachOObjectFile::getDyldInfoWeakBindOpcodes() const {
4922   if (!DyldInfoLoadCmd)
4923     return std::nullopt;
4924 
4925   auto DyldInfoOrErr =
4926     getStructOrErr<MachO::dyld_info_command>(*this, DyldInfoLoadCmd);
4927   if (!DyldInfoOrErr)
4928     return std::nullopt;
4929   MachO::dyld_info_command DyldInfo = DyldInfoOrErr.get();
4930   const uint8_t *Ptr =
4931       reinterpret_cast<const uint8_t *>(getPtr(*this, DyldInfo.weak_bind_off));
4932   return ArrayRef(Ptr, DyldInfo.weak_bind_size);
4933 }
4934 
4935 ArrayRef<uint8_t> MachOObjectFile::getDyldInfoLazyBindOpcodes() const {
4936   if (!DyldInfoLoadCmd)
4937     return std::nullopt;
4938 
4939   auto DyldInfoOrErr =
4940       getStructOrErr<MachO::dyld_info_command>(*this, DyldInfoLoadCmd);
4941   if (!DyldInfoOrErr)
4942     return std::nullopt;
4943   MachO::dyld_info_command DyldInfo = DyldInfoOrErr.get();
4944   const uint8_t *Ptr =
4945       reinterpret_cast<const uint8_t *>(getPtr(*this, DyldInfo.lazy_bind_off));
4946   return ArrayRef(Ptr, DyldInfo.lazy_bind_size);
4947 }
4948 
4949 ArrayRef<uint8_t> MachOObjectFile::getDyldInfoExportsTrie() const {
4950   if (!DyldInfoLoadCmd)
4951     return std::nullopt;
4952 
4953   auto DyldInfoOrErr =
4954       getStructOrErr<MachO::dyld_info_command>(*this, DyldInfoLoadCmd);
4955   if (!DyldInfoOrErr)
4956     return std::nullopt;
4957   MachO::dyld_info_command DyldInfo = DyldInfoOrErr.get();
4958   const uint8_t *Ptr =
4959       reinterpret_cast<const uint8_t *>(getPtr(*this, DyldInfo.export_off));
4960   return ArrayRef(Ptr, DyldInfo.export_size);
4961 }
4962 
4963 Expected<std::optional<MachO::linkedit_data_command>>
4964 MachOObjectFile::getChainedFixupsLoadCommand() const {
4965   // Load the dyld chained fixups load command.
4966   if (!DyldChainedFixupsLoadCmd)
4967     return std::nullopt;
4968   auto DyldChainedFixupsOrErr = getStructOrErr<MachO::linkedit_data_command>(
4969       *this, DyldChainedFixupsLoadCmd);
4970   if (!DyldChainedFixupsOrErr)
4971     return DyldChainedFixupsOrErr.takeError();
4972   const MachO::linkedit_data_command &DyldChainedFixups =
4973       *DyldChainedFixupsOrErr;
4974 
4975   // If the load command is present but the data offset has been zeroed out,
4976   // as is the case for dylib stubs, return std::nullopt (no error).
4977   if (!DyldChainedFixups.dataoff)
4978     return std::nullopt;
4979   return DyldChainedFixups;
4980 }
4981 
4982 Expected<std::optional<MachO::dyld_chained_fixups_header>>
4983 MachOObjectFile::getChainedFixupsHeader() const {
4984   auto CFOrErr = getChainedFixupsLoadCommand();
4985   if (!CFOrErr)
4986     return CFOrErr.takeError();
4987   if (!CFOrErr->has_value())
4988     return std::nullopt;
4989 
4990   const MachO::linkedit_data_command &DyldChainedFixups = **CFOrErr;
4991 
4992   uint64_t CFHeaderOffset = DyldChainedFixups.dataoff;
4993   uint64_t CFSize = DyldChainedFixups.datasize;
4994 
4995   // Load the dyld chained fixups header.
4996   const char *CFHeaderPtr = getPtr(*this, CFHeaderOffset);
4997   auto CFHeaderOrErr =
4998       getStructOrErr<MachO::dyld_chained_fixups_header>(*this, CFHeaderPtr);
4999   if (!CFHeaderOrErr)
5000     return CFHeaderOrErr.takeError();
5001   MachO::dyld_chained_fixups_header CFHeader = CFHeaderOrErr.get();
5002 
5003   // Reject unknown chained fixup formats.
5004   if (CFHeader.fixups_version != 0)
5005     return malformedError(Twine("bad chained fixups: unknown version: ") +
5006                           Twine(CFHeader.fixups_version));
5007   if (CFHeader.imports_format < 1 || CFHeader.imports_format > 3)
5008     return malformedError(
5009         Twine("bad chained fixups: unknown imports format: ") +
5010         Twine(CFHeader.imports_format));
5011 
5012   // Validate the image format.
5013   //
5014   // Load the image starts.
5015   uint64_t CFImageStartsOffset = (CFHeaderOffset + CFHeader.starts_offset);
5016   if (CFHeader.starts_offset < sizeof(MachO::dyld_chained_fixups_header)) {
5017     return malformedError(Twine("bad chained fixups: image starts offset ") +
5018                           Twine(CFHeader.starts_offset) +
5019                           " overlaps with chained fixups header");
5020   }
5021   uint32_t EndOffset = CFHeaderOffset + CFSize;
5022   if (CFImageStartsOffset + sizeof(MachO::dyld_chained_starts_in_image) >
5023       EndOffset) {
5024     return malformedError(Twine("bad chained fixups: image starts end ") +
5025                           Twine(CFImageStartsOffset +
5026                                 sizeof(MachO::dyld_chained_starts_in_image)) +
5027                           " extends past end " + Twine(EndOffset));
5028   }
5029 
5030   return CFHeader;
5031 }
5032 
5033 Expected<std::pair<size_t, std::vector<ChainedFixupsSegment>>>
5034 MachOObjectFile::getChainedFixupsSegments() const {
5035   auto CFOrErr = getChainedFixupsLoadCommand();
5036   if (!CFOrErr)
5037     return CFOrErr.takeError();
5038 
5039   std::vector<ChainedFixupsSegment> Segments;
5040   if (!CFOrErr->has_value())
5041     return std::make_pair(0, Segments);
5042 
5043   const MachO::linkedit_data_command &DyldChainedFixups = **CFOrErr;
5044 
5045   auto HeaderOrErr = getChainedFixupsHeader();
5046   if (!HeaderOrErr)
5047     return HeaderOrErr.takeError();
5048   if (!HeaderOrErr->has_value())
5049     return std::make_pair(0, Segments);
5050   const MachO::dyld_chained_fixups_header &Header = **HeaderOrErr;
5051 
5052   const char *Contents = getPtr(*this, DyldChainedFixups.dataoff);
5053 
5054   auto ImageStartsOrErr = getStructOrErr<MachO::dyld_chained_starts_in_image>(
5055       *this, Contents + Header.starts_offset);
5056   if (!ImageStartsOrErr)
5057     return ImageStartsOrErr.takeError();
5058   const MachO::dyld_chained_starts_in_image &ImageStarts = *ImageStartsOrErr;
5059 
5060   const char *SegOffsPtr =
5061       Contents + Header.starts_offset +
5062       offsetof(MachO::dyld_chained_starts_in_image, seg_info_offset);
5063   const char *SegOffsEnd =
5064       SegOffsPtr + ImageStarts.seg_count * sizeof(uint32_t);
5065   if (SegOffsEnd > Contents + DyldChainedFixups.datasize)
5066     return malformedError(
5067         "bad chained fixups: seg_info_offset extends past end");
5068 
5069   const char *LastSegEnd = nullptr;
5070   for (size_t I = 0, N = ImageStarts.seg_count; I < N; ++I) {
5071     auto OffOrErr =
5072         getStructOrErr<uint32_t>(*this, SegOffsPtr + I * sizeof(uint32_t));
5073     if (!OffOrErr)
5074       return OffOrErr.takeError();
5075     // seg_info_offset == 0 means there is no associated starts_in_segment
5076     // entry.
5077     if (!*OffOrErr)
5078       continue;
5079 
5080     auto Fail = [&](Twine Message) {
5081       return malformedError("bad chained fixups: segment info" + Twine(I) +
5082                             " at offset " + Twine(*OffOrErr) + Message);
5083     };
5084 
5085     const char *SegPtr = Contents + Header.starts_offset + *OffOrErr;
5086     if (LastSegEnd && SegPtr < LastSegEnd)
5087       return Fail(" overlaps with previous segment info");
5088 
5089     auto SegOrErr =
5090         getStructOrErr<MachO::dyld_chained_starts_in_segment>(*this, SegPtr);
5091     if (!SegOrErr)
5092       return SegOrErr.takeError();
5093     const MachO::dyld_chained_starts_in_segment &Seg = *SegOrErr;
5094 
5095     LastSegEnd = SegPtr + Seg.size;
5096     if (Seg.pointer_format < 1 || Seg.pointer_format > 12)
5097       return Fail(" has unknown pointer format: " + Twine(Seg.pointer_format));
5098 
5099     const char *PageStart =
5100         SegPtr + offsetof(MachO::dyld_chained_starts_in_segment, page_start);
5101     const char *PageEnd = PageStart + Seg.page_count * sizeof(uint16_t);
5102     if (PageEnd > SegPtr + Seg.size)
5103       return Fail(" : page_starts extend past seg_info size");
5104 
5105     // FIXME: This does not account for multiple offsets on a single page
5106     //        (DYLD_CHAINED_PTR_START_MULTI; 32-bit only).
5107     std::vector<uint16_t> PageStarts;
5108     for (size_t PageIdx = 0; PageIdx < Seg.page_count; ++PageIdx) {
5109       uint16_t Start;
5110       memcpy(&Start, PageStart + PageIdx * sizeof(uint16_t), sizeof(uint16_t));
5111       if (isLittleEndian() != sys::IsLittleEndianHost)
5112         sys::swapByteOrder(Start);
5113       PageStarts.push_back(Start);
5114     }
5115 
5116     Segments.emplace_back(I, *OffOrErr, Seg, std::move(PageStarts));
5117   }
5118 
5119   return std::make_pair(ImageStarts.seg_count, Segments);
5120 }
5121 
5122 // The special library ordinals have a negative value, but they are encoded in
5123 // an unsigned bitfield, so we need to sign extend the value.
5124 template <typename T> static int getEncodedOrdinal(T Value) {
5125   if (Value == static_cast<T>(MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE) ||
5126       Value == static_cast<T>(MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP) ||
5127       Value == static_cast<T>(MachO::BIND_SPECIAL_DYLIB_WEAK_LOOKUP))
5128     return SignExtend32<sizeof(T) * CHAR_BIT>(Value);
5129   return Value;
5130 }
5131 
5132 template <typename T, unsigned N>
5133 static std::array<T, N> getArray(const MachOObjectFile &O, const void *Ptr) {
5134   std::array<T, N> RawValue;
5135   memcpy(RawValue.data(), Ptr, N * sizeof(T));
5136   if (O.isLittleEndian() != sys::IsLittleEndianHost)
5137     for (auto &Element : RawValue)
5138       sys::swapByteOrder(Element);
5139   return RawValue;
5140 }
5141 
5142 Expected<std::vector<ChainedFixupTarget>>
5143 MachOObjectFile::getDyldChainedFixupTargets() const {
5144   auto CFOrErr = getChainedFixupsLoadCommand();
5145   if (!CFOrErr)
5146     return CFOrErr.takeError();
5147 
5148   std::vector<ChainedFixupTarget> Targets;
5149   if (!CFOrErr->has_value())
5150     return Targets;
5151 
5152   const MachO::linkedit_data_command &DyldChainedFixups = **CFOrErr;
5153 
5154   auto CFHeaderOrErr = getChainedFixupsHeader();
5155   if (!CFHeaderOrErr)
5156     return CFHeaderOrErr.takeError();
5157   if (!(*CFHeaderOrErr))
5158     return Targets;
5159   const MachO::dyld_chained_fixups_header &Header = **CFHeaderOrErr;
5160 
5161   size_t ImportSize = 0;
5162   if (Header.imports_format == MachO::DYLD_CHAINED_IMPORT)
5163     ImportSize = sizeof(MachO::dyld_chained_import);
5164   else if (Header.imports_format == MachO::DYLD_CHAINED_IMPORT_ADDEND)
5165     ImportSize = sizeof(MachO::dyld_chained_import_addend);
5166   else if (Header.imports_format == MachO::DYLD_CHAINED_IMPORT_ADDEND64)
5167     ImportSize = sizeof(MachO::dyld_chained_import_addend64);
5168   else
5169     return malformedError("bad chained fixups: unknown imports format: " +
5170                           Twine(Header.imports_format));
5171 
5172   const char *Contents = getPtr(*this, DyldChainedFixups.dataoff);
5173   const char *Imports = Contents + Header.imports_offset;
5174   size_t ImportsEndOffset =
5175       Header.imports_offset + ImportSize * Header.imports_count;
5176   const char *ImportsEnd = Contents + ImportsEndOffset;
5177   const char *Symbols = Contents + Header.symbols_offset;
5178   const char *SymbolsEnd = Contents + DyldChainedFixups.datasize;
5179 
5180   if (ImportsEnd > Symbols)
5181     return malformedError("bad chained fixups: imports end " +
5182                           Twine(ImportsEndOffset) + " extends past end " +
5183                           Twine(DyldChainedFixups.datasize));
5184 
5185   if (ImportsEnd > Symbols)
5186     return malformedError("bad chained fixups: imports end " +
5187                           Twine(ImportsEndOffset) + " overlaps with symbols");
5188 
5189   // We use bit manipulation to extract data from the bitfields. This is correct
5190   // for both LE and BE hosts, but we assume that the object is little-endian.
5191   if (!isLittleEndian())
5192     return createError("parsing big-endian chained fixups is not implemented");
5193   for (const char *ImportPtr = Imports; ImportPtr < ImportsEnd;
5194        ImportPtr += ImportSize) {
5195     int LibOrdinal;
5196     bool WeakImport;
5197     uint32_t NameOffset;
5198     uint64_t Addend;
5199     if (Header.imports_format == MachO::DYLD_CHAINED_IMPORT) {
5200       static_assert(sizeof(uint32_t) == sizeof(MachO::dyld_chained_import));
5201       auto RawValue = getArray<uint32_t, 1>(*this, ImportPtr);
5202 
5203       LibOrdinal = getEncodedOrdinal<uint8_t>(RawValue[0] & 0xFF);
5204       WeakImport = (RawValue[0] >> 8) & 1;
5205       NameOffset = RawValue[0] >> 9;
5206       Addend = 0;
5207     } else if (Header.imports_format == MachO::DYLD_CHAINED_IMPORT_ADDEND) {
5208       static_assert(sizeof(uint64_t) ==
5209                     sizeof(MachO::dyld_chained_import_addend));
5210       auto RawValue = getArray<uint32_t, 2>(*this, ImportPtr);
5211 
5212       LibOrdinal = getEncodedOrdinal<uint8_t>(RawValue[0] & 0xFF);
5213       WeakImport = (RawValue[0] >> 8) & 1;
5214       NameOffset = RawValue[0] >> 9;
5215       Addend = bit_cast<int32_t>(RawValue[1]);
5216     } else if (Header.imports_format == MachO::DYLD_CHAINED_IMPORT_ADDEND64) {
5217       static_assert(2 * sizeof(uint64_t) ==
5218                     sizeof(MachO::dyld_chained_import_addend64));
5219       auto RawValue = getArray<uint64_t, 2>(*this, ImportPtr);
5220 
5221       LibOrdinal = getEncodedOrdinal<uint16_t>(RawValue[0] & 0xFFFF);
5222       NameOffset = (RawValue[0] >> 16) & 1;
5223       WeakImport = RawValue[0] >> 17;
5224       Addend = RawValue[1];
5225     } else {
5226       llvm_unreachable("Import format should have been checked");
5227     }
5228 
5229     const char *Str = Symbols + NameOffset;
5230     if (Str >= SymbolsEnd)
5231       return malformedError("bad chained fixups: symbol offset " +
5232                             Twine(NameOffset) + " extends past end " +
5233                             Twine(DyldChainedFixups.datasize));
5234     Targets.emplace_back(LibOrdinal, NameOffset, Str, Addend, WeakImport);
5235   }
5236 
5237   return std::move(Targets);
5238 }
5239 
5240 ArrayRef<uint8_t> MachOObjectFile::getDyldExportsTrie() const {
5241   if (!DyldExportsTrieLoadCmd)
5242     return std::nullopt;
5243 
5244   auto DyldExportsTrieOrError = getStructOrErr<MachO::linkedit_data_command>(
5245       *this, DyldExportsTrieLoadCmd);
5246   if (!DyldExportsTrieOrError)
5247     return std::nullopt;
5248   MachO::linkedit_data_command DyldExportsTrie = DyldExportsTrieOrError.get();
5249   const uint8_t *Ptr =
5250       reinterpret_cast<const uint8_t *>(getPtr(*this, DyldExportsTrie.dataoff));
5251   return ArrayRef(Ptr, DyldExportsTrie.datasize);
5252 }
5253 
5254 SmallVector<uint64_t> MachOObjectFile::getFunctionStarts() const {
5255   if (!FuncStartsLoadCmd)
5256     return {};
5257 
5258   auto InfoOrErr =
5259       getStructOrErr<MachO::linkedit_data_command>(*this, FuncStartsLoadCmd);
5260   if (!InfoOrErr)
5261     return {};
5262 
5263   MachO::linkedit_data_command Info = InfoOrErr.get();
5264   SmallVector<uint64_t, 8> FunctionStarts;
5265   this->ReadULEB128s(Info.dataoff, FunctionStarts);
5266   return std::move(FunctionStarts);
5267 }
5268 
5269 ArrayRef<uint8_t> MachOObjectFile::getUuid() const {
5270   if (!UuidLoadCmd)
5271     return std::nullopt;
5272   // Returning a pointer is fine as uuid doesn't need endian swapping.
5273   const char *Ptr = UuidLoadCmd + offsetof(MachO::uuid_command, uuid);
5274   return ArrayRef(reinterpret_cast<const uint8_t *>(Ptr), 16);
5275 }
5276 
5277 StringRef MachOObjectFile::getStringTableData() const {
5278   MachO::symtab_command S = getSymtabLoadCommand();
5279   return getData().substr(S.stroff, S.strsize);
5280 }
5281 
5282 bool MachOObjectFile::is64Bit() const {
5283   return getType() == getMachOType(false, true) ||
5284     getType() == getMachOType(true, true);
5285 }
5286 
5287 void MachOObjectFile::ReadULEB128s(uint64_t Index,
5288                                    SmallVectorImpl<uint64_t> &Out) const {
5289   DataExtractor extractor(ObjectFile::getData(), true, 0);
5290 
5291   uint64_t offset = Index;
5292   uint64_t data = 0;
5293   while (uint64_t delta = extractor.getULEB128(&offset)) {
5294     data += delta;
5295     Out.push_back(data);
5296   }
5297 }
5298 
5299 bool MachOObjectFile::isRelocatableObject() const {
5300   return getHeader().filetype == MachO::MH_OBJECT;
5301 }
5302 
5303 Expected<std::unique_ptr<MachOObjectFile>>
5304 ObjectFile::createMachOObjectFile(MemoryBufferRef Buffer,
5305                                   uint32_t UniversalCputype,
5306                                   uint32_t UniversalIndex) {
5307   StringRef Magic = Buffer.getBuffer().slice(0, 4);
5308   if (Magic == "\xFE\xED\xFA\xCE")
5309     return MachOObjectFile::create(Buffer, false, false,
5310                                    UniversalCputype, UniversalIndex);
5311   if (Magic == "\xCE\xFA\xED\xFE")
5312     return MachOObjectFile::create(Buffer, true, false,
5313                                    UniversalCputype, UniversalIndex);
5314   if (Magic == "\xFE\xED\xFA\xCF")
5315     return MachOObjectFile::create(Buffer, false, true,
5316                                    UniversalCputype, UniversalIndex);
5317   if (Magic == "\xCF\xFA\xED\xFE")
5318     return MachOObjectFile::create(Buffer, true, true,
5319                                    UniversalCputype, UniversalIndex);
5320   return make_error<GenericBinaryError>("Unrecognized MachO magic number",
5321                                         object_error::invalid_file_type);
5322 }
5323 
5324 StringRef MachOObjectFile::mapDebugSectionName(StringRef Name) const {
5325   return StringSwitch<StringRef>(Name)
5326       .Case("debug_str_offs", "debug_str_offsets")
5327       .Default(Name);
5328 }
5329 
5330 Expected<std::vector<std::string>>
5331 MachOObjectFile::findDsymObjectMembers(StringRef Path) {
5332   SmallString<256> BundlePath(Path);
5333   // Normalize input path. This is necessary to accept `bundle.dSYM/`.
5334   sys::path::remove_dots(BundlePath);
5335   if (!sys::fs::is_directory(BundlePath) ||
5336       sys::path::extension(BundlePath) != ".dSYM")
5337     return std::vector<std::string>();
5338   sys::path::append(BundlePath, "Contents", "Resources", "DWARF");
5339   bool IsDir;
5340   auto EC = sys::fs::is_directory(BundlePath, IsDir);
5341   if (EC == errc::no_such_file_or_directory || (!EC && !IsDir))
5342     return createStringError(
5343         EC, "%s: expected directory 'Contents/Resources/DWARF' in dSYM bundle",
5344         Path.str().c_str());
5345   if (EC)
5346     return createFileError(BundlePath, errorCodeToError(EC));
5347 
5348   std::vector<std::string> ObjectPaths;
5349   for (sys::fs::directory_iterator Dir(BundlePath, EC), DirEnd;
5350        Dir != DirEnd && !EC; Dir.increment(EC)) {
5351     StringRef ObjectPath = Dir->path();
5352     sys::fs::file_status Status;
5353     if (auto EC = sys::fs::status(ObjectPath, Status))
5354       return createFileError(ObjectPath, errorCodeToError(EC));
5355     switch (Status.type()) {
5356     case sys::fs::file_type::regular_file:
5357     case sys::fs::file_type::symlink_file:
5358     case sys::fs::file_type::type_unknown:
5359       ObjectPaths.push_back(ObjectPath.str());
5360       break;
5361     default: /*ignore*/;
5362     }
5363   }
5364   if (EC)
5365     return createFileError(BundlePath, errorCodeToError(EC));
5366   if (ObjectPaths.empty())
5367     return createStringError(std::error_code(),
5368                              "%s: no objects found in dSYM bundle",
5369                              Path.str().c_str());
5370   return ObjectPaths;
5371 }
5372 
5373 llvm::binaryformat::Swift5ReflectionSectionKind
5374 MachOObjectFile::mapReflectionSectionNameToEnumValue(
5375     StringRef SectionName) const {
5376 #define HANDLE_SWIFT_SECTION(KIND, MACHO, ELF, COFF)                           \
5377   .Case(MACHO, llvm::binaryformat::Swift5ReflectionSectionKind::KIND)
5378   return StringSwitch<llvm::binaryformat::Swift5ReflectionSectionKind>(
5379              SectionName)
5380 #include "llvm/BinaryFormat/Swift.def"
5381       .Default(llvm::binaryformat::Swift5ReflectionSectionKind::unknown);
5382 #undef HANDLE_SWIFT_SECTION
5383 }
5384 
5385 bool MachOObjectFile::isMachOPairedReloc(uint64_t RelocType, uint64_t Arch) {
5386   switch (Arch) {
5387   case Triple::x86:
5388     return RelocType == MachO::GENERIC_RELOC_SECTDIFF ||
5389            RelocType == MachO::GENERIC_RELOC_LOCAL_SECTDIFF;
5390   case Triple::x86_64:
5391     return RelocType == MachO::X86_64_RELOC_SUBTRACTOR;
5392   case Triple::arm:
5393   case Triple::thumb:
5394     return RelocType == MachO::ARM_RELOC_SECTDIFF ||
5395            RelocType == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
5396            RelocType == MachO::ARM_RELOC_HALF ||
5397            RelocType == MachO::ARM_RELOC_HALF_SECTDIFF;
5398   case Triple::aarch64:
5399     return RelocType == MachO::ARM64_RELOC_SUBTRACTOR;
5400   default:
5401     return false;
5402   }
5403 }
5404