1 /* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*-
3 * Copyright (c) 2004-2007 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@
30 #include <sys/param.h>
31 #include <mach/mach_time.h> // mach_absolute_time()
32 #include <sys/types.h>
34 #include <mach-o/fat.h>
35 #include <mach-o/loader.h>
36 #include <mach-o/ldsyms.h>
37 #include <libkern/OSByteOrder.h>
38 #include <mach/mach.h>
39 #include <sys/sysctl.h>
41 #include <sys/dtrace.h>
46 #include "mach-o/dyld_gdb.h"
49 #include "ImageLoader.h"
50 #include "ImageLoaderMachO.h"
51 #include "dyldLibSystemInterface.h"
52 #include "dyld_cache_format.h"
54 // from _simple.h in libc
55 typedef struct _SIMPLE
* _SIMPLE_STRING
;
56 extern "C" void _simple_vdprintf(int __fd
, const char *__fmt
, va_list __ap
);
57 extern "C" void _simple_dprintf(int __fd
, const char *__fmt
, ...);
58 extern "C" _SIMPLE_STRING
_simple_salloc(void);
59 extern "C" int _simple_vsprintf(_SIMPLE_STRING __b
, const char *__fmt
, va_list __ap
);
60 extern "C" void _simple_sfree(_SIMPLE_STRING __b
);
61 extern "C" char * _simple_string(_SIMPLE_STRING __b
);
65 // 32-bit ppc is only architecture that uses cpu-sub-types
66 #define CPU_SUBTYPES_SUPPORTED __ppc__
69 #define OLD_GDB_DYLD_INTERFACE __ppc__ || __i386__
72 #define CPU_TYPE_MASK 0x00FFFFFF /* complement of CPU_ARCH_MASK */
75 /* implemented in dyld_gdb.cpp */
76 extern void addImagesToAllImages(uint32_t infoCount
, const dyld_image_info info
[]);
77 extern void removeImageFromAllImages(const mach_header
* mh
);
78 #if OLD_GDB_DYLD_INTERFACE
79 extern void addImageForgdb(const mach_header
* mh
, uintptr_t slide
, const char* physicalPath
, const char* logicalPath
);
80 extern void removeImageForgdb(const struct mach_header
* mh
);
83 // magic so CrashReporter logs message
85 char error_string
[1024];
87 // implemented in dyldStartup.s for CrashReporter
88 extern "C" void dyld_fatal_error(const char* errString
) __attribute__((noreturn
));
93 // The file contains the core of dyld used to get a process to main().
94 // The API's that dyld supports are implemented in dyldAPIs.cpp.
106 // state of all environment variables dyld uses
108 struct EnvironmentVariables
{
109 const char* const * DYLD_FRAMEWORK_PATH
;
110 const char* const * DYLD_FALLBACK_FRAMEWORK_PATH
;
111 const char* const * DYLD_LIBRARY_PATH
;
112 const char* const * DYLD_FALLBACK_LIBRARY_PATH
;
113 const char* const * DYLD_ROOT_PATH
;
114 const char* const * DYLD_INSERT_LIBRARIES
;
115 const char* const * LD_LIBRARY_PATH
; // for unix conformance
116 bool DYLD_PRINT_LIBRARIES
;
117 bool DYLD_PRINT_LIBRARIES_POST_LAUNCH
;
118 bool DYLD_BIND_AT_LAUNCH
;
119 bool DYLD_PRINT_STATISTICS
;
120 bool DYLD_PRINT_OPTS
;
122 bool DYLD_DISABLE_DOFS
;
123 // DYLD_IMAGE_SUFFIX ==> gLinkContext.imageSuffix
124 // DYLD_PRINT_OPTS ==> gLinkContext.verboseOpts
125 // DYLD_PRINT_ENV ==> gLinkContext.verboseEnv
126 // DYLD_FORCE_FLAT_NAMESPACE ==> gLinkContext.bindFlat
127 // DYLD_PRINT_INITIALIZERS ==> gLinkContext.verboseInit
128 // DYLD_PRINT_SEGMENTS ==> gLinkContext.verboseMapping
129 // DYLD_PRINT_BINDINGS ==> gLinkContext.verboseBind
130 // DYLD_PRINT_REBASINGS ==> gLinkContext.verboseRebase
131 // DYLD_PRINT_DOFS ==> gLinkContext.verboseDOF
132 // DYLD_PRINT_APIS ==> gLogAPIs
133 // DYLD_IGNORE_PREBINDING ==> gLinkContext.prebindUsage
134 // DYLD_PREBIND_DEBUG ==> gLinkContext.verbosePrebinding
135 // DYLD_NEW_LOCAL_SHARED_REGIONS ==> gLinkContext.sharedRegionMode
136 // DYLD_SHARED_REGION ==> gLinkContext.sharedRegionMode
137 // DYLD_PRINT_WARNINGS ==> gLinkContext.verboseWarnings
140 typedef std::vector
<dyld_image_state_change_handler
> StateHandlers
;
141 struct RegisteredDOF
{ const mach_header
* mh
; int registrationID
; };
144 static const char* sExecPath
= NULL
;
145 static const struct mach_header
* sMainExecutableMachHeader
= NULL
;
146 static cpu_type_t sHostCPU
;
147 static cpu_subtype_t sHostCPUsubtype
;
148 static ImageLoader
* sMainExecutable
= NULL
;
149 static bool sMainExecutableIsSetuid
= false;
150 static unsigned int sInsertedDylibCount
= 0;
151 static std::vector
<ImageLoader
*> sAllImages
;
152 static std::vector
<ImageLoader
*> sImageRoots
;
153 static std::vector
<ImageLoader
*> sImageFilesNeedingTermination
;
154 static std::vector
<RegisteredDOF
> sImageFilesNeedingDOFUnregistration
;
155 #if IMAGE_NOTIFY_SUPPORT
156 static std::vector
<ImageLoader
*> sImagesToNotifyAboutOtherImages
;
158 static std::vector
<ImageCallback
> sAddImageCallbacks
;
159 static std::vector
<ImageCallback
> sRemoveImageCallbacks
;
160 static StateHandlers sSingleHandlers
[7];
161 static StateHandlers sBatchHandlers
[7];
162 static ImageLoader
* sLastImageByAddressCache
;
163 static EnvironmentVariables sEnv
;
164 static const char* sFrameworkFallbackPaths
[] = { "$HOME/Library/Frameworks", "/Library/Frameworks", "/Network/Library/Frameworks", "/System/Library/Frameworks", NULL
};
165 static const char* sLibraryFallbackPaths
[] = { "$HOME/lib", "/usr/local/lib", "/usr/lib", NULL
};
166 static BundleNotificationCallBack sBundleNotifier
= NULL
;
167 static BundleLocatorCallBack sBundleLocation
= NULL
;
168 static UndefinedHandler sUndefinedHandler
= NULL
;
169 static ImageLoader
* sBundleBeingLoaded
= NULL
; // hack until OFI is reworked
170 #if DYLD_SHARED_CACHE_SUPPORT
171 static const dyld_cache_header
* sSharedCache
= NULL
;
172 bool gSharedCacheNotFound
= false;
173 bool gSharedCacheNeedsUpdating
= false;
174 bool gSharedCacheDontNotify
= false;
176 ImageLoader::LinkContext gLinkContext
;
177 bool gLogAPIs
= false;
178 const struct LibSystemHelpers
* gLibSystemHelpers
= NULL
;
179 #if SUPPORT_OLD_CRT_INITIALIZATION
180 bool gRunInitializersOldWay
= false;
183 static uint32_t sImportSegmentsStart
= 0;
184 static uint32_t sImportSegmentsSize
= 0;
189 const char* mkstringf(const char* format
, ...)
192 va_start(list
, format
);
193 _SIMPLE_STRING buf
= _simple_salloc();
194 _simple_vsprintf(buf
, format
, list
);
196 const char* t
= strdup(_simple_string(buf
));
202 void throwf(const char* format
, ...)
205 va_start(list
, format
);
206 _SIMPLE_STRING buf
= _simple_salloc();
207 _simple_vsprintf(buf
, format
, list
);
209 const char* t
= strdup(_simple_string(buf
));
214 void log(const char* format
, ...)
217 va_start(list
, format
);
218 _simple_vdprintf(STDERR_FILENO
, format
, list
);
222 void warn(const char* format
, ...)
224 _simple_dprintf(STDERR_FILENO
, "dyld: warning, ");
226 va_start(list
, format
);
227 _simple_vdprintf(STDERR_FILENO
, format
, list
);
232 // utility class to assure files are closed when an exception is thrown
235 FileOpener(const char* path
);
237 int getFileDescriptor() { return fd
; }
242 FileOpener::FileOpener(const char* path
)
245 fd
= open(path
, O_RDONLY
, 0);
248 FileOpener::~FileOpener()
255 // forward declaration
256 #if __ppc__ || __i386__
261 static void registerDOFs(const std::vector
<ImageLoader::DOFInfo
>& dofs
)
264 // can't dtrace a program running emulated under rosetta rdar://problem/5179640
268 const unsigned int dofSectionCount
= dofs
.size();
269 if ( !sEnv
.DYLD_DISABLE_DOFS
&& (dofSectionCount
!= 0) ) {
270 int fd
= open("/dev/" DTRACEMNR_HELPER
, O_RDWR
);
272 //dyld::warn("can't open /dev/" DTRACEMNR_HELPER " to register dtrace DOF sections\n");
275 // allocate a buffer on the stack for the variable length dof_ioctl_data_t type
276 uint8_t buffer
[sizeof(dof_ioctl_data_t
) + dofSectionCount
*sizeof(dof_helper_t
)];
277 dof_ioctl_data_t
* ioctlData
= (dof_ioctl_data_t
*)buffer
;
279 // fill in buffer with one dof_helper_t per DOF section
280 ioctlData
->dofiod_count
= dofSectionCount
;
281 for (unsigned int i
=0; i
< dofSectionCount
; ++i
) {
282 strlcpy(ioctlData
->dofiod_helpers
[i
].dofhp_mod
, dofs
[i
].imageShortName
, DTRACE_MODNAMELEN
);
283 ioctlData
->dofiod_helpers
[i
].dofhp_dof
= (uintptr_t)(dofs
[i
].dof
);
284 ioctlData
->dofiod_helpers
[i
].dofhp_addr
= (uintptr_t)(dofs
[i
].dof
);
287 // tell kernel about all DOF sections en mas
288 // pass pointer to ioctlData because ioctl() only copies a fixed size amount of data into kernel
289 user_addr_t val
= (user_addr_t
)(unsigned long)ioctlData
;
290 if ( ioctl(fd
, DTRACEHIOC_ADDDOF
, &val
) != -1 ) {
291 // kernel returns a unique identifier for each section in the dofiod_helpers[].dofhp_dof field.
292 for (unsigned int i
=0; i
< dofSectionCount
; ++i
) {
294 info
.mh
= dofs
[i
].imageHeader
;
295 info
.registrationID
= (int)(ioctlData
->dofiod_helpers
[i
].dofhp_dof
);
296 sImageFilesNeedingDOFUnregistration
.push_back(info
);
297 if ( gLinkContext
.verboseDOF
) {
298 dyld::log("dyld: registering DOF section 0x%p in %s with dtrace, ID=0x%08X\n",
299 dofs
[i
].dof
, dofs
[i
].imageShortName
, info
.registrationID
);
304 dyld::log( "dyld: ioctl to register dtrace DOF section failed\n");
311 static void unregisterDOF(int registrationID
)
313 int fd
= open("/dev/" DTRACEMNR_HELPER
, O_RDWR
);
315 dyld::warn("can't open /dev/" DTRACEMNR_HELPER
" to unregister dtrace DOF section\n");
318 ioctl(fd
, DTRACEHIOC_REMOVE
, registrationID
);
320 if ( gLinkContext
.verboseInit
)
321 dyld::warn("unregistering DOF section ID=0x%08X with dtrace\n", registrationID
);
327 // _dyld_register_func_for_add_image() is implemented as part of the general image state change notification
329 static void notifyAddImageCallbacks(ImageLoader
* image
)
331 for (std::vector
<ImageCallback
>::iterator it
=sAddImageCallbacks
.begin(); it
!= sAddImageCallbacks
.end(); it
++)
332 (*it
)(image
->machHeader(), image
->getSlide());
336 // notify gdb about these new images
337 static const char* notifyGDB(enum dyld_image_states state
, uint32_t infoCount
, const struct dyld_image_info info
[])
339 addImagesToAllImages(infoCount
, info
);
343 #if IMAGE_NOTIFY_SUPPORT
344 // notify objc about these new images
345 static void notifyAdding(const ImageLoader
* const * images
, unsigned int count
)
349 dyld_image_info infos
[count
];
350 for (unsigned int i
=0; i
< count
; ++i
) {
351 dyld_image_info
* p
= &infos
[i
];
352 const ImageLoader
* image
= images
[i
];
353 p
->imageLoadAddress
= image
->machHeader();
354 p
->imageFilePath
= image
->getPath();
355 p
->imageFileModDate
= image
->lastModified();
356 //dyld::log("notifying objc about %s\n", image->getPath());
359 // tell all interested images (after gdb, so you can debug anything the notification does)
360 for (std::vector
<ImageLoader
*>::iterator it
=sImagesToNotifyAboutOtherImages
.begin(); it
!= sImagesToNotifyAboutOtherImages
.end(); it
++) {
361 (*it
)->doNotification(dyld_image_adding
, count
, infos
);
367 static StateHandlers
* stateToHandlers(dyld_image_states state
, StateHandlers handlersArray
[8])
370 case dyld_image_state_mapped
:
371 return &handlersArray
[0];
373 case dyld_image_state_dependents_mapped
:
374 return &handlersArray
[1];
376 case dyld_image_state_rebased
:
377 return &handlersArray
[2];
379 case dyld_image_state_bound
:
380 return &handlersArray
[3];
382 case dyld_image_state_dependents_initialized
:
383 return &handlersArray
[4];
385 case dyld_image_state_initialized
:
386 return &handlersArray
[5];
388 case dyld_image_state_terminated
:
389 return &handlersArray
[6];
394 static void notifySingle(dyld_image_states state
, const struct mach_header
* mh
, const char* path
, time_t modDate
)
396 std::vector
<dyld_image_state_change_handler
>* handlers
= stateToHandlers(state
, sSingleHandlers
);
397 if ( handlers
!= NULL
) {
398 dyld_image_info info
;
399 info
.imageLoadAddress
= mh
;
400 info
.imageFilePath
= path
;
401 info
.imageFileModDate
= modDate
;
402 for (std::vector
<dyld_image_state_change_handler
>::iterator it
= handlers
->begin(); it
!= handlers
->end(); ++it
) {
403 const char* result
= (*it
)(state
, 1, &info
);
404 if ( (result
!= NULL
) && (state
== dyld_image_state_mapped
) ) {
405 //fprintf(stderr, " image rejected by handler=%p\n", *it);
406 // make copy of thrown string so that later catch clauses can free it
407 const char* str
= strdup(result
);
416 static int imageSorter(const void* l
, const void* r
)
418 const ImageLoader
* left
= *((ImageLoader
**)l
);
419 const ImageLoader
* right
= *((ImageLoader
**)r
);
420 return left
->compare(right
);
423 static void notifyBatchPartial(dyld_image_states state
, bool orLater
, dyld_image_state_change_handler onlyHandler
)
425 std::vector
<dyld_image_state_change_handler
>* handlers
= stateToHandlers(state
, sBatchHandlers
);
426 if ( handlers
!= NULL
) {
427 // don't use a vector because it will use malloc/free and we want notifcation to be low cost
428 ImageLoader
* images
[sAllImages
.size()+1];
429 ImageLoader
** end
= images
;
430 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
431 dyld_image_states imageState
= (*it
)->getState();
432 if ( (imageState
== state
) || (orLater
&& (imageState
> state
)) )
435 if ( sBundleBeingLoaded
!= NULL
) {
436 dyld_image_states imageState
= sBundleBeingLoaded
->getState();
437 if ( (imageState
== state
) || (orLater
&& (imageState
> state
)) )
438 *end
++ = sBundleBeingLoaded
;
440 unsigned int count
= end
-images
;
441 if ( end
!= images
) {
443 qsort(images
, count
, sizeof(ImageLoader
*), &imageSorter
);
445 dyld_image_info infos
[count
];
446 for (unsigned int i
=0; i
< count
; ++i
) {
447 dyld_image_info
* p
= &infos
[i
];
448 ImageLoader
* image
= images
[i
];
449 //dyld::log(" state=%d, name=%s\n", state, image->getPath());
450 p
->imageLoadAddress
= image
->machHeader();
451 p
->imageFilePath
= image
->getPath();
452 p
->imageFileModDate
= image
->lastModified();
453 // special case for add_image hook
454 if ( state
== dyld_image_state_bound
)
455 notifyAddImageCallbacks(image
);
458 if ( onlyHandler
!= NULL
) {
459 const char* result
= (*onlyHandler
)(state
, count
, infos
);
460 if ( (result
!= NULL
) && (state
== dyld_image_state_dependents_mapped
) ) {
461 //fprintf(stderr, " images rejected by handler=%p\n", onlyHandler);
462 // make copy of thrown string so that later catch clauses can free it
463 const char* str
= strdup(result
);
468 // call each handler with whole array
469 for (std::vector
<dyld_image_state_change_handler
>::iterator it
= handlers
->begin(); it
!= handlers
->end(); ++it
) {
470 const char* result
= (*it
)(state
, count
, infos
);
471 if ( (result
!= NULL
) && (state
== dyld_image_state_dependents_mapped
) ) {
472 //fprintf(stderr, " images rejected by handler=%p\n", *it);
473 // make copy of thrown string so that later catch clauses can free it
474 const char* str
= strdup(result
);
483 static void notifyBatch(dyld_image_states state
)
485 notifyBatchPartial(state
, false, NULL
);
488 // In order for register_func_for_add_image() callbacks to to be called bottom up,
489 // we need to maintain a list of root images. The main executable is usally the
490 // first root. Any images dynamically added are also roots (unless already loaded).
491 // If DYLD_INSERT_LIBRARIES is used, those libraries are first.
492 static void addRootImage(ImageLoader
* image
)
494 //dyld::log("addRootImage(%p, %s)\n", image, image->getPath());
495 // add to list of roots
496 sImageRoots
.push_back(image
);
499 #if IMAGE_NOTIFY_SUPPORT
500 // Objective-C will contain a __DATA/__image_notify section which contains pointers to a function to call
501 // whenever any new image is loaded.
502 static void addImageNeedingNotification(ImageLoader
* image
)
504 sImagesToNotifyAboutOtherImages
.push_back(image
);
508 static void clearAllDepths()
510 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++)
514 static unsigned int imageCount()
516 return sAllImages
.size();
519 static void notifySharedCacheInvalid()
521 gSharedCacheNeedsUpdating
= true;
527 static void makeSharedCacheImportSegmentsWritable(bool writable
)
529 // if cache was built with read-only __IMPORT segments
530 if ( sImportSegmentsSize
!= 0 ) {
531 vm_prot_t prot
= VM_PROT_EXECUTE
| PROT_READ
;
533 prot
|= VM_PROT_WRITE
;
534 vm_protect(mach_task_self(), sImportSegmentsStart
, sImportSegmentsSize
, false, prot
);
535 if ( gLinkContext
.verboseMapping
) {
536 dyld::log("%18s at %p->%p altered permissions to %c%c%c\n", "", (char*)sImportSegmentsStart
, (char*)sImportSegmentsStart
+sImportSegmentsSize
-1,
537 (prot
& PROT_READ
) ? 'r' : '.', (prot
& PROT_WRITE
) ? 'w' : '.', (prot
& PROT_EXEC
) ? 'x' : '.' );
543 static void setNewProgramVars(const ProgramVars
& newVars
)
545 // make a copy of the pointers to program variables
546 gLinkContext
.programVars
= newVars
;
548 // now set each program global to their initial value
549 *gLinkContext
.programVars
.NXArgcPtr
= gLinkContext
.argc
;
550 *gLinkContext
.programVars
.NXArgvPtr
= gLinkContext
.argv
;
551 *gLinkContext
.programVars
.environPtr
= gLinkContext
.envp
;
552 *gLinkContext
.programVars
.__prognamePtr
= gLinkContext
.progname
;
555 #if SUPPORT_OLD_CRT_INITIALIZATION
556 static void setRunInitialzersOldWay()
558 gRunInitializersOldWay
= true;
562 static void addImage(ImageLoader
* image
)
564 // add to master list
565 sAllImages
.push_back(image
);
567 if ( sEnv
.DYLD_PRINT_LIBRARIES
|| (sEnv
.DYLD_PRINT_LIBRARIES_POST_LAUNCH
&& (sMainExecutable
!=NULL
) && sMainExecutable
->isLinked()) ) {
568 dyld::log("dyld: loaded: %s\n", image
->getPath());
571 #if OLD_GDB_DYLD_INTERFACE
572 // let gdb find out about this
573 addImageForgdb(image
->machHeader(), image
->getSlide(), image
->getPath(), image
->getLogicalPath());
577 void removeImage(ImageLoader
* image
)
579 // if in termination list, pull it out and run terminator
580 for (std::vector
<ImageLoader
*>::iterator it
=sImageFilesNeedingTermination
.begin(); it
!= sImageFilesNeedingTermination
.end(); it
++) {
581 if ( *it
== image
) {
582 sImageFilesNeedingTermination
.erase(it
);
583 image
->doTermination(gLinkContext
);
588 // if has dtrace DOF section, tell dtrace it is going away, then remove from sImageFilesNeedingDOFUnregistration
589 for (std::vector
<RegisteredDOF
>::iterator it
=sImageFilesNeedingDOFUnregistration
.begin(); it
!= sImageFilesNeedingDOFUnregistration
.end(); ) {
590 if ( it
->mh
== image
->machHeader() ) {
591 unregisterDOF(it
->registrationID
);
592 sImageFilesNeedingDOFUnregistration
.erase(it
);
593 // don't increment iterator, the erase caused next element to be copied to where this iterator points
600 // tell all register add image handlers about this
601 // do this before removing image from internal data structures so that the callback can query dyld about the image
602 if ( image
->getState() >= dyld_image_state_bound
) {
603 for (std::vector
<ImageCallback
>::iterator it
=sRemoveImageCallbacks
.begin(); it
!= sRemoveImageCallbacks
.end(); it
++) {
604 (*it
)(image
->machHeader(), image
->getSlide());
608 #if IMAGE_NOTIFY_SUPPORT
609 // tell all interested images
610 for (std::vector
<ImageLoader
*>::iterator it
=sImagesToNotifyAboutOtherImages
.begin(); it
!= sImagesToNotifyAboutOtherImages
.end(); it
++) {
611 dyld_image_info info
;
612 info
.imageLoadAddress
= image
->machHeader();
613 info
.imageFilePath
= image
->getPath();
614 info
.imageFileModDate
= image
->lastModified();
615 (*it
)->doNotification(dyld_image_removing
, 1, &info
);
619 // remove from master list
620 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
621 if ( *it
== image
) {
622 sAllImages
.erase(it
);
627 // flush find-by-address cache (do this after removed from master list, so there is no chance it can come back)
628 if ( sLastImageByAddressCache
== image
)
629 sLastImageByAddressCache
= NULL
;
631 #if IMAGE_NOTIFY_SUPPORT
632 // if in announcement list, pull it out
633 for (std::vector
<ImageLoader
*>::iterator it
=sImagesToNotifyAboutOtherImages
.begin(); it
!= sImagesToNotifyAboutOtherImages
.end(); it
++) {
634 if ( *it
== image
) {
635 sImagesToNotifyAboutOtherImages
.erase(it
);
641 // if in root list, pull it out
642 for (std::vector
<ImageLoader
*>::iterator it
=sImageRoots
.begin(); it
!= sImageRoots
.end(); it
++) {
643 if ( *it
== image
) {
644 sImageRoots
.erase(it
);
650 if ( sEnv
.DYLD_PRINT_LIBRARIES
|| (sEnv
.DYLD_PRINT_LIBRARIES_POST_LAUNCH
&& (sMainExecutable
!=NULL
) && sMainExecutable
->isLinked()) ) {
651 dyld::log("dyld: unloaded: %s\n", image
->getPath());
655 removeImageFromAllImages(image
->machHeader());
657 #if OLD_GDB_DYLD_INTERFACE
659 removeImageForgdb(image
->machHeader());
660 gdb_dyld_state_changed();
665 static void terminationRecorder(ImageLoader
* image
)
667 sImageFilesNeedingTermination
.push_back(image
);
670 const char* getExecutablePath()
676 void initializeMainExecutable()
680 // make all __IMPORT segments in the shared cache read-only
681 // before executing any code
682 makeSharedCacheImportSegmentsWritable(false);
685 // run initialzers for any inserted dylibs
686 const int rootCount
= sImageRoots
.size();
687 if ( rootCount
> 1 ) {
688 for(int i
=1; i
< rootCount
; ++i
)
689 sImageRoots
[i
]->runInitializers(gLinkContext
);
692 // run initializers for main executable and everything it brings up
693 sMainExecutable
->runInitializers(gLinkContext
);
695 // register atexit() handler to run terminators in all loaded images when this process exits
696 if ( gLibSystemHelpers
!= NULL
)
697 (*gLibSystemHelpers
->cxa_atexit
)(&runTerminators
, NULL
, NULL
);
699 // dump info if requested
700 if ( sEnv
.DYLD_PRINT_STATISTICS
)
701 ImageLoaderMachO::printStatistics(sAllImages
.size());
704 bool mainExecutablePrebound()
706 return sMainExecutable
->usablePrebinding(gLinkContext
);
709 ImageLoader
* mainExecutable()
711 return sMainExecutable
;
715 void runTerminators(void* extra
)
717 const unsigned int imageCount
= sImageFilesNeedingTermination
.size();
718 for(unsigned int i
=imageCount
; i
> 0; --i
){
719 ImageLoader
* image
= sImageFilesNeedingTermination
[i
-1];
720 image
->doTermination(gLinkContext
);
721 notifySingle(dyld_image_state_terminated
, image
->machHeader(), image
->getPath(), image
->lastModified());
723 sImageFilesNeedingTermination
.clear();
724 notifyBatch(dyld_image_state_terminated
);
729 // Turns a colon separated list of strings
730 // into a NULL terminated array of string
733 static const char** parseColonList(const char* list
)
735 if ( list
[0] == '\0' )
739 for(const char* s
=list
; *s
!= '\0'; ++s
) {
745 const char* start
= list
;
746 char** result
= new char*[colonCount
+2];
747 for(const char* s
=list
; *s
!= '\0'; ++s
) {
750 char* str
= new char[len
+1];
751 strncpy(str
, start
, len
);
754 result
[index
++] = str
;
757 int len
= strlen(start
);
758 char* str
= new char[len
+1];
760 result
[index
++] = str
;
761 result
[index
] = NULL
;
763 return (const char**)result
;
767 static void paths_expand_roots(const char **paths
, const char *key
, const char *val
)
769 // assert(val != NULL);
770 // assert(paths != NULL);
772 size_t keyLen
= strlen(key
);
773 for(int i
=0; paths
[i
] != NULL
; ++i
) {
774 if ( strncmp(paths
[i
], key
, keyLen
) == 0 ) {
775 char* newPath
= new char[strlen(val
) + (strlen(paths
[i
]) - keyLen
) + 1];
776 strcpy(newPath
, val
);
777 strcat(newPath
, &paths
[i
][keyLen
]);
785 static void removePathWithPrefix(const char* paths
[], const char* prefix
)
787 size_t prefixLen
= strlen(prefix
);
790 for(i
= 0; paths
[i
] != NULL
; ++i
) {
791 if ( strncmp(paths
[i
], prefix
, prefixLen
) == 0 )
794 paths
[i
-skip
] = paths
[i
];
796 paths
[i
-skip
] = NULL
;
801 static void paths_dump(const char **paths
)
803 // assert(paths != NULL);
804 const char **strs
= paths
;
807 dyld::log("\"%s\"\n", *strs
);
814 static void printOptions(const char* argv
[])
817 while ( NULL
!= argv
[i
] ) {
818 dyld::log("opt[%i] = \"%s\"\n", i
, argv
[i
]);
823 static void printEnvironmentVariables(const char* envp
[])
825 while ( NULL
!= *envp
) {
826 dyld::log("%s\n", *envp
);
831 void processDyldEnvironmentVarible(const char* key
, const char* value
)
833 if ( strcmp(key
, "DYLD_FRAMEWORK_PATH") == 0 ) {
834 sEnv
.DYLD_FRAMEWORK_PATH
= parseColonList(value
);
835 gSharedCacheDontNotify
= true;
837 else if ( strcmp(key
, "DYLD_FALLBACK_FRAMEWORK_PATH") == 0 ) {
838 sEnv
.DYLD_FALLBACK_FRAMEWORK_PATH
= parseColonList(value
);
839 gSharedCacheDontNotify
= true;
841 else if ( strcmp(key
, "DYLD_LIBRARY_PATH") == 0 ) {
842 sEnv
.DYLD_LIBRARY_PATH
= parseColonList(value
);
843 gSharedCacheDontNotify
= true;
845 else if ( strcmp(key
, "DYLD_FALLBACK_LIBRARY_PATH") == 0 ) {
846 sEnv
.DYLD_FALLBACK_LIBRARY_PATH
= parseColonList(value
);
847 gSharedCacheDontNotify
= true;
849 else if ( (strcmp(key
, "DYLD_ROOT_PATH") == 0) || (strcmp(key
, "DYLD_PATHS_ROOT") == 0) ) {
850 gSharedCacheDontNotify
= true;
851 if ( strcmp(value
, "/") != 0 ) {
852 sEnv
.DYLD_ROOT_PATH
= parseColonList(value
);
853 for (int i
=0; sEnv
.DYLD_ROOT_PATH
[i
] != NULL
; ++i
) {
854 if ( sEnv
.DYLD_ROOT_PATH
[i
][0] != '/' ) {
855 dyld::warn("DYLD_ROOT_PATH not used because it contains a non-absolute path\n");
856 sEnv
.DYLD_ROOT_PATH
= NULL
;
862 else if ( strcmp(key
, "DYLD_IMAGE_SUFFIX") == 0 ) {
863 gSharedCacheDontNotify
= true;
864 gLinkContext
.imageSuffix
= value
;
866 else if ( strcmp(key
, "DYLD_INSERT_LIBRARIES") == 0 ) {
867 sEnv
.DYLD_INSERT_LIBRARIES
= parseColonList(value
);
868 gSharedCacheDontNotify
= true;
870 else if ( strcmp(key
, "DYLD_PRINT_OPTS") == 0 ) {
871 sEnv
.DYLD_PRINT_OPTS
= true;
873 else if ( strcmp(key
, "DYLD_PRINT_ENV") == 0 ) {
874 sEnv
.DYLD_PRINT_ENV
= true;
876 else if ( strcmp(key
, "DYLD_DISABLE_DOFS") == 0 ) {
877 sEnv
.DYLD_DISABLE_DOFS
= true;
879 else if ( strcmp(key
, "DYLD_DISABLE_PREFETCH") == 0 ) {
880 gLinkContext
.preFetchDisabled
= true;
882 else if ( strcmp(key
, "DYLD_PRINT_LIBRARIES") == 0 ) {
883 sEnv
.DYLD_PRINT_LIBRARIES
= true;
885 else if ( strcmp(key
, "DYLD_PRINT_LIBRARIES_POST_LAUNCH") == 0 ) {
886 sEnv
.DYLD_PRINT_LIBRARIES_POST_LAUNCH
= true;
888 else if ( strcmp(key
, "DYLD_BIND_AT_LAUNCH") == 0 ) {
889 sEnv
.DYLD_BIND_AT_LAUNCH
= true;
891 else if ( strcmp(key
, "DYLD_FORCE_FLAT_NAMESPACE") == 0 ) {
892 gLinkContext
.bindFlat
= true;
894 else if ( strcmp(key
, "DYLD_NEW_LOCAL_SHARED_REGIONS") == 0 ) {
895 // ignore, no longer relevant but some scripts still set it
897 else if ( strcmp(key
, "DYLD_NO_FIX_PREBINDING") == 0 ) {
898 gSharedCacheDontNotify
= true;
900 else if ( strcmp(key
, "DYLD_PREBIND_DEBUG") == 0 ) {
901 gLinkContext
.verbosePrebinding
= true;
903 else if ( strcmp(key
, "DYLD_PRINT_INITIALIZERS") == 0 ) {
904 gLinkContext
.verboseInit
= true;
906 else if ( strcmp(key
, "DYLD_PRINT_DOFS") == 0 ) {
907 gLinkContext
.verboseDOF
= true;
909 else if ( strcmp(key
, "DYLD_PRINT_STATISTICS") == 0 ) {
910 sEnv
.DYLD_PRINT_STATISTICS
= true;
912 else if ( strcmp(key
, "DYLD_PRINT_SEGMENTS") == 0 ) {
913 gLinkContext
.verboseMapping
= true;
915 else if ( strcmp(key
, "DYLD_PRINT_BINDINGS") == 0 ) {
916 gLinkContext
.verboseBind
= true;
918 else if ( strcmp(key
, "DYLD_PRINT_REBASINGS") == 0 ) {
919 gLinkContext
.verboseRebase
= true;
921 else if ( strcmp(key
, "DYLD_PRINT_APIS") == 0 ) {
924 else if ( strcmp(key
, "DYLD_PRINT_WARNINGS") == 0 ) {
925 gLinkContext
.verboseWarnings
= true;
927 else if ( strcmp(key
, "DYLD_SHARED_REGION") == 0 ) {
928 gSharedCacheDontNotify
= true;
929 if ( strcmp(value
, "private") == 0 ) {
930 gLinkContext
.sharedRegionMode
= ImageLoader::kUsePrivateSharedRegion
;
932 else if ( strcmp(value
, "avoid") == 0 ) {
933 gLinkContext
.sharedRegionMode
= ImageLoader::kDontUseSharedRegion
;
935 else if ( strcmp(value
, "use") == 0 ) {
936 gLinkContext
.sharedRegionMode
= ImageLoader::kUseSharedRegion
;
938 else if ( value
[0] == '\0' ) {
939 gLinkContext
.sharedRegionMode
= ImageLoader::kUseSharedRegion
;
942 dyld::warn("unknown option to DYLD_SHARED_REGION. Valid options are: use, private, avoid\n");
945 else if ( strcmp(key
, "DYLD_IGNORE_PREBINDING") == 0 ) {
946 gSharedCacheDontNotify
= true;
947 if ( strcmp(value
, "all") == 0 ) {
948 gLinkContext
.prebindUsage
= ImageLoader::kUseNoPrebinding
;
950 else if ( strcmp(value
, "app") == 0 ) {
951 gLinkContext
.prebindUsage
= ImageLoader::kUseAllButAppPredbinding
;
953 else if ( strcmp(value
, "nonsplit") == 0 ) {
954 gLinkContext
.prebindUsage
= ImageLoader::kUseSplitSegPrebinding
;
956 else if ( value
[0] == '\0' ) {
957 gLinkContext
.prebindUsage
= ImageLoader::kUseSplitSegPrebinding
;
960 dyld::warn("unknown option to DYLD_IGNORE_PREBINDING. Valid options are: all, app, nonsplit\n");
964 dyld::warn("unknown environment variable: %s\n", key
);
970 // For security, setuid programs ignore DYLD_* environment variables.
971 // Additionally, the DYLD_* enviroment variables are removed
972 // from the environment, so that any child processes don't see them.
974 static void pruneEnvironmentVariables(const char* envp
[], const char*** applep
)
976 // setuit binaries don't trigger a cache rebuild
977 gSharedCacheDontNotify
= true;
979 // delete all DYLD_* and LD_LIBRARY_PATH environment variables
980 int removedCount
= 0;
981 const char** d
= envp
;
982 for(const char** s
= envp
; *s
!= NULL
; s
++) {
983 if ( (strncmp(*s
, "DYLD_", 5) != 0) && (strncmp(*s
, "LD_LIBRARY_PATH=", 16) != 0) ) {
992 // slide apple parameters
993 if ( removedCount
> 0 ) {
996 *d
= d
[removedCount
];
997 } while ( *d
++ != NULL
);
1000 // disable framework and library fallback paths for setuid binaries rdar://problem/4589305
1001 sEnv
.DYLD_FALLBACK_FRAMEWORK_PATH
= NULL
;
1002 sEnv
.DYLD_FALLBACK_LIBRARY_PATH
= NULL
;
1006 static void checkEnvironmentVariables(const char* envp
[], bool ignoreEnviron
)
1008 const char* home
= NULL
;
1010 for(p
= envp
; *p
!= NULL
; p
++) {
1011 const char* keyEqualsValue
= *p
;
1012 if ( strncmp(keyEqualsValue
, "DYLD_", 5) == 0 ) {
1013 const char* equals
= strchr(keyEqualsValue
, '=');
1014 if ( (equals
!= NULL
) && !ignoreEnviron
) {
1015 const char* value
= &equals
[1];
1016 const int keyLen
= equals
-keyEqualsValue
;
1018 strncpy(key
, keyEqualsValue
, keyLen
);
1020 processDyldEnvironmentVarible(key
, value
);
1023 else if ( strncmp(keyEqualsValue
, "HOME=", 5) == 0 ) {
1024 home
= &keyEqualsValue
[5];
1026 else if ( strncmp(keyEqualsValue
, "LD_LIBRARY_PATH=", 16) == 0 ) {
1027 const char* path
= &keyEqualsValue
[16];
1028 sEnv
.LD_LIBRARY_PATH
= parseColonList(path
);
1032 // default value for DYLD_FALLBACK_FRAMEWORK_PATH, if not set in environment
1033 if ( sEnv
.DYLD_FALLBACK_FRAMEWORK_PATH
== NULL
) {
1034 const char** paths
= sFrameworkFallbackPaths
;
1036 removePathWithPrefix(paths
, "$HOME");
1038 paths_expand_roots(paths
, "$HOME", home
);
1039 sEnv
.DYLD_FALLBACK_FRAMEWORK_PATH
= paths
;
1042 // default value for DYLD_FALLBACK_LIBRARY_PATH, if not set in environment
1043 if ( sEnv
.DYLD_FALLBACK_LIBRARY_PATH
== NULL
) {
1044 const char** paths
= sLibraryFallbackPaths
;
1046 removePathWithPrefix(paths
, "$HOME");
1048 paths_expand_roots(paths
, "$HOME", home
);
1049 sEnv
.DYLD_FALLBACK_LIBRARY_PATH
= paths
;
1054 static void getHostInfo()
1057 struct host_basic_info info
;
1058 mach_msg_type_number_t count
= HOST_BASIC_INFO_COUNT
;
1059 mach_port_t hostPort
= mach_host_self();
1060 kern_return_t result
= host_info(hostPort
, HOST_BASIC_INFO
, (host_info_t
)&info
, &count
);
1061 mach_port_deallocate(mach_task_self(), hostPort
);
1062 if ( result
!= KERN_SUCCESS
)
1063 throw "host_info() failed";
1065 sHostCPU
= info
.cpu_type
;
1066 sHostCPUsubtype
= info
.cpu_subtype
;
1068 size_t valSize
= sizeof(sHostCPU
);
1069 if (sysctlbyname ("hw.cputype", &sHostCPU
, &valSize
, NULL
, 0) != 0)
1070 throw "sysctlbyname(hw.cputype) failed";
1071 valSize
= sizeof(sHostCPUsubtype
);
1072 if (sysctlbyname ("hw.cpusubtype", &sHostCPUsubtype
, &valSize
, NULL
, 0) != 0)
1073 throw "sysctlbyname(hw.cpusubtype) failed";
1077 static void checkSharedRegionDisable()
1079 #if __ppc__ || __i386__
1080 // if main executable has segments that overlap the shared region,
1081 // then disable using the shared region
1082 if ( sMainExecutable
->overlapsWithAddressRange((void*)0x90000000, (void*)0xAFFFFFFF) ) {
1083 gLinkContext
.sharedRegionMode
= ImageLoader::kDontUseSharedRegion
;
1084 if ( gLinkContext
.verboseMapping
)
1085 dyld::warn("disabling shared region because main executable overlaps\n");
1090 bool validImage(const ImageLoader
* possibleImage
)
1092 const unsigned int imageCount
= sAllImages
.size();
1093 for(unsigned int i
=0; i
< imageCount
; ++i
) {
1094 if ( possibleImage
== sAllImages
[i
] ) {
1101 uint32_t getImageCount()
1103 return sAllImages
.size();
1106 ImageLoader
* getIndexedImage(unsigned int index
)
1108 if ( index
< sAllImages
.size() )
1109 return sAllImages
[index
];
1113 ImageLoader
* findImageByMachHeader(const struct mach_header
* target
)
1115 const unsigned int imageCount
= sAllImages
.size();
1116 for(unsigned int i
=0; i
< imageCount
; ++i
) {
1117 ImageLoader
* anImage
= sAllImages
[i
];
1118 if ( anImage
->machHeader() == target
)
1125 ImageLoader
* findImageContainingAddress(const void* addr
)
1128 static int cacheHit
= 0;
1129 static int cacheMiss
= 0;
1130 static int cacheNotMacho
= 0;
1131 if ( ((cacheHit
+cacheMiss
+cacheNotMacho
) % 100) == 0 )
1132 dyld::log("findImageContainingAddress(): cache hit = %d, miss = %d, unknown = %d\n", cacheHit
, cacheMiss
, cacheNotMacho
);
1134 // first look in image where last address was found rdar://problem/3685517
1135 if ( (sLastImageByAddressCache
!= NULL
) && sLastImageByAddressCache
->containsAddress(addr
) ) {
1139 return sLastImageByAddressCache
;
1141 // do exhastive search
1142 // todo: consider maintaining a list sorted by address ranges and do a binary search on that
1143 const unsigned int imageCount
= sAllImages
.size();
1144 for(unsigned int i
=0; i
< imageCount
; ++i
) {
1145 ImageLoader
* anImage
= sAllImages
[i
];
1146 if ( anImage
->containsAddress(addr
) ) {
1147 sLastImageByAddressCache
= anImage
;
1160 ImageLoader
* findImageContainingAddressThreadSafe(const void* addr
)
1162 // do exhastive search
1163 // todo: consider maintaining a list sorted by address ranges and do a binary search on that
1164 const unsigned int imageCount
= sAllImages
.size();
1165 for(unsigned int i
=0; i
< imageCount
; ++i
) {
1166 ImageLoader
* anImage
= sAllImages
[i
];
1167 if ( anImage
->containsAddress(addr
) ) {
1175 void forEachImageDo( void (*callback
)(ImageLoader
*, void* userData
), void* userData
)
1177 const unsigned int imageCount
= sAllImages
.size();
1178 for(unsigned int i
=0; i
< imageCount
; ++i
) {
1179 ImageLoader
* anImage
= sAllImages
[i
];
1180 (*callback
)(anImage
, userData
);
1184 ImageLoader
* findLoadedImage(const struct stat
& stat_buf
)
1186 const unsigned int imageCount
= sAllImages
.size();
1187 for(unsigned int i
=0; i
< imageCount
; ++i
){
1188 ImageLoader
* anImage
= sAllImages
[i
];
1189 if ( anImage
->statMatch(stat_buf
) )
1195 // based on ANSI-C strstr()
1196 static const char* strrstr(const char* str
, const char* sub
)
1198 const int sublen
= strlen(sub
);
1199 for(const char* p
= &str
[strlen(str
)]; p
!= str
; --p
) {
1200 if ( strncmp(p
, sub
, sublen
) == 0 )
1208 // Find framework path
1210 // /path/foo.framework/foo => foo.framework/foo
1211 // /path/foo.framework/Versions/A/foo => foo.framework/Versions/A/foo
1212 // /path/foo.framework/Frameworks/bar.framework/bar => bar.framework/bar
1213 // /path/foo.framework/Libraries/bar.dylb => NULL
1214 // /path/foo.framework/bar => NULL
1216 // Returns NULL if not a framework path
1218 static const char* getFrameworkPartialPath(const char* path
)
1220 const char* dirDot
= strrstr(path
, ".framework/");
1221 if ( dirDot
!= NULL
) {
1222 const char* dirStart
= dirDot
;
1223 for ( ; dirStart
>= path
; --dirStart
) {
1224 if ( (*dirStart
== '/') || (dirStart
== path
) ) {
1225 const char* frameworkStart
= &dirStart
[1];
1226 if ( dirStart
== path
)
1228 int len
= dirDot
- frameworkStart
;
1229 char framework
[len
+1];
1230 strncpy(framework
, frameworkStart
, len
);
1231 framework
[len
] = '\0';
1232 const char* leaf
= strrchr(path
, '/');
1233 if ( leaf
!= NULL
) {
1234 if ( strcmp(framework
, &leaf
[1]) == 0 ) {
1235 return frameworkStart
;
1237 if ( gLinkContext
.imageSuffix
!= NULL
) {
1238 // some debug frameworks have install names that end in _debug
1239 if ( strncmp(framework
, &leaf
[1], len
) == 0 ) {
1240 if ( strcmp( gLinkContext
.imageSuffix
, &leaf
[len
+1]) == 0 )
1241 return frameworkStart
;
1252 static const char* getLibraryLeafName(const char* path
)
1254 const char* start
= strrchr(path
, '/');
1255 if ( start
!= NULL
)
1262 // only for architectures that use cpu-sub-types
1263 #if CPU_SUBTYPES_SUPPORTED
1265 const cpu_subtype_t CPU_SUBTYPE_END_OF_LIST
= -1;
1269 // A fat file may contain multiple sub-images for the same CPU type.
1270 // In that case, dyld picks which sub-image to use by scanning a table
1271 // of preferred cpu-sub-types for the running cpu.
1273 // There is one row in the table for each cpu-sub-type on which dyld might run.
1274 // The first entry in a row is that cpu-sub-type. It is followed by all
1275 // cpu-sub-types that can run on that cpu, if preferred order. Each row ends with
1276 // a "SUBTYPE_ALL" (to denote that images written to run on any cpu-sub-type are usable),
1277 // followed by one or more CPU_SUBTYPE_END_OF_LIST to pad out this row.
1282 // 32-bit PowerPC sub-type lists
1284 const int kPPC_RowCount
= 4;
1285 static const cpu_subtype_t kPPC32
[kPPC_RowCount
][6] = {
1286 // G5 can run any code
1287 { 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
},
1289 // G4 can run all but G5 code
1290 { 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
},
1291 { 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
},
1293 // G3 cannot run G4 or G5 code
1294 { 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
}
1299 // scan the tables above to find the cpu-sub-type-list for this machine
1300 static const cpu_subtype_t
* findCPUSubtypeList(cpu_type_t cpu
, cpu_subtype_t subtype
)
1303 case CPU_TYPE_POWERPC
:
1304 for (int i
=0; i
< kPPC_RowCount
; ++i
) {
1305 if ( kPPC32
[i
][0] == subtype
)
1316 // scan fat table-of-contents for best most preferred subtype
1317 static bool fatFindBestFromOrderedList(cpu_type_t cpu
, const cpu_subtype_t list
[], const fat_header
* fh
, uint64_t* offset
, uint64_t* len
)
1319 const fat_arch
* const archs
= (fat_arch
*)(((char*)fh
)+sizeof(fat_header
));
1320 for (uint32_t subTypeIndex
=0; list
[subTypeIndex
] != CPU_SUBTYPE_END_OF_LIST
; ++subTypeIndex
) {
1321 for(uint32_t fatIndex
=0; fatIndex
< OSSwapBigToHostInt32(fh
->nfat_arch
); ++fatIndex
) {
1322 if ( ((cpu_type_t
)OSSwapBigToHostInt32(archs
[fatIndex
].cputype
) == cpu
)
1323 && (list
[subTypeIndex
] == (cpu_subtype_t
)OSSwapBigToHostInt32(archs
[fatIndex
].cpusubtype
)) ) {
1324 *offset
= OSSwapBigToHostInt32(archs
[fatIndex
].offset
);
1325 *len
= OSSwapBigToHostInt32(archs
[fatIndex
].size
);
1333 // scan fat table-of-contents for exact match of cpu and cpu-sub-type
1334 static bool fatFindExactMatch(cpu_type_t cpu
, cpu_subtype_t subtype
, const fat_header
* fh
, uint64_t* offset
, uint64_t* len
)
1336 const fat_arch
* archs
= (fat_arch
*)(((char*)fh
)+sizeof(fat_header
));
1337 for(uint32_t i
=0; i
< OSSwapBigToHostInt32(fh
->nfat_arch
); ++i
) {
1338 if ( ((cpu_type_t
)OSSwapBigToHostInt32(archs
[i
].cputype
) == cpu
)
1339 && ((cpu_subtype_t
)OSSwapBigToHostInt32(archs
[i
].cpusubtype
) == subtype
) ) {
1340 *offset
= OSSwapBigToHostInt32(archs
[i
].offset
);
1341 *len
= OSSwapBigToHostInt32(archs
[i
].size
);
1348 // scan fat table-of-contents for image with matching cpu-type and runs-on-all-sub-types
1349 static bool fatFindRunsOnAllCPUs(cpu_type_t cpu
, const fat_header
* fh
, uint64_t* offset
, uint64_t* len
)
1351 const fat_arch
* archs
= (fat_arch
*)(((char*)fh
)+sizeof(fat_header
));
1352 for(uint32_t i
=0; i
< OSSwapBigToHostInt32(fh
->nfat_arch
); ++i
) {
1353 if ( (cpu_type_t
)OSSwapBigToHostInt32(archs
[i
].cputype
) == cpu
) {
1355 case CPU_TYPE_POWERPC
:
1356 if ( (cpu_subtype_t
)OSSwapBigToHostInt32(archs
[i
].cpusubtype
) == CPU_SUBTYPE_POWERPC_ALL
) {
1357 *offset
= OSSwapBigToHostInt32(archs
[i
].offset
);
1358 *len
= OSSwapBigToHostInt32(archs
[i
].size
);
1368 #endif // CPU_SUBTYPES_SUPPORTED
1371 // A fat file may contain multiple sub-images for the same cpu-type,
1372 // each optimized for a different cpu-sub-type (e.g G3 or G5).
1373 // This routine picks the optimal sub-image.
1375 static bool fatFindBest(const fat_header
* fh
, uint64_t* offset
, uint64_t* len
)
1377 #if CPU_SUBTYPES_SUPPORTED
1378 // assume all dylibs loaded must have same cpu type as main executable
1379 const cpu_type_t cpu
= sMainExecutableMachHeader
->cputype
;
1381 // We only know the subtype to use if the main executable cpu type matches the host
1382 if ( (cpu
& CPU_TYPE_MASK
) == sHostCPU
) {
1383 // get preference ordered list of subtypes
1384 const cpu_subtype_t
* subTypePreferenceList
= findCPUSubtypeList(cpu
, sHostCPUsubtype
);
1386 // use ordered list to find best sub-image in fat file
1387 if ( subTypePreferenceList
!= NULL
)
1388 return fatFindBestFromOrderedList(cpu
, subTypePreferenceList
, fh
, offset
, len
);
1390 // if running cpu is not in list, try for an exact match
1391 if ( fatFindExactMatch(cpu
, sHostCPUsubtype
, fh
, offset
, len
) )
1395 // running on an uknown cpu, can only load generic code
1396 return fatFindRunsOnAllCPUs(cpu
, fh
, offset
, len
);
1398 // just find first slice with matching architecture
1399 const fat_arch
* archs
= (fat_arch
*)(((char*)fh
)+sizeof(fat_header
));
1400 for(uint32_t i
=0; i
< OSSwapBigToHostInt32(fh
->nfat_arch
); ++i
) {
1401 if ( (cpu_type_t
)OSSwapBigToHostInt32(archs
[i
].cputype
) == sMainExecutableMachHeader
->cputype
) {
1402 *offset
= OSSwapBigToHostInt32(archs
[i
].offset
);
1403 *len
= OSSwapBigToHostInt32(archs
[i
].size
);
1414 // This is used to validate if a non-fat (aka thin or raw) mach-o file can be used
1415 // on the current processor. //
1416 bool isCompatibleMachO(const uint8_t* firstPage
)
1418 #if CPU_SUBTYPES_SUPPORTED
1419 // It is deemed compatible if any of the following are true:
1420 // 1) mach_header subtype is in list of compatible subtypes for running processor
1421 // 2) mach_header subtype is same as running processor subtype
1422 // 3) mach_header subtype runs on all processor variants
1423 const mach_header
* mh
= (mach_header
*)firstPage
;
1424 if ( mh
->magic
== sMainExecutableMachHeader
->magic
) {
1425 if ( mh
->cputype
== sMainExecutableMachHeader
->cputype
) {
1426 if ( (mh
->cputype
& CPU_TYPE_MASK
) == sHostCPU
) {
1427 // get preference ordered list of subtypes that this machine can use
1428 const cpu_subtype_t
* subTypePreferenceList
= findCPUSubtypeList(mh
->cputype
, sHostCPUsubtype
);
1429 if ( subTypePreferenceList
!= NULL
) {
1430 // if image's subtype is in the list, it is compatible
1431 for (const cpu_subtype_t
* p
= subTypePreferenceList
; *p
!= CPU_SUBTYPE_END_OF_LIST
; ++p
) {
1432 if ( *p
== mh
->cpusubtype
)
1435 // have list and not in list, so not compatible
1436 throw "incompatible cpu-subtype";
1438 // unknown cpu sub-type, but if exact match for current subtype then ok to use
1439 if ( mh
->cpusubtype
== sHostCPUsubtype
)
1443 // cpu type has no ordered list of subtypes
1444 switch (mh
->cputype
) {
1445 case CPU_TYPE_POWERPC
:
1446 // allow _ALL to be used by any client
1447 if ( mh
->cpusubtype
== CPU_SUBTYPE_POWERPC_ALL
)
1450 case CPU_TYPE_POWERPC64
:
1452 case CPU_TYPE_X86_64
:
1453 // subtypes are not used or these architectures
1459 // For architectures that don't support cpu-sub-types
1460 // this just check the cpu type.
1461 const mach_header
* mh
= (mach_header
*)firstPage
;
1462 if ( mh
->magic
== sMainExecutableMachHeader
->magic
) {
1463 if ( mh
->cputype
== sMainExecutableMachHeader
->cputype
) {
1474 // The kernel maps in main executable before dyld gets control. We need to
1475 // make an ImageLoader* for the already mapped in main executable.
1476 static ImageLoader
* instantiateFromLoadedImage(const struct mach_header
* mh
, uintptr_t slide
, const char* path
)
1478 // try mach-o loader
1479 if ( isCompatibleMachO((const uint8_t*)mh
) ) {
1480 ImageLoader
* image
= new ImageLoaderMachO(mh
, slide
, path
, gLinkContext
);
1485 throw "main executable not a known format";
1488 #if DYLD_SHARED_CACHE_SUPPORT
1489 static ImageLoader
* findSharedCacheImage(const struct stat
& stat_buf
, const char* path
)
1491 if ( sSharedCache
!= NULL
) {
1492 // walk shared cache to see if there is a cached image that matches the inode/mtime/path desired
1493 const dyld_cache_image_info
* const start
= (dyld_cache_image_info
*)((uint8_t*)sSharedCache
+ sSharedCache
->imagesOffset
);
1494 const dyld_cache_image_info
* const end
= &start
[sSharedCache
->imagesCount
];
1495 for( const dyld_cache_image_info
* p
= start
; p
!= end
; ++p
) {
1496 // check mtime and inode first because it is fast
1497 if ( ((time_t)p
->modTime
== stat_buf
.st_mtime
) && ((ino_t
)p
->inode
== stat_buf
.st_ino
) ) {
1498 // mod-time and inode match an image in the shared cache, now check path
1499 const char* pathInCache
= (char*)sSharedCache
+ p
->pathFileOffset
;
1500 bool cacheHit
= (strcmp(path
, pathInCache
) == 0);
1502 // path does not match install name of dylib in cache, but inode and mtime does match
1503 // perhaps path is a symlink to the cached dylib
1504 struct stat pathInCacheStatBuf
;
1505 if ( stat(pathInCache
, &pathInCacheStatBuf
) != -1 )
1506 cacheHit
= ( (pathInCacheStatBuf
.st_dev
== stat_buf
.st_dev
) && (pathInCacheStatBuf
.st_ino
== stat_buf
.st_ino
) );
1509 // found image in cache, instantiate an ImageLoader with it
1510 return new ImageLoaderMachO((struct mach_header
*)(p
->address
), pathInCache
, stat_buf
, gLinkContext
);
1519 static ImageLoader
* checkandAddImage(ImageLoader
* image
, const LoadContext
& context
)
1521 // now sanity check that this loaded image does not have the same install path as any existing image
1522 const char* loadedImageInstallPath
= image
->getInstallPath();
1523 if ( image
->isDylib() && (loadedImageInstallPath
!= NULL
) && (loadedImageInstallPath
[0] == '/') ) {
1524 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
1525 ImageLoader
* anImage
= *it
;
1526 const char* installPath
= anImage
->getInstallPath();
1527 if ( installPath
!= NULL
) {
1528 if ( strcmp(loadedImageInstallPath
, installPath
) == 0 ) {
1529 //dyld::log("duplicate(%s) => %p\n", installPath, anImage);
1537 // some API's restrict what they can load
1538 if ( context
.mustBeBundle
&& !image
->isBundle() )
1539 throw "not a bundle";
1540 if ( context
.mustBeDylib
&& !image
->isDylib() )
1541 throw "not a dylib";
1543 // don't add bundles to global list, they can be loaded but not linked. When linked it will be added to list
1544 if ( ! image
->isBundle() )
1550 // map in file and instantiate an ImageLoader
1551 static ImageLoader
* loadPhase6(int fd
, struct stat
& stat_buf
, const char* path
, const LoadContext
& context
)
1553 //dyld::log("%s(%s)\n", __func__ , path);
1554 uint64_t fileOffset
= 0;
1555 uint64_t fileLength
= stat_buf
.st_size
;
1557 // validate it is a file (not directory)
1558 if ( (stat_buf
.st_mode
& S_IFMT
) != S_IFREG
)
1561 uint8_t firstPage
[4096];
1562 bool shortPage
= false;
1564 // min mach-o file is 4K
1565 if ( fileLength
< 4096 ) {
1566 pread(fd
, firstPage
, fileLength
, 0);
1570 pread(fd
, firstPage
, 4096,0);
1573 // if fat wrapper, find usable sub-file
1574 const fat_header
* fileStartAsFat
= (fat_header
*)firstPage
;
1575 if ( fileStartAsFat
->magic
== OSSwapBigToHostInt32(FAT_MAGIC
) ) {
1576 if ( fatFindBest(fileStartAsFat
, &fileOffset
, &fileLength
) ) {
1577 pread(fd
, firstPage
, 4096, fileOffset
);
1580 throw "no matching architecture in universal wrapper";
1584 // try mach-o loader
1585 if ( isCompatibleMachO(firstPage
) ) {
1587 throw "file too short";
1589 // instantiate an image
1590 ImageLoader
* image
= new ImageLoaderMachO(path
, fd
, firstPage
, fileOffset
, fileLength
, stat_buf
, gLinkContext
);
1593 return checkandAddImage(image
, context
);
1596 // try other file formats here...
1599 // throw error about what was found
1600 switch (*(uint32_t*)firstPage
) {
1605 throw "mach-o, but wrong architecture";
1607 throwf("unknown file type, first eight bytes: 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X",
1608 firstPage
[0], firstPage
[1], firstPage
[2], firstPage
[3], firstPage
[4], firstPage
[5], firstPage
[6],firstPage
[7]);
1614 static ImageLoader
* loadPhase5open(const char* path
, const LoadContext
& context
, std::vector
<const char*>* exceptions
)
1616 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
1617 ImageLoader
* image
= NULL
;
1619 // just return NULL if file not found, but record any other errors
1620 struct stat stat_buf
;
1621 if ( stat(path
, &stat_buf
) == -1 ) {
1623 if ( err
!= ENOENT
) {
1624 exceptions
->push_back(dyld::mkstringf("%s: stat() failed with errno=%d", path
, err
));
1629 // in case image was renamed or found via symlinks, check for inode match
1630 image
= findLoadedImage(stat_buf
);
1631 if ( image
!= NULL
)
1634 // do nothing if not already loaded and if RTLD_NOLOAD or NSADDIMAGE_OPTION_RETURN_ONLY_IF_LOADED
1635 if ( context
.dontLoad
)
1638 #if DYLD_SHARED_CACHE_SUPPORT
1639 // see if this image is in shared cache
1640 image
= findSharedCacheImage(stat_buf
, path
);
1641 if ( image
!= NULL
) {
1642 return checkandAddImage(image
, context
);
1646 // open file (automagically closed when this function exits)
1647 FileOpener
file(path
);
1649 // just return NULL if file not found
1650 if ( file
.getFileDescriptor() == -1 )
1654 return loadPhase6(file
.getFileDescriptor(), stat_buf
, path
, context
);
1656 catch (const char* msg
) {
1657 const char* newMsg
= dyld::mkstringf("%s: %s", path
, msg
);
1658 exceptions
->push_back(newMsg
);
1664 // look for path match with existing loaded images
1665 static ImageLoader
* loadPhase5check(const char* path
, const LoadContext
& context
)
1667 //dyld::log("%s(%s)\n", __func__ , path);
1668 // search path against load-path and install-path of all already loaded images
1669 uint32_t hash
= ImageLoader::hash(path
);
1670 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
1671 ImageLoader
* anImage
= *it
;
1672 // check has first to cut down on strcmp calls
1673 if ( anImage
->getPathHash() == hash
)
1674 if ( strcmp(path
, anImage
->getPath()) == 0 ) {
1675 // if we are looking for a dylib don't return something else
1676 if ( !context
.mustBeDylib
|| anImage
->isDylib() )
1679 if ( context
.matchByInstallName
|| anImage
->matchInstallPath() ) {
1680 const char* installPath
= anImage
->getInstallPath();
1681 if ( installPath
!= NULL
) {
1682 if ( strcmp(path
, installPath
) == 0 ) {
1683 // if we are looking for a dylib don't return something else
1684 if ( !context
.mustBeDylib
|| anImage
->isDylib() )
1691 //dyld::log("%s(%s) => NULL\n", __func__, path);
1696 // open or check existing
1697 static ImageLoader
* loadPhase5(const char* path
, const LoadContext
& context
, std::vector
<const char*>* exceptions
)
1699 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
1700 if ( exceptions
!= NULL
)
1701 return loadPhase5open(path
, context
, exceptions
);
1703 return loadPhase5check(path
, context
);
1706 // try with and without image suffix
1707 static ImageLoader
* loadPhase4(const char* path
, const LoadContext
& context
, std::vector
<const char*>* exceptions
)
1709 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
1710 ImageLoader
* image
= NULL
;
1711 if ( gLinkContext
.imageSuffix
!= NULL
) {
1712 char pathWithSuffix
[strlen(path
)+strlen( gLinkContext
.imageSuffix
)+2];
1713 ImageLoader::addSuffix(path
, gLinkContext
.imageSuffix
, pathWithSuffix
);
1714 image
= loadPhase5(pathWithSuffix
, context
, exceptions
);
1716 if ( image
== NULL
)
1717 image
= loadPhase5(path
, context
, exceptions
);
1721 static ImageLoader
* loadPhase2(const char* path
, const LoadContext
& context
,
1722 const char* const frameworkPaths
[], const char* const libraryPaths
[],
1723 std::vector
<const char*>* exceptions
); // forward reference
1726 // expand @ variables
1727 static ImageLoader
* loadPhase3(const char* path
, const LoadContext
& context
, std::vector
<const char*>* exceptions
)
1729 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
1730 ImageLoader
* image
= NULL
;
1731 if ( strncmp(path
, "@executable_path/", 17) == 0 ) {
1732 // executable_path cannot be in used in any binary in a setuid process rdar://problem/4589305
1733 if ( sMainExecutableIsSetuid
) {
1734 throwf("unsafe use of @executable_path in %s with setuid binary", context
.origin
);
1736 // handle @executable_path path prefix
1737 const char* executablePath
= sExecPath
;
1738 char newPath
[strlen(executablePath
) + strlen(path
)];
1739 strcpy(newPath
, executablePath
);
1740 char* addPoint
= strrchr(newPath
,'/');
1741 if ( addPoint
!= NULL
)
1742 strcpy(&addPoint
[1], &path
[17]);
1744 strcpy(newPath
, &path
[17]);
1745 image
= loadPhase4(newPath
, context
, exceptions
);
1746 if ( image
!= NULL
)
1749 // perhaps main executable path is a sym link, find realpath and retry
1750 char resolvedPath
[PATH_MAX
];
1751 if ( realpath(sExecPath
, resolvedPath
) != NULL
) {
1752 char newRealPath
[strlen(resolvedPath
) + strlen(path
)];
1753 strcpy(newRealPath
, resolvedPath
);
1754 char* addPoint
= strrchr(newRealPath
,'/');
1755 if ( addPoint
!= NULL
)
1756 strcpy(&addPoint
[1], &path
[17]);
1758 strcpy(newRealPath
, &path
[17]);
1759 image
= loadPhase4(newRealPath
, context
, exceptions
);
1760 if ( image
!= NULL
)
1764 else if ( (strncmp(path
, "@loader_path/", 13) == 0) && (context
.origin
!= NULL
) ) {
1765 // @loader_path cannot be used from the main executable of a setuid process rdar://problem/4589305
1766 if ( sMainExecutableIsSetuid
&& (strcmp(context
.origin
, sExecPath
) == 0) )
1767 throwf("unsafe use of @loader_path in %s with setuid binary", context
.origin
);
1769 // handle @loader_path path prefix
1770 char newPath
[strlen(context
.origin
) + strlen(path
)];
1771 strcpy(newPath
, context
.origin
);
1772 char* addPoint
= strrchr(newPath
,'/');
1773 if ( addPoint
!= NULL
)
1774 strcpy(&addPoint
[1], &path
[13]);
1776 strcpy(newPath
, &path
[13]);
1777 image
= loadPhase4(newPath
, context
, exceptions
);
1778 if ( image
!= NULL
)
1781 // perhaps loader path is a sym link, find realpath and retry
1782 char resolvedPath
[PATH_MAX
];
1783 if ( realpath(context
.origin
, resolvedPath
) != NULL
) {
1784 char newRealPath
[strlen(resolvedPath
) + strlen(path
)];
1785 strcpy(newRealPath
, resolvedPath
);
1786 char* addPoint
= strrchr(newRealPath
,'/');
1787 if ( addPoint
!= NULL
)
1788 strcpy(&addPoint
[1], &path
[13]);
1790 strcpy(newRealPath
, &path
[13]);
1791 image
= loadPhase4(newRealPath
, context
, exceptions
);
1792 if ( image
!= NULL
)
1796 else if ( context
.implicitRPath
|| (strncmp(path
, "@rpath/", 7) == 0) ) {
1797 const char* trailingPath
= (strncmp(path
, "@rpath/", 7) == 0) ? &path
[7] : path
;
1798 // substitute @rpath with all -rpath paths up the load chain
1799 for(const ImageLoader::RPathChain
* rp
=context
.rpath
; rp
!= NULL
; rp
=rp
->next
) {
1800 if (rp
->paths
!= NULL
) {
1801 for(std::vector
<const char*>::iterator it
=rp
->paths
->begin(); it
!= rp
->paths
->end(); ++it
) {
1802 const char* anRPath
= *it
;
1803 char newPath
[strlen(anRPath
) + strlen(trailingPath
)+2];
1804 strcpy(newPath
, anRPath
);
1805 strcat(newPath
, "/");
1806 strcat(newPath
, trailingPath
);
1807 image
= loadPhase4(newPath
, context
, exceptions
);
1808 if ( image
!= NULL
)
1814 // substitute @rpath with LD_LIBRARY_PATH
1815 if ( sEnv
.LD_LIBRARY_PATH
!= NULL
) {
1816 image
= loadPhase2(trailingPath
, context
, NULL
, sEnv
.LD_LIBRARY_PATH
, exceptions
);
1817 if ( image
!= NULL
)
1821 // if this is the "open" pass, don't try to open @rpath/... as a relative path
1822 if ( (exceptions
!= NULL
) && (trailingPath
!= path
) )
1825 else if ( sMainExecutableIsSetuid
&& (path
[0] != '/') ) {
1826 throwf("unsafe use of relative rpath %s in %s with setuid binary", path
, context
.origin
);
1829 return loadPhase4(path
, context
, exceptions
);
1834 static ImageLoader
* loadPhase2(const char* path
, const LoadContext
& context
,
1835 const char* const frameworkPaths
[], const char* const libraryPaths
[],
1836 std::vector
<const char*>* exceptions
)
1838 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
1839 ImageLoader
* image
= NULL
;
1840 const char* frameworkPartialPath
= getFrameworkPartialPath(path
);
1841 if ( frameworkPaths
!= NULL
) {
1842 if ( frameworkPartialPath
!= NULL
) {
1843 const int frameworkPartialPathLen
= strlen(frameworkPartialPath
);
1844 for(const char* const* fp
= frameworkPaths
; *fp
!= NULL
; ++fp
) {
1845 char npath
[strlen(*fp
)+frameworkPartialPathLen
+8];
1848 strcat(npath
, frameworkPartialPath
);
1849 //dyld::log("dyld: fallback framework path used: %s() -> loadPhase4(\"%s\", ...)\n", __func__, npath);
1850 image
= loadPhase4(npath
, context
, exceptions
);
1851 if ( image
!= NULL
)
1856 if ( libraryPaths
!= NULL
) {
1857 const char* libraryLeafName
= getLibraryLeafName(path
);
1858 const int libraryLeafNameLen
= strlen(libraryLeafName
);
1859 for(const char* const* lp
= libraryPaths
; *lp
!= NULL
; ++lp
) {
1860 char libpath
[strlen(*lp
)+libraryLeafNameLen
+8];
1861 strcpy(libpath
, *lp
);
1862 strcat(libpath
, "/");
1863 strcat(libpath
, libraryLeafName
);
1864 //dyld::log("dyld: fallback library path used: %s() -> loadPhase4(\"%s\", ...)\n", __func__, libpath);
1865 image
= loadPhase4(libpath
, context
, exceptions
);
1866 if ( image
!= NULL
)
1873 // try search overrides and fallbacks
1874 static ImageLoader
* loadPhase1(const char* path
, const LoadContext
& context
, std::vector
<const char*>* exceptions
)
1876 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
1877 ImageLoader
* image
= NULL
;
1879 // handle LD_LIBRARY_PATH environment variables that force searching
1880 if ( context
.useLdLibraryPath
&& (sEnv
.LD_LIBRARY_PATH
!= NULL
) ) {
1881 image
= loadPhase2(path
, context
, NULL
, sEnv
.LD_LIBRARY_PATH
, exceptions
);
1882 if ( image
!= NULL
)
1886 // handle DYLD_ environment variables that force searching
1887 if ( context
.useSearchPaths
&& ((sEnv
.DYLD_FRAMEWORK_PATH
!= NULL
) || (sEnv
.DYLD_LIBRARY_PATH
!= NULL
)) ) {
1888 image
= loadPhase2(path
, context
, sEnv
.DYLD_FRAMEWORK_PATH
, sEnv
.DYLD_LIBRARY_PATH
, exceptions
);
1889 if ( image
!= NULL
)
1894 image
= loadPhase3(path
, context
, exceptions
);
1895 if ( image
!= NULL
)
1898 // try fallback paths during second time (will open file)
1899 if ( !context
.dontLoad
&& (exceptions
!= NULL
) && ((sEnv
.DYLD_FALLBACK_FRAMEWORK_PATH
!= NULL
) || (sEnv
.DYLD_FALLBACK_LIBRARY_PATH
!= NULL
)) ) {
1900 image
= loadPhase2(path
, context
, sEnv
.DYLD_FALLBACK_FRAMEWORK_PATH
, sEnv
.DYLD_FALLBACK_LIBRARY_PATH
, exceptions
);
1901 if ( image
!= NULL
)
1908 // try root substitutions
1909 static ImageLoader
* loadPhase0(const char* path
, const LoadContext
& context
, std::vector
<const char*>* exceptions
)
1911 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
1913 // handle DYLD_ROOT_PATH which forces absolute paths to use a new root
1914 if ( (sEnv
.DYLD_ROOT_PATH
!= NULL
) && (path
[0] == '/') ) {
1915 for(const char* const* rootPath
= sEnv
.DYLD_ROOT_PATH
; *rootPath
!= NULL
; ++rootPath
) {
1916 char newPath
[strlen(*rootPath
) + strlen(path
)+2];
1917 strcpy(newPath
, *rootPath
);
1918 strcat(newPath
, path
);
1919 ImageLoader
* image
= loadPhase1(newPath
, context
, exceptions
);
1920 if ( image
!= NULL
)
1926 return loadPhase1(path
, context
, exceptions
);
1930 // Given all the DYLD_ environment variables, the general case for loading libraries
1931 // is that any given path expands into a list of possible locations to load. We
1932 // also must take care to ensure two copies of the "same" library are never loaded.
1934 // The algorithm used here is that there is a separate function for each "phase" of the
1935 // path expansion. Each phase function calls the next phase with each possible expansion
1936 // of that phase. The result is the last phase is called with all possible paths.
1938 // To catch duplicates the algorithm is run twice. The first time, the last phase checks
1939 // the path against all loaded images. The second time, the last phase calls open() on
1940 // the path. Either time, if an image is found, the phases all unwind without checking
1943 ImageLoader
* load(const char* path
, const LoadContext
& context
)
1945 //dyld::log("%s(%s)\n", __func__ , path);
1946 char realPath
[PATH_MAX
];
1947 // when DYLD_IMAGE_SUFFIX is in used, do a realpath(), otherwise a load of "Foo.framework/Foo" will not match
1948 if ( context
.useSearchPaths
&& ( gLinkContext
.imageSuffix
!= NULL
) ) {
1949 if ( realpath(path
, realPath
) != NULL
)
1953 // try all path permutations and check against existing loaded images
1954 ImageLoader
* image
= loadPhase0(path
, context
, NULL
);
1955 if ( image
!= NULL
)
1958 // try all path permutations and try open() until first sucesss
1959 std::vector
<const char*> exceptions
;
1960 image
= loadPhase0(path
, context
, &exceptions
);
1961 if ( image
!= NULL
)
1963 else if ( exceptions
.size() == 0 )
1964 throw "image not found";
1966 const char* msgStart
= "no suitable image found. Did find:";
1967 const char* delim
= "\n\t";
1968 size_t allsizes
= strlen(msgStart
)+8;
1969 for (unsigned int i
=0; i
< exceptions
.size(); ++i
)
1970 allsizes
+= (strlen(exceptions
[i
]) + strlen(delim
));
1971 char* fullMsg
= new char[allsizes
];
1972 strcpy(fullMsg
, msgStart
);
1973 for (unsigned int i
=0; i
< exceptions
.size(); ++i
) {
1974 strcat(fullMsg
, delim
);
1975 strcat(fullMsg
, exceptions
[i
]);
1976 free((void*)exceptions
[i
]);
1978 throw (const char*)fullMsg
;
1985 #if DYLD_SHARED_CACHE_SUPPORT
1988 // hack until dyld no longer needs to run on Leopard kernels that don't have new shared region syscall
1989 static bool newSharedRegionSyscallAvailable()
1992 size_t buffer_size
= sizeof(shreg_version
);
1993 if ( sysctlbyname("vm.shared_region_version", &shreg_version
, &buffer_size
, NULL
, 0) == 0 ) {
1994 if ( shreg_version
== 3 )
2001 static int __attribute__((noinline
)) _shared_region_check_np(uint64_t* start_address
)
2003 if ( (gLinkContext
.sharedRegionMode
== ImageLoader::kUseSharedRegion
) && newSharedRegionSyscallAvailable() )
2004 return syscall(294, start_address
);
2009 static int __attribute__((noinline
)) _shared_region_map_np(int fd
, uint32_t count
, const shared_file_mapping_np mappings
[])
2012 if ( (gLinkContext
.sharedRegionMode
== ImageLoader::kUseSharedRegion
) && newSharedRegionSyscallAvailable() ) {
2013 return syscall(295, fd
, count
, mappings
);
2016 // remove the shared region sub-map
2017 #if __ppc__ || __i386__
2018 vm_address_t addr
= (vm_address_t
)0x90000000;
2019 vm_deallocate(mach_task_self(), addr
, 0x20000000);
2020 #elif __ppc64__ || __x86_64__
2021 vm_address_t addr
= (vm_address_t
)0x7FFF60000000;
2022 vm_deallocate(mach_task_self(), addr
, 0x80000000);
2025 // map cache just for this process with mmap()
2026 bool failed
= false;
2027 const shared_file_mapping_np
* start
= mappings
;
2028 const shared_file_mapping_np
* end
= &mappings
[count
];
2029 for (const shared_file_mapping_np
* p
= start
; p
< end
; ++p
) {
2030 void* mmapAddress
= (void*)(uintptr_t)(p
->sfm_address
);
2031 size_t size
= p
->sfm_size
;
2033 if ( p
->sfm_init_prot
& VM_PROT_EXECUTE
)
2034 protection
|= PROT_EXEC
;
2035 if ( p
->sfm_init_prot
& VM_PROT_READ
)
2036 protection
|= PROT_READ
;
2037 if ( p
->sfm_init_prot
& VM_PROT_WRITE
)
2038 protection
|= PROT_WRITE
;
2039 off_t offset
= p
->sfm_file_offset
;
2040 mmapAddress
= mmap(mmapAddress
, size
, protection
, MAP_FIXED
| MAP_PRIVATE
, fd
, offset
);
2041 if ( mmap(mmapAddress
, size
, protection
, MAP_FIXED
| MAP_PRIVATE
, fd
, offset
) != mmapAddress
)
2046 gLinkContext
.sharedRegionMode
= ImageLoader::kUsePrivateSharedRegion
;
2050 gLinkContext
.sharedRegionMode
= ImageLoader::kDontUseSharedRegion
;
2051 if ( gLinkContext
.verboseMapping
)
2052 dyld::log("dyld: shared cached cannot be mapped\n");
2061 #define ARCH_NAME "ppc"
2062 #define ARCH_NAME_ROSETTA "rosetta"
2063 #define ARCH_VALUE CPU_TYPE_POWERPC
2064 #define ARCH_CACHE_MAGIC "dyld_v1 ppc"
2066 #define ARCH_NAME "ppc64"
2067 #define ARCH_VALUE CPU_TYPE_POWERPC64
2068 #define ARCH_CACHE_MAGIC "dyld_v1 ppc64"
2070 #define ARCH_NAME "i386"
2071 #define ARCH_VALUE CPU_TYPE_I386
2072 #define ARCH_CACHE_MAGIC "dyld_v1 i386"
2074 #define ARCH_NAME "x86_64"
2075 #define ARCH_VALUE CPU_TYPE_X86_64
2076 #define ARCH_CACHE_MAGIC "dyld_v1 x86_64"
2080 static void mapSharedCache()
2082 uint64_t cacheBaseAddress
;
2083 // quick check if a cache is alreay mapped into shared region
2084 if ( _shared_region_check_np(&cacheBaseAddress
) == 0 ) {
2085 sSharedCache
= (dyld_cache_header
*)cacheBaseAddress
;
2086 // if we don't understand the currently mapped shared cache, then ignore
2087 if ( strcmp(sSharedCache
->magic
, ARCH_CACHE_MAGIC
) != 0 ) {
2088 sSharedCache
= NULL
;
2089 if ( gLinkContext
.verboseMapping
)
2090 dyld::log("dyld: existing shared cached in memory is not compatible\n");
2094 // map in shared cache to shared region
2097 // rosetta cannot handle optimized _ppc cache, so it use _rosetta cache instead, rdar://problem/5495438
2099 fd
= open(DYLD_SHARED_CACHE_DIR DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME_ROSETTA
, O_RDONLY
);
2102 fd
= open(DYLD_SHARED_CACHE_DIR DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME
, O_RDONLY
);
2104 uint8_t firstPage
[4096];
2105 if ( ::read(fd
, firstPage
, 4096) == 4096 ) {
2106 dyld_cache_header
* header
= (dyld_cache_header
*)firstPage
;
2107 if ( strcmp(header
->magic
, ARCH_CACHE_MAGIC
) == 0 ) {
2108 const shared_file_mapping_np
* mappings
= (shared_file_mapping_np
*)&firstPage
[header
->mappingOffset
];
2109 const shared_file_mapping_np
* const end
= &mappings
[header
->mappingCount
];
2110 // validate that the cache file has not been truncated
2111 bool goodCache
= false;
2112 struct stat stat_buf
;
2113 if ( fstat(fd
, &stat_buf
) == 0 ) {
2115 for (const shared_file_mapping_np
* p
= mappings
; p
< end
; ++p
) {
2116 if ( p
->sfm_file_offset
+p
->sfm_size
> (uint64_t)stat_buf
.st_size
)
2121 const shared_file_mapping_np
* mappings
= (shared_file_mapping_np
*)&firstPage
[header
->mappingOffset
];
2122 if (_shared_region_map_np(fd
, header
->mappingCount
, mappings
) == 0) {
2123 // sucessfully mapped cache into shared region
2124 sSharedCache
= (dyld_cache_header
*)mappings
[0].sfm_address
;
2128 gSharedCacheNeedsUpdating
= true;
2129 dyld::log("dyld: shared cached file is corrupt: " DYLD_SHARED_CACHE_DIR DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME
"\n");
2133 gSharedCacheNeedsUpdating
= true;
2134 if ( gLinkContext
.verboseMapping
)
2135 dyld::log("dyld: shared cached file is invalid\n");
2139 gSharedCacheNeedsUpdating
= true;
2140 if ( gLinkContext
.verboseMapping
)
2141 dyld::log("dyld: shared cached file cannot be read\n");
2146 gSharedCacheNotFound
= true;
2147 if ( gLinkContext
.verboseMapping
)
2148 dyld::log("dyld: shared cached file cannot be opened\n");
2152 // remember if dyld loaded at same address as when cache built
2153 if ( sSharedCache
!= NULL
) {
2154 gLinkContext
.dyldLoadedAtSameAddressNeededBySharedCache
= ((uintptr_t)(sSharedCache
->dyldBaseAddress
) == (uintptr_t)&_mh_dylinker_header
);
2157 // tell gdb where the shared cache is
2158 if ( sSharedCache
!= NULL
) {
2159 const shared_file_mapping_np
* const start
= (shared_file_mapping_np
*)((uint8_t*)sSharedCache
+ sSharedCache
->mappingOffset
);
2160 dyld_shared_cache_ranges
.sharedRegionsCount
= sSharedCache
->mappingCount
;
2161 // only room to tell gdb about first four regions
2162 if ( dyld_shared_cache_ranges
.sharedRegionsCount
> 4 )
2163 dyld_shared_cache_ranges
.sharedRegionsCount
= 4;
2164 if ( gLinkContext
.verboseMapping
) {
2165 if ( gLinkContext
.sharedRegionMode
== ImageLoader::kUseSharedRegion
)
2166 dyld::log("dyld: Mapping shared cache\n");
2167 else if ( gLinkContext
.sharedRegionMode
== ImageLoader::kUsePrivateSharedRegion
)
2168 dyld::log("dyld: Mapping private shared cache\n");
2170 const shared_file_mapping_np
* const end
= &start
[dyld_shared_cache_ranges
.sharedRegionsCount
];
2172 for (const shared_file_mapping_np
* p
= start
; p
< end
; ++p
, ++index
) {
2173 dyld_shared_cache_ranges
.ranges
[index
].start
= p
->sfm_address
;
2174 dyld_shared_cache_ranges
.ranges
[index
].length
= p
->sfm_size
;
2175 if ( gLinkContext
.verboseMapping
) {
2176 dyld::log(" 0x%08llX->0x%08llX %s%s%s init=%x, max=%x\n", p
->sfm_address
, p
->sfm_address
+p
->sfm_size
-1,
2177 ((p
->sfm_init_prot
& VM_PROT_READ
) ? "read " : ""),
2178 ((p
->sfm_init_prot
& VM_PROT_WRITE
) ? "write " : ""),
2179 ((p
->sfm_init_prot
& VM_PROT_EXECUTE
) ? "execute " : ""), p
->sfm_init_prot
, p
->sfm_max_prot
);
2182 // record if a non-writable and executable region is found in the R/W shared region
2183 // this is the __IMPORT segments. dyld will turn write protection on and off as needed
2184 if ( (p
->sfm_init_prot
== (VM_PROT_READ
|VM_PROT_EXECUTE
)) && ((p
->sfm_address
& 0xF0000000) == 0xA0000000) ) {
2185 sImportSegmentsStart
= p
->sfm_address
;
2186 sImportSegmentsSize
= p
->sfm_size
;
2187 makeSharedCacheImportSegmentsWritable(true);
2194 #endif // #if DYLD_SHARED_CACHE_SUPPORT
2198 // create when NSLinkModule is called for a second time on a bundle
2199 ImageLoader
* cloneImage(ImageLoader
* image
)
2201 const uint64_t offsetInFat
= image
->getOffsetInFatFile();
2203 // open file (automagically closed when this function exits)
2204 FileOpener
file(image
->getPath());
2206 struct stat stat_buf
;
2207 if ( fstat(file
.getFileDescriptor(), &stat_buf
) == -1)
2210 // read first page of file
2211 uint8_t firstPage
[4096];
2212 pread(file
.getFileDescriptor(), firstPage
, 4096, offsetInFat
);
2214 // fat length is only used for sanity checking, since this image was already loaded once, just use upper bound
2215 uint64_t lenInFat
= stat_buf
.st_size
- offsetInFat
;
2217 // try mach-o loader
2218 if ( isCompatibleMachO(firstPage
) ) {
2219 ImageLoader
* clone
= new ImageLoaderMachO(image
->getPath(), file
.getFileDescriptor(), firstPage
, offsetInFat
, lenInFat
, stat_buf
, gLinkContext
);
2220 // don't add bundles to global list, they can be loaded but not linked. When linked it will be added to list
2221 if ( ! image
->isBundle() )
2226 // try other file formats...
2227 throw "can't clone image";
2231 ImageLoader
* loadFromMemory(const uint8_t* mem
, uint64_t len
, const char* moduleName
)
2233 // if fat wrapper, find usable sub-file
2234 const fat_header
* memStartAsFat
= (fat_header
*)mem
;
2235 uint64_t fileOffset
= 0;
2236 uint64_t fileLength
= len
;
2237 if ( memStartAsFat
->magic
== OSSwapBigToHostInt32(FAT_MAGIC
) ) {
2238 if ( fatFindBest(memStartAsFat
, &fileOffset
, &fileLength
) ) {
2239 mem
= &mem
[fileOffset
];
2243 throw "no matching architecture in universal wrapper";
2248 if ( isCompatibleMachO(mem
) ) {
2249 ImageLoader
* image
= new ImageLoaderMachO(moduleName
, (mach_header
*)mem
, len
, gLinkContext
);
2250 // don't add bundles to global list, they can be loaded but not linked. When linked it will be added to list
2251 if ( ! image
->isBundle() )
2256 // try other file formats here...
2258 // throw error about what was found
2259 switch (*(uint32_t*)mem
) {
2264 throw "mach-o, but wrong architecture";
2266 throwf("unknown file type, first eight bytes: 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X",
2267 mem
[0], mem
[1], mem
[2], mem
[3], mem
[4], mem
[5], mem
[6],mem
[7]);
2272 void registerAddCallback(ImageCallback func
)
2274 // now add to list to get notified when any more images are added
2275 sAddImageCallbacks
.push_back(func
);
2277 // call callback with all existing images
2278 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
2279 ImageLoader
* image
= *it
;
2280 if ( image
->getState() >= dyld_image_state_bound
&& image
->getState() < dyld_image_state_terminated
)
2281 (*func
)(image
->machHeader(), image
->getSlide());
2285 void registerRemoveCallback(ImageCallback func
)
2287 sRemoveImageCallbacks
.push_back(func
);
2290 void clearErrorMessage()
2292 error_string
[0] = '\0';
2295 void setErrorMessage(const char* message
)
2297 // save off error message in global buffer for CrashReporter to find
2298 strncpy(error_string
, message
, sizeof(error_string
)-1);
2299 error_string
[sizeof(error_string
)-1] = '\0';
2302 const char* getErrorMessage()
2304 return error_string
;
2308 void halt(const char* message
)
2310 dyld::log("dyld: %s\n", message
);
2311 setErrorMessage(message
);
2312 strncpy(error_string
, message
, sizeof(error_string
)-1);
2313 error_string
[sizeof(error_string
)-1] = '\0';
2314 dyld_fatal_error(error_string
);
2318 uintptr_t bindLazySymbol(const mach_header
* mh
, uintptr_t* lazyPointer
)
2320 uintptr_t result
= 0;
2321 // acquire read-lock on dyld's data structures
2322 #if 0 // rdar://problem/3811777 turn off locking until deadlock is resolved
2323 if ( gLibSystemHelpers
!= NULL
)
2324 (*gLibSystemHelpers
->lockForReading
)();
2326 // lookup and bind lazy pointer and get target address
2328 ImageLoader
* target
;
2330 // fast stubs pass NULL for mh and image is instead found via the location of stub (aka lazyPointer)
2332 target
= dyld::findImageContainingAddressThreadSafe(lazyPointer
);
2334 target
= dyld::findImageByMachHeader(mh
);
2336 // note, target should always be mach-o, because only mach-o lazy handler wired up to this
2337 target
= dyld::findImageByMachHeader(mh
);
2339 if ( target
== NULL
)
2340 throwf("image not found for lazy pointer at %p", lazyPointer
);
2341 result
= target
->doBindLazySymbol(lazyPointer
, gLinkContext
);
2343 catch (const char* message
) {
2344 dyld::log("dyld: lazy symbol binding failed: %s\n", message
);
2347 // release read-lock on dyld's data structures
2349 if ( gLibSystemHelpers
!= NULL
)
2350 (*gLibSystemHelpers
->unlockForReading
)();
2352 // return target address to glue which jumps to it with real parameters restored
2357 // SPI used by ZeroLink to lazy load bundles
2358 void registerZeroLinkHandlers(BundleNotificationCallBack notify
, BundleLocatorCallBack locate
)
2360 sBundleNotifier
= notify
;
2361 sBundleLocation
= locate
;
2364 void registerUndefinedHandler(UndefinedHandler handler
)
2366 sUndefinedHandler
= handler
;
2369 static void undefinedHandler(const char* symboName
)
2371 if ( sUndefinedHandler
!= NULL
) {
2372 (*sUndefinedHandler
)(symboName
);
2376 static bool findExportedSymbol(const char* name
, bool onlyInCoalesced
, const ImageLoader::Symbol
** sym
, const ImageLoader
** image
)
2378 // try ZeroLink short cut to finding bundle which exports this symbol
2379 if ( sBundleLocation
!= NULL
) {
2380 ImageLoader
* zlImage
= (*sBundleLocation
)(name
);
2381 if ( zlImage
== ((ImageLoader
*)(-1)) ) {
2382 // -1 is magic value that request symbol is in a bundle not yet linked into process
2383 // try calling handler to link in that symbol
2384 undefinedHandler(name
);
2385 // call locator again
2386 zlImage
= (*sBundleLocation
)(name
);
2388 // if still not found, then ZeroLink has no idea where to find it
2389 if ( zlImage
== ((ImageLoader
*)(-1)) )
2391 if ( zlImage
!= NULL
) {
2392 // ZeroLink cache knows where the symbol is
2393 if ( onlyInCoalesced
) {
2394 // but ZeroLink does not know about coalescing weak symbols, so ignore ZeroLink's hint when onlyInCoalesced==true
2397 *sym
= zlImage
->findExportedSymbol(name
, NULL
, false, image
);
2398 if ( *sym
!= NULL
) {
2405 // ZeroLink says it is in some bundle already loaded, but not linked, walk them all
2406 const unsigned int imageCount
= sAllImages
.size();
2407 for(unsigned int i
=0; i
< imageCount
; ++i
){
2408 ImageLoader
* anImage
= sAllImages
[i
];
2409 if ( anImage
->isBundle() && !anImage
->hasHiddenExports() ) {
2410 //dyld::log("dyld: search for %s in %s\n", name, anImage->getPath());
2411 *sym
= anImage
->findExportedSymbol(name
, NULL
, false, image
);
2412 if ( *sym
!= NULL
) {
2420 // search all images in order
2421 const ImageLoader
* firstWeakImage
= NULL
;
2422 const ImageLoader::Symbol
* firstWeakSym
= NULL
;
2423 const unsigned int imageCount
= sAllImages
.size();
2424 for(unsigned int i
=0; i
< imageCount
; ++i
) {
2425 ImageLoader
* anImage
= sAllImages
[i
];
2426 // the use of inserted libraries alters search order
2427 // so that inserted libraries are found before the main executable
2428 if ( sInsertedDylibCount
> 0 ) {
2429 if ( i
< sInsertedDylibCount
)
2430 anImage
= sAllImages
[i
+1];
2431 else if ( i
== sInsertedDylibCount
)
2432 anImage
= sAllImages
[0];
2434 if ( ! anImage
->hasHiddenExports() && (!onlyInCoalesced
|| anImage
->hasCoalescedExports()) ) {
2435 *sym
= anImage
->findExportedSymbol(name
, NULL
, false, image
);
2436 if ( *sym
!= NULL
) {
2437 // if weak definition found, record first one found
2438 if ( ((*image
)->getExportedSymbolInfo(*sym
) & ImageLoader::kWeakDefinition
) != 0 ) {
2439 if ( firstWeakImage
== NULL
) {
2440 firstWeakImage
= *image
;
2441 firstWeakSym
= *sym
;
2445 // found non-weak, so immediately return with it
2451 if ( firstWeakSym
!= NULL
) {
2452 // found a weak definition, but no non-weak, so return first weak found
2453 *sym
= firstWeakSym
;
2454 *image
= firstWeakImage
;
2461 bool flatFindExportedSymbol(const char* name
, const ImageLoader::Symbol
** sym
, const ImageLoader
** image
)
2463 return findExportedSymbol(name
, false, sym
, image
);
2466 bool findCoalescedExportedSymbol(const char* name
, const ImageLoader::Symbol
** sym
, const ImageLoader
** image
)
2468 return findExportedSymbol(name
, true, sym
, image
);
2472 bool flatFindExportedSymbolWithHint(const char* name
, const char* librarySubstring
, const ImageLoader::Symbol
** sym
, const ImageLoader
** image
)
2474 // search all images in order
2475 const unsigned int imageCount
= sAllImages
.size();
2476 for(unsigned int i
=0; i
< imageCount
; ++i
){
2477 ImageLoader
* anImage
= sAllImages
[i
];
2478 // only look at images whose paths contain the hint string (NULL hint string is wildcard)
2479 if ( ! anImage
->isBundle() && ((librarySubstring
==NULL
) || (strstr(anImage
->getPath(), librarySubstring
) != NULL
)) ) {
2480 *sym
= anImage
->findExportedSymbol(name
, NULL
, false, image
);
2481 if ( *sym
!= NULL
) {
2489 static ImageLoader::MappedRegion
* getMappedRegions(ImageLoader::MappedRegion
* regions
)
2491 ImageLoader::MappedRegion
* end
= regions
;
2492 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
2493 (*it
)->getMappedRegions(end
);
2498 void registerImageStateSingleChangeHandler(dyld_image_states state
, dyld_image_state_change_handler handler
)
2500 // mark the image that the handler is in as never-unload because dyld has a reference into it
2501 ImageLoader
* handlerImage
= findImageContainingAddress((void*)handler
);
2502 if ( handlerImage
!= NULL
)
2503 handlerImage
->setNeverUnload();
2505 // add to list of handlers
2506 std::vector
<dyld_image_state_change_handler
>* handlers
= stateToHandlers(state
, sSingleHandlers
);
2507 if ( handlers
!= NULL
) {
2508 handlers
->push_back(handler
);
2510 // call callback with all existing images
2511 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
2512 ImageLoader
* image
= *it
;
2513 dyld_image_info info
;
2514 info
.imageLoadAddress
= image
->machHeader();
2515 info
.imageFilePath
= image
->getPath();
2516 info
.imageFileModDate
= image
->lastModified();
2517 // should only call handler if state == image->state
2518 if ( image
->getState() == state
)
2519 (*handler
)(state
, 1, &info
);
2520 // ignore returned string, too late to do anything
2525 void registerImageStateBatchChangeHandler(dyld_image_states state
, dyld_image_state_change_handler handler
)
2527 // mark the image that the handler is in as never-unload because dyld has a reference into it
2528 ImageLoader
* handlerImage
= findImageContainingAddress((void*)handler
);
2529 if ( handlerImage
!= NULL
)
2530 handlerImage
->setNeverUnload();
2532 // add to list of handlers
2533 std::vector
<dyld_image_state_change_handler
>* handlers
= stateToHandlers(state
, sBatchHandlers
);
2534 if ( handlers
!= NULL
) {
2535 // insert at front, so that gdb handler is always last
2536 handlers
->insert(handlers
->begin(), handler
);
2538 // call callback with all existing images
2540 notifyBatchPartial(state
, true, handler
);
2542 catch (const char* msg
) {
2543 // ignore request to abort during registration
2548 static ImageLoader
* libraryLocator(const char* libraryName
, bool search
, bool findDLL
, const char* origin
, const ImageLoader::RPathChain
* rpaths
)
2550 dyld::LoadContext context
;
2551 context
.useSearchPaths
= search
;
2552 context
.useLdLibraryPath
= false;
2553 context
.implicitRPath
= false;
2554 context
.matchByInstallName
= false;
2555 context
.dontLoad
= false;
2556 context
.mustBeBundle
= false;
2557 context
.mustBeDylib
= true;
2558 context
.findDLL
= findDLL
;
2559 context
.origin
= origin
;
2560 context
.rpath
= rpaths
;
2561 return load(libraryName
, context
);
2564 static const char* basename(const char* path
)
2566 const char* last
= path
;
2567 for (const char* s
= path
; *s
!= '\0'; s
++) {
2574 static void setContext(const struct mach_header
* mainExecutableMH
, int argc
, const char* argv
[], const char* envp
[], const char* apple
[])
2576 gLinkContext
.loadLibrary
= &libraryLocator
;
2577 gLinkContext
.terminationRecorder
= &terminationRecorder
;
2578 gLinkContext
.flatExportFinder
= &flatFindExportedSymbol
;
2579 gLinkContext
.coalescedExportFinder
= &findCoalescedExportedSymbol
;
2580 gLinkContext
.undefinedHandler
= &undefinedHandler
;
2581 #if IMAGE_NOTIFY_SUPPORT
2582 gLinkContext
.addImageNeedingNotification
= &addImageNeedingNotification
;
2583 gLinkContext
.notifyAdding
= ¬ifyAdding
;
2585 gLinkContext
.getAllMappedRegions
= &getMappedRegions
;
2586 gLinkContext
.bindingHandler
= NULL
;
2587 gLinkContext
.notifySingle
= ¬ifySingle
;
2588 gLinkContext
.notifyBatch
= ¬ifyBatch
;
2589 gLinkContext
.removeImage
= &removeImage
;
2590 gLinkContext
.registerDOFs
= ®isterDOFs
;
2591 gLinkContext
.clearAllDepths
= &clearAllDepths
;
2592 gLinkContext
.imageCount
= &imageCount
;
2593 gLinkContext
.notifySharedCacheInvalid
= ¬ifySharedCacheInvalid
;
2595 gLinkContext
.makeSharedCacheImportSegmentsWritable
= &makeSharedCacheImportSegmentsWritable
;
2597 gLinkContext
.setNewProgramVars
= &setNewProgramVars
;
2598 #if SUPPORT_OLD_CRT_INITIALIZATION
2599 gLinkContext
.setRunInitialzersOldWay
= &setRunInitialzersOldWay
;
2601 gLinkContext
.bindingOptions
= ImageLoader::kBindingNone
;
2602 gLinkContext
.argc
= argc
;
2603 gLinkContext
.argv
= argv
;
2604 gLinkContext
.envp
= envp
;
2605 gLinkContext
.apple
= apple
;
2606 gLinkContext
.progname
= (argv
[0] != NULL
) ? basename(argv
[0]) : "";
2607 gLinkContext
.programVars
.mh
= mainExecutableMH
;
2608 gLinkContext
.programVars
.NXArgcPtr
= &gLinkContext
.argc
;
2609 gLinkContext
.programVars
.NXArgvPtr
= &gLinkContext
.argv
;
2610 gLinkContext
.programVars
.environPtr
= &gLinkContext
.envp
;
2611 gLinkContext
.programVars
.__prognamePtr
=&gLinkContext
.progname
;
2612 gLinkContext
.mainExecutable
= NULL
;
2613 gLinkContext
.imageSuffix
= NULL
;
2614 gLinkContext
.prebindUsage
= ImageLoader::kUseAllPrebinding
;
2615 gLinkContext
.sharedRegionMode
= ImageLoader::kUseSharedRegion
;
2618 #if __ppc__ || __i386__
2621 int mib
[] = { CTL_KERN
, KERN_CLASSIC
, getpid() };
2623 size_t len
= sizeof(int);
2624 int ret
= sysctl(mib
, 3, &is_classic
, &len
, NULL
, 0);
2625 if ((ret
!= -1) && is_classic
) {
2626 // we're running under Rosetta
2634 static void printAllImages()
2636 dyld::log("printAllImages()\n");
2637 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
2638 ImageLoader
* image
= *it
;
2639 dyld_image_states imageState
= image
->getState();
2640 dyld::log(" state=%d, refcount=%d, name=%s\n", imageState
, image
->referenceCount(), image
->getShortName());
2641 image
->printReferenceCounts();
2647 void link(ImageLoader
* image
, bool forceLazysBound
, const ImageLoader::RPathChain
& loaderRPaths
)
2649 // add to list of known images. This did not happen at creation time for bundles
2650 if ( image
->isBundle() && !image
->isLinked() )
2653 // we detect root images as those not linked in yet
2654 if ( !image
->isLinked() )
2655 addRootImage(image
);
2657 // notify ZeroLink of new image with concat of logical and physical name
2658 if ( sBundleNotifier
!= NULL
&& image
->isBundle() ) {
2659 const int logicalLen
= strlen(image
->getLogicalPath());
2660 char logAndPhys
[strlen(image
->getPath())+logicalLen
+2];
2661 strcpy(logAndPhys
, image
->getLogicalPath());
2662 strcpy(&logAndPhys
[logicalLen
+1], image
->getPath());
2663 (*sBundleNotifier
)(logAndPhys
, image
);
2668 image
->link(gLinkContext
, forceLazysBound
, false, loaderRPaths
);
2670 catch (const char* msg
) {
2671 garbageCollectImages();
2675 #if OLD_GDB_DYLD_INTERFACE
2676 // notify gdb that loaded libraries have changed
2677 gdb_dyld_state_changed();
2682 void runInitializers(ImageLoader
* image
)
2684 // do bottom up initialization
2685 image
->runInitializers(gLinkContext
);
2688 void garbageCollectImages()
2690 // keep scanning list of images until entire list is scanned with no unreferenced images
2691 bool mightBeUnreferencedImages
= true;
2692 while ( mightBeUnreferencedImages
) {
2693 mightBeUnreferencedImages
= false;
2694 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
2695 ImageLoader
* image
= *it
;
2696 if ( (image
->referenceCount() == 0) && !image
->neverUnload() && !image
->isBeingRemoved() ) {
2698 //dyld::log("garbageCollectImages: deleting %s\n", image->getPath());
2699 image
->setBeingRemoved();
2703 catch (const char* msg
) {
2704 dyld::warn("problem deleting image: %s\n", msg
);
2706 mightBeUnreferencedImages
= true;
2715 static void preflight_finally(ImageLoader
* image
)
2717 if ( image
->isBundle() ) {
2718 removeImageFromAllImages(image
->machHeader());
2721 sBundleBeingLoaded
= NULL
;
2722 dyld::garbageCollectImages();
2726 void preflight(ImageLoader
* image
, const ImageLoader::RPathChain
& loaderRPaths
)
2729 if ( image
->isBundle() )
2730 sBundleBeingLoaded
= image
; // hack
2731 image
->link(gLinkContext
, false, true, loaderRPaths
);
2733 catch (const char* msg
) {
2734 preflight_finally(image
);
2737 preflight_finally(image
);
2740 static void loadInsertedDylib(const char* path
)
2742 ImageLoader
* image
= NULL
;
2744 LoadContext context
;
2745 context
.useSearchPaths
= false;
2746 context
.useLdLibraryPath
= false;
2747 context
.implicitRPath
= false;
2748 context
.matchByInstallName
= false;
2749 context
.dontLoad
= false;
2750 context
.mustBeBundle
= false;
2751 context
.mustBeDylib
= true;
2752 context
.findDLL
= false;
2753 context
.origin
= NULL
; // can't use @loader_path with DYLD_INSERT_LIBRARIES
2754 context
.rpath
= NULL
;
2755 image
= load(path
, context
);
2756 image
->setNeverUnload();
2759 halt(dyld::mkstringf("could not load inserted library: %s\n", path
));
2764 // Entry point for dyld. The kernel loads dyld and jumps to __dyld_start which
2765 // sets up some registers and call this function.
2767 // Returns address of main() in target program which __dyld_start jumps to
2770 _main(const struct mach_header
* mainExecutableMH
, uintptr_t mainExecutableSlide
, int argc
, const char* argv
[], const char* envp
[], const char* apple
[])
2772 setContext(mainExecutableMH
, argc
, argv
, envp
, apple
);
2774 // Pickup the pointer to the exec path.
2775 sExecPath
= apple
[0];
2776 bool ignoreEnvironmentVariables
= false;
2778 if ( isRosetta() ) {
2779 // under Rosetta (x86 side)
2780 // When a 32-bit ppc program is run under emulation on an Intel processor,
2781 // we want any i386 dylibs (e.g. any used by Rosetta) to not load in the shared region
2782 // because the shared region is being used by ppc dylibs
2783 gLinkContext
.sharedRegionMode
= ImageLoader::kDontUseSharedRegion
;
2784 ignoreEnvironmentVariables
= true;
2787 if ( sExecPath
[0] != '/' ) {
2788 // have relative path, use cwd to make absolute
2789 char cwdbuff
[MAXPATHLEN
];
2790 if ( getcwd(cwdbuff
, MAXPATHLEN
) != NULL
) {
2791 // maybe use static buffer to avoid calling malloc so early...
2792 char* s
= new char[strlen(cwdbuff
) + strlen(sExecPath
) + 2];
2795 strcat(s
, sExecPath
);
2799 uintptr_t result
= 0;
2800 sMainExecutableMachHeader
= mainExecutableMH
;
2801 sMainExecutableIsSetuid
= issetugid();
2802 if ( sMainExecutableIsSetuid
)
2803 pruneEnvironmentVariables(envp
, &apple
);
2805 checkEnvironmentVariables(envp
, ignoreEnvironmentVariables
);
2806 if ( sEnv
.DYLD_PRINT_OPTS
)
2808 if ( sEnv
.DYLD_PRINT_ENV
)
2809 printEnvironmentVariables(envp
);
2811 // install gdb notifier
2812 stateToHandlers(dyld_image_state_dependents_mapped
, sBatchHandlers
)->push_back(notifyGDB
);
2813 // make initial allocations large enough that it is unlikely to need to be re-alloced
2814 sAllImages
.reserve(200);
2815 sImageRoots
.reserve(16);
2816 sAddImageCallbacks
.reserve(4);
2817 sRemoveImageCallbacks
.reserve(4);
2818 sImageFilesNeedingTermination
.reserve(16);
2819 sImageFilesNeedingDOFUnregistration
.reserve(8);
2822 // instantiate ImageLoader for main executable
2823 sMainExecutable
= instantiateFromLoadedImage(mainExecutableMH
, mainExecutableSlide
, sExecPath
);
2824 sMainExecutable
->setNeverUnload();
2825 gLinkContext
.mainExecutable
= sMainExecutable
;
2826 // load shared cache
2827 checkSharedRegionDisable();
2828 #if DYLD_SHARED_CACHE_SUPPORT
2829 if ( gLinkContext
.sharedRegionMode
!= ImageLoader::kDontUseSharedRegion
)
2832 // load any inserted libraries
2833 if ( sEnv
.DYLD_INSERT_LIBRARIES
!= NULL
) {
2834 for (const char* const* lib
= sEnv
.DYLD_INSERT_LIBRARIES
; *lib
!= NULL
; ++lib
)
2835 loadInsertedDylib(*lib
);
2837 // record count of inserted libraries so that a flat search will look at
2838 // inserted libraries, then main, then others.
2839 sInsertedDylibCount
= sAllImages
.size()-1;
2841 // link main executable
2842 gLinkContext
.linkingMainExecutable
= true;
2843 link(sMainExecutable
, sEnv
.DYLD_BIND_AT_LAUNCH
, ImageLoader::RPathChain(NULL
, NULL
));
2844 gLinkContext
.linkingMainExecutable
= false;
2845 if ( sMainExecutable
->forceFlat() ) {
2846 gLinkContext
.bindFlat
= true;
2847 gLinkContext
.prebindUsage
= ImageLoader::kUseNoPrebinding
;
2849 result
= (uintptr_t)sMainExecutable
->getMain();
2851 // link any inserted libraries
2852 // do this after linking main executable so that any dylibs pulled in by inserted
2853 // dylibs (e.g. libSystem) will not be in front of dylibs the program uses
2854 if ( sInsertedDylibCount
> 0 ) {
2855 for(unsigned int i
=0; i
< sInsertedDylibCount
; ++i
) {
2856 ImageLoader
* image
= sAllImages
[i
+1];
2857 link(image
, sEnv
.DYLD_BIND_AT_LAUNCH
, ImageLoader::RPathChain(NULL
, NULL
));
2861 #if SUPPORT_OLD_CRT_INITIALIZATION
2862 // Old way is to run initializers via a callback from crt1.o
2863 if ( ! gRunInitializersOldWay
)
2865 initializeMainExecutable(); // run all initializers
2867 catch(const char* message
) {
2871 dyld::log("dyld: launch failed\n");