LCOV - code coverage report
Current view: top level - lib/Object - MachOObjectFile.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 2441 2842 85.9 %
Date: 2017-09-14 15:23:50 Functions: 245 259 94.6 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.13