1 /* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*-
3 * Copyright (c) 2004-2013 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@
31 #include <sys/param.h>
32 #include <mach/mach_time.h> // mach_absolute_time()
33 #include <mach/mach_init.h>
34 #include <sys/types.h>
36 #include <sys/syscall.h>
37 #include <sys/socket.h>
39 #include <sys/syslog.h>
41 #include <mach-o/fat.h>
42 #include <mach-o/loader.h>
43 #include <mach-o/ldsyms.h>
44 #include <libkern/OSByteOrder.h>
45 #include <libkern/OSAtomic.h>
46 #include <mach/mach.h>
47 #include <sys/sysctl.h>
49 #include <sys/dtrace.h>
50 #include <libkern/OSAtomic.h>
51 #include <Availability.h>
52 #include <System/sys/codesign.h>
54 #include <os/lock_private.h>
57 #ifndef CPU_SUBTYPE_ARM_V5TEJ
58 #define CPU_SUBTYPE_ARM_V5TEJ ((cpu_subtype_t) 7)
60 #ifndef CPU_SUBTYPE_ARM_XSCALE
61 #define CPU_SUBTYPE_ARM_XSCALE ((cpu_subtype_t) 8)
63 #ifndef CPU_SUBTYPE_ARM_V7
64 #define CPU_SUBTYPE_ARM_V7 ((cpu_subtype_t) 9)
66 #ifndef CPU_SUBTYPE_ARM_V7F
67 #define CPU_SUBTYPE_ARM_V7F ((cpu_subtype_t) 10)
69 #ifndef CPU_SUBTYPE_ARM_V7S
70 #define CPU_SUBTYPE_ARM_V7S ((cpu_subtype_t) 11)
72 #ifndef CPU_SUBTYPE_ARM_V7K
73 #define CPU_SUBTYPE_ARM_V7K ((cpu_subtype_t) 12)
75 #ifndef LC_DYLD_ENVIRONMENT
76 #define LC_DYLD_ENVIRONMENT 0x27
79 #ifndef CPU_SUBTYPE_X86_64_H
80 #define CPU_SUBTYPE_X86_64_H ((cpu_subtype_t) 8)
84 #define VM_PROT_SLIDE 0x20
90 #include "mach-o/dyld_gdb.h"
93 #include "ImageLoader.h"
94 #include "ImageLoaderMachO.h"
95 #include "dyldLibSystemInterface.h"
96 #include "dyldSyscallInterface.h"
97 #if DYLD_SHARED_CACHE_SUPPORT
98 #include "dyld_cache_format.h"
100 #if TARGET_IPHONE_SIMULATOR
101 void coresymbolication_load_image(void*, const ImageLoader
*, uint64_t);
102 void coresymbolication_unload_image(void*, const ImageLoader
*);
104 #include "coreSymbolicationDyldSupport.hpp"
107 // not libc header for send() syscall interface
108 extern "C" ssize_t
__sendto(int, const void *, size_t, int, const struct sockaddr
*, socklen_t
);
111 // ARM and x86_64 are the only architecture that use cpu-sub-types
112 #define CPU_SUBTYPES_SUPPORTED ((__arm__ || __x86_64__) && !TARGET_IPHONE_SIMULATOR)
116 #define CPU_TYPE_MASK 0x00FFFFFF /* complement of CPU_ARCH_MASK */
119 /* implemented in dyld_gdb.cpp */
120 extern void addImagesToAllImages(uint32_t infoCount
, const dyld_image_info info
[]);
121 extern void removeImageFromAllImages(const mach_header
* mh
);
122 extern void setAlImageInfosHalt(const char* message
, uintptr_t flags
);
123 extern void addNonSharedCacheImageUUID(const dyld_uuid_info
& info
);
124 extern const char* notifyGDB(enum dyld_image_states state
, uint32_t infoCount
, const dyld_image_info info
[]);
126 // magic so CrashReporter logs message
128 char error_string
[1024];
130 // implemented in dyldStartup.s for CrashReporter
131 extern "C" void dyld_fatal_error(const char* errString
) __attribute__((noreturn
));
133 // magic linker symbol for start of dyld binary
134 extern "C" const macho_header __dso_handle
;
138 // The file contains the core of dyld used to get a process to main().
139 // The API's that dyld supports are implemented in dyldAPIs.cpp.
146 struct RegisteredDOF
{ const mach_header
* mh
; int registrationID
; };
147 struct DylibOverride
{ const char* installName
; const char* override
; };
151 VECTOR_NEVER_DESTRUCTED(ImageLoader
*);
152 VECTOR_NEVER_DESTRUCTED(dyld::RegisteredDOF
);
153 VECTOR_NEVER_DESTRUCTED(dyld::ImageCallback
);
154 VECTOR_NEVER_DESTRUCTED(dyld::DylibOverride
);
155 VECTOR_NEVER_DESTRUCTED(ImageLoader::DynamicReference
);
157 VECTOR_NEVER_DESTRUCTED(dyld_image_state_change_handler
);
163 // state of all environment variables dyld uses
165 struct EnvironmentVariables
{
166 const char* const * DYLD_FRAMEWORK_PATH
;
167 const char* const * DYLD_FALLBACK_FRAMEWORK_PATH
;
168 const char* const * DYLD_LIBRARY_PATH
;
169 const char* const * DYLD_FALLBACK_LIBRARY_PATH
;
170 const char* const * DYLD_INSERT_LIBRARIES
;
171 const char* const * LD_LIBRARY_PATH
; // for unix conformance
172 const char* const * DYLD_VERSIONED_LIBRARY_PATH
;
173 const char* const * DYLD_VERSIONED_FRAMEWORK_PATH
;
174 bool DYLD_PRINT_LIBRARIES
;
175 bool DYLD_PRINT_LIBRARIES_POST_LAUNCH
;
176 bool DYLD_BIND_AT_LAUNCH
;
177 bool DYLD_PRINT_STATISTICS
;
178 bool DYLD_PRINT_OPTS
;
180 bool DYLD_DISABLE_DOFS
;
181 bool DYLD_PRINT_CS_NOTIFICATIONS
;
182 // DYLD_SHARED_CACHE_DONT_VALIDATE ==> sSharedCacheIgnoreInodeAndTimeStamp
183 // DYLD_SHARED_CACHE_DIR ==> sSharedCacheDir
184 // DYLD_ROOT_PATH ==> gLinkContext.rootPaths
185 // DYLD_IMAGE_SUFFIX ==> gLinkContext.imageSuffix
186 // DYLD_PRINT_OPTS ==> gLinkContext.verboseOpts
187 // DYLD_PRINT_ENV ==> gLinkContext.verboseEnv
188 // DYLD_FORCE_FLAT_NAMESPACE ==> gLinkContext.bindFlat
189 // DYLD_PRINT_INITIALIZERS ==> gLinkContext.verboseInit
190 // DYLD_PRINT_SEGMENTS ==> gLinkContext.verboseMapping
191 // DYLD_PRINT_BINDINGS ==> gLinkContext.verboseBind
192 // DYLD_PRINT_WEAK_BINDINGS ==> gLinkContext.verboseWeakBind
193 // DYLD_PRINT_REBASINGS ==> gLinkContext.verboseRebase
194 // DYLD_PRINT_DOFS ==> gLinkContext.verboseDOF
195 // DYLD_PRINT_APIS ==> gLogAPIs
196 // DYLD_IGNORE_PREBINDING ==> gLinkContext.prebindUsage
197 // DYLD_PREBIND_DEBUG ==> gLinkContext.verbosePrebinding
198 // DYLD_NEW_LOCAL_SHARED_REGIONS ==> gLinkContext.sharedRegionMode
199 // DYLD_SHARED_REGION ==> gLinkContext.sharedRegionMode
200 // DYLD_PRINT_WARNINGS ==> gLinkContext.verboseWarnings
201 // DYLD_PRINT_RPATHS ==> gLinkContext.verboseRPaths
202 // DYLD_PRINT_INTERPOSING ==> gLinkContext.verboseInterposing
207 typedef std::vector
<dyld_image_state_change_handler
> StateHandlers
;
210 enum RestrictedReason
{ restrictedNot
, restrictedBySetGUid
, restrictedBySegment
, restrictedByEntitlements
};
213 static const char* sExecPath
= NULL
;
214 static const char* sExecShortName
= NULL
;
215 static const macho_header
* sMainExecutableMachHeader
= NULL
;
216 #if CPU_SUBTYPES_SUPPORTED
217 static cpu_type_t sHostCPU
;
218 static cpu_subtype_t sHostCPUsubtype
;
220 static ImageLoader
* sMainExecutable
= NULL
;
221 static bool sProcessIsRestricted
= false;
222 static RestrictedReason sRestrictedReason
= restrictedNot
;
223 static size_t sInsertedDylibCount
= 0;
224 static std::vector
<ImageLoader
*> sAllImages
;
225 static std::vector
<ImageLoader
*> sImageRoots
;
226 static std::vector
<ImageLoader
*> sImageFilesNeedingTermination
;
227 static std::vector
<RegisteredDOF
> sImageFilesNeedingDOFUnregistration
;
228 static std::vector
<ImageCallback
> sAddImageCallbacks
;
229 static std::vector
<ImageCallback
> sRemoveImageCallbacks
;
230 static bool sRemoveImageCallbacksInUse
= false;
231 static void* sSingleHandlers
[7][3];
232 static void* sBatchHandlers
[7][3];
233 static ImageLoader
* sLastImageByAddressCache
;
234 static EnvironmentVariables sEnv
;
235 static const char* sFrameworkFallbackPaths
[] = { "$HOME/Library/Frameworks", "/Library/Frameworks", "/Network/Library/Frameworks", "/System/Library/Frameworks", NULL
};
236 static const char* sLibraryFallbackPaths
[] = { "$HOME/lib", "/usr/local/lib", "/usr/lib", NULL
};
237 static UndefinedHandler sUndefinedHandler
= NULL
;
238 static ImageLoader
* sBundleBeingLoaded
= NULL
; // hack until OFI is reworked
239 #if DYLD_SHARED_CACHE_SUPPORT
240 static const dyld_cache_header
* sSharedCache
= NULL
;
241 static long sSharedCacheSlide
= 0;
242 static bool sSharedCacheIgnoreInodeAndTimeStamp
= false;
243 bool gSharedCacheOverridden
= false;
244 #if __IPHONE_OS_VERSION_MIN_REQUIRED
245 static const char* sSharedCacheDir
= IPHONE_DYLD_SHARED_CACHE_DIR
;
246 static bool sDylibsOverrideCache
= false;
247 #define ENABLE_DYLIBS_TO_OVERRIDE_CACHE_SIZE 1024
249 static const char* sSharedCacheDir
= MACOSX_DYLD_SHARED_CACHE_DIR
;
252 ImageLoader::LinkContext gLinkContext
;
253 bool gLogAPIs
= false;
254 const struct LibSystemHelpers
* gLibSystemHelpers
= NULL
;
255 #if SUPPORT_OLD_CRT_INITIALIZATION
256 bool gRunInitializersOldWay
= false;
258 static std::vector
<DylibOverride
> sDylibOverrides
;
259 #if !TARGET_IPHONE_SIMULATOR
260 static int sLogSocket
= -1;
262 static bool sFrameworksFoundAsDylibs
= false;
264 static bool sHaswell
= false;
266 static std::vector
<ImageLoader::DynamicReference
> sDynamicReferences
;
267 static bool sLogToFile
= false;
268 static char sLoadingCrashMessage
[1024] = "dyld: launch, loading dependent libraries";
271 // The MappedRanges structure is used for fast address->image lookups.
272 // The table is only updated when the dyld lock is held, so we don't
273 // need to worry about multiple writers. But readers may look at this
274 // data without holding the lock. Therefore, all updates must be done
275 // in an order that will never cause readers to see inconsistent data.
276 // The general rule is that if the image field is non-NULL then
277 // the other fields are valid.
290 static MappedRanges sMappedRangesStart
;
292 void addMappedRange(ImageLoader
* image
, uintptr_t start
, uintptr_t end
)
294 //dyld::log("addMappedRange(0x%lX->0x%lX) for %s\n", start, end, image->getShortName());
295 for (MappedRanges
* p
= &sMappedRangesStart
; p
!= NULL
; p
= p
->next
) {
296 for (int i
=0; i
< MappedRanges::count
; ++i
) {
297 if ( p
->array
[i
].image
== NULL
) {
298 p
->array
[i
].start
= start
;
299 p
->array
[i
].end
= end
;
300 // add image field last with a barrier so that any reader will see consistent records
302 p
->array
[i
].image
= image
;
307 // table must be full, chain another
308 MappedRanges
* newRanges
= (MappedRanges
*)malloc(sizeof(MappedRanges
));
309 bzero(newRanges
, sizeof(MappedRanges
));
310 newRanges
->array
[0].start
= start
;
311 newRanges
->array
[0].end
= end
;
312 newRanges
->array
[0].image
= image
;
313 for (MappedRanges
* p
= &sMappedRangesStart
; p
!= NULL
; p
= p
->next
) {
314 if ( p
->next
== NULL
) {
322 void removedMappedRanges(ImageLoader
* image
)
324 for (MappedRanges
* p
= &sMappedRangesStart
; p
!= NULL
; p
= p
->next
) {
325 for (int i
=0; i
< MappedRanges::count
; ++i
) {
326 if ( p
->array
[i
].image
== image
) {
327 // clear with a barrier so that any reader will see consistent records
329 p
->array
[i
].image
= NULL
;
335 ImageLoader
* findMappedRange(uintptr_t target
)
337 for (MappedRanges
* p
= &sMappedRangesStart
; p
!= NULL
; p
= p
->next
) {
338 for (int i
=0; i
< MappedRanges::count
; ++i
) {
339 if ( p
->array
[i
].image
!= NULL
) {
340 if ( (p
->array
[i
].start
<= target
) && (target
< p
->array
[i
].end
) )
341 return p
->array
[i
].image
;
350 const char* mkstringf(const char* format
, ...)
352 _SIMPLE_STRING buf
= _simple_salloc();
355 va_start(list
, format
);
356 _simple_vsprintf(buf
, format
, list
);
358 const char* t
= strdup(_simple_string(buf
));
363 return "mkstringf, out of memory error";
367 void throwf(const char* format
, ...)
369 _SIMPLE_STRING buf
= _simple_salloc();
372 va_start(list
, format
);
373 _simple_vsprintf(buf
, format
, list
);
375 const char* t
= strdup(_simple_string(buf
));
380 throw "throwf, out of memory error";
384 #if !TARGET_IPHONE_SIMULATOR
385 static int sLogfile
= STDERR_FILENO
;
389 static int sBindingsLogfile
= -1;
390 static void mysprintf(char* dst
, const char* format
, ...)
392 _SIMPLE_STRING buf
= _simple_salloc();
395 va_start(list
, format
);
396 _simple_vsprintf(buf
, format
, list
);
398 strcpy(dst
, _simple_string(buf
));
402 strcpy(dst
, "out of memory");
405 void logBindings(const char* format
, ...)
407 if ( sBindingsLogfile
!= -1 ) {
409 va_start(list
, format
);
410 _simple_vdprintf(sBindingsLogfile
, format
, list
);
416 #if !TARGET_IPHONE_SIMULATOR
417 // based on CFUtilities.c: also_do_stderr()
418 static bool useSyslog()
420 // Use syslog() for processes managed by launchd
421 if ( (gLibSystemHelpers
!= NULL
) && (gLibSystemHelpers
->version
>= 11) ) {
422 if ( (*gLibSystemHelpers
->isLaunchdOwned
)() ) {
427 // If stderr is not available, use syslog()
429 int result
= fstat(STDERR_FILENO
, &sb
);
431 return true; // file descriptor 2 is closed
437 static void socket_syslogv(int priority
, const char* format
, va_list list
)
439 // lazily create socket and connection to syslogd
440 if ( sLogSocket
== -1 ) {
441 sLogSocket
= ::socket(AF_UNIX
, SOCK_DGRAM
, 0);
442 if (sLogSocket
== -1)
443 return; // cannot log
444 ::fcntl(sLogSocket
, F_SETFD
, 1);
446 struct sockaddr_un addr
;
447 addr
.sun_family
= AF_UNIX
;
448 strncpy(addr
.sun_path
, _PATH_LOG
, sizeof(addr
.sun_path
));
449 if ( ::connect(sLogSocket
, (struct sockaddr
*)&addr
, sizeof(addr
)) == -1 ) {
456 // format message to syslogd like: "<priority>Process[pid]: message"
457 _SIMPLE_STRING buf
= _simple_salloc();
460 if ( _simple_sprintf(buf
, "<%d>%s[%d]: ", LOG_USER
|LOG_NOTICE
, sExecShortName
, getpid()) == 0 ) {
461 if ( _simple_vsprintf(buf
, format
, list
) == 0 ) {
462 const char* p
= _simple_string(buf
);
463 ::__sendto(sLogSocket
, p
, strlen(p
), 0, NULL
, 0);
469 void vlog(const char* format
, va_list list
)
471 if ( !sLogToFile
&& useSyslog() )
472 socket_syslogv(LOG_ERR
, format
, list
);
474 _simple_vdprintf(sLogfile
, format
, list
);
478 void log(const char* format
, ...)
481 va_start(list
, format
);
487 void vwarn(const char* format
, va_list list
)
489 _simple_dprintf(sLogfile
, "dyld: warning, ");
490 _simple_vdprintf(sLogfile
, format
, list
);
493 void warn(const char* format
, ...)
496 va_start(list
, format
);
502 #endif // !TARGET_IPHONE_SIMULATOR
505 // <rdar://problem/8867781> control access to sAllImages through a lock
506 // because global dyld lock is not held during initialization phase of dlopen()
507 // <rdar://problem/16145518> Use OSSpinLockLock to allow yielding
508 static OSSpinLock sAllImagesLock
= 0;
510 static void allImagesLock()
512 //dyld::log("allImagesLock()\n");
513 #if TARGET_IPHONE_SIMULATOR
514 // <rdar://problem/16154256> can't use OSSpinLockLock in simulator until thread_switch is provided by host dyld
515 while ( ! OSAtomicCompareAndSwapPtrBarrier((void*)0, (void*)1, (void**)&sAllImagesLock
) ) {
519 OSSpinLockLock(&sAllImagesLock
);
523 static void allImagesUnlock()
525 //dyld::log("allImagesUnlock()\n");
526 #if TARGET_IPHONE_SIMULATOR
527 while ( ! OSAtomicCompareAndSwapPtrBarrier((void*)1, (void*)0, (void**)&sAllImagesLock
) ) {
531 OSSpinLockUnlock(&sAllImagesLock
);
538 // utility class to assure files are closed when an exception is thrown
541 FileOpener(const char* path
);
543 int getFileDescriptor() { return fd
; }
548 FileOpener::FileOpener(const char* path
)
551 fd
= my_open(path
, O_RDONLY
, 0);
554 FileOpener::~FileOpener()
561 static void registerDOFs(const std::vector
<ImageLoader::DOFInfo
>& dofs
)
563 const size_t dofSectionCount
= dofs
.size();
564 if ( !sEnv
.DYLD_DISABLE_DOFS
&& (dofSectionCount
!= 0) ) {
565 int fd
= open("/dev/" DTRACEMNR_HELPER
, O_RDWR
);
567 //dyld::warn("can't open /dev/" DTRACEMNR_HELPER " to register dtrace DOF sections\n");
570 // allocate a buffer on the stack for the variable length dof_ioctl_data_t type
571 uint8_t buffer
[sizeof(dof_ioctl_data_t
) + dofSectionCount
*sizeof(dof_helper_t
)];
572 dof_ioctl_data_t
* ioctlData
= (dof_ioctl_data_t
*)buffer
;
574 // fill in buffer with one dof_helper_t per DOF section
575 ioctlData
->dofiod_count
= dofSectionCount
;
576 for (unsigned int i
=0; i
< dofSectionCount
; ++i
) {
577 strlcpy(ioctlData
->dofiod_helpers
[i
].dofhp_mod
, dofs
[i
].imageShortName
, DTRACE_MODNAMELEN
);
578 ioctlData
->dofiod_helpers
[i
].dofhp_dof
= (uintptr_t)(dofs
[i
].dof
);
579 ioctlData
->dofiod_helpers
[i
].dofhp_addr
= (uintptr_t)(dofs
[i
].dof
);
582 // tell kernel about all DOF sections en mas
583 // pass pointer to ioctlData because ioctl() only copies a fixed size amount of data into kernel
584 user_addr_t val
= (user_addr_t
)(unsigned long)ioctlData
;
585 if ( ioctl(fd
, DTRACEHIOC_ADDDOF
, &val
) != -1 ) {
586 // kernel returns a unique identifier for each section in the dofiod_helpers[].dofhp_dof field.
587 for (unsigned int i
=0; i
< dofSectionCount
; ++i
) {
589 info
.mh
= dofs
[i
].imageHeader
;
590 info
.registrationID
= (int)(ioctlData
->dofiod_helpers
[i
].dofhp_dof
);
591 sImageFilesNeedingDOFUnregistration
.push_back(info
);
592 if ( gLinkContext
.verboseDOF
) {
593 dyld::log("dyld: registering DOF section %p in %s with dtrace, ID=0x%08X\n",
594 dofs
[i
].dof
, dofs
[i
].imageShortName
, info
.registrationID
);
599 //dyld::log( "dyld: ioctl to register dtrace DOF section failed\n");
606 static void unregisterDOF(int registrationID
)
608 int fd
= open("/dev/" DTRACEMNR_HELPER
, O_RDWR
);
610 dyld::warn("can't open /dev/" DTRACEMNR_HELPER
" to unregister dtrace DOF section\n");
613 ioctl(fd
, DTRACEHIOC_REMOVE
, registrationID
);
615 if ( gLinkContext
.verboseInit
)
616 dyld::warn("unregistering DOF section ID=0x%08X with dtrace\n", registrationID
);
622 // _dyld_register_func_for_add_image() is implemented as part of the general image state change notification
624 static void notifyAddImageCallbacks(ImageLoader
* image
)
626 // use guard so that we cannot notify about the same image twice
627 if ( ! image
->addFuncNotified() ) {
628 for (std::vector
<ImageCallback
>::iterator it
=sAddImageCallbacks
.begin(); it
!= sAddImageCallbacks
.end(); it
++)
629 (*it
)(image
->machHeader(), image
->getSlide());
630 image
->setAddFuncNotified();
636 // notify gdb about these new images
637 static const char* updateAllImages(enum dyld_image_states state
, uint32_t infoCount
, const struct dyld_image_info info
[])
639 // <rdar://problem/8812589> don't add images without paths to all-image-info-list
640 if ( info
[0].imageFilePath
!= NULL
)
641 addImagesToAllImages(infoCount
, info
);
646 static StateHandlers
* stateToHandlers(dyld_image_states state
, void* handlersArray
[7][3])
649 case dyld_image_state_mapped
:
650 return reinterpret_cast<StateHandlers
*>(&handlersArray
[0]);
652 case dyld_image_state_dependents_mapped
:
653 return reinterpret_cast<StateHandlers
*>(&handlersArray
[1]);
655 case dyld_image_state_rebased
:
656 return reinterpret_cast<StateHandlers
*>(&handlersArray
[2]);
658 case dyld_image_state_bound
:
659 return reinterpret_cast<StateHandlers
*>(&handlersArray
[3]);
661 case dyld_image_state_dependents_initialized
:
662 return reinterpret_cast<StateHandlers
*>(&handlersArray
[4]);
664 case dyld_image_state_initialized
:
665 return reinterpret_cast<StateHandlers
*>(&handlersArray
[5]);
667 case dyld_image_state_terminated
:
668 return reinterpret_cast<StateHandlers
*>(&handlersArray
[6]);
673 static void notifySingle(dyld_image_states state
, const ImageLoader
* image
)
675 //dyld::log("notifySingle(state=%d, image=%s)\n", state, image->getPath());
676 std::vector
<dyld_image_state_change_handler
>* handlers
= stateToHandlers(state
, sSingleHandlers
);
677 if ( handlers
!= NULL
) {
678 dyld_image_info info
;
679 info
.imageLoadAddress
= image
->machHeader();
680 info
.imageFilePath
= image
->getRealPath();
681 info
.imageFileModDate
= image
->lastModified();
682 for (std::vector
<dyld_image_state_change_handler
>::iterator it
= handlers
->begin(); it
!= handlers
->end(); ++it
) {
683 const char* result
= (*it
)(state
, 1, &info
);
684 if ( (result
!= NULL
) && (state
== dyld_image_state_mapped
) ) {
685 //fprintf(stderr, " image rejected by handler=%p\n", *it);
686 // make copy of thrown string so that later catch clauses can free it
687 const char* str
= strdup(result
);
692 if ( state
== dyld_image_state_mapped
) {
693 // <rdar://problem/7008875> Save load addr + UUID for images from outside the shared cache
694 if ( !image
->inSharedCache() ) {
696 if ( image
->getUUID(info
.imageUUID
) ) {
697 info
.imageLoadAddress
= image
->machHeader();
698 addNonSharedCacheImageUUID(info
);
702 // mach message csdlc about dynamically loaded images
703 if ( image
->addFuncNotified() && (state
== dyld_image_state_terminated
) ) {
704 if ( sEnv
.DYLD_PRINT_CS_NOTIFICATIONS
) {
705 dyld::log("dyld core symbolication unload notification: %p %s\n", image
->machHeader(), image
->getPath());
707 if ( dyld::gProcessInfo
->coreSymbolicationShmPage
!= NULL
) {
708 #if TARGET_IPHONE_SIMULATOR
709 void* connection
= dyld::gProcessInfo
->coreSymbolicationShmPage
;
710 if ( *((uint32_t*)connection
) == 2 ) {
712 CSCppDyldSharedMemoryPage
* connection
= (CSCppDyldSharedMemoryPage
*)dyld::gProcessInfo
->coreSymbolicationShmPage
;
713 if ( connection
->is_valid_version() ) {
715 coresymbolication_unload_image(connection
, image
);
725 // Normally, dyld_all_image_infos is only updated in batches after an entire
726 // graph is loaded. But if there is an error loading the initial set of
727 // dylibs needed by the main executable, dyld_all_image_infos is not yet set
728 // up, leading to usually brief crash logs.
730 // This function manually adds the images loaded so far to dyld::gProcessInfo.
731 // It should only be called before terminating.
735 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); ++it
) {
736 dyld_image_info info
;
737 ImageLoader
* image
= *it
;
738 info
.imageLoadAddress
= image
->machHeader();
739 info
.imageFilePath
= image
->getRealPath();
740 info
.imageFileModDate
= image
->lastModified();
741 // add to all_image_infos if not already there
743 int existingCount
= dyld::gProcessInfo
->infoArrayCount
;
744 const dyld_image_info
* existing
= dyld::gProcessInfo
->infoArray
;
745 if ( existing
!= NULL
) {
746 for (int i
=0; i
< existingCount
; ++i
) {
747 if ( existing
[i
].imageLoadAddress
== info
.imageLoadAddress
) {
748 //dyld::log("not adding %s\n", info.imageFilePath);
755 //dyld::log("adding %s\n", info.imageFilePath);
756 addImagesToAllImages(1, &info
);
762 static int imageSorter(const void* l
, const void* r
)
764 const ImageLoader
* left
= *((ImageLoader
**)l
);
765 const ImageLoader
* right
= *((ImageLoader
**)r
);
766 return left
->compare(right
);
769 static void notifyBatchPartial(dyld_image_states state
, bool orLater
, dyld_image_state_change_handler onlyHandler
)
771 std::vector
<dyld_image_state_change_handler
>* handlers
= stateToHandlers(state
, sBatchHandlers
);
772 if ( handlers
!= NULL
) {
773 // don't use a vector because it will use malloc/free and we want notifcation to be low cost
775 ImageLoader
* images
[sAllImages
.size()+1];
776 ImageLoader
** end
= images
;
777 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
778 dyld_image_states imageState
= (*it
)->getState();
779 if ( (imageState
== state
) || (orLater
&& (imageState
> state
)) )
782 if ( sBundleBeingLoaded
!= NULL
) {
783 dyld_image_states imageState
= sBundleBeingLoaded
->getState();
784 if ( (imageState
== state
) || (orLater
&& (imageState
> state
)) )
785 *end
++ = sBundleBeingLoaded
;
787 const char* dontLoadReason
= NULL
;
788 uint32_t count
= (uint32_t)(end
-images
);
789 if ( end
!= images
) {
791 qsort(images
, count
, sizeof(ImageLoader
*), &imageSorter
);
793 dyld_image_info infos
[count
];
794 for (unsigned int i
=0; i
< count
; ++i
) {
795 dyld_image_info
* p
= &infos
[i
];
796 ImageLoader
* image
= images
[i
];
797 //dyld::log(" state=%d, name=%s\n", state, image->getPath());
798 p
->imageLoadAddress
= image
->machHeader();
799 p
->imageFilePath
= image
->getRealPath();
800 p
->imageFileModDate
= image
->lastModified();
801 // special case for add_image hook
802 if ( state
== dyld_image_state_bound
)
803 notifyAddImageCallbacks(image
);
806 if ( onlyHandler
!= NULL
) {
807 const char* result
= (*onlyHandler
)(state
, count
, infos
);
808 if ( (result
!= NULL
) && (state
== dyld_image_state_dependents_mapped
) ) {
809 //fprintf(stderr, " images rejected by handler=%p\n", onlyHandler);
810 // make copy of thrown string so that later catch clauses can free it
811 dontLoadReason
= strdup(result
);
815 // call each handler with whole array
816 for (std::vector
<dyld_image_state_change_handler
>::iterator it
= handlers
->begin(); it
!= handlers
->end(); ++it
) {
817 const char* result
= (*it
)(state
, count
, infos
);
818 if ( (result
!= NULL
) && (state
== dyld_image_state_dependents_mapped
) ) {
819 //fprintf(stderr, " images rejected by handler=%p\n", *it);
820 // make copy of thrown string so that later catch clauses can free it
821 dontLoadReason
= strdup(result
);
828 if ( dontLoadReason
!= NULL
)
829 throw dontLoadReason
;
831 if ( state
== dyld_image_state_rebased
) {
832 if ( sEnv
.DYLD_PRINT_CS_NOTIFICATIONS
) {
833 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
834 dyld_image_states imageState
= (*it
)->getState();
835 if ( (imageState
== dyld_image_state_rebased
) || (orLater
&& (imageState
> dyld_image_state_rebased
)) )
836 dyld::log("dyld core symbolication load notification: %p %s\n", (*it
)->machHeader(), (*it
)->getPath());
839 if ( dyld::gProcessInfo
->coreSymbolicationShmPage
!= NULL
) {
840 #if TARGET_IPHONE_SIMULATOR
841 void* connection
= dyld::gProcessInfo
->coreSymbolicationShmPage
;
842 if ( *((uint32_t*)connection
) == 2 ) {
844 CSCppDyldSharedMemoryPage
* connection
= (CSCppDyldSharedMemoryPage
*)dyld::gProcessInfo
->coreSymbolicationShmPage
;
845 if ( connection
->is_valid_version() ) {
847 // This needs to be captured now
848 uint64_t load_timestamp
= mach_absolute_time();
849 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
850 dyld_image_states imageState
= (*it
)->getState();
851 if ( (imageState
== state
) || (orLater
&& (imageState
> state
)) )
852 coresymbolication_load_image(connection
, *it
, load_timestamp
);
861 static void notifyBatch(dyld_image_states state
)
863 notifyBatchPartial(state
, false, NULL
);
866 // In order for register_func_for_add_image() callbacks to to be called bottom up,
867 // we need to maintain a list of root images. The main executable is usally the
868 // first root. Any images dynamically added are also roots (unless already loaded).
869 // If DYLD_INSERT_LIBRARIES is used, those libraries are first.
870 static void addRootImage(ImageLoader
* image
)
872 //dyld::log("addRootImage(%p, %s)\n", image, image->getPath());
873 // add to list of roots
874 sImageRoots
.push_back(image
);
878 static void clearAllDepths()
880 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++)
884 static void printAllDepths()
886 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++)
887 dyld::log("%03d %s\n", (*it
)->getDepth(), (*it
)->getShortName());
891 static unsigned int imageCount()
893 return (unsigned int)sAllImages
.size();
897 static void setNewProgramVars(const ProgramVars
& newVars
)
899 // make a copy of the pointers to program variables
900 gLinkContext
.programVars
= newVars
;
902 // now set each program global to their initial value
903 *gLinkContext
.programVars
.NXArgcPtr
= gLinkContext
.argc
;
904 *gLinkContext
.programVars
.NXArgvPtr
= gLinkContext
.argv
;
905 *gLinkContext
.programVars
.environPtr
= gLinkContext
.envp
;
906 *gLinkContext
.programVars
.__prognamePtr
= gLinkContext
.progname
;
909 #if SUPPORT_OLD_CRT_INITIALIZATION
910 static void setRunInitialzersOldWay()
912 gRunInitializersOldWay
= true;
916 static void addDynamicReference(ImageLoader
* from
, ImageLoader
* to
) {
917 // don't add dynamic reference if either are in the shared cache
918 if( from
->inSharedCache() )
920 if( to
->inSharedCache() )
923 // don't add dynamic reference if there already is a static one
924 if ( from
->dependsOn(to
) )
927 // don't add if this combination already exists
928 for (std::vector
<ImageLoader::DynamicReference
>::iterator it
=sDynamicReferences
.begin(); it
!= sDynamicReferences
.end(); ++it
) {
929 if ( (it
->from
== from
) && (it
->to
== to
) )
932 //dyld::log("addDynamicReference(%s, %s\n", from->getShortName(), to->getShortName());
933 ImageLoader::DynamicReference t
;
936 sDynamicReferences
.push_back(t
);
939 static void addImage(ImageLoader
* image
)
941 // add to master list
943 sAllImages
.push_back(image
);
946 // update mapped ranges
947 uintptr_t lastSegStart
= 0;
948 uintptr_t lastSegEnd
= 0;
949 for(unsigned int i
=0, e
=image
->segmentCount(); i
< e
; ++i
) {
950 if ( image
->segUnaccessible(i
) )
952 uintptr_t start
= image
->segActualLoadAddress(i
);
953 uintptr_t end
= image
->segActualEndAddress(i
);
954 if ( start
== lastSegEnd
) {
955 // two segments are contiguous, just record combined segments
959 // non-contiguous segments, record last (if any)
960 if ( lastSegEnd
!= 0 )
961 addMappedRange(image
, lastSegStart
, lastSegEnd
);
962 lastSegStart
= start
;
966 if ( lastSegEnd
!= 0 )
967 addMappedRange(image
, lastSegStart
, lastSegEnd
);
970 if ( sEnv
.DYLD_PRINT_LIBRARIES
|| (sEnv
.DYLD_PRINT_LIBRARIES_POST_LAUNCH
&& (sMainExecutable
!=NULL
) && sMainExecutable
->isLinked()) ) {
971 dyld::log("dyld: loaded: %s\n", image
->getPath());
977 // Helper for std::remove_if
981 RefUsesImage(ImageLoader
* image
) : _image(image
) {}
982 bool operator()(const ImageLoader::DynamicReference
& ref
) const {
983 return ( (ref
.from
== _image
) || (ref
.to
== _image
) );
991 void removeImage(ImageLoader
* image
)
993 // if has dtrace DOF section, tell dtrace it is going away, then remove from sImageFilesNeedingDOFUnregistration
994 for (std::vector
<RegisteredDOF
>::iterator it
=sImageFilesNeedingDOFUnregistration
.begin(); it
!= sImageFilesNeedingDOFUnregistration
.end(); ) {
995 if ( it
->mh
== image
->machHeader() ) {
996 unregisterDOF(it
->registrationID
);
997 sImageFilesNeedingDOFUnregistration
.erase(it
);
998 // don't increment iterator, the erase caused next element to be copied to where this iterator points
1005 // tell all registered remove image handlers about this
1006 // do this before removing image from internal data structures so that the callback can query dyld about the image
1007 if ( image
->getState() >= dyld_image_state_bound
) {
1008 sRemoveImageCallbacksInUse
= true; // This only runs inside dyld's global lock, so ok to use a global for the in-use flag.
1009 for (std::vector
<ImageCallback
>::iterator it
=sRemoveImageCallbacks
.begin(); it
!= sRemoveImageCallbacks
.end(); it
++) {
1010 (*it
)(image
->machHeader(), image
->getSlide());
1012 sRemoveImageCallbacksInUse
= false;
1016 notifySingle(dyld_image_state_terminated
, image
);
1018 // remove from mapped images table
1019 removedMappedRanges(image
);
1021 // remove from master list
1023 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
1024 if ( *it
== image
) {
1025 sAllImages
.erase(it
);
1031 // remove from sDynamicReferences
1032 sDynamicReferences
.erase(std::remove_if(sDynamicReferences
.begin(), sDynamicReferences
.end(), RefUsesImage(image
)), sDynamicReferences
.end());
1034 // flush find-by-address cache (do this after removed from master list, so there is no chance it can come back)
1035 if ( sLastImageByAddressCache
== image
)
1036 sLastImageByAddressCache
= NULL
;
1038 // if in root list, pull it out
1039 for (std::vector
<ImageLoader
*>::iterator it
=sImageRoots
.begin(); it
!= sImageRoots
.end(); it
++) {
1040 if ( *it
== image
) {
1041 sImageRoots
.erase(it
);
1047 if ( sEnv
.DYLD_PRINT_LIBRARIES
|| (sEnv
.DYLD_PRINT_LIBRARIES_POST_LAUNCH
&& (sMainExecutable
!=NULL
) && sMainExecutable
->isLinked()) ) {
1048 dyld::log("dyld: unloaded: %s\n", image
->getPath());
1051 // tell gdb, new way
1052 removeImageFromAllImages(image
->machHeader());
1056 void runImageStaticTerminators(ImageLoader
* image
)
1058 // if in termination list, pull it out and run terminator
1061 mightBeMore
= false;
1062 for (std::vector
<ImageLoader
*>::iterator it
=sImageFilesNeedingTermination
.begin(); it
!= sImageFilesNeedingTermination
.end(); it
++) {
1063 if ( *it
== image
) {
1064 sImageFilesNeedingTermination
.erase(it
);
1065 if (gLogAPIs
) dyld::log("dlclose(), running static terminators for %p %s\n", image
, image
->getShortName());
1066 image
->doTermination(gLinkContext
);
1071 } while ( mightBeMore
);
1074 static void terminationRecorder(ImageLoader
* image
)
1076 sImageFilesNeedingTermination
.push_back(image
);
1079 const char* getExecutablePath()
1084 static void runAllStaticTerminators(void* extra
)
1087 const size_t imageCount
= sImageFilesNeedingTermination
.size();
1088 for(size_t i
=imageCount
; i
> 0; --i
){
1089 ImageLoader
* image
= sImageFilesNeedingTermination
[i
-1];
1090 image
->doTermination(gLinkContext
);
1092 sImageFilesNeedingTermination
.clear();
1093 notifyBatch(dyld_image_state_terminated
);
1095 catch (const char* msg
) {
1100 void initializeMainExecutable()
1102 // record that we've reached this step
1103 gLinkContext
.startedInitializingMainExecutable
= true;
1105 // run initialzers for any inserted dylibs
1106 ImageLoader::InitializerTimingList initializerTimes
[sAllImages
.size()];
1107 initializerTimes
[0].count
= 0;
1108 const size_t rootCount
= sImageRoots
.size();
1109 if ( rootCount
> 1 ) {
1110 for(size_t i
=1; i
< rootCount
; ++i
) {
1111 sImageRoots
[i
]->runInitializers(gLinkContext
, initializerTimes
[0]);
1115 // run initializers for main executable and everything it brings up
1116 sMainExecutable
->runInitializers(gLinkContext
, initializerTimes
[0]);
1118 // register cxa_atexit() handler to run static terminators in all loaded images when this process exits
1119 if ( gLibSystemHelpers
!= NULL
)
1120 (*gLibSystemHelpers
->cxa_atexit
)(&runAllStaticTerminators
, NULL
, NULL
);
1122 // dump info if requested
1123 if ( sEnv
.DYLD_PRINT_STATISTICS
)
1124 ImageLoaderMachO::printStatistics((unsigned int)sAllImages
.size(), initializerTimes
[0]);
1127 bool mainExecutablePrebound()
1129 return sMainExecutable
->usablePrebinding(gLinkContext
);
1132 ImageLoader
* mainExecutable()
1134 return sMainExecutable
;
1140 #if SUPPORT_VERSIONED_PATHS
1142 // forward reference
1143 static bool getDylibVersionAndInstallname(const char* dylibPath
, uint32_t* version
, char* installName
);
1147 // Examines a dylib file and if its current_version is newer than the installed
1148 // dylib at its install_name, then add the dylib file to sDylibOverrides.
1150 static void checkDylibOverride(const char* dylibFile
)
1152 //dyld::log("checkDylibOverride('%s')\n", dylibFile);
1153 uint32_t altVersion
;
1154 char sysInstallName
[PATH_MAX
];
1155 if ( getDylibVersionAndInstallname(dylibFile
, &altVersion
, sysInstallName
) ) {
1156 //dyld::log("%s has version 0x%08X and install name %s\n", dylibFile, altVersion, sysInstallName);
1157 uint32_t sysVersion
;
1158 if ( getDylibVersionAndInstallname(sysInstallName
, &sysVersion
, NULL
) ) {
1159 //dyld::log("%s has version 0x%08X\n", sysInstallName, sysVersion);
1160 if ( altVersion
> sysVersion
) {
1161 //dyld::log("override found: %s -> %s\n", sysInstallName, dylibFile);
1162 // see if there already is an override for this dylib
1163 bool entryExists
= false;
1164 for (std::vector
<DylibOverride
>::iterator it
= sDylibOverrides
.begin(); it
!= sDylibOverrides
.end(); ++it
) {
1165 if ( strcmp(it
->installName
, sysInstallName
) == 0 ) {
1167 uint32_t prevVersion
;
1168 if ( getDylibVersionAndInstallname(it
->override
, &prevVersion
, NULL
) ) {
1169 if ( altVersion
> prevVersion
) {
1170 // found an even newer override
1171 free((void*)(it
->override
));
1172 char resolvedPath
[PATH_MAX
];
1173 if ( realpath(dylibFile
, resolvedPath
) != NULL
)
1174 it
->override
= strdup(resolvedPath
);
1176 it
->override
= strdup(dylibFile
);
1182 if ( ! entryExists
) {
1183 DylibOverride entry
;
1184 entry
.installName
= strdup(sysInstallName
);
1185 char resolvedPath
[PATH_MAX
];
1186 if ( realpath(dylibFile
, resolvedPath
) != NULL
)
1187 entry
.override
= strdup(resolvedPath
);
1189 entry
.override
= strdup(dylibFile
);
1190 sDylibOverrides
.push_back(entry
);
1191 //dyld::log("added override: %s -> %s\n", entry.installName, entry.override);
1199 static void checkDylibOverridesInDir(const char* dirPath
)
1201 //dyld::log("checkDylibOverridesInDir('%s')\n", dirPath);
1202 char dylibPath
[PATH_MAX
];
1203 int dirPathLen
= strlen(dirPath
);
1204 strlcpy(dylibPath
, dirPath
, PATH_MAX
);
1205 DIR* dirp
= opendir(dirPath
);
1206 if ( dirp
!= NULL
) {
1208 dirent
* entp
= NULL
;
1209 while ( readdir_r(dirp
, &entry
, &entp
) == 0 ) {
1212 if ( entp
->d_type
!= DT_REG
)
1214 dylibPath
[dirPathLen
] = '/';
1215 dylibPath
[dirPathLen
+1] = '\0';
1216 if ( strlcat(dylibPath
, entp
->d_name
, PATH_MAX
) > PATH_MAX
)
1218 checkDylibOverride(dylibPath
);
1225 static void checkFrameworkOverridesInDir(const char* dirPath
)
1227 //dyld::log("checkFrameworkOverridesInDir('%s')\n", dirPath);
1228 char frameworkPath
[PATH_MAX
];
1229 int dirPathLen
= strlen(dirPath
);
1230 strlcpy(frameworkPath
, dirPath
, PATH_MAX
);
1231 DIR* dirp
= opendir(dirPath
);
1232 if ( dirp
!= NULL
) {
1234 dirent
* entp
= NULL
;
1235 while ( readdir_r(dirp
, &entry
, &entp
) == 0 ) {
1238 if ( entp
->d_type
!= DT_DIR
)
1240 frameworkPath
[dirPathLen
] = '/';
1241 frameworkPath
[dirPathLen
+1] = '\0';
1242 int dirNameLen
= strlen(entp
->d_name
);
1243 if ( dirNameLen
< 11 )
1245 if ( strcmp(&entp
->d_name
[dirNameLen
-10], ".framework") != 0 )
1247 if ( strlcat(frameworkPath
, entp
->d_name
, PATH_MAX
) > PATH_MAX
)
1249 if ( strlcat(frameworkPath
, "/", PATH_MAX
) > PATH_MAX
)
1251 if ( strlcat(frameworkPath
, entp
->d_name
, PATH_MAX
) > PATH_MAX
)
1253 frameworkPath
[strlen(frameworkPath
)-10] = '\0';
1254 checkDylibOverride(frameworkPath
);
1259 #endif // SUPPORT_VERSIONED_PATHS
1263 // Turns a colon separated list of strings into a NULL terminated array
1264 // of string pointers. If mainExecutableDir param is not NULL,
1265 // substitutes @loader_path with main executable's dir.
1267 static const char** parseColonList(const char* list
, const char* mainExecutableDir
)
1269 static const char* sEmptyList
[] = { NULL
};
1271 if ( list
[0] == '\0' )
1275 for(const char* s
=list
; *s
!= '\0'; ++s
) {
1281 const char* start
= list
;
1282 char** result
= new char*[colonCount
+2];
1283 for(const char* s
=list
; *s
!= '\0'; ++s
) {
1285 size_t len
= s
-start
;
1286 if ( (mainExecutableDir
!= NULL
) && (strncmp(start
, "@loader_path/", 13) == 0) ) {
1287 size_t mainExecDirLen
= strlen(mainExecutableDir
);
1288 char* str
= new char[mainExecDirLen
+len
+1];
1289 strcpy(str
, mainExecutableDir
);
1290 strlcat(str
, &start
[13], mainExecDirLen
+len
+1);
1291 str
[mainExecDirLen
+len
-13] = '\0';
1293 result
[index
++] = str
;
1295 else if ( (mainExecutableDir
!= NULL
) && (strncmp(start
, "@executable_path/", 17) == 0) ) {
1296 size_t mainExecDirLen
= strlen(mainExecutableDir
);
1297 char* str
= new char[mainExecDirLen
+len
+1];
1298 strcpy(str
, mainExecutableDir
);
1299 strlcat(str
, &start
[17], mainExecDirLen
+len
+1);
1300 str
[mainExecDirLen
+len
-17] = '\0';
1302 result
[index
++] = str
;
1305 char* str
= new char[len
+1];
1306 strncpy(str
, start
, len
);
1309 result
[index
++] = str
;
1313 size_t len
= strlen(start
);
1314 if ( (mainExecutableDir
!= NULL
) && (strncmp(start
, "@loader_path/", 13) == 0) ) {
1315 size_t mainExecDirLen
= strlen(mainExecutableDir
);
1316 char* str
= new char[mainExecDirLen
+len
+1];
1317 strcpy(str
, mainExecutableDir
);
1318 strlcat(str
, &start
[13], mainExecDirLen
+len
+1);
1319 str
[mainExecDirLen
+len
-13] = '\0';
1320 result
[index
++] = str
;
1322 else if ( (mainExecutableDir
!= NULL
) && (strncmp(start
, "@executable_path/", 17) == 0) ) {
1323 size_t mainExecDirLen
= strlen(mainExecutableDir
);
1324 char* str
= new char[mainExecDirLen
+len
+1];
1325 strcpy(str
, mainExecutableDir
);
1326 strlcat(str
, &start
[17], mainExecDirLen
+len
+1);
1327 str
[mainExecDirLen
+len
-17] = '\0';
1328 result
[index
++] = str
;
1331 char* str
= new char[len
+1];
1333 result
[index
++] = str
;
1335 result
[index
] = NULL
;
1337 //dyld::log("parseColonList(%s)\n", list);
1338 //for(int i=0; result[i] != NULL; ++i)
1339 // dyld::log(" %s\n", result[i]);
1340 return (const char**)result
;
1343 static void appendParsedColonList(const char* list
, const char* mainExecutableDir
, const char* const ** storage
)
1345 const char** newlist
= parseColonList(list
, mainExecutableDir
);
1346 if ( *storage
== NULL
) {
1347 // first time, just set
1351 // need to append to existing list
1352 const char* const* existing
= *storage
;
1354 for(int i
=0; existing
[i
] != NULL
; ++i
)
1356 for(int i
=0; newlist
[i
] != NULL
; ++i
)
1358 const char** combinedList
= new const char*[count
+2];
1360 for(int i
=0; existing
[i
] != NULL
; ++i
)
1361 combinedList
[index
++] = existing
[i
];
1362 for(int i
=0; newlist
[i
] != NULL
; ++i
)
1363 combinedList
[index
++] = newlist
[i
];
1364 combinedList
[index
] = NULL
;
1366 *storage
= combinedList
;
1371 static void paths_expand_roots(const char **paths
, const char *key
, const char *val
)
1373 // assert(val != NULL);
1374 // assert(paths != NULL);
1376 size_t keyLen
= strlen(key
);
1377 for(int i
=0; paths
[i
] != NULL
; ++i
) {
1378 if ( strncmp(paths
[i
], key
, keyLen
) == 0 ) {
1379 char* newPath
= new char[strlen(val
) + (strlen(paths
[i
]) - keyLen
) + 1];
1380 strcpy(newPath
, val
);
1381 strcat(newPath
, &paths
[i
][keyLen
]);
1389 static void removePathWithPrefix(const char* paths
[], const char* prefix
)
1391 size_t prefixLen
= strlen(prefix
);
1394 for(i
= 0; paths
[i
] != NULL
; ++i
) {
1395 if ( strncmp(paths
[i
], prefix
, prefixLen
) == 0 )
1398 paths
[i
-skip
] = paths
[i
];
1400 paths
[i
-skip
] = NULL
;
1405 static void paths_dump(const char **paths
)
1407 // assert(paths != NULL);
1408 const char **strs
= paths
;
1409 while(*strs
!= NULL
)
1411 dyld::log("\"%s\"\n", *strs
);
1418 static void printOptions(const char* argv
[])
1421 while ( NULL
!= argv
[i
] ) {
1422 dyld::log("opt[%i] = \"%s\"\n", i
, argv
[i
]);
1427 static void printEnvironmentVariables(const char* envp
[])
1429 while ( NULL
!= *envp
) {
1430 dyld::log("%s\n", *envp
);
1435 void processDyldEnvironmentVariable(const char* key
, const char* value
, const char* mainExecutableDir
)
1437 if ( strcmp(key
, "DYLD_FRAMEWORK_PATH") == 0 ) {
1438 appendParsedColonList(value
, mainExecutableDir
, &sEnv
.DYLD_FRAMEWORK_PATH
);
1440 else if ( strcmp(key
, "DYLD_FALLBACK_FRAMEWORK_PATH") == 0 ) {
1441 appendParsedColonList(value
, mainExecutableDir
, &sEnv
.DYLD_FALLBACK_FRAMEWORK_PATH
);
1443 else if ( strcmp(key
, "DYLD_LIBRARY_PATH") == 0 ) {
1444 appendParsedColonList(value
, mainExecutableDir
, &sEnv
.DYLD_LIBRARY_PATH
);
1446 else if ( strcmp(key
, "DYLD_FALLBACK_LIBRARY_PATH") == 0 ) {
1447 appendParsedColonList(value
, mainExecutableDir
, &sEnv
.DYLD_FALLBACK_LIBRARY_PATH
);
1449 else if ( (strcmp(key
, "DYLD_ROOT_PATH") == 0) || (strcmp(key
, "DYLD_PATHS_ROOT") == 0) ) {
1450 if ( strcmp(value
, "/") != 0 ) {
1451 gLinkContext
.rootPaths
= parseColonList(value
, mainExecutableDir
);
1452 for (int i
=0; gLinkContext
.rootPaths
[i
] != NULL
; ++i
) {
1453 if ( gLinkContext
.rootPaths
[i
][0] != '/' ) {
1454 dyld::warn("DYLD_ROOT_PATH not used because it contains a non-absolute path\n");
1455 gLinkContext
.rootPaths
= NULL
;
1461 else if ( strcmp(key
, "DYLD_IMAGE_SUFFIX") == 0 ) {
1462 gLinkContext
.imageSuffix
= value
;
1464 else if ( strcmp(key
, "DYLD_INSERT_LIBRARIES") == 0 ) {
1465 sEnv
.DYLD_INSERT_LIBRARIES
= parseColonList(value
, NULL
);
1467 else if ( strcmp(key
, "DYLD_PRINT_OPTS") == 0 ) {
1468 sEnv
.DYLD_PRINT_OPTS
= true;
1470 else if ( strcmp(key
, "DYLD_PRINT_ENV") == 0 ) {
1471 sEnv
.DYLD_PRINT_ENV
= true;
1473 else if ( strcmp(key
, "DYLD_DISABLE_DOFS") == 0 ) {
1474 sEnv
.DYLD_DISABLE_DOFS
= true;
1476 else if ( strcmp(key
, "DYLD_DISABLE_PREFETCH") == 0 ) {
1477 gLinkContext
.preFetchDisabled
= true;
1479 else if ( strcmp(key
, "DYLD_PRINT_LIBRARIES") == 0 ) {
1480 sEnv
.DYLD_PRINT_LIBRARIES
= true;
1482 else if ( strcmp(key
, "DYLD_PRINT_LIBRARIES_POST_LAUNCH") == 0 ) {
1483 sEnv
.DYLD_PRINT_LIBRARIES_POST_LAUNCH
= true;
1485 else if ( strcmp(key
, "DYLD_BIND_AT_LAUNCH") == 0 ) {
1486 sEnv
.DYLD_BIND_AT_LAUNCH
= true;
1488 else if ( strcmp(key
, "DYLD_FORCE_FLAT_NAMESPACE") == 0 ) {
1489 gLinkContext
.bindFlat
= true;
1491 else if ( strcmp(key
, "DYLD_NEW_LOCAL_SHARED_REGIONS") == 0 ) {
1492 // ignore, no longer relevant but some scripts still set it
1494 else if ( strcmp(key
, "DYLD_NO_FIX_PREBINDING") == 0 ) {
1496 else if ( strcmp(key
, "DYLD_PREBIND_DEBUG") == 0 ) {
1497 gLinkContext
.verbosePrebinding
= true;
1499 else if ( strcmp(key
, "DYLD_PRINT_INITIALIZERS") == 0 ) {
1500 gLinkContext
.verboseInit
= true;
1502 else if ( strcmp(key
, "DYLD_PRINT_DOFS") == 0 ) {
1503 gLinkContext
.verboseDOF
= true;
1505 else if ( strcmp(key
, "DYLD_PRINT_STATISTICS") == 0 ) {
1506 sEnv
.DYLD_PRINT_STATISTICS
= true;
1508 else if ( strcmp(key
, "DYLD_PRINT_SEGMENTS") == 0 ) {
1509 gLinkContext
.verboseMapping
= true;
1511 else if ( strcmp(key
, "DYLD_PRINT_BINDINGS") == 0 ) {
1512 gLinkContext
.verboseBind
= true;
1514 else if ( strcmp(key
, "DYLD_PRINT_WEAK_BINDINGS") == 0 ) {
1515 gLinkContext
.verboseWeakBind
= true;
1517 else if ( strcmp(key
, "DYLD_PRINT_REBASINGS") == 0 ) {
1518 gLinkContext
.verboseRebase
= true;
1520 else if ( strcmp(key
, "DYLD_PRINT_APIS") == 0 ) {
1523 else if ( strcmp(key
, "DYLD_PRINT_WARNINGS") == 0 ) {
1524 gLinkContext
.verboseWarnings
= true;
1526 else if ( strcmp(key
, "DYLD_PRINT_RPATHS") == 0 ) {
1527 gLinkContext
.verboseRPaths
= true;
1529 else if ( strcmp(key
, "DYLD_PRINT_CS_NOTIFICATIONS") == 0 ) {
1530 sEnv
.DYLD_PRINT_CS_NOTIFICATIONS
= true;
1532 else if ( strcmp(key
, "DYLD_PRINT_INTERPOSING") == 0 ) {
1533 gLinkContext
.verboseInterposing
= true;
1535 else if ( strcmp(key
, "DYLD_PRINT_CODE_SIGNATURES") == 0 ) {
1536 gLinkContext
.verboseCodeSignatures
= true;
1538 else if ( strcmp(key
, "DYLD_SHARED_REGION") == 0 ) {
1539 if ( strcmp(value
, "private") == 0 ) {
1540 gLinkContext
.sharedRegionMode
= ImageLoader::kUsePrivateSharedRegion
;
1542 else if ( strcmp(value
, "avoid") == 0 ) {
1543 gLinkContext
.sharedRegionMode
= ImageLoader::kDontUseSharedRegion
;
1545 else if ( strcmp(value
, "use") == 0 ) {
1546 gLinkContext
.sharedRegionMode
= ImageLoader::kUseSharedRegion
;
1548 else if ( value
[0] == '\0' ) {
1549 gLinkContext
.sharedRegionMode
= ImageLoader::kUseSharedRegion
;
1552 dyld::warn("unknown option to DYLD_SHARED_REGION. Valid options are: use, private, avoid\n");
1555 #if DYLD_SHARED_CACHE_SUPPORT
1556 else if ( strcmp(key
, "DYLD_SHARED_CACHE_DIR") == 0 ) {
1557 sSharedCacheDir
= value
;
1559 else if ( strcmp(key
, "DYLD_SHARED_CACHE_DONT_VALIDATE") == 0 ) {
1560 sSharedCacheIgnoreInodeAndTimeStamp
= true;
1563 else if ( strcmp(key
, "DYLD_IGNORE_PREBINDING") == 0 ) {
1564 if ( strcmp(value
, "all") == 0 ) {
1565 gLinkContext
.prebindUsage
= ImageLoader::kUseNoPrebinding
;
1567 else if ( strcmp(value
, "app") == 0 ) {
1568 gLinkContext
.prebindUsage
= ImageLoader::kUseAllButAppPredbinding
;
1570 else if ( strcmp(value
, "nonsplit") == 0 ) {
1571 gLinkContext
.prebindUsage
= ImageLoader::kUseSplitSegPrebinding
;
1573 else if ( value
[0] == '\0' ) {
1574 gLinkContext
.prebindUsage
= ImageLoader::kUseSplitSegPrebinding
;
1577 dyld::warn("unknown option to DYLD_IGNORE_PREBINDING. Valid options are: all, app, nonsplit\n");
1580 #if SUPPORT_VERSIONED_PATHS
1581 else if ( strcmp(key
, "DYLD_VERSIONED_LIBRARY_PATH") == 0 ) {
1582 appendParsedColonList(value
, mainExecutableDir
, &sEnv
.DYLD_VERSIONED_LIBRARY_PATH
);
1584 else if ( strcmp(key
, "DYLD_VERSIONED_FRAMEWORK_PATH") == 0 ) {
1585 appendParsedColonList(value
, mainExecutableDir
, &sEnv
.DYLD_VERSIONED_FRAMEWORK_PATH
);
1588 #if !TARGET_IPHONE_SIMULATOR
1589 else if ( (strcmp(key
, "DYLD_PRINT_TO_FILE") == 0) && (mainExecutableDir
== NULL
) ) {
1590 int fd
= open(value
, O_WRONLY
| O_CREAT
| O_APPEND
, 0644);
1596 dyld::log("dyld: could not open DYLD_PRINT_TO_FILE='%s', errno=%d\n", value
, errno
);
1601 dyld::warn("unknown environment variable: %s\n", key
);
1606 #if SUPPORT_LC_DYLD_ENVIRONMENT
1607 static void checkLoadCommandEnvironmentVariables()
1609 // <rdar://problem/8440934> Support augmenting dyld environment variables in load commands
1610 const uint32_t cmd_count
= sMainExecutableMachHeader
->ncmds
;
1611 const struct load_command
* const cmds
= (struct load_command
*)(((char*)sMainExecutableMachHeader
)+sizeof(macho_header
));
1612 const struct load_command
* cmd
= cmds
;
1613 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
1615 case LC_DYLD_ENVIRONMENT
:
1617 const struct dylinker_command
* envcmd
= (struct dylinker_command
*)cmd
;
1618 const char* keyEqualsValue
= (char*)envcmd
+ envcmd
->name
.offset
;
1619 char mainExecutableDir
[strlen(sExecPath
)+2];
1620 strcpy(mainExecutableDir
, sExecPath
);
1621 char* lastSlash
= strrchr(mainExecutableDir
, '/');
1622 if ( lastSlash
!= NULL
)
1623 lastSlash
[1] = '\0';
1624 // only process variables that start with DYLD_ and end in _PATH
1625 if ( (strncmp(keyEqualsValue
, "DYLD_", 5) == 0) ) {
1626 const char* equals
= strchr(keyEqualsValue
, '=');
1627 if ( equals
!= NULL
) {
1628 if ( strncmp(&equals
[-5], "_PATH", 5) == 0 ) {
1629 const char* value
= &equals
[1];
1630 const size_t keyLen
= equals
-keyEqualsValue
;
1632 strncpy(key
, keyEqualsValue
, keyLen
);
1634 //dyld::log("processing: %s\n", keyEqualsValue);
1635 //dyld::log("mainExecutableDir: %s\n", mainExecutableDir);
1636 processDyldEnvironmentVariable(key
, value
, mainExecutableDir
);
1643 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
1646 #endif // SUPPORT_LC_DYLD_ENVIRONMENT
1649 static bool hasCodeSignatureLoadCommand(const macho_header
* mh
)
1651 const uint32_t cmd_count
= mh
->ncmds
;
1652 const struct load_command
* const cmds
= (struct load_command
*)(((char*)mh
)+sizeof(macho_header
));
1653 const struct load_command
* cmd
= cmds
;
1654 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
1655 if (cmd
->cmd
== LC_CODE_SIGNATURE
)
1657 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
1663 #if SUPPORT_VERSIONED_PATHS
1664 static void checkVersionedPaths()
1666 // search DYLD_VERSIONED_LIBRARY_PATH directories for dylibs and check if they are newer
1667 if ( sEnv
.DYLD_VERSIONED_LIBRARY_PATH
!= NULL
) {
1668 for(const char* const* lp
= sEnv
.DYLD_VERSIONED_LIBRARY_PATH
; *lp
!= NULL
; ++lp
) {
1669 checkDylibOverridesInDir(*lp
);
1673 // search DYLD_VERSIONED_FRAMEWORK_PATH directories for dylibs and check if they are newer
1674 if ( sEnv
.DYLD_VERSIONED_FRAMEWORK_PATH
!= NULL
) {
1675 for(const char* const* fp
= sEnv
.DYLD_VERSIONED_FRAMEWORK_PATH
; *fp
!= NULL
; ++fp
) {
1676 checkFrameworkOverridesInDir(*fp
);
1684 // For security, setuid programs ignore DYLD_* environment variables.
1685 // Additionally, the DYLD_* enviroment variables are removed
1686 // from the environment, so that any child processes don't see them.
1688 static void pruneEnvironmentVariables(const char* envp
[], const char*** applep
)
1690 // delete all DYLD_* and LD_LIBRARY_PATH environment variables
1691 int removedCount
= 0;
1692 const char** d
= envp
;
1693 for(const char** s
= envp
; *s
!= NULL
; s
++) {
1694 if ( (strncmp(*s
, "DYLD_", 5) != 0) && (strncmp(*s
, "LD_LIBRARY_PATH=", 16) != 0) ) {
1702 // <rdar://11894054> Disable warnings about DYLD_ env vars being ignored. The warnings are causing too much confusion.
1704 if ( removedCount
!= 0 ) {
1705 dyld::log("dyld: DYLD_ environment variables being ignored because ");
1706 switch (sRestrictedReason
) {
1709 case restrictedBySetGUid
:
1710 dyld::log("main executable (%s) is setuid or setgid\n", sExecPath
);
1712 case restrictedBySegment
:
1713 dyld::log("main executable (%s) has __RESTRICT/__restrict section\n", sExecPath
);
1715 case restrictedByEntitlements
:
1716 dyld::log("main executable (%s) is code signed with entitlements\n", sExecPath
);
1721 // slide apple parameters
1722 if ( removedCount
> 0 ) {
1725 *d
= d
[removedCount
];
1726 } while ( *d
++ != NULL
);
1727 for(int i
=0; i
< removedCount
; ++i
)
1731 // disable framework and library fallback paths for setuid binaries rdar://problem/4589305
1732 sEnv
.DYLD_FALLBACK_FRAMEWORK_PATH
= NULL
;
1733 sEnv
.DYLD_FALLBACK_LIBRARY_PATH
= NULL
;
1735 if ( removedCount
> 0 )
1736 strlcat(sLoadingCrashMessage
, ", ignoring DYLD_* env vars", sizeof(sLoadingCrashMessage
));
1740 static void checkEnvironmentVariables(const char* envp
[], bool ignoreEnviron
)
1742 const char* home
= NULL
;
1744 for(p
= envp
; *p
!= NULL
; p
++) {
1745 const char* keyEqualsValue
= *p
;
1746 if ( strncmp(keyEqualsValue
, "DYLD_", 5) == 0 ) {
1747 const char* equals
= strchr(keyEqualsValue
, '=');
1748 if ( (equals
!= NULL
) && !ignoreEnviron
) {
1749 strlcat(sLoadingCrashMessage
, "\n", sizeof(sLoadingCrashMessage
));
1750 strlcat(sLoadingCrashMessage
, keyEqualsValue
, sizeof(sLoadingCrashMessage
));
1751 const char* value
= &equals
[1];
1752 const size_t keyLen
= equals
-keyEqualsValue
;
1754 strncpy(key
, keyEqualsValue
, keyLen
);
1756 processDyldEnvironmentVariable(key
, value
, NULL
);
1759 else if ( strncmp(keyEqualsValue
, "HOME=", 5) == 0 ) {
1760 home
= &keyEqualsValue
[5];
1762 else if ( strncmp(keyEqualsValue
, "LD_LIBRARY_PATH=", 16) == 0 ) {
1763 const char* path
= &keyEqualsValue
[16];
1764 sEnv
.LD_LIBRARY_PATH
= parseColonList(path
, NULL
);
1768 #if SUPPORT_LC_DYLD_ENVIRONMENT
1769 checkLoadCommandEnvironmentVariables();
1770 #endif // SUPPORT_LC_DYLD_ENVIRONMENT
1772 // default value for DYLD_FALLBACK_FRAMEWORK_PATH, if not set in environment
1773 if ( sEnv
.DYLD_FALLBACK_FRAMEWORK_PATH
== NULL
) {
1774 const char** paths
= sFrameworkFallbackPaths
;
1776 removePathWithPrefix(paths
, "$HOME");
1778 paths_expand_roots(paths
, "$HOME", home
);
1779 sEnv
.DYLD_FALLBACK_FRAMEWORK_PATH
= paths
;
1782 // default value for DYLD_FALLBACK_LIBRARY_PATH, if not set in environment
1783 if ( sEnv
.DYLD_FALLBACK_LIBRARY_PATH
== NULL
) {
1784 const char** paths
= sLibraryFallbackPaths
;
1786 removePathWithPrefix(paths
, "$HOME");
1788 paths_expand_roots(paths
, "$HOME", home
);
1789 sEnv
.DYLD_FALLBACK_LIBRARY_PATH
= paths
;
1792 // <rdar://problem/11281064> DYLD_IMAGE_SUFFIX and DYLD_ROOT_PATH cannot be used together
1793 if ( (gLinkContext
.imageSuffix
!= NULL
) && (gLinkContext
.rootPaths
!= NULL
) ) {
1794 dyld::warn("Ignoring DYLD_IMAGE_SUFFIX because DYLD_ROOT_PATH is used.\n");
1795 gLinkContext
.imageSuffix
= NULL
;
1798 #if SUPPORT_VERSIONED_PATHS
1799 checkVersionedPaths();
1804 static void getHostInfo()
1806 #if CPU_SUBTYPES_SUPPORTED
1808 sHostCPU
= CPU_TYPE_ARM
;
1809 sHostCPUsubtype
= CPU_SUBTYPE_ARM_V7K
;
1810 #elif __ARM_ARCH_7A__
1811 sHostCPU
= CPU_TYPE_ARM
;
1812 sHostCPUsubtype
= CPU_SUBTYPE_ARM_V7
;
1813 #elif __ARM_ARCH_6K__
1814 sHostCPU
= CPU_TYPE_ARM
;
1815 sHostCPUsubtype
= CPU_SUBTYPE_ARM_V6
;
1816 #elif __ARM_ARCH_7F__
1817 sHostCPU
= CPU_TYPE_ARM
;
1818 sHostCPUsubtype
= CPU_SUBTYPE_ARM_V7F
;
1819 #elif __ARM_ARCH_7S__
1820 sHostCPU
= CPU_TYPE_ARM
;
1821 sHostCPUsubtype
= CPU_SUBTYPE_ARM_V7S
;
1823 struct host_basic_info info
;
1824 mach_msg_type_number_t count
= HOST_BASIC_INFO_COUNT
;
1825 mach_port_t hostPort
= mach_host_self();
1826 kern_return_t result
= host_info(hostPort
, HOST_BASIC_INFO
, (host_info_t
)&info
, &count
);
1827 if ( result
!= KERN_SUCCESS
)
1828 throw "host_info() failed";
1829 sHostCPU
= info
.cpu_type
;
1830 sHostCPUsubtype
= info
.cpu_subtype
;
1831 mach_port_deallocate(mach_task_self(), hostPort
);
1836 static void checkSharedRegionDisable()
1838 #if __MAC_OS_X_VERSION_MIN_REQUIRED
1839 // if main executable has segments that overlap the shared region,
1840 // then disable using the shared region
1841 if ( sMainExecutable
->overlapsWithAddressRange((void*)(uintptr_t)SHARED_REGION_BASE
, (void*)(uintptr_t)(SHARED_REGION_BASE
+ SHARED_REGION_SIZE
)) ) {
1842 gLinkContext
.sharedRegionMode
= ImageLoader::kDontUseSharedRegion
;
1843 if ( gLinkContext
.verboseMapping
)
1844 dyld::warn("disabling shared region because main executable overlaps\n");
1847 if ( sProcessIsRestricted
) {
1848 // <rdar://problem/15280847> use private or no shared region for suid processes
1849 gLinkContext
.sharedRegionMode
= ImageLoader::kUsePrivateSharedRegion
;
1853 // iPhoneOS cannot run without shared region
1856 bool validImage(const ImageLoader
* possibleImage
)
1858 const size_t imageCount
= sAllImages
.size();
1859 for(size_t i
=0; i
< imageCount
; ++i
) {
1860 if ( possibleImage
== sAllImages
[i
] ) {
1867 uint32_t getImageCount()
1869 return (uint32_t)sAllImages
.size();
1872 ImageLoader
* getIndexedImage(unsigned int index
)
1874 if ( index
< sAllImages
.size() )
1875 return sAllImages
[index
];
1879 ImageLoader
* findImageByMachHeader(const struct mach_header
* target
)
1881 return findMappedRange((uintptr_t)target
);
1885 ImageLoader
* findImageContainingAddress(const void* addr
)
1887 return findMappedRange((uintptr_t)addr
);
1891 ImageLoader
* findImageContainingSymbol(const void* symbol
)
1893 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
1894 ImageLoader
* anImage
= *it
;
1895 if ( anImage
->containsSymbol(symbol
) )
1903 void forEachImageDo( void (*callback
)(ImageLoader
*, void* userData
), void* userData
)
1905 const size_t imageCount
= sAllImages
.size();
1906 for(size_t i
=0; i
< imageCount
; ++i
) {
1907 ImageLoader
* anImage
= sAllImages
[i
];
1908 (*callback
)(anImage
, userData
);
1912 ImageLoader
* findLoadedImage(const struct stat
& stat_buf
)
1914 const size_t imageCount
= sAllImages
.size();
1915 for(size_t i
=0; i
< imageCount
; ++i
){
1916 ImageLoader
* anImage
= sAllImages
[i
];
1917 if ( anImage
->statMatch(stat_buf
) )
1923 // based on ANSI-C strstr()
1924 static const char* strrstr(const char* str
, const char* sub
)
1926 const size_t sublen
= strlen(sub
);
1927 for(const char* p
= &str
[strlen(str
)]; p
!= str
; --p
) {
1928 if ( strncmp(p
, sub
, sublen
) == 0 )
1936 // Find framework path
1938 // /path/foo.framework/foo => foo.framework/foo
1939 // /path/foo.framework/Versions/A/foo => foo.framework/Versions/A/foo
1940 // /path/foo.framework/Frameworks/bar.framework/bar => bar.framework/bar
1941 // /path/foo.framework/Libraries/bar.dylb => NULL
1942 // /path/foo.framework/bar => NULL
1944 // Returns NULL if not a framework path
1946 static const char* getFrameworkPartialPath(const char* path
)
1948 const char* dirDot
= strrstr(path
, ".framework/");
1949 if ( dirDot
!= NULL
) {
1950 const char* dirStart
= dirDot
;
1951 for ( ; dirStart
>= path
; --dirStart
) {
1952 if ( (*dirStart
== '/') || (dirStart
== path
) ) {
1953 const char* frameworkStart
= &dirStart
[1];
1954 if ( dirStart
== path
)
1956 size_t len
= dirDot
- frameworkStart
;
1957 char framework
[len
+1];
1958 strncpy(framework
, frameworkStart
, len
);
1959 framework
[len
] = '\0';
1960 const char* leaf
= strrchr(path
, '/');
1961 if ( leaf
!= NULL
) {
1962 if ( strcmp(framework
, &leaf
[1]) == 0 ) {
1963 return frameworkStart
;
1965 if ( gLinkContext
.imageSuffix
!= NULL
) {
1966 // some debug frameworks have install names that end in _debug
1967 if ( strncmp(framework
, &leaf
[1], len
) == 0 ) {
1968 if ( strcmp( gLinkContext
.imageSuffix
, &leaf
[len
+1]) == 0 )
1969 return frameworkStart
;
1980 static const char* getLibraryLeafName(const char* path
)
1982 const char* start
= strrchr(path
, '/');
1983 if ( start
!= NULL
)
1990 // only for architectures that use cpu-sub-types
1991 #if CPU_SUBTYPES_SUPPORTED
1993 const cpu_subtype_t CPU_SUBTYPE_END_OF_LIST
= -1;
1997 // A fat file may contain multiple sub-images for the same CPU type.
1998 // In that case, dyld picks which sub-image to use by scanning a table
1999 // of preferred cpu-sub-types for the running cpu.
2001 // There is one row in the table for each cpu-sub-type on which dyld might run.
2002 // The first entry in a row is that cpu-sub-type. It is followed by all
2003 // cpu-sub-types that can run on that cpu, if preferred order. Each row ends with
2004 // a "SUBTYPE_ALL" (to denote that images written to run on any cpu-sub-type are usable),
2005 // followed by one or more CPU_SUBTYPE_END_OF_LIST to pad out this row.
2011 // ARM sub-type lists
2013 const int kARM_RowCount
= 8;
2014 static const cpu_subtype_t kARM
[kARM_RowCount
][9] = {
2016 // armv7f can run: v7f, v7, v6, v5, and v4
2017 { CPU_SUBTYPE_ARM_V7F
, CPU_SUBTYPE_ARM_V7
, CPU_SUBTYPE_ARM_V6
, CPU_SUBTYPE_ARM_V5TEJ
, CPU_SUBTYPE_ARM_V4T
, CPU_SUBTYPE_ARM_ALL
, CPU_SUBTYPE_END_OF_LIST
},
2019 // armv7k can run: v7k
2020 { CPU_SUBTYPE_ARM_V7K
, CPU_SUBTYPE_END_OF_LIST
},
2022 // armv7s can run: v7s, v7, v7f, v7k, v6, v5, and v4
2023 { CPU_SUBTYPE_ARM_V7S
, CPU_SUBTYPE_ARM_V7
, CPU_SUBTYPE_ARM_V7F
, CPU_SUBTYPE_ARM_V6
, CPU_SUBTYPE_ARM_V5TEJ
, CPU_SUBTYPE_ARM_V4T
, CPU_SUBTYPE_ARM_ALL
, CPU_SUBTYPE_END_OF_LIST
},
2025 // armv7 can run: v7, v6, v5, and v4
2026 { CPU_SUBTYPE_ARM_V7
, CPU_SUBTYPE_ARM_V6
, CPU_SUBTYPE_ARM_V5TEJ
, CPU_SUBTYPE_ARM_V4T
, CPU_SUBTYPE_ARM_ALL
, CPU_SUBTYPE_END_OF_LIST
},
2028 // armv6 can run: v6, v5, and v4
2029 { CPU_SUBTYPE_ARM_V6
, CPU_SUBTYPE_ARM_V5TEJ
, CPU_SUBTYPE_ARM_V4T
, CPU_SUBTYPE_ARM_ALL
, CPU_SUBTYPE_END_OF_LIST
, CPU_SUBTYPE_END_OF_LIST
},
2031 // xscale can run: xscale, v5, and v4
2032 { CPU_SUBTYPE_ARM_XSCALE
, CPU_SUBTYPE_ARM_V5TEJ
, CPU_SUBTYPE_ARM_V4T
, CPU_SUBTYPE_ARM_ALL
, CPU_SUBTYPE_END_OF_LIST
, CPU_SUBTYPE_END_OF_LIST
},
2034 // armv5 can run: v5 and v4
2035 { CPU_SUBTYPE_ARM_V5TEJ
, CPU_SUBTYPE_ARM_V4T
, CPU_SUBTYPE_ARM_ALL
, CPU_SUBTYPE_END_OF_LIST
, CPU_SUBTYPE_END_OF_LIST
, CPU_SUBTYPE_END_OF_LIST
},
2037 // armv4 can run: v4
2038 { CPU_SUBTYPE_ARM_V4T
, CPU_SUBTYPE_ARM_ALL
, CPU_SUBTYPE_END_OF_LIST
, CPU_SUBTYPE_END_OF_LIST
, CPU_SUBTYPE_END_OF_LIST
, CPU_SUBTYPE_END_OF_LIST
},
2044 // x86_64 sub-type lists
2046 const int kX86_64_RowCount
= 2;
2047 static const cpu_subtype_t kX86_64
[kX86_64_RowCount
][5] = {
2049 // x86_64h can run: x86_64h, x86_64h(lib), x86_64(lib), and x86_64
2050 { CPU_SUBTYPE_X86_64_H
, CPU_SUBTYPE_LIB64
|CPU_SUBTYPE_X86_64_H
, CPU_SUBTYPE_LIB64
|CPU_SUBTYPE_X86_64_ALL
, CPU_SUBTYPE_X86_64_ALL
, CPU_SUBTYPE_END_OF_LIST
},
2052 // x86_64 can run: x86_64(lib) and x86_64
2053 { CPU_SUBTYPE_X86_64_ALL
, CPU_SUBTYPE_LIB64
|CPU_SUBTYPE_X86_64_ALL
, CPU_SUBTYPE_END_OF_LIST
},
2059 // scan the tables above to find the cpu-sub-type-list for this machine
2060 static const cpu_subtype_t
* findCPUSubtypeList(cpu_type_t cpu
, cpu_subtype_t subtype
)
2065 for (int i
=0; i
< kARM_RowCount
; ++i
) {
2066 if ( kARM
[i
][0] == subtype
)
2072 case CPU_TYPE_X86_64
:
2073 for (int i
=0; i
< kX86_64_RowCount
; ++i
) {
2074 if ( kX86_64
[i
][0] == subtype
)
2086 // scan fat table-of-contents for best most preferred subtype
2087 static bool fatFindBestFromOrderedList(cpu_type_t cpu
, const cpu_subtype_t list
[], const fat_header
* fh
, uint64_t* offset
, uint64_t* len
)
2089 const fat_arch
* const archs
= (fat_arch
*)(((char*)fh
)+sizeof(fat_header
));
2090 for (uint32_t subTypeIndex
=0; list
[subTypeIndex
] != CPU_SUBTYPE_END_OF_LIST
; ++subTypeIndex
) {
2091 for(uint32_t fatIndex
=0; fatIndex
< OSSwapBigToHostInt32(fh
->nfat_arch
); ++fatIndex
) {
2092 if ( ((cpu_type_t
)OSSwapBigToHostInt32(archs
[fatIndex
].cputype
) == cpu
)
2093 && (list
[subTypeIndex
] == (cpu_subtype_t
)OSSwapBigToHostInt32(archs
[fatIndex
].cpusubtype
)) ) {
2094 *offset
= OSSwapBigToHostInt32(archs
[fatIndex
].offset
);
2095 *len
= OSSwapBigToHostInt32(archs
[fatIndex
].size
);
2103 // scan fat table-of-contents for exact match of cpu and cpu-sub-type
2104 static bool fatFindExactMatch(cpu_type_t cpu
, cpu_subtype_t subtype
, const fat_header
* fh
, uint64_t* offset
, uint64_t* len
)
2106 const fat_arch
* archs
= (fat_arch
*)(((char*)fh
)+sizeof(fat_header
));
2107 for(uint32_t i
=0; i
< OSSwapBigToHostInt32(fh
->nfat_arch
); ++i
) {
2108 if ( ((cpu_type_t
)OSSwapBigToHostInt32(archs
[i
].cputype
) == cpu
)
2109 && ((cpu_subtype_t
)OSSwapBigToHostInt32(archs
[i
].cpusubtype
) == subtype
) ) {
2110 *offset
= OSSwapBigToHostInt32(archs
[i
].offset
);
2111 *len
= OSSwapBigToHostInt32(archs
[i
].size
);
2118 // scan fat table-of-contents for image with matching cpu-type and runs-on-all-sub-types
2119 static bool fatFindRunsOnAllCPUs(cpu_type_t cpu
, const fat_header
* fh
, uint64_t* offset
, uint64_t* len
)
2121 const fat_arch
* archs
= (fat_arch
*)(((char*)fh
)+sizeof(fat_header
));
2122 for(uint32_t i
=0; i
< OSSwapBigToHostInt32(fh
->nfat_arch
); ++i
) {
2123 if ( (cpu_type_t
)OSSwapBigToHostInt32(archs
[i
].cputype
) == cpu
) {
2127 if ( (cpu_subtype_t
)OSSwapBigToHostInt32(archs
[i
].cpusubtype
) == CPU_SUBTYPE_ARM_ALL
) {
2128 *offset
= OSSwapBigToHostInt32(archs
[i
].offset
);
2129 *len
= OSSwapBigToHostInt32(archs
[i
].size
);
2135 case CPU_TYPE_X86_64
:
2136 if ( (cpu_subtype_t
)OSSwapBigToHostInt32(archs
[i
].cpusubtype
) == CPU_SUBTYPE_X86_64_ALL
) {
2137 *offset
= OSSwapBigToHostInt32(archs
[i
].offset
);
2138 *len
= OSSwapBigToHostInt32(archs
[i
].size
);
2149 #endif // CPU_SUBTYPES_SUPPORTED
2152 // A fat file may contain multiple sub-images for the same cpu-type,
2153 // each optimized for a different cpu-sub-type (e.g G3 or G5).
2154 // This routine picks the optimal sub-image.
2156 static bool fatFindBest(const fat_header
* fh
, uint64_t* offset
, uint64_t* len
)
2158 #if CPU_SUBTYPES_SUPPORTED
2159 // assume all dylibs loaded must have same cpu type as main executable
2160 const cpu_type_t cpu
= sMainExecutableMachHeader
->cputype
;
2162 // We only know the subtype to use if the main executable cpu type matches the host
2163 if ( (cpu
& CPU_TYPE_MASK
) == sHostCPU
) {
2164 // get preference ordered list of subtypes
2165 const cpu_subtype_t
* subTypePreferenceList
= findCPUSubtypeList(cpu
, sHostCPUsubtype
);
2167 // use ordered list to find best sub-image in fat file
2168 if ( subTypePreferenceList
!= NULL
)
2169 return fatFindBestFromOrderedList(cpu
, subTypePreferenceList
, fh
, offset
, len
);
2171 // if running cpu is not in list, try for an exact match
2172 if ( fatFindExactMatch(cpu
, sHostCPUsubtype
, fh
, offset
, len
) )
2176 // running on an uknown cpu, can only load generic code
2177 return fatFindRunsOnAllCPUs(cpu
, fh
, offset
, len
);
2179 // just find first slice with matching architecture
2180 const fat_arch
* archs
= (fat_arch
*)(((char*)fh
)+sizeof(fat_header
));
2181 for(uint32_t i
=0; i
< OSSwapBigToHostInt32(fh
->nfat_arch
); ++i
) {
2182 if ( (cpu_type_t
)OSSwapBigToHostInt32(archs
[i
].cputype
) == sMainExecutableMachHeader
->cputype
) {
2183 *offset
= OSSwapBigToHostInt32(archs
[i
].offset
);
2184 *len
= OSSwapBigToHostInt32(archs
[i
].size
);
2195 // This is used to validate if a non-fat (aka thin or raw) mach-o file can be used
2196 // on the current processor. //
2197 bool isCompatibleMachO(const uint8_t* firstPage
, const char* path
)
2199 #if CPU_SUBTYPES_SUPPORTED
2200 // It is deemed compatible if any of the following are true:
2201 // 1) mach_header subtype is in list of compatible subtypes for running processor
2202 // 2) mach_header subtype is same as running processor subtype
2203 // 3) mach_header subtype runs on all processor variants
2204 const mach_header
* mh
= (mach_header
*)firstPage
;
2205 if ( mh
->magic
== sMainExecutableMachHeader
->magic
) {
2206 if ( mh
->cputype
== sMainExecutableMachHeader
->cputype
) {
2207 if ( (mh
->cputype
& CPU_TYPE_MASK
) == sHostCPU
) {
2208 // get preference ordered list of subtypes that this machine can use
2209 const cpu_subtype_t
* subTypePreferenceList
= findCPUSubtypeList(mh
->cputype
, sHostCPUsubtype
);
2210 if ( subTypePreferenceList
!= NULL
) {
2211 // if image's subtype is in the list, it is compatible
2212 for (const cpu_subtype_t
* p
= subTypePreferenceList
; *p
!= CPU_SUBTYPE_END_OF_LIST
; ++p
) {
2213 if ( *p
== mh
->cpusubtype
)
2216 // have list and not in list, so not compatible
2217 throwf("incompatible cpu-subtype: 0x%08X in %s", mh
->cpusubtype
, path
);
2219 // unknown cpu sub-type, but if exact match for current subtype then ok to use
2220 if ( mh
->cpusubtype
== sHostCPUsubtype
)
2224 // cpu type has no ordered list of subtypes
2225 switch (mh
->cputype
) {
2227 case CPU_TYPE_X86_64
:
2228 // subtypes are not used or these architectures
2234 // For architectures that don't support cpu-sub-types
2235 // this just check the cpu type.
2236 const mach_header
* mh
= (mach_header
*)firstPage
;
2237 if ( mh
->magic
== sMainExecutableMachHeader
->magic
) {
2238 if ( mh
->cputype
== sMainExecutableMachHeader
->cputype
) {
2249 // The kernel maps in main executable before dyld gets control. We need to
2250 // make an ImageLoader* for the already mapped in main executable.
2251 static ImageLoader
* instantiateFromLoadedImage(const macho_header
* mh
, uintptr_t slide
, const char* path
)
2253 // try mach-o loader
2254 if ( isCompatibleMachO((const uint8_t*)mh
, path
) ) {
2255 ImageLoader
* image
= ImageLoaderMachO::instantiateMainExecutable(mh
, slide
, path
, gLinkContext
);
2260 throw "main executable not a known format";
2264 #if DYLD_SHARED_CACHE_SUPPORT
2265 static bool findInSharedCacheImage(const char* path
, bool searchByPath
, const struct stat
* stat_buf
, const macho_header
** mh
, const char** pathInCache
, long* slide
)
2267 if ( sSharedCache
!= NULL
) {
2268 #if __MAC_OS_X_VERSION_MIN_REQUIRED
2269 // Mac OS X always requires inode/mtime to valid cache
2270 // if stat() not done yet, do it now
2272 if ( stat_buf
== NULL
) {
2273 if ( my_stat(path
, &statb
) == -1 )
2278 #if __IPHONE_OS_VERSION_MIN_REQUIRED
2280 for (const char* s
=path
; *s
!= '\0'; ++s
)
2281 hash
+= hash
*4 + *s
;
2284 // walk shared cache to see if there is a cached image that matches the inode/mtime/path desired
2285 const dyld_cache_image_info
* const start
= (dyld_cache_image_info
*)((uint8_t*)sSharedCache
+ sSharedCache
->imagesOffset
);
2286 const dyld_cache_image_info
* const end
= &start
[sSharedCache
->imagesCount
];
2287 #if __IPHONE_OS_VERSION_MIN_REQUIRED
2288 const bool cacheHasHashInfo
= (start
->modTime
== 0);
2290 for( const dyld_cache_image_info
* p
= start
; p
!= end
; ++p
) {
2291 #if __IPHONE_OS_VERSION_MIN_REQUIRED
2293 const char* aPath
= (char*)sSharedCache
+ p
->pathFileOffset
;
2294 if ( cacheHasHashInfo
&& (p
->inode
!= hash
) )
2296 if ( strcmp(path
, aPath
) == 0 ) {
2297 // found image in cache
2298 *mh
= (macho_header
*)(p
->address
+sSharedCacheSlide
);
2299 *pathInCache
= aPath
;
2300 *slide
= sSharedCacheSlide
;
2303 #elif __MAC_OS_X_VERSION_MIN_REQUIRED
2304 // check mtime and inode first because it is fast
2305 bool inodeMatch
= ( ((time_t)p
->modTime
== stat_buf
->st_mtime
) && ((ino_t
)p
->inode
== stat_buf
->st_ino
) );
2306 if ( searchByPath
|| sSharedCacheIgnoreInodeAndTimeStamp
|| inodeMatch
) {
2307 // mod-time and inode match an image in the shared cache, now check path
2308 const char* aPath
= (char*)sSharedCache
+ p
->pathFileOffset
;
2309 bool cacheHit
= (strcmp(path
, aPath
) == 0);
2310 if ( inodeMatch
&& !cacheHit
) {
2311 // path does not match install name of dylib in cache, but inode and mtime does match
2312 // perhaps path is a symlink to the cached dylib
2313 struct stat pathInCacheStatBuf
;
2314 if ( my_stat(aPath
, &pathInCacheStatBuf
) != -1 )
2315 cacheHit
= ( (pathInCacheStatBuf
.st_dev
== stat_buf
->st_dev
) && (pathInCacheStatBuf
.st_ino
== stat_buf
->st_ino
) );
2318 // found image in cache, return info
2319 *mh
= (macho_header
*)(p
->address
+sSharedCacheSlide
);
2320 //dyld::log("findInSharedCacheImage(), mh=%p, p->address=0x%0llX, slid=0x%0lX, path=%p\n",
2321 // *mh, p->address, sSharedCacheSlide, aPath);
2322 *pathInCache
= aPath
;
2323 *slide
= sSharedCacheSlide
;
2333 bool inSharedCache(const char* path
)
2335 const macho_header
* mhInCache
;
2336 const char* pathInCache
;
2338 return findInSharedCacheImage(path
, true, NULL
, &mhInCache
, &pathInCache
, &slide
);
2343 static ImageLoader
* checkandAddImage(ImageLoader
* image
, const LoadContext
& context
)
2345 // now sanity check that this loaded image does not have the same install path as any existing image
2346 const char* loadedImageInstallPath
= image
->getInstallPath();
2347 if ( image
->isDylib() && (loadedImageInstallPath
!= NULL
) && (loadedImageInstallPath
[0] == '/') ) {
2348 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
2349 ImageLoader
* anImage
= *it
;
2350 const char* installPath
= anImage
->getInstallPath();
2351 if ( installPath
!= NULL
) {
2352 if ( strcmp(loadedImageInstallPath
, installPath
) == 0 ) {
2353 //dyld::log("duplicate(%s) => %p\n", installPath, anImage);
2355 ImageLoader::deleteImage(image
);
2362 // some API's restrict what they can load
2363 if ( context
.mustBeBundle
&& !image
->isBundle() )
2364 throw "not a bundle";
2365 if ( context
.mustBeDylib
&& !image
->isDylib() )
2366 throw "not a dylib";
2368 // regular main executables cannot be loaded
2369 if ( image
->isExecutable() ) {
2370 if ( !context
.canBePIE
|| !image
->isPositionIndependentExecutable() )
2371 throw "can't load a main executable";
2374 // don't add bundles to global list, they can be loaded but not linked. When linked it will be added to list
2375 if ( ! image
->isBundle() )
2381 #if TARGET_IPHONE_SIMULATOR
2382 static bool isSimulatorBinary(const uint8_t* firstPage
, const char* path
)
2384 const macho_header
* mh
= (macho_header
*)firstPage
;
2385 const uint32_t cmd_count
= mh
->ncmds
;
2386 const struct load_command
* const cmds
= (struct load_command
*)(((char*)mh
)+sizeof(macho_header
));
2387 const struct load_command
* const cmdsReadEnd
= (struct load_command
*)(((char*)mh
)+4096);
2388 const struct load_command
* cmd
= cmds
;
2389 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
2391 case LC_VERSION_MIN_IPHONEOS
:
2393 case LC_VERSION_MIN_MACOSX
:
2394 // grandfather in a few libSystem dylibs
2395 if ( strncmp(path
, "/usr/lib/system/libsystem_", 26) == 0 )
2399 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
2400 if ( cmd
> cmdsReadEnd
)
2407 // map in file and instantiate an ImageLoader
2408 static ImageLoader
* loadPhase6(int fd
, const struct stat
& stat_buf
, const char* path
, const LoadContext
& context
)
2410 //dyld::log("%s(%s)\n", __func__ , path);
2411 uint64_t fileOffset
= 0;
2412 uint64_t fileLength
= stat_buf
.st_size
;
2414 // validate it is a file (not directory)
2415 if ( (stat_buf
.st_mode
& S_IFMT
) != S_IFREG
)
2418 uint8_t firstPage
[4096];
2419 bool shortPage
= false;
2421 // min mach-o file is 4K
2422 if ( fileLength
< 4096 ) {
2423 if ( pread(fd
, firstPage
, fileLength
, 0) != (ssize_t
)fileLength
)
2424 throwf("pread of short file failed: %d", errno
);
2428 if ( pread(fd
, firstPage
, 4096,0) != 4096 )
2429 throwf("pread of first 4K failed: %d", errno
);
2432 // if fat wrapper, find usable sub-file
2433 const fat_header
* fileStartAsFat
= (fat_header
*)firstPage
;
2434 if ( fileStartAsFat
->magic
== OSSwapBigToHostInt32(FAT_MAGIC
) ) {
2435 if ( fatFindBest(fileStartAsFat
, &fileOffset
, &fileLength
) ) {
2436 if ( (fileOffset
+fileLength
) > (uint64_t)(stat_buf
.st_size
) )
2437 throwf("truncated fat file. file length=%llu, but needed slice goes to %llu", stat_buf
.st_size
, fileOffset
+fileLength
);
2438 if (pread(fd
, firstPage
, 4096, fileOffset
) != 4096)
2439 throwf("pread of fat file failed: %d", errno
);
2442 throw "no matching architecture in universal wrapper";
2446 // try mach-o loader
2448 throw "file too short";
2449 if ( isCompatibleMachO(firstPage
, path
) ) {
2451 // only MH_BUNDLE, MH_DYLIB, and some MH_EXECUTE can be dynamically loaded
2452 switch ( ((mach_header
*)firstPage
)->filetype
) {
2458 throw "mach-o, but wrong filetype";
2461 #if TARGET_IPHONE_SIMULATOR
2462 // <rdar://problem/14168872> dyld_sim should restrict loading osx binaries
2463 if ( !isSimulatorBinary(firstPage
, path
) ) {
2464 throw "mach-o, but not built for iOS simulator";
2468 // instantiate an image
2469 ImageLoader
* image
= ImageLoaderMachO::instantiateFromFile(path
, fd
, firstPage
, fileOffset
, fileLength
, stat_buf
, gLinkContext
);
2472 return checkandAddImage(image
, context
);
2475 // try other file formats here...
2478 // throw error about what was found
2479 switch (*(uint32_t*)firstPage
) {
2484 throw "mach-o, but wrong architecture";
2486 throwf("unknown file type, first eight bytes: 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X",
2487 firstPage
[0], firstPage
[1], firstPage
[2], firstPage
[3], firstPage
[4], firstPage
[5], firstPage
[6],firstPage
[7]);
2492 static ImageLoader
* loadPhase5open(const char* path
, const LoadContext
& context
, const struct stat
& stat_buf
, std::vector
<const char*>* exceptions
)
2494 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
2496 // open file (automagically closed when this function exits)
2497 FileOpener
file(path
);
2499 // just return NULL if file not found, but record any other errors
2500 if ( file
.getFileDescriptor() == -1 ) {
2502 if ( err
!= ENOENT
) {
2503 const char* newMsg
= dyld::mkstringf("%s: open() failed with errno=%d", path
, err
);
2504 exceptions
->push_back(newMsg
);
2510 return loadPhase6(file
.getFileDescriptor(), stat_buf
, path
, context
);
2512 catch (const char* msg
) {
2513 const char* newMsg
= dyld::mkstringf("%s: %s", path
, msg
);
2514 exceptions
->push_back(newMsg
);
2521 #if __MAC_OS_X_VERSION_MIN_REQUIRED
2522 static ImageLoader
* loadPhase5load(const char* path
, const char* orgPath
, const LoadContext
& context
, std::vector
<const char*>* exceptions
)
2524 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
2525 ImageLoader
* image
= NULL
;
2527 // just return NULL if file not found, but record any other errors
2528 struct stat stat_buf
;
2529 if ( my_stat(path
, &stat_buf
) == -1 ) {
2531 if ( err
!= ENOENT
) {
2532 exceptions
->push_back(dyld::mkstringf("%s: stat() failed with errno=%d", path
, err
));
2537 // in case image was renamed or found via symlinks, check for inode match
2538 image
= findLoadedImage(stat_buf
);
2539 if ( image
!= NULL
)
2542 // do nothing if not already loaded and if RTLD_NOLOAD or NSADDIMAGE_OPTION_RETURN_ONLY_IF_LOADED
2543 if ( context
.dontLoad
)
2546 #if DYLD_SHARED_CACHE_SUPPORT
2547 // see if this image is in shared cache
2548 const macho_header
* mhInCache
;
2549 const char* pathInCache
;
2551 if ( findInSharedCacheImage(path
, false, &stat_buf
, &mhInCache
, &pathInCache
, &slideInCache
) ) {
2552 image
= ImageLoaderMachO::instantiateFromCache(mhInCache
, pathInCache
, slideInCache
, stat_buf
, gLinkContext
);
2553 return checkandAddImage(image
, context
);
2556 // file exists and is not in dyld shared cache, so open it
2557 return loadPhase5open(path
, context
, stat_buf
, exceptions
);
2559 #endif // __MAC_OS_X_VERSION_MIN_REQUIRED
2563 #if __IPHONE_OS_VERSION_MIN_REQUIRED
2564 static ImageLoader
* loadPhase5stat(const char* path
, const LoadContext
& context
, struct stat
* stat_buf
,
2565 int* statErrNo
, bool* imageFound
, std::vector
<const char*>* exceptions
)
2567 ImageLoader
* image
= NULL
;
2568 *imageFound
= false;
2570 if ( my_stat(path
, stat_buf
) == 0 ) {
2571 // in case image was renamed or found via symlinks, check for inode match
2572 image
= findLoadedImage(*stat_buf
);
2573 if ( image
!= NULL
) {
2577 // do nothing if not already loaded and if RTLD_NOLOAD
2578 if ( context
.dontLoad
) {
2582 image
= loadPhase5open(path
, context
, *stat_buf
, exceptions
);
2583 if ( image
!= NULL
) {
2595 static ImageLoader
* loadPhase5load(const char* path
, const char* orgPath
, const LoadContext
& context
, std::vector
<const char*>* exceptions
)
2597 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
2598 struct stat stat_buf
;
2602 #if DYLD_SHARED_CACHE_SUPPORT
2603 if ( sDylibsOverrideCache
) {
2604 // flag is set that allows installed framework roots to override dyld shared cache
2605 image
= loadPhase5stat(path
, context
, &stat_buf
, &statErrNo
, &imageFound
, exceptions
);
2609 // see if this image is in shared cache
2610 const macho_header
* mhInCache
;
2611 const char* pathInCache
;
2613 if ( findInSharedCacheImage(path
, true, NULL
, &mhInCache
, &pathInCache
, &slideInCache
) ) {
2614 // see if this image in the cache was already loaded via a different path
2615 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); ++it
) {
2616 ImageLoader
* anImage
= *it
;
2617 if ( (const macho_header
*)anImage
->machHeader() == mhInCache
)
2620 // do nothing if not already loaded and if RTLD_NOLOAD
2621 if ( context
.dontLoad
)
2623 // nope, so instantiate a new image from dyld shared cache
2624 // <rdar://problem/7014995> zero out stat buffer so mtime, etc are zero for items from the shared cache
2625 bzero(&stat_buf
, sizeof(stat_buf
));
2626 image
= ImageLoaderMachO::instantiateFromCache(mhInCache
, pathInCache
, slideInCache
, stat_buf
, gLinkContext
);
2627 return checkandAddImage(image
, context
);
2630 if ( !sDylibsOverrideCache
) {
2631 // flag is not set, and not in cache to try opening it
2632 image
= loadPhase5stat(path
, context
, &stat_buf
, &statErrNo
, &imageFound
, exceptions
);
2637 image
= loadPhase5stat(path
, context
, &stat_buf
, &statErrNo
, &imageFound
, exceptions
);
2641 // just return NULL if file not found, but record any other errors
2642 if ( (statErrNo
!= ENOENT
) && (statErrNo
!= 0) ) {
2643 exceptions
->push_back(dyld::mkstringf("%s: stat() failed with errno=%d", path
, statErrNo
));
2647 #endif // __IPHONE_OS_VERSION_MIN_REQUIRED
2650 // look for path match with existing loaded images
2651 static ImageLoader
* loadPhase5check(const char* path
, const char* orgPath
, const LoadContext
& context
)
2653 //dyld::log("%s(%s, %s)\n", __func__ , path, orgPath);
2654 // search path against load-path and install-path of all already loaded images
2655 uint32_t hash
= ImageLoader::hash(path
);
2656 //dyld::log("check() hash=%d, path=%s\n", hash, path);
2657 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
2658 ImageLoader
* anImage
= *it
;
2659 // check hash first to cut down on strcmp calls
2660 //dyld::log(" check() hash=%d, path=%s\n", anImage->getPathHash(), anImage->getPath());
2661 if ( anImage
->getPathHash() == hash
) {
2662 if ( strcmp(path
, anImage
->getPath()) == 0 ) {
2663 // if we are looking for a dylib don't return something else
2664 if ( !context
.mustBeDylib
|| anImage
->isDylib() )
2668 if ( context
.matchByInstallName
|| anImage
->matchInstallPath() ) {
2669 const char* installPath
= anImage
->getInstallPath();
2670 if ( installPath
!= NULL
) {
2671 if ( strcmp(path
, installPath
) == 0 ) {
2672 // if we are looking for a dylib don't return something else
2673 if ( !context
.mustBeDylib
|| anImage
->isDylib() )
2678 // an install name starting with @rpath should match by install name, not just real path
2679 if ( (orgPath
[0] == '@') && (strncmp(orgPath
, "@rpath/", 7) == 0) ) {
2680 const char* installPath
= anImage
->getInstallPath();
2681 if ( installPath
!= NULL
) {
2682 if ( !context
.mustBeDylib
|| anImage
->isDylib() ) {
2683 if ( strcmp(orgPath
, installPath
) == 0 )
2690 //dyld::log("%s(%s) => NULL\n", __func__, path);
2695 // open or check existing
2696 static ImageLoader
* loadPhase5(const char* path
, const char* orgPath
, const LoadContext
& context
, std::vector
<const char*>* exceptions
)
2698 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
2700 // check for specific dylib overrides
2701 for (std::vector
<DylibOverride
>::iterator it
= sDylibOverrides
.begin(); it
!= sDylibOverrides
.end(); ++it
) {
2702 if ( strcmp(it
->installName
, path
) == 0 ) {
2703 path
= it
->override
;
2708 if ( exceptions
!= NULL
)
2709 return loadPhase5load(path
, orgPath
, context
, exceptions
);
2711 return loadPhase5check(path
, orgPath
, context
);
2714 // try with and without image suffix
2715 static ImageLoader
* loadPhase4(const char* path
, const char* orgPath
, const LoadContext
& context
, std::vector
<const char*>* exceptions
)
2717 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
2718 ImageLoader
* image
= NULL
;
2719 if ( gLinkContext
.imageSuffix
!= NULL
) {
2720 char pathWithSuffix
[strlen(path
)+strlen( gLinkContext
.imageSuffix
)+2];
2721 ImageLoader::addSuffix(path
, gLinkContext
.imageSuffix
, pathWithSuffix
);
2722 image
= loadPhase5(pathWithSuffix
, orgPath
, context
, exceptions
);
2724 if ( image
== NULL
)
2725 image
= loadPhase5(path
, orgPath
, context
, exceptions
);
2729 static ImageLoader
* loadPhase2(const char* path
, const char* orgPath
, const LoadContext
& context
,
2730 const char* const frameworkPaths
[], const char* const libraryPaths
[],
2731 std::vector
<const char*>* exceptions
); // forward reference
2734 // expand @ variables
2735 static ImageLoader
* loadPhase3(const char* path
, const char* orgPath
, const LoadContext
& context
, std::vector
<const char*>* exceptions
)
2737 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
2738 ImageLoader
* image
= NULL
;
2739 if ( strncmp(path
, "@executable_path/", 17) == 0 ) {
2740 // executable_path cannot be in used in any binary in a setuid process rdar://problem/4589305
2741 if ( sProcessIsRestricted
)
2742 throwf("unsafe use of @executable_path in %s with restricted binary", context
.origin
);
2743 // handle @executable_path path prefix
2744 const char* executablePath
= sExecPath
;
2745 char newPath
[strlen(executablePath
) + strlen(path
)];
2746 strcpy(newPath
, executablePath
);
2747 char* addPoint
= strrchr(newPath
,'/');
2748 if ( addPoint
!= NULL
)
2749 strcpy(&addPoint
[1], &path
[17]);
2751 strcpy(newPath
, &path
[17]);
2752 image
= loadPhase4(newPath
, orgPath
, context
, exceptions
);
2753 if ( image
!= NULL
)
2756 // perhaps main executable path is a sym link, find realpath and retry
2757 char resolvedPath
[PATH_MAX
];
2758 if ( realpath(sExecPath
, resolvedPath
) != NULL
) {
2759 char newRealPath
[strlen(resolvedPath
) + strlen(path
)];
2760 strcpy(newRealPath
, resolvedPath
);
2761 char* addPoint
= strrchr(newRealPath
,'/');
2762 if ( addPoint
!= NULL
)
2763 strcpy(&addPoint
[1], &path
[17]);
2765 strcpy(newRealPath
, &path
[17]);
2766 image
= loadPhase4(newRealPath
, orgPath
, context
, exceptions
);
2767 if ( image
!= NULL
)
2771 else if ( (strncmp(path
, "@loader_path/", 13) == 0) && (context
.origin
!= NULL
) ) {
2772 // @loader_path cannot be used from the main executable of a setuid process rdar://problem/4589305
2773 if ( sProcessIsRestricted
&& (strcmp(context
.origin
, sExecPath
) == 0) )
2774 throwf("unsafe use of @loader_path in %s with restricted binary", context
.origin
);
2775 // handle @loader_path path prefix
2776 char newPath
[strlen(context
.origin
) + strlen(path
)];
2777 strcpy(newPath
, context
.origin
);
2778 char* addPoint
= strrchr(newPath
,'/');
2779 if ( addPoint
!= NULL
)
2780 strcpy(&addPoint
[1], &path
[13]);
2782 strcpy(newPath
, &path
[13]);
2783 image
= loadPhase4(newPath
, orgPath
, context
, exceptions
);
2784 if ( image
!= NULL
)
2787 // perhaps loader path is a sym link, find realpath and retry
2788 char resolvedPath
[PATH_MAX
];
2789 if ( realpath(context
.origin
, resolvedPath
) != NULL
) {
2790 char newRealPath
[strlen(resolvedPath
) + strlen(path
)];
2791 strcpy(newRealPath
, resolvedPath
);
2792 char* addPoint
= strrchr(newRealPath
,'/');
2793 if ( addPoint
!= NULL
)
2794 strcpy(&addPoint
[1], &path
[13]);
2796 strcpy(newRealPath
, &path
[13]);
2797 image
= loadPhase4(newRealPath
, orgPath
, context
, exceptions
);
2798 if ( image
!= NULL
)
2802 else if ( context
.implicitRPath
|| (strncmp(path
, "@rpath/", 7) == 0) ) {
2803 const char* trailingPath
= (strncmp(path
, "@rpath/", 7) == 0) ? &path
[7] : path
;
2804 // substitute @rpath with all -rpath paths up the load chain
2805 for(const ImageLoader::RPathChain
* rp
=context
.rpath
; rp
!= NULL
; rp
=rp
->next
) {
2806 if (rp
->paths
!= NULL
) {
2807 for(std::vector
<const char*>::iterator it
=rp
->paths
->begin(); it
!= rp
->paths
->end(); ++it
) {
2808 const char* anRPath
= *it
;
2809 char newPath
[strlen(anRPath
) + strlen(trailingPath
)+2];
2810 strcpy(newPath
, anRPath
);
2811 strcat(newPath
, "/");
2812 strcat(newPath
, trailingPath
);
2813 image
= loadPhase4(newPath
, orgPath
, context
, exceptions
);
2814 if ( gLinkContext
.verboseRPaths
&& (exceptions
!= NULL
) ) {
2815 if ( image
!= NULL
)
2816 dyld::log("RPATH successful expansion of %s to: %s\n", orgPath
, newPath
);
2818 dyld::log("RPATH failed to expanding %s to: %s\n", orgPath
, newPath
);
2820 if ( image
!= NULL
)
2826 // substitute @rpath with LD_LIBRARY_PATH
2827 if ( sEnv
.LD_LIBRARY_PATH
!= NULL
) {
2828 image
= loadPhase2(trailingPath
, orgPath
, context
, NULL
, sEnv
.LD_LIBRARY_PATH
, exceptions
);
2829 if ( image
!= NULL
)
2833 // if this is the "open" pass, don't try to open @rpath/... as a relative path
2834 if ( (exceptions
!= NULL
) && (trailingPath
!= path
) )
2837 else if (sProcessIsRestricted
&& (path
[0] != '/' )) {
2838 throwf("unsafe use of relative rpath %s in %s with restricted binary", path
, context
.origin
);
2841 return loadPhase4(path
, orgPath
, context
, exceptions
);
2846 static ImageLoader
* loadPhase2(const char* path
, const char* orgPath
, const LoadContext
& context
,
2847 const char* const frameworkPaths
[], const char* const libraryPaths
[],
2848 std::vector
<const char*>* exceptions
)
2850 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
2851 ImageLoader
* image
= NULL
;
2852 const char* frameworkPartialPath
= getFrameworkPartialPath(path
);
2853 if ( frameworkPaths
!= NULL
) {
2854 if ( frameworkPartialPath
!= NULL
) {
2855 const size_t frameworkPartialPathLen
= strlen(frameworkPartialPath
);
2856 for(const char* const* fp
= frameworkPaths
; *fp
!= NULL
; ++fp
) {
2857 char npath
[strlen(*fp
)+frameworkPartialPathLen
+8];
2860 strcat(npath
, frameworkPartialPath
);
2861 //dyld::log("dyld: fallback framework path used: %s() -> loadPhase4(\"%s\", ...)\n", __func__, npath);
2862 image
= loadPhase4(npath
, orgPath
, context
, exceptions
);
2863 if ( image
!= NULL
)
2868 // <rdar://problem/12649639> An executable with the same name as a framework & DYLD_LIBRARY_PATH pointing to it gets loaded twice
2869 // <rdar://problem/14160846> Some apps depend on frameworks being found via library paths
2870 if ( (libraryPaths
!= NULL
) && ((frameworkPartialPath
== NULL
) || sFrameworksFoundAsDylibs
) ) {
2871 const char* libraryLeafName
= getLibraryLeafName(path
);
2872 const size_t libraryLeafNameLen
= strlen(libraryLeafName
);
2873 for(const char* const* lp
= libraryPaths
; *lp
!= NULL
; ++lp
) {
2874 char libpath
[strlen(*lp
)+libraryLeafNameLen
+8];
2875 strcpy(libpath
, *lp
);
2876 strcat(libpath
, "/");
2877 strcat(libpath
, libraryLeafName
);
2878 //dyld::log("dyld: fallback library path used: %s() -> loadPhase4(\"%s\", ...)\n", __func__, libpath);
2879 image
= loadPhase4(libpath
, orgPath
, context
, exceptions
);
2880 if ( image
!= NULL
)
2887 // try search overrides and fallbacks
2888 static ImageLoader
* loadPhase1(const char* path
, const char* orgPath
, const LoadContext
& context
, std::vector
<const char*>* exceptions
)
2890 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
2891 ImageLoader
* image
= NULL
;
2893 // handle LD_LIBRARY_PATH environment variables that force searching
2894 if ( context
.useLdLibraryPath
&& (sEnv
.LD_LIBRARY_PATH
!= NULL
) ) {
2895 image
= loadPhase2(path
, orgPath
, context
, NULL
, sEnv
.LD_LIBRARY_PATH
, exceptions
);
2896 if ( image
!= NULL
)
2900 // handle DYLD_ environment variables that force searching
2901 if ( context
.useSearchPaths
&& ((sEnv
.DYLD_FRAMEWORK_PATH
!= NULL
) || (sEnv
.DYLD_LIBRARY_PATH
!= NULL
)) ) {
2902 image
= loadPhase2(path
, orgPath
, context
, sEnv
.DYLD_FRAMEWORK_PATH
, sEnv
.DYLD_LIBRARY_PATH
, exceptions
);
2903 if ( image
!= NULL
)
2908 image
= loadPhase3(path
, orgPath
, context
, exceptions
);
2909 if ( image
!= NULL
)
2912 // try fallback paths during second time (will open file)
2913 const char* const* fallbackLibraryPaths
= sEnv
.DYLD_FALLBACK_LIBRARY_PATH
;
2914 if ( (fallbackLibraryPaths
!= NULL
) && !context
.useFallbackPaths
)
2915 fallbackLibraryPaths
= NULL
;
2916 if ( !context
.dontLoad
&& (exceptions
!= NULL
) && ((sEnv
.DYLD_FALLBACK_FRAMEWORK_PATH
!= NULL
) || (fallbackLibraryPaths
!= NULL
)) ) {
2917 image
= loadPhase2(path
, orgPath
, context
, sEnv
.DYLD_FALLBACK_FRAMEWORK_PATH
, fallbackLibraryPaths
, exceptions
);
2918 if ( image
!= NULL
)
2925 // try root substitutions
2926 static ImageLoader
* loadPhase0(const char* path
, const char* orgPath
, const LoadContext
& context
, std::vector
<const char*>* exceptions
)
2928 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
2930 // handle DYLD_ROOT_PATH which forces absolute paths to use a new root
2931 if ( (gLinkContext
.rootPaths
!= NULL
) && (path
[0] == '/') ) {
2932 for(const char* const* rootPath
= gLinkContext
.rootPaths
; *rootPath
!= NULL
; ++rootPath
) {
2933 char newPath
[strlen(*rootPath
) + strlen(path
)+2];
2934 strcpy(newPath
, *rootPath
);
2935 strcat(newPath
, path
);
2936 ImageLoader
* image
= loadPhase1(newPath
, orgPath
, context
, exceptions
);
2937 if ( image
!= NULL
)
2943 return loadPhase1(path
, orgPath
, context
, exceptions
);
2946 #if DYLD_SHARED_CACHE_SUPPORT
2947 static bool cacheablePath(const char* path
) {
2948 if (strncmp(path
, "/usr/lib/", 9) == 0)
2950 if (strncmp(path
, "/System/Library/", 16) == 0)
2957 // Given all the DYLD_ environment variables, the general case for loading libraries
2958 // is that any given path expands into a list of possible locations to load. We
2959 // also must take care to ensure two copies of the "same" library are never loaded.
2961 // The algorithm used here is that there is a separate function for each "phase" of the
2962 // path expansion. Each phase function calls the next phase with each possible expansion
2963 // of that phase. The result is the last phase is called with all possible paths.
2965 // To catch duplicates the algorithm is run twice. The first time, the last phase checks
2966 // the path against all loaded images. The second time, the last phase calls open() on
2967 // the path. Either time, if an image is found, the phases all unwind without checking
2970 ImageLoader
* load(const char* path
, const LoadContext
& context
)
2972 CRSetCrashLogMessage2(path
);
2973 const char* orgPath
= path
;
2975 //dyld::log("%s(%s)\n", __func__ , path);
2976 char realPath
[PATH_MAX
];
2977 // when DYLD_IMAGE_SUFFIX is in used, do a realpath(), otherwise a load of "Foo.framework/Foo" will not match
2978 if ( context
.useSearchPaths
&& ( gLinkContext
.imageSuffix
!= NULL
) ) {
2979 if ( realpath(path
, realPath
) != NULL
)
2983 // try all path permutations and check against existing loaded images
2984 ImageLoader
* image
= loadPhase0(path
, orgPath
, context
, NULL
);
2985 if ( image
!= NULL
) {
2986 CRSetCrashLogMessage2(NULL
);
2990 // try all path permutations and try open() until first success
2991 std::vector
<const char*> exceptions
;
2992 image
= loadPhase0(path
, orgPath
, context
, &exceptions
);
2993 #if __IPHONE_OS_VERSION_MIN_REQUIRED && DYLD_SHARED_CACHE_SUPPORT && !TARGET_IPHONE_SIMULATOR
2994 // <rdar://problem/16704628> support symlinks on disk to a path in dyld shared cache
2995 if ( (image
== NULL
) && cacheablePath(path
) && !context
.dontLoad
) {
2996 char resolvedPath
[PATH_MAX
];
2997 realpath(path
, resolvedPath
);
2999 // If realpath() resolves to a path which does not exist on disk, errno is set to ENOENT
3000 if ( (myerr
== ENOENT
) || (myerr
== 0) )
3002 // see if this image is in shared cache
3003 const macho_header
* mhInCache
;
3004 const char* pathInCache
;
3006 if ( findInSharedCacheImage(resolvedPath
, false, NULL
, &mhInCache
, &pathInCache
, &slideInCache
) ) {
3007 struct stat stat_buf
;
3008 bzero(&stat_buf
, sizeof(stat_buf
));
3010 image
= ImageLoaderMachO::instantiateFromCache(mhInCache
, pathInCache
, slideInCache
, stat_buf
, gLinkContext
);
3011 image
= checkandAddImage(image
, context
);
3020 CRSetCrashLogMessage2(NULL
);
3021 if ( image
!= NULL
) {
3022 // <rdar://problem/6916014> leak in dyld during dlopen when using DYLD_ variables
3023 for (std::vector
<const char*>::iterator it
= exceptions
.begin(); it
!= exceptions
.end(); ++it
) {
3026 #if DYLD_SHARED_CACHE_SUPPORT
3027 // if loaded image is not from cache, but original path is in cache
3028 // set gSharedCacheOverridden flag to disable some ObjC optimizations
3029 if ( !gSharedCacheOverridden
&& !image
->inSharedCache() && image
->isDylib() && cacheablePath(path
) && inSharedCache(path
) ) {
3030 gSharedCacheOverridden
= true;
3035 else if ( exceptions
.size() == 0 ) {
3036 if ( context
.dontLoad
) {
3040 throw "image not found";
3043 const char* msgStart
= "no suitable image found. Did find:";
3044 const char* delim
= "\n\t";
3045 size_t allsizes
= strlen(msgStart
)+8;
3046 for (size_t i
=0; i
< exceptions
.size(); ++i
)
3047 allsizes
+= (strlen(exceptions
[i
]) + strlen(delim
));
3048 char* fullMsg
= new char[allsizes
];
3049 strcpy(fullMsg
, msgStart
);
3050 for (size_t i
=0; i
< exceptions
.size(); ++i
) {
3051 strcat(fullMsg
, delim
);
3052 strcat(fullMsg
, exceptions
[i
]);
3053 free((void*)exceptions
[i
]);
3055 throw (const char*)fullMsg
;
3061 #if DYLD_SHARED_CACHE_SUPPORT
3066 #define ARCH_NAME "i386"
3067 #define ARCH_CACHE_MAGIC "dyld_v1 i386"
3069 #define ARCH_NAME "x86_64"
3070 #define ARCH_CACHE_MAGIC "dyld_v1 x86_64"
3071 #define ARCH_NAME_H "x86_64h"
3072 #define ARCH_CACHE_MAGIC_H "dyld_v1 x86_64h"
3073 #elif __ARM_ARCH_5TEJ__
3074 #define ARCH_NAME "armv5"
3075 #define ARCH_CACHE_MAGIC "dyld_v1 armv5"
3076 #elif __ARM_ARCH_6K__
3077 #define ARCH_NAME "armv6"
3078 #define ARCH_CACHE_MAGIC "dyld_v1 armv6"
3079 #elif __ARM_ARCH_7F__
3080 #define ARCH_NAME "armv7f"
3081 #define ARCH_CACHE_MAGIC "dyld_v1 armv7f"
3082 #elif __ARM_ARCH_7K__
3083 #define ARCH_NAME "armv7k"
3084 #define ARCH_CACHE_MAGIC "dyld_v1 armv7k"
3085 #elif __ARM_ARCH_7A__
3086 #define ARCH_NAME "armv7"
3087 #define ARCH_CACHE_MAGIC "dyld_v1 armv7"
3088 #elif __ARM_ARCH_7S__
3089 #define ARCH_NAME "armv7s"
3090 #define ARCH_CACHE_MAGIC "dyld_v1 armv7s"
3092 #define ARCH_NAME "arm64"
3093 #define ARCH_CACHE_MAGIC "dyld_v1 arm64"
3097 static int __attribute__((noinline
)) _shared_region_check_np(uint64_t* start_address
)
3099 if ( gLinkContext
.sharedRegionMode
== ImageLoader::kUseSharedRegion
)
3100 return syscall(294, start_address
);
3105 static int __attribute__((noinline
)) _shared_region_map_and_slide_np(int fd
, uint32_t count
, const shared_file_mapping_np mappings
[],
3106 int codeSignatureMappingIndex
, long slide
, void* slideInfo
, unsigned long slideInfoSize
)
3108 // register code signature blob for whole dyld cache
3109 if ( codeSignatureMappingIndex
!= -1 ) {
3110 fsignatures_t siginfo
;
3111 siginfo
.fs_file_start
= 0; // cache always starts at beginning of file
3112 siginfo
.fs_blob_start
= (void*)mappings
[codeSignatureMappingIndex
].sfm_file_offset
;
3113 siginfo
.fs_blob_size
= mappings
[codeSignatureMappingIndex
].sfm_size
;
3114 int result
= fcntl(fd
, F_ADDFILESIGS
, &siginfo
);
3115 // <rdar://problem/12891874> don't warn in chrooted case because mapping syscall is about to fail too
3116 if ( (result
== -1) && gLinkContext
.verboseMapping
)
3117 dyld::log("dyld: code signature registration for shared cache failed with errno=%d\n", errno
);
3120 if ( gLinkContext
.sharedRegionMode
== ImageLoader::kUseSharedRegion
) {
3121 return syscall(438, fd
, count
, mappings
, slide
, slideInfo
, slideInfoSize
);
3124 // remove the shared region sub-map
3125 vm_deallocate(mach_task_self(), (vm_address_t
)SHARED_REGION_BASE
, SHARED_REGION_SIZE
);
3127 // notify gdb or other lurkers that this process is no longer using the shared region
3128 dyld::gProcessInfo
->processDetachedFromSharedRegion
= true;
3130 // map cache just for this process with mmap()
3131 const shared_file_mapping_np
* const start
= mappings
;
3132 const shared_file_mapping_np
* const end
= &mappings
[count
];
3133 for (const shared_file_mapping_np
* p
= start
; p
< end
; ++p
) {
3134 void* mmapAddress
= (void*)(uintptr_t)(p
->sfm_address
);
3135 size_t size
= p
->sfm_size
;
3136 //dyld::log("dyld: mapping address %p with size 0x%08lX\n", mmapAddress, size);
3138 if ( p
->sfm_init_prot
& VM_PROT_EXECUTE
)
3139 protection
|= PROT_EXEC
;
3140 if ( p
->sfm_init_prot
& VM_PROT_READ
)
3141 protection
|= PROT_READ
;
3142 if ( p
->sfm_init_prot
& VM_PROT_WRITE
)
3143 protection
|= PROT_WRITE
;
3144 off_t offset
= p
->sfm_file_offset
;
3145 if ( mmap(mmapAddress
, size
, protection
, MAP_FIXED
| MAP_PRIVATE
, fd
, offset
) != mmapAddress
) {
3146 // failed to map some chunk of this shared cache file
3147 // clear shared region
3148 vm_deallocate(mach_task_self(), (vm_address_t
)SHARED_REGION_BASE
, SHARED_REGION_SIZE
);
3149 // go back to not using shared region at all
3150 gLinkContext
.sharedRegionMode
= ImageLoader::kDontUseSharedRegion
;
3151 if ( gLinkContext
.verboseMapping
) {
3152 dyld::log("dyld: shared cached region cannot be mapped at address %p with size 0x%08lX\n",
3160 // update all __DATA pages with slide info
3162 const uintptr_t dataPagesStart
= mappings
[1].sfm_address
;
3163 const dyld_cache_slide_info
* slideInfoHeader
= (dyld_cache_slide_info
*)slideInfo
;
3164 const uint16_t* toc
= (uint16_t*)((long)(slideInfoHeader
) + slideInfoHeader
->toc_offset
);
3165 const uint8_t* entries
= (uint8_t*)((long)(slideInfoHeader
) + slideInfoHeader
->entries_offset
);
3166 for(uint32_t i
=0; i
< slideInfoHeader
->toc_count
; ++i
) {
3167 const uint8_t* entry
= &entries
[toc
[i
]*slideInfoHeader
->entries_size
];
3168 const uint8_t* page
= (uint8_t*)(long)(dataPagesStart
+ (4096*i
));
3169 //dyld::log("page=%p toc[%d]=%d entries=%p\n", page, i, toc[i], entry);
3170 for(int j
=0; j
< 128; ++j
) {
3171 uint8_t b
= entry
[j
];
3172 //dyld::log(" entry[%d] = 0x%02X\n", j, b);
3174 for(int k
=0; k
< 8; ++k
) {
3176 uintptr_t* p
= (uintptr_t*)(page
+ j
*8*4 + k
*4);
3177 uintptr_t value
= *p
;
3178 //dyld::log(" *%p was 0x%lX will be 0x%lX\n", p, value, value+sSharedCacheSlide);
3187 // succesfully mapped shared cache for just this process
3188 gLinkContext
.sharedRegionMode
= ImageLoader::kUsePrivateSharedRegion
;
3194 const void* imMemorySharedCacheHeader()
3196 return sSharedCache
;
3199 int openSharedCacheFile()
3201 char path
[MAXPATHLEN
];
3202 strlcpy(path
, sSharedCacheDir
, MAXPATHLEN
);
3203 strlcat(path
, "/", MAXPATHLEN
);
3206 strlcat(path
, DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME_H
, MAXPATHLEN
);
3207 int fd
= my_open(path
, O_RDONLY
, 0);
3209 if ( gLinkContext
.verboseMapping
)
3210 dyld::log("dyld: Mapping%s shared cache from %s\n", (gLinkContext
.sharedRegionMode
== ImageLoader::kUsePrivateSharedRegion
) ? " private": "", path
);
3213 strlcpy(path
, sSharedCacheDir
, MAXPATHLEN
);
3216 strlcat(path
, DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME
, MAXPATHLEN
);
3217 if ( gLinkContext
.verboseMapping
)
3218 dyld::log("dyld: Mapping%s shared cache from %s\n", (gLinkContext
.sharedRegionMode
== ImageLoader::kUsePrivateSharedRegion
) ? " private": "", path
);
3219 return my_open(path
, O_RDONLY
, 0);
3223 static void getCacheBounds(uint32_t mappingsCount
, const shared_file_mapping_np mappings
[], uint64_t& lowAddress
, uint64_t& highAddress
)
3227 for(uint32_t i
=0; i
< mappingsCount
; ++i
) {
3228 if ( lowAddress
== 0 ) {
3229 lowAddress
= mappings
[i
].sfm_address
;
3230 highAddress
= mappings
[i
].sfm_address
+ mappings
[i
].sfm_size
;
3233 if ( mappings
[i
].sfm_address
< lowAddress
)
3234 lowAddress
= mappings
[i
].sfm_address
;
3235 if ( (mappings
[i
].sfm_address
+ mappings
[i
].sfm_size
) > highAddress
)
3236 highAddress
= mappings
[i
].sfm_address
+ mappings
[i
].sfm_size
;
3241 static long pickCacheSlide(uint32_t mappingsCount
, shared_file_mapping_np mappings
[])
3244 // x86_64 has a two memory regions:
3245 // 256MB at 0x00007FFF70000000
3246 // 1024MB at 0x00007FFF80000000
3247 // Some old shared caches have r/w region after rx region, so all regions slide within 1GB range
3248 // Newer shared caches have r/w region based at 0x7FFF70000000 and r/o regions at 0x7FFF80000000, so each part has max slide
3249 if ( (mappingsCount
>= 3) && (mappings
[1].sfm_init_prot
== (VM_PROT_READ
|VM_PROT_WRITE
)) && (mappings
[1].sfm_address
== 0x00007FFF70000000) ) {
3250 const uint64_t rwSize
= mappings
[1].sfm_size
;
3251 const uint64_t rwSlop
= 0x10000000ULL
- rwSize
;
3252 const uint64_t roSize
= (mappings
[2].sfm_address
+ mappings
[2].sfm_size
) - mappings
[0].sfm_address
;
3253 const uint64_t roSlop
= 0x40000000ULL
- roSize
;
3254 const uint64_t space
= (rwSlop
< roSlop
) ? rwSlop
: roSlop
;
3256 // choose new random slide
3257 long slide
= (arc4random() % space
) & (-4096);
3258 //dyld::log("rwSlop=0x%0llX, roSlop=0x%0llX\n", rwSlop, roSlop);
3259 //dyld::log("space=0x%0llX, slide=0x%0lX\n", space, slide);
3262 for(uint32_t i
=0; i
< mappingsCount
; ++i
) {
3263 mappings
[i
].sfm_address
+= slide
;
3268 // else fall through to handle old style cache
3270 // get bounds of cache
3271 uint64_t lowAddress
;
3272 uint64_t highAddress
;
3273 getCacheBounds(mappingsCount
, mappings
, lowAddress
, highAddress
);
3276 const uint64_t space
= (SHARED_REGION_BASE
+ SHARED_REGION_SIZE
) - highAddress
;
3278 // choose new random slide
3279 long slide
= dyld_page_trunc(arc4random() % space
);
3280 //dyld::log("slideSpace=0x%0llX\n", space);
3281 //dyld::log("slide=0x%0lX\n", slide);
3284 for(uint32_t i
=0; i
< mappingsCount
; ++i
) {
3285 mappings
[i
].sfm_address
+= slide
;
3291 static void mapSharedCache()
3293 uint64_t cacheBaseAddress
= 0;
3294 // quick check if a cache is already mapped into shared region
3295 if ( _shared_region_check_np(&cacheBaseAddress
) == 0 ) {
3296 sSharedCache
= (dyld_cache_header
*)cacheBaseAddress
;
3297 // if we don't understand the currently mapped shared cache, then ignore
3299 const char* magic
= (sHaswell
? ARCH_CACHE_MAGIC_H
: ARCH_CACHE_MAGIC
);
3301 const char* magic
= ARCH_CACHE_MAGIC
;
3303 if ( strcmp(sSharedCache
->magic
, magic
) != 0 ) {
3304 sSharedCache
= NULL
;
3305 if ( gLinkContext
.verboseMapping
) {
3306 dyld::log("dyld: existing shared cached in memory is not compatible\n");
3310 // check if cache file is slidable
3311 const dyld_cache_header
* header
= sSharedCache
;
3312 if ( (header
->mappingOffset
>= 0x48) && (header
->slideInfoSize
!= 0) ) {
3313 // solve for slide by comparing loaded address to address of first region
3314 const uint8_t* loadedAddress
= (uint8_t*)sSharedCache
;
3315 const dyld_cache_mapping_info
* const mappings
= (dyld_cache_mapping_info
*)(loadedAddress
+header
->mappingOffset
);
3316 const uint8_t* preferedLoadAddress
= (uint8_t*)(long)(mappings
[0].address
);
3317 sSharedCacheSlide
= loadedAddress
- preferedLoadAddress
;
3318 dyld::gProcessInfo
->sharedCacheSlide
= sSharedCacheSlide
;
3319 //dyld::log("sSharedCacheSlide=0x%08lX, loadedAddress=%p, preferedLoadAddress=%p\n", sSharedCacheSlide, loadedAddress, preferedLoadAddress);
3321 // if cache has a uuid, copy it
3322 if ( header
->mappingOffset
>= 0x68 ) {
3323 memcpy(dyld::gProcessInfo
->sharedCacheUUID
, header
->uuid
, 16);
3326 if ( gLinkContext
.verboseMapping
) {
3327 dyld::log("dyld: re-using existing shared cache mapping\n");
3331 #if __i386__ || __x86_64__
3332 // <rdar://problem/5925940> Safe Boot should disable dyld shared cache
3333 // if we are in safe-boot mode and the cache was not made during this boot cycle,
3334 // delete the cache file
3335 uint32_t safeBootValue
= 0;
3336 size_t safeBootValueSize
= sizeof(safeBootValue
);
3337 if ( (sysctlbyname("kern.safeboot", &safeBootValue
, &safeBootValueSize
, NULL
, 0) == 0) && (safeBootValue
!= 0) ) {
3338 // user booted machine in safe-boot mode
3339 struct stat dyldCacheStatInfo
;
3340 // Don't use custom DYLD_SHARED_CACHE_DIR if provided, use standard path
3341 if ( my_stat(MACOSX_DYLD_SHARED_CACHE_DIR DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME
, &dyldCacheStatInfo
) == 0 ) {
3342 struct timeval bootTimeValue
;
3343 size_t bootTimeValueSize
= sizeof(bootTimeValue
);
3344 if ( (sysctlbyname("kern.boottime", &bootTimeValue
, &bootTimeValueSize
, NULL
, 0) == 0) && (bootTimeValue
.tv_sec
!= 0) ) {
3345 // if the cache file was created before this boot, then throw it away and let it rebuild itself
3346 if ( dyldCacheStatInfo
.st_mtime
< bootTimeValue
.tv_sec
) {
3347 ::unlink(MACOSX_DYLD_SHARED_CACHE_DIR DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME
);
3348 gLinkContext
.sharedRegionMode
= ImageLoader::kDontUseSharedRegion
;
3355 // map in shared cache to shared region
3356 int fd
= openSharedCacheFile();
3358 uint8_t firstPages
[8192];
3359 if ( ::read(fd
, firstPages
, 8192) == 8192 ) {
3360 dyld_cache_header
* header
= (dyld_cache_header
*)firstPages
;
3362 const char* magic
= (sHaswell
? ARCH_CACHE_MAGIC_H
: ARCH_CACHE_MAGIC
);
3364 const char* magic
= ARCH_CACHE_MAGIC
;
3366 if ( strcmp(header
->magic
, magic
) == 0 ) {
3367 const dyld_cache_mapping_info
* const fileMappingsStart
= (dyld_cache_mapping_info
*)&firstPages
[header
->mappingOffset
];
3368 const dyld_cache_mapping_info
* const fileMappingsEnd
= &fileMappingsStart
[header
->mappingCount
];
3369 shared_file_mapping_np mappings
[header
->mappingCount
+1]; // add room for code-sig
3370 unsigned int mappingCount
= header
->mappingCount
;
3371 int codeSignatureMappingIndex
= -1;
3372 int readWriteMappingIndex
= -1;
3373 int readOnlyMappingIndex
= -1;
3374 // validate that the cache file has not been truncated
3375 bool goodCache
= false;
3376 struct stat stat_buf
;
3377 if ( fstat(fd
, &stat_buf
) == 0 ) {
3380 for (const dyld_cache_mapping_info
* p
= fileMappingsStart
; p
< fileMappingsEnd
; ++p
, ++i
) {
3381 mappings
[i
].sfm_address
= p
->address
;
3382 mappings
[i
].sfm_size
= p
->size
;
3383 mappings
[i
].sfm_file_offset
= p
->fileOffset
;
3384 mappings
[i
].sfm_max_prot
= p
->maxProt
;
3385 mappings
[i
].sfm_init_prot
= p
->initProt
;
3386 // rdar://problem/5694507 old update_dyld_shared_cache tool could make a cache file
3387 // that is not page aligned, but otherwise ok.
3388 if ( p
->fileOffset
+p
->size
> (uint64_t)(stat_buf
.st_size
+4095 & (-4096)) ) {
3389 dyld::log("dyld: shared cached file is corrupt: %s" DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME
"\n", sSharedCacheDir
);
3392 if ( (mappings
[i
].sfm_init_prot
& (VM_PROT_READ
|VM_PROT_WRITE
)) == (VM_PROT_READ
|VM_PROT_WRITE
) ) {
3393 readWriteMappingIndex
= i
;
3395 if ( mappings
[i
].sfm_init_prot
== VM_PROT_READ
) {
3396 readOnlyMappingIndex
= i
;
3399 // if shared cache is code signed, add a mapping for the code signature
3400 uint64_t signatureSize
= header
->codeSignatureSize
;
3401 // zero size in header means signature runs to end-of-file
3402 if ( signatureSize
== 0 )
3403 signatureSize
= stat_buf
.st_size
- header
->codeSignatureOffset
;
3404 if ( signatureSize
!= 0 ) {
3405 int linkeditMapping
= mappingCount
-1;
3406 codeSignatureMappingIndex
= mappingCount
++;
3407 mappings
[codeSignatureMappingIndex
].sfm_address
= mappings
[linkeditMapping
].sfm_address
+ mappings
[linkeditMapping
].sfm_size
;
3408 #if __arm__ || __arm64__
3409 mappings
[codeSignatureMappingIndex
].sfm_size
= (signatureSize
+16383) & (-16384);
3411 mappings
[codeSignatureMappingIndex
].sfm_size
= (signatureSize
+4095) & (-4096);
3413 mappings
[codeSignatureMappingIndex
].sfm_file_offset
= header
->codeSignatureOffset
;
3414 mappings
[codeSignatureMappingIndex
].sfm_max_prot
= VM_PROT_READ
;
3415 mappings
[codeSignatureMappingIndex
].sfm_init_prot
= VM_PROT_READ
;
3418 #if __MAC_OS_X_VERSION_MIN_REQUIRED
3419 // sanity check that /usr/lib/libSystem.B.dylib stat() info matches cache
3420 if ( header
->imagesCount
* sizeof(dyld_cache_image_info
) + header
->imagesOffset
< 8192 ) {
3421 bool foundLibSystem
= false;
3422 if ( my_stat("/usr/lib/libSystem.B.dylib", &stat_buf
) == 0 ) {
3423 const dyld_cache_image_info
* images
= (dyld_cache_image_info
*)&firstPages
[header
->imagesOffset
];
3424 const dyld_cache_image_info
* const imagesEnd
= &images
[header
->imagesCount
];
3425 for (const dyld_cache_image_info
* p
= images
; p
< imagesEnd
; ++p
) {
3426 if ( ((time_t)p
->modTime
== stat_buf
.st_mtime
) && ((ino_t
)p
->inode
== stat_buf
.st_ino
) ) {
3427 foundLibSystem
= true;
3432 if ( !sSharedCacheIgnoreInodeAndTimeStamp
&& !foundLibSystem
) {
3433 dyld::log("dyld: shared cached file was built against a different libSystem.dylib, ignoring cache.\n"
3434 "to update dyld shared cache run: 'sudo update_dyld_shared_cache' then reboot.\n");
3439 #if __IPHONE_OS_VERSION_MIN_REQUIRED
3441 uint64_t lowAddress
;
3442 uint64_t highAddress
;
3443 getCacheBounds(mappingCount
, mappings
, lowAddress
, highAddress
);
3444 if ( (highAddress
-lowAddress
) > SHARED_REGION_SIZE
)
3445 throw "dyld shared cache is too big to fit in shared region";
3449 if ( goodCache
&& (readWriteMappingIndex
== -1) ) {
3450 dyld::log("dyld: shared cached file is missing read/write mapping: %s" DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME
"\n", sSharedCacheDir
);
3453 if ( goodCache
&& (readOnlyMappingIndex
== -1) ) {
3454 dyld::log("dyld: shared cached file is missing read-only mapping: %s" DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME
"\n", sSharedCacheDir
);
3458 long cacheSlide
= 0;
3459 void* slideInfo
= NULL
;
3460 uint64_t slideInfoSize
= 0;
3461 // check if shared cache contains slid info
3462 if ( header
->slideInfoSize
!= 0 ) {
3463 // <rdar://problem/8611968> don't slide shared cache if ASLR disabled (main executable didn't slide)
3464 if ( sMainExecutable
->isPositionIndependentExecutable() && (sMainExecutable
->getSlide() == 0) )
3467 // generate random slide amount
3468 cacheSlide
= pickCacheSlide(mappingCount
, mappings
);
3469 slideInfo
= (void*)(long)(mappings
[readOnlyMappingIndex
].sfm_address
+ (header
->slideInfoOffset
- mappings
[readOnlyMappingIndex
].sfm_file_offset
));
3470 slideInfoSize
= header
->slideInfoSize
;
3471 // add VM_PROT_SLIDE bit to __DATA area of cache
3472 mappings
[readWriteMappingIndex
].sfm_max_prot
|= VM_PROT_SLIDE
;
3473 mappings
[readWriteMappingIndex
].sfm_init_prot
|= VM_PROT_SLIDE
;
3476 if ( gLinkContext
.verboseMapping
) {
3477 dyld::log("dyld: calling _shared_region_map_and_slide_np() with regions:\n");
3478 for (int i
=0; i
< mappingCount
; ++i
) {
3479 dyld::log(" address=0x%08llX, size=0x%08llX, fileOffset=0x%08llX\n", mappings
[i
].sfm_address
, mappings
[i
].sfm_size
, mappings
[i
].sfm_file_offset
);
3482 if (_shared_region_map_and_slide_np(fd
, mappingCount
, mappings
, codeSignatureMappingIndex
, cacheSlide
, slideInfo
, slideInfoSize
) == 0) {
3483 // successfully mapped cache into shared region
3484 sSharedCache
= (dyld_cache_header
*)mappings
[0].sfm_address
;
3485 sSharedCacheSlide
= cacheSlide
;
3486 dyld::gProcessInfo
->sharedCacheSlide
= cacheSlide
;
3487 //dyld::log("sSharedCache=%p sSharedCacheSlide=0x%08lX\n", sSharedCache, sSharedCacheSlide);
3488 // if cache has a uuid, copy it
3489 if ( header
->mappingOffset
>= 0x68 ) {
3490 memcpy(dyld::gProcessInfo
->sharedCacheUUID
, header
->uuid
, 16);
3494 #if __IPHONE_OS_VERSION_MIN_REQUIRED
3495 throw "dyld shared cache could not be mapped";
3497 if ( gLinkContext
.verboseMapping
)
3498 dyld::log("dyld: shared cached file could not be mapped\n");
3503 if ( gLinkContext
.verboseMapping
)
3504 dyld::log("dyld: shared cached file is invalid\n");
3508 if ( gLinkContext
.verboseMapping
)
3509 dyld::log("dyld: shared cached file cannot be read\n");
3514 if ( gLinkContext
.verboseMapping
)
3515 dyld::log("dyld: shared cached file cannot be opened\n");
3519 // remember if dyld loaded at same address as when cache built
3520 if ( sSharedCache
!= NULL
) {
3521 gLinkContext
.dyldLoadedAtSameAddressNeededBySharedCache
= ((uintptr_t)(sSharedCache
->dyldBaseAddress
) == (uintptr_t)&_mh_dylinker_header
);
3524 // tell gdb where the shared cache is
3525 if ( sSharedCache
!= NULL
) {
3526 const dyld_cache_mapping_info
* const start
= (dyld_cache_mapping_info
*)((uint8_t*)sSharedCache
+ sSharedCache
->mappingOffset
);
3527 dyld_shared_cache_ranges
.sharedRegionsCount
= sSharedCache
->mappingCount
;
3528 // only room to tell gdb about first four regions
3529 if ( dyld_shared_cache_ranges
.sharedRegionsCount
> 4 )
3530 dyld_shared_cache_ranges
.sharedRegionsCount
= 4;
3531 const dyld_cache_mapping_info
* const end
= &start
[dyld_shared_cache_ranges
.sharedRegionsCount
];
3533 for (const dyld_cache_mapping_info
* p
= start
; p
< end
; ++p
, ++index
) {
3534 dyld_shared_cache_ranges
.ranges
[index
].start
= p
->address
+sSharedCacheSlide
;
3535 dyld_shared_cache_ranges
.ranges
[index
].length
= p
->size
;
3536 if ( gLinkContext
.verboseMapping
) {
3537 dyld::log(" 0x%08llX->0x%08llX %s%s%s init=%x, max=%x\n",
3538 p
->address
+sSharedCacheSlide
, p
->address
+sSharedCacheSlide
+p
->size
-1,
3539 ((p
->initProt
& VM_PROT_READ
) ? "read " : ""),
3540 ((p
->initProt
& VM_PROT_WRITE
) ? "write " : ""),
3541 ((p
->initProt
& VM_PROT_EXECUTE
) ? "execute " : ""), p
->initProt
, p
->maxProt
);
3544 // If a non-writable and executable region is found in the R/W shared region, then this is __IMPORT segments
3545 // This is an old cache. Make writable. dyld no longer supports turn W on and off as it binds
3546 if ( (p
->initProt
== (VM_PROT_READ
|VM_PROT_EXECUTE
)) && ((p
->address
& 0xF0000000) == 0xA0000000) ) {
3547 if ( p
->size
!= 0 ) {
3548 vm_prot_t prot
= VM_PROT_EXECUTE
| PROT_READ
| VM_PROT_WRITE
;
3549 vm_protect(mach_task_self(), p
->address
, p
->size
, false, prot
);
3550 if ( gLinkContext
.verboseMapping
) {
3551 dyld::log("%18s at 0x%08llX->0x%08llX altered permissions to %c%c%c\n", "", p
->address
,
3552 p
->address
+p
->size
-1,
3553 (prot
& PROT_READ
) ? 'r' : '.', (prot
& PROT_WRITE
) ? 'w' : '.', (prot
& PROT_EXEC
) ? 'x' : '.' );
3559 if ( gLinkContext
.verboseMapping
) {
3560 // list the code blob
3561 dyld_cache_header
* header
= (dyld_cache_header
*)sSharedCache
;
3562 uint64_t signatureSize
= header
->codeSignatureSize
;
3563 // zero size in header means signature runs to end-of-file
3564 if ( signatureSize
== 0 ) {
3565 struct stat stat_buf
;
3566 if ( my_stat(IPHONE_DYLD_SHARED_CACHE_DIR DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME
, &stat_buf
) == 0 )
3567 signatureSize
= stat_buf
.st_size
- header
->codeSignatureOffset
;
3569 if ( signatureSize
!= 0 ) {
3570 const dyld_cache_mapping_info
* const last
= &start
[dyld_shared_cache_ranges
.sharedRegionsCount
-1];
3571 uint64_t codeBlobStart
= last
->address
+ last
->size
;
3572 dyld::log(" 0x%08llX->0x%08llX (code signature)\n", codeBlobStart
, codeBlobStart
+signatureSize
);
3575 #if __IPHONE_OS_VERSION_MIN_REQUIRED
3576 // check for file that enables dyld shared cache dylibs to be overridden
3577 struct stat enableStatBuf
;
3578 // check file size to determine if correct file is in place.
3579 // See <rdar://problem/13591370> Need a way to disable roots without removing /S/L/C/com.apple.dyld/enable...
3580 sDylibsOverrideCache
= ( (my_stat(IPHONE_DYLD_SHARED_CACHE_DIR
"enable-dylibs-to-override-cache", &enableStatBuf
) == 0)
3581 && (enableStatBuf
.st_size
< ENABLE_DYLIBS_TO_OVERRIDE_CACHE_SIZE
) );
3585 #endif // #if DYLD_SHARED_CACHE_SUPPORT
3589 // create when NSLinkModule is called for a second time on a bundle
3590 ImageLoader
* cloneImage(ImageLoader
* image
)
3592 // open file (automagically closed when this function exits)
3593 FileOpener
file(image
->getPath());
3595 struct stat stat_buf
;
3596 if ( fstat(file
.getFileDescriptor(), &stat_buf
) == -1)
3599 dyld::LoadContext context
;
3600 context
.useSearchPaths
= false;
3601 context
.useFallbackPaths
= false;
3602 context
.useLdLibraryPath
= false;
3603 context
.implicitRPath
= false;
3604 context
.matchByInstallName
= false;
3605 context
.dontLoad
= false;
3606 context
.mustBeBundle
= true;
3607 context
.mustBeDylib
= false;
3608 context
.canBePIE
= false;
3609 context
.origin
= NULL
;
3610 context
.rpath
= NULL
;
3611 return loadPhase6(file
.getFileDescriptor(), stat_buf
, image
->getPath(), context
);
3615 ImageLoader
* loadFromMemory(const uint8_t* mem
, uint64_t len
, const char* moduleName
)
3617 // if fat wrapper, find usable sub-file
3618 const fat_header
* memStartAsFat
= (fat_header
*)mem
;
3619 uint64_t fileOffset
= 0;
3620 uint64_t fileLength
= len
;
3621 if ( memStartAsFat
->magic
== OSSwapBigToHostInt32(FAT_MAGIC
) ) {
3622 if ( fatFindBest(memStartAsFat
, &fileOffset
, &fileLength
) ) {
3623 mem
= &mem
[fileOffset
];
3627 throw "no matching architecture in universal wrapper";
3632 if ( isCompatibleMachO(mem
, moduleName
) ) {
3633 ImageLoader
* image
= ImageLoaderMachO::instantiateFromMemory(moduleName
, (macho_header
*)mem
, len
, gLinkContext
);
3634 // don't add bundles to global list, they can be loaded but not linked. When linked it will be added to list
3635 if ( ! image
->isBundle() )
3640 // try other file formats here...
3642 // throw error about what was found
3643 switch (*(uint32_t*)mem
) {
3648 throw "mach-o, but wrong architecture";
3650 throwf("unknown file type, first eight bytes: 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X",
3651 mem
[0], mem
[1], mem
[2], mem
[3], mem
[4], mem
[5], mem
[6],mem
[7]);
3656 void registerAddCallback(ImageCallback func
)
3658 // now add to list to get notified when any more images are added
3659 sAddImageCallbacks
.push_back(func
);
3661 // call callback with all existing images
3662 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
3663 ImageLoader
* image
= *it
;
3664 if ( image
->getState() >= dyld_image_state_bound
&& image
->getState() < dyld_image_state_terminated
)
3665 (*func
)(image
->machHeader(), image
->getSlide());
3669 void registerRemoveCallback(ImageCallback func
)
3671 // <rdar://problem/15025198> ignore calls to register a notification during a notification
3672 if ( sRemoveImageCallbacksInUse
)
3674 sRemoveImageCallbacks
.push_back(func
);
3677 void clearErrorMessage()
3679 error_string
[0] = '\0';
3682 void setErrorMessage(const char* message
)
3684 // save off error message in global buffer for CrashReporter to find
3685 strlcpy(error_string
, message
, sizeof(error_string
));
3688 const char* getErrorMessage()
3690 return error_string
;
3694 void halt(const char* message
)
3696 dyld::log("dyld: %s\n", message
);
3697 setErrorMessage(message
);
3698 uintptr_t terminationFlags
= 0;
3699 if ( !gLinkContext
.startedInitializingMainExecutable
)
3700 terminationFlags
= 1;
3701 setAlImageInfosHalt(error_string
, terminationFlags
);
3702 dyld_fatal_error(error_string
);
3705 static void setErrorStrings(unsigned errorCode
, const char* errorClientOfDylibPath
,
3706 const char* errorTargetDylibPath
, const char* errorSymbol
)
3708 dyld::gProcessInfo
->errorKind
= errorCode
;
3709 dyld::gProcessInfo
->errorClientOfDylibPath
= errorClientOfDylibPath
;
3710 dyld::gProcessInfo
->errorTargetDylibPath
= errorTargetDylibPath
;
3711 dyld::gProcessInfo
->errorSymbol
= errorSymbol
;
3715 uintptr_t bindLazySymbol(const mach_header
* mh
, uintptr_t* lazyPointer
)
3717 uintptr_t result
= 0;
3718 // acquire read-lock on dyld's data structures
3719 #if 0 // rdar://problem/3811777 turn off locking until deadlock is resolved
3720 if ( gLibSystemHelpers
!= NULL
)
3721 (*gLibSystemHelpers
->lockForReading
)();
3723 // lookup and bind lazy pointer and get target address
3725 ImageLoader
* target
;
3727 // fast stubs pass NULL for mh and image is instead found via the location of stub (aka lazyPointer)
3729 target
= dyld::findImageContainingAddress(lazyPointer
);
3731 target
= dyld::findImageByMachHeader(mh
);
3733 // note, target should always be mach-o, because only mach-o lazy handler wired up to this
3734 target
= dyld::findImageByMachHeader(mh
);
3736 if ( target
== NULL
)
3737 throwf("image not found for lazy pointer at %p", lazyPointer
);
3738 result
= target
->doBindLazySymbol(lazyPointer
, gLinkContext
);
3740 catch (const char* message
) {
3741 dyld::log("dyld: lazy symbol binding failed: %s\n", message
);
3744 // release read-lock on dyld's data structures
3746 if ( gLibSystemHelpers
!= NULL
)
3747 (*gLibSystemHelpers
->unlockForReading
)();
3749 // return target address to glue which jumps to it with real parameters restored
3754 uintptr_t fastBindLazySymbol(ImageLoader
** imageLoaderCache
, uintptr_t lazyBindingInfoOffset
)
3756 uintptr_t result
= 0;
3758 if ( *imageLoaderCache
== NULL
) {
3760 *imageLoaderCache
= dyld::findMappedRange((uintptr_t)imageLoaderCache
);
3761 if ( *imageLoaderCache
== NULL
) {
3762 const char* message
= "fast lazy binding from unknown image";
3763 dyld::log("dyld: %s\n", message
);
3768 // bind lazy pointer and return it
3770 result
= (*imageLoaderCache
)->doBindFastLazySymbol((uint32_t)lazyBindingInfoOffset
, gLinkContext
,
3771 (dyld::gLibSystemHelpers
!= NULL
) ? dyld::gLibSystemHelpers
->acquireGlobalDyldLock
: NULL
,
3772 (dyld::gLibSystemHelpers
!= NULL
) ? dyld::gLibSystemHelpers
->releaseGlobalDyldLock
: NULL
);
3774 catch (const char* message
) {
3775 dyld::log("dyld: lazy symbol binding failed: %s\n", message
);
3779 // return target address to glue which jumps to it with real parameters restored
3785 void registerUndefinedHandler(UndefinedHandler handler
)
3787 sUndefinedHandler
= handler
;
3790 static void undefinedHandler(const char* symboName
)
3792 if ( sUndefinedHandler
!= NULL
) {
3793 (*sUndefinedHandler
)(symboName
);
3797 static bool findExportedSymbol(const char* name
, bool onlyInCoalesced
, const ImageLoader::Symbol
** sym
, const ImageLoader
** image
)
3799 // search all images in order
3800 const ImageLoader
* firstWeakImage
= NULL
;
3801 const ImageLoader::Symbol
* firstWeakSym
= NULL
;
3802 const size_t imageCount
= sAllImages
.size();
3803 for(size_t i
=0; i
< imageCount
; ++i
) {
3804 ImageLoader
* anImage
= sAllImages
[i
];
3805 // the use of inserted libraries alters search order
3806 // so that inserted libraries are found before the main executable
3807 if ( sInsertedDylibCount
> 0 ) {
3808 if ( i
< sInsertedDylibCount
)
3809 anImage
= sAllImages
[i
+1];
3810 else if ( i
== sInsertedDylibCount
)
3811 anImage
= sAllImages
[0];
3813 if ( ! anImage
->hasHiddenExports() && (!onlyInCoalesced
|| anImage
->hasCoalescedExports()) ) {
3814 *sym
= anImage
->findExportedSymbol(name
, false, image
);
3815 if ( *sym
!= NULL
) {
3816 // if weak definition found, record first one found
3817 if ( ((*image
)->getExportedSymbolInfo(*sym
) & ImageLoader::kWeakDefinition
) != 0 ) {
3818 if ( firstWeakImage
== NULL
) {
3819 firstWeakImage
= *image
;
3820 firstWeakSym
= *sym
;
3824 // found non-weak, so immediately return with it
3830 if ( firstWeakSym
!= NULL
) {
3831 // found a weak definition, but no non-weak, so return first weak found
3832 *sym
= firstWeakSym
;
3833 *image
= firstWeakImage
;
3840 bool flatFindExportedSymbol(const char* name
, const ImageLoader::Symbol
** sym
, const ImageLoader
** image
)
3842 return findExportedSymbol(name
, false, sym
, image
);
3845 bool findCoalescedExportedSymbol(const char* name
, const ImageLoader::Symbol
** sym
, const ImageLoader
** image
)
3847 return findExportedSymbol(name
, true, sym
, image
);
3851 bool flatFindExportedSymbolWithHint(const char* name
, const char* librarySubstring
, const ImageLoader::Symbol
** sym
, const ImageLoader
** image
)
3853 // search all images in order
3854 const size_t imageCount
= sAllImages
.size();
3855 for(size_t i
=0; i
< imageCount
; ++i
){
3856 ImageLoader
* anImage
= sAllImages
[i
];
3857 // only look at images whose paths contain the hint string (NULL hint string is wildcard)
3858 if ( ! anImage
->isBundle() && ((librarySubstring
==NULL
) || (strstr(anImage
->getPath(), librarySubstring
) != NULL
)) ) {
3859 *sym
= anImage
->findExportedSymbol(name
, false, image
);
3860 if ( *sym
!= NULL
) {
3868 unsigned int getCoalescedImages(ImageLoader
* images
[])
3870 unsigned int count
= 0;
3871 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
3872 ImageLoader
* image
= *it
;
3873 if ( image
->participatesInCoalescing() ) {
3882 static ImageLoader::MappedRegion
* getMappedRegions(ImageLoader::MappedRegion
* regions
)
3884 ImageLoader::MappedRegion
* end
= regions
;
3885 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
3886 (*it
)->getMappedRegions(end
);
3891 void registerImageStateSingleChangeHandler(dyld_image_states state
, dyld_image_state_change_handler handler
)
3893 // mark the image that the handler is in as never-unload because dyld has a reference into it
3894 ImageLoader
* handlerImage
= findImageContainingAddress((void*)handler
);
3895 if ( handlerImage
!= NULL
)
3896 handlerImage
->setNeverUnload();
3898 // add to list of handlers
3899 std::vector
<dyld_image_state_change_handler
>* handlers
= stateToHandlers(state
, sSingleHandlers
);
3900 if ( handlers
!= NULL
) {
3901 // <rdar://problem/10332417> need updateAllImages() to be last in dyld_image_state_mapped list
3902 // so that if ObjC adds a handler that prevents a load, it happens before the gdb list is updated
3903 if ( state
== dyld_image_state_mapped
)
3904 handlers
->insert(handlers
->begin(), handler
);
3906 handlers
->push_back(handler
);
3908 // call callback with all existing images
3909 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
3910 ImageLoader
* image
= *it
;
3911 dyld_image_info info
;
3912 info
.imageLoadAddress
= image
->machHeader();
3913 info
.imageFilePath
= image
->getRealPath();
3914 info
.imageFileModDate
= image
->lastModified();
3915 // should only call handler if state == image->state
3916 if ( image
->getState() == state
)
3917 (*handler
)(state
, 1, &info
);
3918 // ignore returned string, too late to do anything
3923 void registerImageStateBatchChangeHandler(dyld_image_states state
, dyld_image_state_change_handler handler
)
3925 // mark the image that the handler is in as never-unload because dyld has a reference into it
3926 ImageLoader
* handlerImage
= findImageContainingAddress((void*)handler
);
3927 if ( handlerImage
!= NULL
)
3928 handlerImage
->setNeverUnload();
3930 // add to list of handlers
3931 std::vector
<dyld_image_state_change_handler
>* handlers
= stateToHandlers(state
, sBatchHandlers
);
3932 if ( handlers
!= NULL
) {
3933 // insert at front, so that gdb handler is always last
3934 handlers
->insert(handlers
->begin(), handler
);
3936 // call callback with all existing images
3938 notifyBatchPartial(state
, true, handler
);
3940 catch (const char* msg
) {
3941 // ignore request to abort during registration
3946 static ImageLoader
* libraryLocator(const char* libraryName
, bool search
, const char* origin
, const ImageLoader::RPathChain
* rpaths
)
3948 dyld::LoadContext context
;
3949 context
.useSearchPaths
= search
;
3950 context
.useFallbackPaths
= search
;
3951 context
.useLdLibraryPath
= false;
3952 context
.implicitRPath
= false;
3953 context
.matchByInstallName
= false;
3954 context
.dontLoad
= false;
3955 context
.mustBeBundle
= false;
3956 context
.mustBeDylib
= true;
3957 context
.canBePIE
= false;
3958 context
.origin
= origin
;
3959 context
.rpath
= rpaths
;
3960 return load(libraryName
, context
);
3963 static const char* basename(const char* path
)
3965 const char* last
= path
;
3966 for (const char* s
= path
; *s
!= '\0'; s
++) {
3973 static void setContext(const macho_header
* mainExecutableMH
, int argc
, const char* argv
[], const char* envp
[], const char* apple
[])
3975 gLinkContext
.loadLibrary
= &libraryLocator
;
3976 gLinkContext
.terminationRecorder
= &terminationRecorder
;
3977 gLinkContext
.flatExportFinder
= &flatFindExportedSymbol
;
3978 gLinkContext
.coalescedExportFinder
= &findCoalescedExportedSymbol
;
3979 gLinkContext
.getCoalescedImages
= &getCoalescedImages
;
3980 gLinkContext
.undefinedHandler
= &undefinedHandler
;
3981 gLinkContext
.getAllMappedRegions
= &getMappedRegions
;
3982 gLinkContext
.bindingHandler
= NULL
;
3983 gLinkContext
.notifySingle
= ¬ifySingle
;
3984 gLinkContext
.notifyBatch
= ¬ifyBatch
;
3985 gLinkContext
.removeImage
= &removeImage
;
3986 gLinkContext
.registerDOFs
= ®isterDOFs
;
3987 gLinkContext
.clearAllDepths
= &clearAllDepths
;
3988 gLinkContext
.printAllDepths
= &printAllDepths
;
3989 gLinkContext
.imageCount
= &imageCount
;
3990 gLinkContext
.setNewProgramVars
= &setNewProgramVars
;
3991 #if DYLD_SHARED_CACHE_SUPPORT
3992 gLinkContext
.inSharedCache
= &inSharedCache
;
3994 gLinkContext
.setErrorStrings
= &setErrorStrings
;
3995 #if SUPPORT_OLD_CRT_INITIALIZATION
3996 gLinkContext
.setRunInitialzersOldWay
= &setRunInitialzersOldWay
;
3998 gLinkContext
.findImageContainingAddress
= &findImageContainingAddress
;
3999 gLinkContext
.addDynamicReference
= &addDynamicReference
;
4000 gLinkContext
.bindingOptions
= ImageLoader::kBindingNone
;
4001 gLinkContext
.argc
= argc
;
4002 gLinkContext
.argv
= argv
;
4003 gLinkContext
.envp
= envp
;
4004 gLinkContext
.apple
= apple
;
4005 gLinkContext
.progname
= (argv
[0] != NULL
) ? basename(argv
[0]) : "";
4006 gLinkContext
.programVars
.mh
= mainExecutableMH
;
4007 gLinkContext
.programVars
.NXArgcPtr
= &gLinkContext
.argc
;
4008 gLinkContext
.programVars
.NXArgvPtr
= &gLinkContext
.argv
;
4009 gLinkContext
.programVars
.environPtr
= &gLinkContext
.envp
;
4010 gLinkContext
.programVars
.__prognamePtr
=&gLinkContext
.progname
;
4011 gLinkContext
.mainExecutable
= NULL
;
4012 gLinkContext
.imageSuffix
= NULL
;
4013 gLinkContext
.dynamicInterposeArray
= NULL
;
4014 gLinkContext
.dynamicInterposeCount
= 0;
4015 gLinkContext
.prebindUsage
= ImageLoader::kUseAllPrebinding
;
4016 #if TARGET_IPHONE_SIMULATOR
4017 gLinkContext
.sharedRegionMode
= ImageLoader::kDontUseSharedRegion
;
4019 gLinkContext
.sharedRegionMode
= ImageLoader::kUseSharedRegion
;
4025 #define LC_SEGMENT_COMMAND LC_SEGMENT_64
4026 #define macho_segment_command segment_command_64
4027 #define macho_section section_64
4029 #define LC_SEGMENT_COMMAND LC_SEGMENT
4030 #define macho_segment_command segment_command
4031 #define macho_section section
4036 // Look for a special segment in the mach header.
4037 // Its presences means that the binary wants to have DYLD ignore
4038 // DYLD_ environment variables.
4040 static bool hasRestrictedSegment(const macho_header
* mh
)
4042 const uint32_t cmd_count
= mh
->ncmds
;
4043 const struct load_command
* const cmds
= (struct load_command
*)(((char*)mh
)+sizeof(macho_header
));
4044 const struct load_command
* cmd
= cmds
;
4045 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
4047 case LC_SEGMENT_COMMAND
:
4049 const struct macho_segment_command
* seg
= (struct macho_segment_command
*)cmd
;
4051 //dyld::log("seg name: %s\n", seg->segname);
4052 if (strcmp(seg
->segname
, "__RESTRICT") == 0) {
4053 const struct macho_section
* const sectionsStart
= (struct macho_section
*)((char*)seg
+ sizeof(struct macho_segment_command
));
4054 const struct macho_section
* const sectionsEnd
= §ionsStart
[seg
->nsects
];
4055 for (const struct macho_section
* sect
=sectionsStart
; sect
< sectionsEnd
; ++sect
) {
4056 if (strcmp(sect
->sectname
, "__restrict") == 0)
4063 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
4069 #if SUPPORT_VERSIONED_PATHS
4071 // Peeks at a dylib file and returns its current_version and install_name.
4072 // Returns false on error.
4074 static bool getDylibVersionAndInstallname(const char* dylibPath
, uint32_t* version
, char* installName
)
4076 // open file (automagically closed when this function exits)
4077 FileOpener
file(dylibPath
);
4079 if ( file
.getFileDescriptor() == -1 )
4082 uint8_t firstPage
[4096];
4083 if ( pread(file
.getFileDescriptor(), firstPage
, 4096, 0) != 4096 )
4086 // if fat wrapper, find usable sub-file
4087 const fat_header
* fileStartAsFat
= (fat_header
*)firstPage
;
4088 if ( fileStartAsFat
->magic
== OSSwapBigToHostInt32(FAT_MAGIC
) ) {
4089 uint64_t fileOffset
;
4090 uint64_t fileLength
;
4091 if ( fatFindBest(fileStartAsFat
, &fileOffset
, &fileLength
) ) {
4092 if ( pread(file
.getFileDescriptor(), firstPage
, 4096, fileOffset
) != 4096 )
4100 // check mach-o header
4101 const mach_header
* mh
= (mach_header
*)firstPage
;
4102 if ( mh
->magic
!= sMainExecutableMachHeader
->magic
)
4104 if ( mh
->cputype
!= sMainExecutableMachHeader
->cputype
)
4107 // scan load commands for LC_ID_DYLIB
4108 const uint32_t cmd_count
= mh
->ncmds
;
4109 const struct load_command
* const cmds
= (struct load_command
*)(((char*)mh
)+sizeof(macho_header
));
4110 const struct load_command
* const cmdsReadEnd
= (struct load_command
*)(((char*)mh
)+4096);
4111 const struct load_command
* cmd
= cmds
;
4112 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
4116 const struct dylib_command
* id
= (struct dylib_command
*)cmd
;
4117 *version
= id
->dylib
.current_version
;
4118 if ( installName
!= NULL
)
4119 strlcpy(installName
, (char *)id
+ id
->dylib
.name
.offset
, PATH_MAX
);
4124 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
4125 if ( cmd
> cmdsReadEnd
)
4131 #endif // SUPPORT_VERSIONED_PATHS
4135 static void printAllImages()
4137 dyld::log("printAllImages()\n");
4138 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
4139 ImageLoader
* image
= *it
;
4140 dyld_image_states imageState
= image
->getState();
4141 dyld::log(" state=%d, dlopen-count=%d, never-unload=%d, in-use=%d, name=%s\n",
4142 imageState
, image
->dlopenCount(), image
->neverUnload(), image
->isMarkedInUse(), image
->getShortName());
4147 void link(ImageLoader
* image
, bool forceLazysBound
, bool neverUnload
, const ImageLoader::RPathChain
& loaderRPaths
)
4149 // add to list of known images. This did not happen at creation time for bundles
4150 if ( image
->isBundle() && !image
->isLinked() )
4153 // we detect root images as those not linked in yet
4154 if ( !image
->isLinked() )
4155 addRootImage(image
);
4159 image
->link(gLinkContext
, forceLazysBound
, false, neverUnload
, loaderRPaths
);
4161 catch (const char* msg
) {
4162 garbageCollectImages();
4168 void runInitializers(ImageLoader
* image
)
4170 // do bottom up initialization
4171 ImageLoader::InitializerTimingList initializerTimes
[sAllImages
.size()];
4172 initializerTimes
[0].count
= 0;
4173 image
->runInitializers(gLinkContext
, initializerTimes
[0]);
4176 // This function is called at the end of dlclose() when the reference count goes to zero.
4177 // The dylib being unloaded may have brought in other dependent dylibs when it was loaded.
4178 // Those dependent dylibs need to be unloaded, but only if they are not referenced by
4179 // something else. We use a standard mark and sweep garbage collection.
4181 // The tricky part is that when a dylib is unloaded it may have a termination function that
4182 // can run and itself call dlclose() on yet another dylib. The problem is that this
4183 // sort of gabage collection is not re-entrant. Instead a terminator's call to dlclose()
4184 // which calls garbageCollectImages() will just set a flag to re-do the garbage collection
4185 // when the current pass is done.
4187 // Also note that this is done within the dyld global lock, so it is always single threaded.
4189 void garbageCollectImages()
4191 static bool sDoingGC
= false;
4192 static bool sRedo
= false;
4195 // GC is currently being run, just set a flag to have it run again.
4204 // mark phase: mark all images not-in-use
4205 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
4206 ImageLoader
* image
= *it
;
4207 //dyld::log("gc: neverUnload=%d name=%s\n", image->neverUnload(), image->getShortName());
4208 image
->markNotUsed();
4211 // sweep phase: mark as in-use, images reachable from never-unload or in-use image
4212 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
4213 ImageLoader
* image
= *it
;
4214 if ( (image
->dlopenCount() != 0) || image
->neverUnload() ) {
4215 image
->markedUsedRecursive(sDynamicReferences
);
4219 // collect phase: build array of images not marked in-use
4220 ImageLoader
* deadImages
[sAllImages
.size()];
4221 unsigned deadCount
= 0;
4223 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
4224 ImageLoader
* image
= *it
;
4225 if ( ! image
->isMarkedInUse() ) {
4226 deadImages
[i
++] = image
;
4227 if (gLogAPIs
) dyld::log("dlclose(), found unused image %p %s\n", image
, image
->getShortName());
4232 // collect phase: run termination routines for images not marked in-use
4233 const int maxRangeCount
= deadCount
*2;
4234 __cxa_range_t ranges
[maxRangeCount
];
4236 for (unsigned i
=0; i
< deadCount
; ++i
) {
4237 ImageLoader
* image
= deadImages
[i
];
4238 for (unsigned int j
=0; j
< image
->segmentCount(); ++j
) {
4239 if ( !image
->segExecutable(j
) )
4241 if ( rangeCount
< maxRangeCount
) {
4242 ranges
[rangeCount
].addr
= (const void*)image
->segActualLoadAddress(j
);
4243 ranges
[rangeCount
].length
= image
->segSize(j
);
4248 runImageStaticTerminators(image
);
4250 catch (const char* msg
) {
4251 dyld::warn("problem running terminators for image: %s\n", msg
);
4255 // <rdar://problem/14718598> dyld should call __cxa_finalize_ranges()
4256 if ( (rangeCount
> 0) && (gLibSystemHelpers
!= NULL
) && (gLibSystemHelpers
->version
>= 13) )
4257 (*gLibSystemHelpers
->cxa_finalize_ranges
)(ranges
, rangeCount
);
4259 // collect phase: delete all images which are not marked in-use
4262 mightBeMore
= false;
4263 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
4264 ImageLoader
* image
= *it
;
4265 if ( ! image
->isMarkedInUse() ) {
4267 if (gLogAPIs
) dyld::log("dlclose(), deleting %p %s\n", image
, image
->getShortName());
4269 ImageLoader::deleteImage(image
);
4271 break; // interator in invalidated by this removal
4273 catch (const char* msg
) {
4274 dyld::warn("problem deleting image: %s\n", msg
);
4278 } while ( mightBeMore
);
4287 static void preflight_finally(ImageLoader
* image
)
4289 if ( image
->isBundle() ) {
4290 removeImageFromAllImages(image
->machHeader());
4291 ImageLoader::deleteImage(image
);
4293 sBundleBeingLoaded
= NULL
;
4294 dyld::garbageCollectImages();
4298 void preflight(ImageLoader
* image
, const ImageLoader::RPathChain
& loaderRPaths
)
4301 if ( image
->isBundle() )
4302 sBundleBeingLoaded
= image
; // hack
4303 image
->link(gLinkContext
, false, true, false, loaderRPaths
);
4305 catch (const char* msg
) {
4306 preflight_finally(image
);
4309 preflight_finally(image
);
4313 static bool isHaswell()
4315 #if TARGET_IPHONE_SIMULATOR
4318 // check system is capable of running x86_64h code
4319 struct host_basic_info info
;
4320 mach_msg_type_number_t count
= HOST_BASIC_INFO_COUNT
;
4321 mach_port_t hostPort
= mach_host_self();
4322 kern_return_t result
= host_info(hostPort
, HOST_BASIC_INFO
, (host_info_t
)&info
, &count
);
4323 mach_port_deallocate(mach_task_self(), hostPort
);
4324 if ( result
!= KERN_SUCCESS
)
4326 return ( info
.cpu_subtype
== CPU_SUBTYPE_X86_64_H
);
4331 static void loadInsertedDylib(const char* path
)
4333 ImageLoader
* image
= NULL
;
4335 LoadContext context
;
4336 context
.useSearchPaths
= false;
4337 context
.useFallbackPaths
= false;
4338 context
.useLdLibraryPath
= false;
4339 context
.implicitRPath
= false;
4340 context
.matchByInstallName
= false;
4341 context
.dontLoad
= false;
4342 context
.mustBeBundle
= false;
4343 context
.mustBeDylib
= true;
4344 context
.canBePIE
= false;
4345 context
.origin
= NULL
; // can't use @loader_path with DYLD_INSERT_LIBRARIES
4346 context
.rpath
= NULL
;
4347 image
= load(path
, context
);
4349 catch (const char* msg
) {
4350 #if TARGET_IPHONE_SIMULATOR
4351 dyld::log("dyld: warning: could not load inserted library '%s' because %s\n", path
, msg
);
4353 halt(dyld::mkstringf("could not load inserted library '%s' because %s\n", path
, msg
));
4357 halt(dyld::mkstringf("could not load inserted library '%s'\n", path
));
4361 static bool processRestricted(const macho_header
* mainExecutableMH
)
4363 #if __MAC_OS_X_VERSION_MIN_REQUIRED
4364 // ask kernel if code signature of program makes it restricted
4366 if ( csops(0, CS_OPS_STATUS
, &flags
, sizeof(flags
)) != -1 ) {
4367 if ( flags
& CS_ENFORCEMENT
) {
4368 gLinkContext
.codeSigningEnforced
= true;
4371 if (flags
& CS_RESTRICT
) {
4372 sRestrictedReason
= restrictedByEntitlements
;
4376 gLinkContext
.codeSigningEnforced
= true;
4379 // all processes with setuid or setgid bit set are restricted
4380 if ( issetugid() ) {
4381 sRestrictedReason
= restrictedBySetGUid
;
4385 // <rdar://problem/13158444&13245742> Respect __RESTRICT,__restrict section for root processes
4386 if ( hasRestrictedSegment(mainExecutableMH
) ) {
4387 // existence of __RESTRICT/__restrict section make process restricted
4388 sRestrictedReason
= restrictedBySegment
;
4395 bool processIsRestricted()
4397 return sProcessIsRestricted
;
4401 // <rdar://problem/10583252> Add dyld to uuidArray to enable symbolication of stackshots
4402 static void addDyldImageToUUIDList()
4404 const struct macho_header
* mh
= (macho_header
*)&__dso_handle
;
4405 const uint32_t cmd_count
= mh
->ncmds
;
4406 const struct load_command
* const cmds
= (struct load_command
*)((char*)mh
+ sizeof(macho_header
));
4407 const struct load_command
* cmd
= cmds
;
4408 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
4411 uuid_command
* uc
= (uuid_command
*)cmd
;
4412 dyld_uuid_info info
;
4413 info
.imageLoadAddress
= (mach_header
*)mh
;
4414 memcpy(info
.imageUUID
, uc
->uuid
, 16);
4415 addNonSharedCacheImageUUID(info
);
4419 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
4423 #if __MAC_OS_X_VERSION_MIN_REQUIRED
4424 typedef int (*open_proc_t
)(const char*, int, int);
4425 typedef int (*fcntl_proc_t
)(int, int, void*);
4426 typedef int (*ioctl_proc_t
)(int, unsigned long, void*);
4427 static void* getProcessInfo() { return dyld::gProcessInfo
; }
4428 static SyscallHelpers sSysCalls
= {
4430 // added in version 1
4439 (fcntl_proc_t
)&fcntl
,
4440 (ioctl_proc_t
)&ioctl
,
4449 &pthread_mutex_lock
,
4450 &pthread_mutex_unlock
,
4452 &mach_port_deallocate
,
4454 &mach_timebase_info
,
4455 &OSAtomicCompareAndSwapPtrBarrier
,
4459 &mach_absolute_time
,
4460 // added in version 2
4462 // added in version 3
4468 __attribute__((noinline
))
4469 static uintptr_t useSimulatorDyld(int fd
, const macho_header
* mainExecutableMH
, const char* dyldPath
,
4470 int argc
, const char* argv
[], const char* envp
[], const char* apple
[], uintptr_t* startGlue
)
4474 // verify simulator dyld file is owned by root
4476 if ( fstat(fd
, &sb
) == -1 )
4479 // read first page of dyld file
4480 uint8_t firstPage
[4096];
4481 if ( pread(fd
, firstPage
, 4096, 0) != 4096 )
4484 // if fat file, pick matching slice
4485 uint64_t fileOffset
= 0;
4486 uint64_t fileLength
= sb
.st_size
;
4487 const fat_header
* fileStartAsFat
= (fat_header
*)firstPage
;
4488 if ( fileStartAsFat
->magic
== OSSwapBigToHostInt32(FAT_MAGIC
) ) {
4489 if ( !fatFindBest(fileStartAsFat
, &fileOffset
, &fileLength
) )
4491 // re-read buffer from start of mach-o slice in fat file
4492 if ( pread(fd
, firstPage
, 4096, fileOffset
) != 4096 )
4495 else if ( !isCompatibleMachO(firstPage
, dyldPath
) ) {
4499 // calculate total size of dyld segments
4500 const macho_header
* mh
= (const macho_header
*)firstPage
;
4501 uintptr_t mappingSize
= 0;
4502 uintptr_t preferredLoadAddress
= 0;
4503 const uint32_t cmd_count
= mh
->ncmds
;
4504 const struct load_command
* const cmds
= (struct load_command
*)(((char*)mh
)+sizeof(macho_header
));
4505 const struct load_command
* cmd
= cmds
;
4506 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
4508 case LC_SEGMENT_COMMAND
:
4510 struct macho_segment_command
* seg
= (struct macho_segment_command
*)cmd
;
4511 mappingSize
+= seg
->vmsize
;
4512 if ( seg
->fileoff
== 0 )
4513 preferredLoadAddress
= seg
->vmaddr
;
4517 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
4520 // reserve space, then mmap each segment
4521 vm_address_t loadAddress
= 0;
4522 uintptr_t entry
= 0;
4523 if ( ::vm_allocate(mach_task_self(), &loadAddress
, mappingSize
, VM_FLAGS_ANYWHERE
) != 0 )
4526 struct linkedit_data_command
* codeSigCmd
= NULL
;
4527 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
4529 case LC_SEGMENT_COMMAND
:
4531 struct macho_segment_command
* seg
= (struct macho_segment_command
*)cmd
;
4532 uintptr_t requestedLoadAddress
= seg
->vmaddr
- preferredLoadAddress
+ loadAddress
;
4533 void* segAddress
= ::mmap((void*)requestedLoadAddress
, seg
->filesize
, seg
->initprot
, MAP_FIXED
| MAP_PRIVATE
, fd
, fileOffset
+ seg
->fileoff
);
4534 //dyld::log("dyld_sim %s mapped at %p\n", seg->segname, segAddress);
4535 if ( segAddress
== (void*)(-1) )
4542 const i386_thread_state_t
* registers
= (i386_thread_state_t
*)(((char*)cmd
) + 16);
4543 entry
= (registers
->__eip
+ loadAddress
- preferredLoadAddress
);
4545 const x86_thread_state64_t
* registers
= (x86_thread_state64_t
*)(((char*)cmd
) + 16);
4546 entry
= (registers
->__rip
+ loadAddress
- preferredLoadAddress
);
4550 case LC_CODE_SIGNATURE
:
4551 codeSigCmd
= (struct linkedit_data_command
*)cmd
;
4554 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
4557 if ( codeSigCmd
== NULL
)
4560 fsignatures_t siginfo
;
4561 siginfo
.fs_file_start
=fileOffset
; // start of mach-o slice in fat file
4562 siginfo
.fs_blob_start
=(void*)(long)(codeSigCmd
->dataoff
); // start of code-signature in mach-o file
4563 siginfo
.fs_blob_size
=codeSigCmd
->datasize
; // size of code-signature
4564 int result
= fcntl(fd
, F_ADDFILESIGS_FOR_DYLD_SIM
, &siginfo
);
4565 if ( result
== -1 ) {
4566 dyld::log("fcntl(F_ADDFILESIGS_FOR_DYLD_SIM) failed with errno=%d\n", errno
);
4572 // notify debugger that dyld_sim is loaded
4573 dyld_image_info info
;
4574 info
.imageLoadAddress
= (mach_header
*)loadAddress
;
4575 info
.imageFilePath
= strdup(dyldPath
);
4576 info
.imageFileModDate
= sb
.st_mtime
;
4577 addImagesToAllImages(1, &info
);
4578 dyld::gProcessInfo
->notification(dyld_image_adding
, 1, &info
);
4580 // jump into new simulator dyld
4581 typedef uintptr_t (*sim_entry_proc_t
)(int argc
, const char* argv
[], const char* envp
[], const char* apple
[],
4582 const macho_header
* mainExecutableMH
, const macho_header
* dyldMH
, uintptr_t dyldSlide
,
4583 const dyld::SyscallHelpers
* vtable
, uintptr_t* startGlue
);
4584 sim_entry_proc_t newDyld
= (sim_entry_proc_t
)entry
;
4585 return (*newDyld
)(argc
, argv
, envp
, apple
, mainExecutableMH
, (macho_header
*)loadAddress
,
4586 loadAddress
- preferredLoadAddress
,
4587 &sSysCalls
, startGlue
);
4593 // Entry point for dyld. The kernel loads dyld and jumps to __dyld_start which
4594 // sets up some registers and call this function.
4596 // Returns address of main() in target program which __dyld_start jumps to
4599 _main(const macho_header
* mainExecutableMH
, uintptr_t mainExecutableSlide
,
4600 int argc
, const char* argv
[], const char* envp
[], const char* apple
[],
4601 uintptr_t* startGlue
)
4603 uintptr_t result
= 0;
4604 sMainExecutableMachHeader
= mainExecutableMH
;
4605 #if __MAC_OS_X_VERSION_MIN_REQUIRED
4606 // if this is host dyld, check to see if iOS simulator is being run
4607 const char* rootPath
= _simple_getenv(envp
, "DYLD_ROOT_PATH");
4608 if ( rootPath
!= NULL
) {
4609 // look to see if simulator has its own dyld
4610 char simDyldPath
[PATH_MAX
];
4611 strlcpy(simDyldPath
, rootPath
, PATH_MAX
);
4612 strlcat(simDyldPath
, "/usr/lib/dyld_sim", PATH_MAX
);
4613 int fd
= my_open(simDyldPath
, O_RDONLY
, 0);
4615 result
= useSimulatorDyld(fd
, mainExecutableMH
, simDyldPath
, argc
, argv
, envp
, apple
, startGlue
);
4616 if ( !result
&& (*startGlue
== 0) )
4617 halt("problem loading iOS simulator dyld");
4623 CRSetCrashLogMessage("dyld: launch started");
4626 char bindingsLogPath
[256];
4628 const char* shortProgName
= "unknown";
4630 shortProgName
= strrchr(argv
[0], '/');
4631 if ( shortProgName
== NULL
)
4632 shortProgName
= argv
[0];
4636 mysprintf(bindingsLogPath
, "/tmp/bindings/%d-%s", getpid(), shortProgName
);
4637 sBindingsLogfile
= open(bindingsLogPath
, O_WRONLY
| O_CREAT
, 0666);
4638 if ( sBindingsLogfile
== -1 ) {
4639 ::mkdir("/tmp/bindings", 0777);
4640 sBindingsLogfile
= open(bindingsLogPath
, O_WRONLY
| O_CREAT
, 0666);
4642 //dyld::log("open(%s) => %d, errno = %d\n", bindingsLogPath, sBindingsLogfile, errno);
4644 setContext(mainExecutableMH
, argc
, argv
, envp
, apple
);
4646 // Pickup the pointer to the exec path.
4647 sExecPath
= _simple_getenv(apple
, "executable_path");
4649 // <rdar://problem/13868260> Remove interim apple[0] transition code from dyld
4650 if (!sExecPath
) sExecPath
= apple
[0];
4652 sExecPath
= apple
[0];
4653 bool ignoreEnvironmentVariables
= false;
4654 if ( sExecPath
[0] != '/' ) {
4655 // have relative path, use cwd to make absolute
4656 char cwdbuff
[MAXPATHLEN
];
4657 if ( getcwd(cwdbuff
, MAXPATHLEN
) != NULL
) {
4658 // maybe use static buffer to avoid calling malloc so early...
4659 char* s
= new char[strlen(cwdbuff
) + strlen(sExecPath
) + 2];
4662 strcat(s
, sExecPath
);
4666 // Remember short name of process for later logging
4667 sExecShortName
= ::strrchr(sExecPath
, '/');
4668 if ( sExecShortName
!= NULL
)
4671 sExecShortName
= sExecPath
;
4672 sProcessIsRestricted
= processRestricted(mainExecutableMH
);
4673 if ( sProcessIsRestricted
) {
4674 #if SUPPORT_LC_DYLD_ENVIRONMENT
4675 checkLoadCommandEnvironmentVariables();
4676 #if SUPPORT_VERSIONED_PATHS
4677 checkVersionedPaths();
4680 pruneEnvironmentVariables(envp
, &apple
);
4681 // set again because envp and apple may have changed or moved
4682 setContext(mainExecutableMH
, argc
, argv
, envp
, apple
);
4685 checkEnvironmentVariables(envp
, ignoreEnvironmentVariables
);
4686 if ( sEnv
.DYLD_PRINT_OPTS
)
4688 if ( sEnv
.DYLD_PRINT_ENV
)
4689 printEnvironmentVariables(envp
);
4691 // install gdb notifier
4692 stateToHandlers(dyld_image_state_dependents_mapped
, sBatchHandlers
)->push_back(notifyGDB
);
4693 stateToHandlers(dyld_image_state_mapped
, sSingleHandlers
)->push_back(updateAllImages
);
4694 // make initial allocations large enough that it is unlikely to need to be re-alloced
4695 sAllImages
.reserve(INITIAL_IMAGE_COUNT
);
4696 sImageRoots
.reserve(16);
4697 sAddImageCallbacks
.reserve(4);
4698 sRemoveImageCallbacks
.reserve(4);
4699 sImageFilesNeedingTermination
.reserve(16);
4700 sImageFilesNeedingDOFUnregistration
.reserve(8);
4702 #ifdef WAIT_FOR_SYSTEM_ORDER_HANDSHAKE
4703 // <rdar://problem/6849505> Add gating mechanism to dyld support system order file generation process
4704 WAIT_FOR_SYSTEM_ORDER_HANDSHAKE(dyld::gProcessInfo
->systemOrderFlag
);
4709 // add dyld itself to UUID list
4710 addDyldImageToUUIDList();
4711 CRSetCrashLogMessage(sLoadingCrashMessage
);
4712 // instantiate ImageLoader for main executable
4713 sMainExecutable
= instantiateFromLoadedImage(mainExecutableMH
, mainExecutableSlide
, sExecPath
);
4714 gLinkContext
.mainExecutable
= sMainExecutable
;
4715 gLinkContext
.processIsRestricted
= sProcessIsRestricted
;
4716 gLinkContext
.mainExecutableCodeSigned
= hasCodeSignatureLoadCommand(mainExecutableMH
);
4718 #if TARGET_IPHONE_SIMULATOR
4719 // check main executable is not too new for this OS
4721 if ( ! isSimulatorBinary((uint8_t*)mainExecutableMH
, sExecPath
) ) {
4722 throwf("program was built for Mac OS X and cannot be run in simulator");
4724 uint32_t mainMinOS
= sMainExecutable
->minOSVersion();
4725 // dyld is always built for the current OS, so we can get the current OS version
4726 // from the load command in dyld itself.
4727 uint32_t dyldMinOS
= ImageLoaderMachO::minOSVersion((const mach_header
*)&__dso_handle
);
4728 if ( mainMinOS
> dyldMinOS
) {
4729 throwf("app was built for iOS %d.%d which is newer than this simulator %d.%d",
4730 mainMinOS
>> 16, ((mainMinOS
>> 8) & 0xFF),
4731 dyldMinOS
>> 16, ((dyldMinOS
>> 8) & 0xFF));
4736 // load shared cache
4738 sHaswell
= isHaswell();
4740 checkSharedRegionDisable();
4741 #if DYLD_SHARED_CACHE_SUPPORT
4742 if ( gLinkContext
.sharedRegionMode
!= ImageLoader::kDontUseSharedRegion
)
4745 // load any inserted libraries
4746 if ( sEnv
.DYLD_INSERT_LIBRARIES
!= NULL
) {
4747 for (const char* const* lib
= sEnv
.DYLD_INSERT_LIBRARIES
; *lib
!= NULL
; ++lib
)
4748 loadInsertedDylib(*lib
);
4750 // record count of inserted libraries so that a flat search will look at
4751 // inserted libraries, then main, then others.
4752 sInsertedDylibCount
= sAllImages
.size()-1;
4754 // link main executable
4755 gLinkContext
.linkingMainExecutable
= true;
4756 link(sMainExecutable
, sEnv
.DYLD_BIND_AT_LAUNCH
, true, ImageLoader::RPathChain(NULL
, NULL
));
4757 sMainExecutable
->setNeverUnloadRecursive();
4758 if ( sMainExecutable
->forceFlat() ) {
4759 gLinkContext
.bindFlat
= true;
4760 gLinkContext
.prebindUsage
= ImageLoader::kUseNoPrebinding
;
4763 // link any inserted libraries
4764 // do this after linking main executable so that any dylibs pulled in by inserted
4765 // dylibs (e.g. libSystem) will not be in front of dylibs the program uses
4766 if ( sInsertedDylibCount
> 0 ) {
4767 for(unsigned int i
=0; i
< sInsertedDylibCount
; ++i
) {
4768 ImageLoader
* image
= sAllImages
[i
+1];
4769 link(image
, sEnv
.DYLD_BIND_AT_LAUNCH
, true, ImageLoader::RPathChain(NULL
, NULL
));
4770 image
->setNeverUnloadRecursive();
4772 // only INSERTED libraries can interpose
4773 // register interposing info after all inserted libraries are bound so chaining works
4774 for(unsigned int i
=0; i
< sInsertedDylibCount
; ++i
) {
4775 ImageLoader
* image
= sAllImages
[i
+1];
4776 image
->registerInterposing();
4779 // apply interposing to initial set of images
4780 for(int i
=0; i
< sImageRoots
.size(); ++i
) {
4781 sImageRoots
[i
]->applyInterposing(gLinkContext
);
4783 gLinkContext
.linkingMainExecutable
= false;
4785 // <rdar://problem/12186933> do weak binding only after all inserted images linked
4786 sMainExecutable
->weakBind(gLinkContext
);
4788 CRSetCrashLogMessage("dyld: launch, running initializers");
4789 #if SUPPORT_OLD_CRT_INITIALIZATION
4790 // Old way is to run initializers via a callback from crt1.o
4791 if ( ! gRunInitializersOldWay
)
4792 initializeMainExecutable();
4794 // run all initializers
4795 initializeMainExecutable();
4797 // find entry point for main executable
4798 result
= (uintptr_t)sMainExecutable
->getThreadPC();
4799 if ( result
!= 0 ) {
4800 // main executable uses LC_MAIN, needs to return to glue in libdyld.dylib
4801 if ( (gLibSystemHelpers
!= NULL
) && (gLibSystemHelpers
->version
>= 9) )
4802 *startGlue
= (uintptr_t)gLibSystemHelpers
->startGlueToCallExit
;
4804 halt("libdyld.dylib support not present for LC_MAIN");
4807 // main executable uses LC_UNIXTHREAD, dyld needs to let "start" in program set up for main()
4808 result
= (uintptr_t)sMainExecutable
->getMain();
4812 catch(const char* message
) {
4817 dyld::log("dyld: launch failed\n");
4820 CRSetCrashLogMessage(NULL
);