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