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 (isLoadCommandObsolete(Load.C.cmd)) {
1600       Err = malformedError("load command " + Twine(I) + " for cmd value of: " +
1601                            Twine(Load.C.cmd) + " is obsolete and not "
1602                            "supported");
1603       return;
1604     }
1605     // TODO: generate a error for unknown load commands by default.  But still
1606     // need work out an approach to allow or not allow unknown values like this
1607     // as an option for some uses like lldb.
1608     if (I < LoadCommandCount - 1) {
1609       if (auto LoadOrErr = getNextLoadCommandInfo(*this, I, Load))
1610         Load = *LoadOrErr;
1611       else {
1612         Err = LoadOrErr.takeError();
1613         return;
1614       }
1615     }
1616   }
1617   if (!SymtabLoadCmd) {
1618     if (DysymtabLoadCmd) {
1619       Err = malformedError("contains LC_DYSYMTAB load command without a "
1620                            "LC_SYMTAB load command");
1621       return;
1622     }
1623   } else if (DysymtabLoadCmd) {
1624     MachO::symtab_command Symtab =
1625       getStruct<MachO::symtab_command>(*this, SymtabLoadCmd);
1626     MachO::dysymtab_command Dysymtab =
1627       getStruct<MachO::dysymtab_command>(*this, DysymtabLoadCmd);
1628     if (Dysymtab.nlocalsym != 0 && Dysymtab.ilocalsym > Symtab.nsyms) {
1629       Err = malformedError("ilocalsym in LC_DYSYMTAB load command "
1630                            "extends past the end of the symbol table");
1631       return;
1632     }
1633     uint64_t BigSize = Dysymtab.ilocalsym;
1634     BigSize += Dysymtab.nlocalsym;
1635     if (Dysymtab.nlocalsym != 0 && BigSize > Symtab.nsyms) {
1636       Err = malformedError("ilocalsym plus nlocalsym in LC_DYSYMTAB load "
1637                            "command extends past the end of the symbol table");
1638       return;
1639     }
1640     if (Dysymtab.nextdefsym != 0 && Dysymtab.iextdefsym > Symtab.nsyms) {
1641       Err = malformedError("iextdefsym in LC_DYSYMTAB load command "
1642                            "extends past the end of the symbol table");
1643       return;
1644     }
1645     BigSize = Dysymtab.iextdefsym;
1646     BigSize += Dysymtab.nextdefsym;
1647     if (Dysymtab.nextdefsym != 0 && BigSize > Symtab.nsyms) {
1648       Err = malformedError("iextdefsym plus nextdefsym in LC_DYSYMTAB "
1649                            "load command extends past the end of the symbol "
1650                            "table");
1651       return;
1652     }
1653     if (Dysymtab.nundefsym != 0 && Dysymtab.iundefsym > Symtab.nsyms) {
1654       Err = malformedError("iundefsym in LC_DYSYMTAB load command "
1655                            "extends past the end of the symbol table");
1656       return;
1657     }
1658     BigSize = Dysymtab.iundefsym;
1659     BigSize += Dysymtab.nundefsym;
1660     if (Dysymtab.nundefsym != 0 && BigSize > Symtab.nsyms) {
1661       Err = malformedError("iundefsym plus nundefsym in LC_DYSYMTAB load "
1662                            " command extends past the end of the symbol table");
1663       return;
1664     }
1665   }
1666   if ((getHeader().filetype == MachO::MH_DYLIB ||
1667        getHeader().filetype == MachO::MH_DYLIB_STUB) &&
1668        DyldIdLoadCmd == nullptr) {
1669     Err = malformedError("no LC_ID_DYLIB load command in dynamic library "
1670                          "filetype");
1671     return;
1672   }
1673   assert(LoadCommands.size() == LoadCommandCount);
1674 
1675   Err = Error::success();
1676 }
1677 
checkSymbolTable() const1678 Error MachOObjectFile::checkSymbolTable() const {
1679   uint32_t Flags = 0;
1680   if (is64Bit()) {
1681     MachO::mach_header_64 H_64 = MachOObjectFile::getHeader64();
1682     Flags = H_64.flags;
1683   } else {
1684     MachO::mach_header H = MachOObjectFile::getHeader();
1685     Flags = H.flags;
1686   }
1687   uint8_t NType = 0;
1688   uint8_t NSect = 0;
1689   uint16_t NDesc = 0;
1690   uint32_t NStrx = 0;
1691   uint64_t NValue = 0;
1692   uint32_t SymbolIndex = 0;
1693   MachO::symtab_command S = getSymtabLoadCommand();
1694   for (const SymbolRef &Symbol : symbols()) {
1695     DataRefImpl SymDRI = Symbol.getRawDataRefImpl();
1696     if (is64Bit()) {
1697       MachO::nlist_64 STE_64 = getSymbol64TableEntry(SymDRI);
1698       NType = STE_64.n_type;
1699       NSect = STE_64.n_sect;
1700       NDesc = STE_64.n_desc;
1701       NStrx = STE_64.n_strx;
1702       NValue = STE_64.n_value;
1703     } else {
1704       MachO::nlist STE = getSymbolTableEntry(SymDRI);
1705       NType = STE.n_type;
1706       NSect = STE.n_sect;
1707       NDesc = STE.n_desc;
1708       NStrx = STE.n_strx;
1709       NValue = STE.n_value;
1710     }
1711     if ((NType & MachO::N_STAB) == 0) {
1712       if ((NType & MachO::N_TYPE) == MachO::N_SECT) {
1713         if (NSect == 0 || NSect > Sections.size())
1714           return malformedError("bad section index: " + Twine((int)NSect) +
1715                                 " for symbol at index " + Twine(SymbolIndex));
1716       }
1717       if ((NType & MachO::N_TYPE) == MachO::N_INDR) {
1718         if (NValue >= S.strsize)
1719           return malformedError("bad n_value: " + Twine((int)NValue) + " past "
1720                                 "the end of string table, for N_INDR symbol at "
1721                                 "index " + Twine(SymbolIndex));
1722       }
1723       if ((Flags & MachO::MH_TWOLEVEL) == MachO::MH_TWOLEVEL &&
1724           (((NType & MachO::N_TYPE) == MachO::N_UNDF && NValue == 0) ||
1725            (NType & MachO::N_TYPE) == MachO::N_PBUD)) {
1726             uint32_t LibraryOrdinal = MachO::GET_LIBRARY_ORDINAL(NDesc);
1727             if (LibraryOrdinal != 0 &&
1728                 LibraryOrdinal != MachO::EXECUTABLE_ORDINAL &&
1729                 LibraryOrdinal != MachO::DYNAMIC_LOOKUP_ORDINAL &&
1730                 LibraryOrdinal - 1 >= Libraries.size() ) {
1731               return malformedError("bad library ordinal: " + Twine(LibraryOrdinal) +
1732                                     " for symbol at index " + Twine(SymbolIndex));
1733             }
1734           }
1735     }
1736     if (NStrx >= S.strsize)
1737       return malformedError("bad string table index: " + Twine((int)NStrx) +
1738                             " past the end of string table, for symbol at "
1739                             "index " + Twine(SymbolIndex));
1740     SymbolIndex++;
1741   }
1742   return Error::success();
1743 }
1744 
moveSymbolNext(DataRefImpl & Symb) const1745 void MachOObjectFile::moveSymbolNext(DataRefImpl &Symb) const {
1746   unsigned SymbolTableEntrySize = is64Bit() ?
1747     sizeof(MachO::nlist_64) :
1748     sizeof(MachO::nlist);
1749   Symb.p += SymbolTableEntrySize;
1750 }
1751 
getSymbolName(DataRefImpl Symb) const1752 Expected<StringRef> MachOObjectFile::getSymbolName(DataRefImpl Symb) const {
1753   StringRef StringTable = getStringTableData();
1754   MachO::nlist_base Entry = getSymbolTableEntryBase(*this, Symb);
1755   if (Entry.n_strx == 0)
1756     // A n_strx value of 0 indicates that no name is associated with a
1757     // particular symbol table entry.
1758     return StringRef();
1759   const char *Start = &StringTable.data()[Entry.n_strx];
1760   if (Start < getData().begin() || Start >= getData().end()) {
1761     return malformedError("bad string index: " + Twine(Entry.n_strx) +
1762                           " for symbol at index " + Twine(getSymbolIndex(Symb)));
1763   }
1764   return StringRef(Start);
1765 }
1766 
getSectionType(SectionRef Sec) const1767 unsigned MachOObjectFile::getSectionType(SectionRef Sec) const {
1768   DataRefImpl DRI = Sec.getRawDataRefImpl();
1769   uint32_t Flags = getSectionFlags(*this, DRI);
1770   return Flags & MachO::SECTION_TYPE;
1771 }
1772 
getNValue(DataRefImpl Sym) const1773 uint64_t MachOObjectFile::getNValue(DataRefImpl Sym) const {
1774   if (is64Bit()) {
1775     MachO::nlist_64 Entry = getSymbol64TableEntry(Sym);
1776     return Entry.n_value;
1777   }
1778   MachO::nlist Entry = getSymbolTableEntry(Sym);
1779   return Entry.n_value;
1780 }
1781 
1782 // getIndirectName() returns the name of the alias'ed symbol who's string table
1783 // index is in the n_value field.
getIndirectName(DataRefImpl Symb,StringRef & Res) const1784 std::error_code MachOObjectFile::getIndirectName(DataRefImpl Symb,
1785                                                  StringRef &Res) const {
1786   StringRef StringTable = getStringTableData();
1787   MachO::nlist_base Entry = getSymbolTableEntryBase(*this, Symb);
1788   if ((Entry.n_type & MachO::N_TYPE) != MachO::N_INDR)
1789     return object_error::parse_failed;
1790   uint64_t NValue = getNValue(Symb);
1791   if (NValue >= StringTable.size())
1792     return object_error::parse_failed;
1793   const char *Start = &StringTable.data()[NValue];
1794   Res = StringRef(Start);
1795   return std::error_code();
1796 }
1797 
getSymbolValueImpl(DataRefImpl Sym) const1798 uint64_t MachOObjectFile::getSymbolValueImpl(DataRefImpl Sym) const {
1799   return getNValue(Sym);
1800 }
1801 
getSymbolAddress(DataRefImpl Sym) const1802 Expected<uint64_t> MachOObjectFile::getSymbolAddress(DataRefImpl Sym) const {
1803   return getSymbolValue(Sym);
1804 }
1805 
getSymbolAlignment(DataRefImpl DRI) const1806 uint32_t MachOObjectFile::getSymbolAlignment(DataRefImpl DRI) const {
1807   uint32_t Flags = cantFail(getSymbolFlags(DRI));
1808   if (Flags & SymbolRef::SF_Common) {
1809     MachO::nlist_base Entry = getSymbolTableEntryBase(*this, DRI);
1810     return 1 << MachO::GET_COMM_ALIGN(Entry.n_desc);
1811   }
1812   return 0;
1813 }
1814 
getCommonSymbolSizeImpl(DataRefImpl DRI) const1815 uint64_t MachOObjectFile::getCommonSymbolSizeImpl(DataRefImpl DRI) const {
1816   return getNValue(DRI);
1817 }
1818 
1819 Expected<SymbolRef::Type>
getSymbolType(DataRefImpl Symb) const1820 MachOObjectFile::getSymbolType(DataRefImpl Symb) const {
1821   MachO::nlist_base Entry = getSymbolTableEntryBase(*this, Symb);
1822   uint8_t n_type = Entry.n_type;
1823 
1824   // If this is a STAB debugging symbol, we can do nothing more.
1825   if (n_type & MachO::N_STAB)
1826     return SymbolRef::ST_Debug;
1827 
1828   switch (n_type & MachO::N_TYPE) {
1829     case MachO::N_UNDF :
1830       return SymbolRef::ST_Unknown;
1831     case MachO::N_SECT :
1832       Expected<section_iterator> SecOrError = getSymbolSection(Symb);
1833       if (!SecOrError)
1834         return SecOrError.takeError();
1835       section_iterator Sec = *SecOrError;
1836       if (Sec->isData() || Sec->isBSS())
1837         return SymbolRef::ST_Data;
1838       return SymbolRef::ST_Function;
1839   }
1840   return SymbolRef::ST_Other;
1841 }
1842 
getSymbolFlags(DataRefImpl DRI) const1843 Expected<uint32_t> MachOObjectFile::getSymbolFlags(DataRefImpl DRI) const {
1844   MachO::nlist_base Entry = getSymbolTableEntryBase(*this, DRI);
1845 
1846   uint8_t MachOType = Entry.n_type;
1847   uint16_t MachOFlags = Entry.n_desc;
1848 
1849   uint32_t Result = SymbolRef::SF_None;
1850 
1851   if ((MachOType & MachO::N_TYPE) == MachO::N_INDR)
1852     Result |= SymbolRef::SF_Indirect;
1853 
1854   if (MachOType & MachO::N_STAB)
1855     Result |= SymbolRef::SF_FormatSpecific;
1856 
1857   if (MachOType & MachO::N_EXT) {
1858     Result |= SymbolRef::SF_Global;
1859     if ((MachOType & MachO::N_TYPE) == MachO::N_UNDF) {
1860       if (getNValue(DRI))
1861         Result |= SymbolRef::SF_Common;
1862       else
1863         Result |= SymbolRef::SF_Undefined;
1864     }
1865 
1866     if (!(MachOType & MachO::N_PEXT))
1867       Result |= SymbolRef::SF_Exported;
1868   }
1869 
1870   if (MachOFlags & (MachO::N_WEAK_REF | MachO::N_WEAK_DEF))
1871     Result |= SymbolRef::SF_Weak;
1872 
1873   if (MachOFlags & (MachO::N_ARM_THUMB_DEF))
1874     Result |= SymbolRef::SF_Thumb;
1875 
1876   if ((MachOType & MachO::N_TYPE) == MachO::N_ABS)
1877     Result |= SymbolRef::SF_Absolute;
1878 
1879   return Result;
1880 }
1881 
1882 Expected<section_iterator>
getSymbolSection(DataRefImpl Symb) const1883 MachOObjectFile::getSymbolSection(DataRefImpl Symb) const {
1884   MachO::nlist_base Entry = getSymbolTableEntryBase(*this, Symb);
1885   uint8_t index = Entry.n_sect;
1886 
1887   if (index == 0)
1888     return section_end();
1889   DataRefImpl DRI;
1890   DRI.d.a = index - 1;
1891   if (DRI.d.a >= Sections.size()){
1892     return malformedError("bad section index: " + Twine((int)index) +
1893                           " for symbol at index " + Twine(getSymbolIndex(Symb)));
1894   }
1895   return section_iterator(SectionRef(DRI, this));
1896 }
1897 
getSymbolSectionID(SymbolRef Sym) const1898 unsigned MachOObjectFile::getSymbolSectionID(SymbolRef Sym) const {
1899   MachO::nlist_base Entry =
1900       getSymbolTableEntryBase(*this, Sym.getRawDataRefImpl());
1901   return Entry.n_sect - 1;
1902 }
1903 
moveSectionNext(DataRefImpl & Sec) const1904 void MachOObjectFile::moveSectionNext(DataRefImpl &Sec) const {
1905   Sec.d.a++;
1906 }
1907 
getSectionName(DataRefImpl Sec) const1908 Expected<StringRef> MachOObjectFile::getSectionName(DataRefImpl Sec) const {
1909   ArrayRef<char> Raw = getSectionRawName(Sec);
1910   return parseSegmentOrSectionName(Raw.data());
1911 }
1912 
getSectionAddress(DataRefImpl Sec) const1913 uint64_t MachOObjectFile::getSectionAddress(DataRefImpl Sec) const {
1914   if (is64Bit())
1915     return getSection64(Sec).addr;
1916   return getSection(Sec).addr;
1917 }
1918 
getSectionIndex(DataRefImpl Sec) const1919 uint64_t MachOObjectFile::getSectionIndex(DataRefImpl Sec) const {
1920   return Sec.d.a;
1921 }
1922 
getSectionSize(DataRefImpl Sec) const1923 uint64_t MachOObjectFile::getSectionSize(DataRefImpl Sec) const {
1924   // In the case if a malformed Mach-O file where the section offset is past
1925   // the end of the file or some part of the section size is past the end of
1926   // the file return a size of zero or a size that covers the rest of the file
1927   // but does not extend past the end of the file.
1928   uint32_t SectOffset, SectType;
1929   uint64_t SectSize;
1930 
1931   if (is64Bit()) {
1932     MachO::section_64 Sect = getSection64(Sec);
1933     SectOffset = Sect.offset;
1934     SectSize = Sect.size;
1935     SectType = Sect.flags & MachO::SECTION_TYPE;
1936   } else {
1937     MachO::section Sect = getSection(Sec);
1938     SectOffset = Sect.offset;
1939     SectSize = Sect.size;
1940     SectType = Sect.flags & MachO::SECTION_TYPE;
1941   }
1942   if (SectType == MachO::S_ZEROFILL || SectType == MachO::S_GB_ZEROFILL)
1943     return SectSize;
1944   uint64_t FileSize = getData().size();
1945   if (SectOffset > FileSize)
1946     return 0;
1947   if (FileSize - SectOffset < SectSize)
1948     return FileSize - SectOffset;
1949   return SectSize;
1950 }
1951 
getSectionContents(uint32_t Offset,uint64_t Size) const1952 ArrayRef<uint8_t> MachOObjectFile::getSectionContents(uint32_t Offset,
1953                                                       uint64_t Size) const {
1954   return arrayRefFromStringRef(getData().substr(Offset, Size));
1955 }
1956 
1957 Expected<ArrayRef<uint8_t>>
getSectionContents(DataRefImpl Sec) const1958 MachOObjectFile::getSectionContents(DataRefImpl Sec) const {
1959   uint32_t Offset;
1960   uint64_t Size;
1961 
1962   if (is64Bit()) {
1963     MachO::section_64 Sect = getSection64(Sec);
1964     Offset = Sect.offset;
1965     Size = Sect.size;
1966   } else {
1967     MachO::section Sect = getSection(Sec);
1968     Offset = Sect.offset;
1969     Size = Sect.size;
1970   }
1971 
1972   return getSectionContents(Offset, Size);
1973 }
1974 
getSectionAlignment(DataRefImpl Sec) const1975 uint64_t MachOObjectFile::getSectionAlignment(DataRefImpl Sec) const {
1976   uint32_t Align;
1977   if (is64Bit()) {
1978     MachO::section_64 Sect = getSection64(Sec);
1979     Align = Sect.align;
1980   } else {
1981     MachO::section Sect = getSection(Sec);
1982     Align = Sect.align;
1983   }
1984 
1985   return uint64_t(1) << Align;
1986 }
1987 
getSection(unsigned SectionIndex) const1988 Expected<SectionRef> MachOObjectFile::getSection(unsigned SectionIndex) const {
1989   if (SectionIndex < 1 || SectionIndex > Sections.size())
1990     return malformedError("bad section index: " + Twine((int)SectionIndex));
1991 
1992   DataRefImpl DRI;
1993   DRI.d.a = SectionIndex - 1;
1994   return SectionRef(DRI, this);
1995 }
1996 
getSection(StringRef SectionName) const1997 Expected<SectionRef> MachOObjectFile::getSection(StringRef SectionName) const {
1998   for (const SectionRef &Section : sections()) {
1999     auto NameOrErr = Section.getName();
2000     if (!NameOrErr)
2001       return NameOrErr.takeError();
2002     if (*NameOrErr == SectionName)
2003       return Section;
2004   }
2005   return errorCodeToError(object_error::parse_failed);
2006 }
2007 
isSectionCompressed(DataRefImpl Sec) const2008 bool MachOObjectFile::isSectionCompressed(DataRefImpl Sec) const {
2009   return false;
2010 }
2011 
isSectionText(DataRefImpl Sec) const2012 bool MachOObjectFile::isSectionText(DataRefImpl Sec) const {
2013   uint32_t Flags = getSectionFlags(*this, Sec);
2014   return Flags & MachO::S_ATTR_PURE_INSTRUCTIONS;
2015 }
2016 
isSectionData(DataRefImpl Sec) const2017 bool MachOObjectFile::isSectionData(DataRefImpl Sec) const {
2018   uint32_t Flags = getSectionFlags(*this, Sec);
2019   unsigned SectionType = Flags & MachO::SECTION_TYPE;
2020   return !(Flags & MachO::S_ATTR_PURE_INSTRUCTIONS) &&
2021          !(SectionType == MachO::S_ZEROFILL ||
2022            SectionType == MachO::S_GB_ZEROFILL);
2023 }
2024 
isSectionBSS(DataRefImpl Sec) const2025 bool MachOObjectFile::isSectionBSS(DataRefImpl Sec) const {
2026   uint32_t Flags = getSectionFlags(*this, Sec);
2027   unsigned SectionType = Flags & MachO::SECTION_TYPE;
2028   return !(Flags & MachO::S_ATTR_PURE_INSTRUCTIONS) &&
2029          (SectionType == MachO::S_ZEROFILL ||
2030           SectionType == MachO::S_GB_ZEROFILL);
2031 }
2032 
isDebugSection(StringRef SectionName) const2033 bool MachOObjectFile::isDebugSection(StringRef SectionName) const {
2034   return SectionName.startswith("__debug") ||
2035          SectionName.startswith("__zdebug") ||
2036          SectionName.startswith("__apple") || SectionName == "__gdb_index" ||
2037          SectionName == "__swift_ast";
2038 }
2039 
getSectionID(SectionRef Sec) const2040 unsigned MachOObjectFile::getSectionID(SectionRef Sec) const {
2041   return Sec.getRawDataRefImpl().d.a;
2042 }
2043 
isSectionVirtual(DataRefImpl Sec) const2044 bool MachOObjectFile::isSectionVirtual(DataRefImpl Sec) const {
2045   uint32_t Flags = getSectionFlags(*this, Sec);
2046   unsigned SectionType = Flags & MachO::SECTION_TYPE;
2047   return SectionType == MachO::S_ZEROFILL ||
2048          SectionType == MachO::S_GB_ZEROFILL;
2049 }
2050 
isSectionBitcode(DataRefImpl Sec) const2051 bool MachOObjectFile::isSectionBitcode(DataRefImpl Sec) const {
2052   StringRef SegmentName = getSectionFinalSegmentName(Sec);
2053   if (Expected<StringRef> NameOrErr = getSectionName(Sec))
2054     return (SegmentName == "__LLVM" && *NameOrErr == "__bitcode");
2055   return false;
2056 }
2057 
isSectionStripped(DataRefImpl Sec) const2058 bool MachOObjectFile::isSectionStripped(DataRefImpl Sec) const {
2059   if (is64Bit())
2060     return getSection64(Sec).offset == 0;
2061   return getSection(Sec).offset == 0;
2062 }
2063 
section_rel_begin(DataRefImpl Sec) const2064 relocation_iterator MachOObjectFile::section_rel_begin(DataRefImpl Sec) const {
2065   DataRefImpl Ret;
2066   Ret.d.a = Sec.d.a;
2067   Ret.d.b = 0;
2068   return relocation_iterator(RelocationRef(Ret, this));
2069 }
2070 
2071 relocation_iterator
section_rel_end(DataRefImpl Sec) const2072 MachOObjectFile::section_rel_end(DataRefImpl Sec) const {
2073   uint32_t Num;
2074   if (is64Bit()) {
2075     MachO::section_64 Sect = getSection64(Sec);
2076     Num = Sect.nreloc;
2077   } else {
2078     MachO::section Sect = getSection(Sec);
2079     Num = Sect.nreloc;
2080   }
2081 
2082   DataRefImpl Ret;
2083   Ret.d.a = Sec.d.a;
2084   Ret.d.b = Num;
2085   return relocation_iterator(RelocationRef(Ret, this));
2086 }
2087 
extrel_begin() const2088 relocation_iterator MachOObjectFile::extrel_begin() const {
2089   DataRefImpl Ret;
2090   // for DYSYMTAB symbols, Ret.d.a == 0 for external relocations
2091   Ret.d.a = 0; // Would normally be a section index.
2092   Ret.d.b = 0; // Index into the external relocations
2093   return relocation_iterator(RelocationRef(Ret, this));
2094 }
2095 
extrel_end() const2096 relocation_iterator MachOObjectFile::extrel_end() const {
2097   MachO::dysymtab_command DysymtabLoadCmd = getDysymtabLoadCommand();
2098   DataRefImpl Ret;
2099   // for DYSYMTAB symbols, Ret.d.a == 0 for external relocations
2100   Ret.d.a = 0; // Would normally be a section index.
2101   Ret.d.b = DysymtabLoadCmd.nextrel; // Index into the external relocations
2102   return relocation_iterator(RelocationRef(Ret, this));
2103 }
2104 
locrel_begin() const2105 relocation_iterator MachOObjectFile::locrel_begin() const {
2106   DataRefImpl Ret;
2107   // for DYSYMTAB symbols, Ret.d.a == 1 for local relocations
2108   Ret.d.a = 1; // Would normally be a section index.
2109   Ret.d.b = 0; // Index into the local relocations
2110   return relocation_iterator(RelocationRef(Ret, this));
2111 }
2112 
locrel_end() const2113 relocation_iterator MachOObjectFile::locrel_end() const {
2114   MachO::dysymtab_command DysymtabLoadCmd = getDysymtabLoadCommand();
2115   DataRefImpl Ret;
2116   // for DYSYMTAB symbols, Ret.d.a == 1 for local relocations
2117   Ret.d.a = 1; // Would normally be a section index.
2118   Ret.d.b = DysymtabLoadCmd.nlocrel; // Index into the local relocations
2119   return relocation_iterator(RelocationRef(Ret, this));
2120 }
2121 
moveRelocationNext(DataRefImpl & Rel) const2122 void MachOObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
2123   ++Rel.d.b;
2124 }
2125 
getRelocationOffset(DataRefImpl Rel) const2126 uint64_t MachOObjectFile::getRelocationOffset(DataRefImpl Rel) const {
2127   assert((getHeader().filetype == MachO::MH_OBJECT ||
2128           getHeader().filetype == MachO::MH_KEXT_BUNDLE) &&
2129          "Only implemented for MH_OBJECT && MH_KEXT_BUNDLE");
2130   MachO::any_relocation_info RE = getRelocation(Rel);
2131   return getAnyRelocationAddress(RE);
2132 }
2133 
2134 symbol_iterator
getRelocationSymbol(DataRefImpl Rel) const2135 MachOObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
2136   MachO::any_relocation_info RE = getRelocation(Rel);
2137   if (isRelocationScattered(RE))
2138     return symbol_end();
2139 
2140   uint32_t SymbolIdx = getPlainRelocationSymbolNum(RE);
2141   bool isExtern = getPlainRelocationExternal(RE);
2142   if (!isExtern)
2143     return symbol_end();
2144 
2145   MachO::symtab_command S = getSymtabLoadCommand();
2146   unsigned SymbolTableEntrySize = is64Bit() ?
2147     sizeof(MachO::nlist_64) :
2148     sizeof(MachO::nlist);
2149   uint64_t Offset = S.symoff + SymbolIdx * SymbolTableEntrySize;
2150   DataRefImpl Sym;
2151   Sym.p = reinterpret_cast<uintptr_t>(getPtr(*this, Offset));
2152   return symbol_iterator(SymbolRef(Sym, this));
2153 }
2154 
2155 section_iterator
getRelocationSection(DataRefImpl Rel) const2156 MachOObjectFile::getRelocationSection(DataRefImpl Rel) const {
2157   return section_iterator(getAnyRelocationSection(getRelocation(Rel)));
2158 }
2159 
getRelocationType(DataRefImpl Rel) const2160 uint64_t MachOObjectFile::getRelocationType(DataRefImpl Rel) const {
2161   MachO::any_relocation_info RE = getRelocation(Rel);
2162   return getAnyRelocationType(RE);
2163 }
2164 
getRelocationTypeName(DataRefImpl Rel,SmallVectorImpl<char> & Result) const2165 void MachOObjectFile::getRelocationTypeName(
2166     DataRefImpl Rel, SmallVectorImpl<char> &Result) const {
2167   StringRef res;
2168   uint64_t RType = getRelocationType(Rel);
2169 
2170   unsigned Arch = this->getArch();
2171 
2172   switch (Arch) {
2173     case Triple::x86: {
2174       static const char *const Table[] =  {
2175         "GENERIC_RELOC_VANILLA",
2176         "GENERIC_RELOC_PAIR",
2177         "GENERIC_RELOC_SECTDIFF",
2178         "GENERIC_RELOC_PB_LA_PTR",
2179         "GENERIC_RELOC_LOCAL_SECTDIFF",
2180         "GENERIC_RELOC_TLV" };
2181 
2182       if (RType > 5)
2183         res = "Unknown";
2184       else
2185         res = Table[RType];
2186       break;
2187     }
2188     case Triple::x86_64: {
2189       static const char *const Table[] =  {
2190         "X86_64_RELOC_UNSIGNED",
2191         "X86_64_RELOC_SIGNED",
2192         "X86_64_RELOC_BRANCH",
2193         "X86_64_RELOC_GOT_LOAD",
2194         "X86_64_RELOC_GOT",
2195         "X86_64_RELOC_SUBTRACTOR",
2196         "X86_64_RELOC_SIGNED_1",
2197         "X86_64_RELOC_SIGNED_2",
2198         "X86_64_RELOC_SIGNED_4",
2199         "X86_64_RELOC_TLV" };
2200 
2201       if (RType > 9)
2202         res = "Unknown";
2203       else
2204         res = Table[RType];
2205       break;
2206     }
2207     case Triple::arm: {
2208       static const char *const Table[] =  {
2209         "ARM_RELOC_VANILLA",
2210         "ARM_RELOC_PAIR",
2211         "ARM_RELOC_SECTDIFF",
2212         "ARM_RELOC_LOCAL_SECTDIFF",
2213         "ARM_RELOC_PB_LA_PTR",
2214         "ARM_RELOC_BR24",
2215         "ARM_THUMB_RELOC_BR22",
2216         "ARM_THUMB_32BIT_BRANCH",
2217         "ARM_RELOC_HALF",
2218         "ARM_RELOC_HALF_SECTDIFF" };
2219 
2220       if (RType > 9)
2221         res = "Unknown";
2222       else
2223         res = Table[RType];
2224       break;
2225     }
2226     case Triple::aarch64:
2227     case Triple::aarch64_32: {
2228       static const char *const Table[] = {
2229         "ARM64_RELOC_UNSIGNED",           "ARM64_RELOC_SUBTRACTOR",
2230         "ARM64_RELOC_BRANCH26",           "ARM64_RELOC_PAGE21",
2231         "ARM64_RELOC_PAGEOFF12",          "ARM64_RELOC_GOT_LOAD_PAGE21",
2232         "ARM64_RELOC_GOT_LOAD_PAGEOFF12", "ARM64_RELOC_POINTER_TO_GOT",
2233         "ARM64_RELOC_TLVP_LOAD_PAGE21",   "ARM64_RELOC_TLVP_LOAD_PAGEOFF12",
2234         "ARM64_RELOC_ADDEND"
2235       };
2236 
2237       if (RType >= array_lengthof(Table))
2238         res = "Unknown";
2239       else
2240         res = Table[RType];
2241       break;
2242     }
2243     case Triple::ppc: {
2244       static const char *const Table[] =  {
2245         "PPC_RELOC_VANILLA",
2246         "PPC_RELOC_PAIR",
2247         "PPC_RELOC_BR14",
2248         "PPC_RELOC_BR24",
2249         "PPC_RELOC_HI16",
2250         "PPC_RELOC_LO16",
2251         "PPC_RELOC_HA16",
2252         "PPC_RELOC_LO14",
2253         "PPC_RELOC_SECTDIFF",
2254         "PPC_RELOC_PB_LA_PTR",
2255         "PPC_RELOC_HI16_SECTDIFF",
2256         "PPC_RELOC_LO16_SECTDIFF",
2257         "PPC_RELOC_HA16_SECTDIFF",
2258         "PPC_RELOC_JBSR",
2259         "PPC_RELOC_LO14_SECTDIFF",
2260         "PPC_RELOC_LOCAL_SECTDIFF" };
2261 
2262       if (RType > 15)
2263         res = "Unknown";
2264       else
2265         res = Table[RType];
2266       break;
2267     }
2268     case Triple::UnknownArch:
2269       res = "Unknown";
2270       break;
2271   }
2272   Result.append(res.begin(), res.end());
2273 }
2274 
getRelocationLength(DataRefImpl Rel) const2275 uint8_t MachOObjectFile::getRelocationLength(DataRefImpl Rel) const {
2276   MachO::any_relocation_info RE = getRelocation(Rel);
2277   return getAnyRelocationLength(RE);
2278 }
2279 
2280 //
2281 // guessLibraryShortName() is passed a name of a dynamic library and returns a
2282 // guess on what the short name is.  Then name is returned as a substring of the
2283 // StringRef Name passed in.  The name of the dynamic library is recognized as
2284 // a framework if it has one of the two following forms:
2285 //      Foo.framework/Versions/A/Foo
2286 //      Foo.framework/Foo
2287 // Where A and Foo can be any string.  And may contain a trailing suffix
2288 // starting with an underbar.  If the Name is recognized as a framework then
2289 // isFramework is set to true else it is set to false.  If the Name has a
2290 // suffix then Suffix is set to the substring in Name that contains the suffix
2291 // else it is set to a NULL StringRef.
2292 //
2293 // The Name of the dynamic library is recognized as a library name if it has
2294 // one of the two following forms:
2295 //      libFoo.A.dylib
2296 //      libFoo.dylib
2297 //
2298 // The library may have a suffix trailing the name Foo of the form:
2299 //      libFoo_profile.A.dylib
2300 //      libFoo_profile.dylib
2301 // These dyld image suffixes are separated from the short name by a '_'
2302 // character. Because the '_' character is commonly used to separate words in
2303 // filenames guessLibraryShortName() cannot reliably separate a dylib's short
2304 // name from an arbitrary image suffix; imagine if both the short name and the
2305 // suffix contains an '_' character! To better deal with this ambiguity,
2306 // guessLibraryShortName() will recognize only "_debug" and "_profile" as valid
2307 // Suffix values. Calling code needs to be tolerant of guessLibraryShortName()
2308 // guessing incorrectly.
2309 //
2310 // The Name of the dynamic library is also recognized as a library name if it
2311 // has the following form:
2312 //      Foo.qtx
2313 //
2314 // If the Name of the dynamic library is none of the forms above then a NULL
2315 // StringRef is returned.
guessLibraryShortName(StringRef Name,bool & isFramework,StringRef & Suffix)2316 StringRef MachOObjectFile::guessLibraryShortName(StringRef Name,
2317                                                  bool &isFramework,
2318                                                  StringRef &Suffix) {
2319   StringRef Foo, F, DotFramework, V, Dylib, Lib, Dot, Qtx;
2320   size_t a, b, c, d, Idx;
2321 
2322   isFramework = false;
2323   Suffix = StringRef();
2324 
2325   // Pull off the last component and make Foo point to it
2326   a = Name.rfind('/');
2327   if (a == Name.npos || a == 0)
2328     goto guess_library;
2329   Foo = Name.slice(a+1, Name.npos);
2330 
2331   // Look for a suffix starting with a '_'
2332   Idx = Foo.rfind('_');
2333   if (Idx != Foo.npos && Foo.size() >= 2) {
2334     Suffix = Foo.slice(Idx, Foo.npos);
2335     if (Suffix != "_debug" && Suffix != "_profile")
2336       Suffix = StringRef();
2337     else
2338       Foo = Foo.slice(0, Idx);
2339   }
2340 
2341   // First look for the form Foo.framework/Foo
2342   b = Name.rfind('/', a);
2343   if (b == Name.npos)
2344     Idx = 0;
2345   else
2346     Idx = b+1;
2347   F = Name.slice(Idx, Idx + Foo.size());
2348   DotFramework = Name.slice(Idx + Foo.size(),
2349                             Idx + Foo.size() + sizeof(".framework/")-1);
2350   if (F == Foo && DotFramework == ".framework/") {
2351     isFramework = true;
2352     return Foo;
2353   }
2354 
2355   // Next look for the form Foo.framework/Versions/A/Foo
2356   if (b == Name.npos)
2357     goto guess_library;
2358   c =  Name.rfind('/', b);
2359   if (c == Name.npos || c == 0)
2360     goto guess_library;
2361   V = Name.slice(c+1, Name.npos);
2362   if (!V.startswith("Versions/"))
2363     goto guess_library;
2364   d =  Name.rfind('/', c);
2365   if (d == Name.npos)
2366     Idx = 0;
2367   else
2368     Idx = d+1;
2369   F = Name.slice(Idx, Idx + Foo.size());
2370   DotFramework = Name.slice(Idx + Foo.size(),
2371                             Idx + Foo.size() + sizeof(".framework/")-1);
2372   if (F == Foo && DotFramework == ".framework/") {
2373     isFramework = true;
2374     return Foo;
2375   }
2376 
2377 guess_library:
2378   // pull off the suffix after the "." and make a point to it
2379   a = Name.rfind('.');
2380   if (a == Name.npos || a == 0)
2381     return StringRef();
2382   Dylib = Name.slice(a, Name.npos);
2383   if (Dylib != ".dylib")
2384     goto guess_qtx;
2385 
2386   // First pull off the version letter for the form Foo.A.dylib if any.
2387   if (a >= 3) {
2388     Dot = Name.slice(a-2, a-1);
2389     if (Dot == ".")
2390       a = a - 2;
2391   }
2392 
2393   b = Name.rfind('/', a);
2394   if (b == Name.npos)
2395     b = 0;
2396   else
2397     b = b+1;
2398   // ignore any suffix after an underbar like Foo_profile.A.dylib
2399   Idx = Name.rfind('_');
2400   if (Idx != Name.npos && Idx != b) {
2401     Lib = Name.slice(b, Idx);
2402     Suffix = Name.slice(Idx, a);
2403     if (Suffix != "_debug" && Suffix != "_profile") {
2404       Suffix = StringRef();
2405       Lib = Name.slice(b, a);
2406     }
2407   }
2408   else
2409     Lib = Name.slice(b, a);
2410   // There are incorrect library names of the form:
2411   // libATS.A_profile.dylib so check for these.
2412   if (Lib.size() >= 3) {
2413     Dot = Lib.slice(Lib.size()-2, Lib.size()-1);
2414     if (Dot == ".")
2415       Lib = Lib.slice(0, Lib.size()-2);
2416   }
2417   return Lib;
2418 
2419 guess_qtx:
2420   Qtx = Name.slice(a, Name.npos);
2421   if (Qtx != ".qtx")
2422     return StringRef();
2423   b = Name.rfind('/', a);
2424   if (b == Name.npos)
2425     Lib = Name.slice(0, a);
2426   else
2427     Lib = Name.slice(b+1, a);
2428   // There are library names of the form: QT.A.qtx so check for these.
2429   if (Lib.size() >= 3) {
2430     Dot = Lib.slice(Lib.size()-2, Lib.size()-1);
2431     if (Dot == ".")
2432       Lib = Lib.slice(0, Lib.size()-2);
2433   }
2434   return Lib;
2435 }
2436 
2437 // getLibraryShortNameByIndex() is used to get the short name of the library
2438 // for an undefined symbol in a linked Mach-O binary that was linked with the
2439 // normal two-level namespace default (that is MH_TWOLEVEL in the header).
2440 // It is passed the index (0 - based) of the library as translated from
2441 // GET_LIBRARY_ORDINAL (1 - based).
getLibraryShortNameByIndex(unsigned Index,StringRef & Res) const2442 std::error_code MachOObjectFile::getLibraryShortNameByIndex(unsigned Index,
2443                                                          StringRef &Res) const {
2444   if (Index >= Libraries.size())
2445     return object_error::parse_failed;
2446 
2447   // If the cache of LibrariesShortNames is not built up do that first for
2448   // all the Libraries.
2449   if (LibrariesShortNames.size() == 0) {
2450     for (unsigned i = 0; i < Libraries.size(); i++) {
2451       auto CommandOrErr =
2452         getStructOrErr<MachO::dylib_command>(*this, Libraries[i]);
2453       if (!CommandOrErr)
2454         return object_error::parse_failed;
2455       MachO::dylib_command D = CommandOrErr.get();
2456       if (D.dylib.name >= D.cmdsize)
2457         return object_error::parse_failed;
2458       const char *P = (const char *)(Libraries[i]) + D.dylib.name;
2459       StringRef Name = StringRef(P);
2460       if (D.dylib.name+Name.size() >= D.cmdsize)
2461         return object_error::parse_failed;
2462       StringRef Suffix;
2463       bool isFramework;
2464       StringRef shortName = guessLibraryShortName(Name, isFramework, Suffix);
2465       if (shortName.empty())
2466         LibrariesShortNames.push_back(Name);
2467       else
2468         LibrariesShortNames.push_back(shortName);
2469     }
2470   }
2471 
2472   Res = LibrariesShortNames[Index];
2473   return std::error_code();
2474 }
2475 
getLibraryCount() const2476 uint32_t MachOObjectFile::getLibraryCount() const {
2477   return Libraries.size();
2478 }
2479 
2480 section_iterator
getRelocationRelocatedSection(relocation_iterator Rel) const2481 MachOObjectFile::getRelocationRelocatedSection(relocation_iterator Rel) const {
2482   DataRefImpl Sec;
2483   Sec.d.a = Rel->getRawDataRefImpl().d.a;
2484   return section_iterator(SectionRef(Sec, this));
2485 }
2486 
symbol_begin() const2487 basic_symbol_iterator MachOObjectFile::symbol_begin() const {
2488   DataRefImpl DRI;
2489   MachO::symtab_command Symtab = getSymtabLoadCommand();
2490   if (!SymtabLoadCmd || Symtab.nsyms == 0)
2491     return basic_symbol_iterator(SymbolRef(DRI, this));
2492 
2493   return getSymbolByIndex(0);
2494 }
2495 
symbol_end() const2496 basic_symbol_iterator MachOObjectFile::symbol_end() const {
2497   DataRefImpl DRI;
2498   MachO::symtab_command Symtab = getSymtabLoadCommand();
2499   if (!SymtabLoadCmd || Symtab.nsyms == 0)
2500     return basic_symbol_iterator(SymbolRef(DRI, this));
2501 
2502   unsigned SymbolTableEntrySize = is64Bit() ?
2503     sizeof(MachO::nlist_64) :
2504     sizeof(MachO::nlist);
2505   unsigned Offset = Symtab.symoff +
2506     Symtab.nsyms * SymbolTableEntrySize;
2507   DRI.p = reinterpret_cast<uintptr_t>(getPtr(*this, Offset));
2508   return basic_symbol_iterator(SymbolRef(DRI, this));
2509 }
2510 
getSymbolByIndex(unsigned Index) const2511 symbol_iterator MachOObjectFile::getSymbolByIndex(unsigned Index) const {
2512   MachO::symtab_command Symtab = getSymtabLoadCommand();
2513   if (!SymtabLoadCmd || Index >= Symtab.nsyms)
2514     report_fatal_error("Requested symbol index is out of range.");
2515   unsigned SymbolTableEntrySize =
2516     is64Bit() ? sizeof(MachO::nlist_64) : sizeof(MachO::nlist);
2517   DataRefImpl DRI;
2518   DRI.p = reinterpret_cast<uintptr_t>(getPtr(*this, Symtab.symoff));
2519   DRI.p += Index * SymbolTableEntrySize;
2520   return basic_symbol_iterator(SymbolRef(DRI, this));
2521 }
2522 
getSymbolIndex(DataRefImpl Symb) const2523 uint64_t MachOObjectFile::getSymbolIndex(DataRefImpl Symb) const {
2524   MachO::symtab_command Symtab = getSymtabLoadCommand();
2525   if (!SymtabLoadCmd)
2526     report_fatal_error("getSymbolIndex() called with no symbol table symbol");
2527   unsigned SymbolTableEntrySize =
2528     is64Bit() ? sizeof(MachO::nlist_64) : sizeof(MachO::nlist);
2529   DataRefImpl DRIstart;
2530   DRIstart.p = reinterpret_cast<uintptr_t>(getPtr(*this, Symtab.symoff));
2531   uint64_t Index = (Symb.p - DRIstart.p) / SymbolTableEntrySize;
2532   return Index;
2533 }
2534 
section_begin() const2535 section_iterator MachOObjectFile::section_begin() const {
2536   DataRefImpl DRI;
2537   return section_iterator(SectionRef(DRI, this));
2538 }
2539 
section_end() const2540 section_iterator MachOObjectFile::section_end() const {
2541   DataRefImpl DRI;
2542   DRI.d.a = Sections.size();
2543   return section_iterator(SectionRef(DRI, this));
2544 }
2545 
getBytesInAddress() const2546 uint8_t MachOObjectFile::getBytesInAddress() const {
2547   return is64Bit() ? 8 : 4;
2548 }
2549 
getFileFormatName() const2550 StringRef MachOObjectFile::getFileFormatName() const {
2551   unsigned CPUType = getCPUType(*this);
2552   if (!is64Bit()) {
2553     switch (CPUType) {
2554     case MachO::CPU_TYPE_I386:
2555       return "Mach-O 32-bit i386";
2556     case MachO::CPU_TYPE_ARM:
2557       return "Mach-O arm";
2558     case MachO::CPU_TYPE_ARM64_32:
2559       return "Mach-O arm64 (ILP32)";
2560     case MachO::CPU_TYPE_POWERPC:
2561       return "Mach-O 32-bit ppc";
2562     default:
2563       return "Mach-O 32-bit unknown";
2564     }
2565   }
2566 
2567   switch (CPUType) {
2568   case MachO::CPU_TYPE_X86_64:
2569     return "Mach-O 64-bit x86-64";
2570   case MachO::CPU_TYPE_ARM64:
2571     return "Mach-O arm64";
2572   case MachO::CPU_TYPE_POWERPC64:
2573     return "Mach-O 64-bit ppc64";
2574   default:
2575     return "Mach-O 64-bit unknown";
2576   }
2577 }
2578 
getArch(uint32_t CPUType,uint32_t CPUSubType)2579 Triple::ArchType MachOObjectFile::getArch(uint32_t CPUType, uint32_t CPUSubType) {
2580   switch (CPUType) {
2581   case MachO::CPU_TYPE_I386:
2582     return Triple::x86;
2583   case MachO::CPU_TYPE_X86_64:
2584     return Triple::x86_64;
2585   case MachO::CPU_TYPE_ARM:
2586     return Triple::arm;
2587   case MachO::CPU_TYPE_ARM64:
2588     return Triple::aarch64;
2589   case MachO::CPU_TYPE_ARM64_32:
2590     return Triple::aarch64_32;
2591   case MachO::CPU_TYPE_POWERPC:
2592     return Triple::ppc;
2593   case MachO::CPU_TYPE_POWERPC64:
2594     return Triple::ppc64;
2595   default:
2596     return Triple::UnknownArch;
2597   }
2598 }
2599 
getArchTriple(uint32_t CPUType,uint32_t CPUSubType,const char ** McpuDefault,const char ** ArchFlag)2600 Triple MachOObjectFile::getArchTriple(uint32_t CPUType, uint32_t CPUSubType,
2601                                       const char **McpuDefault,
2602                                       const char **ArchFlag) {
2603   if (McpuDefault)
2604     *McpuDefault = nullptr;
2605   if (ArchFlag)
2606     *ArchFlag = nullptr;
2607 
2608   switch (CPUType) {
2609   case MachO::CPU_TYPE_I386:
2610     switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2611     case MachO::CPU_SUBTYPE_I386_ALL:
2612       if (ArchFlag)
2613         *ArchFlag = "i386";
2614       return Triple("i386-apple-darwin");
2615     default:
2616       return Triple();
2617     }
2618   case MachO::CPU_TYPE_X86_64:
2619     switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2620     case MachO::CPU_SUBTYPE_X86_64_ALL:
2621       if (ArchFlag)
2622         *ArchFlag = "x86_64";
2623       return Triple("x86_64-apple-darwin");
2624     case MachO::CPU_SUBTYPE_X86_64_H:
2625       if (ArchFlag)
2626         *ArchFlag = "x86_64h";
2627       return Triple("x86_64h-apple-darwin");
2628     default:
2629       return Triple();
2630     }
2631   case MachO::CPU_TYPE_ARM:
2632     switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2633     case MachO::CPU_SUBTYPE_ARM_V4T:
2634       if (ArchFlag)
2635         *ArchFlag = "armv4t";
2636       return Triple("armv4t-apple-darwin");
2637     case MachO::CPU_SUBTYPE_ARM_V5TEJ:
2638       if (ArchFlag)
2639         *ArchFlag = "armv5e";
2640       return Triple("armv5e-apple-darwin");
2641     case MachO::CPU_SUBTYPE_ARM_XSCALE:
2642       if (ArchFlag)
2643         *ArchFlag = "xscale";
2644       return Triple("xscale-apple-darwin");
2645     case MachO::CPU_SUBTYPE_ARM_V6:
2646       if (ArchFlag)
2647         *ArchFlag = "armv6";
2648       return Triple("armv6-apple-darwin");
2649     case MachO::CPU_SUBTYPE_ARM_V6M:
2650       if (McpuDefault)
2651         *McpuDefault = "cortex-m0";
2652       if (ArchFlag)
2653         *ArchFlag = "armv6m";
2654       return Triple("armv6m-apple-darwin");
2655     case MachO::CPU_SUBTYPE_ARM_V7:
2656       if (ArchFlag)
2657         *ArchFlag = "armv7";
2658       return Triple("armv7-apple-darwin");
2659     case MachO::CPU_SUBTYPE_ARM_V7EM:
2660       if (McpuDefault)
2661         *McpuDefault = "cortex-m4";
2662       if (ArchFlag)
2663         *ArchFlag = "armv7em";
2664       return Triple("thumbv7em-apple-darwin");
2665     case MachO::CPU_SUBTYPE_ARM_V7K:
2666       if (McpuDefault)
2667         *McpuDefault = "cortex-a7";
2668       if (ArchFlag)
2669         *ArchFlag = "armv7k";
2670       return Triple("armv7k-apple-darwin");
2671     case MachO::CPU_SUBTYPE_ARM_V7M:
2672       if (McpuDefault)
2673         *McpuDefault = "cortex-m3";
2674       if (ArchFlag)
2675         *ArchFlag = "armv7m";
2676       return Triple("thumbv7m-apple-darwin");
2677     case MachO::CPU_SUBTYPE_ARM_V7S:
2678       if (McpuDefault)
2679         *McpuDefault = "cortex-a7";
2680       if (ArchFlag)
2681         *ArchFlag = "armv7s";
2682       return Triple("armv7s-apple-darwin");
2683     default:
2684       return Triple();
2685     }
2686   case MachO::CPU_TYPE_ARM64:
2687     switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2688     case MachO::CPU_SUBTYPE_ARM64_ALL:
2689       if (McpuDefault)
2690         *McpuDefault = "cyclone";
2691       if (ArchFlag)
2692         *ArchFlag = "arm64";
2693       return Triple("arm64-apple-darwin");
2694     default:
2695       return Triple();
2696     }
2697   case MachO::CPU_TYPE_ARM64_32:
2698     switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2699     case MachO::CPU_SUBTYPE_ARM64_32_V8:
2700       if (McpuDefault)
2701         *McpuDefault = "cyclone";
2702       if (ArchFlag)
2703         *ArchFlag = "arm64_32";
2704       return Triple("arm64_32-apple-darwin");
2705     default:
2706       return Triple();
2707     }
2708   case MachO::CPU_TYPE_POWERPC:
2709     switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2710     case MachO::CPU_SUBTYPE_POWERPC_ALL:
2711       if (ArchFlag)
2712         *ArchFlag = "ppc";
2713       return Triple("ppc-apple-darwin");
2714     default:
2715       return Triple();
2716     }
2717   case MachO::CPU_TYPE_POWERPC64:
2718     switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2719     case MachO::CPU_SUBTYPE_POWERPC_ALL:
2720       if (ArchFlag)
2721         *ArchFlag = "ppc64";
2722       return Triple("ppc64-apple-darwin");
2723     default:
2724       return Triple();
2725     }
2726   default:
2727     return Triple();
2728   }
2729 }
2730 
getHostArch()2731 Triple MachOObjectFile::getHostArch() {
2732   return Triple(sys::getDefaultTargetTriple());
2733 }
2734 
isValidArch(StringRef ArchFlag)2735 bool MachOObjectFile::isValidArch(StringRef ArchFlag) {
2736   auto validArchs = getValidArchs();
2737   return llvm::find(validArchs, ArchFlag) != validArchs.end();
2738 }
2739 
getValidArchs()2740 ArrayRef<StringRef> MachOObjectFile::getValidArchs() {
2741   static const std::array<StringRef, 17> validArchs = {{
2742       "i386",   "x86_64", "x86_64h",  "armv4t",  "arm",    "armv5e",
2743       "armv6",  "armv6m", "armv7",    "armv7em", "armv7k", "armv7m",
2744       "armv7s", "arm64",  "arm64_32", "ppc",     "ppc64",
2745   }};
2746 
2747   return validArchs;
2748 }
2749 
getArch() const2750 Triple::ArchType MachOObjectFile::getArch() const {
2751   return getArch(getCPUType(*this), getCPUSubType(*this));
2752 }
2753 
getArchTriple(const char ** McpuDefault) const2754 Triple MachOObjectFile::getArchTriple(const char **McpuDefault) const {
2755   return getArchTriple(Header.cputype, Header.cpusubtype, McpuDefault);
2756 }
2757 
section_rel_begin(unsigned Index) const2758 relocation_iterator MachOObjectFile::section_rel_begin(unsigned Index) const {
2759   DataRefImpl DRI;
2760   DRI.d.a = Index;
2761   return section_rel_begin(DRI);
2762 }
2763 
section_rel_end(unsigned Index) const2764 relocation_iterator MachOObjectFile::section_rel_end(unsigned Index) const {
2765   DataRefImpl DRI;
2766   DRI.d.a = Index;
2767   return section_rel_end(DRI);
2768 }
2769 
begin_dices() const2770 dice_iterator MachOObjectFile::begin_dices() const {
2771   DataRefImpl DRI;
2772   if (!DataInCodeLoadCmd)
2773     return dice_iterator(DiceRef(DRI, this));
2774 
2775   MachO::linkedit_data_command DicLC = getDataInCodeLoadCommand();
2776   DRI.p = reinterpret_cast<uintptr_t>(getPtr(*this, DicLC.dataoff));
2777   return dice_iterator(DiceRef(DRI, this));
2778 }
2779 
end_dices() const2780 dice_iterator MachOObjectFile::end_dices() const {
2781   DataRefImpl DRI;
2782   if (!DataInCodeLoadCmd)
2783     return dice_iterator(DiceRef(DRI, this));
2784 
2785   MachO::linkedit_data_command DicLC = getDataInCodeLoadCommand();
2786   unsigned Offset = DicLC.dataoff + DicLC.datasize;
2787   DRI.p = reinterpret_cast<uintptr_t>(getPtr(*this, Offset));
2788   return dice_iterator(DiceRef(DRI, this));
2789 }
2790 
ExportEntry(Error * E,const MachOObjectFile * O,ArrayRef<uint8_t> T)2791 ExportEntry::ExportEntry(Error *E, const MachOObjectFile *O,
2792                          ArrayRef<uint8_t> T) : E(E), O(O), Trie(T) {}
2793 
moveToFirst()2794 void ExportEntry::moveToFirst() {
2795   ErrorAsOutParameter ErrAsOutParam(E);
2796   pushNode(0);
2797   if (*E)
2798     return;
2799   pushDownUntilBottom();
2800 }
2801 
moveToEnd()2802 void ExportEntry::moveToEnd() {
2803   Stack.clear();
2804   Done = true;
2805 }
2806 
operator ==(const ExportEntry & Other) const2807 bool ExportEntry::operator==(const ExportEntry &Other) const {
2808   // Common case, one at end, other iterating from begin.
2809   if (Done || Other.Done)
2810     return (Done == Other.Done);
2811   // Not equal if different stack sizes.
2812   if (Stack.size() != Other.Stack.size())
2813     return false;
2814   // Not equal if different cumulative strings.
2815   if (!CumulativeString.equals(Other.CumulativeString))
2816     return false;
2817   // Equal if all nodes in both stacks match.
2818   for (unsigned i=0; i < Stack.size(); ++i) {
2819     if (Stack[i].Start != Other.Stack[i].Start)
2820       return false;
2821   }
2822   return true;
2823 }
2824 
readULEB128(const uint8_t * & Ptr,const char ** error)2825 uint64_t ExportEntry::readULEB128(const uint8_t *&Ptr, const char **error) {
2826   unsigned Count;
2827   uint64_t Result = decodeULEB128(Ptr, &Count, Trie.end(), error);
2828   Ptr += Count;
2829   if (Ptr > Trie.end())
2830     Ptr = Trie.end();
2831   return Result;
2832 }
2833 
name() const2834 StringRef ExportEntry::name() const {
2835   return CumulativeString;
2836 }
2837 
flags() const2838 uint64_t ExportEntry::flags() const {
2839   return Stack.back().Flags;
2840 }
2841 
address() const2842 uint64_t ExportEntry::address() const {
2843   return Stack.back().Address;
2844 }
2845 
other() const2846 uint64_t ExportEntry::other() const {
2847   return Stack.back().Other;
2848 }
2849 
otherName() const2850 StringRef ExportEntry::otherName() const {
2851   const char* ImportName = Stack.back().ImportName;
2852   if (ImportName)
2853     return StringRef(ImportName);
2854   return StringRef();
2855 }
2856 
nodeOffset() const2857 uint32_t ExportEntry::nodeOffset() const {
2858   return Stack.back().Start - Trie.begin();
2859 }
2860 
NodeState(const uint8_t * Ptr)2861 ExportEntry::NodeState::NodeState(const uint8_t *Ptr)
2862     : Start(Ptr), Current(Ptr) {}
2863 
pushNode(uint64_t offset)2864 void ExportEntry::pushNode(uint64_t offset) {
2865   ErrorAsOutParameter ErrAsOutParam(E);
2866   const uint8_t *Ptr = Trie.begin() + offset;
2867   NodeState State(Ptr);
2868   const char *error;
2869   uint64_t ExportInfoSize = readULEB128(State.Current, &error);
2870   if (error) {
2871     *E = malformedError("export info size " + Twine(error) +
2872                         " in export trie data at node: 0x" +
2873                         Twine::utohexstr(offset));
2874     moveToEnd();
2875     return;
2876   }
2877   State.IsExportNode = (ExportInfoSize != 0);
2878   const uint8_t* Children = State.Current + ExportInfoSize;
2879   if (Children > Trie.end()) {
2880     *E = malformedError(
2881         "export info size: 0x" + Twine::utohexstr(ExportInfoSize) +
2882         " in export trie data at node: 0x" + Twine::utohexstr(offset) +
2883         " too big and extends past end of trie data");
2884     moveToEnd();
2885     return;
2886   }
2887   if (State.IsExportNode) {
2888     const uint8_t *ExportStart = State.Current;
2889     State.Flags = readULEB128(State.Current, &error);
2890     if (error) {
2891       *E = malformedError("flags " + Twine(error) +
2892                           " in export trie data at node: 0x" +
2893                           Twine::utohexstr(offset));
2894       moveToEnd();
2895       return;
2896     }
2897     uint64_t Kind = State.Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK;
2898     if (State.Flags != 0 &&
2899         (Kind != MachO::EXPORT_SYMBOL_FLAGS_KIND_REGULAR &&
2900          Kind != MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE &&
2901          Kind != MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL)) {
2902       *E = malformedError(
2903           "unsupported exported symbol kind: " + Twine((int)Kind) +
2904           " in flags: 0x" + Twine::utohexstr(State.Flags) +
2905           " in export trie data at node: 0x" + Twine::utohexstr(offset));
2906       moveToEnd();
2907       return;
2908     }
2909     if (State.Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT) {
2910       State.Address = 0;
2911       State.Other = readULEB128(State.Current, &error); // dylib ordinal
2912       if (error) {
2913         *E = malformedError("dylib ordinal of re-export " + Twine(error) +
2914                             " in export trie data at node: 0x" +
2915                             Twine::utohexstr(offset));
2916         moveToEnd();
2917         return;
2918       }
2919       if (O != nullptr) {
2920         if (State.Other > O->getLibraryCount()) {
2921           *E = malformedError(
2922               "bad library ordinal: " + Twine((int)State.Other) + " (max " +
2923               Twine((int)O->getLibraryCount()) +
2924               ") in export trie data at node: 0x" + Twine::utohexstr(offset));
2925           moveToEnd();
2926           return;
2927         }
2928       }
2929       State.ImportName = reinterpret_cast<const char*>(State.Current);
2930       if (*State.ImportName == '\0') {
2931         State.Current++;
2932       } else {
2933         const uint8_t *End = State.Current + 1;
2934         if (End >= Trie.end()) {
2935           *E = malformedError("import name of re-export in export trie data at "
2936                               "node: 0x" +
2937                               Twine::utohexstr(offset) +
2938                               " starts past end of trie data");
2939           moveToEnd();
2940           return;
2941         }
2942         while(*End != '\0' && End < Trie.end())
2943           End++;
2944         if (*End != '\0') {
2945           *E = malformedError("import name of re-export in export trie data at "
2946                               "node: 0x" +
2947                               Twine::utohexstr(offset) +
2948                               " extends past end of trie data");
2949           moveToEnd();
2950           return;
2951         }
2952         State.Current = End + 1;
2953       }
2954     } else {
2955       State.Address = readULEB128(State.Current, &error);
2956       if (error) {
2957         *E = malformedError("address " + Twine(error) +
2958                             " in export trie data at node: 0x" +
2959                             Twine::utohexstr(offset));
2960         moveToEnd();
2961         return;
2962       }
2963       if (State.Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER) {
2964         State.Other = readULEB128(State.Current, &error);
2965         if (error) {
2966           *E = malformedError("resolver of stub and resolver " + Twine(error) +
2967                               " in export trie data at node: 0x" +
2968                               Twine::utohexstr(offset));
2969           moveToEnd();
2970           return;
2971         }
2972       }
2973     }
2974     if(ExportStart + ExportInfoSize != State.Current) {
2975       *E = malformedError(
2976           "inconsistant export info size: 0x" +
2977           Twine::utohexstr(ExportInfoSize) + " where actual size was: 0x" +
2978           Twine::utohexstr(State.Current - ExportStart) +
2979           " in export trie data at node: 0x" + Twine::utohexstr(offset));
2980       moveToEnd();
2981       return;
2982     }
2983   }
2984   State.ChildCount = *Children;
2985   if (State.ChildCount != 0 && Children + 1 >= Trie.end()) {
2986     *E = malformedError("byte for count of childern in export trie data at "
2987                         "node: 0x" +
2988                         Twine::utohexstr(offset) +
2989                         " extends past end of trie data");
2990     moveToEnd();
2991     return;
2992   }
2993   State.Current = Children + 1;
2994   State.NextChildIndex = 0;
2995   State.ParentStringLength = CumulativeString.size();
2996   Stack.push_back(State);
2997 }
2998 
pushDownUntilBottom()2999 void ExportEntry::pushDownUntilBottom() {
3000   ErrorAsOutParameter ErrAsOutParam(E);
3001   const char *error;
3002   while (Stack.back().NextChildIndex < Stack.back().ChildCount) {
3003     NodeState &Top = Stack.back();
3004     CumulativeString.resize(Top.ParentStringLength);
3005     for (;*Top.Current != 0 && Top.Current < Trie.end(); Top.Current++) {
3006       char C = *Top.Current;
3007       CumulativeString.push_back(C);
3008     }
3009     if (Top.Current >= Trie.end()) {
3010       *E = malformedError("edge sub-string in export trie data at node: 0x" +
3011                           Twine::utohexstr(Top.Start - Trie.begin()) +
3012                           " for child #" + Twine((int)Top.NextChildIndex) +
3013                           " extends past end of trie data");
3014       moveToEnd();
3015       return;
3016     }
3017     Top.Current += 1;
3018     uint64_t childNodeIndex = readULEB128(Top.Current, &error);
3019     if (error) {
3020       *E = malformedError("child node offset " + Twine(error) +
3021                           " in export trie data at node: 0x" +
3022                           Twine::utohexstr(Top.Start - Trie.begin()));
3023       moveToEnd();
3024       return;
3025     }
3026     for (const NodeState &node : nodes()) {
3027       if (node.Start == Trie.begin() + childNodeIndex){
3028         *E = malformedError("loop in childern in export trie data at node: 0x" +
3029                             Twine::utohexstr(Top.Start - Trie.begin()) +
3030                             " back to node: 0x" +
3031                             Twine::utohexstr(childNodeIndex));
3032         moveToEnd();
3033         return;
3034       }
3035     }
3036     Top.NextChildIndex += 1;
3037     pushNode(childNodeIndex);
3038     if (*E)
3039       return;
3040   }
3041   if (!Stack.back().IsExportNode) {
3042     *E = malformedError("node is not an export node in export trie data at "
3043                         "node: 0x" +
3044                         Twine::utohexstr(Stack.back().Start - Trie.begin()));
3045     moveToEnd();
3046     return;
3047   }
3048 }
3049 
3050 // We have a trie data structure and need a way to walk it that is compatible
3051 // with the C++ iterator model. The solution is a non-recursive depth first
3052 // traversal where the iterator contains a stack of parent nodes along with a
3053 // string that is the accumulation of all edge strings along the parent chain
3054 // to this point.
3055 //
3056 // There is one "export" node for each exported symbol.  But because some
3057 // symbols may be a prefix of another symbol (e.g. _dup and _dup2), an export
3058 // node may have child nodes too.
3059 //
3060 // The algorithm for moveNext() is to keep moving down the leftmost unvisited
3061 // child until hitting a node with no children (which is an export node or
3062 // else the trie is malformed). On the way down, each node is pushed on the
3063 // stack ivar.  If there is no more ways down, it pops up one and tries to go
3064 // down a sibling path until a childless node is reached.
moveNext()3065 void ExportEntry::moveNext() {
3066   assert(!Stack.empty() && "ExportEntry::moveNext() with empty node stack");
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   Stack.pop_back();
3076   while (!Stack.empty()) {
3077     NodeState &Top = Stack.back();
3078     if (Top.NextChildIndex < Top.ChildCount) {
3079       pushDownUntilBottom();
3080       // Now at the next export node.
3081       return;
3082     } else {
3083       if (Top.IsExportNode) {
3084         // This node has no children but is itself an export node.
3085         CumulativeString.resize(Top.ParentStringLength);
3086         return;
3087       }
3088       Stack.pop_back();
3089     }
3090   }
3091   Done = true;
3092 }
3093 
3094 iterator_range<export_iterator>
exports(Error & E,ArrayRef<uint8_t> Trie,const MachOObjectFile * O)3095 MachOObjectFile::exports(Error &E, ArrayRef<uint8_t> Trie,
3096                          const MachOObjectFile *O) {
3097   ExportEntry Start(&E, O, Trie);
3098   if (Trie.empty())
3099     Start.moveToEnd();
3100   else
3101     Start.moveToFirst();
3102 
3103   ExportEntry Finish(&E, O, Trie);
3104   Finish.moveToEnd();
3105 
3106   return make_range(export_iterator(Start), export_iterator(Finish));
3107 }
3108 
exports(Error & Err) const3109 iterator_range<export_iterator> MachOObjectFile::exports(Error &Err) const {
3110   return exports(Err, getDyldInfoExportsTrie(), this);
3111 }
3112 
MachORebaseEntry(Error * E,const MachOObjectFile * O,ArrayRef<uint8_t> Bytes,bool is64Bit)3113 MachORebaseEntry::MachORebaseEntry(Error *E, const MachOObjectFile *O,
3114                                    ArrayRef<uint8_t> Bytes, bool is64Bit)
3115     : E(E), O(O), Opcodes(Bytes), Ptr(Bytes.begin()),
3116       PointerSize(is64Bit ? 8 : 4) {}
3117 
moveToFirst()3118 void MachORebaseEntry::moveToFirst() {
3119   Ptr = Opcodes.begin();
3120   moveNext();
3121 }
3122 
moveToEnd()3123 void MachORebaseEntry::moveToEnd() {
3124   Ptr = Opcodes.end();
3125   RemainingLoopCount = 0;
3126   Done = true;
3127 }
3128 
moveNext()3129 void MachORebaseEntry::moveNext() {
3130   ErrorAsOutParameter ErrAsOutParam(E);
3131   // If in the middle of some loop, move to next rebasing in loop.
3132   SegmentOffset += AdvanceAmount;
3133   if (RemainingLoopCount) {
3134     --RemainingLoopCount;
3135     return;
3136   }
3137   // REBASE_OPCODE_DONE is only used for padding if we are not aligned to
3138   // pointer size. Therefore it is possible to reach the end without ever having
3139   // seen REBASE_OPCODE_DONE.
3140   if (Ptr == Opcodes.end()) {
3141     Done = true;
3142     return;
3143   }
3144   bool More = true;
3145   while (More) {
3146     // Parse next opcode and set up next loop.
3147     const uint8_t *OpcodeStart = Ptr;
3148     uint8_t Byte = *Ptr++;
3149     uint8_t ImmValue = Byte & MachO::REBASE_IMMEDIATE_MASK;
3150     uint8_t Opcode = Byte & MachO::REBASE_OPCODE_MASK;
3151     uint32_t Count, Skip;
3152     const char *error = nullptr;
3153     switch (Opcode) {
3154     case MachO::REBASE_OPCODE_DONE:
3155       More = false;
3156       Done = true;
3157       moveToEnd();
3158       DEBUG_WITH_TYPE("mach-o-rebase", dbgs() << "REBASE_OPCODE_DONE\n");
3159       break;
3160     case MachO::REBASE_OPCODE_SET_TYPE_IMM:
3161       RebaseType = ImmValue;
3162       if (RebaseType > MachO::REBASE_TYPE_TEXT_PCREL32) {
3163         *E = malformedError("for REBASE_OPCODE_SET_TYPE_IMM bad bind type: " +
3164                             Twine((int)RebaseType) + " for opcode at: 0x" +
3165                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3166         moveToEnd();
3167         return;
3168       }
3169       DEBUG_WITH_TYPE(
3170           "mach-o-rebase",
3171           dbgs() << "REBASE_OPCODE_SET_TYPE_IMM: "
3172                  << "RebaseType=" << (int) RebaseType << "\n");
3173       break;
3174     case MachO::REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:
3175       SegmentIndex = ImmValue;
3176       SegmentOffset = readULEB128(&error);
3177       if (error) {
3178         *E = malformedError("for REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB " +
3179                             Twine(error) + " for opcode at: 0x" +
3180                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3181         moveToEnd();
3182         return;
3183       }
3184       error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3185                                                PointerSize);
3186       if (error) {
3187         *E = malformedError("for REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB " +
3188                             Twine(error) + " for opcode at: 0x" +
3189                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3190         moveToEnd();
3191         return;
3192       }
3193       DEBUG_WITH_TYPE(
3194           "mach-o-rebase",
3195           dbgs() << "REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: "
3196                  << "SegmentIndex=" << SegmentIndex << ", "
3197                  << format("SegmentOffset=0x%06X", SegmentOffset)
3198                  << "\n");
3199       break;
3200     case MachO::REBASE_OPCODE_ADD_ADDR_ULEB:
3201       SegmentOffset += readULEB128(&error);
3202       if (error) {
3203         *E = malformedError("for REBASE_OPCODE_ADD_ADDR_ULEB " + Twine(error) +
3204                             " for opcode at: 0x" +
3205                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3206         moveToEnd();
3207         return;
3208       }
3209       error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3210                                                PointerSize);
3211       if (error) {
3212         *E = malformedError("for REBASE_OPCODE_ADD_ADDR_ULEB " + Twine(error) +
3213                             " for opcode at: 0x" +
3214                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3215         moveToEnd();
3216         return;
3217       }
3218       DEBUG_WITH_TYPE("mach-o-rebase",
3219                       dbgs() << "REBASE_OPCODE_ADD_ADDR_ULEB: "
3220                              << format("SegmentOffset=0x%06X",
3221                                        SegmentOffset) << "\n");
3222       break;
3223     case MachO::REBASE_OPCODE_ADD_ADDR_IMM_SCALED:
3224       SegmentOffset += ImmValue * PointerSize;
3225       error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3226                                                PointerSize);
3227       if (error) {
3228         *E = malformedError("for REBASE_OPCODE_ADD_ADDR_IMM_SCALED " +
3229                             Twine(error) + " for opcode at: 0x" +
3230                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3231         moveToEnd();
3232         return;
3233       }
3234       DEBUG_WITH_TYPE("mach-o-rebase",
3235                       dbgs() << "REBASE_OPCODE_ADD_ADDR_IMM_SCALED: "
3236                              << format("SegmentOffset=0x%06X",
3237                                        SegmentOffset) << "\n");
3238       break;
3239     case MachO::REBASE_OPCODE_DO_REBASE_IMM_TIMES:
3240       AdvanceAmount = PointerSize;
3241       Skip = 0;
3242       Count = ImmValue;
3243       if (ImmValue != 0)
3244         RemainingLoopCount = ImmValue - 1;
3245       else
3246         RemainingLoopCount = 0;
3247       error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3248                                                PointerSize, Count, Skip);
3249       if (error) {
3250         *E = malformedError("for REBASE_OPCODE_DO_REBASE_IMM_TIMES " +
3251                             Twine(error) + " for opcode at: 0x" +
3252                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3253         moveToEnd();
3254         return;
3255       }
3256       DEBUG_WITH_TYPE(
3257           "mach-o-rebase",
3258           dbgs() << "REBASE_OPCODE_DO_REBASE_IMM_TIMES: "
3259                  << format("SegmentOffset=0x%06X", SegmentOffset)
3260                  << ", AdvanceAmount=" << AdvanceAmount
3261                  << ", RemainingLoopCount=" << RemainingLoopCount
3262                  << "\n");
3263       return;
3264     case MachO::REBASE_OPCODE_DO_REBASE_ULEB_TIMES:
3265       AdvanceAmount = PointerSize;
3266       Skip = 0;
3267       Count = readULEB128(&error);
3268       if (error) {
3269         *E = malformedError("for REBASE_OPCODE_DO_REBASE_ULEB_TIMES " +
3270                             Twine(error) + " for opcode at: 0x" +
3271                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3272         moveToEnd();
3273         return;
3274       }
3275       if (Count != 0)
3276         RemainingLoopCount = Count - 1;
3277       else
3278         RemainingLoopCount = 0;
3279       error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3280                                                PointerSize, Count, Skip);
3281       if (error) {
3282         *E = malformedError("for REBASE_OPCODE_DO_REBASE_ULEB_TIMES " +
3283                             Twine(error) + " for opcode at: 0x" +
3284                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3285         moveToEnd();
3286         return;
3287       }
3288       DEBUG_WITH_TYPE(
3289           "mach-o-rebase",
3290           dbgs() << "REBASE_OPCODE_DO_REBASE_ULEB_TIMES: "
3291                  << format("SegmentOffset=0x%06X", SegmentOffset)
3292                  << ", AdvanceAmount=" << AdvanceAmount
3293                  << ", RemainingLoopCount=" << RemainingLoopCount
3294                  << "\n");
3295       return;
3296     case MachO::REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB:
3297       Skip = readULEB128(&error);
3298       if (error) {
3299         *E = malformedError("for REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB " +
3300                             Twine(error) + " for opcode at: 0x" +
3301                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3302         moveToEnd();
3303         return;
3304       }
3305       AdvanceAmount = Skip + PointerSize;
3306       Count = 1;
3307       RemainingLoopCount = 0;
3308       error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3309                                                PointerSize, Count, Skip);
3310       if (error) {
3311         *E = malformedError("for REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB " +
3312                             Twine(error) + " for opcode at: 0x" +
3313                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3314         moveToEnd();
3315         return;
3316       }
3317       DEBUG_WITH_TYPE(
3318           "mach-o-rebase",
3319           dbgs() << "REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB: "
3320                  << format("SegmentOffset=0x%06X", SegmentOffset)
3321                  << ", AdvanceAmount=" << AdvanceAmount
3322                  << ", RemainingLoopCount=" << RemainingLoopCount
3323                  << "\n");
3324       return;
3325     case MachO::REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB:
3326       Count = readULEB128(&error);
3327       if (error) {
3328         *E = malformedError("for REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_"
3329                             "ULEB " +
3330                             Twine(error) + " for opcode at: 0x" +
3331                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3332         moveToEnd();
3333         return;
3334       }
3335       if (Count != 0)
3336         RemainingLoopCount = Count - 1;
3337       else
3338         RemainingLoopCount = 0;
3339       Skip = readULEB128(&error);
3340       if (error) {
3341         *E = malformedError("for REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_"
3342                             "ULEB " +
3343                             Twine(error) + " for opcode at: 0x" +
3344                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3345         moveToEnd();
3346         return;
3347       }
3348       AdvanceAmount = Skip + PointerSize;
3349 
3350       error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3351                                                PointerSize, Count, Skip);
3352       if (error) {
3353         *E = malformedError("for REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_"
3354                             "ULEB " +
3355                             Twine(error) + " for opcode at: 0x" +
3356                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3357         moveToEnd();
3358         return;
3359       }
3360       DEBUG_WITH_TYPE(
3361           "mach-o-rebase",
3362           dbgs() << "REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB: "
3363                  << format("SegmentOffset=0x%06X", SegmentOffset)
3364                  << ", AdvanceAmount=" << AdvanceAmount
3365                  << ", RemainingLoopCount=" << RemainingLoopCount
3366                  << "\n");
3367       return;
3368     default:
3369       *E = malformedError("bad rebase info (bad opcode value 0x" +
3370                           Twine::utohexstr(Opcode) + " for opcode at: 0x" +
3371                           Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3372       moveToEnd();
3373       return;
3374     }
3375   }
3376 }
3377 
readULEB128(const char ** error)3378 uint64_t MachORebaseEntry::readULEB128(const char **error) {
3379   unsigned Count;
3380   uint64_t Result = decodeULEB128(Ptr, &Count, Opcodes.end(), error);
3381   Ptr += Count;
3382   if (Ptr > Opcodes.end())
3383     Ptr = Opcodes.end();
3384   return Result;
3385 }
3386 
segmentIndex() const3387 int32_t MachORebaseEntry::segmentIndex() const { return SegmentIndex; }
3388 
segmentOffset() const3389 uint64_t MachORebaseEntry::segmentOffset() const { return SegmentOffset; }
3390 
typeName() const3391 StringRef MachORebaseEntry::typeName() const {
3392   switch (RebaseType) {
3393   case MachO::REBASE_TYPE_POINTER:
3394     return "pointer";
3395   case MachO::REBASE_TYPE_TEXT_ABSOLUTE32:
3396     return "text abs32";
3397   case MachO::REBASE_TYPE_TEXT_PCREL32:
3398     return "text rel32";
3399   }
3400   return "unknown";
3401 }
3402 
3403 // For use with the SegIndex of a checked Mach-O Rebase entry
3404 // to get the segment name.
segmentName() const3405 StringRef MachORebaseEntry::segmentName() const {
3406   return O->BindRebaseSegmentName(SegmentIndex);
3407 }
3408 
3409 // For use with a SegIndex,SegOffset pair from a checked Mach-O Rebase entry
3410 // to get the section name.
sectionName() const3411 StringRef MachORebaseEntry::sectionName() const {
3412   return O->BindRebaseSectionName(SegmentIndex, SegmentOffset);
3413 }
3414 
3415 // For use with a SegIndex,SegOffset pair from a checked Mach-O Rebase entry
3416 // to get the address.
address() const3417 uint64_t MachORebaseEntry::address() const {
3418   return O->BindRebaseAddress(SegmentIndex, SegmentOffset);
3419 }
3420 
operator ==(const MachORebaseEntry & Other) const3421 bool MachORebaseEntry::operator==(const MachORebaseEntry &Other) const {
3422 #ifdef EXPENSIVE_CHECKS
3423   assert(Opcodes == Other.Opcodes && "compare iterators of different files");
3424 #else
3425   assert(Opcodes.data() == Other.Opcodes.data() && "compare iterators of different files");
3426 #endif
3427   return (Ptr == Other.Ptr) &&
3428          (RemainingLoopCount == Other.RemainingLoopCount) &&
3429          (Done == Other.Done);
3430 }
3431 
3432 iterator_range<rebase_iterator>
rebaseTable(Error & Err,MachOObjectFile * O,ArrayRef<uint8_t> Opcodes,bool is64)3433 MachOObjectFile::rebaseTable(Error &Err, MachOObjectFile *O,
3434                              ArrayRef<uint8_t> Opcodes, bool is64) {
3435   if (O->BindRebaseSectionTable == nullptr)
3436     O->BindRebaseSectionTable = std::make_unique<BindRebaseSegInfo>(O);
3437   MachORebaseEntry Start(&Err, O, Opcodes, is64);
3438   Start.moveToFirst();
3439 
3440   MachORebaseEntry Finish(&Err, O, Opcodes, is64);
3441   Finish.moveToEnd();
3442 
3443   return make_range(rebase_iterator(Start), rebase_iterator(Finish));
3444 }
3445 
rebaseTable(Error & Err)3446 iterator_range<rebase_iterator> MachOObjectFile::rebaseTable(Error &Err) {
3447   return rebaseTable(Err, this, getDyldInfoRebaseOpcodes(), is64Bit());
3448 }
3449 
MachOBindEntry(Error * E,const MachOObjectFile * O,ArrayRef<uint8_t> Bytes,bool is64Bit,Kind BK)3450 MachOBindEntry::MachOBindEntry(Error *E, const MachOObjectFile *O,
3451                                ArrayRef<uint8_t> Bytes, bool is64Bit, Kind BK)
3452     : E(E), O(O), Opcodes(Bytes), Ptr(Bytes.begin()),
3453       PointerSize(is64Bit ? 8 : 4), TableKind(BK) {}
3454 
moveToFirst()3455 void MachOBindEntry::moveToFirst() {
3456   Ptr = Opcodes.begin();
3457   moveNext();
3458 }
3459 
moveToEnd()3460 void MachOBindEntry::moveToEnd() {
3461   Ptr = Opcodes.end();
3462   RemainingLoopCount = 0;
3463   Done = true;
3464 }
3465 
moveNext()3466 void MachOBindEntry::moveNext() {
3467   ErrorAsOutParameter ErrAsOutParam(E);
3468   // If in the middle of some loop, move to next binding in loop.
3469   SegmentOffset += AdvanceAmount;
3470   if (RemainingLoopCount) {
3471     --RemainingLoopCount;
3472     return;
3473   }
3474   // BIND_OPCODE_DONE is only used for padding if we are not aligned to
3475   // pointer size. Therefore it is possible to reach the end without ever having
3476   // seen BIND_OPCODE_DONE.
3477   if (Ptr == Opcodes.end()) {
3478     Done = true;
3479     return;
3480   }
3481   bool More = true;
3482   while (More) {
3483     // Parse next opcode and set up next loop.
3484     const uint8_t *OpcodeStart = Ptr;
3485     uint8_t Byte = *Ptr++;
3486     uint8_t ImmValue = Byte & MachO::BIND_IMMEDIATE_MASK;
3487     uint8_t Opcode = Byte & MachO::BIND_OPCODE_MASK;
3488     int8_t SignExtended;
3489     const uint8_t *SymStart;
3490     uint32_t Count, Skip;
3491     const char *error = nullptr;
3492     switch (Opcode) {
3493     case MachO::BIND_OPCODE_DONE:
3494       if (TableKind == Kind::Lazy) {
3495         // Lazying bindings have a DONE opcode between entries.  Need to ignore
3496         // it to advance to next entry.  But need not if this is last entry.
3497         bool NotLastEntry = false;
3498         for (const uint8_t *P = Ptr; P < Opcodes.end(); ++P) {
3499           if (*P) {
3500             NotLastEntry = true;
3501           }
3502         }
3503         if (NotLastEntry)
3504           break;
3505       }
3506       More = false;
3507       moveToEnd();
3508       DEBUG_WITH_TYPE("mach-o-bind", dbgs() << "BIND_OPCODE_DONE\n");
3509       break;
3510     case MachO::BIND_OPCODE_SET_DYLIB_ORDINAL_IMM:
3511       if (TableKind == Kind::Weak) {
3512         *E = malformedError("BIND_OPCODE_SET_DYLIB_ORDINAL_IMM not allowed in "
3513                             "weak bind table for opcode at: 0x" +
3514                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3515         moveToEnd();
3516         return;
3517       }
3518       Ordinal = ImmValue;
3519       LibraryOrdinalSet = true;
3520       if (ImmValue > O->getLibraryCount()) {
3521         *E = malformedError("for BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB bad "
3522                             "library ordinal: " +
3523                             Twine((int)ImmValue) + " (max " +
3524                             Twine((int)O->getLibraryCount()) +
3525                             ") for opcode at: 0x" +
3526                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3527         moveToEnd();
3528         return;
3529       }
3530       DEBUG_WITH_TYPE(
3531           "mach-o-bind",
3532           dbgs() << "BIND_OPCODE_SET_DYLIB_ORDINAL_IMM: "
3533                  << "Ordinal=" << Ordinal << "\n");
3534       break;
3535     case MachO::BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB:
3536       if (TableKind == Kind::Weak) {
3537         *E = malformedError("BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB not allowed in "
3538                             "weak bind table for opcode at: 0x" +
3539                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3540         moveToEnd();
3541         return;
3542       }
3543       Ordinal = readULEB128(&error);
3544       LibraryOrdinalSet = true;
3545       if (error) {
3546         *E = malformedError("for BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB " +
3547                             Twine(error) + " for opcode at: 0x" +
3548                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3549         moveToEnd();
3550         return;
3551       }
3552       if (Ordinal > (int)O->getLibraryCount()) {
3553         *E = malformedError("for BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB bad "
3554                             "library ordinal: " +
3555                             Twine((int)Ordinal) + " (max " +
3556                             Twine((int)O->getLibraryCount()) +
3557                             ") for opcode at: 0x" +
3558                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3559         moveToEnd();
3560         return;
3561       }
3562       DEBUG_WITH_TYPE(
3563           "mach-o-bind",
3564           dbgs() << "BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB: "
3565                  << "Ordinal=" << Ordinal << "\n");
3566       break;
3567     case MachO::BIND_OPCODE_SET_DYLIB_SPECIAL_IMM:
3568       if (TableKind == Kind::Weak) {
3569         *E = malformedError("BIND_OPCODE_SET_DYLIB_SPECIAL_IMM not allowed in "
3570                             "weak bind table for opcode at: 0x" +
3571                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3572         moveToEnd();
3573         return;
3574       }
3575       if (ImmValue) {
3576         SignExtended = MachO::BIND_OPCODE_MASK | ImmValue;
3577         Ordinal = SignExtended;
3578         if (Ordinal < MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP) {
3579           *E = malformedError("for BIND_OPCODE_SET_DYLIB_SPECIAL_IMM unknown "
3580                               "special ordinal: " +
3581                               Twine((int)Ordinal) + " for opcode at: 0x" +
3582                               Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3583           moveToEnd();
3584           return;
3585         }
3586       } else
3587         Ordinal = 0;
3588       LibraryOrdinalSet = true;
3589       DEBUG_WITH_TYPE(
3590           "mach-o-bind",
3591           dbgs() << "BIND_OPCODE_SET_DYLIB_SPECIAL_IMM: "
3592                  << "Ordinal=" << Ordinal << "\n");
3593       break;
3594     case MachO::BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM:
3595       Flags = ImmValue;
3596       SymStart = Ptr;
3597       while (*Ptr && (Ptr < Opcodes.end())) {
3598         ++Ptr;
3599       }
3600       if (Ptr == Opcodes.end()) {
3601         *E = malformedError(
3602             "for BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM "
3603             "symbol name extends past opcodes for opcode at: 0x" +
3604             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3605         moveToEnd();
3606         return;
3607       }
3608       SymbolName = StringRef(reinterpret_cast<const char*>(SymStart),
3609                              Ptr-SymStart);
3610       ++Ptr;
3611       DEBUG_WITH_TYPE(
3612           "mach-o-bind",
3613           dbgs() << "BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM: "
3614                  << "SymbolName=" << SymbolName << "\n");
3615       if (TableKind == Kind::Weak) {
3616         if (ImmValue & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION)
3617           return;
3618       }
3619       break;
3620     case MachO::BIND_OPCODE_SET_TYPE_IMM:
3621       BindType = ImmValue;
3622       if (ImmValue > MachO::BIND_TYPE_TEXT_PCREL32) {
3623         *E = malformedError("for BIND_OPCODE_SET_TYPE_IMM bad bind type: " +
3624                             Twine((int)ImmValue) + " for opcode at: 0x" +
3625                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3626         moveToEnd();
3627         return;
3628       }
3629       DEBUG_WITH_TYPE(
3630           "mach-o-bind",
3631           dbgs() << "BIND_OPCODE_SET_TYPE_IMM: "
3632                  << "BindType=" << (int)BindType << "\n");
3633       break;
3634     case MachO::BIND_OPCODE_SET_ADDEND_SLEB:
3635       Addend = readSLEB128(&error);
3636       if (error) {
3637         *E = malformedError("for BIND_OPCODE_SET_ADDEND_SLEB " + Twine(error) +
3638                             " for opcode at: 0x" +
3639                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3640         moveToEnd();
3641         return;
3642       }
3643       DEBUG_WITH_TYPE(
3644           "mach-o-bind",
3645           dbgs() << "BIND_OPCODE_SET_ADDEND_SLEB: "
3646                  << "Addend=" << Addend << "\n");
3647       break;
3648     case MachO::BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:
3649       SegmentIndex = ImmValue;
3650       SegmentOffset = readULEB128(&error);
3651       if (error) {
3652         *E = malformedError("for BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB " +
3653                             Twine(error) + " for opcode at: 0x" +
3654                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3655         moveToEnd();
3656         return;
3657       }
3658       error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3659                                              PointerSize);
3660       if (error) {
3661         *E = malformedError("for BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB " +
3662                             Twine(error) + " for opcode at: 0x" +
3663                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3664         moveToEnd();
3665         return;
3666       }
3667       DEBUG_WITH_TYPE(
3668           "mach-o-bind",
3669           dbgs() << "BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: "
3670                  << "SegmentIndex=" << SegmentIndex << ", "
3671                  << format("SegmentOffset=0x%06X", SegmentOffset)
3672                  << "\n");
3673       break;
3674     case MachO::BIND_OPCODE_ADD_ADDR_ULEB:
3675       SegmentOffset += readULEB128(&error);
3676       if (error) {
3677         *E = malformedError("for BIND_OPCODE_ADD_ADDR_ULEB " + Twine(error) +
3678                             " for opcode at: 0x" +
3679                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3680         moveToEnd();
3681         return;
3682       }
3683       error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3684                                              PointerSize);
3685       if (error) {
3686         *E = malformedError("for BIND_OPCODE_ADD_ADDR_ULEB " + Twine(error) +
3687                             " for opcode at: 0x" +
3688                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3689         moveToEnd();
3690         return;
3691       }
3692       DEBUG_WITH_TYPE("mach-o-bind",
3693                       dbgs() << "BIND_OPCODE_ADD_ADDR_ULEB: "
3694                              << format("SegmentOffset=0x%06X",
3695                                        SegmentOffset) << "\n");
3696       break;
3697     case MachO::BIND_OPCODE_DO_BIND:
3698       AdvanceAmount = PointerSize;
3699       RemainingLoopCount = 0;
3700       error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3701                                              PointerSize);
3702       if (error) {
3703         *E = malformedError("for BIND_OPCODE_DO_BIND " + Twine(error) +
3704                             " for opcode at: 0x" +
3705                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3706         moveToEnd();
3707         return;
3708       }
3709       if (SymbolName == StringRef()) {
3710         *E = malformedError(
3711             "for BIND_OPCODE_DO_BIND missing preceding "
3712             "BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM for opcode at: 0x" +
3713             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3714         moveToEnd();
3715         return;
3716       }
3717       if (!LibraryOrdinalSet && TableKind != Kind::Weak) {
3718         *E =
3719             malformedError("for BIND_OPCODE_DO_BIND missing preceding "
3720                            "BIND_OPCODE_SET_DYLIB_ORDINAL_* for opcode at: 0x" +
3721                            Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3722         moveToEnd();
3723         return;
3724       }
3725       DEBUG_WITH_TYPE("mach-o-bind",
3726                       dbgs() << "BIND_OPCODE_DO_BIND: "
3727                              << format("SegmentOffset=0x%06X",
3728                                        SegmentOffset) << "\n");
3729       return;
3730      case MachO::BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB:
3731       if (TableKind == Kind::Lazy) {
3732         *E = malformedError("BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB not allowed in "
3733                             "lazy bind table for opcode at: 0x" +
3734                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3735         moveToEnd();
3736         return;
3737       }
3738       error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3739                                              PointerSize);
3740       if (error) {
3741         *E = malformedError("for BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB " +
3742                             Twine(error) + " for opcode at: 0x" +
3743                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3744         moveToEnd();
3745         return;
3746       }
3747       if (SymbolName == StringRef()) {
3748         *E = malformedError(
3749             "for BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB missing "
3750             "preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM for opcode "
3751             "at: 0x" +
3752             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3753         moveToEnd();
3754         return;
3755       }
3756       if (!LibraryOrdinalSet && TableKind != Kind::Weak) {
3757         *E = malformedError(
3758             "for BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB missing "
3759             "preceding BIND_OPCODE_SET_DYLIB_ORDINAL_* for opcode at: 0x" +
3760             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3761         moveToEnd();
3762         return;
3763       }
3764       AdvanceAmount = readULEB128(&error) + PointerSize;
3765       if (error) {
3766         *E = malformedError("for BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB " +
3767                             Twine(error) + " for opcode at: 0x" +
3768                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3769         moveToEnd();
3770         return;
3771       }
3772       // Note, this is not really an error until the next bind but make no sense
3773       // for a BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB to not be followed by another
3774       // bind operation.
3775       error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset +
3776                                             AdvanceAmount, PointerSize);
3777       if (error) {
3778         *E = malformedError("for BIND_OPCODE_ADD_ADDR_ULEB (after adding "
3779                             "ULEB) " +
3780                             Twine(error) + " for opcode at: 0x" +
3781                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3782         moveToEnd();
3783         return;
3784       }
3785       RemainingLoopCount = 0;
3786       DEBUG_WITH_TYPE(
3787           "mach-o-bind",
3788           dbgs() << "BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB: "
3789                  << format("SegmentOffset=0x%06X", SegmentOffset)
3790                  << ", AdvanceAmount=" << AdvanceAmount
3791                  << ", RemainingLoopCount=" << RemainingLoopCount
3792                  << "\n");
3793       return;
3794     case MachO::BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED:
3795       if (TableKind == Kind::Lazy) {
3796         *E = malformedError("BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED not "
3797                             "allowed in lazy bind table for opcode at: 0x" +
3798                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3799         moveToEnd();
3800         return;
3801       }
3802       if (SymbolName == StringRef()) {
3803         *E = malformedError(
3804             "for BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED "
3805             "missing preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM for "
3806             "opcode at: 0x" +
3807             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3808         moveToEnd();
3809         return;
3810       }
3811       if (!LibraryOrdinalSet && TableKind != Kind::Weak) {
3812         *E = malformedError(
3813             "for BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED "
3814             "missing preceding BIND_OPCODE_SET_DYLIB_ORDINAL_* for opcode "
3815             "at: 0x" +
3816             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3817         moveToEnd();
3818         return;
3819       }
3820       AdvanceAmount = ImmValue * PointerSize + PointerSize;
3821       RemainingLoopCount = 0;
3822       error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset +
3823                                              AdvanceAmount, PointerSize);
3824       if (error) {
3825         *E = malformedError("for BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED " +
3826                             Twine(error) + " for opcode at: 0x" +
3827                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3828         moveToEnd();
3829         return;
3830       }
3831       DEBUG_WITH_TYPE("mach-o-bind",
3832                       dbgs()
3833                       << "BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED: "
3834                       << format("SegmentOffset=0x%06X", SegmentOffset) << "\n");
3835       return;
3836     case MachO::BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB:
3837       if (TableKind == Kind::Lazy) {
3838         *E = malformedError("BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB not "
3839                             "allowed in lazy bind table for opcode at: 0x" +
3840                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3841         moveToEnd();
3842         return;
3843       }
3844       Count = readULEB128(&error);
3845       if (Count != 0)
3846         RemainingLoopCount = Count - 1;
3847       else
3848         RemainingLoopCount = 0;
3849       if (error) {
3850         *E = malformedError("for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB "
3851                             " (count value) " +
3852                             Twine(error) + " for opcode at: 0x" +
3853                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3854         moveToEnd();
3855         return;
3856       }
3857       Skip = readULEB128(&error);
3858       AdvanceAmount = Skip + PointerSize;
3859       if (error) {
3860         *E = malformedError("for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB "
3861                             " (skip value) " +
3862                             Twine(error) + " for opcode at: 0x" +
3863                             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3864         moveToEnd();
3865         return;
3866       }
3867       if (SymbolName == StringRef()) {
3868         *E = malformedError(
3869             "for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB "
3870             "missing preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM for "
3871             "opcode at: 0x" +
3872             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3873         moveToEnd();
3874         return;
3875       }
3876       if (!LibraryOrdinalSet && TableKind != Kind::Weak) {
3877         *E = malformedError(
3878             "for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB "
3879             "missing preceding BIND_OPCODE_SET_DYLIB_ORDINAL_* for opcode "
3880             "at: 0x" +
3881             Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3882         moveToEnd();
3883         return;
3884       }
3885       error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
3886                                              PointerSize, Count, Skip);
3887       if (error) {
3888         *E =
3889             malformedError("for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB " +
3890                            Twine(error) + " for opcode at: 0x" +
3891                            Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3892         moveToEnd();
3893         return;
3894       }
3895       DEBUG_WITH_TYPE(
3896           "mach-o-bind",
3897           dbgs() << "BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB: "
3898                  << format("SegmentOffset=0x%06X", SegmentOffset)
3899                  << ", AdvanceAmount=" << AdvanceAmount
3900                  << ", RemainingLoopCount=" << RemainingLoopCount
3901                  << "\n");
3902       return;
3903     default:
3904       *E = malformedError("bad bind info (bad opcode value 0x" +
3905                           Twine::utohexstr(Opcode) + " for opcode at: 0x" +
3906                           Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3907       moveToEnd();
3908       return;
3909     }
3910   }
3911 }
3912 
readULEB128(const char ** error)3913 uint64_t MachOBindEntry::readULEB128(const char **error) {
3914   unsigned Count;
3915   uint64_t Result = decodeULEB128(Ptr, &Count, Opcodes.end(), error);
3916   Ptr += Count;
3917   if (Ptr > Opcodes.end())
3918     Ptr = Opcodes.end();
3919   return Result;
3920 }
3921 
readSLEB128(const char ** error)3922 int64_t MachOBindEntry::readSLEB128(const char **error) {
3923   unsigned Count;
3924   int64_t Result = decodeSLEB128(Ptr, &Count, Opcodes.end(), error);
3925   Ptr += Count;
3926   if (Ptr > Opcodes.end())
3927     Ptr = Opcodes.end();
3928   return Result;
3929 }
3930 
segmentIndex() const3931 int32_t MachOBindEntry::segmentIndex() const { return SegmentIndex; }
3932 
segmentOffset() const3933 uint64_t MachOBindEntry::segmentOffset() const { return SegmentOffset; }
3934 
typeName() const3935 StringRef MachOBindEntry::typeName() const {
3936   switch (BindType) {
3937   case MachO::BIND_TYPE_POINTER:
3938     return "pointer";
3939   case MachO::BIND_TYPE_TEXT_ABSOLUTE32:
3940     return "text abs32";
3941   case MachO::BIND_TYPE_TEXT_PCREL32:
3942     return "text rel32";
3943   }
3944   return "unknown";
3945 }
3946 
symbolName() const3947 StringRef MachOBindEntry::symbolName() const { return SymbolName; }
3948 
addend() const3949 int64_t MachOBindEntry::addend() const { return Addend; }
3950 
flags() const3951 uint32_t MachOBindEntry::flags() const { return Flags; }
3952 
ordinal() const3953 int MachOBindEntry::ordinal() const { return Ordinal; }
3954 
3955 // For use with the SegIndex of a checked Mach-O Bind entry
3956 // to get the segment name.
segmentName() const3957 StringRef MachOBindEntry::segmentName() const {
3958   return O->BindRebaseSegmentName(SegmentIndex);
3959 }
3960 
3961 // For use with a SegIndex,SegOffset pair from a checked Mach-O Bind entry
3962 // to get the section name.
sectionName() const3963 StringRef MachOBindEntry::sectionName() const {
3964   return O->BindRebaseSectionName(SegmentIndex, SegmentOffset);
3965 }
3966 
3967 // For use with a SegIndex,SegOffset pair from a checked Mach-O Bind entry
3968 // to get the address.
address() const3969 uint64_t MachOBindEntry::address() const {
3970   return O->BindRebaseAddress(SegmentIndex, SegmentOffset);
3971 }
3972 
operator ==(const MachOBindEntry & Other) const3973 bool MachOBindEntry::operator==(const MachOBindEntry &Other) const {
3974 #ifdef EXPENSIVE_CHECKS
3975   assert(Opcodes == Other.Opcodes && "compare iterators of different files");
3976 #else
3977   assert(Opcodes.data() == Other.Opcodes.data() && "compare iterators of different files");
3978 #endif
3979   return (Ptr == Other.Ptr) &&
3980          (RemainingLoopCount == Other.RemainingLoopCount) &&
3981          (Done == Other.Done);
3982 }
3983 
3984 // Build table of sections so SegIndex/SegOffset pairs can be translated.
BindRebaseSegInfo(const object::MachOObjectFile * Obj)3985 BindRebaseSegInfo::BindRebaseSegInfo(const object::MachOObjectFile *Obj) {
3986   uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
3987   StringRef CurSegName;
3988   uint64_t CurSegAddress;
3989   for (const SectionRef &Section : Obj->sections()) {
3990     SectionInfo Info;
3991     Expected<StringRef> NameOrErr = Section.getName();
3992     if (!NameOrErr)
3993       consumeError(NameOrErr.takeError());
3994     else
3995       Info.SectionName = *NameOrErr;
3996     Info.Address = Section.getAddress();
3997     Info.Size = Section.getSize();
3998     Info.SegmentName =
3999         Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
4000     if (!Info.SegmentName.equals(CurSegName)) {
4001       ++CurSegIndex;
4002       CurSegName = Info.SegmentName;
4003       CurSegAddress = Info.Address;
4004     }
4005     Info.SegmentIndex = CurSegIndex - 1;
4006     Info.OffsetInSegment = Info.Address - CurSegAddress;
4007     Info.SegmentStartAddress = CurSegAddress;
4008     Sections.push_back(Info);
4009   }
4010   MaxSegIndex = CurSegIndex;
4011 }
4012 
4013 // For use with a SegIndex, SegOffset, and PointerSize triple in
4014 // MachOBindEntry::moveNext() to validate a MachOBindEntry or MachORebaseEntry.
4015 //
4016 // Given a SegIndex, SegOffset, and PointerSize, verify a valid section exists
4017 // that fully contains a pointer at that location. Multiple fixups in a bind
4018 // (such as with the BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB opcode) can
4019 // be tested via the Count and Skip parameters.
checkSegAndOffsets(int32_t SegIndex,uint64_t SegOffset,uint8_t PointerSize,uint32_t Count,uint32_t Skip)4020 const char * BindRebaseSegInfo::checkSegAndOffsets(int32_t SegIndex,
4021                                                    uint64_t SegOffset,
4022                                                    uint8_t PointerSize,
4023                                                    uint32_t Count,
4024                                                    uint32_t Skip) {
4025   if (SegIndex == -1)
4026     return "missing preceding *_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB";
4027   if (SegIndex >= MaxSegIndex)
4028     return "bad segIndex (too large)";
4029   for (uint32_t i = 0; i < Count; ++i) {
4030     uint32_t Start = SegOffset + i * (PointerSize + Skip);
4031     uint32_t End = Start + PointerSize;
4032     bool Found = false;
4033     for (const SectionInfo &SI : Sections) {
4034       if (SI.SegmentIndex != SegIndex)
4035         continue;
4036       if ((SI.OffsetInSegment<=Start) && (Start<(SI.OffsetInSegment+SI.Size))) {
4037         if (End <= SI.OffsetInSegment + SI.Size) {
4038           Found = true;
4039           break;
4040         }
4041         else
4042           return "bad offset, extends beyond section boundary";
4043       }
4044     }
4045     if (!Found)
4046       return "bad offset, not in section";
4047   }
4048   return nullptr;
4049 }
4050 
4051 // For use with the SegIndex of a checked Mach-O Bind or Rebase entry
4052 // to get the segment name.
segmentName(int32_t SegIndex)4053 StringRef BindRebaseSegInfo::segmentName(int32_t SegIndex) {
4054   for (const SectionInfo &SI : Sections) {
4055     if (SI.SegmentIndex == SegIndex)
4056       return SI.SegmentName;
4057   }
4058   llvm_unreachable("invalid SegIndex");
4059 }
4060 
4061 // For use with a SegIndex,SegOffset pair from a checked Mach-O Bind or Rebase
4062 // to get the SectionInfo.
findSection(int32_t SegIndex,uint64_t SegOffset)4063 const BindRebaseSegInfo::SectionInfo &BindRebaseSegInfo::findSection(
4064                                      int32_t SegIndex, uint64_t SegOffset) {
4065   for (const SectionInfo &SI : Sections) {
4066     if (SI.SegmentIndex != SegIndex)
4067       continue;
4068     if (SI.OffsetInSegment > SegOffset)
4069       continue;
4070     if (SegOffset >= (SI.OffsetInSegment + SI.Size))
4071       continue;
4072     return SI;
4073   }
4074   llvm_unreachable("SegIndex and SegOffset not in any section");
4075 }
4076 
4077 // For use with a SegIndex,SegOffset pair from a checked Mach-O Bind or Rebase
4078 // entry to get the section name.
sectionName(int32_t SegIndex,uint64_t SegOffset)4079 StringRef BindRebaseSegInfo::sectionName(int32_t SegIndex,
4080                                          uint64_t SegOffset) {
4081   return findSection(SegIndex, SegOffset).SectionName;
4082 }
4083 
4084 // For use with a SegIndex,SegOffset pair from a checked Mach-O Bind or Rebase
4085 // entry to get the address.
address(uint32_t SegIndex,uint64_t OffsetInSeg)4086 uint64_t BindRebaseSegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
4087   const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
4088   return SI.SegmentStartAddress + OffsetInSeg;
4089 }
4090 
4091 iterator_range<bind_iterator>
bindTable(Error & Err,MachOObjectFile * O,ArrayRef<uint8_t> Opcodes,bool is64,MachOBindEntry::Kind BKind)4092 MachOObjectFile::bindTable(Error &Err, MachOObjectFile *O,
4093                            ArrayRef<uint8_t> Opcodes, bool is64,
4094                            MachOBindEntry::Kind BKind) {
4095   if (O->BindRebaseSectionTable == nullptr)
4096     O->BindRebaseSectionTable = std::make_unique<BindRebaseSegInfo>(O);
4097   MachOBindEntry Start(&Err, O, Opcodes, is64, BKind);
4098   Start.moveToFirst();
4099 
4100   MachOBindEntry Finish(&Err, O, Opcodes, is64, BKind);
4101   Finish.moveToEnd();
4102 
4103   return make_range(bind_iterator(Start), bind_iterator(Finish));
4104 }
4105 
bindTable(Error & Err)4106 iterator_range<bind_iterator> MachOObjectFile::bindTable(Error &Err) {
4107   return bindTable(Err, this, getDyldInfoBindOpcodes(), is64Bit(),
4108                    MachOBindEntry::Kind::Regular);
4109 }
4110 
lazyBindTable(Error & Err)4111 iterator_range<bind_iterator> MachOObjectFile::lazyBindTable(Error &Err) {
4112   return bindTable(Err, this, getDyldInfoLazyBindOpcodes(), is64Bit(),
4113                    MachOBindEntry::Kind::Lazy);
4114 }
4115 
weakBindTable(Error & Err)4116 iterator_range<bind_iterator> MachOObjectFile::weakBindTable(Error &Err) {
4117   return bindTable(Err, this, getDyldInfoWeakBindOpcodes(), is64Bit(),
4118                    MachOBindEntry::Kind::Weak);
4119 }
4120 
4121 MachOObjectFile::load_command_iterator
begin_load_commands() const4122 MachOObjectFile::begin_load_commands() const {
4123   return LoadCommands.begin();
4124 }
4125 
4126 MachOObjectFile::load_command_iterator
end_load_commands() const4127 MachOObjectFile::end_load_commands() const {
4128   return LoadCommands.end();
4129 }
4130 
4131 iterator_range<MachOObjectFile::load_command_iterator>
load_commands() const4132 MachOObjectFile::load_commands() const {
4133   return make_range(begin_load_commands(), end_load_commands());
4134 }
4135 
4136 StringRef
getSectionFinalSegmentName(DataRefImpl Sec) const4137 MachOObjectFile::getSectionFinalSegmentName(DataRefImpl Sec) const {
4138   ArrayRef<char> Raw = getSectionRawFinalSegmentName(Sec);
4139   return parseSegmentOrSectionName(Raw.data());
4140 }
4141 
4142 ArrayRef<char>
getSectionRawName(DataRefImpl Sec) const4143 MachOObjectFile::getSectionRawName(DataRefImpl Sec) const {
4144   assert(Sec.d.a < Sections.size() && "Should have detected this earlier");
4145   const section_base *Base =
4146     reinterpret_cast<const section_base *>(Sections[Sec.d.a]);
4147   return makeArrayRef(Base->sectname);
4148 }
4149 
4150 ArrayRef<char>
getSectionRawFinalSegmentName(DataRefImpl Sec) const4151 MachOObjectFile::getSectionRawFinalSegmentName(DataRefImpl Sec) const {
4152   assert(Sec.d.a < Sections.size() && "Should have detected this earlier");
4153   const section_base *Base =
4154     reinterpret_cast<const section_base *>(Sections[Sec.d.a]);
4155   return makeArrayRef(Base->segname);
4156 }
4157 
4158 bool
isRelocationScattered(const MachO::any_relocation_info & RE) const4159 MachOObjectFile::isRelocationScattered(const MachO::any_relocation_info &RE)
4160   const {
4161   if (getCPUType(*this) == MachO::CPU_TYPE_X86_64)
4162     return false;
4163   return getPlainRelocationAddress(RE) & MachO::R_SCATTERED;
4164 }
4165 
getPlainRelocationSymbolNum(const MachO::any_relocation_info & RE) const4166 unsigned MachOObjectFile::getPlainRelocationSymbolNum(
4167     const MachO::any_relocation_info &RE) const {
4168   if (isLittleEndian())
4169     return RE.r_word1 & 0xffffff;
4170   return RE.r_word1 >> 8;
4171 }
4172 
getPlainRelocationExternal(const MachO::any_relocation_info & RE) const4173 bool MachOObjectFile::getPlainRelocationExternal(
4174     const MachO::any_relocation_info &RE) const {
4175   if (isLittleEndian())
4176     return (RE.r_word1 >> 27) & 1;
4177   return (RE.r_word1 >> 4) & 1;
4178 }
4179 
getScatteredRelocationScattered(const MachO::any_relocation_info & RE) const4180 bool MachOObjectFile::getScatteredRelocationScattered(
4181     const MachO::any_relocation_info &RE) const {
4182   return RE.r_word0 >> 31;
4183 }
4184 
getScatteredRelocationValue(const MachO::any_relocation_info & RE) const4185 uint32_t MachOObjectFile::getScatteredRelocationValue(
4186     const MachO::any_relocation_info &RE) const {
4187   return RE.r_word1;
4188 }
4189 
getScatteredRelocationType(const MachO::any_relocation_info & RE) const4190 uint32_t MachOObjectFile::getScatteredRelocationType(
4191     const MachO::any_relocation_info &RE) const {
4192   return (RE.r_word0 >> 24) & 0xf;
4193 }
4194 
getAnyRelocationAddress(const MachO::any_relocation_info & RE) const4195 unsigned MachOObjectFile::getAnyRelocationAddress(
4196     const MachO::any_relocation_info &RE) const {
4197   if (isRelocationScattered(RE))
4198     return getScatteredRelocationAddress(RE);
4199   return getPlainRelocationAddress(RE);
4200 }
4201 
getAnyRelocationPCRel(const MachO::any_relocation_info & RE) const4202 unsigned MachOObjectFile::getAnyRelocationPCRel(
4203     const MachO::any_relocation_info &RE) const {
4204   if (isRelocationScattered(RE))
4205     return getScatteredRelocationPCRel(RE);
4206   return getPlainRelocationPCRel(*this, RE);
4207 }
4208 
getAnyRelocationLength(const MachO::any_relocation_info & RE) const4209 unsigned MachOObjectFile::getAnyRelocationLength(
4210     const MachO::any_relocation_info &RE) const {
4211   if (isRelocationScattered(RE))
4212     return getScatteredRelocationLength(RE);
4213   return getPlainRelocationLength(*this, RE);
4214 }
4215 
4216 unsigned
getAnyRelocationType(const MachO::any_relocation_info & RE) const4217 MachOObjectFile::getAnyRelocationType(
4218                                    const MachO::any_relocation_info &RE) const {
4219   if (isRelocationScattered(RE))
4220     return getScatteredRelocationType(RE);
4221   return getPlainRelocationType(*this, RE);
4222 }
4223 
4224 SectionRef
getAnyRelocationSection(const MachO::any_relocation_info & RE) const4225 MachOObjectFile::getAnyRelocationSection(
4226                                    const MachO::any_relocation_info &RE) const {
4227   if (isRelocationScattered(RE) || getPlainRelocationExternal(RE))
4228     return *section_end();
4229   unsigned SecNum = getPlainRelocationSymbolNum(RE);
4230   if (SecNum == MachO::R_ABS || SecNum > Sections.size())
4231     return *section_end();
4232   DataRefImpl DRI;
4233   DRI.d.a = SecNum - 1;
4234   return SectionRef(DRI, this);
4235 }
4236 
getSection(DataRefImpl DRI) const4237 MachO::section MachOObjectFile::getSection(DataRefImpl DRI) const {
4238   assert(DRI.d.a < Sections.size() && "Should have detected this earlier");
4239   return getStruct<MachO::section>(*this, Sections[DRI.d.a]);
4240 }
4241 
getSection64(DataRefImpl DRI) const4242 MachO::section_64 MachOObjectFile::getSection64(DataRefImpl DRI) const {
4243   assert(DRI.d.a < Sections.size() && "Should have detected this earlier");
4244   return getStruct<MachO::section_64>(*this, Sections[DRI.d.a]);
4245 }
4246 
getSection(const LoadCommandInfo & L,unsigned Index) const4247 MachO::section MachOObjectFile::getSection(const LoadCommandInfo &L,
4248                                            unsigned Index) const {
4249   const char *Sec = getSectionPtr(*this, L, Index);
4250   return getStruct<MachO::section>(*this, Sec);
4251 }
4252 
getSection64(const LoadCommandInfo & L,unsigned Index) const4253 MachO::section_64 MachOObjectFile::getSection64(const LoadCommandInfo &L,
4254                                                 unsigned Index) const {
4255   const char *Sec = getSectionPtr(*this, L, Index);
4256   return getStruct<MachO::section_64>(*this, Sec);
4257 }
4258 
4259 MachO::nlist
getSymbolTableEntry(DataRefImpl DRI) const4260 MachOObjectFile::getSymbolTableEntry(DataRefImpl DRI) const {
4261   const char *P = reinterpret_cast<const char *>(DRI.p);
4262   return getStruct<MachO::nlist>(*this, P);
4263 }
4264 
4265 MachO::nlist_64
getSymbol64TableEntry(DataRefImpl DRI) const4266 MachOObjectFile::getSymbol64TableEntry(DataRefImpl DRI) const {
4267   const char *P = reinterpret_cast<const char *>(DRI.p);
4268   return getStruct<MachO::nlist_64>(*this, P);
4269 }
4270 
4271 MachO::linkedit_data_command
getLinkeditDataLoadCommand(const LoadCommandInfo & L) const4272 MachOObjectFile::getLinkeditDataLoadCommand(const LoadCommandInfo &L) const {
4273   return getStruct<MachO::linkedit_data_command>(*this, L.Ptr);
4274 }
4275 
4276 MachO::segment_command
getSegmentLoadCommand(const LoadCommandInfo & L) const4277 MachOObjectFile::getSegmentLoadCommand(const LoadCommandInfo &L) const {
4278   return getStruct<MachO::segment_command>(*this, L.Ptr);
4279 }
4280 
4281 MachO::segment_command_64
getSegment64LoadCommand(const LoadCommandInfo & L) const4282 MachOObjectFile::getSegment64LoadCommand(const LoadCommandInfo &L) const {
4283   return getStruct<MachO::segment_command_64>(*this, L.Ptr);
4284 }
4285 
4286 MachO::linker_option_command
getLinkerOptionLoadCommand(const LoadCommandInfo & L) const4287 MachOObjectFile::getLinkerOptionLoadCommand(const LoadCommandInfo &L) const {
4288   return getStruct<MachO::linker_option_command>(*this, L.Ptr);
4289 }
4290 
4291 MachO::version_min_command
getVersionMinLoadCommand(const LoadCommandInfo & L) const4292 MachOObjectFile::getVersionMinLoadCommand(const LoadCommandInfo &L) const {
4293   return getStruct<MachO::version_min_command>(*this, L.Ptr);
4294 }
4295 
4296 MachO::note_command
getNoteLoadCommand(const LoadCommandInfo & L) const4297 MachOObjectFile::getNoteLoadCommand(const LoadCommandInfo &L) const {
4298   return getStruct<MachO::note_command>(*this, L.Ptr);
4299 }
4300 
4301 MachO::build_version_command
getBuildVersionLoadCommand(const LoadCommandInfo & L) const4302 MachOObjectFile::getBuildVersionLoadCommand(const LoadCommandInfo &L) const {
4303   return getStruct<MachO::build_version_command>(*this, L.Ptr);
4304 }
4305 
4306 MachO::build_tool_version
getBuildToolVersion(unsigned index) const4307 MachOObjectFile::getBuildToolVersion(unsigned index) const {
4308   return getStruct<MachO::build_tool_version>(*this, BuildTools[index]);
4309 }
4310 
4311 MachO::dylib_command
getDylibIDLoadCommand(const LoadCommandInfo & L) const4312 MachOObjectFile::getDylibIDLoadCommand(const LoadCommandInfo &L) const {
4313   return getStruct<MachO::dylib_command>(*this, L.Ptr);
4314 }
4315 
4316 MachO::dyld_info_command
getDyldInfoLoadCommand(const LoadCommandInfo & L) const4317 MachOObjectFile::getDyldInfoLoadCommand(const LoadCommandInfo &L) const {
4318   return getStruct<MachO::dyld_info_command>(*this, L.Ptr);
4319 }
4320 
4321 MachO::dylinker_command
getDylinkerCommand(const LoadCommandInfo & L) const4322 MachOObjectFile::getDylinkerCommand(const LoadCommandInfo &L) const {
4323   return getStruct<MachO::dylinker_command>(*this, L.Ptr);
4324 }
4325 
4326 MachO::uuid_command
getUuidCommand(const LoadCommandInfo & L) const4327 MachOObjectFile::getUuidCommand(const LoadCommandInfo &L) const {
4328   return getStruct<MachO::uuid_command>(*this, L.Ptr);
4329 }
4330 
4331 MachO::rpath_command
getRpathCommand(const LoadCommandInfo & L) const4332 MachOObjectFile::getRpathCommand(const LoadCommandInfo &L) const {
4333   return getStruct<MachO::rpath_command>(*this, L.Ptr);
4334 }
4335 
4336 MachO::source_version_command
getSourceVersionCommand(const LoadCommandInfo & L) const4337 MachOObjectFile::getSourceVersionCommand(const LoadCommandInfo &L) const {
4338   return getStruct<MachO::source_version_command>(*this, L.Ptr);
4339 }
4340 
4341 MachO::entry_point_command
getEntryPointCommand(const LoadCommandInfo & L) const4342 MachOObjectFile::getEntryPointCommand(const LoadCommandInfo &L) const {
4343   return getStruct<MachO::entry_point_command>(*this, L.Ptr);
4344 }
4345 
4346 MachO::encryption_info_command
getEncryptionInfoCommand(const LoadCommandInfo & L) const4347 MachOObjectFile::getEncryptionInfoCommand(const LoadCommandInfo &L) const {
4348   return getStruct<MachO::encryption_info_command>(*this, L.Ptr);
4349 }
4350 
4351 MachO::encryption_info_command_64
getEncryptionInfoCommand64(const LoadCommandInfo & L) const4352 MachOObjectFile::getEncryptionInfoCommand64(const LoadCommandInfo &L) const {
4353   return getStruct<MachO::encryption_info_command_64>(*this, L.Ptr);
4354 }
4355 
4356 MachO::sub_framework_command
getSubFrameworkCommand(const LoadCommandInfo & L) const4357 MachOObjectFile::getSubFrameworkCommand(const LoadCommandInfo &L) const {
4358   return getStruct<MachO::sub_framework_command>(*this, L.Ptr);
4359 }
4360 
4361 MachO::sub_umbrella_command
getSubUmbrellaCommand(const LoadCommandInfo & L) const4362 MachOObjectFile::getSubUmbrellaCommand(const LoadCommandInfo &L) const {
4363   return getStruct<MachO::sub_umbrella_command>(*this, L.Ptr);
4364 }
4365 
4366 MachO::sub_library_command
getSubLibraryCommand(const LoadCommandInfo & L) const4367 MachOObjectFile::getSubLibraryCommand(const LoadCommandInfo &L) const {
4368   return getStruct<MachO::sub_library_command>(*this, L.Ptr);
4369 }
4370 
4371 MachO::sub_client_command
getSubClientCommand(const LoadCommandInfo & L) const4372 MachOObjectFile::getSubClientCommand(const LoadCommandInfo &L) const {
4373   return getStruct<MachO::sub_client_command>(*this, L.Ptr);
4374 }
4375 
4376 MachO::routines_command
getRoutinesCommand(const LoadCommandInfo & L) const4377 MachOObjectFile::getRoutinesCommand(const LoadCommandInfo &L) const {
4378   return getStruct<MachO::routines_command>(*this, L.Ptr);
4379 }
4380 
4381 MachO::routines_command_64
getRoutinesCommand64(const LoadCommandInfo & L) const4382 MachOObjectFile::getRoutinesCommand64(const LoadCommandInfo &L) const {
4383   return getStruct<MachO::routines_command_64>(*this, L.Ptr);
4384 }
4385 
4386 MachO::thread_command
getThreadCommand(const LoadCommandInfo & L) const4387 MachOObjectFile::getThreadCommand(const LoadCommandInfo &L) const {
4388   return getStruct<MachO::thread_command>(*this, L.Ptr);
4389 }
4390 
4391 MachO::any_relocation_info
getRelocation(DataRefImpl Rel) const4392 MachOObjectFile::getRelocation(DataRefImpl Rel) const {
4393   uint32_t Offset;
4394   if (getHeader().filetype == MachO::MH_OBJECT) {
4395     DataRefImpl Sec;
4396     Sec.d.a = Rel.d.a;
4397     if (is64Bit()) {
4398       MachO::section_64 Sect = getSection64(Sec);
4399       Offset = Sect.reloff;
4400     } else {
4401       MachO::section Sect = getSection(Sec);
4402       Offset = Sect.reloff;
4403     }
4404   } else {
4405     MachO::dysymtab_command DysymtabLoadCmd = getDysymtabLoadCommand();
4406     if (Rel.d.a == 0)
4407       Offset = DysymtabLoadCmd.extreloff; // Offset to the external relocations
4408     else
4409       Offset = DysymtabLoadCmd.locreloff; // Offset to the local relocations
4410   }
4411 
4412   auto P = reinterpret_cast<const MachO::any_relocation_info *>(
4413       getPtr(*this, Offset)) + Rel.d.b;
4414   return getStruct<MachO::any_relocation_info>(
4415       *this, reinterpret_cast<const char *>(P));
4416 }
4417 
4418 MachO::data_in_code_entry
getDice(DataRefImpl Rel) const4419 MachOObjectFile::getDice(DataRefImpl Rel) const {
4420   const char *P = reinterpret_cast<const char *>(Rel.p);
4421   return getStruct<MachO::data_in_code_entry>(*this, P);
4422 }
4423 
getHeader() const4424 const MachO::mach_header &MachOObjectFile::getHeader() const {
4425   return Header;
4426 }
4427 
getHeader64() const4428 const MachO::mach_header_64 &MachOObjectFile::getHeader64() const {
4429   assert(is64Bit());
4430   return Header64;
4431 }
4432 
getIndirectSymbolTableEntry(const MachO::dysymtab_command & DLC,unsigned Index) const4433 uint32_t MachOObjectFile::getIndirectSymbolTableEntry(
4434                                              const MachO::dysymtab_command &DLC,
4435                                              unsigned Index) const {
4436   uint64_t Offset = DLC.indirectsymoff + Index * sizeof(uint32_t);
4437   return getStruct<uint32_t>(*this, getPtr(*this, Offset));
4438 }
4439 
4440 MachO::data_in_code_entry
getDataInCodeTableEntry(uint32_t DataOffset,unsigned Index) const4441 MachOObjectFile::getDataInCodeTableEntry(uint32_t DataOffset,
4442                                          unsigned Index) const {
4443   uint64_t Offset = DataOffset + Index * sizeof(MachO::data_in_code_entry);
4444   return getStruct<MachO::data_in_code_entry>(*this, getPtr(*this, Offset));
4445 }
4446 
getSymtabLoadCommand() const4447 MachO::symtab_command MachOObjectFile::getSymtabLoadCommand() const {
4448   if (SymtabLoadCmd)
4449     return getStruct<MachO::symtab_command>(*this, SymtabLoadCmd);
4450 
4451   // If there is no SymtabLoadCmd return a load command with zero'ed fields.
4452   MachO::symtab_command Cmd;
4453   Cmd.cmd = MachO::LC_SYMTAB;
4454   Cmd.cmdsize = sizeof(MachO::symtab_command);
4455   Cmd.symoff = 0;
4456   Cmd.nsyms = 0;
4457   Cmd.stroff = 0;
4458   Cmd.strsize = 0;
4459   return Cmd;
4460 }
4461 
getDysymtabLoadCommand() const4462 MachO::dysymtab_command MachOObjectFile::getDysymtabLoadCommand() const {
4463   if (DysymtabLoadCmd)
4464     return getStruct<MachO::dysymtab_command>(*this, DysymtabLoadCmd);
4465 
4466   // If there is no DysymtabLoadCmd return a load command with zero'ed fields.
4467   MachO::dysymtab_command Cmd;
4468   Cmd.cmd = MachO::LC_DYSYMTAB;
4469   Cmd.cmdsize = sizeof(MachO::dysymtab_command);
4470   Cmd.ilocalsym = 0;
4471   Cmd.nlocalsym = 0;
4472   Cmd.iextdefsym = 0;
4473   Cmd.nextdefsym = 0;
4474   Cmd.iundefsym = 0;
4475   Cmd.nundefsym = 0;
4476   Cmd.tocoff = 0;
4477   Cmd.ntoc = 0;
4478   Cmd.modtaboff = 0;
4479   Cmd.nmodtab = 0;
4480   Cmd.extrefsymoff = 0;
4481   Cmd.nextrefsyms = 0;
4482   Cmd.indirectsymoff = 0;
4483   Cmd.nindirectsyms = 0;
4484   Cmd.extreloff = 0;
4485   Cmd.nextrel = 0;
4486   Cmd.locreloff = 0;
4487   Cmd.nlocrel = 0;
4488   return Cmd;
4489 }
4490 
4491 MachO::linkedit_data_command
getDataInCodeLoadCommand() const4492 MachOObjectFile::getDataInCodeLoadCommand() const {
4493   if (DataInCodeLoadCmd)
4494     return getStruct<MachO::linkedit_data_command>(*this, DataInCodeLoadCmd);
4495 
4496   // If there is no DataInCodeLoadCmd return a load command with zero'ed fields.
4497   MachO::linkedit_data_command Cmd;
4498   Cmd.cmd = MachO::LC_DATA_IN_CODE;
4499   Cmd.cmdsize = sizeof(MachO::linkedit_data_command);
4500   Cmd.dataoff = 0;
4501   Cmd.datasize = 0;
4502   return Cmd;
4503 }
4504 
4505 MachO::linkedit_data_command
getLinkOptHintsLoadCommand() const4506 MachOObjectFile::getLinkOptHintsLoadCommand() const {
4507   if (LinkOptHintsLoadCmd)
4508     return getStruct<MachO::linkedit_data_command>(*this, LinkOptHintsLoadCmd);
4509 
4510   // If there is no LinkOptHintsLoadCmd return a load command with zero'ed
4511   // fields.
4512   MachO::linkedit_data_command Cmd;
4513   Cmd.cmd = MachO::LC_LINKER_OPTIMIZATION_HINT;
4514   Cmd.cmdsize = sizeof(MachO::linkedit_data_command);
4515   Cmd.dataoff = 0;
4516   Cmd.datasize = 0;
4517   return Cmd;
4518 }
4519 
getDyldInfoRebaseOpcodes() const4520 ArrayRef<uint8_t> MachOObjectFile::getDyldInfoRebaseOpcodes() const {
4521   if (!DyldInfoLoadCmd)
4522     return None;
4523 
4524   auto DyldInfoOrErr =
4525     getStructOrErr<MachO::dyld_info_command>(*this, DyldInfoLoadCmd);
4526   if (!DyldInfoOrErr)
4527     return None;
4528   MachO::dyld_info_command DyldInfo = DyldInfoOrErr.get();
4529   const uint8_t *Ptr =
4530       reinterpret_cast<const uint8_t *>(getPtr(*this, DyldInfo.rebase_off));
4531   return makeArrayRef(Ptr, DyldInfo.rebase_size);
4532 }
4533 
getDyldInfoBindOpcodes() const4534 ArrayRef<uint8_t> MachOObjectFile::getDyldInfoBindOpcodes() const {
4535   if (!DyldInfoLoadCmd)
4536     return None;
4537 
4538   auto DyldInfoOrErr =
4539     getStructOrErr<MachO::dyld_info_command>(*this, DyldInfoLoadCmd);
4540   if (!DyldInfoOrErr)
4541     return None;
4542   MachO::dyld_info_command DyldInfo = DyldInfoOrErr.get();
4543   const uint8_t *Ptr =
4544       reinterpret_cast<const uint8_t *>(getPtr(*this, DyldInfo.bind_off));
4545   return makeArrayRef(Ptr, DyldInfo.bind_size);
4546 }
4547 
getDyldInfoWeakBindOpcodes() const4548 ArrayRef<uint8_t> MachOObjectFile::getDyldInfoWeakBindOpcodes() const {
4549   if (!DyldInfoLoadCmd)
4550     return None;
4551 
4552   auto DyldInfoOrErr =
4553     getStructOrErr<MachO::dyld_info_command>(*this, DyldInfoLoadCmd);
4554   if (!DyldInfoOrErr)
4555     return None;
4556   MachO::dyld_info_command DyldInfo = DyldInfoOrErr.get();
4557   const uint8_t *Ptr =
4558       reinterpret_cast<const uint8_t *>(getPtr(*this, DyldInfo.weak_bind_off));
4559   return makeArrayRef(Ptr, DyldInfo.weak_bind_size);
4560 }
4561 
getDyldInfoLazyBindOpcodes() const4562 ArrayRef<uint8_t> MachOObjectFile::getDyldInfoLazyBindOpcodes() const {
4563   if (!DyldInfoLoadCmd)
4564     return None;
4565 
4566   auto DyldInfoOrErr =
4567     getStructOrErr<MachO::dyld_info_command>(*this, DyldInfoLoadCmd);
4568   if (!DyldInfoOrErr)
4569     return None;
4570   MachO::dyld_info_command DyldInfo = DyldInfoOrErr.get();
4571   const uint8_t *Ptr =
4572       reinterpret_cast<const uint8_t *>(getPtr(*this, DyldInfo.lazy_bind_off));
4573   return makeArrayRef(Ptr, DyldInfo.lazy_bind_size);
4574 }
4575 
getDyldInfoExportsTrie() const4576 ArrayRef<uint8_t> MachOObjectFile::getDyldInfoExportsTrie() const {
4577   if (!DyldInfoLoadCmd)
4578     return None;
4579 
4580   auto DyldInfoOrErr =
4581     getStructOrErr<MachO::dyld_info_command>(*this, DyldInfoLoadCmd);
4582   if (!DyldInfoOrErr)
4583     return None;
4584   MachO::dyld_info_command DyldInfo = DyldInfoOrErr.get();
4585   const uint8_t *Ptr =
4586       reinterpret_cast<const uint8_t *>(getPtr(*this, DyldInfo.export_off));
4587   return makeArrayRef(Ptr, DyldInfo.export_size);
4588 }
4589 
getUuid() const4590 ArrayRef<uint8_t> MachOObjectFile::getUuid() const {
4591   if (!UuidLoadCmd)
4592     return None;
4593   // Returning a pointer is fine as uuid doesn't need endian swapping.
4594   const char *Ptr = UuidLoadCmd + offsetof(MachO::uuid_command, uuid);
4595   return makeArrayRef(reinterpret_cast<const uint8_t *>(Ptr), 16);
4596 }
4597 
getStringTableData() const4598 StringRef MachOObjectFile::getStringTableData() const {
4599   MachO::symtab_command S = getSymtabLoadCommand();
4600   return getData().substr(S.stroff, S.strsize);
4601 }
4602 
is64Bit() const4603 bool MachOObjectFile::is64Bit() const {
4604   return getType() == getMachOType(false, true) ||
4605     getType() == getMachOType(true, true);
4606 }
4607 
ReadULEB128s(uint64_t Index,SmallVectorImpl<uint64_t> & Out) const4608 void MachOObjectFile::ReadULEB128s(uint64_t Index,
4609                                    SmallVectorImpl<uint64_t> &Out) const {
4610   DataExtractor extractor(ObjectFile::getData(), true, 0);
4611 
4612   uint64_t offset = Index;
4613   uint64_t data = 0;
4614   while (uint64_t delta = extractor.getULEB128(&offset)) {
4615     data += delta;
4616     Out.push_back(data);
4617   }
4618 }
4619 
isRelocatableObject() const4620 bool MachOObjectFile::isRelocatableObject() const {
4621   return getHeader().filetype == MachO::MH_OBJECT;
4622 }
4623 
4624 Expected<std::unique_ptr<MachOObjectFile>>
createMachOObjectFile(MemoryBufferRef Buffer,uint32_t UniversalCputype,uint32_t UniversalIndex)4625 ObjectFile::createMachOObjectFile(MemoryBufferRef Buffer,
4626                                   uint32_t UniversalCputype,
4627                                   uint32_t UniversalIndex) {
4628   StringRef Magic = Buffer.getBuffer().slice(0, 4);
4629   if (Magic == "\xFE\xED\xFA\xCE")
4630     return MachOObjectFile::create(Buffer, false, false,
4631                                    UniversalCputype, UniversalIndex);
4632   if (Magic == "\xCE\xFA\xED\xFE")
4633     return MachOObjectFile::create(Buffer, true, false,
4634                                    UniversalCputype, UniversalIndex);
4635   if (Magic == "\xFE\xED\xFA\xCF")
4636     return MachOObjectFile::create(Buffer, false, true,
4637                                    UniversalCputype, UniversalIndex);
4638   if (Magic == "\xCF\xFA\xED\xFE")
4639     return MachOObjectFile::create(Buffer, true, true,
4640                                    UniversalCputype, UniversalIndex);
4641   return make_error<GenericBinaryError>("Unrecognized MachO magic number",
4642                                         object_error::invalid_file_type);
4643 }
4644 
mapDebugSectionName(StringRef Name) const4645 StringRef MachOObjectFile::mapDebugSectionName(StringRef Name) const {
4646   return StringSwitch<StringRef>(Name)
4647       .Case("debug_str_offs", "debug_str_offsets")
4648       .Default(Name);
4649 }
4650