blob: ce4d1cf92e207ddd3b1a1ac430f1fef13ee13194 [file] [log] [blame]
Eugene Zelenko903f87e2017-04-21 22:03:05 +00001//===- MachOObjectFile.cpp - Mach-O object file binding -------------------===//
Eric Christopher6256b032011-04-22 03:19:48 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the MachOObjectFile class, which binds the MachOObject
11// class to the generic ObjectFile wrapper.
12//
13//===----------------------------------------------------------------------===//
14
Eugene Zelenko903f87e2017-04-21 22:03:05 +000015#include "llvm/ADT/ArrayRef.h"
16#include "llvm/ADT/None.h"
Tim Northover7b837d82014-03-29 10:18:08 +000017#include "llvm/ADT/STLExtras.h"
Chandler Carruthe3e43d92017-06-06 11:49:48 +000018#include "llvm/ADT/SmallVector.h"
Eugene Zelenko903f87e2017-04-21 22:03:05 +000019#include "llvm/ADT/StringRef.h"
Rafael Espindola015f5762014-08-08 16:30:17 +000020#include "llvm/ADT/StringSwitch.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000021#include "llvm/ADT/Triple.h"
Eugene Zelenko903f87e2017-04-21 22:03:05 +000022#include "llvm/ADT/Twine.h"
Zachary Turner19ca2b02017-06-07 03:48:56 +000023#include "llvm/BinaryFormat/MachO.h"
Eugene Zelenko903f87e2017-04-21 22:03:05 +000024#include "llvm/Object/Error.h"
25#include "llvm/Object/MachO.h"
26#include "llvm/Object/ObjectFile.h"
27#include "llvm/Object/SymbolicFile.h"
Rafael Espindola8764c892013-04-07 20:01:29 +000028#include "llvm/Support/DataExtractor.h"
Nick Kledzika240fc52014-09-12 21:34:15 +000029#include "llvm/Support/Debug.h"
Eugene Zelenko903f87e2017-04-21 22:03:05 +000030#include "llvm/Support/Error.h"
31#include "llvm/Support/ErrorHandling.h"
Owen Anderson1832f4d2011-10-26 20:42:54 +000032#include "llvm/Support/Format.h"
Rafael Espindolafd7aa382013-04-18 18:08:55 +000033#include "llvm/Support/Host.h"
Nick Kledzikaa4d2ac2014-08-30 00:20:14 +000034#include "llvm/Support/LEB128.h"
Eric Christopher6256b032011-04-22 03:19:48 +000035#include "llvm/Support/MemoryBuffer.h"
Eugene Zelenko903f87e2017-04-21 22:03:05 +000036#include "llvm/Support/SwapByteOrder.h"
Chandler Carruthe3e43d92017-06-06 11:49:48 +000037#include "llvm/Support/raw_ostream.h"
Eugene Zelenko903f87e2017-04-21 22:03:05 +000038#include <algorithm>
39#include <cassert>
40#include <cstddef>
41#include <cstdint>
Eric Christopher6256b032011-04-22 03:19:48 +000042#include <cstring>
43#include <limits>
Kevin Enderbye9885e02016-10-31 20:29:48 +000044#include <list>
Eugene Zelenko903f87e2017-04-21 22:03:05 +000045#include <memory>
46#include <string>
47#include <system_error>
Eric Christopher6256b032011-04-22 03:19:48 +000048
49using namespace llvm;
50using namespace object;
51
Artyom Skrobovc543b262014-07-20 12:08:28 +000052namespace {
Eugene Zelenko903f87e2017-04-21 22:03:05 +000053
Artyom Skrobovc543b262014-07-20 12:08:28 +000054 struct section_base {
55 char sectname[16];
56 char segname[16];
57 };
Eugene Zelenko903f87e2017-04-21 22:03:05 +000058
59} // end anonymous namespace
Rafael Espindolafd7aa382013-04-18 18:08:55 +000060
Benjamin Kramerefa50a22017-08-20 15:13:39 +000061static Error malformedError(const Twine &Msg) {
62 return make_error<GenericBinaryError>("truncated or malformed object (" +
63 Msg + ")",
Kevin Enderbyba3a53c2016-05-05 23:41:05 +000064 object_error::parse_failed);
Lang Hames3e222972016-03-25 17:25:34 +000065}
66
Alexey Samsonov1d4ec712015-06-04 19:45:22 +000067// FIXME: Replace all uses of this function with getStructOrErr.
Filipe Cabecinhas01834772015-01-15 22:52:38 +000068template <typename T>
Lang Hames85334ad2016-12-04 01:56:10 +000069static T getStruct(const MachOObjectFile &O, const char *P) {
Filipe Cabecinhas01834772015-01-15 22:52:38 +000070 // Don't read before the beginning or past the end of the file
Lang Hames85334ad2016-12-04 01:56:10 +000071 if (P < O.getData().begin() || P + sizeof(T) > O.getData().end())
Filipe Cabecinhas01834772015-01-15 22:52:38 +000072 report_fatal_error("Malformed MachO file.");
73
Rafael Espindola143d2232013-04-19 13:45:05 +000074 T Cmd;
75 memcpy(&Cmd, P, sizeof(T));
Lang Hames85334ad2016-12-04 01:56:10 +000076 if (O.isLittleEndian() != sys::IsLittleEndianHost)
Artyom Skrobov11c20582014-07-18 09:26:16 +000077 MachO::swapStruct(Cmd);
Rafael Espindola143d2232013-04-19 13:45:05 +000078 return Cmd;
Rafael Espindolafd7aa382013-04-18 18:08:55 +000079}
80
Alexey Samsonov1d4ec712015-06-04 19:45:22 +000081template <typename T>
Lang Hames85334ad2016-12-04 01:56:10 +000082static Expected<T> getStructOrErr(const MachOObjectFile &O, const char *P) {
Alexey Samsonov1d4ec712015-06-04 19:45:22 +000083 // Don't read before the beginning or past the end of the file
Lang Hames85334ad2016-12-04 01:56:10 +000084 if (P < O.getData().begin() || P + sizeof(T) > O.getData().end())
Kevin Enderbyeaa1f082016-05-06 20:16:28 +000085 return malformedError("Structure read out-of-range");
Alexey Samsonov1d4ec712015-06-04 19:45:22 +000086
87 T Cmd;
88 memcpy(&Cmd, P, sizeof(T));
Lang Hames85334ad2016-12-04 01:56:10 +000089 if (O.isLittleEndian() != sys::IsLittleEndianHost)
Alexey Samsonov1d4ec712015-06-04 19:45:22 +000090 MachO::swapStruct(Cmd);
91 return Cmd;
92}
93
Rafael Espindola2173e182013-04-26 20:07:33 +000094static const char *
Lang Hames85334ad2016-12-04 01:56:10 +000095getSectionPtr(const MachOObjectFile &O, MachOObjectFile::LoadCommandInfo L,
Rafael Espindola2173e182013-04-26 20:07:33 +000096 unsigned Sec) {
Rafael Espindolafd7aa382013-04-18 18:08:55 +000097 uintptr_t CommandAddr = reinterpret_cast<uintptr_t>(L.Ptr);
98
Lang Hames85334ad2016-12-04 01:56:10 +000099 bool Is64 = O.is64Bit();
Charles Davis55107282013-09-01 04:28:48 +0000100 unsigned SegmentLoadSize = Is64 ? sizeof(MachO::segment_command_64) :
101 sizeof(MachO::segment_command);
102 unsigned SectionSize = Is64 ? sizeof(MachO::section_64) :
103 sizeof(MachO::section);
Rafael Espindolafd7aa382013-04-18 18:08:55 +0000104
105 uintptr_t SectionAddr = CommandAddr + SegmentLoadSize + Sec * SectionSize;
Charles Davisf69a29b2013-08-27 05:38:30 +0000106 return reinterpret_cast<const char*>(SectionAddr);
Rafael Espindola0f08eb12013-04-07 19:05:30 +0000107}
108
Lang Hames85334ad2016-12-04 01:56:10 +0000109static const char *getPtr(const MachOObjectFile &O, size_t Offset) {
Sam Clegg8844a172018-06-04 17:01:20 +0000110 assert(Offset <= O.getData().size());
Sam Clegg45484532018-05-30 03:37:26 +0000111 return O.getData().data() + Offset;
Rafael Espindola0f08eb12013-04-07 19:05:30 +0000112}
113
Artyom Skrobov11c20582014-07-18 09:26:16 +0000114static MachO::nlist_base
Lang Hames85334ad2016-12-04 01:56:10 +0000115getSymbolTableEntryBase(const MachOObjectFile &O, DataRefImpl DRI) {
Rafael Espindola802fe932013-04-24 19:47:55 +0000116 const char *P = reinterpret_cast<const char *>(DRI.p);
Artyom Skrobov11c20582014-07-18 09:26:16 +0000117 return getStruct<MachO::nlist_base>(O, P);
Eric Christopher6256b032011-04-22 03:19:48 +0000118}
119
Rafael Espindolafd7aa382013-04-18 18:08:55 +0000120static StringRef parseSegmentOrSectionName(const char *P) {
Rafael Espindolacef81b32012-12-21 03:47:03 +0000121 if (P[15] == 0)
122 // Null terminated.
123 return P;
124 // Not null terminated, so this is a 16 char string.
125 return StringRef(P, 16);
126}
127
Lang Hames85334ad2016-12-04 01:56:10 +0000128static unsigned getCPUType(const MachOObjectFile &O) {
129 return O.getHeader().cputype;
Rafael Espindolafd7aa382013-04-18 18:08:55 +0000130}
131
Charles Davis55107282013-09-01 04:28:48 +0000132static uint32_t
133getPlainRelocationAddress(const MachO::any_relocation_info &RE) {
134 return RE.r_word0;
Rafael Espindolafd7aa382013-04-18 18:08:55 +0000135}
136
137static unsigned
Charles Davis55107282013-09-01 04:28:48 +0000138getScatteredRelocationAddress(const MachO::any_relocation_info &RE) {
139 return RE.r_word0 & 0xffffff;
Rafael Espindolafd7aa382013-04-18 18:08:55 +0000140}
141
Lang Hames85334ad2016-12-04 01:56:10 +0000142static bool getPlainRelocationPCRel(const MachOObjectFile &O,
Charles Davis55107282013-09-01 04:28:48 +0000143 const MachO::any_relocation_info &RE) {
Lang Hames85334ad2016-12-04 01:56:10 +0000144 if (O.isLittleEndian())
Charles Davis55107282013-09-01 04:28:48 +0000145 return (RE.r_word1 >> 24) & 1;
146 return (RE.r_word1 >> 7) & 1;
Rafael Espindolafd7aa382013-04-18 18:08:55 +0000147}
148
149static bool
Lang Hames85334ad2016-12-04 01:56:10 +0000150getScatteredRelocationPCRel(const MachO::any_relocation_info &RE) {
Charles Davis55107282013-09-01 04:28:48 +0000151 return (RE.r_word0 >> 30) & 1;
Rafael Espindolafd7aa382013-04-18 18:08:55 +0000152}
153
Lang Hames85334ad2016-12-04 01:56:10 +0000154static unsigned getPlainRelocationLength(const MachOObjectFile &O,
Charles Davis55107282013-09-01 04:28:48 +0000155 const MachO::any_relocation_info &RE) {
Lang Hames85334ad2016-12-04 01:56:10 +0000156 if (O.isLittleEndian())
Charles Davis55107282013-09-01 04:28:48 +0000157 return (RE.r_word1 >> 25) & 3;
158 return (RE.r_word1 >> 5) & 3;
Rafael Espindolafd7aa382013-04-18 18:08:55 +0000159}
160
161static unsigned
Charles Davis55107282013-09-01 04:28:48 +0000162getScatteredRelocationLength(const MachO::any_relocation_info &RE) {
163 return (RE.r_word0 >> 28) & 3;
Rafael Espindolafd7aa382013-04-18 18:08:55 +0000164}
165
Lang Hames85334ad2016-12-04 01:56:10 +0000166static unsigned getPlainRelocationType(const MachOObjectFile &O,
Charles Davis55107282013-09-01 04:28:48 +0000167 const MachO::any_relocation_info &RE) {
Lang Hames85334ad2016-12-04 01:56:10 +0000168 if (O.isLittleEndian())
Charles Davis55107282013-09-01 04:28:48 +0000169 return RE.r_word1 >> 28;
170 return RE.r_word1 & 0xf;
Rafael Espindolafd7aa382013-04-18 18:08:55 +0000171}
172
Lang Hames85334ad2016-12-04 01:56:10 +0000173static uint32_t getSectionFlags(const MachOObjectFile &O,
Rafael Espindolafd7aa382013-04-18 18:08:55 +0000174 DataRefImpl Sec) {
Lang Hames85334ad2016-12-04 01:56:10 +0000175 if (O.is64Bit()) {
176 MachO::section_64 Sect = O.getSection64(Sec);
Charles Davis55107282013-09-01 04:28:48 +0000177 return Sect.flags;
Rafael Espindolafd7aa382013-04-18 18:08:55 +0000178 }
Lang Hames85334ad2016-12-04 01:56:10 +0000179 MachO::section Sect = O.getSection(Sec);
Charles Davis55107282013-09-01 04:28:48 +0000180 return Sect.flags;
Rafael Espindolafd7aa382013-04-18 18:08:55 +0000181}
182
Lang Hames3e222972016-03-25 17:25:34 +0000183static Expected<MachOObjectFile::LoadCommandInfo>
Lang Hames85334ad2016-12-04 01:56:10 +0000184getLoadCommandInfo(const MachOObjectFile &Obj, const char *Ptr,
Kevin Enderby1820caa2016-05-03 23:13:50 +0000185 uint32_t LoadCommandIndex) {
Lang Hames3e222972016-03-25 17:25:34 +0000186 if (auto CmdOrErr = getStructOrErr<MachO::load_command>(Obj, Ptr)) {
Jonas Devlieghere143e1f12017-09-13 13:43:01 +0000187 if (CmdOrErr->cmdsize + Ptr > Obj.getData().end())
188 return malformedError("load command " + Twine(LoadCommandIndex) +
189 " extends past end of file");
Lang Hames3e222972016-03-25 17:25:34 +0000190 if (CmdOrErr->cmdsize < 8)
Kevin Enderbyeaa1f082016-05-06 20:16:28 +0000191 return malformedError("load command " + Twine(LoadCommandIndex) +
Kevin Enderbyba3a53c2016-05-05 23:41:05 +0000192 " with size less than 8 bytes");
Lang Hames3e222972016-03-25 17:25:34 +0000193 return MachOObjectFile::LoadCommandInfo({Ptr, *CmdOrErr});
194 } else
195 return CmdOrErr.takeError();
Alexey Samsonov00faba72015-06-04 19:34:14 +0000196}
197
Lang Hames3e222972016-03-25 17:25:34 +0000198static Expected<MachOObjectFile::LoadCommandInfo>
Lang Hames85334ad2016-12-04 01:56:10 +0000199getFirstLoadCommandInfo(const MachOObjectFile &Obj) {
200 unsigned HeaderSize = Obj.is64Bit() ? sizeof(MachO::mach_header_64)
201 : sizeof(MachO::mach_header);
202 if (sizeof(MachO::load_command) > Obj.getHeader().sizeofcmds)
Kevin Enderbyeaa1f082016-05-06 20:16:28 +0000203 return malformedError("load command 0 extends past the end all load "
Kevin Enderbyba3a53c2016-05-05 23:41:05 +0000204 "commands in the file");
Kevin Enderby1820caa2016-05-03 23:13:50 +0000205 return getLoadCommandInfo(Obj, getPtr(Obj, HeaderSize), 0);
Alexey Samsonov00faba72015-06-04 19:34:14 +0000206}
207
Lang Hames3e222972016-03-25 17:25:34 +0000208static Expected<MachOObjectFile::LoadCommandInfo>
Lang Hames85334ad2016-12-04 01:56:10 +0000209getNextLoadCommandInfo(const MachOObjectFile &Obj, uint32_t LoadCommandIndex,
Alexey Samsonov00faba72015-06-04 19:34:14 +0000210 const MachOObjectFile::LoadCommandInfo &L) {
Lang Hames85334ad2016-12-04 01:56:10 +0000211 unsigned HeaderSize = Obj.is64Bit() ? sizeof(MachO::mach_header_64)
212 : sizeof(MachO::mach_header);
Kevin Enderbyf2e03382016-08-31 17:57:46 +0000213 if (L.Ptr + L.C.cmdsize + sizeof(MachO::load_command) >
Lang Hames85334ad2016-12-04 01:56:10 +0000214 Obj.getData().data() + HeaderSize + Obj.getHeader().sizeofcmds)
Kevin Enderbyeaa1f082016-05-06 20:16:28 +0000215 return malformedError("load command " + Twine(LoadCommandIndex + 1) +
Kevin Enderbyba3a53c2016-05-05 23:41:05 +0000216 " extends past the end all load commands in the file");
Kevin Enderby1820caa2016-05-03 23:13:50 +0000217 return getLoadCommandInfo(Obj, L.Ptr + L.C.cmdsize, LoadCommandIndex + 1);
Alexey Samsonov00faba72015-06-04 19:34:14 +0000218}
219
Alexey Samsonov1d4ec712015-06-04 19:45:22 +0000220template <typename T>
Lang Hames85334ad2016-12-04 01:56:10 +0000221static void parseHeader(const MachOObjectFile &Obj, T &Header,
Lang Hames3e222972016-03-25 17:25:34 +0000222 Error &Err) {
Lang Hames85334ad2016-12-04 01:56:10 +0000223 if (sizeof(T) > Obj.getData().size()) {
Kevin Enderbyeaa1f082016-05-06 20:16:28 +0000224 Err = malformedError("the mach header extends past the end of the "
Kevin Enderbyba3a53c2016-05-05 23:41:05 +0000225 "file");
Kevin Enderby63247512016-04-13 21:17:58 +0000226 return;
227 }
Lang Hames3e222972016-03-25 17:25:34 +0000228 if (auto HeaderOrErr = getStructOrErr<T>(Obj, getPtr(Obj, 0)))
229 Header = *HeaderOrErr;
Alexey Samsonov1d4ec712015-06-04 19:45:22 +0000230 else
Lang Hames3e222972016-03-25 17:25:34 +0000231 Err = HeaderOrErr.takeError();
Alexey Samsonov1d4ec712015-06-04 19:45:22 +0000232}
233
Kevin Enderbye9885e02016-10-31 20:29:48 +0000234// This is used to check for overlapping of Mach-O elements.
235struct MachOElement {
236 uint64_t Offset;
237 uint64_t Size;
238 const char *Name;
239};
240
241static Error checkOverlappingElement(std::list<MachOElement> &Elements,
242 uint64_t Offset, uint64_t Size,
243 const char *Name) {
244 if (Size == 0)
245 return Error::success();
246
247 for (auto it=Elements.begin() ; it != Elements.end(); ++it) {
248 auto E = *it;
249 if ((Offset >= E.Offset && Offset < E.Offset + E.Size) ||
250 (Offset + Size > E.Offset && Offset + Size < E.Offset + E.Size) ||
251 (Offset <= E.Offset && Offset + Size >= E.Offset + E.Size))
252 return malformedError(Twine(Name) + " at offset " + Twine(Offset) +
253 " with a size of " + Twine(Size) + ", overlaps " +
254 E.Name + " at offset " + Twine(E.Offset) + " with "
255 "a size of " + Twine(E.Size));
256 auto nt = it;
257 nt++;
258 if (nt != Elements.end()) {
259 auto N = *nt;
260 if (Offset + Size <= N.Offset) {
261 Elements.insert(nt, {Offset, Size, Name});
262 return Error::success();
263 }
264 }
265 }
266 Elements.push_back({Offset, Size, Name});
267 return Error::success();
268}
269
Alexey Samsonov468b9042015-06-04 22:08:37 +0000270// Parses LC_SEGMENT or LC_SEGMENT_64 load command, adds addresses of all
271// sections to \param Sections, and optionally sets
272// \param IsPageZeroSegment to true.
Kevin Enderby296471b2016-08-12 20:10:25 +0000273template <typename Segment, typename Section>
Lang Hames3e222972016-03-25 17:25:34 +0000274static Error parseSegmentLoadCommand(
Lang Hames85334ad2016-12-04 01:56:10 +0000275 const MachOObjectFile &Obj, const MachOObjectFile::LoadCommandInfo &Load,
Kevin Enderby00e8fc52016-05-05 17:43:35 +0000276 SmallVectorImpl<const char *> &Sections, bool &IsPageZeroSegment,
Kevin Enderby4b3270e2016-11-02 21:08:39 +0000277 uint32_t LoadCommandIndex, const char *CmdName, uint64_t SizeOfHeaders,
278 std::list<MachOElement> &Elements) {
Kevin Enderby296471b2016-08-12 20:10:25 +0000279 const unsigned SegmentLoadSize = sizeof(Segment);
Alexey Samsonov468b9042015-06-04 22:08:37 +0000280 if (Load.C.cmdsize < SegmentLoadSize)
Kevin Enderbyeaa1f082016-05-06 20:16:28 +0000281 return malformedError("load command " + Twine(LoadCommandIndex) +
Kevin Enderbyba3a53c2016-05-05 23:41:05 +0000282 " " + CmdName + " cmdsize too small");
Kevin Enderby296471b2016-08-12 20:10:25 +0000283 if (auto SegOrErr = getStructOrErr<Segment>(Obj, Load.Ptr)) {
284 Segment S = SegOrErr.get();
285 const unsigned SectionSize = sizeof(Section);
Lang Hames85334ad2016-12-04 01:56:10 +0000286 uint64_t FileSize = Obj.getData().size();
Lang Hames3e222972016-03-25 17:25:34 +0000287 if (S.nsects > std::numeric_limits<uint32_t>::max() / SectionSize ||
288 S.nsects * SectionSize > Load.C.cmdsize - SegmentLoadSize)
Kevin Enderbyeaa1f082016-05-06 20:16:28 +0000289 return malformedError("load command " + Twine(LoadCommandIndex) +
NAKAMURA Takumifb2d85d2016-08-22 00:58:47 +0000290 " inconsistent cmdsize in " + CmdName +
Kevin Enderbyba3a53c2016-05-05 23:41:05 +0000291 " for the number of sections");
Lang Hames3e222972016-03-25 17:25:34 +0000292 for (unsigned J = 0; J < S.nsects; ++J) {
293 const char *Sec = getSectionPtr(Obj, Load, J);
294 Sections.push_back(Sec);
Kevin Enderby296471b2016-08-12 20:10:25 +0000295 Section s = getStruct<Section>(Obj, Sec);
Lang Hames85334ad2016-12-04 01:56:10 +0000296 if (Obj.getHeader().filetype != MachO::MH_DYLIB_STUB &&
297 Obj.getHeader().filetype != MachO::MH_DSYM &&
Kevin Enderby296471b2016-08-12 20:10:25 +0000298 s.flags != MachO::S_ZEROFILL &&
299 s.flags != MachO::S_THREAD_LOCAL_ZEROFILL &&
300 s.offset > FileSize)
301 return malformedError("offset field of section " + Twine(J) + " in " +
302 CmdName + " command " + Twine(LoadCommandIndex) +
303 " extends past the end of the file");
Lang Hames85334ad2016-12-04 01:56:10 +0000304 if (Obj.getHeader().filetype != MachO::MH_DYLIB_STUB &&
305 Obj.getHeader().filetype != MachO::MH_DSYM &&
Kevin Enderby296471b2016-08-12 20:10:25 +0000306 s.flags != MachO::S_ZEROFILL &&
NAKAMURA Takumi805f0aa2016-08-22 00:58:04 +0000307 s.flags != MachO::S_THREAD_LOCAL_ZEROFILL && S.fileoff == 0 &&
308 s.offset < SizeOfHeaders && s.size != 0)
Kevin Enderby296471b2016-08-12 20:10:25 +0000309 return malformedError("offset field of section " + Twine(J) + " in " +
310 CmdName + " command " + Twine(LoadCommandIndex) +
311 " not past the headers of the file");
312 uint64_t BigSize = s.offset;
313 BigSize += s.size;
Lang Hames85334ad2016-12-04 01:56:10 +0000314 if (Obj.getHeader().filetype != MachO::MH_DYLIB_STUB &&
315 Obj.getHeader().filetype != MachO::MH_DSYM &&
Kevin Enderby296471b2016-08-12 20:10:25 +0000316 s.flags != MachO::S_ZEROFILL &&
317 s.flags != MachO::S_THREAD_LOCAL_ZEROFILL &&
318 BigSize > FileSize)
319 return malformedError("offset field plus size field of section " +
320 Twine(J) + " in " + CmdName + " command " +
321 Twine(LoadCommandIndex) +
322 " extends past the end of the file");
Lang Hames85334ad2016-12-04 01:56:10 +0000323 if (Obj.getHeader().filetype != MachO::MH_DYLIB_STUB &&
324 Obj.getHeader().filetype != MachO::MH_DSYM &&
Kevin Enderby296471b2016-08-12 20:10:25 +0000325 s.flags != MachO::S_ZEROFILL &&
326 s.flags != MachO::S_THREAD_LOCAL_ZEROFILL &&
327 s.size > S.filesize)
328 return malformedError("size field of section " +
329 Twine(J) + " in " + CmdName + " command " +
330 Twine(LoadCommandIndex) +
331 " greater than the segment");
Lang Hames85334ad2016-12-04 01:56:10 +0000332 if (Obj.getHeader().filetype != MachO::MH_DYLIB_STUB &&
333 Obj.getHeader().filetype != MachO::MH_DSYM && s.size != 0 &&
NAKAMURA Takumi805f0aa2016-08-22 00:58:04 +0000334 s.addr < S.vmaddr)
335 return malformedError("addr field of section " + Twine(J) + " in " +
336 CmdName + " command " + Twine(LoadCommandIndex) +
337 " less than the segment's vmaddr");
Kevin Enderby296471b2016-08-12 20:10:25 +0000338 BigSize = s.addr;
339 BigSize += s.size;
340 uint64_t BigEnd = S.vmaddr;
341 BigEnd += S.vmsize;
342 if (S.vmsize != 0 && s.size != 0 && BigSize > BigEnd)
NAKAMURA Takumi805f0aa2016-08-22 00:58:04 +0000343 return malformedError("addr field plus size of section " + Twine(J) +
344 " in " + CmdName + " command " +
345 Twine(LoadCommandIndex) +
346 " greater than than "
Kevin Enderby296471b2016-08-12 20:10:25 +0000347 "the segment's vmaddr plus vmsize");
Lang Hames85334ad2016-12-04 01:56:10 +0000348 if (Obj.getHeader().filetype != MachO::MH_DYLIB_STUB &&
349 Obj.getHeader().filetype != MachO::MH_DSYM &&
Kevin Enderby4b3270e2016-11-02 21:08:39 +0000350 s.flags != MachO::S_ZEROFILL &&
351 s.flags != MachO::S_THREAD_LOCAL_ZEROFILL)
352 if (Error Err = checkOverlappingElement(Elements, s.offset, s.size,
353 "section contents"))
354 return Err;
Kevin Enderby296471b2016-08-12 20:10:25 +0000355 if (s.reloff > FileSize)
NAKAMURA Takumi805f0aa2016-08-22 00:58:04 +0000356 return malformedError("reloff field of section " + Twine(J) + " in " +
357 CmdName + " command " + Twine(LoadCommandIndex) +
Kevin Enderby296471b2016-08-12 20:10:25 +0000358 " extends past the end of the file");
359 BigSize = s.nreloc;
360 BigSize *= sizeof(struct MachO::relocation_info);
361 BigSize += s.reloff;
362 if (BigSize > FileSize)
363 return malformedError("reloff field plus nreloc field times sizeof("
364 "struct relocation_info) of section " +
365 Twine(J) + " in " + CmdName + " command " +
NAKAMURA Takumi805f0aa2016-08-22 00:58:04 +0000366 Twine(LoadCommandIndex) +
Kevin Enderby296471b2016-08-12 20:10:25 +0000367 " extends past the end of the file");
Kevin Enderby4b3270e2016-11-02 21:08:39 +0000368 if (Error Err = checkOverlappingElement(Elements, s.reloff, s.nreloc *
369 sizeof(struct
370 MachO::relocation_info),
371 "section relocation entries"))
372 return Err;
Lang Hames3e222972016-03-25 17:25:34 +0000373 }
Kevin Enderbycedb0b62016-08-05 18:19:40 +0000374 if (S.fileoff > FileSize)
375 return malformedError("load command " + Twine(LoadCommandIndex) +
NAKAMURA Takumifb2d85d2016-08-22 00:58:47 +0000376 " fileoff field in " + CmdName +
Kevin Enderbycedb0b62016-08-05 18:19:40 +0000377 " extends past the end of the file");
Kevin Enderby296471b2016-08-12 20:10:25 +0000378 uint64_t BigSize = S.fileoff;
379 BigSize += S.filesize;
380 if (BigSize > FileSize)
381 return malformedError("load command " + Twine(LoadCommandIndex) +
382 " fileoff field plus filesize field in " +
383 CmdName + " extends past the end of the file");
384 if (S.vmsize != 0 && S.filesize > S.vmsize)
385 return malformedError("load command " + Twine(LoadCommandIndex) +
Kevin Enderbyb1b66d42017-02-07 21:20:44 +0000386 " filesize field in " + CmdName +
Kevin Enderby296471b2016-08-12 20:10:25 +0000387 " greater than vmsize field");
Lang Hames3e222972016-03-25 17:25:34 +0000388 IsPageZeroSegment |= StringRef("__PAGEZERO").equals(S.segname);
389 } else
390 return SegOrErr.takeError();
391
392 return Error::success();
Alexey Samsonov468b9042015-06-04 22:08:37 +0000393}
394
Lang Hames85334ad2016-12-04 01:56:10 +0000395static Error checkSymtabCommand(const MachOObjectFile &Obj,
Kevin Enderbyff19e2b2016-08-26 19:34:07 +0000396 const MachOObjectFile::LoadCommandInfo &Load,
397 uint32_t LoadCommandIndex,
Kevin Enderbye9885e02016-10-31 20:29:48 +0000398 const char **SymtabLoadCmd,
399 std::list<MachOElement> &Elements) {
Kevin Enderbyff19e2b2016-08-26 19:34:07 +0000400 if (Load.C.cmdsize < sizeof(MachO::symtab_command))
401 return malformedError("load command " + Twine(LoadCommandIndex) +
402 " LC_SYMTAB cmdsize too small");
403 if (*SymtabLoadCmd != nullptr)
404 return malformedError("more than one LC_SYMTAB command");
405 MachO::symtab_command Symtab =
406 getStruct<MachO::symtab_command>(Obj, Load.Ptr);
407 if (Symtab.cmdsize != sizeof(MachO::symtab_command))
408 return malformedError("LC_SYMTAB command " + Twine(LoadCommandIndex) +
409 " has incorrect cmdsize");
Lang Hames85334ad2016-12-04 01:56:10 +0000410 uint64_t FileSize = Obj.getData().size();
Kevin Enderbyff19e2b2016-08-26 19:34:07 +0000411 if (Symtab.symoff > FileSize)
412 return malformedError("symoff field of LC_SYMTAB command " +
413 Twine(LoadCommandIndex) + " extends past the end "
414 "of the file");
Kevin Enderbye9885e02016-10-31 20:29:48 +0000415 uint64_t SymtabSize = Symtab.nsyms;
Kevin Enderbyff19e2b2016-08-26 19:34:07 +0000416 const char *struct_nlist_name;
Lang Hames85334ad2016-12-04 01:56:10 +0000417 if (Obj.is64Bit()) {
Kevin Enderbye9885e02016-10-31 20:29:48 +0000418 SymtabSize *= sizeof(MachO::nlist_64);
Kevin Enderbyff19e2b2016-08-26 19:34:07 +0000419 struct_nlist_name = "struct nlist_64";
420 } else {
Kevin Enderbye9885e02016-10-31 20:29:48 +0000421 SymtabSize *= sizeof(MachO::nlist);
Kevin Enderbyff19e2b2016-08-26 19:34:07 +0000422 struct_nlist_name = "struct nlist";
423 }
Kevin Enderbye9885e02016-10-31 20:29:48 +0000424 uint64_t BigSize = SymtabSize;
Kevin Enderbyff19e2b2016-08-26 19:34:07 +0000425 BigSize += Symtab.symoff;
426 if (BigSize > FileSize)
427 return malformedError("symoff field plus nsyms field times sizeof(" +
428 Twine(struct_nlist_name) + ") of LC_SYMTAB command " +
429 Twine(LoadCommandIndex) + " extends past the end "
430 "of the file");
Kevin Enderbye9885e02016-10-31 20:29:48 +0000431 if (Error Err = checkOverlappingElement(Elements, Symtab.symoff, SymtabSize,
432 "symbol table"))
433 return Err;
Kevin Enderbyff19e2b2016-08-26 19:34:07 +0000434 if (Symtab.stroff > FileSize)
435 return malformedError("stroff field of LC_SYMTAB command " +
436 Twine(LoadCommandIndex) + " extends past the end "
437 "of the file");
438 BigSize = Symtab.stroff;
439 BigSize += Symtab.strsize;
440 if (BigSize > FileSize)
441 return malformedError("stroff field plus strsize field of LC_SYMTAB "
442 "command " + Twine(LoadCommandIndex) + " extends "
443 "past the end of the file");
Kevin Enderbye9885e02016-10-31 20:29:48 +0000444 if (Error Err = checkOverlappingElement(Elements, Symtab.stroff,
445 Symtab.strsize, "string table"))
446 return Err;
Kevin Enderbyff19e2b2016-08-26 19:34:07 +0000447 *SymtabLoadCmd = Load.Ptr;
448 return Error::success();
449}
450
Lang Hames85334ad2016-12-04 01:56:10 +0000451static Error checkDysymtabCommand(const MachOObjectFile &Obj,
452 const MachOObjectFile::LoadCommandInfo &Load,
453 uint32_t LoadCommandIndex,
454 const char **DysymtabLoadCmd,
455 std::list<MachOElement> &Elements) {
Kevin Enderbyb8c2c1d2016-08-30 21:28:30 +0000456 if (Load.C.cmdsize < sizeof(MachO::dysymtab_command))
457 return malformedError("load command " + Twine(LoadCommandIndex) +
458 " LC_DYSYMTAB cmdsize too small");
459 if (*DysymtabLoadCmd != nullptr)
460 return malformedError("more than one LC_DYSYMTAB command");
461 MachO::dysymtab_command Dysymtab =
462 getStruct<MachO::dysymtab_command>(Obj, Load.Ptr);
463 if (Dysymtab.cmdsize != sizeof(MachO::dysymtab_command))
464 return malformedError("LC_DYSYMTAB command " + Twine(LoadCommandIndex) +
465 " has incorrect cmdsize");
Lang Hames85334ad2016-12-04 01:56:10 +0000466 uint64_t FileSize = Obj.getData().size();
Kevin Enderbyb8c2c1d2016-08-30 21:28:30 +0000467 if (Dysymtab.tocoff > FileSize)
468 return malformedError("tocoff field of LC_DYSYMTAB command " +
469 Twine(LoadCommandIndex) + " extends past the end of "
470 "the file");
471 uint64_t BigSize = Dysymtab.ntoc;
472 BigSize *= sizeof(MachO::dylib_table_of_contents);
473 BigSize += Dysymtab.tocoff;
474 if (BigSize > FileSize)
475 return malformedError("tocoff field plus ntoc field times sizeof(struct "
476 "dylib_table_of_contents) of LC_DYSYMTAB command " +
477 Twine(LoadCommandIndex) + " extends past the end of "
478 "the file");
Kevin Enderby4b3270e2016-11-02 21:08:39 +0000479 if (Error Err = checkOverlappingElement(Elements, Dysymtab.tocoff,
480 Dysymtab.ntoc * sizeof(struct
NAKAMURA Takumid8ff2f42017-10-18 13:31:28 +0000481 MachO::dylib_table_of_contents),
482 "table of contents"))
Kevin Enderby4b3270e2016-11-02 21:08:39 +0000483 return Err;
Kevin Enderbyb8c2c1d2016-08-30 21:28:30 +0000484 if (Dysymtab.modtaboff > FileSize)
485 return malformedError("modtaboff field of LC_DYSYMTAB command " +
486 Twine(LoadCommandIndex) + " extends past the end of "
487 "the file");
488 BigSize = Dysymtab.nmodtab;
489 const char *struct_dylib_module_name;
Kevin Enderby4b3270e2016-11-02 21:08:39 +0000490 uint64_t sizeof_modtab;
Lang Hames85334ad2016-12-04 01:56:10 +0000491 if (Obj.is64Bit()) {
Kevin Enderby4b3270e2016-11-02 21:08:39 +0000492 sizeof_modtab = sizeof(MachO::dylib_module_64);
Kevin Enderbyb8c2c1d2016-08-30 21:28:30 +0000493 struct_dylib_module_name = "struct dylib_module_64";
494 } else {
Kevin Enderby4b3270e2016-11-02 21:08:39 +0000495 sizeof_modtab = sizeof(MachO::dylib_module);
Kevin Enderbyb8c2c1d2016-08-30 21:28:30 +0000496 struct_dylib_module_name = "struct dylib_module";
497 }
Kevin Enderby4b3270e2016-11-02 21:08:39 +0000498 BigSize *= sizeof_modtab;
Kevin Enderbyb8c2c1d2016-08-30 21:28:30 +0000499 BigSize += Dysymtab.modtaboff;
500 if (BigSize > FileSize)
501 return malformedError("modtaboff field plus nmodtab field times sizeof(" +
502 Twine(struct_dylib_module_name) + ") of LC_DYSYMTAB "
503 "command " + Twine(LoadCommandIndex) + " extends "
504 "past the end of the file");
Kevin Enderby4b3270e2016-11-02 21:08:39 +0000505 if (Error Err = checkOverlappingElement(Elements, Dysymtab.modtaboff,
506 Dysymtab.nmodtab * sizeof_modtab,
NAKAMURA Takumief15f2c2017-08-28 06:47:47 +0000507 "module table"))
Kevin Enderby4b3270e2016-11-02 21:08:39 +0000508 return Err;
Kevin Enderbyb8c2c1d2016-08-30 21:28:30 +0000509 if (Dysymtab.extrefsymoff > FileSize)
510 return malformedError("extrefsymoff field of LC_DYSYMTAB command " +
511 Twine(LoadCommandIndex) + " extends past the end of "
512 "the file");
513 BigSize = Dysymtab.nextrefsyms;
514 BigSize *= sizeof(MachO::dylib_reference);
515 BigSize += Dysymtab.extrefsymoff;
516 if (BigSize > FileSize)
517 return malformedError("extrefsymoff field plus nextrefsyms field times "
518 "sizeof(struct dylib_reference) of LC_DYSYMTAB "
519 "command " + Twine(LoadCommandIndex) + " extends "
520 "past the end of the file");
Kevin Enderby4b3270e2016-11-02 21:08:39 +0000521 if (Error Err = checkOverlappingElement(Elements, Dysymtab.extrefsymoff,
522 Dysymtab.nextrefsyms *
NAKAMURA Takumief15f2c2017-08-28 06:47:47 +0000523 sizeof(MachO::dylib_reference),
524 "reference table"))
Kevin Enderby4b3270e2016-11-02 21:08:39 +0000525 return Err;
Kevin Enderbyb8c2c1d2016-08-30 21:28:30 +0000526 if (Dysymtab.indirectsymoff > FileSize)
527 return malformedError("indirectsymoff field of LC_DYSYMTAB command " +
528 Twine(LoadCommandIndex) + " extends past the end of "
529 "the file");
530 BigSize = Dysymtab.nindirectsyms;
531 BigSize *= sizeof(uint32_t);
532 BigSize += Dysymtab.indirectsymoff;
533 if (BigSize > FileSize)
534 return malformedError("indirectsymoff field plus nindirectsyms field times "
535 "sizeof(uint32_t) of LC_DYSYMTAB command " +
536 Twine(LoadCommandIndex) + " extends past the end of "
537 "the file");
Kevin Enderby4b3270e2016-11-02 21:08:39 +0000538 if (Error Err = checkOverlappingElement(Elements, Dysymtab.indirectsymoff,
539 Dysymtab.nindirectsyms *
540 sizeof(uint32_t),
NAKAMURA Takumid8ff2f42017-10-18 13:31:28 +0000541 "indirect table"))
Kevin Enderby4b3270e2016-11-02 21:08:39 +0000542 return Err;
Kevin Enderbyb8c2c1d2016-08-30 21:28:30 +0000543 if (Dysymtab.extreloff > FileSize)
544 return malformedError("extreloff field of LC_DYSYMTAB command " +
545 Twine(LoadCommandIndex) + " extends past the end of "
546 "the file");
547 BigSize = Dysymtab.nextrel;
548 BigSize *= sizeof(MachO::relocation_info);
549 BigSize += Dysymtab.extreloff;
550 if (BigSize > FileSize)
551 return malformedError("extreloff field plus nextrel field times sizeof"
552 "(struct relocation_info) of LC_DYSYMTAB command " +
553 Twine(LoadCommandIndex) + " extends past the end of "
554 "the file");
Kevin Enderby4b3270e2016-11-02 21:08:39 +0000555 if (Error Err = checkOverlappingElement(Elements, Dysymtab.extreloff,
556 Dysymtab.nextrel *
NAKAMURA Takumief15f2c2017-08-28 06:47:47 +0000557 sizeof(MachO::relocation_info),
558 "external relocation table"))
Kevin Enderby4b3270e2016-11-02 21:08:39 +0000559 return Err;
Kevin Enderbyb8c2c1d2016-08-30 21:28:30 +0000560 if (Dysymtab.locreloff > FileSize)
561 return malformedError("locreloff field of LC_DYSYMTAB command " +
562 Twine(LoadCommandIndex) + " extends past the end of "
563 "the file");
564 BigSize = Dysymtab.nlocrel;
565 BigSize *= sizeof(MachO::relocation_info);
566 BigSize += Dysymtab.locreloff;
567 if (BigSize > FileSize)
568 return malformedError("locreloff field plus nlocrel field times sizeof"
569 "(struct relocation_info) of LC_DYSYMTAB command " +
570 Twine(LoadCommandIndex) + " extends past the end of "
571 "the file");
Kevin Enderby4b3270e2016-11-02 21:08:39 +0000572 if (Error Err = checkOverlappingElement(Elements, Dysymtab.locreloff,
573 Dysymtab.nlocrel *
NAKAMURA Takumief15f2c2017-08-28 06:47:47 +0000574 sizeof(MachO::relocation_info),
575 "local relocation table"))
Kevin Enderby4b3270e2016-11-02 21:08:39 +0000576 return Err;
Kevin Enderbyb8c2c1d2016-08-30 21:28:30 +0000577 *DysymtabLoadCmd = Load.Ptr;
578 return Error::success();
579}
580
Lang Hames85334ad2016-12-04 01:56:10 +0000581static Error checkLinkeditDataCommand(const MachOObjectFile &Obj,
Kevin Enderbyf2e03382016-08-31 17:57:46 +0000582 const MachOObjectFile::LoadCommandInfo &Load,
583 uint32_t LoadCommandIndex,
Kevin Enderby4b3270e2016-11-02 21:08:39 +0000584 const char **LoadCmd, const char *CmdName,
585 std::list<MachOElement> &Elements,
586 const char *ElementName) {
Kevin Enderbyf2e03382016-08-31 17:57:46 +0000587 if (Load.C.cmdsize < sizeof(MachO::linkedit_data_command))
588 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
589 CmdName + " cmdsize too small");
590 if (*LoadCmd != nullptr)
591 return malformedError("more than one " + Twine(CmdName) + " command");
592 MachO::linkedit_data_command LinkData =
593 getStruct<MachO::linkedit_data_command>(Obj, Load.Ptr);
594 if (LinkData.cmdsize != sizeof(MachO::linkedit_data_command))
595 return malformedError(Twine(CmdName) + " command " +
596 Twine(LoadCommandIndex) + " has incorrect cmdsize");
Lang Hames85334ad2016-12-04 01:56:10 +0000597 uint64_t FileSize = Obj.getData().size();
Kevin Enderbyf2e03382016-08-31 17:57:46 +0000598 if (LinkData.dataoff > FileSize)
599 return malformedError("dataoff field of " + Twine(CmdName) + " command " +
600 Twine(LoadCommandIndex) + " extends past the end of "
601 "the file");
602 uint64_t BigSize = LinkData.dataoff;
603 BigSize += LinkData.datasize;
604 if (BigSize > FileSize)
605 return malformedError("dataoff field plus datasize field of " +
606 Twine(CmdName) + " command " +
607 Twine(LoadCommandIndex) + " extends past the end of "
608 "the file");
Kevin Enderby4b3270e2016-11-02 21:08:39 +0000609 if (Error Err = checkOverlappingElement(Elements, LinkData.dataoff,
610 LinkData.datasize, ElementName))
611 return Err;
Kevin Enderbyf2e03382016-08-31 17:57:46 +0000612 *LoadCmd = Load.Ptr;
613 return Error::success();
614}
615
Lang Hames85334ad2016-12-04 01:56:10 +0000616static Error checkDyldInfoCommand(const MachOObjectFile &Obj,
Kevin Enderby7402add2016-09-13 21:42:28 +0000617 const MachOObjectFile::LoadCommandInfo &Load,
618 uint32_t LoadCommandIndex,
Kevin Enderby4b3270e2016-11-02 21:08:39 +0000619 const char **LoadCmd, const char *CmdName,
620 std::list<MachOElement> &Elements) {
Kevin Enderby7402add2016-09-13 21:42:28 +0000621 if (Load.C.cmdsize < sizeof(MachO::dyld_info_command))
622 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
623 CmdName + " cmdsize too small");
624 if (*LoadCmd != nullptr)
625 return malformedError("more than one LC_DYLD_INFO and or LC_DYLD_INFO_ONLY "
626 "command");
627 MachO::dyld_info_command DyldInfo =
628 getStruct<MachO::dyld_info_command>(Obj, Load.Ptr);
629 if (DyldInfo.cmdsize != sizeof(MachO::dyld_info_command))
630 return malformedError(Twine(CmdName) + " command " +
631 Twine(LoadCommandIndex) + " has incorrect cmdsize");
Lang Hames85334ad2016-12-04 01:56:10 +0000632 uint64_t FileSize = Obj.getData().size();
Kevin Enderby7402add2016-09-13 21:42:28 +0000633 if (DyldInfo.rebase_off > FileSize)
634 return malformedError("rebase_off field of " + Twine(CmdName) +
635 " command " + Twine(LoadCommandIndex) + " extends "
636 "past the end of the file");
637 uint64_t BigSize = DyldInfo.rebase_off;
638 BigSize += DyldInfo.rebase_size;
639 if (BigSize > FileSize)
640 return malformedError("rebase_off field plus rebase_size field of " +
641 Twine(CmdName) + " command " +
642 Twine(LoadCommandIndex) + " extends past the end of "
643 "the file");
Kevin Enderby4b3270e2016-11-02 21:08:39 +0000644 if (Error Err = checkOverlappingElement(Elements, DyldInfo.rebase_off,
645 DyldInfo.rebase_size,
646 "dyld rebase info"))
647 return Err;
Kevin Enderby7402add2016-09-13 21:42:28 +0000648 if (DyldInfo.bind_off > FileSize)
649 return malformedError("bind_off field of " + Twine(CmdName) +
650 " command " + Twine(LoadCommandIndex) + " extends "
651 "past the end of the file");
652 BigSize = DyldInfo.bind_off;
653 BigSize += DyldInfo.bind_size;
654 if (BigSize > FileSize)
655 return malformedError("bind_off field plus bind_size field of " +
656 Twine(CmdName) + " command " +
657 Twine(LoadCommandIndex) + " extends past the end of "
658 "the file");
Kevin Enderby4b3270e2016-11-02 21:08:39 +0000659 if (Error Err = checkOverlappingElement(Elements, DyldInfo.bind_off,
660 DyldInfo.bind_size,
661 "dyld bind info"))
662 return Err;
Kevin Enderby7402add2016-09-13 21:42:28 +0000663 if (DyldInfo.weak_bind_off > FileSize)
664 return malformedError("weak_bind_off field of " + Twine(CmdName) +
665 " command " + Twine(LoadCommandIndex) + " extends "
666 "past the end of the file");
667 BigSize = DyldInfo.weak_bind_off;
668 BigSize += DyldInfo.weak_bind_size;
669 if (BigSize > FileSize)
670 return malformedError("weak_bind_off field plus weak_bind_size field of " +
671 Twine(CmdName) + " command " +
672 Twine(LoadCommandIndex) + " extends past the end of "
673 "the file");
Kevin Enderby4b3270e2016-11-02 21:08:39 +0000674 if (Error Err = checkOverlappingElement(Elements, DyldInfo.weak_bind_off,
675 DyldInfo.weak_bind_size,
676 "dyld weak bind info"))
677 return Err;
Kevin Enderby7402add2016-09-13 21:42:28 +0000678 if (DyldInfo.lazy_bind_off > FileSize)
679 return malformedError("lazy_bind_off field of " + Twine(CmdName) +
680 " command " + Twine(LoadCommandIndex) + " extends "
681 "past the end of the file");
682 BigSize = DyldInfo.lazy_bind_off;
683 BigSize += DyldInfo.lazy_bind_size;
684 if (BigSize > FileSize)
685 return malformedError("lazy_bind_off field plus lazy_bind_size field of " +
686 Twine(CmdName) + " command " +
687 Twine(LoadCommandIndex) + " extends past the end of "
688 "the file");
Kevin Enderby4b3270e2016-11-02 21:08:39 +0000689 if (Error Err = checkOverlappingElement(Elements, DyldInfo.lazy_bind_off,
690 DyldInfo.lazy_bind_size,
691 "dyld lazy bind info"))
692 return Err;
Kevin Enderby7402add2016-09-13 21:42:28 +0000693 if (DyldInfo.export_off > FileSize)
694 return malformedError("export_off field of " + Twine(CmdName) +
695 " command " + Twine(LoadCommandIndex) + " extends "
696 "past the end of the file");
697 BigSize = DyldInfo.export_off;
698 BigSize += DyldInfo.export_size;
699 if (BigSize > FileSize)
700 return malformedError("export_off field plus export_size field of " +
701 Twine(CmdName) + " command " +
702 Twine(LoadCommandIndex) + " extends past the end of "
703 "the file");
Kevin Enderby4b3270e2016-11-02 21:08:39 +0000704 if (Error Err = checkOverlappingElement(Elements, DyldInfo.export_off,
705 DyldInfo.export_size,
706 "dyld export info"))
707 return Err;
Kevin Enderby7402add2016-09-13 21:42:28 +0000708 *LoadCmd = Load.Ptr;
709 return Error::success();
710}
711
Lang Hames85334ad2016-12-04 01:56:10 +0000712static Error checkDylibCommand(const MachOObjectFile &Obj,
Kevin Enderby7bcdeca2016-09-20 20:14:14 +0000713 const MachOObjectFile::LoadCommandInfo &Load,
714 uint32_t LoadCommandIndex, const char *CmdName) {
715 if (Load.C.cmdsize < sizeof(MachO::dylib_command))
716 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
717 CmdName + " cmdsize too small");
718 MachO::dylib_command D = getStruct<MachO::dylib_command>(Obj, Load.Ptr);
719 if (D.dylib.name < sizeof(MachO::dylib_command))
720 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
721 CmdName + " name.offset field too small, not past "
722 "the end of the dylib_command struct");
723 if (D.dylib.name >= D.cmdsize)
724 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
725 CmdName + " name.offset field extends past the end "
726 "of the load command");
727 // Make sure there is a null between the starting offset of the name and
728 // the end of the load command.
729 uint32_t i;
730 const char *P = (const char *)Load.Ptr;
731 for (i = D.dylib.name; i < D.cmdsize; i++)
732 if (P[i] == '\0')
733 break;
734 if (i >= D.cmdsize)
735 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
736 CmdName + " library name extends past the end of the "
737 "load command");
738 return Error::success();
739}
740
Lang Hames85334ad2016-12-04 01:56:10 +0000741static Error checkDylibIdCommand(const MachOObjectFile &Obj,
Kevin Enderby7bcdeca2016-09-20 20:14:14 +0000742 const MachOObjectFile::LoadCommandInfo &Load,
743 uint32_t LoadCommandIndex,
744 const char **LoadCmd) {
745 if (Error Err = checkDylibCommand(Obj, Load, LoadCommandIndex,
746 "LC_ID_DYLIB"))
747 return Err;
748 if (*LoadCmd != nullptr)
749 return malformedError("more than one LC_ID_DYLIB command");
Lang Hames85334ad2016-12-04 01:56:10 +0000750 if (Obj.getHeader().filetype != MachO::MH_DYLIB &&
751 Obj.getHeader().filetype != MachO::MH_DYLIB_STUB)
Kevin Enderby7bcdeca2016-09-20 20:14:14 +0000752 return malformedError("LC_ID_DYLIB load command in non-dynamic library "
753 "file type");
754 *LoadCmd = Load.Ptr;
755 return Error::success();
756}
757
Lang Hames85334ad2016-12-04 01:56:10 +0000758static Error checkDyldCommand(const MachOObjectFile &Obj,
Kevin Enderby4bc0cbd2016-09-27 23:24:13 +0000759 const MachOObjectFile::LoadCommandInfo &Load,
760 uint32_t LoadCommandIndex, const char *CmdName) {
761 if (Load.C.cmdsize < sizeof(MachO::dylinker_command))
762 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
763 CmdName + " cmdsize too small");
764 MachO::dylinker_command D = getStruct<MachO::dylinker_command>(Obj, Load.Ptr);
765 if (D.name < sizeof(MachO::dylinker_command))
766 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
767 CmdName + " name.offset field too small, not past "
768 "the end of the dylinker_command struct");
769 if (D.name >= D.cmdsize)
770 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
771 CmdName + " name.offset field extends past the end "
772 "of the load command");
773 // Make sure there is a null between the starting offset of the name and
774 // the end of the load command.
775 uint32_t i;
776 const char *P = (const char *)Load.Ptr;
777 for (i = D.name; i < D.cmdsize; i++)
778 if (P[i] == '\0')
779 break;
780 if (i >= D.cmdsize)
781 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
782 CmdName + " dyld name extends past the end of the "
783 "load command");
784 return Error::success();
785}
786
Lang Hames85334ad2016-12-04 01:56:10 +0000787static Error checkVersCommand(const MachOObjectFile &Obj,
Kevin Enderbya2d25512016-09-28 21:20:45 +0000788 const MachOObjectFile::LoadCommandInfo &Load,
789 uint32_t LoadCommandIndex,
790 const char **LoadCmd, const char *CmdName) {
791 if (Load.C.cmdsize != sizeof(MachO::version_min_command))
792 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
793 CmdName + " has incorrect cmdsize");
794 if (*LoadCmd != nullptr)
795 return malformedError("more than one LC_VERSION_MIN_MACOSX, "
796 "LC_VERSION_MIN_IPHONEOS, LC_VERSION_MIN_TVOS or "
797 "LC_VERSION_MIN_WATCHOS command");
798 *LoadCmd = Load.Ptr;
799 return Error::success();
800}
801
Kevin Enderby045015e2017-01-19 17:36:31 +0000802static Error checkNoteCommand(const MachOObjectFile &Obj,
803 const MachOObjectFile::LoadCommandInfo &Load,
804 uint32_t LoadCommandIndex,
805 std::list<MachOElement> &Elements) {
806 if (Load.C.cmdsize != sizeof(MachO::note_command))
Jonas Devlieghere143e1f12017-09-13 13:43:01 +0000807 return malformedError("load command " + Twine(LoadCommandIndex) +
Kevin Enderby045015e2017-01-19 17:36:31 +0000808 " LC_NOTE has incorrect cmdsize");
809 MachO::note_command Nt = getStruct<MachO::note_command>(Obj, Load.Ptr);
810 uint64_t FileSize = Obj.getData().size();
811 if (Nt.offset > FileSize)
812 return malformedError("offset field of LC_NOTE command " +
813 Twine(LoadCommandIndex) + " extends "
814 "past the end of the file");
815 uint64_t BigSize = Nt.offset;
816 BigSize += Nt.size;
817 if (BigSize > FileSize)
818 return malformedError("size field plus offset field of LC_NOTE command " +
819 Twine(LoadCommandIndex) + " extends past the end of "
820 "the file");
821 if (Error Err = checkOverlappingElement(Elements, Nt.offset, Nt.size,
822 "LC_NOTE data"))
823 return Err;
824 return Error::success();
825}
826
Steven Wu6d5a0272017-01-23 20:07:55 +0000827static Error
828parseBuildVersionCommand(const MachOObjectFile &Obj,
829 const MachOObjectFile::LoadCommandInfo &Load,
830 SmallVectorImpl<const char*> &BuildTools,
831 uint32_t LoadCommandIndex) {
832 MachO::build_version_command BVC =
833 getStruct<MachO::build_version_command>(Obj, Load.Ptr);
834 if (Load.C.cmdsize !=
835 sizeof(MachO::build_version_command) +
836 BVC.ntools * sizeof(MachO::build_tool_version))
837 return malformedError("load command " + Twine(LoadCommandIndex) +
838 " LC_BUILD_VERSION_COMMAND has incorrect cmdsize");
839
840 auto Start = Load.Ptr + sizeof(MachO::build_version_command);
841 BuildTools.resize(BVC.ntools);
842 for (unsigned i = 0; i < BVC.ntools; ++i)
843 BuildTools[i] = Start + i * sizeof(MachO::build_tool_version);
844
845 return Error::success();
846}
847
Lang Hames85334ad2016-12-04 01:56:10 +0000848static Error checkRpathCommand(const MachOObjectFile &Obj,
Kevin Enderbydda50f22016-09-28 23:16:01 +0000849 const MachOObjectFile::LoadCommandInfo &Load,
850 uint32_t LoadCommandIndex) {
851 if (Load.C.cmdsize < sizeof(MachO::rpath_command))
852 return malformedError("load command " + Twine(LoadCommandIndex) +
853 " LC_RPATH cmdsize too small");
854 MachO::rpath_command R = getStruct<MachO::rpath_command>(Obj, Load.Ptr);
855 if (R.path < sizeof(MachO::rpath_command))
856 return malformedError("load command " + Twine(LoadCommandIndex) +
857 " LC_RPATH path.offset field too small, not past "
858 "the end of the rpath_command struct");
859 if (R.path >= R.cmdsize)
860 return malformedError("load command " + Twine(LoadCommandIndex) +
861 " LC_RPATH path.offset field extends past the end "
862 "of the load command");
863 // Make sure there is a null between the starting offset of the path and
864 // the end of the load command.
865 uint32_t i;
866 const char *P = (const char *)Load.Ptr;
867 for (i = R.path; i < R.cmdsize; i++)
868 if (P[i] == '\0')
869 break;
870 if (i >= R.cmdsize)
871 return malformedError("load command " + Twine(LoadCommandIndex) +
872 " LC_RPATH library name extends past the end of the "
873 "load command");
874 return Error::success();
875}
876
Lang Hames85334ad2016-12-04 01:56:10 +0000877static Error checkEncryptCommand(const MachOObjectFile &Obj,
Kevin Enderbyec53f4b2016-10-04 20:37:43 +0000878 const MachOObjectFile::LoadCommandInfo &Load,
879 uint32_t LoadCommandIndex,
880 uint64_t cryptoff, uint64_t cryptsize,
881 const char **LoadCmd, const char *CmdName) {
882 if (*LoadCmd != nullptr)
883 return malformedError("more than one LC_ENCRYPTION_INFO and or "
884 "LC_ENCRYPTION_INFO_64 command");
Lang Hames85334ad2016-12-04 01:56:10 +0000885 uint64_t FileSize = Obj.getData().size();
Kevin Enderbyec53f4b2016-10-04 20:37:43 +0000886 if (cryptoff > FileSize)
887 return malformedError("cryptoff field of " + Twine(CmdName) +
888 " command " + Twine(LoadCommandIndex) + " extends "
889 "past the end of the file");
890 uint64_t BigSize = cryptoff;
891 BigSize += cryptsize;
892 if (BigSize > FileSize)
893 return malformedError("cryptoff field plus cryptsize field of " +
894 Twine(CmdName) + " command " +
895 Twine(LoadCommandIndex) + " extends past the end of "
896 "the file");
897 *LoadCmd = Load.Ptr;
898 return Error::success();
899}
900
Lang Hames85334ad2016-12-04 01:56:10 +0000901static Error checkLinkerOptCommand(const MachOObjectFile &Obj,
Kevin Enderby9a966692016-10-11 21:04:39 +0000902 const MachOObjectFile::LoadCommandInfo &Load,
903 uint32_t LoadCommandIndex) {
904 if (Load.C.cmdsize < sizeof(MachO::linker_option_command))
905 return malformedError("load command " + Twine(LoadCommandIndex) +
906 " LC_LINKER_OPTION cmdsize too small");
907 MachO::linker_option_command L =
908 getStruct<MachO::linker_option_command>(Obj, Load.Ptr);
909 // Make sure the count of strings is correct.
910 const char *string = (const char *)Load.Ptr +
911 sizeof(struct MachO::linker_option_command);
912 uint32_t left = L.cmdsize - sizeof(struct MachO::linker_option_command);
913 uint32_t i = 0;
914 while (left > 0) {
915 while (*string == '\0' && left > 0) {
916 string++;
917 left--;
918 }
919 if (left > 0) {
920 i++;
921 uint32_t NullPos = StringRef(string, left).find('\0');
922 uint32_t len = std::min(NullPos, left) + 1;
923 string += len;
924 left -= len;
925 }
926 }
927 if (L.count != i)
928 return malformedError("load command " + Twine(LoadCommandIndex) +
929 " LC_LINKER_OPTION string count " + Twine(L.count) +
930 " does not match number of strings");
931 return Error::success();
932}
933
Lang Hames85334ad2016-12-04 01:56:10 +0000934static Error checkSubCommand(const MachOObjectFile &Obj,
Kevin Enderby9296e5f2016-10-17 22:09:25 +0000935 const MachOObjectFile::LoadCommandInfo &Load,
936 uint32_t LoadCommandIndex, const char *CmdName,
937 size_t SizeOfCmd, const char *CmdStructName,
938 uint32_t PathOffset, const char *PathFieldName) {
939 if (PathOffset < SizeOfCmd)
940 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
941 CmdName + " " + PathFieldName + ".offset field too "
942 "small, not past the end of the " + CmdStructName);
943 if (PathOffset >= Load.C.cmdsize)
944 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
945 CmdName + " " + PathFieldName + ".offset field "
946 "extends past the end of the load command");
947 // Make sure there is a null between the starting offset of the path and
948 // the end of the load command.
949 uint32_t i;
950 const char *P = (const char *)Load.Ptr;
951 for (i = PathOffset; i < Load.C.cmdsize; i++)
952 if (P[i] == '\0')
953 break;
954 if (i >= Load.C.cmdsize)
955 return malformedError("load command " + Twine(LoadCommandIndex) + " " +
956 CmdName + " " + PathFieldName + " name extends past "
957 "the end of the load command");
958 return Error::success();
959}
960
Lang Hames85334ad2016-12-04 01:56:10 +0000961static Error checkThreadCommand(const MachOObjectFile &Obj,
Kevin Enderby04e33072016-10-19 23:44:34 +0000962 const MachOObjectFile::LoadCommandInfo &Load,
963 uint32_t LoadCommandIndex,
964 const char *CmdName) {
965 if (Load.C.cmdsize < sizeof(MachO::thread_command))
966 return malformedError("load command " + Twine(LoadCommandIndex) +
967 CmdName + " cmdsize too small");
968 MachO::thread_command T =
969 getStruct<MachO::thread_command>(Obj, Load.Ptr);
970 const char *state = Load.Ptr + sizeof(MachO::thread_command);
971 const char *end = Load.Ptr + T.cmdsize;
972 uint32_t nflavor = 0;
973 uint32_t cputype = getCPUType(Obj);
974 while (state < end) {
975 if(state + sizeof(uint32_t) > end)
976 return malformedError("load command " + Twine(LoadCommandIndex) +
977 "flavor in " + CmdName + " extends past end of "
978 "command");
979 uint32_t flavor;
980 memcpy(&flavor, state, sizeof(uint32_t));
Lang Hames85334ad2016-12-04 01:56:10 +0000981 if (Obj.isLittleEndian() != sys::IsLittleEndianHost)
Kevin Enderby04e33072016-10-19 23:44:34 +0000982 sys::swapByteOrder(flavor);
983 state += sizeof(uint32_t);
984
985 if(state + sizeof(uint32_t) > end)
986 return malformedError("load command " + Twine(LoadCommandIndex) +
987 " count in " + CmdName + " extends past end of "
988 "command");
989 uint32_t count;
990 memcpy(&count, state, sizeof(uint32_t));
Lang Hames85334ad2016-12-04 01:56:10 +0000991 if (Obj.isLittleEndian() != sys::IsLittleEndianHost)
Kevin Enderby04e33072016-10-19 23:44:34 +0000992 sys::swapByteOrder(count);
993 state += sizeof(uint32_t);
994
Kevin Enderbyaf0e1c52017-01-23 21:13:29 +0000995 if (cputype == MachO::CPU_TYPE_I386) {
996 if (flavor == MachO::x86_THREAD_STATE32) {
997 if (count != MachO::x86_THREAD_STATE32_COUNT)
998 return malformedError("load command " + Twine(LoadCommandIndex) +
999 " count not x86_THREAD_STATE32_COUNT for "
1000 "flavor number " + Twine(nflavor) + " which is "
1001 "a x86_THREAD_STATE32 flavor in " + CmdName +
1002 " command");
1003 if (state + sizeof(MachO::x86_thread_state32_t) > end)
1004 return malformedError("load command " + Twine(LoadCommandIndex) +
1005 " x86_THREAD_STATE32 extends past end of "
1006 "command in " + CmdName + " command");
1007 state += sizeof(MachO::x86_thread_state32_t);
1008 } else {
1009 return malformedError("load command " + Twine(LoadCommandIndex) +
1010 " unknown flavor (" + Twine(flavor) + ") for "
1011 "flavor number " + Twine(nflavor) + " in " +
1012 CmdName + " command");
1013 }
1014 } else if (cputype == MachO::CPU_TYPE_X86_64) {
Kevin Enderby0e9471b2018-03-08 23:10:38 +00001015 if (flavor == MachO::x86_THREAD_STATE) {
1016 if (count != MachO::x86_THREAD_STATE_COUNT)
1017 return malformedError("load command " + Twine(LoadCommandIndex) +
1018 " count not x86_THREAD_STATE_COUNT for "
1019 "flavor number " + Twine(nflavor) + " which is "
1020 "a x86_THREAD_STATE flavor in " + CmdName +
1021 " command");
1022 if (state + sizeof(MachO::x86_thread_state_t) > end)
1023 return malformedError("load command " + Twine(LoadCommandIndex) +
1024 " x86_THREAD_STATE extends past end of "
1025 "command in " + CmdName + " command");
1026 state += sizeof(MachO::x86_thread_state_t);
1027 } else if (flavor == MachO::x86_FLOAT_STATE) {
1028 if (count != MachO::x86_FLOAT_STATE_COUNT)
1029 return malformedError("load command " + Twine(LoadCommandIndex) +
1030 " count not x86_FLOAT_STATE_COUNT for "
1031 "flavor number " + Twine(nflavor) + " which is "
1032 "a x86_FLOAT_STATE flavor in " + CmdName +
1033 " command");
1034 if (state + sizeof(MachO::x86_float_state_t) > end)
1035 return malformedError("load command " + Twine(LoadCommandIndex) +
1036 " x86_FLOAT_STATE extends past end of "
1037 "command in " + CmdName + " command");
1038 state += sizeof(MachO::x86_float_state_t);
1039 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
1040 if (count != MachO::x86_EXCEPTION_STATE_COUNT)
1041 return malformedError("load command " + Twine(LoadCommandIndex) +
1042 " count not x86_EXCEPTION_STATE_COUNT for "
1043 "flavor number " + Twine(nflavor) + " which is "
1044 "a x86_EXCEPTION_STATE flavor in " + CmdName +
1045 " command");
1046 if (state + sizeof(MachO::x86_exception_state_t) > end)
1047 return malformedError("load command " + Twine(LoadCommandIndex) +
1048 " x86_EXCEPTION_STATE extends past end of "
1049 "command in " + CmdName + " command");
1050 state += sizeof(MachO::x86_exception_state_t);
1051 } else if (flavor == MachO::x86_THREAD_STATE64) {
Kevin Enderby04e33072016-10-19 23:44:34 +00001052 if (count != MachO::x86_THREAD_STATE64_COUNT)
1053 return malformedError("load command " + Twine(LoadCommandIndex) +
1054 " count not x86_THREAD_STATE64_COUNT for "
1055 "flavor number " + Twine(nflavor) + " which is "
1056 "a x86_THREAD_STATE64 flavor in " + CmdName +
1057 " command");
1058 if (state + sizeof(MachO::x86_thread_state64_t) > end)
1059 return malformedError("load command " + Twine(LoadCommandIndex) +
1060 " x86_THREAD_STATE64 extends past end of "
1061 "command in " + CmdName + " command");
1062 state += sizeof(MachO::x86_thread_state64_t);
Kevin Enderby0e9471b2018-03-08 23:10:38 +00001063 } else if (flavor == MachO::x86_EXCEPTION_STATE64) {
1064 if (count != MachO::x86_EXCEPTION_STATE64_COUNT)
1065 return malformedError("load command " + Twine(LoadCommandIndex) +
1066 " count not x86_EXCEPTION_STATE64_COUNT for "
1067 "flavor number " + Twine(nflavor) + " which is "
1068 "a x86_EXCEPTION_STATE64 flavor in " + CmdName +
1069 " command");
1070 if (state + sizeof(MachO::x86_exception_state64_t) > end)
1071 return malformedError("load command " + Twine(LoadCommandIndex) +
1072 " x86_EXCEPTION_STATE64 extends past end of "
1073 "command in " + CmdName + " command");
1074 state += sizeof(MachO::x86_exception_state64_t);
Kevin Enderby04e33072016-10-19 23:44:34 +00001075 } else {
1076 return malformedError("load command " + Twine(LoadCommandIndex) +
1077 " unknown flavor (" + Twine(flavor) + ") for "
1078 "flavor number " + Twine(nflavor) + " in " +
1079 CmdName + " command");
1080 }
1081 } else if (cputype == MachO::CPU_TYPE_ARM) {
1082 if (flavor == MachO::ARM_THREAD_STATE) {
1083 if (count != MachO::ARM_THREAD_STATE_COUNT)
1084 return malformedError("load command " + Twine(LoadCommandIndex) +
1085 " count not ARM_THREAD_STATE_COUNT for "
1086 "flavor number " + Twine(nflavor) + " which is "
1087 "a ARM_THREAD_STATE flavor in " + CmdName +
1088 " command");
1089 if (state + sizeof(MachO::arm_thread_state32_t) > end)
1090 return malformedError("load command " + Twine(LoadCommandIndex) +
1091 " ARM_THREAD_STATE extends past end of "
1092 "command in " + CmdName + " command");
1093 state += sizeof(MachO::arm_thread_state32_t);
1094 } else {
1095 return malformedError("load command " + Twine(LoadCommandIndex) +
1096 " unknown flavor (" + Twine(flavor) + ") for "
1097 "flavor number " + Twine(nflavor) + " in " +
1098 CmdName + " command");
1099 }
Kevin Enderby00b62fb2016-11-03 20:51:28 +00001100 } else if (cputype == MachO::CPU_TYPE_ARM64) {
1101 if (flavor == MachO::ARM_THREAD_STATE64) {
1102 if (count != MachO::ARM_THREAD_STATE64_COUNT)
1103 return malformedError("load command " + Twine(LoadCommandIndex) +
1104 " count not ARM_THREAD_STATE64_COUNT for "
1105 "flavor number " + Twine(nflavor) + " which is "
1106 "a ARM_THREAD_STATE64 flavor in " + CmdName +
1107 " command");
1108 if (state + sizeof(MachO::arm_thread_state64_t) > end)
1109 return malformedError("load command " + Twine(LoadCommandIndex) +
1110 " ARM_THREAD_STATE64 extends past end of "
1111 "command in " + CmdName + " command");
1112 state += sizeof(MachO::arm_thread_state64_t);
1113 } else {
1114 return malformedError("load command " + Twine(LoadCommandIndex) +
1115 " unknown flavor (" + Twine(flavor) + ") for "
1116 "flavor number " + Twine(nflavor) + " in " +
1117 CmdName + " command");
1118 }
Kevin Enderby04e33072016-10-19 23:44:34 +00001119 } else if (cputype == MachO::CPU_TYPE_POWERPC) {
1120 if (flavor == MachO::PPC_THREAD_STATE) {
1121 if (count != MachO::PPC_THREAD_STATE_COUNT)
1122 return malformedError("load command " + Twine(LoadCommandIndex) +
1123 " count not PPC_THREAD_STATE_COUNT for "
1124 "flavor number " + Twine(nflavor) + " which is "
1125 "a PPC_THREAD_STATE flavor in " + CmdName +
1126 " command");
1127 if (state + sizeof(MachO::ppc_thread_state32_t) > end)
1128 return malformedError("load command " + Twine(LoadCommandIndex) +
1129 " PPC_THREAD_STATE extends past end of "
1130 "command in " + CmdName + " command");
1131 state += sizeof(MachO::ppc_thread_state32_t);
1132 } else {
1133 return malformedError("load command " + Twine(LoadCommandIndex) +
1134 " unknown flavor (" + Twine(flavor) + ") for "
1135 "flavor number " + Twine(nflavor) + " in " +
1136 CmdName + " command");
1137 }
1138 } else {
1139 return malformedError("unknown cputype (" + Twine(cputype) + ") load "
1140 "command " + Twine(LoadCommandIndex) + " for " +
1141 CmdName + " command can't be checked");
1142 }
1143 nflavor++;
1144 }
1145 return Error::success();
1146}
1147
Lang Hames85334ad2016-12-04 01:56:10 +00001148static Error checkTwoLevelHintsCommand(const MachOObjectFile &Obj,
Kevin Enderbyd6842a62016-10-20 20:10:30 +00001149 const MachOObjectFile::LoadCommandInfo
1150 &Load,
1151 uint32_t LoadCommandIndex,
Kevin Enderby4b3270e2016-11-02 21:08:39 +00001152 const char **LoadCmd,
1153 std::list<MachOElement> &Elements) {
Kevin Enderbyd6842a62016-10-20 20:10:30 +00001154 if (Load.C.cmdsize != sizeof(MachO::twolevel_hints_command))
1155 return malformedError("load command " + Twine(LoadCommandIndex) +
1156 " LC_TWOLEVEL_HINTS has incorrect cmdsize");
1157 if (*LoadCmd != nullptr)
1158 return malformedError("more than one LC_TWOLEVEL_HINTS command");
1159 MachO::twolevel_hints_command Hints =
1160 getStruct<MachO::twolevel_hints_command>(Obj, Load.Ptr);
Lang Hames85334ad2016-12-04 01:56:10 +00001161 uint64_t FileSize = Obj.getData().size();
Kevin Enderbyd6842a62016-10-20 20:10:30 +00001162 if (Hints.offset > FileSize)
1163 return malformedError("offset field of LC_TWOLEVEL_HINTS command " +
1164 Twine(LoadCommandIndex) + " extends past the end of "
1165 "the file");
1166 uint64_t BigSize = Hints.nhints;
Jessica Paquetteb5459572017-10-17 20:43:33 +00001167 BigSize *= sizeof(MachO::twolevel_hint);
Kevin Enderbyd6842a62016-10-20 20:10:30 +00001168 BigSize += Hints.offset;
1169 if (BigSize > FileSize)
1170 return malformedError("offset field plus nhints times sizeof(struct "
1171 "twolevel_hint) field of LC_TWOLEVEL_HINTS command " +
1172 Twine(LoadCommandIndex) + " extends past the end of "
1173 "the file");
Kevin Enderby4b3270e2016-11-02 21:08:39 +00001174 if (Error Err = checkOverlappingElement(Elements, Hints.offset, Hints.nhints *
1175 sizeof(MachO::twolevel_hint),
1176 "two level hints"))
1177 return Err;
Kevin Enderbyd6842a62016-10-20 20:10:30 +00001178 *LoadCmd = Load.Ptr;
1179 return Error::success();
1180}
1181
Kevin Enderby60923f32016-10-27 20:59:10 +00001182// Returns true if the libObject code does not support the load command and its
1183// contents. The cmd value it is treated as an unknown load command but with
1184// an error message that says the cmd value is obsolete.
1185static bool isLoadCommandObsolete(uint32_t cmd) {
1186 if (cmd == MachO::LC_SYMSEG ||
1187 cmd == MachO::LC_LOADFVMLIB ||
1188 cmd == MachO::LC_IDFVMLIB ||
1189 cmd == MachO::LC_IDENT ||
1190 cmd == MachO::LC_FVMFILE ||
1191 cmd == MachO::LC_PREPAGE ||
1192 cmd == MachO::LC_PREBOUND_DYLIB ||
1193 cmd == MachO::LC_TWOLEVEL_HINTS ||
1194 cmd == MachO::LC_PREBIND_CKSUM)
1195 return true;
1196 return false;
1197}
1198
Lang Hames086a6fa2016-03-25 21:59:14 +00001199Expected<std::unique_ptr<MachOObjectFile>>
1200MachOObjectFile::create(MemoryBufferRef Object, bool IsLittleEndian,
Kevin Enderbyaa450922016-10-24 21:15:11 +00001201 bool Is64Bits, uint32_t UniversalCputype,
1202 uint32_t UniversalIndex) {
Mehdi Aminidf0b8bc2016-11-11 04:28:40 +00001203 Error Err = Error::success();
Lang Hames086a6fa2016-03-25 21:59:14 +00001204 std::unique_ptr<MachOObjectFile> Obj(
1205 new MachOObjectFile(std::move(Object), IsLittleEndian,
Kevin Enderbyaa450922016-10-24 21:15:11 +00001206 Is64Bits, Err, UniversalCputype,
1207 UniversalIndex));
Lang Hames086a6fa2016-03-25 21:59:14 +00001208 if (Err)
1209 return std::move(Err);
1210 return std::move(Obj);
1211}
1212
Rafael Espindola548f2b62014-08-19 18:44:46 +00001213MachOObjectFile::MachOObjectFile(MemoryBufferRef Object, bool IsLittleEndian,
Kevin Enderbyaa450922016-10-24 21:15:11 +00001214 bool Is64bits, Error &Err,
1215 uint32_t UniversalCputype,
1216 uint32_t UniversalIndex)
Eugene Zelenko903f87e2017-04-21 22:03:05 +00001217 : ObjectFile(getMachOType(IsLittleEndian, Is64bits), Object) {
Lang Hames78095432016-07-22 16:11:25 +00001218 ErrorAsOutParameter ErrAsOutParam(&Err);
Kevin Enderby296471b2016-08-12 20:10:25 +00001219 uint64_t SizeOfHeaders;
Kevin Enderbyaa450922016-10-24 21:15:11 +00001220 uint32_t cputype;
Kevin Enderby63247512016-04-13 21:17:58 +00001221 if (is64Bit()) {
Lang Hames85334ad2016-12-04 01:56:10 +00001222 parseHeader(*this, Header64, Err);
Kevin Enderby296471b2016-08-12 20:10:25 +00001223 SizeOfHeaders = sizeof(MachO::mach_header_64);
Kevin Enderbyaa450922016-10-24 21:15:11 +00001224 cputype = Header64.cputype;
Kevin Enderby63247512016-04-13 21:17:58 +00001225 } else {
Lang Hames85334ad2016-12-04 01:56:10 +00001226 parseHeader(*this, Header, Err);
Kevin Enderby296471b2016-08-12 20:10:25 +00001227 SizeOfHeaders = sizeof(MachO::mach_header);
Kevin Enderbyaa450922016-10-24 21:15:11 +00001228 cputype = Header.cputype;
Kevin Enderby63247512016-04-13 21:17:58 +00001229 }
Lang Hames3e222972016-03-25 17:25:34 +00001230 if (Err)
Alexey Samsonov1d4ec712015-06-04 19:45:22 +00001231 return;
Kevin Enderby296471b2016-08-12 20:10:25 +00001232 SizeOfHeaders += getHeader().sizeofcmds;
1233 if (getData().data() + SizeOfHeaders > getData().end()) {
Kevin Enderbyeaa1f082016-05-06 20:16:28 +00001234 Err = malformedError("load commands extend past the end of the file");
Kevin Enderby63247512016-04-13 21:17:58 +00001235 return;
1236 }
Kevin Enderbyaa450922016-10-24 21:15:11 +00001237 if (UniversalCputype != 0 && cputype != UniversalCputype) {
1238 Err = malformedError("universal header architecture: " +
1239 Twine(UniversalIndex) + "'s cputype does not match "
1240 "object file's mach header");
1241 return;
1242 }
Kevin Enderbye9885e02016-10-31 20:29:48 +00001243 std::list<MachOElement> Elements;
1244 Elements.push_back({0, SizeOfHeaders, "Mach-O headers"});
Alexey Samsonovd7eb7d72015-06-04 19:22:03 +00001245
1246 uint32_t LoadCommandCount = getHeader().ncmds;
Lang Hames3e222972016-03-25 17:25:34 +00001247 LoadCommandInfo Load;
Kevin Enderby7bcdeca2016-09-20 20:14:14 +00001248 if (LoadCommandCount != 0) {
Lang Hames85334ad2016-12-04 01:56:10 +00001249 if (auto LoadOrErr = getFirstLoadCommandInfo(*this))
Kevin Enderby7bcdeca2016-09-20 20:14:14 +00001250 Load = *LoadOrErr;
1251 else {
1252 Err = LoadOrErr.takeError();
1253 return;
1254 }
Alexey Samsonov7e699dc2015-06-04 19:57:46 +00001255 }
Lang Hames3e222972016-03-25 17:25:34 +00001256
Kevin Enderby7bcdeca2016-09-20 20:14:14 +00001257 const char *DyldIdLoadCmd = nullptr;
Kevin Enderby851d92e2016-09-26 21:11:03 +00001258 const char *FuncStartsLoadCmd = nullptr;
1259 const char *SplitInfoLoadCmd = nullptr;
1260 const char *CodeSignDrsLoadCmd = nullptr;
Kevin Enderbyc6b8aca2016-10-18 20:24:12 +00001261 const char *CodeSignLoadCmd = nullptr;
Kevin Enderbya2d25512016-09-28 21:20:45 +00001262 const char *VersLoadCmd = nullptr;
Kevin Enderby9b04a402016-09-29 17:45:23 +00001263 const char *SourceLoadCmd = nullptr;
Kevin Enderbyc681bf52016-09-29 21:07:29 +00001264 const char *EntryPointLoadCmd = nullptr;
Kevin Enderbyec53f4b2016-10-04 20:37:43 +00001265 const char *EncryptLoadCmd = nullptr;
Kevin Enderby640265d2016-10-18 17:54:17 +00001266 const char *RoutinesLoadCmd = nullptr;
Kevin Enderby04e33072016-10-19 23:44:34 +00001267 const char *UnixThreadLoadCmd = nullptr;
Kevin Enderbyd6842a62016-10-20 20:10:30 +00001268 const char *TwoLevelHintsLoadCmd = nullptr;
Alexey Samsonov40ec40a2015-06-03 22:19:36 +00001269 for (unsigned I = 0; I < LoadCommandCount; ++I) {
Kevin Enderbyac3d9342016-07-07 22:11:42 +00001270 if (is64Bit()) {
1271 if (Load.C.cmdsize % 8 != 0) {
1272 // We have a hack here to allow 64-bit Mach-O core files to have
1273 // LC_THREAD commands that are only a multiple of 4 and not 8 to be
1274 // allowed since the macOS kernel produces them.
1275 if (getHeader().filetype != MachO::MH_CORE ||
1276 Load.C.cmd != MachO::LC_THREAD || Load.C.cmdsize % 4) {
1277 Err = malformedError("load command " + Twine(I) + " cmdsize not a "
1278 "multiple of 8");
1279 return;
1280 }
1281 }
1282 } else {
1283 if (Load.C.cmdsize % 4 != 0) {
1284 Err = malformedError("load command " + Twine(I) + " cmdsize not a "
1285 "multiple of 4");
1286 return;
1287 }
1288 }
Alexey Samsonov40ec40a2015-06-03 22:19:36 +00001289 LoadCommands.push_back(Load);
Charles Davis55107282013-09-01 04:28:48 +00001290 if (Load.C.cmd == MachO::LC_SYMTAB) {
Lang Hames85334ad2016-12-04 01:56:10 +00001291 if ((Err = checkSymtabCommand(*this, Load, I, &SymtabLoadCmd, Elements)))
David Majnemer4141e002014-11-13 19:48:56 +00001292 return;
Charles Davis55107282013-09-01 04:28:48 +00001293 } else if (Load.C.cmd == MachO::LC_DYSYMTAB) {
Lang Hames85334ad2016-12-04 01:56:10 +00001294 if ((Err = checkDysymtabCommand(*this, Load, I, &DysymtabLoadCmd,
Kevin Enderby4b3270e2016-11-02 21:08:39 +00001295 Elements)))
David Majnemer4141e002014-11-13 19:48:56 +00001296 return;
Charles Davis55107282013-09-01 04:28:48 +00001297 } else if (Load.C.cmd == MachO::LC_DATA_IN_CODE) {
Lang Hames85334ad2016-12-04 01:56:10 +00001298 if ((Err = checkLinkeditDataCommand(*this, Load, I, &DataInCodeLoadCmd,
Kevin Enderby4b3270e2016-11-02 21:08:39 +00001299 "LC_DATA_IN_CODE", Elements,
1300 "data in code info")))
David Majnemer4141e002014-11-13 19:48:56 +00001301 return;
Kevin Enderbya167fe12015-01-27 21:28:24 +00001302 } else if (Load.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
Lang Hames85334ad2016-12-04 01:56:10 +00001303 if ((Err = checkLinkeditDataCommand(*this, Load, I, &LinkOptHintsLoadCmd,
Kevin Enderby4b3270e2016-11-02 21:08:39 +00001304 "LC_LINKER_OPTIMIZATION_HINT",
1305 Elements, "linker optimization "
1306 "hints")))
Kevin Enderbya167fe12015-01-27 21:28:24 +00001307 return;
Kevin Enderby851d92e2016-09-26 21:11:03 +00001308 } else if (Load.C.cmd == MachO::LC_FUNCTION_STARTS) {
Lang Hames85334ad2016-12-04 01:56:10 +00001309 if ((Err = checkLinkeditDataCommand(*this, Load, I, &FuncStartsLoadCmd,
Kevin Enderby4b3270e2016-11-02 21:08:39 +00001310 "LC_FUNCTION_STARTS", Elements,
1311 "function starts data")))
Kevin Enderby851d92e2016-09-26 21:11:03 +00001312 return;
1313 } else if (Load.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO) {
Lang Hames85334ad2016-12-04 01:56:10 +00001314 if ((Err = checkLinkeditDataCommand(*this, Load, I, &SplitInfoLoadCmd,
Kevin Enderby4b3270e2016-11-02 21:08:39 +00001315 "LC_SEGMENT_SPLIT_INFO", Elements,
1316 "split info data")))
Kevin Enderby851d92e2016-09-26 21:11:03 +00001317 return;
1318 } else if (Load.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS) {
Lang Hames85334ad2016-12-04 01:56:10 +00001319 if ((Err = checkLinkeditDataCommand(*this, Load, I, &CodeSignDrsLoadCmd,
Kevin Enderby4b3270e2016-11-02 21:08:39 +00001320 "LC_DYLIB_CODE_SIGN_DRS", Elements,
1321 "code signing RDs data")))
Kevin Enderby851d92e2016-09-26 21:11:03 +00001322 return;
Kevin Enderbyc6b8aca2016-10-18 20:24:12 +00001323 } else if (Load.C.cmd == MachO::LC_CODE_SIGNATURE) {
Lang Hames85334ad2016-12-04 01:56:10 +00001324 if ((Err = checkLinkeditDataCommand(*this, Load, I, &CodeSignLoadCmd,
Kevin Enderby4b3270e2016-11-02 21:08:39 +00001325 "LC_CODE_SIGNATURE", Elements,
1326 "code signature data")))
Kevin Enderbyc6b8aca2016-10-18 20:24:12 +00001327 return;
Kevin Enderby7402add2016-09-13 21:42:28 +00001328 } else if (Load.C.cmd == MachO::LC_DYLD_INFO) {
Lang Hames85334ad2016-12-04 01:56:10 +00001329 if ((Err = checkDyldInfoCommand(*this, Load, I, &DyldInfoLoadCmd,
Kevin Enderby4b3270e2016-11-02 21:08:39 +00001330 "LC_DYLD_INFO", Elements)))
David Majnemer4141e002014-11-13 19:48:56 +00001331 return;
Kevin Enderby7402add2016-09-13 21:42:28 +00001332 } else if (Load.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
Lang Hames85334ad2016-12-04 01:56:10 +00001333 if ((Err = checkDyldInfoCommand(*this, Load, I, &DyldInfoLoadCmd,
Kevin Enderby4b3270e2016-11-02 21:08:39 +00001334 "LC_DYLD_INFO_ONLY", Elements)))
Kevin Enderby7402add2016-09-13 21:42:28 +00001335 return;
Alexander Potapenko4976a532014-10-15 23:35:45 +00001336 } else if (Load.C.cmd == MachO::LC_UUID) {
Kevin Enderbye10e0e32016-09-21 20:03:09 +00001337 if (Load.C.cmdsize != sizeof(MachO::uuid_command)) {
1338 Err = malformedError("LC_UUID command " + Twine(I) + " has incorrect "
1339 "cmdsize");
1340 return;
1341 }
David Majnemer4141e002014-11-13 19:48:56 +00001342 if (UuidLoadCmd) {
Kevin Enderbye10e0e32016-09-21 20:03:09 +00001343 Err = malformedError("more than one LC_UUID command");
David Majnemer4141e002014-11-13 19:48:56 +00001344 return;
1345 }
Alexander Potapenko4976a532014-10-15 23:35:45 +00001346 UuidLoadCmd = Load.Ptr;
Alexey Samsonov468b9042015-06-04 22:08:37 +00001347 } else if (Load.C.cmd == MachO::LC_SEGMENT_64) {
Kevin Enderby296471b2016-08-12 20:10:25 +00001348 if ((Err = parseSegmentLoadCommand<MachO::segment_command_64,
1349 MachO::section_64>(
Lang Hames85334ad2016-12-04 01:56:10 +00001350 *this, Load, Sections, HasPageZeroSegment, I,
Kevin Enderby4b3270e2016-11-02 21:08:39 +00001351 "LC_SEGMENT_64", SizeOfHeaders, Elements)))
Alexey Samsonov54009802015-06-04 20:08:52 +00001352 return;
Alexey Samsonov468b9042015-06-04 22:08:37 +00001353 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
Kevin Enderby296471b2016-08-12 20:10:25 +00001354 if ((Err = parseSegmentLoadCommand<MachO::segment_command,
1355 MachO::section>(
Lang Hames85334ad2016-12-04 01:56:10 +00001356 *this, Load, Sections, HasPageZeroSegment, I,
Kevin Enderby4b3270e2016-11-02 21:08:39 +00001357 "LC_SEGMENT", SizeOfHeaders, Elements)))
Alexey Samsonov54009802015-06-04 20:08:52 +00001358 return;
Kevin Enderby7bcdeca2016-09-20 20:14:14 +00001359 } else if (Load.C.cmd == MachO::LC_ID_DYLIB) {
Lang Hames85334ad2016-12-04 01:56:10 +00001360 if ((Err = checkDylibIdCommand(*this, Load, I, &DyldIdLoadCmd)))
Kevin Enderby7bcdeca2016-09-20 20:14:14 +00001361 return;
1362 } else if (Load.C.cmd == MachO::LC_LOAD_DYLIB) {
Lang Hames85334ad2016-12-04 01:56:10 +00001363 if ((Err = checkDylibCommand(*this, Load, I, "LC_LOAD_DYLIB")))
Kevin Enderby7bcdeca2016-09-20 20:14:14 +00001364 return;
1365 Libraries.push_back(Load.Ptr);
1366 } else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB) {
Lang Hames85334ad2016-12-04 01:56:10 +00001367 if ((Err = checkDylibCommand(*this, Load, I, "LC_LOAD_WEAK_DYLIB")))
Kevin Enderby7bcdeca2016-09-20 20:14:14 +00001368 return;
1369 Libraries.push_back(Load.Ptr);
1370 } else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB) {
Lang Hames85334ad2016-12-04 01:56:10 +00001371 if ((Err = checkDylibCommand(*this, Load, I, "LC_LAZY_LOAD_DYLIB")))
Kevin Enderby7bcdeca2016-09-20 20:14:14 +00001372 return;
1373 Libraries.push_back(Load.Ptr);
1374 } else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB) {
Lang Hames85334ad2016-12-04 01:56:10 +00001375 if ((Err = checkDylibCommand(*this, Load, I, "LC_REEXPORT_DYLIB")))
Kevin Enderby7bcdeca2016-09-20 20:14:14 +00001376 return;
1377 Libraries.push_back(Load.Ptr);
1378 } else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
Lang Hames85334ad2016-12-04 01:56:10 +00001379 if ((Err = checkDylibCommand(*this, Load, I, "LC_LOAD_UPWARD_DYLIB")))
Kevin Enderby7bcdeca2016-09-20 20:14:14 +00001380 return;
Kevin Enderbyecbc7242014-06-05 21:21:57 +00001381 Libraries.push_back(Load.Ptr);
Kevin Enderby4bc0cbd2016-09-27 23:24:13 +00001382 } else if (Load.C.cmd == MachO::LC_ID_DYLINKER) {
Lang Hames85334ad2016-12-04 01:56:10 +00001383 if ((Err = checkDyldCommand(*this, Load, I, "LC_ID_DYLINKER")))
Kevin Enderby4bc0cbd2016-09-27 23:24:13 +00001384 return;
1385 } else if (Load.C.cmd == MachO::LC_LOAD_DYLINKER) {
Lang Hames85334ad2016-12-04 01:56:10 +00001386 if ((Err = checkDyldCommand(*this, Load, I, "LC_LOAD_DYLINKER")))
Kevin Enderby4bc0cbd2016-09-27 23:24:13 +00001387 return;
1388 } else if (Load.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
Lang Hames85334ad2016-12-04 01:56:10 +00001389 if ((Err = checkDyldCommand(*this, Load, I, "LC_DYLD_ENVIRONMENT")))
Kevin Enderby4bc0cbd2016-09-27 23:24:13 +00001390 return;
Kevin Enderbya2d25512016-09-28 21:20:45 +00001391 } else if (Load.C.cmd == MachO::LC_VERSION_MIN_MACOSX) {
Lang Hames85334ad2016-12-04 01:56:10 +00001392 if ((Err = checkVersCommand(*this, Load, I, &VersLoadCmd,
Kevin Enderbya2d25512016-09-28 21:20:45 +00001393 "LC_VERSION_MIN_MACOSX")))
1394 return;
1395 } else if (Load.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS) {
Lang Hames85334ad2016-12-04 01:56:10 +00001396 if ((Err = checkVersCommand(*this, Load, I, &VersLoadCmd,
Kevin Enderbya2d25512016-09-28 21:20:45 +00001397 "LC_VERSION_MIN_IPHONEOS")))
1398 return;
1399 } else if (Load.C.cmd == MachO::LC_VERSION_MIN_TVOS) {
Lang Hames85334ad2016-12-04 01:56:10 +00001400 if ((Err = checkVersCommand(*this, Load, I, &VersLoadCmd,
Kevin Enderbya2d25512016-09-28 21:20:45 +00001401 "LC_VERSION_MIN_TVOS")))
1402 return;
1403 } else if (Load.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
Lang Hames85334ad2016-12-04 01:56:10 +00001404 if ((Err = checkVersCommand(*this, Load, I, &VersLoadCmd,
Kevin Enderbya2d25512016-09-28 21:20:45 +00001405 "LC_VERSION_MIN_WATCHOS")))
1406 return;
Kevin Enderby045015e2017-01-19 17:36:31 +00001407 } else if (Load.C.cmd == MachO::LC_NOTE) {
1408 if ((Err = checkNoteCommand(*this, Load, I, Elements)))
1409 return;
Steven Wu6d5a0272017-01-23 20:07:55 +00001410 } else if (Load.C.cmd == MachO::LC_BUILD_VERSION) {
1411 if ((Err = parseBuildVersionCommand(*this, Load, BuildTools, I)))
1412 return;
Kevin Enderbydda50f22016-09-28 23:16:01 +00001413 } else if (Load.C.cmd == MachO::LC_RPATH) {
Lang Hames85334ad2016-12-04 01:56:10 +00001414 if ((Err = checkRpathCommand(*this, Load, I)))
Kevin Enderbydda50f22016-09-28 23:16:01 +00001415 return;
Kevin Enderby9b04a402016-09-29 17:45:23 +00001416 } else if (Load.C.cmd == MachO::LC_SOURCE_VERSION) {
1417 if (Load.C.cmdsize != sizeof(MachO::source_version_command)) {
1418 Err = malformedError("LC_SOURCE_VERSION command " + Twine(I) +
1419 " has incorrect cmdsize");
1420 return;
1421 }
1422 if (SourceLoadCmd) {
1423 Err = malformedError("more than one LC_SOURCE_VERSION command");
1424 return;
1425 }
1426 SourceLoadCmd = Load.Ptr;
Kevin Enderbyc681bf52016-09-29 21:07:29 +00001427 } else if (Load.C.cmd == MachO::LC_MAIN) {
1428 if (Load.C.cmdsize != sizeof(MachO::entry_point_command)) {
1429 Err = malformedError("LC_MAIN command " + Twine(I) +
1430 " has incorrect cmdsize");
1431 return;
1432 }
1433 if (EntryPointLoadCmd) {
1434 Err = malformedError("more than one LC_MAIN command");
1435 return;
1436 }
1437 EntryPointLoadCmd = Load.Ptr;
Kevin Enderbyec53f4b2016-10-04 20:37:43 +00001438 } else if (Load.C.cmd == MachO::LC_ENCRYPTION_INFO) {
1439 if (Load.C.cmdsize != sizeof(MachO::encryption_info_command)) {
1440 Err = malformedError("LC_ENCRYPTION_INFO command " + Twine(I) +
1441 " has incorrect cmdsize");
1442 return;
1443 }
1444 MachO::encryption_info_command E =
Lang Hames85334ad2016-12-04 01:56:10 +00001445 getStruct<MachO::encryption_info_command>(*this, Load.Ptr);
1446 if ((Err = checkEncryptCommand(*this, Load, I, E.cryptoff, E.cryptsize,
Kevin Enderbyec53f4b2016-10-04 20:37:43 +00001447 &EncryptLoadCmd, "LC_ENCRYPTION_INFO")))
1448 return;
1449 } else if (Load.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
1450 if (Load.C.cmdsize != sizeof(MachO::encryption_info_command_64)) {
1451 Err = malformedError("LC_ENCRYPTION_INFO_64 command " + Twine(I) +
1452 " has incorrect cmdsize");
1453 return;
1454 }
1455 MachO::encryption_info_command_64 E =
Lang Hames85334ad2016-12-04 01:56:10 +00001456 getStruct<MachO::encryption_info_command_64>(*this, Load.Ptr);
1457 if ((Err = checkEncryptCommand(*this, Load, I, E.cryptoff, E.cryptsize,
Kevin Enderbyec53f4b2016-10-04 20:37:43 +00001458 &EncryptLoadCmd, "LC_ENCRYPTION_INFO_64")))
1459 return;
Kevin Enderby9a966692016-10-11 21:04:39 +00001460 } else if (Load.C.cmd == MachO::LC_LINKER_OPTION) {
Lang Hames85334ad2016-12-04 01:56:10 +00001461 if ((Err = checkLinkerOptCommand(*this, Load, I)))
Kevin Enderby9a966692016-10-11 21:04:39 +00001462 return;
Kevin Enderby9296e5f2016-10-17 22:09:25 +00001463 } else if (Load.C.cmd == MachO::LC_SUB_FRAMEWORK) {
1464 if (Load.C.cmdsize < sizeof(MachO::sub_framework_command)) {
1465 Err = malformedError("load command " + Twine(I) +
1466 " LC_SUB_FRAMEWORK cmdsize too small");
1467 return;
1468 }
1469 MachO::sub_framework_command S =
Lang Hames85334ad2016-12-04 01:56:10 +00001470 getStruct<MachO::sub_framework_command>(*this, Load.Ptr);
1471 if ((Err = checkSubCommand(*this, Load, I, "LC_SUB_FRAMEWORK",
Kevin Enderby9296e5f2016-10-17 22:09:25 +00001472 sizeof(MachO::sub_framework_command),
1473 "sub_framework_command", S.umbrella,
1474 "umbrella")))
1475 return;
1476 } else if (Load.C.cmd == MachO::LC_SUB_UMBRELLA) {
1477 if (Load.C.cmdsize < sizeof(MachO::sub_umbrella_command)) {
1478 Err = malformedError("load command " + Twine(I) +
1479 " LC_SUB_UMBRELLA cmdsize too small");
1480 return;
1481 }
1482 MachO::sub_umbrella_command S =
Lang Hames85334ad2016-12-04 01:56:10 +00001483 getStruct<MachO::sub_umbrella_command>(*this, Load.Ptr);
1484 if ((Err = checkSubCommand(*this, Load, I, "LC_SUB_UMBRELLA",
Kevin Enderby9296e5f2016-10-17 22:09:25 +00001485 sizeof(MachO::sub_umbrella_command),
1486 "sub_umbrella_command", S.sub_umbrella,
1487 "sub_umbrella")))
1488 return;
1489 } else if (Load.C.cmd == MachO::LC_SUB_LIBRARY) {
1490 if (Load.C.cmdsize < sizeof(MachO::sub_library_command)) {
1491 Err = malformedError("load command " + Twine(I) +
1492 " LC_SUB_LIBRARY cmdsize too small");
1493 return;
1494 }
1495 MachO::sub_library_command S =
Lang Hames85334ad2016-12-04 01:56:10 +00001496 getStruct<MachO::sub_library_command>(*this, Load.Ptr);
1497 if ((Err = checkSubCommand(*this, Load, I, "LC_SUB_LIBRARY",
Kevin Enderby9296e5f2016-10-17 22:09:25 +00001498 sizeof(MachO::sub_library_command),
1499 "sub_library_command", S.sub_library,
1500 "sub_library")))
1501 return;
1502 } else if (Load.C.cmd == MachO::LC_SUB_CLIENT) {
1503 if (Load.C.cmdsize < sizeof(MachO::sub_client_command)) {
1504 Err = malformedError("load command " + Twine(I) +
1505 " LC_SUB_CLIENT cmdsize too small");
1506 return;
1507 }
1508 MachO::sub_client_command S =
Lang Hames85334ad2016-12-04 01:56:10 +00001509 getStruct<MachO::sub_client_command>(*this, Load.Ptr);
1510 if ((Err = checkSubCommand(*this, Load, I, "LC_SUB_CLIENT",
Kevin Enderby9296e5f2016-10-17 22:09:25 +00001511 sizeof(MachO::sub_client_command),
1512 "sub_client_command", S.client, "client")))
1513 return;
Kevin Enderby640265d2016-10-18 17:54:17 +00001514 } else if (Load.C.cmd == MachO::LC_ROUTINES) {
1515 if (Load.C.cmdsize != sizeof(MachO::routines_command)) {
1516 Err = malformedError("LC_ROUTINES command " + Twine(I) +
1517 " has incorrect cmdsize");
1518 return;
1519 }
1520 if (RoutinesLoadCmd) {
1521 Err = malformedError("more than one LC_ROUTINES and or LC_ROUTINES_64 "
1522 "command");
1523 return;
1524 }
1525 RoutinesLoadCmd = Load.Ptr;
1526 } else if (Load.C.cmd == MachO::LC_ROUTINES_64) {
1527 if (Load.C.cmdsize != sizeof(MachO::routines_command_64)) {
1528 Err = malformedError("LC_ROUTINES_64 command " + Twine(I) +
1529 " has incorrect cmdsize");
1530 return;
1531 }
1532 if (RoutinesLoadCmd) {
1533 Err = malformedError("more than one LC_ROUTINES_64 and or LC_ROUTINES "
1534 "command");
1535 return;
1536 }
1537 RoutinesLoadCmd = Load.Ptr;
Kevin Enderby04e33072016-10-19 23:44:34 +00001538 } else if (Load.C.cmd == MachO::LC_UNIXTHREAD) {
Lang Hames85334ad2016-12-04 01:56:10 +00001539 if ((Err = checkThreadCommand(*this, Load, I, "LC_UNIXTHREAD")))
Kevin Enderby04e33072016-10-19 23:44:34 +00001540 return;
1541 if (UnixThreadLoadCmd) {
1542 Err = malformedError("more than one LC_UNIXTHREAD command");
1543 return;
1544 }
1545 UnixThreadLoadCmd = Load.Ptr;
1546 } else if (Load.C.cmd == MachO::LC_THREAD) {
Lang Hames85334ad2016-12-04 01:56:10 +00001547 if ((Err = checkThreadCommand(*this, Load, I, "LC_THREAD")))
Kevin Enderby04e33072016-10-19 23:44:34 +00001548 return;
Kevin Enderby60923f32016-10-27 20:59:10 +00001549 // Note: LC_TWOLEVEL_HINTS is really obsolete and is not supported.
Kevin Enderbyd6842a62016-10-20 20:10:30 +00001550 } else if (Load.C.cmd == MachO::LC_TWOLEVEL_HINTS) {
Lang Hames85334ad2016-12-04 01:56:10 +00001551 if ((Err = checkTwoLevelHintsCommand(*this, Load, I,
Kevin Enderby4b3270e2016-11-02 21:08:39 +00001552 &TwoLevelHintsLoadCmd, Elements)))
Kevin Enderbyd6842a62016-10-20 20:10:30 +00001553 return;
Kevin Enderby60923f32016-10-27 20:59:10 +00001554 } else if (isLoadCommandObsolete(Load.C.cmd)) {
1555 Err = malformedError("load command " + Twine(I) + " for cmd value of: " +
1556 Twine(Load.C.cmd) + " is obsolete and not "
1557 "supported");
1558 return;
Rafael Espindolafd7aa382013-04-18 18:08:55 +00001559 }
Kevin Enderby60923f32016-10-27 20:59:10 +00001560 // TODO: generate a error for unknown load commands by default. But still
1561 // need work out an approach to allow or not allow unknown values like this
1562 // as an option for some uses like lldb.
Alexey Samsonov7e699dc2015-06-04 19:57:46 +00001563 if (I < LoadCommandCount - 1) {
Lang Hames85334ad2016-12-04 01:56:10 +00001564 if (auto LoadOrErr = getNextLoadCommandInfo(*this, I, Load))
Lang Hames3e222972016-03-25 17:25:34 +00001565 Load = *LoadOrErr;
1566 else {
1567 Err = LoadOrErr.takeError();
Alexey Samsonov7e699dc2015-06-04 19:57:46 +00001568 return;
1569 }
Alexey Samsonov7e699dc2015-06-04 19:57:46 +00001570 }
Rafael Espindolafd7aa382013-04-18 18:08:55 +00001571 }
Kevin Enderby5479bf72016-01-22 22:49:55 +00001572 if (!SymtabLoadCmd) {
1573 if (DysymtabLoadCmd) {
Kevin Enderbyeaa1f082016-05-06 20:16:28 +00001574 Err = malformedError("contains LC_DYSYMTAB load command without a "
Kevin Enderbyba3a53c2016-05-05 23:41:05 +00001575 "LC_SYMTAB load command");
Kevin Enderby5479bf72016-01-22 22:49:55 +00001576 return;
1577 }
1578 } else if (DysymtabLoadCmd) {
1579 MachO::symtab_command Symtab =
Lang Hames85334ad2016-12-04 01:56:10 +00001580 getStruct<MachO::symtab_command>(*this, SymtabLoadCmd);
Kevin Enderby5479bf72016-01-22 22:49:55 +00001581 MachO::dysymtab_command Dysymtab =
Lang Hames85334ad2016-12-04 01:56:10 +00001582 getStruct<MachO::dysymtab_command>(*this, DysymtabLoadCmd);
Kevin Enderby5479bf72016-01-22 22:49:55 +00001583 if (Dysymtab.nlocalsym != 0 && Dysymtab.ilocalsym > Symtab.nsyms) {
Kevin Enderbyeaa1f082016-05-06 20:16:28 +00001584 Err = malformedError("ilocalsym in LC_DYSYMTAB load command "
Kevin Enderbyba3a53c2016-05-05 23:41:05 +00001585 "extends past the end of the symbol table");
Kevin Enderby5479bf72016-01-22 22:49:55 +00001586 return;
1587 }
Kevin Enderbyc7e7d322016-04-21 20:29:49 +00001588 uint64_t BigSize = Dysymtab.ilocalsym;
1589 BigSize += Dysymtab.nlocalsym;
1590 if (Dysymtab.nlocalsym != 0 && BigSize > Symtab.nsyms) {
Kevin Enderbyeaa1f082016-05-06 20:16:28 +00001591 Err = malformedError("ilocalsym plus nlocalsym in LC_DYSYMTAB load "
Kevin Enderbyba3a53c2016-05-05 23:41:05 +00001592 "command extends past the end of the symbol table");
Kevin Enderby5479bf72016-01-22 22:49:55 +00001593 return;
1594 }
Francis Visoiu Mistrihe6cfed92018-09-04 16:31:48 +00001595 if (Dysymtab.nextdefsym != 0 && Dysymtab.iextdefsym > Symtab.nsyms) {
Francis Visoiu Mistrihfe2c6872018-09-04 16:31:53 +00001596 Err = malformedError("iextdefsym in LC_DYSYMTAB load command "
Kevin Enderbyba3a53c2016-05-05 23:41:05 +00001597 "extends past the end of the symbol table");
Kevin Enderby5479bf72016-01-22 22:49:55 +00001598 return;
1599 }
Kevin Enderbyc7e7d322016-04-21 20:29:49 +00001600 BigSize = Dysymtab.iextdefsym;
1601 BigSize += Dysymtab.nextdefsym;
1602 if (Dysymtab.nextdefsym != 0 && BigSize > Symtab.nsyms) {
Kevin Enderbyeaa1f082016-05-06 20:16:28 +00001603 Err = malformedError("iextdefsym plus nextdefsym in LC_DYSYMTAB "
Kevin Enderbyba3a53c2016-05-05 23:41:05 +00001604 "load command extends past the end of the symbol "
1605 "table");
Kevin Enderby5479bf72016-01-22 22:49:55 +00001606 return;
1607 }
1608 if (Dysymtab.nundefsym != 0 && Dysymtab.iundefsym > Symtab.nsyms) {
Francis Visoiu Mistrihfe2c6872018-09-04 16:31:53 +00001609 Err = malformedError("iundefsym in LC_DYSYMTAB load command "
Kevin Enderbyba3a53c2016-05-05 23:41:05 +00001610 "extends past the end of the symbol table");
Kevin Enderby5479bf72016-01-22 22:49:55 +00001611 return;
1612 }
Kevin Enderbyc7e7d322016-04-21 20:29:49 +00001613 BigSize = Dysymtab.iundefsym;
1614 BigSize += Dysymtab.nundefsym;
1615 if (Dysymtab.nundefsym != 0 && BigSize > Symtab.nsyms) {
Kevin Enderbyeaa1f082016-05-06 20:16:28 +00001616 Err = malformedError("iundefsym plus nundefsym in LC_DYSYMTAB load "
Kevin Enderbyba3a53c2016-05-05 23:41:05 +00001617 " command extends past the end of the symbol table");
Kevin Enderby5479bf72016-01-22 22:49:55 +00001618 return;
1619 }
1620 }
Kevin Enderby7bcdeca2016-09-20 20:14:14 +00001621 if ((getHeader().filetype == MachO::MH_DYLIB ||
1622 getHeader().filetype == MachO::MH_DYLIB_STUB) &&
1623 DyldIdLoadCmd == nullptr) {
1624 Err = malformedError("no LC_ID_DYLIB load command in dynamic library "
1625 "filetype");
1626 return;
1627 }
Alexey Samsonov40ec40a2015-06-03 22:19:36 +00001628 assert(LoadCommands.size() == LoadCommandCount);
Lang Hames3e222972016-03-25 17:25:34 +00001629
1630 Err = Error::success();
Rafael Espindolafd7aa382013-04-18 18:08:55 +00001631}
1632
Kevin Enderby34a869c2016-11-14 20:57:04 +00001633Error MachOObjectFile::checkSymbolTable() const {
1634 uint32_t Flags = 0;
1635 if (is64Bit()) {
1636 MachO::mach_header_64 H_64 = MachOObjectFile::getHeader64();
1637 Flags = H_64.flags;
1638 } else {
1639 MachO::mach_header H = MachOObjectFile::getHeader();
1640 Flags = H.flags;
1641 }
1642 uint8_t NType = 0;
1643 uint8_t NSect = 0;
1644 uint16_t NDesc = 0;
1645 uint32_t NStrx = 0;
1646 uint64_t NValue = 0;
1647 uint32_t SymbolIndex = 0;
1648 MachO::symtab_command S = getSymtabLoadCommand();
1649 for (const SymbolRef &Symbol : symbols()) {
1650 DataRefImpl SymDRI = Symbol.getRawDataRefImpl();
1651 if (is64Bit()) {
1652 MachO::nlist_64 STE_64 = getSymbol64TableEntry(SymDRI);
1653 NType = STE_64.n_type;
1654 NSect = STE_64.n_sect;
1655 NDesc = STE_64.n_desc;
1656 NStrx = STE_64.n_strx;
1657 NValue = STE_64.n_value;
1658 } else {
1659 MachO::nlist STE = getSymbolTableEntry(SymDRI);
1660 NType = STE.n_type;
1661 NType = STE.n_type;
1662 NSect = STE.n_sect;
1663 NDesc = STE.n_desc;
1664 NStrx = STE.n_strx;
1665 NValue = STE.n_value;
1666 }
1667 if ((NType & MachO::N_STAB) == 0 &&
1668 (NType & MachO::N_TYPE) == MachO::N_SECT) {
1669 if (NSect == 0 || NSect > Sections.size())
1670 return malformedError("bad section index: " + Twine((int)NSect) +
1671 " for symbol at index " + Twine(SymbolIndex));
1672 }
1673 if ((NType & MachO::N_STAB) == 0 &&
1674 (NType & MachO::N_TYPE) == MachO::N_INDR) {
1675 if (NValue >= S.strsize)
1676 return malformedError("bad n_value: " + Twine((int)NValue) + " past "
1677 "the end of string table, for N_INDR symbol at "
1678 "index " + Twine(SymbolIndex));
1679 }
1680 if ((Flags & MachO::MH_TWOLEVEL) == MachO::MH_TWOLEVEL &&
1681 (((NType & MachO::N_TYPE) == MachO::N_UNDF && NValue == 0) ||
1682 (NType & MachO::N_TYPE) == MachO::N_PBUD)) {
1683 uint32_t LibraryOrdinal = MachO::GET_LIBRARY_ORDINAL(NDesc);
1684 if (LibraryOrdinal != 0 &&
1685 LibraryOrdinal != MachO::EXECUTABLE_ORDINAL &&
1686 LibraryOrdinal != MachO::DYNAMIC_LOOKUP_ORDINAL &&
1687 LibraryOrdinal - 1 >= Libraries.size() ) {
1688 return malformedError("bad library ordinal: " + Twine(LibraryOrdinal) +
1689 " for symbol at index " + Twine(SymbolIndex));
1690 }
1691 }
1692 if (NStrx >= S.strsize)
1693 return malformedError("bad string table index: " + Twine((int)NStrx) +
1694 " past the end of string table, for symbol at "
1695 "index " + Twine(SymbolIndex));
1696 SymbolIndex++;
1697 }
1698 return Error::success();
1699}
1700
Rafael Espindolaefdbec82014-01-30 02:49:50 +00001701void MachOObjectFile::moveSymbolNext(DataRefImpl &Symb) const {
Rafael Espindola802fe932013-04-24 19:47:55 +00001702 unsigned SymbolTableEntrySize = is64Bit() ?
Charles Davis55107282013-09-01 04:28:48 +00001703 sizeof(MachO::nlist_64) :
1704 sizeof(MachO::nlist);
Rafael Espindola802fe932013-04-24 19:47:55 +00001705 Symb.p += SymbolTableEntrySize;
Rafael Espindolafd7aa382013-04-18 18:08:55 +00001706}
1707
Kevin Enderby813e0cf2016-04-20 21:24:34 +00001708Expected<StringRef> MachOObjectFile::getSymbolName(DataRefImpl Symb) const {
Rafael Espindola2173e182013-04-26 20:07:33 +00001709 StringRef StringTable = getStringTableData();
Lang Hames85334ad2016-12-04 01:56:10 +00001710 MachO::nlist_base Entry = getSymbolTableEntryBase(*this, Symb);
Michael Trentcb27e1d2018-01-03 23:28:32 +00001711 if (Entry.n_strx == 0)
1712 // A n_strx value of 0 indicates that no name is associated with a
1713 // particular symbol table entry.
1714 return StringRef();
Charles Davis55107282013-09-01 04:28:48 +00001715 const char *Start = &StringTable.data()[Entry.n_strx];
Kevin Enderby813e0cf2016-04-20 21:24:34 +00001716 if (Start < getData().begin() || Start >= getData().end()) {
Kevin Enderbyeaa1f082016-05-06 20:16:28 +00001717 return malformedError("bad string index: " + Twine(Entry.n_strx) +
Kevin Enderbyba3a53c2016-05-05 23:41:05 +00001718 " for symbol at index " + Twine(getSymbolIndex(Symb)));
Kevin Enderby813e0cf2016-04-20 21:24:34 +00001719 }
Rafael Espindola8a806412015-07-02 20:55:21 +00001720 return StringRef(Start);
Rafael Espindolafd7aa382013-04-18 18:08:55 +00001721}
1722
Rafael Espindolac0e33402014-12-10 20:46:55 +00001723unsigned MachOObjectFile::getSectionType(SectionRef Sec) const {
1724 DataRefImpl DRI = Sec.getRawDataRefImpl();
Lang Hames85334ad2016-12-04 01:56:10 +00001725 uint32_t Flags = getSectionFlags(*this, DRI);
Rafael Espindolac0e33402014-12-10 20:46:55 +00001726 return Flags & MachO::SECTION_TYPE;
1727}
1728
Rafael Espindola262e9482015-06-24 18:14:41 +00001729uint64_t MachOObjectFile::getNValue(DataRefImpl Sym) const {
1730 if (is64Bit()) {
1731 MachO::nlist_64 Entry = getSymbol64TableEntry(Sym);
1732 return Entry.n_value;
1733 }
1734 MachO::nlist Entry = getSymbolTableEntry(Sym);
1735 return Entry.n_value;
1736}
1737
Kevin Enderbyecbc7242014-06-05 21:21:57 +00001738// getIndirectName() returns the name of the alias'ed symbol who's string table
1739// index is in the n_value field.
Rafael Espindola5c792fa2014-06-12 21:46:39 +00001740std::error_code MachOObjectFile::getIndirectName(DataRefImpl Symb,
1741 StringRef &Res) const {
Kevin Enderbyecbc7242014-06-05 21:21:57 +00001742 StringRef StringTable = getStringTableData();
Lang Hames85334ad2016-12-04 01:56:10 +00001743 MachO::nlist_base Entry = getSymbolTableEntryBase(*this, Symb);
Rafael Espindola262e9482015-06-24 18:14:41 +00001744 if ((Entry.n_type & MachO::N_TYPE) != MachO::N_INDR)
1745 return object_error::parse_failed;
1746 uint64_t NValue = getNValue(Symb);
Kevin Enderbyecbc7242014-06-05 21:21:57 +00001747 if (NValue >= StringTable.size())
1748 return object_error::parse_failed;
1749 const char *Start = &StringTable.data()[NValue];
1750 Res = StringRef(Start);
Rui Ueyamaeae46732015-06-09 15:20:42 +00001751 return std::error_code();
Kevin Enderbyecbc7242014-06-05 21:21:57 +00001752}
1753
Rafael Espindola7b7c81c2015-07-07 17:12:59 +00001754uint64_t MachOObjectFile::getSymbolValueImpl(DataRefImpl Sym) const {
Rafael Espindola9ca3a032015-07-07 15:05:09 +00001755 return getNValue(Sym);
Rafael Espindola9fa0ab32015-06-24 19:11:10 +00001756}
1757
Kevin Enderby317de7c2016-06-24 18:24:42 +00001758Expected<uint64_t> MachOObjectFile::getSymbolAddress(DataRefImpl Sym) const {
Rafael Espindola5954faa2015-07-03 18:19:00 +00001759 return getSymbolValue(Sym);
Rafael Espindolafd7aa382013-04-18 18:08:55 +00001760}
1761
Rafael Espindola64afb832015-05-31 23:52:50 +00001762uint32_t MachOObjectFile::getSymbolAlignment(DataRefImpl DRI) const {
Rafael Espindolad8324e62014-01-31 20:57:12 +00001763 uint32_t flags = getSymbolFlags(DRI);
Rafael Espindola59a0e792013-04-29 22:24:22 +00001764 if (flags & SymbolRef::SF_Common) {
Lang Hames85334ad2016-12-04 01:56:10 +00001765 MachO::nlist_base Entry = getSymbolTableEntryBase(*this, DRI);
Rafael Espindola64afb832015-05-31 23:52:50 +00001766 return 1 << MachO::GET_COMM_ALIGN(Entry.n_desc);
Rafael Espindola59a0e792013-04-29 22:24:22 +00001767 }
Rafael Espindola64afb832015-05-31 23:52:50 +00001768 return 0;
Rafael Espindola59a0e792013-04-29 22:24:22 +00001769}
1770
Rafael Espindola821b06f2015-06-24 10:20:30 +00001771uint64_t MachOObjectFile::getCommonSymbolSizeImpl(DataRefImpl DRI) const {
Rafael Espindola6b24d0a2015-07-07 13:58:32 +00001772 return getNValue(DRI);
Rafael Espindolafd7aa382013-04-18 18:08:55 +00001773}
1774
Kevin Enderbya486dca2016-05-02 20:28:12 +00001775Expected<SymbolRef::Type>
Kevin Enderby46e35ed2016-03-23 20:27:00 +00001776MachOObjectFile::getSymbolType(DataRefImpl Symb) const {
Lang Hames85334ad2016-12-04 01:56:10 +00001777 MachO::nlist_base Entry = getSymbolTableEntryBase(*this, Symb);
Charles Davis55107282013-09-01 04:28:48 +00001778 uint8_t n_type = Entry.n_type;
Rafael Espindolafd7aa382013-04-18 18:08:55 +00001779
Rafael Espindolafd7aa382013-04-18 18:08:55 +00001780 // If this is a STAB debugging symbol, we can do nothing more.
Rafael Espindola50bea402015-06-26 12:18:49 +00001781 if (n_type & MachO::N_STAB)
1782 return SymbolRef::ST_Debug;
Rafael Espindolafd7aa382013-04-18 18:08:55 +00001783
Charles Davisbf778d02013-08-27 05:00:13 +00001784 switch (n_type & MachO::N_TYPE) {
1785 case MachO::N_UNDF :
Rafael Espindola50bea402015-06-26 12:18:49 +00001786 return SymbolRef::ST_Unknown;
Charles Davisbf778d02013-08-27 05:00:13 +00001787 case MachO::N_SECT :
Kevin Enderbya486dca2016-05-02 20:28:12 +00001788 Expected<section_iterator> SecOrError = getSymbolSection(Symb);
Kevin Enderby46e35ed2016-03-23 20:27:00 +00001789 if (!SecOrError)
Kevin Enderbya486dca2016-05-02 20:28:12 +00001790 return SecOrError.takeError();
Kevin Enderby46e35ed2016-03-23 20:27:00 +00001791 section_iterator Sec = *SecOrError;
Kuba Brecka4e0567a2015-11-12 09:40:29 +00001792 if (Sec->isData() || Sec->isBSS())
1793 return SymbolRef::ST_Data;
Rafael Espindola50bea402015-06-26 12:18:49 +00001794 return SymbolRef::ST_Function;
Rafael Espindolafd7aa382013-04-18 18:08:55 +00001795 }
Rafael Espindola50bea402015-06-26 12:18:49 +00001796 return SymbolRef::ST_Other;
Rafael Espindolafd7aa382013-04-18 18:08:55 +00001797}
1798
Rafael Espindolad8324e62014-01-31 20:57:12 +00001799uint32_t MachOObjectFile::getSymbolFlags(DataRefImpl DRI) const {
Lang Hames85334ad2016-12-04 01:56:10 +00001800 MachO::nlist_base Entry = getSymbolTableEntryBase(*this, DRI);
Rafael Espindolafd7aa382013-04-18 18:08:55 +00001801
Charles Davis55107282013-09-01 04:28:48 +00001802 uint8_t MachOType = Entry.n_type;
1803 uint16_t MachOFlags = Entry.n_desc;
Rafael Espindolafd7aa382013-04-18 18:08:55 +00001804
Rafael Espindolad8324e62014-01-31 20:57:12 +00001805 uint32_t Result = SymbolRef::SF_None;
Rafael Espindolafd7aa382013-04-18 18:08:55 +00001806
Tim Northover98f8bc92014-05-30 13:22:59 +00001807 if ((MachOType & MachO::N_TYPE) == MachO::N_INDR)
1808 Result |= SymbolRef::SF_Indirect;
1809
Rafael Espindola6152f7d2013-11-02 05:03:24 +00001810 if (MachOType & MachO::N_STAB)
Rafael Espindolafd7aa382013-04-18 18:08:55 +00001811 Result |= SymbolRef::SF_FormatSpecific;
1812
Charles Davisbf778d02013-08-27 05:00:13 +00001813 if (MachOType & MachO::N_EXT) {
Rafael Espindolafd7aa382013-04-18 18:08:55 +00001814 Result |= SymbolRef::SF_Global;
Charles Davisbf778d02013-08-27 05:00:13 +00001815 if ((MachOType & MachO::N_TYPE) == MachO::N_UNDF) {
Rafael Espindola6b24d0a2015-07-07 13:58:32 +00001816 if (getNValue(DRI))
Rafael Espindola59a0e792013-04-29 22:24:22 +00001817 Result |= SymbolRef::SF_Common;
Rafael Espindola8b3aaab2015-07-07 14:26:39 +00001818 else
1819 Result |= SymbolRef::SF_Undefined;
Rafael Espindola59a0e792013-04-29 22:24:22 +00001820 }
Lang Hames07e3f812015-01-15 22:33:30 +00001821
1822 if (!(MachOType & MachO::N_PEXT))
1823 Result |= SymbolRef::SF_Exported;
Rafael Espindolafd7aa382013-04-18 18:08:55 +00001824 }
1825
Charles Davisbf778d02013-08-27 05:00:13 +00001826 if (MachOFlags & (MachO::N_WEAK_REF | MachO::N_WEAK_DEF))
Rafael Espindolafd7aa382013-04-18 18:08:55 +00001827 Result |= SymbolRef::SF_Weak;
1828
Kevin Enderbyf7590322014-08-18 20:21:02 +00001829 if (MachOFlags & (MachO::N_ARM_THUMB_DEF))
1830 Result |= SymbolRef::SF_Thumb;
1831
Charles Davisbf778d02013-08-27 05:00:13 +00001832 if ((MachOType & MachO::N_TYPE) == MachO::N_ABS)
Rafael Espindolafd7aa382013-04-18 18:08:55 +00001833 Result |= SymbolRef::SF_Absolute;
1834
Rafael Espindolad8324e62014-01-31 20:57:12 +00001835 return Result;
Rafael Espindolafd7aa382013-04-18 18:08:55 +00001836}
1837
Kevin Enderbya486dca2016-05-02 20:28:12 +00001838Expected<section_iterator>
Rafael Espindolae84d8c12015-08-07 23:27:14 +00001839MachOObjectFile::getSymbolSection(DataRefImpl Symb) const {
Lang Hames85334ad2016-12-04 01:56:10 +00001840 MachO::nlist_base Entry = getSymbolTableEntryBase(*this, Symb);
Charles Davis55107282013-09-01 04:28:48 +00001841 uint8_t index = Entry.n_sect;
Rafael Espindolafd7aa382013-04-18 18:08:55 +00001842
Rafael Espindolae84d8c12015-08-07 23:27:14 +00001843 if (index == 0)
1844 return section_end();
1845 DataRefImpl DRI;
1846 DRI.d.a = index - 1;
Kevin Enderby46e35ed2016-03-23 20:27:00 +00001847 if (DRI.d.a >= Sections.size()){
Kevin Enderbyeaa1f082016-05-06 20:16:28 +00001848 return malformedError("bad section index: " + Twine((int)index) +
Kevin Enderbyba3a53c2016-05-05 23:41:05 +00001849 " for symbol at index " + Twine(getSymbolIndex(Symb)));
Kevin Enderby46e35ed2016-03-23 20:27:00 +00001850 }
Rafael Espindolae84d8c12015-08-07 23:27:14 +00001851 return section_iterator(SectionRef(DRI, this));
Rafael Espindolafd7aa382013-04-18 18:08:55 +00001852}
1853
Rafael Espindolaa3af3472015-06-24 19:57:32 +00001854unsigned MachOObjectFile::getSymbolSectionID(SymbolRef Sym) const {
1855 MachO::nlist_base Entry =
Lang Hames85334ad2016-12-04 01:56:10 +00001856 getSymbolTableEntryBase(*this, Sym.getRawDataRefImpl());
Rafael Espindolaa3af3472015-06-24 19:57:32 +00001857 return Entry.n_sect - 1;
1858}
1859
Rafael Espindolaefdbec82014-01-30 02:49:50 +00001860void MachOObjectFile::moveSectionNext(DataRefImpl &Sec) const {
Rafael Espindolafd7aa382013-04-18 18:08:55 +00001861 Sec.d.a++;
Rafael Espindolafd7aa382013-04-18 18:08:55 +00001862}
1863
Rafael Espindola5c792fa2014-06-12 21:46:39 +00001864std::error_code MachOObjectFile::getSectionName(DataRefImpl Sec,
1865 StringRef &Result) const {
Rafael Espindolafd7aa382013-04-18 18:08:55 +00001866 ArrayRef<char> Raw = getSectionRawName(Sec);
1867 Result = parseSegmentOrSectionName(Raw.data());
Rui Ueyamaeae46732015-06-09 15:20:42 +00001868 return std::error_code();
Rafael Espindolafd7aa382013-04-18 18:08:55 +00001869}
1870
Rafael Espindola8175be52014-10-08 15:28:58 +00001871uint64_t MachOObjectFile::getSectionAddress(DataRefImpl Sec) const {
1872 if (is64Bit())
1873 return getSection64(Sec).addr;
1874 return getSection(Sec).addr;
Rafael Espindolafd7aa382013-04-18 18:08:55 +00001875}
1876
George Rimarb5ac7002017-05-27 18:10:23 +00001877uint64_t MachOObjectFile::getSectionIndex(DataRefImpl Sec) const {
1878 return Sec.d.a;
1879}
1880
Rafael Espindola8175be52014-10-08 15:28:58 +00001881uint64_t MachOObjectFile::getSectionSize(DataRefImpl Sec) const {
Kevin Enderby1ef3c282015-10-08 22:50:55 +00001882 // In the case if a malformed Mach-O file where the section offset is past
1883 // the end of the file or some part of the section size is past the end of
1884 // the file return a size of zero or a size that covers the rest of the file
1885 // but does not extend past the end of the file.
1886 uint32_t SectOffset, SectType;
1887 uint64_t SectSize;
1888
1889 if (is64Bit()) {
1890 MachO::section_64 Sect = getSection64(Sec);
1891 SectOffset = Sect.offset;
1892 SectSize = Sect.size;
1893 SectType = Sect.flags & MachO::SECTION_TYPE;
1894 } else {
1895 MachO::section Sect = getSection(Sec);
1896 SectOffset = Sect.offset;
1897 SectSize = Sect.size;
1898 SectType = Sect.flags & MachO::SECTION_TYPE;
1899 }
1900 if (SectType == MachO::S_ZEROFILL || SectType == MachO::S_GB_ZEROFILL)
1901 return SectSize;
1902 uint64_t FileSize = getData().size();
1903 if (SectOffset > FileSize)
1904 return 0;
1905 if (FileSize - SectOffset < SectSize)
1906 return FileSize - SectOffset;
1907 return SectSize;
Rafael Espindolafd7aa382013-04-18 18:08:55 +00001908}
1909
Rafael Espindola5c792fa2014-06-12 21:46:39 +00001910std::error_code MachOObjectFile::getSectionContents(DataRefImpl Sec,
1911 StringRef &Res) const {
Rafael Espindolafd7aa382013-04-18 18:08:55 +00001912 uint32_t Offset;
1913 uint64_t Size;
1914
1915 if (is64Bit()) {
Charles Davis55107282013-09-01 04:28:48 +00001916 MachO::section_64 Sect = getSection64(Sec);
1917 Offset = Sect.offset;
1918 Size = Sect.size;
Rafael Espindolafd7aa382013-04-18 18:08:55 +00001919 } else {
Charles Davis55107282013-09-01 04:28:48 +00001920 MachO::section Sect = getSection(Sec);
1921 Offset = Sect.offset;
1922 Size = Sect.size;
Rafael Espindolafd7aa382013-04-18 18:08:55 +00001923 }
1924
1925 Res = this->getData().substr(Offset, Size);
Rui Ueyamaeae46732015-06-09 15:20:42 +00001926 return std::error_code();
Rafael Espindolafd7aa382013-04-18 18:08:55 +00001927}
1928
Rafael Espindola8175be52014-10-08 15:28:58 +00001929uint64_t MachOObjectFile::getSectionAlignment(DataRefImpl Sec) const {
Rafael Espindolafd7aa382013-04-18 18:08:55 +00001930 uint32_t Align;
1931 if (is64Bit()) {
Charles Davis55107282013-09-01 04:28:48 +00001932 MachO::section_64 Sect = getSection64(Sec);
1933 Align = Sect.align;
Rafael Espindolafd7aa382013-04-18 18:08:55 +00001934 } else {
Charles Davis55107282013-09-01 04:28:48 +00001935 MachO::section Sect = getSection(Sec);
1936 Align = Sect.align;
Rafael Espindolafd7aa382013-04-18 18:08:55 +00001937 }
1938
Rafael Espindola8175be52014-10-08 15:28:58 +00001939 return uint64_t(1) << Align;
Rafael Espindolafd7aa382013-04-18 18:08:55 +00001940}
1941
Paul Semel94b09402018-07-11 10:00:29 +00001942Expected<SectionRef> MachOObjectFile::getSection(unsigned SectionIndex) const {
1943 if (SectionIndex < 1 || SectionIndex > Sections.size())
1944 return malformedError("bad section index: " + Twine((int)SectionIndex));
1945
1946 DataRefImpl DRI;
1947 DRI.d.a = SectionIndex - 1;
1948 return SectionRef(DRI, this);
1949}
1950
1951Expected<SectionRef> MachOObjectFile::getSection(StringRef SectionName) const {
1952 StringRef SecName;
1953 for (const SectionRef &Section : sections()) {
1954 if (std::error_code E = Section.getName(SecName))
1955 return errorCodeToError(E);
1956 if (SecName == SectionName) {
1957 return Section;
1958 }
1959 }
1960 return errorCodeToError(object_error::parse_failed);
1961}
1962
George Rimar5ad80b22016-05-24 12:48:46 +00001963bool MachOObjectFile::isSectionCompressed(DataRefImpl Sec) const {
1964 return false;
1965}
1966
Rafael Espindola8175be52014-10-08 15:28:58 +00001967bool MachOObjectFile::isSectionText(DataRefImpl Sec) const {
Lang Hames85334ad2016-12-04 01:56:10 +00001968 uint32_t Flags = getSectionFlags(*this, Sec);
Rafael Espindola8175be52014-10-08 15:28:58 +00001969 return Flags & MachO::S_ATTR_PURE_INSTRUCTIONS;
Rafael Espindolafd7aa382013-04-18 18:08:55 +00001970}
1971
Rafael Espindola8175be52014-10-08 15:28:58 +00001972bool MachOObjectFile::isSectionData(DataRefImpl Sec) const {
Lang Hames85334ad2016-12-04 01:56:10 +00001973 uint32_t Flags = getSectionFlags(*this, Sec);
Kevin Enderby86ad7b72014-05-19 20:36:02 +00001974 unsigned SectionType = Flags & MachO::SECTION_TYPE;
Rafael Espindola8175be52014-10-08 15:28:58 +00001975 return !(Flags & MachO::S_ATTR_PURE_INSTRUCTIONS) &&
1976 !(SectionType == MachO::S_ZEROFILL ||
1977 SectionType == MachO::S_GB_ZEROFILL);
Michael J. Spencer13afc5e2011-09-28 20:57:30 +00001978}
1979
Rafael Espindola8175be52014-10-08 15:28:58 +00001980bool MachOObjectFile::isSectionBSS(DataRefImpl Sec) const {
Lang Hames85334ad2016-12-04 01:56:10 +00001981 uint32_t Flags = getSectionFlags(*this, Sec);
Kevin Enderby86ad7b72014-05-19 20:36:02 +00001982 unsigned SectionType = Flags & MachO::SECTION_TYPE;
Rafael Espindola8175be52014-10-08 15:28:58 +00001983 return !(Flags & MachO::S_ATTR_PURE_INSTRUCTIONS) &&
1984 (SectionType == MachO::S_ZEROFILL ||
1985 SectionType == MachO::S_GB_ZEROFILL);
Preston Gurdc68dda82012-04-12 20:13:57 +00001986}
1987
Rafael Espindolaa3af3472015-06-24 19:57:32 +00001988unsigned MachOObjectFile::getSectionID(SectionRef Sec) const {
1989 return Sec.getRawDataRefImpl().d.a;
1990}
1991
Rafael Espindola8175be52014-10-08 15:28:58 +00001992bool MachOObjectFile::isSectionVirtual(DataRefImpl Sec) const {
Francis Visoiu Mistrih7effcbd2018-04-19 17:02:57 +00001993 uint32_t Flags = getSectionFlags(*this, Sec);
1994 unsigned SectionType = Flags & MachO::SECTION_TYPE;
1995 return SectionType == MachO::S_ZEROFILL ||
1996 SectionType == MachO::S_GB_ZEROFILL;
Rafael Espindolaf6cfc152013-04-09 14:49:08 +00001997}
1998
Steven Wub9de1972016-02-29 19:40:10 +00001999bool MachOObjectFile::isSectionBitcode(DataRefImpl Sec) const {
2000 StringRef SegmentName = getSectionFinalSegmentName(Sec);
2001 StringRef SectName;
2002 if (!getSectionName(Sec, SectName))
2003 return (SegmentName == "__LLVM" && SectName == "__bitcode");
2004 return false;
2005}
2006
Jonas Devlieghereac9a5002017-09-26 14:22:35 +00002007bool MachOObjectFile::isSectionStripped(DataRefImpl Sec) const {
2008 if (is64Bit())
2009 return getSection64(Sec).offset == 0;
2010 return getSection(Sec).offset == 0;
2011}
2012
Rui Ueyama29552222013-09-27 21:47:05 +00002013relocation_iterator MachOObjectFile::section_rel_begin(DataRefImpl Sec) const {
Rafael Espindolae5330f72013-04-25 12:45:46 +00002014 DataRefImpl Ret;
Rafael Espindola5ca1f952014-04-03 23:51:28 +00002015 Ret.d.a = Sec.d.a;
2016 Ret.d.b = 0;
Rafael Espindolae5330f72013-04-25 12:45:46 +00002017 return relocation_iterator(RelocationRef(Ret, this));
Michael J. Spencer4344b1e2011-10-07 19:25:32 +00002018}
Rafael Espindola335f1d42013-04-08 20:45:01 +00002019
Rafael Espindolafd7aa382013-04-18 18:08:55 +00002020relocation_iterator
Rui Ueyama29552222013-09-27 21:47:05 +00002021MachOObjectFile::section_rel_end(DataRefImpl Sec) const {
Rafael Espindolae5330f72013-04-25 12:45:46 +00002022 uint32_t Num;
Rafael Espindolafd7aa382013-04-18 18:08:55 +00002023 if (is64Bit()) {
Charles Davis55107282013-09-01 04:28:48 +00002024 MachO::section_64 Sect = getSection64(Sec);
Charles Davis55107282013-09-01 04:28:48 +00002025 Num = Sect.nreloc;
Rafael Espindolafd7aa382013-04-18 18:08:55 +00002026 } else {
Charles Davis55107282013-09-01 04:28:48 +00002027 MachO::section Sect = getSection(Sec);
Charles Davis55107282013-09-01 04:28:48 +00002028 Num = Sect.nreloc;
Rafael Espindolafd7aa382013-04-18 18:08:55 +00002029 }
Eric Christopher6256b032011-04-22 03:19:48 +00002030
Rafael Espindolafd7aa382013-04-18 18:08:55 +00002031 DataRefImpl Ret;
Rafael Espindola5ca1f952014-04-03 23:51:28 +00002032 Ret.d.a = Sec.d.a;
2033 Ret.d.b = Num;
Rafael Espindolafd7aa382013-04-18 18:08:55 +00002034 return relocation_iterator(RelocationRef(Ret, this));
2035}
Benjamin Kramer0fcab072011-09-08 20:52:17 +00002036
Kevin Enderby96e8b4c2017-06-22 17:41:22 +00002037relocation_iterator MachOObjectFile::extrel_begin() const {
2038 DataRefImpl Ret;
Michael Trent6469bc62017-12-15 17:57:40 +00002039 // for DYSYMTAB symbols, Ret.d.a == 0 for external relocations
Kevin Enderby96e8b4c2017-06-22 17:41:22 +00002040 Ret.d.a = 0; // Would normally be a section index.
2041 Ret.d.b = 0; // Index into the external relocations
2042 return relocation_iterator(RelocationRef(Ret, this));
2043}
2044
2045relocation_iterator MachOObjectFile::extrel_end() const {
2046 MachO::dysymtab_command DysymtabLoadCmd = getDysymtabLoadCommand();
2047 DataRefImpl Ret;
Michael Trent6469bc62017-12-15 17:57:40 +00002048 // for DYSYMTAB symbols, Ret.d.a == 0 for external relocations
Kevin Enderby96e8b4c2017-06-22 17:41:22 +00002049 Ret.d.a = 0; // Would normally be a section index.
2050 Ret.d.b = DysymtabLoadCmd.nextrel; // Index into the external relocations
2051 return relocation_iterator(RelocationRef(Ret, this));
2052}
2053
Michael Trent6469bc62017-12-15 17:57:40 +00002054relocation_iterator MachOObjectFile::locrel_begin() const {
2055 DataRefImpl Ret;
2056 // for DYSYMTAB symbols, Ret.d.a == 1 for local relocations
2057 Ret.d.a = 1; // Would normally be a section index.
2058 Ret.d.b = 0; // Index into the local relocations
2059 return relocation_iterator(RelocationRef(Ret, this));
2060}
2061
2062relocation_iterator MachOObjectFile::locrel_end() const {
2063 MachO::dysymtab_command DysymtabLoadCmd = getDysymtabLoadCommand();
2064 DataRefImpl Ret;
2065 // for DYSYMTAB symbols, Ret.d.a == 1 for local relocations
2066 Ret.d.a = 1; // Would normally be a section index.
2067 Ret.d.b = DysymtabLoadCmd.nlocrel; // Index into the local relocations
2068 return relocation_iterator(RelocationRef(Ret, this));
2069}
2070
Rafael Espindolaefdbec82014-01-30 02:49:50 +00002071void MachOObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
Rafael Espindola5ca1f952014-04-03 23:51:28 +00002072 ++Rel.d.b;
Benjamin Kramer0fcab072011-09-08 20:52:17 +00002073}
Owen Andersond8fa76d2011-10-24 23:20:07 +00002074
Rafael Espindolaff676292015-06-29 23:29:12 +00002075uint64_t MachOObjectFile::getRelocationOffset(DataRefImpl Rel) const {
Kevin Enderby96e8b4c2017-06-22 17:41:22 +00002076 assert((getHeader().filetype == MachO::MH_OBJECT ||
2077 getHeader().filetype == MachO::MH_KEXT_BUNDLE) &&
2078 "Only implemented for MH_OBJECT && MH_KEXT_BUNDLE");
Charles Davis55107282013-09-01 04:28:48 +00002079 MachO::any_relocation_info RE = getRelocation(Rel);
Rafael Espindolaff676292015-06-29 23:29:12 +00002080 return getAnyRelocationAddress(RE);
David Meyer5c2b4ea2012-03-01 01:36:50 +00002081}
2082
Rafael Espindola6c1202c2013-06-05 01:33:53 +00002083symbol_iterator
2084MachOObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
Charles Davis55107282013-09-01 04:28:48 +00002085 MachO::any_relocation_info RE = getRelocation(Rel);
Tim Northover5b003bb2014-07-04 10:57:56 +00002086 if (isRelocationScattered(RE))
2087 return symbol_end();
2088
Rafael Espindolafd7aa382013-04-18 18:08:55 +00002089 uint32_t SymbolIdx = getPlainRelocationSymbolNum(RE);
2090 bool isExtern = getPlainRelocationExternal(RE);
Rafael Espindola6c1202c2013-06-05 01:33:53 +00002091 if (!isExtern)
Rafael Espindolaa40b3522014-02-10 20:24:04 +00002092 return symbol_end();
Rafael Espindola802fe932013-04-24 19:47:55 +00002093
Charles Davis55107282013-09-01 04:28:48 +00002094 MachO::symtab_command S = getSymtabLoadCommand();
Rafael Espindola802fe932013-04-24 19:47:55 +00002095 unsigned SymbolTableEntrySize = is64Bit() ?
Charles Davis55107282013-09-01 04:28:48 +00002096 sizeof(MachO::nlist_64) :
2097 sizeof(MachO::nlist);
2098 uint64_t Offset = S.symoff + SymbolIdx * SymbolTableEntrySize;
Rafael Espindola802fe932013-04-24 19:47:55 +00002099 DataRefImpl Sym;
Lang Hames85334ad2016-12-04 01:56:10 +00002100 Sym.p = reinterpret_cast<uintptr_t>(getPtr(*this, Offset));
Rafael Espindola6c1202c2013-06-05 01:33:53 +00002101 return symbol_iterator(SymbolRef(Sym, this));
Rafael Espindolafd7aa382013-04-18 18:08:55 +00002102}
2103
Keno Fischerb6976af2015-05-21 21:24:32 +00002104section_iterator
2105MachOObjectFile::getRelocationSection(DataRefImpl Rel) const {
2106 return section_iterator(getAnyRelocationSection(getRelocation(Rel)));
2107}
2108
Rafael Espindola7ede9642015-06-30 01:53:01 +00002109uint64_t MachOObjectFile::getRelocationType(DataRefImpl Rel) const {
Charles Davis55107282013-09-01 04:28:48 +00002110 MachO::any_relocation_info RE = getRelocation(Rel);
Rafael Espindola7ede9642015-06-30 01:53:01 +00002111 return getAnyRelocationType(RE);
Rafael Espindolafd7aa382013-04-18 18:08:55 +00002112}
2113
Rafael Espindolaf8a35ff2015-06-30 04:08:37 +00002114void MachOObjectFile::getRelocationTypeName(
2115 DataRefImpl Rel, SmallVectorImpl<char> &Result) const {
Rafael Espindolafd7aa382013-04-18 18:08:55 +00002116 StringRef res;
Rafael Espindola7ede9642015-06-30 01:53:01 +00002117 uint64_t RType = getRelocationType(Rel);
Rafael Espindolafd7aa382013-04-18 18:08:55 +00002118
2119 unsigned Arch = this->getArch();
2120
2121 switch (Arch) {
2122 case Triple::x86: {
2123 static const char *const Table[] = {
2124 "GENERIC_RELOC_VANILLA",
2125 "GENERIC_RELOC_PAIR",
2126 "GENERIC_RELOC_SECTDIFF",
2127 "GENERIC_RELOC_PB_LA_PTR",
2128 "GENERIC_RELOC_LOCAL_SECTDIFF",
2129 "GENERIC_RELOC_TLV" };
2130
Eric Christophera6000642013-12-06 02:33:38 +00002131 if (RType > 5)
Rafael Espindolafd7aa382013-04-18 18:08:55 +00002132 res = "Unknown";
2133 else
2134 res = Table[RType];
2135 break;
2136 }
2137 case Triple::x86_64: {
2138 static const char *const Table[] = {
2139 "X86_64_RELOC_UNSIGNED",
2140 "X86_64_RELOC_SIGNED",
2141 "X86_64_RELOC_BRANCH",
2142 "X86_64_RELOC_GOT_LOAD",
2143 "X86_64_RELOC_GOT",
2144 "X86_64_RELOC_SUBTRACTOR",
2145 "X86_64_RELOC_SIGNED_1",
2146 "X86_64_RELOC_SIGNED_2",
2147 "X86_64_RELOC_SIGNED_4",
2148 "X86_64_RELOC_TLV" };
2149
2150 if (RType > 9)
2151 res = "Unknown";
2152 else
2153 res = Table[RType];
2154 break;
2155 }
2156 case Triple::arm: {
2157 static const char *const Table[] = {
2158 "ARM_RELOC_VANILLA",
2159 "ARM_RELOC_PAIR",
2160 "ARM_RELOC_SECTDIFF",
2161 "ARM_RELOC_LOCAL_SECTDIFF",
2162 "ARM_RELOC_PB_LA_PTR",
2163 "ARM_RELOC_BR24",
2164 "ARM_THUMB_RELOC_BR22",
2165 "ARM_THUMB_32BIT_BRANCH",
2166 "ARM_RELOC_HALF",
2167 "ARM_RELOC_HALF_SECTDIFF" };
2168
2169 if (RType > 9)
2170 res = "Unknown";
2171 else
2172 res = Table[RType];
2173 break;
2174 }
Tim Northover7b837d82014-03-29 10:18:08 +00002175 case Triple::aarch64: {
2176 static const char *const Table[] = {
2177 "ARM64_RELOC_UNSIGNED", "ARM64_RELOC_SUBTRACTOR",
2178 "ARM64_RELOC_BRANCH26", "ARM64_RELOC_PAGE21",
2179 "ARM64_RELOC_PAGEOFF12", "ARM64_RELOC_GOT_LOAD_PAGE21",
2180 "ARM64_RELOC_GOT_LOAD_PAGEOFF12", "ARM64_RELOC_POINTER_TO_GOT",
2181 "ARM64_RELOC_TLVP_LOAD_PAGE21", "ARM64_RELOC_TLVP_LOAD_PAGEOFF12",
2182 "ARM64_RELOC_ADDEND"
2183 };
2184
2185 if (RType >= array_lengthof(Table))
2186 res = "Unknown";
2187 else
2188 res = Table[RType];
2189 break;
2190 }
Rafael Espindolafd7aa382013-04-18 18:08:55 +00002191 case Triple::ppc: {
2192 static const char *const Table[] = {
2193 "PPC_RELOC_VANILLA",
2194 "PPC_RELOC_PAIR",
2195 "PPC_RELOC_BR14",
2196 "PPC_RELOC_BR24",
2197 "PPC_RELOC_HI16",
2198 "PPC_RELOC_LO16",
2199 "PPC_RELOC_HA16",
2200 "PPC_RELOC_LO14",
2201 "PPC_RELOC_SECTDIFF",
2202 "PPC_RELOC_PB_LA_PTR",
2203 "PPC_RELOC_HI16_SECTDIFF",
2204 "PPC_RELOC_LO16_SECTDIFF",
2205 "PPC_RELOC_HA16_SECTDIFF",
2206 "PPC_RELOC_JBSR",
2207 "PPC_RELOC_LO14_SECTDIFF",
2208 "PPC_RELOC_LOCAL_SECTDIFF" };
2209
Eric Christophera6000642013-12-06 02:33:38 +00002210 if (RType > 15)
2211 res = "Unknown";
2212 else
2213 res = Table[RType];
Rafael Espindolafd7aa382013-04-18 18:08:55 +00002214 break;
2215 }
2216 case Triple::UnknownArch:
2217 res = "Unknown";
2218 break;
2219 }
2220 Result.append(res.begin(), res.end());
Rafael Espindolafd7aa382013-04-18 18:08:55 +00002221}
2222
Keno Fischerdbdf6672015-05-30 19:44:53 +00002223uint8_t MachOObjectFile::getRelocationLength(DataRefImpl Rel) const {
2224 MachO::any_relocation_info RE = getRelocation(Rel);
2225 return getAnyRelocationLength(RE);
2226}
2227
Kevin Enderbyecbc7242014-06-05 21:21:57 +00002228//
2229// guessLibraryShortName() is passed a name of a dynamic library and returns a
2230// guess on what the short name is. Then name is returned as a substring of the
2231// StringRef Name passed in. The name of the dynamic library is recognized as
2232// a framework if it has one of the two following forms:
2233// Foo.framework/Versions/A/Foo
2234// Foo.framework/Foo
2235// Where A and Foo can be any string. And may contain a trailing suffix
2236// starting with an underbar. If the Name is recognized as a framework then
2237// isFramework is set to true else it is set to false. If the Name has a
2238// suffix then Suffix is set to the substring in Name that contains the suffix
2239// else it is set to a NULL StringRef.
2240//
2241// The Name of the dynamic library is recognized as a library name if it has
2242// one of the two following forms:
2243// libFoo.A.dylib
2244// libFoo.dylib
2245// The library may have a suffix trailing the name Foo of the form:
2246// libFoo_profile.A.dylib
2247// libFoo_profile.dylib
2248//
2249// The Name of the dynamic library is also recognized as a library name if it
2250// has the following form:
2251// Foo.qtx
2252//
2253// If the Name of the dynamic library is none of the forms above then a NULL
2254// StringRef is returned.
2255//
2256StringRef MachOObjectFile::guessLibraryShortName(StringRef Name,
2257 bool &isFramework,
2258 StringRef &Suffix) {
2259 StringRef Foo, F, DotFramework, V, Dylib, Lib, Dot, Qtx;
2260 size_t a, b, c, d, Idx;
2261
2262 isFramework = false;
2263 Suffix = StringRef();
2264
2265 // Pull off the last component and make Foo point to it
2266 a = Name.rfind('/');
2267 if (a == Name.npos || a == 0)
2268 goto guess_library;
2269 Foo = Name.slice(a+1, Name.npos);
2270
2271 // Look for a suffix starting with a '_'
2272 Idx = Foo.rfind('_');
2273 if (Idx != Foo.npos && Foo.size() >= 2) {
2274 Suffix = Foo.slice(Idx, Foo.npos);
2275 Foo = Foo.slice(0, Idx);
2276 }
2277
2278 // First look for the form Foo.framework/Foo
2279 b = Name.rfind('/', a);
2280 if (b == Name.npos)
2281 Idx = 0;
2282 else
2283 Idx = b+1;
2284 F = Name.slice(Idx, Idx + Foo.size());
2285 DotFramework = Name.slice(Idx + Foo.size(),
2286 Idx + Foo.size() + sizeof(".framework/")-1);
2287 if (F == Foo && DotFramework == ".framework/") {
2288 isFramework = true;
2289 return Foo;
2290 }
2291
2292 // Next look for the form Foo.framework/Versions/A/Foo
2293 if (b == Name.npos)
2294 goto guess_library;
2295 c = Name.rfind('/', b);
2296 if (c == Name.npos || c == 0)
2297 goto guess_library;
2298 V = Name.slice(c+1, Name.npos);
2299 if (!V.startswith("Versions/"))
2300 goto guess_library;
2301 d = Name.rfind('/', c);
2302 if (d == Name.npos)
2303 Idx = 0;
2304 else
2305 Idx = d+1;
2306 F = Name.slice(Idx, Idx + Foo.size());
2307 DotFramework = Name.slice(Idx + Foo.size(),
2308 Idx + Foo.size() + sizeof(".framework/")-1);
2309 if (F == Foo && DotFramework == ".framework/") {
2310 isFramework = true;
2311 return Foo;
2312 }
2313
2314guess_library:
2315 // pull off the suffix after the "." and make a point to it
2316 a = Name.rfind('.');
2317 if (a == Name.npos || a == 0)
2318 return StringRef();
2319 Dylib = Name.slice(a, Name.npos);
2320 if (Dylib != ".dylib")
2321 goto guess_qtx;
2322
2323 // First pull off the version letter for the form Foo.A.dylib if any.
2324 if (a >= 3) {
2325 Dot = Name.slice(a-2, a-1);
2326 if (Dot == ".")
2327 a = a - 2;
2328 }
2329
2330 b = Name.rfind('/', a);
2331 if (b == Name.npos)
2332 b = 0;
2333 else
2334 b = b+1;
2335 // ignore any suffix after an underbar like Foo_profile.A.dylib
2336 Idx = Name.find('_', b);
2337 if (Idx != Name.npos && Idx != b) {
2338 Lib = Name.slice(b, Idx);
2339 Suffix = Name.slice(Idx, a);
2340 }
2341 else
2342 Lib = Name.slice(b, a);
2343 // There are incorrect library names of the form:
2344 // libATS.A_profile.dylib so check for these.
2345 if (Lib.size() >= 3) {
2346 Dot = Lib.slice(Lib.size()-2, Lib.size()-1);
2347 if (Dot == ".")
2348 Lib = Lib.slice(0, Lib.size()-2);
2349 }
2350 return Lib;
2351
2352guess_qtx:
2353 Qtx = Name.slice(a, Name.npos);
2354 if (Qtx != ".qtx")
2355 return StringRef();
2356 b = Name.rfind('/', a);
2357 if (b == Name.npos)
2358 Lib = Name.slice(0, a);
2359 else
2360 Lib = Name.slice(b+1, a);
2361 // There are library names of the form: QT.A.qtx so check for these.
2362 if (Lib.size() >= 3) {
2363 Dot = Lib.slice(Lib.size()-2, Lib.size()-1);
2364 if (Dot == ".")
2365 Lib = Lib.slice(0, Lib.size()-2);
2366 }
2367 return Lib;
2368}
2369
2370// getLibraryShortNameByIndex() is used to get the short name of the library
2371// for an undefined symbol in a linked Mach-O binary that was linked with the
2372// normal two-level namespace default (that is MH_TWOLEVEL in the header).
2373// It is passed the index (0 - based) of the library as translated from
2374// GET_LIBRARY_ORDINAL (1 - based).
Rafael Espindola5c792fa2014-06-12 21:46:39 +00002375std::error_code MachOObjectFile::getLibraryShortNameByIndex(unsigned Index,
Nick Kledzikaa4d2ac2014-08-30 00:20:14 +00002376 StringRef &Res) const {
Kevin Enderbyecbc7242014-06-05 21:21:57 +00002377 if (Index >= Libraries.size())
2378 return object_error::parse_failed;
2379
Kevin Enderbyecbc7242014-06-05 21:21:57 +00002380 // If the cache of LibrariesShortNames is not built up do that first for
2381 // all the Libraries.
2382 if (LibrariesShortNames.size() == 0) {
2383 for (unsigned i = 0; i < Libraries.size(); i++) {
2384 MachO::dylib_command D =
Lang Hames85334ad2016-12-04 01:56:10 +00002385 getStruct<MachO::dylib_command>(*this, Libraries[i]);
Nick Kledzik2b906112014-09-17 00:25:22 +00002386 if (D.dylib.name >= D.cmdsize)
2387 return object_error::parse_failed;
Kevin Enderby602941c2014-06-20 18:07:34 +00002388 const char *P = (const char *)(Libraries[i]) + D.dylib.name;
Kevin Enderbyecbc7242014-06-05 21:21:57 +00002389 StringRef Name = StringRef(P);
Nick Kledzik2b906112014-09-17 00:25:22 +00002390 if (D.dylib.name+Name.size() >= D.cmdsize)
2391 return object_error::parse_failed;
Kevin Enderbyecbc7242014-06-05 21:21:57 +00002392 StringRef Suffix;
2393 bool isFramework;
2394 StringRef shortName = guessLibraryShortName(Name, isFramework, Suffix);
Nick Kledzik2b906112014-09-17 00:25:22 +00002395 if (shortName.empty())
Kevin Enderbyecbc7242014-06-05 21:21:57 +00002396 LibrariesShortNames.push_back(Name);
2397 else
2398 LibrariesShortNames.push_back(shortName);
2399 }
2400 }
2401
2402 Res = LibrariesShortNames[Index];
Rui Ueyamaeae46732015-06-09 15:20:42 +00002403 return std::error_code();
Kevin Enderbyecbc7242014-06-05 21:21:57 +00002404}
2405
Kevin Enderby505b7702017-02-28 21:47:07 +00002406uint32_t MachOObjectFile::getLibraryCount() const {
2407 return Libraries.size();
2408}
2409
Rafael Espindolac2966a32015-07-06 14:55:37 +00002410section_iterator
2411MachOObjectFile::getRelocationRelocatedSection(relocation_iterator Rel) const {
2412 DataRefImpl Sec;
2413 Sec.d.a = Rel->getRawDataRefImpl().d.a;
2414 return section_iterator(SectionRef(Sec, this));
2415}
2416
Peter Collingbourneb9b39082016-11-22 03:38:40 +00002417basic_symbol_iterator MachOObjectFile::symbol_begin() const {
Kevin Enderby5479bf72016-01-22 22:49:55 +00002418 DataRefImpl DRI;
2419 MachO::symtab_command Symtab = getSymtabLoadCommand();
2420 if (!SymtabLoadCmd || Symtab.nsyms == 0)
2421 return basic_symbol_iterator(SymbolRef(DRI, this));
2422
Lang Hamesb572bc12014-05-12 21:39:59 +00002423 return getSymbolByIndex(0);
Rafael Espindolafd7aa382013-04-18 18:08:55 +00002424}
2425
Peter Collingbourneb9b39082016-11-22 03:38:40 +00002426basic_symbol_iterator MachOObjectFile::symbol_end() const {
Rafael Espindolafd7aa382013-04-18 18:08:55 +00002427 DataRefImpl DRI;
Kevin Enderby5479bf72016-01-22 22:49:55 +00002428 MachO::symtab_command Symtab = getSymtabLoadCommand();
2429 if (!SymtabLoadCmd || Symtab.nsyms == 0)
Rafael Espindola91f86b72014-02-21 20:10:59 +00002430 return basic_symbol_iterator(SymbolRef(DRI, this));
Rafael Espindola802fe932013-04-24 19:47:55 +00002431
Rafael Espindola802fe932013-04-24 19:47:55 +00002432 unsigned SymbolTableEntrySize = is64Bit() ?
Charles Davis55107282013-09-01 04:28:48 +00002433 sizeof(MachO::nlist_64) :
2434 sizeof(MachO::nlist);
2435 unsigned Offset = Symtab.symoff +
2436 Symtab.nsyms * SymbolTableEntrySize;
Lang Hames85334ad2016-12-04 01:56:10 +00002437 DRI.p = reinterpret_cast<uintptr_t>(getPtr(*this, Offset));
Rafael Espindola91f86b72014-02-21 20:10:59 +00002438 return basic_symbol_iterator(SymbolRef(DRI, this));
Rafael Espindolafd7aa382013-04-18 18:08:55 +00002439}
2440
Lang Hamesd2d60da2019-01-14 22:05:12 +00002441symbol_iterator MachOObjectFile::getSymbolByIndex(unsigned Index) const {
Lang Hamesb572bc12014-05-12 21:39:59 +00002442 MachO::symtab_command Symtab = getSymtabLoadCommand();
Kevin Enderby5479bf72016-01-22 22:49:55 +00002443 if (!SymtabLoadCmd || Index >= Symtab.nsyms)
Filipe Cabecinhas01834772015-01-15 22:52:38 +00002444 report_fatal_error("Requested symbol index is out of range.");
Lang Hamesb572bc12014-05-12 21:39:59 +00002445 unsigned SymbolTableEntrySize =
2446 is64Bit() ? sizeof(MachO::nlist_64) : sizeof(MachO::nlist);
Kevin Enderby5479bf72016-01-22 22:49:55 +00002447 DataRefImpl DRI;
Lang Hames85334ad2016-12-04 01:56:10 +00002448 DRI.p = reinterpret_cast<uintptr_t>(getPtr(*this, Symtab.symoff));
Lang Hamesb572bc12014-05-12 21:39:59 +00002449 DRI.p += Index * SymbolTableEntrySize;
2450 return basic_symbol_iterator(SymbolRef(DRI, this));
2451}
2452
Kevin Enderby813e0cf2016-04-20 21:24:34 +00002453uint64_t MachOObjectFile::getSymbolIndex(DataRefImpl Symb) const {
2454 MachO::symtab_command Symtab = getSymtabLoadCommand();
2455 if (!SymtabLoadCmd)
2456 report_fatal_error("getSymbolIndex() called with no symbol table symbol");
2457 unsigned SymbolTableEntrySize =
2458 is64Bit() ? sizeof(MachO::nlist_64) : sizeof(MachO::nlist);
2459 DataRefImpl DRIstart;
Lang Hames85334ad2016-12-04 01:56:10 +00002460 DRIstart.p = reinterpret_cast<uintptr_t>(getPtr(*this, Symtab.symoff));
Kevin Enderby813e0cf2016-04-20 21:24:34 +00002461 uint64_t Index = (Symb.p - DRIstart.p) / SymbolTableEntrySize;
2462 return Index;
2463}
2464
Rafael Espindolaa40b3522014-02-10 20:24:04 +00002465section_iterator MachOObjectFile::section_begin() const {
Rafael Espindolafd7aa382013-04-18 18:08:55 +00002466 DataRefImpl DRI;
2467 return section_iterator(SectionRef(DRI, this));
2468}
2469
Rafael Espindolaa40b3522014-02-10 20:24:04 +00002470section_iterator MachOObjectFile::section_end() const {
Rafael Espindolafd7aa382013-04-18 18:08:55 +00002471 DataRefImpl DRI;
2472 DRI.d.a = Sections.size();
2473 return section_iterator(SectionRef(DRI, this));
2474}
2475
Rafael Espindolafd7aa382013-04-18 18:08:55 +00002476uint8_t MachOObjectFile::getBytesInAddress() const {
Rafael Espindola0f08eb12013-04-07 19:05:30 +00002477 return is64Bit() ? 8 : 4;
Eric Christopher6256b032011-04-22 03:19:48 +00002478}
2479
Rafael Espindolafd7aa382013-04-18 18:08:55 +00002480StringRef MachOObjectFile::getFileFormatName() const {
Lang Hames85334ad2016-12-04 01:56:10 +00002481 unsigned CPUType = getCPUType(*this);
Rafael Espindolafd7aa382013-04-18 18:08:55 +00002482 if (!is64Bit()) {
2483 switch (CPUType) {
Eugene Zelenko903f87e2017-04-21 22:03:05 +00002484 case MachO::CPU_TYPE_I386:
Rafael Espindolafd7aa382013-04-18 18:08:55 +00002485 return "Mach-O 32-bit i386";
Eugene Zelenko903f87e2017-04-21 22:03:05 +00002486 case MachO::CPU_TYPE_ARM:
Rafael Espindolafd7aa382013-04-18 18:08:55 +00002487 return "Mach-O arm";
Eugene Zelenko903f87e2017-04-21 22:03:05 +00002488 case MachO::CPU_TYPE_POWERPC:
Rafael Espindolafd7aa382013-04-18 18:08:55 +00002489 return "Mach-O 32-bit ppc";
2490 default:
Rafael Espindolafd7aa382013-04-18 18:08:55 +00002491 return "Mach-O 32-bit unknown";
2492 }
2493 }
2494
Rafael Espindolafd7aa382013-04-18 18:08:55 +00002495 switch (CPUType) {
Eugene Zelenko903f87e2017-04-21 22:03:05 +00002496 case MachO::CPU_TYPE_X86_64:
Rafael Espindolafd7aa382013-04-18 18:08:55 +00002497 return "Mach-O 64-bit x86-64";
Eugene Zelenko903f87e2017-04-21 22:03:05 +00002498 case MachO::CPU_TYPE_ARM64:
Tim Northover7b837d82014-03-29 10:18:08 +00002499 return "Mach-O arm64";
Eugene Zelenko903f87e2017-04-21 22:03:05 +00002500 case MachO::CPU_TYPE_POWERPC64:
Rafael Espindolafd7aa382013-04-18 18:08:55 +00002501 return "Mach-O 64-bit ppc64";
2502 default:
2503 return "Mach-O 64-bit unknown";
2504 }
2505}
2506
Alexey Samsonov9c22f872013-06-18 15:03:28 +00002507Triple::ArchType MachOObjectFile::getArch(uint32_t CPUType) {
2508 switch (CPUType) {
Eugene Zelenko903f87e2017-04-21 22:03:05 +00002509 case MachO::CPU_TYPE_I386:
Rafael Espindolafd7aa382013-04-18 18:08:55 +00002510 return Triple::x86;
Eugene Zelenko903f87e2017-04-21 22:03:05 +00002511 case MachO::CPU_TYPE_X86_64:
Rafael Espindolafd7aa382013-04-18 18:08:55 +00002512 return Triple::x86_64;
Eugene Zelenko903f87e2017-04-21 22:03:05 +00002513 case MachO::CPU_TYPE_ARM:
Rafael Espindolafd7aa382013-04-18 18:08:55 +00002514 return Triple::arm;
Eugene Zelenko903f87e2017-04-21 22:03:05 +00002515 case MachO::CPU_TYPE_ARM64:
Tim Northover92311482014-07-23 12:32:47 +00002516 return Triple::aarch64;
Eugene Zelenko903f87e2017-04-21 22:03:05 +00002517 case MachO::CPU_TYPE_POWERPC:
Rafael Espindolafd7aa382013-04-18 18:08:55 +00002518 return Triple::ppc;
Eugene Zelenko903f87e2017-04-21 22:03:05 +00002519 case MachO::CPU_TYPE_POWERPC64:
Rafael Espindolafd7aa382013-04-18 18:08:55 +00002520 return Triple::ppc64;
2521 default:
2522 return Triple::UnknownArch;
2523 }
2524}
2525
Tim Northoverd52a2442016-04-22 23:21:13 +00002526Triple MachOObjectFile::getArchTriple(uint32_t CPUType, uint32_t CPUSubType,
Kevin Enderby398ecdf2016-12-16 22:54:02 +00002527 const char **McpuDefault,
2528 const char **ArchFlag) {
Kevin Enderbyf7590322014-08-18 20:21:02 +00002529 if (McpuDefault)
2530 *McpuDefault = nullptr;
Kevin Enderby398ecdf2016-12-16 22:54:02 +00002531 if (ArchFlag)
2532 *ArchFlag = nullptr;
Kevin Enderbyf7590322014-08-18 20:21:02 +00002533
Kevin Enderbyc28eff12014-06-30 18:45:23 +00002534 switch (CPUType) {
2535 case MachO::CPU_TYPE_I386:
2536 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2537 case MachO::CPU_SUBTYPE_I386_ALL:
Kevin Enderby398ecdf2016-12-16 22:54:02 +00002538 if (ArchFlag)
2539 *ArchFlag = "i386";
Kevin Enderbyc28eff12014-06-30 18:45:23 +00002540 return Triple("i386-apple-darwin");
2541 default:
2542 return Triple();
2543 }
2544 case MachO::CPU_TYPE_X86_64:
2545 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2546 case MachO::CPU_SUBTYPE_X86_64_ALL:
Kevin Enderby398ecdf2016-12-16 22:54:02 +00002547 if (ArchFlag)
2548 *ArchFlag = "x86_64";
Kevin Enderbyc28eff12014-06-30 18:45:23 +00002549 return Triple("x86_64-apple-darwin");
2550 case MachO::CPU_SUBTYPE_X86_64_H:
Kevin Enderby398ecdf2016-12-16 22:54:02 +00002551 if (ArchFlag)
2552 *ArchFlag = "x86_64h";
Kevin Enderbyc28eff12014-06-30 18:45:23 +00002553 return Triple("x86_64h-apple-darwin");
2554 default:
2555 return Triple();
2556 }
2557 case MachO::CPU_TYPE_ARM:
2558 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2559 case MachO::CPU_SUBTYPE_ARM_V4T:
Kevin Enderby398ecdf2016-12-16 22:54:02 +00002560 if (ArchFlag)
2561 *ArchFlag = "armv4t";
Kevin Enderbyc28eff12014-06-30 18:45:23 +00002562 return Triple("armv4t-apple-darwin");
2563 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
Kevin Enderby398ecdf2016-12-16 22:54:02 +00002564 if (ArchFlag)
2565 *ArchFlag = "armv5e";
Kevin Enderbyc28eff12014-06-30 18:45:23 +00002566 return Triple("armv5e-apple-darwin");
Kevin Enderby31dec852014-08-07 21:30:25 +00002567 case MachO::CPU_SUBTYPE_ARM_XSCALE:
Kevin Enderby398ecdf2016-12-16 22:54:02 +00002568 if (ArchFlag)
2569 *ArchFlag = "xscale";
Kevin Enderby31dec852014-08-07 21:30:25 +00002570 return Triple("xscale-apple-darwin");
Kevin Enderbyc28eff12014-06-30 18:45:23 +00002571 case MachO::CPU_SUBTYPE_ARM_V6:
Kevin Enderby398ecdf2016-12-16 22:54:02 +00002572 if (ArchFlag)
2573 *ArchFlag = "armv6";
Kevin Enderbyc28eff12014-06-30 18:45:23 +00002574 return Triple("armv6-apple-darwin");
2575 case MachO::CPU_SUBTYPE_ARM_V6M:
Kevin Enderbyf7590322014-08-18 20:21:02 +00002576 if (McpuDefault)
2577 *McpuDefault = "cortex-m0";
Kevin Enderby398ecdf2016-12-16 22:54:02 +00002578 if (ArchFlag)
2579 *ArchFlag = "armv6m";
Kevin Enderbyc28eff12014-06-30 18:45:23 +00002580 return Triple("armv6m-apple-darwin");
Kevin Enderby31dec852014-08-07 21:30:25 +00002581 case MachO::CPU_SUBTYPE_ARM_V7:
Kevin Enderby398ecdf2016-12-16 22:54:02 +00002582 if (ArchFlag)
2583 *ArchFlag = "armv7";
Kevin Enderby31dec852014-08-07 21:30:25 +00002584 return Triple("armv7-apple-darwin");
Kevin Enderbyc28eff12014-06-30 18:45:23 +00002585 case MachO::CPU_SUBTYPE_ARM_V7EM:
Kevin Enderbyf7590322014-08-18 20:21:02 +00002586 if (McpuDefault)
2587 *McpuDefault = "cortex-m4";
Kevin Enderby398ecdf2016-12-16 22:54:02 +00002588 if (ArchFlag)
2589 *ArchFlag = "armv7em";
Tim Northoverd52a2442016-04-22 23:21:13 +00002590 return Triple("thumbv7em-apple-darwin");
Kevin Enderbyc28eff12014-06-30 18:45:23 +00002591 case MachO::CPU_SUBTYPE_ARM_V7K:
Kevin Enderby61fed382017-01-24 23:41:04 +00002592 if (McpuDefault)
2593 *McpuDefault = "cortex-a7";
Kevin Enderby398ecdf2016-12-16 22:54:02 +00002594 if (ArchFlag)
2595 *ArchFlag = "armv7k";
Kevin Enderbyc28eff12014-06-30 18:45:23 +00002596 return Triple("armv7k-apple-darwin");
2597 case MachO::CPU_SUBTYPE_ARM_V7M:
Kevin Enderbyf7590322014-08-18 20:21:02 +00002598 if (McpuDefault)
2599 *McpuDefault = "cortex-m3";
Kevin Enderby398ecdf2016-12-16 22:54:02 +00002600 if (ArchFlag)
2601 *ArchFlag = "armv7m";
Tim Northoverd52a2442016-04-22 23:21:13 +00002602 return Triple("thumbv7m-apple-darwin");
Kevin Enderbyc28eff12014-06-30 18:45:23 +00002603 case MachO::CPU_SUBTYPE_ARM_V7S:
Kevin Enderby61fed382017-01-24 23:41:04 +00002604 if (McpuDefault)
2605 *McpuDefault = "cortex-a7";
Kevin Enderby398ecdf2016-12-16 22:54:02 +00002606 if (ArchFlag)
2607 *ArchFlag = "armv7s";
Kevin Enderbyc28eff12014-06-30 18:45:23 +00002608 return Triple("armv7s-apple-darwin");
2609 default:
2610 return Triple();
2611 }
2612 case MachO::CPU_TYPE_ARM64:
2613 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2614 case MachO::CPU_SUBTYPE_ARM64_ALL:
Kevin Enderby0aa69102017-02-10 19:27:10 +00002615 if (McpuDefault)
2616 *McpuDefault = "cyclone";
Kevin Enderby398ecdf2016-12-16 22:54:02 +00002617 if (ArchFlag)
2618 *ArchFlag = "arm64";
Kevin Enderbyc28eff12014-06-30 18:45:23 +00002619 return Triple("arm64-apple-darwin");
2620 default:
2621 return Triple();
2622 }
2623 case MachO::CPU_TYPE_POWERPC:
2624 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
2625 case MachO::CPU_SUBTYPE_POWERPC_ALL:
Kevin Enderby398ecdf2016-12-16 22:54:02 +00002626 if (ArchFlag)
2627 *ArchFlag = "ppc";
Kevin Enderbyc28eff12014-06-30 18:45:23 +00002628 return Triple("ppc-apple-darwin");
2629 default:
2630 return Triple();
2631 }
2632 case MachO::CPU_TYPE_POWERPC64:
Reid Klecknerb23ae552014-06-30 20:12:59 +00002633 switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
Kevin Enderbyc28eff12014-06-30 18:45:23 +00002634 case MachO::CPU_SUBTYPE_POWERPC_ALL:
Kevin Enderby398ecdf2016-12-16 22:54:02 +00002635 if (ArchFlag)
2636 *ArchFlag = "ppc64";
Kevin Enderbyc28eff12014-06-30 18:45:23 +00002637 return Triple("ppc64-apple-darwin");
Kevin Enderbyc28eff12014-06-30 18:45:23 +00002638 default:
2639 return Triple();
2640 }
2641 default:
2642 return Triple();
2643 }
2644}
2645
2646Triple MachOObjectFile::getHostArch() {
2647 return Triple(sys::getDefaultTargetTriple());
2648}
2649
Rafael Espindola015f5762014-08-08 16:30:17 +00002650bool MachOObjectFile::isValidArch(StringRef ArchFlag) {
2651 return StringSwitch<bool>(ArchFlag)
2652 .Case("i386", true)
2653 .Case("x86_64", true)
2654 .Case("x86_64h", true)
2655 .Case("armv4t", true)
2656 .Case("arm", true)
2657 .Case("armv5e", true)
2658 .Case("armv6", true)
2659 .Case("armv6m", true)
Frederic Riss37c67e62015-06-16 17:37:03 +00002660 .Case("armv7", true)
Rafael Espindola015f5762014-08-08 16:30:17 +00002661 .Case("armv7em", true)
2662 .Case("armv7k", true)
2663 .Case("armv7m", true)
2664 .Case("armv7s", true)
2665 .Case("arm64", true)
2666 .Case("ppc", true)
2667 .Case("ppc64", true)
2668 .Default(false);
Kevin Enderbyc28eff12014-06-30 18:45:23 +00002669}
2670
Zachary Turnerece9b232017-12-14 22:07:03 +00002671Triple::ArchType MachOObjectFile::getArch() const {
Lang Hames85334ad2016-12-04 01:56:10 +00002672 return getArch(getCPUType(*this));
Alexey Samsonov9c22f872013-06-18 15:03:28 +00002673}
2674
Tim Northoverd52a2442016-04-22 23:21:13 +00002675Triple MachOObjectFile::getArchTriple(const char **McpuDefault) const {
2676 return getArchTriple(Header.cputype, Header.cpusubtype, McpuDefault);
Kevin Enderbyf7590322014-08-18 20:21:02 +00002677}
2678
Rui Ueyama29552222013-09-27 21:47:05 +00002679relocation_iterator MachOObjectFile::section_rel_begin(unsigned Index) const {
Rafael Espindola2173e182013-04-26 20:07:33 +00002680 DataRefImpl DRI;
2681 DRI.d.a = Index;
Rui Ueyama29552222013-09-27 21:47:05 +00002682 return section_rel_begin(DRI);
Rafael Espindola2173e182013-04-26 20:07:33 +00002683}
2684
Rui Ueyama29552222013-09-27 21:47:05 +00002685relocation_iterator MachOObjectFile::section_rel_end(unsigned Index) const {
Rafael Espindola2173e182013-04-26 20:07:33 +00002686 DataRefImpl DRI;
2687 DRI.d.a = Index;
Rui Ueyama29552222013-09-27 21:47:05 +00002688 return section_rel_end(DRI);
Rafael Espindola2173e182013-04-26 20:07:33 +00002689}
2690
Kevin Enderby54154f32013-06-06 17:20:50 +00002691dice_iterator MachOObjectFile::begin_dices() const {
2692 DataRefImpl DRI;
2693 if (!DataInCodeLoadCmd)
2694 return dice_iterator(DiceRef(DRI, this));
2695
Charles Davis55107282013-09-01 04:28:48 +00002696 MachO::linkedit_data_command DicLC = getDataInCodeLoadCommand();
Lang Hames85334ad2016-12-04 01:56:10 +00002697 DRI.p = reinterpret_cast<uintptr_t>(getPtr(*this, DicLC.dataoff));
Kevin Enderby54154f32013-06-06 17:20:50 +00002698 return dice_iterator(DiceRef(DRI, this));
2699}
2700
2701dice_iterator MachOObjectFile::end_dices() const {
2702 DataRefImpl DRI;
2703 if (!DataInCodeLoadCmd)
2704 return dice_iterator(DiceRef(DRI, this));
2705
Charles Davis55107282013-09-01 04:28:48 +00002706 MachO::linkedit_data_command DicLC = getDataInCodeLoadCommand();
2707 unsigned Offset = DicLC.dataoff + DicLC.datasize;
Lang Hames85334ad2016-12-04 01:56:10 +00002708 DRI.p = reinterpret_cast<uintptr_t>(getPtr(*this, Offset));
Kevin Enderby54154f32013-06-06 17:20:50 +00002709 return dice_iterator(DiceRef(DRI, this));
2710}
2711
Kevin Enderbyed0a9e12017-07-20 23:08:41 +00002712ExportEntry::ExportEntry(Error *E, const MachOObjectFile *O,
2713 ArrayRef<uint8_t> T) : E(E), O(O), Trie(T) {}
Nick Kledzikaa4d2ac2014-08-30 00:20:14 +00002714
2715void ExportEntry::moveToFirst() {
Kevin Enderbyed0a9e12017-07-20 23:08:41 +00002716 ErrorAsOutParameter ErrAsOutParam(E);
Nick Kledzikaa4d2ac2014-08-30 00:20:14 +00002717 pushNode(0);
Kevin Enderbyed0a9e12017-07-20 23:08:41 +00002718 if (*E)
2719 return;
Nick Kledzikaa4d2ac2014-08-30 00:20:14 +00002720 pushDownUntilBottom();
2721}
2722
2723void ExportEntry::moveToEnd() {
2724 Stack.clear();
2725 Done = true;
2726}
2727
2728bool ExportEntry::operator==(const ExportEntry &Other) const {
NAKAMURA Takumi6902c8d2015-09-22 11:14:12 +00002729 // Common case, one at end, other iterating from begin.
Nick Kledzikaa4d2ac2014-08-30 00:20:14 +00002730 if (Done || Other.Done)
2731 return (Done == Other.Done);
2732 // Not equal if different stack sizes.
2733 if (Stack.size() != Other.Stack.size())
2734 return false;
2735 // Not equal if different cumulative strings.
Yaron Keren6e92e7b2015-03-30 15:42:36 +00002736 if (!CumulativeString.equals(Other.CumulativeString))
Nick Kledzikaa4d2ac2014-08-30 00:20:14 +00002737 return false;
2738 // Equal if all nodes in both stacks match.
2739 for (unsigned i=0; i < Stack.size(); ++i) {
2740 if (Stack[i].Start != Other.Stack[i].Start)
2741 return false;
2742 }
NAKAMURA Takumiccf2ea32015-09-22 11:19:03 +00002743 return true;
Nick Kledzikaa4d2ac2014-08-30 00:20:14 +00002744}
2745
Kevin Enderbyed0a9e12017-07-20 23:08:41 +00002746uint64_t ExportEntry::readULEB128(const uint8_t *&Ptr, const char **error) {
Nick Kledzik9bf03272014-09-02 18:50:24 +00002747 unsigned Count;
Kevin Enderbyed0a9e12017-07-20 23:08:41 +00002748 uint64_t Result = decodeULEB128(Ptr, &Count, Trie.end(), error);
Nick Kledzik9bf03272014-09-02 18:50:24 +00002749 Ptr += Count;
Kevin Enderbyed0a9e12017-07-20 23:08:41 +00002750 if (Ptr > Trie.end())
Nick Kledzik9bf03272014-09-02 18:50:24 +00002751 Ptr = Trie.end();
Nick Kledzik9bf03272014-09-02 18:50:24 +00002752 return Result;
Nick Kledzikaa4d2ac2014-08-30 00:20:14 +00002753}
2754
2755StringRef ExportEntry::name() const {
Yaron Keren6e92e7b2015-03-30 15:42:36 +00002756 return CumulativeString;
Nick Kledzikaa4d2ac2014-08-30 00:20:14 +00002757}
2758
2759uint64_t ExportEntry::flags() const {
2760 return Stack.back().Flags;
2761}
2762
2763uint64_t ExportEntry::address() const {
2764 return Stack.back().Address;
2765}
2766
2767uint64_t ExportEntry::other() const {
2768 return Stack.back().Other;
2769}
2770
2771StringRef ExportEntry::otherName() const {
2772 const char* ImportName = Stack.back().ImportName;
2773 if (ImportName)
2774 return StringRef(ImportName);
2775 return StringRef();
2776}
2777
2778uint32_t ExportEntry::nodeOffset() const {
2779 return Stack.back().Start - Trie.begin();
2780}
2781
NAKAMURA Takumid4cdf192015-09-22 11:13:55 +00002782ExportEntry::NodeState::NodeState(const uint8_t *Ptr)
Eugene Zelenko903f87e2017-04-21 22:03:05 +00002783 : Start(Ptr), Current(Ptr) {}
Nick Kledzikaa4d2ac2014-08-30 00:20:14 +00002784
2785void ExportEntry::pushNode(uint64_t offset) {
Kevin Enderbyed0a9e12017-07-20 23:08:41 +00002786 ErrorAsOutParameter ErrAsOutParam(E);
Nick Kledzikaa4d2ac2014-08-30 00:20:14 +00002787 const uint8_t *Ptr = Trie.begin() + offset;
2788 NodeState State(Ptr);
Kevin Enderbyed0a9e12017-07-20 23:08:41 +00002789 const char *error;
2790 uint64_t ExportInfoSize = readULEB128(State.Current, &error);
2791 if (error) {
Benjamin Kramerefa50a22017-08-20 15:13:39 +00002792 *E = malformedError("export info size " + Twine(error) +
2793 " in export trie data at node: 0x" +
2794 Twine::utohexstr(offset));
Kevin Enderbyed0a9e12017-07-20 23:08:41 +00002795 moveToEnd();
2796 return;
2797 }
Nick Kledzikaa4d2ac2014-08-30 00:20:14 +00002798 State.IsExportNode = (ExportInfoSize != 0);
2799 const uint8_t* Children = State.Current + ExportInfoSize;
Kevin Enderbyed0a9e12017-07-20 23:08:41 +00002800 if (Children > Trie.end()) {
Benjamin Kramerefa50a22017-08-20 15:13:39 +00002801 *E = malformedError(
2802 "export info size: 0x" + Twine::utohexstr(ExportInfoSize) +
2803 " in export trie data at node: 0x" + Twine::utohexstr(offset) +
2804 " too big and extends past end of trie data");
Kevin Enderbyed0a9e12017-07-20 23:08:41 +00002805 moveToEnd();
2806 return;
2807 }
Nick Kledzikaa4d2ac2014-08-30 00:20:14 +00002808 if (State.IsExportNode) {
Kevin Enderbyed0a9e12017-07-20 23:08:41 +00002809 const uint8_t *ExportStart = State.Current;
2810 State.Flags = readULEB128(State.Current, &error);
2811 if (error) {
Benjamin Kramerefa50a22017-08-20 15:13:39 +00002812 *E = malformedError("flags " + Twine(error) +
2813 " in export trie data at node: 0x" +
2814 Twine::utohexstr(offset));
Kevin Enderbyed0a9e12017-07-20 23:08:41 +00002815 moveToEnd();
2816 return;
2817 }
2818 uint64_t Kind = State.Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK;
2819 if (State.Flags != 0 &&
2820 (Kind != MachO::EXPORT_SYMBOL_FLAGS_KIND_REGULAR &&
2821 Kind != MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE &&
2822 Kind != MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL)) {
Benjamin Kramerefa50a22017-08-20 15:13:39 +00002823 *E = malformedError(
2824 "unsupported exported symbol kind: " + Twine((int)Kind) +
2825 " in flags: 0x" + Twine::utohexstr(State.Flags) +
2826 " in export trie data at node: 0x" + Twine::utohexstr(offset));
Kevin Enderbyed0a9e12017-07-20 23:08:41 +00002827 moveToEnd();
2828 return;
2829 }
Nick Kledzikaa4d2ac2014-08-30 00:20:14 +00002830 if (State.Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT) {
2831 State.Address = 0;
Kevin Enderbyed0a9e12017-07-20 23:08:41 +00002832 State.Other = readULEB128(State.Current, &error); // dylib ordinal
2833 if (error) {
2834 *E = malformedError("dylib ordinal of re-export " + Twine(error) +
Benjamin Kramerefa50a22017-08-20 15:13:39 +00002835 " in export trie data at node: 0x" +
2836 Twine::utohexstr(offset));
Kevin Enderbyed0a9e12017-07-20 23:08:41 +00002837 moveToEnd();
2838 return;
2839 }
2840 if (O != nullptr) {
2841 if (State.Other > O->getLibraryCount()) {
Benjamin Kramerefa50a22017-08-20 15:13:39 +00002842 *E = malformedError(
2843 "bad library ordinal: " + Twine((int)State.Other) + " (max " +
2844 Twine((int)O->getLibraryCount()) +
2845 ") in export trie data at node: 0x" + Twine::utohexstr(offset));
Kevin Enderbyed0a9e12017-07-20 23:08:41 +00002846 moveToEnd();
2847 return;
2848 }
2849 }
Nick Kledzikaa4d2ac2014-08-30 00:20:14 +00002850 State.ImportName = reinterpret_cast<const char*>(State.Current);
Kevin Enderbyed0a9e12017-07-20 23:08:41 +00002851 if (*State.ImportName == '\0') {
2852 State.Current++;
2853 } else {
2854 const uint8_t *End = State.Current + 1;
2855 if (End >= Trie.end()) {
2856 *E = malformedError("import name of re-export in export trie data at "
Benjamin Kramerefa50a22017-08-20 15:13:39 +00002857 "node: 0x" +
2858 Twine::utohexstr(offset) +
2859 " starts past end of trie data");
Kevin Enderbyed0a9e12017-07-20 23:08:41 +00002860 moveToEnd();
2861 return;
2862 }
2863 while(*End != '\0' && End < Trie.end())
2864 End++;
2865 if (*End != '\0') {
2866 *E = malformedError("import name of re-export in export trie data at "
Benjamin Kramerefa50a22017-08-20 15:13:39 +00002867 "node: 0x" +
2868 Twine::utohexstr(offset) +
2869 " extends past end of trie data");
Kevin Enderbyed0a9e12017-07-20 23:08:41 +00002870 moveToEnd();
2871 return;
2872 }
2873 State.Current = End + 1;
2874 }
Nick Kledzikaa4d2ac2014-08-30 00:20:14 +00002875 } else {
Kevin Enderbyed0a9e12017-07-20 23:08:41 +00002876 State.Address = readULEB128(State.Current, &error);
2877 if (error) {
Benjamin Kramerefa50a22017-08-20 15:13:39 +00002878 *E = malformedError("address " + Twine(error) +
2879 " in export trie data at node: 0x" +
2880 Twine::utohexstr(offset));
Kevin Enderbyed0a9e12017-07-20 23:08:41 +00002881 moveToEnd();
2882 return;
2883 }
2884 if (State.Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER) {
2885 State.Other = readULEB128(State.Current, &error);
2886 if (error) {
2887 *E = malformedError("resolver of stub and resolver " + Twine(error) +
Benjamin Kramerefa50a22017-08-20 15:13:39 +00002888 " in export trie data at node: 0x" +
2889 Twine::utohexstr(offset));
Kevin Enderbyed0a9e12017-07-20 23:08:41 +00002890 moveToEnd();
2891 return;
2892 }
2893 }
Nick Kledzikaa4d2ac2014-08-30 00:20:14 +00002894 }
Kevin Enderbyed0a9e12017-07-20 23:08:41 +00002895 if(ExportStart + ExportInfoSize != State.Current) {
Benjamin Kramerefa50a22017-08-20 15:13:39 +00002896 *E = malformedError(
2897 "inconsistant export info size: 0x" +
2898 Twine::utohexstr(ExportInfoSize) + " where actual size was: 0x" +
2899 Twine::utohexstr(State.Current - ExportStart) +
2900 " in export trie data at node: 0x" + Twine::utohexstr(offset));
Kevin Enderbyed0a9e12017-07-20 23:08:41 +00002901 moveToEnd();
2902 return;
2903 }
2904 }
Kevin Enderby04cdb2e2017-07-24 20:33:41 +00002905 State.ChildCount = *Children;
2906 if (State.ChildCount != 0 && Children + 1 >= Trie.end()) {
Kevin Enderbyed0a9e12017-07-20 23:08:41 +00002907 *E = malformedError("byte for count of childern in export trie data at "
Benjamin Kramerefa50a22017-08-20 15:13:39 +00002908 "node: 0x" +
2909 Twine::utohexstr(offset) +
2910 " extends past end of trie data");
Kevin Enderbyed0a9e12017-07-20 23:08:41 +00002911 moveToEnd();
2912 return;
Nick Kledzikaa4d2ac2014-08-30 00:20:14 +00002913 }
Nick Kledzikaa4d2ac2014-08-30 00:20:14 +00002914 State.Current = Children + 1;
2915 State.NextChildIndex = 0;
2916 State.ParentStringLength = CumulativeString.size();
2917 Stack.push_back(State);
2918}
2919
2920void ExportEntry::pushDownUntilBottom() {
Kevin Enderbyed0a9e12017-07-20 23:08:41 +00002921 ErrorAsOutParameter ErrAsOutParam(E);
2922 const char *error;
Nick Kledzikaa4d2ac2014-08-30 00:20:14 +00002923 while (Stack.back().NextChildIndex < Stack.back().ChildCount) {
2924 NodeState &Top = Stack.back();
2925 CumulativeString.resize(Top.ParentStringLength);
Kevin Enderbyed0a9e12017-07-20 23:08:41 +00002926 for (;*Top.Current != 0 && Top.Current < Trie.end(); Top.Current++) {
Nick Kledzik9bf03272014-09-02 18:50:24 +00002927 char C = *Top.Current;
2928 CumulativeString.push_back(C);
Nick Kledzikaa4d2ac2014-08-30 00:20:14 +00002929 }
Kevin Enderbyed0a9e12017-07-20 23:08:41 +00002930 if (Top.Current >= Trie.end()) {
2931 *E = malformedError("edge sub-string in export trie data at node: 0x" +
Benjamin Kramerefa50a22017-08-20 15:13:39 +00002932 Twine::utohexstr(Top.Start - Trie.begin()) +
2933 " for child #" + Twine((int)Top.NextChildIndex) +
2934 " extends past end of trie data");
Kevin Enderbyed0a9e12017-07-20 23:08:41 +00002935 moveToEnd();
2936 return;
2937 }
Nick Kledzikaa4d2ac2014-08-30 00:20:14 +00002938 Top.Current += 1;
Kevin Enderbyed0a9e12017-07-20 23:08:41 +00002939 uint64_t childNodeIndex = readULEB128(Top.Current, &error);
2940 if (error) {
2941 *E = malformedError("child node offset " + Twine(error) +
Benjamin Kramerefa50a22017-08-20 15:13:39 +00002942 " in export trie data at node: 0x" +
2943 Twine::utohexstr(Top.Start - Trie.begin()));
Kevin Enderbyed0a9e12017-07-20 23:08:41 +00002944 moveToEnd();
2945 return;
2946 }
2947 for (const NodeState &node : nodes()) {
2948 if (node.Start == Trie.begin() + childNodeIndex){
2949 *E = malformedError("loop in childern in export trie data at node: 0x" +
Benjamin Kramerefa50a22017-08-20 15:13:39 +00002950 Twine::utohexstr(Top.Start - Trie.begin()) +
2951 " back to node: 0x" +
2952 Twine::utohexstr(childNodeIndex));
Kevin Enderbyed0a9e12017-07-20 23:08:41 +00002953 moveToEnd();
2954 return;
2955 }
2956 }
Nick Kledzikaa4d2ac2014-08-30 00:20:14 +00002957 Top.NextChildIndex += 1;
2958 pushNode(childNodeIndex);
Kevin Enderbyed0a9e12017-07-20 23:08:41 +00002959 if (*E)
2960 return;
Nick Kledzikaa4d2ac2014-08-30 00:20:14 +00002961 }
2962 if (!Stack.back().IsExportNode) {
Kevin Enderbyed0a9e12017-07-20 23:08:41 +00002963 *E = malformedError("node is not an export node in export trie data at "
Benjamin Kramerefa50a22017-08-20 15:13:39 +00002964 "node: 0x" +
2965 Twine::utohexstr(Stack.back().Start - Trie.begin()));
Nick Kledzikaa4d2ac2014-08-30 00:20:14 +00002966 moveToEnd();
Kevin Enderbyed0a9e12017-07-20 23:08:41 +00002967 return;
Nick Kledzikaa4d2ac2014-08-30 00:20:14 +00002968 }
2969}
2970
2971// We have a trie data structure and need a way to walk it that is compatible
2972// with the C++ iterator model. The solution is a non-recursive depth first
2973// traversal where the iterator contains a stack of parent nodes along with a
2974// string that is the accumulation of all edge strings along the parent chain
2975// to this point.
2976//
NAKAMURA Takumia85a0b32014-10-27 08:08:18 +00002977// There is one "export" node for each exported symbol. But because some
Nick Kledzikaa4d2ac2014-08-30 00:20:14 +00002978// symbols may be a prefix of another symbol (e.g. _dup and _dup2), an export
NAKAMURA Takumi6902c8d2015-09-22 11:14:12 +00002979// node may have child nodes too.
Nick Kledzikaa4d2ac2014-08-30 00:20:14 +00002980//
2981// The algorithm for moveNext() is to keep moving down the leftmost unvisited
2982// child until hitting a node with no children (which is an export node or
2983// else the trie is malformed). On the way down, each node is pushed on the
2984// stack ivar. If there is no more ways down, it pops up one and tries to go
2985// down a sibling path until a childless node is reached.
2986void ExportEntry::moveNext() {
Kevin Enderbyed0a9e12017-07-20 23:08:41 +00002987 assert(!Stack.empty() && "ExportEntry::moveNext() with empty node stack");
2988 if (!Stack.back().IsExportNode) {
2989 *E = malformedError("node is not an export node in export trie data at "
Benjamin Kramerefa50a22017-08-20 15:13:39 +00002990 "node: 0x" +
2991 Twine::utohexstr(Stack.back().Start - Trie.begin()));
Nick Kledzikaa4d2ac2014-08-30 00:20:14 +00002992 moveToEnd();
2993 return;
2994 }
2995
2996 Stack.pop_back();
2997 while (!Stack.empty()) {
2998 NodeState &Top = Stack.back();
2999 if (Top.NextChildIndex < Top.ChildCount) {
3000 pushDownUntilBottom();
3001 // Now at the next export node.
3002 return;
3003 } else {
3004 if (Top.IsExportNode) {
3005 // This node has no children but is itself an export node.
3006 CumulativeString.resize(Top.ParentStringLength);
3007 return;
3008 }
3009 Stack.pop_back();
3010 }
3011 }
3012 Done = true;
3013}
3014
NAKAMURA Takumiccf2ea32015-09-22 11:19:03 +00003015iterator_range<export_iterator>
Kevin Enderbyed0a9e12017-07-20 23:08:41 +00003016MachOObjectFile::exports(Error &E, ArrayRef<uint8_t> Trie,
3017 const MachOObjectFile *O) {
3018 ExportEntry Start(&E, O, Trie);
Eugene Zelenko903f87e2017-04-21 22:03:05 +00003019 if (Trie.empty())
Juergen Ributzka15067a62014-12-19 02:31:01 +00003020 Start.moveToEnd();
3021 else
3022 Start.moveToFirst();
Nick Kledzikaa4d2ac2014-08-30 00:20:14 +00003023
Kevin Enderbyed0a9e12017-07-20 23:08:41 +00003024 ExportEntry Finish(&E, O, Trie);
Nick Kledzikaa4d2ac2014-08-30 00:20:14 +00003025 Finish.moveToEnd();
3026
Craig Toppere6bc7d12015-12-06 05:08:07 +00003027 return make_range(export_iterator(Start), export_iterator(Finish));
Nick Kledzikaa4d2ac2014-08-30 00:20:14 +00003028}
3029
Alexander Shaposhnikovb5b38542017-07-29 00:30:45 +00003030iterator_range<export_iterator> MachOObjectFile::exports(Error &Err) const {
3031 return exports(Err, getDyldInfoExportsTrie(), this);
Nick Kledzikaa4d2ac2014-08-30 00:20:14 +00003032}
3033
Kevin Enderby1ae32f12017-03-20 19:46:55 +00003034MachORebaseEntry::MachORebaseEntry(Error *E, const MachOObjectFile *O,
3035 ArrayRef<uint8_t> Bytes, bool is64Bit)
Eugene Zelenko903f87e2017-04-21 22:03:05 +00003036 : E(E), O(O), Opcodes(Bytes), Ptr(Bytes.begin()),
3037 PointerSize(is64Bit ? 8 : 4) {}
Nick Kledzika240fc52014-09-12 21:34:15 +00003038
3039void MachORebaseEntry::moveToFirst() {
3040 Ptr = Opcodes.begin();
3041 moveNext();
3042}
3043
3044void MachORebaseEntry::moveToEnd() {
3045 Ptr = Opcodes.end();
3046 RemainingLoopCount = 0;
3047 Done = true;
3048}
3049
3050void MachORebaseEntry::moveNext() {
Kevin Enderby3903b472017-03-27 20:09:23 +00003051 ErrorAsOutParameter ErrAsOutParam(E);
Nick Kledzika240fc52014-09-12 21:34:15 +00003052 // If in the middle of some loop, move to next rebasing in loop.
3053 SegmentOffset += AdvanceAmount;
3054 if (RemainingLoopCount) {
3055 --RemainingLoopCount;
3056 return;
3057 }
Juergen Ributzka2bca52a2017-03-30 19:56:50 +00003058 // REBASE_OPCODE_DONE is only used for padding if we are not aligned to
3059 // pointer size. Therefore it is possible to reach the end without ever having
3060 // seen REBASE_OPCODE_DONE.
3061 if (Ptr == Opcodes.end()) {
Nick Kledzika240fc52014-09-12 21:34:15 +00003062 Done = true;
3063 return;
3064 }
3065 bool More = true;
Kevin Enderby3903b472017-03-27 20:09:23 +00003066 while (More) {
Nick Kledzika240fc52014-09-12 21:34:15 +00003067 // Parse next opcode and set up next loop.
Kevin Enderby3903b472017-03-27 20:09:23 +00003068 const uint8_t *OpcodeStart = Ptr;
Nick Kledzika240fc52014-09-12 21:34:15 +00003069 uint8_t Byte = *Ptr++;
3070 uint8_t ImmValue = Byte & MachO::REBASE_IMMEDIATE_MASK;
3071 uint8_t Opcode = Byte & MachO::REBASE_OPCODE_MASK;
Kevin Enderby3903b472017-03-27 20:09:23 +00003072 uint32_t Count, Skip;
3073 const char *error = nullptr;
Nick Kledzika240fc52014-09-12 21:34:15 +00003074 switch (Opcode) {
3075 case MachO::REBASE_OPCODE_DONE:
3076 More = false;
3077 Done = true;
3078 moveToEnd();
Eugene Zelenko903f87e2017-04-21 22:03:05 +00003079 DEBUG_WITH_TYPE("mach-o-rebase", dbgs() << "REBASE_OPCODE_DONE\n");
Nick Kledzika240fc52014-09-12 21:34:15 +00003080 break;
3081 case MachO::REBASE_OPCODE_SET_TYPE_IMM:
3082 RebaseType = ImmValue;
Kevin Enderby3903b472017-03-27 20:09:23 +00003083 if (RebaseType > MachO::REBASE_TYPE_TEXT_PCREL32) {
Benjamin Kramerefa50a22017-08-20 15:13:39 +00003084 *E = malformedError("for REBASE_OPCODE_SET_TYPE_IMM bad bind type: " +
3085 Twine((int)RebaseType) + " for opcode at: 0x" +
3086 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3087 moveToEnd();
3088 return;
Kevin Enderby3903b472017-03-27 20:09:23 +00003089 }
Nick Kledzika240fc52014-09-12 21:34:15 +00003090 DEBUG_WITH_TYPE(
3091 "mach-o-rebase",
Eugene Zelenko903f87e2017-04-21 22:03:05 +00003092 dbgs() << "REBASE_OPCODE_SET_TYPE_IMM: "
3093 << "RebaseType=" << (int) RebaseType << "\n");
Nick Kledzika240fc52014-09-12 21:34:15 +00003094 break;
3095 case MachO::REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:
3096 SegmentIndex = ImmValue;
Kevin Enderby3903b472017-03-27 20:09:23 +00003097 SegmentOffset = readULEB128(&error);
3098 if (error) {
3099 *E = malformedError("for REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB " +
Benjamin Kramerefa50a22017-08-20 15:13:39 +00003100 Twine(error) + " for opcode at: 0x" +
3101 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
Kevin Enderby3903b472017-03-27 20:09:23 +00003102 moveToEnd();
3103 return;
3104 }
3105 error = O->RebaseEntryCheckSegAndOffset(SegmentIndex, SegmentOffset,
3106 true);
3107 if (error) {
3108 *E = malformedError("for REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB " +
Benjamin Kramerefa50a22017-08-20 15:13:39 +00003109 Twine(error) + " for opcode at: 0x" +
3110 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
Kevin Enderby3903b472017-03-27 20:09:23 +00003111 moveToEnd();
3112 return;
3113 }
Nick Kledzika240fc52014-09-12 21:34:15 +00003114 DEBUG_WITH_TYPE(
3115 "mach-o-rebase",
Eugene Zelenko903f87e2017-04-21 22:03:05 +00003116 dbgs() << "REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: "
3117 << "SegmentIndex=" << SegmentIndex << ", "
3118 << format("SegmentOffset=0x%06X", SegmentOffset)
3119 << "\n");
Nick Kledzika240fc52014-09-12 21:34:15 +00003120 break;
3121 case MachO::REBASE_OPCODE_ADD_ADDR_ULEB:
Kevin Enderby3903b472017-03-27 20:09:23 +00003122 SegmentOffset += readULEB128(&error);
3123 if (error) {
Benjamin Kramerefa50a22017-08-20 15:13:39 +00003124 *E = malformedError("for REBASE_OPCODE_ADD_ADDR_ULEB " + Twine(error) +
3125 " for opcode at: 0x" +
3126 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
Kevin Enderby3903b472017-03-27 20:09:23 +00003127 moveToEnd();
3128 return;
3129 }
3130 error = O->RebaseEntryCheckSegAndOffset(SegmentIndex, SegmentOffset,
3131 true);
3132 if (error) {
Benjamin Kramerefa50a22017-08-20 15:13:39 +00003133 *E = malformedError("for REBASE_OPCODE_ADD_ADDR_ULEB " + Twine(error) +
3134 " for opcode at: 0x" +
3135 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
Kevin Enderby3903b472017-03-27 20:09:23 +00003136 moveToEnd();
3137 return;
3138 }
Nick Kledzika240fc52014-09-12 21:34:15 +00003139 DEBUG_WITH_TYPE("mach-o-rebase",
Eugene Zelenko903f87e2017-04-21 22:03:05 +00003140 dbgs() << "REBASE_OPCODE_ADD_ADDR_ULEB: "
3141 << format("SegmentOffset=0x%06X",
3142 SegmentOffset) << "\n");
Nick Kledzika240fc52014-09-12 21:34:15 +00003143 break;
3144 case MachO::REBASE_OPCODE_ADD_ADDR_IMM_SCALED:
Kevin Enderby3903b472017-03-27 20:09:23 +00003145 error = O->RebaseEntryCheckSegAndOffset(SegmentIndex, SegmentOffset,
3146 true);
3147 if (error) {
3148 *E = malformedError("for REBASE_OPCODE_ADD_ADDR_IMM_SCALED " +
Benjamin Kramerefa50a22017-08-20 15:13:39 +00003149 Twine(error) + " for opcode at: 0x" +
3150 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
Kevin Enderby3903b472017-03-27 20:09:23 +00003151 moveToEnd();
3152 return;
3153 }
Nick Kledzika240fc52014-09-12 21:34:15 +00003154 SegmentOffset += ImmValue * PointerSize;
Kevin Enderby3903b472017-03-27 20:09:23 +00003155 error = O->RebaseEntryCheckSegAndOffset(SegmentIndex, SegmentOffset,
3156 false);
3157 if (error) {
Benjamin Kramerefa50a22017-08-20 15:13:39 +00003158 *E =
3159 malformedError("for REBASE_OPCODE_ADD_ADDR_IMM_SCALED "
3160 " (after adding immediate times the pointer size) " +
3161 Twine(error) + " for opcode at: 0x" +
3162 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
Kevin Enderby3903b472017-03-27 20:09:23 +00003163 moveToEnd();
3164 return;
3165 }
Nick Kledzika240fc52014-09-12 21:34:15 +00003166 DEBUG_WITH_TYPE("mach-o-rebase",
Eugene Zelenko903f87e2017-04-21 22:03:05 +00003167 dbgs() << "REBASE_OPCODE_ADD_ADDR_IMM_SCALED: "
3168 << format("SegmentOffset=0x%06X",
3169 SegmentOffset) << "\n");
Nick Kledzika240fc52014-09-12 21:34:15 +00003170 break;
3171 case MachO::REBASE_OPCODE_DO_REBASE_IMM_TIMES:
Kevin Enderby3903b472017-03-27 20:09:23 +00003172 error = O->RebaseEntryCheckSegAndOffset(SegmentIndex, SegmentOffset,
3173 true);
3174 if (error) {
3175 *E = malformedError("for REBASE_OPCODE_DO_REBASE_IMM_TIMES " +
Benjamin Kramerefa50a22017-08-20 15:13:39 +00003176 Twine(error) + " for opcode at: 0x" +
3177 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
Kevin Enderby3903b472017-03-27 20:09:23 +00003178 moveToEnd();
3179 return;
3180 }
Nick Kledzika240fc52014-09-12 21:34:15 +00003181 AdvanceAmount = PointerSize;
Kevin Enderby3903b472017-03-27 20:09:23 +00003182 Skip = 0;
3183 Count = ImmValue;
3184 if (ImmValue != 0)
3185 RemainingLoopCount = ImmValue - 1;
3186 else
3187 RemainingLoopCount = 0;
3188 error = O->RebaseEntryCheckCountAndSkip(Count, Skip, PointerSize,
3189 SegmentIndex, SegmentOffset);
3190 if (error) {
Benjamin Kramerefa50a22017-08-20 15:13:39 +00003191 *E = malformedError("for REBASE_OPCODE_DO_REBASE_IMM_TIMES " +
3192 Twine(error) + " for opcode at: 0x" +
3193 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
Kevin Enderby3903b472017-03-27 20:09:23 +00003194 moveToEnd();
NAKAMURA Takumief15f2c2017-08-28 06:47:47 +00003195 return;
Kevin Enderby3903b472017-03-27 20:09:23 +00003196 }
Nick Kledzika240fc52014-09-12 21:34:15 +00003197 DEBUG_WITH_TYPE(
3198 "mach-o-rebase",
Eugene Zelenko903f87e2017-04-21 22:03:05 +00003199 dbgs() << "REBASE_OPCODE_DO_REBASE_IMM_TIMES: "
3200 << format("SegmentOffset=0x%06X", SegmentOffset)
3201 << ", AdvanceAmount=" << AdvanceAmount
3202 << ", RemainingLoopCount=" << RemainingLoopCount
3203 << "\n");
Nick Kledzika240fc52014-09-12 21:34:15 +00003204 return;
3205 case MachO::REBASE_OPCODE_DO_REBASE_ULEB_TIMES:
Kevin Enderby3903b472017-03-27 20:09:23 +00003206 error = O->RebaseEntryCheckSegAndOffset(SegmentIndex, SegmentOffset,
3207 true);
3208 if (error) {
3209 *E = malformedError("for REBASE_OPCODE_DO_REBASE_ULEB_TIMES " +
Benjamin Kramerefa50a22017-08-20 15:13:39 +00003210 Twine(error) + " for opcode at: 0x" +
3211 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
Kevin Enderby3903b472017-03-27 20:09:23 +00003212 moveToEnd();
3213 return;
3214 }
Nick Kledzika240fc52014-09-12 21:34:15 +00003215 AdvanceAmount = PointerSize;
Kevin Enderby3903b472017-03-27 20:09:23 +00003216 Skip = 0;
3217 Count = readULEB128(&error);
3218 if (error) {
3219 *E = malformedError("for REBASE_OPCODE_DO_REBASE_ULEB_TIMES " +
Benjamin Kramerefa50a22017-08-20 15:13:39 +00003220 Twine(error) + " for opcode at: 0x" +
3221 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
Kevin Enderby3903b472017-03-27 20:09:23 +00003222 moveToEnd();
3223 return;
3224 }
3225 if (Count != 0)
3226 RemainingLoopCount = Count - 1;
3227 else
3228 RemainingLoopCount = 0;
3229 error = O->RebaseEntryCheckCountAndSkip(Count, Skip, PointerSize,
3230 SegmentIndex, SegmentOffset);
3231 if (error) {
Benjamin Kramerefa50a22017-08-20 15:13:39 +00003232 *E = malformedError("for REBASE_OPCODE_DO_REBASE_ULEB_TIMES " +
3233 Twine(error) + " for opcode at: 0x" +
3234 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
Kevin Enderby3903b472017-03-27 20:09:23 +00003235 moveToEnd();
NAKAMURA Takumief15f2c2017-08-28 06:47:47 +00003236 return;
Kevin Enderby3903b472017-03-27 20:09:23 +00003237 }
Nick Kledzika240fc52014-09-12 21:34:15 +00003238 DEBUG_WITH_TYPE(
3239 "mach-o-rebase",
Eugene Zelenko903f87e2017-04-21 22:03:05 +00003240 dbgs() << "REBASE_OPCODE_DO_REBASE_ULEB_TIMES: "
3241 << format("SegmentOffset=0x%06X", SegmentOffset)
3242 << ", AdvanceAmount=" << AdvanceAmount
3243 << ", RemainingLoopCount=" << RemainingLoopCount
3244 << "\n");
Nick Kledzika240fc52014-09-12 21:34:15 +00003245 return;
3246 case MachO::REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB:
Kevin Enderby3903b472017-03-27 20:09:23 +00003247 error = O->RebaseEntryCheckSegAndOffset(SegmentIndex, SegmentOffset,
3248 true);
3249 if (error) {
3250 *E = malformedError("for REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB " +
Benjamin Kramerefa50a22017-08-20 15:13:39 +00003251 Twine(error) + " for opcode at: 0x" +
3252 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
Kevin Enderby3903b472017-03-27 20:09:23 +00003253 moveToEnd();
3254 return;
3255 }
3256 Skip = readULEB128(&error);
3257 if (error) {
3258 *E = malformedError("for REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB " +
Benjamin Kramerefa50a22017-08-20 15:13:39 +00003259 Twine(error) + " for opcode at: 0x" +
3260 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
Kevin Enderby3903b472017-03-27 20:09:23 +00003261 moveToEnd();
3262 return;
3263 }
3264 AdvanceAmount = Skip + PointerSize;
3265 Count = 1;
Nick Kledzika240fc52014-09-12 21:34:15 +00003266 RemainingLoopCount = 0;
Kevin Enderby3903b472017-03-27 20:09:23 +00003267 error = O->RebaseEntryCheckCountAndSkip(Count, Skip, PointerSize,
3268 SegmentIndex, SegmentOffset);
3269 if (error) {
Benjamin Kramerefa50a22017-08-20 15:13:39 +00003270 *E = malformedError("for REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB " +
3271 Twine(error) + " for opcode at: 0x" +
3272 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
Kevin Enderby3903b472017-03-27 20:09:23 +00003273 moveToEnd();
NAKAMURA Takumief15f2c2017-08-28 06:47:47 +00003274 return;
Kevin Enderby3903b472017-03-27 20:09:23 +00003275 }
Nick Kledzika240fc52014-09-12 21:34:15 +00003276 DEBUG_WITH_TYPE(
3277 "mach-o-rebase",
Eugene Zelenko903f87e2017-04-21 22:03:05 +00003278 dbgs() << "REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB: "
3279 << format("SegmentOffset=0x%06X", SegmentOffset)
3280 << ", AdvanceAmount=" << AdvanceAmount
3281 << ", RemainingLoopCount=" << RemainingLoopCount
3282 << "\n");
Nick Kledzika240fc52014-09-12 21:34:15 +00003283 return;
3284 case MachO::REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB:
Kevin Enderby3903b472017-03-27 20:09:23 +00003285 error = O->RebaseEntryCheckSegAndOffset(SegmentIndex, SegmentOffset,
3286 true);
3287 if (error) {
3288 *E = malformedError("for REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_"
Benjamin Kramerefa50a22017-08-20 15:13:39 +00003289 "ULEB " +
3290 Twine(error) + " for opcode at: 0x" +
3291 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
Kevin Enderby3903b472017-03-27 20:09:23 +00003292 moveToEnd();
3293 return;
3294 }
3295 Count = readULEB128(&error);
3296 if (error) {
3297 *E = malformedError("for REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_"
Benjamin Kramerefa50a22017-08-20 15:13:39 +00003298 "ULEB " +
3299 Twine(error) + " for opcode at: 0x" +
3300 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
Kevin Enderby3903b472017-03-27 20:09:23 +00003301 moveToEnd();
3302 return;
3303 }
3304 if (Count != 0)
3305 RemainingLoopCount = Count - 1;
3306 else
3307 RemainingLoopCount = 0;
3308 Skip = readULEB128(&error);
3309 if (error) {
3310 *E = malformedError("for REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_"
Benjamin Kramerefa50a22017-08-20 15:13:39 +00003311 "ULEB " +
3312 Twine(error) + " for opcode at: 0x" +
3313 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
Kevin Enderby3903b472017-03-27 20:09:23 +00003314 moveToEnd();
3315 return;
3316 }
3317 AdvanceAmount = Skip + PointerSize;
3318
3319 error = O->RebaseEntryCheckCountAndSkip(Count, Skip, PointerSize,
3320 SegmentIndex, SegmentOffset);
3321 if (error) {
3322 *E = malformedError("for REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_"
Benjamin Kramerefa50a22017-08-20 15:13:39 +00003323 "ULEB " +
3324 Twine(error) + " for opcode at: 0x" +
3325 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
Kevin Enderby3903b472017-03-27 20:09:23 +00003326 moveToEnd();
NAKAMURA Takumief15f2c2017-08-28 06:47:47 +00003327 return;
Kevin Enderby3903b472017-03-27 20:09:23 +00003328 }
Nick Kledzika240fc52014-09-12 21:34:15 +00003329 DEBUG_WITH_TYPE(
3330 "mach-o-rebase",
Eugene Zelenko903f87e2017-04-21 22:03:05 +00003331 dbgs() << "REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB: "
3332 << format("SegmentOffset=0x%06X", SegmentOffset)
3333 << ", AdvanceAmount=" << AdvanceAmount
3334 << ", RemainingLoopCount=" << RemainingLoopCount
3335 << "\n");
Nick Kledzika240fc52014-09-12 21:34:15 +00003336 return;
3337 default:
Kevin Enderby3903b472017-03-27 20:09:23 +00003338 *E = malformedError("bad rebase info (bad opcode value 0x" +
Benjamin Kramerefa50a22017-08-20 15:13:39 +00003339 Twine::utohexstr(Opcode) + " for opcode at: 0x" +
3340 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
Kevin Enderby3903b472017-03-27 20:09:23 +00003341 moveToEnd();
3342 return;
Nick Kledzika240fc52014-09-12 21:34:15 +00003343 }
3344 }
3345}
3346
Kevin Enderby3903b472017-03-27 20:09:23 +00003347uint64_t MachORebaseEntry::readULEB128(const char **error) {
Nick Kledzika240fc52014-09-12 21:34:15 +00003348 unsigned Count;
Kevin Enderby3903b472017-03-27 20:09:23 +00003349 uint64_t Result = decodeULEB128(Ptr, &Count, Opcodes.end(), error);
Nick Kledzika240fc52014-09-12 21:34:15 +00003350 Ptr += Count;
Kevin Enderby3903b472017-03-27 20:09:23 +00003351 if (Ptr > Opcodes.end())
Nick Kledzika240fc52014-09-12 21:34:15 +00003352 Ptr = Opcodes.end();
Nick Kledzika240fc52014-09-12 21:34:15 +00003353 return Result;
3354}
3355
Kevin Enderby3903b472017-03-27 20:09:23 +00003356int32_t MachORebaseEntry::segmentIndex() const { return SegmentIndex; }
Nick Kledzika240fc52014-09-12 21:34:15 +00003357
3358uint64_t MachORebaseEntry::segmentOffset() const { return SegmentOffset; }
3359
3360StringRef MachORebaseEntry::typeName() const {
3361 switch (RebaseType) {
3362 case MachO::REBASE_TYPE_POINTER:
3363 return "pointer";
3364 case MachO::REBASE_TYPE_TEXT_ABSOLUTE32:
3365 return "text abs32";
3366 case MachO::REBASE_TYPE_TEXT_PCREL32:
3367 return "text rel32";
3368 }
3369 return "unknown";
3370}
3371
Kevin Enderby1ae32f12017-03-20 19:46:55 +00003372// For use with the SegIndex of a checked Mach-O Rebase entry
3373// to get the segment name.
3374StringRef MachORebaseEntry::segmentName() const {
3375 return O->BindRebaseSegmentName(SegmentIndex);
3376}
3377
3378// For use with a SegIndex,SegOffset pair from a checked Mach-O Rebase entry
3379// to get the section name.
3380StringRef MachORebaseEntry::sectionName() const {
3381 return O->BindRebaseSectionName(SegmentIndex, SegmentOffset);
3382}
3383
3384// For use with a SegIndex,SegOffset pair from a checked Mach-O Rebase entry
3385// to get the address.
3386uint64_t MachORebaseEntry::address() const {
3387 return O->BindRebaseAddress(SegmentIndex, SegmentOffset);
3388}
3389
Nick Kledzika240fc52014-09-12 21:34:15 +00003390bool MachORebaseEntry::operator==(const MachORebaseEntry &Other) const {
Saleem Abdulrasool8204fd72017-01-08 19:14:15 +00003391#ifdef EXPENSIVE_CHECKS
Nick Kledzika240fc52014-09-12 21:34:15 +00003392 assert(Opcodes == Other.Opcodes && "compare iterators of different files");
Saleem Abdulrasool8204fd72017-01-08 19:14:15 +00003393#else
3394 assert(Opcodes.data() == Other.Opcodes.data() && "compare iterators of different files");
3395#endif
Nick Kledzika240fc52014-09-12 21:34:15 +00003396 return (Ptr == Other.Ptr) &&
3397 (RemainingLoopCount == Other.RemainingLoopCount) &&
3398 (Done == Other.Done);
3399}
3400
3401iterator_range<rebase_iterator>
Kevin Enderby1ae32f12017-03-20 19:46:55 +00003402MachOObjectFile::rebaseTable(Error &Err, MachOObjectFile *O,
3403 ArrayRef<uint8_t> Opcodes, bool is64) {
3404 if (O->BindRebaseSectionTable == nullptr)
3405 O->BindRebaseSectionTable = llvm::make_unique<BindRebaseSegInfo>(O);
3406 MachORebaseEntry Start(&Err, O, Opcodes, is64);
Nick Kledzika240fc52014-09-12 21:34:15 +00003407 Start.moveToFirst();
3408
Kevin Enderby1ae32f12017-03-20 19:46:55 +00003409 MachORebaseEntry Finish(&Err, O, Opcodes, is64);
Nick Kledzika240fc52014-09-12 21:34:15 +00003410 Finish.moveToEnd();
3411
Craig Toppere6bc7d12015-12-06 05:08:07 +00003412 return make_range(rebase_iterator(Start), rebase_iterator(Finish));
Nick Kledzika240fc52014-09-12 21:34:15 +00003413}
3414
Kevin Enderby1ae32f12017-03-20 19:46:55 +00003415iterator_range<rebase_iterator> MachOObjectFile::rebaseTable(Error &Err) {
3416 return rebaseTable(Err, this, getDyldInfoRebaseOpcodes(), is64Bit());
Nick Kledzika240fc52014-09-12 21:34:15 +00003417}
3418
Kevin Enderby505b7702017-02-28 21:47:07 +00003419MachOBindEntry::MachOBindEntry(Error *E, const MachOObjectFile *O,
3420 ArrayRef<uint8_t> Bytes, bool is64Bit, Kind BK)
Eugene Zelenko903f87e2017-04-21 22:03:05 +00003421 : E(E), O(O), Opcodes(Bytes), Ptr(Bytes.begin()),
3422 PointerSize(is64Bit ? 8 : 4), TableKind(BK) {}
Nick Kledzik367cf702014-09-16 01:41:51 +00003423
3424void MachOBindEntry::moveToFirst() {
3425 Ptr = Opcodes.begin();
3426 moveNext();
3427}
3428
3429void MachOBindEntry::moveToEnd() {
3430 Ptr = Opcodes.end();
3431 RemainingLoopCount = 0;
3432 Done = true;
3433}
3434
3435void MachOBindEntry::moveNext() {
Kevin Enderby505b7702017-02-28 21:47:07 +00003436 ErrorAsOutParameter ErrAsOutParam(E);
Nick Kledzik367cf702014-09-16 01:41:51 +00003437 // If in the middle of some loop, move to next binding in loop.
3438 SegmentOffset += AdvanceAmount;
3439 if (RemainingLoopCount) {
3440 --RemainingLoopCount;
3441 return;
3442 }
Juergen Ributzka2bca52a2017-03-30 19:56:50 +00003443 // BIND_OPCODE_DONE is only used for padding if we are not aligned to
3444 // pointer size. Therefore it is possible to reach the end without ever having
3445 // seen BIND_OPCODE_DONE.
3446 if (Ptr == Opcodes.end()) {
Nick Kledzik367cf702014-09-16 01:41:51 +00003447 Done = true;
3448 return;
3449 }
3450 bool More = true;
Kevin Enderby3903b472017-03-27 20:09:23 +00003451 while (More) {
Nick Kledzik367cf702014-09-16 01:41:51 +00003452 // Parse next opcode and set up next loop.
Kevin Enderby505b7702017-02-28 21:47:07 +00003453 const uint8_t *OpcodeStart = Ptr;
Nick Kledzik367cf702014-09-16 01:41:51 +00003454 uint8_t Byte = *Ptr++;
3455 uint8_t ImmValue = Byte & MachO::BIND_IMMEDIATE_MASK;
3456 uint8_t Opcode = Byte & MachO::BIND_OPCODE_MASK;
3457 int8_t SignExtended;
3458 const uint8_t *SymStart;
Kevin Enderby1ae32f12017-03-20 19:46:55 +00003459 uint32_t Count, Skip;
3460 const char *error = nullptr;
Nick Kledzik367cf702014-09-16 01:41:51 +00003461 switch (Opcode) {
3462 case MachO::BIND_OPCODE_DONE:
3463 if (TableKind == Kind::Lazy) {
3464 // Lazying bindings have a DONE opcode between entries. Need to ignore
3465 // it to advance to next entry. But need not if this is last entry.
3466 bool NotLastEntry = false;
3467 for (const uint8_t *P = Ptr; P < Opcodes.end(); ++P) {
3468 if (*P) {
3469 NotLastEntry = true;
3470 }
3471 }
3472 if (NotLastEntry)
3473 break;
3474 }
3475 More = false;
Nick Kledzik367cf702014-09-16 01:41:51 +00003476 moveToEnd();
Eugene Zelenko903f87e2017-04-21 22:03:05 +00003477 DEBUG_WITH_TYPE("mach-o-bind", dbgs() << "BIND_OPCODE_DONE\n");
Nick Kledzik367cf702014-09-16 01:41:51 +00003478 break;
3479 case MachO::BIND_OPCODE_SET_DYLIB_ORDINAL_IMM:
Kevin Enderby3903b472017-03-27 20:09:23 +00003480 if (TableKind == Kind::Weak) {
3481 *E = malformedError("BIND_OPCODE_SET_DYLIB_ORDINAL_IMM not allowed in "
Benjamin Kramerefa50a22017-08-20 15:13:39 +00003482 "weak bind table for opcode at: 0x" +
3483 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
Kevin Enderby3903b472017-03-27 20:09:23 +00003484 moveToEnd();
3485 return;
3486 }
Nick Kledzik367cf702014-09-16 01:41:51 +00003487 Ordinal = ImmValue;
Kevin Enderby1ae32f12017-03-20 19:46:55 +00003488 LibraryOrdinalSet = true;
Kevin Enderby505b7702017-02-28 21:47:07 +00003489 if (ImmValue > O->getLibraryCount()) {
3490 *E = malformedError("for BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB bad "
Benjamin Kramerefa50a22017-08-20 15:13:39 +00003491 "library ordinal: " +
3492 Twine((int)ImmValue) + " (max " +
3493 Twine((int)O->getLibraryCount()) +
3494 ") for opcode at: 0x" +
3495 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
Kevin Enderby505b7702017-02-28 21:47:07 +00003496 moveToEnd();
3497 return;
3498 }
Nick Kledzik367cf702014-09-16 01:41:51 +00003499 DEBUG_WITH_TYPE(
3500 "mach-o-bind",
Eugene Zelenko903f87e2017-04-21 22:03:05 +00003501 dbgs() << "BIND_OPCODE_SET_DYLIB_ORDINAL_IMM: "
3502 << "Ordinal=" << Ordinal << "\n");
Nick Kledzik367cf702014-09-16 01:41:51 +00003503 break;
3504 case MachO::BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB:
Kevin Enderby3903b472017-03-27 20:09:23 +00003505 if (TableKind == Kind::Weak) {
3506 *E = malformedError("BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB not allowed in "
Benjamin Kramerefa50a22017-08-20 15:13:39 +00003507 "weak bind table for opcode at: 0x" +
3508 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
Kevin Enderby3903b472017-03-27 20:09:23 +00003509 moveToEnd();
3510 return;
3511 }
Kevin Enderby1ae32f12017-03-20 19:46:55 +00003512 Ordinal = readULEB128(&error);
3513 LibraryOrdinalSet = true;
3514 if (error) {
3515 *E = malformedError("for BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB " +
Benjamin Kramerefa50a22017-08-20 15:13:39 +00003516 Twine(error) + " for opcode at: 0x" +
3517 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
Kevin Enderby1ae32f12017-03-20 19:46:55 +00003518 moveToEnd();
3519 return;
3520 }
3521 if (Ordinal > (int)O->getLibraryCount()) {
3522 *E = malformedError("for BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB bad "
Benjamin Kramerefa50a22017-08-20 15:13:39 +00003523 "library ordinal: " +
3524 Twine((int)Ordinal) + " (max " +
3525 Twine((int)O->getLibraryCount()) +
3526 ") for opcode at: 0x" +
3527 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
Kevin Enderby1ae32f12017-03-20 19:46:55 +00003528 moveToEnd();
3529 return;
3530 }
Nick Kledzik367cf702014-09-16 01:41:51 +00003531 DEBUG_WITH_TYPE(
3532 "mach-o-bind",
Eugene Zelenko903f87e2017-04-21 22:03:05 +00003533 dbgs() << "BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB: "
3534 << "Ordinal=" << Ordinal << "\n");
Nick Kledzik367cf702014-09-16 01:41:51 +00003535 break;
3536 case MachO::BIND_OPCODE_SET_DYLIB_SPECIAL_IMM:
Kevin Enderby3903b472017-03-27 20:09:23 +00003537 if (TableKind == Kind::Weak) {
3538 *E = malformedError("BIND_OPCODE_SET_DYLIB_SPECIAL_IMM not allowed in "
Benjamin Kramerefa50a22017-08-20 15:13:39 +00003539 "weak bind table for opcode at: 0x" +
3540 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
Kevin Enderby3903b472017-03-27 20:09:23 +00003541 moveToEnd();
3542 return;
3543 }
Nick Kledzik367cf702014-09-16 01:41:51 +00003544 if (ImmValue) {
3545 SignExtended = MachO::BIND_OPCODE_MASK | ImmValue;
3546 Ordinal = SignExtended;
Kevin Enderby1ae32f12017-03-20 19:46:55 +00003547 if (Ordinal < MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP) {
3548 *E = malformedError("for BIND_OPCODE_SET_DYLIB_SPECIAL_IMM unknown "
Benjamin Kramerefa50a22017-08-20 15:13:39 +00003549 "special ordinal: " +
3550 Twine((int)Ordinal) + " for opcode at: 0x" +
3551 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
Kevin Enderby1ae32f12017-03-20 19:46:55 +00003552 moveToEnd();
3553 return;
3554 }
Nick Kledzik367cf702014-09-16 01:41:51 +00003555 } else
3556 Ordinal = 0;
Steven Wub2ab2732017-05-31 22:17:43 +00003557 LibraryOrdinalSet = true;
Nick Kledzik367cf702014-09-16 01:41:51 +00003558 DEBUG_WITH_TYPE(
3559 "mach-o-bind",
Eugene Zelenko903f87e2017-04-21 22:03:05 +00003560 dbgs() << "BIND_OPCODE_SET_DYLIB_SPECIAL_IMM: "
3561 << "Ordinal=" << Ordinal << "\n");
Nick Kledzik367cf702014-09-16 01:41:51 +00003562 break;
3563 case MachO::BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM:
3564 Flags = ImmValue;
3565 SymStart = Ptr;
Kevin Enderby1ae32f12017-03-20 19:46:55 +00003566 while (*Ptr && (Ptr < Opcodes.end())) {
Nick Kledzik367cf702014-09-16 01:41:51 +00003567 ++Ptr;
3568 }
Kevin Enderby1ae32f12017-03-20 19:46:55 +00003569 if (Ptr == Opcodes.end()) {
Benjamin Kramerefa50a22017-08-20 15:13:39 +00003570 *E = malformedError(
3571 "for BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM "
3572 "symbol name extends past opcodes for opcode at: 0x" +
3573 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3574 moveToEnd();
3575 return;
Kevin Enderby1ae32f12017-03-20 19:46:55 +00003576 }
Nick Kledzik367cf702014-09-16 01:41:51 +00003577 SymbolName = StringRef(reinterpret_cast<const char*>(SymStart),
3578 Ptr-SymStart);
Nick Kledzik22d885d2014-09-17 01:51:43 +00003579 ++Ptr;
Nick Kledzik367cf702014-09-16 01:41:51 +00003580 DEBUG_WITH_TYPE(
3581 "mach-o-bind",
Eugene Zelenko903f87e2017-04-21 22:03:05 +00003582 dbgs() << "BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM: "
3583 << "SymbolName=" << SymbolName << "\n");
Nick Kledzik367cf702014-09-16 01:41:51 +00003584 if (TableKind == Kind::Weak) {
3585 if (ImmValue & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION)
3586 return;
3587 }
3588 break;
3589 case MachO::BIND_OPCODE_SET_TYPE_IMM:
3590 BindType = ImmValue;
Kevin Enderby1ae32f12017-03-20 19:46:55 +00003591 if (ImmValue > MachO::BIND_TYPE_TEXT_PCREL32) {
Benjamin Kramerefa50a22017-08-20 15:13:39 +00003592 *E = malformedError("for BIND_OPCODE_SET_TYPE_IMM bad bind type: " +
3593 Twine((int)ImmValue) + " for opcode at: 0x" +
3594 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
3595 moveToEnd();
3596 return;
Kevin Enderby1ae32f12017-03-20 19:46:55 +00003597 }
Nick Kledzik367cf702014-09-16 01:41:51 +00003598 DEBUG_WITH_TYPE(
3599 "mach-o-bind",
Eugene Zelenko903f87e2017-04-21 22:03:05 +00003600 dbgs() << "BIND_OPCODE_SET_TYPE_IMM: "
3601 << "BindType=" << (int)BindType << "\n");
Nick Kledzik367cf702014-09-16 01:41:51 +00003602 break;
3603 case MachO::BIND_OPCODE_SET_ADDEND_SLEB:
Kevin Enderby1ae32f12017-03-20 19:46:55 +00003604 Addend = readSLEB128(&error);
3605 if (error) {
Benjamin Kramerefa50a22017-08-20 15:13:39 +00003606 *E = malformedError("for BIND_OPCODE_SET_ADDEND_SLEB " + Twine(error) +
3607 " for opcode at: 0x" +
3608 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
Kevin Enderby1ae32f12017-03-20 19:46:55 +00003609 moveToEnd();
3610 return;
3611 }
Nick Kledzik367cf702014-09-16 01:41:51 +00003612 DEBUG_WITH_TYPE(
3613 "mach-o-bind",
Eugene Zelenko903f87e2017-04-21 22:03:05 +00003614 dbgs() << "BIND_OPCODE_SET_ADDEND_SLEB: "
3615 << "Addend=" << Addend << "\n");
Nick Kledzik367cf702014-09-16 01:41:51 +00003616 break;
3617 case MachO::BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:
3618 SegmentIndex = ImmValue;
Kevin Enderby1ae32f12017-03-20 19:46:55 +00003619 SegmentOffset = readULEB128(&error);
3620 if (error) {
3621 *E = malformedError("for BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB " +
Benjamin Kramerefa50a22017-08-20 15:13:39 +00003622 Twine(error) + " for opcode at: 0x" +
3623 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
Kevin Enderby1ae32f12017-03-20 19:46:55 +00003624 moveToEnd();
3625 return;
3626 }
3627 error = O->BindEntryCheckSegAndOffset(SegmentIndex, SegmentOffset, true);
3628 if (error) {
3629 *E = malformedError("for BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB " +
Benjamin Kramerefa50a22017-08-20 15:13:39 +00003630 Twine(error) + " for opcode at: 0x" +
3631 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
Kevin Enderby1ae32f12017-03-20 19:46:55 +00003632 moveToEnd();
3633 return;
3634 }
Nick Kledzik367cf702014-09-16 01:41:51 +00003635 DEBUG_WITH_TYPE(
3636 "mach-o-bind",
Eugene Zelenko903f87e2017-04-21 22:03:05 +00003637 dbgs() << "BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: "
3638 << "SegmentIndex=" << SegmentIndex << ", "
3639 << format("SegmentOffset=0x%06X", SegmentOffset)
3640 << "\n");
Nick Kledzik367cf702014-09-16 01:41:51 +00003641 break;
3642 case MachO::BIND_OPCODE_ADD_ADDR_ULEB:
Kevin Enderby1ae32f12017-03-20 19:46:55 +00003643 SegmentOffset += readULEB128(&error);
3644 if (error) {
Benjamin Kramerefa50a22017-08-20 15:13:39 +00003645 *E = malformedError("for BIND_OPCODE_ADD_ADDR_ULEB " + Twine(error) +
3646 " for opcode at: 0x" +
3647 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
Kevin Enderby1ae32f12017-03-20 19:46:55 +00003648 moveToEnd();
3649 return;
3650 }
3651 error = O->BindEntryCheckSegAndOffset(SegmentIndex, SegmentOffset, true);
3652 if (error) {
Benjamin Kramerefa50a22017-08-20 15:13:39 +00003653 *E = malformedError("for BIND_OPCODE_ADD_ADDR_ULEB " + Twine(error) +
3654 " for opcode at: 0x" +
3655 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
Kevin Enderby1ae32f12017-03-20 19:46:55 +00003656 moveToEnd();
3657 return;
3658 }
Nick Kledzik367cf702014-09-16 01:41:51 +00003659 DEBUG_WITH_TYPE("mach-o-bind",
Eugene Zelenko903f87e2017-04-21 22:03:05 +00003660 dbgs() << "BIND_OPCODE_ADD_ADDR_ULEB: "
3661 << format("SegmentOffset=0x%06X",
3662 SegmentOffset) << "\n");
Nick Kledzik367cf702014-09-16 01:41:51 +00003663 break;
3664 case MachO::BIND_OPCODE_DO_BIND:
3665 AdvanceAmount = PointerSize;
3666 RemainingLoopCount = 0;
Kevin Enderby1ae32f12017-03-20 19:46:55 +00003667 error = O->BindEntryCheckSegAndOffset(SegmentIndex, SegmentOffset, true);
3668 if (error) {
3669 *E = malformedError("for BIND_OPCODE_DO_BIND " + Twine(error) +
Benjamin Kramerefa50a22017-08-20 15:13:39 +00003670 " for opcode at: 0x" +
3671 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
Kevin Enderby1ae32f12017-03-20 19:46:55 +00003672 moveToEnd();
3673 return;
3674 }
3675 if (SymbolName == StringRef()) {
Benjamin Kramerefa50a22017-08-20 15:13:39 +00003676 *E = malformedError(
3677 "for BIND_OPCODE_DO_BIND missing preceding "
3678 "BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM for opcode at: 0x" +
3679 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
Kevin Enderby1ae32f12017-03-20 19:46:55 +00003680 moveToEnd();
3681 return;
3682 }
3683 if (!LibraryOrdinalSet && TableKind != Kind::Weak) {
Benjamin Kramerefa50a22017-08-20 15:13:39 +00003684 *E =
3685 malformedError("for BIND_OPCODE_DO_BIND missing preceding "
3686 "BIND_OPCODE_SET_DYLIB_ORDINAL_* for opcode at: 0x" +
3687 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
Kevin Enderby1ae32f12017-03-20 19:46:55 +00003688 moveToEnd();
3689 return;
3690 }
Nick Kledzik367cf702014-09-16 01:41:51 +00003691 DEBUG_WITH_TYPE("mach-o-bind",
Eugene Zelenko903f87e2017-04-21 22:03:05 +00003692 dbgs() << "BIND_OPCODE_DO_BIND: "
3693 << format("SegmentOffset=0x%06X",
3694 SegmentOffset) << "\n");
Nick Kledzik367cf702014-09-16 01:41:51 +00003695 return;
3696 case MachO::BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB:
Kevin Enderby3903b472017-03-27 20:09:23 +00003697 if (TableKind == Kind::Lazy) {
3698 *E = malformedError("BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB not allowed in "
Benjamin Kramerefa50a22017-08-20 15:13:39 +00003699 "lazy bind table for opcode at: 0x" +
3700 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
Kevin Enderby3903b472017-03-27 20:09:23 +00003701 moveToEnd();
3702 return;
3703 }
Kevin Enderby1ae32f12017-03-20 19:46:55 +00003704 error = O->BindEntryCheckSegAndOffset(SegmentIndex, SegmentOffset, true);
3705 if (error) {
3706 *E = malformedError("for BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB " +
Benjamin Kramerefa50a22017-08-20 15:13:39 +00003707 Twine(error) + " for opcode at: 0x" +
3708 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
Kevin Enderby1ae32f12017-03-20 19:46:55 +00003709 moveToEnd();
3710 return;
3711 }
3712 if (SymbolName == StringRef()) {
Benjamin Kramerefa50a22017-08-20 15:13:39 +00003713 *E = malformedError(
3714 "for BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB missing "
3715 "preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM for opcode "
3716 "at: 0x" +
3717 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
Kevin Enderby1ae32f12017-03-20 19:46:55 +00003718 moveToEnd();
3719 return;
3720 }
3721 if (!LibraryOrdinalSet && TableKind != Kind::Weak) {
Benjamin Kramerefa50a22017-08-20 15:13:39 +00003722 *E = malformedError(
3723 "for BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB missing "
3724 "preceding BIND_OPCODE_SET_DYLIB_ORDINAL_* for opcode at: 0x" +
3725 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
Kevin Enderby1ae32f12017-03-20 19:46:55 +00003726 moveToEnd();
3727 return;
3728 }
3729 AdvanceAmount = readULEB128(&error) + PointerSize;
3730 if (error) {
3731 *E = malformedError("for BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB " +
Benjamin Kramerefa50a22017-08-20 15:13:39 +00003732 Twine(error) + " for opcode at: 0x" +
3733 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
Kevin Enderby1ae32f12017-03-20 19:46:55 +00003734 moveToEnd();
3735 return;
3736 }
3737 // Note, this is not really an error until the next bind but make no sense
3738 // for a BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB to not be followed by another
3739 // bind operation.
3740 error = O->BindEntryCheckSegAndOffset(SegmentIndex, SegmentOffset +
3741 AdvanceAmount, false);
3742 if (error) {
3743 *E = malformedError("for BIND_OPCODE_ADD_ADDR_ULEB (after adding "
Benjamin Kramerefa50a22017-08-20 15:13:39 +00003744 "ULEB) " +
3745 Twine(error) + " for opcode at: 0x" +
3746 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
Kevin Enderby1ae32f12017-03-20 19:46:55 +00003747 moveToEnd();
3748 return;
3749 }
Nick Kledzik367cf702014-09-16 01:41:51 +00003750 RemainingLoopCount = 0;
Nick Kledzik367cf702014-09-16 01:41:51 +00003751 DEBUG_WITH_TYPE(
3752 "mach-o-bind",
Eugene Zelenko903f87e2017-04-21 22:03:05 +00003753 dbgs() << "BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB: "
3754 << format("SegmentOffset=0x%06X", SegmentOffset)
3755 << ", AdvanceAmount=" << AdvanceAmount
3756 << ", RemainingLoopCount=" << RemainingLoopCount
3757 << "\n");
Nick Kledzik367cf702014-09-16 01:41:51 +00003758 return;
3759 case MachO::BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED:
Kevin Enderby3903b472017-03-27 20:09:23 +00003760 if (TableKind == Kind::Lazy) {
3761 *E = malformedError("BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED not "
Benjamin Kramerefa50a22017-08-20 15:13:39 +00003762 "allowed in lazy bind table for opcode at: 0x" +
3763 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
Kevin Enderby3903b472017-03-27 20:09:23 +00003764 moveToEnd();
3765 return;
3766 }
Kevin Enderby1ae32f12017-03-20 19:46:55 +00003767 error = O->BindEntryCheckSegAndOffset(SegmentIndex, SegmentOffset, true);
3768 if (error) {
3769 *E = malformedError("for BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED " +
Benjamin Kramerefa50a22017-08-20 15:13:39 +00003770 Twine(error) + " for opcode at: 0x" +
3771 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
Kevin Enderby1ae32f12017-03-20 19:46:55 +00003772 moveToEnd();
3773 return;
3774 }
3775 if (SymbolName == StringRef()) {
Benjamin Kramerefa50a22017-08-20 15:13:39 +00003776 *E = malformedError(
3777 "for BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED "
3778 "missing preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM for "
3779 "opcode at: 0x" +
3780 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
Kevin Enderby1ae32f12017-03-20 19:46:55 +00003781 moveToEnd();
3782 return;
3783 }
3784 if (!LibraryOrdinalSet && TableKind != Kind::Weak) {
Benjamin Kramerefa50a22017-08-20 15:13:39 +00003785 *E = malformedError(
3786 "for BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED "
3787 "missing preceding BIND_OPCODE_SET_DYLIB_ORDINAL_* for opcode "
3788 "at: 0x" +
3789 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
Kevin Enderby1ae32f12017-03-20 19:46:55 +00003790 moveToEnd();
3791 return;
3792 }
Nick Kledzik50ede162014-10-18 01:21:02 +00003793 AdvanceAmount = ImmValue * PointerSize + PointerSize;
Nick Kledzik367cf702014-09-16 01:41:51 +00003794 RemainingLoopCount = 0;
Kevin Enderby1ae32f12017-03-20 19:46:55 +00003795 error = O->BindEntryCheckSegAndOffset(SegmentIndex, SegmentOffset +
3796 AdvanceAmount, false);
3797 if (error) {
Benjamin Kramerefa50a22017-08-20 15:13:39 +00003798 *E =
3799 malformedError("for BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED "
3800 " (after adding immediate times the pointer size) " +
3801 Twine(error) + " for opcode at: 0x" +
3802 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
Kevin Enderby1ae32f12017-03-20 19:46:55 +00003803 moveToEnd();
3804 return;
3805 }
Nick Kledzik367cf702014-09-16 01:41:51 +00003806 DEBUG_WITH_TYPE("mach-o-bind",
Eugene Zelenko903f87e2017-04-21 22:03:05 +00003807 dbgs()
Nick Kledzik367cf702014-09-16 01:41:51 +00003808 << "BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED: "
Eugene Zelenko903f87e2017-04-21 22:03:05 +00003809 << format("SegmentOffset=0x%06X", SegmentOffset) << "\n");
Nick Kledzik367cf702014-09-16 01:41:51 +00003810 return;
3811 case MachO::BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB:
Kevin Enderby3903b472017-03-27 20:09:23 +00003812 if (TableKind == Kind::Lazy) {
3813 *E = malformedError("BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB not "
Benjamin Kramerefa50a22017-08-20 15:13:39 +00003814 "allowed in lazy bind table for opcode at: 0x" +
3815 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
Kevin Enderby3903b472017-03-27 20:09:23 +00003816 moveToEnd();
3817 return;
3818 }
Kevin Enderby1ae32f12017-03-20 19:46:55 +00003819 Count = readULEB128(&error);
3820 if (Count != 0)
3821 RemainingLoopCount = Count - 1;
3822 else
3823 RemainingLoopCount = 0;
3824 if (error) {
3825 *E = malformedError("for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB "
Benjamin Kramerefa50a22017-08-20 15:13:39 +00003826 " (count value) " +
3827 Twine(error) + " for opcode at: 0x" +
3828 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
Kevin Enderby1ae32f12017-03-20 19:46:55 +00003829 moveToEnd();
3830 return;
3831 }
3832 Skip = readULEB128(&error);
3833 AdvanceAmount = Skip + PointerSize;
3834 if (error) {
3835 *E = malformedError("for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB "
Benjamin Kramerefa50a22017-08-20 15:13:39 +00003836 " (skip value) " +
3837 Twine(error) + " for opcode at: 0x" +
3838 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
Kevin Enderby1ae32f12017-03-20 19:46:55 +00003839 moveToEnd();
3840 return;
3841 }
3842 error = O->BindEntryCheckSegAndOffset(SegmentIndex, SegmentOffset, true);
3843 if (error) {
Benjamin Kramerefa50a22017-08-20 15:13:39 +00003844 *E =
3845 malformedError("for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB " +
3846 Twine(error) + " for opcode at: 0x" +
3847 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
Kevin Enderby1ae32f12017-03-20 19:46:55 +00003848 moveToEnd();
3849 return;
3850 }
3851 if (SymbolName == StringRef()) {
Benjamin Kramerefa50a22017-08-20 15:13:39 +00003852 *E = malformedError(
3853 "for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB "
3854 "missing preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM for "
3855 "opcode at: 0x" +
3856 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
Kevin Enderby1ae32f12017-03-20 19:46:55 +00003857 moveToEnd();
3858 return;
3859 }
3860 if (!LibraryOrdinalSet && TableKind != Kind::Weak) {
Benjamin Kramerefa50a22017-08-20 15:13:39 +00003861 *E = malformedError(
3862 "for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB "
3863 "missing preceding BIND_OPCODE_SET_DYLIB_ORDINAL_* for opcode "
3864 "at: 0x" +
3865 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
Kevin Enderby1ae32f12017-03-20 19:46:55 +00003866 moveToEnd();
3867 return;
3868 }
3869 error = O->BindEntryCheckCountAndSkip(Count, Skip, PointerSize,
3870 SegmentIndex, SegmentOffset);
3871 if (error) {
Benjamin Kramerefa50a22017-08-20 15:13:39 +00003872 *E =
3873 malformedError("for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB " +
3874 Twine(error) + " for opcode at: 0x" +
3875 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
Kevin Enderby1ae32f12017-03-20 19:46:55 +00003876 moveToEnd();
NAKAMURA Takumief15f2c2017-08-28 06:47:47 +00003877 return;
Kevin Enderby1ae32f12017-03-20 19:46:55 +00003878 }
Nick Kledzik367cf702014-09-16 01:41:51 +00003879 DEBUG_WITH_TYPE(
3880 "mach-o-bind",
Eugene Zelenko903f87e2017-04-21 22:03:05 +00003881 dbgs() << "BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB: "
3882 << format("SegmentOffset=0x%06X", SegmentOffset)
3883 << ", AdvanceAmount=" << AdvanceAmount
3884 << ", RemainingLoopCount=" << RemainingLoopCount
3885 << "\n");
Nick Kledzik367cf702014-09-16 01:41:51 +00003886 return;
3887 default:
Kevin Enderby1ae32f12017-03-20 19:46:55 +00003888 *E = malformedError("bad bind info (bad opcode value 0x" +
Benjamin Kramerefa50a22017-08-20 15:13:39 +00003889 Twine::utohexstr(Opcode) + " for opcode at: 0x" +
3890 Twine::utohexstr(OpcodeStart - Opcodes.begin()));
Kevin Enderby1ae32f12017-03-20 19:46:55 +00003891 moveToEnd();
3892 return;
Nick Kledzik367cf702014-09-16 01:41:51 +00003893 }
3894 }
3895}
3896
Kevin Enderby1ae32f12017-03-20 19:46:55 +00003897uint64_t MachOBindEntry::readULEB128(const char **error) {
Nick Kledzik367cf702014-09-16 01:41:51 +00003898 unsigned Count;
Kevin Enderby1ae32f12017-03-20 19:46:55 +00003899 uint64_t Result = decodeULEB128(Ptr, &Count, Opcodes.end(), error);
Nick Kledzik367cf702014-09-16 01:41:51 +00003900 Ptr += Count;
Kevin Enderby3903b472017-03-27 20:09:23 +00003901 if (Ptr > Opcodes.end())
Nick Kledzik367cf702014-09-16 01:41:51 +00003902 Ptr = Opcodes.end();
Nick Kledzik367cf702014-09-16 01:41:51 +00003903 return Result;
3904}
3905
Kevin Enderby1ae32f12017-03-20 19:46:55 +00003906int64_t MachOBindEntry::readSLEB128(const char **error) {
Nick Kledzik367cf702014-09-16 01:41:51 +00003907 unsigned Count;
Kevin Enderby1ae32f12017-03-20 19:46:55 +00003908 int64_t Result = decodeSLEB128(Ptr, &Count, Opcodes.end(), error);
Nick Kledzik367cf702014-09-16 01:41:51 +00003909 Ptr += Count;
Kevin Enderby3903b472017-03-27 20:09:23 +00003910 if (Ptr > Opcodes.end())
Nick Kledzik367cf702014-09-16 01:41:51 +00003911 Ptr = Opcodes.end();
Nick Kledzik367cf702014-09-16 01:41:51 +00003912 return Result;
3913}
3914
Kevin Enderby1ae32f12017-03-20 19:46:55 +00003915int32_t MachOBindEntry::segmentIndex() const { return SegmentIndex; }
Nick Kledzik367cf702014-09-16 01:41:51 +00003916
3917uint64_t MachOBindEntry::segmentOffset() const { return SegmentOffset; }
3918
3919StringRef MachOBindEntry::typeName() const {
3920 switch (BindType) {
3921 case MachO::BIND_TYPE_POINTER:
3922 return "pointer";
3923 case MachO::BIND_TYPE_TEXT_ABSOLUTE32:
3924 return "text abs32";
3925 case MachO::BIND_TYPE_TEXT_PCREL32:
3926 return "text rel32";
3927 }
3928 return "unknown";
3929}
3930
3931StringRef MachOBindEntry::symbolName() const { return SymbolName; }
3932
3933int64_t MachOBindEntry::addend() const { return Addend; }
3934
3935uint32_t MachOBindEntry::flags() const { return Flags; }
3936
3937int MachOBindEntry::ordinal() const { return Ordinal; }
3938
Kevin Enderby1ae32f12017-03-20 19:46:55 +00003939// For use with the SegIndex of a checked Mach-O Bind entry
3940// to get the segment name.
3941StringRef MachOBindEntry::segmentName() const {
3942 return O->BindRebaseSegmentName(SegmentIndex);
3943}
3944
3945// For use with a SegIndex,SegOffset pair from a checked Mach-O Bind entry
3946// to get the section name.
3947StringRef MachOBindEntry::sectionName() const {
3948 return O->BindRebaseSectionName(SegmentIndex, SegmentOffset);
3949}
3950
3951// For use with a SegIndex,SegOffset pair from a checked Mach-O Bind entry
3952// to get the address.
3953uint64_t MachOBindEntry::address() const {
3954 return O->BindRebaseAddress(SegmentIndex, SegmentOffset);
3955}
3956
Nick Kledzik367cf702014-09-16 01:41:51 +00003957bool MachOBindEntry::operator==(const MachOBindEntry &Other) const {
Saleem Abdulrasool8204fd72017-01-08 19:14:15 +00003958#ifdef EXPENSIVE_CHECKS
Nick Kledzik367cf702014-09-16 01:41:51 +00003959 assert(Opcodes == Other.Opcodes && "compare iterators of different files");
Saleem Abdulrasool8204fd72017-01-08 19:14:15 +00003960#else
3961 assert(Opcodes.data() == Other.Opcodes.data() && "compare iterators of different files");
3962#endif
Nick Kledzik367cf702014-09-16 01:41:51 +00003963 return (Ptr == Other.Ptr) &&
3964 (RemainingLoopCount == Other.RemainingLoopCount) &&
3965 (Done == Other.Done);
3966}
3967
Kevin Enderby1ae32f12017-03-20 19:46:55 +00003968// Build table of sections so SegIndex/SegOffset pairs can be translated.
3969BindRebaseSegInfo::BindRebaseSegInfo(const object::MachOObjectFile *Obj) {
3970 uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
3971 StringRef CurSegName;
3972 uint64_t CurSegAddress;
3973 for (const SectionRef &Section : Obj->sections()) {
3974 SectionInfo Info;
3975 Section.getName(Info.SectionName);
3976 Info.Address = Section.getAddress();
3977 Info.Size = Section.getSize();
3978 Info.SegmentName =
3979 Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
3980 if (!Info.SegmentName.equals(CurSegName)) {
3981 ++CurSegIndex;
3982 CurSegName = Info.SegmentName;
3983 CurSegAddress = Info.Address;
3984 }
3985 Info.SegmentIndex = CurSegIndex - 1;
3986 Info.OffsetInSegment = Info.Address - CurSegAddress;
3987 Info.SegmentStartAddress = CurSegAddress;
3988 Sections.push_back(Info);
3989 }
3990 MaxSegIndex = CurSegIndex;
3991}
3992
3993// For use with a SegIndex,SegOffset pair in MachOBindEntry::moveNext() to
Kevin Enderby3903b472017-03-27 20:09:23 +00003994// validate a MachOBindEntry or MachORebaseEntry.
Kevin Enderby1ae32f12017-03-20 19:46:55 +00003995const char * BindRebaseSegInfo::checkSegAndOffset(int32_t SegIndex,
3996 uint64_t SegOffset,
3997 bool endInvalid) {
3998 if (SegIndex == -1)
Kevin Enderby3903b472017-03-27 20:09:23 +00003999 return "missing preceding *_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB";
Kevin Enderby1ae32f12017-03-20 19:46:55 +00004000 if (SegIndex >= MaxSegIndex)
4001 return "bad segIndex (too large)";
4002 for (const SectionInfo &SI : Sections) {
4003 if (SI.SegmentIndex != SegIndex)
4004 continue;
4005 if (SI.OffsetInSegment > SegOffset)
4006 continue;
4007 if (SegOffset > (SI.OffsetInSegment + SI.Size))
4008 continue;
4009 if (endInvalid && SegOffset >= (SI.OffsetInSegment + SI.Size))
4010 continue;
4011 return nullptr;
4012 }
4013 return "bad segOffset, too large";
4014}
4015
4016// For use in MachOBindEntry::moveNext() to validate a MachOBindEntry for
Kevin Enderby3903b472017-03-27 20:09:23 +00004017// the BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB opcode and for use in
4018// MachORebaseEntry::moveNext() to validate a MachORebaseEntry for
4019// REBASE_OPCODE_DO_*_TIMES* opcodes. The SegIndex and SegOffset must have
4020// been already checked.
Kevin Enderby1ae32f12017-03-20 19:46:55 +00004021const char * BindRebaseSegInfo::checkCountAndSkip(uint32_t Count, uint32_t Skip,
4022 uint8_t PointerSize,
Kevin Enderby3903b472017-03-27 20:09:23 +00004023 int32_t SegIndex,
4024 uint64_t SegOffset) {
Kevin Enderby1ae32f12017-03-20 19:46:55 +00004025 const SectionInfo &SI = findSection(SegIndex, SegOffset);
4026 uint64_t addr = SI.SegmentStartAddress + SegOffset;
4027 if (addr >= SI.Address + SI.Size)
4028 return "bad segOffset, too large";
4029 uint64_t i = 0;
4030 if (Count > 1)
4031 i = (Skip + PointerSize) * (Count - 1);
Kevin Enderby3903b472017-03-27 20:09:23 +00004032 else if (Count == 1)
4033 i = Skip + PointerSize;
4034 if (addr + i >= SI.Address + SI.Size) {
4035 // For rebase opcodes they can step from one section to another.
4036 uint64_t TrailingSegOffset = (addr + i) - SI.SegmentStartAddress;
4037 const char *error = checkSegAndOffset(SegIndex, TrailingSegOffset, false);
4038 if (error)
4039 return "bad count and skip, too large";
4040 }
Kevin Enderby1ae32f12017-03-20 19:46:55 +00004041 return nullptr;
4042}
4043
4044// For use with the SegIndex of a checked Mach-O Bind or Rebase entry
4045// to get the segment name.
4046StringRef BindRebaseSegInfo::segmentName(int32_t SegIndex) {
4047 for (const SectionInfo &SI : Sections) {
4048 if (SI.SegmentIndex == SegIndex)
4049 return SI.SegmentName;
4050 }
4051 llvm_unreachable("invalid SegIndex");
4052}
4053
4054// For use with a SegIndex,SegOffset pair from a checked Mach-O Bind or Rebase
4055// to get the SectionInfo.
4056const BindRebaseSegInfo::SectionInfo &BindRebaseSegInfo::findSection(
4057 int32_t SegIndex, uint64_t SegOffset) {
4058 for (const SectionInfo &SI : Sections) {
4059 if (SI.SegmentIndex != SegIndex)
4060 continue;
4061 if (SI.OffsetInSegment > SegOffset)
4062 continue;
4063 if (SegOffset >= (SI.OffsetInSegment + SI.Size))
4064 continue;
4065 return SI;
4066 }
4067 llvm_unreachable("SegIndex and SegOffset not in any section");
4068}
4069
4070// For use with a SegIndex,SegOffset pair from a checked Mach-O Bind or Rebase
4071// entry to get the section name.
4072StringRef BindRebaseSegInfo::sectionName(int32_t SegIndex,
4073 uint64_t SegOffset) {
4074 return findSection(SegIndex, SegOffset).SectionName;
4075}
4076
4077// For use with a SegIndex,SegOffset pair from a checked Mach-O Bind or Rebase
4078// entry to get the address.
4079uint64_t BindRebaseSegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
4080 const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
4081 return SI.SegmentStartAddress + OffsetInSeg;
4082}
4083
Nick Kledzik367cf702014-09-16 01:41:51 +00004084iterator_range<bind_iterator>
Kevin Enderby1ae32f12017-03-20 19:46:55 +00004085MachOObjectFile::bindTable(Error &Err, MachOObjectFile *O,
Kevin Enderby505b7702017-02-28 21:47:07 +00004086 ArrayRef<uint8_t> Opcodes, bool is64,
Nick Kledzik367cf702014-09-16 01:41:51 +00004087 MachOBindEntry::Kind BKind) {
Kevin Enderby1ae32f12017-03-20 19:46:55 +00004088 if (O->BindRebaseSectionTable == nullptr)
4089 O->BindRebaseSectionTable = llvm::make_unique<BindRebaseSegInfo>(O);
Kevin Enderby505b7702017-02-28 21:47:07 +00004090 MachOBindEntry Start(&Err, O, Opcodes, is64, BKind);
Nick Kledzik367cf702014-09-16 01:41:51 +00004091 Start.moveToFirst();
4092
Kevin Enderby505b7702017-02-28 21:47:07 +00004093 MachOBindEntry Finish(&Err, O, Opcodes, is64, BKind);
Nick Kledzik367cf702014-09-16 01:41:51 +00004094 Finish.moveToEnd();
4095
Craig Toppere6bc7d12015-12-06 05:08:07 +00004096 return make_range(bind_iterator(Start), bind_iterator(Finish));
Nick Kledzik367cf702014-09-16 01:41:51 +00004097}
4098
Kevin Enderby1ae32f12017-03-20 19:46:55 +00004099iterator_range<bind_iterator> MachOObjectFile::bindTable(Error &Err) {
Kevin Enderby505b7702017-02-28 21:47:07 +00004100 return bindTable(Err, this, getDyldInfoBindOpcodes(), is64Bit(),
Nick Kledzik367cf702014-09-16 01:41:51 +00004101 MachOBindEntry::Kind::Regular);
4102}
4103
Kevin Enderby1ae32f12017-03-20 19:46:55 +00004104iterator_range<bind_iterator> MachOObjectFile::lazyBindTable(Error &Err) {
Kevin Enderby505b7702017-02-28 21:47:07 +00004105 return bindTable(Err, this, getDyldInfoLazyBindOpcodes(), is64Bit(),
Nick Kledzik367cf702014-09-16 01:41:51 +00004106 MachOBindEntry::Kind::Lazy);
4107}
4108
Kevin Enderby1ae32f12017-03-20 19:46:55 +00004109iterator_range<bind_iterator> MachOObjectFile::weakBindTable(Error &Err) {
Kevin Enderby505b7702017-02-28 21:47:07 +00004110 return bindTable(Err, this, getDyldInfoWeakBindOpcodes(), is64Bit(),
Nick Kledzik367cf702014-09-16 01:41:51 +00004111 MachOBindEntry::Kind::Weak);
4112}
4113
Alexey Samsonov40ec40a2015-06-03 22:19:36 +00004114MachOObjectFile::load_command_iterator
4115MachOObjectFile::begin_load_commands() const {
4116 return LoadCommands.begin();
4117}
4118
4119MachOObjectFile::load_command_iterator
4120MachOObjectFile::end_load_commands() const {
4121 return LoadCommands.end();
4122}
4123
4124iterator_range<MachOObjectFile::load_command_iterator>
4125MachOObjectFile::load_commands() const {
Craig Toppere6bc7d12015-12-06 05:08:07 +00004126 return make_range(begin_load_commands(), end_load_commands());
Alexey Samsonov40ec40a2015-06-03 22:19:36 +00004127}
4128
Rafael Espindolafd7aa382013-04-18 18:08:55 +00004129StringRef
4130MachOObjectFile::getSectionFinalSegmentName(DataRefImpl Sec) const {
4131 ArrayRef<char> Raw = getSectionRawFinalSegmentName(Sec);
4132 return parseSegmentOrSectionName(Raw.data());
4133}
4134
4135ArrayRef<char>
4136MachOObjectFile::getSectionRawName(DataRefImpl Sec) const {
Rafael Espindolacc3f1db2015-05-22 14:59:27 +00004137 assert(Sec.d.a < Sections.size() && "Should have detected this earlier");
Charles Davis55107282013-09-01 04:28:48 +00004138 const section_base *Base =
4139 reinterpret_cast<const section_base *>(Sections[Sec.d.a]);
Craig Topper35120342014-08-27 05:25:25 +00004140 return makeArrayRef(Base->sectname);
Rafael Espindolafd7aa382013-04-18 18:08:55 +00004141}
4142
4143ArrayRef<char>
4144MachOObjectFile::getSectionRawFinalSegmentName(DataRefImpl Sec) const {
Rafael Espindolacc3f1db2015-05-22 14:59:27 +00004145 assert(Sec.d.a < Sections.size() && "Should have detected this earlier");
Charles Davis55107282013-09-01 04:28:48 +00004146 const section_base *Base =
4147 reinterpret_cast<const section_base *>(Sections[Sec.d.a]);
Craig Topper35120342014-08-27 05:25:25 +00004148 return makeArrayRef(Base->segname);
Rafael Espindolafd7aa382013-04-18 18:08:55 +00004149}
4150
4151bool
Charles Davis55107282013-09-01 04:28:48 +00004152MachOObjectFile::isRelocationScattered(const MachO::any_relocation_info &RE)
Rafael Espindolafd7aa382013-04-18 18:08:55 +00004153 const {
Lang Hames85334ad2016-12-04 01:56:10 +00004154 if (getCPUType(*this) == MachO::CPU_TYPE_X86_64)
Rafael Espindolafd7aa382013-04-18 18:08:55 +00004155 return false;
Charles Davis55107282013-09-01 04:28:48 +00004156 return getPlainRelocationAddress(RE) & MachO::R_SCATTERED;
Rafael Espindolafd7aa382013-04-18 18:08:55 +00004157}
4158
Eric Christopher60d65912013-07-22 22:25:07 +00004159unsigned MachOObjectFile::getPlainRelocationSymbolNum(
Charles Davis55107282013-09-01 04:28:48 +00004160 const MachO::any_relocation_info &RE) const {
Rafael Espindolafd7aa382013-04-18 18:08:55 +00004161 if (isLittleEndian())
Charles Davis55107282013-09-01 04:28:48 +00004162 return RE.r_word1 & 0xffffff;
4163 return RE.r_word1 >> 8;
Rafael Espindolafd7aa382013-04-18 18:08:55 +00004164}
4165
Eric Christopher60d65912013-07-22 22:25:07 +00004166bool MachOObjectFile::getPlainRelocationExternal(
Charles Davis55107282013-09-01 04:28:48 +00004167 const MachO::any_relocation_info &RE) const {
Rafael Espindolafd7aa382013-04-18 18:08:55 +00004168 if (isLittleEndian())
Charles Davis55107282013-09-01 04:28:48 +00004169 return (RE.r_word1 >> 27) & 1;
4170 return (RE.r_word1 >> 4) & 1;
Rafael Espindolafd7aa382013-04-18 18:08:55 +00004171}
4172
Eric Christopher60d65912013-07-22 22:25:07 +00004173bool MachOObjectFile::getScatteredRelocationScattered(
Charles Davis55107282013-09-01 04:28:48 +00004174 const MachO::any_relocation_info &RE) const {
4175 return RE.r_word0 >> 31;
Rafael Espindolafd7aa382013-04-18 18:08:55 +00004176}
4177
Eric Christopher60d65912013-07-22 22:25:07 +00004178uint32_t MachOObjectFile::getScatteredRelocationValue(
Charles Davis55107282013-09-01 04:28:48 +00004179 const MachO::any_relocation_info &RE) const {
4180 return RE.r_word1;
Rafael Espindolafd7aa382013-04-18 18:08:55 +00004181}
4182
Kevin Enderbya2503222014-11-04 00:43:16 +00004183uint32_t MachOObjectFile::getScatteredRelocationType(
4184 const MachO::any_relocation_info &RE) const {
4185 return (RE.r_word0 >> 24) & 0xf;
4186}
4187
Eric Christopher60d65912013-07-22 22:25:07 +00004188unsigned MachOObjectFile::getAnyRelocationAddress(
Charles Davis55107282013-09-01 04:28:48 +00004189 const MachO::any_relocation_info &RE) const {
Rafael Espindolafd7aa382013-04-18 18:08:55 +00004190 if (isRelocationScattered(RE))
4191 return getScatteredRelocationAddress(RE);
4192 return getPlainRelocationAddress(RE);
4193}
4194
Charles Davis55107282013-09-01 04:28:48 +00004195unsigned MachOObjectFile::getAnyRelocationPCRel(
4196 const MachO::any_relocation_info &RE) const {
Rafael Espindolafd7aa382013-04-18 18:08:55 +00004197 if (isRelocationScattered(RE))
Lang Hames85334ad2016-12-04 01:56:10 +00004198 return getScatteredRelocationPCRel(RE);
4199 return getPlainRelocationPCRel(*this, RE);
Rafael Espindolafd7aa382013-04-18 18:08:55 +00004200}
4201
Eric Christopher60d65912013-07-22 22:25:07 +00004202unsigned MachOObjectFile::getAnyRelocationLength(
Charles Davis55107282013-09-01 04:28:48 +00004203 const MachO::any_relocation_info &RE) const {
Rafael Espindolafd7aa382013-04-18 18:08:55 +00004204 if (isRelocationScattered(RE))
4205 return getScatteredRelocationLength(RE);
Lang Hames85334ad2016-12-04 01:56:10 +00004206 return getPlainRelocationLength(*this, RE);
Rafael Espindolafd7aa382013-04-18 18:08:55 +00004207}
4208
4209unsigned
Charles Davis55107282013-09-01 04:28:48 +00004210MachOObjectFile::getAnyRelocationType(
4211 const MachO::any_relocation_info &RE) const {
Rafael Espindolafd7aa382013-04-18 18:08:55 +00004212 if (isRelocationScattered(RE))
4213 return getScatteredRelocationType(RE);
Lang Hames85334ad2016-12-04 01:56:10 +00004214 return getPlainRelocationType(*this, RE);
Rafael Espindolafd7aa382013-04-18 18:08:55 +00004215}
4216
Rafael Espindolae87dadc2013-04-30 15:40:54 +00004217SectionRef
Keno Fischerb6976af2015-05-21 21:24:32 +00004218MachOObjectFile::getAnyRelocationSection(
Charles Davis55107282013-09-01 04:28:48 +00004219 const MachO::any_relocation_info &RE) const {
Rafael Espindolae87dadc2013-04-30 15:40:54 +00004220 if (isRelocationScattered(RE) || getPlainRelocationExternal(RE))
Rafael Espindolaa40b3522014-02-10 20:24:04 +00004221 return *section_end();
Rafael Espindola28b186f2015-06-18 22:38:20 +00004222 unsigned SecNum = getPlainRelocationSymbolNum(RE);
4223 if (SecNum == MachO::R_ABS || SecNum > Sections.size())
4224 return *section_end();
Rafael Espindolae87dadc2013-04-30 15:40:54 +00004225 DataRefImpl DRI;
Rafael Espindola28b186f2015-06-18 22:38:20 +00004226 DRI.d.a = SecNum - 1;
Rafael Espindolae87dadc2013-04-30 15:40:54 +00004227 return SectionRef(DRI, this);
4228}
4229
Charles Davis55107282013-09-01 04:28:48 +00004230MachO::section MachOObjectFile::getSection(DataRefImpl DRI) const {
Rafael Espindola7b677dd2015-05-22 15:43:00 +00004231 assert(DRI.d.a < Sections.size() && "Should have detected this earlier");
Lang Hames85334ad2016-12-04 01:56:10 +00004232 return getStruct<MachO::section>(*this, Sections[DRI.d.a]);
Rafael Espindolafd7aa382013-04-18 18:08:55 +00004233}
4234
Charles Davis55107282013-09-01 04:28:48 +00004235MachO::section_64 MachOObjectFile::getSection64(DataRefImpl DRI) const {
Rafael Espindola7b677dd2015-05-22 15:43:00 +00004236 assert(DRI.d.a < Sections.size() && "Should have detected this earlier");
Lang Hames85334ad2016-12-04 01:56:10 +00004237 return getStruct<MachO::section_64>(*this, Sections[DRI.d.a]);
Rafael Espindolafd7aa382013-04-18 18:08:55 +00004238}
4239
Charles Davis55107282013-09-01 04:28:48 +00004240MachO::section MachOObjectFile::getSection(const LoadCommandInfo &L,
Rafael Espindola2173e182013-04-26 20:07:33 +00004241 unsigned Index) const {
Lang Hames85334ad2016-12-04 01:56:10 +00004242 const char *Sec = getSectionPtr(*this, L, Index);
4243 return getStruct<MachO::section>(*this, Sec);
Rafael Espindola2173e182013-04-26 20:07:33 +00004244}
4245
Charles Davis55107282013-09-01 04:28:48 +00004246MachO::section_64 MachOObjectFile::getSection64(const LoadCommandInfo &L,
4247 unsigned Index) const {
Lang Hames85334ad2016-12-04 01:56:10 +00004248 const char *Sec = getSectionPtr(*this, L, Index);
4249 return getStruct<MachO::section_64>(*this, Sec);
Rafael Espindola2173e182013-04-26 20:07:33 +00004250}
4251
Charles Davis55107282013-09-01 04:28:48 +00004252MachO::nlist
Rafael Espindolafd7aa382013-04-18 18:08:55 +00004253MachOObjectFile::getSymbolTableEntry(DataRefImpl DRI) const {
Rafael Espindola802fe932013-04-24 19:47:55 +00004254 const char *P = reinterpret_cast<const char *>(DRI.p);
Lang Hames85334ad2016-12-04 01:56:10 +00004255 return getStruct<MachO::nlist>(*this, P);
Rafael Espindolafd7aa382013-04-18 18:08:55 +00004256}
4257
Charles Davis55107282013-09-01 04:28:48 +00004258MachO::nlist_64
Rafael Espindolafd7aa382013-04-18 18:08:55 +00004259MachOObjectFile::getSymbol64TableEntry(DataRefImpl DRI) const {
Rafael Espindola802fe932013-04-24 19:47:55 +00004260 const char *P = reinterpret_cast<const char *>(DRI.p);
Lang Hames85334ad2016-12-04 01:56:10 +00004261 return getStruct<MachO::nlist_64>(*this, P);
Rafael Espindolafd7aa382013-04-18 18:08:55 +00004262}
4263
Charles Davis55107282013-09-01 04:28:48 +00004264MachO::linkedit_data_command
4265MachOObjectFile::getLinkeditDataLoadCommand(const LoadCommandInfo &L) const {
Lang Hames85334ad2016-12-04 01:56:10 +00004266 return getStruct<MachO::linkedit_data_command>(*this, L.Ptr);
Rafael Espindolafd7aa382013-04-18 18:08:55 +00004267}
4268
Charles Davis55107282013-09-01 04:28:48 +00004269MachO::segment_command
Rafael Espindola2173e182013-04-26 20:07:33 +00004270MachOObjectFile::getSegmentLoadCommand(const LoadCommandInfo &L) const {
Lang Hames85334ad2016-12-04 01:56:10 +00004271 return getStruct<MachO::segment_command>(*this, L.Ptr);
Rafael Espindola2173e182013-04-26 20:07:33 +00004272}
4273
Charles Davis55107282013-09-01 04:28:48 +00004274MachO::segment_command_64
Rafael Espindola2173e182013-04-26 20:07:33 +00004275MachOObjectFile::getSegment64LoadCommand(const LoadCommandInfo &L) const {
Lang Hames85334ad2016-12-04 01:56:10 +00004276 return getStruct<MachO::segment_command_64>(*this, L.Ptr);
Rafael Espindola2173e182013-04-26 20:07:33 +00004277}
4278
Kevin Enderby1025e9e2014-12-18 00:53:40 +00004279MachO::linker_option_command
4280MachOObjectFile::getLinkerOptionLoadCommand(const LoadCommandInfo &L) const {
Lang Hames85334ad2016-12-04 01:56:10 +00004281 return getStruct<MachO::linker_option_command>(*this, L.Ptr);
Rafael Espindola2173e182013-04-26 20:07:33 +00004282}
4283
Jim Grosbachd55fc3f2014-03-18 22:09:05 +00004284MachO::version_min_command
4285MachOObjectFile::getVersionMinLoadCommand(const LoadCommandInfo &L) const {
Lang Hames85334ad2016-12-04 01:56:10 +00004286 return getStruct<MachO::version_min_command>(*this, L.Ptr);
Jim Grosbachd55fc3f2014-03-18 22:09:05 +00004287}
4288
Kevin Enderby045015e2017-01-19 17:36:31 +00004289MachO::note_command
4290MachOObjectFile::getNoteLoadCommand(const LoadCommandInfo &L) const {
4291 return getStruct<MachO::note_command>(*this, L.Ptr);
4292}
4293
Steven Wu6d5a0272017-01-23 20:07:55 +00004294MachO::build_version_command
4295MachOObjectFile::getBuildVersionLoadCommand(const LoadCommandInfo &L) const {
4296 return getStruct<MachO::build_version_command>(*this, L.Ptr);
4297}
4298
4299MachO::build_tool_version
4300MachOObjectFile::getBuildToolVersion(unsigned index) const {
4301 return getStruct<MachO::build_tool_version>(*this, BuildTools[index]);
4302}
4303
Tim Northover12a261e2014-06-30 14:40:57 +00004304MachO::dylib_command
4305MachOObjectFile::getDylibIDLoadCommand(const LoadCommandInfo &L) const {
Lang Hames85334ad2016-12-04 01:56:10 +00004306 return getStruct<MachO::dylib_command>(*this, L.Ptr);
Tim Northover12a261e2014-06-30 14:40:57 +00004307}
4308
Kevin Enderby37598b62014-09-04 16:54:47 +00004309MachO::dyld_info_command
4310MachOObjectFile::getDyldInfoLoadCommand(const LoadCommandInfo &L) const {
Lang Hames85334ad2016-12-04 01:56:10 +00004311 return getStruct<MachO::dyld_info_command>(*this, L.Ptr);
Kevin Enderby37598b62014-09-04 16:54:47 +00004312}
4313
4314MachO::dylinker_command
4315MachOObjectFile::getDylinkerCommand(const LoadCommandInfo &L) const {
Lang Hames85334ad2016-12-04 01:56:10 +00004316 return getStruct<MachO::dylinker_command>(*this, L.Ptr);
Kevin Enderby37598b62014-09-04 16:54:47 +00004317}
4318
4319MachO::uuid_command
4320MachOObjectFile::getUuidCommand(const LoadCommandInfo &L) const {
Lang Hames85334ad2016-12-04 01:56:10 +00004321 return getStruct<MachO::uuid_command>(*this, L.Ptr);
Kevin Enderby37598b62014-09-04 16:54:47 +00004322}
4323
Jean-Daniel Dupas206b84f2014-12-04 07:37:02 +00004324MachO::rpath_command
4325MachOObjectFile::getRpathCommand(const LoadCommandInfo &L) const {
Lang Hames85334ad2016-12-04 01:56:10 +00004326 return getStruct<MachO::rpath_command>(*this, L.Ptr);
Jean-Daniel Dupas206b84f2014-12-04 07:37:02 +00004327}
4328
Kevin Enderby37598b62014-09-04 16:54:47 +00004329MachO::source_version_command
4330MachOObjectFile::getSourceVersionCommand(const LoadCommandInfo &L) const {
Lang Hames85334ad2016-12-04 01:56:10 +00004331 return getStruct<MachO::source_version_command>(*this, L.Ptr);
Kevin Enderby37598b62014-09-04 16:54:47 +00004332}
4333
4334MachO::entry_point_command
4335MachOObjectFile::getEntryPointCommand(const LoadCommandInfo &L) const {
Lang Hames85334ad2016-12-04 01:56:10 +00004336 return getStruct<MachO::entry_point_command>(*this, L.Ptr);
Kevin Enderby37598b62014-09-04 16:54:47 +00004337}
4338
Kevin Enderby46a81fd2014-12-16 23:25:52 +00004339MachO::encryption_info_command
4340MachOObjectFile::getEncryptionInfoCommand(const LoadCommandInfo &L) const {
Lang Hames85334ad2016-12-04 01:56:10 +00004341 return getStruct<MachO::encryption_info_command>(*this, L.Ptr);
Kevin Enderby46a81fd2014-12-16 23:25:52 +00004342}
4343
Kevin Enderbye479df22014-12-17 01:01:30 +00004344MachO::encryption_info_command_64
4345MachOObjectFile::getEncryptionInfoCommand64(const LoadCommandInfo &L) const {
Lang Hames85334ad2016-12-04 01:56:10 +00004346 return getStruct<MachO::encryption_info_command_64>(*this, L.Ptr);
Kevin Enderbye479df22014-12-17 01:01:30 +00004347}
4348
Kevin Enderbya42da312014-12-18 19:24:35 +00004349MachO::sub_framework_command
4350MachOObjectFile::getSubFrameworkCommand(const LoadCommandInfo &L) const {
Lang Hames85334ad2016-12-04 01:56:10 +00004351 return getStruct<MachO::sub_framework_command>(*this, L.Ptr);
Kevin Enderbya42da312014-12-18 19:24:35 +00004352}
Tim Northover12a261e2014-06-30 14:40:57 +00004353
Kevin Enderby604a34e2014-12-18 23:13:26 +00004354MachO::sub_umbrella_command
4355MachOObjectFile::getSubUmbrellaCommand(const LoadCommandInfo &L) const {
Lang Hames85334ad2016-12-04 01:56:10 +00004356 return getStruct<MachO::sub_umbrella_command>(*this, L.Ptr);
Kevin Enderby604a34e2014-12-18 23:13:26 +00004357}
4358
Kevin Enderby2ef4e252014-12-19 19:48:16 +00004359MachO::sub_library_command
4360MachOObjectFile::getSubLibraryCommand(const LoadCommandInfo &L) const {
Lang Hames85334ad2016-12-04 01:56:10 +00004361 return getStruct<MachO::sub_library_command>(*this, L.Ptr);
Kevin Enderby2ef4e252014-12-19 19:48:16 +00004362}
4363
Kevin Enderby728b8cf2014-12-19 21:06:24 +00004364MachO::sub_client_command
4365MachOObjectFile::getSubClientCommand(const LoadCommandInfo &L) const {
Lang Hames85334ad2016-12-04 01:56:10 +00004366 return getStruct<MachO::sub_client_command>(*this, L.Ptr);
Kevin Enderby728b8cf2014-12-19 21:06:24 +00004367}
4368
Kevin Enderby5ebdee52014-12-19 22:25:22 +00004369MachO::routines_command
4370MachOObjectFile::getRoutinesCommand(const LoadCommandInfo &L) const {
Lang Hames85334ad2016-12-04 01:56:10 +00004371 return getStruct<MachO::routines_command>(*this, L.Ptr);
Kevin Enderby5ebdee52014-12-19 22:25:22 +00004372}
4373
4374MachO::routines_command_64
4375MachOObjectFile::getRoutinesCommand64(const LoadCommandInfo &L) const {
Lang Hames85334ad2016-12-04 01:56:10 +00004376 return getStruct<MachO::routines_command_64>(*this, L.Ptr);
Kevin Enderby5ebdee52014-12-19 22:25:22 +00004377}
4378
Kevin Enderby9a516cd2014-12-23 22:56:39 +00004379MachO::thread_command
4380MachOObjectFile::getThreadCommand(const LoadCommandInfo &L) const {
Lang Hames85334ad2016-12-04 01:56:10 +00004381 return getStruct<MachO::thread_command>(*this, L.Ptr);
Kevin Enderby9a516cd2014-12-23 22:56:39 +00004382}
4383
Charles Davis55107282013-09-01 04:28:48 +00004384MachO::any_relocation_info
Rafael Espindolafd7aa382013-04-18 18:08:55 +00004385MachOObjectFile::getRelocation(DataRefImpl Rel) const {
Rafael Espindola5ca1f952014-04-03 23:51:28 +00004386 uint32_t Offset;
Kevin Enderby96e8b4c2017-06-22 17:41:22 +00004387 if (getHeader().filetype == MachO::MH_OBJECT) {
4388 DataRefImpl Sec;
4389 Sec.d.a = Rel.d.a;
4390 if (is64Bit()) {
4391 MachO::section_64 Sect = getSection64(Sec);
4392 Offset = Sect.reloff;
4393 } else {
4394 MachO::section Sect = getSection(Sec);
4395 Offset = Sect.reloff;
4396 }
Rafael Espindola5ca1f952014-04-03 23:51:28 +00004397 } else {
Kevin Enderby96e8b4c2017-06-22 17:41:22 +00004398 MachO::dysymtab_command DysymtabLoadCmd = getDysymtabLoadCommand();
Michael Trent6469bc62017-12-15 17:57:40 +00004399 if (Rel.d.a == 0)
4400 Offset = DysymtabLoadCmd.extreloff; // Offset to the external relocations
4401 else
4402 Offset = DysymtabLoadCmd.locreloff; // Offset to the local relocations
Rafael Espindola5ca1f952014-04-03 23:51:28 +00004403 }
4404
4405 auto P = reinterpret_cast<const MachO::any_relocation_info *>(
Lang Hames85334ad2016-12-04 01:56:10 +00004406 getPtr(*this, Offset)) + Rel.d.b;
Rafael Espindola5ca1f952014-04-03 23:51:28 +00004407 return getStruct<MachO::any_relocation_info>(
Lang Hames85334ad2016-12-04 01:56:10 +00004408 *this, reinterpret_cast<const char *>(P));
Rafael Espindolafd7aa382013-04-18 18:08:55 +00004409}
4410
Charles Davis55107282013-09-01 04:28:48 +00004411MachO::data_in_code_entry
Kevin Enderby54154f32013-06-06 17:20:50 +00004412MachOObjectFile::getDice(DataRefImpl Rel) const {
4413 const char *P = reinterpret_cast<const char *>(Rel.p);
Lang Hames85334ad2016-12-04 01:56:10 +00004414 return getStruct<MachO::data_in_code_entry>(*this, P);
Kevin Enderby54154f32013-06-06 17:20:50 +00004415}
4416
Alexey Samsonovd7eb7d72015-06-04 19:22:03 +00004417const MachO::mach_header &MachOObjectFile::getHeader() const {
Alexey Samsonov27d60c92015-06-04 22:49:55 +00004418 return Header;
Rafael Espindolafd7aa382013-04-18 18:08:55 +00004419}
4420
Alexey Samsonovd7eb7d72015-06-04 19:22:03 +00004421const MachO::mach_header_64 &MachOObjectFile::getHeader64() const {
4422 assert(is64Bit());
4423 return Header64;
Rafael Espindola2173e182013-04-26 20:07:33 +00004424}
4425
Charles Davis55107282013-09-01 04:28:48 +00004426uint32_t MachOObjectFile::getIndirectSymbolTableEntry(
4427 const MachO::dysymtab_command &DLC,
4428 unsigned Index) const {
4429 uint64_t Offset = DLC.indirectsymoff + Index * sizeof(uint32_t);
Lang Hames85334ad2016-12-04 01:56:10 +00004430 return getStruct<uint32_t>(*this, getPtr(*this, Offset));
Rafael Espindola2173e182013-04-26 20:07:33 +00004431}
4432
Charles Davis55107282013-09-01 04:28:48 +00004433MachO::data_in_code_entry
Rafael Espindola2173e182013-04-26 20:07:33 +00004434MachOObjectFile::getDataInCodeTableEntry(uint32_t DataOffset,
4435 unsigned Index) const {
Charles Davis55107282013-09-01 04:28:48 +00004436 uint64_t Offset = DataOffset + Index * sizeof(MachO::data_in_code_entry);
Lang Hames85334ad2016-12-04 01:56:10 +00004437 return getStruct<MachO::data_in_code_entry>(*this, getPtr(*this, Offset));
Rafael Espindola2173e182013-04-26 20:07:33 +00004438}
4439
Charles Davis55107282013-09-01 04:28:48 +00004440MachO::symtab_command MachOObjectFile::getSymtabLoadCommand() const {
Kevin Enderbya1afbd62014-10-23 19:37:31 +00004441 if (SymtabLoadCmd)
Lang Hames85334ad2016-12-04 01:56:10 +00004442 return getStruct<MachO::symtab_command>(*this, SymtabLoadCmd);
Kevin Enderbya1afbd62014-10-23 19:37:31 +00004443
4444 // If there is no SymtabLoadCmd return a load command with zero'ed fields.
4445 MachO::symtab_command Cmd;
4446 Cmd.cmd = MachO::LC_SYMTAB;
4447 Cmd.cmdsize = sizeof(MachO::symtab_command);
4448 Cmd.symoff = 0;
4449 Cmd.nsyms = 0;
4450 Cmd.stroff = 0;
4451 Cmd.strsize = 0;
4452 return Cmd;
Rafael Espindolafd7aa382013-04-18 18:08:55 +00004453}
4454
Charles Davis55107282013-09-01 04:28:48 +00004455MachO::dysymtab_command MachOObjectFile::getDysymtabLoadCommand() const {
Kevin Enderbya1afbd62014-10-23 19:37:31 +00004456 if (DysymtabLoadCmd)
Lang Hames85334ad2016-12-04 01:56:10 +00004457 return getStruct<MachO::dysymtab_command>(*this, DysymtabLoadCmd);
Kevin Enderbya1afbd62014-10-23 19:37:31 +00004458
4459 // If there is no DysymtabLoadCmd return a load command with zero'ed fields.
4460 MachO::dysymtab_command Cmd;
4461 Cmd.cmd = MachO::LC_DYSYMTAB;
4462 Cmd.cmdsize = sizeof(MachO::dysymtab_command);
4463 Cmd.ilocalsym = 0;
4464 Cmd.nlocalsym = 0;
4465 Cmd.iextdefsym = 0;
4466 Cmd.nextdefsym = 0;
4467 Cmd.iundefsym = 0;
4468 Cmd.nundefsym = 0;
4469 Cmd.tocoff = 0;
4470 Cmd.ntoc = 0;
4471 Cmd.modtaboff = 0;
4472 Cmd.nmodtab = 0;
4473 Cmd.extrefsymoff = 0;
4474 Cmd.nextrefsyms = 0;
4475 Cmd.indirectsymoff = 0;
4476 Cmd.nindirectsyms = 0;
4477 Cmd.extreloff = 0;
4478 Cmd.nextrel = 0;
4479 Cmd.locreloff = 0;
4480 Cmd.nlocrel = 0;
4481 return Cmd;
Rafael Espindola2173e182013-04-26 20:07:33 +00004482}
4483
Charles Davis55107282013-09-01 04:28:48 +00004484MachO::linkedit_data_command
Kevin Enderby54154f32013-06-06 17:20:50 +00004485MachOObjectFile::getDataInCodeLoadCommand() const {
4486 if (DataInCodeLoadCmd)
Lang Hames85334ad2016-12-04 01:56:10 +00004487 return getStruct<MachO::linkedit_data_command>(*this, DataInCodeLoadCmd);
Kevin Enderby54154f32013-06-06 17:20:50 +00004488
4489 // If there is no DataInCodeLoadCmd return a load command with zero'ed fields.
Charles Davis55107282013-09-01 04:28:48 +00004490 MachO::linkedit_data_command Cmd;
4491 Cmd.cmd = MachO::LC_DATA_IN_CODE;
4492 Cmd.cmdsize = sizeof(MachO::linkedit_data_command);
4493 Cmd.dataoff = 0;
4494 Cmd.datasize = 0;
Kevin Enderby54154f32013-06-06 17:20:50 +00004495 return Cmd;
4496}
4497
Kevin Enderbya167fe12015-01-27 21:28:24 +00004498MachO::linkedit_data_command
4499MachOObjectFile::getLinkOptHintsLoadCommand() const {
4500 if (LinkOptHintsLoadCmd)
Lang Hames85334ad2016-12-04 01:56:10 +00004501 return getStruct<MachO::linkedit_data_command>(*this, LinkOptHintsLoadCmd);
Kevin Enderbya167fe12015-01-27 21:28:24 +00004502
4503 // If there is no LinkOptHintsLoadCmd return a load command with zero'ed
4504 // fields.
4505 MachO::linkedit_data_command Cmd;
4506 Cmd.cmd = MachO::LC_LINKER_OPTIMIZATION_HINT;
4507 Cmd.cmdsize = sizeof(MachO::linkedit_data_command);
4508 Cmd.dataoff = 0;
4509 Cmd.datasize = 0;
4510 return Cmd;
4511}
4512
Nick Kledzikaa4d2ac2014-08-30 00:20:14 +00004513ArrayRef<uint8_t> MachOObjectFile::getDyldInfoRebaseOpcodes() const {
NAKAMURA Takumiccf2ea32015-09-22 11:19:03 +00004514 if (!DyldInfoLoadCmd)
Craig Topper795a06a2015-09-21 05:32:41 +00004515 return None;
Nick Kledzikaa4d2ac2014-08-30 00:20:14 +00004516
NAKAMURA Takumid4cdf192015-09-22 11:13:55 +00004517 MachO::dyld_info_command DyldInfo =
Lang Hames85334ad2016-12-04 01:56:10 +00004518 getStruct<MachO::dyld_info_command>(*this, DyldInfoLoadCmd);
NAKAMURA Takumid4cdf192015-09-22 11:13:55 +00004519 const uint8_t *Ptr =
Lang Hames85334ad2016-12-04 01:56:10 +00004520 reinterpret_cast<const uint8_t *>(getPtr(*this, DyldInfo.rebase_off));
Craig Topper795a06a2015-09-21 05:32:41 +00004521 return makeArrayRef(Ptr, DyldInfo.rebase_size);
Nick Kledzikaa4d2ac2014-08-30 00:20:14 +00004522}
4523
4524ArrayRef<uint8_t> MachOObjectFile::getDyldInfoBindOpcodes() const {
NAKAMURA Takumiccf2ea32015-09-22 11:19:03 +00004525 if (!DyldInfoLoadCmd)
Craig Topper795a06a2015-09-21 05:32:41 +00004526 return None;
Nick Kledzikaa4d2ac2014-08-30 00:20:14 +00004527
NAKAMURA Takumid4cdf192015-09-22 11:13:55 +00004528 MachO::dyld_info_command DyldInfo =
Lang Hames85334ad2016-12-04 01:56:10 +00004529 getStruct<MachO::dyld_info_command>(*this, DyldInfoLoadCmd);
NAKAMURA Takumid4cdf192015-09-22 11:13:55 +00004530 const uint8_t *Ptr =
Lang Hames85334ad2016-12-04 01:56:10 +00004531 reinterpret_cast<const uint8_t *>(getPtr(*this, DyldInfo.bind_off));
Craig Topper795a06a2015-09-21 05:32:41 +00004532 return makeArrayRef(Ptr, DyldInfo.bind_size);
Nick Kledzikaa4d2ac2014-08-30 00:20:14 +00004533}
4534
4535ArrayRef<uint8_t> MachOObjectFile::getDyldInfoWeakBindOpcodes() const {
NAKAMURA Takumiccf2ea32015-09-22 11:19:03 +00004536 if (!DyldInfoLoadCmd)
Craig Topper795a06a2015-09-21 05:32:41 +00004537 return None;
Nick Kledzikaa4d2ac2014-08-30 00:20:14 +00004538
NAKAMURA Takumid4cdf192015-09-22 11:13:55 +00004539 MachO::dyld_info_command DyldInfo =
Lang Hames85334ad2016-12-04 01:56:10 +00004540 getStruct<MachO::dyld_info_command>(*this, DyldInfoLoadCmd);
NAKAMURA Takumid4cdf192015-09-22 11:13:55 +00004541 const uint8_t *Ptr =
Lang Hames85334ad2016-12-04 01:56:10 +00004542 reinterpret_cast<const uint8_t *>(getPtr(*this, DyldInfo.weak_bind_off));
Craig Topper795a06a2015-09-21 05:32:41 +00004543 return makeArrayRef(Ptr, DyldInfo.weak_bind_size);
Nick Kledzikaa4d2ac2014-08-30 00:20:14 +00004544}
4545
4546ArrayRef<uint8_t> MachOObjectFile::getDyldInfoLazyBindOpcodes() const {
NAKAMURA Takumiccf2ea32015-09-22 11:19:03 +00004547 if (!DyldInfoLoadCmd)
Craig Topper795a06a2015-09-21 05:32:41 +00004548 return None;
Nick Kledzikaa4d2ac2014-08-30 00:20:14 +00004549
NAKAMURA Takumid4cdf192015-09-22 11:13:55 +00004550 MachO::dyld_info_command DyldInfo =
Lang Hames85334ad2016-12-04 01:56:10 +00004551 getStruct<MachO::dyld_info_command>(*this, DyldInfoLoadCmd);
NAKAMURA Takumid4cdf192015-09-22 11:13:55 +00004552 const uint8_t *Ptr =
Lang Hames85334ad2016-12-04 01:56:10 +00004553 reinterpret_cast<const uint8_t *>(getPtr(*this, DyldInfo.lazy_bind_off));
Craig Topper795a06a2015-09-21 05:32:41 +00004554 return makeArrayRef(Ptr, DyldInfo.lazy_bind_size);
Nick Kledzikaa4d2ac2014-08-30 00:20:14 +00004555}
4556
4557ArrayRef<uint8_t> MachOObjectFile::getDyldInfoExportsTrie() const {
NAKAMURA Takumiccf2ea32015-09-22 11:19:03 +00004558 if (!DyldInfoLoadCmd)
Craig Topper795a06a2015-09-21 05:32:41 +00004559 return None;
Nick Kledzikaa4d2ac2014-08-30 00:20:14 +00004560
NAKAMURA Takumid4cdf192015-09-22 11:13:55 +00004561 MachO::dyld_info_command DyldInfo =
Lang Hames85334ad2016-12-04 01:56:10 +00004562 getStruct<MachO::dyld_info_command>(*this, DyldInfoLoadCmd);
NAKAMURA Takumid4cdf192015-09-22 11:13:55 +00004563 const uint8_t *Ptr =
Lang Hames85334ad2016-12-04 01:56:10 +00004564 reinterpret_cast<const uint8_t *>(getPtr(*this, DyldInfo.export_off));
Craig Topper795a06a2015-09-21 05:32:41 +00004565 return makeArrayRef(Ptr, DyldInfo.export_size);
Nick Kledzikaa4d2ac2014-08-30 00:20:14 +00004566}
4567
Alexander Potapenko4976a532014-10-15 23:35:45 +00004568ArrayRef<uint8_t> MachOObjectFile::getUuid() const {
4569 if (!UuidLoadCmd)
Craig Topper795a06a2015-09-21 05:32:41 +00004570 return None;
Benjamin Kramer5ea04462014-10-24 15:52:05 +00004571 // Returning a pointer is fine as uuid doesn't need endian swapping.
4572 const char *Ptr = UuidLoadCmd + offsetof(MachO::uuid_command, uuid);
Craig Topper795a06a2015-09-21 05:32:41 +00004573 return makeArrayRef(reinterpret_cast<const uint8_t *>(Ptr), 16);
Alexander Potapenko4976a532014-10-15 23:35:45 +00004574}
Nick Kledzikaa4d2ac2014-08-30 00:20:14 +00004575
Rafael Espindola2173e182013-04-26 20:07:33 +00004576StringRef MachOObjectFile::getStringTableData() const {
Charles Davis55107282013-09-01 04:28:48 +00004577 MachO::symtab_command S = getSymtabLoadCommand();
4578 return getData().substr(S.stroff, S.strsize);
Rafael Espindola2173e182013-04-26 20:07:33 +00004579}
4580
Rafael Espindolafd7aa382013-04-18 18:08:55 +00004581bool MachOObjectFile::is64Bit() const {
4582 return getType() == getMachOType(false, true) ||
Lang Hames58d03b32014-07-15 19:35:22 +00004583 getType() == getMachOType(true, true);
Rafael Espindolafd7aa382013-04-18 18:08:55 +00004584}
4585
4586void MachOObjectFile::ReadULEB128s(uint64_t Index,
4587 SmallVectorImpl<uint64_t> &Out) const {
4588 DataExtractor extractor(ObjectFile::getData(), true, 0);
4589
4590 uint32_t offset = Index;
4591 uint64_t data = 0;
4592 while (uint64_t delta = extractor.getULEB128(&offset)) {
4593 data += delta;
4594 Out.push_back(data);
4595 }
4596}
4597
Rafael Espindola78e8d522014-08-17 19:09:37 +00004598bool MachOObjectFile::isRelocatableObject() const {
4599 return getHeader().filetype == MachO::MH_OBJECT;
4600}
4601
Lang Hamesbe17ef72016-03-25 23:11:52 +00004602Expected<std::unique_ptr<MachOObjectFile>>
Kevin Enderbyaa450922016-10-24 21:15:11 +00004603ObjectFile::createMachOObjectFile(MemoryBufferRef Buffer,
4604 uint32_t UniversalCputype,
4605 uint32_t UniversalIndex) {
Rafael Espindola548f2b62014-08-19 18:44:46 +00004606 StringRef Magic = Buffer.getBuffer().slice(0, 4);
Lang Hames086a6fa2016-03-25 21:59:14 +00004607 if (Magic == "\xFE\xED\xFA\xCE")
Kevin Enderbyaa450922016-10-24 21:15:11 +00004608 return MachOObjectFile::create(Buffer, false, false,
4609 UniversalCputype, UniversalIndex);
David Blaikie63cf3b32016-03-28 17:45:48 +00004610 if (Magic == "\xCE\xFA\xED\xFE")
Kevin Enderbyaa450922016-10-24 21:15:11 +00004611 return MachOObjectFile::create(Buffer, true, false,
4612 UniversalCputype, UniversalIndex);
David Blaikie63cf3b32016-03-28 17:45:48 +00004613 if (Magic == "\xFE\xED\xFA\xCF")
Kevin Enderbyaa450922016-10-24 21:15:11 +00004614 return MachOObjectFile::create(Buffer, false, true,
4615 UniversalCputype, UniversalIndex);
David Blaikie63cf3b32016-03-28 17:45:48 +00004616 if (Magic == "\xCF\xFA\xED\xFE")
Kevin Enderbyaa450922016-10-24 21:15:11 +00004617 return MachOObjectFile::create(Buffer, true, true,
4618 UniversalCputype, UniversalIndex);
Kevin Enderbyeaa1f082016-05-06 20:16:28 +00004619 return make_error<GenericBinaryError>("Unrecognized MachO magic number",
Justin Bogner2dd0b892016-05-05 23:59:57 +00004620 object_error::invalid_file_type);
Rafael Espindolafd7aa382013-04-18 18:08:55 +00004621}
Wolfgang Piebc9977b62017-06-06 01:22:34 +00004622
4623StringRef MachOObjectFile::mapDebugSectionName(StringRef Name) const {
4624 return StringSwitch<StringRef>(Name)
4625 .Case("debug_str_offs", "debug_str_offsets")
4626 .Default(Name);
4627}