]> git.saurik.com Git - apple/dyld.git/blob - src/dyld.cpp
648b8873bd7a1e7588efaa769650fe16083fcaca
[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 if ( strlcpy(dylibPath, dirPath, PATH_MAX) >= PATH_MAX )
1194 return;
1195 DIR* dirp = opendir(dirPath);
1196 if ( dirp != NULL) {
1197 dirent entry;
1198 dirent* entp = NULL;
1199 while ( readdir_r(dirp, &entry, &entp) == 0 ) {
1200 if ( entp == NULL )
1201 break;
1202 if ( entp->d_type != DT_REG )
1203 continue;
1204 if ( strlcat(dylibPath, "/", PATH_MAX) >= PATH_MAX )
1205 continue;
1206 if ( strlcat(dylibPath, entp->d_name, PATH_MAX) >= PATH_MAX )
1207 continue;
1208 checkDylibOverride(dylibPath);
1209 }
1210 closedir(dirp);
1211 }
1212 }
1213
1214
1215 static void checkFrameworkOverridesInDir(const char* dirPath)
1216 {
1217 //dyld::log("checkFrameworkOverridesInDir('%s')\n", dirPath);
1218 char frameworkPath[PATH_MAX];
1219 if ( strlcpy(frameworkPath, dirPath, PATH_MAX) >= PATH_MAX )
1220 return;
1221 DIR* dirp = opendir(dirPath);
1222 if ( dirp != NULL) {
1223 dirent entry;
1224 dirent* entp = NULL;
1225 while ( readdir_r(dirp, &entry, &entp) == 0 ) {
1226 if ( entp == NULL )
1227 break;
1228 if ( entp->d_type != DT_DIR )
1229 continue;
1230 if ( strlcat(frameworkPath, "/", PATH_MAX) >= PATH_MAX )
1231 continue;
1232 int dirNameLen = strlen(entp->d_name);
1233 if ( dirNameLen < 11 )
1234 continue;
1235 if ( strcmp(&entp->d_name[dirNameLen-10], ".framework") != 0 )
1236 continue;
1237 if ( strlcat(frameworkPath, entp->d_name, PATH_MAX) >= PATH_MAX )
1238 continue;
1239 if ( strlcat(frameworkPath, "/", PATH_MAX) >= PATH_MAX )
1240 continue;
1241 if ( strlcat(frameworkPath, entp->d_name, PATH_MAX) >= PATH_MAX )
1242 continue;
1243 frameworkPath[strlen(frameworkPath)-10] = '\0';
1244 checkDylibOverride(frameworkPath);
1245 }
1246 closedir(dirp);
1247 }
1248 }
1249 #endif // SUPPORT_VERSIONED_PATHS
1250
1251
1252 //
1253 // Turns a colon separated list of strings into a NULL terminated array
1254 // of string pointers. If mainExecutableDir param is not NULL,
1255 // substitutes @loader_path with main executable's dir.
1256 //
1257 static const char** parseColonList(const char* list, const char* mainExecutableDir)
1258 {
1259 static const char* sEmptyList[] = { NULL };
1260
1261 if ( list[0] == '\0' )
1262 return sEmptyList;
1263
1264 int colonCount = 0;
1265 for(const char* s=list; *s != '\0'; ++s) {
1266 if (*s == ':')
1267 ++colonCount;
1268 }
1269
1270 int index = 0;
1271 const char* start = list;
1272 char** result = new char*[colonCount+2];
1273 for(const char* s=list; *s != '\0'; ++s) {
1274 if (*s == ':') {
1275 size_t len = s-start;
1276 if ( (mainExecutableDir != NULL) && (strncmp(start, "@loader_path/", 13) == 0) ) {
1277 size_t mainExecDirLen = strlen(mainExecutableDir);
1278 char* str = new char[mainExecDirLen+len+1];
1279 strcpy(str, mainExecutableDir);
1280 strlcat(str, &start[13], mainExecDirLen+len+1);
1281 str[mainExecDirLen+len-13] = '\0';
1282 start = &s[1];
1283 result[index++] = str;
1284 }
1285 else if ( (mainExecutableDir != NULL) && (strncmp(start, "@executable_path/", 17) == 0) ) {
1286 size_t mainExecDirLen = strlen(mainExecutableDir);
1287 char* str = new char[mainExecDirLen+len+1];
1288 strcpy(str, mainExecutableDir);
1289 strlcat(str, &start[17], mainExecDirLen+len+1);
1290 str[mainExecDirLen+len-17] = '\0';
1291 start = &s[1];
1292 result[index++] = str;
1293 }
1294 else {
1295 char* str = new char[len+1];
1296 strncpy(str, start, len);
1297 str[len] = '\0';
1298 start = &s[1];
1299 result[index++] = str;
1300 }
1301 }
1302 }
1303 size_t len = strlen(start);
1304 if ( (mainExecutableDir != NULL) && (strncmp(start, "@loader_path/", 13) == 0) ) {
1305 size_t mainExecDirLen = strlen(mainExecutableDir);
1306 char* str = new char[mainExecDirLen+len+1];
1307 strcpy(str, mainExecutableDir);
1308 strlcat(str, &start[13], mainExecDirLen+len+1);
1309 str[mainExecDirLen+len-13] = '\0';
1310 result[index++] = str;
1311 }
1312 else if ( (mainExecutableDir != NULL) && (strncmp(start, "@executable_path/", 17) == 0) ) {
1313 size_t mainExecDirLen = strlen(mainExecutableDir);
1314 char* str = new char[mainExecDirLen+len+1];
1315 strcpy(str, mainExecutableDir);
1316 strlcat(str, &start[17], mainExecDirLen+len+1);
1317 str[mainExecDirLen+len-17] = '\0';
1318 result[index++] = str;
1319 }
1320 else {
1321 char* str = new char[len+1];
1322 strcpy(str, start);
1323 result[index++] = str;
1324 }
1325 result[index] = NULL;
1326
1327 //dyld::log("parseColonList(%s)\n", list);
1328 //for(int i=0; result[i] != NULL; ++i)
1329 // dyld::log(" %s\n", result[i]);
1330 return (const char**)result;
1331 }
1332
1333 static void appendParsedColonList(const char* list, const char* mainExecutableDir, const char* const ** storage)
1334 {
1335 const char** newlist = parseColonList(list, mainExecutableDir);
1336 if ( *storage == NULL ) {
1337 // first time, just set
1338 *storage = newlist;
1339 }
1340 else {
1341 // need to append to existing list
1342 const char* const* existing = *storage;
1343 int count = 0;
1344 for(int i=0; existing[i] != NULL; ++i)
1345 ++count;
1346 for(int i=0; newlist[i] != NULL; ++i)
1347 ++count;
1348 const char** combinedList = new const char*[count+2];
1349 int index = 0;
1350 for(int i=0; existing[i] != NULL; ++i)
1351 combinedList[index++] = existing[i];
1352 for(int i=0; newlist[i] != NULL; ++i)
1353 combinedList[index++] = newlist[i];
1354 combinedList[index] = NULL;
1355 // leak old arrays
1356 *storage = combinedList;
1357 }
1358 }
1359
1360
1361 static void paths_expand_roots(const char **paths, const char *key, const char *val)
1362 {
1363 // assert(val != NULL);
1364 // assert(paths != NULL);
1365 if(NULL != key) {
1366 size_t keyLen = strlen(key);
1367 for(int i=0; paths[i] != NULL; ++i) {
1368 if ( strncmp(paths[i], key, keyLen) == 0 ) {
1369 char* newPath = new char[strlen(val) + (strlen(paths[i]) - keyLen) + 1];
1370 strcpy(newPath, val);
1371 strcat(newPath, &paths[i][keyLen]);
1372 paths[i] = newPath;
1373 }
1374 }
1375 }
1376 return;
1377 }
1378
1379 static void removePathWithPrefix(const char* paths[], const char* prefix)
1380 {
1381 size_t prefixLen = strlen(prefix);
1382 int skip = 0;
1383 int i;
1384 for(i = 0; paths[i] != NULL; ++i) {
1385 if ( strncmp(paths[i], prefix, prefixLen) == 0 )
1386 ++skip;
1387 else
1388 paths[i-skip] = paths[i];
1389 }
1390 paths[i-skip] = NULL;
1391 }
1392
1393
1394 #if 0
1395 static void paths_dump(const char **paths)
1396 {
1397 // assert(paths != NULL);
1398 const char **strs = paths;
1399 while(*strs != NULL)
1400 {
1401 dyld::log("\"%s\"\n", *strs);
1402 strs++;
1403 }
1404 return;
1405 }
1406 #endif
1407
1408 static void printOptions(const char* argv[])
1409 {
1410 uint32_t i = 0;
1411 while ( NULL != argv[i] ) {
1412 dyld::log("opt[%i] = \"%s\"\n", i, argv[i]);
1413 i++;
1414 }
1415 }
1416
1417 static void printEnvironmentVariables(const char* envp[])
1418 {
1419 while ( NULL != *envp ) {
1420 dyld::log("%s\n", *envp);
1421 envp++;
1422 }
1423 }
1424
1425 void processDyldEnvironmentVariable(const char* key, const char* value, const char* mainExecutableDir)
1426 {
1427 if ( strcmp(key, "DYLD_FRAMEWORK_PATH") == 0 ) {
1428 appendParsedColonList(value, mainExecutableDir, &sEnv.DYLD_FRAMEWORK_PATH);
1429 }
1430 else if ( strcmp(key, "DYLD_FALLBACK_FRAMEWORK_PATH") == 0 ) {
1431 appendParsedColonList(value, mainExecutableDir, &sEnv.DYLD_FALLBACK_FRAMEWORK_PATH);
1432 }
1433 else if ( strcmp(key, "DYLD_LIBRARY_PATH") == 0 ) {
1434 appendParsedColonList(value, mainExecutableDir, &sEnv.DYLD_LIBRARY_PATH);
1435 }
1436 else if ( strcmp(key, "DYLD_FALLBACK_LIBRARY_PATH") == 0 ) {
1437 appendParsedColonList(value, mainExecutableDir, &sEnv.DYLD_FALLBACK_LIBRARY_PATH);
1438 }
1439 else if ( (strcmp(key, "DYLD_ROOT_PATH") == 0) || (strcmp(key, "DYLD_PATHS_ROOT") == 0) ) {
1440 if ( strcmp(value, "/") != 0 ) {
1441 gLinkContext.rootPaths = parseColonList(value, mainExecutableDir);
1442 for (int i=0; gLinkContext.rootPaths[i] != NULL; ++i) {
1443 if ( gLinkContext.rootPaths[i][0] != '/' ) {
1444 dyld::warn("DYLD_ROOT_PATH not used because it contains a non-absolute path\n");
1445 gLinkContext.rootPaths = NULL;
1446 break;
1447 }
1448 }
1449 }
1450 }
1451 else if ( strcmp(key, "DYLD_IMAGE_SUFFIX") == 0 ) {
1452 gLinkContext.imageSuffix = value;
1453 }
1454 else if ( strcmp(key, "DYLD_INSERT_LIBRARIES") == 0 ) {
1455 sEnv.DYLD_INSERT_LIBRARIES = parseColonList(value, NULL);
1456 }
1457 else if ( strcmp(key, "DYLD_PRINT_OPTS") == 0 ) {
1458 sEnv.DYLD_PRINT_OPTS = true;
1459 }
1460 else if ( strcmp(key, "DYLD_PRINT_ENV") == 0 ) {
1461 sEnv.DYLD_PRINT_ENV = true;
1462 }
1463 else if ( strcmp(key, "DYLD_DISABLE_DOFS") == 0 ) {
1464 sEnv.DYLD_DISABLE_DOFS = true;
1465 }
1466 else if ( strcmp(key, "DYLD_DISABLE_PREFETCH") == 0 ) {
1467 gLinkContext.preFetchDisabled = true;
1468 }
1469 else if ( strcmp(key, "DYLD_PRINT_LIBRARIES") == 0 ) {
1470 sEnv.DYLD_PRINT_LIBRARIES = true;
1471 }
1472 else if ( strcmp(key, "DYLD_PRINT_LIBRARIES_POST_LAUNCH") == 0 ) {
1473 sEnv.DYLD_PRINT_LIBRARIES_POST_LAUNCH = true;
1474 }
1475 else if ( strcmp(key, "DYLD_BIND_AT_LAUNCH") == 0 ) {
1476 sEnv.DYLD_BIND_AT_LAUNCH = true;
1477 }
1478 else if ( strcmp(key, "DYLD_FORCE_FLAT_NAMESPACE") == 0 ) {
1479 gLinkContext.bindFlat = true;
1480 }
1481 else if ( strcmp(key, "DYLD_NEW_LOCAL_SHARED_REGIONS") == 0 ) {
1482 // ignore, no longer relevant but some scripts still set it
1483 }
1484 else if ( strcmp(key, "DYLD_NO_FIX_PREBINDING") == 0 ) {
1485 }
1486 else if ( strcmp(key, "DYLD_PREBIND_DEBUG") == 0 ) {
1487 gLinkContext.verbosePrebinding = true;
1488 }
1489 else if ( strcmp(key, "DYLD_PRINT_INITIALIZERS") == 0 ) {
1490 gLinkContext.verboseInit = true;
1491 }
1492 else if ( strcmp(key, "DYLD_PRINT_DOFS") == 0 ) {
1493 gLinkContext.verboseDOF = true;
1494 }
1495 else if ( strcmp(key, "DYLD_PRINT_STATISTICS") == 0 ) {
1496 sEnv.DYLD_PRINT_STATISTICS = true;
1497 }
1498 else if ( strcmp(key, "DYLD_PRINT_SEGMENTS") == 0 ) {
1499 gLinkContext.verboseMapping = true;
1500 }
1501 else if ( strcmp(key, "DYLD_PRINT_BINDINGS") == 0 ) {
1502 gLinkContext.verboseBind = true;
1503 }
1504 else if ( strcmp(key, "DYLD_PRINT_WEAK_BINDINGS") == 0 ) {
1505 gLinkContext.verboseWeakBind = true;
1506 }
1507 else if ( strcmp(key, "DYLD_PRINT_REBASINGS") == 0 ) {
1508 gLinkContext.verboseRebase = true;
1509 }
1510 else if ( strcmp(key, "DYLD_PRINT_APIS") == 0 ) {
1511 gLogAPIs = true;
1512 }
1513 else if ( strcmp(key, "DYLD_PRINT_WARNINGS") == 0 ) {
1514 gLinkContext.verboseWarnings = true;
1515 }
1516 else if ( strcmp(key, "DYLD_PRINT_RPATHS") == 0 ) {
1517 gLinkContext.verboseRPaths = true;
1518 }
1519 else if ( strcmp(key, "DYLD_PRINT_CS_NOTIFICATIONS") == 0 ) {
1520 sEnv.DYLD_PRINT_CS_NOTIFICATIONS = true;
1521 }
1522 else if ( strcmp(key, "DYLD_PRINT_INTERPOSING") == 0 ) {
1523 gLinkContext.verboseInterposing = true;
1524 }
1525 else if ( strcmp(key, "DYLD_PRINT_CODE_SIGNATURES") == 0 ) {
1526 gLinkContext.verboseCodeSignatures = true;
1527 }
1528 else if ( strcmp(key, "DYLD_SHARED_REGION") == 0 ) {
1529 if ( strcmp(value, "private") == 0 ) {
1530 gLinkContext.sharedRegionMode = ImageLoader::kUsePrivateSharedRegion;
1531 }
1532 else if ( strcmp(value, "avoid") == 0 ) {
1533 gLinkContext.sharedRegionMode = ImageLoader::kDontUseSharedRegion;
1534 }
1535 else if ( strcmp(value, "use") == 0 ) {
1536 gLinkContext.sharedRegionMode = ImageLoader::kUseSharedRegion;
1537 }
1538 else if ( value[0] == '\0' ) {
1539 gLinkContext.sharedRegionMode = ImageLoader::kUseSharedRegion;
1540 }
1541 else {
1542 dyld::warn("unknown option to DYLD_SHARED_REGION. Valid options are: use, private, avoid\n");
1543 }
1544 }
1545 #if DYLD_SHARED_CACHE_SUPPORT
1546 else if ( strcmp(key, "DYLD_SHARED_CACHE_DIR") == 0 ) {
1547 sSharedCacheDir = value;
1548 }
1549 else if ( strcmp(key, "DYLD_SHARED_CACHE_DONT_VALIDATE") == 0 ) {
1550 sSharedCacheIgnoreInodeAndTimeStamp = true;
1551 }
1552 #endif
1553 else if ( strcmp(key, "DYLD_IGNORE_PREBINDING") == 0 ) {
1554 if ( strcmp(value, "all") == 0 ) {
1555 gLinkContext.prebindUsage = ImageLoader::kUseNoPrebinding;
1556 }
1557 else if ( strcmp(value, "app") == 0 ) {
1558 gLinkContext.prebindUsage = ImageLoader::kUseAllButAppPredbinding;
1559 }
1560 else if ( strcmp(value, "nonsplit") == 0 ) {
1561 gLinkContext.prebindUsage = ImageLoader::kUseSplitSegPrebinding;
1562 }
1563 else if ( value[0] == '\0' ) {
1564 gLinkContext.prebindUsage = ImageLoader::kUseSplitSegPrebinding;
1565 }
1566 else {
1567 dyld::warn("unknown option to DYLD_IGNORE_PREBINDING. Valid options are: all, app, nonsplit\n");
1568 }
1569 }
1570 #if SUPPORT_VERSIONED_PATHS
1571 else if ( strcmp(key, "DYLD_VERSIONED_LIBRARY_PATH") == 0 ) {
1572 appendParsedColonList(value, mainExecutableDir, &sEnv.DYLD_VERSIONED_LIBRARY_PATH);
1573 }
1574 else if ( strcmp(key, "DYLD_VERSIONED_FRAMEWORK_PATH") == 0 ) {
1575 appendParsedColonList(value, mainExecutableDir, &sEnv.DYLD_VERSIONED_FRAMEWORK_PATH);
1576 }
1577 #endif
1578 #if !TARGET_IPHONE_SIMULATOR
1579 else if ( (strcmp(key, "DYLD_PRINT_TO_FILE") == 0) && (mainExecutableDir == NULL) ) {
1580 int fd = open(value, O_WRONLY | O_CREAT | O_APPEND, 0644);
1581 if ( fd != -1 ) {
1582 sLogfile = fd;
1583 sLogToFile = true;
1584 }
1585 else {
1586 dyld::log("dyld: could not open DYLD_PRINT_TO_FILE='%s', errno=%d\n", value, errno);
1587 }
1588 }
1589 #endif
1590 else {
1591 dyld::warn("unknown environment variable: %s\n", key);
1592 }
1593 }
1594
1595
1596 #if SUPPORT_LC_DYLD_ENVIRONMENT
1597 static void checkLoadCommandEnvironmentVariables()
1598 {
1599 // <rdar://problem/8440934> Support augmenting dyld environment variables in load commands
1600 const uint32_t cmd_count = sMainExecutableMachHeader->ncmds;
1601 const struct load_command* const cmds = (struct load_command*)(((char*)sMainExecutableMachHeader)+sizeof(macho_header));
1602 const struct load_command* cmd = cmds;
1603 for (uint32_t i = 0; i < cmd_count; ++i) {
1604 switch (cmd->cmd) {
1605 case LC_DYLD_ENVIRONMENT:
1606 {
1607 const struct dylinker_command* envcmd = (struct dylinker_command*)cmd;
1608 const char* keyEqualsValue = (char*)envcmd + envcmd->name.offset;
1609 char mainExecutableDir[strlen(sExecPath)+2];
1610 strcpy(mainExecutableDir, sExecPath);
1611 char* lastSlash = strrchr(mainExecutableDir, '/');
1612 if ( lastSlash != NULL)
1613 lastSlash[1] = '\0';
1614 // only process variables that start with DYLD_ and end in _PATH
1615 if ( (strncmp(keyEqualsValue, "DYLD_", 5) == 0) ) {
1616 const char* equals = strchr(keyEqualsValue, '=');
1617 if ( equals != NULL ) {
1618 if ( strncmp(&equals[-5], "_PATH", 5) == 0 ) {
1619 const char* value = &equals[1];
1620 const size_t keyLen = equals-keyEqualsValue;
1621 char key[keyLen+1];
1622 strncpy(key, keyEqualsValue, keyLen);
1623 key[keyLen] = '\0';
1624 //dyld::log("processing: %s\n", keyEqualsValue);
1625 //dyld::log("mainExecutableDir: %s\n", mainExecutableDir);
1626 processDyldEnvironmentVariable(key, value, mainExecutableDir);
1627 }
1628 }
1629 }
1630 }
1631 break;
1632 }
1633 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
1634 }
1635 }
1636 #endif // SUPPORT_LC_DYLD_ENVIRONMENT
1637
1638
1639 static bool hasCodeSignatureLoadCommand(const macho_header* mh)
1640 {
1641 const uint32_t cmd_count = mh->ncmds;
1642 const struct load_command* const cmds = (struct load_command*)(((char*)mh)+sizeof(macho_header));
1643 const struct load_command* cmd = cmds;
1644 for (uint32_t i = 0; i < cmd_count; ++i) {
1645 if (cmd->cmd == LC_CODE_SIGNATURE)
1646 return true;
1647 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
1648 }
1649 return false;
1650 }
1651
1652
1653 #if SUPPORT_VERSIONED_PATHS
1654 static void checkVersionedPaths()
1655 {
1656 // search DYLD_VERSIONED_LIBRARY_PATH directories for dylibs and check if they are newer
1657 if ( sEnv.DYLD_VERSIONED_LIBRARY_PATH != NULL ) {
1658 for(const char* const* lp = sEnv.DYLD_VERSIONED_LIBRARY_PATH; *lp != NULL; ++lp) {
1659 checkDylibOverridesInDir(*lp);
1660 }
1661 }
1662
1663 // search DYLD_VERSIONED_FRAMEWORK_PATH directories for dylibs and check if they are newer
1664 if ( sEnv.DYLD_VERSIONED_FRAMEWORK_PATH != NULL ) {
1665 for(const char* const* fp = sEnv.DYLD_VERSIONED_FRAMEWORK_PATH; *fp != NULL; ++fp) {
1666 checkFrameworkOverridesInDir(*fp);
1667 }
1668 }
1669 }
1670 #endif
1671
1672
1673 //
1674 // For security, setuid programs ignore DYLD_* environment variables.
1675 // Additionally, the DYLD_* enviroment variables are removed
1676 // from the environment, so that any child processes don't see them.
1677 //
1678 static void pruneEnvironmentVariables(const char* envp[], const char*** applep)
1679 {
1680 // delete all DYLD_* and LD_LIBRARY_PATH environment variables
1681 int removedCount = 0;
1682 const char** d = envp;
1683 for(const char** s = envp; *s != NULL; s++) {
1684 if ( (strncmp(*s, "DYLD_", 5) != 0) && (strncmp(*s, "LD_LIBRARY_PATH=", 16) != 0) ) {
1685 *d++ = *s;
1686 }
1687 else {
1688 ++removedCount;
1689 }
1690 }
1691 *d++ = NULL;
1692 // <rdar://11894054> Disable warnings about DYLD_ env vars being ignored. The warnings are causing too much confusion.
1693 #if 0
1694 if ( removedCount != 0 ) {
1695 dyld::log("dyld: DYLD_ environment variables being ignored because ");
1696 switch (sRestrictedReason) {
1697 case restrictedNot:
1698 break;
1699 case restrictedBySetGUid:
1700 dyld::log("main executable (%s) is setuid or setgid\n", sExecPath);
1701 break;
1702 case restrictedBySegment:
1703 dyld::log("main executable (%s) has __RESTRICT/__restrict section\n", sExecPath);
1704 break;
1705 case restrictedByEntitlements:
1706 dyld::log("main executable (%s) is code signed with entitlements\n", sExecPath);
1707 break;
1708 }
1709 }
1710 #endif
1711 // slide apple parameters
1712 if ( removedCount > 0 ) {
1713 *applep = d;
1714 do {
1715 *d = d[removedCount];
1716 } while ( *d++ != NULL );
1717 for(int i=0; i < removedCount; ++i)
1718 *d++ = NULL;
1719 }
1720
1721 // disable framework and library fallback paths for setuid binaries rdar://problem/4589305
1722 sEnv.DYLD_FALLBACK_FRAMEWORK_PATH = NULL;
1723 sEnv.DYLD_FALLBACK_LIBRARY_PATH = NULL;
1724
1725 if ( removedCount > 0 )
1726 strlcat(sLoadingCrashMessage, ", ignoring DYLD_* env vars", sizeof(sLoadingCrashMessage));
1727 }
1728
1729 static void defaultUninitializedFallbackPaths(const char* envp[])
1730 {
1731 #if __MAC_OS_X_VERSION_MIN_REQUIRED
1732 // default value for DYLD_FALLBACK_FRAMEWORK_PATH, if not set in environment
1733 const char* home = _simple_getenv(envp, "HOME");;
1734 if ( sEnv.DYLD_FALLBACK_FRAMEWORK_PATH == NULL ) {
1735 const char** fpaths = sFrameworkFallbackPaths;
1736 if ( home == NULL )
1737 removePathWithPrefix(fpaths, "$HOME");
1738 else
1739 paths_expand_roots(fpaths, "$HOME", home);
1740 sEnv.DYLD_FALLBACK_FRAMEWORK_PATH = fpaths;
1741 }
1742
1743 // default value for DYLD_FALLBACK_LIBRARY_PATH, if not set in environment
1744 if ( sEnv.DYLD_FALLBACK_LIBRARY_PATH == NULL ) {
1745 const char** lpaths = sLibraryFallbackPaths;
1746 if ( home == NULL )
1747 removePathWithPrefix(lpaths, "$HOME");
1748 else
1749 paths_expand_roots(lpaths, "$HOME", home);
1750 sEnv.DYLD_FALLBACK_LIBRARY_PATH = lpaths;
1751 }
1752 #else
1753 if ( sEnv.DYLD_FALLBACK_FRAMEWORK_PATH == NULL )
1754 sEnv.DYLD_FALLBACK_FRAMEWORK_PATH = sFrameworkFallbackPaths;
1755
1756 if ( sEnv.DYLD_FALLBACK_LIBRARY_PATH == NULL )
1757 sEnv.DYLD_FALLBACK_LIBRARY_PATH = sLibraryFallbackPaths;
1758 #endif
1759 }
1760
1761
1762 static void checkEnvironmentVariables(const char* envp[])
1763 {
1764 const char** p;
1765 for(p = envp; *p != NULL; p++) {
1766 const char* keyEqualsValue = *p;
1767 if ( strncmp(keyEqualsValue, "DYLD_", 5) == 0 ) {
1768 const char* equals = strchr(keyEqualsValue, '=');
1769 if ( equals != NULL ) {
1770 strlcat(sLoadingCrashMessage, "\n", sizeof(sLoadingCrashMessage));
1771 strlcat(sLoadingCrashMessage, keyEqualsValue, sizeof(sLoadingCrashMessage));
1772 const char* value = &equals[1];
1773 const size_t keyLen = equals-keyEqualsValue;
1774 char key[keyLen+1];
1775 strncpy(key, keyEqualsValue, keyLen);
1776 key[keyLen] = '\0';
1777 processDyldEnvironmentVariable(key, value, NULL);
1778 }
1779 }
1780 else if ( strncmp(keyEqualsValue, "LD_LIBRARY_PATH=", 16) == 0 ) {
1781 const char* path = &keyEqualsValue[16];
1782 sEnv.LD_LIBRARY_PATH = parseColonList(path, NULL);
1783 }
1784 }
1785
1786 #if SUPPORT_LC_DYLD_ENVIRONMENT
1787 checkLoadCommandEnvironmentVariables();
1788 #endif // SUPPORT_LC_DYLD_ENVIRONMENT
1789
1790 // <rdar://problem/11281064> DYLD_IMAGE_SUFFIX and DYLD_ROOT_PATH cannot be used together
1791 if ( (gLinkContext.imageSuffix != NULL) && (gLinkContext.rootPaths != NULL) ) {
1792 dyld::warn("Ignoring DYLD_IMAGE_SUFFIX because DYLD_ROOT_PATH is used.\n");
1793 gLinkContext.imageSuffix = NULL;
1794 }
1795 }
1796
1797 #if __x86_64__
1798 static bool isGCProgram(const macho_header* mh, uintptr_t slide)
1799 {
1800 const uint32_t cmd_count = mh->ncmds;
1801 const struct load_command* const cmds = (struct load_command*)(((char*)mh)+sizeof(macho_header));
1802 const struct load_command* cmd = cmds;
1803 for (uint32_t i = 0; i < cmd_count; ++i) {
1804 switch (cmd->cmd) {
1805 case LC_SEGMENT_COMMAND:
1806 {
1807 const struct macho_segment_command* seg = (struct macho_segment_command*)cmd;
1808 if (strcmp(seg->segname, "__DATA") == 0) {
1809 const struct macho_section* const sectionsStart = (struct macho_section*)((char*)seg + sizeof(struct macho_segment_command));
1810 const struct macho_section* const sectionsEnd = &sectionsStart[seg->nsects];
1811 for (const struct macho_section* sect=sectionsStart; sect < sectionsEnd; ++sect) {
1812 if (strncmp(sect->sectname, "__objc_imageinfo", 16) == 0) {
1813 const uint32_t* objcInfo = (uint32_t*)(sect->addr + slide);
1814 return (objcInfo[1] & 6); // 6 = (OBJC_IMAGE_SUPPORTS_GC | OBJC_IMAGE_REQUIRES_GC)
1815 }
1816 }
1817 }
1818 }
1819 break;
1820 }
1821 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
1822 }
1823 return false;
1824 }
1825 #endif
1826 static void getHostInfo(const macho_header* mainExecutableMH, uintptr_t mainExecutableSlide)
1827 {
1828 #if CPU_SUBTYPES_SUPPORTED
1829 #if __ARM_ARCH_7K__
1830 sHostCPU = CPU_TYPE_ARM;
1831 sHostCPUsubtype = CPU_SUBTYPE_ARM_V7K;
1832 #elif __ARM_ARCH_7A__
1833 sHostCPU = CPU_TYPE_ARM;
1834 sHostCPUsubtype = CPU_SUBTYPE_ARM_V7;
1835 #elif __ARM_ARCH_6K__
1836 sHostCPU = CPU_TYPE_ARM;
1837 sHostCPUsubtype = CPU_SUBTYPE_ARM_V6;
1838 #elif __ARM_ARCH_7F__
1839 sHostCPU = CPU_TYPE_ARM;
1840 sHostCPUsubtype = CPU_SUBTYPE_ARM_V7F;
1841 #elif __ARM_ARCH_7S__
1842 sHostCPU = CPU_TYPE_ARM;
1843 sHostCPUsubtype = CPU_SUBTYPE_ARM_V7S;
1844 #else
1845 struct host_basic_info info;
1846 mach_msg_type_number_t count = HOST_BASIC_INFO_COUNT;
1847 mach_port_t hostPort = mach_host_self();
1848 kern_return_t result = host_info(hostPort, HOST_BASIC_INFO, (host_info_t)&info, &count);
1849 if ( result != KERN_SUCCESS )
1850 throw "host_info() failed";
1851 sHostCPU = info.cpu_type;
1852 sHostCPUsubtype = info.cpu_subtype;
1853 mach_port_deallocate(mach_task_self(), hostPort);
1854 #if __x86_64__
1855 #if TARGET_IPHONE_SIMULATOR
1856 sHaswell = false;
1857 #else
1858 sHaswell = (sHostCPUsubtype == CPU_SUBTYPE_X86_64_H);
1859 // <rdar://problem/18528074> x86_64h: Fall back to the x86_64 slice if an app requires GC.
1860 if ( sHaswell ) {
1861 if ( isGCProgram(mainExecutableMH, mainExecutableSlide) ) {
1862 // When running a GC program on a haswell machine, don't use and 'h slices
1863 sHostCPUsubtype = CPU_SUBTYPE_X86_64_ALL;
1864 sHaswell = false;
1865 gLinkContext.sharedRegionMode = ImageLoader::kDontUseSharedRegion;
1866 }
1867 }
1868 #endif
1869 #endif
1870 #endif
1871 #endif
1872 }
1873
1874 static void checkSharedRegionDisable()
1875 {
1876 #if __MAC_OS_X_VERSION_MIN_REQUIRED
1877 // if main executable has segments that overlap the shared region,
1878 // then disable using the shared region
1879 if ( sMainExecutable->overlapsWithAddressRange((void*)(uintptr_t)SHARED_REGION_BASE, (void*)(uintptr_t)(SHARED_REGION_BASE + SHARED_REGION_SIZE)) ) {
1880 gLinkContext.sharedRegionMode = ImageLoader::kDontUseSharedRegion;
1881 if ( gLinkContext.verboseMapping )
1882 dyld::warn("disabling shared region because main executable overlaps\n");
1883 }
1884 #if __i386__
1885 if ( sProcessIsRestricted ) {
1886 // <rdar://problem/15280847> use private or no shared region for suid processes
1887 gLinkContext.sharedRegionMode = ImageLoader::kUsePrivateSharedRegion;
1888 }
1889 #endif
1890 #endif
1891 // iPhoneOS cannot run without shared region
1892 }
1893
1894 bool validImage(const ImageLoader* possibleImage)
1895 {
1896 const size_t imageCount = sAllImages.size();
1897 for(size_t i=0; i < imageCount; ++i) {
1898 if ( possibleImage == sAllImages[i] ) {
1899 return true;
1900 }
1901 }
1902 return false;
1903 }
1904
1905 uint32_t getImageCount()
1906 {
1907 return (uint32_t)sAllImages.size();
1908 }
1909
1910 ImageLoader* getIndexedImage(unsigned int index)
1911 {
1912 if ( index < sAllImages.size() )
1913 return sAllImages[index];
1914 return NULL;
1915 }
1916
1917 ImageLoader* findImageByMachHeader(const struct mach_header* target)
1918 {
1919 return findMappedRange((uintptr_t)target);
1920 }
1921
1922
1923 ImageLoader* findImageContainingAddress(const void* addr)
1924 {
1925 return findMappedRange((uintptr_t)addr);
1926 }
1927
1928
1929 ImageLoader* findImageContainingSymbol(const void* symbol)
1930 {
1931 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
1932 ImageLoader* anImage = *it;
1933 if ( anImage->containsSymbol(symbol) )
1934 return anImage;
1935 }
1936 return NULL;
1937 }
1938
1939
1940
1941 void forEachImageDo( void (*callback)(ImageLoader*, void* userData), void* userData)
1942 {
1943 const size_t imageCount = sAllImages.size();
1944 for(size_t i=0; i < imageCount; ++i) {
1945 ImageLoader* anImage = sAllImages[i];
1946 (*callback)(anImage, userData);
1947 }
1948 }
1949
1950 ImageLoader* findLoadedImage(const struct stat& stat_buf)
1951 {
1952 const size_t imageCount = sAllImages.size();
1953 for(size_t i=0; i < imageCount; ++i){
1954 ImageLoader* anImage = sAllImages[i];
1955 if ( anImage->statMatch(stat_buf) )
1956 return anImage;
1957 }
1958 return NULL;
1959 }
1960
1961 // based on ANSI-C strstr()
1962 static const char* strrstr(const char* str, const char* sub)
1963 {
1964 const size_t sublen = strlen(sub);
1965 for(const char* p = &str[strlen(str)]; p != str; --p) {
1966 if ( strncmp(p, sub, sublen) == 0 )
1967 return p;
1968 }
1969 return NULL;
1970 }
1971
1972
1973 //
1974 // Find framework path
1975 //
1976 // /path/foo.framework/foo => foo.framework/foo
1977 // /path/foo.framework/Versions/A/foo => foo.framework/Versions/A/foo
1978 // /path/foo.framework/Frameworks/bar.framework/bar => bar.framework/bar
1979 // /path/foo.framework/Libraries/bar.dylb => NULL
1980 // /path/foo.framework/bar => NULL
1981 //
1982 // Returns NULL if not a framework path
1983 //
1984 static const char* getFrameworkPartialPath(const char* path)
1985 {
1986 const char* dirDot = strrstr(path, ".framework/");
1987 if ( dirDot != NULL ) {
1988 const char* dirStart = dirDot;
1989 for ( ; dirStart >= path; --dirStart) {
1990 if ( (*dirStart == '/') || (dirStart == path) ) {
1991 const char* frameworkStart = &dirStart[1];
1992 if ( dirStart == path )
1993 --frameworkStart;
1994 size_t len = dirDot - frameworkStart;
1995 char framework[len+1];
1996 strncpy(framework, frameworkStart, len);
1997 framework[len] = '\0';
1998 const char* leaf = strrchr(path, '/');
1999 if ( leaf != NULL ) {
2000 if ( strcmp(framework, &leaf[1]) == 0 ) {
2001 return frameworkStart;
2002 }
2003 if ( gLinkContext.imageSuffix != NULL ) {
2004 // some debug frameworks have install names that end in _debug
2005 if ( strncmp(framework, &leaf[1], len) == 0 ) {
2006 if ( strcmp( gLinkContext.imageSuffix, &leaf[len+1]) == 0 )
2007 return frameworkStart;
2008 }
2009 }
2010 }
2011 }
2012 }
2013 }
2014 return NULL;
2015 }
2016
2017
2018 static const char* getLibraryLeafName(const char* path)
2019 {
2020 const char* start = strrchr(path, '/');
2021 if ( start != NULL )
2022 return &start[1];
2023 else
2024 return path;
2025 }
2026
2027
2028 // only for architectures that use cpu-sub-types
2029 #if CPU_SUBTYPES_SUPPORTED
2030
2031 const cpu_subtype_t CPU_SUBTYPE_END_OF_LIST = -1;
2032
2033
2034 //
2035 // A fat file may contain multiple sub-images for the same CPU type.
2036 // In that case, dyld picks which sub-image to use by scanning a table
2037 // of preferred cpu-sub-types for the running cpu.
2038 //
2039 // There is one row in the table for each cpu-sub-type on which dyld might run.
2040 // The first entry in a row is that cpu-sub-type. It is followed by all
2041 // cpu-sub-types that can run on that cpu, if preferred order. Each row ends with
2042 // a "SUBTYPE_ALL" (to denote that images written to run on any cpu-sub-type are usable),
2043 // followed by one or more CPU_SUBTYPE_END_OF_LIST to pad out this row.
2044 //
2045
2046
2047 #if __arm__
2048 //
2049 // ARM sub-type lists
2050 //
2051 const int kARM_RowCount = 8;
2052 static const cpu_subtype_t kARM[kARM_RowCount][9] = {
2053
2054 // armv7f can run: v7f, v7, v6, v5, and v4
2055 { 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 },
2056
2057 // armv7k can run: v7k
2058 { CPU_SUBTYPE_ARM_V7K, CPU_SUBTYPE_END_OF_LIST },
2059
2060 // armv7s can run: v7s, v7, v7f, v7k, v6, v5, and v4
2061 { 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 },
2062
2063 // armv7 can run: v7, v6, v5, and v4
2064 { 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 },
2065
2066 // armv6 can run: v6, v5, and v4
2067 { 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 },
2068
2069 // xscale can run: xscale, v5, and v4
2070 { 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 },
2071
2072 // armv5 can run: v5 and v4
2073 { 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 },
2074
2075 // armv4 can run: v4
2076 { 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 },
2077 };
2078 #endif
2079
2080 #if __x86_64__
2081 //
2082 // x86_64 sub-type lists
2083 //
2084 const int kX86_64_RowCount = 2;
2085 static const cpu_subtype_t kX86_64[kX86_64_RowCount][5] = {
2086
2087 // x86_64h can run: x86_64h, x86_64h(lib), x86_64(lib), and x86_64
2088 { 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 },
2089
2090 // x86_64 can run: x86_64(lib) and x86_64
2091 { CPU_SUBTYPE_X86_64_ALL, CPU_SUBTYPE_LIB64|CPU_SUBTYPE_X86_64_ALL, CPU_SUBTYPE_END_OF_LIST },
2092
2093 };
2094 #endif
2095
2096
2097 // scan the tables above to find the cpu-sub-type-list for this machine
2098 static const cpu_subtype_t* findCPUSubtypeList(cpu_type_t cpu, cpu_subtype_t subtype)
2099 {
2100 switch (cpu) {
2101 #if __arm__
2102 case CPU_TYPE_ARM:
2103 for (int i=0; i < kARM_RowCount ; ++i) {
2104 if ( kARM[i][0] == subtype )
2105 return kARM[i];
2106 }
2107 break;
2108 #endif
2109 #if __x86_64__
2110 case CPU_TYPE_X86_64:
2111 for (int i=0; i < kX86_64_RowCount ; ++i) {
2112 if ( kX86_64[i][0] == subtype )
2113 return kX86_64[i];
2114 }
2115 break;
2116 #endif
2117 }
2118 return NULL;
2119 }
2120
2121
2122
2123
2124 // scan fat table-of-contents for best most preferred subtype
2125 static bool fatFindBestFromOrderedList(cpu_type_t cpu, const cpu_subtype_t list[], const fat_header* fh, uint64_t* offset, uint64_t* len)
2126 {
2127 const fat_arch* const archs = (fat_arch*)(((char*)fh)+sizeof(fat_header));
2128 for (uint32_t subTypeIndex=0; list[subTypeIndex] != CPU_SUBTYPE_END_OF_LIST; ++subTypeIndex) {
2129 for(uint32_t fatIndex=0; fatIndex < OSSwapBigToHostInt32(fh->nfat_arch); ++fatIndex) {
2130 if ( ((cpu_type_t)OSSwapBigToHostInt32(archs[fatIndex].cputype) == cpu)
2131 && (list[subTypeIndex] == (cpu_subtype_t)OSSwapBigToHostInt32(archs[fatIndex].cpusubtype)) ) {
2132 *offset = OSSwapBigToHostInt32(archs[fatIndex].offset);
2133 *len = OSSwapBigToHostInt32(archs[fatIndex].size);
2134 return true;
2135 }
2136 }
2137 }
2138 return false;
2139 }
2140
2141 // scan fat table-of-contents for exact match of cpu and cpu-sub-type
2142 static bool fatFindExactMatch(cpu_type_t cpu, cpu_subtype_t subtype, const fat_header* fh, uint64_t* offset, uint64_t* len)
2143 {
2144 const fat_arch* archs = (fat_arch*)(((char*)fh)+sizeof(fat_header));
2145 for(uint32_t i=0; i < OSSwapBigToHostInt32(fh->nfat_arch); ++i) {
2146 if ( ((cpu_type_t)OSSwapBigToHostInt32(archs[i].cputype) == cpu)
2147 && ((cpu_subtype_t)OSSwapBigToHostInt32(archs[i].cpusubtype) == subtype) ) {
2148 *offset = OSSwapBigToHostInt32(archs[i].offset);
2149 *len = OSSwapBigToHostInt32(archs[i].size);
2150 return true;
2151 }
2152 }
2153 return false;
2154 }
2155
2156 // scan fat table-of-contents for image with matching cpu-type and runs-on-all-sub-types
2157 static bool fatFindRunsOnAllCPUs(cpu_type_t cpu, const fat_header* fh, uint64_t* offset, uint64_t* len)
2158 {
2159 const fat_arch* archs = (fat_arch*)(((char*)fh)+sizeof(fat_header));
2160 for(uint32_t i=0; i < OSSwapBigToHostInt32(fh->nfat_arch); ++i) {
2161 if ( (cpu_type_t)OSSwapBigToHostInt32(archs[i].cputype) == cpu) {
2162 switch (cpu) {
2163 #if __arm__
2164 case CPU_TYPE_ARM:
2165 if ( (cpu_subtype_t)OSSwapBigToHostInt32(archs[i].cpusubtype) == CPU_SUBTYPE_ARM_ALL ) {
2166 *offset = OSSwapBigToHostInt32(archs[i].offset);
2167 *len = OSSwapBigToHostInt32(archs[i].size);
2168 return true;
2169 }
2170 break;
2171 #endif
2172 #if __x86_64__
2173 case CPU_TYPE_X86_64:
2174 if ( (cpu_subtype_t)OSSwapBigToHostInt32(archs[i].cpusubtype) == CPU_SUBTYPE_X86_64_ALL ) {
2175 *offset = OSSwapBigToHostInt32(archs[i].offset);
2176 *len = OSSwapBigToHostInt32(archs[i].size);
2177 return true;
2178 }
2179 break;
2180 #endif
2181 }
2182 }
2183 }
2184 return false;
2185 }
2186
2187 #endif // CPU_SUBTYPES_SUPPORTED
2188
2189 //
2190 // A fat file may contain multiple sub-images for the same cpu-type,
2191 // each optimized for a different cpu-sub-type (e.g G3 or G5).
2192 // This routine picks the optimal sub-image.
2193 //
2194 static bool fatFindBest(const fat_header* fh, uint64_t* offset, uint64_t* len)
2195 {
2196 #if CPU_SUBTYPES_SUPPORTED
2197 // assume all dylibs loaded must have same cpu type as main executable
2198 const cpu_type_t cpu = sMainExecutableMachHeader->cputype;
2199
2200 // We only know the subtype to use if the main executable cpu type matches the host
2201 if ( (cpu & CPU_TYPE_MASK) == sHostCPU ) {
2202 // get preference ordered list of subtypes
2203 const cpu_subtype_t* subTypePreferenceList = findCPUSubtypeList(cpu, sHostCPUsubtype);
2204
2205 // use ordered list to find best sub-image in fat file
2206 if ( subTypePreferenceList != NULL )
2207 return fatFindBestFromOrderedList(cpu, subTypePreferenceList, fh, offset, len);
2208
2209 // if running cpu is not in list, try for an exact match
2210 if ( fatFindExactMatch(cpu, sHostCPUsubtype, fh, offset, len) )
2211 return true;
2212 }
2213
2214 // running on an uknown cpu, can only load generic code
2215 return fatFindRunsOnAllCPUs(cpu, fh, offset, len);
2216 #else
2217 // just find first slice with matching architecture
2218 const fat_arch* archs = (fat_arch*)(((char*)fh)+sizeof(fat_header));
2219 for(uint32_t i=0; i < OSSwapBigToHostInt32(fh->nfat_arch); ++i) {
2220 if ( (cpu_type_t)OSSwapBigToHostInt32(archs[i].cputype) == sMainExecutableMachHeader->cputype) {
2221 *offset = OSSwapBigToHostInt32(archs[i].offset);
2222 *len = OSSwapBigToHostInt32(archs[i].size);
2223 return true;
2224 }
2225 }
2226 return false;
2227 #endif
2228 }
2229
2230
2231
2232 //
2233 // This is used to validate if a non-fat (aka thin or raw) mach-o file can be used
2234 // on the current processor. //
2235 bool isCompatibleMachO(const uint8_t* firstPage, const char* path)
2236 {
2237 #if CPU_SUBTYPES_SUPPORTED
2238 // It is deemed compatible if any of the following are true:
2239 // 1) mach_header subtype is in list of compatible subtypes for running processor
2240 // 2) mach_header subtype is same as running processor subtype
2241 // 3) mach_header subtype runs on all processor variants
2242 const mach_header* mh = (mach_header*)firstPage;
2243 if ( mh->magic == sMainExecutableMachHeader->magic ) {
2244 if ( mh->cputype == sMainExecutableMachHeader->cputype ) {
2245 if ( (mh->cputype & CPU_TYPE_MASK) == sHostCPU ) {
2246 // get preference ordered list of subtypes that this machine can use
2247 const cpu_subtype_t* subTypePreferenceList = findCPUSubtypeList(mh->cputype, sHostCPUsubtype);
2248 if ( subTypePreferenceList != NULL ) {
2249 // if image's subtype is in the list, it is compatible
2250 for (const cpu_subtype_t* p = subTypePreferenceList; *p != CPU_SUBTYPE_END_OF_LIST; ++p) {
2251 if ( *p == mh->cpusubtype )
2252 return true;
2253 }
2254 // have list and not in list, so not compatible
2255 throwf("incompatible cpu-subtype: 0x%08X in %s", mh->cpusubtype, path);
2256 }
2257 // unknown cpu sub-type, but if exact match for current subtype then ok to use
2258 if ( mh->cpusubtype == sHostCPUsubtype )
2259 return true;
2260 }
2261
2262 // cpu type has no ordered list of subtypes
2263 switch (mh->cputype) {
2264 case CPU_TYPE_I386:
2265 case CPU_TYPE_X86_64:
2266 // subtypes are not used or these architectures
2267 return true;
2268 }
2269 }
2270 }
2271 #else
2272 // For architectures that don't support cpu-sub-types
2273 // this just check the cpu type.
2274 const mach_header* mh = (mach_header*)firstPage;
2275 if ( mh->magic == sMainExecutableMachHeader->magic ) {
2276 if ( mh->cputype == sMainExecutableMachHeader->cputype ) {
2277 return true;
2278 }
2279 }
2280 #endif
2281 return false;
2282 }
2283
2284
2285
2286
2287 // The kernel maps in main executable before dyld gets control. We need to
2288 // make an ImageLoader* for the already mapped in main executable.
2289 static ImageLoader* instantiateFromLoadedImage(const macho_header* mh, uintptr_t slide, const char* path)
2290 {
2291 // try mach-o loader
2292 if ( isCompatibleMachO((const uint8_t*)mh, path) ) {
2293 ImageLoader* image = ImageLoaderMachO::instantiateMainExecutable(mh, slide, path, gLinkContext);
2294 addImage(image);
2295 return image;
2296 }
2297
2298 throw "main executable not a known format";
2299 }
2300
2301
2302 #if DYLD_SHARED_CACHE_SUPPORT
2303 static bool findInSharedCacheImage(const char* path, bool searchByPath, const struct stat* stat_buf, const macho_header** mh, const char** pathInCache, long* slide)
2304 {
2305 if ( sSharedCache != NULL ) {
2306 #if __MAC_OS_X_VERSION_MIN_REQUIRED
2307 // Mac OS X always requires inode/mtime to valid cache
2308 // if stat() not done yet, do it now
2309 struct stat statb;
2310 if ( stat_buf == NULL ) {
2311 if ( my_stat(path, &statb) == -1 )
2312 return false;
2313 stat_buf = &statb;
2314 }
2315 #endif
2316 #if __IPHONE_OS_VERSION_MIN_REQUIRED
2317 uint64_t hash = 0;
2318 for (const char* s=path; *s != '\0'; ++s)
2319 hash += hash*4 + *s;
2320 #endif
2321
2322 // walk shared cache to see if there is a cached image that matches the inode/mtime/path desired
2323 const dyld_cache_image_info* const start = (dyld_cache_image_info*)((uint8_t*)sSharedCache + sSharedCache->imagesOffset);
2324 const dyld_cache_image_info* const end = &start[sSharedCache->imagesCount];
2325 #if __IPHONE_OS_VERSION_MIN_REQUIRED
2326 const bool cacheHasHashInfo = (start->modTime == 0);
2327 #endif
2328 for( const dyld_cache_image_info* p = start; p != end; ++p) {
2329 #if __IPHONE_OS_VERSION_MIN_REQUIRED
2330 // just check path
2331 const char* aPath = (char*)sSharedCache + p->pathFileOffset;
2332 if ( cacheHasHashInfo && (p->inode != hash) )
2333 continue;
2334 if ( strcmp(path, aPath) == 0 ) {
2335 // found image in cache
2336 *mh = (macho_header*)(p->address+sSharedCacheSlide);
2337 *pathInCache = aPath;
2338 *slide = sSharedCacheSlide;
2339 return true;
2340 }
2341 #elif __MAC_OS_X_VERSION_MIN_REQUIRED
2342 // check mtime and inode first because it is fast
2343 bool inodeMatch = ( ((time_t)p->modTime == stat_buf->st_mtime) && ((ino_t)p->inode == stat_buf->st_ino) );
2344 if ( searchByPath || sSharedCacheIgnoreInodeAndTimeStamp || inodeMatch ) {
2345 // mod-time and inode match an image in the shared cache, now check path
2346 const char* aPath = (char*)sSharedCache + p->pathFileOffset;
2347 bool cacheHit = (strcmp(path, aPath) == 0);
2348 if ( inodeMatch && !cacheHit ) {
2349 // path does not match install name of dylib in cache, but inode and mtime does match
2350 // perhaps path is a symlink to the cached dylib
2351 struct stat pathInCacheStatBuf;
2352 if ( my_stat(aPath, &pathInCacheStatBuf) != -1 )
2353 cacheHit = ( (pathInCacheStatBuf.st_dev == stat_buf->st_dev) && (pathInCacheStatBuf.st_ino == stat_buf->st_ino) );
2354 }
2355 if ( cacheHit ) {
2356 // found image in cache, return info
2357 *mh = (macho_header*)(p->address+sSharedCacheSlide);
2358 //dyld::log("findInSharedCacheImage(), mh=%p, p->address=0x%0llX, slid=0x%0lX, path=%p\n",
2359 // *mh, p->address, sSharedCacheSlide, aPath);
2360 *pathInCache = aPath;
2361 *slide = sSharedCacheSlide;
2362 return true;
2363 }
2364 }
2365 #endif
2366 }
2367 }
2368 return false;
2369 }
2370
2371 bool inSharedCache(const char* path)
2372 {
2373 const macho_header* mhInCache;
2374 const char* pathInCache;
2375 long slide;
2376 return findInSharedCacheImage(path, true, NULL, &mhInCache, &pathInCache, &slide);
2377 }
2378
2379 #endif
2380
2381 static ImageLoader* checkandAddImage(ImageLoader* image, const LoadContext& context)
2382 {
2383 // now sanity check that this loaded image does not have the same install path as any existing image
2384 const char* loadedImageInstallPath = image->getInstallPath();
2385 if ( image->isDylib() && (loadedImageInstallPath != NULL) && (loadedImageInstallPath[0] == '/') ) {
2386 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
2387 ImageLoader* anImage = *it;
2388 const char* installPath = anImage->getInstallPath();
2389 if ( installPath != NULL) {
2390 if ( strcmp(loadedImageInstallPath, installPath) == 0 ) {
2391 //dyld::log("duplicate(%s) => %p\n", installPath, anImage);
2392 removeImage(image);
2393 ImageLoader::deleteImage(image);
2394 return anImage;
2395 }
2396 }
2397 }
2398 }
2399
2400 // some API's restrict what they can load
2401 if ( context.mustBeBundle && !image->isBundle() )
2402 throw "not a bundle";
2403 if ( context.mustBeDylib && !image->isDylib() )
2404 throw "not a dylib";
2405
2406 // regular main executables cannot be loaded
2407 if ( image->isExecutable() ) {
2408 if ( !context.canBePIE || !image->isPositionIndependentExecutable() )
2409 throw "can't load a main executable";
2410 }
2411
2412 // don't add bundles to global list, they can be loaded but not linked. When linked it will be added to list
2413 if ( ! image->isBundle() )
2414 addImage(image);
2415
2416 return image;
2417 }
2418
2419 #if TARGET_IPHONE_SIMULATOR
2420 static bool isSimulatorBinary(const uint8_t* firstPage, const char* path)
2421 {
2422 const macho_header* mh = (macho_header*)firstPage;
2423 const uint32_t cmd_count = mh->ncmds;
2424 const struct load_command* const cmds = (struct load_command*)(((char*)mh)+sizeof(macho_header));
2425 const struct load_command* const cmdsReadEnd = (struct load_command*)(((char*)mh)+4096);
2426 const struct load_command* cmd = cmds;
2427 for (uint32_t i = 0; i < cmd_count; ++i) {
2428 switch (cmd->cmd) {
2429 case LC_VERSION_MIN_IPHONEOS:
2430 case LC_VERSION_MIN_TVOS:
2431 case LC_VERSION_MIN_WATCHOS:
2432 return true;
2433 case LC_VERSION_MIN_MACOSX:
2434 // grandfather in a few libSystem dylibs
2435 if (strstr(path, "/usr/lib/system") || strstr(path, "/usr/lib/libSystem"))
2436 return true;
2437 return false;
2438 }
2439 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
2440 if ( cmd > cmdsReadEnd )
2441 return true;
2442 }
2443 return false;
2444 }
2445 #endif
2446
2447 // map in file and instantiate an ImageLoader
2448 static ImageLoader* loadPhase6(int fd, const struct stat& stat_buf, const char* path, const LoadContext& context)
2449 {
2450 //dyld::log("%s(%s)\n", __func__ , path);
2451 uint64_t fileOffset = 0;
2452 uint64_t fileLength = stat_buf.st_size;
2453
2454 // validate it is a file (not directory)
2455 if ( (stat_buf.st_mode & S_IFMT) != S_IFREG )
2456 throw "not a file";
2457
2458 uint8_t firstPage[4096];
2459 bool shortPage = false;
2460
2461 // min mach-o file is 4K
2462 if ( fileLength < 4096 ) {
2463 if ( pread(fd, firstPage, fileLength, 0) != (ssize_t)fileLength )
2464 throwf("pread of short file failed: %d", errno);
2465 shortPage = true;
2466 }
2467 else {
2468 if ( pread(fd, firstPage, 4096,0) != 4096 )
2469 throwf("pread of first 4K failed: %d", errno);
2470 }
2471
2472 // if fat wrapper, find usable sub-file
2473 const fat_header* fileStartAsFat = (fat_header*)firstPage;
2474 if ( fileStartAsFat->magic == OSSwapBigToHostInt32(FAT_MAGIC) ) {
2475 if ( fatFindBest(fileStartAsFat, &fileOffset, &fileLength) ) {
2476 if ( (fileOffset+fileLength) > (uint64_t)(stat_buf.st_size) )
2477 throwf("truncated fat file. file length=%llu, but needed slice goes to %llu", stat_buf.st_size, fileOffset+fileLength);
2478 if (pread(fd, firstPage, 4096, fileOffset) != 4096)
2479 throwf("pread of fat file failed: %d", errno);
2480 }
2481 else {
2482 throw "no matching architecture in universal wrapper";
2483 }
2484 }
2485
2486 // try mach-o loader
2487 if ( shortPage )
2488 throw "file too short";
2489 if ( isCompatibleMachO(firstPage, path) ) {
2490
2491 // only MH_BUNDLE, MH_DYLIB, and some MH_EXECUTE can be dynamically loaded
2492 switch ( ((mach_header*)firstPage)->filetype ) {
2493 case MH_EXECUTE:
2494 case MH_DYLIB:
2495 case MH_BUNDLE:
2496 break;
2497 default:
2498 throw "mach-o, but wrong filetype";
2499 }
2500
2501 #if TARGET_IPHONE_SIMULATOR
2502 #if TARGET_OS_WATCH || TARGET_OS_TV
2503 // disable error during bring up of these simulators
2504 #else
2505 // <rdar://problem/14168872> dyld_sim should restrict loading osx binaries
2506 if ( !isSimulatorBinary(firstPage, path) ) {
2507 throw "mach-o, but not built for iOS simulator";
2508 }
2509 #endif
2510 #endif
2511
2512 // instantiate an image
2513 ImageLoader* image = ImageLoaderMachO::instantiateFromFile(path, fd, firstPage, fileOffset, fileLength, stat_buf, gLinkContext);
2514
2515 // validate
2516 return checkandAddImage(image, context);
2517 }
2518
2519 // try other file formats here...
2520
2521
2522 // throw error about what was found
2523 switch (*(uint32_t*)firstPage) {
2524 case MH_MAGIC:
2525 case MH_CIGAM:
2526 case MH_MAGIC_64:
2527 case MH_CIGAM_64:
2528 throw "mach-o, but wrong architecture";
2529 default:
2530 throwf("unknown file type, first eight bytes: 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X",
2531 firstPage[0], firstPage[1], firstPage[2], firstPage[3], firstPage[4], firstPage[5], firstPage[6],firstPage[7]);
2532 }
2533 }
2534
2535
2536 static ImageLoader* loadPhase5open(const char* path, const LoadContext& context, const struct stat& stat_buf, std::vector<const char*>* exceptions)
2537 {
2538 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
2539
2540 // open file (automagically closed when this function exits)
2541 FileOpener file(path);
2542
2543 // just return NULL if file not found, but record any other errors
2544 if ( file.getFileDescriptor() == -1 ) {
2545 int err = errno;
2546 if ( err != ENOENT ) {
2547 const char* newMsg = dyld::mkstringf("%s: open() failed with errno=%d", path, err);
2548 exceptions->push_back(newMsg);
2549 }
2550 return NULL;
2551 }
2552
2553 try {
2554 return loadPhase6(file.getFileDescriptor(), stat_buf, path, context);
2555 }
2556 catch (const char* msg) {
2557 const char* newMsg = dyld::mkstringf("%s: %s", path, msg);
2558 exceptions->push_back(newMsg);
2559 free((void*)msg);
2560 return NULL;
2561 }
2562 }
2563
2564
2565 #if __MAC_OS_X_VERSION_MIN_REQUIRED
2566 static ImageLoader* loadPhase5load(const char* path, const char* orgPath, const LoadContext& context, std::vector<const char*>* exceptions)
2567 {
2568 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
2569 ImageLoader* image = NULL;
2570
2571 // just return NULL if file not found, but record any other errors
2572 struct stat stat_buf;
2573 if ( my_stat(path, &stat_buf) == -1 ) {
2574 int err = errno;
2575 if ( err != ENOENT ) {
2576 exceptions->push_back(dyld::mkstringf("%s: stat() failed with errno=%d", path, err));
2577 }
2578 return NULL;
2579 }
2580
2581 // in case image was renamed or found via symlinks, check for inode match
2582 image = findLoadedImage(stat_buf);
2583 if ( image != NULL )
2584 return image;
2585
2586 // do nothing if not already loaded and if RTLD_NOLOAD or NSADDIMAGE_OPTION_RETURN_ONLY_IF_LOADED
2587 if ( context.dontLoad )
2588 return NULL;
2589
2590 #if DYLD_SHARED_CACHE_SUPPORT
2591 // see if this image is in shared cache
2592 const macho_header* mhInCache;
2593 const char* pathInCache;
2594 long slideInCache;
2595 if ( findInSharedCacheImage(path, false, &stat_buf, &mhInCache, &pathInCache, &slideInCache) ) {
2596 image = ImageLoaderMachO::instantiateFromCache(mhInCache, pathInCache, slideInCache, stat_buf, gLinkContext);
2597 return checkandAddImage(image, context);
2598 }
2599 #endif
2600 // file exists and is not in dyld shared cache, so open it
2601 return loadPhase5open(path, context, stat_buf, exceptions);
2602 }
2603 #endif // __MAC_OS_X_VERSION_MIN_REQUIRED
2604
2605
2606
2607 #if __IPHONE_OS_VERSION_MIN_REQUIRED
2608 static ImageLoader* loadPhase5stat(const char* path, const LoadContext& context, struct stat* stat_buf,
2609 int* statErrNo, bool* imageFound, std::vector<const char*>* exceptions)
2610 {
2611 ImageLoader* image = NULL;
2612 *imageFound = false;
2613 *statErrNo = 0;
2614 if ( my_stat(path, stat_buf) == 0 ) {
2615 // in case image was renamed or found via symlinks, check for inode match
2616 image = findLoadedImage(*stat_buf);
2617 if ( image != NULL ) {
2618 *imageFound = true;
2619 return image;
2620 }
2621 // do nothing if not already loaded and if RTLD_NOLOAD
2622 if ( context.dontLoad ) {
2623 *imageFound = true;
2624 return NULL;
2625 }
2626 image = loadPhase5open(path, context, *stat_buf, exceptions);
2627 if ( image != NULL ) {
2628 *imageFound = true;
2629 return image;
2630 }
2631 }
2632 else {
2633 *statErrNo = errno;
2634 }
2635 return NULL;
2636 }
2637
2638 // try to open file
2639 static ImageLoader* loadPhase5load(const char* path, const char* orgPath, const LoadContext& context, std::vector<const char*>* exceptions)
2640 {
2641 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
2642 struct stat stat_buf;
2643 bool imageFound;
2644 int statErrNo;
2645 ImageLoader* image;
2646 #if DYLD_SHARED_CACHE_SUPPORT
2647 if ( sDylibsOverrideCache ) {
2648 // flag is set that allows installed framework roots to override dyld shared cache
2649 image = loadPhase5stat(path, context, &stat_buf, &statErrNo, &imageFound, exceptions);
2650 if ( imageFound )
2651 return image;
2652 }
2653 // see if this image is in shared cache
2654 const macho_header* mhInCache;
2655 const char* pathInCache;
2656 long slideInCache;
2657 if ( findInSharedCacheImage(path, true, NULL, &mhInCache, &pathInCache, &slideInCache) ) {
2658 // see if this image in the cache was already loaded via a different path
2659 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); ++it) {
2660 ImageLoader* anImage = *it;
2661 if ( (const macho_header*)anImage->machHeader() == mhInCache )
2662 return anImage;
2663 }
2664 // do nothing if not already loaded and if RTLD_NOLOAD
2665 if ( context.dontLoad )
2666 return NULL;
2667 // nope, so instantiate a new image from dyld shared cache
2668 // <rdar://problem/7014995> zero out stat buffer so mtime, etc are zero for items from the shared cache
2669 bzero(&stat_buf, sizeof(stat_buf));
2670 image = ImageLoaderMachO::instantiateFromCache(mhInCache, pathInCache, slideInCache, stat_buf, gLinkContext);
2671 return checkandAddImage(image, context);
2672 }
2673
2674 if ( !sDylibsOverrideCache ) {
2675 // flag is not set, and not in cache to try opening it
2676 image = loadPhase5stat(path, context, &stat_buf, &statErrNo, &imageFound, exceptions);
2677 if ( imageFound )
2678 return image;
2679 }
2680 #else
2681 image = loadPhase5stat(path, context, &stat_buf, &statErrNo, &imageFound, exceptions);
2682 if ( imageFound )
2683 return image;
2684 #endif
2685 // just return NULL if file not found, but record any other errors
2686 if ( (statErrNo != ENOENT) && (statErrNo != 0) ) {
2687 exceptions->push_back(dyld::mkstringf("%s: stat() failed with errno=%d", path, statErrNo));
2688 }
2689 return NULL;
2690 }
2691 #endif // __IPHONE_OS_VERSION_MIN_REQUIRED
2692
2693
2694 // look for path match with existing loaded images
2695 static ImageLoader* loadPhase5check(const char* path, const char* orgPath, const LoadContext& context)
2696 {
2697 //dyld::log("%s(%s, %s)\n", __func__ , path, orgPath);
2698 // search path against load-path and install-path of all already loaded images
2699 uint32_t hash = ImageLoader::hash(path);
2700 //dyld::log("check() hash=%d, path=%s\n", hash, path);
2701 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
2702 ImageLoader* anImage = *it;
2703 // check hash first to cut down on strcmp calls
2704 //dyld::log(" check() hash=%d, path=%s\n", anImage->getPathHash(), anImage->getPath());
2705 if ( anImage->getPathHash() == hash ) {
2706 if ( strcmp(path, anImage->getPath()) == 0 ) {
2707 // if we are looking for a dylib don't return something else
2708 if ( !context.mustBeDylib || anImage->isDylib() )
2709 return anImage;
2710 }
2711 }
2712 if ( context.matchByInstallName || anImage->matchInstallPath() ) {
2713 const char* installPath = anImage->getInstallPath();
2714 if ( installPath != NULL) {
2715 if ( strcmp(path, installPath) == 0 ) {
2716 // if we are looking for a dylib don't return something else
2717 if ( !context.mustBeDylib || anImage->isDylib() )
2718 return anImage;
2719 }
2720 }
2721 }
2722 // an install name starting with @rpath should match by install name, not just real path
2723 if ( (orgPath[0] == '@') && (strncmp(orgPath, "@rpath/", 7) == 0) ) {
2724 const char* installPath = anImage->getInstallPath();
2725 if ( installPath != NULL) {
2726 if ( !context.mustBeDylib || anImage->isDylib() ) {
2727 if ( strcmp(orgPath, installPath) == 0 )
2728 return anImage;
2729 }
2730 }
2731 }
2732 }
2733
2734 //dyld::log("%s(%s) => NULL\n", __func__, path);
2735 return NULL;
2736 }
2737
2738
2739 // open or check existing
2740 static ImageLoader* loadPhase5(const char* path, const char* orgPath, const LoadContext& context, std::vector<const char*>* exceptions)
2741 {
2742 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
2743
2744 // check for specific dylib overrides
2745 for (std::vector<DylibOverride>::iterator it = sDylibOverrides.begin(); it != sDylibOverrides.end(); ++it) {
2746 if ( strcmp(it->installName, path) == 0 ) {
2747 path = it->override;
2748 break;
2749 }
2750 }
2751
2752 if ( exceptions != NULL )
2753 return loadPhase5load(path, orgPath, context, exceptions);
2754 else
2755 return loadPhase5check(path, orgPath, context);
2756 }
2757
2758 // try with and without image suffix
2759 static ImageLoader* loadPhase4(const char* path, const char* orgPath, const LoadContext& context, std::vector<const char*>* exceptions)
2760 {
2761 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
2762 ImageLoader* image = NULL;
2763 if ( gLinkContext.imageSuffix != NULL ) {
2764 char pathWithSuffix[strlen(path)+strlen( gLinkContext.imageSuffix)+2];
2765 ImageLoader::addSuffix(path, gLinkContext.imageSuffix, pathWithSuffix);
2766 image = loadPhase5(pathWithSuffix, orgPath, context, exceptions);
2767 }
2768 if ( image == NULL )
2769 image = loadPhase5(path, orgPath, context, exceptions);
2770 return image;
2771 }
2772
2773 static ImageLoader* loadPhase2(const char* path, const char* orgPath, const LoadContext& context,
2774 const char* const frameworkPaths[], const char* const libraryPaths[],
2775 std::vector<const char*>* exceptions); // forward reference
2776
2777
2778 // expand @ variables
2779 static ImageLoader* loadPhase3(const char* path, const char* orgPath, const LoadContext& context, std::vector<const char*>* exceptions)
2780 {
2781 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
2782 ImageLoader* image = NULL;
2783 if ( strncmp(path, "@executable_path/", 17) == 0 ) {
2784 // executable_path cannot be in used in any binary in a setuid process rdar://problem/4589305
2785 if ( sProcessIsRestricted && !sProcessRequiresLibraryValidation )
2786 throwf("unsafe use of @executable_path in %s with restricted binary", context.origin);
2787 // handle @executable_path path prefix
2788 const char* executablePath = sExecPath;
2789 char newPath[strlen(executablePath) + strlen(path)];
2790 strcpy(newPath, executablePath);
2791 char* addPoint = strrchr(newPath,'/');
2792 if ( addPoint != NULL )
2793 strcpy(&addPoint[1], &path[17]);
2794 else
2795 strcpy(newPath, &path[17]);
2796 image = loadPhase4(newPath, orgPath, context, exceptions);
2797 if ( image != NULL )
2798 return image;
2799
2800 // perhaps main executable path is a sym link, find realpath and retry
2801 char resolvedPath[PATH_MAX];
2802 if ( realpath(sExecPath, resolvedPath) != NULL ) {
2803 char newRealPath[strlen(resolvedPath) + strlen(path)];
2804 strcpy(newRealPath, resolvedPath);
2805 char* addPoint = strrchr(newRealPath,'/');
2806 if ( addPoint != NULL )
2807 strcpy(&addPoint[1], &path[17]);
2808 else
2809 strcpy(newRealPath, &path[17]);
2810 image = loadPhase4(newRealPath, orgPath, context, exceptions);
2811 if ( image != NULL )
2812 return image;
2813 }
2814 }
2815 else if ( (strncmp(path, "@loader_path/", 13) == 0) && (context.origin != NULL) ) {
2816 // @loader_path cannot be used from the main executable of a setuid process rdar://problem/4589305
2817 if ( sProcessIsRestricted && (strcmp(context.origin, sExecPath) == 0) && !sProcessRequiresLibraryValidation )
2818 throwf("unsafe use of @loader_path in %s with restricted binary", context.origin);
2819 // handle @loader_path path prefix
2820 char newPath[strlen(context.origin) + strlen(path)];
2821 strcpy(newPath, context.origin);
2822 char* addPoint = strrchr(newPath,'/');
2823 if ( addPoint != NULL )
2824 strcpy(&addPoint[1], &path[13]);
2825 else
2826 strcpy(newPath, &path[13]);
2827 image = loadPhase4(newPath, orgPath, context, exceptions);
2828 if ( image != NULL )
2829 return image;
2830
2831 // perhaps loader path is a sym link, find realpath and retry
2832 char resolvedPath[PATH_MAX];
2833 if ( realpath(context.origin, resolvedPath) != NULL ) {
2834 char newRealPath[strlen(resolvedPath) + strlen(path)];
2835 strcpy(newRealPath, resolvedPath);
2836 char* addPoint = strrchr(newRealPath,'/');
2837 if ( addPoint != NULL )
2838 strcpy(&addPoint[1], &path[13]);
2839 else
2840 strcpy(newRealPath, &path[13]);
2841 image = loadPhase4(newRealPath, orgPath, context, exceptions);
2842 if ( image != NULL )
2843 return image;
2844 }
2845 }
2846 else if ( context.implicitRPath || (strncmp(path, "@rpath/", 7) == 0) ) {
2847 const char* trailingPath = (strncmp(path, "@rpath/", 7) == 0) ? &path[7] : path;
2848 // substitute @rpath with all -rpath paths up the load chain
2849 for(const ImageLoader::RPathChain* rp=context.rpath; rp != NULL; rp=rp->next) {
2850 if (rp->paths != NULL ) {
2851 for(std::vector<const char*>::iterator it=rp->paths->begin(); it != rp->paths->end(); ++it) {
2852 const char* anRPath = *it;
2853 char newPath[strlen(anRPath) + strlen(trailingPath)+2];
2854 strcpy(newPath, anRPath);
2855 strcat(newPath, "/");
2856 strcat(newPath, trailingPath);
2857 image = loadPhase4(newPath, orgPath, context, exceptions);
2858 if ( gLinkContext.verboseRPaths && (exceptions != NULL) ) {
2859 if ( image != NULL )
2860 dyld::log("RPATH successful expansion of %s to: %s\n", orgPath, newPath);
2861 else
2862 dyld::log("RPATH failed to expanding %s to: %s\n", orgPath, newPath);
2863 }
2864 if ( image != NULL )
2865 return image;
2866 }
2867 }
2868 }
2869
2870 // substitute @rpath with LD_LIBRARY_PATH
2871 if ( sEnv.LD_LIBRARY_PATH != NULL ) {
2872 image = loadPhase2(trailingPath, orgPath, context, NULL, sEnv.LD_LIBRARY_PATH, exceptions);
2873 if ( image != NULL )
2874 return image;
2875 }
2876
2877 // if this is the "open" pass, don't try to open @rpath/... as a relative path
2878 if ( (exceptions != NULL) && (trailingPath != path) )
2879 return NULL;
2880 }
2881 else if (sProcessIsRestricted && (path[0] != '/' ) && !sProcessRequiresLibraryValidation) {
2882 throwf("unsafe use of relative rpath %s in %s with restricted binary", path, context.origin);
2883 }
2884
2885 return loadPhase4(path, orgPath, context, exceptions);
2886 }
2887
2888
2889 // try search paths
2890 static ImageLoader* loadPhase2(const char* path, const char* orgPath, const LoadContext& context,
2891 const char* const frameworkPaths[], const char* const libraryPaths[],
2892 std::vector<const char*>* exceptions)
2893 {
2894 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
2895 ImageLoader* image = NULL;
2896 const char* frameworkPartialPath = getFrameworkPartialPath(path);
2897 if ( frameworkPaths != NULL ) {
2898 if ( frameworkPartialPath != NULL ) {
2899 const size_t frameworkPartialPathLen = strlen(frameworkPartialPath);
2900 for(const char* const* fp = frameworkPaths; *fp != NULL; ++fp) {
2901 char npath[strlen(*fp)+frameworkPartialPathLen+8];
2902 strcpy(npath, *fp);
2903 strcat(npath, "/");
2904 strcat(npath, frameworkPartialPath);
2905 //dyld::log("dyld: fallback framework path used: %s() -> loadPhase4(\"%s\", ...)\n", __func__, npath);
2906 image = loadPhase4(npath, orgPath, context, exceptions);
2907 if ( image != NULL )
2908 return image;
2909 }
2910 }
2911 }
2912 // <rdar://problem/12649639> An executable with the same name as a framework & DYLD_LIBRARY_PATH pointing to it gets loaded twice
2913 // <rdar://problem/14160846> Some apps depend on frameworks being found via library paths
2914 if ( (libraryPaths != NULL) && ((frameworkPartialPath == NULL) || sFrameworksFoundAsDylibs) ) {
2915 const char* libraryLeafName = getLibraryLeafName(path);
2916 const size_t libraryLeafNameLen = strlen(libraryLeafName);
2917 for(const char* const* lp = libraryPaths; *lp != NULL; ++lp) {
2918 char libpath[strlen(*lp)+libraryLeafNameLen+8];
2919 strcpy(libpath, *lp);
2920 strcat(libpath, "/");
2921 strcat(libpath, libraryLeafName);
2922 //dyld::log("dyld: fallback library path used: %s() -> loadPhase4(\"%s\", ...)\n", __func__, libpath);
2923 image = loadPhase4(libpath, orgPath, context, exceptions);
2924 if ( image != NULL )
2925 return image;
2926 }
2927 }
2928 return NULL;
2929 }
2930
2931 // try search overrides and fallbacks
2932 static ImageLoader* loadPhase1(const char* path, const char* orgPath, const LoadContext& context, std::vector<const char*>* exceptions)
2933 {
2934 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
2935 ImageLoader* image = NULL;
2936
2937 // handle LD_LIBRARY_PATH environment variables that force searching
2938 if ( context.useLdLibraryPath && (sEnv.LD_LIBRARY_PATH != NULL) ) {
2939 image = loadPhase2(path, orgPath, context, NULL, sEnv.LD_LIBRARY_PATH, exceptions);
2940 if ( image != NULL )
2941 return image;
2942 }
2943
2944 // handle DYLD_ environment variables that force searching
2945 if ( context.useSearchPaths && ((sEnv.DYLD_FRAMEWORK_PATH != NULL) || (sEnv.DYLD_LIBRARY_PATH != NULL)) ) {
2946 image = loadPhase2(path, orgPath, context, sEnv.DYLD_FRAMEWORK_PATH, sEnv.DYLD_LIBRARY_PATH, exceptions);
2947 if ( image != NULL )
2948 return image;
2949 }
2950
2951 // try raw path
2952 image = loadPhase3(path, orgPath, context, exceptions);
2953 if ( image != NULL )
2954 return image;
2955
2956 // try fallback paths during second time (will open file)
2957 const char* const* fallbackLibraryPaths = sEnv.DYLD_FALLBACK_LIBRARY_PATH;
2958 if ( (fallbackLibraryPaths != NULL) && !context.useFallbackPaths )
2959 fallbackLibraryPaths = NULL;
2960 if ( !context.dontLoad && (exceptions != NULL) && ((sEnv.DYLD_FALLBACK_FRAMEWORK_PATH != NULL) || (fallbackLibraryPaths != NULL)) ) {
2961 image = loadPhase2(path, orgPath, context, sEnv.DYLD_FALLBACK_FRAMEWORK_PATH, fallbackLibraryPaths, exceptions);
2962 if ( image != NULL )
2963 return image;
2964 }
2965
2966 return NULL;
2967 }
2968
2969 // try root substitutions
2970 static ImageLoader* loadPhase0(const char* path, const char* orgPath, const LoadContext& context, std::vector<const char*>* exceptions)
2971 {
2972 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
2973
2974 // handle DYLD_ROOT_PATH which forces absolute paths to use a new root
2975 if ( (gLinkContext.rootPaths != NULL) && (path[0] == '/') ) {
2976 for(const char* const* rootPath = gLinkContext.rootPaths ; *rootPath != NULL; ++rootPath) {
2977 char newPath[strlen(*rootPath) + strlen(path)+2];
2978 strcpy(newPath, *rootPath);
2979 strcat(newPath, path);
2980 ImageLoader* image = loadPhase1(newPath, orgPath, context, exceptions);
2981 if ( image != NULL )
2982 return image;
2983 }
2984 }
2985
2986 // try raw path
2987 return loadPhase1(path, orgPath, context, exceptions);
2988 }
2989
2990 #if DYLD_SHARED_CACHE_SUPPORT
2991 static bool cacheablePath(const char* path) {
2992 if (strncmp(path, "/usr/lib/", 9) == 0)
2993 return true;
2994 if (strncmp(path, "/System/Library/", 16) == 0)
2995 return true;
2996 return false;
2997 }
2998 #endif
2999
3000 //
3001 // Given all the DYLD_ environment variables, the general case for loading libraries
3002 // is that any given path expands into a list of possible locations to load. We
3003 // also must take care to ensure two copies of the "same" library are never loaded.
3004 //
3005 // The algorithm used here is that there is a separate function for each "phase" of the
3006 // path expansion. Each phase function calls the next phase with each possible expansion
3007 // of that phase. The result is the last phase is called with all possible paths.
3008 //
3009 // To catch duplicates the algorithm is run twice. The first time, the last phase checks
3010 // the path against all loaded images. The second time, the last phase calls open() on
3011 // the path. Either time, if an image is found, the phases all unwind without checking
3012 // for other paths.
3013 //
3014 ImageLoader* load(const char* path, const LoadContext& context)
3015 {
3016 CRSetCrashLogMessage2(path);
3017 const char* orgPath = path;
3018
3019 //dyld::log("%s(%s)\n", __func__ , path);
3020 char realPath[PATH_MAX];
3021 // when DYLD_IMAGE_SUFFIX is in used, do a realpath(), otherwise a load of "Foo.framework/Foo" will not match
3022 if ( context.useSearchPaths && ( gLinkContext.imageSuffix != NULL) ) {
3023 if ( realpath(path, realPath) != NULL )
3024 path = realPath;
3025 }
3026
3027 // try all path permutations and check against existing loaded images
3028 ImageLoader* image = loadPhase0(path, orgPath, context, NULL);
3029 if ( image != NULL ) {
3030 CRSetCrashLogMessage2(NULL);
3031 return image;
3032 }
3033
3034 // try all path permutations and try open() until first success
3035 std::vector<const char*> exceptions;
3036 image = loadPhase0(path, orgPath, context, &exceptions);
3037 #if __IPHONE_OS_VERSION_MIN_REQUIRED && DYLD_SHARED_CACHE_SUPPORT && !TARGET_IPHONE_SIMULATOR
3038 // <rdar://problem/16704628> support symlinks on disk to a path in dyld shared cache
3039 if ( (image == NULL) && cacheablePath(path) && !context.dontLoad ) {
3040 char resolvedPath[PATH_MAX];
3041 realpath(path, resolvedPath);
3042 int myerr = errno;
3043 // If realpath() resolves to a path which does not exist on disk, errno is set to ENOENT
3044 if ( (myerr == ENOENT) || (myerr == 0) )
3045 {
3046 // see if this image is in shared cache
3047 const macho_header* mhInCache;
3048 const char* pathInCache;
3049 long slideInCache;
3050 if ( findInSharedCacheImage(resolvedPath, false, NULL, &mhInCache, &pathInCache, &slideInCache) ) {
3051 struct stat stat_buf;
3052 bzero(&stat_buf, sizeof(stat_buf));
3053 try {
3054 image = ImageLoaderMachO::instantiateFromCache(mhInCache, pathInCache, slideInCache, stat_buf, gLinkContext);
3055 image = checkandAddImage(image, context);
3056 }
3057 catch (...) {
3058 image = NULL;
3059 }
3060 }
3061 }
3062 }
3063 #endif
3064 CRSetCrashLogMessage2(NULL);
3065 if ( image != NULL ) {
3066 // <rdar://problem/6916014> leak in dyld during dlopen when using DYLD_ variables
3067 for (std::vector<const char*>::iterator it = exceptions.begin(); it != exceptions.end(); ++it) {
3068 free((void*)(*it));
3069 }
3070 #if DYLD_SHARED_CACHE_SUPPORT
3071 // if loaded image is not from cache, but original path is in cache
3072 // set gSharedCacheOverridden flag to disable some ObjC optimizations
3073 if ( !gSharedCacheOverridden && !image->inSharedCache() && image->isDylib() && cacheablePath(path) && inSharedCache(path) ) {
3074 gSharedCacheOverridden = true;
3075 }
3076 #endif
3077 return image;
3078 }
3079 else if ( exceptions.size() == 0 ) {
3080 if ( context.dontLoad ) {
3081 return NULL;
3082 }
3083 else
3084 throw "image not found";
3085 }
3086 else {
3087 const char* msgStart = "no suitable image found. Did find:";
3088 const char* delim = "\n\t";
3089 size_t allsizes = strlen(msgStart)+8;
3090 for (size_t i=0; i < exceptions.size(); ++i)
3091 allsizes += (strlen(exceptions[i]) + strlen(delim));
3092 char* fullMsg = new char[allsizes];
3093 strcpy(fullMsg, msgStart);
3094 for (size_t i=0; i < exceptions.size(); ++i) {
3095 strcat(fullMsg, delim);
3096 strcat(fullMsg, exceptions[i]);
3097 free((void*)exceptions[i]);
3098 }
3099 throw (const char*)fullMsg;
3100 }
3101 }
3102
3103
3104
3105 #if DYLD_SHARED_CACHE_SUPPORT
3106
3107
3108
3109 #if __i386__
3110 #define ARCH_NAME "i386"
3111 #define ARCH_CACHE_MAGIC "dyld_v1 i386"
3112 #elif __x86_64__
3113 #define ARCH_NAME "x86_64"
3114 #define ARCH_CACHE_MAGIC "dyld_v1 x86_64"
3115 #define ARCH_NAME_H "x86_64h"
3116 #define ARCH_CACHE_MAGIC_H "dyld_v1 x86_64h"
3117 #elif __ARM_ARCH_5TEJ__
3118 #define ARCH_NAME "armv5"
3119 #define ARCH_CACHE_MAGIC "dyld_v1 armv5"
3120 #elif __ARM_ARCH_6K__
3121 #define ARCH_NAME "armv6"
3122 #define ARCH_CACHE_MAGIC "dyld_v1 armv6"
3123 #elif __ARM_ARCH_7F__
3124 #define ARCH_NAME "armv7f"
3125 #define ARCH_CACHE_MAGIC "dyld_v1 armv7f"
3126 #elif __ARM_ARCH_7K__
3127 #define ARCH_NAME "armv7k"
3128 #define ARCH_CACHE_MAGIC "dyld_v1 armv7k"
3129 #elif __ARM_ARCH_7A__
3130 #define ARCH_NAME "armv7"
3131 #define ARCH_CACHE_MAGIC "dyld_v1 armv7"
3132 #elif __ARM_ARCH_7S__
3133 #define ARCH_NAME "armv7s"
3134 #define ARCH_CACHE_MAGIC "dyld_v1 armv7s"
3135 #elif __arm64__
3136 #define ARCH_NAME "arm64"
3137 #define ARCH_CACHE_MAGIC "dyld_v1 arm64"
3138 #endif
3139
3140
3141 static int __attribute__((noinline)) _shared_region_check_np(uint64_t* start_address)
3142 {
3143 if ( gLinkContext.sharedRegionMode == ImageLoader::kUseSharedRegion )
3144 return syscall(294, start_address);
3145 return -1;
3146 }
3147
3148
3149 static int __attribute__((noinline)) _shared_region_map_and_slide_np(int fd, uint32_t count, const shared_file_mapping_np mappings[],
3150 int codeSignatureMappingIndex, long slide, void* slideInfo, unsigned long slideInfoSize)
3151 {
3152 // register code signature blob for whole dyld cache
3153 if ( codeSignatureMappingIndex != -1 ) {
3154 fsignatures_t siginfo;
3155 siginfo.fs_file_start = 0; // cache always starts at beginning of file
3156 siginfo.fs_blob_start = (void*)mappings[codeSignatureMappingIndex].sfm_file_offset;
3157 siginfo.fs_blob_size = mappings[codeSignatureMappingIndex].sfm_size;
3158 int result = fcntl(fd, F_ADDFILESIGS, &siginfo);
3159 // <rdar://problem/12891874> don't warn in chrooted case because mapping syscall is about to fail too
3160 if ( (result == -1) && gLinkContext.verboseMapping )
3161 dyld::log("dyld: code signature registration for shared cache failed with errno=%d\n", errno);
3162 }
3163
3164 if ( gLinkContext.sharedRegionMode == ImageLoader::kUseSharedRegion ) {
3165 return syscall(438, fd, count, mappings, slide, slideInfo, slideInfoSize);
3166 }
3167
3168 // remove the shared region sub-map
3169 vm_deallocate(mach_task_self(), (vm_address_t)SHARED_REGION_BASE, SHARED_REGION_SIZE);
3170
3171 // notify gdb or other lurkers that this process is no longer using the shared region
3172 dyld::gProcessInfo->processDetachedFromSharedRegion = true;
3173
3174 // map cache just for this process with mmap()
3175 const shared_file_mapping_np* const start = mappings;
3176 const shared_file_mapping_np* const end = &mappings[count];
3177 for (const shared_file_mapping_np* p = start; p < end; ++p ) {
3178 void* mmapAddress = (void*)(uintptr_t)(p->sfm_address);
3179 size_t size = p->sfm_size;
3180 //dyld::log("dyld: mapping address %p with size 0x%08lX\n", mmapAddress, size);
3181 int protection = 0;
3182 if ( p->sfm_init_prot & VM_PROT_EXECUTE )
3183 protection |= PROT_EXEC;
3184 if ( p->sfm_init_prot & VM_PROT_READ )
3185 protection |= PROT_READ;
3186 if ( p->sfm_init_prot & VM_PROT_WRITE )
3187 protection |= PROT_WRITE;
3188 off_t offset = p->sfm_file_offset;
3189 if ( mmap(mmapAddress, size, protection, MAP_FIXED | MAP_PRIVATE, fd, offset) != mmapAddress ) {
3190 // failed to map some chunk of this shared cache file
3191 // clear shared region
3192 vm_deallocate(mach_task_self(), (vm_address_t)SHARED_REGION_BASE, SHARED_REGION_SIZE);
3193 // go back to not using shared region at all
3194 gLinkContext.sharedRegionMode = ImageLoader::kDontUseSharedRegion;
3195 if ( gLinkContext.verboseMapping ) {
3196 dyld::log("dyld: shared cached region cannot be mapped at address %p with size 0x%08lX\n",
3197 mmapAddress, size);
3198 }
3199 // return failure
3200 return -1;
3201 }
3202 }
3203
3204 // update all __DATA pages with slide info
3205 if ( slide != 0 ) {
3206 const uintptr_t dataPagesStart = mappings[1].sfm_address;
3207 const dyld_cache_slide_info* slideInfoHeader = (dyld_cache_slide_info*)slideInfo;
3208 const uint16_t* toc = (uint16_t*)((long)(slideInfoHeader) + slideInfoHeader->toc_offset);
3209 const uint8_t* entries = (uint8_t*)((long)(slideInfoHeader) + slideInfoHeader->entries_offset);
3210 for(uint32_t i=0; i < slideInfoHeader->toc_count; ++i) {
3211 const uint8_t* entry = &entries[toc[i]*slideInfoHeader->entries_size];
3212 const uint8_t* page = (uint8_t*)(long)(dataPagesStart + (4096*i));
3213 //dyld::log("page=%p toc[%d]=%d entries=%p\n", page, i, toc[i], entry);
3214 for(int j=0; j < 128; ++j) {
3215 uint8_t b = entry[j];
3216 //dyld::log(" entry[%d] = 0x%02X\n", j, b);
3217 if ( b != 0 ) {
3218 for(int k=0; k < 8; ++k) {
3219 if ( b & (1<<k) ) {
3220 uintptr_t* p = (uintptr_t*)(page + j*8*4 + k*4);
3221 uintptr_t value = *p;
3222 //dyld::log(" *%p was 0x%lX will be 0x%lX\n", p, value, value+sSharedCacheSlide);
3223 *p = value + slide;
3224 }
3225 }
3226 }
3227 }
3228 }
3229 }
3230
3231 // succesfully mapped shared cache for just this process
3232 gLinkContext.sharedRegionMode = ImageLoader::kUsePrivateSharedRegion;
3233
3234 return 0;
3235 }
3236
3237
3238 const void* imMemorySharedCacheHeader()
3239 {
3240 return sSharedCache;
3241 }
3242
3243 const char* getStandardSharedCacheFilePath()
3244 {
3245 #if __IPHONE_OS_VERSION_MIN_REQUIRED
3246 return IPHONE_DYLD_SHARED_CACHE_DIR DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME;
3247 #else
3248 #if __x86_64__
3249 if ( sHaswell ) {
3250 const char* path2 = MACOSX_DYLD_SHARED_CACHE_DIR DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME_H;
3251 struct stat statBuf;
3252 if ( my_stat(path2, &statBuf) == 0 )
3253 return path2;
3254 }
3255 #endif
3256 return MACOSX_DYLD_SHARED_CACHE_DIR DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME;
3257 #endif
3258 }
3259
3260 int openSharedCacheFile()
3261 {
3262 char path[MAXPATHLEN];
3263 strlcpy(path, sSharedCacheDir, MAXPATHLEN);
3264 strlcat(path, "/", MAXPATHLEN);
3265 #if __x86_64__
3266 if ( sHaswell ) {
3267 strlcat(path, DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME_H, MAXPATHLEN);
3268 int fd = my_open(path, O_RDONLY, 0);
3269 if ( fd != -1 ) {
3270 if ( gLinkContext.verboseMapping )
3271 dyld::log("dyld: Mapping%s shared cache from %s\n", (gLinkContext.sharedRegionMode == ImageLoader::kUsePrivateSharedRegion) ? " private": "", path);
3272 return fd;
3273 }
3274 strlcpy(path, sSharedCacheDir, MAXPATHLEN);
3275 }
3276 #endif
3277 strlcat(path, DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME, MAXPATHLEN);
3278 if ( gLinkContext.verboseMapping )
3279 dyld::log("dyld: Mapping%s shared cache from %s\n", (gLinkContext.sharedRegionMode == ImageLoader::kUsePrivateSharedRegion) ? " private": "", path);
3280 return my_open(path, O_RDONLY, 0);
3281 }
3282
3283
3284 static void getCacheBounds(uint32_t mappingsCount, const shared_file_mapping_np mappings[], uint64_t& lowAddress, uint64_t& highAddress)
3285 {
3286 lowAddress = 0;
3287 highAddress = 0;
3288 for(uint32_t i=0; i < mappingsCount; ++i) {
3289 if ( lowAddress == 0 ) {
3290 lowAddress = mappings[i].sfm_address;
3291 highAddress = mappings[i].sfm_address + mappings[i].sfm_size;
3292 }
3293 else {
3294 if ( mappings[i].sfm_address < lowAddress )
3295 lowAddress = mappings[i].sfm_address;
3296 if ( (mappings[i].sfm_address + mappings[i].sfm_size) > highAddress )
3297 highAddress = mappings[i].sfm_address + mappings[i].sfm_size;
3298 }
3299 }
3300 }
3301
3302 static long pickCacheSlide(uint32_t mappingsCount, shared_file_mapping_np mappings[])
3303 {
3304 #if __x86_64__
3305 // x86_64 has a two memory regions:
3306 // 256MB at 0x00007FFF70000000
3307 // 1024MB at 0x00007FFF80000000
3308 // Some old shared caches have r/w region after rx region, so all regions slide within 1GB range
3309 // Newer shared caches have r/w region based at 0x7FFF70000000 and r/o regions at 0x7FFF80000000, so each part has max slide
3310 if ( (mappingsCount >= 3) && (mappings[1].sfm_init_prot == (VM_PROT_READ|VM_PROT_WRITE)) && (mappings[1].sfm_address == 0x00007FFF70000000) ) {
3311 const uint64_t rwSize = mappings[1].sfm_size;
3312 const uint64_t rwSlop = 0x10000000ULL - rwSize;
3313 const uint64_t roSize = (mappings[2].sfm_address + mappings[2].sfm_size) - mappings[0].sfm_address;
3314 const uint64_t roSlop = 0x40000000ULL - roSize;
3315 const uint64_t space = (rwSlop < roSlop) ? rwSlop : roSlop;
3316
3317 // choose new random slide
3318 long slide = (arc4random() % space) & (-4096);
3319 //dyld::log("rwSlop=0x%0llX, roSlop=0x%0llX\n", rwSlop, roSlop);
3320 //dyld::log("space=0x%0llX, slide=0x%0lX\n", space, slide);
3321
3322 // update mappings
3323 for(uint32_t i=0; i < mappingsCount; ++i) {
3324 mappings[i].sfm_address += slide;
3325 }
3326
3327 return slide;
3328 }
3329 // else fall through to handle old style cache
3330 #endif
3331 // get bounds of cache
3332 uint64_t lowAddress;
3333 uint64_t highAddress;
3334 getCacheBounds(mappingsCount, mappings, lowAddress, highAddress);
3335
3336 // find slop space
3337 const uint64_t space = (SHARED_REGION_BASE + SHARED_REGION_SIZE) - highAddress;
3338
3339 // choose new random slide
3340 long slide = dyld_page_trunc(arc4random() % space);
3341 //dyld::log("slideSpace=0x%0llX\n", space);
3342 //dyld::log("slide=0x%0lX\n", slide);
3343
3344 // update mappings
3345 for(uint32_t i=0; i < mappingsCount; ++i) {
3346 mappings[i].sfm_address += slide;
3347 }
3348
3349 return slide;
3350 }
3351
3352 static void mapSharedCache()
3353 {
3354 uint64_t cacheBaseAddress = 0;
3355 // quick check if a cache is already mapped into shared region
3356 if ( _shared_region_check_np(&cacheBaseAddress) == 0 ) {
3357 sSharedCache = (dyld_cache_header*)cacheBaseAddress;
3358 // if we don't understand the currently mapped shared cache, then ignore
3359 #if __x86_64__
3360 const char* magic = (sHaswell ? ARCH_CACHE_MAGIC_H : ARCH_CACHE_MAGIC);
3361 #else
3362 const char* magic = ARCH_CACHE_MAGIC;
3363 #endif
3364 if ( strcmp(sSharedCache->magic, magic) != 0 ) {
3365 sSharedCache = NULL;
3366 if ( gLinkContext.verboseMapping ) {
3367 dyld::log("dyld: existing shared cached in memory is not compatible\n");
3368 return;
3369 }
3370 }
3371 // check if cache file is slidable
3372 const dyld_cache_header* header = sSharedCache;
3373 if ( (header->mappingOffset >= 0x48) && (header->slideInfoSize != 0) ) {
3374 // solve for slide by comparing loaded address to address of first region
3375 const uint8_t* loadedAddress = (uint8_t*)sSharedCache;
3376 const dyld_cache_mapping_info* const mappings = (dyld_cache_mapping_info*)(loadedAddress+header->mappingOffset);
3377 const uint8_t* preferedLoadAddress = (uint8_t*)(long)(mappings[0].address);
3378 sSharedCacheSlide = loadedAddress - preferedLoadAddress;
3379 dyld::gProcessInfo->sharedCacheSlide = sSharedCacheSlide;
3380 //dyld::log("sSharedCacheSlide=0x%08lX, loadedAddress=%p, preferedLoadAddress=%p\n", sSharedCacheSlide, loadedAddress, preferedLoadAddress);
3381 }
3382 // if cache has a uuid, copy it
3383 if ( header->mappingOffset >= 0x68 ) {
3384 memcpy(dyld::gProcessInfo->sharedCacheUUID, header->uuid, 16);
3385 }
3386 // verbose logging
3387 if ( gLinkContext.verboseMapping ) {
3388 dyld::log("dyld: re-using existing shared cache mapping\n");
3389 }
3390 }
3391 else {
3392 #if __i386__ || __x86_64__
3393 // <rdar://problem/5925940> Safe Boot should disable dyld shared cache
3394 // if we are in safe-boot mode and the cache was not made during this boot cycle,
3395 // delete the cache file
3396 uint32_t safeBootValue = 0;
3397 size_t safeBootValueSize = sizeof(safeBootValue);
3398 if ( (sysctlbyname("kern.safeboot", &safeBootValue, &safeBootValueSize, NULL, 0) == 0) && (safeBootValue != 0) ) {
3399 // user booted machine in safe-boot mode
3400 struct stat dyldCacheStatInfo;
3401 // Don't use custom DYLD_SHARED_CACHE_DIR if provided, use standard path
3402 if ( my_stat(MACOSX_DYLD_SHARED_CACHE_DIR DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME, &dyldCacheStatInfo) == 0 ) {
3403 struct timeval bootTimeValue;
3404 size_t bootTimeValueSize = sizeof(bootTimeValue);
3405 if ( (sysctlbyname("kern.boottime", &bootTimeValue, &bootTimeValueSize, NULL, 0) == 0) && (bootTimeValue.tv_sec != 0) ) {
3406 // if the cache file was created before this boot, then throw it away and let it rebuild itself
3407 if ( dyldCacheStatInfo.st_mtime < bootTimeValue.tv_sec ) {
3408 ::unlink(MACOSX_DYLD_SHARED_CACHE_DIR DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME);
3409 gLinkContext.sharedRegionMode = ImageLoader::kDontUseSharedRegion;
3410 return;
3411 }
3412 }
3413 }
3414 }
3415 #endif
3416 // map in shared cache to shared region
3417 int fd = openSharedCacheFile();
3418 if ( fd != -1 ) {
3419 uint8_t firstPages[8192];
3420 if ( ::read(fd, firstPages, 8192) == 8192 ) {
3421 dyld_cache_header* header = (dyld_cache_header*)firstPages;
3422 #if __x86_64__
3423 const char* magic = (sHaswell ? ARCH_CACHE_MAGIC_H : ARCH_CACHE_MAGIC);
3424 #else
3425 const char* magic = ARCH_CACHE_MAGIC;
3426 #endif
3427 if ( strcmp(header->magic, magic) == 0 ) {
3428 const dyld_cache_mapping_info* const fileMappingsStart = (dyld_cache_mapping_info*)&firstPages[header->mappingOffset];
3429 const dyld_cache_mapping_info* const fileMappingsEnd = &fileMappingsStart[header->mappingCount];
3430 shared_file_mapping_np mappings[header->mappingCount+1]; // add room for code-sig
3431 unsigned int mappingCount = header->mappingCount;
3432 int codeSignatureMappingIndex = -1;
3433 int readWriteMappingIndex = -1;
3434 int readOnlyMappingIndex = -1;
3435 // validate that the cache file has not been truncated
3436 bool goodCache = false;
3437 struct stat stat_buf;
3438 if ( fstat(fd, &stat_buf) == 0 ) {
3439 goodCache = true;
3440 int i=0;
3441 for (const dyld_cache_mapping_info* p = fileMappingsStart; p < fileMappingsEnd; ++p, ++i) {
3442 mappings[i].sfm_address = p->address;
3443 mappings[i].sfm_size = p->size;
3444 mappings[i].sfm_file_offset = p->fileOffset;
3445 mappings[i].sfm_max_prot = p->maxProt;
3446 mappings[i].sfm_init_prot = p->initProt;
3447 // rdar://problem/5694507 old update_dyld_shared_cache tool could make a cache file
3448 // that is not page aligned, but otherwise ok.
3449 if ( p->fileOffset+p->size > (uint64_t)(stat_buf.st_size+4095 & (-4096)) ) {
3450 dyld::log("dyld: shared cached file is corrupt: %s" DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME "\n", sSharedCacheDir);
3451 goodCache = false;
3452 }
3453 if ( (mappings[i].sfm_init_prot & (VM_PROT_READ|VM_PROT_WRITE)) == (VM_PROT_READ|VM_PROT_WRITE) ) {
3454 readWriteMappingIndex = i;
3455 }
3456 if ( mappings[i].sfm_init_prot == VM_PROT_READ ) {
3457 readOnlyMappingIndex = i;
3458 }
3459 }
3460 // if shared cache is code signed, add a mapping for the code signature
3461 uint64_t signatureSize = header->codeSignatureSize;
3462 // zero size in header means signature runs to end-of-file
3463 if ( signatureSize == 0 )
3464 signatureSize = stat_buf.st_size - header->codeSignatureOffset;
3465 if ( signatureSize != 0 ) {
3466 int linkeditMapping = mappingCount-1;
3467 codeSignatureMappingIndex = mappingCount++;
3468 mappings[codeSignatureMappingIndex].sfm_address = mappings[linkeditMapping].sfm_address + mappings[linkeditMapping].sfm_size;
3469 #if __arm__ || __arm64__
3470 mappings[codeSignatureMappingIndex].sfm_size = (signatureSize+16383) & (-16384);
3471 #else
3472 mappings[codeSignatureMappingIndex].sfm_size = (signatureSize+4095) & (-4096);
3473 #endif
3474 mappings[codeSignatureMappingIndex].sfm_file_offset = header->codeSignatureOffset;
3475 mappings[codeSignatureMappingIndex].sfm_max_prot = VM_PROT_READ;
3476 mappings[codeSignatureMappingIndex].sfm_init_prot = VM_PROT_READ;
3477 }
3478 }
3479 #if __MAC_OS_X_VERSION_MIN_REQUIRED
3480 // sanity check that /usr/lib/libSystem.B.dylib stat() info matches cache
3481 if ( header->imagesCount * sizeof(dyld_cache_image_info) + header->imagesOffset < 8192 ) {
3482 bool foundLibSystem = false;
3483 if ( my_stat("/usr/lib/libSystem.B.dylib", &stat_buf) == 0 ) {
3484 const dyld_cache_image_info* images = (dyld_cache_image_info*)&firstPages[header->imagesOffset];
3485 const dyld_cache_image_info* const imagesEnd = &images[header->imagesCount];
3486 for (const dyld_cache_image_info* p = images; p < imagesEnd; ++p) {
3487 if ( ((time_t)p->modTime == stat_buf.st_mtime) && ((ino_t)p->inode == stat_buf.st_ino) ) {
3488 foundLibSystem = true;
3489 break;
3490 }
3491 }
3492 }
3493 if ( !sSharedCacheIgnoreInodeAndTimeStamp && !foundLibSystem ) {
3494 dyld::log("dyld: shared cached file was built against a different libSystem.dylib, ignoring cache.\n"
3495 "to update dyld shared cache run: 'sudo update_dyld_shared_cache' then reboot.\n");
3496 goodCache = false;
3497 }
3498 }
3499 #endif
3500 #if __IPHONE_OS_VERSION_MIN_REQUIRED
3501 {
3502 uint64_t lowAddress;
3503 uint64_t highAddress;
3504 getCacheBounds(mappingCount, mappings, lowAddress, highAddress);
3505 if ( (highAddress-lowAddress) > SHARED_REGION_SIZE )
3506 throw "dyld shared cache is too big to fit in shared region";
3507 }
3508 #endif
3509
3510 if ( goodCache && (readWriteMappingIndex == -1) ) {
3511 dyld::log("dyld: shared cached file is missing read/write mapping: %s" DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME "\n", sSharedCacheDir);
3512 goodCache = false;
3513 }
3514 if ( goodCache && (readOnlyMappingIndex == -1) ) {
3515 dyld::log("dyld: shared cached file is missing read-only mapping: %s" DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME "\n", sSharedCacheDir);
3516 goodCache = false;
3517 }
3518 if ( goodCache ) {
3519 long cacheSlide = 0;
3520 void* slideInfo = NULL;
3521 uint64_t slideInfoSize = 0;
3522 // check if shared cache contains slid info
3523 if ( header->slideInfoSize != 0 ) {
3524 // <rdar://problem/8611968> don't slide shared cache if ASLR disabled (main executable didn't slide)
3525 if ( sMainExecutable->isPositionIndependentExecutable() && (sMainExecutable->getSlide() == 0) )
3526 cacheSlide = 0;
3527 else {
3528 // generate random slide amount
3529 cacheSlide = pickCacheSlide(mappingCount, mappings);
3530 slideInfo = (void*)(long)(mappings[readOnlyMappingIndex].sfm_address + (header->slideInfoOffset - mappings[readOnlyMappingIndex].sfm_file_offset));
3531 slideInfoSize = header->slideInfoSize;
3532 // add VM_PROT_SLIDE bit to __DATA area of cache
3533 mappings[readWriteMappingIndex].sfm_max_prot |= VM_PROT_SLIDE;
3534 mappings[readWriteMappingIndex].sfm_init_prot |= VM_PROT_SLIDE;
3535 }
3536 }
3537 if ( gLinkContext.verboseMapping ) {
3538 dyld::log("dyld: calling _shared_region_map_and_slide_np() with regions:\n");
3539 for (int i=0; i < mappingCount; ++i) {
3540 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);
3541 }
3542 }
3543 if (_shared_region_map_and_slide_np(fd, mappingCount, mappings, codeSignatureMappingIndex, cacheSlide, slideInfo, slideInfoSize) == 0) {
3544 // successfully mapped cache into shared region
3545 sSharedCache = (dyld_cache_header*)mappings[0].sfm_address;
3546 sSharedCacheSlide = cacheSlide;
3547 dyld::gProcessInfo->sharedCacheSlide = cacheSlide;
3548 //dyld::log("sSharedCache=%p sSharedCacheSlide=0x%08lX\n", sSharedCache, sSharedCacheSlide);
3549 // if cache has a uuid, copy it
3550 if ( header->mappingOffset >= 0x68 ) {
3551 memcpy(dyld::gProcessInfo->sharedCacheUUID, header->uuid, 16);
3552 }
3553 }
3554 else {
3555 #if __IPHONE_OS_VERSION_MIN_REQUIRED
3556 throw "dyld shared cache could not be mapped";
3557 #endif
3558 if ( gLinkContext.verboseMapping )
3559 dyld::log("dyld: shared cached file could not be mapped\n");
3560 }
3561 }
3562 }
3563 else {
3564 if ( gLinkContext.verboseMapping )
3565 dyld::log("dyld: shared cached file is invalid\n");
3566 }
3567 }
3568 else {
3569 if ( gLinkContext.verboseMapping )
3570 dyld::log("dyld: shared cached file cannot be read\n");
3571 }
3572 close(fd);
3573 }
3574 else {
3575 if ( gLinkContext.verboseMapping )
3576 dyld::log("dyld: shared cached file cannot be opened\n");
3577 }
3578 }
3579
3580 // remember if dyld loaded at same address as when cache built
3581 if ( sSharedCache != NULL ) {
3582 gLinkContext.dyldLoadedAtSameAddressNeededBySharedCache = ((uintptr_t)(sSharedCache->dyldBaseAddress) == (uintptr_t)&_mh_dylinker_header);
3583 }
3584
3585 // tell gdb where the shared cache is
3586 if ( sSharedCache != NULL ) {
3587 const dyld_cache_mapping_info* const start = (dyld_cache_mapping_info*)((uint8_t*)sSharedCache + sSharedCache->mappingOffset);
3588 dyld_shared_cache_ranges.sharedRegionsCount = sSharedCache->mappingCount;
3589 // only room to tell gdb about first four regions
3590 if ( dyld_shared_cache_ranges.sharedRegionsCount > 4 )
3591 dyld_shared_cache_ranges.sharedRegionsCount = 4;
3592 const dyld_cache_mapping_info* const end = &start[dyld_shared_cache_ranges.sharedRegionsCount];
3593 int index = 0;
3594 for (const dyld_cache_mapping_info* p = start; p < end; ++p, ++index ) {
3595 dyld_shared_cache_ranges.ranges[index].start = p->address+sSharedCacheSlide;
3596 dyld_shared_cache_ranges.ranges[index].length = p->size;
3597 if ( gLinkContext.verboseMapping ) {
3598 dyld::log(" 0x%08llX->0x%08llX %s%s%s init=%x, max=%x\n",
3599 p->address+sSharedCacheSlide, p->address+sSharedCacheSlide+p->size-1,
3600 ((p->initProt & VM_PROT_READ) ? "read " : ""),
3601 ((p->initProt & VM_PROT_WRITE) ? "write " : ""),
3602 ((p->initProt & VM_PROT_EXECUTE) ? "execute " : ""), p->initProt, p->maxProt);
3603 }
3604 #if __i386__
3605 // If a non-writable and executable region is found in the R/W shared region, then this is __IMPORT segments
3606 // This is an old cache. Make writable. dyld no longer supports turn W on and off as it binds
3607 if ( (p->initProt == (VM_PROT_READ|VM_PROT_EXECUTE)) && ((p->address & 0xF0000000) == 0xA0000000) ) {
3608 if ( p->size != 0 ) {
3609 vm_prot_t prot = VM_PROT_EXECUTE | PROT_READ | VM_PROT_WRITE;
3610 vm_protect(mach_task_self(), p->address, p->size, false, prot);
3611 if ( gLinkContext.verboseMapping ) {
3612 dyld::log("%18s at 0x%08llX->0x%08llX altered permissions to %c%c%c\n", "", p->address,
3613 p->address+p->size-1,
3614 (prot & PROT_READ) ? 'r' : '.', (prot & PROT_WRITE) ? 'w' : '.', (prot & PROT_EXEC) ? 'x' : '.' );
3615 }
3616 }
3617 }
3618 #endif
3619 }
3620 if ( gLinkContext.verboseMapping ) {
3621 // list the code blob
3622 dyld_cache_header* header = (dyld_cache_header*)sSharedCache;
3623 uint64_t signatureSize = header->codeSignatureSize;
3624 // zero size in header means signature runs to end-of-file
3625 if ( signatureSize == 0 ) {
3626 struct stat stat_buf;
3627 // FIXME: need size of cache file actually used
3628 if ( my_stat(IPHONE_DYLD_SHARED_CACHE_DIR DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME, &stat_buf) == 0 )
3629 signatureSize = stat_buf.st_size - header->codeSignatureOffset;
3630 }
3631 if ( signatureSize != 0 ) {
3632 const dyld_cache_mapping_info* const last = &start[dyld_shared_cache_ranges.sharedRegionsCount-1];
3633 uint64_t codeBlobStart = last->address + last->size;
3634 dyld::log(" 0x%08llX->0x%08llX (code signature)\n", codeBlobStart, codeBlobStart+signatureSize);
3635 }
3636 }
3637 #if __IPHONE_OS_VERSION_MIN_REQUIRED
3638 // check for file that enables dyld shared cache dylibs to be overridden
3639 struct stat enableStatBuf;
3640 // check file size to determine if correct file is in place.
3641 // See <rdar://problem/13591370> Need a way to disable roots without removing /S/L/C/com.apple.dyld/enable...
3642 sDylibsOverrideCache = ( (my_stat(IPHONE_DYLD_SHARED_CACHE_DIR "enable-dylibs-to-override-cache", &enableStatBuf) == 0)
3643 && (enableStatBuf.st_size < ENABLE_DYLIBS_TO_OVERRIDE_CACHE_SIZE) );
3644 #endif
3645 }
3646 }
3647 #endif // #if DYLD_SHARED_CACHE_SUPPORT
3648
3649
3650
3651 // create when NSLinkModule is called for a second time on a bundle
3652 ImageLoader* cloneImage(ImageLoader* image)
3653 {
3654 // open file (automagically closed when this function exits)
3655 FileOpener file(image->getPath());
3656
3657 struct stat stat_buf;
3658 if ( fstat(file.getFileDescriptor(), &stat_buf) == -1)
3659 throw "stat error";
3660
3661 dyld::LoadContext context;
3662 context.useSearchPaths = false;
3663 context.useFallbackPaths = false;
3664 context.useLdLibraryPath = false;
3665 context.implicitRPath = false;
3666 context.matchByInstallName = false;
3667 context.dontLoad = false;
3668 context.mustBeBundle = true;
3669 context.mustBeDylib = false;
3670 context.canBePIE = false;
3671 context.origin = NULL;
3672 context.rpath = NULL;
3673 return loadPhase6(file.getFileDescriptor(), stat_buf, image->getPath(), context);
3674 }
3675
3676
3677 ImageLoader* loadFromMemory(const uint8_t* mem, uint64_t len, const char* moduleName)
3678 {
3679 // if fat wrapper, find usable sub-file
3680 const fat_header* memStartAsFat = (fat_header*)mem;
3681 uint64_t fileOffset = 0;
3682 uint64_t fileLength = len;
3683 if ( memStartAsFat->magic == OSSwapBigToHostInt32(FAT_MAGIC) ) {
3684 if ( fatFindBest(memStartAsFat, &fileOffset, &fileLength) ) {
3685 mem = &mem[fileOffset];
3686 len = fileLength;
3687 }
3688 else {
3689 throw "no matching architecture in universal wrapper";
3690 }
3691 }
3692
3693 // try each loader
3694 if ( isCompatibleMachO(mem, moduleName) ) {
3695 ImageLoader* image = ImageLoaderMachO::instantiateFromMemory(moduleName, (macho_header*)mem, len, gLinkContext);
3696 // don't add bundles to global list, they can be loaded but not linked. When linked it will be added to list
3697 if ( ! image->isBundle() )
3698 addImage(image);
3699 return image;
3700 }
3701
3702 // try other file formats here...
3703
3704 // throw error about what was found
3705 switch (*(uint32_t*)mem) {
3706 case MH_MAGIC:
3707 case MH_CIGAM:
3708 case MH_MAGIC_64:
3709 case MH_CIGAM_64:
3710 throw "mach-o, but wrong architecture";
3711 default:
3712 throwf("unknown file type, first eight bytes: 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X",
3713 mem[0], mem[1], mem[2], mem[3], mem[4], mem[5], mem[6],mem[7]);
3714 }
3715 }
3716
3717
3718 void registerAddCallback(ImageCallback func)
3719 {
3720 // now add to list to get notified when any more images are added
3721 sAddImageCallbacks.push_back(func);
3722
3723 // call callback with all existing images
3724 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
3725 ImageLoader* image = *it;
3726 if ( image->getState() >= dyld_image_state_bound && image->getState() < dyld_image_state_terminated )
3727 (*func)(image->machHeader(), image->getSlide());
3728 }
3729 }
3730
3731 void registerRemoveCallback(ImageCallback func)
3732 {
3733 // <rdar://problem/15025198> ignore calls to register a notification during a notification
3734 if ( sRemoveImageCallbacksInUse )
3735 return;
3736 sRemoveImageCallbacks.push_back(func);
3737 }
3738
3739 void clearErrorMessage()
3740 {
3741 error_string[0] = '\0';
3742 }
3743
3744 void setErrorMessage(const char* message)
3745 {
3746 // save off error message in global buffer for CrashReporter to find
3747 strlcpy(error_string, message, sizeof(error_string));
3748 }
3749
3750 const char* getErrorMessage()
3751 {
3752 return error_string;
3753 }
3754
3755
3756 void halt(const char* message)
3757 {
3758 dyld::log("dyld: %s\n", message);
3759 setErrorMessage(message);
3760 uintptr_t terminationFlags = 0;
3761 if ( !gLinkContext.startedInitializingMainExecutable )
3762 terminationFlags = 1;
3763 setAlImageInfosHalt(error_string, terminationFlags);
3764 dyld_fatal_error(error_string);
3765 }
3766
3767 static void setErrorStrings(unsigned errorCode, const char* errorClientOfDylibPath,
3768 const char* errorTargetDylibPath, const char* errorSymbol)
3769 {
3770 dyld::gProcessInfo->errorKind = errorCode;
3771 dyld::gProcessInfo->errorClientOfDylibPath = errorClientOfDylibPath;
3772 dyld::gProcessInfo->errorTargetDylibPath = errorTargetDylibPath;
3773 dyld::gProcessInfo->errorSymbol = errorSymbol;
3774 }
3775
3776
3777 uintptr_t bindLazySymbol(const mach_header* mh, uintptr_t* lazyPointer)
3778 {
3779 uintptr_t result = 0;
3780 // acquire read-lock on dyld's data structures
3781 #if 0 // rdar://problem/3811777 turn off locking until deadlock is resolved
3782 if ( gLibSystemHelpers != NULL )
3783 (*gLibSystemHelpers->lockForReading)();
3784 #endif
3785 // lookup and bind lazy pointer and get target address
3786 try {
3787 ImageLoader* target;
3788 #if __i386__
3789 // fast stubs pass NULL for mh and image is instead found via the location of stub (aka lazyPointer)
3790 if ( mh == NULL )
3791 target = dyld::findImageContainingAddress(lazyPointer);
3792 else
3793 target = dyld::findImageByMachHeader(mh);
3794 #else
3795 // note, target should always be mach-o, because only mach-o lazy handler wired up to this
3796 target = dyld::findImageByMachHeader(mh);
3797 #endif
3798 if ( target == NULL )
3799 throwf("image not found for lazy pointer at %p", lazyPointer);
3800 result = target->doBindLazySymbol(lazyPointer, gLinkContext);
3801 }
3802 catch (const char* message) {
3803 dyld::log("dyld: lazy symbol binding failed: %s\n", message);
3804 halt(message);
3805 }
3806 // release read-lock on dyld's data structures
3807 #if 0
3808 if ( gLibSystemHelpers != NULL )
3809 (*gLibSystemHelpers->unlockForReading)();
3810 #endif
3811 // return target address to glue which jumps to it with real parameters restored
3812 return result;
3813 }
3814
3815
3816 uintptr_t fastBindLazySymbol(ImageLoader** imageLoaderCache, uintptr_t lazyBindingInfoOffset)
3817 {
3818 uintptr_t result = 0;
3819 // get image
3820 if ( *imageLoaderCache == NULL ) {
3821 // save in cache
3822 *imageLoaderCache = dyld::findMappedRange((uintptr_t)imageLoaderCache);
3823 if ( *imageLoaderCache == NULL ) {
3824 const char* message = "fast lazy binding from unknown image";
3825 dyld::log("dyld: %s\n", message);
3826 halt(message);
3827 }
3828 }
3829
3830 // bind lazy pointer and return it
3831 try {
3832 result = (*imageLoaderCache)->doBindFastLazySymbol((uint32_t)lazyBindingInfoOffset, gLinkContext,
3833 (dyld::gLibSystemHelpers != NULL) ? dyld::gLibSystemHelpers->acquireGlobalDyldLock : NULL,
3834 (dyld::gLibSystemHelpers != NULL) ? dyld::gLibSystemHelpers->releaseGlobalDyldLock : NULL);
3835 }
3836 catch (const char* message) {
3837 dyld::log("dyld: lazy symbol binding failed: %s\n", message);
3838 halt(message);
3839 }
3840
3841 // return target address to glue which jumps to it with real parameters restored
3842 return result;
3843 }
3844
3845
3846
3847 void registerUndefinedHandler(UndefinedHandler handler)
3848 {
3849 sUndefinedHandler = handler;
3850 }
3851
3852 static void undefinedHandler(const char* symboName)
3853 {
3854 if ( sUndefinedHandler != NULL ) {
3855 (*sUndefinedHandler)(symboName);
3856 }
3857 }
3858
3859 static bool findExportedSymbol(const char* name, bool onlyInCoalesced, const ImageLoader::Symbol** sym, const ImageLoader** image)
3860 {
3861 // search all images in order
3862 const ImageLoader* firstWeakImage = NULL;
3863 const ImageLoader::Symbol* firstWeakSym = NULL;
3864 const size_t imageCount = sAllImages.size();
3865 for(size_t i=0; i < imageCount; ++i) {
3866 ImageLoader* anImage = sAllImages[i];
3867 // the use of inserted libraries alters search order
3868 // so that inserted libraries are found before the main executable
3869 if ( sInsertedDylibCount > 0 ) {
3870 if ( i < sInsertedDylibCount )
3871 anImage = sAllImages[i+1];
3872 else if ( i == sInsertedDylibCount )
3873 anImage = sAllImages[0];
3874 }
3875 if ( ! anImage->hasHiddenExports() && (!onlyInCoalesced || anImage->hasCoalescedExports()) ) {
3876 *sym = anImage->findExportedSymbol(name, false, image);
3877 if ( *sym != NULL ) {
3878 // if weak definition found, record first one found
3879 if ( ((*image)->getExportedSymbolInfo(*sym) & ImageLoader::kWeakDefinition) != 0 ) {
3880 if ( firstWeakImage == NULL ) {
3881 firstWeakImage = *image;
3882 firstWeakSym = *sym;
3883 }
3884 }
3885 else {
3886 // found non-weak, so immediately return with it
3887 return true;
3888 }
3889 }
3890 }
3891 }
3892 if ( firstWeakSym != NULL ) {
3893 // found a weak definition, but no non-weak, so return first weak found
3894 *sym = firstWeakSym;
3895 *image = firstWeakImage;
3896 return true;
3897 }
3898
3899 return false;
3900 }
3901
3902 bool flatFindExportedSymbol(const char* name, const ImageLoader::Symbol** sym, const ImageLoader** image)
3903 {
3904 return findExportedSymbol(name, false, sym, image);
3905 }
3906
3907 bool findCoalescedExportedSymbol(const char* name, const ImageLoader::Symbol** sym, const ImageLoader** image)
3908 {
3909 return findExportedSymbol(name, true, sym, image);
3910 }
3911
3912
3913 bool flatFindExportedSymbolWithHint(const char* name, const char* librarySubstring, const ImageLoader::Symbol** sym, const ImageLoader** image)
3914 {
3915 // search all images in order
3916 const size_t imageCount = sAllImages.size();
3917 for(size_t i=0; i < imageCount; ++i){
3918 ImageLoader* anImage = sAllImages[i];
3919 // only look at images whose paths contain the hint string (NULL hint string is wildcard)
3920 if ( ! anImage->isBundle() && ((librarySubstring==NULL) || (strstr(anImage->getPath(), librarySubstring) != NULL)) ) {
3921 *sym = anImage->findExportedSymbol(name, false, image);
3922 if ( *sym != NULL ) {
3923 return true;
3924 }
3925 }
3926 }
3927 return false;
3928 }
3929
3930 unsigned int getCoalescedImages(ImageLoader* images[])
3931 {
3932 unsigned int count = 0;
3933 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
3934 ImageLoader* image = *it;
3935 if ( image->participatesInCoalescing() ) {
3936 *images++ = *it;
3937 ++count;
3938 }
3939 }
3940 return count;
3941 }
3942
3943
3944 static ImageLoader::MappedRegion* getMappedRegions(ImageLoader::MappedRegion* regions)
3945 {
3946 ImageLoader::MappedRegion* end = regions;
3947 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
3948 (*it)->getMappedRegions(end);
3949 }
3950 return end;
3951 }
3952
3953 void registerImageStateSingleChangeHandler(dyld_image_states state, dyld_image_state_change_handler handler)
3954 {
3955 // mark the image that the handler is in as never-unload because dyld has a reference into it
3956 ImageLoader* handlerImage = findImageContainingAddress((void*)handler);
3957 if ( handlerImage != NULL )
3958 handlerImage->setNeverUnload();
3959
3960 // add to list of handlers
3961 std::vector<dyld_image_state_change_handler>* handlers = stateToHandlers(state, sSingleHandlers);
3962 if ( handlers != NULL ) {
3963 // <rdar://problem/10332417> need updateAllImages() to be last in dyld_image_state_mapped list
3964 // so that if ObjC adds a handler that prevents a load, it happens before the gdb list is updated
3965 if ( state == dyld_image_state_mapped )
3966 handlers->insert(handlers->begin(), handler);
3967 else
3968 handlers->push_back(handler);
3969
3970 // call callback with all existing images
3971 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
3972 ImageLoader* image = *it;
3973 dyld_image_info info;
3974 info.imageLoadAddress = image->machHeader();
3975 info.imageFilePath = image->getRealPath();
3976 info.imageFileModDate = image->lastModified();
3977 // should only call handler if state == image->state
3978 if ( image->getState() == state )
3979 (*handler)(state, 1, &info);
3980 // ignore returned string, too late to do anything
3981 }
3982 }
3983 }
3984
3985 void registerImageStateBatchChangeHandler(dyld_image_states state, dyld_image_state_change_handler handler)
3986 {
3987 // mark the image that the handler is in as never-unload because dyld has a reference into it
3988 ImageLoader* handlerImage = findImageContainingAddress((void*)handler);
3989 if ( handlerImage != NULL )
3990 handlerImage->setNeverUnload();
3991
3992 // add to list of handlers
3993 std::vector<dyld_image_state_change_handler>* handlers = stateToHandlers(state, sBatchHandlers);
3994 if ( handlers != NULL ) {
3995 // insert at front, so that gdb handler is always last
3996 handlers->insert(handlers->begin(), handler);
3997
3998 // call callback with all existing images
3999 try {
4000 notifyBatchPartial(state, true, handler);
4001 }
4002 catch (const char* msg) {
4003 // ignore request to abort during registration
4004 }
4005 }
4006 }
4007
4008 static ImageLoader* libraryLocator(const char* libraryName, bool search, const char* origin, const ImageLoader::RPathChain* rpaths)
4009 {
4010 dyld::LoadContext context;
4011 context.useSearchPaths = search;
4012 context.useFallbackPaths = search;
4013 context.useLdLibraryPath = false;
4014 context.implicitRPath = false;
4015 context.matchByInstallName = false;
4016 context.dontLoad = false;
4017 context.mustBeBundle = false;
4018 context.mustBeDylib = true;
4019 context.canBePIE = false;
4020 context.origin = origin;
4021 context.rpath = rpaths;
4022 return load(libraryName, context);
4023 }
4024
4025 static const char* basename(const char* path)
4026 {
4027 const char* last = path;
4028 for (const char* s = path; *s != '\0'; s++) {
4029 if (*s == '/')
4030 last = s+1;
4031 }
4032 return last;
4033 }
4034
4035 static void setContext(const macho_header* mainExecutableMH, int argc, const char* argv[], const char* envp[], const char* apple[])
4036 {
4037 gLinkContext.loadLibrary = &libraryLocator;
4038 gLinkContext.terminationRecorder = &terminationRecorder;
4039 gLinkContext.flatExportFinder = &flatFindExportedSymbol;
4040 gLinkContext.coalescedExportFinder = &findCoalescedExportedSymbol;
4041 gLinkContext.getCoalescedImages = &getCoalescedImages;
4042 gLinkContext.undefinedHandler = &undefinedHandler;
4043 gLinkContext.getAllMappedRegions = &getMappedRegions;
4044 gLinkContext.bindingHandler = NULL;
4045 gLinkContext.notifySingle = &notifySingle;
4046 gLinkContext.notifyBatch = &notifyBatch;
4047 gLinkContext.removeImage = &removeImage;
4048 gLinkContext.registerDOFs = &registerDOFs;
4049 gLinkContext.clearAllDepths = &clearAllDepths;
4050 gLinkContext.printAllDepths = &printAllDepths;
4051 gLinkContext.imageCount = &imageCount;
4052 gLinkContext.setNewProgramVars = &setNewProgramVars;
4053 #if DYLD_SHARED_CACHE_SUPPORT
4054 gLinkContext.inSharedCache = &inSharedCache;
4055 #endif
4056 gLinkContext.setErrorStrings = &setErrorStrings;
4057 #if SUPPORT_OLD_CRT_INITIALIZATION
4058 gLinkContext.setRunInitialzersOldWay= &setRunInitialzersOldWay;
4059 #endif
4060 gLinkContext.findImageContainingAddress = &findImageContainingAddress;
4061 gLinkContext.addDynamicReference = &addDynamicReference;
4062 gLinkContext.bindingOptions = ImageLoader::kBindingNone;
4063 gLinkContext.argc = argc;
4064 gLinkContext.argv = argv;
4065 gLinkContext.envp = envp;
4066 gLinkContext.apple = apple;
4067 gLinkContext.progname = (argv[0] != NULL) ? basename(argv[0]) : "";
4068 gLinkContext.programVars.mh = mainExecutableMH;
4069 gLinkContext.programVars.NXArgcPtr = &gLinkContext.argc;
4070 gLinkContext.programVars.NXArgvPtr = &gLinkContext.argv;
4071 gLinkContext.programVars.environPtr = &gLinkContext.envp;
4072 gLinkContext.programVars.__prognamePtr=&gLinkContext.progname;
4073 gLinkContext.mainExecutable = NULL;
4074 gLinkContext.imageSuffix = NULL;
4075 gLinkContext.dynamicInterposeArray = NULL;
4076 gLinkContext.dynamicInterposeCount = 0;
4077 gLinkContext.prebindUsage = ImageLoader::kUseAllPrebinding;
4078 #if TARGET_IPHONE_SIMULATOR
4079 gLinkContext.sharedRegionMode = ImageLoader::kDontUseSharedRegion;
4080 #else
4081 gLinkContext.sharedRegionMode = ImageLoader::kUseSharedRegion;
4082 #endif
4083 }
4084
4085
4086
4087 //
4088 // Look for a special segment in the mach header.
4089 // Its presences means that the binary wants to have DYLD ignore
4090 // DYLD_ environment variables.
4091 //
4092 static bool hasRestrictedSegment(const macho_header* mh)
4093 {
4094 const uint32_t cmd_count = mh->ncmds;
4095 const struct load_command* const cmds = (struct load_command*)(((char*)mh)+sizeof(macho_header));
4096 const struct load_command* cmd = cmds;
4097 for (uint32_t i = 0; i < cmd_count; ++i) {
4098 switch (cmd->cmd) {
4099 case LC_SEGMENT_COMMAND:
4100 {
4101 const struct macho_segment_command* seg = (struct macho_segment_command*)cmd;
4102
4103 //dyld::log("seg name: %s\n", seg->segname);
4104 if (strcmp(seg->segname, "__RESTRICT") == 0) {
4105 const struct macho_section* const sectionsStart = (struct macho_section*)((char*)seg + sizeof(struct macho_segment_command));
4106 const struct macho_section* const sectionsEnd = &sectionsStart[seg->nsects];
4107 for (const struct macho_section* sect=sectionsStart; sect < sectionsEnd; ++sect) {
4108 if (strcmp(sect->sectname, "__restrict") == 0)
4109 return true;
4110 }
4111 }
4112 }
4113 break;
4114 }
4115 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
4116 }
4117
4118 return false;
4119 }
4120
4121
4122 #if SUPPORT_VERSIONED_PATHS
4123
4124 static bool readFirstPage(const char* dylibPath, uint8_t firstPage[4096])
4125 {
4126 firstPage[0] = 0;
4127 // open file (automagically closed when this function exits)
4128 FileOpener file(dylibPath);
4129
4130 if ( file.getFileDescriptor() == -1 )
4131 return false;
4132
4133 if ( pread(file.getFileDescriptor(), firstPage, 4096, 0) != 4096 )
4134 return false;
4135
4136 // if fat wrapper, find usable sub-file
4137 const fat_header* fileStartAsFat = (fat_header*)firstPage;
4138 if ( fileStartAsFat->magic == OSSwapBigToHostInt32(FAT_MAGIC) ) {
4139 uint64_t fileOffset;
4140 uint64_t fileLength;
4141 if ( fatFindBest(fileStartAsFat, &fileOffset, &fileLength) ) {
4142 if ( pread(file.getFileDescriptor(), firstPage, 4096, fileOffset) != 4096 )
4143 return false;
4144 }
4145 else {
4146 return false;
4147 }
4148 }
4149
4150 return true;
4151 }
4152
4153 //
4154 // Peeks at a dylib file and returns its current_version and install_name.
4155 // Returns false on error.
4156 //
4157 static bool getDylibVersionAndInstallname(const char* dylibPath, uint32_t* version, char* installName)
4158 {
4159 uint8_t firstPage[4096];
4160 const macho_header* mh = (macho_header*)firstPage;
4161 if ( !readFirstPage(dylibPath, firstPage) ) {
4162 #if DYLD_SHARED_CACHE_SUPPORT
4163 // If file cannot be read, check to see if path is in shared cache
4164 const macho_header* mhInCache;
4165 const char* pathInCache;
4166 long slideInCache;
4167 if ( !findInSharedCacheImage(dylibPath, true, NULL, &mhInCache, &pathInCache, &slideInCache) )
4168 return false;
4169 mh = mhInCache;
4170 #else
4171 return false;
4172 #endif
4173 }
4174
4175 // check mach-o header
4176 if ( mh->magic != sMainExecutableMachHeader->magic )
4177 return false;
4178 if ( mh->cputype != sMainExecutableMachHeader->cputype )
4179 return false;
4180
4181 // scan load commands for LC_ID_DYLIB
4182 const uint32_t cmd_count = mh->ncmds;
4183 const struct load_command* const cmds = (struct load_command*)(((char*)mh)+sizeof(macho_header));
4184 const struct load_command* const cmdsReadEnd = (struct load_command*)(((char*)mh)+4096);
4185 const struct load_command* cmd = cmds;
4186 for (uint32_t i = 0; i < cmd_count; ++i) {
4187 switch (cmd->cmd) {
4188 case LC_ID_DYLIB:
4189 {
4190 const struct dylib_command* id = (struct dylib_command*)cmd;
4191 *version = id->dylib.current_version;
4192 if ( installName != NULL )
4193 strlcpy(installName, (char *)id + id->dylib.name.offset, PATH_MAX);
4194 return true;
4195 }
4196 break;
4197 }
4198 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
4199 if ( cmd > cmdsReadEnd )
4200 return false;
4201 }
4202
4203 return false;
4204 }
4205 #endif // SUPPORT_VERSIONED_PATHS
4206
4207
4208 #if 0
4209 static void printAllImages()
4210 {
4211 dyld::log("printAllImages()\n");
4212 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
4213 ImageLoader* image = *it;
4214 dyld_image_states imageState = image->getState();
4215 dyld::log(" state=%d, dlopen-count=%d, never-unload=%d, in-use=%d, name=%s\n",
4216 imageState, image->dlopenCount(), image->neverUnload(), image->isMarkedInUse(), image->getShortName());
4217 }
4218 }
4219 #endif
4220
4221 void link(ImageLoader* image, bool forceLazysBound, bool neverUnload, const ImageLoader::RPathChain& loaderRPaths)
4222 {
4223 // add to list of known images. This did not happen at creation time for bundles
4224 if ( image->isBundle() && !image->isLinked() )
4225 addImage(image);
4226
4227 // we detect root images as those not linked in yet
4228 if ( !image->isLinked() )
4229 addRootImage(image);
4230
4231 // process images
4232 try {
4233 image->link(gLinkContext, forceLazysBound, false, neverUnload, loaderRPaths);
4234 }
4235 catch (const char* msg) {
4236 garbageCollectImages();
4237 throw;
4238 }
4239 }
4240
4241
4242 void runInitializers(ImageLoader* image)
4243 {
4244 // do bottom up initialization
4245 ImageLoader::InitializerTimingList initializerTimes[sAllImages.size()];
4246 initializerTimes[0].count = 0;
4247 image->runInitializers(gLinkContext, initializerTimes[0]);
4248 }
4249
4250 // This function is called at the end of dlclose() when the reference count goes to zero.
4251 // The dylib being unloaded may have brought in other dependent dylibs when it was loaded.
4252 // Those dependent dylibs need to be unloaded, but only if they are not referenced by
4253 // something else. We use a standard mark and sweep garbage collection.
4254 //
4255 // The tricky part is that when a dylib is unloaded it may have a termination function that
4256 // can run and itself call dlclose() on yet another dylib. The problem is that this
4257 // sort of gabage collection is not re-entrant. Instead a terminator's call to dlclose()
4258 // which calls garbageCollectImages() will just set a flag to re-do the garbage collection
4259 // when the current pass is done.
4260 //
4261 // Also note that this is done within the dyld global lock, so it is always single threaded.
4262 //
4263 void garbageCollectImages()
4264 {
4265 static bool sDoingGC = false;
4266 static bool sRedo = false;
4267
4268 if ( sDoingGC ) {
4269 // GC is currently being run, just set a flag to have it run again.
4270 sRedo = true;
4271 return;
4272 }
4273
4274 sDoingGC = true;
4275 do {
4276 sRedo = false;
4277
4278 // mark phase: mark all images not-in-use
4279 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
4280 ImageLoader* image = *it;
4281 //dyld::log("gc: neverUnload=%d name=%s\n", image->neverUnload(), image->getShortName());
4282 image->markNotUsed();
4283 }
4284
4285 // sweep phase: mark as in-use, images reachable from never-unload or in-use image
4286 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
4287 ImageLoader* image = *it;
4288 if ( (image->dlopenCount() != 0) || image->neverUnload() ) {
4289 OSSpinLockLock(&sDynamicReferencesLock);
4290 image->markedUsedRecursive(sDynamicReferences);
4291 OSSpinLockUnlock(&sDynamicReferencesLock);
4292 }
4293 }
4294
4295 // collect phase: build array of images not marked in-use
4296 ImageLoader* deadImages[sAllImages.size()];
4297 unsigned deadCount = 0;
4298 int maxRangeCount = 0;
4299 unsigned i = 0;
4300 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
4301 ImageLoader* image = *it;
4302 if ( ! image->isMarkedInUse() ) {
4303 deadImages[i++] = image;
4304 if (gLogAPIs) dyld::log("dlclose(), found unused image %p %s\n", image, image->getShortName());
4305 ++deadCount;
4306 maxRangeCount += image->segmentCount();
4307 }
4308 }
4309
4310 // collect phase: run termination routines for images not marked in-use
4311 __cxa_range_t ranges[maxRangeCount];
4312 int rangeCount = 0;
4313 for (unsigned i=0; i < deadCount; ++i) {
4314 ImageLoader* image = deadImages[i];
4315 for (unsigned int j=0; j < image->segmentCount(); ++j) {
4316 if ( !image->segExecutable(j) )
4317 continue;
4318 if ( rangeCount < maxRangeCount ) {
4319 ranges[rangeCount].addr = (const void*)image->segActualLoadAddress(j);
4320 ranges[rangeCount].length = image->segSize(j);
4321 ++rangeCount;
4322 }
4323 }
4324 try {
4325 runImageStaticTerminators(image);
4326 }
4327 catch (const char* msg) {
4328 dyld::warn("problem running terminators for image: %s\n", msg);
4329 }
4330 }
4331
4332 // <rdar://problem/14718598> dyld should call __cxa_finalize_ranges()
4333 if ( (rangeCount > 0) && (gLibSystemHelpers != NULL) && (gLibSystemHelpers->version >= 13) )
4334 (*gLibSystemHelpers->cxa_finalize_ranges)(ranges, rangeCount);
4335
4336 // collect phase: delete all images which are not marked in-use
4337 bool mightBeMore;
4338 do {
4339 mightBeMore = false;
4340 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
4341 ImageLoader* image = *it;
4342 if ( ! image->isMarkedInUse() ) {
4343 try {
4344 if (gLogAPIs) dyld::log("dlclose(), deleting %p %s\n", image, image->getShortName());
4345 removeImage(image);
4346 ImageLoader::deleteImage(image);
4347 mightBeMore = true;
4348 break; // interator in invalidated by this removal
4349 }
4350 catch (const char* msg) {
4351 dyld::warn("problem deleting image: %s\n", msg);
4352 }
4353 }
4354 }
4355 } while ( mightBeMore );
4356 } while (sRedo);
4357 sDoingGC = false;
4358
4359 //printAllImages();
4360
4361 }
4362
4363
4364 static void preflight_finally(ImageLoader* image)
4365 {
4366 if ( image->isBundle() ) {
4367 removeImageFromAllImages(image->machHeader());
4368 ImageLoader::deleteImage(image);
4369 }
4370 sBundleBeingLoaded = NULL;
4371 dyld::garbageCollectImages();
4372 }
4373
4374
4375 void preflight(ImageLoader* image, const ImageLoader::RPathChain& loaderRPaths)
4376 {
4377 try {
4378 if ( image->isBundle() )
4379 sBundleBeingLoaded = image; // hack
4380 image->link(gLinkContext, false, true, false, loaderRPaths);
4381 }
4382 catch (const char* msg) {
4383 preflight_finally(image);
4384 throw;
4385 }
4386 preflight_finally(image);
4387 }
4388
4389 static void loadInsertedDylib(const char* path)
4390 {
4391 ImageLoader* image = NULL;
4392 try {
4393 LoadContext context;
4394 context.useSearchPaths = false;
4395 context.useFallbackPaths = false;
4396 context.useLdLibraryPath = false;
4397 context.implicitRPath = false;
4398 context.matchByInstallName = false;
4399 context.dontLoad = false;
4400 context.mustBeBundle = false;
4401 context.mustBeDylib = true;
4402 context.canBePIE = false;
4403 context.origin = NULL; // can't use @loader_path with DYLD_INSERT_LIBRARIES
4404 context.rpath = NULL;
4405 image = load(path, context);
4406 }
4407 catch (const char* msg) {
4408 #if TARGET_IPHONE_SIMULATOR
4409 dyld::log("dyld: warning: could not load inserted library '%s' because %s\n", path, msg);
4410 #else
4411 halt(dyld::mkstringf("could not load inserted library '%s' because %s\n", path, msg));
4412 #endif
4413 }
4414 catch (...) {
4415 halt(dyld::mkstringf("could not load inserted library '%s'\n", path));
4416 }
4417 }
4418
4419 static bool processRestricted(const macho_header* mainExecutableMH, bool* ignoreEnvVars, bool* processRequiresLibraryValidation)
4420 {
4421 #if TARGET_IPHONE_SIMULATOR
4422 gLinkContext.codeSigningEnforced = true;
4423 #else
4424 // ask kernel if code signature of program makes it restricted
4425 uint32_t flags;
4426 if ( csops(0, CS_OPS_STATUS, &flags, sizeof(flags)) != -1 ) {
4427 if (flags & CS_REQUIRE_LV)
4428 *processRequiresLibraryValidation = true;
4429
4430 #if __MAC_OS_X_VERSION_MIN_REQUIRED
4431 if ( flags & CS_ENFORCEMENT ) {
4432 gLinkContext.codeSigningEnforced = true;
4433 }
4434 if ( ((flags & CS_RESTRICT) == CS_RESTRICT) && (csr_check(CSR_ALLOW_TASK_FOR_PID) != 0) ) {
4435 sRestrictedReason = restrictedByEntitlements;
4436 return true;
4437 }
4438 #else
4439 if ((flags & CS_ENFORCEMENT) && !(flags & CS_GET_TASK_ALLOW)) {
4440 *ignoreEnvVars = true;
4441 }
4442 gLinkContext.codeSigningEnforced = true;
4443 #endif
4444 }
4445 #endif
4446
4447 // all processes with setuid or setgid bit set are restricted
4448 if ( issetugid() ) {
4449 sRestrictedReason = restrictedBySetGUid;
4450 return true;
4451 }
4452
4453 // <rdar://problem/13158444&13245742> Respect __RESTRICT,__restrict section for root processes
4454 if ( hasRestrictedSegment(mainExecutableMH) ) {
4455 // existence of __RESTRICT/__restrict section make process restricted
4456 sRestrictedReason = restrictedBySegment;
4457 return true;
4458 }
4459 return false;
4460 }
4461
4462
4463 bool processIsRestricted()
4464 {
4465 return sProcessIsRestricted;
4466 }
4467
4468
4469 // <rdar://problem/10583252> Add dyld to uuidArray to enable symbolication of stackshots
4470 static void addDyldImageToUUIDList()
4471 {
4472 const struct macho_header* mh = (macho_header*)&__dso_handle;
4473 const uint32_t cmd_count = mh->ncmds;
4474 const struct load_command* const cmds = (struct load_command*)((char*)mh + sizeof(macho_header));
4475 const struct load_command* cmd = cmds;
4476 for (uint32_t i = 0; i < cmd_count; ++i) {
4477 switch (cmd->cmd) {
4478 case LC_UUID: {
4479 uuid_command* uc = (uuid_command*)cmd;
4480 dyld_uuid_info info;
4481 info.imageLoadAddress = (mach_header*)mh;
4482 memcpy(info.imageUUID, uc->uuid, 16);
4483 addNonSharedCacheImageUUID(info);
4484 return;
4485 }
4486 }
4487 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
4488 }
4489 }
4490
4491 #if __MAC_OS_X_VERSION_MIN_REQUIRED
4492 typedef int (*open_proc_t)(const char*, int, int);
4493 typedef int (*fcntl_proc_t)(int, int, void*);
4494 typedef int (*ioctl_proc_t)(int, unsigned long, void*);
4495 static void* getProcessInfo() { return dyld::gProcessInfo; }
4496 static SyscallHelpers sSysCalls = {
4497 4,
4498 // added in version 1
4499 (open_proc_t)&open,
4500 &close,
4501 &pread,
4502 &write,
4503 &mmap,
4504 &munmap,
4505 &madvise,
4506 &stat,
4507 (fcntl_proc_t)&fcntl,
4508 (ioctl_proc_t)&ioctl,
4509 &issetugid,
4510 &getcwd,
4511 &realpath,
4512 &vm_allocate,
4513 &vm_deallocate,
4514 &vm_protect,
4515 &vlog,
4516 &vwarn,
4517 &pthread_mutex_lock,
4518 &pthread_mutex_unlock,
4519 &mach_thread_self,
4520 &mach_port_deallocate,
4521 &task_self_trap,
4522 &mach_timebase_info,
4523 &OSAtomicCompareAndSwapPtrBarrier,
4524 &OSMemoryBarrier,
4525 &getProcessInfo,
4526 &__error,
4527 &mach_absolute_time,
4528 // added in version 2
4529 &thread_switch,
4530 // added in version 3
4531 &opendir,
4532 &readdir_r,
4533 &closedir,
4534 // added in version 4
4535 &coresymbolication_load_notifier,
4536 &coresymbolication_unload_notifier
4537 };
4538
4539 __attribute__((noinline))
4540 static uintptr_t useSimulatorDyld(int fd, const macho_header* mainExecutableMH, const char* dyldPath,
4541 int argc, const char* argv[], const char* envp[], const char* apple[], uintptr_t* startGlue)
4542 {
4543 *startGlue = 0;
4544
4545 // verify simulator dyld file is owned by root
4546 struct stat sb;
4547 if ( fstat(fd, &sb) == -1 )
4548 return 0;
4549
4550 // read first page of dyld file
4551 uint8_t firstPage[4096];
4552 if ( pread(fd, firstPage, 4096, 0) != 4096 )
4553 return 0;
4554
4555 // if fat file, pick matching slice
4556 uint64_t fileOffset = 0;
4557 uint64_t fileLength = sb.st_size;
4558 const fat_header* fileStartAsFat = (fat_header*)firstPage;
4559 if ( fileStartAsFat->magic == OSSwapBigToHostInt32(FAT_MAGIC) ) {
4560 if ( !fatFindBest(fileStartAsFat, &fileOffset, &fileLength) )
4561 return 0;
4562 // re-read buffer from start of mach-o slice in fat file
4563 if ( pread(fd, firstPage, 4096, fileOffset) != 4096 )
4564 return 0;
4565 }
4566 else if ( !isCompatibleMachO(firstPage, dyldPath) ) {
4567 return 0;
4568 }
4569
4570 // calculate total size of dyld segments
4571 const macho_header* mh = (const macho_header*)firstPage;
4572 struct macho_segment_command* lastSeg = NULL;
4573 struct macho_segment_command* firstSeg = NULL;
4574 uintptr_t mappingSize = 0;
4575 uintptr_t preferredLoadAddress = 0;
4576 const uint32_t cmd_count = mh->ncmds;
4577 if ( (sizeof(macho_header) + mh->sizeofcmds) > 4096 )
4578 return 0;
4579 const struct load_command* const cmds = (struct load_command*)(((char*)mh)+sizeof(macho_header));
4580 const struct load_command* const endCmds = (struct load_command*)(((char*)mh) + sizeof(macho_header) + mh->sizeofcmds);
4581 const struct load_command* cmd = cmds;
4582 for (uint32_t i = 0; i < cmd_count; ++i) {
4583 uint32_t cmdLength = cmd->cmdsize;
4584 if ( cmdLength < 8 )
4585 return 0;
4586 const struct load_command* const nextCmd = (const struct load_command*)(((char*)cmd)+cmdLength);
4587 if ( (nextCmd > endCmds) || (nextCmd < cmd) )
4588 return 0;
4589 switch (cmd->cmd) {
4590 case LC_SEGMENT_COMMAND:
4591 {
4592 struct macho_segment_command* seg = (struct macho_segment_command*)cmd;
4593 if ( seg->vmaddr + seg->vmsize < seg->vmaddr )
4594 return 0;
4595 if ( seg->vmsize < seg->filesize )
4596 return 0;
4597 if ( lastSeg == NULL ) {
4598 // first segment must be __TEXT and start at beginning of file/slice
4599 firstSeg = seg;
4600 if ( strcmp(seg->segname, "__TEXT") != 0 )
4601 return 0;
4602 if ( seg->fileoff != 0 )
4603 return 0;
4604 if ( seg->filesize < (sizeof(macho_header) + mh->sizeofcmds) )
4605 return 0;
4606 preferredLoadAddress = seg->vmaddr;
4607 }
4608 else {
4609 // other sements must be continguous with previous segment and not executable
4610 if ( lastSeg->fileoff + lastSeg->filesize != seg->fileoff )
4611 return 0;
4612 if ( lastSeg->vmaddr + lastSeg->vmsize != seg->vmaddr )
4613 return 0;
4614 if ( (seg->initprot & VM_PROT_EXECUTE) != 0 )
4615 return 0;
4616 }
4617 mappingSize += seg->vmsize;
4618 lastSeg = seg;
4619 }
4620 break;
4621 case LC_SEGMENT_COMMAND_WRONG:
4622 return 0;
4623 }
4624 cmd = nextCmd;
4625 }
4626 // last segment must be named __LINKEDIT and not writable
4627 if ( strcmp(lastSeg->segname, "__LINKEDIT") != 0 )
4628 return 0;
4629 if ( lastSeg->initprot & VM_PROT_WRITE )
4630 return 0;
4631
4632 // reserve space, then mmap each segment
4633 vm_address_t loadAddress = 0;
4634 if ( ::vm_allocate(mach_task_self(), &loadAddress, mappingSize, VM_FLAGS_ANYWHERE) != 0 )
4635 return 0;
4636 cmd = cmds;
4637 struct linkedit_data_command* codeSigCmd = NULL;
4638 struct source_version_command* dyldVersionCmd = NULL;
4639 for (uint32_t i = 0; i < cmd_count; ++i) {
4640 switch (cmd->cmd) {
4641 case LC_SEGMENT_COMMAND:
4642 {
4643 struct macho_segment_command* seg = (struct macho_segment_command*)cmd;
4644 uintptr_t requestedLoadAddress = seg->vmaddr - preferredLoadAddress + loadAddress;
4645 void* segAddress = ::mmap((void*)requestedLoadAddress, seg->filesize, seg->initprot, MAP_FIXED | MAP_PRIVATE, fd, fileOffset + seg->fileoff);
4646 //dyld::log("dyld_sim %s mapped at %p\n", seg->segname, segAddress);
4647 if ( segAddress == (void*)(-1) )
4648 return 0;
4649 }
4650 break;
4651 case LC_CODE_SIGNATURE:
4652 codeSigCmd = (struct linkedit_data_command*)cmd;
4653 break;
4654 case LC_SOURCE_VERSION:
4655 dyldVersionCmd = (struct source_version_command*)cmd;
4656 break;
4657 }
4658 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
4659 }
4660
4661 // must have code signature which is contained within LINKEDIT segment
4662 if ( codeSigCmd == NULL )
4663 return 0;
4664 if ( codeSigCmd->dataoff < lastSeg->fileoff )
4665 return 0;
4666 if ( (codeSigCmd->dataoff + codeSigCmd->datasize) > (lastSeg->fileoff + lastSeg->filesize) )
4667 return 0;
4668
4669 fsignatures_t siginfo;
4670 siginfo.fs_file_start=fileOffset; // start of mach-o slice in fat file
4671 siginfo.fs_blob_start=(void*)(long)(codeSigCmd->dataoff); // start of code-signature in mach-o file
4672 siginfo.fs_blob_size=codeSigCmd->datasize; // size of code-signature
4673 int result = fcntl(fd, F_ADDFILESIGS_FOR_DYLD_SIM, &siginfo);
4674 if ( result == -1 ) {
4675 dyld::log("fcntl(F_ADDFILESIGS_FOR_DYLD_SIM) failed with errno=%d\n", errno);
4676 return 0;
4677 }
4678 close(fd);
4679 // file range covered by code signature must extend up to code signature itself
4680 if ( siginfo.fs_file_start < codeSigCmd->dataoff )
4681 return 0;
4682
4683 // walk newly mapped dyld_sim __TEXT load commands to find entry point
4684 uintptr_t entry = 0;
4685 cmd = (struct load_command*)(((char*)loadAddress)+sizeof(macho_header));
4686 const uint32_t count = ((macho_header*)(loadAddress))->ncmds;
4687 for (uint32_t i = 0; i < count; ++i) {
4688 if (cmd->cmd == LC_UNIXTHREAD) {
4689 #if __i386__
4690 const i386_thread_state_t* registers = (i386_thread_state_t*)(((char*)cmd) + 16);
4691 // entry point must be in first segment
4692 if ( registers->__eip < firstSeg->vmaddr )
4693 return 0;
4694 if ( registers->__eip > (firstSeg->vmaddr + firstSeg->vmsize) )
4695 return 0;
4696 entry = (registers->__eip + loadAddress - preferredLoadAddress);
4697 #elif __x86_64__
4698 const x86_thread_state64_t* registers = (x86_thread_state64_t*)(((char*)cmd) + 16);
4699 // entry point must be in first segment
4700 if ( registers->__rip < firstSeg->vmaddr )
4701 return 0;
4702 if ( registers->__rip > (firstSeg->vmaddr + firstSeg->vmsize) )
4703 return 0;
4704 entry = (registers->__rip + loadAddress - preferredLoadAddress);
4705 #endif
4706 }
4707 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
4708 }
4709
4710 // notify debugger that dyld_sim is loaded
4711 dyld_image_info info;
4712 info.imageLoadAddress = (mach_header*)loadAddress;
4713 info.imageFilePath = strdup(dyldPath);
4714 info.imageFileModDate = sb.st_mtime;
4715 addImagesToAllImages(1, &info);
4716 dyld::gProcessInfo->notification(dyld_image_adding, 1, &info);
4717
4718 const char** appleParams = apple;
4719 // jump into new simulator dyld
4720 typedef uintptr_t (*sim_entry_proc_t)(int argc, const char* argv[], const char* envp[], const char* apple[],
4721 const macho_header* mainExecutableMH, const macho_header* dyldMH, uintptr_t dyldSlide,
4722 const dyld::SyscallHelpers* vtable, uintptr_t* startGlue);
4723 sim_entry_proc_t newDyld = (sim_entry_proc_t)entry;
4724 return (*newDyld)(argc, argv, envp, appleParams, mainExecutableMH, (macho_header*)loadAddress,
4725 loadAddress - preferredLoadAddress,
4726 &sSysCalls, startGlue);
4727 }
4728 #endif
4729
4730
4731 //
4732 // Entry point for dyld. The kernel loads dyld and jumps to __dyld_start which
4733 // sets up some registers and call this function.
4734 //
4735 // Returns address of main() in target program which __dyld_start jumps to
4736 //
4737 uintptr_t
4738 _main(const macho_header* mainExecutableMH, uintptr_t mainExecutableSlide,
4739 int argc, const char* argv[], const char* envp[], const char* apple[],
4740 uintptr_t* startGlue)
4741 {
4742 uintptr_t result = 0;
4743 sMainExecutableMachHeader = mainExecutableMH;
4744 #if __MAC_OS_X_VERSION_MIN_REQUIRED
4745 // if this is host dyld, check to see if iOS simulator is being run
4746 const char* rootPath = _simple_getenv(envp, "DYLD_ROOT_PATH");
4747 if ( rootPath != NULL ) {
4748 // look to see if simulator has its own dyld
4749 char simDyldPath[PATH_MAX];
4750 strlcpy(simDyldPath, rootPath, PATH_MAX);
4751 strlcat(simDyldPath, "/usr/lib/dyld_sim", PATH_MAX);
4752 int fd = my_open(simDyldPath, O_RDONLY, 0);
4753 if ( fd != -1 ) {
4754 result = useSimulatorDyld(fd, mainExecutableMH, simDyldPath, argc, argv, envp, apple, startGlue);
4755 if ( !result && (*startGlue == 0) )
4756 halt("problem loading iOS simulator dyld");
4757 return result;
4758 }
4759 }
4760 #endif
4761
4762 CRSetCrashLogMessage("dyld: launch started");
4763
4764 #if LOG_BINDINGS
4765 char bindingsLogPath[256];
4766
4767 const char* shortProgName = "unknown";
4768 if ( argc > 0 ) {
4769 shortProgName = strrchr(argv[0], '/');
4770 if ( shortProgName == NULL )
4771 shortProgName = argv[0];
4772 else
4773 ++shortProgName;
4774 }
4775 mysprintf(bindingsLogPath, "/tmp/bindings/%d-%s", getpid(), shortProgName);
4776 sBindingsLogfile = open(bindingsLogPath, O_WRONLY | O_CREAT, 0666);
4777 if ( sBindingsLogfile == -1 ) {
4778 ::mkdir("/tmp/bindings", 0777);
4779 sBindingsLogfile = open(bindingsLogPath, O_WRONLY | O_CREAT, 0666);
4780 }
4781 //dyld::log("open(%s) => %d, errno = %d\n", bindingsLogPath, sBindingsLogfile, errno);
4782 #endif
4783 setContext(mainExecutableMH, argc, argv, envp, apple);
4784
4785 // Pickup the pointer to the exec path.
4786 sExecPath = _simple_getenv(apple, "executable_path");
4787
4788 // <rdar://problem/13868260> Remove interim apple[0] transition code from dyld
4789 if (!sExecPath) sExecPath = apple[0];
4790
4791 bool ignoreEnvironmentVariables = false;
4792 if ( sExecPath[0] != '/' ) {
4793 // have relative path, use cwd to make absolute
4794 char cwdbuff[MAXPATHLEN];
4795 if ( getcwd(cwdbuff, MAXPATHLEN) != NULL ) {
4796 // maybe use static buffer to avoid calling malloc so early...
4797 char* s = new char[strlen(cwdbuff) + strlen(sExecPath) + 2];
4798 strcpy(s, cwdbuff);
4799 strcat(s, "/");
4800 strcat(s, sExecPath);
4801 sExecPath = s;
4802 }
4803 }
4804 // Remember short name of process for later logging
4805 sExecShortName = ::strrchr(sExecPath, '/');
4806 if ( sExecShortName != NULL )
4807 ++sExecShortName;
4808 else
4809 sExecShortName = sExecPath;
4810 sProcessIsRestricted = processRestricted(mainExecutableMH, &ignoreEnvironmentVariables, &sProcessRequiresLibraryValidation);
4811 if ( sProcessIsRestricted ) {
4812 #if SUPPORT_LC_DYLD_ENVIRONMENT
4813 checkLoadCommandEnvironmentVariables();
4814 #endif
4815 pruneEnvironmentVariables(envp, &apple);
4816 // set again because envp and apple may have changed or moved
4817 setContext(mainExecutableMH, argc, argv, envp, apple);
4818 }
4819 else {
4820 if ( !ignoreEnvironmentVariables )
4821 checkEnvironmentVariables(envp);
4822 defaultUninitializedFallbackPaths(envp);
4823 }
4824 if ( sEnv.DYLD_PRINT_OPTS )
4825 printOptions(argv);
4826 if ( sEnv.DYLD_PRINT_ENV )
4827 printEnvironmentVariables(envp);
4828 getHostInfo(mainExecutableMH, mainExecutableSlide);
4829 // install gdb notifier
4830 stateToHandlers(dyld_image_state_dependents_mapped, sBatchHandlers)->push_back(notifyGDB);
4831 stateToHandlers(dyld_image_state_mapped, sSingleHandlers)->push_back(updateAllImages);
4832 // make initial allocations large enough that it is unlikely to need to be re-alloced
4833 sAllImages.reserve(INITIAL_IMAGE_COUNT);
4834 sImageRoots.reserve(16);
4835 sAddImageCallbacks.reserve(4);
4836 sRemoveImageCallbacks.reserve(4);
4837 sImageFilesNeedingTermination.reserve(16);
4838 sImageFilesNeedingDOFUnregistration.reserve(8);
4839
4840 #ifdef WAIT_FOR_SYSTEM_ORDER_HANDSHAKE
4841 // <rdar://problem/6849505> Add gating mechanism to dyld support system order file generation process
4842 WAIT_FOR_SYSTEM_ORDER_HANDSHAKE(dyld::gProcessInfo->systemOrderFlag);
4843 #endif
4844
4845
4846 try {
4847 // add dyld itself to UUID list
4848 addDyldImageToUUIDList();
4849 CRSetCrashLogMessage(sLoadingCrashMessage);
4850 // instantiate ImageLoader for main executable
4851 sMainExecutable = instantiateFromLoadedImage(mainExecutableMH, mainExecutableSlide, sExecPath);
4852 gLinkContext.mainExecutable = sMainExecutable;
4853 gLinkContext.processIsRestricted = sProcessIsRestricted;
4854 gLinkContext.processRequiresLibraryValidation = sProcessRequiresLibraryValidation;
4855 gLinkContext.mainExecutableCodeSigned = hasCodeSignatureLoadCommand(mainExecutableMH);
4856
4857 #if TARGET_IPHONE_SIMULATOR
4858 #if TARGET_OS_WATCH || TARGET_OS_TV
4859 // disable error during bring up of these simulators
4860 #else
4861 // check main executable is not too new for this OS
4862 {
4863 if ( ! isSimulatorBinary((uint8_t*)mainExecutableMH, sExecPath) ) {
4864 throwf("program was built for Mac OS X and cannot be run in simulator");
4865 }
4866 uint32_t mainMinOS = sMainExecutable->minOSVersion();
4867 // dyld is always built for the current OS, so we can get the current OS version
4868 // from the load command in dyld itself.
4869 uint32_t dyldMinOS = ImageLoaderMachO::minOSVersion((const mach_header*)&__dso_handle);
4870 if ( mainMinOS > dyldMinOS ) {
4871 throwf("app was built for iOS %d.%d which is newer than this simulator %d.%d",
4872 mainMinOS >> 16, ((mainMinOS >> 8) & 0xFF),
4873 dyldMinOS >> 16, ((dyldMinOS >> 8) & 0xFF));
4874 }
4875 }
4876 #endif
4877 #endif
4878
4879 // load shared cache
4880 checkSharedRegionDisable();
4881 #if DYLD_SHARED_CACHE_SUPPORT
4882 if ( gLinkContext.sharedRegionMode != ImageLoader::kDontUseSharedRegion )
4883 mapSharedCache();
4884 #endif
4885
4886 // Now that shared cache is loaded, setup an versioned dylib overrides
4887 #if SUPPORT_VERSIONED_PATHS
4888 checkVersionedPaths();
4889 #endif
4890
4891 // load any inserted libraries
4892 if ( sEnv.DYLD_INSERT_LIBRARIES != NULL ) {
4893 for (const char* const* lib = sEnv.DYLD_INSERT_LIBRARIES; *lib != NULL; ++lib)
4894 loadInsertedDylib(*lib);
4895 }
4896 // record count of inserted libraries so that a flat search will look at
4897 // inserted libraries, then main, then others.
4898 sInsertedDylibCount = sAllImages.size()-1;
4899
4900 // link main executable
4901 gLinkContext.linkingMainExecutable = true;
4902 link(sMainExecutable, sEnv.DYLD_BIND_AT_LAUNCH, true, ImageLoader::RPathChain(NULL, NULL));
4903 sMainExecutable->setNeverUnloadRecursive();
4904 if ( sMainExecutable->forceFlat() ) {
4905 gLinkContext.bindFlat = true;
4906 gLinkContext.prebindUsage = ImageLoader::kUseNoPrebinding;
4907 }
4908
4909 // link any inserted libraries
4910 // do this after linking main executable so that any dylibs pulled in by inserted
4911 // dylibs (e.g. libSystem) will not be in front of dylibs the program uses
4912 if ( sInsertedDylibCount > 0 ) {
4913 for(unsigned int i=0; i < sInsertedDylibCount; ++i) {
4914 ImageLoader* image = sAllImages[i+1];
4915 link(image, sEnv.DYLD_BIND_AT_LAUNCH, true, ImageLoader::RPathChain(NULL, NULL));
4916 image->setNeverUnloadRecursive();
4917 }
4918 // only INSERTED libraries can interpose
4919 // register interposing info after all inserted libraries are bound so chaining works
4920 for(unsigned int i=0; i < sInsertedDylibCount; ++i) {
4921 ImageLoader* image = sAllImages[i+1];
4922 image->registerInterposing();
4923 }
4924 }
4925
4926 // <rdar://problem/19315404> dyld should support interposition even without DYLD_INSERT_LIBRARIES
4927 for (int i=sInsertedDylibCount+1; i < sAllImages.size(); ++i) {
4928 ImageLoader* image = sAllImages[i];
4929 if ( image->inSharedCache() )
4930 continue;
4931 image->registerInterposing();
4932 }
4933
4934 // apply interposing to initial set of images
4935 for(int i=0; i < sImageRoots.size(); ++i) {
4936 sImageRoots[i]->applyInterposing(gLinkContext);
4937 }
4938 gLinkContext.linkingMainExecutable = false;
4939
4940 // <rdar://problem/12186933> do weak binding only after all inserted images linked
4941 sMainExecutable->weakBind(gLinkContext);
4942
4943 CRSetCrashLogMessage("dyld: launch, running initializers");
4944 #if SUPPORT_OLD_CRT_INITIALIZATION
4945 // Old way is to run initializers via a callback from crt1.o
4946 if ( ! gRunInitializersOldWay )
4947 initializeMainExecutable();
4948 #else
4949 // run all initializers
4950 initializeMainExecutable();
4951 #endif
4952 // find entry point for main executable
4953 result = (uintptr_t)sMainExecutable->getThreadPC();
4954 if ( result != 0 ) {
4955 // main executable uses LC_MAIN, needs to return to glue in libdyld.dylib
4956 if ( (gLibSystemHelpers != NULL) && (gLibSystemHelpers->version >= 9) )
4957 *startGlue = (uintptr_t)gLibSystemHelpers->startGlueToCallExit;
4958 else
4959 halt("libdyld.dylib support not present for LC_MAIN");
4960 }
4961 else {
4962 // main executable uses LC_UNIXTHREAD, dyld needs to let "start" in program set up for main()
4963 result = (uintptr_t)sMainExecutable->getMain();
4964 *startGlue = 0;
4965 }
4966 }
4967 catch(const char* message) {
4968 syncAllImages();
4969 halt(message);
4970 }
4971 catch(...) {
4972 dyld::log("dyld: launch failed\n");
4973 }
4974
4975 CRSetCrashLogMessage(NULL);
4976
4977 return result;
4978 }
4979
4980
4981
4982 } // namespace
4983
4984
4985