]> git.saurik.com Git - apple/dyld.git/blob - src/dyld.cpp
dyld-95.3.tar.gz
[apple/dyld.git] / src / dyld.cpp
1 /* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*-
2 *
3 * Copyright (c) 2004-2007 Apple 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 <errno.h>
29 #include <fcntl.h>
30 #include <sys/param.h>
31 #include <mach/mach_time.h> // mach_absolute_time()
32 #include <sys/types.h>
33 #include <sys/stat.h>
34 #include <mach-o/fat.h>
35 #include <mach-o/loader.h>
36 #include <mach-o/ldsyms.h>
37 #include <libkern/OSByteOrder.h>
38 #include <mach/mach.h>
39 #include <sys/sysctl.h>
40 #include <sys/mman.h>
41 #include <sys/dtrace.h>
42
43 #include <vector>
44 #include <algorithm>
45
46 #include "mach-o/dyld_gdb.h"
47
48 #include "dyld.h"
49 #include "ImageLoader.h"
50 #include "ImageLoaderMachO.h"
51 #include "dyldLibSystemInterface.h"
52 #include "dyld_cache_format.h"
53
54 // from _simple.h in libc
55 typedef struct _SIMPLE* _SIMPLE_STRING;
56 extern "C" void _simple_vdprintf(int __fd, const char *__fmt, va_list __ap);
57 extern "C" void _simple_dprintf(int __fd, const char *__fmt, ...);
58 extern "C" _SIMPLE_STRING _simple_salloc(void);
59 extern "C" int _simple_vsprintf(_SIMPLE_STRING __b, const char *__fmt, va_list __ap);
60 extern "C" void _simple_sfree(_SIMPLE_STRING __b);
61 extern "C" char * _simple_string(_SIMPLE_STRING __b);
62
63
64
65 // 32-bit ppc is only architecture that uses cpu-sub-types
66 #define CPU_SUBTYPES_SUPPORTED __ppc__
67
68
69 #define OLD_GDB_DYLD_INTERFACE __ppc__ || __i386__
70
71
72 #define CPU_TYPE_MASK 0x00FFFFFF /* complement of CPU_ARCH_MASK */
73
74
75 /* implemented in dyld_gdb.cpp */
76 extern void addImagesToAllImages(uint32_t infoCount, const dyld_image_info info[]);
77 extern void removeImageFromAllImages(const mach_header* mh);
78 #if OLD_GDB_DYLD_INTERFACE
79 extern void addImageForgdb(const mach_header* mh, uintptr_t slide, const char* physicalPath, const char* logicalPath);
80 extern void removeImageForgdb(const struct mach_header* mh);
81 #endif
82
83 // magic so CrashReporter logs message
84 extern "C" {
85 char error_string[1024];
86 }
87 // implemented in dyldStartup.s for CrashReporter
88 extern "C" void dyld_fatal_error(const char* errString) __attribute__((noreturn));
89
90
91
92 //
93 // The file contains the core of dyld used to get a process to main().
94 // The API's that dyld supports are implemented in dyldAPIs.cpp.
95 //
96 //
97 //
98 //
99 //
100
101
102 namespace dyld {
103
104
105 //
106 // state of all environment variables dyld uses
107 //
108 struct EnvironmentVariables {
109 const char* const * DYLD_FRAMEWORK_PATH;
110 const char* const * DYLD_FALLBACK_FRAMEWORK_PATH;
111 const char* const * DYLD_LIBRARY_PATH;
112 const char* const * DYLD_FALLBACK_LIBRARY_PATH;
113 const char* const * DYLD_ROOT_PATH;
114 const char* const * DYLD_INSERT_LIBRARIES;
115 const char* const * LD_LIBRARY_PATH; // for unix conformance
116 bool DYLD_PRINT_LIBRARIES;
117 bool DYLD_PRINT_LIBRARIES_POST_LAUNCH;
118 bool DYLD_BIND_AT_LAUNCH;
119 bool DYLD_PRINT_STATISTICS;
120 bool DYLD_PRINT_OPTS;
121 bool DYLD_PRINT_ENV;
122 bool DYLD_DISABLE_DOFS;
123 // DYLD_IMAGE_SUFFIX ==> gLinkContext.imageSuffix
124 // DYLD_PRINT_OPTS ==> gLinkContext.verboseOpts
125 // DYLD_PRINT_ENV ==> gLinkContext.verboseEnv
126 // DYLD_FORCE_FLAT_NAMESPACE ==> gLinkContext.bindFlat
127 // DYLD_PRINT_INITIALIZERS ==> gLinkContext.verboseInit
128 // DYLD_PRINT_SEGMENTS ==> gLinkContext.verboseMapping
129 // DYLD_PRINT_BINDINGS ==> gLinkContext.verboseBind
130 // DYLD_PRINT_REBASINGS ==> gLinkContext.verboseRebase
131 // DYLD_PRINT_DOFS ==> gLinkContext.verboseDOF
132 // DYLD_PRINT_APIS ==> gLogAPIs
133 // DYLD_IGNORE_PREBINDING ==> gLinkContext.prebindUsage
134 // DYLD_PREBIND_DEBUG ==> gLinkContext.verbosePrebinding
135 // DYLD_NEW_LOCAL_SHARED_REGIONS ==> gLinkContext.sharedRegionMode
136 // DYLD_SHARED_REGION ==> gLinkContext.sharedRegionMode
137 // DYLD_PRINT_WARNINGS ==> gLinkContext.verboseWarnings
138 };
139
140 typedef std::vector<dyld_image_state_change_handler> StateHandlers;
141 struct RegisteredDOF { const mach_header* mh; int registrationID; };
142
143 // all global state
144 static const char* sExecPath = NULL;
145 static const struct mach_header* sMainExecutableMachHeader = NULL;
146 static cpu_type_t sHostCPU;
147 static cpu_subtype_t sHostCPUsubtype;
148 static ImageLoader* sMainExecutable = NULL;
149 static bool sMainExecutableIsSetuid = false;
150 static unsigned int sInsertedDylibCount = 0;
151 static std::vector<ImageLoader*> sAllImages;
152 static std::vector<ImageLoader*> sImageRoots;
153 static std::vector<ImageLoader*> sImageFilesNeedingTermination;
154 static std::vector<RegisteredDOF> sImageFilesNeedingDOFUnregistration;
155 #if IMAGE_NOTIFY_SUPPORT
156 static std::vector<ImageLoader*> sImagesToNotifyAboutOtherImages;
157 #endif
158 static std::vector<ImageCallback> sAddImageCallbacks;
159 static std::vector<ImageCallback> sRemoveImageCallbacks;
160 static StateHandlers sSingleHandlers[7];
161 static StateHandlers sBatchHandlers[7];
162 static ImageLoader* sLastImageByAddressCache;
163 static EnvironmentVariables sEnv;
164 static const char* sFrameworkFallbackPaths[] = { "$HOME/Library/Frameworks", "/Library/Frameworks", "/Network/Library/Frameworks", "/System/Library/Frameworks", NULL };
165 static const char* sLibraryFallbackPaths[] = { "$HOME/lib", "/usr/local/lib", "/usr/lib", NULL };
166 static BundleNotificationCallBack sBundleNotifier = NULL;
167 static BundleLocatorCallBack sBundleLocation = NULL;
168 static UndefinedHandler sUndefinedHandler = NULL;
169 static ImageLoader* sBundleBeingLoaded = NULL; // hack until OFI is reworked
170 #if DYLD_SHARED_CACHE_SUPPORT
171 static const dyld_cache_header* sSharedCache = NULL;
172 bool gSharedCacheNotFound = false;
173 bool gSharedCacheNeedsUpdating = false;
174 bool gSharedCacheDontNotify = false;
175 #endif
176 ImageLoader::LinkContext gLinkContext;
177 bool gLogAPIs = false;
178 const struct LibSystemHelpers* gLibSystemHelpers = NULL;
179 #if SUPPORT_OLD_CRT_INITIALIZATION
180 bool gRunInitializersOldWay = false;
181 #endif
182 #if __i386__
183 static uint32_t sImportSegmentsStart = 0;
184 static uint32_t sImportSegmentsSize = 0;
185 #endif
186
187
188
189 const char* mkstringf(const char* format, ...)
190 {
191 va_list list;
192 va_start(list, format);
193 _SIMPLE_STRING buf = _simple_salloc();
194 _simple_vsprintf(buf, format, list);
195 va_end(list);
196 const char* t = strdup(_simple_string(buf));
197 _simple_sfree(buf);
198 return t;
199 }
200
201
202 void throwf(const char* format, ...)
203 {
204 va_list list;
205 va_start(list, format);
206 _SIMPLE_STRING buf = _simple_salloc();
207 _simple_vsprintf(buf, format, list);
208 va_end(list);
209 const char* t = strdup(_simple_string(buf));
210 _simple_sfree(buf);
211 throw t;
212 }
213
214 void log(const char* format, ...)
215 {
216 va_list list;
217 va_start(list, format);
218 _simple_vdprintf(STDERR_FILENO, format, list);
219 va_end(list);
220 }
221
222 void warn(const char* format, ...)
223 {
224 _simple_dprintf(STDERR_FILENO, "dyld: warning, ");
225 va_list list;
226 va_start(list, format);
227 _simple_vdprintf(STDERR_FILENO, format, list);
228 va_end(list);
229 }
230
231
232 // utility class to assure files are closed when an exception is thrown
233 class FileOpener {
234 public:
235 FileOpener(const char* path);
236 ~FileOpener();
237 int getFileDescriptor() { return fd; }
238 private:
239 int fd;
240 };
241
242 FileOpener::FileOpener(const char* path)
243 : fd(-1)
244 {
245 fd = open(path, O_RDONLY, 0);
246 }
247
248 FileOpener::~FileOpener()
249 {
250 if ( fd != -1 )
251 close(fd);
252 }
253
254
255 // forward declaration
256 #if __ppc__ || __i386__
257 bool isRosetta();
258 #endif
259
260
261 static void registerDOFs(const std::vector<ImageLoader::DOFInfo>& dofs)
262 {
263 #if __ppc__
264 // can't dtrace a program running emulated under rosetta rdar://problem/5179640
265 if ( isRosetta() )
266 return;
267 #endif
268 const unsigned int dofSectionCount = dofs.size();
269 if ( !sEnv.DYLD_DISABLE_DOFS && (dofSectionCount != 0) ) {
270 int fd = open("/dev/" DTRACEMNR_HELPER, O_RDWR);
271 if ( fd < 0 ) {
272 //dyld::warn("can't open /dev/" DTRACEMNR_HELPER " to register dtrace DOF sections\n");
273 }
274 else {
275 // allocate a buffer on the stack for the variable length dof_ioctl_data_t type
276 uint8_t buffer[sizeof(dof_ioctl_data_t) + dofSectionCount*sizeof(dof_helper_t)];
277 dof_ioctl_data_t* ioctlData = (dof_ioctl_data_t*)buffer;
278
279 // fill in buffer with one dof_helper_t per DOF section
280 ioctlData->dofiod_count = dofSectionCount;
281 for (unsigned int i=0; i < dofSectionCount; ++i) {
282 strlcpy(ioctlData->dofiod_helpers[i].dofhp_mod, dofs[i].imageShortName, DTRACE_MODNAMELEN);
283 ioctlData->dofiod_helpers[i].dofhp_dof = (uintptr_t)(dofs[i].dof);
284 ioctlData->dofiod_helpers[i].dofhp_addr = (uintptr_t)(dofs[i].dof);
285 }
286
287 // tell kernel about all DOF sections en mas
288 // pass pointer to ioctlData because ioctl() only copies a fixed size amount of data into kernel
289 user_addr_t val = (user_addr_t)(unsigned long)ioctlData;
290 if ( ioctl(fd, DTRACEHIOC_ADDDOF, &val) != -1 ) {
291 // kernel returns a unique identifier for each section in the dofiod_helpers[].dofhp_dof field.
292 for (unsigned int i=0; i < dofSectionCount; ++i) {
293 RegisteredDOF info;
294 info.mh = dofs[i].imageHeader;
295 info.registrationID = (int)(ioctlData->dofiod_helpers[i].dofhp_dof);
296 sImageFilesNeedingDOFUnregistration.push_back(info);
297 if ( gLinkContext.verboseDOF ) {
298 dyld::log("dyld: registering DOF section 0x%p in %s with dtrace, ID=0x%08X\n",
299 dofs[i].dof, dofs[i].imageShortName, info.registrationID);
300 }
301 }
302 }
303 else {
304 dyld::log( "dyld: ioctl to register dtrace DOF section failed\n");
305 }
306 close(fd);
307 }
308 }
309 }
310
311 static void unregisterDOF(int registrationID)
312 {
313 int fd = open("/dev/" DTRACEMNR_HELPER, O_RDWR);
314 if ( fd < 0 ) {
315 dyld::warn("can't open /dev/" DTRACEMNR_HELPER " to unregister dtrace DOF section\n");
316 }
317 else {
318 ioctl(fd, DTRACEHIOC_REMOVE, registrationID);
319 close(fd);
320 if ( gLinkContext.verboseInit )
321 dyld::warn("unregistering DOF section ID=0x%08X with dtrace\n", registrationID);
322 }
323 }
324
325
326 //
327 // _dyld_register_func_for_add_image() is implemented as part of the general image state change notification
328 //
329 static void notifyAddImageCallbacks(ImageLoader* image)
330 {
331 for (std::vector<ImageCallback>::iterator it=sAddImageCallbacks.begin(); it != sAddImageCallbacks.end(); it++)
332 (*it)(image->machHeader(), image->getSlide());
333 }
334
335
336 // notify gdb about these new images
337 static const char* notifyGDB(enum dyld_image_states state, uint32_t infoCount, const struct dyld_image_info info[])
338 {
339 addImagesToAllImages(infoCount, info);
340 return NULL;
341 }
342
343 #if IMAGE_NOTIFY_SUPPORT
344 // notify objc about these new images
345 static void notifyAdding(const ImageLoader* const * images, unsigned int count)
346 {
347 // build array
348 if ( count != 0 ) {
349 dyld_image_info infos[count];
350 for (unsigned int i=0; i < count; ++i) {
351 dyld_image_info* p = &infos[i];
352 const ImageLoader* image = images[i];
353 p->imageLoadAddress = image->machHeader();
354 p->imageFilePath = image->getPath();
355 p->imageFileModDate = image->lastModified();
356 //dyld::log("notifying objc about %s\n", image->getPath());
357 }
358
359 // tell all interested images (after gdb, so you can debug anything the notification does)
360 for (std::vector<ImageLoader*>::iterator it=sImagesToNotifyAboutOtherImages.begin(); it != sImagesToNotifyAboutOtherImages.end(); it++) {
361 (*it)->doNotification(dyld_image_adding, count, infos);
362 }
363 }
364 }
365 #endif
366
367 static StateHandlers* stateToHandlers(dyld_image_states state, StateHandlers handlersArray[8])
368 {
369 switch ( state ) {
370 case dyld_image_state_mapped:
371 return &handlersArray[0];
372
373 case dyld_image_state_dependents_mapped:
374 return &handlersArray[1];
375
376 case dyld_image_state_rebased:
377 return &handlersArray[2];
378
379 case dyld_image_state_bound:
380 return &handlersArray[3];
381
382 case dyld_image_state_dependents_initialized:
383 return &handlersArray[4];
384
385 case dyld_image_state_initialized:
386 return &handlersArray[5];
387
388 case dyld_image_state_terminated:
389 return &handlersArray[6];
390 }
391 return NULL;
392 }
393
394 static void notifySingle(dyld_image_states state, const struct mach_header* mh, const char* path, time_t modDate)
395 {
396 std::vector<dyld_image_state_change_handler>* handlers = stateToHandlers(state, sSingleHandlers);
397 if ( handlers != NULL ) {
398 dyld_image_info info;
399 info.imageLoadAddress = mh;
400 info.imageFilePath = path;
401 info.imageFileModDate = modDate;
402 for (std::vector<dyld_image_state_change_handler>::iterator it = handlers->begin(); it != handlers->end(); ++it) {
403 const char* result = (*it)(state, 1, &info);
404 if ( (result != NULL) && (state == dyld_image_state_mapped) ) {
405 //fprintf(stderr, " image rejected by handler=%p\n", *it);
406 // make copy of thrown string so that later catch clauses can free it
407 const char* str = strdup(result);
408 throw str;
409 }
410 }
411 }
412 }
413
414
415
416 static int imageSorter(const void* l, const void* r)
417 {
418 const ImageLoader* left = *((ImageLoader**)l);
419 const ImageLoader* right= *((ImageLoader**)r);
420 return left->compare(right);
421 }
422
423 static void notifyBatchPartial(dyld_image_states state, bool orLater, dyld_image_state_change_handler onlyHandler)
424 {
425 std::vector<dyld_image_state_change_handler>* handlers = stateToHandlers(state, sBatchHandlers);
426 if ( handlers != NULL ) {
427 // don't use a vector because it will use malloc/free and we want notifcation to be low cost
428 ImageLoader* images[sAllImages.size()+1];
429 ImageLoader** end = images;
430 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
431 dyld_image_states imageState = (*it)->getState();
432 if ( (imageState == state) || (orLater && (imageState > state)) )
433 *end++ = *it;
434 }
435 if ( sBundleBeingLoaded != NULL ) {
436 dyld_image_states imageState = sBundleBeingLoaded->getState();
437 if ( (imageState == state) || (orLater && (imageState > state)) )
438 *end++ = sBundleBeingLoaded;
439 }
440 unsigned int count = end-images;
441 if ( end != images ) {
442 // sort bottom up
443 qsort(images, count, sizeof(ImageLoader*), &imageSorter);
444 // build info array
445 dyld_image_info infos[count];
446 for (unsigned int i=0; i < count; ++i) {
447 dyld_image_info* p = &infos[i];
448 ImageLoader* image = images[i];
449 //dyld::log(" state=%d, name=%s\n", state, image->getPath());
450 p->imageLoadAddress = image->machHeader();
451 p->imageFilePath = image->getPath();
452 p->imageFileModDate = image->lastModified();
453 // special case for add_image hook
454 if ( state == dyld_image_state_bound )
455 notifyAddImageCallbacks(image);
456 }
457
458 if ( onlyHandler != NULL ) {
459 const char* result = (*onlyHandler)(state, count, infos);
460 if ( (result != NULL) && (state == dyld_image_state_dependents_mapped) ) {
461 //fprintf(stderr, " images rejected by handler=%p\n", onlyHandler);
462 // make copy of thrown string so that later catch clauses can free it
463 const char* str = strdup(result);
464 throw str;
465 }
466 }
467 else {
468 // call each handler with whole array
469 for (std::vector<dyld_image_state_change_handler>::iterator it = handlers->begin(); it != handlers->end(); ++it) {
470 const char* result = (*it)(state, count, infos);
471 if ( (result != NULL) && (state == dyld_image_state_dependents_mapped) ) {
472 //fprintf(stderr, " images rejected by handler=%p\n", *it);
473 // make copy of thrown string so that later catch clauses can free it
474 const char* str = strdup(result);
475 throw str;
476 }
477 }
478 }
479 }
480 }
481 }
482
483 static void notifyBatch(dyld_image_states state)
484 {
485 notifyBatchPartial(state, false, NULL);
486 }
487
488 // In order for register_func_for_add_image() callbacks to to be called bottom up,
489 // we need to maintain a list of root images. The main executable is usally the
490 // first root. Any images dynamically added are also roots (unless already loaded).
491 // If DYLD_INSERT_LIBRARIES is used, those libraries are first.
492 static void addRootImage(ImageLoader* image)
493 {
494 //dyld::log("addRootImage(%p, %s)\n", image, image->getPath());
495 // add to list of roots
496 sImageRoots.push_back(image);
497 }
498
499 #if IMAGE_NOTIFY_SUPPORT
500 // Objective-C will contain a __DATA/__image_notify section which contains pointers to a function to call
501 // whenever any new image is loaded.
502 static void addImageNeedingNotification(ImageLoader* image)
503 {
504 sImagesToNotifyAboutOtherImages.push_back(image);
505 }
506 #endif
507
508 static void clearAllDepths()
509 {
510 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++)
511 (*it)->clearDepth();
512 }
513
514 static unsigned int imageCount()
515 {
516 return sAllImages.size();
517 }
518
519 static void notifySharedCacheInvalid()
520 {
521 gSharedCacheNeedsUpdating = true;
522 }
523
524
525
526 #if __i386__
527 static void makeSharedCacheImportSegmentsWritable(bool writable)
528 {
529 // if cache was built with read-only __IMPORT segments
530 if ( sImportSegmentsSize != 0 ) {
531 vm_prot_t prot = VM_PROT_EXECUTE | PROT_READ;
532 if ( writable )
533 prot |= VM_PROT_WRITE;
534 vm_protect(mach_task_self(), sImportSegmentsStart, sImportSegmentsSize, false, prot);
535 if ( gLinkContext.verboseMapping ) {
536 dyld::log("%18s at %p->%p altered permissions to %c%c%c\n", "", (char*)sImportSegmentsStart, (char*)sImportSegmentsStart+sImportSegmentsSize-1,
537 (prot & PROT_READ) ? 'r' : '.', (prot & PROT_WRITE) ? 'w' : '.', (prot & PROT_EXEC) ? 'x' : '.' );
538 }
539 }
540 }
541 #endif
542
543 static void setNewProgramVars(const ProgramVars& newVars)
544 {
545 // make a copy of the pointers to program variables
546 gLinkContext.programVars = newVars;
547
548 // now set each program global to their initial value
549 *gLinkContext.programVars.NXArgcPtr = gLinkContext.argc;
550 *gLinkContext.programVars.NXArgvPtr = gLinkContext.argv;
551 *gLinkContext.programVars.environPtr = gLinkContext.envp;
552 *gLinkContext.programVars.__prognamePtr = gLinkContext.progname;
553 }
554
555 #if SUPPORT_OLD_CRT_INITIALIZATION
556 static void setRunInitialzersOldWay()
557 {
558 gRunInitializersOldWay = true;
559 }
560 #endif
561
562 static void addImage(ImageLoader* image)
563 {
564 // add to master list
565 sAllImages.push_back(image);
566
567 if ( sEnv.DYLD_PRINT_LIBRARIES || (sEnv.DYLD_PRINT_LIBRARIES_POST_LAUNCH && (sMainExecutable!=NULL) && sMainExecutable->isLinked()) ) {
568 dyld::log("dyld: loaded: %s\n", image->getPath());
569 }
570
571 #if OLD_GDB_DYLD_INTERFACE
572 // let gdb find out about this
573 addImageForgdb(image->machHeader(), image->getSlide(), image->getPath(), image->getLogicalPath());
574 #endif
575 }
576
577 void removeImage(ImageLoader* image)
578 {
579 // if in termination list, pull it out and run terminator
580 for (std::vector<ImageLoader*>::iterator it=sImageFilesNeedingTermination.begin(); it != sImageFilesNeedingTermination.end(); it++) {
581 if ( *it == image ) {
582 sImageFilesNeedingTermination.erase(it);
583 image->doTermination(gLinkContext);
584 break;
585 }
586 }
587
588 // if has dtrace DOF section, tell dtrace it is going away, then remove from sImageFilesNeedingDOFUnregistration
589 for (std::vector<RegisteredDOF>::iterator it=sImageFilesNeedingDOFUnregistration.begin(); it != sImageFilesNeedingDOFUnregistration.end(); ) {
590 if ( it->mh == image->machHeader() ) {
591 unregisterDOF(it->registrationID);
592 sImageFilesNeedingDOFUnregistration.erase(it);
593 // don't increment iterator, the erase caused next element to be copied to where this iterator points
594 }
595 else {
596 ++it;
597 }
598 }
599
600 // tell all register add image handlers about this
601 // do this before removing image from internal data structures so that the callback can query dyld about the image
602 if ( image->getState() >= dyld_image_state_bound ) {
603 for (std::vector<ImageCallback>::iterator it=sRemoveImageCallbacks.begin(); it != sRemoveImageCallbacks.end(); it++) {
604 (*it)(image->machHeader(), image->getSlide());
605 }
606 }
607
608 #if IMAGE_NOTIFY_SUPPORT
609 // tell all interested images
610 for (std::vector<ImageLoader*>::iterator it=sImagesToNotifyAboutOtherImages.begin(); it != sImagesToNotifyAboutOtherImages.end(); it++) {
611 dyld_image_info info;
612 info.imageLoadAddress = image->machHeader();
613 info.imageFilePath = image->getPath();
614 info.imageFileModDate = image->lastModified();
615 (*it)->doNotification(dyld_image_removing, 1, &info);
616 }
617 #endif
618
619 // remove from master list
620 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
621 if ( *it == image ) {
622 sAllImages.erase(it);
623 break;
624 }
625 }
626
627 // flush find-by-address cache (do this after removed from master list, so there is no chance it can come back)
628 if ( sLastImageByAddressCache == image )
629 sLastImageByAddressCache = NULL;
630
631 #if IMAGE_NOTIFY_SUPPORT
632 // if in announcement list, pull it out
633 for (std::vector<ImageLoader*>::iterator it=sImagesToNotifyAboutOtherImages.begin(); it != sImagesToNotifyAboutOtherImages.end(); it++) {
634 if ( *it == image ) {
635 sImagesToNotifyAboutOtherImages.erase(it);
636 break;
637 }
638 }
639 #endif
640
641 // if in root list, pull it out
642 for (std::vector<ImageLoader*>::iterator it=sImageRoots.begin(); it != sImageRoots.end(); it++) {
643 if ( *it == image ) {
644 sImageRoots.erase(it);
645 break;
646 }
647 }
648
649 // log if requested
650 if ( sEnv.DYLD_PRINT_LIBRARIES || (sEnv.DYLD_PRINT_LIBRARIES_POST_LAUNCH && (sMainExecutable!=NULL) && sMainExecutable->isLinked()) ) {
651 dyld::log("dyld: unloaded: %s\n", image->getPath());
652 }
653
654 // tell gdb, new way
655 removeImageFromAllImages(image->machHeader());
656
657 #if OLD_GDB_DYLD_INTERFACE
658 // tell gdb, old way
659 removeImageForgdb(image->machHeader());
660 gdb_dyld_state_changed();
661 #endif
662 }
663
664
665 static void terminationRecorder(ImageLoader* image)
666 {
667 sImageFilesNeedingTermination.push_back(image);
668 }
669
670 const char* getExecutablePath()
671 {
672 return sExecPath;
673 }
674
675
676 void initializeMainExecutable()
677 {
678
679 #if __i386__
680 // make all __IMPORT segments in the shared cache read-only
681 // before executing any code
682 makeSharedCacheImportSegmentsWritable(false);
683 #endif
684
685 // run initialzers for any inserted dylibs
686 const int rootCount = sImageRoots.size();
687 if ( rootCount > 1 ) {
688 for(int i=1; i < rootCount; ++i)
689 sImageRoots[i]->runInitializers(gLinkContext);
690 }
691
692 // run initializers for main executable and everything it brings up
693 sMainExecutable->runInitializers(gLinkContext);
694
695 // register atexit() handler to run terminators in all loaded images when this process exits
696 if ( gLibSystemHelpers != NULL )
697 (*gLibSystemHelpers->cxa_atexit)(&runTerminators, NULL, NULL);
698
699 // dump info if requested
700 if ( sEnv.DYLD_PRINT_STATISTICS )
701 ImageLoaderMachO::printStatistics(sAllImages.size());
702 }
703
704 bool mainExecutablePrebound()
705 {
706 return sMainExecutable->usablePrebinding(gLinkContext);
707 }
708
709 ImageLoader* mainExecutable()
710 {
711 return sMainExecutable;
712 }
713
714
715 void runTerminators(void* extra)
716 {
717 const unsigned int imageCount = sImageFilesNeedingTermination.size();
718 for(unsigned int i=imageCount; i > 0; --i){
719 ImageLoader* image = sImageFilesNeedingTermination[i-1];
720 image->doTermination(gLinkContext);
721 notifySingle(dyld_image_state_terminated, image->machHeader(), image->getPath(), image->lastModified());
722 }
723 sImageFilesNeedingTermination.clear();
724 notifyBatch(dyld_image_state_terminated);
725 }
726
727
728 //
729 // Turns a colon separated list of strings
730 // into a NULL terminated array of string
731 // pointers.
732 //
733 static const char** parseColonList(const char* list)
734 {
735 if ( list[0] == '\0' )
736 return NULL;
737
738 int colonCount = 0;
739 for(const char* s=list; *s != '\0'; ++s) {
740 if (*s == ':')
741 ++colonCount;
742 }
743
744 int index = 0;
745 const char* start = list;
746 char** result = new char*[colonCount+2];
747 for(const char* s=list; *s != '\0'; ++s) {
748 if (*s == ':') {
749 int len = s-start;
750 char* str = new char[len+1];
751 strncpy(str, start, len);
752 str[len] = '\0';
753 start = &s[1];
754 result[index++] = str;
755 }
756 }
757 int len = strlen(start);
758 char* str = new char[len+1];
759 strcpy(str, start);
760 result[index++] = str;
761 result[index] = NULL;
762
763 return (const char**)result;
764 }
765
766
767 static void paths_expand_roots(const char **paths, const char *key, const char *val)
768 {
769 // assert(val != NULL);
770 // assert(paths != NULL);
771 if(NULL != key) {
772 size_t keyLen = strlen(key);
773 for(int i=0; paths[i] != NULL; ++i) {
774 if ( strncmp(paths[i], key, keyLen) == 0 ) {
775 char* newPath = new char[strlen(val) + (strlen(paths[i]) - keyLen) + 1];
776 strcpy(newPath, val);
777 strcat(newPath, &paths[i][keyLen]);
778 paths[i] = newPath;
779 }
780 }
781 }
782 return;
783 }
784
785 static void removePathWithPrefix(const char* paths[], const char* prefix)
786 {
787 size_t prefixLen = strlen(prefix);
788 int skip = 0;
789 int i;
790 for(i = 0; paths[i] != NULL; ++i) {
791 if ( strncmp(paths[i], prefix, prefixLen) == 0 )
792 ++skip;
793 else
794 paths[i-skip] = paths[i];
795 }
796 paths[i-skip] = NULL;
797 }
798
799
800 #if 0
801 static void paths_dump(const char **paths)
802 {
803 // assert(paths != NULL);
804 const char **strs = paths;
805 while(*strs != NULL)
806 {
807 dyld::log("\"%s\"\n", *strs);
808 strs++;
809 }
810 return;
811 }
812 #endif
813
814 static void printOptions(const char* argv[])
815 {
816 uint32_t i = 0;
817 while ( NULL != argv[i] ) {
818 dyld::log("opt[%i] = \"%s\"\n", i, argv[i]);
819 i++;
820 }
821 }
822
823 static void printEnvironmentVariables(const char* envp[])
824 {
825 while ( NULL != *envp ) {
826 dyld::log("%s\n", *envp);
827 envp++;
828 }
829 }
830
831 void processDyldEnvironmentVarible(const char* key, const char* value)
832 {
833 if ( strcmp(key, "DYLD_FRAMEWORK_PATH") == 0 ) {
834 sEnv.DYLD_FRAMEWORK_PATH = parseColonList(value);
835 gSharedCacheDontNotify = true;
836 }
837 else if ( strcmp(key, "DYLD_FALLBACK_FRAMEWORK_PATH") == 0 ) {
838 sEnv.DYLD_FALLBACK_FRAMEWORK_PATH = parseColonList(value);
839 gSharedCacheDontNotify = true;
840 }
841 else if ( strcmp(key, "DYLD_LIBRARY_PATH") == 0 ) {
842 sEnv.DYLD_LIBRARY_PATH = parseColonList(value);
843 gSharedCacheDontNotify = true;
844 }
845 else if ( strcmp(key, "DYLD_FALLBACK_LIBRARY_PATH") == 0 ) {
846 sEnv.DYLD_FALLBACK_LIBRARY_PATH = parseColonList(value);
847 gSharedCacheDontNotify = true;
848 }
849 else if ( (strcmp(key, "DYLD_ROOT_PATH") == 0) || (strcmp(key, "DYLD_PATHS_ROOT") == 0) ) {
850 gSharedCacheDontNotify = true;
851 if ( strcmp(value, "/") != 0 ) {
852 sEnv.DYLD_ROOT_PATH = parseColonList(value);
853 for (int i=0; sEnv.DYLD_ROOT_PATH[i] != NULL; ++i) {
854 if ( sEnv.DYLD_ROOT_PATH[i][0] != '/' ) {
855 dyld::warn("DYLD_ROOT_PATH not used because it contains a non-absolute path\n");
856 sEnv.DYLD_ROOT_PATH = NULL;
857 break;
858 }
859 }
860 }
861 }
862 else if ( strcmp(key, "DYLD_IMAGE_SUFFIX") == 0 ) {
863 gSharedCacheDontNotify = true;
864 gLinkContext.imageSuffix = value;
865 }
866 else if ( strcmp(key, "DYLD_INSERT_LIBRARIES") == 0 ) {
867 sEnv.DYLD_INSERT_LIBRARIES = parseColonList(value);
868 gSharedCacheDontNotify = true;
869 }
870 else if ( strcmp(key, "DYLD_PRINT_OPTS") == 0 ) {
871 sEnv.DYLD_PRINT_OPTS = true;
872 }
873 else if ( strcmp(key, "DYLD_PRINT_ENV") == 0 ) {
874 sEnv.DYLD_PRINT_ENV = true;
875 }
876 else if ( strcmp(key, "DYLD_DISABLE_DOFS") == 0 ) {
877 sEnv.DYLD_DISABLE_DOFS = true;
878 }
879 else if ( strcmp(key, "DYLD_DISABLE_PREFETCH") == 0 ) {
880 gLinkContext.preFetchDisabled = true;
881 }
882 else if ( strcmp(key, "DYLD_PRINT_LIBRARIES") == 0 ) {
883 sEnv.DYLD_PRINT_LIBRARIES = true;
884 }
885 else if ( strcmp(key, "DYLD_PRINT_LIBRARIES_POST_LAUNCH") == 0 ) {
886 sEnv.DYLD_PRINT_LIBRARIES_POST_LAUNCH = true;
887 }
888 else if ( strcmp(key, "DYLD_BIND_AT_LAUNCH") == 0 ) {
889 sEnv.DYLD_BIND_AT_LAUNCH = true;
890 }
891 else if ( strcmp(key, "DYLD_FORCE_FLAT_NAMESPACE") == 0 ) {
892 gLinkContext.bindFlat = true;
893 }
894 else if ( strcmp(key, "DYLD_NEW_LOCAL_SHARED_REGIONS") == 0 ) {
895 // ignore, no longer relevant but some scripts still set it
896 }
897 else if ( strcmp(key, "DYLD_NO_FIX_PREBINDING") == 0 ) {
898 gSharedCacheDontNotify = true;
899 }
900 else if ( strcmp(key, "DYLD_PREBIND_DEBUG") == 0 ) {
901 gLinkContext.verbosePrebinding = true;
902 }
903 else if ( strcmp(key, "DYLD_PRINT_INITIALIZERS") == 0 ) {
904 gLinkContext.verboseInit = true;
905 }
906 else if ( strcmp(key, "DYLD_PRINT_DOFS") == 0 ) {
907 gLinkContext.verboseDOF = true;
908 }
909 else if ( strcmp(key, "DYLD_PRINT_STATISTICS") == 0 ) {
910 sEnv.DYLD_PRINT_STATISTICS = true;
911 }
912 else if ( strcmp(key, "DYLD_PRINT_SEGMENTS") == 0 ) {
913 gLinkContext.verboseMapping = true;
914 }
915 else if ( strcmp(key, "DYLD_PRINT_BINDINGS") == 0 ) {
916 gLinkContext.verboseBind = true;
917 }
918 else if ( strcmp(key, "DYLD_PRINT_REBASINGS") == 0 ) {
919 gLinkContext.verboseRebase = true;
920 }
921 else if ( strcmp(key, "DYLD_PRINT_APIS") == 0 ) {
922 gLogAPIs = true;
923 }
924 else if ( strcmp(key, "DYLD_PRINT_WARNINGS") == 0 ) {
925 gLinkContext.verboseWarnings = true;
926 }
927 else if ( strcmp(key, "DYLD_SHARED_REGION") == 0 ) {
928 gSharedCacheDontNotify = true;
929 if ( strcmp(value, "private") == 0 ) {
930 gLinkContext.sharedRegionMode = ImageLoader::kUsePrivateSharedRegion;
931 }
932 else if ( strcmp(value, "avoid") == 0 ) {
933 gLinkContext.sharedRegionMode = ImageLoader::kDontUseSharedRegion;
934 }
935 else if ( strcmp(value, "use") == 0 ) {
936 gLinkContext.sharedRegionMode = ImageLoader::kUseSharedRegion;
937 }
938 else if ( value[0] == '\0' ) {
939 gLinkContext.sharedRegionMode = ImageLoader::kUseSharedRegion;
940 }
941 else {
942 dyld::warn("unknown option to DYLD_SHARED_REGION. Valid options are: use, private, avoid\n");
943 }
944 }
945 else if ( strcmp(key, "DYLD_IGNORE_PREBINDING") == 0 ) {
946 gSharedCacheDontNotify = true;
947 if ( strcmp(value, "all") == 0 ) {
948 gLinkContext.prebindUsage = ImageLoader::kUseNoPrebinding;
949 }
950 else if ( strcmp(value, "app") == 0 ) {
951 gLinkContext.prebindUsage = ImageLoader::kUseAllButAppPredbinding;
952 }
953 else if ( strcmp(value, "nonsplit") == 0 ) {
954 gLinkContext.prebindUsage = ImageLoader::kUseSplitSegPrebinding;
955 }
956 else if ( value[0] == '\0' ) {
957 gLinkContext.prebindUsage = ImageLoader::kUseSplitSegPrebinding;
958 }
959 else {
960 dyld::warn("unknown option to DYLD_IGNORE_PREBINDING. Valid options are: all, app, nonsplit\n");
961 }
962 }
963 else {
964 dyld::warn("unknown environment variable: %s\n", key);
965 }
966 }
967
968
969 //
970 // For security, setuid programs ignore DYLD_* environment variables.
971 // Additionally, the DYLD_* enviroment variables are removed
972 // from the environment, so that any child processes don't see them.
973 //
974 static void pruneEnvironmentVariables(const char* envp[], const char*** applep)
975 {
976 // setuit binaries don't trigger a cache rebuild
977 gSharedCacheDontNotify = true;
978
979 // delete all DYLD_* and LD_LIBRARY_PATH environment variables
980 int removedCount = 0;
981 const char** d = envp;
982 for(const char** s = envp; *s != NULL; s++) {
983 if ( (strncmp(*s, "DYLD_", 5) != 0) && (strncmp(*s, "LD_LIBRARY_PATH=", 16) != 0) ) {
984 *d++ = *s;
985 }
986 else {
987 ++removedCount;
988 }
989 }
990 *d++ = NULL;
991
992 // slide apple parameters
993 if ( removedCount > 0 ) {
994 *applep = d;
995 do {
996 *d = d[removedCount];
997 } while ( *d++ != NULL );
998 }
999
1000 // disable framework and library fallback paths for setuid binaries rdar://problem/4589305
1001 sEnv.DYLD_FALLBACK_FRAMEWORK_PATH = NULL;
1002 sEnv.DYLD_FALLBACK_LIBRARY_PATH = NULL;
1003 }
1004
1005
1006 static void checkEnvironmentVariables(const char* envp[], bool ignoreEnviron)
1007 {
1008 const char* home = NULL;
1009 const char** p;
1010 for(p = envp; *p != NULL; p++) {
1011 const char* keyEqualsValue = *p;
1012 if ( strncmp(keyEqualsValue, "DYLD_", 5) == 0 ) {
1013 const char* equals = strchr(keyEqualsValue, '=');
1014 if ( (equals != NULL) && !ignoreEnviron ) {
1015 const char* value = &equals[1];
1016 const int keyLen = equals-keyEqualsValue;
1017 char key[keyLen+1];
1018 strncpy(key, keyEqualsValue, keyLen);
1019 key[keyLen] = '\0';
1020 processDyldEnvironmentVarible(key, value);
1021 }
1022 }
1023 else if ( strncmp(keyEqualsValue, "HOME=", 5) == 0 ) {
1024 home = &keyEqualsValue[5];
1025 }
1026 else if ( strncmp(keyEqualsValue, "LD_LIBRARY_PATH=", 16) == 0 ) {
1027 const char* path = &keyEqualsValue[16];
1028 sEnv.LD_LIBRARY_PATH = parseColonList(path);
1029 }
1030 }
1031
1032 // default value for DYLD_FALLBACK_FRAMEWORK_PATH, if not set in environment
1033 if ( sEnv.DYLD_FALLBACK_FRAMEWORK_PATH == NULL ) {
1034 const char** paths = sFrameworkFallbackPaths;
1035 if ( home == NULL )
1036 removePathWithPrefix(paths, "$HOME");
1037 else
1038 paths_expand_roots(paths, "$HOME", home);
1039 sEnv.DYLD_FALLBACK_FRAMEWORK_PATH = paths;
1040 }
1041
1042 // default value for DYLD_FALLBACK_LIBRARY_PATH, if not set in environment
1043 if ( sEnv.DYLD_FALLBACK_LIBRARY_PATH == NULL ) {
1044 const char** paths = sLibraryFallbackPaths;
1045 if ( home == NULL )
1046 removePathWithPrefix(paths, "$HOME");
1047 else
1048 paths_expand_roots(paths, "$HOME", home);
1049 sEnv.DYLD_FALLBACK_LIBRARY_PATH = paths;
1050 }
1051 }
1052
1053
1054 static void getHostInfo()
1055 {
1056 #if 1
1057 struct host_basic_info info;
1058 mach_msg_type_number_t count = HOST_BASIC_INFO_COUNT;
1059 mach_port_t hostPort = mach_host_self();
1060 kern_return_t result = host_info(hostPort, HOST_BASIC_INFO, (host_info_t)&info, &count);
1061 mach_port_deallocate(mach_task_self(), hostPort);
1062 if ( result != KERN_SUCCESS )
1063 throw "host_info() failed";
1064
1065 sHostCPU = info.cpu_type;
1066 sHostCPUsubtype = info.cpu_subtype;
1067 #else
1068 size_t valSize = sizeof(sHostCPU);
1069 if (sysctlbyname ("hw.cputype", &sHostCPU, &valSize, NULL, 0) != 0)
1070 throw "sysctlbyname(hw.cputype) failed";
1071 valSize = sizeof(sHostCPUsubtype);
1072 if (sysctlbyname ("hw.cpusubtype", &sHostCPUsubtype, &valSize, NULL, 0) != 0)
1073 throw "sysctlbyname(hw.cpusubtype) failed";
1074 #endif
1075 }
1076
1077 static void checkSharedRegionDisable()
1078 {
1079 #if __ppc__ || __i386__
1080 // if main executable has segments that overlap the shared region,
1081 // then disable using the shared region
1082 if ( sMainExecutable->overlapsWithAddressRange((void*)0x90000000, (void*)0xAFFFFFFF) ) {
1083 gLinkContext.sharedRegionMode = ImageLoader::kDontUseSharedRegion;
1084 if ( gLinkContext.verboseMapping )
1085 dyld::warn("disabling shared region because main executable overlaps\n");
1086 }
1087 #endif
1088 }
1089
1090 bool validImage(const ImageLoader* possibleImage)
1091 {
1092 const unsigned int imageCount = sAllImages.size();
1093 for(unsigned int i=0; i < imageCount; ++i) {
1094 if ( possibleImage == sAllImages[i] ) {
1095 return true;
1096 }
1097 }
1098 return false;
1099 }
1100
1101 uint32_t getImageCount()
1102 {
1103 return sAllImages.size();
1104 }
1105
1106 ImageLoader* getIndexedImage(unsigned int index)
1107 {
1108 if ( index < sAllImages.size() )
1109 return sAllImages[index];
1110 return NULL;
1111 }
1112
1113 ImageLoader* findImageByMachHeader(const struct mach_header* target)
1114 {
1115 const unsigned int imageCount = sAllImages.size();
1116 for(unsigned int i=0; i < imageCount; ++i) {
1117 ImageLoader* anImage = sAllImages[i];
1118 if ( anImage->machHeader() == target )
1119 return anImage;
1120 }
1121 return NULL;
1122 }
1123
1124
1125 ImageLoader* findImageContainingAddress(const void* addr)
1126 {
1127 #if FIND_STATS
1128 static int cacheHit = 0;
1129 static int cacheMiss = 0;
1130 static int cacheNotMacho = 0;
1131 if ( ((cacheHit+cacheMiss+cacheNotMacho) % 100) == 0 )
1132 dyld::log("findImageContainingAddress(): cache hit = %d, miss = %d, unknown = %d\n", cacheHit, cacheMiss, cacheNotMacho);
1133 #endif
1134 // first look in image where last address was found rdar://problem/3685517
1135 if ( (sLastImageByAddressCache != NULL) && sLastImageByAddressCache->containsAddress(addr) ) {
1136 #if FIND_STATS
1137 ++cacheHit;
1138 #endif
1139 return sLastImageByAddressCache;
1140 }
1141 // do exhastive search
1142 // todo: consider maintaining a list sorted by address ranges and do a binary search on that
1143 const unsigned int imageCount = sAllImages.size();
1144 for(unsigned int i=0; i < imageCount; ++i) {
1145 ImageLoader* anImage = sAllImages[i];
1146 if ( anImage->containsAddress(addr) ) {
1147 sLastImageByAddressCache = anImage;
1148 #if FIND_STATS
1149 ++cacheMiss;
1150 #endif
1151 return anImage;
1152 }
1153 }
1154 #if FIND_STATS
1155 ++cacheNotMacho;
1156 #endif
1157 return NULL;
1158 }
1159
1160 ImageLoader* findImageContainingAddressThreadSafe(const void* addr)
1161 {
1162 // do exhastive search
1163 // todo: consider maintaining a list sorted by address ranges and do a binary search on that
1164 const unsigned int imageCount = sAllImages.size();
1165 for(unsigned int i=0; i < imageCount; ++i) {
1166 ImageLoader* anImage = sAllImages[i];
1167 if ( anImage->containsAddress(addr) ) {
1168 return anImage;
1169 }
1170 }
1171 return NULL;
1172 }
1173
1174
1175 void forEachImageDo( void (*callback)(ImageLoader*, void* userData), void* userData)
1176 {
1177 const unsigned int imageCount = sAllImages.size();
1178 for(unsigned int i=0; i < imageCount; ++i) {
1179 ImageLoader* anImage = sAllImages[i];
1180 (*callback)(anImage, userData);
1181 }
1182 }
1183
1184 ImageLoader* findLoadedImage(const struct stat& stat_buf)
1185 {
1186 const unsigned int imageCount = sAllImages.size();
1187 for(unsigned int i=0; i < imageCount; ++i){
1188 ImageLoader* anImage = sAllImages[i];
1189 if ( anImage->statMatch(stat_buf) )
1190 return anImage;
1191 }
1192 return NULL;
1193 }
1194
1195 // based on ANSI-C strstr()
1196 static const char* strrstr(const char* str, const char* sub)
1197 {
1198 const int sublen = strlen(sub);
1199 for(const char* p = &str[strlen(str)]; p != str; --p) {
1200 if ( strncmp(p, sub, sublen) == 0 )
1201 return p;
1202 }
1203 return NULL;
1204 }
1205
1206
1207 //
1208 // Find framework path
1209 //
1210 // /path/foo.framework/foo => foo.framework/foo
1211 // /path/foo.framework/Versions/A/foo => foo.framework/Versions/A/foo
1212 // /path/foo.framework/Frameworks/bar.framework/bar => bar.framework/bar
1213 // /path/foo.framework/Libraries/bar.dylb => NULL
1214 // /path/foo.framework/bar => NULL
1215 //
1216 // Returns NULL if not a framework path
1217 //
1218 static const char* getFrameworkPartialPath(const char* path)
1219 {
1220 const char* dirDot = strrstr(path, ".framework/");
1221 if ( dirDot != NULL ) {
1222 const char* dirStart = dirDot;
1223 for ( ; dirStart >= path; --dirStart) {
1224 if ( (*dirStart == '/') || (dirStart == path) ) {
1225 const char* frameworkStart = &dirStart[1];
1226 if ( dirStart == path )
1227 --frameworkStart;
1228 int len = dirDot - frameworkStart;
1229 char framework[len+1];
1230 strncpy(framework, frameworkStart, len);
1231 framework[len] = '\0';
1232 const char* leaf = strrchr(path, '/');
1233 if ( leaf != NULL ) {
1234 if ( strcmp(framework, &leaf[1]) == 0 ) {
1235 return frameworkStart;
1236 }
1237 if ( gLinkContext.imageSuffix != NULL ) {
1238 // some debug frameworks have install names that end in _debug
1239 if ( strncmp(framework, &leaf[1], len) == 0 ) {
1240 if ( strcmp( gLinkContext.imageSuffix, &leaf[len+1]) == 0 )
1241 return frameworkStart;
1242 }
1243 }
1244 }
1245 }
1246 }
1247 }
1248 return NULL;
1249 }
1250
1251
1252 static const char* getLibraryLeafName(const char* path)
1253 {
1254 const char* start = strrchr(path, '/');
1255 if ( start != NULL )
1256 return &start[1];
1257 else
1258 return path;
1259 }
1260
1261
1262 // only for architectures that use cpu-sub-types
1263 #if CPU_SUBTYPES_SUPPORTED
1264
1265 const cpu_subtype_t CPU_SUBTYPE_END_OF_LIST = -1;
1266
1267
1268 //
1269 // A fat file may contain multiple sub-images for the same CPU type.
1270 // In that case, dyld picks which sub-image to use by scanning a table
1271 // of preferred cpu-sub-types for the running cpu.
1272 //
1273 // There is one row in the table for each cpu-sub-type on which dyld might run.
1274 // The first entry in a row is that cpu-sub-type. It is followed by all
1275 // cpu-sub-types that can run on that cpu, if preferred order. Each row ends with
1276 // a "SUBTYPE_ALL" (to denote that images written to run on any cpu-sub-type are usable),
1277 // followed by one or more CPU_SUBTYPE_END_OF_LIST to pad out this row.
1278 //
1279
1280
1281 //
1282 // 32-bit PowerPC sub-type lists
1283 //
1284 const int kPPC_RowCount = 4;
1285 static const cpu_subtype_t kPPC32[kPPC_RowCount][6] = {
1286 // G5 can run any code
1287 { 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 },
1288
1289 // G4 can run all but G5 code
1290 { 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 },
1291 { 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 },
1292
1293 // G3 cannot run G4 or G5 code
1294 { 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 }
1295 };
1296
1297
1298
1299 // scan the tables above to find the cpu-sub-type-list for this machine
1300 static const cpu_subtype_t* findCPUSubtypeList(cpu_type_t cpu, cpu_subtype_t subtype)
1301 {
1302 switch (cpu) {
1303 case CPU_TYPE_POWERPC:
1304 for (int i=0; i < kPPC_RowCount ; ++i) {
1305 if ( kPPC32[i][0] == subtype )
1306 return kPPC32[i];
1307 }
1308 break;
1309 }
1310 return NULL;
1311 }
1312
1313
1314
1315
1316 // scan fat table-of-contents for best most preferred subtype
1317 static bool fatFindBestFromOrderedList(cpu_type_t cpu, const cpu_subtype_t list[], const fat_header* fh, uint64_t* offset, uint64_t* len)
1318 {
1319 const fat_arch* const archs = (fat_arch*)(((char*)fh)+sizeof(fat_header));
1320 for (uint32_t subTypeIndex=0; list[subTypeIndex] != CPU_SUBTYPE_END_OF_LIST; ++subTypeIndex) {
1321 for(uint32_t fatIndex=0; fatIndex < OSSwapBigToHostInt32(fh->nfat_arch); ++fatIndex) {
1322 if ( ((cpu_type_t)OSSwapBigToHostInt32(archs[fatIndex].cputype) == cpu)
1323 && (list[subTypeIndex] == (cpu_subtype_t)OSSwapBigToHostInt32(archs[fatIndex].cpusubtype)) ) {
1324 *offset = OSSwapBigToHostInt32(archs[fatIndex].offset);
1325 *len = OSSwapBigToHostInt32(archs[fatIndex].size);
1326 return true;
1327 }
1328 }
1329 }
1330 return false;
1331 }
1332
1333 // scan fat table-of-contents for exact match of cpu and cpu-sub-type
1334 static bool fatFindExactMatch(cpu_type_t cpu, cpu_subtype_t subtype, const fat_header* fh, uint64_t* offset, uint64_t* len)
1335 {
1336 const fat_arch* archs = (fat_arch*)(((char*)fh)+sizeof(fat_header));
1337 for(uint32_t i=0; i < OSSwapBigToHostInt32(fh->nfat_arch); ++i) {
1338 if ( ((cpu_type_t)OSSwapBigToHostInt32(archs[i].cputype) == cpu)
1339 && ((cpu_subtype_t)OSSwapBigToHostInt32(archs[i].cpusubtype) == subtype) ) {
1340 *offset = OSSwapBigToHostInt32(archs[i].offset);
1341 *len = OSSwapBigToHostInt32(archs[i].size);
1342 return true;
1343 }
1344 }
1345 return false;
1346 }
1347
1348 // scan fat table-of-contents for image with matching cpu-type and runs-on-all-sub-types
1349 static bool fatFindRunsOnAllCPUs(cpu_type_t cpu, const fat_header* fh, uint64_t* offset, uint64_t* len)
1350 {
1351 const fat_arch* archs = (fat_arch*)(((char*)fh)+sizeof(fat_header));
1352 for(uint32_t i=0; i < OSSwapBigToHostInt32(fh->nfat_arch); ++i) {
1353 if ( (cpu_type_t)OSSwapBigToHostInt32(archs[i].cputype) == cpu) {
1354 switch (cpu) {
1355 case CPU_TYPE_POWERPC:
1356 if ( (cpu_subtype_t)OSSwapBigToHostInt32(archs[i].cpusubtype) == CPU_SUBTYPE_POWERPC_ALL ) {
1357 *offset = OSSwapBigToHostInt32(archs[i].offset);
1358 *len = OSSwapBigToHostInt32(archs[i].size);
1359 return true;
1360 }
1361 break;
1362 }
1363 }
1364 }
1365 return false;
1366 }
1367
1368 #endif // CPU_SUBTYPES_SUPPORTED
1369
1370 //
1371 // A fat file may contain multiple sub-images for the same cpu-type,
1372 // each optimized for a different cpu-sub-type (e.g G3 or G5).
1373 // This routine picks the optimal sub-image.
1374 //
1375 static bool fatFindBest(const fat_header* fh, uint64_t* offset, uint64_t* len)
1376 {
1377 #if CPU_SUBTYPES_SUPPORTED
1378 // assume all dylibs loaded must have same cpu type as main executable
1379 const cpu_type_t cpu = sMainExecutableMachHeader->cputype;
1380
1381 // We only know the subtype to use if the main executable cpu type matches the host
1382 if ( (cpu & CPU_TYPE_MASK) == sHostCPU ) {
1383 // get preference ordered list of subtypes
1384 const cpu_subtype_t* subTypePreferenceList = findCPUSubtypeList(cpu, sHostCPUsubtype);
1385
1386 // use ordered list to find best sub-image in fat file
1387 if ( subTypePreferenceList != NULL )
1388 return fatFindBestFromOrderedList(cpu, subTypePreferenceList, fh, offset, len);
1389
1390 // if running cpu is not in list, try for an exact match
1391 if ( fatFindExactMatch(cpu, sHostCPUsubtype, fh, offset, len) )
1392 return true;
1393 }
1394
1395 // running on an uknown cpu, can only load generic code
1396 return fatFindRunsOnAllCPUs(cpu, fh, offset, len);
1397 #else
1398 // just find first slice with matching architecture
1399 const fat_arch* archs = (fat_arch*)(((char*)fh)+sizeof(fat_header));
1400 for(uint32_t i=0; i < OSSwapBigToHostInt32(fh->nfat_arch); ++i) {
1401 if ( (cpu_type_t)OSSwapBigToHostInt32(archs[i].cputype) == sMainExecutableMachHeader->cputype) {
1402 *offset = OSSwapBigToHostInt32(archs[i].offset);
1403 *len = OSSwapBigToHostInt32(archs[i].size);
1404 return true;
1405 }
1406 }
1407 return false;
1408 #endif
1409 }
1410
1411
1412
1413 //
1414 // This is used to validate if a non-fat (aka thin or raw) mach-o file can be used
1415 // on the current processor. //
1416 bool isCompatibleMachO(const uint8_t* firstPage)
1417 {
1418 #if CPU_SUBTYPES_SUPPORTED
1419 // It is deemed compatible if any of the following are true:
1420 // 1) mach_header subtype is in list of compatible subtypes for running processor
1421 // 2) mach_header subtype is same as running processor subtype
1422 // 3) mach_header subtype runs on all processor variants
1423 const mach_header* mh = (mach_header*)firstPage;
1424 if ( mh->magic == sMainExecutableMachHeader->magic ) {
1425 if ( mh->cputype == sMainExecutableMachHeader->cputype ) {
1426 if ( (mh->cputype & CPU_TYPE_MASK) == sHostCPU ) {
1427 // get preference ordered list of subtypes that this machine can use
1428 const cpu_subtype_t* subTypePreferenceList = findCPUSubtypeList(mh->cputype, sHostCPUsubtype);
1429 if ( subTypePreferenceList != NULL ) {
1430 // if image's subtype is in the list, it is compatible
1431 for (const cpu_subtype_t* p = subTypePreferenceList; *p != CPU_SUBTYPE_END_OF_LIST; ++p) {
1432 if ( *p == mh->cpusubtype )
1433 return true;
1434 }
1435 // have list and not in list, so not compatible
1436 throw "incompatible cpu-subtype";
1437 }
1438 // unknown cpu sub-type, but if exact match for current subtype then ok to use
1439 if ( mh->cpusubtype == sHostCPUsubtype )
1440 return true;
1441 }
1442
1443 // cpu type has no ordered list of subtypes
1444 switch (mh->cputype) {
1445 case CPU_TYPE_POWERPC:
1446 // allow _ALL to be used by any client
1447 if ( mh->cpusubtype == CPU_SUBTYPE_POWERPC_ALL )
1448 return true;
1449 break;
1450 case CPU_TYPE_POWERPC64:
1451 case CPU_TYPE_I386:
1452 case CPU_TYPE_X86_64:
1453 // subtypes are not used or these architectures
1454 return true;
1455 }
1456 }
1457 }
1458 #else
1459 // For architectures that don't support cpu-sub-types
1460 // this just check the cpu type.
1461 const mach_header* mh = (mach_header*)firstPage;
1462 if ( mh->magic == sMainExecutableMachHeader->magic ) {
1463 if ( mh->cputype == sMainExecutableMachHeader->cputype ) {
1464 return true;
1465 }
1466 }
1467 #endif
1468 return false;
1469 }
1470
1471
1472
1473
1474 // The kernel maps in main executable before dyld gets control. We need to
1475 // make an ImageLoader* for the already mapped in main executable.
1476 static ImageLoader* instantiateFromLoadedImage(const struct mach_header* mh, uintptr_t slide, const char* path)
1477 {
1478 // try mach-o loader
1479 if ( isCompatibleMachO((const uint8_t*)mh) ) {
1480 ImageLoader* image = new ImageLoaderMachO(mh, slide, path, gLinkContext);
1481 addImage(image);
1482 return image;
1483 }
1484
1485 throw "main executable not a known format";
1486 }
1487
1488 #if DYLD_SHARED_CACHE_SUPPORT
1489 static ImageLoader* findSharedCacheImage(const struct stat& stat_buf, const char* path)
1490 {
1491 if ( sSharedCache != NULL ) {
1492 // walk shared cache to see if there is a cached image that matches the inode/mtime/path desired
1493 const dyld_cache_image_info* const start = (dyld_cache_image_info*)((uint8_t*)sSharedCache + sSharedCache->imagesOffset);
1494 const dyld_cache_image_info* const end = &start[sSharedCache->imagesCount];
1495 for( const dyld_cache_image_info* p = start; p != end; ++p) {
1496 // check mtime and inode first because it is fast
1497 if ( ((time_t)p->modTime == stat_buf.st_mtime) && ((ino_t)p->inode == stat_buf.st_ino) ) {
1498 // mod-time and inode match an image in the shared cache, now check path
1499 const char* pathInCache = (char*)sSharedCache + p->pathFileOffset;
1500 bool cacheHit = (strcmp(path, pathInCache) == 0);
1501 if ( ! cacheHit ) {
1502 // path does not match install name of dylib in cache, but inode and mtime does match
1503 // perhaps path is a symlink to the cached dylib
1504 struct stat pathInCacheStatBuf;
1505 if ( stat(pathInCache, &pathInCacheStatBuf) != -1 )
1506 cacheHit = ( (pathInCacheStatBuf.st_dev == stat_buf.st_dev) && (pathInCacheStatBuf.st_ino == stat_buf.st_ino) );
1507 }
1508 if ( cacheHit ) {
1509 // found image in cache, instantiate an ImageLoader with it
1510 return new ImageLoaderMachO((struct mach_header*)(p->address), pathInCache, stat_buf, gLinkContext);
1511 }
1512 }
1513 }
1514 }
1515 return NULL;
1516 }
1517 #endif
1518
1519 static ImageLoader* checkandAddImage(ImageLoader* image, const LoadContext& context)
1520 {
1521 // now sanity check that this loaded image does not have the same install path as any existing image
1522 const char* loadedImageInstallPath = image->getInstallPath();
1523 if ( image->isDylib() && (loadedImageInstallPath != NULL) && (loadedImageInstallPath[0] == '/') ) {
1524 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
1525 ImageLoader* anImage = *it;
1526 const char* installPath = anImage->getInstallPath();
1527 if ( installPath != NULL) {
1528 if ( strcmp(loadedImageInstallPath, installPath) == 0 ) {
1529 //dyld::log("duplicate(%s) => %p\n", installPath, anImage);
1530 delete image;
1531 return anImage;
1532 }
1533 }
1534 }
1535 }
1536
1537 // some API's restrict what they can load
1538 if ( context.mustBeBundle && !image->isBundle() )
1539 throw "not a bundle";
1540 if ( context.mustBeDylib && !image->isDylib() )
1541 throw "not a dylib";
1542
1543 // don't add bundles to global list, they can be loaded but not linked. When linked it will be added to list
1544 if ( ! image->isBundle() )
1545 addImage(image);
1546
1547 return image;
1548 }
1549
1550 // map in file and instantiate an ImageLoader
1551 static ImageLoader* loadPhase6(int fd, struct stat& stat_buf, const char* path, const LoadContext& context)
1552 {
1553 //dyld::log("%s(%s)\n", __func__ , path);
1554 uint64_t fileOffset = 0;
1555 uint64_t fileLength = stat_buf.st_size;
1556
1557 // validate it is a file (not directory)
1558 if ( (stat_buf.st_mode & S_IFMT) != S_IFREG )
1559 throw "not a file";
1560
1561 uint8_t firstPage[4096];
1562 bool shortPage = false;
1563
1564 // min mach-o file is 4K
1565 if ( fileLength < 4096 ) {
1566 pread(fd, firstPage, fileLength, 0);
1567 shortPage = true;
1568 }
1569 else {
1570 pread(fd, firstPage, 4096,0);
1571 }
1572
1573 // if fat wrapper, find usable sub-file
1574 const fat_header* fileStartAsFat = (fat_header*)firstPage;
1575 if ( fileStartAsFat->magic == OSSwapBigToHostInt32(FAT_MAGIC) ) {
1576 if ( fatFindBest(fileStartAsFat, &fileOffset, &fileLength) ) {
1577 pread(fd, firstPage, 4096, fileOffset);
1578 }
1579 else {
1580 throw "no matching architecture in universal wrapper";
1581 }
1582 }
1583
1584 // try mach-o loader
1585 if ( isCompatibleMachO(firstPage) ) {
1586 if ( shortPage )
1587 throw "file too short";
1588
1589 // instantiate an image
1590 ImageLoader* image = new ImageLoaderMachO(path, fd, firstPage, fileOffset, fileLength, stat_buf, gLinkContext);
1591
1592 // validate
1593 return checkandAddImage(image, context);
1594 }
1595
1596 // try other file formats here...
1597
1598
1599 // throw error about what was found
1600 switch (*(uint32_t*)firstPage) {
1601 case MH_MAGIC:
1602 case MH_CIGAM:
1603 case MH_MAGIC_64:
1604 case MH_CIGAM_64:
1605 throw "mach-o, but wrong architecture";
1606 default:
1607 throwf("unknown file type, first eight bytes: 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X",
1608 firstPage[0], firstPage[1], firstPage[2], firstPage[3], firstPage[4], firstPage[5], firstPage[6],firstPage[7]);
1609 }
1610 }
1611
1612
1613 // try to open file
1614 static ImageLoader* loadPhase5open(const char* path, const LoadContext& context, std::vector<const char*>* exceptions)
1615 {
1616 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
1617 ImageLoader* image = NULL;
1618
1619 // just return NULL if file not found, but record any other errors
1620 struct stat stat_buf;
1621 if ( stat(path, &stat_buf) == -1 ) {
1622 int err = errno;
1623 if ( err != ENOENT ) {
1624 exceptions->push_back(dyld::mkstringf("%s: stat() failed with errno=%d", path, err));
1625 }
1626 return NULL;
1627 }
1628
1629 // in case image was renamed or found via symlinks, check for inode match
1630 image = findLoadedImage(stat_buf);
1631 if ( image != NULL )
1632 return image;
1633
1634 // do nothing if not already loaded and if RTLD_NOLOAD or NSADDIMAGE_OPTION_RETURN_ONLY_IF_LOADED
1635 if ( context.dontLoad )
1636 return NULL;
1637
1638 #if DYLD_SHARED_CACHE_SUPPORT
1639 // see if this image is in shared cache
1640 image = findSharedCacheImage(stat_buf, path);
1641 if ( image != NULL ) {
1642 return checkandAddImage(image, context);
1643 }
1644 #endif
1645
1646 // open file (automagically closed when this function exits)
1647 FileOpener file(path);
1648
1649 // just return NULL if file not found
1650 if ( file.getFileDescriptor() == -1 )
1651 return NULL;
1652
1653 try {
1654 return loadPhase6(file.getFileDescriptor(), stat_buf, path, context);
1655 }
1656 catch (const char* msg) {
1657 const char* newMsg = dyld::mkstringf("%s: %s", path, msg);
1658 exceptions->push_back(newMsg);
1659 free((void*)msg);
1660 return NULL;
1661 }
1662 }
1663
1664 // look for path match with existing loaded images
1665 static ImageLoader* loadPhase5check(const char* path, const LoadContext& context)
1666 {
1667 //dyld::log("%s(%s)\n", __func__ , path);
1668 // search path against load-path and install-path of all already loaded images
1669 uint32_t hash = ImageLoader::hash(path);
1670 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
1671 ImageLoader* anImage = *it;
1672 // check has first to cut down on strcmp calls
1673 if ( anImage->getPathHash() == hash )
1674 if ( strcmp(path, anImage->getPath()) == 0 ) {
1675 // if we are looking for a dylib don't return something else
1676 if ( !context.mustBeDylib || anImage->isDylib() )
1677 return anImage;
1678 }
1679 if ( context.matchByInstallName || anImage->matchInstallPath() ) {
1680 const char* installPath = anImage->getInstallPath();
1681 if ( installPath != NULL) {
1682 if ( strcmp(path, installPath) == 0 ) {
1683 // if we are looking for a dylib don't return something else
1684 if ( !context.mustBeDylib || anImage->isDylib() )
1685 return anImage;
1686 }
1687 }
1688 }
1689 }
1690
1691 //dyld::log("%s(%s) => NULL\n", __func__, path);
1692 return NULL;
1693 }
1694
1695
1696 // open or check existing
1697 static ImageLoader* loadPhase5(const char* path, const LoadContext& context, std::vector<const char*>* exceptions)
1698 {
1699 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
1700 if ( exceptions != NULL )
1701 return loadPhase5open(path, context, exceptions);
1702 else
1703 return loadPhase5check(path, context);
1704 }
1705
1706 // try with and without image suffix
1707 static ImageLoader* loadPhase4(const char* path, const LoadContext& context, std::vector<const char*>* exceptions)
1708 {
1709 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
1710 ImageLoader* image = NULL;
1711 if ( gLinkContext.imageSuffix != NULL ) {
1712 char pathWithSuffix[strlen(path)+strlen( gLinkContext.imageSuffix)+2];
1713 ImageLoader::addSuffix(path, gLinkContext.imageSuffix, pathWithSuffix);
1714 image = loadPhase5(pathWithSuffix, context, exceptions);
1715 }
1716 if ( image == NULL )
1717 image = loadPhase5(path, context, exceptions);
1718 return image;
1719 }
1720
1721 static ImageLoader* loadPhase2(const char* path, const LoadContext& context,
1722 const char* const frameworkPaths[], const char* const libraryPaths[],
1723 std::vector<const char*>* exceptions); // forward reference
1724
1725
1726 // expand @ variables
1727 static ImageLoader* loadPhase3(const char* path, const LoadContext& context, std::vector<const char*>* exceptions)
1728 {
1729 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
1730 ImageLoader* image = NULL;
1731 if ( strncmp(path, "@executable_path/", 17) == 0 ) {
1732 // executable_path cannot be in used in any binary in a setuid process rdar://problem/4589305
1733 if ( sMainExecutableIsSetuid ) {
1734 throwf("unsafe use of @executable_path in %s with setuid binary", context.origin);
1735 }
1736 // handle @executable_path path prefix
1737 const char* executablePath = sExecPath;
1738 char newPath[strlen(executablePath) + strlen(path)];
1739 strcpy(newPath, executablePath);
1740 char* addPoint = strrchr(newPath,'/');
1741 if ( addPoint != NULL )
1742 strcpy(&addPoint[1], &path[17]);
1743 else
1744 strcpy(newPath, &path[17]);
1745 image = loadPhase4(newPath, context, exceptions);
1746 if ( image != NULL )
1747 return image;
1748
1749 // perhaps main executable path is a sym link, find realpath and retry
1750 char resolvedPath[PATH_MAX];
1751 if ( realpath(sExecPath, resolvedPath) != NULL ) {
1752 char newRealPath[strlen(resolvedPath) + strlen(path)];
1753 strcpy(newRealPath, resolvedPath);
1754 char* addPoint = strrchr(newRealPath,'/');
1755 if ( addPoint != NULL )
1756 strcpy(&addPoint[1], &path[17]);
1757 else
1758 strcpy(newRealPath, &path[17]);
1759 image = loadPhase4(newRealPath, context, exceptions);
1760 if ( image != NULL )
1761 return image;
1762 }
1763 }
1764 else if ( (strncmp(path, "@loader_path/", 13) == 0) && (context.origin != NULL) ) {
1765 // @loader_path cannot be used from the main executable of a setuid process rdar://problem/4589305
1766 if ( sMainExecutableIsSetuid && (strcmp(context.origin, sExecPath) == 0) )
1767 throwf("unsafe use of @loader_path in %s with setuid binary", context.origin);
1768
1769 // handle @loader_path path prefix
1770 char newPath[strlen(context.origin) + strlen(path)];
1771 strcpy(newPath, context.origin);
1772 char* addPoint = strrchr(newPath,'/');
1773 if ( addPoint != NULL )
1774 strcpy(&addPoint[1], &path[13]);
1775 else
1776 strcpy(newPath, &path[13]);
1777 image = loadPhase4(newPath, context, exceptions);
1778 if ( image != NULL )
1779 return image;
1780
1781 // perhaps loader path is a sym link, find realpath and retry
1782 char resolvedPath[PATH_MAX];
1783 if ( realpath(context.origin, resolvedPath) != NULL ) {
1784 char newRealPath[strlen(resolvedPath) + strlen(path)];
1785 strcpy(newRealPath, resolvedPath);
1786 char* addPoint = strrchr(newRealPath,'/');
1787 if ( addPoint != NULL )
1788 strcpy(&addPoint[1], &path[13]);
1789 else
1790 strcpy(newRealPath, &path[13]);
1791 image = loadPhase4(newRealPath, context, exceptions);
1792 if ( image != NULL )
1793 return image;
1794 }
1795 }
1796 else if ( context.implicitRPath || (strncmp(path, "@rpath/", 7) == 0) ) {
1797 const char* trailingPath = (strncmp(path, "@rpath/", 7) == 0) ? &path[7] : path;
1798 // substitute @rpath with all -rpath paths up the load chain
1799 for(const ImageLoader::RPathChain* rp=context.rpath; rp != NULL; rp=rp->next) {
1800 if (rp->paths != NULL ) {
1801 for(std::vector<const char*>::iterator it=rp->paths->begin(); it != rp->paths->end(); ++it) {
1802 const char* anRPath = *it;
1803 char newPath[strlen(anRPath) + strlen(trailingPath)+2];
1804 strcpy(newPath, anRPath);
1805 strcat(newPath, "/");
1806 strcat(newPath, trailingPath);
1807 image = loadPhase4(newPath, context, exceptions);
1808 if ( image != NULL )
1809 return image;
1810 }
1811 }
1812 }
1813
1814 // substitute @rpath with LD_LIBRARY_PATH
1815 if ( sEnv.LD_LIBRARY_PATH != NULL ) {
1816 image = loadPhase2(trailingPath, context, NULL, sEnv.LD_LIBRARY_PATH, exceptions);
1817 if ( image != NULL )
1818 return image;
1819 }
1820
1821 // if this is the "open" pass, don't try to open @rpath/... as a relative path
1822 if ( (exceptions != NULL) && (trailingPath != path) )
1823 return NULL;
1824 }
1825 else if ( sMainExecutableIsSetuid && (path[0] != '/') ) {
1826 throwf("unsafe use of relative rpath %s in %s with setuid binary", path, context.origin);
1827 }
1828
1829 return loadPhase4(path, context, exceptions);
1830 }
1831
1832
1833 // try search paths
1834 static ImageLoader* loadPhase2(const char* path, const LoadContext& context,
1835 const char* const frameworkPaths[], const char* const libraryPaths[],
1836 std::vector<const char*>* exceptions)
1837 {
1838 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
1839 ImageLoader* image = NULL;
1840 const char* frameworkPartialPath = getFrameworkPartialPath(path);
1841 if ( frameworkPaths != NULL ) {
1842 if ( frameworkPartialPath != NULL ) {
1843 const int frameworkPartialPathLen = strlen(frameworkPartialPath);
1844 for(const char* const* fp = frameworkPaths; *fp != NULL; ++fp) {
1845 char npath[strlen(*fp)+frameworkPartialPathLen+8];
1846 strcpy(npath, *fp);
1847 strcat(npath, "/");
1848 strcat(npath, frameworkPartialPath);
1849 //dyld::log("dyld: fallback framework path used: %s() -> loadPhase4(\"%s\", ...)\n", __func__, npath);
1850 image = loadPhase4(npath, context, exceptions);
1851 if ( image != NULL )
1852 return image;
1853 }
1854 }
1855 }
1856 if ( libraryPaths != NULL ) {
1857 const char* libraryLeafName = getLibraryLeafName(path);
1858 const int libraryLeafNameLen = strlen(libraryLeafName);
1859 for(const char* const* lp = libraryPaths; *lp != NULL; ++lp) {
1860 char libpath[strlen(*lp)+libraryLeafNameLen+8];
1861 strcpy(libpath, *lp);
1862 strcat(libpath, "/");
1863 strcat(libpath, libraryLeafName);
1864 //dyld::log("dyld: fallback library path used: %s() -> loadPhase4(\"%s\", ...)\n", __func__, libpath);
1865 image = loadPhase4(libpath, context, exceptions);
1866 if ( image != NULL )
1867 return image;
1868 }
1869 }
1870 return NULL;
1871 }
1872
1873 // try search overrides and fallbacks
1874 static ImageLoader* loadPhase1(const char* path, const LoadContext& context, std::vector<const char*>* exceptions)
1875 {
1876 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
1877 ImageLoader* image = NULL;
1878
1879 // handle LD_LIBRARY_PATH environment variables that force searching
1880 if ( context.useLdLibraryPath && (sEnv.LD_LIBRARY_PATH != NULL) ) {
1881 image = loadPhase2(path, context, NULL, sEnv.LD_LIBRARY_PATH, exceptions);
1882 if ( image != NULL )
1883 return image;
1884 }
1885
1886 // handle DYLD_ environment variables that force searching
1887 if ( context.useSearchPaths && ((sEnv.DYLD_FRAMEWORK_PATH != NULL) || (sEnv.DYLD_LIBRARY_PATH != NULL)) ) {
1888 image = loadPhase2(path, context, sEnv.DYLD_FRAMEWORK_PATH, sEnv.DYLD_LIBRARY_PATH, exceptions);
1889 if ( image != NULL )
1890 return image;
1891 }
1892
1893 // try raw path
1894 image = loadPhase3(path, context, exceptions);
1895 if ( image != NULL )
1896 return image;
1897
1898 // try fallback paths during second time (will open file)
1899 if ( !context.dontLoad && (exceptions != NULL) && ((sEnv.DYLD_FALLBACK_FRAMEWORK_PATH != NULL) || (sEnv.DYLD_FALLBACK_LIBRARY_PATH != NULL)) ) {
1900 image = loadPhase2(path, context, sEnv.DYLD_FALLBACK_FRAMEWORK_PATH, sEnv.DYLD_FALLBACK_LIBRARY_PATH, exceptions);
1901 if ( image != NULL )
1902 return image;
1903 }
1904
1905 return NULL;
1906 }
1907
1908 // try root substitutions
1909 static ImageLoader* loadPhase0(const char* path, const LoadContext& context, std::vector<const char*>* exceptions)
1910 {
1911 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
1912
1913 // handle DYLD_ROOT_PATH which forces absolute paths to use a new root
1914 if ( (sEnv.DYLD_ROOT_PATH != NULL) && (path[0] == '/') ) {
1915 for(const char* const* rootPath = sEnv.DYLD_ROOT_PATH ; *rootPath != NULL; ++rootPath) {
1916 char newPath[strlen(*rootPath) + strlen(path)+2];
1917 strcpy(newPath, *rootPath);
1918 strcat(newPath, path);
1919 ImageLoader* image = loadPhase1(newPath, context, exceptions);
1920 if ( image != NULL )
1921 return image;
1922 }
1923 }
1924
1925 // try raw path
1926 return loadPhase1(path, context, exceptions);
1927 }
1928
1929 //
1930 // Given all the DYLD_ environment variables, the general case for loading libraries
1931 // is that any given path expands into a list of possible locations to load. We
1932 // also must take care to ensure two copies of the "same" library are never loaded.
1933 //
1934 // The algorithm used here is that there is a separate function for each "phase" of the
1935 // path expansion. Each phase function calls the next phase with each possible expansion
1936 // of that phase. The result is the last phase is called with all possible paths.
1937 //
1938 // To catch duplicates the algorithm is run twice. The first time, the last phase checks
1939 // the path against all loaded images. The second time, the last phase calls open() on
1940 // the path. Either time, if an image is found, the phases all unwind without checking
1941 // for other paths.
1942 //
1943 ImageLoader* load(const char* path, const LoadContext& context)
1944 {
1945 //dyld::log("%s(%s)\n", __func__ , path);
1946 char realPath[PATH_MAX];
1947 // when DYLD_IMAGE_SUFFIX is in used, do a realpath(), otherwise a load of "Foo.framework/Foo" will not match
1948 if ( context.useSearchPaths && ( gLinkContext.imageSuffix != NULL) ) {
1949 if ( realpath(path, realPath) != NULL )
1950 path = realPath;
1951 }
1952
1953 // try all path permutations and check against existing loaded images
1954 ImageLoader* image = loadPhase0(path, context, NULL);
1955 if ( image != NULL )
1956 return image;
1957
1958 // try all path permutations and try open() until first sucesss
1959 std::vector<const char*> exceptions;
1960 image = loadPhase0(path, context, &exceptions);
1961 if ( image != NULL )
1962 return image;
1963 else if ( exceptions.size() == 0 )
1964 throw "image not found";
1965 else {
1966 const char* msgStart = "no suitable image found. Did find:";
1967 const char* delim = "\n\t";
1968 size_t allsizes = strlen(msgStart)+8;
1969 for (unsigned int i=0; i < exceptions.size(); ++i)
1970 allsizes += (strlen(exceptions[i]) + strlen(delim));
1971 char* fullMsg = new char[allsizes];
1972 strcpy(fullMsg, msgStart);
1973 for (unsigned int i=0; i < exceptions.size(); ++i) {
1974 strcat(fullMsg, delim);
1975 strcat(fullMsg, exceptions[i]);
1976 free((void*)exceptions[i]);
1977 }
1978 throw (const char*)fullMsg;
1979 }
1980 }
1981
1982
1983
1984
1985 #if DYLD_SHARED_CACHE_SUPPORT
1986
1987
1988 // hack until dyld no longer needs to run on Leopard kernels that don't have new shared region syscall
1989 static bool newSharedRegionSyscallAvailable()
1990 {
1991 int shreg_version;
1992 size_t buffer_size = sizeof(shreg_version);
1993 if ( sysctlbyname("vm.shared_region_version", &shreg_version, &buffer_size, NULL, 0) == 0 ) {
1994 if ( shreg_version == 3 )
1995 return true;
1996 }
1997 return false;
1998 }
1999
2000
2001 static int __attribute__((noinline)) _shared_region_check_np(uint64_t* start_address)
2002 {
2003 if ( (gLinkContext.sharedRegionMode == ImageLoader::kUseSharedRegion) && newSharedRegionSyscallAvailable() )
2004 return syscall(294, start_address);
2005 return -1;
2006 }
2007
2008
2009 static int __attribute__((noinline)) _shared_region_map_np(int fd, uint32_t count, const shared_file_mapping_np mappings[])
2010 {
2011 int result;
2012 if ( (gLinkContext.sharedRegionMode == ImageLoader::kUseSharedRegion) && newSharedRegionSyscallAvailable() ) {
2013 return syscall(295, fd, count, mappings);
2014 }
2015
2016 // remove the shared region sub-map
2017 #if __ppc__ || __i386__
2018 vm_address_t addr = (vm_address_t)0x90000000;
2019 vm_deallocate(mach_task_self(), addr, 0x20000000);
2020 #elif __ppc64__ || __x86_64__
2021 vm_address_t addr = (vm_address_t)0x7FFF60000000;
2022 vm_deallocate(mach_task_self(), addr, 0x80000000);
2023 #endif
2024
2025 // map cache just for this process with mmap()
2026 bool failed = false;
2027 const shared_file_mapping_np* start = mappings;
2028 const shared_file_mapping_np* end = &mappings[count];
2029 for (const shared_file_mapping_np* p = start; p < end; ++p ) {
2030 void* mmapAddress = (void*)(uintptr_t)(p->sfm_address);
2031 size_t size = p->sfm_size;
2032 int protection = 0;
2033 if ( p->sfm_init_prot & VM_PROT_EXECUTE )
2034 protection |= PROT_EXEC;
2035 if ( p->sfm_init_prot & VM_PROT_READ )
2036 protection |= PROT_READ;
2037 if ( p->sfm_init_prot & VM_PROT_WRITE )
2038 protection |= PROT_WRITE;
2039 off_t offset = p->sfm_file_offset;
2040 mmapAddress = mmap(mmapAddress, size, protection, MAP_FIXED | MAP_PRIVATE, fd, offset);
2041 if ( mmap(mmapAddress, size, protection, MAP_FIXED | MAP_PRIVATE, fd, offset) != mmapAddress )
2042 failed = true;
2043 }
2044 if ( !failed ) {
2045 result = 0;
2046 gLinkContext.sharedRegionMode = ImageLoader::kUsePrivateSharedRegion;
2047 }
2048 else {
2049 result = -1;
2050 gLinkContext.sharedRegionMode = ImageLoader::kDontUseSharedRegion;
2051 if ( gLinkContext.verboseMapping )
2052 dyld::log("dyld: shared cached cannot be mapped\n");
2053 }
2054
2055 return result;
2056 }
2057
2058
2059
2060 #if __ppc__
2061 #define ARCH_NAME "ppc"
2062 #define ARCH_NAME_ROSETTA "rosetta"
2063 #define ARCH_VALUE CPU_TYPE_POWERPC
2064 #define ARCH_CACHE_MAGIC "dyld_v1 ppc"
2065 #elif __ppc64__
2066 #define ARCH_NAME "ppc64"
2067 #define ARCH_VALUE CPU_TYPE_POWERPC64
2068 #define ARCH_CACHE_MAGIC "dyld_v1 ppc64"
2069 #elif __i386__
2070 #define ARCH_NAME "i386"
2071 #define ARCH_VALUE CPU_TYPE_I386
2072 #define ARCH_CACHE_MAGIC "dyld_v1 i386"
2073 #elif __x86_64__
2074 #define ARCH_NAME "x86_64"
2075 #define ARCH_VALUE CPU_TYPE_X86_64
2076 #define ARCH_CACHE_MAGIC "dyld_v1 x86_64"
2077 #endif
2078
2079
2080 static void mapSharedCache()
2081 {
2082 uint64_t cacheBaseAddress;
2083 // quick check if a cache is alreay mapped into shared region
2084 if ( _shared_region_check_np(&cacheBaseAddress) == 0 ) {
2085 sSharedCache = (dyld_cache_header*)cacheBaseAddress;
2086 // if we don't understand the currently mapped shared cache, then ignore
2087 if ( strcmp(sSharedCache->magic, ARCH_CACHE_MAGIC) != 0 ) {
2088 sSharedCache = NULL;
2089 if ( gLinkContext.verboseMapping )
2090 dyld::log("dyld: existing shared cached in memory is not compatible\n");
2091 }
2092 }
2093 else {
2094 // map in shared cache to shared region
2095 int fd;
2096 #if __ppc__
2097 // rosetta cannot handle optimized _ppc cache, so it use _rosetta cache instead, rdar://problem/5495438
2098 if ( isRosetta() )
2099 fd = open(DYLD_SHARED_CACHE_DIR DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME_ROSETTA, O_RDONLY);
2100 else
2101 #endif
2102 fd = open(DYLD_SHARED_CACHE_DIR DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME, O_RDONLY);
2103 if ( fd != -1 ) {
2104 uint8_t firstPage[4096];
2105 if ( ::read(fd, firstPage, 4096) == 4096 ) {
2106 dyld_cache_header* header = (dyld_cache_header*)firstPage;
2107 if ( strcmp(header->magic, ARCH_CACHE_MAGIC) == 0 ) {
2108 const shared_file_mapping_np* mappings = (shared_file_mapping_np*)&firstPage[header->mappingOffset];
2109 const shared_file_mapping_np* const end = &mappings[header->mappingCount];
2110 // validate that the cache file has not been truncated
2111 bool goodCache = false;
2112 struct stat stat_buf;
2113 if ( fstat(fd, &stat_buf) == 0 ) {
2114 goodCache = true;
2115 for (const shared_file_mapping_np* p = mappings; p < end; ++p) {
2116 if ( p->sfm_file_offset+p->sfm_size > (uint64_t)stat_buf.st_size )
2117 goodCache = false;
2118 }
2119 }
2120 if ( goodCache ) {
2121 const shared_file_mapping_np* mappings = (shared_file_mapping_np*)&firstPage[header->mappingOffset];
2122 if (_shared_region_map_np(fd, header->mappingCount, mappings) == 0) {
2123 // sucessfully mapped cache into shared region
2124 sSharedCache = (dyld_cache_header*)mappings[0].sfm_address;
2125 }
2126 }
2127 else {
2128 gSharedCacheNeedsUpdating = true;
2129 dyld::log("dyld: shared cached file is corrupt: " DYLD_SHARED_CACHE_DIR DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME "\n");
2130 }
2131 }
2132 else {
2133 gSharedCacheNeedsUpdating = true;
2134 if ( gLinkContext.verboseMapping )
2135 dyld::log("dyld: shared cached file is invalid\n");
2136 }
2137 }
2138 else {
2139 gSharedCacheNeedsUpdating = true;
2140 if ( gLinkContext.verboseMapping )
2141 dyld::log("dyld: shared cached file cannot be read\n");
2142 }
2143 close(fd);
2144 }
2145 else {
2146 gSharedCacheNotFound = true;
2147 if ( gLinkContext.verboseMapping )
2148 dyld::log("dyld: shared cached file cannot be opened\n");
2149 }
2150 }
2151
2152 // remember if dyld loaded at same address as when cache built
2153 if ( sSharedCache != NULL ) {
2154 gLinkContext.dyldLoadedAtSameAddressNeededBySharedCache = ((uintptr_t)(sSharedCache->dyldBaseAddress) == (uintptr_t)&_mh_dylinker_header);
2155 }
2156
2157 // tell gdb where the shared cache is
2158 if ( sSharedCache != NULL ) {
2159 const shared_file_mapping_np* const start = (shared_file_mapping_np*)((uint8_t*)sSharedCache + sSharedCache->mappingOffset);
2160 dyld_shared_cache_ranges.sharedRegionsCount = sSharedCache->mappingCount;
2161 // only room to tell gdb about first four regions
2162 if ( dyld_shared_cache_ranges.sharedRegionsCount > 4 )
2163 dyld_shared_cache_ranges.sharedRegionsCount = 4;
2164 if ( gLinkContext.verboseMapping ) {
2165 if ( gLinkContext.sharedRegionMode == ImageLoader::kUseSharedRegion )
2166 dyld::log("dyld: Mapping shared cache\n");
2167 else if ( gLinkContext.sharedRegionMode == ImageLoader::kUsePrivateSharedRegion )
2168 dyld::log("dyld: Mapping private shared cache\n");
2169 }
2170 const shared_file_mapping_np* const end = &start[dyld_shared_cache_ranges.sharedRegionsCount];
2171 int index = 0;
2172 for (const shared_file_mapping_np* p = start; p < end; ++p, ++index ) {
2173 dyld_shared_cache_ranges.ranges[index].start = p->sfm_address;
2174 dyld_shared_cache_ranges.ranges[index].length = p->sfm_size;
2175 if ( gLinkContext.verboseMapping ) {
2176 dyld::log(" 0x%08llX->0x%08llX %s%s%s init=%x, max=%x\n", p->sfm_address, p->sfm_address+p->sfm_size-1,
2177 ((p->sfm_init_prot & VM_PROT_READ) ? "read " : ""),
2178 ((p->sfm_init_prot & VM_PROT_WRITE) ? "write " : ""),
2179 ((p->sfm_init_prot & VM_PROT_EXECUTE) ? "execute " : ""), p->sfm_init_prot, p->sfm_max_prot);
2180 }
2181 #if __i386__
2182 // record if a non-writable and executable region is found in the R/W shared region
2183 // this is the __IMPORT segments. dyld will turn write protection on and off as needed
2184 if ( (p->sfm_init_prot == (VM_PROT_READ|VM_PROT_EXECUTE)) && ((p->sfm_address & 0xF0000000) == 0xA0000000) ) {
2185 sImportSegmentsStart = p->sfm_address;
2186 sImportSegmentsSize = p->sfm_size;
2187 makeSharedCacheImportSegmentsWritable(true);
2188 }
2189 #endif
2190 }
2191
2192 }
2193 }
2194 #endif // #if DYLD_SHARED_CACHE_SUPPORT
2195
2196
2197
2198 // create when NSLinkModule is called for a second time on a bundle
2199 ImageLoader* cloneImage(ImageLoader* image)
2200 {
2201 const uint64_t offsetInFat = image->getOffsetInFatFile();
2202
2203 // open file (automagically closed when this function exits)
2204 FileOpener file(image->getPath());
2205
2206 struct stat stat_buf;
2207 if ( fstat(file.getFileDescriptor(), &stat_buf) == -1)
2208 throw "stat error";
2209
2210 // read first page of file
2211 uint8_t firstPage[4096];
2212 pread(file.getFileDescriptor(), firstPage, 4096, offsetInFat);
2213
2214 // fat length is only used for sanity checking, since this image was already loaded once, just use upper bound
2215 uint64_t lenInFat = stat_buf.st_size - offsetInFat;
2216
2217 // try mach-o loader
2218 if ( isCompatibleMachO(firstPage) ) {
2219 ImageLoader* clone = new ImageLoaderMachO(image->getPath(), file.getFileDescriptor(), firstPage, offsetInFat, lenInFat, stat_buf, gLinkContext);
2220 // don't add bundles to global list, they can be loaded but not linked. When linked it will be added to list
2221 if ( ! image->isBundle() )
2222 addImage(clone);
2223 return clone;
2224 }
2225
2226 // try other file formats...
2227 throw "can't clone image";
2228 }
2229
2230
2231 ImageLoader* loadFromMemory(const uint8_t* mem, uint64_t len, const char* moduleName)
2232 {
2233 // if fat wrapper, find usable sub-file
2234 const fat_header* memStartAsFat = (fat_header*)mem;
2235 uint64_t fileOffset = 0;
2236 uint64_t fileLength = len;
2237 if ( memStartAsFat->magic == OSSwapBigToHostInt32(FAT_MAGIC) ) {
2238 if ( fatFindBest(memStartAsFat, &fileOffset, &fileLength) ) {
2239 mem = &mem[fileOffset];
2240 len = fileLength;
2241 }
2242 else {
2243 throw "no matching architecture in universal wrapper";
2244 }
2245 }
2246
2247 // try each loader
2248 if ( isCompatibleMachO(mem) ) {
2249 ImageLoader* image = new ImageLoaderMachO(moduleName, (mach_header*)mem, len, gLinkContext);
2250 // don't add bundles to global list, they can be loaded but not linked. When linked it will be added to list
2251 if ( ! image->isBundle() )
2252 addImage(image);
2253 return image;
2254 }
2255
2256 // try other file formats here...
2257
2258 // throw error about what was found
2259 switch (*(uint32_t*)mem) {
2260 case MH_MAGIC:
2261 case MH_CIGAM:
2262 case MH_MAGIC_64:
2263 case MH_CIGAM_64:
2264 throw "mach-o, but wrong architecture";
2265 default:
2266 throwf("unknown file type, first eight bytes: 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X",
2267 mem[0], mem[1], mem[2], mem[3], mem[4], mem[5], mem[6],mem[7]);
2268 }
2269 }
2270
2271
2272 void registerAddCallback(ImageCallback func)
2273 {
2274 // now add to list to get notified when any more images are added
2275 sAddImageCallbacks.push_back(func);
2276
2277 // call callback with all existing images
2278 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
2279 ImageLoader* image = *it;
2280 if ( image->getState() >= dyld_image_state_bound && image->getState() < dyld_image_state_terminated )
2281 (*func)(image->machHeader(), image->getSlide());
2282 }
2283 }
2284
2285 void registerRemoveCallback(ImageCallback func)
2286 {
2287 sRemoveImageCallbacks.push_back(func);
2288 }
2289
2290 void clearErrorMessage()
2291 {
2292 error_string[0] = '\0';
2293 }
2294
2295 void setErrorMessage(const char* message)
2296 {
2297 // save off error message in global buffer for CrashReporter to find
2298 strncpy(error_string, message, sizeof(error_string)-1);
2299 error_string[sizeof(error_string)-1] = '\0';
2300 }
2301
2302 const char* getErrorMessage()
2303 {
2304 return error_string;
2305 }
2306
2307
2308 void halt(const char* message)
2309 {
2310 dyld::log("dyld: %s\n", message);
2311 setErrorMessage(message);
2312 strncpy(error_string, message, sizeof(error_string)-1);
2313 error_string[sizeof(error_string)-1] = '\0';
2314 dyld_fatal_error(error_string);
2315 }
2316
2317
2318 uintptr_t bindLazySymbol(const mach_header* mh, uintptr_t* lazyPointer)
2319 {
2320 uintptr_t result = 0;
2321 // acquire read-lock on dyld's data structures
2322 #if 0 // rdar://problem/3811777 turn off locking until deadlock is resolved
2323 if ( gLibSystemHelpers != NULL )
2324 (*gLibSystemHelpers->lockForReading)();
2325 #endif
2326 // lookup and bind lazy pointer and get target address
2327 try {
2328 ImageLoader* target;
2329 #if __i386__
2330 // fast stubs pass NULL for mh and image is instead found via the location of stub (aka lazyPointer)
2331 if ( mh == NULL )
2332 target = dyld::findImageContainingAddressThreadSafe(lazyPointer);
2333 else
2334 target = dyld::findImageByMachHeader(mh);
2335 #else
2336 // note, target should always be mach-o, because only mach-o lazy handler wired up to this
2337 target = dyld::findImageByMachHeader(mh);
2338 #endif
2339 if ( target == NULL )
2340 throwf("image not found for lazy pointer at %p", lazyPointer);
2341 result = target->doBindLazySymbol(lazyPointer, gLinkContext);
2342 }
2343 catch (const char* message) {
2344 dyld::log("dyld: lazy symbol binding failed: %s\n", message);
2345 halt(message);
2346 }
2347 // release read-lock on dyld's data structures
2348 #if 0
2349 if ( gLibSystemHelpers != NULL )
2350 (*gLibSystemHelpers->unlockForReading)();
2351 #endif
2352 // return target address to glue which jumps to it with real parameters restored
2353 return result;
2354 }
2355
2356
2357 // SPI used by ZeroLink to lazy load bundles
2358 void registerZeroLinkHandlers(BundleNotificationCallBack notify, BundleLocatorCallBack locate)
2359 {
2360 sBundleNotifier = notify;
2361 sBundleLocation = locate;
2362 }
2363
2364 void registerUndefinedHandler(UndefinedHandler handler)
2365 {
2366 sUndefinedHandler = handler;
2367 }
2368
2369 static void undefinedHandler(const char* symboName)
2370 {
2371 if ( sUndefinedHandler != NULL ) {
2372 (*sUndefinedHandler)(symboName);
2373 }
2374 }
2375
2376 static bool findExportedSymbol(const char* name, bool onlyInCoalesced, const ImageLoader::Symbol** sym, const ImageLoader** image)
2377 {
2378 // try ZeroLink short cut to finding bundle which exports this symbol
2379 if ( sBundleLocation != NULL ) {
2380 ImageLoader* zlImage = (*sBundleLocation)(name);
2381 if ( zlImage == ((ImageLoader*)(-1)) ) {
2382 // -1 is magic value that request symbol is in a bundle not yet linked into process
2383 // try calling handler to link in that symbol
2384 undefinedHandler(name);
2385 // call locator again
2386 zlImage = (*sBundleLocation)(name);
2387 }
2388 // if still not found, then ZeroLink has no idea where to find it
2389 if ( zlImage == ((ImageLoader*)(-1)) )
2390 return false;
2391 if ( zlImage != NULL ) {
2392 // ZeroLink cache knows where the symbol is
2393 if ( onlyInCoalesced ) {
2394 // but ZeroLink does not know about coalescing weak symbols, so ignore ZeroLink's hint when onlyInCoalesced==true
2395 }
2396 else {
2397 *sym = zlImage->findExportedSymbol(name, NULL, false, image);
2398 if ( *sym != NULL ) {
2399 *image = zlImage;
2400 return true;
2401 }
2402 }
2403 }
2404 else {
2405 // ZeroLink says it is in some bundle already loaded, but not linked, walk them all
2406 const unsigned int imageCount = sAllImages.size();
2407 for(unsigned int i=0; i < imageCount; ++i){
2408 ImageLoader* anImage = sAllImages[i];
2409 if ( anImage->isBundle() && !anImage->hasHiddenExports() ) {
2410 //dyld::log("dyld: search for %s in %s\n", name, anImage->getPath());
2411 *sym = anImage->findExportedSymbol(name, NULL, false, image);
2412 if ( *sym != NULL ) {
2413 return true;
2414 }
2415 }
2416 }
2417 }
2418 }
2419
2420 // search all images in order
2421 const ImageLoader* firstWeakImage = NULL;
2422 const ImageLoader::Symbol* firstWeakSym = NULL;
2423 const unsigned int imageCount = sAllImages.size();
2424 for(unsigned int i=0; i < imageCount; ++i) {
2425 ImageLoader* anImage = sAllImages[i];
2426 // the use of inserted libraries alters search order
2427 // so that inserted libraries are found before the main executable
2428 if ( sInsertedDylibCount > 0 ) {
2429 if ( i < sInsertedDylibCount )
2430 anImage = sAllImages[i+1];
2431 else if ( i == sInsertedDylibCount )
2432 anImage = sAllImages[0];
2433 }
2434 if ( ! anImage->hasHiddenExports() && (!onlyInCoalesced || anImage->hasCoalescedExports()) ) {
2435 *sym = anImage->findExportedSymbol(name, NULL, false, image);
2436 if ( *sym != NULL ) {
2437 // if weak definition found, record first one found
2438 if ( ((*image)->getExportedSymbolInfo(*sym) & ImageLoader::kWeakDefinition) != 0 ) {
2439 if ( firstWeakImage == NULL ) {
2440 firstWeakImage = *image;
2441 firstWeakSym = *sym;
2442 }
2443 }
2444 else {
2445 // found non-weak, so immediately return with it
2446 return true;
2447 }
2448 }
2449 }
2450 }
2451 if ( firstWeakSym != NULL ) {
2452 // found a weak definition, but no non-weak, so return first weak found
2453 *sym = firstWeakSym;
2454 *image = firstWeakImage;
2455 return true;
2456 }
2457
2458 return false;
2459 }
2460
2461 bool flatFindExportedSymbol(const char* name, const ImageLoader::Symbol** sym, const ImageLoader** image)
2462 {
2463 return findExportedSymbol(name, false, sym, image);
2464 }
2465
2466 bool findCoalescedExportedSymbol(const char* name, const ImageLoader::Symbol** sym, const ImageLoader** image)
2467 {
2468 return findExportedSymbol(name, true, sym, image);
2469 }
2470
2471
2472 bool flatFindExportedSymbolWithHint(const char* name, const char* librarySubstring, const ImageLoader::Symbol** sym, const ImageLoader** image)
2473 {
2474 // search all images in order
2475 const unsigned int imageCount = sAllImages.size();
2476 for(unsigned int i=0; i < imageCount; ++i){
2477 ImageLoader* anImage = sAllImages[i];
2478 // only look at images whose paths contain the hint string (NULL hint string is wildcard)
2479 if ( ! anImage->isBundle() && ((librarySubstring==NULL) || (strstr(anImage->getPath(), librarySubstring) != NULL)) ) {
2480 *sym = anImage->findExportedSymbol(name, NULL, false, image);
2481 if ( *sym != NULL ) {
2482 return true;
2483 }
2484 }
2485 }
2486 return false;
2487 }
2488
2489 static ImageLoader::MappedRegion* getMappedRegions(ImageLoader::MappedRegion* regions)
2490 {
2491 ImageLoader::MappedRegion* end = regions;
2492 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
2493 (*it)->getMappedRegions(end);
2494 }
2495 return end;
2496 }
2497
2498 void registerImageStateSingleChangeHandler(dyld_image_states state, dyld_image_state_change_handler handler)
2499 {
2500 // mark the image that the handler is in as never-unload because dyld has a reference into it
2501 ImageLoader* handlerImage = findImageContainingAddress((void*)handler);
2502 if ( handlerImage != NULL )
2503 handlerImage->setNeverUnload();
2504
2505 // add to list of handlers
2506 std::vector<dyld_image_state_change_handler>* handlers = stateToHandlers(state, sSingleHandlers);
2507 if ( handlers != NULL ) {
2508 handlers->push_back(handler);
2509
2510 // call callback with all existing images
2511 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
2512 ImageLoader* image = *it;
2513 dyld_image_info info;
2514 info.imageLoadAddress = image->machHeader();
2515 info.imageFilePath = image->getPath();
2516 info.imageFileModDate = image->lastModified();
2517 // should only call handler if state == image->state
2518 if ( image->getState() == state )
2519 (*handler)(state, 1, &info);
2520 // ignore returned string, too late to do anything
2521 }
2522 }
2523 }
2524
2525 void registerImageStateBatchChangeHandler(dyld_image_states state, dyld_image_state_change_handler handler)
2526 {
2527 // mark the image that the handler is in as never-unload because dyld has a reference into it
2528 ImageLoader* handlerImage = findImageContainingAddress((void*)handler);
2529 if ( handlerImage != NULL )
2530 handlerImage->setNeverUnload();
2531
2532 // add to list of handlers
2533 std::vector<dyld_image_state_change_handler>* handlers = stateToHandlers(state, sBatchHandlers);
2534 if ( handlers != NULL ) {
2535 // insert at front, so that gdb handler is always last
2536 handlers->insert(handlers->begin(), handler);
2537
2538 // call callback with all existing images
2539 try {
2540 notifyBatchPartial(state, true, handler);
2541 }
2542 catch (const char* msg) {
2543 // ignore request to abort during registration
2544 }
2545 }
2546 }
2547
2548 static ImageLoader* libraryLocator(const char* libraryName, bool search, bool findDLL, const char* origin, const ImageLoader::RPathChain* rpaths)
2549 {
2550 dyld::LoadContext context;
2551 context.useSearchPaths = search;
2552 context.useLdLibraryPath = false;
2553 context.implicitRPath = false;
2554 context.matchByInstallName = false;
2555 context.dontLoad = false;
2556 context.mustBeBundle = false;
2557 context.mustBeDylib = true;
2558 context.findDLL = findDLL;
2559 context.origin = origin;
2560 context.rpath = rpaths;
2561 return load(libraryName, context);
2562 }
2563
2564 static const char* basename(const char* path)
2565 {
2566 const char* last = path;
2567 for (const char* s = path; *s != '\0'; s++) {
2568 if (*s == '/')
2569 last = s+1;
2570 }
2571 return last;
2572 }
2573
2574 static void setContext(const struct mach_header* mainExecutableMH, int argc, const char* argv[], const char* envp[], const char* apple[])
2575 {
2576 gLinkContext.loadLibrary = &libraryLocator;
2577 gLinkContext.terminationRecorder = &terminationRecorder;
2578 gLinkContext.flatExportFinder = &flatFindExportedSymbol;
2579 gLinkContext.coalescedExportFinder = &findCoalescedExportedSymbol;
2580 gLinkContext.undefinedHandler = &undefinedHandler;
2581 #if IMAGE_NOTIFY_SUPPORT
2582 gLinkContext.addImageNeedingNotification = &addImageNeedingNotification;
2583 gLinkContext.notifyAdding = &notifyAdding;
2584 #endif
2585 gLinkContext.getAllMappedRegions = &getMappedRegions;
2586 gLinkContext.bindingHandler = NULL;
2587 gLinkContext.notifySingle = &notifySingle;
2588 gLinkContext.notifyBatch = &notifyBatch;
2589 gLinkContext.removeImage = &removeImage;
2590 gLinkContext.registerDOFs = &registerDOFs;
2591 gLinkContext.clearAllDepths = &clearAllDepths;
2592 gLinkContext.imageCount = &imageCount;
2593 gLinkContext.notifySharedCacheInvalid= &notifySharedCacheInvalid;
2594 #if __i386__
2595 gLinkContext.makeSharedCacheImportSegmentsWritable = &makeSharedCacheImportSegmentsWritable;
2596 #endif
2597 gLinkContext.setNewProgramVars = &setNewProgramVars;
2598 #if SUPPORT_OLD_CRT_INITIALIZATION
2599 gLinkContext.setRunInitialzersOldWay= &setRunInitialzersOldWay;
2600 #endif
2601 gLinkContext.bindingOptions = ImageLoader::kBindingNone;
2602 gLinkContext.argc = argc;
2603 gLinkContext.argv = argv;
2604 gLinkContext.envp = envp;
2605 gLinkContext.apple = apple;
2606 gLinkContext.progname = (argv[0] != NULL) ? basename(argv[0]) : "";
2607 gLinkContext.programVars.mh = mainExecutableMH;
2608 gLinkContext.programVars.NXArgcPtr = &gLinkContext.argc;
2609 gLinkContext.programVars.NXArgvPtr = &gLinkContext.argv;
2610 gLinkContext.programVars.environPtr = &gLinkContext.envp;
2611 gLinkContext.programVars.__prognamePtr=&gLinkContext.progname;
2612 gLinkContext.mainExecutable = NULL;
2613 gLinkContext.imageSuffix = NULL;
2614 gLinkContext.prebindUsage = ImageLoader::kUseAllPrebinding;
2615 gLinkContext.sharedRegionMode = ImageLoader::kUseSharedRegion;
2616 }
2617
2618 #if __ppc__ || __i386__
2619 bool isRosetta()
2620 {
2621 int mib[] = { CTL_KERN, KERN_CLASSIC, getpid() };
2622 int is_classic = 0;
2623 size_t len = sizeof(int);
2624 int ret = sysctl(mib, 3, &is_classic, &len, NULL, 0);
2625 if ((ret != -1) && is_classic) {
2626 // we're running under Rosetta
2627 return true;
2628 }
2629 return false;
2630 }
2631 #endif
2632
2633 #if 0
2634 static void printAllImages()
2635 {
2636 dyld::log("printAllImages()\n");
2637 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
2638 ImageLoader* image = *it;
2639 dyld_image_states imageState = image->getState();
2640 dyld::log(" state=%d, refcount=%d, name=%s\n", imageState, image->referenceCount(), image->getShortName());
2641 image->printReferenceCounts();
2642 }
2643 }
2644 #endif
2645
2646
2647 void link(ImageLoader* image, bool forceLazysBound, const ImageLoader::RPathChain& loaderRPaths)
2648 {
2649 // add to list of known images. This did not happen at creation time for bundles
2650 if ( image->isBundle() && !image->isLinked() )
2651 addImage(image);
2652
2653 // we detect root images as those not linked in yet
2654 if ( !image->isLinked() )
2655 addRootImage(image);
2656
2657 // notify ZeroLink of new image with concat of logical and physical name
2658 if ( sBundleNotifier != NULL && image->isBundle() ) {
2659 const int logicalLen = strlen(image->getLogicalPath());
2660 char logAndPhys[strlen(image->getPath())+logicalLen+2];
2661 strcpy(logAndPhys, image->getLogicalPath());
2662 strcpy(&logAndPhys[logicalLen+1], image->getPath());
2663 (*sBundleNotifier)(logAndPhys, image);
2664 }
2665
2666 // process images
2667 try {
2668 image->link(gLinkContext, forceLazysBound, false, loaderRPaths);
2669 }
2670 catch (const char* msg) {
2671 garbageCollectImages();
2672 throw;
2673 }
2674
2675 #if OLD_GDB_DYLD_INTERFACE
2676 // notify gdb that loaded libraries have changed
2677 gdb_dyld_state_changed();
2678 #endif
2679 }
2680
2681
2682 void runInitializers(ImageLoader* image)
2683 {
2684 // do bottom up initialization
2685 image->runInitializers(gLinkContext);
2686 }
2687
2688 void garbageCollectImages()
2689 {
2690 // keep scanning list of images until entire list is scanned with no unreferenced images
2691 bool mightBeUnreferencedImages = true;
2692 while ( mightBeUnreferencedImages ) {
2693 mightBeUnreferencedImages = false;
2694 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
2695 ImageLoader* image = *it;
2696 if ( (image->referenceCount() == 0) && !image->neverUnload() && !image->isBeingRemoved() ) {
2697 try {
2698 //dyld::log("garbageCollectImages: deleting %s\n", image->getPath());
2699 image->setBeingRemoved();
2700 removeImage(image);
2701 delete image;
2702 }
2703 catch (const char* msg) {
2704 dyld::warn("problem deleting image: %s\n", msg);
2705 }
2706 mightBeUnreferencedImages = true;
2707 break;
2708 }
2709 }
2710 }
2711 //printAllImages();
2712 }
2713
2714
2715 static void preflight_finally(ImageLoader* image)
2716 {
2717 if ( image->isBundle() ) {
2718 removeImageFromAllImages(image->machHeader());
2719 delete image;
2720 }
2721 sBundleBeingLoaded = NULL;
2722 dyld::garbageCollectImages();
2723 }
2724
2725
2726 void preflight(ImageLoader* image, const ImageLoader::RPathChain& loaderRPaths)
2727 {
2728 try {
2729 if ( image->isBundle() )
2730 sBundleBeingLoaded = image; // hack
2731 image->link(gLinkContext, false, true, loaderRPaths);
2732 }
2733 catch (const char* msg) {
2734 preflight_finally(image);
2735 throw;
2736 }
2737 preflight_finally(image);
2738 }
2739
2740 static void loadInsertedDylib(const char* path)
2741 {
2742 ImageLoader* image = NULL;
2743 try {
2744 LoadContext context;
2745 context.useSearchPaths = false;
2746 context.useLdLibraryPath = false;
2747 context.implicitRPath = false;
2748 context.matchByInstallName = false;
2749 context.dontLoad = false;
2750 context.mustBeBundle = false;
2751 context.mustBeDylib = true;
2752 context.findDLL = false;
2753 context.origin = NULL; // can't use @loader_path with DYLD_INSERT_LIBRARIES
2754 context.rpath = NULL;
2755 image = load(path, context);
2756 image->setNeverUnload();
2757 }
2758 catch (...) {
2759 halt(dyld::mkstringf("could not load inserted library: %s\n", path));
2760 }
2761 }
2762
2763 //
2764 // Entry point for dyld. The kernel loads dyld and jumps to __dyld_start which
2765 // sets up some registers and call this function.
2766 //
2767 // Returns address of main() in target program which __dyld_start jumps to
2768 //
2769 uintptr_t
2770 _main(const struct mach_header* mainExecutableMH, uintptr_t mainExecutableSlide, int argc, const char* argv[], const char* envp[], const char* apple[])
2771 {
2772 setContext(mainExecutableMH, argc, argv, envp, apple);
2773
2774 // Pickup the pointer to the exec path.
2775 sExecPath = apple[0];
2776 bool ignoreEnvironmentVariables = false;
2777 #if __i386__
2778 if ( isRosetta() ) {
2779 // under Rosetta (x86 side)
2780 // When a 32-bit ppc program is run under emulation on an Intel processor,
2781 // we want any i386 dylibs (e.g. any used by Rosetta) to not load in the shared region
2782 // because the shared region is being used by ppc dylibs
2783 gLinkContext.sharedRegionMode = ImageLoader::kDontUseSharedRegion;
2784 ignoreEnvironmentVariables = true;
2785 }
2786 #endif
2787 if ( sExecPath[0] != '/' ) {
2788 // have relative path, use cwd to make absolute
2789 char cwdbuff[MAXPATHLEN];
2790 if ( getcwd(cwdbuff, MAXPATHLEN) != NULL ) {
2791 // maybe use static buffer to avoid calling malloc so early...
2792 char* s = new char[strlen(cwdbuff) + strlen(sExecPath) + 2];
2793 strcpy(s, cwdbuff);
2794 strcat(s, "/");
2795 strcat(s, sExecPath);
2796 sExecPath = s;
2797 }
2798 }
2799 uintptr_t result = 0;
2800 sMainExecutableMachHeader = mainExecutableMH;
2801 sMainExecutableIsSetuid = issetugid();
2802 if ( sMainExecutableIsSetuid )
2803 pruneEnvironmentVariables(envp, &apple);
2804 else
2805 checkEnvironmentVariables(envp, ignoreEnvironmentVariables);
2806 if ( sEnv.DYLD_PRINT_OPTS )
2807 printOptions(argv);
2808 if ( sEnv.DYLD_PRINT_ENV )
2809 printEnvironmentVariables(envp);
2810 getHostInfo();
2811 // install gdb notifier
2812 stateToHandlers(dyld_image_state_dependents_mapped, sBatchHandlers)->push_back(notifyGDB);
2813 // make initial allocations large enough that it is unlikely to need to be re-alloced
2814 sAllImages.reserve(200);
2815 sImageRoots.reserve(16);
2816 sAddImageCallbacks.reserve(4);
2817 sRemoveImageCallbacks.reserve(4);
2818 sImageFilesNeedingTermination.reserve(16);
2819 sImageFilesNeedingDOFUnregistration.reserve(8);
2820
2821 try {
2822 // instantiate ImageLoader for main executable
2823 sMainExecutable = instantiateFromLoadedImage(mainExecutableMH, mainExecutableSlide, sExecPath);
2824 sMainExecutable->setNeverUnload();
2825 gLinkContext.mainExecutable = sMainExecutable;
2826 // load shared cache
2827 checkSharedRegionDisable();
2828 #if DYLD_SHARED_CACHE_SUPPORT
2829 if ( gLinkContext.sharedRegionMode != ImageLoader::kDontUseSharedRegion )
2830 mapSharedCache();
2831 #endif
2832 // load any inserted libraries
2833 if ( sEnv.DYLD_INSERT_LIBRARIES != NULL ) {
2834 for (const char* const* lib = sEnv.DYLD_INSERT_LIBRARIES; *lib != NULL; ++lib)
2835 loadInsertedDylib(*lib);
2836 }
2837 // record count of inserted libraries so that a flat search will look at
2838 // inserted libraries, then main, then others.
2839 sInsertedDylibCount = sAllImages.size()-1;
2840
2841 // link main executable
2842 gLinkContext.linkingMainExecutable = true;
2843 link(sMainExecutable, sEnv.DYLD_BIND_AT_LAUNCH, ImageLoader::RPathChain(NULL, NULL));
2844 gLinkContext.linkingMainExecutable = false;
2845 if ( sMainExecutable->forceFlat() ) {
2846 gLinkContext.bindFlat = true;
2847 gLinkContext.prebindUsage = ImageLoader::kUseNoPrebinding;
2848 }
2849 result = (uintptr_t)sMainExecutable->getMain();
2850
2851 // link any inserted libraries
2852 // do this after linking main executable so that any dylibs pulled in by inserted
2853 // dylibs (e.g. libSystem) will not be in front of dylibs the program uses
2854 if ( sInsertedDylibCount > 0 ) {
2855 for(unsigned int i=0; i < sInsertedDylibCount; ++i) {
2856 ImageLoader* image = sAllImages[i+1];
2857 link(image, sEnv.DYLD_BIND_AT_LAUNCH, ImageLoader::RPathChain(NULL, NULL));
2858 }
2859 }
2860
2861 #if SUPPORT_OLD_CRT_INITIALIZATION
2862 // Old way is to run initializers via a callback from crt1.o
2863 if ( ! gRunInitializersOldWay )
2864 #endif
2865 initializeMainExecutable(); // run all initializers
2866 }
2867 catch(const char* message) {
2868 halt(message);
2869 }
2870 catch(...) {
2871 dyld::log("dyld: launch failed\n");
2872 }
2873
2874 return result;
2875 }
2876
2877
2878
2879
2880 }; // namespace
2881
2882
2883