1 //===- MachOObjectFile.cpp - Mach-O object file binding ---------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the MachOObjectFile class, which binds the MachOObject
11 // class to the generic ObjectFile wrapper.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/Object/MachO.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/StringSwitch.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/Support/DataExtractor.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/Format.h"
22 #include "llvm/Support/Host.h"
23 #include "llvm/Support/LEB128.h"
24 #include "llvm/Support/MachO.h"
25 #include "llvm/Support/MemoryBuffer.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include <cctype>
28 #include <cstring>
29 #include <limits>
30 
31 using namespace llvm;
32 using namespace object;
33 
34 namespace {
35   struct section_base {
36     char sectname[16];
37     char segname[16];
38   };
39 }
40 
41 static Error
42 malformedError(Twine Msg) {
43   std::string StringMsg = "truncated or malformed object (" + Msg.str() + ")";
44   return make_error<GenericBinaryError>(std::move(StringMsg),
45                                         object_error::parse_failed);
46 }
47 
48 // FIXME: Replace all uses of this function with getStructOrErr.
49 template <typename T>
50 static T getStruct(const MachOObjectFile *O, const char *P) {
51   // Don't read before the beginning or past the end of the file
52   if (P < O->getData().begin() || P + sizeof(T) > O->getData().end())
53     report_fatal_error("Malformed MachO file.");
54 
55   T Cmd;
56   memcpy(&Cmd, P, sizeof(T));
57   if (O->isLittleEndian() != sys::IsLittleEndianHost)
58     MachO::swapStruct(Cmd);
59   return Cmd;
60 }
61 
62 template <typename T>
63 static Expected<T> getStructOrErr(const MachOObjectFile *O, const char *P) {
64   // Don't read before the beginning or past the end of the file
65   if (P < O->getData().begin() || P + sizeof(T) > O->getData().end())
66     return malformedError("Structure read out-of-range");
67 
68   T Cmd;
69   memcpy(&Cmd, P, sizeof(T));
70   if (O->isLittleEndian() != sys::IsLittleEndianHost)
71     MachO::swapStruct(Cmd);
72   return Cmd;
73 }
74 
75 static const char *
76 getSectionPtr(const MachOObjectFile *O, MachOObjectFile::LoadCommandInfo L,
77               unsigned Sec) {
78   uintptr_t CommandAddr = reinterpret_cast<uintptr_t>(L.Ptr);
79 
80   bool Is64 = O->is64Bit();
81   unsigned SegmentLoadSize = Is64 ? sizeof(MachO::segment_command_64) :
82                                     sizeof(MachO::segment_command);
83   unsigned SectionSize = Is64 ? sizeof(MachO::section_64) :
84                                 sizeof(MachO::section);
85 
86   uintptr_t SectionAddr = CommandAddr + SegmentLoadSize + Sec * SectionSize;
87   return reinterpret_cast<const char*>(SectionAddr);
88 }
89 
90 static const char *getPtr(const MachOObjectFile *O, size_t Offset) {
91   return O->getData().substr(Offset, 1).data();
92 }
93 
94 static MachO::nlist_base
95 getSymbolTableEntryBase(const MachOObjectFile *O, DataRefImpl DRI) {
96   const char *P = reinterpret_cast<const char *>(DRI.p);
97   return getStruct<MachO::nlist_base>(O, P);
98 }
99 
100 static StringRef parseSegmentOrSectionName(const char *P) {
101   if (P[15] == 0)
102     // Null terminated.
103     return P;
104   // Not null terminated, so this is a 16 char string.
105   return StringRef(P, 16);
106 }
107 
108 // Helper to advance a section or symbol iterator multiple increments at a time.
109 template<class T>
110 static void advance(T &it, size_t Val) {
111   while (Val--)
112     ++it;
113 }
114 
115 static unsigned getCPUType(const MachOObjectFile *O) {
116   return O->getHeader().cputype;
117 }
118 
119 static uint32_t
120 getPlainRelocationAddress(const MachO::any_relocation_info &RE) {
121   return RE.r_word0;
122 }
123 
124 static unsigned
125 getScatteredRelocationAddress(const MachO::any_relocation_info &RE) {
126   return RE.r_word0 & 0xffffff;
127 }
128 
129 static bool getPlainRelocationPCRel(const MachOObjectFile *O,
130                                     const MachO::any_relocation_info &RE) {
131   if (O->isLittleEndian())
132     return (RE.r_word1 >> 24) & 1;
133   return (RE.r_word1 >> 7) & 1;
134 }
135 
136 static bool
137 getScatteredRelocationPCRel(const MachOObjectFile *O,
138                             const MachO::any_relocation_info &RE) {
139   return (RE.r_word0 >> 30) & 1;
140 }
141 
142 static unsigned getPlainRelocationLength(const MachOObjectFile *O,
143                                          const MachO::any_relocation_info &RE) {
144   if (O->isLittleEndian())
145     return (RE.r_word1 >> 25) & 3;
146   return (RE.r_word1 >> 5) & 3;
147 }
148 
149 static unsigned
150 getScatteredRelocationLength(const MachO::any_relocation_info &RE) {
151   return (RE.r_word0 >> 28) & 3;
152 }
153 
154 static unsigned getPlainRelocationType(const MachOObjectFile *O,
155                                        const MachO::any_relocation_info &RE) {
156   if (O->isLittleEndian())
157     return RE.r_word1 >> 28;
158   return RE.r_word1 & 0xf;
159 }
160 
161 static uint32_t getSectionFlags(const MachOObjectFile *O,
162                                 DataRefImpl Sec) {
163   if (O->is64Bit()) {
164     MachO::section_64 Sect = O->getSection64(Sec);
165     return Sect.flags;
166   }
167   MachO::section Sect = O->getSection(Sec);
168   return Sect.flags;
169 }
170 
171 static Expected<MachOObjectFile::LoadCommandInfo>
172 getLoadCommandInfo(const MachOObjectFile *Obj, const char *Ptr,
173                    uint32_t LoadCommandIndex) {
174   if (auto CmdOrErr = getStructOrErr<MachO::load_command>(Obj, Ptr)) {
175     if (CmdOrErr->cmdsize < 8)
176       return malformedError("load command " + Twine(LoadCommandIndex) +
177                             " with size less than 8 bytes");
178     return MachOObjectFile::LoadCommandInfo({Ptr, *CmdOrErr});
179   } else
180     return CmdOrErr.takeError();
181 }
182 
183 static Expected<MachOObjectFile::LoadCommandInfo>
184 getFirstLoadCommandInfo(const MachOObjectFile *Obj) {
185   unsigned HeaderSize = Obj->is64Bit() ? sizeof(MachO::mach_header_64)
186                                        : sizeof(MachO::mach_header);
187   if (sizeof(MachO::load_command) > Obj->getHeader().sizeofcmds)
188     return malformedError("load command 0 extends past the end all load "
189                           "commands in the file");
190   return getLoadCommandInfo(Obj, getPtr(Obj, HeaderSize), 0);
191 }
192 
193 static Expected<MachOObjectFile::LoadCommandInfo>
194 getNextLoadCommandInfo(const MachOObjectFile *Obj, uint32_t LoadCommandIndex,
195                        const MachOObjectFile::LoadCommandInfo &L) {
196   unsigned HeaderSize = Obj->is64Bit() ? sizeof(MachO::mach_header_64)
197                                        : sizeof(MachO::mach_header);
198   if (L.Ptr + L.C.cmdsize + sizeof(MachO::load_command) >
199       Obj->getData().data() + HeaderSize + Obj->getHeader().sizeofcmds)
200     return malformedError("load command " + Twine(LoadCommandIndex + 1) +
201                           " extends past the end all load commands in the file");
202   return getLoadCommandInfo(Obj, L.Ptr + L.C.cmdsize, LoadCommandIndex + 1);
203 }
204 
205 template <typename T>
206 static void parseHeader(const MachOObjectFile *Obj, T &Header,
207                         Error &Err) {
208   if (sizeof(T) > Obj->getData().size()) {
209     Err = malformedError("the mach header extends past the end of the "
210                          "file");
211     return;
212   }
213   if (auto HeaderOrErr = getStructOrErr<T>(Obj, getPtr(Obj, 0)))
214     Header = *HeaderOrErr;
215   else
216     Err = HeaderOrErr.takeError();
217 }
218 
219 // Parses LC_SEGMENT or LC_SEGMENT_64 load command, adds addresses of all
220 // sections to \param Sections, and optionally sets
221 // \param IsPageZeroSegment to true.
222 template <typename Segment, typename Section>
223 static Error parseSegmentLoadCommand(
224     const MachOObjectFile *Obj, const MachOObjectFile::LoadCommandInfo &Load,
225     SmallVectorImpl<const char *> &Sections, bool &IsPageZeroSegment,
226     uint32_t LoadCommandIndex, const char *CmdName, uint64_t SizeOfHeaders) {
227   const unsigned SegmentLoadSize = sizeof(Segment);
228   if (Load.C.cmdsize < SegmentLoadSize)
229     return malformedError("load command " + Twine(LoadCommandIndex) +
230                           " " + CmdName + " cmdsize too small");
231   if (auto SegOrErr = getStructOrErr<Segment>(Obj, Load.Ptr)) {
232     Segment S = SegOrErr.get();
233     const unsigned SectionSize = sizeof(Section);
234     uint64_t FileSize = Obj->getData().size();
235     if (S.nsects > std::numeric_limits<uint32_t>::max() / SectionSize ||
236         S.nsects * SectionSize > Load.C.cmdsize - SegmentLoadSize)
237       return malformedError("load command " + Twine(LoadCommandIndex) +
238                             " inconsistent cmdsize in " + CmdName +
239                             " for the number of sections");
240     for (unsigned J = 0; J < S.nsects; ++J) {
241       const char *Sec = getSectionPtr(Obj, Load, J);
242       Sections.push_back(Sec);
243       Section s = getStruct<Section>(Obj, Sec);
244       if (Obj->getHeader().filetype != MachO::MH_DYLIB_STUB &&
245           Obj->getHeader().filetype != MachO::MH_DSYM &&
246           s.flags != MachO::S_ZEROFILL &&
247           s.flags != MachO::S_THREAD_LOCAL_ZEROFILL &&
248           s.offset > FileSize)
249         return malformedError("offset field of section " + Twine(J) + " in " +
250                               CmdName + " command " + Twine(LoadCommandIndex) +
251                               " extends past the end of the file");
252       if (Obj->getHeader().filetype != MachO::MH_DYLIB_STUB &&
253           Obj->getHeader().filetype != MachO::MH_DSYM &&
254           s.flags != MachO::S_ZEROFILL &&
255           s.flags != MachO::S_THREAD_LOCAL_ZEROFILL && S.fileoff == 0 &&
256           s.offset < SizeOfHeaders && s.size != 0)
257         return malformedError("offset field of section " + Twine(J) + " in " +
258                               CmdName + " command " + Twine(LoadCommandIndex) +
259                               " not past the headers of the file");
260       uint64_t BigSize = s.offset;
261       BigSize += s.size;
262       if (Obj->getHeader().filetype != MachO::MH_DYLIB_STUB &&
263           Obj->getHeader().filetype != MachO::MH_DSYM &&
264           s.flags != MachO::S_ZEROFILL &&
265           s.flags != MachO::S_THREAD_LOCAL_ZEROFILL &&
266           BigSize > FileSize)
267         return malformedError("offset field plus size field of section " +
268                               Twine(J) + " in " + CmdName + " command " +
269                               Twine(LoadCommandIndex) +
270                               " extends past the end of the file");
271       if (Obj->getHeader().filetype != MachO::MH_DYLIB_STUB &&
272           Obj->getHeader().filetype != MachO::MH_DSYM &&
273           s.flags != MachO::S_ZEROFILL &&
274           s.flags != MachO::S_THREAD_LOCAL_ZEROFILL &&
275           s.size > S.filesize)
276         return malformedError("size field of section " +
277                               Twine(J) + " in " + CmdName + " command " +
278                               Twine(LoadCommandIndex) +
279                               " greater than the segment");
280       if (Obj->getHeader().filetype != MachO::MH_DYLIB_STUB &&
281           Obj->getHeader().filetype != MachO::MH_DSYM && s.size != 0 &&
282           s.addr < S.vmaddr)
283         return malformedError("addr field of section " + Twine(J) + " in " +
284                               CmdName + " command " + Twine(LoadCommandIndex) +
285                               " less than the segment's vmaddr");
286       BigSize = s.addr;
287       BigSize += s.size;
288       uint64_t BigEnd = S.vmaddr;
289       BigEnd += S.vmsize;
290       if (S.vmsize != 0 && s.size != 0 && BigSize > BigEnd)
291         return malformedError("addr field plus size of section " + Twine(J) +
292                               " in " + CmdName + " command " +
293                               Twine(LoadCommandIndex) +
294                               " greater than than "
295                               "the segment's vmaddr plus vmsize");
296       if (s.reloff > FileSize)
297         return malformedError("reloff field of section " + Twine(J) + " in " +
298                               CmdName + " command " + Twine(LoadCommandIndex) +
299                               " extends past the end of the file");
300       BigSize = s.nreloc;
301       BigSize *= sizeof(struct MachO::relocation_info);
302       BigSize += s.reloff;
303       if (BigSize > FileSize)
304         return malformedError("reloff field plus nreloc field times sizeof("
305                               "struct relocation_info) of section " +
306                               Twine(J) + " in " + CmdName + " command " +
307                               Twine(LoadCommandIndex) +
308                               " extends past the end of the file");
309     }
310     if (S.fileoff > FileSize)
311       return malformedError("load command " + Twine(LoadCommandIndex) +
312                             " fileoff field in " + CmdName +
313                             " extends past the end of the file");
314     uint64_t BigSize = S.fileoff;
315     BigSize += S.filesize;
316     if (BigSize > FileSize)
317       return malformedError("load command " + Twine(LoadCommandIndex) +
318                             " fileoff field plus filesize field in " +
319                             CmdName + " extends past the end of the file");
320     if (S.vmsize != 0 && S.filesize > S.vmsize)
321       return malformedError("load command " + Twine(LoadCommandIndex) +
322                             " fileoff field in " + CmdName +
323                             " greater than vmsize field");
324     IsPageZeroSegment |= StringRef("__PAGEZERO").equals(S.segname);
325   } else
326     return SegOrErr.takeError();
327 
328   return Error::success();
329 }
330 
331 static Error checkSymtabCommand(const MachOObjectFile *Obj,
332                                 const MachOObjectFile::LoadCommandInfo &Load,
333                                 uint32_t LoadCommandIndex,
334                                 const char **SymtabLoadCmd) {
335   if (Load.C.cmdsize < sizeof(MachO::symtab_command))
336     return malformedError("load command " + Twine(LoadCommandIndex) +
337                           " LC_SYMTAB cmdsize too small");
338   if (*SymtabLoadCmd != nullptr)
339     return malformedError("more than one LC_SYMTAB command");
340   MachO::symtab_command Symtab =
341     getStruct<MachO::symtab_command>(Obj, Load.Ptr);
342   if (Symtab.cmdsize != sizeof(MachO::symtab_command))
343     return malformedError("LC_SYMTAB command " + Twine(LoadCommandIndex) +
344                           " has incorrect cmdsize");
345   uint64_t FileSize = Obj->getData().size();
346   if (Symtab.symoff > FileSize)
347     return malformedError("symoff field of LC_SYMTAB command " +
348                           Twine(LoadCommandIndex) + " extends past the end "
349                           "of the file");
350   uint64_t BigSize = Symtab.nsyms;
351   const char *struct_nlist_name;
352   if (Obj->is64Bit()) {
353     BigSize *= sizeof(MachO::nlist_64);
354     struct_nlist_name = "struct nlist_64";
355   } else {
356     BigSize *= sizeof(MachO::nlist);
357     struct_nlist_name = "struct nlist";
358   }
359   BigSize += Symtab.symoff;
360   if (BigSize > FileSize)
361     return malformedError("symoff field plus nsyms field times sizeof(" +
362                           Twine(struct_nlist_name) + ") of LC_SYMTAB command " +
363                           Twine(LoadCommandIndex) + " extends past the end "
364                           "of the file");
365   if (Symtab.stroff > FileSize)
366     return malformedError("stroff field of LC_SYMTAB command " +
367                           Twine(LoadCommandIndex) + " extends past the end "
368                           "of the file");
369   BigSize = Symtab.stroff;
370   BigSize += Symtab.strsize;
371   if (BigSize > FileSize)
372     return malformedError("stroff field plus strsize field of LC_SYMTAB "
373                           "command " + Twine(LoadCommandIndex) + " extends "
374                           "past the end of the file");
375   *SymtabLoadCmd = Load.Ptr;
376   return Error::success();
377 }
378 
379 static Error checkDysymtabCommand(const MachOObjectFile *Obj,
380                                  const MachOObjectFile::LoadCommandInfo &Load,
381                                  uint32_t LoadCommandIndex,
382                                  const char **DysymtabLoadCmd) {
383   if (Load.C.cmdsize < sizeof(MachO::dysymtab_command))
384     return malformedError("load command " + Twine(LoadCommandIndex) +
385                           " LC_DYSYMTAB cmdsize too small");
386   if (*DysymtabLoadCmd != nullptr)
387     return malformedError("more than one LC_DYSYMTAB command");
388   MachO::dysymtab_command Dysymtab =
389     getStruct<MachO::dysymtab_command>(Obj, Load.Ptr);
390   if (Dysymtab.cmdsize != sizeof(MachO::dysymtab_command))
391     return malformedError("LC_DYSYMTAB command " + Twine(LoadCommandIndex) +
392                           " has incorrect cmdsize");
393   uint64_t FileSize = Obj->getData().size();
394   if (Dysymtab.tocoff > FileSize)
395     return malformedError("tocoff field of LC_DYSYMTAB command " +
396                           Twine(LoadCommandIndex) + " extends past the end of "
397                           "the file");
398   uint64_t BigSize = Dysymtab.ntoc;
399   BigSize *= sizeof(MachO::dylib_table_of_contents);
400   BigSize += Dysymtab.tocoff;
401   if (BigSize > FileSize)
402     return malformedError("tocoff field plus ntoc field times sizeof(struct "
403                           "dylib_table_of_contents) of LC_DYSYMTAB command " +
404                           Twine(LoadCommandIndex) + " extends past the end of "
405                           "the file");
406   if (Dysymtab.modtaboff > FileSize)
407     return malformedError("modtaboff field of LC_DYSYMTAB command " +
408                           Twine(LoadCommandIndex) + " extends past the end of "
409                           "the file");
410   BigSize = Dysymtab.nmodtab;
411   const char *struct_dylib_module_name;
412   if (Obj->is64Bit()) {
413     BigSize *= sizeof(MachO::dylib_module_64);
414     struct_dylib_module_name = "struct dylib_module_64";
415   } else {
416     BigSize *= sizeof(MachO::dylib_module);
417     struct_dylib_module_name = "struct dylib_module";
418   }
419   BigSize += Dysymtab.modtaboff;
420   if (BigSize > FileSize)
421     return malformedError("modtaboff field plus nmodtab field times sizeof(" +
422                           Twine(struct_dylib_module_name) + ") of LC_DYSYMTAB "
423                           "command " + Twine(LoadCommandIndex) + " extends "
424                           "past the end of the file");
425   if (Dysymtab.extrefsymoff > FileSize)
426     return malformedError("extrefsymoff field of LC_DYSYMTAB command " +
427                           Twine(LoadCommandIndex) + " extends past the end of "
428                           "the file");
429   BigSize = Dysymtab.nextrefsyms;
430   BigSize *= sizeof(MachO::dylib_reference);
431   BigSize += Dysymtab.extrefsymoff;
432   if (BigSize > FileSize)
433     return malformedError("extrefsymoff field plus nextrefsyms field times "
434                           "sizeof(struct dylib_reference) of LC_DYSYMTAB "
435                           "command " + Twine(LoadCommandIndex) + " extends "
436                           "past the end of the file");
437   if (Dysymtab.indirectsymoff > FileSize)
438     return malformedError("indirectsymoff field of LC_DYSYMTAB command " +
439                           Twine(LoadCommandIndex) + " extends past the end of "
440                           "the file");
441   BigSize = Dysymtab.nindirectsyms;
442   BigSize *= sizeof(uint32_t);
443   BigSize += Dysymtab.indirectsymoff;
444   if (BigSize > FileSize)
445     return malformedError("indirectsymoff field plus nindirectsyms field times "
446                           "sizeof(uint32_t) of LC_DYSYMTAB command " +
447                           Twine(LoadCommandIndex) + " extends past the end of "
448                           "the file");
449   if (Dysymtab.extreloff > FileSize)
450     return malformedError("extreloff field of LC_DYSYMTAB command " +
451                           Twine(LoadCommandIndex) + " extends past the end of "
452                           "the file");
453   BigSize = Dysymtab.nextrel;
454   BigSize *= sizeof(MachO::relocation_info);
455   BigSize += Dysymtab.extreloff;
456   if (BigSize > FileSize)
457     return malformedError("extreloff field plus nextrel field times sizeof"
458                           "(struct relocation_info) of LC_DYSYMTAB command " +
459                           Twine(LoadCommandIndex) + " extends past the end of "
460                           "the file");
461   if (Dysymtab.locreloff > FileSize)
462     return malformedError("locreloff field of LC_DYSYMTAB command " +
463                           Twine(LoadCommandIndex) + " extends past the end of "
464                           "the file");
465   BigSize = Dysymtab.nlocrel;
466   BigSize *= sizeof(MachO::relocation_info);
467   BigSize += Dysymtab.locreloff;
468   if (BigSize > FileSize)
469     return malformedError("locreloff field plus nlocrel field times sizeof"
470                           "(struct relocation_info) of LC_DYSYMTAB command " +
471                           Twine(LoadCommandIndex) + " extends past the end of "
472                           "the file");
473   *DysymtabLoadCmd = Load.Ptr;
474   return Error::success();
475 }
476 
477 static Error checkLinkeditDataCommand(const MachOObjectFile *Obj,
478                                  const MachOObjectFile::LoadCommandInfo &Load,
479                                  uint32_t LoadCommandIndex,
480                                  const char **LoadCmd, const char *CmdName) {
481   if (Load.C.cmdsize < sizeof(MachO::linkedit_data_command))
482     return malformedError("load command " + Twine(LoadCommandIndex) + " " +
483                           CmdName + " cmdsize too small");
484   if (*LoadCmd != nullptr)
485     return malformedError("more than one " + Twine(CmdName) + " command");
486   MachO::linkedit_data_command LinkData =
487     getStruct<MachO::linkedit_data_command>(Obj, Load.Ptr);
488   if (LinkData.cmdsize != sizeof(MachO::linkedit_data_command))
489     return malformedError(Twine(CmdName) + " command " +
490                           Twine(LoadCommandIndex) + " has incorrect cmdsize");
491   uint64_t FileSize = Obj->getData().size();
492   if (LinkData.dataoff > FileSize)
493     return malformedError("dataoff field of " + Twine(CmdName) + " command " +
494                           Twine(LoadCommandIndex) + " extends past the end of "
495                           "the file");
496   uint64_t BigSize = LinkData.dataoff;
497   BigSize += LinkData.datasize;
498   if (BigSize > FileSize)
499     return malformedError("dataoff field plus datasize field of " +
500                           Twine(CmdName) + " command " +
501                           Twine(LoadCommandIndex) + " extends past the end of "
502                           "the file");
503   *LoadCmd = Load.Ptr;
504   return Error::success();
505 }
506 
507 static Error checkDyldInfoCommand(const MachOObjectFile *Obj,
508                                   const MachOObjectFile::LoadCommandInfo &Load,
509                                   uint32_t LoadCommandIndex,
510                                   const char **LoadCmd, const char *CmdName) {
511   if (Load.C.cmdsize < sizeof(MachO::dyld_info_command))
512     return malformedError("load command " + Twine(LoadCommandIndex) + " " +
513                           CmdName + " cmdsize too small");
514   if (*LoadCmd != nullptr)
515     return malformedError("more than one LC_DYLD_INFO and or LC_DYLD_INFO_ONLY "
516                           "command");
517   MachO::dyld_info_command DyldInfo =
518     getStruct<MachO::dyld_info_command>(Obj, Load.Ptr);
519   if (DyldInfo.cmdsize != sizeof(MachO::dyld_info_command))
520     return malformedError(Twine(CmdName) + " command " +
521                           Twine(LoadCommandIndex) + " has incorrect cmdsize");
522   uint64_t FileSize = Obj->getData().size();
523   if (DyldInfo.rebase_off > FileSize)
524     return malformedError("rebase_off field of " + Twine(CmdName) +
525                           " command " + Twine(LoadCommandIndex) + " extends "
526                           "past the end of the file");
527   uint64_t BigSize = DyldInfo.rebase_off;
528   BigSize += DyldInfo.rebase_size;
529   if (BigSize > FileSize)
530     return malformedError("rebase_off field plus rebase_size field of " +
531                           Twine(CmdName) + " command " +
532                           Twine(LoadCommandIndex) + " extends past the end of "
533                           "the file");
534   if (DyldInfo.bind_off > FileSize)
535     return malformedError("bind_off field of " + Twine(CmdName) +
536                           " command " + Twine(LoadCommandIndex) + " extends "
537                           "past the end of the file");
538   BigSize = DyldInfo.bind_off;
539   BigSize += DyldInfo.bind_size;
540   if (BigSize > FileSize)
541     return malformedError("bind_off field plus bind_size field of " +
542                           Twine(CmdName) + " command " +
543                           Twine(LoadCommandIndex) + " extends past the end of "
544                           "the file");
545   if (DyldInfo.weak_bind_off > FileSize)
546     return malformedError("weak_bind_off field of " + Twine(CmdName) +
547                           " command " + Twine(LoadCommandIndex) + " extends "
548                           "past the end of the file");
549   BigSize = DyldInfo.weak_bind_off;
550   BigSize += DyldInfo.weak_bind_size;
551   if (BigSize > FileSize)
552     return malformedError("weak_bind_off field plus weak_bind_size field of " +
553                           Twine(CmdName) + " command " +
554                           Twine(LoadCommandIndex) + " extends past the end of "
555                           "the file");
556   if (DyldInfo.lazy_bind_off > FileSize)
557     return malformedError("lazy_bind_off field of " + Twine(CmdName) +
558                           " command " + Twine(LoadCommandIndex) + " extends "
559                           "past the end of the file");
560   BigSize = DyldInfo.lazy_bind_off;
561   BigSize += DyldInfo.lazy_bind_size;
562   if (BigSize > FileSize)
563     return malformedError("lazy_bind_off field plus lazy_bind_size field of " +
564                           Twine(CmdName) + " command " +
565                           Twine(LoadCommandIndex) + " extends past the end of "
566                           "the file");
567   if (DyldInfo.export_off > FileSize)
568     return malformedError("export_off field of " + Twine(CmdName) +
569                           " command " + Twine(LoadCommandIndex) + " extends "
570                           "past the end of the file");
571   BigSize = DyldInfo.export_off;
572   BigSize += DyldInfo.export_size;
573   if (BigSize > FileSize)
574     return malformedError("export_off field plus export_size field of " +
575                           Twine(CmdName) + " command " +
576                           Twine(LoadCommandIndex) + " extends past the end of "
577                           "the file");
578   *LoadCmd = Load.Ptr;
579   return Error::success();
580 }
581 
582 Expected<std::unique_ptr<MachOObjectFile>>
583 MachOObjectFile::create(MemoryBufferRef Object, bool IsLittleEndian,
584                         bool Is64Bits) {
585   Error Err;
586   std::unique_ptr<MachOObjectFile> Obj(
587       new MachOObjectFile(std::move(Object), IsLittleEndian,
588                            Is64Bits, Err));
589   if (Err)
590     return std::move(Err);
591   return std::move(Obj);
592 }
593 
594 MachOObjectFile::MachOObjectFile(MemoryBufferRef Object, bool IsLittleEndian,
595                                  bool Is64bits, Error &Err)
596     : ObjectFile(getMachOType(IsLittleEndian, Is64bits), Object),
597       SymtabLoadCmd(nullptr), DysymtabLoadCmd(nullptr),
598       DataInCodeLoadCmd(nullptr), LinkOptHintsLoadCmd(nullptr),
599       DyldInfoLoadCmd(nullptr), UuidLoadCmd(nullptr),
600       HasPageZeroSegment(false) {
601   ErrorAsOutParameter ErrAsOutParam(&Err);
602   uint64_t SizeOfHeaders;
603   if (is64Bit()) {
604     parseHeader(this, Header64, Err);
605     SizeOfHeaders = sizeof(MachO::mach_header_64);
606   } else {
607     parseHeader(this, Header, Err);
608     SizeOfHeaders = sizeof(MachO::mach_header);
609   }
610   if (Err)
611     return;
612   SizeOfHeaders += getHeader().sizeofcmds;
613   if (getData().data() + SizeOfHeaders > getData().end()) {
614     Err = malformedError("load commands extend past the end of the file");
615     return;
616   }
617 
618   uint32_t LoadCommandCount = getHeader().ncmds;
619   if (LoadCommandCount == 0)
620     return;
621 
622   LoadCommandInfo Load;
623   if (auto LoadOrErr = getFirstLoadCommandInfo(this))
624     Load = *LoadOrErr;
625   else {
626     Err = LoadOrErr.takeError();
627     return;
628   }
629 
630   for (unsigned I = 0; I < LoadCommandCount; ++I) {
631     if (is64Bit()) {
632       if (Load.C.cmdsize % 8 != 0) {
633         // We have a hack here to allow 64-bit Mach-O core files to have
634         // LC_THREAD commands that are only a multiple of 4 and not 8 to be
635         // allowed since the macOS kernel produces them.
636         if (getHeader().filetype != MachO::MH_CORE ||
637             Load.C.cmd != MachO::LC_THREAD || Load.C.cmdsize % 4) {
638           Err = malformedError("load command " + Twine(I) + " cmdsize not a "
639                                "multiple of 8");
640           return;
641         }
642       }
643     } else {
644       if (Load.C.cmdsize % 4 != 0) {
645         Err = malformedError("load command " + Twine(I) + " cmdsize not a "
646                              "multiple of 4");
647         return;
648       }
649     }
650     LoadCommands.push_back(Load);
651     if (Load.C.cmd == MachO::LC_SYMTAB) {
652       if ((Err = checkSymtabCommand(this, Load, I, &SymtabLoadCmd)))
653         return;
654     } else if (Load.C.cmd == MachO::LC_DYSYMTAB) {
655       if ((Err = checkDysymtabCommand(this, Load, I, &DysymtabLoadCmd)))
656         return;
657     } else if (Load.C.cmd == MachO::LC_DATA_IN_CODE) {
658       if ((Err = checkLinkeditDataCommand(this, Load, I, &DataInCodeLoadCmd,
659                                           "LC_DATA_IN_CODE")))
660         return;
661     } else if (Load.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
662       if ((Err = checkLinkeditDataCommand(this, Load, I, &LinkOptHintsLoadCmd,
663                                           "LC_LINKER_OPTIMIZATION_HINT")))
664         return;
665     } else if (Load.C.cmd == MachO::LC_DYLD_INFO) {
666       if ((Err = checkDyldInfoCommand(this, Load, I, &DyldInfoLoadCmd,
667                                       "LC_DYLD_INFO")))
668         return;
669     } else if (Load.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
670       if ((Err = checkDyldInfoCommand(this, Load, I, &DyldInfoLoadCmd,
671                                       "LC_DYLD_INFO_ONLY")))
672         return;
673     } else if (Load.C.cmd == MachO::LC_UUID) {
674       // Multiple UUID load commands
675       if (UuidLoadCmd) {
676         Err = malformedError("Multiple UUID load commands");
677         return;
678       }
679       UuidLoadCmd = Load.Ptr;
680     } else if (Load.C.cmd == MachO::LC_SEGMENT_64) {
681       if ((Err = parseSegmentLoadCommand<MachO::segment_command_64,
682                                          MachO::section_64>(
683                    this, Load, Sections, HasPageZeroSegment, I,
684                    "LC_SEGMENT_64", SizeOfHeaders)))
685         return;
686     } else if (Load.C.cmd == MachO::LC_SEGMENT) {
687       if ((Err = parseSegmentLoadCommand<MachO::segment_command,
688                                          MachO::section>(
689                    this, Load, Sections, HasPageZeroSegment, I,
690                    "LC_SEGMENT", SizeOfHeaders)))
691         return;
692     } else if (Load.C.cmd == MachO::LC_LOAD_DYLIB ||
693                Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
694                Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
695                Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
696                Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
697       Libraries.push_back(Load.Ptr);
698     }
699     if (I < LoadCommandCount - 1) {
700       if (auto LoadOrErr = getNextLoadCommandInfo(this, I, Load))
701         Load = *LoadOrErr;
702       else {
703         Err = LoadOrErr.takeError();
704         return;
705       }
706     }
707   }
708   if (!SymtabLoadCmd) {
709     if (DysymtabLoadCmd) {
710       Err = malformedError("contains LC_DYSYMTAB load command without a "
711                            "LC_SYMTAB load command");
712       return;
713     }
714   } else if (DysymtabLoadCmd) {
715     MachO::symtab_command Symtab =
716       getStruct<MachO::symtab_command>(this, SymtabLoadCmd);
717     MachO::dysymtab_command Dysymtab =
718       getStruct<MachO::dysymtab_command>(this, DysymtabLoadCmd);
719     if (Dysymtab.nlocalsym != 0 && Dysymtab.ilocalsym > Symtab.nsyms) {
720       Err = malformedError("ilocalsym in LC_DYSYMTAB load command "
721                            "extends past the end of the symbol table");
722       return;
723     }
724     uint64_t BigSize = Dysymtab.ilocalsym;
725     BigSize += Dysymtab.nlocalsym;
726     if (Dysymtab.nlocalsym != 0 && BigSize > Symtab.nsyms) {
727       Err = malformedError("ilocalsym plus nlocalsym in LC_DYSYMTAB load "
728                            "command extends past the end of the symbol table");
729       return;
730     }
731     if (Dysymtab.nextdefsym != 0 && Dysymtab.ilocalsym > Symtab.nsyms) {
732       Err = malformedError("nextdefsym in LC_DYSYMTAB load command "
733                            "extends past the end of the symbol table");
734       return;
735     }
736     BigSize = Dysymtab.iextdefsym;
737     BigSize += Dysymtab.nextdefsym;
738     if (Dysymtab.nextdefsym != 0 && BigSize > Symtab.nsyms) {
739       Err = malformedError("iextdefsym plus nextdefsym in LC_DYSYMTAB "
740                            "load command extends past the end of the symbol "
741                            "table");
742       return;
743     }
744     if (Dysymtab.nundefsym != 0 && Dysymtab.iundefsym > Symtab.nsyms) {
745       Err = malformedError("nundefsym in LC_DYSYMTAB load command "
746                            "extends past the end of the symbol table");
747       return;
748     }
749     BigSize = Dysymtab.iundefsym;
750     BigSize += Dysymtab.nundefsym;
751     if (Dysymtab.nundefsym != 0 && BigSize > Symtab.nsyms) {
752       Err = malformedError("iundefsym plus nundefsym in LC_DYSYMTAB load "
753                            " command extends past the end of the symbol table");
754       return;
755     }
756   }
757   assert(LoadCommands.size() == LoadCommandCount);
758 
759   Err = Error::success();
760 }
761 
762 void MachOObjectFile::moveSymbolNext(DataRefImpl &Symb) const {
763   unsigned SymbolTableEntrySize = is64Bit() ?
764     sizeof(MachO::nlist_64) :
765     sizeof(MachO::nlist);
766   Symb.p += SymbolTableEntrySize;
767 }
768 
769 Expected<StringRef> MachOObjectFile::getSymbolName(DataRefImpl Symb) const {
770   StringRef StringTable = getStringTableData();
771   MachO::nlist_base Entry = getSymbolTableEntryBase(this, Symb);
772   const char *Start = &StringTable.data()[Entry.n_strx];
773   if (Start < getData().begin() || Start >= getData().end()) {
774     return malformedError("bad string index: " + Twine(Entry.n_strx) +
775                           " for symbol at index " + Twine(getSymbolIndex(Symb)));
776   }
777   return StringRef(Start);
778 }
779 
780 unsigned MachOObjectFile::getSectionType(SectionRef Sec) const {
781   DataRefImpl DRI = Sec.getRawDataRefImpl();
782   uint32_t Flags = getSectionFlags(this, DRI);
783   return Flags & MachO::SECTION_TYPE;
784 }
785 
786 uint64_t MachOObjectFile::getNValue(DataRefImpl Sym) const {
787   if (is64Bit()) {
788     MachO::nlist_64 Entry = getSymbol64TableEntry(Sym);
789     return Entry.n_value;
790   }
791   MachO::nlist Entry = getSymbolTableEntry(Sym);
792   return Entry.n_value;
793 }
794 
795 // getIndirectName() returns the name of the alias'ed symbol who's string table
796 // index is in the n_value field.
797 std::error_code MachOObjectFile::getIndirectName(DataRefImpl Symb,
798                                                  StringRef &Res) const {
799   StringRef StringTable = getStringTableData();
800   MachO::nlist_base Entry = getSymbolTableEntryBase(this, Symb);
801   if ((Entry.n_type & MachO::N_TYPE) != MachO::N_INDR)
802     return object_error::parse_failed;
803   uint64_t NValue = getNValue(Symb);
804   if (NValue >= StringTable.size())
805     return object_error::parse_failed;
806   const char *Start = &StringTable.data()[NValue];
807   Res = StringRef(Start);
808   return std::error_code();
809 }
810 
811 uint64_t MachOObjectFile::getSymbolValueImpl(DataRefImpl Sym) const {
812   return getNValue(Sym);
813 }
814 
815 Expected<uint64_t> MachOObjectFile::getSymbolAddress(DataRefImpl Sym) const {
816   return getSymbolValue(Sym);
817 }
818 
819 uint32_t MachOObjectFile::getSymbolAlignment(DataRefImpl DRI) const {
820   uint32_t flags = getSymbolFlags(DRI);
821   if (flags & SymbolRef::SF_Common) {
822     MachO::nlist_base Entry = getSymbolTableEntryBase(this, DRI);
823     return 1 << MachO::GET_COMM_ALIGN(Entry.n_desc);
824   }
825   return 0;
826 }
827 
828 uint64_t MachOObjectFile::getCommonSymbolSizeImpl(DataRefImpl DRI) const {
829   return getNValue(DRI);
830 }
831 
832 Expected<SymbolRef::Type>
833 MachOObjectFile::getSymbolType(DataRefImpl Symb) const {
834   MachO::nlist_base Entry = getSymbolTableEntryBase(this, Symb);
835   uint8_t n_type = Entry.n_type;
836 
837   // If this is a STAB debugging symbol, we can do nothing more.
838   if (n_type & MachO::N_STAB)
839     return SymbolRef::ST_Debug;
840 
841   switch (n_type & MachO::N_TYPE) {
842     case MachO::N_UNDF :
843       return SymbolRef::ST_Unknown;
844     case MachO::N_SECT :
845       Expected<section_iterator> SecOrError = getSymbolSection(Symb);
846       if (!SecOrError)
847         return SecOrError.takeError();
848       section_iterator Sec = *SecOrError;
849       if (Sec->isData() || Sec->isBSS())
850         return SymbolRef::ST_Data;
851       return SymbolRef::ST_Function;
852   }
853   return SymbolRef::ST_Other;
854 }
855 
856 uint32_t MachOObjectFile::getSymbolFlags(DataRefImpl DRI) const {
857   MachO::nlist_base Entry = getSymbolTableEntryBase(this, DRI);
858 
859   uint8_t MachOType = Entry.n_type;
860   uint16_t MachOFlags = Entry.n_desc;
861 
862   uint32_t Result = SymbolRef::SF_None;
863 
864   if ((MachOType & MachO::N_TYPE) == MachO::N_INDR)
865     Result |= SymbolRef::SF_Indirect;
866 
867   if (MachOType & MachO::N_STAB)
868     Result |= SymbolRef::SF_FormatSpecific;
869 
870   if (MachOType & MachO::N_EXT) {
871     Result |= SymbolRef::SF_Global;
872     if ((MachOType & MachO::N_TYPE) == MachO::N_UNDF) {
873       if (getNValue(DRI))
874         Result |= SymbolRef::SF_Common;
875       else
876         Result |= SymbolRef::SF_Undefined;
877     }
878 
879     if (!(MachOType & MachO::N_PEXT))
880       Result |= SymbolRef::SF_Exported;
881   }
882 
883   if (MachOFlags & (MachO::N_WEAK_REF | MachO::N_WEAK_DEF))
884     Result |= SymbolRef::SF_Weak;
885 
886   if (MachOFlags & (MachO::N_ARM_THUMB_DEF))
887     Result |= SymbolRef::SF_Thumb;
888 
889   if ((MachOType & MachO::N_TYPE) == MachO::N_ABS)
890     Result |= SymbolRef::SF_Absolute;
891 
892   return Result;
893 }
894 
895 Expected<section_iterator>
896 MachOObjectFile::getSymbolSection(DataRefImpl Symb) const {
897   MachO::nlist_base Entry = getSymbolTableEntryBase(this, Symb);
898   uint8_t index = Entry.n_sect;
899 
900   if (index == 0)
901     return section_end();
902   DataRefImpl DRI;
903   DRI.d.a = index - 1;
904   if (DRI.d.a >= Sections.size()){
905     return malformedError("bad section index: " + Twine((int)index) +
906                           " for symbol at index " + Twine(getSymbolIndex(Symb)));
907   }
908   return section_iterator(SectionRef(DRI, this));
909 }
910 
911 unsigned MachOObjectFile::getSymbolSectionID(SymbolRef Sym) const {
912   MachO::nlist_base Entry =
913       getSymbolTableEntryBase(this, Sym.getRawDataRefImpl());
914   return Entry.n_sect - 1;
915 }
916 
917 void MachOObjectFile::moveSectionNext(DataRefImpl &Sec) const {
918   Sec.d.a++;
919 }
920 
921 std::error_code MachOObjectFile::getSectionName(DataRefImpl Sec,
922                                                 StringRef &Result) const {
923   ArrayRef<char> Raw = getSectionRawName(Sec);
924   Result = parseSegmentOrSectionName(Raw.data());
925   return std::error_code();
926 }
927 
928 uint64_t MachOObjectFile::getSectionAddress(DataRefImpl Sec) const {
929   if (is64Bit())
930     return getSection64(Sec).addr;
931   return getSection(Sec).addr;
932 }
933 
934 uint64_t MachOObjectFile::getSectionSize(DataRefImpl Sec) const {
935   // In the case if a malformed Mach-O file where the section offset is past
936   // the end of the file or some part of the section size is past the end of
937   // the file return a size of zero or a size that covers the rest of the file
938   // but does not extend past the end of the file.
939   uint32_t SectOffset, SectType;
940   uint64_t SectSize;
941 
942   if (is64Bit()) {
943     MachO::section_64 Sect = getSection64(Sec);
944     SectOffset = Sect.offset;
945     SectSize = Sect.size;
946     SectType = Sect.flags & MachO::SECTION_TYPE;
947   } else {
948     MachO::section Sect = getSection(Sec);
949     SectOffset = Sect.offset;
950     SectSize = Sect.size;
951     SectType = Sect.flags & MachO::SECTION_TYPE;
952   }
953   if (SectType == MachO::S_ZEROFILL || SectType == MachO::S_GB_ZEROFILL)
954     return SectSize;
955   uint64_t FileSize = getData().size();
956   if (SectOffset > FileSize)
957     return 0;
958   if (FileSize - SectOffset < SectSize)
959     return FileSize - SectOffset;
960   return SectSize;
961 }
962 
963 std::error_code MachOObjectFile::getSectionContents(DataRefImpl Sec,
964                                                     StringRef &Res) const {
965   uint32_t Offset;
966   uint64_t Size;
967 
968   if (is64Bit()) {
969     MachO::section_64 Sect = getSection64(Sec);
970     Offset = Sect.offset;
971     Size = Sect.size;
972   } else {
973     MachO::section Sect = getSection(Sec);
974     Offset = Sect.offset;
975     Size = Sect.size;
976   }
977 
978   Res = this->getData().substr(Offset, Size);
979   return std::error_code();
980 }
981 
982 uint64_t MachOObjectFile::getSectionAlignment(DataRefImpl Sec) const {
983   uint32_t Align;
984   if (is64Bit()) {
985     MachO::section_64 Sect = getSection64(Sec);
986     Align = Sect.align;
987   } else {
988     MachO::section Sect = getSection(Sec);
989     Align = Sect.align;
990   }
991 
992   return uint64_t(1) << Align;
993 }
994 
995 bool MachOObjectFile::isSectionCompressed(DataRefImpl Sec) const {
996   return false;
997 }
998 
999 bool MachOObjectFile::isSectionText(DataRefImpl Sec) const {
1000   uint32_t Flags = getSectionFlags(this, Sec);
1001   return Flags & MachO::S_ATTR_PURE_INSTRUCTIONS;
1002 }
1003 
1004 bool MachOObjectFile::isSectionData(DataRefImpl Sec) const {
1005   uint32_t Flags = getSectionFlags(this, Sec);
1006   unsigned SectionType = Flags & MachO::SECTION_TYPE;
1007   return !(Flags & MachO::S_ATTR_PURE_INSTRUCTIONS) &&
1008          !(SectionType == MachO::S_ZEROFILL ||
1009            SectionType == MachO::S_GB_ZEROFILL);
1010 }
1011 
1012 bool MachOObjectFile::isSectionBSS(DataRefImpl Sec) const {
1013   uint32_t Flags = getSectionFlags(this, Sec);
1014   unsigned SectionType = Flags & MachO::SECTION_TYPE;
1015   return !(Flags & MachO::S_ATTR_PURE_INSTRUCTIONS) &&
1016          (SectionType == MachO::S_ZEROFILL ||
1017           SectionType == MachO::S_GB_ZEROFILL);
1018 }
1019 
1020 unsigned MachOObjectFile::getSectionID(SectionRef Sec) const {
1021   return Sec.getRawDataRefImpl().d.a;
1022 }
1023 
1024 bool MachOObjectFile::isSectionVirtual(DataRefImpl Sec) const {
1025   // FIXME: Unimplemented.
1026   return false;
1027 }
1028 
1029 bool MachOObjectFile::isSectionBitcode(DataRefImpl Sec) const {
1030   StringRef SegmentName = getSectionFinalSegmentName(Sec);
1031   StringRef SectName;
1032   if (!getSectionName(Sec, SectName))
1033     return (SegmentName == "__LLVM" && SectName == "__bitcode");
1034   return false;
1035 }
1036 
1037 relocation_iterator MachOObjectFile::section_rel_begin(DataRefImpl Sec) const {
1038   DataRefImpl Ret;
1039   Ret.d.a = Sec.d.a;
1040   Ret.d.b = 0;
1041   return relocation_iterator(RelocationRef(Ret, this));
1042 }
1043 
1044 relocation_iterator
1045 MachOObjectFile::section_rel_end(DataRefImpl Sec) const {
1046   uint32_t Num;
1047   if (is64Bit()) {
1048     MachO::section_64 Sect = getSection64(Sec);
1049     Num = Sect.nreloc;
1050   } else {
1051     MachO::section Sect = getSection(Sec);
1052     Num = Sect.nreloc;
1053   }
1054 
1055   DataRefImpl Ret;
1056   Ret.d.a = Sec.d.a;
1057   Ret.d.b = Num;
1058   return relocation_iterator(RelocationRef(Ret, this));
1059 }
1060 
1061 void MachOObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
1062   ++Rel.d.b;
1063 }
1064 
1065 uint64_t MachOObjectFile::getRelocationOffset(DataRefImpl Rel) const {
1066   assert(getHeader().filetype == MachO::MH_OBJECT &&
1067          "Only implemented for MH_OBJECT");
1068   MachO::any_relocation_info RE = getRelocation(Rel);
1069   return getAnyRelocationAddress(RE);
1070 }
1071 
1072 symbol_iterator
1073 MachOObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
1074   MachO::any_relocation_info RE = getRelocation(Rel);
1075   if (isRelocationScattered(RE))
1076     return symbol_end();
1077 
1078   uint32_t SymbolIdx = getPlainRelocationSymbolNum(RE);
1079   bool isExtern = getPlainRelocationExternal(RE);
1080   if (!isExtern)
1081     return symbol_end();
1082 
1083   MachO::symtab_command S = getSymtabLoadCommand();
1084   unsigned SymbolTableEntrySize = is64Bit() ?
1085     sizeof(MachO::nlist_64) :
1086     sizeof(MachO::nlist);
1087   uint64_t Offset = S.symoff + SymbolIdx * SymbolTableEntrySize;
1088   DataRefImpl Sym;
1089   Sym.p = reinterpret_cast<uintptr_t>(getPtr(this, Offset));
1090   return symbol_iterator(SymbolRef(Sym, this));
1091 }
1092 
1093 section_iterator
1094 MachOObjectFile::getRelocationSection(DataRefImpl Rel) const {
1095   return section_iterator(getAnyRelocationSection(getRelocation(Rel)));
1096 }
1097 
1098 uint64_t MachOObjectFile::getRelocationType(DataRefImpl Rel) const {
1099   MachO::any_relocation_info RE = getRelocation(Rel);
1100   return getAnyRelocationType(RE);
1101 }
1102 
1103 void MachOObjectFile::getRelocationTypeName(
1104     DataRefImpl Rel, SmallVectorImpl<char> &Result) const {
1105   StringRef res;
1106   uint64_t RType = getRelocationType(Rel);
1107 
1108   unsigned Arch = this->getArch();
1109 
1110   switch (Arch) {
1111     case Triple::x86: {
1112       static const char *const Table[] =  {
1113         "GENERIC_RELOC_VANILLA",
1114         "GENERIC_RELOC_PAIR",
1115         "GENERIC_RELOC_SECTDIFF",
1116         "GENERIC_RELOC_PB_LA_PTR",
1117         "GENERIC_RELOC_LOCAL_SECTDIFF",
1118         "GENERIC_RELOC_TLV" };
1119 
1120       if (RType > 5)
1121         res = "Unknown";
1122       else
1123         res = Table[RType];
1124       break;
1125     }
1126     case Triple::x86_64: {
1127       static const char *const Table[] =  {
1128         "X86_64_RELOC_UNSIGNED",
1129         "X86_64_RELOC_SIGNED",
1130         "X86_64_RELOC_BRANCH",
1131         "X86_64_RELOC_GOT_LOAD",
1132         "X86_64_RELOC_GOT",
1133         "X86_64_RELOC_SUBTRACTOR",
1134         "X86_64_RELOC_SIGNED_1",
1135         "X86_64_RELOC_SIGNED_2",
1136         "X86_64_RELOC_SIGNED_4",
1137         "X86_64_RELOC_TLV" };
1138 
1139       if (RType > 9)
1140         res = "Unknown";
1141       else
1142         res = Table[RType];
1143       break;
1144     }
1145     case Triple::arm: {
1146       static const char *const Table[] =  {
1147         "ARM_RELOC_VANILLA",
1148         "ARM_RELOC_PAIR",
1149         "ARM_RELOC_SECTDIFF",
1150         "ARM_RELOC_LOCAL_SECTDIFF",
1151         "ARM_RELOC_PB_LA_PTR",
1152         "ARM_RELOC_BR24",
1153         "ARM_THUMB_RELOC_BR22",
1154         "ARM_THUMB_32BIT_BRANCH",
1155         "ARM_RELOC_HALF",
1156         "ARM_RELOC_HALF_SECTDIFF" };
1157 
1158       if (RType > 9)
1159         res = "Unknown";
1160       else
1161         res = Table[RType];
1162       break;
1163     }
1164     case Triple::aarch64: {
1165       static const char *const Table[] = {
1166         "ARM64_RELOC_UNSIGNED",           "ARM64_RELOC_SUBTRACTOR",
1167         "ARM64_RELOC_BRANCH26",           "ARM64_RELOC_PAGE21",
1168         "ARM64_RELOC_PAGEOFF12",          "ARM64_RELOC_GOT_LOAD_PAGE21",
1169         "ARM64_RELOC_GOT_LOAD_PAGEOFF12", "ARM64_RELOC_POINTER_TO_GOT",
1170         "ARM64_RELOC_TLVP_LOAD_PAGE21",   "ARM64_RELOC_TLVP_LOAD_PAGEOFF12",
1171         "ARM64_RELOC_ADDEND"
1172       };
1173 
1174       if (RType >= array_lengthof(Table))
1175         res = "Unknown";
1176       else
1177         res = Table[RType];
1178       break;
1179     }
1180     case Triple::ppc: {
1181       static const char *const Table[] =  {
1182         "PPC_RELOC_VANILLA",
1183         "PPC_RELOC_PAIR",
1184         "PPC_RELOC_BR14",
1185         "PPC_RELOC_BR24",
1186         "PPC_RELOC_HI16",
1187         "PPC_RELOC_LO16",
1188         "PPC_RELOC_HA16",
1189         "PPC_RELOC_LO14",
1190         "PPC_RELOC_SECTDIFF",
1191         "PPC_RELOC_PB_LA_PTR",
1192         "PPC_RELOC_HI16_SECTDIFF",
1193         "PPC_RELOC_LO16_SECTDIFF",
1194         "PPC_RELOC_HA16_SECTDIFF",
1195         "PPC_RELOC_JBSR",
1196         "PPC_RELOC_LO14_SECTDIFF",
1197         "PPC_RELOC_LOCAL_SECTDIFF" };
1198 
1199       if (RType > 15)
1200         res = "Unknown";
1201       else
1202         res = Table[RType];
1203       break;
1204     }
1205     case Triple::UnknownArch:
1206       res = "Unknown";
1207       break;
1208   }
1209   Result.append(res.begin(), res.end());
1210 }
1211 
1212 uint8_t MachOObjectFile::getRelocationLength(DataRefImpl Rel) const {
1213   MachO::any_relocation_info RE = getRelocation(Rel);
1214   return getAnyRelocationLength(RE);
1215 }
1216 
1217 //
1218 // guessLibraryShortName() is passed a name of a dynamic library and returns a
1219 // guess on what the short name is.  Then name is returned as a substring of the
1220 // StringRef Name passed in.  The name of the dynamic library is recognized as
1221 // a framework if it has one of the two following forms:
1222 //      Foo.framework/Versions/A/Foo
1223 //      Foo.framework/Foo
1224 // Where A and Foo can be any string.  And may contain a trailing suffix
1225 // starting with an underbar.  If the Name is recognized as a framework then
1226 // isFramework is set to true else it is set to false.  If the Name has a
1227 // suffix then Suffix is set to the substring in Name that contains the suffix
1228 // else it is set to a NULL StringRef.
1229 //
1230 // The Name of the dynamic library is recognized as a library name if it has
1231 // one of the two following forms:
1232 //      libFoo.A.dylib
1233 //      libFoo.dylib
1234 // The library may have a suffix trailing the name Foo of the form:
1235 //      libFoo_profile.A.dylib
1236 //      libFoo_profile.dylib
1237 //
1238 // The Name of the dynamic library is also recognized as a library name if it
1239 // has the following form:
1240 //      Foo.qtx
1241 //
1242 // If the Name of the dynamic library is none of the forms above then a NULL
1243 // StringRef is returned.
1244 //
1245 StringRef MachOObjectFile::guessLibraryShortName(StringRef Name,
1246                                                  bool &isFramework,
1247                                                  StringRef &Suffix) {
1248   StringRef Foo, F, DotFramework, V, Dylib, Lib, Dot, Qtx;
1249   size_t a, b, c, d, Idx;
1250 
1251   isFramework = false;
1252   Suffix = StringRef();
1253 
1254   // Pull off the last component and make Foo point to it
1255   a = Name.rfind('/');
1256   if (a == Name.npos || a == 0)
1257     goto guess_library;
1258   Foo = Name.slice(a+1, Name.npos);
1259 
1260   // Look for a suffix starting with a '_'
1261   Idx = Foo.rfind('_');
1262   if (Idx != Foo.npos && Foo.size() >= 2) {
1263     Suffix = Foo.slice(Idx, Foo.npos);
1264     Foo = Foo.slice(0, Idx);
1265   }
1266 
1267   // First look for the form Foo.framework/Foo
1268   b = Name.rfind('/', a);
1269   if (b == Name.npos)
1270     Idx = 0;
1271   else
1272     Idx = b+1;
1273   F = Name.slice(Idx, Idx + Foo.size());
1274   DotFramework = Name.slice(Idx + Foo.size(),
1275                             Idx + Foo.size() + sizeof(".framework/")-1);
1276   if (F == Foo && DotFramework == ".framework/") {
1277     isFramework = true;
1278     return Foo;
1279   }
1280 
1281   // Next look for the form Foo.framework/Versions/A/Foo
1282   if (b == Name.npos)
1283     goto guess_library;
1284   c =  Name.rfind('/', b);
1285   if (c == Name.npos || c == 0)
1286     goto guess_library;
1287   V = Name.slice(c+1, Name.npos);
1288   if (!V.startswith("Versions/"))
1289     goto guess_library;
1290   d =  Name.rfind('/', c);
1291   if (d == Name.npos)
1292     Idx = 0;
1293   else
1294     Idx = d+1;
1295   F = Name.slice(Idx, Idx + Foo.size());
1296   DotFramework = Name.slice(Idx + Foo.size(),
1297                             Idx + Foo.size() + sizeof(".framework/")-1);
1298   if (F == Foo && DotFramework == ".framework/") {
1299     isFramework = true;
1300     return Foo;
1301   }
1302 
1303 guess_library:
1304   // pull off the suffix after the "." and make a point to it
1305   a = Name.rfind('.');
1306   if (a == Name.npos || a == 0)
1307     return StringRef();
1308   Dylib = Name.slice(a, Name.npos);
1309   if (Dylib != ".dylib")
1310     goto guess_qtx;
1311 
1312   // First pull off the version letter for the form Foo.A.dylib if any.
1313   if (a >= 3) {
1314     Dot = Name.slice(a-2, a-1);
1315     if (Dot == ".")
1316       a = a - 2;
1317   }
1318 
1319   b = Name.rfind('/', a);
1320   if (b == Name.npos)
1321     b = 0;
1322   else
1323     b = b+1;
1324   // ignore any suffix after an underbar like Foo_profile.A.dylib
1325   Idx = Name.find('_', b);
1326   if (Idx != Name.npos && Idx != b) {
1327     Lib = Name.slice(b, Idx);
1328     Suffix = Name.slice(Idx, a);
1329   }
1330   else
1331     Lib = Name.slice(b, a);
1332   // There are incorrect library names of the form:
1333   // libATS.A_profile.dylib so check for these.
1334   if (Lib.size() >= 3) {
1335     Dot = Lib.slice(Lib.size()-2, Lib.size()-1);
1336     if (Dot == ".")
1337       Lib = Lib.slice(0, Lib.size()-2);
1338   }
1339   return Lib;
1340 
1341 guess_qtx:
1342   Qtx = Name.slice(a, Name.npos);
1343   if (Qtx != ".qtx")
1344     return StringRef();
1345   b = Name.rfind('/', a);
1346   if (b == Name.npos)
1347     Lib = Name.slice(0, a);
1348   else
1349     Lib = Name.slice(b+1, a);
1350   // There are library names of the form: QT.A.qtx so check for these.
1351   if (Lib.size() >= 3) {
1352     Dot = Lib.slice(Lib.size()-2, Lib.size()-1);
1353     if (Dot == ".")
1354       Lib = Lib.slice(0, Lib.size()-2);
1355   }
1356   return Lib;
1357 }
1358 
1359 // getLibraryShortNameByIndex() is used to get the short name of the library
1360 // for an undefined symbol in a linked Mach-O binary that was linked with the
1361 // normal two-level namespace default (that is MH_TWOLEVEL in the header).
1362 // It is passed the index (0 - based) of the library as translated from
1363 // GET_LIBRARY_ORDINAL (1 - based).
1364 std::error_code MachOObjectFile::getLibraryShortNameByIndex(unsigned Index,
1365                                                          StringRef &Res) const {
1366   if (Index >= Libraries.size())
1367     return object_error::parse_failed;
1368 
1369   // If the cache of LibrariesShortNames is not built up do that first for
1370   // all the Libraries.
1371   if (LibrariesShortNames.size() == 0) {
1372     for (unsigned i = 0; i < Libraries.size(); i++) {
1373       MachO::dylib_command D =
1374         getStruct<MachO::dylib_command>(this, Libraries[i]);
1375       if (D.dylib.name >= D.cmdsize)
1376         return object_error::parse_failed;
1377       const char *P = (const char *)(Libraries[i]) + D.dylib.name;
1378       StringRef Name = StringRef(P);
1379       if (D.dylib.name+Name.size() >= D.cmdsize)
1380         return object_error::parse_failed;
1381       StringRef Suffix;
1382       bool isFramework;
1383       StringRef shortName = guessLibraryShortName(Name, isFramework, Suffix);
1384       if (shortName.empty())
1385         LibrariesShortNames.push_back(Name);
1386       else
1387         LibrariesShortNames.push_back(shortName);
1388     }
1389   }
1390 
1391   Res = LibrariesShortNames[Index];
1392   return std::error_code();
1393 }
1394 
1395 section_iterator
1396 MachOObjectFile::getRelocationRelocatedSection(relocation_iterator Rel) const {
1397   DataRefImpl Sec;
1398   Sec.d.a = Rel->getRawDataRefImpl().d.a;
1399   return section_iterator(SectionRef(Sec, this));
1400 }
1401 
1402 basic_symbol_iterator MachOObjectFile::symbol_begin_impl() const {
1403   DataRefImpl DRI;
1404   MachO::symtab_command Symtab = getSymtabLoadCommand();
1405   if (!SymtabLoadCmd || Symtab.nsyms == 0)
1406     return basic_symbol_iterator(SymbolRef(DRI, this));
1407 
1408   return getSymbolByIndex(0);
1409 }
1410 
1411 basic_symbol_iterator MachOObjectFile::symbol_end_impl() const {
1412   DataRefImpl DRI;
1413   MachO::symtab_command Symtab = getSymtabLoadCommand();
1414   if (!SymtabLoadCmd || Symtab.nsyms == 0)
1415     return basic_symbol_iterator(SymbolRef(DRI, this));
1416 
1417   unsigned SymbolTableEntrySize = is64Bit() ?
1418     sizeof(MachO::nlist_64) :
1419     sizeof(MachO::nlist);
1420   unsigned Offset = Symtab.symoff +
1421     Symtab.nsyms * SymbolTableEntrySize;
1422   DRI.p = reinterpret_cast<uintptr_t>(getPtr(this, Offset));
1423   return basic_symbol_iterator(SymbolRef(DRI, this));
1424 }
1425 
1426 basic_symbol_iterator MachOObjectFile::getSymbolByIndex(unsigned Index) const {
1427   MachO::symtab_command Symtab = getSymtabLoadCommand();
1428   if (!SymtabLoadCmd || Index >= Symtab.nsyms)
1429     report_fatal_error("Requested symbol index is out of range.");
1430   unsigned SymbolTableEntrySize =
1431     is64Bit() ? sizeof(MachO::nlist_64) : sizeof(MachO::nlist);
1432   DataRefImpl DRI;
1433   DRI.p = reinterpret_cast<uintptr_t>(getPtr(this, Symtab.symoff));
1434   DRI.p += Index * SymbolTableEntrySize;
1435   return basic_symbol_iterator(SymbolRef(DRI, this));
1436 }
1437 
1438 uint64_t MachOObjectFile::getSymbolIndex(DataRefImpl Symb) const {
1439   MachO::symtab_command Symtab = getSymtabLoadCommand();
1440   if (!SymtabLoadCmd)
1441     report_fatal_error("getSymbolIndex() called with no symbol table symbol");
1442   unsigned SymbolTableEntrySize =
1443     is64Bit() ? sizeof(MachO::nlist_64) : sizeof(MachO::nlist);
1444   DataRefImpl DRIstart;
1445   DRIstart.p = reinterpret_cast<uintptr_t>(getPtr(this, Symtab.symoff));
1446   uint64_t Index = (Symb.p - DRIstart.p) / SymbolTableEntrySize;
1447   return Index;
1448 }
1449 
1450 section_iterator MachOObjectFile::section_begin() const {
1451   DataRefImpl DRI;
1452   return section_iterator(SectionRef(DRI, this));
1453 }
1454 
1455 section_iterator MachOObjectFile::section_end() const {
1456   DataRefImpl DRI;
1457   DRI.d.a = Sections.size();
1458   return section_iterator(SectionRef(DRI, this));
1459 }
1460 
1461 uint8_t MachOObjectFile::getBytesInAddress() const {
1462   return is64Bit() ? 8 : 4;
1463 }
1464 
1465 StringRef MachOObjectFile::getFileFormatName() const {
1466   unsigned CPUType = getCPUType(this);
1467   if (!is64Bit()) {
1468     switch (CPUType) {
1469     case llvm::MachO::CPU_TYPE_I386:
1470       return "Mach-O 32-bit i386";
1471     case llvm::MachO::CPU_TYPE_ARM:
1472       return "Mach-O arm";
1473     case llvm::MachO::CPU_TYPE_POWERPC:
1474       return "Mach-O 32-bit ppc";
1475     default:
1476       return "Mach-O 32-bit unknown";
1477     }
1478   }
1479 
1480   switch (CPUType) {
1481   case llvm::MachO::CPU_TYPE_X86_64:
1482     return "Mach-O 64-bit x86-64";
1483   case llvm::MachO::CPU_TYPE_ARM64:
1484     return "Mach-O arm64";
1485   case llvm::MachO::CPU_TYPE_POWERPC64:
1486     return "Mach-O 64-bit ppc64";
1487   default:
1488     return "Mach-O 64-bit unknown";
1489   }
1490 }
1491 
1492 Triple::ArchType MachOObjectFile::getArch(uint32_t CPUType) {
1493   switch (CPUType) {
1494   case llvm::MachO::CPU_TYPE_I386:
1495     return Triple::x86;
1496   case llvm::MachO::CPU_TYPE_X86_64:
1497     return Triple::x86_64;
1498   case llvm::MachO::CPU_TYPE_ARM:
1499     return Triple::arm;
1500   case llvm::MachO::CPU_TYPE_ARM64:
1501     return Triple::aarch64;
1502   case llvm::MachO::CPU_TYPE_POWERPC:
1503     return Triple::ppc;
1504   case llvm::MachO::CPU_TYPE_POWERPC64:
1505     return Triple::ppc64;
1506   default:
1507     return Triple::UnknownArch;
1508   }
1509 }
1510 
1511 Triple MachOObjectFile::getArchTriple(uint32_t CPUType, uint32_t CPUSubType,
1512                                       const char **McpuDefault) {
1513   if (McpuDefault)
1514     *McpuDefault = nullptr;
1515 
1516   switch (CPUType) {
1517   case MachO::CPU_TYPE_I386:
1518     switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
1519     case MachO::CPU_SUBTYPE_I386_ALL:
1520       return Triple("i386-apple-darwin");
1521     default:
1522       return Triple();
1523     }
1524   case MachO::CPU_TYPE_X86_64:
1525     switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
1526     case MachO::CPU_SUBTYPE_X86_64_ALL:
1527       return Triple("x86_64-apple-darwin");
1528     case MachO::CPU_SUBTYPE_X86_64_H:
1529       return Triple("x86_64h-apple-darwin");
1530     default:
1531       return Triple();
1532     }
1533   case MachO::CPU_TYPE_ARM:
1534     switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
1535     case MachO::CPU_SUBTYPE_ARM_V4T:
1536       return Triple("armv4t-apple-darwin");
1537     case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1538       return Triple("armv5e-apple-darwin");
1539     case MachO::CPU_SUBTYPE_ARM_XSCALE:
1540       return Triple("xscale-apple-darwin");
1541     case MachO::CPU_SUBTYPE_ARM_V6:
1542       return Triple("armv6-apple-darwin");
1543     case MachO::CPU_SUBTYPE_ARM_V6M:
1544       if (McpuDefault)
1545         *McpuDefault = "cortex-m0";
1546       return Triple("armv6m-apple-darwin");
1547     case MachO::CPU_SUBTYPE_ARM_V7:
1548       return Triple("armv7-apple-darwin");
1549     case MachO::CPU_SUBTYPE_ARM_V7EM:
1550       if (McpuDefault)
1551         *McpuDefault = "cortex-m4";
1552       return Triple("thumbv7em-apple-darwin");
1553     case MachO::CPU_SUBTYPE_ARM_V7K:
1554       return Triple("armv7k-apple-darwin");
1555     case MachO::CPU_SUBTYPE_ARM_V7M:
1556       if (McpuDefault)
1557         *McpuDefault = "cortex-m3";
1558       return Triple("thumbv7m-apple-darwin");
1559     case MachO::CPU_SUBTYPE_ARM_V7S:
1560       return Triple("armv7s-apple-darwin");
1561     default:
1562       return Triple();
1563     }
1564   case MachO::CPU_TYPE_ARM64:
1565     switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
1566     case MachO::CPU_SUBTYPE_ARM64_ALL:
1567       return Triple("arm64-apple-darwin");
1568     default:
1569       return Triple();
1570     }
1571   case MachO::CPU_TYPE_POWERPC:
1572     switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
1573     case MachO::CPU_SUBTYPE_POWERPC_ALL:
1574       return Triple("ppc-apple-darwin");
1575     default:
1576       return Triple();
1577     }
1578   case MachO::CPU_TYPE_POWERPC64:
1579     switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
1580     case MachO::CPU_SUBTYPE_POWERPC_ALL:
1581       return Triple("ppc64-apple-darwin");
1582     default:
1583       return Triple();
1584     }
1585   default:
1586     return Triple();
1587   }
1588 }
1589 
1590 Triple MachOObjectFile::getHostArch() {
1591   return Triple(sys::getDefaultTargetTriple());
1592 }
1593 
1594 bool MachOObjectFile::isValidArch(StringRef ArchFlag) {
1595   return StringSwitch<bool>(ArchFlag)
1596       .Case("i386", true)
1597       .Case("x86_64", true)
1598       .Case("x86_64h", true)
1599       .Case("armv4t", true)
1600       .Case("arm", true)
1601       .Case("armv5e", true)
1602       .Case("armv6", true)
1603       .Case("armv6m", true)
1604       .Case("armv7", true)
1605       .Case("armv7em", true)
1606       .Case("armv7k", true)
1607       .Case("armv7m", true)
1608       .Case("armv7s", true)
1609       .Case("arm64", true)
1610       .Case("ppc", true)
1611       .Case("ppc64", true)
1612       .Default(false);
1613 }
1614 
1615 unsigned MachOObjectFile::getArch() const {
1616   return getArch(getCPUType(this));
1617 }
1618 
1619 Triple MachOObjectFile::getArchTriple(const char **McpuDefault) const {
1620   return getArchTriple(Header.cputype, Header.cpusubtype, McpuDefault);
1621 }
1622 
1623 relocation_iterator MachOObjectFile::section_rel_begin(unsigned Index) const {
1624   DataRefImpl DRI;
1625   DRI.d.a = Index;
1626   return section_rel_begin(DRI);
1627 }
1628 
1629 relocation_iterator MachOObjectFile::section_rel_end(unsigned Index) const {
1630   DataRefImpl DRI;
1631   DRI.d.a = Index;
1632   return section_rel_end(DRI);
1633 }
1634 
1635 dice_iterator MachOObjectFile::begin_dices() const {
1636   DataRefImpl DRI;
1637   if (!DataInCodeLoadCmd)
1638     return dice_iterator(DiceRef(DRI, this));
1639 
1640   MachO::linkedit_data_command DicLC = getDataInCodeLoadCommand();
1641   DRI.p = reinterpret_cast<uintptr_t>(getPtr(this, DicLC.dataoff));
1642   return dice_iterator(DiceRef(DRI, this));
1643 }
1644 
1645 dice_iterator MachOObjectFile::end_dices() const {
1646   DataRefImpl DRI;
1647   if (!DataInCodeLoadCmd)
1648     return dice_iterator(DiceRef(DRI, this));
1649 
1650   MachO::linkedit_data_command DicLC = getDataInCodeLoadCommand();
1651   unsigned Offset = DicLC.dataoff + DicLC.datasize;
1652   DRI.p = reinterpret_cast<uintptr_t>(getPtr(this, Offset));
1653   return dice_iterator(DiceRef(DRI, this));
1654 }
1655 
1656 ExportEntry::ExportEntry(ArrayRef<uint8_t> T)
1657     : Trie(T), Malformed(false), Done(false) {}
1658 
1659 void ExportEntry::moveToFirst() {
1660   pushNode(0);
1661   pushDownUntilBottom();
1662 }
1663 
1664 void ExportEntry::moveToEnd() {
1665   Stack.clear();
1666   Done = true;
1667 }
1668 
1669 bool ExportEntry::operator==(const ExportEntry &Other) const {
1670   // Common case, one at end, other iterating from begin.
1671   if (Done || Other.Done)
1672     return (Done == Other.Done);
1673   // Not equal if different stack sizes.
1674   if (Stack.size() != Other.Stack.size())
1675     return false;
1676   // Not equal if different cumulative strings.
1677   if (!CumulativeString.equals(Other.CumulativeString))
1678     return false;
1679   // Equal if all nodes in both stacks match.
1680   for (unsigned i=0; i < Stack.size(); ++i) {
1681     if (Stack[i].Start != Other.Stack[i].Start)
1682       return false;
1683   }
1684   return true;
1685 }
1686 
1687 uint64_t ExportEntry::readULEB128(const uint8_t *&Ptr) {
1688   unsigned Count;
1689   uint64_t Result = decodeULEB128(Ptr, &Count);
1690   Ptr += Count;
1691   if (Ptr > Trie.end()) {
1692     Ptr = Trie.end();
1693     Malformed = true;
1694   }
1695   return Result;
1696 }
1697 
1698 StringRef ExportEntry::name() const {
1699   return CumulativeString;
1700 }
1701 
1702 uint64_t ExportEntry::flags() const {
1703   return Stack.back().Flags;
1704 }
1705 
1706 uint64_t ExportEntry::address() const {
1707   return Stack.back().Address;
1708 }
1709 
1710 uint64_t ExportEntry::other() const {
1711   return Stack.back().Other;
1712 }
1713 
1714 StringRef ExportEntry::otherName() const {
1715   const char* ImportName = Stack.back().ImportName;
1716   if (ImportName)
1717     return StringRef(ImportName);
1718   return StringRef();
1719 }
1720 
1721 uint32_t ExportEntry::nodeOffset() const {
1722   return Stack.back().Start - Trie.begin();
1723 }
1724 
1725 ExportEntry::NodeState::NodeState(const uint8_t *Ptr)
1726     : Start(Ptr), Current(Ptr), Flags(0), Address(0), Other(0),
1727       ImportName(nullptr), ChildCount(0), NextChildIndex(0),
1728       ParentStringLength(0), IsExportNode(false) {}
1729 
1730 void ExportEntry::pushNode(uint64_t offset) {
1731   const uint8_t *Ptr = Trie.begin() + offset;
1732   NodeState State(Ptr);
1733   uint64_t ExportInfoSize = readULEB128(State.Current);
1734   State.IsExportNode = (ExportInfoSize != 0);
1735   const uint8_t* Children = State.Current + ExportInfoSize;
1736   if (State.IsExportNode) {
1737     State.Flags = readULEB128(State.Current);
1738     if (State.Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT) {
1739       State.Address = 0;
1740       State.Other = readULEB128(State.Current); // dylib ordinal
1741       State.ImportName = reinterpret_cast<const char*>(State.Current);
1742     } else {
1743       State.Address = readULEB128(State.Current);
1744       if (State.Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER)
1745         State.Other = readULEB128(State.Current);
1746     }
1747   }
1748   State.ChildCount = *Children;
1749   State.Current = Children + 1;
1750   State.NextChildIndex = 0;
1751   State.ParentStringLength = CumulativeString.size();
1752   Stack.push_back(State);
1753 }
1754 
1755 void ExportEntry::pushDownUntilBottom() {
1756   while (Stack.back().NextChildIndex < Stack.back().ChildCount) {
1757     NodeState &Top = Stack.back();
1758     CumulativeString.resize(Top.ParentStringLength);
1759     for (;*Top.Current != 0; Top.Current++) {
1760       char C = *Top.Current;
1761       CumulativeString.push_back(C);
1762     }
1763     Top.Current += 1;
1764     uint64_t childNodeIndex = readULEB128(Top.Current);
1765     Top.NextChildIndex += 1;
1766     pushNode(childNodeIndex);
1767   }
1768   if (!Stack.back().IsExportNode) {
1769     Malformed = true;
1770     moveToEnd();
1771   }
1772 }
1773 
1774 // We have a trie data structure and need a way to walk it that is compatible
1775 // with the C++ iterator model. The solution is a non-recursive depth first
1776 // traversal where the iterator contains a stack of parent nodes along with a
1777 // string that is the accumulation of all edge strings along the parent chain
1778 // to this point.
1779 //
1780 // There is one "export" node for each exported symbol.  But because some
1781 // symbols may be a prefix of another symbol (e.g. _dup and _dup2), an export
1782 // node may have child nodes too.
1783 //
1784 // The algorithm for moveNext() is to keep moving down the leftmost unvisited
1785 // child until hitting a node with no children (which is an export node or
1786 // else the trie is malformed). On the way down, each node is pushed on the
1787 // stack ivar.  If there is no more ways down, it pops up one and tries to go
1788 // down a sibling path until a childless node is reached.
1789 void ExportEntry::moveNext() {
1790   if (Stack.empty() || !Stack.back().IsExportNode) {
1791     Malformed = true;
1792     moveToEnd();
1793     return;
1794   }
1795 
1796   Stack.pop_back();
1797   while (!Stack.empty()) {
1798     NodeState &Top = Stack.back();
1799     if (Top.NextChildIndex < Top.ChildCount) {
1800       pushDownUntilBottom();
1801       // Now at the next export node.
1802       return;
1803     } else {
1804       if (Top.IsExportNode) {
1805         // This node has no children but is itself an export node.
1806         CumulativeString.resize(Top.ParentStringLength);
1807         return;
1808       }
1809       Stack.pop_back();
1810     }
1811   }
1812   Done = true;
1813 }
1814 
1815 iterator_range<export_iterator>
1816 MachOObjectFile::exports(ArrayRef<uint8_t> Trie) {
1817   ExportEntry Start(Trie);
1818   if (Trie.size() == 0)
1819     Start.moveToEnd();
1820   else
1821     Start.moveToFirst();
1822 
1823   ExportEntry Finish(Trie);
1824   Finish.moveToEnd();
1825 
1826   return make_range(export_iterator(Start), export_iterator(Finish));
1827 }
1828 
1829 iterator_range<export_iterator> MachOObjectFile::exports() const {
1830   return exports(getDyldInfoExportsTrie());
1831 }
1832 
1833 MachORebaseEntry::MachORebaseEntry(ArrayRef<uint8_t> Bytes, bool is64Bit)
1834     : Opcodes(Bytes), Ptr(Bytes.begin()), SegmentOffset(0), SegmentIndex(0),
1835       RemainingLoopCount(0), AdvanceAmount(0), RebaseType(0),
1836       PointerSize(is64Bit ? 8 : 4), Malformed(false), Done(false) {}
1837 
1838 void MachORebaseEntry::moveToFirst() {
1839   Ptr = Opcodes.begin();
1840   moveNext();
1841 }
1842 
1843 void MachORebaseEntry::moveToEnd() {
1844   Ptr = Opcodes.end();
1845   RemainingLoopCount = 0;
1846   Done = true;
1847 }
1848 
1849 void MachORebaseEntry::moveNext() {
1850   // If in the middle of some loop, move to next rebasing in loop.
1851   SegmentOffset += AdvanceAmount;
1852   if (RemainingLoopCount) {
1853     --RemainingLoopCount;
1854     return;
1855   }
1856   if (Ptr == Opcodes.end()) {
1857     Done = true;
1858     return;
1859   }
1860   bool More = true;
1861   while (More && !Malformed) {
1862     // Parse next opcode and set up next loop.
1863     uint8_t Byte = *Ptr++;
1864     uint8_t ImmValue = Byte & MachO::REBASE_IMMEDIATE_MASK;
1865     uint8_t Opcode = Byte & MachO::REBASE_OPCODE_MASK;
1866     switch (Opcode) {
1867     case MachO::REBASE_OPCODE_DONE:
1868       More = false;
1869       Done = true;
1870       moveToEnd();
1871       DEBUG_WITH_TYPE("mach-o-rebase", llvm::dbgs() << "REBASE_OPCODE_DONE\n");
1872       break;
1873     case MachO::REBASE_OPCODE_SET_TYPE_IMM:
1874       RebaseType = ImmValue;
1875       DEBUG_WITH_TYPE(
1876           "mach-o-rebase",
1877           llvm::dbgs() << "REBASE_OPCODE_SET_TYPE_IMM: "
1878                        << "RebaseType=" << (int) RebaseType << "\n");
1879       break;
1880     case MachO::REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:
1881       SegmentIndex = ImmValue;
1882       SegmentOffset = readULEB128();
1883       DEBUG_WITH_TYPE(
1884           "mach-o-rebase",
1885           llvm::dbgs() << "REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: "
1886                        << "SegmentIndex=" << SegmentIndex << ", "
1887                        << format("SegmentOffset=0x%06X", SegmentOffset)
1888                        << "\n");
1889       break;
1890     case MachO::REBASE_OPCODE_ADD_ADDR_ULEB:
1891       SegmentOffset += readULEB128();
1892       DEBUG_WITH_TYPE("mach-o-rebase",
1893                       llvm::dbgs() << "REBASE_OPCODE_ADD_ADDR_ULEB: "
1894                                    << format("SegmentOffset=0x%06X",
1895                                              SegmentOffset) << "\n");
1896       break;
1897     case MachO::REBASE_OPCODE_ADD_ADDR_IMM_SCALED:
1898       SegmentOffset += ImmValue * PointerSize;
1899       DEBUG_WITH_TYPE("mach-o-rebase",
1900                       llvm::dbgs() << "REBASE_OPCODE_ADD_ADDR_IMM_SCALED: "
1901                                    << format("SegmentOffset=0x%06X",
1902                                              SegmentOffset) << "\n");
1903       break;
1904     case MachO::REBASE_OPCODE_DO_REBASE_IMM_TIMES:
1905       AdvanceAmount = PointerSize;
1906       RemainingLoopCount = ImmValue - 1;
1907       DEBUG_WITH_TYPE(
1908           "mach-o-rebase",
1909           llvm::dbgs() << "REBASE_OPCODE_DO_REBASE_IMM_TIMES: "
1910                        << format("SegmentOffset=0x%06X", SegmentOffset)
1911                        << ", AdvanceAmount=" << AdvanceAmount
1912                        << ", RemainingLoopCount=" << RemainingLoopCount
1913                        << "\n");
1914       return;
1915     case MachO::REBASE_OPCODE_DO_REBASE_ULEB_TIMES:
1916       AdvanceAmount = PointerSize;
1917       RemainingLoopCount = readULEB128() - 1;
1918       DEBUG_WITH_TYPE(
1919           "mach-o-rebase",
1920           llvm::dbgs() << "REBASE_OPCODE_DO_REBASE_ULEB_TIMES: "
1921                        << format("SegmentOffset=0x%06X", SegmentOffset)
1922                        << ", AdvanceAmount=" << AdvanceAmount
1923                        << ", RemainingLoopCount=" << RemainingLoopCount
1924                        << "\n");
1925       return;
1926     case MachO::REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB:
1927       AdvanceAmount = readULEB128() + PointerSize;
1928       RemainingLoopCount = 0;
1929       DEBUG_WITH_TYPE(
1930           "mach-o-rebase",
1931           llvm::dbgs() << "REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB: "
1932                        << format("SegmentOffset=0x%06X", SegmentOffset)
1933                        << ", AdvanceAmount=" << AdvanceAmount
1934                        << ", RemainingLoopCount=" << RemainingLoopCount
1935                        << "\n");
1936       return;
1937     case MachO::REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB:
1938       RemainingLoopCount = readULEB128() - 1;
1939       AdvanceAmount = readULEB128() + PointerSize;
1940       DEBUG_WITH_TYPE(
1941           "mach-o-rebase",
1942           llvm::dbgs() << "REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB: "
1943                        << format("SegmentOffset=0x%06X", SegmentOffset)
1944                        << ", AdvanceAmount=" << AdvanceAmount
1945                        << ", RemainingLoopCount=" << RemainingLoopCount
1946                        << "\n");
1947       return;
1948     default:
1949       Malformed = true;
1950     }
1951   }
1952 }
1953 
1954 uint64_t MachORebaseEntry::readULEB128() {
1955   unsigned Count;
1956   uint64_t Result = decodeULEB128(Ptr, &Count);
1957   Ptr += Count;
1958   if (Ptr > Opcodes.end()) {
1959     Ptr = Opcodes.end();
1960     Malformed = true;
1961   }
1962   return Result;
1963 }
1964 
1965 uint32_t MachORebaseEntry::segmentIndex() const { return SegmentIndex; }
1966 
1967 uint64_t MachORebaseEntry::segmentOffset() const { return SegmentOffset; }
1968 
1969 StringRef MachORebaseEntry::typeName() const {
1970   switch (RebaseType) {
1971   case MachO::REBASE_TYPE_POINTER:
1972     return "pointer";
1973   case MachO::REBASE_TYPE_TEXT_ABSOLUTE32:
1974     return "text abs32";
1975   case MachO::REBASE_TYPE_TEXT_PCREL32:
1976     return "text rel32";
1977   }
1978   return "unknown";
1979 }
1980 
1981 bool MachORebaseEntry::operator==(const MachORebaseEntry &Other) const {
1982   assert(Opcodes == Other.Opcodes && "compare iterators of different files");
1983   return (Ptr == Other.Ptr) &&
1984          (RemainingLoopCount == Other.RemainingLoopCount) &&
1985          (Done == Other.Done);
1986 }
1987 
1988 iterator_range<rebase_iterator>
1989 MachOObjectFile::rebaseTable(ArrayRef<uint8_t> Opcodes, bool is64) {
1990   MachORebaseEntry Start(Opcodes, is64);
1991   Start.moveToFirst();
1992 
1993   MachORebaseEntry Finish(Opcodes, is64);
1994   Finish.moveToEnd();
1995 
1996   return make_range(rebase_iterator(Start), rebase_iterator(Finish));
1997 }
1998 
1999 iterator_range<rebase_iterator> MachOObjectFile::rebaseTable() const {
2000   return rebaseTable(getDyldInfoRebaseOpcodes(), is64Bit());
2001 }
2002 
2003 MachOBindEntry::MachOBindEntry(ArrayRef<uint8_t> Bytes, bool is64Bit, Kind BK)
2004     : Opcodes(Bytes), Ptr(Bytes.begin()), SegmentOffset(0), SegmentIndex(0),
2005       Ordinal(0), Flags(0), Addend(0), RemainingLoopCount(0), AdvanceAmount(0),
2006       BindType(0), PointerSize(is64Bit ? 8 : 4),
2007       TableKind(BK), Malformed(false), Done(false) {}
2008 
2009 void MachOBindEntry::moveToFirst() {
2010   Ptr = Opcodes.begin();
2011   moveNext();
2012 }
2013 
2014 void MachOBindEntry::moveToEnd() {
2015   Ptr = Opcodes.end();
2016   RemainingLoopCount = 0;
2017   Done = true;
2018 }
2019 
2020 void MachOBindEntry::moveNext() {
2021   // If in the middle of some loop, move to next binding in loop.
2022   SegmentOffset += AdvanceAmount;
2023   if (RemainingLoopCount) {
2024     --RemainingLoopCount;
2025     return;
2026   }
2027   if (Ptr == Opcodes.end()) {
2028     Done = true;
2029     return;
2030   }
2031   bool More = true;
2032   while (More && !Malformed) {
2033     // Parse next opcode and set up next loop.
2034     uint8_t Byte = *Ptr++;
2035     uint8_t ImmValue = Byte & MachO::BIND_IMMEDIATE_MASK;
2036     uint8_t Opcode = Byte & MachO::BIND_OPCODE_MASK;
2037     int8_t SignExtended;
2038     const uint8_t *SymStart;
2039     switch (Opcode) {
2040     case MachO::BIND_OPCODE_DONE:
2041       if (TableKind == Kind::Lazy) {
2042         // Lazying bindings have a DONE opcode between entries.  Need to ignore
2043         // it to advance to next entry.  But need not if this is last entry.
2044         bool NotLastEntry = false;
2045         for (const uint8_t *P = Ptr; P < Opcodes.end(); ++P) {
2046           if (*P) {
2047             NotLastEntry = true;
2048           }
2049         }
2050         if (NotLastEntry)
2051           break;
2052       }
2053       More = false;
2054       Done = true;
2055       moveToEnd();
2056       DEBUG_WITH_TYPE("mach-o-bind", llvm::dbgs() << "BIND_OPCODE_DONE\n");
2057       break;
2058     case MachO::BIND_OPCODE_SET_DYLIB_ORDINAL_IMM:
2059       Ordinal = ImmValue;
2060       DEBUG_WITH_TYPE(
2061           "mach-o-bind",
2062           llvm::dbgs() << "BIND_OPCODE_SET_DYLIB_ORDINAL_IMM: "
2063                        << "Ordinal=" << Ordinal << "\n");
2064       break;
2065     case MachO::BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB:
2066       Ordinal = readULEB128();
2067       DEBUG_WITH_TYPE(
2068           "mach-o-bind",
2069           llvm::dbgs() << "BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB: "
2070                        << "Ordinal=" << Ordinal << "\n");
2071       break;
2072     case MachO::BIND_OPCODE_SET_DYLIB_SPECIAL_IMM:
2073       if (ImmValue) {
2074         SignExtended = MachO::BIND_OPCODE_MASK | ImmValue;
2075         Ordinal = SignExtended;
2076       } else
2077         Ordinal = 0;
2078       DEBUG_WITH_TYPE(
2079           "mach-o-bind",
2080           llvm::dbgs() << "BIND_OPCODE_SET_DYLIB_SPECIAL_IMM: "
2081                        << "Ordinal=" << Ordinal << "\n");
2082       break;
2083     case MachO::BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM:
2084       Flags = ImmValue;
2085       SymStart = Ptr;
2086       while (*Ptr) {
2087         ++Ptr;
2088       }
2089       SymbolName = StringRef(reinterpret_cast<const char*>(SymStart),
2090                              Ptr-SymStart);
2091       ++Ptr;
2092       DEBUG_WITH_TYPE(
2093           "mach-o-bind",
2094           llvm::dbgs() << "BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM: "
2095                        << "SymbolName=" << SymbolName << "\n");
2096       if (TableKind == Kind::Weak) {
2097         if (ImmValue & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION)
2098           return;
2099       }
2100       break;
2101     case MachO::BIND_OPCODE_SET_TYPE_IMM:
2102       BindType = ImmValue;
2103       DEBUG_WITH_TYPE(
2104           "mach-o-bind",
2105           llvm::dbgs() << "BIND_OPCODE_SET_TYPE_IMM: "
2106                        << "BindType=" << (int)BindType << "\n");
2107       break;
2108     case MachO::BIND_OPCODE_SET_ADDEND_SLEB:
2109       Addend = readSLEB128();
2110       if (TableKind == Kind::Lazy)
2111         Malformed = true;
2112       DEBUG_WITH_TYPE(
2113           "mach-o-bind",
2114           llvm::dbgs() << "BIND_OPCODE_SET_ADDEND_SLEB: "
2115                        << "Addend=" << Addend << "\n");
2116       break;
2117     case MachO::BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:
2118       SegmentIndex = ImmValue;
2119       SegmentOffset = readULEB128();
2120       DEBUG_WITH_TYPE(
2121           "mach-o-bind",
2122           llvm::dbgs() << "BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: "
2123                        << "SegmentIndex=" << SegmentIndex << ", "
2124                        << format("SegmentOffset=0x%06X", SegmentOffset)
2125                        << "\n");
2126       break;
2127     case MachO::BIND_OPCODE_ADD_ADDR_ULEB:
2128       SegmentOffset += readULEB128();
2129       DEBUG_WITH_TYPE("mach-o-bind",
2130                       llvm::dbgs() << "BIND_OPCODE_ADD_ADDR_ULEB: "
2131                                    << format("SegmentOffset=0x%06X",
2132                                              SegmentOffset) << "\n");
2133       break;
2134     case MachO::BIND_OPCODE_DO_BIND:
2135       AdvanceAmount = PointerSize;
2136       RemainingLoopCount = 0;
2137       DEBUG_WITH_TYPE("mach-o-bind",
2138                       llvm::dbgs() << "BIND_OPCODE_DO_BIND: "
2139                                    << format("SegmentOffset=0x%06X",
2140                                              SegmentOffset) << "\n");
2141       return;
2142      case MachO::BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB:
2143       AdvanceAmount = readULEB128() + PointerSize;
2144       RemainingLoopCount = 0;
2145       if (TableKind == Kind::Lazy)
2146         Malformed = true;
2147       DEBUG_WITH_TYPE(
2148           "mach-o-bind",
2149           llvm::dbgs() << "BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB: "
2150                        << format("SegmentOffset=0x%06X", SegmentOffset)
2151                        << ", AdvanceAmount=" << AdvanceAmount
2152                        << ", RemainingLoopCount=" << RemainingLoopCount
2153                        << "\n");
2154       return;
2155     case MachO::BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED:
2156       AdvanceAmount = ImmValue * PointerSize + PointerSize;
2157       RemainingLoopCount = 0;
2158       if (TableKind == Kind::Lazy)
2159         Malformed = true;
2160       DEBUG_WITH_TYPE("mach-o-bind",
2161                       llvm::dbgs()
2162                       << "BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED: "
2163                       << format("SegmentOffset=0x%06X",
2164                                              SegmentOffset) << "\n");
2165       return;
2166     case MachO::BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB:
2167       RemainingLoopCount = readULEB128() - 1;
2168       AdvanceAmount = readULEB128() + PointerSize;
2169       if (TableKind == Kind::Lazy)
2170         Malformed = true;
2171       DEBUG_WITH_TYPE(
2172           "mach-o-bind",
2173           llvm::dbgs() << "BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB: "
2174                        << format("SegmentOffset=0x%06X", SegmentOffset)
2175                        << ", AdvanceAmount=" << AdvanceAmount
2176                        << ", RemainingLoopCount=" << RemainingLoopCount
2177                        << "\n");
2178       return;
2179     default:
2180       Malformed = true;
2181     }
2182   }
2183 }
2184 
2185 uint64_t MachOBindEntry::readULEB128() {
2186   unsigned Count;
2187   uint64_t Result = decodeULEB128(Ptr, &Count);
2188   Ptr += Count;
2189   if (Ptr > Opcodes.end()) {
2190     Ptr = Opcodes.end();
2191     Malformed = true;
2192   }
2193   return Result;
2194 }
2195 
2196 int64_t MachOBindEntry::readSLEB128() {
2197   unsigned Count;
2198   int64_t Result = decodeSLEB128(Ptr, &Count);
2199   Ptr += Count;
2200   if (Ptr > Opcodes.end()) {
2201     Ptr = Opcodes.end();
2202     Malformed = true;
2203   }
2204   return Result;
2205 }
2206 
2207 uint32_t MachOBindEntry::segmentIndex() const { return SegmentIndex; }
2208 
2209 uint64_t MachOBindEntry::segmentOffset() const { return SegmentOffset; }
2210 
2211 StringRef MachOBindEntry::typeName() const {
2212   switch (BindType) {
2213   case MachO::BIND_TYPE_POINTER:
2214     return "pointer";
2215   case MachO::BIND_TYPE_TEXT_ABSOLUTE32:
2216     return "text abs32";
2217   case MachO::BIND_TYPE_TEXT_PCREL32:
2218     return "text rel32";
2219   }
2220   return "unknown";
2221 }
2222 
2223 StringRef MachOBindEntry::symbolName() const { return SymbolName; }
2224 
2225 int64_t MachOBindEntry::addend() const { return Addend; }
2226 
2227 uint32_t MachOBindEntry::flags() const { return Flags; }
2228 
2229 int MachOBindEntry::ordinal() const { return Ordinal; }
2230 
2231 bool MachOBindEntry::operator==(const MachOBindEntry &Other) const {
2232   assert(Opcodes == Other.Opcodes && "compare iterators of different files");
2233   return (Ptr == Other.Ptr) &&
2234          (RemainingLoopCount == Other.RemainingLoopCount) &&
2235          (Done == Other.Done);
2236 }
2237 
2238 iterator_range<bind_iterator>
2239 MachOObjectFile::bindTable(ArrayRef<uint8_t> Opcodes, bool is64,
2240                            MachOBindEntry::Kind BKind) {
2241   MachOBindEntry Start(Opcodes, is64, BKind);
2242   Start.moveToFirst();
2243 
2244   MachOBindEntry Finish(Opcodes, is64, BKind);
2245   Finish.moveToEnd();
2246 
2247   return make_range(bind_iterator(Start), bind_iterator(Finish));
2248 }
2249 
2250 iterator_range<bind_iterator> MachOObjectFile::bindTable() const {
2251   return bindTable(getDyldInfoBindOpcodes(), is64Bit(),
2252                    MachOBindEntry::Kind::Regular);
2253 }
2254 
2255 iterator_range<bind_iterator> MachOObjectFile::lazyBindTable() const {
2256   return bindTable(getDyldInfoLazyBindOpcodes(), is64Bit(),
2257                    MachOBindEntry::Kind::Lazy);
2258 }
2259 
2260 iterator_range<bind_iterator> MachOObjectFile::weakBindTable() const {
2261   return bindTable(getDyldInfoWeakBindOpcodes(), is64Bit(),
2262                    MachOBindEntry::Kind::Weak);
2263 }
2264 
2265 MachOObjectFile::load_command_iterator
2266 MachOObjectFile::begin_load_commands() const {
2267   return LoadCommands.begin();
2268 }
2269 
2270 MachOObjectFile::load_command_iterator
2271 MachOObjectFile::end_load_commands() const {
2272   return LoadCommands.end();
2273 }
2274 
2275 iterator_range<MachOObjectFile::load_command_iterator>
2276 MachOObjectFile::load_commands() const {
2277   return make_range(begin_load_commands(), end_load_commands());
2278 }
2279 
2280 StringRef
2281 MachOObjectFile::getSectionFinalSegmentName(DataRefImpl Sec) const {
2282   ArrayRef<char> Raw = getSectionRawFinalSegmentName(Sec);
2283   return parseSegmentOrSectionName(Raw.data());
2284 }
2285 
2286 ArrayRef<char>
2287 MachOObjectFile::getSectionRawName(DataRefImpl Sec) const {
2288   assert(Sec.d.a < Sections.size() && "Should have detected this earlier");
2289   const section_base *Base =
2290     reinterpret_cast<const section_base *>(Sections[Sec.d.a]);
2291   return makeArrayRef(Base->sectname);
2292 }
2293 
2294 ArrayRef<char>
2295 MachOObjectFile::getSectionRawFinalSegmentName(DataRefImpl Sec) const {
2296   assert(Sec.d.a < Sections.size() && "Should have detected this earlier");
2297   const section_base *Base =
2298     reinterpret_cast<const section_base *>(Sections[Sec.d.a]);
2299   return makeArrayRef(Base->segname);
2300 }
2301 
2302 bool
2303 MachOObjectFile::isRelocationScattered(const MachO::any_relocation_info &RE)
2304   const {
2305   if (getCPUType(this) == MachO::CPU_TYPE_X86_64)
2306     return false;
2307   return getPlainRelocationAddress(RE) & MachO::R_SCATTERED;
2308 }
2309 
2310 unsigned MachOObjectFile::getPlainRelocationSymbolNum(
2311     const MachO::any_relocation_info &RE) const {
2312   if (isLittleEndian())
2313     return RE.r_word1 & 0xffffff;
2314   return RE.r_word1 >> 8;
2315 }
2316 
2317 bool MachOObjectFile::getPlainRelocationExternal(
2318     const MachO::any_relocation_info &RE) const {
2319   if (isLittleEndian())
2320     return (RE.r_word1 >> 27) & 1;
2321   return (RE.r_word1 >> 4) & 1;
2322 }
2323 
2324 bool MachOObjectFile::getScatteredRelocationScattered(
2325     const MachO::any_relocation_info &RE) const {
2326   return RE.r_word0 >> 31;
2327 }
2328 
2329 uint32_t MachOObjectFile::getScatteredRelocationValue(
2330     const MachO::any_relocation_info &RE) const {
2331   return RE.r_word1;
2332 }
2333 
2334 uint32_t MachOObjectFile::getScatteredRelocationType(
2335     const MachO::any_relocation_info &RE) const {
2336   return (RE.r_word0 >> 24) & 0xf;
2337 }
2338 
2339 unsigned MachOObjectFile::getAnyRelocationAddress(
2340     const MachO::any_relocation_info &RE) const {
2341   if (isRelocationScattered(RE))
2342     return getScatteredRelocationAddress(RE);
2343   return getPlainRelocationAddress(RE);
2344 }
2345 
2346 unsigned MachOObjectFile::getAnyRelocationPCRel(
2347     const MachO::any_relocation_info &RE) const {
2348   if (isRelocationScattered(RE))
2349     return getScatteredRelocationPCRel(this, RE);
2350   return getPlainRelocationPCRel(this, RE);
2351 }
2352 
2353 unsigned MachOObjectFile::getAnyRelocationLength(
2354     const MachO::any_relocation_info &RE) const {
2355   if (isRelocationScattered(RE))
2356     return getScatteredRelocationLength(RE);
2357   return getPlainRelocationLength(this, RE);
2358 }
2359 
2360 unsigned
2361 MachOObjectFile::getAnyRelocationType(
2362                                    const MachO::any_relocation_info &RE) const {
2363   if (isRelocationScattered(RE))
2364     return getScatteredRelocationType(RE);
2365   return getPlainRelocationType(this, RE);
2366 }
2367 
2368 SectionRef
2369 MachOObjectFile::getAnyRelocationSection(
2370                                    const MachO::any_relocation_info &RE) const {
2371   if (isRelocationScattered(RE) || getPlainRelocationExternal(RE))
2372     return *section_end();
2373   unsigned SecNum = getPlainRelocationSymbolNum(RE);
2374   if (SecNum == MachO::R_ABS || SecNum > Sections.size())
2375     return *section_end();
2376   DataRefImpl DRI;
2377   DRI.d.a = SecNum - 1;
2378   return SectionRef(DRI, this);
2379 }
2380 
2381 MachO::section MachOObjectFile::getSection(DataRefImpl DRI) const {
2382   assert(DRI.d.a < Sections.size() && "Should have detected this earlier");
2383   return getStruct<MachO::section>(this, Sections[DRI.d.a]);
2384 }
2385 
2386 MachO::section_64 MachOObjectFile::getSection64(DataRefImpl DRI) const {
2387   assert(DRI.d.a < Sections.size() && "Should have detected this earlier");
2388   return getStruct<MachO::section_64>(this, Sections[DRI.d.a]);
2389 }
2390 
2391 MachO::section MachOObjectFile::getSection(const LoadCommandInfo &L,
2392                                            unsigned Index) const {
2393   const char *Sec = getSectionPtr(this, L, Index);
2394   return getStruct<MachO::section>(this, Sec);
2395 }
2396 
2397 MachO::section_64 MachOObjectFile::getSection64(const LoadCommandInfo &L,
2398                                                 unsigned Index) const {
2399   const char *Sec = getSectionPtr(this, L, Index);
2400   return getStruct<MachO::section_64>(this, Sec);
2401 }
2402 
2403 MachO::nlist
2404 MachOObjectFile::getSymbolTableEntry(DataRefImpl DRI) const {
2405   const char *P = reinterpret_cast<const char *>(DRI.p);
2406   return getStruct<MachO::nlist>(this, P);
2407 }
2408 
2409 MachO::nlist_64
2410 MachOObjectFile::getSymbol64TableEntry(DataRefImpl DRI) const {
2411   const char *P = reinterpret_cast<const char *>(DRI.p);
2412   return getStruct<MachO::nlist_64>(this, P);
2413 }
2414 
2415 MachO::linkedit_data_command
2416 MachOObjectFile::getLinkeditDataLoadCommand(const LoadCommandInfo &L) const {
2417   return getStruct<MachO::linkedit_data_command>(this, L.Ptr);
2418 }
2419 
2420 MachO::segment_command
2421 MachOObjectFile::getSegmentLoadCommand(const LoadCommandInfo &L) const {
2422   return getStruct<MachO::segment_command>(this, L.Ptr);
2423 }
2424 
2425 MachO::segment_command_64
2426 MachOObjectFile::getSegment64LoadCommand(const LoadCommandInfo &L) const {
2427   return getStruct<MachO::segment_command_64>(this, L.Ptr);
2428 }
2429 
2430 MachO::linker_option_command
2431 MachOObjectFile::getLinkerOptionLoadCommand(const LoadCommandInfo &L) const {
2432   return getStruct<MachO::linker_option_command>(this, L.Ptr);
2433 }
2434 
2435 MachO::version_min_command
2436 MachOObjectFile::getVersionMinLoadCommand(const LoadCommandInfo &L) const {
2437   return getStruct<MachO::version_min_command>(this, L.Ptr);
2438 }
2439 
2440 MachO::dylib_command
2441 MachOObjectFile::getDylibIDLoadCommand(const LoadCommandInfo &L) const {
2442   return getStruct<MachO::dylib_command>(this, L.Ptr);
2443 }
2444 
2445 MachO::dyld_info_command
2446 MachOObjectFile::getDyldInfoLoadCommand(const LoadCommandInfo &L) const {
2447   return getStruct<MachO::dyld_info_command>(this, L.Ptr);
2448 }
2449 
2450 MachO::dylinker_command
2451 MachOObjectFile::getDylinkerCommand(const LoadCommandInfo &L) const {
2452   return getStruct<MachO::dylinker_command>(this, L.Ptr);
2453 }
2454 
2455 MachO::uuid_command
2456 MachOObjectFile::getUuidCommand(const LoadCommandInfo &L) const {
2457   return getStruct<MachO::uuid_command>(this, L.Ptr);
2458 }
2459 
2460 MachO::rpath_command
2461 MachOObjectFile::getRpathCommand(const LoadCommandInfo &L) const {
2462   return getStruct<MachO::rpath_command>(this, L.Ptr);
2463 }
2464 
2465 MachO::source_version_command
2466 MachOObjectFile::getSourceVersionCommand(const LoadCommandInfo &L) const {
2467   return getStruct<MachO::source_version_command>(this, L.Ptr);
2468 }
2469 
2470 MachO::entry_point_command
2471 MachOObjectFile::getEntryPointCommand(const LoadCommandInfo &L) const {
2472   return getStruct<MachO::entry_point_command>(this, L.Ptr);
2473 }
2474 
2475 MachO::encryption_info_command
2476 MachOObjectFile::getEncryptionInfoCommand(const LoadCommandInfo &L) const {
2477   return getStruct<MachO::encryption_info_command>(this, L.Ptr);
2478 }
2479 
2480 MachO::encryption_info_command_64
2481 MachOObjectFile::getEncryptionInfoCommand64(const LoadCommandInfo &L) const {
2482   return getStruct<MachO::encryption_info_command_64>(this, L.Ptr);
2483 }
2484 
2485 MachO::sub_framework_command
2486 MachOObjectFile::getSubFrameworkCommand(const LoadCommandInfo &L) const {
2487   return getStruct<MachO::sub_framework_command>(this, L.Ptr);
2488 }
2489 
2490 MachO::sub_umbrella_command
2491 MachOObjectFile::getSubUmbrellaCommand(const LoadCommandInfo &L) const {
2492   return getStruct<MachO::sub_umbrella_command>(this, L.Ptr);
2493 }
2494 
2495 MachO::sub_library_command
2496 MachOObjectFile::getSubLibraryCommand(const LoadCommandInfo &L) const {
2497   return getStruct<MachO::sub_library_command>(this, L.Ptr);
2498 }
2499 
2500 MachO::sub_client_command
2501 MachOObjectFile::getSubClientCommand(const LoadCommandInfo &L) const {
2502   return getStruct<MachO::sub_client_command>(this, L.Ptr);
2503 }
2504 
2505 MachO::routines_command
2506 MachOObjectFile::getRoutinesCommand(const LoadCommandInfo &L) const {
2507   return getStruct<MachO::routines_command>(this, L.Ptr);
2508 }
2509 
2510 MachO::routines_command_64
2511 MachOObjectFile::getRoutinesCommand64(const LoadCommandInfo &L) const {
2512   return getStruct<MachO::routines_command_64>(this, L.Ptr);
2513 }
2514 
2515 MachO::thread_command
2516 MachOObjectFile::getThreadCommand(const LoadCommandInfo &L) const {
2517   return getStruct<MachO::thread_command>(this, L.Ptr);
2518 }
2519 
2520 MachO::any_relocation_info
2521 MachOObjectFile::getRelocation(DataRefImpl Rel) const {
2522   DataRefImpl Sec;
2523   Sec.d.a = Rel.d.a;
2524   uint32_t Offset;
2525   if (is64Bit()) {
2526     MachO::section_64 Sect = getSection64(Sec);
2527     Offset = Sect.reloff;
2528   } else {
2529     MachO::section Sect = getSection(Sec);
2530     Offset = Sect.reloff;
2531   }
2532 
2533   auto P = reinterpret_cast<const MachO::any_relocation_info *>(
2534       getPtr(this, Offset)) + Rel.d.b;
2535   return getStruct<MachO::any_relocation_info>(
2536       this, reinterpret_cast<const char *>(P));
2537 }
2538 
2539 MachO::data_in_code_entry
2540 MachOObjectFile::getDice(DataRefImpl Rel) const {
2541   const char *P = reinterpret_cast<const char *>(Rel.p);
2542   return getStruct<MachO::data_in_code_entry>(this, P);
2543 }
2544 
2545 const MachO::mach_header &MachOObjectFile::getHeader() const {
2546   return Header;
2547 }
2548 
2549 const MachO::mach_header_64 &MachOObjectFile::getHeader64() const {
2550   assert(is64Bit());
2551   return Header64;
2552 }
2553 
2554 uint32_t MachOObjectFile::getIndirectSymbolTableEntry(
2555                                              const MachO::dysymtab_command &DLC,
2556                                              unsigned Index) const {
2557   uint64_t Offset = DLC.indirectsymoff + Index * sizeof(uint32_t);
2558   return getStruct<uint32_t>(this, getPtr(this, Offset));
2559 }
2560 
2561 MachO::data_in_code_entry
2562 MachOObjectFile::getDataInCodeTableEntry(uint32_t DataOffset,
2563                                          unsigned Index) const {
2564   uint64_t Offset = DataOffset + Index * sizeof(MachO::data_in_code_entry);
2565   return getStruct<MachO::data_in_code_entry>(this, getPtr(this, Offset));
2566 }
2567 
2568 MachO::symtab_command MachOObjectFile::getSymtabLoadCommand() const {
2569   if (SymtabLoadCmd)
2570     return getStruct<MachO::symtab_command>(this, SymtabLoadCmd);
2571 
2572   // If there is no SymtabLoadCmd return a load command with zero'ed fields.
2573   MachO::symtab_command Cmd;
2574   Cmd.cmd = MachO::LC_SYMTAB;
2575   Cmd.cmdsize = sizeof(MachO::symtab_command);
2576   Cmd.symoff = 0;
2577   Cmd.nsyms = 0;
2578   Cmd.stroff = 0;
2579   Cmd.strsize = 0;
2580   return Cmd;
2581 }
2582 
2583 MachO::dysymtab_command MachOObjectFile::getDysymtabLoadCommand() const {
2584   if (DysymtabLoadCmd)
2585     return getStruct<MachO::dysymtab_command>(this, DysymtabLoadCmd);
2586 
2587   // If there is no DysymtabLoadCmd return a load command with zero'ed fields.
2588   MachO::dysymtab_command Cmd;
2589   Cmd.cmd = MachO::LC_DYSYMTAB;
2590   Cmd.cmdsize = sizeof(MachO::dysymtab_command);
2591   Cmd.ilocalsym = 0;
2592   Cmd.nlocalsym = 0;
2593   Cmd.iextdefsym = 0;
2594   Cmd.nextdefsym = 0;
2595   Cmd.iundefsym = 0;
2596   Cmd.nundefsym = 0;
2597   Cmd.tocoff = 0;
2598   Cmd.ntoc = 0;
2599   Cmd.modtaboff = 0;
2600   Cmd.nmodtab = 0;
2601   Cmd.extrefsymoff = 0;
2602   Cmd.nextrefsyms = 0;
2603   Cmd.indirectsymoff = 0;
2604   Cmd.nindirectsyms = 0;
2605   Cmd.extreloff = 0;
2606   Cmd.nextrel = 0;
2607   Cmd.locreloff = 0;
2608   Cmd.nlocrel = 0;
2609   return Cmd;
2610 }
2611 
2612 MachO::linkedit_data_command
2613 MachOObjectFile::getDataInCodeLoadCommand() const {
2614   if (DataInCodeLoadCmd)
2615     return getStruct<MachO::linkedit_data_command>(this, DataInCodeLoadCmd);
2616 
2617   // If there is no DataInCodeLoadCmd return a load command with zero'ed fields.
2618   MachO::linkedit_data_command Cmd;
2619   Cmd.cmd = MachO::LC_DATA_IN_CODE;
2620   Cmd.cmdsize = sizeof(MachO::linkedit_data_command);
2621   Cmd.dataoff = 0;
2622   Cmd.datasize = 0;
2623   return Cmd;
2624 }
2625 
2626 MachO::linkedit_data_command
2627 MachOObjectFile::getLinkOptHintsLoadCommand() const {
2628   if (LinkOptHintsLoadCmd)
2629     return getStruct<MachO::linkedit_data_command>(this, LinkOptHintsLoadCmd);
2630 
2631   // If there is no LinkOptHintsLoadCmd return a load command with zero'ed
2632   // fields.
2633   MachO::linkedit_data_command Cmd;
2634   Cmd.cmd = MachO::LC_LINKER_OPTIMIZATION_HINT;
2635   Cmd.cmdsize = sizeof(MachO::linkedit_data_command);
2636   Cmd.dataoff = 0;
2637   Cmd.datasize = 0;
2638   return Cmd;
2639 }
2640 
2641 ArrayRef<uint8_t> MachOObjectFile::getDyldInfoRebaseOpcodes() const {
2642   if (!DyldInfoLoadCmd)
2643     return None;
2644 
2645   MachO::dyld_info_command DyldInfo =
2646       getStruct<MachO::dyld_info_command>(this, DyldInfoLoadCmd);
2647   const uint8_t *Ptr =
2648       reinterpret_cast<const uint8_t *>(getPtr(this, DyldInfo.rebase_off));
2649   return makeArrayRef(Ptr, DyldInfo.rebase_size);
2650 }
2651 
2652 ArrayRef<uint8_t> MachOObjectFile::getDyldInfoBindOpcodes() const {
2653   if (!DyldInfoLoadCmd)
2654     return None;
2655 
2656   MachO::dyld_info_command DyldInfo =
2657       getStruct<MachO::dyld_info_command>(this, DyldInfoLoadCmd);
2658   const uint8_t *Ptr =
2659       reinterpret_cast<const uint8_t *>(getPtr(this, DyldInfo.bind_off));
2660   return makeArrayRef(Ptr, DyldInfo.bind_size);
2661 }
2662 
2663 ArrayRef<uint8_t> MachOObjectFile::getDyldInfoWeakBindOpcodes() const {
2664   if (!DyldInfoLoadCmd)
2665     return None;
2666 
2667   MachO::dyld_info_command DyldInfo =
2668       getStruct<MachO::dyld_info_command>(this, DyldInfoLoadCmd);
2669   const uint8_t *Ptr =
2670       reinterpret_cast<const uint8_t *>(getPtr(this, DyldInfo.weak_bind_off));
2671   return makeArrayRef(Ptr, DyldInfo.weak_bind_size);
2672 }
2673 
2674 ArrayRef<uint8_t> MachOObjectFile::getDyldInfoLazyBindOpcodes() const {
2675   if (!DyldInfoLoadCmd)
2676     return None;
2677 
2678   MachO::dyld_info_command DyldInfo =
2679       getStruct<MachO::dyld_info_command>(this, DyldInfoLoadCmd);
2680   const uint8_t *Ptr =
2681       reinterpret_cast<const uint8_t *>(getPtr(this, DyldInfo.lazy_bind_off));
2682   return makeArrayRef(Ptr, DyldInfo.lazy_bind_size);
2683 }
2684 
2685 ArrayRef<uint8_t> MachOObjectFile::getDyldInfoExportsTrie() const {
2686   if (!DyldInfoLoadCmd)
2687     return None;
2688 
2689   MachO::dyld_info_command DyldInfo =
2690       getStruct<MachO::dyld_info_command>(this, DyldInfoLoadCmd);
2691   const uint8_t *Ptr =
2692       reinterpret_cast<const uint8_t *>(getPtr(this, DyldInfo.export_off));
2693   return makeArrayRef(Ptr, DyldInfo.export_size);
2694 }
2695 
2696 ArrayRef<uint8_t> MachOObjectFile::getUuid() const {
2697   if (!UuidLoadCmd)
2698     return None;
2699   // Returning a pointer is fine as uuid doesn't need endian swapping.
2700   const char *Ptr = UuidLoadCmd + offsetof(MachO::uuid_command, uuid);
2701   return makeArrayRef(reinterpret_cast<const uint8_t *>(Ptr), 16);
2702 }
2703 
2704 StringRef MachOObjectFile::getStringTableData() const {
2705   MachO::symtab_command S = getSymtabLoadCommand();
2706   return getData().substr(S.stroff, S.strsize);
2707 }
2708 
2709 bool MachOObjectFile::is64Bit() const {
2710   return getType() == getMachOType(false, true) ||
2711     getType() == getMachOType(true, true);
2712 }
2713 
2714 void MachOObjectFile::ReadULEB128s(uint64_t Index,
2715                                    SmallVectorImpl<uint64_t> &Out) const {
2716   DataExtractor extractor(ObjectFile::getData(), true, 0);
2717 
2718   uint32_t offset = Index;
2719   uint64_t data = 0;
2720   while (uint64_t delta = extractor.getULEB128(&offset)) {
2721     data += delta;
2722     Out.push_back(data);
2723   }
2724 }
2725 
2726 bool MachOObjectFile::isRelocatableObject() const {
2727   return getHeader().filetype == MachO::MH_OBJECT;
2728 }
2729 
2730 Expected<std::unique_ptr<MachOObjectFile>>
2731 ObjectFile::createMachOObjectFile(MemoryBufferRef Buffer) {
2732   StringRef Magic = Buffer.getBuffer().slice(0, 4);
2733   if (Magic == "\xFE\xED\xFA\xCE")
2734     return MachOObjectFile::create(Buffer, false, false);
2735   if (Magic == "\xCE\xFA\xED\xFE")
2736     return MachOObjectFile::create(Buffer, true, false);
2737   if (Magic == "\xFE\xED\xFA\xCF")
2738     return MachOObjectFile::create(Buffer, false, true);
2739   if (Magic == "\xCF\xFA\xED\xFE")
2740     return MachOObjectFile::create(Buffer, true, true);
2741   return make_error<GenericBinaryError>("Unrecognized MachO magic number",
2742                                         object_error::invalid_file_type);
2743 }
2744