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