1 /* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*-
3 * Copyright (c) 2004-2005 Apple Computer, 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@
29 #include <sys/param.h>
30 #include <mach/mach_time.h> // mach_absolute_time()
31 #include <sys/types.h>
33 #include <mach-o/fat.h>
34 #include <mach-o/loader.h>
35 #include <libkern/OSByteOrder.h>
36 #include <mach/mach.h>
37 #include <sys/sysctl.h>
41 #include "mach-o/dyld_gdb.h"
44 #include "ImageLoader.h"
45 #include "ImageLoaderMachO.h"
46 #include "dyldLibSystemThreadHelpers.h"
49 #define CPU_TYPE_MASK 0x00FFFFFF /* complement of CPU_ARCH_MASK */
52 /* implemented in dyld_gdb.cpp */
53 void addImagesToAllImages(uint32_t infoCount
, const dyld_image_info info
[]);
54 void removeImageFromAllImages(const mach_header
* mh
);
55 #if OLD_GDB_DYLD_INTERFACE
56 void addImageForgdb(const mach_header
* mh
, uintptr_t slide
, const char* physicalPath
, const char* logicalPath
);
57 void removeImageForgdb(const struct mach_header
* mh
);
60 // magic so CrashReporter logs message
62 char error_string
[1024];
67 // The file contains the core of dyld used to get a process to main().
68 // The API's that dyld supports are implemented in dyldAPIs.cpp.
80 // state of all environment variables dyld uses
82 struct EnvironmentVariables
{
83 const char* const * DYLD_FRAMEWORK_PATH
;
84 const char* const * DYLD_FALLBACK_FRAMEWORK_PATH
;
85 const char* const * DYLD_LIBRARY_PATH
;
86 const char* const * DYLD_FALLBACK_LIBRARY_PATH
;
87 const char* const * DYLD_ROOT_PATH
;
88 const char* const * DYLD_INSERT_LIBRARIES
;
89 const char* const * LD_LIBRARY_PATH
; // for unix conformance
90 bool DYLD_PRINT_LIBRARIES
;
91 bool DYLD_PRINT_LIBRARIES_POST_LAUNCH
;
92 bool DYLD_BIND_AT_LAUNCH
;
93 bool DYLD_PRINT_STATISTICS
;
96 // DYLD_IMAGE_SUFFIX ==> gLinkContext.imageSuffix
97 // DYLD_PRINT_OPTS ==> gLinkContext.verboseOpts
98 // DYLD_PRINT_ENV ==> gLinkContext.verboseEnv
99 // DYLD_FORCE_FLAT_NAMESPACE ==> gLinkContext.bindFlat
100 // DYLD_PRINT_INITIALIZERS ==> gLinkContext.verboseInit
101 // DYLD_PRINT_SEGMENTS ==> gLinkContext.verboseMapping
102 // DYLD_PRINT_BINDINGS ==> gLinkContext.verboseBind
103 // DYLD_PRINT_REBASINGS ==> gLinkContext.verboseRebase
104 // DYLD_PRINT_APIS ==> gLogAPIs
105 // DYLD_IGNORE_PREBINDING ==> gLinkContext.prebindUsage
106 // DYLD_PREBIND_DEBUG ==> gLinkContext.verbosePrebinding
107 // DYLD_NEW_LOCAL_SHARED_REGIONS ==> gLinkContext.sharedRegionMode
108 // DYLD_SHARED_REGION ==> gLinkContext.sharedRegionMode
109 // DYLD_SLIDE_AND_PACK_DYLIBS ==> gLinkContext.slideAndPackDylibs
110 // DYLD_PRINT_WARNINGS ==> gLinkContext.verboseWarnings
114 static const char* sExecPath
= NULL
;
115 static const struct mach_header
* sMainExecutableMachHeader
= NULL
;
116 static cpu_type_t sHostCPU
;
117 static cpu_subtype_t sHostCPUsubtype
;
118 static ImageLoader
* sMainExecutable
= NULL
;
119 static std::vector
<ImageLoader
*> sAllImages
;
120 static std::vector
<ImageLoader
*> sImageRoots
;
121 static std::vector
<ImageLoader
*> sImageFilesNeedingTermination
;
122 static std::vector
<ImageLoader
*> sImagesToNotifyAboutOtherImages
;
123 static std::vector
<ImageCallback
> sAddImageCallbacks
;
124 static std::vector
<ImageCallback
> sRemoveImageCallbacks
;
125 static ImageLoader
* sLastImageByAddressCache
;
126 static EnvironmentVariables sEnv
;
127 static const char* sFrameworkFallbackPaths
[] = { "$HOME/Library/Frameworks", "/Library/Frameworks", "/Network/Library/Frameworks", "/System/Library/Frameworks", NULL
};
128 static const char* sLibraryFallbackPaths
[] = { "$HOME/lib", "/usr/local/lib", "/usr/lib", NULL
};
129 static BundleNotificationCallBack sBundleNotifier
= NULL
;
130 static BundleLocatorCallBack sBundleLocation
= NULL
;
131 static UndefinedHandler sUndefinedHandler
= NULL
;
132 ImageLoader::LinkContext gLinkContext
;
133 bool gLogAPIs
= false;
134 const struct ThreadingHelpers
* gThreadHelpers
= NULL
;
138 // utility class to assure files are closed when an exception is thrown
141 FileOpener(const char* path
);
143 int getFileDescriptor() { return fd
; }
148 FileOpener::FileOpener(const char* path
)
150 fd
= open(path
, O_RDONLY
, 0);
153 FileOpener::~FileOpener()
160 // Objective-C installs an addImage hook to dyld to get notified about new images
161 // The callback needs to be run after the image is rebased and bound, but before its initializers are called
162 static uint32_t imageNotification(ImageLoader
* image
, uint32_t startIndex
)
164 // tell all register add image handlers about this
165 const uint32_t callbackCount
= sAddImageCallbacks
.size();
166 for (uint32_t i
=startIndex
; i
< callbackCount
; ++i
) {
167 ImageCallback cb
= sAddImageCallbacks
[i
];
168 //fprintf(stderr, "dyld: calling add-image-callback[%d]=%p for %s\n", i, cb, image->getPath());
169 (cb
)(image
->machHeader(), image
->getSlide());
171 return callbackCount
;
176 // notify gdb et al about these new images
177 static void notifyAdding(std::vector
<ImageLoader
*>& images
)
180 unsigned int len
= images
.size();
182 dyld_image_info infos
[len
];
183 for (unsigned int i
=0; i
< len
; ++i
) {
184 dyld_image_info
* p
= &infos
[i
];
185 ImageLoader
* image
= images
[i
];
186 p
->imageLoadAddress
= image
->machHeader();
187 p
->imageFilePath
= image
->getPath();
188 p
->imageFileModDate
= image
->lastModified();
189 //fprintf(stderr, "notifying objc about %s\n", image->getPath());
193 addImagesToAllImages(len
, infos
);
195 // tell all interested images (after gdb, so you can debug anything the notification does)
196 for (std::vector
<ImageLoader
*>::iterator it
=sImagesToNotifyAboutOtherImages
.begin(); it
!= sImagesToNotifyAboutOtherImages
.end(); it
++) {
197 (*it
)->doNotification(dyld_image_adding
, len
, infos
);
204 // In order for register_func_for_add_image() callbacks to to be called bottom up,
205 // we need to maintain a list of root images. The main executable is usally the
206 // first root. Any images dynamically added are also roots (unless already loaded).
207 // If DYLD_INSERT_LIBRARIES is used, those libraries are first.
208 static void addRootImage(ImageLoader
* image
)
210 //fprintf(stderr, "addRootImage(%p, %s)\n", image, image->getPath());
211 // add to list of roots
212 sImageRoots
.push_back(image
);
215 // Objective-C will contain a __DATA/__image_notify section which contains pointers to a function to call
216 // whenever any new image is loaded.
217 static void addImageNeedingNotification(ImageLoader
* image
)
219 sImagesToNotifyAboutOtherImages
.push_back(image
);
222 static void addImage(ImageLoader
* image
)
224 // add to master list
225 sAllImages
.push_back(image
);
227 if ( sEnv
.DYLD_PRINT_LIBRARIES
|| (sEnv
.DYLD_PRINT_LIBRARIES_POST_LAUNCH
&& (sMainExecutable
!=NULL
) && sMainExecutable
->isLinked()) ) {
228 uint64_t offset
= image
->getOffsetInFatFile();
230 fprintf(stderr
, "dyld: loaded: %s\n", image
->getPath());
232 fprintf(stderr
, "dyld: loaded: %s, cpu-sub-type: %d\n", image
->getPath(), image
->machHeader()->cpusubtype
);
235 #if OLD_GDB_DYLD_INTERFACE
236 // let gdb find out about this
237 addImageForgdb(image
->machHeader(), image
->getSlide(), image
->getPath(), image
->getLogicalPath());
241 void removeImage(ImageLoader
* image
)
243 // flush find-by-address cache
244 if ( sLastImageByAddressCache
== image
)
245 sLastImageByAddressCache
= NULL
;
247 // if in termination list, pull it out and run terminator
248 for (std::vector
<ImageLoader
*>::iterator it
=sImageFilesNeedingTermination
.begin(); it
!= sImageFilesNeedingTermination
.end(); it
++) {
249 if ( *it
== image
) {
250 sImageFilesNeedingTermination
.erase(it
);
251 image
->doTermination(gLinkContext
);
256 // tell all register add image handlers about this
257 // do this before removing image from internal data structures so that the callback can querey dyld about the image
258 for (std::vector
<ImageCallback
>::iterator it
=sRemoveImageCallbacks
.begin(); it
!= sRemoveImageCallbacks
.end(); it
++) {
259 (*it
)(image
->machHeader(), image
->getSlide());
262 // tell all interested images
263 for (std::vector
<ImageLoader
*>::iterator it
=sImagesToNotifyAboutOtherImages
.begin(); it
!= sImagesToNotifyAboutOtherImages
.end(); it
++) {
264 dyld_image_info info
;
265 info
.imageLoadAddress
= image
->machHeader();
266 info
.imageFilePath
= image
->getPath();
267 info
.imageFileModDate
= image
->lastModified();
268 (*it
)->doNotification(dyld_image_removing
, 1, &info
);
271 // remove from master list
272 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
273 if ( *it
== image
) {
274 sAllImages
.erase(it
);
279 // if in announcement list, pull it out
280 for (std::vector
<ImageLoader
*>::iterator it
=sImagesToNotifyAboutOtherImages
.begin(); it
!= sImagesToNotifyAboutOtherImages
.end(); it
++) {
281 if ( *it
== image
) {
282 sImagesToNotifyAboutOtherImages
.erase(it
);
287 // if in root list, pull it out
288 for (std::vector
<ImageLoader
*>::iterator it
=sImageRoots
.begin(); it
!= sImageRoots
.end(); it
++) {
289 if ( *it
== image
) {
290 sImageRoots
.erase(it
);
296 removeImageFromAllImages(image
->machHeader());
298 #if OLD_GDB_DYLD_INTERFACE
300 removeImageForgdb(image
->machHeader());
301 gdb_dyld_state_changed();
306 static void terminationRecorder(ImageLoader
* image
)
308 sImageFilesNeedingTermination
.push_back(image
);
311 const char* getExecutablePath()
317 void initializeMainExecutable()
319 const int rootCount
= sImageRoots
.size();
320 for(int i
=0; i
< rootCount
; ++i
) {
321 ImageLoader
* image
= sImageRoots
[i
];
322 //fprintf(stderr, "initializeMainExecutable: image = %p\n", image);
323 image
->runInitializers(gLinkContext
);
326 // this does not work???
327 for (std::vector<ImageLoader*>::iterator it=sImageRoots.begin(); it != sImageRoots.end(); it++) {
328 ImageLoader* image = *it;
329 fprintf(stderr, "initializeMainExecutable: image = %p\n", image);
330 // don't know why vector sometimes starts with NULL element???
332 image->runInitializers(gLinkContext);
335 if ( sEnv
.DYLD_PRINT_STATISTICS
)
336 ImageLoaderMachO::printStatistics(sAllImages
.size());
339 bool mainExecutablePrebound()
341 return sMainExecutable
->usablePrebinding(gLinkContext
);
344 ImageLoader
* mainExecutable()
346 return sMainExecutable
;
350 void runTerminators()
352 const unsigned int imageCount
= sImageFilesNeedingTermination
.size();
353 for(unsigned int i
=imageCount
; i
> 0; --i
){
354 ImageLoader
* image
= sImageFilesNeedingTermination
[i
-1];
355 image
->doTermination(gLinkContext
);
357 sImageFilesNeedingTermination
.clear();
362 // Turns a colon separated list of strings
363 // into a NULL terminated array of string
366 static const char** parseColonList(const char* list
)
368 if ( list
[0] == '\0' )
372 for(const char* s
=list
; *s
!= '\0'; ++s
) {
378 const char* start
= list
;
379 char** result
= new char*[colonCount
+2];
380 for(const char* s
=list
; *s
!= '\0'; ++s
) {
383 char* str
= new char[len
+1];
384 strncpy(str
, start
, len
);
387 result
[index
++] = str
;
390 int len
= strlen(start
);
391 char* str
= new char[len
+1];
393 result
[index
++] = str
;
394 result
[index
] = NULL
;
396 return (const char**)result
;
400 * Library path searching is not done for setuid programs
401 * which are not run by the real user. Futher the
402 * evironment varaible for the library path is cleared so
403 * that if this program executes a non-set uid program this
404 * part of the evironment will not be passed along so that
405 * that program also will not have it's libraries searched
408 static bool riskyUser()
410 static bool checked
= false;
411 static bool risky
= false;
413 risky
= ( getuid() != 0 && (getuid() != geteuid() || getgid() != getegid()) );
420 static bool disableIfBadUser(char* rhs
)
422 bool didDisable
= false;
430 static void paths_expand_roots(const char **paths
, const char *key
, const char *val
)
432 // assert(val != NULL);
433 // assert(paths != NULL);
435 size_t keyLen
= strlen(key
);
436 for(int i
=0; paths
[i
] != NULL
; ++i
) {
437 if ( strncmp(paths
[i
], key
, keyLen
) == 0 ) {
438 char* newPath
= new char[strlen(val
) + (strlen(paths
[i
]) - keyLen
) + 1];
439 strcpy(newPath
, val
);
440 strcat(newPath
, &paths
[i
][keyLen
]);
448 static void removePathWithPrefix(const char* paths
[], const char* prefix
)
450 size_t prefixLen
= strlen(prefix
);
451 for(int s
=0,d
=0; (paths
[d
] != NULL
) && (paths
[s
] != NULL
); ++s
, ++d
) {
452 if ( strncmp(paths
[s
], prefix
, prefixLen
) == 0 )
459 static void paths_dump(const char **paths
)
461 // assert(paths != NULL);
462 const char **strs
= paths
;
465 fprintf(stderr
, "\"%s\"\n", *strs
);
472 static void printOptions(const char* argv
[])
475 while ( NULL
!= argv
[i
] ) {
476 fprintf(stderr
, "opt[%i] = \"%s\"\n", i
, argv
[i
]);
481 static void printEnvironmentVariables(const char* envp
[])
483 while ( NULL
!= *envp
) {
484 fprintf(stderr
, "%s\n", *envp
);
491 void processDyldEnvironmentVarible(const char* key
, const char* value
)
493 if ( strcmp(key
, "DYLD_FRAMEWORK_PATH") == 0 ) {
494 if ( !disableIfBadUser((char*)value
) )
495 sEnv
.DYLD_FRAMEWORK_PATH
= parseColonList(value
);
497 else if ( strcmp(key
, "DYLD_FALLBACK_FRAMEWORK_PATH") == 0 ) {
498 if ( !disableIfBadUser((char*)value
) )
499 sEnv
.DYLD_FALLBACK_FRAMEWORK_PATH
= parseColonList(value
);
501 else if ( strcmp(key
, "DYLD_LIBRARY_PATH") == 0 ) {
502 if ( !disableIfBadUser((char*)value
) )
503 sEnv
.DYLD_LIBRARY_PATH
= parseColonList(value
);
505 else if ( strcmp(key
, "DYLD_FALLBACK_LIBRARY_PATH") == 0 ) {
506 if ( !disableIfBadUser((char*)value
) )
507 sEnv
.DYLD_FALLBACK_LIBRARY_PATH
= parseColonList(value
);
509 else if ( (strcmp(key
, "DYLD_ROOT_PATH") == 0) || (strcmp(key
, "DYLD_PATHS_ROOT") == 0) ) {
510 if ( !disableIfBadUser((char*)value
) ) {
511 if ( strcmp(value
, "/") != 0 ) {
512 sEnv
.DYLD_ROOT_PATH
= parseColonList(value
);
513 for (int i
=0; sEnv
.DYLD_ROOT_PATH
[i
] != NULL
; ++i
) {
514 if ( sEnv
.DYLD_ROOT_PATH
[i
][0] != '/' ) {
515 fprintf(stderr
, "dyld: warning DYLD_ROOT_PATH not used because it contains a non-absolute path\n");
516 sEnv
.DYLD_ROOT_PATH
= NULL
;
523 else if ( strcmp(key
, "DYLD_IMAGE_SUFFIX") == 0 ) {
524 if ( !disableIfBadUser((char*)value
) )
525 gLinkContext
.imageSuffix
= value
;
527 else if ( strcmp(key
, "DYLD_INSERT_LIBRARIES") == 0 ) {
528 if ( !disableIfBadUser((char*)value
) )
529 sEnv
.DYLD_INSERT_LIBRARIES
= parseColonList(value
);
531 else if ( strcmp(key
, "DYLD_DEBUG_TRACE") == 0 ) {
532 fprintf(stderr
, "dyld: warning DYLD_DEBUG_TRACE not supported\n");
534 else if ( strcmp(key
, "DYLD_ERROR_PRINT") == 0 ) {
535 fprintf(stderr
, "dyld: warning DYLD_ERROR_PRINT not supported\n");
537 else if ( strcmp(key
, "DYLD_PRINT_OPTS") == 0 ) {
538 sEnv
.DYLD_PRINT_OPTS
= true;
540 else if ( strcmp(key
, "DYLD_PRINT_ENV") == 0 ) {
541 sEnv
.DYLD_PRINT_ENV
= true;
543 else if ( strcmp(key
, "DYLD_PRINT_LIBRARIES") == 0 ) {
544 sEnv
.DYLD_PRINT_LIBRARIES
= true;
546 else if ( strcmp(key
, "DYLD_PRINT_LIBRARIES_POST_LAUNCH") == 0 ) {
547 sEnv
.DYLD_PRINT_LIBRARIES_POST_LAUNCH
= true;
549 else if ( strcmp(key
, "DYLD_TRACE") == 0 ) {
550 fprintf(stderr
, "dyld: warning DYLD_TRACE not supported\n");
552 else if ( strcmp(key
, "DYLD_EBADEXEC_ONLY") == 0 ) {
553 fprintf(stderr
, "dyld: warning DYLD_EBADEXEC_ONLY not supported\n");
555 else if ( strcmp(key
, "DYLD_BIND_AT_LAUNCH") == 0 ) {
556 sEnv
.DYLD_BIND_AT_LAUNCH
= true;
558 else if ( strcmp(key
, "DYLD_FORCE_FLAT_NAMESPACE") == 0 ) {
559 gLinkContext
.bindFlat
= true;
561 else if ( strcmp(key
, "DYLD_DEAD_LOCK_HANG") == 0 ) {
562 fprintf(stderr
, "dyld: warning DYLD_DEAD_LOCK_HANG not supported\n");
564 else if ( strcmp(key
, "DYLD_ABORT_MULTIPLE_INITS") == 0 ) {
565 fprintf(stderr
, "dyld: warning DYLD_ABORT_MULTIPLE_INITS not supported\n");
567 else if ( strcmp(key
, "DYLD_NEW_LOCAL_SHARED_REGIONS") == 0 ) {
568 gLinkContext
.sharedRegionMode
= ImageLoader::kUsePrivateSharedRegion
;
570 else if ( strcmp(key
, "DYLD_SLIDE_AND_PACK_DYLIBS") == 0 ) {
571 gLinkContext
.slideAndPackDylibs
= true;
573 else if ( strcmp(key
, "DYLD_NO_FIX_PREBINDING") == 0 ) {
574 // since the new dyld never runs fix_prebinding, no need to warn if someone does not want it run
575 //fprintf(stderr, "dyld: warning DYLD_NO_FIX_PREBINDING not supported\n");
577 else if ( strcmp(key
, "DYLD_PREBIND_DEBUG") == 0 ) {
578 gLinkContext
.verbosePrebinding
= true;
580 else if ( strcmp(key
, "DYLD_HINTS_DEBUG") == 0 ) {
581 fprintf(stderr
, "dyld: warning DYLD_HINTS_DEBUG not supported\n");
583 else if ( strcmp(key
, "DYLD_SAMPLE_DEBUG") == 0 ) {
584 fprintf(stderr
, "dyld: warning DYLD_SAMPLE_DEBUG not supported\n");
586 else if ( strcmp(key
, "DYLD_EXECUTABLE_PATH_DEBUG") == 0 ) {
587 fprintf(stderr
, "dyld: warning DYLD_EXECUTABLE_PATH_DEBUG not supported\n");
589 else if ( strcmp(key
, "DYLD_TWO_LEVEL_DEBUG") == 0 ) {
590 fprintf(stderr
, "dyld: warning DYLD_TWO_LEVEL_DEBUG not supported\n");
592 else if ( strcmp(key
, "DYLD_LAZY_INITIALIZERS") == 0 ) {
593 fprintf(stderr
, "dyld: warning DYLD_LAZY_INITIALIZERS not supported\n");
595 else if ( strcmp(key
, "DYLD_PRINT_INITIALIZERS") == 0 ) {
596 gLinkContext
.verboseInit
= true;
598 else if ( strcmp(key
, "DYLD_PRINT_STATISTICS") == 0 ) {
599 sEnv
.DYLD_PRINT_STATISTICS
= true;
601 else if ( strcmp(key
, "DYLD_PRINT_SEGMENTS") == 0 ) {
602 gLinkContext
.verboseMapping
= true;
604 else if ( strcmp(key
, "DYLD_PRINT_BINDINGS") == 0 ) {
605 gLinkContext
.verboseBind
= true;
607 else if ( strcmp(key
, "DYLD_PRINT_REBASINGS") == 0 ) {
608 gLinkContext
.verboseRebase
= true;
610 else if ( strcmp(key
, "DYLD_PRINT_APIS") == 0 ) {
613 else if ( strcmp(key
, "DYLD_PRINT_WARNINGS") == 0 ) {
614 gLinkContext
.verboseWarnings
= true;
616 else if ( strcmp(key
, "DYLD_SHARED_REGION") == 0 ) {
617 if ( strcmp(value
, "private") == 0 ) {
618 gLinkContext
.sharedRegionMode
= ImageLoader::kUsePrivateSharedRegion
;
620 else if ( strcmp(value
, "avoid") == 0 ) {
621 gLinkContext
.sharedRegionMode
= ImageLoader::kDontUseSharedRegion
;
623 else if ( strcmp(value
, "use") == 0 ) {
624 gLinkContext
.sharedRegionMode
= ImageLoader::kUseSharedRegion
;
626 else if ( value
[0] == '\0' ) {
627 gLinkContext
.sharedRegionMode
= ImageLoader::kUseSharedRegion
;
630 fprintf(stderr
, "dyld: warning unknown option to DYLD_SHARED_REGION. Valid options are: use, private, avoid\n");
633 else if ( strcmp(key
, "DYLD_IGNORE_PREBINDING") == 0 ) {
634 if ( strcmp(value
, "all") == 0 ) {
635 gLinkContext
.prebindUsage
= ImageLoader::kUseNoPrebinding
;
637 else if ( strcmp(value
, "app") == 0 ) {
638 gLinkContext
.prebindUsage
= ImageLoader::kUseAllButAppPredbinding
;
640 else if ( strcmp(value
, "nonsplit") == 0 ) {
641 gLinkContext
.prebindUsage
= ImageLoader::kUseSplitSegPrebinding
;
643 else if ( value
[0] == '\0' ) {
644 gLinkContext
.prebindUsage
= ImageLoader::kUseSplitSegPrebinding
;
647 fprintf(stderr
, "dyld: warning unknown option to DYLD_IGNORE_PREBINDING. Valid options are: all, app, nonsplit\n");
651 fprintf(stderr
, "dyld: warning, unknown environment variable: %s\n", key
);
655 static void checkEnvironmentVariables(const char* envp
[])
657 const char* home
= NULL
;
659 for(p
= envp
; *p
!= NULL
; p
++) {
660 const char* keyEqualsValue
= *p
;
661 if ( strncmp(keyEqualsValue
, "DYLD_", 5) == 0 ) {
662 const char* equals
= strchr(keyEqualsValue
, '=');
663 if ( equals
!= NULL
) {
664 const char* value
= &equals
[1];
665 const int keyLen
= equals
-keyEqualsValue
;
667 strncpy(key
, keyEqualsValue
, keyLen
);
669 processDyldEnvironmentVarible(key
, value
);
672 else if ( strncmp(keyEqualsValue
, "HOME=", 5) == 0 ) {
673 home
= &keyEqualsValue
[5];
675 else if ( strncmp(keyEqualsValue
, "LD_LIBRARY_PATH=", 16) == 0 ) {
676 const char* path
= &keyEqualsValue
[16];
677 if ( !disableIfBadUser((char*)path
) )
678 sEnv
.LD_LIBRARY_PATH
= parseColonList(path
);
682 // default value for DYLD_FALLBACK_FRAMEWORK_PATH, if not set in environment
683 if ( sEnv
.DYLD_FALLBACK_FRAMEWORK_PATH
== NULL
) {
684 const char** paths
= sFrameworkFallbackPaths
;
685 if ( home
!= NULL
) {
687 removePathWithPrefix(paths
, "$HOME");
689 paths_expand_roots(paths
, "$HOME", home
);
691 sEnv
.DYLD_FALLBACK_FRAMEWORK_PATH
= paths
;
694 // default value for DYLD_FALLBACK_LIBRARY_PATH, if not set in environment
695 if ( sEnv
.DYLD_FALLBACK_LIBRARY_PATH
== NULL
) {
696 const char** paths
= sLibraryFallbackPaths
;
697 if ( home
!= NULL
) {
699 removePathWithPrefix(paths
, "$HOME");
701 paths_expand_roots(paths
, "$HOME", home
);
703 sEnv
.DYLD_FALLBACK_LIBRARY_PATH
= paths
;
708 static void getHostInfo()
711 struct host_basic_info info
;
712 mach_msg_type_number_t count
= HOST_BASIC_INFO_COUNT
;
713 mach_port_t hostPort
= mach_host_self();
714 kern_return_t result
= host_info(hostPort
, HOST_BASIC_INFO
, (host_info_t
)&info
, &count
);
715 mach_port_deallocate(mach_task_self(), hostPort
);
716 if ( result
!= KERN_SUCCESS
)
717 throw "host_info() failed";
719 sHostCPU
= info
.cpu_type
;
720 sHostCPUsubtype
= info
.cpu_subtype
;
723 size_t valSize
= sizeof(sHostCPU
);
724 if (sysctlbyname ("hw.cputype", &sHostCPU
, &valSize
, NULL
, 0) != 0)
725 throw "sysctlbyname(hw.cputype) failed";
726 valSize
= sizeof(sHostCPUsubtype
);
727 if (sysctlbyname ("hw.cpusubtype", &sHostCPUsubtype
, &valSize
, NULL
, 0) != 0)
728 throw "sysctlbyname(hw.cpusubtype) failed";
731 bool validImage(ImageLoader
* possibleImage
)
733 const unsigned int imageCount
= sAllImages
.size();
734 for(unsigned int i
=0; i
< imageCount
; ++i
) {
735 if ( possibleImage
== sAllImages
[i
] ) {
742 uint32_t getImageCount()
744 return sAllImages
.size();
747 ImageLoader
* getIndexedImage(unsigned int index
)
749 if ( index
< sAllImages
.size() )
750 return sAllImages
[index
];
755 ImageLoader
* findImageByMachHeader(const struct mach_header
* target
)
757 const unsigned int imageCount
= sAllImages
.size();
758 for(unsigned int i
=0; i
< imageCount
; ++i
) {
759 ImageLoader
* anImage
= sAllImages
[i
];
760 if ( anImage
->machHeader() == target
)
767 ImageLoader
* findImageContainingAddress(const void* addr
)
770 static int cacheHit
= 0;
771 static int cacheMiss
= 0;
772 static int cacheNotMacho
= 0;
773 if ( ((cacheHit
+cacheMiss
+cacheNotMacho
) % 100) == 0 )
774 fprintf(stderr
, "findImageContainingAddress(): cache hit = %d, miss = %d, unknown = %d\n", cacheHit
, cacheMiss
, cacheNotMacho
);
776 // first look in image where last address was found rdar://problem/3685517
777 if ( (sLastImageByAddressCache
!= NULL
) && sLastImageByAddressCache
->containsAddress(addr
) ) {
781 return sLastImageByAddressCache
;
783 // do exhastive search
784 // todo: consider maintaining a list sorted by address ranges and do a binary search on that
785 const unsigned int imageCount
= sAllImages
.size();
786 for(unsigned int i
=0; i
< imageCount
; ++i
) {
787 ImageLoader
* anImage
= sAllImages
[i
];
788 if ( anImage
->containsAddress(addr
) ) {
789 sLastImageByAddressCache
= anImage
;
803 void forEachImageDo( void (*callback
)(ImageLoader
*, void* userData
), void* userData
)
805 const unsigned int imageCount
= sAllImages
.size();
806 for(unsigned int i
=0; i
< imageCount
; ++i
) {
807 ImageLoader
* anImage
= sAllImages
[i
];
808 (*callback
)(anImage
, userData
);
812 ImageLoader
* findLoadedImage(const struct stat
& stat_buf
)
814 const unsigned int imageCount
= sAllImages
.size();
815 for(unsigned int i
=0; i
< imageCount
; ++i
){
816 ImageLoader
* anImage
= sAllImages
[i
];
817 if ( anImage
->statMatch(stat_buf
) )
823 // based on ANSI-C strstr()
824 static const char* strrstr(const char* str
, const char* sub
)
826 const int sublen
= strlen(sub
);
827 for(const char* p
= &str
[strlen(str
)]; p
!= str
; --p
) {
828 if ( strncmp(p
, sub
, sublen
) == 0 )
836 // Find framework path
838 // /path/foo.framework/foo => foo.framework/foo
839 // /path/foo.framework/Versions/A/foo => foo.framework/Versions/A/foo
840 // /path/foo.framework/Frameworks/bar.framework/bar => bar.framework/bar
841 // /path/foo.framework/Libraries/bar.dylb => NULL
842 // /path/foo.framework/bar => NULL
844 // Returns NULL if not a framework path
846 static const char* getFrameworkPartialPath(const char* path
)
848 const char* dirDot
= strrstr(path
, ".framework/");
849 if ( dirDot
!= NULL
) {
850 const char* dirStart
= dirDot
;
851 for ( ; dirStart
>= path
; --dirStart
) {
852 if ( (*dirStart
== '/') || (dirStart
== path
) ) {
853 const char* frameworkStart
= &dirStart
[1];
854 if ( dirStart
== path
)
856 int len
= dirDot
- frameworkStart
;
857 char framework
[len
+1];
858 strncpy(framework
, frameworkStart
, len
);
859 framework
[len
] = '\0';
860 const char* leaf
= strrchr(path
, '/');
861 if ( leaf
!= NULL
) {
862 if ( strcmp(framework
, &leaf
[1]) == 0 ) {
863 return frameworkStart
;
865 if ( gLinkContext
.imageSuffix
!= NULL
) {
866 // some debug frameworks have install names that end in _debug
867 if ( strncmp(framework
, &leaf
[1], len
) == 0 ) {
868 if ( strcmp( gLinkContext
.imageSuffix
, &leaf
[len
+1]) == 0 )
869 return frameworkStart
;
880 static const char* getLibraryLeafName(const char* path
)
882 const char* start
= strrchr(path
, '/');
891 const cpu_subtype_t CPU_SUBTYPE_END_OF_LIST
= -1;
895 // A fat file may contain multiple sub-images for the same CPU type.
896 // In that case, dyld picks which sub-image to use by scanning a table
897 // of preferred cpu-sub-types for the running cpu.
899 // There is one row in the table for each cpu-sub-type on which dyld might run.
900 // The first entry in a row is that cpu-sub-type. It is followed by all
901 // cpu-sub-types that can run on that cpu, if preferred order. Each row ends with
902 // a "SUBTYPE_ALL" (to denote that images written to run on any cpu-sub-type are usable),
903 // followed by one or more CPU_SUBTYPE_END_OF_LIST to pad out this row.
908 // 32-bit PowerPC sub-type lists
910 const int kPPC_RowCount
= 4;
911 static const cpu_subtype_t kPPC32
[kPPC_RowCount
][6] = {
912 // G5 can run any code
913 { 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
},
915 // G4 can run all but G5 code
916 { 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
},
917 { 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
},
919 // G3 cannot run G4 or G5 code
920 { 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
}
925 // 64-bit PowerPC sub-type lists
927 const int kPPC64_RowCount
= 1;
928 static const cpu_subtype_t kPPC64
[kPPC64_RowCount
][3] = {
929 // G5 can run any 64-bit code
930 { CPU_SUBTYPE_POWERPC_970
, CPU_SUBTYPE_POWERPC_ALL
, CPU_SUBTYPE_END_OF_LIST
},
936 // 32-bit x86 sub-type lists
942 // scan the tables above to find the cpu-sub-type-list for this machine
943 static const cpu_subtype_t
* findCPUSubtypeList(cpu_type_t cpu
, cpu_subtype_t subtype
)
946 case CPU_TYPE_POWERPC
:
947 for (int i
=0; i
< kPPC_RowCount
; ++i
) {
948 if ( kPPC32
[i
][0] == subtype
)
952 case CPU_TYPE_POWERPC64
:
953 for (int i
=0; i
< kPPC64_RowCount
; ++i
) {
954 if ( kPPC64
[i
][0] == subtype
)
968 // scan fat table-of-contents for best most preferred subtype
969 static bool fatFindBestFromOrderedList(cpu_type_t cpu
, const cpu_subtype_t list
[], const fat_header
* fh
, uint64_t* offset
, uint64_t* len
)
971 const fat_arch
* const archs
= (fat_arch
*)(((char*)fh
)+sizeof(fat_header
));
972 for (uint32_t subTypeIndex
=0; list
[subTypeIndex
] != CPU_SUBTYPE_END_OF_LIST
; ++subTypeIndex
) {
973 for(uint32_t fatIndex
=0; fatIndex
< OSSwapBigToHostInt32(fh
->nfat_arch
); ++fatIndex
) {
974 if ( ((cpu_type_t
)OSSwapBigToHostInt32(archs
[fatIndex
].cputype
) == cpu
)
975 && (list
[subTypeIndex
] == archs
[fatIndex
].cpusubtype
) ) {
976 *offset
= OSSwapBigToHostInt32(archs
[fatIndex
].offset
);
977 *len
= OSSwapBigToHostInt32(archs
[fatIndex
].size
);
985 // scan fat table-of-contents for exact match of cpu and cpu-sub-type
986 static bool fatFindExactMatch(cpu_type_t cpu
, cpu_subtype_t subtype
, const fat_header
* fh
, uint64_t* offset
, uint64_t* len
)
988 const fat_arch
* archs
= (fat_arch
*)(((char*)fh
)+sizeof(fat_header
));
989 for(uint32_t i
=0; i
< OSSwapBigToHostInt32(fh
->nfat_arch
); ++i
) {
990 if ( ((cpu_type_t
)OSSwapBigToHostInt32(archs
[i
].cputype
) == cpu
)
991 && ((cpu_subtype_t
)OSSwapBigToHostInt32(archs
[i
].cpusubtype
) == subtype
) ) {
992 *offset
= OSSwapBigToHostInt32(archs
[i
].offset
);
993 *len
= OSSwapBigToHostInt32(archs
[i
].size
);
1000 // scan fat table-of-contents for image with matching cpu-type and runs-on-all-sub-types
1001 static bool fatFindRunsOnAllCPUs(cpu_type_t cpu
, const fat_header
* fh
, uint64_t* offset
, uint64_t* len
)
1003 const fat_arch
* archs
= (fat_arch
*)(((char*)fh
)+sizeof(fat_header
));
1004 for(uint32_t i
=0; i
< OSSwapBigToHostInt32(fh
->nfat_arch
); ++i
) {
1005 if ( (cpu_type_t
)OSSwapBigToHostInt32(archs
[i
].cputype
) == cpu
) {
1007 case CPU_TYPE_POWERPC
:
1008 case CPU_TYPE_POWERPC64
:
1009 if ( (cpu_subtype_t
)OSSwapBigToHostInt32(archs
[i
].cpusubtype
) == CPU_SUBTYPE_POWERPC_ALL
) {
1010 *offset
= OSSwapBigToHostInt32(archs
[i
].offset
);
1011 *len
= OSSwapBigToHostInt32(archs
[i
].size
);
1016 if ( (cpu_subtype_t
)OSSwapBigToHostInt32(archs
[i
].cpusubtype
) == CPU_SUBTYPE_I386_ALL
) {
1017 *offset
= OSSwapBigToHostInt32(archs
[i
].offset
);
1018 *len
= OSSwapBigToHostInt32(archs
[i
].size
);
1030 // A fat file may contain multiple sub-images for the same cpu-type,
1031 // each optimized for a different cpu-sub-type (e.g G3 or G5).
1032 // This routine picks the optimal sub-image.
1034 static bool fatFindBest(const fat_header
* fh
, uint64_t* offset
, uint64_t* len
)
1036 // assume all dylibs loaded must have same cpu type as main executable
1037 const cpu_type_t cpu
= sMainExecutableMachHeader
->cputype
;
1039 // We only know the subtype to use if the main executable cpu type matches the host
1040 if ( (cpu
& CPU_TYPE_MASK
) == sHostCPU
) {
1041 // get preference ordered list of subtypes
1042 const cpu_subtype_t
* subTypePreferenceList
= findCPUSubtypeList(cpu
, sHostCPUsubtype
);
1044 // use ordered list to find best sub-image in fat file
1045 if ( subTypePreferenceList
!= NULL
)
1046 return fatFindBestFromOrderedList(cpu
, subTypePreferenceList
, fh
, offset
, len
);
1048 // if running cpu is not in list, try for an exact match
1049 if ( fatFindExactMatch(cpu
, sHostCPUsubtype
, fh
, offset
, len
) )
1053 // running on an uknown cpu, can only load generic code
1054 return fatFindRunsOnAllCPUs(cpu
, fh
, offset
, len
);
1060 // This is used to validate if a non-fat (aka thin or raw) mach-o file can be used
1061 // on the current processor. It is deemed compatible if any of the following are true:
1062 // 1) mach_header subtype is in list of compatible subtypes for running processor
1063 // 2) mach_header subtype is same as running processor subtype
1064 // 3) mach_header subtype runs on all processor variants
1067 bool isCompatibleMachO(const uint8_t* firstPage
)
1069 const mach_header
* mh
= (mach_header
*)firstPage
;
1070 if ( mh
->magic
== sMainExecutableMachHeader
->magic
) {
1071 if ( mh
->cputype
== sMainExecutableMachHeader
->cputype
) {
1072 if ( (mh
->cputype
& CPU_TYPE_MASK
) == sHostCPU
) {
1073 // get preference ordered list of subtypes that this machine can use
1074 const cpu_subtype_t
* subTypePreferenceList
= findCPUSubtypeList(mh
->cputype
, sHostCPUsubtype
);
1075 if ( subTypePreferenceList
!= NULL
) {
1076 // if image's subtype is in the list, it is compatible
1077 for (const cpu_subtype_t
* p
= subTypePreferenceList
; *p
!= CPU_SUBTYPE_END_OF_LIST
; ++p
) {
1078 if ( *p
== mh
->cpusubtype
)
1081 // have list and not in list, so not compatible
1082 throw "incompatible cpu-subtype";
1084 // unknown cpu sub-type, but if exact match for current subtype then ok to use
1085 if ( mh
->cpusubtype
== sHostCPUsubtype
)
1089 // cpu unknown, so don't know if subtype is compatible
1090 // only load _ALL variant
1091 switch (mh
->cputype
) {
1092 case CPU_TYPE_POWERPC
:
1093 case CPU_TYPE_POWERPC64
:
1094 if ( mh
->cpusubtype
== CPU_SUBTYPE_POWERPC_ALL
)
1098 if ( mh
->cpusubtype
== CPU_SUBTYPE_I386_ALL
)
1108 // The kernel maps in main executable before dyld gets control. We need to
1109 // make an ImageLoader* for the already mapped in main executable.
1110 static ImageLoader
* instantiateFromLoadedImage(const struct mach_header
* mh
, const char* path
)
1112 // try mach-o loader
1113 if ( isCompatibleMachO((const uint8_t*)mh
) ) {
1114 ImageLoader
* image
= new ImageLoaderMachO(path
, mh
, 0, gLinkContext
);
1125 // map in file and instantiate an ImageLoader
1126 static ImageLoader
* loadPhase6(int fd
, struct stat
& stat_buf
, const char* path
, const LoadContext
& context
)
1128 //fprintf(stderr, "%s(%s)\n", __func__ , path);
1129 uint64_t fileOffset
= 0;
1130 uint64_t fileLength
= stat_buf
.st_size
;
1132 if ( *((uint32_t*)((char*)(&stat_buf
)+0x60)) == 0xFEFEFEFE )
1133 fileLength
= *((uint64_t*)((char*)(&stat_buf
)+0x30)); // HACK work around for kernel stat bug rdar://problem/3845883
1136 // validate it is a file (not directory)
1137 if ( (stat_buf
.st_mode
& S_IFMT
) != S_IFREG
)
1141 if ( fileLength
< 4096 ) {
1142 throw "file to short";
1145 uint8_t firstPage
[4096];
1146 pread(fd
, firstPage
, 4096,0);
1148 // if fat wrapper, find usable sub-file
1149 const fat_header
* fileStartAsFat
= (fat_header
*)firstPage
;
1150 if ( fileStartAsFat
->magic
== OSSwapBigToHostInt32(FAT_MAGIC
) ) {
1151 if ( fatFindBest(fileStartAsFat
, &fileOffset
, &fileLength
) ) {
1152 pread(fd
, firstPage
, 4096, fileOffset
);
1155 throw "no matching architecture in fat wrapper";
1159 // try mach-o loader
1160 if ( isCompatibleMachO(firstPage
) ) {
1161 char realFilePath
[PATH_MAX
];
1162 if ( gLinkContext
.slideAndPackDylibs
) {
1163 // when prebinding, we always want to track the real path of images
1164 if ( realpath(path
, realFilePath
) != NULL
)
1165 path
= realFilePath
;
1168 // instantiate an image
1169 ImageLoader
* image
= new ImageLoaderMachO(path
, fd
, firstPage
, fileOffset
, fileLength
, stat_buf
, gLinkContext
);
1171 // now sanity check that this loaded image does not have the same install path as any existing image
1172 const char* loadedImageInstallPath
= image
->getInstallPath();
1173 if ( image
->isDylib() && (loadedImageInstallPath
!= NULL
) && (loadedImageInstallPath
[0] == '/') ) {
1174 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
1175 ImageLoader
* anImage
= *it
;
1176 const char* installPath
= anImage
->getInstallPath();
1177 if ( installPath
!= NULL
) {
1178 if ( strcmp(loadedImageInstallPath
, installPath
) == 0 ) {
1179 //fprintf(stderr, "duplicate(%s) => %p\n", installPath, anImage);
1187 // some API's restrict what they can load
1188 if ( context
.mustBeBundle
&& !image
->isBundle() )
1189 throw "not a bundle";
1190 if ( context
.mustBeDylib
&& !image
->isDylib() )
1191 throw "not a dylib";
1193 // don't add bundles to global list, they can be loaded but not linked. When linked it will be added to list
1194 if ( ! image
->isBundle() )
1200 // try other file formats...
1202 throwf("unknown file type, first eight bytes: 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X",
1203 firstPage
[0], firstPage
[1], firstPage
[2], firstPage
[3], firstPage
[4], firstPage
[5], firstPage
[6],firstPage
[7]);
1208 static ImageLoader
* loadPhase5open(const char* path
, const LoadContext
& context
, std::vector
<const char*>* exceptions
)
1210 //fprintf(stdout, "%s(%s)\n", __func__, path);
1211 ImageLoader
* image
= NULL
;
1213 // open file (automagically closed when this function exits)
1214 FileOpener
file(path
);
1216 //fprintf(stderr, "open(%s) => %d\n", path, file.getFileDescriptor() );
1218 if ( file
.getFileDescriptor() == -1 )
1221 struct stat stat_buf
;
1223 memset(&stat_buf
, 254, sizeof(struct stat
)); // hack until rdar://problem/3845883 is fixed
1225 if ( fstat(file
.getFileDescriptor(), &stat_buf
) == -1)
1228 // in case image was renamed or found via symlinks, check for inode match
1229 image
= findLoadedImage(stat_buf
);
1230 if ( image
!= NULL
)
1233 // needed to implement NSADDIMAGE_OPTION_RETURN_ONLY_IF_LOADED
1234 if ( context
.dontLoad
)
1238 return loadPhase6(file
.getFileDescriptor(), stat_buf
, path
, context
);
1240 catch (const char* msg
) {
1241 char* newMsg
= new char[strlen(msg
) + strlen(path
) + 8];
1242 sprintf(newMsg
, "%s: %s", path
, msg
);
1243 exceptions
->push_back(newMsg
);
1248 // look for path match with existing loaded images
1249 static ImageLoader
* loadPhase5check(const char* path
, const LoadContext
& context
)
1251 //fprintf(stderr, "%s(%s)\n", __func__ , path);
1252 // search path against load-path and install-path of all already loaded images
1253 uint32_t hash
= ImageLoader::hash(path
);
1254 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
1255 ImageLoader
* anImage
= *it
;
1256 // check has first to cut down on strcmp calls
1257 if ( anImage
->getPathHash() == hash
)
1258 if ( strcmp(path
, anImage
->getPath()) == 0 ) {
1259 // if we are looking for a dylib don't return something else
1260 if ( !context
.mustBeDylib
|| anImage
->isDylib() )
1263 if ( context
.matchByInstallName
|| anImage
->matchInstallPath() ) {
1264 const char* installPath
= anImage
->getInstallPath();
1265 if ( installPath
!= NULL
) {
1266 if ( strcmp(path
, installPath
) == 0 ) {
1267 // if we are looking for a dylib don't return something else
1268 if ( !context
.mustBeDylib
|| anImage
->isDylib() )
1275 //fprintf(stderr, "check(%s) => NULL\n", path);
1280 // open or check existing
1281 static ImageLoader
* loadPhase5(const char* path
, const LoadContext
& context
, std::vector
<const char*>* exceptions
)
1283 //fprintf(stderr, "%s(%s)\n", __func__ , path);
1284 if ( exceptions
!= NULL
)
1285 return loadPhase5open(path
, context
, exceptions
);
1287 return loadPhase5check(path
, context
);
1290 // try with and without image suffix
1291 static ImageLoader
* loadPhase4(const char* path
, const LoadContext
& context
, std::vector
<const char*>* exceptions
)
1293 //fprintf(stderr, "%s(%s)\n", __func__ , path);
1294 ImageLoader
* image
= NULL
;
1295 if ( gLinkContext
.imageSuffix
!= NULL
) {
1296 char pathWithSuffix
[strlen(path
)+strlen( gLinkContext
.imageSuffix
)+2];
1297 ImageLoader::addSuffix(path
, gLinkContext
.imageSuffix
, pathWithSuffix
);
1298 image
= loadPhase5(pathWithSuffix
, context
, exceptions
);
1300 if ( image
== NULL
)
1301 image
= loadPhase5(path
, context
, exceptions
);
1306 // expand @ variables
1307 static ImageLoader
* loadPhase3(const char* path
, const LoadContext
& context
, std::vector
<const char*>* exceptions
)
1309 //fprintf(stderr, "%s(%s)\n", __func__ , path);
1310 ImageLoader
* image
= NULL
;
1311 if ( strncmp(path
, "@executable_path/", 17) == 0 ) {
1312 // handle @executable_path path prefix
1313 const char* executablePath
= sExecPath
;
1314 char newPath
[strlen(executablePath
) + strlen(path
)];
1315 strcpy(newPath
, executablePath
);
1316 char* addPoint
= strrchr(newPath
,'/');
1317 if ( addPoint
!= NULL
)
1318 strcpy(&addPoint
[1], &path
[17]);
1320 strcpy(newPath
, &path
[17]);
1321 image
= loadPhase4(newPath
, context
, exceptions
);
1322 if ( image
!= NULL
)
1325 // perhaps main executable path is a sym link, find realpath and retry
1326 char resolvedPath
[PATH_MAX
];
1327 if ( realpath(sExecPath
, resolvedPath
) != NULL
) {
1328 char newRealPath
[strlen(resolvedPath
) + strlen(path
)];
1329 strcpy(newRealPath
, resolvedPath
);
1330 char* addPoint
= strrchr(newRealPath
,'/');
1331 if ( addPoint
!= NULL
)
1332 strcpy(&addPoint
[1], &path
[17]);
1334 strcpy(newRealPath
, &path
[17]);
1335 image
= loadPhase4(newRealPath
, context
, exceptions
);
1336 if ( image
!= NULL
)
1340 else if ( (strncmp(path
, "@loader_path/", 13) == 0) && (context
.origin
!= NULL
) ) {
1341 // handle @loader_path path prefix
1342 char newPath
[strlen(context
.origin
) + strlen(path
)];
1343 strcpy(newPath
, context
.origin
);
1344 char* addPoint
= strrchr(newPath
,'/');
1345 if ( addPoint
!= NULL
)
1346 strcpy(&addPoint
[1], &path
[13]);
1348 strcpy(newPath
, &path
[13]);
1349 image
= loadPhase4(newPath
, context
, exceptions
);
1350 if ( image
!= NULL
)
1353 // perhaps loader path is a sym link, find realpath and retry
1354 char resolvedPath
[PATH_MAX
];
1355 if ( realpath(context
.origin
, resolvedPath
) != NULL
) {
1356 char newRealPath
[strlen(resolvedPath
) + strlen(path
)];
1357 strcpy(newRealPath
, resolvedPath
);
1358 char* addPoint
= strrchr(newRealPath
,'/');
1359 if ( addPoint
!= NULL
)
1360 strcpy(&addPoint
[1], &path
[13]);
1362 strcpy(newRealPath
, &path
[13]);
1363 image
= loadPhase4(newRealPath
, context
, exceptions
);
1364 if ( image
!= NULL
)
1369 return loadPhase4(path
, context
, exceptions
);
1374 static ImageLoader
* loadPhase2(const char* path
, const LoadContext
& context
,
1375 const char* const frameworkPaths
[], const char* const libraryPaths
[],
1376 std::vector
<const char*>* exceptions
)
1378 //fprintf(stderr, "%s(%s)\n", __func__ , path);
1379 ImageLoader
* image
= NULL
;
1380 const char* frameworkPartialPath
= getFrameworkPartialPath(path
);
1381 if ( frameworkPaths
!= NULL
) {
1382 if ( frameworkPartialPath
!= NULL
) {
1383 const int frameworkPartialPathLen
= strlen(frameworkPartialPath
);
1384 for(const char* const* fp
= frameworkPaths
; *fp
!= NULL
; ++fp
) {
1385 char npath
[strlen(*fp
)+frameworkPartialPathLen
+8];
1388 strcat(npath
, frameworkPartialPath
);
1389 //fprintf(stderr, "dyld: fallback framework path used: %s() -> loadPhase4(\"%s\", ...)\n", __func__, npath);
1390 image
= loadPhase4(npath
, context
, exceptions
);
1391 if ( image
!= NULL
)
1396 if ( libraryPaths
!= NULL
) {
1397 const char* libraryLeafName
= getLibraryLeafName(path
);
1398 const int libraryLeafNameLen
= strlen(libraryLeafName
);
1399 for(const char* const* lp
= libraryPaths
; *lp
!= NULL
; ++lp
) {
1400 char libpath
[strlen(*lp
)+libraryLeafNameLen
+8];
1401 strcpy(libpath
, *lp
);
1402 strcat(libpath
, "/");
1403 strcat(libpath
, libraryLeafName
);
1404 //fprintf(stderr, "dyld: fallback library path used: %s() -> loadPhase4(\"%s\", ...)\n", __func__, libpath);
1405 image
= loadPhase4(libpath
, context
, exceptions
);
1406 if ( image
!= NULL
)
1413 // try search overrides and fallbacks
1414 static ImageLoader
* loadPhase1(const char* path
, const LoadContext
& context
, std::vector
<const char*>* exceptions
)
1416 //fprintf(stderr, "%s(%s)\n", __func__ , path);
1417 ImageLoader
* image
= NULL
;
1419 // handle LD_LIBRARY_PATH environment variables that force searching
1420 if ( context
.useLdLibraryPath
&& (sEnv
.LD_LIBRARY_PATH
!= NULL
) ) {
1421 image
= loadPhase2(path
, context
, NULL
, sEnv
.LD_LIBRARY_PATH
, exceptions
);
1422 if ( image
!= NULL
)
1426 // handle DYLD_ environment variables that force searching
1427 if ( context
.useSearchPaths
&& ((sEnv
.DYLD_FRAMEWORK_PATH
!= NULL
) || (sEnv
.DYLD_LIBRARY_PATH
!= NULL
)) ) {
1428 image
= loadPhase2(path
, context
, sEnv
.DYLD_FRAMEWORK_PATH
, sEnv
.DYLD_LIBRARY_PATH
, exceptions
);
1429 if ( image
!= NULL
)
1434 image
= loadPhase3(path
, context
, exceptions
);
1435 if ( image
!= NULL
)
1438 // try fallback paths
1439 if ( (sEnv
.DYLD_FALLBACK_FRAMEWORK_PATH
!= NULL
) || (sEnv
.DYLD_FALLBACK_LIBRARY_PATH
!= NULL
) ) {
1440 image
= loadPhase2(path
, context
, sEnv
.DYLD_FALLBACK_FRAMEWORK_PATH
, sEnv
.DYLD_FALLBACK_LIBRARY_PATH
, exceptions
);
1441 if ( image
!= NULL
)
1448 // try root substitutions
1449 static ImageLoader
* loadPhase0(const char* path
, const LoadContext
& context
, std::vector
<const char*>* exceptions
)
1451 //fprintf(stderr, "%s(%s)\n", __func__ , path);
1453 // handle DYLD_ROOT_PATH which forces absolute paths to use a new root
1454 if ( (sEnv
.DYLD_ROOT_PATH
!= NULL
) && (path
[0] == '/') ) {
1455 for(const char* const* rootPath
= sEnv
.DYLD_ROOT_PATH
; *rootPath
!= NULL
; ++rootPath
) {
1456 char newPath
[strlen(*rootPath
) + strlen(path
)+2];
1457 strcpy(newPath
, *rootPath
);
1458 strcat(newPath
, path
);
1459 ImageLoader
* image
= loadPhase1(newPath
, context
, exceptions
);
1460 if ( image
!= NULL
)
1466 return loadPhase1(path
, context
, exceptions
);
1470 // Given all the DYLD_ environment variables, the general case for loading libraries
1471 // is that any given path expands into a list of possible locations to load. We
1472 // also must take care to ensure two copies of the "same" library are never loaded.
1474 // The algorithm used here is that there is a separate function for each "phase" of the
1475 // path expansion. Each phase function calls the next phase with each possible expansion
1476 // of that phase. The result is the last phase is called with all possible paths.
1478 // To catch duplicates the algorithm is run twice. The first time, the last phase checks
1479 // the path against all loaded images. The second time, the last phase calls open() on
1480 // the path. Either time, if an image is found, the phases all unwind without checking
1483 ImageLoader
* load(const char* path
, const LoadContext
& context
)
1485 //fprintf(stderr, "%s(%s)\n", __func__ , path);
1486 char realPath
[PATH_MAX
];
1487 // when DYLD_IMAGE_SUFFIX is in used, do a realpath(), otherwise a load of "Foo.framework/Foo" will not match
1488 if ( context
.useSearchPaths
&& ( gLinkContext
.imageSuffix
!= NULL
) ) {
1489 if ( realpath(path
, realPath
) != NULL
)
1493 // try all path permutations and check against existing loaded images
1494 ImageLoader
* image
= loadPhase0(path
, context
, NULL
);
1495 if ( image
!= NULL
)
1498 // try all path permutations and try open() until first sucesss
1499 std::vector
<const char*> exceptions
;
1500 image
= loadPhase0(path
, context
, &exceptions
);
1501 if ( image
!= NULL
)
1503 else if ( context
.dontLoad
)
1505 else if ( exceptions
.size() == 0 )
1506 throw "image not found";
1508 const char* msgStart
= "no suitable image found. Did find:";
1509 const char* delim
= "\n\t";
1510 size_t allsizes
= strlen(msgStart
)+8;
1511 for (unsigned int i
=0; i
< exceptions
.size(); ++i
)
1512 allsizes
+= (strlen(exceptions
[i
]) + strlen(delim
));
1513 char* fullMsg
= new char[allsizes
];
1514 strcpy(fullMsg
, msgStart
);
1515 for (unsigned int i
=0; i
< exceptions
.size(); ++i
) {
1516 strcat(fullMsg
, delim
);
1517 strcat(fullMsg
, exceptions
[i
]);
1519 throw (const char*)fullMsg
;
1526 // create when NSLinkModule is called for a second time on a bundle
1527 ImageLoader
* cloneImage(ImageLoader
* image
)
1529 const uint64_t offsetInFat
= image
->getOffsetInFatFile();
1531 // open file (automagically closed when this function exits)
1532 FileOpener
file(image
->getPath());
1534 struct stat stat_buf
;
1536 memset(&stat_buf
, 254, sizeof(struct stat
)); // hack until rdar://problem/3845883 is fixed
1538 if ( fstat(file
.getFileDescriptor(), &stat_buf
) == -1)
1541 // read first page of file
1542 uint8_t firstPage
[4096];
1543 pread(file
.getFileDescriptor(), firstPage
, 4096, offsetInFat
);
1545 // fat length is only used for sanity checking, since this image was already loaded once, just use upper bound
1546 uint64_t lenInFat
= stat_buf
.st_size
- offsetInFat
;
1548 // try mach-o loader
1549 if ( isCompatibleMachO(firstPage
) ) {
1550 ImageLoader
* clone
= new ImageLoaderMachO(image
->getPath(), file
.getFileDescriptor(), firstPage
, offsetInFat
, lenInFat
, stat_buf
, gLinkContext
);
1551 // don't add bundles to global list, they can be loaded but not linked. When linked it will be added to list
1552 if ( ! image
->isBundle() )
1557 // try other file formats...
1558 throw "can't clone image";
1562 ImageLoader
* loadFromMemory(const uint8_t* mem
, uint64_t len
, const char* moduleName
)
1564 // try mach-o each loader
1565 if ( isCompatibleMachO(mem
) ) {
1566 ImageLoader
* image
= new ImageLoaderMachO(moduleName
, (mach_header
*)mem
, len
, gLinkContext
);
1567 // don't add bundles to global list, they can be loaded but not linked. When linked it will be added to list
1568 if ( ! image
->isBundle() )
1573 // try other file formats...
1575 throwf("unknown file type, first eight bytes: 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X",
1576 mem
[0], mem
[1], mem
[2], mem
[3], mem
[4], mem
[5], mem
[6],mem
[7]);
1580 void registerAddCallback(ImageCallback func
)
1582 // now add to list to get notified when any more images are added
1583 sAddImageCallbacks
.push_back(func
);
1585 // call callback with all existing images, starting at roots
1586 const int rootCount
= sImageRoots
.size();
1587 for(int i
=0; i
< rootCount
; ++i
) {
1588 ImageLoader
* image
= sImageRoots
[i
];
1589 image
->runNotification(gLinkContext
, sAddImageCallbacks
.size());
1592 // for (std::vector<ImageLoader*>::iterator it=sImageRoots.begin(); it != sImageRoots.end(); it++) {
1593 // ImageLoader* image = *it;
1594 // image->runNotification(gLinkContext, sAddImageCallbacks.size());
1598 void registerRemoveCallback(ImageCallback func
)
1600 sRemoveImageCallbacks
.push_back(func
);
1603 void clearErrorMessage()
1605 error_string
[0] = '\0';
1608 void setErrorMessage(const char* message
)
1610 // save off error message in global buffer for CrashReporter to find
1611 strncpy(error_string
, message
, sizeof(error_string
)-1);
1612 error_string
[sizeof(error_string
)-1] = '\0';
1615 const char* getErrorMessage()
1617 return error_string
;
1620 void halt(const char* message
)
1622 fprintf(stderr
, "dyld: %s\n", message
);
1623 setErrorMessage(message
);
1624 strncpy(error_string
, message
, sizeof(error_string
)-1);
1625 error_string
[sizeof(error_string
)-1] = '\0';
1627 #if __ppc__ || __ppc64__
1632 #error unknown architecture
1634 abort(); // needed to suppress warning that noreturn function returns
1638 uintptr_t bindLazySymbol(const mach_header
* mh
, uintptr_t* lazyPointer
)
1640 uintptr_t result
= 0;
1641 // acquire read-lock on dyld's data structures
1642 #if 0 // rdar://problem/3811777 turn off locking until deadlock is resolved
1643 if ( gThreadHelpers
!= NULL
)
1644 (*gThreadHelpers
->lockForReading
)();
1646 // lookup and bind lazy pointer and get target address
1648 // note, target should always be mach-o, because only mach-o lazy handler wired up to this
1649 ImageLoader
* target
= dyld::findImageByMachHeader(mh
);
1650 if ( target
== NULL
)
1651 throw "image not found for lazy pointer";
1652 result
= target
->doBindLazySymbol(lazyPointer
, gLinkContext
);
1654 catch (const char* message
) {
1655 fprintf(stderr
, "dyld: lazy symbol binding failed: %s\n", message
);
1658 // release read-lock on dyld's data structures
1660 if ( gThreadHelpers
!= NULL
)
1661 (*gThreadHelpers
->unlockForReading
)();
1663 // return target address to glue which jumps to it with real parameters restored
1668 // SPI used by ZeroLink to lazy load bundles
1669 void registerZeroLinkHandlers(BundleNotificationCallBack notify
, BundleLocatorCallBack locate
)
1671 sBundleNotifier
= notify
;
1672 sBundleLocation
= locate
;
1675 void registerUndefinedHandler(UndefinedHandler handler
)
1677 sUndefinedHandler
= handler
;
1680 static void undefinedHandler(const char* symboName
)
1682 if ( sUndefinedHandler
!= NULL
) {
1683 (*sUndefinedHandler
)(symboName
);
1687 static bool findExportedSymbol(const char* name
, bool onlyInCoalesced
, const ImageLoader::Symbol
** sym
, ImageLoader
** image
)
1689 // try ZeroLink short cut to finding bundle which exports this symbol
1690 if ( sBundleLocation
!= NULL
) {
1691 ImageLoader
* zlImage
= (*sBundleLocation
)(name
);
1692 if ( zlImage
== ((ImageLoader
*)(-1)) ) {
1693 // -1 is magic value that request symbol is in a bundle not yet linked into process
1694 // try calling handler to link in that symbol
1695 undefinedHandler(name
);
1696 // call locator again
1697 zlImage
= (*sBundleLocation
)(name
);
1699 // if still not found, then ZeroLink has no idea where to find it
1700 if ( zlImage
== ((ImageLoader
*)(-1)) )
1702 if ( zlImage
!= NULL
) {
1703 // ZeroLink cache knows where the symbol is
1704 *sym
= zlImage
->findExportedSymbol(name
, NULL
, false, image
);
1705 if ( *sym
!= NULL
) {
1711 // ZeroLink says it is in some bundle already loaded, but not linked, walk them all
1712 const unsigned int imageCount
= sAllImages
.size();
1713 for(unsigned int i
=0; i
< imageCount
; ++i
){
1714 ImageLoader
* anImage
= sAllImages
[i
];
1715 if ( anImage
->isBundle() && !anImage
->hasHiddenExports() ) {
1716 //fprintf(stderr, "dyld: search for %s in %s\n", name, anImage->getPath());
1717 *sym
= anImage
->findExportedSymbol(name
, NULL
, false, image
);
1718 if ( *sym
!= NULL
) {
1726 // search all images in order
1727 ImageLoader
* firstWeakImage
= NULL
;
1728 const ImageLoader::Symbol
* firstWeakSym
= NULL
;
1729 const unsigned int imageCount
= sAllImages
.size();
1730 for(unsigned int i
=0; i
< imageCount
; ++i
){
1731 ImageLoader
* anImage
= sAllImages
[i
];
1732 if ( ! anImage
->hasHiddenExports() && (!onlyInCoalesced
|| anImage
->hasCoalescedExports()) ) {
1733 *sym
= anImage
->findExportedSymbol(name
, NULL
, false, image
);
1734 if ( *sym
!= NULL
) {
1735 // if weak definition found, record first one found
1736 if ( ((*image
)->getExportedSymbolInfo(*sym
) & ImageLoader::kWeakDefinition
) != 0 ) {
1737 if ( firstWeakImage
== NULL
) {
1738 firstWeakImage
= *image
;
1739 firstWeakSym
= *sym
;
1743 // found non-weak, so immediately return with it
1749 if ( firstWeakSym
!= NULL
) {
1750 // found a weak definition, but no non-weak, so return first weak found
1751 *sym
= firstWeakSym
;
1752 *image
= firstWeakImage
;
1759 bool flatFindExportedSymbol(const char* name
, const ImageLoader::Symbol
** sym
, ImageLoader
** image
)
1761 return findExportedSymbol(name
, false, sym
, image
);
1764 bool findCoalescedExportedSymbol(const char* name
, const ImageLoader::Symbol
** sym
, ImageLoader
** image
)
1766 return findExportedSymbol(name
, true, sym
, image
);
1770 bool flatFindExportedSymbolWithHint(const char* name
, const char* librarySubstring
, const ImageLoader::Symbol
** sym
, ImageLoader
** image
)
1772 // search all images in order
1773 const unsigned int imageCount
= sAllImages
.size();
1774 for(unsigned int i
=0; i
< imageCount
; ++i
){
1775 ImageLoader
* anImage
= sAllImages
[i
];
1776 // only look at images whose paths contain the hint string (NULL hint string is wildcard)
1777 if ( ! anImage
->isBundle() && ((librarySubstring
==NULL
) || (strstr(anImage
->getPath(), librarySubstring
) != NULL
)) ) {
1778 *sym
= anImage
->findExportedSymbol(name
, NULL
, false, image
);
1779 if ( *sym
!= NULL
) {
1787 static void getMappedRegions(ImageLoader::RegionsVector
& regions
)
1789 const unsigned int imageCount
= sAllImages
.size();
1790 for(unsigned int i
=0; i
< imageCount
; ++i
){
1791 ImageLoader
* anImage
= sAllImages
[i
];
1792 anImage
->addMappedRegions(regions
);
1797 static ImageLoader
* libraryLocator(const char* libraryName
, bool search
, const char* origin
, const char* rpath
[])
1799 dyld::LoadContext context
;
1800 context
.useSearchPaths
= search
;
1801 context
.useLdLibraryPath
= false;
1802 context
.dontLoad
= false;
1803 context
.mustBeBundle
= false;
1804 context
.mustBeDylib
= true;
1805 context
.matchByInstallName
= false;
1806 context
.origin
= origin
;
1807 context
.rpath
= rpath
;
1808 return load(libraryName
, context
);
1812 static void setContext(int argc
, const char* argv
[], const char* envp
[], const char* apple
[])
1814 gLinkContext
.loadLibrary
= &libraryLocator
;
1815 gLinkContext
.imageNotification
= &imageNotification
;
1816 gLinkContext
.terminationRecorder
= &terminationRecorder
;
1817 gLinkContext
.flatExportFinder
= &flatFindExportedSymbol
;
1818 gLinkContext
.coalescedExportFinder
= &findCoalescedExportedSymbol
;
1819 gLinkContext
.undefinedHandler
= &undefinedHandler
;
1820 gLinkContext
.addImageNeedingNotification
= &addImageNeedingNotification
;
1821 gLinkContext
.notifyAdding
= ¬ifyAdding
;
1822 gLinkContext
.getAllMappedRegions
= &getMappedRegions
;
1823 gLinkContext
.bindingHandler
= NULL
;
1824 gLinkContext
.bindingOptions
= ImageLoader::kBindingNone
;
1825 gLinkContext
.mainExecutable
= sMainExecutable
;
1826 gLinkContext
.argc
= argc
;
1827 gLinkContext
.argv
= argv
;
1828 gLinkContext
.envp
= envp
;
1829 gLinkContext
.apple
= apple
;
1834 void link(ImageLoader
* image
, ImageLoader::BindingLaziness bindness
, ImageLoader::InitializerRunning runInitializers
)
1836 // add to list of known images. This did not happen at creation time for bundles
1837 if ( image
->isBundle() )
1840 // we detect root images as those not linked in yet
1841 if ( !image
->isLinked() )
1842 addRootImage(image
);
1844 // notify ZeroLink of new image with concat of logical and physical name
1845 if ( sBundleNotifier
!= NULL
&& image
->isBundle() ) {
1846 const int logicalLen
= strlen(image
->getLogicalPath());
1847 char logAndPhys
[strlen(image
->getPath())+logicalLen
+2];
1848 strcpy(logAndPhys
, image
->getLogicalPath());
1849 strcpy(&logAndPhys
[logicalLen
+1], image
->getPath());
1850 (*sBundleNotifier
)(logAndPhys
, image
);
1854 image
->link(gLinkContext
, bindness
, runInitializers
, sAddImageCallbacks
.size());
1856 #if OLD_GDB_DYLD_INTERFACE
1857 // notify gdb that loaded libraries have changed
1858 gdb_dyld_state_changed();
1864 // Entry point for dyld. The kernel loads dyld and jumps to __dyld_start which
1865 // sets up some registers and call this function.
1867 // Returns address of main() in target program which __dyld_start jumps to
1870 _main(const struct mach_header
* mainExecutableMH
, int argc
, const char* argv
[], const char* envp
[], const char* apple
[])
1872 // Pickup the pointer to the exec path.
1873 sExecPath
= apple
[0];
1874 if ( sExecPath
[0] != '/' ) {
1875 // have relative path, use cwd to make absolute
1876 char cwdbuff
[MAXPATHLEN
];
1877 if ( getcwd(cwdbuff
, MAXPATHLEN
) != NULL
) {
1878 // maybe use static buffer to avoid calling malloc so early...
1879 char* s
= new char[strlen(cwdbuff
) + strlen(sExecPath
) + 2];
1882 strcat(s
, sExecPath
);
1886 uintptr_t result
= 0;
1887 sMainExecutableMachHeader
= mainExecutableMH
;
1888 checkEnvironmentVariables(envp
);
1889 if ( sEnv
.DYLD_PRINT_OPTS
)
1891 if ( sEnv
.DYLD_PRINT_ENV
)
1892 printEnvironmentVariables(envp
);
1894 setContext(argc
, argv
, envp
, apple
);
1895 ImageLoader::BindingLaziness bindness
= sEnv
.DYLD_BIND_AT_LAUNCH
? ImageLoader::kLazyAndNonLazy
: ImageLoader::kNonLazyOnly
;
1897 // load any inserted libraries before loading the main executable so that they are first in flat namespace
1898 int insertLibrariesCount
= 0;
1899 if ( sEnv
.DYLD_INSERT_LIBRARIES
!= NULL
) {
1900 for (const char* const* lib
= sEnv
.DYLD_INSERT_LIBRARIES
; *lib
!= NULL
; ++lib
) {
1901 insertLibrariesCount
++;
1904 ImageLoader
* insertedImages
[insertLibrariesCount
];
1905 if ( insertLibrariesCount
> 0 ) {
1906 for (int i
=0; i
< insertLibrariesCount
; ++i
) {
1908 LoadContext context
;
1909 context
.useSearchPaths
= false;
1910 context
.useLdLibraryPath
= false;
1911 context
.dontLoad
= false;
1912 context
.mustBeBundle
= false;
1913 context
.mustBeDylib
= true;
1914 context
.matchByInstallName
= false;
1915 context
.origin
= NULL
; // can't use @loader_path with DYLD_INSERT_LIBRARIES
1916 context
.rpath
= NULL
;
1917 insertedImages
[i
] = load(sEnv
.DYLD_INSERT_LIBRARIES
[i
], context
);
1920 char buf
[strlen(sEnv
.DYLD_INSERT_LIBRARIES
[i
])+50];
1921 sprintf(buf
, "could not load inserted library: %s\n", sEnv
.DYLD_INSERT_LIBRARIES
[i
]);
1922 insertedImages
[i
] = NULL
;
1928 // load and link main executable
1930 sMainExecutable
= instantiateFromLoadedImage(mainExecutableMH
, sExecPath
);
1931 gLinkContext
.mainExecutable
= sMainExecutable
;
1932 if ( sMainExecutable
->forceFlat() ) {
1933 gLinkContext
.bindFlat
= true;
1934 gLinkContext
.prebindUsage
= ImageLoader::kUseNoPrebinding
;
1936 link(sMainExecutable
, bindness
, ImageLoader::kDontRunInitializers
);
1937 result
= (uintptr_t)sMainExecutable
->getMain();
1939 catch(const char* message
) {
1943 fprintf(stderr
, "dyld: launch failed\n");
1946 // Link in any inserted libraries.
1947 // Do this after link main executable so any extra libraries pulled in by inserted libraries are at end of flat namespace
1948 if ( insertLibrariesCount
> 0 ) {
1949 for (int i
=0; i
< insertLibrariesCount
; ++i
) {
1951 if ( insertedImages
[i
] != NULL
)
1952 link(insertedImages
[i
], bindness
, ImageLoader::kDontRunInitializers
);
1954 catch (const char* message
) {
1955 char buf
[strlen(sEnv
.DYLD_INSERT_LIBRARIES
[i
])+50+strlen(message
)];
1956 sprintf(buf
, "could not link inserted library: %s\n%s\n", sEnv
.DYLD_INSERT_LIBRARIES
[i
], message
);