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