1 /* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*-
3 * Copyright (c) 2004-2010 Apple Inc. All rights reserved.
5 * @APPLE_LICENSE_HEADER_START@
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
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.
22 * @APPLE_LICENSE_HEADER_END@
25 // work around until conformance work is complete rdar://problem/4508801
30 #define __STDC_LIMIT_MACROS
34 #include <sys/types.h>
35 #include <sys/fcntl.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>
47 #include <System/sys/codesign.h>
49 #include "ImageLoaderMachO.h"
50 #include "ImageLoaderMachOCompressed.h"
51 #if SUPPORT_CLASSIC_MACHO
52 #include "ImageLoaderMachOClassic.h"
54 #include "mach-o/dyld_images.h"
57 // <rdar://problem/8718137> use stack guard random value to add padding between dylibs
58 extern "C" long __stack_chk_guard
;
60 #ifndef LC_LOAD_UPWARD_DYLIB
61 #define LC_LOAD_UPWARD_DYLIB (0x23|LC_REQ_DYLD) /* load of dylib whose initializers run later */
64 #ifndef LC_VERSION_MIN_TVOS
65 #define LC_VERSION_MIN_TVOS 0x2F
68 #ifndef LC_VERSION_MIN_WATCHOS
69 #define LC_VERSION_MIN_WATCHOS 0x30
73 #if TARGET_IPHONE_SIMULATOR
74 #define LIBSYSTEM_DYLIB_PATH "/usr/lib/libSystem.dylib"
76 #define LIBSYSTEM_DYLIB_PATH "/usr/lib/libSystem.B.dylib"
79 // relocation_info.r_length field has value 3 for 64-bit executables and value 2 for 32-bit executables
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
{};
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
{};
96 uint32_t ImageLoaderMachO::fgSymbolTableBinarySearchs
= 0;
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),
109 fReadOnlyImportSegment(false),
111 fHasSubLibraries(false), fHasSubUmbrella(false), fInUmbrella(false), fHasDOFSections(false), fHasDashInit(false),
112 fHasInitializers(false), fHasTerminators(false), fNotifyObjC(false), fRetainForObjC(false), fRegisteredAsRequiresCoalescing(false)
114 fIsSplitSeg
= ((mh
->flags
& MH_SPLIT_SEGS
) != 0);
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
);
130 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
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
)
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",
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
);
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
;
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) )
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)) )
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 )
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";
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
;
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
);
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
);
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
;
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
);
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
);
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;
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;
277 const struct macho_section
* const sectionsStart
= (struct macho_section
*)((char*)segCmd
+ sizeof(struct macho_segment_command
));
278 const struct macho_section
* const sectionsEnd
= §ionsStart
[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
);
285 case LC_SEGMENT_COMMAND_WRONG
:
286 dyld::throwf("malformed mach-o image: wrong LC_SEGMENT[_64] for architecture");
289 case LC_LOAD_WEAK_DYLIB
:
290 case LC_REEXPORT_DYLIB
:
291 case LC_LOAD_UPWARD_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
);
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
;
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
;
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
;
326 if ( cmd
->cmdsize
!= sizeof(symtab_command
) )
327 throw "malformed mach-o image: LC_SYMTAB size wrong";
328 symTabCmd
= (symtab_command
*)cmd
;
331 if ( cmd
->cmdsize
!= sizeof(dysymtab_command
) )
332 throw "malformed mach-o image: LC_DYSYMTAB size wrong";
333 dynSymbTabCmd
= (dysymtab_command
*)cmd
;
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)";
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
;
366 if (fileStart1
> lastFileStart
)
367 lastFileStart
= fileStart1
;
369 if ( strcmp(&segCmd1
->segname
[0], "__LINKEDIT") == 0 ) {
370 linkeditFileStart
= fileStart1
;
373 const struct load_command
* cmd2
= startCmds
;
374 for (uint32_t j
= 0; j
< cmd_count
; ++j
) {
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
);
390 cmd2
= (const struct load_command
*)(((char*)cmd2
)+cmd2
->cmdsize
);
393 cmd1
= (const struct load_command
*)(((char*)cmd1
)+cmd1
->cmdsize
);
396 if (lastFileStart
!= linkeditFileStart
)
397 dyld::throwf("malformed mach-o image: __LINKEDIT must be last segment");
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";
406 uint32_t linkeditFileOffsetStart
= (uint32_t)linkeditSegCmd
->fileoff
;
407 uint32_t linkeditFileOffsetEnd
= (uint32_t)linkeditSegCmd
->fileoff
+ (uint32_t)linkeditSegCmd
->filesize
;
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";
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";
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";
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";
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";
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";
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";
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";
508 // fSegmentsArrayCount is only 8-bits
509 if ( *segCount
> 255 )
510 dyld::throwf("malformed mach-o image: more than 255 segments in %s", path
);
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
);
516 if ( needsAddedLibSystemDepency(*libCount
, mh
) )
522 // create image for main executable
523 ImageLoader
* ImageLoaderMachO::instantiateMainExecutable(const macho_header
* mh
, uintptr_t slide
, const char* path
, const LinkContext
& context
)
525 //dyld::log("ImageLoader=%ld, ImageLoaderMachO=%ld, ImageLoaderMachOClassic=%ld, ImageLoaderMachOCompressed=%ld\n",
526 // sizeof(ImageLoader), sizeof(ImageLoaderMachO), sizeof(ImageLoaderMachOClassic), sizeof(ImageLoaderMachOCompressed));
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
535 return ImageLoaderMachOCompressed::instantiateMainExecutable(mh
, slide
, path
, segCount
, libCount
, context
);
537 #if SUPPORT_CLASSIC_MACHO
538 return ImageLoaderMachOClassic::instantiateMainExecutable(mh
, slide
, path
, segCount
, libCount
, context
);
540 throw "missing LC_DYLD_INFO load command";
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
)
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
557 return ImageLoaderMachOCompressed::instantiateFromFile(path
, fd
, firstPages
, firstPagesSize
, offsetInFat
, lenInFat
, info
, segCount
, libCount
, codeSigCmd
, encryptCmd
, context
);
559 #if SUPPORT_CLASSIC_MACHO
560 return ImageLoaderMachOClassic::instantiateFromFile(path
, fd
, firstPages
, firstPagesSize
, offsetInFat
, lenInFat
, info
, segCount
, libCount
, codeSigCmd
, context
);
562 throw "missing LC_DYLD_INFO load command";
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
)
569 // instantiate right concrete class
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
578 return ImageLoaderMachOCompressed::instantiateFromCache(mh
, path
, slide
, info
, segCount
, libCount
, context
);
580 #if SUPPORT_CLASSIC_MACHO
581 return ImageLoaderMachOClassic::instantiateFromCache(mh
, path
, slide
, info
, segCount
, libCount
, context
);
583 throw "missing LC_DYLD_INFO load command";
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
)
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
598 return ImageLoaderMachOCompressed::instantiateFromMemory(moduleName
, mh
, len
, segCount
, libCount
, context
);
600 #if SUPPORT_CLASSIC_MACHO
601 return ImageLoaderMachOClassic::instantiateFromMemory(moduleName
, mh
, len
, segCount
, libCount
, context
);
603 throw "missing LC_DYLD_INFO load command";
608 int ImageLoaderMachO::crashIfInvalidCodeSignature()
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
);
624 void ImageLoaderMachO::parseLoadCmds(const LinkContext
& context
)
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
));
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;
644 if ( segIsReadOnlyImport(i
) )
645 fReadOnlyImportSegment
= true;
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
));
653 // keep count of prebound images with weak exports
654 if ( this->participatesInCoalescing() ) {
655 ++fgImagesRequiringCoalescing
;
656 fRegisteredAsRequiresCoalescing
= true;
657 if ( this->hasCoalescedExports() )
658 ++fgImagesHasWeakDefinitions
;
661 // keep count of images used in shared cache
662 if ( fInSharedCache
)
663 ++fgImagesUsedFromSharedCache
;
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
) {
679 const struct symtab_command
* symtab
= (struct symtab_command
*)cmd
;
680 symbolTableStrings
= (const char*)&fLinkEditBase
[symtab
->stroff
];
681 symbolTable
= (macho_nlist
*)(&fLinkEditBase
[symtab
->symoff
]);
685 dynSymbolTable
= (struct dysymtab_command
*)cmd
;
687 case LC_SUB_UMBRELLA
:
688 fHasSubUmbrella
= true;
690 case LC_SUB_FRAMEWORK
:
694 fHasSubLibraries
= true;
696 case LC_ROUTINES_COMMAND
:
700 case LC_DYLD_INFO_ONLY
:
701 dyldInfo
= (struct dyld_info_command
*)cmd
;
703 case LC_SEGMENT_COMMAND
:
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);
712 const bool isDataSeg
= (strncmp(seg
->segname
, "__DATA", 6) == 0);
714 const struct macho_section
* const sectionsStart
= (struct macho_section
*)((char*)seg
+ sizeof(struct macho_segment_command
));
715 const struct macho_section
* const sectionsEnd
= §ionsStart
[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
);
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());
737 else if ( ((macho_header
*)fMachOData
)->filetype
== MH_DYLIB
) {
738 fRetainForObjC
= true;
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());
751 else if ( isDataSeg
&& (strncmp(sect
->sectname
, "__objc_", 7) == 0) && (((macho_header
*)fMachOData
)->filetype
== MH_DYLIB
) )
752 fRetainForObjC
= true;
757 case LC_TWOLEVEL_HINTS
:
758 // no longer supported
762 fDylibIDOffset
= (uint32_t)((uint8_t*)cmd
- fMachOData
);
766 case LC_LOAD_WEAK_DYLIB
:
767 case LC_REEXPORT_DYLIB
:
768 case LC_LOAD_UPWARD_DYLIB
:
770 // do nothing, just prevent LC_REQ_DYLD exception from occuring
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
;
779 if ( (cmd
->cmd
& LC_REQ_DYLD
) != 0 ) {
780 if ( firstUnknownCmd
== NULL
)
781 firstUnknownCmd
= cmd
;
785 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
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
);
795 dyld::throwf("cannot load '%s' (load command 0x%08X is unknown)", this->getShortName(), firstUnknownCmd
->cmd
);
800 if ( dyldInfo
!= NULL
)
801 this->setDyldInfo(dyldInfo
);
802 if ( symbolTable
!= NULL
)
803 this->setSymbolTableInfo(symbolTable
, symbolTableStrings
, dynSymbolTable
);
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()
811 // update count of images with weak exports
812 if ( fRegisteredAsRequiresCoalescing
) {
813 --fgImagesRequiringCoalescing
;
814 if ( this->hasCoalescedExports() )
815 --fgImagesHasWeakDefinitions
;
818 // keep count of images used in shared cache
819 if ( fInSharedCache
)
820 --fgImagesUsedFromSharedCache
;
822 // unmap image when done
827 unsigned int ImageLoaderMachO::segmentCount() const
829 return fSegmentsCount
;
833 const macho_segment_command
* ImageLoaderMachO::segLoadCommand(unsigned int segIndex
) const
835 uint32_t* lcOffsets
= this->segmentCommandOffsets();
836 uint32_t lcOffset
= lcOffsets
[segIndex
];
837 return (macho_segment_command
*)(&fMachOData
[lcOffset
]);
840 const char* ImageLoaderMachO::segName(unsigned int segIndex
) const
842 return segLoadCommand(segIndex
)->segname
;
846 uintptr_t ImageLoaderMachO::segSize(unsigned int segIndex
) const
848 return segLoadCommand(segIndex
)->vmsize
;
852 uintptr_t ImageLoaderMachO::segFileSize(unsigned int segIndex
) const
854 return segLoadCommand(segIndex
)->filesize
;
858 bool ImageLoaderMachO::segHasTrailingZeroFill(unsigned int segIndex
)
860 return ( segWriteable(segIndex
) && (segSize(segIndex
) > segFileSize(segIndex
)) );
864 uintptr_t ImageLoaderMachO::segFileOffset(unsigned int segIndex
) const
866 return segLoadCommand(segIndex
)->fileoff
;
870 bool ImageLoaderMachO::segReadable(unsigned int segIndex
) const
872 return ( (segLoadCommand(segIndex
)->initprot
& VM_PROT_READ
) != 0);
876 bool ImageLoaderMachO::segWriteable(unsigned int segIndex
) const
878 return ( (segLoadCommand(segIndex
)->initprot
& VM_PROT_WRITE
) != 0);
882 bool ImageLoaderMachO::segExecutable(unsigned int segIndex
) const
884 return ( (segLoadCommand(segIndex
)->initprot
& VM_PROT_EXECUTE
) != 0);
888 bool ImageLoaderMachO::segUnaccessible(unsigned int segIndex
) const
890 return (segLoadCommand(segIndex
)->initprot
== 0);
893 bool ImageLoaderMachO::segHasPreferredLoadAddress(unsigned int segIndex
) const
895 return (segLoadCommand(segIndex
)->vmaddr
!= 0);
898 uintptr_t ImageLoaderMachO::segPreferredLoadAddress(unsigned int segIndex
) const
900 return segLoadCommand(segIndex
)->vmaddr
;
903 uintptr_t ImageLoaderMachO::segActualLoadAddress(unsigned int segIndex
) const
905 return segLoadCommand(segIndex
)->vmaddr
+ fSlide
;
909 uintptr_t ImageLoaderMachO::segActualEndAddress(unsigned int segIndex
) const
911 return segActualLoadAddress(segIndex
) + segSize(segIndex
);
914 bool ImageLoaderMachO::segHasRebaseFixUps(unsigned int segIndex
) const
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
= §ionsStart
[segCmd
->nsects
];
921 for (const struct macho_section
* sect
=sectionsStart
; sect
< sectionsEnd
; ++sect
) {
922 if ( (sect
->flags
& S_ATTR_LOC_RELOC
) != 0 )
929 bool ImageLoaderMachO::segHasBindFixUps(unsigned int segIndex
) const
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
= §ionsStart
[segCmd
->nsects
];
936 for (const struct macho_section
* sect
=sectionsStart
; sect
< sectionsEnd
; ++sect
) {
937 if ( (sect
->flags
& S_ATTR_EXT_RELOC
) != 0 )
945 bool ImageLoaderMachO::segIsReadOnlyImport(unsigned int segIndex
) const
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) );
955 void ImageLoaderMachO::UnmapSegments()
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
;
968 --ImageLoader::fgTotalSegmentsMapped
;
969 ImageLoader::fgTotalBytesMapped
-= segSize(i
);
970 munmap((void*)segActualLoadAddress(i
), segSize(i
));
974 --ImageLoader::fgTotalSegmentsMapped
;
975 ImageLoader::fgTotalBytesMapped
-= segSize(textSegmentIndex
);
976 munmap((void*)segActualLoadAddress(textSegmentIndex
), segSize(textSegmentIndex
));
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
)
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
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);
1007 bool ImageLoaderMachO::segmentsMustSlideTogether() const
1012 bool ImageLoaderMachO::segmentsCanSlide() const
1014 return (this->isDylib() || this->isBundle() || this->isPositionIndependentExecutable());
1017 bool ImageLoaderMachO::isBundle() const
1019 const macho_header
* mh
= (macho_header
*)fMachOData
;
1020 return ( mh
->filetype
== MH_BUNDLE
);
1023 bool ImageLoaderMachO::isDylib() const
1025 const macho_header
* mh
= (macho_header
*)fMachOData
;
1026 return ( mh
->filetype
== MH_DYLIB
);
1029 bool ImageLoaderMachO::isExecutable() const
1031 const macho_header
* mh
= (macho_header
*)fMachOData
;
1032 return ( mh
->filetype
== MH_EXECUTE
);
1035 bool ImageLoaderMachO::isPositionIndependentExecutable() const
1037 const macho_header
* mh
= (macho_header
*)fMachOData
;
1038 return ( (mh
->filetype
== MH_EXECUTE
) && ((mh
->flags
& MH_PIE
) != 0) );
1042 bool ImageLoaderMachO::forceFlat() const
1044 const macho_header
* mh
= (macho_header
*)fMachOData
;
1045 return ( (mh
->flags
& MH_FORCE_FLAT
) != 0 );
1048 bool ImageLoaderMachO::usesTwoLevelNameSpace() const
1050 const macho_header
* mh
= (macho_header
*)fMachOData
;
1051 return ( (mh
->flags
& MH_TWOLEVEL
) != 0 );
1054 bool ImageLoaderMachO::isPrebindable() const
1056 const macho_header
* mh
= (macho_header
*)fMachOData
;
1057 return ( (mh
->flags
& MH_PREBOUND
) != 0 );
1060 bool ImageLoaderMachO::hasCoalescedExports() const
1062 const macho_header
* mh
= (macho_header
*)fMachOData
;
1063 return ( (mh
->flags
& MH_WEAK_DEFINES
) != 0 );
1066 bool ImageLoaderMachO::hasReferencesToWeakSymbols() const
1068 const macho_header
* mh
= (macho_header
*)fMachOData
;
1069 return ( (mh
->flags
& MH_BINDS_TO_WEAK
) != 0 );
1072 bool ImageLoaderMachO::participatesInCoalescing() const
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() )
1079 return ( (mh
->flags
& (MH_WEAK_DEFINES
|MH_BINDS_TO_WEAK
)) != 0 );
1084 void ImageLoaderMachO::setSlide(intptr_t slide
)
1089 void ImageLoaderMachO::loadCodeSignature(const struct linkedit_data_command
* codeSigCmd
, int fd
, uint64_t offsetInFatFile
, const LinkContext
& context
)
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());
1097 disableCoverageCheck();
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
) {
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
);
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
1117 if ( result
== -1 ) {
1118 result
= fcntl(fd
, F_ADDFILESIGS
, &siginfo
);
1119 siginfo
.fs_file_start
= codeSigCmd
->dataoff
;
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());
1132 fCoveredCodeLength
= siginfo
.fs_file_start
;
1134 #if __MAC_OS_X_VERSION_MIN_REQUIRED
1135 if ( context
.processUsingLibraryValidation
) {
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
);
1144 dyld::throwf("code signature in (%s) not valid for use in process using Library Validation: %s", this->getPath(), messageBuffer
);
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
)
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
) {
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");
1170 int errnoCopy
= errno
;
1171 if ( errnoCopy
== EPERM
) {
1172 if ( dyld::sandboxBlockedMmap(getPath()) )
1173 dyld::throwf("file system sandbox blocked mmap() of '%s'", getPath());
1175 dyld::throwf("code signing blocked mmap() of '%s'", getPath());
1178 dyld::throwf("mmap() errno=%d validating first page of '%s'", errnoCopy
, getPath());
1181 if ( memcmp(fdata
, fileData
, lenFileData
) != 0 )
1182 dyld::throwf("mmap() page compare failed for '%s'", getPath());
1183 munmap(fdata
, lenFileData
);
1188 const char* ImageLoaderMachO::getInstallPath() const
1190 if ( fDylibIDOffset
!= 0 ) {
1191 const dylib_command
* dylibID
= (dylib_command
*)(&fMachOData
[fDylibIDOffset
]);
1192 return (char*)dylibID
+ dylibID
->dylib
.name
.offset
;
1197 void ImageLoaderMachO::registerInterposing()
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
) {
1206 case LC_SEGMENT_COMMAND
:
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
= §ionsStart
[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 )
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
;
1235 ImageLoader::fgInterposingTuples
.push_back(tuple
);
1243 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
1247 uint32_t ImageLoaderMachO::sdkVersion(const mach_header
* mh
)
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
;
1262 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
1267 uint32_t ImageLoaderMachO::sdkVersion() const
1269 return ImageLoaderMachO::sdkVersion(machHeader());
1272 uint32_t ImageLoaderMachO::minOSVersion(const mach_header
* mh
)
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
;
1287 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
1292 uint32_t ImageLoaderMachO::minOSVersion() const
1294 return ImageLoaderMachO::minOSVersion(machHeader());
1298 void* ImageLoaderMachO::getThreadPC() const
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
) )
1311 throw "LC_MAIN entryoff is out of range";
1313 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
1319 void* ImageLoaderMachO::getMain() const
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
) {
1329 const i386_thread_state_t
* registers
= (i386_thread_state_t
*)(((char*)cmd
) + 16);
1330 void* entry
= (void*)(registers
->eip
+ fSlide
);
1332 const x86_thread_state64_t
* registers
= (x86_thread_state64_t
*)(((char*)cmd
) + 16);
1333 void* entry
= (void*)(registers
->rip
+ fSlide
);
1335 const arm_thread_state_t
* registers
= (arm_thread_state_t
*)(((char*)cmd
) + 16);
1336 void* entry
= (void*)(registers
->__pc
+ fSlide
);
1338 const arm_thread_state64_t
* registers
= (arm_thread_state64_t
*)(((char*)cmd
) + 16);
1339 void* entry
= (void*)(registers
->__pc
+ fSlide
);
1341 #warning need processor specific code
1343 // <rdar://problem/8543820&9228031> verify entry point is in image
1344 if ( this->containsAddress(entry
) ) {
1350 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
1352 throw "no valid entry point";
1355 bool ImageLoaderMachO::needsAddedLibSystemDepency(unsigned int libCount
, const macho_header
* mh
)
1357 // <rdar://problem/6357561> ensure that every image depends on something which depends on libSystem
1361 // <rdar://problem/6409800> dyld implicit-libSystem breaks valgrind
1362 if ( mh
->filetype
== MH_EXECUTE
)
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
) {
1372 case LC_LOAD_WEAK_DYLIB
:
1373 case LC_REEXPORT_DYLIB
:
1374 case LC_LOAD_UPWARD_DYLIB
:
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) );
1387 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
1389 return isNonOSdylib
;
1393 void ImageLoaderMachO::doGetDependentLibraries(DependentLibraryInfo libs
[])
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;
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
) {
1413 case LC_LOAD_WEAK_DYLIB
:
1414 case LC_REEXPORT_DYLIB
:
1415 case LC_LOAD_UPWARD_DYLIB
:
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
);
1430 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
1435 ImageLoader::LibraryInfo
ImageLoaderMachO::doGetLibraryInfo(const LibraryInfo
&)
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
;
1445 info
.minVersion
= 0;
1446 info
.maxVersion
= 0;
1452 void ImageLoaderMachO::getRPaths(const LinkContext
& context
, std::vector
<const char*>& paths
) const
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
) {
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());
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
);
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());
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
);
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());
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
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
);
1522 // make copy so that all elements of 'paths' can be freed
1523 pathToAdd
= strdup(path
);
1528 // make copy so that all elements of 'paths' can be freed
1529 pathToAdd
= strdup(path
);
1531 if ( pathToAdd
!= NULL
)
1532 paths
.push_back(pathToAdd
);
1535 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
1540 bool ImageLoaderMachO::getUUID(uuid_t uuid
) const
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
) {
1548 uuid_command
* uc
= (uuid_command
*)cmd
;
1549 memcpy(uuid
, uc
->uuid
, 16);
1552 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
1558 void ImageLoaderMachO::doRebase(const LinkContext
& context
)
1560 // <rdar://problem/25329861> Delay calling setNeverUnload() until we know this is not for dlopen_preflight()
1561 if ( fRetainForObjC
)
1562 this->setNeverUnload();
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
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());
1576 else if ( fSlide
!= 0 ) {
1577 dyld::log("dyld: image slid, so could not use prebinding in %s\n", this->getPath());
1579 else if ( !this->allDependentLibrariesAsWhenPreBound() ) {
1580 dyld::log("dyld: dependent libraries changed, so could not use prebinding in %s\n", this->getPath());
1582 else if ( !this->usesTwoLevelNameSpace() ){
1583 dyld::log("dyld: image uses flat-namespace so, parts of prebinding ignored %s\n", this->getPath());
1586 dyld::log("dyld: environment variable disabled use of prebinding in %s\n", this->getPath());
1590 //dyld::log("slide=0x%08lX for %s\n", slide, this->getPath());
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
);
1599 // if loaded at preferred address, no rebasing necessary
1600 if ( this->fSlide
== 0 )
1603 #if TEXT_RELOC_SUPPORT
1604 // if there are __TEXT fixups, temporarily make __TEXT writable
1605 if ( fTextSegmentRebases
)
1606 this->makeTextSegmentWritable(context
, true);
1609 // do actual rebasing
1610 this->rebase(context
, fSlide
);
1612 #if TEXT_RELOC_SUPPORT
1613 // if there were __TEXT fixups, restore write protection
1614 if ( fTextSegmentRebases
)
1615 this->makeTextSegmentWritable(context
, false);
1620 #if TEXT_RELOC_SUPPORT
1621 void ImageLoaderMachO::makeTextSegmentWritable(const LinkContext
& context
, bool writeable
)
1623 for(unsigned int i
=0; i
< fSegmentsCount
; ++i
) {
1624 if ( segExecutable(i
) ) {
1626 segMakeWritable(i
, context
);
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
));
1633 segProtect(i
, context
);
1641 const ImageLoader::Symbol
* ImageLoaderMachO::findExportedSymbol(const char* name
, bool searchReExports
, const char* thisPath
, const ImageLoader
** foundIn
) const
1643 // look in this image first
1644 const ImageLoader::Symbol
* result
= this->findShallowExportedSymbol(name
, foundIn
);
1645 if ( result
!= NULL
)
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
)
1668 uintptr_t ImageLoaderMachO::getExportedSymbolAddress(const Symbol
* sym
, const LinkContext
& context
,
1669 const ImageLoader
* requestor
, bool runResolver
, const char* symbolName
) const
1671 return this->getSymbolAddress(sym
, requestor
, context
, runResolver
);
1674 uintptr_t ImageLoaderMachO::getSymbolAddress(const Symbol
* sym
, const ImageLoader
* requestor
,
1675 const LinkContext
& context
, bool runResolver
) const
1677 uintptr_t result
= exportedSymbolAddress(context
, sym
, requestor
, runResolver
);
1678 // check for interposing overrides
1679 result
= interposedAddress(context
, result
, requestor
);
1683 ImageLoader::DefinitionFlags
ImageLoaderMachO::getExportedSymbolInfo(const Symbol
* sym
) const
1685 if ( exportedSymbolIsWeakDefintion(sym
) )
1686 return kWeakDefinition
;
1688 return kNoDefinitionOptions
;
1691 const char* ImageLoaderMachO::getExportedSymbolName(const Symbol
* sym
) const
1693 return exportedSymbolName(sym
);
1696 uint32_t ImageLoaderMachO::getExportedSymbolCount() const
1698 return exportedSymbolCount();
1702 const ImageLoader::Symbol
* ImageLoaderMachO::getIndexedExportedSymbol(uint32_t index
) const
1704 return exportedSymbolIndexed(index
);
1708 uint32_t ImageLoaderMachO::getImportedSymbolCount() const
1710 return importedSymbolCount();
1714 const ImageLoader::Symbol
* ImageLoaderMachO::getIndexedImportedSymbol(uint32_t index
) const
1716 return importedSymbolIndexed(index
);
1720 ImageLoader::ReferenceFlags
ImageLoaderMachO::getImportedSymbolInfo(const ImageLoader::Symbol
* sym
) const
1722 ImageLoader::ReferenceFlags flags
= kNoReferenceOptions
;
1727 const char* ImageLoaderMachO::getImportedSymbolName(const ImageLoader::Symbol
* sym
) const
1729 return importedSymbolName(sym
);
1733 bool ImageLoaderMachO::getSectionContent(const char* segmentName
, const char* sectionName
, void** start
, size_t* length
)
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
) {
1740 case LC_SEGMENT_COMMAND
:
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
= §ionsStart
[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
;
1755 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
1762 void ImageLoaderMachO::getUnwindInfo(dyld_unwind_sections
* info
)
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
;
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
;
1781 intptr_t ImageLoaderMachO::computeSlide(const mach_header
* mh
)
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
);
1792 cmd
= (const load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
1797 bool ImageLoaderMachO::findSection(const mach_header
* mh
, const char* segmentName
, const char* sectionName
, void** sectAddress
, size_t* sectSize
)
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
) {
1804 case LC_SEGMENT_COMMAND
:
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
= §ionsStart
[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
;
1819 cmd
= (const load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
1825 bool ImageLoaderMachO::findSection(const void* imageInterior
, const char** segmentName
, const char** sectionName
, size_t* sectionOffset
)
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
) {
1833 case LC_SEGMENT_COMMAND
:
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
= §ionsStart
[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
;
1854 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
1859 const char* ImageLoaderMachO::libPath(unsigned int index
) const
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
;
1865 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
1866 switch ( cmd
->cmd
) {
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
;
1878 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
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
;
1890 void __attribute__((noreturn
)) ImageLoaderMachO::throwSymbolNotFound(const LinkContext
& context
, const char* symbol
,
1891 const char* referencedFrom
, const char* fromVersMismatch
,
1892 const char* expectedIn
)
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
);
1900 const mach_header
* ImageLoaderMachO::machHeader() const
1902 return (mach_header
*)fMachOData
;
1905 uintptr_t ImageLoaderMachO::getSlide() const
1910 // hmm. maybe this should be up in ImageLoader??
1911 const void* ImageLoaderMachO::getEnd() const
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
;
1921 return (const void*)lastAddress
;
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
)
1930 if ( context
.verboseBind
) {
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
);
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
);
1943 // dyld::logBindings("%s: %s\n", targetImage->getShortName(), symbolName);
1947 uintptr_t* locationToFix
= (uintptr_t*)location
;
1949 uintptr_t newValue
= value
+addend
;
1952 case BIND_TYPE_POINTER
:
1953 // test first so we don't needless dirty pages
1954 if ( *locationToFix
!= newValue
)
1955 *locationToFix
= newValue
;
1957 case BIND_TYPE_TEXT_ABSOLUTE32
:
1958 loc32
= (uint32_t*)locationToFix
;
1959 value32
= (uint32_t)newValue
;
1960 if ( *loc32
!= value32
)
1963 case BIND_TYPE_TEXT_PCREL32
:
1964 loc32
= (uint32_t*)locationToFix
;
1965 value32
= (uint32_t)(newValue
- (((uintptr_t)locationToFix
) + 4));
1966 if ( *loc32
!= value32
)
1970 dyld::throwf("bad bind type %d", type
);
1973 // update statistics
1974 ++fgTotalBindFixups
;
1983 #if SUPPORT_OLD_CRT_INITIALIZATION
1984 // first 16 bytes of "start" in crt1.o
1986 static uint8_t sStandardEntryPointInstructions
[16] = { 0x6a, 0x00, 0x89, 0xe5, 0x83, 0xe4, 0xf0, 0x83, 0xec, 0x10, 0x8b, 0x5d, 0x04, 0x89, 0x5c, 0x24 };
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
1997 // These are defined in dyldStartup.s
1998 extern "C" void stub_binding_helper();
2001 void ImageLoaderMachO::setupLazyPointerHandler(const LinkContext
& context
)
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
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
= §ionsStart
[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
;
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
;
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
);
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();
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
);
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
);
2073 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
2079 void ImageLoaderMachO::lookupProgramVars(const LinkContext
& context
) const
2081 ProgramVars vars
= context
.programVars
;
2082 const ImageLoader::Symbol
* sym
;
2084 // get mach header directly
2085 vars
.mh
= (macho_header
*)fMachOData
;
2088 sym
= this->findShallowExportedSymbol("_NXArgc", NULL
);
2090 vars
.NXArgcPtr
= (int*)this->getExportedSymbolAddress(sym
, context
, this, false, NULL
);
2093 sym
= this->findShallowExportedSymbol("_NXArgv", NULL
);
2095 vars
.NXArgvPtr
= (const char***)this->getExportedSymbolAddress(sym
, context
, this, false, NULL
);
2098 sym
= this->findShallowExportedSymbol("_environ", NULL
);
2100 vars
.environPtr
= (const char***)this->getExportedSymbolAddress(sym
, context
, this, false, NULL
);
2102 // lookup __progname
2103 sym
= this->findShallowExportedSymbol("___progname", NULL
);
2105 vars
.__prognamePtr
= (const char**)this->getExportedSymbolAddress(sym
, context
, this, false, NULL
);
2107 context
.setNewProgramVars(vars
);
2111 bool ImageLoaderMachO::usablePrebinding(const LinkContext
& context
) const
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
)
2120 switch ( context
.prebindUsage
) {
2121 case kUseAllPrebinding
:
2123 case kUseSplitSegPrebinding
:
2124 return this->fIsSplitSeg
;
2125 case kUseAllButAppPredbinding
:
2126 return (this != context
.mainExecutable
);
2127 case kUseNoPrebinding
:
2135 void ImageLoaderMachO::doImageInit(const LinkContext
& context
)
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
) {
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());
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());
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
);
2158 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
2163 void ImageLoaderMachO::doModInitFunctions(const LinkContext
& context
)
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
= §ionsStart
[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());
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());
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;
2207 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
2214 void ImageLoaderMachO::doGetDOFSections(const LinkContext
& context
, std::vector
<ImageLoader::DOFInfo
>& dofs
)
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
) {
2223 case LC_SEGMENT_COMMAND
:
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
= §ionsStart
[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
);
2243 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
2249 bool ImageLoaderMachO::doInitialization(const LinkContext
& context
)
2251 CRSetCrashLogMessage2(this->getPath());
2253 // mach-o has -init and static initializers
2254 doImageInit(context
);
2255 doModInitFunctions(context
);
2257 CRSetCrashLogMessage2(NULL
);
2259 return (fHasDashInit
|| fHasInitializers
);
2262 bool ImageLoaderMachO::needsInitialization()
2264 return ( fHasDashInit
|| fHasInitializers
);
2268 bool ImageLoaderMachO::needsTermination()
2270 return fHasTerminators
;
2274 void ImageLoaderMachO::doTermination(const LinkContext
& context
)
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
= §ionsStart
[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());
2299 if ( context
.verboseInit
)
2300 dyld::log("dyld: calling termination function %p in %s\n", func
, this->getPath());
2306 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
2312 void ImageLoaderMachO::printStatisticsDetails(unsigned int imageCount
, const InitializerTimingList
& timingInfo
)
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
);
2322 intptr_t ImageLoaderMachO::assignSegmentAddresses(const LinkContext
& context
)
2324 // preflight and calculate slide if needed
2325 const bool inPIE
= (fgNextPIEDylibAddress
!= 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");
2339 dyld::throwf("overlapping segments");
2341 if ( segLow
< lowAddr
)
2343 if ( segHigh
> highAddr
)
2346 if ( needsToSlide
|| !imageHasPreferredLoadAddress
|| inPIE
|| !reserveAddressRange(segPreferredLoadAddress(i
), segSize(i
)) )
2347 needsToSlide
= true;
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
;
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) )
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
));
2364 throw "mach-o does not support independently sliding segments";
2370 uintptr_t ImageLoaderMachO::reserveAnAddressRange(size_t length
, const ImageLoader::LinkContext
& context
)
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
;
2384 fgNextPIEDylibAddress
= 0;
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";
2393 bool ImageLoaderMachO::reserveAddressRange(uintptr_t start
, size_t length
)
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
)
2405 void ImageLoaderMachO::mapSegments(int fd
, uint64_t offsetInFat
, uint64_t lenInFat
, uint64_t fileLen
, const LinkContext
& context
)
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
);
2413 dyld::log("dyld: Mapping %s\n", this->getPath());
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
;
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
;
2436 // initially map __IMPORT segments R/W so dyld can update them
2437 if ( segIsReadOnlyImport(i
) )
2438 protection
|= PROT_WRITE
;
2440 // wholly zero-fill segments have nothing to mmap() in
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
);
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());
2453 dyld::throwf("code signing blocked mmap() of '%s'", this->getPath());
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());
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' : '.' );
2468 // update slide to reflect load location
2469 this->setSlide(slide
);
2472 void ImageLoaderMachO::mapSegments(const void* memoryImage
, uint64_t imageLen
, const LinkContext
& context
)
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);
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
);
2498 void ImageLoaderMachO::segProtect(unsigned int segIndex
, const ImageLoader::LinkContext
& context
)
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
;
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());
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' : '.' );
2523 void ImageLoaderMachO::segMakeWritable(unsigned int segIndex
, const ImageLoader::LinkContext
& context
)
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());
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' : '.' );
2543 const char* ImageLoaderMachO::findClosestSymbol(const mach_header
* mh
, const void* addr
, const void** closestAddr
)
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;
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
) {
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;
2564 else if ( (seg
->fileoff
== 0) && (seg
->filesize
!= 0) )
2565 slide
= (uintptr_t)mh
- seg
->vmaddr
;
2568 symtab
= (symtab_command
*)cmd
;
2571 dynSymbolTable
= (dysymtab_command
*)cmd
;
2574 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
2576 // no symbol table => no lookup by address
2577 if ( (symtab
== NULL
) || (dynSymbolTable
== NULL
) || !linkEditBaseFound
)
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
]);
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
)
2595 else if ( (s
->n_value
<= targetAddress
) && (bestSymbol
->n_value
< s
->n_value
) ) {
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
)
2609 else if ( (s
->n_value
<= targetAddress
) && (bestSymbol
->n_value
< s
->n_value
) ) {
2614 if ( bestSymbol
!= NULL
) {
2616 if (bestSymbol
->n_desc
& N_ARM_THUMB_DEF
)
2617 *closestAddr
= (void*)((bestSymbol
->n_value
| 1) + slide
);
2619 *closestAddr
= (void*)(bestSymbol
->n_value
+ slide
);
2621 *closestAddr
= (void*)(bestSymbol
->n_value
+ slide
);
2623 return &symbolTableStrings
[bestSymbol
->n_un
.n_strx
];
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
)
2631 if ( lazyBindingInfoOffset
> (lazyInfoEnd
-lazyInfoStart
) )
2633 uint8_t type
= BIND_TYPE_POINTER
;
2634 uint8_t symboFlags
= 0;
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
;
2642 case BIND_OPCODE_DONE
:
2643 *doneAfterBind
= false;
2646 case BIND_OPCODE_SET_DYLIB_ORDINAL_IMM
:
2647 *ordinal
= immediate
;
2649 case BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB
:
2650 *ordinal
= (int)read_uleb128(p
, lazyInfoEnd
);
2652 case BIND_OPCODE_SET_DYLIB_SPECIAL_IMM
:
2653 // the special ordinals are negative numbers
2654 if ( immediate
== 0 )
2657 int8_t signExtended
= BIND_OPCODE_MASK
| immediate
;
2658 *ordinal
= signExtended
;
2661 case BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM
:
2662 *symbolName
= (char*)p
;
2663 symboFlags
= immediate
;
2668 case BIND_OPCODE_SET_TYPE_IMM
:
2671 case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB
:
2672 *segIndex
= immediate
;
2673 *segOffset
= read_uleb128(p
, lazyInfoEnd
);
2675 case BIND_OPCODE_DO_BIND
:
2676 *doneAfterBind
= ((*p
& BIND_OPCODE_MASK
) == BIND_OPCODE_DONE
);
2677 lazyBindingInfoOffset
+= p
- &lazyInfoStart
[lazyBindingInfoOffset
];
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
:
2692 const dyld_info_command
* ImageLoaderMachO::findDyldInfoLoadCommand(const mach_header
* mh
)
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
) {
2700 case LC_DYLD_INFO_ONLY
:
2701 return (dyld_info_command
*)cmd
;
2703 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
2709 uintptr_t ImageLoaderMachO::segPreferredAddress(const mach_header
* mh
, unsigned segIndex
)
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
;
2723 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);