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