blob: da5a313f4b1724d10189b961df53bec9019de7e3 [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
Lang Hames82627642016-03-25 21:59:14 +0000628Expected<std::unique_ptr<MachOObjectFile>>
629MachOObjectFile::create(MemoryBufferRef Object, bool IsLittleEndian,
630 bool Is64Bits) {
Lang Hamesd1af8fc2016-03-25 23:54:32 +0000631 Error Err;
Lang Hames82627642016-03-25 21:59:14 +0000632 std::unique_ptr<MachOObjectFile> Obj(
633 new MachOObjectFile(std::move(Object), IsLittleEndian,
634 Is64Bits, Err));
635 if (Err)
636 return std::move(Err);
637 return std::move(Obj);
638}
639
Rafael Espindola48af1c22014-08-19 18:44:46 +0000640MachOObjectFile::MachOObjectFile(MemoryBufferRef Object, bool IsLittleEndian,
Lang Hames9e964f32016-03-25 17:25:34 +0000641 bool Is64bits, Error &Err)
Rafael Espindola48af1c22014-08-19 18:44:46 +0000642 : ObjectFile(getMachOType(IsLittleEndian, Is64bits), Object),
Craig Topper2617dcc2014-04-15 06:32:26 +0000643 SymtabLoadCmd(nullptr), DysymtabLoadCmd(nullptr),
Kevin Enderby9a509442015-01-27 21:28:24 +0000644 DataInCodeLoadCmd(nullptr), LinkOptHintsLoadCmd(nullptr),
645 DyldInfoLoadCmd(nullptr), UuidLoadCmd(nullptr),
646 HasPageZeroSegment(false) {
Lang Hames5e51a2e2016-07-22 16:11:25 +0000647 ErrorAsOutParameter ErrAsOutParam(&Err);
Kevin Enderbyc614d282016-08-12 20:10:25 +0000648 uint64_t SizeOfHeaders;
Kevin Enderby87025742016-04-13 21:17:58 +0000649 if (is64Bit()) {
Lang Hames9e964f32016-03-25 17:25:34 +0000650 parseHeader(this, Header64, Err);
Kevin Enderbyc614d282016-08-12 20:10:25 +0000651 SizeOfHeaders = sizeof(MachO::mach_header_64);
Kevin Enderby87025742016-04-13 21:17:58 +0000652 } else {
Lang Hames9e964f32016-03-25 17:25:34 +0000653 parseHeader(this, Header, Err);
Kevin Enderbyc614d282016-08-12 20:10:25 +0000654 SizeOfHeaders = sizeof(MachO::mach_header);
Kevin Enderby87025742016-04-13 21:17:58 +0000655 }
Lang Hames9e964f32016-03-25 17:25:34 +0000656 if (Err)
Alexey Samsonov9f336632015-06-04 19:45:22 +0000657 return;
Kevin Enderbyc614d282016-08-12 20:10:25 +0000658 SizeOfHeaders += getHeader().sizeofcmds;
659 if (getData().data() + SizeOfHeaders > getData().end()) {
Kevin Enderbyd4e075b2016-05-06 20:16:28 +0000660 Err = malformedError("load commands extend past the end of the file");
Kevin Enderby87025742016-04-13 21:17:58 +0000661 return;
662 }
Alexey Samsonov13415ed2015-06-04 19:22:03 +0000663
664 uint32_t LoadCommandCount = getHeader().ncmds;
Lang Hames9e964f32016-03-25 17:25:34 +0000665 LoadCommandInfo Load;
Kevin Enderbyfc0929a2016-09-20 20:14:14 +0000666 if (LoadCommandCount != 0) {
667 if (auto LoadOrErr = getFirstLoadCommandInfo(this))
668 Load = *LoadOrErr;
669 else {
670 Err = LoadOrErr.takeError();
671 return;
672 }
Alexey Samsonovde5a94a2015-06-04 19:57:46 +0000673 }
Lang Hames9e964f32016-03-25 17:25:34 +0000674
Kevin Enderbyfc0929a2016-09-20 20:14:14 +0000675 const char *DyldIdLoadCmd = nullptr;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000676 for (unsigned I = 0; I < LoadCommandCount; ++I) {
Kevin Enderby1851a822016-07-07 22:11:42 +0000677 if (is64Bit()) {
678 if (Load.C.cmdsize % 8 != 0) {
679 // We have a hack here to allow 64-bit Mach-O core files to have
680 // LC_THREAD commands that are only a multiple of 4 and not 8 to be
681 // allowed since the macOS kernel produces them.
682 if (getHeader().filetype != MachO::MH_CORE ||
683 Load.C.cmd != MachO::LC_THREAD || Load.C.cmdsize % 4) {
684 Err = malformedError("load command " + Twine(I) + " cmdsize not a "
685 "multiple of 8");
686 return;
687 }
688 }
689 } else {
690 if (Load.C.cmdsize % 4 != 0) {
691 Err = malformedError("load command " + Twine(I) + " cmdsize not a "
692 "multiple of 4");
693 return;
694 }
695 }
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000696 LoadCommands.push_back(Load);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000697 if (Load.C.cmd == MachO::LC_SYMTAB) {
Kevin Enderby0e52c922016-08-26 19:34:07 +0000698 if ((Err = checkSymtabCommand(this, Load, I, &SymtabLoadCmd)))
David Majnemer73cc6ff2014-11-13 19:48:56 +0000699 return;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000700 } else if (Load.C.cmd == MachO::LC_DYSYMTAB) {
Kevin Enderbydcbc5042016-08-30 21:28:30 +0000701 if ((Err = checkDysymtabCommand(this, Load, I, &DysymtabLoadCmd)))
David Majnemer73cc6ff2014-11-13 19:48:56 +0000702 return;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000703 } else if (Load.C.cmd == MachO::LC_DATA_IN_CODE) {
Kevin Enderby9d0c9452016-08-31 17:57:46 +0000704 if ((Err = checkLinkeditDataCommand(this, Load, I, &DataInCodeLoadCmd,
705 "LC_DATA_IN_CODE")))
David Majnemer73cc6ff2014-11-13 19:48:56 +0000706 return;
Kevin Enderby9a509442015-01-27 21:28:24 +0000707 } else if (Load.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
Kevin Enderby9d0c9452016-08-31 17:57:46 +0000708 if ((Err = checkLinkeditDataCommand(this, Load, I, &LinkOptHintsLoadCmd,
709 "LC_LINKER_OPTIMIZATION_HINT")))
Kevin Enderby9a509442015-01-27 21:28:24 +0000710 return;
Kevin Enderbyf76b56c2016-09-13 21:42:28 +0000711 } else if (Load.C.cmd == MachO::LC_DYLD_INFO) {
712 if ((Err = checkDyldInfoCommand(this, Load, I, &DyldInfoLoadCmd,
713 "LC_DYLD_INFO")))
David Majnemer73cc6ff2014-11-13 19:48:56 +0000714 return;
Kevin Enderbyf76b56c2016-09-13 21:42:28 +0000715 } else if (Load.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
716 if ((Err = checkDyldInfoCommand(this, Load, I, &DyldInfoLoadCmd,
717 "LC_DYLD_INFO_ONLY")))
718 return;
Alexander Potapenko6909b5b2014-10-15 23:35:45 +0000719 } else if (Load.C.cmd == MachO::LC_UUID) {
Kevin Enderbye71e13c2016-09-21 20:03:09 +0000720 if (Load.C.cmdsize != sizeof(MachO::uuid_command)) {
721 Err = malformedError("LC_UUID command " + Twine(I) + " has incorrect "
722 "cmdsize");
723 return;
724 }
David Majnemer73cc6ff2014-11-13 19:48:56 +0000725 if (UuidLoadCmd) {
Kevin Enderbye71e13c2016-09-21 20:03:09 +0000726 Err = malformedError("more than one LC_UUID command");
David Majnemer73cc6ff2014-11-13 19:48:56 +0000727 return;
728 }
Alexander Potapenko6909b5b2014-10-15 23:35:45 +0000729 UuidLoadCmd = Load.Ptr;
Alexey Samsonove1a76ab2015-06-04 22:08:37 +0000730 } else if (Load.C.cmd == MachO::LC_SEGMENT_64) {
Kevin Enderbyc614d282016-08-12 20:10:25 +0000731 if ((Err = parseSegmentLoadCommand<MachO::segment_command_64,
732 MachO::section_64>(
Kevin Enderbyb34e3a12016-05-05 17:43:35 +0000733 this, Load, Sections, HasPageZeroSegment, I,
Kevin Enderbyc614d282016-08-12 20:10:25 +0000734 "LC_SEGMENT_64", SizeOfHeaders)))
Alexey Samsonov074da9b2015-06-04 20:08:52 +0000735 return;
Alexey Samsonove1a76ab2015-06-04 22:08:37 +0000736 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
Kevin Enderbyc614d282016-08-12 20:10:25 +0000737 if ((Err = parseSegmentLoadCommand<MachO::segment_command,
738 MachO::section>(
739 this, Load, Sections, HasPageZeroSegment, I,
740 "LC_SEGMENT", SizeOfHeaders)))
Alexey Samsonov074da9b2015-06-04 20:08:52 +0000741 return;
Kevin Enderbyfc0929a2016-09-20 20:14:14 +0000742 } else if (Load.C.cmd == MachO::LC_ID_DYLIB) {
743 if ((Err = checkDylibIdCommand(this, Load, I, &DyldIdLoadCmd)))
744 return;
745 } else if (Load.C.cmd == MachO::LC_LOAD_DYLIB) {
746 if ((Err = checkDylibCommand(this, Load, I, "LC_LOAD_DYLIB")))
747 return;
748 Libraries.push_back(Load.Ptr);
749 } else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB) {
750 if ((Err = checkDylibCommand(this, Load, I, "LC_LOAD_WEAK_DYLIB")))
751 return;
752 Libraries.push_back(Load.Ptr);
753 } else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB) {
754 if ((Err = checkDylibCommand(this, Load, I, "LC_LAZY_LOAD_DYLIB")))
755 return;
756 Libraries.push_back(Load.Ptr);
757 } else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB) {
758 if ((Err = checkDylibCommand(this, Load, I, "LC_REEXPORT_DYLIB")))
759 return;
760 Libraries.push_back(Load.Ptr);
761 } else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
762 if ((Err = checkDylibCommand(this, Load, I, "LC_LOAD_UPWARD_DYLIB")))
763 return;
Kevin Enderby980b2582014-06-05 21:21:57 +0000764 Libraries.push_back(Load.Ptr);
Rafael Espindola56f976f2013-04-18 18:08:55 +0000765 }
Alexey Samsonovde5a94a2015-06-04 19:57:46 +0000766 if (I < LoadCommandCount - 1) {
Kevin Enderby368e7142016-05-03 17:16:08 +0000767 if (auto LoadOrErr = getNextLoadCommandInfo(this, I, Load))
Lang Hames9e964f32016-03-25 17:25:34 +0000768 Load = *LoadOrErr;
769 else {
770 Err = LoadOrErr.takeError();
Alexey Samsonovde5a94a2015-06-04 19:57:46 +0000771 return;
772 }
Alexey Samsonovde5a94a2015-06-04 19:57:46 +0000773 }
Rafael Espindola56f976f2013-04-18 18:08:55 +0000774 }
Kevin Enderby1829c682016-01-22 22:49:55 +0000775 if (!SymtabLoadCmd) {
776 if (DysymtabLoadCmd) {
Kevin Enderbyd4e075b2016-05-06 20:16:28 +0000777 Err = malformedError("contains LC_DYSYMTAB load command without a "
Kevin Enderby89134962016-05-05 23:41:05 +0000778 "LC_SYMTAB load command");
Kevin Enderby1829c682016-01-22 22:49:55 +0000779 return;
780 }
781 } else if (DysymtabLoadCmd) {
782 MachO::symtab_command Symtab =
783 getStruct<MachO::symtab_command>(this, SymtabLoadCmd);
784 MachO::dysymtab_command Dysymtab =
785 getStruct<MachO::dysymtab_command>(this, DysymtabLoadCmd);
786 if (Dysymtab.nlocalsym != 0 && Dysymtab.ilocalsym > Symtab.nsyms) {
Kevin Enderbyd4e075b2016-05-06 20:16:28 +0000787 Err = malformedError("ilocalsym in LC_DYSYMTAB load command "
Kevin Enderby89134962016-05-05 23:41:05 +0000788 "extends past the end of the symbol table");
Kevin Enderby1829c682016-01-22 22:49:55 +0000789 return;
790 }
Kevin Enderby5e55d172016-04-21 20:29:49 +0000791 uint64_t BigSize = Dysymtab.ilocalsym;
792 BigSize += Dysymtab.nlocalsym;
793 if (Dysymtab.nlocalsym != 0 && BigSize > Symtab.nsyms) {
Kevin Enderbyd4e075b2016-05-06 20:16:28 +0000794 Err = malformedError("ilocalsym plus nlocalsym in LC_DYSYMTAB load "
Kevin Enderby89134962016-05-05 23:41:05 +0000795 "command extends past the end of the symbol table");
Kevin Enderby1829c682016-01-22 22:49:55 +0000796 return;
797 }
798 if (Dysymtab.nextdefsym != 0 && Dysymtab.ilocalsym > Symtab.nsyms) {
Kevin Enderbyd4e075b2016-05-06 20:16:28 +0000799 Err = malformedError("nextdefsym in LC_DYSYMTAB load command "
Kevin Enderby89134962016-05-05 23:41:05 +0000800 "extends past the end of the symbol table");
Kevin Enderby1829c682016-01-22 22:49:55 +0000801 return;
802 }
Kevin Enderby5e55d172016-04-21 20:29:49 +0000803 BigSize = Dysymtab.iextdefsym;
804 BigSize += Dysymtab.nextdefsym;
805 if (Dysymtab.nextdefsym != 0 && BigSize > Symtab.nsyms) {
Kevin Enderbyd4e075b2016-05-06 20:16:28 +0000806 Err = malformedError("iextdefsym plus nextdefsym in LC_DYSYMTAB "
Kevin Enderby89134962016-05-05 23:41:05 +0000807 "load command extends past the end of the symbol "
808 "table");
Kevin Enderby1829c682016-01-22 22:49:55 +0000809 return;
810 }
811 if (Dysymtab.nundefsym != 0 && Dysymtab.iundefsym > Symtab.nsyms) {
Kevin Enderbyd4e075b2016-05-06 20:16:28 +0000812 Err = malformedError("nundefsym in LC_DYSYMTAB load command "
Kevin Enderby89134962016-05-05 23:41:05 +0000813 "extends past the end of the symbol table");
Kevin Enderby1829c682016-01-22 22:49:55 +0000814 return;
815 }
Kevin Enderby5e55d172016-04-21 20:29:49 +0000816 BigSize = Dysymtab.iundefsym;
817 BigSize += Dysymtab.nundefsym;
818 if (Dysymtab.nundefsym != 0 && BigSize > Symtab.nsyms) {
Kevin Enderbyd4e075b2016-05-06 20:16:28 +0000819 Err = malformedError("iundefsym plus nundefsym in LC_DYSYMTAB load "
Kevin Enderby89134962016-05-05 23:41:05 +0000820 " command extends past the end of the symbol table");
Kevin Enderby1829c682016-01-22 22:49:55 +0000821 return;
822 }
823 }
Kevin Enderbyfc0929a2016-09-20 20:14:14 +0000824 if ((getHeader().filetype == MachO::MH_DYLIB ||
825 getHeader().filetype == MachO::MH_DYLIB_STUB) &&
826 DyldIdLoadCmd == nullptr) {
827 Err = malformedError("no LC_ID_DYLIB load command in dynamic library "
828 "filetype");
829 return;
830 }
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000831 assert(LoadCommands.size() == LoadCommandCount);
Lang Hames9e964f32016-03-25 17:25:34 +0000832
833 Err = Error::success();
Rafael Espindola56f976f2013-04-18 18:08:55 +0000834}
835
Rafael Espindola5e812af2014-01-30 02:49:50 +0000836void MachOObjectFile::moveSymbolNext(DataRefImpl &Symb) const {
Rafael Espindola75c30362013-04-24 19:47:55 +0000837 unsigned SymbolTableEntrySize = is64Bit() ?
Charles Davis8bdfafd2013-09-01 04:28:48 +0000838 sizeof(MachO::nlist_64) :
839 sizeof(MachO::nlist);
Rafael Espindola75c30362013-04-24 19:47:55 +0000840 Symb.p += SymbolTableEntrySize;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000841}
842
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000843Expected<StringRef> MachOObjectFile::getSymbolName(DataRefImpl Symb) const {
Rafael Espindola6e040c02013-04-26 20:07:33 +0000844 StringRef StringTable = getStringTableData();
Artyom Skrobov78d5daf2014-07-18 09:26:16 +0000845 MachO::nlist_base Entry = getSymbolTableEntryBase(this, Symb);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000846 const char *Start = &StringTable.data()[Entry.n_strx];
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000847 if (Start < getData().begin() || Start >= getData().end()) {
Kevin Enderbyd4e075b2016-05-06 20:16:28 +0000848 return malformedError("bad string index: " + Twine(Entry.n_strx) +
Kevin Enderby89134962016-05-05 23:41:05 +0000849 " for symbol at index " + Twine(getSymbolIndex(Symb)));
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000850 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000851 return StringRef(Start);
Rafael Espindola56f976f2013-04-18 18:08:55 +0000852}
853
Rafael Espindola0e77a942014-12-10 20:46:55 +0000854unsigned MachOObjectFile::getSectionType(SectionRef Sec) const {
855 DataRefImpl DRI = Sec.getRawDataRefImpl();
856 uint32_t Flags = getSectionFlags(this, DRI);
857 return Flags & MachO::SECTION_TYPE;
858}
859
Rafael Espindola59128922015-06-24 18:14:41 +0000860uint64_t MachOObjectFile::getNValue(DataRefImpl Sym) const {
861 if (is64Bit()) {
862 MachO::nlist_64 Entry = getSymbol64TableEntry(Sym);
863 return Entry.n_value;
864 }
865 MachO::nlist Entry = getSymbolTableEntry(Sym);
866 return Entry.n_value;
867}
868
Kevin Enderby980b2582014-06-05 21:21:57 +0000869// getIndirectName() returns the name of the alias'ed symbol who's string table
870// index is in the n_value field.
Rafael Espindola3acea392014-06-12 21:46:39 +0000871std::error_code MachOObjectFile::getIndirectName(DataRefImpl Symb,
872 StringRef &Res) const {
Kevin Enderby980b2582014-06-05 21:21:57 +0000873 StringRef StringTable = getStringTableData();
Rafael Espindola59128922015-06-24 18:14:41 +0000874 MachO::nlist_base Entry = getSymbolTableEntryBase(this, Symb);
875 if ((Entry.n_type & MachO::N_TYPE) != MachO::N_INDR)
876 return object_error::parse_failed;
877 uint64_t NValue = getNValue(Symb);
Kevin Enderby980b2582014-06-05 21:21:57 +0000878 if (NValue >= StringTable.size())
879 return object_error::parse_failed;
880 const char *Start = &StringTable.data()[NValue];
881 Res = StringRef(Start);
Rui Ueyama7d099192015-06-09 15:20:42 +0000882 return std::error_code();
Kevin Enderby980b2582014-06-05 21:21:57 +0000883}
884
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +0000885uint64_t MachOObjectFile::getSymbolValueImpl(DataRefImpl Sym) const {
Rafael Espindola7e7be922015-07-07 15:05:09 +0000886 return getNValue(Sym);
Rafael Espindola991af662015-06-24 19:11:10 +0000887}
888
Kevin Enderby931cb652016-06-24 18:24:42 +0000889Expected<uint64_t> MachOObjectFile::getSymbolAddress(DataRefImpl Sym) const {
Rafael Espindolaed067c42015-07-03 18:19:00 +0000890 return getSymbolValue(Sym);
Rafael Espindola56f976f2013-04-18 18:08:55 +0000891}
892
Rafael Espindolaa4d224722015-05-31 23:52:50 +0000893uint32_t MachOObjectFile::getSymbolAlignment(DataRefImpl DRI) const {
Rafael Espindola20122a42014-01-31 20:57:12 +0000894 uint32_t flags = getSymbolFlags(DRI);
Rafael Espindolae4dd2e02013-04-29 22:24:22 +0000895 if (flags & SymbolRef::SF_Common) {
Artyom Skrobov78d5daf2014-07-18 09:26:16 +0000896 MachO::nlist_base Entry = getSymbolTableEntryBase(this, DRI);
Rafael Espindolaa4d224722015-05-31 23:52:50 +0000897 return 1 << MachO::GET_COMM_ALIGN(Entry.n_desc);
Rafael Espindolae4dd2e02013-04-29 22:24:22 +0000898 }
Rafael Espindolaa4d224722015-05-31 23:52:50 +0000899 return 0;
Rafael Espindolae4dd2e02013-04-29 22:24:22 +0000900}
901
Rafael Espindolad7a32ea2015-06-24 10:20:30 +0000902uint64_t MachOObjectFile::getCommonSymbolSizeImpl(DataRefImpl DRI) const {
Rafael Espindola05cbccc2015-07-07 13:58:32 +0000903 return getNValue(DRI);
Rafael Espindola56f976f2013-04-18 18:08:55 +0000904}
905
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000906Expected<SymbolRef::Type>
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000907MachOObjectFile::getSymbolType(DataRefImpl Symb) const {
Artyom Skrobov78d5daf2014-07-18 09:26:16 +0000908 MachO::nlist_base Entry = getSymbolTableEntryBase(this, Symb);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000909 uint8_t n_type = Entry.n_type;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000910
Rafael Espindola56f976f2013-04-18 18:08:55 +0000911 // If this is a STAB debugging symbol, we can do nothing more.
Rafael Espindola2fa80cc2015-06-26 12:18:49 +0000912 if (n_type & MachO::N_STAB)
913 return SymbolRef::ST_Debug;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000914
Charles Davis74ec8b02013-08-27 05:00:13 +0000915 switch (n_type & MachO::N_TYPE) {
916 case MachO::N_UNDF :
Rafael Espindola2fa80cc2015-06-26 12:18:49 +0000917 return SymbolRef::ST_Unknown;
Charles Davis74ec8b02013-08-27 05:00:13 +0000918 case MachO::N_SECT :
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000919 Expected<section_iterator> SecOrError = getSymbolSection(Symb);
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000920 if (!SecOrError)
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000921 return SecOrError.takeError();
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000922 section_iterator Sec = *SecOrError;
Kuba Breckade833222015-11-12 09:40:29 +0000923 if (Sec->isData() || Sec->isBSS())
924 return SymbolRef::ST_Data;
Rafael Espindola2fa80cc2015-06-26 12:18:49 +0000925 return SymbolRef::ST_Function;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000926 }
Rafael Espindola2fa80cc2015-06-26 12:18:49 +0000927 return SymbolRef::ST_Other;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000928}
929
Rafael Espindola20122a42014-01-31 20:57:12 +0000930uint32_t MachOObjectFile::getSymbolFlags(DataRefImpl DRI) const {
Artyom Skrobov78d5daf2014-07-18 09:26:16 +0000931 MachO::nlist_base Entry = getSymbolTableEntryBase(this, DRI);
Rafael Espindola56f976f2013-04-18 18:08:55 +0000932
Charles Davis8bdfafd2013-09-01 04:28:48 +0000933 uint8_t MachOType = Entry.n_type;
934 uint16_t MachOFlags = Entry.n_desc;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000935
Rafael Espindola20122a42014-01-31 20:57:12 +0000936 uint32_t Result = SymbolRef::SF_None;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000937
Tim Northovereaef0742014-05-30 13:22:59 +0000938 if ((MachOType & MachO::N_TYPE) == MachO::N_INDR)
939 Result |= SymbolRef::SF_Indirect;
940
Rafael Espindolaa1356322013-11-02 05:03:24 +0000941 if (MachOType & MachO::N_STAB)
Rafael Espindola56f976f2013-04-18 18:08:55 +0000942 Result |= SymbolRef::SF_FormatSpecific;
943
Charles Davis74ec8b02013-08-27 05:00:13 +0000944 if (MachOType & MachO::N_EXT) {
Rafael Espindola56f976f2013-04-18 18:08:55 +0000945 Result |= SymbolRef::SF_Global;
Charles Davis74ec8b02013-08-27 05:00:13 +0000946 if ((MachOType & MachO::N_TYPE) == MachO::N_UNDF) {
Rafael Espindola05cbccc2015-07-07 13:58:32 +0000947 if (getNValue(DRI))
Rafael Espindolae4dd2e02013-04-29 22:24:22 +0000948 Result |= SymbolRef::SF_Common;
Rafael Espindolad8247722015-07-07 14:26:39 +0000949 else
950 Result |= SymbolRef::SF_Undefined;
Rafael Espindolae4dd2e02013-04-29 22:24:22 +0000951 }
Lang Hames7e0692b2015-01-15 22:33:30 +0000952
953 if (!(MachOType & MachO::N_PEXT))
954 Result |= SymbolRef::SF_Exported;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000955 }
956
Charles Davis74ec8b02013-08-27 05:00:13 +0000957 if (MachOFlags & (MachO::N_WEAK_REF | MachO::N_WEAK_DEF))
Rafael Espindola56f976f2013-04-18 18:08:55 +0000958 Result |= SymbolRef::SF_Weak;
959
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000960 if (MachOFlags & (MachO::N_ARM_THUMB_DEF))
961 Result |= SymbolRef::SF_Thumb;
962
Charles Davis74ec8b02013-08-27 05:00:13 +0000963 if ((MachOType & MachO::N_TYPE) == MachO::N_ABS)
Rafael Espindola56f976f2013-04-18 18:08:55 +0000964 Result |= SymbolRef::SF_Absolute;
965
Rafael Espindola20122a42014-01-31 20:57:12 +0000966 return Result;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000967}
968
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000969Expected<section_iterator>
Rafael Espindola8bab8892015-08-07 23:27:14 +0000970MachOObjectFile::getSymbolSection(DataRefImpl Symb) const {
Artyom Skrobov78d5daf2014-07-18 09:26:16 +0000971 MachO::nlist_base Entry = getSymbolTableEntryBase(this, Symb);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000972 uint8_t index = Entry.n_sect;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000973
Rafael Espindola8bab8892015-08-07 23:27:14 +0000974 if (index == 0)
975 return section_end();
976 DataRefImpl DRI;
977 DRI.d.a = index - 1;
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000978 if (DRI.d.a >= Sections.size()){
Kevin Enderbyd4e075b2016-05-06 20:16:28 +0000979 return malformedError("bad section index: " + Twine((int)index) +
Kevin Enderby89134962016-05-05 23:41:05 +0000980 " for symbol at index " + Twine(getSymbolIndex(Symb)));
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000981 }
Rafael Espindola8bab8892015-08-07 23:27:14 +0000982 return section_iterator(SectionRef(DRI, this));
Rafael Espindola56f976f2013-04-18 18:08:55 +0000983}
984
Rafael Espindola6bf32212015-06-24 19:57:32 +0000985unsigned MachOObjectFile::getSymbolSectionID(SymbolRef Sym) const {
986 MachO::nlist_base Entry =
987 getSymbolTableEntryBase(this, Sym.getRawDataRefImpl());
988 return Entry.n_sect - 1;
989}
990
Rafael Espindola5e812af2014-01-30 02:49:50 +0000991void MachOObjectFile::moveSectionNext(DataRefImpl &Sec) const {
Rafael Espindola56f976f2013-04-18 18:08:55 +0000992 Sec.d.a++;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000993}
994
Rafael Espindola3acea392014-06-12 21:46:39 +0000995std::error_code MachOObjectFile::getSectionName(DataRefImpl Sec,
996 StringRef &Result) const {
Rafael Espindola56f976f2013-04-18 18:08:55 +0000997 ArrayRef<char> Raw = getSectionRawName(Sec);
998 Result = parseSegmentOrSectionName(Raw.data());
Rui Ueyama7d099192015-06-09 15:20:42 +0000999 return std::error_code();
Rafael Espindola56f976f2013-04-18 18:08:55 +00001000}
1001
Rafael Espindola80291272014-10-08 15:28:58 +00001002uint64_t MachOObjectFile::getSectionAddress(DataRefImpl Sec) const {
1003 if (is64Bit())
1004 return getSection64(Sec).addr;
1005 return getSection(Sec).addr;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001006}
1007
Rafael Espindola80291272014-10-08 15:28:58 +00001008uint64_t MachOObjectFile::getSectionSize(DataRefImpl Sec) const {
Kevin Enderby46e642f2015-10-08 22:50:55 +00001009 // In the case if a malformed Mach-O file where the section offset is past
1010 // the end of the file or some part of the section size is past the end of
1011 // the file return a size of zero or a size that covers the rest of the file
1012 // but does not extend past the end of the file.
1013 uint32_t SectOffset, SectType;
1014 uint64_t SectSize;
1015
1016 if (is64Bit()) {
1017 MachO::section_64 Sect = getSection64(Sec);
1018 SectOffset = Sect.offset;
1019 SectSize = Sect.size;
1020 SectType = Sect.flags & MachO::SECTION_TYPE;
1021 } else {
1022 MachO::section Sect = getSection(Sec);
1023 SectOffset = Sect.offset;
1024 SectSize = Sect.size;
1025 SectType = Sect.flags & MachO::SECTION_TYPE;
1026 }
1027 if (SectType == MachO::S_ZEROFILL || SectType == MachO::S_GB_ZEROFILL)
1028 return SectSize;
1029 uint64_t FileSize = getData().size();
1030 if (SectOffset > FileSize)
1031 return 0;
1032 if (FileSize - SectOffset < SectSize)
1033 return FileSize - SectOffset;
1034 return SectSize;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001035}
1036
Rafael Espindola3acea392014-06-12 21:46:39 +00001037std::error_code MachOObjectFile::getSectionContents(DataRefImpl Sec,
1038 StringRef &Res) const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00001039 uint32_t Offset;
1040 uint64_t Size;
1041
1042 if (is64Bit()) {
Charles Davis8bdfafd2013-09-01 04:28:48 +00001043 MachO::section_64 Sect = getSection64(Sec);
1044 Offset = Sect.offset;
1045 Size = Sect.size;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001046 } else {
Charles Davis8bdfafd2013-09-01 04:28:48 +00001047 MachO::section Sect = getSection(Sec);
1048 Offset = Sect.offset;
1049 Size = Sect.size;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001050 }
1051
1052 Res = this->getData().substr(Offset, Size);
Rui Ueyama7d099192015-06-09 15:20:42 +00001053 return std::error_code();
Rafael Espindola56f976f2013-04-18 18:08:55 +00001054}
1055
Rafael Espindola80291272014-10-08 15:28:58 +00001056uint64_t MachOObjectFile::getSectionAlignment(DataRefImpl Sec) const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00001057 uint32_t Align;
1058 if (is64Bit()) {
Charles Davis8bdfafd2013-09-01 04:28:48 +00001059 MachO::section_64 Sect = getSection64(Sec);
1060 Align = Sect.align;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001061 } else {
Charles Davis8bdfafd2013-09-01 04:28:48 +00001062 MachO::section Sect = getSection(Sec);
1063 Align = Sect.align;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001064 }
1065
Rafael Espindola80291272014-10-08 15:28:58 +00001066 return uint64_t(1) << Align;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001067}
1068
George Rimar401e4e52016-05-24 12:48:46 +00001069bool MachOObjectFile::isSectionCompressed(DataRefImpl Sec) const {
1070 return false;
1071}
1072
Rafael Espindola80291272014-10-08 15:28:58 +00001073bool MachOObjectFile::isSectionText(DataRefImpl Sec) const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00001074 uint32_t Flags = getSectionFlags(this, Sec);
Rafael Espindola80291272014-10-08 15:28:58 +00001075 return Flags & MachO::S_ATTR_PURE_INSTRUCTIONS;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001076}
1077
Rafael Espindola80291272014-10-08 15:28:58 +00001078bool MachOObjectFile::isSectionData(DataRefImpl Sec) const {
Kevin Enderby403258f2014-05-19 20:36:02 +00001079 uint32_t Flags = getSectionFlags(this, Sec);
1080 unsigned SectionType = Flags & MachO::SECTION_TYPE;
Rafael Espindola80291272014-10-08 15:28:58 +00001081 return !(Flags & MachO::S_ATTR_PURE_INSTRUCTIONS) &&
1082 !(SectionType == MachO::S_ZEROFILL ||
1083 SectionType == MachO::S_GB_ZEROFILL);
Michael J. Spencer800619f2011-09-28 20:57:30 +00001084}
1085
Rafael Espindola80291272014-10-08 15:28:58 +00001086bool MachOObjectFile::isSectionBSS(DataRefImpl Sec) const {
Kevin Enderby403258f2014-05-19 20:36:02 +00001087 uint32_t Flags = getSectionFlags(this, Sec);
1088 unsigned SectionType = Flags & MachO::SECTION_TYPE;
Rafael Espindola80291272014-10-08 15:28:58 +00001089 return !(Flags & MachO::S_ATTR_PURE_INSTRUCTIONS) &&
1090 (SectionType == MachO::S_ZEROFILL ||
1091 SectionType == MachO::S_GB_ZEROFILL);
Preston Gurd2138ef62012-04-12 20:13:57 +00001092}
1093
Rafael Espindola6bf32212015-06-24 19:57:32 +00001094unsigned MachOObjectFile::getSectionID(SectionRef Sec) const {
1095 return Sec.getRawDataRefImpl().d.a;
1096}
1097
Rafael Espindola80291272014-10-08 15:28:58 +00001098bool MachOObjectFile::isSectionVirtual(DataRefImpl Sec) const {
Rafael Espindolac2413f52013-04-09 14:49:08 +00001099 // FIXME: Unimplemented.
Rafael Espindola80291272014-10-08 15:28:58 +00001100 return false;
Rafael Espindolac2413f52013-04-09 14:49:08 +00001101}
1102
Steven Wuf2fe0142016-02-29 19:40:10 +00001103bool MachOObjectFile::isSectionBitcode(DataRefImpl Sec) const {
1104 StringRef SegmentName = getSectionFinalSegmentName(Sec);
1105 StringRef SectName;
1106 if (!getSectionName(Sec, SectName))
1107 return (SegmentName == "__LLVM" && SectName == "__bitcode");
1108 return false;
1109}
1110
Rui Ueyamabc654b12013-09-27 21:47:05 +00001111relocation_iterator MachOObjectFile::section_rel_begin(DataRefImpl Sec) const {
Rafael Espindola04d3f492013-04-25 12:45:46 +00001112 DataRefImpl Ret;
Rafael Espindola128b8112014-04-03 23:51:28 +00001113 Ret.d.a = Sec.d.a;
1114 Ret.d.b = 0;
Rafael Espindola04d3f492013-04-25 12:45:46 +00001115 return relocation_iterator(RelocationRef(Ret, this));
Michael J. Spencere5fd0042011-10-07 19:25:32 +00001116}
Rafael Espindolac0406e12013-04-08 20:45:01 +00001117
Rafael Espindola56f976f2013-04-18 18:08:55 +00001118relocation_iterator
Rui Ueyamabc654b12013-09-27 21:47:05 +00001119MachOObjectFile::section_rel_end(DataRefImpl Sec) const {
Rafael Espindola04d3f492013-04-25 12:45:46 +00001120 uint32_t Num;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001121 if (is64Bit()) {
Charles Davis8bdfafd2013-09-01 04:28:48 +00001122 MachO::section_64 Sect = getSection64(Sec);
Charles Davis8bdfafd2013-09-01 04:28:48 +00001123 Num = Sect.nreloc;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001124 } else {
Charles Davis8bdfafd2013-09-01 04:28:48 +00001125 MachO::section Sect = getSection(Sec);
Charles Davis8bdfafd2013-09-01 04:28:48 +00001126 Num = Sect.nreloc;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001127 }
Eric Christopher7b015c72011-04-22 03:19:48 +00001128
Rafael Espindola56f976f2013-04-18 18:08:55 +00001129 DataRefImpl Ret;
Rafael Espindola128b8112014-04-03 23:51:28 +00001130 Ret.d.a = Sec.d.a;
1131 Ret.d.b = Num;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001132 return relocation_iterator(RelocationRef(Ret, this));
1133}
Benjamin Kramer022ecdf2011-09-08 20:52:17 +00001134
Rafael Espindola5e812af2014-01-30 02:49:50 +00001135void MachOObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
Rafael Espindola128b8112014-04-03 23:51:28 +00001136 ++Rel.d.b;
Benjamin Kramer022ecdf2011-09-08 20:52:17 +00001137}
Owen Anderson171f4852011-10-24 23:20:07 +00001138
Rafael Espindola96d071c2015-06-29 23:29:12 +00001139uint64_t MachOObjectFile::getRelocationOffset(DataRefImpl Rel) const {
Rafael Espindola72475462014-04-04 00:31:12 +00001140 assert(getHeader().filetype == MachO::MH_OBJECT &&
1141 "Only implemented for MH_OBJECT");
Charles Davis8bdfafd2013-09-01 04:28:48 +00001142 MachO::any_relocation_info RE = getRelocation(Rel);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001143 return getAnyRelocationAddress(RE);
David Meyer2fc34c52012-03-01 01:36:50 +00001144}
1145
Rafael Espindola806f0062013-06-05 01:33:53 +00001146symbol_iterator
1147MachOObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
Charles Davis8bdfafd2013-09-01 04:28:48 +00001148 MachO::any_relocation_info RE = getRelocation(Rel);
Tim Northover07f99fb2014-07-04 10:57:56 +00001149 if (isRelocationScattered(RE))
1150 return symbol_end();
1151
Rafael Espindola56f976f2013-04-18 18:08:55 +00001152 uint32_t SymbolIdx = getPlainRelocationSymbolNum(RE);
1153 bool isExtern = getPlainRelocationExternal(RE);
Rafael Espindola806f0062013-06-05 01:33:53 +00001154 if (!isExtern)
Rafael Espindolab5155a52014-02-10 20:24:04 +00001155 return symbol_end();
Rafael Espindola75c30362013-04-24 19:47:55 +00001156
Charles Davis8bdfafd2013-09-01 04:28:48 +00001157 MachO::symtab_command S = getSymtabLoadCommand();
Rafael Espindola75c30362013-04-24 19:47:55 +00001158 unsigned SymbolTableEntrySize = is64Bit() ?
Charles Davis8bdfafd2013-09-01 04:28:48 +00001159 sizeof(MachO::nlist_64) :
1160 sizeof(MachO::nlist);
1161 uint64_t Offset = S.symoff + SymbolIdx * SymbolTableEntrySize;
Rafael Espindola75c30362013-04-24 19:47:55 +00001162 DataRefImpl Sym;
1163 Sym.p = reinterpret_cast<uintptr_t>(getPtr(this, Offset));
Rafael Espindola806f0062013-06-05 01:33:53 +00001164 return symbol_iterator(SymbolRef(Sym, this));
Rafael Espindola56f976f2013-04-18 18:08:55 +00001165}
1166
Keno Fischerc780e8e2015-05-21 21:24:32 +00001167section_iterator
1168MachOObjectFile::getRelocationSection(DataRefImpl Rel) const {
1169 return section_iterator(getAnyRelocationSection(getRelocation(Rel)));
1170}
1171
Rafael Espindola99c041b2015-06-30 01:53:01 +00001172uint64_t MachOObjectFile::getRelocationType(DataRefImpl Rel) const {
Charles Davis8bdfafd2013-09-01 04:28:48 +00001173 MachO::any_relocation_info RE = getRelocation(Rel);
Rafael Espindola99c041b2015-06-30 01:53:01 +00001174 return getAnyRelocationType(RE);
Rafael Espindola56f976f2013-04-18 18:08:55 +00001175}
1176
Rafael Espindola41bb4322015-06-30 04:08:37 +00001177void MachOObjectFile::getRelocationTypeName(
1178 DataRefImpl Rel, SmallVectorImpl<char> &Result) const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00001179 StringRef res;
Rafael Espindola99c041b2015-06-30 01:53:01 +00001180 uint64_t RType = getRelocationType(Rel);
Rafael Espindola56f976f2013-04-18 18:08:55 +00001181
1182 unsigned Arch = this->getArch();
1183
1184 switch (Arch) {
1185 case Triple::x86: {
1186 static const char *const Table[] = {
1187 "GENERIC_RELOC_VANILLA",
1188 "GENERIC_RELOC_PAIR",
1189 "GENERIC_RELOC_SECTDIFF",
1190 "GENERIC_RELOC_PB_LA_PTR",
1191 "GENERIC_RELOC_LOCAL_SECTDIFF",
1192 "GENERIC_RELOC_TLV" };
1193
Eric Christopher13250cb2013-12-06 02:33:38 +00001194 if (RType > 5)
Rafael Espindola56f976f2013-04-18 18:08:55 +00001195 res = "Unknown";
1196 else
1197 res = Table[RType];
1198 break;
1199 }
1200 case Triple::x86_64: {
1201 static const char *const Table[] = {
1202 "X86_64_RELOC_UNSIGNED",
1203 "X86_64_RELOC_SIGNED",
1204 "X86_64_RELOC_BRANCH",
1205 "X86_64_RELOC_GOT_LOAD",
1206 "X86_64_RELOC_GOT",
1207 "X86_64_RELOC_SUBTRACTOR",
1208 "X86_64_RELOC_SIGNED_1",
1209 "X86_64_RELOC_SIGNED_2",
1210 "X86_64_RELOC_SIGNED_4",
1211 "X86_64_RELOC_TLV" };
1212
1213 if (RType > 9)
1214 res = "Unknown";
1215 else
1216 res = Table[RType];
1217 break;
1218 }
1219 case Triple::arm: {
1220 static const char *const Table[] = {
1221 "ARM_RELOC_VANILLA",
1222 "ARM_RELOC_PAIR",
1223 "ARM_RELOC_SECTDIFF",
1224 "ARM_RELOC_LOCAL_SECTDIFF",
1225 "ARM_RELOC_PB_LA_PTR",
1226 "ARM_RELOC_BR24",
1227 "ARM_THUMB_RELOC_BR22",
1228 "ARM_THUMB_32BIT_BRANCH",
1229 "ARM_RELOC_HALF",
1230 "ARM_RELOC_HALF_SECTDIFF" };
1231
1232 if (RType > 9)
1233 res = "Unknown";
1234 else
1235 res = Table[RType];
1236 break;
1237 }
Tim Northover00ed9962014-03-29 10:18:08 +00001238 case Triple::aarch64: {
1239 static const char *const Table[] = {
1240 "ARM64_RELOC_UNSIGNED", "ARM64_RELOC_SUBTRACTOR",
1241 "ARM64_RELOC_BRANCH26", "ARM64_RELOC_PAGE21",
1242 "ARM64_RELOC_PAGEOFF12", "ARM64_RELOC_GOT_LOAD_PAGE21",
1243 "ARM64_RELOC_GOT_LOAD_PAGEOFF12", "ARM64_RELOC_POINTER_TO_GOT",
1244 "ARM64_RELOC_TLVP_LOAD_PAGE21", "ARM64_RELOC_TLVP_LOAD_PAGEOFF12",
1245 "ARM64_RELOC_ADDEND"
1246 };
1247
1248 if (RType >= array_lengthof(Table))
1249 res = "Unknown";
1250 else
1251 res = Table[RType];
1252 break;
1253 }
Rafael Espindola56f976f2013-04-18 18:08:55 +00001254 case Triple::ppc: {
1255 static const char *const Table[] = {
1256 "PPC_RELOC_VANILLA",
1257 "PPC_RELOC_PAIR",
1258 "PPC_RELOC_BR14",
1259 "PPC_RELOC_BR24",
1260 "PPC_RELOC_HI16",
1261 "PPC_RELOC_LO16",
1262 "PPC_RELOC_HA16",
1263 "PPC_RELOC_LO14",
1264 "PPC_RELOC_SECTDIFF",
1265 "PPC_RELOC_PB_LA_PTR",
1266 "PPC_RELOC_HI16_SECTDIFF",
1267 "PPC_RELOC_LO16_SECTDIFF",
1268 "PPC_RELOC_HA16_SECTDIFF",
1269 "PPC_RELOC_JBSR",
1270 "PPC_RELOC_LO14_SECTDIFF",
1271 "PPC_RELOC_LOCAL_SECTDIFF" };
1272
Eric Christopher13250cb2013-12-06 02:33:38 +00001273 if (RType > 15)
1274 res = "Unknown";
1275 else
1276 res = Table[RType];
Rafael Espindola56f976f2013-04-18 18:08:55 +00001277 break;
1278 }
1279 case Triple::UnknownArch:
1280 res = "Unknown";
1281 break;
1282 }
1283 Result.append(res.begin(), res.end());
Rafael Espindola56f976f2013-04-18 18:08:55 +00001284}
1285
Keno Fischer281b6942015-05-30 19:44:53 +00001286uint8_t MachOObjectFile::getRelocationLength(DataRefImpl Rel) const {
1287 MachO::any_relocation_info RE = getRelocation(Rel);
1288 return getAnyRelocationLength(RE);
1289}
1290
Kevin Enderby980b2582014-06-05 21:21:57 +00001291//
1292// guessLibraryShortName() is passed a name of a dynamic library and returns a
1293// guess on what the short name is. Then name is returned as a substring of the
1294// StringRef Name passed in. The name of the dynamic library is recognized as
1295// a framework if it has one of the two following forms:
1296// Foo.framework/Versions/A/Foo
1297// Foo.framework/Foo
1298// Where A and Foo can be any string. And may contain a trailing suffix
1299// starting with an underbar. If the Name is recognized as a framework then
1300// isFramework is set to true else it is set to false. If the Name has a
1301// suffix then Suffix is set to the substring in Name that contains the suffix
1302// else it is set to a NULL StringRef.
1303//
1304// The Name of the dynamic library is recognized as a library name if it has
1305// one of the two following forms:
1306// libFoo.A.dylib
1307// libFoo.dylib
1308// The library may have a suffix trailing the name Foo of the form:
1309// libFoo_profile.A.dylib
1310// libFoo_profile.dylib
1311//
1312// The Name of the dynamic library is also recognized as a library name if it
1313// has the following form:
1314// Foo.qtx
1315//
1316// If the Name of the dynamic library is none of the forms above then a NULL
1317// StringRef is returned.
1318//
1319StringRef MachOObjectFile::guessLibraryShortName(StringRef Name,
1320 bool &isFramework,
1321 StringRef &Suffix) {
1322 StringRef Foo, F, DotFramework, V, Dylib, Lib, Dot, Qtx;
1323 size_t a, b, c, d, Idx;
1324
1325 isFramework = false;
1326 Suffix = StringRef();
1327
1328 // Pull off the last component and make Foo point to it
1329 a = Name.rfind('/');
1330 if (a == Name.npos || a == 0)
1331 goto guess_library;
1332 Foo = Name.slice(a+1, Name.npos);
1333
1334 // Look for a suffix starting with a '_'
1335 Idx = Foo.rfind('_');
1336 if (Idx != Foo.npos && Foo.size() >= 2) {
1337 Suffix = Foo.slice(Idx, Foo.npos);
1338 Foo = Foo.slice(0, Idx);
1339 }
1340
1341 // First look for the form Foo.framework/Foo
1342 b = Name.rfind('/', a);
1343 if (b == Name.npos)
1344 Idx = 0;
1345 else
1346 Idx = b+1;
1347 F = Name.slice(Idx, Idx + Foo.size());
1348 DotFramework = Name.slice(Idx + Foo.size(),
1349 Idx + Foo.size() + sizeof(".framework/")-1);
1350 if (F == Foo && DotFramework == ".framework/") {
1351 isFramework = true;
1352 return Foo;
1353 }
1354
1355 // Next look for the form Foo.framework/Versions/A/Foo
1356 if (b == Name.npos)
1357 goto guess_library;
1358 c = Name.rfind('/', b);
1359 if (c == Name.npos || c == 0)
1360 goto guess_library;
1361 V = Name.slice(c+1, Name.npos);
1362 if (!V.startswith("Versions/"))
1363 goto guess_library;
1364 d = Name.rfind('/', c);
1365 if (d == Name.npos)
1366 Idx = 0;
1367 else
1368 Idx = d+1;
1369 F = Name.slice(Idx, Idx + Foo.size());
1370 DotFramework = Name.slice(Idx + Foo.size(),
1371 Idx + Foo.size() + sizeof(".framework/")-1);
1372 if (F == Foo && DotFramework == ".framework/") {
1373 isFramework = true;
1374 return Foo;
1375 }
1376
1377guess_library:
1378 // pull off the suffix after the "." and make a point to it
1379 a = Name.rfind('.');
1380 if (a == Name.npos || a == 0)
1381 return StringRef();
1382 Dylib = Name.slice(a, Name.npos);
1383 if (Dylib != ".dylib")
1384 goto guess_qtx;
1385
1386 // First pull off the version letter for the form Foo.A.dylib if any.
1387 if (a >= 3) {
1388 Dot = Name.slice(a-2, a-1);
1389 if (Dot == ".")
1390 a = a - 2;
1391 }
1392
1393 b = Name.rfind('/', a);
1394 if (b == Name.npos)
1395 b = 0;
1396 else
1397 b = b+1;
1398 // ignore any suffix after an underbar like Foo_profile.A.dylib
1399 Idx = Name.find('_', b);
1400 if (Idx != Name.npos && Idx != b) {
1401 Lib = Name.slice(b, Idx);
1402 Suffix = Name.slice(Idx, a);
1403 }
1404 else
1405 Lib = Name.slice(b, a);
1406 // There are incorrect library names of the form:
1407 // libATS.A_profile.dylib so check for these.
1408 if (Lib.size() >= 3) {
1409 Dot = Lib.slice(Lib.size()-2, Lib.size()-1);
1410 if (Dot == ".")
1411 Lib = Lib.slice(0, Lib.size()-2);
1412 }
1413 return Lib;
1414
1415guess_qtx:
1416 Qtx = Name.slice(a, Name.npos);
1417 if (Qtx != ".qtx")
1418 return StringRef();
1419 b = Name.rfind('/', a);
1420 if (b == Name.npos)
1421 Lib = Name.slice(0, a);
1422 else
1423 Lib = Name.slice(b+1, a);
1424 // There are library names of the form: QT.A.qtx so check for these.
1425 if (Lib.size() >= 3) {
1426 Dot = Lib.slice(Lib.size()-2, Lib.size()-1);
1427 if (Dot == ".")
1428 Lib = Lib.slice(0, Lib.size()-2);
1429 }
1430 return Lib;
1431}
1432
1433// getLibraryShortNameByIndex() is used to get the short name of the library
1434// for an undefined symbol in a linked Mach-O binary that was linked with the
1435// normal two-level namespace default (that is MH_TWOLEVEL in the header).
1436// It is passed the index (0 - based) of the library as translated from
1437// GET_LIBRARY_ORDINAL (1 - based).
Rafael Espindola3acea392014-06-12 21:46:39 +00001438std::error_code MachOObjectFile::getLibraryShortNameByIndex(unsigned Index,
Nick Kledzikd04bc352014-08-30 00:20:14 +00001439 StringRef &Res) const {
Kevin Enderby980b2582014-06-05 21:21:57 +00001440 if (Index >= Libraries.size())
1441 return object_error::parse_failed;
1442
Kevin Enderby980b2582014-06-05 21:21:57 +00001443 // If the cache of LibrariesShortNames is not built up do that first for
1444 // all the Libraries.
1445 if (LibrariesShortNames.size() == 0) {
1446 for (unsigned i = 0; i < Libraries.size(); i++) {
1447 MachO::dylib_command D =
1448 getStruct<MachO::dylib_command>(this, Libraries[i]);
Nick Kledzik30061302014-09-17 00:25:22 +00001449 if (D.dylib.name >= D.cmdsize)
1450 return object_error::parse_failed;
Kevin Enderby4eff6cd2014-06-20 18:07:34 +00001451 const char *P = (const char *)(Libraries[i]) + D.dylib.name;
Kevin Enderby980b2582014-06-05 21:21:57 +00001452 StringRef Name = StringRef(P);
Nick Kledzik30061302014-09-17 00:25:22 +00001453 if (D.dylib.name+Name.size() >= D.cmdsize)
1454 return object_error::parse_failed;
Kevin Enderby980b2582014-06-05 21:21:57 +00001455 StringRef Suffix;
1456 bool isFramework;
1457 StringRef shortName = guessLibraryShortName(Name, isFramework, Suffix);
Nick Kledzik30061302014-09-17 00:25:22 +00001458 if (shortName.empty())
Kevin Enderby980b2582014-06-05 21:21:57 +00001459 LibrariesShortNames.push_back(Name);
1460 else
1461 LibrariesShortNames.push_back(shortName);
1462 }
1463 }
1464
1465 Res = LibrariesShortNames[Index];
Rui Ueyama7d099192015-06-09 15:20:42 +00001466 return std::error_code();
Kevin Enderby980b2582014-06-05 21:21:57 +00001467}
1468
Rafael Espindola76ad2322015-07-06 14:55:37 +00001469section_iterator
1470MachOObjectFile::getRelocationRelocatedSection(relocation_iterator Rel) const {
1471 DataRefImpl Sec;
1472 Sec.d.a = Rel->getRawDataRefImpl().d.a;
1473 return section_iterator(SectionRef(Sec, this));
1474}
1475
Rafael Espindolaf12b8282014-02-21 20:10:59 +00001476basic_symbol_iterator MachOObjectFile::symbol_begin_impl() const {
Kevin Enderby1829c682016-01-22 22:49:55 +00001477 DataRefImpl DRI;
1478 MachO::symtab_command Symtab = getSymtabLoadCommand();
1479 if (!SymtabLoadCmd || Symtab.nsyms == 0)
1480 return basic_symbol_iterator(SymbolRef(DRI, this));
1481
Lang Hames36072da2014-05-12 21:39:59 +00001482 return getSymbolByIndex(0);
Rafael Espindola56f976f2013-04-18 18:08:55 +00001483}
1484
Rafael Espindolaf12b8282014-02-21 20:10:59 +00001485basic_symbol_iterator MachOObjectFile::symbol_end_impl() const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00001486 DataRefImpl DRI;
Kevin Enderby1829c682016-01-22 22:49:55 +00001487 MachO::symtab_command Symtab = getSymtabLoadCommand();
1488 if (!SymtabLoadCmd || Symtab.nsyms == 0)
Rafael Espindolaf12b8282014-02-21 20:10:59 +00001489 return basic_symbol_iterator(SymbolRef(DRI, this));
Rafael Espindola75c30362013-04-24 19:47:55 +00001490
Rafael Espindola75c30362013-04-24 19:47:55 +00001491 unsigned SymbolTableEntrySize = is64Bit() ?
Charles Davis8bdfafd2013-09-01 04:28:48 +00001492 sizeof(MachO::nlist_64) :
1493 sizeof(MachO::nlist);
1494 unsigned Offset = Symtab.symoff +
1495 Symtab.nsyms * SymbolTableEntrySize;
Rafael Espindola75c30362013-04-24 19:47:55 +00001496 DRI.p = reinterpret_cast<uintptr_t>(getPtr(this, Offset));
Rafael Espindolaf12b8282014-02-21 20:10:59 +00001497 return basic_symbol_iterator(SymbolRef(DRI, this));
Rafael Espindola56f976f2013-04-18 18:08:55 +00001498}
1499
Lang Hames36072da2014-05-12 21:39:59 +00001500basic_symbol_iterator MachOObjectFile::getSymbolByIndex(unsigned Index) const {
Lang Hames36072da2014-05-12 21:39:59 +00001501 MachO::symtab_command Symtab = getSymtabLoadCommand();
Kevin Enderby1829c682016-01-22 22:49:55 +00001502 if (!SymtabLoadCmd || Index >= Symtab.nsyms)
Filipe Cabecinhas40139502015-01-15 22:52:38 +00001503 report_fatal_error("Requested symbol index is out of range.");
Lang Hames36072da2014-05-12 21:39:59 +00001504 unsigned SymbolTableEntrySize =
1505 is64Bit() ? sizeof(MachO::nlist_64) : sizeof(MachO::nlist);
Kevin Enderby1829c682016-01-22 22:49:55 +00001506 DataRefImpl DRI;
Lang Hames36072da2014-05-12 21:39:59 +00001507 DRI.p = reinterpret_cast<uintptr_t>(getPtr(this, Symtab.symoff));
1508 DRI.p += Index * SymbolTableEntrySize;
1509 return basic_symbol_iterator(SymbolRef(DRI, this));
1510}
1511
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001512uint64_t MachOObjectFile::getSymbolIndex(DataRefImpl Symb) const {
1513 MachO::symtab_command Symtab = getSymtabLoadCommand();
1514 if (!SymtabLoadCmd)
1515 report_fatal_error("getSymbolIndex() called with no symbol table symbol");
1516 unsigned SymbolTableEntrySize =
1517 is64Bit() ? sizeof(MachO::nlist_64) : sizeof(MachO::nlist);
1518 DataRefImpl DRIstart;
1519 DRIstart.p = reinterpret_cast<uintptr_t>(getPtr(this, Symtab.symoff));
1520 uint64_t Index = (Symb.p - DRIstart.p) / SymbolTableEntrySize;
1521 return Index;
1522}
1523
Rafael Espindolab5155a52014-02-10 20:24:04 +00001524section_iterator MachOObjectFile::section_begin() const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00001525 DataRefImpl DRI;
1526 return section_iterator(SectionRef(DRI, this));
1527}
1528
Rafael Espindolab5155a52014-02-10 20:24:04 +00001529section_iterator MachOObjectFile::section_end() const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00001530 DataRefImpl DRI;
1531 DRI.d.a = Sections.size();
1532 return section_iterator(SectionRef(DRI, this));
1533}
1534
Rafael Espindola56f976f2013-04-18 18:08:55 +00001535uint8_t MachOObjectFile::getBytesInAddress() const {
Rafael Espindola60689982013-04-07 19:05:30 +00001536 return is64Bit() ? 8 : 4;
Eric Christopher7b015c72011-04-22 03:19:48 +00001537}
1538
Rafael Espindola56f976f2013-04-18 18:08:55 +00001539StringRef MachOObjectFile::getFileFormatName() const {
1540 unsigned CPUType = getCPUType(this);
1541 if (!is64Bit()) {
1542 switch (CPUType) {
Charles Davis74ec8b02013-08-27 05:00:13 +00001543 case llvm::MachO::CPU_TYPE_I386:
Rafael Espindola56f976f2013-04-18 18:08:55 +00001544 return "Mach-O 32-bit i386";
Charles Davis74ec8b02013-08-27 05:00:13 +00001545 case llvm::MachO::CPU_TYPE_ARM:
Rafael Espindola56f976f2013-04-18 18:08:55 +00001546 return "Mach-O arm";
Charles Davis74ec8b02013-08-27 05:00:13 +00001547 case llvm::MachO::CPU_TYPE_POWERPC:
Rafael Espindola56f976f2013-04-18 18:08:55 +00001548 return "Mach-O 32-bit ppc";
1549 default:
Rafael Espindola56f976f2013-04-18 18:08:55 +00001550 return "Mach-O 32-bit unknown";
1551 }
1552 }
1553
Rafael Espindola56f976f2013-04-18 18:08:55 +00001554 switch (CPUType) {
Charles Davis74ec8b02013-08-27 05:00:13 +00001555 case llvm::MachO::CPU_TYPE_X86_64:
Rafael Espindola56f976f2013-04-18 18:08:55 +00001556 return "Mach-O 64-bit x86-64";
Tim Northover00ed9962014-03-29 10:18:08 +00001557 case llvm::MachO::CPU_TYPE_ARM64:
1558 return "Mach-O arm64";
Charles Davis74ec8b02013-08-27 05:00:13 +00001559 case llvm::MachO::CPU_TYPE_POWERPC64:
Rafael Espindola56f976f2013-04-18 18:08:55 +00001560 return "Mach-O 64-bit ppc64";
1561 default:
1562 return "Mach-O 64-bit unknown";
1563 }
1564}
1565
Alexey Samsonove6388e62013-06-18 15:03:28 +00001566Triple::ArchType MachOObjectFile::getArch(uint32_t CPUType) {
1567 switch (CPUType) {
Charles Davis74ec8b02013-08-27 05:00:13 +00001568 case llvm::MachO::CPU_TYPE_I386:
Rafael Espindola56f976f2013-04-18 18:08:55 +00001569 return Triple::x86;
Charles Davis74ec8b02013-08-27 05:00:13 +00001570 case llvm::MachO::CPU_TYPE_X86_64:
Rafael Espindola56f976f2013-04-18 18:08:55 +00001571 return Triple::x86_64;
Charles Davis74ec8b02013-08-27 05:00:13 +00001572 case llvm::MachO::CPU_TYPE_ARM:
Rafael Espindola56f976f2013-04-18 18:08:55 +00001573 return Triple::arm;
Tim Northover00ed9962014-03-29 10:18:08 +00001574 case llvm::MachO::CPU_TYPE_ARM64:
Tim Northovere19bed72014-07-23 12:32:47 +00001575 return Triple::aarch64;
Charles Davis74ec8b02013-08-27 05:00:13 +00001576 case llvm::MachO::CPU_TYPE_POWERPC:
Rafael Espindola56f976f2013-04-18 18:08:55 +00001577 return Triple::ppc;
Charles Davis74ec8b02013-08-27 05:00:13 +00001578 case llvm::MachO::CPU_TYPE_POWERPC64:
Rafael Espindola56f976f2013-04-18 18:08:55 +00001579 return Triple::ppc64;
1580 default:
1581 return Triple::UnknownArch;
1582 }
1583}
1584
Tim Northover9e8eb412016-04-22 23:21:13 +00001585Triple MachOObjectFile::getArchTriple(uint32_t CPUType, uint32_t CPUSubType,
1586 const char **McpuDefault) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001587 if (McpuDefault)
1588 *McpuDefault = nullptr;
1589
Kevin Enderby4c8dfe42014-06-30 18:45:23 +00001590 switch (CPUType) {
1591 case MachO::CPU_TYPE_I386:
1592 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
1593 case MachO::CPU_SUBTYPE_I386_ALL:
1594 return Triple("i386-apple-darwin");
1595 default:
1596 return Triple();
1597 }
1598 case MachO::CPU_TYPE_X86_64:
1599 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
1600 case MachO::CPU_SUBTYPE_X86_64_ALL:
1601 return Triple("x86_64-apple-darwin");
1602 case MachO::CPU_SUBTYPE_X86_64_H:
1603 return Triple("x86_64h-apple-darwin");
1604 default:
1605 return Triple();
1606 }
1607 case MachO::CPU_TYPE_ARM:
1608 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
1609 case MachO::CPU_SUBTYPE_ARM_V4T:
1610 return Triple("armv4t-apple-darwin");
1611 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1612 return Triple("armv5e-apple-darwin");
Kevin Enderbyae2a9a22014-08-07 21:30:25 +00001613 case MachO::CPU_SUBTYPE_ARM_XSCALE:
1614 return Triple("xscale-apple-darwin");
Kevin Enderby4c8dfe42014-06-30 18:45:23 +00001615 case MachO::CPU_SUBTYPE_ARM_V6:
1616 return Triple("armv6-apple-darwin");
1617 case MachO::CPU_SUBTYPE_ARM_V6M:
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001618 if (McpuDefault)
1619 *McpuDefault = "cortex-m0";
Kevin Enderby4c8dfe42014-06-30 18:45:23 +00001620 return Triple("armv6m-apple-darwin");
Kevin Enderbyae2a9a22014-08-07 21:30:25 +00001621 case MachO::CPU_SUBTYPE_ARM_V7:
1622 return Triple("armv7-apple-darwin");
Kevin Enderby4c8dfe42014-06-30 18:45:23 +00001623 case MachO::CPU_SUBTYPE_ARM_V7EM:
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001624 if (McpuDefault)
1625 *McpuDefault = "cortex-m4";
Tim Northover9e8eb412016-04-22 23:21:13 +00001626 return Triple("thumbv7em-apple-darwin");
Kevin Enderby4c8dfe42014-06-30 18:45:23 +00001627 case MachO::CPU_SUBTYPE_ARM_V7K:
1628 return Triple("armv7k-apple-darwin");
1629 case MachO::CPU_SUBTYPE_ARM_V7M:
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001630 if (McpuDefault)
1631 *McpuDefault = "cortex-m3";
Tim Northover9e8eb412016-04-22 23:21:13 +00001632 return Triple("thumbv7m-apple-darwin");
Kevin Enderby4c8dfe42014-06-30 18:45:23 +00001633 case MachO::CPU_SUBTYPE_ARM_V7S:
1634 return Triple("armv7s-apple-darwin");
1635 default:
1636 return Triple();
1637 }
1638 case MachO::CPU_TYPE_ARM64:
1639 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
1640 case MachO::CPU_SUBTYPE_ARM64_ALL:
1641 return Triple("arm64-apple-darwin");
1642 default:
1643 return Triple();
1644 }
1645 case MachO::CPU_TYPE_POWERPC:
1646 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
1647 case MachO::CPU_SUBTYPE_POWERPC_ALL:
1648 return Triple("ppc-apple-darwin");
1649 default:
1650 return Triple();
1651 }
1652 case MachO::CPU_TYPE_POWERPC64:
Reid Kleckner4da3d572014-06-30 20:12:59 +00001653 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
Kevin Enderby4c8dfe42014-06-30 18:45:23 +00001654 case MachO::CPU_SUBTYPE_POWERPC_ALL:
1655 return Triple("ppc64-apple-darwin");
Kevin Enderby4c8dfe42014-06-30 18:45:23 +00001656 default:
1657 return Triple();
1658 }
1659 default:
1660 return Triple();
1661 }
1662}
1663
1664Triple MachOObjectFile::getHostArch() {
1665 return Triple(sys::getDefaultTargetTriple());
1666}
1667
Rafael Espindola72318b42014-08-08 16:30:17 +00001668bool MachOObjectFile::isValidArch(StringRef ArchFlag) {
1669 return StringSwitch<bool>(ArchFlag)
1670 .Case("i386", true)
1671 .Case("x86_64", true)
1672 .Case("x86_64h", true)
1673 .Case("armv4t", true)
1674 .Case("arm", true)
1675 .Case("armv5e", true)
1676 .Case("armv6", true)
1677 .Case("armv6m", true)
Frederic Riss40baa0a2015-06-16 17:37:03 +00001678 .Case("armv7", true)
Rafael Espindola72318b42014-08-08 16:30:17 +00001679 .Case("armv7em", true)
1680 .Case("armv7k", true)
1681 .Case("armv7m", true)
1682 .Case("armv7s", true)
1683 .Case("arm64", true)
1684 .Case("ppc", true)
1685 .Case("ppc64", true)
1686 .Default(false);
Kevin Enderby4c8dfe42014-06-30 18:45:23 +00001687}
1688
Alexey Samsonove6388e62013-06-18 15:03:28 +00001689unsigned MachOObjectFile::getArch() const {
1690 return getArch(getCPUType(this));
1691}
1692
Tim Northover9e8eb412016-04-22 23:21:13 +00001693Triple MachOObjectFile::getArchTriple(const char **McpuDefault) const {
1694 return getArchTriple(Header.cputype, Header.cpusubtype, McpuDefault);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001695}
1696
Rui Ueyamabc654b12013-09-27 21:47:05 +00001697relocation_iterator MachOObjectFile::section_rel_begin(unsigned Index) const {
Rafael Espindola6e040c02013-04-26 20:07:33 +00001698 DataRefImpl DRI;
1699 DRI.d.a = Index;
Rui Ueyamabc654b12013-09-27 21:47:05 +00001700 return section_rel_begin(DRI);
Rafael Espindola6e040c02013-04-26 20:07:33 +00001701}
1702
Rui Ueyamabc654b12013-09-27 21:47:05 +00001703relocation_iterator MachOObjectFile::section_rel_end(unsigned Index) const {
Rafael Espindola6e040c02013-04-26 20:07:33 +00001704 DataRefImpl DRI;
1705 DRI.d.a = Index;
Rui Ueyamabc654b12013-09-27 21:47:05 +00001706 return section_rel_end(DRI);
Rafael Espindola6e040c02013-04-26 20:07:33 +00001707}
1708
Kevin Enderby273ae012013-06-06 17:20:50 +00001709dice_iterator MachOObjectFile::begin_dices() const {
1710 DataRefImpl DRI;
1711 if (!DataInCodeLoadCmd)
1712 return dice_iterator(DiceRef(DRI, this));
1713
Charles Davis8bdfafd2013-09-01 04:28:48 +00001714 MachO::linkedit_data_command DicLC = getDataInCodeLoadCommand();
1715 DRI.p = reinterpret_cast<uintptr_t>(getPtr(this, DicLC.dataoff));
Kevin Enderby273ae012013-06-06 17:20:50 +00001716 return dice_iterator(DiceRef(DRI, this));
1717}
1718
1719dice_iterator MachOObjectFile::end_dices() const {
1720 DataRefImpl DRI;
1721 if (!DataInCodeLoadCmd)
1722 return dice_iterator(DiceRef(DRI, this));
1723
Charles Davis8bdfafd2013-09-01 04:28:48 +00001724 MachO::linkedit_data_command DicLC = getDataInCodeLoadCommand();
1725 unsigned Offset = DicLC.dataoff + DicLC.datasize;
Kevin Enderby273ae012013-06-06 17:20:50 +00001726 DRI.p = reinterpret_cast<uintptr_t>(getPtr(this, Offset));
1727 return dice_iterator(DiceRef(DRI, this));
1728}
1729
NAKAMURA Takumi70ad98a2015-09-22 11:13:55 +00001730ExportEntry::ExportEntry(ArrayRef<uint8_t> T)
1731 : Trie(T), Malformed(false), Done(false) {}
Nick Kledzikd04bc352014-08-30 00:20:14 +00001732
1733void ExportEntry::moveToFirst() {
1734 pushNode(0);
1735 pushDownUntilBottom();
1736}
1737
1738void ExportEntry::moveToEnd() {
1739 Stack.clear();
1740 Done = true;
1741}
1742
1743bool ExportEntry::operator==(const ExportEntry &Other) const {
NAKAMURA Takumi84965032015-09-22 11:14:12 +00001744 // Common case, one at end, other iterating from begin.
Nick Kledzikd04bc352014-08-30 00:20:14 +00001745 if (Done || Other.Done)
1746 return (Done == Other.Done);
1747 // Not equal if different stack sizes.
1748 if (Stack.size() != Other.Stack.size())
1749 return false;
1750 // Not equal if different cumulative strings.
Yaron Keren075759a2015-03-30 15:42:36 +00001751 if (!CumulativeString.equals(Other.CumulativeString))
Nick Kledzikd04bc352014-08-30 00:20:14 +00001752 return false;
1753 // Equal if all nodes in both stacks match.
1754 for (unsigned i=0; i < Stack.size(); ++i) {
1755 if (Stack[i].Start != Other.Stack[i].Start)
1756 return false;
1757 }
NAKAMURA Takumi10c80e72015-09-22 11:19:03 +00001758 return true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00001759}
1760
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00001761uint64_t ExportEntry::readULEB128(const uint8_t *&Ptr) {
1762 unsigned Count;
1763 uint64_t Result = decodeULEB128(Ptr, &Count);
1764 Ptr += Count;
1765 if (Ptr > Trie.end()) {
1766 Ptr = Trie.end();
Nick Kledzikd04bc352014-08-30 00:20:14 +00001767 Malformed = true;
1768 }
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00001769 return Result;
Nick Kledzikd04bc352014-08-30 00:20:14 +00001770}
1771
1772StringRef ExportEntry::name() const {
Yaron Keren075759a2015-03-30 15:42:36 +00001773 return CumulativeString;
Nick Kledzikd04bc352014-08-30 00:20:14 +00001774}
1775
1776uint64_t ExportEntry::flags() const {
1777 return Stack.back().Flags;
1778}
1779
1780uint64_t ExportEntry::address() const {
1781 return Stack.back().Address;
1782}
1783
1784uint64_t ExportEntry::other() const {
1785 return Stack.back().Other;
1786}
1787
1788StringRef ExportEntry::otherName() const {
1789 const char* ImportName = Stack.back().ImportName;
1790 if (ImportName)
1791 return StringRef(ImportName);
1792 return StringRef();
1793}
1794
1795uint32_t ExportEntry::nodeOffset() const {
1796 return Stack.back().Start - Trie.begin();
1797}
1798
NAKAMURA Takumi70ad98a2015-09-22 11:13:55 +00001799ExportEntry::NodeState::NodeState(const uint8_t *Ptr)
1800 : Start(Ptr), Current(Ptr), Flags(0), Address(0), Other(0),
1801 ImportName(nullptr), ChildCount(0), NextChildIndex(0),
1802 ParentStringLength(0), IsExportNode(false) {}
Nick Kledzikd04bc352014-08-30 00:20:14 +00001803
1804void ExportEntry::pushNode(uint64_t offset) {
1805 const uint8_t *Ptr = Trie.begin() + offset;
1806 NodeState State(Ptr);
1807 uint64_t ExportInfoSize = readULEB128(State.Current);
1808 State.IsExportNode = (ExportInfoSize != 0);
1809 const uint8_t* Children = State.Current + ExportInfoSize;
1810 if (State.IsExportNode) {
1811 State.Flags = readULEB128(State.Current);
1812 if (State.Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT) {
1813 State.Address = 0;
1814 State.Other = readULEB128(State.Current); // dylib ordinal
1815 State.ImportName = reinterpret_cast<const char*>(State.Current);
1816 } else {
1817 State.Address = readULEB128(State.Current);
Nick Kledzik1b591bd2014-08-30 01:57:34 +00001818 if (State.Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER)
NAKAMURA Takumi10c80e72015-09-22 11:19:03 +00001819 State.Other = readULEB128(State.Current);
Nick Kledzikd04bc352014-08-30 00:20:14 +00001820 }
1821 }
1822 State.ChildCount = *Children;
1823 State.Current = Children + 1;
1824 State.NextChildIndex = 0;
1825 State.ParentStringLength = CumulativeString.size();
1826 Stack.push_back(State);
1827}
1828
1829void ExportEntry::pushDownUntilBottom() {
1830 while (Stack.back().NextChildIndex < Stack.back().ChildCount) {
1831 NodeState &Top = Stack.back();
1832 CumulativeString.resize(Top.ParentStringLength);
1833 for (;*Top.Current != 0; Top.Current++) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00001834 char C = *Top.Current;
1835 CumulativeString.push_back(C);
Nick Kledzikd04bc352014-08-30 00:20:14 +00001836 }
1837 Top.Current += 1;
1838 uint64_t childNodeIndex = readULEB128(Top.Current);
1839 Top.NextChildIndex += 1;
1840 pushNode(childNodeIndex);
1841 }
1842 if (!Stack.back().IsExportNode) {
1843 Malformed = true;
1844 moveToEnd();
1845 }
1846}
1847
1848// We have a trie data structure and need a way to walk it that is compatible
1849// with the C++ iterator model. The solution is a non-recursive depth first
1850// traversal where the iterator contains a stack of parent nodes along with a
1851// string that is the accumulation of all edge strings along the parent chain
1852// to this point.
1853//
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00001854// There is one "export" node for each exported symbol. But because some
Nick Kledzikd04bc352014-08-30 00:20:14 +00001855// symbols may be a prefix of another symbol (e.g. _dup and _dup2), an export
NAKAMURA Takumi84965032015-09-22 11:14:12 +00001856// node may have child nodes too.
Nick Kledzikd04bc352014-08-30 00:20:14 +00001857//
1858// The algorithm for moveNext() is to keep moving down the leftmost unvisited
1859// child until hitting a node with no children (which is an export node or
1860// else the trie is malformed). On the way down, each node is pushed on the
1861// stack ivar. If there is no more ways down, it pops up one and tries to go
1862// down a sibling path until a childless node is reached.
1863void ExportEntry::moveNext() {
1864 if (Stack.empty() || !Stack.back().IsExportNode) {
1865 Malformed = true;
1866 moveToEnd();
1867 return;
1868 }
1869
1870 Stack.pop_back();
1871 while (!Stack.empty()) {
1872 NodeState &Top = Stack.back();
1873 if (Top.NextChildIndex < Top.ChildCount) {
1874 pushDownUntilBottom();
1875 // Now at the next export node.
1876 return;
1877 } else {
1878 if (Top.IsExportNode) {
1879 // This node has no children but is itself an export node.
1880 CumulativeString.resize(Top.ParentStringLength);
1881 return;
1882 }
1883 Stack.pop_back();
1884 }
1885 }
1886 Done = true;
1887}
1888
NAKAMURA Takumi10c80e72015-09-22 11:19:03 +00001889iterator_range<export_iterator>
Nick Kledzikd04bc352014-08-30 00:20:14 +00001890MachOObjectFile::exports(ArrayRef<uint8_t> Trie) {
1891 ExportEntry Start(Trie);
Juergen Ributzka4d7f70d2014-12-19 02:31:01 +00001892 if (Trie.size() == 0)
1893 Start.moveToEnd();
1894 else
1895 Start.moveToFirst();
Nick Kledzikd04bc352014-08-30 00:20:14 +00001896
1897 ExportEntry Finish(Trie);
1898 Finish.moveToEnd();
1899
Craig Topper15576e12015-12-06 05:08:07 +00001900 return make_range(export_iterator(Start), export_iterator(Finish));
Nick Kledzikd04bc352014-08-30 00:20:14 +00001901}
1902
1903iterator_range<export_iterator> MachOObjectFile::exports() const {
1904 return exports(getDyldInfoExportsTrie());
1905}
1906
Nick Kledzikac431442014-09-12 21:34:15 +00001907MachORebaseEntry::MachORebaseEntry(ArrayRef<uint8_t> Bytes, bool is64Bit)
1908 : Opcodes(Bytes), Ptr(Bytes.begin()), SegmentOffset(0), SegmentIndex(0),
1909 RemainingLoopCount(0), AdvanceAmount(0), RebaseType(0),
1910 PointerSize(is64Bit ? 8 : 4), Malformed(false), Done(false) {}
1911
1912void MachORebaseEntry::moveToFirst() {
1913 Ptr = Opcodes.begin();
1914 moveNext();
1915}
1916
1917void MachORebaseEntry::moveToEnd() {
1918 Ptr = Opcodes.end();
1919 RemainingLoopCount = 0;
1920 Done = true;
1921}
1922
1923void MachORebaseEntry::moveNext() {
1924 // If in the middle of some loop, move to next rebasing in loop.
1925 SegmentOffset += AdvanceAmount;
1926 if (RemainingLoopCount) {
1927 --RemainingLoopCount;
1928 return;
1929 }
1930 if (Ptr == Opcodes.end()) {
1931 Done = true;
1932 return;
1933 }
1934 bool More = true;
1935 while (More && !Malformed) {
1936 // Parse next opcode and set up next loop.
1937 uint8_t Byte = *Ptr++;
1938 uint8_t ImmValue = Byte & MachO::REBASE_IMMEDIATE_MASK;
1939 uint8_t Opcode = Byte & MachO::REBASE_OPCODE_MASK;
1940 switch (Opcode) {
1941 case MachO::REBASE_OPCODE_DONE:
1942 More = false;
1943 Done = true;
1944 moveToEnd();
1945 DEBUG_WITH_TYPE("mach-o-rebase", llvm::dbgs() << "REBASE_OPCODE_DONE\n");
1946 break;
1947 case MachO::REBASE_OPCODE_SET_TYPE_IMM:
1948 RebaseType = ImmValue;
1949 DEBUG_WITH_TYPE(
1950 "mach-o-rebase",
1951 llvm::dbgs() << "REBASE_OPCODE_SET_TYPE_IMM: "
1952 << "RebaseType=" << (int) RebaseType << "\n");
1953 break;
1954 case MachO::REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:
1955 SegmentIndex = ImmValue;
1956 SegmentOffset = readULEB128();
1957 DEBUG_WITH_TYPE(
1958 "mach-o-rebase",
1959 llvm::dbgs() << "REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: "
1960 << "SegmentIndex=" << SegmentIndex << ", "
1961 << format("SegmentOffset=0x%06X", SegmentOffset)
1962 << "\n");
1963 break;
1964 case MachO::REBASE_OPCODE_ADD_ADDR_ULEB:
1965 SegmentOffset += readULEB128();
1966 DEBUG_WITH_TYPE("mach-o-rebase",
1967 llvm::dbgs() << "REBASE_OPCODE_ADD_ADDR_ULEB: "
1968 << format("SegmentOffset=0x%06X",
1969 SegmentOffset) << "\n");
1970 break;
1971 case MachO::REBASE_OPCODE_ADD_ADDR_IMM_SCALED:
1972 SegmentOffset += ImmValue * PointerSize;
1973 DEBUG_WITH_TYPE("mach-o-rebase",
1974 llvm::dbgs() << "REBASE_OPCODE_ADD_ADDR_IMM_SCALED: "
1975 << format("SegmentOffset=0x%06X",
1976 SegmentOffset) << "\n");
1977 break;
1978 case MachO::REBASE_OPCODE_DO_REBASE_IMM_TIMES:
1979 AdvanceAmount = PointerSize;
1980 RemainingLoopCount = ImmValue - 1;
1981 DEBUG_WITH_TYPE(
1982 "mach-o-rebase",
1983 llvm::dbgs() << "REBASE_OPCODE_DO_REBASE_IMM_TIMES: "
1984 << format("SegmentOffset=0x%06X", SegmentOffset)
1985 << ", AdvanceAmount=" << AdvanceAmount
1986 << ", RemainingLoopCount=" << RemainingLoopCount
1987 << "\n");
1988 return;
1989 case MachO::REBASE_OPCODE_DO_REBASE_ULEB_TIMES:
1990 AdvanceAmount = PointerSize;
1991 RemainingLoopCount = readULEB128() - 1;
1992 DEBUG_WITH_TYPE(
1993 "mach-o-rebase",
1994 llvm::dbgs() << "REBASE_OPCODE_DO_REBASE_ULEB_TIMES: "
1995 << format("SegmentOffset=0x%06X", SegmentOffset)
1996 << ", AdvanceAmount=" << AdvanceAmount
1997 << ", RemainingLoopCount=" << RemainingLoopCount
1998 << "\n");
1999 return;
2000 case MachO::REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB:
2001 AdvanceAmount = readULEB128() + PointerSize;
2002 RemainingLoopCount = 0;
2003 DEBUG_WITH_TYPE(
2004 "mach-o-rebase",
2005 llvm::dbgs() << "REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB: "
2006 << format("SegmentOffset=0x%06X", SegmentOffset)
2007 << ", AdvanceAmount=" << AdvanceAmount
2008 << ", RemainingLoopCount=" << RemainingLoopCount
2009 << "\n");
2010 return;
2011 case MachO::REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB:
2012 RemainingLoopCount = readULEB128() - 1;
2013 AdvanceAmount = readULEB128() + PointerSize;
2014 DEBUG_WITH_TYPE(
2015 "mach-o-rebase",
2016 llvm::dbgs() << "REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB: "
2017 << format("SegmentOffset=0x%06X", SegmentOffset)
2018 << ", AdvanceAmount=" << AdvanceAmount
2019 << ", RemainingLoopCount=" << RemainingLoopCount
2020 << "\n");
2021 return;
2022 default:
2023 Malformed = true;
2024 }
2025 }
2026}
2027
2028uint64_t MachORebaseEntry::readULEB128() {
2029 unsigned Count;
2030 uint64_t Result = decodeULEB128(Ptr, &Count);
2031 Ptr += Count;
2032 if (Ptr > Opcodes.end()) {
2033 Ptr = Opcodes.end();
2034 Malformed = true;
2035 }
2036 return Result;
2037}
2038
2039uint32_t MachORebaseEntry::segmentIndex() const { return SegmentIndex; }
2040
2041uint64_t MachORebaseEntry::segmentOffset() const { return SegmentOffset; }
2042
2043StringRef MachORebaseEntry::typeName() const {
2044 switch (RebaseType) {
2045 case MachO::REBASE_TYPE_POINTER:
2046 return "pointer";
2047 case MachO::REBASE_TYPE_TEXT_ABSOLUTE32:
2048 return "text abs32";
2049 case MachO::REBASE_TYPE_TEXT_PCREL32:
2050 return "text rel32";
2051 }
2052 return "unknown";
2053}
2054
2055bool MachORebaseEntry::operator==(const MachORebaseEntry &Other) const {
2056 assert(Opcodes == Other.Opcodes && "compare iterators of different files");
2057 return (Ptr == Other.Ptr) &&
2058 (RemainingLoopCount == Other.RemainingLoopCount) &&
2059 (Done == Other.Done);
2060}
2061
2062iterator_range<rebase_iterator>
2063MachOObjectFile::rebaseTable(ArrayRef<uint8_t> Opcodes, bool is64) {
2064 MachORebaseEntry Start(Opcodes, is64);
2065 Start.moveToFirst();
2066
2067 MachORebaseEntry Finish(Opcodes, is64);
2068 Finish.moveToEnd();
2069
Craig Topper15576e12015-12-06 05:08:07 +00002070 return make_range(rebase_iterator(Start), rebase_iterator(Finish));
Nick Kledzikac431442014-09-12 21:34:15 +00002071}
2072
2073iterator_range<rebase_iterator> MachOObjectFile::rebaseTable() const {
2074 return rebaseTable(getDyldInfoRebaseOpcodes(), is64Bit());
2075}
2076
NAKAMURA Takumi70ad98a2015-09-22 11:13:55 +00002077MachOBindEntry::MachOBindEntry(ArrayRef<uint8_t> Bytes, bool is64Bit, Kind BK)
Nick Kledzik56ebef42014-09-16 01:41:51 +00002078 : Opcodes(Bytes), Ptr(Bytes.begin()), SegmentOffset(0), SegmentIndex(0),
2079 Ordinal(0), Flags(0), Addend(0), RemainingLoopCount(0), AdvanceAmount(0),
2080 BindType(0), PointerSize(is64Bit ? 8 : 4),
2081 TableKind(BK), Malformed(false), Done(false) {}
2082
2083void MachOBindEntry::moveToFirst() {
2084 Ptr = Opcodes.begin();
2085 moveNext();
2086}
2087
2088void MachOBindEntry::moveToEnd() {
2089 Ptr = Opcodes.end();
2090 RemainingLoopCount = 0;
2091 Done = true;
2092}
2093
2094void MachOBindEntry::moveNext() {
2095 // If in the middle of some loop, move to next binding in loop.
2096 SegmentOffset += AdvanceAmount;
2097 if (RemainingLoopCount) {
2098 --RemainingLoopCount;
2099 return;
2100 }
2101 if (Ptr == Opcodes.end()) {
2102 Done = true;
2103 return;
2104 }
2105 bool More = true;
2106 while (More && !Malformed) {
2107 // Parse next opcode and set up next loop.
2108 uint8_t Byte = *Ptr++;
2109 uint8_t ImmValue = Byte & MachO::BIND_IMMEDIATE_MASK;
2110 uint8_t Opcode = Byte & MachO::BIND_OPCODE_MASK;
2111 int8_t SignExtended;
2112 const uint8_t *SymStart;
2113 switch (Opcode) {
2114 case MachO::BIND_OPCODE_DONE:
2115 if (TableKind == Kind::Lazy) {
2116 // Lazying bindings have a DONE opcode between entries. Need to ignore
2117 // it to advance to next entry. But need not if this is last entry.
2118 bool NotLastEntry = false;
2119 for (const uint8_t *P = Ptr; P < Opcodes.end(); ++P) {
2120 if (*P) {
2121 NotLastEntry = true;
2122 }
2123 }
2124 if (NotLastEntry)
2125 break;
2126 }
2127 More = false;
2128 Done = true;
2129 moveToEnd();
2130 DEBUG_WITH_TYPE("mach-o-bind", llvm::dbgs() << "BIND_OPCODE_DONE\n");
2131 break;
2132 case MachO::BIND_OPCODE_SET_DYLIB_ORDINAL_IMM:
2133 Ordinal = ImmValue;
2134 DEBUG_WITH_TYPE(
2135 "mach-o-bind",
2136 llvm::dbgs() << "BIND_OPCODE_SET_DYLIB_ORDINAL_IMM: "
2137 << "Ordinal=" << Ordinal << "\n");
2138 break;
2139 case MachO::BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB:
2140 Ordinal = readULEB128();
2141 DEBUG_WITH_TYPE(
2142 "mach-o-bind",
2143 llvm::dbgs() << "BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB: "
2144 << "Ordinal=" << Ordinal << "\n");
2145 break;
2146 case MachO::BIND_OPCODE_SET_DYLIB_SPECIAL_IMM:
2147 if (ImmValue) {
2148 SignExtended = MachO::BIND_OPCODE_MASK | ImmValue;
2149 Ordinal = SignExtended;
2150 } else
2151 Ordinal = 0;
2152 DEBUG_WITH_TYPE(
2153 "mach-o-bind",
2154 llvm::dbgs() << "BIND_OPCODE_SET_DYLIB_SPECIAL_IMM: "
2155 << "Ordinal=" << Ordinal << "\n");
2156 break;
2157 case MachO::BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM:
2158 Flags = ImmValue;
2159 SymStart = Ptr;
2160 while (*Ptr) {
2161 ++Ptr;
2162 }
Nick Kledzik56ebef42014-09-16 01:41:51 +00002163 SymbolName = StringRef(reinterpret_cast<const char*>(SymStart),
2164 Ptr-SymStart);
Nick Kledzika6375362014-09-17 01:51:43 +00002165 ++Ptr;
Nick Kledzik56ebef42014-09-16 01:41:51 +00002166 DEBUG_WITH_TYPE(
2167 "mach-o-bind",
2168 llvm::dbgs() << "BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM: "
2169 << "SymbolName=" << SymbolName << "\n");
2170 if (TableKind == Kind::Weak) {
2171 if (ImmValue & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION)
2172 return;
2173 }
2174 break;
2175 case MachO::BIND_OPCODE_SET_TYPE_IMM:
2176 BindType = ImmValue;
2177 DEBUG_WITH_TYPE(
2178 "mach-o-bind",
2179 llvm::dbgs() << "BIND_OPCODE_SET_TYPE_IMM: "
2180 << "BindType=" << (int)BindType << "\n");
2181 break;
2182 case MachO::BIND_OPCODE_SET_ADDEND_SLEB:
2183 Addend = readSLEB128();
2184 if (TableKind == Kind::Lazy)
2185 Malformed = true;
2186 DEBUG_WITH_TYPE(
2187 "mach-o-bind",
2188 llvm::dbgs() << "BIND_OPCODE_SET_ADDEND_SLEB: "
2189 << "Addend=" << Addend << "\n");
2190 break;
2191 case MachO::BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:
2192 SegmentIndex = ImmValue;
2193 SegmentOffset = readULEB128();
2194 DEBUG_WITH_TYPE(
2195 "mach-o-bind",
2196 llvm::dbgs() << "BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: "
2197 << "SegmentIndex=" << SegmentIndex << ", "
2198 << format("SegmentOffset=0x%06X", SegmentOffset)
2199 << "\n");
2200 break;
2201 case MachO::BIND_OPCODE_ADD_ADDR_ULEB:
2202 SegmentOffset += readULEB128();
2203 DEBUG_WITH_TYPE("mach-o-bind",
2204 llvm::dbgs() << "BIND_OPCODE_ADD_ADDR_ULEB: "
2205 << format("SegmentOffset=0x%06X",
2206 SegmentOffset) << "\n");
2207 break;
2208 case MachO::BIND_OPCODE_DO_BIND:
2209 AdvanceAmount = PointerSize;
2210 RemainingLoopCount = 0;
2211 DEBUG_WITH_TYPE("mach-o-bind",
2212 llvm::dbgs() << "BIND_OPCODE_DO_BIND: "
2213 << format("SegmentOffset=0x%06X",
2214 SegmentOffset) << "\n");
2215 return;
2216 case MachO::BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB:
Nick Kledzik3b2aa052014-10-18 01:21:02 +00002217 AdvanceAmount = readULEB128() + PointerSize;
Nick Kledzik56ebef42014-09-16 01:41:51 +00002218 RemainingLoopCount = 0;
2219 if (TableKind == Kind::Lazy)
2220 Malformed = true;
2221 DEBUG_WITH_TYPE(
2222 "mach-o-bind",
Nick Kledzik3b2aa052014-10-18 01:21:02 +00002223 llvm::dbgs() << "BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB: "
Nick Kledzik56ebef42014-09-16 01:41:51 +00002224 << format("SegmentOffset=0x%06X", SegmentOffset)
2225 << ", AdvanceAmount=" << AdvanceAmount
2226 << ", RemainingLoopCount=" << RemainingLoopCount
2227 << "\n");
2228 return;
2229 case MachO::BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED:
Nick Kledzik3b2aa052014-10-18 01:21:02 +00002230 AdvanceAmount = ImmValue * PointerSize + PointerSize;
Nick Kledzik56ebef42014-09-16 01:41:51 +00002231 RemainingLoopCount = 0;
2232 if (TableKind == Kind::Lazy)
2233 Malformed = true;
2234 DEBUG_WITH_TYPE("mach-o-bind",
2235 llvm::dbgs()
2236 << "BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED: "
2237 << format("SegmentOffset=0x%06X",
2238 SegmentOffset) << "\n");
2239 return;
2240 case MachO::BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB:
2241 RemainingLoopCount = readULEB128() - 1;
2242 AdvanceAmount = readULEB128() + PointerSize;
2243 if (TableKind == Kind::Lazy)
2244 Malformed = true;
2245 DEBUG_WITH_TYPE(
2246 "mach-o-bind",
2247 llvm::dbgs() << "BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB: "
2248 << format("SegmentOffset=0x%06X", SegmentOffset)
2249 << ", AdvanceAmount=" << AdvanceAmount
2250 << ", RemainingLoopCount=" << RemainingLoopCount
2251 << "\n");
2252 return;
2253 default:
2254 Malformed = true;
2255 }
2256 }
2257}
2258
2259uint64_t MachOBindEntry::readULEB128() {
2260 unsigned Count;
2261 uint64_t Result = decodeULEB128(Ptr, &Count);
2262 Ptr += Count;
2263 if (Ptr > Opcodes.end()) {
2264 Ptr = Opcodes.end();
2265 Malformed = true;
2266 }
2267 return Result;
2268}
2269
2270int64_t MachOBindEntry::readSLEB128() {
2271 unsigned Count;
2272 int64_t Result = decodeSLEB128(Ptr, &Count);
2273 Ptr += Count;
2274 if (Ptr > Opcodes.end()) {
2275 Ptr = Opcodes.end();
2276 Malformed = true;
2277 }
2278 return Result;
2279}
2280
Nick Kledzik56ebef42014-09-16 01:41:51 +00002281uint32_t MachOBindEntry::segmentIndex() const { return SegmentIndex; }
2282
2283uint64_t MachOBindEntry::segmentOffset() const { return SegmentOffset; }
2284
2285StringRef MachOBindEntry::typeName() const {
2286 switch (BindType) {
2287 case MachO::BIND_TYPE_POINTER:
2288 return "pointer";
2289 case MachO::BIND_TYPE_TEXT_ABSOLUTE32:
2290 return "text abs32";
2291 case MachO::BIND_TYPE_TEXT_PCREL32:
2292 return "text rel32";
2293 }
2294 return "unknown";
2295}
2296
2297StringRef MachOBindEntry::symbolName() const { return SymbolName; }
2298
2299int64_t MachOBindEntry::addend() const { return Addend; }
2300
2301uint32_t MachOBindEntry::flags() const { return Flags; }
2302
2303int MachOBindEntry::ordinal() const { return Ordinal; }
2304
2305bool MachOBindEntry::operator==(const MachOBindEntry &Other) const {
2306 assert(Opcodes == Other.Opcodes && "compare iterators of different files");
2307 return (Ptr == Other.Ptr) &&
2308 (RemainingLoopCount == Other.RemainingLoopCount) &&
2309 (Done == Other.Done);
2310}
2311
2312iterator_range<bind_iterator>
2313MachOObjectFile::bindTable(ArrayRef<uint8_t> Opcodes, bool is64,
2314 MachOBindEntry::Kind BKind) {
2315 MachOBindEntry Start(Opcodes, is64, BKind);
2316 Start.moveToFirst();
2317
2318 MachOBindEntry Finish(Opcodes, is64, BKind);
2319 Finish.moveToEnd();
2320
Craig Topper15576e12015-12-06 05:08:07 +00002321 return make_range(bind_iterator(Start), bind_iterator(Finish));
Nick Kledzik56ebef42014-09-16 01:41:51 +00002322}
2323
2324iterator_range<bind_iterator> MachOObjectFile::bindTable() const {
2325 return bindTable(getDyldInfoBindOpcodes(), is64Bit(),
2326 MachOBindEntry::Kind::Regular);
2327}
2328
2329iterator_range<bind_iterator> MachOObjectFile::lazyBindTable() const {
2330 return bindTable(getDyldInfoLazyBindOpcodes(), is64Bit(),
2331 MachOBindEntry::Kind::Lazy);
2332}
2333
2334iterator_range<bind_iterator> MachOObjectFile::weakBindTable() const {
2335 return bindTable(getDyldInfoWeakBindOpcodes(), is64Bit(),
2336 MachOBindEntry::Kind::Weak);
2337}
2338
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002339MachOObjectFile::load_command_iterator
2340MachOObjectFile::begin_load_commands() const {
2341 return LoadCommands.begin();
2342}
2343
2344MachOObjectFile::load_command_iterator
2345MachOObjectFile::end_load_commands() const {
2346 return LoadCommands.end();
2347}
2348
2349iterator_range<MachOObjectFile::load_command_iterator>
2350MachOObjectFile::load_commands() const {
Craig Topper15576e12015-12-06 05:08:07 +00002351 return make_range(begin_load_commands(), end_load_commands());
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002352}
2353
Rafael Espindola56f976f2013-04-18 18:08:55 +00002354StringRef
2355MachOObjectFile::getSectionFinalSegmentName(DataRefImpl Sec) const {
2356 ArrayRef<char> Raw = getSectionRawFinalSegmentName(Sec);
2357 return parseSegmentOrSectionName(Raw.data());
2358}
2359
2360ArrayRef<char>
2361MachOObjectFile::getSectionRawName(DataRefImpl Sec) const {
Rafael Espindola0d85d102015-05-22 14:59:27 +00002362 assert(Sec.d.a < Sections.size() && "Should have detected this earlier");
Charles Davis8bdfafd2013-09-01 04:28:48 +00002363 const section_base *Base =
2364 reinterpret_cast<const section_base *>(Sections[Sec.d.a]);
Craig Toppere1d12942014-08-27 05:25:25 +00002365 return makeArrayRef(Base->sectname);
Rafael Espindola56f976f2013-04-18 18:08:55 +00002366}
2367
2368ArrayRef<char>
2369MachOObjectFile::getSectionRawFinalSegmentName(DataRefImpl Sec) const {
Rafael Espindola0d85d102015-05-22 14:59:27 +00002370 assert(Sec.d.a < Sections.size() && "Should have detected this earlier");
Charles Davis8bdfafd2013-09-01 04:28:48 +00002371 const section_base *Base =
2372 reinterpret_cast<const section_base *>(Sections[Sec.d.a]);
Craig Toppere1d12942014-08-27 05:25:25 +00002373 return makeArrayRef(Base->segname);
Rafael Espindola56f976f2013-04-18 18:08:55 +00002374}
2375
2376bool
Charles Davis8bdfafd2013-09-01 04:28:48 +00002377MachOObjectFile::isRelocationScattered(const MachO::any_relocation_info &RE)
Rafael Espindola56f976f2013-04-18 18:08:55 +00002378 const {
Charles Davis8bdfafd2013-09-01 04:28:48 +00002379 if (getCPUType(this) == MachO::CPU_TYPE_X86_64)
Rafael Espindola56f976f2013-04-18 18:08:55 +00002380 return false;
Charles Davis8bdfafd2013-09-01 04:28:48 +00002381 return getPlainRelocationAddress(RE) & MachO::R_SCATTERED;
Rafael Espindola56f976f2013-04-18 18:08:55 +00002382}
2383
Eric Christopher1d62c252013-07-22 22:25:07 +00002384unsigned MachOObjectFile::getPlainRelocationSymbolNum(
Charles Davis8bdfafd2013-09-01 04:28:48 +00002385 const MachO::any_relocation_info &RE) const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00002386 if (isLittleEndian())
Charles Davis8bdfafd2013-09-01 04:28:48 +00002387 return RE.r_word1 & 0xffffff;
2388 return RE.r_word1 >> 8;
Rafael Espindola56f976f2013-04-18 18:08:55 +00002389}
2390
Eric Christopher1d62c252013-07-22 22:25:07 +00002391bool MachOObjectFile::getPlainRelocationExternal(
Charles Davis8bdfafd2013-09-01 04:28:48 +00002392 const MachO::any_relocation_info &RE) const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00002393 if (isLittleEndian())
Charles Davis8bdfafd2013-09-01 04:28:48 +00002394 return (RE.r_word1 >> 27) & 1;
2395 return (RE.r_word1 >> 4) & 1;
Rafael Espindola56f976f2013-04-18 18:08:55 +00002396}
2397
Eric Christopher1d62c252013-07-22 22:25:07 +00002398bool MachOObjectFile::getScatteredRelocationScattered(
Charles Davis8bdfafd2013-09-01 04:28:48 +00002399 const MachO::any_relocation_info &RE) const {
2400 return RE.r_word0 >> 31;
Rafael Espindola56f976f2013-04-18 18:08:55 +00002401}
2402
Eric Christopher1d62c252013-07-22 22:25:07 +00002403uint32_t MachOObjectFile::getScatteredRelocationValue(
Charles Davis8bdfafd2013-09-01 04:28:48 +00002404 const MachO::any_relocation_info &RE) const {
2405 return RE.r_word1;
Rafael Espindola56f976f2013-04-18 18:08:55 +00002406}
2407
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002408uint32_t MachOObjectFile::getScatteredRelocationType(
2409 const MachO::any_relocation_info &RE) const {
2410 return (RE.r_word0 >> 24) & 0xf;
2411}
2412
Eric Christopher1d62c252013-07-22 22:25:07 +00002413unsigned MachOObjectFile::getAnyRelocationAddress(
Charles Davis8bdfafd2013-09-01 04:28:48 +00002414 const MachO::any_relocation_info &RE) const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00002415 if (isRelocationScattered(RE))
2416 return getScatteredRelocationAddress(RE);
2417 return getPlainRelocationAddress(RE);
2418}
2419
Charles Davis8bdfafd2013-09-01 04:28:48 +00002420unsigned MachOObjectFile::getAnyRelocationPCRel(
2421 const MachO::any_relocation_info &RE) const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00002422 if (isRelocationScattered(RE))
2423 return getScatteredRelocationPCRel(this, RE);
2424 return getPlainRelocationPCRel(this, RE);
2425}
2426
Eric Christopher1d62c252013-07-22 22:25:07 +00002427unsigned MachOObjectFile::getAnyRelocationLength(
Charles Davis8bdfafd2013-09-01 04:28:48 +00002428 const MachO::any_relocation_info &RE) const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00002429 if (isRelocationScattered(RE))
2430 return getScatteredRelocationLength(RE);
2431 return getPlainRelocationLength(this, RE);
2432}
2433
2434unsigned
Charles Davis8bdfafd2013-09-01 04:28:48 +00002435MachOObjectFile::getAnyRelocationType(
2436 const MachO::any_relocation_info &RE) const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00002437 if (isRelocationScattered(RE))
2438 return getScatteredRelocationType(RE);
2439 return getPlainRelocationType(this, RE);
2440}
2441
Rafael Espindola52501032013-04-30 15:40:54 +00002442SectionRef
Keno Fischerc780e8e2015-05-21 21:24:32 +00002443MachOObjectFile::getAnyRelocationSection(
Charles Davis8bdfafd2013-09-01 04:28:48 +00002444 const MachO::any_relocation_info &RE) const {
Rafael Espindola52501032013-04-30 15:40:54 +00002445 if (isRelocationScattered(RE) || getPlainRelocationExternal(RE))
Rafael Espindolab5155a52014-02-10 20:24:04 +00002446 return *section_end();
Rafael Espindola9ac06a02015-06-18 22:38:20 +00002447 unsigned SecNum = getPlainRelocationSymbolNum(RE);
2448 if (SecNum == MachO::R_ABS || SecNum > Sections.size())
2449 return *section_end();
Rafael Espindola52501032013-04-30 15:40:54 +00002450 DataRefImpl DRI;
Rafael Espindola9ac06a02015-06-18 22:38:20 +00002451 DRI.d.a = SecNum - 1;
Rafael Espindola52501032013-04-30 15:40:54 +00002452 return SectionRef(DRI, this);
2453}
2454
Charles Davis8bdfafd2013-09-01 04:28:48 +00002455MachO::section MachOObjectFile::getSection(DataRefImpl DRI) const {
Rafael Espindola62a07cb2015-05-22 15:43:00 +00002456 assert(DRI.d.a < Sections.size() && "Should have detected this earlier");
Charles Davis8bdfafd2013-09-01 04:28:48 +00002457 return getStruct<MachO::section>(this, Sections[DRI.d.a]);
Rafael Espindola56f976f2013-04-18 18:08:55 +00002458}
2459
Charles Davis8bdfafd2013-09-01 04:28:48 +00002460MachO::section_64 MachOObjectFile::getSection64(DataRefImpl DRI) const {
Rafael Espindola62a07cb2015-05-22 15:43:00 +00002461 assert(DRI.d.a < Sections.size() && "Should have detected this earlier");
Charles Davis8bdfafd2013-09-01 04:28:48 +00002462 return getStruct<MachO::section_64>(this, Sections[DRI.d.a]);
Rafael Espindola56f976f2013-04-18 18:08:55 +00002463}
2464
Charles Davis8bdfafd2013-09-01 04:28:48 +00002465MachO::section MachOObjectFile::getSection(const LoadCommandInfo &L,
Rafael Espindola6e040c02013-04-26 20:07:33 +00002466 unsigned Index) const {
2467 const char *Sec = getSectionPtr(this, L, Index);
Charles Davis8bdfafd2013-09-01 04:28:48 +00002468 return getStruct<MachO::section>(this, Sec);
Rafael Espindola6e040c02013-04-26 20:07:33 +00002469}
2470
Charles Davis8bdfafd2013-09-01 04:28:48 +00002471MachO::section_64 MachOObjectFile::getSection64(const LoadCommandInfo &L,
2472 unsigned Index) const {
Rafael Espindola6e040c02013-04-26 20:07:33 +00002473 const char *Sec = getSectionPtr(this, L, Index);
Charles Davis8bdfafd2013-09-01 04:28:48 +00002474 return getStruct<MachO::section_64>(this, Sec);
Rafael Espindola6e040c02013-04-26 20:07:33 +00002475}
2476
Charles Davis8bdfafd2013-09-01 04:28:48 +00002477MachO::nlist
Rafael Espindola56f976f2013-04-18 18:08:55 +00002478MachOObjectFile::getSymbolTableEntry(DataRefImpl DRI) const {
Rafael Espindola75c30362013-04-24 19:47:55 +00002479 const char *P = reinterpret_cast<const char *>(DRI.p);
Charles Davis8bdfafd2013-09-01 04:28:48 +00002480 return getStruct<MachO::nlist>(this, P);
Rafael Espindola56f976f2013-04-18 18:08:55 +00002481}
2482
Charles Davis8bdfafd2013-09-01 04:28:48 +00002483MachO::nlist_64
Rafael Espindola56f976f2013-04-18 18:08:55 +00002484MachOObjectFile::getSymbol64TableEntry(DataRefImpl DRI) const {
Rafael Espindola75c30362013-04-24 19:47:55 +00002485 const char *P = reinterpret_cast<const char *>(DRI.p);
Charles Davis8bdfafd2013-09-01 04:28:48 +00002486 return getStruct<MachO::nlist_64>(this, P);
Rafael Espindola56f976f2013-04-18 18:08:55 +00002487}
2488
Charles Davis8bdfafd2013-09-01 04:28:48 +00002489MachO::linkedit_data_command
2490MachOObjectFile::getLinkeditDataLoadCommand(const LoadCommandInfo &L) const {
2491 return getStruct<MachO::linkedit_data_command>(this, L.Ptr);
Rafael Espindola56f976f2013-04-18 18:08:55 +00002492}
2493
Charles Davis8bdfafd2013-09-01 04:28:48 +00002494MachO::segment_command
Rafael Espindola6e040c02013-04-26 20:07:33 +00002495MachOObjectFile::getSegmentLoadCommand(const LoadCommandInfo &L) const {
Charles Davis8bdfafd2013-09-01 04:28:48 +00002496 return getStruct<MachO::segment_command>(this, L.Ptr);
Rafael Espindola6e040c02013-04-26 20:07:33 +00002497}
2498
Charles Davis8bdfafd2013-09-01 04:28:48 +00002499MachO::segment_command_64
Rafael Espindola6e040c02013-04-26 20:07:33 +00002500MachOObjectFile::getSegment64LoadCommand(const LoadCommandInfo &L) const {
Charles Davis8bdfafd2013-09-01 04:28:48 +00002501 return getStruct<MachO::segment_command_64>(this, L.Ptr);
Rafael Espindola6e040c02013-04-26 20:07:33 +00002502}
2503
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00002504MachO::linker_option_command
2505MachOObjectFile::getLinkerOptionLoadCommand(const LoadCommandInfo &L) const {
2506 return getStruct<MachO::linker_option_command>(this, L.Ptr);
Rafael Espindola6e040c02013-04-26 20:07:33 +00002507}
2508
Jim Grosbach448334a2014-03-18 22:09:05 +00002509MachO::version_min_command
2510MachOObjectFile::getVersionMinLoadCommand(const LoadCommandInfo &L) const {
2511 return getStruct<MachO::version_min_command>(this, L.Ptr);
2512}
2513
Tim Northover8f9590b2014-06-30 14:40:57 +00002514MachO::dylib_command
2515MachOObjectFile::getDylibIDLoadCommand(const LoadCommandInfo &L) const {
2516 return getStruct<MachO::dylib_command>(this, L.Ptr);
2517}
2518
Kevin Enderby8ae63c12014-09-04 16:54:47 +00002519MachO::dyld_info_command
2520MachOObjectFile::getDyldInfoLoadCommand(const LoadCommandInfo &L) const {
2521 return getStruct<MachO::dyld_info_command>(this, L.Ptr);
2522}
2523
2524MachO::dylinker_command
2525MachOObjectFile::getDylinkerCommand(const LoadCommandInfo &L) const {
2526 return getStruct<MachO::dylinker_command>(this, L.Ptr);
2527}
2528
2529MachO::uuid_command
2530MachOObjectFile::getUuidCommand(const LoadCommandInfo &L) const {
2531 return getStruct<MachO::uuid_command>(this, L.Ptr);
2532}
2533
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00002534MachO::rpath_command
2535MachOObjectFile::getRpathCommand(const LoadCommandInfo &L) const {
2536 return getStruct<MachO::rpath_command>(this, L.Ptr);
2537}
2538
Kevin Enderby8ae63c12014-09-04 16:54:47 +00002539MachO::source_version_command
2540MachOObjectFile::getSourceVersionCommand(const LoadCommandInfo &L) const {
2541 return getStruct<MachO::source_version_command>(this, L.Ptr);
2542}
2543
2544MachO::entry_point_command
2545MachOObjectFile::getEntryPointCommand(const LoadCommandInfo &L) const {
2546 return getStruct<MachO::entry_point_command>(this, L.Ptr);
2547}
2548
Kevin Enderby0804f4672014-12-16 23:25:52 +00002549MachO::encryption_info_command
2550MachOObjectFile::getEncryptionInfoCommand(const LoadCommandInfo &L) const {
2551 return getStruct<MachO::encryption_info_command>(this, L.Ptr);
2552}
2553
Kevin Enderby57538292014-12-17 01:01:30 +00002554MachO::encryption_info_command_64
2555MachOObjectFile::getEncryptionInfoCommand64(const LoadCommandInfo &L) const {
2556 return getStruct<MachO::encryption_info_command_64>(this, L.Ptr);
2557}
2558
Kevin Enderbyb4b79312014-12-18 19:24:35 +00002559MachO::sub_framework_command
2560MachOObjectFile::getSubFrameworkCommand(const LoadCommandInfo &L) const {
2561 return getStruct<MachO::sub_framework_command>(this, L.Ptr);
2562}
Tim Northover8f9590b2014-06-30 14:40:57 +00002563
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00002564MachO::sub_umbrella_command
2565MachOObjectFile::getSubUmbrellaCommand(const LoadCommandInfo &L) const {
2566 return getStruct<MachO::sub_umbrella_command>(this, L.Ptr);
2567}
2568
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00002569MachO::sub_library_command
2570MachOObjectFile::getSubLibraryCommand(const LoadCommandInfo &L) const {
2571 return getStruct<MachO::sub_library_command>(this, L.Ptr);
2572}
2573
Kevin Enderby186eac32014-12-19 21:06:24 +00002574MachO::sub_client_command
2575MachOObjectFile::getSubClientCommand(const LoadCommandInfo &L) const {
2576 return getStruct<MachO::sub_client_command>(this, L.Ptr);
2577}
2578
Kevin Enderby52e4ce42014-12-19 22:25:22 +00002579MachO::routines_command
2580MachOObjectFile::getRoutinesCommand(const LoadCommandInfo &L) const {
2581 return getStruct<MachO::routines_command>(this, L.Ptr);
2582}
2583
2584MachO::routines_command_64
2585MachOObjectFile::getRoutinesCommand64(const LoadCommandInfo &L) const {
2586 return getStruct<MachO::routines_command_64>(this, L.Ptr);
2587}
2588
Kevin Enderby48ef5342014-12-23 22:56:39 +00002589MachO::thread_command
2590MachOObjectFile::getThreadCommand(const LoadCommandInfo &L) const {
2591 return getStruct<MachO::thread_command>(this, L.Ptr);
2592}
2593
Charles Davis8bdfafd2013-09-01 04:28:48 +00002594MachO::any_relocation_info
Rafael Espindola56f976f2013-04-18 18:08:55 +00002595MachOObjectFile::getRelocation(DataRefImpl Rel) const {
Rafael Espindola128b8112014-04-03 23:51:28 +00002596 DataRefImpl Sec;
2597 Sec.d.a = Rel.d.a;
2598 uint32_t Offset;
2599 if (is64Bit()) {
2600 MachO::section_64 Sect = getSection64(Sec);
2601 Offset = Sect.reloff;
2602 } else {
2603 MachO::section Sect = getSection(Sec);
2604 Offset = Sect.reloff;
2605 }
2606
2607 auto P = reinterpret_cast<const MachO::any_relocation_info *>(
2608 getPtr(this, Offset)) + Rel.d.b;
2609 return getStruct<MachO::any_relocation_info>(
2610 this, reinterpret_cast<const char *>(P));
Rafael Espindola56f976f2013-04-18 18:08:55 +00002611}
2612
Charles Davis8bdfafd2013-09-01 04:28:48 +00002613MachO::data_in_code_entry
Kevin Enderby273ae012013-06-06 17:20:50 +00002614MachOObjectFile::getDice(DataRefImpl Rel) const {
2615 const char *P = reinterpret_cast<const char *>(Rel.p);
Charles Davis8bdfafd2013-09-01 04:28:48 +00002616 return getStruct<MachO::data_in_code_entry>(this, P);
Kevin Enderby273ae012013-06-06 17:20:50 +00002617}
2618
Alexey Samsonov13415ed2015-06-04 19:22:03 +00002619const MachO::mach_header &MachOObjectFile::getHeader() const {
Alexey Samsonovfa5edc52015-06-04 22:49:55 +00002620 return Header;
Rafael Espindola56f976f2013-04-18 18:08:55 +00002621}
2622
Alexey Samsonov13415ed2015-06-04 19:22:03 +00002623const MachO::mach_header_64 &MachOObjectFile::getHeader64() const {
2624 assert(is64Bit());
2625 return Header64;
Rafael Espindola6e040c02013-04-26 20:07:33 +00002626}
2627
Charles Davis8bdfafd2013-09-01 04:28:48 +00002628uint32_t MachOObjectFile::getIndirectSymbolTableEntry(
2629 const MachO::dysymtab_command &DLC,
2630 unsigned Index) const {
2631 uint64_t Offset = DLC.indirectsymoff + Index * sizeof(uint32_t);
2632 return getStruct<uint32_t>(this, getPtr(this, Offset));
Rafael Espindola6e040c02013-04-26 20:07:33 +00002633}
2634
Charles Davis8bdfafd2013-09-01 04:28:48 +00002635MachO::data_in_code_entry
Rafael Espindola6e040c02013-04-26 20:07:33 +00002636MachOObjectFile::getDataInCodeTableEntry(uint32_t DataOffset,
2637 unsigned Index) const {
Charles Davis8bdfafd2013-09-01 04:28:48 +00002638 uint64_t Offset = DataOffset + Index * sizeof(MachO::data_in_code_entry);
2639 return getStruct<MachO::data_in_code_entry>(this, getPtr(this, Offset));
Rafael Espindola6e040c02013-04-26 20:07:33 +00002640}
2641
Charles Davis8bdfafd2013-09-01 04:28:48 +00002642MachO::symtab_command MachOObjectFile::getSymtabLoadCommand() const {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002643 if (SymtabLoadCmd)
2644 return getStruct<MachO::symtab_command>(this, SymtabLoadCmd);
2645
2646 // If there is no SymtabLoadCmd return a load command with zero'ed fields.
2647 MachO::symtab_command Cmd;
2648 Cmd.cmd = MachO::LC_SYMTAB;
2649 Cmd.cmdsize = sizeof(MachO::symtab_command);
2650 Cmd.symoff = 0;
2651 Cmd.nsyms = 0;
2652 Cmd.stroff = 0;
2653 Cmd.strsize = 0;
2654 return Cmd;
Rafael Espindola56f976f2013-04-18 18:08:55 +00002655}
2656
Charles Davis8bdfafd2013-09-01 04:28:48 +00002657MachO::dysymtab_command MachOObjectFile::getDysymtabLoadCommand() const {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002658 if (DysymtabLoadCmd)
2659 return getStruct<MachO::dysymtab_command>(this, DysymtabLoadCmd);
2660
2661 // If there is no DysymtabLoadCmd return a load command with zero'ed fields.
2662 MachO::dysymtab_command Cmd;
2663 Cmd.cmd = MachO::LC_DYSYMTAB;
2664 Cmd.cmdsize = sizeof(MachO::dysymtab_command);
2665 Cmd.ilocalsym = 0;
2666 Cmd.nlocalsym = 0;
2667 Cmd.iextdefsym = 0;
2668 Cmd.nextdefsym = 0;
2669 Cmd.iundefsym = 0;
2670 Cmd.nundefsym = 0;
2671 Cmd.tocoff = 0;
2672 Cmd.ntoc = 0;
2673 Cmd.modtaboff = 0;
2674 Cmd.nmodtab = 0;
2675 Cmd.extrefsymoff = 0;
2676 Cmd.nextrefsyms = 0;
2677 Cmd.indirectsymoff = 0;
2678 Cmd.nindirectsyms = 0;
2679 Cmd.extreloff = 0;
2680 Cmd.nextrel = 0;
2681 Cmd.locreloff = 0;
2682 Cmd.nlocrel = 0;
2683 return Cmd;
Rafael Espindola6e040c02013-04-26 20:07:33 +00002684}
2685
Charles Davis8bdfafd2013-09-01 04:28:48 +00002686MachO::linkedit_data_command
Kevin Enderby273ae012013-06-06 17:20:50 +00002687MachOObjectFile::getDataInCodeLoadCommand() const {
2688 if (DataInCodeLoadCmd)
Charles Davis8bdfafd2013-09-01 04:28:48 +00002689 return getStruct<MachO::linkedit_data_command>(this, DataInCodeLoadCmd);
Kevin Enderby273ae012013-06-06 17:20:50 +00002690
2691 // If there is no DataInCodeLoadCmd return a load command with zero'ed fields.
Charles Davis8bdfafd2013-09-01 04:28:48 +00002692 MachO::linkedit_data_command Cmd;
2693 Cmd.cmd = MachO::LC_DATA_IN_CODE;
2694 Cmd.cmdsize = sizeof(MachO::linkedit_data_command);
2695 Cmd.dataoff = 0;
2696 Cmd.datasize = 0;
Kevin Enderby273ae012013-06-06 17:20:50 +00002697 return Cmd;
2698}
2699
Kevin Enderby9a509442015-01-27 21:28:24 +00002700MachO::linkedit_data_command
2701MachOObjectFile::getLinkOptHintsLoadCommand() const {
2702 if (LinkOptHintsLoadCmd)
2703 return getStruct<MachO::linkedit_data_command>(this, LinkOptHintsLoadCmd);
2704
2705 // If there is no LinkOptHintsLoadCmd return a load command with zero'ed
2706 // fields.
2707 MachO::linkedit_data_command Cmd;
2708 Cmd.cmd = MachO::LC_LINKER_OPTIMIZATION_HINT;
2709 Cmd.cmdsize = sizeof(MachO::linkedit_data_command);
2710 Cmd.dataoff = 0;
2711 Cmd.datasize = 0;
2712 return Cmd;
2713}
2714
Nick Kledzikd04bc352014-08-30 00:20:14 +00002715ArrayRef<uint8_t> MachOObjectFile::getDyldInfoRebaseOpcodes() const {
NAKAMURA Takumi10c80e72015-09-22 11:19:03 +00002716 if (!DyldInfoLoadCmd)
Craig Topper0013be12015-09-21 05:32:41 +00002717 return None;
Nick Kledzikd04bc352014-08-30 00:20:14 +00002718
NAKAMURA Takumi70ad98a2015-09-22 11:13:55 +00002719 MachO::dyld_info_command DyldInfo =
2720 getStruct<MachO::dyld_info_command>(this, DyldInfoLoadCmd);
2721 const uint8_t *Ptr =
2722 reinterpret_cast<const uint8_t *>(getPtr(this, DyldInfo.rebase_off));
Craig Topper0013be12015-09-21 05:32:41 +00002723 return makeArrayRef(Ptr, DyldInfo.rebase_size);
Nick Kledzikd04bc352014-08-30 00:20:14 +00002724}
2725
2726ArrayRef<uint8_t> MachOObjectFile::getDyldInfoBindOpcodes() const {
NAKAMURA Takumi10c80e72015-09-22 11:19:03 +00002727 if (!DyldInfoLoadCmd)
Craig Topper0013be12015-09-21 05:32:41 +00002728 return None;
Nick Kledzikd04bc352014-08-30 00:20:14 +00002729
NAKAMURA Takumi70ad98a2015-09-22 11:13:55 +00002730 MachO::dyld_info_command DyldInfo =
2731 getStruct<MachO::dyld_info_command>(this, DyldInfoLoadCmd);
2732 const uint8_t *Ptr =
2733 reinterpret_cast<const uint8_t *>(getPtr(this, DyldInfo.bind_off));
Craig Topper0013be12015-09-21 05:32:41 +00002734 return makeArrayRef(Ptr, DyldInfo.bind_size);
Nick Kledzikd04bc352014-08-30 00:20:14 +00002735}
2736
2737ArrayRef<uint8_t> MachOObjectFile::getDyldInfoWeakBindOpcodes() const {
NAKAMURA Takumi10c80e72015-09-22 11:19:03 +00002738 if (!DyldInfoLoadCmd)
Craig Topper0013be12015-09-21 05:32:41 +00002739 return None;
Nick Kledzikd04bc352014-08-30 00:20:14 +00002740
NAKAMURA Takumi70ad98a2015-09-22 11:13:55 +00002741 MachO::dyld_info_command DyldInfo =
2742 getStruct<MachO::dyld_info_command>(this, DyldInfoLoadCmd);
2743 const uint8_t *Ptr =
2744 reinterpret_cast<const uint8_t *>(getPtr(this, DyldInfo.weak_bind_off));
Craig Topper0013be12015-09-21 05:32:41 +00002745 return makeArrayRef(Ptr, DyldInfo.weak_bind_size);
Nick Kledzikd04bc352014-08-30 00:20:14 +00002746}
2747
2748ArrayRef<uint8_t> MachOObjectFile::getDyldInfoLazyBindOpcodes() const {
NAKAMURA Takumi10c80e72015-09-22 11:19:03 +00002749 if (!DyldInfoLoadCmd)
Craig Topper0013be12015-09-21 05:32:41 +00002750 return None;
Nick Kledzikd04bc352014-08-30 00:20:14 +00002751
NAKAMURA Takumi70ad98a2015-09-22 11:13:55 +00002752 MachO::dyld_info_command DyldInfo =
2753 getStruct<MachO::dyld_info_command>(this, DyldInfoLoadCmd);
2754 const uint8_t *Ptr =
2755 reinterpret_cast<const uint8_t *>(getPtr(this, DyldInfo.lazy_bind_off));
Craig Topper0013be12015-09-21 05:32:41 +00002756 return makeArrayRef(Ptr, DyldInfo.lazy_bind_size);
Nick Kledzikd04bc352014-08-30 00:20:14 +00002757}
2758
2759ArrayRef<uint8_t> MachOObjectFile::getDyldInfoExportsTrie() const {
NAKAMURA Takumi10c80e72015-09-22 11:19:03 +00002760 if (!DyldInfoLoadCmd)
Craig Topper0013be12015-09-21 05:32:41 +00002761 return None;
Nick Kledzikd04bc352014-08-30 00:20:14 +00002762
NAKAMURA Takumi70ad98a2015-09-22 11:13:55 +00002763 MachO::dyld_info_command DyldInfo =
2764 getStruct<MachO::dyld_info_command>(this, DyldInfoLoadCmd);
2765 const uint8_t *Ptr =
2766 reinterpret_cast<const uint8_t *>(getPtr(this, DyldInfo.export_off));
Craig Topper0013be12015-09-21 05:32:41 +00002767 return makeArrayRef(Ptr, DyldInfo.export_size);
Nick Kledzikd04bc352014-08-30 00:20:14 +00002768}
2769
Alexander Potapenko6909b5b2014-10-15 23:35:45 +00002770ArrayRef<uint8_t> MachOObjectFile::getUuid() const {
2771 if (!UuidLoadCmd)
Craig Topper0013be12015-09-21 05:32:41 +00002772 return None;
Benjamin Kramer014601d2014-10-24 15:52:05 +00002773 // Returning a pointer is fine as uuid doesn't need endian swapping.
2774 const char *Ptr = UuidLoadCmd + offsetof(MachO::uuid_command, uuid);
Craig Topper0013be12015-09-21 05:32:41 +00002775 return makeArrayRef(reinterpret_cast<const uint8_t *>(Ptr), 16);
Alexander Potapenko6909b5b2014-10-15 23:35:45 +00002776}
Nick Kledzikd04bc352014-08-30 00:20:14 +00002777
Rafael Espindola6e040c02013-04-26 20:07:33 +00002778StringRef MachOObjectFile::getStringTableData() const {
Charles Davis8bdfafd2013-09-01 04:28:48 +00002779 MachO::symtab_command S = getSymtabLoadCommand();
2780 return getData().substr(S.stroff, S.strsize);
Rafael Espindola6e040c02013-04-26 20:07:33 +00002781}
2782
Rafael Espindola56f976f2013-04-18 18:08:55 +00002783bool MachOObjectFile::is64Bit() const {
2784 return getType() == getMachOType(false, true) ||
Lang Hames84bc8182014-07-15 19:35:22 +00002785 getType() == getMachOType(true, true);
Rafael Espindola56f976f2013-04-18 18:08:55 +00002786}
2787
2788void MachOObjectFile::ReadULEB128s(uint64_t Index,
2789 SmallVectorImpl<uint64_t> &Out) const {
2790 DataExtractor extractor(ObjectFile::getData(), true, 0);
2791
2792 uint32_t offset = Index;
2793 uint64_t data = 0;
2794 while (uint64_t delta = extractor.getULEB128(&offset)) {
2795 data += delta;
2796 Out.push_back(data);
2797 }
2798}
2799
Rafael Espindolac66d7612014-08-17 19:09:37 +00002800bool MachOObjectFile::isRelocatableObject() const {
2801 return getHeader().filetype == MachO::MH_OBJECT;
2802}
2803
Lang Hamesff044b12016-03-25 23:11:52 +00002804Expected<std::unique_ptr<MachOObjectFile>>
Rafael Espindola48af1c22014-08-19 18:44:46 +00002805ObjectFile::createMachOObjectFile(MemoryBufferRef Buffer) {
2806 StringRef Magic = Buffer.getBuffer().slice(0, 4);
Lang Hames82627642016-03-25 21:59:14 +00002807 if (Magic == "\xFE\xED\xFA\xCE")
Lang Hamesff044b12016-03-25 23:11:52 +00002808 return MachOObjectFile::create(Buffer, false, false);
David Blaikieb805f732016-03-28 17:45:48 +00002809 if (Magic == "\xCE\xFA\xED\xFE")
Lang Hamesff044b12016-03-25 23:11:52 +00002810 return MachOObjectFile::create(Buffer, true, false);
David Blaikieb805f732016-03-28 17:45:48 +00002811 if (Magic == "\xFE\xED\xFA\xCF")
Lang Hamesff044b12016-03-25 23:11:52 +00002812 return MachOObjectFile::create(Buffer, false, true);
David Blaikieb805f732016-03-28 17:45:48 +00002813 if (Magic == "\xCF\xFA\xED\xFE")
Lang Hamesff044b12016-03-25 23:11:52 +00002814 return MachOObjectFile::create(Buffer, true, true);
Kevin Enderbyd4e075b2016-05-06 20:16:28 +00002815 return make_error<GenericBinaryError>("Unrecognized MachO magic number",
Justin Bogner2a42da92016-05-05 23:59:57 +00002816 object_error::invalid_file_type);
Rafael Espindola56f976f2013-04-18 18:08:55 +00002817}