blob: bb914eea29badd0c1abae850d9dab3cecea227dc [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
Alexey Samsonov9f336632015-06-04 19:45:22 +000041// FIXME: Replace all uses of this function with getStructOrErr.
Filipe Cabecinhas40139502015-01-15 22:52:38 +000042template <typename T>
Artyom Skrobov7d602f72014-07-20 12:08:28 +000043static T getStruct(const MachOObjectFile *O, const char *P) {
Filipe Cabecinhas40139502015-01-15 22:52:38 +000044 // Don't read before the beginning or past the end of the file
45 if (P < O->getData().begin() || P + sizeof(T) > O->getData().end())
46 report_fatal_error("Malformed MachO file.");
47
Rafael Espindola3cdeb172013-04-19 13:45:05 +000048 T Cmd;
49 memcpy(&Cmd, P, sizeof(T));
50 if (O->isLittleEndian() != sys::IsLittleEndianHost)
Artyom Skrobov78d5daf2014-07-18 09:26:16 +000051 MachO::swapStruct(Cmd);
Rafael Espindola3cdeb172013-04-19 13:45:05 +000052 return Cmd;
Rafael Espindola56f976f2013-04-18 18:08:55 +000053}
54
Alexey Samsonov9f336632015-06-04 19:45:22 +000055template <typename T>
56static ErrorOr<T> getStructOrErr(const MachOObjectFile *O, const char *P) {
57 // Don't read before the beginning or past the end of the file
58 if (P < O->getData().begin() || P + sizeof(T) > O->getData().end())
59 return object_error::parse_failed;
60
61 T Cmd;
62 memcpy(&Cmd, P, sizeof(T));
63 if (O->isLittleEndian() != sys::IsLittleEndianHost)
64 MachO::swapStruct(Cmd);
65 return Cmd;
66}
67
Rafael Espindola6e040c02013-04-26 20:07:33 +000068static const char *
69getSectionPtr(const MachOObjectFile *O, MachOObjectFile::LoadCommandInfo L,
70 unsigned Sec) {
Rafael Espindola56f976f2013-04-18 18:08:55 +000071 uintptr_t CommandAddr = reinterpret_cast<uintptr_t>(L.Ptr);
72
73 bool Is64 = O->is64Bit();
Charles Davis8bdfafd2013-09-01 04:28:48 +000074 unsigned SegmentLoadSize = Is64 ? sizeof(MachO::segment_command_64) :
75 sizeof(MachO::segment_command);
76 unsigned SectionSize = Is64 ? sizeof(MachO::section_64) :
77 sizeof(MachO::section);
Rafael Espindola56f976f2013-04-18 18:08:55 +000078
79 uintptr_t SectionAddr = CommandAddr + SegmentLoadSize + Sec * SectionSize;
Charles Davis1827bd82013-08-27 05:38:30 +000080 return reinterpret_cast<const char*>(SectionAddr);
Rafael Espindola60689982013-04-07 19:05:30 +000081}
82
Rafael Espindola56f976f2013-04-18 18:08:55 +000083static const char *getPtr(const MachOObjectFile *O, size_t Offset) {
84 return O->getData().substr(Offset, 1).data();
Rafael Espindola60689982013-04-07 19:05:30 +000085}
86
Artyom Skrobov78d5daf2014-07-18 09:26:16 +000087static MachO::nlist_base
Rafael Espindola56f976f2013-04-18 18:08:55 +000088getSymbolTableEntryBase(const MachOObjectFile *O, DataRefImpl DRI) {
Rafael Espindola75c30362013-04-24 19:47:55 +000089 const char *P = reinterpret_cast<const char *>(DRI.p);
Artyom Skrobov78d5daf2014-07-18 09:26:16 +000090 return getStruct<MachO::nlist_base>(O, P);
Eric Christopher7b015c72011-04-22 03:19:48 +000091}
92
Rafael Espindola56f976f2013-04-18 18:08:55 +000093static StringRef parseSegmentOrSectionName(const char *P) {
Rafael Espindolaa9f810b2012-12-21 03:47:03 +000094 if (P[15] == 0)
95 // Null terminated.
96 return P;
97 // Not null terminated, so this is a 16 char string.
98 return StringRef(P, 16);
99}
100
Rafael Espindola56f976f2013-04-18 18:08:55 +0000101// Helper to advance a section or symbol iterator multiple increments at a time.
102template<class T>
Rafael Espindola5e812af2014-01-30 02:49:50 +0000103static void advance(T &it, size_t Val) {
104 while (Val--)
105 ++it;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000106}
107
108static unsigned getCPUType(const MachOObjectFile *O) {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000109 return O->getHeader().cputype;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000110}
111
Charles Davis8bdfafd2013-09-01 04:28:48 +0000112static uint32_t
113getPlainRelocationAddress(const MachO::any_relocation_info &RE) {
114 return RE.r_word0;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000115}
116
117static unsigned
Charles Davis8bdfafd2013-09-01 04:28:48 +0000118getScatteredRelocationAddress(const MachO::any_relocation_info &RE) {
119 return RE.r_word0 & 0xffffff;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000120}
121
122static bool getPlainRelocationPCRel(const MachOObjectFile *O,
Charles Davis8bdfafd2013-09-01 04:28:48 +0000123 const MachO::any_relocation_info &RE) {
Rafael Espindola56f976f2013-04-18 18:08:55 +0000124 if (O->isLittleEndian())
Charles Davis8bdfafd2013-09-01 04:28:48 +0000125 return (RE.r_word1 >> 24) & 1;
126 return (RE.r_word1 >> 7) & 1;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000127}
128
129static bool
130getScatteredRelocationPCRel(const MachOObjectFile *O,
Charles Davis8bdfafd2013-09-01 04:28:48 +0000131 const MachO::any_relocation_info &RE) {
132 return (RE.r_word0 >> 30) & 1;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000133}
134
135static unsigned getPlainRelocationLength(const MachOObjectFile *O,
Charles Davis8bdfafd2013-09-01 04:28:48 +0000136 const MachO::any_relocation_info &RE) {
Rafael Espindola56f976f2013-04-18 18:08:55 +0000137 if (O->isLittleEndian())
Charles Davis8bdfafd2013-09-01 04:28:48 +0000138 return (RE.r_word1 >> 25) & 3;
139 return (RE.r_word1 >> 5) & 3;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000140}
141
142static unsigned
Charles Davis8bdfafd2013-09-01 04:28:48 +0000143getScatteredRelocationLength(const MachO::any_relocation_info &RE) {
144 return (RE.r_word0 >> 28) & 3;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000145}
146
147static unsigned getPlainRelocationType(const MachOObjectFile *O,
Charles Davis8bdfafd2013-09-01 04:28:48 +0000148 const MachO::any_relocation_info &RE) {
Rafael Espindola56f976f2013-04-18 18:08:55 +0000149 if (O->isLittleEndian())
Charles Davis8bdfafd2013-09-01 04:28:48 +0000150 return RE.r_word1 >> 28;
151 return RE.r_word1 & 0xf;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000152}
153
Rafael Espindola56f976f2013-04-18 18:08:55 +0000154static uint32_t getSectionFlags(const MachOObjectFile *O,
155 DataRefImpl Sec) {
156 if (O->is64Bit()) {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000157 MachO::section_64 Sect = O->getSection64(Sec);
158 return Sect.flags;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000159 }
Charles Davis8bdfafd2013-09-01 04:28:48 +0000160 MachO::section Sect = O->getSection(Sec);
161 return Sect.flags;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000162}
163
Alexey Samsonovde5a94a2015-06-04 19:57:46 +0000164static ErrorOr<MachOObjectFile::LoadCommandInfo>
Alexey Samsonov4fdbed32015-06-04 19:34:14 +0000165getLoadCommandInfo(const MachOObjectFile *Obj, const char *Ptr) {
Alexey Samsonovde5a94a2015-06-04 19:57:46 +0000166 auto CmdOrErr = getStructOrErr<MachO::load_command>(Obj, Ptr);
167 if (!CmdOrErr)
168 return CmdOrErr.getError();
169 if (CmdOrErr->cmdsize < 8)
170 return object_error::macho_small_load_command;
Alexey Samsonov4fdbed32015-06-04 19:34:14 +0000171 MachOObjectFile::LoadCommandInfo Load;
172 Load.Ptr = Ptr;
Alexey Samsonovde5a94a2015-06-04 19:57:46 +0000173 Load.C = CmdOrErr.get();
Alexey Samsonov4fdbed32015-06-04 19:34:14 +0000174 return Load;
175}
176
Alexey Samsonovde5a94a2015-06-04 19:57:46 +0000177static ErrorOr<MachOObjectFile::LoadCommandInfo>
Alexey Samsonov4fdbed32015-06-04 19:34:14 +0000178getFirstLoadCommandInfo(const MachOObjectFile *Obj) {
179 unsigned HeaderSize = Obj->is64Bit() ? sizeof(MachO::mach_header_64)
180 : sizeof(MachO::mach_header);
181 return getLoadCommandInfo(Obj, getPtr(Obj, HeaderSize));
182}
183
Alexey Samsonovde5a94a2015-06-04 19:57:46 +0000184static ErrorOr<MachOObjectFile::LoadCommandInfo>
Alexey Samsonov4fdbed32015-06-04 19:34:14 +0000185getNextLoadCommandInfo(const MachOObjectFile *Obj,
186 const MachOObjectFile::LoadCommandInfo &L) {
187 return getLoadCommandInfo(Obj, L.Ptr + L.C.cmdsize);
188}
189
Alexey Samsonov9f336632015-06-04 19:45:22 +0000190template <typename T>
191static void parseHeader(const MachOObjectFile *Obj, T &Header,
192 std::error_code &EC) {
193 auto HeaderOrErr = getStructOrErr<T>(Obj, getPtr(Obj, 0));
194 if (HeaderOrErr)
195 Header = HeaderOrErr.get();
196 else
197 EC = HeaderOrErr.getError();
198}
199
Alexey Samsonove1a76ab2015-06-04 22:08:37 +0000200// Parses LC_SEGMENT or LC_SEGMENT_64 load command, adds addresses of all
201// sections to \param Sections, and optionally sets
202// \param IsPageZeroSegment to true.
203template <typename SegmentCmd>
204static std::error_code parseSegmentLoadCommand(
205 const MachOObjectFile *Obj, const MachOObjectFile::LoadCommandInfo &Load,
206 SmallVectorImpl<const char *> &Sections, bool &IsPageZeroSegment) {
207 const unsigned SegmentLoadSize = sizeof(SegmentCmd);
208 if (Load.C.cmdsize < SegmentLoadSize)
209 return object_error::macho_load_segment_too_small;
Alexey Samsonovf8a7bf82015-06-04 22:26:44 +0000210 auto SegOrErr = getStructOrErr<SegmentCmd>(Obj, Load.Ptr);
211 if (!SegOrErr)
212 return SegOrErr.getError();
213 SegmentCmd S = SegOrErr.get();
Alexey Samsonove1a76ab2015-06-04 22:08:37 +0000214 const unsigned SectionSize =
215 Obj->is64Bit() ? sizeof(MachO::section_64) : sizeof(MachO::section);
216 if (S.nsects > std::numeric_limits<uint32_t>::max() / SectionSize ||
217 S.nsects * SectionSize > Load.C.cmdsize - SegmentLoadSize)
218 return object_error::macho_load_segment_too_many_sections;
219 for (unsigned J = 0; J < S.nsects; ++J) {
220 const char *Sec = getSectionPtr(Obj, Load, J);
221 Sections.push_back(Sec);
222 }
223 IsPageZeroSegment |= StringRef("__PAGEZERO").equals(S.segname);
Rui Ueyama7d099192015-06-09 15:20:42 +0000224 return std::error_code();
Alexey Samsonove1a76ab2015-06-04 22:08:37 +0000225}
226
Rafael Espindola48af1c22014-08-19 18:44:46 +0000227MachOObjectFile::MachOObjectFile(MemoryBufferRef Object, bool IsLittleEndian,
228 bool Is64bits, std::error_code &EC)
229 : ObjectFile(getMachOType(IsLittleEndian, Is64bits), Object),
Craig Topper2617dcc2014-04-15 06:32:26 +0000230 SymtabLoadCmd(nullptr), DysymtabLoadCmd(nullptr),
Kevin Enderby9a509442015-01-27 21:28:24 +0000231 DataInCodeLoadCmd(nullptr), LinkOptHintsLoadCmd(nullptr),
232 DyldInfoLoadCmd(nullptr), UuidLoadCmd(nullptr),
233 HasPageZeroSegment(false) {
Alexey Samsonov13415ed2015-06-04 19:22:03 +0000234 if (is64Bit())
Alexey Samsonov9f336632015-06-04 19:45:22 +0000235 parseHeader(this, Header64, EC);
Alexey Samsonov13415ed2015-06-04 19:22:03 +0000236 else
Alexey Samsonovfa5edc52015-06-04 22:49:55 +0000237 parseHeader(this, Header, EC);
Alexey Samsonov9f336632015-06-04 19:45:22 +0000238 if (EC)
239 return;
Alexey Samsonov13415ed2015-06-04 19:22:03 +0000240
241 uint32_t LoadCommandCount = getHeader().ncmds;
Filipe Cabecinhase71bd0c2015-01-06 17:08:26 +0000242 if (LoadCommandCount == 0)
243 return;
244
Alexey Samsonovde5a94a2015-06-04 19:57:46 +0000245 auto LoadOrErr = getFirstLoadCommandInfo(this);
246 if (!LoadOrErr) {
247 EC = LoadOrErr.getError();
248 return;
249 }
250 LoadCommandInfo Load = LoadOrErr.get();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000251 for (unsigned I = 0; I < LoadCommandCount; ++I) {
252 LoadCommands.push_back(Load);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000253 if (Load.C.cmd == MachO::LC_SYMTAB) {
David Majnemer73cc6ff2014-11-13 19:48:56 +0000254 // Multiple symbol tables
255 if (SymtabLoadCmd) {
256 EC = object_error::parse_failed;
257 return;
258 }
Rafael Espindola56f976f2013-04-18 18:08:55 +0000259 SymtabLoadCmd = Load.Ptr;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000260 } else if (Load.C.cmd == MachO::LC_DYSYMTAB) {
David Majnemer73cc6ff2014-11-13 19:48:56 +0000261 // Multiple dynamic symbol tables
262 if (DysymtabLoadCmd) {
263 EC = object_error::parse_failed;
264 return;
265 }
Rafael Espindola6e040c02013-04-26 20:07:33 +0000266 DysymtabLoadCmd = Load.Ptr;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000267 } else if (Load.C.cmd == MachO::LC_DATA_IN_CODE) {
David Majnemer73cc6ff2014-11-13 19:48:56 +0000268 // Multiple data in code tables
269 if (DataInCodeLoadCmd) {
270 EC = object_error::parse_failed;
271 return;
272 }
Kevin Enderby273ae012013-06-06 17:20:50 +0000273 DataInCodeLoadCmd = Load.Ptr;
Kevin Enderby9a509442015-01-27 21:28:24 +0000274 } else if (Load.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
275 // Multiple linker optimization hint tables
276 if (LinkOptHintsLoadCmd) {
277 EC = object_error::parse_failed;
278 return;
279 }
280 LinkOptHintsLoadCmd = Load.Ptr;
Nick Kledzikd04bc352014-08-30 00:20:14 +0000281 } else if (Load.C.cmd == MachO::LC_DYLD_INFO ||
282 Load.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
David Majnemer73cc6ff2014-11-13 19:48:56 +0000283 // Multiple dyldinfo load commands
284 if (DyldInfoLoadCmd) {
285 EC = object_error::parse_failed;
286 return;
287 }
Nick Kledzikd04bc352014-08-30 00:20:14 +0000288 DyldInfoLoadCmd = Load.Ptr;
Alexander Potapenko6909b5b2014-10-15 23:35:45 +0000289 } else if (Load.C.cmd == MachO::LC_UUID) {
David Majnemer73cc6ff2014-11-13 19:48:56 +0000290 // Multiple UUID load commands
291 if (UuidLoadCmd) {
292 EC = object_error::parse_failed;
293 return;
294 }
Alexander Potapenko6909b5b2014-10-15 23:35:45 +0000295 UuidLoadCmd = Load.Ptr;
Alexey Samsonove1a76ab2015-06-04 22:08:37 +0000296 } else if (Load.C.cmd == MachO::LC_SEGMENT_64) {
297 if ((EC = parseSegmentLoadCommand<MachO::segment_command_64>(
298 this, Load, Sections, HasPageZeroSegment)))
Alexey Samsonov074da9b2015-06-04 20:08:52 +0000299 return;
Alexey Samsonove1a76ab2015-06-04 22:08:37 +0000300 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
301 if ((EC = parseSegmentLoadCommand<MachO::segment_command>(
302 this, Load, Sections, HasPageZeroSegment)))
Alexey Samsonov074da9b2015-06-04 20:08:52 +0000303 return;
Kevin Enderby980b2582014-06-05 21:21:57 +0000304 } else if (Load.C.cmd == MachO::LC_LOAD_DYLIB ||
305 Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
306 Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
307 Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
308 Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
309 Libraries.push_back(Load.Ptr);
Rafael Espindola56f976f2013-04-18 18:08:55 +0000310 }
Alexey Samsonovde5a94a2015-06-04 19:57:46 +0000311 if (I < LoadCommandCount - 1) {
312 auto LoadOrErr = getNextLoadCommandInfo(this, Load);
313 if (!LoadOrErr) {
314 EC = LoadOrErr.getError();
315 return;
316 }
317 Load = LoadOrErr.get();
318 }
Rafael Espindola56f976f2013-04-18 18:08:55 +0000319 }
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000320 assert(LoadCommands.size() == LoadCommandCount);
Rafael Espindola56f976f2013-04-18 18:08:55 +0000321}
322
Rafael Espindola5e812af2014-01-30 02:49:50 +0000323void MachOObjectFile::moveSymbolNext(DataRefImpl &Symb) const {
Rafael Espindola75c30362013-04-24 19:47:55 +0000324 unsigned SymbolTableEntrySize = is64Bit() ?
Charles Davis8bdfafd2013-09-01 04:28:48 +0000325 sizeof(MachO::nlist_64) :
326 sizeof(MachO::nlist);
Rafael Espindola75c30362013-04-24 19:47:55 +0000327 Symb.p += SymbolTableEntrySize;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000328}
329
Rafael Espindola3acea392014-06-12 21:46:39 +0000330std::error_code MachOObjectFile::getSymbolName(DataRefImpl Symb,
331 StringRef &Res) const {
Rafael Espindola6e040c02013-04-26 20:07:33 +0000332 StringRef StringTable = getStringTableData();
Artyom Skrobov78d5daf2014-07-18 09:26:16 +0000333 MachO::nlist_base Entry = getSymbolTableEntryBase(this, Symb);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000334 const char *Start = &StringTable.data()[Entry.n_strx];
Filipe Cabecinhasc552c9a2015-01-15 23:50:44 +0000335 if (Start < getData().begin() || Start >= getData().end())
336 report_fatal_error(
337 "Symbol name entry points before beginning or past end of file.");
Rafael Espindola56f976f2013-04-18 18:08:55 +0000338 Res = StringRef(Start);
Rui Ueyama7d099192015-06-09 15:20:42 +0000339 return std::error_code();
Rafael Espindola56f976f2013-04-18 18:08:55 +0000340}
341
Rafael Espindola0e77a942014-12-10 20:46:55 +0000342unsigned MachOObjectFile::getSectionType(SectionRef Sec) const {
343 DataRefImpl DRI = Sec.getRawDataRefImpl();
344 uint32_t Flags = getSectionFlags(this, DRI);
345 return Flags & MachO::SECTION_TYPE;
346}
347
Rafael Espindola59128922015-06-24 18:14:41 +0000348uint64_t MachOObjectFile::getNValue(DataRefImpl Sym) const {
349 if (is64Bit()) {
350 MachO::nlist_64 Entry = getSymbol64TableEntry(Sym);
351 return Entry.n_value;
352 }
353 MachO::nlist Entry = getSymbolTableEntry(Sym);
354 return Entry.n_value;
355}
356
Kevin Enderby980b2582014-06-05 21:21:57 +0000357// getIndirectName() returns the name of the alias'ed symbol who's string table
358// index is in the n_value field.
Rafael Espindola3acea392014-06-12 21:46:39 +0000359std::error_code MachOObjectFile::getIndirectName(DataRefImpl Symb,
360 StringRef &Res) const {
Kevin Enderby980b2582014-06-05 21:21:57 +0000361 StringRef StringTable = getStringTableData();
Rafael Espindola59128922015-06-24 18:14:41 +0000362 MachO::nlist_base Entry = getSymbolTableEntryBase(this, Symb);
363 if ((Entry.n_type & MachO::N_TYPE) != MachO::N_INDR)
364 return object_error::parse_failed;
365 uint64_t NValue = getNValue(Symb);
Kevin Enderby980b2582014-06-05 21:21:57 +0000366 if (NValue >= StringTable.size())
367 return object_error::parse_failed;
368 const char *Start = &StringTable.data()[NValue];
369 Res = StringRef(Start);
Rui Ueyama7d099192015-06-09 15:20:42 +0000370 return std::error_code();
Kevin Enderby980b2582014-06-05 21:21:57 +0000371}
372
Rafael Espindola991af662015-06-24 19:11:10 +0000373uint64_t MachOObjectFile::getSymbolValue(DataRefImpl Sym) const {
374 uint64_t NValue = getNValue(Sym);
375 MachO::nlist_base Entry = getSymbolTableEntryBase(this, Sym);
Rafael Espindola59128922015-06-24 18:14:41 +0000376 if ((Entry.n_type & MachO::N_TYPE) == MachO::N_UNDF && NValue == 0)
Rafael Espindola991af662015-06-24 19:11:10 +0000377 return UnknownAddress;
378 return NValue;
379}
380
381std::error_code MachOObjectFile::getSymbolAddress(DataRefImpl Sym,
382 uint64_t &Res) const {
383 Res = getSymbolValue(Sym);
Rui Ueyama7d099192015-06-09 15:20:42 +0000384 return std::error_code();
Rafael Espindola56f976f2013-04-18 18:08:55 +0000385}
386
Rafael Espindolaa4d224722015-05-31 23:52:50 +0000387uint32_t MachOObjectFile::getSymbolAlignment(DataRefImpl DRI) const {
Rafael Espindola20122a42014-01-31 20:57:12 +0000388 uint32_t flags = getSymbolFlags(DRI);
Rafael Espindolae4dd2e02013-04-29 22:24:22 +0000389 if (flags & SymbolRef::SF_Common) {
Artyom Skrobov78d5daf2014-07-18 09:26:16 +0000390 MachO::nlist_base Entry = getSymbolTableEntryBase(this, DRI);
Rafael Espindolaa4d224722015-05-31 23:52:50 +0000391 return 1 << MachO::GET_COMM_ALIGN(Entry.n_desc);
Rafael Espindolae4dd2e02013-04-29 22:24:22 +0000392 }
Rafael Espindolaa4d224722015-05-31 23:52:50 +0000393 return 0;
Rafael Espindolae4dd2e02013-04-29 22:24:22 +0000394}
395
Rafael Espindolad7a32ea2015-06-24 10:20:30 +0000396uint64_t MachOObjectFile::getCommonSymbolSizeImpl(DataRefImpl DRI) const {
Rafael Espindola56f976f2013-04-18 18:08:55 +0000397 uint64_t Value;
398 getSymbolAddress(DRI, Value);
Rafael Espindolad7a32ea2015-06-24 10:20:30 +0000399 return Value;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000400}
401
Rafael Espindola2fa80cc2015-06-26 12:18:49 +0000402SymbolRef::Type MachOObjectFile::getSymbolType(DataRefImpl Symb) const {
Artyom Skrobov78d5daf2014-07-18 09:26:16 +0000403 MachO::nlist_base Entry = getSymbolTableEntryBase(this, Symb);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000404 uint8_t n_type = Entry.n_type;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000405
Rafael Espindola56f976f2013-04-18 18:08:55 +0000406 // If this is a STAB debugging symbol, we can do nothing more.
Rafael Espindola2fa80cc2015-06-26 12:18:49 +0000407 if (n_type & MachO::N_STAB)
408 return SymbolRef::ST_Debug;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000409
Charles Davis74ec8b02013-08-27 05:00:13 +0000410 switch (n_type & MachO::N_TYPE) {
411 case MachO::N_UNDF :
Rafael Espindola2fa80cc2015-06-26 12:18:49 +0000412 return SymbolRef::ST_Unknown;
Charles Davis74ec8b02013-08-27 05:00:13 +0000413 case MachO::N_SECT :
Rafael Espindola2fa80cc2015-06-26 12:18:49 +0000414 return SymbolRef::ST_Function;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000415 }
Rafael Espindola2fa80cc2015-06-26 12:18:49 +0000416 return SymbolRef::ST_Other;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000417}
418
Rafael Espindola20122a42014-01-31 20:57:12 +0000419uint32_t MachOObjectFile::getSymbolFlags(DataRefImpl DRI) const {
Artyom Skrobov78d5daf2014-07-18 09:26:16 +0000420 MachO::nlist_base Entry = getSymbolTableEntryBase(this, DRI);
Rafael Espindola56f976f2013-04-18 18:08:55 +0000421
Charles Davis8bdfafd2013-09-01 04:28:48 +0000422 uint8_t MachOType = Entry.n_type;
423 uint16_t MachOFlags = Entry.n_desc;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000424
Rafael Espindola20122a42014-01-31 20:57:12 +0000425 uint32_t Result = SymbolRef::SF_None;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000426
Charles Davis74ec8b02013-08-27 05:00:13 +0000427 if ((MachOType & MachO::N_TYPE) == MachO::N_UNDF)
Rafael Espindola56f976f2013-04-18 18:08:55 +0000428 Result |= SymbolRef::SF_Undefined;
429
Tim Northovereaef0742014-05-30 13:22:59 +0000430 if ((MachOType & MachO::N_TYPE) == MachO::N_INDR)
431 Result |= SymbolRef::SF_Indirect;
432
Rafael Espindolaa1356322013-11-02 05:03:24 +0000433 if (MachOType & MachO::N_STAB)
Rafael Espindola56f976f2013-04-18 18:08:55 +0000434 Result |= SymbolRef::SF_FormatSpecific;
435
Charles Davis74ec8b02013-08-27 05:00:13 +0000436 if (MachOType & MachO::N_EXT) {
Rafael Espindola56f976f2013-04-18 18:08:55 +0000437 Result |= SymbolRef::SF_Global;
Charles Davis74ec8b02013-08-27 05:00:13 +0000438 if ((MachOType & MachO::N_TYPE) == MachO::N_UNDF) {
Rafael Espindolae4dd2e02013-04-29 22:24:22 +0000439 uint64_t Value;
440 getSymbolAddress(DRI, Value);
Rafael Espindolad7a32ea2015-06-24 10:20:30 +0000441 if (Value && Value != UnknownAddress)
Rafael Espindolae4dd2e02013-04-29 22:24:22 +0000442 Result |= SymbolRef::SF_Common;
443 }
Lang Hames7e0692b2015-01-15 22:33:30 +0000444
445 if (!(MachOType & MachO::N_PEXT))
446 Result |= SymbolRef::SF_Exported;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000447 }
448
Charles Davis74ec8b02013-08-27 05:00:13 +0000449 if (MachOFlags & (MachO::N_WEAK_REF | MachO::N_WEAK_DEF))
Rafael Espindola56f976f2013-04-18 18:08:55 +0000450 Result |= SymbolRef::SF_Weak;
451
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000452 if (MachOFlags & (MachO::N_ARM_THUMB_DEF))
453 Result |= SymbolRef::SF_Thumb;
454
Charles Davis74ec8b02013-08-27 05:00:13 +0000455 if ((MachOType & MachO::N_TYPE) == MachO::N_ABS)
Rafael Espindola56f976f2013-04-18 18:08:55 +0000456 Result |= SymbolRef::SF_Absolute;
457
Rafael Espindola20122a42014-01-31 20:57:12 +0000458 return Result;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000459}
460
Rafael Espindola3acea392014-06-12 21:46:39 +0000461std::error_code MachOObjectFile::getSymbolSection(DataRefImpl Symb,
462 section_iterator &Res) const {
Artyom Skrobov78d5daf2014-07-18 09:26:16 +0000463 MachO::nlist_base Entry = getSymbolTableEntryBase(this, Symb);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000464 uint8_t index = Entry.n_sect;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000465
466 if (index == 0) {
Rafael Espindolab5155a52014-02-10 20:24:04 +0000467 Res = section_end();
Rafael Espindola56f976f2013-04-18 18:08:55 +0000468 } else {
469 DataRefImpl DRI;
470 DRI.d.a = index - 1;
Rafael Espindola0d85d102015-05-22 14:59:27 +0000471 if (DRI.d.a >= Sections.size())
472 report_fatal_error("getSymbolSection: Invalid section index.");
Rafael Espindola56f976f2013-04-18 18:08:55 +0000473 Res = section_iterator(SectionRef(DRI, this));
474 }
475
Rui Ueyama7d099192015-06-09 15:20:42 +0000476 return std::error_code();
Rafael Espindola56f976f2013-04-18 18:08:55 +0000477}
478
Rafael Espindola6bf32212015-06-24 19:57:32 +0000479unsigned MachOObjectFile::getSymbolSectionID(SymbolRef Sym) const {
480 MachO::nlist_base Entry =
481 getSymbolTableEntryBase(this, Sym.getRawDataRefImpl());
482 return Entry.n_sect - 1;
483}
484
Rafael Espindola5e812af2014-01-30 02:49:50 +0000485void MachOObjectFile::moveSectionNext(DataRefImpl &Sec) const {
Rafael Espindola56f976f2013-04-18 18:08:55 +0000486 Sec.d.a++;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000487}
488
Rafael Espindola3acea392014-06-12 21:46:39 +0000489std::error_code MachOObjectFile::getSectionName(DataRefImpl Sec,
490 StringRef &Result) const {
Rafael Espindola56f976f2013-04-18 18:08:55 +0000491 ArrayRef<char> Raw = getSectionRawName(Sec);
492 Result = parseSegmentOrSectionName(Raw.data());
Rui Ueyama7d099192015-06-09 15:20:42 +0000493 return std::error_code();
Rafael Espindola56f976f2013-04-18 18:08:55 +0000494}
495
Rafael Espindola80291272014-10-08 15:28:58 +0000496uint64_t MachOObjectFile::getSectionAddress(DataRefImpl Sec) const {
497 if (is64Bit())
498 return getSection64(Sec).addr;
499 return getSection(Sec).addr;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000500}
501
Rafael Espindola80291272014-10-08 15:28:58 +0000502uint64_t MachOObjectFile::getSectionSize(DataRefImpl Sec) const {
503 if (is64Bit())
504 return getSection64(Sec).size;
505 return getSection(Sec).size;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000506}
507
Rafael Espindola3acea392014-06-12 21:46:39 +0000508std::error_code MachOObjectFile::getSectionContents(DataRefImpl Sec,
509 StringRef &Res) const {
Rafael Espindola56f976f2013-04-18 18:08:55 +0000510 uint32_t Offset;
511 uint64_t Size;
512
513 if (is64Bit()) {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000514 MachO::section_64 Sect = getSection64(Sec);
515 Offset = Sect.offset;
516 Size = Sect.size;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000517 } else {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000518 MachO::section Sect = getSection(Sec);
519 Offset = Sect.offset;
520 Size = Sect.size;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000521 }
522
523 Res = this->getData().substr(Offset, Size);
Rui Ueyama7d099192015-06-09 15:20:42 +0000524 return std::error_code();
Rafael Espindola56f976f2013-04-18 18:08:55 +0000525}
526
Rafael Espindola80291272014-10-08 15:28:58 +0000527uint64_t MachOObjectFile::getSectionAlignment(DataRefImpl Sec) const {
Rafael Espindola56f976f2013-04-18 18:08:55 +0000528 uint32_t Align;
529 if (is64Bit()) {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000530 MachO::section_64 Sect = getSection64(Sec);
531 Align = Sect.align;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000532 } else {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000533 MachO::section Sect = getSection(Sec);
534 Align = Sect.align;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000535 }
536
Rafael Espindola80291272014-10-08 15:28:58 +0000537 return uint64_t(1) << Align;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000538}
539
Rafael Espindola80291272014-10-08 15:28:58 +0000540bool MachOObjectFile::isSectionText(DataRefImpl Sec) const {
Rafael Espindola56f976f2013-04-18 18:08:55 +0000541 uint32_t Flags = getSectionFlags(this, Sec);
Rafael Espindola80291272014-10-08 15:28:58 +0000542 return Flags & MachO::S_ATTR_PURE_INSTRUCTIONS;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000543}
544
Rafael Espindola80291272014-10-08 15:28:58 +0000545bool MachOObjectFile::isSectionData(DataRefImpl Sec) const {
Kevin Enderby403258f2014-05-19 20:36:02 +0000546 uint32_t Flags = getSectionFlags(this, Sec);
547 unsigned SectionType = Flags & MachO::SECTION_TYPE;
Rafael Espindola80291272014-10-08 15:28:58 +0000548 return !(Flags & MachO::S_ATTR_PURE_INSTRUCTIONS) &&
549 !(SectionType == MachO::S_ZEROFILL ||
550 SectionType == MachO::S_GB_ZEROFILL);
Michael J. Spencer800619f2011-09-28 20:57:30 +0000551}
552
Rafael Espindola80291272014-10-08 15:28:58 +0000553bool MachOObjectFile::isSectionBSS(DataRefImpl Sec) const {
Kevin Enderby403258f2014-05-19 20:36:02 +0000554 uint32_t Flags = getSectionFlags(this, Sec);
555 unsigned SectionType = Flags & MachO::SECTION_TYPE;
Rafael Espindola80291272014-10-08 15:28:58 +0000556 return !(Flags & MachO::S_ATTR_PURE_INSTRUCTIONS) &&
557 (SectionType == MachO::S_ZEROFILL ||
558 SectionType == MachO::S_GB_ZEROFILL);
Preston Gurd2138ef62012-04-12 20:13:57 +0000559}
560
Rafael Espindola6bf32212015-06-24 19:57:32 +0000561unsigned MachOObjectFile::getSectionID(SectionRef Sec) const {
562 return Sec.getRawDataRefImpl().d.a;
563}
564
Rafael Espindola80291272014-10-08 15:28:58 +0000565bool MachOObjectFile::isSectionVirtual(DataRefImpl Sec) const {
Rafael Espindolac2413f52013-04-09 14:49:08 +0000566 // FIXME: Unimplemented.
Rafael Espindola80291272014-10-08 15:28:58 +0000567 return false;
Rafael Espindolac2413f52013-04-09 14:49:08 +0000568}
569
Rafael Espindola80291272014-10-08 15:28:58 +0000570bool MachOObjectFile::sectionContainsSymbol(DataRefImpl Sec,
571 DataRefImpl Symb) const {
Rafael Espindola2fa80cc2015-06-26 12:18:49 +0000572 SymbolRef::Type ST = getSymbolType(Symb);
Rafael Espindola80291272014-10-08 15:28:58 +0000573 if (ST == SymbolRef::ST_Unknown)
574 return false;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000575
Rafael Espindola80291272014-10-08 15:28:58 +0000576 uint64_t SectBegin = getSectionAddress(Sec);
577 uint64_t SectEnd = getSectionSize(Sec);
Rafael Espindola56f976f2013-04-18 18:08:55 +0000578 SectEnd += SectBegin;
579
580 uint64_t SymAddr;
581 getSymbolAddress(Symb, SymAddr);
Rafael Espindola80291272014-10-08 15:28:58 +0000582 return (SymAddr >= SectBegin) && (SymAddr < SectEnd);
Rafael Espindola56f976f2013-04-18 18:08:55 +0000583}
584
Rui Ueyamabc654b12013-09-27 21:47:05 +0000585relocation_iterator MachOObjectFile::section_rel_begin(DataRefImpl Sec) const {
Rafael Espindola04d3f492013-04-25 12:45:46 +0000586 DataRefImpl Ret;
Rafael Espindola128b8112014-04-03 23:51:28 +0000587 Ret.d.a = Sec.d.a;
588 Ret.d.b = 0;
Rafael Espindola04d3f492013-04-25 12:45:46 +0000589 return relocation_iterator(RelocationRef(Ret, this));
Michael J. Spencere5fd0042011-10-07 19:25:32 +0000590}
Rafael Espindolac0406e12013-04-08 20:45:01 +0000591
Rafael Espindola56f976f2013-04-18 18:08:55 +0000592relocation_iterator
Rui Ueyamabc654b12013-09-27 21:47:05 +0000593MachOObjectFile::section_rel_end(DataRefImpl Sec) const {
Rafael Espindola04d3f492013-04-25 12:45:46 +0000594 uint32_t Num;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000595 if (is64Bit()) {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000596 MachO::section_64 Sect = getSection64(Sec);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000597 Num = Sect.nreloc;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000598 } else {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000599 MachO::section Sect = getSection(Sec);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000600 Num = Sect.nreloc;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000601 }
Eric Christopher7b015c72011-04-22 03:19:48 +0000602
Rafael Espindola56f976f2013-04-18 18:08:55 +0000603 DataRefImpl Ret;
Rafael Espindola128b8112014-04-03 23:51:28 +0000604 Ret.d.a = Sec.d.a;
605 Ret.d.b = Num;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000606 return relocation_iterator(RelocationRef(Ret, this));
607}
Benjamin Kramer022ecdf2011-09-08 20:52:17 +0000608
Rafael Espindola5e812af2014-01-30 02:49:50 +0000609void MachOObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
Rafael Espindola128b8112014-04-03 23:51:28 +0000610 ++Rel.d.b;
Benjamin Kramer022ecdf2011-09-08 20:52:17 +0000611}
Owen Anderson171f4852011-10-24 23:20:07 +0000612
Rafael Espindola3acea392014-06-12 21:46:39 +0000613std::error_code MachOObjectFile::getRelocationAddress(DataRefImpl Rel,
614 uint64_t &Res) const {
Rafael Espindola72475462014-04-04 00:31:12 +0000615 uint64_t Offset;
616 getRelocationOffset(Rel, Offset);
Rafael Espindola7e91bc92014-04-03 23:54:35 +0000617
618 DataRefImpl Sec;
619 Sec.d.a = Rel.d.a;
Rafael Espindola80291272014-10-08 15:28:58 +0000620 uint64_t SecAddress = getSectionAddress(Sec);
Rafael Espindola7e91bc92014-04-03 23:54:35 +0000621 Res = SecAddress + Offset;
Rui Ueyama7d099192015-06-09 15:20:42 +0000622 return std::error_code();
Benjamin Kramer022ecdf2011-09-08 20:52:17 +0000623}
624
Rafael Espindola3acea392014-06-12 21:46:39 +0000625std::error_code MachOObjectFile::getRelocationOffset(DataRefImpl Rel,
626 uint64_t &Res) const {
Rafael Espindola72475462014-04-04 00:31:12 +0000627 assert(getHeader().filetype == MachO::MH_OBJECT &&
628 "Only implemented for MH_OBJECT");
Charles Davis8bdfafd2013-09-01 04:28:48 +0000629 MachO::any_relocation_info RE = getRelocation(Rel);
Rafael Espindola56f976f2013-04-18 18:08:55 +0000630 Res = getAnyRelocationAddress(RE);
Rui Ueyama7d099192015-06-09 15:20:42 +0000631 return std::error_code();
David Meyer2fc34c52012-03-01 01:36:50 +0000632}
633
Rafael Espindola806f0062013-06-05 01:33:53 +0000634symbol_iterator
635MachOObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000636 MachO::any_relocation_info RE = getRelocation(Rel);
Tim Northover07f99fb2014-07-04 10:57:56 +0000637 if (isRelocationScattered(RE))
638 return symbol_end();
639
Rafael Espindola56f976f2013-04-18 18:08:55 +0000640 uint32_t SymbolIdx = getPlainRelocationSymbolNum(RE);
641 bool isExtern = getPlainRelocationExternal(RE);
Rafael Espindola806f0062013-06-05 01:33:53 +0000642 if (!isExtern)
Rafael Espindolab5155a52014-02-10 20:24:04 +0000643 return symbol_end();
Rafael Espindola75c30362013-04-24 19:47:55 +0000644
Charles Davis8bdfafd2013-09-01 04:28:48 +0000645 MachO::symtab_command S = getSymtabLoadCommand();
Rafael Espindola75c30362013-04-24 19:47:55 +0000646 unsigned SymbolTableEntrySize = is64Bit() ?
Charles Davis8bdfafd2013-09-01 04:28:48 +0000647 sizeof(MachO::nlist_64) :
648 sizeof(MachO::nlist);
649 uint64_t Offset = S.symoff + SymbolIdx * SymbolTableEntrySize;
Rafael Espindola75c30362013-04-24 19:47:55 +0000650 DataRefImpl Sym;
651 Sym.p = reinterpret_cast<uintptr_t>(getPtr(this, Offset));
Rafael Espindola806f0062013-06-05 01:33:53 +0000652 return symbol_iterator(SymbolRef(Sym, this));
Rafael Espindola56f976f2013-04-18 18:08:55 +0000653}
654
Keno Fischerc780e8e2015-05-21 21:24:32 +0000655section_iterator
656MachOObjectFile::getRelocationSection(DataRefImpl Rel) const {
657 return section_iterator(getAnyRelocationSection(getRelocation(Rel)));
658}
659
Rafael Espindola3acea392014-06-12 21:46:39 +0000660std::error_code MachOObjectFile::getRelocationType(DataRefImpl Rel,
661 uint64_t &Res) const {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000662 MachO::any_relocation_info RE = getRelocation(Rel);
Rafael Espindola56f976f2013-04-18 18:08:55 +0000663 Res = getAnyRelocationType(RE);
Rui Ueyama7d099192015-06-09 15:20:42 +0000664 return std::error_code();
Rafael Espindola56f976f2013-04-18 18:08:55 +0000665}
666
Rafael Espindola3acea392014-06-12 21:46:39 +0000667std::error_code
Rafael Espindola56f976f2013-04-18 18:08:55 +0000668MachOObjectFile::getRelocationTypeName(DataRefImpl Rel,
669 SmallVectorImpl<char> &Result) const {
670 StringRef res;
671 uint64_t RType;
672 getRelocationType(Rel, RType);
673
674 unsigned Arch = this->getArch();
675
676 switch (Arch) {
677 case Triple::x86: {
678 static const char *const Table[] = {
679 "GENERIC_RELOC_VANILLA",
680 "GENERIC_RELOC_PAIR",
681 "GENERIC_RELOC_SECTDIFF",
682 "GENERIC_RELOC_PB_LA_PTR",
683 "GENERIC_RELOC_LOCAL_SECTDIFF",
684 "GENERIC_RELOC_TLV" };
685
Eric Christopher13250cb2013-12-06 02:33:38 +0000686 if (RType > 5)
Rafael Espindola56f976f2013-04-18 18:08:55 +0000687 res = "Unknown";
688 else
689 res = Table[RType];
690 break;
691 }
692 case Triple::x86_64: {
693 static const char *const Table[] = {
694 "X86_64_RELOC_UNSIGNED",
695 "X86_64_RELOC_SIGNED",
696 "X86_64_RELOC_BRANCH",
697 "X86_64_RELOC_GOT_LOAD",
698 "X86_64_RELOC_GOT",
699 "X86_64_RELOC_SUBTRACTOR",
700 "X86_64_RELOC_SIGNED_1",
701 "X86_64_RELOC_SIGNED_2",
702 "X86_64_RELOC_SIGNED_4",
703 "X86_64_RELOC_TLV" };
704
705 if (RType > 9)
706 res = "Unknown";
707 else
708 res = Table[RType];
709 break;
710 }
711 case Triple::arm: {
712 static const char *const Table[] = {
713 "ARM_RELOC_VANILLA",
714 "ARM_RELOC_PAIR",
715 "ARM_RELOC_SECTDIFF",
716 "ARM_RELOC_LOCAL_SECTDIFF",
717 "ARM_RELOC_PB_LA_PTR",
718 "ARM_RELOC_BR24",
719 "ARM_THUMB_RELOC_BR22",
720 "ARM_THUMB_32BIT_BRANCH",
721 "ARM_RELOC_HALF",
722 "ARM_RELOC_HALF_SECTDIFF" };
723
724 if (RType > 9)
725 res = "Unknown";
726 else
727 res = Table[RType];
728 break;
729 }
Tim Northover00ed9962014-03-29 10:18:08 +0000730 case Triple::aarch64: {
731 static const char *const Table[] = {
732 "ARM64_RELOC_UNSIGNED", "ARM64_RELOC_SUBTRACTOR",
733 "ARM64_RELOC_BRANCH26", "ARM64_RELOC_PAGE21",
734 "ARM64_RELOC_PAGEOFF12", "ARM64_RELOC_GOT_LOAD_PAGE21",
735 "ARM64_RELOC_GOT_LOAD_PAGEOFF12", "ARM64_RELOC_POINTER_TO_GOT",
736 "ARM64_RELOC_TLVP_LOAD_PAGE21", "ARM64_RELOC_TLVP_LOAD_PAGEOFF12",
737 "ARM64_RELOC_ADDEND"
738 };
739
740 if (RType >= array_lengthof(Table))
741 res = "Unknown";
742 else
743 res = Table[RType];
744 break;
745 }
Rafael Espindola56f976f2013-04-18 18:08:55 +0000746 case Triple::ppc: {
747 static const char *const Table[] = {
748 "PPC_RELOC_VANILLA",
749 "PPC_RELOC_PAIR",
750 "PPC_RELOC_BR14",
751 "PPC_RELOC_BR24",
752 "PPC_RELOC_HI16",
753 "PPC_RELOC_LO16",
754 "PPC_RELOC_HA16",
755 "PPC_RELOC_LO14",
756 "PPC_RELOC_SECTDIFF",
757 "PPC_RELOC_PB_LA_PTR",
758 "PPC_RELOC_HI16_SECTDIFF",
759 "PPC_RELOC_LO16_SECTDIFF",
760 "PPC_RELOC_HA16_SECTDIFF",
761 "PPC_RELOC_JBSR",
762 "PPC_RELOC_LO14_SECTDIFF",
763 "PPC_RELOC_LOCAL_SECTDIFF" };
764
Eric Christopher13250cb2013-12-06 02:33:38 +0000765 if (RType > 15)
766 res = "Unknown";
767 else
768 res = Table[RType];
Rafael Espindola56f976f2013-04-18 18:08:55 +0000769 break;
770 }
771 case Triple::UnknownArch:
772 res = "Unknown";
773 break;
774 }
775 Result.append(res.begin(), res.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000776 return std::error_code();
Rafael Espindola56f976f2013-04-18 18:08:55 +0000777}
778
Rafael Espindola3acea392014-06-12 21:46:39 +0000779std::error_code MachOObjectFile::getRelocationHidden(DataRefImpl Rel,
780 bool &Result) const {
Rafael Espindola56f976f2013-04-18 18:08:55 +0000781 unsigned Arch = getArch();
782 uint64_t Type;
783 getRelocationType(Rel, Type);
784
785 Result = false;
786
787 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
788 // is always hidden.
David Fangb88cdf62013-08-08 20:14:40 +0000789 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000790 if (Type == MachO::GENERIC_RELOC_PAIR) Result = true;
Rafael Espindola56f976f2013-04-18 18:08:55 +0000791 } else if (Arch == Triple::x86_64) {
792 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
Eric Christopher1ff26ab62013-07-22 22:25:09 +0000793 // an X86_64_RELOC_SUBTRACTOR.
Charles Davis8bdfafd2013-09-01 04:28:48 +0000794 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
Rafael Espindola56f976f2013-04-18 18:08:55 +0000795 DataRefImpl RelPrev = Rel;
796 RelPrev.d.a--;
797 uint64_t PrevType;
798 getRelocationType(RelPrev, PrevType);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000799 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
Rafael Espindola56f976f2013-04-18 18:08:55 +0000800 Result = true;
801 }
802 }
803
Rui Ueyama7d099192015-06-09 15:20:42 +0000804 return std::error_code();
Rafael Espindola56f976f2013-04-18 18:08:55 +0000805}
806
Keno Fischer281b6942015-05-30 19:44:53 +0000807uint8_t MachOObjectFile::getRelocationLength(DataRefImpl Rel) const {
808 MachO::any_relocation_info RE = getRelocation(Rel);
809 return getAnyRelocationLength(RE);
810}
811
Kevin Enderby980b2582014-06-05 21:21:57 +0000812//
813// guessLibraryShortName() is passed a name of a dynamic library and returns a
814// guess on what the short name is. Then name is returned as a substring of the
815// StringRef Name passed in. The name of the dynamic library is recognized as
816// a framework if it has one of the two following forms:
817// Foo.framework/Versions/A/Foo
818// Foo.framework/Foo
819// Where A and Foo can be any string. And may contain a trailing suffix
820// starting with an underbar. If the Name is recognized as a framework then
821// isFramework is set to true else it is set to false. If the Name has a
822// suffix then Suffix is set to the substring in Name that contains the suffix
823// else it is set to a NULL StringRef.
824//
825// The Name of the dynamic library is recognized as a library name if it has
826// one of the two following forms:
827// libFoo.A.dylib
828// libFoo.dylib
829// The library may have a suffix trailing the name Foo of the form:
830// libFoo_profile.A.dylib
831// libFoo_profile.dylib
832//
833// The Name of the dynamic library is also recognized as a library name if it
834// has the following form:
835// Foo.qtx
836//
837// If the Name of the dynamic library is none of the forms above then a NULL
838// StringRef is returned.
839//
840StringRef MachOObjectFile::guessLibraryShortName(StringRef Name,
841 bool &isFramework,
842 StringRef &Suffix) {
843 StringRef Foo, F, DotFramework, V, Dylib, Lib, Dot, Qtx;
844 size_t a, b, c, d, Idx;
845
846 isFramework = false;
847 Suffix = StringRef();
848
849 // Pull off the last component and make Foo point to it
850 a = Name.rfind('/');
851 if (a == Name.npos || a == 0)
852 goto guess_library;
853 Foo = Name.slice(a+1, Name.npos);
854
855 // Look for a suffix starting with a '_'
856 Idx = Foo.rfind('_');
857 if (Idx != Foo.npos && Foo.size() >= 2) {
858 Suffix = Foo.slice(Idx, Foo.npos);
859 Foo = Foo.slice(0, Idx);
860 }
861
862 // First look for the form Foo.framework/Foo
863 b = Name.rfind('/', a);
864 if (b == Name.npos)
865 Idx = 0;
866 else
867 Idx = b+1;
868 F = Name.slice(Idx, Idx + Foo.size());
869 DotFramework = Name.slice(Idx + Foo.size(),
870 Idx + Foo.size() + sizeof(".framework/")-1);
871 if (F == Foo && DotFramework == ".framework/") {
872 isFramework = true;
873 return Foo;
874 }
875
876 // Next look for the form Foo.framework/Versions/A/Foo
877 if (b == Name.npos)
878 goto guess_library;
879 c = Name.rfind('/', b);
880 if (c == Name.npos || c == 0)
881 goto guess_library;
882 V = Name.slice(c+1, Name.npos);
883 if (!V.startswith("Versions/"))
884 goto guess_library;
885 d = Name.rfind('/', c);
886 if (d == Name.npos)
887 Idx = 0;
888 else
889 Idx = d+1;
890 F = Name.slice(Idx, Idx + Foo.size());
891 DotFramework = Name.slice(Idx + Foo.size(),
892 Idx + Foo.size() + sizeof(".framework/")-1);
893 if (F == Foo && DotFramework == ".framework/") {
894 isFramework = true;
895 return Foo;
896 }
897
898guess_library:
899 // pull off the suffix after the "." and make a point to it
900 a = Name.rfind('.');
901 if (a == Name.npos || a == 0)
902 return StringRef();
903 Dylib = Name.slice(a, Name.npos);
904 if (Dylib != ".dylib")
905 goto guess_qtx;
906
907 // First pull off the version letter for the form Foo.A.dylib if any.
908 if (a >= 3) {
909 Dot = Name.slice(a-2, a-1);
910 if (Dot == ".")
911 a = a - 2;
912 }
913
914 b = Name.rfind('/', a);
915 if (b == Name.npos)
916 b = 0;
917 else
918 b = b+1;
919 // ignore any suffix after an underbar like Foo_profile.A.dylib
920 Idx = Name.find('_', b);
921 if (Idx != Name.npos && Idx != b) {
922 Lib = Name.slice(b, Idx);
923 Suffix = Name.slice(Idx, a);
924 }
925 else
926 Lib = Name.slice(b, a);
927 // There are incorrect library names of the form:
928 // libATS.A_profile.dylib so check for these.
929 if (Lib.size() >= 3) {
930 Dot = Lib.slice(Lib.size()-2, Lib.size()-1);
931 if (Dot == ".")
932 Lib = Lib.slice(0, Lib.size()-2);
933 }
934 return Lib;
935
936guess_qtx:
937 Qtx = Name.slice(a, Name.npos);
938 if (Qtx != ".qtx")
939 return StringRef();
940 b = Name.rfind('/', a);
941 if (b == Name.npos)
942 Lib = Name.slice(0, a);
943 else
944 Lib = Name.slice(b+1, a);
945 // There are library names of the form: QT.A.qtx so check for these.
946 if (Lib.size() >= 3) {
947 Dot = Lib.slice(Lib.size()-2, Lib.size()-1);
948 if (Dot == ".")
949 Lib = Lib.slice(0, Lib.size()-2);
950 }
951 return Lib;
952}
953
954// getLibraryShortNameByIndex() is used to get the short name of the library
955// for an undefined symbol in a linked Mach-O binary that was linked with the
956// normal two-level namespace default (that is MH_TWOLEVEL in the header).
957// It is passed the index (0 - based) of the library as translated from
958// GET_LIBRARY_ORDINAL (1 - based).
Rafael Espindola3acea392014-06-12 21:46:39 +0000959std::error_code MachOObjectFile::getLibraryShortNameByIndex(unsigned Index,
Nick Kledzikd04bc352014-08-30 00:20:14 +0000960 StringRef &Res) const {
Kevin Enderby980b2582014-06-05 21:21:57 +0000961 if (Index >= Libraries.size())
962 return object_error::parse_failed;
963
Kevin Enderby980b2582014-06-05 21:21:57 +0000964 // If the cache of LibrariesShortNames is not built up do that first for
965 // all the Libraries.
966 if (LibrariesShortNames.size() == 0) {
967 for (unsigned i = 0; i < Libraries.size(); i++) {
968 MachO::dylib_command D =
969 getStruct<MachO::dylib_command>(this, Libraries[i]);
Nick Kledzik30061302014-09-17 00:25:22 +0000970 if (D.dylib.name >= D.cmdsize)
971 return object_error::parse_failed;
Kevin Enderby4eff6cd2014-06-20 18:07:34 +0000972 const char *P = (const char *)(Libraries[i]) + D.dylib.name;
Kevin Enderby980b2582014-06-05 21:21:57 +0000973 StringRef Name = StringRef(P);
Nick Kledzik30061302014-09-17 00:25:22 +0000974 if (D.dylib.name+Name.size() >= D.cmdsize)
975 return object_error::parse_failed;
Kevin Enderby980b2582014-06-05 21:21:57 +0000976 StringRef Suffix;
977 bool isFramework;
978 StringRef shortName = guessLibraryShortName(Name, isFramework, Suffix);
Nick Kledzik30061302014-09-17 00:25:22 +0000979 if (shortName.empty())
Kevin Enderby980b2582014-06-05 21:21:57 +0000980 LibrariesShortNames.push_back(Name);
981 else
982 LibrariesShortNames.push_back(shortName);
983 }
984 }
985
986 Res = LibrariesShortNames[Index];
Rui Ueyama7d099192015-06-09 15:20:42 +0000987 return std::error_code();
Kevin Enderby980b2582014-06-05 21:21:57 +0000988}
989
Rafael Espindolaf12b8282014-02-21 20:10:59 +0000990basic_symbol_iterator MachOObjectFile::symbol_begin_impl() const {
Lang Hames36072da2014-05-12 21:39:59 +0000991 return getSymbolByIndex(0);
Rafael Espindola56f976f2013-04-18 18:08:55 +0000992}
993
Rafael Espindolaf12b8282014-02-21 20:10:59 +0000994basic_symbol_iterator MachOObjectFile::symbol_end_impl() const {
Rafael Espindola56f976f2013-04-18 18:08:55 +0000995 DataRefImpl DRI;
Rafael Espindola75c30362013-04-24 19:47:55 +0000996 if (!SymtabLoadCmd)
Rafael Espindolaf12b8282014-02-21 20:10:59 +0000997 return basic_symbol_iterator(SymbolRef(DRI, this));
Rafael Espindola75c30362013-04-24 19:47:55 +0000998
Charles Davis8bdfafd2013-09-01 04:28:48 +0000999 MachO::symtab_command Symtab = getSymtabLoadCommand();
Rafael Espindola75c30362013-04-24 19:47:55 +00001000 unsigned SymbolTableEntrySize = is64Bit() ?
Charles Davis8bdfafd2013-09-01 04:28:48 +00001001 sizeof(MachO::nlist_64) :
1002 sizeof(MachO::nlist);
1003 unsigned Offset = Symtab.symoff +
1004 Symtab.nsyms * SymbolTableEntrySize;
Rafael Espindola75c30362013-04-24 19:47:55 +00001005 DRI.p = reinterpret_cast<uintptr_t>(getPtr(this, Offset));
Rafael Espindolaf12b8282014-02-21 20:10:59 +00001006 return basic_symbol_iterator(SymbolRef(DRI, this));
Rafael Espindola56f976f2013-04-18 18:08:55 +00001007}
1008
Lang Hames36072da2014-05-12 21:39:59 +00001009basic_symbol_iterator MachOObjectFile::getSymbolByIndex(unsigned Index) const {
1010 DataRefImpl DRI;
1011 if (!SymtabLoadCmd)
1012 return basic_symbol_iterator(SymbolRef(DRI, this));
1013
1014 MachO::symtab_command Symtab = getSymtabLoadCommand();
Filipe Cabecinhas40139502015-01-15 22:52:38 +00001015 if (Index >= Symtab.nsyms)
1016 report_fatal_error("Requested symbol index is out of range.");
Lang Hames36072da2014-05-12 21:39:59 +00001017 unsigned SymbolTableEntrySize =
1018 is64Bit() ? sizeof(MachO::nlist_64) : sizeof(MachO::nlist);
1019 DRI.p = reinterpret_cast<uintptr_t>(getPtr(this, Symtab.symoff));
1020 DRI.p += Index * SymbolTableEntrySize;
1021 return basic_symbol_iterator(SymbolRef(DRI, this));
1022}
1023
Rafael Espindolab5155a52014-02-10 20:24:04 +00001024section_iterator MachOObjectFile::section_begin() const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00001025 DataRefImpl DRI;
1026 return section_iterator(SectionRef(DRI, this));
1027}
1028
Rafael Espindolab5155a52014-02-10 20:24:04 +00001029section_iterator MachOObjectFile::section_end() const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00001030 DataRefImpl DRI;
1031 DRI.d.a = Sections.size();
1032 return section_iterator(SectionRef(DRI, this));
1033}
1034
Rafael Espindola56f976f2013-04-18 18:08:55 +00001035uint8_t MachOObjectFile::getBytesInAddress() const {
Rafael Espindola60689982013-04-07 19:05:30 +00001036 return is64Bit() ? 8 : 4;
Eric Christopher7b015c72011-04-22 03:19:48 +00001037}
1038
Rafael Espindola56f976f2013-04-18 18:08:55 +00001039StringRef MachOObjectFile::getFileFormatName() const {
1040 unsigned CPUType = getCPUType(this);
1041 if (!is64Bit()) {
1042 switch (CPUType) {
Charles Davis74ec8b02013-08-27 05:00:13 +00001043 case llvm::MachO::CPU_TYPE_I386:
Rafael Espindola56f976f2013-04-18 18:08:55 +00001044 return "Mach-O 32-bit i386";
Charles Davis74ec8b02013-08-27 05:00:13 +00001045 case llvm::MachO::CPU_TYPE_ARM:
Rafael Espindola56f976f2013-04-18 18:08:55 +00001046 return "Mach-O arm";
Charles Davis74ec8b02013-08-27 05:00:13 +00001047 case llvm::MachO::CPU_TYPE_POWERPC:
Rafael Espindola56f976f2013-04-18 18:08:55 +00001048 return "Mach-O 32-bit ppc";
1049 default:
Rafael Espindola56f976f2013-04-18 18:08:55 +00001050 return "Mach-O 32-bit unknown";
1051 }
1052 }
1053
Rafael Espindola56f976f2013-04-18 18:08:55 +00001054 switch (CPUType) {
Charles Davis74ec8b02013-08-27 05:00:13 +00001055 case llvm::MachO::CPU_TYPE_X86_64:
Rafael Espindola56f976f2013-04-18 18:08:55 +00001056 return "Mach-O 64-bit x86-64";
Tim Northover00ed9962014-03-29 10:18:08 +00001057 case llvm::MachO::CPU_TYPE_ARM64:
1058 return "Mach-O arm64";
Charles Davis74ec8b02013-08-27 05:00:13 +00001059 case llvm::MachO::CPU_TYPE_POWERPC64:
Rafael Espindola56f976f2013-04-18 18:08:55 +00001060 return "Mach-O 64-bit ppc64";
1061 default:
1062 return "Mach-O 64-bit unknown";
1063 }
1064}
1065
Alexey Samsonove6388e62013-06-18 15:03:28 +00001066Triple::ArchType MachOObjectFile::getArch(uint32_t CPUType) {
1067 switch (CPUType) {
Charles Davis74ec8b02013-08-27 05:00:13 +00001068 case llvm::MachO::CPU_TYPE_I386:
Rafael Espindola56f976f2013-04-18 18:08:55 +00001069 return Triple::x86;
Charles Davis74ec8b02013-08-27 05:00:13 +00001070 case llvm::MachO::CPU_TYPE_X86_64:
Rafael Espindola56f976f2013-04-18 18:08:55 +00001071 return Triple::x86_64;
Charles Davis74ec8b02013-08-27 05:00:13 +00001072 case llvm::MachO::CPU_TYPE_ARM:
Rafael Espindola56f976f2013-04-18 18:08:55 +00001073 return Triple::arm;
Tim Northover00ed9962014-03-29 10:18:08 +00001074 case llvm::MachO::CPU_TYPE_ARM64:
Tim Northovere19bed72014-07-23 12:32:47 +00001075 return Triple::aarch64;
Charles Davis74ec8b02013-08-27 05:00:13 +00001076 case llvm::MachO::CPU_TYPE_POWERPC:
Rafael Espindola56f976f2013-04-18 18:08:55 +00001077 return Triple::ppc;
Charles Davis74ec8b02013-08-27 05:00:13 +00001078 case llvm::MachO::CPU_TYPE_POWERPC64:
Rafael Espindola56f976f2013-04-18 18:08:55 +00001079 return Triple::ppc64;
1080 default:
1081 return Triple::UnknownArch;
1082 }
1083}
1084
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001085Triple MachOObjectFile::getArch(uint32_t CPUType, uint32_t CPUSubType,
1086 const char **McpuDefault) {
1087 if (McpuDefault)
1088 *McpuDefault = nullptr;
1089
Kevin Enderby4c8dfe42014-06-30 18:45:23 +00001090 switch (CPUType) {
1091 case MachO::CPU_TYPE_I386:
1092 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
1093 case MachO::CPU_SUBTYPE_I386_ALL:
1094 return Triple("i386-apple-darwin");
1095 default:
1096 return Triple();
1097 }
1098 case MachO::CPU_TYPE_X86_64:
1099 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
1100 case MachO::CPU_SUBTYPE_X86_64_ALL:
1101 return Triple("x86_64-apple-darwin");
1102 case MachO::CPU_SUBTYPE_X86_64_H:
1103 return Triple("x86_64h-apple-darwin");
1104 default:
1105 return Triple();
1106 }
1107 case MachO::CPU_TYPE_ARM:
1108 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
1109 case MachO::CPU_SUBTYPE_ARM_V4T:
1110 return Triple("armv4t-apple-darwin");
1111 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1112 return Triple("armv5e-apple-darwin");
Kevin Enderbyae2a9a22014-08-07 21:30:25 +00001113 case MachO::CPU_SUBTYPE_ARM_XSCALE:
1114 return Triple("xscale-apple-darwin");
Kevin Enderby4c8dfe42014-06-30 18:45:23 +00001115 case MachO::CPU_SUBTYPE_ARM_V6:
1116 return Triple("armv6-apple-darwin");
1117 case MachO::CPU_SUBTYPE_ARM_V6M:
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001118 if (McpuDefault)
1119 *McpuDefault = "cortex-m0";
Kevin Enderby4c8dfe42014-06-30 18:45:23 +00001120 return Triple("armv6m-apple-darwin");
Kevin Enderbyae2a9a22014-08-07 21:30:25 +00001121 case MachO::CPU_SUBTYPE_ARM_V7:
1122 return Triple("armv7-apple-darwin");
Kevin Enderby4c8dfe42014-06-30 18:45:23 +00001123 case MachO::CPU_SUBTYPE_ARM_V7EM:
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001124 if (McpuDefault)
1125 *McpuDefault = "cortex-m4";
Kevin Enderby4c8dfe42014-06-30 18:45:23 +00001126 return Triple("armv7em-apple-darwin");
1127 case MachO::CPU_SUBTYPE_ARM_V7K:
1128 return Triple("armv7k-apple-darwin");
1129 case MachO::CPU_SUBTYPE_ARM_V7M:
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001130 if (McpuDefault)
1131 *McpuDefault = "cortex-m3";
Kevin Enderby4c8dfe42014-06-30 18:45:23 +00001132 return Triple("armv7m-apple-darwin");
1133 case MachO::CPU_SUBTYPE_ARM_V7S:
1134 return Triple("armv7s-apple-darwin");
1135 default:
1136 return Triple();
1137 }
1138 case MachO::CPU_TYPE_ARM64:
1139 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
1140 case MachO::CPU_SUBTYPE_ARM64_ALL:
1141 return Triple("arm64-apple-darwin");
1142 default:
1143 return Triple();
1144 }
1145 case MachO::CPU_TYPE_POWERPC:
1146 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
1147 case MachO::CPU_SUBTYPE_POWERPC_ALL:
1148 return Triple("ppc-apple-darwin");
1149 default:
1150 return Triple();
1151 }
1152 case MachO::CPU_TYPE_POWERPC64:
Reid Kleckner4da3d572014-06-30 20:12:59 +00001153 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
Kevin Enderby4c8dfe42014-06-30 18:45:23 +00001154 case MachO::CPU_SUBTYPE_POWERPC_ALL:
1155 return Triple("ppc64-apple-darwin");
Kevin Enderby4c8dfe42014-06-30 18:45:23 +00001156 default:
1157 return Triple();
1158 }
1159 default:
1160 return Triple();
1161 }
1162}
1163
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001164Triple MachOObjectFile::getThumbArch(uint32_t CPUType, uint32_t CPUSubType,
1165 const char **McpuDefault) {
1166 if (McpuDefault)
1167 *McpuDefault = nullptr;
1168
1169 switch (CPUType) {
1170 case MachO::CPU_TYPE_ARM:
1171 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
1172 case MachO::CPU_SUBTYPE_ARM_V4T:
1173 return Triple("thumbv4t-apple-darwin");
1174 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1175 return Triple("thumbv5e-apple-darwin");
1176 case MachO::CPU_SUBTYPE_ARM_XSCALE:
1177 return Triple("xscale-apple-darwin");
1178 case MachO::CPU_SUBTYPE_ARM_V6:
1179 return Triple("thumbv6-apple-darwin");
1180 case MachO::CPU_SUBTYPE_ARM_V6M:
1181 if (McpuDefault)
1182 *McpuDefault = "cortex-m0";
1183 return Triple("thumbv6m-apple-darwin");
1184 case MachO::CPU_SUBTYPE_ARM_V7:
1185 return Triple("thumbv7-apple-darwin");
1186 case MachO::CPU_SUBTYPE_ARM_V7EM:
1187 if (McpuDefault)
1188 *McpuDefault = "cortex-m4";
1189 return Triple("thumbv7em-apple-darwin");
1190 case MachO::CPU_SUBTYPE_ARM_V7K:
1191 return Triple("thumbv7k-apple-darwin");
1192 case MachO::CPU_SUBTYPE_ARM_V7M:
1193 if (McpuDefault)
1194 *McpuDefault = "cortex-m3";
1195 return Triple("thumbv7m-apple-darwin");
1196 case MachO::CPU_SUBTYPE_ARM_V7S:
1197 return Triple("thumbv7s-apple-darwin");
1198 default:
1199 return Triple();
1200 }
1201 default:
1202 return Triple();
1203 }
1204}
1205
1206Triple MachOObjectFile::getArch(uint32_t CPUType, uint32_t CPUSubType,
1207 const char **McpuDefault,
1208 Triple *ThumbTriple) {
1209 Triple T = MachOObjectFile::getArch(CPUType, CPUSubType, McpuDefault);
1210 *ThumbTriple = MachOObjectFile::getThumbArch(CPUType, CPUSubType,
1211 McpuDefault);
1212 return T;
1213}
1214
Kevin Enderby4c8dfe42014-06-30 18:45:23 +00001215Triple MachOObjectFile::getHostArch() {
1216 return Triple(sys::getDefaultTargetTriple());
1217}
1218
Rafael Espindola72318b42014-08-08 16:30:17 +00001219bool MachOObjectFile::isValidArch(StringRef ArchFlag) {
1220 return StringSwitch<bool>(ArchFlag)
1221 .Case("i386", true)
1222 .Case("x86_64", true)
1223 .Case("x86_64h", true)
1224 .Case("armv4t", true)
1225 .Case("arm", true)
1226 .Case("armv5e", true)
1227 .Case("armv6", true)
1228 .Case("armv6m", true)
Frederic Riss40baa0a2015-06-16 17:37:03 +00001229 .Case("armv7", true)
Rafael Espindola72318b42014-08-08 16:30:17 +00001230 .Case("armv7em", true)
1231 .Case("armv7k", true)
1232 .Case("armv7m", true)
1233 .Case("armv7s", true)
1234 .Case("arm64", true)
1235 .Case("ppc", true)
1236 .Case("ppc64", true)
1237 .Default(false);
Kevin Enderby4c8dfe42014-06-30 18:45:23 +00001238}
1239
Alexey Samsonove6388e62013-06-18 15:03:28 +00001240unsigned MachOObjectFile::getArch() const {
1241 return getArch(getCPUType(this));
1242}
1243
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001244Triple MachOObjectFile::getArch(const char **McpuDefault,
1245 Triple *ThumbTriple) const {
Alexey Samsonov13415ed2015-06-04 19:22:03 +00001246 *ThumbTriple = getThumbArch(Header.cputype, Header.cpusubtype, McpuDefault);
1247 return getArch(Header.cputype, Header.cpusubtype, McpuDefault);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001248}
1249
Rui Ueyamabc654b12013-09-27 21:47:05 +00001250relocation_iterator MachOObjectFile::section_rel_begin(unsigned Index) const {
Rafael Espindola6e040c02013-04-26 20:07:33 +00001251 DataRefImpl DRI;
1252 DRI.d.a = Index;
Rui Ueyamabc654b12013-09-27 21:47:05 +00001253 return section_rel_begin(DRI);
Rafael Espindola6e040c02013-04-26 20:07:33 +00001254}
1255
Rui Ueyamabc654b12013-09-27 21:47:05 +00001256relocation_iterator MachOObjectFile::section_rel_end(unsigned Index) const {
Rafael Espindola6e040c02013-04-26 20:07:33 +00001257 DataRefImpl DRI;
1258 DRI.d.a = Index;
Rui Ueyamabc654b12013-09-27 21:47:05 +00001259 return section_rel_end(DRI);
Rafael Espindola6e040c02013-04-26 20:07:33 +00001260}
1261
Kevin Enderby273ae012013-06-06 17:20:50 +00001262dice_iterator MachOObjectFile::begin_dices() const {
1263 DataRefImpl DRI;
1264 if (!DataInCodeLoadCmd)
1265 return dice_iterator(DiceRef(DRI, this));
1266
Charles Davis8bdfafd2013-09-01 04:28:48 +00001267 MachO::linkedit_data_command DicLC = getDataInCodeLoadCommand();
1268 DRI.p = reinterpret_cast<uintptr_t>(getPtr(this, DicLC.dataoff));
Kevin Enderby273ae012013-06-06 17:20:50 +00001269 return dice_iterator(DiceRef(DRI, this));
1270}
1271
1272dice_iterator MachOObjectFile::end_dices() const {
1273 DataRefImpl DRI;
1274 if (!DataInCodeLoadCmd)
1275 return dice_iterator(DiceRef(DRI, this));
1276
Charles Davis8bdfafd2013-09-01 04:28:48 +00001277 MachO::linkedit_data_command DicLC = getDataInCodeLoadCommand();
1278 unsigned Offset = DicLC.dataoff + DicLC.datasize;
Kevin Enderby273ae012013-06-06 17:20:50 +00001279 DRI.p = reinterpret_cast<uintptr_t>(getPtr(this, Offset));
1280 return dice_iterator(DiceRef(DRI, this));
1281}
1282
Nick Kledzikd04bc352014-08-30 00:20:14 +00001283ExportEntry::ExportEntry(ArrayRef<uint8_t> T)
1284 : Trie(T), Malformed(false), Done(false) { }
1285
1286void ExportEntry::moveToFirst() {
1287 pushNode(0);
1288 pushDownUntilBottom();
1289}
1290
1291void ExportEntry::moveToEnd() {
1292 Stack.clear();
1293 Done = true;
1294}
1295
1296bool ExportEntry::operator==(const ExportEntry &Other) const {
1297 // Common case, one at end, other iterating from begin.
1298 if (Done || Other.Done)
1299 return (Done == Other.Done);
1300 // Not equal if different stack sizes.
1301 if (Stack.size() != Other.Stack.size())
1302 return false;
1303 // Not equal if different cumulative strings.
Yaron Keren075759a2015-03-30 15:42:36 +00001304 if (!CumulativeString.equals(Other.CumulativeString))
Nick Kledzikd04bc352014-08-30 00:20:14 +00001305 return false;
1306 // Equal if all nodes in both stacks match.
1307 for (unsigned i=0; i < Stack.size(); ++i) {
1308 if (Stack[i].Start != Other.Stack[i].Start)
1309 return false;
1310 }
1311 return true;
1312}
1313
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00001314uint64_t ExportEntry::readULEB128(const uint8_t *&Ptr) {
1315 unsigned Count;
1316 uint64_t Result = decodeULEB128(Ptr, &Count);
1317 Ptr += Count;
1318 if (Ptr > Trie.end()) {
1319 Ptr = Trie.end();
Nick Kledzikd04bc352014-08-30 00:20:14 +00001320 Malformed = true;
1321 }
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00001322 return Result;
Nick Kledzikd04bc352014-08-30 00:20:14 +00001323}
1324
1325StringRef ExportEntry::name() const {
Yaron Keren075759a2015-03-30 15:42:36 +00001326 return CumulativeString;
Nick Kledzikd04bc352014-08-30 00:20:14 +00001327}
1328
1329uint64_t ExportEntry::flags() const {
1330 return Stack.back().Flags;
1331}
1332
1333uint64_t ExportEntry::address() const {
1334 return Stack.back().Address;
1335}
1336
1337uint64_t ExportEntry::other() const {
1338 return Stack.back().Other;
1339}
1340
1341StringRef ExportEntry::otherName() const {
1342 const char* ImportName = Stack.back().ImportName;
1343 if (ImportName)
1344 return StringRef(ImportName);
1345 return StringRef();
1346}
1347
1348uint32_t ExportEntry::nodeOffset() const {
1349 return Stack.back().Start - Trie.begin();
1350}
1351
1352ExportEntry::NodeState::NodeState(const uint8_t *Ptr)
1353 : Start(Ptr), Current(Ptr), Flags(0), Address(0), Other(0),
1354 ImportName(nullptr), ChildCount(0), NextChildIndex(0),
1355 ParentStringLength(0), IsExportNode(false) {
1356}
1357
1358void ExportEntry::pushNode(uint64_t offset) {
1359 const uint8_t *Ptr = Trie.begin() + offset;
1360 NodeState State(Ptr);
1361 uint64_t ExportInfoSize = readULEB128(State.Current);
1362 State.IsExportNode = (ExportInfoSize != 0);
1363 const uint8_t* Children = State.Current + ExportInfoSize;
1364 if (State.IsExportNode) {
1365 State.Flags = readULEB128(State.Current);
1366 if (State.Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT) {
1367 State.Address = 0;
1368 State.Other = readULEB128(State.Current); // dylib ordinal
1369 State.ImportName = reinterpret_cast<const char*>(State.Current);
1370 } else {
1371 State.Address = readULEB128(State.Current);
Nick Kledzik1b591bd2014-08-30 01:57:34 +00001372 if (State.Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER)
1373 State.Other = readULEB128(State.Current);
Nick Kledzikd04bc352014-08-30 00:20:14 +00001374 }
1375 }
1376 State.ChildCount = *Children;
1377 State.Current = Children + 1;
1378 State.NextChildIndex = 0;
1379 State.ParentStringLength = CumulativeString.size();
1380 Stack.push_back(State);
1381}
1382
1383void ExportEntry::pushDownUntilBottom() {
1384 while (Stack.back().NextChildIndex < Stack.back().ChildCount) {
1385 NodeState &Top = Stack.back();
1386 CumulativeString.resize(Top.ParentStringLength);
1387 for (;*Top.Current != 0; Top.Current++) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00001388 char C = *Top.Current;
1389 CumulativeString.push_back(C);
Nick Kledzikd04bc352014-08-30 00:20:14 +00001390 }
1391 Top.Current += 1;
1392 uint64_t childNodeIndex = readULEB128(Top.Current);
1393 Top.NextChildIndex += 1;
1394 pushNode(childNodeIndex);
1395 }
1396 if (!Stack.back().IsExportNode) {
1397 Malformed = true;
1398 moveToEnd();
1399 }
1400}
1401
1402// We have a trie data structure and need a way to walk it that is compatible
1403// with the C++ iterator model. The solution is a non-recursive depth first
1404// traversal where the iterator contains a stack of parent nodes along with a
1405// string that is the accumulation of all edge strings along the parent chain
1406// to this point.
1407//
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00001408// There is one "export" node for each exported symbol. But because some
Nick Kledzikd04bc352014-08-30 00:20:14 +00001409// symbols may be a prefix of another symbol (e.g. _dup and _dup2), an export
1410// node may have child nodes too.
1411//
1412// The algorithm for moveNext() is to keep moving down the leftmost unvisited
1413// child until hitting a node with no children (which is an export node or
1414// else the trie is malformed). On the way down, each node is pushed on the
1415// stack ivar. If there is no more ways down, it pops up one and tries to go
1416// down a sibling path until a childless node is reached.
1417void ExportEntry::moveNext() {
1418 if (Stack.empty() || !Stack.back().IsExportNode) {
1419 Malformed = true;
1420 moveToEnd();
1421 return;
1422 }
1423
1424 Stack.pop_back();
1425 while (!Stack.empty()) {
1426 NodeState &Top = Stack.back();
1427 if (Top.NextChildIndex < Top.ChildCount) {
1428 pushDownUntilBottom();
1429 // Now at the next export node.
1430 return;
1431 } else {
1432 if (Top.IsExportNode) {
1433 // This node has no children but is itself an export node.
1434 CumulativeString.resize(Top.ParentStringLength);
1435 return;
1436 }
1437 Stack.pop_back();
1438 }
1439 }
1440 Done = true;
1441}
1442
1443iterator_range<export_iterator>
1444MachOObjectFile::exports(ArrayRef<uint8_t> Trie) {
1445 ExportEntry Start(Trie);
Juergen Ributzka4d7f70d2014-12-19 02:31:01 +00001446 if (Trie.size() == 0)
1447 Start.moveToEnd();
1448 else
1449 Start.moveToFirst();
Nick Kledzikd04bc352014-08-30 00:20:14 +00001450
1451 ExportEntry Finish(Trie);
1452 Finish.moveToEnd();
1453
1454 return iterator_range<export_iterator>(export_iterator(Start),
1455 export_iterator(Finish));
1456}
1457
1458iterator_range<export_iterator> MachOObjectFile::exports() const {
1459 return exports(getDyldInfoExportsTrie());
1460}
1461
1462
Nick Kledzikac431442014-09-12 21:34:15 +00001463MachORebaseEntry::MachORebaseEntry(ArrayRef<uint8_t> Bytes, bool is64Bit)
1464 : Opcodes(Bytes), Ptr(Bytes.begin()), SegmentOffset(0), SegmentIndex(0),
1465 RemainingLoopCount(0), AdvanceAmount(0), RebaseType(0),
1466 PointerSize(is64Bit ? 8 : 4), Malformed(false), Done(false) {}
1467
1468void MachORebaseEntry::moveToFirst() {
1469 Ptr = Opcodes.begin();
1470 moveNext();
1471}
1472
1473void MachORebaseEntry::moveToEnd() {
1474 Ptr = Opcodes.end();
1475 RemainingLoopCount = 0;
1476 Done = true;
1477}
1478
1479void MachORebaseEntry::moveNext() {
1480 // If in the middle of some loop, move to next rebasing in loop.
1481 SegmentOffset += AdvanceAmount;
1482 if (RemainingLoopCount) {
1483 --RemainingLoopCount;
1484 return;
1485 }
1486 if (Ptr == Opcodes.end()) {
1487 Done = true;
1488 return;
1489 }
1490 bool More = true;
1491 while (More && !Malformed) {
1492 // Parse next opcode and set up next loop.
1493 uint8_t Byte = *Ptr++;
1494 uint8_t ImmValue = Byte & MachO::REBASE_IMMEDIATE_MASK;
1495 uint8_t Opcode = Byte & MachO::REBASE_OPCODE_MASK;
1496 switch (Opcode) {
1497 case MachO::REBASE_OPCODE_DONE:
1498 More = false;
1499 Done = true;
1500 moveToEnd();
1501 DEBUG_WITH_TYPE("mach-o-rebase", llvm::dbgs() << "REBASE_OPCODE_DONE\n");
1502 break;
1503 case MachO::REBASE_OPCODE_SET_TYPE_IMM:
1504 RebaseType = ImmValue;
1505 DEBUG_WITH_TYPE(
1506 "mach-o-rebase",
1507 llvm::dbgs() << "REBASE_OPCODE_SET_TYPE_IMM: "
1508 << "RebaseType=" << (int) RebaseType << "\n");
1509 break;
1510 case MachO::REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:
1511 SegmentIndex = ImmValue;
1512 SegmentOffset = readULEB128();
1513 DEBUG_WITH_TYPE(
1514 "mach-o-rebase",
1515 llvm::dbgs() << "REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: "
1516 << "SegmentIndex=" << SegmentIndex << ", "
1517 << format("SegmentOffset=0x%06X", SegmentOffset)
1518 << "\n");
1519 break;
1520 case MachO::REBASE_OPCODE_ADD_ADDR_ULEB:
1521 SegmentOffset += readULEB128();
1522 DEBUG_WITH_TYPE("mach-o-rebase",
1523 llvm::dbgs() << "REBASE_OPCODE_ADD_ADDR_ULEB: "
1524 << format("SegmentOffset=0x%06X",
1525 SegmentOffset) << "\n");
1526 break;
1527 case MachO::REBASE_OPCODE_ADD_ADDR_IMM_SCALED:
1528 SegmentOffset += ImmValue * PointerSize;
1529 DEBUG_WITH_TYPE("mach-o-rebase",
1530 llvm::dbgs() << "REBASE_OPCODE_ADD_ADDR_IMM_SCALED: "
1531 << format("SegmentOffset=0x%06X",
1532 SegmentOffset) << "\n");
1533 break;
1534 case MachO::REBASE_OPCODE_DO_REBASE_IMM_TIMES:
1535 AdvanceAmount = PointerSize;
1536 RemainingLoopCount = ImmValue - 1;
1537 DEBUG_WITH_TYPE(
1538 "mach-o-rebase",
1539 llvm::dbgs() << "REBASE_OPCODE_DO_REBASE_IMM_TIMES: "
1540 << format("SegmentOffset=0x%06X", SegmentOffset)
1541 << ", AdvanceAmount=" << AdvanceAmount
1542 << ", RemainingLoopCount=" << RemainingLoopCount
1543 << "\n");
1544 return;
1545 case MachO::REBASE_OPCODE_DO_REBASE_ULEB_TIMES:
1546 AdvanceAmount = PointerSize;
1547 RemainingLoopCount = readULEB128() - 1;
1548 DEBUG_WITH_TYPE(
1549 "mach-o-rebase",
1550 llvm::dbgs() << "REBASE_OPCODE_DO_REBASE_ULEB_TIMES: "
1551 << format("SegmentOffset=0x%06X", SegmentOffset)
1552 << ", AdvanceAmount=" << AdvanceAmount
1553 << ", RemainingLoopCount=" << RemainingLoopCount
1554 << "\n");
1555 return;
1556 case MachO::REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB:
1557 AdvanceAmount = readULEB128() + PointerSize;
1558 RemainingLoopCount = 0;
1559 DEBUG_WITH_TYPE(
1560 "mach-o-rebase",
1561 llvm::dbgs() << "REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB: "
1562 << format("SegmentOffset=0x%06X", SegmentOffset)
1563 << ", AdvanceAmount=" << AdvanceAmount
1564 << ", RemainingLoopCount=" << RemainingLoopCount
1565 << "\n");
1566 return;
1567 case MachO::REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB:
1568 RemainingLoopCount = readULEB128() - 1;
1569 AdvanceAmount = readULEB128() + PointerSize;
1570 DEBUG_WITH_TYPE(
1571 "mach-o-rebase",
1572 llvm::dbgs() << "REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB: "
1573 << format("SegmentOffset=0x%06X", SegmentOffset)
1574 << ", AdvanceAmount=" << AdvanceAmount
1575 << ", RemainingLoopCount=" << RemainingLoopCount
1576 << "\n");
1577 return;
1578 default:
1579 Malformed = true;
1580 }
1581 }
1582}
1583
1584uint64_t MachORebaseEntry::readULEB128() {
1585 unsigned Count;
1586 uint64_t Result = decodeULEB128(Ptr, &Count);
1587 Ptr += Count;
1588 if (Ptr > Opcodes.end()) {
1589 Ptr = Opcodes.end();
1590 Malformed = true;
1591 }
1592 return Result;
1593}
1594
1595uint32_t MachORebaseEntry::segmentIndex() const { return SegmentIndex; }
1596
1597uint64_t MachORebaseEntry::segmentOffset() const { return SegmentOffset; }
1598
1599StringRef MachORebaseEntry::typeName() const {
1600 switch (RebaseType) {
1601 case MachO::REBASE_TYPE_POINTER:
1602 return "pointer";
1603 case MachO::REBASE_TYPE_TEXT_ABSOLUTE32:
1604 return "text abs32";
1605 case MachO::REBASE_TYPE_TEXT_PCREL32:
1606 return "text rel32";
1607 }
1608 return "unknown";
1609}
1610
1611bool MachORebaseEntry::operator==(const MachORebaseEntry &Other) const {
1612 assert(Opcodes == Other.Opcodes && "compare iterators of different files");
1613 return (Ptr == Other.Ptr) &&
1614 (RemainingLoopCount == Other.RemainingLoopCount) &&
1615 (Done == Other.Done);
1616}
1617
1618iterator_range<rebase_iterator>
1619MachOObjectFile::rebaseTable(ArrayRef<uint8_t> Opcodes, bool is64) {
1620 MachORebaseEntry Start(Opcodes, is64);
1621 Start.moveToFirst();
1622
1623 MachORebaseEntry Finish(Opcodes, is64);
1624 Finish.moveToEnd();
1625
1626 return iterator_range<rebase_iterator>(rebase_iterator(Start),
1627 rebase_iterator(Finish));
1628}
1629
1630iterator_range<rebase_iterator> MachOObjectFile::rebaseTable() const {
1631 return rebaseTable(getDyldInfoRebaseOpcodes(), is64Bit());
1632}
1633
Nick Kledzik56ebef42014-09-16 01:41:51 +00001634
1635MachOBindEntry::MachOBindEntry(ArrayRef<uint8_t> Bytes, bool is64Bit,
1636 Kind BK)
1637 : Opcodes(Bytes), Ptr(Bytes.begin()), SegmentOffset(0), SegmentIndex(0),
1638 Ordinal(0), Flags(0), Addend(0), RemainingLoopCount(0), AdvanceAmount(0),
1639 BindType(0), PointerSize(is64Bit ? 8 : 4),
1640 TableKind(BK), Malformed(false), Done(false) {}
1641
1642void MachOBindEntry::moveToFirst() {
1643 Ptr = Opcodes.begin();
1644 moveNext();
1645}
1646
1647void MachOBindEntry::moveToEnd() {
1648 Ptr = Opcodes.end();
1649 RemainingLoopCount = 0;
1650 Done = true;
1651}
1652
1653void MachOBindEntry::moveNext() {
1654 // If in the middle of some loop, move to next binding in loop.
1655 SegmentOffset += AdvanceAmount;
1656 if (RemainingLoopCount) {
1657 --RemainingLoopCount;
1658 return;
1659 }
1660 if (Ptr == Opcodes.end()) {
1661 Done = true;
1662 return;
1663 }
1664 bool More = true;
1665 while (More && !Malformed) {
1666 // Parse next opcode and set up next loop.
1667 uint8_t Byte = *Ptr++;
1668 uint8_t ImmValue = Byte & MachO::BIND_IMMEDIATE_MASK;
1669 uint8_t Opcode = Byte & MachO::BIND_OPCODE_MASK;
1670 int8_t SignExtended;
1671 const uint8_t *SymStart;
1672 switch (Opcode) {
1673 case MachO::BIND_OPCODE_DONE:
1674 if (TableKind == Kind::Lazy) {
1675 // Lazying bindings have a DONE opcode between entries. Need to ignore
1676 // it to advance to next entry. But need not if this is last entry.
1677 bool NotLastEntry = false;
1678 for (const uint8_t *P = Ptr; P < Opcodes.end(); ++P) {
1679 if (*P) {
1680 NotLastEntry = true;
1681 }
1682 }
1683 if (NotLastEntry)
1684 break;
1685 }
1686 More = false;
1687 Done = true;
1688 moveToEnd();
1689 DEBUG_WITH_TYPE("mach-o-bind", llvm::dbgs() << "BIND_OPCODE_DONE\n");
1690 break;
1691 case MachO::BIND_OPCODE_SET_DYLIB_ORDINAL_IMM:
1692 Ordinal = ImmValue;
1693 DEBUG_WITH_TYPE(
1694 "mach-o-bind",
1695 llvm::dbgs() << "BIND_OPCODE_SET_DYLIB_ORDINAL_IMM: "
1696 << "Ordinal=" << Ordinal << "\n");
1697 break;
1698 case MachO::BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB:
1699 Ordinal = readULEB128();
1700 DEBUG_WITH_TYPE(
1701 "mach-o-bind",
1702 llvm::dbgs() << "BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB: "
1703 << "Ordinal=" << Ordinal << "\n");
1704 break;
1705 case MachO::BIND_OPCODE_SET_DYLIB_SPECIAL_IMM:
1706 if (ImmValue) {
1707 SignExtended = MachO::BIND_OPCODE_MASK | ImmValue;
1708 Ordinal = SignExtended;
1709 } else
1710 Ordinal = 0;
1711 DEBUG_WITH_TYPE(
1712 "mach-o-bind",
1713 llvm::dbgs() << "BIND_OPCODE_SET_DYLIB_SPECIAL_IMM: "
1714 << "Ordinal=" << Ordinal << "\n");
1715 break;
1716 case MachO::BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM:
1717 Flags = ImmValue;
1718 SymStart = Ptr;
1719 while (*Ptr) {
1720 ++Ptr;
1721 }
Nick Kledzik56ebef42014-09-16 01:41:51 +00001722 SymbolName = StringRef(reinterpret_cast<const char*>(SymStart),
1723 Ptr-SymStart);
Nick Kledzika6375362014-09-17 01:51:43 +00001724 ++Ptr;
Nick Kledzik56ebef42014-09-16 01:41:51 +00001725 DEBUG_WITH_TYPE(
1726 "mach-o-bind",
1727 llvm::dbgs() << "BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM: "
1728 << "SymbolName=" << SymbolName << "\n");
1729 if (TableKind == Kind::Weak) {
1730 if (ImmValue & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION)
1731 return;
1732 }
1733 break;
1734 case MachO::BIND_OPCODE_SET_TYPE_IMM:
1735 BindType = ImmValue;
1736 DEBUG_WITH_TYPE(
1737 "mach-o-bind",
1738 llvm::dbgs() << "BIND_OPCODE_SET_TYPE_IMM: "
1739 << "BindType=" << (int)BindType << "\n");
1740 break;
1741 case MachO::BIND_OPCODE_SET_ADDEND_SLEB:
1742 Addend = readSLEB128();
1743 if (TableKind == Kind::Lazy)
1744 Malformed = true;
1745 DEBUG_WITH_TYPE(
1746 "mach-o-bind",
1747 llvm::dbgs() << "BIND_OPCODE_SET_ADDEND_SLEB: "
1748 << "Addend=" << Addend << "\n");
1749 break;
1750 case MachO::BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:
1751 SegmentIndex = ImmValue;
1752 SegmentOffset = readULEB128();
1753 DEBUG_WITH_TYPE(
1754 "mach-o-bind",
1755 llvm::dbgs() << "BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: "
1756 << "SegmentIndex=" << SegmentIndex << ", "
1757 << format("SegmentOffset=0x%06X", SegmentOffset)
1758 << "\n");
1759 break;
1760 case MachO::BIND_OPCODE_ADD_ADDR_ULEB:
1761 SegmentOffset += readULEB128();
1762 DEBUG_WITH_TYPE("mach-o-bind",
1763 llvm::dbgs() << "BIND_OPCODE_ADD_ADDR_ULEB: "
1764 << format("SegmentOffset=0x%06X",
1765 SegmentOffset) << "\n");
1766 break;
1767 case MachO::BIND_OPCODE_DO_BIND:
1768 AdvanceAmount = PointerSize;
1769 RemainingLoopCount = 0;
1770 DEBUG_WITH_TYPE("mach-o-bind",
1771 llvm::dbgs() << "BIND_OPCODE_DO_BIND: "
1772 << format("SegmentOffset=0x%06X",
1773 SegmentOffset) << "\n");
1774 return;
1775 case MachO::BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB:
Nick Kledzik3b2aa052014-10-18 01:21:02 +00001776 AdvanceAmount = readULEB128() + PointerSize;
Nick Kledzik56ebef42014-09-16 01:41:51 +00001777 RemainingLoopCount = 0;
1778 if (TableKind == Kind::Lazy)
1779 Malformed = true;
1780 DEBUG_WITH_TYPE(
1781 "mach-o-bind",
Nick Kledzik3b2aa052014-10-18 01:21:02 +00001782 llvm::dbgs() << "BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB: "
Nick Kledzik56ebef42014-09-16 01:41:51 +00001783 << format("SegmentOffset=0x%06X", SegmentOffset)
1784 << ", AdvanceAmount=" << AdvanceAmount
1785 << ", RemainingLoopCount=" << RemainingLoopCount
1786 << "\n");
1787 return;
1788 case MachO::BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED:
Nick Kledzik3b2aa052014-10-18 01:21:02 +00001789 AdvanceAmount = ImmValue * PointerSize + PointerSize;
Nick Kledzik56ebef42014-09-16 01:41:51 +00001790 RemainingLoopCount = 0;
1791 if (TableKind == Kind::Lazy)
1792 Malformed = true;
1793 DEBUG_WITH_TYPE("mach-o-bind",
1794 llvm::dbgs()
1795 << "BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED: "
1796 << format("SegmentOffset=0x%06X",
1797 SegmentOffset) << "\n");
1798 return;
1799 case MachO::BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB:
1800 RemainingLoopCount = readULEB128() - 1;
1801 AdvanceAmount = readULEB128() + PointerSize;
1802 if (TableKind == Kind::Lazy)
1803 Malformed = true;
1804 DEBUG_WITH_TYPE(
1805 "mach-o-bind",
1806 llvm::dbgs() << "BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB: "
1807 << format("SegmentOffset=0x%06X", SegmentOffset)
1808 << ", AdvanceAmount=" << AdvanceAmount
1809 << ", RemainingLoopCount=" << RemainingLoopCount
1810 << "\n");
1811 return;
1812 default:
1813 Malformed = true;
1814 }
1815 }
1816}
1817
1818uint64_t MachOBindEntry::readULEB128() {
1819 unsigned Count;
1820 uint64_t Result = decodeULEB128(Ptr, &Count);
1821 Ptr += Count;
1822 if (Ptr > Opcodes.end()) {
1823 Ptr = Opcodes.end();
1824 Malformed = true;
1825 }
1826 return Result;
1827}
1828
1829int64_t MachOBindEntry::readSLEB128() {
1830 unsigned Count;
1831 int64_t Result = decodeSLEB128(Ptr, &Count);
1832 Ptr += Count;
1833 if (Ptr > Opcodes.end()) {
1834 Ptr = Opcodes.end();
1835 Malformed = true;
1836 }
1837 return Result;
1838}
1839
1840
1841uint32_t MachOBindEntry::segmentIndex() const { return SegmentIndex; }
1842
1843uint64_t MachOBindEntry::segmentOffset() const { return SegmentOffset; }
1844
1845StringRef MachOBindEntry::typeName() const {
1846 switch (BindType) {
1847 case MachO::BIND_TYPE_POINTER:
1848 return "pointer";
1849 case MachO::BIND_TYPE_TEXT_ABSOLUTE32:
1850 return "text abs32";
1851 case MachO::BIND_TYPE_TEXT_PCREL32:
1852 return "text rel32";
1853 }
1854 return "unknown";
1855}
1856
1857StringRef MachOBindEntry::symbolName() const { return SymbolName; }
1858
1859int64_t MachOBindEntry::addend() const { return Addend; }
1860
1861uint32_t MachOBindEntry::flags() const { return Flags; }
1862
1863int MachOBindEntry::ordinal() const { return Ordinal; }
1864
1865bool MachOBindEntry::operator==(const MachOBindEntry &Other) const {
1866 assert(Opcodes == Other.Opcodes && "compare iterators of different files");
1867 return (Ptr == Other.Ptr) &&
1868 (RemainingLoopCount == Other.RemainingLoopCount) &&
1869 (Done == Other.Done);
1870}
1871
1872iterator_range<bind_iterator>
1873MachOObjectFile::bindTable(ArrayRef<uint8_t> Opcodes, bool is64,
1874 MachOBindEntry::Kind BKind) {
1875 MachOBindEntry Start(Opcodes, is64, BKind);
1876 Start.moveToFirst();
1877
1878 MachOBindEntry Finish(Opcodes, is64, BKind);
1879 Finish.moveToEnd();
1880
1881 return iterator_range<bind_iterator>(bind_iterator(Start),
1882 bind_iterator(Finish));
1883}
1884
1885iterator_range<bind_iterator> MachOObjectFile::bindTable() const {
1886 return bindTable(getDyldInfoBindOpcodes(), is64Bit(),
1887 MachOBindEntry::Kind::Regular);
1888}
1889
1890iterator_range<bind_iterator> MachOObjectFile::lazyBindTable() const {
1891 return bindTable(getDyldInfoLazyBindOpcodes(), is64Bit(),
1892 MachOBindEntry::Kind::Lazy);
1893}
1894
1895iterator_range<bind_iterator> MachOObjectFile::weakBindTable() const {
1896 return bindTable(getDyldInfoWeakBindOpcodes(), is64Bit(),
1897 MachOBindEntry::Kind::Weak);
1898}
1899
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00001900MachOObjectFile::load_command_iterator
1901MachOObjectFile::begin_load_commands() const {
1902 return LoadCommands.begin();
1903}
1904
1905MachOObjectFile::load_command_iterator
1906MachOObjectFile::end_load_commands() const {
1907 return LoadCommands.end();
1908}
1909
1910iterator_range<MachOObjectFile::load_command_iterator>
1911MachOObjectFile::load_commands() const {
1912 return iterator_range<load_command_iterator>(begin_load_commands(),
1913 end_load_commands());
1914}
1915
Rafael Espindola56f976f2013-04-18 18:08:55 +00001916StringRef
1917MachOObjectFile::getSectionFinalSegmentName(DataRefImpl Sec) const {
1918 ArrayRef<char> Raw = getSectionRawFinalSegmentName(Sec);
1919 return parseSegmentOrSectionName(Raw.data());
1920}
1921
1922ArrayRef<char>
1923MachOObjectFile::getSectionRawName(DataRefImpl Sec) const {
Rafael Espindola0d85d102015-05-22 14:59:27 +00001924 assert(Sec.d.a < Sections.size() && "Should have detected this earlier");
Charles Davis8bdfafd2013-09-01 04:28:48 +00001925 const section_base *Base =
1926 reinterpret_cast<const section_base *>(Sections[Sec.d.a]);
Craig Toppere1d12942014-08-27 05:25:25 +00001927 return makeArrayRef(Base->sectname);
Rafael Espindola56f976f2013-04-18 18:08:55 +00001928}
1929
1930ArrayRef<char>
1931MachOObjectFile::getSectionRawFinalSegmentName(DataRefImpl Sec) const {
Rafael Espindola0d85d102015-05-22 14:59:27 +00001932 assert(Sec.d.a < Sections.size() && "Should have detected this earlier");
Charles Davis8bdfafd2013-09-01 04:28:48 +00001933 const section_base *Base =
1934 reinterpret_cast<const section_base *>(Sections[Sec.d.a]);
Craig Toppere1d12942014-08-27 05:25:25 +00001935 return makeArrayRef(Base->segname);
Rafael Espindola56f976f2013-04-18 18:08:55 +00001936}
1937
1938bool
Charles Davis8bdfafd2013-09-01 04:28:48 +00001939MachOObjectFile::isRelocationScattered(const MachO::any_relocation_info &RE)
Rafael Espindola56f976f2013-04-18 18:08:55 +00001940 const {
Charles Davis8bdfafd2013-09-01 04:28:48 +00001941 if (getCPUType(this) == MachO::CPU_TYPE_X86_64)
Rafael Espindola56f976f2013-04-18 18:08:55 +00001942 return false;
Charles Davis8bdfafd2013-09-01 04:28:48 +00001943 return getPlainRelocationAddress(RE) & MachO::R_SCATTERED;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001944}
1945
Eric Christopher1d62c252013-07-22 22:25:07 +00001946unsigned MachOObjectFile::getPlainRelocationSymbolNum(
Charles Davis8bdfafd2013-09-01 04:28:48 +00001947 const MachO::any_relocation_info &RE) const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00001948 if (isLittleEndian())
Charles Davis8bdfafd2013-09-01 04:28:48 +00001949 return RE.r_word1 & 0xffffff;
1950 return RE.r_word1 >> 8;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001951}
1952
Eric Christopher1d62c252013-07-22 22:25:07 +00001953bool MachOObjectFile::getPlainRelocationExternal(
Charles Davis8bdfafd2013-09-01 04:28:48 +00001954 const MachO::any_relocation_info &RE) const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00001955 if (isLittleEndian())
Charles Davis8bdfafd2013-09-01 04:28:48 +00001956 return (RE.r_word1 >> 27) & 1;
1957 return (RE.r_word1 >> 4) & 1;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001958}
1959
Eric Christopher1d62c252013-07-22 22:25:07 +00001960bool MachOObjectFile::getScatteredRelocationScattered(
Charles Davis8bdfafd2013-09-01 04:28:48 +00001961 const MachO::any_relocation_info &RE) const {
1962 return RE.r_word0 >> 31;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001963}
1964
Eric Christopher1d62c252013-07-22 22:25:07 +00001965uint32_t MachOObjectFile::getScatteredRelocationValue(
Charles Davis8bdfafd2013-09-01 04:28:48 +00001966 const MachO::any_relocation_info &RE) const {
1967 return RE.r_word1;
Rafael Espindola56f976f2013-04-18 18:08:55 +00001968}
1969
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001970uint32_t MachOObjectFile::getScatteredRelocationType(
1971 const MachO::any_relocation_info &RE) const {
1972 return (RE.r_word0 >> 24) & 0xf;
1973}
1974
Eric Christopher1d62c252013-07-22 22:25:07 +00001975unsigned MachOObjectFile::getAnyRelocationAddress(
Charles Davis8bdfafd2013-09-01 04:28:48 +00001976 const MachO::any_relocation_info &RE) const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00001977 if (isRelocationScattered(RE))
1978 return getScatteredRelocationAddress(RE);
1979 return getPlainRelocationAddress(RE);
1980}
1981
Charles Davis8bdfafd2013-09-01 04:28:48 +00001982unsigned MachOObjectFile::getAnyRelocationPCRel(
1983 const MachO::any_relocation_info &RE) const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00001984 if (isRelocationScattered(RE))
1985 return getScatteredRelocationPCRel(this, RE);
1986 return getPlainRelocationPCRel(this, RE);
1987}
1988
Eric Christopher1d62c252013-07-22 22:25:07 +00001989unsigned MachOObjectFile::getAnyRelocationLength(
Charles Davis8bdfafd2013-09-01 04:28:48 +00001990 const MachO::any_relocation_info &RE) const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00001991 if (isRelocationScattered(RE))
1992 return getScatteredRelocationLength(RE);
1993 return getPlainRelocationLength(this, RE);
1994}
1995
1996unsigned
Charles Davis8bdfafd2013-09-01 04:28:48 +00001997MachOObjectFile::getAnyRelocationType(
1998 const MachO::any_relocation_info &RE) const {
Rafael Espindola56f976f2013-04-18 18:08:55 +00001999 if (isRelocationScattered(RE))
2000 return getScatteredRelocationType(RE);
2001 return getPlainRelocationType(this, RE);
2002}
2003
Rafael Espindola52501032013-04-30 15:40:54 +00002004SectionRef
Keno Fischerc780e8e2015-05-21 21:24:32 +00002005MachOObjectFile::getAnyRelocationSection(
Charles Davis8bdfafd2013-09-01 04:28:48 +00002006 const MachO::any_relocation_info &RE) const {
Rafael Espindola52501032013-04-30 15:40:54 +00002007 if (isRelocationScattered(RE) || getPlainRelocationExternal(RE))
Rafael Espindolab5155a52014-02-10 20:24:04 +00002008 return *section_end();
Rafael Espindola9ac06a02015-06-18 22:38:20 +00002009 unsigned SecNum = getPlainRelocationSymbolNum(RE);
2010 if (SecNum == MachO::R_ABS || SecNum > Sections.size())
2011 return *section_end();
Rafael Espindola52501032013-04-30 15:40:54 +00002012 DataRefImpl DRI;
Rafael Espindola9ac06a02015-06-18 22:38:20 +00002013 DRI.d.a = SecNum - 1;
Rafael Espindola52501032013-04-30 15:40:54 +00002014 return SectionRef(DRI, this);
2015}
2016
Charles Davis8bdfafd2013-09-01 04:28:48 +00002017MachO::section MachOObjectFile::getSection(DataRefImpl DRI) const {
Rafael Espindola62a07cb2015-05-22 15:43:00 +00002018 assert(DRI.d.a < Sections.size() && "Should have detected this earlier");
Charles Davis8bdfafd2013-09-01 04:28:48 +00002019 return getStruct<MachO::section>(this, Sections[DRI.d.a]);
Rafael Espindola56f976f2013-04-18 18:08:55 +00002020}
2021
Charles Davis8bdfafd2013-09-01 04:28:48 +00002022MachO::section_64 MachOObjectFile::getSection64(DataRefImpl DRI) const {
Rafael Espindola62a07cb2015-05-22 15:43:00 +00002023 assert(DRI.d.a < Sections.size() && "Should have detected this earlier");
Charles Davis8bdfafd2013-09-01 04:28:48 +00002024 return getStruct<MachO::section_64>(this, Sections[DRI.d.a]);
Rafael Espindola56f976f2013-04-18 18:08:55 +00002025}
2026
Charles Davis8bdfafd2013-09-01 04:28:48 +00002027MachO::section MachOObjectFile::getSection(const LoadCommandInfo &L,
Rafael Espindola6e040c02013-04-26 20:07:33 +00002028 unsigned Index) const {
2029 const char *Sec = getSectionPtr(this, L, Index);
Charles Davis8bdfafd2013-09-01 04:28:48 +00002030 return getStruct<MachO::section>(this, Sec);
Rafael Espindola6e040c02013-04-26 20:07:33 +00002031}
2032
Charles Davis8bdfafd2013-09-01 04:28:48 +00002033MachO::section_64 MachOObjectFile::getSection64(const LoadCommandInfo &L,
2034 unsigned Index) const {
Rafael Espindola6e040c02013-04-26 20:07:33 +00002035 const char *Sec = getSectionPtr(this, L, Index);
Charles Davis8bdfafd2013-09-01 04:28:48 +00002036 return getStruct<MachO::section_64>(this, Sec);
Rafael Espindola6e040c02013-04-26 20:07:33 +00002037}
2038
Charles Davis8bdfafd2013-09-01 04:28:48 +00002039MachO::nlist
Rafael Espindola56f976f2013-04-18 18:08:55 +00002040MachOObjectFile::getSymbolTableEntry(DataRefImpl DRI) const {
Rafael Espindola75c30362013-04-24 19:47:55 +00002041 const char *P = reinterpret_cast<const char *>(DRI.p);
Charles Davis8bdfafd2013-09-01 04:28:48 +00002042 return getStruct<MachO::nlist>(this, P);
Rafael Espindola56f976f2013-04-18 18:08:55 +00002043}
2044
Charles Davis8bdfafd2013-09-01 04:28:48 +00002045MachO::nlist_64
Rafael Espindola56f976f2013-04-18 18:08:55 +00002046MachOObjectFile::getSymbol64TableEntry(DataRefImpl DRI) const {
Rafael Espindola75c30362013-04-24 19:47:55 +00002047 const char *P = reinterpret_cast<const char *>(DRI.p);
Charles Davis8bdfafd2013-09-01 04:28:48 +00002048 return getStruct<MachO::nlist_64>(this, P);
Rafael Espindola56f976f2013-04-18 18:08:55 +00002049}
2050
Charles Davis8bdfafd2013-09-01 04:28:48 +00002051MachO::linkedit_data_command
2052MachOObjectFile::getLinkeditDataLoadCommand(const LoadCommandInfo &L) const {
2053 return getStruct<MachO::linkedit_data_command>(this, L.Ptr);
Rafael Espindola56f976f2013-04-18 18:08:55 +00002054}
2055
Charles Davis8bdfafd2013-09-01 04:28:48 +00002056MachO::segment_command
Rafael Espindola6e040c02013-04-26 20:07:33 +00002057MachOObjectFile::getSegmentLoadCommand(const LoadCommandInfo &L) const {
Charles Davis8bdfafd2013-09-01 04:28:48 +00002058 return getStruct<MachO::segment_command>(this, L.Ptr);
Rafael Espindola6e040c02013-04-26 20:07:33 +00002059}
2060
Charles Davis8bdfafd2013-09-01 04:28:48 +00002061MachO::segment_command_64
Rafael Espindola6e040c02013-04-26 20:07:33 +00002062MachOObjectFile::getSegment64LoadCommand(const LoadCommandInfo &L) const {
Charles Davis8bdfafd2013-09-01 04:28:48 +00002063 return getStruct<MachO::segment_command_64>(this, L.Ptr);
Rafael Espindola6e040c02013-04-26 20:07:33 +00002064}
2065
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00002066MachO::linker_option_command
2067MachOObjectFile::getLinkerOptionLoadCommand(const LoadCommandInfo &L) const {
2068 return getStruct<MachO::linker_option_command>(this, L.Ptr);
Rafael Espindola6e040c02013-04-26 20:07:33 +00002069}
2070
Jim Grosbach448334a2014-03-18 22:09:05 +00002071MachO::version_min_command
2072MachOObjectFile::getVersionMinLoadCommand(const LoadCommandInfo &L) const {
2073 return getStruct<MachO::version_min_command>(this, L.Ptr);
2074}
2075
Tim Northover8f9590b2014-06-30 14:40:57 +00002076MachO::dylib_command
2077MachOObjectFile::getDylibIDLoadCommand(const LoadCommandInfo &L) const {
2078 return getStruct<MachO::dylib_command>(this, L.Ptr);
2079}
2080
Kevin Enderby8ae63c12014-09-04 16:54:47 +00002081MachO::dyld_info_command
2082MachOObjectFile::getDyldInfoLoadCommand(const LoadCommandInfo &L) const {
2083 return getStruct<MachO::dyld_info_command>(this, L.Ptr);
2084}
2085
2086MachO::dylinker_command
2087MachOObjectFile::getDylinkerCommand(const LoadCommandInfo &L) const {
2088 return getStruct<MachO::dylinker_command>(this, L.Ptr);
2089}
2090
2091MachO::uuid_command
2092MachOObjectFile::getUuidCommand(const LoadCommandInfo &L) const {
2093 return getStruct<MachO::uuid_command>(this, L.Ptr);
2094}
2095
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00002096MachO::rpath_command
2097MachOObjectFile::getRpathCommand(const LoadCommandInfo &L) const {
2098 return getStruct<MachO::rpath_command>(this, L.Ptr);
2099}
2100
Kevin Enderby8ae63c12014-09-04 16:54:47 +00002101MachO::source_version_command
2102MachOObjectFile::getSourceVersionCommand(const LoadCommandInfo &L) const {
2103 return getStruct<MachO::source_version_command>(this, L.Ptr);
2104}
2105
2106MachO::entry_point_command
2107MachOObjectFile::getEntryPointCommand(const LoadCommandInfo &L) const {
2108 return getStruct<MachO::entry_point_command>(this, L.Ptr);
2109}
2110
Kevin Enderby0804f4672014-12-16 23:25:52 +00002111MachO::encryption_info_command
2112MachOObjectFile::getEncryptionInfoCommand(const LoadCommandInfo &L) const {
2113 return getStruct<MachO::encryption_info_command>(this, L.Ptr);
2114}
2115
Kevin Enderby57538292014-12-17 01:01:30 +00002116MachO::encryption_info_command_64
2117MachOObjectFile::getEncryptionInfoCommand64(const LoadCommandInfo &L) const {
2118 return getStruct<MachO::encryption_info_command_64>(this, L.Ptr);
2119}
2120
Kevin Enderbyb4b79312014-12-18 19:24:35 +00002121MachO::sub_framework_command
2122MachOObjectFile::getSubFrameworkCommand(const LoadCommandInfo &L) const {
2123 return getStruct<MachO::sub_framework_command>(this, L.Ptr);
2124}
Tim Northover8f9590b2014-06-30 14:40:57 +00002125
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00002126MachO::sub_umbrella_command
2127MachOObjectFile::getSubUmbrellaCommand(const LoadCommandInfo &L) const {
2128 return getStruct<MachO::sub_umbrella_command>(this, L.Ptr);
2129}
2130
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00002131MachO::sub_library_command
2132MachOObjectFile::getSubLibraryCommand(const LoadCommandInfo &L) const {
2133 return getStruct<MachO::sub_library_command>(this, L.Ptr);
2134}
2135
Kevin Enderby186eac32014-12-19 21:06:24 +00002136MachO::sub_client_command
2137MachOObjectFile::getSubClientCommand(const LoadCommandInfo &L) const {
2138 return getStruct<MachO::sub_client_command>(this, L.Ptr);
2139}
2140
Kevin Enderby52e4ce42014-12-19 22:25:22 +00002141MachO::routines_command
2142MachOObjectFile::getRoutinesCommand(const LoadCommandInfo &L) const {
2143 return getStruct<MachO::routines_command>(this, L.Ptr);
2144}
2145
2146MachO::routines_command_64
2147MachOObjectFile::getRoutinesCommand64(const LoadCommandInfo &L) const {
2148 return getStruct<MachO::routines_command_64>(this, L.Ptr);
2149}
2150
Kevin Enderby48ef5342014-12-23 22:56:39 +00002151MachO::thread_command
2152MachOObjectFile::getThreadCommand(const LoadCommandInfo &L) const {
2153 return getStruct<MachO::thread_command>(this, L.Ptr);
2154}
2155
Charles Davis8bdfafd2013-09-01 04:28:48 +00002156MachO::any_relocation_info
Rafael Espindola56f976f2013-04-18 18:08:55 +00002157MachOObjectFile::getRelocation(DataRefImpl Rel) const {
Rafael Espindola128b8112014-04-03 23:51:28 +00002158 DataRefImpl Sec;
2159 Sec.d.a = Rel.d.a;
2160 uint32_t Offset;
2161 if (is64Bit()) {
2162 MachO::section_64 Sect = getSection64(Sec);
2163 Offset = Sect.reloff;
2164 } else {
2165 MachO::section Sect = getSection(Sec);
2166 Offset = Sect.reloff;
2167 }
2168
2169 auto P = reinterpret_cast<const MachO::any_relocation_info *>(
2170 getPtr(this, Offset)) + Rel.d.b;
2171 return getStruct<MachO::any_relocation_info>(
2172 this, reinterpret_cast<const char *>(P));
Rafael Espindola56f976f2013-04-18 18:08:55 +00002173}
2174
Charles Davis8bdfafd2013-09-01 04:28:48 +00002175MachO::data_in_code_entry
Kevin Enderby273ae012013-06-06 17:20:50 +00002176MachOObjectFile::getDice(DataRefImpl Rel) const {
2177 const char *P = reinterpret_cast<const char *>(Rel.p);
Charles Davis8bdfafd2013-09-01 04:28:48 +00002178 return getStruct<MachO::data_in_code_entry>(this, P);
Kevin Enderby273ae012013-06-06 17:20:50 +00002179}
2180
Alexey Samsonov13415ed2015-06-04 19:22:03 +00002181const MachO::mach_header &MachOObjectFile::getHeader() const {
Alexey Samsonovfa5edc52015-06-04 22:49:55 +00002182 return Header;
Rafael Espindola56f976f2013-04-18 18:08:55 +00002183}
2184
Alexey Samsonov13415ed2015-06-04 19:22:03 +00002185const MachO::mach_header_64 &MachOObjectFile::getHeader64() const {
2186 assert(is64Bit());
2187 return Header64;
Rafael Espindola6e040c02013-04-26 20:07:33 +00002188}
2189
Charles Davis8bdfafd2013-09-01 04:28:48 +00002190uint32_t MachOObjectFile::getIndirectSymbolTableEntry(
2191 const MachO::dysymtab_command &DLC,
2192 unsigned Index) const {
2193 uint64_t Offset = DLC.indirectsymoff + Index * sizeof(uint32_t);
2194 return getStruct<uint32_t>(this, getPtr(this, Offset));
Rafael Espindola6e040c02013-04-26 20:07:33 +00002195}
2196
Charles Davis8bdfafd2013-09-01 04:28:48 +00002197MachO::data_in_code_entry
Rafael Espindola6e040c02013-04-26 20:07:33 +00002198MachOObjectFile::getDataInCodeTableEntry(uint32_t DataOffset,
2199 unsigned Index) const {
Charles Davis8bdfafd2013-09-01 04:28:48 +00002200 uint64_t Offset = DataOffset + Index * sizeof(MachO::data_in_code_entry);
2201 return getStruct<MachO::data_in_code_entry>(this, getPtr(this, Offset));
Rafael Espindola6e040c02013-04-26 20:07:33 +00002202}
2203
Charles Davis8bdfafd2013-09-01 04:28:48 +00002204MachO::symtab_command MachOObjectFile::getSymtabLoadCommand() const {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002205 if (SymtabLoadCmd)
2206 return getStruct<MachO::symtab_command>(this, SymtabLoadCmd);
2207
2208 // If there is no SymtabLoadCmd return a load command with zero'ed fields.
2209 MachO::symtab_command Cmd;
2210 Cmd.cmd = MachO::LC_SYMTAB;
2211 Cmd.cmdsize = sizeof(MachO::symtab_command);
2212 Cmd.symoff = 0;
2213 Cmd.nsyms = 0;
2214 Cmd.stroff = 0;
2215 Cmd.strsize = 0;
2216 return Cmd;
Rafael Espindola56f976f2013-04-18 18:08:55 +00002217}
2218
Charles Davis8bdfafd2013-09-01 04:28:48 +00002219MachO::dysymtab_command MachOObjectFile::getDysymtabLoadCommand() const {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002220 if (DysymtabLoadCmd)
2221 return getStruct<MachO::dysymtab_command>(this, DysymtabLoadCmd);
2222
2223 // If there is no DysymtabLoadCmd return a load command with zero'ed fields.
2224 MachO::dysymtab_command Cmd;
2225 Cmd.cmd = MachO::LC_DYSYMTAB;
2226 Cmd.cmdsize = sizeof(MachO::dysymtab_command);
2227 Cmd.ilocalsym = 0;
2228 Cmd.nlocalsym = 0;
2229 Cmd.iextdefsym = 0;
2230 Cmd.nextdefsym = 0;
2231 Cmd.iundefsym = 0;
2232 Cmd.nundefsym = 0;
2233 Cmd.tocoff = 0;
2234 Cmd.ntoc = 0;
2235 Cmd.modtaboff = 0;
2236 Cmd.nmodtab = 0;
2237 Cmd.extrefsymoff = 0;
2238 Cmd.nextrefsyms = 0;
2239 Cmd.indirectsymoff = 0;
2240 Cmd.nindirectsyms = 0;
2241 Cmd.extreloff = 0;
2242 Cmd.nextrel = 0;
2243 Cmd.locreloff = 0;
2244 Cmd.nlocrel = 0;
2245 return Cmd;
Rafael Espindola6e040c02013-04-26 20:07:33 +00002246}
2247
Charles Davis8bdfafd2013-09-01 04:28:48 +00002248MachO::linkedit_data_command
Kevin Enderby273ae012013-06-06 17:20:50 +00002249MachOObjectFile::getDataInCodeLoadCommand() const {
2250 if (DataInCodeLoadCmd)
Charles Davis8bdfafd2013-09-01 04:28:48 +00002251 return getStruct<MachO::linkedit_data_command>(this, DataInCodeLoadCmd);
Kevin Enderby273ae012013-06-06 17:20:50 +00002252
2253 // If there is no DataInCodeLoadCmd return a load command with zero'ed fields.
Charles Davis8bdfafd2013-09-01 04:28:48 +00002254 MachO::linkedit_data_command Cmd;
2255 Cmd.cmd = MachO::LC_DATA_IN_CODE;
2256 Cmd.cmdsize = sizeof(MachO::linkedit_data_command);
2257 Cmd.dataoff = 0;
2258 Cmd.datasize = 0;
Kevin Enderby273ae012013-06-06 17:20:50 +00002259 return Cmd;
2260}
2261
Kevin Enderby9a509442015-01-27 21:28:24 +00002262MachO::linkedit_data_command
2263MachOObjectFile::getLinkOptHintsLoadCommand() const {
2264 if (LinkOptHintsLoadCmd)
2265 return getStruct<MachO::linkedit_data_command>(this, LinkOptHintsLoadCmd);
2266
2267 // If there is no LinkOptHintsLoadCmd return a load command with zero'ed
2268 // fields.
2269 MachO::linkedit_data_command Cmd;
2270 Cmd.cmd = MachO::LC_LINKER_OPTIMIZATION_HINT;
2271 Cmd.cmdsize = sizeof(MachO::linkedit_data_command);
2272 Cmd.dataoff = 0;
2273 Cmd.datasize = 0;
2274 return Cmd;
2275}
2276
Nick Kledzikd04bc352014-08-30 00:20:14 +00002277ArrayRef<uint8_t> MachOObjectFile::getDyldInfoRebaseOpcodes() const {
2278 if (!DyldInfoLoadCmd)
2279 return ArrayRef<uint8_t>();
2280
2281 MachO::dyld_info_command DyldInfo
2282 = getStruct<MachO::dyld_info_command>(this, DyldInfoLoadCmd);
2283 const uint8_t *Ptr = reinterpret_cast<const uint8_t*>(
2284 getPtr(this, DyldInfo.rebase_off));
2285 return ArrayRef<uint8_t>(Ptr, DyldInfo.rebase_size);
2286}
2287
2288ArrayRef<uint8_t> MachOObjectFile::getDyldInfoBindOpcodes() const {
2289 if (!DyldInfoLoadCmd)
2290 return ArrayRef<uint8_t>();
2291
2292 MachO::dyld_info_command DyldInfo
2293 = getStruct<MachO::dyld_info_command>(this, DyldInfoLoadCmd);
2294 const uint8_t *Ptr = reinterpret_cast<const uint8_t*>(
2295 getPtr(this, DyldInfo.bind_off));
2296 return ArrayRef<uint8_t>(Ptr, DyldInfo.bind_size);
2297}
2298
2299ArrayRef<uint8_t> MachOObjectFile::getDyldInfoWeakBindOpcodes() const {
2300 if (!DyldInfoLoadCmd)
2301 return ArrayRef<uint8_t>();
2302
2303 MachO::dyld_info_command DyldInfo
2304 = getStruct<MachO::dyld_info_command>(this, DyldInfoLoadCmd);
2305 const uint8_t *Ptr = reinterpret_cast<const uint8_t*>(
2306 getPtr(this, DyldInfo.weak_bind_off));
2307 return ArrayRef<uint8_t>(Ptr, DyldInfo.weak_bind_size);
2308}
2309
2310ArrayRef<uint8_t> MachOObjectFile::getDyldInfoLazyBindOpcodes() const {
2311 if (!DyldInfoLoadCmd)
2312 return ArrayRef<uint8_t>();
2313
2314 MachO::dyld_info_command DyldInfo
2315 = getStruct<MachO::dyld_info_command>(this, DyldInfoLoadCmd);
2316 const uint8_t *Ptr = reinterpret_cast<const uint8_t*>(
2317 getPtr(this, DyldInfo.lazy_bind_off));
2318 return ArrayRef<uint8_t>(Ptr, DyldInfo.lazy_bind_size);
2319}
2320
2321ArrayRef<uint8_t> MachOObjectFile::getDyldInfoExportsTrie() const {
2322 if (!DyldInfoLoadCmd)
2323 return ArrayRef<uint8_t>();
2324
2325 MachO::dyld_info_command DyldInfo
2326 = getStruct<MachO::dyld_info_command>(this, DyldInfoLoadCmd);
2327 const uint8_t *Ptr = reinterpret_cast<const uint8_t*>(
2328 getPtr(this, DyldInfo.export_off));
2329 return ArrayRef<uint8_t>(Ptr, DyldInfo.export_size);
2330}
2331
Alexander Potapenko6909b5b2014-10-15 23:35:45 +00002332ArrayRef<uint8_t> MachOObjectFile::getUuid() const {
2333 if (!UuidLoadCmd)
2334 return ArrayRef<uint8_t>();
Benjamin Kramer014601d2014-10-24 15:52:05 +00002335 // Returning a pointer is fine as uuid doesn't need endian swapping.
2336 const char *Ptr = UuidLoadCmd + offsetof(MachO::uuid_command, uuid);
2337 return ArrayRef<uint8_t>(reinterpret_cast<const uint8_t *>(Ptr), 16);
Alexander Potapenko6909b5b2014-10-15 23:35:45 +00002338}
Nick Kledzikd04bc352014-08-30 00:20:14 +00002339
Rafael Espindola6e040c02013-04-26 20:07:33 +00002340StringRef MachOObjectFile::getStringTableData() const {
Charles Davis8bdfafd2013-09-01 04:28:48 +00002341 MachO::symtab_command S = getSymtabLoadCommand();
2342 return getData().substr(S.stroff, S.strsize);
Rafael Espindola6e040c02013-04-26 20:07:33 +00002343}
2344
Rafael Espindola56f976f2013-04-18 18:08:55 +00002345bool MachOObjectFile::is64Bit() const {
2346 return getType() == getMachOType(false, true) ||
Lang Hames84bc8182014-07-15 19:35:22 +00002347 getType() == getMachOType(true, true);
Rafael Espindola56f976f2013-04-18 18:08:55 +00002348}
2349
2350void MachOObjectFile::ReadULEB128s(uint64_t Index,
2351 SmallVectorImpl<uint64_t> &Out) const {
2352 DataExtractor extractor(ObjectFile::getData(), true, 0);
2353
2354 uint32_t offset = Index;
2355 uint64_t data = 0;
2356 while (uint64_t delta = extractor.getULEB128(&offset)) {
2357 data += delta;
2358 Out.push_back(data);
2359 }
2360}
2361
Rafael Espindolac66d7612014-08-17 19:09:37 +00002362bool MachOObjectFile::isRelocatableObject() const {
2363 return getHeader().filetype == MachO::MH_OBJECT;
2364}
2365
Rafael Espindola437b0d52014-07-31 03:12:45 +00002366ErrorOr<std::unique_ptr<MachOObjectFile>>
Rafael Espindola48af1c22014-08-19 18:44:46 +00002367ObjectFile::createMachOObjectFile(MemoryBufferRef Buffer) {
2368 StringRef Magic = Buffer.getBuffer().slice(0, 4);
Rafael Espindola3acea392014-06-12 21:46:39 +00002369 std::error_code EC;
Ahmed Charles56440fd2014-03-06 05:51:42 +00002370 std::unique_ptr<MachOObjectFile> Ret;
Rafael Espindola56f976f2013-04-18 18:08:55 +00002371 if (Magic == "\xFE\xED\xFA\xCE")
Rafael Espindola48af1c22014-08-19 18:44:46 +00002372 Ret.reset(new MachOObjectFile(Buffer, false, false, EC));
Rafael Espindola56f976f2013-04-18 18:08:55 +00002373 else if (Magic == "\xCE\xFA\xED\xFE")
Rafael Espindola48af1c22014-08-19 18:44:46 +00002374 Ret.reset(new MachOObjectFile(Buffer, true, false, EC));
Rafael Espindola56f976f2013-04-18 18:08:55 +00002375 else if (Magic == "\xFE\xED\xFA\xCF")
Rafael Espindola48af1c22014-08-19 18:44:46 +00002376 Ret.reset(new MachOObjectFile(Buffer, false, true, EC));
Rafael Espindola56f976f2013-04-18 18:08:55 +00002377 else if (Magic == "\xCF\xFA\xED\xFE")
Rafael Espindola48af1c22014-08-19 18:44:46 +00002378 Ret.reset(new MachOObjectFile(Buffer, true, true, EC));
Rafael Espindola6304e942014-06-23 22:00:37 +00002379 else
Rafael Espindola692410e2014-01-21 23:06:54 +00002380 return object_error::parse_failed;
Rafael Espindola56f976f2013-04-18 18:08:55 +00002381
Rafael Espindola692410e2014-01-21 23:06:54 +00002382 if (EC)
2383 return EC;
Rafael Espindola437b0d52014-07-31 03:12:45 +00002384 return std::move(Ret);
Rafael Espindola56f976f2013-04-18 18:08:55 +00002385}
2386