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 <mach/mach.h>
41 #include <sys/sysctl.h>
43 #include <sys/dtrace.h>
44 #include <libkern/OSAtomic.h>
45 #include <Availability.h>
46 #include <Kernel/sys/codesign.h>
49 #ifndef CPU_SUBTYPE_ARM_V5TEJ
50 #define CPU_SUBTYPE_ARM_V5TEJ ((cpu_subtype_t) 7)
52 #ifndef CPU_SUBTYPE_ARM_XSCALE
53 #define CPU_SUBTYPE_ARM_XSCALE ((cpu_subtype_t) 8)
55 #ifndef CPU_SUBTYPE_ARM_V7
56 #define CPU_SUBTYPE_ARM_V7 ((cpu_subtype_t) 9)
58 #ifndef LC_DYLD_ENVIRONMENT
59 #define LC_DYLD_ENVIRONMENT 0x27
63 #define VM_PROT_SLIDE 0x20
69 #include "mach-o/dyld_gdb.h"
72 #include "ImageLoader.h"
73 #include "ImageLoaderMachO.h"
74 #include "dyldLibSystemInterface.h"
75 #if DYLD_SHARED_CACHE_SUPPORT
76 #include "dyld_cache_format.h"
78 #if CORESYMBOLICATION_SUPPORT
79 #include "coreSymbolicationDyldSupport.hpp"
82 // from _simple.h in libc
83 typedef struct _SIMPLE
* _SIMPLE_STRING
;
84 extern "C" void _simple_vdprintf(int __fd
, const char *__fmt
, va_list __ap
);
85 extern "C" void _simple_dprintf(int __fd
, const char *__fmt
, ...);
86 extern "C" _SIMPLE_STRING
_simple_salloc(void);
87 extern "C" int _simple_vsprintf(_SIMPLE_STRING __b
, const char *__fmt
, va_list __ap
);
88 extern "C" void _simple_sfree(_SIMPLE_STRING __b
);
89 extern "C" char * _simple_string(_SIMPLE_STRING __b
);
93 // 32-bit ppc and ARM are the only architecture that use cpu-sub-types
94 #define CPU_SUBTYPES_SUPPORTED __ppc__ || __arm__
98 #define CPU_TYPE_MASK 0x00FFFFFF /* complement of CPU_ARCH_MASK */
101 /* implemented in dyld_gdb.cpp */
102 extern void addImagesToAllImages(uint32_t infoCount
, const dyld_image_info info
[]);
103 extern void removeImageFromAllImages(const mach_header
* mh
);
104 extern void setAlImageInfosHalt(const char* message
, uintptr_t flags
);
105 extern void addNonSharedCacheImageUUID(const dyld_uuid_info
& info
);
106 extern const char* notifyGDB(enum dyld_image_states state
, uint32_t infoCount
, const dyld_image_info info
[]);
108 // magic so CrashReporter logs message
110 char error_string
[1024];
112 // implemented in dyldStartup.s for CrashReporter
113 extern "C" void dyld_fatal_error(const char* errString
) __attribute__((noreturn
));
118 // The file contains the core of dyld used to get a process to main().
119 // The API's that dyld supports are implemented in dyldAPIs.cpp.
131 // state of all environment variables dyld uses
133 struct EnvironmentVariables
{
134 const char* const * DYLD_FRAMEWORK_PATH
;
135 const char* const * DYLD_FALLBACK_FRAMEWORK_PATH
;
136 const char* const * DYLD_LIBRARY_PATH
;
137 const char* const * DYLD_FALLBACK_LIBRARY_PATH
;
138 const char* const * DYLD_INSERT_LIBRARIES
;
139 const char* const * LD_LIBRARY_PATH
; // for unix conformance
140 const char* const * DYLD_VERSIONED_LIBRARY_PATH
;
141 const char* const * DYLD_VERSIONED_FRAMEWORK_PATH
;
142 bool DYLD_PRINT_LIBRARIES
;
143 bool DYLD_PRINT_LIBRARIES_POST_LAUNCH
;
144 bool DYLD_BIND_AT_LAUNCH
;
145 bool DYLD_PRINT_STATISTICS
;
146 bool DYLD_PRINT_OPTS
;
148 bool DYLD_DISABLE_DOFS
;
149 bool DYLD_PRINT_CS_NOTIFICATIONS
;
150 // DYLD_SHARED_CACHE_DONT_VALIDATE ==> sSharedCacheIgnoreInodeAndTimeStamp
151 // DYLD_SHARED_CACHE_DIR ==> sSharedCacheDir
152 // DYLD_ROOT_PATH ==> gLinkContext.rootPaths
153 // DYLD_IMAGE_SUFFIX ==> gLinkContext.imageSuffix
154 // DYLD_PRINT_OPTS ==> gLinkContext.verboseOpts
155 // DYLD_PRINT_ENV ==> gLinkContext.verboseEnv
156 // DYLD_FORCE_FLAT_NAMESPACE ==> gLinkContext.bindFlat
157 // DYLD_PRINT_INITIALIZERS ==> gLinkContext.verboseInit
158 // DYLD_PRINT_SEGMENTS ==> gLinkContext.verboseMapping
159 // DYLD_PRINT_BINDINGS ==> gLinkContext.verboseBind
160 // DYLD_PRINT_WEAK_BINDINGS ==> gLinkContext.verboseWeakBind
161 // DYLD_PRINT_REBASINGS ==> gLinkContext.verboseRebase
162 // DYLD_PRINT_DOFS ==> gLinkContext.verboseDOF
163 // DYLD_PRINT_APIS ==> gLogAPIs
164 // DYLD_IGNORE_PREBINDING ==> gLinkContext.prebindUsage
165 // DYLD_PREBIND_DEBUG ==> gLinkContext.verbosePrebinding
166 // DYLD_NEW_LOCAL_SHARED_REGIONS ==> gLinkContext.sharedRegionMode
167 // DYLD_SHARED_REGION ==> gLinkContext.sharedRegionMode
168 // DYLD_PRINT_WARNINGS ==> gLinkContext.verboseWarnings
169 // DYLD_PRINT_RPATHS ==> gLinkContext.verboseRPaths
170 // DYLD_PRINT_INTERPOSING ==> gLinkContext.verboseInterposing
173 typedef std::vector
<dyld_image_state_change_handler
> StateHandlers
;
174 struct RegisteredDOF
{ const mach_header
* mh
; int registrationID
; };
175 struct DylibOverride
{ const char* installName
; const char* override
; };
178 static const char* sExecPath
= NULL
;
179 static const macho_header
* sMainExecutableMachHeader
= NULL
;
180 #if CPU_SUBTYPES_SUPPORTED
181 static cpu_type_t sHostCPU
;
182 static cpu_subtype_t sHostCPUsubtype
;
184 static ImageLoader
* sMainExecutable
= NULL
;
185 static bool sProcessIsRestricted
= false;
186 static unsigned int sInsertedDylibCount
= 0;
187 static std::vector
<ImageLoader
*> sAllImages
;
188 static std::vector
<ImageLoader
*> sImageRoots
;
189 static std::vector
<ImageLoader
*> sImageFilesNeedingTermination
;
190 static std::vector
<RegisteredDOF
> sImageFilesNeedingDOFUnregistration
;
191 static std::vector
<ImageCallback
> sAddImageCallbacks
;
192 static std::vector
<ImageCallback
> sRemoveImageCallbacks
;
193 static StateHandlers sSingleHandlers
[7];
194 static StateHandlers sBatchHandlers
[7];
195 static ImageLoader
* sLastImageByAddressCache
;
196 static EnvironmentVariables sEnv
;
197 static const char* sFrameworkFallbackPaths
[] = { "$HOME/Library/Frameworks", "/Library/Frameworks", "/Network/Library/Frameworks", "/System/Library/Frameworks", NULL
};
198 static const char* sLibraryFallbackPaths
[] = { "$HOME/lib", "/usr/local/lib", "/usr/lib", NULL
};
199 static UndefinedHandler sUndefinedHandler
= NULL
;
200 static ImageLoader
* sBundleBeingLoaded
= NULL
; // hack until OFI is reworked
201 #if DYLD_SHARED_CACHE_SUPPORT
202 static const dyld_cache_header
* sSharedCache
= NULL
;
203 static long sSharedCacheSlide
= 0;
204 static bool sSharedCacheIgnoreInodeAndTimeStamp
= false;
205 #if __IPHONE_OS_VERSION_MIN_REQUIRED
206 bool gSharedCacheOverridden
= false;
207 static const char* sSharedCacheDir
= IPHONE_DYLD_SHARED_CACHE_DIR
;
208 static bool sDylibsOverrideCache
= false;
210 static const char* sSharedCacheDir
= MACOSX_DYLD_SHARED_CACHE_DIR
;
213 ImageLoader::LinkContext gLinkContext
;
214 bool gLogAPIs
= false;
215 const struct LibSystemHelpers
* gLibSystemHelpers
= NULL
;
216 #if SUPPORT_OLD_CRT_INITIALIZATION
217 bool gRunInitializersOldWay
= false;
219 static std::vector
<DylibOverride
> sDylibOverrides
;
222 // The MappedRanges structure is used for fast address->image lookups.
223 // The table is only updated when the dyld lock is held, so we don't
224 // need to worry about multiple writers. But readers may look at this
225 // data without holding the lock. Therefore, all updates must be done
226 // in an order that will never cause readers to see inconsistent data.
227 // The general rule is that if the image field is non-NULL then
228 // the other fields are valid.
241 static MappedRanges sMappedRangesStart
;
243 void addMappedRange(ImageLoader
* image
, uintptr_t start
, uintptr_t end
)
245 //dyld::log("addMappedRange(0x%lX->0x%lX) for %s\n", start, end, image->getShortName());
246 for (MappedRanges
* p
= &sMappedRangesStart
; p
!= NULL
; p
= p
->next
) {
247 for (int i
=0; i
< MappedRanges::count
; ++i
) {
248 if ( p
->array
[i
].image
== NULL
) {
249 p
->array
[i
].start
= start
;
250 p
->array
[i
].end
= end
;
251 // add image field last with a barrier so that any reader will see consistent records
253 p
->array
[i
].image
= image
;
258 // table must be full, chain another
259 MappedRanges
* newRanges
= (MappedRanges
*)malloc(sizeof(MappedRanges
));
260 bzero(newRanges
, sizeof(MappedRanges
));
261 newRanges
->array
[0].start
= start
;
262 newRanges
->array
[0].end
= end
;
263 newRanges
->array
[0].image
= image
;
264 for (MappedRanges
* p
= &sMappedRangesStart
; p
!= NULL
; p
= p
->next
) {
265 if ( p
->next
== NULL
) {
273 void removedMappedRanges(ImageLoader
* image
)
275 for (MappedRanges
* p
= &sMappedRangesStart
; p
!= NULL
; p
= p
->next
) {
276 for (int i
=0; i
< MappedRanges::count
; ++i
) {
277 if ( p
->array
[i
].image
== image
) {
278 // clear with a barrier so that any reader will see consistent records
280 p
->array
[i
].image
= NULL
;
286 ImageLoader
* findMappedRange(uintptr_t target
)
288 for (MappedRanges
* p
= &sMappedRangesStart
; p
!= NULL
; p
= p
->next
) {
289 for (int i
=0; i
< MappedRanges::count
; ++i
) {
290 if ( p
->array
[i
].image
!= NULL
) {
291 if ( (p
->array
[i
].start
<= target
) && (target
< p
->array
[i
].end
) )
292 return p
->array
[i
].image
;
301 const char* mkstringf(const char* format
, ...)
303 _SIMPLE_STRING buf
= _simple_salloc();
306 va_start(list
, format
);
307 _simple_vsprintf(buf
, format
, list
);
309 const char* t
= strdup(_simple_string(buf
));
314 return "mkstringf, out of memory error";
318 void throwf(const char* format
, ...)
320 _SIMPLE_STRING buf
= _simple_salloc();
323 va_start(list
, format
);
324 _simple_vsprintf(buf
, format
, list
);
326 const char* t
= strdup(_simple_string(buf
));
331 throw "throwf, out of memory error";
335 //#define ALTERNATIVE_LOGFILE "/dev/console"
336 static int sLogfile
= STDERR_FILENO
;
339 static int sBindingsLogfile
= -1;
340 static void mysprintf(char* dst
, const char* format
, ...)
342 _SIMPLE_STRING buf
= _simple_salloc();
345 va_start(list
, format
);
346 _simple_vsprintf(buf
, format
, list
);
348 strcpy(dst
, _simple_string(buf
));
352 strcpy(dst
, "out of memory");
355 void logBindings(const char* format
, ...)
357 if ( sBindingsLogfile
!= -1 ) {
359 va_start(list
, format
);
360 _simple_vdprintf(sBindingsLogfile
, format
, list
);
367 void log(const char* format
, ...)
370 va_start(list
, format
);
371 _simple_vdprintf(sLogfile
, format
, list
);
375 void warn(const char* format
, ...)
377 _simple_dprintf(sLogfile
, "dyld: warning, ");
379 va_start(list
, format
);
380 _simple_vdprintf(sLogfile
, format
, list
);
385 // utility class to assure files are closed when an exception is thrown
388 FileOpener(const char* path
);
390 int getFileDescriptor() { return fd
; }
395 FileOpener::FileOpener(const char* path
)
398 fd
= open(path
, O_RDONLY
, 0);
401 FileOpener::~FileOpener()
408 // forward declaration
409 #if __ppc__ || __i386__
414 static void registerDOFs(const std::vector
<ImageLoader::DOFInfo
>& dofs
)
417 // can't dtrace a program running emulated under rosetta rdar://problem/5179640
421 const unsigned int dofSectionCount
= dofs
.size();
422 if ( !sEnv
.DYLD_DISABLE_DOFS
&& (dofSectionCount
!= 0) ) {
423 int fd
= open("/dev/" DTRACEMNR_HELPER
, O_RDWR
);
425 //dyld::warn("can't open /dev/" DTRACEMNR_HELPER " to register dtrace DOF sections\n");
428 // allocate a buffer on the stack for the variable length dof_ioctl_data_t type
429 uint8_t buffer
[sizeof(dof_ioctl_data_t
) + dofSectionCount
*sizeof(dof_helper_t
)];
430 dof_ioctl_data_t
* ioctlData
= (dof_ioctl_data_t
*)buffer
;
432 // fill in buffer with one dof_helper_t per DOF section
433 ioctlData
->dofiod_count
= dofSectionCount
;
434 for (unsigned int i
=0; i
< dofSectionCount
; ++i
) {
435 strlcpy(ioctlData
->dofiod_helpers
[i
].dofhp_mod
, dofs
[i
].imageShortName
, DTRACE_MODNAMELEN
);
436 ioctlData
->dofiod_helpers
[i
].dofhp_dof
= (uintptr_t)(dofs
[i
].dof
);
437 ioctlData
->dofiod_helpers
[i
].dofhp_addr
= (uintptr_t)(dofs
[i
].dof
);
440 // tell kernel about all DOF sections en mas
441 // pass pointer to ioctlData because ioctl() only copies a fixed size amount of data into kernel
442 user_addr_t val
= (user_addr_t
)(unsigned long)ioctlData
;
443 if ( ioctl(fd
, DTRACEHIOC_ADDDOF
, &val
) != -1 ) {
444 // kernel returns a unique identifier for each section in the dofiod_helpers[].dofhp_dof field.
445 for (unsigned int i
=0; i
< dofSectionCount
; ++i
) {
447 info
.mh
= dofs
[i
].imageHeader
;
448 info
.registrationID
= (int)(ioctlData
->dofiod_helpers
[i
].dofhp_dof
);
449 sImageFilesNeedingDOFUnregistration
.push_back(info
);
450 if ( gLinkContext
.verboseDOF
) {
451 dyld::log("dyld: registering DOF section 0x%p in %s with dtrace, ID=0x%08X\n",
452 dofs
[i
].dof
, dofs
[i
].imageShortName
, info
.registrationID
);
457 dyld::log( "dyld: ioctl to register dtrace DOF section failed\n");
464 static void unregisterDOF(int registrationID
)
466 int fd
= open("/dev/" DTRACEMNR_HELPER
, O_RDWR
);
468 dyld::warn("can't open /dev/" DTRACEMNR_HELPER
" to unregister dtrace DOF section\n");
471 ioctl(fd
, DTRACEHIOC_REMOVE
, registrationID
);
473 if ( gLinkContext
.verboseInit
)
474 dyld::warn("unregistering DOF section ID=0x%08X with dtrace\n", registrationID
);
480 // _dyld_register_func_for_add_image() is implemented as part of the general image state change notification
482 static void notifyAddImageCallbacks(ImageLoader
* image
)
484 // use guard so that we cannot notify about the same image twice
485 if ( ! image
->addFuncNotified() ) {
486 for (std::vector
<ImageCallback
>::iterator it
=sAddImageCallbacks
.begin(); it
!= sAddImageCallbacks
.end(); it
++)
487 (*it
)(image
->machHeader(), image
->getSlide());
488 image
->setAddFuncNotified();
494 // notify gdb about these new images
495 static const char* updateAllImages(enum dyld_image_states state
, uint32_t infoCount
, const struct dyld_image_info info
[])
497 // <rdar://problem/8812589> don't add images without paths to all-image-info-list
498 if ( info
[0].imageFilePath
!= NULL
)
499 addImagesToAllImages(infoCount
, info
);
504 static StateHandlers
* stateToHandlers(dyld_image_states state
, StateHandlers handlersArray
[8])
507 case dyld_image_state_mapped
:
508 return &handlersArray
[0];
510 case dyld_image_state_dependents_mapped
:
511 return &handlersArray
[1];
513 case dyld_image_state_rebased
:
514 return &handlersArray
[2];
516 case dyld_image_state_bound
:
517 return &handlersArray
[3];
519 case dyld_image_state_dependents_initialized
:
520 return &handlersArray
[4];
522 case dyld_image_state_initialized
:
523 return &handlersArray
[5];
525 case dyld_image_state_terminated
:
526 return &handlersArray
[6];
532 static void notifySingle(dyld_image_states state
, const ImageLoader
* image
)
534 //dyld::log("notifySingle(state=%d, image=%s)\n", state, image->getPath());
535 std::vector
<dyld_image_state_change_handler
>* handlers
= stateToHandlers(state
, sSingleHandlers
);
536 if ( handlers
!= NULL
) {
537 dyld_image_info info
;
538 info
.imageLoadAddress
= image
->machHeader();
539 info
.imageFilePath
= image
->getPath();
540 info
.imageFileModDate
= image
->lastModified();
541 for (std::vector
<dyld_image_state_change_handler
>::iterator it
= handlers
->begin(); it
!= handlers
->end(); ++it
) {
542 const char* result
= (*it
)(state
, 1, &info
);
543 if ( (result
!= NULL
) && (state
== dyld_image_state_mapped
) ) {
544 //fprintf(stderr, " image rejected by handler=%p\n", *it);
545 // make copy of thrown string so that later catch clauses can free it
546 const char* str
= strdup(result
);
551 if ( state
== dyld_image_state_mapped
) {
552 // <rdar://problem/7008875> Save load addr + UUID for images from outside the shared cache
553 if ( !image
->inSharedCache() ) {
555 if ( image
->getUUID(info
.imageUUID
) ) {
556 info
.imageLoadAddress
= image
->machHeader();
557 addNonSharedCacheImageUUID(info
);
561 #if CORESYMBOLICATION_SUPPORT
562 // mach message csdlc about dynamically loaded images
563 if ( image
->addFuncNotified() && (state
== dyld_image_state_terminated
) ) {
564 if ( sEnv
.DYLD_PRINT_CS_NOTIFICATIONS
) {
565 dyld::log("dyld core symbolication unload notification: %p %s\n", image
->machHeader(), image
->getPath());
567 if ( dyld_all_image_infos
.coreSymbolicationShmPage
!= NULL
) {
568 CSCppDyldSharedMemoryPage
* connection
= (CSCppDyldSharedMemoryPage
*)dyld_all_image_infos
.coreSymbolicationShmPage
;
569 if ( connection
->is_valid_version() ) {
570 coresymbolication_unload_image(connection
, image
);
581 // Normally, dyld_all_image_infos is only updated in batches after an entire
582 // graph is loaded. But if there is an error loading the initial set of
583 // dylibs needed by the main executable, dyld_all_image_infos is not yet set
584 // up, leading to usually brief crash logs.
586 // This function manually adds the images loaded so far to dyld_all_image_infos.
587 // It should only be called before terminating.
591 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); ++it
) {
592 dyld_image_info info
;
593 ImageLoader
* image
= *it
;
594 info
.imageLoadAddress
= image
->machHeader();
595 info
.imageFilePath
= image
->getPath();
596 info
.imageFileModDate
= image
->lastModified();
597 // add to all_image_infos if not already there
599 int existingCount
= dyld_all_image_infos
.infoArrayCount
;
600 const dyld_image_info
* existing
= dyld_all_image_infos
.infoArray
;
601 if ( existing
!= NULL
) {
602 for (int i
=0; i
< existingCount
; ++i
) {
603 if ( existing
[i
].imageLoadAddress
== info
.imageLoadAddress
) {
604 //dyld::log("not adding %s\n", info.imageFilePath);
611 //dyld::log("adding %s\n", info.imageFilePath);
612 addImagesToAllImages(1, &info
);
618 static int imageSorter(const void* l
, const void* r
)
620 const ImageLoader
* left
= *((ImageLoader
**)l
);
621 const ImageLoader
* right
= *((ImageLoader
**)r
);
622 return left
->compare(right
);
625 static void notifyBatchPartial(dyld_image_states state
, bool orLater
, dyld_image_state_change_handler onlyHandler
)
627 std::vector
<dyld_image_state_change_handler
>* handlers
= stateToHandlers(state
, sBatchHandlers
);
628 if ( handlers
!= NULL
) {
629 // don't use a vector because it will use malloc/free and we want notifcation to be low cost
630 ImageLoader
* images
[sAllImages
.size()+1];
631 ImageLoader
** end
= images
;
632 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
633 dyld_image_states imageState
= (*it
)->getState();
634 if ( (imageState
== state
) || (orLater
&& (imageState
> state
)) )
637 if ( sBundleBeingLoaded
!= NULL
) {
638 dyld_image_states imageState
= sBundleBeingLoaded
->getState();
639 if ( (imageState
== state
) || (orLater
&& (imageState
> state
)) )
640 *end
++ = sBundleBeingLoaded
;
642 unsigned int count
= end
-images
;
643 if ( end
!= images
) {
645 qsort(images
, count
, sizeof(ImageLoader
*), &imageSorter
);
647 dyld_image_info infos
[count
];
648 for (unsigned int i
=0; i
< count
; ++i
) {
649 dyld_image_info
* p
= &infos
[i
];
650 ImageLoader
* image
= images
[i
];
651 //dyld::log(" state=%d, name=%s\n", state, image->getPath());
652 p
->imageLoadAddress
= image
->machHeader();
653 p
->imageFilePath
= image
->getPath();
654 p
->imageFileModDate
= image
->lastModified();
655 // special case for add_image hook
656 if ( state
== dyld_image_state_bound
)
657 notifyAddImageCallbacks(image
);
660 if ( onlyHandler
!= NULL
) {
661 const char* result
= (*onlyHandler
)(state
, count
, infos
);
662 if ( (result
!= NULL
) && (state
== dyld_image_state_dependents_mapped
) ) {
663 //fprintf(stderr, " images rejected by handler=%p\n", onlyHandler);
664 // make copy of thrown string so that later catch clauses can free it
665 const char* str
= strdup(result
);
670 // call each handler with whole array
671 for (std::vector
<dyld_image_state_change_handler
>::iterator it
= handlers
->begin(); it
!= handlers
->end(); ++it
) {
672 const char* result
= (*it
)(state
, count
, infos
);
673 if ( (result
!= NULL
) && (state
== dyld_image_state_dependents_mapped
) ) {
674 //fprintf(stderr, " images rejected by handler=%p\n", *it);
675 // make copy of thrown string so that later catch clauses can free it
676 const char* str
= strdup(result
);
683 #if CORESYMBOLICATION_SUPPORT
684 if ( state
== dyld_image_state_rebased
) {
685 if ( sEnv
.DYLD_PRINT_CS_NOTIFICATIONS
) {
686 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
687 dyld_image_states imageState
= (*it
)->getState();
688 if ( (imageState
== dyld_image_state_rebased
) || (orLater
&& (imageState
> dyld_image_state_rebased
)) )
689 dyld::log("dyld core symbolication load notification: %p %s\n", (*it
)->machHeader(), (*it
)->getPath());
692 if ( dyld_all_image_infos
.coreSymbolicationShmPage
!= NULL
) {
693 CSCppDyldSharedMemoryPage
* connection
= (CSCppDyldSharedMemoryPage
*)dyld_all_image_infos
.coreSymbolicationShmPage
;
694 if ( connection
->is_valid_version() ) {
695 // This needs to be captured now
696 uint64_t load_timestamp
= mach_absolute_time();
697 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
698 dyld_image_states imageState
= (*it
)->getState();
699 if ( (imageState
== state
) || (orLater
&& (imageState
> state
)) )
700 coresymbolication_load_image(connection
, *it
, load_timestamp
);
710 static void notifyBatch(dyld_image_states state
)
712 notifyBatchPartial(state
, false, NULL
);
715 // In order for register_func_for_add_image() callbacks to to be called bottom up,
716 // we need to maintain a list of root images. The main executable is usally the
717 // first root. Any images dynamically added are also roots (unless already loaded).
718 // If DYLD_INSERT_LIBRARIES is used, those libraries are first.
719 static void addRootImage(ImageLoader
* image
)
721 //dyld::log("addRootImage(%p, %s)\n", image, image->getPath());
722 // add to list of roots
723 sImageRoots
.push_back(image
);
727 static void clearAllDepths()
729 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++)
733 static unsigned int imageCount()
735 return sAllImages
.size();
739 static void setNewProgramVars(const ProgramVars
& newVars
)
741 // make a copy of the pointers to program variables
742 gLinkContext
.programVars
= newVars
;
744 // now set each program global to their initial value
745 *gLinkContext
.programVars
.NXArgcPtr
= gLinkContext
.argc
;
746 *gLinkContext
.programVars
.NXArgvPtr
= gLinkContext
.argv
;
747 *gLinkContext
.programVars
.environPtr
= gLinkContext
.envp
;
748 *gLinkContext
.programVars
.__prognamePtr
= gLinkContext
.progname
;
751 #if SUPPORT_OLD_CRT_INITIALIZATION
752 static void setRunInitialzersOldWay()
754 gRunInitializersOldWay
= true;
758 static void addImage(ImageLoader
* image
)
760 // add to master list
761 sAllImages
.push_back(image
);
763 // update mapped ranges
764 uintptr_t lastSegStart
= 0;
765 uintptr_t lastSegEnd
= 0;
766 for(unsigned int i
=0, e
=image
->segmentCount(); i
< e
; ++i
) {
767 if ( image
->segUnaccessible(i
) )
769 uintptr_t start
= image
->segActualLoadAddress(i
);
770 uintptr_t end
= image
->segActualEndAddress(i
);
771 if ( start
== lastSegEnd
) {
772 // two segments are contiguous, just record combined segments
776 // non-contiguous segments, record last (if any)
777 if ( lastSegEnd
!= 0 )
778 addMappedRange(image
, lastSegStart
, lastSegEnd
);
779 lastSegStart
= start
;
783 if ( lastSegEnd
!= 0 )
784 addMappedRange(image
, lastSegStart
, lastSegEnd
);
787 if ( sEnv
.DYLD_PRINT_LIBRARIES
|| (sEnv
.DYLD_PRINT_LIBRARIES_POST_LAUNCH
&& (sMainExecutable
!=NULL
) && sMainExecutable
->isLinked()) ) {
788 dyld::log("dyld: loaded: %s\n", image
->getPath());
793 void removeImage(ImageLoader
* image
)
795 // if in termination list, pull it out and run terminator
796 for (std::vector
<ImageLoader
*>::iterator it
=sImageFilesNeedingTermination
.begin(); it
!= sImageFilesNeedingTermination
.end(); it
++) {
797 if ( *it
== image
) {
798 sImageFilesNeedingTermination
.erase(it
);
799 image
->doTermination(gLinkContext
);
804 // if has dtrace DOF section, tell dtrace it is going away, then remove from sImageFilesNeedingDOFUnregistration
805 for (std::vector
<RegisteredDOF
>::iterator it
=sImageFilesNeedingDOFUnregistration
.begin(); it
!= sImageFilesNeedingDOFUnregistration
.end(); ) {
806 if ( it
->mh
== image
->machHeader() ) {
807 unregisterDOF(it
->registrationID
);
808 sImageFilesNeedingDOFUnregistration
.erase(it
);
809 // don't increment iterator, the erase caused next element to be copied to where this iterator points
816 // tell all registered remove image handlers about this
817 // do this before removing image from internal data structures so that the callback can query dyld about the image
818 if ( image
->getState() >= dyld_image_state_bound
) {
819 for (std::vector
<ImageCallback
>::iterator it
=sRemoveImageCallbacks
.begin(); it
!= sRemoveImageCallbacks
.end(); it
++) {
820 (*it
)(image
->machHeader(), image
->getSlide());
825 notifySingle(dyld_image_state_terminated
, image
);
827 // <rdar://problem/7740779> dyld should directly call __cxa_finalize()
828 if ( (gLibSystemHelpers
!= NULL
) && (gLibSystemHelpers
->version
>= 8) )
829 (*gLibSystemHelpers
->cxa_finalize
)(image
->machHeader());
831 // remove from mapped images table
832 removedMappedRanges(image
);
834 // remove from master list
835 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
836 if ( *it
== image
) {
837 sAllImages
.erase(it
);
842 // flush find-by-address cache (do this after removed from master list, so there is no chance it can come back)
843 if ( sLastImageByAddressCache
== image
)
844 sLastImageByAddressCache
= NULL
;
846 // if in root list, pull it out
847 for (std::vector
<ImageLoader
*>::iterator it
=sImageRoots
.begin(); it
!= sImageRoots
.end(); it
++) {
848 if ( *it
== image
) {
849 sImageRoots
.erase(it
);
855 if ( sEnv
.DYLD_PRINT_LIBRARIES
|| (sEnv
.DYLD_PRINT_LIBRARIES_POST_LAUNCH
&& (sMainExecutable
!=NULL
) && sMainExecutable
->isLinked()) ) {
856 dyld::log("dyld: unloaded: %s\n", image
->getPath());
860 removeImageFromAllImages(image
->machHeader());
864 static void terminationRecorder(ImageLoader
* image
)
866 sImageFilesNeedingTermination
.push_back(image
);
869 const char* getExecutablePath()
875 void initializeMainExecutable()
877 // apply interposing to initial set of images
878 // do this before making the __IMPORT segments in shared cache read-only
879 sMainExecutable
->applyInterposing(gLinkContext
);
881 // record that we've reached this step
882 gLinkContext
.startedInitializingMainExecutable
= true;
884 // run initialzers for any inserted dylibs
885 ImageLoader::InitializerTimingList initializerTimes
[sAllImages
.size()];
886 const int rootCount
= sImageRoots
.size();
887 if ( rootCount
> 1 ) {
888 for(int i
=1; i
< rootCount
; ++i
) {
889 initializerTimes
[0].count
= 0;
890 sImageRoots
[i
]->runInitializers(gLinkContext
, initializerTimes
[0]);
894 // run initializers for main executable and everything it brings up
895 initializerTimes
[0].count
= 0;
896 sMainExecutable
->runInitializers(gLinkContext
, initializerTimes
[0]);
898 // register atexit() handler to run terminators in all loaded images when this process exits
899 if ( gLibSystemHelpers
!= NULL
)
900 (*gLibSystemHelpers
->cxa_atexit
)(&runTerminators
, NULL
, NULL
);
902 // dump info if requested
903 if ( sEnv
.DYLD_PRINT_STATISTICS
)
904 ImageLoaderMachO::printStatistics(sAllImages
.size(), initializerTimes
[0]);
907 bool mainExecutablePrebound()
909 return sMainExecutable
->usablePrebinding(gLinkContext
);
912 ImageLoader
* mainExecutable()
914 return sMainExecutable
;
918 void runTerminators(void* extra
)
920 const unsigned int imageCount
= sImageFilesNeedingTermination
.size();
921 for(unsigned int i
=imageCount
; i
> 0; --i
){
922 ImageLoader
* image
= sImageFilesNeedingTermination
[i
-1];
923 image
->doTermination(gLinkContext
);
925 sImageFilesNeedingTermination
.clear();
926 notifyBatch(dyld_image_state_terminated
);
931 static bool getDylibVersionAndInstallname(const char* dylibPath
, uint32_t* version
, char* installName
);
935 // Examines a dylib file and if its current_version is newer than the installed
936 // dylib at its install_name, then add the dylib file to sDylibOverrides.
938 static void checkDylibOverride(const char* dylibFile
)
940 //dyld::log("checkDylibOverride('%s')\n", dylibFile);
942 char sysInstallName
[PATH_MAX
];
943 if ( getDylibVersionAndInstallname(dylibFile
, &altVersion
, sysInstallName
) ) {
944 //dyld::log("%s has version 0x%08X and install name %s\n", dylibFile, altVersion, sysInstallName);
946 if ( getDylibVersionAndInstallname(sysInstallName
, &sysVersion
, NULL
) ) {
947 //dyld::log("%s has version 0x%08X\n", sysInstallName, sysVersion);
948 if ( altVersion
> sysVersion
) {
949 //dyld::log("override found: %s -> %s\n", sysInstallName, dylibFile);
950 // see if there already is an override for this dylib
951 bool entryExists
= false;
952 for (std::vector
<DylibOverride
>::iterator it
= sDylibOverrides
.begin(); it
!= sDylibOverrides
.end(); ++it
) {
953 if ( strcmp(it
->installName
, sysInstallName
) == 0 ) {
955 uint32_t prevVersion
;
956 if ( getDylibVersionAndInstallname(it
->override
, &prevVersion
, NULL
) ) {
957 if ( altVersion
> prevVersion
) {
958 // found an even newer override
959 free((void*)(it
->override
));
960 it
->override
= strdup(dylibFile
);
966 if ( ! entryExists
) {
968 entry
.installName
= strdup(sysInstallName
);
969 entry
.override
= strdup(dylibFile
);
970 sDylibOverrides
.push_back(entry
);
971 //dyld::log("added override: %s -> %s\n", entry.installName, entry.override);
979 static void checkDylibOverridesInDir(const char* dirPath
)
981 //dyld::log("checkDylibOverridesInDir('%s')\n", dirPath);
982 char dylibPath
[PATH_MAX
];
983 int dirPathLen
= strlen(dirPath
);
984 strlcpy(dylibPath
, dirPath
, PATH_MAX
);
985 DIR* dirp
= opendir(dirPath
);
989 while ( readdir_r(dirp
, &entry
, &entp
) == 0 ) {
992 if ( entp
->d_type
!= DT_REG
)
994 dylibPath
[dirPathLen
] = '/';
995 dylibPath
[dirPathLen
+1] = '\0';
996 if ( strlcat(dylibPath
, entp
->d_name
, PATH_MAX
) > PATH_MAX
)
998 checkDylibOverride(dylibPath
);
1005 static void checkFrameworkOverridesInDir(const char* dirPath
)
1007 //dyld::log("checkFrameworkOverridesInDir('%s')\n", dirPath);
1008 char frameworkPath
[PATH_MAX
];
1009 int dirPathLen
= strlen(dirPath
);
1010 strlcpy(frameworkPath
, dirPath
, PATH_MAX
);
1011 DIR* dirp
= opendir(dirPath
);
1012 if ( dirp
!= NULL
) {
1014 dirent
* entp
= NULL
;
1015 while ( readdir_r(dirp
, &entry
, &entp
) == 0 ) {
1018 if ( entp
->d_type
!= DT_DIR
)
1020 frameworkPath
[dirPathLen
] = '/';
1021 frameworkPath
[dirPathLen
+1] = '\0';
1022 int dirNameLen
= strlen(entp
->d_name
);
1023 if ( dirNameLen
< 11 )
1025 if ( strcmp(&entp
->d_name
[dirNameLen
-10], ".framework") != 0 )
1027 if ( strlcat(frameworkPath
, entp
->d_name
, PATH_MAX
) > PATH_MAX
)
1029 if ( strlcat(frameworkPath
, "/", PATH_MAX
) > PATH_MAX
)
1031 if ( strlcat(frameworkPath
, entp
->d_name
, PATH_MAX
) > PATH_MAX
)
1033 frameworkPath
[strlen(frameworkPath
)-10] = '\0';
1034 checkDylibOverride(frameworkPath
);
1041 // Turns a colon separated list of strings into a NULL terminated array
1042 // of string pointers. If mainExecutableDir param is not NULL,
1043 // substitutes @loader_path with main executable's dir.
1045 static const char** parseColonList(const char* list
, const char* mainExecutableDir
)
1047 static const char* sEmptyList
[] = { NULL
};
1049 if ( list
[0] == '\0' )
1053 for(const char* s
=list
; *s
!= '\0'; ++s
) {
1059 const char* start
= list
;
1060 char** result
= new char*[colonCount
+2];
1061 for(const char* s
=list
; *s
!= '\0'; ++s
) {
1064 if ( (mainExecutableDir
!= NULL
) && (strncmp(start
, "@loader_path/", 13) == 0) ) {
1065 int mainExecDirLen
= strlen(mainExecutableDir
);
1066 char* str
= new char[mainExecDirLen
+len
+1];
1067 strcpy(str
, mainExecutableDir
);
1068 strlcat(str
, &start
[13], mainExecDirLen
+len
+1);
1069 str
[mainExecDirLen
+len
-13] = '\0';
1071 result
[index
++] = str
;
1073 else if ( (mainExecutableDir
!= NULL
) && (strncmp(start
, "@executable_path/", 17) == 0) ) {
1074 int mainExecDirLen
= strlen(mainExecutableDir
);
1075 char* str
= new char[mainExecDirLen
+len
+1];
1076 strcpy(str
, mainExecutableDir
);
1077 strlcat(str
, &start
[17], mainExecDirLen
+len
+1);
1078 str
[mainExecDirLen
+len
-17] = '\0';
1080 result
[index
++] = str
;
1083 char* str
= new char[len
+1];
1084 strncpy(str
, start
, len
);
1087 result
[index
++] = str
;
1091 int len
= strlen(start
);
1092 if ( (mainExecutableDir
!= NULL
) && (strncmp(start
, "@loader_path/", 13) == 0) ) {
1093 int mainExecDirLen
= strlen(mainExecutableDir
);
1094 char* str
= new char[mainExecDirLen
+len
+1];
1095 strcpy(str
, mainExecutableDir
);
1096 strlcat(str
, &start
[13], mainExecDirLen
+len
+1);
1097 str
[mainExecDirLen
+len
-13] = '\0';
1098 result
[index
++] = str
;
1100 else if ( (mainExecutableDir
!= NULL
) && (strncmp(start
, "@executable_path/", 17) == 0) ) {
1101 int mainExecDirLen
= strlen(mainExecutableDir
);
1102 char* str
= new char[mainExecDirLen
+len
+1];
1103 strcpy(str
, mainExecutableDir
);
1104 strlcat(str
, &start
[17], mainExecDirLen
+len
+1);
1105 str
[mainExecDirLen
+len
-17] = '\0';
1106 result
[index
++] = str
;
1109 char* str
= new char[len
+1];
1111 result
[index
++] = str
;
1113 result
[index
] = NULL
;
1115 //dyld::log("parseColonList(%s)\n", list);
1116 //for(int i=0; result[i] != NULL; ++i)
1117 // dyld::log(" %s\n", result[i]);
1118 return (const char**)result
;
1121 static void appendParsedColonList(const char* list
, const char* mainExecutableDir
, const char* const ** storage
)
1123 const char** newlist
= parseColonList(list
, mainExecutableDir
);
1124 if ( *storage
== NULL
) {
1125 // first time, just set
1129 // need to append to existing list
1130 const char* const* existing
= *storage
;
1132 for(int i
=0; existing
[i
] != NULL
; ++i
)
1134 for(int i
=0; newlist
[i
] != NULL
; ++i
)
1136 const char** combinedList
= new const char*[count
+2];
1138 for(int i
=0; existing
[i
] != NULL
; ++i
)
1139 combinedList
[index
++] = existing
[i
];
1140 for(int i
=0; newlist
[i
] != NULL
; ++i
)
1141 combinedList
[index
++] = newlist
[i
];
1142 combinedList
[index
] = NULL
;
1144 *storage
= combinedList
;
1149 static void paths_expand_roots(const char **paths
, const char *key
, const char *val
)
1151 // assert(val != NULL);
1152 // assert(paths != NULL);
1154 size_t keyLen
= strlen(key
);
1155 for(int i
=0; paths
[i
] != NULL
; ++i
) {
1156 if ( strncmp(paths
[i
], key
, keyLen
) == 0 ) {
1157 char* newPath
= new char[strlen(val
) + (strlen(paths
[i
]) - keyLen
) + 1];
1158 strcpy(newPath
, val
);
1159 strcat(newPath
, &paths
[i
][keyLen
]);
1167 static void removePathWithPrefix(const char* paths
[], const char* prefix
)
1169 size_t prefixLen
= strlen(prefix
);
1172 for(i
= 0; paths
[i
] != NULL
; ++i
) {
1173 if ( strncmp(paths
[i
], prefix
, prefixLen
) == 0 )
1176 paths
[i
-skip
] = paths
[i
];
1178 paths
[i
-skip
] = NULL
;
1183 static void paths_dump(const char **paths
)
1185 // assert(paths != NULL);
1186 const char **strs
= paths
;
1187 while(*strs
!= NULL
)
1189 dyld::log("\"%s\"\n", *strs
);
1196 static void printOptions(const char* argv
[])
1199 while ( NULL
!= argv
[i
] ) {
1200 dyld::log("opt[%i] = \"%s\"\n", i
, argv
[i
]);
1205 static void printEnvironmentVariables(const char* envp
[])
1207 while ( NULL
!= *envp
) {
1208 dyld::log("%s\n", *envp
);
1213 void processDyldEnvironmentVariable(const char* key
, const char* value
, const char* mainExecutableDir
)
1215 if ( strcmp(key
, "DYLD_FRAMEWORK_PATH") == 0 ) {
1216 appendParsedColonList(value
, mainExecutableDir
, &sEnv
.DYLD_FRAMEWORK_PATH
);
1218 else if ( strcmp(key
, "DYLD_FALLBACK_FRAMEWORK_PATH") == 0 ) {
1219 appendParsedColonList(value
, mainExecutableDir
, &sEnv
.DYLD_FALLBACK_FRAMEWORK_PATH
);
1221 else if ( strcmp(key
, "DYLD_LIBRARY_PATH") == 0 ) {
1222 appendParsedColonList(value
, mainExecutableDir
, &sEnv
.DYLD_LIBRARY_PATH
);
1224 else if ( strcmp(key
, "DYLD_FALLBACK_LIBRARY_PATH") == 0 ) {
1225 appendParsedColonList(value
, mainExecutableDir
, &sEnv
.DYLD_FALLBACK_LIBRARY_PATH
);
1227 else if ( (strcmp(key
, "DYLD_ROOT_PATH") == 0) || (strcmp(key
, "DYLD_PATHS_ROOT") == 0) ) {
1228 if ( strcmp(value
, "/") != 0 ) {
1229 gLinkContext
.rootPaths
= parseColonList(value
, mainExecutableDir
);
1230 for (int i
=0; gLinkContext
.rootPaths
[i
] != NULL
; ++i
) {
1231 if ( gLinkContext
.rootPaths
[i
][0] != '/' ) {
1232 dyld::warn("DYLD_ROOT_PATH not used because it contains a non-absolute path\n");
1233 gLinkContext
.rootPaths
= NULL
;
1239 else if ( strcmp(key
, "DYLD_IMAGE_SUFFIX") == 0 ) {
1240 gLinkContext
.imageSuffix
= value
;
1242 else if ( strcmp(key
, "DYLD_INSERT_LIBRARIES") == 0 ) {
1243 sEnv
.DYLD_INSERT_LIBRARIES
= parseColonList(value
, NULL
);
1245 else if ( strcmp(key
, "DYLD_PRINT_OPTS") == 0 ) {
1246 sEnv
.DYLD_PRINT_OPTS
= true;
1248 else if ( strcmp(key
, "DYLD_PRINT_ENV") == 0 ) {
1249 sEnv
.DYLD_PRINT_ENV
= true;
1251 else if ( strcmp(key
, "DYLD_DISABLE_DOFS") == 0 ) {
1252 sEnv
.DYLD_DISABLE_DOFS
= true;
1254 else if ( strcmp(key
, "DYLD_DISABLE_PREFETCH") == 0 ) {
1255 gLinkContext
.preFetchDisabled
= true;
1257 else if ( strcmp(key
, "DYLD_PRINT_LIBRARIES") == 0 ) {
1258 sEnv
.DYLD_PRINT_LIBRARIES
= true;
1260 else if ( strcmp(key
, "DYLD_PRINT_LIBRARIES_POST_LAUNCH") == 0 ) {
1261 sEnv
.DYLD_PRINT_LIBRARIES_POST_LAUNCH
= true;
1263 else if ( strcmp(key
, "DYLD_BIND_AT_LAUNCH") == 0 ) {
1264 sEnv
.DYLD_BIND_AT_LAUNCH
= true;
1266 else if ( strcmp(key
, "DYLD_FORCE_FLAT_NAMESPACE") == 0 ) {
1267 gLinkContext
.bindFlat
= true;
1269 else if ( strcmp(key
, "DYLD_NEW_LOCAL_SHARED_REGIONS") == 0 ) {
1270 // ignore, no longer relevant but some scripts still set it
1272 else if ( strcmp(key
, "DYLD_NO_FIX_PREBINDING") == 0 ) {
1274 else if ( strcmp(key
, "DYLD_PREBIND_DEBUG") == 0 ) {
1275 gLinkContext
.verbosePrebinding
= true;
1277 else if ( strcmp(key
, "DYLD_PRINT_INITIALIZERS") == 0 ) {
1278 gLinkContext
.verboseInit
= true;
1280 else if ( strcmp(key
, "DYLD_PRINT_DOFS") == 0 ) {
1281 gLinkContext
.verboseDOF
= true;
1283 else if ( strcmp(key
, "DYLD_PRINT_STATISTICS") == 0 ) {
1284 sEnv
.DYLD_PRINT_STATISTICS
= true;
1286 else if ( strcmp(key
, "DYLD_PRINT_SEGMENTS") == 0 ) {
1287 gLinkContext
.verboseMapping
= true;
1289 else if ( strcmp(key
, "DYLD_PRINT_BINDINGS") == 0 ) {
1290 gLinkContext
.verboseBind
= true;
1292 else if ( strcmp(key
, "DYLD_PRINT_WEAK_BINDINGS") == 0 ) {
1293 gLinkContext
.verboseWeakBind
= true;
1295 else if ( strcmp(key
, "DYLD_PRINT_REBASINGS") == 0 ) {
1296 gLinkContext
.verboseRebase
= true;
1298 else if ( strcmp(key
, "DYLD_PRINT_APIS") == 0 ) {
1301 else if ( strcmp(key
, "DYLD_PRINT_WARNINGS") == 0 ) {
1302 gLinkContext
.verboseWarnings
= true;
1304 else if ( strcmp(key
, "DYLD_PRINT_RPATHS") == 0 ) {
1305 gLinkContext
.verboseRPaths
= true;
1307 else if ( strcmp(key
, "DYLD_PRINT_CS_NOTIFICATIONS") == 0 ) {
1308 sEnv
.DYLD_PRINT_CS_NOTIFICATIONS
= true;
1310 else if ( strcmp(key
, "DYLD_PRINT_INTERPOSING") == 0 ) {
1311 gLinkContext
.verboseInterposing
= true;
1313 else if ( strcmp(key
, "DYLD_SHARED_REGION") == 0 ) {
1314 if ( strcmp(value
, "private") == 0 ) {
1315 gLinkContext
.sharedRegionMode
= ImageLoader::kUsePrivateSharedRegion
;
1317 else if ( strcmp(value
, "avoid") == 0 ) {
1318 gLinkContext
.sharedRegionMode
= ImageLoader::kDontUseSharedRegion
;
1320 else if ( strcmp(value
, "use") == 0 ) {
1321 gLinkContext
.sharedRegionMode
= ImageLoader::kUseSharedRegion
;
1323 else if ( value
[0] == '\0' ) {
1324 gLinkContext
.sharedRegionMode
= ImageLoader::kUseSharedRegion
;
1327 dyld::warn("unknown option to DYLD_SHARED_REGION. Valid options are: use, private, avoid\n");
1330 #if DYLD_SHARED_CACHE_SUPPORT
1331 else if ( strcmp(key
, "DYLD_SHARED_CACHE_DIR") == 0 ) {
1332 sSharedCacheDir
= value
;
1334 else if ( strcmp(key
, "DYLD_SHARED_CACHE_DONT_VALIDATE") == 0 ) {
1335 sSharedCacheIgnoreInodeAndTimeStamp
= true;
1338 else if ( strcmp(key
, "DYLD_IGNORE_PREBINDING") == 0 ) {
1339 if ( strcmp(value
, "all") == 0 ) {
1340 gLinkContext
.prebindUsage
= ImageLoader::kUseNoPrebinding
;
1342 else if ( strcmp(value
, "app") == 0 ) {
1343 gLinkContext
.prebindUsage
= ImageLoader::kUseAllButAppPredbinding
;
1345 else if ( strcmp(value
, "nonsplit") == 0 ) {
1346 gLinkContext
.prebindUsage
= ImageLoader::kUseSplitSegPrebinding
;
1348 else if ( value
[0] == '\0' ) {
1349 gLinkContext
.prebindUsage
= ImageLoader::kUseSplitSegPrebinding
;
1352 dyld::warn("unknown option to DYLD_IGNORE_PREBINDING. Valid options are: all, app, nonsplit\n");
1355 #if SUPPORT_VERSIONED_PATHS
1356 else if ( strcmp(key
, "DYLD_VERSIONED_LIBRARY_PATH") == 0 ) {
1357 appendParsedColonList(value
, mainExecutableDir
, &sEnv
.DYLD_VERSIONED_LIBRARY_PATH
);
1359 else if ( strcmp(key
, "DYLD_VERSIONED_FRAMEWORK_PATH") == 0 ) {
1360 appendParsedColonList(value
, mainExecutableDir
, &sEnv
.DYLD_VERSIONED_FRAMEWORK_PATH
);
1364 dyld::warn("unknown environment variable: %s\n", key
);
1369 #if SUPPORT_LC_DYLD_ENVIRONMENT
1370 static void checkLoadCommandEnvironmentVariables()
1372 // <rdar://problem/8440934> Support augmenting dyld environment variables in load commands
1373 const uint32_t cmd_count
= sMainExecutableMachHeader
->ncmds
;
1374 const struct load_command
* const cmds
= (struct load_command
*)(((char*)sMainExecutableMachHeader
)+sizeof(macho_header
));
1375 const struct load_command
* cmd
= cmds
;
1376 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
1378 case LC_DYLD_ENVIRONMENT
:
1380 const struct dylinker_command
* envcmd
= (struct dylinker_command
*)cmd
;
1381 const char* keyEqualsValue
= (char*)envcmd
+ envcmd
->name
.offset
;
1382 char mainExecutableDir
[strlen(sExecPath
)];
1383 strcpy(mainExecutableDir
, sExecPath
);
1384 char* lastSlash
= strrchr(mainExecutableDir
, '/');
1385 if ( lastSlash
!= NULL
)
1386 lastSlash
[1] = '\0';
1387 // only process variables that start with DYLD_ and end in _PATH
1388 if ( (strncmp(keyEqualsValue
, "DYLD_", 5) == 0) ) {
1389 const char* equals
= strchr(keyEqualsValue
, '=');
1390 if ( equals
!= NULL
) {
1391 if ( strncmp(&equals
[-5], "_PATH", 5) == 0 ) {
1392 const char* value
= &equals
[1];
1393 const int keyLen
= equals
-keyEqualsValue
;
1395 strncpy(key
, keyEqualsValue
, keyLen
);
1397 //dyld::log("processing: %s\n", keyEqualsValue);
1398 //dyld::log("mainExecutableDir: %s\n", mainExecutableDir);
1399 processDyldEnvironmentVariable(key
, value
, mainExecutableDir
);
1406 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
1409 #endif // SUPPORT_LC_DYLD_ENVIRONMENT
1412 #if SUPPORT_VERSIONED_PATHS
1413 static void checkVersionedPaths()
1415 // search DYLD_VERSIONED_LIBRARY_PATH directories for dylibs and check if they are newer
1416 if ( sEnv
.DYLD_VERSIONED_LIBRARY_PATH
!= NULL
) {
1417 for(const char* const* lp
= sEnv
.DYLD_VERSIONED_LIBRARY_PATH
; *lp
!= NULL
; ++lp
) {
1418 checkDylibOverridesInDir(*lp
);
1422 // search DYLD_VERSIONED_FRAMEWORK_PATH directories for dylibs and check if they are newer
1423 if ( sEnv
.DYLD_VERSIONED_FRAMEWORK_PATH
!= NULL
) {
1424 for(const char* const* fp
= sEnv
.DYLD_VERSIONED_FRAMEWORK_PATH
; *fp
!= NULL
; ++fp
) {
1425 checkFrameworkOverridesInDir(*fp
);
1433 // For security, setuid programs ignore DYLD_* environment variables.
1434 // Additionally, the DYLD_* enviroment variables are removed
1435 // from the environment, so that any child processes don't see them.
1437 static void pruneEnvironmentVariables(const char* envp
[], const char*** applep
)
1439 // delete all DYLD_* and LD_LIBRARY_PATH environment variables
1440 int removedCount
= 0;
1441 const char** d
= envp
;
1442 for(const char** s
= envp
; *s
!= NULL
; s
++) {
1443 if ( (strncmp(*s
, "DYLD_", 5) != 0) && (strncmp(*s
, "LD_LIBRARY_PATH=", 16) != 0) ) {
1452 // slide apple parameters
1453 if ( removedCount
> 0 ) {
1456 *d
= d
[removedCount
];
1457 } while ( *d
++ != NULL
);
1458 for(int i
=0; i
< removedCount
; ++i
)
1462 // disable framework and library fallback paths for setuid binaries rdar://problem/4589305
1463 sEnv
.DYLD_FALLBACK_FRAMEWORK_PATH
= NULL
;
1464 sEnv
.DYLD_FALLBACK_LIBRARY_PATH
= NULL
;
1468 static void checkEnvironmentVariables(const char* envp
[], bool ignoreEnviron
)
1470 const char* home
= NULL
;
1472 for(p
= envp
; *p
!= NULL
; p
++) {
1473 const char* keyEqualsValue
= *p
;
1474 if ( strncmp(keyEqualsValue
, "DYLD_", 5) == 0 ) {
1475 const char* equals
= strchr(keyEqualsValue
, '=');
1476 if ( (equals
!= NULL
) && !ignoreEnviron
) {
1477 const char* value
= &equals
[1];
1478 const int keyLen
= equals
-keyEqualsValue
;
1480 strncpy(key
, keyEqualsValue
, keyLen
);
1482 processDyldEnvironmentVariable(key
, value
, NULL
);
1485 else if ( strncmp(keyEqualsValue
, "HOME=", 5) == 0 ) {
1486 home
= &keyEqualsValue
[5];
1488 else if ( strncmp(keyEqualsValue
, "LD_LIBRARY_PATH=", 16) == 0 ) {
1489 const char* path
= &keyEqualsValue
[16];
1490 sEnv
.LD_LIBRARY_PATH
= parseColonList(path
, NULL
);
1494 #if SUPPORT_LC_DYLD_ENVIRONMENT
1495 checkLoadCommandEnvironmentVariables();
1496 #endif // SUPPORT_LC_DYLD_ENVIRONMENT
1498 // default value for DYLD_FALLBACK_FRAMEWORK_PATH, if not set in environment
1499 if ( sEnv
.DYLD_FALLBACK_FRAMEWORK_PATH
== NULL
) {
1500 const char** paths
= sFrameworkFallbackPaths
;
1502 removePathWithPrefix(paths
, "$HOME");
1504 paths_expand_roots(paths
, "$HOME", home
);
1505 sEnv
.DYLD_FALLBACK_FRAMEWORK_PATH
= paths
;
1508 // default value for DYLD_FALLBACK_LIBRARY_PATH, if not set in environment
1509 if ( sEnv
.DYLD_FALLBACK_LIBRARY_PATH
== NULL
) {
1510 const char** paths
= sLibraryFallbackPaths
;
1512 removePathWithPrefix(paths
, "$HOME");
1514 paths_expand_roots(paths
, "$HOME", home
);
1515 sEnv
.DYLD_FALLBACK_LIBRARY_PATH
= paths
;
1518 #if SUPPORT_VERSIONED_PATHS
1519 checkVersionedPaths();
1524 static void getHostInfo()
1526 #if CPU_SUBTYPES_SUPPORTED
1528 sHostCPU
= CPU_TYPE_ARM
;
1529 sHostCPUsubtype
= CPU_SUBTYPE_ARM_V7
;
1530 #elif __ARM_ARCH_6K__
1531 sHostCPU
= CPU_TYPE_ARM
;
1532 sHostCPUsubtype
= CPU_SUBTYPE_ARM_V6
;
1534 struct host_basic_info info
;
1535 mach_msg_type_number_t count
= HOST_BASIC_INFO_COUNT
;
1536 mach_port_t hostPort
= mach_host_self();
1537 kern_return_t result
= host_info(hostPort
, HOST_BASIC_INFO
, (host_info_t
)&info
, &count
);
1538 if ( result
!= KERN_SUCCESS
)
1539 throw "host_info() failed";
1540 sHostCPU
= info
.cpu_type
;
1541 sHostCPUsubtype
= info
.cpu_subtype
;
1546 static void checkSharedRegionDisable()
1548 #if __MAC_OS_X_VERSION_MIN_REQUIRED
1549 // if main executable has segments that overlap the shared region,
1550 // then disable using the shared region
1551 if ( sMainExecutable
->overlapsWithAddressRange((void*)(uintptr_t)SHARED_REGION_BASE
, (void*)(uintptr_t)(SHARED_REGION_BASE
+ SHARED_REGION_SIZE
)) ) {
1552 gLinkContext
.sharedRegionMode
= ImageLoader::kDontUseSharedRegion
;
1553 if ( gLinkContext
.verboseMapping
)
1554 dyld::warn("disabling shared region because main executable overlaps\n");
1557 // iPhoneOS cannot run without shared region
1560 bool validImage(const ImageLoader
* possibleImage
)
1562 const unsigned int imageCount
= sAllImages
.size();
1563 for(unsigned int i
=0; i
< imageCount
; ++i
) {
1564 if ( possibleImage
== sAllImages
[i
] ) {
1571 uint32_t getImageCount()
1573 return sAllImages
.size();
1576 ImageLoader
* getIndexedImage(unsigned int index
)
1578 if ( index
< sAllImages
.size() )
1579 return sAllImages
[index
];
1583 ImageLoader
* findImageByMachHeader(const struct mach_header
* target
)
1585 return findMappedRange((uintptr_t)target
);
1589 ImageLoader
* findImageContainingAddress(const void* addr
)
1591 return findMappedRange((uintptr_t)addr
);
1595 ImageLoader
* findImageContainingSymbol(const void* symbol
)
1597 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
1598 ImageLoader
* anImage
= *it
;
1599 if ( anImage
->containsSymbol(symbol
) )
1607 void forEachImageDo( void (*callback
)(ImageLoader
*, void* userData
), void* userData
)
1609 const unsigned int imageCount
= sAllImages
.size();
1610 for(unsigned int i
=0; i
< imageCount
; ++i
) {
1611 ImageLoader
* anImage
= sAllImages
[i
];
1612 (*callback
)(anImage
, userData
);
1616 ImageLoader
* findLoadedImage(const struct stat
& stat_buf
)
1618 const unsigned int imageCount
= sAllImages
.size();
1619 for(unsigned int i
=0; i
< imageCount
; ++i
){
1620 ImageLoader
* anImage
= sAllImages
[i
];
1621 if ( anImage
->statMatch(stat_buf
) )
1627 // based on ANSI-C strstr()
1628 static const char* strrstr(const char* str
, const char* sub
)
1630 const int sublen
= strlen(sub
);
1631 for(const char* p
= &str
[strlen(str
)]; p
!= str
; --p
) {
1632 if ( strncmp(p
, sub
, sublen
) == 0 )
1640 // Find framework path
1642 // /path/foo.framework/foo => foo.framework/foo
1643 // /path/foo.framework/Versions/A/foo => foo.framework/Versions/A/foo
1644 // /path/foo.framework/Frameworks/bar.framework/bar => bar.framework/bar
1645 // /path/foo.framework/Libraries/bar.dylb => NULL
1646 // /path/foo.framework/bar => NULL
1648 // Returns NULL if not a framework path
1650 static const char* getFrameworkPartialPath(const char* path
)
1652 const char* dirDot
= strrstr(path
, ".framework/");
1653 if ( dirDot
!= NULL
) {
1654 const char* dirStart
= dirDot
;
1655 for ( ; dirStart
>= path
; --dirStart
) {
1656 if ( (*dirStart
== '/') || (dirStart
== path
) ) {
1657 const char* frameworkStart
= &dirStart
[1];
1658 if ( dirStart
== path
)
1660 int len
= dirDot
- frameworkStart
;
1661 char framework
[len
+1];
1662 strncpy(framework
, frameworkStart
, len
);
1663 framework
[len
] = '\0';
1664 const char* leaf
= strrchr(path
, '/');
1665 if ( leaf
!= NULL
) {
1666 if ( strcmp(framework
, &leaf
[1]) == 0 ) {
1667 return frameworkStart
;
1669 if ( gLinkContext
.imageSuffix
!= NULL
) {
1670 // some debug frameworks have install names that end in _debug
1671 if ( strncmp(framework
, &leaf
[1], len
) == 0 ) {
1672 if ( strcmp( gLinkContext
.imageSuffix
, &leaf
[len
+1]) == 0 )
1673 return frameworkStart
;
1684 static const char* getLibraryLeafName(const char* path
)
1686 const char* start
= strrchr(path
, '/');
1687 if ( start
!= NULL
)
1694 // only for architectures that use cpu-sub-types
1695 #if CPU_SUBTYPES_SUPPORTED
1697 const cpu_subtype_t CPU_SUBTYPE_END_OF_LIST
= -1;
1701 // A fat file may contain multiple sub-images for the same CPU type.
1702 // In that case, dyld picks which sub-image to use by scanning a table
1703 // of preferred cpu-sub-types for the running cpu.
1705 // There is one row in the table for each cpu-sub-type on which dyld might run.
1706 // The first entry in a row is that cpu-sub-type. It is followed by all
1707 // cpu-sub-types that can run on that cpu, if preferred order. Each row ends with
1708 // a "SUBTYPE_ALL" (to denote that images written to run on any cpu-sub-type are usable),
1709 // followed by one or more CPU_SUBTYPE_END_OF_LIST to pad out this row.
1715 // 32-bit PowerPC sub-type lists
1717 const int kPPC_RowCount
= 4;
1718 static const cpu_subtype_t kPPC32
[kPPC_RowCount
][6] = {
1719 // G5 can run any code
1720 { 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
},
1722 // G4 can run all but G5 code
1723 { 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
},
1724 { 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
},
1726 // G3 cannot run G4 or G5 code
1727 { 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
}
1734 // ARM sub-type lists
1736 const int kARM_RowCount
= 5;
1737 static const cpu_subtype_t kARM
[kARM_RowCount
][6] = {
1738 // armv7 can run: v7, v6, v5, and v4
1739 { 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
},
1741 // armv6 can run: v6, v5, and v4
1742 { 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
},
1744 // xscale can run: xscale, v5, and v4
1745 { 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
},
1747 // armv5 can run: v5 and v4
1748 { 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
},
1750 // armv4 can run: v4
1751 { 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
},
1756 // scan the tables above to find the cpu-sub-type-list for this machine
1757 static const cpu_subtype_t
* findCPUSubtypeList(cpu_type_t cpu
, cpu_subtype_t subtype
)
1761 case CPU_TYPE_POWERPC
:
1762 for (int i
=0; i
< kPPC_RowCount
; ++i
) {
1763 if ( kPPC32
[i
][0] == subtype
)
1770 for (int i
=0; i
< kARM_RowCount
; ++i
) {
1771 if ( kARM
[i
][0] == subtype
)
1783 // scan fat table-of-contents for best most preferred subtype
1784 static bool fatFindBestFromOrderedList(cpu_type_t cpu
, const cpu_subtype_t list
[], const fat_header
* fh
, uint64_t* offset
, uint64_t* len
)
1786 const fat_arch
* const archs
= (fat_arch
*)(((char*)fh
)+sizeof(fat_header
));
1787 for (uint32_t subTypeIndex
=0; list
[subTypeIndex
] != CPU_SUBTYPE_END_OF_LIST
; ++subTypeIndex
) {
1788 for(uint32_t fatIndex
=0; fatIndex
< OSSwapBigToHostInt32(fh
->nfat_arch
); ++fatIndex
) {
1789 if ( ((cpu_type_t
)OSSwapBigToHostInt32(archs
[fatIndex
].cputype
) == cpu
)
1790 && (list
[subTypeIndex
] == (cpu_subtype_t
)OSSwapBigToHostInt32(archs
[fatIndex
].cpusubtype
)) ) {
1791 *offset
= OSSwapBigToHostInt32(archs
[fatIndex
].offset
);
1792 *len
= OSSwapBigToHostInt32(archs
[fatIndex
].size
);
1800 // scan fat table-of-contents for exact match of cpu and cpu-sub-type
1801 static bool fatFindExactMatch(cpu_type_t cpu
, cpu_subtype_t subtype
, const fat_header
* fh
, uint64_t* offset
, uint64_t* len
)
1803 const fat_arch
* archs
= (fat_arch
*)(((char*)fh
)+sizeof(fat_header
));
1804 for(uint32_t i
=0; i
< OSSwapBigToHostInt32(fh
->nfat_arch
); ++i
) {
1805 if ( ((cpu_type_t
)OSSwapBigToHostInt32(archs
[i
].cputype
) == cpu
)
1806 && ((cpu_subtype_t
)OSSwapBigToHostInt32(archs
[i
].cpusubtype
) == subtype
) ) {
1807 *offset
= OSSwapBigToHostInt32(archs
[i
].offset
);
1808 *len
= OSSwapBigToHostInt32(archs
[i
].size
);
1815 // scan fat table-of-contents for image with matching cpu-type and runs-on-all-sub-types
1816 static bool fatFindRunsOnAllCPUs(cpu_type_t cpu
, const fat_header
* fh
, uint64_t* offset
, uint64_t* len
)
1818 const fat_arch
* archs
= (fat_arch
*)(((char*)fh
)+sizeof(fat_header
));
1819 for(uint32_t i
=0; i
< OSSwapBigToHostInt32(fh
->nfat_arch
); ++i
) {
1820 if ( (cpu_type_t
)OSSwapBigToHostInt32(archs
[i
].cputype
) == cpu
) {
1823 case CPU_TYPE_POWERPC
:
1824 if ( (cpu_subtype_t
)OSSwapBigToHostInt32(archs
[i
].cpusubtype
) == CPU_SUBTYPE_POWERPC_ALL
) {
1825 *offset
= OSSwapBigToHostInt32(archs
[i
].offset
);
1826 *len
= OSSwapBigToHostInt32(archs
[i
].size
);
1833 if ( (cpu_subtype_t
)OSSwapBigToHostInt32(archs
[i
].cpusubtype
) == CPU_SUBTYPE_ARM_ALL
) {
1834 *offset
= OSSwapBigToHostInt32(archs
[i
].offset
);
1835 *len
= OSSwapBigToHostInt32(archs
[i
].size
);
1846 #endif // CPU_SUBTYPES_SUPPORTED
1849 // A fat file may contain multiple sub-images for the same cpu-type,
1850 // each optimized for a different cpu-sub-type (e.g G3 or G5).
1851 // This routine picks the optimal sub-image.
1853 static bool fatFindBest(const fat_header
* fh
, uint64_t* offset
, uint64_t* len
)
1855 #if CPU_SUBTYPES_SUPPORTED
1856 // assume all dylibs loaded must have same cpu type as main executable
1857 const cpu_type_t cpu
= sMainExecutableMachHeader
->cputype
;
1859 // We only know the subtype to use if the main executable cpu type matches the host
1860 if ( (cpu
& CPU_TYPE_MASK
) == sHostCPU
) {
1861 // get preference ordered list of subtypes
1862 const cpu_subtype_t
* subTypePreferenceList
= findCPUSubtypeList(cpu
, sHostCPUsubtype
);
1864 // use ordered list to find best sub-image in fat file
1865 if ( subTypePreferenceList
!= NULL
)
1866 return fatFindBestFromOrderedList(cpu
, subTypePreferenceList
, fh
, offset
, len
);
1868 // if running cpu is not in list, try for an exact match
1869 if ( fatFindExactMatch(cpu
, sHostCPUsubtype
, fh
, offset
, len
) )
1873 // running on an uknown cpu, can only load generic code
1874 return fatFindRunsOnAllCPUs(cpu
, fh
, offset
, len
);
1876 // just find first slice with matching architecture
1877 const fat_arch
* archs
= (fat_arch
*)(((char*)fh
)+sizeof(fat_header
));
1878 for(uint32_t i
=0; i
< OSSwapBigToHostInt32(fh
->nfat_arch
); ++i
) {
1879 if ( (cpu_type_t
)OSSwapBigToHostInt32(archs
[i
].cputype
) == sMainExecutableMachHeader
->cputype
) {
1880 *offset
= OSSwapBigToHostInt32(archs
[i
].offset
);
1881 *len
= OSSwapBigToHostInt32(archs
[i
].size
);
1892 // This is used to validate if a non-fat (aka thin or raw) mach-o file can be used
1893 // on the current processor. //
1894 bool isCompatibleMachO(const uint8_t* firstPage
, const char* path
)
1896 #if CPU_SUBTYPES_SUPPORTED
1897 // It is deemed compatible if any of the following are true:
1898 // 1) mach_header subtype is in list of compatible subtypes for running processor
1899 // 2) mach_header subtype is same as running processor subtype
1900 // 3) mach_header subtype runs on all processor variants
1901 const mach_header
* mh
= (mach_header
*)firstPage
;
1902 if ( mh
->magic
== sMainExecutableMachHeader
->magic
) {
1903 if ( mh
->cputype
== sMainExecutableMachHeader
->cputype
) {
1904 if ( (mh
->cputype
& CPU_TYPE_MASK
) == sHostCPU
) {
1905 // get preference ordered list of subtypes that this machine can use
1906 const cpu_subtype_t
* subTypePreferenceList
= findCPUSubtypeList(mh
->cputype
, sHostCPUsubtype
);
1907 if ( subTypePreferenceList
!= NULL
) {
1908 // if image's subtype is in the list, it is compatible
1909 for (const cpu_subtype_t
* p
= subTypePreferenceList
; *p
!= CPU_SUBTYPE_END_OF_LIST
; ++p
) {
1910 if ( *p
== mh
->cpusubtype
)
1913 // have list and not in list, so not compatible
1914 throwf("incompatible cpu-subtype: 0x%08X in %s", mh
->cpusubtype
, path
);
1916 // unknown cpu sub-type, but if exact match for current subtype then ok to use
1917 if ( mh
->cpusubtype
== sHostCPUsubtype
)
1921 // cpu type has no ordered list of subtypes
1922 switch (mh
->cputype
) {
1923 case CPU_TYPE_POWERPC
:
1924 // allow _ALL to be used by any client
1925 if ( mh
->cpusubtype
== CPU_SUBTYPE_POWERPC_ALL
)
1928 case CPU_TYPE_POWERPC64
:
1930 case CPU_TYPE_X86_64
:
1931 // subtypes are not used or these architectures
1937 // For architectures that don't support cpu-sub-types
1938 // this just check the cpu type.
1939 const mach_header
* mh
= (mach_header
*)firstPage
;
1940 if ( mh
->magic
== sMainExecutableMachHeader
->magic
) {
1941 if ( mh
->cputype
== sMainExecutableMachHeader
->cputype
) {
1952 // The kernel maps in main executable before dyld gets control. We need to
1953 // make an ImageLoader* for the already mapped in main executable.
1954 static ImageLoader
* instantiateFromLoadedImage(const macho_header
* mh
, uintptr_t slide
, const char* path
)
1956 // try mach-o loader
1957 if ( isCompatibleMachO((const uint8_t*)mh
, path
) ) {
1958 ImageLoader
* image
= ImageLoaderMachO::instantiateMainExecutable(mh
, slide
, path
, gLinkContext
);
1963 throw "main executable not a known format";
1967 #if DYLD_SHARED_CACHE_SUPPORT
1968 static bool findInSharedCacheImage(const char* path
, const struct stat
* stat_buf
, const macho_header
** mh
, const char** pathInCache
, long* slide
)
1970 if ( sSharedCache
!= NULL
) {
1971 #if __MAC_OS_X_VERSION_MIN_REQUIRED
1972 // Mac OS X always requires inode/mtime to valid cache
1973 // if stat() not done yet, do it now
1975 if ( stat_buf
== NULL
) {
1976 if ( stat(path
, &statb
) == -1 )
1981 // walk shared cache to see if there is a cached image that matches the inode/mtime/path desired
1982 const dyld_cache_image_info
* const start
= (dyld_cache_image_info
*)((uint8_t*)sSharedCache
+ sSharedCache
->imagesOffset
);
1983 const dyld_cache_image_info
* const end
= &start
[sSharedCache
->imagesCount
];
1984 for( const dyld_cache_image_info
* p
= start
; p
!= end
; ++p
) {
1985 #if __IPHONE_OS_VERSION_MIN_REQUIRED
1987 const char* aPath
= (char*)sSharedCache
+ p
->pathFileOffset
;
1988 if ( strcmp(path
, aPath
) == 0 ) {
1989 // found image in cache
1990 *mh
= (macho_header
*)(p
->address
+sSharedCacheSlide
);
1991 *pathInCache
= aPath
;
1992 *slide
= sSharedCacheSlide
;
1995 #elif __MAC_OS_X_VERSION_MIN_REQUIRED
1996 // check mtime and inode first because it is fast
1997 if ( sSharedCacheIgnoreInodeAndTimeStamp
1998 || ( ((time_t)p
->modTime
== stat_buf
->st_mtime
) && ((ino_t
)p
->inode
== stat_buf
->st_ino
) ) ) {
1999 // mod-time and inode match an image in the shared cache, now check path
2000 const char* aPath
= (char*)sSharedCache
+ p
->pathFileOffset
;
2001 bool cacheHit
= (strcmp(path
, aPath
) == 0);
2003 // path does not match install name of dylib in cache, but inode and mtime does match
2004 // perhaps path is a symlink to the cached dylib
2005 struct stat pathInCacheStatBuf
;
2006 if ( stat(aPath
, &pathInCacheStatBuf
) != -1 )
2007 cacheHit
= ( (pathInCacheStatBuf
.st_dev
== stat_buf
->st_dev
) && (pathInCacheStatBuf
.st_ino
== stat_buf
->st_ino
) );
2010 // found image in cache, return info
2011 *mh
= (macho_header
*)(p
->address
+sSharedCacheSlide
);
2012 //dyld::log("findInSharedCacheImage(), mh=%p, p->address=0x%0llX, slid=0x%0lX, path=%p\n",
2013 // *mh, p->address, sSharedCacheSlide, aPath);
2014 *pathInCache
= aPath
;
2015 *slide
= sSharedCacheSlide
;
2025 bool inSharedCache(const char* path
)
2027 const macho_header
* mhInCache
;
2028 const char* pathInCache
;
2030 return findInSharedCacheImage(path
, NULL
, &mhInCache
, &pathInCache
, &slide
);
2035 static ImageLoader
* checkandAddImage(ImageLoader
* image
, const LoadContext
& context
)
2037 // now sanity check that this loaded image does not have the same install path as any existing image
2038 const char* loadedImageInstallPath
= image
->getInstallPath();
2039 if ( image
->isDylib() && (loadedImageInstallPath
!= NULL
) && (loadedImageInstallPath
[0] == '/') ) {
2040 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
2041 ImageLoader
* anImage
= *it
;
2042 const char* installPath
= anImage
->getInstallPath();
2043 if ( installPath
!= NULL
) {
2044 if ( strcmp(loadedImageInstallPath
, installPath
) == 0 ) {
2045 //dyld::log("duplicate(%s) => %p\n", installPath, anImage);
2047 ImageLoader::deleteImage(image
);
2054 // some API's restrict what they can load
2055 if ( context
.mustBeBundle
&& !image
->isBundle() )
2056 throw "not a bundle";
2057 if ( context
.mustBeDylib
&& !image
->isDylib() )
2058 throw "not a dylib";
2060 // regular main executables cannot be loaded
2061 if ( image
->isExecutable() ) {
2062 if ( !context
.canBePIE
|| !image
->isPositionIndependentExecutable() )
2063 throw "can't load a main executable";
2066 // don't add bundles to global list, they can be loaded but not linked. When linked it will be added to list
2067 if ( ! image
->isBundle() )
2073 // map in file and instantiate an ImageLoader
2074 static ImageLoader
* loadPhase6(int fd
, const struct stat
& stat_buf
, const char* path
, const LoadContext
& context
)
2076 //dyld::log("%s(%s)\n", __func__ , path);
2077 uint64_t fileOffset
= 0;
2078 uint64_t fileLength
= stat_buf
.st_size
;
2080 // validate it is a file (not directory)
2081 if ( (stat_buf
.st_mode
& S_IFMT
) != S_IFREG
)
2084 uint8_t firstPage
[4096];
2085 bool shortPage
= false;
2087 // min mach-o file is 4K
2088 if ( fileLength
< 4096 ) {
2089 if ( pread(fd
, firstPage
, fileLength
, 0) != (ssize_t
)fileLength
)
2090 throwf("pread of short file failed: %d", errno
);
2094 if ( pread(fd
, firstPage
, 4096,0) != 4096 )
2095 throwf("pread of first 4K failed: %d", errno
);
2098 // if fat wrapper, find usable sub-file
2099 const fat_header
* fileStartAsFat
= (fat_header
*)firstPage
;
2100 if ( fileStartAsFat
->magic
== OSSwapBigToHostInt32(FAT_MAGIC
) ) {
2101 if ( fatFindBest(fileStartAsFat
, &fileOffset
, &fileLength
) ) {
2102 if ( (fileOffset
+fileLength
) > (uint64_t)(stat_buf
.st_size
) )
2103 throwf("truncated fat file. file length=%llu, but needed slice goes to %llu", stat_buf
.st_size
, fileOffset
+fileLength
);
2104 if (pread(fd
, firstPage
, 4096, fileOffset
) != 4096)
2105 throwf("pread of fat file failed: %d", errno
);
2108 throw "no matching architecture in universal wrapper";
2112 // try mach-o loader
2114 throw "file too short";
2115 if ( isCompatibleMachO(firstPage
, path
) ) {
2117 // only MH_BUNDLE, MH_DYLIB, and some MH_EXECUTE can be dynamically loaded
2118 switch ( ((mach_header
*)firstPage
)->filetype
) {
2124 throw "mach-o, but wrong filetype";
2127 // instantiate an image
2128 ImageLoader
* image
= ImageLoaderMachO::instantiateFromFile(path
, fd
, firstPage
, fileOffset
, fileLength
, stat_buf
, gLinkContext
);
2131 return checkandAddImage(image
, context
);
2134 // try other file formats here...
2137 // throw error about what was found
2138 switch (*(uint32_t*)firstPage
) {
2143 throw "mach-o, but wrong architecture";
2145 throwf("unknown file type, first eight bytes: 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X",
2146 firstPage
[0], firstPage
[1], firstPage
[2], firstPage
[3], firstPage
[4], firstPage
[5], firstPage
[6],firstPage
[7]);
2151 static ImageLoader
* loadPhase5open(const char* path
, const LoadContext
& context
, const struct stat
& stat_buf
, std::vector
<const char*>* exceptions
)
2153 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
2155 // open file (automagically closed when this function exits)
2156 FileOpener
file(path
);
2158 // just return NULL if file not found, but record any other errors
2159 if ( file
.getFileDescriptor() == -1 ) {
2161 if ( err
!= ENOENT
) {
2162 const char* newMsg
= dyld::mkstringf("%s: open() failed with errno=%d", path
, err
);
2163 exceptions
->push_back(newMsg
);
2169 return loadPhase6(file
.getFileDescriptor(), stat_buf
, path
, context
);
2171 catch (const char* msg
) {
2172 const char* newMsg
= dyld::mkstringf("%s: %s", path
, msg
);
2173 exceptions
->push_back(newMsg
);
2180 #if __MAC_OS_X_VERSION_MIN_REQUIRED
2181 static ImageLoader
* loadPhase5load(const char* path
, const char* orgPath
, const LoadContext
& context
, std::vector
<const char*>* exceptions
)
2183 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
2184 ImageLoader
* image
= NULL
;
2186 // just return NULL if file not found, but record any other errors
2187 struct stat stat_buf
;
2188 if ( stat(path
, &stat_buf
) == -1 ) {
2190 if ( err
!= ENOENT
) {
2191 exceptions
->push_back(dyld::mkstringf("%s: stat() failed with errno=%d", path
, err
));
2196 // in case image was renamed or found via symlinks, check for inode match
2197 image
= findLoadedImage(stat_buf
);
2198 if ( image
!= NULL
)
2201 // do nothing if not already loaded and if RTLD_NOLOAD or NSADDIMAGE_OPTION_RETURN_ONLY_IF_LOADED
2202 if ( context
.dontLoad
)
2205 #if DYLD_SHARED_CACHE_SUPPORT
2206 // see if this image is in shared cache
2207 const macho_header
* mhInCache
;
2208 const char* pathInCache
;
2210 if ( findInSharedCacheImage(path
, &stat_buf
, &mhInCache
, &pathInCache
, &slideInCache
) ) {
2211 image
= ImageLoaderMachO::instantiateFromCache(mhInCache
, pathInCache
, slideInCache
, stat_buf
, gLinkContext
);
2212 return checkandAddImage(image
, context
);
2215 // file exists and is not in dyld shared cache, so open it
2216 return loadPhase5open(path
, context
, stat_buf
, exceptions
);
2218 #endif // __MAC_OS_X_VERSION_MIN_REQUIRED
2222 #if __IPHONE_OS_VERSION_MIN_REQUIRED
2223 static ImageLoader
* loadPhase5stat(const char* path
, const LoadContext
& context
, struct stat
* stat_buf
,
2224 int* statErrNo
, bool* imageFound
, std::vector
<const char*>* exceptions
)
2226 ImageLoader
* image
= NULL
;
2227 *imageFound
= false;
2228 if ( stat(path
, stat_buf
) == 0 ) {
2229 // in case image was renamed or found via symlinks, check for inode match
2230 image
= findLoadedImage(*stat_buf
);
2231 if ( image
!= NULL
) {
2235 // do nothing if not already loaded and if RTLD_NOLOAD
2236 if ( context
.dontLoad
) {
2240 image
= loadPhase5open(path
, context
, *stat_buf
, exceptions
);
2241 if ( image
!= NULL
) {
2253 static ImageLoader
* loadPhase5load(const char* path
, const char* orgPath
, const LoadContext
& context
, std::vector
<const char*>* exceptions
)
2255 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
2256 struct stat stat_buf
;
2260 #if DYLD_SHARED_CACHE_SUPPORT
2261 if ( sDylibsOverrideCache
) {
2262 // flag is set that allows installed framework roots to override dyld shared cache
2263 image
= loadPhase5stat(path
, context
, &stat_buf
, &statErrNo
, &imageFound
, exceptions
);
2267 // see if this image is in shared cache
2268 const macho_header
* mhInCache
;
2269 const char* pathInCache
;
2271 if ( findInSharedCacheImage(path
, NULL
, &mhInCache
, &pathInCache
, &slideInCache
) ) {
2272 // see if this image in the cache was already loaded via a different path
2273 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); ++it
) {
2274 ImageLoader
* anImage
= *it
;
2275 if ( anImage
->machHeader() == mhInCache
)
2278 // do nothing if not already loaded and if RTLD_NOLOAD
2279 if ( context
.dontLoad
)
2281 // nope, so instantiate a new image from dyld shared cache
2282 // <rdar://problem/7014995> zero out stat buffer so mtime, etc are zero for items from the shared cache
2283 bzero(&stat_buf
, sizeof(stat_buf
));
2284 image
= ImageLoaderMachO::instantiateFromCache(mhInCache
, pathInCache
, slideInCache
, stat_buf
, gLinkContext
);
2285 return checkandAddImage(image
, context
);
2288 if ( !sDylibsOverrideCache
) {
2289 // flag is not set, and not in cache to try opening it
2290 image
= loadPhase5stat(path
, context
, &stat_buf
, &statErrNo
, &imageFound
, exceptions
);
2295 image
= loadPhase5stat(path
, context
, &stat_buf
, &statErrNo
, &imageFound
, exceptions
);
2299 // just return NULL if file not found, but record any other errors
2300 if ( statErrNo
!= ENOENT
) {
2301 exceptions
->push_back(dyld::mkstringf("%s: stat() failed with errno=%d", path
, statErrNo
));
2305 #endif // __IPHONE_OS_VERSION_MIN_REQUIRED
2308 // look for path match with existing loaded images
2309 static ImageLoader
* loadPhase5check(const char* path
, const char* orgPath
, const LoadContext
& context
)
2311 //dyld::log("%s(%s, %s)\n", __func__ , path, orgPath);
2312 // search path against load-path and install-path of all already loaded images
2313 uint32_t hash
= ImageLoader::hash(path
);
2314 //dyld::log("check() hash=%d, path=%s\n", hash, path);
2315 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
2316 ImageLoader
* anImage
= *it
;
2317 // check hash first to cut down on strcmp calls
2318 //dyld::log(" check() hash=%d, path=%s\n", anImage->getPathHash(), anImage->getPath());
2319 if ( anImage
->getPathHash() == hash
) {
2320 if ( strcmp(path
, anImage
->getPath()) == 0 ) {
2321 // if we are looking for a dylib don't return something else
2322 if ( !context
.mustBeDylib
|| anImage
->isDylib() )
2326 if ( context
.matchByInstallName
|| anImage
->matchInstallPath() ) {
2327 const char* installPath
= anImage
->getInstallPath();
2328 if ( installPath
!= NULL
) {
2329 if ( strcmp(path
, installPath
) == 0 ) {
2330 // if we are looking for a dylib don't return something else
2331 if ( !context
.mustBeDylib
|| anImage
->isDylib() )
2336 // an install name starting with @rpath should match by install name, not just real path
2337 if ( (orgPath
[0] == '@') && (strncmp(orgPath
, "@rpath/", 7) == 0) ) {
2338 const char* installPath
= anImage
->getInstallPath();
2339 if ( installPath
!= NULL
) {
2340 if ( !context
.mustBeDylib
|| anImage
->isDylib() ) {
2341 if ( strcmp(orgPath
, installPath
) == 0 )
2348 //dyld::log("%s(%s) => NULL\n", __func__, path);
2353 // open or check existing
2354 static ImageLoader
* loadPhase5(const char* path
, const char* orgPath
, const LoadContext
& context
, std::vector
<const char*>* exceptions
)
2356 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
2358 // check for specific dylib overrides
2359 for (std::vector
<DylibOverride
>::iterator it
= sDylibOverrides
.begin(); it
!= sDylibOverrides
.end(); ++it
) {
2360 if ( strcmp(it
->installName
, path
) == 0 ) {
2361 path
= it
->override
;
2366 if ( exceptions
!= NULL
)
2367 return loadPhase5load(path
, orgPath
, context
, exceptions
);
2369 return loadPhase5check(path
, orgPath
, context
);
2372 // try with and without image suffix
2373 static ImageLoader
* loadPhase4(const char* path
, const char* orgPath
, const LoadContext
& context
, std::vector
<const char*>* exceptions
)
2375 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
2376 ImageLoader
* image
= NULL
;
2377 if ( gLinkContext
.imageSuffix
!= NULL
) {
2378 char pathWithSuffix
[strlen(path
)+strlen( gLinkContext
.imageSuffix
)+2];
2379 ImageLoader::addSuffix(path
, gLinkContext
.imageSuffix
, pathWithSuffix
);
2380 image
= loadPhase5(pathWithSuffix
, orgPath
, context
, exceptions
);
2382 if ( image
== NULL
)
2383 image
= loadPhase5(path
, orgPath
, context
, exceptions
);
2387 static ImageLoader
* loadPhase2(const char* path
, const char* orgPath
, const LoadContext
& context
,
2388 const char* const frameworkPaths
[], const char* const libraryPaths
[],
2389 std::vector
<const char*>* exceptions
); // forward reference
2392 // expand @ variables
2393 static ImageLoader
* loadPhase3(const char* path
, const char* orgPath
, const LoadContext
& context
, std::vector
<const char*>* exceptions
)
2395 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
2396 ImageLoader
* image
= NULL
;
2397 if ( strncmp(path
, "@executable_path/", 17) == 0 ) {
2398 // executable_path cannot be in used in any binary in a setuid process rdar://problem/4589305
2399 if ( sProcessIsRestricted
)
2400 throwf("unsafe use of @executable_path in %s with restricted binary", context
.origin
);
2401 // handle @executable_path path prefix
2402 const char* executablePath
= sExecPath
;
2403 char newPath
[strlen(executablePath
) + strlen(path
)];
2404 strcpy(newPath
, executablePath
);
2405 char* addPoint
= strrchr(newPath
,'/');
2406 if ( addPoint
!= NULL
)
2407 strcpy(&addPoint
[1], &path
[17]);
2409 strcpy(newPath
, &path
[17]);
2410 image
= loadPhase4(newPath
, orgPath
, context
, exceptions
);
2411 if ( image
!= NULL
)
2414 // perhaps main executable path is a sym link, find realpath and retry
2415 char resolvedPath
[PATH_MAX
];
2416 if ( realpath(sExecPath
, resolvedPath
) != NULL
) {
2417 char newRealPath
[strlen(resolvedPath
) + strlen(path
)];
2418 strcpy(newRealPath
, resolvedPath
);
2419 char* addPoint
= strrchr(newRealPath
,'/');
2420 if ( addPoint
!= NULL
)
2421 strcpy(&addPoint
[1], &path
[17]);
2423 strcpy(newRealPath
, &path
[17]);
2424 image
= loadPhase4(newRealPath
, orgPath
, context
, exceptions
);
2425 if ( image
!= NULL
)
2429 else if ( (strncmp(path
, "@loader_path/", 13) == 0) && (context
.origin
!= NULL
) ) {
2430 // @loader_path cannot be used from the main executable of a setuid process rdar://problem/4589305
2431 if ( sProcessIsRestricted
&& (strcmp(context
.origin
, sExecPath
) == 0) )
2432 throwf("unsafe use of @loader_path in %s with restricted binary", context
.origin
);
2433 // handle @loader_path path prefix
2434 char newPath
[strlen(context
.origin
) + strlen(path
)];
2435 strcpy(newPath
, context
.origin
);
2436 char* addPoint
= strrchr(newPath
,'/');
2437 if ( addPoint
!= NULL
)
2438 strcpy(&addPoint
[1], &path
[13]);
2440 strcpy(newPath
, &path
[13]);
2441 image
= loadPhase4(newPath
, orgPath
, context
, exceptions
);
2442 if ( image
!= NULL
)
2445 // perhaps loader path is a sym link, find realpath and retry
2446 char resolvedPath
[PATH_MAX
];
2447 if ( realpath(context
.origin
, resolvedPath
) != NULL
) {
2448 char newRealPath
[strlen(resolvedPath
) + strlen(path
)];
2449 strcpy(newRealPath
, resolvedPath
);
2450 char* addPoint
= strrchr(newRealPath
,'/');
2451 if ( addPoint
!= NULL
)
2452 strcpy(&addPoint
[1], &path
[13]);
2454 strcpy(newRealPath
, &path
[13]);
2455 image
= loadPhase4(newRealPath
, orgPath
, context
, exceptions
);
2456 if ( image
!= NULL
)
2460 else if ( context
.implicitRPath
|| (strncmp(path
, "@rpath/", 7) == 0) ) {
2461 const char* trailingPath
= (strncmp(path
, "@rpath/", 7) == 0) ? &path
[7] : path
;
2462 // substitute @rpath with all -rpath paths up the load chain
2463 for(const ImageLoader::RPathChain
* rp
=context
.rpath
; rp
!= NULL
; rp
=rp
->next
) {
2464 if (rp
->paths
!= NULL
) {
2465 for(std::vector
<const char*>::iterator it
=rp
->paths
->begin(); it
!= rp
->paths
->end(); ++it
) {
2466 const char* anRPath
= *it
;
2467 char newPath
[strlen(anRPath
) + strlen(trailingPath
)+2];
2468 strcpy(newPath
, anRPath
);
2469 strcat(newPath
, "/");
2470 strcat(newPath
, trailingPath
);
2471 image
= loadPhase4(newPath
, orgPath
, context
, exceptions
);
2472 if ( gLinkContext
.verboseRPaths
&& (exceptions
!= NULL
) ) {
2473 if ( image
!= NULL
)
2474 dyld::log("RPATH successful expansion of %s to: %s\n", orgPath
, newPath
);
2476 dyld::log("RPATH failed to expanding %s to: %s\n", orgPath
, newPath
);
2478 if ( image
!= NULL
)
2484 // substitute @rpath with LD_LIBRARY_PATH
2485 if ( sEnv
.LD_LIBRARY_PATH
!= NULL
) {
2486 image
= loadPhase2(trailingPath
, orgPath
, context
, NULL
, sEnv
.LD_LIBRARY_PATH
, exceptions
);
2487 if ( image
!= NULL
)
2491 // if this is the "open" pass, don't try to open @rpath/... as a relative path
2492 if ( (exceptions
!= NULL
) && (trailingPath
!= path
) )
2495 else if (sProcessIsRestricted
&& (path
[0] != '/' )) {
2496 throwf("unsafe use of relative rpath %s in %s with restricted binary", path
, context
.origin
);
2499 return loadPhase4(path
, orgPath
, context
, exceptions
);
2504 static ImageLoader
* loadPhase2(const char* path
, const char* orgPath
, const LoadContext
& context
,
2505 const char* const frameworkPaths
[], const char* const libraryPaths
[],
2506 std::vector
<const char*>* exceptions
)
2508 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
2509 ImageLoader
* image
= NULL
;
2510 const char* frameworkPartialPath
= getFrameworkPartialPath(path
);
2511 if ( frameworkPaths
!= NULL
) {
2512 if ( frameworkPartialPath
!= NULL
) {
2513 const int frameworkPartialPathLen
= strlen(frameworkPartialPath
);
2514 for(const char* const* fp
= frameworkPaths
; *fp
!= NULL
; ++fp
) {
2515 char npath
[strlen(*fp
)+frameworkPartialPathLen
+8];
2518 strcat(npath
, frameworkPartialPath
);
2519 //dyld::log("dyld: fallback framework path used: %s() -> loadPhase4(\"%s\", ...)\n", __func__, npath);
2520 image
= loadPhase4(npath
, orgPath
, context
, exceptions
);
2521 if ( image
!= NULL
)
2526 if ( libraryPaths
!= NULL
) {
2527 const char* libraryLeafName
= getLibraryLeafName(path
);
2528 const int libraryLeafNameLen
= strlen(libraryLeafName
);
2529 for(const char* const* lp
= libraryPaths
; *lp
!= NULL
; ++lp
) {
2530 char libpath
[strlen(*lp
)+libraryLeafNameLen
+8];
2531 strcpy(libpath
, *lp
);
2532 strcat(libpath
, "/");
2533 strcat(libpath
, libraryLeafName
);
2534 //dyld::log("dyld: fallback library path used: %s() -> loadPhase4(\"%s\", ...)\n", __func__, libpath);
2535 image
= loadPhase4(libpath
, orgPath
, context
, exceptions
);
2536 if ( image
!= NULL
)
2543 // try search overrides and fallbacks
2544 static ImageLoader
* loadPhase1(const char* path
, const char* orgPath
, const LoadContext
& context
, std::vector
<const char*>* exceptions
)
2546 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
2547 ImageLoader
* image
= NULL
;
2549 // handle LD_LIBRARY_PATH environment variables that force searching
2550 if ( context
.useLdLibraryPath
&& (sEnv
.LD_LIBRARY_PATH
!= NULL
) ) {
2551 image
= loadPhase2(path
, orgPath
, context
, NULL
, sEnv
.LD_LIBRARY_PATH
, exceptions
);
2552 if ( image
!= NULL
)
2556 // handle DYLD_ environment variables that force searching
2557 if ( context
.useSearchPaths
&& ((sEnv
.DYLD_FRAMEWORK_PATH
!= NULL
) || (sEnv
.DYLD_LIBRARY_PATH
!= NULL
)) ) {
2558 image
= loadPhase2(path
, orgPath
, context
, sEnv
.DYLD_FRAMEWORK_PATH
, sEnv
.DYLD_LIBRARY_PATH
, exceptions
);
2559 if ( image
!= NULL
)
2564 image
= loadPhase3(path
, orgPath
, context
, exceptions
);
2565 if ( image
!= NULL
)
2568 // try fallback paths during second time (will open file)
2569 const char* const* fallbackLibraryPaths
= sEnv
.DYLD_FALLBACK_LIBRARY_PATH
;
2570 if ( (fallbackLibraryPaths
!= NULL
) && !context
.useFallbackPaths
)
2571 fallbackLibraryPaths
= NULL
;
2572 if ( !context
.dontLoad
&& (exceptions
!= NULL
) && ((sEnv
.DYLD_FALLBACK_FRAMEWORK_PATH
!= NULL
) || (fallbackLibraryPaths
!= NULL
)) ) {
2573 image
= loadPhase2(path
, orgPath
, context
, sEnv
.DYLD_FALLBACK_FRAMEWORK_PATH
, fallbackLibraryPaths
, exceptions
);
2574 if ( image
!= NULL
)
2581 // try root substitutions
2582 static ImageLoader
* loadPhase0(const char* path
, const char* orgPath
, const LoadContext
& context
, std::vector
<const char*>* exceptions
)
2584 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
2586 // handle DYLD_ROOT_PATH which forces absolute paths to use a new root
2587 if ( (gLinkContext
.rootPaths
!= NULL
) && (path
[0] == '/') ) {
2588 for(const char* const* rootPath
= gLinkContext
.rootPaths
; *rootPath
!= NULL
; ++rootPath
) {
2589 char newPath
[strlen(*rootPath
) + strlen(path
)+2];
2590 strcpy(newPath
, *rootPath
);
2591 strcat(newPath
, path
);
2592 ImageLoader
* image
= loadPhase1(newPath
, orgPath
, context
, exceptions
);
2593 if ( image
!= NULL
)
2599 return loadPhase1(path
, orgPath
, context
, exceptions
);
2603 // Given all the DYLD_ environment variables, the general case for loading libraries
2604 // is that any given path expands into a list of possible locations to load. We
2605 // also must take care to ensure two copies of the "same" library are never loaded.
2607 // The algorithm used here is that there is a separate function for each "phase" of the
2608 // path expansion. Each phase function calls the next phase with each possible expansion
2609 // of that phase. The result is the last phase is called with all possible paths.
2611 // To catch duplicates the algorithm is run twice. The first time, the last phase checks
2612 // the path against all loaded images. The second time, the last phase calls open() on
2613 // the path. Either time, if an image is found, the phases all unwind without checking
2616 ImageLoader
* load(const char* path
, const LoadContext
& context
)
2618 CRSetCrashLogMessage2(path
);
2619 const char* orgPath
= path
;
2621 //dyld::log("%s(%s)\n", __func__ , path);
2622 char realPath
[PATH_MAX
];
2623 // when DYLD_IMAGE_SUFFIX is in used, do a realpath(), otherwise a load of "Foo.framework/Foo" will not match
2624 if ( context
.useSearchPaths
&& ( gLinkContext
.imageSuffix
!= NULL
) ) {
2625 if ( realpath(path
, realPath
) != NULL
)
2629 // try all path permutations and check against existing loaded images
2630 ImageLoader
* image
= loadPhase0(path
, orgPath
, context
, NULL
);
2631 if ( image
!= NULL
) {
2632 CRSetCrashLogMessage2(NULL
);
2636 // try all path permutations and try open() until first success
2637 std::vector
<const char*> exceptions
;
2638 image
= loadPhase0(path
, orgPath
, context
, &exceptions
);
2639 CRSetCrashLogMessage2(NULL
);
2640 if ( image
!= NULL
) {
2641 // <rdar://problem/6916014> leak in dyld during dlopen when using DYLD_ variables
2642 for (std::vector
<const char*>::iterator it
= exceptions
.begin(); it
!= exceptions
.end(); ++it
) {
2645 #if __IPHONE_OS_VERSION_MIN_REQUIRED
2646 // if loaded image is not from cache, but original path is in cache
2647 // set gSharedCacheOverridden flag to disable some ObjC optimizations
2648 if ( !gSharedCacheOverridden
) {
2649 if ( !image
->inSharedCache() && inSharedCache(path
) ) {
2650 gSharedCacheOverridden
= true;
2656 else if ( exceptions
.size() == 0 ) {
2657 if ( context
.dontLoad
) {
2661 throw "image not found";
2664 const char* msgStart
= "no suitable image found. Did find:";
2665 const char* delim
= "\n\t";
2666 size_t allsizes
= strlen(msgStart
)+8;
2667 for (unsigned int i
=0; i
< exceptions
.size(); ++i
)
2668 allsizes
+= (strlen(exceptions
[i
]) + strlen(delim
));
2669 char* fullMsg
= new char[allsizes
];
2670 strcpy(fullMsg
, msgStart
);
2671 for (unsigned int i
=0; i
< exceptions
.size(); ++i
) {
2672 strcat(fullMsg
, delim
);
2673 strcat(fullMsg
, exceptions
[i
]);
2674 free((void*)exceptions
[i
]);
2676 throw (const char*)fullMsg
;
2683 #if DYLD_SHARED_CACHE_SUPPORT
2689 #define ARCH_NAME "ppc"
2690 #define ARCH_NAME_ROSETTA "rosetta"
2691 #define ARCH_CACHE_MAGIC "dyld_v1 ppc"
2693 #define ARCH_NAME "ppc64"
2694 #define ARCH_CACHE_MAGIC "dyld_v1 ppc64"
2696 #define ARCH_NAME "i386"
2697 #define ARCH_CACHE_MAGIC "dyld_v1 i386"
2699 #define ARCH_NAME "x86_64"
2700 #define ARCH_CACHE_MAGIC "dyld_v1 x86_64"
2701 #define SHARED_REGION_READ_ONLY_START 0x7FFF80000000LL
2702 #define SHARED_REGION_READ_ONLY_END 0x7FFFC0000000LL
2703 #define SHARED_REGION_WRITABLE_START 0x7FFF70000000LL
2704 #define SHARED_REGION_WRITABLE_END 0x7FFF80000000LL
2705 #define SLIDEABLE_CACHE_SUPPORT 1
2706 #elif __ARM_ARCH_5TEJ__
2707 #define ARCH_NAME "armv5"
2708 #define ARCH_CACHE_MAGIC "dyld_v1 armv5"
2709 #elif __ARM_ARCH_6K__
2710 #define ARCH_NAME "armv6"
2711 #define ARCH_CACHE_MAGIC "dyld_v1 armv6"
2712 #elif __ARM_ARCH_7A__
2713 #define ARCH_NAME "armv7"
2714 #define ARCH_CACHE_MAGIC "dyld_v1 armv7"
2715 #define SHARED_REGION_READ_ONLY_START 0x30000000
2716 #define SHARED_REGION_READ_ONLY_END 0x3E000000
2717 #define SHARED_REGION_WRITABLE_START 0x3E000000
2718 #define SHARED_REGION_WRITABLE_END 0x40000000
2719 #define SLIDEABLE_CACHE_SUPPORT 1
2723 static int __attribute__((noinline
)) _shared_region_check_np(uint64_t* start_address
)
2725 if ( (gLinkContext
.sharedRegionMode
== ImageLoader::kUseSharedRegion
) )
2726 return syscall(294, start_address
);
2731 static int __attribute__((noinline
)) _shared_region_map_and_slide_np(int fd
, uint32_t count
, const shared_file_mapping_np mappings
[],
2732 int codeSignatureMappingIndex
, int slide
, void* slideInfo
, uint32_t slideInfoSize
)
2734 #if __IPHONE_OS_VERSION_MIN_REQUIRED
2735 // register code signature blob for whole dyld cache
2736 if ( codeSignatureMappingIndex
!= -1 ) {
2737 fsignatures_t siginfo
;
2738 siginfo
.fs_file_start
= 0; // cache always starts at beginning of file
2739 siginfo
.fs_blob_start
= (void*)mappings
[codeSignatureMappingIndex
].sfm_file_offset
;
2740 siginfo
.fs_blob_size
= mappings
[codeSignatureMappingIndex
].sfm_size
;
2741 int result
= fcntl(fd
, F_ADDFILESIGS
, &siginfo
);
2743 dyld::log("dyld: code signature for shared cache failed with errno=%d\n", errno
);
2746 if ( (gLinkContext
.sharedRegionMode
== ImageLoader::kUseSharedRegion
) ) {
2747 return syscall(438, fd
, count
, mappings
, slide
, slideInfo
, slideInfoSize
);
2750 // remove the shared region sub-map
2751 vm_deallocate(mach_task_self(), (vm_address_t
)SHARED_REGION_BASE
, SHARED_REGION_SIZE
);
2753 // notify gdb or other lurkers that this process is no longer using the shared region
2754 dyld_all_image_infos
.processDetachedFromSharedRegion
= true;
2756 // map cache just for this process with mmap()
2757 const shared_file_mapping_np
* const start
= mappings
;
2758 const shared_file_mapping_np
* const end
= &mappings
[count
];
2759 for (const shared_file_mapping_np
* p
= start
; p
< end
; ++p
) {
2760 void* mmapAddress
= (void*)(uintptr_t)(p
->sfm_address
);
2761 size_t size
= p
->sfm_size
;
2762 //dyld::log("dyld: mapping address %p with size 0x%08lX\n", mmapAddress, size);
2764 if ( p
->sfm_init_prot
& VM_PROT_EXECUTE
)
2765 protection
|= PROT_EXEC
;
2766 if ( p
->sfm_init_prot
& VM_PROT_READ
)
2767 protection
|= PROT_READ
;
2768 if ( p
->sfm_init_prot
& VM_PROT_WRITE
)
2769 protection
|= PROT_WRITE
;
2770 off_t offset
= p
->sfm_file_offset
;
2771 if ( mmap(mmapAddress
, size
, protection
, MAP_FIXED
| MAP_PRIVATE
, fd
, offset
) != mmapAddress
) {
2772 // failed to map some chunk of this shared cache file
2773 // clear shared region
2774 vm_deallocate(mach_task_self(), (vm_address_t
)SHARED_REGION_BASE
, SHARED_REGION_SIZE
);
2775 // go back to not using shared region at all
2776 gLinkContext
.sharedRegionMode
= ImageLoader::kDontUseSharedRegion
;
2777 if ( gLinkContext
.verboseMapping
) {
2778 dyld::log("dyld: shared cached region cannot be mapped at address %p with size 0x%08lX\n",
2786 #if SLIDEABLE_CACHE_SUPPORT
2787 // update all __DATA pages with slide info
2789 const uintptr_t dataPagesStart
= mappings
[1].sfm_address
;
2790 const dyld_cache_slide_info
* slideInfoHeader
= (dyld_cache_slide_info
*)slideInfo
;
2791 const uint16_t* toc
= (uint16_t*)((long)(slideInfoHeader
) + slideInfoHeader
->toc_offset
);
2792 const uint8_t* entries
= (uint8_t*)((long)(slideInfoHeader
) + slideInfoHeader
->entries_offset
);
2793 for(uint32_t i
=0; i
< slideInfoHeader
->toc_count
; ++i
) {
2794 const uint8_t* entry
= &entries
[toc
[i
]*slideInfoHeader
->entries_size
];
2795 const uint8_t* page
= (uint8_t*)(long)(dataPagesStart
+ (4096*i
));
2796 //dyld::log("page=%p toc[%d]=%d entries=%p\n", page, i, toc[i], entry);
2797 for(int j
=0; j
< 128; ++j
) {
2798 uint8_t b
= entry
[j
];
2799 //dyld::log(" entry[%d] = 0x%02X\n", j, b);
2801 for(int k
=0; k
< 8; ++k
) {
2803 uintptr_t* p
= (uintptr_t*)(page
+ j
*8*4 + k
*4);
2804 uintptr_t value
= *p
;
2805 //dyld::log(" *%p was 0x%lX will be 0x%lX\n", p, value, value+sSharedCacheSlide);
2813 #endif // SLIDEABLE_CACHE_SUPPORT
2815 // succesfully mapped shared cache for just this process
2816 gLinkContext
.sharedRegionMode
= ImageLoader::kUsePrivateSharedRegion
;
2822 const void* imMemorySharedCacheHeader()
2824 return sSharedCache
;
2827 int openSharedCacheFile()
2830 strcpy(path
, sSharedCacheDir
);
2833 // rosetta cannot handle optimized _ppc cache, so it use _rosetta cache instead, rdar://problem/5495438
2835 strcat(path
, DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME_ROSETTA
);
2838 strcat(path
, DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME
);
2839 return ::open(path
, O_RDONLY
);
2842 #if SLIDEABLE_CACHE_SUPPORT
2843 static long pickCacheSlide(uint32_t mappingsCount
, shared_file_mapping_np mappings
[])
2845 // get bounds of cache
2846 uint64_t readOnlyLowAddress
= 0;
2847 uint64_t readOnlyHighAddress
= 0;
2848 uint64_t writableLowAddress
= 0;
2849 uint64_t writableHighAddress
= 0;
2850 for(uint32_t i
=0; i
< mappingsCount
; ++i
) {
2851 if ( mappings
[i
].sfm_init_prot
& VM_PROT_WRITE
) {
2852 writableLowAddress
= mappings
[i
].sfm_address
;
2853 writableHighAddress
= mappings
[i
].sfm_address
+ mappings
[i
].sfm_size
;
2856 if ( readOnlyLowAddress
== 0 ) {
2857 readOnlyLowAddress
= mappings
[i
].sfm_address
;
2858 readOnlyHighAddress
= mappings
[i
].sfm_address
+ mappings
[i
].sfm_size
;
2861 if ( readOnlyLowAddress
< mappings
[i
].sfm_address
) {
2862 readOnlyHighAddress
= mappings
[i
].sfm_address
+ mappings
[i
].sfm_size
;
2865 readOnlyLowAddress
= mappings
[i
].sfm_address
;
2871 // find read-only slop space
2872 uint64_t roSpace
= SHARED_REGION_READ_ONLY_END
- readOnlyHighAddress
;
2874 // find writable slop space
2875 uint64_t rwSpace
= SHARED_REGION_WRITABLE_END
- writableHighAddress
;
2877 // choose new random slide
2878 long slideSpace
= (roSpace
> rwSpace
) ? rwSpace
: roSpace
;
2879 long slide
= (arc4random() % slideSpace
) & (-4096);
2880 //dyld::log("roSpace=0x%0llX\n", roSpace);
2881 //dyld::log("rwSpace=0x%0llX\n", rwSpace);
2882 //dyld::log("slideSpace=0x%0lX\n", slideSpace);
2883 //dyld::log("slide=0x%0lX\n", slide);
2886 for(uint32_t i
=0; i
< mappingsCount
; ++i
) {
2887 mappings
[i
].sfm_address
+= slide
;
2892 #endif // SLIDEABLE_CACHE_SUPPORT
2894 static void mapSharedCache()
2896 uint64_t cacheBaseAddress
;
2897 // quick check if a cache is alreay mapped into shared region
2898 if ( _shared_region_check_np(&cacheBaseAddress
) == 0 ) {
2899 sSharedCache
= (dyld_cache_header
*)cacheBaseAddress
;
2900 // if we don't understand the currently mapped shared cache, then ignore
2901 if ( strcmp(sSharedCache
->magic
, ARCH_CACHE_MAGIC
) != 0 ) {
2902 sSharedCache
= NULL
;
2903 if ( gLinkContext
.verboseMapping
)
2904 dyld::log("dyld: existing shared cached in memory is not compatible\n");
2906 // check if cache file is slidable
2907 dyld_cache_header
* header
= (dyld_cache_header
*)sSharedCache
;
2908 if ( (header
->mappingOffset
>= 0x48) && (header
->slideInfoSize
!= 0) ) {
2909 // solve for slide by comparing loaded address to address of first region
2910 const uint8_t* loadedAddress
= (uint8_t*)sSharedCache
;
2911 const dyld_cache_mapping_info
* const mappings
= (dyld_cache_mapping_info
*)(loadedAddress
+header
->mappingOffset
);
2912 const uint8_t* preferedLoadAddress
= (uint8_t*)(long)(mappings
[0].address
);
2913 sSharedCacheSlide
= loadedAddress
- preferedLoadAddress
;
2914 dyld_all_image_infos
.sharedCacheSlide
= sSharedCacheSlide
;
2915 //dyld::log("sSharedCacheSlide=0x%08lX, loadedAddress=%p, preferedLoadAddress=%p\n", sSharedCacheSlide, loadedAddress, preferedLoadAddress);
2919 #if __i386__ || __x86_64__
2920 // <rdar://problem/5925940> Safe Boot should disable dyld shared cache
2921 // if we are in safe-boot mode and the cache was not made during this boot cycle,
2922 // delete the cache file
2923 uint32_t safeBootValue
= 0;
2924 size_t safeBootValueSize
= sizeof(safeBootValue
);
2925 if ( (sysctlbyname("kern.safeboot", &safeBootValue
, &safeBootValueSize
, NULL
, 0) == 0) && (safeBootValue
!= 0) ) {
2926 // user booted machine in safe-boot mode
2927 struct stat dyldCacheStatInfo
;
2928 // Don't use custom DYLD_SHARED_CACHE_DIR if provided, use standard path
2929 if ( ::stat(MACOSX_DYLD_SHARED_CACHE_DIR DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME
, &dyldCacheStatInfo
) == 0 ) {
2930 struct timeval bootTimeValue
;
2931 size_t bootTimeValueSize
= sizeof(bootTimeValue
);
2932 if ( (sysctlbyname("kern.boottime", &bootTimeValue
, &bootTimeValueSize
, NULL
, 0) == 0) && (bootTimeValue
.tv_sec
!= 0) ) {
2933 // if the cache file was created before this boot, then throw it away and let it rebuild itself
2934 if ( dyldCacheStatInfo
.st_mtime
< bootTimeValue
.tv_sec
) {
2935 ::unlink(MACOSX_DYLD_SHARED_CACHE_DIR DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME
);
2936 gLinkContext
.sharedRegionMode
= ImageLoader::kDontUseSharedRegion
;
2943 // map in shared cache to shared region
2944 int fd
= openSharedCacheFile();
2946 uint8_t firstPages
[8192];
2947 if ( ::read(fd
, firstPages
, 8192) == 8192 ) {
2948 dyld_cache_header
* header
= (dyld_cache_header
*)firstPages
;
2949 if ( strcmp(header
->magic
, ARCH_CACHE_MAGIC
) == 0 ) {
2950 const dyld_cache_mapping_info
* const fileMappingsStart
= (dyld_cache_mapping_info
*)&firstPages
[header
->mappingOffset
];
2951 const dyld_cache_mapping_info
* const fileMappingsEnd
= &fileMappingsStart
[header
->mappingCount
];
2952 shared_file_mapping_np mappings
[header
->mappingCount
+1]; // add room for code-sig
2953 unsigned int mappingCount
= header
->mappingCount
;
2954 int codeSignatureMappingIndex
= -1;
2955 // validate that the cache file has not been truncated
2956 bool goodCache
= false;
2957 struct stat stat_buf
;
2958 if ( fstat(fd
, &stat_buf
) == 0 ) {
2961 for (const dyld_cache_mapping_info
* p
= fileMappingsStart
; p
< fileMappingsEnd
; ++p
, ++i
) {
2962 mappings
[i
].sfm_address
= p
->address
;
2963 mappings
[i
].sfm_size
= p
->size
;
2964 mappings
[i
].sfm_file_offset
= p
->fileOffset
;
2965 mappings
[i
].sfm_max_prot
= p
->maxProt
;
2966 mappings
[i
].sfm_init_prot
= p
->initProt
;
2967 // rdar://problem/5694507 old update_dyld_shared_cache tool could make a cache file
2968 // that is not page aligned, but otherwise ok.
2969 if ( p
->fileOffset
+p
->size
> (uint64_t)(stat_buf
.st_size
+4095 & (-4096)) ) {
2970 dyld::log("dyld: shared cached file is corrupt: %s" DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME
"\n", sSharedCacheDir
);
2974 #if __IPHONE_OS_VERSION_MIN_REQUIRED
2975 // if shared cache is code signed, add a mapping for the code signature
2976 uint32_t signatureSize
= header
->codeSignatureSize
;
2977 // zero size in header means signature runs to end-of-file
2978 if ( signatureSize
== 0 )
2979 signatureSize
= stat_buf
.st_size
- header
->codeSignatureOffset
;
2980 if ( signatureSize
!= 0 ) {
2981 int linkeditMapping
= mappingCount
-1;
2982 codeSignatureMappingIndex
= mappingCount
++;
2983 mappings
[codeSignatureMappingIndex
].sfm_address
= mappings
[linkeditMapping
].sfm_address
+ mappings
[linkeditMapping
].sfm_size
;
2984 mappings
[codeSignatureMappingIndex
].sfm_size
= (signatureSize
+4095) & (-4096);
2985 mappings
[codeSignatureMappingIndex
].sfm_file_offset
= header
->codeSignatureOffset
;
2986 mappings
[codeSignatureMappingIndex
].sfm_max_prot
= VM_PROT_READ
;
2987 mappings
[codeSignatureMappingIndex
].sfm_init_prot
= VM_PROT_READ
;
2991 #if __MAC_OS_X_VERSION_MIN_REQUIRED
2992 // sanity check that /usr/lib/libSystem.B.dylib stat() info matches cache
2993 if ( header
->imagesCount
* sizeof(dyld_cache_image_info
) + header
->imagesOffset
< 8192 ) {
2994 bool foundLibSystem
= false;
2995 if ( stat("/usr/lib/libSystem.B.dylib", &stat_buf
) == 0 ) {
2996 const dyld_cache_image_info
* images
= (dyld_cache_image_info
*)&firstPages
[header
->imagesOffset
];
2997 const dyld_cache_image_info
* const imagesEnd
= &images
[header
->imagesCount
];
2998 for (const dyld_cache_image_info
* p
= images
; p
< imagesEnd
; ++p
) {
2999 if ( ((time_t)p
->modTime
== stat_buf
.st_mtime
) && ((ino_t
)p
->inode
== stat_buf
.st_ino
) ) {
3000 foundLibSystem
= true;
3005 if ( !sSharedCacheIgnoreInodeAndTimeStamp
&& !foundLibSystem
) {
3006 dyld::log("dyld: shared cached file was built against a different libSystem.dylib, ignoring cache.\n"
3007 "to update dyld shared cache run: 'sudo update_dyld_shared_cache' then reboot.\n");
3013 long cacheSlide
= 0;
3014 void* slideInfo
= NULL
;
3015 uint32_t slideInfoSize
= 0;
3016 #if SLIDEABLE_CACHE_SUPPORT
3017 // check if shared cache contains slid info
3018 if ( header
->slideInfoSize
!= 0 ) {
3019 // <rdar://problem/8611968> don't slide shared cache if ASLR disabled (main executable didn't slide)
3020 if ( sMainExecutable
->isPositionIndependentExecutable() && (sMainExecutable
->getSlide() == 0) )
3023 // generate random slide amount
3024 cacheSlide
= pickCacheSlide(mappingCount
, mappings
);
3025 slideInfo
= (void*)(long)(mappings
[2].sfm_address
+ (header
->slideInfoOffset
- mappings
[2].sfm_file_offset
));
3026 slideInfoSize
= header
->slideInfoSize
;
3027 // add VM_PROT_SLIDE bit to __DATA area of cache
3028 mappings
[1].sfm_max_prot
|= VM_PROT_SLIDE
;
3029 mappings
[1].sfm_init_prot
|= VM_PROT_SLIDE
;
3033 if (_shared_region_map_and_slide_np(fd
, mappingCount
, mappings
, codeSignatureMappingIndex
, cacheSlide
, slideInfo
, slideInfoSize
) == 0) {
3034 // successfully mapped cache into shared region
3035 sSharedCache
= (dyld_cache_header
*)mappings
[0].sfm_address
;
3036 sSharedCacheSlide
= cacheSlide
;
3037 dyld_all_image_infos
.sharedCacheSlide
= cacheSlide
;
3038 //dyld::log("sSharedCache=%p sSharedCacheSlide=0x%08lX\n", sSharedCache, sSharedCacheSlide);
3041 if ( gLinkContext
.verboseMapping
)
3042 dyld::log("dyld: shared cached file could not be mapped\n");
3047 if ( gLinkContext
.verboseMapping
)
3048 dyld::log("dyld: shared cached file is invalid\n");
3052 if ( gLinkContext
.verboseMapping
)
3053 dyld::log("dyld: shared cached file cannot be read\n");
3058 if ( gLinkContext
.verboseMapping
)
3059 dyld::log("dyld: shared cached file cannot be opened\n");
3063 // remember if dyld loaded at same address as when cache built
3064 if ( sSharedCache
!= NULL
) {
3065 gLinkContext
.dyldLoadedAtSameAddressNeededBySharedCache
= ((uintptr_t)(sSharedCache
->dyldBaseAddress
) == (uintptr_t)&_mh_dylinker_header
);
3068 // tell gdb where the shared cache is
3069 if ( sSharedCache
!= NULL
) {
3070 const dyld_cache_mapping_info
* const start
= (dyld_cache_mapping_info
*)((uint8_t*)sSharedCache
+ sSharedCache
->mappingOffset
);
3071 dyld_shared_cache_ranges
.sharedRegionsCount
= sSharedCache
->mappingCount
;
3072 // only room to tell gdb about first four regions
3073 if ( dyld_shared_cache_ranges
.sharedRegionsCount
> 4 )
3074 dyld_shared_cache_ranges
.sharedRegionsCount
= 4;
3075 if ( gLinkContext
.verboseMapping
) {
3076 if ( gLinkContext
.sharedRegionMode
== ImageLoader::kUseSharedRegion
)
3077 dyld::log("dyld: Mapping shared cache from %s/" DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME
"\n", sSharedCacheDir
);
3078 else if ( gLinkContext
.sharedRegionMode
== ImageLoader::kUsePrivateSharedRegion
)
3079 dyld::log("dyld: Mapping private shared cache from %s/" DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME
"\n", sSharedCacheDir
);
3081 const dyld_cache_mapping_info
* const end
= &start
[dyld_shared_cache_ranges
.sharedRegionsCount
];
3083 for (const dyld_cache_mapping_info
* p
= start
; p
< end
; ++p
, ++index
) {
3084 dyld_shared_cache_ranges
.ranges
[index
].start
= p
->address
+sSharedCacheSlide
;
3085 dyld_shared_cache_ranges
.ranges
[index
].length
= p
->size
;
3086 if ( gLinkContext
.verboseMapping
) {
3087 dyld::log(" 0x%08llX->0x%08llX %s%s%s init=%x, max=%x\n",
3088 p
->address
+sSharedCacheSlide
, p
->address
+sSharedCacheSlide
+p
->size
-1,
3089 ((p
->initProt
& VM_PROT_READ
) ? "read " : ""),
3090 ((p
->initProt
& VM_PROT_WRITE
) ? "write " : ""),
3091 ((p
->initProt
& VM_PROT_EXECUTE
) ? "execute " : ""), p
->initProt
, p
->maxProt
);
3094 // If a non-writable and executable region is found in the R/W shared region, then this is __IMPORT segments
3095 // This is an old cache. Make writable. dyld no longer supports turn W on and off as it binds
3096 if ( (p
->initProt
== (VM_PROT_READ
|VM_PROT_EXECUTE
)) && ((p
->address
& 0xF0000000) == 0xA0000000) ) {
3097 if ( p
->size
!= 0 ) {
3098 vm_prot_t prot
= VM_PROT_EXECUTE
| PROT_READ
| VM_PROT_WRITE
;
3099 vm_protect(mach_task_self(), p
->address
, p
->size
, false, prot
);
3100 if ( gLinkContext
.verboseMapping
) {
3101 dyld::log("%18s at 0x%08llX->0x%08llX altered permissions to %c%c%c\n", "", p
->address
,
3102 p
->address
+p
->size
-1,
3103 (prot
& PROT_READ
) ? 'r' : '.', (prot
& PROT_WRITE
) ? 'w' : '.', (prot
& PROT_EXEC
) ? 'x' : '.' );
3109 #if __IPHONE_OS_VERSION_MIN_REQUIRED
3110 if ( gLinkContext
.verboseMapping
) {
3111 // list the code blob
3112 dyld_cache_header
* header
= (dyld_cache_header
*)sSharedCache
;
3113 uint32_t signatureSize
= header
->codeSignatureSize
;
3114 // zero size in header means signature runs to end-of-file
3115 if ( signatureSize
== 0 ) {
3116 struct stat stat_buf
;
3117 if ( ::stat(IPHONE_DYLD_SHARED_CACHE_DIR DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME
, &stat_buf
) == 0 )
3118 signatureSize
= stat_buf
.st_size
- header
->codeSignatureOffset
;
3120 if ( signatureSize
!= 0 ) {
3121 const dyld_cache_mapping_info
* const last
= &start
[dyld_shared_cache_ranges
.sharedRegionsCount
-1];
3122 uint64_t codeBlobStart
= last
->address
+ last
->size
;
3123 dyld::log(" 0x%08llX->0x%08llX (code signature)\n", codeBlobStart
, codeBlobStart
+signatureSize
);
3126 // check for file that enables dyld shared cache dylibs to be overridden
3127 struct stat enableStatBuf
;
3128 sDylibsOverrideCache
= ( ::stat(IPHONE_DYLD_SHARED_CACHE_DIR
"enable-dylibs-to-override-cache", &enableStatBuf
) == 0 );
3133 #endif // #if DYLD_SHARED_CACHE_SUPPORT
3137 // create when NSLinkModule is called for a second time on a bundle
3138 ImageLoader
* cloneImage(ImageLoader
* image
)
3140 // open file (automagically closed when this function exits)
3141 FileOpener
file(image
->getPath());
3143 struct stat stat_buf
;
3144 if ( fstat(file
.getFileDescriptor(), &stat_buf
) == -1)
3147 dyld::LoadContext context
;
3148 context
.useSearchPaths
= false;
3149 context
.useFallbackPaths
= false;
3150 context
.useLdLibraryPath
= false;
3151 context
.implicitRPath
= false;
3152 context
.matchByInstallName
= false;
3153 context
.dontLoad
= false;
3154 context
.mustBeBundle
= true;
3155 context
.mustBeDylib
= false;
3156 context
.canBePIE
= false;
3157 context
.origin
= NULL
;
3158 context
.rpath
= NULL
;
3159 return loadPhase6(file
.getFileDescriptor(), stat_buf
, image
->getPath(), context
);
3163 ImageLoader
* loadFromMemory(const uint8_t* mem
, uint64_t len
, const char* moduleName
)
3165 // if fat wrapper, find usable sub-file
3166 const fat_header
* memStartAsFat
= (fat_header
*)mem
;
3167 uint64_t fileOffset
= 0;
3168 uint64_t fileLength
= len
;
3169 if ( memStartAsFat
->magic
== OSSwapBigToHostInt32(FAT_MAGIC
) ) {
3170 if ( fatFindBest(memStartAsFat
, &fileOffset
, &fileLength
) ) {
3171 mem
= &mem
[fileOffset
];
3175 throw "no matching architecture in universal wrapper";
3180 if ( isCompatibleMachO(mem
, moduleName
) ) {
3181 ImageLoader
* image
= ImageLoaderMachO::instantiateFromMemory(moduleName
, (macho_header
*)mem
, len
, gLinkContext
);
3182 // don't add bundles to global list, they can be loaded but not linked. When linked it will be added to list
3183 if ( ! image
->isBundle() )
3188 // try other file formats here...
3190 // throw error about what was found
3191 switch (*(uint32_t*)mem
) {
3196 throw "mach-o, but wrong architecture";
3198 throwf("unknown file type, first eight bytes: 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X",
3199 mem
[0], mem
[1], mem
[2], mem
[3], mem
[4], mem
[5], mem
[6],mem
[7]);
3204 void registerAddCallback(ImageCallback func
)
3206 // now add to list to get notified when any more images are added
3207 sAddImageCallbacks
.push_back(func
);
3209 // call callback with all existing images
3210 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
3211 ImageLoader
* image
= *it
;
3212 if ( image
->getState() >= dyld_image_state_bound
&& image
->getState() < dyld_image_state_terminated
)
3213 (*func
)(image
->machHeader(), image
->getSlide());
3217 void registerRemoveCallback(ImageCallback func
)
3219 sRemoveImageCallbacks
.push_back(func
);
3222 void clearErrorMessage()
3224 error_string
[0] = '\0';
3227 void setErrorMessage(const char* message
)
3229 // save off error message in global buffer for CrashReporter to find
3230 strlcpy(error_string
, message
, sizeof(error_string
));
3233 const char* getErrorMessage()
3235 return error_string
;
3239 void halt(const char* message
)
3241 dyld::log("dyld: %s\n", message
);
3242 setErrorMessage(message
);
3243 uintptr_t terminationFlags
= 0;
3244 if ( !gLinkContext
.startedInitializingMainExecutable
)
3245 terminationFlags
= 1;
3246 setAlImageInfosHalt(error_string
, terminationFlags
);
3247 dyld_fatal_error(error_string
);
3250 static void setErrorStrings(unsigned errorCode
, const char* errorClientOfDylibPath
,
3251 const char* errorTargetDylibPath
, const char* errorSymbol
)
3253 dyld_all_image_infos
.errorKind
= errorCode
;
3254 dyld_all_image_infos
.errorClientOfDylibPath
= errorClientOfDylibPath
;
3255 dyld_all_image_infos
.errorTargetDylibPath
= errorTargetDylibPath
;
3256 dyld_all_image_infos
.errorSymbol
= errorSymbol
;
3260 uintptr_t bindLazySymbol(const mach_header
* mh
, uintptr_t* lazyPointer
)
3262 uintptr_t result
= 0;
3263 // acquire read-lock on dyld's data structures
3264 #if 0 // rdar://problem/3811777 turn off locking until deadlock is resolved
3265 if ( gLibSystemHelpers
!= NULL
)
3266 (*gLibSystemHelpers
->lockForReading
)();
3268 // lookup and bind lazy pointer and get target address
3270 ImageLoader
* target
;
3272 // fast stubs pass NULL for mh and image is instead found via the location of stub (aka lazyPointer)
3274 target
= dyld::findImageContainingAddress(lazyPointer
);
3276 target
= dyld::findImageByMachHeader(mh
);
3278 // note, target should always be mach-o, because only mach-o lazy handler wired up to this
3279 target
= dyld::findImageByMachHeader(mh
);
3281 if ( target
== NULL
)
3282 throwf("image not found for lazy pointer at %p", lazyPointer
);
3283 result
= target
->doBindLazySymbol(lazyPointer
, gLinkContext
);
3285 catch (const char* message
) {
3286 dyld::log("dyld: lazy symbol binding failed: %s\n", message
);
3289 // release read-lock on dyld's data structures
3291 if ( gLibSystemHelpers
!= NULL
)
3292 (*gLibSystemHelpers
->unlockForReading
)();
3294 // return target address to glue which jumps to it with real parameters restored
3299 uintptr_t fastBindLazySymbol(ImageLoader
** imageLoaderCache
, uintptr_t lazyBindingInfoOffset
)
3301 uintptr_t result
= 0;
3303 if ( *imageLoaderCache
== NULL
) {
3305 *imageLoaderCache
= dyld::findMappedRange((uintptr_t)imageLoaderCache
);
3306 if ( *imageLoaderCache
== NULL
) {
3307 const char* message
= "fast lazy binding from unknown image";
3308 dyld::log("dyld: %s\n", message
);
3313 // bind lazy pointer and return it
3315 result
= (*imageLoaderCache
)->doBindFastLazySymbol(lazyBindingInfoOffset
, gLinkContext
,
3316 (dyld::gLibSystemHelpers
!= NULL
) ? dyld::gLibSystemHelpers
->acquireGlobalDyldLock
: NULL
,
3317 (dyld::gLibSystemHelpers
!= NULL
) ? dyld::gLibSystemHelpers
->releaseGlobalDyldLock
: NULL
);
3319 catch (const char* message
) {
3320 dyld::log("dyld: lazy symbol binding failed: %s\n", message
);
3324 // return target address to glue which jumps to it with real parameters restored
3330 void registerUndefinedHandler(UndefinedHandler handler
)
3332 sUndefinedHandler
= handler
;
3335 static void undefinedHandler(const char* symboName
)
3337 if ( sUndefinedHandler
!= NULL
) {
3338 (*sUndefinedHandler
)(symboName
);
3342 static bool findExportedSymbol(const char* name
, bool onlyInCoalesced
, const ImageLoader::Symbol
** sym
, const ImageLoader
** image
)
3344 // search all images in order
3345 const ImageLoader
* firstWeakImage
= NULL
;
3346 const ImageLoader::Symbol
* firstWeakSym
= NULL
;
3347 const unsigned int imageCount
= sAllImages
.size();
3348 for(unsigned int i
=0; i
< imageCount
; ++i
) {
3349 ImageLoader
* anImage
= sAllImages
[i
];
3350 // the use of inserted libraries alters search order
3351 // so that inserted libraries are found before the main executable
3352 if ( sInsertedDylibCount
> 0 ) {
3353 if ( i
< sInsertedDylibCount
)
3354 anImage
= sAllImages
[i
+1];
3355 else if ( i
== sInsertedDylibCount
)
3356 anImage
= sAllImages
[0];
3358 if ( ! anImage
->hasHiddenExports() && (!onlyInCoalesced
|| anImage
->hasCoalescedExports()) ) {
3359 *sym
= anImage
->findExportedSymbol(name
, false, image
);
3360 if ( *sym
!= NULL
) {
3361 // if weak definition found, record first one found
3362 if ( ((*image
)->getExportedSymbolInfo(*sym
) & ImageLoader::kWeakDefinition
) != 0 ) {
3363 if ( firstWeakImage
== NULL
) {
3364 firstWeakImage
= *image
;
3365 firstWeakSym
= *sym
;
3369 // found non-weak, so immediately return with it
3375 if ( firstWeakSym
!= NULL
) {
3376 // found a weak definition, but no non-weak, so return first weak found
3377 *sym
= firstWeakSym
;
3378 *image
= firstWeakImage
;
3385 bool flatFindExportedSymbol(const char* name
, const ImageLoader::Symbol
** sym
, const ImageLoader
** image
)
3387 return findExportedSymbol(name
, false, sym
, image
);
3390 bool findCoalescedExportedSymbol(const char* name
, const ImageLoader::Symbol
** sym
, const ImageLoader
** image
)
3392 return findExportedSymbol(name
, true, sym
, image
);
3396 bool flatFindExportedSymbolWithHint(const char* name
, const char* librarySubstring
, const ImageLoader::Symbol
** sym
, const ImageLoader
** image
)
3398 // search all images in order
3399 const unsigned int imageCount
= sAllImages
.size();
3400 for(unsigned int i
=0; i
< imageCount
; ++i
){
3401 ImageLoader
* anImage
= sAllImages
[i
];
3402 // only look at images whose paths contain the hint string (NULL hint string is wildcard)
3403 if ( ! anImage
->isBundle() && ((librarySubstring
==NULL
) || (strstr(anImage
->getPath(), librarySubstring
) != NULL
)) ) {
3404 *sym
= anImage
->findExportedSymbol(name
, false, image
);
3405 if ( *sym
!= NULL
) {
3413 unsigned int getCoalescedImages(ImageLoader
* images
[])
3415 unsigned int count
= 0;
3416 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
3417 ImageLoader
* image
= *it
;
3418 if ( image
->participatesInCoalescing() ) {
3427 static ImageLoader::MappedRegion
* getMappedRegions(ImageLoader::MappedRegion
* regions
)
3429 ImageLoader::MappedRegion
* end
= regions
;
3430 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
3431 (*it
)->getMappedRegions(end
);
3436 void registerImageStateSingleChangeHandler(dyld_image_states state
, dyld_image_state_change_handler handler
)
3438 // mark the image that the handler is in as never-unload because dyld has a reference into it
3439 ImageLoader
* handlerImage
= findImageContainingAddress((void*)handler
);
3440 if ( handlerImage
!= NULL
)
3441 handlerImage
->setNeverUnload();
3443 // add to list of handlers
3444 std::vector
<dyld_image_state_change_handler
>* handlers
= stateToHandlers(state
, sSingleHandlers
);
3445 if ( handlers
!= NULL
) {
3446 handlers
->push_back(handler
);
3448 // call callback with all existing images
3449 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
3450 ImageLoader
* image
= *it
;
3451 dyld_image_info info
;
3452 info
.imageLoadAddress
= image
->machHeader();
3453 info
.imageFilePath
= image
->getPath();
3454 info
.imageFileModDate
= image
->lastModified();
3455 // should only call handler if state == image->state
3456 if ( image
->getState() == state
)
3457 (*handler
)(state
, 1, &info
);
3458 // ignore returned string, too late to do anything
3463 void registerImageStateBatchChangeHandler(dyld_image_states state
, dyld_image_state_change_handler handler
)
3465 // mark the image that the handler is in as never-unload because dyld has a reference into it
3466 ImageLoader
* handlerImage
= findImageContainingAddress((void*)handler
);
3467 if ( handlerImage
!= NULL
)
3468 handlerImage
->setNeverUnload();
3470 // add to list of handlers
3471 std::vector
<dyld_image_state_change_handler
>* handlers
= stateToHandlers(state
, sBatchHandlers
);
3472 if ( handlers
!= NULL
) {
3473 // insert at front, so that gdb handler is always last
3474 handlers
->insert(handlers
->begin(), handler
);
3476 // call callback with all existing images
3478 notifyBatchPartial(state
, true, handler
);
3480 catch (const char* msg
) {
3481 // ignore request to abort during registration
3486 static ImageLoader
* libraryLocator(const char* libraryName
, bool search
, const char* origin
, const ImageLoader::RPathChain
* rpaths
)
3488 dyld::LoadContext context
;
3489 context
.useSearchPaths
= search
;
3490 context
.useFallbackPaths
= search
;
3491 context
.useLdLibraryPath
= false;
3492 context
.implicitRPath
= false;
3493 context
.matchByInstallName
= false;
3494 context
.dontLoad
= false;
3495 context
.mustBeBundle
= false;
3496 context
.mustBeDylib
= true;
3497 context
.canBePIE
= false;
3498 context
.origin
= origin
;
3499 context
.rpath
= rpaths
;
3500 return load(libraryName
, context
);
3503 static const char* basename(const char* path
)
3505 const char* last
= path
;
3506 for (const char* s
= path
; *s
!= '\0'; s
++) {
3513 static void setContext(const macho_header
* mainExecutableMH
, int argc
, const char* argv
[], const char* envp
[], const char* apple
[])
3515 gLinkContext
.loadLibrary
= &libraryLocator
;
3516 gLinkContext
.terminationRecorder
= &terminationRecorder
;
3517 gLinkContext
.flatExportFinder
= &flatFindExportedSymbol
;
3518 gLinkContext
.coalescedExportFinder
= &findCoalescedExportedSymbol
;
3519 gLinkContext
.getCoalescedImages
= &getCoalescedImages
;
3520 gLinkContext
.undefinedHandler
= &undefinedHandler
;
3521 gLinkContext
.getAllMappedRegions
= &getMappedRegions
;
3522 gLinkContext
.bindingHandler
= NULL
;
3523 gLinkContext
.notifySingle
= ¬ifySingle
;
3524 gLinkContext
.notifyBatch
= ¬ifyBatch
;
3525 gLinkContext
.removeImage
= &removeImage
;
3526 gLinkContext
.registerDOFs
= ®isterDOFs
;
3527 gLinkContext
.clearAllDepths
= &clearAllDepths
;
3528 gLinkContext
.imageCount
= &imageCount
;
3529 gLinkContext
.setNewProgramVars
= &setNewProgramVars
;
3530 #if DYLD_SHARED_CACHE_SUPPORT
3531 gLinkContext
.inSharedCache
= &inSharedCache
;
3533 gLinkContext
.setErrorStrings
= &setErrorStrings
;
3534 #if SUPPORT_OLD_CRT_INITIALIZATION
3535 gLinkContext
.setRunInitialzersOldWay
= &setRunInitialzersOldWay
;
3537 gLinkContext
.bindingOptions
= ImageLoader::kBindingNone
;
3538 gLinkContext
.argc
= argc
;
3539 gLinkContext
.argv
= argv
;
3540 gLinkContext
.envp
= envp
;
3541 gLinkContext
.apple
= apple
;
3542 gLinkContext
.progname
= (argv
[0] != NULL
) ? basename(argv
[0]) : "";
3543 gLinkContext
.programVars
.mh
= mainExecutableMH
;
3544 gLinkContext
.programVars
.NXArgcPtr
= &gLinkContext
.argc
;
3545 gLinkContext
.programVars
.NXArgvPtr
= &gLinkContext
.argv
;
3546 gLinkContext
.programVars
.environPtr
= &gLinkContext
.envp
;
3547 gLinkContext
.programVars
.__prognamePtr
=&gLinkContext
.progname
;
3548 gLinkContext
.mainExecutable
= NULL
;
3549 gLinkContext
.imageSuffix
= NULL
;
3550 gLinkContext
.prebindUsage
= ImageLoader::kUseAllPrebinding
;
3551 gLinkContext
.sharedRegionMode
= ImageLoader::kUseSharedRegion
;
3554 #if __ppc__ || __i386__
3557 int mib
[] = { CTL_KERN
, KERN_CLASSIC
, getpid() };
3559 size_t len
= sizeof(int);
3560 int ret
= sysctl(mib
, 3, &is_classic
, &len
, NULL
, 0);
3561 if ((ret
!= -1) && is_classic
) {
3562 // we're running under Rosetta
3571 #define LC_SEGMENT_COMMAND LC_SEGMENT_64
3572 #define macho_segment_command segment_command_64
3573 #define macho_section section_64
3575 #define LC_SEGMENT_COMMAND LC_SEGMENT
3576 #define macho_segment_command segment_command
3577 #define macho_section section
3582 // Look for a special segment in the mach header.
3583 // Its presences means that the binary wants to have DYLD ignore
3584 // DYLD_ environment variables.
3586 static bool hasRestrictedSegment(const macho_header
* mh
)
3588 const uint32_t cmd_count
= mh
->ncmds
;
3589 const struct load_command
* const cmds
= (struct load_command
*)(((char*)mh
)+sizeof(macho_header
));
3590 const struct load_command
* cmd
= cmds
;
3591 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
3593 case LC_SEGMENT_COMMAND
:
3595 const struct macho_segment_command
* seg
= (struct macho_segment_command
*)cmd
;
3597 //dyld::log("seg name: %s\n", seg->segname);
3598 if (strcmp(seg
->segname
, "__RESTRICT") == 0) {
3599 const struct macho_section
* const sectionsStart
= (struct macho_section
*)((char*)seg
+ sizeof(struct macho_segment_command
));
3600 const struct macho_section
* const sectionsEnd
= §ionsStart
[seg
->nsects
];
3601 for (const struct macho_section
* sect
=sectionsStart
; sect
< sectionsEnd
; ++sect
) {
3602 if (strcmp(sect
->sectname
, "__restrict") == 0)
3609 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
3617 // Peeks at a dylib file and returns its current_version and install_name.
3618 // Returns false on error.
3620 static bool getDylibVersionAndInstallname(const char* dylibPath
, uint32_t* version
, char* installName
)
3622 // open file (automagically closed when this function exits)
3623 FileOpener
file(dylibPath
);
3625 if ( file
.getFileDescriptor() == -1 )
3628 uint8_t firstPage
[4096];
3629 if ( pread(file
.getFileDescriptor(), firstPage
, 4096, 0) != 4096 )
3632 // if fat wrapper, find usable sub-file
3633 const fat_header
* fileStartAsFat
= (fat_header
*)firstPage
;
3634 if ( fileStartAsFat
->magic
== OSSwapBigToHostInt32(FAT_MAGIC
) ) {
3635 uint64_t fileOffset
;
3636 uint64_t fileLength
;
3637 if ( fatFindBest(fileStartAsFat
, &fileOffset
, &fileLength
) ) {
3638 if ( pread(file
.getFileDescriptor(), firstPage
, 4096, fileOffset
) != 4096 )
3646 // check mach-o header
3647 const mach_header
* mh
= (mach_header
*)firstPage
;
3648 if ( mh
->magic
!= sMainExecutableMachHeader
->magic
)
3650 if ( mh
->cputype
!= sMainExecutableMachHeader
->cputype
)
3653 // scan load commands for LC_ID_DYLIB
3654 const uint32_t cmd_count
= mh
->ncmds
;
3655 const struct load_command
* const cmds
= (struct load_command
*)(((char*)mh
)+sizeof(macho_header
));
3656 const struct load_command
* const cmdsReadEnd
= (struct load_command
*)(((char*)mh
)+4096);
3657 const struct load_command
* cmd
= cmds
;
3658 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
3662 const struct dylib_command
* id
= (struct dylib_command
*)cmd
;
3663 *version
= id
->dylib
.current_version
;
3664 if ( installName
!= NULL
)
3665 strlcpy(installName
, (char *)id
+ id
->dylib
.name
.offset
, PATH_MAX
);
3670 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
3671 if ( cmd
> cmdsReadEnd
)
3679 static void printAllImages()
3681 dyld::log("printAllImages()\n");
3682 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
3683 ImageLoader
* image
= *it
;
3684 dyld_image_states imageState
= image
->getState();
3685 dyld::log(" state=%d, refcount=%d, name=%s\n", imageState
, image
->referenceCount(), image
->getShortName());
3686 image
->printReferenceCounts();
3691 void link(ImageLoader
* image
, bool forceLazysBound
, const ImageLoader::RPathChain
& loaderRPaths
)
3693 // add to list of known images. This did not happen at creation time for bundles
3694 if ( image
->isBundle() && !image
->isLinked() )
3697 // we detect root images as those not linked in yet
3698 if ( !image
->isLinked() )
3699 addRootImage(image
);
3703 image
->link(gLinkContext
, forceLazysBound
, false, loaderRPaths
);
3705 catch (const char* msg
) {
3706 garbageCollectImages();
3712 void runInitializers(ImageLoader
* image
)
3714 // do bottom up initialization
3715 ImageLoader::InitializerTimingList initializerTimes
[sAllImages
.size()];
3716 initializerTimes
[0].count
= 0;
3717 image
->runInitializers(gLinkContext
, initializerTimes
[0]);
3720 void garbageCollectImages()
3722 // keep scanning list of images until entire list is scanned with no unreferenced images
3723 bool mightBeUnreferencedImages
= true;
3724 while ( mightBeUnreferencedImages
) {
3725 mightBeUnreferencedImages
= false;
3726 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
3727 ImageLoader
* image
= *it
;
3728 if ( (image
->referenceCount() == 0) && !image
->neverUnload() && !image
->isBeingRemoved() ) {
3730 //dyld::log("garbageCollectImages: deleting %s\n", image->getPath());
3731 image
->setBeingRemoved();
3733 ImageLoader::deleteImage(image
);
3735 catch (const char* msg
) {
3736 dyld::warn("problem deleting image: %s\n", msg
);
3738 mightBeUnreferencedImages
= true;
3747 static void preflight_finally(ImageLoader
* image
)
3749 if ( image
->isBundle() ) {
3750 removeImageFromAllImages(image
->machHeader());
3751 ImageLoader::deleteImage(image
);
3753 sBundleBeingLoaded
= NULL
;
3754 dyld::garbageCollectImages();
3758 void preflight(ImageLoader
* image
, const ImageLoader::RPathChain
& loaderRPaths
)
3761 if ( image
->isBundle() )
3762 sBundleBeingLoaded
= image
; // hack
3763 image
->link(gLinkContext
, false, true, loaderRPaths
);
3765 catch (const char* msg
) {
3766 preflight_finally(image
);
3769 preflight_finally(image
);
3772 static void loadInsertedDylib(const char* path
)
3774 ImageLoader
* image
= NULL
;
3776 LoadContext context
;
3777 context
.useSearchPaths
= false;
3778 context
.useFallbackPaths
= false;
3779 context
.useLdLibraryPath
= false;
3780 context
.implicitRPath
= false;
3781 context
.matchByInstallName
= false;
3782 context
.dontLoad
= false;
3783 context
.mustBeBundle
= false;
3784 context
.mustBeDylib
= true;
3785 context
.canBePIE
= false;
3786 context
.origin
= NULL
; // can't use @loader_path with DYLD_INSERT_LIBRARIES
3787 context
.rpath
= NULL
;
3788 image
= load(path
, context
);
3789 image
->setNeverUnload();
3792 halt(dyld::mkstringf("could not load inserted library: %s\n", path
));
3796 static bool processRestricted(const macho_header
* mainExecutableMH
)
3798 // all processes with setuid or setgid bit set are restricted
3802 if ( hasRestrictedSegment(mainExecutableMH
) && (geteuid() != 0) ) {
3803 // existence of __RESTRICT/__restrict section make process restricted
3807 #if __MAC_OS_X_VERSION_MIN_REQUIRED
3808 // ask kernel if code signature of program makes it restricted
3810 if ( syscall(SYS_csops
/* 169 */,
3811 0 /* asking about myself */,
3814 sizeof(flags
)) != -1) {
3815 if (flags
& CS_RESTRICT
)
3824 // Entry point for dyld. The kernel loads dyld and jumps to __dyld_start which
3825 // sets up some registers and call this function.
3827 // Returns address of main() in target program which __dyld_start jumps to
3830 _main(const macho_header
* mainExecutableMH
, uintptr_t mainExecutableSlide
, int argc
, const char* argv
[], const char* envp
[], const char* apple
[])
3832 CRSetCrashLogMessage("dyld: launch started");
3833 #ifdef ALTERNATIVE_LOGFILE
3834 sLogfile
= open(ALTERNATIVE_LOGFILE
, O_WRONLY
| O_CREAT
| O_APPEND
);
3835 if ( sLogfile
== -1 ) {
3836 sLogfile
= STDERR_FILENO
;
3837 dyld::log("error opening alternate log file %s, errno = %d\n", ALTERNATIVE_LOGFILE
, errno
);
3842 char bindingsLogPath
[256];
3844 const char* shortProgName
= "unknown";
3846 shortProgName
= strrchr(argv
[0], '/');
3847 if ( shortProgName
== NULL
)
3848 shortProgName
= argv
[0];
3852 mysprintf(bindingsLogPath
, "/tmp/bindings/%d-%s", getpid(), shortProgName
);
3853 sBindingsLogfile
= open(bindingsLogPath
, O_WRONLY
| O_CREAT
, 0666);
3854 if ( sBindingsLogfile
== -1 ) {
3855 ::mkdir("/tmp/bindings", 0777);
3856 sBindingsLogfile
= open(bindingsLogPath
, O_WRONLY
| O_CREAT
, 0666);
3858 //dyld::log("open(%s) => %d, errno = %d\n", bindingsLogPath, sBindingsLogfile, errno);
3860 setContext(mainExecutableMH
, argc
, argv
, envp
, apple
);
3862 // Pickup the pointer to the exec path.
3863 sExecPath
= apple
[0];
3864 bool ignoreEnvironmentVariables
= false;
3866 if ( isRosetta() ) {
3867 // under Rosetta (x86 side)
3868 // When a 32-bit ppc program is run under emulation on an Intel processor,
3869 // we want any i386 dylibs (e.g. any used by Rosetta) to not load in the shared region
3870 // because the shared region is being used by ppc dylibs
3871 gLinkContext
.sharedRegionMode
= ImageLoader::kDontUseSharedRegion
;
3872 ignoreEnvironmentVariables
= true;
3875 if ( sExecPath
[0] != '/' ) {
3876 // have relative path, use cwd to make absolute
3877 char cwdbuff
[MAXPATHLEN
];
3878 if ( getcwd(cwdbuff
, MAXPATHLEN
) != NULL
) {
3879 // maybe use static buffer to avoid calling malloc so early...
3880 char* s
= new char[strlen(cwdbuff
) + strlen(sExecPath
) + 2];
3883 strcat(s
, sExecPath
);
3887 uintptr_t result
= 0;
3888 sMainExecutableMachHeader
= mainExecutableMH
;
3889 sProcessIsRestricted
= processRestricted(mainExecutableMH
);
3890 if ( sProcessIsRestricted
) {
3891 #if SUPPORT_LC_DYLD_ENVIRONMENT
3892 checkLoadCommandEnvironmentVariables();
3893 #if SUPPORT_VERSIONED_PATHS
3894 checkVersionedPaths();
3897 pruneEnvironmentVariables(envp
, &apple
);
3898 // set again because envp and apple may have changed or moved
3899 setContext(mainExecutableMH
, argc
, argv
, envp
, apple
);
3902 checkEnvironmentVariables(envp
, ignoreEnvironmentVariables
);
3903 if ( sEnv
.DYLD_PRINT_OPTS
)
3905 if ( sEnv
.DYLD_PRINT_ENV
)
3906 printEnvironmentVariables(envp
);
3908 // install gdb notifier
3909 stateToHandlers(dyld_image_state_dependents_mapped
, sBatchHandlers
)->push_back(notifyGDB
);
3910 stateToHandlers(dyld_image_state_mapped
, sSingleHandlers
)->push_back(updateAllImages
);
3911 // make initial allocations large enough that it is unlikely to need to be re-alloced
3912 sAllImages
.reserve(INITIAL_IMAGE_COUNT
);
3913 sImageRoots
.reserve(16);
3914 sAddImageCallbacks
.reserve(4);
3915 sRemoveImageCallbacks
.reserve(4);
3916 sImageFilesNeedingTermination
.reserve(16);
3917 sImageFilesNeedingDOFUnregistration
.reserve(8);
3919 #ifdef WAIT_FOR_SYSTEM_ORDER_HANDSHAKE
3920 // <rdar://problem/6849505> Add gating mechanism to dyld support system order file generation process
3921 WAIT_FOR_SYSTEM_ORDER_HANDSHAKE(dyld_all_image_infos
.systemOrderFlag
);
3925 CRSetCrashLogMessage("dyld: launch, loading dependent libraries");
3926 // instantiate ImageLoader for main executable
3927 sMainExecutable
= instantiateFromLoadedImage(mainExecutableMH
, mainExecutableSlide
, sExecPath
);
3928 sMainExecutable
->setNeverUnload();
3929 gLinkContext
.mainExecutable
= sMainExecutable
;
3930 gLinkContext
.processIsRestricted
= sProcessIsRestricted
;
3931 // load shared cache
3932 checkSharedRegionDisable();
3933 #if DYLD_SHARED_CACHE_SUPPORT
3934 if ( gLinkContext
.sharedRegionMode
!= ImageLoader::kDontUseSharedRegion
)
3937 // load any inserted libraries
3938 if ( sEnv
.DYLD_INSERT_LIBRARIES
!= NULL
) {
3939 for (const char* const* lib
= sEnv
.DYLD_INSERT_LIBRARIES
; *lib
!= NULL
; ++lib
)
3940 loadInsertedDylib(*lib
);
3942 // record count of inserted libraries so that a flat search will look at
3943 // inserted libraries, then main, then others.
3944 sInsertedDylibCount
= sAllImages
.size()-1;
3946 // link main executable
3947 gLinkContext
.linkingMainExecutable
= true;
3948 link(sMainExecutable
, sEnv
.DYLD_BIND_AT_LAUNCH
, ImageLoader::RPathChain(NULL
, NULL
));
3949 gLinkContext
.linkingMainExecutable
= false;
3950 if ( sMainExecutable
->forceFlat() ) {
3951 gLinkContext
.bindFlat
= true;
3952 gLinkContext
.prebindUsage
= ImageLoader::kUseNoPrebinding
;
3954 result
= (uintptr_t)sMainExecutable
->getMain();
3956 // link any inserted libraries
3957 // do this after linking main executable so that any dylibs pulled in by inserted
3958 // dylibs (e.g. libSystem) will not be in front of dylibs the program uses
3959 if ( sInsertedDylibCount
> 0 ) {
3960 for(unsigned int i
=0; i
< sInsertedDylibCount
; ++i
) {
3961 ImageLoader
* image
= sAllImages
[i
+1];
3962 link(image
, sEnv
.DYLD_BIND_AT_LAUNCH
, ImageLoader::RPathChain(NULL
, NULL
));
3963 // only INSERTED libraries can interpose
3964 image
->registerInterposing();
3968 CRSetCrashLogMessage("dyld: launch, running initializers");
3969 #if SUPPORT_OLD_CRT_INITIALIZATION
3970 // Old way is to run initializers via a callback from crt1.o
3971 if ( ! gRunInitializersOldWay
)
3973 initializeMainExecutable(); // run all initializers
3975 catch(const char* message
) {
3980 dyld::log("dyld: launch failed\n");
3983 #ifdef ALTERNATIVE_LOGFILE
3984 // only use alternate log during launch, otherwise file is open forever
3985 if ( sLogfile
!= STDERR_FILENO
) {
3987 sLogfile
= STDERR_FILENO
;
3990 CRSetCrashLogMessage(NULL
);