blob: ad52235a50df8386b7dab51baf12a798fa99056e [file] [log] [blame]
Eric Christopher7b015c72011-04-22 03:19:48 +00001//===- MachOObjectFile.cpp - Mach-O object file binding ---------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the MachOObjectFile class, which binds the MachOObject
11// class to the generic ObjectFile wrapper.
12//
13//===----------------------------------------------------------------------===//
14
Owen Anderson27c579d2011-10-11 17:32:27 +000015#include "llvm/Object/MachO.h"
Tim Northover00ed9962014-03-29 10:18:08 +000016#include "llvm/ADT/STLExtras.h"
Rafael Espindola72318b42014-08-08 16:30:17 +000017#include "llvm/ADT/StringSwitch.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/ADT/Triple.h"
Rafael Espindola421305a2013-04-07 20:01:29 +000019#include "llvm/Support/DataExtractor.h"
Nick Kledzikac431442014-09-12 21:34:15 +000020#include "llvm/Support/Debug.h"
Owen Andersonbc14bd32011-10-26 20:42:54 +000021#include "llvm/Support/Format.h"
Rafael Espindola56f976f2013-04-18 18:08:55 +000022#include "llvm/Support/Host.h"
Nick Kledzikd04bc352014-08-30 00:20:14 +000023#include "llvm/Support/LEB128.h"
24#include "llvm/Support/MachO.h"
Eric Christopher7b015c72011-04-22 03:19:48 +000025#include "llvm/Support/MemoryBuffer.h"
Jakub Staszak84a0ae72013-08-21 01:20:11 +000026#include "llvm/Support/raw_ostream.h"
Eric Christopher7b015c72011-04-22 03:19:48 +000027#include <cctype>
28#include <cstring>
29#include <limits>
Kevin Enderbyd5039402016-10-31 20:29:48 +000030#include <list>
Eric Christopher7b015c72011-04-22 03:19:48 +000031
32using namespace llvm;
33using namespace object;
34
Artyom Skrobov7d602f72014-07-20 12:08:28 +000035namespace {
36 struct section_base {
37 char sectname[16];
38 char segname[16];
39 };
40}
Rafael Espindola56f976f2013-04-18 18:08:55 +000041
Lang Hames9e964f32016-03-25 17:25:34 +000042static Error
Kevin Enderbyd4e075b2016-05-06 20:16:28 +000043malformedError(Twine Msg) {
Kevin Enderby89134962016-05-05 23:41:05 +000044 std::string StringMsg = "truncated or malformed object (" + Msg.str() + ")";
Kevin Enderbyd4e075b2016-05-06 20:16:28 +000045 return make_error<GenericBinaryError>(std::move(StringMsg),
Kevin Enderby89134962016-05-05 23:41:05 +000046 object_error::parse_failed);
Lang Hames9e964f32016-03-25 17:25:34 +000047}
48
Alexey Samsonov9f336632015-06-04 19:45:22 +000049// FIXME: Replace all uses of this function with getStructOrErr.
Filipe Cabecinhas40139502015-01-15 22:52:38 +000050template <typename T>
Artyom Skrobov7d602f72014-07-20 12:08:28 +000051static T getStruct(const MachOObjectFile *O, const char *P) {
Filipe Cabecinhas40139502015-01-15 22:52:38 +000052 // Don't read before the beginning or past the end of the file
53 if (P < O->getData().begin() || P + sizeof(T) > O->getData().end())
54 report_fatal_error("Malformed MachO file.");
55
Rafael Espindola3cdeb172013-04-19 13:45:05 +000056 T Cmd;
57 memcpy(&Cmd, P, sizeof(T));
58 if (O->isLittleEndian() != sys::IsLittleEndianHost)
Artyom Skrobov78d5daf2014-07-18 09:26:16 +000059 MachO::swapStruct(Cmd);
Rafael Espindola3cdeb172013-04-19 13:45:05 +000060 return Cmd;
Rafael Espindola56f976f2013-04-18 18:08:55 +000061}
62
Alexey Samsonov9f336632015-06-04 19:45:22 +000063template <typename T>
Lang Hames9e964f32016-03-25 17:25:34 +000064static Expected<T> getStructOrErr(const MachOObjectFile *O, const char *P) {
Alexey Samsonov9f336632015-06-04 19:45:22 +000065 // Don't read before the beginning or past the end of the file
66 if (P < O->getData().begin() || P + sizeof(T) > O->getData().end())
Kevin Enderbyd4e075b2016-05-06 20:16:28 +000067 return malformedError("Structure read out-of-range");
Alexey Samsonov9f336632015-06-04 19:45:22 +000068
69 T Cmd;
70 memcpy(&Cmd, P, sizeof(T));
71 if (O->isLittleEndian() != sys::IsLittleEndianHost)
72 MachO::swapStruct(Cmd);
73 return Cmd;
74}
75
Rafael Espindola6e040c02013-04-26 20:07:33 +000076static const char *
77getSectionPtr(const MachOObjectFile *O, MachOObjectFile::LoadCommandInfo L,
78 unsigned Sec) {
Rafael Espindola56f976f2013-04-18 18:08:55 +000079 uintptr_t CommandAddr = reinterpret_cast<uintptr_t>(L.Ptr);
80
81 bool Is64 = O->is64Bit();
Charles Davis8bdfafd2013-09-01 04:28:48 +000082 unsigned SegmentLoadSize = Is64 ? sizeof(MachO::segment_command_64) :
83 sizeof(MachO::segment_command);
84 unsigned SectionSize = Is64 ? sizeof(MachO::section_64) :
85 sizeof(MachO::section);
Rafael Espindola56f976f2013-04-18 18:08:55 +000086
87 uintptr_t SectionAddr = CommandAddr + SegmentLoadSize + Sec * SectionSize;
Charles Davis1827bd82013-08-27 05:38:30 +000088 return reinterpret_cast<const char*>(SectionAddr);
Rafael Espindola60689982013-04-07 19:05:30 +000089}
90
Rafael Espindola56f976f2013-04-18 18:08:55 +000091static const char *getPtr(const MachOObjectFile *O, size_t Offset) {
92 return O->getData().substr(Offset, 1).data();
Rafael Espindola60689982013-04-07 19:05:30 +000093}
94
Artyom Skrobov78d5daf2014-07-18 09:26:16 +000095static MachO::nlist_base
Rafael Espindola56f976f2013-04-18 18:08:55 +000096getSymbolTableEntryBase(const MachOObjectFile *O, DataRefImpl DRI) {
Rafael Espindola75c30362013-04-24 19:47:55 +000097 const char *P = reinterpret_cast<const char *>(DRI.p);
Artyom Skrobov78d5daf2014-07-18 09:26:16 +000098 return getStruct<MachO::nlist_base>(O, P);
Eric Christopher7b015c72011-04-22 03:19:48 +000099}
100
Rafael Espindola56f976f2013-04-18 18:08:55 +0000101static StringRef parseSegmentOrSectionName(const char *P) {
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000102 if (P[15] == 0)
103 // Null terminated.
104 return P;
105 // Not null terminated, so this is a 16 char string.
106 return StringRef(P, 16);
107}
108
Rafael Espindola56f976f2013-04-18 18:08:55 +0000109// Helper to advance a section or symbol iterator multiple increments at a time.
110template<class T>
Rafael Espindola5e812af2014-01-30 02:49:50 +0000111static void advance(T &it, size_t Val) {
112 while (Val--)
113 ++it;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000114}
115
116static unsigned getCPUType(const MachOObjectFile *O) {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000117 return O->getHeader().cputype;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000118}
119
Charles Davis8bdfafd2013-09-01 04:28:48 +0000120static uint32_t
121getPlainRelocationAddress(const MachO::any_relocation_info &RE) {
122 return RE.r_word0;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000123}
124
125static unsigned
Charles Davis8bdfafd2013-09-01 04:28:48 +0000126getScatteredRelocationAddress(const MachO::any_relocation_info &RE) {
127 return RE.r_word0 & 0xffffff;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000128}
129
130static bool getPlainRelocationPCRel(const MachOObjectFile *O,
Charles Davis8bdfafd2013-09-01 04:28:48 +0000131 const MachO::any_relocation_info &RE) {
Rafael Espindola56f976f2013-04-18 18:08:55 +0000132 if (O->isLittleEndian())
Charles Davis8bdfafd2013-09-01 04:28:48 +0000133 return (RE.r_word1 >> 24) & 1;
134 return (RE.r_word1 >> 7) & 1;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000135}
136
137static bool
138getScatteredRelocationPCRel(const MachOObjectFile *O,
Charles Davis8bdfafd2013-09-01 04:28:48 +0000139 const MachO::any_relocation_info &RE) {
140 return (RE.r_word0 >> 30) & 1;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000141}
142
143static unsigned getPlainRelocationLength(const MachOObjectFile *O,
Charles Davis8bdfafd2013-09-01 04:28:48 +0000144 const MachO::any_relocation_info &RE) {
Rafael Espindola56f976f2013-04-18 18:08:55 +0000145 if (O->isLittleEndian())
Charles Davis8bdfafd2013-09-01 04:28:48 +0000146 return (RE.r_word1 >> 25) & 3;
147 return (RE.r_word1 >> 5) & 3;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000148}
149
150static unsigned
Charles Davis8bdfafd2013-09-01 04:28:48 +0000151getScatteredRelocationLength(const MachO::any_relocation_info &RE) {
152 return (RE.r_word0 >> 28) & 3;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000153}
154
155static unsigned getPlainRelocationType(const MachOObjectFile *O,
Charles Davis8bdfafd2013-09-01 04:28:48 +0000156 const MachO::any_relocation_info &RE) {
Rafael Espindola56f976f2013-04-18 18:08:55 +0000157 if (O->isLittleEndian())
Charles Davis8bdfafd2013-09-01 04:28:48 +0000158 return RE.r_word1 >> 28;
159 return RE.r_word1 & 0xf;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000160}
161
Rafael Espindola56f976f2013-04-18 18:08:55 +0000162static uint32_t getSectionFlags(const MachOObjectFile *O,
163 DataRefImpl Sec) {
164 if (O->is64Bit()) {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000165 MachO::section_64 Sect = O->getSection64(Sec);
166 return Sect.flags;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000167 }
Charles Davis8bdfafd2013-09-01 04:28:48 +0000168 MachO::section Sect = O->getSection(Sec);
169 return Sect.flags;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000170}
171
Lang Hames9e964f32016-03-25 17:25:34 +0000172static Expected<MachOObjectFile::LoadCommandInfo>
Kevin Enderbya8e3ab02016-05-03 23:13:50 +0000173getLoadCommandInfo(const MachOObjectFile *Obj, const char *Ptr,
174 uint32_t LoadCommandIndex) {
Lang Hames9e964f32016-03-25 17:25:34 +0000175 if (auto CmdOrErr = getStructOrErr<MachO::load_command>(Obj, Ptr)) {
176 if (CmdOrErr->cmdsize < 8)
Kevin Enderbyd4e075b2016-05-06 20:16:28 +0000177 return malformedError("load command " + Twine(LoadCommandIndex) +
Kevin Enderby89134962016-05-05 23:41:05 +0000178 " with size less than 8 bytes");
Lang Hames9e964f32016-03-25 17:25:34 +0000179 return MachOObjectFile::LoadCommandInfo({Ptr, *CmdOrErr});
180 } else
181 return CmdOrErr.takeError();
Alexey Samsonov4fdbed32015-06-04 19:34:14 +0000182}
183
Lang Hames9e964f32016-03-25 17:25:34 +0000184static Expected<MachOObjectFile::LoadCommandInfo>
Alexey Samsonov4fdbed32015-06-04 19:34:14 +0000185getFirstLoadCommandInfo(const MachOObjectFile *Obj) {
186 unsigned HeaderSize = Obj->is64Bit() ? sizeof(MachO::mach_header_64)
187 : sizeof(MachO::mach_header);
Kevin Enderby9d0c9452016-08-31 17:57:46 +0000188 if (sizeof(MachO::load_command) > Obj->getHeader().sizeofcmds)
Kevin Enderbyd4e075b2016-05-06 20:16:28 +0000189 return malformedError("load command 0 extends past the end all load "
Kevin Enderby89134962016-05-05 23:41:05 +0000190 "commands in the file");
Kevin Enderbya8e3ab02016-05-03 23:13:50 +0000191 return getLoadCommandInfo(Obj, getPtr(Obj, HeaderSize), 0);
Alexey Samsonov4fdbed32015-06-04 19:34:14 +0000192}
193
Lang Hames9e964f32016-03-25 17:25:34 +0000194static Expected<MachOObjectFile::LoadCommandInfo>
Kevin Enderby368e7142016-05-03 17:16:08 +0000195getNextLoadCommandInfo(const MachOObjectFile *Obj, uint32_t LoadCommandIndex,
Alexey Samsonov4fdbed32015-06-04 19:34:14 +0000196 const MachOObjectFile::LoadCommandInfo &L) {
Kevin Enderby368e7142016-05-03 17:16:08 +0000197 unsigned HeaderSize = Obj->is64Bit() ? sizeof(MachO::mach_header_64)
198 : sizeof(MachO::mach_header);
Kevin Enderby9d0c9452016-08-31 17:57:46 +0000199 if (L.Ptr + L.C.cmdsize + sizeof(MachO::load_command) >
Kevin Enderby368e7142016-05-03 17:16:08 +0000200 Obj->getData().data() + HeaderSize + Obj->getHeader().sizeofcmds)
Kevin Enderbyd4e075b2016-05-06 20:16:28 +0000201 return malformedError("load command " + Twine(LoadCommandIndex + 1) +
Kevin Enderby89134962016-05-05 23:41:05 +0000202 " extends past the end all load commands in the file");
Kevin Enderbya8e3ab02016-05-03 23:13:50 +0000203 return getLoadCommandInfo(Obj, L.Ptr + L.C.cmdsize, LoadCommandIndex + 1);
Alexey Samsonov4fdbed32015-06-04 19:34:14 +0000204}
205
Alexey Samsonov9f336632015-06-04 19:45:22 +0000206template <typename T>
207static void parseHeader(const MachOObjectFile *Obj, T &Header,
Lang Hames9e964f32016-03-25 17:25:34 +0000208 Error &Err) {
Kevin Enderby87025742016-04-13 21:17:58 +0000209 if (sizeof(T) > Obj->getData().size()) {
Kevin Enderbyd4e075b2016-05-06 20:16:28 +0000210 Err = malformedError("the mach header extends past the end of the "
Kevin Enderby89134962016-05-05 23:41:05 +0000211 "file");
Kevin Enderby87025742016-04-13 21:17:58 +0000212 return;
213 }
Lang Hames9e964f32016-03-25 17:25:34 +0000214 if (auto HeaderOrErr = getStructOrErr<T>(Obj, getPtr(Obj, 0)))
215 Header = *HeaderOrErr;
Alexey Samsonov9f336632015-06-04 19:45:22 +0000216 else
Lang Hames9e964f32016-03-25 17:25:34 +0000217 Err = HeaderOrErr.takeError();
Alexey Samsonov9f336632015-06-04 19:45:22 +0000218}
219
Kevin Enderbyd5039402016-10-31 20:29:48 +0000220// This is used to check for overlapping of Mach-O elements.
221struct MachOElement {
222 uint64_t Offset;
223 uint64_t Size;
224 const char *Name;
225};
226
227static Error checkOverlappingElement(std::list<MachOElement> &Elements,
228 uint64_t Offset, uint64_t Size,
229 const char *Name) {
230 if (Size == 0)
231 return Error::success();
232
233 for (auto it=Elements.begin() ; it != Elements.end(); ++it) {
234 auto E = *it;
235 if ((Offset >= E.Offset && Offset < E.Offset + E.Size) ||
236 (Offset + Size > E.Offset && Offset + Size < E.Offset + E.Size) ||
237 (Offset <= E.Offset && Offset + Size >= E.Offset + E.Size))
238 return malformedError(Twine(Name) + " at offset " + Twine(Offset) +
239 " with a size of " + Twine(Size) + ", overlaps " +
240 E.Name + " at offset " + Twine(E.Offset) + " with "
241 "a size of " + Twine(E.Size));
242 auto nt = it;
243 nt++;
244 if (nt != Elements.end()) {
245 auto N = *nt;
246 if (Offset + Size <= N.Offset) {
247 Elements.insert(nt, {Offset, Size, Name});
248 return Error::success();
249 }
250 }
251 }
252 Elements.push_back({Offset, Size, Name});
253 return Error::success();
254}
255
Alexey Samsonove1a76ab2015-06-04 22:08:37 +0000256// Parses LC_SEGMENT or LC_SEGMENT_64 load command, adds addresses of all
257// sections to \param Sections, and optionally sets
258// \param IsPageZeroSegment to true.
Kevin Enderbyc614d282016-08-12 20:10:25 +0000259template <typename Segment, typename Section>
Lang Hames9e964f32016-03-25 17:25:34 +0000260static Error parseSegmentLoadCommand(
Alexey Samsonove1a76ab2015-06-04 22:08:37 +0000261 const MachOObjectFile *Obj, const MachOObjectFile::LoadCommandInfo &Load,
Kevin Enderbyb34e3a12016-05-05 17:43:35 +0000262 SmallVectorImpl<const char *> &Sections, bool &IsPageZeroSegment,
Kevin Enderbyfbebe162016-11-02 21:08:39 +0000263 uint32_t LoadCommandIndex, const char *CmdName, uint64_t SizeOfHeaders,
264 std::list<MachOElement> &Elements) {
Kevin Enderbyc614d282016-08-12 20:10:25 +0000265 const unsigned SegmentLoadSize = sizeof(Segment);
Alexey Samsonove1a76ab2015-06-04 22:08:37 +0000266 if (Load.C.cmdsize < SegmentLoadSize)
Kevin Enderbyd4e075b2016-05-06 20:16:28 +0000267 return malformedError("load command " + Twine(LoadCommandIndex) +
Kevin Enderby89134962016-05-05 23:41:05 +0000268 " " + CmdName + " cmdsize too small");
Kevin Enderbyc614d282016-08-12 20:10:25 +0000269 if (auto SegOrErr = getStructOrErr<Segment>(Obj, Load.Ptr)) {
270 Segment S = SegOrErr.get();
271 const unsigned SectionSize = sizeof(Section);
272 uint64_t FileSize = Obj->getData().size();
Lang Hames9e964f32016-03-25 17:25:34 +0000273 if (S.nsects > std::numeric_limits<uint32_t>::max() / SectionSize ||
274 S.nsects * SectionSize > Load.C.cmdsize - SegmentLoadSize)
Kevin Enderbyd4e075b2016-05-06 20:16:28 +0000275 return malformedError("load command " + Twine(LoadCommandIndex) +
NAKAMURA Takumi9d0b5312016-08-22 00:58:47 +0000276 " inconsistent cmdsize in " + CmdName +
Kevin Enderby89134962016-05-05 23:41:05 +0000277 " for the number of sections");
Lang Hames9e964f32016-03-25 17:25:34 +0000278 for (unsigned J = 0; J < S.nsects; ++J) {
279 const char *Sec = getSectionPtr(Obj, Load, J);
280 Sections.push_back(Sec);
Kevin Enderbyc614d282016-08-12 20:10:25 +0000281 Section s = getStruct<Section>(Obj, Sec);
282 if (Obj->getHeader().filetype != MachO::MH_DYLIB_STUB &&
283 Obj->getHeader().filetype != MachO::MH_DSYM &&
284 s.flags != MachO::S_ZEROFILL &&
285 s.flags != MachO::S_THREAD_LOCAL_ZEROFILL &&
286 s.offset > FileSize)
287 return malformedError("offset field of section " + Twine(J) + " in " +
288 CmdName + " command " + Twine(LoadCommandIndex) +
289 " extends past the end of the file");
290 if (Obj->getHeader().filetype != MachO::MH_DYLIB_STUB &&
291 Obj->getHeader().filetype != MachO::MH_DSYM &&
292 s.flags != MachO::S_ZEROFILL &&
NAKAMURA Takumi59a20642016-08-22 00:58:04 +0000293 s.flags != MachO::S_THREAD_LOCAL_ZEROFILL && S.fileoff == 0 &&
294 s.offset < SizeOfHeaders && s.size != 0)
Kevin Enderbyc614d282016-08-12 20:10:25 +0000295 return malformedError("offset field of section " + Twine(J) + " in " +
296 CmdName + " command " + Twine(LoadCommandIndex) +
297 " not past the headers of the file");
298 uint64_t BigSize = s.offset;
299 BigSize += s.size;
300 if (Obj->getHeader().filetype != MachO::MH_DYLIB_STUB &&
301 Obj->getHeader().filetype != MachO::MH_DSYM &&
302 s.flags != MachO::S_ZEROFILL &&
303 s.flags != MachO::S_THREAD_LOCAL_ZEROFILL &&
304 BigSize > FileSize)
305 return malformedError("offset field plus size field of section " +
306 Twine(J) + " in " + CmdName + " command " +
307 Twine(LoadCommandIndex) +
308 " extends past the end of the file");
309 if (Obj->getHeader().filetype != MachO::MH_DYLIB_STUB &&
310 Obj->getHeader().filetype != MachO::MH_DSYM &&
311 s.flags != MachO::S_ZEROFILL &&
312 s.flags != MachO::S_THREAD_LOCAL_ZEROFILL &&
313 s.size > S.filesize)
314 return malformedError("size field of section " +
315 Twine(J) + " in " + CmdName + " command " +
316 Twine(LoadCommandIndex) +
317 " greater than the segment");
318 if (Obj->getHeader().filetype != MachO::MH_DYLIB_STUB &&
NAKAMURA Takumi59a20642016-08-22 00:58:04 +0000319 Obj->getHeader().filetype != MachO::MH_DSYM && s.size != 0 &&
320 s.addr < S.vmaddr)
321 return malformedError("addr field of section " + Twine(J) + " in " +
322 CmdName + " command " + Twine(LoadCommandIndex) +
323 " less than the segment's vmaddr");
Kevin Enderbyc614d282016-08-12 20:10:25 +0000324 BigSize = s.addr;
325 BigSize += s.size;
326 uint64_t BigEnd = S.vmaddr;
327 BigEnd += S.vmsize;
328 if (S.vmsize != 0 && s.size != 0 && BigSize > BigEnd)
NAKAMURA Takumi59a20642016-08-22 00:58:04 +0000329 return malformedError("addr field plus size of section " + Twine(J) +
330 " in " + CmdName + " command " +
331 Twine(LoadCommandIndex) +
332 " greater than than "
Kevin Enderbyc614d282016-08-12 20:10:25 +0000333 "the segment's vmaddr plus vmsize");
Kevin Enderbyfbebe162016-11-02 21:08:39 +0000334 if (Obj->getHeader().filetype != MachO::MH_DYLIB_STUB &&
335 Obj->getHeader().filetype != MachO::MH_DSYM &&
336 s.flags != MachO::S_ZEROFILL &&
337 s.flags != MachO::S_THREAD_LOCAL_ZEROFILL)
338 if (Error Err = checkOverlappingElement(Elements, s.offset, s.size,
339 "section contents"))
340 return Err;
Kevin Enderbyc614d282016-08-12 20:10:25 +0000341 if (s.reloff > FileSize)
NAKAMURA Takumi59a20642016-08-22 00:58:04 +0000342 return malformedError("reloff field of section " + Twine(J) + " in " +
343 CmdName + " command " + Twine(LoadCommandIndex) +
Kevin Enderbyc614d282016-08-12 20:10:25 +0000344 " extends past the end of the file");
345 BigSize = s.nreloc;
346 BigSize *= sizeof(struct MachO::relocation_info);
347 BigSize += s.reloff;
348 if (BigSize > FileSize)
349 return malformedError("reloff field plus nreloc field times sizeof("
350 "struct relocation_info) of section " +
351 Twine(J) + " in " + CmdName + " command " +
NAKAMURA Takumi59a20642016-08-22 00:58:04 +0000352 Twine(LoadCommandIndex) +
Kevin Enderbyc614d282016-08-12 20:10:25 +0000353 " extends past the end of the file");
Kevin Enderbyfbebe162016-11-02 21:08:39 +0000354 if (Error Err = checkOverlappingElement(Elements, s.reloff, s.nreloc *
355 sizeof(struct
356 MachO::relocation_info),
357 "section relocation entries"))
358 return Err;
Lang Hames9e964f32016-03-25 17:25:34 +0000359 }
Kevin Enderby600fb3f2016-08-05 18:19:40 +0000360 if (S.fileoff > FileSize)
361 return malformedError("load command " + Twine(LoadCommandIndex) +
NAKAMURA Takumi9d0b5312016-08-22 00:58:47 +0000362 " fileoff field in " + CmdName +
Kevin Enderby600fb3f2016-08-05 18:19:40 +0000363 " extends past the end of the file");
Kevin Enderbyc614d282016-08-12 20:10:25 +0000364 uint64_t BigSize = S.fileoff;
365 BigSize += S.filesize;
366 if (BigSize > FileSize)
367 return malformedError("load command " + Twine(LoadCommandIndex) +
368 " fileoff field plus filesize field in " +
369 CmdName + " extends past the end of the file");
370 if (S.vmsize != 0 && S.filesize > S.vmsize)
371 return malformedError("load command " + Twine(LoadCommandIndex) +
372 " fileoff field in " + CmdName +
373 " greater than vmsize field");
Lang Hames9e964f32016-03-25 17:25:34 +0000374 IsPageZeroSegment |= StringRef("__PAGEZERO").equals(S.segname);
375 } else
376 return SegOrErr.takeError();
377
378 return Error::success();
Alexey Samsonove1a76ab2015-06-04 22:08:37 +0000379}
380
Kevin Enderby0e52c922016-08-26 19:34:07 +0000381static Error checkSymtabCommand(const MachOObjectFile *Obj,
382 const MachOObjectFile::LoadCommandInfo &Load,
383 uint32_t LoadCommandIndex,
Kevin Enderbyd5039402016-10-31 20:29:48 +0000384 const char **SymtabLoadCmd,
385 std::list<MachOElement> &Elements) {
Kevin Enderby0e52c922016-08-26 19:34:07 +0000386 if (Load.C.cmdsize < sizeof(MachO::symtab_command))
387 return malformedError("load command " + Twine(LoadCommandIndex) +
388 " LC_SYMTAB cmdsize too small");
389 if (*SymtabLoadCmd != nullptr)
390 return malformedError("more than one LC_SYMTAB command");
391 MachO::symtab_command Symtab =
392 getStruct<MachO::symtab_command>(Obj, Load.Ptr);
393 if (Symtab.cmdsize != sizeof(MachO::symtab_command))
394 return malformedError("LC_SYMTAB command " + Twine(LoadCommandIndex) +
395 " has incorrect cmdsize");
396 uint64_t FileSize = Obj->getData().size();
397 if (Symtab.symoff > FileSize)
398 return malformedError("symoff field of LC_SYMTAB command " +
399 Twine(LoadCommandIndex) + " extends past the end "
400 "of the file");
Kevin Enderbyd5039402016-10-31 20:29:48 +0000401 uint64_t SymtabSize = Symtab.nsyms;
Kevin Enderby0e52c922016-08-26 19:34:07 +0000402 const char *struct_nlist_name;
403 if (Obj->is64Bit()) {
Kevin Enderbyd5039402016-10-31 20:29:48 +0000404 SymtabSize *= sizeof(MachO::nlist_64);
Kevin Enderby0e52c922016-08-26 19:34:07 +0000405 struct_nlist_name = "struct nlist_64";
406 } else {
Kevin Enderbyd5039402016-10-31 20:29:48 +0000407 SymtabSize *= sizeof(MachO::nlist);
Kevin Enderby0e52c922016-08-26 19:34:07 +0000408 struct_nlist_name = "struct nlist";
409 }
Kevin Enderbyd5039402016-10-31 20:29:48 +0000410 uint64_t BigSize = SymtabSize;
Kevin Enderby0e52c922016-08-26 19:34:07 +0000411 BigSize += Symtab.symoff;
412 if (BigSize > FileSize)
413 return malformedError("symoff field plus nsyms field times sizeof(" +
414 Twine(struct_nlist_name) + ") of LC_SYMTAB command " +
415 Twine(LoadCommandIndex) + " extends past the end "
416 "of the file");
Kevin Enderbyd5039402016-10-31 20:29:48 +0000417 if (Error Err = checkOverlappingElement(Elements, Symtab.symoff, SymtabSize,
418 "symbol table"))
419 return Err;
Kevin Enderby0e52c922016-08-26 19:34:07 +0000420 if (Symtab.stroff > FileSize)
421 return malformedError("stroff field of LC_SYMTAB command " +
422 Twine(LoadCommandIndex) + " extends past the end "
423 "of the file");
424 BigSize = Symtab.stroff;
425 BigSize += Symtab.strsize;
426 if (BigSize > FileSize)
427 return malformedError("stroff field plus strsize field of LC_SYMTAB "
428 "command " + Twine(LoadCommandIndex) + " extends "
429 "past the end of the file");
Kevin Enderbyd5039402016-10-31 20:29:48 +0000430 if (Error Err = checkOverlappingElement(Elements, Symtab.stroff,
431 Symtab.strsize, "string table"))
432 return Err;
Kevin Enderby0e52c922016-08-26 19:34:07 +0000433 *SymtabLoadCmd = Load.Ptr;
434 return Error::success();
435}
436
Kevin Enderbydcbc5042016-08-30 21:28:30 +0000437static Error checkDysymtabCommand(const MachOObjectFile *Obj,
438 const MachOObjectFile::LoadCommandInfo &Load,
439 uint32_t LoadCommandIndex,
Kevin Enderbyfbebe162016-11-02 21:08:39 +0000440 const char **DysymtabLoadCmd,
441 std::list<MachOElement> &Elements) {
Kevin Enderbydcbc5042016-08-30 21:28:30 +0000442 if (Load.C.cmdsize < sizeof(MachO::dysymtab_command))
443 return malformedError("load command " + Twine(LoadCommandIndex) +
444 " LC_DYSYMTAB cmdsize too small");
445 if (*DysymtabLoadCmd != nullptr)
446 return malformedError("more than one LC_DYSYMTAB command");
447 MachO::dysymtab_command Dysymtab =
448 getStruct<MachO::dysymtab_command>(Obj, Load.Ptr);
449 if (Dysymtab.cmdsize != sizeof(MachO::dysymtab_command))
450 return malformedError("LC_DYSYMTAB command " + Twine(LoadCommandIndex) +
451 " has incorrect cmdsize");
452 uint64_t FileSize = Obj->getData().size();
453 if (Dysymtab.tocoff > FileSize)
454 return malformedError("tocoff field of LC_DYSYMTAB command " +
455 Twine(LoadCommandIndex) + " extends past the end of "
456 "the file");
457 uint64_t BigSize = Dysymtab.ntoc;
458 BigSize *= sizeof(MachO::dylib_table_of_contents);
459 BigSize += Dysymtab.tocoff;
460 if (BigSize > FileSize)
461 return malformedError("tocoff field plus ntoc field times sizeof(struct "
462 "dylib_table_of_contents) of LC_DYSYMTAB command " +
463 Twine(LoadCommandIndex) + " extends past the end of "
464 "the file");
Kevin Enderbyfbebe162016-11-02 21:08:39 +0000465 if (Error Err = checkOverlappingElement(Elements, Dysymtab.tocoff,
466 Dysymtab.ntoc * sizeof(struct
467 MachO::dylib_table_of_contents),
468 "table of contents"))
469 return Err;
Kevin Enderbydcbc5042016-08-30 21:28:30 +0000470 if (Dysymtab.modtaboff > FileSize)
471 return malformedError("modtaboff field of LC_DYSYMTAB command " +
472 Twine(LoadCommandIndex) + " extends past the end of "
473 "the file");
474 BigSize = Dysymtab.nmodtab;
475 const char *struct_dylib_module_name;
Kevin Enderbyfbebe162016-11-02 21:08:39 +0000476 uint64_t sizeof_modtab;
Kevin Enderbydcbc5042016-08-30 21:28:30 +0000477 if (Obj->is64Bit()) {
Kevin Enderbyfbebe162016-11-02 21:08:39 +0000478 sizeof_modtab = sizeof(MachO::dylib_module_64);
Kevin Enderbydcbc5042016-08-30 21:28:30 +0000479 struct_dylib_module_name = "struct dylib_module_64";
480 } else {
Kevin Enderbyfbebe162016-11-02 21:08:39 +0000481 sizeof_modtab = sizeof(MachO::dylib_module);
Kevin Enderbydcbc5042016-08-30 21:28:30 +0000482 struct_dylib_module_name = "struct dylib_module";
483 }
Kevin Enderbyfbebe162016-11-02 21:08:39 +0000484 BigSize *= sizeof_modtab;
Kevin Enderbydcbc5042016-08-30 21:28:30 +0000485 BigSize += Dysymtab.modtaboff;
486 if (BigSize > FileSize)
487 return malformedError("modtaboff field plus nmodtab field times sizeof(" +
488 Twine(struct_dylib_module_name) + ") of LC_DYSYMTAB "
489 "command " + Twine(LoadCommandIndex) + " extends "
490 "past the end of the file");
Kevin Enderbyfbebe162016-11-02 21:08:39 +0000491 if (Error Err = checkOverlappingElement(Elements, Dysymtab.modtaboff,
492 Dysymtab.nmodtab * sizeof_modtab,
493 "module table"))
494 return Err;
Kevin Enderbydcbc5042016-08-30 21:28:30 +0000495 if (Dysymtab.extrefsymoff > FileSize)
496 return malformedError("extrefsymoff field of LC_DYSYMTAB command " +
497 Twine(LoadCommandIndex) + " extends past the end of "
498 "the file");
499 BigSize = Dysymtab.nextrefsyms;
500 BigSize *= sizeof(MachO::dylib_reference);
501 BigSize += Dysymtab.extrefsymoff;
502 if (BigSize > FileSize)
503 return malformedError("extrefsymoff field plus nextrefsyms field times "
504 "sizeof(struct dylib_reference) of LC_DYSYMTAB "
505 "command " + Twine(LoadCommandIndex) + " extends "
506 "past the end of the file");
Kevin Enderbyfbebe162016-11-02 21:08:39 +0000507 if (Error Err = checkOverlappingElement(Elements, Dysymtab.extrefsymoff,
508 Dysymtab.nextrefsyms *
509 sizeof(MachO::dylib_reference),
510 "reference table"))
511 return Err;
Kevin Enderbydcbc5042016-08-30 21:28:30 +0000512 if (Dysymtab.indirectsymoff > FileSize)
513 return malformedError("indirectsymoff field of LC_DYSYMTAB command " +
514 Twine(LoadCommandIndex) + " extends past the end of "
515 "the file");
516 BigSize = Dysymtab.nindirectsyms;
517 BigSize *= sizeof(uint32_t);
518 BigSize += Dysymtab.indirectsymoff;
519 if (BigSize > FileSize)
520 return malformedError("indirectsymoff field plus nindirectsyms field times "
521 "sizeof(uint32_t) of LC_DYSYMTAB command " +
522 Twine(LoadCommandIndex) + " extends past the end of "
523 "the file");
Kevin Enderbyfbebe162016-11-02 21:08:39 +0000524 if (Error Err = checkOverlappingElement(Elements, Dysymtab.indirectsymoff,
525 Dysymtab.nindirectsyms *
526 sizeof(uint32_t),
527 "indirect table"))
528 return Err;
Kevin Enderbydcbc5042016-08-30 21:28:30 +0000529 if (Dysymtab.extreloff > FileSize)
530 return malformedError("extreloff field of LC_DYSYMTAB command " +
531 Twine(LoadCommandIndex) + " extends past the end of "
532 "the file");
533 BigSize = Dysymtab.nextrel;
534 BigSize *= sizeof(MachO::relocation_info);
535 BigSize += Dysymtab.extreloff;
536 if (BigSize > FileSize)
537 return malformedError("extreloff field plus nextrel field times sizeof"
538 "(struct relocation_info) of LC_DYSYMTAB command " +
539 Twine(LoadCommandIndex) + " extends past the end of "
540 "the file");
Kevin Enderbyfbebe162016-11-02 21:08:39 +0000541 if (Error Err = checkOverlappingElement(Elements, Dysymtab.extreloff,
542 Dysymtab.nextrel *
543 sizeof(MachO::relocation_info),
544 "external relocation table"))
545 return Err;
Kevin Enderbydcbc5042016-08-30 21:28:30 +0000546 if (Dysymtab.locreloff > FileSize)
547 return malformedError("locreloff field of LC_DYSYMTAB command " +
548 Twine(LoadCommandIndex) + " extends past the end of "
549 "the file");
550 BigSize = Dysymtab.nlocrel;
551 BigSize *= sizeof(MachO::relocation_info);
552 BigSize += Dysymtab.locreloff;
553 if (BigSize > FileSize)
554 return malformedError("locreloff field plus nlocrel field times sizeof"
555 "(struct relocation_info) of LC_DYSYMTAB command " +
556 Twine(LoadCommandIndex) + " extends past the end of "
557 "the file");
Kevin Enderbyfbebe162016-11-02 21:08:39 +0000558 if (Error Err = checkOverlappingElement(Elements, Dysymtab.locreloff,
559 Dysymtab.nlocrel *
560 sizeof(MachO::relocation_info),
561 "local relocation table"))
562 return Err;
Kevin Enderbydcbc5042016-08-30 21:28:30 +0000563 *DysymtabLoadCmd = Load.Ptr;
564 return Error::success();
565}
566
Kevin Enderby9d0c9452016-08-31 17:57:46 +0000567static Error checkLinkeditDataCommand(const MachOObjectFile *Obj,
568 const MachOObjectFile::LoadCommandInfo &Load,
569 uint32_t LoadCommandIndex,
Kevin Enderbyfbebe162016-11-02 21:08:39 +0000570 const char **LoadCmd, const char *CmdName,
571 std::list<MachOElement> &Elements,
572 const char *ElementName) {
Kevin Enderby9d0c9452016-08-31 17:57:46 +0000573 if (Load.C.cmdsize < sizeof(MachO::linkedit_data_command))
574 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
575 CmdName + " cmdsize too small");
576 if (*LoadCmd != nullptr)
577 return malformedError("more than one " + Twine(CmdName) + " command");
578 MachO::linkedit_data_command LinkData =
579 getStruct<MachO::linkedit_data_command>(Obj, Load.Ptr);
580 if (LinkData.cmdsize != sizeof(MachO::linkedit_data_command))
581 return malformedError(Twine(CmdName) + " command " +
582 Twine(LoadCommandIndex) + " has incorrect cmdsize");
583 uint64_t FileSize = Obj->getData().size();
584 if (LinkData.dataoff > FileSize)
585 return malformedError("dataoff field of " + Twine(CmdName) + " command " +
586 Twine(LoadCommandIndex) + " extends past the end of "
587 "the file");
588 uint64_t BigSize = LinkData.dataoff;
589 BigSize += LinkData.datasize;
590 if (BigSize > FileSize)
591 return malformedError("dataoff field plus datasize field of " +
592 Twine(CmdName) + " command " +
593 Twine(LoadCommandIndex) + " extends past the end of "
594 "the file");
Kevin Enderbyfbebe162016-11-02 21:08:39 +0000595 if (Error Err = checkOverlappingElement(Elements, LinkData.dataoff,
596 LinkData.datasize, ElementName))
597 return Err;
Kevin Enderby9d0c9452016-08-31 17:57:46 +0000598 *LoadCmd = Load.Ptr;
599 return Error::success();
600}
601
Kevin Enderbyf76b56c2016-09-13 21:42:28 +0000602static Error checkDyldInfoCommand(const MachOObjectFile *Obj,
603 const MachOObjectFile::LoadCommandInfo &Load,
604 uint32_t LoadCommandIndex,
Kevin Enderbyfbebe162016-11-02 21:08:39 +0000605 const char **LoadCmd, const char *CmdName,
606 std::list<MachOElement> &Elements) {
Kevin Enderbyf76b56c2016-09-13 21:42:28 +0000607 if (Load.C.cmdsize < sizeof(MachO::dyld_info_command))
608 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
609 CmdName + " cmdsize too small");
610 if (*LoadCmd != nullptr)
611 return malformedError("more than one LC_DYLD_INFO and or LC_DYLD_INFO_ONLY "
612 "command");
613 MachO::dyld_info_command DyldInfo =
614 getStruct<MachO::dyld_info_command>(Obj, Load.Ptr);
615 if (DyldInfo.cmdsize != sizeof(MachO::dyld_info_command))
616 return malformedError(Twine(CmdName) + " command " +
617 Twine(LoadCommandIndex) + " has incorrect cmdsize");
618 uint64_t FileSize = Obj->getData().size();
619 if (DyldInfo.rebase_off > FileSize)
620 return malformedError("rebase_off field of " + Twine(CmdName) +
621 " command " + Twine(LoadCommandIndex) + " extends "
622 "past the end of the file");
623 uint64_t BigSize = DyldInfo.rebase_off;
624 BigSize += DyldInfo.rebase_size;
625 if (BigSize > FileSize)
626 return malformedError("rebase_off field plus rebase_size field of " +
627 Twine(CmdName) + " command " +
628 Twine(LoadCommandIndex) + " extends past the end of "
629 "the file");
Kevin Enderbyfbebe162016-11-02 21:08:39 +0000630 if (Error Err = checkOverlappingElement(Elements, DyldInfo.rebase_off,
631 DyldInfo.rebase_size,
632 "dyld rebase info"))
633 return Err;
Kevin Enderbyf76b56c2016-09-13 21:42:28 +0000634 if (DyldInfo.bind_off > FileSize)
635 return malformedError("bind_off field of " + Twine(CmdName) +
636 " command " + Twine(LoadCommandIndex) + " extends "
637 "past the end of the file");
638 BigSize = DyldInfo.bind_off;
639 BigSize += DyldInfo.bind_size;
640 if (BigSize > FileSize)
641 return malformedError("bind_off field plus bind_size field of " +
642 Twine(CmdName) + " command " +
643 Twine(LoadCommandIndex) + " extends past the end of "
644 "the file");
Kevin Enderbyfbebe162016-11-02 21:08:39 +0000645 if (Error Err = checkOverlappingElement(Elements, DyldInfo.bind_off,
646 DyldInfo.bind_size,
647 "dyld bind info"))
648 return Err;
Kevin Enderbyf76b56c2016-09-13 21:42:28 +0000649 if (DyldInfo.weak_bind_off > FileSize)
650 return malformedError("weak_bind_off field of " + Twine(CmdName) +
651 " command " + Twine(LoadCommandIndex) + " extends "
652 "past the end of the file");
653 BigSize = DyldInfo.weak_bind_off;
654 BigSize += DyldInfo.weak_bind_size;
655 if (BigSize > FileSize)
656 return malformedError("weak_bind_off field plus weak_bind_size field of " +
657 Twine(CmdName) + " command " +
658 Twine(LoadCommandIndex) + " extends past the end of "
659 "the file");
Kevin Enderbyfbebe162016-11-02 21:08:39 +0000660 if (Error Err = checkOverlappingElement(Elements, DyldInfo.weak_bind_off,
661 DyldInfo.weak_bind_size,
662 "dyld weak bind info"))
663 return Err;
Kevin Enderbyf76b56c2016-09-13 21:42:28 +0000664 if (DyldInfo.lazy_bind_off > FileSize)
665 return malformedError("lazy_bind_off field of " + Twine(CmdName) +
666 " command " + Twine(LoadCommandIndex) + " extends "
667 "past the end of the file");
668 BigSize = DyldInfo.lazy_bind_off;
669 BigSize += DyldInfo.lazy_bind_size;
670 if (BigSize > FileSize)
671 return malformedError("lazy_bind_off field plus lazy_bind_size field of " +
672 Twine(CmdName) + " command " +
673 Twine(LoadCommandIndex) + " extends past the end of "
674 "the file");
Kevin Enderbyfbebe162016-11-02 21:08:39 +0000675 if (Error Err = checkOverlappingElement(Elements, DyldInfo.lazy_bind_off,
676 DyldInfo.lazy_bind_size,
677 "dyld lazy bind info"))
678 return Err;
Kevin Enderbyf76b56c2016-09-13 21:42:28 +0000679 if (DyldInfo.export_off > FileSize)
680 return malformedError("export_off field of " + Twine(CmdName) +
681 " command " + Twine(LoadCommandIndex) + " extends "
682 "past the end of the file");
683 BigSize = DyldInfo.export_off;
684 BigSize += DyldInfo.export_size;
685 if (BigSize > FileSize)
686 return malformedError("export_off field plus export_size field of " +
687 Twine(CmdName) + " command " +
688 Twine(LoadCommandIndex) + " extends past the end of "
689 "the file");
Kevin Enderbyfbebe162016-11-02 21:08:39 +0000690 if (Error Err = checkOverlappingElement(Elements, DyldInfo.export_off,
691 DyldInfo.export_size,
692 "dyld export info"))
693 return Err;
Kevin Enderbyf76b56c2016-09-13 21:42:28 +0000694 *LoadCmd = Load.Ptr;
695 return Error::success();
696}
697
Kevin Enderbyfc0929a2016-09-20 20:14:14 +0000698static Error checkDylibCommand(const MachOObjectFile *Obj,
699 const MachOObjectFile::LoadCommandInfo &Load,
700 uint32_t LoadCommandIndex, const char *CmdName) {
701 if (Load.C.cmdsize < sizeof(MachO::dylib_command))
702 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
703 CmdName + " cmdsize too small");
704 MachO::dylib_command D = getStruct<MachO::dylib_command>(Obj, Load.Ptr);
705 if (D.dylib.name < sizeof(MachO::dylib_command))
706 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
707 CmdName + " name.offset field too small, not past "
708 "the end of the dylib_command struct");
709 if (D.dylib.name >= D.cmdsize)
710 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
711 CmdName + " name.offset field extends past the end "
712 "of the load command");
713 // Make sure there is a null between the starting offset of the name and
714 // the end of the load command.
715 uint32_t i;
716 const char *P = (const char *)Load.Ptr;
717 for (i = D.dylib.name; i < D.cmdsize; i++)
718 if (P[i] == '\0')
719 break;
720 if (i >= D.cmdsize)
721 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
722 CmdName + " library name extends past the end of the "
723 "load command");
724 return Error::success();
725}
726
727static Error checkDylibIdCommand(const MachOObjectFile *Obj,
728 const MachOObjectFile::LoadCommandInfo &Load,
729 uint32_t LoadCommandIndex,
730 const char **LoadCmd) {
731 if (Error Err = checkDylibCommand(Obj, Load, LoadCommandIndex,
732 "LC_ID_DYLIB"))
733 return Err;
734 if (*LoadCmd != nullptr)
735 return malformedError("more than one LC_ID_DYLIB command");
736 if (Obj->getHeader().filetype != MachO::MH_DYLIB &&
737 Obj->getHeader().filetype != MachO::MH_DYLIB_STUB)
738 return malformedError("LC_ID_DYLIB load command in non-dynamic library "
739 "file type");
740 *LoadCmd = Load.Ptr;
741 return Error::success();
742}
743
Kevin Enderby3e490ef2016-09-27 23:24:13 +0000744static Error checkDyldCommand(const MachOObjectFile *Obj,
745 const MachOObjectFile::LoadCommandInfo &Load,
746 uint32_t LoadCommandIndex, const char *CmdName) {
747 if (Load.C.cmdsize < sizeof(MachO::dylinker_command))
748 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
749 CmdName + " cmdsize too small");
750 MachO::dylinker_command D = getStruct<MachO::dylinker_command>(Obj, Load.Ptr);
751 if (D.name < sizeof(MachO::dylinker_command))
752 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
753 CmdName + " name.offset field too small, not past "
754 "the end of the dylinker_command struct");
755 if (D.name >= D.cmdsize)
756 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
757 CmdName + " name.offset field extends past the end "
758 "of the load command");
759 // Make sure there is a null between the starting offset of the name and
760 // the end of the load command.
761 uint32_t i;
762 const char *P = (const char *)Load.Ptr;
763 for (i = D.name; i < D.cmdsize; i++)
764 if (P[i] == '\0')
765 break;
766 if (i >= D.cmdsize)
767 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
768 CmdName + " dyld name extends past the end of the "
769 "load command");
770 return Error::success();
771}
772
Kevin Enderby32359db2016-09-28 21:20:45 +0000773static Error checkVersCommand(const MachOObjectFile *Obj,
774 const MachOObjectFile::LoadCommandInfo &Load,
775 uint32_t LoadCommandIndex,
776 const char **LoadCmd, const char *CmdName) {
777 if (Load.C.cmdsize != sizeof(MachO::version_min_command))
778 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
779 CmdName + " has incorrect cmdsize");
780 if (*LoadCmd != nullptr)
781 return malformedError("more than one LC_VERSION_MIN_MACOSX, "
782 "LC_VERSION_MIN_IPHONEOS, LC_VERSION_MIN_TVOS or "
783 "LC_VERSION_MIN_WATCHOS command");
784 *LoadCmd = Load.Ptr;
785 return Error::success();
786}
787
Kevin Enderby76966bf2016-09-28 23:16:01 +0000788static Error checkRpathCommand(const MachOObjectFile *Obj,
789 const MachOObjectFile::LoadCommandInfo &Load,
790 uint32_t LoadCommandIndex) {
791 if (Load.C.cmdsize < sizeof(MachO::rpath_command))
792 return malformedError("load command " + Twine(LoadCommandIndex) +
793 " LC_RPATH cmdsize too small");
794 MachO::rpath_command R = getStruct<MachO::rpath_command>(Obj, Load.Ptr);
795 if (R.path < sizeof(MachO::rpath_command))
796 return malformedError("load command " + Twine(LoadCommandIndex) +
797 " LC_RPATH path.offset field too small, not past "
798 "the end of the rpath_command struct");
799 if (R.path >= R.cmdsize)
800 return malformedError("load command " + Twine(LoadCommandIndex) +
801 " LC_RPATH path.offset field extends past the end "
802 "of the load command");
803 // Make sure there is a null between the starting offset of the path and
804 // the end of the load command.
805 uint32_t i;
806 const char *P = (const char *)Load.Ptr;
807 for (i = R.path; i < R.cmdsize; i++)
808 if (P[i] == '\0')
809 break;
810 if (i >= R.cmdsize)
811 return malformedError("load command " + Twine(LoadCommandIndex) +
812 " LC_RPATH library name extends past the end of the "
813 "load command");
814 return Error::success();
815}
816
Kevin Enderbyf993d6e2016-10-04 20:37:43 +0000817static Error checkEncryptCommand(const MachOObjectFile *Obj,
818 const MachOObjectFile::LoadCommandInfo &Load,
819 uint32_t LoadCommandIndex,
820 uint64_t cryptoff, uint64_t cryptsize,
821 const char **LoadCmd, const char *CmdName) {
822 if (*LoadCmd != nullptr)
823 return malformedError("more than one LC_ENCRYPTION_INFO and or "
824 "LC_ENCRYPTION_INFO_64 command");
825 uint64_t FileSize = Obj->getData().size();
826 if (cryptoff > FileSize)
827 return malformedError("cryptoff field of " + Twine(CmdName) +
828 " command " + Twine(LoadCommandIndex) + " extends "
829 "past the end of the file");
830 uint64_t BigSize = cryptoff;
831 BigSize += cryptsize;
832 if (BigSize > FileSize)
833 return malformedError("cryptoff field plus cryptsize field of " +
834 Twine(CmdName) + " command " +
835 Twine(LoadCommandIndex) + " extends past the end of "
836 "the file");
837 *LoadCmd = Load.Ptr;
838 return Error::success();
839}
840
Kevin Enderby68fffa82016-10-11 21:04:39 +0000841static Error checkLinkerOptCommand(const MachOObjectFile *Obj,
842 const MachOObjectFile::LoadCommandInfo &Load,
843 uint32_t LoadCommandIndex) {
844 if (Load.C.cmdsize < sizeof(MachO::linker_option_command))
845 return malformedError("load command " + Twine(LoadCommandIndex) +
846 " LC_LINKER_OPTION cmdsize too small");
847 MachO::linker_option_command L =
848 getStruct<MachO::linker_option_command>(Obj, Load.Ptr);
849 // Make sure the count of strings is correct.
850 const char *string = (const char *)Load.Ptr +
851 sizeof(struct MachO::linker_option_command);
852 uint32_t left = L.cmdsize - sizeof(struct MachO::linker_option_command);
853 uint32_t i = 0;
854 while (left > 0) {
855 while (*string == '\0' && left > 0) {
856 string++;
857 left--;
858 }
859 if (left > 0) {
860 i++;
861 uint32_t NullPos = StringRef(string, left).find('\0');
862 uint32_t len = std::min(NullPos, left) + 1;
863 string += len;
864 left -= len;
865 }
866 }
867 if (L.count != i)
868 return malformedError("load command " + Twine(LoadCommandIndex) +
869 " LC_LINKER_OPTION string count " + Twine(L.count) +
870 " does not match number of strings");
871 return Error::success();
872}
873
Kevin Enderby2490de02016-10-17 22:09:25 +0000874static Error checkSubCommand(const MachOObjectFile *Obj,
875 const MachOObjectFile::LoadCommandInfo &Load,
876 uint32_t LoadCommandIndex, const char *CmdName,
877 size_t SizeOfCmd, const char *CmdStructName,
878 uint32_t PathOffset, const char *PathFieldName) {
879 if (PathOffset < SizeOfCmd)
880 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
881 CmdName + " " + PathFieldName + ".offset field too "
882 "small, not past the end of the " + CmdStructName);
883 if (PathOffset >= Load.C.cmdsize)
884 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
885 CmdName + " " + PathFieldName + ".offset field "
886 "extends past the end of the load command");
887 // Make sure there is a null between the starting offset of the path and
888 // the end of the load command.
889 uint32_t i;
890 const char *P = (const char *)Load.Ptr;
891 for (i = PathOffset; i < Load.C.cmdsize; i++)
892 if (P[i] == '\0')
893 break;
894 if (i >= Load.C.cmdsize)
895 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
896 CmdName + " " + PathFieldName + " name extends past "
897 "the end of the load command");
898 return Error::success();
899}
900
Kevin Enderby210030b2016-10-19 23:44:34 +0000901static Error checkThreadCommand(const MachOObjectFile *Obj,
902 const MachOObjectFile::LoadCommandInfo &Load,
903 uint32_t LoadCommandIndex,
904 const char *CmdName) {
905 if (Load.C.cmdsize < sizeof(MachO::thread_command))
906 return malformedError("load command " + Twine(LoadCommandIndex) +
907 CmdName + " cmdsize too small");
908 MachO::thread_command T =
909 getStruct<MachO::thread_command>(Obj, Load.Ptr);
910 const char *state = Load.Ptr + sizeof(MachO::thread_command);
911 const char *end = Load.Ptr + T.cmdsize;
912 uint32_t nflavor = 0;
913 uint32_t cputype = getCPUType(Obj);
914 while (state < end) {
915 if(state + sizeof(uint32_t) > end)
916 return malformedError("load command " + Twine(LoadCommandIndex) +
917 "flavor in " + CmdName + " extends past end of "
918 "command");
919 uint32_t flavor;
920 memcpy(&flavor, state, sizeof(uint32_t));
921 if (Obj->isLittleEndian() != sys::IsLittleEndianHost)
922 sys::swapByteOrder(flavor);
923 state += sizeof(uint32_t);
924
925 if(state + sizeof(uint32_t) > end)
926 return malformedError("load command " + Twine(LoadCommandIndex) +
927 " count in " + CmdName + " extends past end of "
928 "command");
929 uint32_t count;
930 memcpy(&count, state, sizeof(uint32_t));
931 if (Obj->isLittleEndian() != sys::IsLittleEndianHost)
932 sys::swapByteOrder(count);
933 state += sizeof(uint32_t);
934
935 if (cputype == MachO::CPU_TYPE_X86_64) {
936 if (flavor == MachO::x86_THREAD_STATE64) {
937 if (count != MachO::x86_THREAD_STATE64_COUNT)
938 return malformedError("load command " + Twine(LoadCommandIndex) +
939 " count not x86_THREAD_STATE64_COUNT for "
940 "flavor number " + Twine(nflavor) + " which is "
941 "a x86_THREAD_STATE64 flavor in " + CmdName +
942 " command");
943 if (state + sizeof(MachO::x86_thread_state64_t) > end)
944 return malformedError("load command " + Twine(LoadCommandIndex) +
945 " x86_THREAD_STATE64 extends past end of "
946 "command in " + CmdName + " command");
947 state += sizeof(MachO::x86_thread_state64_t);
948 } else {
949 return malformedError("load command " + Twine(LoadCommandIndex) +
950 " unknown flavor (" + Twine(flavor) + ") for "
951 "flavor number " + Twine(nflavor) + " in " +
952 CmdName + " command");
953 }
954 } else if (cputype == MachO::CPU_TYPE_ARM) {
955 if (flavor == MachO::ARM_THREAD_STATE) {
956 if (count != MachO::ARM_THREAD_STATE_COUNT)
957 return malformedError("load command " + Twine(LoadCommandIndex) +
958 " count not ARM_THREAD_STATE_COUNT for "
959 "flavor number " + Twine(nflavor) + " which is "
960 "a ARM_THREAD_STATE flavor in " + CmdName +
961 " command");
962 if (state + sizeof(MachO::arm_thread_state32_t) > end)
963 return malformedError("load command " + Twine(LoadCommandIndex) +
964 " ARM_THREAD_STATE extends past end of "
965 "command in " + CmdName + " command");
966 state += sizeof(MachO::arm_thread_state32_t);
967 } else {
968 return malformedError("load command " + Twine(LoadCommandIndex) +
969 " unknown flavor (" + Twine(flavor) + ") for "
970 "flavor number " + Twine(nflavor) + " in " +
971 CmdName + " command");
972 }
Kevin Enderby7747cb52016-11-03 20:51:28 +0000973 } else if (cputype == MachO::CPU_TYPE_ARM64) {
974 if (flavor == MachO::ARM_THREAD_STATE64) {
975 if (count != MachO::ARM_THREAD_STATE64_COUNT)
976 return malformedError("load command " + Twine(LoadCommandIndex) +
977 " count not ARM_THREAD_STATE64_COUNT for "
978 "flavor number " + Twine(nflavor) + " which is "
979 "a ARM_THREAD_STATE64 flavor in " + CmdName +
980 " command");
981 if (state + sizeof(MachO::arm_thread_state64_t) > end)
982 return malformedError("load command " + Twine(LoadCommandIndex) +
983 " ARM_THREAD_STATE64 extends past end of "
984 "command in " + CmdName + " command");
985 state += sizeof(MachO::arm_thread_state64_t);
986 } else {
987 return malformedError("load command " + Twine(LoadCommandIndex) +
988 " unknown flavor (" + Twine(flavor) + ") for "
989 "flavor number " + Twine(nflavor) + " in " +
990 CmdName + " command");
991 }
Kevin Enderby210030b2016-10-19 23:44:34 +0000992 } else if (cputype == MachO::CPU_TYPE_POWERPC) {
993 if (flavor == MachO::PPC_THREAD_STATE) {
994 if (count != MachO::PPC_THREAD_STATE_COUNT)
995 return malformedError("load command " + Twine(LoadCommandIndex) +
996 " count not PPC_THREAD_STATE_COUNT for "
997 "flavor number " + Twine(nflavor) + " which is "
998 "a PPC_THREAD_STATE flavor in " + CmdName +
999 " command");
1000 if (state + sizeof(MachO::ppc_thread_state32_t) > end)
1001 return malformedError("load command " + Twine(LoadCommandIndex) +
1002 " PPC_THREAD_STATE extends past end of "
1003 "command in " + CmdName + " command");
1004 state += sizeof(MachO::ppc_thread_state32_t);
1005 } else {
1006 return malformedError("load command " + Twine(LoadCommandIndex) +
1007 " unknown flavor (" + Twine(flavor) + ") for "
1008 "flavor number " + Twine(nflavor) + " in " +
1009 CmdName + " command");
1010 }
1011 } else {
1012 return malformedError("unknown cputype (" + Twine(cputype) + ") load "
1013 "command " + Twine(LoadCommandIndex) + " for " +
1014 CmdName + " command can't be checked");
1015 }
1016 nflavor++;
1017 }
1018 return Error::success();
1019}
1020
Kevin Enderbyc8bb4222016-10-20 20:10:30 +00001021static Error checkTwoLevelHintsCommand(const MachOObjectFile *Obj,
1022 const MachOObjectFile::LoadCommandInfo
1023 &Load,
1024 uint32_t LoadCommandIndex,
Kevin Enderbyfbebe162016-11-02 21:08:39 +00001025 const char **LoadCmd,
1026 std::list<MachOElement> &Elements) {
Kevin Enderbyc8bb4222016-10-20 20:10:30 +00001027 if (Load.C.cmdsize != sizeof(MachO::twolevel_hints_command))
1028 return malformedError("load command " + Twine(LoadCommandIndex) +
1029 " LC_TWOLEVEL_HINTS has incorrect cmdsize");
1030 if (*LoadCmd != nullptr)
1031 return malformedError("more than one LC_TWOLEVEL_HINTS command");
1032 MachO::twolevel_hints_command Hints =
1033 getStruct<MachO::twolevel_hints_command>(Obj, Load.Ptr);
1034 uint64_t FileSize = Obj->getData().size();
1035 if (Hints.offset > FileSize)
1036 return malformedError("offset field of LC_TWOLEVEL_HINTS command " +
1037 Twine(LoadCommandIndex) + " extends past the end of "
1038 "the file");
1039 uint64_t BigSize = Hints.nhints;
1040 BigSize *= Hints.nhints * sizeof(MachO::twolevel_hint);
1041 BigSize += Hints.offset;
1042 if (BigSize > FileSize)
1043 return malformedError("offset field plus nhints times sizeof(struct "
1044 "twolevel_hint) field of LC_TWOLEVEL_HINTS command " +
1045 Twine(LoadCommandIndex) + " extends past the end of "
1046 "the file");
Kevin Enderbyfbebe162016-11-02 21:08:39 +00001047 if (Error Err = checkOverlappingElement(Elements, Hints.offset, Hints.nhints *
1048 sizeof(MachO::twolevel_hint),
1049 "two level hints"))
1050 return Err;
Kevin Enderbyc8bb4222016-10-20 20:10:30 +00001051 *LoadCmd = Load.Ptr;
1052 return Error::success();
1053}
1054
Kevin Enderbybc5c29a2016-10-27 20:59:10 +00001055// Returns true if the libObject code does not support the load command and its
1056// contents. The cmd value it is treated as an unknown load command but with
1057// an error message that says the cmd value is obsolete.
1058static bool isLoadCommandObsolete(uint32_t cmd) {
1059 if (cmd == MachO::LC_SYMSEG ||
1060 cmd == MachO::LC_LOADFVMLIB ||
1061 cmd == MachO::LC_IDFVMLIB ||
1062 cmd == MachO::LC_IDENT ||
1063 cmd == MachO::LC_FVMFILE ||
1064 cmd == MachO::LC_PREPAGE ||
1065 cmd == MachO::LC_PREBOUND_DYLIB ||
1066 cmd == MachO::LC_TWOLEVEL_HINTS ||
1067 cmd == MachO::LC_PREBIND_CKSUM)
1068 return true;
1069 return false;
1070}
1071
Lang Hames82627642016-03-25 21:59:14 +00001072Expected<std::unique_ptr<MachOObjectFile>>
1073MachOObjectFile::create(MemoryBufferRef Object, bool IsLittleEndian,
Kevin Enderby79d6c632016-10-24 21:15:11 +00001074 bool Is64Bits, uint32_t UniversalCputype,
1075 uint32_t UniversalIndex) {
Lang Hamesd1af8fc2016-03-25 23:54:32 +00001076 Error Err;
Lang Hames82627642016-03-25 21:59:14 +00001077 std::unique_ptr<MachOObjectFile> Obj(
1078 new MachOObjectFile(std::move(Object), IsLittleEndian,
Kevin Enderby79d6c632016-10-24 21:15:11 +00001079 Is64Bits, Err, UniversalCputype,
1080 UniversalIndex));
Lang Hames82627642016-03-25 21:59:14 +00001081 if (Err)
1082 return std::move(Err);
1083 return std::move(Obj);
1084}
1085
Rafael Espindola48af1c22014-08-19 18:44:46 +00001086MachOObjectFile::MachOObjectFile(MemoryBufferRef Object, bool IsLittleEndian,
Kevin Enderby79d6c632016-10-24 21:15:11 +00001087 bool Is64bits, Error &Err,
1088 uint32_t UniversalCputype,
1089 uint32_t UniversalIndex)
Rafael Espindola48af1c22014-08-19 18:44:46 +00001090 : ObjectFile(getMachOType(IsLittleEndian, Is64bits), Object),
Craig Topper2617dcc2014-04-15 06:32:26 +00001091 SymtabLoadCmd(nullptr), DysymtabLoadCmd(nullptr),
Kevin Enderby9a509442015-01-27 21:28:24 +00001092 DataInCodeLoadCmd(nullptr), LinkOptHintsLoadCmd(nullptr),
1093 DyldInfoLoadCmd(nullptr), UuidLoadCmd(nullptr),
1094 HasPageZeroSegment(false) {
Lang Hames5e51a2e2016-07-22 16:11:25 +00001095 ErrorAsOutParameter ErrAsOutParam(&Err);
Kevin Enderbyc614d282016-08-12 20:10:25 +00001096 uint64_t SizeOfHeaders;
Kevin Enderby79d6c632016-10-24 21:15:11 +00001097 uint32_t cputype;
Kevin Enderby87025742016-04-13 21:17:58 +00001098 if (is64Bit()) {
Lang Hames9e964f32016-03-25 17:25:34 +00001099 parseHeader(this, Header64, Err);
Kevin Enderbyc614d282016-08-12 20:10:25 +00001100 SizeOfHeaders = sizeof(MachO::mach_header_64);
Kevin Enderby79d6c632016-10-24 21:15:11 +00001101 cputype = Header64.cputype;
Kevin Enderby87025742016-04-13 21:17:58 +00001102 } else {
Lang Hames9e964f32016-03-25 17:25:34 +00001103 parseHeader(this, Header, Err);
Kevin Enderbyc614d282016-08-12 20:10:25 +00001104 SizeOfHeaders = sizeof(MachO::mach_header);
Kevin Enderby79d6c632016-10-24 21:15:11 +00001105 cputype = Header.cputype;
Kevin Enderby87025742016-04-13 21:17:58 +00001106 }
Lang Hames9e964f32016-03-25 17:25:34 +00001107 if (Err)
Alexey Samsonov9f336632015-06-04 19:45:22 +00001108 return;
Kevin Enderbyc614d282016-08-12 20:10:25 +00001109 SizeOfHeaders += getHeader().sizeofcmds;
1110 if (getData().data() + SizeOfHeaders > getData().end()) {
Kevin Enderbyd4e075b2016-05-06 20:16:28 +00001111 Err = malformedError("load commands extend past the end of the file");
Kevin Enderby87025742016-04-13 21:17:58 +00001112 return;
1113 }
Kevin Enderby79d6c632016-10-24 21:15:11 +00001114 if (UniversalCputype != 0 && cputype != UniversalCputype) {
1115 Err = malformedError("universal header architecture: " +
1116 Twine(UniversalIndex) + "'s cputype does not match "
1117 "object file's mach header");
1118 return;
1119 }
Kevin Enderbyd5039402016-10-31 20:29:48 +00001120 std::list<MachOElement> Elements;
1121 Elements.push_back({0, SizeOfHeaders, "Mach-O headers"});
Alexey Samsonov13415ed2015-06-04 19:22:03 +00001122
1123 uint32_t LoadCommandCount = getHeader().ncmds;
Lang Hames9e964f32016-03-25 17:25:34 +00001124 LoadCommandInfo Load;
Kevin Enderbyfc0929a2016-09-20 20:14:14 +00001125 if (LoadCommandCount != 0) {
1126 if (auto LoadOrErr = getFirstLoadCommandInfo(this))
1127 Load = *LoadOrErr;
1128 else {
1129 Err = LoadOrErr.takeError();
1130 return;
1131 }
Alexey Samsonovde5a94a2015-06-04 19:57:46 +00001132 }
Lang Hames9e964f32016-03-25 17:25:34 +00001133
Kevin Enderbyfc0929a2016-09-20 20:14:14 +00001134 const char *DyldIdLoadCmd = nullptr;
Kevin Enderby90986e62016-09-26 21:11:03 +00001135 const char *FuncStartsLoadCmd = nullptr;
1136 const char *SplitInfoLoadCmd = nullptr;
1137 const char *CodeSignDrsLoadCmd = nullptr;
Kevin Enderby89baf992016-10-18 20:24:12 +00001138 const char *CodeSignLoadCmd = nullptr;
Kevin Enderby32359db2016-09-28 21:20:45 +00001139 const char *VersLoadCmd = nullptr;
Kevin Enderby245be3e2016-09-29 17:45:23 +00001140 const char *SourceLoadCmd = nullptr;
Kevin Enderby4f229d82016-09-29 21:07:29 +00001141 const char *EntryPointLoadCmd = nullptr;
Kevin Enderbyf993d6e2016-10-04 20:37:43 +00001142 const char *EncryptLoadCmd = nullptr;
Kevin Enderby6f695822016-10-18 17:54:17 +00001143 const char *RoutinesLoadCmd = nullptr;
Kevin Enderby210030b2016-10-19 23:44:34 +00001144 const char *UnixThreadLoadCmd = nullptr;
Kevin Enderbyc8bb4222016-10-20 20:10:30 +00001145 const char *TwoLevelHintsLoadCmd = nullptr;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00001146 for (unsigned I = 0; I < LoadCommandCount; ++I) {
Kevin Enderby1851a822016-07-07 22:11:42 +00001147 if (is64Bit()) {
1148 if (Load.C.cmdsize % 8 != 0) {
1149 // We have a hack here to allow 64-bit Mach-O core files to have
1150 // LC_THREAD commands that are only a multiple of 4 and not 8 to be
1151 // allowed since the macOS kernel produces them.
1152 if (getHeader().filetype != MachO::MH_CORE ||
1153 Load.C.cmd != MachO::LC_THREAD || Load.C.cmdsize % 4) {
1154 Err = malformedError("load command " + Twine(I) + " cmdsize not a "
1155 "multiple of 8");
1156 return;
1157 }
1158 }
1159 } else {
1160 if (Load.C.cmdsize % 4 != 0) {
1161 Err = malformedError("load command " + Twine(I) + " cmdsize not a "
1162 "multiple of 4");
1163 return;
1164 }
1165 }
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00001166 LoadCommands.push_back(Load);
Charles Davis8bdfafd2013-09-01 04:28:48 +00001167 if (Load.C.cmd == MachO::LC_SYMTAB) {
Kevin Enderbyd5039402016-10-31 20:29:48 +00001168 if ((Err = checkSymtabCommand(this, Load, I, &SymtabLoadCmd, Elements)))
David Majnemer73cc6ff2014-11-13 19:48:56 +00001169 return;
Charles Davis8bdfafd2013-09-01 04:28:48 +00001170 } else if (Load.C.cmd == MachO::LC_DYSYMTAB) {
Kevin Enderbyfbebe162016-11-02 21:08:39 +00001171 if ((Err = checkDysymtabCommand(this, Load, I, &DysymtabLoadCmd,
1172 Elements)))
David Majnemer73cc6ff2014-11-13 19:48:56 +00001173 return;
Charles Davis8bdfafd2013-09-01 04:28:48 +00001174 } else if (Load.C.cmd == MachO::LC_DATA_IN_CODE) {
Kevin Enderby9d0c9452016-08-31 17:57:46 +00001175 if ((Err = checkLinkeditDataCommand(this, Load, I, &DataInCodeLoadCmd,
Kevin Enderbyfbebe162016-11-02 21:08:39 +00001176 "LC_DATA_IN_CODE", Elements,
1177 "data in code info")))
David Majnemer73cc6ff2014-11-13 19:48:56 +00001178 return;
Kevin Enderby9a509442015-01-27 21:28:24 +00001179 } else if (Load.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
Kevin Enderby9d0c9452016-08-31 17:57:46 +00001180 if ((Err = checkLinkeditDataCommand(this, Load, I, &LinkOptHintsLoadCmd,
Kevin Enderbyfbebe162016-11-02 21:08:39 +00001181 "LC_LINKER_OPTIMIZATION_HINT",
1182 Elements, "linker optimization "
1183 "hints")))
Kevin Enderby9a509442015-01-27 21:28:24 +00001184 return;
Kevin Enderby90986e62016-09-26 21:11:03 +00001185 } else if (Load.C.cmd == MachO::LC_FUNCTION_STARTS) {
1186 if ((Err = checkLinkeditDataCommand(this, Load, I, &FuncStartsLoadCmd,
Kevin Enderbyfbebe162016-11-02 21:08:39 +00001187 "LC_FUNCTION_STARTS", Elements,
1188 "function starts data")))
Kevin Enderby90986e62016-09-26 21:11:03 +00001189 return;
1190 } else if (Load.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO) {
1191 if ((Err = checkLinkeditDataCommand(this, Load, I, &SplitInfoLoadCmd,
Kevin Enderbyfbebe162016-11-02 21:08:39 +00001192 "LC_SEGMENT_SPLIT_INFO", Elements,
1193 "split info data")))
Kevin Enderby90986e62016-09-26 21:11:03 +00001194 return;
1195 } else if (Load.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS) {
1196 if ((Err = checkLinkeditDataCommand(this, Load, I, &CodeSignDrsLoadCmd,
Kevin Enderbyfbebe162016-11-02 21:08:39 +00001197 "LC_DYLIB_CODE_SIGN_DRS", Elements,
1198 "code signing RDs data")))
Kevin Enderby90986e62016-09-26 21:11:03 +00001199 return;
Kevin Enderby89baf992016-10-18 20:24:12 +00001200 } else if (Load.C.cmd == MachO::LC_CODE_SIGNATURE) {
1201 if ((Err = checkLinkeditDataCommand(this, Load, I, &CodeSignLoadCmd,
Kevin Enderbyfbebe162016-11-02 21:08:39 +00001202 "LC_CODE_SIGNATURE", Elements,
1203 "code signature data")))
Kevin Enderby89baf992016-10-18 20:24:12 +00001204 return;
Kevin Enderbyf76b56c2016-09-13 21:42:28 +00001205 } else if (Load.C.cmd == MachO::LC_DYLD_INFO) {
1206 if ((Err = checkDyldInfoCommand(this, Load, I, &DyldInfoLoadCmd,
Kevin Enderbyfbebe162016-11-02 21:08:39 +00001207 "LC_DYLD_INFO", Elements)))
David Majnemer73cc6ff2014-11-13 19:48:56 +00001208 return;
Kevin Enderbyf76b56c2016-09-13 21:42:28 +00001209 } else if (Load.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
1210 if ((Err = checkDyldInfoCommand(this, Load, I, &DyldInfoLoadCmd,
Kevin Enderbyfbebe162016-11-02 21:08:39 +00001211 "LC_DYLD_INFO_ONLY", Elements)))
Kevin Enderbyf76b56c2016-09-13 21:42:28 +00001212 return;
Alexander Potapenko6909b5b2014-10-15 23:35:45 +00001213 } else if (Load.C.cmd == MachO::LC_UUID) {
Kevin Enderbye71e13c2016-09-21 20:03:09 +00001214 if (Load.C.cmdsize != sizeof(MachO::uuid_command)) {
1215 Err = malformedError("LC_UUID command " + Twine(I) + " has incorrect "
1216 "cmdsize");
1217 return;
1218 }
David Majnemer73cc6ff2014-11-13 19:48:56 +00001219 if (UuidLoadCmd) {
Kevin Enderbye71e13c2016-09-21 20:03:09 +00001220 Err = malformedError("more than one LC_UUID command");
David Majnemer73cc6ff2014-11-13 19:48:56 +00001221 return;
1222 }
Alexander Potapenko6909b5b2014-10-15 23:35:45 +00001223 UuidLoadCmd = Load.Ptr;
Alexey Samsonove1a76ab2015-06-04 22:08:37 +00001224 } else if (Load.C.cmd == MachO::LC_SEGMENT_64) {
Kevin Enderbyc614d282016-08-12 20:10:25 +00001225 if ((Err = parseSegmentLoadCommand<MachO::segment_command_64,
1226 MachO::section_64>(
Kevin Enderbyb34e3a12016-05-05 17:43:35 +00001227 this, Load, Sections, HasPageZeroSegment, I,
Kevin Enderbyfbebe162016-11-02 21:08:39 +00001228 "LC_SEGMENT_64", SizeOfHeaders, Elements)))
Alexey Samsonov074da9b2015-06-04 20:08:52 +00001229 return;
Alexey Samsonove1a76ab2015-06-04 22:08:37 +00001230 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
Kevin Enderbyc614d282016-08-12 20:10:25 +00001231 if ((Err = parseSegmentLoadCommand<MachO::segment_command,
1232 MachO::section>(
1233 this, Load, Sections, HasPageZeroSegment, I,
Kevin Enderbyfbebe162016-11-02 21:08:39 +00001234 "LC_SEGMENT", SizeOfHeaders, Elements)))
Alexey Samsonov074da9b2015-06-04 20:08:52 +00001235 return;
Kevin Enderbyfc0929a2016-09-20 20:14:14 +00001236 } else if (Load.C.cmd == MachO::LC_ID_DYLIB) {
1237 if ((Err = checkDylibIdCommand(this, Load, I, &DyldIdLoadCmd)))
1238 return;
1239 } else if (Load.C.cmd == MachO::LC_LOAD_DYLIB) {
1240 if ((Err = checkDylibCommand(this, Load, I, "LC_LOAD_DYLIB")))
1241 return;
1242 Libraries.push_back(Load.Ptr);
1243 } else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB) {
1244 if ((Err = checkDylibCommand(this, Load, I, "LC_LOAD_WEAK_DYLIB")))
1245 return;
1246 Libraries.push_back(Load.Ptr);
1247 } else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB) {
1248 if ((Err = checkDylibCommand(this, Load, I, "LC_LAZY_LOAD_DYLIB")))
1249 return;
1250 Libraries.push_back(Load.Ptr);
1251 } else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB) {
1252 if ((Err = checkDylibCommand(this, Load, I, "LC_REEXPORT_DYLIB")))
1253 return;
1254 Libraries.push_back(Load.Ptr);
1255 } else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
1256 if ((Err = checkDylibCommand(this, Load, I, "LC_LOAD_UPWARD_DYLIB")))
1257 return;
Kevin Enderby980b2582014-06-05 21:21:57 +00001258 Libraries.push_back(Load.Ptr);
Kevin Enderby3e490ef2016-09-27 23:24:13 +00001259 } else if (Load.C.cmd == MachO::LC_ID_DYLINKER) {
1260 if ((Err = checkDyldCommand(this, Load, I, "LC_ID_DYLINKER")))
1261 return;
1262 } else if (Load.C.cmd == MachO::LC_LOAD_DYLINKER) {
1263 if ((Err = checkDyldCommand(this, Load, I, "LC_LOAD_DYLINKER")))
1264 return;
1265 } else if (Load.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
1266 if ((Err = checkDyldCommand(this, Load, I, "LC_DYLD_ENVIRONMENT")))
1267 return;
Kevin Enderby32359db2016-09-28 21:20:45 +00001268 } else if (Load.C.cmd == MachO::LC_VERSION_MIN_MACOSX) {
1269 if ((Err = checkVersCommand(this, Load, I, &VersLoadCmd,
1270 "LC_VERSION_MIN_MACOSX")))
1271 return;
1272 } else if (Load.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS) {
1273 if ((Err = checkVersCommand(this, Load, I, &VersLoadCmd,
1274 "LC_VERSION_MIN_IPHONEOS")))
1275 return;
1276 } else if (Load.C.cmd == MachO::LC_VERSION_MIN_TVOS) {
1277 if ((Err = checkVersCommand(this, Load, I, &VersLoadCmd,
1278 "LC_VERSION_MIN_TVOS")))
1279 return;
1280 } else if (Load.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
1281 if ((Err = checkVersCommand(this, Load, I, &VersLoadCmd,
1282 "LC_VERSION_MIN_WATCHOS")))
1283 return;
Kevin Enderby76966bf2016-09-28 23:16:01 +00001284 } else if (Load.C.cmd == MachO::LC_RPATH) {
1285 if ((Err = checkRpathCommand(this, Load, I)))
1286 return;
Kevin Enderby245be3e2016-09-29 17:45:23 +00001287 } else if (Load.C.cmd == MachO::LC_SOURCE_VERSION) {
1288 if (Load.C.cmdsize != sizeof(MachO::source_version_command)) {
1289 Err = malformedError("LC_SOURCE_VERSION command " + Twine(I) +
1290 " has incorrect cmdsize");
1291 return;
1292 }
1293 if (SourceLoadCmd) {
1294 Err = malformedError("more than one LC_SOURCE_VERSION command");
1295 return;
1296 }
1297 SourceLoadCmd = Load.Ptr;
Kevin Enderby4f229d82016-09-29 21:07:29 +00001298 } else if (Load.C.cmd == MachO::LC_MAIN) {
1299 if (Load.C.cmdsize != sizeof(MachO::entry_point_command)) {
1300 Err = malformedError("LC_MAIN command " + Twine(I) +
1301 " has incorrect cmdsize");
1302 return;
1303 }
1304 if (EntryPointLoadCmd) {
1305 Err = malformedError("more than one LC_MAIN command");
1306 return;
1307 }
1308 EntryPointLoadCmd = Load.Ptr;
Kevin Enderbyf993d6e2016-10-04 20:37:43 +00001309 } else if (Load.C.cmd == MachO::LC_ENCRYPTION_INFO) {
1310 if (Load.C.cmdsize != sizeof(MachO::encryption_info_command)) {
1311 Err = malformedError("LC_ENCRYPTION_INFO command " + Twine(I) +
1312 " has incorrect cmdsize");
1313 return;
1314 }
1315 MachO::encryption_info_command E =
1316 getStruct<MachO::encryption_info_command>(this, Load.Ptr);
1317 if ((Err = checkEncryptCommand(this, Load, I, E.cryptoff, E.cryptsize,
1318 &EncryptLoadCmd, "LC_ENCRYPTION_INFO")))
1319 return;
1320 } else if (Load.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
1321 if (Load.C.cmdsize != sizeof(MachO::encryption_info_command_64)) {
1322 Err = malformedError("LC_ENCRYPTION_INFO_64 command " + Twine(I) +
1323 " has incorrect cmdsize");
1324 return;
1325 }
1326 MachO::encryption_info_command_64 E =
1327 getStruct<MachO::encryption_info_command_64>(this, Load.Ptr);
1328 if ((Err = checkEncryptCommand(this, Load, I, E.cryptoff, E.cryptsize,
1329 &EncryptLoadCmd, "LC_ENCRYPTION_INFO_64")))
1330 return;
Kevin Enderby68fffa82016-10-11 21:04:39 +00001331 } else if (Load.C.cmd == MachO::LC_LINKER_OPTION) {
1332 if ((Err = checkLinkerOptCommand(this, Load, I)))
1333 return;
Kevin Enderby2490de02016-10-17 22:09:25 +00001334 } else if (Load.C.cmd == MachO::LC_SUB_FRAMEWORK) {
1335 if (Load.C.cmdsize < sizeof(MachO::sub_framework_command)) {
1336 Err = malformedError("load command " + Twine(I) +
1337 " LC_SUB_FRAMEWORK cmdsize too small");
1338 return;
1339 }
1340 MachO::sub_framework_command S =
1341 getStruct<MachO::sub_framework_command>(this, Load.Ptr);
1342 if ((Err = checkSubCommand(this, Load, I, "LC_SUB_FRAMEWORK",
1343 sizeof(MachO::sub_framework_command),
1344 "sub_framework_command", S.umbrella,
1345 "umbrella")))
1346 return;
1347 } else if (Load.C.cmd == MachO::LC_SUB_UMBRELLA) {
1348 if (Load.C.cmdsize < sizeof(MachO::sub_umbrella_command)) {
1349 Err = malformedError("load command " + Twine(I) +
1350 " LC_SUB_UMBRELLA cmdsize too small");
1351 return;
1352 }
1353 MachO::sub_umbrella_command S =
1354 getStruct<MachO::sub_umbrella_command>(this, Load.Ptr);
1355 if ((Err = checkSubCommand(this, Load, I, "LC_SUB_UMBRELLA",
1356 sizeof(MachO::sub_umbrella_command),
1357 "sub_umbrella_command", S.sub_umbrella,
1358 "sub_umbrella")))
1359 return;
1360 } else if (Load.C.cmd == MachO::LC_SUB_LIBRARY) {
1361 if (Load.C.cmdsize < sizeof(MachO::sub_library_command)) {
1362 Err = malformedError("load command " + Twine(I) +
1363 " LC_SUB_LIBRARY cmdsize too small");
1364 return;
1365 }
1366 MachO::sub_library_command S =
1367 getStruct<MachO::sub_library_command>(this, Load.Ptr);
1368 if ((Err = checkSubCommand(this, Load, I, "LC_SUB_LIBRARY",
1369 sizeof(MachO::sub_library_command),
1370 "sub_library_command", S.sub_library,
1371 "sub_library")))
1372 return;
1373 } else if (Load.C.cmd == MachO::LC_SUB_CLIENT) {
1374 if (Load.C.cmdsize < sizeof(MachO::sub_client_command)) {
1375 Err = malformedError("load command " + Twine(I) +
1376 " LC_SUB_CLIENT cmdsize too small");
1377 return;
1378 }
1379 MachO::sub_client_command S =
1380 getStruct<MachO::sub_client_command>(this, Load.Ptr);
1381 if ((Err = checkSubCommand(this, Load, I, "LC_SUB_CLIENT",
1382 sizeof(MachO::sub_client_command),
1383 "sub_client_command", S.client, "client")))
1384 return;
Kevin Enderby6f695822016-10-18 17:54:17 +00001385 } else if (Load.C.cmd == MachO::LC_ROUTINES) {
1386 if (Load.C.cmdsize != sizeof(MachO::routines_command)) {
1387 Err = malformedError("LC_ROUTINES command " + Twine(I) +
1388 " has incorrect cmdsize");
1389 return;
1390 }
1391 if (RoutinesLoadCmd) {
1392 Err = malformedError("more than one LC_ROUTINES and or LC_ROUTINES_64 "
1393 "command");
1394 return;
1395 }
1396 RoutinesLoadCmd = Load.Ptr;
1397 } else if (Load.C.cmd == MachO::LC_ROUTINES_64) {
1398 if (Load.C.cmdsize != sizeof(MachO::routines_command_64)) {
1399 Err = malformedError("LC_ROUTINES_64 command " + Twine(I) +
1400 " has incorrect cmdsize");
1401 return;
1402 }
1403 if (RoutinesLoadCmd) {
1404 Err = malformedError("more than one LC_ROUTINES_64 and or LC_ROUTINES "
1405 "command");
1406 return;
1407 }
1408 RoutinesLoadCmd = Load.Ptr;
Kevin Enderby210030b2016-10-19 23:44:34 +00001409 } else if (Load.C.cmd == MachO::LC_UNIXTHREAD) {
1410 if ((Err = checkThreadCommand(this, Load, I, "LC_UNIXTHREAD")))
1411 return;
1412 if (UnixThreadLoadCmd) {
1413 Err = malformedError("more than one LC_UNIXTHREAD command");
1414 return;
1415 }
1416 UnixThreadLoadCmd = Load.Ptr;
1417 } else if (Load.C.cmd == MachO::LC_THREAD) {
1418 if ((Err = checkThreadCommand(this, Load, I, "LC_THREAD")))
1419 return;
Kevin Enderbybc5c29a2016-10-27 20:59:10 +00001420 // Note: LC_TWOLEVEL_HINTS is really obsolete and is not supported.
Kevin Enderbyc8bb4222016-10-20 20:10:30 +00001421 } else if (Load.C.cmd == MachO::LC_TWOLEVEL_HINTS) {
1422 if ((Err = checkTwoLevelHintsCommand(this, Load, I,
Kevin Enderbyfbebe162016-11-02 21:08:39 +00001423 &TwoLevelHintsLoadCmd, Elements)))
Kevin Enderbyc8bb4222016-10-20 20:10:30 +00001424 return;
Kevin Enderbybc5c29a2016-10-27 20:59:10 +00001425 } else if (isLoadCommandObsolete(Load.C.cmd)) {
1426 Err = malformedError("load command " + Twine(I) + " for cmd value of: " +
1427 Twine(Load.C.cmd) + " is obsolete and not "
1428 "supported");
1429 return;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001430 }
Kevin Enderbybc5c29a2016-10-27 20:59:10 +00001431 // TODO: generate a error for unknown load commands by default. But still
1432 // need work out an approach to allow or not allow unknown values like this
1433 // as an option for some uses like lldb.
Alexey Samsonovde5a94a2015-06-04 19:57:46 +00001434 if (I < LoadCommandCount - 1) {
Kevin Enderby368e7142016-05-03 17:16:08 +00001435 if (auto LoadOrErr = getNextLoadCommandInfo(this, I, Load))
Lang Hames9e964f32016-03-25 17:25:34 +00001436 Load = *LoadOrErr;
1437 else {
1438 Err = LoadOrErr.takeError();
Alexey Samsonovde5a94a2015-06-04 19:57:46 +00001439 return;
1440 }
Alexey Samsonovde5a94a2015-06-04 19:57:46 +00001441 }
Rafael Espindola56f976f2013-04-18 18:08:55 +00001442 }
Kevin Enderby1829c682016-01-22 22:49:55 +00001443 if (!SymtabLoadCmd) {
1444 if (DysymtabLoadCmd) {
Kevin Enderbyd4e075b2016-05-06 20:16:28 +00001445 Err = malformedError("contains LC_DYSYMTAB load command without a "
Kevin Enderby89134962016-05-05 23:41:05 +00001446 "LC_SYMTAB load command");
Kevin Enderby1829c682016-01-22 22:49:55 +00001447 return;
1448 }
1449 } else if (DysymtabLoadCmd) {
1450 MachO::symtab_command Symtab =
1451 getStruct<MachO::symtab_command>(this, SymtabLoadCmd);
1452 MachO::dysymtab_command Dysymtab =
1453 getStruct<MachO::dysymtab_command>(this, DysymtabLoadCmd);
1454 if (Dysymtab.nlocalsym != 0 && Dysymtab.ilocalsym > Symtab.nsyms) {
Kevin Enderbyd4e075b2016-05-06 20:16:28 +00001455 Err = malformedError("ilocalsym in LC_DYSYMTAB load command "
Kevin Enderby89134962016-05-05 23:41:05 +00001456 "extends past the end of the symbol table");
Kevin Enderby1829c682016-01-22 22:49:55 +00001457 return;
1458 }
Kevin Enderby5e55d172016-04-21 20:29:49 +00001459 uint64_t BigSize = Dysymtab.ilocalsym;
1460 BigSize += Dysymtab.nlocalsym;
1461 if (Dysymtab.nlocalsym != 0 && BigSize > Symtab.nsyms) {
Kevin Enderbyd4e075b2016-05-06 20:16:28 +00001462 Err = malformedError("ilocalsym plus nlocalsym in LC_DYSYMTAB load "
Kevin Enderby89134962016-05-05 23:41:05 +00001463 "command extends past the end of the symbol table");
Kevin Enderby1829c682016-01-22 22:49:55 +00001464 return;
1465 }
1466 if (Dysymtab.nextdefsym != 0 && Dysymtab.ilocalsym > Symtab.nsyms) {
Kevin Enderbyd4e075b2016-05-06 20:16:28 +00001467 Err = malformedError("nextdefsym in LC_DYSYMTAB load command "
Kevin Enderby89134962016-05-05 23:41:05 +00001468 "extends past the end of the symbol table");
Kevin Enderby1829c682016-01-22 22:49:55 +00001469 return;
1470 }
Kevin Enderby5e55d172016-04-21 20:29:49 +00001471 BigSize = Dysymtab.iextdefsym;
1472 BigSize += Dysymtab.nextdefsym;
1473 if (Dysymtab.nextdefsym != 0 && BigSize > Symtab.nsyms) {
Kevin Enderbyd4e075b2016-05-06 20:16:28 +00001474 Err = malformedError("iextdefsym plus nextdefsym in LC_DYSYMTAB "
Kevin Enderby89134962016-05-05 23:41:05 +00001475 "load command extends past the end of the symbol "
1476 "table");
Kevin Enderby1829c682016-01-22 22:49:55 +00001477 return;
1478 }
1479 if (Dysymtab.nundefsym != 0 && Dysymtab.iundefsym > Symtab.nsyms) {
Kevin Enderbyd4e075b2016-05-06 20:16:28 +00001480 Err = malformedError("nundefsym in LC_DYSYMTAB load command "
Kevin Enderby89134962016-05-05 23:41:05 +00001481 "extends past the end of the symbol table");
Kevin Enderby1829c682016-01-22 22:49:55 +00001482 return;
1483 }
Kevin Enderby5e55d172016-04-21 20:29:49 +00001484 BigSize = Dysymtab.iundefsym;
1485 BigSize += Dysymtab.nundefsym;
1486 if (Dysymtab.nundefsym != 0 && BigSize > Symtab.nsyms) {
Kevin Enderbyd4e075b2016-05-06 20:16:28 +00001487 Err = malformedError("iundefsym plus nundefsym in LC_DYSYMTAB load "
Kevin Enderby89134962016-05-05 23:41:05 +00001488 " command extends past the end of the symbol table");
Kevin Enderby1829c682016-01-22 22:49:55 +00001489 return;
1490 }
1491 }
Kevin Enderbyfc0929a2016-09-20 20:14:14 +00001492 if ((getHeader().filetype == MachO::MH_DYLIB ||
1493 getHeader().filetype == MachO::MH_DYLIB_STUB) &&
1494 DyldIdLoadCmd == nullptr) {
1495 Err = malformedError("no LC_ID_DYLIB load command in dynamic library "
1496 "filetype");
1497 return;
1498 }
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00001499 assert(LoadCommands.size() == LoadCommandCount);
Lang Hames9e964f32016-03-25 17:25:34 +00001500
1501 Err = Error::success();
Rafael Espindola56f976f2013-04-18 18:08:55 +00001502}
1503
Rafael Espindola5e812af2014-01-30 02:49:50 +00001504void MachOObjectFile::moveSymbolNext(DataRefImpl &Symb) const {
Rafael Espindola75c30362013-04-24 19:47:55 +00001505 unsigned SymbolTableEntrySize = is64Bit() ?
Charles Davis8bdfafd2013-09-01 04:28:48 +00001506 sizeof(MachO::nlist_64) :
1507 sizeof(MachO::nlist);
Rafael Espindola75c30362013-04-24 19:47:55 +00001508 Symb.p += SymbolTableEntrySize;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001509}
1510
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001511Expected<StringRef> MachOObjectFile::getSymbolName(DataRefImpl Symb) const {
Rafael Espindola6e040c02013-04-26 20:07:33 +00001512 StringRef StringTable = getStringTableData();
Artyom Skrobov78d5daf2014-07-18 09:26:16 +00001513 MachO::nlist_base Entry = getSymbolTableEntryBase(this, Symb);
Charles Davis8bdfafd2013-09-01 04:28:48 +00001514 const char *Start = &StringTable.data()[Entry.n_strx];
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001515 if (Start < getData().begin() || Start >= getData().end()) {
Kevin Enderbyd4e075b2016-05-06 20:16:28 +00001516 return malformedError("bad string index: " + Twine(Entry.n_strx) +
Kevin Enderby89134962016-05-05 23:41:05 +00001517 " for symbol at index " + Twine(getSymbolIndex(Symb)));
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001518 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001519 return StringRef(Start);
Rafael Espindola56f976f2013-04-18 18:08:55 +00001520}
1521
Rafael Espindola0e77a942014-12-10 20:46:55 +00001522unsigned MachOObjectFile::getSectionType(SectionRef Sec) const {
1523 DataRefImpl DRI = Sec.getRawDataRefImpl();
1524 uint32_t Flags = getSectionFlags(this, DRI);
1525 return Flags & MachO::SECTION_TYPE;
1526}
1527
Rafael Espindola59128922015-06-24 18:14:41 +00001528uint64_t MachOObjectFile::getNValue(DataRefImpl Sym) const {
1529 if (is64Bit()) {
1530 MachO::nlist_64 Entry = getSymbol64TableEntry(Sym);
1531 return Entry.n_value;
1532 }
1533 MachO::nlist Entry = getSymbolTableEntry(Sym);
1534 return Entry.n_value;
1535}
1536
Kevin Enderby980b2582014-06-05 21:21:57 +00001537// getIndirectName() returns the name of the alias'ed symbol who's string table
1538// index is in the n_value field.
Rafael Espindola3acea392014-06-12 21:46:39 +00001539std::error_code MachOObjectFile::getIndirectName(DataRefImpl Symb,
1540 StringRef &Res) const {
Kevin Enderby980b2582014-06-05 21:21:57 +00001541 StringRef StringTable = getStringTableData();
Rafael Espindola59128922015-06-24 18:14:41 +00001542 MachO::nlist_base Entry = getSymbolTableEntryBase(this, Symb);
1543 if ((Entry.n_type & MachO::N_TYPE) != MachO::N_INDR)
1544 return object_error::parse_failed;
1545 uint64_t NValue = getNValue(Symb);
Kevin Enderby980b2582014-06-05 21:21:57 +00001546 if (NValue >= StringTable.size())
1547 return object_error::parse_failed;
1548 const char *Start = &StringTable.data()[NValue];
1549 Res = StringRef(Start);
Rui Ueyama7d099192015-06-09 15:20:42 +00001550 return std::error_code();
Kevin Enderby980b2582014-06-05 21:21:57 +00001551}
1552
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00001553uint64_t MachOObjectFile::getSymbolValueImpl(DataRefImpl Sym) const {
Rafael Espindola7e7be922015-07-07 15:05:09 +00001554 return getNValue(Sym);
Rafael Espindola991af662015-06-24 19:11:10 +00001555}
1556
Kevin Enderby931cb652016-06-24 18:24:42 +00001557Expected<uint64_t> MachOObjectFile::getSymbolAddress(DataRefImpl Sym) const {
Rafael Espindolaed067c42015-07-03 18:19:00 +00001558 return getSymbolValue(Sym);
Rafael Espindola56f976f2013-04-18 18:08:55 +00001559}
1560
Rafael Espindolaa4d224722015-05-31 23:52:50 +00001561uint32_t MachOObjectFile::getSymbolAlignment(DataRefImpl DRI) const {
Rafael Espindola20122a42014-01-31 20:57:12 +00001562 uint32_t flags = getSymbolFlags(DRI);
Rafael Espindolae4dd2e02013-04-29 22:24:22 +00001563 if (flags & SymbolRef::SF_Common) {
Artyom Skrobov78d5daf2014-07-18 09:26:16 +00001564 MachO::nlist_base Entry = getSymbolTableEntryBase(this, DRI);
Rafael Espindolaa4d224722015-05-31 23:52:50 +00001565 return 1 << MachO::GET_COMM_ALIGN(Entry.n_desc);
Rafael Espindolae4dd2e02013-04-29 22:24:22 +00001566 }
Rafael Espindolaa4d224722015-05-31 23:52:50 +00001567 return 0;
Rafael Espindolae4dd2e02013-04-29 22:24:22 +00001568}
1569
Rafael Espindolad7a32ea2015-06-24 10:20:30 +00001570uint64_t MachOObjectFile::getCommonSymbolSizeImpl(DataRefImpl DRI) const {
Rafael Espindola05cbccc2015-07-07 13:58:32 +00001571 return getNValue(DRI);
Rafael Espindola56f976f2013-04-18 18:08:55 +00001572}
1573
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001574Expected<SymbolRef::Type>
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00001575MachOObjectFile::getSymbolType(DataRefImpl Symb) const {
Artyom Skrobov78d5daf2014-07-18 09:26:16 +00001576 MachO::nlist_base Entry = getSymbolTableEntryBase(this, Symb);
Charles Davis8bdfafd2013-09-01 04:28:48 +00001577 uint8_t n_type = Entry.n_type;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001578
Rafael Espindola56f976f2013-04-18 18:08:55 +00001579 // If this is a STAB debugging symbol, we can do nothing more.
Rafael Espindola2fa80cc2015-06-26 12:18:49 +00001580 if (n_type & MachO::N_STAB)
1581 return SymbolRef::ST_Debug;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001582
Charles Davis74ec8b02013-08-27 05:00:13 +00001583 switch (n_type & MachO::N_TYPE) {
1584 case MachO::N_UNDF :
Rafael Espindola2fa80cc2015-06-26 12:18:49 +00001585 return SymbolRef::ST_Unknown;
Charles Davis74ec8b02013-08-27 05:00:13 +00001586 case MachO::N_SECT :
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001587 Expected<section_iterator> SecOrError = getSymbolSection(Symb);
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00001588 if (!SecOrError)
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001589 return SecOrError.takeError();
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00001590 section_iterator Sec = *SecOrError;
Kuba Breckade833222015-11-12 09:40:29 +00001591 if (Sec->isData() || Sec->isBSS())
1592 return SymbolRef::ST_Data;
Rafael Espindola2fa80cc2015-06-26 12:18:49 +00001593 return SymbolRef::ST_Function;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001594 }
Rafael Espindola2fa80cc2015-06-26 12:18:49 +00001595 return SymbolRef::ST_Other;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001596}
1597
Rafael Espindola20122a42014-01-31 20:57:12 +00001598uint32_t MachOObjectFile::getSymbolFlags(DataRefImpl DRI) const {
Artyom Skrobov78d5daf2014-07-18 09:26:16 +00001599 MachO::nlist_base Entry = getSymbolTableEntryBase(this, DRI);
Rafael Espindola56f976f2013-04-18 18:08:55 +00001600
Charles Davis8bdfafd2013-09-01 04:28:48 +00001601 uint8_t MachOType = Entry.n_type;
1602 uint16_t MachOFlags = Entry.n_desc;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001603
Rafael Espindola20122a42014-01-31 20:57:12 +00001604 uint32_t Result = SymbolRef::SF_None;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001605
Tim Northovereaef0742014-05-30 13:22:59 +00001606 if ((MachOType & MachO::N_TYPE) == MachO::N_INDR)
1607 Result |= SymbolRef::SF_Indirect;
1608
Rafael Espindolaa1356322013-11-02 05:03:24 +00001609 if (MachOType & MachO::N_STAB)
Rafael Espindola56f976f2013-04-18 18:08:55 +00001610 Result |= SymbolRef::SF_FormatSpecific;
1611
Charles Davis74ec8b02013-08-27 05:00:13 +00001612 if (MachOType & MachO::N_EXT) {
Rafael Espindola56f976f2013-04-18 18:08:55 +00001613 Result |= SymbolRef::SF_Global;
Charles Davis74ec8b02013-08-27 05:00:13 +00001614 if ((MachOType & MachO::N_TYPE) == MachO::N_UNDF) {
Rafael Espindola05cbccc2015-07-07 13:58:32 +00001615 if (getNValue(DRI))
Rafael Espindolae4dd2e02013-04-29 22:24:22 +00001616 Result |= SymbolRef::SF_Common;
Rafael Espindolad8247722015-07-07 14:26:39 +00001617 else
1618 Result |= SymbolRef::SF_Undefined;
Rafael Espindolae4dd2e02013-04-29 22:24:22 +00001619 }
Lang Hames7e0692b2015-01-15 22:33:30 +00001620
1621 if (!(MachOType & MachO::N_PEXT))
1622 Result |= SymbolRef::SF_Exported;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001623 }
1624
Charles Davis74ec8b02013-08-27 05:00:13 +00001625 if (MachOFlags & (MachO::N_WEAK_REF | MachO::N_WEAK_DEF))
Rafael Espindola56f976f2013-04-18 18:08:55 +00001626 Result |= SymbolRef::SF_Weak;
1627
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001628 if (MachOFlags & (MachO::N_ARM_THUMB_DEF))
1629 Result |= SymbolRef::SF_Thumb;
1630
Charles Davis74ec8b02013-08-27 05:00:13 +00001631 if ((MachOType & MachO::N_TYPE) == MachO::N_ABS)
Rafael Espindola56f976f2013-04-18 18:08:55 +00001632 Result |= SymbolRef::SF_Absolute;
1633
Rafael Espindola20122a42014-01-31 20:57:12 +00001634 return Result;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001635}
1636
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001637Expected<section_iterator>
Rafael Espindola8bab8892015-08-07 23:27:14 +00001638MachOObjectFile::getSymbolSection(DataRefImpl Symb) const {
Artyom Skrobov78d5daf2014-07-18 09:26:16 +00001639 MachO::nlist_base Entry = getSymbolTableEntryBase(this, Symb);
Charles Davis8bdfafd2013-09-01 04:28:48 +00001640 uint8_t index = Entry.n_sect;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001641
Rafael Espindola8bab8892015-08-07 23:27:14 +00001642 if (index == 0)
1643 return section_end();
1644 DataRefImpl DRI;
1645 DRI.d.a = index - 1;
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00001646 if (DRI.d.a >= Sections.size()){
Kevin Enderbyd4e075b2016-05-06 20:16:28 +00001647 return malformedError("bad section index: " + Twine((int)index) +
Kevin Enderby89134962016-05-05 23:41:05 +00001648 " for symbol at index " + Twine(getSymbolIndex(Symb)));
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00001649 }
Rafael Espindola8bab8892015-08-07 23:27:14 +00001650 return section_iterator(SectionRef(DRI, this));
Rafael Espindola56f976f2013-04-18 18:08:55 +00001651}
1652
Rafael Espindola6bf32212015-06-24 19:57:32 +00001653unsigned MachOObjectFile::getSymbolSectionID(SymbolRef Sym) const {
1654 MachO::nlist_base Entry =
1655 getSymbolTableEntryBase(this, Sym.getRawDataRefImpl());
1656 return Entry.n_sect - 1;
1657}
1658
Rafael Espindola5e812af2014-01-30 02:49:50 +00001659void MachOObjectFile::moveSectionNext(DataRefImpl &Sec) const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00001660 Sec.d.a++;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001661}
1662
Rafael Espindola3acea392014-06-12 21:46:39 +00001663std::error_code MachOObjectFile::getSectionName(DataRefImpl Sec,
1664 StringRef &Result) const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00001665 ArrayRef<char> Raw = getSectionRawName(Sec);
1666 Result = parseSegmentOrSectionName(Raw.data());
Rui Ueyama7d099192015-06-09 15:20:42 +00001667 return std::error_code();
Rafael Espindola56f976f2013-04-18 18:08:55 +00001668}
1669
Rafael Espindola80291272014-10-08 15:28:58 +00001670uint64_t MachOObjectFile::getSectionAddress(DataRefImpl Sec) const {
1671 if (is64Bit())
1672 return getSection64(Sec).addr;
1673 return getSection(Sec).addr;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001674}
1675
Rafael Espindola80291272014-10-08 15:28:58 +00001676uint64_t MachOObjectFile::getSectionSize(DataRefImpl Sec) const {
Kevin Enderby46e642f2015-10-08 22:50:55 +00001677 // In the case if a malformed Mach-O file where the section offset is past
1678 // the end of the file or some part of the section size is past the end of
1679 // the file return a size of zero or a size that covers the rest of the file
1680 // but does not extend past the end of the file.
1681 uint32_t SectOffset, SectType;
1682 uint64_t SectSize;
1683
1684 if (is64Bit()) {
1685 MachO::section_64 Sect = getSection64(Sec);
1686 SectOffset = Sect.offset;
1687 SectSize = Sect.size;
1688 SectType = Sect.flags & MachO::SECTION_TYPE;
1689 } else {
1690 MachO::section Sect = getSection(Sec);
1691 SectOffset = Sect.offset;
1692 SectSize = Sect.size;
1693 SectType = Sect.flags & MachO::SECTION_TYPE;
1694 }
1695 if (SectType == MachO::S_ZEROFILL || SectType == MachO::S_GB_ZEROFILL)
1696 return SectSize;
1697 uint64_t FileSize = getData().size();
1698 if (SectOffset > FileSize)
1699 return 0;
1700 if (FileSize - SectOffset < SectSize)
1701 return FileSize - SectOffset;
1702 return SectSize;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001703}
1704
Rafael Espindola3acea392014-06-12 21:46:39 +00001705std::error_code MachOObjectFile::getSectionContents(DataRefImpl Sec,
1706 StringRef &Res) const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00001707 uint32_t Offset;
1708 uint64_t Size;
1709
1710 if (is64Bit()) {
Charles Davis8bdfafd2013-09-01 04:28:48 +00001711 MachO::section_64 Sect = getSection64(Sec);
1712 Offset = Sect.offset;
1713 Size = Sect.size;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001714 } else {
Charles Davis8bdfafd2013-09-01 04:28:48 +00001715 MachO::section Sect = getSection(Sec);
1716 Offset = Sect.offset;
1717 Size = Sect.size;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001718 }
1719
1720 Res = this->getData().substr(Offset, Size);
Rui Ueyama7d099192015-06-09 15:20:42 +00001721 return std::error_code();
Rafael Espindola56f976f2013-04-18 18:08:55 +00001722}
1723
Rafael Espindola80291272014-10-08 15:28:58 +00001724uint64_t MachOObjectFile::getSectionAlignment(DataRefImpl Sec) const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00001725 uint32_t Align;
1726 if (is64Bit()) {
Charles Davis8bdfafd2013-09-01 04:28:48 +00001727 MachO::section_64 Sect = getSection64(Sec);
1728 Align = Sect.align;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001729 } else {
Charles Davis8bdfafd2013-09-01 04:28:48 +00001730 MachO::section Sect = getSection(Sec);
1731 Align = Sect.align;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001732 }
1733
Rafael Espindola80291272014-10-08 15:28:58 +00001734 return uint64_t(1) << Align;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001735}
1736
George Rimar401e4e52016-05-24 12:48:46 +00001737bool MachOObjectFile::isSectionCompressed(DataRefImpl Sec) const {
1738 return false;
1739}
1740
Rafael Espindola80291272014-10-08 15:28:58 +00001741bool MachOObjectFile::isSectionText(DataRefImpl Sec) const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00001742 uint32_t Flags = getSectionFlags(this, Sec);
Rafael Espindola80291272014-10-08 15:28:58 +00001743 return Flags & MachO::S_ATTR_PURE_INSTRUCTIONS;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001744}
1745
Rafael Espindola80291272014-10-08 15:28:58 +00001746bool MachOObjectFile::isSectionData(DataRefImpl Sec) const {
Kevin Enderby403258f2014-05-19 20:36:02 +00001747 uint32_t Flags = getSectionFlags(this, Sec);
1748 unsigned SectionType = Flags & MachO::SECTION_TYPE;
Rafael Espindola80291272014-10-08 15:28:58 +00001749 return !(Flags & MachO::S_ATTR_PURE_INSTRUCTIONS) &&
1750 !(SectionType == MachO::S_ZEROFILL ||
1751 SectionType == MachO::S_GB_ZEROFILL);
Michael J. Spencer800619f2011-09-28 20:57:30 +00001752}
1753
Rafael Espindola80291272014-10-08 15:28:58 +00001754bool MachOObjectFile::isSectionBSS(DataRefImpl Sec) const {
Kevin Enderby403258f2014-05-19 20:36:02 +00001755 uint32_t Flags = getSectionFlags(this, Sec);
1756 unsigned SectionType = Flags & MachO::SECTION_TYPE;
Rafael Espindola80291272014-10-08 15:28:58 +00001757 return !(Flags & MachO::S_ATTR_PURE_INSTRUCTIONS) &&
1758 (SectionType == MachO::S_ZEROFILL ||
1759 SectionType == MachO::S_GB_ZEROFILL);
Preston Gurd2138ef62012-04-12 20:13:57 +00001760}
1761
Rafael Espindola6bf32212015-06-24 19:57:32 +00001762unsigned MachOObjectFile::getSectionID(SectionRef Sec) const {
1763 return Sec.getRawDataRefImpl().d.a;
1764}
1765
Rafael Espindola80291272014-10-08 15:28:58 +00001766bool MachOObjectFile::isSectionVirtual(DataRefImpl Sec) const {
Rafael Espindolac2413f52013-04-09 14:49:08 +00001767 // FIXME: Unimplemented.
Rafael Espindola80291272014-10-08 15:28:58 +00001768 return false;
Rafael Espindolac2413f52013-04-09 14:49:08 +00001769}
1770
Steven Wuf2fe0142016-02-29 19:40:10 +00001771bool MachOObjectFile::isSectionBitcode(DataRefImpl Sec) const {
1772 StringRef SegmentName = getSectionFinalSegmentName(Sec);
1773 StringRef SectName;
1774 if (!getSectionName(Sec, SectName))
1775 return (SegmentName == "__LLVM" && SectName == "__bitcode");
1776 return false;
1777}
1778
Rui Ueyamabc654b12013-09-27 21:47:05 +00001779relocation_iterator MachOObjectFile::section_rel_begin(DataRefImpl Sec) const {
Rafael Espindola04d3f492013-04-25 12:45:46 +00001780 DataRefImpl Ret;
Rafael Espindola128b8112014-04-03 23:51:28 +00001781 Ret.d.a = Sec.d.a;
1782 Ret.d.b = 0;
Rafael Espindola04d3f492013-04-25 12:45:46 +00001783 return relocation_iterator(RelocationRef(Ret, this));
Michael J. Spencere5fd0042011-10-07 19:25:32 +00001784}
Rafael Espindolac0406e12013-04-08 20:45:01 +00001785
Rafael Espindola56f976f2013-04-18 18:08:55 +00001786relocation_iterator
Rui Ueyamabc654b12013-09-27 21:47:05 +00001787MachOObjectFile::section_rel_end(DataRefImpl Sec) const {
Rafael Espindola04d3f492013-04-25 12:45:46 +00001788 uint32_t Num;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001789 if (is64Bit()) {
Charles Davis8bdfafd2013-09-01 04:28:48 +00001790 MachO::section_64 Sect = getSection64(Sec);
Charles Davis8bdfafd2013-09-01 04:28:48 +00001791 Num = Sect.nreloc;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001792 } else {
Charles Davis8bdfafd2013-09-01 04:28:48 +00001793 MachO::section Sect = getSection(Sec);
Charles Davis8bdfafd2013-09-01 04:28:48 +00001794 Num = Sect.nreloc;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001795 }
Eric Christopher7b015c72011-04-22 03:19:48 +00001796
Rafael Espindola56f976f2013-04-18 18:08:55 +00001797 DataRefImpl Ret;
Rafael Espindola128b8112014-04-03 23:51:28 +00001798 Ret.d.a = Sec.d.a;
1799 Ret.d.b = Num;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001800 return relocation_iterator(RelocationRef(Ret, this));
1801}
Benjamin Kramer022ecdf2011-09-08 20:52:17 +00001802
Rafael Espindola5e812af2014-01-30 02:49:50 +00001803void MachOObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
Rafael Espindola128b8112014-04-03 23:51:28 +00001804 ++Rel.d.b;
Benjamin Kramer022ecdf2011-09-08 20:52:17 +00001805}
Owen Anderson171f4852011-10-24 23:20:07 +00001806
Rafael Espindola96d071c2015-06-29 23:29:12 +00001807uint64_t MachOObjectFile::getRelocationOffset(DataRefImpl Rel) const {
Rafael Espindola72475462014-04-04 00:31:12 +00001808 assert(getHeader().filetype == MachO::MH_OBJECT &&
1809 "Only implemented for MH_OBJECT");
Charles Davis8bdfafd2013-09-01 04:28:48 +00001810 MachO::any_relocation_info RE = getRelocation(Rel);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001811 return getAnyRelocationAddress(RE);
David Meyer2fc34c52012-03-01 01:36:50 +00001812}
1813
Rafael Espindola806f0062013-06-05 01:33:53 +00001814symbol_iterator
1815MachOObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
Charles Davis8bdfafd2013-09-01 04:28:48 +00001816 MachO::any_relocation_info RE = getRelocation(Rel);
Tim Northover07f99fb2014-07-04 10:57:56 +00001817 if (isRelocationScattered(RE))
1818 return symbol_end();
1819
Rafael Espindola56f976f2013-04-18 18:08:55 +00001820 uint32_t SymbolIdx = getPlainRelocationSymbolNum(RE);
1821 bool isExtern = getPlainRelocationExternal(RE);
Rafael Espindola806f0062013-06-05 01:33:53 +00001822 if (!isExtern)
Rafael Espindolab5155a52014-02-10 20:24:04 +00001823 return symbol_end();
Rafael Espindola75c30362013-04-24 19:47:55 +00001824
Charles Davis8bdfafd2013-09-01 04:28:48 +00001825 MachO::symtab_command S = getSymtabLoadCommand();
Rafael Espindola75c30362013-04-24 19:47:55 +00001826 unsigned SymbolTableEntrySize = is64Bit() ?
Charles Davis8bdfafd2013-09-01 04:28:48 +00001827 sizeof(MachO::nlist_64) :
1828 sizeof(MachO::nlist);
1829 uint64_t Offset = S.symoff + SymbolIdx * SymbolTableEntrySize;
Rafael Espindola75c30362013-04-24 19:47:55 +00001830 DataRefImpl Sym;
1831 Sym.p = reinterpret_cast<uintptr_t>(getPtr(this, Offset));
Rafael Espindola806f0062013-06-05 01:33:53 +00001832 return symbol_iterator(SymbolRef(Sym, this));
Rafael Espindola56f976f2013-04-18 18:08:55 +00001833}
1834
Keno Fischerc780e8e2015-05-21 21:24:32 +00001835section_iterator
1836MachOObjectFile::getRelocationSection(DataRefImpl Rel) const {
1837 return section_iterator(getAnyRelocationSection(getRelocation(Rel)));
1838}
1839
Rafael Espindola99c041b2015-06-30 01:53:01 +00001840uint64_t MachOObjectFile::getRelocationType(DataRefImpl Rel) const {
Charles Davis8bdfafd2013-09-01 04:28:48 +00001841 MachO::any_relocation_info RE = getRelocation(Rel);
Rafael Espindola99c041b2015-06-30 01:53:01 +00001842 return getAnyRelocationType(RE);
Rafael Espindola56f976f2013-04-18 18:08:55 +00001843}
1844
Rafael Espindola41bb4322015-06-30 04:08:37 +00001845void MachOObjectFile::getRelocationTypeName(
1846 DataRefImpl Rel, SmallVectorImpl<char> &Result) const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00001847 StringRef res;
Rafael Espindola99c041b2015-06-30 01:53:01 +00001848 uint64_t RType = getRelocationType(Rel);
Rafael Espindola56f976f2013-04-18 18:08:55 +00001849
1850 unsigned Arch = this->getArch();
1851
1852 switch (Arch) {
1853 case Triple::x86: {
1854 static const char *const Table[] = {
1855 "GENERIC_RELOC_VANILLA",
1856 "GENERIC_RELOC_PAIR",
1857 "GENERIC_RELOC_SECTDIFF",
1858 "GENERIC_RELOC_PB_LA_PTR",
1859 "GENERIC_RELOC_LOCAL_SECTDIFF",
1860 "GENERIC_RELOC_TLV" };
1861
Eric Christopher13250cb2013-12-06 02:33:38 +00001862 if (RType > 5)
Rafael Espindola56f976f2013-04-18 18:08:55 +00001863 res = "Unknown";
1864 else
1865 res = Table[RType];
1866 break;
1867 }
1868 case Triple::x86_64: {
1869 static const char *const Table[] = {
1870 "X86_64_RELOC_UNSIGNED",
1871 "X86_64_RELOC_SIGNED",
1872 "X86_64_RELOC_BRANCH",
1873 "X86_64_RELOC_GOT_LOAD",
1874 "X86_64_RELOC_GOT",
1875 "X86_64_RELOC_SUBTRACTOR",
1876 "X86_64_RELOC_SIGNED_1",
1877 "X86_64_RELOC_SIGNED_2",
1878 "X86_64_RELOC_SIGNED_4",
1879 "X86_64_RELOC_TLV" };
1880
1881 if (RType > 9)
1882 res = "Unknown";
1883 else
1884 res = Table[RType];
1885 break;
1886 }
1887 case Triple::arm: {
1888 static const char *const Table[] = {
1889 "ARM_RELOC_VANILLA",
1890 "ARM_RELOC_PAIR",
1891 "ARM_RELOC_SECTDIFF",
1892 "ARM_RELOC_LOCAL_SECTDIFF",
1893 "ARM_RELOC_PB_LA_PTR",
1894 "ARM_RELOC_BR24",
1895 "ARM_THUMB_RELOC_BR22",
1896 "ARM_THUMB_32BIT_BRANCH",
1897 "ARM_RELOC_HALF",
1898 "ARM_RELOC_HALF_SECTDIFF" };
1899
1900 if (RType > 9)
1901 res = "Unknown";
1902 else
1903 res = Table[RType];
1904 break;
1905 }
Tim Northover00ed9962014-03-29 10:18:08 +00001906 case Triple::aarch64: {
1907 static const char *const Table[] = {
1908 "ARM64_RELOC_UNSIGNED", "ARM64_RELOC_SUBTRACTOR",
1909 "ARM64_RELOC_BRANCH26", "ARM64_RELOC_PAGE21",
1910 "ARM64_RELOC_PAGEOFF12", "ARM64_RELOC_GOT_LOAD_PAGE21",
1911 "ARM64_RELOC_GOT_LOAD_PAGEOFF12", "ARM64_RELOC_POINTER_TO_GOT",
1912 "ARM64_RELOC_TLVP_LOAD_PAGE21", "ARM64_RELOC_TLVP_LOAD_PAGEOFF12",
1913 "ARM64_RELOC_ADDEND"
1914 };
1915
1916 if (RType >= array_lengthof(Table))
1917 res = "Unknown";
1918 else
1919 res = Table[RType];
1920 break;
1921 }
Rafael Espindola56f976f2013-04-18 18:08:55 +00001922 case Triple::ppc: {
1923 static const char *const Table[] = {
1924 "PPC_RELOC_VANILLA",
1925 "PPC_RELOC_PAIR",
1926 "PPC_RELOC_BR14",
1927 "PPC_RELOC_BR24",
1928 "PPC_RELOC_HI16",
1929 "PPC_RELOC_LO16",
1930 "PPC_RELOC_HA16",
1931 "PPC_RELOC_LO14",
1932 "PPC_RELOC_SECTDIFF",
1933 "PPC_RELOC_PB_LA_PTR",
1934 "PPC_RELOC_HI16_SECTDIFF",
1935 "PPC_RELOC_LO16_SECTDIFF",
1936 "PPC_RELOC_HA16_SECTDIFF",
1937 "PPC_RELOC_JBSR",
1938 "PPC_RELOC_LO14_SECTDIFF",
1939 "PPC_RELOC_LOCAL_SECTDIFF" };
1940
Eric Christopher13250cb2013-12-06 02:33:38 +00001941 if (RType > 15)
1942 res = "Unknown";
1943 else
1944 res = Table[RType];
Rafael Espindola56f976f2013-04-18 18:08:55 +00001945 break;
1946 }
1947 case Triple::UnknownArch:
1948 res = "Unknown";
1949 break;
1950 }
1951 Result.append(res.begin(), res.end());
Rafael Espindola56f976f2013-04-18 18:08:55 +00001952}
1953
Keno Fischer281b6942015-05-30 19:44:53 +00001954uint8_t MachOObjectFile::getRelocationLength(DataRefImpl Rel) const {
1955 MachO::any_relocation_info RE = getRelocation(Rel);
1956 return getAnyRelocationLength(RE);
1957}
1958
Kevin Enderby980b2582014-06-05 21:21:57 +00001959//
1960// guessLibraryShortName() is passed a name of a dynamic library and returns a
1961// guess on what the short name is. Then name is returned as a substring of the
1962// StringRef Name passed in. The name of the dynamic library is recognized as
1963// a framework if it has one of the two following forms:
1964// Foo.framework/Versions/A/Foo
1965// Foo.framework/Foo
1966// Where A and Foo can be any string. And may contain a trailing suffix
1967// starting with an underbar. If the Name is recognized as a framework then
1968// isFramework is set to true else it is set to false. If the Name has a
1969// suffix then Suffix is set to the substring in Name that contains the suffix
1970// else it is set to a NULL StringRef.
1971//
1972// The Name of the dynamic library is recognized as a library name if it has
1973// one of the two following forms:
1974// libFoo.A.dylib
1975// libFoo.dylib
1976// The library may have a suffix trailing the name Foo of the form:
1977// libFoo_profile.A.dylib
1978// libFoo_profile.dylib
1979//
1980// The Name of the dynamic library is also recognized as a library name if it
1981// has the following form:
1982// Foo.qtx
1983//
1984// If the Name of the dynamic library is none of the forms above then a NULL
1985// StringRef is returned.
1986//
1987StringRef MachOObjectFile::guessLibraryShortName(StringRef Name,
1988 bool &isFramework,
1989 StringRef &Suffix) {
1990 StringRef Foo, F, DotFramework, V, Dylib, Lib, Dot, Qtx;
1991 size_t a, b, c, d, Idx;
1992
1993 isFramework = false;
1994 Suffix = StringRef();
1995
1996 // Pull off the last component and make Foo point to it
1997 a = Name.rfind('/');
1998 if (a == Name.npos || a == 0)
1999 goto guess_library;
2000 Foo = Name.slice(a+1, Name.npos);
2001
2002 // Look for a suffix starting with a '_'
2003 Idx = Foo.rfind('_');
2004 if (Idx != Foo.npos && Foo.size() >= 2) {
2005 Suffix = Foo.slice(Idx, Foo.npos);
2006 Foo = Foo.slice(0, Idx);
2007 }
2008
2009 // First look for the form Foo.framework/Foo
2010 b = Name.rfind('/', a);
2011 if (b == Name.npos)
2012 Idx = 0;
2013 else
2014 Idx = b+1;
2015 F = Name.slice(Idx, Idx + Foo.size());
2016 DotFramework = Name.slice(Idx + Foo.size(),
2017 Idx + Foo.size() + sizeof(".framework/")-1);
2018 if (F == Foo && DotFramework == ".framework/") {
2019 isFramework = true;
2020 return Foo;
2021 }
2022
2023 // Next look for the form Foo.framework/Versions/A/Foo
2024 if (b == Name.npos)
2025 goto guess_library;
2026 c = Name.rfind('/', b);
2027 if (c == Name.npos || c == 0)
2028 goto guess_library;
2029 V = Name.slice(c+1, Name.npos);
2030 if (!V.startswith("Versions/"))
2031 goto guess_library;
2032 d = Name.rfind('/', c);
2033 if (d == Name.npos)
2034 Idx = 0;
2035 else
2036 Idx = d+1;
2037 F = Name.slice(Idx, Idx + Foo.size());
2038 DotFramework = Name.slice(Idx + Foo.size(),
2039 Idx + Foo.size() + sizeof(".framework/")-1);
2040 if (F == Foo && DotFramework == ".framework/") {
2041 isFramework = true;
2042 return Foo;
2043 }
2044
2045guess_library:
2046 // pull off the suffix after the "." and make a point to it
2047 a = Name.rfind('.');
2048 if (a == Name.npos || a == 0)
2049 return StringRef();
2050 Dylib = Name.slice(a, Name.npos);
2051 if (Dylib != ".dylib")
2052 goto guess_qtx;
2053
2054 // First pull off the version letter for the form Foo.A.dylib if any.
2055 if (a >= 3) {
2056 Dot = Name.slice(a-2, a-1);
2057 if (Dot == ".")
2058 a = a - 2;
2059 }
2060
2061 b = Name.rfind('/', a);
2062 if (b == Name.npos)
2063 b = 0;
2064 else
2065 b = b+1;
2066 // ignore any suffix after an underbar like Foo_profile.A.dylib
2067 Idx = Name.find('_', b);
2068 if (Idx != Name.npos && Idx != b) {
2069 Lib = Name.slice(b, Idx);
2070 Suffix = Name.slice(Idx, a);
2071 }
2072 else
2073 Lib = Name.slice(b, a);
2074 // There are incorrect library names of the form:
2075 // libATS.A_profile.dylib so check for these.
2076 if (Lib.size() >= 3) {
2077 Dot = Lib.slice(Lib.size()-2, Lib.size()-1);
2078 if (Dot == ".")
2079 Lib = Lib.slice(0, Lib.size()-2);
2080 }
2081 return Lib;
2082
2083guess_qtx:
2084 Qtx = Name.slice(a, Name.npos);
2085 if (Qtx != ".qtx")
2086 return StringRef();
2087 b = Name.rfind('/', a);
2088 if (b == Name.npos)
2089 Lib = Name.slice(0, a);
2090 else
2091 Lib = Name.slice(b+1, a);
2092 // There are library names of the form: QT.A.qtx so check for these.
2093 if (Lib.size() >= 3) {
2094 Dot = Lib.slice(Lib.size()-2, Lib.size()-1);
2095 if (Dot == ".")
2096 Lib = Lib.slice(0, Lib.size()-2);
2097 }
2098 return Lib;
2099}
2100
2101// getLibraryShortNameByIndex() is used to get the short name of the library
2102// for an undefined symbol in a linked Mach-O binary that was linked with the
2103// normal two-level namespace default (that is MH_TWOLEVEL in the header).
2104// It is passed the index (0 - based) of the library as translated from
2105// GET_LIBRARY_ORDINAL (1 - based).
Rafael Espindola3acea392014-06-12 21:46:39 +00002106std::error_code MachOObjectFile::getLibraryShortNameByIndex(unsigned Index,
Nick Kledzikd04bc352014-08-30 00:20:14 +00002107 StringRef &Res) const {
Kevin Enderby980b2582014-06-05 21:21:57 +00002108 if (Index >= Libraries.size())
2109 return object_error::parse_failed;
2110
Kevin Enderby980b2582014-06-05 21:21:57 +00002111 // If the cache of LibrariesShortNames is not built up do that first for
2112 // all the Libraries.
2113 if (LibrariesShortNames.size() == 0) {
2114 for (unsigned i = 0; i < Libraries.size(); i++) {
2115 MachO::dylib_command D =
2116 getStruct<MachO::dylib_command>(this, Libraries[i]);
Nick Kledzik30061302014-09-17 00:25:22 +00002117 if (D.dylib.name >= D.cmdsize)
2118 return object_error::parse_failed;
Kevin Enderby4eff6cd2014-06-20 18:07:34 +00002119 const char *P = (const char *)(Libraries[i]) + D.dylib.name;
Kevin Enderby980b2582014-06-05 21:21:57 +00002120 StringRef Name = StringRef(P);
Nick Kledzik30061302014-09-17 00:25:22 +00002121 if (D.dylib.name+Name.size() >= D.cmdsize)
2122 return object_error::parse_failed;
Kevin Enderby980b2582014-06-05 21:21:57 +00002123 StringRef Suffix;
2124 bool isFramework;
2125 StringRef shortName = guessLibraryShortName(Name, isFramework, Suffix);
Nick Kledzik30061302014-09-17 00:25:22 +00002126 if (shortName.empty())
Kevin Enderby980b2582014-06-05 21:21:57 +00002127 LibrariesShortNames.push_back(Name);
2128 else
2129 LibrariesShortNames.push_back(shortName);
2130 }
2131 }
2132
2133 Res = LibrariesShortNames[Index];
Rui Ueyama7d099192015-06-09 15:20:42 +00002134 return std::error_code();
Kevin Enderby980b2582014-06-05 21:21:57 +00002135}
2136
Rafael Espindola76ad2322015-07-06 14:55:37 +00002137section_iterator
2138MachOObjectFile::getRelocationRelocatedSection(relocation_iterator Rel) const {
2139 DataRefImpl Sec;
2140 Sec.d.a = Rel->getRawDataRefImpl().d.a;
2141 return section_iterator(SectionRef(Sec, this));
2142}
2143
Rafael Espindolaf12b8282014-02-21 20:10:59 +00002144basic_symbol_iterator MachOObjectFile::symbol_begin_impl() const {
Kevin Enderby1829c682016-01-22 22:49:55 +00002145 DataRefImpl DRI;
2146 MachO::symtab_command Symtab = getSymtabLoadCommand();
2147 if (!SymtabLoadCmd || Symtab.nsyms == 0)
2148 return basic_symbol_iterator(SymbolRef(DRI, this));
2149
Lang Hames36072da2014-05-12 21:39:59 +00002150 return getSymbolByIndex(0);
Rafael Espindola56f976f2013-04-18 18:08:55 +00002151}
2152
Rafael Espindolaf12b8282014-02-21 20:10:59 +00002153basic_symbol_iterator MachOObjectFile::symbol_end_impl() const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00002154 DataRefImpl DRI;
Kevin Enderby1829c682016-01-22 22:49:55 +00002155 MachO::symtab_command Symtab = getSymtabLoadCommand();
2156 if (!SymtabLoadCmd || Symtab.nsyms == 0)
Rafael Espindolaf12b8282014-02-21 20:10:59 +00002157 return basic_symbol_iterator(SymbolRef(DRI, this));
Rafael Espindola75c30362013-04-24 19:47:55 +00002158
Rafael Espindola75c30362013-04-24 19:47:55 +00002159 unsigned SymbolTableEntrySize = is64Bit() ?
Charles Davis8bdfafd2013-09-01 04:28:48 +00002160 sizeof(MachO::nlist_64) :
2161 sizeof(MachO::nlist);
2162 unsigned Offset = Symtab.symoff +
2163 Symtab.nsyms * SymbolTableEntrySize;
Rafael Espindola75c30362013-04-24 19:47:55 +00002164 DRI.p = reinterpret_cast<uintptr_t>(getPtr(this, Offset));
Rafael Espindolaf12b8282014-02-21 20:10:59 +00002165 return basic_symbol_iterator(SymbolRef(DRI, this));
Rafael Espindola56f976f2013-04-18 18:08:55 +00002166}
2167
Lang Hames36072da2014-05-12 21:39:59 +00002168basic_symbol_iterator MachOObjectFile::getSymbolByIndex(unsigned Index) const {
Lang Hames36072da2014-05-12 21:39:59 +00002169 MachO::symtab_command Symtab = getSymtabLoadCommand();
Kevin Enderby1829c682016-01-22 22:49:55 +00002170 if (!SymtabLoadCmd || Index >= Symtab.nsyms)
Filipe Cabecinhas40139502015-01-15 22:52:38 +00002171 report_fatal_error("Requested symbol index is out of range.");
Lang Hames36072da2014-05-12 21:39:59 +00002172 unsigned SymbolTableEntrySize =
2173 is64Bit() ? sizeof(MachO::nlist_64) : sizeof(MachO::nlist);
Kevin Enderby1829c682016-01-22 22:49:55 +00002174 DataRefImpl DRI;
Lang Hames36072da2014-05-12 21:39:59 +00002175 DRI.p = reinterpret_cast<uintptr_t>(getPtr(this, Symtab.symoff));
2176 DRI.p += Index * SymbolTableEntrySize;
2177 return basic_symbol_iterator(SymbolRef(DRI, this));
2178}
2179
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002180uint64_t MachOObjectFile::getSymbolIndex(DataRefImpl Symb) const {
2181 MachO::symtab_command Symtab = getSymtabLoadCommand();
2182 if (!SymtabLoadCmd)
2183 report_fatal_error("getSymbolIndex() called with no symbol table symbol");
2184 unsigned SymbolTableEntrySize =
2185 is64Bit() ? sizeof(MachO::nlist_64) : sizeof(MachO::nlist);
2186 DataRefImpl DRIstart;
2187 DRIstart.p = reinterpret_cast<uintptr_t>(getPtr(this, Symtab.symoff));
2188 uint64_t Index = (Symb.p - DRIstart.p) / SymbolTableEntrySize;
2189 return Index;
2190}
2191
Rafael Espindolab5155a52014-02-10 20:24:04 +00002192section_iterator MachOObjectFile::section_begin() const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00002193 DataRefImpl DRI;
2194 return section_iterator(SectionRef(DRI, this));
2195}
2196
Rafael Espindolab5155a52014-02-10 20:24:04 +00002197section_iterator MachOObjectFile::section_end() const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00002198 DataRefImpl DRI;
2199 DRI.d.a = Sections.size();
2200 return section_iterator(SectionRef(DRI, this));
2201}
2202
Rafael Espindola56f976f2013-04-18 18:08:55 +00002203uint8_t MachOObjectFile::getBytesInAddress() const {
Rafael Espindola60689982013-04-07 19:05:30 +00002204 return is64Bit() ? 8 : 4;
Eric Christopher7b015c72011-04-22 03:19:48 +00002205}
2206
Rafael Espindola56f976f2013-04-18 18:08:55 +00002207StringRef MachOObjectFile::getFileFormatName() const {
2208 unsigned CPUType = getCPUType(this);
2209 if (!is64Bit()) {
2210 switch (CPUType) {
Charles Davis74ec8b02013-08-27 05:00:13 +00002211 case llvm::MachO::CPU_TYPE_I386:
Rafael Espindola56f976f2013-04-18 18:08:55 +00002212 return "Mach-O 32-bit i386";
Charles Davis74ec8b02013-08-27 05:00:13 +00002213 case llvm::MachO::CPU_TYPE_ARM:
Rafael Espindola56f976f2013-04-18 18:08:55 +00002214 return "Mach-O arm";
Charles Davis74ec8b02013-08-27 05:00:13 +00002215 case llvm::MachO::CPU_TYPE_POWERPC:
Rafael Espindola56f976f2013-04-18 18:08:55 +00002216 return "Mach-O 32-bit ppc";
2217 default:
Rafael Espindola56f976f2013-04-18 18:08:55 +00002218 return "Mach-O 32-bit unknown";
2219 }
2220 }
2221
Rafael Espindola56f976f2013-04-18 18:08:55 +00002222 switch (CPUType) {
Charles Davis74ec8b02013-08-27 05:00:13 +00002223 case llvm::MachO::CPU_TYPE_X86_64:
Rafael Espindola56f976f2013-04-18 18:08:55 +00002224 return "Mach-O 64-bit x86-64";
Tim Northover00ed9962014-03-29 10:18:08 +00002225 case llvm::MachO::CPU_TYPE_ARM64:
2226 return "Mach-O arm64";
Charles Davis74ec8b02013-08-27 05:00:13 +00002227 case llvm::MachO::CPU_TYPE_POWERPC64:
Rafael Espindola56f976f2013-04-18 18:08:55 +00002228 return "Mach-O 64-bit ppc64";
2229 default:
2230 return "Mach-O 64-bit unknown";
2231 }
2232}
2233
Alexey Samsonove6388e62013-06-18 15:03:28 +00002234Triple::ArchType MachOObjectFile::getArch(uint32_t CPUType) {
2235 switch (CPUType) {
Charles Davis74ec8b02013-08-27 05:00:13 +00002236 case llvm::MachO::CPU_TYPE_I386:
Rafael Espindola56f976f2013-04-18 18:08:55 +00002237 return Triple::x86;
Charles Davis74ec8b02013-08-27 05:00:13 +00002238 case llvm::MachO::CPU_TYPE_X86_64:
Rafael Espindola56f976f2013-04-18 18:08:55 +00002239 return Triple::x86_64;
Charles Davis74ec8b02013-08-27 05:00:13 +00002240 case llvm::MachO::CPU_TYPE_ARM:
Rafael Espindola56f976f2013-04-18 18:08:55 +00002241 return Triple::arm;
Tim Northover00ed9962014-03-29 10:18:08 +00002242 case llvm::MachO::CPU_TYPE_ARM64:
Tim Northovere19bed72014-07-23 12:32:47 +00002243 return Triple::aarch64;
Charles Davis74ec8b02013-08-27 05:00:13 +00002244 case llvm::MachO::CPU_TYPE_POWERPC:
Rafael Espindola56f976f2013-04-18 18:08:55 +00002245 return Triple::ppc;
Charles Davis74ec8b02013-08-27 05:00:13 +00002246 case llvm::MachO::CPU_TYPE_POWERPC64:
Rafael Espindola56f976f2013-04-18 18:08:55 +00002247 return Triple::ppc64;
2248 default:
2249 return Triple::UnknownArch;
2250 }
2251}
2252
Tim Northover9e8eb412016-04-22 23:21:13 +00002253Triple MachOObjectFile::getArchTriple(uint32_t CPUType, uint32_t CPUSubType,
2254 const char **McpuDefault) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00002255 if (McpuDefault)
2256 *McpuDefault = nullptr;
2257
Kevin Enderby4c8dfe42014-06-30 18:45:23 +00002258 switch (CPUType) {
2259 case MachO::CPU_TYPE_I386:
2260 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2261 case MachO::CPU_SUBTYPE_I386_ALL:
2262 return Triple("i386-apple-darwin");
2263 default:
2264 return Triple();
2265 }
2266 case MachO::CPU_TYPE_X86_64:
2267 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2268 case MachO::CPU_SUBTYPE_X86_64_ALL:
2269 return Triple("x86_64-apple-darwin");
2270 case MachO::CPU_SUBTYPE_X86_64_H:
2271 return Triple("x86_64h-apple-darwin");
2272 default:
2273 return Triple();
2274 }
2275 case MachO::CPU_TYPE_ARM:
2276 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2277 case MachO::CPU_SUBTYPE_ARM_V4T:
2278 return Triple("armv4t-apple-darwin");
2279 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
2280 return Triple("armv5e-apple-darwin");
Kevin Enderbyae2a9a22014-08-07 21:30:25 +00002281 case MachO::CPU_SUBTYPE_ARM_XSCALE:
2282 return Triple("xscale-apple-darwin");
Kevin Enderby4c8dfe42014-06-30 18:45:23 +00002283 case MachO::CPU_SUBTYPE_ARM_V6:
2284 return Triple("armv6-apple-darwin");
2285 case MachO::CPU_SUBTYPE_ARM_V6M:
Kevin Enderbyec5ca032014-08-18 20:21:02 +00002286 if (McpuDefault)
2287 *McpuDefault = "cortex-m0";
Kevin Enderby4c8dfe42014-06-30 18:45:23 +00002288 return Triple("armv6m-apple-darwin");
Kevin Enderbyae2a9a22014-08-07 21:30:25 +00002289 case MachO::CPU_SUBTYPE_ARM_V7:
2290 return Triple("armv7-apple-darwin");
Kevin Enderby4c8dfe42014-06-30 18:45:23 +00002291 case MachO::CPU_SUBTYPE_ARM_V7EM:
Kevin Enderbyec5ca032014-08-18 20:21:02 +00002292 if (McpuDefault)
2293 *McpuDefault = "cortex-m4";
Tim Northover9e8eb412016-04-22 23:21:13 +00002294 return Triple("thumbv7em-apple-darwin");
Kevin Enderby4c8dfe42014-06-30 18:45:23 +00002295 case MachO::CPU_SUBTYPE_ARM_V7K:
2296 return Triple("armv7k-apple-darwin");
2297 case MachO::CPU_SUBTYPE_ARM_V7M:
Kevin Enderbyec5ca032014-08-18 20:21:02 +00002298 if (McpuDefault)
2299 *McpuDefault = "cortex-m3";
Tim Northover9e8eb412016-04-22 23:21:13 +00002300 return Triple("thumbv7m-apple-darwin");
Kevin Enderby4c8dfe42014-06-30 18:45:23 +00002301 case MachO::CPU_SUBTYPE_ARM_V7S:
2302 return Triple("armv7s-apple-darwin");
2303 default:
2304 return Triple();
2305 }
2306 case MachO::CPU_TYPE_ARM64:
2307 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2308 case MachO::CPU_SUBTYPE_ARM64_ALL:
2309 return Triple("arm64-apple-darwin");
2310 default:
2311 return Triple();
2312 }
2313 case MachO::CPU_TYPE_POWERPC:
2314 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2315 case MachO::CPU_SUBTYPE_POWERPC_ALL:
2316 return Triple("ppc-apple-darwin");
2317 default:
2318 return Triple();
2319 }
2320 case MachO::CPU_TYPE_POWERPC64:
Reid Kleckner4da3d572014-06-30 20:12:59 +00002321 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
Kevin Enderby4c8dfe42014-06-30 18:45:23 +00002322 case MachO::CPU_SUBTYPE_POWERPC_ALL:
2323 return Triple("ppc64-apple-darwin");
Kevin Enderby4c8dfe42014-06-30 18:45:23 +00002324 default:
2325 return Triple();
2326 }
2327 default:
2328 return Triple();
2329 }
2330}
2331
2332Triple MachOObjectFile::getHostArch() {
2333 return Triple(sys::getDefaultTargetTriple());
2334}
2335
Rafael Espindola72318b42014-08-08 16:30:17 +00002336bool MachOObjectFile::isValidArch(StringRef ArchFlag) {
2337 return StringSwitch<bool>(ArchFlag)
2338 .Case("i386", true)
2339 .Case("x86_64", true)
2340 .Case("x86_64h", true)
2341 .Case("armv4t", true)
2342 .Case("arm", true)
2343 .Case("armv5e", true)
2344 .Case("armv6", true)
2345 .Case("armv6m", true)
Frederic Riss40baa0a2015-06-16 17:37:03 +00002346 .Case("armv7", true)
Rafael Espindola72318b42014-08-08 16:30:17 +00002347 .Case("armv7em", true)
2348 .Case("armv7k", true)
2349 .Case("armv7m", true)
2350 .Case("armv7s", true)
2351 .Case("arm64", true)
2352 .Case("ppc", true)
2353 .Case("ppc64", true)
2354 .Default(false);
Kevin Enderby4c8dfe42014-06-30 18:45:23 +00002355}
2356
Alexey Samsonove6388e62013-06-18 15:03:28 +00002357unsigned MachOObjectFile::getArch() const {
2358 return getArch(getCPUType(this));
2359}
2360
Tim Northover9e8eb412016-04-22 23:21:13 +00002361Triple MachOObjectFile::getArchTriple(const char **McpuDefault) const {
2362 return getArchTriple(Header.cputype, Header.cpusubtype, McpuDefault);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00002363}
2364
Rui Ueyamabc654b12013-09-27 21:47:05 +00002365relocation_iterator MachOObjectFile::section_rel_begin(unsigned Index) const {
Rafael Espindola6e040c02013-04-26 20:07:33 +00002366 DataRefImpl DRI;
2367 DRI.d.a = Index;
Rui Ueyamabc654b12013-09-27 21:47:05 +00002368 return section_rel_begin(DRI);
Rafael Espindola6e040c02013-04-26 20:07:33 +00002369}
2370
Rui Ueyamabc654b12013-09-27 21:47:05 +00002371relocation_iterator MachOObjectFile::section_rel_end(unsigned Index) const {
Rafael Espindola6e040c02013-04-26 20:07:33 +00002372 DataRefImpl DRI;
2373 DRI.d.a = Index;
Rui Ueyamabc654b12013-09-27 21:47:05 +00002374 return section_rel_end(DRI);
Rafael Espindola6e040c02013-04-26 20:07:33 +00002375}
2376
Kevin Enderby273ae012013-06-06 17:20:50 +00002377dice_iterator MachOObjectFile::begin_dices() const {
2378 DataRefImpl DRI;
2379 if (!DataInCodeLoadCmd)
2380 return dice_iterator(DiceRef(DRI, this));
2381
Charles Davis8bdfafd2013-09-01 04:28:48 +00002382 MachO::linkedit_data_command DicLC = getDataInCodeLoadCommand();
2383 DRI.p = reinterpret_cast<uintptr_t>(getPtr(this, DicLC.dataoff));
Kevin Enderby273ae012013-06-06 17:20:50 +00002384 return dice_iterator(DiceRef(DRI, this));
2385}
2386
2387dice_iterator MachOObjectFile::end_dices() const {
2388 DataRefImpl DRI;
2389 if (!DataInCodeLoadCmd)
2390 return dice_iterator(DiceRef(DRI, this));
2391
Charles Davis8bdfafd2013-09-01 04:28:48 +00002392 MachO::linkedit_data_command DicLC = getDataInCodeLoadCommand();
2393 unsigned Offset = DicLC.dataoff + DicLC.datasize;
Kevin Enderby273ae012013-06-06 17:20:50 +00002394 DRI.p = reinterpret_cast<uintptr_t>(getPtr(this, Offset));
2395 return dice_iterator(DiceRef(DRI, this));
2396}
2397
NAKAMURA Takumi70ad98a2015-09-22 11:13:55 +00002398ExportEntry::ExportEntry(ArrayRef<uint8_t> T)
2399 : Trie(T), Malformed(false), Done(false) {}
Nick Kledzikd04bc352014-08-30 00:20:14 +00002400
2401void ExportEntry::moveToFirst() {
2402 pushNode(0);
2403 pushDownUntilBottom();
2404}
2405
2406void ExportEntry::moveToEnd() {
2407 Stack.clear();
2408 Done = true;
2409}
2410
2411bool ExportEntry::operator==(const ExportEntry &Other) const {
NAKAMURA Takumi84965032015-09-22 11:14:12 +00002412 // Common case, one at end, other iterating from begin.
Nick Kledzikd04bc352014-08-30 00:20:14 +00002413 if (Done || Other.Done)
2414 return (Done == Other.Done);
2415 // Not equal if different stack sizes.
2416 if (Stack.size() != Other.Stack.size())
2417 return false;
2418 // Not equal if different cumulative strings.
Yaron Keren075759a2015-03-30 15:42:36 +00002419 if (!CumulativeString.equals(Other.CumulativeString))
Nick Kledzikd04bc352014-08-30 00:20:14 +00002420 return false;
2421 // Equal if all nodes in both stacks match.
2422 for (unsigned i=0; i < Stack.size(); ++i) {
2423 if (Stack[i].Start != Other.Stack[i].Start)
2424 return false;
2425 }
NAKAMURA Takumi10c80e72015-09-22 11:19:03 +00002426 return true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00002427}
2428
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00002429uint64_t ExportEntry::readULEB128(const uint8_t *&Ptr) {
2430 unsigned Count;
2431 uint64_t Result = decodeULEB128(Ptr, &Count);
2432 Ptr += Count;
2433 if (Ptr > Trie.end()) {
2434 Ptr = Trie.end();
Nick Kledzikd04bc352014-08-30 00:20:14 +00002435 Malformed = true;
2436 }
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00002437 return Result;
Nick Kledzikd04bc352014-08-30 00:20:14 +00002438}
2439
2440StringRef ExportEntry::name() const {
Yaron Keren075759a2015-03-30 15:42:36 +00002441 return CumulativeString;
Nick Kledzikd04bc352014-08-30 00:20:14 +00002442}
2443
2444uint64_t ExportEntry::flags() const {
2445 return Stack.back().Flags;
2446}
2447
2448uint64_t ExportEntry::address() const {
2449 return Stack.back().Address;
2450}
2451
2452uint64_t ExportEntry::other() const {
2453 return Stack.back().Other;
2454}
2455
2456StringRef ExportEntry::otherName() const {
2457 const char* ImportName = Stack.back().ImportName;
2458 if (ImportName)
2459 return StringRef(ImportName);
2460 return StringRef();
2461}
2462
2463uint32_t ExportEntry::nodeOffset() const {
2464 return Stack.back().Start - Trie.begin();
2465}
2466
NAKAMURA Takumi70ad98a2015-09-22 11:13:55 +00002467ExportEntry::NodeState::NodeState(const uint8_t *Ptr)
2468 : Start(Ptr), Current(Ptr), Flags(0), Address(0), Other(0),
2469 ImportName(nullptr), ChildCount(0), NextChildIndex(0),
2470 ParentStringLength(0), IsExportNode(false) {}
Nick Kledzikd04bc352014-08-30 00:20:14 +00002471
2472void ExportEntry::pushNode(uint64_t offset) {
2473 const uint8_t *Ptr = Trie.begin() + offset;
2474 NodeState State(Ptr);
2475 uint64_t ExportInfoSize = readULEB128(State.Current);
2476 State.IsExportNode = (ExportInfoSize != 0);
2477 const uint8_t* Children = State.Current + ExportInfoSize;
2478 if (State.IsExportNode) {
2479 State.Flags = readULEB128(State.Current);
2480 if (State.Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT) {
2481 State.Address = 0;
2482 State.Other = readULEB128(State.Current); // dylib ordinal
2483 State.ImportName = reinterpret_cast<const char*>(State.Current);
2484 } else {
2485 State.Address = readULEB128(State.Current);
Nick Kledzik1b591bd2014-08-30 01:57:34 +00002486 if (State.Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER)
NAKAMURA Takumi10c80e72015-09-22 11:19:03 +00002487 State.Other = readULEB128(State.Current);
Nick Kledzikd04bc352014-08-30 00:20:14 +00002488 }
2489 }
2490 State.ChildCount = *Children;
2491 State.Current = Children + 1;
2492 State.NextChildIndex = 0;
2493 State.ParentStringLength = CumulativeString.size();
2494 Stack.push_back(State);
2495}
2496
2497void ExportEntry::pushDownUntilBottom() {
2498 while (Stack.back().NextChildIndex < Stack.back().ChildCount) {
2499 NodeState &Top = Stack.back();
2500 CumulativeString.resize(Top.ParentStringLength);
2501 for (;*Top.Current != 0; Top.Current++) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00002502 char C = *Top.Current;
2503 CumulativeString.push_back(C);
Nick Kledzikd04bc352014-08-30 00:20:14 +00002504 }
2505 Top.Current += 1;
2506 uint64_t childNodeIndex = readULEB128(Top.Current);
2507 Top.NextChildIndex += 1;
2508 pushNode(childNodeIndex);
2509 }
2510 if (!Stack.back().IsExportNode) {
2511 Malformed = true;
2512 moveToEnd();
2513 }
2514}
2515
2516// We have a trie data structure and need a way to walk it that is compatible
2517// with the C++ iterator model. The solution is a non-recursive depth first
2518// traversal where the iterator contains a stack of parent nodes along with a
2519// string that is the accumulation of all edge strings along the parent chain
2520// to this point.
2521//
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00002522// There is one "export" node for each exported symbol. But because some
Nick Kledzikd04bc352014-08-30 00:20:14 +00002523// symbols may be a prefix of another symbol (e.g. _dup and _dup2), an export
NAKAMURA Takumi84965032015-09-22 11:14:12 +00002524// node may have child nodes too.
Nick Kledzikd04bc352014-08-30 00:20:14 +00002525//
2526// The algorithm for moveNext() is to keep moving down the leftmost unvisited
2527// child until hitting a node with no children (which is an export node or
2528// else the trie is malformed). On the way down, each node is pushed on the
2529// stack ivar. If there is no more ways down, it pops up one and tries to go
2530// down a sibling path until a childless node is reached.
2531void ExportEntry::moveNext() {
2532 if (Stack.empty() || !Stack.back().IsExportNode) {
2533 Malformed = true;
2534 moveToEnd();
2535 return;
2536 }
2537
2538 Stack.pop_back();
2539 while (!Stack.empty()) {
2540 NodeState &Top = Stack.back();
2541 if (Top.NextChildIndex < Top.ChildCount) {
2542 pushDownUntilBottom();
2543 // Now at the next export node.
2544 return;
2545 } else {
2546 if (Top.IsExportNode) {
2547 // This node has no children but is itself an export node.
2548 CumulativeString.resize(Top.ParentStringLength);
2549 return;
2550 }
2551 Stack.pop_back();
2552 }
2553 }
2554 Done = true;
2555}
2556
NAKAMURA Takumi10c80e72015-09-22 11:19:03 +00002557iterator_range<export_iterator>
Nick Kledzikd04bc352014-08-30 00:20:14 +00002558MachOObjectFile::exports(ArrayRef<uint8_t> Trie) {
2559 ExportEntry Start(Trie);
Juergen Ributzka4d7f70d2014-12-19 02:31:01 +00002560 if (Trie.size() == 0)
2561 Start.moveToEnd();
2562 else
2563 Start.moveToFirst();
Nick Kledzikd04bc352014-08-30 00:20:14 +00002564
2565 ExportEntry Finish(Trie);
2566 Finish.moveToEnd();
2567
Craig Topper15576e12015-12-06 05:08:07 +00002568 return make_range(export_iterator(Start), export_iterator(Finish));
Nick Kledzikd04bc352014-08-30 00:20:14 +00002569}
2570
2571iterator_range<export_iterator> MachOObjectFile::exports() const {
2572 return exports(getDyldInfoExportsTrie());
2573}
2574
Nick Kledzikac431442014-09-12 21:34:15 +00002575MachORebaseEntry::MachORebaseEntry(ArrayRef<uint8_t> Bytes, bool is64Bit)
2576 : Opcodes(Bytes), Ptr(Bytes.begin()), SegmentOffset(0), SegmentIndex(0),
2577 RemainingLoopCount(0), AdvanceAmount(0), RebaseType(0),
2578 PointerSize(is64Bit ? 8 : 4), Malformed(false), Done(false) {}
2579
2580void MachORebaseEntry::moveToFirst() {
2581 Ptr = Opcodes.begin();
2582 moveNext();
2583}
2584
2585void MachORebaseEntry::moveToEnd() {
2586 Ptr = Opcodes.end();
2587 RemainingLoopCount = 0;
2588 Done = true;
2589}
2590
2591void MachORebaseEntry::moveNext() {
2592 // If in the middle of some loop, move to next rebasing in loop.
2593 SegmentOffset += AdvanceAmount;
2594 if (RemainingLoopCount) {
2595 --RemainingLoopCount;
2596 return;
2597 }
2598 if (Ptr == Opcodes.end()) {
2599 Done = true;
2600 return;
2601 }
2602 bool More = true;
2603 while (More && !Malformed) {
2604 // Parse next opcode and set up next loop.
2605 uint8_t Byte = *Ptr++;
2606 uint8_t ImmValue = Byte & MachO::REBASE_IMMEDIATE_MASK;
2607 uint8_t Opcode = Byte & MachO::REBASE_OPCODE_MASK;
2608 switch (Opcode) {
2609 case MachO::REBASE_OPCODE_DONE:
2610 More = false;
2611 Done = true;
2612 moveToEnd();
2613 DEBUG_WITH_TYPE("mach-o-rebase", llvm::dbgs() << "REBASE_OPCODE_DONE\n");
2614 break;
2615 case MachO::REBASE_OPCODE_SET_TYPE_IMM:
2616 RebaseType = ImmValue;
2617 DEBUG_WITH_TYPE(
2618 "mach-o-rebase",
2619 llvm::dbgs() << "REBASE_OPCODE_SET_TYPE_IMM: "
2620 << "RebaseType=" << (int) RebaseType << "\n");
2621 break;
2622 case MachO::REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:
2623 SegmentIndex = ImmValue;
2624 SegmentOffset = readULEB128();
2625 DEBUG_WITH_TYPE(
2626 "mach-o-rebase",
2627 llvm::dbgs() << "REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: "
2628 << "SegmentIndex=" << SegmentIndex << ", "
2629 << format("SegmentOffset=0x%06X", SegmentOffset)
2630 << "\n");
2631 break;
2632 case MachO::REBASE_OPCODE_ADD_ADDR_ULEB:
2633 SegmentOffset += readULEB128();
2634 DEBUG_WITH_TYPE("mach-o-rebase",
2635 llvm::dbgs() << "REBASE_OPCODE_ADD_ADDR_ULEB: "
2636 << format("SegmentOffset=0x%06X",
2637 SegmentOffset) << "\n");
2638 break;
2639 case MachO::REBASE_OPCODE_ADD_ADDR_IMM_SCALED:
2640 SegmentOffset += ImmValue * PointerSize;
2641 DEBUG_WITH_TYPE("mach-o-rebase",
2642 llvm::dbgs() << "REBASE_OPCODE_ADD_ADDR_IMM_SCALED: "
2643 << format("SegmentOffset=0x%06X",
2644 SegmentOffset) << "\n");
2645 break;
2646 case MachO::REBASE_OPCODE_DO_REBASE_IMM_TIMES:
2647 AdvanceAmount = PointerSize;
2648 RemainingLoopCount = ImmValue - 1;
2649 DEBUG_WITH_TYPE(
2650 "mach-o-rebase",
2651 llvm::dbgs() << "REBASE_OPCODE_DO_REBASE_IMM_TIMES: "
2652 << format("SegmentOffset=0x%06X", SegmentOffset)
2653 << ", AdvanceAmount=" << AdvanceAmount
2654 << ", RemainingLoopCount=" << RemainingLoopCount
2655 << "\n");
2656 return;
2657 case MachO::REBASE_OPCODE_DO_REBASE_ULEB_TIMES:
2658 AdvanceAmount = PointerSize;
2659 RemainingLoopCount = readULEB128() - 1;
2660 DEBUG_WITH_TYPE(
2661 "mach-o-rebase",
2662 llvm::dbgs() << "REBASE_OPCODE_DO_REBASE_ULEB_TIMES: "
2663 << format("SegmentOffset=0x%06X", SegmentOffset)
2664 << ", AdvanceAmount=" << AdvanceAmount
2665 << ", RemainingLoopCount=" << RemainingLoopCount
2666 << "\n");
2667 return;
2668 case MachO::REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB:
2669 AdvanceAmount = readULEB128() + PointerSize;
2670 RemainingLoopCount = 0;
2671 DEBUG_WITH_TYPE(
2672 "mach-o-rebase",
2673 llvm::dbgs() << "REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB: "
2674 << format("SegmentOffset=0x%06X", SegmentOffset)
2675 << ", AdvanceAmount=" << AdvanceAmount
2676 << ", RemainingLoopCount=" << RemainingLoopCount
2677 << "\n");
2678 return;
2679 case MachO::REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB:
2680 RemainingLoopCount = readULEB128() - 1;
2681 AdvanceAmount = readULEB128() + PointerSize;
2682 DEBUG_WITH_TYPE(
2683 "mach-o-rebase",
2684 llvm::dbgs() << "REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB: "
2685 << format("SegmentOffset=0x%06X", SegmentOffset)
2686 << ", AdvanceAmount=" << AdvanceAmount
2687 << ", RemainingLoopCount=" << RemainingLoopCount
2688 << "\n");
2689 return;
2690 default:
2691 Malformed = true;
2692 }
2693 }
2694}
2695
2696uint64_t MachORebaseEntry::readULEB128() {
2697 unsigned Count;
2698 uint64_t Result = decodeULEB128(Ptr, &Count);
2699 Ptr += Count;
2700 if (Ptr > Opcodes.end()) {
2701 Ptr = Opcodes.end();
2702 Malformed = true;
2703 }
2704 return Result;
2705}
2706
2707uint32_t MachORebaseEntry::segmentIndex() const { return SegmentIndex; }
2708
2709uint64_t MachORebaseEntry::segmentOffset() const { return SegmentOffset; }
2710
2711StringRef MachORebaseEntry::typeName() const {
2712 switch (RebaseType) {
2713 case MachO::REBASE_TYPE_POINTER:
2714 return "pointer";
2715 case MachO::REBASE_TYPE_TEXT_ABSOLUTE32:
2716 return "text abs32";
2717 case MachO::REBASE_TYPE_TEXT_PCREL32:
2718 return "text rel32";
2719 }
2720 return "unknown";
2721}
2722
2723bool MachORebaseEntry::operator==(const MachORebaseEntry &Other) const {
2724 assert(Opcodes == Other.Opcodes && "compare iterators of different files");
2725 return (Ptr == Other.Ptr) &&
2726 (RemainingLoopCount == Other.RemainingLoopCount) &&
2727 (Done == Other.Done);
2728}
2729
2730iterator_range<rebase_iterator>
2731MachOObjectFile::rebaseTable(ArrayRef<uint8_t> Opcodes, bool is64) {
2732 MachORebaseEntry Start(Opcodes, is64);
2733 Start.moveToFirst();
2734
2735 MachORebaseEntry Finish(Opcodes, is64);
2736 Finish.moveToEnd();
2737
Craig Topper15576e12015-12-06 05:08:07 +00002738 return make_range(rebase_iterator(Start), rebase_iterator(Finish));
Nick Kledzikac431442014-09-12 21:34:15 +00002739}
2740
2741iterator_range<rebase_iterator> MachOObjectFile::rebaseTable() const {
2742 return rebaseTable(getDyldInfoRebaseOpcodes(), is64Bit());
2743}
2744
NAKAMURA Takumi70ad98a2015-09-22 11:13:55 +00002745MachOBindEntry::MachOBindEntry(ArrayRef<uint8_t> Bytes, bool is64Bit, Kind BK)
Nick Kledzik56ebef42014-09-16 01:41:51 +00002746 : Opcodes(Bytes), Ptr(Bytes.begin()), SegmentOffset(0), SegmentIndex(0),
2747 Ordinal(0), Flags(0), Addend(0), RemainingLoopCount(0), AdvanceAmount(0),
2748 BindType(0), PointerSize(is64Bit ? 8 : 4),
2749 TableKind(BK), Malformed(false), Done(false) {}
2750
2751void MachOBindEntry::moveToFirst() {
2752 Ptr = Opcodes.begin();
2753 moveNext();
2754}
2755
2756void MachOBindEntry::moveToEnd() {
2757 Ptr = Opcodes.end();
2758 RemainingLoopCount = 0;
2759 Done = true;
2760}
2761
2762void MachOBindEntry::moveNext() {
2763 // If in the middle of some loop, move to next binding in loop.
2764 SegmentOffset += AdvanceAmount;
2765 if (RemainingLoopCount) {
2766 --RemainingLoopCount;
2767 return;
2768 }
2769 if (Ptr == Opcodes.end()) {
2770 Done = true;
2771 return;
2772 }
2773 bool More = true;
2774 while (More && !Malformed) {
2775 // Parse next opcode and set up next loop.
2776 uint8_t Byte = *Ptr++;
2777 uint8_t ImmValue = Byte & MachO::BIND_IMMEDIATE_MASK;
2778 uint8_t Opcode = Byte & MachO::BIND_OPCODE_MASK;
2779 int8_t SignExtended;
2780 const uint8_t *SymStart;
2781 switch (Opcode) {
2782 case MachO::BIND_OPCODE_DONE:
2783 if (TableKind == Kind::Lazy) {
2784 // Lazying bindings have a DONE opcode between entries. Need to ignore
2785 // it to advance to next entry. But need not if this is last entry.
2786 bool NotLastEntry = false;
2787 for (const uint8_t *P = Ptr; P < Opcodes.end(); ++P) {
2788 if (*P) {
2789 NotLastEntry = true;
2790 }
2791 }
2792 if (NotLastEntry)
2793 break;
2794 }
2795 More = false;
2796 Done = true;
2797 moveToEnd();
2798 DEBUG_WITH_TYPE("mach-o-bind", llvm::dbgs() << "BIND_OPCODE_DONE\n");
2799 break;
2800 case MachO::BIND_OPCODE_SET_DYLIB_ORDINAL_IMM:
2801 Ordinal = ImmValue;
2802 DEBUG_WITH_TYPE(
2803 "mach-o-bind",
2804 llvm::dbgs() << "BIND_OPCODE_SET_DYLIB_ORDINAL_IMM: "
2805 << "Ordinal=" << Ordinal << "\n");
2806 break;
2807 case MachO::BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB:
2808 Ordinal = readULEB128();
2809 DEBUG_WITH_TYPE(
2810 "mach-o-bind",
2811 llvm::dbgs() << "BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB: "
2812 << "Ordinal=" << Ordinal << "\n");
2813 break;
2814 case MachO::BIND_OPCODE_SET_DYLIB_SPECIAL_IMM:
2815 if (ImmValue) {
2816 SignExtended = MachO::BIND_OPCODE_MASK | ImmValue;
2817 Ordinal = SignExtended;
2818 } else
2819 Ordinal = 0;
2820 DEBUG_WITH_TYPE(
2821 "mach-o-bind",
2822 llvm::dbgs() << "BIND_OPCODE_SET_DYLIB_SPECIAL_IMM: "
2823 << "Ordinal=" << Ordinal << "\n");
2824 break;
2825 case MachO::BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM:
2826 Flags = ImmValue;
2827 SymStart = Ptr;
2828 while (*Ptr) {
2829 ++Ptr;
2830 }
Nick Kledzik56ebef42014-09-16 01:41:51 +00002831 SymbolName = StringRef(reinterpret_cast<const char*>(SymStart),
2832 Ptr-SymStart);
Nick Kledzika6375362014-09-17 01:51:43 +00002833 ++Ptr;
Nick Kledzik56ebef42014-09-16 01:41:51 +00002834 DEBUG_WITH_TYPE(
2835 "mach-o-bind",
2836 llvm::dbgs() << "BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM: "
2837 << "SymbolName=" << SymbolName << "\n");
2838 if (TableKind == Kind::Weak) {
2839 if (ImmValue & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION)
2840 return;
2841 }
2842 break;
2843 case MachO::BIND_OPCODE_SET_TYPE_IMM:
2844 BindType = ImmValue;
2845 DEBUG_WITH_TYPE(
2846 "mach-o-bind",
2847 llvm::dbgs() << "BIND_OPCODE_SET_TYPE_IMM: "
2848 << "BindType=" << (int)BindType << "\n");
2849 break;
2850 case MachO::BIND_OPCODE_SET_ADDEND_SLEB:
2851 Addend = readSLEB128();
2852 if (TableKind == Kind::Lazy)
2853 Malformed = true;
2854 DEBUG_WITH_TYPE(
2855 "mach-o-bind",
2856 llvm::dbgs() << "BIND_OPCODE_SET_ADDEND_SLEB: "
2857 << "Addend=" << Addend << "\n");
2858 break;
2859 case MachO::BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:
2860 SegmentIndex = ImmValue;
2861 SegmentOffset = readULEB128();
2862 DEBUG_WITH_TYPE(
2863 "mach-o-bind",
2864 llvm::dbgs() << "BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: "
2865 << "SegmentIndex=" << SegmentIndex << ", "
2866 << format("SegmentOffset=0x%06X", SegmentOffset)
2867 << "\n");
2868 break;
2869 case MachO::BIND_OPCODE_ADD_ADDR_ULEB:
2870 SegmentOffset += readULEB128();
2871 DEBUG_WITH_TYPE("mach-o-bind",
2872 llvm::dbgs() << "BIND_OPCODE_ADD_ADDR_ULEB: "
2873 << format("SegmentOffset=0x%06X",
2874 SegmentOffset) << "\n");
2875 break;
2876 case MachO::BIND_OPCODE_DO_BIND:
2877 AdvanceAmount = PointerSize;
2878 RemainingLoopCount = 0;
2879 DEBUG_WITH_TYPE("mach-o-bind",
2880 llvm::dbgs() << "BIND_OPCODE_DO_BIND: "
2881 << format("SegmentOffset=0x%06X",
2882 SegmentOffset) << "\n");
2883 return;
2884 case MachO::BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB:
Nick Kledzik3b2aa052014-10-18 01:21:02 +00002885 AdvanceAmount = readULEB128() + PointerSize;
Nick Kledzik56ebef42014-09-16 01:41:51 +00002886 RemainingLoopCount = 0;
2887 if (TableKind == Kind::Lazy)
2888 Malformed = true;
2889 DEBUG_WITH_TYPE(
2890 "mach-o-bind",
Nick Kledzik3b2aa052014-10-18 01:21:02 +00002891 llvm::dbgs() << "BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB: "
Nick Kledzik56ebef42014-09-16 01:41:51 +00002892 << format("SegmentOffset=0x%06X", SegmentOffset)
2893 << ", AdvanceAmount=" << AdvanceAmount
2894 << ", RemainingLoopCount=" << RemainingLoopCount
2895 << "\n");
2896 return;
2897 case MachO::BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED:
Nick Kledzik3b2aa052014-10-18 01:21:02 +00002898 AdvanceAmount = ImmValue * PointerSize + PointerSize;
Nick Kledzik56ebef42014-09-16 01:41:51 +00002899 RemainingLoopCount = 0;
2900 if (TableKind == Kind::Lazy)
2901 Malformed = true;
2902 DEBUG_WITH_TYPE("mach-o-bind",
2903 llvm::dbgs()
2904 << "BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED: "
2905 << format("SegmentOffset=0x%06X",
2906 SegmentOffset) << "\n");
2907 return;
2908 case MachO::BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB:
2909 RemainingLoopCount = readULEB128() - 1;
2910 AdvanceAmount = readULEB128() + PointerSize;
2911 if (TableKind == Kind::Lazy)
2912 Malformed = true;
2913 DEBUG_WITH_TYPE(
2914 "mach-o-bind",
2915 llvm::dbgs() << "BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB: "
2916 << format("SegmentOffset=0x%06X", SegmentOffset)
2917 << ", AdvanceAmount=" << AdvanceAmount
2918 << ", RemainingLoopCount=" << RemainingLoopCount
2919 << "\n");
2920 return;
2921 default:
2922 Malformed = true;
2923 }
2924 }
2925}
2926
2927uint64_t MachOBindEntry::readULEB128() {
2928 unsigned Count;
2929 uint64_t Result = decodeULEB128(Ptr, &Count);
2930 Ptr += Count;
2931 if (Ptr > Opcodes.end()) {
2932 Ptr = Opcodes.end();
2933 Malformed = true;
2934 }
2935 return Result;
2936}
2937
2938int64_t MachOBindEntry::readSLEB128() {
2939 unsigned Count;
2940 int64_t Result = decodeSLEB128(Ptr, &Count);
2941 Ptr += Count;
2942 if (Ptr > Opcodes.end()) {
2943 Ptr = Opcodes.end();
2944 Malformed = true;
2945 }
2946 return Result;
2947}
2948
Nick Kledzik56ebef42014-09-16 01:41:51 +00002949uint32_t MachOBindEntry::segmentIndex() const { return SegmentIndex; }
2950
2951uint64_t MachOBindEntry::segmentOffset() const { return SegmentOffset; }
2952
2953StringRef MachOBindEntry::typeName() const {
2954 switch (BindType) {
2955 case MachO::BIND_TYPE_POINTER:
2956 return "pointer";
2957 case MachO::BIND_TYPE_TEXT_ABSOLUTE32:
2958 return "text abs32";
2959 case MachO::BIND_TYPE_TEXT_PCREL32:
2960 return "text rel32";
2961 }
2962 return "unknown";
2963}
2964
2965StringRef MachOBindEntry::symbolName() const { return SymbolName; }
2966
2967int64_t MachOBindEntry::addend() const { return Addend; }
2968
2969uint32_t MachOBindEntry::flags() const { return Flags; }
2970
2971int MachOBindEntry::ordinal() const { return Ordinal; }
2972
2973bool MachOBindEntry::operator==(const MachOBindEntry &Other) const {
2974 assert(Opcodes == Other.Opcodes && "compare iterators of different files");
2975 return (Ptr == Other.Ptr) &&
2976 (RemainingLoopCount == Other.RemainingLoopCount) &&
2977 (Done == Other.Done);
2978}
2979
2980iterator_range<bind_iterator>
2981MachOObjectFile::bindTable(ArrayRef<uint8_t> Opcodes, bool is64,
2982 MachOBindEntry::Kind BKind) {
2983 MachOBindEntry Start(Opcodes, is64, BKind);
2984 Start.moveToFirst();
2985
2986 MachOBindEntry Finish(Opcodes, is64, BKind);
2987 Finish.moveToEnd();
2988
Craig Topper15576e12015-12-06 05:08:07 +00002989 return make_range(bind_iterator(Start), bind_iterator(Finish));
Nick Kledzik56ebef42014-09-16 01:41:51 +00002990}
2991
2992iterator_range<bind_iterator> MachOObjectFile::bindTable() const {
2993 return bindTable(getDyldInfoBindOpcodes(), is64Bit(),
2994 MachOBindEntry::Kind::Regular);
2995}
2996
2997iterator_range<bind_iterator> MachOObjectFile::lazyBindTable() const {
2998 return bindTable(getDyldInfoLazyBindOpcodes(), is64Bit(),
2999 MachOBindEntry::Kind::Lazy);
3000}
3001
3002iterator_range<bind_iterator> MachOObjectFile::weakBindTable() const {
3003 return bindTable(getDyldInfoWeakBindOpcodes(), is64Bit(),
3004 MachOBindEntry::Kind::Weak);
3005}
3006
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00003007MachOObjectFile::load_command_iterator
3008MachOObjectFile::begin_load_commands() const {
3009 return LoadCommands.begin();
3010}
3011
3012MachOObjectFile::load_command_iterator
3013MachOObjectFile::end_load_commands() const {
3014 return LoadCommands.end();
3015}
3016
3017iterator_range<MachOObjectFile::load_command_iterator>
3018MachOObjectFile::load_commands() const {
Craig Topper15576e12015-12-06 05:08:07 +00003019 return make_range(begin_load_commands(), end_load_commands());
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00003020}
3021
Rafael Espindola56f976f2013-04-18 18:08:55 +00003022StringRef
3023MachOObjectFile::getSectionFinalSegmentName(DataRefImpl Sec) const {
3024 ArrayRef<char> Raw = getSectionRawFinalSegmentName(Sec);
3025 return parseSegmentOrSectionName(Raw.data());
3026}
3027
3028ArrayRef<char>
3029MachOObjectFile::getSectionRawName(DataRefImpl Sec) const {
Rafael Espindola0d85d102015-05-22 14:59:27 +00003030 assert(Sec.d.a < Sections.size() && "Should have detected this earlier");
Charles Davis8bdfafd2013-09-01 04:28:48 +00003031 const section_base *Base =
3032 reinterpret_cast<const section_base *>(Sections[Sec.d.a]);
Craig Toppere1d12942014-08-27 05:25:25 +00003033 return makeArrayRef(Base->sectname);
Rafael Espindola56f976f2013-04-18 18:08:55 +00003034}
3035
3036ArrayRef<char>
3037MachOObjectFile::getSectionRawFinalSegmentName(DataRefImpl Sec) const {
Rafael Espindola0d85d102015-05-22 14:59:27 +00003038 assert(Sec.d.a < Sections.size() && "Should have detected this earlier");
Charles Davis8bdfafd2013-09-01 04:28:48 +00003039 const section_base *Base =
3040 reinterpret_cast<const section_base *>(Sections[Sec.d.a]);
Craig Toppere1d12942014-08-27 05:25:25 +00003041 return makeArrayRef(Base->segname);
Rafael Espindola56f976f2013-04-18 18:08:55 +00003042}
3043
3044bool
Charles Davis8bdfafd2013-09-01 04:28:48 +00003045MachOObjectFile::isRelocationScattered(const MachO::any_relocation_info &RE)
Rafael Espindola56f976f2013-04-18 18:08:55 +00003046 const {
Charles Davis8bdfafd2013-09-01 04:28:48 +00003047 if (getCPUType(this) == MachO::CPU_TYPE_X86_64)
Rafael Espindola56f976f2013-04-18 18:08:55 +00003048 return false;
Charles Davis8bdfafd2013-09-01 04:28:48 +00003049 return getPlainRelocationAddress(RE) & MachO::R_SCATTERED;
Rafael Espindola56f976f2013-04-18 18:08:55 +00003050}
3051
Eric Christopher1d62c252013-07-22 22:25:07 +00003052unsigned MachOObjectFile::getPlainRelocationSymbolNum(
Charles Davis8bdfafd2013-09-01 04:28:48 +00003053 const MachO::any_relocation_info &RE) const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00003054 if (isLittleEndian())
Charles Davis8bdfafd2013-09-01 04:28:48 +00003055 return RE.r_word1 & 0xffffff;
3056 return RE.r_word1 >> 8;
Rafael Espindola56f976f2013-04-18 18:08:55 +00003057}
3058
Eric Christopher1d62c252013-07-22 22:25:07 +00003059bool MachOObjectFile::getPlainRelocationExternal(
Charles Davis8bdfafd2013-09-01 04:28:48 +00003060 const MachO::any_relocation_info &RE) const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00003061 if (isLittleEndian())
Charles Davis8bdfafd2013-09-01 04:28:48 +00003062 return (RE.r_word1 >> 27) & 1;
3063 return (RE.r_word1 >> 4) & 1;
Rafael Espindola56f976f2013-04-18 18:08:55 +00003064}
3065
Eric Christopher1d62c252013-07-22 22:25:07 +00003066bool MachOObjectFile::getScatteredRelocationScattered(
Charles Davis8bdfafd2013-09-01 04:28:48 +00003067 const MachO::any_relocation_info &RE) const {
3068 return RE.r_word0 >> 31;
Rafael Espindola56f976f2013-04-18 18:08:55 +00003069}
3070
Eric Christopher1d62c252013-07-22 22:25:07 +00003071uint32_t MachOObjectFile::getScatteredRelocationValue(
Charles Davis8bdfafd2013-09-01 04:28:48 +00003072 const MachO::any_relocation_info &RE) const {
3073 return RE.r_word1;
Rafael Espindola56f976f2013-04-18 18:08:55 +00003074}
3075
Kevin Enderby9907d0a2014-11-04 00:43:16 +00003076uint32_t MachOObjectFile::getScatteredRelocationType(
3077 const MachO::any_relocation_info &RE) const {
3078 return (RE.r_word0 >> 24) & 0xf;
3079}
3080
Eric Christopher1d62c252013-07-22 22:25:07 +00003081unsigned MachOObjectFile::getAnyRelocationAddress(
Charles Davis8bdfafd2013-09-01 04:28:48 +00003082 const MachO::any_relocation_info &RE) const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00003083 if (isRelocationScattered(RE))
3084 return getScatteredRelocationAddress(RE);
3085 return getPlainRelocationAddress(RE);
3086}
3087
Charles Davis8bdfafd2013-09-01 04:28:48 +00003088unsigned MachOObjectFile::getAnyRelocationPCRel(
3089 const MachO::any_relocation_info &RE) const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00003090 if (isRelocationScattered(RE))
3091 return getScatteredRelocationPCRel(this, RE);
3092 return getPlainRelocationPCRel(this, RE);
3093}
3094
Eric Christopher1d62c252013-07-22 22:25:07 +00003095unsigned MachOObjectFile::getAnyRelocationLength(
Charles Davis8bdfafd2013-09-01 04:28:48 +00003096 const MachO::any_relocation_info &RE) const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00003097 if (isRelocationScattered(RE))
3098 return getScatteredRelocationLength(RE);
3099 return getPlainRelocationLength(this, RE);
3100}
3101
3102unsigned
Charles Davis8bdfafd2013-09-01 04:28:48 +00003103MachOObjectFile::getAnyRelocationType(
3104 const MachO::any_relocation_info &RE) const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00003105 if (isRelocationScattered(RE))
3106 return getScatteredRelocationType(RE);
3107 return getPlainRelocationType(this, RE);
3108}
3109
Rafael Espindola52501032013-04-30 15:40:54 +00003110SectionRef
Keno Fischerc780e8e2015-05-21 21:24:32 +00003111MachOObjectFile::getAnyRelocationSection(
Charles Davis8bdfafd2013-09-01 04:28:48 +00003112 const MachO::any_relocation_info &RE) const {
Rafael Espindola52501032013-04-30 15:40:54 +00003113 if (isRelocationScattered(RE) || getPlainRelocationExternal(RE))
Rafael Espindolab5155a52014-02-10 20:24:04 +00003114 return *section_end();
Rafael Espindola9ac06a02015-06-18 22:38:20 +00003115 unsigned SecNum = getPlainRelocationSymbolNum(RE);
3116 if (SecNum == MachO::R_ABS || SecNum > Sections.size())
3117 return *section_end();
Rafael Espindola52501032013-04-30 15:40:54 +00003118 DataRefImpl DRI;
Rafael Espindola9ac06a02015-06-18 22:38:20 +00003119 DRI.d.a = SecNum - 1;
Rafael Espindola52501032013-04-30 15:40:54 +00003120 return SectionRef(DRI, this);
3121}
3122
Charles Davis8bdfafd2013-09-01 04:28:48 +00003123MachO::section MachOObjectFile::getSection(DataRefImpl DRI) const {
Rafael Espindola62a07cb2015-05-22 15:43:00 +00003124 assert(DRI.d.a < Sections.size() && "Should have detected this earlier");
Charles Davis8bdfafd2013-09-01 04:28:48 +00003125 return getStruct<MachO::section>(this, Sections[DRI.d.a]);
Rafael Espindola56f976f2013-04-18 18:08:55 +00003126}
3127
Charles Davis8bdfafd2013-09-01 04:28:48 +00003128MachO::section_64 MachOObjectFile::getSection64(DataRefImpl DRI) const {
Rafael Espindola62a07cb2015-05-22 15:43:00 +00003129 assert(DRI.d.a < Sections.size() && "Should have detected this earlier");
Charles Davis8bdfafd2013-09-01 04:28:48 +00003130 return getStruct<MachO::section_64>(this, Sections[DRI.d.a]);
Rafael Espindola56f976f2013-04-18 18:08:55 +00003131}
3132
Charles Davis8bdfafd2013-09-01 04:28:48 +00003133MachO::section MachOObjectFile::getSection(const LoadCommandInfo &L,
Rafael Espindola6e040c02013-04-26 20:07:33 +00003134 unsigned Index) const {
3135 const char *Sec = getSectionPtr(this, L, Index);
Charles Davis8bdfafd2013-09-01 04:28:48 +00003136 return getStruct<MachO::section>(this, Sec);
Rafael Espindola6e040c02013-04-26 20:07:33 +00003137}
3138
Charles Davis8bdfafd2013-09-01 04:28:48 +00003139MachO::section_64 MachOObjectFile::getSection64(const LoadCommandInfo &L,
3140 unsigned Index) const {
Rafael Espindola6e040c02013-04-26 20:07:33 +00003141 const char *Sec = getSectionPtr(this, L, Index);
Charles Davis8bdfafd2013-09-01 04:28:48 +00003142 return getStruct<MachO::section_64>(this, Sec);
Rafael Espindola6e040c02013-04-26 20:07:33 +00003143}
3144
Charles Davis8bdfafd2013-09-01 04:28:48 +00003145MachO::nlist
Rafael Espindola56f976f2013-04-18 18:08:55 +00003146MachOObjectFile::getSymbolTableEntry(DataRefImpl DRI) const {
Rafael Espindola75c30362013-04-24 19:47:55 +00003147 const char *P = reinterpret_cast<const char *>(DRI.p);
Charles Davis8bdfafd2013-09-01 04:28:48 +00003148 return getStruct<MachO::nlist>(this, P);
Rafael Espindola56f976f2013-04-18 18:08:55 +00003149}
3150
Charles Davis8bdfafd2013-09-01 04:28:48 +00003151MachO::nlist_64
Rafael Espindola56f976f2013-04-18 18:08:55 +00003152MachOObjectFile::getSymbol64TableEntry(DataRefImpl DRI) const {
Rafael Espindola75c30362013-04-24 19:47:55 +00003153 const char *P = reinterpret_cast<const char *>(DRI.p);
Charles Davis8bdfafd2013-09-01 04:28:48 +00003154 return getStruct<MachO::nlist_64>(this, P);
Rafael Espindola56f976f2013-04-18 18:08:55 +00003155}
3156
Charles Davis8bdfafd2013-09-01 04:28:48 +00003157MachO::linkedit_data_command
3158MachOObjectFile::getLinkeditDataLoadCommand(const LoadCommandInfo &L) const {
3159 return getStruct<MachO::linkedit_data_command>(this, L.Ptr);
Rafael Espindola56f976f2013-04-18 18:08:55 +00003160}
3161
Charles Davis8bdfafd2013-09-01 04:28:48 +00003162MachO::segment_command
Rafael Espindola6e040c02013-04-26 20:07:33 +00003163MachOObjectFile::getSegmentLoadCommand(const LoadCommandInfo &L) const {
Charles Davis8bdfafd2013-09-01 04:28:48 +00003164 return getStruct<MachO::segment_command>(this, L.Ptr);
Rafael Espindola6e040c02013-04-26 20:07:33 +00003165}
3166
Charles Davis8bdfafd2013-09-01 04:28:48 +00003167MachO::segment_command_64
Rafael Espindola6e040c02013-04-26 20:07:33 +00003168MachOObjectFile::getSegment64LoadCommand(const LoadCommandInfo &L) const {
Charles Davis8bdfafd2013-09-01 04:28:48 +00003169 return getStruct<MachO::segment_command_64>(this, L.Ptr);
Rafael Espindola6e040c02013-04-26 20:07:33 +00003170}
3171
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00003172MachO::linker_option_command
3173MachOObjectFile::getLinkerOptionLoadCommand(const LoadCommandInfo &L) const {
3174 return getStruct<MachO::linker_option_command>(this, L.Ptr);
Rafael Espindola6e040c02013-04-26 20:07:33 +00003175}
3176
Jim Grosbach448334a2014-03-18 22:09:05 +00003177MachO::version_min_command
3178MachOObjectFile::getVersionMinLoadCommand(const LoadCommandInfo &L) const {
3179 return getStruct<MachO::version_min_command>(this, L.Ptr);
3180}
3181
Tim Northover8f9590b2014-06-30 14:40:57 +00003182MachO::dylib_command
3183MachOObjectFile::getDylibIDLoadCommand(const LoadCommandInfo &L) const {
3184 return getStruct<MachO::dylib_command>(this, L.Ptr);
3185}
3186
Kevin Enderby8ae63c12014-09-04 16:54:47 +00003187MachO::dyld_info_command
3188MachOObjectFile::getDyldInfoLoadCommand(const LoadCommandInfo &L) const {
3189 return getStruct<MachO::dyld_info_command>(this, L.Ptr);
3190}
3191
3192MachO::dylinker_command
3193MachOObjectFile::getDylinkerCommand(const LoadCommandInfo &L) const {
3194 return getStruct<MachO::dylinker_command>(this, L.Ptr);
3195}
3196
3197MachO::uuid_command
3198MachOObjectFile::getUuidCommand(const LoadCommandInfo &L) const {
3199 return getStruct<MachO::uuid_command>(this, L.Ptr);
3200}
3201
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00003202MachO::rpath_command
3203MachOObjectFile::getRpathCommand(const LoadCommandInfo &L) const {
3204 return getStruct<MachO::rpath_command>(this, L.Ptr);
3205}
3206
Kevin Enderby8ae63c12014-09-04 16:54:47 +00003207MachO::source_version_command
3208MachOObjectFile::getSourceVersionCommand(const LoadCommandInfo &L) const {
3209 return getStruct<MachO::source_version_command>(this, L.Ptr);
3210}
3211
3212MachO::entry_point_command
3213MachOObjectFile::getEntryPointCommand(const LoadCommandInfo &L) const {
3214 return getStruct<MachO::entry_point_command>(this, L.Ptr);
3215}
3216
Kevin Enderby0804f4672014-12-16 23:25:52 +00003217MachO::encryption_info_command
3218MachOObjectFile::getEncryptionInfoCommand(const LoadCommandInfo &L) const {
3219 return getStruct<MachO::encryption_info_command>(this, L.Ptr);
3220}
3221
Kevin Enderby57538292014-12-17 01:01:30 +00003222MachO::encryption_info_command_64
3223MachOObjectFile::getEncryptionInfoCommand64(const LoadCommandInfo &L) const {
3224 return getStruct<MachO::encryption_info_command_64>(this, L.Ptr);
3225}
3226
Kevin Enderbyb4b79312014-12-18 19:24:35 +00003227MachO::sub_framework_command
3228MachOObjectFile::getSubFrameworkCommand(const LoadCommandInfo &L) const {
3229 return getStruct<MachO::sub_framework_command>(this, L.Ptr);
3230}
Tim Northover8f9590b2014-06-30 14:40:57 +00003231
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00003232MachO::sub_umbrella_command
3233MachOObjectFile::getSubUmbrellaCommand(const LoadCommandInfo &L) const {
3234 return getStruct<MachO::sub_umbrella_command>(this, L.Ptr);
3235}
3236
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00003237MachO::sub_library_command
3238MachOObjectFile::getSubLibraryCommand(const LoadCommandInfo &L) const {
3239 return getStruct<MachO::sub_library_command>(this, L.Ptr);
3240}
3241
Kevin Enderby186eac32014-12-19 21:06:24 +00003242MachO::sub_client_command
3243MachOObjectFile::getSubClientCommand(const LoadCommandInfo &L) const {
3244 return getStruct<MachO::sub_client_command>(this, L.Ptr);
3245}
3246
Kevin Enderby52e4ce42014-12-19 22:25:22 +00003247MachO::routines_command
3248MachOObjectFile::getRoutinesCommand(const LoadCommandInfo &L) const {
3249 return getStruct<MachO::routines_command>(this, L.Ptr);
3250}
3251
3252MachO::routines_command_64
3253MachOObjectFile::getRoutinesCommand64(const LoadCommandInfo &L) const {
3254 return getStruct<MachO::routines_command_64>(this, L.Ptr);
3255}
3256
Kevin Enderby48ef5342014-12-23 22:56:39 +00003257MachO::thread_command
3258MachOObjectFile::getThreadCommand(const LoadCommandInfo &L) const {
3259 return getStruct<MachO::thread_command>(this, L.Ptr);
3260}
3261
Charles Davis8bdfafd2013-09-01 04:28:48 +00003262MachO::any_relocation_info
Rafael Espindola56f976f2013-04-18 18:08:55 +00003263MachOObjectFile::getRelocation(DataRefImpl Rel) const {
Rafael Espindola128b8112014-04-03 23:51:28 +00003264 DataRefImpl Sec;
3265 Sec.d.a = Rel.d.a;
3266 uint32_t Offset;
3267 if (is64Bit()) {
3268 MachO::section_64 Sect = getSection64(Sec);
3269 Offset = Sect.reloff;
3270 } else {
3271 MachO::section Sect = getSection(Sec);
3272 Offset = Sect.reloff;
3273 }
3274
3275 auto P = reinterpret_cast<const MachO::any_relocation_info *>(
3276 getPtr(this, Offset)) + Rel.d.b;
3277 return getStruct<MachO::any_relocation_info>(
3278 this, reinterpret_cast<const char *>(P));
Rafael Espindola56f976f2013-04-18 18:08:55 +00003279}
3280
Charles Davis8bdfafd2013-09-01 04:28:48 +00003281MachO::data_in_code_entry
Kevin Enderby273ae012013-06-06 17:20:50 +00003282MachOObjectFile::getDice(DataRefImpl Rel) const {
3283 const char *P = reinterpret_cast<const char *>(Rel.p);
Charles Davis8bdfafd2013-09-01 04:28:48 +00003284 return getStruct<MachO::data_in_code_entry>(this, P);
Kevin Enderby273ae012013-06-06 17:20:50 +00003285}
3286
Alexey Samsonov13415ed2015-06-04 19:22:03 +00003287const MachO::mach_header &MachOObjectFile::getHeader() const {
Alexey Samsonovfa5edc52015-06-04 22:49:55 +00003288 return Header;
Rafael Espindola56f976f2013-04-18 18:08:55 +00003289}
3290
Alexey Samsonov13415ed2015-06-04 19:22:03 +00003291const MachO::mach_header_64 &MachOObjectFile::getHeader64() const {
3292 assert(is64Bit());
3293 return Header64;
Rafael Espindola6e040c02013-04-26 20:07:33 +00003294}
3295
Charles Davis8bdfafd2013-09-01 04:28:48 +00003296uint32_t MachOObjectFile::getIndirectSymbolTableEntry(
3297 const MachO::dysymtab_command &DLC,
3298 unsigned Index) const {
3299 uint64_t Offset = DLC.indirectsymoff + Index * sizeof(uint32_t);
3300 return getStruct<uint32_t>(this, getPtr(this, Offset));
Rafael Espindola6e040c02013-04-26 20:07:33 +00003301}
3302
Charles Davis8bdfafd2013-09-01 04:28:48 +00003303MachO::data_in_code_entry
Rafael Espindola6e040c02013-04-26 20:07:33 +00003304MachOObjectFile::getDataInCodeTableEntry(uint32_t DataOffset,
3305 unsigned Index) const {
Charles Davis8bdfafd2013-09-01 04:28:48 +00003306 uint64_t Offset = DataOffset + Index * sizeof(MachO::data_in_code_entry);
3307 return getStruct<MachO::data_in_code_entry>(this, getPtr(this, Offset));
Rafael Espindola6e040c02013-04-26 20:07:33 +00003308}
3309
Charles Davis8bdfafd2013-09-01 04:28:48 +00003310MachO::symtab_command MachOObjectFile::getSymtabLoadCommand() const {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003311 if (SymtabLoadCmd)
3312 return getStruct<MachO::symtab_command>(this, SymtabLoadCmd);
3313
3314 // If there is no SymtabLoadCmd return a load command with zero'ed fields.
3315 MachO::symtab_command Cmd;
3316 Cmd.cmd = MachO::LC_SYMTAB;
3317 Cmd.cmdsize = sizeof(MachO::symtab_command);
3318 Cmd.symoff = 0;
3319 Cmd.nsyms = 0;
3320 Cmd.stroff = 0;
3321 Cmd.strsize = 0;
3322 return Cmd;
Rafael Espindola56f976f2013-04-18 18:08:55 +00003323}
3324
Charles Davis8bdfafd2013-09-01 04:28:48 +00003325MachO::dysymtab_command MachOObjectFile::getDysymtabLoadCommand() const {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003326 if (DysymtabLoadCmd)
3327 return getStruct<MachO::dysymtab_command>(this, DysymtabLoadCmd);
3328
3329 // If there is no DysymtabLoadCmd return a load command with zero'ed fields.
3330 MachO::dysymtab_command Cmd;
3331 Cmd.cmd = MachO::LC_DYSYMTAB;
3332 Cmd.cmdsize = sizeof(MachO::dysymtab_command);
3333 Cmd.ilocalsym = 0;
3334 Cmd.nlocalsym = 0;
3335 Cmd.iextdefsym = 0;
3336 Cmd.nextdefsym = 0;
3337 Cmd.iundefsym = 0;
3338 Cmd.nundefsym = 0;
3339 Cmd.tocoff = 0;
3340 Cmd.ntoc = 0;
3341 Cmd.modtaboff = 0;
3342 Cmd.nmodtab = 0;
3343 Cmd.extrefsymoff = 0;
3344 Cmd.nextrefsyms = 0;
3345 Cmd.indirectsymoff = 0;
3346 Cmd.nindirectsyms = 0;
3347 Cmd.extreloff = 0;
3348 Cmd.nextrel = 0;
3349 Cmd.locreloff = 0;
3350 Cmd.nlocrel = 0;
3351 return Cmd;
Rafael Espindola6e040c02013-04-26 20:07:33 +00003352}
3353
Charles Davis8bdfafd2013-09-01 04:28:48 +00003354MachO::linkedit_data_command
Kevin Enderby273ae012013-06-06 17:20:50 +00003355MachOObjectFile::getDataInCodeLoadCommand() const {
3356 if (DataInCodeLoadCmd)
Charles Davis8bdfafd2013-09-01 04:28:48 +00003357 return getStruct<MachO::linkedit_data_command>(this, DataInCodeLoadCmd);
Kevin Enderby273ae012013-06-06 17:20:50 +00003358
3359 // If there is no DataInCodeLoadCmd return a load command with zero'ed fields.
Charles Davis8bdfafd2013-09-01 04:28:48 +00003360 MachO::linkedit_data_command Cmd;
3361 Cmd.cmd = MachO::LC_DATA_IN_CODE;
3362 Cmd.cmdsize = sizeof(MachO::linkedit_data_command);
3363 Cmd.dataoff = 0;
3364 Cmd.datasize = 0;
Kevin Enderby273ae012013-06-06 17:20:50 +00003365 return Cmd;
3366}
3367
Kevin Enderby9a509442015-01-27 21:28:24 +00003368MachO::linkedit_data_command
3369MachOObjectFile::getLinkOptHintsLoadCommand() const {
3370 if (LinkOptHintsLoadCmd)
3371 return getStruct<MachO::linkedit_data_command>(this, LinkOptHintsLoadCmd);
3372
3373 // If there is no LinkOptHintsLoadCmd return a load command with zero'ed
3374 // fields.
3375 MachO::linkedit_data_command Cmd;
3376 Cmd.cmd = MachO::LC_LINKER_OPTIMIZATION_HINT;
3377 Cmd.cmdsize = sizeof(MachO::linkedit_data_command);
3378 Cmd.dataoff = 0;
3379 Cmd.datasize = 0;
3380 return Cmd;
3381}
3382
Nick Kledzikd04bc352014-08-30 00:20:14 +00003383ArrayRef<uint8_t> MachOObjectFile::getDyldInfoRebaseOpcodes() const {
NAKAMURA Takumi10c80e72015-09-22 11:19:03 +00003384 if (!DyldInfoLoadCmd)
Craig Topper0013be12015-09-21 05:32:41 +00003385 return None;
Nick Kledzikd04bc352014-08-30 00:20:14 +00003386
NAKAMURA Takumi70ad98a2015-09-22 11:13:55 +00003387 MachO::dyld_info_command DyldInfo =
3388 getStruct<MachO::dyld_info_command>(this, DyldInfoLoadCmd);
3389 const uint8_t *Ptr =
3390 reinterpret_cast<const uint8_t *>(getPtr(this, DyldInfo.rebase_off));
Craig Topper0013be12015-09-21 05:32:41 +00003391 return makeArrayRef(Ptr, DyldInfo.rebase_size);
Nick Kledzikd04bc352014-08-30 00:20:14 +00003392}
3393
3394ArrayRef<uint8_t> MachOObjectFile::getDyldInfoBindOpcodes() const {
NAKAMURA Takumi10c80e72015-09-22 11:19:03 +00003395 if (!DyldInfoLoadCmd)
Craig Topper0013be12015-09-21 05:32:41 +00003396 return None;
Nick Kledzikd04bc352014-08-30 00:20:14 +00003397
NAKAMURA Takumi70ad98a2015-09-22 11:13:55 +00003398 MachO::dyld_info_command DyldInfo =
3399 getStruct<MachO::dyld_info_command>(this, DyldInfoLoadCmd);
3400 const uint8_t *Ptr =
3401 reinterpret_cast<const uint8_t *>(getPtr(this, DyldInfo.bind_off));
Craig Topper0013be12015-09-21 05:32:41 +00003402 return makeArrayRef(Ptr, DyldInfo.bind_size);
Nick Kledzikd04bc352014-08-30 00:20:14 +00003403}
3404
3405ArrayRef<uint8_t> MachOObjectFile::getDyldInfoWeakBindOpcodes() const {
NAKAMURA Takumi10c80e72015-09-22 11:19:03 +00003406 if (!DyldInfoLoadCmd)
Craig Topper0013be12015-09-21 05:32:41 +00003407 return None;
Nick Kledzikd04bc352014-08-30 00:20:14 +00003408
NAKAMURA Takumi70ad98a2015-09-22 11:13:55 +00003409 MachO::dyld_info_command DyldInfo =
3410 getStruct<MachO::dyld_info_command>(this, DyldInfoLoadCmd);
3411 const uint8_t *Ptr =
3412 reinterpret_cast<const uint8_t *>(getPtr(this, DyldInfo.weak_bind_off));
Craig Topper0013be12015-09-21 05:32:41 +00003413 return makeArrayRef(Ptr, DyldInfo.weak_bind_size);
Nick Kledzikd04bc352014-08-30 00:20:14 +00003414}
3415
3416ArrayRef<uint8_t> MachOObjectFile::getDyldInfoLazyBindOpcodes() const {
NAKAMURA Takumi10c80e72015-09-22 11:19:03 +00003417 if (!DyldInfoLoadCmd)
Craig Topper0013be12015-09-21 05:32:41 +00003418 return None;
Nick Kledzikd04bc352014-08-30 00:20:14 +00003419
NAKAMURA Takumi70ad98a2015-09-22 11:13:55 +00003420 MachO::dyld_info_command DyldInfo =
3421 getStruct<MachO::dyld_info_command>(this, DyldInfoLoadCmd);
3422 const uint8_t *Ptr =
3423 reinterpret_cast<const uint8_t *>(getPtr(this, DyldInfo.lazy_bind_off));
Craig Topper0013be12015-09-21 05:32:41 +00003424 return makeArrayRef(Ptr, DyldInfo.lazy_bind_size);
Nick Kledzikd04bc352014-08-30 00:20:14 +00003425}
3426
3427ArrayRef<uint8_t> MachOObjectFile::getDyldInfoExportsTrie() const {
NAKAMURA Takumi10c80e72015-09-22 11:19:03 +00003428 if (!DyldInfoLoadCmd)
Craig Topper0013be12015-09-21 05:32:41 +00003429 return None;
Nick Kledzikd04bc352014-08-30 00:20:14 +00003430
NAKAMURA Takumi70ad98a2015-09-22 11:13:55 +00003431 MachO::dyld_info_command DyldInfo =
3432 getStruct<MachO::dyld_info_command>(this, DyldInfoLoadCmd);
3433 const uint8_t *Ptr =
3434 reinterpret_cast<const uint8_t *>(getPtr(this, DyldInfo.export_off));
Craig Topper0013be12015-09-21 05:32:41 +00003435 return makeArrayRef(Ptr, DyldInfo.export_size);
Nick Kledzikd04bc352014-08-30 00:20:14 +00003436}
3437
Alexander Potapenko6909b5b2014-10-15 23:35:45 +00003438ArrayRef<uint8_t> MachOObjectFile::getUuid() const {
3439 if (!UuidLoadCmd)
Craig Topper0013be12015-09-21 05:32:41 +00003440 return None;
Benjamin Kramer014601d2014-10-24 15:52:05 +00003441 // Returning a pointer is fine as uuid doesn't need endian swapping.
3442 const char *Ptr = UuidLoadCmd + offsetof(MachO::uuid_command, uuid);
Craig Topper0013be12015-09-21 05:32:41 +00003443 return makeArrayRef(reinterpret_cast<const uint8_t *>(Ptr), 16);
Alexander Potapenko6909b5b2014-10-15 23:35:45 +00003444}
Nick Kledzikd04bc352014-08-30 00:20:14 +00003445
Rafael Espindola6e040c02013-04-26 20:07:33 +00003446StringRef MachOObjectFile::getStringTableData() const {
Charles Davis8bdfafd2013-09-01 04:28:48 +00003447 MachO::symtab_command S = getSymtabLoadCommand();
3448 return getData().substr(S.stroff, S.strsize);
Rafael Espindola6e040c02013-04-26 20:07:33 +00003449}
3450
Rafael Espindola56f976f2013-04-18 18:08:55 +00003451bool MachOObjectFile::is64Bit() const {
3452 return getType() == getMachOType(false, true) ||
Lang Hames84bc8182014-07-15 19:35:22 +00003453 getType() == getMachOType(true, true);
Rafael Espindola56f976f2013-04-18 18:08:55 +00003454}
3455
3456void MachOObjectFile::ReadULEB128s(uint64_t Index,
3457 SmallVectorImpl<uint64_t> &Out) const {
3458 DataExtractor extractor(ObjectFile::getData(), true, 0);
3459
3460 uint32_t offset = Index;
3461 uint64_t data = 0;
3462 while (uint64_t delta = extractor.getULEB128(&offset)) {
3463 data += delta;
3464 Out.push_back(data);
3465 }
3466}
3467
Rafael Espindolac66d7612014-08-17 19:09:37 +00003468bool MachOObjectFile::isRelocatableObject() const {
3469 return getHeader().filetype == MachO::MH_OBJECT;
3470}
3471
Lang Hamesff044b12016-03-25 23:11:52 +00003472Expected<std::unique_ptr<MachOObjectFile>>
Kevin Enderby79d6c632016-10-24 21:15:11 +00003473ObjectFile::createMachOObjectFile(MemoryBufferRef Buffer,
3474 uint32_t UniversalCputype,
3475 uint32_t UniversalIndex) {
Rafael Espindola48af1c22014-08-19 18:44:46 +00003476 StringRef Magic = Buffer.getBuffer().slice(0, 4);
Lang Hames82627642016-03-25 21:59:14 +00003477 if (Magic == "\xFE\xED\xFA\xCE")
Kevin Enderby79d6c632016-10-24 21:15:11 +00003478 return MachOObjectFile::create(Buffer, false, false,
3479 UniversalCputype, UniversalIndex);
David Blaikieb805f732016-03-28 17:45:48 +00003480 if (Magic == "\xCE\xFA\xED\xFE")
Kevin Enderby79d6c632016-10-24 21:15:11 +00003481 return MachOObjectFile::create(Buffer, true, false,
3482 UniversalCputype, UniversalIndex);
David Blaikieb805f732016-03-28 17:45:48 +00003483 if (Magic == "\xFE\xED\xFA\xCF")
Kevin Enderby79d6c632016-10-24 21:15:11 +00003484 return MachOObjectFile::create(Buffer, false, true,
3485 UniversalCputype, UniversalIndex);
David Blaikieb805f732016-03-28 17:45:48 +00003486 if (Magic == "\xCF\xFA\xED\xFE")
Kevin Enderby79d6c632016-10-24 21:15:11 +00003487 return MachOObjectFile::create(Buffer, true, true,
3488 UniversalCputype, UniversalIndex);
Kevin Enderbyd4e075b2016-05-06 20:16:28 +00003489 return make_error<GenericBinaryError>("Unrecognized MachO magic number",
Justin Bogner2a42da92016-05-05 23:59:57 +00003490 object_error::invalid_file_type);
Rafael Espindola56f976f2013-04-18 18:08:55 +00003491}