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