1 /* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*-
3 * Copyright (c) 2004-2010 Apple Inc. All rights reserved.
5 * @APPLE_LICENSE_HEADER_START@
7 * This file contains Original Code and/or Modifications of Original Code
8 * as defined in and that are subject to the Apple Public Source License
9 * Version 2.0 (the 'License'). You may not use this file except in
10 * compliance with the License. Please obtain a copy of the License at
11 * http://www.opensource.apple.com/apsl/ and read it before using this
14 * The Original Code and all software distributed under the License are
15 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
16 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
17 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
19 * Please see the License for the specific language governing rights and
20 * limitations under the License.
22 * @APPLE_LICENSE_HEADER_END@
31 #include <sys/param.h>
32 #include <mach/mach_time.h> // mach_absolute_time()
33 #include <sys/types.h>
35 #include <sys/syscall.h>
36 #include <mach-o/fat.h>
37 #include <mach-o/loader.h>
38 #include <mach-o/ldsyms.h>
39 #include <libkern/OSByteOrder.h>
40 #include <libkern/OSAtomic.h>
41 #include <mach/mach.h>
42 #include <sys/sysctl.h>
44 #include <sys/dtrace.h>
45 #include <libkern/OSAtomic.h>
46 #include <Availability.h>
47 #include <Kernel/sys/codesign.h>
50 #ifndef CPU_SUBTYPE_ARM_V5TEJ
51 #define CPU_SUBTYPE_ARM_V5TEJ ((cpu_subtype_t) 7)
53 #ifndef CPU_SUBTYPE_ARM_XSCALE
54 #define CPU_SUBTYPE_ARM_XSCALE ((cpu_subtype_t) 8)
56 #ifndef CPU_SUBTYPE_ARM_V7
57 #define CPU_SUBTYPE_ARM_V7 ((cpu_subtype_t) 9)
59 #ifndef LC_DYLD_ENVIRONMENT
60 #define LC_DYLD_ENVIRONMENT 0x27
64 #define VM_PROT_SLIDE 0x20
70 #include "mach-o/dyld_gdb.h"
73 #include "ImageLoader.h"
74 #include "ImageLoaderMachO.h"
75 #include "dyldLibSystemInterface.h"
76 #if DYLD_SHARED_CACHE_SUPPORT
77 #include "dyld_cache_format.h"
79 #if CORESYMBOLICATION_SUPPORT
80 #include "coreSymbolicationDyldSupport.hpp"
83 // from _simple.h in libc
84 typedef struct _SIMPLE
* _SIMPLE_STRING
;
85 extern "C" void _simple_vdprintf(int __fd
, const char *__fmt
, va_list __ap
);
86 extern "C" void _simple_dprintf(int __fd
, const char *__fmt
, ...);
87 extern "C" _SIMPLE_STRING
_simple_salloc(void);
88 extern "C" int _simple_vsprintf(_SIMPLE_STRING __b
, const char *__fmt
, va_list __ap
);
89 extern "C" void _simple_sfree(_SIMPLE_STRING __b
);
90 extern "C" char * _simple_string(_SIMPLE_STRING __b
);
94 // 32-bit ppc and ARM are the only architecture that use cpu-sub-types
95 #define CPU_SUBTYPES_SUPPORTED __ppc__ || __arm__
99 #define CPU_TYPE_MASK 0x00FFFFFF /* complement of CPU_ARCH_MASK */
102 /* implemented in dyld_gdb.cpp */
103 extern void addImagesToAllImages(uint32_t infoCount
, const dyld_image_info info
[]);
104 extern void removeImageFromAllImages(const mach_header
* mh
);
105 extern void setAlImageInfosHalt(const char* message
, uintptr_t flags
);
106 extern void addNonSharedCacheImageUUID(const dyld_uuid_info
& info
);
107 extern const char* notifyGDB(enum dyld_image_states state
, uint32_t infoCount
, const dyld_image_info info
[]);
109 // magic so CrashReporter logs message
111 char error_string
[1024];
113 // implemented in dyldStartup.s for CrashReporter
114 extern "C" void dyld_fatal_error(const char* errString
) __attribute__((noreturn
));
119 // The file contains the core of dyld used to get a process to main().
120 // The API's that dyld supports are implemented in dyldAPIs.cpp.
132 // state of all environment variables dyld uses
134 struct EnvironmentVariables
{
135 const char* const * DYLD_FRAMEWORK_PATH
;
136 const char* const * DYLD_FALLBACK_FRAMEWORK_PATH
;
137 const char* const * DYLD_LIBRARY_PATH
;
138 const char* const * DYLD_FALLBACK_LIBRARY_PATH
;
139 const char* const * DYLD_INSERT_LIBRARIES
;
140 const char* const * LD_LIBRARY_PATH
; // for unix conformance
141 const char* const * DYLD_VERSIONED_LIBRARY_PATH
;
142 const char* const * DYLD_VERSIONED_FRAMEWORK_PATH
;
143 bool DYLD_PRINT_LIBRARIES
;
144 bool DYLD_PRINT_LIBRARIES_POST_LAUNCH
;
145 bool DYLD_BIND_AT_LAUNCH
;
146 bool DYLD_PRINT_STATISTICS
;
147 bool DYLD_PRINT_OPTS
;
149 bool DYLD_DISABLE_DOFS
;
150 bool DYLD_PRINT_CS_NOTIFICATIONS
;
151 // DYLD_SHARED_CACHE_DONT_VALIDATE ==> sSharedCacheIgnoreInodeAndTimeStamp
152 // DYLD_SHARED_CACHE_DIR ==> sSharedCacheDir
153 // DYLD_ROOT_PATH ==> gLinkContext.rootPaths
154 // DYLD_IMAGE_SUFFIX ==> gLinkContext.imageSuffix
155 // DYLD_PRINT_OPTS ==> gLinkContext.verboseOpts
156 // DYLD_PRINT_ENV ==> gLinkContext.verboseEnv
157 // DYLD_FORCE_FLAT_NAMESPACE ==> gLinkContext.bindFlat
158 // DYLD_PRINT_INITIALIZERS ==> gLinkContext.verboseInit
159 // DYLD_PRINT_SEGMENTS ==> gLinkContext.verboseMapping
160 // DYLD_PRINT_BINDINGS ==> gLinkContext.verboseBind
161 // DYLD_PRINT_WEAK_BINDINGS ==> gLinkContext.verboseWeakBind
162 // DYLD_PRINT_REBASINGS ==> gLinkContext.verboseRebase
163 // DYLD_PRINT_DOFS ==> gLinkContext.verboseDOF
164 // DYLD_PRINT_APIS ==> gLogAPIs
165 // DYLD_IGNORE_PREBINDING ==> gLinkContext.prebindUsage
166 // DYLD_PREBIND_DEBUG ==> gLinkContext.verbosePrebinding
167 // DYLD_NEW_LOCAL_SHARED_REGIONS ==> gLinkContext.sharedRegionMode
168 // DYLD_SHARED_REGION ==> gLinkContext.sharedRegionMode
169 // DYLD_PRINT_WARNINGS ==> gLinkContext.verboseWarnings
170 // DYLD_PRINT_RPATHS ==> gLinkContext.verboseRPaths
171 // DYLD_PRINT_INTERPOSING ==> gLinkContext.verboseInterposing
174 typedef std::vector
<dyld_image_state_change_handler
> StateHandlers
;
175 struct RegisteredDOF
{ const mach_header
* mh
; int registrationID
; };
176 struct DylibOverride
{ const char* installName
; const char* override
; };
179 static const char* sExecPath
= NULL
;
180 static const macho_header
* sMainExecutableMachHeader
= NULL
;
181 #if CPU_SUBTYPES_SUPPORTED
182 static cpu_type_t sHostCPU
;
183 static cpu_subtype_t sHostCPUsubtype
;
185 static ImageLoader
* sMainExecutable
= NULL
;
186 static bool sProcessIsRestricted
= false;
187 static unsigned int sInsertedDylibCount
= 0;
188 static std::vector
<ImageLoader
*> sAllImages
;
189 static std::vector
<ImageLoader
*> sImageRoots
;
190 static std::vector
<ImageLoader
*> sImageFilesNeedingTermination
;
191 static std::vector
<RegisteredDOF
> sImageFilesNeedingDOFUnregistration
;
192 static std::vector
<ImageCallback
> sAddImageCallbacks
;
193 static std::vector
<ImageCallback
> sRemoveImageCallbacks
;
194 static StateHandlers sSingleHandlers
[7];
195 static StateHandlers sBatchHandlers
[7];
196 static ImageLoader
* sLastImageByAddressCache
;
197 static EnvironmentVariables sEnv
;
198 static const char* sFrameworkFallbackPaths
[] = { "$HOME/Library/Frameworks", "/Library/Frameworks", "/Network/Library/Frameworks", "/System/Library/Frameworks", NULL
};
199 static const char* sLibraryFallbackPaths
[] = { "$HOME/lib", "/usr/local/lib", "/usr/lib", NULL
};
200 static UndefinedHandler sUndefinedHandler
= NULL
;
201 static ImageLoader
* sBundleBeingLoaded
= NULL
; // hack until OFI is reworked
202 #if DYLD_SHARED_CACHE_SUPPORT
203 static const dyld_cache_header
* sSharedCache
= NULL
;
204 static long sSharedCacheSlide
= 0;
205 static bool sSharedCacheIgnoreInodeAndTimeStamp
= false;
206 #if __IPHONE_OS_VERSION_MIN_REQUIRED
207 bool gSharedCacheOverridden
= false;
208 static const char* sSharedCacheDir
= IPHONE_DYLD_SHARED_CACHE_DIR
;
209 static bool sDylibsOverrideCache
= false;
211 static const char* sSharedCacheDir
= MACOSX_DYLD_SHARED_CACHE_DIR
;
214 ImageLoader::LinkContext gLinkContext
;
215 bool gLogAPIs
= false;
216 const struct LibSystemHelpers
* gLibSystemHelpers
= NULL
;
217 #if SUPPORT_OLD_CRT_INITIALIZATION
218 bool gRunInitializersOldWay
= false;
220 static std::vector
<DylibOverride
> sDylibOverrides
;
223 // The MappedRanges structure is used for fast address->image lookups.
224 // The table is only updated when the dyld lock is held, so we don't
225 // need to worry about multiple writers. But readers may look at this
226 // data without holding the lock. Therefore, all updates must be done
227 // in an order that will never cause readers to see inconsistent data.
228 // The general rule is that if the image field is non-NULL then
229 // the other fields are valid.
242 static MappedRanges sMappedRangesStart
;
244 void addMappedRange(ImageLoader
* image
, uintptr_t start
, uintptr_t end
)
246 //dyld::log("addMappedRange(0x%lX->0x%lX) for %s\n", start, end, image->getShortName());
247 for (MappedRanges
* p
= &sMappedRangesStart
; p
!= NULL
; p
= p
->next
) {
248 for (int i
=0; i
< MappedRanges::count
; ++i
) {
249 if ( p
->array
[i
].image
== NULL
) {
250 p
->array
[i
].start
= start
;
251 p
->array
[i
].end
= end
;
252 // add image field last with a barrier so that any reader will see consistent records
254 p
->array
[i
].image
= image
;
259 // table must be full, chain another
260 MappedRanges
* newRanges
= (MappedRanges
*)malloc(sizeof(MappedRanges
));
261 bzero(newRanges
, sizeof(MappedRanges
));
262 newRanges
->array
[0].start
= start
;
263 newRanges
->array
[0].end
= end
;
264 newRanges
->array
[0].image
= image
;
265 for (MappedRanges
* p
= &sMappedRangesStart
; p
!= NULL
; p
= p
->next
) {
266 if ( p
->next
== NULL
) {
274 void removedMappedRanges(ImageLoader
* image
)
276 for (MappedRanges
* p
= &sMappedRangesStart
; p
!= NULL
; p
= p
->next
) {
277 for (int i
=0; i
< MappedRanges::count
; ++i
) {
278 if ( p
->array
[i
].image
== image
) {
279 // clear with a barrier so that any reader will see consistent records
281 p
->array
[i
].image
= NULL
;
287 ImageLoader
* findMappedRange(uintptr_t target
)
289 for (MappedRanges
* p
= &sMappedRangesStart
; p
!= NULL
; p
= p
->next
) {
290 for (int i
=0; i
< MappedRanges::count
; ++i
) {
291 if ( p
->array
[i
].image
!= NULL
) {
292 if ( (p
->array
[i
].start
<= target
) && (target
< p
->array
[i
].end
) )
293 return p
->array
[i
].image
;
302 const char* mkstringf(const char* format
, ...)
304 _SIMPLE_STRING buf
= _simple_salloc();
307 va_start(list
, format
);
308 _simple_vsprintf(buf
, format
, list
);
310 const char* t
= strdup(_simple_string(buf
));
315 return "mkstringf, out of memory error";
319 void throwf(const char* format
, ...)
321 _SIMPLE_STRING buf
= _simple_salloc();
324 va_start(list
, format
);
325 _simple_vsprintf(buf
, format
, list
);
327 const char* t
= strdup(_simple_string(buf
));
332 throw "throwf, out of memory error";
336 //#define ALTERNATIVE_LOGFILE "/dev/console"
337 static int sLogfile
= STDERR_FILENO
;
340 static int sBindingsLogfile
= -1;
341 static void mysprintf(char* dst
, const char* format
, ...)
343 _SIMPLE_STRING buf
= _simple_salloc();
346 va_start(list
, format
);
347 _simple_vsprintf(buf
, format
, list
);
349 strcpy(dst
, _simple_string(buf
));
353 strcpy(dst
, "out of memory");
356 void logBindings(const char* format
, ...)
358 if ( sBindingsLogfile
!= -1 ) {
360 va_start(list
, format
);
361 _simple_vdprintf(sBindingsLogfile
, format
, list
);
368 void log(const char* format
, ...)
371 va_start(list
, format
);
372 _simple_vdprintf(sLogfile
, format
, list
);
376 void warn(const char* format
, ...)
378 _simple_dprintf(sLogfile
, "dyld: warning, ");
380 va_start(list
, format
);
381 _simple_vdprintf(sLogfile
, format
, list
);
386 // <rdar://problem/8867781> control access to sAllImages through a lock
387 // because global dyld lock is not held during initialization phase of dlopen()
388 static long sAllImagesLock
= 0;
390 static void allImagesLock()
392 //dyld::log("allImagesLock()\n");
393 while ( ! OSAtomicCompareAndSwapPtrBarrier((void*)0, (void*)1, (void**)&sAllImagesLock
) ) {
398 static void allImagesUnlock()
400 //dyld::log("allImagesUnlock()\n");
401 while ( ! OSAtomicCompareAndSwapPtrBarrier((void*)1, (void*)0, (void**)&sAllImagesLock
) ) {
409 // utility class to assure files are closed when an exception is thrown
412 FileOpener(const char* path
);
414 int getFileDescriptor() { return fd
; }
419 FileOpener::FileOpener(const char* path
)
422 fd
= open(path
, O_RDONLY
, 0);
425 FileOpener::~FileOpener()
432 // forward declaration
433 #if __ppc__ || __i386__
438 static void registerDOFs(const std::vector
<ImageLoader::DOFInfo
>& dofs
)
441 // can't dtrace a program running emulated under rosetta rdar://problem/5179640
445 const unsigned int dofSectionCount
= dofs
.size();
446 if ( !sEnv
.DYLD_DISABLE_DOFS
&& (dofSectionCount
!= 0) ) {
447 int fd
= open("/dev/" DTRACEMNR_HELPER
, O_RDWR
);
449 //dyld::warn("can't open /dev/" DTRACEMNR_HELPER " to register dtrace DOF sections\n");
452 // allocate a buffer on the stack for the variable length dof_ioctl_data_t type
453 uint8_t buffer
[sizeof(dof_ioctl_data_t
) + dofSectionCount
*sizeof(dof_helper_t
)];
454 dof_ioctl_data_t
* ioctlData
= (dof_ioctl_data_t
*)buffer
;
456 // fill in buffer with one dof_helper_t per DOF section
457 ioctlData
->dofiod_count
= dofSectionCount
;
458 for (unsigned int i
=0; i
< dofSectionCount
; ++i
) {
459 strlcpy(ioctlData
->dofiod_helpers
[i
].dofhp_mod
, dofs
[i
].imageShortName
, DTRACE_MODNAMELEN
);
460 ioctlData
->dofiod_helpers
[i
].dofhp_dof
= (uintptr_t)(dofs
[i
].dof
);
461 ioctlData
->dofiod_helpers
[i
].dofhp_addr
= (uintptr_t)(dofs
[i
].dof
);
464 // tell kernel about all DOF sections en mas
465 // pass pointer to ioctlData because ioctl() only copies a fixed size amount of data into kernel
466 user_addr_t val
= (user_addr_t
)(unsigned long)ioctlData
;
467 if ( ioctl(fd
, DTRACEHIOC_ADDDOF
, &val
) != -1 ) {
468 // kernel returns a unique identifier for each section in the dofiod_helpers[].dofhp_dof field.
469 for (unsigned int i
=0; i
< dofSectionCount
; ++i
) {
471 info
.mh
= dofs
[i
].imageHeader
;
472 info
.registrationID
= (int)(ioctlData
->dofiod_helpers
[i
].dofhp_dof
);
473 sImageFilesNeedingDOFUnregistration
.push_back(info
);
474 if ( gLinkContext
.verboseDOF
) {
475 dyld::log("dyld: registering DOF section 0x%p in %s with dtrace, ID=0x%08X\n",
476 dofs
[i
].dof
, dofs
[i
].imageShortName
, info
.registrationID
);
481 dyld::log( "dyld: ioctl to register dtrace DOF section failed\n");
488 static void unregisterDOF(int registrationID
)
490 int fd
= open("/dev/" DTRACEMNR_HELPER
, O_RDWR
);
492 dyld::warn("can't open /dev/" DTRACEMNR_HELPER
" to unregister dtrace DOF section\n");
495 ioctl(fd
, DTRACEHIOC_REMOVE
, registrationID
);
497 if ( gLinkContext
.verboseInit
)
498 dyld::warn("unregistering DOF section ID=0x%08X with dtrace\n", registrationID
);
504 // _dyld_register_func_for_add_image() is implemented as part of the general image state change notification
506 static void notifyAddImageCallbacks(ImageLoader
* image
)
508 // use guard so that we cannot notify about the same image twice
509 if ( ! image
->addFuncNotified() ) {
510 for (std::vector
<ImageCallback
>::iterator it
=sAddImageCallbacks
.begin(); it
!= sAddImageCallbacks
.end(); it
++)
511 (*it
)(image
->machHeader(), image
->getSlide());
512 image
->setAddFuncNotified();
518 // notify gdb about these new images
519 static const char* updateAllImages(enum dyld_image_states state
, uint32_t infoCount
, const struct dyld_image_info info
[])
521 // <rdar://problem/8812589> don't add images without paths to all-image-info-list
522 if ( info
[0].imageFilePath
!= NULL
)
523 addImagesToAllImages(infoCount
, info
);
528 static StateHandlers
* stateToHandlers(dyld_image_states state
, StateHandlers handlersArray
[8])
531 case dyld_image_state_mapped
:
532 return &handlersArray
[0];
534 case dyld_image_state_dependents_mapped
:
535 return &handlersArray
[1];
537 case dyld_image_state_rebased
:
538 return &handlersArray
[2];
540 case dyld_image_state_bound
:
541 return &handlersArray
[3];
543 case dyld_image_state_dependents_initialized
:
544 return &handlersArray
[4];
546 case dyld_image_state_initialized
:
547 return &handlersArray
[5];
549 case dyld_image_state_terminated
:
550 return &handlersArray
[6];
556 static void notifySingle(dyld_image_states state
, const ImageLoader
* image
)
558 //dyld::log("notifySingle(state=%d, image=%s)\n", state, image->getPath());
559 std::vector
<dyld_image_state_change_handler
>* handlers
= stateToHandlers(state
, sSingleHandlers
);
560 if ( handlers
!= NULL
) {
561 dyld_image_info info
;
562 info
.imageLoadAddress
= image
->machHeader();
563 info
.imageFilePath
= image
->getPath();
564 info
.imageFileModDate
= image
->lastModified();
565 for (std::vector
<dyld_image_state_change_handler
>::iterator it
= handlers
->begin(); it
!= handlers
->end(); ++it
) {
566 const char* result
= (*it
)(state
, 1, &info
);
567 if ( (result
!= NULL
) && (state
== dyld_image_state_mapped
) ) {
568 //fprintf(stderr, " image rejected by handler=%p\n", *it);
569 // make copy of thrown string so that later catch clauses can free it
570 const char* str
= strdup(result
);
575 if ( state
== dyld_image_state_mapped
) {
576 // <rdar://problem/7008875> Save load addr + UUID for images from outside the shared cache
577 if ( !image
->inSharedCache() ) {
579 if ( image
->getUUID(info
.imageUUID
) ) {
580 info
.imageLoadAddress
= image
->machHeader();
581 addNonSharedCacheImageUUID(info
);
585 #if CORESYMBOLICATION_SUPPORT
586 // mach message csdlc about dynamically loaded images
587 if ( image
->addFuncNotified() && (state
== dyld_image_state_terminated
) ) {
588 if ( sEnv
.DYLD_PRINT_CS_NOTIFICATIONS
) {
589 dyld::log("dyld core symbolication unload notification: %p %s\n", image
->machHeader(), image
->getPath());
591 if ( dyld_all_image_infos
.coreSymbolicationShmPage
!= NULL
) {
592 CSCppDyldSharedMemoryPage
* connection
= (CSCppDyldSharedMemoryPage
*)dyld_all_image_infos
.coreSymbolicationShmPage
;
593 if ( connection
->is_valid_version() ) {
594 coresymbolication_unload_image(connection
, image
);
605 // Normally, dyld_all_image_infos is only updated in batches after an entire
606 // graph is loaded. But if there is an error loading the initial set of
607 // dylibs needed by the main executable, dyld_all_image_infos is not yet set
608 // up, leading to usually brief crash logs.
610 // This function manually adds the images loaded so far to dyld_all_image_infos.
611 // It should only be called before terminating.
615 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); ++it
) {
616 dyld_image_info info
;
617 ImageLoader
* image
= *it
;
618 info
.imageLoadAddress
= image
->machHeader();
619 info
.imageFilePath
= image
->getPath();
620 info
.imageFileModDate
= image
->lastModified();
621 // add to all_image_infos if not already there
623 int existingCount
= dyld_all_image_infos
.infoArrayCount
;
624 const dyld_image_info
* existing
= dyld_all_image_infos
.infoArray
;
625 if ( existing
!= NULL
) {
626 for (int i
=0; i
< existingCount
; ++i
) {
627 if ( existing
[i
].imageLoadAddress
== info
.imageLoadAddress
) {
628 //dyld::log("not adding %s\n", info.imageFilePath);
635 //dyld::log("adding %s\n", info.imageFilePath);
636 addImagesToAllImages(1, &info
);
642 static int imageSorter(const void* l
, const void* r
)
644 const ImageLoader
* left
= *((ImageLoader
**)l
);
645 const ImageLoader
* right
= *((ImageLoader
**)r
);
646 return left
->compare(right
);
649 static void notifyBatchPartial(dyld_image_states state
, bool orLater
, dyld_image_state_change_handler onlyHandler
)
651 std::vector
<dyld_image_state_change_handler
>* handlers
= stateToHandlers(state
, sBatchHandlers
);
652 if ( handlers
!= NULL
) {
653 // don't use a vector because it will use malloc/free and we want notifcation to be low cost
655 ImageLoader
* images
[sAllImages
.size()+1];
656 ImageLoader
** end
= images
;
657 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
658 dyld_image_states imageState
= (*it
)->getState();
659 if ( (imageState
== state
) || (orLater
&& (imageState
> state
)) )
662 if ( sBundleBeingLoaded
!= NULL
) {
663 dyld_image_states imageState
= sBundleBeingLoaded
->getState();
664 if ( (imageState
== state
) || (orLater
&& (imageState
> state
)) )
665 *end
++ = sBundleBeingLoaded
;
667 const char* dontLoadReason
= NULL
;
668 unsigned int count
= end
-images
;
669 if ( end
!= images
) {
671 qsort(images
, count
, sizeof(ImageLoader
*), &imageSorter
);
673 dyld_image_info infos
[count
];
674 for (unsigned int i
=0; i
< count
; ++i
) {
675 dyld_image_info
* p
= &infos
[i
];
676 ImageLoader
* image
= images
[i
];
677 //dyld::log(" state=%d, name=%s\n", state, image->getPath());
678 p
->imageLoadAddress
= image
->machHeader();
679 p
->imageFilePath
= image
->getPath();
680 p
->imageFileModDate
= image
->lastModified();
681 // special case for add_image hook
682 if ( state
== dyld_image_state_bound
)
683 notifyAddImageCallbacks(image
);
686 if ( onlyHandler
!= NULL
) {
687 const char* result
= (*onlyHandler
)(state
, count
, infos
);
688 if ( (result
!= NULL
) && (state
== dyld_image_state_dependents_mapped
) ) {
689 //fprintf(stderr, " images rejected by handler=%p\n", onlyHandler);
690 // make copy of thrown string so that later catch clauses can free it
691 dontLoadReason
= strdup(result
);
695 // call each handler with whole array
696 for (std::vector
<dyld_image_state_change_handler
>::iterator it
= handlers
->begin(); it
!= handlers
->end(); ++it
) {
697 const char* result
= (*it
)(state
, count
, infos
);
698 if ( (result
!= NULL
) && (state
== dyld_image_state_dependents_mapped
) ) {
699 //fprintf(stderr, " images rejected by handler=%p\n", *it);
700 // make copy of thrown string so that later catch clauses can free it
701 dontLoadReason
= strdup(result
);
708 if ( dontLoadReason
!= NULL
)
709 throw dontLoadReason
;
711 #if CORESYMBOLICATION_SUPPORT
712 if ( state
== dyld_image_state_rebased
) {
713 if ( sEnv
.DYLD_PRINT_CS_NOTIFICATIONS
) {
714 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
715 dyld_image_states imageState
= (*it
)->getState();
716 if ( (imageState
== dyld_image_state_rebased
) || (orLater
&& (imageState
> dyld_image_state_rebased
)) )
717 dyld::log("dyld core symbolication load notification: %p %s\n", (*it
)->machHeader(), (*it
)->getPath());
720 if ( dyld_all_image_infos
.coreSymbolicationShmPage
!= NULL
) {
721 CSCppDyldSharedMemoryPage
* connection
= (CSCppDyldSharedMemoryPage
*)dyld_all_image_infos
.coreSymbolicationShmPage
;
722 if ( connection
->is_valid_version() ) {
723 // This needs to be captured now
724 uint64_t load_timestamp
= mach_absolute_time();
725 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
726 dyld_image_states imageState
= (*it
)->getState();
727 if ( (imageState
== state
) || (orLater
&& (imageState
> state
)) )
728 coresymbolication_load_image(connection
, *it
, load_timestamp
);
738 static void notifyBatch(dyld_image_states state
)
740 notifyBatchPartial(state
, false, NULL
);
743 // In order for register_func_for_add_image() callbacks to to be called bottom up,
744 // we need to maintain a list of root images. The main executable is usally the
745 // first root. Any images dynamically added are also roots (unless already loaded).
746 // If DYLD_INSERT_LIBRARIES is used, those libraries are first.
747 static void addRootImage(ImageLoader
* image
)
749 //dyld::log("addRootImage(%p, %s)\n", image, image->getPath());
750 // add to list of roots
751 sImageRoots
.push_back(image
);
755 static void clearAllDepths()
757 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++)
761 static unsigned int imageCount()
763 return sAllImages
.size();
767 static void setNewProgramVars(const ProgramVars
& newVars
)
769 // make a copy of the pointers to program variables
770 gLinkContext
.programVars
= newVars
;
772 // now set each program global to their initial value
773 *gLinkContext
.programVars
.NXArgcPtr
= gLinkContext
.argc
;
774 *gLinkContext
.programVars
.NXArgvPtr
= gLinkContext
.argv
;
775 *gLinkContext
.programVars
.environPtr
= gLinkContext
.envp
;
776 *gLinkContext
.programVars
.__prognamePtr
= gLinkContext
.progname
;
779 #if SUPPORT_OLD_CRT_INITIALIZATION
780 static void setRunInitialzersOldWay()
782 gRunInitializersOldWay
= true;
786 static void addImage(ImageLoader
* image
)
788 // add to master list
790 sAllImages
.push_back(image
);
793 // update mapped ranges
794 uintptr_t lastSegStart
= 0;
795 uintptr_t lastSegEnd
= 0;
796 for(unsigned int i
=0, e
=image
->segmentCount(); i
< e
; ++i
) {
797 if ( image
->segUnaccessible(i
) )
799 uintptr_t start
= image
->segActualLoadAddress(i
);
800 uintptr_t end
= image
->segActualEndAddress(i
);
801 if ( start
== lastSegEnd
) {
802 // two segments are contiguous, just record combined segments
806 // non-contiguous segments, record last (if any)
807 if ( lastSegEnd
!= 0 )
808 addMappedRange(image
, lastSegStart
, lastSegEnd
);
809 lastSegStart
= start
;
813 if ( lastSegEnd
!= 0 )
814 addMappedRange(image
, lastSegStart
, lastSegEnd
);
817 if ( sEnv
.DYLD_PRINT_LIBRARIES
|| (sEnv
.DYLD_PRINT_LIBRARIES_POST_LAUNCH
&& (sMainExecutable
!=NULL
) && sMainExecutable
->isLinked()) ) {
818 dyld::log("dyld: loaded: %s\n", image
->getPath());
823 void removeImage(ImageLoader
* image
)
825 // if in termination list, pull it out and run terminator
826 for (std::vector
<ImageLoader
*>::iterator it
=sImageFilesNeedingTermination
.begin(); it
!= sImageFilesNeedingTermination
.end(); it
++) {
827 if ( *it
== image
) {
828 sImageFilesNeedingTermination
.erase(it
);
829 image
->doTermination(gLinkContext
);
834 // if has dtrace DOF section, tell dtrace it is going away, then remove from sImageFilesNeedingDOFUnregistration
835 for (std::vector
<RegisteredDOF
>::iterator it
=sImageFilesNeedingDOFUnregistration
.begin(); it
!= sImageFilesNeedingDOFUnregistration
.end(); ) {
836 if ( it
->mh
== image
->machHeader() ) {
837 unregisterDOF(it
->registrationID
);
838 sImageFilesNeedingDOFUnregistration
.erase(it
);
839 // don't increment iterator, the erase caused next element to be copied to where this iterator points
846 // tell all registered remove image handlers about this
847 // do this before removing image from internal data structures so that the callback can query dyld about the image
848 if ( image
->getState() >= dyld_image_state_bound
) {
849 for (std::vector
<ImageCallback
>::iterator it
=sRemoveImageCallbacks
.begin(); it
!= sRemoveImageCallbacks
.end(); it
++) {
850 (*it
)(image
->machHeader(), image
->getSlide());
855 notifySingle(dyld_image_state_terminated
, image
);
857 // <rdar://problem/7740779> dyld should directly call __cxa_finalize()
858 if ( (gLibSystemHelpers
!= NULL
) && (gLibSystemHelpers
->version
>= 8) )
859 (*gLibSystemHelpers
->cxa_finalize
)(image
->machHeader());
861 // remove from mapped images table
862 removedMappedRanges(image
);
864 // remove from master list
866 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
867 if ( *it
== image
) {
868 sAllImages
.erase(it
);
874 // flush find-by-address cache (do this after removed from master list, so there is no chance it can come back)
875 if ( sLastImageByAddressCache
== image
)
876 sLastImageByAddressCache
= NULL
;
878 // if in root list, pull it out
879 for (std::vector
<ImageLoader
*>::iterator it
=sImageRoots
.begin(); it
!= sImageRoots
.end(); it
++) {
880 if ( *it
== image
) {
881 sImageRoots
.erase(it
);
887 if ( sEnv
.DYLD_PRINT_LIBRARIES
|| (sEnv
.DYLD_PRINT_LIBRARIES_POST_LAUNCH
&& (sMainExecutable
!=NULL
) && sMainExecutable
->isLinked()) ) {
888 dyld::log("dyld: unloaded: %s\n", image
->getPath());
892 removeImageFromAllImages(image
->machHeader());
896 static void terminationRecorder(ImageLoader
* image
)
898 sImageFilesNeedingTermination
.push_back(image
);
901 const char* getExecutablePath()
907 void initializeMainExecutable()
909 // apply interposing to initial set of images
910 // do this before making the __IMPORT segments in shared cache read-only
911 sMainExecutable
->applyInterposing(gLinkContext
);
913 // record that we've reached this step
914 gLinkContext
.startedInitializingMainExecutable
= true;
916 // run initialzers for any inserted dylibs
917 ImageLoader::InitializerTimingList initializerTimes
[sAllImages
.size()];
918 const int rootCount
= sImageRoots
.size();
919 if ( rootCount
> 1 ) {
920 for(int i
=1; i
< rootCount
; ++i
) {
921 initializerTimes
[0].count
= 0;
922 sImageRoots
[i
]->runInitializers(gLinkContext
, initializerTimes
[0]);
926 // run initializers for main executable and everything it brings up
927 initializerTimes
[0].count
= 0;
928 sMainExecutable
->runInitializers(gLinkContext
, initializerTimes
[0]);
930 // register atexit() handler to run terminators in all loaded images when this process exits
931 if ( gLibSystemHelpers
!= NULL
)
932 (*gLibSystemHelpers
->cxa_atexit
)(&runTerminators
, NULL
, NULL
);
934 // dump info if requested
935 if ( sEnv
.DYLD_PRINT_STATISTICS
)
936 ImageLoaderMachO::printStatistics(sAllImages
.size(), initializerTimes
[0]);
939 bool mainExecutablePrebound()
941 return sMainExecutable
->usablePrebinding(gLinkContext
);
944 ImageLoader
* mainExecutable()
946 return sMainExecutable
;
950 void runTerminators(void* extra
)
952 const unsigned int imageCount
= sImageFilesNeedingTermination
.size();
953 for(unsigned int i
=imageCount
; i
> 0; --i
){
954 ImageLoader
* image
= sImageFilesNeedingTermination
[i
-1];
955 image
->doTermination(gLinkContext
);
957 sImageFilesNeedingTermination
.clear();
958 notifyBatch(dyld_image_state_terminated
);
963 static bool getDylibVersionAndInstallname(const char* dylibPath
, uint32_t* version
, char* installName
);
967 // Examines a dylib file and if its current_version is newer than the installed
968 // dylib at its install_name, then add the dylib file to sDylibOverrides.
970 static void checkDylibOverride(const char* dylibFile
)
972 //dyld::log("checkDylibOverride('%s')\n", dylibFile);
974 char sysInstallName
[PATH_MAX
];
975 if ( getDylibVersionAndInstallname(dylibFile
, &altVersion
, sysInstallName
) ) {
976 //dyld::log("%s has version 0x%08X and install name %s\n", dylibFile, altVersion, sysInstallName);
978 if ( getDylibVersionAndInstallname(sysInstallName
, &sysVersion
, NULL
) ) {
979 //dyld::log("%s has version 0x%08X\n", sysInstallName, sysVersion);
980 if ( altVersion
> sysVersion
) {
981 //dyld::log("override found: %s -> %s\n", sysInstallName, dylibFile);
982 // see if there already is an override for this dylib
983 bool entryExists
= false;
984 for (std::vector
<DylibOverride
>::iterator it
= sDylibOverrides
.begin(); it
!= sDylibOverrides
.end(); ++it
) {
985 if ( strcmp(it
->installName
, sysInstallName
) == 0 ) {
987 uint32_t prevVersion
;
988 if ( getDylibVersionAndInstallname(it
->override
, &prevVersion
, NULL
) ) {
989 if ( altVersion
> prevVersion
) {
990 // found an even newer override
991 free((void*)(it
->override
));
992 it
->override
= strdup(dylibFile
);
998 if ( ! entryExists
) {
1000 entry
.installName
= strdup(sysInstallName
);
1001 entry
.override
= strdup(dylibFile
);
1002 sDylibOverrides
.push_back(entry
);
1003 //dyld::log("added override: %s -> %s\n", entry.installName, entry.override);
1011 static void checkDylibOverridesInDir(const char* dirPath
)
1013 //dyld::log("checkDylibOverridesInDir('%s')\n", dirPath);
1014 char dylibPath
[PATH_MAX
];
1015 int dirPathLen
= strlen(dirPath
);
1016 strlcpy(dylibPath
, dirPath
, PATH_MAX
);
1017 DIR* dirp
= opendir(dirPath
);
1018 if ( dirp
!= NULL
) {
1020 dirent
* entp
= NULL
;
1021 while ( readdir_r(dirp
, &entry
, &entp
) == 0 ) {
1024 if ( entp
->d_type
!= DT_REG
)
1026 dylibPath
[dirPathLen
] = '/';
1027 dylibPath
[dirPathLen
+1] = '\0';
1028 if ( strlcat(dylibPath
, entp
->d_name
, PATH_MAX
) > PATH_MAX
)
1030 checkDylibOverride(dylibPath
);
1037 static void checkFrameworkOverridesInDir(const char* dirPath
)
1039 //dyld::log("checkFrameworkOverridesInDir('%s')\n", dirPath);
1040 char frameworkPath
[PATH_MAX
];
1041 int dirPathLen
= strlen(dirPath
);
1042 strlcpy(frameworkPath
, dirPath
, PATH_MAX
);
1043 DIR* dirp
= opendir(dirPath
);
1044 if ( dirp
!= NULL
) {
1046 dirent
* entp
= NULL
;
1047 while ( readdir_r(dirp
, &entry
, &entp
) == 0 ) {
1050 if ( entp
->d_type
!= DT_DIR
)
1052 frameworkPath
[dirPathLen
] = '/';
1053 frameworkPath
[dirPathLen
+1] = '\0';
1054 int dirNameLen
= strlen(entp
->d_name
);
1055 if ( dirNameLen
< 11 )
1057 if ( strcmp(&entp
->d_name
[dirNameLen
-10], ".framework") != 0 )
1059 if ( strlcat(frameworkPath
, entp
->d_name
, PATH_MAX
) > PATH_MAX
)
1061 if ( strlcat(frameworkPath
, "/", PATH_MAX
) > PATH_MAX
)
1063 if ( strlcat(frameworkPath
, entp
->d_name
, PATH_MAX
) > PATH_MAX
)
1065 frameworkPath
[strlen(frameworkPath
)-10] = '\0';
1066 checkDylibOverride(frameworkPath
);
1073 // Turns a colon separated list of strings into a NULL terminated array
1074 // of string pointers. If mainExecutableDir param is not NULL,
1075 // substitutes @loader_path with main executable's dir.
1077 static const char** parseColonList(const char* list
, const char* mainExecutableDir
)
1079 static const char* sEmptyList
[] = { NULL
};
1081 if ( list
[0] == '\0' )
1085 for(const char* s
=list
; *s
!= '\0'; ++s
) {
1091 const char* start
= list
;
1092 char** result
= new char*[colonCount
+2];
1093 for(const char* s
=list
; *s
!= '\0'; ++s
) {
1096 if ( (mainExecutableDir
!= NULL
) && (strncmp(start
, "@loader_path/", 13) == 0) ) {
1097 int mainExecDirLen
= strlen(mainExecutableDir
);
1098 char* str
= new char[mainExecDirLen
+len
+1];
1099 strcpy(str
, mainExecutableDir
);
1100 strlcat(str
, &start
[13], mainExecDirLen
+len
+1);
1101 str
[mainExecDirLen
+len
-13] = '\0';
1103 result
[index
++] = str
;
1105 else if ( (mainExecutableDir
!= NULL
) && (strncmp(start
, "@executable_path/", 17) == 0) ) {
1106 int mainExecDirLen
= strlen(mainExecutableDir
);
1107 char* str
= new char[mainExecDirLen
+len
+1];
1108 strcpy(str
, mainExecutableDir
);
1109 strlcat(str
, &start
[17], mainExecDirLen
+len
+1);
1110 str
[mainExecDirLen
+len
-17] = '\0';
1112 result
[index
++] = str
;
1115 char* str
= new char[len
+1];
1116 strncpy(str
, start
, len
);
1119 result
[index
++] = str
;
1123 int len
= strlen(start
);
1124 if ( (mainExecutableDir
!= NULL
) && (strncmp(start
, "@loader_path/", 13) == 0) ) {
1125 int mainExecDirLen
= strlen(mainExecutableDir
);
1126 char* str
= new char[mainExecDirLen
+len
+1];
1127 strcpy(str
, mainExecutableDir
);
1128 strlcat(str
, &start
[13], mainExecDirLen
+len
+1);
1129 str
[mainExecDirLen
+len
-13] = '\0';
1130 result
[index
++] = str
;
1132 else if ( (mainExecutableDir
!= NULL
) && (strncmp(start
, "@executable_path/", 17) == 0) ) {
1133 int mainExecDirLen
= strlen(mainExecutableDir
);
1134 char* str
= new char[mainExecDirLen
+len
+1];
1135 strcpy(str
, mainExecutableDir
);
1136 strlcat(str
, &start
[17], mainExecDirLen
+len
+1);
1137 str
[mainExecDirLen
+len
-17] = '\0';
1138 result
[index
++] = str
;
1141 char* str
= new char[len
+1];
1143 result
[index
++] = str
;
1145 result
[index
] = NULL
;
1147 //dyld::log("parseColonList(%s)\n", list);
1148 //for(int i=0; result[i] != NULL; ++i)
1149 // dyld::log(" %s\n", result[i]);
1150 return (const char**)result
;
1153 static void appendParsedColonList(const char* list
, const char* mainExecutableDir
, const char* const ** storage
)
1155 const char** newlist
= parseColonList(list
, mainExecutableDir
);
1156 if ( *storage
== NULL
) {
1157 // first time, just set
1161 // need to append to existing list
1162 const char* const* existing
= *storage
;
1164 for(int i
=0; existing
[i
] != NULL
; ++i
)
1166 for(int i
=0; newlist
[i
] != NULL
; ++i
)
1168 const char** combinedList
= new const char*[count
+2];
1170 for(int i
=0; existing
[i
] != NULL
; ++i
)
1171 combinedList
[index
++] = existing
[i
];
1172 for(int i
=0; newlist
[i
] != NULL
; ++i
)
1173 combinedList
[index
++] = newlist
[i
];
1174 combinedList
[index
] = NULL
;
1176 *storage
= combinedList
;
1181 static void paths_expand_roots(const char **paths
, const char *key
, const char *val
)
1183 // assert(val != NULL);
1184 // assert(paths != NULL);
1186 size_t keyLen
= strlen(key
);
1187 for(int i
=0; paths
[i
] != NULL
; ++i
) {
1188 if ( strncmp(paths
[i
], key
, keyLen
) == 0 ) {
1189 char* newPath
= new char[strlen(val
) + (strlen(paths
[i
]) - keyLen
) + 1];
1190 strcpy(newPath
, val
);
1191 strcat(newPath
, &paths
[i
][keyLen
]);
1199 static void removePathWithPrefix(const char* paths
[], const char* prefix
)
1201 size_t prefixLen
= strlen(prefix
);
1204 for(i
= 0; paths
[i
] != NULL
; ++i
) {
1205 if ( strncmp(paths
[i
], prefix
, prefixLen
) == 0 )
1208 paths
[i
-skip
] = paths
[i
];
1210 paths
[i
-skip
] = NULL
;
1215 static void paths_dump(const char **paths
)
1217 // assert(paths != NULL);
1218 const char **strs
= paths
;
1219 while(*strs
!= NULL
)
1221 dyld::log("\"%s\"\n", *strs
);
1228 static void printOptions(const char* argv
[])
1231 while ( NULL
!= argv
[i
] ) {
1232 dyld::log("opt[%i] = \"%s\"\n", i
, argv
[i
]);
1237 static void printEnvironmentVariables(const char* envp
[])
1239 while ( NULL
!= *envp
) {
1240 dyld::log("%s\n", *envp
);
1245 void processDyldEnvironmentVariable(const char* key
, const char* value
, const char* mainExecutableDir
)
1247 if ( strcmp(key
, "DYLD_FRAMEWORK_PATH") == 0 ) {
1248 appendParsedColonList(value
, mainExecutableDir
, &sEnv
.DYLD_FRAMEWORK_PATH
);
1250 else if ( strcmp(key
, "DYLD_FALLBACK_FRAMEWORK_PATH") == 0 ) {
1251 appendParsedColonList(value
, mainExecutableDir
, &sEnv
.DYLD_FALLBACK_FRAMEWORK_PATH
);
1253 else if ( strcmp(key
, "DYLD_LIBRARY_PATH") == 0 ) {
1254 appendParsedColonList(value
, mainExecutableDir
, &sEnv
.DYLD_LIBRARY_PATH
);
1256 else if ( strcmp(key
, "DYLD_FALLBACK_LIBRARY_PATH") == 0 ) {
1257 appendParsedColonList(value
, mainExecutableDir
, &sEnv
.DYLD_FALLBACK_LIBRARY_PATH
);
1259 else if ( (strcmp(key
, "DYLD_ROOT_PATH") == 0) || (strcmp(key
, "DYLD_PATHS_ROOT") == 0) ) {
1260 if ( strcmp(value
, "/") != 0 ) {
1261 gLinkContext
.rootPaths
= parseColonList(value
, mainExecutableDir
);
1262 for (int i
=0; gLinkContext
.rootPaths
[i
] != NULL
; ++i
) {
1263 if ( gLinkContext
.rootPaths
[i
][0] != '/' ) {
1264 dyld::warn("DYLD_ROOT_PATH not used because it contains a non-absolute path\n");
1265 gLinkContext
.rootPaths
= NULL
;
1271 else if ( strcmp(key
, "DYLD_IMAGE_SUFFIX") == 0 ) {
1272 gLinkContext
.imageSuffix
= value
;
1274 else if ( strcmp(key
, "DYLD_INSERT_LIBRARIES") == 0 ) {
1275 sEnv
.DYLD_INSERT_LIBRARIES
= parseColonList(value
, NULL
);
1277 else if ( strcmp(key
, "DYLD_PRINT_OPTS") == 0 ) {
1278 sEnv
.DYLD_PRINT_OPTS
= true;
1280 else if ( strcmp(key
, "DYLD_PRINT_ENV") == 0 ) {
1281 sEnv
.DYLD_PRINT_ENV
= true;
1283 else if ( strcmp(key
, "DYLD_DISABLE_DOFS") == 0 ) {
1284 sEnv
.DYLD_DISABLE_DOFS
= true;
1286 else if ( strcmp(key
, "DYLD_DISABLE_PREFETCH") == 0 ) {
1287 gLinkContext
.preFetchDisabled
= true;
1289 else if ( strcmp(key
, "DYLD_PRINT_LIBRARIES") == 0 ) {
1290 sEnv
.DYLD_PRINT_LIBRARIES
= true;
1292 else if ( strcmp(key
, "DYLD_PRINT_LIBRARIES_POST_LAUNCH") == 0 ) {
1293 sEnv
.DYLD_PRINT_LIBRARIES_POST_LAUNCH
= true;
1295 else if ( strcmp(key
, "DYLD_BIND_AT_LAUNCH") == 0 ) {
1296 sEnv
.DYLD_BIND_AT_LAUNCH
= true;
1298 else if ( strcmp(key
, "DYLD_FORCE_FLAT_NAMESPACE") == 0 ) {
1299 gLinkContext
.bindFlat
= true;
1301 else if ( strcmp(key
, "DYLD_NEW_LOCAL_SHARED_REGIONS") == 0 ) {
1302 // ignore, no longer relevant but some scripts still set it
1304 else if ( strcmp(key
, "DYLD_NO_FIX_PREBINDING") == 0 ) {
1306 else if ( strcmp(key
, "DYLD_PREBIND_DEBUG") == 0 ) {
1307 gLinkContext
.verbosePrebinding
= true;
1309 else if ( strcmp(key
, "DYLD_PRINT_INITIALIZERS") == 0 ) {
1310 gLinkContext
.verboseInit
= true;
1312 else if ( strcmp(key
, "DYLD_PRINT_DOFS") == 0 ) {
1313 gLinkContext
.verboseDOF
= true;
1315 else if ( strcmp(key
, "DYLD_PRINT_STATISTICS") == 0 ) {
1316 sEnv
.DYLD_PRINT_STATISTICS
= true;
1318 else if ( strcmp(key
, "DYLD_PRINT_SEGMENTS") == 0 ) {
1319 gLinkContext
.verboseMapping
= true;
1321 else if ( strcmp(key
, "DYLD_PRINT_BINDINGS") == 0 ) {
1322 gLinkContext
.verboseBind
= true;
1324 else if ( strcmp(key
, "DYLD_PRINT_WEAK_BINDINGS") == 0 ) {
1325 gLinkContext
.verboseWeakBind
= true;
1327 else if ( strcmp(key
, "DYLD_PRINT_REBASINGS") == 0 ) {
1328 gLinkContext
.verboseRebase
= true;
1330 else if ( strcmp(key
, "DYLD_PRINT_APIS") == 0 ) {
1333 else if ( strcmp(key
, "DYLD_PRINT_WARNINGS") == 0 ) {
1334 gLinkContext
.verboseWarnings
= true;
1336 else if ( strcmp(key
, "DYLD_PRINT_RPATHS") == 0 ) {
1337 gLinkContext
.verboseRPaths
= true;
1339 else if ( strcmp(key
, "DYLD_PRINT_CS_NOTIFICATIONS") == 0 ) {
1340 sEnv
.DYLD_PRINT_CS_NOTIFICATIONS
= true;
1342 else if ( strcmp(key
, "DYLD_PRINT_INTERPOSING") == 0 ) {
1343 gLinkContext
.verboseInterposing
= true;
1345 else if ( strcmp(key
, "DYLD_SHARED_REGION") == 0 ) {
1346 if ( strcmp(value
, "private") == 0 ) {
1347 gLinkContext
.sharedRegionMode
= ImageLoader::kUsePrivateSharedRegion
;
1349 else if ( strcmp(value
, "avoid") == 0 ) {
1350 gLinkContext
.sharedRegionMode
= ImageLoader::kDontUseSharedRegion
;
1352 else if ( strcmp(value
, "use") == 0 ) {
1353 gLinkContext
.sharedRegionMode
= ImageLoader::kUseSharedRegion
;
1355 else if ( value
[0] == '\0' ) {
1356 gLinkContext
.sharedRegionMode
= ImageLoader::kUseSharedRegion
;
1359 dyld::warn("unknown option to DYLD_SHARED_REGION. Valid options are: use, private, avoid\n");
1362 #if DYLD_SHARED_CACHE_SUPPORT
1363 else if ( strcmp(key
, "DYLD_SHARED_CACHE_DIR") == 0 ) {
1364 sSharedCacheDir
= value
;
1366 else if ( strcmp(key
, "DYLD_SHARED_CACHE_DONT_VALIDATE") == 0 ) {
1367 sSharedCacheIgnoreInodeAndTimeStamp
= true;
1370 else if ( strcmp(key
, "DYLD_IGNORE_PREBINDING") == 0 ) {
1371 if ( strcmp(value
, "all") == 0 ) {
1372 gLinkContext
.prebindUsage
= ImageLoader::kUseNoPrebinding
;
1374 else if ( strcmp(value
, "app") == 0 ) {
1375 gLinkContext
.prebindUsage
= ImageLoader::kUseAllButAppPredbinding
;
1377 else if ( strcmp(value
, "nonsplit") == 0 ) {
1378 gLinkContext
.prebindUsage
= ImageLoader::kUseSplitSegPrebinding
;
1380 else if ( value
[0] == '\0' ) {
1381 gLinkContext
.prebindUsage
= ImageLoader::kUseSplitSegPrebinding
;
1384 dyld::warn("unknown option to DYLD_IGNORE_PREBINDING. Valid options are: all, app, nonsplit\n");
1387 #if SUPPORT_VERSIONED_PATHS
1388 else if ( strcmp(key
, "DYLD_VERSIONED_LIBRARY_PATH") == 0 ) {
1389 appendParsedColonList(value
, mainExecutableDir
, &sEnv
.DYLD_VERSIONED_LIBRARY_PATH
);
1391 else if ( strcmp(key
, "DYLD_VERSIONED_FRAMEWORK_PATH") == 0 ) {
1392 appendParsedColonList(value
, mainExecutableDir
, &sEnv
.DYLD_VERSIONED_FRAMEWORK_PATH
);
1396 dyld::warn("unknown environment variable: %s\n", key
);
1401 #if SUPPORT_LC_DYLD_ENVIRONMENT
1402 static void checkLoadCommandEnvironmentVariables()
1404 // <rdar://problem/8440934> Support augmenting dyld environment variables in load commands
1405 const uint32_t cmd_count
= sMainExecutableMachHeader
->ncmds
;
1406 const struct load_command
* const cmds
= (struct load_command
*)(((char*)sMainExecutableMachHeader
)+sizeof(macho_header
));
1407 const struct load_command
* cmd
= cmds
;
1408 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
1410 case LC_DYLD_ENVIRONMENT
:
1412 const struct dylinker_command
* envcmd
= (struct dylinker_command
*)cmd
;
1413 const char* keyEqualsValue
= (char*)envcmd
+ envcmd
->name
.offset
;
1414 char mainExecutableDir
[strlen(sExecPath
)];
1415 strcpy(mainExecutableDir
, sExecPath
);
1416 char* lastSlash
= strrchr(mainExecutableDir
, '/');
1417 if ( lastSlash
!= NULL
)
1418 lastSlash
[1] = '\0';
1419 // only process variables that start with DYLD_ and end in _PATH
1420 if ( (strncmp(keyEqualsValue
, "DYLD_", 5) == 0) ) {
1421 const char* equals
= strchr(keyEqualsValue
, '=');
1422 if ( equals
!= NULL
) {
1423 if ( strncmp(&equals
[-5], "_PATH", 5) == 0 ) {
1424 const char* value
= &equals
[1];
1425 const int keyLen
= equals
-keyEqualsValue
;
1427 strncpy(key
, keyEqualsValue
, keyLen
);
1429 //dyld::log("processing: %s\n", keyEqualsValue);
1430 //dyld::log("mainExecutableDir: %s\n", mainExecutableDir);
1431 processDyldEnvironmentVariable(key
, value
, mainExecutableDir
);
1438 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
1441 #endif // SUPPORT_LC_DYLD_ENVIRONMENT
1444 #if SUPPORT_VERSIONED_PATHS
1445 static void checkVersionedPaths()
1447 // search DYLD_VERSIONED_LIBRARY_PATH directories for dylibs and check if they are newer
1448 if ( sEnv
.DYLD_VERSIONED_LIBRARY_PATH
!= NULL
) {
1449 for(const char* const* lp
= sEnv
.DYLD_VERSIONED_LIBRARY_PATH
; *lp
!= NULL
; ++lp
) {
1450 checkDylibOverridesInDir(*lp
);
1454 // search DYLD_VERSIONED_FRAMEWORK_PATH directories for dylibs and check if they are newer
1455 if ( sEnv
.DYLD_VERSIONED_FRAMEWORK_PATH
!= NULL
) {
1456 for(const char* const* fp
= sEnv
.DYLD_VERSIONED_FRAMEWORK_PATH
; *fp
!= NULL
; ++fp
) {
1457 checkFrameworkOverridesInDir(*fp
);
1465 // For security, setuid programs ignore DYLD_* environment variables.
1466 // Additionally, the DYLD_* enviroment variables are removed
1467 // from the environment, so that any child processes don't see them.
1469 static void pruneEnvironmentVariables(const char* envp
[], const char*** applep
)
1471 // delete all DYLD_* and LD_LIBRARY_PATH environment variables
1472 int removedCount
= 0;
1473 const char** d
= envp
;
1474 for(const char** s
= envp
; *s
!= NULL
; s
++) {
1475 if ( (strncmp(*s
, "DYLD_", 5) != 0) && (strncmp(*s
, "LD_LIBRARY_PATH=", 16) != 0) ) {
1484 // slide apple parameters
1485 if ( removedCount
> 0 ) {
1488 *d
= d
[removedCount
];
1489 } while ( *d
++ != NULL
);
1490 for(int i
=0; i
< removedCount
; ++i
)
1494 // disable framework and library fallback paths for setuid binaries rdar://problem/4589305
1495 sEnv
.DYLD_FALLBACK_FRAMEWORK_PATH
= NULL
;
1496 sEnv
.DYLD_FALLBACK_LIBRARY_PATH
= NULL
;
1500 static void checkEnvironmentVariables(const char* envp
[], bool ignoreEnviron
)
1502 const char* home
= NULL
;
1504 for(p
= envp
; *p
!= NULL
; p
++) {
1505 const char* keyEqualsValue
= *p
;
1506 if ( strncmp(keyEqualsValue
, "DYLD_", 5) == 0 ) {
1507 const char* equals
= strchr(keyEqualsValue
, '=');
1508 if ( (equals
!= NULL
) && !ignoreEnviron
) {
1509 const char* value
= &equals
[1];
1510 const int keyLen
= equals
-keyEqualsValue
;
1512 strncpy(key
, keyEqualsValue
, keyLen
);
1514 processDyldEnvironmentVariable(key
, value
, NULL
);
1517 else if ( strncmp(keyEqualsValue
, "HOME=", 5) == 0 ) {
1518 home
= &keyEqualsValue
[5];
1520 else if ( strncmp(keyEqualsValue
, "LD_LIBRARY_PATH=", 16) == 0 ) {
1521 const char* path
= &keyEqualsValue
[16];
1522 sEnv
.LD_LIBRARY_PATH
= parseColonList(path
, NULL
);
1526 #if SUPPORT_LC_DYLD_ENVIRONMENT
1527 checkLoadCommandEnvironmentVariables();
1528 #endif // SUPPORT_LC_DYLD_ENVIRONMENT
1530 // default value for DYLD_FALLBACK_FRAMEWORK_PATH, if not set in environment
1531 if ( sEnv
.DYLD_FALLBACK_FRAMEWORK_PATH
== NULL
) {
1532 const char** paths
= sFrameworkFallbackPaths
;
1534 removePathWithPrefix(paths
, "$HOME");
1536 paths_expand_roots(paths
, "$HOME", home
);
1537 sEnv
.DYLD_FALLBACK_FRAMEWORK_PATH
= paths
;
1540 // default value for DYLD_FALLBACK_LIBRARY_PATH, if not set in environment
1541 if ( sEnv
.DYLD_FALLBACK_LIBRARY_PATH
== NULL
) {
1542 const char** paths
= sLibraryFallbackPaths
;
1544 removePathWithPrefix(paths
, "$HOME");
1546 paths_expand_roots(paths
, "$HOME", home
);
1547 sEnv
.DYLD_FALLBACK_LIBRARY_PATH
= paths
;
1550 #if SUPPORT_VERSIONED_PATHS
1551 checkVersionedPaths();
1556 static void getHostInfo()
1558 #if CPU_SUBTYPES_SUPPORTED
1560 sHostCPU
= CPU_TYPE_ARM
;
1561 sHostCPUsubtype
= CPU_SUBTYPE_ARM_V7
;
1562 #elif __ARM_ARCH_6K__
1563 sHostCPU
= CPU_TYPE_ARM
;
1564 sHostCPUsubtype
= CPU_SUBTYPE_ARM_V6
;
1566 struct host_basic_info info
;
1567 mach_msg_type_number_t count
= HOST_BASIC_INFO_COUNT
;
1568 mach_port_t hostPort
= mach_host_self();
1569 kern_return_t result
= host_info(hostPort
, HOST_BASIC_INFO
, (host_info_t
)&info
, &count
);
1570 if ( result
!= KERN_SUCCESS
)
1571 throw "host_info() failed";
1572 sHostCPU
= info
.cpu_type
;
1573 sHostCPUsubtype
= info
.cpu_subtype
;
1578 static void checkSharedRegionDisable()
1580 #if __MAC_OS_X_VERSION_MIN_REQUIRED
1581 // if main executable has segments that overlap the shared region,
1582 // then disable using the shared region
1583 if ( sMainExecutable
->overlapsWithAddressRange((void*)(uintptr_t)SHARED_REGION_BASE
, (void*)(uintptr_t)(SHARED_REGION_BASE
+ SHARED_REGION_SIZE
)) ) {
1584 gLinkContext
.sharedRegionMode
= ImageLoader::kDontUseSharedRegion
;
1585 if ( gLinkContext
.verboseMapping
)
1586 dyld::warn("disabling shared region because main executable overlaps\n");
1589 // iPhoneOS cannot run without shared region
1592 bool validImage(const ImageLoader
* possibleImage
)
1594 const unsigned int imageCount
= sAllImages
.size();
1595 for(unsigned int i
=0; i
< imageCount
; ++i
) {
1596 if ( possibleImage
== sAllImages
[i
] ) {
1603 uint32_t getImageCount()
1605 return sAllImages
.size();
1608 ImageLoader
* getIndexedImage(unsigned int index
)
1610 if ( index
< sAllImages
.size() )
1611 return sAllImages
[index
];
1615 ImageLoader
* findImageByMachHeader(const struct mach_header
* target
)
1617 return findMappedRange((uintptr_t)target
);
1621 ImageLoader
* findImageContainingAddress(const void* addr
)
1623 return findMappedRange((uintptr_t)addr
);
1627 ImageLoader
* findImageContainingSymbol(const void* symbol
)
1629 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
1630 ImageLoader
* anImage
= *it
;
1631 if ( anImage
->containsSymbol(symbol
) )
1639 void forEachImageDo( void (*callback
)(ImageLoader
*, void* userData
), void* userData
)
1641 const unsigned int imageCount
= sAllImages
.size();
1642 for(unsigned int i
=0; i
< imageCount
; ++i
) {
1643 ImageLoader
* anImage
= sAllImages
[i
];
1644 (*callback
)(anImage
, userData
);
1648 ImageLoader
* findLoadedImage(const struct stat
& stat_buf
)
1650 const unsigned int imageCount
= sAllImages
.size();
1651 for(unsigned int i
=0; i
< imageCount
; ++i
){
1652 ImageLoader
* anImage
= sAllImages
[i
];
1653 if ( anImage
->statMatch(stat_buf
) )
1659 // based on ANSI-C strstr()
1660 static const char* strrstr(const char* str
, const char* sub
)
1662 const int sublen
= strlen(sub
);
1663 for(const char* p
= &str
[strlen(str
)]; p
!= str
; --p
) {
1664 if ( strncmp(p
, sub
, sublen
) == 0 )
1672 // Find framework path
1674 // /path/foo.framework/foo => foo.framework/foo
1675 // /path/foo.framework/Versions/A/foo => foo.framework/Versions/A/foo
1676 // /path/foo.framework/Frameworks/bar.framework/bar => bar.framework/bar
1677 // /path/foo.framework/Libraries/bar.dylb => NULL
1678 // /path/foo.framework/bar => NULL
1680 // Returns NULL if not a framework path
1682 static const char* getFrameworkPartialPath(const char* path
)
1684 const char* dirDot
= strrstr(path
, ".framework/");
1685 if ( dirDot
!= NULL
) {
1686 const char* dirStart
= dirDot
;
1687 for ( ; dirStart
>= path
; --dirStart
) {
1688 if ( (*dirStart
== '/') || (dirStart
== path
) ) {
1689 const char* frameworkStart
= &dirStart
[1];
1690 if ( dirStart
== path
)
1692 int len
= dirDot
- frameworkStart
;
1693 char framework
[len
+1];
1694 strncpy(framework
, frameworkStart
, len
);
1695 framework
[len
] = '\0';
1696 const char* leaf
= strrchr(path
, '/');
1697 if ( leaf
!= NULL
) {
1698 if ( strcmp(framework
, &leaf
[1]) == 0 ) {
1699 return frameworkStart
;
1701 if ( gLinkContext
.imageSuffix
!= NULL
) {
1702 // some debug frameworks have install names that end in _debug
1703 if ( strncmp(framework
, &leaf
[1], len
) == 0 ) {
1704 if ( strcmp( gLinkContext
.imageSuffix
, &leaf
[len
+1]) == 0 )
1705 return frameworkStart
;
1716 static const char* getLibraryLeafName(const char* path
)
1718 const char* start
= strrchr(path
, '/');
1719 if ( start
!= NULL
)
1726 // only for architectures that use cpu-sub-types
1727 #if CPU_SUBTYPES_SUPPORTED
1729 const cpu_subtype_t CPU_SUBTYPE_END_OF_LIST
= -1;
1733 // A fat file may contain multiple sub-images for the same CPU type.
1734 // In that case, dyld picks which sub-image to use by scanning a table
1735 // of preferred cpu-sub-types for the running cpu.
1737 // There is one row in the table for each cpu-sub-type on which dyld might run.
1738 // The first entry in a row is that cpu-sub-type. It is followed by all
1739 // cpu-sub-types that can run on that cpu, if preferred order. Each row ends with
1740 // a "SUBTYPE_ALL" (to denote that images written to run on any cpu-sub-type are usable),
1741 // followed by one or more CPU_SUBTYPE_END_OF_LIST to pad out this row.
1747 // 32-bit PowerPC sub-type lists
1749 const int kPPC_RowCount
= 4;
1750 static const cpu_subtype_t kPPC32
[kPPC_RowCount
][6] = {
1751 // G5 can run any code
1752 { CPU_SUBTYPE_POWERPC_970
, CPU_SUBTYPE_POWERPC_7450
, CPU_SUBTYPE_POWERPC_7400
, CPU_SUBTYPE_POWERPC_750
, CPU_SUBTYPE_POWERPC_ALL
, CPU_SUBTYPE_END_OF_LIST
},
1754 // G4 can run all but G5 code
1755 { CPU_SUBTYPE_POWERPC_7450
, CPU_SUBTYPE_POWERPC_7400
, CPU_SUBTYPE_POWERPC_750
, CPU_SUBTYPE_POWERPC_ALL
, CPU_SUBTYPE_END_OF_LIST
, CPU_SUBTYPE_END_OF_LIST
},
1756 { CPU_SUBTYPE_POWERPC_7400
, CPU_SUBTYPE_POWERPC_7450
, CPU_SUBTYPE_POWERPC_750
, CPU_SUBTYPE_POWERPC_ALL
, CPU_SUBTYPE_END_OF_LIST
, CPU_SUBTYPE_END_OF_LIST
},
1758 // G3 cannot run G4 or G5 code
1759 { CPU_SUBTYPE_POWERPC_750
, CPU_SUBTYPE_POWERPC_ALL
, CPU_SUBTYPE_END_OF_LIST
, CPU_SUBTYPE_END_OF_LIST
, CPU_SUBTYPE_END_OF_LIST
, CPU_SUBTYPE_END_OF_LIST
}
1766 // ARM sub-type lists
1768 const int kARM_RowCount
= 5;
1769 static const cpu_subtype_t kARM
[kARM_RowCount
][6] = {
1770 // armv7 can run: v7, v6, v5, and v4
1771 { 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
},
1773 // armv6 can run: v6, v5, and v4
1774 { 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
},
1776 // xscale can run: xscale, v5, and v4
1777 { 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
},
1779 // armv5 can run: v5 and v4
1780 { 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
},
1782 // armv4 can run: v4
1783 { 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
},
1788 // scan the tables above to find the cpu-sub-type-list for this machine
1789 static const cpu_subtype_t
* findCPUSubtypeList(cpu_type_t cpu
, cpu_subtype_t subtype
)
1793 case CPU_TYPE_POWERPC
:
1794 for (int i
=0; i
< kPPC_RowCount
; ++i
) {
1795 if ( kPPC32
[i
][0] == subtype
)
1802 for (int i
=0; i
< kARM_RowCount
; ++i
) {
1803 if ( kARM
[i
][0] == subtype
)
1815 // scan fat table-of-contents for best most preferred subtype
1816 static bool fatFindBestFromOrderedList(cpu_type_t cpu
, const cpu_subtype_t list
[], const fat_header
* fh
, uint64_t* offset
, uint64_t* len
)
1818 const fat_arch
* const archs
= (fat_arch
*)(((char*)fh
)+sizeof(fat_header
));
1819 for (uint32_t subTypeIndex
=0; list
[subTypeIndex
] != CPU_SUBTYPE_END_OF_LIST
; ++subTypeIndex
) {
1820 for(uint32_t fatIndex
=0; fatIndex
< OSSwapBigToHostInt32(fh
->nfat_arch
); ++fatIndex
) {
1821 if ( ((cpu_type_t
)OSSwapBigToHostInt32(archs
[fatIndex
].cputype
) == cpu
)
1822 && (list
[subTypeIndex
] == (cpu_subtype_t
)OSSwapBigToHostInt32(archs
[fatIndex
].cpusubtype
)) ) {
1823 *offset
= OSSwapBigToHostInt32(archs
[fatIndex
].offset
);
1824 *len
= OSSwapBigToHostInt32(archs
[fatIndex
].size
);
1832 // scan fat table-of-contents for exact match of cpu and cpu-sub-type
1833 static bool fatFindExactMatch(cpu_type_t cpu
, cpu_subtype_t subtype
, const fat_header
* fh
, uint64_t* offset
, uint64_t* len
)
1835 const fat_arch
* archs
= (fat_arch
*)(((char*)fh
)+sizeof(fat_header
));
1836 for(uint32_t i
=0; i
< OSSwapBigToHostInt32(fh
->nfat_arch
); ++i
) {
1837 if ( ((cpu_type_t
)OSSwapBigToHostInt32(archs
[i
].cputype
) == cpu
)
1838 && ((cpu_subtype_t
)OSSwapBigToHostInt32(archs
[i
].cpusubtype
) == subtype
) ) {
1839 *offset
= OSSwapBigToHostInt32(archs
[i
].offset
);
1840 *len
= OSSwapBigToHostInt32(archs
[i
].size
);
1847 // scan fat table-of-contents for image with matching cpu-type and runs-on-all-sub-types
1848 static bool fatFindRunsOnAllCPUs(cpu_type_t cpu
, const fat_header
* fh
, uint64_t* offset
, uint64_t* len
)
1850 const fat_arch
* archs
= (fat_arch
*)(((char*)fh
)+sizeof(fat_header
));
1851 for(uint32_t i
=0; i
< OSSwapBigToHostInt32(fh
->nfat_arch
); ++i
) {
1852 if ( (cpu_type_t
)OSSwapBigToHostInt32(archs
[i
].cputype
) == cpu
) {
1855 case CPU_TYPE_POWERPC
:
1856 if ( (cpu_subtype_t
)OSSwapBigToHostInt32(archs
[i
].cpusubtype
) == CPU_SUBTYPE_POWERPC_ALL
) {
1857 *offset
= OSSwapBigToHostInt32(archs
[i
].offset
);
1858 *len
= OSSwapBigToHostInt32(archs
[i
].size
);
1865 if ( (cpu_subtype_t
)OSSwapBigToHostInt32(archs
[i
].cpusubtype
) == CPU_SUBTYPE_ARM_ALL
) {
1866 *offset
= OSSwapBigToHostInt32(archs
[i
].offset
);
1867 *len
= OSSwapBigToHostInt32(archs
[i
].size
);
1878 #endif // CPU_SUBTYPES_SUPPORTED
1881 // A fat file may contain multiple sub-images for the same cpu-type,
1882 // each optimized for a different cpu-sub-type (e.g G3 or G5).
1883 // This routine picks the optimal sub-image.
1885 static bool fatFindBest(const fat_header
* fh
, uint64_t* offset
, uint64_t* len
)
1887 #if CPU_SUBTYPES_SUPPORTED
1888 // assume all dylibs loaded must have same cpu type as main executable
1889 const cpu_type_t cpu
= sMainExecutableMachHeader
->cputype
;
1891 // We only know the subtype to use if the main executable cpu type matches the host
1892 if ( (cpu
& CPU_TYPE_MASK
) == sHostCPU
) {
1893 // get preference ordered list of subtypes
1894 const cpu_subtype_t
* subTypePreferenceList
= findCPUSubtypeList(cpu
, sHostCPUsubtype
);
1896 // use ordered list to find best sub-image in fat file
1897 if ( subTypePreferenceList
!= NULL
)
1898 return fatFindBestFromOrderedList(cpu
, subTypePreferenceList
, fh
, offset
, len
);
1900 // if running cpu is not in list, try for an exact match
1901 if ( fatFindExactMatch(cpu
, sHostCPUsubtype
, fh
, offset
, len
) )
1905 // running on an uknown cpu, can only load generic code
1906 return fatFindRunsOnAllCPUs(cpu
, fh
, offset
, len
);
1908 // just find first slice with matching architecture
1909 const fat_arch
* archs
= (fat_arch
*)(((char*)fh
)+sizeof(fat_header
));
1910 for(uint32_t i
=0; i
< OSSwapBigToHostInt32(fh
->nfat_arch
); ++i
) {
1911 if ( (cpu_type_t
)OSSwapBigToHostInt32(archs
[i
].cputype
) == sMainExecutableMachHeader
->cputype
) {
1912 *offset
= OSSwapBigToHostInt32(archs
[i
].offset
);
1913 *len
= OSSwapBigToHostInt32(archs
[i
].size
);
1924 // This is used to validate if a non-fat (aka thin or raw) mach-o file can be used
1925 // on the current processor. //
1926 bool isCompatibleMachO(const uint8_t* firstPage
, const char* path
)
1928 #if CPU_SUBTYPES_SUPPORTED
1929 // It is deemed compatible if any of the following are true:
1930 // 1) mach_header subtype is in list of compatible subtypes for running processor
1931 // 2) mach_header subtype is same as running processor subtype
1932 // 3) mach_header subtype runs on all processor variants
1933 const mach_header
* mh
= (mach_header
*)firstPage
;
1934 if ( mh
->magic
== sMainExecutableMachHeader
->magic
) {
1935 if ( mh
->cputype
== sMainExecutableMachHeader
->cputype
) {
1936 if ( (mh
->cputype
& CPU_TYPE_MASK
) == sHostCPU
) {
1937 // get preference ordered list of subtypes that this machine can use
1938 const cpu_subtype_t
* subTypePreferenceList
= findCPUSubtypeList(mh
->cputype
, sHostCPUsubtype
);
1939 if ( subTypePreferenceList
!= NULL
) {
1940 // if image's subtype is in the list, it is compatible
1941 for (const cpu_subtype_t
* p
= subTypePreferenceList
; *p
!= CPU_SUBTYPE_END_OF_LIST
; ++p
) {
1942 if ( *p
== mh
->cpusubtype
)
1945 // have list and not in list, so not compatible
1946 throwf("incompatible cpu-subtype: 0x%08X in %s", mh
->cpusubtype
, path
);
1948 // unknown cpu sub-type, but if exact match for current subtype then ok to use
1949 if ( mh
->cpusubtype
== sHostCPUsubtype
)
1953 // cpu type has no ordered list of subtypes
1954 switch (mh
->cputype
) {
1955 case CPU_TYPE_POWERPC
:
1956 // allow _ALL to be used by any client
1957 if ( mh
->cpusubtype
== CPU_SUBTYPE_POWERPC_ALL
)
1960 case CPU_TYPE_POWERPC64
:
1962 case CPU_TYPE_X86_64
:
1963 // subtypes are not used or these architectures
1969 // For architectures that don't support cpu-sub-types
1970 // this just check the cpu type.
1971 const mach_header
* mh
= (mach_header
*)firstPage
;
1972 if ( mh
->magic
== sMainExecutableMachHeader
->magic
) {
1973 if ( mh
->cputype
== sMainExecutableMachHeader
->cputype
) {
1984 // The kernel maps in main executable before dyld gets control. We need to
1985 // make an ImageLoader* for the already mapped in main executable.
1986 static ImageLoader
* instantiateFromLoadedImage(const macho_header
* mh
, uintptr_t slide
, const char* path
)
1988 // try mach-o loader
1989 if ( isCompatibleMachO((const uint8_t*)mh
, path
) ) {
1990 ImageLoader
* image
= ImageLoaderMachO::instantiateMainExecutable(mh
, slide
, path
, gLinkContext
);
1995 throw "main executable not a known format";
1999 #if DYLD_SHARED_CACHE_SUPPORT
2000 static bool findInSharedCacheImage(const char* path
, const struct stat
* stat_buf
, const macho_header
** mh
, const char** pathInCache
, long* slide
)
2002 if ( sSharedCache
!= NULL
) {
2003 #if __MAC_OS_X_VERSION_MIN_REQUIRED
2004 // Mac OS X always requires inode/mtime to valid cache
2005 // if stat() not done yet, do it now
2007 if ( stat_buf
== NULL
) {
2008 if ( stat(path
, &statb
) == -1 )
2013 // walk shared cache to see if there is a cached image that matches the inode/mtime/path desired
2014 const dyld_cache_image_info
* const start
= (dyld_cache_image_info
*)((uint8_t*)sSharedCache
+ sSharedCache
->imagesOffset
);
2015 const dyld_cache_image_info
* const end
= &start
[sSharedCache
->imagesCount
];
2016 for( const dyld_cache_image_info
* p
= start
; p
!= end
; ++p
) {
2017 #if __IPHONE_OS_VERSION_MIN_REQUIRED
2019 const char* aPath
= (char*)sSharedCache
+ p
->pathFileOffset
;
2020 if ( strcmp(path
, aPath
) == 0 ) {
2021 // found image in cache
2022 *mh
= (macho_header
*)(p
->address
+sSharedCacheSlide
);
2023 *pathInCache
= aPath
;
2024 *slide
= sSharedCacheSlide
;
2027 #elif __MAC_OS_X_VERSION_MIN_REQUIRED
2028 // check mtime and inode first because it is fast
2029 if ( sSharedCacheIgnoreInodeAndTimeStamp
2030 || ( ((time_t)p
->modTime
== stat_buf
->st_mtime
) && ((ino_t
)p
->inode
== stat_buf
->st_ino
) ) ) {
2031 // mod-time and inode match an image in the shared cache, now check path
2032 const char* aPath
= (char*)sSharedCache
+ p
->pathFileOffset
;
2033 bool cacheHit
= (strcmp(path
, aPath
) == 0);
2035 // path does not match install name of dylib in cache, but inode and mtime does match
2036 // perhaps path is a symlink to the cached dylib
2037 struct stat pathInCacheStatBuf
;
2038 if ( stat(aPath
, &pathInCacheStatBuf
) != -1 )
2039 cacheHit
= ( (pathInCacheStatBuf
.st_dev
== stat_buf
->st_dev
) && (pathInCacheStatBuf
.st_ino
== stat_buf
->st_ino
) );
2042 // found image in cache, return info
2043 *mh
= (macho_header
*)(p
->address
+sSharedCacheSlide
);
2044 //dyld::log("findInSharedCacheImage(), mh=%p, p->address=0x%0llX, slid=0x%0lX, path=%p\n",
2045 // *mh, p->address, sSharedCacheSlide, aPath);
2046 *pathInCache
= aPath
;
2047 *slide
= sSharedCacheSlide
;
2057 bool inSharedCache(const char* path
)
2059 const macho_header
* mhInCache
;
2060 const char* pathInCache
;
2062 return findInSharedCacheImage(path
, NULL
, &mhInCache
, &pathInCache
, &slide
);
2067 static ImageLoader
* checkandAddImage(ImageLoader
* image
, const LoadContext
& context
)
2069 // now sanity check that this loaded image does not have the same install path as any existing image
2070 const char* loadedImageInstallPath
= image
->getInstallPath();
2071 if ( image
->isDylib() && (loadedImageInstallPath
!= NULL
) && (loadedImageInstallPath
[0] == '/') ) {
2072 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
2073 ImageLoader
* anImage
= *it
;
2074 const char* installPath
= anImage
->getInstallPath();
2075 if ( installPath
!= NULL
) {
2076 if ( strcmp(loadedImageInstallPath
, installPath
) == 0 ) {
2077 //dyld::log("duplicate(%s) => %p\n", installPath, anImage);
2079 ImageLoader::deleteImage(image
);
2086 // some API's restrict what they can load
2087 if ( context
.mustBeBundle
&& !image
->isBundle() )
2088 throw "not a bundle";
2089 if ( context
.mustBeDylib
&& !image
->isDylib() )
2090 throw "not a dylib";
2092 // regular main executables cannot be loaded
2093 if ( image
->isExecutable() ) {
2094 if ( !context
.canBePIE
|| !image
->isPositionIndependentExecutable() )
2095 throw "can't load a main executable";
2098 // don't add bundles to global list, they can be loaded but not linked. When linked it will be added to list
2099 if ( ! image
->isBundle() )
2105 // map in file and instantiate an ImageLoader
2106 static ImageLoader
* loadPhase6(int fd
, const struct stat
& stat_buf
, const char* path
, const LoadContext
& context
)
2108 //dyld::log("%s(%s)\n", __func__ , path);
2109 uint64_t fileOffset
= 0;
2110 uint64_t fileLength
= stat_buf
.st_size
;
2112 // validate it is a file (not directory)
2113 if ( (stat_buf
.st_mode
& S_IFMT
) != S_IFREG
)
2116 uint8_t firstPage
[4096];
2117 bool shortPage
= false;
2119 // min mach-o file is 4K
2120 if ( fileLength
< 4096 ) {
2121 if ( pread(fd
, firstPage
, fileLength
, 0) != (ssize_t
)fileLength
)
2122 throwf("pread of short file failed: %d", errno
);
2126 if ( pread(fd
, firstPage
, 4096,0) != 4096 )
2127 throwf("pread of first 4K failed: %d", errno
);
2130 // if fat wrapper, find usable sub-file
2131 const fat_header
* fileStartAsFat
= (fat_header
*)firstPage
;
2132 if ( fileStartAsFat
->magic
== OSSwapBigToHostInt32(FAT_MAGIC
) ) {
2133 if ( fatFindBest(fileStartAsFat
, &fileOffset
, &fileLength
) ) {
2134 if ( (fileOffset
+fileLength
) > (uint64_t)(stat_buf
.st_size
) )
2135 throwf("truncated fat file. file length=%llu, but needed slice goes to %llu", stat_buf
.st_size
, fileOffset
+fileLength
);
2136 if (pread(fd
, firstPage
, 4096, fileOffset
) != 4096)
2137 throwf("pread of fat file failed: %d", errno
);
2140 throw "no matching architecture in universal wrapper";
2144 // try mach-o loader
2146 throw "file too short";
2147 if ( isCompatibleMachO(firstPage
, path
) ) {
2149 // only MH_BUNDLE, MH_DYLIB, and some MH_EXECUTE can be dynamically loaded
2150 switch ( ((mach_header
*)firstPage
)->filetype
) {
2156 throw "mach-o, but wrong filetype";
2159 // instantiate an image
2160 ImageLoader
* image
= ImageLoaderMachO::instantiateFromFile(path
, fd
, firstPage
, fileOffset
, fileLength
, stat_buf
, gLinkContext
);
2163 return checkandAddImage(image
, context
);
2166 // try other file formats here...
2169 // throw error about what was found
2170 switch (*(uint32_t*)firstPage
) {
2175 throw "mach-o, but wrong architecture";
2177 throwf("unknown file type, first eight bytes: 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X",
2178 firstPage
[0], firstPage
[1], firstPage
[2], firstPage
[3], firstPage
[4], firstPage
[5], firstPage
[6],firstPage
[7]);
2183 static ImageLoader
* loadPhase5open(const char* path
, const LoadContext
& context
, const struct stat
& stat_buf
, std::vector
<const char*>* exceptions
)
2185 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
2187 // open file (automagically closed when this function exits)
2188 FileOpener
file(path
);
2190 // just return NULL if file not found, but record any other errors
2191 if ( file
.getFileDescriptor() == -1 ) {
2193 if ( err
!= ENOENT
) {
2194 const char* newMsg
= dyld::mkstringf("%s: open() failed with errno=%d", path
, err
);
2195 exceptions
->push_back(newMsg
);
2201 return loadPhase6(file
.getFileDescriptor(), stat_buf
, path
, context
);
2203 catch (const char* msg
) {
2204 const char* newMsg
= dyld::mkstringf("%s: %s", path
, msg
);
2205 exceptions
->push_back(newMsg
);
2212 #if __MAC_OS_X_VERSION_MIN_REQUIRED
2213 static ImageLoader
* loadPhase5load(const char* path
, const char* orgPath
, const LoadContext
& context
, std::vector
<const char*>* exceptions
)
2215 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
2216 ImageLoader
* image
= NULL
;
2218 // just return NULL if file not found, but record any other errors
2219 struct stat stat_buf
;
2220 if ( stat(path
, &stat_buf
) == -1 ) {
2222 if ( err
!= ENOENT
) {
2223 exceptions
->push_back(dyld::mkstringf("%s: stat() failed with errno=%d", path
, err
));
2228 // in case image was renamed or found via symlinks, check for inode match
2229 image
= findLoadedImage(stat_buf
);
2230 if ( image
!= NULL
)
2233 // do nothing if not already loaded and if RTLD_NOLOAD or NSADDIMAGE_OPTION_RETURN_ONLY_IF_LOADED
2234 if ( context
.dontLoad
)
2237 #if DYLD_SHARED_CACHE_SUPPORT
2238 // see if this image is in shared cache
2239 const macho_header
* mhInCache
;
2240 const char* pathInCache
;
2242 if ( findInSharedCacheImage(path
, &stat_buf
, &mhInCache
, &pathInCache
, &slideInCache
) ) {
2243 image
= ImageLoaderMachO::instantiateFromCache(mhInCache
, pathInCache
, slideInCache
, stat_buf
, gLinkContext
);
2244 return checkandAddImage(image
, context
);
2247 // file exists and is not in dyld shared cache, so open it
2248 return loadPhase5open(path
, context
, stat_buf
, exceptions
);
2250 #endif // __MAC_OS_X_VERSION_MIN_REQUIRED
2254 #if __IPHONE_OS_VERSION_MIN_REQUIRED
2255 static ImageLoader
* loadPhase5stat(const char* path
, const LoadContext
& context
, struct stat
* stat_buf
,
2256 int* statErrNo
, bool* imageFound
, std::vector
<const char*>* exceptions
)
2258 ImageLoader
* image
= NULL
;
2259 *imageFound
= false;
2260 if ( stat(path
, stat_buf
) == 0 ) {
2261 // in case image was renamed or found via symlinks, check for inode match
2262 image
= findLoadedImage(*stat_buf
);
2263 if ( image
!= NULL
) {
2267 // do nothing if not already loaded and if RTLD_NOLOAD
2268 if ( context
.dontLoad
) {
2272 image
= loadPhase5open(path
, context
, *stat_buf
, exceptions
);
2273 if ( image
!= NULL
) {
2285 static ImageLoader
* loadPhase5load(const char* path
, const char* orgPath
, const LoadContext
& context
, std::vector
<const char*>* exceptions
)
2287 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
2288 struct stat stat_buf
;
2292 #if DYLD_SHARED_CACHE_SUPPORT
2293 if ( sDylibsOverrideCache
) {
2294 // flag is set that allows installed framework roots to override dyld shared cache
2295 image
= loadPhase5stat(path
, context
, &stat_buf
, &statErrNo
, &imageFound
, exceptions
);
2299 // see if this image is in shared cache
2300 const macho_header
* mhInCache
;
2301 const char* pathInCache
;
2303 if ( findInSharedCacheImage(path
, NULL
, &mhInCache
, &pathInCache
, &slideInCache
) ) {
2304 // see if this image in the cache was already loaded via a different path
2305 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); ++it
) {
2306 ImageLoader
* anImage
= *it
;
2307 if ( anImage
->machHeader() == mhInCache
)
2310 // do nothing if not already loaded and if RTLD_NOLOAD
2311 if ( context
.dontLoad
)
2313 // nope, so instantiate a new image from dyld shared cache
2314 // <rdar://problem/7014995> zero out stat buffer so mtime, etc are zero for items from the shared cache
2315 bzero(&stat_buf
, sizeof(stat_buf
));
2316 image
= ImageLoaderMachO::instantiateFromCache(mhInCache
, pathInCache
, slideInCache
, stat_buf
, gLinkContext
);
2317 return checkandAddImage(image
, context
);
2320 if ( !sDylibsOverrideCache
) {
2321 // flag is not set, and not in cache to try opening it
2322 image
= loadPhase5stat(path
, context
, &stat_buf
, &statErrNo
, &imageFound
, exceptions
);
2327 image
= loadPhase5stat(path
, context
, &stat_buf
, &statErrNo
, &imageFound
, exceptions
);
2331 // just return NULL if file not found, but record any other errors
2332 if ( statErrNo
!= ENOENT
) {
2333 exceptions
->push_back(dyld::mkstringf("%s: stat() failed with errno=%d", path
, statErrNo
));
2337 #endif // __IPHONE_OS_VERSION_MIN_REQUIRED
2340 // look for path match with existing loaded images
2341 static ImageLoader
* loadPhase5check(const char* path
, const char* orgPath
, const LoadContext
& context
)
2343 //dyld::log("%s(%s, %s)\n", __func__ , path, orgPath);
2344 // search path against load-path and install-path of all already loaded images
2345 uint32_t hash
= ImageLoader::hash(path
);
2346 //dyld::log("check() hash=%d, path=%s\n", hash, path);
2347 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
2348 ImageLoader
* anImage
= *it
;
2349 // check hash first to cut down on strcmp calls
2350 //dyld::log(" check() hash=%d, path=%s\n", anImage->getPathHash(), anImage->getPath());
2351 if ( anImage
->getPathHash() == hash
) {
2352 if ( strcmp(path
, anImage
->getPath()) == 0 ) {
2353 // if we are looking for a dylib don't return something else
2354 if ( !context
.mustBeDylib
|| anImage
->isDylib() )
2358 if ( context
.matchByInstallName
|| anImage
->matchInstallPath() ) {
2359 const char* installPath
= anImage
->getInstallPath();
2360 if ( installPath
!= NULL
) {
2361 if ( strcmp(path
, installPath
) == 0 ) {
2362 // if we are looking for a dylib don't return something else
2363 if ( !context
.mustBeDylib
|| anImage
->isDylib() )
2368 // an install name starting with @rpath should match by install name, not just real path
2369 if ( (orgPath
[0] == '@') && (strncmp(orgPath
, "@rpath/", 7) == 0) ) {
2370 const char* installPath
= anImage
->getInstallPath();
2371 if ( installPath
!= NULL
) {
2372 if ( !context
.mustBeDylib
|| anImage
->isDylib() ) {
2373 if ( strcmp(orgPath
, installPath
) == 0 )
2380 //dyld::log("%s(%s) => NULL\n", __func__, path);
2385 // open or check existing
2386 static ImageLoader
* loadPhase5(const char* path
, const char* orgPath
, const LoadContext
& context
, std::vector
<const char*>* exceptions
)
2388 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
2390 // check for specific dylib overrides
2391 for (std::vector
<DylibOverride
>::iterator it
= sDylibOverrides
.begin(); it
!= sDylibOverrides
.end(); ++it
) {
2392 if ( strcmp(it
->installName
, path
) == 0 ) {
2393 path
= it
->override
;
2398 if ( exceptions
!= NULL
)
2399 return loadPhase5load(path
, orgPath
, context
, exceptions
);
2401 return loadPhase5check(path
, orgPath
, context
);
2404 // try with and without image suffix
2405 static ImageLoader
* loadPhase4(const char* path
, const char* orgPath
, const LoadContext
& context
, std::vector
<const char*>* exceptions
)
2407 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
2408 ImageLoader
* image
= NULL
;
2409 if ( gLinkContext
.imageSuffix
!= NULL
) {
2410 char pathWithSuffix
[strlen(path
)+strlen( gLinkContext
.imageSuffix
)+2];
2411 ImageLoader::addSuffix(path
, gLinkContext
.imageSuffix
, pathWithSuffix
);
2412 image
= loadPhase5(pathWithSuffix
, orgPath
, context
, exceptions
);
2414 if ( image
== NULL
)
2415 image
= loadPhase5(path
, orgPath
, context
, exceptions
);
2419 static ImageLoader
* loadPhase2(const char* path
, const char* orgPath
, const LoadContext
& context
,
2420 const char* const frameworkPaths
[], const char* const libraryPaths
[],
2421 std::vector
<const char*>* exceptions
); // forward reference
2424 // expand @ variables
2425 static ImageLoader
* loadPhase3(const char* path
, const char* orgPath
, const LoadContext
& context
, std::vector
<const char*>* exceptions
)
2427 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
2428 ImageLoader
* image
= NULL
;
2429 if ( strncmp(path
, "@executable_path/", 17) == 0 ) {
2430 // executable_path cannot be in used in any binary in a setuid process rdar://problem/4589305
2431 if ( sProcessIsRestricted
)
2432 throwf("unsafe use of @executable_path in %s with restricted binary", context
.origin
);
2433 // handle @executable_path path prefix
2434 const char* executablePath
= sExecPath
;
2435 char newPath
[strlen(executablePath
) + strlen(path
)];
2436 strcpy(newPath
, executablePath
);
2437 char* addPoint
= strrchr(newPath
,'/');
2438 if ( addPoint
!= NULL
)
2439 strcpy(&addPoint
[1], &path
[17]);
2441 strcpy(newPath
, &path
[17]);
2442 image
= loadPhase4(newPath
, orgPath
, context
, exceptions
);
2443 if ( image
!= NULL
)
2446 // perhaps main executable path is a sym link, find realpath and retry
2447 char resolvedPath
[PATH_MAX
];
2448 if ( realpath(sExecPath
, resolvedPath
) != NULL
) {
2449 char newRealPath
[strlen(resolvedPath
) + strlen(path
)];
2450 strcpy(newRealPath
, resolvedPath
);
2451 char* addPoint
= strrchr(newRealPath
,'/');
2452 if ( addPoint
!= NULL
)
2453 strcpy(&addPoint
[1], &path
[17]);
2455 strcpy(newRealPath
, &path
[17]);
2456 image
= loadPhase4(newRealPath
, orgPath
, context
, exceptions
);
2457 if ( image
!= NULL
)
2461 else if ( (strncmp(path
, "@loader_path/", 13) == 0) && (context
.origin
!= NULL
) ) {
2462 // @loader_path cannot be used from the main executable of a setuid process rdar://problem/4589305
2463 if ( sProcessIsRestricted
&& (strcmp(context
.origin
, sExecPath
) == 0) )
2464 throwf("unsafe use of @loader_path in %s with restricted binary", context
.origin
);
2465 // handle @loader_path path prefix
2466 char newPath
[strlen(context
.origin
) + strlen(path
)];
2467 strcpy(newPath
, context
.origin
);
2468 char* addPoint
= strrchr(newPath
,'/');
2469 if ( addPoint
!= NULL
)
2470 strcpy(&addPoint
[1], &path
[13]);
2472 strcpy(newPath
, &path
[13]);
2473 image
= loadPhase4(newPath
, orgPath
, context
, exceptions
);
2474 if ( image
!= NULL
)
2477 // perhaps loader path is a sym link, find realpath and retry
2478 char resolvedPath
[PATH_MAX
];
2479 if ( realpath(context
.origin
, resolvedPath
) != NULL
) {
2480 char newRealPath
[strlen(resolvedPath
) + strlen(path
)];
2481 strcpy(newRealPath
, resolvedPath
);
2482 char* addPoint
= strrchr(newRealPath
,'/');
2483 if ( addPoint
!= NULL
)
2484 strcpy(&addPoint
[1], &path
[13]);
2486 strcpy(newRealPath
, &path
[13]);
2487 image
= loadPhase4(newRealPath
, orgPath
, context
, exceptions
);
2488 if ( image
!= NULL
)
2492 else if ( context
.implicitRPath
|| (strncmp(path
, "@rpath/", 7) == 0) ) {
2493 const char* trailingPath
= (strncmp(path
, "@rpath/", 7) == 0) ? &path
[7] : path
;
2494 // substitute @rpath with all -rpath paths up the load chain
2495 for(const ImageLoader::RPathChain
* rp
=context
.rpath
; rp
!= NULL
; rp
=rp
->next
) {
2496 if (rp
->paths
!= NULL
) {
2497 for(std::vector
<const char*>::iterator it
=rp
->paths
->begin(); it
!= rp
->paths
->end(); ++it
) {
2498 const char* anRPath
= *it
;
2499 char newPath
[strlen(anRPath
) + strlen(trailingPath
)+2];
2500 strcpy(newPath
, anRPath
);
2501 strcat(newPath
, "/");
2502 strcat(newPath
, trailingPath
);
2503 image
= loadPhase4(newPath
, orgPath
, context
, exceptions
);
2504 if ( gLinkContext
.verboseRPaths
&& (exceptions
!= NULL
) ) {
2505 if ( image
!= NULL
)
2506 dyld::log("RPATH successful expansion of %s to: %s\n", orgPath
, newPath
);
2508 dyld::log("RPATH failed to expanding %s to: %s\n", orgPath
, newPath
);
2510 if ( image
!= NULL
)
2516 // substitute @rpath with LD_LIBRARY_PATH
2517 if ( sEnv
.LD_LIBRARY_PATH
!= NULL
) {
2518 image
= loadPhase2(trailingPath
, orgPath
, context
, NULL
, sEnv
.LD_LIBRARY_PATH
, exceptions
);
2519 if ( image
!= NULL
)
2523 // if this is the "open" pass, don't try to open @rpath/... as a relative path
2524 if ( (exceptions
!= NULL
) && (trailingPath
!= path
) )
2527 else if (sProcessIsRestricted
&& (path
[0] != '/' )) {
2528 throwf("unsafe use of relative rpath %s in %s with restricted binary", path
, context
.origin
);
2531 return loadPhase4(path
, orgPath
, context
, exceptions
);
2536 static ImageLoader
* loadPhase2(const char* path
, const char* orgPath
, const LoadContext
& context
,
2537 const char* const frameworkPaths
[], const char* const libraryPaths
[],
2538 std::vector
<const char*>* exceptions
)
2540 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
2541 ImageLoader
* image
= NULL
;
2542 const char* frameworkPartialPath
= getFrameworkPartialPath(path
);
2543 if ( frameworkPaths
!= NULL
) {
2544 if ( frameworkPartialPath
!= NULL
) {
2545 const int frameworkPartialPathLen
= strlen(frameworkPartialPath
);
2546 for(const char* const* fp
= frameworkPaths
; *fp
!= NULL
; ++fp
) {
2547 char npath
[strlen(*fp
)+frameworkPartialPathLen
+8];
2550 strcat(npath
, frameworkPartialPath
);
2551 //dyld::log("dyld: fallback framework path used: %s() -> loadPhase4(\"%s\", ...)\n", __func__, npath);
2552 image
= loadPhase4(npath
, orgPath
, context
, exceptions
);
2553 if ( image
!= NULL
)
2558 if ( libraryPaths
!= NULL
) {
2559 const char* libraryLeafName
= getLibraryLeafName(path
);
2560 const int libraryLeafNameLen
= strlen(libraryLeafName
);
2561 for(const char* const* lp
= libraryPaths
; *lp
!= NULL
; ++lp
) {
2562 char libpath
[strlen(*lp
)+libraryLeafNameLen
+8];
2563 strcpy(libpath
, *lp
);
2564 strcat(libpath
, "/");
2565 strcat(libpath
, libraryLeafName
);
2566 //dyld::log("dyld: fallback library path used: %s() -> loadPhase4(\"%s\", ...)\n", __func__, libpath);
2567 image
= loadPhase4(libpath
, orgPath
, context
, exceptions
);
2568 if ( image
!= NULL
)
2575 // try search overrides and fallbacks
2576 static ImageLoader
* loadPhase1(const char* path
, const char* orgPath
, const LoadContext
& context
, std::vector
<const char*>* exceptions
)
2578 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
2579 ImageLoader
* image
= NULL
;
2581 // handle LD_LIBRARY_PATH environment variables that force searching
2582 if ( context
.useLdLibraryPath
&& (sEnv
.LD_LIBRARY_PATH
!= NULL
) ) {
2583 image
= loadPhase2(path
, orgPath
, context
, NULL
, sEnv
.LD_LIBRARY_PATH
, exceptions
);
2584 if ( image
!= NULL
)
2588 // handle DYLD_ environment variables that force searching
2589 if ( context
.useSearchPaths
&& ((sEnv
.DYLD_FRAMEWORK_PATH
!= NULL
) || (sEnv
.DYLD_LIBRARY_PATH
!= NULL
)) ) {
2590 image
= loadPhase2(path
, orgPath
, context
, sEnv
.DYLD_FRAMEWORK_PATH
, sEnv
.DYLD_LIBRARY_PATH
, exceptions
);
2591 if ( image
!= NULL
)
2596 image
= loadPhase3(path
, orgPath
, context
, exceptions
);
2597 if ( image
!= NULL
)
2600 // try fallback paths during second time (will open file)
2601 const char* const* fallbackLibraryPaths
= sEnv
.DYLD_FALLBACK_LIBRARY_PATH
;
2602 if ( (fallbackLibraryPaths
!= NULL
) && !context
.useFallbackPaths
)
2603 fallbackLibraryPaths
= NULL
;
2604 if ( !context
.dontLoad
&& (exceptions
!= NULL
) && ((sEnv
.DYLD_FALLBACK_FRAMEWORK_PATH
!= NULL
) || (fallbackLibraryPaths
!= NULL
)) ) {
2605 image
= loadPhase2(path
, orgPath
, context
, sEnv
.DYLD_FALLBACK_FRAMEWORK_PATH
, fallbackLibraryPaths
, exceptions
);
2606 if ( image
!= NULL
)
2613 // try root substitutions
2614 static ImageLoader
* loadPhase0(const char* path
, const char* orgPath
, const LoadContext
& context
, std::vector
<const char*>* exceptions
)
2616 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
2618 // handle DYLD_ROOT_PATH which forces absolute paths to use a new root
2619 if ( (gLinkContext
.rootPaths
!= NULL
) && (path
[0] == '/') ) {
2620 for(const char* const* rootPath
= gLinkContext
.rootPaths
; *rootPath
!= NULL
; ++rootPath
) {
2621 char newPath
[strlen(*rootPath
) + strlen(path
)+2];
2622 strcpy(newPath
, *rootPath
);
2623 strcat(newPath
, path
);
2624 ImageLoader
* image
= loadPhase1(newPath
, orgPath
, context
, exceptions
);
2625 if ( image
!= NULL
)
2631 return loadPhase1(path
, orgPath
, context
, exceptions
);
2635 // Given all the DYLD_ environment variables, the general case for loading libraries
2636 // is that any given path expands into a list of possible locations to load. We
2637 // also must take care to ensure two copies of the "same" library are never loaded.
2639 // The algorithm used here is that there is a separate function for each "phase" of the
2640 // path expansion. Each phase function calls the next phase with each possible expansion
2641 // of that phase. The result is the last phase is called with all possible paths.
2643 // To catch duplicates the algorithm is run twice. The first time, the last phase checks
2644 // the path against all loaded images. The second time, the last phase calls open() on
2645 // the path. Either time, if an image is found, the phases all unwind without checking
2648 ImageLoader
* load(const char* path
, const LoadContext
& context
)
2650 CRSetCrashLogMessage2(path
);
2651 const char* orgPath
= path
;
2653 //dyld::log("%s(%s)\n", __func__ , path);
2654 char realPath
[PATH_MAX
];
2655 // when DYLD_IMAGE_SUFFIX is in used, do a realpath(), otherwise a load of "Foo.framework/Foo" will not match
2656 if ( context
.useSearchPaths
&& ( gLinkContext
.imageSuffix
!= NULL
) ) {
2657 if ( realpath(path
, realPath
) != NULL
)
2661 // try all path permutations and check against existing loaded images
2662 ImageLoader
* image
= loadPhase0(path
, orgPath
, context
, NULL
);
2663 if ( image
!= NULL
) {
2664 CRSetCrashLogMessage2(NULL
);
2668 // try all path permutations and try open() until first success
2669 std::vector
<const char*> exceptions
;
2670 image
= loadPhase0(path
, orgPath
, context
, &exceptions
);
2671 CRSetCrashLogMessage2(NULL
);
2672 if ( image
!= NULL
) {
2673 // <rdar://problem/6916014> leak in dyld during dlopen when using DYLD_ variables
2674 for (std::vector
<const char*>::iterator it
= exceptions
.begin(); it
!= exceptions
.end(); ++it
) {
2677 #if __IPHONE_OS_VERSION_MIN_REQUIRED
2678 // if loaded image is not from cache, but original path is in cache
2679 // set gSharedCacheOverridden flag to disable some ObjC optimizations
2680 if ( !gSharedCacheOverridden
) {
2681 if ( !image
->inSharedCache() && inSharedCache(path
) ) {
2682 gSharedCacheOverridden
= true;
2688 else if ( exceptions
.size() == 0 ) {
2689 if ( context
.dontLoad
) {
2693 throw "image not found";
2696 const char* msgStart
= "no suitable image found. Did find:";
2697 const char* delim
= "\n\t";
2698 size_t allsizes
= strlen(msgStart
)+8;
2699 for (unsigned int i
=0; i
< exceptions
.size(); ++i
)
2700 allsizes
+= (strlen(exceptions
[i
]) + strlen(delim
));
2701 char* fullMsg
= new char[allsizes
];
2702 strcpy(fullMsg
, msgStart
);
2703 for (unsigned int i
=0; i
< exceptions
.size(); ++i
) {
2704 strcat(fullMsg
, delim
);
2705 strcat(fullMsg
, exceptions
[i
]);
2706 free((void*)exceptions
[i
]);
2708 throw (const char*)fullMsg
;
2715 #if DYLD_SHARED_CACHE_SUPPORT
2721 #define ARCH_NAME "ppc"
2722 #define ARCH_NAME_ROSETTA "rosetta"
2723 #define ARCH_CACHE_MAGIC "dyld_v1 ppc"
2725 #define ARCH_NAME "ppc64"
2726 #define ARCH_CACHE_MAGIC "dyld_v1 ppc64"
2728 #define ARCH_NAME "i386"
2729 #define ARCH_CACHE_MAGIC "dyld_v1 i386"
2731 #define ARCH_NAME "x86_64"
2732 #define ARCH_CACHE_MAGIC "dyld_v1 x86_64"
2733 #define SHARED_REGION_READ_ONLY_START 0x7FFF80000000LL
2734 #define SHARED_REGION_READ_ONLY_END 0x7FFFC0000000LL
2735 #define SHARED_REGION_WRITABLE_START 0x7FFF70000000LL
2736 #define SHARED_REGION_WRITABLE_END 0x7FFF80000000LL
2737 #define SLIDEABLE_CACHE_SUPPORT 1
2738 #elif __ARM_ARCH_5TEJ__
2739 #define ARCH_NAME "armv5"
2740 #define ARCH_CACHE_MAGIC "dyld_v1 armv5"
2741 #elif __ARM_ARCH_6K__
2742 #define ARCH_NAME "armv6"
2743 #define ARCH_CACHE_MAGIC "dyld_v1 armv6"
2744 #elif __ARM_ARCH_7A__
2745 #define ARCH_NAME "armv7"
2746 #define ARCH_CACHE_MAGIC "dyld_v1 armv7"
2747 #define SHARED_REGION_READ_ONLY_START 0x30000000
2748 #define SHARED_REGION_READ_ONLY_END 0x3E000000
2749 #define SHARED_REGION_WRITABLE_START 0x3E000000
2750 #define SHARED_REGION_WRITABLE_END 0x40000000
2751 #define SLIDEABLE_CACHE_SUPPORT 1
2755 static int __attribute__((noinline
)) _shared_region_check_np(uint64_t* start_address
)
2757 if ( (gLinkContext
.sharedRegionMode
== ImageLoader::kUseSharedRegion
) )
2758 return syscall(294, start_address
);
2763 static int __attribute__((noinline
)) _shared_region_map_and_slide_np(int fd
, uint32_t count
, const shared_file_mapping_np mappings
[],
2764 int codeSignatureMappingIndex
, int slide
, void* slideInfo
, uint32_t slideInfoSize
)
2766 #if __IPHONE_OS_VERSION_MIN_REQUIRED
2767 // register code signature blob for whole dyld cache
2768 if ( codeSignatureMappingIndex
!= -1 ) {
2769 fsignatures_t siginfo
;
2770 siginfo
.fs_file_start
= 0; // cache always starts at beginning of file
2771 siginfo
.fs_blob_start
= (void*)mappings
[codeSignatureMappingIndex
].sfm_file_offset
;
2772 siginfo
.fs_blob_size
= mappings
[codeSignatureMappingIndex
].sfm_size
;
2773 int result
= fcntl(fd
, F_ADDFILESIGS
, &siginfo
);
2775 dyld::log("dyld: code signature for shared cache failed with errno=%d\n", errno
);
2778 if ( (gLinkContext
.sharedRegionMode
== ImageLoader::kUseSharedRegion
) ) {
2779 return syscall(438, fd
, count
, mappings
, slide
, slideInfo
, slideInfoSize
);
2782 // remove the shared region sub-map
2783 vm_deallocate(mach_task_self(), (vm_address_t
)SHARED_REGION_BASE
, SHARED_REGION_SIZE
);
2785 // notify gdb or other lurkers that this process is no longer using the shared region
2786 dyld_all_image_infos
.processDetachedFromSharedRegion
= true;
2788 // map cache just for this process with mmap()
2789 const shared_file_mapping_np
* const start
= mappings
;
2790 const shared_file_mapping_np
* const end
= &mappings
[count
];
2791 for (const shared_file_mapping_np
* p
= start
; p
< end
; ++p
) {
2792 void* mmapAddress
= (void*)(uintptr_t)(p
->sfm_address
);
2793 size_t size
= p
->sfm_size
;
2794 //dyld::log("dyld: mapping address %p with size 0x%08lX\n", mmapAddress, size);
2796 if ( p
->sfm_init_prot
& VM_PROT_EXECUTE
)
2797 protection
|= PROT_EXEC
;
2798 if ( p
->sfm_init_prot
& VM_PROT_READ
)
2799 protection
|= PROT_READ
;
2800 if ( p
->sfm_init_prot
& VM_PROT_WRITE
)
2801 protection
|= PROT_WRITE
;
2802 off_t offset
= p
->sfm_file_offset
;
2803 if ( mmap(mmapAddress
, size
, protection
, MAP_FIXED
| MAP_PRIVATE
, fd
, offset
) != mmapAddress
) {
2804 // failed to map some chunk of this shared cache file
2805 // clear shared region
2806 vm_deallocate(mach_task_self(), (vm_address_t
)SHARED_REGION_BASE
, SHARED_REGION_SIZE
);
2807 // go back to not using shared region at all
2808 gLinkContext
.sharedRegionMode
= ImageLoader::kDontUseSharedRegion
;
2809 if ( gLinkContext
.verboseMapping
) {
2810 dyld::log("dyld: shared cached region cannot be mapped at address %p with size 0x%08lX\n",
2818 #if SLIDEABLE_CACHE_SUPPORT
2819 // update all __DATA pages with slide info
2821 const uintptr_t dataPagesStart
= mappings
[1].sfm_address
;
2822 const dyld_cache_slide_info
* slideInfoHeader
= (dyld_cache_slide_info
*)slideInfo
;
2823 const uint16_t* toc
= (uint16_t*)((long)(slideInfoHeader
) + slideInfoHeader
->toc_offset
);
2824 const uint8_t* entries
= (uint8_t*)((long)(slideInfoHeader
) + slideInfoHeader
->entries_offset
);
2825 for(uint32_t i
=0; i
< slideInfoHeader
->toc_count
; ++i
) {
2826 const uint8_t* entry
= &entries
[toc
[i
]*slideInfoHeader
->entries_size
];
2827 const uint8_t* page
= (uint8_t*)(long)(dataPagesStart
+ (4096*i
));
2828 //dyld::log("page=%p toc[%d]=%d entries=%p\n", page, i, toc[i], entry);
2829 for(int j
=0; j
< 128; ++j
) {
2830 uint8_t b
= entry
[j
];
2831 //dyld::log(" entry[%d] = 0x%02X\n", j, b);
2833 for(int k
=0; k
< 8; ++k
) {
2835 uintptr_t* p
= (uintptr_t*)(page
+ j
*8*4 + k
*4);
2836 uintptr_t value
= *p
;
2837 //dyld::log(" *%p was 0x%lX will be 0x%lX\n", p, value, value+sSharedCacheSlide);
2845 #endif // SLIDEABLE_CACHE_SUPPORT
2847 // succesfully mapped shared cache for just this process
2848 gLinkContext
.sharedRegionMode
= ImageLoader::kUsePrivateSharedRegion
;
2854 const void* imMemorySharedCacheHeader()
2856 return sSharedCache
;
2859 int openSharedCacheFile()
2862 strcpy(path
, sSharedCacheDir
);
2865 // rosetta cannot handle optimized _ppc cache, so it use _rosetta cache instead, rdar://problem/5495438
2867 strcat(path
, DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME_ROSETTA
);
2870 strcat(path
, DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME
);
2871 return ::open(path
, O_RDONLY
);
2874 #if SLIDEABLE_CACHE_SUPPORT
2875 static long pickCacheSlide(uint32_t mappingsCount
, shared_file_mapping_np mappings
[])
2877 // get bounds of cache
2878 uint64_t readOnlyLowAddress
= 0;
2879 uint64_t readOnlyHighAddress
= 0;
2880 uint64_t writableLowAddress
= 0;
2881 uint64_t writableHighAddress
= 0;
2882 for(uint32_t i
=0; i
< mappingsCount
; ++i
) {
2883 if ( mappings
[i
].sfm_init_prot
& VM_PROT_WRITE
) {
2884 writableLowAddress
= mappings
[i
].sfm_address
;
2885 writableHighAddress
= mappings
[i
].sfm_address
+ mappings
[i
].sfm_size
;
2888 if ( readOnlyLowAddress
== 0 ) {
2889 readOnlyLowAddress
= mappings
[i
].sfm_address
;
2890 readOnlyHighAddress
= mappings
[i
].sfm_address
+ mappings
[i
].sfm_size
;
2893 if ( readOnlyLowAddress
< mappings
[i
].sfm_address
) {
2894 readOnlyHighAddress
= mappings
[i
].sfm_address
+ mappings
[i
].sfm_size
;
2897 readOnlyLowAddress
= mappings
[i
].sfm_address
;
2903 // find read-only slop space
2904 uint64_t roSpace
= SHARED_REGION_READ_ONLY_END
- readOnlyHighAddress
;
2906 // find writable slop space
2907 uint64_t rwSpace
= SHARED_REGION_WRITABLE_END
- writableHighAddress
;
2909 // choose new random slide
2910 long slideSpace
= (roSpace
> rwSpace
) ? rwSpace
: roSpace
;
2911 long slide
= (arc4random() % slideSpace
) & (-4096);
2912 //dyld::log("roSpace=0x%0llX\n", roSpace);
2913 //dyld::log("rwSpace=0x%0llX\n", rwSpace);
2914 //dyld::log("slideSpace=0x%0lX\n", slideSpace);
2915 //dyld::log("slide=0x%0lX\n", slide);
2918 for(uint32_t i
=0; i
< mappingsCount
; ++i
) {
2919 mappings
[i
].sfm_address
+= slide
;
2924 #endif // SLIDEABLE_CACHE_SUPPORT
2926 static void mapSharedCache()
2928 uint64_t cacheBaseAddress
;
2929 // quick check if a cache is alreay mapped into shared region
2930 if ( _shared_region_check_np(&cacheBaseAddress
) == 0 ) {
2931 sSharedCache
= (dyld_cache_header
*)cacheBaseAddress
;
2932 // if we don't understand the currently mapped shared cache, then ignore
2933 if ( strcmp(sSharedCache
->magic
, ARCH_CACHE_MAGIC
) != 0 ) {
2934 sSharedCache
= NULL
;
2935 if ( gLinkContext
.verboseMapping
)
2936 dyld::log("dyld: existing shared cached in memory is not compatible\n");
2938 // check if cache file is slidable
2939 dyld_cache_header
* header
= (dyld_cache_header
*)sSharedCache
;
2940 if ( (header
->mappingOffset
>= 0x48) && (header
->slideInfoSize
!= 0) ) {
2941 // solve for slide by comparing loaded address to address of first region
2942 const uint8_t* loadedAddress
= (uint8_t*)sSharedCache
;
2943 const dyld_cache_mapping_info
* const mappings
= (dyld_cache_mapping_info
*)(loadedAddress
+header
->mappingOffset
);
2944 const uint8_t* preferedLoadAddress
= (uint8_t*)(long)(mappings
[0].address
);
2945 sSharedCacheSlide
= loadedAddress
- preferedLoadAddress
;
2946 dyld_all_image_infos
.sharedCacheSlide
= sSharedCacheSlide
;
2947 //dyld::log("sSharedCacheSlide=0x%08lX, loadedAddress=%p, preferedLoadAddress=%p\n", sSharedCacheSlide, loadedAddress, preferedLoadAddress);
2951 #if __i386__ || __x86_64__
2952 // <rdar://problem/5925940> Safe Boot should disable dyld shared cache
2953 // if we are in safe-boot mode and the cache was not made during this boot cycle,
2954 // delete the cache file
2955 uint32_t safeBootValue
= 0;
2956 size_t safeBootValueSize
= sizeof(safeBootValue
);
2957 if ( (sysctlbyname("kern.safeboot", &safeBootValue
, &safeBootValueSize
, NULL
, 0) == 0) && (safeBootValue
!= 0) ) {
2958 // user booted machine in safe-boot mode
2959 struct stat dyldCacheStatInfo
;
2960 // Don't use custom DYLD_SHARED_CACHE_DIR if provided, use standard path
2961 if ( ::stat(MACOSX_DYLD_SHARED_CACHE_DIR DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME
, &dyldCacheStatInfo
) == 0 ) {
2962 struct timeval bootTimeValue
;
2963 size_t bootTimeValueSize
= sizeof(bootTimeValue
);
2964 if ( (sysctlbyname("kern.boottime", &bootTimeValue
, &bootTimeValueSize
, NULL
, 0) == 0) && (bootTimeValue
.tv_sec
!= 0) ) {
2965 // if the cache file was created before this boot, then throw it away and let it rebuild itself
2966 if ( dyldCacheStatInfo
.st_mtime
< bootTimeValue
.tv_sec
) {
2967 ::unlink(MACOSX_DYLD_SHARED_CACHE_DIR DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME
);
2968 gLinkContext
.sharedRegionMode
= ImageLoader::kDontUseSharedRegion
;
2975 // map in shared cache to shared region
2976 int fd
= openSharedCacheFile();
2978 uint8_t firstPages
[8192];
2979 if ( ::read(fd
, firstPages
, 8192) == 8192 ) {
2980 dyld_cache_header
* header
= (dyld_cache_header
*)firstPages
;
2981 if ( strcmp(header
->magic
, ARCH_CACHE_MAGIC
) == 0 ) {
2982 const dyld_cache_mapping_info
* const fileMappingsStart
= (dyld_cache_mapping_info
*)&firstPages
[header
->mappingOffset
];
2983 const dyld_cache_mapping_info
* const fileMappingsEnd
= &fileMappingsStart
[header
->mappingCount
];
2984 shared_file_mapping_np mappings
[header
->mappingCount
+1]; // add room for code-sig
2985 unsigned int mappingCount
= header
->mappingCount
;
2986 int codeSignatureMappingIndex
= -1;
2987 // validate that the cache file has not been truncated
2988 bool goodCache
= false;
2989 struct stat stat_buf
;
2990 if ( fstat(fd
, &stat_buf
) == 0 ) {
2993 for (const dyld_cache_mapping_info
* p
= fileMappingsStart
; p
< fileMappingsEnd
; ++p
, ++i
) {
2994 mappings
[i
].sfm_address
= p
->address
;
2995 mappings
[i
].sfm_size
= p
->size
;
2996 mappings
[i
].sfm_file_offset
= p
->fileOffset
;
2997 mappings
[i
].sfm_max_prot
= p
->maxProt
;
2998 mappings
[i
].sfm_init_prot
= p
->initProt
;
2999 // rdar://problem/5694507 old update_dyld_shared_cache tool could make a cache file
3000 // that is not page aligned, but otherwise ok.
3001 if ( p
->fileOffset
+p
->size
> (uint64_t)(stat_buf
.st_size
+4095 & (-4096)) ) {
3002 dyld::log("dyld: shared cached file is corrupt: %s" DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME
"\n", sSharedCacheDir
);
3006 #if __IPHONE_OS_VERSION_MIN_REQUIRED
3007 // if shared cache is code signed, add a mapping for the code signature
3008 uint32_t signatureSize
= header
->codeSignatureSize
;
3009 // zero size in header means signature runs to end-of-file
3010 if ( signatureSize
== 0 )
3011 signatureSize
= stat_buf
.st_size
- header
->codeSignatureOffset
;
3012 if ( signatureSize
!= 0 ) {
3013 int linkeditMapping
= mappingCount
-1;
3014 codeSignatureMappingIndex
= mappingCount
++;
3015 mappings
[codeSignatureMappingIndex
].sfm_address
= mappings
[linkeditMapping
].sfm_address
+ mappings
[linkeditMapping
].sfm_size
;
3016 mappings
[codeSignatureMappingIndex
].sfm_size
= (signatureSize
+4095) & (-4096);
3017 mappings
[codeSignatureMappingIndex
].sfm_file_offset
= header
->codeSignatureOffset
;
3018 mappings
[codeSignatureMappingIndex
].sfm_max_prot
= VM_PROT_READ
;
3019 mappings
[codeSignatureMappingIndex
].sfm_init_prot
= VM_PROT_READ
;
3023 #if __MAC_OS_X_VERSION_MIN_REQUIRED
3024 // sanity check that /usr/lib/libSystem.B.dylib stat() info matches cache
3025 if ( header
->imagesCount
* sizeof(dyld_cache_image_info
) + header
->imagesOffset
< 8192 ) {
3026 bool foundLibSystem
= false;
3027 if ( stat("/usr/lib/libSystem.B.dylib", &stat_buf
) == 0 ) {
3028 const dyld_cache_image_info
* images
= (dyld_cache_image_info
*)&firstPages
[header
->imagesOffset
];
3029 const dyld_cache_image_info
* const imagesEnd
= &images
[header
->imagesCount
];
3030 for (const dyld_cache_image_info
* p
= images
; p
< imagesEnd
; ++p
) {
3031 if ( ((time_t)p
->modTime
== stat_buf
.st_mtime
) && ((ino_t
)p
->inode
== stat_buf
.st_ino
) ) {
3032 foundLibSystem
= true;
3037 if ( !sSharedCacheIgnoreInodeAndTimeStamp
&& !foundLibSystem
) {
3038 dyld::log("dyld: shared cached file was built against a different libSystem.dylib, ignoring cache.\n"
3039 "to update dyld shared cache run: 'sudo update_dyld_shared_cache' then reboot.\n");
3045 long cacheSlide
= 0;
3046 void* slideInfo
= NULL
;
3047 uint32_t slideInfoSize
= 0;
3048 #if SLIDEABLE_CACHE_SUPPORT
3049 // check if shared cache contains slid info
3050 if ( header
->slideInfoSize
!= 0 ) {
3051 // <rdar://problem/8611968> don't slide shared cache if ASLR disabled (main executable didn't slide)
3052 if ( sMainExecutable
->isPositionIndependentExecutable() && (sMainExecutable
->getSlide() == 0) )
3055 // generate random slide amount
3056 cacheSlide
= pickCacheSlide(mappingCount
, mappings
);
3057 slideInfo
= (void*)(long)(mappings
[2].sfm_address
+ (header
->slideInfoOffset
- mappings
[2].sfm_file_offset
));
3058 slideInfoSize
= header
->slideInfoSize
;
3059 // add VM_PROT_SLIDE bit to __DATA area of cache
3060 mappings
[1].sfm_max_prot
|= VM_PROT_SLIDE
;
3061 mappings
[1].sfm_init_prot
|= VM_PROT_SLIDE
;
3065 if (_shared_region_map_and_slide_np(fd
, mappingCount
, mappings
, codeSignatureMappingIndex
, cacheSlide
, slideInfo
, slideInfoSize
) == 0) {
3066 // successfully mapped cache into shared region
3067 sSharedCache
= (dyld_cache_header
*)mappings
[0].sfm_address
;
3068 sSharedCacheSlide
= cacheSlide
;
3069 dyld_all_image_infos
.sharedCacheSlide
= cacheSlide
;
3070 //dyld::log("sSharedCache=%p sSharedCacheSlide=0x%08lX\n", sSharedCache, sSharedCacheSlide);
3073 if ( gLinkContext
.verboseMapping
)
3074 dyld::log("dyld: shared cached file could not be mapped\n");
3079 if ( gLinkContext
.verboseMapping
)
3080 dyld::log("dyld: shared cached file is invalid\n");
3084 if ( gLinkContext
.verboseMapping
)
3085 dyld::log("dyld: shared cached file cannot be read\n");
3090 if ( gLinkContext
.verboseMapping
)
3091 dyld::log("dyld: shared cached file cannot be opened\n");
3095 // remember if dyld loaded at same address as when cache built
3096 if ( sSharedCache
!= NULL
) {
3097 gLinkContext
.dyldLoadedAtSameAddressNeededBySharedCache
= ((uintptr_t)(sSharedCache
->dyldBaseAddress
) == (uintptr_t)&_mh_dylinker_header
);
3100 // tell gdb where the shared cache is
3101 if ( sSharedCache
!= NULL
) {
3102 const dyld_cache_mapping_info
* const start
= (dyld_cache_mapping_info
*)((uint8_t*)sSharedCache
+ sSharedCache
->mappingOffset
);
3103 dyld_shared_cache_ranges
.sharedRegionsCount
= sSharedCache
->mappingCount
;
3104 // only room to tell gdb about first four regions
3105 if ( dyld_shared_cache_ranges
.sharedRegionsCount
> 4 )
3106 dyld_shared_cache_ranges
.sharedRegionsCount
= 4;
3107 if ( gLinkContext
.verboseMapping
) {
3108 if ( gLinkContext
.sharedRegionMode
== ImageLoader::kUseSharedRegion
)
3109 dyld::log("dyld: Mapping shared cache from %s/" DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME
"\n", sSharedCacheDir
);
3110 else if ( gLinkContext
.sharedRegionMode
== ImageLoader::kUsePrivateSharedRegion
)
3111 dyld::log("dyld: Mapping private shared cache from %s/" DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME
"\n", sSharedCacheDir
);
3113 const dyld_cache_mapping_info
* const end
= &start
[dyld_shared_cache_ranges
.sharedRegionsCount
];
3115 for (const dyld_cache_mapping_info
* p
= start
; p
< end
; ++p
, ++index
) {
3116 dyld_shared_cache_ranges
.ranges
[index
].start
= p
->address
+sSharedCacheSlide
;
3117 dyld_shared_cache_ranges
.ranges
[index
].length
= p
->size
;
3118 if ( gLinkContext
.verboseMapping
) {
3119 dyld::log(" 0x%08llX->0x%08llX %s%s%s init=%x, max=%x\n",
3120 p
->address
+sSharedCacheSlide
, p
->address
+sSharedCacheSlide
+p
->size
-1,
3121 ((p
->initProt
& VM_PROT_READ
) ? "read " : ""),
3122 ((p
->initProt
& VM_PROT_WRITE
) ? "write " : ""),
3123 ((p
->initProt
& VM_PROT_EXECUTE
) ? "execute " : ""), p
->initProt
, p
->maxProt
);
3126 // If a non-writable and executable region is found in the R/W shared region, then this is __IMPORT segments
3127 // This is an old cache. Make writable. dyld no longer supports turn W on and off as it binds
3128 if ( (p
->initProt
== (VM_PROT_READ
|VM_PROT_EXECUTE
)) && ((p
->address
& 0xF0000000) == 0xA0000000) ) {
3129 if ( p
->size
!= 0 ) {
3130 vm_prot_t prot
= VM_PROT_EXECUTE
| PROT_READ
| VM_PROT_WRITE
;
3131 vm_protect(mach_task_self(), p
->address
, p
->size
, false, prot
);
3132 if ( gLinkContext
.verboseMapping
) {
3133 dyld::log("%18s at 0x%08llX->0x%08llX altered permissions to %c%c%c\n", "", p
->address
,
3134 p
->address
+p
->size
-1,
3135 (prot
& PROT_READ
) ? 'r' : '.', (prot
& PROT_WRITE
) ? 'w' : '.', (prot
& PROT_EXEC
) ? 'x' : '.' );
3141 #if __IPHONE_OS_VERSION_MIN_REQUIRED
3142 if ( gLinkContext
.verboseMapping
) {
3143 // list the code blob
3144 dyld_cache_header
* header
= (dyld_cache_header
*)sSharedCache
;
3145 uint32_t signatureSize
= header
->codeSignatureSize
;
3146 // zero size in header means signature runs to end-of-file
3147 if ( signatureSize
== 0 ) {
3148 struct stat stat_buf
;
3149 if ( ::stat(IPHONE_DYLD_SHARED_CACHE_DIR DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME
, &stat_buf
) == 0 )
3150 signatureSize
= stat_buf
.st_size
- header
->codeSignatureOffset
;
3152 if ( signatureSize
!= 0 ) {
3153 const dyld_cache_mapping_info
* const last
= &start
[dyld_shared_cache_ranges
.sharedRegionsCount
-1];
3154 uint64_t codeBlobStart
= last
->address
+ last
->size
;
3155 dyld::log(" 0x%08llX->0x%08llX (code signature)\n", codeBlobStart
, codeBlobStart
+signatureSize
);
3158 // check for file that enables dyld shared cache dylibs to be overridden
3159 struct stat enableStatBuf
;
3160 sDylibsOverrideCache
= ( ::stat(IPHONE_DYLD_SHARED_CACHE_DIR
"enable-dylibs-to-override-cache", &enableStatBuf
) == 0 );
3165 #endif // #if DYLD_SHARED_CACHE_SUPPORT
3169 // create when NSLinkModule is called for a second time on a bundle
3170 ImageLoader
* cloneImage(ImageLoader
* image
)
3172 // open file (automagically closed when this function exits)
3173 FileOpener
file(image
->getPath());
3175 struct stat stat_buf
;
3176 if ( fstat(file
.getFileDescriptor(), &stat_buf
) == -1)
3179 dyld::LoadContext context
;
3180 context
.useSearchPaths
= false;
3181 context
.useFallbackPaths
= false;
3182 context
.useLdLibraryPath
= false;
3183 context
.implicitRPath
= false;
3184 context
.matchByInstallName
= false;
3185 context
.dontLoad
= false;
3186 context
.mustBeBundle
= true;
3187 context
.mustBeDylib
= false;
3188 context
.canBePIE
= false;
3189 context
.origin
= NULL
;
3190 context
.rpath
= NULL
;
3191 return loadPhase6(file
.getFileDescriptor(), stat_buf
, image
->getPath(), context
);
3195 ImageLoader
* loadFromMemory(const uint8_t* mem
, uint64_t len
, const char* moduleName
)
3197 // if fat wrapper, find usable sub-file
3198 const fat_header
* memStartAsFat
= (fat_header
*)mem
;
3199 uint64_t fileOffset
= 0;
3200 uint64_t fileLength
= len
;
3201 if ( memStartAsFat
->magic
== OSSwapBigToHostInt32(FAT_MAGIC
) ) {
3202 if ( fatFindBest(memStartAsFat
, &fileOffset
, &fileLength
) ) {
3203 mem
= &mem
[fileOffset
];
3207 throw "no matching architecture in universal wrapper";
3212 if ( isCompatibleMachO(mem
, moduleName
) ) {
3213 ImageLoader
* image
= ImageLoaderMachO::instantiateFromMemory(moduleName
, (macho_header
*)mem
, len
, gLinkContext
);
3214 // don't add bundles to global list, they can be loaded but not linked. When linked it will be added to list
3215 if ( ! image
->isBundle() )
3220 // try other file formats here...
3222 // throw error about what was found
3223 switch (*(uint32_t*)mem
) {
3228 throw "mach-o, but wrong architecture";
3230 throwf("unknown file type, first eight bytes: 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X",
3231 mem
[0], mem
[1], mem
[2], mem
[3], mem
[4], mem
[5], mem
[6],mem
[7]);
3236 void registerAddCallback(ImageCallback func
)
3238 // now add to list to get notified when any more images are added
3239 sAddImageCallbacks
.push_back(func
);
3241 // call callback with all existing images
3242 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
3243 ImageLoader
* image
= *it
;
3244 if ( image
->getState() >= dyld_image_state_bound
&& image
->getState() < dyld_image_state_terminated
)
3245 (*func
)(image
->machHeader(), image
->getSlide());
3249 void registerRemoveCallback(ImageCallback func
)
3251 sRemoveImageCallbacks
.push_back(func
);
3254 void clearErrorMessage()
3256 error_string
[0] = '\0';
3259 void setErrorMessage(const char* message
)
3261 // save off error message in global buffer for CrashReporter to find
3262 strlcpy(error_string
, message
, sizeof(error_string
));
3265 const char* getErrorMessage()
3267 return error_string
;
3271 void halt(const char* message
)
3273 dyld::log("dyld: %s\n", message
);
3274 setErrorMessage(message
);
3275 uintptr_t terminationFlags
= 0;
3276 if ( !gLinkContext
.startedInitializingMainExecutable
)
3277 terminationFlags
= 1;
3278 setAlImageInfosHalt(error_string
, terminationFlags
);
3279 dyld_fatal_error(error_string
);
3282 static void setErrorStrings(unsigned errorCode
, const char* errorClientOfDylibPath
,
3283 const char* errorTargetDylibPath
, const char* errorSymbol
)
3285 dyld_all_image_infos
.errorKind
= errorCode
;
3286 dyld_all_image_infos
.errorClientOfDylibPath
= errorClientOfDylibPath
;
3287 dyld_all_image_infos
.errorTargetDylibPath
= errorTargetDylibPath
;
3288 dyld_all_image_infos
.errorSymbol
= errorSymbol
;
3292 uintptr_t bindLazySymbol(const mach_header
* mh
, uintptr_t* lazyPointer
)
3294 uintptr_t result
= 0;
3295 // acquire read-lock on dyld's data structures
3296 #if 0 // rdar://problem/3811777 turn off locking until deadlock is resolved
3297 if ( gLibSystemHelpers
!= NULL
)
3298 (*gLibSystemHelpers
->lockForReading
)();
3300 // lookup and bind lazy pointer and get target address
3302 ImageLoader
* target
;
3304 // fast stubs pass NULL for mh and image is instead found via the location of stub (aka lazyPointer)
3306 target
= dyld::findImageContainingAddress(lazyPointer
);
3308 target
= dyld::findImageByMachHeader(mh
);
3310 // note, target should always be mach-o, because only mach-o lazy handler wired up to this
3311 target
= dyld::findImageByMachHeader(mh
);
3313 if ( target
== NULL
)
3314 throwf("image not found for lazy pointer at %p", lazyPointer
);
3315 result
= target
->doBindLazySymbol(lazyPointer
, gLinkContext
);
3317 catch (const char* message
) {
3318 dyld::log("dyld: lazy symbol binding failed: %s\n", message
);
3321 // release read-lock on dyld's data structures
3323 if ( gLibSystemHelpers
!= NULL
)
3324 (*gLibSystemHelpers
->unlockForReading
)();
3326 // return target address to glue which jumps to it with real parameters restored
3331 uintptr_t fastBindLazySymbol(ImageLoader
** imageLoaderCache
, uintptr_t lazyBindingInfoOffset
)
3333 uintptr_t result
= 0;
3335 if ( *imageLoaderCache
== NULL
) {
3337 *imageLoaderCache
= dyld::findMappedRange((uintptr_t)imageLoaderCache
);
3338 if ( *imageLoaderCache
== NULL
) {
3339 const char* message
= "fast lazy binding from unknown image";
3340 dyld::log("dyld: %s\n", message
);
3345 // bind lazy pointer and return it
3347 result
= (*imageLoaderCache
)->doBindFastLazySymbol(lazyBindingInfoOffset
, gLinkContext
,
3348 (dyld::gLibSystemHelpers
!= NULL
) ? dyld::gLibSystemHelpers
->acquireGlobalDyldLock
: NULL
,
3349 (dyld::gLibSystemHelpers
!= NULL
) ? dyld::gLibSystemHelpers
->releaseGlobalDyldLock
: NULL
);
3351 catch (const char* message
) {
3352 dyld::log("dyld: lazy symbol binding failed: %s\n", message
);
3356 // return target address to glue which jumps to it with real parameters restored
3362 void registerUndefinedHandler(UndefinedHandler handler
)
3364 sUndefinedHandler
= handler
;
3367 static void undefinedHandler(const char* symboName
)
3369 if ( sUndefinedHandler
!= NULL
) {
3370 (*sUndefinedHandler
)(symboName
);
3374 static bool findExportedSymbol(const char* name
, bool onlyInCoalesced
, const ImageLoader::Symbol
** sym
, const ImageLoader
** image
)
3376 // search all images in order
3377 const ImageLoader
* firstWeakImage
= NULL
;
3378 const ImageLoader::Symbol
* firstWeakSym
= NULL
;
3379 const unsigned int imageCount
= sAllImages
.size();
3380 for(unsigned int i
=0; i
< imageCount
; ++i
) {
3381 ImageLoader
* anImage
= sAllImages
[i
];
3382 // the use of inserted libraries alters search order
3383 // so that inserted libraries are found before the main executable
3384 if ( sInsertedDylibCount
> 0 ) {
3385 if ( i
< sInsertedDylibCount
)
3386 anImage
= sAllImages
[i
+1];
3387 else if ( i
== sInsertedDylibCount
)
3388 anImage
= sAllImages
[0];
3390 if ( ! anImage
->hasHiddenExports() && (!onlyInCoalesced
|| anImage
->hasCoalescedExports()) ) {
3391 *sym
= anImage
->findExportedSymbol(name
, false, image
);
3392 if ( *sym
!= NULL
) {
3393 // if weak definition found, record first one found
3394 if ( ((*image
)->getExportedSymbolInfo(*sym
) & ImageLoader::kWeakDefinition
) != 0 ) {
3395 if ( firstWeakImage
== NULL
) {
3396 firstWeakImage
= *image
;
3397 firstWeakSym
= *sym
;
3401 // found non-weak, so immediately return with it
3407 if ( firstWeakSym
!= NULL
) {
3408 // found a weak definition, but no non-weak, so return first weak found
3409 *sym
= firstWeakSym
;
3410 *image
= firstWeakImage
;
3417 bool flatFindExportedSymbol(const char* name
, const ImageLoader::Symbol
** sym
, const ImageLoader
** image
)
3419 return findExportedSymbol(name
, false, sym
, image
);
3422 bool findCoalescedExportedSymbol(const char* name
, const ImageLoader::Symbol
** sym
, const ImageLoader
** image
)
3424 return findExportedSymbol(name
, true, sym
, image
);
3428 bool flatFindExportedSymbolWithHint(const char* name
, const char* librarySubstring
, const ImageLoader::Symbol
** sym
, const ImageLoader
** image
)
3430 // search all images in order
3431 const unsigned int imageCount
= sAllImages
.size();
3432 for(unsigned int i
=0; i
< imageCount
; ++i
){
3433 ImageLoader
* anImage
= sAllImages
[i
];
3434 // only look at images whose paths contain the hint string (NULL hint string is wildcard)
3435 if ( ! anImage
->isBundle() && ((librarySubstring
==NULL
) || (strstr(anImage
->getPath(), librarySubstring
) != NULL
)) ) {
3436 *sym
= anImage
->findExportedSymbol(name
, false, image
);
3437 if ( *sym
!= NULL
) {
3445 unsigned int getCoalescedImages(ImageLoader
* images
[])
3447 unsigned int count
= 0;
3448 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
3449 ImageLoader
* image
= *it
;
3450 if ( image
->participatesInCoalescing() ) {
3459 static ImageLoader::MappedRegion
* getMappedRegions(ImageLoader::MappedRegion
* regions
)
3461 ImageLoader::MappedRegion
* end
= regions
;
3462 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
3463 (*it
)->getMappedRegions(end
);
3468 void registerImageStateSingleChangeHandler(dyld_image_states state
, dyld_image_state_change_handler handler
)
3470 // mark the image that the handler is in as never-unload because dyld has a reference into it
3471 ImageLoader
* handlerImage
= findImageContainingAddress((void*)handler
);
3472 if ( handlerImage
!= NULL
)
3473 handlerImage
->setNeverUnload();
3475 // add to list of handlers
3476 std::vector
<dyld_image_state_change_handler
>* handlers
= stateToHandlers(state
, sSingleHandlers
);
3477 if ( handlers
!= NULL
) {
3478 handlers
->push_back(handler
);
3480 // call callback with all existing images
3481 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
3482 ImageLoader
* image
= *it
;
3483 dyld_image_info info
;
3484 info
.imageLoadAddress
= image
->machHeader();
3485 info
.imageFilePath
= image
->getPath();
3486 info
.imageFileModDate
= image
->lastModified();
3487 // should only call handler if state == image->state
3488 if ( image
->getState() == state
)
3489 (*handler
)(state
, 1, &info
);
3490 // ignore returned string, too late to do anything
3495 void registerImageStateBatchChangeHandler(dyld_image_states state
, dyld_image_state_change_handler handler
)
3497 // mark the image that the handler is in as never-unload because dyld has a reference into it
3498 ImageLoader
* handlerImage
= findImageContainingAddress((void*)handler
);
3499 if ( handlerImage
!= NULL
)
3500 handlerImage
->setNeverUnload();
3502 // add to list of handlers
3503 std::vector
<dyld_image_state_change_handler
>* handlers
= stateToHandlers(state
, sBatchHandlers
);
3504 if ( handlers
!= NULL
) {
3505 // insert at front, so that gdb handler is always last
3506 handlers
->insert(handlers
->begin(), handler
);
3508 // call callback with all existing images
3510 notifyBatchPartial(state
, true, handler
);
3512 catch (const char* msg
) {
3513 // ignore request to abort during registration
3518 static ImageLoader
* libraryLocator(const char* libraryName
, bool search
, const char* origin
, const ImageLoader::RPathChain
* rpaths
)
3520 dyld::LoadContext context
;
3521 context
.useSearchPaths
= search
;
3522 context
.useFallbackPaths
= search
;
3523 context
.useLdLibraryPath
= false;
3524 context
.implicitRPath
= false;
3525 context
.matchByInstallName
= false;
3526 context
.dontLoad
= false;
3527 context
.mustBeBundle
= false;
3528 context
.mustBeDylib
= true;
3529 context
.canBePIE
= false;
3530 context
.origin
= origin
;
3531 context
.rpath
= rpaths
;
3532 return load(libraryName
, context
);
3535 static const char* basename(const char* path
)
3537 const char* last
= path
;
3538 for (const char* s
= path
; *s
!= '\0'; s
++) {
3545 static void setContext(const macho_header
* mainExecutableMH
, int argc
, const char* argv
[], const char* envp
[], const char* apple
[])
3547 gLinkContext
.loadLibrary
= &libraryLocator
;
3548 gLinkContext
.terminationRecorder
= &terminationRecorder
;
3549 gLinkContext
.flatExportFinder
= &flatFindExportedSymbol
;
3550 gLinkContext
.coalescedExportFinder
= &findCoalescedExportedSymbol
;
3551 gLinkContext
.getCoalescedImages
= &getCoalescedImages
;
3552 gLinkContext
.undefinedHandler
= &undefinedHandler
;
3553 gLinkContext
.getAllMappedRegions
= &getMappedRegions
;
3554 gLinkContext
.bindingHandler
= NULL
;
3555 gLinkContext
.notifySingle
= ¬ifySingle
;
3556 gLinkContext
.notifyBatch
= ¬ifyBatch
;
3557 gLinkContext
.removeImage
= &removeImage
;
3558 gLinkContext
.registerDOFs
= ®isterDOFs
;
3559 gLinkContext
.clearAllDepths
= &clearAllDepths
;
3560 gLinkContext
.imageCount
= &imageCount
;
3561 gLinkContext
.setNewProgramVars
= &setNewProgramVars
;
3562 #if DYLD_SHARED_CACHE_SUPPORT
3563 gLinkContext
.inSharedCache
= &inSharedCache
;
3565 gLinkContext
.setErrorStrings
= &setErrorStrings
;
3566 #if SUPPORT_OLD_CRT_INITIALIZATION
3567 gLinkContext
.setRunInitialzersOldWay
= &setRunInitialzersOldWay
;
3569 gLinkContext
.bindingOptions
= ImageLoader::kBindingNone
;
3570 gLinkContext
.argc
= argc
;
3571 gLinkContext
.argv
= argv
;
3572 gLinkContext
.envp
= envp
;
3573 gLinkContext
.apple
= apple
;
3574 gLinkContext
.progname
= (argv
[0] != NULL
) ? basename(argv
[0]) : "";
3575 gLinkContext
.programVars
.mh
= mainExecutableMH
;
3576 gLinkContext
.programVars
.NXArgcPtr
= &gLinkContext
.argc
;
3577 gLinkContext
.programVars
.NXArgvPtr
= &gLinkContext
.argv
;
3578 gLinkContext
.programVars
.environPtr
= &gLinkContext
.envp
;
3579 gLinkContext
.programVars
.__prognamePtr
=&gLinkContext
.progname
;
3580 gLinkContext
.mainExecutable
= NULL
;
3581 gLinkContext
.imageSuffix
= NULL
;
3582 gLinkContext
.prebindUsage
= ImageLoader::kUseAllPrebinding
;
3583 gLinkContext
.sharedRegionMode
= ImageLoader::kUseSharedRegion
;
3586 #if __ppc__ || __i386__
3589 int mib
[] = { CTL_KERN
, KERN_CLASSIC
, getpid() };
3591 size_t len
= sizeof(int);
3592 int ret
= sysctl(mib
, 3, &is_classic
, &len
, NULL
, 0);
3593 if ((ret
!= -1) && is_classic
) {
3594 // we're running under Rosetta
3603 #define LC_SEGMENT_COMMAND LC_SEGMENT_64
3604 #define macho_segment_command segment_command_64
3605 #define macho_section section_64
3607 #define LC_SEGMENT_COMMAND LC_SEGMENT
3608 #define macho_segment_command segment_command
3609 #define macho_section section
3614 // Look for a special segment in the mach header.
3615 // Its presences means that the binary wants to have DYLD ignore
3616 // DYLD_ environment variables.
3618 static bool hasRestrictedSegment(const macho_header
* mh
)
3620 const uint32_t cmd_count
= mh
->ncmds
;
3621 const struct load_command
* const cmds
= (struct load_command
*)(((char*)mh
)+sizeof(macho_header
));
3622 const struct load_command
* cmd
= cmds
;
3623 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
3625 case LC_SEGMENT_COMMAND
:
3627 const struct macho_segment_command
* seg
= (struct macho_segment_command
*)cmd
;
3629 //dyld::log("seg name: %s\n", seg->segname);
3630 if (strcmp(seg
->segname
, "__RESTRICT") == 0) {
3631 const struct macho_section
* const sectionsStart
= (struct macho_section
*)((char*)seg
+ sizeof(struct macho_segment_command
));
3632 const struct macho_section
* const sectionsEnd
= §ionsStart
[seg
->nsects
];
3633 for (const struct macho_section
* sect
=sectionsStart
; sect
< sectionsEnd
; ++sect
) {
3634 if (strcmp(sect
->sectname
, "__restrict") == 0)
3641 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
3649 // Peeks at a dylib file and returns its current_version and install_name.
3650 // Returns false on error.
3652 static bool getDylibVersionAndInstallname(const char* dylibPath
, uint32_t* version
, char* installName
)
3654 // open file (automagically closed when this function exits)
3655 FileOpener
file(dylibPath
);
3657 if ( file
.getFileDescriptor() == -1 )
3660 uint8_t firstPage
[4096];
3661 if ( pread(file
.getFileDescriptor(), firstPage
, 4096, 0) != 4096 )
3664 // if fat wrapper, find usable sub-file
3665 const fat_header
* fileStartAsFat
= (fat_header
*)firstPage
;
3666 if ( fileStartAsFat
->magic
== OSSwapBigToHostInt32(FAT_MAGIC
) ) {
3667 uint64_t fileOffset
;
3668 uint64_t fileLength
;
3669 if ( fatFindBest(fileStartAsFat
, &fileOffset
, &fileLength
) ) {
3670 if ( pread(file
.getFileDescriptor(), firstPage
, 4096, fileOffset
) != 4096 )
3678 // check mach-o header
3679 const mach_header
* mh
= (mach_header
*)firstPage
;
3680 if ( mh
->magic
!= sMainExecutableMachHeader
->magic
)
3682 if ( mh
->cputype
!= sMainExecutableMachHeader
->cputype
)
3685 // scan load commands for LC_ID_DYLIB
3686 const uint32_t cmd_count
= mh
->ncmds
;
3687 const struct load_command
* const cmds
= (struct load_command
*)(((char*)mh
)+sizeof(macho_header
));
3688 const struct load_command
* const cmdsReadEnd
= (struct load_command
*)(((char*)mh
)+4096);
3689 const struct load_command
* cmd
= cmds
;
3690 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
3694 const struct dylib_command
* id
= (struct dylib_command
*)cmd
;
3695 *version
= id
->dylib
.current_version
;
3696 if ( installName
!= NULL
)
3697 strlcpy(installName
, (char *)id
+ id
->dylib
.name
.offset
, PATH_MAX
);
3702 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
3703 if ( cmd
> cmdsReadEnd
)
3711 static void printAllImages()
3713 dyld::log("printAllImages()\n");
3714 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
3715 ImageLoader
* image
= *it
;
3716 dyld_image_states imageState
= image
->getState();
3717 dyld::log(" state=%d, refcount=%d, name=%s\n", imageState
, image
->referenceCount(), image
->getShortName());
3718 image
->printReferenceCounts();
3723 void link(ImageLoader
* image
, bool forceLazysBound
, const ImageLoader::RPathChain
& loaderRPaths
)
3725 // add to list of known images. This did not happen at creation time for bundles
3726 if ( image
->isBundle() && !image
->isLinked() )
3729 // we detect root images as those not linked in yet
3730 if ( !image
->isLinked() )
3731 addRootImage(image
);
3735 image
->link(gLinkContext
, forceLazysBound
, false, loaderRPaths
);
3737 catch (const char* msg
) {
3738 garbageCollectImages();
3744 void runInitializers(ImageLoader
* image
)
3746 // do bottom up initialization
3747 ImageLoader::InitializerTimingList initializerTimes
[sAllImages
.size()];
3748 initializerTimes
[0].count
= 0;
3749 image
->runInitializers(gLinkContext
, initializerTimes
[0]);
3752 void garbageCollectImages()
3754 // keep scanning list of images until entire list is scanned with no unreferenced images
3755 bool mightBeUnreferencedImages
= true;
3756 while ( mightBeUnreferencedImages
) {
3757 mightBeUnreferencedImages
= false;
3758 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
3759 ImageLoader
* image
= *it
;
3760 if ( (image
->referenceCount() == 0) && !image
->neverUnload() && !image
->isBeingRemoved() ) {
3762 //dyld::log("garbageCollectImages: deleting %s\n", image->getPath());
3763 image
->setBeingRemoved();
3765 ImageLoader::deleteImage(image
);
3767 catch (const char* msg
) {
3768 dyld::warn("problem deleting image: %s\n", msg
);
3770 mightBeUnreferencedImages
= true;
3779 static void preflight_finally(ImageLoader
* image
)
3781 if ( image
->isBundle() ) {
3782 removeImageFromAllImages(image
->machHeader());
3783 ImageLoader::deleteImage(image
);
3785 sBundleBeingLoaded
= NULL
;
3786 dyld::garbageCollectImages();
3790 void preflight(ImageLoader
* image
, const ImageLoader::RPathChain
& loaderRPaths
)
3793 if ( image
->isBundle() )
3794 sBundleBeingLoaded
= image
; // hack
3795 image
->link(gLinkContext
, false, true, loaderRPaths
);
3797 catch (const char* msg
) {
3798 preflight_finally(image
);
3801 preflight_finally(image
);
3804 static void loadInsertedDylib(const char* path
)
3806 ImageLoader
* image
= NULL
;
3808 LoadContext context
;
3809 context
.useSearchPaths
= false;
3810 context
.useFallbackPaths
= false;
3811 context
.useLdLibraryPath
= false;
3812 context
.implicitRPath
= false;
3813 context
.matchByInstallName
= false;
3814 context
.dontLoad
= false;
3815 context
.mustBeBundle
= false;
3816 context
.mustBeDylib
= true;
3817 context
.canBePIE
= false;
3818 context
.origin
= NULL
; // can't use @loader_path with DYLD_INSERT_LIBRARIES
3819 context
.rpath
= NULL
;
3820 image
= load(path
, context
);
3821 image
->setNeverUnload();
3824 halt(dyld::mkstringf("could not load inserted library: %s\n", path
));
3828 static bool processRestricted(const macho_header
* mainExecutableMH
)
3830 // all processes with setuid or setgid bit set are restricted
3834 if ( hasRestrictedSegment(mainExecutableMH
) && (geteuid() != 0) ) {
3835 // existence of __RESTRICT/__restrict section make process restricted
3839 #if __MAC_OS_X_VERSION_MIN_REQUIRED
3840 // ask kernel if code signature of program makes it restricted
3842 if ( syscall(SYS_csops
/* 169 */,
3843 0 /* asking about myself */,
3846 sizeof(flags
)) != -1) {
3847 if (flags
& CS_RESTRICT
)
3856 // Entry point for dyld. The kernel loads dyld and jumps to __dyld_start which
3857 // sets up some registers and call this function.
3859 // Returns address of main() in target program which __dyld_start jumps to
3862 _main(const macho_header
* mainExecutableMH
, uintptr_t mainExecutableSlide
, int argc
, const char* argv
[], const char* envp
[], const char* apple
[])
3864 CRSetCrashLogMessage("dyld: launch started");
3865 #ifdef ALTERNATIVE_LOGFILE
3866 sLogfile
= open(ALTERNATIVE_LOGFILE
, O_WRONLY
| O_CREAT
| O_APPEND
);
3867 if ( sLogfile
== -1 ) {
3868 sLogfile
= STDERR_FILENO
;
3869 dyld::log("error opening alternate log file %s, errno = %d\n", ALTERNATIVE_LOGFILE
, errno
);
3874 char bindingsLogPath
[256];
3876 const char* shortProgName
= "unknown";
3878 shortProgName
= strrchr(argv
[0], '/');
3879 if ( shortProgName
== NULL
)
3880 shortProgName
= argv
[0];
3884 mysprintf(bindingsLogPath
, "/tmp/bindings/%d-%s", getpid(), shortProgName
);
3885 sBindingsLogfile
= open(bindingsLogPath
, O_WRONLY
| O_CREAT
, 0666);
3886 if ( sBindingsLogfile
== -1 ) {
3887 ::mkdir("/tmp/bindings", 0777);
3888 sBindingsLogfile
= open(bindingsLogPath
, O_WRONLY
| O_CREAT
, 0666);
3890 //dyld::log("open(%s) => %d, errno = %d\n", bindingsLogPath, sBindingsLogfile, errno);
3892 setContext(mainExecutableMH
, argc
, argv
, envp
, apple
);
3894 // Pickup the pointer to the exec path.
3895 sExecPath
= apple
[0];
3896 bool ignoreEnvironmentVariables
= false;
3898 if ( isRosetta() ) {
3899 // under Rosetta (x86 side)
3900 // When a 32-bit ppc program is run under emulation on an Intel processor,
3901 // we want any i386 dylibs (e.g. any used by Rosetta) to not load in the shared region
3902 // because the shared region is being used by ppc dylibs
3903 gLinkContext
.sharedRegionMode
= ImageLoader::kDontUseSharedRegion
;
3904 ignoreEnvironmentVariables
= true;
3907 if ( sExecPath
[0] != '/' ) {
3908 // have relative path, use cwd to make absolute
3909 char cwdbuff
[MAXPATHLEN
];
3910 if ( getcwd(cwdbuff
, MAXPATHLEN
) != NULL
) {
3911 // maybe use static buffer to avoid calling malloc so early...
3912 char* s
= new char[strlen(cwdbuff
) + strlen(sExecPath
) + 2];
3915 strcat(s
, sExecPath
);
3919 uintptr_t result
= 0;
3920 sMainExecutableMachHeader
= mainExecutableMH
;
3921 sProcessIsRestricted
= processRestricted(mainExecutableMH
);
3922 if ( sProcessIsRestricted
) {
3923 #if SUPPORT_LC_DYLD_ENVIRONMENT
3924 checkLoadCommandEnvironmentVariables();
3925 #if SUPPORT_VERSIONED_PATHS
3926 checkVersionedPaths();
3929 pruneEnvironmentVariables(envp
, &apple
);
3930 // set again because envp and apple may have changed or moved
3931 setContext(mainExecutableMH
, argc
, argv
, envp
, apple
);
3934 checkEnvironmentVariables(envp
, ignoreEnvironmentVariables
);
3935 if ( sEnv
.DYLD_PRINT_OPTS
)
3937 if ( sEnv
.DYLD_PRINT_ENV
)
3938 printEnvironmentVariables(envp
);
3940 // install gdb notifier
3941 stateToHandlers(dyld_image_state_dependents_mapped
, sBatchHandlers
)->push_back(notifyGDB
);
3942 stateToHandlers(dyld_image_state_mapped
, sSingleHandlers
)->push_back(updateAllImages
);
3943 // make initial allocations large enough that it is unlikely to need to be re-alloced
3944 sAllImages
.reserve(INITIAL_IMAGE_COUNT
);
3945 sImageRoots
.reserve(16);
3946 sAddImageCallbacks
.reserve(4);
3947 sRemoveImageCallbacks
.reserve(4);
3948 sImageFilesNeedingTermination
.reserve(16);
3949 sImageFilesNeedingDOFUnregistration
.reserve(8);
3951 #ifdef WAIT_FOR_SYSTEM_ORDER_HANDSHAKE
3952 // <rdar://problem/6849505> Add gating mechanism to dyld support system order file generation process
3953 WAIT_FOR_SYSTEM_ORDER_HANDSHAKE(dyld_all_image_infos
.systemOrderFlag
);
3957 CRSetCrashLogMessage("dyld: launch, loading dependent libraries");
3958 // instantiate ImageLoader for main executable
3959 sMainExecutable
= instantiateFromLoadedImage(mainExecutableMH
, mainExecutableSlide
, sExecPath
);
3960 sMainExecutable
->setNeverUnload();
3961 gLinkContext
.mainExecutable
= sMainExecutable
;
3962 gLinkContext
.processIsRestricted
= sProcessIsRestricted
;
3963 // load shared cache
3964 checkSharedRegionDisable();
3965 #if DYLD_SHARED_CACHE_SUPPORT
3966 if ( gLinkContext
.sharedRegionMode
!= ImageLoader::kDontUseSharedRegion
)
3969 // load any inserted libraries
3970 if ( sEnv
.DYLD_INSERT_LIBRARIES
!= NULL
) {
3971 for (const char* const* lib
= sEnv
.DYLD_INSERT_LIBRARIES
; *lib
!= NULL
; ++lib
)
3972 loadInsertedDylib(*lib
);
3974 // record count of inserted libraries so that a flat search will look at
3975 // inserted libraries, then main, then others.
3976 sInsertedDylibCount
= sAllImages
.size()-1;
3978 // link main executable
3979 gLinkContext
.linkingMainExecutable
= true;
3980 link(sMainExecutable
, sEnv
.DYLD_BIND_AT_LAUNCH
, ImageLoader::RPathChain(NULL
, NULL
));
3981 gLinkContext
.linkingMainExecutable
= false;
3982 if ( sMainExecutable
->forceFlat() ) {
3983 gLinkContext
.bindFlat
= true;
3984 gLinkContext
.prebindUsage
= ImageLoader::kUseNoPrebinding
;
3986 result
= (uintptr_t)sMainExecutable
->getMain();
3988 // link any inserted libraries
3989 // do this after linking main executable so that any dylibs pulled in by inserted
3990 // dylibs (e.g. libSystem) will not be in front of dylibs the program uses
3991 if ( sInsertedDylibCount
> 0 ) {
3992 for(unsigned int i
=0; i
< sInsertedDylibCount
; ++i
) {
3993 ImageLoader
* image
= sAllImages
[i
+1];
3994 link(image
, sEnv
.DYLD_BIND_AT_LAUNCH
, ImageLoader::RPathChain(NULL
, NULL
));
3995 // only INSERTED libraries can interpose
3996 image
->registerInterposing();
4000 CRSetCrashLogMessage("dyld: launch, running initializers");
4001 #if SUPPORT_OLD_CRT_INITIALIZATION
4002 // Old way is to run initializers via a callback from crt1.o
4003 if ( ! gRunInitializersOldWay
)
4005 initializeMainExecutable(); // run all initializers
4007 catch(const char* message
) {
4012 dyld::log("dyld: launch failed\n");
4015 #ifdef ALTERNATIVE_LOGFILE
4016 // only use alternate log during launch, otherwise file is open forever
4017 if ( sLogfile
!= STDERR_FILENO
) {
4019 sLogfile
= STDERR_FILENO
;
4022 CRSetCrashLogMessage(NULL
);