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