]> git.saurik.com Git - apple/dyld.git/blob - src/dyld.cpp
31265a9b7bad6c984fd1d600658aeec4b90a78e4
[apple/dyld.git] / src / dyld.cpp
1 /* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*-
2 *
3 * Copyright (c) 2004-2010 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 <dirent.h>
31 #include <sys/param.h>
32 #include <mach/mach_time.h> // mach_absolute_time()
33 #include <sys/types.h>
34 #include <sys/stat.h>
35 #include <sys/syscall.h>
36 #include <mach-o/fat.h>
37 #include <mach-o/loader.h>
38 #include <mach-o/ldsyms.h>
39 #include <libkern/OSByteOrder.h>
40 #include <libkern/OSAtomic.h>
41 #include <mach/mach.h>
42 #include <sys/sysctl.h>
43 #include <sys/mman.h>
44 #include <sys/dtrace.h>
45 #include <libkern/OSAtomic.h>
46 #include <Availability.h>
47 #include <Kernel/sys/codesign.h>
48
49
50 #ifndef CPU_SUBTYPE_ARM_V5TEJ
51 #define CPU_SUBTYPE_ARM_V5TEJ ((cpu_subtype_t) 7)
52 #endif
53 #ifndef CPU_SUBTYPE_ARM_XSCALE
54 #define CPU_SUBTYPE_ARM_XSCALE ((cpu_subtype_t) 8)
55 #endif
56 #ifndef CPU_SUBTYPE_ARM_V7
57 #define CPU_SUBTYPE_ARM_V7 ((cpu_subtype_t) 9)
58 #endif
59 #ifndef LC_DYLD_ENVIRONMENT
60 #define LC_DYLD_ENVIRONMENT 0x27
61 #endif
62
63 #ifndef VM_PROT_SLIDE
64 #define VM_PROT_SLIDE 0x20
65 #endif
66
67 #include <vector>
68 #include <algorithm>
69
70 #include "mach-o/dyld_gdb.h"
71
72 #include "dyld.h"
73 #include "ImageLoader.h"
74 #include "ImageLoaderMachO.h"
75 #include "dyldLibSystemInterface.h"
76 #if DYLD_SHARED_CACHE_SUPPORT
77 #include "dyld_cache_format.h"
78 #endif
79 #if CORESYMBOLICATION_SUPPORT
80 #include "coreSymbolicationDyldSupport.hpp"
81 #endif
82
83 // from _simple.h in libc
84 typedef struct _SIMPLE* _SIMPLE_STRING;
85 extern "C" void _simple_vdprintf(int __fd, const char *__fmt, va_list __ap);
86 extern "C" void _simple_dprintf(int __fd, const char *__fmt, ...);
87 extern "C" _SIMPLE_STRING _simple_salloc(void);
88 extern "C" int _simple_vsprintf(_SIMPLE_STRING __b, const char *__fmt, va_list __ap);
89 extern "C" void _simple_sfree(_SIMPLE_STRING __b);
90 extern "C" char * _simple_string(_SIMPLE_STRING __b);
91
92
93
94 // 32-bit ppc and ARM are the only architecture that use cpu-sub-types
95 #define CPU_SUBTYPES_SUPPORTED __ppc__ || __arm__
96
97
98
99 #define CPU_TYPE_MASK 0x00FFFFFF /* complement of CPU_ARCH_MASK */
100
101
102 /* implemented in dyld_gdb.cpp */
103 extern void addImagesToAllImages(uint32_t infoCount, const dyld_image_info info[]);
104 extern void removeImageFromAllImages(const mach_header* mh);
105 extern void setAlImageInfosHalt(const char* message, uintptr_t flags);
106 extern void addNonSharedCacheImageUUID(const dyld_uuid_info& info);
107 extern const char* notifyGDB(enum dyld_image_states state, uint32_t infoCount, const dyld_image_info info[]);
108
109 // magic so CrashReporter logs message
110 extern "C" {
111 char error_string[1024];
112 }
113 // implemented in dyldStartup.s for CrashReporter
114 extern "C" void dyld_fatal_error(const char* errString) __attribute__((noreturn));
115
116
117
118 //
119 // The file contains the core of dyld used to get a process to main().
120 // The API's that dyld supports are implemented in dyldAPIs.cpp.
121 //
122 //
123 //
124 //
125 //
126
127
128 namespace dyld {
129
130
131 //
132 // state of all environment variables dyld uses
133 //
134 struct EnvironmentVariables {
135 const char* const * DYLD_FRAMEWORK_PATH;
136 const char* const * DYLD_FALLBACK_FRAMEWORK_PATH;
137 const char* const * DYLD_LIBRARY_PATH;
138 const char* const * DYLD_FALLBACK_LIBRARY_PATH;
139 const char* const * DYLD_INSERT_LIBRARIES;
140 const char* const * LD_LIBRARY_PATH; // for unix conformance
141 const char* const * DYLD_VERSIONED_LIBRARY_PATH;
142 const char* const * DYLD_VERSIONED_FRAMEWORK_PATH;
143 bool DYLD_PRINT_LIBRARIES;
144 bool DYLD_PRINT_LIBRARIES_POST_LAUNCH;
145 bool DYLD_BIND_AT_LAUNCH;
146 bool DYLD_PRINT_STATISTICS;
147 bool DYLD_PRINT_OPTS;
148 bool DYLD_PRINT_ENV;
149 bool DYLD_DISABLE_DOFS;
150 bool DYLD_PRINT_CS_NOTIFICATIONS;
151 // DYLD_SHARED_CACHE_DONT_VALIDATE ==> sSharedCacheIgnoreInodeAndTimeStamp
152 // DYLD_SHARED_CACHE_DIR ==> sSharedCacheDir
153 // DYLD_ROOT_PATH ==> gLinkContext.rootPaths
154 // DYLD_IMAGE_SUFFIX ==> gLinkContext.imageSuffix
155 // DYLD_PRINT_OPTS ==> gLinkContext.verboseOpts
156 // DYLD_PRINT_ENV ==> gLinkContext.verboseEnv
157 // DYLD_FORCE_FLAT_NAMESPACE ==> gLinkContext.bindFlat
158 // DYLD_PRINT_INITIALIZERS ==> gLinkContext.verboseInit
159 // DYLD_PRINT_SEGMENTS ==> gLinkContext.verboseMapping
160 // DYLD_PRINT_BINDINGS ==> gLinkContext.verboseBind
161 // DYLD_PRINT_WEAK_BINDINGS ==> gLinkContext.verboseWeakBind
162 // DYLD_PRINT_REBASINGS ==> gLinkContext.verboseRebase
163 // DYLD_PRINT_DOFS ==> gLinkContext.verboseDOF
164 // DYLD_PRINT_APIS ==> gLogAPIs
165 // DYLD_IGNORE_PREBINDING ==> gLinkContext.prebindUsage
166 // DYLD_PREBIND_DEBUG ==> gLinkContext.verbosePrebinding
167 // DYLD_NEW_LOCAL_SHARED_REGIONS ==> gLinkContext.sharedRegionMode
168 // DYLD_SHARED_REGION ==> gLinkContext.sharedRegionMode
169 // DYLD_PRINT_WARNINGS ==> gLinkContext.verboseWarnings
170 // DYLD_PRINT_RPATHS ==> gLinkContext.verboseRPaths
171 // DYLD_PRINT_INTERPOSING ==> gLinkContext.verboseInterposing
172 };
173
174 typedef std::vector<dyld_image_state_change_handler> StateHandlers;
175 struct RegisteredDOF { const mach_header* mh; int registrationID; };
176 struct DylibOverride { const char* installName; const char* override; };
177
178 // all global state
179 static const char* sExecPath = NULL;
180 static const macho_header* sMainExecutableMachHeader = NULL;
181 #if CPU_SUBTYPES_SUPPORTED
182 static cpu_type_t sHostCPU;
183 static cpu_subtype_t sHostCPUsubtype;
184 #endif
185 static ImageLoader* sMainExecutable = NULL;
186 static bool sProcessIsRestricted = false;
187 static unsigned int sInsertedDylibCount = 0;
188 static std::vector<ImageLoader*> sAllImages;
189 static std::vector<ImageLoader*> sImageRoots;
190 static std::vector<ImageLoader*> sImageFilesNeedingTermination;
191 static std::vector<RegisteredDOF> sImageFilesNeedingDOFUnregistration;
192 static std::vector<ImageCallback> sAddImageCallbacks;
193 static std::vector<ImageCallback> sRemoveImageCallbacks;
194 static StateHandlers sSingleHandlers[7];
195 static StateHandlers sBatchHandlers[7];
196 static ImageLoader* sLastImageByAddressCache;
197 static EnvironmentVariables sEnv;
198 static const char* sFrameworkFallbackPaths[] = { "$HOME/Library/Frameworks", "/Library/Frameworks", "/Network/Library/Frameworks", "/System/Library/Frameworks", NULL };
199 static const char* sLibraryFallbackPaths[] = { "$HOME/lib", "/usr/local/lib", "/usr/lib", NULL };
200 static UndefinedHandler sUndefinedHandler = NULL;
201 static ImageLoader* sBundleBeingLoaded = NULL; // hack until OFI is reworked
202 #if DYLD_SHARED_CACHE_SUPPORT
203 static const dyld_cache_header* sSharedCache = NULL;
204 static long sSharedCacheSlide = 0;
205 static bool sSharedCacheIgnoreInodeAndTimeStamp = false;
206 #if __IPHONE_OS_VERSION_MIN_REQUIRED
207 bool gSharedCacheOverridden = false;
208 static const char* sSharedCacheDir = IPHONE_DYLD_SHARED_CACHE_DIR;
209 static bool sDylibsOverrideCache = false;
210 #else
211 static const char* sSharedCacheDir = MACOSX_DYLD_SHARED_CACHE_DIR;
212 #endif
213 #endif
214 ImageLoader::LinkContext gLinkContext;
215 bool gLogAPIs = false;
216 const struct LibSystemHelpers* gLibSystemHelpers = NULL;
217 #if SUPPORT_OLD_CRT_INITIALIZATION
218 bool gRunInitializersOldWay = false;
219 #endif
220 static std::vector<DylibOverride> sDylibOverrides;
221
222 //
223 // The MappedRanges structure is used for fast address->image lookups.
224 // The table is only updated when the dyld lock is held, so we don't
225 // need to worry about multiple writers. But readers may look at this
226 // data without holding the lock. Therefore, all updates must be done
227 // in an order that will never cause readers to see inconsistent data.
228 // The general rule is that if the image field is non-NULL then
229 // the other fields are valid.
230 //
231 struct MappedRanges
232 {
233 enum { count=400 };
234 struct {
235 ImageLoader* image;
236 uintptr_t start;
237 uintptr_t end;
238 } array[count];
239 MappedRanges* next;
240 };
241
242 static MappedRanges sMappedRangesStart;
243
244 void addMappedRange(ImageLoader* image, uintptr_t start, uintptr_t end)
245 {
246 //dyld::log("addMappedRange(0x%lX->0x%lX) for %s\n", start, end, image->getShortName());
247 for (MappedRanges* p = &sMappedRangesStart; p != NULL; p = p->next) {
248 for (int i=0; i < MappedRanges::count; ++i) {
249 if ( p->array[i].image == NULL ) {
250 p->array[i].start = start;
251 p->array[i].end = end;
252 // add image field last with a barrier so that any reader will see consistent records
253 OSMemoryBarrier();
254 p->array[i].image = image;
255 return;
256 }
257 }
258 }
259 // table must be full, chain another
260 MappedRanges* newRanges = (MappedRanges*)malloc(sizeof(MappedRanges));
261 bzero(newRanges, sizeof(MappedRanges));
262 newRanges->array[0].start = start;
263 newRanges->array[0].end = end;
264 newRanges->array[0].image = image;
265 for (MappedRanges* p = &sMappedRangesStart; p != NULL; p = p->next) {
266 if ( p->next == NULL ) {
267 OSMemoryBarrier();
268 p->next = newRanges;
269 break;
270 }
271 }
272 }
273
274 void removedMappedRanges(ImageLoader* image)
275 {
276 for (MappedRanges* p = &sMappedRangesStart; p != NULL; p = p->next) {
277 for (int i=0; i < MappedRanges::count; ++i) {
278 if ( p->array[i].image == image ) {
279 // clear with a barrier so that any reader will see consistent records
280 OSMemoryBarrier();
281 p->array[i].image = NULL;
282 }
283 }
284 }
285 }
286
287 ImageLoader* findMappedRange(uintptr_t target)
288 {
289 for (MappedRanges* p = &sMappedRangesStart; p != NULL; p = p->next) {
290 for (int i=0; i < MappedRanges::count; ++i) {
291 if ( p->array[i].image != NULL ) {
292 if ( (p->array[i].start <= target) && (target < p->array[i].end) )
293 return p->array[i].image;
294 }
295 }
296 }
297 return NULL;
298 }
299
300
301
302 const char* mkstringf(const char* format, ...)
303 {
304 _SIMPLE_STRING buf = _simple_salloc();
305 if ( buf != NULL ) {
306 va_list list;
307 va_start(list, format);
308 _simple_vsprintf(buf, format, list);
309 va_end(list);
310 const char* t = strdup(_simple_string(buf));
311 _simple_sfree(buf);
312 if ( t != NULL )
313 return t;
314 }
315 return "mkstringf, out of memory error";
316 }
317
318
319 void throwf(const char* format, ...)
320 {
321 _SIMPLE_STRING buf = _simple_salloc();
322 if ( buf != NULL ) {
323 va_list list;
324 va_start(list, format);
325 _simple_vsprintf(buf, format, list);
326 va_end(list);
327 const char* t = strdup(_simple_string(buf));
328 _simple_sfree(buf);
329 if ( t != NULL )
330 throw t;
331 }
332 throw "throwf, out of memory error";
333 }
334
335
336 //#define ALTERNATIVE_LOGFILE "/dev/console"
337 static int sLogfile = STDERR_FILENO;
338
339 #if LOG_BINDINGS
340 static int sBindingsLogfile = -1;
341 static void mysprintf(char* dst, const char* format, ...)
342 {
343 _SIMPLE_STRING buf = _simple_salloc();
344 if ( buf != NULL ) {
345 va_list list;
346 va_start(list, format);
347 _simple_vsprintf(buf, format, list);
348 va_end(list);
349 strcpy(dst, _simple_string(buf));
350 _simple_sfree(buf);
351 }
352 else {
353 strcpy(dst, "out of memory");
354 }
355 }
356 void logBindings(const char* format, ...)
357 {
358 if ( sBindingsLogfile != -1 ) {
359 va_list list;
360 va_start(list, format);
361 _simple_vdprintf(sBindingsLogfile, format, list);
362 va_end(list);
363 }
364 }
365
366 #endif
367
368 void log(const char* format, ...)
369 {
370 va_list list;
371 va_start(list, format);
372 _simple_vdprintf(sLogfile, format, list);
373 va_end(list);
374 }
375
376 void warn(const char* format, ...)
377 {
378 _simple_dprintf(sLogfile, "dyld: warning, ");
379 va_list list;
380 va_start(list, format);
381 _simple_vdprintf(sLogfile, format, list);
382 va_end(list);
383 }
384
385
386 // <rdar://problem/8867781> control access to sAllImages through a lock
387 // because global dyld lock is not held during initialization phase of dlopen()
388 static long sAllImagesLock = 0;
389
390 static void allImagesLock()
391 {
392 //dyld::log("allImagesLock()\n");
393 while ( ! OSAtomicCompareAndSwapPtrBarrier((void*)0, (void*)1, (void**)&sAllImagesLock) ) {
394 // spin
395 }
396 }
397
398 static void allImagesUnlock()
399 {
400 //dyld::log("allImagesUnlock()\n");
401 while ( ! OSAtomicCompareAndSwapPtrBarrier((void*)1, (void*)0, (void**)&sAllImagesLock) ) {
402 // spin
403 }
404 }
405
406
407
408
409 // utility class to assure files are closed when an exception is thrown
410 class FileOpener {
411 public:
412 FileOpener(const char* path);
413 ~FileOpener();
414 int getFileDescriptor() { return fd; }
415 private:
416 int fd;
417 };
418
419 FileOpener::FileOpener(const char* path)
420 : fd(-1)
421 {
422 fd = open(path, O_RDONLY, 0);
423 }
424
425 FileOpener::~FileOpener()
426 {
427 if ( fd != -1 )
428 close(fd);
429 }
430
431
432 // forward declaration
433 #if __ppc__ || __i386__
434 bool isRosetta();
435 #endif
436
437
438 static void registerDOFs(const std::vector<ImageLoader::DOFInfo>& dofs)
439 {
440 #if __ppc__
441 // can't dtrace a program running emulated under rosetta rdar://problem/5179640
442 if ( isRosetta() )
443 return;
444 #endif
445 const unsigned int dofSectionCount = dofs.size();
446 if ( !sEnv.DYLD_DISABLE_DOFS && (dofSectionCount != 0) ) {
447 int fd = open("/dev/" DTRACEMNR_HELPER, O_RDWR);
448 if ( fd < 0 ) {
449 //dyld::warn("can't open /dev/" DTRACEMNR_HELPER " to register dtrace DOF sections\n");
450 }
451 else {
452 // allocate a buffer on the stack for the variable length dof_ioctl_data_t type
453 uint8_t buffer[sizeof(dof_ioctl_data_t) + dofSectionCount*sizeof(dof_helper_t)];
454 dof_ioctl_data_t* ioctlData = (dof_ioctl_data_t*)buffer;
455
456 // fill in buffer with one dof_helper_t per DOF section
457 ioctlData->dofiod_count = dofSectionCount;
458 for (unsigned int i=0; i < dofSectionCount; ++i) {
459 strlcpy(ioctlData->dofiod_helpers[i].dofhp_mod, dofs[i].imageShortName, DTRACE_MODNAMELEN);
460 ioctlData->dofiod_helpers[i].dofhp_dof = (uintptr_t)(dofs[i].dof);
461 ioctlData->dofiod_helpers[i].dofhp_addr = (uintptr_t)(dofs[i].dof);
462 }
463
464 // tell kernel about all DOF sections en mas
465 // pass pointer to ioctlData because ioctl() only copies a fixed size amount of data into kernel
466 user_addr_t val = (user_addr_t)(unsigned long)ioctlData;
467 if ( ioctl(fd, DTRACEHIOC_ADDDOF, &val) != -1 ) {
468 // kernel returns a unique identifier for each section in the dofiod_helpers[].dofhp_dof field.
469 for (unsigned int i=0; i < dofSectionCount; ++i) {
470 RegisteredDOF info;
471 info.mh = dofs[i].imageHeader;
472 info.registrationID = (int)(ioctlData->dofiod_helpers[i].dofhp_dof);
473 sImageFilesNeedingDOFUnregistration.push_back(info);
474 if ( gLinkContext.verboseDOF ) {
475 dyld::log("dyld: registering DOF section 0x%p in %s with dtrace, ID=0x%08X\n",
476 dofs[i].dof, dofs[i].imageShortName, info.registrationID);
477 }
478 }
479 }
480 else {
481 dyld::log( "dyld: ioctl to register dtrace DOF section failed\n");
482 }
483 close(fd);
484 }
485 }
486 }
487
488 static void unregisterDOF(int registrationID)
489 {
490 int fd = open("/dev/" DTRACEMNR_HELPER, O_RDWR);
491 if ( fd < 0 ) {
492 dyld::warn("can't open /dev/" DTRACEMNR_HELPER " to unregister dtrace DOF section\n");
493 }
494 else {
495 ioctl(fd, DTRACEHIOC_REMOVE, registrationID);
496 close(fd);
497 if ( gLinkContext.verboseInit )
498 dyld::warn("unregistering DOF section ID=0x%08X with dtrace\n", registrationID);
499 }
500 }
501
502
503 //
504 // _dyld_register_func_for_add_image() is implemented as part of the general image state change notification
505 //
506 static void notifyAddImageCallbacks(ImageLoader* image)
507 {
508 // use guard so that we cannot notify about the same image twice
509 if ( ! image->addFuncNotified() ) {
510 for (std::vector<ImageCallback>::iterator it=sAddImageCallbacks.begin(); it != sAddImageCallbacks.end(); it++)
511 (*it)(image->machHeader(), image->getSlide());
512 image->setAddFuncNotified();
513 }
514 }
515
516
517
518 // notify gdb about these new images
519 static const char* updateAllImages(enum dyld_image_states state, uint32_t infoCount, const struct dyld_image_info info[])
520 {
521 // <rdar://problem/8812589> don't add images without paths to all-image-info-list
522 if ( info[0].imageFilePath != NULL )
523 addImagesToAllImages(infoCount, info);
524 return NULL;
525 }
526
527
528 static StateHandlers* stateToHandlers(dyld_image_states state, StateHandlers handlersArray[8])
529 {
530 switch ( state ) {
531 case dyld_image_state_mapped:
532 return &handlersArray[0];
533
534 case dyld_image_state_dependents_mapped:
535 return &handlersArray[1];
536
537 case dyld_image_state_rebased:
538 return &handlersArray[2];
539
540 case dyld_image_state_bound:
541 return &handlersArray[3];
542
543 case dyld_image_state_dependents_initialized:
544 return &handlersArray[4];
545
546 case dyld_image_state_initialized:
547 return &handlersArray[5];
548
549 case dyld_image_state_terminated:
550 return &handlersArray[6];
551 }
552 return NULL;
553 }
554
555
556 static void notifySingle(dyld_image_states state, const ImageLoader* image)
557 {
558 //dyld::log("notifySingle(state=%d, image=%s)\n", state, image->getPath());
559 std::vector<dyld_image_state_change_handler>* handlers = stateToHandlers(state, sSingleHandlers);
560 if ( handlers != NULL ) {
561 dyld_image_info info;
562 info.imageLoadAddress = image->machHeader();
563 info.imageFilePath = image->getPath();
564 info.imageFileModDate = image->lastModified();
565 for (std::vector<dyld_image_state_change_handler>::iterator it = handlers->begin(); it != handlers->end(); ++it) {
566 const char* result = (*it)(state, 1, &info);
567 if ( (result != NULL) && (state == dyld_image_state_mapped) ) {
568 //fprintf(stderr, " image rejected by handler=%p\n", *it);
569 // make copy of thrown string so that later catch clauses can free it
570 const char* str = strdup(result);
571 throw str;
572 }
573 }
574 }
575 if ( state == dyld_image_state_mapped ) {
576 // <rdar://problem/7008875> Save load addr + UUID for images from outside the shared cache
577 if ( !image->inSharedCache() ) {
578 dyld_uuid_info info;
579 if ( image->getUUID(info.imageUUID) ) {
580 info.imageLoadAddress = image->machHeader();
581 addNonSharedCacheImageUUID(info);
582 }
583 }
584 }
585 #if CORESYMBOLICATION_SUPPORT
586 // mach message csdlc about dynamically loaded images
587 if ( image->addFuncNotified() && (state == dyld_image_state_terminated) ) {
588 if ( sEnv.DYLD_PRINT_CS_NOTIFICATIONS ) {
589 dyld::log("dyld core symbolication unload notification: %p %s\n", image->machHeader(), image->getPath());
590 }
591 if ( dyld_all_image_infos.coreSymbolicationShmPage != NULL) {
592 CSCppDyldSharedMemoryPage* connection = (CSCppDyldSharedMemoryPage*)dyld_all_image_infos.coreSymbolicationShmPage;
593 if ( connection->is_valid_version() ) {
594 coresymbolication_unload_image(connection, image);
595 }
596 }
597 }
598 #endif
599 }
600
601
602
603
604 //
605 // Normally, dyld_all_image_infos is only updated in batches after an entire
606 // graph is loaded. But if there is an error loading the initial set of
607 // dylibs needed by the main executable, dyld_all_image_infos is not yet set
608 // up, leading to usually brief crash logs.
609 //
610 // This function manually adds the images loaded so far to dyld_all_image_infos.
611 // It should only be called before terminating.
612 //
613 void syncAllImages()
614 {
615 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); ++it) {
616 dyld_image_info info;
617 ImageLoader* image = *it;
618 info.imageLoadAddress = image->machHeader();
619 info.imageFilePath = image->getPath();
620 info.imageFileModDate = image->lastModified();
621 // add to all_image_infos if not already there
622 bool found = false;
623 int existingCount = dyld_all_image_infos.infoArrayCount;
624 const dyld_image_info* existing = dyld_all_image_infos.infoArray;
625 if ( existing != NULL ) {
626 for (int i=0; i < existingCount; ++i) {
627 if ( existing[i].imageLoadAddress == info.imageLoadAddress ) {
628 //dyld::log("not adding %s\n", info.imageFilePath);
629 found = true;
630 break;
631 }
632 }
633 }
634 if ( ! found ) {
635 //dyld::log("adding %s\n", info.imageFilePath);
636 addImagesToAllImages(1, &info);
637 }
638 }
639 }
640
641
642 static int imageSorter(const void* l, const void* r)
643 {
644 const ImageLoader* left = *((ImageLoader**)l);
645 const ImageLoader* right= *((ImageLoader**)r);
646 return left->compare(right);
647 }
648
649 static void notifyBatchPartial(dyld_image_states state, bool orLater, dyld_image_state_change_handler onlyHandler)
650 {
651 std::vector<dyld_image_state_change_handler>* handlers = stateToHandlers(state, sBatchHandlers);
652 if ( handlers != NULL ) {
653 // don't use a vector because it will use malloc/free and we want notifcation to be low cost
654 allImagesLock();
655 ImageLoader* images[sAllImages.size()+1];
656 ImageLoader** end = images;
657 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
658 dyld_image_states imageState = (*it)->getState();
659 if ( (imageState == state) || (orLater && (imageState > state)) )
660 *end++ = *it;
661 }
662 if ( sBundleBeingLoaded != NULL ) {
663 dyld_image_states imageState = sBundleBeingLoaded->getState();
664 if ( (imageState == state) || (orLater && (imageState > state)) )
665 *end++ = sBundleBeingLoaded;
666 }
667 const char* dontLoadReason = NULL;
668 unsigned int count = end-images;
669 if ( end != images ) {
670 // sort bottom up
671 qsort(images, count, sizeof(ImageLoader*), &imageSorter);
672 // build info array
673 dyld_image_info infos[count];
674 for (unsigned int i=0; i < count; ++i) {
675 dyld_image_info* p = &infos[i];
676 ImageLoader* image = images[i];
677 //dyld::log(" state=%d, name=%s\n", state, image->getPath());
678 p->imageLoadAddress = image->machHeader();
679 p->imageFilePath = image->getPath();
680 p->imageFileModDate = image->lastModified();
681 // special case for add_image hook
682 if ( state == dyld_image_state_bound )
683 notifyAddImageCallbacks(image);
684 }
685
686 if ( onlyHandler != NULL ) {
687 const char* result = (*onlyHandler)(state, count, infos);
688 if ( (result != NULL) && (state == dyld_image_state_dependents_mapped) ) {
689 //fprintf(stderr, " images rejected by handler=%p\n", onlyHandler);
690 // make copy of thrown string so that later catch clauses can free it
691 dontLoadReason = strdup(result);
692 }
693 }
694 else {
695 // call each handler with whole array
696 for (std::vector<dyld_image_state_change_handler>::iterator it = handlers->begin(); it != handlers->end(); ++it) {
697 const char* result = (*it)(state, count, infos);
698 if ( (result != NULL) && (state == dyld_image_state_dependents_mapped) ) {
699 //fprintf(stderr, " images rejected by handler=%p\n", *it);
700 // make copy of thrown string so that later catch clauses can free it
701 dontLoadReason = strdup(result);
702 break;
703 }
704 }
705 }
706 }
707 allImagesUnlock();
708 if ( dontLoadReason != NULL )
709 throw dontLoadReason;
710 }
711 #if CORESYMBOLICATION_SUPPORT
712 if ( state == dyld_image_state_rebased ) {
713 if ( sEnv.DYLD_PRINT_CS_NOTIFICATIONS ) {
714 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
715 dyld_image_states imageState = (*it)->getState();
716 if ( (imageState == dyld_image_state_rebased) || (orLater && (imageState > dyld_image_state_rebased)) )
717 dyld::log("dyld core symbolication load notification: %p %s\n", (*it)->machHeader(), (*it)->getPath());
718 }
719 }
720 if ( dyld_all_image_infos.coreSymbolicationShmPage != NULL) {
721 CSCppDyldSharedMemoryPage* connection = (CSCppDyldSharedMemoryPage*)dyld_all_image_infos.coreSymbolicationShmPage;
722 if ( connection->is_valid_version() ) {
723 // This needs to be captured now
724 uint64_t load_timestamp = mach_absolute_time();
725 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
726 dyld_image_states imageState = (*it)->getState();
727 if ( (imageState == state) || (orLater && (imageState > state)) )
728 coresymbolication_load_image(connection, *it, load_timestamp);
729 }
730 }
731 }
732 }
733 #endif
734 }
735
736
737
738 static void notifyBatch(dyld_image_states state)
739 {
740 notifyBatchPartial(state, false, NULL);
741 }
742
743 // In order for register_func_for_add_image() callbacks to to be called bottom up,
744 // we need to maintain a list of root images. The main executable is usally the
745 // first root. Any images dynamically added are also roots (unless already loaded).
746 // If DYLD_INSERT_LIBRARIES is used, those libraries are first.
747 static void addRootImage(ImageLoader* image)
748 {
749 //dyld::log("addRootImage(%p, %s)\n", image, image->getPath());
750 // add to list of roots
751 sImageRoots.push_back(image);
752 }
753
754
755 static void clearAllDepths()
756 {
757 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++)
758 (*it)->clearDepth();
759 }
760
761 static unsigned int imageCount()
762 {
763 return sAllImages.size();
764 }
765
766
767 static void setNewProgramVars(const ProgramVars& newVars)
768 {
769 // make a copy of the pointers to program variables
770 gLinkContext.programVars = newVars;
771
772 // now set each program global to their initial value
773 *gLinkContext.programVars.NXArgcPtr = gLinkContext.argc;
774 *gLinkContext.programVars.NXArgvPtr = gLinkContext.argv;
775 *gLinkContext.programVars.environPtr = gLinkContext.envp;
776 *gLinkContext.programVars.__prognamePtr = gLinkContext.progname;
777 }
778
779 #if SUPPORT_OLD_CRT_INITIALIZATION
780 static void setRunInitialzersOldWay()
781 {
782 gRunInitializersOldWay = true;
783 }
784 #endif
785
786 static void addImage(ImageLoader* image)
787 {
788 // add to master list
789 allImagesLock();
790 sAllImages.push_back(image);
791 allImagesUnlock();
792
793 // update mapped ranges
794 uintptr_t lastSegStart = 0;
795 uintptr_t lastSegEnd = 0;
796 for(unsigned int i=0, e=image->segmentCount(); i < e; ++i) {
797 if ( image->segUnaccessible(i) )
798 continue;
799 uintptr_t start = image->segActualLoadAddress(i);
800 uintptr_t end = image->segActualEndAddress(i);
801 if ( start == lastSegEnd ) {
802 // two segments are contiguous, just record combined segments
803 lastSegEnd = end;
804 }
805 else {
806 // non-contiguous segments, record last (if any)
807 if ( lastSegEnd != 0 )
808 addMappedRange(image, lastSegStart, lastSegEnd);
809 lastSegStart = start;
810 lastSegEnd = end;
811 }
812 }
813 if ( lastSegEnd != 0 )
814 addMappedRange(image, lastSegStart, lastSegEnd);
815
816
817 if ( sEnv.DYLD_PRINT_LIBRARIES || (sEnv.DYLD_PRINT_LIBRARIES_POST_LAUNCH && (sMainExecutable!=NULL) && sMainExecutable->isLinked()) ) {
818 dyld::log("dyld: loaded: %s\n", image->getPath());
819 }
820
821 }
822
823 void removeImage(ImageLoader* image)
824 {
825 // if in termination list, pull it out and run terminator
826 for (std::vector<ImageLoader*>::iterator it=sImageFilesNeedingTermination.begin(); it != sImageFilesNeedingTermination.end(); it++) {
827 if ( *it == image ) {
828 sImageFilesNeedingTermination.erase(it);
829 image->doTermination(gLinkContext);
830 break;
831 }
832 }
833
834 // if has dtrace DOF section, tell dtrace it is going away, then remove from sImageFilesNeedingDOFUnregistration
835 for (std::vector<RegisteredDOF>::iterator it=sImageFilesNeedingDOFUnregistration.begin(); it != sImageFilesNeedingDOFUnregistration.end(); ) {
836 if ( it->mh == image->machHeader() ) {
837 unregisterDOF(it->registrationID);
838 sImageFilesNeedingDOFUnregistration.erase(it);
839 // don't increment iterator, the erase caused next element to be copied to where this iterator points
840 }
841 else {
842 ++it;
843 }
844 }
845
846 // tell all registered remove image handlers about this
847 // do this before removing image from internal data structures so that the callback can query dyld about the image
848 if ( image->getState() >= dyld_image_state_bound ) {
849 for (std::vector<ImageCallback>::iterator it=sRemoveImageCallbacks.begin(); it != sRemoveImageCallbacks.end(); it++) {
850 (*it)(image->machHeader(), image->getSlide());
851 }
852 }
853
854 // notify
855 notifySingle(dyld_image_state_terminated, image);
856
857 // <rdar://problem/7740779> dyld should directly call __cxa_finalize()
858 if ( (gLibSystemHelpers != NULL) && (gLibSystemHelpers->version >= 8) )
859 (*gLibSystemHelpers->cxa_finalize)(image->machHeader());
860
861 // remove from mapped images table
862 removedMappedRanges(image);
863
864 // remove from master list
865 allImagesLock();
866 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
867 if ( *it == image ) {
868 sAllImages.erase(it);
869 break;
870 }
871 }
872 allImagesUnlock();
873
874 // flush find-by-address cache (do this after removed from master list, so there is no chance it can come back)
875 if ( sLastImageByAddressCache == image )
876 sLastImageByAddressCache = NULL;
877
878 // if in root list, pull it out
879 for (std::vector<ImageLoader*>::iterator it=sImageRoots.begin(); it != sImageRoots.end(); it++) {
880 if ( *it == image ) {
881 sImageRoots.erase(it);
882 break;
883 }
884 }
885
886 // log if requested
887 if ( sEnv.DYLD_PRINT_LIBRARIES || (sEnv.DYLD_PRINT_LIBRARIES_POST_LAUNCH && (sMainExecutable!=NULL) && sMainExecutable->isLinked()) ) {
888 dyld::log("dyld: unloaded: %s\n", image->getPath());
889 }
890
891 // tell gdb, new way
892 removeImageFromAllImages(image->machHeader());
893 }
894
895
896 static void terminationRecorder(ImageLoader* image)
897 {
898 sImageFilesNeedingTermination.push_back(image);
899 }
900
901 const char* getExecutablePath()
902 {
903 return sExecPath;
904 }
905
906
907 void initializeMainExecutable()
908 {
909 // apply interposing to initial set of images
910 // do this before making the __IMPORT segments in shared cache read-only
911 sMainExecutable->applyInterposing(gLinkContext);
912
913 // record that we've reached this step
914 gLinkContext.startedInitializingMainExecutable = true;
915
916 // run initialzers for any inserted dylibs
917 ImageLoader::InitializerTimingList initializerTimes[sAllImages.size()];
918 const int rootCount = sImageRoots.size();
919 if ( rootCount > 1 ) {
920 for(int i=1; i < rootCount; ++i) {
921 initializerTimes[0].count = 0;
922 sImageRoots[i]->runInitializers(gLinkContext, initializerTimes[0]);
923 }
924 }
925
926 // run initializers for main executable and everything it brings up
927 initializerTimes[0].count = 0;
928 sMainExecutable->runInitializers(gLinkContext, initializerTimes[0]);
929
930 // register atexit() handler to run terminators in all loaded images when this process exits
931 if ( gLibSystemHelpers != NULL )
932 (*gLibSystemHelpers->cxa_atexit)(&runTerminators, NULL, NULL);
933
934 // dump info if requested
935 if ( sEnv.DYLD_PRINT_STATISTICS )
936 ImageLoaderMachO::printStatistics(sAllImages.size(), initializerTimes[0]);
937 }
938
939 bool mainExecutablePrebound()
940 {
941 return sMainExecutable->usablePrebinding(gLinkContext);
942 }
943
944 ImageLoader* mainExecutable()
945 {
946 return sMainExecutable;
947 }
948
949
950 void runTerminators(void* extra)
951 {
952 const unsigned int imageCount = sImageFilesNeedingTermination.size();
953 for(unsigned int i=imageCount; i > 0; --i){
954 ImageLoader* image = sImageFilesNeedingTermination[i-1];
955 image->doTermination(gLinkContext);
956 }
957 sImageFilesNeedingTermination.clear();
958 notifyBatch(dyld_image_state_terminated);
959 }
960
961
962 // forward reference
963 static bool getDylibVersionAndInstallname(const char* dylibPath, uint32_t* version, char* installName);
964
965
966 //
967 // Examines a dylib file and if its current_version is newer than the installed
968 // dylib at its install_name, then add the dylib file to sDylibOverrides.
969 //
970 static void checkDylibOverride(const char* dylibFile)
971 {
972 //dyld::log("checkDylibOverride('%s')\n", dylibFile);
973 uint32_t altVersion;
974 char sysInstallName[PATH_MAX];
975 if ( getDylibVersionAndInstallname(dylibFile, &altVersion, sysInstallName) ) {
976 //dyld::log("%s has version 0x%08X and install name %s\n", dylibFile, altVersion, sysInstallName);
977 uint32_t sysVersion;
978 if ( getDylibVersionAndInstallname(sysInstallName, &sysVersion, NULL) ) {
979 //dyld::log("%s has version 0x%08X\n", sysInstallName, sysVersion);
980 if ( altVersion > sysVersion ) {
981 //dyld::log("override found: %s -> %s\n", sysInstallName, dylibFile);
982 // see if there already is an override for this dylib
983 bool entryExists = false;
984 for (std::vector<DylibOverride>::iterator it = sDylibOverrides.begin(); it != sDylibOverrides.end(); ++it) {
985 if ( strcmp(it->installName, sysInstallName) == 0 ) {
986 entryExists = true;
987 uint32_t prevVersion;
988 if ( getDylibVersionAndInstallname(it->override, &prevVersion, NULL) ) {
989 if ( altVersion > prevVersion ) {
990 // found an even newer override
991 free((void*)(it->override));
992 it->override = strdup(dylibFile);
993 break;
994 }
995 }
996 }
997 }
998 if ( ! entryExists ) {
999 DylibOverride entry;
1000 entry.installName = strdup(sysInstallName);
1001 entry.override = strdup(dylibFile);
1002 sDylibOverrides.push_back(entry);
1003 //dyld::log("added override: %s -> %s\n", entry.installName, entry.override);
1004 }
1005 }
1006 }
1007 }
1008
1009 }
1010
1011 static void checkDylibOverridesInDir(const char* dirPath)
1012 {
1013 //dyld::log("checkDylibOverridesInDir('%s')\n", dirPath);
1014 char dylibPath[PATH_MAX];
1015 int dirPathLen = strlen(dirPath);
1016 strlcpy(dylibPath, dirPath, PATH_MAX);
1017 DIR* dirp = opendir(dirPath);
1018 if ( dirp != NULL) {
1019 dirent entry;
1020 dirent* entp = NULL;
1021 while ( readdir_r(dirp, &entry, &entp) == 0 ) {
1022 if ( entp == NULL )
1023 break;
1024 if ( entp->d_type != DT_REG )
1025 continue;
1026 dylibPath[dirPathLen] = '/';
1027 dylibPath[dirPathLen+1] = '\0';
1028 if ( strlcat(dylibPath, entp->d_name, PATH_MAX) > PATH_MAX )
1029 continue;
1030 checkDylibOverride(dylibPath);
1031 }
1032 closedir(dirp);
1033 }
1034 }
1035
1036
1037 static void checkFrameworkOverridesInDir(const char* dirPath)
1038 {
1039 //dyld::log("checkFrameworkOverridesInDir('%s')\n", dirPath);
1040 char frameworkPath[PATH_MAX];
1041 int dirPathLen = strlen(dirPath);
1042 strlcpy(frameworkPath, dirPath, PATH_MAX);
1043 DIR* dirp = opendir(dirPath);
1044 if ( dirp != NULL) {
1045 dirent entry;
1046 dirent* entp = NULL;
1047 while ( readdir_r(dirp, &entry, &entp) == 0 ) {
1048 if ( entp == NULL )
1049 break;
1050 if ( entp->d_type != DT_DIR )
1051 continue;
1052 frameworkPath[dirPathLen] = '/';
1053 frameworkPath[dirPathLen+1] = '\0';
1054 int dirNameLen = strlen(entp->d_name);
1055 if ( dirNameLen < 11 )
1056 continue;
1057 if ( strcmp(&entp->d_name[dirNameLen-10], ".framework") != 0 )
1058 continue;
1059 if ( strlcat(frameworkPath, entp->d_name, PATH_MAX) > PATH_MAX )
1060 continue;
1061 if ( strlcat(frameworkPath, "/", PATH_MAX) > PATH_MAX )
1062 continue;
1063 if ( strlcat(frameworkPath, entp->d_name, PATH_MAX) > PATH_MAX )
1064 continue;
1065 frameworkPath[strlen(frameworkPath)-10] = '\0';
1066 checkDylibOverride(frameworkPath);
1067 }
1068 closedir(dirp);
1069 }
1070 }
1071
1072 //
1073 // Turns a colon separated list of strings into a NULL terminated array
1074 // of string pointers. If mainExecutableDir param is not NULL,
1075 // substitutes @loader_path with main executable's dir.
1076 //
1077 static const char** parseColonList(const char* list, const char* mainExecutableDir)
1078 {
1079 static const char* sEmptyList[] = { NULL };
1080
1081 if ( list[0] == '\0' )
1082 return sEmptyList;
1083
1084 int colonCount = 0;
1085 for(const char* s=list; *s != '\0'; ++s) {
1086 if (*s == ':')
1087 ++colonCount;
1088 }
1089
1090 int index = 0;
1091 const char* start = list;
1092 char** result = new char*[colonCount+2];
1093 for(const char* s=list; *s != '\0'; ++s) {
1094 if (*s == ':') {
1095 int len = s-start;
1096 if ( (mainExecutableDir != NULL) && (strncmp(start, "@loader_path/", 13) == 0) ) {
1097 int mainExecDirLen = strlen(mainExecutableDir);
1098 char* str = new char[mainExecDirLen+len+1];
1099 strcpy(str, mainExecutableDir);
1100 strlcat(str, &start[13], mainExecDirLen+len+1);
1101 str[mainExecDirLen+len-13] = '\0';
1102 start = &s[1];
1103 result[index++] = str;
1104 }
1105 else if ( (mainExecutableDir != NULL) && (strncmp(start, "@executable_path/", 17) == 0) ) {
1106 int mainExecDirLen = strlen(mainExecutableDir);
1107 char* str = new char[mainExecDirLen+len+1];
1108 strcpy(str, mainExecutableDir);
1109 strlcat(str, &start[17], mainExecDirLen+len+1);
1110 str[mainExecDirLen+len-17] = '\0';
1111 start = &s[1];
1112 result[index++] = str;
1113 }
1114 else {
1115 char* str = new char[len+1];
1116 strncpy(str, start, len);
1117 str[len] = '\0';
1118 start = &s[1];
1119 result[index++] = str;
1120 }
1121 }
1122 }
1123 int len = strlen(start);
1124 if ( (mainExecutableDir != NULL) && (strncmp(start, "@loader_path/", 13) == 0) ) {
1125 int mainExecDirLen = strlen(mainExecutableDir);
1126 char* str = new char[mainExecDirLen+len+1];
1127 strcpy(str, mainExecutableDir);
1128 strlcat(str, &start[13], mainExecDirLen+len+1);
1129 str[mainExecDirLen+len-13] = '\0';
1130 result[index++] = str;
1131 }
1132 else if ( (mainExecutableDir != NULL) && (strncmp(start, "@executable_path/", 17) == 0) ) {
1133 int mainExecDirLen = strlen(mainExecutableDir);
1134 char* str = new char[mainExecDirLen+len+1];
1135 strcpy(str, mainExecutableDir);
1136 strlcat(str, &start[17], mainExecDirLen+len+1);
1137 str[mainExecDirLen+len-17] = '\0';
1138 result[index++] = str;
1139 }
1140 else {
1141 char* str = new char[len+1];
1142 strcpy(str, start);
1143 result[index++] = str;
1144 }
1145 result[index] = NULL;
1146
1147 //dyld::log("parseColonList(%s)\n", list);
1148 //for(int i=0; result[i] != NULL; ++i)
1149 // dyld::log(" %s\n", result[i]);
1150 return (const char**)result;
1151 }
1152
1153 static void appendParsedColonList(const char* list, const char* mainExecutableDir, const char* const ** storage)
1154 {
1155 const char** newlist = parseColonList(list, mainExecutableDir);
1156 if ( *storage == NULL ) {
1157 // first time, just set
1158 *storage = newlist;
1159 }
1160 else {
1161 // need to append to existing list
1162 const char* const* existing = *storage;
1163 int count = 0;
1164 for(int i=0; existing[i] != NULL; ++i)
1165 ++count;
1166 for(int i=0; newlist[i] != NULL; ++i)
1167 ++count;
1168 const char** combinedList = new const char*[count+2];
1169 int index = 0;
1170 for(int i=0; existing[i] != NULL; ++i)
1171 combinedList[index++] = existing[i];
1172 for(int i=0; newlist[i] != NULL; ++i)
1173 combinedList[index++] = newlist[i];
1174 combinedList[index] = NULL;
1175 // leak old arrays
1176 *storage = combinedList;
1177 }
1178 }
1179
1180
1181 static void paths_expand_roots(const char **paths, const char *key, const char *val)
1182 {
1183 // assert(val != NULL);
1184 // assert(paths != NULL);
1185 if(NULL != key) {
1186 size_t keyLen = strlen(key);
1187 for(int i=0; paths[i] != NULL; ++i) {
1188 if ( strncmp(paths[i], key, keyLen) == 0 ) {
1189 char* newPath = new char[strlen(val) + (strlen(paths[i]) - keyLen) + 1];
1190 strcpy(newPath, val);
1191 strcat(newPath, &paths[i][keyLen]);
1192 paths[i] = newPath;
1193 }
1194 }
1195 }
1196 return;
1197 }
1198
1199 static void removePathWithPrefix(const char* paths[], const char* prefix)
1200 {
1201 size_t prefixLen = strlen(prefix);
1202 int skip = 0;
1203 int i;
1204 for(i = 0; paths[i] != NULL; ++i) {
1205 if ( strncmp(paths[i], prefix, prefixLen) == 0 )
1206 ++skip;
1207 else
1208 paths[i-skip] = paths[i];
1209 }
1210 paths[i-skip] = NULL;
1211 }
1212
1213
1214 #if 0
1215 static void paths_dump(const char **paths)
1216 {
1217 // assert(paths != NULL);
1218 const char **strs = paths;
1219 while(*strs != NULL)
1220 {
1221 dyld::log("\"%s\"\n", *strs);
1222 strs++;
1223 }
1224 return;
1225 }
1226 #endif
1227
1228 static void printOptions(const char* argv[])
1229 {
1230 uint32_t i = 0;
1231 while ( NULL != argv[i] ) {
1232 dyld::log("opt[%i] = \"%s\"\n", i, argv[i]);
1233 i++;
1234 }
1235 }
1236
1237 static void printEnvironmentVariables(const char* envp[])
1238 {
1239 while ( NULL != *envp ) {
1240 dyld::log("%s\n", *envp);
1241 envp++;
1242 }
1243 }
1244
1245 void processDyldEnvironmentVariable(const char* key, const char* value, const char* mainExecutableDir)
1246 {
1247 if ( strcmp(key, "DYLD_FRAMEWORK_PATH") == 0 ) {
1248 appendParsedColonList(value, mainExecutableDir, &sEnv.DYLD_FRAMEWORK_PATH);
1249 }
1250 else if ( strcmp(key, "DYLD_FALLBACK_FRAMEWORK_PATH") == 0 ) {
1251 appendParsedColonList(value, mainExecutableDir, &sEnv.DYLD_FALLBACK_FRAMEWORK_PATH);
1252 }
1253 else if ( strcmp(key, "DYLD_LIBRARY_PATH") == 0 ) {
1254 appendParsedColonList(value, mainExecutableDir, &sEnv.DYLD_LIBRARY_PATH);
1255 }
1256 else if ( strcmp(key, "DYLD_FALLBACK_LIBRARY_PATH") == 0 ) {
1257 appendParsedColonList(value, mainExecutableDir, &sEnv.DYLD_FALLBACK_LIBRARY_PATH);
1258 }
1259 else if ( (strcmp(key, "DYLD_ROOT_PATH") == 0) || (strcmp(key, "DYLD_PATHS_ROOT") == 0) ) {
1260 if ( strcmp(value, "/") != 0 ) {
1261 gLinkContext.rootPaths = parseColonList(value, mainExecutableDir);
1262 for (int i=0; gLinkContext.rootPaths[i] != NULL; ++i) {
1263 if ( gLinkContext.rootPaths[i][0] != '/' ) {
1264 dyld::warn("DYLD_ROOT_PATH not used because it contains a non-absolute path\n");
1265 gLinkContext.rootPaths = NULL;
1266 break;
1267 }
1268 }
1269 }
1270 }
1271 else if ( strcmp(key, "DYLD_IMAGE_SUFFIX") == 0 ) {
1272 gLinkContext.imageSuffix = value;
1273 }
1274 else if ( strcmp(key, "DYLD_INSERT_LIBRARIES") == 0 ) {
1275 sEnv.DYLD_INSERT_LIBRARIES = parseColonList(value, NULL);
1276 }
1277 else if ( strcmp(key, "DYLD_PRINT_OPTS") == 0 ) {
1278 sEnv.DYLD_PRINT_OPTS = true;
1279 }
1280 else if ( strcmp(key, "DYLD_PRINT_ENV") == 0 ) {
1281 sEnv.DYLD_PRINT_ENV = true;
1282 }
1283 else if ( strcmp(key, "DYLD_DISABLE_DOFS") == 0 ) {
1284 sEnv.DYLD_DISABLE_DOFS = true;
1285 }
1286 else if ( strcmp(key, "DYLD_DISABLE_PREFETCH") == 0 ) {
1287 gLinkContext.preFetchDisabled = true;
1288 }
1289 else if ( strcmp(key, "DYLD_PRINT_LIBRARIES") == 0 ) {
1290 sEnv.DYLD_PRINT_LIBRARIES = true;
1291 }
1292 else if ( strcmp(key, "DYLD_PRINT_LIBRARIES_POST_LAUNCH") == 0 ) {
1293 sEnv.DYLD_PRINT_LIBRARIES_POST_LAUNCH = true;
1294 }
1295 else if ( strcmp(key, "DYLD_BIND_AT_LAUNCH") == 0 ) {
1296 sEnv.DYLD_BIND_AT_LAUNCH = true;
1297 }
1298 else if ( strcmp(key, "DYLD_FORCE_FLAT_NAMESPACE") == 0 ) {
1299 gLinkContext.bindFlat = true;
1300 }
1301 else if ( strcmp(key, "DYLD_NEW_LOCAL_SHARED_REGIONS") == 0 ) {
1302 // ignore, no longer relevant but some scripts still set it
1303 }
1304 else if ( strcmp(key, "DYLD_NO_FIX_PREBINDING") == 0 ) {
1305 }
1306 else if ( strcmp(key, "DYLD_PREBIND_DEBUG") == 0 ) {
1307 gLinkContext.verbosePrebinding = true;
1308 }
1309 else if ( strcmp(key, "DYLD_PRINT_INITIALIZERS") == 0 ) {
1310 gLinkContext.verboseInit = true;
1311 }
1312 else if ( strcmp(key, "DYLD_PRINT_DOFS") == 0 ) {
1313 gLinkContext.verboseDOF = true;
1314 }
1315 else if ( strcmp(key, "DYLD_PRINT_STATISTICS") == 0 ) {
1316 sEnv.DYLD_PRINT_STATISTICS = true;
1317 }
1318 else if ( strcmp(key, "DYLD_PRINT_SEGMENTS") == 0 ) {
1319 gLinkContext.verboseMapping = true;
1320 }
1321 else if ( strcmp(key, "DYLD_PRINT_BINDINGS") == 0 ) {
1322 gLinkContext.verboseBind = true;
1323 }
1324 else if ( strcmp(key, "DYLD_PRINT_WEAK_BINDINGS") == 0 ) {
1325 gLinkContext.verboseWeakBind = true;
1326 }
1327 else if ( strcmp(key, "DYLD_PRINT_REBASINGS") == 0 ) {
1328 gLinkContext.verboseRebase = true;
1329 }
1330 else if ( strcmp(key, "DYLD_PRINT_APIS") == 0 ) {
1331 gLogAPIs = true;
1332 }
1333 else if ( strcmp(key, "DYLD_PRINT_WARNINGS") == 0 ) {
1334 gLinkContext.verboseWarnings = true;
1335 }
1336 else if ( strcmp(key, "DYLD_PRINT_RPATHS") == 0 ) {
1337 gLinkContext.verboseRPaths = true;
1338 }
1339 else if ( strcmp(key, "DYLD_PRINT_CS_NOTIFICATIONS") == 0 ) {
1340 sEnv.DYLD_PRINT_CS_NOTIFICATIONS = true;
1341 }
1342 else if ( strcmp(key, "DYLD_PRINT_INTERPOSING") == 0 ) {
1343 gLinkContext.verboseInterposing = true;
1344 }
1345 else if ( strcmp(key, "DYLD_SHARED_REGION") == 0 ) {
1346 if ( strcmp(value, "private") == 0 ) {
1347 gLinkContext.sharedRegionMode = ImageLoader::kUsePrivateSharedRegion;
1348 }
1349 else if ( strcmp(value, "avoid") == 0 ) {
1350 gLinkContext.sharedRegionMode = ImageLoader::kDontUseSharedRegion;
1351 }
1352 else if ( strcmp(value, "use") == 0 ) {
1353 gLinkContext.sharedRegionMode = ImageLoader::kUseSharedRegion;
1354 }
1355 else if ( value[0] == '\0' ) {
1356 gLinkContext.sharedRegionMode = ImageLoader::kUseSharedRegion;
1357 }
1358 else {
1359 dyld::warn("unknown option to DYLD_SHARED_REGION. Valid options are: use, private, avoid\n");
1360 }
1361 }
1362 #if DYLD_SHARED_CACHE_SUPPORT
1363 else if ( strcmp(key, "DYLD_SHARED_CACHE_DIR") == 0 ) {
1364 sSharedCacheDir = value;
1365 }
1366 else if ( strcmp(key, "DYLD_SHARED_CACHE_DONT_VALIDATE") == 0 ) {
1367 sSharedCacheIgnoreInodeAndTimeStamp = true;
1368 }
1369 #endif
1370 else if ( strcmp(key, "DYLD_IGNORE_PREBINDING") == 0 ) {
1371 if ( strcmp(value, "all") == 0 ) {
1372 gLinkContext.prebindUsage = ImageLoader::kUseNoPrebinding;
1373 }
1374 else if ( strcmp(value, "app") == 0 ) {
1375 gLinkContext.prebindUsage = ImageLoader::kUseAllButAppPredbinding;
1376 }
1377 else if ( strcmp(value, "nonsplit") == 0 ) {
1378 gLinkContext.prebindUsage = ImageLoader::kUseSplitSegPrebinding;
1379 }
1380 else if ( value[0] == '\0' ) {
1381 gLinkContext.prebindUsage = ImageLoader::kUseSplitSegPrebinding;
1382 }
1383 else {
1384 dyld::warn("unknown option to DYLD_IGNORE_PREBINDING. Valid options are: all, app, nonsplit\n");
1385 }
1386 }
1387 #if SUPPORT_VERSIONED_PATHS
1388 else if ( strcmp(key, "DYLD_VERSIONED_LIBRARY_PATH") == 0 ) {
1389 appendParsedColonList(value, mainExecutableDir, &sEnv.DYLD_VERSIONED_LIBRARY_PATH);
1390 }
1391 else if ( strcmp(key, "DYLD_VERSIONED_FRAMEWORK_PATH") == 0 ) {
1392 appendParsedColonList(value, mainExecutableDir, &sEnv.DYLD_VERSIONED_FRAMEWORK_PATH);
1393 }
1394 #endif
1395 else {
1396 dyld::warn("unknown environment variable: %s\n", key);
1397 }
1398 }
1399
1400
1401 #if SUPPORT_LC_DYLD_ENVIRONMENT
1402 static void checkLoadCommandEnvironmentVariables()
1403 {
1404 // <rdar://problem/8440934> Support augmenting dyld environment variables in load commands
1405 const uint32_t cmd_count = sMainExecutableMachHeader->ncmds;
1406 const struct load_command* const cmds = (struct load_command*)(((char*)sMainExecutableMachHeader)+sizeof(macho_header));
1407 const struct load_command* cmd = cmds;
1408 for (uint32_t i = 0; i < cmd_count; ++i) {
1409 switch (cmd->cmd) {
1410 case LC_DYLD_ENVIRONMENT:
1411 {
1412 const struct dylinker_command* envcmd = (struct dylinker_command*)cmd;
1413 const char* keyEqualsValue = (char*)envcmd + envcmd->name.offset;
1414 char mainExecutableDir[strlen(sExecPath)];
1415 strcpy(mainExecutableDir, sExecPath);
1416 char* lastSlash = strrchr(mainExecutableDir, '/');
1417 if ( lastSlash != NULL)
1418 lastSlash[1] = '\0';
1419 // only process variables that start with DYLD_ and end in _PATH
1420 if ( (strncmp(keyEqualsValue, "DYLD_", 5) == 0) ) {
1421 const char* equals = strchr(keyEqualsValue, '=');
1422 if ( equals != NULL ) {
1423 if ( strncmp(&equals[-5], "_PATH", 5) == 0 ) {
1424 const char* value = &equals[1];
1425 const int keyLen = equals-keyEqualsValue;
1426 char key[keyLen+1];
1427 strncpy(key, keyEqualsValue, keyLen);
1428 key[keyLen] = '\0';
1429 //dyld::log("processing: %s\n", keyEqualsValue);
1430 //dyld::log("mainExecutableDir: %s\n", mainExecutableDir);
1431 processDyldEnvironmentVariable(key, value, mainExecutableDir);
1432 }
1433 }
1434 }
1435 }
1436 break;
1437 }
1438 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
1439 }
1440 }
1441 #endif // SUPPORT_LC_DYLD_ENVIRONMENT
1442
1443
1444 #if SUPPORT_VERSIONED_PATHS
1445 static void checkVersionedPaths()
1446 {
1447 // search DYLD_VERSIONED_LIBRARY_PATH directories for dylibs and check if they are newer
1448 if ( sEnv.DYLD_VERSIONED_LIBRARY_PATH != NULL ) {
1449 for(const char* const* lp = sEnv.DYLD_VERSIONED_LIBRARY_PATH; *lp != NULL; ++lp) {
1450 checkDylibOverridesInDir(*lp);
1451 }
1452 }
1453
1454 // search DYLD_VERSIONED_FRAMEWORK_PATH directories for dylibs and check if they are newer
1455 if ( sEnv.DYLD_VERSIONED_FRAMEWORK_PATH != NULL ) {
1456 for(const char* const* fp = sEnv.DYLD_VERSIONED_FRAMEWORK_PATH; *fp != NULL; ++fp) {
1457 checkFrameworkOverridesInDir(*fp);
1458 }
1459 }
1460 }
1461 #endif
1462
1463
1464 //
1465 // For security, setuid programs ignore DYLD_* environment variables.
1466 // Additionally, the DYLD_* enviroment variables are removed
1467 // from the environment, so that any child processes don't see them.
1468 //
1469 static void pruneEnvironmentVariables(const char* envp[], const char*** applep)
1470 {
1471 // delete all DYLD_* and LD_LIBRARY_PATH environment variables
1472 int removedCount = 0;
1473 const char** d = envp;
1474 for(const char** s = envp; *s != NULL; s++) {
1475 if ( (strncmp(*s, "DYLD_", 5) != 0) && (strncmp(*s, "LD_LIBRARY_PATH=", 16) != 0) ) {
1476 *d++ = *s;
1477 }
1478 else {
1479 ++removedCount;
1480 }
1481 }
1482 *d++ = NULL;
1483
1484 // slide apple parameters
1485 if ( removedCount > 0 ) {
1486 *applep = d;
1487 do {
1488 *d = d[removedCount];
1489 } while ( *d++ != NULL );
1490 for(int i=0; i < removedCount; ++i)
1491 *d++ = NULL;
1492 }
1493
1494 // disable framework and library fallback paths for setuid binaries rdar://problem/4589305
1495 sEnv.DYLD_FALLBACK_FRAMEWORK_PATH = NULL;
1496 sEnv.DYLD_FALLBACK_LIBRARY_PATH = NULL;
1497 }
1498
1499
1500 static void checkEnvironmentVariables(const char* envp[], bool ignoreEnviron)
1501 {
1502 const char* home = NULL;
1503 const char** p;
1504 for(p = envp; *p != NULL; p++) {
1505 const char* keyEqualsValue = *p;
1506 if ( strncmp(keyEqualsValue, "DYLD_", 5) == 0 ) {
1507 const char* equals = strchr(keyEqualsValue, '=');
1508 if ( (equals != NULL) && !ignoreEnviron ) {
1509 const char* value = &equals[1];
1510 const int keyLen = equals-keyEqualsValue;
1511 char key[keyLen+1];
1512 strncpy(key, keyEqualsValue, keyLen);
1513 key[keyLen] = '\0';
1514 processDyldEnvironmentVariable(key, value, NULL);
1515 }
1516 }
1517 else if ( strncmp(keyEqualsValue, "HOME=", 5) == 0 ) {
1518 home = &keyEqualsValue[5];
1519 }
1520 else if ( strncmp(keyEqualsValue, "LD_LIBRARY_PATH=", 16) == 0 ) {
1521 const char* path = &keyEqualsValue[16];
1522 sEnv.LD_LIBRARY_PATH = parseColonList(path, NULL);
1523 }
1524 }
1525
1526 #if SUPPORT_LC_DYLD_ENVIRONMENT
1527 checkLoadCommandEnvironmentVariables();
1528 #endif // SUPPORT_LC_DYLD_ENVIRONMENT
1529
1530 // default value for DYLD_FALLBACK_FRAMEWORK_PATH, if not set in environment
1531 if ( sEnv.DYLD_FALLBACK_FRAMEWORK_PATH == NULL ) {
1532 const char** paths = sFrameworkFallbackPaths;
1533 if ( home == NULL )
1534 removePathWithPrefix(paths, "$HOME");
1535 else
1536 paths_expand_roots(paths, "$HOME", home);
1537 sEnv.DYLD_FALLBACK_FRAMEWORK_PATH = paths;
1538 }
1539
1540 // default value for DYLD_FALLBACK_LIBRARY_PATH, if not set in environment
1541 if ( sEnv.DYLD_FALLBACK_LIBRARY_PATH == NULL ) {
1542 const char** paths = sLibraryFallbackPaths;
1543 if ( home == NULL )
1544 removePathWithPrefix(paths, "$HOME");
1545 else
1546 paths_expand_roots(paths, "$HOME", home);
1547 sEnv.DYLD_FALLBACK_LIBRARY_PATH = paths;
1548 }
1549
1550 #if SUPPORT_VERSIONED_PATHS
1551 checkVersionedPaths();
1552 #endif
1553 }
1554
1555
1556 static void getHostInfo()
1557 {
1558 #if CPU_SUBTYPES_SUPPORTED
1559 #if __ARM_ARCH_7A__
1560 sHostCPU = CPU_TYPE_ARM;
1561 sHostCPUsubtype = CPU_SUBTYPE_ARM_V7;
1562 #elif __ARM_ARCH_6K__
1563 sHostCPU = CPU_TYPE_ARM;
1564 sHostCPUsubtype = CPU_SUBTYPE_ARM_V6;
1565 #else
1566 struct host_basic_info info;
1567 mach_msg_type_number_t count = HOST_BASIC_INFO_COUNT;
1568 mach_port_t hostPort = mach_host_self();
1569 kern_return_t result = host_info(hostPort, HOST_BASIC_INFO, (host_info_t)&info, &count);
1570 if ( result != KERN_SUCCESS )
1571 throw "host_info() failed";
1572 sHostCPU = info.cpu_type;
1573 sHostCPUsubtype = info.cpu_subtype;
1574 #endif
1575 #endif
1576 }
1577
1578 static void checkSharedRegionDisable()
1579 {
1580 #if __MAC_OS_X_VERSION_MIN_REQUIRED
1581 // if main executable has segments that overlap the shared region,
1582 // then disable using the shared region
1583 if ( sMainExecutable->overlapsWithAddressRange((void*)(uintptr_t)SHARED_REGION_BASE, (void*)(uintptr_t)(SHARED_REGION_BASE + SHARED_REGION_SIZE)) ) {
1584 gLinkContext.sharedRegionMode = ImageLoader::kDontUseSharedRegion;
1585 if ( gLinkContext.verboseMapping )
1586 dyld::warn("disabling shared region because main executable overlaps\n");
1587 }
1588 #endif
1589 // iPhoneOS cannot run without shared region
1590 }
1591
1592 bool validImage(const ImageLoader* possibleImage)
1593 {
1594 const unsigned int imageCount = sAllImages.size();
1595 for(unsigned int i=0; i < imageCount; ++i) {
1596 if ( possibleImage == sAllImages[i] ) {
1597 return true;
1598 }
1599 }
1600 return false;
1601 }
1602
1603 uint32_t getImageCount()
1604 {
1605 return sAllImages.size();
1606 }
1607
1608 ImageLoader* getIndexedImage(unsigned int index)
1609 {
1610 if ( index < sAllImages.size() )
1611 return sAllImages[index];
1612 return NULL;
1613 }
1614
1615 ImageLoader* findImageByMachHeader(const struct mach_header* target)
1616 {
1617 return findMappedRange((uintptr_t)target);
1618 }
1619
1620
1621 ImageLoader* findImageContainingAddress(const void* addr)
1622 {
1623 return findMappedRange((uintptr_t)addr);
1624 }
1625
1626
1627 ImageLoader* findImageContainingSymbol(const void* symbol)
1628 {
1629 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
1630 ImageLoader* anImage = *it;
1631 if ( anImage->containsSymbol(symbol) )
1632 return anImage;
1633 }
1634 return NULL;
1635 }
1636
1637
1638
1639 void forEachImageDo( void (*callback)(ImageLoader*, void* userData), void* userData)
1640 {
1641 const unsigned int imageCount = sAllImages.size();
1642 for(unsigned int i=0; i < imageCount; ++i) {
1643 ImageLoader* anImage = sAllImages[i];
1644 (*callback)(anImage, userData);
1645 }
1646 }
1647
1648 ImageLoader* findLoadedImage(const struct stat& stat_buf)
1649 {
1650 const unsigned int imageCount = sAllImages.size();
1651 for(unsigned int i=0; i < imageCount; ++i){
1652 ImageLoader* anImage = sAllImages[i];
1653 if ( anImage->statMatch(stat_buf) )
1654 return anImage;
1655 }
1656 return NULL;
1657 }
1658
1659 // based on ANSI-C strstr()
1660 static const char* strrstr(const char* str, const char* sub)
1661 {
1662 const int sublen = strlen(sub);
1663 for(const char* p = &str[strlen(str)]; p != str; --p) {
1664 if ( strncmp(p, sub, sublen) == 0 )
1665 return p;
1666 }
1667 return NULL;
1668 }
1669
1670
1671 //
1672 // Find framework path
1673 //
1674 // /path/foo.framework/foo => foo.framework/foo
1675 // /path/foo.framework/Versions/A/foo => foo.framework/Versions/A/foo
1676 // /path/foo.framework/Frameworks/bar.framework/bar => bar.framework/bar
1677 // /path/foo.framework/Libraries/bar.dylb => NULL
1678 // /path/foo.framework/bar => NULL
1679 //
1680 // Returns NULL if not a framework path
1681 //
1682 static const char* getFrameworkPartialPath(const char* path)
1683 {
1684 const char* dirDot = strrstr(path, ".framework/");
1685 if ( dirDot != NULL ) {
1686 const char* dirStart = dirDot;
1687 for ( ; dirStart >= path; --dirStart) {
1688 if ( (*dirStart == '/') || (dirStart == path) ) {
1689 const char* frameworkStart = &dirStart[1];
1690 if ( dirStart == path )
1691 --frameworkStart;
1692 int len = dirDot - frameworkStart;
1693 char framework[len+1];
1694 strncpy(framework, frameworkStart, len);
1695 framework[len] = '\0';
1696 const char* leaf = strrchr(path, '/');
1697 if ( leaf != NULL ) {
1698 if ( strcmp(framework, &leaf[1]) == 0 ) {
1699 return frameworkStart;
1700 }
1701 if ( gLinkContext.imageSuffix != NULL ) {
1702 // some debug frameworks have install names that end in _debug
1703 if ( strncmp(framework, &leaf[1], len) == 0 ) {
1704 if ( strcmp( gLinkContext.imageSuffix, &leaf[len+1]) == 0 )
1705 return frameworkStart;
1706 }
1707 }
1708 }
1709 }
1710 }
1711 }
1712 return NULL;
1713 }
1714
1715
1716 static const char* getLibraryLeafName(const char* path)
1717 {
1718 const char* start = strrchr(path, '/');
1719 if ( start != NULL )
1720 return &start[1];
1721 else
1722 return path;
1723 }
1724
1725
1726 // only for architectures that use cpu-sub-types
1727 #if CPU_SUBTYPES_SUPPORTED
1728
1729 const cpu_subtype_t CPU_SUBTYPE_END_OF_LIST = -1;
1730
1731
1732 //
1733 // A fat file may contain multiple sub-images for the same CPU type.
1734 // In that case, dyld picks which sub-image to use by scanning a table
1735 // of preferred cpu-sub-types for the running cpu.
1736 //
1737 // There is one row in the table for each cpu-sub-type on which dyld might run.
1738 // The first entry in a row is that cpu-sub-type. It is followed by all
1739 // cpu-sub-types that can run on that cpu, if preferred order. Each row ends with
1740 // a "SUBTYPE_ALL" (to denote that images written to run on any cpu-sub-type are usable),
1741 // followed by one or more CPU_SUBTYPE_END_OF_LIST to pad out this row.
1742 //
1743
1744
1745 #if __ppc__
1746 //
1747 // 32-bit PowerPC sub-type lists
1748 //
1749 const int kPPC_RowCount = 4;
1750 static const cpu_subtype_t kPPC32[kPPC_RowCount][6] = {
1751 // G5 can run any code
1752 { 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 },
1753
1754 // G4 can run all but G5 code
1755 { 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 },
1756 { 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 },
1757
1758 // G3 cannot run G4 or G5 code
1759 { 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 }
1760 };
1761 #endif
1762
1763
1764 #if __arm__
1765 //
1766 // ARM sub-type lists
1767 //
1768 const int kARM_RowCount = 5;
1769 static const cpu_subtype_t kARM[kARM_RowCount][6] = {
1770 // armv7 can run: v7, v6, v5, and v4
1771 { CPU_SUBTYPE_ARM_V7, CPU_SUBTYPE_ARM_V6, CPU_SUBTYPE_ARM_V5TEJ, CPU_SUBTYPE_ARM_V4T, CPU_SUBTYPE_ARM_ALL, CPU_SUBTYPE_END_OF_LIST },
1772
1773 // armv6 can run: v6, v5, and v4
1774 { CPU_SUBTYPE_ARM_V6, CPU_SUBTYPE_ARM_V5TEJ, CPU_SUBTYPE_ARM_V4T, CPU_SUBTYPE_ARM_ALL, CPU_SUBTYPE_END_OF_LIST, CPU_SUBTYPE_END_OF_LIST },
1775
1776 // xscale can run: xscale, v5, and v4
1777 { CPU_SUBTYPE_ARM_XSCALE, CPU_SUBTYPE_ARM_V5TEJ, CPU_SUBTYPE_ARM_V4T, CPU_SUBTYPE_ARM_ALL, CPU_SUBTYPE_END_OF_LIST, CPU_SUBTYPE_END_OF_LIST },
1778
1779 // armv5 can run: v5 and v4
1780 { CPU_SUBTYPE_ARM_V5TEJ, CPU_SUBTYPE_ARM_V4T, CPU_SUBTYPE_ARM_ALL, CPU_SUBTYPE_END_OF_LIST, CPU_SUBTYPE_END_OF_LIST, CPU_SUBTYPE_END_OF_LIST },
1781
1782 // armv4 can run: v4
1783 { CPU_SUBTYPE_ARM_V4T, CPU_SUBTYPE_ARM_ALL, CPU_SUBTYPE_END_OF_LIST, CPU_SUBTYPE_END_OF_LIST, CPU_SUBTYPE_END_OF_LIST, CPU_SUBTYPE_END_OF_LIST },
1784 };
1785 #endif
1786
1787
1788 // scan the tables above to find the cpu-sub-type-list for this machine
1789 static const cpu_subtype_t* findCPUSubtypeList(cpu_type_t cpu, cpu_subtype_t subtype)
1790 {
1791 switch (cpu) {
1792 #if __ppc__
1793 case CPU_TYPE_POWERPC:
1794 for (int i=0; i < kPPC_RowCount ; ++i) {
1795 if ( kPPC32[i][0] == subtype )
1796 return kPPC32[i];
1797 }
1798 break;
1799 #endif
1800 #if __arm__
1801 case CPU_TYPE_ARM:
1802 for (int i=0; i < kARM_RowCount ; ++i) {
1803 if ( kARM[i][0] == subtype )
1804 return kARM[i];
1805 }
1806 break;
1807 #endif
1808 }
1809 return NULL;
1810 }
1811
1812
1813
1814
1815 // scan fat table-of-contents for best most preferred subtype
1816 static bool fatFindBestFromOrderedList(cpu_type_t cpu, const cpu_subtype_t list[], const fat_header* fh, uint64_t* offset, uint64_t* len)
1817 {
1818 const fat_arch* const archs = (fat_arch*)(((char*)fh)+sizeof(fat_header));
1819 for (uint32_t subTypeIndex=0; list[subTypeIndex] != CPU_SUBTYPE_END_OF_LIST; ++subTypeIndex) {
1820 for(uint32_t fatIndex=0; fatIndex < OSSwapBigToHostInt32(fh->nfat_arch); ++fatIndex) {
1821 if ( ((cpu_type_t)OSSwapBigToHostInt32(archs[fatIndex].cputype) == cpu)
1822 && (list[subTypeIndex] == (cpu_subtype_t)OSSwapBigToHostInt32(archs[fatIndex].cpusubtype)) ) {
1823 *offset = OSSwapBigToHostInt32(archs[fatIndex].offset);
1824 *len = OSSwapBigToHostInt32(archs[fatIndex].size);
1825 return true;
1826 }
1827 }
1828 }
1829 return false;
1830 }
1831
1832 // scan fat table-of-contents for exact match of cpu and cpu-sub-type
1833 static bool fatFindExactMatch(cpu_type_t cpu, cpu_subtype_t subtype, const fat_header* fh, uint64_t* offset, uint64_t* len)
1834 {
1835 const fat_arch* archs = (fat_arch*)(((char*)fh)+sizeof(fat_header));
1836 for(uint32_t i=0; i < OSSwapBigToHostInt32(fh->nfat_arch); ++i) {
1837 if ( ((cpu_type_t)OSSwapBigToHostInt32(archs[i].cputype) == cpu)
1838 && ((cpu_subtype_t)OSSwapBigToHostInt32(archs[i].cpusubtype) == subtype) ) {
1839 *offset = OSSwapBigToHostInt32(archs[i].offset);
1840 *len = OSSwapBigToHostInt32(archs[i].size);
1841 return true;
1842 }
1843 }
1844 return false;
1845 }
1846
1847 // scan fat table-of-contents for image with matching cpu-type and runs-on-all-sub-types
1848 static bool fatFindRunsOnAllCPUs(cpu_type_t cpu, const fat_header* fh, uint64_t* offset, uint64_t* len)
1849 {
1850 const fat_arch* archs = (fat_arch*)(((char*)fh)+sizeof(fat_header));
1851 for(uint32_t i=0; i < OSSwapBigToHostInt32(fh->nfat_arch); ++i) {
1852 if ( (cpu_type_t)OSSwapBigToHostInt32(archs[i].cputype) == cpu) {
1853 switch (cpu) {
1854 #if __ppc__
1855 case CPU_TYPE_POWERPC:
1856 if ( (cpu_subtype_t)OSSwapBigToHostInt32(archs[i].cpusubtype) == CPU_SUBTYPE_POWERPC_ALL ) {
1857 *offset = OSSwapBigToHostInt32(archs[i].offset);
1858 *len = OSSwapBigToHostInt32(archs[i].size);
1859 return true;
1860 }
1861 break;
1862 #endif
1863 #if __arm__
1864 case CPU_TYPE_ARM:
1865 if ( (cpu_subtype_t)OSSwapBigToHostInt32(archs[i].cpusubtype) == CPU_SUBTYPE_ARM_ALL ) {
1866 *offset = OSSwapBigToHostInt32(archs[i].offset);
1867 *len = OSSwapBigToHostInt32(archs[i].size);
1868 return true;
1869 }
1870 break;
1871 #endif
1872 }
1873 }
1874 }
1875 return false;
1876 }
1877
1878 #endif // CPU_SUBTYPES_SUPPORTED
1879
1880 //
1881 // A fat file may contain multiple sub-images for the same cpu-type,
1882 // each optimized for a different cpu-sub-type (e.g G3 or G5).
1883 // This routine picks the optimal sub-image.
1884 //
1885 static bool fatFindBest(const fat_header* fh, uint64_t* offset, uint64_t* len)
1886 {
1887 #if CPU_SUBTYPES_SUPPORTED
1888 // assume all dylibs loaded must have same cpu type as main executable
1889 const cpu_type_t cpu = sMainExecutableMachHeader->cputype;
1890
1891 // We only know the subtype to use if the main executable cpu type matches the host
1892 if ( (cpu & CPU_TYPE_MASK) == sHostCPU ) {
1893 // get preference ordered list of subtypes
1894 const cpu_subtype_t* subTypePreferenceList = findCPUSubtypeList(cpu, sHostCPUsubtype);
1895
1896 // use ordered list to find best sub-image in fat file
1897 if ( subTypePreferenceList != NULL )
1898 return fatFindBestFromOrderedList(cpu, subTypePreferenceList, fh, offset, len);
1899
1900 // if running cpu is not in list, try for an exact match
1901 if ( fatFindExactMatch(cpu, sHostCPUsubtype, fh, offset, len) )
1902 return true;
1903 }
1904
1905 // running on an uknown cpu, can only load generic code
1906 return fatFindRunsOnAllCPUs(cpu, fh, offset, len);
1907 #else
1908 // just find first slice with matching architecture
1909 const fat_arch* archs = (fat_arch*)(((char*)fh)+sizeof(fat_header));
1910 for(uint32_t i=0; i < OSSwapBigToHostInt32(fh->nfat_arch); ++i) {
1911 if ( (cpu_type_t)OSSwapBigToHostInt32(archs[i].cputype) == sMainExecutableMachHeader->cputype) {
1912 *offset = OSSwapBigToHostInt32(archs[i].offset);
1913 *len = OSSwapBigToHostInt32(archs[i].size);
1914 return true;
1915 }
1916 }
1917 return false;
1918 #endif
1919 }
1920
1921
1922
1923 //
1924 // This is used to validate if a non-fat (aka thin or raw) mach-o file can be used
1925 // on the current processor. //
1926 bool isCompatibleMachO(const uint8_t* firstPage, const char* path)
1927 {
1928 #if CPU_SUBTYPES_SUPPORTED
1929 // It is deemed compatible if any of the following are true:
1930 // 1) mach_header subtype is in list of compatible subtypes for running processor
1931 // 2) mach_header subtype is same as running processor subtype
1932 // 3) mach_header subtype runs on all processor variants
1933 const mach_header* mh = (mach_header*)firstPage;
1934 if ( mh->magic == sMainExecutableMachHeader->magic ) {
1935 if ( mh->cputype == sMainExecutableMachHeader->cputype ) {
1936 if ( (mh->cputype & CPU_TYPE_MASK) == sHostCPU ) {
1937 // get preference ordered list of subtypes that this machine can use
1938 const cpu_subtype_t* subTypePreferenceList = findCPUSubtypeList(mh->cputype, sHostCPUsubtype);
1939 if ( subTypePreferenceList != NULL ) {
1940 // if image's subtype is in the list, it is compatible
1941 for (const cpu_subtype_t* p = subTypePreferenceList; *p != CPU_SUBTYPE_END_OF_LIST; ++p) {
1942 if ( *p == mh->cpusubtype )
1943 return true;
1944 }
1945 // have list and not in list, so not compatible
1946 throwf("incompatible cpu-subtype: 0x%08X in %s", mh->cpusubtype, path);
1947 }
1948 // unknown cpu sub-type, but if exact match for current subtype then ok to use
1949 if ( mh->cpusubtype == sHostCPUsubtype )
1950 return true;
1951 }
1952
1953 // cpu type has no ordered list of subtypes
1954 switch (mh->cputype) {
1955 case CPU_TYPE_POWERPC:
1956 // allow _ALL to be used by any client
1957 if ( mh->cpusubtype == CPU_SUBTYPE_POWERPC_ALL )
1958 return true;
1959 break;
1960 case CPU_TYPE_POWERPC64:
1961 case CPU_TYPE_I386:
1962 case CPU_TYPE_X86_64:
1963 // subtypes are not used or these architectures
1964 return true;
1965 }
1966 }
1967 }
1968 #else
1969 // For architectures that don't support cpu-sub-types
1970 // this just check the cpu type.
1971 const mach_header* mh = (mach_header*)firstPage;
1972 if ( mh->magic == sMainExecutableMachHeader->magic ) {
1973 if ( mh->cputype == sMainExecutableMachHeader->cputype ) {
1974 return true;
1975 }
1976 }
1977 #endif
1978 return false;
1979 }
1980
1981
1982
1983
1984 // The kernel maps in main executable before dyld gets control. We need to
1985 // make an ImageLoader* for the already mapped in main executable.
1986 static ImageLoader* instantiateFromLoadedImage(const macho_header* mh, uintptr_t slide, const char* path)
1987 {
1988 // try mach-o loader
1989 if ( isCompatibleMachO((const uint8_t*)mh, path) ) {
1990 ImageLoader* image = ImageLoaderMachO::instantiateMainExecutable(mh, slide, path, gLinkContext);
1991 addImage(image);
1992 return image;
1993 }
1994
1995 throw "main executable not a known format";
1996 }
1997
1998
1999 #if DYLD_SHARED_CACHE_SUPPORT
2000 static bool findInSharedCacheImage(const char* path, const struct stat* stat_buf, const macho_header** mh, const char** pathInCache, long* slide)
2001 {
2002 if ( sSharedCache != NULL ) {
2003 #if __MAC_OS_X_VERSION_MIN_REQUIRED
2004 // Mac OS X always requires inode/mtime to valid cache
2005 // if stat() not done yet, do it now
2006 struct stat statb;
2007 if ( stat_buf == NULL ) {
2008 if ( stat(path, &statb) == -1 )
2009 return false;
2010 stat_buf = &statb;
2011 }
2012 #endif
2013 // walk shared cache to see if there is a cached image that matches the inode/mtime/path desired
2014 const dyld_cache_image_info* const start = (dyld_cache_image_info*)((uint8_t*)sSharedCache + sSharedCache->imagesOffset);
2015 const dyld_cache_image_info* const end = &start[sSharedCache->imagesCount];
2016 for( const dyld_cache_image_info* p = start; p != end; ++p) {
2017 #if __IPHONE_OS_VERSION_MIN_REQUIRED
2018 // just check path
2019 const char* aPath = (char*)sSharedCache + p->pathFileOffset;
2020 if ( strcmp(path, aPath) == 0 ) {
2021 // found image in cache
2022 *mh = (macho_header*)(p->address+sSharedCacheSlide);
2023 *pathInCache = aPath;
2024 *slide = sSharedCacheSlide;
2025 return true;
2026 }
2027 #elif __MAC_OS_X_VERSION_MIN_REQUIRED
2028 // check mtime and inode first because it is fast
2029 if ( sSharedCacheIgnoreInodeAndTimeStamp
2030 || ( ((time_t)p->modTime == stat_buf->st_mtime) && ((ino_t)p->inode == stat_buf->st_ino) ) ) {
2031 // mod-time and inode match an image in the shared cache, now check path
2032 const char* aPath = (char*)sSharedCache + p->pathFileOffset;
2033 bool cacheHit = (strcmp(path, aPath) == 0);
2034 if ( ! cacheHit ) {
2035 // path does not match install name of dylib in cache, but inode and mtime does match
2036 // perhaps path is a symlink to the cached dylib
2037 struct stat pathInCacheStatBuf;
2038 if ( stat(aPath, &pathInCacheStatBuf) != -1 )
2039 cacheHit = ( (pathInCacheStatBuf.st_dev == stat_buf->st_dev) && (pathInCacheStatBuf.st_ino == stat_buf->st_ino) );
2040 }
2041 if ( cacheHit ) {
2042 // found image in cache, return info
2043 *mh = (macho_header*)(p->address+sSharedCacheSlide);
2044 //dyld::log("findInSharedCacheImage(), mh=%p, p->address=0x%0llX, slid=0x%0lX, path=%p\n",
2045 // *mh, p->address, sSharedCacheSlide, aPath);
2046 *pathInCache = aPath;
2047 *slide = sSharedCacheSlide;
2048 return true;
2049 }
2050 }
2051 #endif
2052 }
2053 }
2054 return false;
2055 }
2056
2057 bool inSharedCache(const char* path)
2058 {
2059 const macho_header* mhInCache;
2060 const char* pathInCache;
2061 long slide;
2062 return findInSharedCacheImage(path, NULL, &mhInCache, &pathInCache, &slide);
2063 }
2064
2065 #endif
2066
2067 static ImageLoader* checkandAddImage(ImageLoader* image, const LoadContext& context)
2068 {
2069 // now sanity check that this loaded image does not have the same install path as any existing image
2070 const char* loadedImageInstallPath = image->getInstallPath();
2071 if ( image->isDylib() && (loadedImageInstallPath != NULL) && (loadedImageInstallPath[0] == '/') ) {
2072 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
2073 ImageLoader* anImage = *it;
2074 const char* installPath = anImage->getInstallPath();
2075 if ( installPath != NULL) {
2076 if ( strcmp(loadedImageInstallPath, installPath) == 0 ) {
2077 //dyld::log("duplicate(%s) => %p\n", installPath, anImage);
2078 removeImage(image);
2079 ImageLoader::deleteImage(image);
2080 return anImage;
2081 }
2082 }
2083 }
2084 }
2085
2086 // some API's restrict what they can load
2087 if ( context.mustBeBundle && !image->isBundle() )
2088 throw "not a bundle";
2089 if ( context.mustBeDylib && !image->isDylib() )
2090 throw "not a dylib";
2091
2092 // regular main executables cannot be loaded
2093 if ( image->isExecutable() ) {
2094 if ( !context.canBePIE || !image->isPositionIndependentExecutable() )
2095 throw "can't load a main executable";
2096 }
2097
2098 // don't add bundles to global list, they can be loaded but not linked. When linked it will be added to list
2099 if ( ! image->isBundle() )
2100 addImage(image);
2101
2102 return image;
2103 }
2104
2105 // map in file and instantiate an ImageLoader
2106 static ImageLoader* loadPhase6(int fd, const struct stat& stat_buf, const char* path, const LoadContext& context)
2107 {
2108 //dyld::log("%s(%s)\n", __func__ , path);
2109 uint64_t fileOffset = 0;
2110 uint64_t fileLength = stat_buf.st_size;
2111
2112 // validate it is a file (not directory)
2113 if ( (stat_buf.st_mode & S_IFMT) != S_IFREG )
2114 throw "not a file";
2115
2116 uint8_t firstPage[4096];
2117 bool shortPage = false;
2118
2119 // min mach-o file is 4K
2120 if ( fileLength < 4096 ) {
2121 if ( pread(fd, firstPage, fileLength, 0) != (ssize_t)fileLength )
2122 throwf("pread of short file failed: %d", errno);
2123 shortPage = true;
2124 }
2125 else {
2126 if ( pread(fd, firstPage, 4096,0) != 4096 )
2127 throwf("pread of first 4K failed: %d", errno);
2128 }
2129
2130 // if fat wrapper, find usable sub-file
2131 const fat_header* fileStartAsFat = (fat_header*)firstPage;
2132 if ( fileStartAsFat->magic == OSSwapBigToHostInt32(FAT_MAGIC) ) {
2133 if ( fatFindBest(fileStartAsFat, &fileOffset, &fileLength) ) {
2134 if ( (fileOffset+fileLength) > (uint64_t)(stat_buf.st_size) )
2135 throwf("truncated fat file. file length=%llu, but needed slice goes to %llu", stat_buf.st_size, fileOffset+fileLength);
2136 if (pread(fd, firstPage, 4096, fileOffset) != 4096)
2137 throwf("pread of fat file failed: %d", errno);
2138 }
2139 else {
2140 throw "no matching architecture in universal wrapper";
2141 }
2142 }
2143
2144 // try mach-o loader
2145 if ( shortPage )
2146 throw "file too short";
2147 if ( isCompatibleMachO(firstPage, path) ) {
2148
2149 // only MH_BUNDLE, MH_DYLIB, and some MH_EXECUTE can be dynamically loaded
2150 switch ( ((mach_header*)firstPage)->filetype ) {
2151 case MH_EXECUTE:
2152 case MH_DYLIB:
2153 case MH_BUNDLE:
2154 break;
2155 default:
2156 throw "mach-o, but wrong filetype";
2157 }
2158
2159 // instantiate an image
2160 ImageLoader* image = ImageLoaderMachO::instantiateFromFile(path, fd, firstPage, fileOffset, fileLength, stat_buf, gLinkContext);
2161
2162 // validate
2163 return checkandAddImage(image, context);
2164 }
2165
2166 // try other file formats here...
2167
2168
2169 // throw error about what was found
2170 switch (*(uint32_t*)firstPage) {
2171 case MH_MAGIC:
2172 case MH_CIGAM:
2173 case MH_MAGIC_64:
2174 case MH_CIGAM_64:
2175 throw "mach-o, but wrong architecture";
2176 default:
2177 throwf("unknown file type, first eight bytes: 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X",
2178 firstPage[0], firstPage[1], firstPage[2], firstPage[3], firstPage[4], firstPage[5], firstPage[6],firstPage[7]);
2179 }
2180 }
2181
2182
2183 static ImageLoader* loadPhase5open(const char* path, const LoadContext& context, const struct stat& stat_buf, std::vector<const char*>* exceptions)
2184 {
2185 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
2186
2187 // open file (automagically closed when this function exits)
2188 FileOpener file(path);
2189
2190 // just return NULL if file not found, but record any other errors
2191 if ( file.getFileDescriptor() == -1 ) {
2192 int err = errno;
2193 if ( err != ENOENT ) {
2194 const char* newMsg = dyld::mkstringf("%s: open() failed with errno=%d", path, err);
2195 exceptions->push_back(newMsg);
2196 }
2197 return NULL;
2198 }
2199
2200 try {
2201 return loadPhase6(file.getFileDescriptor(), stat_buf, path, context);
2202 }
2203 catch (const char* msg) {
2204 const char* newMsg = dyld::mkstringf("%s: %s", path, msg);
2205 exceptions->push_back(newMsg);
2206 free((void*)msg);
2207 return NULL;
2208 }
2209 }
2210
2211
2212 #if __MAC_OS_X_VERSION_MIN_REQUIRED
2213 static ImageLoader* loadPhase5load(const char* path, const char* orgPath, const LoadContext& context, std::vector<const char*>* exceptions)
2214 {
2215 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
2216 ImageLoader* image = NULL;
2217
2218 // just return NULL if file not found, but record any other errors
2219 struct stat stat_buf;
2220 if ( stat(path, &stat_buf) == -1 ) {
2221 int err = errno;
2222 if ( err != ENOENT ) {
2223 exceptions->push_back(dyld::mkstringf("%s: stat() failed with errno=%d", path, err));
2224 }
2225 return NULL;
2226 }
2227
2228 // in case image was renamed or found via symlinks, check for inode match
2229 image = findLoadedImage(stat_buf);
2230 if ( image != NULL )
2231 return image;
2232
2233 // do nothing if not already loaded and if RTLD_NOLOAD or NSADDIMAGE_OPTION_RETURN_ONLY_IF_LOADED
2234 if ( context.dontLoad )
2235 return NULL;
2236
2237 #if DYLD_SHARED_CACHE_SUPPORT
2238 // see if this image is in shared cache
2239 const macho_header* mhInCache;
2240 const char* pathInCache;
2241 long slideInCache;
2242 if ( findInSharedCacheImage(path, &stat_buf, &mhInCache, &pathInCache, &slideInCache) ) {
2243 image = ImageLoaderMachO::instantiateFromCache(mhInCache, pathInCache, slideInCache, stat_buf, gLinkContext);
2244 return checkandAddImage(image, context);
2245 }
2246 #endif
2247 // file exists and is not in dyld shared cache, so open it
2248 return loadPhase5open(path, context, stat_buf, exceptions);
2249 }
2250 #endif // __MAC_OS_X_VERSION_MIN_REQUIRED
2251
2252
2253
2254 #if __IPHONE_OS_VERSION_MIN_REQUIRED
2255 static ImageLoader* loadPhase5stat(const char* path, const LoadContext& context, struct stat* stat_buf,
2256 int* statErrNo, bool* imageFound, std::vector<const char*>* exceptions)
2257 {
2258 ImageLoader* image = NULL;
2259 *imageFound = false;
2260 if ( stat(path, stat_buf) == 0 ) {
2261 // in case image was renamed or found via symlinks, check for inode match
2262 image = findLoadedImage(*stat_buf);
2263 if ( image != NULL ) {
2264 *imageFound = true;
2265 return image;
2266 }
2267 // do nothing if not already loaded and if RTLD_NOLOAD
2268 if ( context.dontLoad ) {
2269 *imageFound = true;
2270 return NULL;
2271 }
2272 image = loadPhase5open(path, context, *stat_buf, exceptions);
2273 if ( image != NULL ) {
2274 *imageFound = true;
2275 return image;
2276 }
2277 }
2278 else {
2279 *statErrNo = errno;
2280 }
2281 return NULL;
2282 }
2283
2284 // try to open file
2285 static ImageLoader* loadPhase5load(const char* path, const char* orgPath, const LoadContext& context, std::vector<const char*>* exceptions)
2286 {
2287 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
2288 struct stat stat_buf;
2289 bool imageFound;
2290 int statErrNo;
2291 ImageLoader* image;
2292 #if DYLD_SHARED_CACHE_SUPPORT
2293 if ( sDylibsOverrideCache ) {
2294 // flag is set that allows installed framework roots to override dyld shared cache
2295 image = loadPhase5stat(path, context, &stat_buf, &statErrNo, &imageFound, exceptions);
2296 if ( imageFound )
2297 return image;
2298 }
2299 // see if this image is in shared cache
2300 const macho_header* mhInCache;
2301 const char* pathInCache;
2302 long slideInCache;
2303 if ( findInSharedCacheImage(path, NULL, &mhInCache, &pathInCache, &slideInCache) ) {
2304 // see if this image in the cache was already loaded via a different path
2305 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); ++it) {
2306 ImageLoader* anImage = *it;
2307 if ( anImage->machHeader() == mhInCache )
2308 return anImage;
2309 }
2310 // do nothing if not already loaded and if RTLD_NOLOAD
2311 if ( context.dontLoad )
2312 return NULL;
2313 // nope, so instantiate a new image from dyld shared cache
2314 // <rdar://problem/7014995> zero out stat buffer so mtime, etc are zero for items from the shared cache
2315 bzero(&stat_buf, sizeof(stat_buf));
2316 image = ImageLoaderMachO::instantiateFromCache(mhInCache, pathInCache, slideInCache, stat_buf, gLinkContext);
2317 return checkandAddImage(image, context);
2318 }
2319
2320 if ( !sDylibsOverrideCache ) {
2321 // flag is not set, and not in cache to try opening it
2322 image = loadPhase5stat(path, context, &stat_buf, &statErrNo, &imageFound, exceptions);
2323 if ( imageFound )
2324 return image;
2325 }
2326 #else
2327 image = loadPhase5stat(path, context, &stat_buf, &statErrNo, &imageFound, exceptions);
2328 if ( imageFound )
2329 return image;
2330 #endif
2331 // just return NULL if file not found, but record any other errors
2332 if ( statErrNo != ENOENT ) {
2333 exceptions->push_back(dyld::mkstringf("%s: stat() failed with errno=%d", path, statErrNo));
2334 }
2335 return NULL;
2336 }
2337 #endif // __IPHONE_OS_VERSION_MIN_REQUIRED
2338
2339
2340 // look for path match with existing loaded images
2341 static ImageLoader* loadPhase5check(const char* path, const char* orgPath, const LoadContext& context)
2342 {
2343 //dyld::log("%s(%s, %s)\n", __func__ , path, orgPath);
2344 // search path against load-path and install-path of all already loaded images
2345 uint32_t hash = ImageLoader::hash(path);
2346 //dyld::log("check() hash=%d, path=%s\n", hash, path);
2347 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
2348 ImageLoader* anImage = *it;
2349 // check hash first to cut down on strcmp calls
2350 //dyld::log(" check() hash=%d, path=%s\n", anImage->getPathHash(), anImage->getPath());
2351 if ( anImage->getPathHash() == hash ) {
2352 if ( strcmp(path, anImage->getPath()) == 0 ) {
2353 // if we are looking for a dylib don't return something else
2354 if ( !context.mustBeDylib || anImage->isDylib() )
2355 return anImage;
2356 }
2357 }
2358 if ( context.matchByInstallName || anImage->matchInstallPath() ) {
2359 const char* installPath = anImage->getInstallPath();
2360 if ( installPath != NULL) {
2361 if ( strcmp(path, installPath) == 0 ) {
2362 // if we are looking for a dylib don't return something else
2363 if ( !context.mustBeDylib || anImage->isDylib() )
2364 return anImage;
2365 }
2366 }
2367 }
2368 // an install name starting with @rpath should match by install name, not just real path
2369 if ( (orgPath[0] == '@') && (strncmp(orgPath, "@rpath/", 7) == 0) ) {
2370 const char* installPath = anImage->getInstallPath();
2371 if ( installPath != NULL) {
2372 if ( !context.mustBeDylib || anImage->isDylib() ) {
2373 if ( strcmp(orgPath, installPath) == 0 )
2374 return anImage;
2375 }
2376 }
2377 }
2378 }
2379
2380 //dyld::log("%s(%s) => NULL\n", __func__, path);
2381 return NULL;
2382 }
2383
2384
2385 // open or check existing
2386 static ImageLoader* loadPhase5(const char* path, const char* orgPath, const LoadContext& context, std::vector<const char*>* exceptions)
2387 {
2388 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
2389
2390 // check for specific dylib overrides
2391 for (std::vector<DylibOverride>::iterator it = sDylibOverrides.begin(); it != sDylibOverrides.end(); ++it) {
2392 if ( strcmp(it->installName, path) == 0 ) {
2393 path = it->override;
2394 break;
2395 }
2396 }
2397
2398 if ( exceptions != NULL )
2399 return loadPhase5load(path, orgPath, context, exceptions);
2400 else
2401 return loadPhase5check(path, orgPath, context);
2402 }
2403
2404 // try with and without image suffix
2405 static ImageLoader* loadPhase4(const char* path, const char* orgPath, const LoadContext& context, std::vector<const char*>* exceptions)
2406 {
2407 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
2408 ImageLoader* image = NULL;
2409 if ( gLinkContext.imageSuffix != NULL ) {
2410 char pathWithSuffix[strlen(path)+strlen( gLinkContext.imageSuffix)+2];
2411 ImageLoader::addSuffix(path, gLinkContext.imageSuffix, pathWithSuffix);
2412 image = loadPhase5(pathWithSuffix, orgPath, context, exceptions);
2413 }
2414 if ( image == NULL )
2415 image = loadPhase5(path, orgPath, context, exceptions);
2416 return image;
2417 }
2418
2419 static ImageLoader* loadPhase2(const char* path, const char* orgPath, const LoadContext& context,
2420 const char* const frameworkPaths[], const char* const libraryPaths[],
2421 std::vector<const char*>* exceptions); // forward reference
2422
2423
2424 // expand @ variables
2425 static ImageLoader* loadPhase3(const char* path, const char* orgPath, const LoadContext& context, std::vector<const char*>* exceptions)
2426 {
2427 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
2428 ImageLoader* image = NULL;
2429 if ( strncmp(path, "@executable_path/", 17) == 0 ) {
2430 // executable_path cannot be in used in any binary in a setuid process rdar://problem/4589305
2431 if ( sProcessIsRestricted )
2432 throwf("unsafe use of @executable_path in %s with restricted binary", context.origin);
2433 // handle @executable_path path prefix
2434 const char* executablePath = sExecPath;
2435 char newPath[strlen(executablePath) + strlen(path)];
2436 strcpy(newPath, executablePath);
2437 char* addPoint = strrchr(newPath,'/');
2438 if ( addPoint != NULL )
2439 strcpy(&addPoint[1], &path[17]);
2440 else
2441 strcpy(newPath, &path[17]);
2442 image = loadPhase4(newPath, orgPath, context, exceptions);
2443 if ( image != NULL )
2444 return image;
2445
2446 // perhaps main executable path is a sym link, find realpath and retry
2447 char resolvedPath[PATH_MAX];
2448 if ( realpath(sExecPath, resolvedPath) != NULL ) {
2449 char newRealPath[strlen(resolvedPath) + strlen(path)];
2450 strcpy(newRealPath, resolvedPath);
2451 char* addPoint = strrchr(newRealPath,'/');
2452 if ( addPoint != NULL )
2453 strcpy(&addPoint[1], &path[17]);
2454 else
2455 strcpy(newRealPath, &path[17]);
2456 image = loadPhase4(newRealPath, orgPath, context, exceptions);
2457 if ( image != NULL )
2458 return image;
2459 }
2460 }
2461 else if ( (strncmp(path, "@loader_path/", 13) == 0) && (context.origin != NULL) ) {
2462 // @loader_path cannot be used from the main executable of a setuid process rdar://problem/4589305
2463 if ( sProcessIsRestricted && (strcmp(context.origin, sExecPath) == 0) )
2464 throwf("unsafe use of @loader_path in %s with restricted binary", context.origin);
2465 // handle @loader_path path prefix
2466 char newPath[strlen(context.origin) + strlen(path)];
2467 strcpy(newPath, context.origin);
2468 char* addPoint = strrchr(newPath,'/');
2469 if ( addPoint != NULL )
2470 strcpy(&addPoint[1], &path[13]);
2471 else
2472 strcpy(newPath, &path[13]);
2473 image = loadPhase4(newPath, orgPath, context, exceptions);
2474 if ( image != NULL )
2475 return image;
2476
2477 // perhaps loader path is a sym link, find realpath and retry
2478 char resolvedPath[PATH_MAX];
2479 if ( realpath(context.origin, resolvedPath) != NULL ) {
2480 char newRealPath[strlen(resolvedPath) + strlen(path)];
2481 strcpy(newRealPath, resolvedPath);
2482 char* addPoint = strrchr(newRealPath,'/');
2483 if ( addPoint != NULL )
2484 strcpy(&addPoint[1], &path[13]);
2485 else
2486 strcpy(newRealPath, &path[13]);
2487 image = loadPhase4(newRealPath, orgPath, context, exceptions);
2488 if ( image != NULL )
2489 return image;
2490 }
2491 }
2492 else if ( context.implicitRPath || (strncmp(path, "@rpath/", 7) == 0) ) {
2493 const char* trailingPath = (strncmp(path, "@rpath/", 7) == 0) ? &path[7] : path;
2494 // substitute @rpath with all -rpath paths up the load chain
2495 for(const ImageLoader::RPathChain* rp=context.rpath; rp != NULL; rp=rp->next) {
2496 if (rp->paths != NULL ) {
2497 for(std::vector<const char*>::iterator it=rp->paths->begin(); it != rp->paths->end(); ++it) {
2498 const char* anRPath = *it;
2499 char newPath[strlen(anRPath) + strlen(trailingPath)+2];
2500 strcpy(newPath, anRPath);
2501 strcat(newPath, "/");
2502 strcat(newPath, trailingPath);
2503 image = loadPhase4(newPath, orgPath, context, exceptions);
2504 if ( gLinkContext.verboseRPaths && (exceptions != NULL) ) {
2505 if ( image != NULL )
2506 dyld::log("RPATH successful expansion of %s to: %s\n", orgPath, newPath);
2507 else
2508 dyld::log("RPATH failed to expanding %s to: %s\n", orgPath, newPath);
2509 }
2510 if ( image != NULL )
2511 return image;
2512 }
2513 }
2514 }
2515
2516 // substitute @rpath with LD_LIBRARY_PATH
2517 if ( sEnv.LD_LIBRARY_PATH != NULL ) {
2518 image = loadPhase2(trailingPath, orgPath, context, NULL, sEnv.LD_LIBRARY_PATH, exceptions);
2519 if ( image != NULL )
2520 return image;
2521 }
2522
2523 // if this is the "open" pass, don't try to open @rpath/... as a relative path
2524 if ( (exceptions != NULL) && (trailingPath != path) )
2525 return NULL;
2526 }
2527 else if (sProcessIsRestricted && (path[0] != '/' )) {
2528 throwf("unsafe use of relative rpath %s in %s with restricted binary", path, context.origin);
2529 }
2530
2531 return loadPhase4(path, orgPath, context, exceptions);
2532 }
2533
2534
2535 // try search paths
2536 static ImageLoader* loadPhase2(const char* path, const char* orgPath, const LoadContext& context,
2537 const char* const frameworkPaths[], const char* const libraryPaths[],
2538 std::vector<const char*>* exceptions)
2539 {
2540 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
2541 ImageLoader* image = NULL;
2542 const char* frameworkPartialPath = getFrameworkPartialPath(path);
2543 if ( frameworkPaths != NULL ) {
2544 if ( frameworkPartialPath != NULL ) {
2545 const int frameworkPartialPathLen = strlen(frameworkPartialPath);
2546 for(const char* const* fp = frameworkPaths; *fp != NULL; ++fp) {
2547 char npath[strlen(*fp)+frameworkPartialPathLen+8];
2548 strcpy(npath, *fp);
2549 strcat(npath, "/");
2550 strcat(npath, frameworkPartialPath);
2551 //dyld::log("dyld: fallback framework path used: %s() -> loadPhase4(\"%s\", ...)\n", __func__, npath);
2552 image = loadPhase4(npath, orgPath, context, exceptions);
2553 if ( image != NULL )
2554 return image;
2555 }
2556 }
2557 }
2558 if ( libraryPaths != NULL ) {
2559 const char* libraryLeafName = getLibraryLeafName(path);
2560 const int libraryLeafNameLen = strlen(libraryLeafName);
2561 for(const char* const* lp = libraryPaths; *lp != NULL; ++lp) {
2562 char libpath[strlen(*lp)+libraryLeafNameLen+8];
2563 strcpy(libpath, *lp);
2564 strcat(libpath, "/");
2565 strcat(libpath, libraryLeafName);
2566 //dyld::log("dyld: fallback library path used: %s() -> loadPhase4(\"%s\", ...)\n", __func__, libpath);
2567 image = loadPhase4(libpath, orgPath, context, exceptions);
2568 if ( image != NULL )
2569 return image;
2570 }
2571 }
2572 return NULL;
2573 }
2574
2575 // try search overrides and fallbacks
2576 static ImageLoader* loadPhase1(const char* path, const char* orgPath, const LoadContext& context, std::vector<const char*>* exceptions)
2577 {
2578 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
2579 ImageLoader* image = NULL;
2580
2581 // handle LD_LIBRARY_PATH environment variables that force searching
2582 if ( context.useLdLibraryPath && (sEnv.LD_LIBRARY_PATH != NULL) ) {
2583 image = loadPhase2(path, orgPath, context, NULL, sEnv.LD_LIBRARY_PATH, exceptions);
2584 if ( image != NULL )
2585 return image;
2586 }
2587
2588 // handle DYLD_ environment variables that force searching
2589 if ( context.useSearchPaths && ((sEnv.DYLD_FRAMEWORK_PATH != NULL) || (sEnv.DYLD_LIBRARY_PATH != NULL)) ) {
2590 image = loadPhase2(path, orgPath, context, sEnv.DYLD_FRAMEWORK_PATH, sEnv.DYLD_LIBRARY_PATH, exceptions);
2591 if ( image != NULL )
2592 return image;
2593 }
2594
2595 // try raw path
2596 image = loadPhase3(path, orgPath, context, exceptions);
2597 if ( image != NULL )
2598 return image;
2599
2600 // try fallback paths during second time (will open file)
2601 const char* const* fallbackLibraryPaths = sEnv.DYLD_FALLBACK_LIBRARY_PATH;
2602 if ( (fallbackLibraryPaths != NULL) && !context.useFallbackPaths )
2603 fallbackLibraryPaths = NULL;
2604 if ( !context.dontLoad && (exceptions != NULL) && ((sEnv.DYLD_FALLBACK_FRAMEWORK_PATH != NULL) || (fallbackLibraryPaths != NULL)) ) {
2605 image = loadPhase2(path, orgPath, context, sEnv.DYLD_FALLBACK_FRAMEWORK_PATH, fallbackLibraryPaths, exceptions);
2606 if ( image != NULL )
2607 return image;
2608 }
2609
2610 return NULL;
2611 }
2612
2613 // try root substitutions
2614 static ImageLoader* loadPhase0(const char* path, const char* orgPath, const LoadContext& context, std::vector<const char*>* exceptions)
2615 {
2616 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
2617
2618 // handle DYLD_ROOT_PATH which forces absolute paths to use a new root
2619 if ( (gLinkContext.rootPaths != NULL) && (path[0] == '/') ) {
2620 for(const char* const* rootPath = gLinkContext.rootPaths ; *rootPath != NULL; ++rootPath) {
2621 char newPath[strlen(*rootPath) + strlen(path)+2];
2622 strcpy(newPath, *rootPath);
2623 strcat(newPath, path);
2624 ImageLoader* image = loadPhase1(newPath, orgPath, context, exceptions);
2625 if ( image != NULL )
2626 return image;
2627 }
2628 }
2629
2630 // try raw path
2631 return loadPhase1(path, orgPath, context, exceptions);
2632 }
2633
2634 //
2635 // Given all the DYLD_ environment variables, the general case for loading libraries
2636 // is that any given path expands into a list of possible locations to load. We
2637 // also must take care to ensure two copies of the "same" library are never loaded.
2638 //
2639 // The algorithm used here is that there is a separate function for each "phase" of the
2640 // path expansion. Each phase function calls the next phase with each possible expansion
2641 // of that phase. The result is the last phase is called with all possible paths.
2642 //
2643 // To catch duplicates the algorithm is run twice. The first time, the last phase checks
2644 // the path against all loaded images. The second time, the last phase calls open() on
2645 // the path. Either time, if an image is found, the phases all unwind without checking
2646 // for other paths.
2647 //
2648 ImageLoader* load(const char* path, const LoadContext& context)
2649 {
2650 CRSetCrashLogMessage2(path);
2651 const char* orgPath = path;
2652
2653 //dyld::log("%s(%s)\n", __func__ , path);
2654 char realPath[PATH_MAX];
2655 // when DYLD_IMAGE_SUFFIX is in used, do a realpath(), otherwise a load of "Foo.framework/Foo" will not match
2656 if ( context.useSearchPaths && ( gLinkContext.imageSuffix != NULL) ) {
2657 if ( realpath(path, realPath) != NULL )
2658 path = realPath;
2659 }
2660
2661 // try all path permutations and check against existing loaded images
2662 ImageLoader* image = loadPhase0(path, orgPath, context, NULL);
2663 if ( image != NULL ) {
2664 CRSetCrashLogMessage2(NULL);
2665 return image;
2666 }
2667
2668 // try all path permutations and try open() until first success
2669 std::vector<const char*> exceptions;
2670 image = loadPhase0(path, orgPath, context, &exceptions);
2671 CRSetCrashLogMessage2(NULL);
2672 if ( image != NULL ) {
2673 // <rdar://problem/6916014> leak in dyld during dlopen when using DYLD_ variables
2674 for (std::vector<const char*>::iterator it = exceptions.begin(); it != exceptions.end(); ++it) {
2675 free((void*)(*it));
2676 }
2677 #if __IPHONE_OS_VERSION_MIN_REQUIRED
2678 // if loaded image is not from cache, but original path is in cache
2679 // set gSharedCacheOverridden flag to disable some ObjC optimizations
2680 if ( !gSharedCacheOverridden ) {
2681 if ( !image->inSharedCache() && inSharedCache(path) ) {
2682 gSharedCacheOverridden = true;
2683 }
2684 }
2685 #endif
2686 return image;
2687 }
2688 else if ( exceptions.size() == 0 ) {
2689 if ( context.dontLoad ) {
2690 return NULL;
2691 }
2692 else
2693 throw "image not found";
2694 }
2695 else {
2696 const char* msgStart = "no suitable image found. Did find:";
2697 const char* delim = "\n\t";
2698 size_t allsizes = strlen(msgStart)+8;
2699 for (unsigned int i=0; i < exceptions.size(); ++i)
2700 allsizes += (strlen(exceptions[i]) + strlen(delim));
2701 char* fullMsg = new char[allsizes];
2702 strcpy(fullMsg, msgStart);
2703 for (unsigned int i=0; i < exceptions.size(); ++i) {
2704 strcat(fullMsg, delim);
2705 strcat(fullMsg, exceptions[i]);
2706 free((void*)exceptions[i]);
2707 }
2708 throw (const char*)fullMsg;
2709 }
2710 }
2711
2712
2713
2714
2715 #if DYLD_SHARED_CACHE_SUPPORT
2716
2717
2718
2719
2720 #if __ppc__
2721 #define ARCH_NAME "ppc"
2722 #define ARCH_NAME_ROSETTA "rosetta"
2723 #define ARCH_CACHE_MAGIC "dyld_v1 ppc"
2724 #elif __ppc64__
2725 #define ARCH_NAME "ppc64"
2726 #define ARCH_CACHE_MAGIC "dyld_v1 ppc64"
2727 #elif __i386__
2728 #define ARCH_NAME "i386"
2729 #define ARCH_CACHE_MAGIC "dyld_v1 i386"
2730 #elif __x86_64__
2731 #define ARCH_NAME "x86_64"
2732 #define ARCH_CACHE_MAGIC "dyld_v1 x86_64"
2733 #define SHARED_REGION_READ_ONLY_START 0x7FFF80000000LL
2734 #define SHARED_REGION_READ_ONLY_END 0x7FFFC0000000LL
2735 #define SHARED_REGION_WRITABLE_START 0x7FFF70000000LL
2736 #define SHARED_REGION_WRITABLE_END 0x7FFF80000000LL
2737 #define SLIDEABLE_CACHE_SUPPORT 1
2738 #elif __ARM_ARCH_5TEJ__
2739 #define ARCH_NAME "armv5"
2740 #define ARCH_CACHE_MAGIC "dyld_v1 armv5"
2741 #elif __ARM_ARCH_6K__
2742 #define ARCH_NAME "armv6"
2743 #define ARCH_CACHE_MAGIC "dyld_v1 armv6"
2744 #elif __ARM_ARCH_7A__
2745 #define ARCH_NAME "armv7"
2746 #define ARCH_CACHE_MAGIC "dyld_v1 armv7"
2747 #define SHARED_REGION_READ_ONLY_START 0x30000000
2748 #define SHARED_REGION_READ_ONLY_END 0x3E000000
2749 #define SHARED_REGION_WRITABLE_START 0x3E000000
2750 #define SHARED_REGION_WRITABLE_END 0x40000000
2751 #define SLIDEABLE_CACHE_SUPPORT 1
2752 #endif
2753
2754
2755 static int __attribute__((noinline)) _shared_region_check_np(uint64_t* start_address)
2756 {
2757 if ( (gLinkContext.sharedRegionMode == ImageLoader::kUseSharedRegion) )
2758 return syscall(294, start_address);
2759 return -1;
2760 }
2761
2762
2763 static int __attribute__((noinline)) _shared_region_map_and_slide_np(int fd, uint32_t count, const shared_file_mapping_np mappings[],
2764 int codeSignatureMappingIndex, int slide, void* slideInfo, uint32_t slideInfoSize)
2765 {
2766 #if __IPHONE_OS_VERSION_MIN_REQUIRED
2767 // register code signature blob for whole dyld cache
2768 if ( codeSignatureMappingIndex != -1 ) {
2769 fsignatures_t siginfo;
2770 siginfo.fs_file_start = 0; // cache always starts at beginning of file
2771 siginfo.fs_blob_start = (void*)mappings[codeSignatureMappingIndex].sfm_file_offset;
2772 siginfo.fs_blob_size = mappings[codeSignatureMappingIndex].sfm_size;
2773 int result = fcntl(fd, F_ADDFILESIGS, &siginfo);
2774 if ( result == -1 )
2775 dyld::log("dyld: code signature for shared cache failed with errno=%d\n", errno);
2776 }
2777 #endif
2778 if ( (gLinkContext.sharedRegionMode == ImageLoader::kUseSharedRegion) ) {
2779 return syscall(438, fd, count, mappings, slide, slideInfo, slideInfoSize);
2780 }
2781
2782 // remove the shared region sub-map
2783 vm_deallocate(mach_task_self(), (vm_address_t)SHARED_REGION_BASE, SHARED_REGION_SIZE);
2784
2785 // notify gdb or other lurkers that this process is no longer using the shared region
2786 dyld_all_image_infos.processDetachedFromSharedRegion = true;
2787
2788 // map cache just for this process with mmap()
2789 const shared_file_mapping_np* const start = mappings;
2790 const shared_file_mapping_np* const end = &mappings[count];
2791 for (const shared_file_mapping_np* p = start; p < end; ++p ) {
2792 void* mmapAddress = (void*)(uintptr_t)(p->sfm_address);
2793 size_t size = p->sfm_size;
2794 //dyld::log("dyld: mapping address %p with size 0x%08lX\n", mmapAddress, size);
2795 int protection = 0;
2796 if ( p->sfm_init_prot & VM_PROT_EXECUTE )
2797 protection |= PROT_EXEC;
2798 if ( p->sfm_init_prot & VM_PROT_READ )
2799 protection |= PROT_READ;
2800 if ( p->sfm_init_prot & VM_PROT_WRITE )
2801 protection |= PROT_WRITE;
2802 off_t offset = p->sfm_file_offset;
2803 if ( mmap(mmapAddress, size, protection, MAP_FIXED | MAP_PRIVATE, fd, offset) != mmapAddress ) {
2804 // failed to map some chunk of this shared cache file
2805 // clear shared region
2806 vm_deallocate(mach_task_self(), (vm_address_t)SHARED_REGION_BASE, SHARED_REGION_SIZE);
2807 // go back to not using shared region at all
2808 gLinkContext.sharedRegionMode = ImageLoader::kDontUseSharedRegion;
2809 if ( gLinkContext.verboseMapping ) {
2810 dyld::log("dyld: shared cached region cannot be mapped at address %p with size 0x%08lX\n",
2811 mmapAddress, size);
2812 }
2813 // return failure
2814 return -1;
2815 }
2816 }
2817
2818 #if SLIDEABLE_CACHE_SUPPORT
2819 // update all __DATA pages with slide info
2820 if ( slide != 0 ) {
2821 const uintptr_t dataPagesStart = mappings[1].sfm_address;
2822 const dyld_cache_slide_info* slideInfoHeader = (dyld_cache_slide_info*)slideInfo;
2823 const uint16_t* toc = (uint16_t*)((long)(slideInfoHeader) + slideInfoHeader->toc_offset);
2824 const uint8_t* entries = (uint8_t*)((long)(slideInfoHeader) + slideInfoHeader->entries_offset);
2825 for(uint32_t i=0; i < slideInfoHeader->toc_count; ++i) {
2826 const uint8_t* entry = &entries[toc[i]*slideInfoHeader->entries_size];
2827 const uint8_t* page = (uint8_t*)(long)(dataPagesStart + (4096*i));
2828 //dyld::log("page=%p toc[%d]=%d entries=%p\n", page, i, toc[i], entry);
2829 for(int j=0; j < 128; ++j) {
2830 uint8_t b = entry[j];
2831 //dyld::log(" entry[%d] = 0x%02X\n", j, b);
2832 if ( b != 0 ) {
2833 for(int k=0; k < 8; ++k) {
2834 if ( b & (1<<k) ) {
2835 uintptr_t* p = (uintptr_t*)(page + j*8*4 + k*4);
2836 uintptr_t value = *p;
2837 //dyld::log(" *%p was 0x%lX will be 0x%lX\n", p, value, value+sSharedCacheSlide);
2838 *p = value + slide;
2839 }
2840 }
2841 }
2842 }
2843 }
2844 }
2845 #endif // SLIDEABLE_CACHE_SUPPORT
2846
2847 // succesfully mapped shared cache for just this process
2848 gLinkContext.sharedRegionMode = ImageLoader::kUsePrivateSharedRegion;
2849
2850 return 0;
2851 }
2852
2853
2854 const void* imMemorySharedCacheHeader()
2855 {
2856 return sSharedCache;
2857 }
2858
2859 int openSharedCacheFile()
2860 {
2861 char path[1024];
2862 strcpy(path, sSharedCacheDir);
2863 strcat(path, "/");
2864 #if __ppc__
2865 // rosetta cannot handle optimized _ppc cache, so it use _rosetta cache instead, rdar://problem/5495438
2866 if ( isRosetta() )
2867 strcat(path, DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME_ROSETTA);
2868 else
2869 #endif
2870 strcat(path, DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME);
2871 return ::open(path, O_RDONLY);
2872 }
2873
2874 #if SLIDEABLE_CACHE_SUPPORT
2875 static long pickCacheSlide(uint32_t mappingsCount, shared_file_mapping_np mappings[])
2876 {
2877 // get bounds of cache
2878 uint64_t readOnlyLowAddress = 0;
2879 uint64_t readOnlyHighAddress = 0;
2880 uint64_t writableLowAddress = 0;
2881 uint64_t writableHighAddress = 0;
2882 for(uint32_t i=0; i < mappingsCount; ++i) {
2883 if ( mappings[i].sfm_init_prot & VM_PROT_WRITE ) {
2884 writableLowAddress = mappings[i].sfm_address;
2885 writableHighAddress = mappings[i].sfm_address + mappings[i].sfm_size;
2886 }
2887 else {
2888 if ( readOnlyLowAddress == 0 ) {
2889 readOnlyLowAddress = mappings[i].sfm_address;
2890 readOnlyHighAddress = mappings[i].sfm_address + mappings[i].sfm_size;
2891 }
2892 else {
2893 if ( readOnlyLowAddress < mappings[i].sfm_address ) {
2894 readOnlyHighAddress = mappings[i].sfm_address + mappings[i].sfm_size;
2895 }
2896 else {
2897 readOnlyLowAddress = mappings[i].sfm_address;
2898 }
2899 }
2900 }
2901 }
2902
2903 // find read-only slop space
2904 uint64_t roSpace = SHARED_REGION_READ_ONLY_END - readOnlyHighAddress;
2905
2906 // find writable slop space
2907 uint64_t rwSpace = SHARED_REGION_WRITABLE_END - writableHighAddress;
2908
2909 // choose new random slide
2910 long slideSpace = (roSpace > rwSpace) ? rwSpace : roSpace;
2911 long slide = (arc4random() % slideSpace) & (-4096);
2912 //dyld::log("roSpace=0x%0llX\n", roSpace);
2913 //dyld::log("rwSpace=0x%0llX\n", rwSpace);
2914 //dyld::log("slideSpace=0x%0lX\n", slideSpace);
2915 //dyld::log("slide=0x%0lX\n", slide);
2916
2917 // update mappings
2918 for(uint32_t i=0; i < mappingsCount; ++i) {
2919 mappings[i].sfm_address += slide;
2920 }
2921
2922 return slide;
2923 }
2924 #endif // SLIDEABLE_CACHE_SUPPORT
2925
2926 static void mapSharedCache()
2927 {
2928 uint64_t cacheBaseAddress;
2929 // quick check if a cache is alreay mapped into shared region
2930 if ( _shared_region_check_np(&cacheBaseAddress) == 0 ) {
2931 sSharedCache = (dyld_cache_header*)cacheBaseAddress;
2932 // if we don't understand the currently mapped shared cache, then ignore
2933 if ( strcmp(sSharedCache->magic, ARCH_CACHE_MAGIC) != 0 ) {
2934 sSharedCache = NULL;
2935 if ( gLinkContext.verboseMapping )
2936 dyld::log("dyld: existing shared cached in memory is not compatible\n");
2937 }
2938 // check if cache file is slidable
2939 dyld_cache_header* header = (dyld_cache_header*)sSharedCache;
2940 if ( (header->mappingOffset >= 0x48) && (header->slideInfoSize != 0) ) {
2941 // solve for slide by comparing loaded address to address of first region
2942 const uint8_t* loadedAddress = (uint8_t*)sSharedCache;
2943 const dyld_cache_mapping_info* const mappings = (dyld_cache_mapping_info*)(loadedAddress+header->mappingOffset);
2944 const uint8_t* preferedLoadAddress = (uint8_t*)(long)(mappings[0].address);
2945 sSharedCacheSlide = loadedAddress - preferedLoadAddress;
2946 dyld_all_image_infos.sharedCacheSlide = sSharedCacheSlide;
2947 //dyld::log("sSharedCacheSlide=0x%08lX, loadedAddress=%p, preferedLoadAddress=%p\n", sSharedCacheSlide, loadedAddress, preferedLoadAddress);
2948 }
2949 }
2950 else {
2951 #if __i386__ || __x86_64__
2952 // <rdar://problem/5925940> Safe Boot should disable dyld shared cache
2953 // if we are in safe-boot mode and the cache was not made during this boot cycle,
2954 // delete the cache file
2955 uint32_t safeBootValue = 0;
2956 size_t safeBootValueSize = sizeof(safeBootValue);
2957 if ( (sysctlbyname("kern.safeboot", &safeBootValue, &safeBootValueSize, NULL, 0) == 0) && (safeBootValue != 0) ) {
2958 // user booted machine in safe-boot mode
2959 struct stat dyldCacheStatInfo;
2960 // Don't use custom DYLD_SHARED_CACHE_DIR if provided, use standard path
2961 if ( ::stat(MACOSX_DYLD_SHARED_CACHE_DIR DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME, &dyldCacheStatInfo) == 0 ) {
2962 struct timeval bootTimeValue;
2963 size_t bootTimeValueSize = sizeof(bootTimeValue);
2964 if ( (sysctlbyname("kern.boottime", &bootTimeValue, &bootTimeValueSize, NULL, 0) == 0) && (bootTimeValue.tv_sec != 0) ) {
2965 // if the cache file was created before this boot, then throw it away and let it rebuild itself
2966 if ( dyldCacheStatInfo.st_mtime < bootTimeValue.tv_sec ) {
2967 ::unlink(MACOSX_DYLD_SHARED_CACHE_DIR DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME);
2968 gLinkContext.sharedRegionMode = ImageLoader::kDontUseSharedRegion;
2969 return;
2970 }
2971 }
2972 }
2973 }
2974 #endif
2975 // map in shared cache to shared region
2976 int fd = openSharedCacheFile();
2977 if ( fd != -1 ) {
2978 uint8_t firstPages[8192];
2979 if ( ::read(fd, firstPages, 8192) == 8192 ) {
2980 dyld_cache_header* header = (dyld_cache_header*)firstPages;
2981 if ( strcmp(header->magic, ARCH_CACHE_MAGIC) == 0 ) {
2982 const dyld_cache_mapping_info* const fileMappingsStart = (dyld_cache_mapping_info*)&firstPages[header->mappingOffset];
2983 const dyld_cache_mapping_info* const fileMappingsEnd = &fileMappingsStart[header->mappingCount];
2984 shared_file_mapping_np mappings[header->mappingCount+1]; // add room for code-sig
2985 unsigned int mappingCount = header->mappingCount;
2986 int codeSignatureMappingIndex = -1;
2987 // validate that the cache file has not been truncated
2988 bool goodCache = false;
2989 struct stat stat_buf;
2990 if ( fstat(fd, &stat_buf) == 0 ) {
2991 goodCache = true;
2992 int i=0;
2993 for (const dyld_cache_mapping_info* p = fileMappingsStart; p < fileMappingsEnd; ++p, ++i) {
2994 mappings[i].sfm_address = p->address;
2995 mappings[i].sfm_size = p->size;
2996 mappings[i].sfm_file_offset = p->fileOffset;
2997 mappings[i].sfm_max_prot = p->maxProt;
2998 mappings[i].sfm_init_prot = p->initProt;
2999 // rdar://problem/5694507 old update_dyld_shared_cache tool could make a cache file
3000 // that is not page aligned, but otherwise ok.
3001 if ( p->fileOffset+p->size > (uint64_t)(stat_buf.st_size+4095 & (-4096)) ) {
3002 dyld::log("dyld: shared cached file is corrupt: %s" DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME "\n", sSharedCacheDir);
3003 goodCache = false;
3004 }
3005 }
3006 #if __IPHONE_OS_VERSION_MIN_REQUIRED
3007 // if shared cache is code signed, add a mapping for the code signature
3008 uint32_t signatureSize = header->codeSignatureSize;
3009 // zero size in header means signature runs to end-of-file
3010 if ( signatureSize == 0 )
3011 signatureSize = stat_buf.st_size - header->codeSignatureOffset;
3012 if ( signatureSize != 0 ) {
3013 int linkeditMapping = mappingCount-1;
3014 codeSignatureMappingIndex = mappingCount++;
3015 mappings[codeSignatureMappingIndex].sfm_address = mappings[linkeditMapping].sfm_address + mappings[linkeditMapping].sfm_size;
3016 mappings[codeSignatureMappingIndex].sfm_size = (signatureSize+4095) & (-4096);
3017 mappings[codeSignatureMappingIndex].sfm_file_offset = header->codeSignatureOffset;
3018 mappings[codeSignatureMappingIndex].sfm_max_prot = VM_PROT_READ;
3019 mappings[codeSignatureMappingIndex].sfm_init_prot = VM_PROT_READ;
3020 }
3021 #endif
3022 }
3023 #if __MAC_OS_X_VERSION_MIN_REQUIRED
3024 // sanity check that /usr/lib/libSystem.B.dylib stat() info matches cache
3025 if ( header->imagesCount * sizeof(dyld_cache_image_info) + header->imagesOffset < 8192 ) {
3026 bool foundLibSystem = false;
3027 if ( stat("/usr/lib/libSystem.B.dylib", &stat_buf) == 0 ) {
3028 const dyld_cache_image_info* images = (dyld_cache_image_info*)&firstPages[header->imagesOffset];
3029 const dyld_cache_image_info* const imagesEnd = &images[header->imagesCount];
3030 for (const dyld_cache_image_info* p = images; p < imagesEnd; ++p) {
3031 if ( ((time_t)p->modTime == stat_buf.st_mtime) && ((ino_t)p->inode == stat_buf.st_ino) ) {
3032 foundLibSystem = true;
3033 break;
3034 }
3035 }
3036 }
3037 if ( !sSharedCacheIgnoreInodeAndTimeStamp && !foundLibSystem ) {
3038 dyld::log("dyld: shared cached file was built against a different libSystem.dylib, ignoring cache.\n"
3039 "to update dyld shared cache run: 'sudo update_dyld_shared_cache' then reboot.\n");
3040 goodCache = false;
3041 }
3042 }
3043 #endif
3044 if ( goodCache ) {
3045 long cacheSlide = 0;
3046 void* slideInfo = NULL;
3047 uint32_t slideInfoSize = 0;
3048 #if SLIDEABLE_CACHE_SUPPORT
3049 // check if shared cache contains slid info
3050 if ( header->slideInfoSize != 0 ) {
3051 // <rdar://problem/8611968> don't slide shared cache if ASLR disabled (main executable didn't slide)
3052 if ( sMainExecutable->isPositionIndependentExecutable() && (sMainExecutable->getSlide() == 0) )
3053 cacheSlide = 0;
3054 else {
3055 // generate random slide amount
3056 cacheSlide = pickCacheSlide(mappingCount, mappings);
3057 slideInfo = (void*)(long)(mappings[2].sfm_address + (header->slideInfoOffset - mappings[2].sfm_file_offset));
3058 slideInfoSize = header->slideInfoSize;
3059 // add VM_PROT_SLIDE bit to __DATA area of cache
3060 mappings[1].sfm_max_prot |= VM_PROT_SLIDE;
3061 mappings[1].sfm_init_prot |= VM_PROT_SLIDE;
3062 }
3063 }
3064 #endif
3065 if (_shared_region_map_and_slide_np(fd, mappingCount, mappings, codeSignatureMappingIndex, cacheSlide, slideInfo, slideInfoSize) == 0) {
3066 // successfully mapped cache into shared region
3067 sSharedCache = (dyld_cache_header*)mappings[0].sfm_address;
3068 sSharedCacheSlide = cacheSlide;
3069 dyld_all_image_infos.sharedCacheSlide = cacheSlide;
3070 //dyld::log("sSharedCache=%p sSharedCacheSlide=0x%08lX\n", sSharedCache, sSharedCacheSlide);
3071 }
3072 else {
3073 if ( gLinkContext.verboseMapping )
3074 dyld::log("dyld: shared cached file could not be mapped\n");
3075 }
3076 }
3077 }
3078 else {
3079 if ( gLinkContext.verboseMapping )
3080 dyld::log("dyld: shared cached file is invalid\n");
3081 }
3082 }
3083 else {
3084 if ( gLinkContext.verboseMapping )
3085 dyld::log("dyld: shared cached file cannot be read\n");
3086 }
3087 close(fd);
3088 }
3089 else {
3090 if ( gLinkContext.verboseMapping )
3091 dyld::log("dyld: shared cached file cannot be opened\n");
3092 }
3093 }
3094
3095 // remember if dyld loaded at same address as when cache built
3096 if ( sSharedCache != NULL ) {
3097 gLinkContext.dyldLoadedAtSameAddressNeededBySharedCache = ((uintptr_t)(sSharedCache->dyldBaseAddress) == (uintptr_t)&_mh_dylinker_header);
3098 }
3099
3100 // tell gdb where the shared cache is
3101 if ( sSharedCache != NULL ) {
3102 const dyld_cache_mapping_info* const start = (dyld_cache_mapping_info*)((uint8_t*)sSharedCache + sSharedCache->mappingOffset);
3103 dyld_shared_cache_ranges.sharedRegionsCount = sSharedCache->mappingCount;
3104 // only room to tell gdb about first four regions
3105 if ( dyld_shared_cache_ranges.sharedRegionsCount > 4 )
3106 dyld_shared_cache_ranges.sharedRegionsCount = 4;
3107 if ( gLinkContext.verboseMapping ) {
3108 if ( gLinkContext.sharedRegionMode == ImageLoader::kUseSharedRegion )
3109 dyld::log("dyld: Mapping shared cache from %s/" DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME "\n", sSharedCacheDir);
3110 else if ( gLinkContext.sharedRegionMode == ImageLoader::kUsePrivateSharedRegion )
3111 dyld::log("dyld: Mapping private shared cache from %s/" DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME "\n", sSharedCacheDir);
3112 }
3113 const dyld_cache_mapping_info* const end = &start[dyld_shared_cache_ranges.sharedRegionsCount];
3114 int index = 0;
3115 for (const dyld_cache_mapping_info* p = start; p < end; ++p, ++index ) {
3116 dyld_shared_cache_ranges.ranges[index].start = p->address+sSharedCacheSlide;
3117 dyld_shared_cache_ranges.ranges[index].length = p->size;
3118 if ( gLinkContext.verboseMapping ) {
3119 dyld::log(" 0x%08llX->0x%08llX %s%s%s init=%x, max=%x\n",
3120 p->address+sSharedCacheSlide, p->address+sSharedCacheSlide+p->size-1,
3121 ((p->initProt & VM_PROT_READ) ? "read " : ""),
3122 ((p->initProt & VM_PROT_WRITE) ? "write " : ""),
3123 ((p->initProt & VM_PROT_EXECUTE) ? "execute " : ""), p->initProt, p->maxProt);
3124 }
3125 #if __i386__
3126 // If a non-writable and executable region is found in the R/W shared region, then this is __IMPORT segments
3127 // This is an old cache. Make writable. dyld no longer supports turn W on and off as it binds
3128 if ( (p->initProt == (VM_PROT_READ|VM_PROT_EXECUTE)) && ((p->address & 0xF0000000) == 0xA0000000) ) {
3129 if ( p->size != 0 ) {
3130 vm_prot_t prot = VM_PROT_EXECUTE | PROT_READ | VM_PROT_WRITE;
3131 vm_protect(mach_task_self(), p->address, p->size, false, prot);
3132 if ( gLinkContext.verboseMapping ) {
3133 dyld::log("%18s at 0x%08llX->0x%08llX altered permissions to %c%c%c\n", "", p->address,
3134 p->address+p->size-1,
3135 (prot & PROT_READ) ? 'r' : '.', (prot & PROT_WRITE) ? 'w' : '.', (prot & PROT_EXEC) ? 'x' : '.' );
3136 }
3137 }
3138 }
3139 #endif
3140 }
3141 #if __IPHONE_OS_VERSION_MIN_REQUIRED
3142 if ( gLinkContext.verboseMapping ) {
3143 // list the code blob
3144 dyld_cache_header* header = (dyld_cache_header*)sSharedCache;
3145 uint32_t signatureSize = header->codeSignatureSize;
3146 // zero size in header means signature runs to end-of-file
3147 if ( signatureSize == 0 ) {
3148 struct stat stat_buf;
3149 if ( ::stat(IPHONE_DYLD_SHARED_CACHE_DIR DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME, &stat_buf) == 0 )
3150 signatureSize = stat_buf.st_size - header->codeSignatureOffset;
3151 }
3152 if ( signatureSize != 0 ) {
3153 const dyld_cache_mapping_info* const last = &start[dyld_shared_cache_ranges.sharedRegionsCount-1];
3154 uint64_t codeBlobStart = last->address + last->size;
3155 dyld::log(" 0x%08llX->0x%08llX (code signature)\n", codeBlobStart, codeBlobStart+signatureSize);
3156 }
3157 }
3158 // check for file that enables dyld shared cache dylibs to be overridden
3159 struct stat enableStatBuf;
3160 sDylibsOverrideCache = ( ::stat(IPHONE_DYLD_SHARED_CACHE_DIR "enable-dylibs-to-override-cache", &enableStatBuf) == 0 );
3161 #endif
3162
3163 }
3164 }
3165 #endif // #if DYLD_SHARED_CACHE_SUPPORT
3166
3167
3168
3169 // create when NSLinkModule is called for a second time on a bundle
3170 ImageLoader* cloneImage(ImageLoader* image)
3171 {
3172 // open file (automagically closed when this function exits)
3173 FileOpener file(image->getPath());
3174
3175 struct stat stat_buf;
3176 if ( fstat(file.getFileDescriptor(), &stat_buf) == -1)
3177 throw "stat error";
3178
3179 dyld::LoadContext context;
3180 context.useSearchPaths = false;
3181 context.useFallbackPaths = false;
3182 context.useLdLibraryPath = false;
3183 context.implicitRPath = false;
3184 context.matchByInstallName = false;
3185 context.dontLoad = false;
3186 context.mustBeBundle = true;
3187 context.mustBeDylib = false;
3188 context.canBePIE = false;
3189 context.origin = NULL;
3190 context.rpath = NULL;
3191 return loadPhase6(file.getFileDescriptor(), stat_buf, image->getPath(), context);
3192 }
3193
3194
3195 ImageLoader* loadFromMemory(const uint8_t* mem, uint64_t len, const char* moduleName)
3196 {
3197 // if fat wrapper, find usable sub-file
3198 const fat_header* memStartAsFat = (fat_header*)mem;
3199 uint64_t fileOffset = 0;
3200 uint64_t fileLength = len;
3201 if ( memStartAsFat->magic == OSSwapBigToHostInt32(FAT_MAGIC) ) {
3202 if ( fatFindBest(memStartAsFat, &fileOffset, &fileLength) ) {
3203 mem = &mem[fileOffset];
3204 len = fileLength;
3205 }
3206 else {
3207 throw "no matching architecture in universal wrapper";
3208 }
3209 }
3210
3211 // try each loader
3212 if ( isCompatibleMachO(mem, moduleName) ) {
3213 ImageLoader* image = ImageLoaderMachO::instantiateFromMemory(moduleName, (macho_header*)mem, len, gLinkContext);
3214 // don't add bundles to global list, they can be loaded but not linked. When linked it will be added to list
3215 if ( ! image->isBundle() )
3216 addImage(image);
3217 return image;
3218 }
3219
3220 // try other file formats here...
3221
3222 // throw error about what was found
3223 switch (*(uint32_t*)mem) {
3224 case MH_MAGIC:
3225 case MH_CIGAM:
3226 case MH_MAGIC_64:
3227 case MH_CIGAM_64:
3228 throw "mach-o, but wrong architecture";
3229 default:
3230 throwf("unknown file type, first eight bytes: 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X",
3231 mem[0], mem[1], mem[2], mem[3], mem[4], mem[5], mem[6],mem[7]);
3232 }
3233 }
3234
3235
3236 void registerAddCallback(ImageCallback func)
3237 {
3238 // now add to list to get notified when any more images are added
3239 sAddImageCallbacks.push_back(func);
3240
3241 // call callback with all existing images
3242 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
3243 ImageLoader* image = *it;
3244 if ( image->getState() >= dyld_image_state_bound && image->getState() < dyld_image_state_terminated )
3245 (*func)(image->machHeader(), image->getSlide());
3246 }
3247 }
3248
3249 void registerRemoveCallback(ImageCallback func)
3250 {
3251 sRemoveImageCallbacks.push_back(func);
3252 }
3253
3254 void clearErrorMessage()
3255 {
3256 error_string[0] = '\0';
3257 }
3258
3259 void setErrorMessage(const char* message)
3260 {
3261 // save off error message in global buffer for CrashReporter to find
3262 strlcpy(error_string, message, sizeof(error_string));
3263 }
3264
3265 const char* getErrorMessage()
3266 {
3267 return error_string;
3268 }
3269
3270
3271 void halt(const char* message)
3272 {
3273 dyld::log("dyld: %s\n", message);
3274 setErrorMessage(message);
3275 uintptr_t terminationFlags = 0;
3276 if ( !gLinkContext.startedInitializingMainExecutable )
3277 terminationFlags = 1;
3278 setAlImageInfosHalt(error_string, terminationFlags);
3279 dyld_fatal_error(error_string);
3280 }
3281
3282 static void setErrorStrings(unsigned errorCode, const char* errorClientOfDylibPath,
3283 const char* errorTargetDylibPath, const char* errorSymbol)
3284 {
3285 dyld_all_image_infos.errorKind = errorCode;
3286 dyld_all_image_infos.errorClientOfDylibPath = errorClientOfDylibPath;
3287 dyld_all_image_infos.errorTargetDylibPath = errorTargetDylibPath;
3288 dyld_all_image_infos.errorSymbol = errorSymbol;
3289 }
3290
3291
3292 uintptr_t bindLazySymbol(const mach_header* mh, uintptr_t* lazyPointer)
3293 {
3294 uintptr_t result = 0;
3295 // acquire read-lock on dyld's data structures
3296 #if 0 // rdar://problem/3811777 turn off locking until deadlock is resolved
3297 if ( gLibSystemHelpers != NULL )
3298 (*gLibSystemHelpers->lockForReading)();
3299 #endif
3300 // lookup and bind lazy pointer and get target address
3301 try {
3302 ImageLoader* target;
3303 #if __i386__
3304 // fast stubs pass NULL for mh and image is instead found via the location of stub (aka lazyPointer)
3305 if ( mh == NULL )
3306 target = dyld::findImageContainingAddress(lazyPointer);
3307 else
3308 target = dyld::findImageByMachHeader(mh);
3309 #else
3310 // note, target should always be mach-o, because only mach-o lazy handler wired up to this
3311 target = dyld::findImageByMachHeader(mh);
3312 #endif
3313 if ( target == NULL )
3314 throwf("image not found for lazy pointer at %p", lazyPointer);
3315 result = target->doBindLazySymbol(lazyPointer, gLinkContext);
3316 }
3317 catch (const char* message) {
3318 dyld::log("dyld: lazy symbol binding failed: %s\n", message);
3319 halt(message);
3320 }
3321 // release read-lock on dyld's data structures
3322 #if 0
3323 if ( gLibSystemHelpers != NULL )
3324 (*gLibSystemHelpers->unlockForReading)();
3325 #endif
3326 // return target address to glue which jumps to it with real parameters restored
3327 return result;
3328 }
3329
3330
3331 uintptr_t fastBindLazySymbol(ImageLoader** imageLoaderCache, uintptr_t lazyBindingInfoOffset)
3332 {
3333 uintptr_t result = 0;
3334 // get image
3335 if ( *imageLoaderCache == NULL ) {
3336 // save in cache
3337 *imageLoaderCache = dyld::findMappedRange((uintptr_t)imageLoaderCache);
3338 if ( *imageLoaderCache == NULL ) {
3339 const char* message = "fast lazy binding from unknown image";
3340 dyld::log("dyld: %s\n", message);
3341 halt(message);
3342 }
3343 }
3344
3345 // bind lazy pointer and return it
3346 try {
3347 result = (*imageLoaderCache)->doBindFastLazySymbol(lazyBindingInfoOffset, gLinkContext,
3348 (dyld::gLibSystemHelpers != NULL) ? dyld::gLibSystemHelpers->acquireGlobalDyldLock : NULL,
3349 (dyld::gLibSystemHelpers != NULL) ? dyld::gLibSystemHelpers->releaseGlobalDyldLock : NULL);
3350 }
3351 catch (const char* message) {
3352 dyld::log("dyld: lazy symbol binding failed: %s\n", message);
3353 halt(message);
3354 }
3355
3356 // return target address to glue which jumps to it with real parameters restored
3357 return result;
3358 }
3359
3360
3361
3362 void registerUndefinedHandler(UndefinedHandler handler)
3363 {
3364 sUndefinedHandler = handler;
3365 }
3366
3367 static void undefinedHandler(const char* symboName)
3368 {
3369 if ( sUndefinedHandler != NULL ) {
3370 (*sUndefinedHandler)(symboName);
3371 }
3372 }
3373
3374 static bool findExportedSymbol(const char* name, bool onlyInCoalesced, const ImageLoader::Symbol** sym, const ImageLoader** image)
3375 {
3376 // search all images in order
3377 const ImageLoader* firstWeakImage = NULL;
3378 const ImageLoader::Symbol* firstWeakSym = NULL;
3379 const unsigned int imageCount = sAllImages.size();
3380 for(unsigned int i=0; i < imageCount; ++i) {
3381 ImageLoader* anImage = sAllImages[i];
3382 // the use of inserted libraries alters search order
3383 // so that inserted libraries are found before the main executable
3384 if ( sInsertedDylibCount > 0 ) {
3385 if ( i < sInsertedDylibCount )
3386 anImage = sAllImages[i+1];
3387 else if ( i == sInsertedDylibCount )
3388 anImage = sAllImages[0];
3389 }
3390 if ( ! anImage->hasHiddenExports() && (!onlyInCoalesced || anImage->hasCoalescedExports()) ) {
3391 *sym = anImage->findExportedSymbol(name, false, image);
3392 if ( *sym != NULL ) {
3393 // if weak definition found, record first one found
3394 if ( ((*image)->getExportedSymbolInfo(*sym) & ImageLoader::kWeakDefinition) != 0 ) {
3395 if ( firstWeakImage == NULL ) {
3396 firstWeakImage = *image;
3397 firstWeakSym = *sym;
3398 }
3399 }
3400 else {
3401 // found non-weak, so immediately return with it
3402 return true;
3403 }
3404 }
3405 }
3406 }
3407 if ( firstWeakSym != NULL ) {
3408 // found a weak definition, but no non-weak, so return first weak found
3409 *sym = firstWeakSym;
3410 *image = firstWeakImage;
3411 return true;
3412 }
3413
3414 return false;
3415 }
3416
3417 bool flatFindExportedSymbol(const char* name, const ImageLoader::Symbol** sym, const ImageLoader** image)
3418 {
3419 return findExportedSymbol(name, false, sym, image);
3420 }
3421
3422 bool findCoalescedExportedSymbol(const char* name, const ImageLoader::Symbol** sym, const ImageLoader** image)
3423 {
3424 return findExportedSymbol(name, true, sym, image);
3425 }
3426
3427
3428 bool flatFindExportedSymbolWithHint(const char* name, const char* librarySubstring, const ImageLoader::Symbol** sym, const ImageLoader** image)
3429 {
3430 // search all images in order
3431 const unsigned int imageCount = sAllImages.size();
3432 for(unsigned int i=0; i < imageCount; ++i){
3433 ImageLoader* anImage = sAllImages[i];
3434 // only look at images whose paths contain the hint string (NULL hint string is wildcard)
3435 if ( ! anImage->isBundle() && ((librarySubstring==NULL) || (strstr(anImage->getPath(), librarySubstring) != NULL)) ) {
3436 *sym = anImage->findExportedSymbol(name, false, image);
3437 if ( *sym != NULL ) {
3438 return true;
3439 }
3440 }
3441 }
3442 return false;
3443 }
3444
3445 unsigned int getCoalescedImages(ImageLoader* images[])
3446 {
3447 unsigned int count = 0;
3448 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
3449 ImageLoader* image = *it;
3450 if ( image->participatesInCoalescing() ) {
3451 *images++ = *it;
3452 ++count;
3453 }
3454 }
3455 return count;
3456 }
3457
3458
3459 static ImageLoader::MappedRegion* getMappedRegions(ImageLoader::MappedRegion* regions)
3460 {
3461 ImageLoader::MappedRegion* end = regions;
3462 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
3463 (*it)->getMappedRegions(end);
3464 }
3465 return end;
3466 }
3467
3468 void registerImageStateSingleChangeHandler(dyld_image_states state, dyld_image_state_change_handler handler)
3469 {
3470 // mark the image that the handler is in as never-unload because dyld has a reference into it
3471 ImageLoader* handlerImage = findImageContainingAddress((void*)handler);
3472 if ( handlerImage != NULL )
3473 handlerImage->setNeverUnload();
3474
3475 // add to list of handlers
3476 std::vector<dyld_image_state_change_handler>* handlers = stateToHandlers(state, sSingleHandlers);
3477 if ( handlers != NULL ) {
3478 handlers->push_back(handler);
3479
3480 // call callback with all existing images
3481 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
3482 ImageLoader* image = *it;
3483 dyld_image_info info;
3484 info.imageLoadAddress = image->machHeader();
3485 info.imageFilePath = image->getPath();
3486 info.imageFileModDate = image->lastModified();
3487 // should only call handler if state == image->state
3488 if ( image->getState() == state )
3489 (*handler)(state, 1, &info);
3490 // ignore returned string, too late to do anything
3491 }
3492 }
3493 }
3494
3495 void registerImageStateBatchChangeHandler(dyld_image_states state, dyld_image_state_change_handler handler)
3496 {
3497 // mark the image that the handler is in as never-unload because dyld has a reference into it
3498 ImageLoader* handlerImage = findImageContainingAddress((void*)handler);
3499 if ( handlerImage != NULL )
3500 handlerImage->setNeverUnload();
3501
3502 // add to list of handlers
3503 std::vector<dyld_image_state_change_handler>* handlers = stateToHandlers(state, sBatchHandlers);
3504 if ( handlers != NULL ) {
3505 // insert at front, so that gdb handler is always last
3506 handlers->insert(handlers->begin(), handler);
3507
3508 // call callback with all existing images
3509 try {
3510 notifyBatchPartial(state, true, handler);
3511 }
3512 catch (const char* msg) {
3513 // ignore request to abort during registration
3514 }
3515 }
3516 }
3517
3518 static ImageLoader* libraryLocator(const char* libraryName, bool search, const char* origin, const ImageLoader::RPathChain* rpaths)
3519 {
3520 dyld::LoadContext context;
3521 context.useSearchPaths = search;
3522 context.useFallbackPaths = search;
3523 context.useLdLibraryPath = false;
3524 context.implicitRPath = false;
3525 context.matchByInstallName = false;
3526 context.dontLoad = false;
3527 context.mustBeBundle = false;
3528 context.mustBeDylib = true;
3529 context.canBePIE = false;
3530 context.origin = origin;
3531 context.rpath = rpaths;
3532 return load(libraryName, context);
3533 }
3534
3535 static const char* basename(const char* path)
3536 {
3537 const char* last = path;
3538 for (const char* s = path; *s != '\0'; s++) {
3539 if (*s == '/')
3540 last = s+1;
3541 }
3542 return last;
3543 }
3544
3545 static void setContext(const macho_header* mainExecutableMH, int argc, const char* argv[], const char* envp[], const char* apple[])
3546 {
3547 gLinkContext.loadLibrary = &libraryLocator;
3548 gLinkContext.terminationRecorder = &terminationRecorder;
3549 gLinkContext.flatExportFinder = &flatFindExportedSymbol;
3550 gLinkContext.coalescedExportFinder = &findCoalescedExportedSymbol;
3551 gLinkContext.getCoalescedImages = &getCoalescedImages;
3552 gLinkContext.undefinedHandler = &undefinedHandler;
3553 gLinkContext.getAllMappedRegions = &getMappedRegions;
3554 gLinkContext.bindingHandler = NULL;
3555 gLinkContext.notifySingle = &notifySingle;
3556 gLinkContext.notifyBatch = &notifyBatch;
3557 gLinkContext.removeImage = &removeImage;
3558 gLinkContext.registerDOFs = &registerDOFs;
3559 gLinkContext.clearAllDepths = &clearAllDepths;
3560 gLinkContext.imageCount = &imageCount;
3561 gLinkContext.setNewProgramVars = &setNewProgramVars;
3562 #if DYLD_SHARED_CACHE_SUPPORT
3563 gLinkContext.inSharedCache = &inSharedCache;
3564 #endif
3565 gLinkContext.setErrorStrings = &setErrorStrings;
3566 #if SUPPORT_OLD_CRT_INITIALIZATION
3567 gLinkContext.setRunInitialzersOldWay= &setRunInitialzersOldWay;
3568 #endif
3569 gLinkContext.bindingOptions = ImageLoader::kBindingNone;
3570 gLinkContext.argc = argc;
3571 gLinkContext.argv = argv;
3572 gLinkContext.envp = envp;
3573 gLinkContext.apple = apple;
3574 gLinkContext.progname = (argv[0] != NULL) ? basename(argv[0]) : "";
3575 gLinkContext.programVars.mh = mainExecutableMH;
3576 gLinkContext.programVars.NXArgcPtr = &gLinkContext.argc;
3577 gLinkContext.programVars.NXArgvPtr = &gLinkContext.argv;
3578 gLinkContext.programVars.environPtr = &gLinkContext.envp;
3579 gLinkContext.programVars.__prognamePtr=&gLinkContext.progname;
3580 gLinkContext.mainExecutable = NULL;
3581 gLinkContext.imageSuffix = NULL;
3582 gLinkContext.prebindUsage = ImageLoader::kUseAllPrebinding;
3583 gLinkContext.sharedRegionMode = ImageLoader::kUseSharedRegion;
3584 }
3585
3586 #if __ppc__ || __i386__
3587 bool isRosetta()
3588 {
3589 int mib[] = { CTL_KERN, KERN_CLASSIC, getpid() };
3590 int is_classic = 0;
3591 size_t len = sizeof(int);
3592 int ret = sysctl(mib, 3, &is_classic, &len, NULL, 0);
3593 if ((ret != -1) && is_classic) {
3594 // we're running under Rosetta
3595 return true;
3596 }
3597 return false;
3598 }
3599 #endif
3600
3601
3602 #if __LP64__
3603 #define LC_SEGMENT_COMMAND LC_SEGMENT_64
3604 #define macho_segment_command segment_command_64
3605 #define macho_section section_64
3606 #else
3607 #define LC_SEGMENT_COMMAND LC_SEGMENT
3608 #define macho_segment_command segment_command
3609 #define macho_section section
3610 #endif
3611
3612
3613 //
3614 // Look for a special segment in the mach header.
3615 // Its presences means that the binary wants to have DYLD ignore
3616 // DYLD_ environment variables.
3617 //
3618 static bool hasRestrictedSegment(const macho_header* mh)
3619 {
3620 const uint32_t cmd_count = mh->ncmds;
3621 const struct load_command* const cmds = (struct load_command*)(((char*)mh)+sizeof(macho_header));
3622 const struct load_command* cmd = cmds;
3623 for (uint32_t i = 0; i < cmd_count; ++i) {
3624 switch (cmd->cmd) {
3625 case LC_SEGMENT_COMMAND:
3626 {
3627 const struct macho_segment_command* seg = (struct macho_segment_command*)cmd;
3628
3629 //dyld::log("seg name: %s\n", seg->segname);
3630 if (strcmp(seg->segname, "__RESTRICT") == 0) {
3631 const struct macho_section* const sectionsStart = (struct macho_section*)((char*)seg + sizeof(struct macho_segment_command));
3632 const struct macho_section* const sectionsEnd = &sectionsStart[seg->nsects];
3633 for (const struct macho_section* sect=sectionsStart; sect < sectionsEnd; ++sect) {
3634 if (strcmp(sect->sectname, "__restrict") == 0)
3635 return true;
3636 }
3637 }
3638 }
3639 break;
3640 }
3641 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
3642 }
3643
3644 return false;
3645 }
3646
3647
3648 //
3649 // Peeks at a dylib file and returns its current_version and install_name.
3650 // Returns false on error.
3651 //
3652 static bool getDylibVersionAndInstallname(const char* dylibPath, uint32_t* version, char* installName)
3653 {
3654 // open file (automagically closed when this function exits)
3655 FileOpener file(dylibPath);
3656
3657 if ( file.getFileDescriptor() == -1 )
3658 return false;
3659
3660 uint8_t firstPage[4096];
3661 if ( pread(file.getFileDescriptor(), firstPage, 4096, 0) != 4096 )
3662 return false;
3663
3664 // if fat wrapper, find usable sub-file
3665 const fat_header* fileStartAsFat = (fat_header*)firstPage;
3666 if ( fileStartAsFat->magic == OSSwapBigToHostInt32(FAT_MAGIC) ) {
3667 uint64_t fileOffset;
3668 uint64_t fileLength;
3669 if ( fatFindBest(fileStartAsFat, &fileOffset, &fileLength) ) {
3670 if ( pread(file.getFileDescriptor(), firstPage, 4096, fileOffset) != 4096 )
3671 return false;
3672 }
3673 else {
3674 return false;
3675 }
3676 }
3677
3678 // check mach-o header
3679 const mach_header* mh = (mach_header*)firstPage;
3680 if ( mh->magic != sMainExecutableMachHeader->magic )
3681 return false;
3682 if ( mh->cputype != sMainExecutableMachHeader->cputype )
3683 return false;
3684
3685 // scan load commands for LC_ID_DYLIB
3686 const uint32_t cmd_count = mh->ncmds;
3687 const struct load_command* const cmds = (struct load_command*)(((char*)mh)+sizeof(macho_header));
3688 const struct load_command* const cmdsReadEnd = (struct load_command*)(((char*)mh)+4096);
3689 const struct load_command* cmd = cmds;
3690 for (uint32_t i = 0; i < cmd_count; ++i) {
3691 switch (cmd->cmd) {
3692 case LC_ID_DYLIB:
3693 {
3694 const struct dylib_command* id = (struct dylib_command*)cmd;
3695 *version = id->dylib.current_version;
3696 if ( installName != NULL )
3697 strlcpy(installName, (char *)id + id->dylib.name.offset, PATH_MAX);
3698 return true;
3699 }
3700 break;
3701 }
3702 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
3703 if ( cmd > cmdsReadEnd )
3704 return false;
3705 }
3706
3707 return false;
3708 }
3709
3710 #if 0
3711 static void printAllImages()
3712 {
3713 dyld::log("printAllImages()\n");
3714 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
3715 ImageLoader* image = *it;
3716 dyld_image_states imageState = image->getState();
3717 dyld::log(" state=%d, refcount=%d, name=%s\n", imageState, image->referenceCount(), image->getShortName());
3718 image->printReferenceCounts();
3719 }
3720 }
3721 #endif
3722
3723 void link(ImageLoader* image, bool forceLazysBound, const ImageLoader::RPathChain& loaderRPaths)
3724 {
3725 // add to list of known images. This did not happen at creation time for bundles
3726 if ( image->isBundle() && !image->isLinked() )
3727 addImage(image);
3728
3729 // we detect root images as those not linked in yet
3730 if ( !image->isLinked() )
3731 addRootImage(image);
3732
3733 // process images
3734 try {
3735 image->link(gLinkContext, forceLazysBound, false, loaderRPaths);
3736 }
3737 catch (const char* msg) {
3738 garbageCollectImages();
3739 throw;
3740 }
3741 }
3742
3743
3744 void runInitializers(ImageLoader* image)
3745 {
3746 // do bottom up initialization
3747 ImageLoader::InitializerTimingList initializerTimes[sAllImages.size()];
3748 initializerTimes[0].count = 0;
3749 image->runInitializers(gLinkContext, initializerTimes[0]);
3750 }
3751
3752 void garbageCollectImages()
3753 {
3754 // keep scanning list of images until entire list is scanned with no unreferenced images
3755 bool mightBeUnreferencedImages = true;
3756 while ( mightBeUnreferencedImages ) {
3757 mightBeUnreferencedImages = false;
3758 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
3759 ImageLoader* image = *it;
3760 if ( (image->referenceCount() == 0) && !image->neverUnload() && !image->isBeingRemoved() ) {
3761 try {
3762 //dyld::log("garbageCollectImages: deleting %s\n", image->getPath());
3763 image->setBeingRemoved();
3764 removeImage(image);
3765 ImageLoader::deleteImage(image);
3766 }
3767 catch (const char* msg) {
3768 dyld::warn("problem deleting image: %s\n", msg);
3769 }
3770 mightBeUnreferencedImages = true;
3771 break;
3772 }
3773 }
3774 }
3775 //printAllImages();
3776 }
3777
3778
3779 static void preflight_finally(ImageLoader* image)
3780 {
3781 if ( image->isBundle() ) {
3782 removeImageFromAllImages(image->machHeader());
3783 ImageLoader::deleteImage(image);
3784 }
3785 sBundleBeingLoaded = NULL;
3786 dyld::garbageCollectImages();
3787 }
3788
3789
3790 void preflight(ImageLoader* image, const ImageLoader::RPathChain& loaderRPaths)
3791 {
3792 try {
3793 if ( image->isBundle() )
3794 sBundleBeingLoaded = image; // hack
3795 image->link(gLinkContext, false, true, loaderRPaths);
3796 }
3797 catch (const char* msg) {
3798 preflight_finally(image);
3799 throw;
3800 }
3801 preflight_finally(image);
3802 }
3803
3804 static void loadInsertedDylib(const char* path)
3805 {
3806 ImageLoader* image = NULL;
3807 try {
3808 LoadContext context;
3809 context.useSearchPaths = false;
3810 context.useFallbackPaths = false;
3811 context.useLdLibraryPath = false;
3812 context.implicitRPath = false;
3813 context.matchByInstallName = false;
3814 context.dontLoad = false;
3815 context.mustBeBundle = false;
3816 context.mustBeDylib = true;
3817 context.canBePIE = false;
3818 context.origin = NULL; // can't use @loader_path with DYLD_INSERT_LIBRARIES
3819 context.rpath = NULL;
3820 image = load(path, context);
3821 image->setNeverUnload();
3822 }
3823 catch (...) {
3824 halt(dyld::mkstringf("could not load inserted library: %s\n", path));
3825 }
3826 }
3827
3828 static bool processRestricted(const macho_header* mainExecutableMH)
3829 {
3830 // all processes with setuid or setgid bit set are restricted
3831 if ( issetugid() )
3832 return true;
3833
3834 if ( hasRestrictedSegment(mainExecutableMH) && (geteuid() != 0) ) {
3835 // existence of __RESTRICT/__restrict section make process restricted
3836 return true;
3837 }
3838
3839 #if __MAC_OS_X_VERSION_MIN_REQUIRED
3840 // ask kernel if code signature of program makes it restricted
3841 uint32_t flags;
3842 if ( syscall(SYS_csops /* 169 */,
3843 0 /* asking about myself */,
3844 CS_OPS_STATUS,
3845 &flags,
3846 sizeof(flags)) != -1) {
3847 if (flags & CS_RESTRICT)
3848 return true;
3849 }
3850 #endif
3851 return false;
3852 }
3853
3854
3855 //
3856 // Entry point for dyld. The kernel loads dyld and jumps to __dyld_start which
3857 // sets up some registers and call this function.
3858 //
3859 // Returns address of main() in target program which __dyld_start jumps to
3860 //
3861 uintptr_t
3862 _main(const macho_header* mainExecutableMH, uintptr_t mainExecutableSlide, int argc, const char* argv[], const char* envp[], const char* apple[])
3863 {
3864 CRSetCrashLogMessage("dyld: launch started");
3865 #ifdef ALTERNATIVE_LOGFILE
3866 sLogfile = open(ALTERNATIVE_LOGFILE, O_WRONLY | O_CREAT | O_APPEND);
3867 if ( sLogfile == -1 ) {
3868 sLogfile = STDERR_FILENO;
3869 dyld::log("error opening alternate log file %s, errno = %d\n", ALTERNATIVE_LOGFILE, errno);
3870 }
3871 #endif
3872
3873 #if LOG_BINDINGS
3874 char bindingsLogPath[256];
3875
3876 const char* shortProgName = "unknown";
3877 if ( argc > 0 ) {
3878 shortProgName = strrchr(argv[0], '/');
3879 if ( shortProgName == NULL )
3880 shortProgName = argv[0];
3881 else
3882 ++shortProgName;
3883 }
3884 mysprintf(bindingsLogPath, "/tmp/bindings/%d-%s", getpid(), shortProgName);
3885 sBindingsLogfile = open(bindingsLogPath, O_WRONLY | O_CREAT, 0666);
3886 if ( sBindingsLogfile == -1 ) {
3887 ::mkdir("/tmp/bindings", 0777);
3888 sBindingsLogfile = open(bindingsLogPath, O_WRONLY | O_CREAT, 0666);
3889 }
3890 //dyld::log("open(%s) => %d, errno = %d\n", bindingsLogPath, sBindingsLogfile, errno);
3891 #endif
3892 setContext(mainExecutableMH, argc, argv, envp, apple);
3893
3894 // Pickup the pointer to the exec path.
3895 sExecPath = apple[0];
3896 bool ignoreEnvironmentVariables = false;
3897 #if __i386__
3898 if ( isRosetta() ) {
3899 // under Rosetta (x86 side)
3900 // When a 32-bit ppc program is run under emulation on an Intel processor,
3901 // we want any i386 dylibs (e.g. any used by Rosetta) to not load in the shared region
3902 // because the shared region is being used by ppc dylibs
3903 gLinkContext.sharedRegionMode = ImageLoader::kDontUseSharedRegion;
3904 ignoreEnvironmentVariables = true;
3905 }
3906 #endif
3907 if ( sExecPath[0] != '/' ) {
3908 // have relative path, use cwd to make absolute
3909 char cwdbuff[MAXPATHLEN];
3910 if ( getcwd(cwdbuff, MAXPATHLEN) != NULL ) {
3911 // maybe use static buffer to avoid calling malloc so early...
3912 char* s = new char[strlen(cwdbuff) + strlen(sExecPath) + 2];
3913 strcpy(s, cwdbuff);
3914 strcat(s, "/");
3915 strcat(s, sExecPath);
3916 sExecPath = s;
3917 }
3918 }
3919 uintptr_t result = 0;
3920 sMainExecutableMachHeader = mainExecutableMH;
3921 sProcessIsRestricted = processRestricted(mainExecutableMH);
3922 if ( sProcessIsRestricted ) {
3923 #if SUPPORT_LC_DYLD_ENVIRONMENT
3924 checkLoadCommandEnvironmentVariables();
3925 #if SUPPORT_VERSIONED_PATHS
3926 checkVersionedPaths();
3927 #endif
3928 #endif
3929 pruneEnvironmentVariables(envp, &apple);
3930 // set again because envp and apple may have changed or moved
3931 setContext(mainExecutableMH, argc, argv, envp, apple);
3932 }
3933 else
3934 checkEnvironmentVariables(envp, ignoreEnvironmentVariables);
3935 if ( sEnv.DYLD_PRINT_OPTS )
3936 printOptions(argv);
3937 if ( sEnv.DYLD_PRINT_ENV )
3938 printEnvironmentVariables(envp);
3939 getHostInfo();
3940 // install gdb notifier
3941 stateToHandlers(dyld_image_state_dependents_mapped, sBatchHandlers)->push_back(notifyGDB);
3942 stateToHandlers(dyld_image_state_mapped, sSingleHandlers)->push_back(updateAllImages);
3943 // make initial allocations large enough that it is unlikely to need to be re-alloced
3944 sAllImages.reserve(INITIAL_IMAGE_COUNT);
3945 sImageRoots.reserve(16);
3946 sAddImageCallbacks.reserve(4);
3947 sRemoveImageCallbacks.reserve(4);
3948 sImageFilesNeedingTermination.reserve(16);
3949 sImageFilesNeedingDOFUnregistration.reserve(8);
3950
3951 #ifdef WAIT_FOR_SYSTEM_ORDER_HANDSHAKE
3952 // <rdar://problem/6849505> Add gating mechanism to dyld support system order file generation process
3953 WAIT_FOR_SYSTEM_ORDER_HANDSHAKE(dyld_all_image_infos.systemOrderFlag);
3954 #endif
3955
3956 try {
3957 CRSetCrashLogMessage("dyld: launch, loading dependent libraries");
3958 // instantiate ImageLoader for main executable
3959 sMainExecutable = instantiateFromLoadedImage(mainExecutableMH, mainExecutableSlide, sExecPath);
3960 sMainExecutable->setNeverUnload();
3961 gLinkContext.mainExecutable = sMainExecutable;
3962 gLinkContext.processIsRestricted = sProcessIsRestricted;
3963 // load shared cache
3964 checkSharedRegionDisable();
3965 #if DYLD_SHARED_CACHE_SUPPORT
3966 if ( gLinkContext.sharedRegionMode != ImageLoader::kDontUseSharedRegion )
3967 mapSharedCache();
3968 #endif
3969 // load any inserted libraries
3970 if ( sEnv.DYLD_INSERT_LIBRARIES != NULL ) {
3971 for (const char* const* lib = sEnv.DYLD_INSERT_LIBRARIES; *lib != NULL; ++lib)
3972 loadInsertedDylib(*lib);
3973 }
3974 // record count of inserted libraries so that a flat search will look at
3975 // inserted libraries, then main, then others.
3976 sInsertedDylibCount = sAllImages.size()-1;
3977
3978 // link main executable
3979 gLinkContext.linkingMainExecutable = true;
3980 link(sMainExecutable, sEnv.DYLD_BIND_AT_LAUNCH, ImageLoader::RPathChain(NULL, NULL));
3981 gLinkContext.linkingMainExecutable = false;
3982 if ( sMainExecutable->forceFlat() ) {
3983 gLinkContext.bindFlat = true;
3984 gLinkContext.prebindUsage = ImageLoader::kUseNoPrebinding;
3985 }
3986 result = (uintptr_t)sMainExecutable->getMain();
3987
3988 // link any inserted libraries
3989 // do this after linking main executable so that any dylibs pulled in by inserted
3990 // dylibs (e.g. libSystem) will not be in front of dylibs the program uses
3991 if ( sInsertedDylibCount > 0 ) {
3992 for(unsigned int i=0; i < sInsertedDylibCount; ++i) {
3993 ImageLoader* image = sAllImages[i+1];
3994 link(image, sEnv.DYLD_BIND_AT_LAUNCH, ImageLoader::RPathChain(NULL, NULL));
3995 // only INSERTED libraries can interpose
3996 image->registerInterposing();
3997 }
3998 }
3999
4000 CRSetCrashLogMessage("dyld: launch, running initializers");
4001 #if SUPPORT_OLD_CRT_INITIALIZATION
4002 // Old way is to run initializers via a callback from crt1.o
4003 if ( ! gRunInitializersOldWay )
4004 #endif
4005 initializeMainExecutable(); // run all initializers
4006 }
4007 catch(const char* message) {
4008 syncAllImages();
4009 halt(message);
4010 }
4011 catch(...) {
4012 dyld::log("dyld: launch failed\n");
4013 }
4014
4015 #ifdef ALTERNATIVE_LOGFILE
4016 // only use alternate log during launch, otherwise file is open forever
4017 if ( sLogfile != STDERR_FILENO ) {
4018 close(sLogfile);
4019 sLogfile = STDERR_FILENO;
4020 }
4021 #endif
4022 CRSetCrashLogMessage(NULL);
4023
4024 return result;
4025 }
4026
4027
4028
4029
4030 }; // namespace
4031
4032
4033