blob: 847e61fff1ea4ddb055814343295d8b391bc4fa8 [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>
30
31using namespace llvm;
32using namespace object;
33
Artyom Skrobov7d602f72014-07-20 12:08:28 +000034namespace {
35 struct section_base {
36 char sectname[16];
37 char segname[16];
38 };
39}
Rafael Espindola56f976f2013-04-18 18:08:55 +000040
Lang Hames9e964f32016-03-25 17:25:34 +000041static Error
Kevin Enderbyd4e075b2016-05-06 20:16:28 +000042malformedError(Twine Msg) {
Kevin Enderby89134962016-05-05 23:41:05 +000043 std::string StringMsg = "truncated or malformed object (" + Msg.str() + ")";
Kevin Enderbyd4e075b2016-05-06 20:16:28 +000044 return make_error<GenericBinaryError>(std::move(StringMsg),
Kevin Enderby89134962016-05-05 23:41:05 +000045 object_error::parse_failed);
Lang Hames9e964f32016-03-25 17:25:34 +000046}
47
Alexey Samsonov9f336632015-06-04 19:45:22 +000048// FIXME: Replace all uses of this function with getStructOrErr.
Filipe Cabecinhas40139502015-01-15 22:52:38 +000049template <typename T>
Artyom Skrobov7d602f72014-07-20 12:08:28 +000050static T getStruct(const MachOObjectFile *O, const char *P) {
Filipe Cabecinhas40139502015-01-15 22:52:38 +000051 // Don't read before the beginning or past the end of the file
52 if (P < O->getData().begin() || P + sizeof(T) > O->getData().end())
53 report_fatal_error("Malformed MachO file.");
54
Rafael Espindola3cdeb172013-04-19 13:45:05 +000055 T Cmd;
56 memcpy(&Cmd, P, sizeof(T));
57 if (O->isLittleEndian() != sys::IsLittleEndianHost)
Artyom Skrobov78d5daf2014-07-18 09:26:16 +000058 MachO::swapStruct(Cmd);
Rafael Espindola3cdeb172013-04-19 13:45:05 +000059 return Cmd;
Rafael Espindola56f976f2013-04-18 18:08:55 +000060}
61
Alexey Samsonov9f336632015-06-04 19:45:22 +000062template <typename T>
Lang Hames9e964f32016-03-25 17:25:34 +000063static Expected<T> getStructOrErr(const MachOObjectFile *O, const char *P) {
Alexey Samsonov9f336632015-06-04 19:45:22 +000064 // Don't read before the beginning or past the end of the file
65 if (P < O->getData().begin() || P + sizeof(T) > O->getData().end())
Kevin Enderbyd4e075b2016-05-06 20:16:28 +000066 return malformedError("Structure read out-of-range");
Alexey Samsonov9f336632015-06-04 19:45:22 +000067
68 T Cmd;
69 memcpy(&Cmd, P, sizeof(T));
70 if (O->isLittleEndian() != sys::IsLittleEndianHost)
71 MachO::swapStruct(Cmd);
72 return Cmd;
73}
74
Rafael Espindola6e040c02013-04-26 20:07:33 +000075static const char *
76getSectionPtr(const MachOObjectFile *O, MachOObjectFile::LoadCommandInfo L,
77 unsigned Sec) {
Rafael Espindola56f976f2013-04-18 18:08:55 +000078 uintptr_t CommandAddr = reinterpret_cast<uintptr_t>(L.Ptr);
79
80 bool Is64 = O->is64Bit();
Charles Davis8bdfafd2013-09-01 04:28:48 +000081 unsigned SegmentLoadSize = Is64 ? sizeof(MachO::segment_command_64) :
82 sizeof(MachO::segment_command);
83 unsigned SectionSize = Is64 ? sizeof(MachO::section_64) :
84 sizeof(MachO::section);
Rafael Espindola56f976f2013-04-18 18:08:55 +000085
86 uintptr_t SectionAddr = CommandAddr + SegmentLoadSize + Sec * SectionSize;
Charles Davis1827bd82013-08-27 05:38:30 +000087 return reinterpret_cast<const char*>(SectionAddr);
Rafael Espindola60689982013-04-07 19:05:30 +000088}
89
Rafael Espindola56f976f2013-04-18 18:08:55 +000090static const char *getPtr(const MachOObjectFile *O, size_t Offset) {
91 return O->getData().substr(Offset, 1).data();
Rafael Espindola60689982013-04-07 19:05:30 +000092}
93
Artyom Skrobov78d5daf2014-07-18 09:26:16 +000094static MachO::nlist_base
Rafael Espindola56f976f2013-04-18 18:08:55 +000095getSymbolTableEntryBase(const MachOObjectFile *O, DataRefImpl DRI) {
Rafael Espindola75c30362013-04-24 19:47:55 +000096 const char *P = reinterpret_cast<const char *>(DRI.p);
Artyom Skrobov78d5daf2014-07-18 09:26:16 +000097 return getStruct<MachO::nlist_base>(O, P);
Eric Christopher7b015c72011-04-22 03:19:48 +000098}
99
Rafael Espindola56f976f2013-04-18 18:08:55 +0000100static StringRef parseSegmentOrSectionName(const char *P) {
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000101 if (P[15] == 0)
102 // Null terminated.
103 return P;
104 // Not null terminated, so this is a 16 char string.
105 return StringRef(P, 16);
106}
107
Rafael Espindola56f976f2013-04-18 18:08:55 +0000108// Helper to advance a section or symbol iterator multiple increments at a time.
109template<class T>
Rafael Espindola5e812af2014-01-30 02:49:50 +0000110static void advance(T &it, size_t Val) {
111 while (Val--)
112 ++it;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000113}
114
115static unsigned getCPUType(const MachOObjectFile *O) {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000116 return O->getHeader().cputype;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000117}
118
Charles Davis8bdfafd2013-09-01 04:28:48 +0000119static uint32_t
120getPlainRelocationAddress(const MachO::any_relocation_info &RE) {
121 return RE.r_word0;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000122}
123
124static unsigned
Charles Davis8bdfafd2013-09-01 04:28:48 +0000125getScatteredRelocationAddress(const MachO::any_relocation_info &RE) {
126 return RE.r_word0 & 0xffffff;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000127}
128
129static bool getPlainRelocationPCRel(const MachOObjectFile *O,
Charles Davis8bdfafd2013-09-01 04:28:48 +0000130 const MachO::any_relocation_info &RE) {
Rafael Espindola56f976f2013-04-18 18:08:55 +0000131 if (O->isLittleEndian())
Charles Davis8bdfafd2013-09-01 04:28:48 +0000132 return (RE.r_word1 >> 24) & 1;
133 return (RE.r_word1 >> 7) & 1;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000134}
135
136static bool
137getScatteredRelocationPCRel(const MachOObjectFile *O,
Charles Davis8bdfafd2013-09-01 04:28:48 +0000138 const MachO::any_relocation_info &RE) {
139 return (RE.r_word0 >> 30) & 1;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000140}
141
142static unsigned getPlainRelocationLength(const MachOObjectFile *O,
Charles Davis8bdfafd2013-09-01 04:28:48 +0000143 const MachO::any_relocation_info &RE) {
Rafael Espindola56f976f2013-04-18 18:08:55 +0000144 if (O->isLittleEndian())
Charles Davis8bdfafd2013-09-01 04:28:48 +0000145 return (RE.r_word1 >> 25) & 3;
146 return (RE.r_word1 >> 5) & 3;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000147}
148
149static unsigned
Charles Davis8bdfafd2013-09-01 04:28:48 +0000150getScatteredRelocationLength(const MachO::any_relocation_info &RE) {
151 return (RE.r_word0 >> 28) & 3;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000152}
153
154static unsigned getPlainRelocationType(const MachOObjectFile *O,
Charles Davis8bdfafd2013-09-01 04:28:48 +0000155 const MachO::any_relocation_info &RE) {
Rafael Espindola56f976f2013-04-18 18:08:55 +0000156 if (O->isLittleEndian())
Charles Davis8bdfafd2013-09-01 04:28:48 +0000157 return RE.r_word1 >> 28;
158 return RE.r_word1 & 0xf;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000159}
160
Rafael Espindola56f976f2013-04-18 18:08:55 +0000161static uint32_t getSectionFlags(const MachOObjectFile *O,
162 DataRefImpl Sec) {
163 if (O->is64Bit()) {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000164 MachO::section_64 Sect = O->getSection64(Sec);
165 return Sect.flags;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000166 }
Charles Davis8bdfafd2013-09-01 04:28:48 +0000167 MachO::section Sect = O->getSection(Sec);
168 return Sect.flags;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000169}
170
Lang Hames9e964f32016-03-25 17:25:34 +0000171static Expected<MachOObjectFile::LoadCommandInfo>
Kevin Enderbya8e3ab02016-05-03 23:13:50 +0000172getLoadCommandInfo(const MachOObjectFile *Obj, const char *Ptr,
173 uint32_t LoadCommandIndex) {
Lang Hames9e964f32016-03-25 17:25:34 +0000174 if (auto CmdOrErr = getStructOrErr<MachO::load_command>(Obj, Ptr)) {
175 if (CmdOrErr->cmdsize < 8)
Kevin Enderbyd4e075b2016-05-06 20:16:28 +0000176 return malformedError("load command " + Twine(LoadCommandIndex) +
Kevin Enderby89134962016-05-05 23:41:05 +0000177 " with size less than 8 bytes");
Lang Hames9e964f32016-03-25 17:25:34 +0000178 return MachOObjectFile::LoadCommandInfo({Ptr, *CmdOrErr});
179 } else
180 return CmdOrErr.takeError();
Alexey Samsonov4fdbed32015-06-04 19:34:14 +0000181}
182
Lang Hames9e964f32016-03-25 17:25:34 +0000183static Expected<MachOObjectFile::LoadCommandInfo>
Alexey Samsonov4fdbed32015-06-04 19:34:14 +0000184getFirstLoadCommandInfo(const MachOObjectFile *Obj) {
185 unsigned HeaderSize = Obj->is64Bit() ? sizeof(MachO::mach_header_64)
186 : sizeof(MachO::mach_header);
Kevin Enderby9d0c9452016-08-31 17:57:46 +0000187 if (sizeof(MachO::load_command) > Obj->getHeader().sizeofcmds)
Kevin Enderbyd4e075b2016-05-06 20:16:28 +0000188 return malformedError("load command 0 extends past the end all load "
Kevin Enderby89134962016-05-05 23:41:05 +0000189 "commands in the file");
Kevin Enderbya8e3ab02016-05-03 23:13:50 +0000190 return getLoadCommandInfo(Obj, getPtr(Obj, HeaderSize), 0);
Alexey Samsonov4fdbed32015-06-04 19:34:14 +0000191}
192
Lang Hames9e964f32016-03-25 17:25:34 +0000193static Expected<MachOObjectFile::LoadCommandInfo>
Kevin Enderby368e7142016-05-03 17:16:08 +0000194getNextLoadCommandInfo(const MachOObjectFile *Obj, uint32_t LoadCommandIndex,
Alexey Samsonov4fdbed32015-06-04 19:34:14 +0000195 const MachOObjectFile::LoadCommandInfo &L) {
Kevin Enderby368e7142016-05-03 17:16:08 +0000196 unsigned HeaderSize = Obj->is64Bit() ? sizeof(MachO::mach_header_64)
197 : sizeof(MachO::mach_header);
Kevin Enderby9d0c9452016-08-31 17:57:46 +0000198 if (L.Ptr + L.C.cmdsize + sizeof(MachO::load_command) >
Kevin Enderby368e7142016-05-03 17:16:08 +0000199 Obj->getData().data() + HeaderSize + Obj->getHeader().sizeofcmds)
Kevin Enderbyd4e075b2016-05-06 20:16:28 +0000200 return malformedError("load command " + Twine(LoadCommandIndex + 1) +
Kevin Enderby89134962016-05-05 23:41:05 +0000201 " extends past the end all load commands in the file");
Kevin Enderbya8e3ab02016-05-03 23:13:50 +0000202 return getLoadCommandInfo(Obj, L.Ptr + L.C.cmdsize, LoadCommandIndex + 1);
Alexey Samsonov4fdbed32015-06-04 19:34:14 +0000203}
204
Alexey Samsonov9f336632015-06-04 19:45:22 +0000205template <typename T>
206static void parseHeader(const MachOObjectFile *Obj, T &Header,
Lang Hames9e964f32016-03-25 17:25:34 +0000207 Error &Err) {
Kevin Enderby87025742016-04-13 21:17:58 +0000208 if (sizeof(T) > Obj->getData().size()) {
Kevin Enderbyd4e075b2016-05-06 20:16:28 +0000209 Err = malformedError("the mach header extends past the end of the "
Kevin Enderby89134962016-05-05 23:41:05 +0000210 "file");
Kevin Enderby87025742016-04-13 21:17:58 +0000211 return;
212 }
Lang Hames9e964f32016-03-25 17:25:34 +0000213 if (auto HeaderOrErr = getStructOrErr<T>(Obj, getPtr(Obj, 0)))
214 Header = *HeaderOrErr;
Alexey Samsonov9f336632015-06-04 19:45:22 +0000215 else
Lang Hames9e964f32016-03-25 17:25:34 +0000216 Err = HeaderOrErr.takeError();
Alexey Samsonov9f336632015-06-04 19:45:22 +0000217}
218
Alexey Samsonove1a76ab2015-06-04 22:08:37 +0000219// Parses LC_SEGMENT or LC_SEGMENT_64 load command, adds addresses of all
220// sections to \param Sections, and optionally sets
221// \param IsPageZeroSegment to true.
Kevin Enderbyc614d282016-08-12 20:10:25 +0000222template <typename Segment, typename Section>
Lang Hames9e964f32016-03-25 17:25:34 +0000223static Error parseSegmentLoadCommand(
Alexey Samsonove1a76ab2015-06-04 22:08:37 +0000224 const MachOObjectFile *Obj, const MachOObjectFile::LoadCommandInfo &Load,
Kevin Enderbyb34e3a12016-05-05 17:43:35 +0000225 SmallVectorImpl<const char *> &Sections, bool &IsPageZeroSegment,
Kevin Enderbyc614d282016-08-12 20:10:25 +0000226 uint32_t LoadCommandIndex, const char *CmdName, uint64_t SizeOfHeaders) {
227 const unsigned SegmentLoadSize = sizeof(Segment);
Alexey Samsonove1a76ab2015-06-04 22:08:37 +0000228 if (Load.C.cmdsize < SegmentLoadSize)
Kevin Enderbyd4e075b2016-05-06 20:16:28 +0000229 return malformedError("load command " + Twine(LoadCommandIndex) +
Kevin Enderby89134962016-05-05 23:41:05 +0000230 " " + CmdName + " cmdsize too small");
Kevin Enderbyc614d282016-08-12 20:10:25 +0000231 if (auto SegOrErr = getStructOrErr<Segment>(Obj, Load.Ptr)) {
232 Segment S = SegOrErr.get();
233 const unsigned SectionSize = sizeof(Section);
234 uint64_t FileSize = Obj->getData().size();
Lang Hames9e964f32016-03-25 17:25:34 +0000235 if (S.nsects > std::numeric_limits<uint32_t>::max() / SectionSize ||
236 S.nsects * SectionSize > Load.C.cmdsize - SegmentLoadSize)
Kevin Enderbyd4e075b2016-05-06 20:16:28 +0000237 return malformedError("load command " + Twine(LoadCommandIndex) +
NAKAMURA Takumi9d0b5312016-08-22 00:58:47 +0000238 " inconsistent cmdsize in " + CmdName +
Kevin Enderby89134962016-05-05 23:41:05 +0000239 " for the number of sections");
Lang Hames9e964f32016-03-25 17:25:34 +0000240 for (unsigned J = 0; J < S.nsects; ++J) {
241 const char *Sec = getSectionPtr(Obj, Load, J);
242 Sections.push_back(Sec);
Kevin Enderbyc614d282016-08-12 20:10:25 +0000243 Section s = getStruct<Section>(Obj, Sec);
244 if (Obj->getHeader().filetype != MachO::MH_DYLIB_STUB &&
245 Obj->getHeader().filetype != MachO::MH_DSYM &&
246 s.flags != MachO::S_ZEROFILL &&
247 s.flags != MachO::S_THREAD_LOCAL_ZEROFILL &&
248 s.offset > FileSize)
249 return malformedError("offset field of section " + Twine(J) + " in " +
250 CmdName + " command " + Twine(LoadCommandIndex) +
251 " extends past the end of the file");
252 if (Obj->getHeader().filetype != MachO::MH_DYLIB_STUB &&
253 Obj->getHeader().filetype != MachO::MH_DSYM &&
254 s.flags != MachO::S_ZEROFILL &&
NAKAMURA Takumi59a20642016-08-22 00:58:04 +0000255 s.flags != MachO::S_THREAD_LOCAL_ZEROFILL && S.fileoff == 0 &&
256 s.offset < SizeOfHeaders && s.size != 0)
Kevin Enderbyc614d282016-08-12 20:10:25 +0000257 return malformedError("offset field of section " + Twine(J) + " in " +
258 CmdName + " command " + Twine(LoadCommandIndex) +
259 " not past the headers of the file");
260 uint64_t BigSize = s.offset;
261 BigSize += s.size;
262 if (Obj->getHeader().filetype != MachO::MH_DYLIB_STUB &&
263 Obj->getHeader().filetype != MachO::MH_DSYM &&
264 s.flags != MachO::S_ZEROFILL &&
265 s.flags != MachO::S_THREAD_LOCAL_ZEROFILL &&
266 BigSize > FileSize)
267 return malformedError("offset field plus size field of section " +
268 Twine(J) + " in " + CmdName + " command " +
269 Twine(LoadCommandIndex) +
270 " extends past the end of the file");
271 if (Obj->getHeader().filetype != MachO::MH_DYLIB_STUB &&
272 Obj->getHeader().filetype != MachO::MH_DSYM &&
273 s.flags != MachO::S_ZEROFILL &&
274 s.flags != MachO::S_THREAD_LOCAL_ZEROFILL &&
275 s.size > S.filesize)
276 return malformedError("size field of section " +
277 Twine(J) + " in " + CmdName + " command " +
278 Twine(LoadCommandIndex) +
279 " greater than the segment");
280 if (Obj->getHeader().filetype != MachO::MH_DYLIB_STUB &&
NAKAMURA Takumi59a20642016-08-22 00:58:04 +0000281 Obj->getHeader().filetype != MachO::MH_DSYM && s.size != 0 &&
282 s.addr < S.vmaddr)
283 return malformedError("addr field of section " + Twine(J) + " in " +
284 CmdName + " command " + Twine(LoadCommandIndex) +
285 " less than the segment's vmaddr");
Kevin Enderbyc614d282016-08-12 20:10:25 +0000286 BigSize = s.addr;
287 BigSize += s.size;
288 uint64_t BigEnd = S.vmaddr;
289 BigEnd += S.vmsize;
290 if (S.vmsize != 0 && s.size != 0 && BigSize > BigEnd)
NAKAMURA Takumi59a20642016-08-22 00:58:04 +0000291 return malformedError("addr field plus size of section " + Twine(J) +
292 " in " + CmdName + " command " +
293 Twine(LoadCommandIndex) +
294 " greater than than "
Kevin Enderbyc614d282016-08-12 20:10:25 +0000295 "the segment's vmaddr plus vmsize");
296 if (s.reloff > FileSize)
NAKAMURA Takumi59a20642016-08-22 00:58:04 +0000297 return malformedError("reloff field of section " + Twine(J) + " in " +
298 CmdName + " command " + Twine(LoadCommandIndex) +
Kevin Enderbyc614d282016-08-12 20:10:25 +0000299 " extends past the end of the file");
300 BigSize = s.nreloc;
301 BigSize *= sizeof(struct MachO::relocation_info);
302 BigSize += s.reloff;
303 if (BigSize > FileSize)
304 return malformedError("reloff field plus nreloc field times sizeof("
305 "struct relocation_info) of section " +
306 Twine(J) + " in " + CmdName + " command " +
NAKAMURA Takumi59a20642016-08-22 00:58:04 +0000307 Twine(LoadCommandIndex) +
Kevin Enderbyc614d282016-08-12 20:10:25 +0000308 " extends past the end of the file");
Lang Hames9e964f32016-03-25 17:25:34 +0000309 }
Kevin Enderby600fb3f2016-08-05 18:19:40 +0000310 if (S.fileoff > FileSize)
311 return malformedError("load command " + Twine(LoadCommandIndex) +
NAKAMURA Takumi9d0b5312016-08-22 00:58:47 +0000312 " fileoff field in " + CmdName +
Kevin Enderby600fb3f2016-08-05 18:19:40 +0000313 " extends past the end of the file");
Kevin Enderbyc614d282016-08-12 20:10:25 +0000314 uint64_t BigSize = S.fileoff;
315 BigSize += S.filesize;
316 if (BigSize > FileSize)
317 return malformedError("load command " + Twine(LoadCommandIndex) +
318 " fileoff field plus filesize field in " +
319 CmdName + " extends past the end of the file");
320 if (S.vmsize != 0 && S.filesize > S.vmsize)
321 return malformedError("load command " + Twine(LoadCommandIndex) +
322 " fileoff field in " + CmdName +
323 " greater than vmsize field");
Lang Hames9e964f32016-03-25 17:25:34 +0000324 IsPageZeroSegment |= StringRef("__PAGEZERO").equals(S.segname);
325 } else
326 return SegOrErr.takeError();
327
328 return Error::success();
Alexey Samsonove1a76ab2015-06-04 22:08:37 +0000329}
330
Kevin Enderby0e52c922016-08-26 19:34:07 +0000331static Error checkSymtabCommand(const MachOObjectFile *Obj,
332 const MachOObjectFile::LoadCommandInfo &Load,
333 uint32_t LoadCommandIndex,
334 const char **SymtabLoadCmd) {
335 if (Load.C.cmdsize < sizeof(MachO::symtab_command))
336 return malformedError("load command " + Twine(LoadCommandIndex) +
337 " LC_SYMTAB cmdsize too small");
338 if (*SymtabLoadCmd != nullptr)
339 return malformedError("more than one LC_SYMTAB command");
340 MachO::symtab_command Symtab =
341 getStruct<MachO::symtab_command>(Obj, Load.Ptr);
342 if (Symtab.cmdsize != sizeof(MachO::symtab_command))
343 return malformedError("LC_SYMTAB command " + Twine(LoadCommandIndex) +
344 " has incorrect cmdsize");
345 uint64_t FileSize = Obj->getData().size();
346 if (Symtab.symoff > FileSize)
347 return malformedError("symoff field of LC_SYMTAB command " +
348 Twine(LoadCommandIndex) + " extends past the end "
349 "of the file");
350 uint64_t BigSize = Symtab.nsyms;
351 const char *struct_nlist_name;
352 if (Obj->is64Bit()) {
353 BigSize *= sizeof(MachO::nlist_64);
354 struct_nlist_name = "struct nlist_64";
355 } else {
356 BigSize *= sizeof(MachO::nlist);
357 struct_nlist_name = "struct nlist";
358 }
359 BigSize += Symtab.symoff;
360 if (BigSize > FileSize)
361 return malformedError("symoff field plus nsyms field times sizeof(" +
362 Twine(struct_nlist_name) + ") of LC_SYMTAB command " +
363 Twine(LoadCommandIndex) + " extends past the end "
364 "of the file");
365 if (Symtab.stroff > FileSize)
366 return malformedError("stroff field of LC_SYMTAB command " +
367 Twine(LoadCommandIndex) + " extends past the end "
368 "of the file");
369 BigSize = Symtab.stroff;
370 BigSize += Symtab.strsize;
371 if (BigSize > FileSize)
372 return malformedError("stroff field plus strsize field of LC_SYMTAB "
373 "command " + Twine(LoadCommandIndex) + " extends "
374 "past the end of the file");
Kevin Enderby0e52c922016-08-26 19:34:07 +0000375 *SymtabLoadCmd = Load.Ptr;
376 return Error::success();
377}
378
Kevin Enderbydcbc5042016-08-30 21:28:30 +0000379static Error checkDysymtabCommand(const MachOObjectFile *Obj,
380 const MachOObjectFile::LoadCommandInfo &Load,
381 uint32_t LoadCommandIndex,
382 const char **DysymtabLoadCmd) {
383 if (Load.C.cmdsize < sizeof(MachO::dysymtab_command))
384 return malformedError("load command " + Twine(LoadCommandIndex) +
385 " LC_DYSYMTAB cmdsize too small");
386 if (*DysymtabLoadCmd != nullptr)
387 return malformedError("more than one LC_DYSYMTAB command");
388 MachO::dysymtab_command Dysymtab =
389 getStruct<MachO::dysymtab_command>(Obj, Load.Ptr);
390 if (Dysymtab.cmdsize != sizeof(MachO::dysymtab_command))
391 return malformedError("LC_DYSYMTAB command " + Twine(LoadCommandIndex) +
392 " has incorrect cmdsize");
393 uint64_t FileSize = Obj->getData().size();
394 if (Dysymtab.tocoff > FileSize)
395 return malformedError("tocoff field of LC_DYSYMTAB command " +
396 Twine(LoadCommandIndex) + " extends past the end of "
397 "the file");
398 uint64_t BigSize = Dysymtab.ntoc;
399 BigSize *= sizeof(MachO::dylib_table_of_contents);
400 BigSize += Dysymtab.tocoff;
401 if (BigSize > FileSize)
402 return malformedError("tocoff field plus ntoc field times sizeof(struct "
403 "dylib_table_of_contents) of LC_DYSYMTAB command " +
404 Twine(LoadCommandIndex) + " extends past the end of "
405 "the file");
406 if (Dysymtab.modtaboff > FileSize)
407 return malformedError("modtaboff field of LC_DYSYMTAB command " +
408 Twine(LoadCommandIndex) + " extends past the end of "
409 "the file");
410 BigSize = Dysymtab.nmodtab;
411 const char *struct_dylib_module_name;
412 if (Obj->is64Bit()) {
413 BigSize *= sizeof(MachO::dylib_module_64);
414 struct_dylib_module_name = "struct dylib_module_64";
415 } else {
416 BigSize *= sizeof(MachO::dylib_module);
417 struct_dylib_module_name = "struct dylib_module";
418 }
419 BigSize += Dysymtab.modtaboff;
420 if (BigSize > FileSize)
421 return malformedError("modtaboff field plus nmodtab field times sizeof(" +
422 Twine(struct_dylib_module_name) + ") of LC_DYSYMTAB "
423 "command " + Twine(LoadCommandIndex) + " extends "
424 "past the end of the file");
425 if (Dysymtab.extrefsymoff > FileSize)
426 return malformedError("extrefsymoff field of LC_DYSYMTAB command " +
427 Twine(LoadCommandIndex) + " extends past the end of "
428 "the file");
429 BigSize = Dysymtab.nextrefsyms;
430 BigSize *= sizeof(MachO::dylib_reference);
431 BigSize += Dysymtab.extrefsymoff;
432 if (BigSize > FileSize)
433 return malformedError("extrefsymoff field plus nextrefsyms field times "
434 "sizeof(struct dylib_reference) of LC_DYSYMTAB "
435 "command " + Twine(LoadCommandIndex) + " extends "
436 "past the end of the file");
437 if (Dysymtab.indirectsymoff > FileSize)
438 return malformedError("indirectsymoff field of LC_DYSYMTAB command " +
439 Twine(LoadCommandIndex) + " extends past the end of "
440 "the file");
441 BigSize = Dysymtab.nindirectsyms;
442 BigSize *= sizeof(uint32_t);
443 BigSize += Dysymtab.indirectsymoff;
444 if (BigSize > FileSize)
445 return malformedError("indirectsymoff field plus nindirectsyms field times "
446 "sizeof(uint32_t) of LC_DYSYMTAB command " +
447 Twine(LoadCommandIndex) + " extends past the end of "
448 "the file");
449 if (Dysymtab.extreloff > FileSize)
450 return malformedError("extreloff field of LC_DYSYMTAB command " +
451 Twine(LoadCommandIndex) + " extends past the end of "
452 "the file");
453 BigSize = Dysymtab.nextrel;
454 BigSize *= sizeof(MachO::relocation_info);
455 BigSize += Dysymtab.extreloff;
456 if (BigSize > FileSize)
457 return malformedError("extreloff field plus nextrel field times sizeof"
458 "(struct relocation_info) of LC_DYSYMTAB command " +
459 Twine(LoadCommandIndex) + " extends past the end of "
460 "the file");
461 if (Dysymtab.locreloff > FileSize)
462 return malformedError("locreloff field of LC_DYSYMTAB command " +
463 Twine(LoadCommandIndex) + " extends past the end of "
464 "the file");
465 BigSize = Dysymtab.nlocrel;
466 BigSize *= sizeof(MachO::relocation_info);
467 BigSize += Dysymtab.locreloff;
468 if (BigSize > FileSize)
469 return malformedError("locreloff field plus nlocrel field times sizeof"
470 "(struct relocation_info) of LC_DYSYMTAB command " +
471 Twine(LoadCommandIndex) + " extends past the end of "
472 "the file");
473 *DysymtabLoadCmd = Load.Ptr;
474 return Error::success();
475}
476
Kevin Enderby9d0c9452016-08-31 17:57:46 +0000477static Error checkLinkeditDataCommand(const MachOObjectFile *Obj,
478 const MachOObjectFile::LoadCommandInfo &Load,
479 uint32_t LoadCommandIndex,
480 const char **LoadCmd, const char *CmdName) {
481 if (Load.C.cmdsize < sizeof(MachO::linkedit_data_command))
482 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
483 CmdName + " cmdsize too small");
484 if (*LoadCmd != nullptr)
485 return malformedError("more than one " + Twine(CmdName) + " command");
486 MachO::linkedit_data_command LinkData =
487 getStruct<MachO::linkedit_data_command>(Obj, Load.Ptr);
488 if (LinkData.cmdsize != sizeof(MachO::linkedit_data_command))
489 return malformedError(Twine(CmdName) + " command " +
490 Twine(LoadCommandIndex) + " has incorrect cmdsize");
491 uint64_t FileSize = Obj->getData().size();
492 if (LinkData.dataoff > FileSize)
493 return malformedError("dataoff field of " + Twine(CmdName) + " command " +
494 Twine(LoadCommandIndex) + " extends past the end of "
495 "the file");
496 uint64_t BigSize = LinkData.dataoff;
497 BigSize += LinkData.datasize;
498 if (BigSize > FileSize)
499 return malformedError("dataoff field plus datasize field of " +
500 Twine(CmdName) + " command " +
501 Twine(LoadCommandIndex) + " extends past the end of "
502 "the file");
503 *LoadCmd = Load.Ptr;
504 return Error::success();
505}
506
Kevin Enderbyf76b56c2016-09-13 21:42:28 +0000507static Error checkDyldInfoCommand(const MachOObjectFile *Obj,
508 const MachOObjectFile::LoadCommandInfo &Load,
509 uint32_t LoadCommandIndex,
510 const char **LoadCmd, const char *CmdName) {
511 if (Load.C.cmdsize < sizeof(MachO::dyld_info_command))
512 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
513 CmdName + " cmdsize too small");
514 if (*LoadCmd != nullptr)
515 return malformedError("more than one LC_DYLD_INFO and or LC_DYLD_INFO_ONLY "
516 "command");
517 MachO::dyld_info_command DyldInfo =
518 getStruct<MachO::dyld_info_command>(Obj, Load.Ptr);
519 if (DyldInfo.cmdsize != sizeof(MachO::dyld_info_command))
520 return malformedError(Twine(CmdName) + " command " +
521 Twine(LoadCommandIndex) + " has incorrect cmdsize");
522 uint64_t FileSize = Obj->getData().size();
523 if (DyldInfo.rebase_off > FileSize)
524 return malformedError("rebase_off field of " + Twine(CmdName) +
525 " command " + Twine(LoadCommandIndex) + " extends "
526 "past the end of the file");
527 uint64_t BigSize = DyldInfo.rebase_off;
528 BigSize += DyldInfo.rebase_size;
529 if (BigSize > FileSize)
530 return malformedError("rebase_off field plus rebase_size field of " +
531 Twine(CmdName) + " command " +
532 Twine(LoadCommandIndex) + " extends past the end of "
533 "the file");
534 if (DyldInfo.bind_off > FileSize)
535 return malformedError("bind_off field of " + Twine(CmdName) +
536 " command " + Twine(LoadCommandIndex) + " extends "
537 "past the end of the file");
538 BigSize = DyldInfo.bind_off;
539 BigSize += DyldInfo.bind_size;
540 if (BigSize > FileSize)
541 return malformedError("bind_off field plus bind_size field of " +
542 Twine(CmdName) + " command " +
543 Twine(LoadCommandIndex) + " extends past the end of "
544 "the file");
545 if (DyldInfo.weak_bind_off > FileSize)
546 return malformedError("weak_bind_off field of " + Twine(CmdName) +
547 " command " + Twine(LoadCommandIndex) + " extends "
548 "past the end of the file");
549 BigSize = DyldInfo.weak_bind_off;
550 BigSize += DyldInfo.weak_bind_size;
551 if (BigSize > FileSize)
552 return malformedError("weak_bind_off field plus weak_bind_size field of " +
553 Twine(CmdName) + " command " +
554 Twine(LoadCommandIndex) + " extends past the end of "
555 "the file");
556 if (DyldInfo.lazy_bind_off > FileSize)
557 return malformedError("lazy_bind_off field of " + Twine(CmdName) +
558 " command " + Twine(LoadCommandIndex) + " extends "
559 "past the end of the file");
560 BigSize = DyldInfo.lazy_bind_off;
561 BigSize += DyldInfo.lazy_bind_size;
562 if (BigSize > FileSize)
563 return malformedError("lazy_bind_off field plus lazy_bind_size field of " +
564 Twine(CmdName) + " command " +
565 Twine(LoadCommandIndex) + " extends past the end of "
566 "the file");
567 if (DyldInfo.export_off > FileSize)
568 return malformedError("export_off field of " + Twine(CmdName) +
569 " command " + Twine(LoadCommandIndex) + " extends "
570 "past the end of the file");
571 BigSize = DyldInfo.export_off;
572 BigSize += DyldInfo.export_size;
573 if (BigSize > FileSize)
574 return malformedError("export_off field plus export_size field of " +
575 Twine(CmdName) + " command " +
576 Twine(LoadCommandIndex) + " extends past the end of "
577 "the file");
578 *LoadCmd = Load.Ptr;
579 return Error::success();
580}
581
Kevin Enderbyfc0929a2016-09-20 20:14:14 +0000582static Error checkDylibCommand(const MachOObjectFile *Obj,
583 const MachOObjectFile::LoadCommandInfo &Load,
584 uint32_t LoadCommandIndex, const char *CmdName) {
585 if (Load.C.cmdsize < sizeof(MachO::dylib_command))
586 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
587 CmdName + " cmdsize too small");
588 MachO::dylib_command D = getStruct<MachO::dylib_command>(Obj, Load.Ptr);
589 if (D.dylib.name < sizeof(MachO::dylib_command))
590 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
591 CmdName + " name.offset field too small, not past "
592 "the end of the dylib_command struct");
593 if (D.dylib.name >= D.cmdsize)
594 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
595 CmdName + " name.offset field extends past the end "
596 "of the load command");
597 // Make sure there is a null between the starting offset of the name and
598 // the end of the load command.
599 uint32_t i;
600 const char *P = (const char *)Load.Ptr;
601 for (i = D.dylib.name; i < D.cmdsize; i++)
602 if (P[i] == '\0')
603 break;
604 if (i >= D.cmdsize)
605 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
606 CmdName + " library name extends past the end of the "
607 "load command");
608 return Error::success();
609}
610
611static Error checkDylibIdCommand(const MachOObjectFile *Obj,
612 const MachOObjectFile::LoadCommandInfo &Load,
613 uint32_t LoadCommandIndex,
614 const char **LoadCmd) {
615 if (Error Err = checkDylibCommand(Obj, Load, LoadCommandIndex,
616 "LC_ID_DYLIB"))
617 return Err;
618 if (*LoadCmd != nullptr)
619 return malformedError("more than one LC_ID_DYLIB command");
620 if (Obj->getHeader().filetype != MachO::MH_DYLIB &&
621 Obj->getHeader().filetype != MachO::MH_DYLIB_STUB)
622 return malformedError("LC_ID_DYLIB load command in non-dynamic library "
623 "file type");
624 *LoadCmd = Load.Ptr;
625 return Error::success();
626}
627
Kevin Enderby3e490ef2016-09-27 23:24:13 +0000628static Error checkDyldCommand(const MachOObjectFile *Obj,
629 const MachOObjectFile::LoadCommandInfo &Load,
630 uint32_t LoadCommandIndex, const char *CmdName) {
631 if (Load.C.cmdsize < sizeof(MachO::dylinker_command))
632 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
633 CmdName + " cmdsize too small");
634 MachO::dylinker_command D = getStruct<MachO::dylinker_command>(Obj, Load.Ptr);
635 if (D.name < sizeof(MachO::dylinker_command))
636 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
637 CmdName + " name.offset field too small, not past "
638 "the end of the dylinker_command struct");
639 if (D.name >= D.cmdsize)
640 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
641 CmdName + " name.offset field extends past the end "
642 "of the load command");
643 // Make sure there is a null between the starting offset of the name and
644 // the end of the load command.
645 uint32_t i;
646 const char *P = (const char *)Load.Ptr;
647 for (i = D.name; i < D.cmdsize; i++)
648 if (P[i] == '\0')
649 break;
650 if (i >= D.cmdsize)
651 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
652 CmdName + " dyld name extends past the end of the "
653 "load command");
654 return Error::success();
655}
656
Kevin Enderby32359db2016-09-28 21:20:45 +0000657static Error checkVersCommand(const MachOObjectFile *Obj,
658 const MachOObjectFile::LoadCommandInfo &Load,
659 uint32_t LoadCommandIndex,
660 const char **LoadCmd, const char *CmdName) {
661 if (Load.C.cmdsize != sizeof(MachO::version_min_command))
662 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
663 CmdName + " has incorrect cmdsize");
664 if (*LoadCmd != nullptr)
665 return malformedError("more than one LC_VERSION_MIN_MACOSX, "
666 "LC_VERSION_MIN_IPHONEOS, LC_VERSION_MIN_TVOS or "
667 "LC_VERSION_MIN_WATCHOS command");
668 *LoadCmd = Load.Ptr;
669 return Error::success();
670}
671
Lang Hames82627642016-03-25 21:59:14 +0000672Expected<std::unique_ptr<MachOObjectFile>>
673MachOObjectFile::create(MemoryBufferRef Object, bool IsLittleEndian,
674 bool Is64Bits) {
Lang Hamesd1af8fc2016-03-25 23:54:32 +0000675 Error Err;
Lang Hames82627642016-03-25 21:59:14 +0000676 std::unique_ptr<MachOObjectFile> Obj(
677 new MachOObjectFile(std::move(Object), IsLittleEndian,
678 Is64Bits, Err));
679 if (Err)
680 return std::move(Err);
681 return std::move(Obj);
682}
683
Rafael Espindola48af1c22014-08-19 18:44:46 +0000684MachOObjectFile::MachOObjectFile(MemoryBufferRef Object, bool IsLittleEndian,
Lang Hames9e964f32016-03-25 17:25:34 +0000685 bool Is64bits, Error &Err)
Rafael Espindola48af1c22014-08-19 18:44:46 +0000686 : ObjectFile(getMachOType(IsLittleEndian, Is64bits), Object),
Craig Topper2617dcc2014-04-15 06:32:26 +0000687 SymtabLoadCmd(nullptr), DysymtabLoadCmd(nullptr),
Kevin Enderby9a509442015-01-27 21:28:24 +0000688 DataInCodeLoadCmd(nullptr), LinkOptHintsLoadCmd(nullptr),
689 DyldInfoLoadCmd(nullptr), UuidLoadCmd(nullptr),
690 HasPageZeroSegment(false) {
Lang Hames5e51a2e2016-07-22 16:11:25 +0000691 ErrorAsOutParameter ErrAsOutParam(&Err);
Kevin Enderbyc614d282016-08-12 20:10:25 +0000692 uint64_t SizeOfHeaders;
Kevin Enderby87025742016-04-13 21:17:58 +0000693 if (is64Bit()) {
Lang Hames9e964f32016-03-25 17:25:34 +0000694 parseHeader(this, Header64, Err);
Kevin Enderbyc614d282016-08-12 20:10:25 +0000695 SizeOfHeaders = sizeof(MachO::mach_header_64);
Kevin Enderby87025742016-04-13 21:17:58 +0000696 } else {
Lang Hames9e964f32016-03-25 17:25:34 +0000697 parseHeader(this, Header, Err);
Kevin Enderbyc614d282016-08-12 20:10:25 +0000698 SizeOfHeaders = sizeof(MachO::mach_header);
Kevin Enderby87025742016-04-13 21:17:58 +0000699 }
Lang Hames9e964f32016-03-25 17:25:34 +0000700 if (Err)
Alexey Samsonov9f336632015-06-04 19:45:22 +0000701 return;
Kevin Enderbyc614d282016-08-12 20:10:25 +0000702 SizeOfHeaders += getHeader().sizeofcmds;
703 if (getData().data() + SizeOfHeaders > getData().end()) {
Kevin Enderbyd4e075b2016-05-06 20:16:28 +0000704 Err = malformedError("load commands extend past the end of the file");
Kevin Enderby87025742016-04-13 21:17:58 +0000705 return;
706 }
Alexey Samsonov13415ed2015-06-04 19:22:03 +0000707
708 uint32_t LoadCommandCount = getHeader().ncmds;
Lang Hames9e964f32016-03-25 17:25:34 +0000709 LoadCommandInfo Load;
Kevin Enderbyfc0929a2016-09-20 20:14:14 +0000710 if (LoadCommandCount != 0) {
711 if (auto LoadOrErr = getFirstLoadCommandInfo(this))
712 Load = *LoadOrErr;
713 else {
714 Err = LoadOrErr.takeError();
715 return;
716 }
Alexey Samsonovde5a94a2015-06-04 19:57:46 +0000717 }
Lang Hames9e964f32016-03-25 17:25:34 +0000718
Kevin Enderbyfc0929a2016-09-20 20:14:14 +0000719 const char *DyldIdLoadCmd = nullptr;
Kevin Enderby90986e62016-09-26 21:11:03 +0000720 const char *FuncStartsLoadCmd = nullptr;
721 const char *SplitInfoLoadCmd = nullptr;
722 const char *CodeSignDrsLoadCmd = nullptr;
Kevin Enderby32359db2016-09-28 21:20:45 +0000723 const char *VersLoadCmd = nullptr;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000724 for (unsigned I = 0; I < LoadCommandCount; ++I) {
Kevin Enderby1851a822016-07-07 22:11:42 +0000725 if (is64Bit()) {
726 if (Load.C.cmdsize % 8 != 0) {
727 // We have a hack here to allow 64-bit Mach-O core files to have
728 // LC_THREAD commands that are only a multiple of 4 and not 8 to be
729 // allowed since the macOS kernel produces them.
730 if (getHeader().filetype != MachO::MH_CORE ||
731 Load.C.cmd != MachO::LC_THREAD || Load.C.cmdsize % 4) {
732 Err = malformedError("load command " + Twine(I) + " cmdsize not a "
733 "multiple of 8");
734 return;
735 }
736 }
737 } else {
738 if (Load.C.cmdsize % 4 != 0) {
739 Err = malformedError("load command " + Twine(I) + " cmdsize not a "
740 "multiple of 4");
741 return;
742 }
743 }
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000744 LoadCommands.push_back(Load);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000745 if (Load.C.cmd == MachO::LC_SYMTAB) {
Kevin Enderby0e52c922016-08-26 19:34:07 +0000746 if ((Err = checkSymtabCommand(this, Load, I, &SymtabLoadCmd)))
David Majnemer73cc6ff2014-11-13 19:48:56 +0000747 return;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000748 } else if (Load.C.cmd == MachO::LC_DYSYMTAB) {
Kevin Enderbydcbc5042016-08-30 21:28:30 +0000749 if ((Err = checkDysymtabCommand(this, Load, I, &DysymtabLoadCmd)))
David Majnemer73cc6ff2014-11-13 19:48:56 +0000750 return;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000751 } else if (Load.C.cmd == MachO::LC_DATA_IN_CODE) {
Kevin Enderby9d0c9452016-08-31 17:57:46 +0000752 if ((Err = checkLinkeditDataCommand(this, Load, I, &DataInCodeLoadCmd,
753 "LC_DATA_IN_CODE")))
David Majnemer73cc6ff2014-11-13 19:48:56 +0000754 return;
Kevin Enderby9a509442015-01-27 21:28:24 +0000755 } else if (Load.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
Kevin Enderby9d0c9452016-08-31 17:57:46 +0000756 if ((Err = checkLinkeditDataCommand(this, Load, I, &LinkOptHintsLoadCmd,
757 "LC_LINKER_OPTIMIZATION_HINT")))
Kevin Enderby9a509442015-01-27 21:28:24 +0000758 return;
Kevin Enderby90986e62016-09-26 21:11:03 +0000759 } else if (Load.C.cmd == MachO::LC_FUNCTION_STARTS) {
760 if ((Err = checkLinkeditDataCommand(this, Load, I, &FuncStartsLoadCmd,
761 "LC_FUNCTION_STARTS")))
762 return;
763 } else if (Load.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO) {
764 if ((Err = checkLinkeditDataCommand(this, Load, I, &SplitInfoLoadCmd,
765 "LC_SEGMENT_SPLIT_INFO")))
766 return;
767 } else if (Load.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS) {
768 if ((Err = checkLinkeditDataCommand(this, Load, I, &CodeSignDrsLoadCmd,
769 "LC_DYLIB_CODE_SIGN_DRS")))
770 return;
Kevin Enderbyf76b56c2016-09-13 21:42:28 +0000771 } else if (Load.C.cmd == MachO::LC_DYLD_INFO) {
772 if ((Err = checkDyldInfoCommand(this, Load, I, &DyldInfoLoadCmd,
773 "LC_DYLD_INFO")))
David Majnemer73cc6ff2014-11-13 19:48:56 +0000774 return;
Kevin Enderbyf76b56c2016-09-13 21:42:28 +0000775 } else if (Load.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
776 if ((Err = checkDyldInfoCommand(this, Load, I, &DyldInfoLoadCmd,
777 "LC_DYLD_INFO_ONLY")))
778 return;
Alexander Potapenko6909b5b2014-10-15 23:35:45 +0000779 } else if (Load.C.cmd == MachO::LC_UUID) {
Kevin Enderbye71e13c2016-09-21 20:03:09 +0000780 if (Load.C.cmdsize != sizeof(MachO::uuid_command)) {
781 Err = malformedError("LC_UUID command " + Twine(I) + " has incorrect "
782 "cmdsize");
783 return;
784 }
David Majnemer73cc6ff2014-11-13 19:48:56 +0000785 if (UuidLoadCmd) {
Kevin Enderbye71e13c2016-09-21 20:03:09 +0000786 Err = malformedError("more than one LC_UUID command");
David Majnemer73cc6ff2014-11-13 19:48:56 +0000787 return;
788 }
Alexander Potapenko6909b5b2014-10-15 23:35:45 +0000789 UuidLoadCmd = Load.Ptr;
Alexey Samsonove1a76ab2015-06-04 22:08:37 +0000790 } else if (Load.C.cmd == MachO::LC_SEGMENT_64) {
Kevin Enderbyc614d282016-08-12 20:10:25 +0000791 if ((Err = parseSegmentLoadCommand<MachO::segment_command_64,
792 MachO::section_64>(
Kevin Enderbyb34e3a12016-05-05 17:43:35 +0000793 this, Load, Sections, HasPageZeroSegment, I,
Kevin Enderbyc614d282016-08-12 20:10:25 +0000794 "LC_SEGMENT_64", SizeOfHeaders)))
Alexey Samsonov074da9b2015-06-04 20:08:52 +0000795 return;
Alexey Samsonove1a76ab2015-06-04 22:08:37 +0000796 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
Kevin Enderbyc614d282016-08-12 20:10:25 +0000797 if ((Err = parseSegmentLoadCommand<MachO::segment_command,
798 MachO::section>(
799 this, Load, Sections, HasPageZeroSegment, I,
800 "LC_SEGMENT", SizeOfHeaders)))
Alexey Samsonov074da9b2015-06-04 20:08:52 +0000801 return;
Kevin Enderbyfc0929a2016-09-20 20:14:14 +0000802 } else if (Load.C.cmd == MachO::LC_ID_DYLIB) {
803 if ((Err = checkDylibIdCommand(this, Load, I, &DyldIdLoadCmd)))
804 return;
805 } else if (Load.C.cmd == MachO::LC_LOAD_DYLIB) {
806 if ((Err = checkDylibCommand(this, Load, I, "LC_LOAD_DYLIB")))
807 return;
808 Libraries.push_back(Load.Ptr);
809 } else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB) {
810 if ((Err = checkDylibCommand(this, Load, I, "LC_LOAD_WEAK_DYLIB")))
811 return;
812 Libraries.push_back(Load.Ptr);
813 } else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB) {
814 if ((Err = checkDylibCommand(this, Load, I, "LC_LAZY_LOAD_DYLIB")))
815 return;
816 Libraries.push_back(Load.Ptr);
817 } else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB) {
818 if ((Err = checkDylibCommand(this, Load, I, "LC_REEXPORT_DYLIB")))
819 return;
820 Libraries.push_back(Load.Ptr);
821 } else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
822 if ((Err = checkDylibCommand(this, Load, I, "LC_LOAD_UPWARD_DYLIB")))
823 return;
Kevin Enderby980b2582014-06-05 21:21:57 +0000824 Libraries.push_back(Load.Ptr);
Kevin Enderby3e490ef2016-09-27 23:24:13 +0000825 } else if (Load.C.cmd == MachO::LC_ID_DYLINKER) {
826 if ((Err = checkDyldCommand(this, Load, I, "LC_ID_DYLINKER")))
827 return;
828 } else if (Load.C.cmd == MachO::LC_LOAD_DYLINKER) {
829 if ((Err = checkDyldCommand(this, Load, I, "LC_LOAD_DYLINKER")))
830 return;
831 } else if (Load.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
832 if ((Err = checkDyldCommand(this, Load, I, "LC_DYLD_ENVIRONMENT")))
833 return;
Kevin Enderby32359db2016-09-28 21:20:45 +0000834 } else if (Load.C.cmd == MachO::LC_VERSION_MIN_MACOSX) {
835 if ((Err = checkVersCommand(this, Load, I, &VersLoadCmd,
836 "LC_VERSION_MIN_MACOSX")))
837 return;
838 } else if (Load.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS) {
839 if ((Err = checkVersCommand(this, Load, I, &VersLoadCmd,
840 "LC_VERSION_MIN_IPHONEOS")))
841 return;
842 } else if (Load.C.cmd == MachO::LC_VERSION_MIN_TVOS) {
843 if ((Err = checkVersCommand(this, Load, I, &VersLoadCmd,
844 "LC_VERSION_MIN_TVOS")))
845 return;
846 } else if (Load.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
847 if ((Err = checkVersCommand(this, Load, I, &VersLoadCmd,
848 "LC_VERSION_MIN_WATCHOS")))
849 return;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000850 }
Alexey Samsonovde5a94a2015-06-04 19:57:46 +0000851 if (I < LoadCommandCount - 1) {
Kevin Enderby368e7142016-05-03 17:16:08 +0000852 if (auto LoadOrErr = getNextLoadCommandInfo(this, I, Load))
Lang Hames9e964f32016-03-25 17:25:34 +0000853 Load = *LoadOrErr;
854 else {
855 Err = LoadOrErr.takeError();
Alexey Samsonovde5a94a2015-06-04 19:57:46 +0000856 return;
857 }
Alexey Samsonovde5a94a2015-06-04 19:57:46 +0000858 }
Rafael Espindola56f976f2013-04-18 18:08:55 +0000859 }
Kevin Enderby1829c682016-01-22 22:49:55 +0000860 if (!SymtabLoadCmd) {
861 if (DysymtabLoadCmd) {
Kevin Enderbyd4e075b2016-05-06 20:16:28 +0000862 Err = malformedError("contains LC_DYSYMTAB load command without a "
Kevin Enderby89134962016-05-05 23:41:05 +0000863 "LC_SYMTAB load command");
Kevin Enderby1829c682016-01-22 22:49:55 +0000864 return;
865 }
866 } else if (DysymtabLoadCmd) {
867 MachO::symtab_command Symtab =
868 getStruct<MachO::symtab_command>(this, SymtabLoadCmd);
869 MachO::dysymtab_command Dysymtab =
870 getStruct<MachO::dysymtab_command>(this, DysymtabLoadCmd);
871 if (Dysymtab.nlocalsym != 0 && Dysymtab.ilocalsym > Symtab.nsyms) {
Kevin Enderbyd4e075b2016-05-06 20:16:28 +0000872 Err = malformedError("ilocalsym in LC_DYSYMTAB load command "
Kevin Enderby89134962016-05-05 23:41:05 +0000873 "extends past the end of the symbol table");
Kevin Enderby1829c682016-01-22 22:49:55 +0000874 return;
875 }
Kevin Enderby5e55d172016-04-21 20:29:49 +0000876 uint64_t BigSize = Dysymtab.ilocalsym;
877 BigSize += Dysymtab.nlocalsym;
878 if (Dysymtab.nlocalsym != 0 && BigSize > Symtab.nsyms) {
Kevin Enderbyd4e075b2016-05-06 20:16:28 +0000879 Err = malformedError("ilocalsym plus nlocalsym in LC_DYSYMTAB load "
Kevin Enderby89134962016-05-05 23:41:05 +0000880 "command extends past the end of the symbol table");
Kevin Enderby1829c682016-01-22 22:49:55 +0000881 return;
882 }
883 if (Dysymtab.nextdefsym != 0 && Dysymtab.ilocalsym > Symtab.nsyms) {
Kevin Enderbyd4e075b2016-05-06 20:16:28 +0000884 Err = malformedError("nextdefsym in LC_DYSYMTAB load command "
Kevin Enderby89134962016-05-05 23:41:05 +0000885 "extends past the end of the symbol table");
Kevin Enderby1829c682016-01-22 22:49:55 +0000886 return;
887 }
Kevin Enderby5e55d172016-04-21 20:29:49 +0000888 BigSize = Dysymtab.iextdefsym;
889 BigSize += Dysymtab.nextdefsym;
890 if (Dysymtab.nextdefsym != 0 && BigSize > Symtab.nsyms) {
Kevin Enderbyd4e075b2016-05-06 20:16:28 +0000891 Err = malformedError("iextdefsym plus nextdefsym in LC_DYSYMTAB "
Kevin Enderby89134962016-05-05 23:41:05 +0000892 "load command extends past the end of the symbol "
893 "table");
Kevin Enderby1829c682016-01-22 22:49:55 +0000894 return;
895 }
896 if (Dysymtab.nundefsym != 0 && Dysymtab.iundefsym > Symtab.nsyms) {
Kevin Enderbyd4e075b2016-05-06 20:16:28 +0000897 Err = malformedError("nundefsym in LC_DYSYMTAB load command "
Kevin Enderby89134962016-05-05 23:41:05 +0000898 "extends past the end of the symbol table");
Kevin Enderby1829c682016-01-22 22:49:55 +0000899 return;
900 }
Kevin Enderby5e55d172016-04-21 20:29:49 +0000901 BigSize = Dysymtab.iundefsym;
902 BigSize += Dysymtab.nundefsym;
903 if (Dysymtab.nundefsym != 0 && BigSize > Symtab.nsyms) {
Kevin Enderbyd4e075b2016-05-06 20:16:28 +0000904 Err = malformedError("iundefsym plus nundefsym in LC_DYSYMTAB load "
Kevin Enderby89134962016-05-05 23:41:05 +0000905 " command extends past the end of the symbol table");
Kevin Enderby1829c682016-01-22 22:49:55 +0000906 return;
907 }
908 }
Kevin Enderbyfc0929a2016-09-20 20:14:14 +0000909 if ((getHeader().filetype == MachO::MH_DYLIB ||
910 getHeader().filetype == MachO::MH_DYLIB_STUB) &&
911 DyldIdLoadCmd == nullptr) {
912 Err = malformedError("no LC_ID_DYLIB load command in dynamic library "
913 "filetype");
914 return;
915 }
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000916 assert(LoadCommands.size() == LoadCommandCount);
Lang Hames9e964f32016-03-25 17:25:34 +0000917
918 Err = Error::success();
Rafael Espindola56f976f2013-04-18 18:08:55 +0000919}
920
Rafael Espindola5e812af2014-01-30 02:49:50 +0000921void MachOObjectFile::moveSymbolNext(DataRefImpl &Symb) const {
Rafael Espindola75c30362013-04-24 19:47:55 +0000922 unsigned SymbolTableEntrySize = is64Bit() ?
Charles Davis8bdfafd2013-09-01 04:28:48 +0000923 sizeof(MachO::nlist_64) :
924 sizeof(MachO::nlist);
Rafael Espindola75c30362013-04-24 19:47:55 +0000925 Symb.p += SymbolTableEntrySize;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000926}
927
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000928Expected<StringRef> MachOObjectFile::getSymbolName(DataRefImpl Symb) const {
Rafael Espindola6e040c02013-04-26 20:07:33 +0000929 StringRef StringTable = getStringTableData();
Artyom Skrobov78d5daf2014-07-18 09:26:16 +0000930 MachO::nlist_base Entry = getSymbolTableEntryBase(this, Symb);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000931 const char *Start = &StringTable.data()[Entry.n_strx];
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000932 if (Start < getData().begin() || Start >= getData().end()) {
Kevin Enderbyd4e075b2016-05-06 20:16:28 +0000933 return malformedError("bad string index: " + Twine(Entry.n_strx) +
Kevin Enderby89134962016-05-05 23:41:05 +0000934 " for symbol at index " + Twine(getSymbolIndex(Symb)));
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000935 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000936 return StringRef(Start);
Rafael Espindola56f976f2013-04-18 18:08:55 +0000937}
938
Rafael Espindola0e77a942014-12-10 20:46:55 +0000939unsigned MachOObjectFile::getSectionType(SectionRef Sec) const {
940 DataRefImpl DRI = Sec.getRawDataRefImpl();
941 uint32_t Flags = getSectionFlags(this, DRI);
942 return Flags & MachO::SECTION_TYPE;
943}
944
Rafael Espindola59128922015-06-24 18:14:41 +0000945uint64_t MachOObjectFile::getNValue(DataRefImpl Sym) const {
946 if (is64Bit()) {
947 MachO::nlist_64 Entry = getSymbol64TableEntry(Sym);
948 return Entry.n_value;
949 }
950 MachO::nlist Entry = getSymbolTableEntry(Sym);
951 return Entry.n_value;
952}
953
Kevin Enderby980b2582014-06-05 21:21:57 +0000954// getIndirectName() returns the name of the alias'ed symbol who's string table
955// index is in the n_value field.
Rafael Espindola3acea392014-06-12 21:46:39 +0000956std::error_code MachOObjectFile::getIndirectName(DataRefImpl Symb,
957 StringRef &Res) const {
Kevin Enderby980b2582014-06-05 21:21:57 +0000958 StringRef StringTable = getStringTableData();
Rafael Espindola59128922015-06-24 18:14:41 +0000959 MachO::nlist_base Entry = getSymbolTableEntryBase(this, Symb);
960 if ((Entry.n_type & MachO::N_TYPE) != MachO::N_INDR)
961 return object_error::parse_failed;
962 uint64_t NValue = getNValue(Symb);
Kevin Enderby980b2582014-06-05 21:21:57 +0000963 if (NValue >= StringTable.size())
964 return object_error::parse_failed;
965 const char *Start = &StringTable.data()[NValue];
966 Res = StringRef(Start);
Rui Ueyama7d099192015-06-09 15:20:42 +0000967 return std::error_code();
Kevin Enderby980b2582014-06-05 21:21:57 +0000968}
969
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +0000970uint64_t MachOObjectFile::getSymbolValueImpl(DataRefImpl Sym) const {
Rafael Espindola7e7be922015-07-07 15:05:09 +0000971 return getNValue(Sym);
Rafael Espindola991af662015-06-24 19:11:10 +0000972}
973
Kevin Enderby931cb652016-06-24 18:24:42 +0000974Expected<uint64_t> MachOObjectFile::getSymbolAddress(DataRefImpl Sym) const {
Rafael Espindolaed067c42015-07-03 18:19:00 +0000975 return getSymbolValue(Sym);
Rafael Espindola56f976f2013-04-18 18:08:55 +0000976}
977
Rafael Espindolaa4d224722015-05-31 23:52:50 +0000978uint32_t MachOObjectFile::getSymbolAlignment(DataRefImpl DRI) const {
Rafael Espindola20122a42014-01-31 20:57:12 +0000979 uint32_t flags = getSymbolFlags(DRI);
Rafael Espindolae4dd2e02013-04-29 22:24:22 +0000980 if (flags & SymbolRef::SF_Common) {
Artyom Skrobov78d5daf2014-07-18 09:26:16 +0000981 MachO::nlist_base Entry = getSymbolTableEntryBase(this, DRI);
Rafael Espindolaa4d224722015-05-31 23:52:50 +0000982 return 1 << MachO::GET_COMM_ALIGN(Entry.n_desc);
Rafael Espindolae4dd2e02013-04-29 22:24:22 +0000983 }
Rafael Espindolaa4d224722015-05-31 23:52:50 +0000984 return 0;
Rafael Espindolae4dd2e02013-04-29 22:24:22 +0000985}
986
Rafael Espindolad7a32ea2015-06-24 10:20:30 +0000987uint64_t MachOObjectFile::getCommonSymbolSizeImpl(DataRefImpl DRI) const {
Rafael Espindola05cbccc2015-07-07 13:58:32 +0000988 return getNValue(DRI);
Rafael Espindola56f976f2013-04-18 18:08:55 +0000989}
990
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000991Expected<SymbolRef::Type>
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000992MachOObjectFile::getSymbolType(DataRefImpl Symb) const {
Artyom Skrobov78d5daf2014-07-18 09:26:16 +0000993 MachO::nlist_base Entry = getSymbolTableEntryBase(this, Symb);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000994 uint8_t n_type = Entry.n_type;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000995
Rafael Espindola56f976f2013-04-18 18:08:55 +0000996 // If this is a STAB debugging symbol, we can do nothing more.
Rafael Espindola2fa80cc2015-06-26 12:18:49 +0000997 if (n_type & MachO::N_STAB)
998 return SymbolRef::ST_Debug;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000999
Charles Davis74ec8b02013-08-27 05:00:13 +00001000 switch (n_type & MachO::N_TYPE) {
1001 case MachO::N_UNDF :
Rafael Espindola2fa80cc2015-06-26 12:18:49 +00001002 return SymbolRef::ST_Unknown;
Charles Davis74ec8b02013-08-27 05:00:13 +00001003 case MachO::N_SECT :
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001004 Expected<section_iterator> SecOrError = getSymbolSection(Symb);
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00001005 if (!SecOrError)
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001006 return SecOrError.takeError();
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00001007 section_iterator Sec = *SecOrError;
Kuba Breckade833222015-11-12 09:40:29 +00001008 if (Sec->isData() || Sec->isBSS())
1009 return SymbolRef::ST_Data;
Rafael Espindola2fa80cc2015-06-26 12:18:49 +00001010 return SymbolRef::ST_Function;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001011 }
Rafael Espindola2fa80cc2015-06-26 12:18:49 +00001012 return SymbolRef::ST_Other;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001013}
1014
Rafael Espindola20122a42014-01-31 20:57:12 +00001015uint32_t MachOObjectFile::getSymbolFlags(DataRefImpl DRI) const {
Artyom Skrobov78d5daf2014-07-18 09:26:16 +00001016 MachO::nlist_base Entry = getSymbolTableEntryBase(this, DRI);
Rafael Espindola56f976f2013-04-18 18:08:55 +00001017
Charles Davis8bdfafd2013-09-01 04:28:48 +00001018 uint8_t MachOType = Entry.n_type;
1019 uint16_t MachOFlags = Entry.n_desc;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001020
Rafael Espindola20122a42014-01-31 20:57:12 +00001021 uint32_t Result = SymbolRef::SF_None;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001022
Tim Northovereaef0742014-05-30 13:22:59 +00001023 if ((MachOType & MachO::N_TYPE) == MachO::N_INDR)
1024 Result |= SymbolRef::SF_Indirect;
1025
Rafael Espindolaa1356322013-11-02 05:03:24 +00001026 if (MachOType & MachO::N_STAB)
Rafael Espindola56f976f2013-04-18 18:08:55 +00001027 Result |= SymbolRef::SF_FormatSpecific;
1028
Charles Davis74ec8b02013-08-27 05:00:13 +00001029 if (MachOType & MachO::N_EXT) {
Rafael Espindola56f976f2013-04-18 18:08:55 +00001030 Result |= SymbolRef::SF_Global;
Charles Davis74ec8b02013-08-27 05:00:13 +00001031 if ((MachOType & MachO::N_TYPE) == MachO::N_UNDF) {
Rafael Espindola05cbccc2015-07-07 13:58:32 +00001032 if (getNValue(DRI))
Rafael Espindolae4dd2e02013-04-29 22:24:22 +00001033 Result |= SymbolRef::SF_Common;
Rafael Espindolad8247722015-07-07 14:26:39 +00001034 else
1035 Result |= SymbolRef::SF_Undefined;
Rafael Espindolae4dd2e02013-04-29 22:24:22 +00001036 }
Lang Hames7e0692b2015-01-15 22:33:30 +00001037
1038 if (!(MachOType & MachO::N_PEXT))
1039 Result |= SymbolRef::SF_Exported;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001040 }
1041
Charles Davis74ec8b02013-08-27 05:00:13 +00001042 if (MachOFlags & (MachO::N_WEAK_REF | MachO::N_WEAK_DEF))
Rafael Espindola56f976f2013-04-18 18:08:55 +00001043 Result |= SymbolRef::SF_Weak;
1044
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001045 if (MachOFlags & (MachO::N_ARM_THUMB_DEF))
1046 Result |= SymbolRef::SF_Thumb;
1047
Charles Davis74ec8b02013-08-27 05:00:13 +00001048 if ((MachOType & MachO::N_TYPE) == MachO::N_ABS)
Rafael Espindola56f976f2013-04-18 18:08:55 +00001049 Result |= SymbolRef::SF_Absolute;
1050
Rafael Espindola20122a42014-01-31 20:57:12 +00001051 return Result;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001052}
1053
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001054Expected<section_iterator>
Rafael Espindola8bab8892015-08-07 23:27:14 +00001055MachOObjectFile::getSymbolSection(DataRefImpl Symb) const {
Artyom Skrobov78d5daf2014-07-18 09:26:16 +00001056 MachO::nlist_base Entry = getSymbolTableEntryBase(this, Symb);
Charles Davis8bdfafd2013-09-01 04:28:48 +00001057 uint8_t index = Entry.n_sect;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001058
Rafael Espindola8bab8892015-08-07 23:27:14 +00001059 if (index == 0)
1060 return section_end();
1061 DataRefImpl DRI;
1062 DRI.d.a = index - 1;
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00001063 if (DRI.d.a >= Sections.size()){
Kevin Enderbyd4e075b2016-05-06 20:16:28 +00001064 return malformedError("bad section index: " + Twine((int)index) +
Kevin Enderby89134962016-05-05 23:41:05 +00001065 " for symbol at index " + Twine(getSymbolIndex(Symb)));
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00001066 }
Rafael Espindola8bab8892015-08-07 23:27:14 +00001067 return section_iterator(SectionRef(DRI, this));
Rafael Espindola56f976f2013-04-18 18:08:55 +00001068}
1069
Rafael Espindola6bf32212015-06-24 19:57:32 +00001070unsigned MachOObjectFile::getSymbolSectionID(SymbolRef Sym) const {
1071 MachO::nlist_base Entry =
1072 getSymbolTableEntryBase(this, Sym.getRawDataRefImpl());
1073 return Entry.n_sect - 1;
1074}
1075
Rafael Espindola5e812af2014-01-30 02:49:50 +00001076void MachOObjectFile::moveSectionNext(DataRefImpl &Sec) const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00001077 Sec.d.a++;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001078}
1079
Rafael Espindola3acea392014-06-12 21:46:39 +00001080std::error_code MachOObjectFile::getSectionName(DataRefImpl Sec,
1081 StringRef &Result) const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00001082 ArrayRef<char> Raw = getSectionRawName(Sec);
1083 Result = parseSegmentOrSectionName(Raw.data());
Rui Ueyama7d099192015-06-09 15:20:42 +00001084 return std::error_code();
Rafael Espindola56f976f2013-04-18 18:08:55 +00001085}
1086
Rafael Espindola80291272014-10-08 15:28:58 +00001087uint64_t MachOObjectFile::getSectionAddress(DataRefImpl Sec) const {
1088 if (is64Bit())
1089 return getSection64(Sec).addr;
1090 return getSection(Sec).addr;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001091}
1092
Rafael Espindola80291272014-10-08 15:28:58 +00001093uint64_t MachOObjectFile::getSectionSize(DataRefImpl Sec) const {
Kevin Enderby46e642f2015-10-08 22:50:55 +00001094 // In the case if a malformed Mach-O file where the section offset is past
1095 // the end of the file or some part of the section size is past the end of
1096 // the file return a size of zero or a size that covers the rest of the file
1097 // but does not extend past the end of the file.
1098 uint32_t SectOffset, SectType;
1099 uint64_t SectSize;
1100
1101 if (is64Bit()) {
1102 MachO::section_64 Sect = getSection64(Sec);
1103 SectOffset = Sect.offset;
1104 SectSize = Sect.size;
1105 SectType = Sect.flags & MachO::SECTION_TYPE;
1106 } else {
1107 MachO::section Sect = getSection(Sec);
1108 SectOffset = Sect.offset;
1109 SectSize = Sect.size;
1110 SectType = Sect.flags & MachO::SECTION_TYPE;
1111 }
1112 if (SectType == MachO::S_ZEROFILL || SectType == MachO::S_GB_ZEROFILL)
1113 return SectSize;
1114 uint64_t FileSize = getData().size();
1115 if (SectOffset > FileSize)
1116 return 0;
1117 if (FileSize - SectOffset < SectSize)
1118 return FileSize - SectOffset;
1119 return SectSize;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001120}
1121
Rafael Espindola3acea392014-06-12 21:46:39 +00001122std::error_code MachOObjectFile::getSectionContents(DataRefImpl Sec,
1123 StringRef &Res) const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00001124 uint32_t Offset;
1125 uint64_t Size;
1126
1127 if (is64Bit()) {
Charles Davis8bdfafd2013-09-01 04:28:48 +00001128 MachO::section_64 Sect = getSection64(Sec);
1129 Offset = Sect.offset;
1130 Size = Sect.size;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001131 } else {
Charles Davis8bdfafd2013-09-01 04:28:48 +00001132 MachO::section Sect = getSection(Sec);
1133 Offset = Sect.offset;
1134 Size = Sect.size;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001135 }
1136
1137 Res = this->getData().substr(Offset, Size);
Rui Ueyama7d099192015-06-09 15:20:42 +00001138 return std::error_code();
Rafael Espindola56f976f2013-04-18 18:08:55 +00001139}
1140
Rafael Espindola80291272014-10-08 15:28:58 +00001141uint64_t MachOObjectFile::getSectionAlignment(DataRefImpl Sec) const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00001142 uint32_t Align;
1143 if (is64Bit()) {
Charles Davis8bdfafd2013-09-01 04:28:48 +00001144 MachO::section_64 Sect = getSection64(Sec);
1145 Align = Sect.align;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001146 } else {
Charles Davis8bdfafd2013-09-01 04:28:48 +00001147 MachO::section Sect = getSection(Sec);
1148 Align = Sect.align;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001149 }
1150
Rafael Espindola80291272014-10-08 15:28:58 +00001151 return uint64_t(1) << Align;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001152}
1153
George Rimar401e4e52016-05-24 12:48:46 +00001154bool MachOObjectFile::isSectionCompressed(DataRefImpl Sec) const {
1155 return false;
1156}
1157
Rafael Espindola80291272014-10-08 15:28:58 +00001158bool MachOObjectFile::isSectionText(DataRefImpl Sec) const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00001159 uint32_t Flags = getSectionFlags(this, Sec);
Rafael Espindola80291272014-10-08 15:28:58 +00001160 return Flags & MachO::S_ATTR_PURE_INSTRUCTIONS;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001161}
1162
Rafael Espindola80291272014-10-08 15:28:58 +00001163bool MachOObjectFile::isSectionData(DataRefImpl Sec) const {
Kevin Enderby403258f2014-05-19 20:36:02 +00001164 uint32_t Flags = getSectionFlags(this, Sec);
1165 unsigned SectionType = Flags & MachO::SECTION_TYPE;
Rafael Espindola80291272014-10-08 15:28:58 +00001166 return !(Flags & MachO::S_ATTR_PURE_INSTRUCTIONS) &&
1167 !(SectionType == MachO::S_ZEROFILL ||
1168 SectionType == MachO::S_GB_ZEROFILL);
Michael J. Spencer800619f2011-09-28 20:57:30 +00001169}
1170
Rafael Espindola80291272014-10-08 15:28:58 +00001171bool MachOObjectFile::isSectionBSS(DataRefImpl Sec) const {
Kevin Enderby403258f2014-05-19 20:36:02 +00001172 uint32_t Flags = getSectionFlags(this, Sec);
1173 unsigned SectionType = Flags & MachO::SECTION_TYPE;
Rafael Espindola80291272014-10-08 15:28:58 +00001174 return !(Flags & MachO::S_ATTR_PURE_INSTRUCTIONS) &&
1175 (SectionType == MachO::S_ZEROFILL ||
1176 SectionType == MachO::S_GB_ZEROFILL);
Preston Gurd2138ef62012-04-12 20:13:57 +00001177}
1178
Rafael Espindola6bf32212015-06-24 19:57:32 +00001179unsigned MachOObjectFile::getSectionID(SectionRef Sec) const {
1180 return Sec.getRawDataRefImpl().d.a;
1181}
1182
Rafael Espindola80291272014-10-08 15:28:58 +00001183bool MachOObjectFile::isSectionVirtual(DataRefImpl Sec) const {
Rafael Espindolac2413f52013-04-09 14:49:08 +00001184 // FIXME: Unimplemented.
Rafael Espindola80291272014-10-08 15:28:58 +00001185 return false;
Rafael Espindolac2413f52013-04-09 14:49:08 +00001186}
1187
Steven Wuf2fe0142016-02-29 19:40:10 +00001188bool MachOObjectFile::isSectionBitcode(DataRefImpl Sec) const {
1189 StringRef SegmentName = getSectionFinalSegmentName(Sec);
1190 StringRef SectName;
1191 if (!getSectionName(Sec, SectName))
1192 return (SegmentName == "__LLVM" && SectName == "__bitcode");
1193 return false;
1194}
1195
Rui Ueyamabc654b12013-09-27 21:47:05 +00001196relocation_iterator MachOObjectFile::section_rel_begin(DataRefImpl Sec) const {
Rafael Espindola04d3f492013-04-25 12:45:46 +00001197 DataRefImpl Ret;
Rafael Espindola128b8112014-04-03 23:51:28 +00001198 Ret.d.a = Sec.d.a;
1199 Ret.d.b = 0;
Rafael Espindola04d3f492013-04-25 12:45:46 +00001200 return relocation_iterator(RelocationRef(Ret, this));
Michael J. Spencere5fd0042011-10-07 19:25:32 +00001201}
Rafael Espindolac0406e12013-04-08 20:45:01 +00001202
Rafael Espindola56f976f2013-04-18 18:08:55 +00001203relocation_iterator
Rui Ueyamabc654b12013-09-27 21:47:05 +00001204MachOObjectFile::section_rel_end(DataRefImpl Sec) const {
Rafael Espindola04d3f492013-04-25 12:45:46 +00001205 uint32_t Num;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001206 if (is64Bit()) {
Charles Davis8bdfafd2013-09-01 04:28:48 +00001207 MachO::section_64 Sect = getSection64(Sec);
Charles Davis8bdfafd2013-09-01 04:28:48 +00001208 Num = Sect.nreloc;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001209 } else {
Charles Davis8bdfafd2013-09-01 04:28:48 +00001210 MachO::section Sect = getSection(Sec);
Charles Davis8bdfafd2013-09-01 04:28:48 +00001211 Num = Sect.nreloc;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001212 }
Eric Christopher7b015c72011-04-22 03:19:48 +00001213
Rafael Espindola56f976f2013-04-18 18:08:55 +00001214 DataRefImpl Ret;
Rafael Espindola128b8112014-04-03 23:51:28 +00001215 Ret.d.a = Sec.d.a;
1216 Ret.d.b = Num;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001217 return relocation_iterator(RelocationRef(Ret, this));
1218}
Benjamin Kramer022ecdf2011-09-08 20:52:17 +00001219
Rafael Espindola5e812af2014-01-30 02:49:50 +00001220void MachOObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
Rafael Espindola128b8112014-04-03 23:51:28 +00001221 ++Rel.d.b;
Benjamin Kramer022ecdf2011-09-08 20:52:17 +00001222}
Owen Anderson171f4852011-10-24 23:20:07 +00001223
Rafael Espindola96d071c2015-06-29 23:29:12 +00001224uint64_t MachOObjectFile::getRelocationOffset(DataRefImpl Rel) const {
Rafael Espindola72475462014-04-04 00:31:12 +00001225 assert(getHeader().filetype == MachO::MH_OBJECT &&
1226 "Only implemented for MH_OBJECT");
Charles Davis8bdfafd2013-09-01 04:28:48 +00001227 MachO::any_relocation_info RE = getRelocation(Rel);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001228 return getAnyRelocationAddress(RE);
David Meyer2fc34c52012-03-01 01:36:50 +00001229}
1230
Rafael Espindola806f0062013-06-05 01:33:53 +00001231symbol_iterator
1232MachOObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
Charles Davis8bdfafd2013-09-01 04:28:48 +00001233 MachO::any_relocation_info RE = getRelocation(Rel);
Tim Northover07f99fb2014-07-04 10:57:56 +00001234 if (isRelocationScattered(RE))
1235 return symbol_end();
1236
Rafael Espindola56f976f2013-04-18 18:08:55 +00001237 uint32_t SymbolIdx = getPlainRelocationSymbolNum(RE);
1238 bool isExtern = getPlainRelocationExternal(RE);
Rafael Espindola806f0062013-06-05 01:33:53 +00001239 if (!isExtern)
Rafael Espindolab5155a52014-02-10 20:24:04 +00001240 return symbol_end();
Rafael Espindola75c30362013-04-24 19:47:55 +00001241
Charles Davis8bdfafd2013-09-01 04:28:48 +00001242 MachO::symtab_command S = getSymtabLoadCommand();
Rafael Espindola75c30362013-04-24 19:47:55 +00001243 unsigned SymbolTableEntrySize = is64Bit() ?
Charles Davis8bdfafd2013-09-01 04:28:48 +00001244 sizeof(MachO::nlist_64) :
1245 sizeof(MachO::nlist);
1246 uint64_t Offset = S.symoff + SymbolIdx * SymbolTableEntrySize;
Rafael Espindola75c30362013-04-24 19:47:55 +00001247 DataRefImpl Sym;
1248 Sym.p = reinterpret_cast<uintptr_t>(getPtr(this, Offset));
Rafael Espindola806f0062013-06-05 01:33:53 +00001249 return symbol_iterator(SymbolRef(Sym, this));
Rafael Espindola56f976f2013-04-18 18:08:55 +00001250}
1251
Keno Fischerc780e8e2015-05-21 21:24:32 +00001252section_iterator
1253MachOObjectFile::getRelocationSection(DataRefImpl Rel) const {
1254 return section_iterator(getAnyRelocationSection(getRelocation(Rel)));
1255}
1256
Rafael Espindola99c041b2015-06-30 01:53:01 +00001257uint64_t MachOObjectFile::getRelocationType(DataRefImpl Rel) const {
Charles Davis8bdfafd2013-09-01 04:28:48 +00001258 MachO::any_relocation_info RE = getRelocation(Rel);
Rafael Espindola99c041b2015-06-30 01:53:01 +00001259 return getAnyRelocationType(RE);
Rafael Espindola56f976f2013-04-18 18:08:55 +00001260}
1261
Rafael Espindola41bb4322015-06-30 04:08:37 +00001262void MachOObjectFile::getRelocationTypeName(
1263 DataRefImpl Rel, SmallVectorImpl<char> &Result) const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00001264 StringRef res;
Rafael Espindola99c041b2015-06-30 01:53:01 +00001265 uint64_t RType = getRelocationType(Rel);
Rafael Espindola56f976f2013-04-18 18:08:55 +00001266
1267 unsigned Arch = this->getArch();
1268
1269 switch (Arch) {
1270 case Triple::x86: {
1271 static const char *const Table[] = {
1272 "GENERIC_RELOC_VANILLA",
1273 "GENERIC_RELOC_PAIR",
1274 "GENERIC_RELOC_SECTDIFF",
1275 "GENERIC_RELOC_PB_LA_PTR",
1276 "GENERIC_RELOC_LOCAL_SECTDIFF",
1277 "GENERIC_RELOC_TLV" };
1278
Eric Christopher13250cb2013-12-06 02:33:38 +00001279 if (RType > 5)
Rafael Espindola56f976f2013-04-18 18:08:55 +00001280 res = "Unknown";
1281 else
1282 res = Table[RType];
1283 break;
1284 }
1285 case Triple::x86_64: {
1286 static const char *const Table[] = {
1287 "X86_64_RELOC_UNSIGNED",
1288 "X86_64_RELOC_SIGNED",
1289 "X86_64_RELOC_BRANCH",
1290 "X86_64_RELOC_GOT_LOAD",
1291 "X86_64_RELOC_GOT",
1292 "X86_64_RELOC_SUBTRACTOR",
1293 "X86_64_RELOC_SIGNED_1",
1294 "X86_64_RELOC_SIGNED_2",
1295 "X86_64_RELOC_SIGNED_4",
1296 "X86_64_RELOC_TLV" };
1297
1298 if (RType > 9)
1299 res = "Unknown";
1300 else
1301 res = Table[RType];
1302 break;
1303 }
1304 case Triple::arm: {
1305 static const char *const Table[] = {
1306 "ARM_RELOC_VANILLA",
1307 "ARM_RELOC_PAIR",
1308 "ARM_RELOC_SECTDIFF",
1309 "ARM_RELOC_LOCAL_SECTDIFF",
1310 "ARM_RELOC_PB_LA_PTR",
1311 "ARM_RELOC_BR24",
1312 "ARM_THUMB_RELOC_BR22",
1313 "ARM_THUMB_32BIT_BRANCH",
1314 "ARM_RELOC_HALF",
1315 "ARM_RELOC_HALF_SECTDIFF" };
1316
1317 if (RType > 9)
1318 res = "Unknown";
1319 else
1320 res = Table[RType];
1321 break;
1322 }
Tim Northover00ed9962014-03-29 10:18:08 +00001323 case Triple::aarch64: {
1324 static const char *const Table[] = {
1325 "ARM64_RELOC_UNSIGNED", "ARM64_RELOC_SUBTRACTOR",
1326 "ARM64_RELOC_BRANCH26", "ARM64_RELOC_PAGE21",
1327 "ARM64_RELOC_PAGEOFF12", "ARM64_RELOC_GOT_LOAD_PAGE21",
1328 "ARM64_RELOC_GOT_LOAD_PAGEOFF12", "ARM64_RELOC_POINTER_TO_GOT",
1329 "ARM64_RELOC_TLVP_LOAD_PAGE21", "ARM64_RELOC_TLVP_LOAD_PAGEOFF12",
1330 "ARM64_RELOC_ADDEND"
1331 };
1332
1333 if (RType >= array_lengthof(Table))
1334 res = "Unknown";
1335 else
1336 res = Table[RType];
1337 break;
1338 }
Rafael Espindola56f976f2013-04-18 18:08:55 +00001339 case Triple::ppc: {
1340 static const char *const Table[] = {
1341 "PPC_RELOC_VANILLA",
1342 "PPC_RELOC_PAIR",
1343 "PPC_RELOC_BR14",
1344 "PPC_RELOC_BR24",
1345 "PPC_RELOC_HI16",
1346 "PPC_RELOC_LO16",
1347 "PPC_RELOC_HA16",
1348 "PPC_RELOC_LO14",
1349 "PPC_RELOC_SECTDIFF",
1350 "PPC_RELOC_PB_LA_PTR",
1351 "PPC_RELOC_HI16_SECTDIFF",
1352 "PPC_RELOC_LO16_SECTDIFF",
1353 "PPC_RELOC_HA16_SECTDIFF",
1354 "PPC_RELOC_JBSR",
1355 "PPC_RELOC_LO14_SECTDIFF",
1356 "PPC_RELOC_LOCAL_SECTDIFF" };
1357
Eric Christopher13250cb2013-12-06 02:33:38 +00001358 if (RType > 15)
1359 res = "Unknown";
1360 else
1361 res = Table[RType];
Rafael Espindola56f976f2013-04-18 18:08:55 +00001362 break;
1363 }
1364 case Triple::UnknownArch:
1365 res = "Unknown";
1366 break;
1367 }
1368 Result.append(res.begin(), res.end());
Rafael Espindola56f976f2013-04-18 18:08:55 +00001369}
1370
Keno Fischer281b6942015-05-30 19:44:53 +00001371uint8_t MachOObjectFile::getRelocationLength(DataRefImpl Rel) const {
1372 MachO::any_relocation_info RE = getRelocation(Rel);
1373 return getAnyRelocationLength(RE);
1374}
1375
Kevin Enderby980b2582014-06-05 21:21:57 +00001376//
1377// guessLibraryShortName() is passed a name of a dynamic library and returns a
1378// guess on what the short name is. Then name is returned as a substring of the
1379// StringRef Name passed in. The name of the dynamic library is recognized as
1380// a framework if it has one of the two following forms:
1381// Foo.framework/Versions/A/Foo
1382// Foo.framework/Foo
1383// Where A and Foo can be any string. And may contain a trailing suffix
1384// starting with an underbar. If the Name is recognized as a framework then
1385// isFramework is set to true else it is set to false. If the Name has a
1386// suffix then Suffix is set to the substring in Name that contains the suffix
1387// else it is set to a NULL StringRef.
1388//
1389// The Name of the dynamic library is recognized as a library name if it has
1390// one of the two following forms:
1391// libFoo.A.dylib
1392// libFoo.dylib
1393// The library may have a suffix trailing the name Foo of the form:
1394// libFoo_profile.A.dylib
1395// libFoo_profile.dylib
1396//
1397// The Name of the dynamic library is also recognized as a library name if it
1398// has the following form:
1399// Foo.qtx
1400//
1401// If the Name of the dynamic library is none of the forms above then a NULL
1402// StringRef is returned.
1403//
1404StringRef MachOObjectFile::guessLibraryShortName(StringRef Name,
1405 bool &isFramework,
1406 StringRef &Suffix) {
1407 StringRef Foo, F, DotFramework, V, Dylib, Lib, Dot, Qtx;
1408 size_t a, b, c, d, Idx;
1409
1410 isFramework = false;
1411 Suffix = StringRef();
1412
1413 // Pull off the last component and make Foo point to it
1414 a = Name.rfind('/');
1415 if (a == Name.npos || a == 0)
1416 goto guess_library;
1417 Foo = Name.slice(a+1, Name.npos);
1418
1419 // Look for a suffix starting with a '_'
1420 Idx = Foo.rfind('_');
1421 if (Idx != Foo.npos && Foo.size() >= 2) {
1422 Suffix = Foo.slice(Idx, Foo.npos);
1423 Foo = Foo.slice(0, Idx);
1424 }
1425
1426 // First look for the form Foo.framework/Foo
1427 b = Name.rfind('/', a);
1428 if (b == Name.npos)
1429 Idx = 0;
1430 else
1431 Idx = b+1;
1432 F = Name.slice(Idx, Idx + Foo.size());
1433 DotFramework = Name.slice(Idx + Foo.size(),
1434 Idx + Foo.size() + sizeof(".framework/")-1);
1435 if (F == Foo && DotFramework == ".framework/") {
1436 isFramework = true;
1437 return Foo;
1438 }
1439
1440 // Next look for the form Foo.framework/Versions/A/Foo
1441 if (b == Name.npos)
1442 goto guess_library;
1443 c = Name.rfind('/', b);
1444 if (c == Name.npos || c == 0)
1445 goto guess_library;
1446 V = Name.slice(c+1, Name.npos);
1447 if (!V.startswith("Versions/"))
1448 goto guess_library;
1449 d = Name.rfind('/', c);
1450 if (d == Name.npos)
1451 Idx = 0;
1452 else
1453 Idx = d+1;
1454 F = Name.slice(Idx, Idx + Foo.size());
1455 DotFramework = Name.slice(Idx + Foo.size(),
1456 Idx + Foo.size() + sizeof(".framework/")-1);
1457 if (F == Foo && DotFramework == ".framework/") {
1458 isFramework = true;
1459 return Foo;
1460 }
1461
1462guess_library:
1463 // pull off the suffix after the "." and make a point to it
1464 a = Name.rfind('.');
1465 if (a == Name.npos || a == 0)
1466 return StringRef();
1467 Dylib = Name.slice(a, Name.npos);
1468 if (Dylib != ".dylib")
1469 goto guess_qtx;
1470
1471 // First pull off the version letter for the form Foo.A.dylib if any.
1472 if (a >= 3) {
1473 Dot = Name.slice(a-2, a-1);
1474 if (Dot == ".")
1475 a = a - 2;
1476 }
1477
1478 b = Name.rfind('/', a);
1479 if (b == Name.npos)
1480 b = 0;
1481 else
1482 b = b+1;
1483 // ignore any suffix after an underbar like Foo_profile.A.dylib
1484 Idx = Name.find('_', b);
1485 if (Idx != Name.npos && Idx != b) {
1486 Lib = Name.slice(b, Idx);
1487 Suffix = Name.slice(Idx, a);
1488 }
1489 else
1490 Lib = Name.slice(b, a);
1491 // There are incorrect library names of the form:
1492 // libATS.A_profile.dylib so check for these.
1493 if (Lib.size() >= 3) {
1494 Dot = Lib.slice(Lib.size()-2, Lib.size()-1);
1495 if (Dot == ".")
1496 Lib = Lib.slice(0, Lib.size()-2);
1497 }
1498 return Lib;
1499
1500guess_qtx:
1501 Qtx = Name.slice(a, Name.npos);
1502 if (Qtx != ".qtx")
1503 return StringRef();
1504 b = Name.rfind('/', a);
1505 if (b == Name.npos)
1506 Lib = Name.slice(0, a);
1507 else
1508 Lib = Name.slice(b+1, a);
1509 // There are library names of the form: QT.A.qtx so check for these.
1510 if (Lib.size() >= 3) {
1511 Dot = Lib.slice(Lib.size()-2, Lib.size()-1);
1512 if (Dot == ".")
1513 Lib = Lib.slice(0, Lib.size()-2);
1514 }
1515 return Lib;
1516}
1517
1518// getLibraryShortNameByIndex() is used to get the short name of the library
1519// for an undefined symbol in a linked Mach-O binary that was linked with the
1520// normal two-level namespace default (that is MH_TWOLEVEL in the header).
1521// It is passed the index (0 - based) of the library as translated from
1522// GET_LIBRARY_ORDINAL (1 - based).
Rafael Espindola3acea392014-06-12 21:46:39 +00001523std::error_code MachOObjectFile::getLibraryShortNameByIndex(unsigned Index,
Nick Kledzikd04bc352014-08-30 00:20:14 +00001524 StringRef &Res) const {
Kevin Enderby980b2582014-06-05 21:21:57 +00001525 if (Index >= Libraries.size())
1526 return object_error::parse_failed;
1527
Kevin Enderby980b2582014-06-05 21:21:57 +00001528 // If the cache of LibrariesShortNames is not built up do that first for
1529 // all the Libraries.
1530 if (LibrariesShortNames.size() == 0) {
1531 for (unsigned i = 0; i < Libraries.size(); i++) {
1532 MachO::dylib_command D =
1533 getStruct<MachO::dylib_command>(this, Libraries[i]);
Nick Kledzik30061302014-09-17 00:25:22 +00001534 if (D.dylib.name >= D.cmdsize)
1535 return object_error::parse_failed;
Kevin Enderby4eff6cd2014-06-20 18:07:34 +00001536 const char *P = (const char *)(Libraries[i]) + D.dylib.name;
Kevin Enderby980b2582014-06-05 21:21:57 +00001537 StringRef Name = StringRef(P);
Nick Kledzik30061302014-09-17 00:25:22 +00001538 if (D.dylib.name+Name.size() >= D.cmdsize)
1539 return object_error::parse_failed;
Kevin Enderby980b2582014-06-05 21:21:57 +00001540 StringRef Suffix;
1541 bool isFramework;
1542 StringRef shortName = guessLibraryShortName(Name, isFramework, Suffix);
Nick Kledzik30061302014-09-17 00:25:22 +00001543 if (shortName.empty())
Kevin Enderby980b2582014-06-05 21:21:57 +00001544 LibrariesShortNames.push_back(Name);
1545 else
1546 LibrariesShortNames.push_back(shortName);
1547 }
1548 }
1549
1550 Res = LibrariesShortNames[Index];
Rui Ueyama7d099192015-06-09 15:20:42 +00001551 return std::error_code();
Kevin Enderby980b2582014-06-05 21:21:57 +00001552}
1553
Rafael Espindola76ad2322015-07-06 14:55:37 +00001554section_iterator
1555MachOObjectFile::getRelocationRelocatedSection(relocation_iterator Rel) const {
1556 DataRefImpl Sec;
1557 Sec.d.a = Rel->getRawDataRefImpl().d.a;
1558 return section_iterator(SectionRef(Sec, this));
1559}
1560
Rafael Espindolaf12b8282014-02-21 20:10:59 +00001561basic_symbol_iterator MachOObjectFile::symbol_begin_impl() const {
Kevin Enderby1829c682016-01-22 22:49:55 +00001562 DataRefImpl DRI;
1563 MachO::symtab_command Symtab = getSymtabLoadCommand();
1564 if (!SymtabLoadCmd || Symtab.nsyms == 0)
1565 return basic_symbol_iterator(SymbolRef(DRI, this));
1566
Lang Hames36072da2014-05-12 21:39:59 +00001567 return getSymbolByIndex(0);
Rafael Espindola56f976f2013-04-18 18:08:55 +00001568}
1569
Rafael Espindolaf12b8282014-02-21 20:10:59 +00001570basic_symbol_iterator MachOObjectFile::symbol_end_impl() const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00001571 DataRefImpl DRI;
Kevin Enderby1829c682016-01-22 22:49:55 +00001572 MachO::symtab_command Symtab = getSymtabLoadCommand();
1573 if (!SymtabLoadCmd || Symtab.nsyms == 0)
Rafael Espindolaf12b8282014-02-21 20:10:59 +00001574 return basic_symbol_iterator(SymbolRef(DRI, this));
Rafael Espindola75c30362013-04-24 19:47:55 +00001575
Rafael Espindola75c30362013-04-24 19:47:55 +00001576 unsigned SymbolTableEntrySize = is64Bit() ?
Charles Davis8bdfafd2013-09-01 04:28:48 +00001577 sizeof(MachO::nlist_64) :
1578 sizeof(MachO::nlist);
1579 unsigned Offset = Symtab.symoff +
1580 Symtab.nsyms * SymbolTableEntrySize;
Rafael Espindola75c30362013-04-24 19:47:55 +00001581 DRI.p = reinterpret_cast<uintptr_t>(getPtr(this, Offset));
Rafael Espindolaf12b8282014-02-21 20:10:59 +00001582 return basic_symbol_iterator(SymbolRef(DRI, this));
Rafael Espindola56f976f2013-04-18 18:08:55 +00001583}
1584
Lang Hames36072da2014-05-12 21:39:59 +00001585basic_symbol_iterator MachOObjectFile::getSymbolByIndex(unsigned Index) const {
Lang Hames36072da2014-05-12 21:39:59 +00001586 MachO::symtab_command Symtab = getSymtabLoadCommand();
Kevin Enderby1829c682016-01-22 22:49:55 +00001587 if (!SymtabLoadCmd || Index >= Symtab.nsyms)
Filipe Cabecinhas40139502015-01-15 22:52:38 +00001588 report_fatal_error("Requested symbol index is out of range.");
Lang Hames36072da2014-05-12 21:39:59 +00001589 unsigned SymbolTableEntrySize =
1590 is64Bit() ? sizeof(MachO::nlist_64) : sizeof(MachO::nlist);
Kevin Enderby1829c682016-01-22 22:49:55 +00001591 DataRefImpl DRI;
Lang Hames36072da2014-05-12 21:39:59 +00001592 DRI.p = reinterpret_cast<uintptr_t>(getPtr(this, Symtab.symoff));
1593 DRI.p += Index * SymbolTableEntrySize;
1594 return basic_symbol_iterator(SymbolRef(DRI, this));
1595}
1596
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001597uint64_t MachOObjectFile::getSymbolIndex(DataRefImpl Symb) const {
1598 MachO::symtab_command Symtab = getSymtabLoadCommand();
1599 if (!SymtabLoadCmd)
1600 report_fatal_error("getSymbolIndex() called with no symbol table symbol");
1601 unsigned SymbolTableEntrySize =
1602 is64Bit() ? sizeof(MachO::nlist_64) : sizeof(MachO::nlist);
1603 DataRefImpl DRIstart;
1604 DRIstart.p = reinterpret_cast<uintptr_t>(getPtr(this, Symtab.symoff));
1605 uint64_t Index = (Symb.p - DRIstart.p) / SymbolTableEntrySize;
1606 return Index;
1607}
1608
Rafael Espindolab5155a52014-02-10 20:24:04 +00001609section_iterator MachOObjectFile::section_begin() const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00001610 DataRefImpl DRI;
1611 return section_iterator(SectionRef(DRI, this));
1612}
1613
Rafael Espindolab5155a52014-02-10 20:24:04 +00001614section_iterator MachOObjectFile::section_end() const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00001615 DataRefImpl DRI;
1616 DRI.d.a = Sections.size();
1617 return section_iterator(SectionRef(DRI, this));
1618}
1619
Rafael Espindola56f976f2013-04-18 18:08:55 +00001620uint8_t MachOObjectFile::getBytesInAddress() const {
Rafael Espindola60689982013-04-07 19:05:30 +00001621 return is64Bit() ? 8 : 4;
Eric Christopher7b015c72011-04-22 03:19:48 +00001622}
1623
Rafael Espindola56f976f2013-04-18 18:08:55 +00001624StringRef MachOObjectFile::getFileFormatName() const {
1625 unsigned CPUType = getCPUType(this);
1626 if (!is64Bit()) {
1627 switch (CPUType) {
Charles Davis74ec8b02013-08-27 05:00:13 +00001628 case llvm::MachO::CPU_TYPE_I386:
Rafael Espindola56f976f2013-04-18 18:08:55 +00001629 return "Mach-O 32-bit i386";
Charles Davis74ec8b02013-08-27 05:00:13 +00001630 case llvm::MachO::CPU_TYPE_ARM:
Rafael Espindola56f976f2013-04-18 18:08:55 +00001631 return "Mach-O arm";
Charles Davis74ec8b02013-08-27 05:00:13 +00001632 case llvm::MachO::CPU_TYPE_POWERPC:
Rafael Espindola56f976f2013-04-18 18:08:55 +00001633 return "Mach-O 32-bit ppc";
1634 default:
Rafael Espindola56f976f2013-04-18 18:08:55 +00001635 return "Mach-O 32-bit unknown";
1636 }
1637 }
1638
Rafael Espindola56f976f2013-04-18 18:08:55 +00001639 switch (CPUType) {
Charles Davis74ec8b02013-08-27 05:00:13 +00001640 case llvm::MachO::CPU_TYPE_X86_64:
Rafael Espindola56f976f2013-04-18 18:08:55 +00001641 return "Mach-O 64-bit x86-64";
Tim Northover00ed9962014-03-29 10:18:08 +00001642 case llvm::MachO::CPU_TYPE_ARM64:
1643 return "Mach-O arm64";
Charles Davis74ec8b02013-08-27 05:00:13 +00001644 case llvm::MachO::CPU_TYPE_POWERPC64:
Rafael Espindola56f976f2013-04-18 18:08:55 +00001645 return "Mach-O 64-bit ppc64";
1646 default:
1647 return "Mach-O 64-bit unknown";
1648 }
1649}
1650
Alexey Samsonove6388e62013-06-18 15:03:28 +00001651Triple::ArchType MachOObjectFile::getArch(uint32_t CPUType) {
1652 switch (CPUType) {
Charles Davis74ec8b02013-08-27 05:00:13 +00001653 case llvm::MachO::CPU_TYPE_I386:
Rafael Espindola56f976f2013-04-18 18:08:55 +00001654 return Triple::x86;
Charles Davis74ec8b02013-08-27 05:00:13 +00001655 case llvm::MachO::CPU_TYPE_X86_64:
Rafael Espindola56f976f2013-04-18 18:08:55 +00001656 return Triple::x86_64;
Charles Davis74ec8b02013-08-27 05:00:13 +00001657 case llvm::MachO::CPU_TYPE_ARM:
Rafael Espindola56f976f2013-04-18 18:08:55 +00001658 return Triple::arm;
Tim Northover00ed9962014-03-29 10:18:08 +00001659 case llvm::MachO::CPU_TYPE_ARM64:
Tim Northovere19bed72014-07-23 12:32:47 +00001660 return Triple::aarch64;
Charles Davis74ec8b02013-08-27 05:00:13 +00001661 case llvm::MachO::CPU_TYPE_POWERPC:
Rafael Espindola56f976f2013-04-18 18:08:55 +00001662 return Triple::ppc;
Charles Davis74ec8b02013-08-27 05:00:13 +00001663 case llvm::MachO::CPU_TYPE_POWERPC64:
Rafael Espindola56f976f2013-04-18 18:08:55 +00001664 return Triple::ppc64;
1665 default:
1666 return Triple::UnknownArch;
1667 }
1668}
1669
Tim Northover9e8eb412016-04-22 23:21:13 +00001670Triple MachOObjectFile::getArchTriple(uint32_t CPUType, uint32_t CPUSubType,
1671 const char **McpuDefault) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001672 if (McpuDefault)
1673 *McpuDefault = nullptr;
1674
Kevin Enderby4c8dfe42014-06-30 18:45:23 +00001675 switch (CPUType) {
1676 case MachO::CPU_TYPE_I386:
1677 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
1678 case MachO::CPU_SUBTYPE_I386_ALL:
1679 return Triple("i386-apple-darwin");
1680 default:
1681 return Triple();
1682 }
1683 case MachO::CPU_TYPE_X86_64:
1684 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
1685 case MachO::CPU_SUBTYPE_X86_64_ALL:
1686 return Triple("x86_64-apple-darwin");
1687 case MachO::CPU_SUBTYPE_X86_64_H:
1688 return Triple("x86_64h-apple-darwin");
1689 default:
1690 return Triple();
1691 }
1692 case MachO::CPU_TYPE_ARM:
1693 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
1694 case MachO::CPU_SUBTYPE_ARM_V4T:
1695 return Triple("armv4t-apple-darwin");
1696 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1697 return Triple("armv5e-apple-darwin");
Kevin Enderbyae2a9a22014-08-07 21:30:25 +00001698 case MachO::CPU_SUBTYPE_ARM_XSCALE:
1699 return Triple("xscale-apple-darwin");
Kevin Enderby4c8dfe42014-06-30 18:45:23 +00001700 case MachO::CPU_SUBTYPE_ARM_V6:
1701 return Triple("armv6-apple-darwin");
1702 case MachO::CPU_SUBTYPE_ARM_V6M:
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001703 if (McpuDefault)
1704 *McpuDefault = "cortex-m0";
Kevin Enderby4c8dfe42014-06-30 18:45:23 +00001705 return Triple("armv6m-apple-darwin");
Kevin Enderbyae2a9a22014-08-07 21:30:25 +00001706 case MachO::CPU_SUBTYPE_ARM_V7:
1707 return Triple("armv7-apple-darwin");
Kevin Enderby4c8dfe42014-06-30 18:45:23 +00001708 case MachO::CPU_SUBTYPE_ARM_V7EM:
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001709 if (McpuDefault)
1710 *McpuDefault = "cortex-m4";
Tim Northover9e8eb412016-04-22 23:21:13 +00001711 return Triple("thumbv7em-apple-darwin");
Kevin Enderby4c8dfe42014-06-30 18:45:23 +00001712 case MachO::CPU_SUBTYPE_ARM_V7K:
1713 return Triple("armv7k-apple-darwin");
1714 case MachO::CPU_SUBTYPE_ARM_V7M:
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001715 if (McpuDefault)
1716 *McpuDefault = "cortex-m3";
Tim Northover9e8eb412016-04-22 23:21:13 +00001717 return Triple("thumbv7m-apple-darwin");
Kevin Enderby4c8dfe42014-06-30 18:45:23 +00001718 case MachO::CPU_SUBTYPE_ARM_V7S:
1719 return Triple("armv7s-apple-darwin");
1720 default:
1721 return Triple();
1722 }
1723 case MachO::CPU_TYPE_ARM64:
1724 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
1725 case MachO::CPU_SUBTYPE_ARM64_ALL:
1726 return Triple("arm64-apple-darwin");
1727 default:
1728 return Triple();
1729 }
1730 case MachO::CPU_TYPE_POWERPC:
1731 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
1732 case MachO::CPU_SUBTYPE_POWERPC_ALL:
1733 return Triple("ppc-apple-darwin");
1734 default:
1735 return Triple();
1736 }
1737 case MachO::CPU_TYPE_POWERPC64:
Reid Kleckner4da3d572014-06-30 20:12:59 +00001738 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
Kevin Enderby4c8dfe42014-06-30 18:45:23 +00001739 case MachO::CPU_SUBTYPE_POWERPC_ALL:
1740 return Triple("ppc64-apple-darwin");
Kevin Enderby4c8dfe42014-06-30 18:45:23 +00001741 default:
1742 return Triple();
1743 }
1744 default:
1745 return Triple();
1746 }
1747}
1748
1749Triple MachOObjectFile::getHostArch() {
1750 return Triple(sys::getDefaultTargetTriple());
1751}
1752
Rafael Espindola72318b42014-08-08 16:30:17 +00001753bool MachOObjectFile::isValidArch(StringRef ArchFlag) {
1754 return StringSwitch<bool>(ArchFlag)
1755 .Case("i386", true)
1756 .Case("x86_64", true)
1757 .Case("x86_64h", true)
1758 .Case("armv4t", true)
1759 .Case("arm", true)
1760 .Case("armv5e", true)
1761 .Case("armv6", true)
1762 .Case("armv6m", true)
Frederic Riss40baa0a2015-06-16 17:37:03 +00001763 .Case("armv7", true)
Rafael Espindola72318b42014-08-08 16:30:17 +00001764 .Case("armv7em", true)
1765 .Case("armv7k", true)
1766 .Case("armv7m", true)
1767 .Case("armv7s", true)
1768 .Case("arm64", true)
1769 .Case("ppc", true)
1770 .Case("ppc64", true)
1771 .Default(false);
Kevin Enderby4c8dfe42014-06-30 18:45:23 +00001772}
1773
Alexey Samsonove6388e62013-06-18 15:03:28 +00001774unsigned MachOObjectFile::getArch() const {
1775 return getArch(getCPUType(this));
1776}
1777
Tim Northover9e8eb412016-04-22 23:21:13 +00001778Triple MachOObjectFile::getArchTriple(const char **McpuDefault) const {
1779 return getArchTriple(Header.cputype, Header.cpusubtype, McpuDefault);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001780}
1781
Rui Ueyamabc654b12013-09-27 21:47:05 +00001782relocation_iterator MachOObjectFile::section_rel_begin(unsigned Index) const {
Rafael Espindola6e040c02013-04-26 20:07:33 +00001783 DataRefImpl DRI;
1784 DRI.d.a = Index;
Rui Ueyamabc654b12013-09-27 21:47:05 +00001785 return section_rel_begin(DRI);
Rafael Espindola6e040c02013-04-26 20:07:33 +00001786}
1787
Rui Ueyamabc654b12013-09-27 21:47:05 +00001788relocation_iterator MachOObjectFile::section_rel_end(unsigned Index) const {
Rafael Espindola6e040c02013-04-26 20:07:33 +00001789 DataRefImpl DRI;
1790 DRI.d.a = Index;
Rui Ueyamabc654b12013-09-27 21:47:05 +00001791 return section_rel_end(DRI);
Rafael Espindola6e040c02013-04-26 20:07:33 +00001792}
1793
Kevin Enderby273ae012013-06-06 17:20:50 +00001794dice_iterator MachOObjectFile::begin_dices() const {
1795 DataRefImpl DRI;
1796 if (!DataInCodeLoadCmd)
1797 return dice_iterator(DiceRef(DRI, this));
1798
Charles Davis8bdfafd2013-09-01 04:28:48 +00001799 MachO::linkedit_data_command DicLC = getDataInCodeLoadCommand();
1800 DRI.p = reinterpret_cast<uintptr_t>(getPtr(this, DicLC.dataoff));
Kevin Enderby273ae012013-06-06 17:20:50 +00001801 return dice_iterator(DiceRef(DRI, this));
1802}
1803
1804dice_iterator MachOObjectFile::end_dices() const {
1805 DataRefImpl DRI;
1806 if (!DataInCodeLoadCmd)
1807 return dice_iterator(DiceRef(DRI, this));
1808
Charles Davis8bdfafd2013-09-01 04:28:48 +00001809 MachO::linkedit_data_command DicLC = getDataInCodeLoadCommand();
1810 unsigned Offset = DicLC.dataoff + DicLC.datasize;
Kevin Enderby273ae012013-06-06 17:20:50 +00001811 DRI.p = reinterpret_cast<uintptr_t>(getPtr(this, Offset));
1812 return dice_iterator(DiceRef(DRI, this));
1813}
1814
NAKAMURA Takumi70ad98a2015-09-22 11:13:55 +00001815ExportEntry::ExportEntry(ArrayRef<uint8_t> T)
1816 : Trie(T), Malformed(false), Done(false) {}
Nick Kledzikd04bc352014-08-30 00:20:14 +00001817
1818void ExportEntry::moveToFirst() {
1819 pushNode(0);
1820 pushDownUntilBottom();
1821}
1822
1823void ExportEntry::moveToEnd() {
1824 Stack.clear();
1825 Done = true;
1826}
1827
1828bool ExportEntry::operator==(const ExportEntry &Other) const {
NAKAMURA Takumi84965032015-09-22 11:14:12 +00001829 // Common case, one at end, other iterating from begin.
Nick Kledzikd04bc352014-08-30 00:20:14 +00001830 if (Done || Other.Done)
1831 return (Done == Other.Done);
1832 // Not equal if different stack sizes.
1833 if (Stack.size() != Other.Stack.size())
1834 return false;
1835 // Not equal if different cumulative strings.
Yaron Keren075759a2015-03-30 15:42:36 +00001836 if (!CumulativeString.equals(Other.CumulativeString))
Nick Kledzikd04bc352014-08-30 00:20:14 +00001837 return false;
1838 // Equal if all nodes in both stacks match.
1839 for (unsigned i=0; i < Stack.size(); ++i) {
1840 if (Stack[i].Start != Other.Stack[i].Start)
1841 return false;
1842 }
NAKAMURA Takumi10c80e72015-09-22 11:19:03 +00001843 return true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00001844}
1845
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00001846uint64_t ExportEntry::readULEB128(const uint8_t *&Ptr) {
1847 unsigned Count;
1848 uint64_t Result = decodeULEB128(Ptr, &Count);
1849 Ptr += Count;
1850 if (Ptr > Trie.end()) {
1851 Ptr = Trie.end();
Nick Kledzikd04bc352014-08-30 00:20:14 +00001852 Malformed = true;
1853 }
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00001854 return Result;
Nick Kledzikd04bc352014-08-30 00:20:14 +00001855}
1856
1857StringRef ExportEntry::name() const {
Yaron Keren075759a2015-03-30 15:42:36 +00001858 return CumulativeString;
Nick Kledzikd04bc352014-08-30 00:20:14 +00001859}
1860
1861uint64_t ExportEntry::flags() const {
1862 return Stack.back().Flags;
1863}
1864
1865uint64_t ExportEntry::address() const {
1866 return Stack.back().Address;
1867}
1868
1869uint64_t ExportEntry::other() const {
1870 return Stack.back().Other;
1871}
1872
1873StringRef ExportEntry::otherName() const {
1874 const char* ImportName = Stack.back().ImportName;
1875 if (ImportName)
1876 return StringRef(ImportName);
1877 return StringRef();
1878}
1879
1880uint32_t ExportEntry::nodeOffset() const {
1881 return Stack.back().Start - Trie.begin();
1882}
1883
NAKAMURA Takumi70ad98a2015-09-22 11:13:55 +00001884ExportEntry::NodeState::NodeState(const uint8_t *Ptr)
1885 : Start(Ptr), Current(Ptr), Flags(0), Address(0), Other(0),
1886 ImportName(nullptr), ChildCount(0), NextChildIndex(0),
1887 ParentStringLength(0), IsExportNode(false) {}
Nick Kledzikd04bc352014-08-30 00:20:14 +00001888
1889void ExportEntry::pushNode(uint64_t offset) {
1890 const uint8_t *Ptr = Trie.begin() + offset;
1891 NodeState State(Ptr);
1892 uint64_t ExportInfoSize = readULEB128(State.Current);
1893 State.IsExportNode = (ExportInfoSize != 0);
1894 const uint8_t* Children = State.Current + ExportInfoSize;
1895 if (State.IsExportNode) {
1896 State.Flags = readULEB128(State.Current);
1897 if (State.Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT) {
1898 State.Address = 0;
1899 State.Other = readULEB128(State.Current); // dylib ordinal
1900 State.ImportName = reinterpret_cast<const char*>(State.Current);
1901 } else {
1902 State.Address = readULEB128(State.Current);
Nick Kledzik1b591bd2014-08-30 01:57:34 +00001903 if (State.Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER)
NAKAMURA Takumi10c80e72015-09-22 11:19:03 +00001904 State.Other = readULEB128(State.Current);
Nick Kledzikd04bc352014-08-30 00:20:14 +00001905 }
1906 }
1907 State.ChildCount = *Children;
1908 State.Current = Children + 1;
1909 State.NextChildIndex = 0;
1910 State.ParentStringLength = CumulativeString.size();
1911 Stack.push_back(State);
1912}
1913
1914void ExportEntry::pushDownUntilBottom() {
1915 while (Stack.back().NextChildIndex < Stack.back().ChildCount) {
1916 NodeState &Top = Stack.back();
1917 CumulativeString.resize(Top.ParentStringLength);
1918 for (;*Top.Current != 0; Top.Current++) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00001919 char C = *Top.Current;
1920 CumulativeString.push_back(C);
Nick Kledzikd04bc352014-08-30 00:20:14 +00001921 }
1922 Top.Current += 1;
1923 uint64_t childNodeIndex = readULEB128(Top.Current);
1924 Top.NextChildIndex += 1;
1925 pushNode(childNodeIndex);
1926 }
1927 if (!Stack.back().IsExportNode) {
1928 Malformed = true;
1929 moveToEnd();
1930 }
1931}
1932
1933// We have a trie data structure and need a way to walk it that is compatible
1934// with the C++ iterator model. The solution is a non-recursive depth first
1935// traversal where the iterator contains a stack of parent nodes along with a
1936// string that is the accumulation of all edge strings along the parent chain
1937// to this point.
1938//
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00001939// There is one "export" node for each exported symbol. But because some
Nick Kledzikd04bc352014-08-30 00:20:14 +00001940// symbols may be a prefix of another symbol (e.g. _dup and _dup2), an export
NAKAMURA Takumi84965032015-09-22 11:14:12 +00001941// node may have child nodes too.
Nick Kledzikd04bc352014-08-30 00:20:14 +00001942//
1943// The algorithm for moveNext() is to keep moving down the leftmost unvisited
1944// child until hitting a node with no children (which is an export node or
1945// else the trie is malformed). On the way down, each node is pushed on the
1946// stack ivar. If there is no more ways down, it pops up one and tries to go
1947// down a sibling path until a childless node is reached.
1948void ExportEntry::moveNext() {
1949 if (Stack.empty() || !Stack.back().IsExportNode) {
1950 Malformed = true;
1951 moveToEnd();
1952 return;
1953 }
1954
1955 Stack.pop_back();
1956 while (!Stack.empty()) {
1957 NodeState &Top = Stack.back();
1958 if (Top.NextChildIndex < Top.ChildCount) {
1959 pushDownUntilBottom();
1960 // Now at the next export node.
1961 return;
1962 } else {
1963 if (Top.IsExportNode) {
1964 // This node has no children but is itself an export node.
1965 CumulativeString.resize(Top.ParentStringLength);
1966 return;
1967 }
1968 Stack.pop_back();
1969 }
1970 }
1971 Done = true;
1972}
1973
NAKAMURA Takumi10c80e72015-09-22 11:19:03 +00001974iterator_range<export_iterator>
Nick Kledzikd04bc352014-08-30 00:20:14 +00001975MachOObjectFile::exports(ArrayRef<uint8_t> Trie) {
1976 ExportEntry Start(Trie);
Juergen Ributzka4d7f70d2014-12-19 02:31:01 +00001977 if (Trie.size() == 0)
1978 Start.moveToEnd();
1979 else
1980 Start.moveToFirst();
Nick Kledzikd04bc352014-08-30 00:20:14 +00001981
1982 ExportEntry Finish(Trie);
1983 Finish.moveToEnd();
1984
Craig Topper15576e12015-12-06 05:08:07 +00001985 return make_range(export_iterator(Start), export_iterator(Finish));
Nick Kledzikd04bc352014-08-30 00:20:14 +00001986}
1987
1988iterator_range<export_iterator> MachOObjectFile::exports() const {
1989 return exports(getDyldInfoExportsTrie());
1990}
1991
Nick Kledzikac431442014-09-12 21:34:15 +00001992MachORebaseEntry::MachORebaseEntry(ArrayRef<uint8_t> Bytes, bool is64Bit)
1993 : Opcodes(Bytes), Ptr(Bytes.begin()), SegmentOffset(0), SegmentIndex(0),
1994 RemainingLoopCount(0), AdvanceAmount(0), RebaseType(0),
1995 PointerSize(is64Bit ? 8 : 4), Malformed(false), Done(false) {}
1996
1997void MachORebaseEntry::moveToFirst() {
1998 Ptr = Opcodes.begin();
1999 moveNext();
2000}
2001
2002void MachORebaseEntry::moveToEnd() {
2003 Ptr = Opcodes.end();
2004 RemainingLoopCount = 0;
2005 Done = true;
2006}
2007
2008void MachORebaseEntry::moveNext() {
2009 // If in the middle of some loop, move to next rebasing in loop.
2010 SegmentOffset += AdvanceAmount;
2011 if (RemainingLoopCount) {
2012 --RemainingLoopCount;
2013 return;
2014 }
2015 if (Ptr == Opcodes.end()) {
2016 Done = true;
2017 return;
2018 }
2019 bool More = true;
2020 while (More && !Malformed) {
2021 // Parse next opcode and set up next loop.
2022 uint8_t Byte = *Ptr++;
2023 uint8_t ImmValue = Byte & MachO::REBASE_IMMEDIATE_MASK;
2024 uint8_t Opcode = Byte & MachO::REBASE_OPCODE_MASK;
2025 switch (Opcode) {
2026 case MachO::REBASE_OPCODE_DONE:
2027 More = false;
2028 Done = true;
2029 moveToEnd();
2030 DEBUG_WITH_TYPE("mach-o-rebase", llvm::dbgs() << "REBASE_OPCODE_DONE\n");
2031 break;
2032 case MachO::REBASE_OPCODE_SET_TYPE_IMM:
2033 RebaseType = ImmValue;
2034 DEBUG_WITH_TYPE(
2035 "mach-o-rebase",
2036 llvm::dbgs() << "REBASE_OPCODE_SET_TYPE_IMM: "
2037 << "RebaseType=" << (int) RebaseType << "\n");
2038 break;
2039 case MachO::REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:
2040 SegmentIndex = ImmValue;
2041 SegmentOffset = readULEB128();
2042 DEBUG_WITH_TYPE(
2043 "mach-o-rebase",
2044 llvm::dbgs() << "REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: "
2045 << "SegmentIndex=" << SegmentIndex << ", "
2046 << format("SegmentOffset=0x%06X", SegmentOffset)
2047 << "\n");
2048 break;
2049 case MachO::REBASE_OPCODE_ADD_ADDR_ULEB:
2050 SegmentOffset += readULEB128();
2051 DEBUG_WITH_TYPE("mach-o-rebase",
2052 llvm::dbgs() << "REBASE_OPCODE_ADD_ADDR_ULEB: "
2053 << format("SegmentOffset=0x%06X",
2054 SegmentOffset) << "\n");
2055 break;
2056 case MachO::REBASE_OPCODE_ADD_ADDR_IMM_SCALED:
2057 SegmentOffset += ImmValue * PointerSize;
2058 DEBUG_WITH_TYPE("mach-o-rebase",
2059 llvm::dbgs() << "REBASE_OPCODE_ADD_ADDR_IMM_SCALED: "
2060 << format("SegmentOffset=0x%06X",
2061 SegmentOffset) << "\n");
2062 break;
2063 case MachO::REBASE_OPCODE_DO_REBASE_IMM_TIMES:
2064 AdvanceAmount = PointerSize;
2065 RemainingLoopCount = ImmValue - 1;
2066 DEBUG_WITH_TYPE(
2067 "mach-o-rebase",
2068 llvm::dbgs() << "REBASE_OPCODE_DO_REBASE_IMM_TIMES: "
2069 << format("SegmentOffset=0x%06X", SegmentOffset)
2070 << ", AdvanceAmount=" << AdvanceAmount
2071 << ", RemainingLoopCount=" << RemainingLoopCount
2072 << "\n");
2073 return;
2074 case MachO::REBASE_OPCODE_DO_REBASE_ULEB_TIMES:
2075 AdvanceAmount = PointerSize;
2076 RemainingLoopCount = readULEB128() - 1;
2077 DEBUG_WITH_TYPE(
2078 "mach-o-rebase",
2079 llvm::dbgs() << "REBASE_OPCODE_DO_REBASE_ULEB_TIMES: "
2080 << format("SegmentOffset=0x%06X", SegmentOffset)
2081 << ", AdvanceAmount=" << AdvanceAmount
2082 << ", RemainingLoopCount=" << RemainingLoopCount
2083 << "\n");
2084 return;
2085 case MachO::REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB:
2086 AdvanceAmount = readULEB128() + PointerSize;
2087 RemainingLoopCount = 0;
2088 DEBUG_WITH_TYPE(
2089 "mach-o-rebase",
2090 llvm::dbgs() << "REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB: "
2091 << format("SegmentOffset=0x%06X", SegmentOffset)
2092 << ", AdvanceAmount=" << AdvanceAmount
2093 << ", RemainingLoopCount=" << RemainingLoopCount
2094 << "\n");
2095 return;
2096 case MachO::REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB:
2097 RemainingLoopCount = readULEB128() - 1;
2098 AdvanceAmount = readULEB128() + PointerSize;
2099 DEBUG_WITH_TYPE(
2100 "mach-o-rebase",
2101 llvm::dbgs() << "REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB: "
2102 << format("SegmentOffset=0x%06X", SegmentOffset)
2103 << ", AdvanceAmount=" << AdvanceAmount
2104 << ", RemainingLoopCount=" << RemainingLoopCount
2105 << "\n");
2106 return;
2107 default:
2108 Malformed = true;
2109 }
2110 }
2111}
2112
2113uint64_t MachORebaseEntry::readULEB128() {
2114 unsigned Count;
2115 uint64_t Result = decodeULEB128(Ptr, &Count);
2116 Ptr += Count;
2117 if (Ptr > Opcodes.end()) {
2118 Ptr = Opcodes.end();
2119 Malformed = true;
2120 }
2121 return Result;
2122}
2123
2124uint32_t MachORebaseEntry::segmentIndex() const { return SegmentIndex; }
2125
2126uint64_t MachORebaseEntry::segmentOffset() const { return SegmentOffset; }
2127
2128StringRef MachORebaseEntry::typeName() const {
2129 switch (RebaseType) {
2130 case MachO::REBASE_TYPE_POINTER:
2131 return "pointer";
2132 case MachO::REBASE_TYPE_TEXT_ABSOLUTE32:
2133 return "text abs32";
2134 case MachO::REBASE_TYPE_TEXT_PCREL32:
2135 return "text rel32";
2136 }
2137 return "unknown";
2138}
2139
2140bool MachORebaseEntry::operator==(const MachORebaseEntry &Other) const {
2141 assert(Opcodes == Other.Opcodes && "compare iterators of different files");
2142 return (Ptr == Other.Ptr) &&
2143 (RemainingLoopCount == Other.RemainingLoopCount) &&
2144 (Done == Other.Done);
2145}
2146
2147iterator_range<rebase_iterator>
2148MachOObjectFile::rebaseTable(ArrayRef<uint8_t> Opcodes, bool is64) {
2149 MachORebaseEntry Start(Opcodes, is64);
2150 Start.moveToFirst();
2151
2152 MachORebaseEntry Finish(Opcodes, is64);
2153 Finish.moveToEnd();
2154
Craig Topper15576e12015-12-06 05:08:07 +00002155 return make_range(rebase_iterator(Start), rebase_iterator(Finish));
Nick Kledzikac431442014-09-12 21:34:15 +00002156}
2157
2158iterator_range<rebase_iterator> MachOObjectFile::rebaseTable() const {
2159 return rebaseTable(getDyldInfoRebaseOpcodes(), is64Bit());
2160}
2161
NAKAMURA Takumi70ad98a2015-09-22 11:13:55 +00002162MachOBindEntry::MachOBindEntry(ArrayRef<uint8_t> Bytes, bool is64Bit, Kind BK)
Nick Kledzik56ebef42014-09-16 01:41:51 +00002163 : Opcodes(Bytes), Ptr(Bytes.begin()), SegmentOffset(0), SegmentIndex(0),
2164 Ordinal(0), Flags(0), Addend(0), RemainingLoopCount(0), AdvanceAmount(0),
2165 BindType(0), PointerSize(is64Bit ? 8 : 4),
2166 TableKind(BK), Malformed(false), Done(false) {}
2167
2168void MachOBindEntry::moveToFirst() {
2169 Ptr = Opcodes.begin();
2170 moveNext();
2171}
2172
2173void MachOBindEntry::moveToEnd() {
2174 Ptr = Opcodes.end();
2175 RemainingLoopCount = 0;
2176 Done = true;
2177}
2178
2179void MachOBindEntry::moveNext() {
2180 // If in the middle of some loop, move to next binding in loop.
2181 SegmentOffset += AdvanceAmount;
2182 if (RemainingLoopCount) {
2183 --RemainingLoopCount;
2184 return;
2185 }
2186 if (Ptr == Opcodes.end()) {
2187 Done = true;
2188 return;
2189 }
2190 bool More = true;
2191 while (More && !Malformed) {
2192 // Parse next opcode and set up next loop.
2193 uint8_t Byte = *Ptr++;
2194 uint8_t ImmValue = Byte & MachO::BIND_IMMEDIATE_MASK;
2195 uint8_t Opcode = Byte & MachO::BIND_OPCODE_MASK;
2196 int8_t SignExtended;
2197 const uint8_t *SymStart;
2198 switch (Opcode) {
2199 case MachO::BIND_OPCODE_DONE:
2200 if (TableKind == Kind::Lazy) {
2201 // Lazying bindings have a DONE opcode between entries. Need to ignore
2202 // it to advance to next entry. But need not if this is last entry.
2203 bool NotLastEntry = false;
2204 for (const uint8_t *P = Ptr; P < Opcodes.end(); ++P) {
2205 if (*P) {
2206 NotLastEntry = true;
2207 }
2208 }
2209 if (NotLastEntry)
2210 break;
2211 }
2212 More = false;
2213 Done = true;
2214 moveToEnd();
2215 DEBUG_WITH_TYPE("mach-o-bind", llvm::dbgs() << "BIND_OPCODE_DONE\n");
2216 break;
2217 case MachO::BIND_OPCODE_SET_DYLIB_ORDINAL_IMM:
2218 Ordinal = ImmValue;
2219 DEBUG_WITH_TYPE(
2220 "mach-o-bind",
2221 llvm::dbgs() << "BIND_OPCODE_SET_DYLIB_ORDINAL_IMM: "
2222 << "Ordinal=" << Ordinal << "\n");
2223 break;
2224 case MachO::BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB:
2225 Ordinal = readULEB128();
2226 DEBUG_WITH_TYPE(
2227 "mach-o-bind",
2228 llvm::dbgs() << "BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB: "
2229 << "Ordinal=" << Ordinal << "\n");
2230 break;
2231 case MachO::BIND_OPCODE_SET_DYLIB_SPECIAL_IMM:
2232 if (ImmValue) {
2233 SignExtended = MachO::BIND_OPCODE_MASK | ImmValue;
2234 Ordinal = SignExtended;
2235 } else
2236 Ordinal = 0;
2237 DEBUG_WITH_TYPE(
2238 "mach-o-bind",
2239 llvm::dbgs() << "BIND_OPCODE_SET_DYLIB_SPECIAL_IMM: "
2240 << "Ordinal=" << Ordinal << "\n");
2241 break;
2242 case MachO::BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM:
2243 Flags = ImmValue;
2244 SymStart = Ptr;
2245 while (*Ptr) {
2246 ++Ptr;
2247 }
Nick Kledzik56ebef42014-09-16 01:41:51 +00002248 SymbolName = StringRef(reinterpret_cast<const char*>(SymStart),
2249 Ptr-SymStart);
Nick Kledzika6375362014-09-17 01:51:43 +00002250 ++Ptr;
Nick Kledzik56ebef42014-09-16 01:41:51 +00002251 DEBUG_WITH_TYPE(
2252 "mach-o-bind",
2253 llvm::dbgs() << "BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM: "
2254 << "SymbolName=" << SymbolName << "\n");
2255 if (TableKind == Kind::Weak) {
2256 if (ImmValue & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION)
2257 return;
2258 }
2259 break;
2260 case MachO::BIND_OPCODE_SET_TYPE_IMM:
2261 BindType = ImmValue;
2262 DEBUG_WITH_TYPE(
2263 "mach-o-bind",
2264 llvm::dbgs() << "BIND_OPCODE_SET_TYPE_IMM: "
2265 << "BindType=" << (int)BindType << "\n");
2266 break;
2267 case MachO::BIND_OPCODE_SET_ADDEND_SLEB:
2268 Addend = readSLEB128();
2269 if (TableKind == Kind::Lazy)
2270 Malformed = true;
2271 DEBUG_WITH_TYPE(
2272 "mach-o-bind",
2273 llvm::dbgs() << "BIND_OPCODE_SET_ADDEND_SLEB: "
2274 << "Addend=" << Addend << "\n");
2275 break;
2276 case MachO::BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:
2277 SegmentIndex = ImmValue;
2278 SegmentOffset = readULEB128();
2279 DEBUG_WITH_TYPE(
2280 "mach-o-bind",
2281 llvm::dbgs() << "BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: "
2282 << "SegmentIndex=" << SegmentIndex << ", "
2283 << format("SegmentOffset=0x%06X", SegmentOffset)
2284 << "\n");
2285 break;
2286 case MachO::BIND_OPCODE_ADD_ADDR_ULEB:
2287 SegmentOffset += readULEB128();
2288 DEBUG_WITH_TYPE("mach-o-bind",
2289 llvm::dbgs() << "BIND_OPCODE_ADD_ADDR_ULEB: "
2290 << format("SegmentOffset=0x%06X",
2291 SegmentOffset) << "\n");
2292 break;
2293 case MachO::BIND_OPCODE_DO_BIND:
2294 AdvanceAmount = PointerSize;
2295 RemainingLoopCount = 0;
2296 DEBUG_WITH_TYPE("mach-o-bind",
2297 llvm::dbgs() << "BIND_OPCODE_DO_BIND: "
2298 << format("SegmentOffset=0x%06X",
2299 SegmentOffset) << "\n");
2300 return;
2301 case MachO::BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB:
Nick Kledzik3b2aa052014-10-18 01:21:02 +00002302 AdvanceAmount = readULEB128() + PointerSize;
Nick Kledzik56ebef42014-09-16 01:41:51 +00002303 RemainingLoopCount = 0;
2304 if (TableKind == Kind::Lazy)
2305 Malformed = true;
2306 DEBUG_WITH_TYPE(
2307 "mach-o-bind",
Nick Kledzik3b2aa052014-10-18 01:21:02 +00002308 llvm::dbgs() << "BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB: "
Nick Kledzik56ebef42014-09-16 01:41:51 +00002309 << format("SegmentOffset=0x%06X", SegmentOffset)
2310 << ", AdvanceAmount=" << AdvanceAmount
2311 << ", RemainingLoopCount=" << RemainingLoopCount
2312 << "\n");
2313 return;
2314 case MachO::BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED:
Nick Kledzik3b2aa052014-10-18 01:21:02 +00002315 AdvanceAmount = ImmValue * PointerSize + PointerSize;
Nick Kledzik56ebef42014-09-16 01:41:51 +00002316 RemainingLoopCount = 0;
2317 if (TableKind == Kind::Lazy)
2318 Malformed = true;
2319 DEBUG_WITH_TYPE("mach-o-bind",
2320 llvm::dbgs()
2321 << "BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED: "
2322 << format("SegmentOffset=0x%06X",
2323 SegmentOffset) << "\n");
2324 return;
2325 case MachO::BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB:
2326 RemainingLoopCount = readULEB128() - 1;
2327 AdvanceAmount = readULEB128() + PointerSize;
2328 if (TableKind == Kind::Lazy)
2329 Malformed = true;
2330 DEBUG_WITH_TYPE(
2331 "mach-o-bind",
2332 llvm::dbgs() << "BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB: "
2333 << format("SegmentOffset=0x%06X", SegmentOffset)
2334 << ", AdvanceAmount=" << AdvanceAmount
2335 << ", RemainingLoopCount=" << RemainingLoopCount
2336 << "\n");
2337 return;
2338 default:
2339 Malformed = true;
2340 }
2341 }
2342}
2343
2344uint64_t MachOBindEntry::readULEB128() {
2345 unsigned Count;
2346 uint64_t Result = decodeULEB128(Ptr, &Count);
2347 Ptr += Count;
2348 if (Ptr > Opcodes.end()) {
2349 Ptr = Opcodes.end();
2350 Malformed = true;
2351 }
2352 return Result;
2353}
2354
2355int64_t MachOBindEntry::readSLEB128() {
2356 unsigned Count;
2357 int64_t Result = decodeSLEB128(Ptr, &Count);
2358 Ptr += Count;
2359 if (Ptr > Opcodes.end()) {
2360 Ptr = Opcodes.end();
2361 Malformed = true;
2362 }
2363 return Result;
2364}
2365
Nick Kledzik56ebef42014-09-16 01:41:51 +00002366uint32_t MachOBindEntry::segmentIndex() const { return SegmentIndex; }
2367
2368uint64_t MachOBindEntry::segmentOffset() const { return SegmentOffset; }
2369
2370StringRef MachOBindEntry::typeName() const {
2371 switch (BindType) {
2372 case MachO::BIND_TYPE_POINTER:
2373 return "pointer";
2374 case MachO::BIND_TYPE_TEXT_ABSOLUTE32:
2375 return "text abs32";
2376 case MachO::BIND_TYPE_TEXT_PCREL32:
2377 return "text rel32";
2378 }
2379 return "unknown";
2380}
2381
2382StringRef MachOBindEntry::symbolName() const { return SymbolName; }
2383
2384int64_t MachOBindEntry::addend() const { return Addend; }
2385
2386uint32_t MachOBindEntry::flags() const { return Flags; }
2387
2388int MachOBindEntry::ordinal() const { return Ordinal; }
2389
2390bool MachOBindEntry::operator==(const MachOBindEntry &Other) const {
2391 assert(Opcodes == Other.Opcodes && "compare iterators of different files");
2392 return (Ptr == Other.Ptr) &&
2393 (RemainingLoopCount == Other.RemainingLoopCount) &&
2394 (Done == Other.Done);
2395}
2396
2397iterator_range<bind_iterator>
2398MachOObjectFile::bindTable(ArrayRef<uint8_t> Opcodes, bool is64,
2399 MachOBindEntry::Kind BKind) {
2400 MachOBindEntry Start(Opcodes, is64, BKind);
2401 Start.moveToFirst();
2402
2403 MachOBindEntry Finish(Opcodes, is64, BKind);
2404 Finish.moveToEnd();
2405
Craig Topper15576e12015-12-06 05:08:07 +00002406 return make_range(bind_iterator(Start), bind_iterator(Finish));
Nick Kledzik56ebef42014-09-16 01:41:51 +00002407}
2408
2409iterator_range<bind_iterator> MachOObjectFile::bindTable() const {
2410 return bindTable(getDyldInfoBindOpcodes(), is64Bit(),
2411 MachOBindEntry::Kind::Regular);
2412}
2413
2414iterator_range<bind_iterator> MachOObjectFile::lazyBindTable() const {
2415 return bindTable(getDyldInfoLazyBindOpcodes(), is64Bit(),
2416 MachOBindEntry::Kind::Lazy);
2417}
2418
2419iterator_range<bind_iterator> MachOObjectFile::weakBindTable() const {
2420 return bindTable(getDyldInfoWeakBindOpcodes(), is64Bit(),
2421 MachOBindEntry::Kind::Weak);
2422}
2423
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002424MachOObjectFile::load_command_iterator
2425MachOObjectFile::begin_load_commands() const {
2426 return LoadCommands.begin();
2427}
2428
2429MachOObjectFile::load_command_iterator
2430MachOObjectFile::end_load_commands() const {
2431 return LoadCommands.end();
2432}
2433
2434iterator_range<MachOObjectFile::load_command_iterator>
2435MachOObjectFile::load_commands() const {
Craig Topper15576e12015-12-06 05:08:07 +00002436 return make_range(begin_load_commands(), end_load_commands());
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002437}
2438
Rafael Espindola56f976f2013-04-18 18:08:55 +00002439StringRef
2440MachOObjectFile::getSectionFinalSegmentName(DataRefImpl Sec) const {
2441 ArrayRef<char> Raw = getSectionRawFinalSegmentName(Sec);
2442 return parseSegmentOrSectionName(Raw.data());
2443}
2444
2445ArrayRef<char>
2446MachOObjectFile::getSectionRawName(DataRefImpl Sec) const {
Rafael Espindola0d85d102015-05-22 14:59:27 +00002447 assert(Sec.d.a < Sections.size() && "Should have detected this earlier");
Charles Davis8bdfafd2013-09-01 04:28:48 +00002448 const section_base *Base =
2449 reinterpret_cast<const section_base *>(Sections[Sec.d.a]);
Craig Toppere1d12942014-08-27 05:25:25 +00002450 return makeArrayRef(Base->sectname);
Rafael Espindola56f976f2013-04-18 18:08:55 +00002451}
2452
2453ArrayRef<char>
2454MachOObjectFile::getSectionRawFinalSegmentName(DataRefImpl Sec) const {
Rafael Espindola0d85d102015-05-22 14:59:27 +00002455 assert(Sec.d.a < Sections.size() && "Should have detected this earlier");
Charles Davis8bdfafd2013-09-01 04:28:48 +00002456 const section_base *Base =
2457 reinterpret_cast<const section_base *>(Sections[Sec.d.a]);
Craig Toppere1d12942014-08-27 05:25:25 +00002458 return makeArrayRef(Base->segname);
Rafael Espindola56f976f2013-04-18 18:08:55 +00002459}
2460
2461bool
Charles Davis8bdfafd2013-09-01 04:28:48 +00002462MachOObjectFile::isRelocationScattered(const MachO::any_relocation_info &RE)
Rafael Espindola56f976f2013-04-18 18:08:55 +00002463 const {
Charles Davis8bdfafd2013-09-01 04:28:48 +00002464 if (getCPUType(this) == MachO::CPU_TYPE_X86_64)
Rafael Espindola56f976f2013-04-18 18:08:55 +00002465 return false;
Charles Davis8bdfafd2013-09-01 04:28:48 +00002466 return getPlainRelocationAddress(RE) & MachO::R_SCATTERED;
Rafael Espindola56f976f2013-04-18 18:08:55 +00002467}
2468
Eric Christopher1d62c252013-07-22 22:25:07 +00002469unsigned MachOObjectFile::getPlainRelocationSymbolNum(
Charles Davis8bdfafd2013-09-01 04:28:48 +00002470 const MachO::any_relocation_info &RE) const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00002471 if (isLittleEndian())
Charles Davis8bdfafd2013-09-01 04:28:48 +00002472 return RE.r_word1 & 0xffffff;
2473 return RE.r_word1 >> 8;
Rafael Espindola56f976f2013-04-18 18:08:55 +00002474}
2475
Eric Christopher1d62c252013-07-22 22:25:07 +00002476bool MachOObjectFile::getPlainRelocationExternal(
Charles Davis8bdfafd2013-09-01 04:28:48 +00002477 const MachO::any_relocation_info &RE) const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00002478 if (isLittleEndian())
Charles Davis8bdfafd2013-09-01 04:28:48 +00002479 return (RE.r_word1 >> 27) & 1;
2480 return (RE.r_word1 >> 4) & 1;
Rafael Espindola56f976f2013-04-18 18:08:55 +00002481}
2482
Eric Christopher1d62c252013-07-22 22:25:07 +00002483bool MachOObjectFile::getScatteredRelocationScattered(
Charles Davis8bdfafd2013-09-01 04:28:48 +00002484 const MachO::any_relocation_info &RE) const {
2485 return RE.r_word0 >> 31;
Rafael Espindola56f976f2013-04-18 18:08:55 +00002486}
2487
Eric Christopher1d62c252013-07-22 22:25:07 +00002488uint32_t MachOObjectFile::getScatteredRelocationValue(
Charles Davis8bdfafd2013-09-01 04:28:48 +00002489 const MachO::any_relocation_info &RE) const {
2490 return RE.r_word1;
Rafael Espindola56f976f2013-04-18 18:08:55 +00002491}
2492
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002493uint32_t MachOObjectFile::getScatteredRelocationType(
2494 const MachO::any_relocation_info &RE) const {
2495 return (RE.r_word0 >> 24) & 0xf;
2496}
2497
Eric Christopher1d62c252013-07-22 22:25:07 +00002498unsigned MachOObjectFile::getAnyRelocationAddress(
Charles Davis8bdfafd2013-09-01 04:28:48 +00002499 const MachO::any_relocation_info &RE) const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00002500 if (isRelocationScattered(RE))
2501 return getScatteredRelocationAddress(RE);
2502 return getPlainRelocationAddress(RE);
2503}
2504
Charles Davis8bdfafd2013-09-01 04:28:48 +00002505unsigned MachOObjectFile::getAnyRelocationPCRel(
2506 const MachO::any_relocation_info &RE) const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00002507 if (isRelocationScattered(RE))
2508 return getScatteredRelocationPCRel(this, RE);
2509 return getPlainRelocationPCRel(this, RE);
2510}
2511
Eric Christopher1d62c252013-07-22 22:25:07 +00002512unsigned MachOObjectFile::getAnyRelocationLength(
Charles Davis8bdfafd2013-09-01 04:28:48 +00002513 const MachO::any_relocation_info &RE) const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00002514 if (isRelocationScattered(RE))
2515 return getScatteredRelocationLength(RE);
2516 return getPlainRelocationLength(this, RE);
2517}
2518
2519unsigned
Charles Davis8bdfafd2013-09-01 04:28:48 +00002520MachOObjectFile::getAnyRelocationType(
2521 const MachO::any_relocation_info &RE) const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00002522 if (isRelocationScattered(RE))
2523 return getScatteredRelocationType(RE);
2524 return getPlainRelocationType(this, RE);
2525}
2526
Rafael Espindola52501032013-04-30 15:40:54 +00002527SectionRef
Keno Fischerc780e8e2015-05-21 21:24:32 +00002528MachOObjectFile::getAnyRelocationSection(
Charles Davis8bdfafd2013-09-01 04:28:48 +00002529 const MachO::any_relocation_info &RE) const {
Rafael Espindola52501032013-04-30 15:40:54 +00002530 if (isRelocationScattered(RE) || getPlainRelocationExternal(RE))
Rafael Espindolab5155a52014-02-10 20:24:04 +00002531 return *section_end();
Rafael Espindola9ac06a02015-06-18 22:38:20 +00002532 unsigned SecNum = getPlainRelocationSymbolNum(RE);
2533 if (SecNum == MachO::R_ABS || SecNum > Sections.size())
2534 return *section_end();
Rafael Espindola52501032013-04-30 15:40:54 +00002535 DataRefImpl DRI;
Rafael Espindola9ac06a02015-06-18 22:38:20 +00002536 DRI.d.a = SecNum - 1;
Rafael Espindola52501032013-04-30 15:40:54 +00002537 return SectionRef(DRI, this);
2538}
2539
Charles Davis8bdfafd2013-09-01 04:28:48 +00002540MachO::section MachOObjectFile::getSection(DataRefImpl DRI) const {
Rafael Espindola62a07cb2015-05-22 15:43:00 +00002541 assert(DRI.d.a < Sections.size() && "Should have detected this earlier");
Charles Davis8bdfafd2013-09-01 04:28:48 +00002542 return getStruct<MachO::section>(this, Sections[DRI.d.a]);
Rafael Espindola56f976f2013-04-18 18:08:55 +00002543}
2544
Charles Davis8bdfafd2013-09-01 04:28:48 +00002545MachO::section_64 MachOObjectFile::getSection64(DataRefImpl DRI) const {
Rafael Espindola62a07cb2015-05-22 15:43:00 +00002546 assert(DRI.d.a < Sections.size() && "Should have detected this earlier");
Charles Davis8bdfafd2013-09-01 04:28:48 +00002547 return getStruct<MachO::section_64>(this, Sections[DRI.d.a]);
Rafael Espindola56f976f2013-04-18 18:08:55 +00002548}
2549
Charles Davis8bdfafd2013-09-01 04:28:48 +00002550MachO::section MachOObjectFile::getSection(const LoadCommandInfo &L,
Rafael Espindola6e040c02013-04-26 20:07:33 +00002551 unsigned Index) const {
2552 const char *Sec = getSectionPtr(this, L, Index);
Charles Davis8bdfafd2013-09-01 04:28:48 +00002553 return getStruct<MachO::section>(this, Sec);
Rafael Espindola6e040c02013-04-26 20:07:33 +00002554}
2555
Charles Davis8bdfafd2013-09-01 04:28:48 +00002556MachO::section_64 MachOObjectFile::getSection64(const LoadCommandInfo &L,
2557 unsigned Index) const {
Rafael Espindola6e040c02013-04-26 20:07:33 +00002558 const char *Sec = getSectionPtr(this, L, Index);
Charles Davis8bdfafd2013-09-01 04:28:48 +00002559 return getStruct<MachO::section_64>(this, Sec);
Rafael Espindola6e040c02013-04-26 20:07:33 +00002560}
2561
Charles Davis8bdfafd2013-09-01 04:28:48 +00002562MachO::nlist
Rafael Espindola56f976f2013-04-18 18:08:55 +00002563MachOObjectFile::getSymbolTableEntry(DataRefImpl DRI) const {
Rafael Espindola75c30362013-04-24 19:47:55 +00002564 const char *P = reinterpret_cast<const char *>(DRI.p);
Charles Davis8bdfafd2013-09-01 04:28:48 +00002565 return getStruct<MachO::nlist>(this, P);
Rafael Espindola56f976f2013-04-18 18:08:55 +00002566}
2567
Charles Davis8bdfafd2013-09-01 04:28:48 +00002568MachO::nlist_64
Rafael Espindola56f976f2013-04-18 18:08:55 +00002569MachOObjectFile::getSymbol64TableEntry(DataRefImpl DRI) const {
Rafael Espindola75c30362013-04-24 19:47:55 +00002570 const char *P = reinterpret_cast<const char *>(DRI.p);
Charles Davis8bdfafd2013-09-01 04:28:48 +00002571 return getStruct<MachO::nlist_64>(this, P);
Rafael Espindola56f976f2013-04-18 18:08:55 +00002572}
2573
Charles Davis8bdfafd2013-09-01 04:28:48 +00002574MachO::linkedit_data_command
2575MachOObjectFile::getLinkeditDataLoadCommand(const LoadCommandInfo &L) const {
2576 return getStruct<MachO::linkedit_data_command>(this, L.Ptr);
Rafael Espindola56f976f2013-04-18 18:08:55 +00002577}
2578
Charles Davis8bdfafd2013-09-01 04:28:48 +00002579MachO::segment_command
Rafael Espindola6e040c02013-04-26 20:07:33 +00002580MachOObjectFile::getSegmentLoadCommand(const LoadCommandInfo &L) const {
Charles Davis8bdfafd2013-09-01 04:28:48 +00002581 return getStruct<MachO::segment_command>(this, L.Ptr);
Rafael Espindola6e040c02013-04-26 20:07:33 +00002582}
2583
Charles Davis8bdfafd2013-09-01 04:28:48 +00002584MachO::segment_command_64
Rafael Espindola6e040c02013-04-26 20:07:33 +00002585MachOObjectFile::getSegment64LoadCommand(const LoadCommandInfo &L) const {
Charles Davis8bdfafd2013-09-01 04:28:48 +00002586 return getStruct<MachO::segment_command_64>(this, L.Ptr);
Rafael Espindola6e040c02013-04-26 20:07:33 +00002587}
2588
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00002589MachO::linker_option_command
2590MachOObjectFile::getLinkerOptionLoadCommand(const LoadCommandInfo &L) const {
2591 return getStruct<MachO::linker_option_command>(this, L.Ptr);
Rafael Espindola6e040c02013-04-26 20:07:33 +00002592}
2593
Jim Grosbach448334a2014-03-18 22:09:05 +00002594MachO::version_min_command
2595MachOObjectFile::getVersionMinLoadCommand(const LoadCommandInfo &L) const {
2596 return getStruct<MachO::version_min_command>(this, L.Ptr);
2597}
2598
Tim Northover8f9590b2014-06-30 14:40:57 +00002599MachO::dylib_command
2600MachOObjectFile::getDylibIDLoadCommand(const LoadCommandInfo &L) const {
2601 return getStruct<MachO::dylib_command>(this, L.Ptr);
2602}
2603
Kevin Enderby8ae63c12014-09-04 16:54:47 +00002604MachO::dyld_info_command
2605MachOObjectFile::getDyldInfoLoadCommand(const LoadCommandInfo &L) const {
2606 return getStruct<MachO::dyld_info_command>(this, L.Ptr);
2607}
2608
2609MachO::dylinker_command
2610MachOObjectFile::getDylinkerCommand(const LoadCommandInfo &L) const {
2611 return getStruct<MachO::dylinker_command>(this, L.Ptr);
2612}
2613
2614MachO::uuid_command
2615MachOObjectFile::getUuidCommand(const LoadCommandInfo &L) const {
2616 return getStruct<MachO::uuid_command>(this, L.Ptr);
2617}
2618
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00002619MachO::rpath_command
2620MachOObjectFile::getRpathCommand(const LoadCommandInfo &L) const {
2621 return getStruct<MachO::rpath_command>(this, L.Ptr);
2622}
2623
Kevin Enderby8ae63c12014-09-04 16:54:47 +00002624MachO::source_version_command
2625MachOObjectFile::getSourceVersionCommand(const LoadCommandInfo &L) const {
2626 return getStruct<MachO::source_version_command>(this, L.Ptr);
2627}
2628
2629MachO::entry_point_command
2630MachOObjectFile::getEntryPointCommand(const LoadCommandInfo &L) const {
2631 return getStruct<MachO::entry_point_command>(this, L.Ptr);
2632}
2633
Kevin Enderby0804f4672014-12-16 23:25:52 +00002634MachO::encryption_info_command
2635MachOObjectFile::getEncryptionInfoCommand(const LoadCommandInfo &L) const {
2636 return getStruct<MachO::encryption_info_command>(this, L.Ptr);
2637}
2638
Kevin Enderby57538292014-12-17 01:01:30 +00002639MachO::encryption_info_command_64
2640MachOObjectFile::getEncryptionInfoCommand64(const LoadCommandInfo &L) const {
2641 return getStruct<MachO::encryption_info_command_64>(this, L.Ptr);
2642}
2643
Kevin Enderbyb4b79312014-12-18 19:24:35 +00002644MachO::sub_framework_command
2645MachOObjectFile::getSubFrameworkCommand(const LoadCommandInfo &L) const {
2646 return getStruct<MachO::sub_framework_command>(this, L.Ptr);
2647}
Tim Northover8f9590b2014-06-30 14:40:57 +00002648
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00002649MachO::sub_umbrella_command
2650MachOObjectFile::getSubUmbrellaCommand(const LoadCommandInfo &L) const {
2651 return getStruct<MachO::sub_umbrella_command>(this, L.Ptr);
2652}
2653
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00002654MachO::sub_library_command
2655MachOObjectFile::getSubLibraryCommand(const LoadCommandInfo &L) const {
2656 return getStruct<MachO::sub_library_command>(this, L.Ptr);
2657}
2658
Kevin Enderby186eac32014-12-19 21:06:24 +00002659MachO::sub_client_command
2660MachOObjectFile::getSubClientCommand(const LoadCommandInfo &L) const {
2661 return getStruct<MachO::sub_client_command>(this, L.Ptr);
2662}
2663
Kevin Enderby52e4ce42014-12-19 22:25:22 +00002664MachO::routines_command
2665MachOObjectFile::getRoutinesCommand(const LoadCommandInfo &L) const {
2666 return getStruct<MachO::routines_command>(this, L.Ptr);
2667}
2668
2669MachO::routines_command_64
2670MachOObjectFile::getRoutinesCommand64(const LoadCommandInfo &L) const {
2671 return getStruct<MachO::routines_command_64>(this, L.Ptr);
2672}
2673
Kevin Enderby48ef5342014-12-23 22:56:39 +00002674MachO::thread_command
2675MachOObjectFile::getThreadCommand(const LoadCommandInfo &L) const {
2676 return getStruct<MachO::thread_command>(this, L.Ptr);
2677}
2678
Charles Davis8bdfafd2013-09-01 04:28:48 +00002679MachO::any_relocation_info
Rafael Espindola56f976f2013-04-18 18:08:55 +00002680MachOObjectFile::getRelocation(DataRefImpl Rel) const {
Rafael Espindola128b8112014-04-03 23:51:28 +00002681 DataRefImpl Sec;
2682 Sec.d.a = Rel.d.a;
2683 uint32_t Offset;
2684 if (is64Bit()) {
2685 MachO::section_64 Sect = getSection64(Sec);
2686 Offset = Sect.reloff;
2687 } else {
2688 MachO::section Sect = getSection(Sec);
2689 Offset = Sect.reloff;
2690 }
2691
2692 auto P = reinterpret_cast<const MachO::any_relocation_info *>(
2693 getPtr(this, Offset)) + Rel.d.b;
2694 return getStruct<MachO::any_relocation_info>(
2695 this, reinterpret_cast<const char *>(P));
Rafael Espindola56f976f2013-04-18 18:08:55 +00002696}
2697
Charles Davis8bdfafd2013-09-01 04:28:48 +00002698MachO::data_in_code_entry
Kevin Enderby273ae012013-06-06 17:20:50 +00002699MachOObjectFile::getDice(DataRefImpl Rel) const {
2700 const char *P = reinterpret_cast<const char *>(Rel.p);
Charles Davis8bdfafd2013-09-01 04:28:48 +00002701 return getStruct<MachO::data_in_code_entry>(this, P);
Kevin Enderby273ae012013-06-06 17:20:50 +00002702}
2703
Alexey Samsonov13415ed2015-06-04 19:22:03 +00002704const MachO::mach_header &MachOObjectFile::getHeader() const {
Alexey Samsonovfa5edc52015-06-04 22:49:55 +00002705 return Header;
Rafael Espindola56f976f2013-04-18 18:08:55 +00002706}
2707
Alexey Samsonov13415ed2015-06-04 19:22:03 +00002708const MachO::mach_header_64 &MachOObjectFile::getHeader64() const {
2709 assert(is64Bit());
2710 return Header64;
Rafael Espindola6e040c02013-04-26 20:07:33 +00002711}
2712
Charles Davis8bdfafd2013-09-01 04:28:48 +00002713uint32_t MachOObjectFile::getIndirectSymbolTableEntry(
2714 const MachO::dysymtab_command &DLC,
2715 unsigned Index) const {
2716 uint64_t Offset = DLC.indirectsymoff + Index * sizeof(uint32_t);
2717 return getStruct<uint32_t>(this, getPtr(this, Offset));
Rafael Espindola6e040c02013-04-26 20:07:33 +00002718}
2719
Charles Davis8bdfafd2013-09-01 04:28:48 +00002720MachO::data_in_code_entry
Rafael Espindola6e040c02013-04-26 20:07:33 +00002721MachOObjectFile::getDataInCodeTableEntry(uint32_t DataOffset,
2722 unsigned Index) const {
Charles Davis8bdfafd2013-09-01 04:28:48 +00002723 uint64_t Offset = DataOffset + Index * sizeof(MachO::data_in_code_entry);
2724 return getStruct<MachO::data_in_code_entry>(this, getPtr(this, Offset));
Rafael Espindola6e040c02013-04-26 20:07:33 +00002725}
2726
Charles Davis8bdfafd2013-09-01 04:28:48 +00002727MachO::symtab_command MachOObjectFile::getSymtabLoadCommand() const {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002728 if (SymtabLoadCmd)
2729 return getStruct<MachO::symtab_command>(this, SymtabLoadCmd);
2730
2731 // If there is no SymtabLoadCmd return a load command with zero'ed fields.
2732 MachO::symtab_command Cmd;
2733 Cmd.cmd = MachO::LC_SYMTAB;
2734 Cmd.cmdsize = sizeof(MachO::symtab_command);
2735 Cmd.symoff = 0;
2736 Cmd.nsyms = 0;
2737 Cmd.stroff = 0;
2738 Cmd.strsize = 0;
2739 return Cmd;
Rafael Espindola56f976f2013-04-18 18:08:55 +00002740}
2741
Charles Davis8bdfafd2013-09-01 04:28:48 +00002742MachO::dysymtab_command MachOObjectFile::getDysymtabLoadCommand() const {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002743 if (DysymtabLoadCmd)
2744 return getStruct<MachO::dysymtab_command>(this, DysymtabLoadCmd);
2745
2746 // If there is no DysymtabLoadCmd return a load command with zero'ed fields.
2747 MachO::dysymtab_command Cmd;
2748 Cmd.cmd = MachO::LC_DYSYMTAB;
2749 Cmd.cmdsize = sizeof(MachO::dysymtab_command);
2750 Cmd.ilocalsym = 0;
2751 Cmd.nlocalsym = 0;
2752 Cmd.iextdefsym = 0;
2753 Cmd.nextdefsym = 0;
2754 Cmd.iundefsym = 0;
2755 Cmd.nundefsym = 0;
2756 Cmd.tocoff = 0;
2757 Cmd.ntoc = 0;
2758 Cmd.modtaboff = 0;
2759 Cmd.nmodtab = 0;
2760 Cmd.extrefsymoff = 0;
2761 Cmd.nextrefsyms = 0;
2762 Cmd.indirectsymoff = 0;
2763 Cmd.nindirectsyms = 0;
2764 Cmd.extreloff = 0;
2765 Cmd.nextrel = 0;
2766 Cmd.locreloff = 0;
2767 Cmd.nlocrel = 0;
2768 return Cmd;
Rafael Espindola6e040c02013-04-26 20:07:33 +00002769}
2770
Charles Davis8bdfafd2013-09-01 04:28:48 +00002771MachO::linkedit_data_command
Kevin Enderby273ae012013-06-06 17:20:50 +00002772MachOObjectFile::getDataInCodeLoadCommand() const {
2773 if (DataInCodeLoadCmd)
Charles Davis8bdfafd2013-09-01 04:28:48 +00002774 return getStruct<MachO::linkedit_data_command>(this, DataInCodeLoadCmd);
Kevin Enderby273ae012013-06-06 17:20:50 +00002775
2776 // If there is no DataInCodeLoadCmd return a load command with zero'ed fields.
Charles Davis8bdfafd2013-09-01 04:28:48 +00002777 MachO::linkedit_data_command Cmd;
2778 Cmd.cmd = MachO::LC_DATA_IN_CODE;
2779 Cmd.cmdsize = sizeof(MachO::linkedit_data_command);
2780 Cmd.dataoff = 0;
2781 Cmd.datasize = 0;
Kevin Enderby273ae012013-06-06 17:20:50 +00002782 return Cmd;
2783}
2784
Kevin Enderby9a509442015-01-27 21:28:24 +00002785MachO::linkedit_data_command
2786MachOObjectFile::getLinkOptHintsLoadCommand() const {
2787 if (LinkOptHintsLoadCmd)
2788 return getStruct<MachO::linkedit_data_command>(this, LinkOptHintsLoadCmd);
2789
2790 // If there is no LinkOptHintsLoadCmd return a load command with zero'ed
2791 // fields.
2792 MachO::linkedit_data_command Cmd;
2793 Cmd.cmd = MachO::LC_LINKER_OPTIMIZATION_HINT;
2794 Cmd.cmdsize = sizeof(MachO::linkedit_data_command);
2795 Cmd.dataoff = 0;
2796 Cmd.datasize = 0;
2797 return Cmd;
2798}
2799
Nick Kledzikd04bc352014-08-30 00:20:14 +00002800ArrayRef<uint8_t> MachOObjectFile::getDyldInfoRebaseOpcodes() const {
NAKAMURA Takumi10c80e72015-09-22 11:19:03 +00002801 if (!DyldInfoLoadCmd)
Craig Topper0013be12015-09-21 05:32:41 +00002802 return None;
Nick Kledzikd04bc352014-08-30 00:20:14 +00002803
NAKAMURA Takumi70ad98a2015-09-22 11:13:55 +00002804 MachO::dyld_info_command DyldInfo =
2805 getStruct<MachO::dyld_info_command>(this, DyldInfoLoadCmd);
2806 const uint8_t *Ptr =
2807 reinterpret_cast<const uint8_t *>(getPtr(this, DyldInfo.rebase_off));
Craig Topper0013be12015-09-21 05:32:41 +00002808 return makeArrayRef(Ptr, DyldInfo.rebase_size);
Nick Kledzikd04bc352014-08-30 00:20:14 +00002809}
2810
2811ArrayRef<uint8_t> MachOObjectFile::getDyldInfoBindOpcodes() const {
NAKAMURA Takumi10c80e72015-09-22 11:19:03 +00002812 if (!DyldInfoLoadCmd)
Craig Topper0013be12015-09-21 05:32:41 +00002813 return None;
Nick Kledzikd04bc352014-08-30 00:20:14 +00002814
NAKAMURA Takumi70ad98a2015-09-22 11:13:55 +00002815 MachO::dyld_info_command DyldInfo =
2816 getStruct<MachO::dyld_info_command>(this, DyldInfoLoadCmd);
2817 const uint8_t *Ptr =
2818 reinterpret_cast<const uint8_t *>(getPtr(this, DyldInfo.bind_off));
Craig Topper0013be12015-09-21 05:32:41 +00002819 return makeArrayRef(Ptr, DyldInfo.bind_size);
Nick Kledzikd04bc352014-08-30 00:20:14 +00002820}
2821
2822ArrayRef<uint8_t> MachOObjectFile::getDyldInfoWeakBindOpcodes() const {
NAKAMURA Takumi10c80e72015-09-22 11:19:03 +00002823 if (!DyldInfoLoadCmd)
Craig Topper0013be12015-09-21 05:32:41 +00002824 return None;
Nick Kledzikd04bc352014-08-30 00:20:14 +00002825
NAKAMURA Takumi70ad98a2015-09-22 11:13:55 +00002826 MachO::dyld_info_command DyldInfo =
2827 getStruct<MachO::dyld_info_command>(this, DyldInfoLoadCmd);
2828 const uint8_t *Ptr =
2829 reinterpret_cast<const uint8_t *>(getPtr(this, DyldInfo.weak_bind_off));
Craig Topper0013be12015-09-21 05:32:41 +00002830 return makeArrayRef(Ptr, DyldInfo.weak_bind_size);
Nick Kledzikd04bc352014-08-30 00:20:14 +00002831}
2832
2833ArrayRef<uint8_t> MachOObjectFile::getDyldInfoLazyBindOpcodes() const {
NAKAMURA Takumi10c80e72015-09-22 11:19:03 +00002834 if (!DyldInfoLoadCmd)
Craig Topper0013be12015-09-21 05:32:41 +00002835 return None;
Nick Kledzikd04bc352014-08-30 00:20:14 +00002836
NAKAMURA Takumi70ad98a2015-09-22 11:13:55 +00002837 MachO::dyld_info_command DyldInfo =
2838 getStruct<MachO::dyld_info_command>(this, DyldInfoLoadCmd);
2839 const uint8_t *Ptr =
2840 reinterpret_cast<const uint8_t *>(getPtr(this, DyldInfo.lazy_bind_off));
Craig Topper0013be12015-09-21 05:32:41 +00002841 return makeArrayRef(Ptr, DyldInfo.lazy_bind_size);
Nick Kledzikd04bc352014-08-30 00:20:14 +00002842}
2843
2844ArrayRef<uint8_t> MachOObjectFile::getDyldInfoExportsTrie() const {
NAKAMURA Takumi10c80e72015-09-22 11:19:03 +00002845 if (!DyldInfoLoadCmd)
Craig Topper0013be12015-09-21 05:32:41 +00002846 return None;
Nick Kledzikd04bc352014-08-30 00:20:14 +00002847
NAKAMURA Takumi70ad98a2015-09-22 11:13:55 +00002848 MachO::dyld_info_command DyldInfo =
2849 getStruct<MachO::dyld_info_command>(this, DyldInfoLoadCmd);
2850 const uint8_t *Ptr =
2851 reinterpret_cast<const uint8_t *>(getPtr(this, DyldInfo.export_off));
Craig Topper0013be12015-09-21 05:32:41 +00002852 return makeArrayRef(Ptr, DyldInfo.export_size);
Nick Kledzikd04bc352014-08-30 00:20:14 +00002853}
2854
Alexander Potapenko6909b5b2014-10-15 23:35:45 +00002855ArrayRef<uint8_t> MachOObjectFile::getUuid() const {
2856 if (!UuidLoadCmd)
Craig Topper0013be12015-09-21 05:32:41 +00002857 return None;
Benjamin Kramer014601d2014-10-24 15:52:05 +00002858 // Returning a pointer is fine as uuid doesn't need endian swapping.
2859 const char *Ptr = UuidLoadCmd + offsetof(MachO::uuid_command, uuid);
Craig Topper0013be12015-09-21 05:32:41 +00002860 return makeArrayRef(reinterpret_cast<const uint8_t *>(Ptr), 16);
Alexander Potapenko6909b5b2014-10-15 23:35:45 +00002861}
Nick Kledzikd04bc352014-08-30 00:20:14 +00002862
Rafael Espindola6e040c02013-04-26 20:07:33 +00002863StringRef MachOObjectFile::getStringTableData() const {
Charles Davis8bdfafd2013-09-01 04:28:48 +00002864 MachO::symtab_command S = getSymtabLoadCommand();
2865 return getData().substr(S.stroff, S.strsize);
Rafael Espindola6e040c02013-04-26 20:07:33 +00002866}
2867
Rafael Espindola56f976f2013-04-18 18:08:55 +00002868bool MachOObjectFile::is64Bit() const {
2869 return getType() == getMachOType(false, true) ||
Lang Hames84bc8182014-07-15 19:35:22 +00002870 getType() == getMachOType(true, true);
Rafael Espindola56f976f2013-04-18 18:08:55 +00002871}
2872
2873void MachOObjectFile::ReadULEB128s(uint64_t Index,
2874 SmallVectorImpl<uint64_t> &Out) const {
2875 DataExtractor extractor(ObjectFile::getData(), true, 0);
2876
2877 uint32_t offset = Index;
2878 uint64_t data = 0;
2879 while (uint64_t delta = extractor.getULEB128(&offset)) {
2880 data += delta;
2881 Out.push_back(data);
2882 }
2883}
2884
Rafael Espindolac66d7612014-08-17 19:09:37 +00002885bool MachOObjectFile::isRelocatableObject() const {
2886 return getHeader().filetype == MachO::MH_OBJECT;
2887}
2888
Lang Hamesff044b12016-03-25 23:11:52 +00002889Expected<std::unique_ptr<MachOObjectFile>>
Rafael Espindola48af1c22014-08-19 18:44:46 +00002890ObjectFile::createMachOObjectFile(MemoryBufferRef Buffer) {
2891 StringRef Magic = Buffer.getBuffer().slice(0, 4);
Lang Hames82627642016-03-25 21:59:14 +00002892 if (Magic == "\xFE\xED\xFA\xCE")
Lang Hamesff044b12016-03-25 23:11:52 +00002893 return MachOObjectFile::create(Buffer, false, false);
David Blaikieb805f732016-03-28 17:45:48 +00002894 if (Magic == "\xCE\xFA\xED\xFE")
Lang Hamesff044b12016-03-25 23:11:52 +00002895 return MachOObjectFile::create(Buffer, true, false);
David Blaikieb805f732016-03-28 17:45:48 +00002896 if (Magic == "\xFE\xED\xFA\xCF")
Lang Hamesff044b12016-03-25 23:11:52 +00002897 return MachOObjectFile::create(Buffer, false, true);
David Blaikieb805f732016-03-28 17:45:48 +00002898 if (Magic == "\xCF\xFA\xED\xFE")
Lang Hamesff044b12016-03-25 23:11:52 +00002899 return MachOObjectFile::create(Buffer, true, true);
Kevin Enderbyd4e075b2016-05-06 20:16:28 +00002900 return make_error<GenericBinaryError>("Unrecognized MachO magic number",
Justin Bogner2a42da92016-05-05 23:59:57 +00002901 object_error::invalid_file_type);
Rafael Espindola56f976f2013-04-18 18:08:55 +00002902}