blob: e8516369493f5492583a22a8c22e80f8e3f62ea2 [file] [log] [blame]
Eugene Zelenko9f5094d2017-04-21 22:03:05 +00001//===- MachOObjectFile.cpp - Mach-O object file binding -------------------===//
Eric Christopher7b015c72011-04-22 03:19:48 +00002//
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
Eugene Zelenko9f5094d2017-04-21 22:03:05 +000015#include "llvm/ADT/ArrayRef.h"
16#include "llvm/ADT/None.h"
17#include "llvm/ADT/SmallVector.h"
Tim Northover00ed9962014-03-29 10:18:08 +000018#include "llvm/ADT/STLExtras.h"
Eugene Zelenko9f5094d2017-04-21 22:03:05 +000019#include "llvm/ADT/StringExtras.h"
20#include "llvm/ADT/StringRef.h"
Rafael Espindola72318b42014-08-08 16:30:17 +000021#include "llvm/ADT/StringSwitch.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "llvm/ADT/Triple.h"
Eugene Zelenko9f5094d2017-04-21 22:03:05 +000023#include "llvm/ADT/Twine.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"
Rafael Espindola421305a2013-04-07 20:01:29 +000028#include "llvm/Support/DataExtractor.h"
Nick Kledzikac431442014-09-12 21:34:15 +000029#include "llvm/Support/Debug.h"
Eugene Zelenko9f5094d2017-04-21 22:03:05 +000030#include "llvm/Support/Error.h"
31#include "llvm/Support/ErrorHandling.h"
Owen Andersonbc14bd32011-10-26 20:42:54 +000032#include "llvm/Support/Format.h"
Rafael Espindola56f976f2013-04-18 18:08:55 +000033#include "llvm/Support/Host.h"
Nick Kledzikd04bc352014-08-30 00:20:14 +000034#include "llvm/Support/LEB128.h"
35#include "llvm/Support/MachO.h"
Eric Christopher7b015c72011-04-22 03:19:48 +000036#include "llvm/Support/MemoryBuffer.h"
Jakub Staszak84a0ae72013-08-21 01:20:11 +000037#include "llvm/Support/raw_ostream.h"
Eugene Zelenko9f5094d2017-04-21 22:03:05 +000038#include "llvm/Support/SwapByteOrder.h"
39#include <algorithm>
40#include <cassert>
41#include <cstddef>
42#include <cstdint>
Eric Christopher7b015c72011-04-22 03:19:48 +000043#include <cstring>
44#include <limits>
Kevin Enderbyd5039402016-10-31 20:29:48 +000045#include <list>
Eugene Zelenko9f5094d2017-04-21 22:03:05 +000046#include <memory>
47#include <string>
48#include <system_error>
Eric Christopher7b015c72011-04-22 03:19:48 +000049
50using namespace llvm;
51using namespace object;
52
Artyom Skrobov7d602f72014-07-20 12:08:28 +000053namespace {
Eugene Zelenko9f5094d2017-04-21 22:03:05 +000054
Artyom Skrobov7d602f72014-07-20 12:08:28 +000055 struct section_base {
56 char sectname[16];
57 char segname[16];
58 };
Eugene Zelenko9f5094d2017-04-21 22:03:05 +000059
60} // end anonymous namespace
Rafael Espindola56f976f2013-04-18 18:08:55 +000061
Lang Hames9e964f32016-03-25 17:25:34 +000062static Error
Kevin Enderbyd4e075b2016-05-06 20:16:28 +000063malformedError(Twine Msg) {
Kevin Enderby89134962016-05-05 23:41:05 +000064 std::string StringMsg = "truncated or malformed object (" + Msg.str() + ")";
Kevin Enderbyd4e075b2016-05-06 20:16:28 +000065 return make_error<GenericBinaryError>(std::move(StringMsg),
Kevin Enderby89134962016-05-05 23:41:05 +000066 object_error::parse_failed);
Lang Hames9e964f32016-03-25 17:25:34 +000067}
68
Alexey Samsonov9f336632015-06-04 19:45:22 +000069// FIXME: Replace all uses of this function with getStructOrErr.
Filipe Cabecinhas40139502015-01-15 22:52:38 +000070template <typename T>
Lang Hames697e7cd2016-12-04 01:56:10 +000071static T getStruct(const MachOObjectFile &O, const char *P) {
Filipe Cabecinhas40139502015-01-15 22:52:38 +000072 // Don't read before the beginning or past the end of the file
Lang Hames697e7cd2016-12-04 01:56:10 +000073 if (P < O.getData().begin() || P + sizeof(T) > O.getData().end())
Filipe Cabecinhas40139502015-01-15 22:52:38 +000074 report_fatal_error("Malformed MachO file.");
75
Rafael Espindola3cdeb172013-04-19 13:45:05 +000076 T Cmd;
77 memcpy(&Cmd, P, sizeof(T));
Lang Hames697e7cd2016-12-04 01:56:10 +000078 if (O.isLittleEndian() != sys::IsLittleEndianHost)
Artyom Skrobov78d5daf2014-07-18 09:26:16 +000079 MachO::swapStruct(Cmd);
Rafael Espindola3cdeb172013-04-19 13:45:05 +000080 return Cmd;
Rafael Espindola56f976f2013-04-18 18:08:55 +000081}
82
Alexey Samsonov9f336632015-06-04 19:45:22 +000083template <typename T>
Lang Hames697e7cd2016-12-04 01:56:10 +000084static Expected<T> getStructOrErr(const MachOObjectFile &O, const char *P) {
Alexey Samsonov9f336632015-06-04 19:45:22 +000085 // Don't read before the beginning or past the end of the file
Lang Hames697e7cd2016-12-04 01:56:10 +000086 if (P < O.getData().begin() || P + sizeof(T) > O.getData().end())
Kevin Enderbyd4e075b2016-05-06 20:16:28 +000087 return malformedError("Structure read out-of-range");
Alexey Samsonov9f336632015-06-04 19:45:22 +000088
89 T Cmd;
90 memcpy(&Cmd, P, sizeof(T));
Lang Hames697e7cd2016-12-04 01:56:10 +000091 if (O.isLittleEndian() != sys::IsLittleEndianHost)
Alexey Samsonov9f336632015-06-04 19:45:22 +000092 MachO::swapStruct(Cmd);
93 return Cmd;
94}
95
Rafael Espindola6e040c02013-04-26 20:07:33 +000096static const char *
Lang Hames697e7cd2016-12-04 01:56:10 +000097getSectionPtr(const MachOObjectFile &O, MachOObjectFile::LoadCommandInfo L,
Rafael Espindola6e040c02013-04-26 20:07:33 +000098 unsigned Sec) {
Rafael Espindola56f976f2013-04-18 18:08:55 +000099 uintptr_t CommandAddr = reinterpret_cast<uintptr_t>(L.Ptr);
100
Lang Hames697e7cd2016-12-04 01:56:10 +0000101 bool Is64 = O.is64Bit();
Charles Davis8bdfafd2013-09-01 04:28:48 +0000102 unsigned SegmentLoadSize = Is64 ? sizeof(MachO::segment_command_64) :
103 sizeof(MachO::segment_command);
104 unsigned SectionSize = Is64 ? sizeof(MachO::section_64) :
105 sizeof(MachO::section);
Rafael Espindola56f976f2013-04-18 18:08:55 +0000106
107 uintptr_t SectionAddr = CommandAddr + SegmentLoadSize + Sec * SectionSize;
Charles Davis1827bd82013-08-27 05:38:30 +0000108 return reinterpret_cast<const char*>(SectionAddr);
Rafael Espindola60689982013-04-07 19:05:30 +0000109}
110
Lang Hames697e7cd2016-12-04 01:56:10 +0000111static const char *getPtr(const MachOObjectFile &O, size_t Offset) {
112 return O.getData().substr(Offset, 1).data();
Rafael Espindola60689982013-04-07 19:05:30 +0000113}
114
Artyom Skrobov78d5daf2014-07-18 09:26:16 +0000115static MachO::nlist_base
Lang Hames697e7cd2016-12-04 01:56:10 +0000116getSymbolTableEntryBase(const MachOObjectFile &O, DataRefImpl DRI) {
Rafael Espindola75c30362013-04-24 19:47:55 +0000117 const char *P = reinterpret_cast<const char *>(DRI.p);
Artyom Skrobov78d5daf2014-07-18 09:26:16 +0000118 return getStruct<MachO::nlist_base>(O, P);
Eric Christopher7b015c72011-04-22 03:19:48 +0000119}
120
Rafael Espindola56f976f2013-04-18 18:08:55 +0000121static StringRef parseSegmentOrSectionName(const char *P) {
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000122 if (P[15] == 0)
123 // Null terminated.
124 return P;
125 // Not null terminated, so this is a 16 char string.
126 return StringRef(P, 16);
127}
128
Lang Hames697e7cd2016-12-04 01:56:10 +0000129static unsigned getCPUType(const MachOObjectFile &O) {
130 return O.getHeader().cputype;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000131}
132
Charles Davis8bdfafd2013-09-01 04:28:48 +0000133static uint32_t
134getPlainRelocationAddress(const MachO::any_relocation_info &RE) {
135 return RE.r_word0;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000136}
137
138static unsigned
Charles Davis8bdfafd2013-09-01 04:28:48 +0000139getScatteredRelocationAddress(const MachO::any_relocation_info &RE) {
140 return RE.r_word0 & 0xffffff;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000141}
142
Lang Hames697e7cd2016-12-04 01:56:10 +0000143static bool getPlainRelocationPCRel(const MachOObjectFile &O,
Charles Davis8bdfafd2013-09-01 04:28:48 +0000144 const MachO::any_relocation_info &RE) {
Lang Hames697e7cd2016-12-04 01:56:10 +0000145 if (O.isLittleEndian())
Charles Davis8bdfafd2013-09-01 04:28:48 +0000146 return (RE.r_word1 >> 24) & 1;
147 return (RE.r_word1 >> 7) & 1;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000148}
149
150static bool
Lang Hames697e7cd2016-12-04 01:56:10 +0000151getScatteredRelocationPCRel(const MachO::any_relocation_info &RE) {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000152 return (RE.r_word0 >> 30) & 1;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000153}
154
Lang Hames697e7cd2016-12-04 01:56:10 +0000155static unsigned getPlainRelocationLength(const MachOObjectFile &O,
Charles Davis8bdfafd2013-09-01 04:28:48 +0000156 const MachO::any_relocation_info &RE) {
Lang Hames697e7cd2016-12-04 01:56:10 +0000157 if (O.isLittleEndian())
Charles Davis8bdfafd2013-09-01 04:28:48 +0000158 return (RE.r_word1 >> 25) & 3;
159 return (RE.r_word1 >> 5) & 3;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000160}
161
162static unsigned
Charles Davis8bdfafd2013-09-01 04:28:48 +0000163getScatteredRelocationLength(const MachO::any_relocation_info &RE) {
164 return (RE.r_word0 >> 28) & 3;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000165}
166
Lang Hames697e7cd2016-12-04 01:56:10 +0000167static unsigned getPlainRelocationType(const MachOObjectFile &O,
Charles Davis8bdfafd2013-09-01 04:28:48 +0000168 const MachO::any_relocation_info &RE) {
Lang Hames697e7cd2016-12-04 01:56:10 +0000169 if (O.isLittleEndian())
Charles Davis8bdfafd2013-09-01 04:28:48 +0000170 return RE.r_word1 >> 28;
171 return RE.r_word1 & 0xf;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000172}
173
Lang Hames697e7cd2016-12-04 01:56:10 +0000174static uint32_t getSectionFlags(const MachOObjectFile &O,
Rafael Espindola56f976f2013-04-18 18:08:55 +0000175 DataRefImpl Sec) {
Lang Hames697e7cd2016-12-04 01:56:10 +0000176 if (O.is64Bit()) {
177 MachO::section_64 Sect = O.getSection64(Sec);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000178 return Sect.flags;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000179 }
Lang Hames697e7cd2016-12-04 01:56:10 +0000180 MachO::section Sect = O.getSection(Sec);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000181 return Sect.flags;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000182}
183
Lang Hames9e964f32016-03-25 17:25:34 +0000184static Expected<MachOObjectFile::LoadCommandInfo>
Lang Hames697e7cd2016-12-04 01:56:10 +0000185getLoadCommandInfo(const MachOObjectFile &Obj, const char *Ptr,
Kevin Enderbya8e3ab02016-05-03 23:13:50 +0000186 uint32_t LoadCommandIndex) {
Lang Hames9e964f32016-03-25 17:25:34 +0000187 if (auto CmdOrErr = getStructOrErr<MachO::load_command>(Obj, Ptr)) {
188 if (CmdOrErr->cmdsize < 8)
Kevin Enderbyd4e075b2016-05-06 20:16:28 +0000189 return malformedError("load command " + Twine(LoadCommandIndex) +
Kevin Enderby89134962016-05-05 23:41:05 +0000190 " with size less than 8 bytes");
Lang Hames9e964f32016-03-25 17:25:34 +0000191 return MachOObjectFile::LoadCommandInfo({Ptr, *CmdOrErr});
192 } else
193 return CmdOrErr.takeError();
Alexey Samsonov4fdbed32015-06-04 19:34:14 +0000194}
195
Lang Hames9e964f32016-03-25 17:25:34 +0000196static Expected<MachOObjectFile::LoadCommandInfo>
Lang Hames697e7cd2016-12-04 01:56:10 +0000197getFirstLoadCommandInfo(const MachOObjectFile &Obj) {
198 unsigned HeaderSize = Obj.is64Bit() ? sizeof(MachO::mach_header_64)
199 : sizeof(MachO::mach_header);
200 if (sizeof(MachO::load_command) > Obj.getHeader().sizeofcmds)
Kevin Enderbyd4e075b2016-05-06 20:16:28 +0000201 return malformedError("load command 0 extends past the end all load "
Kevin Enderby89134962016-05-05 23:41:05 +0000202 "commands in the file");
Kevin Enderbya8e3ab02016-05-03 23:13:50 +0000203 return getLoadCommandInfo(Obj, getPtr(Obj, HeaderSize), 0);
Alexey Samsonov4fdbed32015-06-04 19:34:14 +0000204}
205
Lang Hames9e964f32016-03-25 17:25:34 +0000206static Expected<MachOObjectFile::LoadCommandInfo>
Lang Hames697e7cd2016-12-04 01:56:10 +0000207getNextLoadCommandInfo(const MachOObjectFile &Obj, uint32_t LoadCommandIndex,
Alexey Samsonov4fdbed32015-06-04 19:34:14 +0000208 const MachOObjectFile::LoadCommandInfo &L) {
Lang Hames697e7cd2016-12-04 01:56:10 +0000209 unsigned HeaderSize = Obj.is64Bit() ? sizeof(MachO::mach_header_64)
210 : sizeof(MachO::mach_header);
Kevin Enderby9d0c9452016-08-31 17:57:46 +0000211 if (L.Ptr + L.C.cmdsize + sizeof(MachO::load_command) >
Lang Hames697e7cd2016-12-04 01:56:10 +0000212 Obj.getData().data() + HeaderSize + Obj.getHeader().sizeofcmds)
Kevin Enderbyd4e075b2016-05-06 20:16:28 +0000213 return malformedError("load command " + Twine(LoadCommandIndex + 1) +
Kevin Enderby89134962016-05-05 23:41:05 +0000214 " extends past the end all load commands in the file");
Kevin Enderbya8e3ab02016-05-03 23:13:50 +0000215 return getLoadCommandInfo(Obj, L.Ptr + L.C.cmdsize, LoadCommandIndex + 1);
Alexey Samsonov4fdbed32015-06-04 19:34:14 +0000216}
217
Alexey Samsonov9f336632015-06-04 19:45:22 +0000218template <typename T>
Lang Hames697e7cd2016-12-04 01:56:10 +0000219static void parseHeader(const MachOObjectFile &Obj, T &Header,
Lang Hames9e964f32016-03-25 17:25:34 +0000220 Error &Err) {
Lang Hames697e7cd2016-12-04 01:56:10 +0000221 if (sizeof(T) > Obj.getData().size()) {
Kevin Enderbyd4e075b2016-05-06 20:16:28 +0000222 Err = malformedError("the mach header extends past the end of the "
Kevin Enderby89134962016-05-05 23:41:05 +0000223 "file");
Kevin Enderby87025742016-04-13 21:17:58 +0000224 return;
225 }
Lang Hames9e964f32016-03-25 17:25:34 +0000226 if (auto HeaderOrErr = getStructOrErr<T>(Obj, getPtr(Obj, 0)))
227 Header = *HeaderOrErr;
Alexey Samsonov9f336632015-06-04 19:45:22 +0000228 else
Lang Hames9e964f32016-03-25 17:25:34 +0000229 Err = HeaderOrErr.takeError();
Alexey Samsonov9f336632015-06-04 19:45:22 +0000230}
231
Kevin Enderbyd5039402016-10-31 20:29:48 +0000232// This is used to check for overlapping of Mach-O elements.
233struct MachOElement {
234 uint64_t Offset;
235 uint64_t Size;
236 const char *Name;
237};
238
239static Error checkOverlappingElement(std::list<MachOElement> &Elements,
240 uint64_t Offset, uint64_t Size,
241 const char *Name) {
242 if (Size == 0)
243 return Error::success();
244
245 for (auto it=Elements.begin() ; it != Elements.end(); ++it) {
246 auto E = *it;
247 if ((Offset >= E.Offset && Offset < E.Offset + E.Size) ||
248 (Offset + Size > E.Offset && Offset + Size < E.Offset + E.Size) ||
249 (Offset <= E.Offset && Offset + Size >= E.Offset + E.Size))
250 return malformedError(Twine(Name) + " at offset " + Twine(Offset) +
251 " with a size of " + Twine(Size) + ", overlaps " +
252 E.Name + " at offset " + Twine(E.Offset) + " with "
253 "a size of " + Twine(E.Size));
254 auto nt = it;
255 nt++;
256 if (nt != Elements.end()) {
257 auto N = *nt;
258 if (Offset + Size <= N.Offset) {
259 Elements.insert(nt, {Offset, Size, Name});
260 return Error::success();
261 }
262 }
263 }
264 Elements.push_back({Offset, Size, Name});
265 return Error::success();
266}
267
Alexey Samsonove1a76ab2015-06-04 22:08:37 +0000268// Parses LC_SEGMENT or LC_SEGMENT_64 load command, adds addresses of all
269// sections to \param Sections, and optionally sets
270// \param IsPageZeroSegment to true.
Kevin Enderbyc614d282016-08-12 20:10:25 +0000271template <typename Segment, typename Section>
Lang Hames9e964f32016-03-25 17:25:34 +0000272static Error parseSegmentLoadCommand(
Lang Hames697e7cd2016-12-04 01:56:10 +0000273 const MachOObjectFile &Obj, const MachOObjectFile::LoadCommandInfo &Load,
Kevin Enderbyb34e3a12016-05-05 17:43:35 +0000274 SmallVectorImpl<const char *> &Sections, bool &IsPageZeroSegment,
Kevin Enderbyfbebe162016-11-02 21:08:39 +0000275 uint32_t LoadCommandIndex, const char *CmdName, uint64_t SizeOfHeaders,
276 std::list<MachOElement> &Elements) {
Kevin Enderbyc614d282016-08-12 20:10:25 +0000277 const unsigned SegmentLoadSize = sizeof(Segment);
Alexey Samsonove1a76ab2015-06-04 22:08:37 +0000278 if (Load.C.cmdsize < SegmentLoadSize)
Kevin Enderbyd4e075b2016-05-06 20:16:28 +0000279 return malformedError("load command " + Twine(LoadCommandIndex) +
Kevin Enderby89134962016-05-05 23:41:05 +0000280 " " + CmdName + " cmdsize too small");
Kevin Enderbyc614d282016-08-12 20:10:25 +0000281 if (auto SegOrErr = getStructOrErr<Segment>(Obj, Load.Ptr)) {
282 Segment S = SegOrErr.get();
283 const unsigned SectionSize = sizeof(Section);
Lang Hames697e7cd2016-12-04 01:56:10 +0000284 uint64_t FileSize = Obj.getData().size();
Lang Hames9e964f32016-03-25 17:25:34 +0000285 if (S.nsects > std::numeric_limits<uint32_t>::max() / SectionSize ||
286 S.nsects * SectionSize > Load.C.cmdsize - SegmentLoadSize)
Kevin Enderbyd4e075b2016-05-06 20:16:28 +0000287 return malformedError("load command " + Twine(LoadCommandIndex) +
NAKAMURA Takumi9d0b5312016-08-22 00:58:47 +0000288 " inconsistent cmdsize in " + CmdName +
Kevin Enderby89134962016-05-05 23:41:05 +0000289 " for the number of sections");
Lang Hames9e964f32016-03-25 17:25:34 +0000290 for (unsigned J = 0; J < S.nsects; ++J) {
291 const char *Sec = getSectionPtr(Obj, Load, J);
292 Sections.push_back(Sec);
Kevin Enderbyc614d282016-08-12 20:10:25 +0000293 Section s = getStruct<Section>(Obj, Sec);
Lang Hames697e7cd2016-12-04 01:56:10 +0000294 if (Obj.getHeader().filetype != MachO::MH_DYLIB_STUB &&
295 Obj.getHeader().filetype != MachO::MH_DSYM &&
Kevin Enderbyc614d282016-08-12 20:10:25 +0000296 s.flags != MachO::S_ZEROFILL &&
297 s.flags != MachO::S_THREAD_LOCAL_ZEROFILL &&
298 s.offset > FileSize)
299 return malformedError("offset field of section " + Twine(J) + " in " +
300 CmdName + " command " + Twine(LoadCommandIndex) +
301 " extends past the end of the file");
Lang Hames697e7cd2016-12-04 01:56:10 +0000302 if (Obj.getHeader().filetype != MachO::MH_DYLIB_STUB &&
303 Obj.getHeader().filetype != MachO::MH_DSYM &&
Kevin Enderbyc614d282016-08-12 20:10:25 +0000304 s.flags != MachO::S_ZEROFILL &&
NAKAMURA Takumi59a20642016-08-22 00:58:04 +0000305 s.flags != MachO::S_THREAD_LOCAL_ZEROFILL && S.fileoff == 0 &&
306 s.offset < SizeOfHeaders && s.size != 0)
Kevin Enderbyc614d282016-08-12 20:10:25 +0000307 return malformedError("offset field of section " + Twine(J) + " in " +
308 CmdName + " command " + Twine(LoadCommandIndex) +
309 " not past the headers of the file");
310 uint64_t BigSize = s.offset;
311 BigSize += s.size;
Lang Hames697e7cd2016-12-04 01:56:10 +0000312 if (Obj.getHeader().filetype != MachO::MH_DYLIB_STUB &&
313 Obj.getHeader().filetype != MachO::MH_DSYM &&
Kevin Enderbyc614d282016-08-12 20:10:25 +0000314 s.flags != MachO::S_ZEROFILL &&
315 s.flags != MachO::S_THREAD_LOCAL_ZEROFILL &&
316 BigSize > FileSize)
317 return malformedError("offset field plus size field of section " +
318 Twine(J) + " in " + CmdName + " command " +
319 Twine(LoadCommandIndex) +
320 " extends past the end of the file");
Lang Hames697e7cd2016-12-04 01:56:10 +0000321 if (Obj.getHeader().filetype != MachO::MH_DYLIB_STUB &&
322 Obj.getHeader().filetype != MachO::MH_DSYM &&
Kevin Enderbyc614d282016-08-12 20:10:25 +0000323 s.flags != MachO::S_ZEROFILL &&
324 s.flags != MachO::S_THREAD_LOCAL_ZEROFILL &&
325 s.size > S.filesize)
326 return malformedError("size field of section " +
327 Twine(J) + " in " + CmdName + " command " +
328 Twine(LoadCommandIndex) +
329 " greater than the segment");
Lang Hames697e7cd2016-12-04 01:56:10 +0000330 if (Obj.getHeader().filetype != MachO::MH_DYLIB_STUB &&
331 Obj.getHeader().filetype != MachO::MH_DSYM && s.size != 0 &&
NAKAMURA Takumi59a20642016-08-22 00:58:04 +0000332 s.addr < S.vmaddr)
333 return malformedError("addr field of section " + Twine(J) + " in " +
334 CmdName + " command " + Twine(LoadCommandIndex) +
335 " less than the segment's vmaddr");
Kevin Enderbyc614d282016-08-12 20:10:25 +0000336 BigSize = s.addr;
337 BigSize += s.size;
338 uint64_t BigEnd = S.vmaddr;
339 BigEnd += S.vmsize;
340 if (S.vmsize != 0 && s.size != 0 && BigSize > BigEnd)
NAKAMURA Takumi59a20642016-08-22 00:58:04 +0000341 return malformedError("addr field plus size of section " + Twine(J) +
342 " in " + CmdName + " command " +
343 Twine(LoadCommandIndex) +
344 " greater than than "
Kevin Enderbyc614d282016-08-12 20:10:25 +0000345 "the segment's vmaddr plus vmsize");
Lang Hames697e7cd2016-12-04 01:56:10 +0000346 if (Obj.getHeader().filetype != MachO::MH_DYLIB_STUB &&
347 Obj.getHeader().filetype != MachO::MH_DSYM &&
Kevin Enderbyfbebe162016-11-02 21:08:39 +0000348 s.flags != MachO::S_ZEROFILL &&
349 s.flags != MachO::S_THREAD_LOCAL_ZEROFILL)
350 if (Error Err = checkOverlappingElement(Elements, s.offset, s.size,
351 "section contents"))
352 return Err;
Kevin Enderbyc614d282016-08-12 20:10:25 +0000353 if (s.reloff > FileSize)
NAKAMURA Takumi59a20642016-08-22 00:58:04 +0000354 return malformedError("reloff field of section " + Twine(J) + " in " +
355 CmdName + " command " + Twine(LoadCommandIndex) +
Kevin Enderbyc614d282016-08-12 20:10:25 +0000356 " extends past the end of the file");
357 BigSize = s.nreloc;
358 BigSize *= sizeof(struct MachO::relocation_info);
359 BigSize += s.reloff;
360 if (BigSize > FileSize)
361 return malformedError("reloff field plus nreloc field times sizeof("
362 "struct relocation_info) of section " +
363 Twine(J) + " in " + CmdName + " command " +
NAKAMURA Takumi59a20642016-08-22 00:58:04 +0000364 Twine(LoadCommandIndex) +
Kevin Enderbyc614d282016-08-12 20:10:25 +0000365 " extends past the end of the file");
Kevin Enderbyfbebe162016-11-02 21:08:39 +0000366 if (Error Err = checkOverlappingElement(Elements, s.reloff, s.nreloc *
367 sizeof(struct
368 MachO::relocation_info),
369 "section relocation entries"))
370 return Err;
Lang Hames9e964f32016-03-25 17:25:34 +0000371 }
Kevin Enderby600fb3f2016-08-05 18:19:40 +0000372 if (S.fileoff > FileSize)
373 return malformedError("load command " + Twine(LoadCommandIndex) +
NAKAMURA Takumi9d0b5312016-08-22 00:58:47 +0000374 " fileoff field in " + CmdName +
Kevin Enderby600fb3f2016-08-05 18:19:40 +0000375 " extends past the end of the file");
Kevin Enderbyc614d282016-08-12 20:10:25 +0000376 uint64_t BigSize = S.fileoff;
377 BigSize += S.filesize;
378 if (BigSize > FileSize)
379 return malformedError("load command " + Twine(LoadCommandIndex) +
380 " fileoff field plus filesize field in " +
381 CmdName + " extends past the end of the file");
382 if (S.vmsize != 0 && S.filesize > S.vmsize)
383 return malformedError("load command " + Twine(LoadCommandIndex) +
Kevin Enderby86d8bd12017-02-07 21:20:44 +0000384 " filesize field in " + CmdName +
Kevin Enderbyc614d282016-08-12 20:10:25 +0000385 " greater than vmsize field");
Lang Hames9e964f32016-03-25 17:25:34 +0000386 IsPageZeroSegment |= StringRef("__PAGEZERO").equals(S.segname);
387 } else
388 return SegOrErr.takeError();
389
390 return Error::success();
Alexey Samsonove1a76ab2015-06-04 22:08:37 +0000391}
392
Lang Hames697e7cd2016-12-04 01:56:10 +0000393static Error checkSymtabCommand(const MachOObjectFile &Obj,
Kevin Enderby0e52c922016-08-26 19:34:07 +0000394 const MachOObjectFile::LoadCommandInfo &Load,
395 uint32_t LoadCommandIndex,
Kevin Enderbyd5039402016-10-31 20:29:48 +0000396 const char **SymtabLoadCmd,
397 std::list<MachOElement> &Elements) {
Kevin Enderby0e52c922016-08-26 19:34:07 +0000398 if (Load.C.cmdsize < sizeof(MachO::symtab_command))
399 return malformedError("load command " + Twine(LoadCommandIndex) +
400 " LC_SYMTAB cmdsize too small");
401 if (*SymtabLoadCmd != nullptr)
402 return malformedError("more than one LC_SYMTAB command");
403 MachO::symtab_command Symtab =
404 getStruct<MachO::symtab_command>(Obj, Load.Ptr);
405 if (Symtab.cmdsize != sizeof(MachO::symtab_command))
406 return malformedError("LC_SYMTAB command " + Twine(LoadCommandIndex) +
407 " has incorrect cmdsize");
Lang Hames697e7cd2016-12-04 01:56:10 +0000408 uint64_t FileSize = Obj.getData().size();
Kevin Enderby0e52c922016-08-26 19:34:07 +0000409 if (Symtab.symoff > FileSize)
410 return malformedError("symoff field of LC_SYMTAB command " +
411 Twine(LoadCommandIndex) + " extends past the end "
412 "of the file");
Kevin Enderbyd5039402016-10-31 20:29:48 +0000413 uint64_t SymtabSize = Symtab.nsyms;
Kevin Enderby0e52c922016-08-26 19:34:07 +0000414 const char *struct_nlist_name;
Lang Hames697e7cd2016-12-04 01:56:10 +0000415 if (Obj.is64Bit()) {
Kevin Enderbyd5039402016-10-31 20:29:48 +0000416 SymtabSize *= sizeof(MachO::nlist_64);
Kevin Enderby0e52c922016-08-26 19:34:07 +0000417 struct_nlist_name = "struct nlist_64";
418 } else {
Kevin Enderbyd5039402016-10-31 20:29:48 +0000419 SymtabSize *= sizeof(MachO::nlist);
Kevin Enderby0e52c922016-08-26 19:34:07 +0000420 struct_nlist_name = "struct nlist";
421 }
Kevin Enderbyd5039402016-10-31 20:29:48 +0000422 uint64_t BigSize = SymtabSize;
Kevin Enderby0e52c922016-08-26 19:34:07 +0000423 BigSize += Symtab.symoff;
424 if (BigSize > FileSize)
425 return malformedError("symoff field plus nsyms field times sizeof(" +
426 Twine(struct_nlist_name) + ") of LC_SYMTAB command " +
427 Twine(LoadCommandIndex) + " extends past the end "
428 "of the file");
Kevin Enderbyd5039402016-10-31 20:29:48 +0000429 if (Error Err = checkOverlappingElement(Elements, Symtab.symoff, SymtabSize,
430 "symbol table"))
431 return Err;
Kevin Enderby0e52c922016-08-26 19:34:07 +0000432 if (Symtab.stroff > FileSize)
433 return malformedError("stroff field of LC_SYMTAB command " +
434 Twine(LoadCommandIndex) + " extends past the end "
435 "of the file");
436 BigSize = Symtab.stroff;
437 BigSize += Symtab.strsize;
438 if (BigSize > FileSize)
439 return malformedError("stroff field plus strsize field of LC_SYMTAB "
440 "command " + Twine(LoadCommandIndex) + " extends "
441 "past the end of the file");
Kevin Enderbyd5039402016-10-31 20:29:48 +0000442 if (Error Err = checkOverlappingElement(Elements, Symtab.stroff,
443 Symtab.strsize, "string table"))
444 return Err;
Kevin Enderby0e52c922016-08-26 19:34:07 +0000445 *SymtabLoadCmd = Load.Ptr;
446 return Error::success();
447}
448
Lang Hames697e7cd2016-12-04 01:56:10 +0000449static Error checkDysymtabCommand(const MachOObjectFile &Obj,
450 const MachOObjectFile::LoadCommandInfo &Load,
451 uint32_t LoadCommandIndex,
452 const char **DysymtabLoadCmd,
453 std::list<MachOElement> &Elements) {
Kevin Enderbydcbc5042016-08-30 21:28:30 +0000454 if (Load.C.cmdsize < sizeof(MachO::dysymtab_command))
455 return malformedError("load command " + Twine(LoadCommandIndex) +
456 " LC_DYSYMTAB cmdsize too small");
457 if (*DysymtabLoadCmd != nullptr)
458 return malformedError("more than one LC_DYSYMTAB command");
459 MachO::dysymtab_command Dysymtab =
460 getStruct<MachO::dysymtab_command>(Obj, Load.Ptr);
461 if (Dysymtab.cmdsize != sizeof(MachO::dysymtab_command))
462 return malformedError("LC_DYSYMTAB command " + Twine(LoadCommandIndex) +
463 " has incorrect cmdsize");
Lang Hames697e7cd2016-12-04 01:56:10 +0000464 uint64_t FileSize = Obj.getData().size();
Kevin Enderbydcbc5042016-08-30 21:28:30 +0000465 if (Dysymtab.tocoff > FileSize)
466 return malformedError("tocoff field of LC_DYSYMTAB command " +
467 Twine(LoadCommandIndex) + " extends past the end of "
468 "the file");
469 uint64_t BigSize = Dysymtab.ntoc;
470 BigSize *= sizeof(MachO::dylib_table_of_contents);
471 BigSize += Dysymtab.tocoff;
472 if (BigSize > FileSize)
473 return malformedError("tocoff field plus ntoc field times sizeof(struct "
474 "dylib_table_of_contents) of LC_DYSYMTAB command " +
475 Twine(LoadCommandIndex) + " extends past the end of "
476 "the file");
Kevin Enderbyfbebe162016-11-02 21:08:39 +0000477 if (Error Err = checkOverlappingElement(Elements, Dysymtab.tocoff,
478 Dysymtab.ntoc * sizeof(struct
479 MachO::dylib_table_of_contents),
480 "table of contents"))
481 return Err;
Kevin Enderbydcbc5042016-08-30 21:28:30 +0000482 if (Dysymtab.modtaboff > FileSize)
483 return malformedError("modtaboff field of LC_DYSYMTAB command " +
484 Twine(LoadCommandIndex) + " extends past the end of "
485 "the file");
486 BigSize = Dysymtab.nmodtab;
487 const char *struct_dylib_module_name;
Kevin Enderbyfbebe162016-11-02 21:08:39 +0000488 uint64_t sizeof_modtab;
Lang Hames697e7cd2016-12-04 01:56:10 +0000489 if (Obj.is64Bit()) {
Kevin Enderbyfbebe162016-11-02 21:08:39 +0000490 sizeof_modtab = sizeof(MachO::dylib_module_64);
Kevin Enderbydcbc5042016-08-30 21:28:30 +0000491 struct_dylib_module_name = "struct dylib_module_64";
492 } else {
Kevin Enderbyfbebe162016-11-02 21:08:39 +0000493 sizeof_modtab = sizeof(MachO::dylib_module);
Kevin Enderbydcbc5042016-08-30 21:28:30 +0000494 struct_dylib_module_name = "struct dylib_module";
495 }
Kevin Enderbyfbebe162016-11-02 21:08:39 +0000496 BigSize *= sizeof_modtab;
Kevin Enderbydcbc5042016-08-30 21:28:30 +0000497 BigSize += Dysymtab.modtaboff;
498 if (BigSize > FileSize)
499 return malformedError("modtaboff field plus nmodtab field times sizeof(" +
500 Twine(struct_dylib_module_name) + ") of LC_DYSYMTAB "
501 "command " + Twine(LoadCommandIndex) + " extends "
502 "past the end of the file");
Kevin Enderbyfbebe162016-11-02 21:08:39 +0000503 if (Error Err = checkOverlappingElement(Elements, Dysymtab.modtaboff,
504 Dysymtab.nmodtab * sizeof_modtab,
505 "module table"))
506 return Err;
Kevin Enderbydcbc5042016-08-30 21:28:30 +0000507 if (Dysymtab.extrefsymoff > FileSize)
508 return malformedError("extrefsymoff field of LC_DYSYMTAB command " +
509 Twine(LoadCommandIndex) + " extends past the end of "
510 "the file");
511 BigSize = Dysymtab.nextrefsyms;
512 BigSize *= sizeof(MachO::dylib_reference);
513 BigSize += Dysymtab.extrefsymoff;
514 if (BigSize > FileSize)
515 return malformedError("extrefsymoff field plus nextrefsyms field times "
516 "sizeof(struct dylib_reference) of LC_DYSYMTAB "
517 "command " + Twine(LoadCommandIndex) + " extends "
518 "past the end of the file");
Kevin Enderbyfbebe162016-11-02 21:08:39 +0000519 if (Error Err = checkOverlappingElement(Elements, Dysymtab.extrefsymoff,
520 Dysymtab.nextrefsyms *
521 sizeof(MachO::dylib_reference),
522 "reference table"))
523 return Err;
Kevin Enderbydcbc5042016-08-30 21:28:30 +0000524 if (Dysymtab.indirectsymoff > FileSize)
525 return malformedError("indirectsymoff field of LC_DYSYMTAB command " +
526 Twine(LoadCommandIndex) + " extends past the end of "
527 "the file");
528 BigSize = Dysymtab.nindirectsyms;
529 BigSize *= sizeof(uint32_t);
530 BigSize += Dysymtab.indirectsymoff;
531 if (BigSize > FileSize)
532 return malformedError("indirectsymoff field plus nindirectsyms field times "
533 "sizeof(uint32_t) of LC_DYSYMTAB command " +
534 Twine(LoadCommandIndex) + " extends past the end of "
535 "the file");
Kevin Enderbyfbebe162016-11-02 21:08:39 +0000536 if (Error Err = checkOverlappingElement(Elements, Dysymtab.indirectsymoff,
537 Dysymtab.nindirectsyms *
538 sizeof(uint32_t),
539 "indirect table"))
540 return Err;
Kevin Enderbydcbc5042016-08-30 21:28:30 +0000541 if (Dysymtab.extreloff > FileSize)
542 return malformedError("extreloff field of LC_DYSYMTAB command " +
543 Twine(LoadCommandIndex) + " extends past the end of "
544 "the file");
545 BigSize = Dysymtab.nextrel;
546 BigSize *= sizeof(MachO::relocation_info);
547 BigSize += Dysymtab.extreloff;
548 if (BigSize > FileSize)
549 return malformedError("extreloff field plus nextrel field times sizeof"
550 "(struct relocation_info) of LC_DYSYMTAB command " +
551 Twine(LoadCommandIndex) + " extends past the end of "
552 "the file");
Kevin Enderbyfbebe162016-11-02 21:08:39 +0000553 if (Error Err = checkOverlappingElement(Elements, Dysymtab.extreloff,
554 Dysymtab.nextrel *
555 sizeof(MachO::relocation_info),
556 "external relocation table"))
557 return Err;
Kevin Enderbydcbc5042016-08-30 21:28:30 +0000558 if (Dysymtab.locreloff > FileSize)
559 return malformedError("locreloff field of LC_DYSYMTAB command " +
560 Twine(LoadCommandIndex) + " extends past the end of "
561 "the file");
562 BigSize = Dysymtab.nlocrel;
563 BigSize *= sizeof(MachO::relocation_info);
564 BigSize += Dysymtab.locreloff;
565 if (BigSize > FileSize)
566 return malformedError("locreloff field plus nlocrel field times sizeof"
567 "(struct relocation_info) of LC_DYSYMTAB command " +
568 Twine(LoadCommandIndex) + " extends past the end of "
569 "the file");
Kevin Enderbyfbebe162016-11-02 21:08:39 +0000570 if (Error Err = checkOverlappingElement(Elements, Dysymtab.locreloff,
571 Dysymtab.nlocrel *
572 sizeof(MachO::relocation_info),
573 "local relocation table"))
574 return Err;
Kevin Enderbydcbc5042016-08-30 21:28:30 +0000575 *DysymtabLoadCmd = Load.Ptr;
576 return Error::success();
577}
578
Lang Hames697e7cd2016-12-04 01:56:10 +0000579static Error checkLinkeditDataCommand(const MachOObjectFile &Obj,
Kevin Enderby9d0c9452016-08-31 17:57:46 +0000580 const MachOObjectFile::LoadCommandInfo &Load,
581 uint32_t LoadCommandIndex,
Kevin Enderbyfbebe162016-11-02 21:08:39 +0000582 const char **LoadCmd, const char *CmdName,
583 std::list<MachOElement> &Elements,
584 const char *ElementName) {
Kevin Enderby9d0c9452016-08-31 17:57:46 +0000585 if (Load.C.cmdsize < sizeof(MachO::linkedit_data_command))
586 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
587 CmdName + " cmdsize too small");
588 if (*LoadCmd != nullptr)
589 return malformedError("more than one " + Twine(CmdName) + " command");
590 MachO::linkedit_data_command LinkData =
591 getStruct<MachO::linkedit_data_command>(Obj, Load.Ptr);
592 if (LinkData.cmdsize != sizeof(MachO::linkedit_data_command))
593 return malformedError(Twine(CmdName) + " command " +
594 Twine(LoadCommandIndex) + " has incorrect cmdsize");
Lang Hames697e7cd2016-12-04 01:56:10 +0000595 uint64_t FileSize = Obj.getData().size();
Kevin Enderby9d0c9452016-08-31 17:57:46 +0000596 if (LinkData.dataoff > FileSize)
597 return malformedError("dataoff field of " + Twine(CmdName) + " command " +
598 Twine(LoadCommandIndex) + " extends past the end of "
599 "the file");
600 uint64_t BigSize = LinkData.dataoff;
601 BigSize += LinkData.datasize;
602 if (BigSize > FileSize)
603 return malformedError("dataoff field plus datasize field of " +
604 Twine(CmdName) + " command " +
605 Twine(LoadCommandIndex) + " extends past the end of "
606 "the file");
Kevin Enderbyfbebe162016-11-02 21:08:39 +0000607 if (Error Err = checkOverlappingElement(Elements, LinkData.dataoff,
608 LinkData.datasize, ElementName))
609 return Err;
Kevin Enderby9d0c9452016-08-31 17:57:46 +0000610 *LoadCmd = Load.Ptr;
611 return Error::success();
612}
613
Lang Hames697e7cd2016-12-04 01:56:10 +0000614static Error checkDyldInfoCommand(const MachOObjectFile &Obj,
Kevin Enderbyf76b56c2016-09-13 21:42:28 +0000615 const MachOObjectFile::LoadCommandInfo &Load,
616 uint32_t LoadCommandIndex,
Kevin Enderbyfbebe162016-11-02 21:08:39 +0000617 const char **LoadCmd, const char *CmdName,
618 std::list<MachOElement> &Elements) {
Kevin Enderbyf76b56c2016-09-13 21:42:28 +0000619 if (Load.C.cmdsize < sizeof(MachO::dyld_info_command))
620 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
621 CmdName + " cmdsize too small");
622 if (*LoadCmd != nullptr)
623 return malformedError("more than one LC_DYLD_INFO and or LC_DYLD_INFO_ONLY "
624 "command");
625 MachO::dyld_info_command DyldInfo =
626 getStruct<MachO::dyld_info_command>(Obj, Load.Ptr);
627 if (DyldInfo.cmdsize != sizeof(MachO::dyld_info_command))
628 return malformedError(Twine(CmdName) + " command " +
629 Twine(LoadCommandIndex) + " has incorrect cmdsize");
Lang Hames697e7cd2016-12-04 01:56:10 +0000630 uint64_t FileSize = Obj.getData().size();
Kevin Enderbyf76b56c2016-09-13 21:42:28 +0000631 if (DyldInfo.rebase_off > FileSize)
632 return malformedError("rebase_off field of " + Twine(CmdName) +
633 " command " + Twine(LoadCommandIndex) + " extends "
634 "past the end of the file");
635 uint64_t BigSize = DyldInfo.rebase_off;
636 BigSize += DyldInfo.rebase_size;
637 if (BigSize > FileSize)
638 return malformedError("rebase_off field plus rebase_size field of " +
639 Twine(CmdName) + " command " +
640 Twine(LoadCommandIndex) + " extends past the end of "
641 "the file");
Kevin Enderbyfbebe162016-11-02 21:08:39 +0000642 if (Error Err = checkOverlappingElement(Elements, DyldInfo.rebase_off,
643 DyldInfo.rebase_size,
644 "dyld rebase info"))
645 return Err;
Kevin Enderbyf76b56c2016-09-13 21:42:28 +0000646 if (DyldInfo.bind_off > FileSize)
647 return malformedError("bind_off field of " + Twine(CmdName) +
648 " command " + Twine(LoadCommandIndex) + " extends "
649 "past the end of the file");
650 BigSize = DyldInfo.bind_off;
651 BigSize += DyldInfo.bind_size;
652 if (BigSize > FileSize)
653 return malformedError("bind_off field plus bind_size field of " +
654 Twine(CmdName) + " command " +
655 Twine(LoadCommandIndex) + " extends past the end of "
656 "the file");
Kevin Enderbyfbebe162016-11-02 21:08:39 +0000657 if (Error Err = checkOverlappingElement(Elements, DyldInfo.bind_off,
658 DyldInfo.bind_size,
659 "dyld bind info"))
660 return Err;
Kevin Enderbyf76b56c2016-09-13 21:42:28 +0000661 if (DyldInfo.weak_bind_off > FileSize)
662 return malformedError("weak_bind_off field of " + Twine(CmdName) +
663 " command " + Twine(LoadCommandIndex) + " extends "
664 "past the end of the file");
665 BigSize = DyldInfo.weak_bind_off;
666 BigSize += DyldInfo.weak_bind_size;
667 if (BigSize > FileSize)
668 return malformedError("weak_bind_off field plus weak_bind_size field of " +
669 Twine(CmdName) + " command " +
670 Twine(LoadCommandIndex) + " extends past the end of "
671 "the file");
Kevin Enderbyfbebe162016-11-02 21:08:39 +0000672 if (Error Err = checkOverlappingElement(Elements, DyldInfo.weak_bind_off,
673 DyldInfo.weak_bind_size,
674 "dyld weak bind info"))
675 return Err;
Kevin Enderbyf76b56c2016-09-13 21:42:28 +0000676 if (DyldInfo.lazy_bind_off > FileSize)
677 return malformedError("lazy_bind_off field of " + Twine(CmdName) +
678 " command " + Twine(LoadCommandIndex) + " extends "
679 "past the end of the file");
680 BigSize = DyldInfo.lazy_bind_off;
681 BigSize += DyldInfo.lazy_bind_size;
682 if (BigSize > FileSize)
683 return malformedError("lazy_bind_off field plus lazy_bind_size field of " +
684 Twine(CmdName) + " command " +
685 Twine(LoadCommandIndex) + " extends past the end of "
686 "the file");
Kevin Enderbyfbebe162016-11-02 21:08:39 +0000687 if (Error Err = checkOverlappingElement(Elements, DyldInfo.lazy_bind_off,
688 DyldInfo.lazy_bind_size,
689 "dyld lazy bind info"))
690 return Err;
Kevin Enderbyf76b56c2016-09-13 21:42:28 +0000691 if (DyldInfo.export_off > FileSize)
692 return malformedError("export_off field of " + Twine(CmdName) +
693 " command " + Twine(LoadCommandIndex) + " extends "
694 "past the end of the file");
695 BigSize = DyldInfo.export_off;
696 BigSize += DyldInfo.export_size;
697 if (BigSize > FileSize)
698 return malformedError("export_off field plus export_size field of " +
699 Twine(CmdName) + " command " +
700 Twine(LoadCommandIndex) + " extends past the end of "
701 "the file");
Kevin Enderbyfbebe162016-11-02 21:08:39 +0000702 if (Error Err = checkOverlappingElement(Elements, DyldInfo.export_off,
703 DyldInfo.export_size,
704 "dyld export info"))
705 return Err;
Kevin Enderbyf76b56c2016-09-13 21:42:28 +0000706 *LoadCmd = Load.Ptr;
707 return Error::success();
708}
709
Lang Hames697e7cd2016-12-04 01:56:10 +0000710static Error checkDylibCommand(const MachOObjectFile &Obj,
Kevin Enderbyfc0929a2016-09-20 20:14:14 +0000711 const MachOObjectFile::LoadCommandInfo &Load,
712 uint32_t LoadCommandIndex, const char *CmdName) {
713 if (Load.C.cmdsize < sizeof(MachO::dylib_command))
714 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
715 CmdName + " cmdsize too small");
716 MachO::dylib_command D = getStruct<MachO::dylib_command>(Obj, Load.Ptr);
717 if (D.dylib.name < sizeof(MachO::dylib_command))
718 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
719 CmdName + " name.offset field too small, not past "
720 "the end of the dylib_command struct");
721 if (D.dylib.name >= D.cmdsize)
722 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
723 CmdName + " name.offset field extends past the end "
724 "of the load command");
725 // Make sure there is a null between the starting offset of the name and
726 // the end of the load command.
727 uint32_t i;
728 const char *P = (const char *)Load.Ptr;
729 for (i = D.dylib.name; i < D.cmdsize; i++)
730 if (P[i] == '\0')
731 break;
732 if (i >= D.cmdsize)
733 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
734 CmdName + " library name extends past the end of the "
735 "load command");
736 return Error::success();
737}
738
Lang Hames697e7cd2016-12-04 01:56:10 +0000739static Error checkDylibIdCommand(const MachOObjectFile &Obj,
Kevin Enderbyfc0929a2016-09-20 20:14:14 +0000740 const MachOObjectFile::LoadCommandInfo &Load,
741 uint32_t LoadCommandIndex,
742 const char **LoadCmd) {
743 if (Error Err = checkDylibCommand(Obj, Load, LoadCommandIndex,
744 "LC_ID_DYLIB"))
745 return Err;
746 if (*LoadCmd != nullptr)
747 return malformedError("more than one LC_ID_DYLIB command");
Lang Hames697e7cd2016-12-04 01:56:10 +0000748 if (Obj.getHeader().filetype != MachO::MH_DYLIB &&
749 Obj.getHeader().filetype != MachO::MH_DYLIB_STUB)
Kevin Enderbyfc0929a2016-09-20 20:14:14 +0000750 return malformedError("LC_ID_DYLIB load command in non-dynamic library "
751 "file type");
752 *LoadCmd = Load.Ptr;
753 return Error::success();
754}
755
Lang Hames697e7cd2016-12-04 01:56:10 +0000756static Error checkDyldCommand(const MachOObjectFile &Obj,
Kevin Enderby3e490ef2016-09-27 23:24:13 +0000757 const MachOObjectFile::LoadCommandInfo &Load,
758 uint32_t LoadCommandIndex, const char *CmdName) {
759 if (Load.C.cmdsize < sizeof(MachO::dylinker_command))
760 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
761 CmdName + " cmdsize too small");
762 MachO::dylinker_command D = getStruct<MachO::dylinker_command>(Obj, Load.Ptr);
763 if (D.name < sizeof(MachO::dylinker_command))
764 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
765 CmdName + " name.offset field too small, not past "
766 "the end of the dylinker_command struct");
767 if (D.name >= D.cmdsize)
768 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
769 CmdName + " name.offset field extends past the end "
770 "of the load command");
771 // Make sure there is a null between the starting offset of the name and
772 // the end of the load command.
773 uint32_t i;
774 const char *P = (const char *)Load.Ptr;
775 for (i = D.name; i < D.cmdsize; i++)
776 if (P[i] == '\0')
777 break;
778 if (i >= D.cmdsize)
779 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
780 CmdName + " dyld name extends past the end of the "
781 "load command");
782 return Error::success();
783}
784
Lang Hames697e7cd2016-12-04 01:56:10 +0000785static Error checkVersCommand(const MachOObjectFile &Obj,
Kevin Enderby32359db2016-09-28 21:20:45 +0000786 const MachOObjectFile::LoadCommandInfo &Load,
787 uint32_t LoadCommandIndex,
788 const char **LoadCmd, const char *CmdName) {
789 if (Load.C.cmdsize != sizeof(MachO::version_min_command))
790 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
791 CmdName + " has incorrect cmdsize");
792 if (*LoadCmd != nullptr)
793 return malformedError("more than one LC_VERSION_MIN_MACOSX, "
794 "LC_VERSION_MIN_IPHONEOS, LC_VERSION_MIN_TVOS or "
795 "LC_VERSION_MIN_WATCHOS command");
796 *LoadCmd = Load.Ptr;
797 return Error::success();
798}
799
Kevin Enderbya4579c42017-01-19 17:36:31 +0000800static Error checkNoteCommand(const MachOObjectFile &Obj,
801 const MachOObjectFile::LoadCommandInfo &Load,
802 uint32_t LoadCommandIndex,
803 std::list<MachOElement> &Elements) {
804 if (Load.C.cmdsize != sizeof(MachO::note_command))
805 return malformedError("load command " + Twine(LoadCommandIndex) +
806 " LC_NOTE has incorrect cmdsize");
807 MachO::note_command Nt = getStruct<MachO::note_command>(Obj, Load.Ptr);
808 uint64_t FileSize = Obj.getData().size();
809 if (Nt.offset > FileSize)
810 return malformedError("offset field of LC_NOTE command " +
811 Twine(LoadCommandIndex) + " extends "
812 "past the end of the file");
813 uint64_t BigSize = Nt.offset;
814 BigSize += Nt.size;
815 if (BigSize > FileSize)
816 return malformedError("size field plus offset field of LC_NOTE command " +
817 Twine(LoadCommandIndex) + " extends past the end of "
818 "the file");
819 if (Error Err = checkOverlappingElement(Elements, Nt.offset, Nt.size,
820 "LC_NOTE data"))
821 return Err;
822 return Error::success();
823}
824
Steven Wu5b54a422017-01-23 20:07:55 +0000825static Error
826parseBuildVersionCommand(const MachOObjectFile &Obj,
827 const MachOObjectFile::LoadCommandInfo &Load,
828 SmallVectorImpl<const char*> &BuildTools,
829 uint32_t LoadCommandIndex) {
830 MachO::build_version_command BVC =
831 getStruct<MachO::build_version_command>(Obj, Load.Ptr);
832 if (Load.C.cmdsize !=
833 sizeof(MachO::build_version_command) +
834 BVC.ntools * sizeof(MachO::build_tool_version))
835 return malformedError("load command " + Twine(LoadCommandIndex) +
836 " LC_BUILD_VERSION_COMMAND has incorrect cmdsize");
837
838 auto Start = Load.Ptr + sizeof(MachO::build_version_command);
839 BuildTools.resize(BVC.ntools);
840 for (unsigned i = 0; i < BVC.ntools; ++i)
841 BuildTools[i] = Start + i * sizeof(MachO::build_tool_version);
842
843 return Error::success();
844}
845
Lang Hames697e7cd2016-12-04 01:56:10 +0000846static Error checkRpathCommand(const MachOObjectFile &Obj,
Kevin Enderby76966bf2016-09-28 23:16:01 +0000847 const MachOObjectFile::LoadCommandInfo &Load,
848 uint32_t LoadCommandIndex) {
849 if (Load.C.cmdsize < sizeof(MachO::rpath_command))
850 return malformedError("load command " + Twine(LoadCommandIndex) +
851 " LC_RPATH cmdsize too small");
852 MachO::rpath_command R = getStruct<MachO::rpath_command>(Obj, Load.Ptr);
853 if (R.path < sizeof(MachO::rpath_command))
854 return malformedError("load command " + Twine(LoadCommandIndex) +
855 " LC_RPATH path.offset field too small, not past "
856 "the end of the rpath_command struct");
857 if (R.path >= R.cmdsize)
858 return malformedError("load command " + Twine(LoadCommandIndex) +
859 " LC_RPATH path.offset field extends past the end "
860 "of the load command");
861 // Make sure there is a null between the starting offset of the path and
862 // the end of the load command.
863 uint32_t i;
864 const char *P = (const char *)Load.Ptr;
865 for (i = R.path; i < R.cmdsize; i++)
866 if (P[i] == '\0')
867 break;
868 if (i >= R.cmdsize)
869 return malformedError("load command " + Twine(LoadCommandIndex) +
870 " LC_RPATH library name extends past the end of the "
871 "load command");
872 return Error::success();
873}
874
Lang Hames697e7cd2016-12-04 01:56:10 +0000875static Error checkEncryptCommand(const MachOObjectFile &Obj,
Kevin Enderbyf993d6e2016-10-04 20:37:43 +0000876 const MachOObjectFile::LoadCommandInfo &Load,
877 uint32_t LoadCommandIndex,
878 uint64_t cryptoff, uint64_t cryptsize,
879 const char **LoadCmd, const char *CmdName) {
880 if (*LoadCmd != nullptr)
881 return malformedError("more than one LC_ENCRYPTION_INFO and or "
882 "LC_ENCRYPTION_INFO_64 command");
Lang Hames697e7cd2016-12-04 01:56:10 +0000883 uint64_t FileSize = Obj.getData().size();
Kevin Enderbyf993d6e2016-10-04 20:37:43 +0000884 if (cryptoff > FileSize)
885 return malformedError("cryptoff field of " + Twine(CmdName) +
886 " command " + Twine(LoadCommandIndex) + " extends "
887 "past the end of the file");
888 uint64_t BigSize = cryptoff;
889 BigSize += cryptsize;
890 if (BigSize > FileSize)
891 return malformedError("cryptoff field plus cryptsize field of " +
892 Twine(CmdName) + " command " +
893 Twine(LoadCommandIndex) + " extends past the end of "
894 "the file");
895 *LoadCmd = Load.Ptr;
896 return Error::success();
897}
898
Lang Hames697e7cd2016-12-04 01:56:10 +0000899static Error checkLinkerOptCommand(const MachOObjectFile &Obj,
Kevin Enderby68fffa82016-10-11 21:04:39 +0000900 const MachOObjectFile::LoadCommandInfo &Load,
901 uint32_t LoadCommandIndex) {
902 if (Load.C.cmdsize < sizeof(MachO::linker_option_command))
903 return malformedError("load command " + Twine(LoadCommandIndex) +
904 " LC_LINKER_OPTION cmdsize too small");
905 MachO::linker_option_command L =
906 getStruct<MachO::linker_option_command>(Obj, Load.Ptr);
907 // Make sure the count of strings is correct.
908 const char *string = (const char *)Load.Ptr +
909 sizeof(struct MachO::linker_option_command);
910 uint32_t left = L.cmdsize - sizeof(struct MachO::linker_option_command);
911 uint32_t i = 0;
912 while (left > 0) {
913 while (*string == '\0' && left > 0) {
914 string++;
915 left--;
916 }
917 if (left > 0) {
918 i++;
919 uint32_t NullPos = StringRef(string, left).find('\0');
920 uint32_t len = std::min(NullPos, left) + 1;
921 string += len;
922 left -= len;
923 }
924 }
925 if (L.count != i)
926 return malformedError("load command " + Twine(LoadCommandIndex) +
927 " LC_LINKER_OPTION string count " + Twine(L.count) +
928 " does not match number of strings");
929 return Error::success();
930}
931
Lang Hames697e7cd2016-12-04 01:56:10 +0000932static Error checkSubCommand(const MachOObjectFile &Obj,
Kevin Enderby2490de02016-10-17 22:09:25 +0000933 const MachOObjectFile::LoadCommandInfo &Load,
934 uint32_t LoadCommandIndex, const char *CmdName,
935 size_t SizeOfCmd, const char *CmdStructName,
936 uint32_t PathOffset, const char *PathFieldName) {
937 if (PathOffset < SizeOfCmd)
938 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
939 CmdName + " " + PathFieldName + ".offset field too "
940 "small, not past the end of the " + CmdStructName);
941 if (PathOffset >= Load.C.cmdsize)
942 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
943 CmdName + " " + PathFieldName + ".offset field "
944 "extends past the end of the load command");
945 // Make sure there is a null between the starting offset of the path and
946 // the end of the load command.
947 uint32_t i;
948 const char *P = (const char *)Load.Ptr;
949 for (i = PathOffset; i < Load.C.cmdsize; i++)
950 if (P[i] == '\0')
951 break;
952 if (i >= Load.C.cmdsize)
953 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
954 CmdName + " " + PathFieldName + " name extends past "
955 "the end of the load command");
956 return Error::success();
957}
958
Lang Hames697e7cd2016-12-04 01:56:10 +0000959static Error checkThreadCommand(const MachOObjectFile &Obj,
Kevin Enderby210030b2016-10-19 23:44:34 +0000960 const MachOObjectFile::LoadCommandInfo &Load,
961 uint32_t LoadCommandIndex,
962 const char *CmdName) {
963 if (Load.C.cmdsize < sizeof(MachO::thread_command))
964 return malformedError("load command " + Twine(LoadCommandIndex) +
965 CmdName + " cmdsize too small");
966 MachO::thread_command T =
967 getStruct<MachO::thread_command>(Obj, Load.Ptr);
968 const char *state = Load.Ptr + sizeof(MachO::thread_command);
969 const char *end = Load.Ptr + T.cmdsize;
970 uint32_t nflavor = 0;
971 uint32_t cputype = getCPUType(Obj);
972 while (state < end) {
973 if(state + sizeof(uint32_t) > end)
974 return malformedError("load command " + Twine(LoadCommandIndex) +
975 "flavor in " + CmdName + " extends past end of "
976 "command");
977 uint32_t flavor;
978 memcpy(&flavor, state, sizeof(uint32_t));
Lang Hames697e7cd2016-12-04 01:56:10 +0000979 if (Obj.isLittleEndian() != sys::IsLittleEndianHost)
Kevin Enderby210030b2016-10-19 23:44:34 +0000980 sys::swapByteOrder(flavor);
981 state += sizeof(uint32_t);
982
983 if(state + sizeof(uint32_t) > end)
984 return malformedError("load command " + Twine(LoadCommandIndex) +
985 " count in " + CmdName + " extends past end of "
986 "command");
987 uint32_t count;
988 memcpy(&count, state, sizeof(uint32_t));
Lang Hames697e7cd2016-12-04 01:56:10 +0000989 if (Obj.isLittleEndian() != sys::IsLittleEndianHost)
Kevin Enderby210030b2016-10-19 23:44:34 +0000990 sys::swapByteOrder(count);
991 state += sizeof(uint32_t);
992
Kevin Enderbyc3a035d2017-01-23 21:13:29 +0000993 if (cputype == MachO::CPU_TYPE_I386) {
994 if (flavor == MachO::x86_THREAD_STATE32) {
995 if (count != MachO::x86_THREAD_STATE32_COUNT)
996 return malformedError("load command " + Twine(LoadCommandIndex) +
997 " count not x86_THREAD_STATE32_COUNT for "
998 "flavor number " + Twine(nflavor) + " which is "
999 "a x86_THREAD_STATE32 flavor in " + CmdName +
1000 " command");
1001 if (state + sizeof(MachO::x86_thread_state32_t) > end)
1002 return malformedError("load command " + Twine(LoadCommandIndex) +
1003 " x86_THREAD_STATE32 extends past end of "
1004 "command in " + CmdName + " command");
1005 state += sizeof(MachO::x86_thread_state32_t);
1006 } else {
1007 return malformedError("load command " + Twine(LoadCommandIndex) +
1008 " unknown flavor (" + Twine(flavor) + ") for "
1009 "flavor number " + Twine(nflavor) + " in " +
1010 CmdName + " command");
1011 }
1012 } else if (cputype == MachO::CPU_TYPE_X86_64) {
Kevin Enderby210030b2016-10-19 23:44:34 +00001013 if (flavor == MachO::x86_THREAD_STATE64) {
1014 if (count != MachO::x86_THREAD_STATE64_COUNT)
1015 return malformedError("load command " + Twine(LoadCommandIndex) +
1016 " count not x86_THREAD_STATE64_COUNT for "
1017 "flavor number " + Twine(nflavor) + " which is "
1018 "a x86_THREAD_STATE64 flavor in " + CmdName +
1019 " command");
1020 if (state + sizeof(MachO::x86_thread_state64_t) > end)
1021 return malformedError("load command " + Twine(LoadCommandIndex) +
1022 " x86_THREAD_STATE64 extends past end of "
1023 "command in " + CmdName + " command");
1024 state += sizeof(MachO::x86_thread_state64_t);
1025 } else {
1026 return malformedError("load command " + Twine(LoadCommandIndex) +
1027 " unknown flavor (" + Twine(flavor) + ") for "
1028 "flavor number " + Twine(nflavor) + " in " +
1029 CmdName + " command");
1030 }
1031 } else if (cputype == MachO::CPU_TYPE_ARM) {
1032 if (flavor == MachO::ARM_THREAD_STATE) {
1033 if (count != MachO::ARM_THREAD_STATE_COUNT)
1034 return malformedError("load command " + Twine(LoadCommandIndex) +
1035 " count not ARM_THREAD_STATE_COUNT for "
1036 "flavor number " + Twine(nflavor) + " which is "
1037 "a ARM_THREAD_STATE flavor in " + CmdName +
1038 " command");
1039 if (state + sizeof(MachO::arm_thread_state32_t) > end)
1040 return malformedError("load command " + Twine(LoadCommandIndex) +
1041 " ARM_THREAD_STATE extends past end of "
1042 "command in " + CmdName + " command");
1043 state += sizeof(MachO::arm_thread_state32_t);
1044 } else {
1045 return malformedError("load command " + Twine(LoadCommandIndex) +
1046 " unknown flavor (" + Twine(flavor) + ") for "
1047 "flavor number " + Twine(nflavor) + " in " +
1048 CmdName + " command");
1049 }
Kevin Enderby7747cb52016-11-03 20:51:28 +00001050 } else if (cputype == MachO::CPU_TYPE_ARM64) {
1051 if (flavor == MachO::ARM_THREAD_STATE64) {
1052 if (count != MachO::ARM_THREAD_STATE64_COUNT)
1053 return malformedError("load command " + Twine(LoadCommandIndex) +
1054 " count not ARM_THREAD_STATE64_COUNT for "
1055 "flavor number " + Twine(nflavor) + " which is "
1056 "a ARM_THREAD_STATE64 flavor in " + CmdName +
1057 " command");
1058 if (state + sizeof(MachO::arm_thread_state64_t) > end)
1059 return malformedError("load command " + Twine(LoadCommandIndex) +
1060 " ARM_THREAD_STATE64 extends past end of "
1061 "command in " + CmdName + " command");
1062 state += sizeof(MachO::arm_thread_state64_t);
1063 } else {
1064 return malformedError("load command " + Twine(LoadCommandIndex) +
1065 " unknown flavor (" + Twine(flavor) + ") for "
1066 "flavor number " + Twine(nflavor) + " in " +
1067 CmdName + " command");
1068 }
Kevin Enderby210030b2016-10-19 23:44:34 +00001069 } else if (cputype == MachO::CPU_TYPE_POWERPC) {
1070 if (flavor == MachO::PPC_THREAD_STATE) {
1071 if (count != MachO::PPC_THREAD_STATE_COUNT)
1072 return malformedError("load command " + Twine(LoadCommandIndex) +
1073 " count not PPC_THREAD_STATE_COUNT for "
1074 "flavor number " + Twine(nflavor) + " which is "
1075 "a PPC_THREAD_STATE flavor in " + CmdName +
1076 " command");
1077 if (state + sizeof(MachO::ppc_thread_state32_t) > end)
1078 return malformedError("load command " + Twine(LoadCommandIndex) +
1079 " PPC_THREAD_STATE extends past end of "
1080 "command in " + CmdName + " command");
1081 state += sizeof(MachO::ppc_thread_state32_t);
1082 } else {
1083 return malformedError("load command " + Twine(LoadCommandIndex) +
1084 " unknown flavor (" + Twine(flavor) + ") for "
1085 "flavor number " + Twine(nflavor) + " in " +
1086 CmdName + " command");
1087 }
1088 } else {
1089 return malformedError("unknown cputype (" + Twine(cputype) + ") load "
1090 "command " + Twine(LoadCommandIndex) + " for " +
1091 CmdName + " command can't be checked");
1092 }
1093 nflavor++;
1094 }
1095 return Error::success();
1096}
1097
Lang Hames697e7cd2016-12-04 01:56:10 +00001098static Error checkTwoLevelHintsCommand(const MachOObjectFile &Obj,
Kevin Enderbyc8bb4222016-10-20 20:10:30 +00001099 const MachOObjectFile::LoadCommandInfo
1100 &Load,
1101 uint32_t LoadCommandIndex,
Kevin Enderbyfbebe162016-11-02 21:08:39 +00001102 const char **LoadCmd,
1103 std::list<MachOElement> &Elements) {
Kevin Enderbyc8bb4222016-10-20 20:10:30 +00001104 if (Load.C.cmdsize != sizeof(MachO::twolevel_hints_command))
1105 return malformedError("load command " + Twine(LoadCommandIndex) +
1106 " LC_TWOLEVEL_HINTS has incorrect cmdsize");
1107 if (*LoadCmd != nullptr)
1108 return malformedError("more than one LC_TWOLEVEL_HINTS command");
1109 MachO::twolevel_hints_command Hints =
1110 getStruct<MachO::twolevel_hints_command>(Obj, Load.Ptr);
Lang Hames697e7cd2016-12-04 01:56:10 +00001111 uint64_t FileSize = Obj.getData().size();
Kevin Enderbyc8bb4222016-10-20 20:10:30 +00001112 if (Hints.offset > FileSize)
1113 return malformedError("offset field of LC_TWOLEVEL_HINTS command " +
1114 Twine(LoadCommandIndex) + " extends past the end of "
1115 "the file");
1116 uint64_t BigSize = Hints.nhints;
1117 BigSize *= Hints.nhints * sizeof(MachO::twolevel_hint);
1118 BigSize += Hints.offset;
1119 if (BigSize > FileSize)
1120 return malformedError("offset field plus nhints times sizeof(struct "
1121 "twolevel_hint) field of LC_TWOLEVEL_HINTS command " +
1122 Twine(LoadCommandIndex) + " extends past the end of "
1123 "the file");
Kevin Enderbyfbebe162016-11-02 21:08:39 +00001124 if (Error Err = checkOverlappingElement(Elements, Hints.offset, Hints.nhints *
1125 sizeof(MachO::twolevel_hint),
1126 "two level hints"))
1127 return Err;
Kevin Enderbyc8bb4222016-10-20 20:10:30 +00001128 *LoadCmd = Load.Ptr;
1129 return Error::success();
1130}
1131
Kevin Enderbybc5c29a2016-10-27 20:59:10 +00001132// Returns true if the libObject code does not support the load command and its
1133// contents. The cmd value it is treated as an unknown load command but with
1134// an error message that says the cmd value is obsolete.
1135static bool isLoadCommandObsolete(uint32_t cmd) {
1136 if (cmd == MachO::LC_SYMSEG ||
1137 cmd == MachO::LC_LOADFVMLIB ||
1138 cmd == MachO::LC_IDFVMLIB ||
1139 cmd == MachO::LC_IDENT ||
1140 cmd == MachO::LC_FVMFILE ||
1141 cmd == MachO::LC_PREPAGE ||
1142 cmd == MachO::LC_PREBOUND_DYLIB ||
1143 cmd == MachO::LC_TWOLEVEL_HINTS ||
1144 cmd == MachO::LC_PREBIND_CKSUM)
1145 return true;
1146 return false;
1147}
1148
Lang Hames82627642016-03-25 21:59:14 +00001149Expected<std::unique_ptr<MachOObjectFile>>
1150MachOObjectFile::create(MemoryBufferRef Object, bool IsLittleEndian,
Kevin Enderby79d6c632016-10-24 21:15:11 +00001151 bool Is64Bits, uint32_t UniversalCputype,
1152 uint32_t UniversalIndex) {
Mehdi Amini41af4302016-11-11 04:28:40 +00001153 Error Err = Error::success();
Lang Hames82627642016-03-25 21:59:14 +00001154 std::unique_ptr<MachOObjectFile> Obj(
1155 new MachOObjectFile(std::move(Object), IsLittleEndian,
Kevin Enderby79d6c632016-10-24 21:15:11 +00001156 Is64Bits, Err, UniversalCputype,
1157 UniversalIndex));
Lang Hames82627642016-03-25 21:59:14 +00001158 if (Err)
1159 return std::move(Err);
1160 return std::move(Obj);
1161}
1162
Rafael Espindola48af1c22014-08-19 18:44:46 +00001163MachOObjectFile::MachOObjectFile(MemoryBufferRef Object, bool IsLittleEndian,
Kevin Enderby79d6c632016-10-24 21:15:11 +00001164 bool Is64bits, Error &Err,
1165 uint32_t UniversalCputype,
1166 uint32_t UniversalIndex)
Eugene Zelenko9f5094d2017-04-21 22:03:05 +00001167 : ObjectFile(getMachOType(IsLittleEndian, Is64bits), Object) {
Lang Hames5e51a2e2016-07-22 16:11:25 +00001168 ErrorAsOutParameter ErrAsOutParam(&Err);
Kevin Enderbyc614d282016-08-12 20:10:25 +00001169 uint64_t SizeOfHeaders;
Kevin Enderby79d6c632016-10-24 21:15:11 +00001170 uint32_t cputype;
Kevin Enderby87025742016-04-13 21:17:58 +00001171 if (is64Bit()) {
Lang Hames697e7cd2016-12-04 01:56:10 +00001172 parseHeader(*this, Header64, Err);
Kevin Enderbyc614d282016-08-12 20:10:25 +00001173 SizeOfHeaders = sizeof(MachO::mach_header_64);
Kevin Enderby79d6c632016-10-24 21:15:11 +00001174 cputype = Header64.cputype;
Kevin Enderby87025742016-04-13 21:17:58 +00001175 } else {
Lang Hames697e7cd2016-12-04 01:56:10 +00001176 parseHeader(*this, Header, Err);
Kevin Enderbyc614d282016-08-12 20:10:25 +00001177 SizeOfHeaders = sizeof(MachO::mach_header);
Kevin Enderby79d6c632016-10-24 21:15:11 +00001178 cputype = Header.cputype;
Kevin Enderby87025742016-04-13 21:17:58 +00001179 }
Lang Hames9e964f32016-03-25 17:25:34 +00001180 if (Err)
Alexey Samsonov9f336632015-06-04 19:45:22 +00001181 return;
Kevin Enderbyc614d282016-08-12 20:10:25 +00001182 SizeOfHeaders += getHeader().sizeofcmds;
1183 if (getData().data() + SizeOfHeaders > getData().end()) {
Kevin Enderbyd4e075b2016-05-06 20:16:28 +00001184 Err = malformedError("load commands extend past the end of the file");
Kevin Enderby87025742016-04-13 21:17:58 +00001185 return;
1186 }
Kevin Enderby79d6c632016-10-24 21:15:11 +00001187 if (UniversalCputype != 0 && cputype != UniversalCputype) {
1188 Err = malformedError("universal header architecture: " +
1189 Twine(UniversalIndex) + "'s cputype does not match "
1190 "object file's mach header");
1191 return;
1192 }
Kevin Enderbyd5039402016-10-31 20:29:48 +00001193 std::list<MachOElement> Elements;
1194 Elements.push_back({0, SizeOfHeaders, "Mach-O headers"});
Alexey Samsonov13415ed2015-06-04 19:22:03 +00001195
1196 uint32_t LoadCommandCount = getHeader().ncmds;
Lang Hames9e964f32016-03-25 17:25:34 +00001197 LoadCommandInfo Load;
Kevin Enderbyfc0929a2016-09-20 20:14:14 +00001198 if (LoadCommandCount != 0) {
Lang Hames697e7cd2016-12-04 01:56:10 +00001199 if (auto LoadOrErr = getFirstLoadCommandInfo(*this))
Kevin Enderbyfc0929a2016-09-20 20:14:14 +00001200 Load = *LoadOrErr;
1201 else {
1202 Err = LoadOrErr.takeError();
1203 return;
1204 }
Alexey Samsonovde5a94a2015-06-04 19:57:46 +00001205 }
Lang Hames9e964f32016-03-25 17:25:34 +00001206
Kevin Enderbyfc0929a2016-09-20 20:14:14 +00001207 const char *DyldIdLoadCmd = nullptr;
Kevin Enderby90986e62016-09-26 21:11:03 +00001208 const char *FuncStartsLoadCmd = nullptr;
1209 const char *SplitInfoLoadCmd = nullptr;
1210 const char *CodeSignDrsLoadCmd = nullptr;
Kevin Enderby89baf992016-10-18 20:24:12 +00001211 const char *CodeSignLoadCmd = nullptr;
Kevin Enderby32359db2016-09-28 21:20:45 +00001212 const char *VersLoadCmd = nullptr;
Kevin Enderby245be3e2016-09-29 17:45:23 +00001213 const char *SourceLoadCmd = nullptr;
Kevin Enderby4f229d82016-09-29 21:07:29 +00001214 const char *EntryPointLoadCmd = nullptr;
Kevin Enderbyf993d6e2016-10-04 20:37:43 +00001215 const char *EncryptLoadCmd = nullptr;
Kevin Enderby6f695822016-10-18 17:54:17 +00001216 const char *RoutinesLoadCmd = nullptr;
Kevin Enderby210030b2016-10-19 23:44:34 +00001217 const char *UnixThreadLoadCmd = nullptr;
Kevin Enderbyc8bb4222016-10-20 20:10:30 +00001218 const char *TwoLevelHintsLoadCmd = nullptr;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00001219 for (unsigned I = 0; I < LoadCommandCount; ++I) {
Kevin Enderby1851a822016-07-07 22:11:42 +00001220 if (is64Bit()) {
1221 if (Load.C.cmdsize % 8 != 0) {
1222 // We have a hack here to allow 64-bit Mach-O core files to have
1223 // LC_THREAD commands that are only a multiple of 4 and not 8 to be
1224 // allowed since the macOS kernel produces them.
1225 if (getHeader().filetype != MachO::MH_CORE ||
1226 Load.C.cmd != MachO::LC_THREAD || Load.C.cmdsize % 4) {
1227 Err = malformedError("load command " + Twine(I) + " cmdsize not a "
1228 "multiple of 8");
1229 return;
1230 }
1231 }
1232 } else {
1233 if (Load.C.cmdsize % 4 != 0) {
1234 Err = malformedError("load command " + Twine(I) + " cmdsize not a "
1235 "multiple of 4");
1236 return;
1237 }
1238 }
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00001239 LoadCommands.push_back(Load);
Charles Davis8bdfafd2013-09-01 04:28:48 +00001240 if (Load.C.cmd == MachO::LC_SYMTAB) {
Lang Hames697e7cd2016-12-04 01:56:10 +00001241 if ((Err = checkSymtabCommand(*this, Load, I, &SymtabLoadCmd, Elements)))
David Majnemer73cc6ff2014-11-13 19:48:56 +00001242 return;
Charles Davis8bdfafd2013-09-01 04:28:48 +00001243 } else if (Load.C.cmd == MachO::LC_DYSYMTAB) {
Lang Hames697e7cd2016-12-04 01:56:10 +00001244 if ((Err = checkDysymtabCommand(*this, Load, I, &DysymtabLoadCmd,
Kevin Enderbyfbebe162016-11-02 21:08:39 +00001245 Elements)))
David Majnemer73cc6ff2014-11-13 19:48:56 +00001246 return;
Charles Davis8bdfafd2013-09-01 04:28:48 +00001247 } else if (Load.C.cmd == MachO::LC_DATA_IN_CODE) {
Lang Hames697e7cd2016-12-04 01:56:10 +00001248 if ((Err = checkLinkeditDataCommand(*this, Load, I, &DataInCodeLoadCmd,
Kevin Enderbyfbebe162016-11-02 21:08:39 +00001249 "LC_DATA_IN_CODE", Elements,
1250 "data in code info")))
David Majnemer73cc6ff2014-11-13 19:48:56 +00001251 return;
Kevin Enderby9a509442015-01-27 21:28:24 +00001252 } else if (Load.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
Lang Hames697e7cd2016-12-04 01:56:10 +00001253 if ((Err = checkLinkeditDataCommand(*this, Load, I, &LinkOptHintsLoadCmd,
Kevin Enderbyfbebe162016-11-02 21:08:39 +00001254 "LC_LINKER_OPTIMIZATION_HINT",
1255 Elements, "linker optimization "
1256 "hints")))
Kevin Enderby9a509442015-01-27 21:28:24 +00001257 return;
Kevin Enderby90986e62016-09-26 21:11:03 +00001258 } else if (Load.C.cmd == MachO::LC_FUNCTION_STARTS) {
Lang Hames697e7cd2016-12-04 01:56:10 +00001259 if ((Err = checkLinkeditDataCommand(*this, Load, I, &FuncStartsLoadCmd,
Kevin Enderbyfbebe162016-11-02 21:08:39 +00001260 "LC_FUNCTION_STARTS", Elements,
1261 "function starts data")))
Kevin Enderby90986e62016-09-26 21:11:03 +00001262 return;
1263 } else if (Load.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO) {
Lang Hames697e7cd2016-12-04 01:56:10 +00001264 if ((Err = checkLinkeditDataCommand(*this, Load, I, &SplitInfoLoadCmd,
Kevin Enderbyfbebe162016-11-02 21:08:39 +00001265 "LC_SEGMENT_SPLIT_INFO", Elements,
1266 "split info data")))
Kevin Enderby90986e62016-09-26 21:11:03 +00001267 return;
1268 } else if (Load.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS) {
Lang Hames697e7cd2016-12-04 01:56:10 +00001269 if ((Err = checkLinkeditDataCommand(*this, Load, I, &CodeSignDrsLoadCmd,
Kevin Enderbyfbebe162016-11-02 21:08:39 +00001270 "LC_DYLIB_CODE_SIGN_DRS", Elements,
1271 "code signing RDs data")))
Kevin Enderby90986e62016-09-26 21:11:03 +00001272 return;
Kevin Enderby89baf992016-10-18 20:24:12 +00001273 } else if (Load.C.cmd == MachO::LC_CODE_SIGNATURE) {
Lang Hames697e7cd2016-12-04 01:56:10 +00001274 if ((Err = checkLinkeditDataCommand(*this, Load, I, &CodeSignLoadCmd,
Kevin Enderbyfbebe162016-11-02 21:08:39 +00001275 "LC_CODE_SIGNATURE", Elements,
1276 "code signature data")))
Kevin Enderby89baf992016-10-18 20:24:12 +00001277 return;
Kevin Enderbyf76b56c2016-09-13 21:42:28 +00001278 } else if (Load.C.cmd == MachO::LC_DYLD_INFO) {
Lang Hames697e7cd2016-12-04 01:56:10 +00001279 if ((Err = checkDyldInfoCommand(*this, Load, I, &DyldInfoLoadCmd,
Kevin Enderbyfbebe162016-11-02 21:08:39 +00001280 "LC_DYLD_INFO", Elements)))
David Majnemer73cc6ff2014-11-13 19:48:56 +00001281 return;
Kevin Enderbyf76b56c2016-09-13 21:42:28 +00001282 } else if (Load.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
Lang Hames697e7cd2016-12-04 01:56:10 +00001283 if ((Err = checkDyldInfoCommand(*this, Load, I, &DyldInfoLoadCmd,
Kevin Enderbyfbebe162016-11-02 21:08:39 +00001284 "LC_DYLD_INFO_ONLY", Elements)))
Kevin Enderbyf76b56c2016-09-13 21:42:28 +00001285 return;
Alexander Potapenko6909b5b2014-10-15 23:35:45 +00001286 } else if (Load.C.cmd == MachO::LC_UUID) {
Kevin Enderbye71e13c2016-09-21 20:03:09 +00001287 if (Load.C.cmdsize != sizeof(MachO::uuid_command)) {
1288 Err = malformedError("LC_UUID command " + Twine(I) + " has incorrect "
1289 "cmdsize");
1290 return;
1291 }
David Majnemer73cc6ff2014-11-13 19:48:56 +00001292 if (UuidLoadCmd) {
Kevin Enderbye71e13c2016-09-21 20:03:09 +00001293 Err = malformedError("more than one LC_UUID command");
David Majnemer73cc6ff2014-11-13 19:48:56 +00001294 return;
1295 }
Alexander Potapenko6909b5b2014-10-15 23:35:45 +00001296 UuidLoadCmd = Load.Ptr;
Alexey Samsonove1a76ab2015-06-04 22:08:37 +00001297 } else if (Load.C.cmd == MachO::LC_SEGMENT_64) {
Kevin Enderbyc614d282016-08-12 20:10:25 +00001298 if ((Err = parseSegmentLoadCommand<MachO::segment_command_64,
1299 MachO::section_64>(
Lang Hames697e7cd2016-12-04 01:56:10 +00001300 *this, Load, Sections, HasPageZeroSegment, I,
Kevin Enderbyfbebe162016-11-02 21:08:39 +00001301 "LC_SEGMENT_64", SizeOfHeaders, Elements)))
Alexey Samsonov074da9b2015-06-04 20:08:52 +00001302 return;
Alexey Samsonove1a76ab2015-06-04 22:08:37 +00001303 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
Kevin Enderbyc614d282016-08-12 20:10:25 +00001304 if ((Err = parseSegmentLoadCommand<MachO::segment_command,
1305 MachO::section>(
Lang Hames697e7cd2016-12-04 01:56:10 +00001306 *this, Load, Sections, HasPageZeroSegment, I,
Kevin Enderbyfbebe162016-11-02 21:08:39 +00001307 "LC_SEGMENT", SizeOfHeaders, Elements)))
Alexey Samsonov074da9b2015-06-04 20:08:52 +00001308 return;
Kevin Enderbyfc0929a2016-09-20 20:14:14 +00001309 } else if (Load.C.cmd == MachO::LC_ID_DYLIB) {
Lang Hames697e7cd2016-12-04 01:56:10 +00001310 if ((Err = checkDylibIdCommand(*this, Load, I, &DyldIdLoadCmd)))
Kevin Enderbyfc0929a2016-09-20 20:14:14 +00001311 return;
1312 } else if (Load.C.cmd == MachO::LC_LOAD_DYLIB) {
Lang Hames697e7cd2016-12-04 01:56:10 +00001313 if ((Err = checkDylibCommand(*this, Load, I, "LC_LOAD_DYLIB")))
Kevin Enderbyfc0929a2016-09-20 20:14:14 +00001314 return;
1315 Libraries.push_back(Load.Ptr);
1316 } else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB) {
Lang Hames697e7cd2016-12-04 01:56:10 +00001317 if ((Err = checkDylibCommand(*this, Load, I, "LC_LOAD_WEAK_DYLIB")))
Kevin Enderbyfc0929a2016-09-20 20:14:14 +00001318 return;
1319 Libraries.push_back(Load.Ptr);
1320 } else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB) {
Lang Hames697e7cd2016-12-04 01:56:10 +00001321 if ((Err = checkDylibCommand(*this, Load, I, "LC_LAZY_LOAD_DYLIB")))
Kevin Enderbyfc0929a2016-09-20 20:14:14 +00001322 return;
1323 Libraries.push_back(Load.Ptr);
1324 } else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB) {
Lang Hames697e7cd2016-12-04 01:56:10 +00001325 if ((Err = checkDylibCommand(*this, Load, I, "LC_REEXPORT_DYLIB")))
Kevin Enderbyfc0929a2016-09-20 20:14:14 +00001326 return;
1327 Libraries.push_back(Load.Ptr);
1328 } else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
Lang Hames697e7cd2016-12-04 01:56:10 +00001329 if ((Err = checkDylibCommand(*this, Load, I, "LC_LOAD_UPWARD_DYLIB")))
Kevin Enderbyfc0929a2016-09-20 20:14:14 +00001330 return;
Kevin Enderby980b2582014-06-05 21:21:57 +00001331 Libraries.push_back(Load.Ptr);
Kevin Enderby3e490ef2016-09-27 23:24:13 +00001332 } else if (Load.C.cmd == MachO::LC_ID_DYLINKER) {
Lang Hames697e7cd2016-12-04 01:56:10 +00001333 if ((Err = checkDyldCommand(*this, Load, I, "LC_ID_DYLINKER")))
Kevin Enderby3e490ef2016-09-27 23:24:13 +00001334 return;
1335 } else if (Load.C.cmd == MachO::LC_LOAD_DYLINKER) {
Lang Hames697e7cd2016-12-04 01:56:10 +00001336 if ((Err = checkDyldCommand(*this, Load, I, "LC_LOAD_DYLINKER")))
Kevin Enderby3e490ef2016-09-27 23:24:13 +00001337 return;
1338 } else if (Load.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
Lang Hames697e7cd2016-12-04 01:56:10 +00001339 if ((Err = checkDyldCommand(*this, Load, I, "LC_DYLD_ENVIRONMENT")))
Kevin Enderby3e490ef2016-09-27 23:24:13 +00001340 return;
Kevin Enderby32359db2016-09-28 21:20:45 +00001341 } else if (Load.C.cmd == MachO::LC_VERSION_MIN_MACOSX) {
Lang Hames697e7cd2016-12-04 01:56:10 +00001342 if ((Err = checkVersCommand(*this, Load, I, &VersLoadCmd,
Kevin Enderby32359db2016-09-28 21:20:45 +00001343 "LC_VERSION_MIN_MACOSX")))
1344 return;
1345 } else if (Load.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS) {
Lang Hames697e7cd2016-12-04 01:56:10 +00001346 if ((Err = checkVersCommand(*this, Load, I, &VersLoadCmd,
Kevin Enderby32359db2016-09-28 21:20:45 +00001347 "LC_VERSION_MIN_IPHONEOS")))
1348 return;
1349 } else if (Load.C.cmd == MachO::LC_VERSION_MIN_TVOS) {
Lang Hames697e7cd2016-12-04 01:56:10 +00001350 if ((Err = checkVersCommand(*this, Load, I, &VersLoadCmd,
Kevin Enderby32359db2016-09-28 21:20:45 +00001351 "LC_VERSION_MIN_TVOS")))
1352 return;
1353 } else if (Load.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
Lang Hames697e7cd2016-12-04 01:56:10 +00001354 if ((Err = checkVersCommand(*this, Load, I, &VersLoadCmd,
Kevin Enderby32359db2016-09-28 21:20:45 +00001355 "LC_VERSION_MIN_WATCHOS")))
1356 return;
Kevin Enderbya4579c42017-01-19 17:36:31 +00001357 } else if (Load.C.cmd == MachO::LC_NOTE) {
1358 if ((Err = checkNoteCommand(*this, Load, I, Elements)))
1359 return;
Steven Wu5b54a422017-01-23 20:07:55 +00001360 } else if (Load.C.cmd == MachO::LC_BUILD_VERSION) {
1361 if ((Err = parseBuildVersionCommand(*this, Load, BuildTools, I)))
1362 return;
Kevin Enderby76966bf2016-09-28 23:16:01 +00001363 } else if (Load.C.cmd == MachO::LC_RPATH) {
Lang Hames697e7cd2016-12-04 01:56:10 +00001364 if ((Err = checkRpathCommand(*this, Load, I)))
Kevin Enderby76966bf2016-09-28 23:16:01 +00001365 return;
Kevin Enderby245be3e2016-09-29 17:45:23 +00001366 } else if (Load.C.cmd == MachO::LC_SOURCE_VERSION) {
1367 if (Load.C.cmdsize != sizeof(MachO::source_version_command)) {
1368 Err = malformedError("LC_SOURCE_VERSION command " + Twine(I) +
1369 " has incorrect cmdsize");
1370 return;
1371 }
1372 if (SourceLoadCmd) {
1373 Err = malformedError("more than one LC_SOURCE_VERSION command");
1374 return;
1375 }
1376 SourceLoadCmd = Load.Ptr;
Kevin Enderby4f229d82016-09-29 21:07:29 +00001377 } else if (Load.C.cmd == MachO::LC_MAIN) {
1378 if (Load.C.cmdsize != sizeof(MachO::entry_point_command)) {
1379 Err = malformedError("LC_MAIN command " + Twine(I) +
1380 " has incorrect cmdsize");
1381 return;
1382 }
1383 if (EntryPointLoadCmd) {
1384 Err = malformedError("more than one LC_MAIN command");
1385 return;
1386 }
1387 EntryPointLoadCmd = Load.Ptr;
Kevin Enderbyf993d6e2016-10-04 20:37:43 +00001388 } else if (Load.C.cmd == MachO::LC_ENCRYPTION_INFO) {
1389 if (Load.C.cmdsize != sizeof(MachO::encryption_info_command)) {
1390 Err = malformedError("LC_ENCRYPTION_INFO command " + Twine(I) +
1391 " has incorrect cmdsize");
1392 return;
1393 }
1394 MachO::encryption_info_command E =
Lang Hames697e7cd2016-12-04 01:56:10 +00001395 getStruct<MachO::encryption_info_command>(*this, Load.Ptr);
1396 if ((Err = checkEncryptCommand(*this, Load, I, E.cryptoff, E.cryptsize,
Kevin Enderbyf993d6e2016-10-04 20:37:43 +00001397 &EncryptLoadCmd, "LC_ENCRYPTION_INFO")))
1398 return;
1399 } else if (Load.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
1400 if (Load.C.cmdsize != sizeof(MachO::encryption_info_command_64)) {
1401 Err = malformedError("LC_ENCRYPTION_INFO_64 command " + Twine(I) +
1402 " has incorrect cmdsize");
1403 return;
1404 }
1405 MachO::encryption_info_command_64 E =
Lang Hames697e7cd2016-12-04 01:56:10 +00001406 getStruct<MachO::encryption_info_command_64>(*this, Load.Ptr);
1407 if ((Err = checkEncryptCommand(*this, Load, I, E.cryptoff, E.cryptsize,
Kevin Enderbyf993d6e2016-10-04 20:37:43 +00001408 &EncryptLoadCmd, "LC_ENCRYPTION_INFO_64")))
1409 return;
Kevin Enderby68fffa82016-10-11 21:04:39 +00001410 } else if (Load.C.cmd == MachO::LC_LINKER_OPTION) {
Lang Hames697e7cd2016-12-04 01:56:10 +00001411 if ((Err = checkLinkerOptCommand(*this, Load, I)))
Kevin Enderby68fffa82016-10-11 21:04:39 +00001412 return;
Kevin Enderby2490de02016-10-17 22:09:25 +00001413 } else if (Load.C.cmd == MachO::LC_SUB_FRAMEWORK) {
1414 if (Load.C.cmdsize < sizeof(MachO::sub_framework_command)) {
1415 Err = malformedError("load command " + Twine(I) +
1416 " LC_SUB_FRAMEWORK cmdsize too small");
1417 return;
1418 }
1419 MachO::sub_framework_command S =
Lang Hames697e7cd2016-12-04 01:56:10 +00001420 getStruct<MachO::sub_framework_command>(*this, Load.Ptr);
1421 if ((Err = checkSubCommand(*this, Load, I, "LC_SUB_FRAMEWORK",
Kevin Enderby2490de02016-10-17 22:09:25 +00001422 sizeof(MachO::sub_framework_command),
1423 "sub_framework_command", S.umbrella,
1424 "umbrella")))
1425 return;
1426 } else if (Load.C.cmd == MachO::LC_SUB_UMBRELLA) {
1427 if (Load.C.cmdsize < sizeof(MachO::sub_umbrella_command)) {
1428 Err = malformedError("load command " + Twine(I) +
1429 " LC_SUB_UMBRELLA cmdsize too small");
1430 return;
1431 }
1432 MachO::sub_umbrella_command S =
Lang Hames697e7cd2016-12-04 01:56:10 +00001433 getStruct<MachO::sub_umbrella_command>(*this, Load.Ptr);
1434 if ((Err = checkSubCommand(*this, Load, I, "LC_SUB_UMBRELLA",
Kevin Enderby2490de02016-10-17 22:09:25 +00001435 sizeof(MachO::sub_umbrella_command),
1436 "sub_umbrella_command", S.sub_umbrella,
1437 "sub_umbrella")))
1438 return;
1439 } else if (Load.C.cmd == MachO::LC_SUB_LIBRARY) {
1440 if (Load.C.cmdsize < sizeof(MachO::sub_library_command)) {
1441 Err = malformedError("load command " + Twine(I) +
1442 " LC_SUB_LIBRARY cmdsize too small");
1443 return;
1444 }
1445 MachO::sub_library_command S =
Lang Hames697e7cd2016-12-04 01:56:10 +00001446 getStruct<MachO::sub_library_command>(*this, Load.Ptr);
1447 if ((Err = checkSubCommand(*this, Load, I, "LC_SUB_LIBRARY",
Kevin Enderby2490de02016-10-17 22:09:25 +00001448 sizeof(MachO::sub_library_command),
1449 "sub_library_command", S.sub_library,
1450 "sub_library")))
1451 return;
1452 } else if (Load.C.cmd == MachO::LC_SUB_CLIENT) {
1453 if (Load.C.cmdsize < sizeof(MachO::sub_client_command)) {
1454 Err = malformedError("load command " + Twine(I) +
1455 " LC_SUB_CLIENT cmdsize too small");
1456 return;
1457 }
1458 MachO::sub_client_command S =
Lang Hames697e7cd2016-12-04 01:56:10 +00001459 getStruct<MachO::sub_client_command>(*this, Load.Ptr);
1460 if ((Err = checkSubCommand(*this, Load, I, "LC_SUB_CLIENT",
Kevin Enderby2490de02016-10-17 22:09:25 +00001461 sizeof(MachO::sub_client_command),
1462 "sub_client_command", S.client, "client")))
1463 return;
Kevin Enderby6f695822016-10-18 17:54:17 +00001464 } else if (Load.C.cmd == MachO::LC_ROUTINES) {
1465 if (Load.C.cmdsize != sizeof(MachO::routines_command)) {
1466 Err = malformedError("LC_ROUTINES command " + Twine(I) +
1467 " has incorrect cmdsize");
1468 return;
1469 }
1470 if (RoutinesLoadCmd) {
1471 Err = malformedError("more than one LC_ROUTINES and or LC_ROUTINES_64 "
1472 "command");
1473 return;
1474 }
1475 RoutinesLoadCmd = Load.Ptr;
1476 } else if (Load.C.cmd == MachO::LC_ROUTINES_64) {
1477 if (Load.C.cmdsize != sizeof(MachO::routines_command_64)) {
1478 Err = malformedError("LC_ROUTINES_64 command " + Twine(I) +
1479 " has incorrect cmdsize");
1480 return;
1481 }
1482 if (RoutinesLoadCmd) {
1483 Err = malformedError("more than one LC_ROUTINES_64 and or LC_ROUTINES "
1484 "command");
1485 return;
1486 }
1487 RoutinesLoadCmd = Load.Ptr;
Kevin Enderby210030b2016-10-19 23:44:34 +00001488 } else if (Load.C.cmd == MachO::LC_UNIXTHREAD) {
Lang Hames697e7cd2016-12-04 01:56:10 +00001489 if ((Err = checkThreadCommand(*this, Load, I, "LC_UNIXTHREAD")))
Kevin Enderby210030b2016-10-19 23:44:34 +00001490 return;
1491 if (UnixThreadLoadCmd) {
1492 Err = malformedError("more than one LC_UNIXTHREAD command");
1493 return;
1494 }
1495 UnixThreadLoadCmd = Load.Ptr;
1496 } else if (Load.C.cmd == MachO::LC_THREAD) {
Lang Hames697e7cd2016-12-04 01:56:10 +00001497 if ((Err = checkThreadCommand(*this, Load, I, "LC_THREAD")))
Kevin Enderby210030b2016-10-19 23:44:34 +00001498 return;
Kevin Enderbybc5c29a2016-10-27 20:59:10 +00001499 // Note: LC_TWOLEVEL_HINTS is really obsolete and is not supported.
Kevin Enderbyc8bb4222016-10-20 20:10:30 +00001500 } else if (Load.C.cmd == MachO::LC_TWOLEVEL_HINTS) {
Lang Hames697e7cd2016-12-04 01:56:10 +00001501 if ((Err = checkTwoLevelHintsCommand(*this, Load, I,
Kevin Enderbyfbebe162016-11-02 21:08:39 +00001502 &TwoLevelHintsLoadCmd, Elements)))
Kevin Enderbyc8bb4222016-10-20 20:10:30 +00001503 return;
Kevin Enderbybc5c29a2016-10-27 20:59:10 +00001504 } else if (isLoadCommandObsolete(Load.C.cmd)) {
1505 Err = malformedError("load command " + Twine(I) + " for cmd value of: " +
1506 Twine(Load.C.cmd) + " is obsolete and not "
1507 "supported");
1508 return;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001509 }
Kevin Enderbybc5c29a2016-10-27 20:59:10 +00001510 // TODO: generate a error for unknown load commands by default. But still
1511 // need work out an approach to allow or not allow unknown values like this
1512 // as an option for some uses like lldb.
Alexey Samsonovde5a94a2015-06-04 19:57:46 +00001513 if (I < LoadCommandCount - 1) {
Lang Hames697e7cd2016-12-04 01:56:10 +00001514 if (auto LoadOrErr = getNextLoadCommandInfo(*this, I, Load))
Lang Hames9e964f32016-03-25 17:25:34 +00001515 Load = *LoadOrErr;
1516 else {
1517 Err = LoadOrErr.takeError();
Alexey Samsonovde5a94a2015-06-04 19:57:46 +00001518 return;
1519 }
Alexey Samsonovde5a94a2015-06-04 19:57:46 +00001520 }
Rafael Espindola56f976f2013-04-18 18:08:55 +00001521 }
Kevin Enderby1829c682016-01-22 22:49:55 +00001522 if (!SymtabLoadCmd) {
1523 if (DysymtabLoadCmd) {
Kevin Enderbyd4e075b2016-05-06 20:16:28 +00001524 Err = malformedError("contains LC_DYSYMTAB load command without a "
Kevin Enderby89134962016-05-05 23:41:05 +00001525 "LC_SYMTAB load command");
Kevin Enderby1829c682016-01-22 22:49:55 +00001526 return;
1527 }
1528 } else if (DysymtabLoadCmd) {
1529 MachO::symtab_command Symtab =
Lang Hames697e7cd2016-12-04 01:56:10 +00001530 getStruct<MachO::symtab_command>(*this, SymtabLoadCmd);
Kevin Enderby1829c682016-01-22 22:49:55 +00001531 MachO::dysymtab_command Dysymtab =
Lang Hames697e7cd2016-12-04 01:56:10 +00001532 getStruct<MachO::dysymtab_command>(*this, DysymtabLoadCmd);
Kevin Enderby1829c682016-01-22 22:49:55 +00001533 if (Dysymtab.nlocalsym != 0 && Dysymtab.ilocalsym > Symtab.nsyms) {
Kevin Enderbyd4e075b2016-05-06 20:16:28 +00001534 Err = malformedError("ilocalsym in LC_DYSYMTAB load command "
Kevin Enderby89134962016-05-05 23:41:05 +00001535 "extends past the end of the symbol table");
Kevin Enderby1829c682016-01-22 22:49:55 +00001536 return;
1537 }
Kevin Enderby5e55d172016-04-21 20:29:49 +00001538 uint64_t BigSize = Dysymtab.ilocalsym;
1539 BigSize += Dysymtab.nlocalsym;
1540 if (Dysymtab.nlocalsym != 0 && BigSize > Symtab.nsyms) {
Kevin Enderbyd4e075b2016-05-06 20:16:28 +00001541 Err = malformedError("ilocalsym plus nlocalsym in LC_DYSYMTAB load "
Kevin Enderby89134962016-05-05 23:41:05 +00001542 "command extends past the end of the symbol table");
Kevin Enderby1829c682016-01-22 22:49:55 +00001543 return;
1544 }
1545 if (Dysymtab.nextdefsym != 0 && Dysymtab.ilocalsym > Symtab.nsyms) {
Kevin Enderbyd4e075b2016-05-06 20:16:28 +00001546 Err = malformedError("nextdefsym in LC_DYSYMTAB load command "
Kevin Enderby89134962016-05-05 23:41:05 +00001547 "extends past the end of the symbol table");
Kevin Enderby1829c682016-01-22 22:49:55 +00001548 return;
1549 }
Kevin Enderby5e55d172016-04-21 20:29:49 +00001550 BigSize = Dysymtab.iextdefsym;
1551 BigSize += Dysymtab.nextdefsym;
1552 if (Dysymtab.nextdefsym != 0 && BigSize > Symtab.nsyms) {
Kevin Enderbyd4e075b2016-05-06 20:16:28 +00001553 Err = malformedError("iextdefsym plus nextdefsym in LC_DYSYMTAB "
Kevin Enderby89134962016-05-05 23:41:05 +00001554 "load command extends past the end of the symbol "
1555 "table");
Kevin Enderby1829c682016-01-22 22:49:55 +00001556 return;
1557 }
1558 if (Dysymtab.nundefsym != 0 && Dysymtab.iundefsym > Symtab.nsyms) {
Kevin Enderbyd4e075b2016-05-06 20:16:28 +00001559 Err = malformedError("nundefsym in LC_DYSYMTAB load command "
Kevin Enderby89134962016-05-05 23:41:05 +00001560 "extends past the end of the symbol table");
Kevin Enderby1829c682016-01-22 22:49:55 +00001561 return;
1562 }
Kevin Enderby5e55d172016-04-21 20:29:49 +00001563 BigSize = Dysymtab.iundefsym;
1564 BigSize += Dysymtab.nundefsym;
1565 if (Dysymtab.nundefsym != 0 && BigSize > Symtab.nsyms) {
Kevin Enderbyd4e075b2016-05-06 20:16:28 +00001566 Err = malformedError("iundefsym plus nundefsym in LC_DYSYMTAB load "
Kevin Enderby89134962016-05-05 23:41:05 +00001567 " command extends past the end of the symbol table");
Kevin Enderby1829c682016-01-22 22:49:55 +00001568 return;
1569 }
1570 }
Kevin Enderbyfc0929a2016-09-20 20:14:14 +00001571 if ((getHeader().filetype == MachO::MH_DYLIB ||
1572 getHeader().filetype == MachO::MH_DYLIB_STUB) &&
1573 DyldIdLoadCmd == nullptr) {
1574 Err = malformedError("no LC_ID_DYLIB load command in dynamic library "
1575 "filetype");
1576 return;
1577 }
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00001578 assert(LoadCommands.size() == LoadCommandCount);
Lang Hames9e964f32016-03-25 17:25:34 +00001579
1580 Err = Error::success();
Rafael Espindola56f976f2013-04-18 18:08:55 +00001581}
1582
Kevin Enderby22fc0072016-11-14 20:57:04 +00001583Error MachOObjectFile::checkSymbolTable() const {
1584 uint32_t Flags = 0;
1585 if (is64Bit()) {
1586 MachO::mach_header_64 H_64 = MachOObjectFile::getHeader64();
1587 Flags = H_64.flags;
1588 } else {
1589 MachO::mach_header H = MachOObjectFile::getHeader();
1590 Flags = H.flags;
1591 }
1592 uint8_t NType = 0;
1593 uint8_t NSect = 0;
1594 uint16_t NDesc = 0;
1595 uint32_t NStrx = 0;
1596 uint64_t NValue = 0;
1597 uint32_t SymbolIndex = 0;
1598 MachO::symtab_command S = getSymtabLoadCommand();
1599 for (const SymbolRef &Symbol : symbols()) {
1600 DataRefImpl SymDRI = Symbol.getRawDataRefImpl();
1601 if (is64Bit()) {
1602 MachO::nlist_64 STE_64 = getSymbol64TableEntry(SymDRI);
1603 NType = STE_64.n_type;
1604 NSect = STE_64.n_sect;
1605 NDesc = STE_64.n_desc;
1606 NStrx = STE_64.n_strx;
1607 NValue = STE_64.n_value;
1608 } else {
1609 MachO::nlist STE = getSymbolTableEntry(SymDRI);
1610 NType = STE.n_type;
1611 NType = STE.n_type;
1612 NSect = STE.n_sect;
1613 NDesc = STE.n_desc;
1614 NStrx = STE.n_strx;
1615 NValue = STE.n_value;
1616 }
1617 if ((NType & MachO::N_STAB) == 0 &&
1618 (NType & MachO::N_TYPE) == MachO::N_SECT) {
1619 if (NSect == 0 || NSect > Sections.size())
1620 return malformedError("bad section index: " + Twine((int)NSect) +
1621 " for symbol at index " + Twine(SymbolIndex));
1622 }
1623 if ((NType & MachO::N_STAB) == 0 &&
1624 (NType & MachO::N_TYPE) == MachO::N_INDR) {
1625 if (NValue >= S.strsize)
1626 return malformedError("bad n_value: " + Twine((int)NValue) + " past "
1627 "the end of string table, for N_INDR symbol at "
1628 "index " + Twine(SymbolIndex));
1629 }
1630 if ((Flags & MachO::MH_TWOLEVEL) == MachO::MH_TWOLEVEL &&
1631 (((NType & MachO::N_TYPE) == MachO::N_UNDF && NValue == 0) ||
1632 (NType & MachO::N_TYPE) == MachO::N_PBUD)) {
1633 uint32_t LibraryOrdinal = MachO::GET_LIBRARY_ORDINAL(NDesc);
1634 if (LibraryOrdinal != 0 &&
1635 LibraryOrdinal != MachO::EXECUTABLE_ORDINAL &&
1636 LibraryOrdinal != MachO::DYNAMIC_LOOKUP_ORDINAL &&
1637 LibraryOrdinal - 1 >= Libraries.size() ) {
1638 return malformedError("bad library ordinal: " + Twine(LibraryOrdinal) +
1639 " for symbol at index " + Twine(SymbolIndex));
1640 }
1641 }
1642 if (NStrx >= S.strsize)
1643 return malformedError("bad string table index: " + Twine((int)NStrx) +
1644 " past the end of string table, for symbol at "
1645 "index " + Twine(SymbolIndex));
1646 SymbolIndex++;
1647 }
1648 return Error::success();
1649}
1650
Rafael Espindola5e812af2014-01-30 02:49:50 +00001651void MachOObjectFile::moveSymbolNext(DataRefImpl &Symb) const {
Rafael Espindola75c30362013-04-24 19:47:55 +00001652 unsigned SymbolTableEntrySize = is64Bit() ?
Charles Davis8bdfafd2013-09-01 04:28:48 +00001653 sizeof(MachO::nlist_64) :
1654 sizeof(MachO::nlist);
Rafael Espindola75c30362013-04-24 19:47:55 +00001655 Symb.p += SymbolTableEntrySize;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001656}
1657
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001658Expected<StringRef> MachOObjectFile::getSymbolName(DataRefImpl Symb) const {
Rafael Espindola6e040c02013-04-26 20:07:33 +00001659 StringRef StringTable = getStringTableData();
Lang Hames697e7cd2016-12-04 01:56:10 +00001660 MachO::nlist_base Entry = getSymbolTableEntryBase(*this, Symb);
Charles Davis8bdfafd2013-09-01 04:28:48 +00001661 const char *Start = &StringTable.data()[Entry.n_strx];
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001662 if (Start < getData().begin() || Start >= getData().end()) {
Kevin Enderbyd4e075b2016-05-06 20:16:28 +00001663 return malformedError("bad string index: " + Twine(Entry.n_strx) +
Kevin Enderby89134962016-05-05 23:41:05 +00001664 " for symbol at index " + Twine(getSymbolIndex(Symb)));
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001665 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001666 return StringRef(Start);
Rafael Espindola56f976f2013-04-18 18:08:55 +00001667}
1668
Rafael Espindola0e77a942014-12-10 20:46:55 +00001669unsigned MachOObjectFile::getSectionType(SectionRef Sec) const {
1670 DataRefImpl DRI = Sec.getRawDataRefImpl();
Lang Hames697e7cd2016-12-04 01:56:10 +00001671 uint32_t Flags = getSectionFlags(*this, DRI);
Rafael Espindola0e77a942014-12-10 20:46:55 +00001672 return Flags & MachO::SECTION_TYPE;
1673}
1674
Rafael Espindola59128922015-06-24 18:14:41 +00001675uint64_t MachOObjectFile::getNValue(DataRefImpl Sym) const {
1676 if (is64Bit()) {
1677 MachO::nlist_64 Entry = getSymbol64TableEntry(Sym);
1678 return Entry.n_value;
1679 }
1680 MachO::nlist Entry = getSymbolTableEntry(Sym);
1681 return Entry.n_value;
1682}
1683
Kevin Enderby980b2582014-06-05 21:21:57 +00001684// getIndirectName() returns the name of the alias'ed symbol who's string table
1685// index is in the n_value field.
Rafael Espindola3acea392014-06-12 21:46:39 +00001686std::error_code MachOObjectFile::getIndirectName(DataRefImpl Symb,
1687 StringRef &Res) const {
Kevin Enderby980b2582014-06-05 21:21:57 +00001688 StringRef StringTable = getStringTableData();
Lang Hames697e7cd2016-12-04 01:56:10 +00001689 MachO::nlist_base Entry = getSymbolTableEntryBase(*this, Symb);
Rafael Espindola59128922015-06-24 18:14:41 +00001690 if ((Entry.n_type & MachO::N_TYPE) != MachO::N_INDR)
1691 return object_error::parse_failed;
1692 uint64_t NValue = getNValue(Symb);
Kevin Enderby980b2582014-06-05 21:21:57 +00001693 if (NValue >= StringTable.size())
1694 return object_error::parse_failed;
1695 const char *Start = &StringTable.data()[NValue];
1696 Res = StringRef(Start);
Rui Ueyama7d099192015-06-09 15:20:42 +00001697 return std::error_code();
Kevin Enderby980b2582014-06-05 21:21:57 +00001698}
1699
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00001700uint64_t MachOObjectFile::getSymbolValueImpl(DataRefImpl Sym) const {
Rafael Espindola7e7be922015-07-07 15:05:09 +00001701 return getNValue(Sym);
Rafael Espindola991af662015-06-24 19:11:10 +00001702}
1703
Kevin Enderby931cb652016-06-24 18:24:42 +00001704Expected<uint64_t> MachOObjectFile::getSymbolAddress(DataRefImpl Sym) const {
Rafael Espindolaed067c42015-07-03 18:19:00 +00001705 return getSymbolValue(Sym);
Rafael Espindola56f976f2013-04-18 18:08:55 +00001706}
1707
Rafael Espindolaa4d224722015-05-31 23:52:50 +00001708uint32_t MachOObjectFile::getSymbolAlignment(DataRefImpl DRI) const {
Rafael Espindola20122a42014-01-31 20:57:12 +00001709 uint32_t flags = getSymbolFlags(DRI);
Rafael Espindolae4dd2e02013-04-29 22:24:22 +00001710 if (flags & SymbolRef::SF_Common) {
Lang Hames697e7cd2016-12-04 01:56:10 +00001711 MachO::nlist_base Entry = getSymbolTableEntryBase(*this, DRI);
Rafael Espindolaa4d224722015-05-31 23:52:50 +00001712 return 1 << MachO::GET_COMM_ALIGN(Entry.n_desc);
Rafael Espindolae4dd2e02013-04-29 22:24:22 +00001713 }
Rafael Espindolaa4d224722015-05-31 23:52:50 +00001714 return 0;
Rafael Espindolae4dd2e02013-04-29 22:24:22 +00001715}
1716
Rafael Espindolad7a32ea2015-06-24 10:20:30 +00001717uint64_t MachOObjectFile::getCommonSymbolSizeImpl(DataRefImpl DRI) const {
Rafael Espindola05cbccc2015-07-07 13:58:32 +00001718 return getNValue(DRI);
Rafael Espindola56f976f2013-04-18 18:08:55 +00001719}
1720
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001721Expected<SymbolRef::Type>
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00001722MachOObjectFile::getSymbolType(DataRefImpl Symb) const {
Lang Hames697e7cd2016-12-04 01:56:10 +00001723 MachO::nlist_base Entry = getSymbolTableEntryBase(*this, Symb);
Charles Davis8bdfafd2013-09-01 04:28:48 +00001724 uint8_t n_type = Entry.n_type;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001725
Rafael Espindola56f976f2013-04-18 18:08:55 +00001726 // If this is a STAB debugging symbol, we can do nothing more.
Rafael Espindola2fa80cc2015-06-26 12:18:49 +00001727 if (n_type & MachO::N_STAB)
1728 return SymbolRef::ST_Debug;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001729
Charles Davis74ec8b02013-08-27 05:00:13 +00001730 switch (n_type & MachO::N_TYPE) {
1731 case MachO::N_UNDF :
Rafael Espindola2fa80cc2015-06-26 12:18:49 +00001732 return SymbolRef::ST_Unknown;
Charles Davis74ec8b02013-08-27 05:00:13 +00001733 case MachO::N_SECT :
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001734 Expected<section_iterator> SecOrError = getSymbolSection(Symb);
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00001735 if (!SecOrError)
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001736 return SecOrError.takeError();
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00001737 section_iterator Sec = *SecOrError;
Kuba Breckade833222015-11-12 09:40:29 +00001738 if (Sec->isData() || Sec->isBSS())
1739 return SymbolRef::ST_Data;
Rafael Espindola2fa80cc2015-06-26 12:18:49 +00001740 return SymbolRef::ST_Function;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001741 }
Rafael Espindola2fa80cc2015-06-26 12:18:49 +00001742 return SymbolRef::ST_Other;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001743}
1744
Rafael Espindola20122a42014-01-31 20:57:12 +00001745uint32_t MachOObjectFile::getSymbolFlags(DataRefImpl DRI) const {
Lang Hames697e7cd2016-12-04 01:56:10 +00001746 MachO::nlist_base Entry = getSymbolTableEntryBase(*this, DRI);
Rafael Espindola56f976f2013-04-18 18:08:55 +00001747
Charles Davis8bdfafd2013-09-01 04:28:48 +00001748 uint8_t MachOType = Entry.n_type;
1749 uint16_t MachOFlags = Entry.n_desc;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001750
Rafael Espindola20122a42014-01-31 20:57:12 +00001751 uint32_t Result = SymbolRef::SF_None;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001752
Tim Northovereaef0742014-05-30 13:22:59 +00001753 if ((MachOType & MachO::N_TYPE) == MachO::N_INDR)
1754 Result |= SymbolRef::SF_Indirect;
1755
Rafael Espindolaa1356322013-11-02 05:03:24 +00001756 if (MachOType & MachO::N_STAB)
Rafael Espindola56f976f2013-04-18 18:08:55 +00001757 Result |= SymbolRef::SF_FormatSpecific;
1758
Charles Davis74ec8b02013-08-27 05:00:13 +00001759 if (MachOType & MachO::N_EXT) {
Rafael Espindola56f976f2013-04-18 18:08:55 +00001760 Result |= SymbolRef::SF_Global;
Charles Davis74ec8b02013-08-27 05:00:13 +00001761 if ((MachOType & MachO::N_TYPE) == MachO::N_UNDF) {
Rafael Espindola05cbccc2015-07-07 13:58:32 +00001762 if (getNValue(DRI))
Rafael Espindolae4dd2e02013-04-29 22:24:22 +00001763 Result |= SymbolRef::SF_Common;
Rafael Espindolad8247722015-07-07 14:26:39 +00001764 else
1765 Result |= SymbolRef::SF_Undefined;
Rafael Espindolae4dd2e02013-04-29 22:24:22 +00001766 }
Lang Hames7e0692b2015-01-15 22:33:30 +00001767
1768 if (!(MachOType & MachO::N_PEXT))
1769 Result |= SymbolRef::SF_Exported;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001770 }
1771
Charles Davis74ec8b02013-08-27 05:00:13 +00001772 if (MachOFlags & (MachO::N_WEAK_REF | MachO::N_WEAK_DEF))
Rafael Espindola56f976f2013-04-18 18:08:55 +00001773 Result |= SymbolRef::SF_Weak;
1774
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001775 if (MachOFlags & (MachO::N_ARM_THUMB_DEF))
1776 Result |= SymbolRef::SF_Thumb;
1777
Charles Davis74ec8b02013-08-27 05:00:13 +00001778 if ((MachOType & MachO::N_TYPE) == MachO::N_ABS)
Rafael Espindola56f976f2013-04-18 18:08:55 +00001779 Result |= SymbolRef::SF_Absolute;
1780
Rafael Espindola20122a42014-01-31 20:57:12 +00001781 return Result;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001782}
1783
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001784Expected<section_iterator>
Rafael Espindola8bab8892015-08-07 23:27:14 +00001785MachOObjectFile::getSymbolSection(DataRefImpl Symb) const {
Lang Hames697e7cd2016-12-04 01:56:10 +00001786 MachO::nlist_base Entry = getSymbolTableEntryBase(*this, Symb);
Charles Davis8bdfafd2013-09-01 04:28:48 +00001787 uint8_t index = Entry.n_sect;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001788
Rafael Espindola8bab8892015-08-07 23:27:14 +00001789 if (index == 0)
1790 return section_end();
1791 DataRefImpl DRI;
1792 DRI.d.a = index - 1;
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00001793 if (DRI.d.a >= Sections.size()){
Kevin Enderbyd4e075b2016-05-06 20:16:28 +00001794 return malformedError("bad section index: " + Twine((int)index) +
Kevin Enderby89134962016-05-05 23:41:05 +00001795 " for symbol at index " + Twine(getSymbolIndex(Symb)));
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00001796 }
Rafael Espindola8bab8892015-08-07 23:27:14 +00001797 return section_iterator(SectionRef(DRI, this));
Rafael Espindola56f976f2013-04-18 18:08:55 +00001798}
1799
Rafael Espindola6bf32212015-06-24 19:57:32 +00001800unsigned MachOObjectFile::getSymbolSectionID(SymbolRef Sym) const {
1801 MachO::nlist_base Entry =
Lang Hames697e7cd2016-12-04 01:56:10 +00001802 getSymbolTableEntryBase(*this, Sym.getRawDataRefImpl());
Rafael Espindola6bf32212015-06-24 19:57:32 +00001803 return Entry.n_sect - 1;
1804}
1805
Rafael Espindola5e812af2014-01-30 02:49:50 +00001806void MachOObjectFile::moveSectionNext(DataRefImpl &Sec) const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00001807 Sec.d.a++;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001808}
1809
Rafael Espindola3acea392014-06-12 21:46:39 +00001810std::error_code MachOObjectFile::getSectionName(DataRefImpl Sec,
1811 StringRef &Result) const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00001812 ArrayRef<char> Raw = getSectionRawName(Sec);
1813 Result = parseSegmentOrSectionName(Raw.data());
Rui Ueyama7d099192015-06-09 15:20:42 +00001814 return std::error_code();
Rafael Espindola56f976f2013-04-18 18:08:55 +00001815}
1816
Rafael Espindola80291272014-10-08 15:28:58 +00001817uint64_t MachOObjectFile::getSectionAddress(DataRefImpl Sec) const {
1818 if (is64Bit())
1819 return getSection64(Sec).addr;
1820 return getSection(Sec).addr;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001821}
1822
George Rimara25d3292017-05-27 18:10:23 +00001823uint64_t MachOObjectFile::getSectionIndex(DataRefImpl Sec) const {
1824 return Sec.d.a;
1825}
1826
Rafael Espindola80291272014-10-08 15:28:58 +00001827uint64_t MachOObjectFile::getSectionSize(DataRefImpl Sec) const {
Kevin Enderby46e642f2015-10-08 22:50:55 +00001828 // In the case if a malformed Mach-O file where the section offset is past
1829 // the end of the file or some part of the section size is past the end of
1830 // the file return a size of zero or a size that covers the rest of the file
1831 // but does not extend past the end of the file.
1832 uint32_t SectOffset, SectType;
1833 uint64_t SectSize;
1834
1835 if (is64Bit()) {
1836 MachO::section_64 Sect = getSection64(Sec);
1837 SectOffset = Sect.offset;
1838 SectSize = Sect.size;
1839 SectType = Sect.flags & MachO::SECTION_TYPE;
1840 } else {
1841 MachO::section Sect = getSection(Sec);
1842 SectOffset = Sect.offset;
1843 SectSize = Sect.size;
1844 SectType = Sect.flags & MachO::SECTION_TYPE;
1845 }
1846 if (SectType == MachO::S_ZEROFILL || SectType == MachO::S_GB_ZEROFILL)
1847 return SectSize;
1848 uint64_t FileSize = getData().size();
1849 if (SectOffset > FileSize)
1850 return 0;
1851 if (FileSize - SectOffset < SectSize)
1852 return FileSize - SectOffset;
1853 return SectSize;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001854}
1855
Rafael Espindola3acea392014-06-12 21:46:39 +00001856std::error_code MachOObjectFile::getSectionContents(DataRefImpl Sec,
1857 StringRef &Res) const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00001858 uint32_t Offset;
1859 uint64_t Size;
1860
1861 if (is64Bit()) {
Charles Davis8bdfafd2013-09-01 04:28:48 +00001862 MachO::section_64 Sect = getSection64(Sec);
1863 Offset = Sect.offset;
1864 Size = Sect.size;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001865 } else {
Charles Davis8bdfafd2013-09-01 04:28:48 +00001866 MachO::section Sect = getSection(Sec);
1867 Offset = Sect.offset;
1868 Size = Sect.size;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001869 }
1870
1871 Res = this->getData().substr(Offset, Size);
Rui Ueyama7d099192015-06-09 15:20:42 +00001872 return std::error_code();
Rafael Espindola56f976f2013-04-18 18:08:55 +00001873}
1874
Rafael Espindola80291272014-10-08 15:28:58 +00001875uint64_t MachOObjectFile::getSectionAlignment(DataRefImpl Sec) const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00001876 uint32_t Align;
1877 if (is64Bit()) {
Charles Davis8bdfafd2013-09-01 04:28:48 +00001878 MachO::section_64 Sect = getSection64(Sec);
1879 Align = Sect.align;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001880 } else {
Charles Davis8bdfafd2013-09-01 04:28:48 +00001881 MachO::section Sect = getSection(Sec);
1882 Align = Sect.align;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001883 }
1884
Rafael Espindola80291272014-10-08 15:28:58 +00001885 return uint64_t(1) << Align;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001886}
1887
George Rimar401e4e52016-05-24 12:48:46 +00001888bool MachOObjectFile::isSectionCompressed(DataRefImpl Sec) const {
1889 return false;
1890}
1891
Rafael Espindola80291272014-10-08 15:28:58 +00001892bool MachOObjectFile::isSectionText(DataRefImpl Sec) const {
Lang Hames697e7cd2016-12-04 01:56:10 +00001893 uint32_t Flags = getSectionFlags(*this, Sec);
Rafael Espindola80291272014-10-08 15:28:58 +00001894 return Flags & MachO::S_ATTR_PURE_INSTRUCTIONS;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001895}
1896
Rafael Espindola80291272014-10-08 15:28:58 +00001897bool MachOObjectFile::isSectionData(DataRefImpl Sec) const {
Lang Hames697e7cd2016-12-04 01:56:10 +00001898 uint32_t Flags = getSectionFlags(*this, Sec);
Kevin Enderby403258f2014-05-19 20:36:02 +00001899 unsigned SectionType = Flags & MachO::SECTION_TYPE;
Rafael Espindola80291272014-10-08 15:28:58 +00001900 return !(Flags & MachO::S_ATTR_PURE_INSTRUCTIONS) &&
1901 !(SectionType == MachO::S_ZEROFILL ||
1902 SectionType == MachO::S_GB_ZEROFILL);
Michael J. Spencer800619f2011-09-28 20:57:30 +00001903}
1904
Rafael Espindola80291272014-10-08 15:28:58 +00001905bool MachOObjectFile::isSectionBSS(DataRefImpl Sec) const {
Lang Hames697e7cd2016-12-04 01:56:10 +00001906 uint32_t Flags = getSectionFlags(*this, Sec);
Kevin Enderby403258f2014-05-19 20:36:02 +00001907 unsigned SectionType = Flags & MachO::SECTION_TYPE;
Rafael Espindola80291272014-10-08 15:28:58 +00001908 return !(Flags & MachO::S_ATTR_PURE_INSTRUCTIONS) &&
1909 (SectionType == MachO::S_ZEROFILL ||
1910 SectionType == MachO::S_GB_ZEROFILL);
Preston Gurd2138ef62012-04-12 20:13:57 +00001911}
1912
Rafael Espindola6bf32212015-06-24 19:57:32 +00001913unsigned MachOObjectFile::getSectionID(SectionRef Sec) const {
1914 return Sec.getRawDataRefImpl().d.a;
1915}
1916
Rafael Espindola80291272014-10-08 15:28:58 +00001917bool MachOObjectFile::isSectionVirtual(DataRefImpl Sec) const {
Rafael Espindolac2413f52013-04-09 14:49:08 +00001918 // FIXME: Unimplemented.
Rafael Espindola80291272014-10-08 15:28:58 +00001919 return false;
Rafael Espindolac2413f52013-04-09 14:49:08 +00001920}
1921
Steven Wuf2fe0142016-02-29 19:40:10 +00001922bool MachOObjectFile::isSectionBitcode(DataRefImpl Sec) const {
1923 StringRef SegmentName = getSectionFinalSegmentName(Sec);
1924 StringRef SectName;
1925 if (!getSectionName(Sec, SectName))
1926 return (SegmentName == "__LLVM" && SectName == "__bitcode");
1927 return false;
1928}
1929
Rui Ueyamabc654b12013-09-27 21:47:05 +00001930relocation_iterator MachOObjectFile::section_rel_begin(DataRefImpl Sec) const {
Rafael Espindola04d3f492013-04-25 12:45:46 +00001931 DataRefImpl Ret;
Rafael Espindola128b8112014-04-03 23:51:28 +00001932 Ret.d.a = Sec.d.a;
1933 Ret.d.b = 0;
Rafael Espindola04d3f492013-04-25 12:45:46 +00001934 return relocation_iterator(RelocationRef(Ret, this));
Michael J. Spencere5fd0042011-10-07 19:25:32 +00001935}
Rafael Espindolac0406e12013-04-08 20:45:01 +00001936
Rafael Espindola56f976f2013-04-18 18:08:55 +00001937relocation_iterator
Rui Ueyamabc654b12013-09-27 21:47:05 +00001938MachOObjectFile::section_rel_end(DataRefImpl Sec) const {
Rafael Espindola04d3f492013-04-25 12:45:46 +00001939 uint32_t Num;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001940 if (is64Bit()) {
Charles Davis8bdfafd2013-09-01 04:28:48 +00001941 MachO::section_64 Sect = getSection64(Sec);
Charles Davis8bdfafd2013-09-01 04:28:48 +00001942 Num = Sect.nreloc;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001943 } else {
Charles Davis8bdfafd2013-09-01 04:28:48 +00001944 MachO::section Sect = getSection(Sec);
Charles Davis8bdfafd2013-09-01 04:28:48 +00001945 Num = Sect.nreloc;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001946 }
Eric Christopher7b015c72011-04-22 03:19:48 +00001947
Rafael Espindola56f976f2013-04-18 18:08:55 +00001948 DataRefImpl Ret;
Rafael Espindola128b8112014-04-03 23:51:28 +00001949 Ret.d.a = Sec.d.a;
1950 Ret.d.b = Num;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001951 return relocation_iterator(RelocationRef(Ret, this));
1952}
Benjamin Kramer022ecdf2011-09-08 20:52:17 +00001953
Rafael Espindola5e812af2014-01-30 02:49:50 +00001954void MachOObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
Rafael Espindola128b8112014-04-03 23:51:28 +00001955 ++Rel.d.b;
Benjamin Kramer022ecdf2011-09-08 20:52:17 +00001956}
Owen Anderson171f4852011-10-24 23:20:07 +00001957
Rafael Espindola96d071c2015-06-29 23:29:12 +00001958uint64_t MachOObjectFile::getRelocationOffset(DataRefImpl Rel) const {
Rafael Espindola72475462014-04-04 00:31:12 +00001959 assert(getHeader().filetype == MachO::MH_OBJECT &&
1960 "Only implemented for MH_OBJECT");
Charles Davis8bdfafd2013-09-01 04:28:48 +00001961 MachO::any_relocation_info RE = getRelocation(Rel);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001962 return getAnyRelocationAddress(RE);
David Meyer2fc34c52012-03-01 01:36:50 +00001963}
1964
Rafael Espindola806f0062013-06-05 01:33:53 +00001965symbol_iterator
1966MachOObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
Charles Davis8bdfafd2013-09-01 04:28:48 +00001967 MachO::any_relocation_info RE = getRelocation(Rel);
Tim Northover07f99fb2014-07-04 10:57:56 +00001968 if (isRelocationScattered(RE))
1969 return symbol_end();
1970
Rafael Espindola56f976f2013-04-18 18:08:55 +00001971 uint32_t SymbolIdx = getPlainRelocationSymbolNum(RE);
1972 bool isExtern = getPlainRelocationExternal(RE);
Rafael Espindola806f0062013-06-05 01:33:53 +00001973 if (!isExtern)
Rafael Espindolab5155a52014-02-10 20:24:04 +00001974 return symbol_end();
Rafael Espindola75c30362013-04-24 19:47:55 +00001975
Charles Davis8bdfafd2013-09-01 04:28:48 +00001976 MachO::symtab_command S = getSymtabLoadCommand();
Rafael Espindola75c30362013-04-24 19:47:55 +00001977 unsigned SymbolTableEntrySize = is64Bit() ?
Charles Davis8bdfafd2013-09-01 04:28:48 +00001978 sizeof(MachO::nlist_64) :
1979 sizeof(MachO::nlist);
1980 uint64_t Offset = S.symoff + SymbolIdx * SymbolTableEntrySize;
Rafael Espindola75c30362013-04-24 19:47:55 +00001981 DataRefImpl Sym;
Lang Hames697e7cd2016-12-04 01:56:10 +00001982 Sym.p = reinterpret_cast<uintptr_t>(getPtr(*this, Offset));
Rafael Espindola806f0062013-06-05 01:33:53 +00001983 return symbol_iterator(SymbolRef(Sym, this));
Rafael Espindola56f976f2013-04-18 18:08:55 +00001984}
1985
Keno Fischerc780e8e2015-05-21 21:24:32 +00001986section_iterator
1987MachOObjectFile::getRelocationSection(DataRefImpl Rel) const {
1988 return section_iterator(getAnyRelocationSection(getRelocation(Rel)));
1989}
1990
Rafael Espindola99c041b2015-06-30 01:53:01 +00001991uint64_t MachOObjectFile::getRelocationType(DataRefImpl Rel) const {
Charles Davis8bdfafd2013-09-01 04:28:48 +00001992 MachO::any_relocation_info RE = getRelocation(Rel);
Rafael Espindola99c041b2015-06-30 01:53:01 +00001993 return getAnyRelocationType(RE);
Rafael Espindola56f976f2013-04-18 18:08:55 +00001994}
1995
Rafael Espindola41bb4322015-06-30 04:08:37 +00001996void MachOObjectFile::getRelocationTypeName(
1997 DataRefImpl Rel, SmallVectorImpl<char> &Result) const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00001998 StringRef res;
Rafael Espindola99c041b2015-06-30 01:53:01 +00001999 uint64_t RType = getRelocationType(Rel);
Rafael Espindola56f976f2013-04-18 18:08:55 +00002000
2001 unsigned Arch = this->getArch();
2002
2003 switch (Arch) {
2004 case Triple::x86: {
2005 static const char *const Table[] = {
2006 "GENERIC_RELOC_VANILLA",
2007 "GENERIC_RELOC_PAIR",
2008 "GENERIC_RELOC_SECTDIFF",
2009 "GENERIC_RELOC_PB_LA_PTR",
2010 "GENERIC_RELOC_LOCAL_SECTDIFF",
2011 "GENERIC_RELOC_TLV" };
2012
Eric Christopher13250cb2013-12-06 02:33:38 +00002013 if (RType > 5)
Rafael Espindola56f976f2013-04-18 18:08:55 +00002014 res = "Unknown";
2015 else
2016 res = Table[RType];
2017 break;
2018 }
2019 case Triple::x86_64: {
2020 static const char *const Table[] = {
2021 "X86_64_RELOC_UNSIGNED",
2022 "X86_64_RELOC_SIGNED",
2023 "X86_64_RELOC_BRANCH",
2024 "X86_64_RELOC_GOT_LOAD",
2025 "X86_64_RELOC_GOT",
2026 "X86_64_RELOC_SUBTRACTOR",
2027 "X86_64_RELOC_SIGNED_1",
2028 "X86_64_RELOC_SIGNED_2",
2029 "X86_64_RELOC_SIGNED_4",
2030 "X86_64_RELOC_TLV" };
2031
2032 if (RType > 9)
2033 res = "Unknown";
2034 else
2035 res = Table[RType];
2036 break;
2037 }
2038 case Triple::arm: {
2039 static const char *const Table[] = {
2040 "ARM_RELOC_VANILLA",
2041 "ARM_RELOC_PAIR",
2042 "ARM_RELOC_SECTDIFF",
2043 "ARM_RELOC_LOCAL_SECTDIFF",
2044 "ARM_RELOC_PB_LA_PTR",
2045 "ARM_RELOC_BR24",
2046 "ARM_THUMB_RELOC_BR22",
2047 "ARM_THUMB_32BIT_BRANCH",
2048 "ARM_RELOC_HALF",
2049 "ARM_RELOC_HALF_SECTDIFF" };
2050
2051 if (RType > 9)
2052 res = "Unknown";
2053 else
2054 res = Table[RType];
2055 break;
2056 }
Tim Northover00ed9962014-03-29 10:18:08 +00002057 case Triple::aarch64: {
2058 static const char *const Table[] = {
2059 "ARM64_RELOC_UNSIGNED", "ARM64_RELOC_SUBTRACTOR",
2060 "ARM64_RELOC_BRANCH26", "ARM64_RELOC_PAGE21",
2061 "ARM64_RELOC_PAGEOFF12", "ARM64_RELOC_GOT_LOAD_PAGE21",
2062 "ARM64_RELOC_GOT_LOAD_PAGEOFF12", "ARM64_RELOC_POINTER_TO_GOT",
2063 "ARM64_RELOC_TLVP_LOAD_PAGE21", "ARM64_RELOC_TLVP_LOAD_PAGEOFF12",
2064 "ARM64_RELOC_ADDEND"
2065 };
2066
2067 if (RType >= array_lengthof(Table))
2068 res = "Unknown";
2069 else
2070 res = Table[RType];
2071 break;
2072 }
Rafael Espindola56f976f2013-04-18 18:08:55 +00002073 case Triple::ppc: {
2074 static const char *const Table[] = {
2075 "PPC_RELOC_VANILLA",
2076 "PPC_RELOC_PAIR",
2077 "PPC_RELOC_BR14",
2078 "PPC_RELOC_BR24",
2079 "PPC_RELOC_HI16",
2080 "PPC_RELOC_LO16",
2081 "PPC_RELOC_HA16",
2082 "PPC_RELOC_LO14",
2083 "PPC_RELOC_SECTDIFF",
2084 "PPC_RELOC_PB_LA_PTR",
2085 "PPC_RELOC_HI16_SECTDIFF",
2086 "PPC_RELOC_LO16_SECTDIFF",
2087 "PPC_RELOC_HA16_SECTDIFF",
2088 "PPC_RELOC_JBSR",
2089 "PPC_RELOC_LO14_SECTDIFF",
2090 "PPC_RELOC_LOCAL_SECTDIFF" };
2091
Eric Christopher13250cb2013-12-06 02:33:38 +00002092 if (RType > 15)
2093 res = "Unknown";
2094 else
2095 res = Table[RType];
Rafael Espindola56f976f2013-04-18 18:08:55 +00002096 break;
2097 }
2098 case Triple::UnknownArch:
2099 res = "Unknown";
2100 break;
2101 }
2102 Result.append(res.begin(), res.end());
Rafael Espindola56f976f2013-04-18 18:08:55 +00002103}
2104
Keno Fischer281b6942015-05-30 19:44:53 +00002105uint8_t MachOObjectFile::getRelocationLength(DataRefImpl Rel) const {
2106 MachO::any_relocation_info RE = getRelocation(Rel);
2107 return getAnyRelocationLength(RE);
2108}
2109
Kevin Enderby980b2582014-06-05 21:21:57 +00002110//
2111// guessLibraryShortName() is passed a name of a dynamic library and returns a
2112// guess on what the short name is. Then name is returned as a substring of the
2113// StringRef Name passed in. The name of the dynamic library is recognized as
2114// a framework if it has one of the two following forms:
2115// Foo.framework/Versions/A/Foo
2116// Foo.framework/Foo
2117// Where A and Foo can be any string. And may contain a trailing suffix
2118// starting with an underbar. If the Name is recognized as a framework then
2119// isFramework is set to true else it is set to false. If the Name has a
2120// suffix then Suffix is set to the substring in Name that contains the suffix
2121// else it is set to a NULL StringRef.
2122//
2123// The Name of the dynamic library is recognized as a library name if it has
2124// one of the two following forms:
2125// libFoo.A.dylib
2126// libFoo.dylib
2127// The library may have a suffix trailing the name Foo of the form:
2128// libFoo_profile.A.dylib
2129// libFoo_profile.dylib
2130//
2131// The Name of the dynamic library is also recognized as a library name if it
2132// has the following form:
2133// Foo.qtx
2134//
2135// If the Name of the dynamic library is none of the forms above then a NULL
2136// StringRef is returned.
2137//
2138StringRef MachOObjectFile::guessLibraryShortName(StringRef Name,
2139 bool &isFramework,
2140 StringRef &Suffix) {
2141 StringRef Foo, F, DotFramework, V, Dylib, Lib, Dot, Qtx;
2142 size_t a, b, c, d, Idx;
2143
2144 isFramework = false;
2145 Suffix = StringRef();
2146
2147 // Pull off the last component and make Foo point to it
2148 a = Name.rfind('/');
2149 if (a == Name.npos || a == 0)
2150 goto guess_library;
2151 Foo = Name.slice(a+1, Name.npos);
2152
2153 // Look for a suffix starting with a '_'
2154 Idx = Foo.rfind('_');
2155 if (Idx != Foo.npos && Foo.size() >= 2) {
2156 Suffix = Foo.slice(Idx, Foo.npos);
2157 Foo = Foo.slice(0, Idx);
2158 }
2159
2160 // First look for the form Foo.framework/Foo
2161 b = Name.rfind('/', a);
2162 if (b == Name.npos)
2163 Idx = 0;
2164 else
2165 Idx = b+1;
2166 F = Name.slice(Idx, Idx + Foo.size());
2167 DotFramework = Name.slice(Idx + Foo.size(),
2168 Idx + Foo.size() + sizeof(".framework/")-1);
2169 if (F == Foo && DotFramework == ".framework/") {
2170 isFramework = true;
2171 return Foo;
2172 }
2173
2174 // Next look for the form Foo.framework/Versions/A/Foo
2175 if (b == Name.npos)
2176 goto guess_library;
2177 c = Name.rfind('/', b);
2178 if (c == Name.npos || c == 0)
2179 goto guess_library;
2180 V = Name.slice(c+1, Name.npos);
2181 if (!V.startswith("Versions/"))
2182 goto guess_library;
2183 d = Name.rfind('/', c);
2184 if (d == Name.npos)
2185 Idx = 0;
2186 else
2187 Idx = d+1;
2188 F = Name.slice(Idx, Idx + Foo.size());
2189 DotFramework = Name.slice(Idx + Foo.size(),
2190 Idx + Foo.size() + sizeof(".framework/")-1);
2191 if (F == Foo && DotFramework == ".framework/") {
2192 isFramework = true;
2193 return Foo;
2194 }
2195
2196guess_library:
2197 // pull off the suffix after the "." and make a point to it
2198 a = Name.rfind('.');
2199 if (a == Name.npos || a == 0)
2200 return StringRef();
2201 Dylib = Name.slice(a, Name.npos);
2202 if (Dylib != ".dylib")
2203 goto guess_qtx;
2204
2205 // First pull off the version letter for the form Foo.A.dylib if any.
2206 if (a >= 3) {
2207 Dot = Name.slice(a-2, a-1);
2208 if (Dot == ".")
2209 a = a - 2;
2210 }
2211
2212 b = Name.rfind('/', a);
2213 if (b == Name.npos)
2214 b = 0;
2215 else
2216 b = b+1;
2217 // ignore any suffix after an underbar like Foo_profile.A.dylib
2218 Idx = Name.find('_', b);
2219 if (Idx != Name.npos && Idx != b) {
2220 Lib = Name.slice(b, Idx);
2221 Suffix = Name.slice(Idx, a);
2222 }
2223 else
2224 Lib = Name.slice(b, a);
2225 // There are incorrect library names of the form:
2226 // libATS.A_profile.dylib so check for these.
2227 if (Lib.size() >= 3) {
2228 Dot = Lib.slice(Lib.size()-2, Lib.size()-1);
2229 if (Dot == ".")
2230 Lib = Lib.slice(0, Lib.size()-2);
2231 }
2232 return Lib;
2233
2234guess_qtx:
2235 Qtx = Name.slice(a, Name.npos);
2236 if (Qtx != ".qtx")
2237 return StringRef();
2238 b = Name.rfind('/', a);
2239 if (b == Name.npos)
2240 Lib = Name.slice(0, a);
2241 else
2242 Lib = Name.slice(b+1, a);
2243 // There are library names of the form: QT.A.qtx so check for these.
2244 if (Lib.size() >= 3) {
2245 Dot = Lib.slice(Lib.size()-2, Lib.size()-1);
2246 if (Dot == ".")
2247 Lib = Lib.slice(0, Lib.size()-2);
2248 }
2249 return Lib;
2250}
2251
2252// getLibraryShortNameByIndex() is used to get the short name of the library
2253// for an undefined symbol in a linked Mach-O binary that was linked with the
2254// normal two-level namespace default (that is MH_TWOLEVEL in the header).
2255// It is passed the index (0 - based) of the library as translated from
2256// GET_LIBRARY_ORDINAL (1 - based).
Rafael Espindola3acea392014-06-12 21:46:39 +00002257std::error_code MachOObjectFile::getLibraryShortNameByIndex(unsigned Index,
Nick Kledzikd04bc352014-08-30 00:20:14 +00002258 StringRef &Res) const {
Kevin Enderby980b2582014-06-05 21:21:57 +00002259 if (Index >= Libraries.size())
2260 return object_error::parse_failed;
2261
Kevin Enderby980b2582014-06-05 21:21:57 +00002262 // If the cache of LibrariesShortNames is not built up do that first for
2263 // all the Libraries.
2264 if (LibrariesShortNames.size() == 0) {
2265 for (unsigned i = 0; i < Libraries.size(); i++) {
2266 MachO::dylib_command D =
Lang Hames697e7cd2016-12-04 01:56:10 +00002267 getStruct<MachO::dylib_command>(*this, Libraries[i]);
Nick Kledzik30061302014-09-17 00:25:22 +00002268 if (D.dylib.name >= D.cmdsize)
2269 return object_error::parse_failed;
Kevin Enderby4eff6cd2014-06-20 18:07:34 +00002270 const char *P = (const char *)(Libraries[i]) + D.dylib.name;
Kevin Enderby980b2582014-06-05 21:21:57 +00002271 StringRef Name = StringRef(P);
Nick Kledzik30061302014-09-17 00:25:22 +00002272 if (D.dylib.name+Name.size() >= D.cmdsize)
2273 return object_error::parse_failed;
Kevin Enderby980b2582014-06-05 21:21:57 +00002274 StringRef Suffix;
2275 bool isFramework;
2276 StringRef shortName = guessLibraryShortName(Name, isFramework, Suffix);
Nick Kledzik30061302014-09-17 00:25:22 +00002277 if (shortName.empty())
Kevin Enderby980b2582014-06-05 21:21:57 +00002278 LibrariesShortNames.push_back(Name);
2279 else
2280 LibrariesShortNames.push_back(shortName);
2281 }
2282 }
2283
2284 Res = LibrariesShortNames[Index];
Rui Ueyama7d099192015-06-09 15:20:42 +00002285 return std::error_code();
Kevin Enderby980b2582014-06-05 21:21:57 +00002286}
2287
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00002288uint32_t MachOObjectFile::getLibraryCount() const {
2289 return Libraries.size();
2290}
2291
Rafael Espindola76ad2322015-07-06 14:55:37 +00002292section_iterator
2293MachOObjectFile::getRelocationRelocatedSection(relocation_iterator Rel) const {
2294 DataRefImpl Sec;
2295 Sec.d.a = Rel->getRawDataRefImpl().d.a;
2296 return section_iterator(SectionRef(Sec, this));
2297}
2298
Peter Collingbourne435890a2016-11-22 03:38:40 +00002299basic_symbol_iterator MachOObjectFile::symbol_begin() const {
Kevin Enderby1829c682016-01-22 22:49:55 +00002300 DataRefImpl DRI;
2301 MachO::symtab_command Symtab = getSymtabLoadCommand();
2302 if (!SymtabLoadCmd || Symtab.nsyms == 0)
2303 return basic_symbol_iterator(SymbolRef(DRI, this));
2304
Lang Hames36072da2014-05-12 21:39:59 +00002305 return getSymbolByIndex(0);
Rafael Espindola56f976f2013-04-18 18:08:55 +00002306}
2307
Peter Collingbourne435890a2016-11-22 03:38:40 +00002308basic_symbol_iterator MachOObjectFile::symbol_end() const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00002309 DataRefImpl DRI;
Kevin Enderby1829c682016-01-22 22:49:55 +00002310 MachO::symtab_command Symtab = getSymtabLoadCommand();
2311 if (!SymtabLoadCmd || Symtab.nsyms == 0)
Rafael Espindolaf12b8282014-02-21 20:10:59 +00002312 return basic_symbol_iterator(SymbolRef(DRI, this));
Rafael Espindola75c30362013-04-24 19:47:55 +00002313
Rafael Espindola75c30362013-04-24 19:47:55 +00002314 unsigned SymbolTableEntrySize = is64Bit() ?
Charles Davis8bdfafd2013-09-01 04:28:48 +00002315 sizeof(MachO::nlist_64) :
2316 sizeof(MachO::nlist);
2317 unsigned Offset = Symtab.symoff +
2318 Symtab.nsyms * SymbolTableEntrySize;
Lang Hames697e7cd2016-12-04 01:56:10 +00002319 DRI.p = reinterpret_cast<uintptr_t>(getPtr(*this, Offset));
Rafael Espindolaf12b8282014-02-21 20:10:59 +00002320 return basic_symbol_iterator(SymbolRef(DRI, this));
Rafael Espindola56f976f2013-04-18 18:08:55 +00002321}
2322
Lang Hames36072da2014-05-12 21:39:59 +00002323basic_symbol_iterator MachOObjectFile::getSymbolByIndex(unsigned Index) const {
Lang Hames36072da2014-05-12 21:39:59 +00002324 MachO::symtab_command Symtab = getSymtabLoadCommand();
Kevin Enderby1829c682016-01-22 22:49:55 +00002325 if (!SymtabLoadCmd || Index >= Symtab.nsyms)
Filipe Cabecinhas40139502015-01-15 22:52:38 +00002326 report_fatal_error("Requested symbol index is out of range.");
Lang Hames36072da2014-05-12 21:39:59 +00002327 unsigned SymbolTableEntrySize =
2328 is64Bit() ? sizeof(MachO::nlist_64) : sizeof(MachO::nlist);
Kevin Enderby1829c682016-01-22 22:49:55 +00002329 DataRefImpl DRI;
Lang Hames697e7cd2016-12-04 01:56:10 +00002330 DRI.p = reinterpret_cast<uintptr_t>(getPtr(*this, Symtab.symoff));
Lang Hames36072da2014-05-12 21:39:59 +00002331 DRI.p += Index * SymbolTableEntrySize;
2332 return basic_symbol_iterator(SymbolRef(DRI, this));
2333}
2334
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002335uint64_t MachOObjectFile::getSymbolIndex(DataRefImpl Symb) const {
2336 MachO::symtab_command Symtab = getSymtabLoadCommand();
2337 if (!SymtabLoadCmd)
2338 report_fatal_error("getSymbolIndex() called with no symbol table symbol");
2339 unsigned SymbolTableEntrySize =
2340 is64Bit() ? sizeof(MachO::nlist_64) : sizeof(MachO::nlist);
2341 DataRefImpl DRIstart;
Lang Hames697e7cd2016-12-04 01:56:10 +00002342 DRIstart.p = reinterpret_cast<uintptr_t>(getPtr(*this, Symtab.symoff));
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002343 uint64_t Index = (Symb.p - DRIstart.p) / SymbolTableEntrySize;
2344 return Index;
2345}
2346
Rafael Espindolab5155a52014-02-10 20:24:04 +00002347section_iterator MachOObjectFile::section_begin() const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00002348 DataRefImpl DRI;
2349 return section_iterator(SectionRef(DRI, this));
2350}
2351
Rafael Espindolab5155a52014-02-10 20:24:04 +00002352section_iterator MachOObjectFile::section_end() const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00002353 DataRefImpl DRI;
2354 DRI.d.a = Sections.size();
2355 return section_iterator(SectionRef(DRI, this));
2356}
2357
Rafael Espindola56f976f2013-04-18 18:08:55 +00002358uint8_t MachOObjectFile::getBytesInAddress() const {
Rafael Espindola60689982013-04-07 19:05:30 +00002359 return is64Bit() ? 8 : 4;
Eric Christopher7b015c72011-04-22 03:19:48 +00002360}
2361
Rafael Espindola56f976f2013-04-18 18:08:55 +00002362StringRef MachOObjectFile::getFileFormatName() const {
Lang Hames697e7cd2016-12-04 01:56:10 +00002363 unsigned CPUType = getCPUType(*this);
Rafael Espindola56f976f2013-04-18 18:08:55 +00002364 if (!is64Bit()) {
2365 switch (CPUType) {
Eugene Zelenko9f5094d2017-04-21 22:03:05 +00002366 case MachO::CPU_TYPE_I386:
Rafael Espindola56f976f2013-04-18 18:08:55 +00002367 return "Mach-O 32-bit i386";
Eugene Zelenko9f5094d2017-04-21 22:03:05 +00002368 case MachO::CPU_TYPE_ARM:
Rafael Espindola56f976f2013-04-18 18:08:55 +00002369 return "Mach-O arm";
Eugene Zelenko9f5094d2017-04-21 22:03:05 +00002370 case MachO::CPU_TYPE_POWERPC:
Rafael Espindola56f976f2013-04-18 18:08:55 +00002371 return "Mach-O 32-bit ppc";
2372 default:
Rafael Espindola56f976f2013-04-18 18:08:55 +00002373 return "Mach-O 32-bit unknown";
2374 }
2375 }
2376
Rafael Espindola56f976f2013-04-18 18:08:55 +00002377 switch (CPUType) {
Eugene Zelenko9f5094d2017-04-21 22:03:05 +00002378 case MachO::CPU_TYPE_X86_64:
Rafael Espindola56f976f2013-04-18 18:08:55 +00002379 return "Mach-O 64-bit x86-64";
Eugene Zelenko9f5094d2017-04-21 22:03:05 +00002380 case MachO::CPU_TYPE_ARM64:
Tim Northover00ed9962014-03-29 10:18:08 +00002381 return "Mach-O arm64";
Eugene Zelenko9f5094d2017-04-21 22:03:05 +00002382 case MachO::CPU_TYPE_POWERPC64:
Rafael Espindola56f976f2013-04-18 18:08:55 +00002383 return "Mach-O 64-bit ppc64";
2384 default:
2385 return "Mach-O 64-bit unknown";
2386 }
2387}
2388
Alexey Samsonove6388e62013-06-18 15:03:28 +00002389Triple::ArchType MachOObjectFile::getArch(uint32_t CPUType) {
2390 switch (CPUType) {
Eugene Zelenko9f5094d2017-04-21 22:03:05 +00002391 case MachO::CPU_TYPE_I386:
Rafael Espindola56f976f2013-04-18 18:08:55 +00002392 return Triple::x86;
Eugene Zelenko9f5094d2017-04-21 22:03:05 +00002393 case MachO::CPU_TYPE_X86_64:
Rafael Espindola56f976f2013-04-18 18:08:55 +00002394 return Triple::x86_64;
Eugene Zelenko9f5094d2017-04-21 22:03:05 +00002395 case MachO::CPU_TYPE_ARM:
Rafael Espindola56f976f2013-04-18 18:08:55 +00002396 return Triple::arm;
Eugene Zelenko9f5094d2017-04-21 22:03:05 +00002397 case MachO::CPU_TYPE_ARM64:
Tim Northovere19bed72014-07-23 12:32:47 +00002398 return Triple::aarch64;
Eugene Zelenko9f5094d2017-04-21 22:03:05 +00002399 case MachO::CPU_TYPE_POWERPC:
Rafael Espindola56f976f2013-04-18 18:08:55 +00002400 return Triple::ppc;
Eugene Zelenko9f5094d2017-04-21 22:03:05 +00002401 case MachO::CPU_TYPE_POWERPC64:
Rafael Espindola56f976f2013-04-18 18:08:55 +00002402 return Triple::ppc64;
2403 default:
2404 return Triple::UnknownArch;
2405 }
2406}
2407
Tim Northover9e8eb412016-04-22 23:21:13 +00002408Triple MachOObjectFile::getArchTriple(uint32_t CPUType, uint32_t CPUSubType,
Kevin Enderby59343a92016-12-16 22:54:02 +00002409 const char **McpuDefault,
2410 const char **ArchFlag) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00002411 if (McpuDefault)
2412 *McpuDefault = nullptr;
Kevin Enderby59343a92016-12-16 22:54:02 +00002413 if (ArchFlag)
2414 *ArchFlag = nullptr;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00002415
Kevin Enderby4c8dfe42014-06-30 18:45:23 +00002416 switch (CPUType) {
2417 case MachO::CPU_TYPE_I386:
2418 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2419 case MachO::CPU_SUBTYPE_I386_ALL:
Kevin Enderby59343a92016-12-16 22:54:02 +00002420 if (ArchFlag)
2421 *ArchFlag = "i386";
Kevin Enderby4c8dfe42014-06-30 18:45:23 +00002422 return Triple("i386-apple-darwin");
2423 default:
2424 return Triple();
2425 }
2426 case MachO::CPU_TYPE_X86_64:
2427 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2428 case MachO::CPU_SUBTYPE_X86_64_ALL:
Kevin Enderby59343a92016-12-16 22:54:02 +00002429 if (ArchFlag)
2430 *ArchFlag = "x86_64";
Kevin Enderby4c8dfe42014-06-30 18:45:23 +00002431 return Triple("x86_64-apple-darwin");
2432 case MachO::CPU_SUBTYPE_X86_64_H:
Kevin Enderby59343a92016-12-16 22:54:02 +00002433 if (ArchFlag)
2434 *ArchFlag = "x86_64h";
Kevin Enderby4c8dfe42014-06-30 18:45:23 +00002435 return Triple("x86_64h-apple-darwin");
2436 default:
2437 return Triple();
2438 }
2439 case MachO::CPU_TYPE_ARM:
2440 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2441 case MachO::CPU_SUBTYPE_ARM_V4T:
Kevin Enderby59343a92016-12-16 22:54:02 +00002442 if (ArchFlag)
2443 *ArchFlag = "armv4t";
Kevin Enderby4c8dfe42014-06-30 18:45:23 +00002444 return Triple("armv4t-apple-darwin");
2445 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
Kevin Enderby59343a92016-12-16 22:54:02 +00002446 if (ArchFlag)
2447 *ArchFlag = "armv5e";
Kevin Enderby4c8dfe42014-06-30 18:45:23 +00002448 return Triple("armv5e-apple-darwin");
Kevin Enderbyae2a9a22014-08-07 21:30:25 +00002449 case MachO::CPU_SUBTYPE_ARM_XSCALE:
Kevin Enderby59343a92016-12-16 22:54:02 +00002450 if (ArchFlag)
2451 *ArchFlag = "xscale";
Kevin Enderbyae2a9a22014-08-07 21:30:25 +00002452 return Triple("xscale-apple-darwin");
Kevin Enderby4c8dfe42014-06-30 18:45:23 +00002453 case MachO::CPU_SUBTYPE_ARM_V6:
Kevin Enderby59343a92016-12-16 22:54:02 +00002454 if (ArchFlag)
2455 *ArchFlag = "armv6";
Kevin Enderby4c8dfe42014-06-30 18:45:23 +00002456 return Triple("armv6-apple-darwin");
2457 case MachO::CPU_SUBTYPE_ARM_V6M:
Kevin Enderbyec5ca032014-08-18 20:21:02 +00002458 if (McpuDefault)
2459 *McpuDefault = "cortex-m0";
Kevin Enderby59343a92016-12-16 22:54:02 +00002460 if (ArchFlag)
2461 *ArchFlag = "armv6m";
Kevin Enderby4c8dfe42014-06-30 18:45:23 +00002462 return Triple("armv6m-apple-darwin");
Kevin Enderbyae2a9a22014-08-07 21:30:25 +00002463 case MachO::CPU_SUBTYPE_ARM_V7:
Kevin Enderby59343a92016-12-16 22:54:02 +00002464 if (ArchFlag)
2465 *ArchFlag = "armv7";
Kevin Enderbyae2a9a22014-08-07 21:30:25 +00002466 return Triple("armv7-apple-darwin");
Kevin Enderby4c8dfe42014-06-30 18:45:23 +00002467 case MachO::CPU_SUBTYPE_ARM_V7EM:
Kevin Enderbyec5ca032014-08-18 20:21:02 +00002468 if (McpuDefault)
2469 *McpuDefault = "cortex-m4";
Kevin Enderby59343a92016-12-16 22:54:02 +00002470 if (ArchFlag)
2471 *ArchFlag = "armv7em";
Tim Northover9e8eb412016-04-22 23:21:13 +00002472 return Triple("thumbv7em-apple-darwin");
Kevin Enderby4c8dfe42014-06-30 18:45:23 +00002473 case MachO::CPU_SUBTYPE_ARM_V7K:
Kevin Enderby7a165752017-01-24 23:41:04 +00002474 if (McpuDefault)
2475 *McpuDefault = "cortex-a7";
Kevin Enderby59343a92016-12-16 22:54:02 +00002476 if (ArchFlag)
2477 *ArchFlag = "armv7k";
Kevin Enderby4c8dfe42014-06-30 18:45:23 +00002478 return Triple("armv7k-apple-darwin");
2479 case MachO::CPU_SUBTYPE_ARM_V7M:
Kevin Enderbyec5ca032014-08-18 20:21:02 +00002480 if (McpuDefault)
2481 *McpuDefault = "cortex-m3";
Kevin Enderby59343a92016-12-16 22:54:02 +00002482 if (ArchFlag)
2483 *ArchFlag = "armv7m";
Tim Northover9e8eb412016-04-22 23:21:13 +00002484 return Triple("thumbv7m-apple-darwin");
Kevin Enderby4c8dfe42014-06-30 18:45:23 +00002485 case MachO::CPU_SUBTYPE_ARM_V7S:
Kevin Enderby7a165752017-01-24 23:41:04 +00002486 if (McpuDefault)
2487 *McpuDefault = "cortex-a7";
Kevin Enderby59343a92016-12-16 22:54:02 +00002488 if (ArchFlag)
2489 *ArchFlag = "armv7s";
Kevin Enderby4c8dfe42014-06-30 18:45:23 +00002490 return Triple("armv7s-apple-darwin");
2491 default:
2492 return Triple();
2493 }
2494 case MachO::CPU_TYPE_ARM64:
2495 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2496 case MachO::CPU_SUBTYPE_ARM64_ALL:
Kevin Enderbydc412cc2017-02-10 19:27:10 +00002497 if (McpuDefault)
2498 *McpuDefault = "cyclone";
Kevin Enderby59343a92016-12-16 22:54:02 +00002499 if (ArchFlag)
2500 *ArchFlag = "arm64";
Kevin Enderby4c8dfe42014-06-30 18:45:23 +00002501 return Triple("arm64-apple-darwin");
2502 default:
2503 return Triple();
2504 }
2505 case MachO::CPU_TYPE_POWERPC:
2506 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2507 case MachO::CPU_SUBTYPE_POWERPC_ALL:
Kevin Enderby59343a92016-12-16 22:54:02 +00002508 if (ArchFlag)
2509 *ArchFlag = "ppc";
Kevin Enderby4c8dfe42014-06-30 18:45:23 +00002510 return Triple("ppc-apple-darwin");
2511 default:
2512 return Triple();
2513 }
2514 case MachO::CPU_TYPE_POWERPC64:
Reid Kleckner4da3d572014-06-30 20:12:59 +00002515 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
Kevin Enderby4c8dfe42014-06-30 18:45:23 +00002516 case MachO::CPU_SUBTYPE_POWERPC_ALL:
Kevin Enderby59343a92016-12-16 22:54:02 +00002517 if (ArchFlag)
2518 *ArchFlag = "ppc64";
Kevin Enderby4c8dfe42014-06-30 18:45:23 +00002519 return Triple("ppc64-apple-darwin");
Kevin Enderby4c8dfe42014-06-30 18:45:23 +00002520 default:
2521 return Triple();
2522 }
2523 default:
2524 return Triple();
2525 }
2526}
2527
2528Triple MachOObjectFile::getHostArch() {
2529 return Triple(sys::getDefaultTargetTriple());
2530}
2531
Rafael Espindola72318b42014-08-08 16:30:17 +00002532bool MachOObjectFile::isValidArch(StringRef ArchFlag) {
2533 return StringSwitch<bool>(ArchFlag)
2534 .Case("i386", true)
2535 .Case("x86_64", true)
2536 .Case("x86_64h", true)
2537 .Case("armv4t", true)
2538 .Case("arm", true)
2539 .Case("armv5e", true)
2540 .Case("armv6", true)
2541 .Case("armv6m", true)
Frederic Riss40baa0a2015-06-16 17:37:03 +00002542 .Case("armv7", true)
Rafael Espindola72318b42014-08-08 16:30:17 +00002543 .Case("armv7em", true)
2544 .Case("armv7k", true)
2545 .Case("armv7m", true)
2546 .Case("armv7s", true)
2547 .Case("arm64", true)
2548 .Case("ppc", true)
2549 .Case("ppc64", true)
2550 .Default(false);
Kevin Enderby4c8dfe42014-06-30 18:45:23 +00002551}
2552
Alexey Samsonove6388e62013-06-18 15:03:28 +00002553unsigned MachOObjectFile::getArch() const {
Lang Hames697e7cd2016-12-04 01:56:10 +00002554 return getArch(getCPUType(*this));
Alexey Samsonove6388e62013-06-18 15:03:28 +00002555}
2556
Tim Northover9e8eb412016-04-22 23:21:13 +00002557Triple MachOObjectFile::getArchTriple(const char **McpuDefault) const {
2558 return getArchTriple(Header.cputype, Header.cpusubtype, McpuDefault);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00002559}
2560
Rui Ueyamabc654b12013-09-27 21:47:05 +00002561relocation_iterator MachOObjectFile::section_rel_begin(unsigned Index) const {
Rafael Espindola6e040c02013-04-26 20:07:33 +00002562 DataRefImpl DRI;
2563 DRI.d.a = Index;
Rui Ueyamabc654b12013-09-27 21:47:05 +00002564 return section_rel_begin(DRI);
Rafael Espindola6e040c02013-04-26 20:07:33 +00002565}
2566
Rui Ueyamabc654b12013-09-27 21:47:05 +00002567relocation_iterator MachOObjectFile::section_rel_end(unsigned Index) const {
Rafael Espindola6e040c02013-04-26 20:07:33 +00002568 DataRefImpl DRI;
2569 DRI.d.a = Index;
Rui Ueyamabc654b12013-09-27 21:47:05 +00002570 return section_rel_end(DRI);
Rafael Espindola6e040c02013-04-26 20:07:33 +00002571}
2572
Kevin Enderby273ae012013-06-06 17:20:50 +00002573dice_iterator MachOObjectFile::begin_dices() const {
2574 DataRefImpl DRI;
2575 if (!DataInCodeLoadCmd)
2576 return dice_iterator(DiceRef(DRI, this));
2577
Charles Davis8bdfafd2013-09-01 04:28:48 +00002578 MachO::linkedit_data_command DicLC = getDataInCodeLoadCommand();
Lang Hames697e7cd2016-12-04 01:56:10 +00002579 DRI.p = reinterpret_cast<uintptr_t>(getPtr(*this, DicLC.dataoff));
Kevin Enderby273ae012013-06-06 17:20:50 +00002580 return dice_iterator(DiceRef(DRI, this));
2581}
2582
2583dice_iterator MachOObjectFile::end_dices() const {
2584 DataRefImpl DRI;
2585 if (!DataInCodeLoadCmd)
2586 return dice_iterator(DiceRef(DRI, this));
2587
Charles Davis8bdfafd2013-09-01 04:28:48 +00002588 MachO::linkedit_data_command DicLC = getDataInCodeLoadCommand();
2589 unsigned Offset = DicLC.dataoff + DicLC.datasize;
Lang Hames697e7cd2016-12-04 01:56:10 +00002590 DRI.p = reinterpret_cast<uintptr_t>(getPtr(*this, Offset));
Kevin Enderby273ae012013-06-06 17:20:50 +00002591 return dice_iterator(DiceRef(DRI, this));
2592}
2593
Eugene Zelenko9f5094d2017-04-21 22:03:05 +00002594ExportEntry::ExportEntry(ArrayRef<uint8_t> T) : Trie(T) {}
Nick Kledzikd04bc352014-08-30 00:20:14 +00002595
2596void ExportEntry::moveToFirst() {
2597 pushNode(0);
2598 pushDownUntilBottom();
2599}
2600
2601void ExportEntry::moveToEnd() {
2602 Stack.clear();
2603 Done = true;
2604}
2605
2606bool ExportEntry::operator==(const ExportEntry &Other) const {
NAKAMURA Takumi84965032015-09-22 11:14:12 +00002607 // Common case, one at end, other iterating from begin.
Nick Kledzikd04bc352014-08-30 00:20:14 +00002608 if (Done || Other.Done)
2609 return (Done == Other.Done);
2610 // Not equal if different stack sizes.
2611 if (Stack.size() != Other.Stack.size())
2612 return false;
2613 // Not equal if different cumulative strings.
Yaron Keren075759a2015-03-30 15:42:36 +00002614 if (!CumulativeString.equals(Other.CumulativeString))
Nick Kledzikd04bc352014-08-30 00:20:14 +00002615 return false;
2616 // Equal if all nodes in both stacks match.
2617 for (unsigned i=0; i < Stack.size(); ++i) {
2618 if (Stack[i].Start != Other.Stack[i].Start)
2619 return false;
2620 }
NAKAMURA Takumi10c80e72015-09-22 11:19:03 +00002621 return true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00002622}
2623
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00002624uint64_t ExportEntry::readULEB128(const uint8_t *&Ptr) {
2625 unsigned Count;
2626 uint64_t Result = decodeULEB128(Ptr, &Count);
2627 Ptr += Count;
2628 if (Ptr > Trie.end()) {
2629 Ptr = Trie.end();
Nick Kledzikd04bc352014-08-30 00:20:14 +00002630 Malformed = true;
2631 }
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00002632 return Result;
Nick Kledzikd04bc352014-08-30 00:20:14 +00002633}
2634
2635StringRef ExportEntry::name() const {
Yaron Keren075759a2015-03-30 15:42:36 +00002636 return CumulativeString;
Nick Kledzikd04bc352014-08-30 00:20:14 +00002637}
2638
2639uint64_t ExportEntry::flags() const {
2640 return Stack.back().Flags;
2641}
2642
2643uint64_t ExportEntry::address() const {
2644 return Stack.back().Address;
2645}
2646
2647uint64_t ExportEntry::other() const {
2648 return Stack.back().Other;
2649}
2650
2651StringRef ExportEntry::otherName() const {
2652 const char* ImportName = Stack.back().ImportName;
2653 if (ImportName)
2654 return StringRef(ImportName);
2655 return StringRef();
2656}
2657
2658uint32_t ExportEntry::nodeOffset() const {
2659 return Stack.back().Start - Trie.begin();
2660}
2661
NAKAMURA Takumi70ad98a2015-09-22 11:13:55 +00002662ExportEntry::NodeState::NodeState(const uint8_t *Ptr)
Eugene Zelenko9f5094d2017-04-21 22:03:05 +00002663 : Start(Ptr), Current(Ptr) {}
Nick Kledzikd04bc352014-08-30 00:20:14 +00002664
2665void ExportEntry::pushNode(uint64_t offset) {
2666 const uint8_t *Ptr = Trie.begin() + offset;
2667 NodeState State(Ptr);
2668 uint64_t ExportInfoSize = readULEB128(State.Current);
2669 State.IsExportNode = (ExportInfoSize != 0);
2670 const uint8_t* Children = State.Current + ExportInfoSize;
2671 if (State.IsExportNode) {
2672 State.Flags = readULEB128(State.Current);
2673 if (State.Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT) {
2674 State.Address = 0;
2675 State.Other = readULEB128(State.Current); // dylib ordinal
2676 State.ImportName = reinterpret_cast<const char*>(State.Current);
2677 } else {
2678 State.Address = readULEB128(State.Current);
Nick Kledzik1b591bd2014-08-30 01:57:34 +00002679 if (State.Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER)
NAKAMURA Takumi10c80e72015-09-22 11:19:03 +00002680 State.Other = readULEB128(State.Current);
Nick Kledzikd04bc352014-08-30 00:20:14 +00002681 }
2682 }
2683 State.ChildCount = *Children;
2684 State.Current = Children + 1;
2685 State.NextChildIndex = 0;
2686 State.ParentStringLength = CumulativeString.size();
2687 Stack.push_back(State);
2688}
2689
2690void ExportEntry::pushDownUntilBottom() {
2691 while (Stack.back().NextChildIndex < Stack.back().ChildCount) {
2692 NodeState &Top = Stack.back();
2693 CumulativeString.resize(Top.ParentStringLength);
2694 for (;*Top.Current != 0; Top.Current++) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00002695 char C = *Top.Current;
2696 CumulativeString.push_back(C);
Nick Kledzikd04bc352014-08-30 00:20:14 +00002697 }
2698 Top.Current += 1;
2699 uint64_t childNodeIndex = readULEB128(Top.Current);
2700 Top.NextChildIndex += 1;
2701 pushNode(childNodeIndex);
2702 }
2703 if (!Stack.back().IsExportNode) {
2704 Malformed = true;
2705 moveToEnd();
2706 }
2707}
2708
2709// We have a trie data structure and need a way to walk it that is compatible
2710// with the C++ iterator model. The solution is a non-recursive depth first
2711// traversal where the iterator contains a stack of parent nodes along with a
2712// string that is the accumulation of all edge strings along the parent chain
2713// to this point.
2714//
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00002715// There is one "export" node for each exported symbol. But because some
Nick Kledzikd04bc352014-08-30 00:20:14 +00002716// symbols may be a prefix of another symbol (e.g. _dup and _dup2), an export
NAKAMURA Takumi84965032015-09-22 11:14:12 +00002717// node may have child nodes too.
Nick Kledzikd04bc352014-08-30 00:20:14 +00002718//
2719// The algorithm for moveNext() is to keep moving down the leftmost unvisited
2720// child until hitting a node with no children (which is an export node or
2721// else the trie is malformed). On the way down, each node is pushed on the
2722// stack ivar. If there is no more ways down, it pops up one and tries to go
2723// down a sibling path until a childless node is reached.
2724void ExportEntry::moveNext() {
2725 if (Stack.empty() || !Stack.back().IsExportNode) {
2726 Malformed = true;
2727 moveToEnd();
2728 return;
2729 }
2730
2731 Stack.pop_back();
2732 while (!Stack.empty()) {
2733 NodeState &Top = Stack.back();
2734 if (Top.NextChildIndex < Top.ChildCount) {
2735 pushDownUntilBottom();
2736 // Now at the next export node.
2737 return;
2738 } else {
2739 if (Top.IsExportNode) {
2740 // This node has no children but is itself an export node.
2741 CumulativeString.resize(Top.ParentStringLength);
2742 return;
2743 }
2744 Stack.pop_back();
2745 }
2746 }
2747 Done = true;
2748}
2749
NAKAMURA Takumi10c80e72015-09-22 11:19:03 +00002750iterator_range<export_iterator>
Nick Kledzikd04bc352014-08-30 00:20:14 +00002751MachOObjectFile::exports(ArrayRef<uint8_t> Trie) {
2752 ExportEntry Start(Trie);
Eugene Zelenko9f5094d2017-04-21 22:03:05 +00002753 if (Trie.empty())
Juergen Ributzka4d7f70d2014-12-19 02:31:01 +00002754 Start.moveToEnd();
2755 else
2756 Start.moveToFirst();
Nick Kledzikd04bc352014-08-30 00:20:14 +00002757
2758 ExportEntry Finish(Trie);
2759 Finish.moveToEnd();
2760
Craig Topper15576e12015-12-06 05:08:07 +00002761 return make_range(export_iterator(Start), export_iterator(Finish));
Nick Kledzikd04bc352014-08-30 00:20:14 +00002762}
2763
2764iterator_range<export_iterator> MachOObjectFile::exports() const {
2765 return exports(getDyldInfoExportsTrie());
2766}
2767
Kevin Enderbya8d256c2017-03-20 19:46:55 +00002768MachORebaseEntry::MachORebaseEntry(Error *E, const MachOObjectFile *O,
2769 ArrayRef<uint8_t> Bytes, bool is64Bit)
Eugene Zelenko9f5094d2017-04-21 22:03:05 +00002770 : E(E), O(O), Opcodes(Bytes), Ptr(Bytes.begin()),
2771 PointerSize(is64Bit ? 8 : 4) {}
Nick Kledzikac431442014-09-12 21:34:15 +00002772
2773void MachORebaseEntry::moveToFirst() {
2774 Ptr = Opcodes.begin();
2775 moveNext();
2776}
2777
2778void MachORebaseEntry::moveToEnd() {
2779 Ptr = Opcodes.end();
2780 RemainingLoopCount = 0;
2781 Done = true;
2782}
2783
2784void MachORebaseEntry::moveNext() {
Kevin Enderby6c1d2b42017-03-27 20:09:23 +00002785 ErrorAsOutParameter ErrAsOutParam(E);
Nick Kledzikac431442014-09-12 21:34:15 +00002786 // If in the middle of some loop, move to next rebasing in loop.
2787 SegmentOffset += AdvanceAmount;
2788 if (RemainingLoopCount) {
2789 --RemainingLoopCount;
2790 return;
2791 }
Juergen Ributzkacad12492017-03-30 19:56:50 +00002792 // REBASE_OPCODE_DONE is only used for padding if we are not aligned to
2793 // pointer size. Therefore it is possible to reach the end without ever having
2794 // seen REBASE_OPCODE_DONE.
2795 if (Ptr == Opcodes.end()) {
Nick Kledzikac431442014-09-12 21:34:15 +00002796 Done = true;
2797 return;
2798 }
2799 bool More = true;
Kevin Enderby6c1d2b42017-03-27 20:09:23 +00002800 while (More) {
Nick Kledzikac431442014-09-12 21:34:15 +00002801 // Parse next opcode and set up next loop.
Kevin Enderby6c1d2b42017-03-27 20:09:23 +00002802 const uint8_t *OpcodeStart = Ptr;
Nick Kledzikac431442014-09-12 21:34:15 +00002803 uint8_t Byte = *Ptr++;
2804 uint8_t ImmValue = Byte & MachO::REBASE_IMMEDIATE_MASK;
2805 uint8_t Opcode = Byte & MachO::REBASE_OPCODE_MASK;
Kevin Enderby6c1d2b42017-03-27 20:09:23 +00002806 uint32_t Count, Skip;
2807 const char *error = nullptr;
Nick Kledzikac431442014-09-12 21:34:15 +00002808 switch (Opcode) {
2809 case MachO::REBASE_OPCODE_DONE:
2810 More = false;
2811 Done = true;
2812 moveToEnd();
Eugene Zelenko9f5094d2017-04-21 22:03:05 +00002813 DEBUG_WITH_TYPE("mach-o-rebase", dbgs() << "REBASE_OPCODE_DONE\n");
Nick Kledzikac431442014-09-12 21:34:15 +00002814 break;
2815 case MachO::REBASE_OPCODE_SET_TYPE_IMM:
2816 RebaseType = ImmValue;
Kevin Enderby6c1d2b42017-03-27 20:09:23 +00002817 if (RebaseType > MachO::REBASE_TYPE_TEXT_PCREL32) {
2818 *E = malformedError("for REBASE_OPCODE_SET_TYPE_IMM bad bind type: " +
2819 Twine((int)RebaseType) + " for opcode at: 0x" +
2820 utohexstr(OpcodeStart - Opcodes.begin()));
2821 moveToEnd();
2822 return;
2823 }
Nick Kledzikac431442014-09-12 21:34:15 +00002824 DEBUG_WITH_TYPE(
2825 "mach-o-rebase",
Eugene Zelenko9f5094d2017-04-21 22:03:05 +00002826 dbgs() << "REBASE_OPCODE_SET_TYPE_IMM: "
2827 << "RebaseType=" << (int) RebaseType << "\n");
Nick Kledzikac431442014-09-12 21:34:15 +00002828 break;
2829 case MachO::REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:
2830 SegmentIndex = ImmValue;
Kevin Enderby6c1d2b42017-03-27 20:09:23 +00002831 SegmentOffset = readULEB128(&error);
2832 if (error) {
2833 *E = malformedError("for REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB " +
2834 Twine(error) + " for opcode at: 0x" +
2835 utohexstr(OpcodeStart - Opcodes.begin()));
2836 moveToEnd();
2837 return;
2838 }
2839 error = O->RebaseEntryCheckSegAndOffset(SegmentIndex, SegmentOffset,
2840 true);
2841 if (error) {
2842 *E = malformedError("for REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB " +
2843 Twine(error) + " for opcode at: 0x" +
2844 utohexstr(OpcodeStart - Opcodes.begin()));
2845 moveToEnd();
2846 return;
2847 }
Nick Kledzikac431442014-09-12 21:34:15 +00002848 DEBUG_WITH_TYPE(
2849 "mach-o-rebase",
Eugene Zelenko9f5094d2017-04-21 22:03:05 +00002850 dbgs() << "REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: "
2851 << "SegmentIndex=" << SegmentIndex << ", "
2852 << format("SegmentOffset=0x%06X", SegmentOffset)
2853 << "\n");
Nick Kledzikac431442014-09-12 21:34:15 +00002854 break;
2855 case MachO::REBASE_OPCODE_ADD_ADDR_ULEB:
Kevin Enderby6c1d2b42017-03-27 20:09:23 +00002856 SegmentOffset += readULEB128(&error);
2857 if (error) {
2858 *E = malformedError("for REBASE_OPCODE_ADD_ADDR_ULEB " +
2859 Twine(error) + " for opcode at: 0x" +
2860 utohexstr(OpcodeStart - Opcodes.begin()));
2861 moveToEnd();
2862 return;
2863 }
2864 error = O->RebaseEntryCheckSegAndOffset(SegmentIndex, SegmentOffset,
2865 true);
2866 if (error) {
2867 *E = malformedError("for REBASE_OPCODE_ADD_ADDR_ULEB " +
2868 Twine(error) + " for opcode at: 0x" +
2869 utohexstr(OpcodeStart - Opcodes.begin()));
2870 moveToEnd();
2871 return;
2872 }
Nick Kledzikac431442014-09-12 21:34:15 +00002873 DEBUG_WITH_TYPE("mach-o-rebase",
Eugene Zelenko9f5094d2017-04-21 22:03:05 +00002874 dbgs() << "REBASE_OPCODE_ADD_ADDR_ULEB: "
2875 << format("SegmentOffset=0x%06X",
2876 SegmentOffset) << "\n");
Nick Kledzikac431442014-09-12 21:34:15 +00002877 break;
2878 case MachO::REBASE_OPCODE_ADD_ADDR_IMM_SCALED:
Kevin Enderby6c1d2b42017-03-27 20:09:23 +00002879 error = O->RebaseEntryCheckSegAndOffset(SegmentIndex, SegmentOffset,
2880 true);
2881 if (error) {
2882 *E = malformedError("for REBASE_OPCODE_ADD_ADDR_IMM_SCALED " +
2883 Twine(error) + " for opcode at: 0x" +
2884 utohexstr(OpcodeStart - Opcodes.begin()));
2885 moveToEnd();
2886 return;
2887 }
Nick Kledzikac431442014-09-12 21:34:15 +00002888 SegmentOffset += ImmValue * PointerSize;
Kevin Enderby6c1d2b42017-03-27 20:09:23 +00002889 error = O->RebaseEntryCheckSegAndOffset(SegmentIndex, SegmentOffset,
2890 false);
2891 if (error) {
2892 *E = malformedError("for REBASE_OPCODE_ADD_ADDR_IMM_SCALED "
2893 " (after adding immediate times the pointer size) " +
2894 Twine(error) + " for opcode at: 0x" +
2895 utohexstr(OpcodeStart - Opcodes.begin()));
2896 moveToEnd();
2897 return;
2898 }
Nick Kledzikac431442014-09-12 21:34:15 +00002899 DEBUG_WITH_TYPE("mach-o-rebase",
Eugene Zelenko9f5094d2017-04-21 22:03:05 +00002900 dbgs() << "REBASE_OPCODE_ADD_ADDR_IMM_SCALED: "
2901 << format("SegmentOffset=0x%06X",
2902 SegmentOffset) << "\n");
Nick Kledzikac431442014-09-12 21:34:15 +00002903 break;
2904 case MachO::REBASE_OPCODE_DO_REBASE_IMM_TIMES:
Kevin Enderby6c1d2b42017-03-27 20:09:23 +00002905 error = O->RebaseEntryCheckSegAndOffset(SegmentIndex, SegmentOffset,
2906 true);
2907 if (error) {
2908 *E = malformedError("for REBASE_OPCODE_DO_REBASE_IMM_TIMES " +
2909 Twine(error) + " for opcode at: 0x" +
2910 utohexstr(OpcodeStart - Opcodes.begin()));
2911 moveToEnd();
2912 return;
2913 }
Nick Kledzikac431442014-09-12 21:34:15 +00002914 AdvanceAmount = PointerSize;
Kevin Enderby6c1d2b42017-03-27 20:09:23 +00002915 Skip = 0;
2916 Count = ImmValue;
2917 if (ImmValue != 0)
2918 RemainingLoopCount = ImmValue - 1;
2919 else
2920 RemainingLoopCount = 0;
2921 error = O->RebaseEntryCheckCountAndSkip(Count, Skip, PointerSize,
2922 SegmentIndex, SegmentOffset);
2923 if (error) {
2924 *E = malformedError("for REBASE_OPCODE_DO_REBASE_IMM_TIMES "
2925 + Twine(error) + " for opcode at: 0x" +
2926 utohexstr(OpcodeStart - Opcodes.begin()));
2927 moveToEnd();
2928 return;
2929 }
Nick Kledzikac431442014-09-12 21:34:15 +00002930 DEBUG_WITH_TYPE(
2931 "mach-o-rebase",
Eugene Zelenko9f5094d2017-04-21 22:03:05 +00002932 dbgs() << "REBASE_OPCODE_DO_REBASE_IMM_TIMES: "
2933 << format("SegmentOffset=0x%06X", SegmentOffset)
2934 << ", AdvanceAmount=" << AdvanceAmount
2935 << ", RemainingLoopCount=" << RemainingLoopCount
2936 << "\n");
Nick Kledzikac431442014-09-12 21:34:15 +00002937 return;
2938 case MachO::REBASE_OPCODE_DO_REBASE_ULEB_TIMES:
Kevin Enderby6c1d2b42017-03-27 20:09:23 +00002939 error = O->RebaseEntryCheckSegAndOffset(SegmentIndex, SegmentOffset,
2940 true);
2941 if (error) {
2942 *E = malformedError("for REBASE_OPCODE_DO_REBASE_ULEB_TIMES " +
2943 Twine(error) + " for opcode at: 0x" +
2944 utohexstr(OpcodeStart - Opcodes.begin()));
2945 moveToEnd();
2946 return;
2947 }
Nick Kledzikac431442014-09-12 21:34:15 +00002948 AdvanceAmount = PointerSize;
Kevin Enderby6c1d2b42017-03-27 20:09:23 +00002949 Skip = 0;
2950 Count = readULEB128(&error);
2951 if (error) {
2952 *E = malformedError("for REBASE_OPCODE_DO_REBASE_ULEB_TIMES " +
2953 Twine(error) + " for opcode at: 0x" +
2954 utohexstr(OpcodeStart - Opcodes.begin()));
2955 moveToEnd();
2956 return;
2957 }
2958 if (Count != 0)
2959 RemainingLoopCount = Count - 1;
2960 else
2961 RemainingLoopCount = 0;
2962 error = O->RebaseEntryCheckCountAndSkip(Count, Skip, PointerSize,
2963 SegmentIndex, SegmentOffset);
2964 if (error) {
2965 *E = malformedError("for REBASE_OPCODE_DO_REBASE_ULEB_TIMES "
2966 + Twine(error) + " for opcode at: 0x" +
2967 utohexstr(OpcodeStart - Opcodes.begin()));
2968 moveToEnd();
2969 return;
2970 }
Nick Kledzikac431442014-09-12 21:34:15 +00002971 DEBUG_WITH_TYPE(
2972 "mach-o-rebase",
Eugene Zelenko9f5094d2017-04-21 22:03:05 +00002973 dbgs() << "REBASE_OPCODE_DO_REBASE_ULEB_TIMES: "
2974 << format("SegmentOffset=0x%06X", SegmentOffset)
2975 << ", AdvanceAmount=" << AdvanceAmount
2976 << ", RemainingLoopCount=" << RemainingLoopCount
2977 << "\n");
Nick Kledzikac431442014-09-12 21:34:15 +00002978 return;
2979 case MachO::REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB:
Kevin Enderby6c1d2b42017-03-27 20:09:23 +00002980 error = O->RebaseEntryCheckSegAndOffset(SegmentIndex, SegmentOffset,
2981 true);
2982 if (error) {
2983 *E = malformedError("for REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB " +
2984 Twine(error) + " for opcode at: 0x" +
2985 utohexstr(OpcodeStart - Opcodes.begin()));
2986 moveToEnd();
2987 return;
2988 }
2989 Skip = readULEB128(&error);
2990 if (error) {
2991 *E = malformedError("for REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB " +
2992 Twine(error) + " for opcode at: 0x" +
2993 utohexstr(OpcodeStart - Opcodes.begin()));
2994 moveToEnd();
2995 return;
2996 }
2997 AdvanceAmount = Skip + PointerSize;
2998 Count = 1;
Nick Kledzikac431442014-09-12 21:34:15 +00002999 RemainingLoopCount = 0;
Kevin Enderby6c1d2b42017-03-27 20:09:23 +00003000 error = O->RebaseEntryCheckCountAndSkip(Count, Skip, PointerSize,
3001 SegmentIndex, SegmentOffset);
3002 if (error) {
3003 *E = malformedError("for REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB "
3004 + Twine(error) + " for opcode at: 0x" +
3005 utohexstr(OpcodeStart - Opcodes.begin()));
3006 moveToEnd();
3007 return;
3008 }
Nick Kledzikac431442014-09-12 21:34:15 +00003009 DEBUG_WITH_TYPE(
3010 "mach-o-rebase",
Eugene Zelenko9f5094d2017-04-21 22:03:05 +00003011 dbgs() << "REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB: "
3012 << format("SegmentOffset=0x%06X", SegmentOffset)
3013 << ", AdvanceAmount=" << AdvanceAmount
3014 << ", RemainingLoopCount=" << RemainingLoopCount
3015 << "\n");
Nick Kledzikac431442014-09-12 21:34:15 +00003016 return;
3017 case MachO::REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB:
Kevin Enderby6c1d2b42017-03-27 20:09:23 +00003018 error = O->RebaseEntryCheckSegAndOffset(SegmentIndex, SegmentOffset,
3019 true);
3020 if (error) {
3021 *E = malformedError("for REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_"
3022 "ULEB " + Twine(error) + " for opcode at: 0x" +
3023 utohexstr(OpcodeStart - Opcodes.begin()));
3024 moveToEnd();
3025 return;
3026 }
3027 Count = readULEB128(&error);
3028 if (error) {
3029 *E = malformedError("for REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_"
3030 "ULEB " + Twine(error) + " for opcode at: 0x" +
3031 utohexstr(OpcodeStart - Opcodes.begin()));
3032 moveToEnd();
3033 return;
3034 }
3035 if (Count != 0)
3036 RemainingLoopCount = Count - 1;
3037 else
3038 RemainingLoopCount = 0;
3039 Skip = readULEB128(&error);
3040 if (error) {
3041 *E = malformedError("for REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_"
3042 "ULEB " + Twine(error) + " for opcode at: 0x" +
3043 utohexstr(OpcodeStart - Opcodes.begin()));
3044 moveToEnd();
3045 return;
3046 }
3047 AdvanceAmount = Skip + PointerSize;
3048
3049 error = O->RebaseEntryCheckCountAndSkip(Count, Skip, PointerSize,
3050 SegmentIndex, SegmentOffset);
3051 if (error) {
3052 *E = malformedError("for REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_"
3053 "ULEB " + Twine(error) + " for opcode at: 0x" +
3054 utohexstr(OpcodeStart - Opcodes.begin()));
3055 moveToEnd();
3056 return;
3057 }
Nick Kledzikac431442014-09-12 21:34:15 +00003058 DEBUG_WITH_TYPE(
3059 "mach-o-rebase",
Eugene Zelenko9f5094d2017-04-21 22:03:05 +00003060 dbgs() << "REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB: "
3061 << format("SegmentOffset=0x%06X", SegmentOffset)
3062 << ", AdvanceAmount=" << AdvanceAmount
3063 << ", RemainingLoopCount=" << RemainingLoopCount
3064 << "\n");
Nick Kledzikac431442014-09-12 21:34:15 +00003065 return;
3066 default:
Kevin Enderby6c1d2b42017-03-27 20:09:23 +00003067 *E = malformedError("bad rebase info (bad opcode value 0x" +
3068 utohexstr(Opcode) + " for opcode at: 0x" +
3069 utohexstr(OpcodeStart - Opcodes.begin()));
3070 moveToEnd();
3071 return;
Nick Kledzikac431442014-09-12 21:34:15 +00003072 }
3073 }
3074}
3075
Kevin Enderby6c1d2b42017-03-27 20:09:23 +00003076uint64_t MachORebaseEntry::readULEB128(const char **error) {
Nick Kledzikac431442014-09-12 21:34:15 +00003077 unsigned Count;
Kevin Enderby6c1d2b42017-03-27 20:09:23 +00003078 uint64_t Result = decodeULEB128(Ptr, &Count, Opcodes.end(), error);
Nick Kledzikac431442014-09-12 21:34:15 +00003079 Ptr += Count;
Kevin Enderby6c1d2b42017-03-27 20:09:23 +00003080 if (Ptr > Opcodes.end())
Nick Kledzikac431442014-09-12 21:34:15 +00003081 Ptr = Opcodes.end();
Nick Kledzikac431442014-09-12 21:34:15 +00003082 return Result;
3083}
3084
Kevin Enderby6c1d2b42017-03-27 20:09:23 +00003085int32_t MachORebaseEntry::segmentIndex() const { return SegmentIndex; }
Nick Kledzikac431442014-09-12 21:34:15 +00003086
3087uint64_t MachORebaseEntry::segmentOffset() const { return SegmentOffset; }
3088
3089StringRef MachORebaseEntry::typeName() const {
3090 switch (RebaseType) {
3091 case MachO::REBASE_TYPE_POINTER:
3092 return "pointer";
3093 case MachO::REBASE_TYPE_TEXT_ABSOLUTE32:
3094 return "text abs32";
3095 case MachO::REBASE_TYPE_TEXT_PCREL32:
3096 return "text rel32";
3097 }
3098 return "unknown";
3099}
3100
Kevin Enderbya8d256c2017-03-20 19:46:55 +00003101// For use with the SegIndex of a checked Mach-O Rebase entry
3102// to get the segment name.
3103StringRef MachORebaseEntry::segmentName() const {
3104 return O->BindRebaseSegmentName(SegmentIndex);
3105}
3106
3107// For use with a SegIndex,SegOffset pair from a checked Mach-O Rebase entry
3108// to get the section name.
3109StringRef MachORebaseEntry::sectionName() const {
3110 return O->BindRebaseSectionName(SegmentIndex, SegmentOffset);
3111}
3112
3113// For use with a SegIndex,SegOffset pair from a checked Mach-O Rebase entry
3114// to get the address.
3115uint64_t MachORebaseEntry::address() const {
3116 return O->BindRebaseAddress(SegmentIndex, SegmentOffset);
3117}
3118
Nick Kledzikac431442014-09-12 21:34:15 +00003119bool MachORebaseEntry::operator==(const MachORebaseEntry &Other) const {
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +00003120#ifdef EXPENSIVE_CHECKS
Nick Kledzikac431442014-09-12 21:34:15 +00003121 assert(Opcodes == Other.Opcodes && "compare iterators of different files");
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +00003122#else
3123 assert(Opcodes.data() == Other.Opcodes.data() && "compare iterators of different files");
3124#endif
Nick Kledzikac431442014-09-12 21:34:15 +00003125 return (Ptr == Other.Ptr) &&
3126 (RemainingLoopCount == Other.RemainingLoopCount) &&
3127 (Done == Other.Done);
3128}
3129
3130iterator_range<rebase_iterator>
Kevin Enderbya8d256c2017-03-20 19:46:55 +00003131MachOObjectFile::rebaseTable(Error &Err, MachOObjectFile *O,
3132 ArrayRef<uint8_t> Opcodes, bool is64) {
3133 if (O->BindRebaseSectionTable == nullptr)
3134 O->BindRebaseSectionTable = llvm::make_unique<BindRebaseSegInfo>(O);
3135 MachORebaseEntry Start(&Err, O, Opcodes, is64);
Nick Kledzikac431442014-09-12 21:34:15 +00003136 Start.moveToFirst();
3137
Kevin Enderbya8d256c2017-03-20 19:46:55 +00003138 MachORebaseEntry Finish(&Err, O, Opcodes, is64);
Nick Kledzikac431442014-09-12 21:34:15 +00003139 Finish.moveToEnd();
3140
Craig Topper15576e12015-12-06 05:08:07 +00003141 return make_range(rebase_iterator(Start), rebase_iterator(Finish));
Nick Kledzikac431442014-09-12 21:34:15 +00003142}
3143
Kevin Enderbya8d256c2017-03-20 19:46:55 +00003144iterator_range<rebase_iterator> MachOObjectFile::rebaseTable(Error &Err) {
3145 return rebaseTable(Err, this, getDyldInfoRebaseOpcodes(), is64Bit());
Nick Kledzikac431442014-09-12 21:34:15 +00003146}
3147
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00003148MachOBindEntry::MachOBindEntry(Error *E, const MachOObjectFile *O,
3149 ArrayRef<uint8_t> Bytes, bool is64Bit, Kind BK)
Eugene Zelenko9f5094d2017-04-21 22:03:05 +00003150 : E(E), O(O), Opcodes(Bytes), Ptr(Bytes.begin()),
3151 PointerSize(is64Bit ? 8 : 4), TableKind(BK) {}
Nick Kledzik56ebef42014-09-16 01:41:51 +00003152
3153void MachOBindEntry::moveToFirst() {
3154 Ptr = Opcodes.begin();
3155 moveNext();
3156}
3157
3158void MachOBindEntry::moveToEnd() {
3159 Ptr = Opcodes.end();
3160 RemainingLoopCount = 0;
3161 Done = true;
3162}
3163
3164void MachOBindEntry::moveNext() {
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00003165 ErrorAsOutParameter ErrAsOutParam(E);
Nick Kledzik56ebef42014-09-16 01:41:51 +00003166 // If in the middle of some loop, move to next binding in loop.
3167 SegmentOffset += AdvanceAmount;
3168 if (RemainingLoopCount) {
3169 --RemainingLoopCount;
3170 return;
3171 }
Juergen Ributzkacad12492017-03-30 19:56:50 +00003172 // BIND_OPCODE_DONE is only used for padding if we are not aligned to
3173 // pointer size. Therefore it is possible to reach the end without ever having
3174 // seen BIND_OPCODE_DONE.
3175 if (Ptr == Opcodes.end()) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00003176 Done = true;
3177 return;
3178 }
3179 bool More = true;
Kevin Enderby6c1d2b42017-03-27 20:09:23 +00003180 while (More) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00003181 // Parse next opcode and set up next loop.
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00003182 const uint8_t *OpcodeStart = Ptr;
Nick Kledzik56ebef42014-09-16 01:41:51 +00003183 uint8_t Byte = *Ptr++;
3184 uint8_t ImmValue = Byte & MachO::BIND_IMMEDIATE_MASK;
3185 uint8_t Opcode = Byte & MachO::BIND_OPCODE_MASK;
3186 int8_t SignExtended;
3187 const uint8_t *SymStart;
Kevin Enderbya8d256c2017-03-20 19:46:55 +00003188 uint32_t Count, Skip;
3189 const char *error = nullptr;
Nick Kledzik56ebef42014-09-16 01:41:51 +00003190 switch (Opcode) {
3191 case MachO::BIND_OPCODE_DONE:
3192 if (TableKind == Kind::Lazy) {
3193 // Lazying bindings have a DONE opcode between entries. Need to ignore
3194 // it to advance to next entry. But need not if this is last entry.
3195 bool NotLastEntry = false;
3196 for (const uint8_t *P = Ptr; P < Opcodes.end(); ++P) {
3197 if (*P) {
3198 NotLastEntry = true;
3199 }
3200 }
3201 if (NotLastEntry)
3202 break;
3203 }
3204 More = false;
Nick Kledzik56ebef42014-09-16 01:41:51 +00003205 moveToEnd();
Eugene Zelenko9f5094d2017-04-21 22:03:05 +00003206 DEBUG_WITH_TYPE("mach-o-bind", dbgs() << "BIND_OPCODE_DONE\n");
Nick Kledzik56ebef42014-09-16 01:41:51 +00003207 break;
3208 case MachO::BIND_OPCODE_SET_DYLIB_ORDINAL_IMM:
Kevin Enderby6c1d2b42017-03-27 20:09:23 +00003209 if (TableKind == Kind::Weak) {
3210 *E = malformedError("BIND_OPCODE_SET_DYLIB_ORDINAL_IMM not allowed in "
3211 "weak bind table for opcode at: 0x" +
3212 utohexstr(OpcodeStart - Opcodes.begin()));
3213 moveToEnd();
3214 return;
3215 }
Nick Kledzik56ebef42014-09-16 01:41:51 +00003216 Ordinal = ImmValue;
Kevin Enderbya8d256c2017-03-20 19:46:55 +00003217 LibraryOrdinalSet = true;
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00003218 if (ImmValue > O->getLibraryCount()) {
3219 *E = malformedError("for BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB bad "
3220 "library ordinal: " + Twine((int)ImmValue) + " (max " +
3221 Twine((int)O->getLibraryCount()) + ") for opcode at: 0x" +
3222 utohexstr(OpcodeStart - Opcodes.begin()));
3223 moveToEnd();
3224 return;
3225 }
Nick Kledzik56ebef42014-09-16 01:41:51 +00003226 DEBUG_WITH_TYPE(
3227 "mach-o-bind",
Eugene Zelenko9f5094d2017-04-21 22:03:05 +00003228 dbgs() << "BIND_OPCODE_SET_DYLIB_ORDINAL_IMM: "
3229 << "Ordinal=" << Ordinal << "\n");
Nick Kledzik56ebef42014-09-16 01:41:51 +00003230 break;
3231 case MachO::BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB:
Kevin Enderby6c1d2b42017-03-27 20:09:23 +00003232 if (TableKind == Kind::Weak) {
3233 *E = malformedError("BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB not allowed in "
3234 "weak bind table for opcode at: 0x" +
3235 utohexstr(OpcodeStart - Opcodes.begin()));
3236 moveToEnd();
3237 return;
3238 }
Kevin Enderbya8d256c2017-03-20 19:46:55 +00003239 Ordinal = readULEB128(&error);
3240 LibraryOrdinalSet = true;
3241 if (error) {
3242 *E = malformedError("for BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB " +
3243 Twine(error) + " for opcode at: 0x" +
3244 utohexstr(OpcodeStart - Opcodes.begin()));
3245 moveToEnd();
3246 return;
3247 }
3248 if (Ordinal > (int)O->getLibraryCount()) {
3249 *E = malformedError("for BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB bad "
3250 "library ordinal: " + Twine((int)Ordinal) + " (max " +
3251 Twine((int)O->getLibraryCount()) + ") for opcode at: 0x" +
3252 utohexstr(OpcodeStart - Opcodes.begin()));
3253 moveToEnd();
3254 return;
3255 }
Nick Kledzik56ebef42014-09-16 01:41:51 +00003256 DEBUG_WITH_TYPE(
3257 "mach-o-bind",
Eugene Zelenko9f5094d2017-04-21 22:03:05 +00003258 dbgs() << "BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB: "
3259 << "Ordinal=" << Ordinal << "\n");
Nick Kledzik56ebef42014-09-16 01:41:51 +00003260 break;
3261 case MachO::BIND_OPCODE_SET_DYLIB_SPECIAL_IMM:
Kevin Enderby6c1d2b42017-03-27 20:09:23 +00003262 if (TableKind == Kind::Weak) {
3263 *E = malformedError("BIND_OPCODE_SET_DYLIB_SPECIAL_IMM not allowed in "
3264 "weak bind table for opcode at: 0x" +
3265 utohexstr(OpcodeStart - Opcodes.begin()));
3266 moveToEnd();
3267 return;
3268 }
Nick Kledzik56ebef42014-09-16 01:41:51 +00003269 if (ImmValue) {
3270 SignExtended = MachO::BIND_OPCODE_MASK | ImmValue;
3271 Ordinal = SignExtended;
Kevin Enderbya8d256c2017-03-20 19:46:55 +00003272 if (Ordinal < MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP) {
3273 *E = malformedError("for BIND_OPCODE_SET_DYLIB_SPECIAL_IMM unknown "
3274 "special ordinal: " + Twine((int)Ordinal) + " for opcode at: "
3275 "0x" + utohexstr(OpcodeStart - Opcodes.begin()));
3276 moveToEnd();
3277 return;
3278 }
Nick Kledzik56ebef42014-09-16 01:41:51 +00003279 } else
3280 Ordinal = 0;
Steven Wu97e2cf82017-05-31 22:17:43 +00003281 LibraryOrdinalSet = true;
Nick Kledzik56ebef42014-09-16 01:41:51 +00003282 DEBUG_WITH_TYPE(
3283 "mach-o-bind",
Eugene Zelenko9f5094d2017-04-21 22:03:05 +00003284 dbgs() << "BIND_OPCODE_SET_DYLIB_SPECIAL_IMM: "
3285 << "Ordinal=" << Ordinal << "\n");
Nick Kledzik56ebef42014-09-16 01:41:51 +00003286 break;
3287 case MachO::BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM:
3288 Flags = ImmValue;
3289 SymStart = Ptr;
Kevin Enderbya8d256c2017-03-20 19:46:55 +00003290 while (*Ptr && (Ptr < Opcodes.end())) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00003291 ++Ptr;
3292 }
Kevin Enderbya8d256c2017-03-20 19:46:55 +00003293 if (Ptr == Opcodes.end()) {
3294 *E = malformedError("for BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM "
3295 "symbol name extends past opcodes for opcode at: 0x" +
3296 utohexstr(OpcodeStart - Opcodes.begin()));
3297 moveToEnd();
3298 return;
3299 }
Nick Kledzik56ebef42014-09-16 01:41:51 +00003300 SymbolName = StringRef(reinterpret_cast<const char*>(SymStart),
3301 Ptr-SymStart);
Nick Kledzika6375362014-09-17 01:51:43 +00003302 ++Ptr;
Nick Kledzik56ebef42014-09-16 01:41:51 +00003303 DEBUG_WITH_TYPE(
3304 "mach-o-bind",
Eugene Zelenko9f5094d2017-04-21 22:03:05 +00003305 dbgs() << "BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM: "
3306 << "SymbolName=" << SymbolName << "\n");
Nick Kledzik56ebef42014-09-16 01:41:51 +00003307 if (TableKind == Kind::Weak) {
3308 if (ImmValue & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION)
3309 return;
3310 }
3311 break;
3312 case MachO::BIND_OPCODE_SET_TYPE_IMM:
3313 BindType = ImmValue;
Kevin Enderbya8d256c2017-03-20 19:46:55 +00003314 if (ImmValue > MachO::BIND_TYPE_TEXT_PCREL32) {
3315 *E = malformedError("for BIND_OPCODE_SET_TYPE_IMM bad bind type: " +
3316 Twine((int)ImmValue) + " for opcode at: 0x" +
3317 utohexstr(OpcodeStart - Opcodes.begin()));
3318 moveToEnd();
3319 return;
3320 }
Nick Kledzik56ebef42014-09-16 01:41:51 +00003321 DEBUG_WITH_TYPE(
3322 "mach-o-bind",
Eugene Zelenko9f5094d2017-04-21 22:03:05 +00003323 dbgs() << "BIND_OPCODE_SET_TYPE_IMM: "
3324 << "BindType=" << (int)BindType << "\n");
Nick Kledzik56ebef42014-09-16 01:41:51 +00003325 break;
3326 case MachO::BIND_OPCODE_SET_ADDEND_SLEB:
Kevin Enderbya8d256c2017-03-20 19:46:55 +00003327 Addend = readSLEB128(&error);
3328 if (error) {
3329 *E = malformedError("for BIND_OPCODE_SET_ADDEND_SLEB " +
3330 Twine(error) + " for opcode at: 0x" +
3331 utohexstr(OpcodeStart - Opcodes.begin()));
3332 moveToEnd();
3333 return;
3334 }
Nick Kledzik56ebef42014-09-16 01:41:51 +00003335 DEBUG_WITH_TYPE(
3336 "mach-o-bind",
Eugene Zelenko9f5094d2017-04-21 22:03:05 +00003337 dbgs() << "BIND_OPCODE_SET_ADDEND_SLEB: "
3338 << "Addend=" << Addend << "\n");
Nick Kledzik56ebef42014-09-16 01:41:51 +00003339 break;
3340 case MachO::BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:
3341 SegmentIndex = ImmValue;
Kevin Enderbya8d256c2017-03-20 19:46:55 +00003342 SegmentOffset = readULEB128(&error);
3343 if (error) {
3344 *E = malformedError("for BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB " +
3345 Twine(error) + " for opcode at: 0x" +
3346 utohexstr(OpcodeStart - Opcodes.begin()));
3347 moveToEnd();
3348 return;
3349 }
3350 error = O->BindEntryCheckSegAndOffset(SegmentIndex, SegmentOffset, true);
3351 if (error) {
3352 *E = malformedError("for BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB " +
3353 Twine(error) + " for opcode at: 0x" +
3354 utohexstr(OpcodeStart - Opcodes.begin()));
3355 moveToEnd();
3356 return;
3357 }
Nick Kledzik56ebef42014-09-16 01:41:51 +00003358 DEBUG_WITH_TYPE(
3359 "mach-o-bind",
Eugene Zelenko9f5094d2017-04-21 22:03:05 +00003360 dbgs() << "BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: "
3361 << "SegmentIndex=" << SegmentIndex << ", "
3362 << format("SegmentOffset=0x%06X", SegmentOffset)
3363 << "\n");
Nick Kledzik56ebef42014-09-16 01:41:51 +00003364 break;
3365 case MachO::BIND_OPCODE_ADD_ADDR_ULEB:
Kevin Enderbya8d256c2017-03-20 19:46:55 +00003366 SegmentOffset += readULEB128(&error);
3367 if (error) {
3368 *E = malformedError("for BIND_OPCODE_ADD_ADDR_ULEB " +
3369 Twine(error) + " for opcode at: 0x" +
3370 utohexstr(OpcodeStart - Opcodes.begin()));
3371 moveToEnd();
3372 return;
3373 }
3374 error = O->BindEntryCheckSegAndOffset(SegmentIndex, SegmentOffset, true);
3375 if (error) {
3376 *E = malformedError("for BIND_OPCODE_ADD_ADDR_ULEB " +
3377 Twine(error) + " for opcode at: 0x" +
3378 utohexstr(OpcodeStart - Opcodes.begin()));
3379 moveToEnd();
3380 return;
3381 }
Nick Kledzik56ebef42014-09-16 01:41:51 +00003382 DEBUG_WITH_TYPE("mach-o-bind",
Eugene Zelenko9f5094d2017-04-21 22:03:05 +00003383 dbgs() << "BIND_OPCODE_ADD_ADDR_ULEB: "
3384 << format("SegmentOffset=0x%06X",
3385 SegmentOffset) << "\n");
Nick Kledzik56ebef42014-09-16 01:41:51 +00003386 break;
3387 case MachO::BIND_OPCODE_DO_BIND:
3388 AdvanceAmount = PointerSize;
3389 RemainingLoopCount = 0;
Kevin Enderbya8d256c2017-03-20 19:46:55 +00003390 error = O->BindEntryCheckSegAndOffset(SegmentIndex, SegmentOffset, true);
3391 if (error) {
3392 *E = malformedError("for BIND_OPCODE_DO_BIND " + Twine(error) +
3393 " for opcode at: 0x" + utohexstr(OpcodeStart - Opcodes.begin()));
3394 moveToEnd();
3395 return;
3396 }
3397 if (SymbolName == StringRef()) {
3398 *E = malformedError("for BIND_OPCODE_DO_BIND missing preceding "
3399 "BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM for opcode at: 0x" +
3400 utohexstr(OpcodeStart - Opcodes.begin()));
3401 moveToEnd();
3402 return;
3403 }
3404 if (!LibraryOrdinalSet && TableKind != Kind::Weak) {
3405 *E = malformedError("for BIND_OPCODE_DO_BIND missing preceding "
3406 "BIND_OPCODE_SET_DYLIB_ORDINAL_* for opcode at: 0x" +
3407 utohexstr(OpcodeStart - Opcodes.begin()));
3408 moveToEnd();
3409 return;
3410 }
Nick Kledzik56ebef42014-09-16 01:41:51 +00003411 DEBUG_WITH_TYPE("mach-o-bind",
Eugene Zelenko9f5094d2017-04-21 22:03:05 +00003412 dbgs() << "BIND_OPCODE_DO_BIND: "
3413 << format("SegmentOffset=0x%06X",
3414 SegmentOffset) << "\n");
Nick Kledzik56ebef42014-09-16 01:41:51 +00003415 return;
3416 case MachO::BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB:
Kevin Enderby6c1d2b42017-03-27 20:09:23 +00003417 if (TableKind == Kind::Lazy) {
3418 *E = malformedError("BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB not allowed in "
3419 "lazy bind table for opcode at: 0x" +
3420 utohexstr(OpcodeStart - Opcodes.begin()));
3421 moveToEnd();
3422 return;
3423 }
Kevin Enderbya8d256c2017-03-20 19:46:55 +00003424 error = O->BindEntryCheckSegAndOffset(SegmentIndex, SegmentOffset, true);
3425 if (error) {
3426 *E = malformedError("for BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB " +
3427 Twine(error) + " for opcode at: 0x" +
3428 utohexstr(OpcodeStart - Opcodes.begin()));
3429 moveToEnd();
3430 return;
3431 }
3432 if (SymbolName == StringRef()) {
3433 *E = malformedError("for BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB missing "
3434 "preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM for opcode "
3435 "at: 0x" + utohexstr(OpcodeStart - Opcodes.begin()));
3436 moveToEnd();
3437 return;
3438 }
3439 if (!LibraryOrdinalSet && TableKind != Kind::Weak) {
3440 *E = malformedError("for BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB missing "
3441 "preceding BIND_OPCODE_SET_DYLIB_ORDINAL_* for opcode at: 0x" +
3442 utohexstr(OpcodeStart - Opcodes.begin()));
3443 moveToEnd();
3444 return;
3445 }
3446 AdvanceAmount = readULEB128(&error) + PointerSize;
3447 if (error) {
3448 *E = malformedError("for BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB " +
3449 Twine(error) + " for opcode at: 0x" +
3450 utohexstr(OpcodeStart - Opcodes.begin()));
3451 moveToEnd();
3452 return;
3453 }
3454 // Note, this is not really an error until the next bind but make no sense
3455 // for a BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB to not be followed by another
3456 // bind operation.
3457 error = O->BindEntryCheckSegAndOffset(SegmentIndex, SegmentOffset +
3458 AdvanceAmount, false);
3459 if (error) {
3460 *E = malformedError("for BIND_OPCODE_ADD_ADDR_ULEB (after adding "
3461 "ULEB) " + Twine(error) + " for opcode at: 0x" +
3462 utohexstr(OpcodeStart - Opcodes.begin()));
3463 moveToEnd();
3464 return;
3465 }
Nick Kledzik56ebef42014-09-16 01:41:51 +00003466 RemainingLoopCount = 0;
Nick Kledzik56ebef42014-09-16 01:41:51 +00003467 DEBUG_WITH_TYPE(
3468 "mach-o-bind",
Eugene Zelenko9f5094d2017-04-21 22:03:05 +00003469 dbgs() << "BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB: "
3470 << format("SegmentOffset=0x%06X", SegmentOffset)
3471 << ", AdvanceAmount=" << AdvanceAmount
3472 << ", RemainingLoopCount=" << RemainingLoopCount
3473 << "\n");
Nick Kledzik56ebef42014-09-16 01:41:51 +00003474 return;
3475 case MachO::BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED:
Kevin Enderby6c1d2b42017-03-27 20:09:23 +00003476 if (TableKind == Kind::Lazy) {
3477 *E = malformedError("BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED not "
3478 "allowed in lazy bind table for opcode at: 0x" +
3479 utohexstr(OpcodeStart - Opcodes.begin()));
3480 moveToEnd();
3481 return;
3482 }
Kevin Enderbya8d256c2017-03-20 19:46:55 +00003483 error = O->BindEntryCheckSegAndOffset(SegmentIndex, SegmentOffset, true);
3484 if (error) {
3485 *E = malformedError("for BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED " +
3486 Twine(error) + " for opcode at: 0x" +
3487 utohexstr(OpcodeStart - Opcodes.begin()));
3488 moveToEnd();
3489 return;
3490 }
3491 if (SymbolName == StringRef()) {
3492 *E = malformedError("for BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED "
3493 "missing preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM for "
3494 "opcode at: 0x" + utohexstr(OpcodeStart - Opcodes.begin()));
3495 moveToEnd();
3496 return;
3497 }
3498 if (!LibraryOrdinalSet && TableKind != Kind::Weak) {
3499 *E = malformedError("for BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED "
3500 "missing preceding BIND_OPCODE_SET_DYLIB_ORDINAL_* for opcode "
3501 "at: 0x" + utohexstr(OpcodeStart - Opcodes.begin()));
3502 moveToEnd();
3503 return;
3504 }
Nick Kledzik3b2aa052014-10-18 01:21:02 +00003505 AdvanceAmount = ImmValue * PointerSize + PointerSize;
Nick Kledzik56ebef42014-09-16 01:41:51 +00003506 RemainingLoopCount = 0;
Kevin Enderbya8d256c2017-03-20 19:46:55 +00003507 error = O->BindEntryCheckSegAndOffset(SegmentIndex, SegmentOffset +
3508 AdvanceAmount, false);
3509 if (error) {
3510 *E = malformedError("for BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED "
3511 " (after adding immediate times the pointer size) " +
3512 Twine(error) + " for opcode at: 0x" +
3513 utohexstr(OpcodeStart - Opcodes.begin()));
3514 moveToEnd();
3515 return;
3516 }
Nick Kledzik56ebef42014-09-16 01:41:51 +00003517 DEBUG_WITH_TYPE("mach-o-bind",
Eugene Zelenko9f5094d2017-04-21 22:03:05 +00003518 dbgs()
Nick Kledzik56ebef42014-09-16 01:41:51 +00003519 << "BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED: "
Eugene Zelenko9f5094d2017-04-21 22:03:05 +00003520 << format("SegmentOffset=0x%06X", SegmentOffset) << "\n");
Nick Kledzik56ebef42014-09-16 01:41:51 +00003521 return;
3522 case MachO::BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB:
Kevin Enderby6c1d2b42017-03-27 20:09:23 +00003523 if (TableKind == Kind::Lazy) {
3524 *E = malformedError("BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB not "
3525 "allowed in lazy bind table for opcode at: 0x" +
3526 utohexstr(OpcodeStart - Opcodes.begin()));
3527 moveToEnd();
3528 return;
3529 }
Kevin Enderbya8d256c2017-03-20 19:46:55 +00003530 Count = readULEB128(&error);
3531 if (Count != 0)
3532 RemainingLoopCount = Count - 1;
3533 else
3534 RemainingLoopCount = 0;
3535 if (error) {
3536 *E = malformedError("for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB "
3537 " (count value) " + Twine(error) + " for opcode at"
3538 ": 0x" + utohexstr(OpcodeStart - Opcodes.begin()));
3539 moveToEnd();
3540 return;
3541 }
3542 Skip = readULEB128(&error);
3543 AdvanceAmount = Skip + PointerSize;
3544 if (error) {
3545 *E = malformedError("for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB "
3546 " (skip value) " + Twine(error) + " for opcode at"
3547 ": 0x" + utohexstr(OpcodeStart - Opcodes.begin()));
3548 moveToEnd();
3549 return;
3550 }
3551 error = O->BindEntryCheckSegAndOffset(SegmentIndex, SegmentOffset, true);
3552 if (error) {
3553 *E = malformedError("for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB "
3554 + Twine(error) + " for opcode at: 0x" +
3555 utohexstr(OpcodeStart - Opcodes.begin()));
3556 moveToEnd();
3557 return;
3558 }
3559 if (SymbolName == StringRef()) {
3560 *E = malformedError("for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB "
3561 "missing preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM for "
3562 "opcode at: 0x" + utohexstr(OpcodeStart - Opcodes.begin()));
3563 moveToEnd();
3564 return;
3565 }
3566 if (!LibraryOrdinalSet && TableKind != Kind::Weak) {
3567 *E = malformedError("for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB "
3568 "missing preceding BIND_OPCODE_SET_DYLIB_ORDINAL_* for opcode "
3569 "at: 0x" + utohexstr(OpcodeStart - Opcodes.begin()));
3570 moveToEnd();
3571 return;
3572 }
3573 error = O->BindEntryCheckCountAndSkip(Count, Skip, PointerSize,
3574 SegmentIndex, SegmentOffset);
3575 if (error) {
3576 *E = malformedError("for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB "
3577 + Twine(error) + " for opcode at: 0x" +
3578 utohexstr(OpcodeStart - Opcodes.begin()));
3579 moveToEnd();
3580 return;
3581 }
Nick Kledzik56ebef42014-09-16 01:41:51 +00003582 DEBUG_WITH_TYPE(
3583 "mach-o-bind",
Eugene Zelenko9f5094d2017-04-21 22:03:05 +00003584 dbgs() << "BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB: "
3585 << format("SegmentOffset=0x%06X", SegmentOffset)
3586 << ", AdvanceAmount=" << AdvanceAmount
3587 << ", RemainingLoopCount=" << RemainingLoopCount
3588 << "\n");
Nick Kledzik56ebef42014-09-16 01:41:51 +00003589 return;
3590 default:
Kevin Enderbya8d256c2017-03-20 19:46:55 +00003591 *E = malformedError("bad bind info (bad opcode value 0x" +
3592 utohexstr(Opcode) + " for opcode at: 0x" +
3593 utohexstr(OpcodeStart - Opcodes.begin()));
3594 moveToEnd();
3595 return;
Nick Kledzik56ebef42014-09-16 01:41:51 +00003596 }
3597 }
3598}
3599
Kevin Enderbya8d256c2017-03-20 19:46:55 +00003600uint64_t MachOBindEntry::readULEB128(const char **error) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00003601 unsigned Count;
Kevin Enderbya8d256c2017-03-20 19:46:55 +00003602 uint64_t Result = decodeULEB128(Ptr, &Count, Opcodes.end(), error);
Nick Kledzik56ebef42014-09-16 01:41:51 +00003603 Ptr += Count;
Kevin Enderby6c1d2b42017-03-27 20:09:23 +00003604 if (Ptr > Opcodes.end())
Nick Kledzik56ebef42014-09-16 01:41:51 +00003605 Ptr = Opcodes.end();
Nick Kledzik56ebef42014-09-16 01:41:51 +00003606 return Result;
3607}
3608
Kevin Enderbya8d256c2017-03-20 19:46:55 +00003609int64_t MachOBindEntry::readSLEB128(const char **error) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00003610 unsigned Count;
Kevin Enderbya8d256c2017-03-20 19:46:55 +00003611 int64_t Result = decodeSLEB128(Ptr, &Count, Opcodes.end(), error);
Nick Kledzik56ebef42014-09-16 01:41:51 +00003612 Ptr += Count;
Kevin Enderby6c1d2b42017-03-27 20:09:23 +00003613 if (Ptr > Opcodes.end())
Nick Kledzik56ebef42014-09-16 01:41:51 +00003614 Ptr = Opcodes.end();
Nick Kledzik56ebef42014-09-16 01:41:51 +00003615 return Result;
3616}
3617
Kevin Enderbya8d256c2017-03-20 19:46:55 +00003618int32_t MachOBindEntry::segmentIndex() const { return SegmentIndex; }
Nick Kledzik56ebef42014-09-16 01:41:51 +00003619
3620uint64_t MachOBindEntry::segmentOffset() const { return SegmentOffset; }
3621
3622StringRef MachOBindEntry::typeName() const {
3623 switch (BindType) {
3624 case MachO::BIND_TYPE_POINTER:
3625 return "pointer";
3626 case MachO::BIND_TYPE_TEXT_ABSOLUTE32:
3627 return "text abs32";
3628 case MachO::BIND_TYPE_TEXT_PCREL32:
3629 return "text rel32";
3630 }
3631 return "unknown";
3632}
3633
3634StringRef MachOBindEntry::symbolName() const { return SymbolName; }
3635
3636int64_t MachOBindEntry::addend() const { return Addend; }
3637
3638uint32_t MachOBindEntry::flags() const { return Flags; }
3639
3640int MachOBindEntry::ordinal() const { return Ordinal; }
3641
Kevin Enderbya8d256c2017-03-20 19:46:55 +00003642// For use with the SegIndex of a checked Mach-O Bind entry
3643// to get the segment name.
3644StringRef MachOBindEntry::segmentName() const {
3645 return O->BindRebaseSegmentName(SegmentIndex);
3646}
3647
3648// For use with a SegIndex,SegOffset pair from a checked Mach-O Bind entry
3649// to get the section name.
3650StringRef MachOBindEntry::sectionName() const {
3651 return O->BindRebaseSectionName(SegmentIndex, SegmentOffset);
3652}
3653
3654// For use with a SegIndex,SegOffset pair from a checked Mach-O Bind entry
3655// to get the address.
3656uint64_t MachOBindEntry::address() const {
3657 return O->BindRebaseAddress(SegmentIndex, SegmentOffset);
3658}
3659
Nick Kledzik56ebef42014-09-16 01:41:51 +00003660bool MachOBindEntry::operator==(const MachOBindEntry &Other) const {
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +00003661#ifdef EXPENSIVE_CHECKS
Nick Kledzik56ebef42014-09-16 01:41:51 +00003662 assert(Opcodes == Other.Opcodes && "compare iterators of different files");
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +00003663#else
3664 assert(Opcodes.data() == Other.Opcodes.data() && "compare iterators of different files");
3665#endif
Nick Kledzik56ebef42014-09-16 01:41:51 +00003666 return (Ptr == Other.Ptr) &&
3667 (RemainingLoopCount == Other.RemainingLoopCount) &&
3668 (Done == Other.Done);
3669}
3670
Kevin Enderbya8d256c2017-03-20 19:46:55 +00003671// Build table of sections so SegIndex/SegOffset pairs can be translated.
3672BindRebaseSegInfo::BindRebaseSegInfo(const object::MachOObjectFile *Obj) {
3673 uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
3674 StringRef CurSegName;
3675 uint64_t CurSegAddress;
3676 for (const SectionRef &Section : Obj->sections()) {
3677 SectionInfo Info;
3678 Section.getName(Info.SectionName);
3679 Info.Address = Section.getAddress();
3680 Info.Size = Section.getSize();
3681 Info.SegmentName =
3682 Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
3683 if (!Info.SegmentName.equals(CurSegName)) {
3684 ++CurSegIndex;
3685 CurSegName = Info.SegmentName;
3686 CurSegAddress = Info.Address;
3687 }
3688 Info.SegmentIndex = CurSegIndex - 1;
3689 Info.OffsetInSegment = Info.Address - CurSegAddress;
3690 Info.SegmentStartAddress = CurSegAddress;
3691 Sections.push_back(Info);
3692 }
3693 MaxSegIndex = CurSegIndex;
3694}
3695
3696// For use with a SegIndex,SegOffset pair in MachOBindEntry::moveNext() to
Kevin Enderby6c1d2b42017-03-27 20:09:23 +00003697// validate a MachOBindEntry or MachORebaseEntry.
Kevin Enderbya8d256c2017-03-20 19:46:55 +00003698const char * BindRebaseSegInfo::checkSegAndOffset(int32_t SegIndex,
3699 uint64_t SegOffset,
3700 bool endInvalid) {
3701 if (SegIndex == -1)
Kevin Enderby6c1d2b42017-03-27 20:09:23 +00003702 return "missing preceding *_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB";
Kevin Enderbya8d256c2017-03-20 19:46:55 +00003703 if (SegIndex >= MaxSegIndex)
3704 return "bad segIndex (too large)";
3705 for (const SectionInfo &SI : Sections) {
3706 if (SI.SegmentIndex != SegIndex)
3707 continue;
3708 if (SI.OffsetInSegment > SegOffset)
3709 continue;
3710 if (SegOffset > (SI.OffsetInSegment + SI.Size))
3711 continue;
3712 if (endInvalid && SegOffset >= (SI.OffsetInSegment + SI.Size))
3713 continue;
3714 return nullptr;
3715 }
3716 return "bad segOffset, too large";
3717}
3718
3719// For use in MachOBindEntry::moveNext() to validate a MachOBindEntry for
Kevin Enderby6c1d2b42017-03-27 20:09:23 +00003720// the BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB opcode and for use in
3721// MachORebaseEntry::moveNext() to validate a MachORebaseEntry for
3722// REBASE_OPCODE_DO_*_TIMES* opcodes. The SegIndex and SegOffset must have
3723// been already checked.
Kevin Enderbya8d256c2017-03-20 19:46:55 +00003724const char * BindRebaseSegInfo::checkCountAndSkip(uint32_t Count, uint32_t Skip,
3725 uint8_t PointerSize,
Kevin Enderby6c1d2b42017-03-27 20:09:23 +00003726 int32_t SegIndex,
3727 uint64_t SegOffset) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +00003728 const SectionInfo &SI = findSection(SegIndex, SegOffset);
3729 uint64_t addr = SI.SegmentStartAddress + SegOffset;
3730 if (addr >= SI.Address + SI.Size)
3731 return "bad segOffset, too large";
3732 uint64_t i = 0;
3733 if (Count > 1)
3734 i = (Skip + PointerSize) * (Count - 1);
Kevin Enderby6c1d2b42017-03-27 20:09:23 +00003735 else if (Count == 1)
3736 i = Skip + PointerSize;
3737 if (addr + i >= SI.Address + SI.Size) {
3738 // For rebase opcodes they can step from one section to another.
3739 uint64_t TrailingSegOffset = (addr + i) - SI.SegmentStartAddress;
3740 const char *error = checkSegAndOffset(SegIndex, TrailingSegOffset, false);
3741 if (error)
3742 return "bad count and skip, too large";
3743 }
Kevin Enderbya8d256c2017-03-20 19:46:55 +00003744 return nullptr;
3745}
3746
3747// For use with the SegIndex of a checked Mach-O Bind or Rebase entry
3748// to get the segment name.
3749StringRef BindRebaseSegInfo::segmentName(int32_t SegIndex) {
3750 for (const SectionInfo &SI : Sections) {
3751 if (SI.SegmentIndex == SegIndex)
3752 return SI.SegmentName;
3753 }
3754 llvm_unreachable("invalid SegIndex");
3755}
3756
3757// For use with a SegIndex,SegOffset pair from a checked Mach-O Bind or Rebase
3758// to get the SectionInfo.
3759const BindRebaseSegInfo::SectionInfo &BindRebaseSegInfo::findSection(
3760 int32_t SegIndex, uint64_t SegOffset) {
3761 for (const SectionInfo &SI : Sections) {
3762 if (SI.SegmentIndex != SegIndex)
3763 continue;
3764 if (SI.OffsetInSegment > SegOffset)
3765 continue;
3766 if (SegOffset >= (SI.OffsetInSegment + SI.Size))
3767 continue;
3768 return SI;
3769 }
3770 llvm_unreachable("SegIndex and SegOffset not in any section");
3771}
3772
3773// For use with a SegIndex,SegOffset pair from a checked Mach-O Bind or Rebase
3774// entry to get the section name.
3775StringRef BindRebaseSegInfo::sectionName(int32_t SegIndex,
3776 uint64_t SegOffset) {
3777 return findSection(SegIndex, SegOffset).SectionName;
3778}
3779
3780// For use with a SegIndex,SegOffset pair from a checked Mach-O Bind or Rebase
3781// entry to get the address.
3782uint64_t BindRebaseSegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
3783 const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
3784 return SI.SegmentStartAddress + OffsetInSeg;
3785}
3786
Nick Kledzik56ebef42014-09-16 01:41:51 +00003787iterator_range<bind_iterator>
Kevin Enderbya8d256c2017-03-20 19:46:55 +00003788MachOObjectFile::bindTable(Error &Err, MachOObjectFile *O,
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00003789 ArrayRef<uint8_t> Opcodes, bool is64,
Nick Kledzik56ebef42014-09-16 01:41:51 +00003790 MachOBindEntry::Kind BKind) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +00003791 if (O->BindRebaseSectionTable == nullptr)
3792 O->BindRebaseSectionTable = llvm::make_unique<BindRebaseSegInfo>(O);
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00003793 MachOBindEntry Start(&Err, O, Opcodes, is64, BKind);
Nick Kledzik56ebef42014-09-16 01:41:51 +00003794 Start.moveToFirst();
3795
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00003796 MachOBindEntry Finish(&Err, O, Opcodes, is64, BKind);
Nick Kledzik56ebef42014-09-16 01:41:51 +00003797 Finish.moveToEnd();
3798
Craig Topper15576e12015-12-06 05:08:07 +00003799 return make_range(bind_iterator(Start), bind_iterator(Finish));
Nick Kledzik56ebef42014-09-16 01:41:51 +00003800}
3801
Kevin Enderbya8d256c2017-03-20 19:46:55 +00003802iterator_range<bind_iterator> MachOObjectFile::bindTable(Error &Err) {
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00003803 return bindTable(Err, this, getDyldInfoBindOpcodes(), is64Bit(),
Nick Kledzik56ebef42014-09-16 01:41:51 +00003804 MachOBindEntry::Kind::Regular);
3805}
3806
Kevin Enderbya8d256c2017-03-20 19:46:55 +00003807iterator_range<bind_iterator> MachOObjectFile::lazyBindTable(Error &Err) {
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00003808 return bindTable(Err, this, getDyldInfoLazyBindOpcodes(), is64Bit(),
Nick Kledzik56ebef42014-09-16 01:41:51 +00003809 MachOBindEntry::Kind::Lazy);
3810}
3811
Kevin Enderbya8d256c2017-03-20 19:46:55 +00003812iterator_range<bind_iterator> MachOObjectFile::weakBindTable(Error &Err) {
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00003813 return bindTable(Err, this, getDyldInfoWeakBindOpcodes(), is64Bit(),
Nick Kledzik56ebef42014-09-16 01:41:51 +00003814 MachOBindEntry::Kind::Weak);
3815}
3816
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00003817MachOObjectFile::load_command_iterator
3818MachOObjectFile::begin_load_commands() const {
3819 return LoadCommands.begin();
3820}
3821
3822MachOObjectFile::load_command_iterator
3823MachOObjectFile::end_load_commands() const {
3824 return LoadCommands.end();
3825}
3826
3827iterator_range<MachOObjectFile::load_command_iterator>
3828MachOObjectFile::load_commands() const {
Craig Topper15576e12015-12-06 05:08:07 +00003829 return make_range(begin_load_commands(), end_load_commands());
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00003830}
3831
Rafael Espindola56f976f2013-04-18 18:08:55 +00003832StringRef
3833MachOObjectFile::getSectionFinalSegmentName(DataRefImpl Sec) const {
3834 ArrayRef<char> Raw = getSectionRawFinalSegmentName(Sec);
3835 return parseSegmentOrSectionName(Raw.data());
3836}
3837
3838ArrayRef<char>
3839MachOObjectFile::getSectionRawName(DataRefImpl Sec) const {
Rafael Espindola0d85d102015-05-22 14:59:27 +00003840 assert(Sec.d.a < Sections.size() && "Should have detected this earlier");
Charles Davis8bdfafd2013-09-01 04:28:48 +00003841 const section_base *Base =
3842 reinterpret_cast<const section_base *>(Sections[Sec.d.a]);
Craig Toppere1d12942014-08-27 05:25:25 +00003843 return makeArrayRef(Base->sectname);
Rafael Espindola56f976f2013-04-18 18:08:55 +00003844}
3845
3846ArrayRef<char>
3847MachOObjectFile::getSectionRawFinalSegmentName(DataRefImpl Sec) const {
Rafael Espindola0d85d102015-05-22 14:59:27 +00003848 assert(Sec.d.a < Sections.size() && "Should have detected this earlier");
Charles Davis8bdfafd2013-09-01 04:28:48 +00003849 const section_base *Base =
3850 reinterpret_cast<const section_base *>(Sections[Sec.d.a]);
Craig Toppere1d12942014-08-27 05:25:25 +00003851 return makeArrayRef(Base->segname);
Rafael Espindola56f976f2013-04-18 18:08:55 +00003852}
3853
3854bool
Charles Davis8bdfafd2013-09-01 04:28:48 +00003855MachOObjectFile::isRelocationScattered(const MachO::any_relocation_info &RE)
Rafael Espindola56f976f2013-04-18 18:08:55 +00003856 const {
Lang Hames697e7cd2016-12-04 01:56:10 +00003857 if (getCPUType(*this) == MachO::CPU_TYPE_X86_64)
Rafael Espindola56f976f2013-04-18 18:08:55 +00003858 return false;
Charles Davis8bdfafd2013-09-01 04:28:48 +00003859 return getPlainRelocationAddress(RE) & MachO::R_SCATTERED;
Rafael Espindola56f976f2013-04-18 18:08:55 +00003860}
3861
Eric Christopher1d62c252013-07-22 22:25:07 +00003862unsigned MachOObjectFile::getPlainRelocationSymbolNum(
Charles Davis8bdfafd2013-09-01 04:28:48 +00003863 const MachO::any_relocation_info &RE) const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00003864 if (isLittleEndian())
Charles Davis8bdfafd2013-09-01 04:28:48 +00003865 return RE.r_word1 & 0xffffff;
3866 return RE.r_word1 >> 8;
Rafael Espindola56f976f2013-04-18 18:08:55 +00003867}
3868
Eric Christopher1d62c252013-07-22 22:25:07 +00003869bool MachOObjectFile::getPlainRelocationExternal(
Charles Davis8bdfafd2013-09-01 04:28:48 +00003870 const MachO::any_relocation_info &RE) const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00003871 if (isLittleEndian())
Charles Davis8bdfafd2013-09-01 04:28:48 +00003872 return (RE.r_word1 >> 27) & 1;
3873 return (RE.r_word1 >> 4) & 1;
Rafael Espindola56f976f2013-04-18 18:08:55 +00003874}
3875
Eric Christopher1d62c252013-07-22 22:25:07 +00003876bool MachOObjectFile::getScatteredRelocationScattered(
Charles Davis8bdfafd2013-09-01 04:28:48 +00003877 const MachO::any_relocation_info &RE) const {
3878 return RE.r_word0 >> 31;
Rafael Espindola56f976f2013-04-18 18:08:55 +00003879}
3880
Eric Christopher1d62c252013-07-22 22:25:07 +00003881uint32_t MachOObjectFile::getScatteredRelocationValue(
Charles Davis8bdfafd2013-09-01 04:28:48 +00003882 const MachO::any_relocation_info &RE) const {
3883 return RE.r_word1;
Rafael Espindola56f976f2013-04-18 18:08:55 +00003884}
3885
Kevin Enderby9907d0a2014-11-04 00:43:16 +00003886uint32_t MachOObjectFile::getScatteredRelocationType(
3887 const MachO::any_relocation_info &RE) const {
3888 return (RE.r_word0 >> 24) & 0xf;
3889}
3890
Eric Christopher1d62c252013-07-22 22:25:07 +00003891unsigned MachOObjectFile::getAnyRelocationAddress(
Charles Davis8bdfafd2013-09-01 04:28:48 +00003892 const MachO::any_relocation_info &RE) const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00003893 if (isRelocationScattered(RE))
3894 return getScatteredRelocationAddress(RE);
3895 return getPlainRelocationAddress(RE);
3896}
3897
Charles Davis8bdfafd2013-09-01 04:28:48 +00003898unsigned MachOObjectFile::getAnyRelocationPCRel(
3899 const MachO::any_relocation_info &RE) const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00003900 if (isRelocationScattered(RE))
Lang Hames697e7cd2016-12-04 01:56:10 +00003901 return getScatteredRelocationPCRel(RE);
3902 return getPlainRelocationPCRel(*this, RE);
Rafael Espindola56f976f2013-04-18 18:08:55 +00003903}
3904
Eric Christopher1d62c252013-07-22 22:25:07 +00003905unsigned MachOObjectFile::getAnyRelocationLength(
Charles Davis8bdfafd2013-09-01 04:28:48 +00003906 const MachO::any_relocation_info &RE) const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00003907 if (isRelocationScattered(RE))
3908 return getScatteredRelocationLength(RE);
Lang Hames697e7cd2016-12-04 01:56:10 +00003909 return getPlainRelocationLength(*this, RE);
Rafael Espindola56f976f2013-04-18 18:08:55 +00003910}
3911
3912unsigned
Charles Davis8bdfafd2013-09-01 04:28:48 +00003913MachOObjectFile::getAnyRelocationType(
3914 const MachO::any_relocation_info &RE) const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00003915 if (isRelocationScattered(RE))
3916 return getScatteredRelocationType(RE);
Lang Hames697e7cd2016-12-04 01:56:10 +00003917 return getPlainRelocationType(*this, RE);
Rafael Espindola56f976f2013-04-18 18:08:55 +00003918}
3919
Rafael Espindola52501032013-04-30 15:40:54 +00003920SectionRef
Keno Fischerc780e8e2015-05-21 21:24:32 +00003921MachOObjectFile::getAnyRelocationSection(
Charles Davis8bdfafd2013-09-01 04:28:48 +00003922 const MachO::any_relocation_info &RE) const {
Rafael Espindola52501032013-04-30 15:40:54 +00003923 if (isRelocationScattered(RE) || getPlainRelocationExternal(RE))
Rafael Espindolab5155a52014-02-10 20:24:04 +00003924 return *section_end();
Rafael Espindola9ac06a02015-06-18 22:38:20 +00003925 unsigned SecNum = getPlainRelocationSymbolNum(RE);
3926 if (SecNum == MachO::R_ABS || SecNum > Sections.size())
3927 return *section_end();
Rafael Espindola52501032013-04-30 15:40:54 +00003928 DataRefImpl DRI;
Rafael Espindola9ac06a02015-06-18 22:38:20 +00003929 DRI.d.a = SecNum - 1;
Rafael Espindola52501032013-04-30 15:40:54 +00003930 return SectionRef(DRI, this);
3931}
3932
Charles Davis8bdfafd2013-09-01 04:28:48 +00003933MachO::section MachOObjectFile::getSection(DataRefImpl DRI) const {
Rafael Espindola62a07cb2015-05-22 15:43:00 +00003934 assert(DRI.d.a < Sections.size() && "Should have detected this earlier");
Lang Hames697e7cd2016-12-04 01:56:10 +00003935 return getStruct<MachO::section>(*this, Sections[DRI.d.a]);
Rafael Espindola56f976f2013-04-18 18:08:55 +00003936}
3937
Charles Davis8bdfafd2013-09-01 04:28:48 +00003938MachO::section_64 MachOObjectFile::getSection64(DataRefImpl DRI) const {
Rafael Espindola62a07cb2015-05-22 15:43:00 +00003939 assert(DRI.d.a < Sections.size() && "Should have detected this earlier");
Lang Hames697e7cd2016-12-04 01:56:10 +00003940 return getStruct<MachO::section_64>(*this, Sections[DRI.d.a]);
Rafael Espindola56f976f2013-04-18 18:08:55 +00003941}
3942
Charles Davis8bdfafd2013-09-01 04:28:48 +00003943MachO::section MachOObjectFile::getSection(const LoadCommandInfo &L,
Rafael Espindola6e040c02013-04-26 20:07:33 +00003944 unsigned Index) const {
Lang Hames697e7cd2016-12-04 01:56:10 +00003945 const char *Sec = getSectionPtr(*this, L, Index);
3946 return getStruct<MachO::section>(*this, Sec);
Rafael Espindola6e040c02013-04-26 20:07:33 +00003947}
3948
Charles Davis8bdfafd2013-09-01 04:28:48 +00003949MachO::section_64 MachOObjectFile::getSection64(const LoadCommandInfo &L,
3950 unsigned Index) const {
Lang Hames697e7cd2016-12-04 01:56:10 +00003951 const char *Sec = getSectionPtr(*this, L, Index);
3952 return getStruct<MachO::section_64>(*this, Sec);
Rafael Espindola6e040c02013-04-26 20:07:33 +00003953}
3954
Charles Davis8bdfafd2013-09-01 04:28:48 +00003955MachO::nlist
Rafael Espindola56f976f2013-04-18 18:08:55 +00003956MachOObjectFile::getSymbolTableEntry(DataRefImpl DRI) const {
Rafael Espindola75c30362013-04-24 19:47:55 +00003957 const char *P = reinterpret_cast<const char *>(DRI.p);
Lang Hames697e7cd2016-12-04 01:56:10 +00003958 return getStruct<MachO::nlist>(*this, P);
Rafael Espindola56f976f2013-04-18 18:08:55 +00003959}
3960
Charles Davis8bdfafd2013-09-01 04:28:48 +00003961MachO::nlist_64
Rafael Espindola56f976f2013-04-18 18:08:55 +00003962MachOObjectFile::getSymbol64TableEntry(DataRefImpl DRI) const {
Rafael Espindola75c30362013-04-24 19:47:55 +00003963 const char *P = reinterpret_cast<const char *>(DRI.p);
Lang Hames697e7cd2016-12-04 01:56:10 +00003964 return getStruct<MachO::nlist_64>(*this, P);
Rafael Espindola56f976f2013-04-18 18:08:55 +00003965}
3966
Charles Davis8bdfafd2013-09-01 04:28:48 +00003967MachO::linkedit_data_command
3968MachOObjectFile::getLinkeditDataLoadCommand(const LoadCommandInfo &L) const {
Lang Hames697e7cd2016-12-04 01:56:10 +00003969 return getStruct<MachO::linkedit_data_command>(*this, L.Ptr);
Rafael Espindola56f976f2013-04-18 18:08:55 +00003970}
3971
Charles Davis8bdfafd2013-09-01 04:28:48 +00003972MachO::segment_command
Rafael Espindola6e040c02013-04-26 20:07:33 +00003973MachOObjectFile::getSegmentLoadCommand(const LoadCommandInfo &L) const {
Lang Hames697e7cd2016-12-04 01:56:10 +00003974 return getStruct<MachO::segment_command>(*this, L.Ptr);
Rafael Espindola6e040c02013-04-26 20:07:33 +00003975}
3976
Charles Davis8bdfafd2013-09-01 04:28:48 +00003977MachO::segment_command_64
Rafael Espindola6e040c02013-04-26 20:07:33 +00003978MachOObjectFile::getSegment64LoadCommand(const LoadCommandInfo &L) const {
Lang Hames697e7cd2016-12-04 01:56:10 +00003979 return getStruct<MachO::segment_command_64>(*this, L.Ptr);
Rafael Espindola6e040c02013-04-26 20:07:33 +00003980}
3981
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00003982MachO::linker_option_command
3983MachOObjectFile::getLinkerOptionLoadCommand(const LoadCommandInfo &L) const {
Lang Hames697e7cd2016-12-04 01:56:10 +00003984 return getStruct<MachO::linker_option_command>(*this, L.Ptr);
Rafael Espindola6e040c02013-04-26 20:07:33 +00003985}
3986
Jim Grosbach448334a2014-03-18 22:09:05 +00003987MachO::version_min_command
3988MachOObjectFile::getVersionMinLoadCommand(const LoadCommandInfo &L) const {
Lang Hames697e7cd2016-12-04 01:56:10 +00003989 return getStruct<MachO::version_min_command>(*this, L.Ptr);
Jim Grosbach448334a2014-03-18 22:09:05 +00003990}
3991
Kevin Enderbya4579c42017-01-19 17:36:31 +00003992MachO::note_command
3993MachOObjectFile::getNoteLoadCommand(const LoadCommandInfo &L) const {
3994 return getStruct<MachO::note_command>(*this, L.Ptr);
3995}
3996
Steven Wu5b54a422017-01-23 20:07:55 +00003997MachO::build_version_command
3998MachOObjectFile::getBuildVersionLoadCommand(const LoadCommandInfo &L) const {
3999 return getStruct<MachO::build_version_command>(*this, L.Ptr);
4000}
4001
4002MachO::build_tool_version
4003MachOObjectFile::getBuildToolVersion(unsigned index) const {
4004 return getStruct<MachO::build_tool_version>(*this, BuildTools[index]);
4005}
4006
Tim Northover8f9590b2014-06-30 14:40:57 +00004007MachO::dylib_command
4008MachOObjectFile::getDylibIDLoadCommand(const LoadCommandInfo &L) const {
Lang Hames697e7cd2016-12-04 01:56:10 +00004009 return getStruct<MachO::dylib_command>(*this, L.Ptr);
Tim Northover8f9590b2014-06-30 14:40:57 +00004010}
4011
Kevin Enderby8ae63c12014-09-04 16:54:47 +00004012MachO::dyld_info_command
4013MachOObjectFile::getDyldInfoLoadCommand(const LoadCommandInfo &L) const {
Lang Hames697e7cd2016-12-04 01:56:10 +00004014 return getStruct<MachO::dyld_info_command>(*this, L.Ptr);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00004015}
4016
4017MachO::dylinker_command
4018MachOObjectFile::getDylinkerCommand(const LoadCommandInfo &L) const {
Lang Hames697e7cd2016-12-04 01:56:10 +00004019 return getStruct<MachO::dylinker_command>(*this, L.Ptr);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00004020}
4021
4022MachO::uuid_command
4023MachOObjectFile::getUuidCommand(const LoadCommandInfo &L) const {
Lang Hames697e7cd2016-12-04 01:56:10 +00004024 return getStruct<MachO::uuid_command>(*this, L.Ptr);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00004025}
4026
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00004027MachO::rpath_command
4028MachOObjectFile::getRpathCommand(const LoadCommandInfo &L) const {
Lang Hames697e7cd2016-12-04 01:56:10 +00004029 return getStruct<MachO::rpath_command>(*this, L.Ptr);
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00004030}
4031
Kevin Enderby8ae63c12014-09-04 16:54:47 +00004032MachO::source_version_command
4033MachOObjectFile::getSourceVersionCommand(const LoadCommandInfo &L) const {
Lang Hames697e7cd2016-12-04 01:56:10 +00004034 return getStruct<MachO::source_version_command>(*this, L.Ptr);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00004035}
4036
4037MachO::entry_point_command
4038MachOObjectFile::getEntryPointCommand(const LoadCommandInfo &L) const {
Lang Hames697e7cd2016-12-04 01:56:10 +00004039 return getStruct<MachO::entry_point_command>(*this, L.Ptr);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00004040}
4041
Kevin Enderby0804f4672014-12-16 23:25:52 +00004042MachO::encryption_info_command
4043MachOObjectFile::getEncryptionInfoCommand(const LoadCommandInfo &L) const {
Lang Hames697e7cd2016-12-04 01:56:10 +00004044 return getStruct<MachO::encryption_info_command>(*this, L.Ptr);
Kevin Enderby0804f4672014-12-16 23:25:52 +00004045}
4046
Kevin Enderby57538292014-12-17 01:01:30 +00004047MachO::encryption_info_command_64
4048MachOObjectFile::getEncryptionInfoCommand64(const LoadCommandInfo &L) const {
Lang Hames697e7cd2016-12-04 01:56:10 +00004049 return getStruct<MachO::encryption_info_command_64>(*this, L.Ptr);
Kevin Enderby57538292014-12-17 01:01:30 +00004050}
4051
Kevin Enderbyb4b79312014-12-18 19:24:35 +00004052MachO::sub_framework_command
4053MachOObjectFile::getSubFrameworkCommand(const LoadCommandInfo &L) const {
Lang Hames697e7cd2016-12-04 01:56:10 +00004054 return getStruct<MachO::sub_framework_command>(*this, L.Ptr);
Kevin Enderbyb4b79312014-12-18 19:24:35 +00004055}
Tim Northover8f9590b2014-06-30 14:40:57 +00004056
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00004057MachO::sub_umbrella_command
4058MachOObjectFile::getSubUmbrellaCommand(const LoadCommandInfo &L) const {
Lang Hames697e7cd2016-12-04 01:56:10 +00004059 return getStruct<MachO::sub_umbrella_command>(*this, L.Ptr);
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00004060}
4061
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00004062MachO::sub_library_command
4063MachOObjectFile::getSubLibraryCommand(const LoadCommandInfo &L) const {
Lang Hames697e7cd2016-12-04 01:56:10 +00004064 return getStruct<MachO::sub_library_command>(*this, L.Ptr);
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00004065}
4066
Kevin Enderby186eac32014-12-19 21:06:24 +00004067MachO::sub_client_command
4068MachOObjectFile::getSubClientCommand(const LoadCommandInfo &L) const {
Lang Hames697e7cd2016-12-04 01:56:10 +00004069 return getStruct<MachO::sub_client_command>(*this, L.Ptr);
Kevin Enderby186eac32014-12-19 21:06:24 +00004070}
4071
Kevin Enderby52e4ce42014-12-19 22:25:22 +00004072MachO::routines_command
4073MachOObjectFile::getRoutinesCommand(const LoadCommandInfo &L) const {
Lang Hames697e7cd2016-12-04 01:56:10 +00004074 return getStruct<MachO::routines_command>(*this, L.Ptr);
Kevin Enderby52e4ce42014-12-19 22:25:22 +00004075}
4076
4077MachO::routines_command_64
4078MachOObjectFile::getRoutinesCommand64(const LoadCommandInfo &L) const {
Lang Hames697e7cd2016-12-04 01:56:10 +00004079 return getStruct<MachO::routines_command_64>(*this, L.Ptr);
Kevin Enderby52e4ce42014-12-19 22:25:22 +00004080}
4081
Kevin Enderby48ef5342014-12-23 22:56:39 +00004082MachO::thread_command
4083MachOObjectFile::getThreadCommand(const LoadCommandInfo &L) const {
Lang Hames697e7cd2016-12-04 01:56:10 +00004084 return getStruct<MachO::thread_command>(*this, L.Ptr);
Kevin Enderby48ef5342014-12-23 22:56:39 +00004085}
4086
Charles Davis8bdfafd2013-09-01 04:28:48 +00004087MachO::any_relocation_info
Rafael Espindola56f976f2013-04-18 18:08:55 +00004088MachOObjectFile::getRelocation(DataRefImpl Rel) const {
Rafael Espindola128b8112014-04-03 23:51:28 +00004089 DataRefImpl Sec;
4090 Sec.d.a = Rel.d.a;
4091 uint32_t Offset;
4092 if (is64Bit()) {
4093 MachO::section_64 Sect = getSection64(Sec);
4094 Offset = Sect.reloff;
4095 } else {
4096 MachO::section Sect = getSection(Sec);
4097 Offset = Sect.reloff;
4098 }
4099
4100 auto P = reinterpret_cast<const MachO::any_relocation_info *>(
Lang Hames697e7cd2016-12-04 01:56:10 +00004101 getPtr(*this, Offset)) + Rel.d.b;
Rafael Espindola128b8112014-04-03 23:51:28 +00004102 return getStruct<MachO::any_relocation_info>(
Lang Hames697e7cd2016-12-04 01:56:10 +00004103 *this, reinterpret_cast<const char *>(P));
Rafael Espindola56f976f2013-04-18 18:08:55 +00004104}
4105
Charles Davis8bdfafd2013-09-01 04:28:48 +00004106MachO::data_in_code_entry
Kevin Enderby273ae012013-06-06 17:20:50 +00004107MachOObjectFile::getDice(DataRefImpl Rel) const {
4108 const char *P = reinterpret_cast<const char *>(Rel.p);
Lang Hames697e7cd2016-12-04 01:56:10 +00004109 return getStruct<MachO::data_in_code_entry>(*this, P);
Kevin Enderby273ae012013-06-06 17:20:50 +00004110}
4111
Alexey Samsonov13415ed2015-06-04 19:22:03 +00004112const MachO::mach_header &MachOObjectFile::getHeader() const {
Alexey Samsonovfa5edc52015-06-04 22:49:55 +00004113 return Header;
Rafael Espindola56f976f2013-04-18 18:08:55 +00004114}
4115
Alexey Samsonov13415ed2015-06-04 19:22:03 +00004116const MachO::mach_header_64 &MachOObjectFile::getHeader64() const {
4117 assert(is64Bit());
4118 return Header64;
Rafael Espindola6e040c02013-04-26 20:07:33 +00004119}
4120
Charles Davis8bdfafd2013-09-01 04:28:48 +00004121uint32_t MachOObjectFile::getIndirectSymbolTableEntry(
4122 const MachO::dysymtab_command &DLC,
4123 unsigned Index) const {
4124 uint64_t Offset = DLC.indirectsymoff + Index * sizeof(uint32_t);
Lang Hames697e7cd2016-12-04 01:56:10 +00004125 return getStruct<uint32_t>(*this, getPtr(*this, Offset));
Rafael Espindola6e040c02013-04-26 20:07:33 +00004126}
4127
Charles Davis8bdfafd2013-09-01 04:28:48 +00004128MachO::data_in_code_entry
Rafael Espindola6e040c02013-04-26 20:07:33 +00004129MachOObjectFile::getDataInCodeTableEntry(uint32_t DataOffset,
4130 unsigned Index) const {
Charles Davis8bdfafd2013-09-01 04:28:48 +00004131 uint64_t Offset = DataOffset + Index * sizeof(MachO::data_in_code_entry);
Lang Hames697e7cd2016-12-04 01:56:10 +00004132 return getStruct<MachO::data_in_code_entry>(*this, getPtr(*this, Offset));
Rafael Espindola6e040c02013-04-26 20:07:33 +00004133}
4134
Charles Davis8bdfafd2013-09-01 04:28:48 +00004135MachO::symtab_command MachOObjectFile::getSymtabLoadCommand() const {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00004136 if (SymtabLoadCmd)
Lang Hames697e7cd2016-12-04 01:56:10 +00004137 return getStruct<MachO::symtab_command>(*this, SymtabLoadCmd);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00004138
4139 // If there is no SymtabLoadCmd return a load command with zero'ed fields.
4140 MachO::symtab_command Cmd;
4141 Cmd.cmd = MachO::LC_SYMTAB;
4142 Cmd.cmdsize = sizeof(MachO::symtab_command);
4143 Cmd.symoff = 0;
4144 Cmd.nsyms = 0;
4145 Cmd.stroff = 0;
4146 Cmd.strsize = 0;
4147 return Cmd;
Rafael Espindola56f976f2013-04-18 18:08:55 +00004148}
4149
Charles Davis8bdfafd2013-09-01 04:28:48 +00004150MachO::dysymtab_command MachOObjectFile::getDysymtabLoadCommand() const {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00004151 if (DysymtabLoadCmd)
Lang Hames697e7cd2016-12-04 01:56:10 +00004152 return getStruct<MachO::dysymtab_command>(*this, DysymtabLoadCmd);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00004153
4154 // If there is no DysymtabLoadCmd return a load command with zero'ed fields.
4155 MachO::dysymtab_command Cmd;
4156 Cmd.cmd = MachO::LC_DYSYMTAB;
4157 Cmd.cmdsize = sizeof(MachO::dysymtab_command);
4158 Cmd.ilocalsym = 0;
4159 Cmd.nlocalsym = 0;
4160 Cmd.iextdefsym = 0;
4161 Cmd.nextdefsym = 0;
4162 Cmd.iundefsym = 0;
4163 Cmd.nundefsym = 0;
4164 Cmd.tocoff = 0;
4165 Cmd.ntoc = 0;
4166 Cmd.modtaboff = 0;
4167 Cmd.nmodtab = 0;
4168 Cmd.extrefsymoff = 0;
4169 Cmd.nextrefsyms = 0;
4170 Cmd.indirectsymoff = 0;
4171 Cmd.nindirectsyms = 0;
4172 Cmd.extreloff = 0;
4173 Cmd.nextrel = 0;
4174 Cmd.locreloff = 0;
4175 Cmd.nlocrel = 0;
4176 return Cmd;
Rafael Espindola6e040c02013-04-26 20:07:33 +00004177}
4178
Charles Davis8bdfafd2013-09-01 04:28:48 +00004179MachO::linkedit_data_command
Kevin Enderby273ae012013-06-06 17:20:50 +00004180MachOObjectFile::getDataInCodeLoadCommand() const {
4181 if (DataInCodeLoadCmd)
Lang Hames697e7cd2016-12-04 01:56:10 +00004182 return getStruct<MachO::linkedit_data_command>(*this, DataInCodeLoadCmd);
Kevin Enderby273ae012013-06-06 17:20:50 +00004183
4184 // If there is no DataInCodeLoadCmd return a load command with zero'ed fields.
Charles Davis8bdfafd2013-09-01 04:28:48 +00004185 MachO::linkedit_data_command Cmd;
4186 Cmd.cmd = MachO::LC_DATA_IN_CODE;
4187 Cmd.cmdsize = sizeof(MachO::linkedit_data_command);
4188 Cmd.dataoff = 0;
4189 Cmd.datasize = 0;
Kevin Enderby273ae012013-06-06 17:20:50 +00004190 return Cmd;
4191}
4192
Kevin Enderby9a509442015-01-27 21:28:24 +00004193MachO::linkedit_data_command
4194MachOObjectFile::getLinkOptHintsLoadCommand() const {
4195 if (LinkOptHintsLoadCmd)
Lang Hames697e7cd2016-12-04 01:56:10 +00004196 return getStruct<MachO::linkedit_data_command>(*this, LinkOptHintsLoadCmd);
Kevin Enderby9a509442015-01-27 21:28:24 +00004197
4198 // If there is no LinkOptHintsLoadCmd return a load command with zero'ed
4199 // fields.
4200 MachO::linkedit_data_command Cmd;
4201 Cmd.cmd = MachO::LC_LINKER_OPTIMIZATION_HINT;
4202 Cmd.cmdsize = sizeof(MachO::linkedit_data_command);
4203 Cmd.dataoff = 0;
4204 Cmd.datasize = 0;
4205 return Cmd;
4206}
4207
Nick Kledzikd04bc352014-08-30 00:20:14 +00004208ArrayRef<uint8_t> MachOObjectFile::getDyldInfoRebaseOpcodes() const {
NAKAMURA Takumi10c80e72015-09-22 11:19:03 +00004209 if (!DyldInfoLoadCmd)
Craig Topper0013be12015-09-21 05:32:41 +00004210 return None;
Nick Kledzikd04bc352014-08-30 00:20:14 +00004211
NAKAMURA Takumi70ad98a2015-09-22 11:13:55 +00004212 MachO::dyld_info_command DyldInfo =
Lang Hames697e7cd2016-12-04 01:56:10 +00004213 getStruct<MachO::dyld_info_command>(*this, DyldInfoLoadCmd);
NAKAMURA Takumi70ad98a2015-09-22 11:13:55 +00004214 const uint8_t *Ptr =
Lang Hames697e7cd2016-12-04 01:56:10 +00004215 reinterpret_cast<const uint8_t *>(getPtr(*this, DyldInfo.rebase_off));
Craig Topper0013be12015-09-21 05:32:41 +00004216 return makeArrayRef(Ptr, DyldInfo.rebase_size);
Nick Kledzikd04bc352014-08-30 00:20:14 +00004217}
4218
4219ArrayRef<uint8_t> MachOObjectFile::getDyldInfoBindOpcodes() const {
NAKAMURA Takumi10c80e72015-09-22 11:19:03 +00004220 if (!DyldInfoLoadCmd)
Craig Topper0013be12015-09-21 05:32:41 +00004221 return None;
Nick Kledzikd04bc352014-08-30 00:20:14 +00004222
NAKAMURA Takumi70ad98a2015-09-22 11:13:55 +00004223 MachO::dyld_info_command DyldInfo =
Lang Hames697e7cd2016-12-04 01:56:10 +00004224 getStruct<MachO::dyld_info_command>(*this, DyldInfoLoadCmd);
NAKAMURA Takumi70ad98a2015-09-22 11:13:55 +00004225 const uint8_t *Ptr =
Lang Hames697e7cd2016-12-04 01:56:10 +00004226 reinterpret_cast<const uint8_t *>(getPtr(*this, DyldInfo.bind_off));
Craig Topper0013be12015-09-21 05:32:41 +00004227 return makeArrayRef(Ptr, DyldInfo.bind_size);
Nick Kledzikd04bc352014-08-30 00:20:14 +00004228}
4229
4230ArrayRef<uint8_t> MachOObjectFile::getDyldInfoWeakBindOpcodes() const {
NAKAMURA Takumi10c80e72015-09-22 11:19:03 +00004231 if (!DyldInfoLoadCmd)
Craig Topper0013be12015-09-21 05:32:41 +00004232 return None;
Nick Kledzikd04bc352014-08-30 00:20:14 +00004233
NAKAMURA Takumi70ad98a2015-09-22 11:13:55 +00004234 MachO::dyld_info_command DyldInfo =
Lang Hames697e7cd2016-12-04 01:56:10 +00004235 getStruct<MachO::dyld_info_command>(*this, DyldInfoLoadCmd);
NAKAMURA Takumi70ad98a2015-09-22 11:13:55 +00004236 const uint8_t *Ptr =
Lang Hames697e7cd2016-12-04 01:56:10 +00004237 reinterpret_cast<const uint8_t *>(getPtr(*this, DyldInfo.weak_bind_off));
Craig Topper0013be12015-09-21 05:32:41 +00004238 return makeArrayRef(Ptr, DyldInfo.weak_bind_size);
Nick Kledzikd04bc352014-08-30 00:20:14 +00004239}
4240
4241ArrayRef<uint8_t> MachOObjectFile::getDyldInfoLazyBindOpcodes() const {
NAKAMURA Takumi10c80e72015-09-22 11:19:03 +00004242 if (!DyldInfoLoadCmd)
Craig Topper0013be12015-09-21 05:32:41 +00004243 return None;
Nick Kledzikd04bc352014-08-30 00:20:14 +00004244
NAKAMURA Takumi70ad98a2015-09-22 11:13:55 +00004245 MachO::dyld_info_command DyldInfo =
Lang Hames697e7cd2016-12-04 01:56:10 +00004246 getStruct<MachO::dyld_info_command>(*this, DyldInfoLoadCmd);
NAKAMURA Takumi70ad98a2015-09-22 11:13:55 +00004247 const uint8_t *Ptr =
Lang Hames697e7cd2016-12-04 01:56:10 +00004248 reinterpret_cast<const uint8_t *>(getPtr(*this, DyldInfo.lazy_bind_off));
Craig Topper0013be12015-09-21 05:32:41 +00004249 return makeArrayRef(Ptr, DyldInfo.lazy_bind_size);
Nick Kledzikd04bc352014-08-30 00:20:14 +00004250}
4251
4252ArrayRef<uint8_t> MachOObjectFile::getDyldInfoExportsTrie() const {
NAKAMURA Takumi10c80e72015-09-22 11:19:03 +00004253 if (!DyldInfoLoadCmd)
Craig Topper0013be12015-09-21 05:32:41 +00004254 return None;
Nick Kledzikd04bc352014-08-30 00:20:14 +00004255
NAKAMURA Takumi70ad98a2015-09-22 11:13:55 +00004256 MachO::dyld_info_command DyldInfo =
Lang Hames697e7cd2016-12-04 01:56:10 +00004257 getStruct<MachO::dyld_info_command>(*this, DyldInfoLoadCmd);
NAKAMURA Takumi70ad98a2015-09-22 11:13:55 +00004258 const uint8_t *Ptr =
Lang Hames697e7cd2016-12-04 01:56:10 +00004259 reinterpret_cast<const uint8_t *>(getPtr(*this, DyldInfo.export_off));
Craig Topper0013be12015-09-21 05:32:41 +00004260 return makeArrayRef(Ptr, DyldInfo.export_size);
Nick Kledzikd04bc352014-08-30 00:20:14 +00004261}
4262
Alexander Potapenko6909b5b2014-10-15 23:35:45 +00004263ArrayRef<uint8_t> MachOObjectFile::getUuid() const {
4264 if (!UuidLoadCmd)
Craig Topper0013be12015-09-21 05:32:41 +00004265 return None;
Benjamin Kramer014601d2014-10-24 15:52:05 +00004266 // Returning a pointer is fine as uuid doesn't need endian swapping.
4267 const char *Ptr = UuidLoadCmd + offsetof(MachO::uuid_command, uuid);
Craig Topper0013be12015-09-21 05:32:41 +00004268 return makeArrayRef(reinterpret_cast<const uint8_t *>(Ptr), 16);
Alexander Potapenko6909b5b2014-10-15 23:35:45 +00004269}
Nick Kledzikd04bc352014-08-30 00:20:14 +00004270
Rafael Espindola6e040c02013-04-26 20:07:33 +00004271StringRef MachOObjectFile::getStringTableData() const {
Charles Davis8bdfafd2013-09-01 04:28:48 +00004272 MachO::symtab_command S = getSymtabLoadCommand();
4273 return getData().substr(S.stroff, S.strsize);
Rafael Espindola6e040c02013-04-26 20:07:33 +00004274}
4275
Rafael Espindola56f976f2013-04-18 18:08:55 +00004276bool MachOObjectFile::is64Bit() const {
4277 return getType() == getMachOType(false, true) ||
Lang Hames84bc8182014-07-15 19:35:22 +00004278 getType() == getMachOType(true, true);
Rafael Espindola56f976f2013-04-18 18:08:55 +00004279}
4280
4281void MachOObjectFile::ReadULEB128s(uint64_t Index,
4282 SmallVectorImpl<uint64_t> &Out) const {
4283 DataExtractor extractor(ObjectFile::getData(), true, 0);
4284
4285 uint32_t offset = Index;
4286 uint64_t data = 0;
4287 while (uint64_t delta = extractor.getULEB128(&offset)) {
4288 data += delta;
4289 Out.push_back(data);
4290 }
4291}
4292
Rafael Espindolac66d7612014-08-17 19:09:37 +00004293bool MachOObjectFile::isRelocatableObject() const {
4294 return getHeader().filetype == MachO::MH_OBJECT;
4295}
4296
Lang Hamesff044b12016-03-25 23:11:52 +00004297Expected<std::unique_ptr<MachOObjectFile>>
Kevin Enderby79d6c632016-10-24 21:15:11 +00004298ObjectFile::createMachOObjectFile(MemoryBufferRef Buffer,
4299 uint32_t UniversalCputype,
4300 uint32_t UniversalIndex) {
Rafael Espindola48af1c22014-08-19 18:44:46 +00004301 StringRef Magic = Buffer.getBuffer().slice(0, 4);
Lang Hames82627642016-03-25 21:59:14 +00004302 if (Magic == "\xFE\xED\xFA\xCE")
Kevin Enderby79d6c632016-10-24 21:15:11 +00004303 return MachOObjectFile::create(Buffer, false, false,
4304 UniversalCputype, UniversalIndex);
David Blaikieb805f732016-03-28 17:45:48 +00004305 if (Magic == "\xCE\xFA\xED\xFE")
Kevin Enderby79d6c632016-10-24 21:15:11 +00004306 return MachOObjectFile::create(Buffer, true, false,
4307 UniversalCputype, UniversalIndex);
David Blaikieb805f732016-03-28 17:45:48 +00004308 if (Magic == "\xFE\xED\xFA\xCF")
Kevin Enderby79d6c632016-10-24 21:15:11 +00004309 return MachOObjectFile::create(Buffer, false, true,
4310 UniversalCputype, UniversalIndex);
David Blaikieb805f732016-03-28 17:45:48 +00004311 if (Magic == "\xCF\xFA\xED\xFE")
Kevin Enderby79d6c632016-10-24 21:15:11 +00004312 return MachOObjectFile::create(Buffer, true, true,
4313 UniversalCputype, UniversalIndex);
Kevin Enderbyd4e075b2016-05-06 20:16:28 +00004314 return make_error<GenericBinaryError>("Unrecognized MachO magic number",
Justin Bogner2a42da92016-05-05 23:59:57 +00004315 object_error::invalid_file_type);
Rafael Espindola56f976f2013-04-18 18:08:55 +00004316}
Wolfgang Pieb77d3e932017-06-06 01:22:34 +00004317
4318StringRef MachOObjectFile::mapDebugSectionName(StringRef Name) const {
4319 return StringSwitch<StringRef>(Name)
4320 .Case("debug_str_offs", "debug_str_offsets")
4321 .Default(Name);
4322}