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