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