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 bool sAllImagesMightContainUnlinkedImages
; // necessary until will support dylib unloading
120 static std::vector
<ImageLoader
*> sAllImages
;
121 static std::vector
<ImageLoader
*> sImageRoots
;
122 static std::vector
<ImageLoader
*> sImageFilesNeedingTermination
;
123 static std::vector
<ImageLoader
*> sImagesToNotifyAboutOtherImages
;
124 static std::vector
<ImageCallback
> sAddImageCallbacks
;
125 static std::vector
<ImageCallback
> sRemoveImageCallbacks
;
126 static ImageLoader
* sLastImageByAddressCache
;
127 static EnvironmentVariables sEnv
;
128 static const char* sFrameworkFallbackPaths
[] = { "$HOME/Library/Frameworks", "/Library/Frameworks", "/Network/Library/Frameworks", "/System/Library/Frameworks", NULL
};
129 static const char* sLibraryFallbackPaths
[] = { "$HOME/lib", "/usr/local/lib", "/usr/lib", NULL
};
130 static BundleNotificationCallBack sBundleNotifier
= NULL
;
131 static BundleLocatorCallBack sBundleLocation
= NULL
;
132 static UndefinedHandler sUndefinedHandler
= NULL
;
133 ImageLoader::LinkContext gLinkContext
;
134 bool gLogAPIs
= false;
135 const struct ThreadingHelpers
* gThreadHelpers
= NULL
;
139 // utility class to assure files are closed when an exception is thrown
142 FileOpener(const char* path
);
144 int getFileDescriptor() { return fd
; }
149 FileOpener::FileOpener(const char* path
)
151 fd
= open(path
, O_RDONLY
, 0);
154 FileOpener::~FileOpener()
161 // Objective-C installs an addImage hook to dyld to get notified about new images
162 // The callback needs to be run after the image is rebased and bound, but before its initializers are called
163 static uint32_t imageNotification(ImageLoader
* image
, uint32_t startIndex
)
165 // tell all register add image handlers about this
166 const uint32_t callbackCount
= sAddImageCallbacks
.size();
167 for (uint32_t i
=startIndex
; i
< callbackCount
; ++i
) {
168 ImageCallback cb
= sAddImageCallbacks
[i
];
169 //fprintf(stderr, "dyld: calling add-image-callback[%d]=%p for %s\n", i, cb, image->getPath());
170 (cb
)(image
->machHeader(), image
->getSlide());
172 return callbackCount
;
177 // notify gdb et al about these new images
178 static void notifyAdding(std::vector
<ImageLoader
*>& images
)
181 unsigned int len
= images
.size();
183 dyld_image_info infos
[len
];
184 for (unsigned int i
=0; i
< len
; ++i
) {
185 dyld_image_info
* p
= &infos
[i
];
186 ImageLoader
* image
= images
[i
];
187 p
->imageLoadAddress
= image
->machHeader();
188 p
->imageFilePath
= image
->getPath();
189 p
->imageFileModDate
= image
->lastModified();
190 //fprintf(stderr, "notifying objc about %s\n", image->getPath());
194 addImagesToAllImages(len
, infos
);
196 // tell all interested images (after gdb, so you can debug anything the notification does)
197 for (std::vector
<ImageLoader
*>::iterator it
=sImagesToNotifyAboutOtherImages
.begin(); it
!= sImagesToNotifyAboutOtherImages
.end(); it
++) {
198 (*it
)->doNotification(dyld_image_adding
, len
, infos
);
205 // In order for register_func_for_add_image() callbacks to to be called bottom up,
206 // we need to maintain a list of root images. The main executable is usally the
207 // first root. Any images dynamically added are also roots (unless already loaded).
208 // If DYLD_INSERT_LIBRARIES is used, those libraries are first.
209 static void addRootImage(ImageLoader
* image
)
211 //fprintf(stderr, "addRootImage(%p, %s)\n", image, image->getPath());
212 // add to list of roots
213 sImageRoots
.push_back(image
);
216 // Objective-C will contain a __DATA/__image_notify section which contains pointers to a function to call
217 // whenever any new image is loaded.
218 static void addImageNeedingNotification(ImageLoader
* image
)
220 sImagesToNotifyAboutOtherImages
.push_back(image
);
223 static void addImage(ImageLoader
* image
)
225 // add to master list
226 sAllImages
.push_back(image
);
228 if ( sEnv
.DYLD_PRINT_LIBRARIES
|| (sEnv
.DYLD_PRINT_LIBRARIES_POST_LAUNCH
&& (sMainExecutable
!=NULL
) && sMainExecutable
->isLinked()) ) {
229 uint64_t offset
= image
->getOffsetInFatFile();
231 fprintf(stderr
, "dyld: loaded: %s\n", image
->getPath());
233 fprintf(stderr
, "dyld: loaded: %s, cpu-sub-type: %d\n", image
->getPath(), image
->machHeader()->cpusubtype
);
236 #if OLD_GDB_DYLD_INTERFACE
237 // let gdb find out about this
238 addImageForgdb(image
->machHeader(), image
->getSlide(), image
->getPath(), image
->getLogicalPath());
242 void removeImage(ImageLoader
* image
)
244 // if in termination list, pull it out and run terminator
245 for (std::vector
<ImageLoader
*>::iterator it
=sImageFilesNeedingTermination
.begin(); it
!= sImageFilesNeedingTermination
.end(); it
++) {
246 if ( *it
== image
) {
247 sImageFilesNeedingTermination
.erase(it
);
248 image
->doTermination(gLinkContext
);
253 // tell all register add image handlers about this
254 // do this before removing image from internal data structures so that the callback can querey dyld about the image
255 for (std::vector
<ImageCallback
>::iterator it
=sRemoveImageCallbacks
.begin(); it
!= sRemoveImageCallbacks
.end(); it
++) {
256 (*it
)(image
->machHeader(), image
->getSlide());
259 // tell all interested images
260 for (std::vector
<ImageLoader
*>::iterator it
=sImagesToNotifyAboutOtherImages
.begin(); it
!= sImagesToNotifyAboutOtherImages
.end(); it
++) {
261 dyld_image_info info
;
262 info
.imageLoadAddress
= image
->machHeader();
263 info
.imageFilePath
= image
->getPath();
264 info
.imageFileModDate
= image
->lastModified();
265 (*it
)->doNotification(dyld_image_removing
, 1, &info
);
268 // remove from master list
269 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
270 if ( *it
== image
) {
271 sAllImages
.erase(it
);
276 // flush find-by-address cache
277 if ( sLastImageByAddressCache
== image
)
278 sLastImageByAddressCache
= NULL
;
280 // if in announcement list, pull it out
281 for (std::vector
<ImageLoader
*>::iterator it
=sImagesToNotifyAboutOtherImages
.begin(); it
!= sImagesToNotifyAboutOtherImages
.end(); it
++) {
282 if ( *it
== image
) {
283 sImagesToNotifyAboutOtherImages
.erase(it
);
288 // if in root list, pull it out
289 for (std::vector
<ImageLoader
*>::iterator it
=sImageRoots
.begin(); it
!= sImageRoots
.end(); it
++) {
290 if ( *it
== image
) {
291 sImageRoots
.erase(it
);
297 removeImageFromAllImages(image
->machHeader());
299 #if OLD_GDB_DYLD_INTERFACE
301 removeImageForgdb(image
->machHeader());
302 gdb_dyld_state_changed();
307 static void terminationRecorder(ImageLoader
* image
)
309 sImageFilesNeedingTermination
.push_back(image
);
312 const char* getExecutablePath()
318 void initializeMainExecutable()
320 const int rootCount
= sImageRoots
.size();
321 for(int i
=0; i
< rootCount
; ++i
) {
322 ImageLoader
* image
= sImageRoots
[i
];
323 //fprintf(stderr, "initializeMainExecutable: image = %p\n", image);
324 image
->runInitializers(gLinkContext
);
327 // this does not work???
328 for (std::vector<ImageLoader*>::iterator it=sImageRoots.begin(); it != sImageRoots.end(); it++) {
329 ImageLoader* image = *it;
330 fprintf(stderr, "initializeMainExecutable: image = %p\n", image);
331 // don't know why vector sometimes starts with NULL element???
333 image->runInitializers(gLinkContext);
336 if ( sEnv
.DYLD_PRINT_STATISTICS
)
337 ImageLoaderMachO::printStatistics(sAllImages
.size());
340 bool mainExecutablePrebound()
342 return sMainExecutable
->usablePrebinding(gLinkContext
);
345 ImageLoader
* mainExecutable()
347 return sMainExecutable
;
351 void runTerminators()
353 const unsigned int imageCount
= sImageFilesNeedingTermination
.size();
354 for(unsigned int i
=imageCount
; i
> 0; --i
){
355 ImageLoader
* image
= sImageFilesNeedingTermination
[i
-1];
356 image
->doTermination(gLinkContext
);
358 sImageFilesNeedingTermination
.clear();
363 // Turns a colon separated list of strings
364 // into a NULL terminated array of string
367 static const char** parseColonList(const char* list
)
369 if ( list
[0] == '\0' )
373 for(const char* s
=list
; *s
!= '\0'; ++s
) {
379 const char* start
= list
;
380 char** result
= new char*[colonCount
+2];
381 for(const char* s
=list
; *s
!= '\0'; ++s
) {
384 char* str
= new char[len
+1];
385 strncpy(str
, start
, len
);
388 result
[index
++] = str
;
391 int len
= strlen(start
);
392 char* str
= new char[len
+1];
394 result
[index
++] = str
;
395 result
[index
] = NULL
;
397 return (const char**)result
;
401 * Library path searching is not done for setuid programs
402 * which are not run by the real user. Futher the
403 * evironment varaible for the library path is cleared so
404 * that if this program executes a non-set uid program this
405 * part of the evironment will not be passed along so that
406 * that program also will not have it's libraries searched
409 static bool riskyUser()
411 static bool checked
= false;
412 static bool risky
= false;
414 risky
= ( getuid() != 0 && (getuid() != geteuid() || getgid() != getegid()) );
421 static bool disableIfBadUser(char* rhs
)
423 bool didDisable
= false;
431 static void paths_expand_roots(const char **paths
, const char *key
, const char *val
)
433 // assert(val != NULL);
434 // assert(paths != NULL);
436 size_t keyLen
= strlen(key
);
437 for(int i
=0; paths
[i
] != NULL
; ++i
) {
438 if ( strncmp(paths
[i
], key
, keyLen
) == 0 ) {
439 char* newPath
= new char[strlen(val
) + (strlen(paths
[i
]) - keyLen
) + 1];
440 strcpy(newPath
, val
);
441 strcat(newPath
, &paths
[i
][keyLen
]);
449 static void removePathWithPrefix(const char* paths
[], const char* prefix
)
451 size_t prefixLen
= strlen(prefix
);
452 for(int s
=0,d
=0; (paths
[d
] != NULL
) && (paths
[s
] != NULL
); ++s
, ++d
) {
453 if ( strncmp(paths
[s
], prefix
, prefixLen
) == 0 )
460 static void paths_dump(const char **paths
)
462 // assert(paths != NULL);
463 const char **strs
= paths
;
466 fprintf(stderr
, "\"%s\"\n", *strs
);
473 static void printOptions(const char* argv
[])
476 while ( NULL
!= argv
[i
] ) {
477 fprintf(stderr
, "opt[%i] = \"%s\"\n", i
, argv
[i
]);
482 static void printEnvironmentVariables(const char* envp
[])
484 while ( NULL
!= *envp
) {
485 fprintf(stderr
, "%s\n", *envp
);
492 void processDyldEnvironmentVarible(const char* key
, const char* value
)
494 if ( strcmp(key
, "DYLD_FRAMEWORK_PATH") == 0 ) {
495 if ( !disableIfBadUser((char*)value
) )
496 sEnv
.DYLD_FRAMEWORK_PATH
= parseColonList(value
);
498 else if ( strcmp(key
, "DYLD_FALLBACK_FRAMEWORK_PATH") == 0 ) {
499 if ( !disableIfBadUser((char*)value
) )
500 sEnv
.DYLD_FALLBACK_FRAMEWORK_PATH
= parseColonList(value
);
502 else if ( strcmp(key
, "DYLD_LIBRARY_PATH") == 0 ) {
503 if ( !disableIfBadUser((char*)value
) )
504 sEnv
.DYLD_LIBRARY_PATH
= parseColonList(value
);
506 else if ( strcmp(key
, "DYLD_FALLBACK_LIBRARY_PATH") == 0 ) {
507 if ( !disableIfBadUser((char*)value
) )
508 sEnv
.DYLD_FALLBACK_LIBRARY_PATH
= parseColonList(value
);
510 else if ( (strcmp(key
, "DYLD_ROOT_PATH") == 0) || (strcmp(key
, "DYLD_PATHS_ROOT") == 0) ) {
511 if ( !disableIfBadUser((char*)value
) ) {
512 if ( strcmp(value
, "/") != 0 ) {
513 sEnv
.DYLD_ROOT_PATH
= parseColonList(value
);
514 for (int i
=0; sEnv
.DYLD_ROOT_PATH
[i
] != NULL
; ++i
) {
515 if ( sEnv
.DYLD_ROOT_PATH
[i
][0] != '/' ) {
516 fprintf(stderr
, "dyld: warning DYLD_ROOT_PATH not used because it contains a non-absolute path\n");
517 sEnv
.DYLD_ROOT_PATH
= NULL
;
524 else if ( strcmp(key
, "DYLD_IMAGE_SUFFIX") == 0 ) {
525 if ( !disableIfBadUser((char*)value
) )
526 gLinkContext
.imageSuffix
= value
;
528 else if ( strcmp(key
, "DYLD_INSERT_LIBRARIES") == 0 ) {
529 if ( !disableIfBadUser((char*)value
) )
530 sEnv
.DYLD_INSERT_LIBRARIES
= parseColonList(value
);
532 else if ( strcmp(key
, "DYLD_DEBUG_TRACE") == 0 ) {
533 fprintf(stderr
, "dyld: warning DYLD_DEBUG_TRACE not supported\n");
535 else if ( strcmp(key
, "DYLD_ERROR_PRINT") == 0 ) {
536 fprintf(stderr
, "dyld: warning DYLD_ERROR_PRINT not supported\n");
538 else if ( strcmp(key
, "DYLD_PRINT_OPTS") == 0 ) {
539 sEnv
.DYLD_PRINT_OPTS
= true;
541 else if ( strcmp(key
, "DYLD_PRINT_ENV") == 0 ) {
542 sEnv
.DYLD_PRINT_ENV
= true;
544 else if ( strcmp(key
, "DYLD_PRINT_LIBRARIES") == 0 ) {
545 sEnv
.DYLD_PRINT_LIBRARIES
= true;
547 else if ( strcmp(key
, "DYLD_PRINT_LIBRARIES_POST_LAUNCH") == 0 ) {
548 sEnv
.DYLD_PRINT_LIBRARIES_POST_LAUNCH
= true;
550 else if ( strcmp(key
, "DYLD_TRACE") == 0 ) {
551 fprintf(stderr
, "dyld: warning DYLD_TRACE not supported\n");
553 else if ( strcmp(key
, "DYLD_EBADEXEC_ONLY") == 0 ) {
554 fprintf(stderr
, "dyld: warning DYLD_EBADEXEC_ONLY not supported\n");
556 else if ( strcmp(key
, "DYLD_BIND_AT_LAUNCH") == 0 ) {
557 sEnv
.DYLD_BIND_AT_LAUNCH
= true;
559 else if ( strcmp(key
, "DYLD_FORCE_FLAT_NAMESPACE") == 0 ) {
560 gLinkContext
.bindFlat
= true;
562 else if ( strcmp(key
, "DYLD_DEAD_LOCK_HANG") == 0 ) {
563 fprintf(stderr
, "dyld: warning DYLD_DEAD_LOCK_HANG not supported\n");
565 else if ( strcmp(key
, "DYLD_ABORT_MULTIPLE_INITS") == 0 ) {
566 fprintf(stderr
, "dyld: warning DYLD_ABORT_MULTIPLE_INITS not supported\n");
568 else if ( strcmp(key
, "DYLD_NEW_LOCAL_SHARED_REGIONS") == 0 ) {
569 gLinkContext
.sharedRegionMode
= ImageLoader::kUsePrivateSharedRegion
;
571 else if ( strcmp(key
, "DYLD_SLIDE_AND_PACK_DYLIBS") == 0 ) {
572 gLinkContext
.slideAndPackDylibs
= true;
574 else if ( strcmp(key
, "DYLD_NO_FIX_PREBINDING") == 0 ) {
575 // since the new dyld never runs fix_prebinding, no need to warn if someone does not want it run
576 //fprintf(stderr, "dyld: warning DYLD_NO_FIX_PREBINDING not supported\n");
578 else if ( strcmp(key
, "DYLD_PREBIND_DEBUG") == 0 ) {
579 gLinkContext
.verbosePrebinding
= true;
581 else if ( strcmp(key
, "DYLD_HINTS_DEBUG") == 0 ) {
582 fprintf(stderr
, "dyld: warning DYLD_HINTS_DEBUG not supported\n");
584 else if ( strcmp(key
, "DYLD_SAMPLE_DEBUG") == 0 ) {
585 fprintf(stderr
, "dyld: warning DYLD_SAMPLE_DEBUG not supported\n");
587 else if ( strcmp(key
, "DYLD_EXECUTABLE_PATH_DEBUG") == 0 ) {
588 fprintf(stderr
, "dyld: warning DYLD_EXECUTABLE_PATH_DEBUG not supported\n");
590 else if ( strcmp(key
, "DYLD_TWO_LEVEL_DEBUG") == 0 ) {
591 fprintf(stderr
, "dyld: warning DYLD_TWO_LEVEL_DEBUG not supported\n");
593 else if ( strcmp(key
, "DYLD_LAZY_INITIALIZERS") == 0 ) {
594 fprintf(stderr
, "dyld: warning DYLD_LAZY_INITIALIZERS not supported\n");
596 else if ( strcmp(key
, "DYLD_PRINT_INITIALIZERS") == 0 ) {
597 gLinkContext
.verboseInit
= true;
599 else if ( strcmp(key
, "DYLD_PRINT_STATISTICS") == 0 ) {
600 sEnv
.DYLD_PRINT_STATISTICS
= true;
602 else if ( strcmp(key
, "DYLD_PRINT_SEGMENTS") == 0 ) {
603 gLinkContext
.verboseMapping
= true;
605 else if ( strcmp(key
, "DYLD_PRINT_BINDINGS") == 0 ) {
606 gLinkContext
.verboseBind
= true;
608 else if ( strcmp(key
, "DYLD_PRINT_REBASINGS") == 0 ) {
609 gLinkContext
.verboseRebase
= true;
611 else if ( strcmp(key
, "DYLD_PRINT_APIS") == 0 ) {
614 else if ( strcmp(key
, "DYLD_PRINT_WARNINGS") == 0 ) {
615 gLinkContext
.verboseWarnings
= true;
617 else if ( strcmp(key
, "DYLD_SHARED_REGION") == 0 ) {
618 if ( strcmp(value
, "private") == 0 ) {
619 gLinkContext
.sharedRegionMode
= ImageLoader::kUsePrivateSharedRegion
;
621 else if ( strcmp(value
, "avoid") == 0 ) {
622 gLinkContext
.sharedRegionMode
= ImageLoader::kDontUseSharedRegion
;
624 else if ( strcmp(value
, "use") == 0 ) {
625 gLinkContext
.sharedRegionMode
= ImageLoader::kUseSharedRegion
;
627 else if ( value
[0] == '\0' ) {
628 gLinkContext
.sharedRegionMode
= ImageLoader::kUseSharedRegion
;
631 fprintf(stderr
, "dyld: warning unknown option to DYLD_SHARED_REGION. Valid options are: use, private, avoid\n");
634 else if ( strcmp(key
, "DYLD_IGNORE_PREBINDING") == 0 ) {
635 if ( strcmp(value
, "all") == 0 ) {
636 gLinkContext
.prebindUsage
= ImageLoader::kUseNoPrebinding
;
638 else if ( strcmp(value
, "app") == 0 ) {
639 gLinkContext
.prebindUsage
= ImageLoader::kUseAllButAppPredbinding
;
641 else if ( strcmp(value
, "nonsplit") == 0 ) {
642 gLinkContext
.prebindUsage
= ImageLoader::kUseSplitSegPrebinding
;
644 else if ( value
[0] == '\0' ) {
645 gLinkContext
.prebindUsage
= ImageLoader::kUseSplitSegPrebinding
;
648 fprintf(stderr
, "dyld: warning unknown option to DYLD_IGNORE_PREBINDING. Valid options are: all, app, nonsplit\n");
652 fprintf(stderr
, "dyld: warning, unknown environment variable: %s\n", key
);
656 static void checkEnvironmentVariables(const char* envp
[], bool ignoreEnviron
)
658 const char* home
= NULL
;
660 for(p
= envp
; *p
!= NULL
; p
++) {
661 const char* keyEqualsValue
= *p
;
662 if ( strncmp(keyEqualsValue
, "DYLD_", 5) == 0 ) {
663 const char* equals
= strchr(keyEqualsValue
, '=');
664 if ( (equals
!= NULL
) && !ignoreEnviron
) {
665 const char* value
= &equals
[1];
666 const int keyLen
= equals
-keyEqualsValue
;
668 strncpy(key
, keyEqualsValue
, keyLen
);
670 processDyldEnvironmentVarible(key
, value
);
673 else if ( strncmp(keyEqualsValue
, "HOME=", 5) == 0 ) {
674 home
= &keyEqualsValue
[5];
676 else if ( strncmp(keyEqualsValue
, "LD_LIBRARY_PATH=", 16) == 0 ) {
677 const char* path
= &keyEqualsValue
[16];
678 if ( !disableIfBadUser((char*)path
) )
679 sEnv
.LD_LIBRARY_PATH
= parseColonList(path
);
683 // default value for DYLD_FALLBACK_FRAMEWORK_PATH, if not set in environment
684 if ( sEnv
.DYLD_FALLBACK_FRAMEWORK_PATH
== NULL
) {
685 const char** paths
= sFrameworkFallbackPaths
;
686 if ( home
!= NULL
) {
688 removePathWithPrefix(paths
, "$HOME");
690 paths_expand_roots(paths
, "$HOME", home
);
692 sEnv
.DYLD_FALLBACK_FRAMEWORK_PATH
= paths
;
695 // default value for DYLD_FALLBACK_LIBRARY_PATH, if not set in environment
696 if ( sEnv
.DYLD_FALLBACK_LIBRARY_PATH
== NULL
) {
697 const char** paths
= sLibraryFallbackPaths
;
698 if ( home
!= NULL
) {
700 removePathWithPrefix(paths
, "$HOME");
702 paths_expand_roots(paths
, "$HOME", home
);
704 sEnv
.DYLD_FALLBACK_LIBRARY_PATH
= paths
;
709 static void getHostInfo()
712 struct host_basic_info info
;
713 mach_msg_type_number_t count
= HOST_BASIC_INFO_COUNT
;
714 mach_port_t hostPort
= mach_host_self();
715 kern_return_t result
= host_info(hostPort
, HOST_BASIC_INFO
, (host_info_t
)&info
, &count
);
716 mach_port_deallocate(mach_task_self(), hostPort
);
717 if ( result
!= KERN_SUCCESS
)
718 throw "host_info() failed";
720 sHostCPU
= info
.cpu_type
;
721 sHostCPUsubtype
= info
.cpu_subtype
;
724 size_t valSize
= sizeof(sHostCPU
);
725 if (sysctlbyname ("hw.cputype", &sHostCPU
, &valSize
, NULL
, 0) != 0)
726 throw "sysctlbyname(hw.cputype) failed";
727 valSize
= sizeof(sHostCPUsubtype
);
728 if (sysctlbyname ("hw.cpusubtype", &sHostCPUsubtype
, &valSize
, NULL
, 0) != 0)
729 throw "sysctlbyname(hw.cpusubtype) failed";
732 bool validImage(ImageLoader
* possibleImage
)
734 const unsigned int imageCount
= sAllImages
.size();
735 for(unsigned int i
=0; i
< imageCount
; ++i
) {
736 if ( possibleImage
== sAllImages
[i
] ) {
743 uint32_t getImageCount()
745 if ( sAllImagesMightContainUnlinkedImages
) {
747 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
748 if ( (*it
)->isLinked() )
754 return sAllImages
.size();
758 ImageLoader
* getIndexedImage(unsigned int index
)
760 if ( sAllImagesMightContainUnlinkedImages
) {
762 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
763 if ( (*it
)->isLinked() ) {
764 if ( index
== count
)
771 if ( index
< sAllImages
.size() )
772 return sAllImages
[index
];
777 ImageLoader
* findImageByMachHeader(const struct mach_header
* target
)
779 const unsigned int imageCount
= sAllImages
.size();
780 for(unsigned int i
=0; i
< imageCount
; ++i
) {
781 ImageLoader
* anImage
= sAllImages
[i
];
782 if ( anImage
->machHeader() == target
)
789 ImageLoader
* findImageContainingAddress(const void* addr
)
792 static int cacheHit
= 0;
793 static int cacheMiss
= 0;
794 static int cacheNotMacho
= 0;
795 if ( ((cacheHit
+cacheMiss
+cacheNotMacho
) % 100) == 0 )
796 fprintf(stderr
, "findImageContainingAddress(): cache hit = %d, miss = %d, unknown = %d\n", cacheHit
, cacheMiss
, cacheNotMacho
);
798 // first look in image where last address was found rdar://problem/3685517
799 if ( (sLastImageByAddressCache
!= NULL
) && sLastImageByAddressCache
->containsAddress(addr
) ) {
803 return sLastImageByAddressCache
;
805 // do exhastive search
806 // todo: consider maintaining a list sorted by address ranges and do a binary search on that
807 const unsigned int imageCount
= sAllImages
.size();
808 for(unsigned int i
=0; i
< imageCount
; ++i
) {
809 ImageLoader
* anImage
= sAllImages
[i
];
810 if ( anImage
->containsAddress(addr
) ) {
811 sLastImageByAddressCache
= anImage
;
824 ImageLoader
* findImageContainingAddressThreadSafe(const void* addr
)
826 // do exhastive search
827 // todo: consider maintaining a list sorted by address ranges and do a binary search on that
828 const unsigned int imageCount
= sAllImages
.size();
829 for(unsigned int i
=0; i
< imageCount
; ++i
) {
830 ImageLoader
* anImage
= sAllImages
[i
];
831 if ( anImage
->containsAddress(addr
) ) {
839 void forEachImageDo( void (*callback
)(ImageLoader
*, void* userData
), void* userData
)
841 const unsigned int imageCount
= sAllImages
.size();
842 for(unsigned int i
=0; i
< imageCount
; ++i
) {
843 ImageLoader
* anImage
= sAllImages
[i
];
844 (*callback
)(anImage
, userData
);
848 ImageLoader
* findLoadedImage(const struct stat
& stat_buf
)
850 const unsigned int imageCount
= sAllImages
.size();
851 for(unsigned int i
=0; i
< imageCount
; ++i
){
852 ImageLoader
* anImage
= sAllImages
[i
];
853 if ( anImage
->statMatch(stat_buf
) )
859 // based on ANSI-C strstr()
860 static const char* strrstr(const char* str
, const char* sub
)
862 const int sublen
= strlen(sub
);
863 for(const char* p
= &str
[strlen(str
)]; p
!= str
; --p
) {
864 if ( strncmp(p
, sub
, sublen
) == 0 )
872 // Find framework path
874 // /path/foo.framework/foo => foo.framework/foo
875 // /path/foo.framework/Versions/A/foo => foo.framework/Versions/A/foo
876 // /path/foo.framework/Frameworks/bar.framework/bar => bar.framework/bar
877 // /path/foo.framework/Libraries/bar.dylb => NULL
878 // /path/foo.framework/bar => NULL
880 // Returns NULL if not a framework path
882 static const char* getFrameworkPartialPath(const char* path
)
884 const char* dirDot
= strrstr(path
, ".framework/");
885 if ( dirDot
!= NULL
) {
886 const char* dirStart
= dirDot
;
887 for ( ; dirStart
>= path
; --dirStart
) {
888 if ( (*dirStart
== '/') || (dirStart
== path
) ) {
889 const char* frameworkStart
= &dirStart
[1];
890 if ( dirStart
== path
)
892 int len
= dirDot
- frameworkStart
;
893 char framework
[len
+1];
894 strncpy(framework
, frameworkStart
, len
);
895 framework
[len
] = '\0';
896 const char* leaf
= strrchr(path
, '/');
897 if ( leaf
!= NULL
) {
898 if ( strcmp(framework
, &leaf
[1]) == 0 ) {
899 return frameworkStart
;
901 if ( gLinkContext
.imageSuffix
!= NULL
) {
902 // some debug frameworks have install names that end in _debug
903 if ( strncmp(framework
, &leaf
[1], len
) == 0 ) {
904 if ( strcmp( gLinkContext
.imageSuffix
, &leaf
[len
+1]) == 0 )
905 return frameworkStart
;
916 static const char* getLibraryLeafName(const char* path
)
918 const char* start
= strrchr(path
, '/');
927 const cpu_subtype_t CPU_SUBTYPE_END_OF_LIST
= -1;
931 // A fat file may contain multiple sub-images for the same CPU type.
932 // In that case, dyld picks which sub-image to use by scanning a table
933 // of preferred cpu-sub-types for the running cpu.
935 // There is one row in the table for each cpu-sub-type on which dyld might run.
936 // The first entry in a row is that cpu-sub-type. It is followed by all
937 // cpu-sub-types that can run on that cpu, if preferred order. Each row ends with
938 // a "SUBTYPE_ALL" (to denote that images written to run on any cpu-sub-type are usable),
939 // followed by one or more CPU_SUBTYPE_END_OF_LIST to pad out this row.
944 // 32-bit PowerPC sub-type lists
946 const int kPPC_RowCount
= 4;
947 static const cpu_subtype_t kPPC32
[kPPC_RowCount
][6] = {
948 // G5 can run any code
949 { 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
},
951 // G4 can run all but G5 code
952 { 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
},
953 { 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
},
955 // G3 cannot run G4 or G5 code
956 { 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
}
961 // 64-bit PowerPC sub-type lists
963 const int kPPC64_RowCount
= 1;
964 static const cpu_subtype_t kPPC64
[kPPC64_RowCount
][3] = {
965 // G5 can run any 64-bit code
966 { CPU_SUBTYPE_POWERPC_970
, CPU_SUBTYPE_POWERPC_ALL
, CPU_SUBTYPE_END_OF_LIST
},
972 // 32-bit x86 sub-type lists
978 // scan the tables above to find the cpu-sub-type-list for this machine
979 static const cpu_subtype_t
* findCPUSubtypeList(cpu_type_t cpu
, cpu_subtype_t subtype
)
982 case CPU_TYPE_POWERPC
:
983 for (int i
=0; i
< kPPC_RowCount
; ++i
) {
984 if ( kPPC32
[i
][0] == subtype
)
988 case CPU_TYPE_POWERPC64
:
989 for (int i
=0; i
< kPPC64_RowCount
; ++i
) {
990 if ( kPPC64
[i
][0] == subtype
)
1004 // scan fat table-of-contents for best most preferred subtype
1005 static bool fatFindBestFromOrderedList(cpu_type_t cpu
, const cpu_subtype_t list
[], const fat_header
* fh
, uint64_t* offset
, uint64_t* len
)
1007 const fat_arch
* const archs
= (fat_arch
*)(((char*)fh
)+sizeof(fat_header
));
1008 for (uint32_t subTypeIndex
=0; list
[subTypeIndex
] != CPU_SUBTYPE_END_OF_LIST
; ++subTypeIndex
) {
1009 for(uint32_t fatIndex
=0; fatIndex
< OSSwapBigToHostInt32(fh
->nfat_arch
); ++fatIndex
) {
1010 if ( ((cpu_type_t
)OSSwapBigToHostInt32(archs
[fatIndex
].cputype
) == cpu
)
1011 && (list
[subTypeIndex
] == archs
[fatIndex
].cpusubtype
) ) {
1012 *offset
= OSSwapBigToHostInt32(archs
[fatIndex
].offset
);
1013 *len
= OSSwapBigToHostInt32(archs
[fatIndex
].size
);
1021 // scan fat table-of-contents for exact match of cpu and cpu-sub-type
1022 static bool fatFindExactMatch(cpu_type_t cpu
, cpu_subtype_t subtype
, const fat_header
* fh
, uint64_t* offset
, uint64_t* len
)
1024 const fat_arch
* archs
= (fat_arch
*)(((char*)fh
)+sizeof(fat_header
));
1025 for(uint32_t i
=0; i
< OSSwapBigToHostInt32(fh
->nfat_arch
); ++i
) {
1026 if ( ((cpu_type_t
)OSSwapBigToHostInt32(archs
[i
].cputype
) == cpu
)
1027 && ((cpu_subtype_t
)OSSwapBigToHostInt32(archs
[i
].cpusubtype
) == subtype
) ) {
1028 *offset
= OSSwapBigToHostInt32(archs
[i
].offset
);
1029 *len
= OSSwapBigToHostInt32(archs
[i
].size
);
1036 // scan fat table-of-contents for image with matching cpu-type and runs-on-all-sub-types
1037 static bool fatFindRunsOnAllCPUs(cpu_type_t cpu
, const fat_header
* fh
, uint64_t* offset
, uint64_t* len
)
1039 const fat_arch
* archs
= (fat_arch
*)(((char*)fh
)+sizeof(fat_header
));
1040 for(uint32_t i
=0; i
< OSSwapBigToHostInt32(fh
->nfat_arch
); ++i
) {
1041 if ( (cpu_type_t
)OSSwapBigToHostInt32(archs
[i
].cputype
) == cpu
) {
1043 case CPU_TYPE_POWERPC
:
1044 case CPU_TYPE_POWERPC64
:
1045 if ( (cpu_subtype_t
)OSSwapBigToHostInt32(archs
[i
].cpusubtype
) == CPU_SUBTYPE_POWERPC_ALL
) {
1046 *offset
= OSSwapBigToHostInt32(archs
[i
].offset
);
1047 *len
= OSSwapBigToHostInt32(archs
[i
].size
);
1052 if ( (cpu_subtype_t
)OSSwapBigToHostInt32(archs
[i
].cpusubtype
) == CPU_SUBTYPE_I386_ALL
) {
1053 *offset
= OSSwapBigToHostInt32(archs
[i
].offset
);
1054 *len
= OSSwapBigToHostInt32(archs
[i
].size
);
1066 // A fat file may contain multiple sub-images for the same cpu-type,
1067 // each optimized for a different cpu-sub-type (e.g G3 or G5).
1068 // This routine picks the optimal sub-image.
1070 static bool fatFindBest(const fat_header
* fh
, uint64_t* offset
, uint64_t* len
)
1072 // assume all dylibs loaded must have same cpu type as main executable
1073 const cpu_type_t cpu
= sMainExecutableMachHeader
->cputype
;
1075 // We only know the subtype to use if the main executable cpu type matches the host
1076 if ( (cpu
& CPU_TYPE_MASK
) == sHostCPU
) {
1077 // get preference ordered list of subtypes
1078 const cpu_subtype_t
* subTypePreferenceList
= findCPUSubtypeList(cpu
, sHostCPUsubtype
);
1080 // use ordered list to find best sub-image in fat file
1081 if ( subTypePreferenceList
!= NULL
)
1082 return fatFindBestFromOrderedList(cpu
, subTypePreferenceList
, fh
, offset
, len
);
1084 // if running cpu is not in list, try for an exact match
1085 if ( fatFindExactMatch(cpu
, sHostCPUsubtype
, fh
, offset
, len
) )
1089 // running on an uknown cpu, can only load generic code
1090 return fatFindRunsOnAllCPUs(cpu
, fh
, offset
, len
);
1096 // This is used to validate if a non-fat (aka thin or raw) mach-o file can be used
1097 // on the current processor. It is deemed compatible if any of the following are true:
1098 // 1) mach_header subtype is in list of compatible subtypes for running processor
1099 // 2) mach_header subtype is same as running processor subtype
1100 // 3) mach_header subtype runs on all processor variants
1103 bool isCompatibleMachO(const uint8_t* firstPage
)
1105 const mach_header
* mh
= (mach_header
*)firstPage
;
1106 if ( mh
->magic
== sMainExecutableMachHeader
->magic
) {
1107 if ( mh
->cputype
== sMainExecutableMachHeader
->cputype
) {
1108 if ( (mh
->cputype
& CPU_TYPE_MASK
) == sHostCPU
) {
1109 // get preference ordered list of subtypes that this machine can use
1110 const cpu_subtype_t
* subTypePreferenceList
= findCPUSubtypeList(mh
->cputype
, sHostCPUsubtype
);
1111 if ( subTypePreferenceList
!= NULL
) {
1112 // if image's subtype is in the list, it is compatible
1113 for (const cpu_subtype_t
* p
= subTypePreferenceList
; *p
!= CPU_SUBTYPE_END_OF_LIST
; ++p
) {
1114 if ( *p
== mh
->cpusubtype
)
1117 // have list and not in list, so not compatible
1118 throw "incompatible cpu-subtype";
1120 // unknown cpu sub-type, but if exact match for current subtype then ok to use
1121 if ( mh
->cpusubtype
== sHostCPUsubtype
)
1125 // cpu unknown, so don't know if subtype is compatible
1126 // only load _ALL variant
1127 switch (mh
->cputype
) {
1128 case CPU_TYPE_POWERPC
:
1129 case CPU_TYPE_POWERPC64
:
1130 if ( mh
->cpusubtype
== CPU_SUBTYPE_POWERPC_ALL
)
1134 if ( mh
->cpusubtype
== CPU_SUBTYPE_I386_ALL
)
1144 // The kernel maps in main executable before dyld gets control. We need to
1145 // make an ImageLoader* for the already mapped in main executable.
1146 static ImageLoader
* instantiateFromLoadedImage(const struct mach_header
* mh
, const char* path
)
1148 // try mach-o loader
1149 if ( isCompatibleMachO((const uint8_t*)mh
) ) {
1150 ImageLoader
* image
= new ImageLoaderMachO(path
, mh
, 0, gLinkContext
);
1161 // map in file and instantiate an ImageLoader
1162 static ImageLoader
* loadPhase6(int fd
, struct stat
& stat_buf
, const char* path
, const LoadContext
& context
)
1164 //fprintf(stderr, "%s(%s)\n", __func__ , path);
1165 uint64_t fileOffset
= 0;
1166 uint64_t fileLength
= stat_buf
.st_size
;
1168 if ( *((uint32_t*)((char*)(&stat_buf
)+0x60)) == 0xFEFEFEFE )
1169 fileLength
= *((uint64_t*)((char*)(&stat_buf
)+0x30)); // HACK work around for kernel stat bug rdar://problem/3845883
1172 // validate it is a file (not directory)
1173 if ( (stat_buf
.st_mode
& S_IFMT
) != S_IFREG
)
1177 if ( fileLength
< 4096 ) {
1178 throw "file to short";
1181 uint8_t firstPage
[4096];
1182 pread(fd
, firstPage
, 4096,0);
1184 // if fat wrapper, find usable sub-file
1185 const fat_header
* fileStartAsFat
= (fat_header
*)firstPage
;
1186 if ( fileStartAsFat
->magic
== OSSwapBigToHostInt32(FAT_MAGIC
) ) {
1187 if ( fatFindBest(fileStartAsFat
, &fileOffset
, &fileLength
) ) {
1188 pread(fd
, firstPage
, 4096, fileOffset
);
1191 throw "no matching architecture in universal wrapper";
1195 // try mach-o loader
1196 if ( isCompatibleMachO(firstPage
) ) {
1197 char realFilePath
[PATH_MAX
];
1198 if ( gLinkContext
.slideAndPackDylibs
) {
1199 // when prebinding, we always want to track the real path of images
1200 if ( realpath(path
, realFilePath
) != NULL
)
1201 path
= realFilePath
;
1204 // instantiate an image
1205 ImageLoader
* image
= new ImageLoaderMachO(path
, fd
, firstPage
, fileOffset
, fileLength
, stat_buf
, gLinkContext
);
1207 // now sanity check that this loaded image does not have the same install path as any existing image
1208 const char* loadedImageInstallPath
= image
->getInstallPath();
1209 if ( image
->isDylib() && (loadedImageInstallPath
!= NULL
) && (loadedImageInstallPath
[0] == '/') ) {
1210 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
1211 ImageLoader
* anImage
= *it
;
1212 const char* installPath
= anImage
->getInstallPath();
1213 if ( installPath
!= NULL
) {
1214 if ( strcmp(loadedImageInstallPath
, installPath
) == 0 ) {
1215 //fprintf(stderr, "duplicate(%s) => %p\n", installPath, anImage);
1223 // some API's restrict what they can load
1224 if ( context
.mustBeBundle
&& !image
->isBundle() )
1225 throw "not a bundle";
1226 if ( context
.mustBeDylib
&& !image
->isDylib() )
1227 throw "not a dylib";
1229 // don't add bundles to global list, they can be loaded but not linked. When linked it will be added to list
1230 if ( ! image
->isBundle() )
1236 // try other file formats...
1239 // throw error about what was found
1240 switch (*(uint32_t*)firstPage
) {
1245 throw "mach-o, but wrong architecture";
1247 throwf("unknown file type, first eight bytes: 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X",
1248 firstPage
[0], firstPage
[1], firstPage
[2], firstPage
[3], firstPage
[4], firstPage
[5], firstPage
[6],firstPage
[7]);
1254 static ImageLoader
* loadPhase5open(const char* path
, const LoadContext
& context
, std::vector
<const char*>* exceptions
)
1256 //fprintf(stdout, "%s(%s)\n", __func__, path);
1257 ImageLoader
* image
= NULL
;
1259 // open file (automagically closed when this function exits)
1260 FileOpener
file(path
);
1262 //fprintf(stderr, "open(%s) => %d\n", path, file.getFileDescriptor() );
1264 if ( file
.getFileDescriptor() == -1 )
1267 struct stat stat_buf
;
1269 memset(&stat_buf
, 254, sizeof(struct stat
)); // hack until rdar://problem/3845883 is fixed
1271 if ( fstat(file
.getFileDescriptor(), &stat_buf
) == -1)
1274 // in case image was renamed or found via symlinks, check for inode match
1275 image
= findLoadedImage(stat_buf
);
1276 if ( image
!= NULL
)
1279 // needed to implement NSADDIMAGE_OPTION_RETURN_ONLY_IF_LOADED
1280 if ( context
.dontLoad
)
1284 return loadPhase6(file
.getFileDescriptor(), stat_buf
, path
, context
);
1286 catch (const char* msg
) {
1287 char* newMsg
= new char[strlen(msg
) + strlen(path
) + 8];
1288 sprintf(newMsg
, "%s: %s", path
, msg
);
1289 exceptions
->push_back(newMsg
);
1294 // look for path match with existing loaded images
1295 static ImageLoader
* loadPhase5check(const char* path
, const LoadContext
& context
)
1297 //fprintf(stderr, "%s(%s)\n", __func__ , path);
1298 // search path against load-path and install-path of all already loaded images
1299 uint32_t hash
= ImageLoader::hash(path
);
1300 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
1301 ImageLoader
* anImage
= *it
;
1302 // check has first to cut down on strcmp calls
1303 if ( anImage
->getPathHash() == hash
)
1304 if ( strcmp(path
, anImage
->getPath()) == 0 ) {
1305 // if we are looking for a dylib don't return something else
1306 if ( !context
.mustBeDylib
|| anImage
->isDylib() )
1309 if ( context
.matchByInstallName
|| anImage
->matchInstallPath() ) {
1310 const char* installPath
= anImage
->getInstallPath();
1311 if ( installPath
!= NULL
) {
1312 if ( strcmp(path
, installPath
) == 0 ) {
1313 // if we are looking for a dylib don't return something else
1314 if ( !context
.mustBeDylib
|| anImage
->isDylib() )
1321 //fprintf(stderr, "check(%s) => NULL\n", path);
1326 // open or check existing
1327 static ImageLoader
* loadPhase5(const char* path
, const LoadContext
& context
, std::vector
<const char*>* exceptions
)
1329 //fprintf(stderr, "%s(%s)\n", __func__ , path);
1330 if ( exceptions
!= NULL
)
1331 return loadPhase5open(path
, context
, exceptions
);
1333 return loadPhase5check(path
, context
);
1336 // try with and without image suffix
1337 static ImageLoader
* loadPhase4(const char* path
, const LoadContext
& context
, std::vector
<const char*>* exceptions
)
1339 //fprintf(stderr, "%s(%s)\n", __func__ , path);
1340 ImageLoader
* image
= NULL
;
1341 if ( gLinkContext
.imageSuffix
!= NULL
) {
1342 char pathWithSuffix
[strlen(path
)+strlen( gLinkContext
.imageSuffix
)+2];
1343 ImageLoader::addSuffix(path
, gLinkContext
.imageSuffix
, pathWithSuffix
);
1344 image
= loadPhase5(pathWithSuffix
, context
, exceptions
);
1346 if ( image
== NULL
)
1347 image
= loadPhase5(path
, context
, exceptions
);
1352 // expand @ variables
1353 static ImageLoader
* loadPhase3(const char* path
, const LoadContext
& context
, std::vector
<const char*>* exceptions
)
1355 //fprintf(stderr, "%s(%s)\n", __func__ , path);
1356 ImageLoader
* image
= NULL
;
1357 if ( strncmp(path
, "@executable_path/", 17) == 0 ) {
1358 // handle @executable_path path prefix
1359 const char* executablePath
= sExecPath
;
1360 char newPath
[strlen(executablePath
) + strlen(path
)];
1361 strcpy(newPath
, executablePath
);
1362 char* addPoint
= strrchr(newPath
,'/');
1363 if ( addPoint
!= NULL
)
1364 strcpy(&addPoint
[1], &path
[17]);
1366 strcpy(newPath
, &path
[17]);
1367 image
= loadPhase4(newPath
, context
, exceptions
);
1368 if ( image
!= NULL
)
1371 // perhaps main executable path is a sym link, find realpath and retry
1372 char resolvedPath
[PATH_MAX
];
1373 if ( realpath(sExecPath
, resolvedPath
) != NULL
) {
1374 char newRealPath
[strlen(resolvedPath
) + strlen(path
)];
1375 strcpy(newRealPath
, resolvedPath
);
1376 char* addPoint
= strrchr(newRealPath
,'/');
1377 if ( addPoint
!= NULL
)
1378 strcpy(&addPoint
[1], &path
[17]);
1380 strcpy(newRealPath
, &path
[17]);
1381 image
= loadPhase4(newRealPath
, context
, exceptions
);
1382 if ( image
!= NULL
)
1386 else if ( (strncmp(path
, "@loader_path/", 13) == 0) && (context
.origin
!= NULL
) ) {
1387 // handle @loader_path path prefix
1388 char newPath
[strlen(context
.origin
) + strlen(path
)];
1389 strcpy(newPath
, context
.origin
);
1390 char* addPoint
= strrchr(newPath
,'/');
1391 if ( addPoint
!= NULL
)
1392 strcpy(&addPoint
[1], &path
[13]);
1394 strcpy(newPath
, &path
[13]);
1395 image
= loadPhase4(newPath
, context
, exceptions
);
1396 if ( image
!= NULL
)
1399 // perhaps loader path is a sym link, find realpath and retry
1400 char resolvedPath
[PATH_MAX
];
1401 if ( realpath(context
.origin
, resolvedPath
) != NULL
) {
1402 char newRealPath
[strlen(resolvedPath
) + strlen(path
)];
1403 strcpy(newRealPath
, resolvedPath
);
1404 char* addPoint
= strrchr(newRealPath
,'/');
1405 if ( addPoint
!= NULL
)
1406 strcpy(&addPoint
[1], &path
[13]);
1408 strcpy(newRealPath
, &path
[13]);
1409 image
= loadPhase4(newRealPath
, context
, exceptions
);
1410 if ( image
!= NULL
)
1415 return loadPhase4(path
, context
, exceptions
);
1420 static ImageLoader
* loadPhase2(const char* path
, const LoadContext
& context
,
1421 const char* const frameworkPaths
[], const char* const libraryPaths
[],
1422 std::vector
<const char*>* exceptions
)
1424 //fprintf(stderr, "%s(%s)\n", __func__ , path);
1425 ImageLoader
* image
= NULL
;
1426 const char* frameworkPartialPath
= getFrameworkPartialPath(path
);
1427 if ( frameworkPaths
!= NULL
) {
1428 if ( frameworkPartialPath
!= NULL
) {
1429 const int frameworkPartialPathLen
= strlen(frameworkPartialPath
);
1430 for(const char* const* fp
= frameworkPaths
; *fp
!= NULL
; ++fp
) {
1431 char npath
[strlen(*fp
)+frameworkPartialPathLen
+8];
1434 strcat(npath
, frameworkPartialPath
);
1435 //fprintf(stderr, "dyld: fallback framework path used: %s() -> loadPhase4(\"%s\", ...)\n", __func__, npath);
1436 image
= loadPhase4(npath
, context
, exceptions
);
1437 if ( image
!= NULL
)
1442 if ( libraryPaths
!= NULL
) {
1443 const char* libraryLeafName
= getLibraryLeafName(path
);
1444 const int libraryLeafNameLen
= strlen(libraryLeafName
);
1445 for(const char* const* lp
= libraryPaths
; *lp
!= NULL
; ++lp
) {
1446 char libpath
[strlen(*lp
)+libraryLeafNameLen
+8];
1447 strcpy(libpath
, *lp
);
1448 strcat(libpath
, "/");
1449 strcat(libpath
, libraryLeafName
);
1450 //fprintf(stderr, "dyld: fallback library path used: %s() -> loadPhase4(\"%s\", ...)\n", __func__, libpath);
1451 image
= loadPhase4(libpath
, context
, exceptions
);
1452 if ( image
!= NULL
)
1459 // try search overrides and fallbacks
1460 static ImageLoader
* loadPhase1(const char* path
, const LoadContext
& context
, std::vector
<const char*>* exceptions
)
1462 //fprintf(stderr, "%s(%s)\n", __func__ , path);
1463 ImageLoader
* image
= NULL
;
1465 // handle LD_LIBRARY_PATH environment variables that force searching
1466 if ( context
.useLdLibraryPath
&& (sEnv
.LD_LIBRARY_PATH
!= NULL
) ) {
1467 image
= loadPhase2(path
, context
, NULL
, sEnv
.LD_LIBRARY_PATH
, exceptions
);
1468 if ( image
!= NULL
)
1472 // handle DYLD_ environment variables that force searching
1473 if ( context
.useSearchPaths
&& ((sEnv
.DYLD_FRAMEWORK_PATH
!= NULL
) || (sEnv
.DYLD_LIBRARY_PATH
!= NULL
)) ) {
1474 image
= loadPhase2(path
, context
, sEnv
.DYLD_FRAMEWORK_PATH
, sEnv
.DYLD_LIBRARY_PATH
, exceptions
);
1475 if ( image
!= NULL
)
1480 image
= loadPhase3(path
, context
, exceptions
);
1481 if ( image
!= NULL
)
1484 // try fallback paths during second time (will open file)
1485 if ( (exceptions
!= NULL
) && ((sEnv
.DYLD_FALLBACK_FRAMEWORK_PATH
!= NULL
) || (sEnv
.DYLD_FALLBACK_LIBRARY_PATH
!= NULL
)) ) {
1486 image
= loadPhase2(path
, context
, sEnv
.DYLD_FALLBACK_FRAMEWORK_PATH
, sEnv
.DYLD_FALLBACK_LIBRARY_PATH
, exceptions
);
1487 if ( image
!= NULL
)
1494 // try root substitutions
1495 static ImageLoader
* loadPhase0(const char* path
, const LoadContext
& context
, std::vector
<const char*>* exceptions
)
1497 //fprintf(stderr, "%s(%s)\n", __func__ , path);
1499 // handle DYLD_ROOT_PATH which forces absolute paths to use a new root
1500 if ( (sEnv
.DYLD_ROOT_PATH
!= NULL
) && (path
[0] == '/') ) {
1501 for(const char* const* rootPath
= sEnv
.DYLD_ROOT_PATH
; *rootPath
!= NULL
; ++rootPath
) {
1502 char newPath
[strlen(*rootPath
) + strlen(path
)+2];
1503 strcpy(newPath
, *rootPath
);
1504 strcat(newPath
, path
);
1505 ImageLoader
* image
= loadPhase1(newPath
, context
, exceptions
);
1506 if ( image
!= NULL
)
1512 return loadPhase1(path
, context
, exceptions
);
1516 // Given all the DYLD_ environment variables, the general case for loading libraries
1517 // is that any given path expands into a list of possible locations to load. We
1518 // also must take care to ensure two copies of the "same" library are never loaded.
1520 // The algorithm used here is that there is a separate function for each "phase" of the
1521 // path expansion. Each phase function calls the next phase with each possible expansion
1522 // of that phase. The result is the last phase is called with all possible paths.
1524 // To catch duplicates the algorithm is run twice. The first time, the last phase checks
1525 // the path against all loaded images. The second time, the last phase calls open() on
1526 // the path. Either time, if an image is found, the phases all unwind without checking
1529 ImageLoader
* load(const char* path
, const LoadContext
& context
)
1531 //fprintf(stderr, "%s(%s)\n", __func__ , path);
1532 char realPath
[PATH_MAX
];
1533 // when DYLD_IMAGE_SUFFIX is in used, do a realpath(), otherwise a load of "Foo.framework/Foo" will not match
1534 if ( context
.useSearchPaths
&& ( gLinkContext
.imageSuffix
!= NULL
) ) {
1535 if ( realpath(path
, realPath
) != NULL
)
1539 // try all path permutations and check against existing loaded images
1540 ImageLoader
* image
= loadPhase0(path
, context
, NULL
);
1541 if ( image
!= NULL
)
1544 // try all path permutations and try open() until first sucesss
1545 std::vector
<const char*> exceptions
;
1546 image
= loadPhase0(path
, context
, &exceptions
);
1547 if ( image
!= NULL
)
1549 else if ( context
.dontLoad
)
1551 else if ( exceptions
.size() == 0 )
1552 throw "image not found";
1554 const char* msgStart
= "no suitable image found. Did find:";
1555 const char* delim
= "\n\t";
1556 size_t allsizes
= strlen(msgStart
)+8;
1557 for (unsigned int i
=0; i
< exceptions
.size(); ++i
)
1558 allsizes
+= (strlen(exceptions
[i
]) + strlen(delim
));
1559 char* fullMsg
= new char[allsizes
];
1560 strcpy(fullMsg
, msgStart
);
1561 for (unsigned int i
=0; i
< exceptions
.size(); ++i
) {
1562 strcat(fullMsg
, delim
);
1563 strcat(fullMsg
, exceptions
[i
]);
1565 throw (const char*)fullMsg
;
1572 // create when NSLinkModule is called for a second time on a bundle
1573 ImageLoader
* cloneImage(ImageLoader
* image
)
1575 const uint64_t offsetInFat
= image
->getOffsetInFatFile();
1577 // open file (automagically closed when this function exits)
1578 FileOpener
file(image
->getPath());
1580 struct stat stat_buf
;
1582 memset(&stat_buf
, 254, sizeof(struct stat
)); // hack until rdar://problem/3845883 is fixed
1584 if ( fstat(file
.getFileDescriptor(), &stat_buf
) == -1)
1587 // read first page of file
1588 uint8_t firstPage
[4096];
1589 pread(file
.getFileDescriptor(), firstPage
, 4096, offsetInFat
);
1591 // fat length is only used for sanity checking, since this image was already loaded once, just use upper bound
1592 uint64_t lenInFat
= stat_buf
.st_size
- offsetInFat
;
1594 // try mach-o loader
1595 if ( isCompatibleMachO(firstPage
) ) {
1596 ImageLoader
* clone
= new ImageLoaderMachO(image
->getPath(), file
.getFileDescriptor(), firstPage
, offsetInFat
, lenInFat
, stat_buf
, gLinkContext
);
1597 // don't add bundles to global list, they can be loaded but not linked. When linked it will be added to list
1598 if ( ! image
->isBundle() )
1603 // try other file formats...
1604 throw "can't clone image";
1608 ImageLoader
* loadFromMemory(const uint8_t* mem
, uint64_t len
, const char* moduleName
)
1610 // if fat wrapper, find usable sub-file
1611 const fat_header
* memStartAsFat
= (fat_header
*)mem
;
1612 uint64_t fileOffset
= 0;
1613 uint64_t fileLength
= len
;
1614 if ( memStartAsFat
->magic
== OSSwapBigToHostInt32(FAT_MAGIC
) ) {
1615 if ( fatFindBest(memStartAsFat
, &fileOffset
, &fileLength
) ) {
1616 mem
= &mem
[fileOffset
];
1620 throw "no matching architecture in universal wrapper";
1624 // try mach-o each loader
1625 if ( isCompatibleMachO(mem
) ) {
1626 ImageLoader
* image
= new ImageLoaderMachO(moduleName
, (mach_header
*)mem
, len
, gLinkContext
);
1627 // don't add bundles to global list, they can be loaded but not linked. When linked it will be added to list
1628 if ( ! image
->isBundle() )
1633 // try other file formats...
1635 // throw error about what was found
1636 switch (*(uint32_t*)mem
) {
1641 throw "mach-o, but wrong architecture";
1643 throwf("unknown file type, first eight bytes: 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X",
1644 mem
[0], mem
[1], mem
[2], mem
[3], mem
[4], mem
[5], mem
[6],mem
[7]);
1649 void registerAddCallback(ImageCallback func
)
1651 // now add to list to get notified when any more images are added
1652 sAddImageCallbacks
.push_back(func
);
1654 // call callback with all existing images, starting at roots
1655 const int rootCount
= sImageRoots
.size();
1656 for(int i
=0; i
< rootCount
; ++i
) {
1657 ImageLoader
* image
= sImageRoots
[i
];
1658 image
->runNotification(gLinkContext
, sAddImageCallbacks
.size());
1661 // for (std::vector<ImageLoader*>::iterator it=sImageRoots.begin(); it != sImageRoots.end(); it++) {
1662 // ImageLoader* image = *it;
1663 // image->runNotification(gLinkContext, sAddImageCallbacks.size());
1667 void registerRemoveCallback(ImageCallback func
)
1669 sRemoveImageCallbacks
.push_back(func
);
1672 void clearErrorMessage()
1674 error_string
[0] = '\0';
1677 void setErrorMessage(const char* message
)
1679 // save off error message in global buffer for CrashReporter to find
1680 strncpy(error_string
, message
, sizeof(error_string
)-1);
1681 error_string
[sizeof(error_string
)-1] = '\0';
1684 const char* getErrorMessage()
1686 return error_string
;
1689 void halt(const char* message
)
1691 fprintf(stderr
, "dyld: %s\n", message
);
1692 setErrorMessage(message
);
1693 strncpy(error_string
, message
, sizeof(error_string
)-1);
1694 error_string
[sizeof(error_string
)-1] = '\0';
1696 #if __ppc__ || __ppc64__
1701 #error unknown architecture
1703 abort(); // needed to suppress warning that noreturn function returns
1707 uintptr_t bindLazySymbol(const mach_header
* mh
, uintptr_t* lazyPointer
)
1709 uintptr_t result
= 0;
1710 // acquire read-lock on dyld's data structures
1711 #if 0 // rdar://problem/3811777 turn off locking until deadlock is resolved
1712 if ( gThreadHelpers
!= NULL
)
1713 (*gThreadHelpers
->lockForReading
)();
1715 // lookup and bind lazy pointer and get target address
1717 ImageLoader
* target
;
1719 // fast stubs pass NULL for mh and image is instead found via the location of stub (aka lazyPointer)
1721 target
= dyld::findImageContainingAddressThreadSafe(lazyPointer
);
1723 target
= dyld::findImageByMachHeader(mh
);
1725 // note, target should always be mach-o, because only mach-o lazy handler wired up to this
1726 target
= dyld::findImageByMachHeader(mh
);
1728 if ( target
== NULL
)
1729 throw "image not found for lazy pointer";
1730 result
= target
->doBindLazySymbol(lazyPointer
, gLinkContext
);
1732 catch (const char* message
) {
1733 fprintf(stderr
, "dyld: lazy symbol binding failed: %s\n", message
);
1736 // release read-lock on dyld's data structures
1738 if ( gThreadHelpers
!= NULL
)
1739 (*gThreadHelpers
->unlockForReading
)();
1741 // return target address to glue which jumps to it with real parameters restored
1746 // SPI used by ZeroLink to lazy load bundles
1747 void registerZeroLinkHandlers(BundleNotificationCallBack notify
, BundleLocatorCallBack locate
)
1749 sBundleNotifier
= notify
;
1750 sBundleLocation
= locate
;
1753 void registerUndefinedHandler(UndefinedHandler handler
)
1755 sUndefinedHandler
= handler
;
1758 static void undefinedHandler(const char* symboName
)
1760 if ( sUndefinedHandler
!= NULL
) {
1761 (*sUndefinedHandler
)(symboName
);
1765 static bool findExportedSymbol(const char* name
, bool onlyInCoalesced
, const ImageLoader::Symbol
** sym
, ImageLoader
** image
)
1767 // try ZeroLink short cut to finding bundle which exports this symbol
1768 if ( sBundleLocation
!= NULL
) {
1769 ImageLoader
* zlImage
= (*sBundleLocation
)(name
);
1770 if ( zlImage
== ((ImageLoader
*)(-1)) ) {
1771 // -1 is magic value that request symbol is in a bundle not yet linked into process
1772 // try calling handler to link in that symbol
1773 undefinedHandler(name
);
1774 // call locator again
1775 zlImage
= (*sBundleLocation
)(name
);
1777 // if still not found, then ZeroLink has no idea where to find it
1778 if ( zlImage
== ((ImageLoader
*)(-1)) )
1780 if ( zlImage
!= NULL
) {
1781 // ZeroLink cache knows where the symbol is
1782 *sym
= zlImage
->findExportedSymbol(name
, NULL
, false, image
);
1783 if ( *sym
!= NULL
) {
1789 // ZeroLink says it is in some bundle already loaded, but not linked, walk them all
1790 const unsigned int imageCount
= sAllImages
.size();
1791 for(unsigned int i
=0; i
< imageCount
; ++i
){
1792 ImageLoader
* anImage
= sAllImages
[i
];
1793 if ( anImage
->isBundle() && !anImage
->hasHiddenExports() ) {
1794 //fprintf(stderr, "dyld: search for %s in %s\n", name, anImage->getPath());
1795 *sym
= anImage
->findExportedSymbol(name
, NULL
, false, image
);
1796 if ( *sym
!= NULL
) {
1804 // search all images in order
1805 ImageLoader
* firstWeakImage
= NULL
;
1806 const ImageLoader::Symbol
* firstWeakSym
= NULL
;
1807 const unsigned int imageCount
= sAllImages
.size();
1808 for(unsigned int i
=0; i
< imageCount
; ++i
){
1809 ImageLoader
* anImage
= sAllImages
[i
];
1810 if ( ! anImage
->hasHiddenExports() && (!onlyInCoalesced
|| anImage
->hasCoalescedExports()) ) {
1811 *sym
= anImage
->findExportedSymbol(name
, NULL
, false, image
);
1812 if ( *sym
!= NULL
) {
1813 // if weak definition found, record first one found
1814 if ( ((*image
)->getExportedSymbolInfo(*sym
) & ImageLoader::kWeakDefinition
) != 0 ) {
1815 if ( firstWeakImage
== NULL
) {
1816 firstWeakImage
= *image
;
1817 firstWeakSym
= *sym
;
1821 // found non-weak, so immediately return with it
1827 if ( firstWeakSym
!= NULL
) {
1828 // found a weak definition, but no non-weak, so return first weak found
1829 *sym
= firstWeakSym
;
1830 *image
= firstWeakImage
;
1837 bool flatFindExportedSymbol(const char* name
, const ImageLoader::Symbol
** sym
, ImageLoader
** image
)
1839 return findExportedSymbol(name
, false, sym
, image
);
1842 bool findCoalescedExportedSymbol(const char* name
, const ImageLoader::Symbol
** sym
, ImageLoader
** image
)
1844 return findExportedSymbol(name
, true, sym
, image
);
1848 bool flatFindExportedSymbolWithHint(const char* name
, const char* librarySubstring
, const ImageLoader::Symbol
** sym
, ImageLoader
** image
)
1850 // search all images in order
1851 const unsigned int imageCount
= sAllImages
.size();
1852 for(unsigned int i
=0; i
< imageCount
; ++i
){
1853 ImageLoader
* anImage
= sAllImages
[i
];
1854 // only look at images whose paths contain the hint string (NULL hint string is wildcard)
1855 if ( ! anImage
->isBundle() && ((librarySubstring
==NULL
) || (strstr(anImage
->getPath(), librarySubstring
) != NULL
)) ) {
1856 *sym
= anImage
->findExportedSymbol(name
, NULL
, false, image
);
1857 if ( *sym
!= NULL
) {
1865 static void getMappedRegions(ImageLoader::RegionsVector
& regions
)
1867 const unsigned int imageCount
= sAllImages
.size();
1868 for(unsigned int i
=0; i
< imageCount
; ++i
){
1869 ImageLoader
* anImage
= sAllImages
[i
];
1870 anImage
->addMappedRegions(regions
);
1875 static ImageLoader
* libraryLocator(const char* libraryName
, bool search
, const char* origin
, const char* rpath
[])
1877 dyld::LoadContext context
;
1878 context
.useSearchPaths
= search
;
1879 context
.useLdLibraryPath
= false;
1880 context
.dontLoad
= false;
1881 context
.mustBeBundle
= false;
1882 context
.mustBeDylib
= true;
1883 context
.matchByInstallName
= false;
1884 context
.origin
= origin
;
1885 context
.rpath
= rpath
;
1886 return load(libraryName
, context
);
1890 static void setContext(int argc
, const char* argv
[], const char* envp
[], const char* apple
[])
1892 gLinkContext
.loadLibrary
= &libraryLocator
;
1893 gLinkContext
.imageNotification
= &imageNotification
;
1894 gLinkContext
.terminationRecorder
= &terminationRecorder
;
1895 gLinkContext
.flatExportFinder
= &flatFindExportedSymbol
;
1896 gLinkContext
.coalescedExportFinder
= &findCoalescedExportedSymbol
;
1897 gLinkContext
.undefinedHandler
= &undefinedHandler
;
1898 gLinkContext
.addImageNeedingNotification
= &addImageNeedingNotification
;
1899 gLinkContext
.notifyAdding
= ¬ifyAdding
;
1900 gLinkContext
.getAllMappedRegions
= &getMappedRegions
;
1901 gLinkContext
.bindingHandler
= NULL
;
1902 gLinkContext
.bindingOptions
= ImageLoader::kBindingNone
;
1903 gLinkContext
.mainExecutable
= sMainExecutable
;
1904 gLinkContext
.argc
= argc
;
1905 gLinkContext
.argv
= argv
;
1906 gLinkContext
.envp
= envp
;
1907 gLinkContext
.apple
= apple
;
1910 static bool checkEmulation()
1913 int mib
[] = { CTL_KERN
, KERN_CLASSIC
, getpid() };
1915 size_t len
= sizeof(int);
1916 int ret
= sysctl(mib
, 3, &is_classic
, &len
, NULL
, 0);
1917 if ((ret
!= -1) && is_classic
) {
1918 // When a 32-bit ppc program is run under emulation on an Intel processor,
1919 // we want any i386 dylibs (e.g. the emulator) to not load in the shared region
1920 // because the shared region is being used by ppc dylibs
1921 gLinkContext
.sharedRegionMode
= ImageLoader::kDontUseSharedRegion
;
1928 void link(ImageLoader
* image
, ImageLoader::BindingLaziness bindness
, ImageLoader::InitializerRunning runInitializers
)
1930 // add to list of known images. This did not happen at creation time for bundles
1931 if ( image
->isBundle() )
1934 // we detect root images as those not linked in yet
1935 if ( !image
->isLinked() )
1936 addRootImage(image
);
1938 // notify ZeroLink of new image with concat of logical and physical name
1939 if ( sBundleNotifier
!= NULL
&& image
->isBundle() ) {
1940 const int logicalLen
= strlen(image
->getLogicalPath());
1941 char logAndPhys
[strlen(image
->getPath())+logicalLen
+2];
1942 strcpy(logAndPhys
, image
->getLogicalPath());
1943 strcpy(&logAndPhys
[logicalLen
+1], image
->getPath());
1944 (*sBundleNotifier
)(logAndPhys
, image
);
1949 image
->link(gLinkContext
, bindness
, runInitializers
, sAddImageCallbacks
.size());
1951 catch (const char* msg
) {
1952 sAllImagesMightContainUnlinkedImages
= true;
1956 #if OLD_GDB_DYLD_INTERFACE
1957 // notify gdb that loaded libraries have changed
1958 gdb_dyld_state_changed();
1964 // _pthread_keys is partitioned in a lower part that dyld will use; libSystem
1965 // will use the upper part. We set __pthread_tsd_first to 1 as the start of
1966 // the lower part. Libc will take #1 and c++ exceptions will take #2. There
1967 // is one free key=3 left.
1970 extern int __pthread_tsd_first
;
1975 // Entry point for dyld. The kernel loads dyld and jumps to __dyld_start which
1976 // sets up some registers and call this function.
1978 // Returns address of main() in target program which __dyld_start jumps to
1981 _main(const struct mach_header
* mainExecutableMH
, int argc
, const char* argv
[], const char* envp
[], const char* apple
[])
1983 // set pthread keys to dyld range
1984 __pthread_tsd_first
= 1;
1986 bool isEmulated
= checkEmulation();
1987 // Pickup the pointer to the exec path.
1988 sExecPath
= apple
[0];
1991 sExecPath
= strdup(apple
[0] + strlen(apple
[0]) + 1);
1993 if ( sExecPath
[0] != '/' ) {
1994 // have relative path, use cwd to make absolute
1995 char cwdbuff
[MAXPATHLEN
];
1996 if ( getcwd(cwdbuff
, MAXPATHLEN
) != NULL
) {
1997 // maybe use static buffer to avoid calling malloc so early...
1998 char* s
= new char[strlen(cwdbuff
) + strlen(sExecPath
) + 2];
2001 strcat(s
, sExecPath
);
2005 uintptr_t result
= 0;
2006 sMainExecutableMachHeader
= mainExecutableMH
;
2007 checkEnvironmentVariables(envp
, isEmulated
);
2008 if ( sEnv
.DYLD_PRINT_OPTS
)
2010 if ( sEnv
.DYLD_PRINT_ENV
)
2011 printEnvironmentVariables(envp
);
2013 setContext(argc
, argv
, envp
, apple
);
2014 ImageLoader::BindingLaziness bindness
= sEnv
.DYLD_BIND_AT_LAUNCH
? ImageLoader::kLazyAndNonLazy
: ImageLoader::kNonLazyOnly
;
2016 // load any inserted libraries before loading the main executable so that they are first in flat namespace
2017 int insertLibrariesCount
= 0;
2018 if ( sEnv
.DYLD_INSERT_LIBRARIES
!= NULL
) {
2019 for (const char* const* lib
= sEnv
.DYLD_INSERT_LIBRARIES
; *lib
!= NULL
; ++lib
) {
2020 insertLibrariesCount
++;
2023 ImageLoader
* insertedImages
[insertLibrariesCount
];
2024 if ( insertLibrariesCount
> 0 ) {
2025 for (int i
=0; i
< insertLibrariesCount
; ++i
) {
2027 LoadContext context
;
2028 context
.useSearchPaths
= false;
2029 context
.useLdLibraryPath
= false;
2030 context
.dontLoad
= false;
2031 context
.mustBeBundle
= false;
2032 context
.mustBeDylib
= true;
2033 context
.matchByInstallName
= false;
2034 context
.origin
= NULL
; // can't use @loader_path with DYLD_INSERT_LIBRARIES
2035 context
.rpath
= NULL
;
2036 insertedImages
[i
] = load(sEnv
.DYLD_INSERT_LIBRARIES
[i
], context
);
2039 char buf
[strlen(sEnv
.DYLD_INSERT_LIBRARIES
[i
])+50];
2040 sprintf(buf
, "could not load inserted library: %s\n", sEnv
.DYLD_INSERT_LIBRARIES
[i
]);
2041 insertedImages
[i
] = NULL
;
2047 // load and link main executable
2049 sMainExecutable
= instantiateFromLoadedImage(mainExecutableMH
, sExecPath
);
2050 gLinkContext
.mainExecutable
= sMainExecutable
;
2051 if ( sMainExecutable
->forceFlat() ) {
2052 gLinkContext
.bindFlat
= true;
2053 gLinkContext
.prebindUsage
= ImageLoader::kUseNoPrebinding
;
2055 link(sMainExecutable
, bindness
, ImageLoader::kDontRunInitializers
);
2056 result
= (uintptr_t)sMainExecutable
->getMain();
2058 catch(const char* message
) {
2062 fprintf(stderr
, "dyld: launch failed\n");
2065 // Link in any inserted libraries.
2066 // Do this after link main executable so any extra libraries pulled in by inserted libraries are at end of flat namespace
2067 if ( insertLibrariesCount
> 0 ) {
2068 for (int i
=0; i
< insertLibrariesCount
; ++i
) {
2070 if ( insertedImages
[i
] != NULL
)
2071 link(insertedImages
[i
], bindness
, ImageLoader::kDontRunInitializers
);
2073 catch (const char* message
) {
2074 char buf
[strlen(sEnv
.DYLD_INSERT_LIBRARIES
[i
])+50+strlen(message
)];
2075 sprintf(buf
, "could not link inserted library: %s\n%s\n", sEnv
.DYLD_INSERT_LIBRARIES
[i
], message
);