dyld-45.1.tar.gz
[apple/dyld.git] / src / dyld.cpp
1 /* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*-
2 *
3 * Copyright (c) 2004-2006 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 // if in termination list, pull it out and run terminator
245 for (std::vector<ImageLoader*>::iterator it=sImageFilesNeedingTermination.begin(); it != sImageFilesNeedingTermination.end(); it++) {
246 if ( *it == image ) {
247 sImageFilesNeedingTermination.erase(it);
248 image->doTermination(gLinkContext);
249 break;
250 }
251 }
252
253 // tell all register add image handlers about this
254 // do this before removing image from internal data structures so that the callback can querey dyld about the image
255 for (std::vector<ImageCallback>::iterator it=sRemoveImageCallbacks.begin(); it != sRemoveImageCallbacks.end(); it++) {
256 (*it)(image->machHeader(), image->getSlide());
257 }
258
259 // tell all interested images
260 for (std::vector<ImageLoader*>::iterator it=sImagesToNotifyAboutOtherImages.begin(); it != sImagesToNotifyAboutOtherImages.end(); it++) {
261 dyld_image_info info;
262 info.imageLoadAddress = image->machHeader();
263 info.imageFilePath = image->getPath();
264 info.imageFileModDate = image->lastModified();
265 (*it)->doNotification(dyld_image_removing, 1, &info);
266 }
267
268 // remove from master list
269 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
270 if ( *it == image ) {
271 sAllImages.erase(it);
272 break;
273 }
274 }
275
276 // flush find-by-address cache
277 if ( sLastImageByAddressCache == image )
278 sLastImageByAddressCache = NULL;
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
657 static void checkEnvironmentVariables(const char* envp[], bool ignoreEnviron)
658 {
659 const char* home = NULL;
660 const char** p;
661 for(p = envp; *p != NULL; p++) {
662 const char* keyEqualsValue = *p;
663 if ( strncmp(keyEqualsValue, "DYLD_", 5) == 0 ) {
664 const char* equals = strchr(keyEqualsValue, '=');
665 if ( (equals != NULL) && !ignoreEnviron ) {
666 const char* value = &equals[1];
667 const int keyLen = equals-keyEqualsValue;
668 char key[keyLen+1];
669 strncpy(key, keyEqualsValue, keyLen);
670 key[keyLen] = '\0';
671 processDyldEnvironmentVarible(key, value);
672 }
673 }
674 else if ( strncmp(keyEqualsValue, "HOME=", 5) == 0 ) {
675 home = &keyEqualsValue[5];
676 }
677 else if ( strncmp(keyEqualsValue, "LD_LIBRARY_PATH=", 16) == 0 ) {
678 const char* path = &keyEqualsValue[16];
679 if ( !disableIfBadUser((char*)path) )
680 sEnv.LD_LIBRARY_PATH = parseColonList(path);
681 }
682 }
683
684 // default value for DYLD_FALLBACK_FRAMEWORK_PATH, if not set in environment
685 if ( sEnv.DYLD_FALLBACK_FRAMEWORK_PATH == NULL ) {
686 const char** paths = sFrameworkFallbackPaths;
687 if ( home == NULL )
688 removePathWithPrefix(paths, "$HOME");
689 else
690 paths_expand_roots(paths, "$HOME", home);
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 removePathWithPrefix(paths, "$HOME");
699 else
700 paths_expand_roots(paths, "$HOME", home);
701 sEnv.DYLD_FALLBACK_LIBRARY_PATH = paths;
702 }
703 }
704
705
706 static void getHostInfo()
707 {
708 #if 0
709 struct host_basic_info info;
710 mach_msg_type_number_t count = HOST_BASIC_INFO_COUNT;
711 mach_port_t hostPort = mach_host_self();
712 kern_return_t result = host_info(hostPort, HOST_BASIC_INFO, (host_info_t)&info, &count);
713 mach_port_deallocate(mach_task_self(), hostPort);
714 if ( result != KERN_SUCCESS )
715 throw "host_info() failed";
716
717 sHostCPU = info.cpu_type;
718 sHostCPUsubtype = info.cpu_subtype;
719 #endif
720
721 size_t valSize = sizeof(sHostCPU);
722 if (sysctlbyname ("hw.cputype", &sHostCPU, &valSize, NULL, 0) != 0)
723 throw "sysctlbyname(hw.cputype) failed";
724 valSize = sizeof(sHostCPUsubtype);
725 if (sysctlbyname ("hw.cpusubtype", &sHostCPUsubtype, &valSize, NULL, 0) != 0)
726 throw "sysctlbyname(hw.cpusubtype) failed";
727 }
728
729 bool validImage(ImageLoader* possibleImage)
730 {
731 const unsigned int imageCount = sAllImages.size();
732 for(unsigned int i=0; i < imageCount; ++i) {
733 if ( possibleImage == sAllImages[i] ) {
734 return true;
735 }
736 }
737 return false;
738 }
739
740 uint32_t getImageCount()
741 {
742 if ( sAllImagesMightContainUnlinkedImages ) {
743 uint32_t count = 0;
744 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
745 if ( (*it)->isLinked() )
746 ++count;
747 }
748 return count;
749 }
750 else {
751 return sAllImages.size();
752 }
753 }
754
755 ImageLoader* getIndexedImage(unsigned int index)
756 {
757 if ( sAllImagesMightContainUnlinkedImages ) {
758 uint32_t count = 0;
759 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
760 if ( (*it)->isLinked() ) {
761 if ( index == count )
762 return *it;
763 ++count;
764 }
765 }
766 }
767 else {
768 if ( index < sAllImages.size() )
769 return sAllImages[index];
770 }
771 return NULL;
772 }
773
774 ImageLoader* findImageByMachHeader(const struct mach_header* target)
775 {
776 const unsigned int imageCount = sAllImages.size();
777 for(unsigned int i=0; i < imageCount; ++i) {
778 ImageLoader* anImage = sAllImages[i];
779 if ( anImage->machHeader() == target )
780 return anImage;
781 }
782 return NULL;
783 }
784
785
786 ImageLoader* findImageContainingAddress(const void* addr)
787 {
788 #if FIND_STATS
789 static int cacheHit = 0;
790 static int cacheMiss = 0;
791 static int cacheNotMacho = 0;
792 if ( ((cacheHit+cacheMiss+cacheNotMacho) % 100) == 0 )
793 fprintf(stderr, "findImageContainingAddress(): cache hit = %d, miss = %d, unknown = %d\n", cacheHit, cacheMiss, cacheNotMacho);
794 #endif
795 // first look in image where last address was found rdar://problem/3685517
796 if ( (sLastImageByAddressCache != NULL) && sLastImageByAddressCache->containsAddress(addr) ) {
797 #if FIND_STATS
798 ++cacheHit;
799 #endif
800 return sLastImageByAddressCache;
801 }
802 // do exhastive search
803 // todo: consider maintaining a list sorted by address ranges and do a binary search on that
804 const unsigned int imageCount = sAllImages.size();
805 for(unsigned int i=0; i < imageCount; ++i) {
806 ImageLoader* anImage = sAllImages[i];
807 if ( anImage->containsAddress(addr) ) {
808 sLastImageByAddressCache = anImage;
809 #if FIND_STATS
810 ++cacheMiss;
811 #endif
812 return anImage;
813 }
814 }
815 #if FIND_STATS
816 ++cacheNotMacho;
817 #endif
818 return NULL;
819 }
820
821 ImageLoader* findImageContainingAddressThreadSafe(const void* addr)
822 {
823 // do exhastive search
824 // todo: consider maintaining a list sorted by address ranges and do a binary search on that
825 const unsigned int imageCount = sAllImages.size();
826 for(unsigned int i=0; i < imageCount; ++i) {
827 ImageLoader* anImage = sAllImages[i];
828 if ( anImage->containsAddress(addr) ) {
829 return anImage;
830 }
831 }
832 return NULL;
833 }
834
835
836 void forEachImageDo( void (*callback)(ImageLoader*, void* userData), void* userData)
837 {
838 const unsigned int imageCount = sAllImages.size();
839 for(unsigned int i=0; i < imageCount; ++i) {
840 ImageLoader* anImage = sAllImages[i];
841 (*callback)(anImage, userData);
842 }
843 }
844
845 ImageLoader* findLoadedImage(const struct stat& stat_buf)
846 {
847 const unsigned int imageCount = sAllImages.size();
848 for(unsigned int i=0; i < imageCount; ++i){
849 ImageLoader* anImage = sAllImages[i];
850 if ( anImage->statMatch(stat_buf) )
851 return anImage;
852 }
853 return NULL;
854 }
855
856 // based on ANSI-C strstr()
857 static const char* strrstr(const char* str, const char* sub)
858 {
859 const int sublen = strlen(sub);
860 for(const char* p = &str[strlen(str)]; p != str; --p) {
861 if ( strncmp(p, sub, sublen) == 0 )
862 return p;
863 }
864 return NULL;
865 }
866
867
868 //
869 // Find framework path
870 //
871 // /path/foo.framework/foo => foo.framework/foo
872 // /path/foo.framework/Versions/A/foo => foo.framework/Versions/A/foo
873 // /path/foo.framework/Frameworks/bar.framework/bar => bar.framework/bar
874 // /path/foo.framework/Libraries/bar.dylb => NULL
875 // /path/foo.framework/bar => NULL
876 //
877 // Returns NULL if not a framework path
878 //
879 static const char* getFrameworkPartialPath(const char* path)
880 {
881 const char* dirDot = strrstr(path, ".framework/");
882 if ( dirDot != NULL ) {
883 const char* dirStart = dirDot;
884 for ( ; dirStart >= path; --dirStart) {
885 if ( (*dirStart == '/') || (dirStart == path) ) {
886 const char* frameworkStart = &dirStart[1];
887 if ( dirStart == path )
888 --frameworkStart;
889 int len = dirDot - frameworkStart;
890 char framework[len+1];
891 strncpy(framework, frameworkStart, len);
892 framework[len] = '\0';
893 const char* leaf = strrchr(path, '/');
894 if ( leaf != NULL ) {
895 if ( strcmp(framework, &leaf[1]) == 0 ) {
896 return frameworkStart;
897 }
898 if ( gLinkContext.imageSuffix != NULL ) {
899 // some debug frameworks have install names that end in _debug
900 if ( strncmp(framework, &leaf[1], len) == 0 ) {
901 if ( strcmp( gLinkContext.imageSuffix, &leaf[len+1]) == 0 )
902 return frameworkStart;
903 }
904 }
905 }
906 }
907 }
908 }
909 return NULL;
910 }
911
912
913 static const char* getLibraryLeafName(const char* path)
914 {
915 const char* start = strrchr(path, '/');
916 if ( start != NULL )
917 return &start[1];
918 else
919 return path;
920 }
921
922
923
924 const cpu_subtype_t CPU_SUBTYPE_END_OF_LIST = -1;
925
926
927 //
928 // A fat file may contain multiple sub-images for the same CPU type.
929 // In that case, dyld picks which sub-image to use by scanning a table
930 // of preferred cpu-sub-types for the running cpu.
931 //
932 // There is one row in the table for each cpu-sub-type on which dyld might run.
933 // The first entry in a row is that cpu-sub-type. It is followed by all
934 // cpu-sub-types that can run on that cpu, if preferred order. Each row ends with
935 // a "SUBTYPE_ALL" (to denote that images written to run on any cpu-sub-type are usable),
936 // followed by one or more CPU_SUBTYPE_END_OF_LIST to pad out this row.
937 //
938
939
940 //
941 // 32-bit PowerPC sub-type lists
942 //
943 const int kPPC_RowCount = 4;
944 static const cpu_subtype_t kPPC32[kPPC_RowCount][6] = {
945 // G5 can run any code
946 { 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 },
947
948 // G4 can run all but G5 code
949 { 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 },
950 { 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 },
951
952 // G3 cannot run G4 or G5 code
953 { 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 }
954 };
955
956
957 //
958 // 64-bit PowerPC sub-type lists
959 //
960 const int kPPC64_RowCount = 1;
961 static const cpu_subtype_t kPPC64[kPPC64_RowCount][3] = {
962 // G5 can run any 64-bit code
963 { CPU_SUBTYPE_POWERPC_970, CPU_SUBTYPE_POWERPC_ALL, CPU_SUBTYPE_END_OF_LIST },
964 };
965
966
967
968 //
969 // 32-bit x86 sub-type lists
970 //
971 // TO-DO
972
973
974
975 // scan the tables above to find the cpu-sub-type-list for this machine
976 static const cpu_subtype_t* findCPUSubtypeList(cpu_type_t cpu, cpu_subtype_t subtype)
977 {
978 switch (cpu) {
979 case CPU_TYPE_POWERPC:
980 for (int i=0; i < kPPC_RowCount ; ++i) {
981 if ( kPPC32[i][0] == subtype )
982 return kPPC32[i];
983 }
984 break;
985 case CPU_TYPE_POWERPC64:
986 for (int i=0; i < kPPC64_RowCount ; ++i) {
987 if ( kPPC64[i][0] == subtype )
988 return kPPC64[i];
989 }
990 break;
991 case CPU_TYPE_I386:
992 // To do
993 break;
994 }
995 return NULL;
996 }
997
998
999
1000
1001 // scan fat table-of-contents for best most preferred subtype
1002 static bool fatFindBestFromOrderedList(cpu_type_t cpu, const cpu_subtype_t list[], const fat_header* fh, uint64_t* offset, uint64_t* len)
1003 {
1004 const fat_arch* const archs = (fat_arch*)(((char*)fh)+sizeof(fat_header));
1005 for (uint32_t subTypeIndex=0; list[subTypeIndex] != CPU_SUBTYPE_END_OF_LIST; ++subTypeIndex) {
1006 for(uint32_t fatIndex=0; fatIndex < OSSwapBigToHostInt32(fh->nfat_arch); ++fatIndex) {
1007 if ( ((cpu_type_t)OSSwapBigToHostInt32(archs[fatIndex].cputype) == cpu)
1008 && (list[subTypeIndex] == archs[fatIndex].cpusubtype) ) {
1009 *offset = OSSwapBigToHostInt32(archs[fatIndex].offset);
1010 *len = OSSwapBigToHostInt32(archs[fatIndex].size);
1011 return true;
1012 }
1013 }
1014 }
1015 return false;
1016 }
1017
1018 // scan fat table-of-contents for exact match of cpu and cpu-sub-type
1019 static bool fatFindExactMatch(cpu_type_t cpu, cpu_subtype_t subtype, const fat_header* fh, uint64_t* offset, uint64_t* len)
1020 {
1021 const fat_arch* archs = (fat_arch*)(((char*)fh)+sizeof(fat_header));
1022 for(uint32_t i=0; i < OSSwapBigToHostInt32(fh->nfat_arch); ++i) {
1023 if ( ((cpu_type_t)OSSwapBigToHostInt32(archs[i].cputype) == cpu)
1024 && ((cpu_subtype_t)OSSwapBigToHostInt32(archs[i].cpusubtype) == subtype) ) {
1025 *offset = OSSwapBigToHostInt32(archs[i].offset);
1026 *len = OSSwapBigToHostInt32(archs[i].size);
1027 return true;
1028 }
1029 }
1030 return false;
1031 }
1032
1033 // scan fat table-of-contents for image with matching cpu-type and runs-on-all-sub-types
1034 static bool fatFindRunsOnAllCPUs(cpu_type_t cpu, const fat_header* fh, uint64_t* offset, uint64_t* len)
1035 {
1036 const fat_arch* archs = (fat_arch*)(((char*)fh)+sizeof(fat_header));
1037 for(uint32_t i=0; i < OSSwapBigToHostInt32(fh->nfat_arch); ++i) {
1038 if ( (cpu_type_t)OSSwapBigToHostInt32(archs[i].cputype) == cpu) {
1039 switch (cpu) {
1040 case CPU_TYPE_POWERPC:
1041 case CPU_TYPE_POWERPC64:
1042 if ( (cpu_subtype_t)OSSwapBigToHostInt32(archs[i].cpusubtype) == CPU_SUBTYPE_POWERPC_ALL ) {
1043 *offset = OSSwapBigToHostInt32(archs[i].offset);
1044 *len = OSSwapBigToHostInt32(archs[i].size);
1045 return true;
1046 }
1047 break;
1048 case CPU_TYPE_I386:
1049 if ( (cpu_subtype_t)OSSwapBigToHostInt32(archs[i].cpusubtype) == CPU_SUBTYPE_I386_ALL ) {
1050 *offset = OSSwapBigToHostInt32(archs[i].offset);
1051 *len = OSSwapBigToHostInt32(archs[i].size);
1052 return true;
1053 }
1054 break;
1055 }
1056 }
1057 }
1058 return false;
1059 }
1060
1061
1062 //
1063 // A fat file may contain multiple sub-images for the same cpu-type,
1064 // each optimized for a different cpu-sub-type (e.g G3 or G5).
1065 // This routine picks the optimal sub-image.
1066 //
1067 static bool fatFindBest(const fat_header* fh, uint64_t* offset, uint64_t* len)
1068 {
1069 // assume all dylibs loaded must have same cpu type as main executable
1070 const cpu_type_t cpu = sMainExecutableMachHeader->cputype;
1071
1072 // We only know the subtype to use if the main executable cpu type matches the host
1073 if ( (cpu & CPU_TYPE_MASK) == sHostCPU ) {
1074 // get preference ordered list of subtypes
1075 const cpu_subtype_t* subTypePreferenceList = findCPUSubtypeList(cpu, sHostCPUsubtype);
1076
1077 // use ordered list to find best sub-image in fat file
1078 if ( subTypePreferenceList != NULL )
1079 return fatFindBestFromOrderedList(cpu, subTypePreferenceList, fh, offset, len);
1080
1081 // if running cpu is not in list, try for an exact match
1082 if ( fatFindExactMatch(cpu, sHostCPUsubtype, fh, offset, len) )
1083 return true;
1084 }
1085
1086 // running on an uknown cpu, can only load generic code
1087 return fatFindRunsOnAllCPUs(cpu, fh, offset, len);
1088 }
1089
1090
1091
1092 //
1093 // This is used to validate if a non-fat (aka thin or raw) mach-o file can be used
1094 // on the current processor. It is deemed compatible if any of the following are true:
1095 // 1) mach_header subtype is in list of compatible subtypes for running processor
1096 // 2) mach_header subtype is same as running processor subtype
1097 // 3) mach_header subtype runs on all processor variants
1098 //
1099 //
1100 bool isCompatibleMachO(const uint8_t* firstPage)
1101 {
1102 const mach_header* mh = (mach_header*)firstPage;
1103 if ( mh->magic == sMainExecutableMachHeader->magic ) {
1104 if ( mh->cputype == sMainExecutableMachHeader->cputype ) {
1105 if ( (mh->cputype & CPU_TYPE_MASK) == sHostCPU ) {
1106 // get preference ordered list of subtypes that this machine can use
1107 const cpu_subtype_t* subTypePreferenceList = findCPUSubtypeList(mh->cputype, sHostCPUsubtype);
1108 if ( subTypePreferenceList != NULL ) {
1109 // if image's subtype is in the list, it is compatible
1110 for (const cpu_subtype_t* p = subTypePreferenceList; *p != CPU_SUBTYPE_END_OF_LIST; ++p) {
1111 if ( *p == mh->cpusubtype )
1112 return true;
1113 }
1114 // have list and not in list, so not compatible
1115 throw "incompatible cpu-subtype";
1116 }
1117 // unknown cpu sub-type, but if exact match for current subtype then ok to use
1118 if ( mh->cpusubtype == sHostCPUsubtype )
1119 return true;
1120 }
1121
1122 // cpu unknown, so don't know if subtype is compatible
1123 // only load _ALL variant
1124 switch (mh->cputype) {
1125 case CPU_TYPE_POWERPC:
1126 case CPU_TYPE_POWERPC64:
1127 if ( mh->cpusubtype == CPU_SUBTYPE_POWERPC_ALL )
1128 return true;
1129 break;
1130 case CPU_TYPE_I386:
1131 if ( mh->cpusubtype == CPU_SUBTYPE_I386_ALL )
1132 return true;
1133 break;
1134 }
1135 }
1136 }
1137 return false;
1138 }
1139
1140
1141 // The kernel maps in main executable before dyld gets control. We need to
1142 // make an ImageLoader* for the already mapped in main executable.
1143 static ImageLoader* instantiateFromLoadedImage(const struct mach_header* mh, const char* path)
1144 {
1145 // try mach-o loader
1146 if ( isCompatibleMachO((const uint8_t*)mh) ) {
1147 ImageLoader* image = new ImageLoaderMachO(path, mh, 0, gLinkContext);
1148 addImage(image);
1149 return image;
1150 }
1151
1152 throw "main executable not a known format";
1153 }
1154
1155
1156
1157
1158 // map in file and instantiate an ImageLoader
1159 static ImageLoader* loadPhase6(int fd, struct stat& stat_buf, const char* path, const LoadContext& context)
1160 {
1161 //fprintf(stderr, "%s(%s)\n", __func__ , path);
1162 uint64_t fileOffset = 0;
1163 uint64_t fileLength = stat_buf.st_size;
1164 #if __ppc64__
1165 if ( *((uint32_t*)((char*)(&stat_buf)+0x60)) == 0xFEFEFEFE )
1166 fileLength = *((uint64_t*)((char*)(&stat_buf)+0x30)); // HACK work around for kernel stat bug rdar://problem/3845883
1167 #endif
1168
1169 // validate it is a file (not directory)
1170 if ( (stat_buf.st_mode & S_IFMT) != S_IFREG )
1171 throw "not a file";
1172
1173 // min file is 4K
1174 if ( fileLength < 4096 ) {
1175 throw "file to short";
1176 }
1177
1178 uint8_t firstPage[4096];
1179 pread(fd, firstPage, 4096,0);
1180
1181 // if fat wrapper, find usable sub-file
1182 const fat_header* fileStartAsFat = (fat_header*)firstPage;
1183 if ( fileStartAsFat->magic == OSSwapBigToHostInt32(FAT_MAGIC) ) {
1184 if ( fatFindBest(fileStartAsFat, &fileOffset, &fileLength) ) {
1185 pread(fd, firstPage, 4096, fileOffset);
1186 }
1187 else {
1188 throw "no matching architecture in universal wrapper";
1189 }
1190 }
1191
1192 // try mach-o loader
1193 if ( isCompatibleMachO(firstPage) ) {
1194 char realFilePath[PATH_MAX];
1195 if ( gLinkContext.slideAndPackDylibs ) {
1196 // when prebinding, we always want to track the real path of images
1197 if ( realpath(path, realFilePath) != NULL )
1198 path = realFilePath;
1199 }
1200
1201 // instantiate an image
1202 ImageLoader* image = new ImageLoaderMachO(path, fd, firstPage, fileOffset, fileLength, stat_buf, gLinkContext);
1203
1204 // now sanity check that this loaded image does not have the same install path as any existing image
1205 const char* loadedImageInstallPath = image->getInstallPath();
1206 if ( image->isDylib() && (loadedImageInstallPath != NULL) && (loadedImageInstallPath[0] == '/') ) {
1207 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
1208 ImageLoader* anImage = *it;
1209 const char* installPath = anImage->getInstallPath();
1210 if ( installPath != NULL) {
1211 if ( strcmp(loadedImageInstallPath, installPath) == 0 ) {
1212 //fprintf(stderr, "duplicate(%s) => %p\n", installPath, anImage);
1213 delete image;
1214 return anImage;
1215 }
1216 }
1217 }
1218 }
1219
1220 // some API's restrict what they can load
1221 if ( context.mustBeBundle && !image->isBundle() )
1222 throw "not a bundle";
1223 if ( context.mustBeDylib && !image->isDylib() )
1224 throw "not a dylib";
1225
1226 // don't add bundles to global list, they can be loaded but not linked. When linked it will be added to list
1227 if ( ! image->isBundle() )
1228 addImage(image);
1229
1230 return image;
1231 }
1232
1233 // try other file formats...
1234
1235
1236 // throw error about what was found
1237 switch (*(uint32_t*)firstPage) {
1238 case MH_MAGIC:
1239 case MH_CIGAM:
1240 case MH_MAGIC_64:
1241 case MH_CIGAM_64:
1242 throw "mach-o, but wrong architecture";
1243 default:
1244 throwf("unknown file type, first eight bytes: 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X",
1245 firstPage[0], firstPage[1], firstPage[2], firstPage[3], firstPage[4], firstPage[5], firstPage[6],firstPage[7]);
1246 }
1247 }
1248
1249
1250 // try to open file
1251 static ImageLoader* loadPhase5open(const char* path, const LoadContext& context, std::vector<const char*>* exceptions)
1252 {
1253 //fprintf(stdout, "%s(%s)\n", __func__, path);
1254 ImageLoader* image = NULL;
1255
1256 // open file (automagically closed when this function exits)
1257 FileOpener file(path);
1258
1259 //fprintf(stderr, "open(%s) => %d\n", path, file.getFileDescriptor() );
1260
1261 if ( file.getFileDescriptor() == -1 )
1262 return NULL;
1263
1264 struct stat stat_buf;
1265 #if __ppc64__
1266 memset(&stat_buf, 254, sizeof(struct stat)); // hack until rdar://problem/3845883 is fixed
1267 #endif
1268 if ( fstat(file.getFileDescriptor(), &stat_buf) == -1)
1269 throw "stat error";
1270
1271 // in case image was renamed or found via symlinks, check for inode match
1272 image = findLoadedImage(stat_buf);
1273 if ( image != NULL )
1274 return image;
1275
1276 // needed to implement NSADDIMAGE_OPTION_RETURN_ONLY_IF_LOADED
1277 if ( context.dontLoad )
1278 return NULL;
1279
1280 try {
1281 return loadPhase6(file.getFileDescriptor(), stat_buf, path, context);
1282 }
1283 catch (const char* msg) {
1284 char* newMsg = new char[strlen(msg) + strlen(path) + 8];
1285 sprintf(newMsg, "%s: %s", path, msg);
1286 exceptions->push_back(newMsg);
1287 return NULL;
1288 }
1289 }
1290
1291 // look for path match with existing loaded images
1292 static ImageLoader* loadPhase5check(const char* path, const LoadContext& context)
1293 {
1294 //fprintf(stderr, "%s(%s)\n", __func__ , path);
1295 // search path against load-path and install-path of all already loaded images
1296 uint32_t hash = ImageLoader::hash(path);
1297 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
1298 ImageLoader* anImage = *it;
1299 // check has first to cut down on strcmp calls
1300 if ( anImage->getPathHash() == hash )
1301 if ( strcmp(path, anImage->getPath()) == 0 ) {
1302 // if we are looking for a dylib don't return something else
1303 if ( !context.mustBeDylib || anImage->isDylib() )
1304 return anImage;
1305 }
1306 if ( context.matchByInstallName || anImage->matchInstallPath() ) {
1307 const char* installPath = anImage->getInstallPath();
1308 if ( installPath != NULL) {
1309 if ( strcmp(path, installPath) == 0 ) {
1310 // if we are looking for a dylib don't return something else
1311 if ( !context.mustBeDylib || anImage->isDylib() )
1312 return anImage;
1313 }
1314 }
1315 }
1316 }
1317
1318 //fprintf(stderr, "check(%s) => NULL\n", path);
1319 return NULL;
1320 }
1321
1322
1323 // open or check existing
1324 static ImageLoader* loadPhase5(const char* path, const LoadContext& context, std::vector<const char*>* exceptions)
1325 {
1326 //fprintf(stderr, "%s(%s)\n", __func__ , path);
1327 if ( exceptions != NULL )
1328 return loadPhase5open(path, context, exceptions);
1329 else
1330 return loadPhase5check(path, context);
1331 }
1332
1333 // try with and without image suffix
1334 static ImageLoader* loadPhase4(const char* path, const LoadContext& context, std::vector<const char*>* exceptions)
1335 {
1336 //fprintf(stderr, "%s(%s)\n", __func__ , path);
1337 ImageLoader* image = NULL;
1338 if ( gLinkContext.imageSuffix != NULL ) {
1339 char pathWithSuffix[strlen(path)+strlen( gLinkContext.imageSuffix)+2];
1340 ImageLoader::addSuffix(path, gLinkContext.imageSuffix, pathWithSuffix);
1341 image = loadPhase5(pathWithSuffix, context, exceptions);
1342 }
1343 if ( image == NULL )
1344 image = loadPhase5(path, context, exceptions);
1345 return image;
1346 }
1347
1348
1349 // expand @ variables
1350 static ImageLoader* loadPhase3(const char* path, const LoadContext& context, std::vector<const char*>* exceptions)
1351 {
1352 //fprintf(stderr, "%s(%s)\n", __func__ , path);
1353 ImageLoader* image = NULL;
1354 if ( strncmp(path, "@executable_path/", 17) == 0 ) {
1355 // handle @executable_path path prefix
1356 const char* executablePath = sExecPath;
1357 char newPath[strlen(executablePath) + strlen(path)];
1358 strcpy(newPath, executablePath);
1359 char* addPoint = strrchr(newPath,'/');
1360 if ( addPoint != NULL )
1361 strcpy(&addPoint[1], &path[17]);
1362 else
1363 strcpy(newPath, &path[17]);
1364 image = loadPhase4(newPath, context, exceptions);
1365 if ( image != NULL )
1366 return image;
1367
1368 // perhaps main executable path is a sym link, find realpath and retry
1369 char resolvedPath[PATH_MAX];
1370 if ( realpath(sExecPath, resolvedPath) != NULL ) {
1371 char newRealPath[strlen(resolvedPath) + strlen(path)];
1372 strcpy(newRealPath, resolvedPath);
1373 char* addPoint = strrchr(newRealPath,'/');
1374 if ( addPoint != NULL )
1375 strcpy(&addPoint[1], &path[17]);
1376 else
1377 strcpy(newRealPath, &path[17]);
1378 image = loadPhase4(newRealPath, context, exceptions);
1379 if ( image != NULL )
1380 return image;
1381 }
1382 }
1383 else if ( (strncmp(path, "@loader_path/", 13) == 0) && (context.origin != NULL) ) {
1384 // handle @loader_path path prefix
1385 char newPath[strlen(context.origin) + strlen(path)];
1386 strcpy(newPath, context.origin);
1387 char* addPoint = strrchr(newPath,'/');
1388 if ( addPoint != NULL )
1389 strcpy(&addPoint[1], &path[13]);
1390 else
1391 strcpy(newPath, &path[13]);
1392 image = loadPhase4(newPath, context, exceptions);
1393 if ( image != NULL )
1394 return image;
1395
1396 // perhaps loader path is a sym link, find realpath and retry
1397 char resolvedPath[PATH_MAX];
1398 if ( realpath(context.origin, resolvedPath) != NULL ) {
1399 char newRealPath[strlen(resolvedPath) + strlen(path)];
1400 strcpy(newRealPath, resolvedPath);
1401 char* addPoint = strrchr(newRealPath,'/');
1402 if ( addPoint != NULL )
1403 strcpy(&addPoint[1], &path[13]);
1404 else
1405 strcpy(newRealPath, &path[13]);
1406 image = loadPhase4(newRealPath, context, exceptions);
1407 if ( image != NULL )
1408 return image;
1409 }
1410 }
1411
1412 return loadPhase4(path, context, exceptions);
1413 }
1414
1415
1416 // try search paths
1417 static ImageLoader* loadPhase2(const char* path, const LoadContext& context,
1418 const char* const frameworkPaths[], const char* const libraryPaths[],
1419 std::vector<const char*>* exceptions)
1420 {
1421 //fprintf(stderr, "%s(%s)\n", __func__ , path);
1422 ImageLoader* image = NULL;
1423 const char* frameworkPartialPath = getFrameworkPartialPath(path);
1424 if ( frameworkPaths != NULL ) {
1425 if ( frameworkPartialPath != NULL ) {
1426 const int frameworkPartialPathLen = strlen(frameworkPartialPath);
1427 for(const char* const* fp = frameworkPaths; *fp != NULL; ++fp) {
1428 char npath[strlen(*fp)+frameworkPartialPathLen+8];
1429 strcpy(npath, *fp);
1430 strcat(npath, "/");
1431 strcat(npath, frameworkPartialPath);
1432 //fprintf(stderr, "dyld: fallback framework path used: %s() -> loadPhase4(\"%s\", ...)\n", __func__, npath);
1433 image = loadPhase4(npath, context, exceptions);
1434 if ( image != NULL )
1435 return image;
1436 }
1437 }
1438 }
1439 if ( libraryPaths != NULL ) {
1440 const char* libraryLeafName = getLibraryLeafName(path);
1441 const int libraryLeafNameLen = strlen(libraryLeafName);
1442 for(const char* const* lp = libraryPaths; *lp != NULL; ++lp) {
1443 char libpath[strlen(*lp)+libraryLeafNameLen+8];
1444 strcpy(libpath, *lp);
1445 strcat(libpath, "/");
1446 strcat(libpath, libraryLeafName);
1447 //fprintf(stderr, "dyld: fallback library path used: %s() -> loadPhase4(\"%s\", ...)\n", __func__, libpath);
1448 image = loadPhase4(libpath, context, exceptions);
1449 if ( image != NULL )
1450 return image;
1451 }
1452 }
1453 return NULL;
1454 }
1455
1456 // try search overrides and fallbacks
1457 static ImageLoader* loadPhase1(const char* path, const LoadContext& context, std::vector<const char*>* exceptions)
1458 {
1459 //fprintf(stderr, "%s(%s)\n", __func__ , path);
1460 ImageLoader* image = NULL;
1461
1462 // handle LD_LIBRARY_PATH environment variables that force searching
1463 if ( context.useLdLibraryPath && (sEnv.LD_LIBRARY_PATH != NULL) ) {
1464 image = loadPhase2(path, context, NULL, sEnv.LD_LIBRARY_PATH, exceptions);
1465 if ( image != NULL )
1466 return image;
1467 }
1468
1469 // handle DYLD_ environment variables that force searching
1470 if ( context.useSearchPaths && ((sEnv.DYLD_FRAMEWORK_PATH != NULL) || (sEnv.DYLD_LIBRARY_PATH != NULL)) ) {
1471 image = loadPhase2(path, context, sEnv.DYLD_FRAMEWORK_PATH, sEnv.DYLD_LIBRARY_PATH, exceptions);
1472 if ( image != NULL )
1473 return image;
1474 }
1475
1476 // try raw path
1477 image = loadPhase3(path, context, exceptions);
1478 if ( image != NULL )
1479 return image;
1480
1481 // try fallback paths during second time (will open file)
1482 if ( (exceptions != NULL) && ((sEnv.DYLD_FALLBACK_FRAMEWORK_PATH != NULL) || (sEnv.DYLD_FALLBACK_LIBRARY_PATH != NULL)) ) {
1483 image = loadPhase2(path, context, sEnv.DYLD_FALLBACK_FRAMEWORK_PATH, sEnv.DYLD_FALLBACK_LIBRARY_PATH, exceptions);
1484 if ( image != NULL )
1485 return image;
1486 }
1487
1488 return NULL;
1489 }
1490
1491 // try root substitutions
1492 static ImageLoader* loadPhase0(const char* path, const LoadContext& context, std::vector<const char*>* exceptions)
1493 {
1494 //fprintf(stderr, "%s(%s)\n", __func__ , path);
1495
1496 // handle DYLD_ROOT_PATH which forces absolute paths to use a new root
1497 if ( (sEnv.DYLD_ROOT_PATH != NULL) && (path[0] == '/') ) {
1498 for(const char* const* rootPath = sEnv.DYLD_ROOT_PATH ; *rootPath != NULL; ++rootPath) {
1499 char newPath[strlen(*rootPath) + strlen(path)+2];
1500 strcpy(newPath, *rootPath);
1501 strcat(newPath, path);
1502 ImageLoader* image = loadPhase1(newPath, context, exceptions);
1503 if ( image != NULL )
1504 return image;
1505 }
1506 }
1507
1508 // try raw path
1509 return loadPhase1(path, context, exceptions);
1510 }
1511
1512 //
1513 // Given all the DYLD_ environment variables, the general case for loading libraries
1514 // is that any given path expands into a list of possible locations to load. We
1515 // also must take care to ensure two copies of the "same" library are never loaded.
1516 //
1517 // The algorithm used here is that there is a separate function for each "phase" of the
1518 // path expansion. Each phase function calls the next phase with each possible expansion
1519 // of that phase. The result is the last phase is called with all possible paths.
1520 //
1521 // To catch duplicates the algorithm is run twice. The first time, the last phase checks
1522 // the path against all loaded images. The second time, the last phase calls open() on
1523 // the path. Either time, if an image is found, the phases all unwind without checking
1524 // for other paths.
1525 //
1526 ImageLoader* load(const char* path, const LoadContext& context)
1527 {
1528 //fprintf(stderr, "%s(%s)\n", __func__ , path);
1529 char realPath[PATH_MAX];
1530 // when DYLD_IMAGE_SUFFIX is in used, do a realpath(), otherwise a load of "Foo.framework/Foo" will not match
1531 if ( context.useSearchPaths && ( gLinkContext.imageSuffix != NULL) ) {
1532 if ( realpath(path, realPath) != NULL )
1533 path = realPath;
1534 }
1535
1536 // try all path permutations and check against existing loaded images
1537 ImageLoader* image = loadPhase0(path, context, NULL);
1538 if ( image != NULL )
1539 return image;
1540
1541 // try all path permutations and try open() until first sucesss
1542 std::vector<const char*> exceptions;
1543 image = loadPhase0(path, context, &exceptions);
1544 if ( image != NULL )
1545 return image;
1546 else if ( context.dontLoad )
1547 return NULL;
1548 else if ( exceptions.size() == 0 )
1549 throw "image not found";
1550 else {
1551 const char* msgStart = "no suitable image found. Did find:";
1552 const char* delim = "\n\t";
1553 size_t allsizes = strlen(msgStart)+8;
1554 for (unsigned int i=0; i < exceptions.size(); ++i)
1555 allsizes += (strlen(exceptions[i]) + strlen(delim));
1556 char* fullMsg = new char[allsizes];
1557 strcpy(fullMsg, msgStart);
1558 for (unsigned int i=0; i < exceptions.size(); ++i) {
1559 strcat(fullMsg, delim);
1560 strcat(fullMsg, exceptions[i]);
1561 }
1562 throw (const char*)fullMsg;
1563 }
1564 }
1565
1566
1567
1568
1569 // create when NSLinkModule is called for a second time on a bundle
1570 ImageLoader* cloneImage(ImageLoader* image)
1571 {
1572 const uint64_t offsetInFat = image->getOffsetInFatFile();
1573
1574 // open file (automagically closed when this function exits)
1575 FileOpener file(image->getPath());
1576
1577 struct stat stat_buf;
1578 #if __ppc64__
1579 memset(&stat_buf, 254, sizeof(struct stat)); // hack until rdar://problem/3845883 is fixed
1580 #endif
1581 if ( fstat(file.getFileDescriptor(), &stat_buf) == -1)
1582 throw "stat error";
1583
1584 // read first page of file
1585 uint8_t firstPage[4096];
1586 pread(file.getFileDescriptor(), firstPage, 4096, offsetInFat);
1587
1588 // fat length is only used for sanity checking, since this image was already loaded once, just use upper bound
1589 uint64_t lenInFat = stat_buf.st_size - offsetInFat;
1590
1591 // try mach-o loader
1592 if ( isCompatibleMachO(firstPage) ) {
1593 ImageLoader* clone = new ImageLoaderMachO(image->getPath(), file.getFileDescriptor(), firstPage, offsetInFat, lenInFat, stat_buf, gLinkContext);
1594 // don't add bundles to global list, they can be loaded but not linked. When linked it will be added to list
1595 if ( ! image->isBundle() )
1596 addImage(clone);
1597 return clone;
1598 }
1599
1600 // try other file formats...
1601 throw "can't clone image";
1602 }
1603
1604
1605 ImageLoader* loadFromMemory(const uint8_t* mem, uint64_t len, const char* moduleName)
1606 {
1607 // if fat wrapper, find usable sub-file
1608 const fat_header* memStartAsFat = (fat_header*)mem;
1609 uint64_t fileOffset = 0;
1610 uint64_t fileLength = len;
1611 if ( memStartAsFat->magic == OSSwapBigToHostInt32(FAT_MAGIC) ) {
1612 if ( fatFindBest(memStartAsFat, &fileOffset, &fileLength) ) {
1613 mem = &mem[fileOffset];
1614 len = fileLength;
1615 }
1616 else {
1617 throw "no matching architecture in universal wrapper";
1618 }
1619 }
1620
1621 // try mach-o each loader
1622 if ( isCompatibleMachO(mem) ) {
1623 ImageLoader* image = new ImageLoaderMachO(moduleName, (mach_header*)mem, len, gLinkContext);
1624 // don't add bundles to global list, they can be loaded but not linked. When linked it will be added to list
1625 if ( ! image->isBundle() )
1626 addImage(image);
1627 return image;
1628 }
1629
1630 // try other file formats...
1631
1632 // throw error about what was found
1633 switch (*(uint32_t*)mem) {
1634 case MH_MAGIC:
1635 case MH_CIGAM:
1636 case MH_MAGIC_64:
1637 case MH_CIGAM_64:
1638 throw "mach-o, but wrong architecture";
1639 default:
1640 throwf("unknown file type, first eight bytes: 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X",
1641 mem[0], mem[1], mem[2], mem[3], mem[4], mem[5], mem[6],mem[7]);
1642 }
1643 }
1644
1645
1646 void registerAddCallback(ImageCallback func)
1647 {
1648 // now add to list to get notified when any more images are added
1649 sAddImageCallbacks.push_back(func);
1650
1651 // call callback with all existing images, starting at roots
1652 const int rootCount = sImageRoots.size();
1653 for(int i=0; i < rootCount; ++i) {
1654 ImageLoader* image = sImageRoots[i];
1655 image->runNotification(gLinkContext, sAddImageCallbacks.size());
1656 }
1657
1658 // for (std::vector<ImageLoader*>::iterator it=sImageRoots.begin(); it != sImageRoots.end(); it++) {
1659 // ImageLoader* image = *it;
1660 // image->runNotification(gLinkContext, sAddImageCallbacks.size());
1661 // }
1662 }
1663
1664 void registerRemoveCallback(ImageCallback func)
1665 {
1666 sRemoveImageCallbacks.push_back(func);
1667 }
1668
1669 void clearErrorMessage()
1670 {
1671 error_string[0] = '\0';
1672 }
1673
1674 void setErrorMessage(const char* message)
1675 {
1676 // save off error message in global buffer for CrashReporter to find
1677 strncpy(error_string, message, sizeof(error_string)-1);
1678 error_string[sizeof(error_string)-1] = '\0';
1679 }
1680
1681 const char* getErrorMessage()
1682 {
1683 return error_string;
1684 }
1685
1686 void halt(const char* message)
1687 {
1688 fprintf(stderr, "dyld: %s\n", message);
1689 setErrorMessage(message);
1690 strncpy(error_string, message, sizeof(error_string)-1);
1691 error_string[sizeof(error_string)-1] = '\0';
1692
1693 #if __ppc__ || __ppc64__
1694 __asm__ ("trap");
1695 #elif __i386__
1696 __asm__ ("int3");
1697 #else
1698 #error unknown architecture
1699 #endif
1700 abort(); // needed to suppress warning that noreturn function returns
1701 }
1702
1703
1704 uintptr_t bindLazySymbol(const mach_header* mh, uintptr_t* lazyPointer)
1705 {
1706 uintptr_t result = 0;
1707 // acquire read-lock on dyld's data structures
1708 #if 0 // rdar://problem/3811777 turn off locking until deadlock is resolved
1709 if ( gThreadHelpers != NULL )
1710 (*gThreadHelpers->lockForReading)();
1711 #endif
1712 // lookup and bind lazy pointer and get target address
1713 try {
1714 ImageLoader* target;
1715 #if __i386__
1716 // fast stubs pass NULL for mh and image is instead found via the location of stub (aka lazyPointer)
1717 if ( mh == NULL )
1718 target = dyld::findImageContainingAddressThreadSafe(lazyPointer);
1719 else
1720 target = dyld::findImageByMachHeader(mh);
1721 #else
1722 // note, target should always be mach-o, because only mach-o lazy handler wired up to this
1723 target = dyld::findImageByMachHeader(mh);
1724 #endif
1725 if ( target == NULL )
1726 throw "image not found for lazy pointer";
1727 result = target->doBindLazySymbol(lazyPointer, gLinkContext);
1728 }
1729 catch (const char* message) {
1730 fprintf(stderr, "dyld: lazy symbol binding failed: %s\n", message);
1731 halt(message);
1732 }
1733 // release read-lock on dyld's data structures
1734 #if 0
1735 if ( gThreadHelpers != NULL )
1736 (*gThreadHelpers->unlockForReading)();
1737 #endif
1738 // return target address to glue which jumps to it with real parameters restored
1739 return result;
1740 }
1741
1742
1743 // SPI used by ZeroLink to lazy load bundles
1744 void registerZeroLinkHandlers(BundleNotificationCallBack notify, BundleLocatorCallBack locate)
1745 {
1746 sBundleNotifier = notify;
1747 sBundleLocation = locate;
1748 }
1749
1750 void registerUndefinedHandler(UndefinedHandler handler)
1751 {
1752 sUndefinedHandler = handler;
1753 }
1754
1755 static void undefinedHandler(const char* symboName)
1756 {
1757 if ( sUndefinedHandler != NULL ) {
1758 (*sUndefinedHandler)(symboName);
1759 }
1760 }
1761
1762 static bool findExportedSymbol(const char* name, bool onlyInCoalesced, const ImageLoader::Symbol** sym, ImageLoader** image)
1763 {
1764 // try ZeroLink short cut to finding bundle which exports this symbol
1765 if ( sBundleLocation != NULL ) {
1766 ImageLoader* zlImage = (*sBundleLocation)(name);
1767 if ( zlImage == ((ImageLoader*)(-1)) ) {
1768 // -1 is magic value that request symbol is in a bundle not yet linked into process
1769 // try calling handler to link in that symbol
1770 undefinedHandler(name);
1771 // call locator again
1772 zlImage = (*sBundleLocation)(name);
1773 }
1774 // if still not found, then ZeroLink has no idea where to find it
1775 if ( zlImage == ((ImageLoader*)(-1)) )
1776 return false;
1777 if ( zlImage != NULL ) {
1778 // ZeroLink cache knows where the symbol is
1779 *sym = zlImage->findExportedSymbol(name, NULL, false, image);
1780 if ( *sym != NULL ) {
1781 *image = zlImage;
1782 return true;
1783 }
1784 }
1785 else {
1786 // ZeroLink says it is in some bundle already loaded, but not linked, walk them all
1787 const unsigned int imageCount = sAllImages.size();
1788 for(unsigned int i=0; i < imageCount; ++i){
1789 ImageLoader* anImage = sAllImages[i];
1790 if ( anImage->isBundle() && !anImage->hasHiddenExports() ) {
1791 //fprintf(stderr, "dyld: search for %s in %s\n", name, anImage->getPath());
1792 *sym = anImage->findExportedSymbol(name, NULL, false, image);
1793 if ( *sym != NULL ) {
1794 return true;
1795 }
1796 }
1797 }
1798 }
1799 }
1800
1801 // search all images in order
1802 ImageLoader* firstWeakImage = NULL;
1803 const ImageLoader::Symbol* firstWeakSym = NULL;
1804 const unsigned int imageCount = sAllImages.size();
1805 for(unsigned int i=0; i < imageCount; ++i){
1806 ImageLoader* anImage = sAllImages[i];
1807 if ( ! anImage->hasHiddenExports() && (!onlyInCoalesced || anImage->hasCoalescedExports()) ) {
1808 *sym = anImage->findExportedSymbol(name, NULL, false, image);
1809 if ( *sym != NULL ) {
1810 // if weak definition found, record first one found
1811 if ( ((*image)->getExportedSymbolInfo(*sym) & ImageLoader::kWeakDefinition) != 0 ) {
1812 if ( firstWeakImage == NULL ) {
1813 firstWeakImage = *image;
1814 firstWeakSym = *sym;
1815 }
1816 }
1817 else {
1818 // found non-weak, so immediately return with it
1819 return true;
1820 }
1821 }
1822 }
1823 }
1824 if ( firstWeakSym != NULL ) {
1825 // found a weak definition, but no non-weak, so return first weak found
1826 *sym = firstWeakSym;
1827 *image = firstWeakImage;
1828 return true;
1829 }
1830
1831 return false;
1832 }
1833
1834 bool flatFindExportedSymbol(const char* name, const ImageLoader::Symbol** sym, ImageLoader** image)
1835 {
1836 return findExportedSymbol(name, false, sym, image);
1837 }
1838
1839 bool findCoalescedExportedSymbol(const char* name, const ImageLoader::Symbol** sym, ImageLoader** image)
1840 {
1841 return findExportedSymbol(name, true, sym, image);
1842 }
1843
1844
1845 bool flatFindExportedSymbolWithHint(const char* name, const char* librarySubstring, const ImageLoader::Symbol** sym, ImageLoader** image)
1846 {
1847 // search all images in order
1848 const unsigned int imageCount = sAllImages.size();
1849 for(unsigned int i=0; i < imageCount; ++i){
1850 ImageLoader* anImage = sAllImages[i];
1851 // only look at images whose paths contain the hint string (NULL hint string is wildcard)
1852 if ( ! anImage->isBundle() && ((librarySubstring==NULL) || (strstr(anImage->getPath(), librarySubstring) != NULL)) ) {
1853 *sym = anImage->findExportedSymbol(name, NULL, false, image);
1854 if ( *sym != NULL ) {
1855 return true;
1856 }
1857 }
1858 }
1859 return false;
1860 }
1861
1862 static void getMappedRegions(ImageLoader::RegionsVector& regions)
1863 {
1864 const unsigned int imageCount = sAllImages.size();
1865 for(unsigned int i=0; i < imageCount; ++i){
1866 ImageLoader* anImage = sAllImages[i];
1867 anImage->addMappedRegions(regions);
1868 }
1869 }
1870
1871
1872 static ImageLoader* libraryLocator(const char* libraryName, bool search, const char* origin, const char* rpath[])
1873 {
1874 dyld::LoadContext context;
1875 context.useSearchPaths = search;
1876 context.useLdLibraryPath = false;
1877 context.dontLoad = false;
1878 context.mustBeBundle = false;
1879 context.mustBeDylib = true;
1880 context.matchByInstallName = false;
1881 context.origin = origin;
1882 context.rpath = rpath;
1883 return load(libraryName, context);
1884 }
1885
1886
1887 static void setContext(int argc, const char* argv[], const char* envp[], const char* apple[])
1888 {
1889 gLinkContext.loadLibrary = &libraryLocator;
1890 gLinkContext.imageNotification = &imageNotification;
1891 gLinkContext.terminationRecorder = &terminationRecorder;
1892 gLinkContext.flatExportFinder = &flatFindExportedSymbol;
1893 gLinkContext.coalescedExportFinder = &findCoalescedExportedSymbol;
1894 gLinkContext.undefinedHandler = &undefinedHandler;
1895 gLinkContext.addImageNeedingNotification = &addImageNeedingNotification;
1896 gLinkContext.notifyAdding = &notifyAdding;
1897 gLinkContext.getAllMappedRegions = &getMappedRegions;
1898 gLinkContext.bindingHandler = NULL;
1899 gLinkContext.bindingOptions = ImageLoader::kBindingNone;
1900 gLinkContext.mainExecutable = sMainExecutable;
1901 gLinkContext.argc = argc;
1902 gLinkContext.argv = argv;
1903 gLinkContext.envp = envp;
1904 gLinkContext.apple = apple;
1905 }
1906
1907 static bool checkEmulation()
1908 {
1909 #if __i386__
1910 int mib[] = { CTL_KERN, KERN_CLASSIC, getpid() };
1911 int is_classic = 0;
1912 size_t len = sizeof(int);
1913 int ret = sysctl(mib, 3, &is_classic, &len, NULL, 0);
1914 if ((ret != -1) && is_classic) {
1915 // When a 32-bit ppc program is run under emulation on an Intel processor,
1916 // we want any i386 dylibs (e.g. the emulator) to not load in the shared region
1917 // because the shared region is being used by ppc dylibs
1918 gLinkContext.sharedRegionMode = ImageLoader::kDontUseSharedRegion;
1919 return true;
1920 }
1921 #endif
1922 return false;
1923 }
1924
1925 void link(ImageLoader* image, ImageLoader::BindingLaziness bindness, ImageLoader::InitializerRunning runInitializers)
1926 {
1927 // add to list of known images. This did not happen at creation time for bundles
1928 if ( image->isBundle() )
1929 addImage(image);
1930
1931 // we detect root images as those not linked in yet
1932 if ( !image->isLinked() )
1933 addRootImage(image);
1934
1935 // notify ZeroLink of new image with concat of logical and physical name
1936 if ( sBundleNotifier != NULL && image->isBundle() ) {
1937 const int logicalLen = strlen(image->getLogicalPath());
1938 char logAndPhys[strlen(image->getPath())+logicalLen+2];
1939 strcpy(logAndPhys, image->getLogicalPath());
1940 strcpy(&logAndPhys[logicalLen+1], image->getPath());
1941 (*sBundleNotifier)(logAndPhys, image);
1942 }
1943
1944 // process images
1945 try {
1946 image->link(gLinkContext, bindness, runInitializers, sAddImageCallbacks.size());
1947 }
1948 catch (const char* msg) {
1949 sAllImagesMightContainUnlinkedImages = true;
1950 throw msg;
1951 }
1952
1953 #if OLD_GDB_DYLD_INTERFACE
1954 // notify gdb that loaded libraries have changed
1955 gdb_dyld_state_changed();
1956 #endif
1957 }
1958
1959
1960 //
1961 // _pthread_keys is partitioned in a lower part that dyld will use; libSystem
1962 // will use the upper part. We set __pthread_tsd_first to 1 as the start of
1963 // the lower part. Libc will take #1 and c++ exceptions will take #2. There
1964 // is one free key=3 left.
1965 //
1966 extern "C" {
1967 extern int __pthread_tsd_first;
1968 }
1969
1970
1971 //
1972 // Entry point for dyld. The kernel loads dyld and jumps to __dyld_start which
1973 // sets up some registers and call this function.
1974 //
1975 // Returns address of main() in target program which __dyld_start jumps to
1976 //
1977 uintptr_t
1978 _main(const struct mach_header* mainExecutableMH, int argc, const char* argv[], const char* envp[], const char* apple[])
1979 {
1980 // set pthread keys to dyld range
1981 __pthread_tsd_first = 1;
1982
1983 bool isEmulated = checkEmulation();
1984 // Pickup the pointer to the exec path.
1985 sExecPath = apple[0];
1986 if (isEmulated) {
1987 // under Rosetta
1988 sExecPath = strdup(apple[0] + strlen(apple[0]) + 1);
1989 }
1990 if ( sExecPath[0] != '/' ) {
1991 // have relative path, use cwd to make absolute
1992 char cwdbuff[MAXPATHLEN];
1993 if ( getcwd(cwdbuff, MAXPATHLEN) != NULL ) {
1994 // maybe use static buffer to avoid calling malloc so early...
1995 char* s = new char[strlen(cwdbuff) + strlen(sExecPath) + 2];
1996 strcpy(s, cwdbuff);
1997 strcat(s, "/");
1998 strcat(s, sExecPath);
1999 sExecPath = s;
2000 }
2001 }
2002 uintptr_t result = 0;
2003 sMainExecutableMachHeader = mainExecutableMH;
2004 checkEnvironmentVariables(envp, isEmulated);
2005 if ( sEnv.DYLD_PRINT_OPTS )
2006 printOptions(argv);
2007 if ( sEnv.DYLD_PRINT_ENV )
2008 printEnvironmentVariables(envp);
2009 getHostInfo();
2010 setContext(argc, argv, envp, apple);
2011 ImageLoader::BindingLaziness bindness = sEnv.DYLD_BIND_AT_LAUNCH ? ImageLoader::kLazyAndNonLazy : ImageLoader::kNonLazyOnly;
2012
2013 // load any inserted libraries before loading the main executable so that they are first in flat namespace
2014 int insertLibrariesCount = 0;
2015 if ( sEnv.DYLD_INSERT_LIBRARIES != NULL ) {
2016 for (const char* const* lib = sEnv.DYLD_INSERT_LIBRARIES; *lib != NULL; ++lib) {
2017 insertLibrariesCount++;
2018 }
2019 }
2020 ImageLoader* insertedImages[insertLibrariesCount];
2021 if ( insertLibrariesCount > 0 ) {
2022 for (int i=0; i < insertLibrariesCount; ++i) {
2023 try {
2024 LoadContext context;
2025 context.useSearchPaths = false;
2026 context.useLdLibraryPath = false;
2027 context.dontLoad = false;
2028 context.mustBeBundle = false;
2029 context.mustBeDylib = true;
2030 context.matchByInstallName = false;
2031 context.origin = NULL; // can't use @loader_path with DYLD_INSERT_LIBRARIES
2032 context.rpath = NULL;
2033 insertedImages[i] = load(sEnv.DYLD_INSERT_LIBRARIES[i], context);
2034 }
2035 catch (...) {
2036 char buf[strlen(sEnv.DYLD_INSERT_LIBRARIES[i])+50];
2037 sprintf(buf, "could not load inserted library: %s\n", sEnv.DYLD_INSERT_LIBRARIES[i]);
2038 insertedImages[i] = NULL;
2039 halt(buf);
2040 }
2041 }
2042 }
2043
2044 // load and link main executable
2045 try {
2046 sMainExecutable = instantiateFromLoadedImage(mainExecutableMH, sExecPath);
2047 gLinkContext.mainExecutable = sMainExecutable;
2048 if ( sMainExecutable->forceFlat() ) {
2049 gLinkContext.bindFlat = true;
2050 gLinkContext.prebindUsage = ImageLoader::kUseNoPrebinding;
2051 }
2052 link(sMainExecutable, bindness, ImageLoader::kDontRunInitializers);
2053 result = (uintptr_t)sMainExecutable->getMain();
2054 }
2055 catch(const char* message) {
2056 halt(message);
2057 }
2058 catch(...) {
2059 fprintf(stderr, "dyld: launch failed\n");
2060 }
2061
2062 // Link in any inserted libraries.
2063 // Do this after link main executable so any extra libraries pulled in by inserted libraries are at end of flat namespace
2064 if ( insertLibrariesCount > 0 ) {
2065 for (int i=0; i < insertLibrariesCount; ++i) {
2066 try {
2067 if ( insertedImages[i] != NULL )
2068 link(insertedImages[i], bindness, ImageLoader::kDontRunInitializers);
2069 }
2070 catch (const char* message) {
2071 char buf[strlen(sEnv.DYLD_INSERT_LIBRARIES[i])+50+strlen(message)];
2072 sprintf(buf, "could not link inserted library: %s\n%s\n", sEnv.DYLD_INSERT_LIBRARIES[i], message);
2073 halt(buf);
2074 }
2075 }
2076 }
2077
2078 return result;
2079 }
2080
2081
2082
2083
2084 }; // namespace
2085
2086
2087