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
);
135 #if __MAC_OS_X_VERSION_MIN_REQUIRED
136 static uintptr_t pageAlign(uintptr_t value
)
138 return (value
+ 4095) & (-4096);
142 // determine if this mach-o file has classic or compressed LINKEDIT and number of segments it has
143 void ImageLoaderMachO::sniffLoadCommands(const macho_header
* mh
, const char* path
, bool inCache
, bool* compressed
,
144 unsigned int* segCount
, unsigned int* libCount
, const LinkContext
& context
,
145 const linkedit_data_command
** codeSigCmd
,
146 const encryption_info_command
** encryptCmd
)
154 const uint32_t cmd_count
= mh
->ncmds
;
155 const uint32_t sizeofcmds
= mh
->sizeofcmds
;
156 if ( sizeofcmds
> (MAX_MACH_O_HEADER_AND_LOAD_COMMANDS_SIZE
-sizeof(macho_header
)) )
157 dyld::throwf("malformed mach-o: load commands size (%u) > %u", sizeofcmds
, MAX_MACH_O_HEADER_AND_LOAD_COMMANDS_SIZE
);
158 if ( cmd_count
> (sizeofcmds
/sizeof(load_command
)) )
159 dyld::throwf("malformed mach-o: ncmds (%u) too large to fit in sizeofcmds (%u)", cmd_count
, sizeofcmds
);
160 const struct load_command
* const startCmds
= (struct load_command
*)(((uint8_t*)mh
) + sizeof(macho_header
));
161 const struct load_command
* const endCmds
= (struct load_command
*)(((uint8_t*)mh
) + sizeof(macho_header
) + sizeofcmds
);
162 const struct load_command
* cmd
= startCmds
;
163 bool foundLoadCommandSegment
= false;
164 const macho_segment_command
* linkeditSegCmd
= NULL
;
165 const macho_segment_command
* startOfFileSegCmd
= NULL
;
166 const dyld_info_command
* dyldInfoCmd
= NULL
;
167 const symtab_command
* symTabCmd
= NULL
;
168 const dysymtab_command
* dynSymbTabCmd
= NULL
;
169 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
170 uint32_t cmdLength
= cmd
->cmdsize
;
171 const macho_segment_command
* segCmd
;
172 const dylib_command
* dylibCmd
;
173 if ( cmdLength
< 8 ) {
174 dyld::throwf("malformed mach-o image: load command #%d length (%u) too small in %s",
177 const struct load_command
* const nextCmd
= (const struct load_command
*)(((char*)cmd
)+cmdLength
);
178 if ( (nextCmd
> endCmds
) || (nextCmd
< cmd
) ) {
179 dyld::throwf("malformed mach-o image: load command #%d length (%u) would exceed sizeofcmds (%u) in %s",
180 i
, cmdLength
, mh
->sizeofcmds
, path
);
184 case LC_DYLD_INFO_ONLY
:
185 if ( cmd
->cmdsize
!= sizeof(dyld_info_command
) )
186 throw "malformed mach-o image: LC_DYLD_INFO size wrong";
187 dyldInfoCmd
= (struct dyld_info_command
*)cmd
;
190 case LC_SEGMENT_COMMAND
:
191 segCmd
= (struct macho_segment_command
*)cmd
;
192 #if __MAC_OS_X_VERSION_MIN_REQUIRED
193 // rdar://problem/19617624 allow unmapped segments on OSX (but not iOS)
194 if ( ((segCmd
->filesize
) > pageAlign(segCmd
->vmsize
)) && (segCmd
->vmsize
!= 0) )
196 // <rdar://problem/19986776> dyld should support non-allocatable __LLVM segment
197 if ( (segCmd
->filesize
> segCmd
->vmsize
) && ((segCmd
->vmsize
!= 0) || ((segCmd
->flags
& SG_NORELOC
) == 0)) )
199 dyld::throwf("malformed mach-o image: segment load command %s filesize (0x%0lX) is larger than vmsize (0x%0lX)", segCmd
->segname
, (long)segCmd
->filesize
, (long)segCmd
->vmsize
);
200 if ( cmd
->cmdsize
< sizeof(macho_segment_command
) )
201 throw "malformed mach-o image: LC_SEGMENT size too small";
202 if ( cmd
->cmdsize
!= (sizeof(macho_segment_command
) + segCmd
->nsects
* sizeof(macho_section
)) )
203 throw "malformed mach-o image: LC_SEGMENT size wrong for number of sections";
204 // ignore zero-sized segments
205 if ( segCmd
->vmsize
!= 0 )
207 if ( strcmp(segCmd
->segname
, "__LINKEDIT") == 0 ) {
208 #if TARGET_IPHONE_SIMULATOR
209 // Note: should check on all platforms that __LINKEDIT is read-only, but <rdar://problem/22637626&22525618>
210 if ( segCmd
->initprot
!= VM_PROT_READ
)
211 throw "malformed mach-o image: __LINKEDIT segment does not have read-only permissions";
213 if ( segCmd
->fileoff
== 0 )
214 throw "malformed mach-o image: __LINKEDIT has fileoff==0 which overlaps mach_header";
215 if ( linkeditSegCmd
!= NULL
)
216 throw "malformed mach-o image: multiple __LINKEDIT segments";
217 linkeditSegCmd
= segCmd
;
220 if ( segCmd
->initprot
& 0xFFFFFFF8 )
221 dyld::throwf("malformed mach-o image: %s segment has invalid permission bits (0x%X) in initprot", segCmd
->segname
, segCmd
->initprot
);
222 if ( segCmd
->maxprot
& 0xFFFFFFF8 )
223 dyld::throwf("malformed mach-o image: %s segment has invalid permission bits (0x%X) in maxprot", segCmd
->segname
, segCmd
->maxprot
);
224 if ( (segCmd
->initprot
!= 0) && ((segCmd
->initprot
& VM_PROT_READ
) == 0) )
225 dyld::throwf("malformed mach-o image: %s segment is not mapped readable", segCmd
->segname
);
227 if ( (segCmd
->fileoff
== 0) && (segCmd
->filesize
!= 0) ) {
228 if ( (segCmd
->initprot
& VM_PROT_READ
) == 0 )
229 dyld::throwf("malformed mach-o image: %s segment maps start of file but is not readable", segCmd
->segname
);
230 if ( (segCmd
->initprot
& VM_PROT_WRITE
) == VM_PROT_WRITE
) {
231 if ( context
.strictMachORequired
)
232 dyld::throwf("malformed mach-o image: %s segment maps start of file but is writable", segCmd
->segname
);
234 if ( segCmd
->filesize
< (sizeof(macho_header
) + mh
->sizeofcmds
) )
235 dyld::throwf("malformed mach-o image: %s segment does not map all of load commands", segCmd
->segname
);
236 if ( startOfFileSegCmd
!= NULL
)
237 dyld::throwf("malformed mach-o image: multiple segments map start of file: %s %s", startOfFileSegCmd
->segname
, segCmd
->segname
);
238 startOfFileSegCmd
= segCmd
;
240 if ( context
.strictMachORequired
) {
241 uintptr_t vmStart
= segCmd
->vmaddr
;
242 uintptr_t vmSize
= segCmd
->vmsize
;
243 uintptr_t vmEnd
= vmStart
+ vmSize
;
244 uintptr_t fileStart
= segCmd
->fileoff
;
245 uintptr_t fileSize
= segCmd
->filesize
;
246 if ( (intptr_t)(vmSize
) < 0 )
247 dyld::throwf("malformed mach-o image: segment load command %s vmsize too large in %s", segCmd
->segname
, path
);
248 if ( vmStart
> vmEnd
)
249 dyld::throwf("malformed mach-o image: segment load command %s wraps around address space", segCmd
->segname
);
250 if ( vmSize
!= fileSize
) {
251 if ( segCmd
->initprot
== 0 ) {
252 // allow: fileSize == 0 && initprot == 0 e.g. __PAGEZERO
253 // allow: vmSize == 0 && initprot == 0 e.g. __LLVM
254 if ( (fileSize
!= 0) && (vmSize
!= 0) )
255 dyld::throwf("malformed mach-o image: unaccessable segment %s has non-zero filesize and vmsize", segCmd
->segname
);
258 // allow: vmSize > fileSize && initprot != X e.g. __DATA
259 if ( vmSize
< fileSize
) {
260 dyld::throwf("malformed mach-o image: segment %s has vmsize < filesize", segCmd
->segname
);
262 if ( segCmd
->initprot
& VM_PROT_EXECUTE
) {
263 dyld::throwf("malformed mach-o image: segment %s has vmsize != filesize and is executable", segCmd
->segname
);
268 if ( (fileSize
!= 0) && (segCmd
->initprot
== (VM_PROT_READ
| VM_PROT_EXECUTE
)) ) {
269 if ( foundLoadCommandSegment
)
270 throw "load commands in multiple segments";
271 foundLoadCommandSegment
= true;
274 else if ( (fileStart
< mh
->sizeofcmds
) && (fileSize
!= 0) ) {
275 // <rdar://problem/7942521> all load commands must be in an executable segment
276 if ( (fileStart
!= 0) || (fileSize
< (mh
->sizeofcmds
+sizeof(macho_header
))) )
277 dyld::throwf("malformed mach-o image: segment %s does not span all load commands", segCmd
->segname
);
278 if ( segCmd
->initprot
!= (VM_PROT_READ
| VM_PROT_EXECUTE
) )
279 dyld::throwf("malformed mach-o image: load commands found in segment %s with wrong permissions", segCmd
->segname
);
280 if ( foundLoadCommandSegment
)
281 throw "load commands in multiple segments";
282 foundLoadCommandSegment
= true;
285 const struct macho_section
* const sectionsStart
= (struct macho_section
*)((char*)segCmd
+ sizeof(struct macho_segment_command
));
286 const struct macho_section
* const sectionsEnd
= §ionsStart
[segCmd
->nsects
];
287 for (const struct macho_section
* sect
=sectionsStart
; sect
< sectionsEnd
; ++sect
) {
288 if (!inCache
&& sect
->offset
!= 0 && ((sect
->offset
+ sect
->size
) > (segCmd
->fileoff
+ segCmd
->filesize
)))
289 dyld::throwf("malformed mach-o image: section %s,%s of '%s' exceeds segment %s booundary", sect
->segname
, sect
->sectname
, path
, segCmd
->segname
);
293 case LC_SEGMENT_COMMAND_WRONG
:
294 dyld::throwf("malformed mach-o image: wrong LC_SEGMENT[_64] for architecture");
297 case LC_LOAD_WEAK_DYLIB
:
298 case LC_REEXPORT_DYLIB
:
299 case LC_LOAD_UPWARD_DYLIB
:
303 dylibCmd
= (dylib_command
*)cmd
;
304 if ( dylibCmd
->dylib
.name
.offset
> cmdLength
)
305 dyld::throwf("malformed mach-o image: dylib load command #%d has offset (%u) outside its size (%u)", i
, dylibCmd
->dylib
.name
.offset
, cmdLength
);
306 if ( (dylibCmd
->dylib
.name
.offset
+ strlen((char*)dylibCmd
+ dylibCmd
->dylib
.name
.offset
) + 1) > cmdLength
)
307 dyld::throwf("malformed mach-o image: dylib load command #%d string extends beyond end of load command", i
);
309 case LC_CODE_SIGNATURE
:
310 if ( cmd
->cmdsize
!= sizeof(linkedit_data_command
) )
311 throw "malformed mach-o image: LC_CODE_SIGNATURE size wrong";
312 // <rdar://problem/22799652> only support one LC_CODE_SIGNATURE per image
313 if ( *codeSigCmd
!= NULL
)
314 throw "malformed mach-o image: multiple LC_CODE_SIGNATURE load commands";
315 *codeSigCmd
= (struct linkedit_data_command
*)cmd
;
317 case LC_ENCRYPTION_INFO
:
318 if ( cmd
->cmdsize
!= sizeof(encryption_info_command
) )
319 throw "malformed mach-o image: LC_ENCRYPTION_INFO size wrong";
320 // <rdar://problem/22799652> only support one LC_ENCRYPTION_INFO per image
321 if ( *encryptCmd
!= NULL
)
322 throw "malformed mach-o image: multiple LC_ENCRYPTION_INFO load commands";
323 *encryptCmd
= (encryption_info_command
*)cmd
;
325 case LC_ENCRYPTION_INFO_64
:
326 if ( cmd
->cmdsize
!= sizeof(encryption_info_command_64
) )
327 throw "malformed mach-o image: LC_ENCRYPTION_INFO_64 size wrong";
328 // <rdar://problem/22799652> only support one LC_ENCRYPTION_INFO_64 per image
329 if ( *encryptCmd
!= NULL
)
330 throw "malformed mach-o image: multiple LC_ENCRYPTION_INFO_64 load commands";
331 *encryptCmd
= (encryption_info_command
*)cmd
;
334 if ( cmd
->cmdsize
!= sizeof(symtab_command
) )
335 throw "malformed mach-o image: LC_SYMTAB size wrong";
336 symTabCmd
= (symtab_command
*)cmd
;
339 if ( cmd
->cmdsize
!= sizeof(dysymtab_command
) )
340 throw "malformed mach-o image: LC_DYSYMTAB size wrong";
341 dynSymbTabCmd
= (dysymtab_command
*)cmd
;
343 #if __MAC_OS_X_VERSION_MIN_REQUIRED
344 // <rdar://problem/26797345> error when loading iOS Simulator mach-o binary into macOS process
345 case LC_VERSION_MIN_WATCHOS
:
346 case LC_VERSION_MIN_TVOS
:
347 case LC_VERSION_MIN_IPHONEOS
:
348 throw "mach-o, but built for simulator (not macOS)";
355 if ( context
.strictMachORequired
&& !foundLoadCommandSegment
)
356 throw "load commands not in a segment";
357 if ( linkeditSegCmd
== NULL
)
358 throw "malformed mach-o image: missing __LINKEDIT segment";
359 if ( startOfFileSegCmd
== NULL
)
360 throw "malformed mach-o image: missing __TEXT segment that maps start of file";
361 // <rdar://problem/13145644> verify every segment does not overlap another segment
362 if ( context
.strictMachORequired
) {
363 uintptr_t lastFileStart
= 0;
364 uintptr_t linkeditFileStart
= 0;
365 const struct load_command
* cmd1
= startCmds
;
366 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
367 if ( cmd1
->cmd
== LC_SEGMENT_COMMAND
) {
368 struct macho_segment_command
* segCmd1
= (struct macho_segment_command
*)cmd1
;
369 uintptr_t vmStart1
= segCmd1
->vmaddr
;
370 uintptr_t vmEnd1
= segCmd1
->vmaddr
+ segCmd1
->vmsize
;
371 uintptr_t fileStart1
= segCmd1
->fileoff
;
372 uintptr_t fileEnd1
= segCmd1
->fileoff
+ segCmd1
->filesize
;
374 if (fileStart1
> lastFileStart
)
375 lastFileStart
= fileStart1
;
377 if ( strcmp(&segCmd1
->segname
[0], "__LINKEDIT") == 0 ) {
378 linkeditFileStart
= fileStart1
;
381 const struct load_command
* cmd2
= startCmds
;
382 for (uint32_t j
= 0; j
< cmd_count
; ++j
) {
385 if ( cmd2
->cmd
== LC_SEGMENT_COMMAND
) {
386 struct macho_segment_command
* segCmd2
= (struct macho_segment_command
*)cmd2
;
387 uintptr_t vmStart2
= segCmd2
->vmaddr
;
388 uintptr_t vmEnd2
= segCmd2
->vmaddr
+ segCmd2
->vmsize
;
389 uintptr_t fileStart2
= segCmd2
->fileoff
;
390 uintptr_t fileEnd2
= segCmd2
->fileoff
+ segCmd2
->filesize
;
391 if ( ((vmStart2
<= vmStart1
) && (vmEnd2
> vmStart1
) && (vmEnd1
> vmStart1
))
392 || ((vmStart2
>= vmStart1
) && (vmStart2
< vmEnd1
) && (vmEnd2
> vmStart2
)) )
393 dyld::throwf("malformed mach-o image: segment %s vm overlaps segment %s", segCmd1
->segname
, segCmd2
->segname
);
394 if ( ((fileStart2
<= fileStart1
) && (fileEnd2
> fileStart1
) && (fileEnd1
> fileStart1
))
395 || ((fileStart2
>= fileStart1
) && (fileStart2
< fileEnd1
) && (fileEnd2
> fileStart2
)) )
396 dyld::throwf("malformed mach-o image: segment %s file content overlaps segment %s", segCmd1
->segname
, segCmd2
->segname
);
398 cmd2
= (const struct load_command
*)(((char*)cmd2
)+cmd2
->cmdsize
);
401 cmd1
= (const struct load_command
*)(((char*)cmd1
)+cmd1
->cmdsize
);
404 if (lastFileStart
!= linkeditFileStart
)
405 dyld::throwf("malformed mach-o image: __LINKEDIT must be last segment");
408 // validate linkedit content
409 if ( (dyldInfoCmd
== NULL
) && (symTabCmd
== NULL
) )
410 throw "malformed mach-o image: missing LC_SYMTAB or LC_DYLD_INFO";
411 if ( dynSymbTabCmd
== NULL
)
412 throw "malformed mach-o image: missing LC_DYSYMTAB";
414 uint32_t linkeditFileOffsetStart
= (uint32_t)linkeditSegCmd
->fileoff
;
415 uint32_t linkeditFileOffsetEnd
= (uint32_t)linkeditSegCmd
->fileoff
+ (uint32_t)linkeditSegCmd
->filesize
;
417 if ( !inCache
&& (dyldInfoCmd
!= NULL
) && context
.strictMachORequired
) {
418 // validate all LC_DYLD_INFO chunks fit in LINKEDIT and don't overlap
419 uint32_t offset
= linkeditFileOffsetStart
;
420 if ( dyldInfoCmd
->rebase_size
!= 0 ) {
421 if ( dyldInfoCmd
->rebase_size
& 0x80000000 )
422 throw "malformed mach-o image: dyld rebase info size overflow";
423 if ( dyldInfoCmd
->rebase_off
< offset
)
424 throw "malformed mach-o image: dyld rebase info underruns __LINKEDIT";
425 offset
= dyldInfoCmd
->rebase_off
+ dyldInfoCmd
->rebase_size
;
426 if ( offset
> linkeditFileOffsetEnd
)
427 throw "malformed mach-o image: dyld rebase info overruns __LINKEDIT";
429 if ( dyldInfoCmd
->bind_size
!= 0 ) {
430 if ( dyldInfoCmd
->bind_size
& 0x80000000 )
431 throw "malformed mach-o image: dyld bind info size overflow";
432 if ( dyldInfoCmd
->bind_off
< offset
)
433 throw "malformed mach-o image: dyld bind info overlaps rebase info";
434 offset
= dyldInfoCmd
->bind_off
+ dyldInfoCmd
->bind_size
;
435 if ( offset
> linkeditFileOffsetEnd
)
436 throw "malformed mach-o image: dyld bind info overruns __LINKEDIT";
438 if ( dyldInfoCmd
->weak_bind_size
!= 0 ) {
439 if ( dyldInfoCmd
->weak_bind_size
& 0x80000000 )
440 throw "malformed mach-o image: dyld weak bind info size overflow";
441 if ( dyldInfoCmd
->weak_bind_off
< offset
)
442 throw "malformed mach-o image: dyld weak bind info overlaps bind info";
443 offset
= dyldInfoCmd
->weak_bind_off
+ dyldInfoCmd
->weak_bind_size
;
444 if ( offset
> linkeditFileOffsetEnd
)
445 throw "malformed mach-o image: dyld weak bind info overruns __LINKEDIT";
447 if ( dyldInfoCmd
->lazy_bind_size
!= 0 ) {
448 if ( dyldInfoCmd
->lazy_bind_size
& 0x80000000 )
449 throw "malformed mach-o image: dyld lazy bind info size overflow";
450 if ( dyldInfoCmd
->lazy_bind_off
< offset
)
451 throw "malformed mach-o image: dyld lazy bind info overlaps weak bind info";
452 offset
= dyldInfoCmd
->lazy_bind_off
+ dyldInfoCmd
->lazy_bind_size
;
453 if ( offset
> linkeditFileOffsetEnd
)
454 throw "malformed mach-o image: dyld lazy bind info overruns __LINKEDIT";
456 if ( dyldInfoCmd
->export_size
!= 0 ) {
457 if ( dyldInfoCmd
->export_size
& 0x80000000 )
458 throw "malformed mach-o image: dyld export info size overflow";
459 if ( dyldInfoCmd
->export_off
< offset
)
460 throw "malformed mach-o image: dyld export info overlaps lazy bind info";
461 offset
= dyldInfoCmd
->export_off
+ dyldInfoCmd
->export_size
;
462 if ( offset
> linkeditFileOffsetEnd
)
463 throw "malformed mach-o image: dyld export info overruns __LINKEDIT";
467 if ( symTabCmd
!= NULL
) {
468 // validate symbol table fits in LINKEDIT
469 if ( symTabCmd
->symoff
< linkeditFileOffsetStart
)
470 throw "malformed mach-o image: symbol table underruns __LINKEDIT";
471 if ( symTabCmd
->nsyms
> 0x10000000 )
472 throw "malformed mach-o image: symbol table too large";
473 uint32_t symbolsSize
= symTabCmd
->nsyms
* sizeof(macho_nlist
);
474 if ( symbolsSize
> linkeditSegCmd
->filesize
)
475 throw "malformed mach-o image: symbol table overruns __LINKEDIT";
476 if ( symTabCmd
->symoff
+ symbolsSize
< symTabCmd
->symoff
)
477 throw "malformed mach-o image: symbol table size wraps";
478 if ( symTabCmd
->symoff
+ symbolsSize
> symTabCmd
->stroff
)
479 throw "malformed mach-o image: symbol table overlaps symbol strings";
480 if ( symTabCmd
->stroff
+ symTabCmd
->strsize
< symTabCmd
->stroff
)
481 throw "malformed mach-o image: symbol string size wraps";
482 if ( symTabCmd
->stroff
+ symTabCmd
->strsize
> linkeditFileOffsetEnd
) {
483 // <rdar://problem/24220313> let old apps overflow as long as it stays within mapped page
484 if ( context
.strictMachORequired
|| (symTabCmd
->stroff
+ symTabCmd
->strsize
> ((linkeditFileOffsetEnd
+ 4095) & (-4096))) )
485 throw "malformed mach-o image: symbol strings overrun __LINKEDIT";
487 // validate indirect symbol table
488 if ( dynSymbTabCmd
->nindirectsyms
!= 0 ) {
489 if ( dynSymbTabCmd
->indirectsymoff
< linkeditFileOffsetStart
)
490 throw "malformed mach-o image: indirect symbol table underruns __LINKEDIT";
491 if ( dynSymbTabCmd
->nindirectsyms
> 0x10000000 )
492 throw "malformed mach-o image: indirect symbol table too large";
493 uint32_t indirectTableSize
= dynSymbTabCmd
->nindirectsyms
* sizeof(uint32_t);
494 if ( indirectTableSize
> linkeditSegCmd
->filesize
)
495 throw "malformed mach-o image: indirect symbol table overruns __LINKEDIT";
496 if ( dynSymbTabCmd
->indirectsymoff
+ indirectTableSize
< dynSymbTabCmd
->indirectsymoff
)
497 throw "malformed mach-o image: indirect symbol table size wraps";
498 if ( context
.strictMachORequired
&& (dynSymbTabCmd
->indirectsymoff
+ indirectTableSize
> symTabCmd
->stroff
) )
499 throw "malformed mach-o image: indirect symbol table overruns string pool";
501 if ( (dynSymbTabCmd
->nlocalsym
> symTabCmd
->nsyms
) || (dynSymbTabCmd
->ilocalsym
> symTabCmd
->nsyms
) )
502 throw "malformed mach-o image: indirect symbol table local symbol count exceeds total symbols";
503 if ( dynSymbTabCmd
->ilocalsym
+ dynSymbTabCmd
->nlocalsym
< dynSymbTabCmd
->ilocalsym
)
504 throw "malformed mach-o image: indirect symbol table local symbol count wraps";
505 if ( (dynSymbTabCmd
->nextdefsym
> symTabCmd
->nsyms
) || (dynSymbTabCmd
->iextdefsym
> symTabCmd
->nsyms
) )
506 throw "malformed mach-o image: indirect symbol table extern symbol count exceeds total symbols";
507 if ( dynSymbTabCmd
->iextdefsym
+ dynSymbTabCmd
->nextdefsym
< dynSymbTabCmd
->iextdefsym
)
508 throw "malformed mach-o image: indirect symbol table extern symbol count wraps";
509 if ( (dynSymbTabCmd
->nundefsym
> symTabCmd
->nsyms
) || (dynSymbTabCmd
->iundefsym
> symTabCmd
->nsyms
) )
510 throw "malformed mach-o image: indirect symbol table undefined symbol count exceeds total symbols";
511 if ( dynSymbTabCmd
->iundefsym
+ dynSymbTabCmd
->nundefsym
< dynSymbTabCmd
->iundefsym
)
512 throw "malformed mach-o image: indirect symbol table undefined symbol count wraps";
516 // fSegmentsArrayCount is only 8-bits
517 if ( *segCount
> 255 )
518 dyld::throwf("malformed mach-o image: more than 255 segments in %s", path
);
520 // fSegmentsArrayCount is only 8-bits
521 if ( *libCount
> 4095 )
522 dyld::throwf("malformed mach-o image: more than 4095 dependent libraries in %s", path
);
524 if ( needsAddedLibSystemDepency(*libCount
, mh
) )
530 // create image for main executable
531 ImageLoader
* ImageLoaderMachO::instantiateMainExecutable(const macho_header
* mh
, uintptr_t slide
, const char* path
, const LinkContext
& context
)
533 //dyld::log("ImageLoader=%ld, ImageLoaderMachO=%ld, ImageLoaderMachOClassic=%ld, ImageLoaderMachOCompressed=%ld\n",
534 // sizeof(ImageLoader), sizeof(ImageLoaderMachO), sizeof(ImageLoaderMachOClassic), sizeof(ImageLoaderMachOCompressed));
536 unsigned int segCount
;
537 unsigned int libCount
;
538 const linkedit_data_command
* codeSigCmd
;
539 const encryption_info_command
* encryptCmd
;
540 sniffLoadCommands(mh
, path
, false, &compressed
, &segCount
, &libCount
, context
, &codeSigCmd
, &encryptCmd
);
541 // instantiate concrete class based on content of load commands
543 return ImageLoaderMachOCompressed::instantiateMainExecutable(mh
, slide
, path
, segCount
, libCount
, context
);
545 #if SUPPORT_CLASSIC_MACHO
546 return ImageLoaderMachOClassic::instantiateMainExecutable(mh
, slide
, path
, segCount
, libCount
, context
);
548 throw "missing LC_DYLD_INFO load command";
553 // create image by mapping in a mach-o file
554 ImageLoader
* ImageLoaderMachO::instantiateFromFile(const char* path
, int fd
, const uint8_t firstPages
[], size_t firstPagesSize
, uint64_t offsetInFat
,
555 uint64_t lenInFat
, const struct stat
& info
, const LinkContext
& context
)
558 unsigned int segCount
;
559 unsigned int libCount
;
560 const linkedit_data_command
* codeSigCmd
;
561 const encryption_info_command
* encryptCmd
;
562 sniffLoadCommands((const macho_header
*)firstPages
, path
, false, &compressed
, &segCount
, &libCount
, context
, &codeSigCmd
, &encryptCmd
);
563 // instantiate concrete class based on content of load commands
565 return ImageLoaderMachOCompressed::instantiateFromFile(path
, fd
, firstPages
, firstPagesSize
, offsetInFat
, lenInFat
, info
, segCount
, libCount
, codeSigCmd
, encryptCmd
, context
);
567 #if SUPPORT_CLASSIC_MACHO
568 return ImageLoaderMachOClassic::instantiateFromFile(path
, fd
, firstPages
, firstPagesSize
, offsetInFat
, lenInFat
, info
, segCount
, libCount
, codeSigCmd
, context
);
570 throw "missing LC_DYLD_INFO load command";
574 // create image by using cached mach-o file
575 ImageLoader
* ImageLoaderMachO::instantiateFromCache(const macho_header
* mh
, const char* path
, long slide
, const struct stat
& info
, const LinkContext
& context
)
577 // instantiate right concrete class
579 unsigned int segCount
;
580 unsigned int libCount
;
581 const linkedit_data_command
* codeSigCmd
;
582 const encryption_info_command
* encryptCmd
;
583 sniffLoadCommands(mh
, path
, true, &compressed
, &segCount
, &libCount
, context
, &codeSigCmd
, &encryptCmd
);
584 // instantiate concrete class based on content of load commands
586 return ImageLoaderMachOCompressed::instantiateFromCache(mh
, path
, slide
, info
, segCount
, libCount
, context
);
588 #if SUPPORT_CLASSIC_MACHO
589 return ImageLoaderMachOClassic::instantiateFromCache(mh
, path
, slide
, info
, segCount
, libCount
, context
);
591 throw "missing LC_DYLD_INFO load command";
595 // create image by copying an in-memory mach-o file
596 ImageLoader
* ImageLoaderMachO::instantiateFromMemory(const char* moduleName
, const macho_header
* mh
, uint64_t len
, const LinkContext
& context
)
599 unsigned int segCount
;
600 unsigned int libCount
;
601 const linkedit_data_command
* sigcmd
;
602 const encryption_info_command
* encryptCmd
;
603 sniffLoadCommands(mh
, moduleName
, false, &compressed
, &segCount
, &libCount
, context
, &sigcmd
, &encryptCmd
);
604 // instantiate concrete class based on content of load commands
606 return ImageLoaderMachOCompressed::instantiateFromMemory(moduleName
, mh
, len
, segCount
, libCount
, context
);
608 #if SUPPORT_CLASSIC_MACHO
609 return ImageLoaderMachOClassic::instantiateFromMemory(moduleName
, mh
, len
, segCount
, libCount
, context
);
611 throw "missing LC_DYLD_INFO load command";
616 int ImageLoaderMachO::crashIfInvalidCodeSignature()
618 // Now that segments are mapped in, try reading from first executable segment.
619 // If code signing is enabled the kernel will validate the code signature
620 // when paging in, and kill the process if invalid.
621 for(unsigned int i
=0; i
< fSegmentsCount
; ++i
) {
622 if ( (segFileOffset(i
) == 0) && (segFileSize(i
) != 0) ) {
623 // return read value to ensure compiler does not optimize away load
624 int* p
= (int*)segActualLoadAddress(i
);
632 void ImageLoaderMachO::parseLoadCmds(const LinkContext
& context
)
634 // now that segments are mapped in, get real fMachOData, fLinkEditBase, and fSlide
635 for(unsigned int i
=0; i
< fSegmentsCount
; ++i
) {
636 // set up pointer to __LINKEDIT segment
637 if ( strcmp(segName(i
),"__LINKEDIT") == 0 ) {
638 if ( context
.requireCodeSignature
&& (segFileOffset(i
) > fCoveredCodeLength
))
639 dyld::throwf("cannot load '%s' (segment outside of code signature)", this->getShortName());
640 fLinkEditBase
= (uint8_t*)(segActualLoadAddress(i
) - segFileOffset(i
));
642 #if TEXT_RELOC_SUPPORT
643 // __TEXT segment always starts at beginning of file and contains mach_header and load commands
644 if ( segExecutable(i
) ) {
645 if ( segHasRebaseFixUps(i
) && (fSlide
!= 0) )
646 fTextSegmentRebases
= true;
647 if ( segHasBindFixUps(i
) )
648 fTextSegmentBinds
= true;
652 if ( segIsReadOnlyImport(i
) )
653 fReadOnlyImportSegment
= true;
655 // some segment always starts at beginning of file and contains mach_header and load commands
656 if ( (segFileOffset(i
) == 0) && (segFileSize(i
) != 0) ) {
657 fMachOData
= (uint8_t*)(segActualLoadAddress(i
));
661 // keep count of prebound images with weak exports
662 if ( this->participatesInCoalescing() ) {
663 ++fgImagesRequiringCoalescing
;
664 fRegisteredAsRequiresCoalescing
= true;
665 if ( this->hasCoalescedExports() )
666 ++fgImagesHasWeakDefinitions
;
669 // keep count of images used in shared cache
670 if ( fInSharedCache
)
671 ++fgImagesUsedFromSharedCache
;
673 // walk load commands (mapped in at start of __TEXT segment)
674 const dyld_info_command
* dyldInfo
= NULL
;
675 const macho_nlist
* symbolTable
= NULL
;
676 const char* symbolTableStrings
= NULL
;
677 const struct load_command
* firstUnknownCmd
= NULL
;
678 const struct version_min_command
* minOSVersionCmd
= NULL
;
679 const dysymtab_command
* dynSymbolTable
= NULL
;
680 const uint32_t cmd_count
= ((macho_header
*)fMachOData
)->ncmds
;
681 const struct load_command
* const cmds
= (struct load_command
*)&fMachOData
[sizeof(macho_header
)];
682 const struct load_command
* cmd
= cmds
;
683 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
687 const struct symtab_command
* symtab
= (struct symtab_command
*)cmd
;
688 symbolTableStrings
= (const char*)&fLinkEditBase
[symtab
->stroff
];
689 symbolTable
= (macho_nlist
*)(&fLinkEditBase
[symtab
->symoff
]);
693 dynSymbolTable
= (struct dysymtab_command
*)cmd
;
695 case LC_SUB_UMBRELLA
:
696 fHasSubUmbrella
= true;
698 case LC_SUB_FRAMEWORK
:
702 fHasSubLibraries
= true;
704 case LC_ROUTINES_COMMAND
:
708 case LC_DYLD_INFO_ONLY
:
709 dyldInfo
= (struct dyld_info_command
*)cmd
;
711 case LC_SEGMENT_COMMAND
:
713 const struct macho_segment_command
* seg
= (struct macho_segment_command
*)cmd
;
714 const bool isTextSeg
= (strcmp(seg
->segname
, "__TEXT") == 0);
715 #if __i386__ && __MAC_OS_X_VERSION_MIN_REQUIRED
716 const bool isObjCSeg
= (strcmp(seg
->segname
, "__OBJC") == 0);
720 const bool isDataSeg
= (strncmp(seg
->segname
, "__DATA", 6) == 0);
722 const struct macho_section
* const sectionsStart
= (struct macho_section
*)((char*)seg
+ sizeof(struct macho_segment_command
));
723 const struct macho_section
* const sectionsEnd
= §ionsStart
[seg
->nsects
];
724 for (const struct macho_section
* sect
=sectionsStart
; sect
< sectionsEnd
; ++sect
) {
725 const uint8_t type
= sect
->flags
& SECTION_TYPE
;
726 if ( type
== S_MOD_INIT_FUNC_POINTERS
)
727 fHasInitializers
= true;
728 else if ( type
== S_MOD_TERM_FUNC_POINTERS
)
729 fHasTerminators
= true;
730 else if ( type
== S_DTRACE_DOF
)
731 fHasDOFSections
= true;
732 else if ( isTextSeg
&& (strcmp(sect
->sectname
, "__eh_frame") == 0) )
733 fEHFrameSectionOffset
= (uint32_t)((uint8_t*)sect
- fMachOData
);
734 else if ( isTextSeg
&& (strcmp(sect
->sectname
, "__unwind_info") == 0) )
735 fUnwindInfoSectionOffset
= (uint32_t)((uint8_t*)sect
- fMachOData
);
737 #if __i386__ && __MAC_OS_X_VERSION_MIN_REQUIRED
738 else if ( isObjCSeg
) {
739 if ( strcmp(sect
->sectname
, "__image_info") == 0 ) {
740 const uint32_t* imageInfo
= (uint32_t*)(sect
->addr
+ fSlide
);
741 uint32_t flags
= imageInfo
[1];
742 if ( (flags
& 4) && (((macho_header
*)fMachOData
)->filetype
!= MH_EXECUTE
) )
743 dyld::throwf("cannot load '%s' because Objective-C garbage collection is not supported", getPath());
745 else if ( ((macho_header
*)fMachOData
)->filetype
== MH_DYLIB
) {
746 fRetainForObjC
= true;
750 else if ( isDataSeg
&& (strncmp(sect
->sectname
, "__objc_imageinfo", 16) == 0) ) {
751 #if __MAC_OS_X_VERSION_MIN_REQUIRED
752 const uint32_t* imageInfo
= (uint32_t*)(sect
->addr
+ fSlide
);
753 uint32_t flags
= imageInfo
[1];
754 if ( (flags
& 4) && (((macho_header
*)fMachOData
)->filetype
!= MH_EXECUTE
) )
755 dyld::throwf("cannot load '%s' because Objective-C garbage collection is not supported", getPath());
759 else if ( isDataSeg
&& (strncmp(sect
->sectname
, "__objc_", 7) == 0) && (((macho_header
*)fMachOData
)->filetype
== MH_DYLIB
) )
760 fRetainForObjC
= true;
765 case LC_TWOLEVEL_HINTS
:
766 // no longer supported
770 fDylibIDOffset
= (uint32_t)((uint8_t*)cmd
- fMachOData
);
774 case LC_LOAD_WEAK_DYLIB
:
775 case LC_REEXPORT_DYLIB
:
776 case LC_LOAD_UPWARD_DYLIB
:
778 // do nothing, just prevent LC_REQ_DYLD exception from occuring
780 case LC_VERSION_MIN_MACOSX
:
781 case LC_VERSION_MIN_IPHONEOS
:
782 case LC_VERSION_MIN_TVOS
:
783 case LC_VERSION_MIN_WATCHOS
:
784 minOSVersionCmd
= (version_min_command
*)cmd
;
787 if ( (cmd
->cmd
& LC_REQ_DYLD
) != 0 ) {
788 if ( firstUnknownCmd
== NULL
)
789 firstUnknownCmd
= cmd
;
793 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
795 if ( firstUnknownCmd
!= NULL
) {
796 if ( minOSVersionCmd
!= NULL
) {
797 dyld::throwf("cannot load '%s' because it was built for OS version %u.%u (load command 0x%08X is unknown)",
798 this->getShortName(),
799 minOSVersionCmd
->version
>> 16, ((minOSVersionCmd
->version
>> 8) & 0xff),
800 firstUnknownCmd
->cmd
);
803 dyld::throwf("cannot load '%s' (load command 0x%08X is unknown)", this->getShortName(), firstUnknownCmd
->cmd
);
808 if ( dyldInfo
!= NULL
)
809 this->setDyldInfo(dyldInfo
);
810 if ( symbolTable
!= NULL
)
811 this->setSymbolTableInfo(symbolTable
, symbolTableStrings
, dynSymbolTable
);
815 // don't do this work in destructor because we need object to be full subclass
816 // for UnmapSegments() to work
817 void ImageLoaderMachO::destroy()
819 // update count of images with weak exports
820 if ( fRegisteredAsRequiresCoalescing
) {
821 --fgImagesRequiringCoalescing
;
822 if ( this->hasCoalescedExports() )
823 --fgImagesHasWeakDefinitions
;
826 // keep count of images used in shared cache
827 if ( fInSharedCache
)
828 --fgImagesUsedFromSharedCache
;
830 // unmap image when done
835 unsigned int ImageLoaderMachO::segmentCount() const
837 return fSegmentsCount
;
841 const macho_segment_command
* ImageLoaderMachO::segLoadCommand(unsigned int segIndex
) const
843 uint32_t* lcOffsets
= this->segmentCommandOffsets();
844 uint32_t lcOffset
= lcOffsets
[segIndex
];
845 return (macho_segment_command
*)(&fMachOData
[lcOffset
]);
848 const char* ImageLoaderMachO::segName(unsigned int segIndex
) const
850 return segLoadCommand(segIndex
)->segname
;
854 uintptr_t ImageLoaderMachO::segSize(unsigned int segIndex
) const
856 return segLoadCommand(segIndex
)->vmsize
;
860 uintptr_t ImageLoaderMachO::segFileSize(unsigned int segIndex
) const
862 return segLoadCommand(segIndex
)->filesize
;
866 bool ImageLoaderMachO::segHasTrailingZeroFill(unsigned int segIndex
)
868 return ( segWriteable(segIndex
) && (segSize(segIndex
) > segFileSize(segIndex
)) );
872 uintptr_t ImageLoaderMachO::segFileOffset(unsigned int segIndex
) const
874 return segLoadCommand(segIndex
)->fileoff
;
878 bool ImageLoaderMachO::segReadable(unsigned int segIndex
) const
880 return ( (segLoadCommand(segIndex
)->initprot
& VM_PROT_READ
) != 0);
884 bool ImageLoaderMachO::segWriteable(unsigned int segIndex
) const
886 return ( (segLoadCommand(segIndex
)->initprot
& VM_PROT_WRITE
) != 0);
890 bool ImageLoaderMachO::segExecutable(unsigned int segIndex
) const
892 return ( (segLoadCommand(segIndex
)->initprot
& VM_PROT_EXECUTE
) != 0);
896 bool ImageLoaderMachO::segUnaccessible(unsigned int segIndex
) const
898 return (segLoadCommand(segIndex
)->initprot
== 0);
901 bool ImageLoaderMachO::segHasPreferredLoadAddress(unsigned int segIndex
) const
903 return (segLoadCommand(segIndex
)->vmaddr
!= 0);
906 uintptr_t ImageLoaderMachO::segPreferredLoadAddress(unsigned int segIndex
) const
908 return segLoadCommand(segIndex
)->vmaddr
;
911 uintptr_t ImageLoaderMachO::segActualLoadAddress(unsigned int segIndex
) const
913 return segLoadCommand(segIndex
)->vmaddr
+ fSlide
;
917 uintptr_t ImageLoaderMachO::segActualEndAddress(unsigned int segIndex
) const
919 return segActualLoadAddress(segIndex
) + segSize(segIndex
);
922 bool ImageLoaderMachO::segHasRebaseFixUps(unsigned int segIndex
) const
924 #if TEXT_RELOC_SUPPORT
925 // scan sections for fix-up bit
926 const macho_segment_command
* segCmd
= segLoadCommand(segIndex
);
927 const struct macho_section
* const sectionsStart
= (struct macho_section
*)((char*)segCmd
+ sizeof(struct macho_segment_command
));
928 const struct macho_section
* const sectionsEnd
= §ionsStart
[segCmd
->nsects
];
929 for (const struct macho_section
* sect
=sectionsStart
; sect
< sectionsEnd
; ++sect
) {
930 if ( (sect
->flags
& S_ATTR_LOC_RELOC
) != 0 )
937 bool ImageLoaderMachO::segHasBindFixUps(unsigned int segIndex
) const
939 #if TEXT_RELOC_SUPPORT
940 // scan sections for fix-up bit
941 const macho_segment_command
* segCmd
= segLoadCommand(segIndex
);
942 const struct macho_section
* const sectionsStart
= (struct macho_section
*)((char*)segCmd
+ sizeof(struct macho_segment_command
));
943 const struct macho_section
* const sectionsEnd
= §ionsStart
[segCmd
->nsects
];
944 for (const struct macho_section
* sect
=sectionsStart
; sect
< sectionsEnd
; ++sect
) {
945 if ( (sect
->flags
& S_ATTR_EXT_RELOC
) != 0 )
953 bool ImageLoaderMachO::segIsReadOnlyImport(unsigned int segIndex
) const
955 const macho_segment_command
* segCmd
= segLoadCommand(segIndex
);
956 return ( (segCmd
->initprot
& VM_PROT_EXECUTE
)
957 && ((segCmd
->initprot
& VM_PROT_WRITE
) == 0)
958 && (strcmp(segCmd
->segname
, "__IMPORT") == 0) );
963 void ImageLoaderMachO::UnmapSegments()
965 // usually unmap image when done
966 if ( ! this->leaveMapped() && (this->getState() >= dyld_image_state_mapped
) ) {
967 // unmap TEXT segment last because it contains load command being inspected
968 unsigned int textSegmentIndex
= 0;
969 for(unsigned int i
=0; i
< fSegmentsCount
; ++i
) {
970 //dyld::log("unmap %s at 0x%08lX\n", seg->getName(), seg->getActualLoadAddress(this));
971 if ( (segFileOffset(i
) == 0) && (segFileSize(i
) != 0) ) {
972 textSegmentIndex
= i
;
976 --ImageLoader::fgTotalSegmentsMapped
;
977 ImageLoader::fgTotalBytesMapped
-= segSize(i
);
978 munmap((void*)segActualLoadAddress(i
), segSize(i
));
982 --ImageLoader::fgTotalSegmentsMapped
;
983 ImageLoader::fgTotalBytesMapped
-= segSize(textSegmentIndex
);
984 munmap((void*)segActualLoadAddress(textSegmentIndex
), segSize(textSegmentIndex
));
989 // prefetch __DATA/__OBJC pages during launch, but not for dynamically loaded code
990 void ImageLoaderMachO::preFetchDATA(int fd
, uint64_t offsetInFat
, const LinkContext
& context
)
992 if ( context
.linkingMainExecutable
) {
993 for(unsigned int i
=0, e
=segmentCount(); i
< e
; ++i
) {
994 if ( segWriteable(i
) && (segFileSize(i
) > 0) ) {
995 // prefetch writable segment that have mmap'ed regions
997 advice
.ra_offset
= offsetInFat
+ segFileOffset(i
);
998 advice
.ra_count
= (int)segFileSize(i
);
999 // limit prefetch to 1MB (256 pages)
1000 if ( advice
.ra_count
> 1024*1024 )
1001 advice
.ra_count
= 1024*1024;
1002 // don't prefetch single pages, let them fault in
1003 fgTotalBytesPreFetched
+= advice
.ra_count
;
1004 fcntl(fd
, F_RDADVISE
, &advice
);
1005 if ( context
.verboseMapping
) {
1006 dyld::log("%18s prefetching 0x%0lX -> 0x%0lX\n",
1007 segName(i
), segActualLoadAddress(i
), segActualLoadAddress(i
)+advice
.ra_count
-1);
1015 bool ImageLoaderMachO::segmentsMustSlideTogether() const
1020 bool ImageLoaderMachO::segmentsCanSlide() const
1022 return (this->isDylib() || this->isBundle() || this->isPositionIndependentExecutable());
1025 bool ImageLoaderMachO::isBundle() const
1027 const macho_header
* mh
= (macho_header
*)fMachOData
;
1028 return ( mh
->filetype
== MH_BUNDLE
);
1031 bool ImageLoaderMachO::isDylib() const
1033 const macho_header
* mh
= (macho_header
*)fMachOData
;
1034 return ( mh
->filetype
== MH_DYLIB
);
1037 bool ImageLoaderMachO::isExecutable() const
1039 const macho_header
* mh
= (macho_header
*)fMachOData
;
1040 return ( mh
->filetype
== MH_EXECUTE
);
1043 bool ImageLoaderMachO::isPositionIndependentExecutable() const
1045 const macho_header
* mh
= (macho_header
*)fMachOData
;
1046 return ( (mh
->filetype
== MH_EXECUTE
) && ((mh
->flags
& MH_PIE
) != 0) );
1050 bool ImageLoaderMachO::forceFlat() const
1052 const macho_header
* mh
= (macho_header
*)fMachOData
;
1053 return ( (mh
->flags
& MH_FORCE_FLAT
) != 0 );
1056 bool ImageLoaderMachO::usesTwoLevelNameSpace() const
1058 const macho_header
* mh
= (macho_header
*)fMachOData
;
1059 return ( (mh
->flags
& MH_TWOLEVEL
) != 0 );
1062 bool ImageLoaderMachO::isPrebindable() const
1064 const macho_header
* mh
= (macho_header
*)fMachOData
;
1065 return ( (mh
->flags
& MH_PREBOUND
) != 0 );
1068 bool ImageLoaderMachO::hasCoalescedExports() const
1070 const macho_header
* mh
= (macho_header
*)fMachOData
;
1071 return ( (mh
->flags
& MH_WEAK_DEFINES
) != 0 );
1074 bool ImageLoaderMachO::hasReferencesToWeakSymbols() const
1076 const macho_header
* mh
= (macho_header
*)fMachOData
;
1077 return ( (mh
->flags
& MH_BINDS_TO_WEAK
) != 0 );
1080 bool ImageLoaderMachO::participatesInCoalescing() const
1082 const macho_header
* mh
= (macho_header
*)fMachOData
;
1083 // if image is loaded with RTLD_LOCAL, then its symbols' visibility
1084 // is reduced and it can't coalesce with other images
1085 if ( this->hasHiddenExports() )
1087 return ( (mh
->flags
& (MH_WEAK_DEFINES
|MH_BINDS_TO_WEAK
)) != 0 );
1092 void ImageLoaderMachO::setSlide(intptr_t slide
)
1097 void ImageLoaderMachO::loadCodeSignature(const struct linkedit_data_command
* codeSigCmd
, int fd
, uint64_t offsetInFatFile
, const LinkContext
& context
)
1099 // if dylib being loaded has no code signature load command
1100 if ( codeSigCmd
== NULL
) {
1101 if (context
.requireCodeSignature
) {
1102 // if we require dylibs to be codesigned there needs to be a signature.
1103 dyld::throwf("required code signature missing for '%s'\n", this->getPath());
1105 disableCoverageCheck();
1109 #if __MAC_OS_X_VERSION_MIN_REQUIRED
1110 // <rdar://problem/13622786> ignore code signatures in binaries built with pre-10.9 tools
1111 if ( this->sdkVersion() < DYLD_MACOSX_VERSION_10_9
) {
1115 fsignatures_t siginfo
;
1116 siginfo
.fs_file_start
=offsetInFatFile
; // start of mach-o slice in fat file
1117 siginfo
.fs_blob_start
=(void*)(long)(codeSigCmd
->dataoff
); // start of CD in mach-o file
1118 siginfo
.fs_blob_size
=codeSigCmd
->datasize
; // size of CD
1119 int result
= fcntl(fd
, F_ADDFILESIGS_RETURN
, &siginfo
);
1121 #if TARGET_IPHONE_SIMULATOR
1122 // rdar://problem/18759224> check range covered by the code directory after loading
1123 // Attempt to fallback only if we are in the simulator
1125 if ( result
== -1 ) {
1126 result
= fcntl(fd
, F_ADDFILESIGS
, &siginfo
);
1127 siginfo
.fs_file_start
= codeSigCmd
->dataoff
;
1131 if ( result
== -1 ) {
1132 if ( (errno
== EPERM
) || (errno
== EBADEXEC
) )
1133 dyld::throwf("code signature invalid for '%s'\n", this->getPath());
1134 if ( context
.verboseCodeSignatures
)
1135 dyld::log("dyld: Failed registering code signature for %s, errno=%d\n", this->getPath(), errno
);
1136 siginfo
.fs_file_start
= UINT64_MAX
;
1137 } else if ( context
.verboseCodeSignatures
) {
1138 dyld::log("dyld: Registered code signature for %s\n", this->getPath());
1140 fCoveredCodeLength
= siginfo
.fs_file_start
;
1142 #if __MAC_OS_X_VERSION_MIN_REQUIRED
1143 if ( context
.processUsingLibraryValidation
) {
1145 char messageBuffer
[512];
1146 messageBuffer
[0] = '\0';
1147 checkInfo
.lv_file_start
= offsetInFatFile
;
1148 checkInfo
.lv_error_message_size
= sizeof(messageBuffer
);
1149 checkInfo
.lv_error_message
= messageBuffer
;
1150 int res
= fcntl(fd
, F_CHECK_LV
, &checkInfo
);
1152 dyld::throwf("code signature in (%s) not valid for use in process using Library Validation: %s", this->getPath(), messageBuffer
);
1159 void ImageLoaderMachO::validateFirstPages(const struct linkedit_data_command
* codeSigCmd
, int fd
, const uint8_t *fileData
, size_t lenFileData
, off_t offsetInFat
, const LinkContext
& context
)
1161 #if __MAC_OS_X_VERSION_MIN_REQUIRED
1162 // rdar://problem/21839703> 15A226d: dyld crashes in mageLoaderMachO::validateFirstPages during dlopen() after encountering an mmap failure
1163 // We need to ignore older code signatures because they will be bad.
1164 if ( this->sdkVersion() < DYLD_MACOSX_VERSION_10_9
) {
1168 if (codeSigCmd
!= NULL
) {
1169 void *fdata
= xmmap(NULL
, lenFileData
, PROT_READ
| PROT_EXEC
, MAP_SHARED
, fd
, offsetInFat
);
1170 if ( fdata
== MAP_FAILED
) {
1171 #if __MAC_OS_X_VERSION_MIN_REQUIRED
1172 if ( context
.processUsingLibraryValidation
) {
1173 dyld::throwf("cannot load image with wrong team ID in process using Library Validation");
1178 int errnoCopy
= errno
;
1179 if ( errnoCopy
== EPERM
) {
1180 if ( dyld::sandboxBlockedMmap(getPath()) )
1181 dyld::throwf("file system sandbox blocked mmap() of '%s'", getPath());
1183 dyld::throwf("code signing blocked mmap() of '%s'", getPath());
1186 dyld::throwf("mmap() errno=%d validating first page of '%s'", errnoCopy
, getPath());
1189 if ( memcmp(fdata
, fileData
, lenFileData
) != 0 )
1190 dyld::throwf("mmap() page compare failed for '%s'", getPath());
1191 munmap(fdata
, lenFileData
);
1196 const char* ImageLoaderMachO::getInstallPath() const
1198 if ( fDylibIDOffset
!= 0 ) {
1199 const dylib_command
* dylibID
= (dylib_command
*)(&fMachOData
[fDylibIDOffset
]);
1200 return (char*)dylibID
+ dylibID
->dylib
.name
.offset
;
1205 void ImageLoaderMachO::registerInterposing()
1207 // mach-o files advertise interposing by having a __DATA __interpose section
1208 struct InterposeData
{ uintptr_t replacement
; uintptr_t replacee
; };
1209 const uint32_t cmd_count
= ((macho_header
*)fMachOData
)->ncmds
;
1210 const struct load_command
* const cmds
= (struct load_command
*)&fMachOData
[sizeof(macho_header
)];
1211 const struct load_command
* cmd
= cmds
;
1212 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
1214 case LC_SEGMENT_COMMAND
:
1216 const struct macho_segment_command
* seg
= (struct macho_segment_command
*)cmd
;
1217 const struct macho_section
* const sectionsStart
= (struct macho_section
*)((char*)seg
+ sizeof(struct macho_segment_command
));
1218 const struct macho_section
* const sectionsEnd
= §ionsStart
[seg
->nsects
];
1219 for (const struct macho_section
* sect
=sectionsStart
; sect
< sectionsEnd
; ++sect
) {
1220 if ( ((sect
->flags
& SECTION_TYPE
) == S_INTERPOSING
) || ((strcmp(sect
->sectname
, "__interpose") == 0) && (strcmp(seg
->segname
, "__DATA") == 0)) ) {
1221 // <rdar://problem/23929217> Ensure section is within segment
1222 if ( (sect
->addr
< seg
->vmaddr
) || (sect
->addr
+sect
->size
> seg
->vmaddr
+seg
->vmsize
) || (sect
->addr
+sect
->size
< sect
->addr
) )
1223 dyld::throwf("interpose section has malformed address range for %s\n", this->getPath());
1224 const InterposeData
* interposeArray
= (InterposeData
*)(sect
->addr
+ fSlide
);
1225 const size_t count
= sect
->size
/ sizeof(InterposeData
);
1226 for (size_t j
=0; j
< count
; ++j
) {
1227 ImageLoader::InterposeTuple tuple
;
1228 tuple
.replacement
= interposeArray
[j
].replacement
;
1229 tuple
.neverImage
= this;
1230 tuple
.onlyImage
= NULL
;
1231 tuple
.replacee
= interposeArray
[j
].replacee
;
1232 // <rdar://problem/25686570> ignore interposing on a weak function that does not exist
1233 if ( tuple
.replacee
== 0 )
1235 // <rdar://problem/7937695> verify that replacement is in this image
1236 if ( this->containsAddress((void*)tuple
.replacement
) ) {
1237 // chain to any existing interpositions
1238 for (std::vector
<InterposeTuple
>::iterator it
=fgInterposingTuples
.begin(); it
!= fgInterposingTuples
.end(); it
++) {
1239 if ( it
->replacee
== tuple
.replacee
) {
1240 tuple
.replacee
= it
->replacement
;
1243 ImageLoader::fgInterposingTuples
.push_back(tuple
);
1251 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
1255 uint32_t ImageLoaderMachO::sdkVersion(const mach_header
* mh
)
1257 const uint32_t cmd_count
= mh
->ncmds
;
1258 const struct load_command
* const cmds
= (struct load_command
*)(((char*)mh
) + sizeof(macho_header
));
1259 const struct load_command
* cmd
= cmds
;
1260 const struct version_min_command
* versCmd
;
1261 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
1262 switch ( cmd
->cmd
) {
1263 case LC_VERSION_MIN_MACOSX
:
1264 case LC_VERSION_MIN_IPHONEOS
:
1265 case LC_VERSION_MIN_TVOS
:
1266 case LC_VERSION_MIN_WATCHOS
:
1267 versCmd
= (version_min_command
*)cmd
;
1268 return versCmd
->sdk
;
1270 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
1275 uint32_t ImageLoaderMachO::sdkVersion() const
1277 return ImageLoaderMachO::sdkVersion(machHeader());
1280 uint32_t ImageLoaderMachO::minOSVersion(const mach_header
* mh
)
1282 const uint32_t cmd_count
= mh
->ncmds
;
1283 const struct load_command
* const cmds
= (struct load_command
*)(((char*)mh
) + sizeof(macho_header
));
1284 const struct load_command
* cmd
= cmds
;
1285 const struct version_min_command
* versCmd
;
1286 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
1287 switch ( cmd
->cmd
) {
1288 case LC_VERSION_MIN_MACOSX
:
1289 case LC_VERSION_MIN_IPHONEOS
:
1290 case LC_VERSION_MIN_TVOS
:
1291 case LC_VERSION_MIN_WATCHOS
:
1292 versCmd
= (version_min_command
*)cmd
;
1293 return versCmd
->version
;
1295 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
1300 uint32_t ImageLoaderMachO::minOSVersion() const
1302 return ImageLoaderMachO::minOSVersion(machHeader());
1306 void* ImageLoaderMachO::getThreadPC() const
1308 const uint32_t cmd_count
= ((macho_header
*)fMachOData
)->ncmds
;
1309 const struct load_command
* const cmds
= (struct load_command
*)&fMachOData
[sizeof(macho_header
)];
1310 const struct load_command
* cmd
= cmds
;
1311 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
1312 if ( cmd
->cmd
== LC_MAIN
) {
1313 entry_point_command
* mainCmd
= (entry_point_command
*)cmd
;
1314 void* entry
= (void*)(mainCmd
->entryoff
+ (char*)fMachOData
);
1315 // <rdar://problem/8543820&9228031> verify entry point is in image
1316 if ( this->containsAddress(entry
) )
1319 throw "LC_MAIN entryoff is out of range";
1321 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
1327 void* ImageLoaderMachO::getMain() const
1329 const uint32_t cmd_count
= ((macho_header
*)fMachOData
)->ncmds
;
1330 const struct load_command
* const cmds
= (struct load_command
*)&fMachOData
[sizeof(macho_header
)];
1331 const struct load_command
* cmd
= cmds
;
1332 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
1337 const i386_thread_state_t
* registers
= (i386_thread_state_t
*)(((char*)cmd
) + 16);
1338 void* entry
= (void*)(registers
->eip
+ fSlide
);
1340 const x86_thread_state64_t
* registers
= (x86_thread_state64_t
*)(((char*)cmd
) + 16);
1341 void* entry
= (void*)(registers
->rip
+ fSlide
);
1343 const arm_thread_state_t
* registers
= (arm_thread_state_t
*)(((char*)cmd
) + 16);
1344 void* entry
= (void*)(registers
->__pc
+ fSlide
);
1346 const arm_thread_state64_t
* registers
= (arm_thread_state64_t
*)(((char*)cmd
) + 16);
1347 void* entry
= (void*)(registers
->__pc
+ fSlide
);
1349 #warning need processor specific code
1351 // <rdar://problem/8543820&9228031> verify entry point is in image
1352 if ( this->containsAddress(entry
) ) {
1358 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
1360 throw "no valid entry point";
1363 bool ImageLoaderMachO::needsAddedLibSystemDepency(unsigned int libCount
, const macho_header
* mh
)
1365 // <rdar://problem/6357561> ensure that every image depends on something which depends on libSystem
1369 // <rdar://problem/6409800> dyld implicit-libSystem breaks valgrind
1370 if ( mh
->filetype
== MH_EXECUTE
)
1373 bool isNonOSdylib
= false;
1374 const uint32_t cmd_count
= mh
->ncmds
;
1375 const struct load_command
* const cmds
= (struct load_command
*)((uint8_t*)mh
+sizeof(macho_header
));
1376 const struct load_command
* cmd
= cmds
;
1377 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
1380 case LC_LOAD_WEAK_DYLIB
:
1381 case LC_REEXPORT_DYLIB
:
1382 case LC_LOAD_UPWARD_DYLIB
:
1386 const dylib_command
* dylibID
= (dylib_command
*)cmd
;
1387 const char* installPath
= (char*)cmd
+ dylibID
->dylib
.name
.offset
;
1388 // It is OK for OS dylibs (libSystem or libmath or Rosetta shims) to have no dependents
1389 // but all other dylibs must depend on libSystem for initialization to initialize libSystem first
1390 // <rdar://problem/6497528> rosetta circular dependency spew
1391 isNonOSdylib
= ( (strncmp(installPath
, "/usr/lib/", 9) != 0) && (strncmp(installPath
, "/usr/libexec/oah/Shims", 9) != 0) );
1395 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
1397 return isNonOSdylib
;
1401 void ImageLoaderMachO::doGetDependentLibraries(DependentLibraryInfo libs
[])
1403 if ( needsAddedLibSystemDepency(libraryCount(), (macho_header
*)fMachOData
) ) {
1404 DependentLibraryInfo
* lib
= &libs
[0];
1405 lib
->name
= LIBSYSTEM_DYLIB_PATH
;
1406 lib
->info
.checksum
= 0;
1407 lib
->info
.minVersion
= 0;
1408 lib
->info
.maxVersion
= 0;
1409 lib
->required
= false;
1410 lib
->reExported
= false;
1411 lib
->upward
= false;
1415 const uint32_t cmd_count
= ((macho_header
*)fMachOData
)->ncmds
;
1416 const struct load_command
* const cmds
= (struct load_command
*)&fMachOData
[sizeof(macho_header
)];
1417 const struct load_command
* cmd
= cmds
;
1418 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
1421 case LC_LOAD_WEAK_DYLIB
:
1422 case LC_REEXPORT_DYLIB
:
1423 case LC_LOAD_UPWARD_DYLIB
:
1425 const struct dylib_command
* dylib
= (struct dylib_command
*)cmd
;
1426 DependentLibraryInfo
* lib
= &libs
[index
++];
1427 lib
->name
= (char*)cmd
+ dylib
->dylib
.name
.offset
;
1428 //lib->name = strdup((char*)cmd + dylib->dylib.name.offset);
1429 lib
->info
.checksum
= dylib
->dylib
.timestamp
;
1430 lib
->info
.minVersion
= dylib
->dylib
.compatibility_version
;
1431 lib
->info
.maxVersion
= dylib
->dylib
.current_version
;
1432 lib
->required
= (cmd
->cmd
!= LC_LOAD_WEAK_DYLIB
);
1433 lib
->reExported
= (cmd
->cmd
== LC_REEXPORT_DYLIB
);
1434 lib
->upward
= (cmd
->cmd
== LC_LOAD_UPWARD_DYLIB
);
1438 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
1443 ImageLoader::LibraryInfo
ImageLoaderMachO::doGetLibraryInfo(const LibraryInfo
&)
1446 if ( fDylibIDOffset
!= 0 ) {
1447 const dylib_command
* dylibID
= (dylib_command
*)(&fMachOData
[fDylibIDOffset
]);
1448 info
.minVersion
= dylibID
->dylib
.compatibility_version
;
1449 info
.maxVersion
= dylibID
->dylib
.current_version
;
1450 info
.checksum
= dylibID
->dylib
.timestamp
;
1453 info
.minVersion
= 0;
1454 info
.maxVersion
= 0;
1460 void ImageLoaderMachO::getRPaths(const LinkContext
& context
, std::vector
<const char*>& paths
) const
1462 const uint32_t cmd_count
= ((macho_header
*)fMachOData
)->ncmds
;
1463 const struct load_command
* const cmds
= (struct load_command
*)&fMachOData
[sizeof(macho_header
)];
1464 const struct load_command
* cmd
= cmds
;
1465 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
1468 const char* pathToAdd
= NULL
;
1469 const char* path
= (char*)cmd
+ ((struct rpath_command
*)cmd
)->path
.offset
;
1470 if ( (strncmp(path
, "@loader_path", 12) == 0) && ((path
[12] == '/') || (path
[12] == '\0')) ) {
1471 #if __MAC_OS_X_VERSION_MIN_REQUIRED
1472 if ( context
.processIsRestricted
&& (context
.mainExecutable
== this) ) {
1473 dyld::warn("LC_RPATH %s in %s being ignored in restricted program because of @loader_path\n", path
, this->getPath());
1477 char resolvedPath
[PATH_MAX
];
1478 if ( realpath(this->getPath(), resolvedPath
) != NULL
) {
1479 char newRealPath
[strlen(resolvedPath
) + strlen(path
)];
1480 strcpy(newRealPath
, resolvedPath
);
1481 char* addPoint
= strrchr(newRealPath
,'/');
1482 if ( addPoint
!= NULL
) {
1483 strcpy(addPoint
, &path
[12]);
1484 pathToAdd
= strdup(newRealPath
);
1488 else if ( (strncmp(path
, "@executable_path", 16) == 0) && ((path
[16] == '/') || (path
[16] == '\0')) ) {
1489 #if __MAC_OS_X_VERSION_MIN_REQUIRED
1490 if ( context
.processIsRestricted
) {
1491 dyld::warn("LC_RPATH %s in %s being ignored in restricted program because of @executable_path\n", path
, this->getPath());
1495 char resolvedPath
[PATH_MAX
];
1496 if ( realpath(context
.mainExecutable
->getPath(), resolvedPath
) != NULL
) {
1497 char newRealPath
[strlen(resolvedPath
) + strlen(path
)];
1498 strcpy(newRealPath
, resolvedPath
);
1499 char* addPoint
= strrchr(newRealPath
,'/');
1500 if ( addPoint
!= NULL
) {
1501 strcpy(addPoint
, &path
[16]);
1502 pathToAdd
= strdup(newRealPath
);
1506 #if __MAC_OS_X_VERSION_MIN_REQUIRED
1507 else if ( (path
[0] != '/') && context
.processIsRestricted
) {
1508 dyld::warn("LC_RPATH %s in %s being ignored in restricted program because it is a relative path\n", path
, this->getPath());
1512 #if SUPPORT_ROOT_PATH
1513 else if ( (path
[0] == '/') && (context
.rootPaths
!= NULL
) ) {
1514 // <rdar://problem/5869973> DYLD_ROOT_PATH should apply to LC_RPATH rpaths
1515 // DYLD_ROOT_PATH can be a list of paths, but at this point we can only support one, so use first combination that exists
1517 for(const char** rp
= context
.rootPaths
; *rp
!= NULL
; ++rp
) {
1518 char newPath
[PATH_MAX
];
1519 strlcpy(newPath
, *rp
, PATH_MAX
);
1520 strlcat(newPath
, path
, PATH_MAX
);
1521 struct stat stat_buf
;
1522 if ( stat(newPath
, &stat_buf
) != -1 ) {
1523 //dyld::log("combined DYLD_ROOT_PATH and LC_RPATH: %s\n", newPath);
1524 pathToAdd
= strdup(newPath
);
1530 // make copy so that all elements of 'paths' can be freed
1531 pathToAdd
= strdup(path
);
1536 // make copy so that all elements of 'paths' can be freed
1537 pathToAdd
= strdup(path
);
1539 if ( pathToAdd
!= NULL
)
1540 paths
.push_back(pathToAdd
);
1543 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
1548 bool ImageLoaderMachO::getUUID(uuid_t uuid
) const
1550 const uint32_t cmd_count
= ((macho_header
*)fMachOData
)->ncmds
;
1551 const struct load_command
* const cmds
= (struct load_command
*)&fMachOData
[sizeof(macho_header
)];
1552 const struct load_command
* cmd
= cmds
;
1553 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
1556 uuid_command
* uc
= (uuid_command
*)cmd
;
1557 memcpy(uuid
, uc
->uuid
, 16);
1560 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
1566 void ImageLoaderMachO::doRebase(const LinkContext
& context
)
1568 // <rdar://problem/25329861> Delay calling setNeverUnload() until we know this is not for dlopen_preflight()
1569 if ( fRetainForObjC
)
1570 this->setNeverUnload();
1572 // if prebound and loaded at prebound address, then no need to rebase
1573 if ( this->usablePrebinding(context
) ) {
1574 // skip rebasing because prebinding is valid
1575 ++fgImagesWithUsedPrebinding
; // bump totals for statistics
1579 // print why prebinding was not used
1580 if ( context
.verbosePrebinding
) {
1581 if ( !this->isPrebindable() ) {
1582 dyld::log("dyld: image not prebound, so could not use prebinding in %s\n", this->getPath());
1584 else if ( fSlide
!= 0 ) {
1585 dyld::log("dyld: image slid, so could not use prebinding in %s\n", this->getPath());
1587 else if ( !this->allDependentLibrariesAsWhenPreBound() ) {
1588 dyld::log("dyld: dependent libraries changed, so could not use prebinding in %s\n", this->getPath());
1590 else if ( !this->usesTwoLevelNameSpace() ){
1591 dyld::log("dyld: image uses flat-namespace so, parts of prebinding ignored %s\n", this->getPath());
1594 dyld::log("dyld: environment variable disabled use of prebinding in %s\n", this->getPath());
1598 //dyld::log("slide=0x%08lX for %s\n", slide, this->getPath());
1600 #if PREBOUND_IMAGE_SUPPORT
1601 // if prebound and we got here, then prebinding is not valid, so reset all lazy pointers
1602 // if this image is in the shared cache, do not reset, they will be bound in doBind()
1603 if ( this->isPrebindable() && !fInSharedCache
)
1604 this->resetPreboundLazyPointers(context
);
1607 // if loaded at preferred address, no rebasing necessary
1608 if ( this->fSlide
== 0 )
1611 #if TEXT_RELOC_SUPPORT
1612 // if there are __TEXT fixups, temporarily make __TEXT writable
1613 if ( fTextSegmentRebases
)
1614 this->makeTextSegmentWritable(context
, true);
1617 // do actual rebasing
1618 this->rebase(context
, fSlide
);
1620 #if TEXT_RELOC_SUPPORT
1621 // if there were __TEXT fixups, restore write protection
1622 if ( fTextSegmentRebases
)
1623 this->makeTextSegmentWritable(context
, false);
1628 #if TEXT_RELOC_SUPPORT
1629 void ImageLoaderMachO::makeTextSegmentWritable(const LinkContext
& context
, bool writeable
)
1631 for(unsigned int i
=0; i
< fSegmentsCount
; ++i
) {
1632 if ( segExecutable(i
) ) {
1634 segMakeWritable(i
, context
);
1637 #if !__i386__ && !__x86_64__
1638 // some processors require range to be invalidated before it is made executable
1639 sys_icache_invalidate((void*)segActualLoadAddress(i
), segSize(textSegmentIndex
));
1641 segProtect(i
, context
);
1649 const ImageLoader::Symbol
* ImageLoaderMachO::findExportedSymbol(const char* name
, bool searchReExports
, const char* thisPath
, const ImageLoader
** foundIn
) const
1651 // look in this image first
1652 const ImageLoader::Symbol
* result
= this->findShallowExportedSymbol(name
, foundIn
);
1653 if ( result
!= NULL
)
1656 if ( searchReExports
) {
1657 for(unsigned int i
=0; i
< libraryCount(); ++i
){
1658 if ( libReExported(i
) ) {
1659 ImageLoader
* image
= libImage(i
);
1660 if ( image
!= NULL
) {
1661 const char* reExPath
= libPath(i
);
1662 result
= image
->findExportedSymbol(name
, searchReExports
, reExPath
, foundIn
);
1663 if ( result
!= NULL
)
1676 uintptr_t ImageLoaderMachO::getExportedSymbolAddress(const Symbol
* sym
, const LinkContext
& context
,
1677 const ImageLoader
* requestor
, bool runResolver
, const char* symbolName
) const
1679 return this->getSymbolAddress(sym
, requestor
, context
, runResolver
);
1682 uintptr_t ImageLoaderMachO::getSymbolAddress(const Symbol
* sym
, const ImageLoader
* requestor
,
1683 const LinkContext
& context
, bool runResolver
) const
1685 uintptr_t result
= exportedSymbolAddress(context
, sym
, requestor
, runResolver
);
1686 // check for interposing overrides
1687 result
= interposedAddress(context
, result
, requestor
);
1691 ImageLoader::DefinitionFlags
ImageLoaderMachO::getExportedSymbolInfo(const Symbol
* sym
) const
1693 if ( exportedSymbolIsWeakDefintion(sym
) )
1694 return kWeakDefinition
;
1696 return kNoDefinitionOptions
;
1699 const char* ImageLoaderMachO::getExportedSymbolName(const Symbol
* sym
) const
1701 return exportedSymbolName(sym
);
1704 uint32_t ImageLoaderMachO::getExportedSymbolCount() const
1706 return exportedSymbolCount();
1710 const ImageLoader::Symbol
* ImageLoaderMachO::getIndexedExportedSymbol(uint32_t index
) const
1712 return exportedSymbolIndexed(index
);
1716 uint32_t ImageLoaderMachO::getImportedSymbolCount() const
1718 return importedSymbolCount();
1722 const ImageLoader::Symbol
* ImageLoaderMachO::getIndexedImportedSymbol(uint32_t index
) const
1724 return importedSymbolIndexed(index
);
1728 ImageLoader::ReferenceFlags
ImageLoaderMachO::getImportedSymbolInfo(const ImageLoader::Symbol
* sym
) const
1730 ImageLoader::ReferenceFlags flags
= kNoReferenceOptions
;
1735 const char* ImageLoaderMachO::getImportedSymbolName(const ImageLoader::Symbol
* sym
) const
1737 return importedSymbolName(sym
);
1741 bool ImageLoaderMachO::getSectionContent(const char* segmentName
, const char* sectionName
, void** start
, size_t* length
)
1743 const uint32_t cmd_count
= ((macho_header
*)fMachOData
)->ncmds
;
1744 const struct load_command
* const cmds
= (struct load_command
*)&fMachOData
[sizeof(macho_header
)];
1745 const struct load_command
* cmd
= cmds
;
1746 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
1748 case LC_SEGMENT_COMMAND
:
1750 const struct macho_segment_command
* seg
= (struct macho_segment_command
*)cmd
;
1751 const struct macho_section
* const sectionsStart
= (struct macho_section
*)((char*)seg
+ sizeof(struct macho_segment_command
));
1752 const struct macho_section
* const sectionsEnd
= §ionsStart
[seg
->nsects
];
1753 for (const struct macho_section
* sect
=sectionsStart
; sect
< sectionsEnd
; ++sect
) {
1754 if ( (strcmp(sect
->segname
, segmentName
) == 0) && (strcmp(sect
->sectname
, sectionName
) == 0) ) {
1755 *start
= (uintptr_t*)(sect
->addr
+ fSlide
);
1756 *length
= sect
->size
;
1763 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
1770 void ImageLoaderMachO::getUnwindInfo(dyld_unwind_sections
* info
)
1772 info
->mh
= this->machHeader();
1773 info
->dwarf_section
= 0;
1774 info
->dwarf_section_length
= 0;
1775 info
->compact_unwind_section
= 0;
1776 info
->compact_unwind_section_length
= 0;
1777 if ( fEHFrameSectionOffset
!= 0 ) {
1778 const macho_section
* sect
= (macho_section
*)&fMachOData
[fEHFrameSectionOffset
];
1779 info
->dwarf_section
= (void*)(sect
->addr
+ fSlide
);
1780 info
->dwarf_section_length
= sect
->size
;
1782 if ( fUnwindInfoSectionOffset
!= 0 ) {
1783 const macho_section
* sect
= (macho_section
*)&fMachOData
[fUnwindInfoSectionOffset
];
1784 info
->compact_unwind_section
= (void*)(sect
->addr
+ fSlide
);
1785 info
->compact_unwind_section_length
= sect
->size
;
1789 intptr_t ImageLoaderMachO::computeSlide(const mach_header
* mh
)
1791 const uint32_t cmd_count
= mh
->ncmds
;
1792 const load_command
* const cmds
= (load_command
*)((char*)mh
+ sizeof(macho_header
));
1793 const load_command
* cmd
= cmds
;
1794 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
1795 if ( cmd
->cmd
== LC_SEGMENT_COMMAND
) {
1796 const macho_segment_command
* seg
= (macho_segment_command
*)cmd
;
1797 if ( (seg
->fileoff
== 0) && (seg
->filesize
!= 0) )
1798 return (char*)mh
- (char*)(seg
->vmaddr
);
1800 cmd
= (const load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
1805 bool ImageLoaderMachO::findSection(const mach_header
* mh
, const char* segmentName
, const char* sectionName
, void** sectAddress
, size_t* sectSize
)
1807 const uint32_t cmd_count
= mh
->ncmds
;
1808 const load_command
* const cmds
= (load_command
*)((char*)mh
+ sizeof(macho_header
));
1809 const load_command
* cmd
= cmds
;
1810 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
1812 case LC_SEGMENT_COMMAND
:
1814 const macho_segment_command
* seg
= (macho_segment_command
*)cmd
;
1815 const macho_section
* const sectionsStart
= (macho_section
*)((char*)seg
+ sizeof(macho_segment_command
));
1816 const macho_section
* const sectionsEnd
= §ionsStart
[seg
->nsects
];
1817 for (const macho_section
* sect
=sectionsStart
; sect
< sectionsEnd
; ++sect
) {
1818 if ( (strcmp(sect
->segname
, segmentName
) == 0) && (strcmp(sect
->sectname
, sectionName
) == 0) ) {
1819 *sectAddress
= (void*)(sect
->addr
+ computeSlide(mh
));
1820 *sectSize
= sect
->size
;
1827 cmd
= (const load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
1833 bool ImageLoaderMachO::findSection(const void* imageInterior
, const char** segmentName
, const char** sectionName
, size_t* sectionOffset
)
1835 const uint32_t cmd_count
= ((macho_header
*)fMachOData
)->ncmds
;
1836 const struct load_command
* const cmds
= (struct load_command
*)&fMachOData
[sizeof(macho_header
)];
1837 const struct load_command
* cmd
= cmds
;
1838 const uintptr_t unslidInteriorAddress
= (uintptr_t)imageInterior
- this->getSlide();
1839 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
1841 case LC_SEGMENT_COMMAND
:
1843 const struct macho_segment_command
* seg
= (struct macho_segment_command
*)cmd
;
1844 if ( (unslidInteriorAddress
>= seg
->vmaddr
) && (unslidInteriorAddress
< (seg
->vmaddr
+seg
->vmsize
)) ) {
1845 const struct macho_section
* const sectionsStart
= (struct macho_section
*)((char*)seg
+ sizeof(struct macho_segment_command
));
1846 const struct macho_section
* const sectionsEnd
= §ionsStart
[seg
->nsects
];
1847 for (const struct macho_section
* sect
=sectionsStart
; sect
< sectionsEnd
; ++sect
) {
1848 if ((sect
->addr
<= unslidInteriorAddress
) && (unslidInteriorAddress
< (sect
->addr
+sect
->size
))) {
1849 if ( segmentName
!= NULL
)
1850 *segmentName
= sect
->segname
;
1851 if ( sectionName
!= NULL
)
1852 *sectionName
= sect
->sectname
;
1853 if ( sectionOffset
!= NULL
)
1854 *sectionOffset
= unslidInteriorAddress
- sect
->addr
;
1862 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
1867 const char* ImageLoaderMachO::libPath(unsigned int index
) const
1869 const uint32_t cmd_count
= ((macho_header
*)fMachOData
)->ncmds
;
1870 const struct load_command
* const cmds
= (struct load_command
*)&fMachOData
[sizeof(macho_header
)];
1871 const struct load_command
* cmd
= cmds
;
1873 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
1874 switch ( cmd
->cmd
) {
1876 case LC_LOAD_WEAK_DYLIB
:
1877 case LC_REEXPORT_DYLIB
:
1878 case LC_LOAD_UPWARD_DYLIB
:
1879 if ( index
== count
) {
1880 const struct dylib_command
* dylibCmd
= (struct dylib_command
*)cmd
;
1881 return (char*)cmd
+ dylibCmd
->dylib
.name
.offset
;
1886 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
1889 // <rdar://problem/24256354> if image linked with nothing and we implicitly added libSystem.dylib, return that
1890 if ( needsAddedLibSystemDepency(libraryCount(), (macho_header
*)fMachOData
) ) {
1891 return LIBSYSTEM_DYLIB_PATH
;
1898 void __attribute__((noreturn
)) ImageLoaderMachO::throwSymbolNotFound(const LinkContext
& context
, const char* symbol
,
1899 const char* referencedFrom
, const char* fromVersMismatch
,
1900 const char* expectedIn
)
1902 // record values for possible use by CrashReporter or Finder
1903 (*context
.setErrorStrings
)(DYLD_EXIT_REASON_SYMBOL_MISSING
, referencedFrom
, expectedIn
, symbol
);
1904 dyld::throwf("Symbol not found: %s\n Referenced from: %s%s\n Expected in: %s\n",
1905 symbol
, referencedFrom
, fromVersMismatch
, expectedIn
);
1908 const mach_header
* ImageLoaderMachO::machHeader() const
1910 return (mach_header
*)fMachOData
;
1913 uintptr_t ImageLoaderMachO::getSlide() const
1918 // hmm. maybe this should be up in ImageLoader??
1919 const void* ImageLoaderMachO::getEnd() const
1921 uintptr_t lastAddress
= 0;
1922 for(unsigned int i
=0; i
< fSegmentsCount
; ++i
) {
1923 uintptr_t segEnd
= segActualEndAddress(i
);
1924 if ( strcmp(segName(i
), "__UNIXSTACK") != 0 ) {
1925 if ( segEnd
> lastAddress
)
1926 lastAddress
= segEnd
;
1929 return (const void*)lastAddress
;
1933 uintptr_t ImageLoaderMachO::bindLocation(const LinkContext
& context
, uintptr_t location
, uintptr_t value
,
1934 uint8_t type
, const char* symbolName
,
1935 intptr_t addend
, const char* inPath
, const char* toPath
, const char* msg
)
1938 if ( context
.verboseBind
) {
1940 dyld::log("dyld: %sbind: %s:0x%08lX = %s:%s, *0x%08lX = 0x%08lX + %ld\n",
1941 msg
, shortName(inPath
), (uintptr_t)location
,
1942 ((toPath
!= NULL
) ? shortName(toPath
) : "<missing weak_import>"),
1943 symbolName
, (uintptr_t)location
, value
, addend
);
1945 dyld::log("dyld: %sbind: %s:0x%08lX = %s:%s, *0x%08lX = 0x%08lX\n",
1946 msg
, shortName(inPath
), (uintptr_t)location
,
1947 ((toPath
!= NULL
) ? shortName(toPath
) : "<missing weak_import>"),
1948 symbolName
, (uintptr_t)location
, value
);
1951 // dyld::logBindings("%s: %s\n", targetImage->getShortName(), symbolName);
1955 uintptr_t* locationToFix
= (uintptr_t*)location
;
1957 uintptr_t newValue
= value
+addend
;
1960 case BIND_TYPE_POINTER
:
1961 // test first so we don't needless dirty pages
1962 if ( *locationToFix
!= newValue
)
1963 *locationToFix
= newValue
;
1965 case BIND_TYPE_TEXT_ABSOLUTE32
:
1966 loc32
= (uint32_t*)locationToFix
;
1967 value32
= (uint32_t)newValue
;
1968 if ( *loc32
!= value32
)
1971 case BIND_TYPE_TEXT_PCREL32
:
1972 loc32
= (uint32_t*)locationToFix
;
1973 value32
= (uint32_t)(newValue
- (((uintptr_t)locationToFix
) + 4));
1974 if ( *loc32
!= value32
)
1978 dyld::throwf("bad bind type %d", type
);
1981 // update statistics
1982 ++fgTotalBindFixups
;
1991 #if SUPPORT_OLD_CRT_INITIALIZATION
1992 // first 16 bytes of "start" in crt1.o
1994 static uint8_t sStandardEntryPointInstructions
[16] = { 0x6a, 0x00, 0x89, 0xe5, 0x83, 0xe4, 0xf0, 0x83, 0xec, 0x10, 0x8b, 0x5d, 0x04, 0x89, 0x5c, 0x24 };
1999 void* dyldLazyBinder
; // filled in at launch by dyld to point into dyld to &stub_binding_helper
2000 void* dyldFuncLookup
; // filled in at launch by dyld to point into dyld to &_dyld_func_lookup
2001 // the following only exist in main executables built for 10.5 or later
2005 // These are defined in dyldStartup.s
2006 extern "C" void stub_binding_helper();
2009 void ImageLoaderMachO::setupLazyPointerHandler(const LinkContext
& context
)
2011 const macho_header
* mh
= (macho_header
*)fMachOData
;
2012 const uint32_t cmd_count
= mh
->ncmds
;
2013 const struct load_command
* const cmds
= (struct load_command
*)&fMachOData
[sizeof(macho_header
)];
2014 const struct load_command
* cmd
;
2015 // There used to be some optimizations to skip this section scan, but we need to handle the
2016 // __dyld section in libdyld.dylib, so everything needs to be scanned for now.
2017 // <rdar://problem/10910062> CrashTracer: 1,295 crashes in bash at bash: getenv
2020 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
2021 if ( cmd
->cmd
== LC_SEGMENT_COMMAND
) {
2022 const struct macho_segment_command
* seg
= (struct macho_segment_command
*)cmd
;
2023 if ( strncmp(seg
->segname
, "__DATA", 6) == 0 ) {
2024 const struct macho_section
* const sectionsStart
= (struct macho_section
*)((char*)seg
+ sizeof(struct macho_segment_command
));
2025 const struct macho_section
* const sectionsEnd
= §ionsStart
[seg
->nsects
];
2026 for (const struct macho_section
* sect
=sectionsStart
; sect
< sectionsEnd
; ++sect
) {
2027 if ( strcmp(sect
->sectname
, "__dyld" ) == 0 ) {
2028 struct DATAdyld
* dd
= (struct DATAdyld
*)(sect
->addr
+ fSlide
);
2029 #if !__arm64__ && !__ARM_ARCH_7K__
2030 if ( sect
->size
> offsetof(DATAdyld
, dyldLazyBinder
) ) {
2031 if ( dd
->dyldLazyBinder
!= (void*)&stub_binding_helper
)
2032 dd
->dyldLazyBinder
= (void*)&stub_binding_helper
;
2034 #endif // !__arm64__
2035 if ( sect
->size
> offsetof(DATAdyld
, dyldFuncLookup
) ) {
2036 if ( dd
->dyldFuncLookup
!= (void*)&_dyld_func_lookup
)
2037 dd
->dyldFuncLookup
= (void*)&_dyld_func_lookup
;
2039 if ( mh
->filetype
== MH_EXECUTE
) {
2040 // there are two ways to get the program variables
2041 if ( (sect
->size
> offsetof(DATAdyld
, vars
)) && (dd
->vars
.mh
== mh
) ) {
2042 // some really old binaries have space for vars, but it is zero filled
2043 // main executable has 10.5 style __dyld section that has program variable pointers
2044 context
.setNewProgramVars(dd
->vars
);
2047 // main executable is pre-10.5 and requires the symbols names to be looked up
2048 this->lookupProgramVars(context
);
2049 #if SUPPORT_OLD_CRT_INITIALIZATION
2050 // If the first 16 bytes of the entry point's instructions do not
2051 // match what crt1.o supplies, then the program has a custom entry point.
2052 // This means it might be doing something that needs to be executed before
2053 // initializers are run.
2054 if ( memcmp(this->getMain(), sStandardEntryPointInstructions
, 16) != 0 ) {
2055 if ( context
.verboseInit
)
2056 dyld::log("dyld: program uses non-standard entry point so delaying running of initializers\n");
2057 context
.setRunInitialzersOldWay();
2062 else if ( mh
->filetype
== MH_DYLIB
) {
2063 const char* installPath
= this->getInstallPath();
2064 if ( (installPath
!= NULL
) && (strncmp(installPath
, "/usr/lib/", 9) == 0) ) {
2065 if ( sect
->size
> offsetof(DATAdyld
, vars
) ) {
2066 // use ProgramVars from libdyld.dylib but tweak mh field to correct value
2067 dd
->vars
.mh
= context
.mainExecutable
->machHeader();
2068 context
.setNewProgramVars(dd
->vars
);
2073 else if ( (strcmp(sect
->sectname
, "__program_vars" ) == 0) && (mh
->filetype
== MH_EXECUTE
) ) {
2074 // this is a Mac OS X 10.6 or later main executable
2075 struct ProgramVars
* pv
= (struct ProgramVars
*)(sect
->addr
+ fSlide
);
2076 context
.setNewProgramVars(*pv
);
2081 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
2087 void ImageLoaderMachO::lookupProgramVars(const LinkContext
& context
) const
2089 ProgramVars vars
= context
.programVars
;
2090 const ImageLoader::Symbol
* sym
;
2092 // get mach header directly
2093 vars
.mh
= (macho_header
*)fMachOData
;
2096 sym
= this->findShallowExportedSymbol("_NXArgc", NULL
);
2098 vars
.NXArgcPtr
= (int*)this->getExportedSymbolAddress(sym
, context
, this, false, NULL
);
2101 sym
= this->findShallowExportedSymbol("_NXArgv", NULL
);
2103 vars
.NXArgvPtr
= (const char***)this->getExportedSymbolAddress(sym
, context
, this, false, NULL
);
2106 sym
= this->findShallowExportedSymbol("_environ", NULL
);
2108 vars
.environPtr
= (const char***)this->getExportedSymbolAddress(sym
, context
, this, false, NULL
);
2110 // lookup __progname
2111 sym
= this->findShallowExportedSymbol("___progname", NULL
);
2113 vars
.__prognamePtr
= (const char**)this->getExportedSymbolAddress(sym
, context
, this, false, NULL
);
2115 context
.setNewProgramVars(vars
);
2119 bool ImageLoaderMachO::usablePrebinding(const LinkContext
& context
) const
2121 // if prebound and loaded at prebound address, and all libraries are same as when this was prebound, then no need to bind
2122 if ( ((this->isPrebindable() && (this->getSlide() == 0)) || fInSharedCache
)
2123 && this->usesTwoLevelNameSpace()
2124 && this->allDependentLibrariesAsWhenPreBound() ) {
2125 // allow environment variables to disable prebinding
2126 if ( context
.bindFlat
)
2128 switch ( context
.prebindUsage
) {
2129 case kUseAllPrebinding
:
2131 case kUseSplitSegPrebinding
:
2132 return this->fIsSplitSeg
;
2133 case kUseAllButAppPredbinding
:
2134 return (this != context
.mainExecutable
);
2135 case kUseNoPrebinding
:
2143 void ImageLoaderMachO::doImageInit(const LinkContext
& context
)
2145 if ( fHasDashInit
) {
2146 const uint32_t cmd_count
= ((macho_header
*)fMachOData
)->ncmds
;
2147 const struct load_command
* const cmds
= (struct load_command
*)&fMachOData
[sizeof(macho_header
)];
2148 const struct load_command
* cmd
= cmds
;
2149 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
2151 case LC_ROUTINES_COMMAND
:
2152 Initializer func
= (Initializer
)(((struct macho_routines_command
*)cmd
)->init_address
+ fSlide
);
2153 // <rdar://problem/8543820&9228031> verify initializers are in image
2154 if ( ! this->containsAddress((void*)func
) ) {
2155 dyld::throwf("initializer function %p not in mapped image for %s\n", func
, this->getPath());
2157 if ( ! dyld::gProcessInfo
->libSystemInitialized
) {
2158 // <rdar://problem/17973316> libSystem initializer must run first
2159 dyld::throwf("-init function in image (%s) that does not link with libSystem.dylib\n", this->getPath());
2161 if ( context
.verboseInit
)
2162 dyld::log("dyld: calling -init function %p in %s\n", func
, this->getPath());
2163 func(context
.argc
, context
.argv
, context
.envp
, context
.apple
, &context
.programVars
);
2166 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
2171 void ImageLoaderMachO::doModInitFunctions(const LinkContext
& context
)
2173 if ( fHasInitializers
) {
2174 const uint32_t cmd_count
= ((macho_header
*)fMachOData
)->ncmds
;
2175 const struct load_command
* const cmds
= (struct load_command
*)&fMachOData
[sizeof(macho_header
)];
2176 const struct load_command
* cmd
= cmds
;
2177 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
2178 if ( cmd
->cmd
== LC_SEGMENT_COMMAND
) {
2179 const struct macho_segment_command
* seg
= (struct macho_segment_command
*)cmd
;
2180 const struct macho_section
* const sectionsStart
= (struct macho_section
*)((char*)seg
+ sizeof(struct macho_segment_command
));
2181 const struct macho_section
* const sectionsEnd
= §ionsStart
[seg
->nsects
];
2182 for (const struct macho_section
* sect
=sectionsStart
; sect
< sectionsEnd
; ++sect
) {
2183 const uint8_t type
= sect
->flags
& SECTION_TYPE
;
2184 if ( type
== S_MOD_INIT_FUNC_POINTERS
) {
2185 Initializer
* inits
= (Initializer
*)(sect
->addr
+ fSlide
);
2186 const size_t count
= sect
->size
/ sizeof(uintptr_t);
2187 // <rdar://problem/23929217> Ensure __mod_init_func section is within segment
2188 if ( (sect
->addr
< seg
->vmaddr
) || (sect
->addr
+sect
->size
> seg
->vmaddr
+seg
->vmsize
) || (sect
->addr
+sect
->size
< sect
->addr
) )
2189 dyld::throwf("__mod_init_funcs section has malformed address range for %s\n", this->getPath());
2190 for (size_t j
=0; j
< count
; ++j
) {
2191 Initializer func
= inits
[j
];
2192 // <rdar://problem/8543820&9228031> verify initializers are in image
2193 if ( ! this->containsAddress((void*)func
) ) {
2194 dyld::throwf("initializer function %p not in mapped image for %s\n", func
, this->getPath());
2196 if ( ! dyld::gProcessInfo
->libSystemInitialized
) {
2197 // <rdar://problem/17973316> libSystem initializer must run first
2198 const char* installPath
= getInstallPath();
2199 if ( (installPath
== NULL
) || (strcmp(installPath
, LIBSYSTEM_DYLIB_PATH
) != 0) )
2200 dyld::throwf("initializer in image (%s) that does not link with libSystem.dylib\n", this->getPath());
2202 if ( context
.verboseInit
)
2203 dyld::log("dyld: calling initializer function %p in %s\n", func
, this->getPath());
2204 bool haveLibSystemHelpersBefore
= (dyld::gLibSystemHelpers
!= NULL
);
2205 func(context
.argc
, context
.argv
, context
.envp
, context
.apple
, &context
.programVars
);
2206 bool haveLibSystemHelpersAfter
= (dyld::gLibSystemHelpers
!= NULL
);
2207 if ( !haveLibSystemHelpersBefore
&& haveLibSystemHelpersAfter
) {
2208 // now safe to use malloc() and other calls in libSystem.dylib
2209 dyld::gProcessInfo
->libSystemInitialized
= true;
2215 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
2222 void ImageLoaderMachO::doGetDOFSections(const LinkContext
& context
, std::vector
<ImageLoader::DOFInfo
>& dofs
)
2224 if ( fHasDOFSections
) {
2225 // walk load commands (mapped in at start of __TEXT segment)
2226 const uint32_t cmd_count
= ((macho_header
*)fMachOData
)->ncmds
;
2227 const struct load_command
* const cmds
= (struct load_command
*)&fMachOData
[sizeof(macho_header
)];
2228 const struct load_command
* cmd
= cmds
;
2229 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
2231 case LC_SEGMENT_COMMAND
:
2233 const struct macho_segment_command
* seg
= (struct macho_segment_command
*)cmd
;
2234 const struct macho_section
* const sectionsStart
= (struct macho_section
*)((char*)seg
+ sizeof(struct macho_segment_command
));
2235 const struct macho_section
* const sectionsEnd
= §ionsStart
[seg
->nsects
];
2236 for (const struct macho_section
* sect
=sectionsStart
; sect
< sectionsEnd
; ++sect
) {
2237 if ( (sect
->flags
& SECTION_TYPE
) == S_DTRACE_DOF
) {
2238 // <rdar://problem/23929217> Ensure section is within segment
2239 if ( (sect
->addr
< seg
->vmaddr
) || (sect
->addr
+sect
->size
> seg
->vmaddr
+seg
->vmsize
) || (sect
->addr
+sect
->size
< sect
->addr
) )
2240 dyld::throwf("DOF section has malformed address range for %s\n", this->getPath());
2241 ImageLoader::DOFInfo info
;
2242 info
.dof
= (void*)(sect
->addr
+ fSlide
);
2243 info
.imageHeader
= this->machHeader();
2244 info
.imageShortName
= this->getShortName();
2245 dofs
.push_back(info
);
2251 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
2257 bool ImageLoaderMachO::doInitialization(const LinkContext
& context
)
2259 CRSetCrashLogMessage2(this->getPath());
2261 // mach-o has -init and static initializers
2262 doImageInit(context
);
2263 doModInitFunctions(context
);
2265 CRSetCrashLogMessage2(NULL
);
2267 return (fHasDashInit
|| fHasInitializers
);
2270 bool ImageLoaderMachO::needsInitialization()
2272 return ( fHasDashInit
|| fHasInitializers
);
2276 bool ImageLoaderMachO::needsTermination()
2278 return fHasTerminators
;
2282 void ImageLoaderMachO::doTermination(const LinkContext
& context
)
2284 if ( fHasTerminators
) {
2285 const uint32_t cmd_count
= ((macho_header
*)fMachOData
)->ncmds
;
2286 const struct load_command
* const cmds
= (struct load_command
*)&fMachOData
[sizeof(macho_header
)];
2287 const struct load_command
* cmd
= cmds
;
2288 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
2289 if ( cmd
->cmd
== LC_SEGMENT_COMMAND
) {
2290 const struct macho_segment_command
* seg
= (struct macho_segment_command
*)cmd
;
2291 const struct macho_section
* const sectionsStart
= (struct macho_section
*)((char*)seg
+ sizeof(struct macho_segment_command
));
2292 const struct macho_section
* const sectionsEnd
= §ionsStart
[seg
->nsects
];
2293 for (const struct macho_section
* sect
=sectionsStart
; sect
< sectionsEnd
; ++sect
) {
2294 const uint8_t type
= sect
->flags
& SECTION_TYPE
;
2295 if ( type
== S_MOD_TERM_FUNC_POINTERS
) {
2296 // <rdar://problem/23929217> Ensure section is within segment
2297 if ( (sect
->addr
< seg
->vmaddr
) || (sect
->addr
+sect
->size
> seg
->vmaddr
+seg
->vmsize
) || (sect
->addr
+sect
->size
< sect
->addr
) )
2298 dyld::throwf("DOF section has malformed address range for %s\n", this->getPath());
2299 Terminator
* terms
= (Terminator
*)(sect
->addr
+ fSlide
);
2300 const size_t count
= sect
->size
/ sizeof(uintptr_t);
2301 for (size_t j
=count
; j
> 0; --j
) {
2302 Terminator func
= terms
[j
-1];
2303 // <rdar://problem/8543820&9228031> verify terminators are in image
2304 if ( ! this->containsAddress((void*)func
) ) {
2305 dyld::throwf("termination function %p not in mapped image for %s\n", func
, this->getPath());
2307 if ( context
.verboseInit
)
2308 dyld::log("dyld: calling termination function %p in %s\n", func
, this->getPath());
2314 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
2320 void ImageLoaderMachO::printStatisticsDetails(unsigned int imageCount
, const InitializerTimingList
& timingInfo
)
2322 ImageLoader::printStatisticsDetails(imageCount
, timingInfo
);
2323 dyld::log("total symbol trie searches: %d\n", fgSymbolTrieSearchs
);
2324 dyld::log("total symbol table binary searches: %d\n", fgSymbolTableBinarySearchs
);
2325 dyld::log("total images defining weak symbols: %u\n", fgImagesHasWeakDefinitions
);
2326 dyld::log("total images using weak symbols: %u\n", fgImagesRequiringCoalescing
);
2330 intptr_t ImageLoaderMachO::assignSegmentAddresses(const LinkContext
& context
)
2332 // preflight and calculate slide if needed
2333 const bool inPIE
= (fgNextPIEDylibAddress
!= 0);
2335 if ( this->segmentsCanSlide() && this->segmentsMustSlideTogether() ) {
2336 bool needsToSlide
= false;
2337 bool imageHasPreferredLoadAddress
= segHasPreferredLoadAddress(0);
2338 uintptr_t lowAddr
= (unsigned long)(-1);
2339 uintptr_t highAddr
= 0;
2340 for(unsigned int i
=0, e
=segmentCount(); i
< e
; ++i
) {
2341 const uintptr_t segLow
= segPreferredLoadAddress(i
);
2342 const uintptr_t segHigh
= dyld_page_round(segLow
+ segSize(i
));
2343 if ( segLow
< highAddr
) {
2344 if ( dyld_page_size
> 4096 )
2345 dyld::throwf("can't map segments into 16KB pages");
2347 dyld::throwf("overlapping segments");
2349 if ( segLow
< lowAddr
)
2351 if ( segHigh
> highAddr
)
2354 if ( needsToSlide
|| !imageHasPreferredLoadAddress
|| inPIE
|| !reserveAddressRange(segPreferredLoadAddress(i
), segSize(i
)) )
2355 needsToSlide
= true;
2357 if ( needsToSlide
) {
2358 // find a chunk of address space to hold all segments
2359 uintptr_t addr
= reserveAnAddressRange(highAddr
-lowAddr
, context
);
2360 slide
= addr
- lowAddr
;
2363 else if ( ! this->segmentsCanSlide() ) {
2364 for(unsigned int i
=0, e
=segmentCount(); i
< e
; ++i
) {
2365 if ( (strcmp(segName(i
), "__PAGEZERO") == 0) && (segFileSize(i
) == 0) && (segPreferredLoadAddress(i
) == 0) )
2367 if ( !reserveAddressRange(segPreferredLoadAddress(i
), segSize(i
)) )
2368 dyld::throwf("can't map unslidable segment %s to 0x%lX with size 0x%lX", segName(i
), segPreferredLoadAddress(i
), segSize(i
));
2372 throw "mach-o does not support independently sliding segments";
2378 uintptr_t ImageLoaderMachO::reserveAnAddressRange(size_t length
, const ImageLoader::LinkContext
& context
)
2380 vm_address_t addr
= 0;
2381 vm_size_t size
= length
;
2382 // in PIE programs, load initial dylibs after main executable so they don't have fixed addresses either
2383 if ( fgNextPIEDylibAddress
!= 0 ) {
2384 // add small (0-3 pages) random padding between dylibs
2385 addr
= fgNextPIEDylibAddress
+ (__stack_chk_guard
/fgNextPIEDylibAddress
& (sizeof(long)-1))*dyld_page_size
;
2386 //dyld::log("padding 0x%08llX, guard=0x%08llX\n", (long long)(addr - fgNextPIEDylibAddress), (long long)(__stack_chk_guard));
2387 kern_return_t r
= vm_alloc(&addr
, size
, VM_FLAGS_FIXED
| VM_MAKE_TAG(VM_MEMORY_DYLIB
));
2388 if ( r
== KERN_SUCCESS
) {
2389 fgNextPIEDylibAddress
= addr
+ size
;
2392 fgNextPIEDylibAddress
= 0;
2394 kern_return_t r
= vm_alloc(&addr
, size
, VM_FLAGS_ANYWHERE
| VM_MAKE_TAG(VM_MEMORY_DYLIB
));
2395 if ( r
!= KERN_SUCCESS
)
2396 throw "out of address space";
2401 bool ImageLoaderMachO::reserveAddressRange(uintptr_t start
, size_t length
)
2403 vm_address_t addr
= start
;
2404 vm_size_t size
= length
;
2405 kern_return_t r
= vm_alloc(&addr
, size
, VM_FLAGS_FIXED
| VM_MAKE_TAG(VM_MEMORY_DYLIB
));
2406 if ( r
!= KERN_SUCCESS
)
2413 void ImageLoaderMachO::mapSegments(int fd
, uint64_t offsetInFat
, uint64_t lenInFat
, uint64_t fileLen
, const LinkContext
& context
)
2415 // find address range for image
2416 intptr_t slide
= this->assignSegmentAddresses(context
);
2417 if ( context
.verboseMapping
) {
2418 if ( offsetInFat
!= 0 )
2419 dyld::log("dyld: Mapping %s (slice offset=%llu)\n", this->getPath(), (unsigned long long)offsetInFat
);
2421 dyld::log("dyld: Mapping %s\n", this->getPath());
2423 // map in all segments
2424 for(unsigned int i
=0, e
=segmentCount(); i
< e
; ++i
) {
2425 vm_offset_t fileOffset
= segFileOffset(i
) + offsetInFat
;
2426 vm_size_t size
= segFileSize(i
);
2427 uintptr_t requestedLoadAddress
= segPreferredLoadAddress(i
) + slide
;
2429 if ( !segUnaccessible(i
) ) {
2430 // If has text-relocs, don't set x-bit initially.
2431 // Instead set it later after text-relocs have been done.
2432 if ( segExecutable(i
) && !(segHasRebaseFixUps(i
) && (slide
!= 0)) )
2433 protection
|= PROT_EXEC
;
2434 if ( segReadable(i
) )
2435 protection
|= PROT_READ
;
2436 if ( segWriteable(i
) ) {
2437 protection
|= PROT_WRITE
;
2438 // rdar://problem/22525618 force __LINKEDIT to always be mapped read-only
2439 if ( strcmp(segName(i
), "__LINKEDIT") == 0 )
2440 protection
= PROT_READ
;
2444 // initially map __IMPORT segments R/W so dyld can update them
2445 if ( segIsReadOnlyImport(i
) )
2446 protection
|= PROT_WRITE
;
2448 // wholly zero-fill segments have nothing to mmap() in
2450 if ( (fileOffset
+size
) > fileLen
) {
2451 dyld::throwf("truncated mach-o error: segment %s extends to %llu which is past end of file %llu",
2452 segName(i
), (uint64_t)(fileOffset
+size
), fileLen
);
2454 void* loadAddress
= xmmap((void*)requestedLoadAddress
, size
, protection
, MAP_FIXED
| MAP_PRIVATE
, fd
, fileOffset
);
2455 if ( loadAddress
== ((void*)(-1)) ) {
2456 int mmapErr
= errno
;
2457 if ( mmapErr
== EPERM
) {
2458 if ( dyld::sandboxBlockedMmap(getPath()) )
2459 dyld::throwf("file system sandbox blocked mmap() of '%s'", this->getPath());
2461 dyld::throwf("code signing blocked mmap() of '%s'", this->getPath());
2464 dyld::throwf("mmap() errno=%d at address=0x%08lX, size=0x%08lX segment=%s in Segment::map() mapping %s",
2465 mmapErr
, requestedLoadAddress
, (uintptr_t)size
, segName(i
), getPath());
2469 ++ImageLoader::fgTotalSegmentsMapped
;
2470 ImageLoader::fgTotalBytesMapped
+= size
;
2471 if ( context
.verboseMapping
)
2472 dyld::log("%18s at 0x%08lX->0x%08lX with permissions %c%c%c\n", segName(i
), requestedLoadAddress
, requestedLoadAddress
+size
-1,
2473 (protection
& PROT_READ
) ? 'r' : '.', (protection
& PROT_WRITE
) ? 'w' : '.', (protection
& PROT_EXEC
) ? 'x' : '.' );
2476 // update slide to reflect load location
2477 this->setSlide(slide
);
2480 void ImageLoaderMachO::mapSegments(const void* memoryImage
, uint64_t imageLen
, const LinkContext
& context
)
2482 // find address range for image
2483 intptr_t slide
= this->assignSegmentAddresses(context
);
2484 if ( context
.verboseMapping
)
2485 dyld::log("dyld: Mapping memory %p\n", memoryImage
);
2486 // map in all segments
2487 for(unsigned int i
=0, e
=segmentCount(); i
< e
; ++i
) {
2488 vm_address_t loadAddress
= segPreferredLoadAddress(i
) + slide
;
2489 vm_address_t srcAddr
= (uintptr_t)memoryImage
+ segFileOffset(i
);
2490 vm_size_t size
= segFileSize(i
);
2491 kern_return_t r
= vm_copy(mach_task_self(), srcAddr
, size
, loadAddress
);
2492 if ( r
!= KERN_SUCCESS
)
2493 throw "can't map segment";
2494 if ( context
.verboseMapping
)
2495 dyld::log("%18s at 0x%08lX->0x%08lX\n", segName(i
), (uintptr_t)loadAddress
, (uintptr_t)loadAddress
+size
-1);
2497 // update slide to reflect load location
2498 this->setSlide(slide
);
2499 // set R/W permissions on all segments at slide location
2500 for(unsigned int i
=0, e
=segmentCount(); i
< e
; ++i
) {
2501 segProtect(i
, context
);
2506 void ImageLoaderMachO::segProtect(unsigned int segIndex
, const ImageLoader::LinkContext
& context
)
2508 vm_prot_t protection
= 0;
2509 if ( !segUnaccessible(segIndex
) ) {
2510 if ( segExecutable(segIndex
) )
2511 protection
|= PROT_EXEC
;
2512 if ( segReadable(segIndex
) )
2513 protection
|= PROT_READ
;
2514 if ( segWriteable(segIndex
) )
2515 protection
|= PROT_WRITE
;
2517 vm_address_t addr
= segActualLoadAddress(segIndex
);
2518 vm_size_t size
= segSize(segIndex
);
2519 const bool setCurrentPermissions
= false;
2520 kern_return_t r
= vm_protect(mach_task_self(), addr
, size
, setCurrentPermissions
, protection
);
2521 if ( r
!= KERN_SUCCESS
) {
2522 dyld::throwf("vm_protect(0x%08llX, 0x%08llX, false, 0x%02X) failed, result=%d for segment %s in %s",
2523 (long long)addr
, (long long)size
, protection
, r
, segName(segIndex
), this->getPath());
2525 if ( context
.verboseMapping
) {
2526 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,
2527 (protection
& PROT_READ
) ? 'r' : '.', (protection
& PROT_WRITE
) ? 'w' : '.', (protection
& PROT_EXEC
) ? 'x' : '.' );
2531 void ImageLoaderMachO::segMakeWritable(unsigned int segIndex
, const ImageLoader::LinkContext
& context
)
2533 vm_address_t addr
= segActualLoadAddress(segIndex
);
2534 vm_size_t size
= segSize(segIndex
);
2535 const bool setCurrentPermissions
= false;
2536 vm_prot_t protection
= VM_PROT_WRITE
| VM_PROT_READ
;
2537 if ( segExecutable(segIndex
) && !segHasRebaseFixUps(segIndex
) )
2538 protection
|= VM_PROT_EXECUTE
;
2539 kern_return_t r
= vm_protect(mach_task_self(), addr
, size
, setCurrentPermissions
, protection
);
2540 if ( r
!= KERN_SUCCESS
) {
2541 dyld::throwf("vm_protect(0x%08llX, 0x%08llX, false, 0x%02X) failed, result=%d for segment %s in %s",
2542 (long long)addr
, (long long)size
, protection
, r
, segName(segIndex
), this->getPath());
2544 if ( context
.verboseMapping
) {
2545 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,
2546 (protection
& PROT_READ
) ? 'r' : '.', (protection
& PROT_WRITE
) ? 'w' : '.', (protection
& PROT_EXEC
) ? 'x' : '.' );
2551 const char* ImageLoaderMachO::findClosestSymbol(const mach_header
* mh
, const void* addr
, const void** closestAddr
)
2553 // called by dladdr()
2554 // only works with compressed LINKEDIT if classic symbol table is also present
2555 const dysymtab_command
* dynSymbolTable
= NULL
;
2556 const symtab_command
* symtab
= NULL
;
2557 const macho_segment_command
* seg
;
2558 const uint8_t* unslidLinkEditBase
= NULL
;
2559 bool linkEditBaseFound
= false;
2561 const uint32_t cmd_count
= mh
->ncmds
;
2562 const load_command
* const cmds
= (load_command
*)((char*)mh
+ sizeof(macho_header
));
2563 const load_command
* cmd
= cmds
;
2564 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
2566 case LC_SEGMENT_COMMAND
:
2567 seg
= (macho_segment_command
*)cmd
;
2568 if ( strcmp(seg
->segname
, "__LINKEDIT") == 0 ) {
2569 unslidLinkEditBase
= (uint8_t*)(seg
->vmaddr
- seg
->fileoff
);
2570 linkEditBaseFound
= true;
2572 else if ( (seg
->fileoff
== 0) && (seg
->filesize
!= 0) )
2573 slide
= (uintptr_t)mh
- seg
->vmaddr
;
2576 symtab
= (symtab_command
*)cmd
;
2579 dynSymbolTable
= (dysymtab_command
*)cmd
;
2582 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
2584 // no symbol table => no lookup by address
2585 if ( (symtab
== NULL
) || (dynSymbolTable
== NULL
) || !linkEditBaseFound
)
2588 const uint8_t* linkEditBase
= unslidLinkEditBase
+ slide
;
2589 const char* symbolTableStrings
= (const char*)&linkEditBase
[symtab
->stroff
];
2590 const macho_nlist
* symbolTable
= (macho_nlist
*)(&linkEditBase
[symtab
->symoff
]);
2592 uintptr_t targetAddress
= (uintptr_t)addr
- slide
;
2593 const struct macho_nlist
* bestSymbol
= NULL
;
2594 // first walk all global symbols
2595 const struct macho_nlist
* const globalsStart
= &symbolTable
[dynSymbolTable
->iextdefsym
];
2596 const struct macho_nlist
* const globalsEnd
= &globalsStart
[dynSymbolTable
->nextdefsym
];
2597 for (const struct macho_nlist
* s
= globalsStart
; s
< globalsEnd
; ++s
) {
2598 if ( (s
->n_type
& N_TYPE
) == N_SECT
) {
2599 if ( bestSymbol
== NULL
) {
2600 if ( s
->n_value
<= targetAddress
)
2603 else if ( (s
->n_value
<= targetAddress
) && (bestSymbol
->n_value
< s
->n_value
) ) {
2608 // next walk all local symbols
2609 const struct macho_nlist
* const localsStart
= &symbolTable
[dynSymbolTable
->ilocalsym
];
2610 const struct macho_nlist
* const localsEnd
= &localsStart
[dynSymbolTable
->nlocalsym
];
2611 for (const struct macho_nlist
* s
= localsStart
; s
< localsEnd
; ++s
) {
2612 if ( ((s
->n_type
& N_TYPE
) == N_SECT
) && ((s
->n_type
& N_STAB
) == 0) ) {
2613 if ( bestSymbol
== NULL
) {
2614 if ( s
->n_value
<= targetAddress
)
2617 else if ( (s
->n_value
<= targetAddress
) && (bestSymbol
->n_value
< s
->n_value
) ) {
2622 if ( bestSymbol
!= NULL
) {
2624 if (bestSymbol
->n_desc
& N_ARM_THUMB_DEF
)
2625 *closestAddr
= (void*)((bestSymbol
->n_value
| 1) + slide
);
2627 *closestAddr
= (void*)(bestSymbol
->n_value
+ slide
);
2629 *closestAddr
= (void*)(bestSymbol
->n_value
+ slide
);
2631 return &symbolTableStrings
[bestSymbol
->n_un
.n_strx
];
2636 bool ImageLoaderMachO::getLazyBindingInfo(uint32_t& lazyBindingInfoOffset
, const uint8_t* lazyInfoStart
, const uint8_t* lazyInfoEnd
,
2637 uint8_t* segIndex
, uintptr_t* segOffset
, int* ordinal
, const char** symbolName
, bool* doneAfterBind
)
2639 if ( lazyBindingInfoOffset
> (lazyInfoEnd
-lazyInfoStart
) )
2641 uint8_t type
= BIND_TYPE_POINTER
;
2642 uint8_t symboFlags
= 0;
2644 const uint8_t* p
= &lazyInfoStart
[lazyBindingInfoOffset
];
2645 while ( !done
&& (p
< lazyInfoEnd
) ) {
2646 uint8_t immediate
= *p
& BIND_IMMEDIATE_MASK
;
2647 uint8_t opcode
= *p
& BIND_OPCODE_MASK
;
2650 case BIND_OPCODE_DONE
:
2651 *doneAfterBind
= false;
2654 case BIND_OPCODE_SET_DYLIB_ORDINAL_IMM
:
2655 *ordinal
= immediate
;
2657 case BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB
:
2658 *ordinal
= (int)read_uleb128(p
, lazyInfoEnd
);
2660 case BIND_OPCODE_SET_DYLIB_SPECIAL_IMM
:
2661 // the special ordinals are negative numbers
2662 if ( immediate
== 0 )
2665 int8_t signExtended
= BIND_OPCODE_MASK
| immediate
;
2666 *ordinal
= signExtended
;
2669 case BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM
:
2670 *symbolName
= (char*)p
;
2671 symboFlags
= immediate
;
2676 case BIND_OPCODE_SET_TYPE_IMM
:
2679 case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB
:
2680 *segIndex
= immediate
;
2681 *segOffset
= read_uleb128(p
, lazyInfoEnd
);
2683 case BIND_OPCODE_DO_BIND
:
2684 *doneAfterBind
= ((*p
& BIND_OPCODE_MASK
) == BIND_OPCODE_DONE
);
2685 lazyBindingInfoOffset
+= p
- &lazyInfoStart
[lazyBindingInfoOffset
];
2688 case BIND_OPCODE_SET_ADDEND_SLEB
:
2689 case BIND_OPCODE_ADD_ADDR_ULEB
:
2690 case BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB
:
2691 case BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED
:
2692 case BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB
:
2700 const dyld_info_command
* ImageLoaderMachO::findDyldInfoLoadCommand(const mach_header
* mh
)
2702 const uint32_t cmd_count
= mh
->ncmds
;
2703 const load_command
* const cmds
= (load_command
*)((char*)mh
+ sizeof(macho_header
));
2704 const load_command
* cmd
= cmds
;
2705 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
2708 case LC_DYLD_INFO_ONLY
:
2709 return (dyld_info_command
*)cmd
;
2711 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
2717 uintptr_t ImageLoaderMachO::segPreferredAddress(const mach_header
* mh
, unsigned segIndex
)
2719 const uint32_t cmd_count
= mh
->ncmds
;
2720 const load_command
* const cmds
= (load_command
*)((char*)mh
+ sizeof(macho_header
));
2721 const load_command
* cmd
= cmds
;
2722 unsigned curSegIndex
= 0;
2723 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
2724 if ( cmd
->cmd
== LC_SEGMENT_COMMAND
) {
2725 if ( segIndex
== curSegIndex
) {
2726 const macho_segment_command
* segCmd
= (macho_segment_command
*)cmd
;
2727 return segCmd
->vmaddr
;
2731 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);