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