]> git.saurik.com Git - apple/dyld.git/blob - src/dyld.cpp
2017ba6318b98ae199de6325c63a19c2f675602b
[apple/dyld.git] / src / dyld.cpp
1 /* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*-
2 *
3 * Copyright (c) 2004-2005 Apple Computer, Inc. All rights reserved.
4 *
5 * @APPLE_LICENSE_HEADER_START@
6 *
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
12 * file.
13 *
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.
21 *
22 * @APPLE_LICENSE_HEADER_END@
23 */
24
25 #include <stdint.h>
26 #include <string.h>
27 #include <unistd.h>
28 #include <fcntl.h>
29 #include <sys/param.h>
30 #include <mach/mach_time.h> // mach_absolute_time()
31 #include <sys/types.h>
32 #include <sys/stat.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>
38
39 #include <vector>
40
41 #include "mach-o/dyld_gdb.h"
42
43 #include "dyld.h"
44 #include "ImageLoader.h"
45 #include "ImageLoaderMachO.h"
46 #include "dyldLibSystemThreadHelpers.h"
47
48
49 #define CPU_TYPE_MASK 0x00FFFFFF /* complement of CPU_ARCH_MASK */
50
51
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);
58 #endif
59
60 // magic so CrashReporter logs message
61 extern "C" {
62 char error_string[1024];
63 }
64
65
66 //
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.
69 //
70 //
71 //
72 //
73 //
74
75
76 namespace dyld {
77
78
79 //
80 // state of all environment variables dyld uses
81 //
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;
94 bool DYLD_PRINT_OPTS;
95 bool DYLD_PRINT_ENV;
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
111 };
112
113 // all global state
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;
136
137
138
139 // utility class to assure files are closed when an exception is thrown
140 class FileOpener {
141 public:
142 FileOpener(const char* path);
143 ~FileOpener();
144 int getFileDescriptor() { return fd; }
145 private:
146 int fd;
147 };
148
149 FileOpener::FileOpener(const char* path)
150 {
151 fd = open(path, O_RDONLY, 0);
152 }
153
154 FileOpener::~FileOpener()
155 {
156 close(fd);
157 }
158
159
160
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)
164 {
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());
171 }
172 return callbackCount;
173 }
174
175
176
177 // notify gdb et al about these new images
178 static void notifyAdding(std::vector<ImageLoader*>& images)
179 {
180 // build array
181 unsigned int len = images.size();
182 if ( len != 0 ) {
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());
191 }
192
193 // tell gdb
194 addImagesToAllImages(len, infos);
195
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);
199 }
200 }
201 }
202
203
204
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)
210 {
211 //fprintf(stderr, "addRootImage(%p, %s)\n", image, image->getPath());
212 // add to list of roots
213 sImageRoots.push_back(image);
214 }
215
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)
219 {
220 sImagesToNotifyAboutOtherImages.push_back(image);
221 }
222
223 static void addImage(ImageLoader* image)
224 {
225 // add to master list
226 sAllImages.push_back(image);
227
228 if ( sEnv.DYLD_PRINT_LIBRARIES || (sEnv.DYLD_PRINT_LIBRARIES_POST_LAUNCH && (sMainExecutable!=NULL) && sMainExecutable->isLinked()) ) {
229 uint64_t offset = image->getOffsetInFatFile();
230 if ( offset == 0 )
231 fprintf(stderr, "dyld: loaded: %s\n", image->getPath());
232 else
233 fprintf(stderr, "dyld: loaded: %s, cpu-sub-type: %d\n", image->getPath(), image->machHeader()->cpusubtype);
234 }
235
236 #if OLD_GDB_DYLD_INTERFACE
237 // let gdb find out about this
238 addImageForgdb(image->machHeader(), image->getSlide(), image->getPath(), image->getLogicalPath());
239 #endif
240 }
241
242 void removeImage(ImageLoader* image)
243 {
244 // flush find-by-address cache
245 if ( sLastImageByAddressCache == image )
246 sLastImageByAddressCache = NULL;
247
248 // if in termination list, pull it out and run terminator
249 for (std::vector<ImageLoader*>::iterator it=sImageFilesNeedingTermination.begin(); it != sImageFilesNeedingTermination.end(); it++) {
250 if ( *it == image ) {
251 sImageFilesNeedingTermination.erase(it);
252 image->doTermination(gLinkContext);
253 break;
254 }
255 }
256
257 // tell all register add image handlers about this
258 // do this before removing image from internal data structures so that the callback can querey dyld about the image
259 for (std::vector<ImageCallback>::iterator it=sRemoveImageCallbacks.begin(); it != sRemoveImageCallbacks.end(); it++) {
260 (*it)(image->machHeader(), image->getSlide());
261 }
262
263 // tell all interested images
264 for (std::vector<ImageLoader*>::iterator it=sImagesToNotifyAboutOtherImages.begin(); it != sImagesToNotifyAboutOtherImages.end(); it++) {
265 dyld_image_info info;
266 info.imageLoadAddress = image->machHeader();
267 info.imageFilePath = image->getPath();
268 info.imageFileModDate = image->lastModified();
269 (*it)->doNotification(dyld_image_removing, 1, &info);
270 }
271
272 // remove from master list
273 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
274 if ( *it == image ) {
275 sAllImages.erase(it);
276 break;
277 }
278 }
279
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);
284 break;
285 }
286 }
287
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);
292 break;
293 }
294 }
295
296 // tell gdb, new way
297 removeImageFromAllImages(image->machHeader());
298
299 #if OLD_GDB_DYLD_INTERFACE
300 // tell gdb, old way
301 removeImageForgdb(image->machHeader());
302 gdb_dyld_state_changed();
303 #endif
304 }
305
306
307 static void terminationRecorder(ImageLoader* image)
308 {
309 sImageFilesNeedingTermination.push_back(image);
310 }
311
312 const char* getExecutablePath()
313 {
314 return sExecPath;
315 }
316
317
318 void initializeMainExecutable()
319 {
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);
325 }
326 /*
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???
332 if ( image != NULL )
333 image->runInitializers(gLinkContext);
334 }
335 */
336 if ( sEnv.DYLD_PRINT_STATISTICS )
337 ImageLoaderMachO::printStatistics(sAllImages.size());
338 }
339
340 bool mainExecutablePrebound()
341 {
342 return sMainExecutable->usablePrebinding(gLinkContext);
343 }
344
345 ImageLoader* mainExecutable()
346 {
347 return sMainExecutable;
348 }
349
350
351 void runTerminators()
352 {
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);
357 }
358 sImageFilesNeedingTermination.clear();
359 }
360
361
362 //
363 // Turns a colon separated list of strings
364 // into a NULL terminated array of string
365 // pointers.
366 //
367 static const char** parseColonList(const char* list)
368 {
369 if ( list[0] == '\0' )
370 return NULL;
371
372 int colonCount = 0;
373 for(const char* s=list; *s != '\0'; ++s) {
374 if (*s == ':')
375 ++colonCount;
376 }
377
378 int index = 0;
379 const char* start = list;
380 char** result = new char*[colonCount+2];
381 for(const char* s=list; *s != '\0'; ++s) {
382 if (*s == ':') {
383 int len = s-start;
384 char* str = new char[len+1];
385 strncpy(str, start, len);
386 str[len] = '\0';
387 start = &s[1];
388 result[index++] = str;
389 }
390 }
391 int len = strlen(start);
392 char* str = new char[len+1];
393 strcpy(str, start);
394 result[index++] = str;
395 result[index] = NULL;
396
397 return (const char**)result;
398 }
399
400 /*
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
407 * for.
408 */
409 static bool riskyUser()
410 {
411 static bool checked = false;
412 static bool risky = false;
413 if ( !checked ) {
414 risky = ( getuid() != 0 && (getuid() != geteuid() || getgid() != getegid()) );
415 checked = true;
416 }
417 return risky;
418 }
419
420
421 static bool disableIfBadUser(char* rhs)
422 {
423 bool didDisable = false;
424 if ( riskyUser() ) {
425 *rhs ='\0';
426 didDisable = true;
427 }
428 return didDisable;
429 }
430
431 static void paths_expand_roots(const char **paths, const char *key, const char *val)
432 {
433 // assert(val != NULL);
434 // assert(paths != NULL);
435 if(NULL != key) {
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]);
442 paths[i] = newPath;
443 }
444 }
445 }
446 return;
447 }
448
449 static void removePathWithPrefix(const char* paths[], const char* prefix)
450 {
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 )
454 ++s;
455 paths[d] = paths[s];
456 }
457 }
458
459 #if 0
460 static void paths_dump(const char **paths)
461 {
462 // assert(paths != NULL);
463 const char **strs = paths;
464 while(*strs != NULL)
465 {
466 fprintf(stderr, "\"%s\"\n", *strs);
467 strs++;
468 }
469 return;
470 }
471 #endif
472
473 static void printOptions(const char* argv[])
474 {
475 uint32_t i = 0;
476 while ( NULL != argv[i] ) {
477 fprintf(stderr, "opt[%i] = \"%s\"\n", i, argv[i]);
478 i++;
479 }
480 }
481
482 static void printEnvironmentVariables(const char* envp[])
483 {
484 while ( NULL != *envp ) {
485 fprintf(stderr, "%s\n", *envp);
486 envp++;
487 }
488 }
489
490
491
492 void processDyldEnvironmentVarible(const char* key, const char* value)
493 {
494 if ( strcmp(key, "DYLD_FRAMEWORK_PATH") == 0 ) {
495 if ( !disableIfBadUser((char*)value) )
496 sEnv.DYLD_FRAMEWORK_PATH = parseColonList(value);
497 }
498 else if ( strcmp(key, "DYLD_FALLBACK_FRAMEWORK_PATH") == 0 ) {
499 if ( !disableIfBadUser((char*)value) )
500 sEnv.DYLD_FALLBACK_FRAMEWORK_PATH = parseColonList(value);
501 }
502 else if ( strcmp(key, "DYLD_LIBRARY_PATH") == 0 ) {
503 if ( !disableIfBadUser((char*)value) )
504 sEnv.DYLD_LIBRARY_PATH = parseColonList(value);
505 }
506 else if ( strcmp(key, "DYLD_FALLBACK_LIBRARY_PATH") == 0 ) {
507 if ( !disableIfBadUser((char*)value) )
508 sEnv.DYLD_FALLBACK_LIBRARY_PATH = parseColonList(value);
509 }
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;
518 break;
519 }
520 }
521 }
522 }
523 }
524 else if ( strcmp(key, "DYLD_IMAGE_SUFFIX") == 0 ) {
525 if ( !disableIfBadUser((char*)value) )
526 gLinkContext.imageSuffix = value;
527 }
528 else if ( strcmp(key, "DYLD_INSERT_LIBRARIES") == 0 ) {
529 if ( !disableIfBadUser((char*)value) )
530 sEnv.DYLD_INSERT_LIBRARIES = parseColonList(value);
531 }
532 else if ( strcmp(key, "DYLD_DEBUG_TRACE") == 0 ) {
533 fprintf(stderr, "dyld: warning DYLD_DEBUG_TRACE not supported\n");
534 }
535 else if ( strcmp(key, "DYLD_ERROR_PRINT") == 0 ) {
536 fprintf(stderr, "dyld: warning DYLD_ERROR_PRINT not supported\n");
537 }
538 else if ( strcmp(key, "DYLD_PRINT_OPTS") == 0 ) {
539 sEnv.DYLD_PRINT_OPTS = true;
540 }
541 else if ( strcmp(key, "DYLD_PRINT_ENV") == 0 ) {
542 sEnv.DYLD_PRINT_ENV = true;
543 }
544 else if ( strcmp(key, "DYLD_PRINT_LIBRARIES") == 0 ) {
545 sEnv.DYLD_PRINT_LIBRARIES = true;
546 }
547 else if ( strcmp(key, "DYLD_PRINT_LIBRARIES_POST_LAUNCH") == 0 ) {
548 sEnv.DYLD_PRINT_LIBRARIES_POST_LAUNCH = true;
549 }
550 else if ( strcmp(key, "DYLD_TRACE") == 0 ) {
551 fprintf(stderr, "dyld: warning DYLD_TRACE not supported\n");
552 }
553 else if ( strcmp(key, "DYLD_EBADEXEC_ONLY") == 0 ) {
554 fprintf(stderr, "dyld: warning DYLD_EBADEXEC_ONLY not supported\n");
555 }
556 else if ( strcmp(key, "DYLD_BIND_AT_LAUNCH") == 0 ) {
557 sEnv.DYLD_BIND_AT_LAUNCH = true;
558 }
559 else if ( strcmp(key, "DYLD_FORCE_FLAT_NAMESPACE") == 0 ) {
560 gLinkContext.bindFlat = true;
561 }
562 else if ( strcmp(key, "DYLD_DEAD_LOCK_HANG") == 0 ) {
563 fprintf(stderr, "dyld: warning DYLD_DEAD_LOCK_HANG not supported\n");
564 }
565 else if ( strcmp(key, "DYLD_ABORT_MULTIPLE_INITS") == 0 ) {
566 fprintf(stderr, "dyld: warning DYLD_ABORT_MULTIPLE_INITS not supported\n");
567 }
568 else if ( strcmp(key, "DYLD_NEW_LOCAL_SHARED_REGIONS") == 0 ) {
569 gLinkContext.sharedRegionMode = ImageLoader::kUsePrivateSharedRegion;
570 }
571 else if ( strcmp(key, "DYLD_SLIDE_AND_PACK_DYLIBS") == 0 ) {
572 gLinkContext.slideAndPackDylibs = true;
573 }
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");
577 }
578 else if ( strcmp(key, "DYLD_PREBIND_DEBUG") == 0 ) {
579 gLinkContext.verbosePrebinding = true;
580 }
581 else if ( strcmp(key, "DYLD_HINTS_DEBUG") == 0 ) {
582 fprintf(stderr, "dyld: warning DYLD_HINTS_DEBUG not supported\n");
583 }
584 else if ( strcmp(key, "DYLD_SAMPLE_DEBUG") == 0 ) {
585 fprintf(stderr, "dyld: warning DYLD_SAMPLE_DEBUG not supported\n");
586 }
587 else if ( strcmp(key, "DYLD_EXECUTABLE_PATH_DEBUG") == 0 ) {
588 fprintf(stderr, "dyld: warning DYLD_EXECUTABLE_PATH_DEBUG not supported\n");
589 }
590 else if ( strcmp(key, "DYLD_TWO_LEVEL_DEBUG") == 0 ) {
591 fprintf(stderr, "dyld: warning DYLD_TWO_LEVEL_DEBUG not supported\n");
592 }
593 else if ( strcmp(key, "DYLD_LAZY_INITIALIZERS") == 0 ) {
594 fprintf(stderr, "dyld: warning DYLD_LAZY_INITIALIZERS not supported\n");
595 }
596 else if ( strcmp(key, "DYLD_PRINT_INITIALIZERS") == 0 ) {
597 gLinkContext.verboseInit = true;
598 }
599 else if ( strcmp(key, "DYLD_PRINT_STATISTICS") == 0 ) {
600 sEnv.DYLD_PRINT_STATISTICS = true;
601 }
602 else if ( strcmp(key, "DYLD_PRINT_SEGMENTS") == 0 ) {
603 gLinkContext.verboseMapping = true;
604 }
605 else if ( strcmp(key, "DYLD_PRINT_BINDINGS") == 0 ) {
606 gLinkContext.verboseBind = true;
607 }
608 else if ( strcmp(key, "DYLD_PRINT_REBASINGS") == 0 ) {
609 gLinkContext.verboseRebase = true;
610 }
611 else if ( strcmp(key, "DYLD_PRINT_APIS") == 0 ) {
612 gLogAPIs = true;
613 }
614 else if ( strcmp(key, "DYLD_PRINT_WARNINGS") == 0 ) {
615 gLinkContext.verboseWarnings = true;
616 }
617 else if ( strcmp(key, "DYLD_SHARED_REGION") == 0 ) {
618 if ( strcmp(value, "private") == 0 ) {
619 gLinkContext.sharedRegionMode = ImageLoader::kUsePrivateSharedRegion;
620 }
621 else if ( strcmp(value, "avoid") == 0 ) {
622 gLinkContext.sharedRegionMode = ImageLoader::kDontUseSharedRegion;
623 }
624 else if ( strcmp(value, "use") == 0 ) {
625 gLinkContext.sharedRegionMode = ImageLoader::kUseSharedRegion;
626 }
627 else if ( value[0] == '\0' ) {
628 gLinkContext.sharedRegionMode = ImageLoader::kUseSharedRegion;
629 }
630 else {
631 fprintf(stderr, "dyld: warning unknown option to DYLD_SHARED_REGION. Valid options are: use, private, avoid\n");
632 }
633 }
634 else if ( strcmp(key, "DYLD_IGNORE_PREBINDING") == 0 ) {
635 if ( strcmp(value, "all") == 0 ) {
636 gLinkContext.prebindUsage = ImageLoader::kUseNoPrebinding;
637 }
638 else if ( strcmp(value, "app") == 0 ) {
639 gLinkContext.prebindUsage = ImageLoader::kUseAllButAppPredbinding;
640 }
641 else if ( strcmp(value, "nonsplit") == 0 ) {
642 gLinkContext.prebindUsage = ImageLoader::kUseSplitSegPrebinding;
643 }
644 else if ( value[0] == '\0' ) {
645 gLinkContext.prebindUsage = ImageLoader::kUseSplitSegPrebinding;
646 }
647 else {
648 fprintf(stderr, "dyld: warning unknown option to DYLD_IGNORE_PREBINDING. Valid options are: all, app, nonsplit\n");
649 }
650 }
651 else {
652 fprintf(stderr, "dyld: warning, unknown environment variable: %s\n", key);
653 }
654 }
655
656 static void checkEnvironmentVariables(const char* envp[], bool ignoreEnviron)
657 {
658 const char* home = NULL;
659 const char** p;
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;
667 char key[keyLen+1];
668 strncpy(key, keyEqualsValue, keyLen);
669 key[keyLen] = '\0';
670 processDyldEnvironmentVarible(key, value);
671 }
672 }
673 else if ( strncmp(keyEqualsValue, "HOME=", 5) == 0 ) {
674 home = &keyEqualsValue[5];
675 }
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);
680 }
681 }
682
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 ) {
687 if ( riskyUser() )
688 removePathWithPrefix(paths, "$HOME");
689 else
690 paths_expand_roots(paths, "$HOME", home);
691 }
692 sEnv.DYLD_FALLBACK_FRAMEWORK_PATH = paths;
693 }
694
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 ) {
699 if ( riskyUser() )
700 removePathWithPrefix(paths, "$HOME");
701 else
702 paths_expand_roots(paths, "$HOME", home);
703 }
704 sEnv.DYLD_FALLBACK_LIBRARY_PATH = paths;
705 }
706 }
707
708
709 static void getHostInfo()
710 {
711 #if 0
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";
719
720 sHostCPU = info.cpu_type;
721 sHostCPUsubtype = info.cpu_subtype;
722 #endif
723
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";
730 }
731
732 bool validImage(ImageLoader* possibleImage)
733 {
734 const unsigned int imageCount = sAllImages.size();
735 for(unsigned int i=0; i < imageCount; ++i) {
736 if ( possibleImage == sAllImages[i] ) {
737 return true;
738 }
739 }
740 return false;
741 }
742
743 uint32_t getImageCount()
744 {
745 if ( sAllImagesMightContainUnlinkedImages ) {
746 uint32_t count = 0;
747 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
748 if ( (*it)->isLinked() )
749 ++count;
750 }
751 return count;
752 }
753 else {
754 return sAllImages.size();
755 }
756 }
757
758 ImageLoader* getIndexedImage(unsigned int index)
759 {
760 if ( sAllImagesMightContainUnlinkedImages ) {
761 uint32_t count = 0;
762 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
763 if ( (*it)->isLinked() ) {
764 if ( index == count )
765 return *it;
766 ++count;
767 }
768 }
769 }
770 else {
771 if ( index < sAllImages.size() )
772 return sAllImages[index];
773 }
774 return NULL;
775 }
776
777 ImageLoader* findImageByMachHeader(const struct mach_header* target)
778 {
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 )
783 return anImage;
784 }
785 return NULL;
786 }
787
788
789 ImageLoader* findImageContainingAddress(const void* addr)
790 {
791 #if FIND_STATS
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);
797 #endif
798 // first look in image where last address was found rdar://problem/3685517
799 if ( (sLastImageByAddressCache != NULL) && sLastImageByAddressCache->containsAddress(addr) ) {
800 #if FIND_STATS
801 ++cacheHit;
802 #endif
803 return sLastImageByAddressCache;
804 }
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;
812 #if FIND_STATS
813 ++cacheMiss;
814 #endif
815 return anImage;
816 }
817 }
818 #if FIND_STATS
819 ++cacheNotMacho;
820 #endif
821 return NULL;
822 }
823
824
825 void forEachImageDo( void (*callback)(ImageLoader*, void* userData), void* userData)
826 {
827 const unsigned int imageCount = sAllImages.size();
828 for(unsigned int i=0; i < imageCount; ++i) {
829 ImageLoader* anImage = sAllImages[i];
830 (*callback)(anImage, userData);
831 }
832 }
833
834 ImageLoader* findLoadedImage(const struct stat& stat_buf)
835 {
836 const unsigned int imageCount = sAllImages.size();
837 for(unsigned int i=0; i < imageCount; ++i){
838 ImageLoader* anImage = sAllImages[i];
839 if ( anImage->statMatch(stat_buf) )
840 return anImage;
841 }
842 return NULL;
843 }
844
845 // based on ANSI-C strstr()
846 static const char* strrstr(const char* str, const char* sub)
847 {
848 const int sublen = strlen(sub);
849 for(const char* p = &str[strlen(str)]; p != str; --p) {
850 if ( strncmp(p, sub, sublen) == 0 )
851 return p;
852 }
853 return NULL;
854 }
855
856
857 //
858 // Find framework path
859 //
860 // /path/foo.framework/foo => foo.framework/foo
861 // /path/foo.framework/Versions/A/foo => foo.framework/Versions/A/foo
862 // /path/foo.framework/Frameworks/bar.framework/bar => bar.framework/bar
863 // /path/foo.framework/Libraries/bar.dylb => NULL
864 // /path/foo.framework/bar => NULL
865 //
866 // Returns NULL if not a framework path
867 //
868 static const char* getFrameworkPartialPath(const char* path)
869 {
870 const char* dirDot = strrstr(path, ".framework/");
871 if ( dirDot != NULL ) {
872 const char* dirStart = dirDot;
873 for ( ; dirStart >= path; --dirStart) {
874 if ( (*dirStart == '/') || (dirStart == path) ) {
875 const char* frameworkStart = &dirStart[1];
876 if ( dirStart == path )
877 --frameworkStart;
878 int len = dirDot - frameworkStart;
879 char framework[len+1];
880 strncpy(framework, frameworkStart, len);
881 framework[len] = '\0';
882 const char* leaf = strrchr(path, '/');
883 if ( leaf != NULL ) {
884 if ( strcmp(framework, &leaf[1]) == 0 ) {
885 return frameworkStart;
886 }
887 if ( gLinkContext.imageSuffix != NULL ) {
888 // some debug frameworks have install names that end in _debug
889 if ( strncmp(framework, &leaf[1], len) == 0 ) {
890 if ( strcmp( gLinkContext.imageSuffix, &leaf[len+1]) == 0 )
891 return frameworkStart;
892 }
893 }
894 }
895 }
896 }
897 }
898 return NULL;
899 }
900
901
902 static const char* getLibraryLeafName(const char* path)
903 {
904 const char* start = strrchr(path, '/');
905 if ( start != NULL )
906 return &start[1];
907 else
908 return path;
909 }
910
911
912
913 const cpu_subtype_t CPU_SUBTYPE_END_OF_LIST = -1;
914
915
916 //
917 // A fat file may contain multiple sub-images for the same CPU type.
918 // In that case, dyld picks which sub-image to use by scanning a table
919 // of preferred cpu-sub-types for the running cpu.
920 //
921 // There is one row in the table for each cpu-sub-type on which dyld might run.
922 // The first entry in a row is that cpu-sub-type. It is followed by all
923 // cpu-sub-types that can run on that cpu, if preferred order. Each row ends with
924 // a "SUBTYPE_ALL" (to denote that images written to run on any cpu-sub-type are usable),
925 // followed by one or more CPU_SUBTYPE_END_OF_LIST to pad out this row.
926 //
927
928
929 //
930 // 32-bit PowerPC sub-type lists
931 //
932 const int kPPC_RowCount = 4;
933 static const cpu_subtype_t kPPC32[kPPC_RowCount][6] = {
934 // G5 can run any code
935 { 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 },
936
937 // G4 can run all but G5 code
938 { 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 },
939 { 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 },
940
941 // G3 cannot run G4 or G5 code
942 { 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 }
943 };
944
945
946 //
947 // 64-bit PowerPC sub-type lists
948 //
949 const int kPPC64_RowCount = 1;
950 static const cpu_subtype_t kPPC64[kPPC64_RowCount][3] = {
951 // G5 can run any 64-bit code
952 { CPU_SUBTYPE_POWERPC_970, CPU_SUBTYPE_POWERPC_ALL, CPU_SUBTYPE_END_OF_LIST },
953 };
954
955
956
957 //
958 // 32-bit x86 sub-type lists
959 //
960 // TO-DO
961
962
963
964 // scan the tables above to find the cpu-sub-type-list for this machine
965 static const cpu_subtype_t* findCPUSubtypeList(cpu_type_t cpu, cpu_subtype_t subtype)
966 {
967 switch (cpu) {
968 case CPU_TYPE_POWERPC:
969 for (int i=0; i < kPPC_RowCount ; ++i) {
970 if ( kPPC32[i][0] == subtype )
971 return kPPC32[i];
972 }
973 break;
974 case CPU_TYPE_POWERPC64:
975 for (int i=0; i < kPPC64_RowCount ; ++i) {
976 if ( kPPC64[i][0] == subtype )
977 return kPPC64[i];
978 }
979 break;
980 case CPU_TYPE_I386:
981 // To do
982 break;
983 }
984 return NULL;
985 }
986
987
988
989
990 // scan fat table-of-contents for best most preferred subtype
991 static bool fatFindBestFromOrderedList(cpu_type_t cpu, const cpu_subtype_t list[], const fat_header* fh, uint64_t* offset, uint64_t* len)
992 {
993 const fat_arch* const archs = (fat_arch*)(((char*)fh)+sizeof(fat_header));
994 for (uint32_t subTypeIndex=0; list[subTypeIndex] != CPU_SUBTYPE_END_OF_LIST; ++subTypeIndex) {
995 for(uint32_t fatIndex=0; fatIndex < OSSwapBigToHostInt32(fh->nfat_arch); ++fatIndex) {
996 if ( ((cpu_type_t)OSSwapBigToHostInt32(archs[fatIndex].cputype) == cpu)
997 && (list[subTypeIndex] == archs[fatIndex].cpusubtype) ) {
998 *offset = OSSwapBigToHostInt32(archs[fatIndex].offset);
999 *len = OSSwapBigToHostInt32(archs[fatIndex].size);
1000 return true;
1001 }
1002 }
1003 }
1004 return false;
1005 }
1006
1007 // scan fat table-of-contents for exact match of cpu and cpu-sub-type
1008 static bool fatFindExactMatch(cpu_type_t cpu, cpu_subtype_t subtype, const fat_header* fh, uint64_t* offset, uint64_t* len)
1009 {
1010 const fat_arch* archs = (fat_arch*)(((char*)fh)+sizeof(fat_header));
1011 for(uint32_t i=0; i < OSSwapBigToHostInt32(fh->nfat_arch); ++i) {
1012 if ( ((cpu_type_t)OSSwapBigToHostInt32(archs[i].cputype) == cpu)
1013 && ((cpu_subtype_t)OSSwapBigToHostInt32(archs[i].cpusubtype) == subtype) ) {
1014 *offset = OSSwapBigToHostInt32(archs[i].offset);
1015 *len = OSSwapBigToHostInt32(archs[i].size);
1016 return true;
1017 }
1018 }
1019 return false;
1020 }
1021
1022 // scan fat table-of-contents for image with matching cpu-type and runs-on-all-sub-types
1023 static bool fatFindRunsOnAllCPUs(cpu_type_t cpu, const fat_header* fh, uint64_t* offset, uint64_t* len)
1024 {
1025 const fat_arch* archs = (fat_arch*)(((char*)fh)+sizeof(fat_header));
1026 for(uint32_t i=0; i < OSSwapBigToHostInt32(fh->nfat_arch); ++i) {
1027 if ( (cpu_type_t)OSSwapBigToHostInt32(archs[i].cputype) == cpu) {
1028 switch (cpu) {
1029 case CPU_TYPE_POWERPC:
1030 case CPU_TYPE_POWERPC64:
1031 if ( (cpu_subtype_t)OSSwapBigToHostInt32(archs[i].cpusubtype) == CPU_SUBTYPE_POWERPC_ALL ) {
1032 *offset = OSSwapBigToHostInt32(archs[i].offset);
1033 *len = OSSwapBigToHostInt32(archs[i].size);
1034 return true;
1035 }
1036 break;
1037 case CPU_TYPE_I386:
1038 if ( (cpu_subtype_t)OSSwapBigToHostInt32(archs[i].cpusubtype) == CPU_SUBTYPE_I386_ALL ) {
1039 *offset = OSSwapBigToHostInt32(archs[i].offset);
1040 *len = OSSwapBigToHostInt32(archs[i].size);
1041 return true;
1042 }
1043 break;
1044 }
1045 }
1046 }
1047 return false;
1048 }
1049
1050
1051 //
1052 // A fat file may contain multiple sub-images for the same cpu-type,
1053 // each optimized for a different cpu-sub-type (e.g G3 or G5).
1054 // This routine picks the optimal sub-image.
1055 //
1056 static bool fatFindBest(const fat_header* fh, uint64_t* offset, uint64_t* len)
1057 {
1058 // assume all dylibs loaded must have same cpu type as main executable
1059 const cpu_type_t cpu = sMainExecutableMachHeader->cputype;
1060
1061 // We only know the subtype to use if the main executable cpu type matches the host
1062 if ( (cpu & CPU_TYPE_MASK) == sHostCPU ) {
1063 // get preference ordered list of subtypes
1064 const cpu_subtype_t* subTypePreferenceList = findCPUSubtypeList(cpu, sHostCPUsubtype);
1065
1066 // use ordered list to find best sub-image in fat file
1067 if ( subTypePreferenceList != NULL )
1068 return fatFindBestFromOrderedList(cpu, subTypePreferenceList, fh, offset, len);
1069
1070 // if running cpu is not in list, try for an exact match
1071 if ( fatFindExactMatch(cpu, sHostCPUsubtype, fh, offset, len) )
1072 return true;
1073 }
1074
1075 // running on an uknown cpu, can only load generic code
1076 return fatFindRunsOnAllCPUs(cpu, fh, offset, len);
1077 }
1078
1079
1080
1081 //
1082 // This is used to validate if a non-fat (aka thin or raw) mach-o file can be used
1083 // on the current processor. It is deemed compatible if any of the following are true:
1084 // 1) mach_header subtype is in list of compatible subtypes for running processor
1085 // 2) mach_header subtype is same as running processor subtype
1086 // 3) mach_header subtype runs on all processor variants
1087 //
1088 //
1089 bool isCompatibleMachO(const uint8_t* firstPage)
1090 {
1091 const mach_header* mh = (mach_header*)firstPage;
1092 if ( mh->magic == sMainExecutableMachHeader->magic ) {
1093 if ( mh->cputype == sMainExecutableMachHeader->cputype ) {
1094 if ( (mh->cputype & CPU_TYPE_MASK) == sHostCPU ) {
1095 // get preference ordered list of subtypes that this machine can use
1096 const cpu_subtype_t* subTypePreferenceList = findCPUSubtypeList(mh->cputype, sHostCPUsubtype);
1097 if ( subTypePreferenceList != NULL ) {
1098 // if image's subtype is in the list, it is compatible
1099 for (const cpu_subtype_t* p = subTypePreferenceList; *p != CPU_SUBTYPE_END_OF_LIST; ++p) {
1100 if ( *p == mh->cpusubtype )
1101 return true;
1102 }
1103 // have list and not in list, so not compatible
1104 throw "incompatible cpu-subtype";
1105 }
1106 // unknown cpu sub-type, but if exact match for current subtype then ok to use
1107 if ( mh->cpusubtype == sHostCPUsubtype )
1108 return true;
1109 }
1110
1111 // cpu unknown, so don't know if subtype is compatible
1112 // only load _ALL variant
1113 switch (mh->cputype) {
1114 case CPU_TYPE_POWERPC:
1115 case CPU_TYPE_POWERPC64:
1116 if ( mh->cpusubtype == CPU_SUBTYPE_POWERPC_ALL )
1117 return true;
1118 break;
1119 case CPU_TYPE_I386:
1120 if ( mh->cpusubtype == CPU_SUBTYPE_I386_ALL )
1121 return true;
1122 break;
1123 }
1124 }
1125 }
1126 return false;
1127 }
1128
1129
1130 // The kernel maps in main executable before dyld gets control. We need to
1131 // make an ImageLoader* for the already mapped in main executable.
1132 static ImageLoader* instantiateFromLoadedImage(const struct mach_header* mh, const char* path)
1133 {
1134 // try mach-o loader
1135 if ( isCompatibleMachO((const uint8_t*)mh) ) {
1136 ImageLoader* image = new ImageLoaderMachO(path, mh, 0, gLinkContext);
1137 addImage(image);
1138 return image;
1139 }
1140
1141 return NULL;
1142 }
1143
1144
1145
1146
1147 // map in file and instantiate an ImageLoader
1148 static ImageLoader* loadPhase6(int fd, struct stat& stat_buf, const char* path, const LoadContext& context)
1149 {
1150 //fprintf(stderr, "%s(%s)\n", __func__ , path);
1151 uint64_t fileOffset = 0;
1152 uint64_t fileLength = stat_buf.st_size;
1153 #if __ppc64__
1154 if ( *((uint32_t*)((char*)(&stat_buf)+0x60)) == 0xFEFEFEFE )
1155 fileLength = *((uint64_t*)((char*)(&stat_buf)+0x30)); // HACK work around for kernel stat bug rdar://problem/3845883
1156 #endif
1157
1158 // validate it is a file (not directory)
1159 if ( (stat_buf.st_mode & S_IFMT) != S_IFREG )
1160 throw "not a file";
1161
1162 // min file is 4K
1163 if ( fileLength < 4096 ) {
1164 throw "file to short";
1165 }
1166
1167 uint8_t firstPage[4096];
1168 pread(fd, firstPage, 4096,0);
1169
1170 // if fat wrapper, find usable sub-file
1171 const fat_header* fileStartAsFat = (fat_header*)firstPage;
1172 if ( fileStartAsFat->magic == OSSwapBigToHostInt32(FAT_MAGIC) ) {
1173 if ( fatFindBest(fileStartAsFat, &fileOffset, &fileLength) ) {
1174 pread(fd, firstPage, 4096, fileOffset);
1175 }
1176 else {
1177 throw "no matching architecture in universal wrapper";
1178 }
1179 }
1180
1181 // try mach-o loader
1182 if ( isCompatibleMachO(firstPage) ) {
1183 char realFilePath[PATH_MAX];
1184 if ( gLinkContext.slideAndPackDylibs ) {
1185 // when prebinding, we always want to track the real path of images
1186 if ( realpath(path, realFilePath) != NULL )
1187 path = realFilePath;
1188 }
1189
1190 // instantiate an image
1191 ImageLoader* image = new ImageLoaderMachO(path, fd, firstPage, fileOffset, fileLength, stat_buf, gLinkContext);
1192
1193 // now sanity check that this loaded image does not have the same install path as any existing image
1194 const char* loadedImageInstallPath = image->getInstallPath();
1195 if ( image->isDylib() && (loadedImageInstallPath != NULL) && (loadedImageInstallPath[0] == '/') ) {
1196 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
1197 ImageLoader* anImage = *it;
1198 const char* installPath = anImage->getInstallPath();
1199 if ( installPath != NULL) {
1200 if ( strcmp(loadedImageInstallPath, installPath) == 0 ) {
1201 //fprintf(stderr, "duplicate(%s) => %p\n", installPath, anImage);
1202 delete image;
1203 return anImage;
1204 }
1205 }
1206 }
1207 }
1208
1209 // some API's restrict what they can load
1210 if ( context.mustBeBundle && !image->isBundle() )
1211 throw "not a bundle";
1212 if ( context.mustBeDylib && !image->isDylib() )
1213 throw "not a dylib";
1214
1215 // don't add bundles to global list, they can be loaded but not linked. When linked it will be added to list
1216 if ( ! image->isBundle() )
1217 addImage(image);
1218
1219 return image;
1220 }
1221
1222 // try other file formats...
1223
1224
1225 // throw error about what was found
1226 switch (*(uint32_t*)firstPage) {
1227 case MH_MAGIC:
1228 case MH_CIGAM:
1229 case MH_MAGIC_64:
1230 case MH_CIGAM_64:
1231 throw "mach-o, but wrong architecture";
1232 default:
1233 throwf("unknown file type, first eight bytes: 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X",
1234 firstPage[0], firstPage[1], firstPage[2], firstPage[3], firstPage[4], firstPage[5], firstPage[6],firstPage[7]);
1235 }
1236 }
1237
1238
1239 // try to open file
1240 static ImageLoader* loadPhase5open(const char* path, const LoadContext& context, std::vector<const char*>* exceptions)
1241 {
1242 //fprintf(stdout, "%s(%s)\n", __func__, path);
1243 ImageLoader* image = NULL;
1244
1245 // open file (automagically closed when this function exits)
1246 FileOpener file(path);
1247
1248 //fprintf(stderr, "open(%s) => %d\n", path, file.getFileDescriptor() );
1249
1250 if ( file.getFileDescriptor() == -1 )
1251 return NULL;
1252
1253 struct stat stat_buf;
1254 #if __ppc64__
1255 memset(&stat_buf, 254, sizeof(struct stat)); // hack until rdar://problem/3845883 is fixed
1256 #endif
1257 if ( fstat(file.getFileDescriptor(), &stat_buf) == -1)
1258 throw "stat error";
1259
1260 // in case image was renamed or found via symlinks, check for inode match
1261 image = findLoadedImage(stat_buf);
1262 if ( image != NULL )
1263 return image;
1264
1265 // needed to implement NSADDIMAGE_OPTION_RETURN_ONLY_IF_LOADED
1266 if ( context.dontLoad )
1267 return NULL;
1268
1269 try {
1270 return loadPhase6(file.getFileDescriptor(), stat_buf, path, context);
1271 }
1272 catch (const char* msg) {
1273 char* newMsg = new char[strlen(msg) + strlen(path) + 8];
1274 sprintf(newMsg, "%s: %s", path, msg);
1275 exceptions->push_back(newMsg);
1276 return NULL;
1277 }
1278 }
1279
1280 // look for path match with existing loaded images
1281 static ImageLoader* loadPhase5check(const char* path, const LoadContext& context)
1282 {
1283 //fprintf(stderr, "%s(%s)\n", __func__ , path);
1284 // search path against load-path and install-path of all already loaded images
1285 uint32_t hash = ImageLoader::hash(path);
1286 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
1287 ImageLoader* anImage = *it;
1288 // check has first to cut down on strcmp calls
1289 if ( anImage->getPathHash() == hash )
1290 if ( strcmp(path, anImage->getPath()) == 0 ) {
1291 // if we are looking for a dylib don't return something else
1292 if ( !context.mustBeDylib || anImage->isDylib() )
1293 return anImage;
1294 }
1295 if ( context.matchByInstallName || anImage->matchInstallPath() ) {
1296 const char* installPath = anImage->getInstallPath();
1297 if ( installPath != NULL) {
1298 if ( strcmp(path, installPath) == 0 ) {
1299 // if we are looking for a dylib don't return something else
1300 if ( !context.mustBeDylib || anImage->isDylib() )
1301 return anImage;
1302 }
1303 }
1304 }
1305 }
1306
1307 //fprintf(stderr, "check(%s) => NULL\n", path);
1308 return NULL;
1309 }
1310
1311
1312 // open or check existing
1313 static ImageLoader* loadPhase5(const char* path, const LoadContext& context, std::vector<const char*>* exceptions)
1314 {
1315 //fprintf(stderr, "%s(%s)\n", __func__ , path);
1316 if ( exceptions != NULL )
1317 return loadPhase5open(path, context, exceptions);
1318 else
1319 return loadPhase5check(path, context);
1320 }
1321
1322 // try with and without image suffix
1323 static ImageLoader* loadPhase4(const char* path, const LoadContext& context, std::vector<const char*>* exceptions)
1324 {
1325 //fprintf(stderr, "%s(%s)\n", __func__ , path);
1326 ImageLoader* image = NULL;
1327 if ( gLinkContext.imageSuffix != NULL ) {
1328 char pathWithSuffix[strlen(path)+strlen( gLinkContext.imageSuffix)+2];
1329 ImageLoader::addSuffix(path, gLinkContext.imageSuffix, pathWithSuffix);
1330 image = loadPhase5(pathWithSuffix, context, exceptions);
1331 }
1332 if ( image == NULL )
1333 image = loadPhase5(path, context, exceptions);
1334 return image;
1335 }
1336
1337
1338 // expand @ variables
1339 static ImageLoader* loadPhase3(const char* path, const LoadContext& context, std::vector<const char*>* exceptions)
1340 {
1341 //fprintf(stderr, "%s(%s)\n", __func__ , path);
1342 ImageLoader* image = NULL;
1343 if ( strncmp(path, "@executable_path/", 17) == 0 ) {
1344 // handle @executable_path path prefix
1345 const char* executablePath = sExecPath;
1346 char newPath[strlen(executablePath) + strlen(path)];
1347 strcpy(newPath, executablePath);
1348 char* addPoint = strrchr(newPath,'/');
1349 if ( addPoint != NULL )
1350 strcpy(&addPoint[1], &path[17]);
1351 else
1352 strcpy(newPath, &path[17]);
1353 image = loadPhase4(newPath, context, exceptions);
1354 if ( image != NULL )
1355 return image;
1356
1357 // perhaps main executable path is a sym link, find realpath and retry
1358 char resolvedPath[PATH_MAX];
1359 if ( realpath(sExecPath, resolvedPath) != NULL ) {
1360 char newRealPath[strlen(resolvedPath) + strlen(path)];
1361 strcpy(newRealPath, resolvedPath);
1362 char* addPoint = strrchr(newRealPath,'/');
1363 if ( addPoint != NULL )
1364 strcpy(&addPoint[1], &path[17]);
1365 else
1366 strcpy(newRealPath, &path[17]);
1367 image = loadPhase4(newRealPath, context, exceptions);
1368 if ( image != NULL )
1369 return image;
1370 }
1371 }
1372 else if ( (strncmp(path, "@loader_path/", 13) == 0) && (context.origin != NULL) ) {
1373 // handle @loader_path path prefix
1374 char newPath[strlen(context.origin) + strlen(path)];
1375 strcpy(newPath, context.origin);
1376 char* addPoint = strrchr(newPath,'/');
1377 if ( addPoint != NULL )
1378 strcpy(&addPoint[1], &path[13]);
1379 else
1380 strcpy(newPath, &path[13]);
1381 image = loadPhase4(newPath, context, exceptions);
1382 if ( image != NULL )
1383 return image;
1384
1385 // perhaps loader path is a sym link, find realpath and retry
1386 char resolvedPath[PATH_MAX];
1387 if ( realpath(context.origin, resolvedPath) != NULL ) {
1388 char newRealPath[strlen(resolvedPath) + strlen(path)];
1389 strcpy(newRealPath, resolvedPath);
1390 char* addPoint = strrchr(newRealPath,'/');
1391 if ( addPoint != NULL )
1392 strcpy(&addPoint[1], &path[13]);
1393 else
1394 strcpy(newRealPath, &path[13]);
1395 image = loadPhase4(newRealPath, context, exceptions);
1396 if ( image != NULL )
1397 return image;
1398 }
1399 }
1400
1401 return loadPhase4(path, context, exceptions);
1402 }
1403
1404
1405 // try search paths
1406 static ImageLoader* loadPhase2(const char* path, const LoadContext& context,
1407 const char* const frameworkPaths[], const char* const libraryPaths[],
1408 std::vector<const char*>* exceptions)
1409 {
1410 //fprintf(stderr, "%s(%s)\n", __func__ , path);
1411 ImageLoader* image = NULL;
1412 const char* frameworkPartialPath = getFrameworkPartialPath(path);
1413 if ( frameworkPaths != NULL ) {
1414 if ( frameworkPartialPath != NULL ) {
1415 const int frameworkPartialPathLen = strlen(frameworkPartialPath);
1416 for(const char* const* fp = frameworkPaths; *fp != NULL; ++fp) {
1417 char npath[strlen(*fp)+frameworkPartialPathLen+8];
1418 strcpy(npath, *fp);
1419 strcat(npath, "/");
1420 strcat(npath, frameworkPartialPath);
1421 //fprintf(stderr, "dyld: fallback framework path used: %s() -> loadPhase4(\"%s\", ...)\n", __func__, npath);
1422 image = loadPhase4(npath, context, exceptions);
1423 if ( image != NULL )
1424 return image;
1425 }
1426 }
1427 }
1428 if ( libraryPaths != NULL ) {
1429 const char* libraryLeafName = getLibraryLeafName(path);
1430 const int libraryLeafNameLen = strlen(libraryLeafName);
1431 for(const char* const* lp = libraryPaths; *lp != NULL; ++lp) {
1432 char libpath[strlen(*lp)+libraryLeafNameLen+8];
1433 strcpy(libpath, *lp);
1434 strcat(libpath, "/");
1435 strcat(libpath, libraryLeafName);
1436 //fprintf(stderr, "dyld: fallback library path used: %s() -> loadPhase4(\"%s\", ...)\n", __func__, libpath);
1437 image = loadPhase4(libpath, context, exceptions);
1438 if ( image != NULL )
1439 return image;
1440 }
1441 }
1442 return NULL;
1443 }
1444
1445 // try search overrides and fallbacks
1446 static ImageLoader* loadPhase1(const char* path, const LoadContext& context, std::vector<const char*>* exceptions)
1447 {
1448 //fprintf(stderr, "%s(%s)\n", __func__ , path);
1449 ImageLoader* image = NULL;
1450
1451 // handle LD_LIBRARY_PATH environment variables that force searching
1452 if ( context.useLdLibraryPath && (sEnv.LD_LIBRARY_PATH != NULL) ) {
1453 image = loadPhase2(path, context, NULL, sEnv.LD_LIBRARY_PATH, exceptions);
1454 if ( image != NULL )
1455 return image;
1456 }
1457
1458 // handle DYLD_ environment variables that force searching
1459 if ( context.useSearchPaths && ((sEnv.DYLD_FRAMEWORK_PATH != NULL) || (sEnv.DYLD_LIBRARY_PATH != NULL)) ) {
1460 image = loadPhase2(path, context, sEnv.DYLD_FRAMEWORK_PATH, sEnv.DYLD_LIBRARY_PATH, exceptions);
1461 if ( image != NULL )
1462 return image;
1463 }
1464
1465 // try raw path
1466 image = loadPhase3(path, context, exceptions);
1467 if ( image != NULL )
1468 return image;
1469
1470 // try fallback paths during second time (will open file)
1471 if ( (exceptions != NULL) && ((sEnv.DYLD_FALLBACK_FRAMEWORK_PATH != NULL) || (sEnv.DYLD_FALLBACK_LIBRARY_PATH != NULL)) ) {
1472 image = loadPhase2(path, context, sEnv.DYLD_FALLBACK_FRAMEWORK_PATH, sEnv.DYLD_FALLBACK_LIBRARY_PATH, exceptions);
1473 if ( image != NULL )
1474 return image;
1475 }
1476
1477 return NULL;
1478 }
1479
1480 // try root substitutions
1481 static ImageLoader* loadPhase0(const char* path, const LoadContext& context, std::vector<const char*>* exceptions)
1482 {
1483 //fprintf(stderr, "%s(%s)\n", __func__ , path);
1484
1485 // handle DYLD_ROOT_PATH which forces absolute paths to use a new root
1486 if ( (sEnv.DYLD_ROOT_PATH != NULL) && (path[0] == '/') ) {
1487 for(const char* const* rootPath = sEnv.DYLD_ROOT_PATH ; *rootPath != NULL; ++rootPath) {
1488 char newPath[strlen(*rootPath) + strlen(path)+2];
1489 strcpy(newPath, *rootPath);
1490 strcat(newPath, path);
1491 ImageLoader* image = loadPhase1(newPath, context, exceptions);
1492 if ( image != NULL )
1493 return image;
1494 }
1495 }
1496
1497 // try raw path
1498 return loadPhase1(path, context, exceptions);
1499 }
1500
1501 //
1502 // Given all the DYLD_ environment variables, the general case for loading libraries
1503 // is that any given path expands into a list of possible locations to load. We
1504 // also must take care to ensure two copies of the "same" library are never loaded.
1505 //
1506 // The algorithm used here is that there is a separate function for each "phase" of the
1507 // path expansion. Each phase function calls the next phase with each possible expansion
1508 // of that phase. The result is the last phase is called with all possible paths.
1509 //
1510 // To catch duplicates the algorithm is run twice. The first time, the last phase checks
1511 // the path against all loaded images. The second time, the last phase calls open() on
1512 // the path. Either time, if an image is found, the phases all unwind without checking
1513 // for other paths.
1514 //
1515 ImageLoader* load(const char* path, const LoadContext& context)
1516 {
1517 //fprintf(stderr, "%s(%s)\n", __func__ , path);
1518 char realPath[PATH_MAX];
1519 // when DYLD_IMAGE_SUFFIX is in used, do a realpath(), otherwise a load of "Foo.framework/Foo" will not match
1520 if ( context.useSearchPaths && ( gLinkContext.imageSuffix != NULL) ) {
1521 if ( realpath(path, realPath) != NULL )
1522 path = realPath;
1523 }
1524
1525 // try all path permutations and check against existing loaded images
1526 ImageLoader* image = loadPhase0(path, context, NULL);
1527 if ( image != NULL )
1528 return image;
1529
1530 // try all path permutations and try open() until first sucesss
1531 std::vector<const char*> exceptions;
1532 image = loadPhase0(path, context, &exceptions);
1533 if ( image != NULL )
1534 return image;
1535 else if ( context.dontLoad )
1536 return NULL;
1537 else if ( exceptions.size() == 0 )
1538 throw "image not found";
1539 else {
1540 const char* msgStart = "no suitable image found. Did find:";
1541 const char* delim = "\n\t";
1542 size_t allsizes = strlen(msgStart)+8;
1543 for (unsigned int i=0; i < exceptions.size(); ++i)
1544 allsizes += (strlen(exceptions[i]) + strlen(delim));
1545 char* fullMsg = new char[allsizes];
1546 strcpy(fullMsg, msgStart);
1547 for (unsigned int i=0; i < exceptions.size(); ++i) {
1548 strcat(fullMsg, delim);
1549 strcat(fullMsg, exceptions[i]);
1550 }
1551 throw (const char*)fullMsg;
1552 }
1553 }
1554
1555
1556
1557
1558 // create when NSLinkModule is called for a second time on a bundle
1559 ImageLoader* cloneImage(ImageLoader* image)
1560 {
1561 const uint64_t offsetInFat = image->getOffsetInFatFile();
1562
1563 // open file (automagically closed when this function exits)
1564 FileOpener file(image->getPath());
1565
1566 struct stat stat_buf;
1567 #if __ppc64__
1568 memset(&stat_buf, 254, sizeof(struct stat)); // hack until rdar://problem/3845883 is fixed
1569 #endif
1570 if ( fstat(file.getFileDescriptor(), &stat_buf) == -1)
1571 throw "stat error";
1572
1573 // read first page of file
1574 uint8_t firstPage[4096];
1575 pread(file.getFileDescriptor(), firstPage, 4096, offsetInFat);
1576
1577 // fat length is only used for sanity checking, since this image was already loaded once, just use upper bound
1578 uint64_t lenInFat = stat_buf.st_size - offsetInFat;
1579
1580 // try mach-o loader
1581 if ( isCompatibleMachO(firstPage) ) {
1582 ImageLoader* clone = new ImageLoaderMachO(image->getPath(), file.getFileDescriptor(), firstPage, offsetInFat, lenInFat, stat_buf, gLinkContext);
1583 // don't add bundles to global list, they can be loaded but not linked. When linked it will be added to list
1584 if ( ! image->isBundle() )
1585 addImage(clone);
1586 return clone;
1587 }
1588
1589 // try other file formats...
1590 throw "can't clone image";
1591 }
1592
1593
1594 ImageLoader* loadFromMemory(const uint8_t* mem, uint64_t len, const char* moduleName)
1595 {
1596 // if fat wrapper, find usable sub-file
1597 const fat_header* memStartAsFat = (fat_header*)mem;
1598 uint64_t fileOffset = 0;
1599 uint64_t fileLength = len;
1600 if ( memStartAsFat->magic == OSSwapBigToHostInt32(FAT_MAGIC) ) {
1601 if ( fatFindBest(memStartAsFat, &fileOffset, &fileLength) ) {
1602 mem = &mem[fileOffset];
1603 len = fileLength;
1604 }
1605 else {
1606 throw "no matching architecture in universal wrapper";
1607 }
1608 }
1609
1610 // try mach-o each loader
1611 if ( isCompatibleMachO(mem) ) {
1612 ImageLoader* image = new ImageLoaderMachO(moduleName, (mach_header*)mem, len, gLinkContext);
1613 // don't add bundles to global list, they can be loaded but not linked. When linked it will be added to list
1614 if ( ! image->isBundle() )
1615 addImage(image);
1616 return image;
1617 }
1618
1619 // try other file formats...
1620
1621 // throw error about what was found
1622 switch (*(uint32_t*)mem) {
1623 case MH_MAGIC:
1624 case MH_CIGAM:
1625 case MH_MAGIC_64:
1626 case MH_CIGAM_64:
1627 throw "mach-o, but wrong architecture";
1628 default:
1629 throwf("unknown file type, first eight bytes: 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X",
1630 mem[0], mem[1], mem[2], mem[3], mem[4], mem[5], mem[6],mem[7]);
1631 }
1632 }
1633
1634
1635 void registerAddCallback(ImageCallback func)
1636 {
1637 // now add to list to get notified when any more images are added
1638 sAddImageCallbacks.push_back(func);
1639
1640 // call callback with all existing images, starting at roots
1641 const int rootCount = sImageRoots.size();
1642 for(int i=0; i < rootCount; ++i) {
1643 ImageLoader* image = sImageRoots[i];
1644 image->runNotification(gLinkContext, sAddImageCallbacks.size());
1645 }
1646
1647 // for (std::vector<ImageLoader*>::iterator it=sImageRoots.begin(); it != sImageRoots.end(); it++) {
1648 // ImageLoader* image = *it;
1649 // image->runNotification(gLinkContext, sAddImageCallbacks.size());
1650 // }
1651 }
1652
1653 void registerRemoveCallback(ImageCallback func)
1654 {
1655 sRemoveImageCallbacks.push_back(func);
1656 }
1657
1658 void clearErrorMessage()
1659 {
1660 error_string[0] = '\0';
1661 }
1662
1663 void setErrorMessage(const char* message)
1664 {
1665 // save off error message in global buffer for CrashReporter to find
1666 strncpy(error_string, message, sizeof(error_string)-1);
1667 error_string[sizeof(error_string)-1] = '\0';
1668 }
1669
1670 const char* getErrorMessage()
1671 {
1672 return error_string;
1673 }
1674
1675 void halt(const char* message)
1676 {
1677 fprintf(stderr, "dyld: %s\n", message);
1678 setErrorMessage(message);
1679 strncpy(error_string, message, sizeof(error_string)-1);
1680 error_string[sizeof(error_string)-1] = '\0';
1681
1682 #if __ppc__ || __ppc64__
1683 __asm__ ("trap");
1684 #elif __i386__
1685 __asm__ ("int3");
1686 #else
1687 #error unknown architecture
1688 #endif
1689 abort(); // needed to suppress warning that noreturn function returns
1690 }
1691
1692
1693 uintptr_t bindLazySymbol(const mach_header* mh, uintptr_t* lazyPointer)
1694 {
1695 uintptr_t result = 0;
1696 // acquire read-lock on dyld's data structures
1697 #if 0 // rdar://problem/3811777 turn off locking until deadlock is resolved
1698 if ( gThreadHelpers != NULL )
1699 (*gThreadHelpers->lockForReading)();
1700 #endif
1701 // lookup and bind lazy pointer and get target address
1702 try {
1703 // note, target should always be mach-o, because only mach-o lazy handler wired up to this
1704 ImageLoader* target = dyld::findImageByMachHeader(mh);
1705 if ( target == NULL )
1706 throw "image not found for lazy pointer";
1707 result = target->doBindLazySymbol(lazyPointer, gLinkContext);
1708 }
1709 catch (const char* message) {
1710 fprintf(stderr, "dyld: lazy symbol binding failed: %s\n", message);
1711 halt(message);
1712 }
1713 // release read-lock on dyld's data structures
1714 #if 0
1715 if ( gThreadHelpers != NULL )
1716 (*gThreadHelpers->unlockForReading)();
1717 #endif
1718 // return target address to glue which jumps to it with real parameters restored
1719 return result;
1720 }
1721
1722
1723 // SPI used by ZeroLink to lazy load bundles
1724 void registerZeroLinkHandlers(BundleNotificationCallBack notify, BundleLocatorCallBack locate)
1725 {
1726 sBundleNotifier = notify;
1727 sBundleLocation = locate;
1728 }
1729
1730 void registerUndefinedHandler(UndefinedHandler handler)
1731 {
1732 sUndefinedHandler = handler;
1733 }
1734
1735 static void undefinedHandler(const char* symboName)
1736 {
1737 if ( sUndefinedHandler != NULL ) {
1738 (*sUndefinedHandler)(symboName);
1739 }
1740 }
1741
1742 static bool findExportedSymbol(const char* name, bool onlyInCoalesced, const ImageLoader::Symbol** sym, ImageLoader** image)
1743 {
1744 // try ZeroLink short cut to finding bundle which exports this symbol
1745 if ( sBundleLocation != NULL ) {
1746 ImageLoader* zlImage = (*sBundleLocation)(name);
1747 if ( zlImage == ((ImageLoader*)(-1)) ) {
1748 // -1 is magic value that request symbol is in a bundle not yet linked into process
1749 // try calling handler to link in that symbol
1750 undefinedHandler(name);
1751 // call locator again
1752 zlImage = (*sBundleLocation)(name);
1753 }
1754 // if still not found, then ZeroLink has no idea where to find it
1755 if ( zlImage == ((ImageLoader*)(-1)) )
1756 return false;
1757 if ( zlImage != NULL ) {
1758 // ZeroLink cache knows where the symbol is
1759 *sym = zlImage->findExportedSymbol(name, NULL, false, image);
1760 if ( *sym != NULL ) {
1761 *image = zlImage;
1762 return true;
1763 }
1764 }
1765 else {
1766 // ZeroLink says it is in some bundle already loaded, but not linked, walk them all
1767 const unsigned int imageCount = sAllImages.size();
1768 for(unsigned int i=0; i < imageCount; ++i){
1769 ImageLoader* anImage = sAllImages[i];
1770 if ( anImage->isBundle() && !anImage->hasHiddenExports() ) {
1771 //fprintf(stderr, "dyld: search for %s in %s\n", name, anImage->getPath());
1772 *sym = anImage->findExportedSymbol(name, NULL, false, image);
1773 if ( *sym != NULL ) {
1774 return true;
1775 }
1776 }
1777 }
1778 }
1779 }
1780
1781 // search all images in order
1782 ImageLoader* firstWeakImage = NULL;
1783 const ImageLoader::Symbol* firstWeakSym = NULL;
1784 const unsigned int imageCount = sAllImages.size();
1785 for(unsigned int i=0; i < imageCount; ++i){
1786 ImageLoader* anImage = sAllImages[i];
1787 if ( ! anImage->hasHiddenExports() && (!onlyInCoalesced || anImage->hasCoalescedExports()) ) {
1788 *sym = anImage->findExportedSymbol(name, NULL, false, image);
1789 if ( *sym != NULL ) {
1790 // if weak definition found, record first one found
1791 if ( ((*image)->getExportedSymbolInfo(*sym) & ImageLoader::kWeakDefinition) != 0 ) {
1792 if ( firstWeakImage == NULL ) {
1793 firstWeakImage = *image;
1794 firstWeakSym = *sym;
1795 }
1796 }
1797 else {
1798 // found non-weak, so immediately return with it
1799 return true;
1800 }
1801 }
1802 }
1803 }
1804 if ( firstWeakSym != NULL ) {
1805 // found a weak definition, but no non-weak, so return first weak found
1806 *sym = firstWeakSym;
1807 *image = firstWeakImage;
1808 return true;
1809 }
1810
1811 return false;
1812 }
1813
1814 bool flatFindExportedSymbol(const char* name, const ImageLoader::Symbol** sym, ImageLoader** image)
1815 {
1816 return findExportedSymbol(name, false, sym, image);
1817 }
1818
1819 bool findCoalescedExportedSymbol(const char* name, const ImageLoader::Symbol** sym, ImageLoader** image)
1820 {
1821 return findExportedSymbol(name, true, sym, image);
1822 }
1823
1824
1825 bool flatFindExportedSymbolWithHint(const char* name, const char* librarySubstring, const ImageLoader::Symbol** sym, ImageLoader** image)
1826 {
1827 // search all images in order
1828 const unsigned int imageCount = sAllImages.size();
1829 for(unsigned int i=0; i < imageCount; ++i){
1830 ImageLoader* anImage = sAllImages[i];
1831 // only look at images whose paths contain the hint string (NULL hint string is wildcard)
1832 if ( ! anImage->isBundle() && ((librarySubstring==NULL) || (strstr(anImage->getPath(), librarySubstring) != NULL)) ) {
1833 *sym = anImage->findExportedSymbol(name, NULL, false, image);
1834 if ( *sym != NULL ) {
1835 return true;
1836 }
1837 }
1838 }
1839 return false;
1840 }
1841
1842 static void getMappedRegions(ImageLoader::RegionsVector& regions)
1843 {
1844 const unsigned int imageCount = sAllImages.size();
1845 for(unsigned int i=0; i < imageCount; ++i){
1846 ImageLoader* anImage = sAllImages[i];
1847 anImage->addMappedRegions(regions);
1848 }
1849 }
1850
1851
1852 static ImageLoader* libraryLocator(const char* libraryName, bool search, const char* origin, const char* rpath[])
1853 {
1854 dyld::LoadContext context;
1855 context.useSearchPaths = search;
1856 context.useLdLibraryPath = false;
1857 context.dontLoad = false;
1858 context.mustBeBundle = false;
1859 context.mustBeDylib = true;
1860 context.matchByInstallName = false;
1861 context.origin = origin;
1862 context.rpath = rpath;
1863 return load(libraryName, context);
1864 }
1865
1866
1867 static void setContext(int argc, const char* argv[], const char* envp[], const char* apple[])
1868 {
1869 gLinkContext.loadLibrary = &libraryLocator;
1870 gLinkContext.imageNotification = &imageNotification;
1871 gLinkContext.terminationRecorder = &terminationRecorder;
1872 gLinkContext.flatExportFinder = &flatFindExportedSymbol;
1873 gLinkContext.coalescedExportFinder = &findCoalescedExportedSymbol;
1874 gLinkContext.undefinedHandler = &undefinedHandler;
1875 gLinkContext.addImageNeedingNotification = &addImageNeedingNotification;
1876 gLinkContext.notifyAdding = &notifyAdding;
1877 gLinkContext.getAllMappedRegions = &getMappedRegions;
1878 gLinkContext.bindingHandler = NULL;
1879 gLinkContext.bindingOptions = ImageLoader::kBindingNone;
1880 gLinkContext.mainExecutable = sMainExecutable;
1881 gLinkContext.argc = argc;
1882 gLinkContext.argv = argv;
1883 gLinkContext.envp = envp;
1884 gLinkContext.apple = apple;
1885 }
1886
1887 static bool checkEmulation()
1888 {
1889 #if __i386__
1890 int mib[] = { CTL_KERN, KERN_CLASSIC, getpid() };
1891 int is_classic = 0;
1892 size_t len = sizeof(int);
1893 int ret = sysctl(mib, 3, &is_classic, &len, NULL, 0);
1894 if ((ret != -1) && is_classic) {
1895 // When a 32-bit ppc program is run under emulation on an Intel processor,
1896 // we want any i386 dylibs (e.g. the emulator) to not load in the shared region
1897 // because the shared region is being used by ppc dylibs
1898 gLinkContext.sharedRegionMode = ImageLoader::kDontUseSharedRegion;
1899 return true;
1900 }
1901 #endif
1902 return false;
1903 }
1904
1905 void link(ImageLoader* image, ImageLoader::BindingLaziness bindness, ImageLoader::InitializerRunning runInitializers)
1906 {
1907 // add to list of known images. This did not happen at creation time for bundles
1908 if ( image->isBundle() )
1909 addImage(image);
1910
1911 // we detect root images as those not linked in yet
1912 if ( !image->isLinked() )
1913 addRootImage(image);
1914
1915 // notify ZeroLink of new image with concat of logical and physical name
1916 if ( sBundleNotifier != NULL && image->isBundle() ) {
1917 const int logicalLen = strlen(image->getLogicalPath());
1918 char logAndPhys[strlen(image->getPath())+logicalLen+2];
1919 strcpy(logAndPhys, image->getLogicalPath());
1920 strcpy(&logAndPhys[logicalLen+1], image->getPath());
1921 (*sBundleNotifier)(logAndPhys, image);
1922 }
1923
1924 // process images
1925 try {
1926 image->link(gLinkContext, bindness, runInitializers, sAddImageCallbacks.size());
1927 }
1928 catch (const char* msg) {
1929 sAllImagesMightContainUnlinkedImages = true;
1930 throw msg;
1931 }
1932
1933 #if OLD_GDB_DYLD_INTERFACE
1934 // notify gdb that loaded libraries have changed
1935 gdb_dyld_state_changed();
1936 #endif
1937 }
1938
1939
1940 //
1941 // Entry point for dyld. The kernel loads dyld and jumps to __dyld_start which
1942 // sets up some registers and call this function.
1943 //
1944 // Returns address of main() in target program which __dyld_start jumps to
1945 //
1946 uintptr_t
1947 _main(const struct mach_header* mainExecutableMH, int argc, const char* argv[], const char* envp[], const char* apple[])
1948 {
1949 // Pickup the pointer to the exec path.
1950 sExecPath = apple[0];
1951 if ( sExecPath[0] != '/' ) {
1952 // have relative path, use cwd to make absolute
1953 char cwdbuff[MAXPATHLEN];
1954 if ( getcwd(cwdbuff, MAXPATHLEN) != NULL ) {
1955 // maybe use static buffer to avoid calling malloc so early...
1956 char* s = new char[strlen(cwdbuff) + strlen(sExecPath) + 2];
1957 strcpy(s, cwdbuff);
1958 strcat(s, "/");
1959 strcat(s, sExecPath);
1960 sExecPath = s;
1961 }
1962 }
1963 uintptr_t result = 0;
1964 sMainExecutableMachHeader = mainExecutableMH;
1965 bool isEmulated = checkEmulation();
1966 checkEnvironmentVariables(envp, isEmulated);
1967 if ( sEnv.DYLD_PRINT_OPTS )
1968 printOptions(argv);
1969 if ( sEnv.DYLD_PRINT_ENV )
1970 printEnvironmentVariables(envp);
1971 getHostInfo();
1972 setContext(argc, argv, envp, apple);
1973 ImageLoader::BindingLaziness bindness = sEnv.DYLD_BIND_AT_LAUNCH ? ImageLoader::kLazyAndNonLazy : ImageLoader::kNonLazyOnly;
1974
1975 // load any inserted libraries before loading the main executable so that they are first in flat namespace
1976 int insertLibrariesCount = 0;
1977 if ( sEnv.DYLD_INSERT_LIBRARIES != NULL ) {
1978 for (const char* const* lib = sEnv.DYLD_INSERT_LIBRARIES; *lib != NULL; ++lib) {
1979 insertLibrariesCount++;
1980 }
1981 }
1982 ImageLoader* insertedImages[insertLibrariesCount];
1983 if ( insertLibrariesCount > 0 ) {
1984 for (int i=0; i < insertLibrariesCount; ++i) {
1985 try {
1986 LoadContext context;
1987 context.useSearchPaths = false;
1988 context.useLdLibraryPath = false;
1989 context.dontLoad = false;
1990 context.mustBeBundle = false;
1991 context.mustBeDylib = true;
1992 context.matchByInstallName = false;
1993 context.origin = NULL; // can't use @loader_path with DYLD_INSERT_LIBRARIES
1994 context.rpath = NULL;
1995 insertedImages[i] = load(sEnv.DYLD_INSERT_LIBRARIES[i], context);
1996 }
1997 catch (...) {
1998 char buf[strlen(sEnv.DYLD_INSERT_LIBRARIES[i])+50];
1999 sprintf(buf, "could not load inserted library: %s\n", sEnv.DYLD_INSERT_LIBRARIES[i]);
2000 insertedImages[i] = NULL;
2001 halt(buf);
2002 }
2003 }
2004 }
2005
2006 // load and link main executable
2007 try {
2008 sMainExecutable = instantiateFromLoadedImage(mainExecutableMH, sExecPath);
2009 gLinkContext.mainExecutable = sMainExecutable;
2010 if ( sMainExecutable->forceFlat() ) {
2011 gLinkContext.bindFlat = true;
2012 gLinkContext.prebindUsage = ImageLoader::kUseNoPrebinding;
2013 }
2014 link(sMainExecutable, bindness, ImageLoader::kDontRunInitializers);
2015 result = (uintptr_t)sMainExecutable->getMain();
2016 }
2017 catch(const char* message) {
2018 halt(message);
2019 }
2020 catch(...) {
2021 fprintf(stderr, "dyld: launch failed\n");
2022 }
2023
2024 // Link in any inserted libraries.
2025 // Do this after link main executable so any extra libraries pulled in by inserted libraries are at end of flat namespace
2026 if ( insertLibrariesCount > 0 ) {
2027 for (int i=0; i < insertLibrariesCount; ++i) {
2028 try {
2029 if ( insertedImages[i] != NULL )
2030 link(insertedImages[i], bindness, ImageLoader::kDontRunInitializers);
2031 }
2032 catch (const char* message) {
2033 char buf[strlen(sEnv.DYLD_INSERT_LIBRARIES[i])+50+strlen(message)];
2034 sprintf(buf, "could not link inserted library: %s\n%s\n", sEnv.DYLD_INSERT_LIBRARIES[i], message);
2035 halt(buf);
2036 }
2037 }
2038 }
2039
2040 return result;
2041 }
2042
2043
2044
2045
2046 }; // namespace
2047
2048
2049