]> git.saurik.com Git - apple/dyld.git/blob - src/ImageLoaderMachO.cpp
dd9b5af76ef7d31e708a5e6f3331035da52a20fa
[apple/dyld.git] / src / ImageLoaderMachO.cpp
1 /* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*-
2 *
3 * Copyright (c) 2004-2010 Apple Inc. All rights reserved.
4 *
5 * @APPLE_LICENSE_HEADER_START@
6 *
7 * This file contains Original Code and/or Modifications of Original Code
8 * as defined in and that are subject to the Apple Public Source License
9 * Version 2.0 (the 'License'). You may not use this file except in
10 * compliance with the License. Please obtain a copy of the License at
11 * http://www.opensource.apple.com/apsl/ and read it before using this
12 * file.
13 *
14 * The Original Code and all software distributed under the License are
15 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
16 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
17 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
19 * Please see the License for the specific language governing rights and
20 * limitations under the License.
21 *
22 * @APPLE_LICENSE_HEADER_END@
23 */
24
25 // work around until conformance work is complete rdar://problem/4508801
26 #define __srr0 srr0
27 #define __eip eip
28 #define __rip rip
29
30 #define __STDC_LIMIT_MACROS
31 #include <string.h>
32 #include <fcntl.h>
33 #include <errno.h>
34 #include <sys/types.h>
35 #include <sys/fcntl.h>
36 #include <sys/stat.h>
37 #include <sys/mman.h>
38 #include <mach/mach.h>
39 #include <mach/thread_status.h>
40 #include <mach-o/loader.h>
41 #include <mach-o/nlist.h>
42 #include <sys/sysctl.h>
43 #include <sys/syscall.h>
44 #include <libkern/OSAtomic.h>
45 #include <libkern/OSCacheControl.h>
46 #include <stdint.h>
47 #include <System/sys/codesign.h>
48
49 #include "ImageLoaderMachO.h"
50 #include "ImageLoaderMachOCompressed.h"
51 #if SUPPORT_CLASSIC_MACHO
52 #include "ImageLoaderMachOClassic.h"
53 #endif
54 #include "mach-o/dyld_images.h"
55 #include "dyld.h"
56
57 // <rdar://problem/8718137> use stack guard random value to add padding between dylibs
58 extern "C" long __stack_chk_guard;
59
60 #ifndef LC_LOAD_UPWARD_DYLIB
61 #define LC_LOAD_UPWARD_DYLIB (0x23|LC_REQ_DYLD) /* load of dylib whose initializers run later */
62 #endif
63
64 #ifndef LC_VERSION_MIN_TVOS
65 #define LC_VERSION_MIN_TVOS 0x2F
66 #endif
67
68 #ifndef LC_VERSION_MIN_WATCHOS
69 #define LC_VERSION_MIN_WATCHOS 0x30
70 #endif
71
72
73 #if TARGET_IPHONE_SIMULATOR
74 #define LIBSYSTEM_DYLIB_PATH "/usr/lib/libSystem.dylib"
75 #else
76 #define LIBSYSTEM_DYLIB_PATH "/usr/lib/libSystem.B.dylib"
77 #endif
78
79 // relocation_info.r_length field has value 3 for 64-bit executables and value 2 for 32-bit executables
80 #if __LP64__
81 #define LC_SEGMENT_COMMAND LC_SEGMENT_64
82 #define LC_ROUTINES_COMMAND LC_ROUTINES_64
83 #define LC_SEGMENT_COMMAND_WRONG LC_SEGMENT
84 struct macho_segment_command : public segment_command_64 {};
85 struct macho_section : public section_64 {};
86 struct macho_routines_command : public routines_command_64 {};
87 #else
88 #define LC_SEGMENT_COMMAND LC_SEGMENT
89 #define LC_ROUTINES_COMMAND LC_ROUTINES
90 #define LC_SEGMENT_COMMAND_WRONG LC_SEGMENT_64
91 struct macho_segment_command : public segment_command {};
92 struct macho_section : public section {};
93 struct macho_routines_command : public routines_command {};
94 #endif
95
96 uint32_t ImageLoaderMachO::fgSymbolTableBinarySearchs = 0;
97
98
99 ImageLoaderMachO::ImageLoaderMachO(const macho_header* mh, const char* path, unsigned int segCount,
100 uint32_t segOffsets[], unsigned int libCount)
101 : ImageLoader(path, libCount), fCoveredCodeLength(0), fMachOData((uint8_t*)mh), fLinkEditBase(NULL), fSlide(0),
102 fEHFrameSectionOffset(0), fUnwindInfoSectionOffset(0), fDylibIDOffset(0),
103 fSegmentsCount(segCount), fIsSplitSeg(false), fInSharedCache(false),
104 #if TEXT_RELOC_SUPPORT
105 fTextSegmentRebases(false),
106 fTextSegmentBinds(false),
107 #endif
108 #if __i386__
109 fReadOnlyImportSegment(false),
110 #endif
111 fHasSubLibraries(false), fHasSubUmbrella(false), fInUmbrella(false), fHasDOFSections(false), fHasDashInit(false),
112 fHasInitializers(false), fHasTerminators(false), fNotifyObjC(false), fRetainForObjC(false), fRegisteredAsRequiresCoalescing(false)
113 {
114 fIsSplitSeg = ((mh->flags & MH_SPLIT_SEGS) != 0);
115
116 // construct SegmentMachO object for each LC_SEGMENT cmd using "placement new" to put
117 // each SegmentMachO object in array at end of ImageLoaderMachO object
118 const uint32_t cmd_count = mh->ncmds;
119 const struct load_command* const cmds = (struct load_command*)&fMachOData[sizeof(macho_header)];
120 const struct load_command* cmd = cmds;
121 for (uint32_t i = 0, segIndex=0; i < cmd_count; ++i) {
122 if ( cmd->cmd == LC_SEGMENT_COMMAND ) {
123 const struct macho_segment_command* segCmd = (struct macho_segment_command*)cmd;
124 // ignore zero-sized segments
125 if ( segCmd->vmsize != 0 ) {
126 // record offset of load command
127 segOffsets[segIndex++] = (uint32_t)((uint8_t*)segCmd - fMachOData);
128 }
129 }
130 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
131 }
132
133 }
134
135
136 // determine if this mach-o file has classic or compressed LINKEDIT and number of segments it has
137 void ImageLoaderMachO::sniffLoadCommands(const macho_header* mh, const char* path, bool inCache, bool* compressed,
138 unsigned int* segCount, unsigned int* libCount, const LinkContext& context,
139 const linkedit_data_command** codeSigCmd,
140 const encryption_info_command** encryptCmd)
141 {
142 *compressed = false;
143 *segCount = 0;
144 *libCount = 0;
145 *codeSigCmd = NULL;
146 *encryptCmd = NULL;
147
148 const uint32_t cmd_count = mh->ncmds;
149 const uint32_t sizeofcmds = mh->sizeofcmds;
150 if ( sizeofcmds > (MAX_MACH_O_HEADER_AND_LOAD_COMMANDS_SIZE-sizeof(macho_header)) )
151 dyld::throwf("malformed mach-o: load commands size (%u) > %u", sizeofcmds, MAX_MACH_O_HEADER_AND_LOAD_COMMANDS_SIZE);
152 if ( cmd_count > (sizeofcmds/sizeof(load_command)) )
153 dyld::throwf("malformed mach-o: ncmds (%u) too large to fit in sizeofcmds (%u)", cmd_count, sizeofcmds);
154 const struct load_command* const startCmds = (struct load_command*)(((uint8_t*)mh) + sizeof(macho_header));
155 const struct load_command* const endCmds = (struct load_command*)(((uint8_t*)mh) + sizeof(macho_header) + sizeofcmds);
156 const struct load_command* cmd = startCmds;
157 bool foundLoadCommandSegment = false;
158 const macho_segment_command* linkeditSegCmd = NULL;
159 const macho_segment_command* startOfFileSegCmd = NULL;
160 const dyld_info_command* dyldInfoCmd = NULL;
161 const symtab_command* symTabCmd = NULL;
162 const dysymtab_command* dynSymbTabCmd = NULL;
163 for (uint32_t i = 0; i < cmd_count; ++i) {
164 uint32_t cmdLength = cmd->cmdsize;
165 const macho_segment_command* segCmd;
166 const dylib_command* dylibCmd;
167 if ( cmdLength < 8 ) {
168 dyld::throwf("malformed mach-o image: load command #%d length (%u) too small in %s",
169 i, cmdLength, path);
170 }
171 const struct load_command* const nextCmd = (const struct load_command*)(((char*)cmd)+cmdLength);
172 if ( (nextCmd > endCmds) || (nextCmd < cmd) ) {
173 dyld::throwf("malformed mach-o image: load command #%d length (%u) would exceed sizeofcmds (%u) in %s",
174 i, cmdLength, mh->sizeofcmds, path);
175 }
176 switch (cmd->cmd) {
177 case LC_DYLD_INFO:
178 case LC_DYLD_INFO_ONLY:
179 if ( cmd->cmdsize != sizeof(dyld_info_command) )
180 throw "malformed mach-o image: LC_DYLD_INFO size wrong";
181 dyldInfoCmd = (struct dyld_info_command*)cmd;
182 *compressed = true;
183 break;
184 case LC_SEGMENT_COMMAND:
185 segCmd = (struct macho_segment_command*)cmd;
186 #if __MAC_OS_X_VERSION_MIN_REQUIRED
187 // rdar://problem/19617624 allow unmapped segments on OSX (but not iOS)
188 if ( (segCmd->filesize > segCmd->vmsize) && (segCmd->vmsize != 0) )
189 #else
190 // <rdar://problem/19986776> dyld should support non-allocatable __LLVM segment
191 if ( (segCmd->filesize > segCmd->vmsize) && ((segCmd->vmsize != 0) || ((segCmd->flags & SG_NORELOC) == 0)) )
192 #endif
193 dyld::throwf("malformed mach-o image: segment load command %s filesize is larger than vmsize", segCmd->segname);
194 if ( cmd->cmdsize < sizeof(macho_segment_command) )
195 throw "malformed mach-o image: LC_SEGMENT size too small";
196 if ( cmd->cmdsize != (sizeof(macho_segment_command) + segCmd->nsects * sizeof(macho_section)) )
197 throw "malformed mach-o image: LC_SEGMENT size wrong for number of sections";
198 // ignore zero-sized segments
199 if ( segCmd->vmsize != 0 )
200 *segCount += 1;
201 if ( strcmp(segCmd->segname, "__LINKEDIT") == 0 ) {
202 #if TARGET_IPHONE_SIMULATOR
203 // Note: should check on all platforms that __LINKEDIT is read-only, but <rdar://problem/22637626&22525618>
204 if ( segCmd->initprot != VM_PROT_READ )
205 throw "malformed mach-o image: __LINKEDIT segment does not have read-only permissions";
206 #endif
207 if ( segCmd->fileoff == 0 )
208 throw "malformed mach-o image: __LINKEDIT has fileoff==0 which overlaps mach_header";
209 if ( linkeditSegCmd != NULL )
210 throw "malformed mach-o image: multiple __LINKEDIT segments";
211 linkeditSegCmd = segCmd;
212 }
213 else {
214 if ( segCmd->initprot & 0xFFFFFFF8 )
215 dyld::throwf("malformed mach-o image: %s segment has invalid permission bits (0x%X) in initprot", segCmd->segname, segCmd->initprot);
216 if ( segCmd->maxprot & 0xFFFFFFF8 )
217 dyld::throwf("malformed mach-o image: %s segment has invalid permission bits (0x%X) in maxprot", segCmd->segname, segCmd->maxprot);
218 if ( (segCmd->initprot != 0) && ((segCmd->initprot & VM_PROT_READ) == 0) )
219 dyld::throwf("malformed mach-o image: %s segment is not mapped readable", segCmd->segname);
220 }
221 if ( (segCmd->fileoff == 0) && (segCmd->filesize != 0) ) {
222 if ( (segCmd->initprot & VM_PROT_READ) == 0 )
223 dyld::throwf("malformed mach-o image: %s segment maps start of file but is not readable", segCmd->segname);
224 if ( (segCmd->initprot & VM_PROT_WRITE) == VM_PROT_WRITE ) {
225 if ( context.strictMachORequired )
226 dyld::throwf("malformed mach-o image: %s segment maps start of file but is writable", segCmd->segname);
227 }
228 if ( segCmd->filesize < (sizeof(macho_header) + mh->sizeofcmds) )
229 dyld::throwf("malformed mach-o image: %s segment does not map all of load commands", segCmd->segname);
230 if ( startOfFileSegCmd != NULL )
231 dyld::throwf("malformed mach-o image: multiple segments map start of file: %s %s", startOfFileSegCmd->segname, segCmd->segname);
232 startOfFileSegCmd = segCmd;
233 }
234 if ( context.strictMachORequired ) {
235 uintptr_t vmStart = segCmd->vmaddr;
236 uintptr_t vmSize = segCmd->vmsize;
237 uintptr_t vmEnd = vmStart + vmSize;
238 uintptr_t fileStart = segCmd->fileoff;
239 uintptr_t fileSize = segCmd->filesize;
240 if ( (intptr_t)(vmSize) < 0 )
241 dyld::throwf("malformed mach-o image: segment load command %s vmsize too large in %s", segCmd->segname, path);
242 if ( vmStart > vmEnd )
243 dyld::throwf("malformed mach-o image: segment load command %s wraps around address space", segCmd->segname);
244 if ( vmSize != fileSize ) {
245 if ( segCmd->initprot == 0 ) {
246 // allow: fileSize == 0 && initprot == 0 e.g. __PAGEZERO
247 // allow: vmSize == 0 && initprot == 0 e.g. __LLVM
248 if ( (fileSize != 0) && (vmSize != 0) )
249 dyld::throwf("malformed mach-o image: unaccessable segment %s has non-zero filesize and vmsize", segCmd->segname);
250 }
251 else {
252 // allow: vmSize > fileSize && initprot != X e.g. __DATA
253 if ( vmSize < fileSize )
254 dyld::throwf("malformed mach-o image: segment %s has vmsize < filesize", segCmd->segname);
255 if ( segCmd->initprot & VM_PROT_EXECUTE )
256 dyld::throwf("malformed mach-o image: segment %s has vmsize != filesize and is executable", segCmd->segname);
257 }
258 }
259 if ( inCache ) {
260 if ( (fileSize != 0) && (segCmd->initprot == (VM_PROT_READ | VM_PROT_EXECUTE)) ) {
261 if ( foundLoadCommandSegment )
262 throw "load commands in multiple segments";
263 foundLoadCommandSegment = true;
264 }
265 }
266 else if ( (fileStart < mh->sizeofcmds) && (fileSize != 0) ) {
267 // <rdar://problem/7942521> all load commands must be in an executable segment
268 if ( (fileStart != 0) || (fileSize < (mh->sizeofcmds+sizeof(macho_header))) )
269 dyld::throwf("malformed mach-o image: segment %s does not span all load commands", segCmd->segname);
270 if ( segCmd->initprot != (VM_PROT_READ | VM_PROT_EXECUTE) )
271 dyld::throwf("malformed mach-o image: load commands found in segment %s with wrong permissions", segCmd->segname);
272 if ( foundLoadCommandSegment )
273 throw "load commands in multiple segments";
274 foundLoadCommandSegment = true;
275 }
276
277 const struct macho_section* const sectionsStart = (struct macho_section*)((char*)segCmd + sizeof(struct macho_segment_command));
278 const struct macho_section* const sectionsEnd = &sectionsStart[segCmd->nsects];
279 for (const struct macho_section* sect=sectionsStart; sect < sectionsEnd; ++sect) {
280 if (!inCache && sect->offset != 0 && ((sect->offset + sect->size) > (segCmd->fileoff + segCmd->filesize)))
281 dyld::throwf("malformed mach-o image: section %s,%s of '%s' exceeds segment %s booundary", sect->segname, sect->sectname, path, segCmd->segname);
282 }
283 }
284 break;
285 case LC_SEGMENT_COMMAND_WRONG:
286 dyld::throwf("malformed mach-o image: wrong LC_SEGMENT[_64] for architecture");
287 break;
288 case LC_LOAD_DYLIB:
289 case LC_LOAD_WEAK_DYLIB:
290 case LC_REEXPORT_DYLIB:
291 case LC_LOAD_UPWARD_DYLIB:
292 *libCount += 1;
293 // fall thru
294 case LC_ID_DYLIB:
295 dylibCmd = (dylib_command*)cmd;
296 if ( dylibCmd->dylib.name.offset > cmdLength )
297 dyld::throwf("malformed mach-o image: dylib load command #%d has offset (%u) outside its size (%u)", i, dylibCmd->dylib.name.offset, cmdLength);
298 if ( (dylibCmd->dylib.name.offset + strlen((char*)dylibCmd + dylibCmd->dylib.name.offset) + 1) > cmdLength )
299 dyld::throwf("malformed mach-o image: dylib load command #%d string extends beyond end of load command", i);
300 break;
301 case LC_CODE_SIGNATURE:
302 if ( cmd->cmdsize != sizeof(linkedit_data_command) )
303 throw "malformed mach-o image: LC_CODE_SIGNATURE size wrong";
304 // <rdar://problem/22799652> only support one LC_CODE_SIGNATURE per image
305 if ( *codeSigCmd != NULL )
306 throw "malformed mach-o image: multiple LC_CODE_SIGNATURE load commands";
307 *codeSigCmd = (struct linkedit_data_command*)cmd;
308 break;
309 case LC_ENCRYPTION_INFO:
310 if ( cmd->cmdsize != sizeof(encryption_info_command) )
311 throw "malformed mach-o image: LC_ENCRYPTION_INFO size wrong";
312 // <rdar://problem/22799652> only support one LC_ENCRYPTION_INFO per image
313 if ( *encryptCmd != NULL )
314 throw "malformed mach-o image: multiple LC_ENCRYPTION_INFO load commands";
315 *encryptCmd = (encryption_info_command*)cmd;
316 break;
317 case LC_ENCRYPTION_INFO_64:
318 if ( cmd->cmdsize != sizeof(encryption_info_command_64) )
319 throw "malformed mach-o image: LC_ENCRYPTION_INFO_64 size wrong";
320 // <rdar://problem/22799652> only support one LC_ENCRYPTION_INFO_64 per image
321 if ( *encryptCmd != NULL )
322 throw "malformed mach-o image: multiple LC_ENCRYPTION_INFO_64 load commands";
323 *encryptCmd = (encryption_info_command*)cmd;
324 break;
325 case LC_SYMTAB:
326 if ( cmd->cmdsize != sizeof(symtab_command) )
327 throw "malformed mach-o image: LC_SYMTAB size wrong";
328 symTabCmd = (symtab_command*)cmd;
329 break;
330 case LC_DYSYMTAB:
331 if ( cmd->cmdsize != sizeof(dysymtab_command) )
332 throw "malformed mach-o image: LC_DYSYMTAB size wrong";
333 dynSymbTabCmd = (dysymtab_command*)cmd;
334 break;
335 #if __MAC_OS_X_VERSION_MIN_REQUIRED
336 // <rdar://problem/26797345> error when loading iOS Simulator mach-o binary into macOS process
337 case LC_VERSION_MIN_WATCHOS:
338 case LC_VERSION_MIN_TVOS:
339 case LC_VERSION_MIN_IPHONEOS:
340 throw "mach-o, but built for simulator (not macOS)";
341 break;
342 #endif
343 }
344 cmd = nextCmd;
345 }
346
347 if ( context.strictMachORequired && !foundLoadCommandSegment )
348 throw "load commands not in a segment";
349 if ( linkeditSegCmd == NULL )
350 throw "malformed mach-o image: missing __LINKEDIT segment";
351 if ( startOfFileSegCmd == NULL )
352 throw "malformed mach-o image: missing __TEXT segment that maps start of file";
353 // <rdar://problem/13145644> verify every segment does not overlap another segment
354 if ( context.strictMachORequired ) {
355 uintptr_t lastFileStart = 0;
356 uintptr_t linkeditFileStart = 0;
357 const struct load_command* cmd1 = startCmds;
358 for (uint32_t i = 0; i < cmd_count; ++i) {
359 if ( cmd1->cmd == LC_SEGMENT_COMMAND ) {
360 struct macho_segment_command* segCmd1 = (struct macho_segment_command*)cmd1;
361 uintptr_t vmStart1 = segCmd1->vmaddr;
362 uintptr_t vmEnd1 = segCmd1->vmaddr + segCmd1->vmsize;
363 uintptr_t fileStart1 = segCmd1->fileoff;
364 uintptr_t fileEnd1 = segCmd1->fileoff + segCmd1->filesize;
365
366 if (fileStart1 > lastFileStart)
367 lastFileStart = fileStart1;
368
369 if ( strcmp(&segCmd1->segname[0], "__LINKEDIT") == 0 ) {
370 linkeditFileStart = fileStart1;
371 }
372
373 const struct load_command* cmd2 = startCmds;
374 for (uint32_t j = 0; j < cmd_count; ++j) {
375 if ( cmd2 == cmd1 )
376 continue;
377 if ( cmd2->cmd == LC_SEGMENT_COMMAND ) {
378 struct macho_segment_command* segCmd2 = (struct macho_segment_command*)cmd2;
379 uintptr_t vmStart2 = segCmd2->vmaddr;
380 uintptr_t vmEnd2 = segCmd2->vmaddr + segCmd2->vmsize;
381 uintptr_t fileStart2 = segCmd2->fileoff;
382 uintptr_t fileEnd2 = segCmd2->fileoff + segCmd2->filesize;
383 if ( ((vmStart2 <= vmStart1) && (vmEnd2 > vmStart1) && (vmEnd1 > vmStart1))
384 || ((vmStart2 >= vmStart1) && (vmStart2 < vmEnd1) && (vmEnd2 > vmStart2)) )
385 dyld::throwf("malformed mach-o image: segment %s vm overlaps segment %s", segCmd1->segname, segCmd2->segname);
386 if ( ((fileStart2 <= fileStart1) && (fileEnd2 > fileStart1) && (fileEnd1 > fileStart1))
387 || ((fileStart2 >= fileStart1) && (fileStart2 < fileEnd1) && (fileEnd2 > fileStart2)) )
388 dyld::throwf("malformed mach-o image: segment %s file content overlaps segment %s", segCmd1->segname, segCmd2->segname);
389 }
390 cmd2 = (const struct load_command*)(((char*)cmd2)+cmd2->cmdsize);
391 }
392 }
393 cmd1 = (const struct load_command*)(((char*)cmd1)+cmd1->cmdsize);
394 }
395
396 if (lastFileStart != linkeditFileStart)
397 dyld::throwf("malformed mach-o image: __LINKEDIT must be last segment");
398 }
399
400 // validate linkedit content
401 if ( (dyldInfoCmd == NULL) && (symTabCmd == NULL) )
402 throw "malformed mach-o image: missing LC_SYMTAB or LC_DYLD_INFO";
403 if ( dynSymbTabCmd == NULL )
404 throw "malformed mach-o image: missing LC_DYSYMTAB";
405
406 uint32_t linkeditFileOffsetStart = (uint32_t)linkeditSegCmd->fileoff;
407 uint32_t linkeditFileOffsetEnd = (uint32_t)linkeditSegCmd->fileoff + (uint32_t)linkeditSegCmd->filesize;
408
409 if ( !inCache && (dyldInfoCmd != NULL) && context.strictMachORequired ) {
410 // validate all LC_DYLD_INFO chunks fit in LINKEDIT and don't overlap
411 uint32_t offset = linkeditFileOffsetStart;
412 if ( dyldInfoCmd->rebase_size != 0 ) {
413 if ( dyldInfoCmd->rebase_size & 0x80000000 )
414 throw "malformed mach-o image: dyld rebase info size overflow";
415 if ( dyldInfoCmd->rebase_off < offset )
416 throw "malformed mach-o image: dyld rebase info underruns __LINKEDIT";
417 offset = dyldInfoCmd->rebase_off + dyldInfoCmd->rebase_size;
418 if ( offset > linkeditFileOffsetEnd )
419 throw "malformed mach-o image: dyld rebase info overruns __LINKEDIT";
420 }
421 if ( dyldInfoCmd->bind_size != 0 ) {
422 if ( dyldInfoCmd->bind_size & 0x80000000 )
423 throw "malformed mach-o image: dyld bind info size overflow";
424 if ( dyldInfoCmd->bind_off < offset )
425 throw "malformed mach-o image: dyld bind info overlaps rebase info";
426 offset = dyldInfoCmd->bind_off + dyldInfoCmd->bind_size;
427 if ( offset > linkeditFileOffsetEnd )
428 throw "malformed mach-o image: dyld bind info overruns __LINKEDIT";
429 }
430 if ( dyldInfoCmd->weak_bind_size != 0 ) {
431 if ( dyldInfoCmd->weak_bind_size & 0x80000000 )
432 throw "malformed mach-o image: dyld weak bind info size overflow";
433 if ( dyldInfoCmd->weak_bind_off < offset )
434 throw "malformed mach-o image: dyld weak bind info overlaps bind info";
435 offset = dyldInfoCmd->weak_bind_off + dyldInfoCmd->weak_bind_size;
436 if ( offset > linkeditFileOffsetEnd )
437 throw "malformed mach-o image: dyld weak bind info overruns __LINKEDIT";
438 }
439 if ( dyldInfoCmd->lazy_bind_size != 0 ) {
440 if ( dyldInfoCmd->lazy_bind_size & 0x80000000 )
441 throw "malformed mach-o image: dyld lazy bind info size overflow";
442 if ( dyldInfoCmd->lazy_bind_off < offset )
443 throw "malformed mach-o image: dyld lazy bind info overlaps weak bind info";
444 offset = dyldInfoCmd->lazy_bind_off + dyldInfoCmd->lazy_bind_size;
445 if ( offset > linkeditFileOffsetEnd )
446 throw "malformed mach-o image: dyld lazy bind info overruns __LINKEDIT";
447 }
448 if ( dyldInfoCmd->export_size != 0 ) {
449 if ( dyldInfoCmd->export_size & 0x80000000 )
450 throw "malformed mach-o image: dyld export info size overflow";
451 if ( dyldInfoCmd->export_off < offset )
452 throw "malformed mach-o image: dyld export info overlaps lazy bind info";
453 offset = dyldInfoCmd->export_off + dyldInfoCmd->export_size;
454 if ( offset > linkeditFileOffsetEnd )
455 throw "malformed mach-o image: dyld export info overruns __LINKEDIT";
456 }
457 }
458
459 if ( symTabCmd != NULL ) {
460 // validate symbol table fits in LINKEDIT
461 if ( symTabCmd->symoff < linkeditFileOffsetStart )
462 throw "malformed mach-o image: symbol table underruns __LINKEDIT";
463 if ( symTabCmd->nsyms > 0x10000000 )
464 throw "malformed mach-o image: symbol table too large";
465 uint32_t symbolsSize = symTabCmd->nsyms * sizeof(macho_nlist);
466 if ( symbolsSize > linkeditSegCmd->filesize )
467 throw "malformed mach-o image: symbol table overruns __LINKEDIT";
468 if ( symTabCmd->symoff + symbolsSize < symTabCmd->symoff )
469 throw "malformed mach-o image: symbol table size wraps";
470 if ( symTabCmd->symoff + symbolsSize > symTabCmd->stroff )
471 throw "malformed mach-o image: symbol table overlaps symbol strings";
472 if ( symTabCmd->stroff + symTabCmd->strsize < symTabCmd->stroff )
473 throw "malformed mach-o image: symbol string size wraps";
474 if ( symTabCmd->stroff + symTabCmd->strsize > linkeditFileOffsetEnd ) {
475 // <rdar://problem/24220313> let old apps overflow as long as it stays within mapped page
476 if ( context.strictMachORequired || (symTabCmd->stroff + symTabCmd->strsize > ((linkeditFileOffsetEnd + 4095) & (-4096))) )
477 throw "malformed mach-o image: symbol strings overrun __LINKEDIT";
478 }
479 // validate indirect symbol table
480 if ( dynSymbTabCmd->nindirectsyms != 0 ) {
481 if ( dynSymbTabCmd->indirectsymoff < linkeditFileOffsetStart )
482 throw "malformed mach-o image: indirect symbol table underruns __LINKEDIT";
483 if ( dynSymbTabCmd->nindirectsyms > 0x10000000 )
484 throw "malformed mach-o image: indirect symbol table too large";
485 uint32_t indirectTableSize = dynSymbTabCmd->nindirectsyms * sizeof(uint32_t);
486 if ( indirectTableSize > linkeditSegCmd->filesize )
487 throw "malformed mach-o image: indirect symbol table overruns __LINKEDIT";
488 if ( dynSymbTabCmd->indirectsymoff + indirectTableSize < dynSymbTabCmd->indirectsymoff )
489 throw "malformed mach-o image: indirect symbol table size wraps";
490 if ( context.strictMachORequired && (dynSymbTabCmd->indirectsymoff + indirectTableSize > symTabCmd->stroff) )
491 throw "malformed mach-o image: indirect symbol table overruns string pool";
492 }
493 if ( (dynSymbTabCmd->nlocalsym > symTabCmd->nsyms) || (dynSymbTabCmd->ilocalsym > symTabCmd->nsyms) )
494 throw "malformed mach-o image: indirect symbol table local symbol count exceeds total symbols";
495 if ( dynSymbTabCmd->ilocalsym + dynSymbTabCmd->nlocalsym < dynSymbTabCmd->ilocalsym )
496 throw "malformed mach-o image: indirect symbol table local symbol count wraps";
497 if ( (dynSymbTabCmd->nextdefsym > symTabCmd->nsyms) || (dynSymbTabCmd->iextdefsym > symTabCmd->nsyms) )
498 throw "malformed mach-o image: indirect symbol table extern symbol count exceeds total symbols";
499 if ( dynSymbTabCmd->iextdefsym + dynSymbTabCmd->nextdefsym < dynSymbTabCmd->iextdefsym )
500 throw "malformed mach-o image: indirect symbol table extern symbol count wraps";
501 if ( (dynSymbTabCmd->nundefsym > symTabCmd->nsyms) || (dynSymbTabCmd->iundefsym > symTabCmd->nsyms) )
502 throw "malformed mach-o image: indirect symbol table undefined symbol count exceeds total symbols";
503 if ( dynSymbTabCmd->iundefsym + dynSymbTabCmd->nundefsym < dynSymbTabCmd->iundefsym )
504 throw "malformed mach-o image: indirect symbol table undefined symbol count wraps";
505 }
506
507
508 // fSegmentsArrayCount is only 8-bits
509 if ( *segCount > 255 )
510 dyld::throwf("malformed mach-o image: more than 255 segments in %s", path);
511
512 // fSegmentsArrayCount is only 8-bits
513 if ( *libCount > 4095 )
514 dyld::throwf("malformed mach-o image: more than 4095 dependent libraries in %s", path);
515
516 if ( needsAddedLibSystemDepency(*libCount, mh) )
517 *libCount = 1;
518 }
519
520
521
522 // create image for main executable
523 ImageLoader* ImageLoaderMachO::instantiateMainExecutable(const macho_header* mh, uintptr_t slide, const char* path, const LinkContext& context)
524 {
525 //dyld::log("ImageLoader=%ld, ImageLoaderMachO=%ld, ImageLoaderMachOClassic=%ld, ImageLoaderMachOCompressed=%ld\n",
526 // sizeof(ImageLoader), sizeof(ImageLoaderMachO), sizeof(ImageLoaderMachOClassic), sizeof(ImageLoaderMachOCompressed));
527 bool compressed;
528 unsigned int segCount;
529 unsigned int libCount;
530 const linkedit_data_command* codeSigCmd;
531 const encryption_info_command* encryptCmd;
532 sniffLoadCommands(mh, path, false, &compressed, &segCount, &libCount, context, &codeSigCmd, &encryptCmd);
533 // instantiate concrete class based on content of load commands
534 if ( compressed )
535 return ImageLoaderMachOCompressed::instantiateMainExecutable(mh, slide, path, segCount, libCount, context);
536 else
537 #if SUPPORT_CLASSIC_MACHO
538 return ImageLoaderMachOClassic::instantiateMainExecutable(mh, slide, path, segCount, libCount, context);
539 #else
540 throw "missing LC_DYLD_INFO load command";
541 #endif
542 }
543
544
545 // create image by mapping in a mach-o file
546 ImageLoader* ImageLoaderMachO::instantiateFromFile(const char* path, int fd, const uint8_t firstPages[], size_t firstPagesSize, uint64_t offsetInFat,
547 uint64_t lenInFat, const struct stat& info, const LinkContext& context)
548 {
549 bool compressed;
550 unsigned int segCount;
551 unsigned int libCount;
552 const linkedit_data_command* codeSigCmd;
553 const encryption_info_command* encryptCmd;
554 sniffLoadCommands((const macho_header*)firstPages, path, false, &compressed, &segCount, &libCount, context, &codeSigCmd, &encryptCmd);
555 // instantiate concrete class based on content of load commands
556 if ( compressed )
557 return ImageLoaderMachOCompressed::instantiateFromFile(path, fd, firstPages, firstPagesSize, offsetInFat, lenInFat, info, segCount, libCount, codeSigCmd, encryptCmd, context);
558 else
559 #if SUPPORT_CLASSIC_MACHO
560 return ImageLoaderMachOClassic::instantiateFromFile(path, fd, firstPages, firstPagesSize, offsetInFat, lenInFat, info, segCount, libCount, codeSigCmd, context);
561 #else
562 throw "missing LC_DYLD_INFO load command";
563 #endif
564 }
565
566 // create image by using cached mach-o file
567 ImageLoader* ImageLoaderMachO::instantiateFromCache(const macho_header* mh, const char* path, long slide, const struct stat& info, const LinkContext& context)
568 {
569 // instantiate right concrete class
570 bool compressed;
571 unsigned int segCount;
572 unsigned int libCount;
573 const linkedit_data_command* codeSigCmd;
574 const encryption_info_command* encryptCmd;
575 sniffLoadCommands(mh, path, true, &compressed, &segCount, &libCount, context, &codeSigCmd, &encryptCmd);
576 // instantiate concrete class based on content of load commands
577 if ( compressed )
578 return ImageLoaderMachOCompressed::instantiateFromCache(mh, path, slide, info, segCount, libCount, context);
579 else
580 #if SUPPORT_CLASSIC_MACHO
581 return ImageLoaderMachOClassic::instantiateFromCache(mh, path, slide, info, segCount, libCount, context);
582 #else
583 throw "missing LC_DYLD_INFO load command";
584 #endif
585 }
586
587 // create image by copying an in-memory mach-o file
588 ImageLoader* ImageLoaderMachO::instantiateFromMemory(const char* moduleName, const macho_header* mh, uint64_t len, const LinkContext& context)
589 {
590 bool compressed;
591 unsigned int segCount;
592 unsigned int libCount;
593 const linkedit_data_command* sigcmd;
594 const encryption_info_command* encryptCmd;
595 sniffLoadCommands(mh, moduleName, false, &compressed, &segCount, &libCount, context, &sigcmd, &encryptCmd);
596 // instantiate concrete class based on content of load commands
597 if ( compressed )
598 return ImageLoaderMachOCompressed::instantiateFromMemory(moduleName, mh, len, segCount, libCount, context);
599 else
600 #if SUPPORT_CLASSIC_MACHO
601 return ImageLoaderMachOClassic::instantiateFromMemory(moduleName, mh, len, segCount, libCount, context);
602 #else
603 throw "missing LC_DYLD_INFO load command";
604 #endif
605 }
606
607
608 int ImageLoaderMachO::crashIfInvalidCodeSignature()
609 {
610 // Now that segments are mapped in, try reading from first executable segment.
611 // If code signing is enabled the kernel will validate the code signature
612 // when paging in, and kill the process if invalid.
613 for(unsigned int i=0; i < fSegmentsCount; ++i) {
614 if ( (segFileOffset(i) == 0) && (segFileSize(i) != 0) ) {
615 // return read value to ensure compiler does not optimize away load
616 int* p = (int*)segActualLoadAddress(i);
617 return *p;
618 }
619 }
620 return 0;
621 }
622
623
624 void ImageLoaderMachO::parseLoadCmds(const LinkContext& context)
625 {
626 // now that segments are mapped in, get real fMachOData, fLinkEditBase, and fSlide
627 for(unsigned int i=0; i < fSegmentsCount; ++i) {
628 // set up pointer to __LINKEDIT segment
629 if ( strcmp(segName(i),"__LINKEDIT") == 0 ) {
630 if ( context.requireCodeSignature && (segFileOffset(i) > fCoveredCodeLength))
631 dyld::throwf("cannot load '%s' (segment outside of code signature)", this->getShortName());
632 fLinkEditBase = (uint8_t*)(segActualLoadAddress(i) - segFileOffset(i));
633 }
634 #if TEXT_RELOC_SUPPORT
635 // __TEXT segment always starts at beginning of file and contains mach_header and load commands
636 if ( segExecutable(i) ) {
637 if ( segHasRebaseFixUps(i) && (fSlide != 0) )
638 fTextSegmentRebases = true;
639 if ( segHasBindFixUps(i) )
640 fTextSegmentBinds = true;
641 }
642 #endif
643 #if __i386__
644 if ( segIsReadOnlyImport(i) )
645 fReadOnlyImportSegment = true;
646 #endif
647 // some segment always starts at beginning of file and contains mach_header and load commands
648 if ( (segFileOffset(i) == 0) && (segFileSize(i) != 0) ) {
649 fMachOData = (uint8_t*)(segActualLoadAddress(i));
650 }
651 }
652
653 // keep count of prebound images with weak exports
654 if ( this->participatesInCoalescing() ) {
655 ++fgImagesRequiringCoalescing;
656 fRegisteredAsRequiresCoalescing = true;
657 if ( this->hasCoalescedExports() )
658 ++fgImagesHasWeakDefinitions;
659 }
660
661 // keep count of images used in shared cache
662 if ( fInSharedCache )
663 ++fgImagesUsedFromSharedCache;
664
665 // walk load commands (mapped in at start of __TEXT segment)
666 const dyld_info_command* dyldInfo = NULL;
667 const macho_nlist* symbolTable = NULL;
668 const char* symbolTableStrings = NULL;
669 const struct load_command* firstUnknownCmd = NULL;
670 const struct version_min_command* minOSVersionCmd = NULL;
671 const dysymtab_command* dynSymbolTable = NULL;
672 const uint32_t cmd_count = ((macho_header*)fMachOData)->ncmds;
673 const struct load_command* const cmds = (struct load_command*)&fMachOData[sizeof(macho_header)];
674 const struct load_command* cmd = cmds;
675 for (uint32_t i = 0; i < cmd_count; ++i) {
676 switch (cmd->cmd) {
677 case LC_SYMTAB:
678 {
679 const struct symtab_command* symtab = (struct symtab_command*)cmd;
680 symbolTableStrings = (const char*)&fLinkEditBase[symtab->stroff];
681 symbolTable = (macho_nlist*)(&fLinkEditBase[symtab->symoff]);
682 }
683 break;
684 case LC_DYSYMTAB:
685 dynSymbolTable = (struct dysymtab_command*)cmd;
686 break;
687 case LC_SUB_UMBRELLA:
688 fHasSubUmbrella = true;
689 break;
690 case LC_SUB_FRAMEWORK:
691 fInUmbrella = true;
692 break;
693 case LC_SUB_LIBRARY:
694 fHasSubLibraries = true;
695 break;
696 case LC_ROUTINES_COMMAND:
697 fHasDashInit = true;
698 break;
699 case LC_DYLD_INFO:
700 case LC_DYLD_INFO_ONLY:
701 dyldInfo = (struct dyld_info_command*)cmd;
702 break;
703 case LC_SEGMENT_COMMAND:
704 {
705 const struct macho_segment_command* seg = (struct macho_segment_command*)cmd;
706 const bool isTextSeg = (strcmp(seg->segname, "__TEXT") == 0);
707 #if __i386__ && __MAC_OS_X_VERSION_MIN_REQUIRED
708 const bool isObjCSeg = (strcmp(seg->segname, "__OBJC") == 0);
709 if ( isObjCSeg )
710 fNotifyObjC = true;
711 #else
712 const bool isDataSeg = (strncmp(seg->segname, "__DATA", 6) == 0);
713 #endif
714 const struct macho_section* const sectionsStart = (struct macho_section*)((char*)seg + sizeof(struct macho_segment_command));
715 const struct macho_section* const sectionsEnd = &sectionsStart[seg->nsects];
716 for (const struct macho_section* sect=sectionsStart; sect < sectionsEnd; ++sect) {
717 const uint8_t type = sect->flags & SECTION_TYPE;
718 if ( type == S_MOD_INIT_FUNC_POINTERS )
719 fHasInitializers = true;
720 else if ( type == S_MOD_TERM_FUNC_POINTERS )
721 fHasTerminators = true;
722 else if ( type == S_DTRACE_DOF )
723 fHasDOFSections = true;
724 else if ( isTextSeg && (strcmp(sect->sectname, "__eh_frame") == 0) )
725 fEHFrameSectionOffset = (uint32_t)((uint8_t*)sect - fMachOData);
726 else if ( isTextSeg && (strcmp(sect->sectname, "__unwind_info") == 0) )
727 fUnwindInfoSectionOffset = (uint32_t)((uint8_t*)sect - fMachOData);
728
729 #if __i386__ && __MAC_OS_X_VERSION_MIN_REQUIRED
730 else if ( isObjCSeg ) {
731 if ( strcmp(sect->sectname, "__image_info") == 0 ) {
732 const uint32_t* imageInfo = (uint32_t*)(sect->addr + fSlide);
733 uint32_t flags = imageInfo[1];
734 if ( (flags & 4) && (((macho_header*)fMachOData)->filetype != MH_EXECUTE) )
735 dyld::throwf("cannot load '%s' because Objective-C garbage collection is not supported", getPath());
736 }
737 else if ( ((macho_header*)fMachOData)->filetype == MH_DYLIB ) {
738 fRetainForObjC = true;
739 }
740 }
741 #else
742 else if ( isDataSeg && (strncmp(sect->sectname, "__objc_imageinfo", 16) == 0) ) {
743 #if __MAC_OS_X_VERSION_MIN_REQUIRED
744 const uint32_t* imageInfo = (uint32_t*)(sect->addr + fSlide);
745 uint32_t flags = imageInfo[1];
746 if ( (flags & 4) && (((macho_header*)fMachOData)->filetype != MH_EXECUTE) )
747 dyld::throwf("cannot load '%s' because Objective-C garbage collection is not supported", getPath());
748 #endif
749 fNotifyObjC = true;
750 }
751 else if ( isDataSeg && (strncmp(sect->sectname, "__objc_", 7) == 0) && (((macho_header*)fMachOData)->filetype == MH_DYLIB) )
752 fRetainForObjC = true;
753 #endif
754 }
755 }
756 break;
757 case LC_TWOLEVEL_HINTS:
758 // no longer supported
759 break;
760 case LC_ID_DYLIB:
761 {
762 fDylibIDOffset = (uint32_t)((uint8_t*)cmd - fMachOData);
763 }
764 break;
765 case LC_RPATH:
766 case LC_LOAD_WEAK_DYLIB:
767 case LC_REEXPORT_DYLIB:
768 case LC_LOAD_UPWARD_DYLIB:
769 case LC_MAIN:
770 // do nothing, just prevent LC_REQ_DYLD exception from occuring
771 break;
772 case LC_VERSION_MIN_MACOSX:
773 case LC_VERSION_MIN_IPHONEOS:
774 case LC_VERSION_MIN_TVOS:
775 case LC_VERSION_MIN_WATCHOS:
776 minOSVersionCmd = (version_min_command*)cmd;
777 break;
778 default:
779 if ( (cmd->cmd & LC_REQ_DYLD) != 0 ) {
780 if ( firstUnknownCmd == NULL )
781 firstUnknownCmd = cmd;
782 }
783 break;
784 }
785 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
786 }
787 if ( firstUnknownCmd != NULL ) {
788 if ( minOSVersionCmd != NULL ) {
789 dyld::throwf("cannot load '%s' because it was built for OS version %u.%u (load command 0x%08X is unknown)",
790 this->getShortName(),
791 minOSVersionCmd->version >> 16, ((minOSVersionCmd->version >> 8) & 0xff),
792 firstUnknownCmd->cmd);
793 }
794 else {
795 dyld::throwf("cannot load '%s' (load command 0x%08X is unknown)", this->getShortName(), firstUnknownCmd->cmd);
796 }
797 }
798
799
800 if ( dyldInfo != NULL )
801 this->setDyldInfo(dyldInfo);
802 if ( symbolTable != NULL)
803 this->setSymbolTableInfo(symbolTable, symbolTableStrings, dynSymbolTable);
804
805 }
806
807 // don't do this work in destructor because we need object to be full subclass
808 // for UnmapSegments() to work
809 void ImageLoaderMachO::destroy()
810 {
811 // update count of images with weak exports
812 if ( fRegisteredAsRequiresCoalescing ) {
813 --fgImagesRequiringCoalescing;
814 if ( this->hasCoalescedExports() )
815 --fgImagesHasWeakDefinitions;
816 }
817
818 // keep count of images used in shared cache
819 if ( fInSharedCache )
820 --fgImagesUsedFromSharedCache;
821
822 // unmap image when done
823 UnmapSegments();
824 }
825
826
827 unsigned int ImageLoaderMachO::segmentCount() const
828 {
829 return fSegmentsCount;
830 }
831
832
833 const macho_segment_command* ImageLoaderMachO::segLoadCommand(unsigned int segIndex) const
834 {
835 uint32_t* lcOffsets = this->segmentCommandOffsets();
836 uint32_t lcOffset = lcOffsets[segIndex];
837 return (macho_segment_command*)(&fMachOData[lcOffset]);
838 }
839
840 const char* ImageLoaderMachO::segName(unsigned int segIndex) const
841 {
842 return segLoadCommand(segIndex)->segname;
843 }
844
845
846 uintptr_t ImageLoaderMachO::segSize(unsigned int segIndex) const
847 {
848 return segLoadCommand(segIndex)->vmsize;
849 }
850
851
852 uintptr_t ImageLoaderMachO::segFileSize(unsigned int segIndex) const
853 {
854 return segLoadCommand(segIndex)->filesize;
855 }
856
857
858 bool ImageLoaderMachO::segHasTrailingZeroFill(unsigned int segIndex)
859 {
860 return ( segWriteable(segIndex) && (segSize(segIndex) > segFileSize(segIndex)) );
861 }
862
863
864 uintptr_t ImageLoaderMachO::segFileOffset(unsigned int segIndex) const
865 {
866 return segLoadCommand(segIndex)->fileoff;
867 }
868
869
870 bool ImageLoaderMachO::segReadable(unsigned int segIndex) const
871 {
872 return ( (segLoadCommand(segIndex)->initprot & VM_PROT_READ) != 0);
873 }
874
875
876 bool ImageLoaderMachO::segWriteable(unsigned int segIndex) const
877 {
878 return ( (segLoadCommand(segIndex)->initprot & VM_PROT_WRITE) != 0);
879 }
880
881
882 bool ImageLoaderMachO::segExecutable(unsigned int segIndex) const
883 {
884 return ( (segLoadCommand(segIndex)->initprot & VM_PROT_EXECUTE) != 0);
885 }
886
887
888 bool ImageLoaderMachO::segUnaccessible(unsigned int segIndex) const
889 {
890 return (segLoadCommand(segIndex)->initprot == 0);
891 }
892
893 bool ImageLoaderMachO::segHasPreferredLoadAddress(unsigned int segIndex) const
894 {
895 return (segLoadCommand(segIndex)->vmaddr != 0);
896 }
897
898 uintptr_t ImageLoaderMachO::segPreferredLoadAddress(unsigned int segIndex) const
899 {
900 return segLoadCommand(segIndex)->vmaddr;
901 }
902
903 uintptr_t ImageLoaderMachO::segActualLoadAddress(unsigned int segIndex) const
904 {
905 return segLoadCommand(segIndex)->vmaddr + fSlide;
906 }
907
908
909 uintptr_t ImageLoaderMachO::segActualEndAddress(unsigned int segIndex) const
910 {
911 return segActualLoadAddress(segIndex) + segSize(segIndex);
912 }
913
914 bool ImageLoaderMachO::segHasRebaseFixUps(unsigned int segIndex) const
915 {
916 #if TEXT_RELOC_SUPPORT
917 // scan sections for fix-up bit
918 const macho_segment_command* segCmd = segLoadCommand(segIndex);
919 const struct macho_section* const sectionsStart = (struct macho_section*)((char*)segCmd + sizeof(struct macho_segment_command));
920 const struct macho_section* const sectionsEnd = &sectionsStart[segCmd->nsects];
921 for (const struct macho_section* sect=sectionsStart; sect < sectionsEnd; ++sect) {
922 if ( (sect->flags & S_ATTR_LOC_RELOC) != 0 )
923 return true;
924 }
925 #endif
926 return false;
927 }
928
929 bool ImageLoaderMachO::segHasBindFixUps(unsigned int segIndex) const
930 {
931 #if TEXT_RELOC_SUPPORT
932 // scan sections for fix-up bit
933 const macho_segment_command* segCmd = segLoadCommand(segIndex);
934 const struct macho_section* const sectionsStart = (struct macho_section*)((char*)segCmd + sizeof(struct macho_segment_command));
935 const struct macho_section* const sectionsEnd = &sectionsStart[segCmd->nsects];
936 for (const struct macho_section* sect=sectionsStart; sect < sectionsEnd; ++sect) {
937 if ( (sect->flags & S_ATTR_EXT_RELOC) != 0 )
938 return true;
939 }
940 #endif
941 return false;
942 }
943
944 #if __i386__
945 bool ImageLoaderMachO::segIsReadOnlyImport(unsigned int segIndex) const
946 {
947 const macho_segment_command* segCmd = segLoadCommand(segIndex);
948 return ( (segCmd->initprot & VM_PROT_EXECUTE)
949 && ((segCmd->initprot & VM_PROT_WRITE) == 0)
950 && (strcmp(segCmd->segname, "__IMPORT") == 0) );
951 }
952 #endif
953
954
955 void ImageLoaderMachO::UnmapSegments()
956 {
957 // usually unmap image when done
958 if ( ! this->leaveMapped() && (this->getState() >= dyld_image_state_mapped) ) {
959 // unmap TEXT segment last because it contains load command being inspected
960 unsigned int textSegmentIndex = 0;
961 for(unsigned int i=0; i < fSegmentsCount; ++i) {
962 //dyld::log("unmap %s at 0x%08lX\n", seg->getName(), seg->getActualLoadAddress(this));
963 if ( (segFileOffset(i) == 0) && (segFileSize(i) != 0) ) {
964 textSegmentIndex = i;
965 }
966 else {
967 // update stats
968 --ImageLoader::fgTotalSegmentsMapped;
969 ImageLoader::fgTotalBytesMapped -= segSize(i);
970 munmap((void*)segActualLoadAddress(i), segSize(i));
971 }
972 }
973 // now unmap TEXT
974 --ImageLoader::fgTotalSegmentsMapped;
975 ImageLoader::fgTotalBytesMapped -= segSize(textSegmentIndex);
976 munmap((void*)segActualLoadAddress(textSegmentIndex), segSize(textSegmentIndex));
977 }
978 }
979
980
981 // prefetch __DATA/__OBJC pages during launch, but not for dynamically loaded code
982 void ImageLoaderMachO::preFetchDATA(int fd, uint64_t offsetInFat, const LinkContext& context)
983 {
984 if ( context.linkingMainExecutable ) {
985 for(unsigned int i=0, e=segmentCount(); i < e; ++i) {
986 if ( segWriteable(i) && (segFileSize(i) > 0) ) {
987 // prefetch writable segment that have mmap'ed regions
988 radvisory advice;
989 advice.ra_offset = offsetInFat + segFileOffset(i);
990 advice.ra_count = (int)segFileSize(i);
991 // limit prefetch to 1MB (256 pages)
992 if ( advice.ra_count > 1024*1024 )
993 advice.ra_count = 1024*1024;
994 // don't prefetch single pages, let them fault in
995 fgTotalBytesPreFetched += advice.ra_count;
996 fcntl(fd, F_RDADVISE, &advice);
997 if ( context.verboseMapping ) {
998 dyld::log("%18s prefetching 0x%0lX -> 0x%0lX\n",
999 segName(i), segActualLoadAddress(i), segActualLoadAddress(i)+advice.ra_count-1);
1000 }
1001 }
1002 }
1003 }
1004 }
1005
1006
1007 bool ImageLoaderMachO::segmentsMustSlideTogether() const
1008 {
1009 return true;
1010 }
1011
1012 bool ImageLoaderMachO::segmentsCanSlide() const
1013 {
1014 return (this->isDylib() || this->isBundle() || this->isPositionIndependentExecutable());
1015 }
1016
1017 bool ImageLoaderMachO::isBundle() const
1018 {
1019 const macho_header* mh = (macho_header*)fMachOData;
1020 return ( mh->filetype == MH_BUNDLE );
1021 }
1022
1023 bool ImageLoaderMachO::isDylib() const
1024 {
1025 const macho_header* mh = (macho_header*)fMachOData;
1026 return ( mh->filetype == MH_DYLIB );
1027 }
1028
1029 bool ImageLoaderMachO::isExecutable() const
1030 {
1031 const macho_header* mh = (macho_header*)fMachOData;
1032 return ( mh->filetype == MH_EXECUTE );
1033 }
1034
1035 bool ImageLoaderMachO::isPositionIndependentExecutable() const
1036 {
1037 const macho_header* mh = (macho_header*)fMachOData;
1038 return ( (mh->filetype == MH_EXECUTE) && ((mh->flags & MH_PIE) != 0) );
1039 }
1040
1041
1042 bool ImageLoaderMachO::forceFlat() const
1043 {
1044 const macho_header* mh = (macho_header*)fMachOData;
1045 return ( (mh->flags & MH_FORCE_FLAT) != 0 );
1046 }
1047
1048 bool ImageLoaderMachO::usesTwoLevelNameSpace() const
1049 {
1050 const macho_header* mh = (macho_header*)fMachOData;
1051 return ( (mh->flags & MH_TWOLEVEL) != 0 );
1052 }
1053
1054 bool ImageLoaderMachO::isPrebindable() const
1055 {
1056 const macho_header* mh = (macho_header*)fMachOData;
1057 return ( (mh->flags & MH_PREBOUND) != 0 );
1058 }
1059
1060 bool ImageLoaderMachO::hasCoalescedExports() const
1061 {
1062 const macho_header* mh = (macho_header*)fMachOData;
1063 return ( (mh->flags & MH_WEAK_DEFINES) != 0 );
1064 }
1065
1066 bool ImageLoaderMachO::hasReferencesToWeakSymbols() const
1067 {
1068 const macho_header* mh = (macho_header*)fMachOData;
1069 return ( (mh->flags & MH_BINDS_TO_WEAK) != 0 );
1070 }
1071
1072 bool ImageLoaderMachO::participatesInCoalescing() const
1073 {
1074 const macho_header* mh = (macho_header*)fMachOData;
1075 // if image is loaded with RTLD_LOCAL, then its symbols' visibility
1076 // is reduced and it can't coalesce with other images
1077 if ( this->hasHiddenExports() )
1078 return false;
1079 return ( (mh->flags & (MH_WEAK_DEFINES|MH_BINDS_TO_WEAK)) != 0 );
1080 }
1081
1082
1083
1084 void ImageLoaderMachO::setSlide(intptr_t slide)
1085 {
1086 fSlide = slide;
1087 }
1088
1089 void ImageLoaderMachO::loadCodeSignature(const struct linkedit_data_command* codeSigCmd, int fd, uint64_t offsetInFatFile, const LinkContext& context)
1090 {
1091 // if dylib being loaded has no code signature load command
1092 if ( codeSigCmd == NULL) {
1093 if (context.requireCodeSignature ) {
1094 // if we require dylibs to be codesigned there needs to be a signature.
1095 dyld::throwf("required code signature missing for '%s'\n", this->getPath());
1096 } else {
1097 disableCoverageCheck();
1098 }
1099 }
1100 else {
1101 #if __MAC_OS_X_VERSION_MIN_REQUIRED
1102 // <rdar://problem/13622786> ignore code signatures in binaries built with pre-10.9 tools
1103 if ( this->sdkVersion() < DYLD_MACOSX_VERSION_10_9 ) {
1104 return;
1105 }
1106 #endif
1107 fsignatures_t siginfo;
1108 siginfo.fs_file_start=offsetInFatFile; // start of mach-o slice in fat file
1109 siginfo.fs_blob_start=(void*)(long)(codeSigCmd->dataoff); // start of CD in mach-o file
1110 siginfo.fs_blob_size=codeSigCmd->datasize; // size of CD
1111 int result = fcntl(fd, F_ADDFILESIGS_RETURN, &siginfo);
1112
1113 #if TARGET_IPHONE_SIMULATOR
1114 // rdar://problem/18759224> check range covered by the code directory after loading
1115 // Attempt to fallback only if we are in the simulator
1116
1117 if ( result == -1 ) {
1118 result = fcntl(fd, F_ADDFILESIGS, &siginfo);
1119 siginfo.fs_file_start = codeSigCmd->dataoff;
1120 }
1121 #endif
1122
1123 if ( result == -1 ) {
1124 if ( (errno == EPERM) || (errno == EBADEXEC) )
1125 dyld::throwf("code signature invalid for '%s'\n", this->getPath());
1126 if ( context.verboseCodeSignatures )
1127 dyld::log("dyld: Failed registering code signature for %s, errno=%d\n", this->getPath(), errno);
1128 siginfo.fs_file_start = UINT64_MAX;
1129 } else if ( context.verboseCodeSignatures ) {
1130 dyld::log("dyld: Registered code signature for %s\n", this->getPath());
1131 }
1132 fCoveredCodeLength = siginfo.fs_file_start;
1133
1134 #if __MAC_OS_X_VERSION_MIN_REQUIRED
1135 if ( context.processUsingLibraryValidation ) {
1136 fchecklv checkInfo;
1137 char messageBuffer[512];
1138 messageBuffer[0] = '\0';
1139 checkInfo.lv_file_start = offsetInFatFile;
1140 checkInfo.lv_error_message_size = sizeof(messageBuffer);
1141 checkInfo.lv_error_message = messageBuffer;
1142 int res = fcntl(fd, F_CHECK_LV, &checkInfo);
1143 if ( res == -1 ) {
1144 dyld::throwf("code signature in (%s) not valid for use in process using Library Validation: %s", this->getPath(), messageBuffer);
1145 }
1146 }
1147 #endif
1148 }
1149 }
1150
1151 void ImageLoaderMachO::validateFirstPages(const struct linkedit_data_command* codeSigCmd, int fd, const uint8_t *fileData, size_t lenFileData, off_t offsetInFat, const LinkContext& context)
1152 {
1153 #if __MAC_OS_X_VERSION_MIN_REQUIRED
1154 // rdar://problem/21839703> 15A226d: dyld crashes in mageLoaderMachO::validateFirstPages during dlopen() after encountering an mmap failure
1155 // We need to ignore older code signatures because they will be bad.
1156 if ( this->sdkVersion() < DYLD_MACOSX_VERSION_10_9 ) {
1157 return;
1158 }
1159 #endif
1160 if (codeSigCmd != NULL) {
1161 void *fdata = xmmap(NULL, lenFileData, PROT_READ | PROT_EXEC, MAP_SHARED, fd, offsetInFat);
1162 if ( fdata == MAP_FAILED ) {
1163 #if __MAC_OS_X_VERSION_MIN_REQUIRED
1164 if ( context.processUsingLibraryValidation ) {
1165 dyld::throwf("cannot load image with wrong team ID in process using Library Validation");
1166 }
1167 else
1168 #endif
1169 {
1170 int errnoCopy = errno;
1171 if ( errnoCopy == EPERM ) {
1172 if ( dyld::sandboxBlockedMmap(getPath()) )
1173 dyld::throwf("file system sandbox blocked mmap() of '%s'", getPath());
1174 else
1175 dyld::throwf("code signing blocked mmap() of '%s'", getPath());
1176 }
1177 else
1178 dyld::throwf("mmap() errno=%d validating first page of '%s'", errnoCopy, getPath());
1179 }
1180 }
1181 if ( memcmp(fdata, fileData, lenFileData) != 0 )
1182 dyld::throwf("mmap() page compare failed for '%s'", getPath());
1183 munmap(fdata, lenFileData);
1184 }
1185 }
1186
1187
1188 const char* ImageLoaderMachO::getInstallPath() const
1189 {
1190 if ( fDylibIDOffset != 0 ) {
1191 const dylib_command* dylibID = (dylib_command*)(&fMachOData[fDylibIDOffset]);
1192 return (char*)dylibID + dylibID->dylib.name.offset;
1193 }
1194 return NULL;
1195 }
1196
1197 void ImageLoaderMachO::registerInterposing()
1198 {
1199 // mach-o files advertise interposing by having a __DATA __interpose section
1200 struct InterposeData { uintptr_t replacement; uintptr_t replacee; };
1201 const uint32_t cmd_count = ((macho_header*)fMachOData)->ncmds;
1202 const struct load_command* const cmds = (struct load_command*)&fMachOData[sizeof(macho_header)];
1203 const struct load_command* cmd = cmds;
1204 for (uint32_t i = 0; i < cmd_count; ++i) {
1205 switch (cmd->cmd) {
1206 case LC_SEGMENT_COMMAND:
1207 {
1208 const struct macho_segment_command* seg = (struct macho_segment_command*)cmd;
1209 const struct macho_section* const sectionsStart = (struct macho_section*)((char*)seg + sizeof(struct macho_segment_command));
1210 const struct macho_section* const sectionsEnd = &sectionsStart[seg->nsects];
1211 for (const struct macho_section* sect=sectionsStart; sect < sectionsEnd; ++sect) {
1212 if ( ((sect->flags & SECTION_TYPE) == S_INTERPOSING) || ((strcmp(sect->sectname, "__interpose") == 0) && (strcmp(seg->segname, "__DATA") == 0)) ) {
1213 // <rdar://problem/23929217> Ensure section is within segment
1214 if ( (sect->addr < seg->vmaddr) || (sect->addr+sect->size > seg->vmaddr+seg->vmsize) || (sect->addr+sect->size < sect->addr) )
1215 dyld::throwf("interpose section has malformed address range for %s\n", this->getPath());
1216 const InterposeData* interposeArray = (InterposeData*)(sect->addr + fSlide);
1217 const size_t count = sect->size / sizeof(InterposeData);
1218 for (size_t j=0; j < count; ++j) {
1219 ImageLoader::InterposeTuple tuple;
1220 tuple.replacement = interposeArray[j].replacement;
1221 tuple.neverImage = this;
1222 tuple.onlyImage = NULL;
1223 tuple.replacee = interposeArray[j].replacee;
1224 // <rdar://problem/25686570> ignore interposing on a weak function that does not exist
1225 if ( tuple.replacee == 0 )
1226 continue;
1227 // <rdar://problem/7937695> verify that replacement is in this image
1228 if ( this->containsAddress((void*)tuple.replacement) ) {
1229 // chain to any existing interpositions
1230 for (std::vector<InterposeTuple>::iterator it=fgInterposingTuples.begin(); it != fgInterposingTuples.end(); it++) {
1231 if ( it->replacee == tuple.replacee ) {
1232 tuple.replacee = it->replacement;
1233 }
1234 }
1235 ImageLoader::fgInterposingTuples.push_back(tuple);
1236 }
1237 }
1238 }
1239 }
1240 }
1241 break;
1242 }
1243 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
1244 }
1245 }
1246
1247 uint32_t ImageLoaderMachO::sdkVersion(const mach_header* mh)
1248 {
1249 const uint32_t cmd_count = mh->ncmds;
1250 const struct load_command* const cmds = (struct load_command*)(((char*)mh) + sizeof(macho_header));
1251 const struct load_command* cmd = cmds;
1252 const struct version_min_command* versCmd;
1253 for (uint32_t i = 0; i < cmd_count; ++i) {
1254 switch ( cmd->cmd ) {
1255 case LC_VERSION_MIN_MACOSX:
1256 case LC_VERSION_MIN_IPHONEOS:
1257 case LC_VERSION_MIN_TVOS:
1258 case LC_VERSION_MIN_WATCHOS:
1259 versCmd = (version_min_command*)cmd;
1260 return versCmd->sdk;
1261 }
1262 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
1263 }
1264 return 0;
1265 }
1266
1267 uint32_t ImageLoaderMachO::sdkVersion() const
1268 {
1269 return ImageLoaderMachO::sdkVersion(machHeader());
1270 }
1271
1272 uint32_t ImageLoaderMachO::minOSVersion(const mach_header* mh)
1273 {
1274 const uint32_t cmd_count = mh->ncmds;
1275 const struct load_command* const cmds = (struct load_command*)(((char*)mh) + sizeof(macho_header));
1276 const struct load_command* cmd = cmds;
1277 const struct version_min_command* versCmd;
1278 for (uint32_t i = 0; i < cmd_count; ++i) {
1279 switch ( cmd->cmd ) {
1280 case LC_VERSION_MIN_MACOSX:
1281 case LC_VERSION_MIN_IPHONEOS:
1282 case LC_VERSION_MIN_TVOS:
1283 case LC_VERSION_MIN_WATCHOS:
1284 versCmd = (version_min_command*)cmd;
1285 return versCmd->version;
1286 }
1287 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
1288 }
1289 return 0;
1290 }
1291
1292 uint32_t ImageLoaderMachO::minOSVersion() const
1293 {
1294 return ImageLoaderMachO::minOSVersion(machHeader());
1295 }
1296
1297
1298 void* ImageLoaderMachO::getThreadPC() const
1299 {
1300 const uint32_t cmd_count = ((macho_header*)fMachOData)->ncmds;
1301 const struct load_command* const cmds = (struct load_command*)&fMachOData[sizeof(macho_header)];
1302 const struct load_command* cmd = cmds;
1303 for (uint32_t i = 0; i < cmd_count; ++i) {
1304 if ( cmd->cmd == LC_MAIN ) {
1305 entry_point_command* mainCmd = (entry_point_command*)cmd;
1306 void* entry = (void*)(mainCmd->entryoff + (char*)fMachOData);
1307 // <rdar://problem/8543820&9228031> verify entry point is in image
1308 if ( this->containsAddress(entry) )
1309 return entry;
1310 else
1311 throw "LC_MAIN entryoff is out of range";
1312 }
1313 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
1314 }
1315 return NULL;
1316 }
1317
1318
1319 void* ImageLoaderMachO::getMain() const
1320 {
1321 const uint32_t cmd_count = ((macho_header*)fMachOData)->ncmds;
1322 const struct load_command* const cmds = (struct load_command*)&fMachOData[sizeof(macho_header)];
1323 const struct load_command* cmd = cmds;
1324 for (uint32_t i = 0; i < cmd_count; ++i) {
1325 switch (cmd->cmd) {
1326 case LC_UNIXTHREAD:
1327 {
1328 #if __i386__
1329 const i386_thread_state_t* registers = (i386_thread_state_t*)(((char*)cmd) + 16);
1330 void* entry = (void*)(registers->eip + fSlide);
1331 #elif __x86_64__
1332 const x86_thread_state64_t* registers = (x86_thread_state64_t*)(((char*)cmd) + 16);
1333 void* entry = (void*)(registers->rip + fSlide);
1334 #elif __arm__
1335 const arm_thread_state_t* registers = (arm_thread_state_t*)(((char*)cmd) + 16);
1336 void* entry = (void*)(registers->__pc + fSlide);
1337 #elif __arm64__
1338 const arm_thread_state64_t* registers = (arm_thread_state64_t*)(((char*)cmd) + 16);
1339 void* entry = (void*)(registers->__pc + fSlide);
1340 #else
1341 #warning need processor specific code
1342 #endif
1343 // <rdar://problem/8543820&9228031> verify entry point is in image
1344 if ( this->containsAddress(entry) ) {
1345 return entry;
1346 }
1347 }
1348 break;
1349 }
1350 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
1351 }
1352 throw "no valid entry point";
1353 }
1354
1355 bool ImageLoaderMachO::needsAddedLibSystemDepency(unsigned int libCount, const macho_header* mh)
1356 {
1357 // <rdar://problem/6357561> ensure that every image depends on something which depends on libSystem
1358 if ( libCount > 1 )
1359 return false;
1360
1361 // <rdar://problem/6409800> dyld implicit-libSystem breaks valgrind
1362 if ( mh->filetype == MH_EXECUTE )
1363 return false;
1364
1365 bool isNonOSdylib = false;
1366 const uint32_t cmd_count = mh->ncmds;
1367 const struct load_command* const cmds = (struct load_command*)((uint8_t*)mh+sizeof(macho_header));
1368 const struct load_command* cmd = cmds;
1369 for (uint32_t i = 0; i < cmd_count; ++i) {
1370 switch (cmd->cmd) {
1371 case LC_LOAD_DYLIB:
1372 case LC_LOAD_WEAK_DYLIB:
1373 case LC_REEXPORT_DYLIB:
1374 case LC_LOAD_UPWARD_DYLIB:
1375 return false;
1376 case LC_ID_DYLIB:
1377 {
1378 const dylib_command* dylibID = (dylib_command*)cmd;
1379 const char* installPath = (char*)cmd + dylibID->dylib.name.offset;
1380 // It is OK for OS dylibs (libSystem or libmath or Rosetta shims) to have no dependents
1381 // but all other dylibs must depend on libSystem for initialization to initialize libSystem first
1382 // <rdar://problem/6497528> rosetta circular dependency spew
1383 isNonOSdylib = ( (strncmp(installPath, "/usr/lib/", 9) != 0) && (strncmp(installPath, "/usr/libexec/oah/Shims", 9) != 0) );
1384 }
1385 break;
1386 }
1387 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
1388 }
1389 return isNonOSdylib;
1390 }
1391
1392
1393 void ImageLoaderMachO::doGetDependentLibraries(DependentLibraryInfo libs[])
1394 {
1395 if ( needsAddedLibSystemDepency(libraryCount(), (macho_header*)fMachOData) ) {
1396 DependentLibraryInfo* lib = &libs[0];
1397 lib->name = LIBSYSTEM_DYLIB_PATH;
1398 lib->info.checksum = 0;
1399 lib->info.minVersion = 0;
1400 lib->info.maxVersion = 0;
1401 lib->required = false;
1402 lib->reExported = false;
1403 lib->upward = false;
1404 }
1405 else {
1406 uint32_t index = 0;
1407 const uint32_t cmd_count = ((macho_header*)fMachOData)->ncmds;
1408 const struct load_command* const cmds = (struct load_command*)&fMachOData[sizeof(macho_header)];
1409 const struct load_command* cmd = cmds;
1410 for (uint32_t i = 0; i < cmd_count; ++i) {
1411 switch (cmd->cmd) {
1412 case LC_LOAD_DYLIB:
1413 case LC_LOAD_WEAK_DYLIB:
1414 case LC_REEXPORT_DYLIB:
1415 case LC_LOAD_UPWARD_DYLIB:
1416 {
1417 const struct dylib_command* dylib = (struct dylib_command*)cmd;
1418 DependentLibraryInfo* lib = &libs[index++];
1419 lib->name = (char*)cmd + dylib->dylib.name.offset;
1420 //lib->name = strdup((char*)cmd + dylib->dylib.name.offset);
1421 lib->info.checksum = dylib->dylib.timestamp;
1422 lib->info.minVersion = dylib->dylib.compatibility_version;
1423 lib->info.maxVersion = dylib->dylib.current_version;
1424 lib->required = (cmd->cmd != LC_LOAD_WEAK_DYLIB);
1425 lib->reExported = (cmd->cmd == LC_REEXPORT_DYLIB);
1426 lib->upward = (cmd->cmd == LC_LOAD_UPWARD_DYLIB);
1427 }
1428 break;
1429 }
1430 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
1431 }
1432 }
1433 }
1434
1435 ImageLoader::LibraryInfo ImageLoaderMachO::doGetLibraryInfo(const LibraryInfo&)
1436 {
1437 LibraryInfo info;
1438 if ( fDylibIDOffset != 0 ) {
1439 const dylib_command* dylibID = (dylib_command*)(&fMachOData[fDylibIDOffset]);
1440 info.minVersion = dylibID->dylib.compatibility_version;
1441 info.maxVersion = dylibID->dylib.current_version;
1442 info.checksum = dylibID->dylib.timestamp;
1443 }
1444 else {
1445 info.minVersion = 0;
1446 info.maxVersion = 0;
1447 info.checksum = 0;
1448 }
1449 return info;
1450 }
1451
1452 void ImageLoaderMachO::getRPaths(const LinkContext& context, std::vector<const char*>& paths) const
1453 {
1454 const uint32_t cmd_count = ((macho_header*)fMachOData)->ncmds;
1455 const struct load_command* const cmds = (struct load_command*)&fMachOData[sizeof(macho_header)];
1456 const struct load_command* cmd = cmds;
1457 for (uint32_t i = 0; i < cmd_count; ++i) {
1458 switch (cmd->cmd) {
1459 case LC_RPATH:
1460 const char* pathToAdd = NULL;
1461 const char* path = (char*)cmd + ((struct rpath_command*)cmd)->path.offset;
1462 if ( (strncmp(path, "@loader_path", 12) == 0) && ((path[12] == '/') || (path[12] == '\0')) ) {
1463 #if __MAC_OS_X_VERSION_MIN_REQUIRED
1464 if ( context.processIsRestricted && (context.mainExecutable == this) ) {
1465 dyld::warn("LC_RPATH %s in %s being ignored in restricted program because of @loader_path\n", path, this->getPath());
1466 break;
1467 }
1468 #endif
1469 char resolvedPath[PATH_MAX];
1470 if ( realpath(this->getPath(), resolvedPath) != NULL ) {
1471 char newRealPath[strlen(resolvedPath) + strlen(path)];
1472 strcpy(newRealPath, resolvedPath);
1473 char* addPoint = strrchr(newRealPath,'/');
1474 if ( addPoint != NULL ) {
1475 strcpy(addPoint, &path[12]);
1476 pathToAdd = strdup(newRealPath);
1477 }
1478 }
1479 }
1480 else if ( (strncmp(path, "@executable_path", 16) == 0) && ((path[16] == '/') || (path[16] == '\0')) ) {
1481 #if __MAC_OS_X_VERSION_MIN_REQUIRED
1482 if ( context.processIsRestricted ) {
1483 dyld::warn("LC_RPATH %s in %s being ignored in restricted program because of @executable_path\n", path, this->getPath());
1484 break;
1485 }
1486 #endif
1487 char resolvedPath[PATH_MAX];
1488 if ( realpath(context.mainExecutable->getPath(), resolvedPath) != NULL ) {
1489 char newRealPath[strlen(resolvedPath) + strlen(path)];
1490 strcpy(newRealPath, resolvedPath);
1491 char* addPoint = strrchr(newRealPath,'/');
1492 if ( addPoint != NULL ) {
1493 strcpy(addPoint, &path[16]);
1494 pathToAdd = strdup(newRealPath);
1495 }
1496 }
1497 }
1498 #if __MAC_OS_X_VERSION_MIN_REQUIRED
1499 else if ( (path[0] != '/') && context.processIsRestricted ) {
1500 dyld::warn("LC_RPATH %s in %s being ignored in restricted program because it is a relative path\n", path, this->getPath());
1501 break;
1502 }
1503 #endif
1504 #if SUPPORT_ROOT_PATH
1505 else if ( (path[0] == '/') && (context.rootPaths != NULL) ) {
1506 // <rdar://problem/5869973> DYLD_ROOT_PATH should apply to LC_RPATH rpaths
1507 // DYLD_ROOT_PATH can be a list of paths, but at this point we can only support one, so use first combination that exists
1508 bool found = false;
1509 for(const char** rp = context.rootPaths; *rp != NULL; ++rp) {
1510 char newPath[PATH_MAX];
1511 strlcpy(newPath, *rp, PATH_MAX);
1512 strlcat(newPath, path, PATH_MAX);
1513 struct stat stat_buf;
1514 if ( stat(newPath, &stat_buf) != -1 ) {
1515 //dyld::log("combined DYLD_ROOT_PATH and LC_RPATH: %s\n", newPath);
1516 pathToAdd = strdup(newPath);
1517 found = true;
1518 break;
1519 }
1520 }
1521 if ( ! found ) {
1522 // make copy so that all elements of 'paths' can be freed
1523 pathToAdd = strdup(path);
1524 }
1525 }
1526 #endif
1527 else {
1528 // make copy so that all elements of 'paths' can be freed
1529 pathToAdd = strdup(path);
1530 }
1531 if ( pathToAdd != NULL )
1532 paths.push_back(pathToAdd);
1533 break;
1534 }
1535 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
1536 }
1537 }
1538
1539
1540 bool ImageLoaderMachO::getUUID(uuid_t uuid) const
1541 {
1542 const uint32_t cmd_count = ((macho_header*)fMachOData)->ncmds;
1543 const struct load_command* const cmds = (struct load_command*)&fMachOData[sizeof(macho_header)];
1544 const struct load_command* cmd = cmds;
1545 for (uint32_t i = 0; i < cmd_count; ++i) {
1546 switch (cmd->cmd) {
1547 case LC_UUID:
1548 uuid_command* uc = (uuid_command*)cmd;
1549 memcpy(uuid, uc->uuid, 16);
1550 return true;
1551 }
1552 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
1553 }
1554 bzero(uuid, 16);
1555 return false;
1556 }
1557
1558 void ImageLoaderMachO::doRebase(const LinkContext& context)
1559 {
1560 // <rdar://problem/25329861> Delay calling setNeverUnload() until we know this is not for dlopen_preflight()
1561 if ( fRetainForObjC )
1562 this->setNeverUnload();
1563
1564 // if prebound and loaded at prebound address, then no need to rebase
1565 if ( this->usablePrebinding(context) ) {
1566 // skip rebasing because prebinding is valid
1567 ++fgImagesWithUsedPrebinding; // bump totals for statistics
1568 return;
1569 }
1570
1571 // print why prebinding was not used
1572 if ( context.verbosePrebinding ) {
1573 if ( !this->isPrebindable() ) {
1574 dyld::log("dyld: image not prebound, so could not use prebinding in %s\n", this->getPath());
1575 }
1576 else if ( fSlide != 0 ) {
1577 dyld::log("dyld: image slid, so could not use prebinding in %s\n", this->getPath());
1578 }
1579 else if ( !this->allDependentLibrariesAsWhenPreBound() ) {
1580 dyld::log("dyld: dependent libraries changed, so could not use prebinding in %s\n", this->getPath());
1581 }
1582 else if ( !this->usesTwoLevelNameSpace() ){
1583 dyld::log("dyld: image uses flat-namespace so, parts of prebinding ignored %s\n", this->getPath());
1584 }
1585 else {
1586 dyld::log("dyld: environment variable disabled use of prebinding in %s\n", this->getPath());
1587 }
1588 }
1589
1590 //dyld::log("slide=0x%08lX for %s\n", slide, this->getPath());
1591
1592 #if PREBOUND_IMAGE_SUPPORT
1593 // if prebound and we got here, then prebinding is not valid, so reset all lazy pointers
1594 // if this image is in the shared cache, do not reset, they will be bound in doBind()
1595 if ( this->isPrebindable() && !fInSharedCache )
1596 this->resetPreboundLazyPointers(context);
1597 #endif
1598
1599 // if loaded at preferred address, no rebasing necessary
1600 if ( this->fSlide == 0 )
1601 return;
1602
1603 #if TEXT_RELOC_SUPPORT
1604 // if there are __TEXT fixups, temporarily make __TEXT writable
1605 if ( fTextSegmentRebases )
1606 this->makeTextSegmentWritable(context, true);
1607 #endif
1608
1609 // do actual rebasing
1610 this->rebase(context, fSlide);
1611
1612 #if TEXT_RELOC_SUPPORT
1613 // if there were __TEXT fixups, restore write protection
1614 if ( fTextSegmentRebases )
1615 this->makeTextSegmentWritable(context, false);
1616
1617 #endif
1618 }
1619
1620 #if TEXT_RELOC_SUPPORT
1621 void ImageLoaderMachO::makeTextSegmentWritable(const LinkContext& context, bool writeable)
1622 {
1623 for(unsigned int i=0; i < fSegmentsCount; ++i) {
1624 if ( segExecutable(i) ) {
1625 if ( writeable ) {
1626 segMakeWritable(i, context);
1627 }
1628 else {
1629 #if !__i386__ && !__x86_64__
1630 // some processors require range to be invalidated before it is made executable
1631 sys_icache_invalidate((void*)segActualLoadAddress(i), segSize(textSegmentIndex));
1632 #endif
1633 segProtect(i, context);
1634 }
1635 }
1636 }
1637
1638 }
1639 #endif
1640
1641 const ImageLoader::Symbol* ImageLoaderMachO::findExportedSymbol(const char* name, bool searchReExports, const char* thisPath, const ImageLoader** foundIn) const
1642 {
1643 // look in this image first
1644 const ImageLoader::Symbol* result = this->findShallowExportedSymbol(name, foundIn);
1645 if ( result != NULL )
1646 return result;
1647
1648 if ( searchReExports ) {
1649 for(unsigned int i=0; i < libraryCount(); ++i){
1650 if ( libReExported(i) ) {
1651 ImageLoader* image = libImage(i);
1652 if ( image != NULL ) {
1653 const char* reExPath = libPath(i);
1654 result = image->findExportedSymbol(name, searchReExports, reExPath, foundIn);
1655 if ( result != NULL )
1656 return result;
1657 }
1658 }
1659 }
1660 }
1661
1662
1663 return NULL;
1664 }
1665
1666
1667
1668 uintptr_t ImageLoaderMachO::getExportedSymbolAddress(const Symbol* sym, const LinkContext& context,
1669 const ImageLoader* requestor, bool runResolver, const char* symbolName) const
1670 {
1671 return this->getSymbolAddress(sym, requestor, context, runResolver);
1672 }
1673
1674 uintptr_t ImageLoaderMachO::getSymbolAddress(const Symbol* sym, const ImageLoader* requestor,
1675 const LinkContext& context, bool runResolver) const
1676 {
1677 uintptr_t result = exportedSymbolAddress(context, sym, requestor, runResolver);
1678 // check for interposing overrides
1679 result = interposedAddress(context, result, requestor);
1680 return result;
1681 }
1682
1683 ImageLoader::DefinitionFlags ImageLoaderMachO::getExportedSymbolInfo(const Symbol* sym) const
1684 {
1685 if ( exportedSymbolIsWeakDefintion(sym) )
1686 return kWeakDefinition;
1687 else
1688 return kNoDefinitionOptions;
1689 }
1690
1691 const char* ImageLoaderMachO::getExportedSymbolName(const Symbol* sym) const
1692 {
1693 return exportedSymbolName(sym);
1694 }
1695
1696 uint32_t ImageLoaderMachO::getExportedSymbolCount() const
1697 {
1698 return exportedSymbolCount();
1699 }
1700
1701
1702 const ImageLoader::Symbol* ImageLoaderMachO::getIndexedExportedSymbol(uint32_t index) const
1703 {
1704 return exportedSymbolIndexed(index);
1705 }
1706
1707
1708 uint32_t ImageLoaderMachO::getImportedSymbolCount() const
1709 {
1710 return importedSymbolCount();
1711 }
1712
1713
1714 const ImageLoader::Symbol* ImageLoaderMachO::getIndexedImportedSymbol(uint32_t index) const
1715 {
1716 return importedSymbolIndexed(index);
1717 }
1718
1719
1720 ImageLoader::ReferenceFlags ImageLoaderMachO::getImportedSymbolInfo(const ImageLoader::Symbol* sym) const
1721 {
1722 ImageLoader::ReferenceFlags flags = kNoReferenceOptions;
1723 return flags;
1724 }
1725
1726
1727 const char* ImageLoaderMachO::getImportedSymbolName(const ImageLoader::Symbol* sym) const
1728 {
1729 return importedSymbolName(sym);
1730 }
1731
1732
1733 bool ImageLoaderMachO::getSectionContent(const char* segmentName, const char* sectionName, void** start, size_t* length)
1734 {
1735 const uint32_t cmd_count = ((macho_header*)fMachOData)->ncmds;
1736 const struct load_command* const cmds = (struct load_command*)&fMachOData[sizeof(macho_header)];
1737 const struct load_command* cmd = cmds;
1738 for (uint32_t i = 0; i < cmd_count; ++i) {
1739 switch (cmd->cmd) {
1740 case LC_SEGMENT_COMMAND:
1741 {
1742 const struct macho_segment_command* seg = (struct macho_segment_command*)cmd;
1743 const struct macho_section* const sectionsStart = (struct macho_section*)((char*)seg + sizeof(struct macho_segment_command));
1744 const struct macho_section* const sectionsEnd = &sectionsStart[seg->nsects];
1745 for (const struct macho_section* sect=sectionsStart; sect < sectionsEnd; ++sect) {
1746 if ( (strcmp(sect->segname, segmentName) == 0) && (strcmp(sect->sectname, sectionName) == 0) ) {
1747 *start = (uintptr_t*)(sect->addr + fSlide);
1748 *length = sect->size;
1749 return true;
1750 }
1751 }
1752 }
1753 break;
1754 }
1755 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
1756 }
1757 *start = NULL;
1758 *length = 0;
1759 return false;
1760 }
1761
1762 void ImageLoaderMachO::getUnwindInfo(dyld_unwind_sections* info)
1763 {
1764 info->mh = this->machHeader();
1765 info->dwarf_section = 0;
1766 info->dwarf_section_length = 0;
1767 info->compact_unwind_section = 0;
1768 info->compact_unwind_section_length = 0;
1769 if ( fEHFrameSectionOffset != 0 ) {
1770 const macho_section* sect = (macho_section*)&fMachOData[fEHFrameSectionOffset];
1771 info->dwarf_section = (void*)(sect->addr + fSlide);
1772 info->dwarf_section_length = sect->size;
1773 }
1774 if ( fUnwindInfoSectionOffset != 0 ) {
1775 const macho_section* sect = (macho_section*)&fMachOData[fUnwindInfoSectionOffset];
1776 info->compact_unwind_section = (void*)(sect->addr + fSlide);
1777 info->compact_unwind_section_length = sect->size;
1778 }
1779 }
1780
1781 intptr_t ImageLoaderMachO::computeSlide(const mach_header* mh)
1782 {
1783 const uint32_t cmd_count = mh->ncmds;
1784 const load_command* const cmds = (load_command*)((char*)mh + sizeof(macho_header));
1785 const load_command* cmd = cmds;
1786 for (uint32_t i = 0; i < cmd_count; ++i) {
1787 if ( cmd->cmd == LC_SEGMENT_COMMAND ) {
1788 const macho_segment_command* seg = (macho_segment_command*)cmd;
1789 if ( (seg->fileoff == 0) && (seg->filesize != 0) )
1790 return (char*)mh - (char*)(seg->vmaddr);
1791 }
1792 cmd = (const load_command*)(((char*)cmd)+cmd->cmdsize);
1793 }
1794 return 0;
1795 }
1796
1797 bool ImageLoaderMachO::findSection(const mach_header* mh, const char* segmentName, const char* sectionName, void** sectAddress, size_t* sectSize)
1798 {
1799 const uint32_t cmd_count = mh->ncmds;
1800 const load_command* const cmds = (load_command*)((char*)mh + sizeof(macho_header));
1801 const load_command* cmd = cmds;
1802 for (uint32_t i = 0; i < cmd_count; ++i) {
1803 switch (cmd->cmd) {
1804 case LC_SEGMENT_COMMAND:
1805 {
1806 const macho_segment_command* seg = (macho_segment_command*)cmd;
1807 const macho_section* const sectionsStart = (macho_section*)((char*)seg + sizeof(macho_segment_command));
1808 const macho_section* const sectionsEnd = &sectionsStart[seg->nsects];
1809 for (const macho_section* sect=sectionsStart; sect < sectionsEnd; ++sect) {
1810 if ( (strcmp(sect->segname, segmentName) == 0) && (strcmp(sect->sectname, sectionName) == 0) ) {
1811 *sectAddress = (void*)(sect->addr + computeSlide(mh));
1812 *sectSize = sect->size;
1813 return true;
1814 }
1815 }
1816 }
1817 break;
1818 }
1819 cmd = (const load_command*)(((char*)cmd)+cmd->cmdsize);
1820 }
1821 return false;
1822 }
1823
1824
1825 bool ImageLoaderMachO::findSection(const void* imageInterior, const char** segmentName, const char** sectionName, size_t* sectionOffset)
1826 {
1827 const uint32_t cmd_count = ((macho_header*)fMachOData)->ncmds;
1828 const struct load_command* const cmds = (struct load_command*)&fMachOData[sizeof(macho_header)];
1829 const struct load_command* cmd = cmds;
1830 const uintptr_t unslidInteriorAddress = (uintptr_t)imageInterior - this->getSlide();
1831 for (uint32_t i = 0; i < cmd_count; ++i) {
1832 switch (cmd->cmd) {
1833 case LC_SEGMENT_COMMAND:
1834 {
1835 const struct macho_segment_command* seg = (struct macho_segment_command*)cmd;
1836 if ( (unslidInteriorAddress >= seg->vmaddr) && (unslidInteriorAddress < (seg->vmaddr+seg->vmsize)) ) {
1837 const struct macho_section* const sectionsStart = (struct macho_section*)((char*)seg + sizeof(struct macho_segment_command));
1838 const struct macho_section* const sectionsEnd = &sectionsStart[seg->nsects];
1839 for (const struct macho_section* sect=sectionsStart; sect < sectionsEnd; ++sect) {
1840 if ((sect->addr <= unslidInteriorAddress) && (unslidInteriorAddress < (sect->addr+sect->size))) {
1841 if ( segmentName != NULL )
1842 *segmentName = sect->segname;
1843 if ( sectionName != NULL )
1844 *sectionName = sect->sectname;
1845 if ( sectionOffset != NULL )
1846 *sectionOffset = unslidInteriorAddress - sect->addr;
1847 return true;
1848 }
1849 }
1850 }
1851 }
1852 break;
1853 }
1854 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
1855 }
1856 return false;
1857 }
1858
1859 const char* ImageLoaderMachO::libPath(unsigned int index) const
1860 {
1861 const uint32_t cmd_count = ((macho_header*)fMachOData)->ncmds;
1862 const struct load_command* const cmds = (struct load_command*)&fMachOData[sizeof(macho_header)];
1863 const struct load_command* cmd = cmds;
1864 unsigned count = 0;
1865 for (uint32_t i = 0; i < cmd_count; ++i) {
1866 switch ( cmd->cmd ) {
1867 case LC_LOAD_DYLIB:
1868 case LC_LOAD_WEAK_DYLIB:
1869 case LC_REEXPORT_DYLIB:
1870 case LC_LOAD_UPWARD_DYLIB:
1871 if ( index == count ) {
1872 const struct dylib_command* dylibCmd = (struct dylib_command*)cmd;
1873 return (char*)cmd + dylibCmd->dylib.name.offset;
1874 }
1875 ++count;
1876 break;
1877 }
1878 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
1879 }
1880
1881 // <rdar://problem/24256354> if image linked with nothing and we implicitly added libSystem.dylib, return that
1882 if ( needsAddedLibSystemDepency(libraryCount(), (macho_header*)fMachOData) ) {
1883 return LIBSYSTEM_DYLIB_PATH;
1884 }
1885
1886 return NULL;
1887 }
1888
1889
1890 void __attribute__((noreturn)) ImageLoaderMachO::throwSymbolNotFound(const LinkContext& context, const char* symbol,
1891 const char* referencedFrom, const char* fromVersMismatch,
1892 const char* expectedIn)
1893 {
1894 // record values for possible use by CrashReporter or Finder
1895 (*context.setErrorStrings)(DYLD_EXIT_REASON_SYMBOL_MISSING, referencedFrom, expectedIn, symbol);
1896 dyld::throwf("Symbol not found: %s\n Referenced from: %s%s\n Expected in: %s\n",
1897 symbol, referencedFrom, fromVersMismatch, expectedIn);
1898 }
1899
1900 const mach_header* ImageLoaderMachO::machHeader() const
1901 {
1902 return (mach_header*)fMachOData;
1903 }
1904
1905 uintptr_t ImageLoaderMachO::getSlide() const
1906 {
1907 return fSlide;
1908 }
1909
1910 // hmm. maybe this should be up in ImageLoader??
1911 const void* ImageLoaderMachO::getEnd() const
1912 {
1913 uintptr_t lastAddress = 0;
1914 for(unsigned int i=0; i < fSegmentsCount; ++i) {
1915 uintptr_t segEnd = segActualEndAddress(i);
1916 if ( strcmp(segName(i), "__UNIXSTACK") != 0 ) {
1917 if ( segEnd > lastAddress )
1918 lastAddress = segEnd;
1919 }
1920 }
1921 return (const void*)lastAddress;
1922 }
1923
1924
1925 uintptr_t ImageLoaderMachO::bindLocation(const LinkContext& context, uintptr_t location, uintptr_t value,
1926 uint8_t type, const char* symbolName,
1927 intptr_t addend, const char* inPath, const char* toPath, const char* msg)
1928 {
1929 // log
1930 if ( context.verboseBind ) {
1931 if ( addend != 0 )
1932 dyld::log("dyld: %sbind: %s:0x%08lX = %s:%s, *0x%08lX = 0x%08lX + %ld\n",
1933 msg, shortName(inPath), (uintptr_t)location,
1934 ((toPath != NULL) ? shortName(toPath) : "<missing weak_import>"),
1935 symbolName, (uintptr_t)location, value, addend);
1936 else
1937 dyld::log("dyld: %sbind: %s:0x%08lX = %s:%s, *0x%08lX = 0x%08lX\n",
1938 msg, shortName(inPath), (uintptr_t)location,
1939 ((toPath != NULL) ? shortName(toPath) : "<missing weak_import>"),
1940 symbolName, (uintptr_t)location, value);
1941 }
1942 #if LOG_BINDINGS
1943 // dyld::logBindings("%s: %s\n", targetImage->getShortName(), symbolName);
1944 #endif
1945
1946 // do actual update
1947 uintptr_t* locationToFix = (uintptr_t*)location;
1948 uint32_t* loc32;
1949 uintptr_t newValue = value+addend;
1950 uint32_t value32;
1951 switch (type) {
1952 case BIND_TYPE_POINTER:
1953 // test first so we don't needless dirty pages
1954 if ( *locationToFix != newValue )
1955 *locationToFix = newValue;
1956 break;
1957 case BIND_TYPE_TEXT_ABSOLUTE32:
1958 loc32 = (uint32_t*)locationToFix;
1959 value32 = (uint32_t)newValue;
1960 if ( *loc32 != value32 )
1961 *loc32 = value32;
1962 break;
1963 case BIND_TYPE_TEXT_PCREL32:
1964 loc32 = (uint32_t*)locationToFix;
1965 value32 = (uint32_t)(newValue - (((uintptr_t)locationToFix) + 4));
1966 if ( *loc32 != value32 )
1967 *loc32 = value32;
1968 break;
1969 default:
1970 dyld::throwf("bad bind type %d", type);
1971 }
1972
1973 // update statistics
1974 ++fgTotalBindFixups;
1975
1976 return newValue;
1977 }
1978
1979
1980
1981
1982
1983 #if SUPPORT_OLD_CRT_INITIALIZATION
1984 // first 16 bytes of "start" in crt1.o
1985 #if __i386__
1986 static uint8_t sStandardEntryPointInstructions[16] = { 0x6a, 0x00, 0x89, 0xe5, 0x83, 0xe4, 0xf0, 0x83, 0xec, 0x10, 0x8b, 0x5d, 0x04, 0x89, 0x5c, 0x24 };
1987 #endif
1988 #endif
1989
1990 struct DATAdyld {
1991 void* dyldLazyBinder; // filled in at launch by dyld to point into dyld to &stub_binding_helper
1992 void* dyldFuncLookup; // filled in at launch by dyld to point into dyld to &_dyld_func_lookup
1993 // the following only exist in main executables built for 10.5 or later
1994 ProgramVars vars;
1995 };
1996
1997 // These are defined in dyldStartup.s
1998 extern "C" void stub_binding_helper();
1999
2000
2001 void ImageLoaderMachO::setupLazyPointerHandler(const LinkContext& context)
2002 {
2003 const macho_header* mh = (macho_header*)fMachOData;
2004 const uint32_t cmd_count = mh->ncmds;
2005 const struct load_command* const cmds = (struct load_command*)&fMachOData[sizeof(macho_header)];
2006 const struct load_command* cmd;
2007 // There used to be some optimizations to skip this section scan, but we need to handle the
2008 // __dyld section in libdyld.dylib, so everything needs to be scanned for now.
2009 // <rdar://problem/10910062> CrashTracer: 1,295 crashes in bash at bash: getenv
2010 if ( true ) {
2011 cmd = cmds;
2012 for (uint32_t i = 0; i < cmd_count; ++i) {
2013 if ( cmd->cmd == LC_SEGMENT_COMMAND ) {
2014 const struct macho_segment_command* seg = (struct macho_segment_command*)cmd;
2015 if ( strncmp(seg->segname, "__DATA", 6) == 0 ) {
2016 const struct macho_section* const sectionsStart = (struct macho_section*)((char*)seg + sizeof(struct macho_segment_command));
2017 const struct macho_section* const sectionsEnd = &sectionsStart[seg->nsects];
2018 for (const struct macho_section* sect=sectionsStart; sect < sectionsEnd; ++sect) {
2019 if ( strcmp(sect->sectname, "__dyld" ) == 0 ) {
2020 struct DATAdyld* dd = (struct DATAdyld*)(sect->addr + fSlide);
2021 #if !__arm64__ && !__ARM_ARCH_7K__
2022 if ( sect->size > offsetof(DATAdyld, dyldLazyBinder) ) {
2023 if ( dd->dyldLazyBinder != (void*)&stub_binding_helper )
2024 dd->dyldLazyBinder = (void*)&stub_binding_helper;
2025 }
2026 #endif // !__arm64__
2027 if ( sect->size > offsetof(DATAdyld, dyldFuncLookup) ) {
2028 if ( dd->dyldFuncLookup != (void*)&_dyld_func_lookup )
2029 dd->dyldFuncLookup = (void*)&_dyld_func_lookup;
2030 }
2031 if ( mh->filetype == MH_EXECUTE ) {
2032 // there are two ways to get the program variables
2033 if ( (sect->size > offsetof(DATAdyld, vars)) && (dd->vars.mh == mh) ) {
2034 // some really old binaries have space for vars, but it is zero filled
2035 // main executable has 10.5 style __dyld section that has program variable pointers
2036 context.setNewProgramVars(dd->vars);
2037 }
2038 else {
2039 // main executable is pre-10.5 and requires the symbols names to be looked up
2040 this->lookupProgramVars(context);
2041 #if SUPPORT_OLD_CRT_INITIALIZATION
2042 // If the first 16 bytes of the entry point's instructions do not
2043 // match what crt1.o supplies, then the program has a custom entry point.
2044 // This means it might be doing something that needs to be executed before
2045 // initializers are run.
2046 if ( memcmp(this->getMain(), sStandardEntryPointInstructions, 16) != 0 ) {
2047 if ( context.verboseInit )
2048 dyld::log("dyld: program uses non-standard entry point so delaying running of initializers\n");
2049 context.setRunInitialzersOldWay();
2050 }
2051 #endif
2052 }
2053 }
2054 else if ( mh->filetype == MH_DYLIB ) {
2055 const char* installPath = this->getInstallPath();
2056 if ( (installPath != NULL) && (strncmp(installPath, "/usr/lib/", 9) == 0) ) {
2057 if ( sect->size > offsetof(DATAdyld, vars) ) {
2058 // use ProgramVars from libdyld.dylib but tweak mh field to correct value
2059 dd->vars.mh = context.mainExecutable->machHeader();
2060 context.setNewProgramVars(dd->vars);
2061 }
2062 }
2063 }
2064 }
2065 else if ( (strcmp(sect->sectname, "__program_vars" ) == 0) && (mh->filetype == MH_EXECUTE) ) {
2066 // this is a Mac OS X 10.6 or later main executable
2067 struct ProgramVars* pv = (struct ProgramVars*)(sect->addr + fSlide);
2068 context.setNewProgramVars(*pv);
2069 }
2070 }
2071 }
2072 }
2073 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
2074 }
2075 }
2076 }
2077
2078
2079 void ImageLoaderMachO::lookupProgramVars(const LinkContext& context) const
2080 {
2081 ProgramVars vars = context.programVars;
2082 const ImageLoader::Symbol* sym;
2083
2084 // get mach header directly
2085 vars.mh = (macho_header*)fMachOData;
2086
2087 // lookup _NXArgc
2088 sym = this->findShallowExportedSymbol("_NXArgc", NULL);
2089 if ( sym != NULL )
2090 vars.NXArgcPtr = (int*)this->getExportedSymbolAddress(sym, context, this, false, NULL);
2091
2092 // lookup _NXArgv
2093 sym = this->findShallowExportedSymbol("_NXArgv", NULL);
2094 if ( sym != NULL )
2095 vars.NXArgvPtr = (const char***)this->getExportedSymbolAddress(sym, context, this, false, NULL);
2096
2097 // lookup _environ
2098 sym = this->findShallowExportedSymbol("_environ", NULL);
2099 if ( sym != NULL )
2100 vars.environPtr = (const char***)this->getExportedSymbolAddress(sym, context, this, false, NULL);
2101
2102 // lookup __progname
2103 sym = this->findShallowExportedSymbol("___progname", NULL);
2104 if ( sym != NULL )
2105 vars.__prognamePtr = (const char**)this->getExportedSymbolAddress(sym, context, this, false, NULL);
2106
2107 context.setNewProgramVars(vars);
2108 }
2109
2110
2111 bool ImageLoaderMachO::usablePrebinding(const LinkContext& context) const
2112 {
2113 // if prebound and loaded at prebound address, and all libraries are same as when this was prebound, then no need to bind
2114 if ( ((this->isPrebindable() && (this->getSlide() == 0)) || fInSharedCache)
2115 && this->usesTwoLevelNameSpace()
2116 && this->allDependentLibrariesAsWhenPreBound() ) {
2117 // allow environment variables to disable prebinding
2118 if ( context.bindFlat )
2119 return false;
2120 switch ( context.prebindUsage ) {
2121 case kUseAllPrebinding:
2122 return true;
2123 case kUseSplitSegPrebinding:
2124 return this->fIsSplitSeg;
2125 case kUseAllButAppPredbinding:
2126 return (this != context.mainExecutable);
2127 case kUseNoPrebinding:
2128 return false;
2129 }
2130 }
2131 return false;
2132 }
2133
2134
2135 void ImageLoaderMachO::doImageInit(const LinkContext& context)
2136 {
2137 if ( fHasDashInit ) {
2138 const uint32_t cmd_count = ((macho_header*)fMachOData)->ncmds;
2139 const struct load_command* const cmds = (struct load_command*)&fMachOData[sizeof(macho_header)];
2140 const struct load_command* cmd = cmds;
2141 for (uint32_t i = 0; i < cmd_count; ++i) {
2142 switch (cmd->cmd) {
2143 case LC_ROUTINES_COMMAND:
2144 Initializer func = (Initializer)(((struct macho_routines_command*)cmd)->init_address + fSlide);
2145 // <rdar://problem/8543820&9228031> verify initializers are in image
2146 if ( ! this->containsAddress((void*)func) ) {
2147 dyld::throwf("initializer function %p not in mapped image for %s\n", func, this->getPath());
2148 }
2149 if ( ! dyld::gProcessInfo->libSystemInitialized ) {
2150 // <rdar://problem/17973316> libSystem initializer must run first
2151 dyld::throwf("-init function in image (%s) that does not link with libSystem.dylib\n", this->getPath());
2152 }
2153 if ( context.verboseInit )
2154 dyld::log("dyld: calling -init function %p in %s\n", func, this->getPath());
2155 func(context.argc, context.argv, context.envp, context.apple, &context.programVars);
2156 break;
2157 }
2158 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
2159 }
2160 }
2161 }
2162
2163 void ImageLoaderMachO::doModInitFunctions(const LinkContext& context)
2164 {
2165 if ( fHasInitializers ) {
2166 const uint32_t cmd_count = ((macho_header*)fMachOData)->ncmds;
2167 const struct load_command* const cmds = (struct load_command*)&fMachOData[sizeof(macho_header)];
2168 const struct load_command* cmd = cmds;
2169 for (uint32_t i = 0; i < cmd_count; ++i) {
2170 if ( cmd->cmd == LC_SEGMENT_COMMAND ) {
2171 const struct macho_segment_command* seg = (struct macho_segment_command*)cmd;
2172 const struct macho_section* const sectionsStart = (struct macho_section*)((char*)seg + sizeof(struct macho_segment_command));
2173 const struct macho_section* const sectionsEnd = &sectionsStart[seg->nsects];
2174 for (const struct macho_section* sect=sectionsStart; sect < sectionsEnd; ++sect) {
2175 const uint8_t type = sect->flags & SECTION_TYPE;
2176 if ( type == S_MOD_INIT_FUNC_POINTERS ) {
2177 Initializer* inits = (Initializer*)(sect->addr + fSlide);
2178 const size_t count = sect->size / sizeof(uintptr_t);
2179 // <rdar://problem/23929217> Ensure __mod_init_func section is within segment
2180 if ( (sect->addr < seg->vmaddr) || (sect->addr+sect->size > seg->vmaddr+seg->vmsize) || (sect->addr+sect->size < sect->addr) )
2181 dyld::throwf("__mod_init_funcs section has malformed address range for %s\n", this->getPath());
2182 for (size_t j=0; j < count; ++j) {
2183 Initializer func = inits[j];
2184 // <rdar://problem/8543820&9228031> verify initializers are in image
2185 if ( ! this->containsAddress((void*)func) ) {
2186 dyld::throwf("initializer function %p not in mapped image for %s\n", func, this->getPath());
2187 }
2188 if ( ! dyld::gProcessInfo->libSystemInitialized ) {
2189 // <rdar://problem/17973316> libSystem initializer must run first
2190 const char* installPath = getInstallPath();
2191 if ( (installPath == NULL) || (strcmp(installPath, LIBSYSTEM_DYLIB_PATH) != 0) )
2192 dyld::throwf("initializer in image (%s) that does not link with libSystem.dylib\n", this->getPath());
2193 }
2194 if ( context.verboseInit )
2195 dyld::log("dyld: calling initializer function %p in %s\n", func, this->getPath());
2196 bool haveLibSystemHelpersBefore = (dyld::gLibSystemHelpers != NULL);
2197 func(context.argc, context.argv, context.envp, context.apple, &context.programVars);
2198 bool haveLibSystemHelpersAfter = (dyld::gLibSystemHelpers != NULL);
2199 if ( !haveLibSystemHelpersBefore && haveLibSystemHelpersAfter ) {
2200 // now safe to use malloc() and other calls in libSystem.dylib
2201 dyld::gProcessInfo->libSystemInitialized = true;
2202 }
2203 }
2204 }
2205 }
2206 }
2207 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
2208 }
2209 }
2210 }
2211
2212
2213
2214 void ImageLoaderMachO::doGetDOFSections(const LinkContext& context, std::vector<ImageLoader::DOFInfo>& dofs)
2215 {
2216 if ( fHasDOFSections ) {
2217 // walk load commands (mapped in at start of __TEXT segment)
2218 const uint32_t cmd_count = ((macho_header*)fMachOData)->ncmds;
2219 const struct load_command* const cmds = (struct load_command*)&fMachOData[sizeof(macho_header)];
2220 const struct load_command* cmd = cmds;
2221 for (uint32_t i = 0; i < cmd_count; ++i) {
2222 switch (cmd->cmd) {
2223 case LC_SEGMENT_COMMAND:
2224 {
2225 const struct macho_segment_command* seg = (struct macho_segment_command*)cmd;
2226 const struct macho_section* const sectionsStart = (struct macho_section*)((char*)seg + sizeof(struct macho_segment_command));
2227 const struct macho_section* const sectionsEnd = &sectionsStart[seg->nsects];
2228 for (const struct macho_section* sect=sectionsStart; sect < sectionsEnd; ++sect) {
2229 if ( (sect->flags & SECTION_TYPE) == S_DTRACE_DOF ) {
2230 // <rdar://problem/23929217> Ensure section is within segment
2231 if ( (sect->addr < seg->vmaddr) || (sect->addr+sect->size > seg->vmaddr+seg->vmsize) || (sect->addr+sect->size < sect->addr) )
2232 dyld::throwf("DOF section has malformed address range for %s\n", this->getPath());
2233 ImageLoader::DOFInfo info;
2234 info.dof = (void*)(sect->addr + fSlide);
2235 info.imageHeader = this->machHeader();
2236 info.imageShortName = this->getShortName();
2237 dofs.push_back(info);
2238 }
2239 }
2240 }
2241 break;
2242 }
2243 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
2244 }
2245 }
2246 }
2247
2248
2249 bool ImageLoaderMachO::doInitialization(const LinkContext& context)
2250 {
2251 CRSetCrashLogMessage2(this->getPath());
2252
2253 // mach-o has -init and static initializers
2254 doImageInit(context);
2255 doModInitFunctions(context);
2256
2257 CRSetCrashLogMessage2(NULL);
2258
2259 return (fHasDashInit || fHasInitializers);
2260 }
2261
2262 bool ImageLoaderMachO::needsInitialization()
2263 {
2264 return ( fHasDashInit || fHasInitializers );
2265 }
2266
2267
2268 bool ImageLoaderMachO::needsTermination()
2269 {
2270 return fHasTerminators;
2271 }
2272
2273
2274 void ImageLoaderMachO::doTermination(const LinkContext& context)
2275 {
2276 if ( fHasTerminators ) {
2277 const uint32_t cmd_count = ((macho_header*)fMachOData)->ncmds;
2278 const struct load_command* const cmds = (struct load_command*)&fMachOData[sizeof(macho_header)];
2279 const struct load_command* cmd = cmds;
2280 for (uint32_t i = 0; i < cmd_count; ++i) {
2281 if ( cmd->cmd == LC_SEGMENT_COMMAND ) {
2282 const struct macho_segment_command* seg = (struct macho_segment_command*)cmd;
2283 const struct macho_section* const sectionsStart = (struct macho_section*)((char*)seg + sizeof(struct macho_segment_command));
2284 const struct macho_section* const sectionsEnd = &sectionsStart[seg->nsects];
2285 for (const struct macho_section* sect=sectionsStart; sect < sectionsEnd; ++sect) {
2286 const uint8_t type = sect->flags & SECTION_TYPE;
2287 if ( type == S_MOD_TERM_FUNC_POINTERS ) {
2288 // <rdar://problem/23929217> Ensure section is within segment
2289 if ( (sect->addr < seg->vmaddr) || (sect->addr+sect->size > seg->vmaddr+seg->vmsize) || (sect->addr+sect->size < sect->addr) )
2290 dyld::throwf("DOF section has malformed address range for %s\n", this->getPath());
2291 Terminator* terms = (Terminator*)(sect->addr + fSlide);
2292 const size_t count = sect->size / sizeof(uintptr_t);
2293 for (size_t j=count; j > 0; --j) {
2294 Terminator func = terms[j-1];
2295 // <rdar://problem/8543820&9228031> verify terminators are in image
2296 if ( ! this->containsAddress((void*)func) ) {
2297 dyld::throwf("termination function %p not in mapped image for %s\n", func, this->getPath());
2298 }
2299 if ( context.verboseInit )
2300 dyld::log("dyld: calling termination function %p in %s\n", func, this->getPath());
2301 func();
2302 }
2303 }
2304 }
2305 }
2306 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
2307 }
2308 }
2309 }
2310
2311
2312 void ImageLoaderMachO::printStatisticsDetails(unsigned int imageCount, const InitializerTimingList& timingInfo)
2313 {
2314 ImageLoader::printStatisticsDetails(imageCount, timingInfo);
2315 dyld::log("total symbol trie searches: %d\n", fgSymbolTrieSearchs);
2316 dyld::log("total symbol table binary searches: %d\n", fgSymbolTableBinarySearchs);
2317 dyld::log("total images defining weak symbols: %u\n", fgImagesHasWeakDefinitions);
2318 dyld::log("total images using weak symbols: %u\n", fgImagesRequiringCoalescing);
2319 }
2320
2321
2322 intptr_t ImageLoaderMachO::assignSegmentAddresses(const LinkContext& context)
2323 {
2324 // preflight and calculate slide if needed
2325 const bool inPIE = (fgNextPIEDylibAddress != 0);
2326 intptr_t slide = 0;
2327 if ( this->segmentsCanSlide() && this->segmentsMustSlideTogether() ) {
2328 bool needsToSlide = false;
2329 bool imageHasPreferredLoadAddress = segHasPreferredLoadAddress(0);
2330 uintptr_t lowAddr = (unsigned long)(-1);
2331 uintptr_t highAddr = 0;
2332 for(unsigned int i=0, e=segmentCount(); i < e; ++i) {
2333 const uintptr_t segLow = segPreferredLoadAddress(i);
2334 const uintptr_t segHigh = dyld_page_round(segLow + segSize(i));
2335 if ( segLow < highAddr ) {
2336 if ( dyld_page_size > 4096 )
2337 dyld::throwf("can't map segments into 16KB pages");
2338 else
2339 dyld::throwf("overlapping segments");
2340 }
2341 if ( segLow < lowAddr )
2342 lowAddr = segLow;
2343 if ( segHigh > highAddr )
2344 highAddr = segHigh;
2345
2346 if ( needsToSlide || !imageHasPreferredLoadAddress || inPIE || !reserveAddressRange(segPreferredLoadAddress(i), segSize(i)) )
2347 needsToSlide = true;
2348 }
2349 if ( needsToSlide ) {
2350 // find a chunk of address space to hold all segments
2351 uintptr_t addr = reserveAnAddressRange(highAddr-lowAddr, context);
2352 slide = addr - lowAddr;
2353 }
2354 }
2355 else if ( ! this->segmentsCanSlide() ) {
2356 for(unsigned int i=0, e=segmentCount(); i < e; ++i) {
2357 if ( (strcmp(segName(i), "__PAGEZERO") == 0) && (segFileSize(i) == 0) && (segPreferredLoadAddress(i) == 0) )
2358 continue;
2359 if ( !reserveAddressRange(segPreferredLoadAddress(i), segSize(i)) )
2360 dyld::throwf("can't map unslidable segment %s to 0x%lX with size 0x%lX", segName(i), segPreferredLoadAddress(i), segSize(i));
2361 }
2362 }
2363 else {
2364 throw "mach-o does not support independently sliding segments";
2365 }
2366 return slide;
2367 }
2368
2369
2370 uintptr_t ImageLoaderMachO::reserveAnAddressRange(size_t length, const ImageLoader::LinkContext& context)
2371 {
2372 vm_address_t addr = 0;
2373 vm_size_t size = length;
2374 // in PIE programs, load initial dylibs after main executable so they don't have fixed addresses either
2375 if ( fgNextPIEDylibAddress != 0 ) {
2376 // add small (0-3 pages) random padding between dylibs
2377 addr = fgNextPIEDylibAddress + (__stack_chk_guard/fgNextPIEDylibAddress & (sizeof(long)-1))*dyld_page_size;
2378 //dyld::log("padding 0x%08llX, guard=0x%08llX\n", (long long)(addr - fgNextPIEDylibAddress), (long long)(__stack_chk_guard));
2379 kern_return_t r = vm_alloc(&addr, size, VM_FLAGS_FIXED | VM_MAKE_TAG(VM_MEMORY_DYLIB));
2380 if ( r == KERN_SUCCESS ) {
2381 fgNextPIEDylibAddress = addr + size;
2382 return addr;
2383 }
2384 fgNextPIEDylibAddress = 0;
2385 }
2386 kern_return_t r = vm_alloc(&addr, size, VM_FLAGS_ANYWHERE | VM_MAKE_TAG(VM_MEMORY_DYLIB));
2387 if ( r != KERN_SUCCESS )
2388 throw "out of address space";
2389
2390 return addr;
2391 }
2392
2393 bool ImageLoaderMachO::reserveAddressRange(uintptr_t start, size_t length)
2394 {
2395 vm_address_t addr = start;
2396 vm_size_t size = length;
2397 kern_return_t r = vm_alloc(&addr, size, VM_FLAGS_FIXED | VM_MAKE_TAG(VM_MEMORY_DYLIB));
2398 if ( r != KERN_SUCCESS )
2399 return false;
2400 return true;
2401 }
2402
2403
2404
2405 void ImageLoaderMachO::mapSegments(int fd, uint64_t offsetInFat, uint64_t lenInFat, uint64_t fileLen, const LinkContext& context)
2406 {
2407 // find address range for image
2408 intptr_t slide = this->assignSegmentAddresses(context);
2409 if ( context.verboseMapping ) {
2410 if ( offsetInFat != 0 )
2411 dyld::log("dyld: Mapping %s (slice offset=%llu)\n", this->getPath(), (unsigned long long)offsetInFat);
2412 else
2413 dyld::log("dyld: Mapping %s\n", this->getPath());
2414 }
2415 // map in all segments
2416 for(unsigned int i=0, e=segmentCount(); i < e; ++i) {
2417 vm_offset_t fileOffset = segFileOffset(i) + offsetInFat;
2418 vm_size_t size = segFileSize(i);
2419 uintptr_t requestedLoadAddress = segPreferredLoadAddress(i) + slide;
2420 int protection = 0;
2421 if ( !segUnaccessible(i) ) {
2422 // If has text-relocs, don't set x-bit initially.
2423 // Instead set it later after text-relocs have been done.
2424 if ( segExecutable(i) && !(segHasRebaseFixUps(i) && (slide != 0)) )
2425 protection |= PROT_EXEC;
2426 if ( segReadable(i) )
2427 protection |= PROT_READ;
2428 if ( segWriteable(i) ) {
2429 protection |= PROT_WRITE;
2430 // rdar://problem/22525618 force __LINKEDIT to always be mapped read-only
2431 if ( strcmp(segName(i), "__LINKEDIT") == 0 )
2432 protection = PROT_READ;
2433 }
2434 }
2435 #if __i386__
2436 // initially map __IMPORT segments R/W so dyld can update them
2437 if ( segIsReadOnlyImport(i) )
2438 protection |= PROT_WRITE;
2439 #endif
2440 // wholly zero-fill segments have nothing to mmap() in
2441 if ( size > 0 ) {
2442 if ( (fileOffset+size) > fileLen ) {
2443 dyld::throwf("truncated mach-o error: segment %s extends to %llu which is past end of file %llu",
2444 segName(i), (uint64_t)(fileOffset+size), fileLen);
2445 }
2446 void* loadAddress = xmmap((void*)requestedLoadAddress, size, protection, MAP_FIXED | MAP_PRIVATE, fd, fileOffset);
2447 if ( loadAddress == ((void*)(-1)) ) {
2448 int mmapErr = errno;
2449 if ( mmapErr == EPERM ) {
2450 if ( dyld::sandboxBlockedMmap(getPath()) )
2451 dyld::throwf("file system sandbox blocked mmap() of '%s'", this->getPath());
2452 else
2453 dyld::throwf("code signing blocked mmap() of '%s'", this->getPath());
2454 }
2455 else
2456 dyld::throwf("mmap() errno=%d at address=0x%08lX, size=0x%08lX segment=%s in Segment::map() mapping %s",
2457 mmapErr, requestedLoadAddress, (uintptr_t)size, segName(i), getPath());
2458 }
2459 }
2460 // update stats
2461 ++ImageLoader::fgTotalSegmentsMapped;
2462 ImageLoader::fgTotalBytesMapped += size;
2463 if ( context.verboseMapping )
2464 dyld::log("%18s at 0x%08lX->0x%08lX with permissions %c%c%c\n", segName(i), requestedLoadAddress, requestedLoadAddress+size-1,
2465 (protection & PROT_READ) ? 'r' : '.', (protection & PROT_WRITE) ? 'w' : '.', (protection & PROT_EXEC) ? 'x' : '.' );
2466 }
2467
2468 // update slide to reflect load location
2469 this->setSlide(slide);
2470 }
2471
2472 void ImageLoaderMachO::mapSegments(const void* memoryImage, uint64_t imageLen, const LinkContext& context)
2473 {
2474 // find address range for image
2475 intptr_t slide = this->assignSegmentAddresses(context);
2476 if ( context.verboseMapping )
2477 dyld::log("dyld: Mapping memory %p\n", memoryImage);
2478 // map in all segments
2479 for(unsigned int i=0, e=segmentCount(); i < e; ++i) {
2480 vm_address_t loadAddress = segPreferredLoadAddress(i) + slide;
2481 vm_address_t srcAddr = (uintptr_t)memoryImage + segFileOffset(i);
2482 vm_size_t size = segFileSize(i);
2483 kern_return_t r = vm_copy(mach_task_self(), srcAddr, size, loadAddress);
2484 if ( r != KERN_SUCCESS )
2485 throw "can't map segment";
2486 if ( context.verboseMapping )
2487 dyld::log("%18s at 0x%08lX->0x%08lX\n", segName(i), (uintptr_t)loadAddress, (uintptr_t)loadAddress+size-1);
2488 }
2489 // update slide to reflect load location
2490 this->setSlide(slide);
2491 // set R/W permissions on all segments at slide location
2492 for(unsigned int i=0, e=segmentCount(); i < e; ++i) {
2493 segProtect(i, context);
2494 }
2495 }
2496
2497
2498 void ImageLoaderMachO::segProtect(unsigned int segIndex, const ImageLoader::LinkContext& context)
2499 {
2500 vm_prot_t protection = 0;
2501 if ( !segUnaccessible(segIndex) ) {
2502 if ( segExecutable(segIndex) )
2503 protection |= PROT_EXEC;
2504 if ( segReadable(segIndex) )
2505 protection |= PROT_READ;
2506 if ( segWriteable(segIndex) )
2507 protection |= PROT_WRITE;
2508 }
2509 vm_address_t addr = segActualLoadAddress(segIndex);
2510 vm_size_t size = segSize(segIndex);
2511 const bool setCurrentPermissions = false;
2512 kern_return_t r = vm_protect(mach_task_self(), addr, size, setCurrentPermissions, protection);
2513 if ( r != KERN_SUCCESS ) {
2514 dyld::throwf("vm_protect(0x%08llX, 0x%08llX, false, 0x%02X) failed, result=%d for segment %s in %s",
2515 (long long)addr, (long long)size, protection, r, segName(segIndex), this->getPath());
2516 }
2517 if ( context.verboseMapping ) {
2518 dyld::log("%18s at 0x%08lX->0x%08lX altered permissions to %c%c%c\n", segName(segIndex), (uintptr_t)addr, (uintptr_t)addr+size-1,
2519 (protection & PROT_READ) ? 'r' : '.', (protection & PROT_WRITE) ? 'w' : '.', (protection & PROT_EXEC) ? 'x' : '.' );
2520 }
2521 }
2522
2523 void ImageLoaderMachO::segMakeWritable(unsigned int segIndex, const ImageLoader::LinkContext& context)
2524 {
2525 vm_address_t addr = segActualLoadAddress(segIndex);
2526 vm_size_t size = segSize(segIndex);
2527 const bool setCurrentPermissions = false;
2528 vm_prot_t protection = VM_PROT_WRITE | VM_PROT_READ;
2529 if ( segExecutable(segIndex) && !segHasRebaseFixUps(segIndex) )
2530 protection |= VM_PROT_EXECUTE;
2531 kern_return_t r = vm_protect(mach_task_self(), addr, size, setCurrentPermissions, protection);
2532 if ( r != KERN_SUCCESS ) {
2533 dyld::throwf("vm_protect(0x%08llX, 0x%08llX, false, 0x%02X) failed, result=%d for segment %s in %s",
2534 (long long)addr, (long long)size, protection, r, segName(segIndex), this->getPath());
2535 }
2536 if ( context.verboseMapping ) {
2537 dyld::log("%18s at 0x%08lX->0x%08lX altered permissions to %c%c%c\n", segName(segIndex), (uintptr_t)addr, (uintptr_t)addr+size-1,
2538 (protection & PROT_READ) ? 'r' : '.', (protection & PROT_WRITE) ? 'w' : '.', (protection & PROT_EXEC) ? 'x' : '.' );
2539 }
2540 }
2541
2542
2543 const char* ImageLoaderMachO::findClosestSymbol(const mach_header* mh, const void* addr, const void** closestAddr)
2544 {
2545 // called by dladdr()
2546 // only works with compressed LINKEDIT if classic symbol table is also present
2547 const dysymtab_command* dynSymbolTable = NULL;
2548 const symtab_command* symtab = NULL;
2549 const macho_segment_command* seg;
2550 const uint8_t* unslidLinkEditBase = NULL;
2551 bool linkEditBaseFound = false;
2552 intptr_t slide = 0;
2553 const uint32_t cmd_count = mh->ncmds;
2554 const load_command* const cmds = (load_command*)((char*)mh + sizeof(macho_header));
2555 const load_command* cmd = cmds;
2556 for (uint32_t i = 0; i < cmd_count; ++i) {
2557 switch (cmd->cmd) {
2558 case LC_SEGMENT_COMMAND:
2559 seg = (macho_segment_command*)cmd;
2560 if ( strcmp(seg->segname, "__LINKEDIT") == 0 ) {
2561 unslidLinkEditBase = (uint8_t*)(seg->vmaddr - seg->fileoff);
2562 linkEditBaseFound = true;
2563 }
2564 else if ( (seg->fileoff == 0) && (seg->filesize != 0) )
2565 slide = (uintptr_t)mh - seg->vmaddr;
2566 break;
2567 case LC_SYMTAB:
2568 symtab = (symtab_command*)cmd;
2569 break;
2570 case LC_DYSYMTAB:
2571 dynSymbolTable = (dysymtab_command*)cmd;
2572 break;
2573 }
2574 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
2575 }
2576 // no symbol table => no lookup by address
2577 if ( (symtab == NULL) || (dynSymbolTable == NULL) || !linkEditBaseFound )
2578 return NULL;
2579
2580 const uint8_t* linkEditBase = unslidLinkEditBase + slide;
2581 const char* symbolTableStrings = (const char*)&linkEditBase[symtab->stroff];
2582 const macho_nlist* symbolTable = (macho_nlist*)(&linkEditBase[symtab->symoff]);
2583
2584 uintptr_t targetAddress = (uintptr_t)addr - slide;
2585 const struct macho_nlist* bestSymbol = NULL;
2586 // first walk all global symbols
2587 const struct macho_nlist* const globalsStart = &symbolTable[dynSymbolTable->iextdefsym];
2588 const struct macho_nlist* const globalsEnd= &globalsStart[dynSymbolTable->nextdefsym];
2589 for (const struct macho_nlist* s = globalsStart; s < globalsEnd; ++s) {
2590 if ( (s->n_type & N_TYPE) == N_SECT ) {
2591 if ( bestSymbol == NULL ) {
2592 if ( s->n_value <= targetAddress )
2593 bestSymbol = s;
2594 }
2595 else if ( (s->n_value <= targetAddress) && (bestSymbol->n_value < s->n_value) ) {
2596 bestSymbol = s;
2597 }
2598 }
2599 }
2600 // next walk all local symbols
2601 const struct macho_nlist* const localsStart = &symbolTable[dynSymbolTable->ilocalsym];
2602 const struct macho_nlist* const localsEnd= &localsStart[dynSymbolTable->nlocalsym];
2603 for (const struct macho_nlist* s = localsStart; s < localsEnd; ++s) {
2604 if ( ((s->n_type & N_TYPE) == N_SECT) && ((s->n_type & N_STAB) == 0) ) {
2605 if ( bestSymbol == NULL ) {
2606 if ( s->n_value <= targetAddress )
2607 bestSymbol = s;
2608 }
2609 else if ( (s->n_value <= targetAddress) && (bestSymbol->n_value < s->n_value) ) {
2610 bestSymbol = s;
2611 }
2612 }
2613 }
2614 if ( bestSymbol != NULL ) {
2615 #if __arm__
2616 if (bestSymbol->n_desc & N_ARM_THUMB_DEF)
2617 *closestAddr = (void*)((bestSymbol->n_value | 1) + slide);
2618 else
2619 *closestAddr = (void*)(bestSymbol->n_value + slide);
2620 #else
2621 *closestAddr = (void*)(bestSymbol->n_value + slide);
2622 #endif
2623 return &symbolTableStrings[bestSymbol->n_un.n_strx];
2624 }
2625 return NULL;
2626 }
2627
2628 bool ImageLoaderMachO::getLazyBindingInfo(uint32_t& lazyBindingInfoOffset, const uint8_t* lazyInfoStart, const uint8_t* lazyInfoEnd,
2629 uint8_t* segIndex, uintptr_t* segOffset, int* ordinal, const char** symbolName, bool* doneAfterBind)
2630 {
2631 if ( lazyBindingInfoOffset > (lazyInfoEnd-lazyInfoStart) )
2632 return false;
2633 uint8_t type = BIND_TYPE_POINTER;
2634 uint8_t symboFlags = 0;
2635 bool done = false;
2636 const uint8_t* p = &lazyInfoStart[lazyBindingInfoOffset];
2637 while ( !done && (p < lazyInfoEnd) ) {
2638 uint8_t immediate = *p & BIND_IMMEDIATE_MASK;
2639 uint8_t opcode = *p & BIND_OPCODE_MASK;
2640 ++p;
2641 switch (opcode) {
2642 case BIND_OPCODE_DONE:
2643 *doneAfterBind = false;
2644 return true;
2645 break;
2646 case BIND_OPCODE_SET_DYLIB_ORDINAL_IMM:
2647 *ordinal = immediate;
2648 break;
2649 case BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB:
2650 *ordinal = (int)read_uleb128(p, lazyInfoEnd);
2651 break;
2652 case BIND_OPCODE_SET_DYLIB_SPECIAL_IMM:
2653 // the special ordinals are negative numbers
2654 if ( immediate == 0 )
2655 *ordinal = 0;
2656 else {
2657 int8_t signExtended = BIND_OPCODE_MASK | immediate;
2658 *ordinal = signExtended;
2659 }
2660 break;
2661 case BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM:
2662 *symbolName = (char*)p;
2663 symboFlags = immediate;
2664 while (*p != '\0')
2665 ++p;
2666 ++p;
2667 break;
2668 case BIND_OPCODE_SET_TYPE_IMM:
2669 type = immediate;
2670 break;
2671 case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:
2672 *segIndex = immediate;
2673 *segOffset = read_uleb128(p, lazyInfoEnd);
2674 break;
2675 case BIND_OPCODE_DO_BIND:
2676 *doneAfterBind = ((*p & BIND_OPCODE_MASK) == BIND_OPCODE_DONE);
2677 lazyBindingInfoOffset += p - &lazyInfoStart[lazyBindingInfoOffset];
2678 return true;
2679 break;
2680 case BIND_OPCODE_SET_ADDEND_SLEB:
2681 case BIND_OPCODE_ADD_ADDR_ULEB:
2682 case BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB:
2683 case BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED:
2684 case BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB:
2685 default:
2686 return false;
2687 }
2688 }
2689 return false;
2690 }
2691
2692 const dyld_info_command* ImageLoaderMachO::findDyldInfoLoadCommand(const mach_header* mh)
2693 {
2694 const uint32_t cmd_count = mh->ncmds;
2695 const load_command* const cmds = (load_command*)((char*)mh + sizeof(macho_header));
2696 const load_command* cmd = cmds;
2697 for (uint32_t i = 0; i < cmd_count; ++i) {
2698 switch (cmd->cmd) {
2699 case LC_DYLD_INFO:
2700 case LC_DYLD_INFO_ONLY:
2701 return (dyld_info_command*)cmd;
2702 }
2703 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
2704 }
2705 return NULL;
2706 }
2707
2708
2709 uintptr_t ImageLoaderMachO::segPreferredAddress(const mach_header* mh, unsigned segIndex)
2710 {
2711 const uint32_t cmd_count = mh->ncmds;
2712 const load_command* const cmds = (load_command*)((char*)mh + sizeof(macho_header));
2713 const load_command* cmd = cmds;
2714 unsigned curSegIndex = 0;
2715 for (uint32_t i = 0; i < cmd_count; ++i) {
2716 if ( cmd->cmd == LC_SEGMENT_COMMAND ) {
2717 if ( segIndex == curSegIndex ) {
2718 const macho_segment_command* segCmd = (macho_segment_command*)cmd;
2719 return segCmd->vmaddr;
2720 }
2721 ++curSegIndex;
2722 }
2723 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
2724 }
2725 return 0;
2726 }
2727
2728
2729