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