1 /* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*-
3 * Copyright (c) 2004-2013 Apple Inc. All rights reserved.
5 * @APPLE_LICENSE_HEADER_START@
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
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.
22 * @APPLE_LICENSE_HEADER_END@
33 #include <sys/param.h>
34 #include <mach/mach_time.h> // mach_absolute_time()
35 #include <mach/mach_init.h>
36 #include <sys/types.h>
38 #include <sys/syscall.h>
39 #include <sys/socket.h>
41 #include <sys/syslog.h>
43 #include <sys/xattr.h>
44 #include <mach/mach.h>
45 #include <mach-o/fat.h>
46 #include <mach-o/loader.h>
47 #include <mach-o/ldsyms.h>
48 #include <libkern/OSByteOrder.h>
49 #include <libkern/OSAtomic.h>
50 #include <mach/mach.h>
51 #include <sys/sysctl.h>
53 #include <sys/dtrace.h>
54 #include <libkern/OSAtomic.h>
55 #include <Availability.h>
56 #include <System/sys/codesign.h>
57 #include <System/sys/csr.h>
59 #include <os/lock_private.h>
60 #include <System/machine/cpu_capabilities.h>
61 #include <System/sys/reason.h>
62 #include <kern/kcdata.h>
64 #include <sandbox/private.h>
66 extern "C" int __fork();
72 #ifndef CPU_SUBTYPE_ARM_V5TEJ
73 #define CPU_SUBTYPE_ARM_V5TEJ ((cpu_subtype_t) 7)
75 #ifndef CPU_SUBTYPE_ARM_XSCALE
76 #define CPU_SUBTYPE_ARM_XSCALE ((cpu_subtype_t) 8)
78 #ifndef CPU_SUBTYPE_ARM_V7
79 #define CPU_SUBTYPE_ARM_V7 ((cpu_subtype_t) 9)
81 #ifndef CPU_SUBTYPE_ARM_V7F
82 #define CPU_SUBTYPE_ARM_V7F ((cpu_subtype_t) 10)
84 #ifndef CPU_SUBTYPE_ARM_V7S
85 #define CPU_SUBTYPE_ARM_V7S ((cpu_subtype_t) 11)
87 #ifndef CPU_SUBTYPE_ARM_V7K
88 #define CPU_SUBTYPE_ARM_V7K ((cpu_subtype_t) 12)
90 #ifndef LC_DYLD_ENVIRONMENT
91 #define LC_DYLD_ENVIRONMENT 0x27
94 #ifndef CPU_SUBTYPE_X86_64_H
95 #define CPU_SUBTYPE_X86_64_H ((cpu_subtype_t) 8)
98 #ifndef CPU_SUBTYPE_ARM64_E
99 #define CPU_SUBTYPE_ARM64_E 2
102 #ifndef VM_PROT_SLIDE
103 #define VM_PROT_SLIDE 0x20
106 #include "mach-o/dyld_gdb.h"
109 #include "ImageLoader.h"
110 #include "ImageLoaderMachO.h"
111 #include "dyldLibSystemInterface.h"
112 #include "dyld_cache_format.h"
113 #include "dyld_process_info_internal.h"
114 #include <coreSymbolicationDyldSupport.h>
115 #if TARGET_IPHONE_SIMULATOR
116 extern "C" void xcoresymbolication_load_notifier(void *connection
, uint64_t load_timestamp
, const char *image_path
, const struct mach_header
*mach_header
);
117 extern "C" void xcoresymbolication_unload_notifier(void *connection
, uint64_t unload_timestamp
, const char *image_path
, const struct mach_header
*mach_header
);
118 #define coresymbolication_load_notifier(c, t, p, h) xcoresymbolication_load_notifier(c, t, p, h)
119 #define coresymbolication_unload_notifier(c, t, p, h) xcoresymbolication_unload_notifier(c, t, p, h)
122 #if SUPPORT_ACCELERATE_TABLES
123 #include "ImageLoaderMegaDylib.h"
126 #if TARGET_IPHONE_SIMULATOR
127 extern "C" void* gSyscallHelpers
;
129 #include "dyldSyscallInterface.h"
132 #include "LaunchCache.h"
133 #include "libdyldEntryVector.h"
134 #include "MachOParser.h"
136 #include "DyldSharedCache.h"
137 #include "SharedCacheRuntime.h"
138 #include "StringUtils.h"
140 #include "DyldCacheParser.h"
143 #include "closuredProtocol.h"
147 // not libc header for send() syscall interface
148 extern "C" ssize_t
__sendto(int, const void *, size_t, int, const struct sockaddr
*, socklen_t
);
151 // ARM and x86_64 are the only architecture that use cpu-sub-types
152 #define CPU_SUBTYPES_SUPPORTED ((__arm__ || __arm64__ || __x86_64__) && !TARGET_IPHONE_SIMULATOR)
155 #define LC_SEGMENT_COMMAND LC_SEGMENT_64
156 #define LC_SEGMENT_COMMAND_WRONG LC_SEGMENT
157 #define LC_ENCRYPT_COMMAND LC_ENCRYPTION_INFO
158 #define macho_segment_command segment_command_64
159 #define macho_section section_64
161 #define LC_SEGMENT_COMMAND LC_SEGMENT
162 #define LC_SEGMENT_COMMAND_WRONG LC_SEGMENT_64
163 #define LC_ENCRYPT_COMMAND LC_ENCRYPTION_INFO_64
164 #define macho_segment_command segment_command
165 #define macho_section section
170 #define CPU_TYPE_MASK 0x00FFFFFF /* complement of CPU_ARCH_MASK */
173 /* implemented in dyld_gdb.cpp */
174 extern void resetAllImages();
175 extern void addImagesToAllImages(uint32_t infoCount
, const dyld_image_info info
[]);
176 extern void removeImageFromAllImages(const mach_header
* mh
);
177 extern void addNonSharedCacheImageUUID(const dyld_uuid_info
& info
);
178 extern const char* notifyGDB(enum dyld_image_states state
, uint32_t infoCount
, const dyld_image_info info
[]);
179 extern size_t allImagesCount();
181 // magic so CrashReporter logs message
183 char error_string
[1024];
186 // magic linker symbol for start of dyld binary
187 extern "C" const macho_header __dso_handle
;
191 // The file contains the core of dyld used to get a process to main().
192 // The API's that dyld supports are implemented in dyldAPIs.cpp.
199 struct RegisteredDOF
{ const mach_header
* mh
; int registrationID
; };
200 struct DylibOverride
{ const char* installName
; const char* override
; };
204 VECTOR_NEVER_DESTRUCTED(ImageLoader
*);
205 VECTOR_NEVER_DESTRUCTED(dyld::RegisteredDOF
);
206 VECTOR_NEVER_DESTRUCTED(dyld::ImageCallback
);
207 VECTOR_NEVER_DESTRUCTED(dyld::DylibOverride
);
208 VECTOR_NEVER_DESTRUCTED(ImageLoader::DynamicReference
);
210 VECTOR_NEVER_DESTRUCTED(dyld_image_state_change_handler
);
216 // state of all environment variables dyld uses
218 struct EnvironmentVariables
{
219 const char* const * DYLD_FRAMEWORK_PATH
;
220 const char* const * DYLD_FALLBACK_FRAMEWORK_PATH
;
221 const char* const * DYLD_LIBRARY_PATH
;
222 const char* const * DYLD_FALLBACK_LIBRARY_PATH
;
223 const char* const * DYLD_INSERT_LIBRARIES
;
224 const char* const * LD_LIBRARY_PATH
; // for unix conformance
225 const char* const * DYLD_VERSIONED_LIBRARY_PATH
;
226 const char* const * DYLD_VERSIONED_FRAMEWORK_PATH
;
227 bool DYLD_PRINT_LIBRARIES_POST_LAUNCH
;
228 bool DYLD_BIND_AT_LAUNCH
;
229 bool DYLD_PRINT_STATISTICS
;
230 bool DYLD_PRINT_STATISTICS_DETAILS
;
231 bool DYLD_PRINT_OPTS
;
233 bool DYLD_DISABLE_DOFS
;
234 bool DYLD_PRINT_CS_NOTIFICATIONS
;
235 // DYLD_SHARED_CACHE_DIR ==> sSharedCacheOverrideDir
236 // DYLD_ROOT_PATH ==> gLinkContext.rootPaths
237 // DYLD_IMAGE_SUFFIX ==> gLinkContext.imageSuffix
238 // DYLD_PRINT_OPTS ==> gLinkContext.verboseOpts
239 // DYLD_PRINT_ENV ==> gLinkContext.verboseEnv
240 // DYLD_FORCE_FLAT_NAMESPACE ==> gLinkContext.bindFlat
241 // DYLD_PRINT_INITIALIZERS ==> gLinkContext.verboseInit
242 // DYLD_PRINT_SEGMENTS ==> gLinkContext.verboseMapping
243 // DYLD_PRINT_BINDINGS ==> gLinkContext.verboseBind
244 // DYLD_PRINT_WEAK_BINDINGS ==> gLinkContext.verboseWeakBind
245 // DYLD_PRINT_REBASINGS ==> gLinkContext.verboseRebase
246 // DYLD_PRINT_DOFS ==> gLinkContext.verboseDOF
247 // DYLD_PRINT_APIS ==> gLogAPIs
248 // DYLD_IGNORE_PREBINDING ==> gLinkContext.prebindUsage
249 // DYLD_PREBIND_DEBUG ==> gLinkContext.verbosePrebinding
250 // DYLD_NEW_LOCAL_SHARED_REGIONS ==> gLinkContext.sharedRegionMode
251 // DYLD_SHARED_REGION ==> gLinkContext.sharedRegionMode
252 // DYLD_PRINT_WARNINGS ==> gLinkContext.verboseWarnings
253 // DYLD_PRINT_RPATHS ==> gLinkContext.verboseRPaths
254 // DYLD_PRINT_INTERPOSING ==> gLinkContext.verboseInterposing
255 // DYLD_PRINT_LIBRARIES ==> gLinkContext.verboseLoading
260 typedef std::vector
<dyld_image_state_change_handler
> StateHandlers
;
263 enum EnvVarMode
{ envNone
, envPrintOnly
, envAll
};
266 static const char* sExecPath
= NULL
;
267 static const char* sExecShortName
= NULL
;
268 static const macho_header
* sMainExecutableMachHeader
= NULL
;
269 static uintptr_t sMainExecutableSlide
= 0;
270 #if CPU_SUBTYPES_SUPPORTED
271 static cpu_type_t sHostCPU
;
272 static cpu_subtype_t sHostCPUsubtype
;
274 static ImageLoaderMachO
* sMainExecutable
= NULL
;
275 static EnvVarMode sEnvMode
= envNone
;
276 static size_t sInsertedDylibCount
= 0;
277 static std::vector
<ImageLoader
*> sAllImages
;
278 static std::vector
<ImageLoader
*> sImageRoots
;
279 static std::vector
<ImageLoader
*> sImageFilesNeedingTermination
;
280 static std::vector
<RegisteredDOF
> sImageFilesNeedingDOFUnregistration
;
281 static std::vector
<ImageCallback
> sAddImageCallbacks
;
282 static std::vector
<ImageCallback
> sRemoveImageCallbacks
;
283 static bool sRemoveImageCallbacksInUse
= false;
284 static void* sSingleHandlers
[7][3];
285 static void* sBatchHandlers
[7][3];
286 static ImageLoader
* sLastImageByAddressCache
;
287 static EnvironmentVariables sEnv
;
288 #if __MAC_OS_X_VERSION_MIN_REQUIRED
289 static const char* sFrameworkFallbackPaths
[] = { "$HOME/Library/Frameworks", "/Library/Frameworks", "/Network/Library/Frameworks", "/System/Library/Frameworks", NULL
};
290 static const char* sLibraryFallbackPaths
[] = { "$HOME/lib", "/usr/local/lib", "/usr/lib", NULL
};
291 static const char* sRestrictedFrameworkFallbackPaths
[] = { "/System/Library/Frameworks", NULL
};
292 static const char* sRestrictedLibraryFallbackPaths
[] = { "/usr/lib", NULL
};
294 static const char* sFrameworkFallbackPaths
[] = { "/System/Library/Frameworks", NULL
};
295 static const char* sLibraryFallbackPaths
[] = { "/usr/local/lib", "/usr/lib", NULL
};
297 static UndefinedHandler sUndefinedHandler
= NULL
;
298 static ImageLoader
* sBundleBeingLoaded
= NULL
; // hack until OFI is reworked
299 static dyld3::SharedCacheLoadInfo sSharedCacheLoadInfo
;
300 static const char* sSharedCacheOverrideDir
;
301 bool gSharedCacheOverridden
= false;
302 ImageLoader::LinkContext gLinkContext
;
303 bool gLogAPIs
= false;
304 #if SUPPORT_ACCELERATE_TABLES
305 bool gLogAppAPIs
= false;
307 const struct LibSystemHelpers
* gLibSystemHelpers
= NULL
;
308 #if SUPPORT_OLD_CRT_INITIALIZATION
309 bool gRunInitializersOldWay
= false;
311 static std::vector
<DylibOverride
> sDylibOverrides
;
312 #if !TARGET_IPHONE_SIMULATOR
313 static int sLogSocket
= -1;
315 static bool sFrameworksFoundAsDylibs
= false;
316 #if __x86_64__ && !TARGET_IPHONE_SIMULATOR
317 static bool sHaswell
= false;
319 static std::vector
<ImageLoader::DynamicReference
> sDynamicReferences
;
320 static OSSpinLock sDynamicReferencesLock
= 0;
321 #if !TARGET_IPHONE_SIMULATOR
322 static bool sLogToFile
= false;
324 static char sLoadingCrashMessage
[1024] = "dyld: launch, loading dependent libraries";
325 static bool sSafeMode
= false;
326 static _dyld_objc_notify_mapped sNotifyObjCMapped
;
327 static _dyld_objc_notify_init sNotifyObjCInit
;
328 static _dyld_objc_notify_unmapped sNotifyObjCUnmapped
;
330 #if __IPHONE_OS_VERSION_MIN_REQUIRED && !TARGET_IPHONE_SIMULATOR
331 static bool sForceStderr
= false;
335 #if SUPPORT_ACCELERATE_TABLES
336 static ImageLoaderMegaDylib
* sAllCacheImagesProxy
= NULL
;
337 static bool sDisableAcceleratorTables
= false;
340 bool gUseDyld3
= false;
341 static bool sSkipMain
= false;
342 static bool sEnableClosures
= false;
345 // The MappedRanges structure is used for fast address->image lookups.
346 // The table is only updated when the dyld lock is held, so we don't
347 // need to worry about multiple writers. But readers may look at this
348 // data without holding the lock. Therefore, all updates must be done
349 // in an order that will never cause readers to see inconsistent data.
350 // The general rule is that if the image field is non-NULL then
351 // the other fields are valid.
364 static MappedRanges
* sMappedRangesStart
;
366 void addMappedRange(ImageLoader
* image
, uintptr_t start
, uintptr_t end
)
368 //dyld::log("addMappedRange(0x%lX->0x%lX) for %s\n", start, end, image->getShortName());
369 for (MappedRanges
* p
= sMappedRangesStart
; p
!= NULL
; p
= p
->next
) {
370 for (unsigned long i
=0; i
< p
->count
; ++i
) {
371 if ( p
->array
[i
].image
== NULL
) {
372 p
->array
[i
].start
= start
;
373 p
->array
[i
].end
= end
;
374 // add image field last with a barrier so that any reader will see consistent records
376 p
->array
[i
].image
= image
;
381 // table must be full, chain another
382 #if SUPPORT_ACCELERATE_TABLES
383 unsigned count
= (sAllCacheImagesProxy
!= NULL
) ? 16 : 400;
385 unsigned count
= 400;
387 size_t allocationSize
= sizeof(MappedRanges
) + (count
-1)*3*sizeof(void*);
388 MappedRanges
* newRanges
= (MappedRanges
*)malloc(allocationSize
);
389 bzero(newRanges
, allocationSize
);
390 newRanges
->count
= count
;
391 newRanges
->array
[0].start
= start
;
392 newRanges
->array
[0].end
= end
;
393 newRanges
->array
[0].image
= image
;
395 if ( sMappedRangesStart
== NULL
) {
396 sMappedRangesStart
= newRanges
;
399 for (MappedRanges
* p
= sMappedRangesStart
; p
!= NULL
; p
= p
->next
) {
400 if ( p
->next
== NULL
) {
409 void removedMappedRanges(ImageLoader
* image
)
411 for (MappedRanges
* p
= sMappedRangesStart
; p
!= NULL
; p
= p
->next
) {
412 for (unsigned long i
=0; i
< p
->count
; ++i
) {
413 if ( p
->array
[i
].image
== image
) {
414 // clear with a barrier so that any reader will see consistent records
416 p
->array
[i
].image
= NULL
;
422 ImageLoader
* findMappedRange(uintptr_t target
)
424 for (MappedRanges
* p
= sMappedRangesStart
; p
!= NULL
; p
= p
->next
) {
425 for (unsigned long i
=0; i
< p
->count
; ++i
) {
426 if ( p
->array
[i
].image
!= NULL
) {
427 if ( (p
->array
[i
].start
<= target
) && (target
< p
->array
[i
].end
) )
428 return p
->array
[i
].image
;
437 const char* mkstringf(const char* format
, ...)
439 _SIMPLE_STRING buf
= _simple_salloc();
442 va_start(list
, format
);
443 _simple_vsprintf(buf
, format
, list
);
445 const char* t
= strdup(_simple_string(buf
));
450 return "mkstringf, out of memory error";
454 void throwf(const char* format
, ...)
456 _SIMPLE_STRING buf
= _simple_salloc();
459 va_start(list
, format
);
460 _simple_vsprintf(buf
, format
, list
);
462 const char* t
= strdup(_simple_string(buf
));
467 throw "throwf, out of memory error";
471 #if !TARGET_IPHONE_SIMULATOR
472 static int sLogfile
= STDERR_FILENO
;
475 #if !TARGET_IPHONE_SIMULATOR
476 // based on CFUtilities.c: also_do_stderr()
477 static bool useSyslog()
479 // Use syslog() for processes managed by launchd
480 static bool launchdChecked
= false;
481 static bool launchdOwned
= false;
482 if ( !launchdChecked
&& gProcessInfo
->libSystemInitialized
) {
483 if ( (gLibSystemHelpers
!= NULL
) && (gLibSystemHelpers
->version
>= 11) ) {
484 // <rdar://problem/23520449> only call isLaunchdOwned() after libSystem is initialized
485 launchdOwned
= (*gLibSystemHelpers
->isLaunchdOwned
)();
486 launchdChecked
= true;
489 if ( launchdChecked
&& launchdOwned
)
492 // If stderr is not available, use syslog()
494 int result
= fstat(STDERR_FILENO
, &sb
);
496 return true; // file descriptor 2 is closed
502 static void socket_syslogv(int priority
, const char* format
, va_list list
)
504 // lazily create socket and connection to syslogd
505 if ( sLogSocket
== -1 ) {
506 sLogSocket
= ::socket(AF_UNIX
, SOCK_DGRAM
, 0);
507 if (sLogSocket
== -1)
508 return; // cannot log
509 ::fcntl(sLogSocket
, F_SETFD
, 1);
511 struct sockaddr_un addr
;
512 addr
.sun_family
= AF_UNIX
;
513 strncpy(addr
.sun_path
, _PATH_LOG
, sizeof(addr
.sun_path
));
514 if ( ::connect(sLogSocket
, (struct sockaddr
*)&addr
, sizeof(addr
)) == -1 ) {
521 // format message to syslogd like: "<priority>Process[pid]: message"
522 _SIMPLE_STRING buf
= _simple_salloc();
525 if ( _simple_sprintf(buf
, "<%d>%s[%d]: ", LOG_USER
|LOG_NOTICE
, sExecShortName
, getpid()) == 0 ) {
526 if ( _simple_vsprintf(buf
, format
, list
) == 0 ) {
527 const char* p
= _simple_string(buf
);
528 ::__sendto(sLogSocket
, p
, strlen(p
), 0, NULL
, 0);
536 void vlog(const char* format
, va_list list
)
538 #if __IPHONE_OS_VERSION_MIN_REQUIRED && !TARGET_IPHONE_SIMULATOR
539 // <rdar://problem/25965832> log to console when running iOS app from Xcode
540 if ( !sLogToFile
&& !sForceStderr
&& useSyslog() )
542 if ( !sLogToFile
&& useSyslog() )
544 socket_syslogv(LOG_ERR
, format
, list
);
546 _simple_vdprintf(sLogfile
, format
, list
);
550 void log(const char* format
, ...)
553 va_start(list
, format
);
559 void vwarn(const char* format
, va_list list
)
561 _simple_dprintf(sLogfile
, "dyld: warning, ");
562 _simple_vdprintf(sLogfile
, format
, list
);
565 void warn(const char* format
, ...)
568 va_start(list
, format
);
574 extern void vlog(const char* format
, va_list list
);
575 #endif // !TARGET_IPHONE_SIMULATOR
578 // <rdar://problem/8867781> control access to sAllImages through a lock
579 // because global dyld lock is not held during initialization phase of dlopen()
580 // <rdar://problem/16145518> Use OSSpinLockLock to allow yielding
581 static OSSpinLock sAllImagesLock
= 0;
583 static void allImagesLock()
585 OSSpinLockLock(&sAllImagesLock
);
588 static void allImagesUnlock()
590 OSSpinLockUnlock(&sAllImagesLock
);
594 // utility class to assure files are closed when an exception is thrown
597 FileOpener(const char* path
);
599 int getFileDescriptor() { return fd
; }
604 FileOpener::FileOpener(const char* path
)
607 fd
= my_open(path
, O_RDONLY
, 0);
610 FileOpener::~FileOpener()
617 static void registerDOFs(const std::vector
<ImageLoader::DOFInfo
>& dofs
)
619 const size_t dofSectionCount
= dofs
.size();
620 if ( !sEnv
.DYLD_DISABLE_DOFS
&& (dofSectionCount
!= 0) ) {
621 int fd
= open("/dev/" DTRACEMNR_HELPER
, O_RDWR
);
623 //dyld::warn("can't open /dev/" DTRACEMNR_HELPER " to register dtrace DOF sections\n");
626 // allocate a buffer on the stack for the variable length dof_ioctl_data_t type
627 uint8_t buffer
[sizeof(dof_ioctl_data_t
) + dofSectionCount
*sizeof(dof_helper_t
)];
628 dof_ioctl_data_t
* ioctlData
= (dof_ioctl_data_t
*)buffer
;
630 // fill in buffer with one dof_helper_t per DOF section
631 ioctlData
->dofiod_count
= dofSectionCount
;
632 for (unsigned int i
=0; i
< dofSectionCount
; ++i
) {
633 strlcpy(ioctlData
->dofiod_helpers
[i
].dofhp_mod
, dofs
[i
].imageShortName
, DTRACE_MODNAMELEN
);
634 ioctlData
->dofiod_helpers
[i
].dofhp_dof
= (uintptr_t)(dofs
[i
].dof
);
635 ioctlData
->dofiod_helpers
[i
].dofhp_addr
= (uintptr_t)(dofs
[i
].dof
);
638 // tell kernel about all DOF sections en mas
639 // pass pointer to ioctlData because ioctl() only copies a fixed size amount of data into kernel
640 user_addr_t val
= (user_addr_t
)(unsigned long)ioctlData
;
641 if ( ioctl(fd
, DTRACEHIOC_ADDDOF
, &val
) != -1 ) {
642 // kernel returns a unique identifier for each section in the dofiod_helpers[].dofhp_dof field.
643 for (unsigned int i
=0; i
< dofSectionCount
; ++i
) {
645 info
.mh
= dofs
[i
].imageHeader
;
646 info
.registrationID
= (int)(ioctlData
->dofiod_helpers
[i
].dofhp_dof
);
647 sImageFilesNeedingDOFUnregistration
.push_back(info
);
648 if ( gLinkContext
.verboseDOF
) {
649 dyld::log("dyld: registering DOF section %p in %s with dtrace, ID=0x%08X\n",
650 dofs
[i
].dof
, dofs
[i
].imageShortName
, info
.registrationID
);
655 //dyld::log( "dyld: ioctl to register dtrace DOF section failed\n");
662 static void unregisterDOF(int registrationID
)
664 int fd
= open("/dev/" DTRACEMNR_HELPER
, O_RDWR
);
666 dyld::warn("can't open /dev/" DTRACEMNR_HELPER
" to unregister dtrace DOF section\n");
669 ioctl(fd
, DTRACEHIOC_REMOVE
, registrationID
);
671 if ( gLinkContext
.verboseInit
)
672 dyld::warn("unregistering DOF section ID=0x%08X with dtrace\n", registrationID
);
678 // _dyld_register_func_for_add_image() is implemented as part of the general image state change notification
680 static void notifyAddImageCallbacks(ImageLoader
* image
)
682 // use guard so that we cannot notify about the same image twice
683 if ( ! image
->addFuncNotified() ) {
684 for (std::vector
<ImageCallback
>::iterator it
=sAddImageCallbacks
.begin(); it
!= sAddImageCallbacks
.end(); it
++)
685 (*it
)(image
->machHeader(), image
->getSlide());
686 image
->setAddFuncNotified();
692 // notify gdb about these new images
693 static const char* updateAllImages(enum dyld_image_states state
, uint32_t infoCount
, const struct dyld_image_info info
[])
695 // <rdar://problem/8812589> don't add images without paths to all-image-info-list
696 if ( info
[0].imageFilePath
!= NULL
)
697 addImagesToAllImages(infoCount
, info
);
702 static StateHandlers
* stateToHandlers(dyld_image_states state
, void* handlersArray
[7][3])
705 case dyld_image_state_mapped
:
706 return reinterpret_cast<StateHandlers
*>(&handlersArray
[0]);
708 case dyld_image_state_dependents_mapped
:
709 return reinterpret_cast<StateHandlers
*>(&handlersArray
[1]);
711 case dyld_image_state_rebased
:
712 return reinterpret_cast<StateHandlers
*>(&handlersArray
[2]);
714 case dyld_image_state_bound
:
715 return reinterpret_cast<StateHandlers
*>(&handlersArray
[3]);
717 case dyld_image_state_dependents_initialized
:
718 return reinterpret_cast<StateHandlers
*>(&handlersArray
[4]);
720 case dyld_image_state_initialized
:
721 return reinterpret_cast<StateHandlers
*>(&handlersArray
[5]);
723 case dyld_image_state_terminated
:
724 return reinterpret_cast<StateHandlers
*>(&handlersArray
[6]);
729 #if SUPPORT_ACCELERATE_TABLES
730 static dyld_image_state_change_handler
getPreInitNotifyHandler(unsigned index
)
732 std::vector
<dyld_image_state_change_handler
>* handlers
= stateToHandlers(dyld_image_state_dependents_initialized
, sSingleHandlers
);
733 if ( index
>= handlers
->size() )
735 return (*handlers
)[index
];
738 static dyld_image_state_change_handler
getBoundBatchHandler(unsigned index
)
740 std::vector
<dyld_image_state_change_handler
>* handlers
= stateToHandlers(dyld_image_state_bound
, sBatchHandlers
);
741 if ( index
>= handlers
->size() )
743 return (*handlers
)[index
];
746 static void notifySingleFromCache(dyld_image_states state
, const mach_header
* mh
, const char* path
)
748 //dyld::log("notifySingle(state=%d, image=%s)\n", state, image->getPath());
749 std::vector
<dyld_image_state_change_handler
>* handlers
= stateToHandlers(state
, sSingleHandlers
);
750 if ( handlers
!= NULL
) {
751 dyld_image_info info
;
752 info
.imageLoadAddress
= mh
;
753 info
.imageFilePath
= path
;
754 info
.imageFileModDate
= 0;
755 for (dyld_image_state_change_handler handler
: *handlers
) {
756 const char* result
= (*handler
)(state
, 1, &info
);
757 if ( (result
!= NULL
) && (state
== dyld_image_state_mapped
) ) {
758 //fprintf(stderr, " image rejected by handler=%p\n", *it);
759 // make copy of thrown string so that later catch clauses can free it
760 const char* str
= strdup(result
);
765 if ( (state
== dyld_image_state_dependents_initialized
) && (sNotifyObjCInit
!= NULL
) && (mh
->flags
& MH_HAS_OBJC
) ) {
766 (*sNotifyObjCInit
)(path
, mh
);
771 static mach_port_t sNotifyReplyPorts
[DYLD_MAX_PROCESS_INFO_NOTIFY_COUNT
];
772 static bool sZombieNotifiers
[DYLD_MAX_PROCESS_INFO_NOTIFY_COUNT
];
774 static void notifyMonitoringDyld(bool unloading
, unsigned portSlot
, unsigned imageCount
, const dyld_image_info infos
[])
776 if ( sZombieNotifiers
[portSlot
] )
779 unsigned entriesSize
= imageCount
*sizeof(dyld_process_info_image_entry
);
780 unsigned pathsSize
= 0;
781 for (unsigned j
=0; j
< imageCount
; ++j
) {
782 pathsSize
+= (strlen(infos
[j
].imageFilePath
) + 1);
784 unsigned totalSize
= (sizeof(dyld_process_info_notify_header
) + MAX_TRAILER_SIZE
+ entriesSize
+ pathsSize
+ 127) & -128; // align
785 if ( totalSize
> DYLD_PROCESS_INFO_NOTIFY_MAX_BUFFER_SIZE
) {
786 // Putting all image paths into one message would make buffer too big.
787 // Instead split into two messages. Recurse as needed until paths fit in buffer.
788 unsigned imageHalfCount
= imageCount
/2;
789 notifyMonitoringDyld(unloading
, portSlot
, imageHalfCount
, infos
);
790 notifyMonitoringDyld(unloading
, portSlot
, imageCount
- imageHalfCount
, &infos
[imageHalfCount
]);
793 uint8_t buffer
[totalSize
];
794 dyld_process_info_notify_header
* header
= (dyld_process_info_notify_header
*)buffer
;
796 header
->imageCount
= imageCount
;
797 header
->imagesOffset
= sizeof(dyld_process_info_notify_header
);
798 header
->stringsOffset
= sizeof(dyld_process_info_notify_header
) + entriesSize
;
799 header
->timestamp
= dyld::gProcessInfo
->infoArrayChangeTimestamp
;
800 dyld_process_info_image_entry
* entries
= (dyld_process_info_image_entry
*)&buffer
[header
->imagesOffset
];
801 char* const pathPoolStart
= (char*)&buffer
[header
->stringsOffset
];
802 char* pathPool
= pathPoolStart
;
803 for (unsigned j
=0; j
< imageCount
; ++j
) {
804 strcpy(pathPool
, infos
[j
].imageFilePath
);
805 uint32_t len
= (uint32_t)strlen(pathPool
);
806 bzero(entries
->uuid
, 16);
807 const ImageLoader
* image
= findImageByMachHeader(infos
[j
].imageLoadAddress
);
808 if ( image
!= NULL
) {
809 image
->getUUID(entries
->uuid
);
811 #if SUPPORT_ACCELERATE_TABLES
812 else if ( sAllCacheImagesProxy
!= NULL
) {
813 const mach_header
* mh
;
816 if ( sAllCacheImagesProxy
->addressInCache(infos
[j
].imageLoadAddress
, &mh
, &path
, &index
) ) {
817 sAllCacheImagesProxy
->getDylibUUID(index
, entries
->uuid
);
821 entries
->loadAddress
= (uint64_t)infos
[j
].imageLoadAddress
;
822 entries
->pathStringOffset
= (uint32_t)(pathPool
- pathPoolStart
);
823 entries
->pathLength
= len
;
824 pathPool
+= (len
+1);
828 if ( sNotifyReplyPorts
[portSlot
] == 0 ) {
829 if ( !mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_RECEIVE
, &sNotifyReplyPorts
[portSlot
]) )
830 mach_port_insert_right(mach_task_self(), sNotifyReplyPorts
[portSlot
], sNotifyReplyPorts
[portSlot
], MACH_MSG_TYPE_MAKE_SEND
);
831 //dyld::log("allocated reply port %d\n", sNotifyReplyPorts[portSlot]);
833 //dyld::log("found port to send to\n");
834 mach_msg_header_t
* h
= (mach_msg_header_t
*)buffer
;
835 h
->msgh_bits
= MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND
,MACH_MSG_TYPE_MAKE_SEND
); // MACH_MSG_TYPE_MAKE_SEND_ONCE
836 h
->msgh_id
= unloading
? DYLD_PROCESS_INFO_NOTIFY_UNLOAD_ID
: DYLD_PROCESS_INFO_NOTIFY_LOAD_ID
;
837 h
->msgh_local_port
= sNotifyReplyPorts
[portSlot
];
838 h
->msgh_remote_port
= dyld::gProcessInfo
->notifyPorts
[portSlot
];
839 h
->msgh_reserved
= 0;
840 h
->msgh_size
= (mach_msg_size_t
)sizeof(buffer
);
841 //dyld::log("sending to port[%d]=%d, size=%d, reply port=%d, id=0x%X\n", portSlot, dyld::gProcessInfo->notifyPorts[portSlot], h->msgh_size, sNotifyReplyPorts[portSlot], h->msgh_id);
842 kern_return_t sendResult
= mach_msg(h
, MACH_SEND_MSG
| MACH_RCV_MSG
| MACH_RCV_TIMEOUT
, h
->msgh_size
, h
->msgh_size
, sNotifyReplyPorts
[portSlot
], 5000, MACH_PORT_NULL
);
843 //dyld::log("send result = 0x%X, msg_id=%d, msg_size=%d\n", sendResult, h->msgh_id, h->msgh_size);
844 if ( sendResult
== MACH_SEND_INVALID_DEST
) {
845 // sender is not responding, detatch
846 //dyld::log("process requesting notification gone. deallocation send port %d and receive port %d\n", dyld::gProcessInfo->notifyPorts[portSlot], sNotifyReplyPorts[portSlot]);
847 mach_port_deallocate(mach_task_self(), dyld::gProcessInfo
->notifyPorts
[portSlot
]);
848 mach_port_deallocate(mach_task_self(), sNotifyReplyPorts
[portSlot
]);
849 dyld::gProcessInfo
->notifyPorts
[portSlot
] = 0;
850 sNotifyReplyPorts
[portSlot
] = 0;
852 else if ( sendResult
== MACH_RCV_TIMED_OUT
) {
853 // client took too long, ignore him from now on
854 sZombieNotifiers
[portSlot
] = true;
855 mach_port_deallocate(mach_task_self(), sNotifyReplyPorts
[portSlot
]);
856 sNotifyReplyPorts
[portSlot
] = 0;
860 static void notifyMonitoringDyldMain()
862 for (int slot
=0; slot
< DYLD_MAX_PROCESS_INFO_NOTIFY_COUNT
; ++slot
) {
863 if ( (dyld::gProcessInfo
->notifyPorts
[slot
] != 0 ) && !sZombieNotifiers
[slot
] ) {
864 if ( sNotifyReplyPorts
[slot
] == 0 ) {
865 if ( !mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_RECEIVE
, &sNotifyReplyPorts
[slot
]) )
866 mach_port_insert_right(mach_task_self(), sNotifyReplyPorts
[slot
], sNotifyReplyPorts
[slot
], MACH_MSG_TYPE_MAKE_SEND
);
867 //dyld::log("allocated reply port %d\n", sNotifyReplyPorts[slot]);
869 //dyld::log("found port to send to\n");
870 uint8_t messageBuffer
[sizeof(mach_msg_header_t
) + MAX_TRAILER_SIZE
];
871 mach_msg_header_t
* h
= (mach_msg_header_t
*)messageBuffer
;
872 h
->msgh_bits
= MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND
,MACH_MSG_TYPE_MAKE_SEND
); // MACH_MSG_TYPE_MAKE_SEND_ONCE
873 h
->msgh_id
= DYLD_PROCESS_INFO_NOTIFY_MAIN_ID
;
874 h
->msgh_local_port
= sNotifyReplyPorts
[slot
];
875 h
->msgh_remote_port
= dyld::gProcessInfo
->notifyPorts
[slot
];
876 h
->msgh_reserved
= 0;
877 h
->msgh_size
= (mach_msg_size_t
)sizeof(messageBuffer
);
878 //dyld::log("sending to port[%d]=%d, size=%d, reply port=%d, id=0x%X\n", slot, dyld::gProcessInfo->notifyPorts[slot], h->msgh_size, sNotifyReplyPorts[slot], h->msgh_id);
879 kern_return_t sendResult
= mach_msg(h
, MACH_SEND_MSG
| MACH_RCV_MSG
| MACH_RCV_TIMEOUT
, h
->msgh_size
, h
->msgh_size
, sNotifyReplyPorts
[slot
], 5000, MACH_PORT_NULL
);
880 //dyld::log("send result = 0x%X, msg_id=%d, msg_size=%d\n", sendResult, h->msgh_id, h->msgh_size);
881 if ( sendResult
== MACH_SEND_INVALID_DEST
) {
882 // sender is not responding, detatch
883 //dyld::log("process requesting notification gone. deallocation send port %d and receive port %d\n", dyld::gProcessInfo->notifyPorts[slot], sNotifyReplyPorts[slot]);
884 mach_port_deallocate(mach_task_self(), dyld::gProcessInfo
->notifyPorts
[slot
]);
885 mach_port_deallocate(mach_task_self(), sNotifyReplyPorts
[slot
]);
886 dyld::gProcessInfo
->notifyPorts
[slot
] = 0;
887 sNotifyReplyPorts
[slot
] = 0;
889 else if ( sendResult
== MACH_RCV_TIMED_OUT
) {
890 // client took too long, ignore him from now on
891 sZombieNotifiers
[slot
] = true;
892 mach_port_deallocate(mach_task_self(), sNotifyReplyPorts
[slot
]);
893 sNotifyReplyPorts
[slot
] = 0;
899 void notifyKernel(const ImageLoader
& image
, bool loading
) {
900 if ( !image
.inSharedCache() ) {
901 uint32_t baseCode
= loading
? DBG_DYLD_UUID_MAP_A
: DBG_DYLD_UUID_UNMAP_A
;
903 ino_t inode
= image
.getInode();
905 dyld3::kdebug_trace_dyld_image(baseCode
, (const uuid_t
*)&uuid
, *(fsobj_id_t
*)&inode
, {{ image
.getDevice(), 0 }}, image
.machHeader());
909 static void notifySingle(dyld_image_states state
, const ImageLoader
* image
, ImageLoader::InitializerTimingList
* timingInfo
)
911 //dyld::log("notifySingle(state=%d, image=%s)\n", state, image->getPath());
912 std::vector
<dyld_image_state_change_handler
>* handlers
= stateToHandlers(state
, sSingleHandlers
);
913 if ( handlers
!= NULL
) {
914 dyld_image_info info
;
915 info
.imageLoadAddress
= image
->machHeader();
916 info
.imageFilePath
= image
->getRealPath();
917 info
.imageFileModDate
= image
->lastModified();
918 for (std::vector
<dyld_image_state_change_handler
>::iterator it
= handlers
->begin(); it
!= handlers
->end(); ++it
) {
919 const char* result
= (*it
)(state
, 1, &info
);
920 if ( (result
!= NULL
) && (state
== dyld_image_state_mapped
) ) {
921 //fprintf(stderr, " image rejected by handler=%p\n", *it);
922 // make copy of thrown string so that later catch clauses can free it
923 const char* str
= strdup(result
);
928 if ( state
== dyld_image_state_mapped
) {
929 // <rdar://problem/7008875> Save load addr + UUID for images from outside the shared cache
930 if ( !image
->inSharedCache() ) {
932 if ( image
->getUUID(info
.imageUUID
) ) {
933 info
.imageLoadAddress
= image
->machHeader();
934 addNonSharedCacheImageUUID(info
);
938 if ( (state
== dyld_image_state_dependents_initialized
) && (sNotifyObjCInit
!= NULL
) && image
->notifyObjC() ) {
939 uint64_t t0
= mach_absolute_time();
940 (*sNotifyObjCInit
)(image
->getRealPath(), image
->machHeader());
941 uint64_t t1
= mach_absolute_time();
942 uint64_t t2
= mach_absolute_time();
943 uint64_t timeInObjC
= t1
-t0
;
944 uint64_t emptyTime
= (t2
-t1
)*100;
945 if ( (timeInObjC
> emptyTime
) && (timingInfo
!= NULL
) ) {
946 timingInfo
->addTime(image
->getShortName(), timeInObjC
);
949 // mach message csdlc about dynamically unloaded images
950 if ( image
->addFuncNotified() && (state
== dyld_image_state_terminated
) ) {
951 notifyKernel(*image
, false);
953 uint64_t loadTimestamp
= mach_absolute_time();
954 if ( sEnv
.DYLD_PRINT_CS_NOTIFICATIONS
) {
955 dyld::log("dyld: coresymbolication_unload_notifier(%p, 0x%016llX, %p, %s)\n",
956 dyld::gProcessInfo
->coreSymbolicationShmPage
, loadTimestamp
, image
->machHeader(), image
->getPath());
958 if ( dyld::gProcessInfo
->coreSymbolicationShmPage
!= NULL
) {
959 coresymbolication_unload_notifier(dyld::gProcessInfo
->coreSymbolicationShmPage
, loadTimestamp
, image
->getPath(), image
->machHeader());
961 for (int slot
=0; slot
< DYLD_MAX_PROCESS_INFO_NOTIFY_COUNT
; ++slot
) {
962 if ( dyld::gProcessInfo
->notifyPorts
[slot
] != 0 ) {
963 dyld_image_info info
;
964 info
.imageLoadAddress
= image
->machHeader();
965 info
.imageFilePath
= image
->getPath();
966 info
.imageFileModDate
= 0;
967 notifyMonitoringDyld(true, slot
, 1, &info
);
969 else if ( sNotifyReplyPorts
[slot
] != 0 ) {
970 // monitoring process detached from this process, so release reply port
971 //dyld::log("deallocated reply port %d\n", sNotifyReplyPorts[slot]);
972 mach_port_deallocate(mach_task_self(), sNotifyReplyPorts
[slot
]);
973 sNotifyReplyPorts
[slot
] = 0;
974 sZombieNotifiers
[slot
] = false;
983 // Normally, dyld_all_image_infos is only updated in batches after an entire
984 // graph is loaded. But if there is an error loading the initial set of
985 // dylibs needed by the main executable, dyld_all_image_infos is not yet set
986 // up, leading to usually brief crash logs.
988 // This function manually adds the images loaded so far to dyld::gProcessInfo.
989 // It should only be called before terminating.
993 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); ++it
) {
994 dyld_image_info info
;
995 ImageLoader
* image
= *it
;
996 info
.imageLoadAddress
= image
->machHeader();
997 info
.imageFilePath
= image
->getRealPath();
998 info
.imageFileModDate
= image
->lastModified();
999 // add to all_image_infos if not already there
1001 int existingCount
= dyld::gProcessInfo
->infoArrayCount
;
1002 const dyld_image_info
* existing
= dyld::gProcessInfo
->infoArray
;
1003 if ( existing
!= NULL
) {
1004 for (int i
=0; i
< existingCount
; ++i
) {
1005 if ( existing
[i
].imageLoadAddress
== info
.imageLoadAddress
) {
1006 //dyld::log("not adding %s\n", info.imageFilePath);
1013 //dyld::log("adding %s\n", info.imageFilePath);
1014 addImagesToAllImages(1, &info
);
1020 static int imageSorter(const void* l
, const void* r
)
1022 const ImageLoader
* left
= *((ImageLoader
**)l
);
1023 const ImageLoader
* right
= *((ImageLoader
**)r
);
1024 return left
->compare(right
);
1027 static void notifyBatchPartial(dyld_image_states state
, bool orLater
, dyld_image_state_change_handler onlyHandler
, bool preflightOnly
, bool onlyObjCMappedNotification
)
1029 std::vector
<dyld_image_state_change_handler
>* handlers
= stateToHandlers(state
, sBatchHandlers
);
1030 if ( (handlers
!= NULL
) || ((state
== dyld_image_state_bound
) && (sNotifyObjCMapped
!= NULL
)) ) {
1031 // don't use a vector because it will use malloc/free and we want notifcation to be low cost
1033 dyld_image_info infos
[allImagesCount()+1];
1034 ImageLoader
* images
[allImagesCount()+1];
1035 ImageLoader
** end
= images
;
1036 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
1037 dyld_image_states imageState
= (*it
)->getState();
1038 if ( (imageState
== state
) || (orLater
&& (imageState
> state
)) )
1041 if ( sBundleBeingLoaded
!= NULL
) {
1042 dyld_image_states imageState
= sBundleBeingLoaded
->getState();
1043 if ( (imageState
== state
) || (orLater
&& (imageState
> state
)) )
1044 *end
++ = sBundleBeingLoaded
;
1046 const char* dontLoadReason
= NULL
;
1047 uint32_t imageCount
= (uint32_t)(end
-images
);
1048 if ( imageCount
!= 0 ) {
1050 qsort(images
, imageCount
, sizeof(ImageLoader
*), &imageSorter
);
1052 for (unsigned int i
=0; i
< imageCount
; ++i
) {
1053 dyld_image_info
* p
= &infos
[i
];
1054 ImageLoader
* image
= images
[i
];
1055 //dyld::log(" state=%d, name=%s\n", state, image->getPath());
1056 p
->imageLoadAddress
= image
->machHeader();
1057 p
->imageFilePath
= image
->getRealPath();
1058 p
->imageFileModDate
= image
->lastModified();
1059 // get these registered with the kernel as early as possible
1060 if ( state
== dyld_image_state_dependents_mapped
)
1061 notifyKernel(*image
, true);
1062 // special case for add_image hook
1063 if ( state
== dyld_image_state_bound
)
1064 notifyAddImageCallbacks(image
);
1067 #if SUPPORT_ACCELERATE_TABLES
1068 if ( sAllCacheImagesProxy
!= NULL
) {
1069 unsigned cacheCount
= sAllCacheImagesProxy
->appendImagesToNotify(state
, orLater
, &infos
[imageCount
]);
1070 // support _dyld_register_func_for_add_image()
1071 if ( state
== dyld_image_state_bound
) {
1072 for (ImageCallback callback
: sAddImageCallbacks
) {
1073 for (unsigned i
=0; i
< cacheCount
; ++i
)
1074 (*callback
)(infos
[imageCount
+i
].imageLoadAddress
, sSharedCacheLoadInfo
.slide
);
1077 imageCount
+= cacheCount
;
1080 if ( imageCount
!= 0 ) {
1081 if ( !onlyObjCMappedNotification
) {
1082 if ( onlyHandler
!= NULL
) {
1083 const char* result
= NULL
;
1084 if ( result
== NULL
) {
1085 result
= (*onlyHandler
)(state
, imageCount
, infos
);
1087 if ( (result
!= NULL
) && (state
== dyld_image_state_dependents_mapped
) ) {
1088 //fprintf(stderr, " images rejected by handler=%p\n", onlyHandler);
1089 // make copy of thrown string so that later catch clauses can free it
1090 dontLoadReason
= strdup(result
);
1094 // call each handler with whole array
1095 if ( handlers
!= NULL
) {
1096 for (std::vector
<dyld_image_state_change_handler
>::iterator it
= handlers
->begin(); it
!= handlers
->end(); ++it
) {
1097 const char* result
= (*it
)(state
, imageCount
, infos
);
1098 if ( (result
!= NULL
) && (state
== dyld_image_state_dependents_mapped
) ) {
1099 //fprintf(stderr, " images rejected by handler=%p\n", *it);
1100 // make copy of thrown string so that later catch clauses can free it
1101 dontLoadReason
= strdup(result
);
1108 // tell objc about new images
1109 if ( (onlyHandler
== NULL
) && ((state
== dyld_image_state_bound
) || (orLater
&& (dyld_image_state_bound
> state
))) && (sNotifyObjCMapped
!= NULL
) ) {
1110 const char* paths
[imageCount
];
1111 const mach_header
* mhs
[imageCount
];
1112 unsigned objcImageCount
= 0;
1113 for (int i
=0; i
< imageCount
; ++i
) {
1114 const ImageLoader
* image
= findImageByMachHeader(infos
[i
].imageLoadAddress
);
1115 bool hasObjC
= false;
1116 if ( image
!= NULL
) {
1117 hasObjC
= image
->notifyObjC();
1119 #if SUPPORT_ACCELERATE_TABLES
1120 else if ( sAllCacheImagesProxy
!= NULL
) {
1121 const mach_header
* mh
;
1124 if ( sAllCacheImagesProxy
->addressInCache(infos
[i
].imageLoadAddress
, &mh
, &path
, &index
) ) {
1125 hasObjC
= (mh
->flags
& MH_HAS_OBJC
);
1130 paths
[objcImageCount
] = infos
[i
].imageFilePath
;
1131 mhs
[objcImageCount
] = infos
[i
].imageLoadAddress
;
1135 if ( objcImageCount
!= 0 ) {
1136 uint64_t t0
= mach_absolute_time();
1137 (*sNotifyObjCMapped
)(objcImageCount
, paths
, mhs
);
1138 uint64_t t1
= mach_absolute_time();
1139 ImageLoader::fgTotalObjCSetupTime
+= (t1
-t0
);
1144 if ( dontLoadReason
!= NULL
)
1145 throw dontLoadReason
;
1146 if ( !preflightOnly
&& (state
== dyld_image_state_dependents_mapped
) ) {
1147 if ( (dyld::gProcessInfo
->coreSymbolicationShmPage
!= NULL
) || sEnv
.DYLD_PRINT_CS_NOTIFICATIONS
) {
1148 // mach message csdlc about loaded images
1149 uint64_t loadTimestamp
= mach_absolute_time();
1150 for (unsigned j
=0; j
< imageCount
; ++j
) {
1151 if ( sEnv
.DYLD_PRINT_CS_NOTIFICATIONS
) {
1152 dyld::log("dyld: coresymbolication_load_notifier(%p, 0x%016llX, %p, %s)\n",
1153 dyld::gProcessInfo
->coreSymbolicationShmPage
, loadTimestamp
, infos
[j
].imageLoadAddress
, infos
[j
].imageFilePath
);
1155 coresymbolication_load_notifier(dyld::gProcessInfo
->coreSymbolicationShmPage
, loadTimestamp
, infos
[j
].imageFilePath
, infos
[j
].imageLoadAddress
);
1158 for (int slot
=0; slot
< DYLD_MAX_PROCESS_INFO_NOTIFY_COUNT
; ++slot
) {
1159 if ( dyld::gProcessInfo
->notifyPorts
[slot
] )
1160 notifyMonitoringDyld(false, slot
, imageCount
, infos
);
1168 static void notifyBatch(dyld_image_states state
, bool preflightOnly
)
1170 notifyBatchPartial(state
, false, NULL
, preflightOnly
, false);
1173 // In order for register_func_for_add_image() callbacks to to be called bottom up,
1174 // we need to maintain a list of root images. The main executable is usally the
1175 // first root. Any images dynamically added are also roots (unless already loaded).
1176 // If DYLD_INSERT_LIBRARIES is used, those libraries are first.
1177 static void addRootImage(ImageLoader
* image
)
1179 //dyld::log("addRootImage(%p, %s)\n", image, image->getPath());
1180 // add to list of roots
1181 sImageRoots
.push_back(image
);
1185 static void clearAllDepths()
1187 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++)
1188 (*it
)->clearDepth();
1191 static void printAllDepths()
1193 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++)
1194 dyld::log("%03d %s\n", (*it
)->getDepth(), (*it
)->getShortName());
1198 static unsigned int imageCount()
1201 unsigned int result
= (unsigned int)sAllImages
.size();
1207 static void setNewProgramVars(const ProgramVars
& newVars
)
1209 // make a copy of the pointers to program variables
1210 gLinkContext
.programVars
= newVars
;
1212 // now set each program global to their initial value
1213 *gLinkContext
.programVars
.NXArgcPtr
= gLinkContext
.argc
;
1214 *gLinkContext
.programVars
.NXArgvPtr
= gLinkContext
.argv
;
1215 *gLinkContext
.programVars
.environPtr
= gLinkContext
.envp
;
1216 *gLinkContext
.programVars
.__prognamePtr
= gLinkContext
.progname
;
1219 #if SUPPORT_OLD_CRT_INITIALIZATION
1220 static void setRunInitialzersOldWay()
1222 gRunInitializersOldWay
= true;
1226 static bool sandboxBlocked(const char* path
, const char* kind
)
1228 #if TARGET_IPHONE_SIMULATOR
1229 // sandbox calls not yet supported in simulator runtime
1232 sandbox_filter_type filter
= (sandbox_filter_type
)(SANDBOX_FILTER_PATH
| SANDBOX_CHECK_NO_REPORT
);
1233 return ( sandbox_check(getpid(), kind
, filter
, path
) > 0 );
1237 bool sandboxBlockedMmap(const char* path
)
1239 return sandboxBlocked(path
, "file-map-executable");
1242 bool sandboxBlockedOpen(const char* path
)
1244 return sandboxBlocked(path
, "file-read-data");
1247 bool sandboxBlockedStat(const char* path
)
1249 return sandboxBlocked(path
, "file-read-metadata");
1253 static void addDynamicReference(ImageLoader
* from
, ImageLoader
* to
) {
1254 // don't add dynamic reference if target is in the shared cache (since it can't be unloaded)
1255 if ( to
->inSharedCache() )
1258 // don't add dynamic reference if there already is a static one
1259 if ( from
->dependsOn(to
) )
1262 // don't add if this combination already exists
1263 OSSpinLockLock(&sDynamicReferencesLock
);
1264 for (std::vector
<ImageLoader::DynamicReference
>::iterator it
=sDynamicReferences
.begin(); it
!= sDynamicReferences
.end(); ++it
) {
1265 if ( (it
->from
== from
) && (it
->to
== to
) ) {
1266 OSSpinLockUnlock(&sDynamicReferencesLock
);
1271 //dyld::log("addDynamicReference(%s, %s\n", from->getShortName(), to->getShortName());
1272 ImageLoader::DynamicReference t
;
1275 sDynamicReferences
.push_back(t
);
1276 OSSpinLockUnlock(&sDynamicReferencesLock
);
1279 static void addImage(ImageLoader
* image
)
1281 // add to master list
1283 sAllImages
.push_back(image
);
1286 // update mapped ranges
1287 uintptr_t lastSegStart
= 0;
1288 uintptr_t lastSegEnd
= 0;
1289 for(unsigned int i
=0, e
=image
->segmentCount(); i
< e
; ++i
) {
1290 if ( image
->segUnaccessible(i
) )
1292 uintptr_t start
= image
->segActualLoadAddress(i
);
1293 uintptr_t end
= image
->segActualEndAddress(i
);
1294 if ( start
== lastSegEnd
) {
1295 // two segments are contiguous, just record combined segments
1299 // non-contiguous segments, record last (if any)
1300 if ( lastSegEnd
!= 0 )
1301 addMappedRange(image
, lastSegStart
, lastSegEnd
);
1302 lastSegStart
= start
;
1306 if ( lastSegEnd
!= 0 )
1307 addMappedRange(image
, lastSegStart
, lastSegEnd
);
1310 if ( gLinkContext
.verboseLoading
|| (sEnv
.DYLD_PRINT_LIBRARIES_POST_LAUNCH
&& (sMainExecutable
!=NULL
) && sMainExecutable
->isLinked()) ) {
1311 dyld::log("dyld: loaded: %s\n", image
->getPath());
1317 // Helper for std::remove_if
1319 class RefUsesImage
{
1321 RefUsesImage(ImageLoader
* image
) : _image(image
) {}
1322 bool operator()(const ImageLoader::DynamicReference
& ref
) const {
1323 return ( (ref
.from
== _image
) || (ref
.to
== _image
) );
1326 ImageLoader
* _image
;
1331 void removeImage(ImageLoader
* image
)
1333 // if has dtrace DOF section, tell dtrace it is going away, then remove from sImageFilesNeedingDOFUnregistration
1334 for (std::vector
<RegisteredDOF
>::iterator it
=sImageFilesNeedingDOFUnregistration
.begin(); it
!= sImageFilesNeedingDOFUnregistration
.end(); ) {
1335 if ( it
->mh
== image
->machHeader() ) {
1336 unregisterDOF(it
->registrationID
);
1337 sImageFilesNeedingDOFUnregistration
.erase(it
);
1338 // don't increment iterator, the erase caused next element to be copied to where this iterator points
1345 // tell all registered remove image handlers about this
1346 // do this before removing image from internal data structures so that the callback can query dyld about the image
1347 if ( image
->getState() >= dyld_image_state_bound
) {
1348 sRemoveImageCallbacksInUse
= true; // This only runs inside dyld's global lock, so ok to use a global for the in-use flag.
1349 for (std::vector
<ImageCallback
>::iterator it
=sRemoveImageCallbacks
.begin(); it
!= sRemoveImageCallbacks
.end(); it
++) {
1350 (*it
)(image
->machHeader(), image
->getSlide());
1352 sRemoveImageCallbacksInUse
= false;
1354 if ( sNotifyObjCUnmapped
!= NULL
&& image
->notifyObjC() )
1355 (*sNotifyObjCUnmapped
)(image
->getRealPath(), image
->machHeader());
1359 notifySingle(dyld_image_state_terminated
, image
, NULL
);
1361 // remove from mapped images table
1362 removedMappedRanges(image
);
1364 // remove from master list
1366 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
1367 if ( *it
== image
) {
1368 sAllImages
.erase(it
);
1374 // remove from sDynamicReferences
1375 OSSpinLockLock(&sDynamicReferencesLock
);
1376 sDynamicReferences
.erase(std::remove_if(sDynamicReferences
.begin(), sDynamicReferences
.end(), RefUsesImage(image
)), sDynamicReferences
.end());
1377 OSSpinLockUnlock(&sDynamicReferencesLock
);
1379 // flush find-by-address cache (do this after removed from master list, so there is no chance it can come back)
1380 if ( sLastImageByAddressCache
== image
)
1381 sLastImageByAddressCache
= NULL
;
1383 // if in root list, pull it out
1384 for (std::vector
<ImageLoader
*>::iterator it
=sImageRoots
.begin(); it
!= sImageRoots
.end(); it
++) {
1385 if ( *it
== image
) {
1386 sImageRoots
.erase(it
);
1392 if ( gLinkContext
.verboseLoading
|| (sEnv
.DYLD_PRINT_LIBRARIES_POST_LAUNCH
&& (sMainExecutable
!=NULL
) && sMainExecutable
->isLinked()) ) {
1393 dyld::log("dyld: unloaded: %s\n", image
->getPath());
1396 // tell gdb, new way
1397 removeImageFromAllImages(image
->machHeader());
1401 void runImageStaticTerminators(ImageLoader
* image
)
1403 // if in termination list, pull it out and run terminator
1406 mightBeMore
= false;
1407 for (std::vector
<ImageLoader
*>::iterator it
=sImageFilesNeedingTermination
.begin(); it
!= sImageFilesNeedingTermination
.end(); it
++) {
1408 if ( *it
== image
) {
1409 sImageFilesNeedingTermination
.erase(it
);
1410 if (gLogAPIs
) dyld::log("dlclose(), running static terminators for %p %s\n", image
, image
->getShortName());
1411 image
->doTermination(gLinkContext
);
1416 } while ( mightBeMore
);
1419 static void terminationRecorder(ImageLoader
* image
)
1421 sImageFilesNeedingTermination
.push_back(image
);
1424 const char* getExecutablePath()
1429 static void runAllStaticTerminators(void* extra
)
1432 const size_t imageCount
= sImageFilesNeedingTermination
.size();
1433 for(size_t i
=imageCount
; i
> 0; --i
){
1434 ImageLoader
* image
= sImageFilesNeedingTermination
[i
-1];
1435 image
->doTermination(gLinkContext
);
1437 sImageFilesNeedingTermination
.clear();
1438 notifyBatch(dyld_image_state_terminated
, false);
1440 catch (const char* msg
) {
1445 void initializeMainExecutable()
1447 // record that we've reached this step
1448 gLinkContext
.startedInitializingMainExecutable
= true;
1450 // run initialzers for any inserted dylibs
1451 ImageLoader::InitializerTimingList initializerTimes
[allImagesCount()];
1452 initializerTimes
[0].count
= 0;
1453 const size_t rootCount
= sImageRoots
.size();
1454 if ( rootCount
> 1 ) {
1455 for(size_t i
=1; i
< rootCount
; ++i
) {
1456 sImageRoots
[i
]->runInitializers(gLinkContext
, initializerTimes
[0]);
1460 // run initializers for main executable and everything it brings up
1461 sMainExecutable
->runInitializers(gLinkContext
, initializerTimes
[0]);
1463 // register cxa_atexit() handler to run static terminators in all loaded images when this process exits
1464 if ( gLibSystemHelpers
!= NULL
)
1465 (*gLibSystemHelpers
->cxa_atexit
)(&runAllStaticTerminators
, NULL
, NULL
);
1467 // dump info if requested
1468 if ( sEnv
.DYLD_PRINT_STATISTICS
)
1469 ImageLoader::printStatistics((unsigned int)allImagesCount(), initializerTimes
[0]);
1470 if ( sEnv
.DYLD_PRINT_STATISTICS_DETAILS
)
1471 ImageLoaderMachO::printStatisticsDetails((unsigned int)allImagesCount(), initializerTimes
[0]);
1474 bool mainExecutablePrebound()
1476 return sMainExecutable
->usablePrebinding(gLinkContext
);
1479 ImageLoader
* mainExecutable()
1481 return sMainExecutable
;
1487 #if SUPPORT_VERSIONED_PATHS
1489 // forward reference
1490 static bool getDylibVersionAndInstallname(const char* dylibPath
, uint32_t* version
, char* installName
);
1494 // Examines a dylib file and if its current_version is newer than the installed
1495 // dylib at its install_name, then add the dylib file to sDylibOverrides.
1497 static void checkDylibOverride(const char* dylibFile
)
1499 //dyld::log("checkDylibOverride('%s')\n", dylibFile);
1500 uint32_t altVersion
;
1501 char sysInstallName
[PATH_MAX
];
1502 if ( getDylibVersionAndInstallname(dylibFile
, &altVersion
, sysInstallName
) && (sysInstallName
[0] =='/') ) {
1503 //dyld::log("%s has version 0x%08X and install name %s\n", dylibFile, altVersion, sysInstallName);
1504 uint32_t sysVersion
;
1505 if ( getDylibVersionAndInstallname(sysInstallName
, &sysVersion
, NULL
) ) {
1506 //dyld::log("%s has version 0x%08X\n", sysInstallName, sysVersion);
1507 if ( altVersion
> sysVersion
) {
1508 //dyld::log("override found: %s -> %s\n", sysInstallName, dylibFile);
1509 // see if there already is an override for this dylib
1510 bool entryExists
= false;
1511 for (std::vector
<DylibOverride
>::iterator it
= sDylibOverrides
.begin(); it
!= sDylibOverrides
.end(); ++it
) {
1512 if ( strcmp(it
->installName
, sysInstallName
) == 0 ) {
1514 uint32_t prevVersion
;
1515 if ( getDylibVersionAndInstallname(it
->override
, &prevVersion
, NULL
) ) {
1516 if ( altVersion
> prevVersion
) {
1517 // found an even newer override
1518 free((void*)(it
->override
));
1519 char resolvedPath
[PATH_MAX
];
1520 if ( realpath(dylibFile
, resolvedPath
) != NULL
)
1521 it
->override
= strdup(resolvedPath
);
1523 it
->override
= strdup(dylibFile
);
1529 if ( ! entryExists
) {
1530 DylibOverride entry
;
1531 entry
.installName
= strdup(sysInstallName
);
1532 char resolvedPath
[PATH_MAX
];
1533 if ( realpath(dylibFile
, resolvedPath
) != NULL
)
1534 entry
.override
= strdup(resolvedPath
);
1536 entry
.override
= strdup(dylibFile
);
1537 sDylibOverrides
.push_back(entry
);
1538 //dyld::log("added override: %s -> %s\n", entry.installName, entry.override);
1546 static void checkDylibOverridesInDir(const char* dirPath
)
1548 //dyld::log("checkDylibOverridesInDir('%s')\n", dirPath);
1549 char dylibPath
[PATH_MAX
];
1550 long dirPathLen
= strlcpy(dylibPath
, dirPath
, PATH_MAX
-1);
1551 if ( dirPathLen
>= PATH_MAX
)
1553 DIR* dirp
= opendir(dirPath
);
1554 if ( dirp
!= NULL
) {
1556 dirent
* entp
= NULL
;
1557 while ( readdir_r(dirp
, &entry
, &entp
) == 0 ) {
1560 if ( entp
->d_type
!= DT_REG
)
1562 dylibPath
[dirPathLen
] = '/';
1563 dylibPath
[dirPathLen
+1] = '\0';
1564 if ( strlcat(dylibPath
, entp
->d_name
, PATH_MAX
) >= PATH_MAX
)
1566 checkDylibOverride(dylibPath
);
1573 static void checkFrameworkOverridesInDir(const char* dirPath
)
1575 //dyld::log("checkFrameworkOverridesInDir('%s')\n", dirPath);
1576 char frameworkPath
[PATH_MAX
];
1577 long dirPathLen
= strlcpy(frameworkPath
, dirPath
, PATH_MAX
-1);
1578 if ( dirPathLen
>= PATH_MAX
)
1580 DIR* dirp
= opendir(dirPath
);
1581 if ( dirp
!= NULL
) {
1583 dirent
* entp
= NULL
;
1584 while ( readdir_r(dirp
, &entry
, &entp
) == 0 ) {
1587 if ( entp
->d_type
!= DT_DIR
)
1589 frameworkPath
[dirPathLen
] = '/';
1590 frameworkPath
[dirPathLen
+1] = '\0';
1591 int dirNameLen
= (int)strlen(entp
->d_name
);
1592 if ( dirNameLen
< 11 )
1594 if ( strcmp(&entp
->d_name
[dirNameLen
-10], ".framework") != 0 )
1596 if ( strlcat(frameworkPath
, entp
->d_name
, PATH_MAX
) >= PATH_MAX
)
1598 if ( strlcat(frameworkPath
, "/", PATH_MAX
) >= PATH_MAX
)
1600 if ( strlcat(frameworkPath
, entp
->d_name
, PATH_MAX
) >= PATH_MAX
)
1602 frameworkPath
[strlen(frameworkPath
)-10] = '\0';
1603 checkDylibOverride(frameworkPath
);
1608 #endif // SUPPORT_VERSIONED_PATHS
1612 // Turns a colon separated list of strings into a NULL terminated array
1613 // of string pointers. If mainExecutableDir param is not NULL,
1614 // substitutes @loader_path with main executable's dir.
1616 static const char** parseColonList(const char* list
, const char* mainExecutableDir
)
1618 static const char* sEmptyList
[] = { NULL
};
1620 if ( list
[0] == '\0' )
1624 for(const char* s
=list
; *s
!= '\0'; ++s
) {
1630 const char* start
= list
;
1631 char** result
= new char*[colonCount
+2];
1632 for(const char* s
=list
; *s
!= '\0'; ++s
) {
1634 size_t len
= s
-start
;
1635 if ( (mainExecutableDir
!= NULL
) && (strncmp(start
, "@loader_path/", 13) == 0) ) {
1636 #if __MAC_OS_X_VERSION_MIN_REQUIRED
1637 if ( gLinkContext
.processIsRestricted
) {
1638 dyld::log("dyld: warning: @loader_path/ ignored in restricted process\n");
1642 size_t mainExecDirLen
= strlen(mainExecutableDir
);
1643 char* str
= new char[mainExecDirLen
+len
+1];
1644 strcpy(str
, mainExecutableDir
);
1645 strlcat(str
, &start
[13], mainExecDirLen
+len
+1);
1646 str
[mainExecDirLen
+len
-13] = '\0';
1648 result
[index
++] = str
;
1650 else if ( (mainExecutableDir
!= NULL
) && (strncmp(start
, "@executable_path/", 17) == 0) ) {
1651 #if __MAC_OS_X_VERSION_MIN_REQUIRED
1652 if ( gLinkContext
.processIsRestricted
) {
1653 dyld::log("dyld: warning: @executable_path/ ignored in restricted process\n");
1657 size_t mainExecDirLen
= strlen(mainExecutableDir
);
1658 char* str
= new char[mainExecDirLen
+len
+1];
1659 strcpy(str
, mainExecutableDir
);
1660 strlcat(str
, &start
[17], mainExecDirLen
+len
+1);
1661 str
[mainExecDirLen
+len
-17] = '\0';
1663 result
[index
++] = str
;
1666 char* str
= new char[len
+1];
1667 strncpy(str
, start
, len
);
1670 result
[index
++] = str
;
1674 size_t len
= strlen(start
);
1675 if ( (mainExecutableDir
!= NULL
) && (strncmp(start
, "@loader_path/", 13) == 0) ) {
1676 #if __MAC_OS_X_VERSION_MIN_REQUIRED
1677 if ( gLinkContext
.processIsRestricted
) {
1678 dyld::log("dyld: warning: @loader_path/ ignored in restricted process\n");
1683 size_t mainExecDirLen
= strlen(mainExecutableDir
);
1684 char* str
= new char[mainExecDirLen
+len
+1];
1685 strcpy(str
, mainExecutableDir
);
1686 strlcat(str
, &start
[13], mainExecDirLen
+len
+1);
1687 str
[mainExecDirLen
+len
-13] = '\0';
1688 result
[index
++] = str
;
1691 else if ( (mainExecutableDir
!= NULL
) && (strncmp(start
, "@executable_path/", 17) == 0) ) {
1692 #if __MAC_OS_X_VERSION_MIN_REQUIRED
1693 if ( gLinkContext
.processIsRestricted
) {
1694 dyld::log("dyld: warning: @executable_path/ ignored in restricted process\n");
1699 size_t mainExecDirLen
= strlen(mainExecutableDir
);
1700 char* str
= new char[mainExecDirLen
+len
+1];
1701 strcpy(str
, mainExecutableDir
);
1702 strlcat(str
, &start
[17], mainExecDirLen
+len
+1);
1703 str
[mainExecDirLen
+len
-17] = '\0';
1704 result
[index
++] = str
;
1708 char* str
= new char[len
+1];
1710 result
[index
++] = str
;
1712 result
[index
] = NULL
;
1714 //dyld::log("parseColonList(%s)\n", list);
1715 //for(int i=0; result[i] != NULL; ++i)
1716 // dyld::log(" %s\n", result[i]);
1717 return (const char**)result
;
1720 static void appendParsedColonList(const char* list
, const char* mainExecutableDir
, const char* const ** storage
)
1722 const char** newlist
= parseColonList(list
, mainExecutableDir
);
1723 if ( *storage
== NULL
) {
1724 // first time, just set
1728 // need to append to existing list
1729 const char* const* existing
= *storage
;
1731 for(int i
=0; existing
[i
] != NULL
; ++i
)
1733 for(int i
=0; newlist
[i
] != NULL
; ++i
)
1735 const char** combinedList
= new const char*[count
+2];
1737 for(int i
=0; existing
[i
] != NULL
; ++i
)
1738 combinedList
[index
++] = existing
[i
];
1739 for(int i
=0; newlist
[i
] != NULL
; ++i
)
1740 combinedList
[index
++] = newlist
[i
];
1741 combinedList
[index
] = NULL
;
1743 *storage
= combinedList
;
1747 #if __MAC_OS_X_VERSION_MIN_REQUIRED
1748 static void paths_expand_roots(const char **paths
, const char *key
, const char *val
)
1750 // assert(val != NULL);
1751 // assert(paths != NULL);
1753 size_t keyLen
= strlen(key
);
1754 for(int i
=0; paths
[i
] != NULL
; ++i
) {
1755 if ( strncmp(paths
[i
], key
, keyLen
) == 0 ) {
1756 char* newPath
= new char[strlen(val
) + (strlen(paths
[i
]) - keyLen
) + 1];
1757 strcpy(newPath
, val
);
1758 strcat(newPath
, &paths
[i
][keyLen
]);
1766 static void removePathWithPrefix(const char* paths
[], const char* prefix
)
1768 size_t prefixLen
= strlen(prefix
);
1771 for(i
= 0; paths
[i
] != NULL
; ++i
) {
1772 if ( strncmp(paths
[i
], prefix
, prefixLen
) == 0 )
1775 paths
[i
-skip
] = paths
[i
];
1777 paths
[i
-skip
] = NULL
;
1783 static void paths_dump(const char **paths
)
1785 // assert(paths != NULL);
1786 const char **strs
= paths
;
1787 while(*strs
!= NULL
)
1789 dyld::log("\"%s\"\n", *strs
);
1798 static void printOptions(const char* argv
[])
1801 while ( NULL
!= argv
[i
] ) {
1802 dyld::log("opt[%i] = \"%s\"\n", i
, argv
[i
]);
1807 static void printEnvironmentVariables(const char* envp
[])
1809 while ( NULL
!= *envp
) {
1810 dyld::log("%s\n", *envp
);
1815 void processDyldEnvironmentVariable(const char* key
, const char* value
, const char* mainExecutableDir
)
1817 if ( strcmp(key
, "DYLD_FRAMEWORK_PATH") == 0 ) {
1818 appendParsedColonList(value
, mainExecutableDir
, &sEnv
.DYLD_FRAMEWORK_PATH
);
1820 else if ( strcmp(key
, "DYLD_FALLBACK_FRAMEWORK_PATH") == 0 ) {
1821 appendParsedColonList(value
, mainExecutableDir
, &sEnv
.DYLD_FALLBACK_FRAMEWORK_PATH
);
1823 else if ( strcmp(key
, "DYLD_LIBRARY_PATH") == 0 ) {
1824 appendParsedColonList(value
, mainExecutableDir
, &sEnv
.DYLD_LIBRARY_PATH
);
1826 else if ( strcmp(key
, "DYLD_FALLBACK_LIBRARY_PATH") == 0 ) {
1827 appendParsedColonList(value
, mainExecutableDir
, &sEnv
.DYLD_FALLBACK_LIBRARY_PATH
);
1829 #if SUPPORT_ROOT_PATH
1830 else if ( (strcmp(key
, "DYLD_ROOT_PATH") == 0) || (strcmp(key
, "DYLD_PATHS_ROOT") == 0) ) {
1831 if ( strcmp(value
, "/") != 0 ) {
1832 gLinkContext
.rootPaths
= parseColonList(value
, mainExecutableDir
);
1833 for (int i
=0; gLinkContext
.rootPaths
[i
] != NULL
; ++i
) {
1834 if ( gLinkContext
.rootPaths
[i
][0] != '/' ) {
1835 dyld::warn("DYLD_ROOT_PATH not used because it contains a non-absolute path\n");
1836 gLinkContext
.rootPaths
= NULL
;
1843 else if ( strcmp(key
, "DYLD_IMAGE_SUFFIX") == 0 ) {
1844 gLinkContext
.imageSuffix
= value
;
1846 else if ( strcmp(key
, "DYLD_INSERT_LIBRARIES") == 0 ) {
1847 sEnv
.DYLD_INSERT_LIBRARIES
= parseColonList(value
, NULL
);
1848 #if SUPPORT_ACCELERATE_TABLES
1849 sDisableAcceleratorTables
= true;
1852 else if ( strcmp(key
, "DYLD_PRINT_OPTS") == 0 ) {
1853 sEnv
.DYLD_PRINT_OPTS
= true;
1855 else if ( strcmp(key
, "DYLD_PRINT_ENV") == 0 ) {
1856 sEnv
.DYLD_PRINT_ENV
= true;
1858 else if ( strcmp(key
, "DYLD_DISABLE_DOFS") == 0 ) {
1859 sEnv
.DYLD_DISABLE_DOFS
= true;
1861 else if ( strcmp(key
, "DYLD_DISABLE_PREFETCH") == 0 ) {
1862 gLinkContext
.preFetchDisabled
= true;
1864 else if ( strcmp(key
, "DYLD_PRINT_LIBRARIES") == 0 ) {
1865 gLinkContext
.verboseLoading
= true;
1867 else if ( strcmp(key
, "DYLD_PRINT_LIBRARIES_POST_LAUNCH") == 0 ) {
1868 sEnv
.DYLD_PRINT_LIBRARIES_POST_LAUNCH
= true;
1870 else if ( strcmp(key
, "DYLD_BIND_AT_LAUNCH") == 0 ) {
1871 sEnv
.DYLD_BIND_AT_LAUNCH
= true;
1873 else if ( strcmp(key
, "DYLD_FORCE_FLAT_NAMESPACE") == 0 ) {
1874 gLinkContext
.bindFlat
= true;
1876 else if ( strcmp(key
, "DYLD_NEW_LOCAL_SHARED_REGIONS") == 0 ) {
1877 // ignore, no longer relevant but some scripts still set it
1879 else if ( strcmp(key
, "DYLD_NO_FIX_PREBINDING") == 0 ) {
1881 else if ( strcmp(key
, "DYLD_PREBIND_DEBUG") == 0 ) {
1882 gLinkContext
.verbosePrebinding
= true;
1884 else if ( strcmp(key
, "DYLD_PRINT_INITIALIZERS") == 0 ) {
1885 gLinkContext
.verboseInit
= true;
1887 else if ( strcmp(key
, "DYLD_PRINT_DOFS") == 0 ) {
1888 gLinkContext
.verboseDOF
= true;
1890 else if ( strcmp(key
, "DYLD_PRINT_STATISTICS") == 0 ) {
1891 sEnv
.DYLD_PRINT_STATISTICS
= true;
1892 #if __IPHONE_OS_VERSION_MIN_REQUIRED && !TARGET_IPHONE_SIMULATOR
1893 // <rdar://problem/26614838> DYLD_PRINT_STATISTICS no longer logs to xcode console for device apps
1894 sForceStderr
= true;
1897 else if ( strcmp(key
, "DYLD_PRINT_TO_STDERR") == 0 ) {
1898 #if __IPHONE_OS_VERSION_MIN_REQUIRED && !TARGET_IPHONE_SIMULATOR
1899 // <rdar://problem/26633440> DYLD_PRINT_STATISTICS no longer logs to xcode console for device apps
1900 sForceStderr
= true;
1903 else if ( strcmp(key
, "DYLD_PRINT_STATISTICS_DETAILS") == 0 ) {
1904 sEnv
.DYLD_PRINT_STATISTICS_DETAILS
= true;
1906 else if ( strcmp(key
, "DYLD_PRINT_SEGMENTS") == 0 ) {
1907 gLinkContext
.verboseMapping
= true;
1909 else if ( strcmp(key
, "DYLD_PRINT_BINDINGS") == 0 ) {
1910 gLinkContext
.verboseBind
= true;
1912 else if ( strcmp(key
, "DYLD_PRINT_WEAK_BINDINGS") == 0 ) {
1913 gLinkContext
.verboseWeakBind
= true;
1915 else if ( strcmp(key
, "DYLD_PRINT_REBASINGS") == 0 ) {
1916 gLinkContext
.verboseRebase
= true;
1918 else if ( strcmp(key
, "DYLD_PRINT_APIS") == 0 ) {
1921 #if SUPPORT_ACCELERATE_TABLES
1922 else if ( strcmp(key
, "DYLD_PRINT_APIS_APP") == 0 ) {
1926 else if ( strcmp(key
, "DYLD_PRINT_WARNINGS") == 0 ) {
1927 gLinkContext
.verboseWarnings
= true;
1929 else if ( strcmp(key
, "DYLD_PRINT_RPATHS") == 0 ) {
1930 gLinkContext
.verboseRPaths
= true;
1932 else if ( strcmp(key
, "DYLD_PRINT_CS_NOTIFICATIONS") == 0 ) {
1933 sEnv
.DYLD_PRINT_CS_NOTIFICATIONS
= true;
1935 else if ( strcmp(key
, "DYLD_PRINT_INTERPOSING") == 0 ) {
1936 gLinkContext
.verboseInterposing
= true;
1938 else if ( strcmp(key
, "DYLD_PRINT_CODE_SIGNATURES") == 0 ) {
1939 gLinkContext
.verboseCodeSignatures
= true;
1941 else if ( (strcmp(key
, "DYLD_SHARED_REGION") == 0) && !sSafeMode
) {
1942 if ( strcmp(value
, "private") == 0 ) {
1943 gLinkContext
.sharedRegionMode
= ImageLoader::kUsePrivateSharedRegion
;
1945 else if ( strcmp(value
, "avoid") == 0 ) {
1946 gLinkContext
.sharedRegionMode
= ImageLoader::kDontUseSharedRegion
;
1948 else if ( strcmp(value
, "use") == 0 ) {
1949 gLinkContext
.sharedRegionMode
= ImageLoader::kUseSharedRegion
;
1951 else if ( value
[0] == '\0' ) {
1952 gLinkContext
.sharedRegionMode
= ImageLoader::kUseSharedRegion
;
1955 dyld::warn("unknown option to DYLD_SHARED_REGION. Valid options are: use, private, avoid\n");
1958 else if ( (strcmp(key
, "DYLD_SHARED_CACHE_DIR") == 0) && !sSafeMode
) {
1959 sSharedCacheOverrideDir
= value
;
1961 else if ( strcmp(key
, "DYLD_USE_CLOSURES") == 0 ) {
1962 if ( dyld3::loader::internalInstall() )
1963 sEnableClosures
= true;
1965 else if ( strcmp(key
, "DYLD_IGNORE_PREBINDING") == 0 ) {
1966 if ( strcmp(value
, "all") == 0 ) {
1967 gLinkContext
.prebindUsage
= ImageLoader::kUseNoPrebinding
;
1969 else if ( strcmp(value
, "app") == 0 ) {
1970 gLinkContext
.prebindUsage
= ImageLoader::kUseAllButAppPredbinding
;
1972 else if ( strcmp(value
, "nonsplit") == 0 ) {
1973 gLinkContext
.prebindUsage
= ImageLoader::kUseSplitSegPrebinding
;
1975 else if ( value
[0] == '\0' ) {
1976 gLinkContext
.prebindUsage
= ImageLoader::kUseSplitSegPrebinding
;
1979 dyld::warn("unknown option to DYLD_IGNORE_PREBINDING. Valid options are: all, app, nonsplit\n");
1982 #if SUPPORT_VERSIONED_PATHS
1983 else if ( strcmp(key
, "DYLD_VERSIONED_LIBRARY_PATH") == 0 ) {
1984 appendParsedColonList(value
, mainExecutableDir
, &sEnv
.DYLD_VERSIONED_LIBRARY_PATH
);
1985 #if SUPPORT_ACCELERATE_TABLES
1986 sDisableAcceleratorTables
= true;
1989 else if ( strcmp(key
, "DYLD_VERSIONED_FRAMEWORK_PATH") == 0 ) {
1990 appendParsedColonList(value
, mainExecutableDir
, &sEnv
.DYLD_VERSIONED_FRAMEWORK_PATH
);
1991 #if SUPPORT_ACCELERATE_TABLES
1992 sDisableAcceleratorTables
= true;
1996 #if !TARGET_IPHONE_SIMULATOR
1997 else if ( (strcmp(key
, "DYLD_PRINT_TO_FILE") == 0) && (mainExecutableDir
== NULL
) && !sSafeMode
) {
1998 int fd
= open(value
, O_WRONLY
| O_CREAT
| O_APPEND
, 0644);
2004 dyld::log("dyld: could not open DYLD_PRINT_TO_FILE='%s', errno=%d\n", value
, errno
);
2007 else if ( (strcmp(key
, "DYLD_SKIP_MAIN") == 0)) {
2008 if ( dyld3::loader::internalInstall() )
2013 dyld::warn("unknown environment variable: %s\n", key
);
2018 #if SUPPORT_LC_DYLD_ENVIRONMENT
2019 static void checkLoadCommandEnvironmentVariables()
2021 // <rdar://problem/8440934> Support augmenting dyld environment variables in load commands
2022 const uint32_t cmd_count
= sMainExecutableMachHeader
->ncmds
;
2023 const struct load_command
* const cmds
= (struct load_command
*)(((char*)sMainExecutableMachHeader
)+sizeof(macho_header
));
2024 const struct load_command
* cmd
= cmds
;
2025 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
2027 case LC_DYLD_ENVIRONMENT
:
2029 const struct dylinker_command
* envcmd
= (struct dylinker_command
*)cmd
;
2030 const char* keyEqualsValue
= (char*)envcmd
+ envcmd
->name
.offset
;
2031 char mainExecutableDir
[strlen(sExecPath
)+2];
2032 strcpy(mainExecutableDir
, sExecPath
);
2033 char* lastSlash
= strrchr(mainExecutableDir
, '/');
2034 if ( lastSlash
!= NULL
)
2035 lastSlash
[1] = '\0';
2036 // only process variables that start with DYLD_ and end in _PATH
2037 if ( (strncmp(keyEqualsValue
, "DYLD_", 5) == 0) ) {
2038 const char* equals
= strchr(keyEqualsValue
, '=');
2039 if ( equals
!= NULL
) {
2040 if ( strncmp(&equals
[-5], "_PATH", 5) == 0 ) {
2041 const char* value
= &equals
[1];
2042 const size_t keyLen
= equals
-keyEqualsValue
;
2043 // <rdar://problem/22799635> don't let malformed load command overflow stack
2044 if ( keyLen
< 40 ) {
2046 strncpy(key
, keyEqualsValue
, keyLen
);
2048 //dyld::log("processing: %s\n", keyEqualsValue);
2049 //dyld::log("mainExecutableDir: %s\n", mainExecutableDir);
2050 processDyldEnvironmentVariable(key
, value
, mainExecutableDir
);
2058 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
2061 #endif // SUPPORT_LC_DYLD_ENVIRONMENT
2064 static bool hasCodeSignatureLoadCommand(const macho_header
* mh
)
2066 const uint32_t cmd_count
= mh
->ncmds
;
2067 const struct load_command
* const cmds
= (struct load_command
*)(((char*)mh
)+sizeof(macho_header
));
2068 const struct load_command
* cmd
= cmds
;
2069 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
2070 if (cmd
->cmd
== LC_CODE_SIGNATURE
)
2072 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
2078 #if SUPPORT_VERSIONED_PATHS
2079 static void checkVersionedPaths()
2081 // search DYLD_VERSIONED_LIBRARY_PATH directories for dylibs and check if they are newer
2082 if ( sEnv
.DYLD_VERSIONED_LIBRARY_PATH
!= NULL
) {
2083 for(const char* const* lp
= sEnv
.DYLD_VERSIONED_LIBRARY_PATH
; *lp
!= NULL
; ++lp
) {
2084 checkDylibOverridesInDir(*lp
);
2088 // search DYLD_VERSIONED_FRAMEWORK_PATH directories for dylibs and check if they are newer
2089 if ( sEnv
.DYLD_VERSIONED_FRAMEWORK_PATH
!= NULL
) {
2090 for(const char* const* fp
= sEnv
.DYLD_VERSIONED_FRAMEWORK_PATH
; *fp
!= NULL
; ++fp
) {
2091 checkFrameworkOverridesInDir(*fp
);
2098 #if __MAC_OS_X_VERSION_MIN_REQUIRED
2100 // For security, setuid programs ignore DYLD_* environment variables.
2101 // Additionally, the DYLD_* enviroment variables are removed
2102 // from the environment, so that any child processes don't see them.
2104 static void pruneEnvironmentVariables(const char* envp
[], const char*** applep
)
2106 #if SUPPORT_LC_DYLD_ENVIRONMENT
2107 checkLoadCommandEnvironmentVariables();
2110 // Are we testing dyld on an internal config?
2111 if ( _simple_getenv(envp
, "DYLD_SKIP_MAIN") != NULL
) {
2112 if ( dyld3::loader::internalInstall() )
2116 // delete all DYLD_* and LD_LIBRARY_PATH environment variables
2117 int removedCount
= 0;
2118 const char** d
= envp
;
2119 for(const char** s
= envp
; *s
!= NULL
; s
++) {
2121 if ( (strncmp(*s
, "DYLD_", 5) != 0) && (strncmp(*s
, "LD_LIBRARY_PATH=", 16) != 0) ) {
2129 // slide apple parameters
2130 if ( removedCount
> 0 ) {
2133 *d
= d
[removedCount
];
2134 } while ( *d
++ != NULL
);
2135 for(int i
=0; i
< removedCount
; ++i
)
2139 // disable framework and library fallback paths for setuid binaries rdar://problem/4589305
2140 sEnv
.DYLD_FALLBACK_FRAMEWORK_PATH
= NULL
;
2141 sEnv
.DYLD_FALLBACK_LIBRARY_PATH
= NULL
;
2143 if ( removedCount
> 0 )
2144 strlcat(sLoadingCrashMessage
, ", ignoring DYLD_* env vars", sizeof(sLoadingCrashMessage
));
2148 static void defaultUninitializedFallbackPaths(const char* envp
[])
2150 #if __MAC_OS_X_VERSION_MIN_REQUIRED
2151 if ( gLinkContext
.processIsRestricted
) {
2152 sEnv
.DYLD_FALLBACK_FRAMEWORK_PATH
= sRestrictedFrameworkFallbackPaths
;
2153 sEnv
.DYLD_FALLBACK_LIBRARY_PATH
= sRestrictedLibraryFallbackPaths
;
2157 // default value for DYLD_FALLBACK_FRAMEWORK_PATH, if not set in environment
2158 const char* home
= _simple_getenv(envp
, "HOME");;
2159 if ( sEnv
.DYLD_FALLBACK_FRAMEWORK_PATH
== NULL
) {
2160 const char** fpaths
= sFrameworkFallbackPaths
;
2162 removePathWithPrefix(fpaths
, "$HOME");
2164 paths_expand_roots(fpaths
, "$HOME", home
);
2165 sEnv
.DYLD_FALLBACK_FRAMEWORK_PATH
= fpaths
;
2168 // default value for DYLD_FALLBACK_LIBRARY_PATH, if not set in environment
2169 if ( sEnv
.DYLD_FALLBACK_LIBRARY_PATH
== NULL
) {
2170 const char** lpaths
= sLibraryFallbackPaths
;
2172 removePathWithPrefix(lpaths
, "$HOME");
2174 paths_expand_roots(lpaths
, "$HOME", home
);
2175 sEnv
.DYLD_FALLBACK_LIBRARY_PATH
= lpaths
;
2178 if ( sEnv
.DYLD_FALLBACK_FRAMEWORK_PATH
== NULL
)
2179 sEnv
.DYLD_FALLBACK_FRAMEWORK_PATH
= sFrameworkFallbackPaths
;
2181 if ( sEnv
.DYLD_FALLBACK_LIBRARY_PATH
== NULL
)
2182 sEnv
.DYLD_FALLBACK_LIBRARY_PATH
= sLibraryFallbackPaths
;
2187 static void checkEnvironmentVariables(const char* envp
[])
2189 if ( sEnvMode
== envNone
)
2192 for(p
= envp
; *p
!= NULL
; p
++) {
2193 const char* keyEqualsValue
= *p
;
2194 if ( strncmp(keyEqualsValue
, "DYLD_", 5) == 0 ) {
2195 const char* equals
= strchr(keyEqualsValue
, '=');
2196 if ( equals
!= NULL
) {
2197 strlcat(sLoadingCrashMessage
, "\n", sizeof(sLoadingCrashMessage
));
2198 strlcat(sLoadingCrashMessage
, keyEqualsValue
, sizeof(sLoadingCrashMessage
));
2199 const char* value
= &equals
[1];
2200 const size_t keyLen
= equals
-keyEqualsValue
;
2202 strncpy(key
, keyEqualsValue
, keyLen
);
2204 if ( (sEnvMode
== envPrintOnly
) && (strncmp(key
, "DYLD_PRINT_", 11) != 0) )
2206 processDyldEnvironmentVariable(key
, value
, NULL
);
2209 else if ( strncmp(keyEqualsValue
, "LD_LIBRARY_PATH=", 16) == 0 ) {
2210 const char* path
= &keyEqualsValue
[16];
2211 sEnv
.LD_LIBRARY_PATH
= parseColonList(path
, NULL
);
2215 #if SUPPORT_LC_DYLD_ENVIRONMENT
2216 checkLoadCommandEnvironmentVariables();
2217 #endif // SUPPORT_LC_DYLD_ENVIRONMENT
2219 #if SUPPORT_ROOT_PATH
2220 // <rdar://problem/11281064> DYLD_IMAGE_SUFFIX and DYLD_ROOT_PATH cannot be used together
2221 if ( (gLinkContext
.imageSuffix
!= NULL
) && (gLinkContext
.rootPaths
!= NULL
) ) {
2222 dyld::warn("Ignoring DYLD_IMAGE_SUFFIX because DYLD_ROOT_PATH is used.\n");
2223 gLinkContext
.imageSuffix
= NULL
;
2228 #if __x86_64__ && !TARGET_IPHONE_SIMULATOR
2229 static bool isGCProgram(const macho_header
* mh
, uintptr_t slide
)
2231 const uint32_t cmd_count
= mh
->ncmds
;
2232 const struct load_command
* const cmds
= (struct load_command
*)(((char*)mh
)+sizeof(macho_header
));
2233 const struct load_command
* cmd
= cmds
;
2234 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
2236 case LC_SEGMENT_COMMAND
:
2238 const struct macho_segment_command
* seg
= (struct macho_segment_command
*)cmd
;
2239 if (strcmp(seg
->segname
, "__DATA") == 0) {
2240 const struct macho_section
* const sectionsStart
= (struct macho_section
*)((char*)seg
+ sizeof(struct macho_segment_command
));
2241 const struct macho_section
* const sectionsEnd
= §ionsStart
[seg
->nsects
];
2242 for (const struct macho_section
* sect
=sectionsStart
; sect
< sectionsEnd
; ++sect
) {
2243 if (strncmp(sect
->sectname
, "__objc_imageinfo", 16) == 0) {
2244 const uint32_t* objcInfo
= (uint32_t*)(sect
->addr
+ slide
);
2245 return (objcInfo
[1] & 6); // 6 = (OBJC_IMAGE_SUPPORTS_GC | OBJC_IMAGE_REQUIRES_GC)
2252 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
2258 static void getHostInfo(const macho_header
* mainExecutableMH
, uintptr_t mainExecutableSlide
)
2260 #if CPU_SUBTYPES_SUPPORTED
2262 sHostCPU
= CPU_TYPE_ARM
;
2263 sHostCPUsubtype
= CPU_SUBTYPE_ARM_V7K
;
2264 #elif __ARM_ARCH_7A__
2265 sHostCPU
= CPU_TYPE_ARM
;
2266 sHostCPUsubtype
= CPU_SUBTYPE_ARM_V7
;
2267 #elif __ARM_ARCH_6K__
2268 sHostCPU
= CPU_TYPE_ARM
;
2269 sHostCPUsubtype
= CPU_SUBTYPE_ARM_V6
;
2270 #elif __ARM_ARCH_7F__
2271 sHostCPU
= CPU_TYPE_ARM
;
2272 sHostCPUsubtype
= CPU_SUBTYPE_ARM_V7F
;
2273 #elif __ARM_ARCH_7S__
2274 sHostCPU
= CPU_TYPE_ARM
;
2275 sHostCPUsubtype
= CPU_SUBTYPE_ARM_V7S
;
2277 sHostCPU
= CPU_TYPE_ARM64
;
2278 sHostCPUsubtype
= CPU_SUBTYPE_ARM64_E
;
2280 sHostCPU
= CPU_TYPE_ARM64
;
2281 sHostCPUsubtype
= CPU_SUBTYPE_ARM64_V8
;
2283 struct host_basic_info info
;
2284 mach_msg_type_number_t count
= HOST_BASIC_INFO_COUNT
;
2285 mach_port_t hostPort
= mach_host_self();
2286 kern_return_t result
= host_info(hostPort
, HOST_BASIC_INFO
, (host_info_t
)&info
, &count
);
2287 if ( result
!= KERN_SUCCESS
)
2288 throw "host_info() failed";
2289 sHostCPU
= info
.cpu_type
;
2290 sHostCPUsubtype
= info
.cpu_subtype
;
2291 mach_port_deallocate(mach_task_self(), hostPort
);
2293 // host_info returns CPU_TYPE_I386 even for x86_64. Override that here so that
2294 // we don't need to mask the cpu type later.
2295 sHostCPU
= CPU_TYPE_X86_64
;
2296 #if !TARGET_IPHONE_SIMULATOR
2297 sHaswell
= (sHostCPUsubtype
== CPU_SUBTYPE_X86_64_H
);
2298 // <rdar://problem/18528074> x86_64h: Fall back to the x86_64 slice if an app requires GC.
2300 if ( isGCProgram(mainExecutableMH
, mainExecutableSlide
) ) {
2301 // When running a GC program on a haswell machine, don't use and 'h slices
2302 sHostCPUsubtype
= CPU_SUBTYPE_X86_64_ALL
;
2304 gLinkContext
.sharedRegionMode
= ImageLoader::kDontUseSharedRegion
;
2313 static void checkSharedRegionDisable(const mach_header
* mainExecutableMH
)
2315 #if __MAC_OS_X_VERSION_MIN_REQUIRED
2316 // if main executable has segments that overlap the shared region,
2317 // then disable using the shared region
2318 dyld3::MachOParser
parser(mainExecutableMH
);
2319 uintptr_t slide
= parser
.getSlide();
2320 dyld3::launch_cache::MemoryRange sharedRegion
= { (void*)(long)(SHARED_REGION_BASE
), SHARED_REGION_SIZE
};
2321 __block
bool disable
= false;
2322 parser
.forEachSegment(^(const char *segName
, uint32_t fileOffset
, uint32_t fileSize
, uint64_t vmAddr
, uint64_t vmSize
, uint8_t protections
, bool &stop
) {
2323 dyld3::launch_cache::MemoryRange segRegion
= { (void*)(long)(vmAddr
+slide
), vmSize
};
2324 if ( segRegion
.intersects(sharedRegion
) )
2328 gLinkContext
.sharedRegionMode
= ImageLoader::kDontUseSharedRegion
;
2329 if ( gLinkContext
.verboseMapping
)
2330 dyld::warn("disabling shared region because main executable overlaps\n");
2333 if ( gLinkContext
.processIsRestricted
) {
2334 // <rdar://problem/15280847> use private or no shared region for suid processes
2335 gLinkContext
.sharedRegionMode
= ImageLoader::kUsePrivateSharedRegion
;
2339 // iOS cannot run without shared region
2342 bool validImage(const ImageLoader
* possibleImage
)
2344 const size_t imageCount
= sAllImages
.size();
2345 for(size_t i
=0; i
< imageCount
; ++i
) {
2346 if ( possibleImage
== sAllImages
[i
] ) {
2353 uint32_t getImageCount()
2355 return (uint32_t)sAllImages
.size();
2358 ImageLoader
* getIndexedImage(unsigned int index
)
2360 if ( index
< sAllImages
.size() )
2361 return sAllImages
[index
];
2365 ImageLoader
* findImageByMachHeader(const struct mach_header
* target
)
2367 return findMappedRange((uintptr_t)target
);
2371 ImageLoader
* findImageContainingAddress(const void* addr
)
2373 #if SUPPORT_ACCELERATE_TABLES
2374 if ( sAllCacheImagesProxy
!= NULL
) {
2375 const mach_header
* mh
;
2378 if ( sAllCacheImagesProxy
->addressInCache(addr
, &mh
, &path
, &index
) )
2379 return sAllCacheImagesProxy
;
2382 return findMappedRange((uintptr_t)addr
);
2386 ImageLoader
* findImageContainingSymbol(const void* symbol
)
2388 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
2389 ImageLoader
* anImage
= *it
;
2390 if ( anImage
->containsSymbol(symbol
) )
2398 void forEachImageDo( void (*callback
)(ImageLoader
*, void* userData
), void* userData
)
2400 const size_t imageCount
= sAllImages
.size();
2401 for(size_t i
=0; i
< imageCount
; ++i
) {
2402 ImageLoader
* anImage
= sAllImages
[i
];
2403 (*callback
)(anImage
, userData
);
2407 ImageLoader
* findLoadedImage(const struct stat
& stat_buf
)
2409 const size_t imageCount
= sAllImages
.size();
2410 for(size_t i
=0; i
< imageCount
; ++i
){
2411 ImageLoader
* anImage
= sAllImages
[i
];
2412 if ( anImage
->statMatch(stat_buf
) )
2418 // based on ANSI-C strstr()
2419 static const char* strrstr(const char* str
, const char* sub
)
2421 const size_t sublen
= strlen(sub
);
2422 for(const char* p
= &str
[strlen(str
)]; p
!= str
; --p
) {
2423 if ( strncmp(p
, sub
, sublen
) == 0 )
2431 // Find framework path
2433 // /path/foo.framework/foo => foo.framework/foo
2434 // /path/foo.framework/Versions/A/foo => foo.framework/Versions/A/foo
2435 // /path/foo.framework/Frameworks/bar.framework/bar => bar.framework/bar
2436 // /path/foo.framework/Libraries/bar.dylb => NULL
2437 // /path/foo.framework/bar => NULL
2439 // Returns NULL if not a framework path
2441 static const char* getFrameworkPartialPath(const char* path
)
2443 const char* dirDot
= strrstr(path
, ".framework/");
2444 if ( dirDot
!= NULL
) {
2445 const char* dirStart
= dirDot
;
2446 for ( ; dirStart
>= path
; --dirStart
) {
2447 if ( (*dirStart
== '/') || (dirStart
== path
) ) {
2448 const char* frameworkStart
= &dirStart
[1];
2449 if ( dirStart
== path
)
2451 size_t len
= dirDot
- frameworkStart
;
2452 char framework
[len
+1];
2453 strncpy(framework
, frameworkStart
, len
);
2454 framework
[len
] = '\0';
2455 const char* leaf
= strrchr(path
, '/');
2456 if ( leaf
!= NULL
) {
2457 if ( strcmp(framework
, &leaf
[1]) == 0 ) {
2458 return frameworkStart
;
2460 if ( gLinkContext
.imageSuffix
!= NULL
) {
2461 // some debug frameworks have install names that end in _debug
2462 if ( strncmp(framework
, &leaf
[1], len
) == 0 ) {
2463 if ( strcmp( gLinkContext
.imageSuffix
, &leaf
[len
+1]) == 0 )
2464 return frameworkStart
;
2475 static const char* getLibraryLeafName(const char* path
)
2477 const char* start
= strrchr(path
, '/');
2478 if ( start
!= NULL
)
2485 // only for architectures that use cpu-sub-types
2486 #if CPU_SUBTYPES_SUPPORTED
2488 const cpu_subtype_t CPU_SUBTYPE_END_OF_LIST
= -1;
2492 // A fat file may contain multiple sub-images for the same CPU type.
2493 // In that case, dyld picks which sub-image to use by scanning a table
2494 // of preferred cpu-sub-types for the running cpu.
2496 // There is one row in the table for each cpu-sub-type on which dyld might run.
2497 // The first entry in a row is that cpu-sub-type. It is followed by all
2498 // cpu-sub-types that can run on that cpu, if preferred order. Each row ends with
2499 // a "SUBTYPE_ALL" (to denote that images written to run on any cpu-sub-type are usable),
2500 // followed by one or more CPU_SUBTYPE_END_OF_LIST to pad out this row.
2506 // ARM sub-type lists
2508 const int kARM_RowCount
= 8;
2509 static const cpu_subtype_t kARM
[kARM_RowCount
][9] = {
2511 // armv7f can run: v7f, v7, v6, v5, and v4
2512 { 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
},
2514 // armv7k can run: v7k
2515 { CPU_SUBTYPE_ARM_V7K
, CPU_SUBTYPE_END_OF_LIST
},
2517 // armv7s can run: v7s, v7, v7f, v7k, v6, v5, and v4
2518 { 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
},
2520 // armv7 can run: v7, v6, v5, and v4
2521 { 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
},
2523 // armv6 can run: v6, v5, and v4
2524 { 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
},
2526 // xscale can run: xscale, v5, and v4
2527 { 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
},
2529 // armv5 can run: v5 and v4
2530 { 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
},
2532 // armv4 can run: v4
2533 { 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
},
2539 // ARM64 sub-type lists
2541 const int kARM64_RowCount
= 2;
2542 static const cpu_subtype_t kARM64
[kARM64_RowCount
][4] = {
2544 // armv64e can run: 64e, 64
2545 { CPU_SUBTYPE_ARM64_E
, CPU_SUBTYPE_ARM64_V8
, CPU_SUBTYPE_ARM64_ALL
, CPU_SUBTYPE_END_OF_LIST
},
2547 // armv64 can run: 64
2548 { CPU_SUBTYPE_ARM64_V8
, CPU_SUBTYPE_ARM64_ALL
, CPU_SUBTYPE_END_OF_LIST
},
2554 // x86_64 sub-type lists
2556 const int kX86_64_RowCount
= 2;
2557 static const cpu_subtype_t kX86_64
[kX86_64_RowCount
][5] = {
2559 // x86_64h can run: x86_64h, x86_64h(lib), x86_64(lib), and x86_64
2560 { CPU_SUBTYPE_X86_64_H
, (cpu_subtype_t
)(CPU_SUBTYPE_LIB64
|CPU_SUBTYPE_X86_64_H
), (cpu_subtype_t
)(CPU_SUBTYPE_LIB64
|CPU_SUBTYPE_X86_64_ALL
), CPU_SUBTYPE_X86_64_ALL
, CPU_SUBTYPE_END_OF_LIST
},
2562 // x86_64 can run: x86_64(lib) and x86_64
2563 { CPU_SUBTYPE_X86_64_ALL
, (cpu_subtype_t
)(CPU_SUBTYPE_LIB64
|CPU_SUBTYPE_X86_64_ALL
), CPU_SUBTYPE_END_OF_LIST
},
2569 // scan the tables above to find the cpu-sub-type-list for this machine
2570 static const cpu_subtype_t
* findCPUSubtypeList(cpu_type_t cpu
, cpu_subtype_t subtype
)
2575 for (int i
=0; i
< kARM_RowCount
; ++i
) {
2576 if ( kARM
[i
][0] == subtype
)
2582 case CPU_TYPE_ARM64
:
2583 for (int i
=0; i
< kARM64_RowCount
; ++i
) {
2584 if ( kARM64
[i
][0] == subtype
)
2590 case CPU_TYPE_X86_64
:
2591 for (int i
=0; i
< kX86_64_RowCount
; ++i
) {
2592 if ( kX86_64
[i
][0] == subtype
)
2604 // scan fat table-of-contents for best most preferred subtype
2605 static bool fatFindBestFromOrderedList(cpu_type_t cpu
, const cpu_subtype_t list
[], const fat_header
* fh
, uint64_t* offset
, uint64_t* len
)
2607 const fat_arch
* const archs
= (fat_arch
*)(((char*)fh
)+sizeof(fat_header
));
2608 for (uint32_t subTypeIndex
=0; list
[subTypeIndex
] != CPU_SUBTYPE_END_OF_LIST
; ++subTypeIndex
) {
2609 for(uint32_t fatIndex
=0; fatIndex
< OSSwapBigToHostInt32(fh
->nfat_arch
); ++fatIndex
) {
2610 if ( ((cpu_type_t
)OSSwapBigToHostInt32(archs
[fatIndex
].cputype
) == cpu
)
2611 && (list
[subTypeIndex
] == (cpu_subtype_t
)OSSwapBigToHostInt32(archs
[fatIndex
].cpusubtype
)) ) {
2612 *offset
= OSSwapBigToHostInt32(archs
[fatIndex
].offset
);
2613 *len
= OSSwapBigToHostInt32(archs
[fatIndex
].size
);
2621 // scan fat table-of-contents for exact match of cpu and cpu-sub-type
2622 static bool fatFindExactMatch(cpu_type_t cpu
, cpu_subtype_t subtype
, const fat_header
* fh
, uint64_t* offset
, uint64_t* len
)
2624 const fat_arch
* archs
= (fat_arch
*)(((char*)fh
)+sizeof(fat_header
));
2625 for(uint32_t i
=0; i
< OSSwapBigToHostInt32(fh
->nfat_arch
); ++i
) {
2626 if ( ((cpu_type_t
)OSSwapBigToHostInt32(archs
[i
].cputype
) == cpu
)
2627 && ((cpu_subtype_t
)OSSwapBigToHostInt32(archs
[i
].cpusubtype
) == subtype
) ) {
2628 *offset
= OSSwapBigToHostInt32(archs
[i
].offset
);
2629 *len
= OSSwapBigToHostInt32(archs
[i
].size
);
2636 // scan fat table-of-contents for image with matching cpu-type and runs-on-all-sub-types
2637 static bool fatFindRunsOnAllCPUs(cpu_type_t cpu
, const fat_header
* fh
, uint64_t* offset
, uint64_t* len
)
2639 const fat_arch
* archs
= (fat_arch
*)(((char*)fh
)+sizeof(fat_header
));
2640 for(uint32_t i
=0; i
< OSSwapBigToHostInt32(fh
->nfat_arch
); ++i
) {
2641 if ( (cpu_type_t
)OSSwapBigToHostInt32(archs
[i
].cputype
) == cpu
) {
2645 if ( (cpu_subtype_t
)OSSwapBigToHostInt32(archs
[i
].cpusubtype
) == CPU_SUBTYPE_ARM_ALL
) {
2646 *offset
= OSSwapBigToHostInt32(archs
[i
].offset
);
2647 *len
= OSSwapBigToHostInt32(archs
[i
].size
);
2653 case CPU_TYPE_ARM64
:
2654 if ( (cpu_subtype_t
)OSSwapBigToHostInt32(archs
[i
].cpusubtype
) == CPU_SUBTYPE_ARM64_ALL
) {
2655 *offset
= OSSwapBigToHostInt32(archs
[i
].offset
);
2656 *len
= OSSwapBigToHostInt32(archs
[i
].size
);
2662 case CPU_TYPE_X86_64
:
2663 if ( (cpu_subtype_t
)OSSwapBigToHostInt32(archs
[i
].cpusubtype
) == CPU_SUBTYPE_X86_64_ALL
) {
2664 *offset
= OSSwapBigToHostInt32(archs
[i
].offset
);
2665 *len
= OSSwapBigToHostInt32(archs
[i
].size
);
2676 #endif // CPU_SUBTYPES_SUPPORTED
2680 // Validate the fat_header and fat_arch array:
2682 // 1) arch count would not cause array to extend past 4096 byte read buffer
2683 // 2) no slice overlaps the fat_header and arch array
2684 // 3) arch list does not contain duplicate cputype/cpusubtype tuples
2685 // 4) arch list does not have two overlapping slices.
2687 static bool fatValidate(const fat_header
* fh
)
2689 if ( fh
->magic
!= OSSwapBigToHostInt32(FAT_MAGIC
) )
2692 // since only first 4096 bytes of file read, we can only handle up to 204 slices.
2693 const uint32_t sliceCount
= OSSwapBigToHostInt32(fh
->nfat_arch
);
2694 if ( sliceCount
> 204 )
2697 // compare all slices looking for conflicts
2698 const fat_arch
* archs
= (fat_arch
*)(((char*)fh
)+sizeof(fat_header
));
2699 for (uint32_t i
=0; i
< sliceCount
; ++i
) {
2700 uint32_t i_offset
= OSSwapBigToHostInt32(archs
[i
].offset
);
2701 uint32_t i_size
= OSSwapBigToHostInt32(archs
[i
].size
);
2702 uint32_t i_cputype
= OSSwapBigToHostInt32(archs
[i
].cputype
);
2703 uint32_t i_cpusubtype
= OSSwapBigToHostInt32(archs
[i
].cpusubtype
);
2704 uint32_t i_end
= i_offset
+ i_size
;
2705 // slice cannot overlap with header
2706 if ( i_offset
< 4096 )
2708 // slice size cannot overflow
2709 if ( i_end
< i_offset
)
2711 for (uint32_t j
=i
+1; j
< sliceCount
; ++j
) {
2712 uint32_t j_offset
= OSSwapBigToHostInt32(archs
[j
].offset
);
2713 uint32_t j_size
= OSSwapBigToHostInt32(archs
[j
].size
);
2714 uint32_t j_cputype
= OSSwapBigToHostInt32(archs
[j
].cputype
);
2715 uint32_t j_cpusubtype
= OSSwapBigToHostInt32(archs
[j
].cpusubtype
);
2716 uint32_t j_end
= j_offset
+ j_size
;
2717 // duplicate slices types not allowed
2718 if ( (i_cputype
== j_cputype
) && (i_cpusubtype
== j_cpusubtype
) )
2720 // slice size cannot overflow
2721 if ( j_end
< j_offset
)
2723 // check for overlap of slices
2724 if ( i_offset
<= j_offset
) {
2725 if ( j_offset
< i_end
)
2726 return false; // j overlaps end of i
2729 // j overlaps end of i
2730 if ( i_offset
< j_end
)
2731 return false; // i overlaps end of j
2739 // A fat file may contain multiple sub-images for the same cpu-type,
2740 // each optimized for a different cpu-sub-type (e.g G3 or G5).
2741 // This routine picks the optimal sub-image.
2743 static bool fatFindBest(const fat_header
* fh
, uint64_t* offset
, uint64_t* len
)
2745 if ( !fatValidate(fh
) )
2748 #if CPU_SUBTYPES_SUPPORTED
2749 // assume all dylibs loaded must have same cpu type as main executable
2750 const cpu_type_t cpu
= sMainExecutableMachHeader
->cputype
;
2752 // We only know the subtype to use if the main executable cpu type matches the host
2753 if ( cpu
== sHostCPU
) {
2754 // get preference ordered list of subtypes
2755 const cpu_subtype_t
* subTypePreferenceList
= findCPUSubtypeList(cpu
, sHostCPUsubtype
);
2757 // use ordered list to find best sub-image in fat file
2758 if ( subTypePreferenceList
!= NULL
) {
2759 if ( fatFindBestFromOrderedList(cpu
, subTypePreferenceList
, fh
, offset
, len
) )
2763 // if running cpu is not in list, try for an exact match
2764 if ( fatFindExactMatch(cpu
, sHostCPUsubtype
, fh
, offset
, len
) )
2768 // running on an uknown cpu, can only load generic code
2769 return fatFindRunsOnAllCPUs(cpu
, fh
, offset
, len
);
2771 // just find first slice with matching architecture
2772 const fat_arch
* archs
= (fat_arch
*)(((char*)fh
)+sizeof(fat_header
));
2773 for(uint32_t i
=0; i
< OSSwapBigToHostInt32(fh
->nfat_arch
); ++i
) {
2774 if ( (cpu_type_t
)OSSwapBigToHostInt32(archs
[i
].cputype
) == sMainExecutableMachHeader
->cputype
) {
2775 *offset
= OSSwapBigToHostInt32(archs
[i
].offset
);
2776 *len
= OSSwapBigToHostInt32(archs
[i
].size
);
2787 // This is used to validate if a non-fat (aka thin or raw) mach-o file can be used
2788 // on the current processor. //
2789 bool isCompatibleMachO(const uint8_t* firstPage
, const char* path
)
2791 #if CPU_SUBTYPES_SUPPORTED
2792 // It is deemed compatible if any of the following are true:
2793 // 1) mach_header subtype is in list of compatible subtypes for running processor
2794 // 2) mach_header subtype is same as running processor subtype
2795 // 3) mach_header subtype runs on all processor variants
2796 const mach_header
* mh
= (mach_header
*)firstPage
;
2797 if ( mh
->magic
== sMainExecutableMachHeader
->magic
) {
2798 if ( mh
->cputype
== sMainExecutableMachHeader
->cputype
) {
2799 if ( mh
->cputype
== sHostCPU
) {
2800 // get preference ordered list of subtypes that this machine can use
2801 const cpu_subtype_t
* subTypePreferenceList
= findCPUSubtypeList(mh
->cputype
, sHostCPUsubtype
);
2802 if ( subTypePreferenceList
!= NULL
) {
2803 // if image's subtype is in the list, it is compatible
2804 for (const cpu_subtype_t
* p
= subTypePreferenceList
; *p
!= CPU_SUBTYPE_END_OF_LIST
; ++p
) {
2805 if ( *p
== mh
->cpusubtype
)
2808 // have list and not in list, so not compatible
2809 throwf("incompatible cpu-subtype: 0x%08X in %s", mh
->cpusubtype
, path
);
2811 // unknown cpu sub-type, but if exact match for current subtype then ok to use
2812 if ( mh
->cpusubtype
== sHostCPUsubtype
)
2816 // cpu type has no ordered list of subtypes
2817 switch (mh
->cputype
) {
2819 case CPU_TYPE_X86_64
:
2820 // subtypes are not used or these architectures
2826 // For architectures that don't support cpu-sub-types
2827 // this just check the cpu type.
2828 const mach_header
* mh
= (mach_header
*)firstPage
;
2829 if ( mh
->magic
== sMainExecutableMachHeader
->magic
) {
2830 if ( mh
->cputype
== sMainExecutableMachHeader
->cputype
) {
2841 // The kernel maps in main executable before dyld gets control. We need to
2842 // make an ImageLoader* for the already mapped in main executable.
2843 static ImageLoaderMachO
* instantiateFromLoadedImage(const macho_header
* mh
, uintptr_t slide
, const char* path
)
2845 // try mach-o loader
2846 if ( isCompatibleMachO((const uint8_t*)mh
, path
) ) {
2847 ImageLoader
* image
= ImageLoaderMachO::instantiateMainExecutable(mh
, slide
, path
, gLinkContext
);
2849 return (ImageLoaderMachO
*)image
;
2852 throw "main executable not a known format";
2855 #if SUPPORT_ACCELERATE_TABLES
2856 static bool dylibsCanOverrideCache()
2858 if ( !dyld3::loader::internalInstall() )
2860 return ( (sSharedCacheLoadInfo
.loadAddress
!= nullptr) && (sSharedCacheLoadInfo
.loadAddress
->header
.cacheType
== kDyldSharedCacheTypeDevelopment
) );
2864 const void* imMemorySharedCacheHeader()
2866 return sSharedCacheLoadInfo
.loadAddress
;
2870 const char* getStandardSharedCacheFilePath()
2872 if ( sSharedCacheLoadInfo
.loadAddress
!= nullptr )
2873 return sSharedCacheLoadInfo
.path
;
2879 static bool findInSharedCacheImage(const char* path
, bool searchByPath
, const struct stat
* stat_buf
, const macho_header
** mh
, const char** pathInCache
, long* slide
)
2881 dyld3::SharedCacheFindDylibResults results
;
2882 if ( dyld3::findInSharedCacheImage(sSharedCacheLoadInfo
, path
, &results
) ) {
2883 *mh
= (macho_header
*)results
.mhInCache
;
2884 *pathInCache
= results
.pathInCache
;
2885 *slide
= results
.slideInCache
;
2891 bool inSharedCache(const char* path
)
2893 return dyld3::pathIsInSharedCacheImage(sSharedCacheLoadInfo
, path
);
2897 static ImageLoader
* checkandAddImage(ImageLoader
* image
, const LoadContext
& context
)
2899 // now sanity check that this loaded image does not have the same install path as any existing image
2900 const char* loadedImageInstallPath
= image
->getInstallPath();
2901 if ( image
->isDylib() && (loadedImageInstallPath
!= NULL
) && (loadedImageInstallPath
[0] == '/') ) {
2902 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
2903 ImageLoader
* anImage
= *it
;
2904 const char* installPath
= anImage
->getInstallPath();
2905 if ( installPath
!= NULL
) {
2906 if ( strcmp(loadedImageInstallPath
, installPath
) == 0 ) {
2907 //dyld::log("duplicate(%s) => %p\n", installPath, anImage);
2909 ImageLoader::deleteImage(image
);
2916 // some API's restrict what they can load
2917 if ( context
.mustBeBundle
&& !image
->isBundle() )
2918 throw "not a bundle";
2919 if ( context
.mustBeDylib
&& !image
->isDylib() )
2920 throw "not a dylib";
2922 // regular main executables cannot be loaded
2923 if ( image
->isExecutable() ) {
2924 if ( !context
.canBePIE
|| !image
->isPositionIndependentExecutable() )
2925 throw "can't load a main executable";
2928 // don't add bundles to global list, they can be loaded but not linked. When linked it will be added to list
2929 if ( ! image
->isBundle() )
2935 #if TARGET_IPHONE_SIMULATOR
2936 static bool isSimulatorBinary(const uint8_t* firstPages
, const char* path
)
2938 const macho_header
* mh
= (macho_header
*)firstPages
;
2939 const uint32_t cmd_count
= mh
->ncmds
;
2940 const load_command
* const cmds
= (struct load_command
*)(((char*)mh
)+sizeof(macho_header
));
2941 const load_command
* const cmdsEnd
= (load_command
*)((char*)cmds
+ mh
->sizeofcmds
);
2942 const struct load_command
* cmd
= cmds
;
2943 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
2946 case LC_VERSION_MIN_WATCHOS
:
2949 case LC_VERSION_MIN_TVOS
:
2952 case LC_VERSION_MIN_IPHONEOS
:
2955 case LC_VERSION_MIN_MACOSX
:
2956 // grandfather in a few libSystem dylibs
2957 if ((strcmp(path
, "/usr/lib/system/libsystem_kernel.dylib") == 0) ||
2958 (strcmp(path
, "/usr/lib/system/libsystem_platform.dylib") == 0) ||
2959 (strcmp(path
, "/usr/lib/system/libsystem_pthread.dylib") == 0))
2963 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
2964 if ( cmd
> cmdsEnd
)
2971 // map in file and instantiate an ImageLoader
2972 static ImageLoader
* loadPhase6(int fd
, const struct stat
& stat_buf
, const char* path
, const LoadContext
& context
)
2974 //dyld::log("%s(%s)\n", __func__ , path);
2975 uint64_t fileOffset
= 0;
2976 uint64_t fileLength
= stat_buf
.st_size
;
2978 // validate it is a file (not directory)
2979 if ( (stat_buf
.st_mode
& S_IFMT
) != S_IFREG
)
2982 uint8_t firstPages
[MAX_MACH_O_HEADER_AND_LOAD_COMMANDS_SIZE
];
2983 bool shortPage
= false;
2985 // min mach-o file is 4K
2986 if ( fileLength
< 4096 ) {
2987 if ( pread(fd
, firstPages
, (size_t)fileLength
, 0) != (ssize_t
)fileLength
)
2988 throwf("pread of short file failed: %d", errno
);
2992 // optimistically read only first 4KB
2993 if ( pread(fd
, firstPages
, 4096, 0) != 4096 )
2994 throwf("pread of first 4K failed: %d", errno
);
2997 // if fat wrapper, find usable sub-file
2998 const fat_header
* fileStartAsFat
= (fat_header
*)firstPages
;
2999 if ( fileStartAsFat
->magic
== OSSwapBigToHostInt32(FAT_MAGIC
) ) {
3000 if ( OSSwapBigToHostInt32(fileStartAsFat
->nfat_arch
) > ((4096 - sizeof(fat_header
)) / sizeof(fat_arch
)) )
3001 throwf("fat header too large: %u entries", OSSwapBigToHostInt32(fileStartAsFat
->nfat_arch
));
3002 if ( fatFindBest(fileStartAsFat
, &fileOffset
, &fileLength
) ) {
3003 if ( (fileOffset
+fileLength
) > (uint64_t)(stat_buf
.st_size
) )
3004 throwf("truncated fat file. file length=%llu, but needed slice goes to %llu", stat_buf
.st_size
, fileOffset
+fileLength
);
3005 if (pread(fd
, firstPages
, 4096, fileOffset
) != 4096)
3006 throwf("pread of fat file failed: %d", errno
);
3009 throw "no matching architecture in universal wrapper";
3013 // try mach-o loader
3015 throw "file too short";
3016 if ( isCompatibleMachO(firstPages
, path
) ) {
3018 // only MH_BUNDLE, MH_DYLIB, and some MH_EXECUTE can be dynamically loaded
3019 const mach_header
* mh
= (mach_header
*)firstPages
;
3020 switch ( mh
->filetype
) {
3026 throw "mach-o, but wrong filetype";
3029 uint32_t headerAndLoadCommandsSize
= sizeof(macho_header
) + mh
->sizeofcmds
;
3030 if ( headerAndLoadCommandsSize
> MAX_MACH_O_HEADER_AND_LOAD_COMMANDS_SIZE
)
3031 throwf("malformed mach-o: load commands size (%u) > %u", headerAndLoadCommandsSize
, MAX_MACH_O_HEADER_AND_LOAD_COMMANDS_SIZE
);
3033 if ( headerAndLoadCommandsSize
> fileLength
)
3034 dyld::throwf("malformed mach-o: load commands size (%u) > mach-o file size (%llu)", headerAndLoadCommandsSize
, fileLength
);
3036 if ( headerAndLoadCommandsSize
> 4096 ) {
3038 unsigned readAmount
= headerAndLoadCommandsSize
- 4096;
3039 if ( pread(fd
, &firstPages
[4096], readAmount
, fileOffset
+4096) != readAmount
)
3040 throwf("pread of extra load commands past 4KB failed: %d", errno
);
3043 #if TARGET_IPHONE_SIMULATOR
3044 // <rdar://problem/14168872> dyld_sim should restrict loading osx binaries
3045 if ( !isSimulatorBinary(firstPages
, path
) ) {
3047 throw "mach-o, but not built for watchOS simulator";
3049 throw "mach-o, but not built for tvOS simulator";
3051 throw "mach-o, but not built for iOS simulator";
3056 // instantiate an image
3057 ImageLoader
* image
= ImageLoaderMachO::instantiateFromFile(path
, fd
, firstPages
, headerAndLoadCommandsSize
, fileOffset
, fileLength
, stat_buf
, gLinkContext
);
3060 return checkandAddImage(image
, context
);
3063 // try other file formats here...
3066 // throw error about what was found
3067 switch (*(uint32_t*)firstPages
) {
3072 throw "mach-o, but wrong architecture";
3074 throwf("unknown file type, first eight bytes: 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X",
3075 firstPages
[0], firstPages
[1], firstPages
[2], firstPages
[3], firstPages
[4], firstPages
[5], firstPages
[6],firstPages
[7]);
3080 static ImageLoader
* loadPhase5open(const char* path
, const LoadContext
& context
, const struct stat
& stat_buf
, std::vector
<const char*>* exceptions
)
3082 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
3084 // open file (automagically closed when this function exits)
3085 FileOpener
file(path
);
3087 // just return NULL if file not found, but record any other errors
3088 if ( file
.getFileDescriptor() == -1 ) {
3090 if ( err
!= ENOENT
) {
3092 if ( (err
== EPERM
) && sandboxBlockedOpen(path
) )
3093 newMsg
= dyld::mkstringf("file system sandbox blocked open() of '%s'", path
);
3095 newMsg
= dyld::mkstringf("%s: open() failed with errno=%d", path
, err
);
3096 exceptions
->push_back(newMsg
);
3102 return loadPhase6(file
.getFileDescriptor(), stat_buf
, path
, context
);
3104 catch (const char* msg
) {
3105 const char* newMsg
= dyld::mkstringf("%s: %s", path
, msg
);
3106 exceptions
->push_back(newMsg
);
3115 static ImageLoader
* loadPhase5load(const char* path
, const char* orgPath
, const LoadContext
& context
, unsigned& cacheIndex
, std::vector
<const char*>* exceptions
)
3117 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
3118 #if SUPPORT_ACCELERATE_TABLES
3119 if ( sAllCacheImagesProxy
!= NULL
) {
3120 if ( sAllCacheImagesProxy
->hasDylib(path
, &cacheIndex
) )
3121 return sAllCacheImagesProxy
;
3124 #if TARGET_IPHONE_SIMULATOR
3125 // in simulators, 'path' has DYLD_ROOT_PATH prepended, but cache index does not have the prefix, so use orgPath
3126 const char* pathToFindInCache
= orgPath
;
3128 const char* pathToFindInCache
= path
;
3131 struct stat statBuf
;
3132 bool didStat
= false;
3134 dyld3::SharedCacheFindDylibResults shareCacheResults
;
3135 if ( dyld3::findInSharedCacheImage(sSharedCacheLoadInfo
, pathToFindInCache
, &shareCacheResults
) ) {
3136 // see if this image in the cache was already loaded via a different path
3137 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); ++it
) {
3138 ImageLoader
* anImage
= *it
;
3139 if ( (const mach_header
*)anImage
->machHeader() == shareCacheResults
.mhInCache
)
3142 // if RTLD_NOLOAD, do nothing if not already loaded
3143 if ( context
.dontLoad
) {
3144 // <rdar://33412890> possible that there is an override of cache
3145 if ( my_stat(path
, &statBuf
) == 0 ) {
3146 ImageLoader
* imageLoader
= findLoadedImage(statBuf
);
3147 if ( imageLoader
!= NULL
)
3152 bool useCache
= false;
3153 if ( shareCacheResults
.imageData
== nullptr ) {
3154 // HACK to support old caches
3155 existsOnDisk
= ( my_stat(path
, &statBuf
) == 0 );
3158 useCache
= !existsOnDisk
;
3161 // <rdar://problem/7014995> zero out stat buffer so mtime, etc are zero for items from the shared cache
3162 bzero(&statBuf
, sizeof(statBuf
));
3163 dyld3::launch_cache::Image
image(shareCacheResults
.imageData
);
3164 if ( image
.overridableDylib() ) {
3165 existsOnDisk
= ( my_stat(path
, &statBuf
) == 0 );
3168 if ( sSharedCacheLoadInfo
.loadAddress
->header
.dylibsExpectedOnDisk
) {
3169 if ( (image
.fileModTime() == statBuf
.st_mtime
) && (image
.fileINode() == statBuf
.st_ino
) )
3173 if ( !existsOnDisk
)
3182 ImageLoader
* imageLoader
= ImageLoaderMachO::instantiateFromCache((macho_header
*)shareCacheResults
.mhInCache
, shareCacheResults
.pathInCache
, shareCacheResults
.slideInCache
, statBuf
, gLinkContext
);
3183 return checkandAddImage(imageLoader
, context
);
3187 // not in cache or cache not usable
3189 existsOnDisk
= ( my_stat(path
, &statBuf
) == 0 );
3192 if ( existsOnDisk
) {
3193 // in case image was renamed or found via symlinks, check for inode match
3194 ImageLoader
* imageLoader
= findLoadedImage(statBuf
);
3195 if ( imageLoader
!= NULL
)
3197 // do nothing if not already loaded and if RTLD_NOLOAD
3198 if ( context
.dontLoad
)
3201 imageLoader
= loadPhase5open(path
, context
, statBuf
, exceptions
);
3202 if ( imageLoader
!= NULL
)
3206 // just return NULL if file not found, but record any other errors
3207 if ( (statErrNo
!= ENOENT
) && (statErrNo
!= 0) ) {
3208 if ( (statErrNo
== EPERM
) && sandboxBlockedStat(path
) )
3209 exceptions
->push_back(dyld::mkstringf("%s: file system sandbox blocked stat()", path
));
3211 exceptions
->push_back(dyld::mkstringf("%s: stat() failed with errno=%d", path
, statErrNo
));
3216 // look for path match with existing loaded images
3217 static ImageLoader
* loadPhase5check(const char* path
, const char* orgPath
, const LoadContext
& context
)
3219 //dyld::log("%s(%s, %s)\n", __func__ , path, orgPath);
3220 // search path against load-path and install-path of all already loaded images
3221 uint32_t hash
= ImageLoader::hash(path
);
3222 //dyld::log("check() hash=%d, path=%s\n", hash, path);
3223 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
3224 ImageLoader
* anImage
= *it
;
3225 // check hash first to cut down on strcmp calls
3226 //dyld::log(" check() hash=%d, path=%s\n", anImage->getPathHash(), anImage->getPath());
3227 if ( anImage
->getPathHash() == hash
) {
3228 if ( strcmp(path
, anImage
->getPath()) == 0 ) {
3229 // if we are looking for a dylib don't return something else
3230 if ( !context
.mustBeDylib
|| anImage
->isDylib() )
3234 if ( context
.matchByInstallName
|| anImage
->matchInstallPath() ) {
3235 const char* installPath
= anImage
->getInstallPath();
3236 if ( installPath
!= NULL
) {
3237 if ( strcmp(path
, installPath
) == 0 ) {
3238 // if we are looking for a dylib don't return something else
3239 if ( !context
.mustBeDylib
|| anImage
->isDylib() )
3244 // an install name starting with @rpath should match by install name, not just real path
3245 if ( (orgPath
[0] == '@') && (strncmp(orgPath
, "@rpath/", 7) == 0) ) {
3246 const char* installPath
= anImage
->getInstallPath();
3247 if ( installPath
!= NULL
) {
3248 if ( !context
.mustBeDylib
|| anImage
->isDylib() ) {
3249 if ( strcmp(orgPath
, installPath
) == 0 )
3256 //dyld::log("%s(%s) => NULL\n", __func__, path);
3261 // open or check existing
3262 static ImageLoader
* loadPhase5(const char* path
, const char* orgPath
, const LoadContext
& context
, unsigned& cacheIndex
, std::vector
<const char*>* exceptions
)
3264 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
3266 // check for specific dylib overrides
3267 for (std::vector
<DylibOverride
>::iterator it
= sDylibOverrides
.begin(); it
!= sDylibOverrides
.end(); ++it
) {
3268 if ( strcmp(it
->installName
, path
) == 0 ) {
3269 path
= it
->override
;
3274 if ( exceptions
!= NULL
)
3275 return loadPhase5load(path
, orgPath
, context
, cacheIndex
, exceptions
);
3277 return loadPhase5check(path
, orgPath
, context
);
3280 // try with and without image suffix
3281 static ImageLoader
* loadPhase4(const char* path
, const char* orgPath
, const LoadContext
& context
, unsigned& cacheIndex
, std::vector
<const char*>* exceptions
)
3283 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
3284 ImageLoader
* image
= NULL
;
3285 if ( gLinkContext
.imageSuffix
!= NULL
) {
3286 char pathWithSuffix
[strlen(path
)+strlen( gLinkContext
.imageSuffix
)+2];
3287 ImageLoader::addSuffix(path
, gLinkContext
.imageSuffix
, pathWithSuffix
);
3288 image
= loadPhase5(pathWithSuffix
, orgPath
, context
, cacheIndex
, exceptions
);
3290 if ( image
== NULL
)
3291 image
= loadPhase5(path
, orgPath
, context
, cacheIndex
, exceptions
);
3295 static ImageLoader
* loadPhase2(const char* path
, const char* orgPath
, const LoadContext
& context
,
3296 const char* const frameworkPaths
[], const char* const libraryPaths
[],
3297 unsigned& cacheIndex
, std::vector
<const char*>* exceptions
); // forward reference
3300 // expand @ variables
3301 static ImageLoader
* loadPhase3(const char* path
, const char* orgPath
, const LoadContext
& context
, unsigned& cacheIndex
, std::vector
<const char*>* exceptions
)
3303 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
3304 ImageLoader
* image
= NULL
;
3305 if ( strncmp(path
, "@executable_path/", 17) == 0 ) {
3306 #if __MAC_OS_X_VERSION_MIN_REQUIRED
3307 // executable_path cannot be in used in any binary in a setuid process rdar://problem/4589305
3308 if ( gLinkContext
.processIsRestricted
)
3309 throwf("unsafe use of @executable_path in %s with restricted binary", context
.origin
);
3311 // handle @executable_path path prefix
3312 const char* executablePath
= sExecPath
;
3313 char newPath
[strlen(executablePath
) + strlen(path
)];
3314 strcpy(newPath
, executablePath
);
3315 char* addPoint
= strrchr(newPath
,'/');
3316 if ( addPoint
!= NULL
)
3317 strcpy(&addPoint
[1], &path
[17]);
3319 strcpy(newPath
, &path
[17]);
3320 image
= loadPhase4(newPath
, orgPath
, context
, cacheIndex
, exceptions
);
3321 if ( image
!= NULL
)
3324 // perhaps main executable path is a sym link, find realpath and retry
3325 char resolvedPath
[PATH_MAX
];
3326 if ( realpath(sExecPath
, resolvedPath
) != NULL
) {
3327 char newRealPath
[strlen(resolvedPath
) + strlen(path
)];
3328 strcpy(newRealPath
, resolvedPath
);
3329 addPoint
= strrchr(newRealPath
,'/');
3330 if ( addPoint
!= NULL
)
3331 strcpy(&addPoint
[1], &path
[17]);
3333 strcpy(newRealPath
, &path
[17]);
3334 image
= loadPhase4(newRealPath
, orgPath
, context
, cacheIndex
, exceptions
);
3335 if ( image
!= NULL
)
3339 else if ( (strncmp(path
, "@loader_path/", 13) == 0) && (context
.origin
!= NULL
) ) {
3340 #if __MAC_OS_X_VERSION_MIN_REQUIRED
3341 // @loader_path cannot be used from the main executable of a setuid process rdar://problem/4589305
3342 if ( gLinkContext
.processIsRestricted
&& (strcmp(context
.origin
, sExecPath
) == 0) )
3343 throwf("unsafe use of @loader_path in %s with restricted binary", context
.origin
);
3345 // handle @loader_path path prefix
3346 char newPath
[strlen(context
.origin
) + strlen(path
)];
3347 strcpy(newPath
, context
.origin
);
3348 char* addPoint
= strrchr(newPath
,'/');
3349 if ( addPoint
!= NULL
)
3350 strcpy(&addPoint
[1], &path
[13]);
3352 strcpy(newPath
, &path
[13]);
3353 image
= loadPhase4(newPath
, orgPath
, context
, cacheIndex
, exceptions
);
3354 if ( image
!= NULL
)
3357 // perhaps loader path is a sym link, find realpath and retry
3358 char resolvedPath
[PATH_MAX
];
3359 if ( realpath(context
.origin
, resolvedPath
) != NULL
) {
3360 char newRealPath
[strlen(resolvedPath
) + strlen(path
)];
3361 strcpy(newRealPath
, resolvedPath
);
3362 addPoint
= strrchr(newRealPath
,'/');
3363 if ( addPoint
!= NULL
)
3364 strcpy(&addPoint
[1], &path
[13]);
3366 strcpy(newRealPath
, &path
[13]);
3367 image
= loadPhase4(newRealPath
, orgPath
, context
, cacheIndex
, exceptions
);
3368 if ( image
!= NULL
)
3372 else if ( context
.implicitRPath
|| (strncmp(path
, "@rpath/", 7) == 0) ) {
3373 const char* trailingPath
= (strncmp(path
, "@rpath/", 7) == 0) ? &path
[7] : path
;
3374 // substitute @rpath with all -rpath paths up the load chain
3375 for(const ImageLoader::RPathChain
* rp
=context
.rpath
; rp
!= NULL
; rp
=rp
->next
) {
3376 if (rp
->paths
!= NULL
) {
3377 for(std::vector
<const char*>::iterator it
=rp
->paths
->begin(); it
!= rp
->paths
->end(); ++it
) {
3378 const char* anRPath
= *it
;
3379 char newPath
[strlen(anRPath
) + strlen(trailingPath
)+2];
3380 strcpy(newPath
, anRPath
);
3381 if ( newPath
[strlen(newPath
)-1] != '/' )
3382 strcat(newPath
, "/");
3383 strcat(newPath
, trailingPath
);
3384 image
= loadPhase4(newPath
, orgPath
, context
, cacheIndex
, exceptions
);
3385 if ( gLinkContext
.verboseRPaths
&& (exceptions
!= NULL
) ) {
3386 if ( image
!= NULL
)
3387 dyld::log("RPATH successful expansion of %s to: %s\n", orgPath
, newPath
);
3389 dyld::log("RPATH failed to expanding %s to: %s\n", orgPath
, newPath
);
3391 if ( image
!= NULL
)
3397 // substitute @rpath with LD_LIBRARY_PATH
3398 if ( sEnv
.LD_LIBRARY_PATH
!= NULL
) {
3399 image
= loadPhase2(trailingPath
, orgPath
, context
, NULL
, sEnv
.LD_LIBRARY_PATH
, cacheIndex
, exceptions
);
3400 if ( image
!= NULL
)
3404 // if this is the "open" pass, don't try to open @rpath/... as a relative path
3405 if ( (exceptions
!= NULL
) && (trailingPath
!= path
) )
3408 #if __MAC_OS_X_VERSION_MIN_REQUIRED
3409 else if ( gLinkContext
.processIsRestricted
&& (path
[0] != '/' ) ) {
3410 throwf("unsafe use of relative rpath %s in %s with restricted binary", path
, context
.origin
);
3414 return loadPhase4(path
, orgPath
, context
, cacheIndex
, exceptions
);
3417 static ImageLoader
* loadPhase2cache(const char* path
, const char *orgPath
, const LoadContext
& context
, unsigned& cacheIndex
, std::vector
<const char*>* exceptions
) {
3418 ImageLoader
* image
= NULL
;
3419 #if !TARGET_IPHONE_SIMULATOR
3420 if ( exceptions
!= NULL
) {
3421 char resolvedPath
[PATH_MAX
];
3422 realpath(path
, resolvedPath
);
3424 // If realpath() resolves to a path which does not exist on disk, errno is set to ENOENT
3425 if ( (myerr
== ENOENT
) || (myerr
== 0) )
3427 image
= loadPhase4(resolvedPath
, orgPath
, context
, cacheIndex
, exceptions
);
3436 static ImageLoader
* loadPhase2(const char* path
, const char* orgPath
, const LoadContext
& context
,
3437 const char* const frameworkPaths
[], const char* const libraryPaths
[],
3438 unsigned& cacheIndex
, std::vector
<const char*>* exceptions
)
3440 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
3441 ImageLoader
* image
= NULL
;
3442 const char* frameworkPartialPath
= getFrameworkPartialPath(path
);
3443 if ( frameworkPaths
!= NULL
) {
3444 if ( frameworkPartialPath
!= NULL
) {
3445 const size_t frameworkPartialPathLen
= strlen(frameworkPartialPath
);
3446 for(const char* const* fp
= frameworkPaths
; *fp
!= NULL
; ++fp
) {
3447 char npath
[strlen(*fp
)+frameworkPartialPathLen
+8];
3450 strcat(npath
, frameworkPartialPath
);
3451 //dyld::log("dyld: fallback framework path used: %s() -> loadPhase4(\"%s\", ...)\n", __func__, npath);
3452 image
= loadPhase4(npath
, orgPath
, context
, cacheIndex
, exceptions
);
3453 // Look in the cache if appropriate
3455 image
= loadPhase2cache(npath
, orgPath
, context
, cacheIndex
, exceptions
);
3456 if ( image
!= NULL
)
3461 // <rdar://problem/12649639> An executable with the same name as a framework & DYLD_LIBRARY_PATH pointing to it gets loaded twice
3462 // <rdar://problem/14160846> Some apps depend on frameworks being found via library paths
3463 if ( (libraryPaths
!= NULL
) && ((frameworkPartialPath
== NULL
) || sFrameworksFoundAsDylibs
) ) {
3464 const char* libraryLeafName
= getLibraryLeafName(path
);
3465 const size_t libraryLeafNameLen
= strlen(libraryLeafName
);
3466 for(const char* const* lp
= libraryPaths
; *lp
!= NULL
; ++lp
) {
3467 char libpath
[strlen(*lp
)+libraryLeafNameLen
+8];
3468 strcpy(libpath
, *lp
);
3469 strcat(libpath
, "/");
3470 strcat(libpath
, libraryLeafName
);
3471 //dyld::log("dyld: fallback library path used: %s() -> loadPhase4(\"%s\", ...)\n", __func__, libpath);
3472 image
= loadPhase4(libpath
, orgPath
, context
, cacheIndex
, exceptions
);
3473 // Look in the cache if appropriate
3475 image
= loadPhase2cache(libpath
, orgPath
, context
, cacheIndex
, exceptions
);
3476 if ( image
!= NULL
)
3483 // try search overrides and fallbacks
3484 static ImageLoader
* loadPhase1(const char* path
, const char* orgPath
, const LoadContext
& context
, unsigned& cacheIndex
, std::vector
<const char*>* exceptions
)
3486 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
3487 ImageLoader
* image
= NULL
;
3489 // handle LD_LIBRARY_PATH environment variables that force searching
3490 if ( context
.useLdLibraryPath
&& (sEnv
.LD_LIBRARY_PATH
!= NULL
) ) {
3491 image
= loadPhase2(path
, orgPath
, context
, NULL
, sEnv
.LD_LIBRARY_PATH
, cacheIndex
,exceptions
);
3492 if ( image
!= NULL
)
3496 // handle DYLD_ environment variables that force searching
3497 if ( context
.useSearchPaths
&& ((sEnv
.DYLD_FRAMEWORK_PATH
!= NULL
) || (sEnv
.DYLD_LIBRARY_PATH
!= NULL
)) ) {
3498 image
= loadPhase2(path
, orgPath
, context
, sEnv
.DYLD_FRAMEWORK_PATH
, sEnv
.DYLD_LIBRARY_PATH
, cacheIndex
, exceptions
);
3499 if ( image
!= NULL
)
3504 image
= loadPhase3(path
, orgPath
, context
, cacheIndex
, exceptions
);
3505 if ( image
!= NULL
)
3508 // try fallback paths during second time (will open file)
3509 const char* const* fallbackLibraryPaths
= sEnv
.DYLD_FALLBACK_LIBRARY_PATH
;
3510 if ( (fallbackLibraryPaths
!= NULL
) && !context
.useFallbackPaths
)
3511 fallbackLibraryPaths
= NULL
;
3512 if ( !context
.dontLoad
&& (exceptions
!= NULL
) && ((sEnv
.DYLD_FALLBACK_FRAMEWORK_PATH
!= NULL
) || (fallbackLibraryPaths
!= NULL
)) ) {
3513 image
= loadPhase2(path
, orgPath
, context
, sEnv
.DYLD_FALLBACK_FRAMEWORK_PATH
, fallbackLibraryPaths
, cacheIndex
, exceptions
);
3514 if ( image
!= NULL
)
3521 // try root substitutions
3522 static ImageLoader
* loadPhase0(const char* path
, const char* orgPath
, const LoadContext
& context
, unsigned& cacheIndex
, std::vector
<const char*>* exceptions
)
3524 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
3526 #if SUPPORT_ROOT_PATH
3527 // handle DYLD_ROOT_PATH which forces absolute paths to use a new root
3528 if ( (gLinkContext
.rootPaths
!= NULL
) && (path
[0] == '/') ) {
3529 for(const char* const* rootPath
= gLinkContext
.rootPaths
; *rootPath
!= NULL
; ++rootPath
) {
3530 char newPath
[strlen(*rootPath
) + strlen(path
)+2];
3531 strcpy(newPath
, *rootPath
);
3532 strcat(newPath
, path
);
3533 ImageLoader
* image
= loadPhase1(newPath
, orgPath
, context
, cacheIndex
, exceptions
);
3534 if ( image
!= NULL
)
3541 return loadPhase1(path
, orgPath
, context
, cacheIndex
, exceptions
);
3544 static bool cacheablePath(const char* path
) {
3545 if (strncmp(path
, "/usr/lib/", 9) == 0)
3547 if (strncmp(path
, "/System/Library/", 16) == 0)
3553 // Given all the DYLD_ environment variables, the general case for loading libraries
3554 // is that any given path expands into a list of possible locations to load. We
3555 // also must take care to ensure two copies of the "same" library are never loaded.
3557 // The algorithm used here is that there is a separate function for each "phase" of the
3558 // path expansion. Each phase function calls the next phase with each possible expansion
3559 // of that phase. The result is the last phase is called with all possible paths.
3561 // To catch duplicates the algorithm is run twice. The first time, the last phase checks
3562 // the path against all loaded images. The second time, the last phase calls open() on
3563 // the path. Either time, if an image is found, the phases all unwind without checking
3566 ImageLoader
* load(const char* path
, const LoadContext
& context
, unsigned& cacheIndex
)
3568 CRSetCrashLogMessage2(path
);
3569 const char* orgPath
= path
;
3570 cacheIndex
= UINT32_MAX
;
3572 //dyld::log("%s(%s)\n", __func__ , path);
3573 char realPath
[PATH_MAX
];
3574 // when DYLD_IMAGE_SUFFIX is in used, do a realpath(), otherwise a load of "Foo.framework/Foo" will not match
3575 if ( context
.useSearchPaths
&& ( gLinkContext
.imageSuffix
!= NULL
) ) {
3576 if ( realpath(path
, realPath
) != NULL
)
3580 // try all path permutations and check against existing loaded images
3582 ImageLoader
* image
= loadPhase0(path
, orgPath
, context
, cacheIndex
, NULL
);
3583 if ( image
!= NULL
) {
3584 CRSetCrashLogMessage2(NULL
);
3588 // try all path permutations and try open() until first success
3589 std::vector
<const char*> exceptions
;
3590 image
= loadPhase0(path
, orgPath
, context
, cacheIndex
, &exceptions
);
3591 #if !TARGET_IPHONE_SIMULATOR
3592 // <rdar://problem/16704628> support symlinks on disk to a path in dyld shared cache
3594 image
= loadPhase2cache(path
, orgPath
, context
, cacheIndex
, &exceptions
);
3596 CRSetCrashLogMessage2(NULL
);
3597 if ( image
!= NULL
) {
3598 // <rdar://problem/6916014> leak in dyld during dlopen when using DYLD_ variables
3599 for (std::vector
<const char*>::iterator it
= exceptions
.begin(); it
!= exceptions
.end(); ++it
) {
3602 // if loaded image is not from cache, but original path is in cache
3603 // set gSharedCacheOverridden flag to disable some ObjC optimizations
3604 if ( !gSharedCacheOverridden
&& !image
->inSharedCache() && image
->isDylib() && cacheablePath(path
) && inSharedCache(path
) ) {
3605 gSharedCacheOverridden
= true;
3609 else if ( exceptions
.size() == 0 ) {
3610 if ( context
.dontLoad
) {
3614 throw "image not found";
3617 const char* msgStart
= "no suitable image found. Did find:";
3618 const char* delim
= "\n\t";
3619 size_t allsizes
= strlen(msgStart
)+8;
3620 for (size_t i
=0; i
< exceptions
.size(); ++i
)
3621 allsizes
+= (strlen(exceptions
[i
]) + strlen(delim
));
3622 char* fullMsg
= new char[allsizes
];
3623 strcpy(fullMsg
, msgStart
);
3624 for (size_t i
=0; i
< exceptions
.size(); ++i
) {
3625 strcat(fullMsg
, delim
);
3626 strcat(fullMsg
, exceptions
[i
]);
3627 free((void*)exceptions
[i
]);
3629 throw (const char*)fullMsg
;
3637 static void mapSharedCache()
3639 dyld3::SharedCacheOptions opts
;
3640 opts
.cacheDirOverride
= sSharedCacheOverrideDir
;
3641 opts
.forcePrivate
= (gLinkContext
.sharedRegionMode
== ImageLoader::kUsePrivateSharedRegion
);
3642 #if __x86_64__ && !TARGET_IPHONE_SIMULATOR
3643 opts
.useHaswell
= sHaswell
;
3645 opts
.useHaswell
= false;
3647 opts
.verbose
= gLinkContext
.verboseMapping
;
3648 loadDyldCache(opts
, &sSharedCacheLoadInfo
);
3650 // update global state
3651 if ( sSharedCacheLoadInfo
.loadAddress
!= nullptr ) {
3652 dyld::gProcessInfo
->processDetachedFromSharedRegion
= opts
.forcePrivate
;
3653 dyld::gProcessInfo
->sharedCacheSlide
= sSharedCacheLoadInfo
.slide
;
3654 dyld::gProcessInfo
->sharedCacheBaseAddress
= (unsigned long)sSharedCacheLoadInfo
.loadAddress
;
3655 sSharedCacheLoadInfo
.loadAddress
->getUUID(dyld::gProcessInfo
->sharedCacheUUID
);
3656 dyld3::kdebug_trace_dyld_image(DBG_DYLD_UUID_SHARED_CACHE_A
, (const uuid_t
*)&dyld::gProcessInfo
->sharedCacheUUID
[0], {0,0}, {{ 0, 0 }}, (const mach_header
*)sSharedCacheLoadInfo
.loadAddress
);
3659 //#if __IPHONE_OS_VERSION_MIN_REQUIRED && !TARGET_IPHONE_SIMULATOR
3660 // RAM disk booting does not have shared cache yet
3661 // Don't make lack of a shared cache fatal in that case
3662 // if ( sSharedCacheLoadInfo.loadAddress == nullptr ) {
3663 // if ( sSharedCacheLoadInfo.errorMessage != nullptr )
3664 // halt(sSharedCacheLoadInfo.errorMessage);
3666 // halt("error loading dyld shared cache");
3673 // create when NSLinkModule is called for a second time on a bundle
3674 ImageLoader
* cloneImage(ImageLoader
* image
)
3676 // open file (automagically closed when this function exits)
3677 FileOpener
file(image
->getPath());
3679 struct stat stat_buf
;
3680 if ( fstat(file
.getFileDescriptor(), &stat_buf
) == -1)
3683 dyld::LoadContext context
;
3684 context
.useSearchPaths
= false;
3685 context
.useFallbackPaths
= false;
3686 context
.useLdLibraryPath
= false;
3687 context
.implicitRPath
= false;
3688 context
.matchByInstallName
= false;
3689 context
.dontLoad
= false;
3690 context
.mustBeBundle
= true;
3691 context
.mustBeDylib
= false;
3692 context
.canBePIE
= false;
3693 context
.origin
= NULL
;
3694 context
.rpath
= NULL
;
3695 return loadPhase6(file
.getFileDescriptor(), stat_buf
, image
->getPath(), context
);
3699 ImageLoader
* loadFromMemory(const uint8_t* mem
, uint64_t len
, const char* moduleName
)
3701 // if fat wrapper, find usable sub-file
3702 const fat_header
* memStartAsFat
= (fat_header
*)mem
;
3703 uint64_t fileOffset
= 0;
3704 uint64_t fileLength
= len
;
3705 if ( memStartAsFat
->magic
== OSSwapBigToHostInt32(FAT_MAGIC
) ) {
3706 if ( fatFindBest(memStartAsFat
, &fileOffset
, &fileLength
) ) {
3707 mem
= &mem
[fileOffset
];
3711 throw "no matching architecture in universal wrapper";
3716 if ( isCompatibleMachO(mem
, moduleName
) ) {
3717 ImageLoader
* image
= ImageLoaderMachO::instantiateFromMemory(moduleName
, (macho_header
*)mem
, len
, gLinkContext
);
3718 // don't add bundles to global list, they can be loaded but not linked. When linked it will be added to list
3719 if ( ! image
->isBundle() )
3724 // try other file formats here...
3726 // throw error about what was found
3727 switch (*(uint32_t*)mem
) {
3732 throw "mach-o, but wrong architecture";
3734 throwf("unknown file type, first eight bytes: 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X",
3735 mem
[0], mem
[1], mem
[2], mem
[3], mem
[4], mem
[5], mem
[6],mem
[7]);
3740 void registerAddCallback(ImageCallback func
)
3742 // now add to list to get notified when any more images are added
3743 sAddImageCallbacks
.push_back(func
);
3745 // call callback with all existing images
3746 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
3747 ImageLoader
* image
= *it
;
3748 if ( image
->getState() >= dyld_image_state_bound
&& image
->getState() < dyld_image_state_terminated
)
3749 (*func
)(image
->machHeader(), image
->getSlide());
3751 #if SUPPORT_ACCELERATE_TABLES
3752 if ( sAllCacheImagesProxy
!= NULL
) {
3753 dyld_image_info infos
[allImagesCount()+1];
3754 unsigned cacheCount
= sAllCacheImagesProxy
->appendImagesToNotify(dyld_image_state_bound
, true, infos
);
3755 for (unsigned i
=0; i
< cacheCount
; ++i
) {
3756 (*func
)(infos
[i
].imageLoadAddress
, sSharedCacheLoadInfo
.slide
);
3762 void registerRemoveCallback(ImageCallback func
)
3764 // <rdar://problem/15025198> ignore calls to register a notification during a notification
3765 if ( sRemoveImageCallbacksInUse
)
3767 sRemoveImageCallbacks
.push_back(func
);
3770 void clearErrorMessage()
3772 error_string
[0] = '\0';
3775 void setErrorMessage(const char* message
)
3777 // save off error message in global buffer for CrashReporter to find
3778 strlcpy(error_string
, message
, sizeof(error_string
));
3781 const char* getErrorMessage()
3783 return error_string
;
3786 void halt(const char* message
)
3788 dyld::log("dyld: %s\n", message
);
3789 setErrorMessage(message
);
3790 dyld::gProcessInfo
->errorMessage
= error_string
;
3791 if ( !gLinkContext
.startedInitializingMainExecutable
)
3792 dyld::gProcessInfo
->terminationFlags
= 1;
3794 dyld::gProcessInfo
->terminationFlags
= 0;
3796 char payloadBuffer
[EXIT_REASON_PAYLOAD_MAX_LEN
];
3797 dyld_abort_payload
* payload
= (dyld_abort_payload
*)payloadBuffer
;
3798 payload
->version
= 1;
3799 payload
->flags
= gLinkContext
.startedInitializingMainExecutable
? 0 : 1;
3800 payload
->targetDylibPathOffset
= 0;
3801 payload
->clientPathOffset
= 0;
3802 payload
->symbolOffset
= 0;
3803 int payloadSize
= sizeof(dyld_abort_payload
);
3805 if ( dyld::gProcessInfo
->errorTargetDylibPath
!= NULL
) {
3806 payload
->targetDylibPathOffset
= payloadSize
;
3807 payloadSize
+= strlcpy(&payloadBuffer
[payloadSize
], dyld::gProcessInfo
->errorTargetDylibPath
, sizeof(payloadBuffer
)-payloadSize
) + 1;
3809 if ( dyld::gProcessInfo
->errorClientOfDylibPath
!= NULL
) {
3810 payload
->clientPathOffset
= payloadSize
;
3811 payloadSize
+= strlcpy(&payloadBuffer
[payloadSize
], dyld::gProcessInfo
->errorClientOfDylibPath
, sizeof(payloadBuffer
)-payloadSize
) + 1;
3813 if ( dyld::gProcessInfo
->errorSymbol
!= NULL
) {
3814 payload
->symbolOffset
= payloadSize
;
3815 payloadSize
+= strlcpy(&payloadBuffer
[payloadSize
], dyld::gProcessInfo
->errorSymbol
, sizeof(payloadBuffer
)-payloadSize
) + 1;
3817 char truncMessage
[EXIT_REASON_USER_DESC_MAX_LEN
];
3818 strlcpy(truncMessage
, message
, EXIT_REASON_USER_DESC_MAX_LEN
);
3819 abort_with_payload(OS_REASON_DYLD
, dyld::gProcessInfo
->errorKind
? dyld::gProcessInfo
->errorKind
: DYLD_EXIT_REASON_OTHER
, payloadBuffer
, payloadSize
, truncMessage
, 0);
3822 static void setErrorStrings(unsigned errorCode
, const char* errorClientOfDylibPath
,
3823 const char* errorTargetDylibPath
, const char* errorSymbol
)
3825 dyld::gProcessInfo
->errorKind
= errorCode
;
3826 dyld::gProcessInfo
->errorClientOfDylibPath
= errorClientOfDylibPath
;
3827 dyld::gProcessInfo
->errorTargetDylibPath
= errorTargetDylibPath
;
3828 dyld::gProcessInfo
->errorSymbol
= errorSymbol
;
3832 uintptr_t bindLazySymbol(const mach_header
* mh
, uintptr_t* lazyPointer
)
3834 uintptr_t result
= 0;
3835 // acquire read-lock on dyld's data structures
3836 #if 0 // rdar://problem/3811777 turn off locking until deadlock is resolved
3837 if ( gLibSystemHelpers
!= NULL
)
3838 (*gLibSystemHelpers
->lockForReading
)();
3840 // lookup and bind lazy pointer and get target address
3842 ImageLoader
* target
;
3844 // fast stubs pass NULL for mh and image is instead found via the location of stub (aka lazyPointer)
3846 target
= dyld::findImageContainingAddress(lazyPointer
);
3848 target
= dyld::findImageByMachHeader(mh
);
3850 // note, target should always be mach-o, because only mach-o lazy handler wired up to this
3851 target
= dyld::findImageByMachHeader(mh
);
3853 if ( target
== NULL
)
3854 throwf("image not found for lazy pointer at %p", lazyPointer
);
3855 result
= target
->doBindLazySymbol(lazyPointer
, gLinkContext
);
3857 catch (const char* message
) {
3858 dyld::log("dyld: lazy symbol binding failed: %s\n", message
);
3861 // release read-lock on dyld's data structures
3863 if ( gLibSystemHelpers
!= NULL
)
3864 (*gLibSystemHelpers
->unlockForReading
)();
3866 // return target address to glue which jumps to it with real parameters restored
3871 uintptr_t fastBindLazySymbol(ImageLoader
** imageLoaderCache
, uintptr_t lazyBindingInfoOffset
)
3873 uintptr_t result
= 0;
3875 if ( *imageLoaderCache
== NULL
) {
3877 *imageLoaderCache
= dyld::findMappedRange((uintptr_t)imageLoaderCache
);
3878 if ( *imageLoaderCache
== NULL
) {
3879 #if SUPPORT_ACCELERATE_TABLES
3880 if ( sAllCacheImagesProxy
!= NULL
) {
3881 const mach_header
* mh
;
3884 if ( sAllCacheImagesProxy
->addressInCache(imageLoaderCache
, &mh
, &path
, &index
) ) {
3885 result
= sAllCacheImagesProxy
->bindLazy(lazyBindingInfoOffset
, gLinkContext
, mh
, index
);
3886 if ( result
== 0 ) {
3887 halt("dyld: lazy symbol binding failed for image in dyld shared\n");
3893 const char* message
= "fast lazy binding from unknown image";
3894 dyld::log("dyld: %s\n", message
);
3899 // bind lazy pointer and return it
3901 result
= (*imageLoaderCache
)->doBindFastLazySymbol((uint32_t)lazyBindingInfoOffset
, gLinkContext
,
3902 (dyld::gLibSystemHelpers
!= NULL
) ? dyld::gLibSystemHelpers
->acquireGlobalDyldLock
: NULL
,
3903 (dyld::gLibSystemHelpers
!= NULL
) ? dyld::gLibSystemHelpers
->releaseGlobalDyldLock
: NULL
);
3905 catch (const char* message
) {
3906 dyld::log("dyld: lazy symbol binding failed: %s\n", message
);
3910 // return target address to glue which jumps to it with real parameters restored
3916 void registerUndefinedHandler(UndefinedHandler handler
)
3918 sUndefinedHandler
= handler
;
3921 static void undefinedHandler(const char* symboName
)
3923 if ( sUndefinedHandler
!= NULL
) {
3924 (*sUndefinedHandler
)(symboName
);
3928 static bool findExportedSymbol(const char* name
, bool onlyInCoalesced
, const ImageLoader::Symbol
** sym
, const ImageLoader
** image
)
3930 // search all images in order
3931 const ImageLoader
* firstWeakImage
= NULL
;
3932 const ImageLoader::Symbol
* firstWeakSym
= NULL
;
3933 const size_t imageCount
= sAllImages
.size();
3934 for(size_t i
=0; i
< imageCount
; ++i
) {
3935 ImageLoader
* anImage
= sAllImages
[i
];
3936 // the use of inserted libraries alters search order
3937 // so that inserted libraries are found before the main executable
3938 if ( sInsertedDylibCount
> 0 ) {
3939 if ( i
< sInsertedDylibCount
)
3940 anImage
= sAllImages
[i
+1];
3941 else if ( i
== sInsertedDylibCount
)
3942 anImage
= sAllImages
[0];
3944 if ( ! anImage
->hasHiddenExports() && (!onlyInCoalesced
|| anImage
->hasCoalescedExports()) ) {
3945 *sym
= anImage
->findExportedSymbol(name
, false, image
);
3946 if ( *sym
!= NULL
) {
3947 // if weak definition found, record first one found
3948 if ( ((*image
)->getExportedSymbolInfo(*sym
) & ImageLoader::kWeakDefinition
) != 0 ) {
3949 if ( firstWeakImage
== NULL
) {
3950 firstWeakImage
= *image
;
3951 firstWeakSym
= *sym
;
3955 // found non-weak, so immediately return with it
3961 if ( firstWeakSym
!= NULL
) {
3962 // found a weak definition, but no non-weak, so return first weak found
3963 *sym
= firstWeakSym
;
3964 *image
= firstWeakImage
;
3967 #if SUPPORT_ACCELERATE_TABLES
3968 if ( sAllCacheImagesProxy
!= NULL
) {
3969 if ( sAllCacheImagesProxy
->flatFindSymbol(name
, onlyInCoalesced
, sym
, image
) )
3977 bool flatFindExportedSymbol(const char* name
, const ImageLoader::Symbol
** sym
, const ImageLoader
** image
)
3979 return findExportedSymbol(name
, false, sym
, image
);
3982 bool findCoalescedExportedSymbol(const char* name
, const ImageLoader::Symbol
** sym
, const ImageLoader
** image
)
3984 return findExportedSymbol(name
, true, sym
, image
);
3988 bool flatFindExportedSymbolWithHint(const char* name
, const char* librarySubstring
, const ImageLoader::Symbol
** sym
, const ImageLoader
** image
)
3990 // search all images in order
3991 const size_t imageCount
= sAllImages
.size();
3992 for(size_t i
=0; i
< imageCount
; ++i
){
3993 ImageLoader
* anImage
= sAllImages
[i
];
3994 // only look at images whose paths contain the hint string (NULL hint string is wildcard)
3995 if ( ! anImage
->isBundle() && ((librarySubstring
==NULL
) || (strstr(anImage
->getPath(), librarySubstring
) != NULL
)) ) {
3996 *sym
= anImage
->findExportedSymbol(name
, false, image
);
3997 if ( *sym
!= NULL
) {
4006 unsigned int getCoalescedImages(ImageLoader
* images
[], unsigned imageIndex
[])
4008 unsigned int count
= 0;
4009 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
4010 ImageLoader
* image
= *it
;
4011 if ( image
->participatesInCoalescing() ) {
4012 images
[count
] = *it
;
4013 imageIndex
[count
] = 0;
4017 #if SUPPORT_ACCELERATE_TABLES
4018 if ( sAllCacheImagesProxy
!= NULL
) {
4019 sAllCacheImagesProxy
->appendImagesNeedingCoalescing(images
, imageIndex
, count
);
4026 static ImageLoader::MappedRegion
* getMappedRegions(ImageLoader::MappedRegion
* regions
)
4028 ImageLoader::MappedRegion
* end
= regions
;
4029 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
4030 (*it
)->getMappedRegions(end
);
4035 void registerImageStateSingleChangeHandler(dyld_image_states state
, dyld_image_state_change_handler handler
)
4037 // mark the image that the handler is in as never-unload because dyld has a reference into it
4038 ImageLoader
* handlerImage
= findImageContainingAddress((void*)handler
);
4039 if ( handlerImage
!= NULL
)
4040 handlerImage
->setNeverUnload();
4042 // add to list of handlers
4043 std::vector
<dyld_image_state_change_handler
>* handlers
= stateToHandlers(state
, sSingleHandlers
);
4044 if ( handlers
!= NULL
) {
4045 // <rdar://problem/10332417> need updateAllImages() to be last in dyld_image_state_mapped list
4046 // so that if ObjC adds a handler that prevents a load, it happens before the gdb list is updated
4047 if ( state
== dyld_image_state_mapped
)
4048 handlers
->insert(handlers
->begin(), handler
);
4050 handlers
->push_back(handler
);
4052 // call callback with all existing images
4053 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
4054 ImageLoader
* image
= *it
;
4055 dyld_image_info info
;
4056 info
.imageLoadAddress
= image
->machHeader();
4057 info
.imageFilePath
= image
->getRealPath();
4058 info
.imageFileModDate
= image
->lastModified();
4059 // should only call handler if state == image->state
4060 if ( image
->getState() == state
)
4061 (*handler
)(state
, 1, &info
);
4062 // ignore returned string, too late to do anything
4067 void registerImageStateBatchChangeHandler(dyld_image_states state
, dyld_image_state_change_handler handler
)
4069 // mark the image that the handler is in as never-unload because dyld has a reference into it
4070 ImageLoader
* handlerImage
= findImageContainingAddress((void*)handler
);
4071 if ( handlerImage
!= NULL
)
4072 handlerImage
->setNeverUnload();
4074 // add to list of handlers
4075 std::vector
<dyld_image_state_change_handler
>* handlers
= stateToHandlers(state
, sBatchHandlers
);
4076 if ( handlers
!= NULL
) {
4077 // insert at front, so that gdb handler is always last
4078 handlers
->insert(handlers
->begin(), handler
);
4080 // call callback with all existing images
4082 notifyBatchPartial(state
, true, handler
, false, false);
4084 catch (const char* msg
) {
4085 // ignore request to abort during registration
4091 void registerObjCNotifiers(_dyld_objc_notify_mapped mapped
, _dyld_objc_notify_init init
, _dyld_objc_notify_unmapped unmapped
)
4093 // record functions to call
4094 sNotifyObjCMapped
= mapped
;
4095 sNotifyObjCInit
= init
;
4096 sNotifyObjCUnmapped
= unmapped
;
4098 // call 'mapped' function with all images mapped so far
4100 notifyBatchPartial(dyld_image_state_bound
, true, NULL
, false, true);
4102 catch (const char* msg
) {
4103 // ignore request to abort during registration
4106 // <rdar://problem/32209809> call 'init' function on all images already init'ed (below libSystem)
4107 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
4108 ImageLoader
* image
= *it
;
4109 if ( (image
->getState() == dyld_image_state_initialized
) && image
->notifyObjC() ) {
4110 (*sNotifyObjCInit
)(image
->getRealPath(), image
->machHeader());
4115 bool sharedCacheUUID(uuid_t uuid
)
4117 if ( sSharedCacheLoadInfo
.loadAddress
== nullptr )
4120 sSharedCacheLoadInfo
.loadAddress
->getUUID(uuid
);
4124 #if SUPPORT_ACCELERATE_TABLES
4126 bool dlopenFromCache(const char* path
, int mode
, void** handle
)
4128 if ( sAllCacheImagesProxy
== NULL
)
4130 char fallbackPath
[PATH_MAX
];
4131 bool result
= sAllCacheImagesProxy
->dlopenFromCache(gLinkContext
, path
, mode
, handle
);
4132 if ( !result
&& (strchr(path
, '/') == NULL
) ) {
4133 // POSIX says you can call dlopen() with a leaf name (e.g. dlopen("libz.dylb"))
4134 strcpy(fallbackPath
, "/usr/lib/");
4135 strlcat(fallbackPath
, path
, PATH_MAX
);
4136 result
= sAllCacheImagesProxy
->dlopenFromCache(gLinkContext
, fallbackPath
, mode
, handle
);
4138 path
= fallbackPath
;
4141 // leaf name could be a symlink
4142 char resolvedPath
[PATH_MAX
];
4143 realpath(path
, resolvedPath
);
4144 int realpathErrno
= errno
;
4145 // If realpath() resolves to a path which does not exist on disk, errno is set to ENOENT
4146 if ( (realpathErrno
== ENOENT
) || (realpathErrno
== 0) ) {
4147 result
= sAllCacheImagesProxy
->dlopenFromCache(gLinkContext
, resolvedPath
, mode
, handle
);
4154 bool makeCacheHandle(ImageLoader
* image
, unsigned cacheIndex
, int mode
, void** result
)
4156 if ( sAllCacheImagesProxy
== NULL
)
4158 return sAllCacheImagesProxy
->makeCacheHandle(gLinkContext
, cacheIndex
, mode
, result
);
4161 bool isCacheHandle(void* handle
)
4163 if ( sAllCacheImagesProxy
== NULL
)
4165 return sAllCacheImagesProxy
->isCacheHandle(handle
, NULL
, NULL
);
4168 bool isPathInCache(const char* path
)
4170 if ( sAllCacheImagesProxy
== NULL
)
4173 return sAllCacheImagesProxy
->hasDylib(path
, &index
);
4176 const char* getPathFromIndex(unsigned cacheIndex
)
4178 if ( sAllCacheImagesProxy
== NULL
)
4180 return sAllCacheImagesProxy
->getIndexedPath(cacheIndex
);
4183 void* dlsymFromCache(void* handle
, const char* symName
, unsigned index
)
4185 if ( sAllCacheImagesProxy
== NULL
)
4187 return sAllCacheImagesProxy
->dlsymFromCache(gLinkContext
, handle
, symName
, index
);
4190 bool addressInCache(const void* address
, const mach_header
** mh
, const char** path
, unsigned* index
)
4192 if ( sAllCacheImagesProxy
== NULL
)
4195 return sAllCacheImagesProxy
->addressInCache(address
, mh
, path
, index
? index
: &ignore
);
4198 bool findUnwindSections(const void* addr
, dyld_unwind_sections
* info
)
4200 if ( sAllCacheImagesProxy
== NULL
)
4202 return sAllCacheImagesProxy
->findUnwindSections(addr
, info
);
4205 bool dladdrFromCache(const void* address
, Dl_info
* info
)
4207 if ( sAllCacheImagesProxy
== NULL
)
4209 return sAllCacheImagesProxy
->dladdrFromCache(address
, info
);
4213 static ImageLoader
* libraryLocator(const char* libraryName
, bool search
, const char* origin
, const ImageLoader::RPathChain
* rpaths
, unsigned& cacheIndex
)
4215 dyld::LoadContext context
;
4216 context
.useSearchPaths
= search
;
4217 context
.useFallbackPaths
= search
;
4218 context
.useLdLibraryPath
= false;
4219 context
.implicitRPath
= false;
4220 context
.matchByInstallName
= false;
4221 context
.dontLoad
= false;
4222 context
.mustBeBundle
= false;
4223 context
.mustBeDylib
= true;
4224 context
.canBePIE
= false;
4225 context
.origin
= origin
;
4226 context
.rpath
= rpaths
;
4227 return load(libraryName
, context
, cacheIndex
);
4230 static const char* basename(const char* path
)
4232 const char* last
= path
;
4233 for (const char* s
= path
; *s
!= '\0'; s
++) {
4240 static void setContext(const macho_header
* mainExecutableMH
, int argc
, const char* argv
[], const char* envp
[], const char* apple
[])
4242 gLinkContext
.loadLibrary
= &libraryLocator
;
4243 gLinkContext
.terminationRecorder
= &terminationRecorder
;
4244 gLinkContext
.flatExportFinder
= &flatFindExportedSymbol
;
4245 gLinkContext
.coalescedExportFinder
= &findCoalescedExportedSymbol
;
4246 gLinkContext
.getCoalescedImages
= &getCoalescedImages
;
4247 gLinkContext
.undefinedHandler
= &undefinedHandler
;
4248 gLinkContext
.getAllMappedRegions
= &getMappedRegions
;
4249 gLinkContext
.bindingHandler
= NULL
;
4250 gLinkContext
.notifySingle
= ¬ifySingle
;
4251 gLinkContext
.notifyBatch
= ¬ifyBatch
;
4252 gLinkContext
.removeImage
= &removeImage
;
4253 gLinkContext
.registerDOFs
= ®isterDOFs
;
4254 gLinkContext
.clearAllDepths
= &clearAllDepths
;
4255 gLinkContext
.printAllDepths
= &printAllDepths
;
4256 gLinkContext
.imageCount
= &imageCount
;
4257 gLinkContext
.setNewProgramVars
= &setNewProgramVars
;
4258 gLinkContext
.inSharedCache
= &inSharedCache
;
4259 gLinkContext
.setErrorStrings
= &setErrorStrings
;
4260 #if SUPPORT_OLD_CRT_INITIALIZATION
4261 gLinkContext
.setRunInitialzersOldWay
= &setRunInitialzersOldWay
;
4263 gLinkContext
.findImageContainingAddress
= &findImageContainingAddress
;
4264 gLinkContext
.addDynamicReference
= &addDynamicReference
;
4265 #if SUPPORT_ACCELERATE_TABLES
4266 gLinkContext
.notifySingleFromCache
= ¬ifySingleFromCache
;
4267 gLinkContext
.getPreInitNotifyHandler
= &getPreInitNotifyHandler
;
4268 gLinkContext
.getBoundBatchHandler
= &getBoundBatchHandler
;
4270 gLinkContext
.bindingOptions
= ImageLoader::kBindingNone
;
4271 gLinkContext
.argc
= argc
;
4272 gLinkContext
.argv
= argv
;
4273 gLinkContext
.envp
= envp
;
4274 gLinkContext
.apple
= apple
;
4275 gLinkContext
.progname
= (argv
[0] != NULL
) ? basename(argv
[0]) : "";
4276 gLinkContext
.programVars
.mh
= mainExecutableMH
;
4277 gLinkContext
.programVars
.NXArgcPtr
= &gLinkContext
.argc
;
4278 gLinkContext
.programVars
.NXArgvPtr
= &gLinkContext
.argv
;
4279 gLinkContext
.programVars
.environPtr
= &gLinkContext
.envp
;
4280 gLinkContext
.programVars
.__prognamePtr
=&gLinkContext
.progname
;
4281 gLinkContext
.mainExecutable
= NULL
;
4282 gLinkContext
.imageSuffix
= NULL
;
4283 gLinkContext
.dynamicInterposeArray
= NULL
;
4284 gLinkContext
.dynamicInterposeCount
= 0;
4285 gLinkContext
.prebindUsage
= ImageLoader::kUseAllPrebinding
;
4286 #if TARGET_IPHONE_SIMULATOR
4287 gLinkContext
.sharedRegionMode
= ImageLoader::kUsePrivateSharedRegion
;
4289 gLinkContext
.sharedRegionMode
= ImageLoader::kUseSharedRegion
;
4296 // Look for a special segment in the mach header.
4297 // Its presences means that the binary wants to have DYLD ignore
4298 // DYLD_ environment variables.
4300 #if __MAC_OS_X_VERSION_MIN_REQUIRED
4301 static bool hasRestrictedSegment(const macho_header
* mh
)
4303 const uint32_t cmd_count
= mh
->ncmds
;
4304 const struct load_command
* const cmds
= (struct load_command
*)(((char*)mh
)+sizeof(macho_header
));
4305 const struct load_command
* cmd
= cmds
;
4306 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
4308 case LC_SEGMENT_COMMAND
:
4310 const struct macho_segment_command
* seg
= (struct macho_segment_command
*)cmd
;
4312 //dyld::log("seg name: %s\n", seg->segname);
4313 if (strcmp(seg
->segname
, "__RESTRICT") == 0) {
4314 const struct macho_section
* const sectionsStart
= (struct macho_section
*)((char*)seg
+ sizeof(struct macho_segment_command
));
4315 const struct macho_section
* const sectionsEnd
= §ionsStart
[seg
->nsects
];
4316 for (const struct macho_section
* sect
=sectionsStart
; sect
< sectionsEnd
; ++sect
) {
4317 if (strcmp(sect
->sectname
, "__restrict") == 0)
4324 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
4331 #if __IPHONE_OS_VERSION_MIN_REQUIRED && !TARGET_IPHONE_SIMULATOR
4332 static bool isFairPlayEncrypted(const macho_header
* mh
)
4334 const uint32_t cmd_count
= mh
->ncmds
;
4335 const struct load_command
* const cmds
= (struct load_command
*)(((char*)mh
)+sizeof(macho_header
));
4336 const struct load_command
* cmd
= cmds
;
4337 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
4338 if ( cmd
->cmd
== LC_ENCRYPT_COMMAND
) {
4339 const encryption_info_command
* enc
= (encryption_info_command
*)cmd
;
4340 return (enc
->cryptid
!= 0);
4342 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
4349 #if SUPPORT_VERSIONED_PATHS
4351 static bool readFirstPage(const char* dylibPath
, uint8_t firstPage
[4096])
4354 // open file (automagically closed when this function exits)
4355 FileOpener
file(dylibPath
);
4357 if ( file
.getFileDescriptor() == -1 )
4360 if ( pread(file
.getFileDescriptor(), firstPage
, 4096, 0) != 4096 )
4363 // if fat wrapper, find usable sub-file
4364 const fat_header
* fileStartAsFat
= (fat_header
*)firstPage
;
4365 if ( fileStartAsFat
->magic
== OSSwapBigToHostInt32(FAT_MAGIC
) ) {
4366 uint64_t fileOffset
;
4367 uint64_t fileLength
;
4368 if ( fatFindBest(fileStartAsFat
, &fileOffset
, &fileLength
) ) {
4369 if ( pread(file
.getFileDescriptor(), firstPage
, 4096, fileOffset
) != 4096 )
4381 // Peeks at a dylib file and returns its current_version and install_name.
4382 // Returns false on error.
4384 static bool getDylibVersionAndInstallname(const char* dylibPath
, uint32_t* version
, char* installName
)
4386 uint8_t firstPage
[4096];
4387 const macho_header
* mh
= (macho_header
*)firstPage
;
4388 if ( !readFirstPage(dylibPath
, firstPage
) ) {
4389 // If file cannot be read, check to see if path is in shared cache
4390 const macho_header
* mhInCache
;
4391 const char* pathInCache
;
4393 if ( !findInSharedCacheImage(dylibPath
, true, NULL
, &mhInCache
, &pathInCache
, &slideInCache
) )
4398 // check mach-o header
4399 if ( mh
->magic
!= sMainExecutableMachHeader
->magic
)
4401 if ( mh
->cputype
!= sMainExecutableMachHeader
->cputype
)
4404 // scan load commands for LC_ID_DYLIB
4405 const uint32_t cmd_count
= mh
->ncmds
;
4406 const struct load_command
* const cmds
= (struct load_command
*)(((char*)mh
)+sizeof(macho_header
));
4407 const struct load_command
* const cmdsReadEnd
= (struct load_command
*)(((char*)mh
)+4096);
4408 const struct load_command
* cmd
= cmds
;
4409 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
4413 const struct dylib_command
* id
= (struct dylib_command
*)cmd
;
4414 *version
= id
->dylib
.current_version
;
4415 if ( installName
!= NULL
)
4416 strlcpy(installName
, (char *)id
+ id
->dylib
.name
.offset
, PATH_MAX
);
4421 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
4422 if ( cmd
> cmdsReadEnd
)
4428 #endif // SUPPORT_VERSIONED_PATHS
4432 static void printAllImages()
4434 dyld::log("printAllImages()\n");
4435 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
4436 ImageLoader
* image
= *it
;
4437 dyld_image_states imageState
= image
->getState();
4438 dyld::log(" state=%d, dlopen-count=%d, never-unload=%d, in-use=%d, name=%s\n",
4439 imageState
, image
->dlopenCount(), image
->neverUnload(), image
->isMarkedInUse(), image
->getShortName());
4444 void link(ImageLoader
* image
, bool forceLazysBound
, bool neverUnload
, const ImageLoader::RPathChain
& loaderRPaths
, unsigned cacheIndex
)
4446 // add to list of known images. This did not happen at creation time for bundles
4447 if ( image
->isBundle() && !image
->isLinked() )
4450 // we detect root images as those not linked in yet
4451 if ( !image
->isLinked() )
4452 addRootImage(image
);
4456 const char* path
= image
->getPath();
4457 #if SUPPORT_ACCELERATE_TABLES
4458 if ( image
== sAllCacheImagesProxy
)
4459 path
= sAllCacheImagesProxy
->getIndexedPath(cacheIndex
);
4461 image
->link(gLinkContext
, forceLazysBound
, false, neverUnload
, loaderRPaths
, path
);
4463 catch (const char* msg
) {
4464 garbageCollectImages();
4470 void runInitializers(ImageLoader
* image
)
4472 // do bottom up initialization
4473 ImageLoader::InitializerTimingList initializerTimes
[allImagesCount()];
4474 initializerTimes
[0].count
= 0;
4475 image
->runInitializers(gLinkContext
, initializerTimes
[0]);
4478 // This function is called at the end of dlclose() when the reference count goes to zero.
4479 // The dylib being unloaded may have brought in other dependent dylibs when it was loaded.
4480 // Those dependent dylibs need to be unloaded, but only if they are not referenced by
4481 // something else. We use a standard mark and sweep garbage collection.
4483 // The tricky part is that when a dylib is unloaded it may have a termination function that
4484 // can run and itself call dlclose() on yet another dylib. The problem is that this
4485 // sort of gabage collection is not re-entrant. Instead a terminator's call to dlclose()
4486 // which calls garbageCollectImages() will just set a flag to re-do the garbage collection
4487 // when the current pass is done.
4489 // Also note that this is done within the dyld global lock, so it is always single threaded.
4491 void garbageCollectImages()
4493 static bool sDoingGC
= false;
4494 static bool sRedo
= false;
4497 // GC is currently being run, just set a flag to have it run again.
4506 // mark phase: mark all images not-in-use
4507 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
4508 ImageLoader
* image
= *it
;
4509 //dyld::log("gc: neverUnload=%d name=%s\n", image->neverUnload(), image->getShortName());
4510 image
->markNotUsed();
4513 // sweep phase: mark as in-use, images reachable from never-unload or in-use image
4514 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
4515 ImageLoader
* image
= *it
;
4516 if ( (image
->dlopenCount() != 0) || image
->neverUnload() || (image
== sMainExecutable
) ) {
4517 OSSpinLockLock(&sDynamicReferencesLock
);
4518 image
->markedUsedRecursive(sDynamicReferences
);
4519 OSSpinLockUnlock(&sDynamicReferencesLock
);
4523 // collect phase: build array of images not marked in-use
4524 ImageLoader
* deadImages
[sAllImages
.size()];
4525 unsigned deadCount
= 0;
4526 int maxRangeCount
= 0;
4527 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
4528 ImageLoader
* image
= *it
;
4529 if ( ! image
->isMarkedInUse() ) {
4530 deadImages
[deadCount
++] = image
;
4531 if (gLogAPIs
) dyld::log("dlclose(), found unused image %p %s\n", image
, image
->getShortName());
4532 maxRangeCount
+= image
->segmentCount();
4536 // collect phase: run termination routines for images not marked in-use
4537 __cxa_range_t ranges
[maxRangeCount
];
4539 for (unsigned i
=0; i
< deadCount
; ++i
) {
4540 ImageLoader
* image
= deadImages
[i
];
4541 for (unsigned int j
=0; j
< image
->segmentCount(); ++j
) {
4542 if ( !image
->segExecutable(j
) )
4544 if ( rangeCount
< maxRangeCount
) {
4545 ranges
[rangeCount
].addr
= (const void*)image
->segActualLoadAddress(j
);
4546 ranges
[rangeCount
].length
= image
->segSize(j
);
4551 runImageStaticTerminators(image
);
4553 catch (const char* msg
) {
4554 dyld::warn("problem running terminators for image: %s\n", msg
);
4558 // <rdar://problem/14718598> dyld should call __cxa_finalize_ranges()
4559 if ( (rangeCount
> 0) && (gLibSystemHelpers
!= NULL
) && (gLibSystemHelpers
->version
>= 13) )
4560 (*gLibSystemHelpers
->cxa_finalize_ranges
)(ranges
, rangeCount
);
4562 // collect phase: delete all images which are not marked in-use
4565 mightBeMore
= false;
4566 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
4567 ImageLoader
* image
= *it
;
4568 if ( ! image
->isMarkedInUse() ) {
4570 if (gLogAPIs
) dyld::log("dlclose(), deleting %p %s\n", image
, image
->getShortName());
4572 ImageLoader::deleteImage(image
);
4574 break; // interator in invalidated by this removal
4576 catch (const char* msg
) {
4577 dyld::warn("problem deleting image: %s\n", msg
);
4581 } while ( mightBeMore
);
4590 static void preflight_finally(ImageLoader
* image
)
4592 if ( image
->isBundle() ) {
4593 removeImageFromAllImages(image
->machHeader());
4594 ImageLoader::deleteImage(image
);
4596 sBundleBeingLoaded
= NULL
;
4597 dyld::garbageCollectImages();
4601 void preflight(ImageLoader
* image
, const ImageLoader::RPathChain
& loaderRPaths
, unsigned cacheIndex
)
4604 if ( image
->isBundle() )
4605 sBundleBeingLoaded
= image
; // hack
4606 const char* path
= image
->getPath();
4607 #if SUPPORT_ACCELERATE_TABLES
4608 if ( image
== sAllCacheImagesProxy
)
4609 path
= sAllCacheImagesProxy
->getIndexedPath(cacheIndex
);
4611 image
->link(gLinkContext
, false, true, false, loaderRPaths
, path
);
4613 catch (const char* msg
) {
4614 preflight_finally(image
);
4617 preflight_finally(image
);
4620 static void loadInsertedDylib(const char* path
)
4622 ImageLoader
* image
= NULL
;
4623 unsigned cacheIndex
;
4625 LoadContext context
;
4626 context
.useSearchPaths
= false;
4627 context
.useFallbackPaths
= false;
4628 context
.useLdLibraryPath
= false;
4629 context
.implicitRPath
= false;
4630 context
.matchByInstallName
= false;
4631 context
.dontLoad
= false;
4632 context
.mustBeBundle
= false;
4633 context
.mustBeDylib
= true;
4634 context
.canBePIE
= false;
4635 context
.origin
= NULL
; // can't use @loader_path with DYLD_INSERT_LIBRARIES
4636 context
.rpath
= NULL
;
4637 image
= load(path
, context
, cacheIndex
);
4639 catch (const char* msg
) {
4640 #if TARGET_IPHONE_SIMULATOR
4641 dyld::log("dyld: warning: could not load inserted library '%s' because %s\n", path
, msg
);
4643 #if __MAC_OS_X_VERSION_MIN_REQUIRED
4644 if ( gLinkContext
.processUsingLibraryValidation
)
4645 dyld::log("dyld: warning: could not load inserted library '%s' into library validated process because %s\n", path
, msg
);
4648 halt(dyld::mkstringf("could not load inserted library '%s' because %s\n", path
, msg
));
4652 halt(dyld::mkstringf("could not load inserted library '%s'\n", path
));
4660 // gLinkContext.requireCodeSignature
4661 // gLinkContext.processIsRestricted // Mac OS X only
4662 // gLinkContext.processUsingLibraryValidation // Mac OS X only
4664 static void configureProcessRestrictions(const macho_header
* mainExecutableMH
)
4666 #if TARGET_IPHONE_SIMULATOR
4668 gLinkContext
.requireCodeSignature
= true;
4669 #elif __IPHONE_OS_VERSION_MIN_REQUIRED
4671 gLinkContext
.requireCodeSignature
= true;
4673 if ( csops(0, CS_OPS_STATUS
, &flags
, sizeof(flags
)) != -1 ) {
4674 if ( flags
& CS_ENFORCEMENT
) {
4675 if ( flags
& CS_GET_TASK_ALLOW
) {
4676 // Xcode built app for Debug allowed to use DYLD_* variables
4680 // Development kernel can use DYLD_PRINT_* variables on any FairPlay encrypted app
4681 uint32_t secureValue
= 0;
4682 size_t secureValueSize
= sizeof(secureValue
);
4683 if ( (sysctlbyname("kern.secure_kernel", &secureValue
, &secureValueSize
, NULL
, 0) == 0) && (secureValue
== 0) && isFairPlayEncrypted(mainExecutableMH
) ) {
4684 sEnvMode
= envPrintOnly
;
4689 // Development kernel can run unsigned code
4691 gLinkContext
.requireCodeSignature
= false;
4694 if ( issetugid() ) {
4697 #elif __MAC_OS_X_VERSION_MIN_REQUIRED
4699 gLinkContext
.requireCodeSignature
= false;
4700 gLinkContext
.processIsRestricted
= false;
4701 gLinkContext
.processUsingLibraryValidation
= false;
4702 // any processes with setuid or setgid bit set or with __RESTRICT segment is restricted
4703 if ( issetugid() || hasRestrictedSegment(mainExecutableMH
) ) {
4704 gLinkContext
.processIsRestricted
= true;
4706 bool usingSIP
= (csr_check(CSR_ALLOW_TASK_FOR_PID
) != 0);
4708 if ( csops(0, CS_OPS_STATUS
, &flags
, sizeof(flags
)) != -1 ) {
4709 // On OS X CS_RESTRICT means the program was signed with entitlements
4710 if ( ((flags
& CS_RESTRICT
) == CS_RESTRICT
) && usingSIP
) {
4711 gLinkContext
.processIsRestricted
= true;
4713 // Library Validation loosens searching but requires everything to be code signed
4714 if ( flags
& CS_REQUIRE_LV
) {
4715 gLinkContext
.processIsRestricted
= false;
4716 //gLinkContext.requireCodeSignature = true;
4717 gLinkContext
.processUsingLibraryValidation
= true;
4718 sSafeMode
= usingSIP
;
4725 bool processIsRestricted()
4727 #if __MAC_OS_X_VERSION_MIN_REQUIRED
4728 return gLinkContext
.processIsRestricted
;
4735 // <rdar://problem/10583252> Add dyld to uuidArray to enable symbolication of stackshots
4736 static void addDyldImageToUUIDList()
4738 const struct macho_header
* mh
= (macho_header
*)&__dso_handle
;
4739 const uint32_t cmd_count
= mh
->ncmds
;
4740 const struct load_command
* const cmds
= (struct load_command
*)((char*)mh
+ sizeof(macho_header
));
4741 const struct load_command
* cmd
= cmds
;
4742 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
4745 uuid_command
* uc
= (uuid_command
*)cmd
;
4746 dyld_uuid_info info
;
4747 info
.imageLoadAddress
= (mach_header
*)mh
;
4748 memcpy(info
.imageUUID
, uc
->uuid
, 16);
4749 addNonSharedCacheImageUUID(info
);
4753 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
4757 void notifyKernelAboutImage(const struct macho_header
* mh
, const char* fileInfo
)
4759 const char *endptr
= nullptr;
4760 uint64_t fsid_scalar
= hexToUInt64(fileInfo
, &endptr
);
4761 uint64_t fsobj_id_scalar
= 0;
4762 if (endptr
!= nullptr) {
4763 fsobj_id_scalar
= hexToUInt64(endptr
+1, &endptr
);
4765 const uint32_t cmd_count
= mh
->ncmds
;
4766 const struct load_command
* const cmds
= (struct load_command
*)((char*)mh
+ sizeof(macho_header
));
4767 const struct load_command
* cmd
= cmds
;
4768 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
4771 // Add dyld to the kernel image info
4772 uuid_command
* uc
= (uuid_command
*)cmd
;
4773 dyld3::kdebug_trace_dyld_image(DBG_DYLD_UUID_MAP_A
, (const uuid_t
*)&uc
->uuid
[0], *reinterpret_cast<fsobj_id_t
*>(&fsobj_id_scalar
), *reinterpret_cast<fsid_t
*>(&fsid_scalar
), (const mach_header
*)mh
);
4777 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
4781 #if __MAC_OS_X_VERSION_MIN_REQUIRED
4782 typedef int (*open_proc_t
)(const char*, int, int);
4783 typedef int (*fcntl_proc_t
)(int, int, void*);
4784 typedef int (*ioctl_proc_t
)(int, unsigned long, void*);
4785 static void* getProcessInfo() { return dyld::gProcessInfo
; }
4786 static SyscallHelpers sSysCalls
= {
4788 // added in version 1
4797 (fcntl_proc_t
)&fcntl
,
4798 (ioctl_proc_t
)&ioctl
,
4807 &pthread_mutex_lock
,
4808 &pthread_mutex_unlock
,
4810 &mach_port_deallocate
,
4812 &mach_timebase_info
,
4813 &OSAtomicCompareAndSwapPtrBarrier
,
4817 &mach_absolute_time
,
4818 // added in version 2
4820 // added in version 3
4824 // added in version 4
4825 &coresymbolication_load_notifier
,
4826 &coresymbolication_unload_notifier
,
4827 // Added in version 5
4828 &proc_regionfilename
,
4830 &mach_port_insert_right
,
4831 &mach_port_allocate
,
4833 // Added in version 6
4834 &abort_with_payload
,
4835 // Added in version 7
4836 &task_register_dyld_image_infos
,
4837 &task_unregister_dyld_image_infos
,
4838 &task_get_dyld_image_infos
,
4839 &task_register_dyld_shared_cache_image_info
,
4840 &task_register_dyld_set_dyld_state
,
4841 &task_register_dyld_get_process_state
,
4842 // Added in version 8
4849 __attribute__((noinline
))
4850 static const char* useSimulatorDyld(int fd
, const macho_header
* mainExecutableMH
, const char* dyldPath
,
4851 int argc
, const char* argv
[], const char* envp
[], const char* apple
[],
4852 uintptr_t* startGlue
, uintptr_t* mainAddr
)
4857 // <rdar://problem/25311921> simulator does not support restricted processes
4859 if ( csops(0, CS_OPS_STATUS
, &flags
, sizeof(flags
)) == -1 )
4860 return "csops() failed";
4861 if ( (flags
& CS_RESTRICT
) == CS_RESTRICT
)
4862 return "dyld_sim cannot be loaded in a restricted process";
4864 return "dyld_sim cannot be loaded in a setuid process";
4865 if ( hasRestrictedSegment(mainExecutableMH
) )
4866 return "dyld_sim cannot be loaded in a restricted process";
4868 // get file size of dyld_sim
4870 if ( fstat(fd
, &sb
) == -1 )
4871 return "stat(dyld_sim) failed";
4873 // read first page of dyld_sim file
4874 uint8_t firstPage
[4096];
4875 if ( pread(fd
, firstPage
, 4096, 0) != 4096 )
4876 return "pread(dyld_sim) failed";
4878 // if fat file, pick matching slice
4879 uint64_t fileOffset
= 0;
4880 uint64_t fileLength
= sb
.st_size
;
4881 const fat_header
* fileStartAsFat
= (fat_header
*)firstPage
;
4882 if ( fileStartAsFat
->magic
== OSSwapBigToHostInt32(FAT_MAGIC
) ) {
4883 if ( !fatFindBest(fileStartAsFat
, &fileOffset
, &fileLength
) )
4884 return "no matching arch in dyld_sim";
4885 // re-read buffer from start of mach-o slice in fat file
4886 if ( pread(fd
, firstPage
, 4096, fileOffset
) != 4096 )
4887 return "pread(dyld_sim) failed";
4889 else if ( !isCompatibleMachO(firstPage
, dyldPath
) ) {
4890 return "dyld_sim is not compatible with the loaded process, likely due to architecture mismatch";
4893 // calculate total size of dyld segments
4894 const macho_header
* mh
= (const macho_header
*)firstPage
;
4895 struct macho_segment_command
* lastSeg
= NULL
;
4896 struct macho_segment_command
* firstSeg
= NULL
;
4897 uintptr_t mappingSize
= 0;
4898 uintptr_t preferredLoadAddress
= 0;
4899 const uint32_t cmd_count
= mh
->ncmds
;
4900 if ( mh
->sizeofcmds
> 4096 )
4901 return "dyld_sim load commands to large";
4902 if ( (sizeof(macho_header
) + mh
->sizeofcmds
) > 4096 )
4903 return "dyld_sim load commands to large";
4904 const struct load_command
* const cmds
= (struct load_command
*)(((char*)mh
)+sizeof(macho_header
));
4905 const struct load_command
* const endCmds
= (struct load_command
*)(((char*)mh
) + sizeof(macho_header
) + mh
->sizeofcmds
);
4906 const struct load_command
* cmd
= cmds
;
4907 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
4908 uint32_t cmdLength
= cmd
->cmdsize
;
4909 if ( cmdLength
< 8 )
4910 return "dyld_sim load command too small";
4911 const struct load_command
* const nextCmd
= (const struct load_command
*)(((char*)cmd
)+cmdLength
);
4912 if ( (nextCmd
> endCmds
) || (nextCmd
< cmd
) )
4913 return "dyld_sim load command too large";
4915 case LC_SEGMENT_COMMAND
:
4917 struct macho_segment_command
* seg
= (struct macho_segment_command
*)cmd
;
4918 if ( seg
->vmaddr
+ seg
->vmsize
< seg
->vmaddr
)
4919 return "dyld_sim seg wraps address space";
4920 if ( seg
->vmsize
< seg
->filesize
)
4921 return "dyld_sim seg vmsize too small";
4922 if ( (seg
->fileoff
+ seg
->filesize
) < seg
->fileoff
)
4923 return "dyld_sim seg size wraps address space";
4924 if ( lastSeg
== NULL
) {
4925 // first segment must be __TEXT and start at beginning of file/slice
4927 if ( strcmp(seg
->segname
, "__TEXT") != 0 )
4928 return "dyld_sim first segment not __TEXT";
4929 if ( seg
->fileoff
!= 0 )
4930 return "dyld_sim first segment not at file offset zero";
4931 if ( seg
->filesize
< (sizeof(macho_header
) + mh
->sizeofcmds
) )
4932 return "dyld_sim first segment smaller than load commands";
4933 preferredLoadAddress
= seg
->vmaddr
;
4936 // other sements must be continguous with previous segment and not executable
4937 if ( lastSeg
->fileoff
+ lastSeg
->filesize
!= seg
->fileoff
)
4938 return "dyld_sim segments not contiguous";
4939 if ( lastSeg
->vmaddr
+ lastSeg
->vmsize
!= seg
->vmaddr
)
4940 return "dyld_sim segments not address contiguous";
4941 if ( (seg
->initprot
& VM_PROT_EXECUTE
) != 0 )
4942 return "dyld_sim non-first segment is executable";
4944 mappingSize
+= seg
->vmsize
;
4948 case LC_SEGMENT_COMMAND_WRONG
:
4949 return "dyld_sim wrong load segment load command";
4953 // last segment must be named __LINKEDIT and not writable
4954 if ( strcmp(lastSeg
->segname
, "__LINKEDIT") != 0 )
4955 return "dyld_sim last segment not __LINKEDIT";
4956 if ( lastSeg
->initprot
& VM_PROT_WRITE
)
4957 return "dyld_sim __LINKEDIT segment writable";
4959 // reserve space, then mmap each segment
4960 vm_address_t loadAddress
= 0;
4961 if ( ::vm_allocate(mach_task_self(), &loadAddress
, mappingSize
, VM_FLAGS_ANYWHERE
) != 0 )
4962 return "dyld_sim cannot allocate space";
4964 struct linkedit_data_command
* codeSigCmd
= NULL
;
4965 struct source_version_command
* dyldVersionCmd
= NULL
;
4966 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
4968 case LC_SEGMENT_COMMAND
:
4970 struct macho_segment_command
* seg
= (struct macho_segment_command
*)cmd
;
4971 uintptr_t requestedLoadAddress
= seg
->vmaddr
- preferredLoadAddress
+ loadAddress
;
4972 void* segAddress
= ::mmap((void*)requestedLoadAddress
, seg
->filesize
, seg
->initprot
, MAP_FIXED
| MAP_PRIVATE
, fd
, fileOffset
+ seg
->fileoff
);
4973 //dyld::log("dyld_sim %s mapped at %p\n", seg->segname, segAddress);
4974 if ( segAddress
== (void*)(-1) )
4975 return "dyld_sim mmap() of segment failed";
4976 if ( ((uintptr_t)segAddress
< loadAddress
) || ((uintptr_t)segAddress
+seg
->filesize
> loadAddress
+mappingSize
) )
4977 return "dyld_sim mmap() to wrong location";
4980 case LC_CODE_SIGNATURE
:
4981 codeSigCmd
= (struct linkedit_data_command
*)cmd
;
4983 case LC_SOURCE_VERSION
:
4984 dyldVersionCmd
= (struct source_version_command
*)cmd
;
4987 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
4990 // must have code signature which is contained within LINKEDIT segment
4991 if ( codeSigCmd
== NULL
)
4992 return "dyld_sim not code signed";
4993 if ( codeSigCmd
->dataoff
< lastSeg
->fileoff
)
4994 return "dyld_sim code signature not in __LINKEDIT";
4995 if ( (codeSigCmd
->dataoff
+ codeSigCmd
->datasize
) < codeSigCmd
->dataoff
)
4996 return "dyld_sim code signature size wraps";
4997 if ( (codeSigCmd
->dataoff
+ codeSigCmd
->datasize
) > (lastSeg
->fileoff
+ lastSeg
->filesize
) )
4998 return "dyld_sim code signature extends beyond __LINKEDIT";
5000 fsignatures_t siginfo
;
5001 siginfo
.fs_file_start
=fileOffset
; // start of mach-o slice in fat file
5002 siginfo
.fs_blob_start
=(void*)(long)(codeSigCmd
->dataoff
); // start of code-signature in mach-o file
5003 siginfo
.fs_blob_size
=codeSigCmd
->datasize
; // size of code-signature
5004 int result
= fcntl(fd
, F_ADDFILESIGS_FOR_DYLD_SIM
, &siginfo
);
5005 if ( result
== -1 ) {
5006 return mkstringf("dyld_sim fcntl(F_ADDFILESIGS_FOR_DYLD_SIM) failed with errno=%d", errno
);
5009 // file range covered by code signature must extend up to code signature itself
5010 if ( siginfo
.fs_file_start
< codeSigCmd
->dataoff
)
5011 return mkstringf("dyld_sim code signature does not cover all of dyld_sim. Signature covers up to 0x%08lX. Signature starts at 0x%08X", (unsigned long)siginfo
.fs_file_start
, codeSigCmd
->dataoff
);
5013 // walk newly mapped dyld_sim __TEXT load commands to find entry point
5014 uintptr_t entry
= 0;
5015 cmd
= (struct load_command
*)(((char*)loadAddress
)+sizeof(macho_header
));
5016 const uint32_t count
= ((macho_header
*)(loadAddress
))->ncmds
;
5017 for (uint32_t i
= 0; i
< count
; ++i
) {
5018 if (cmd
->cmd
== LC_UNIXTHREAD
) {
5020 const i386_thread_state_t
* registers
= (i386_thread_state_t
*)(((char*)cmd
) + 16);
5021 // entry point must be in first segment
5022 if ( registers
->__eip
< firstSeg
->vmaddr
)
5023 return "dyld_sim entry point not in __TEXT segment";
5024 if ( registers
->__eip
> (firstSeg
->vmaddr
+ firstSeg
->vmsize
) )
5025 return "dyld_sim entry point not in __TEXT segment";
5026 entry
= (registers
->__eip
+ loadAddress
- preferredLoadAddress
);
5028 const x86_thread_state64_t
* registers
= (x86_thread_state64_t
*)(((char*)cmd
) + 16);
5029 // entry point must be in first segment
5030 if ( registers
->__rip
< firstSeg
->vmaddr
)
5031 return "dyld_sim entry point not in __TEXT segment";
5032 if ( registers
->__rip
> (firstSeg
->vmaddr
+ firstSeg
->vmsize
) )
5033 return "dyld_sim entry point not in __TEXT segment";
5034 entry
= (registers
->__rip
+ loadAddress
- preferredLoadAddress
);
5037 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
5040 // notify debugger that dyld_sim is loaded
5041 dyld_image_info info
;
5042 info
.imageLoadAddress
= (mach_header
*)loadAddress
;
5043 info
.imageFilePath
= strdup(dyldPath
);
5044 info
.imageFileModDate
= sb
.st_mtime
;
5045 addImagesToAllImages(1, &info
);
5046 dyld::gProcessInfo
->notification(dyld_image_adding
, 1, &info
);
5048 const char** appleParams
= apple
;
5049 // jump into new simulator dyld
5050 typedef uintptr_t (*sim_entry_proc_t
)(int argc
, const char* argv
[], const char* envp
[], const char* apple
[],
5051 const macho_header
* mainExecutableMH
, const macho_header
* dyldMH
, uintptr_t dyldSlide
,
5052 const dyld::SyscallHelpers
* vtable
, uintptr_t* startGlue
);
5053 sim_entry_proc_t newDyld
= (sim_entry_proc_t
)entry
;
5054 *mainAddr
= (*newDyld
)(argc
, argv
, envp
, appleParams
, mainExecutableMH
, (macho_header
*)loadAddress
,
5055 loadAddress
- preferredLoadAddress
,
5056 &sSysCalls
, startGlue
);
5062 // If the DYLD_SKIP_MAIN environment is set to 1, dyld will return the
5063 // address of this function instead of main() in the target program which
5064 // __dyld_start jumps to. Useful for qualifying dyld itself.
5075 static bool envVarMatches(dyld3::launch_cache::Closure mainClosure
, const char* envp
[], const char* varName
)
5077 __block
const char* valueFromClosure
= nullptr;
5078 mainClosure
.forEachEnvVar(^(const char* keyEqualValue
, bool& stop
) {
5079 size_t keyLen
= strlen(varName
);
5080 if ( (strncmp(varName
, keyEqualValue
, keyLen
) == 0) && (keyEqualValue
[keyLen
] == '=') ) {
5081 valueFromClosure
= &keyEqualValue
[keyLen
+1];
5086 const char* valueFromEnv
= _simple_getenv(envp
, varName
);
5088 bool inClosure
= (valueFromClosure
!= nullptr);
5089 bool inEnv
= (valueFromEnv
!= nullptr);
5090 if ( inClosure
!= inEnv
)
5092 if ( !inClosure
&& !inEnv
)
5094 return ( strcmp(valueFromClosure
, valueFromEnv
) == 0 );
5097 static const char* const sEnvVarsToCheck
[] = {
5098 "DYLD_LIBRARY_PATH",
5099 "DYLD_FRAMEWORK_PATH",
5100 "DYLD_FALLBACK_LIBRARY_PATH",
5101 "DYLD_FALLBACK_FRAMEWORK_PATH",
5102 "DYLD_INSERT_LIBRARIES",
5103 "DYLD_IMAGE_SUFFIX",
5104 "DYLD_VERSIONED_FRAMEWORK_PATH",
5105 "DYLD_VERSIONED_LIBRARY_PATH",
5109 static bool envVarsMatch(dyld3::launch_cache::Closure mainClosure
, const char* envp
[])
5111 for (const char* envVar
: sEnvVarsToCheck
) {
5112 if ( !envVarMatches(mainClosure
, envp
, envVar
) ) {
5113 if ( gLinkContext
.verboseWarnings
)
5114 dyld::log("dyld: closure %p not used because %s changed\n", mainClosure
.binaryData(), envVar
);
5122 static bool closureValid(const dyld3::launch_cache::BinaryClosureData
* mainClosureData
, const mach_header
* mainExecutableMH
, const uint8_t* mainExecutableCDHash
, bool closureInCache
, const char* envp
[])
5124 const dyld3::launch_cache::Closure
mainClosure(mainClosureData
);
5125 const dyld3::launch_cache::ImageGroup mainGroup
= mainClosure
.group();
5127 // verify current dyld cache is same as expected
5128 if ( sSharedCacheLoadInfo
.loadAddress
== nullptr ) {
5129 if ( gLinkContext
.verboseWarnings
)
5130 dyld::log("dyld: closure %p dyld cache not loaded\n", mainClosureData
);
5133 if ( !closureInCache
) {
5134 // closures in cache don't have cache's UUID
5136 sSharedCacheLoadInfo
.loadAddress
->getUUID(cacheUUID
);
5137 if ( memcmp(mainClosure
.dyldCacheUUID(), cacheUUID
, sizeof(uuid_t
)) != 0 ) {
5138 if ( gLinkContext
.verboseWarnings
)
5139 dyld::log("dyld: closure %p not used because built against different dyld cache\n", mainClosureData
);
5143 #if __MAC_OS_X_VERSION_MIN_REQUIRED
5145 // If the in-memory cache doesn't have the same UUID xattr as the on-disk cache then we must
5146 // have built a new cache but not rebooted. In this case, don't use dyld3.
5147 const char* sharedCachePath
= getStandardSharedCacheFilePath();
5148 uuid_t inMemoryUUID
;
5150 sharedCacheUUID(inMemoryUUID
);
5151 if (getxattr(sharedCachePath
, "cacheUUID", (void*)&onDiskUUID
, sizeof(uuid_t
), 0, 0) != sizeof(uuid_t
)) {
5152 if ( gLinkContext
.verboseWarnings
)
5153 dyld::log("dyld: closure %p on disk cache doesn't have a UUID xattr\n", mainClosureData
);
5156 if (memcmp(&inMemoryUUID
, &onDiskUUID
, sizeof(uuid_t
)) != 0) {
5157 if ( gLinkContext
.verboseWarnings
)
5158 dyld::log("dyld: closure %p not used because current cache on disk and in memory cache have UUID mismatches\n", mainClosureData
);
5164 // verify main executable file has not changed since closure was built
5165 const dyld3::launch_cache::Image mainImage
= mainGroup
.image(mainClosure
.mainExecutableImageIndex());
5166 if ( mainImage
.validateUsingModTimeAndInode() ) {
5167 struct stat statBuf
;
5168 if ( ::stat(mainImage
.path(), &statBuf
) != 0 ) {
5169 if ( gLinkContext
.verboseWarnings
)
5170 dyld::log("dyld: closure %p not used because stat() failed on main executable\n", mainClosureData
);
5173 else if ( (statBuf
.st_mtime
!= mainImage
.fileModTime()) || (statBuf
.st_ino
!= mainImage
.fileINode()) ) {
5174 if ( gLinkContext
.verboseWarnings
)
5175 dyld::log("dyld: closure %p not used because mtime/inode changed since closure was built\n", mainClosureData
);
5180 // verify cdHash of main executable is same as recorded in closure
5181 if ( mainImage
.validateUsingCdHash() ) {
5182 if ( mainExecutableCDHash
== nullptr ) {
5183 if ( gLinkContext
.verboseWarnings
)
5184 dyld::log("dyld: closure %p not used because main executable is not code signed but was expected to be\n", mainClosureData
);
5187 if ( memcmp(mainExecutableCDHash
, mainClosure
.cdHash(), 20) != 0 ) {
5188 if ( gLinkContext
.verboseWarnings
)
5189 dyld::log("dyld: closure %p not used because main executable cd-hash changed since closure was built\n", mainClosureData
);
5194 // verify UUID of main executable is same as recorded in closure
5195 const uuid_t
* closureMainUUID
= mainImage
.uuid();
5196 dyld3::MachOParser
parser(mainExecutableMH
);
5198 parser
.getUuid(actualUUID
);
5199 if ( memcmp(actualUUID
, closureMainUUID
, sizeof(uuid_t
)) != 0 ) {
5200 if ( gLinkContext
.verboseWarnings
)
5201 dyld::log("dyld: closure %p not used because UUID of executable changed since closure was built\n", mainClosureData
);
5205 // verify DYLD_* env vars are same as when closure was built
5206 if ( !envVarsMatch(mainClosure
, envp
) ) {
5210 // verify files that are supposed to be missing actually are missing
5211 __block
bool foundFileThatInvalidatesClosure
= false;
5212 mainClosure
.forEachMustBeMissingFile(^(const char* path
, bool& stop
) {
5213 struct stat statBuf
;
5214 if ( ::stat(path
, &statBuf
) == 0 ) {
5216 foundFileThatInvalidatesClosure
= true;
5217 if ( gLinkContext
.verboseWarnings
)
5218 dyld::log("dyld: closure %p not used because found unexpected file '%s'\n", mainClosureData
, path
);
5222 #if __MAC_OS_X_VERSION_MIN_REQUIRED
5223 // verify no key frameworks have been overridden since cache was built
5224 if ( dyld3::loader::internalInstall() ) {
5225 dyld3::loader::forEachLineInFile("/AppleInternal/Library/Preferences/dyld-potential-framework-overrides", ^(const char* path
, bool& stop
) {
5226 dyld3::SharedCacheFindDylibResults shareCacheResults
;
5227 if ( dyld3::findInSharedCacheImage(sSharedCacheLoadInfo
, path
, &shareCacheResults
) ) {
5228 dyld3::launch_cache::Image
image(shareCacheResults
.imageData
);
5229 struct stat statBuf
;
5230 if ( ::stat(path
, &statBuf
) == 0 ) {
5231 if ( (image
.fileModTime() != statBuf
.st_mtime
) || (image
.fileINode() != statBuf
.st_ino
)) {
5232 if ( gLinkContext
.verboseWarnings
)
5233 dyld::log("dyld: closure %p not used because framework has changed: '%s'\n", mainClosureData
, path
);
5234 foundFileThatInvalidatesClosure
= true;
5243 return !foundFileThatInvalidatesClosure
;
5246 static bool nolog(const char* format
, ...)
5251 static bool dolog(const char* format
, ...)
5254 va_start(list
, format
);
5260 static bool launchWithClosure(const dyld3::launch_cache::BinaryClosureData
* mainClosureData
,
5261 const DyldSharedCache
* dyldCache
,
5262 const mach_header
* mainExecutableMH
, uintptr_t mainExecutableSlide
,
5263 int argc
, const char* argv
[], const char* envp
[], const char* apple
[],
5264 uintptr_t* entry
, uintptr_t* startGlue
)
5266 dyld3::launch_cache::Closure
mainClosure(mainClosureData
);
5267 const dyld3::launch_cache::ImageGroup mainGroup
= mainClosure
.group();
5268 const uint32_t mainExecutableIndex
= mainClosure
.mainExecutableImageIndex();
5269 const dyld3::launch_cache::Image mainImage
= mainGroup
.image(mainExecutableIndex
);
5270 const uint32_t loadedImageCount
= mainClosure
.initialImageCount();
5272 // construct array of groups
5273 dyld3::DyldCacheParser
cacheParser(dyldCache
, false);
5274 STACK_ALLOC_DYNARRAY(const dyld3::launch_cache::binary_format::ImageGroup
*, 3, theGroups
);
5275 theGroups
[0] = cacheParser
.cachedDylibsGroup();
5276 theGroups
[1] = cacheParser
.otherDylibsGroup();
5277 theGroups
[2] = mainClosure
.group().binaryData();
5279 // construct array of all Image*, starting with any inserted dylibs, then main executable
5280 const dyld3::launch_cache::BinaryImageData
* images
[loadedImageCount
];
5281 dyld3::launch_cache::SlowLoadSet
imageSet(&images
[0], &images
[loadedImageCount
]);
5282 for (uint32_t i
=0; i
<= mainExecutableIndex
; ++i
) {
5283 imageSet
.add(mainGroup
.image(i
).binaryData());
5285 // add all dependents of main executable
5286 if ( !mainImage
.recurseAllDependentImages(theGroups
, imageSet
, nullptr) ) {
5287 dyld::log("initial image list overflow, expected only %d\n", loadedImageCount
);
5290 // add dependents of any inserted dylibs
5291 for (uint32_t i
=0; i
< mainExecutableIndex
; ++i
) {
5292 if ( !mainGroup
.image(i
).recurseAllDependentImages(theGroups
, imageSet
, nullptr) ) {
5293 dyld::log("initial image list overflow in inserted libraries, expected only %d\n", loadedImageCount
);
5297 const uint32_t actualImageCount
= (uint32_t)imageSet
.count();
5298 // construct array of allImages
5299 STACK_ALLOC_DYNARRAY(dyld3::loader::ImageInfo
, actualImageCount
, allImages
);
5300 for (int i
=0; i
< actualImageCount
; ++i
) {
5301 dyld3::launch_cache::Image
img(images
[i
]);
5302 dyld3::launch_cache::ImageGroup grp
= img
.group();
5303 allImages
[i
].imageData
= img
.binaryData();
5304 allImages
[i
].loadAddress
= nullptr;
5305 allImages
[i
].groupNum
= grp
.groupNum();
5306 allImages
[i
].indexInGroup
= grp
.indexInGroup(img
.binaryData());
5307 allImages
[i
].previouslyFixedUp
= false;
5308 allImages
[i
].justMapped
= false;
5309 allImages
[i
].justUsedFromDyldCache
= false;
5310 allImages
[i
].neverUnload
= false;
5312 // prefill address of main executable to mark it is already loaded
5313 allImages
[mainExecutableIndex
].loadAddress
= mainExecutableMH
;
5315 // map new images and apply all fixups
5317 mapAndFixupImages(diag
, allImages
, (const uint8_t*)dyldCache
, (gLinkContext
.verboseLoading
? &dolog
: &nolog
),
5318 (gLinkContext
.verboseMapping
? &dolog
: &nolog
),
5319 (gLinkContext
.verboseBind
? &dolog
: &nolog
),
5320 (gLinkContext
.verboseDOF
? &dolog
: &nolog
));
5321 if ( diag
.hasError() ) {
5322 if ( gLinkContext
.verboseWarnings
)
5323 dyld::log("dyld: %s\n", diag
.errorMessage());
5327 //dyld::log("loaded image list:\n");
5328 //for (int i=0; i < allImages.count(); ++i) {
5329 // dyld3::launch_cache::Image img(allImages[i].imageData);
5330 // dyld::log("binImage[%d]=%p, mh=%p, path=%s\n", i, allImages[i].imageData, allImages[i].loadAddress, img.path());
5333 // find special images
5334 const dyld3::launch_cache::BinaryImageData
* libSystemImage
= mainClosure
.libSystem(theGroups
);
5335 const dyld3::launch_cache::BinaryImageData
* libDyldImage
= mainClosure
.libDyld(theGroups
);
5336 const mach_header
* libdyldMH
= nullptr;
5337 const mach_header
* libSystemMH
= nullptr;
5338 for (int i
=0; i
< allImages
.count(); ++i
) {
5339 if ( allImages
[i
].imageData
== libSystemImage
)
5340 libSystemMH
= allImages
[i
].loadAddress
;
5341 else if ( allImages
[i
].imageData
== libDyldImage
)
5342 libdyldMH
= allImages
[i
].loadAddress
;
5345 // send info on all images to libdyld.dylb
5346 const dyld3::LibDyldEntryVector
* libDyldEntry
= (dyld3::LibDyldEntryVector
*)((uint8_t*)libdyldMH
+ mainClosure
.libdyldVectorOffset());
5347 libDyldEntry
->setVars(mainExecutableMH
, argc
, argv
, envp
, apple
);
5348 libDyldEntry
->setHaltFunction(&halt
);
5349 if ( libDyldEntry
->vectorVersion
> 2 )
5350 libDyldEntry
->setChildForkFunction(&_dyld_fork_child
);
5351 #if !TARGET_IPHONE_SIMULATOR
5352 if ( libDyldEntry
->vectorVersion
> 3 )
5353 libDyldEntry
->setLogFunction(&dyld::vlog
);
5355 libDyldEntry
->setOldAllImageInfo(gProcessInfo
);
5356 libDyldEntry
->setInitialImageList(mainClosureData
, dyldCache
, sSharedCacheLoadInfo
.path
, allImages
, libSystemMH
, libSystemImage
);
5358 CRSetCrashLogMessage("dyld3: launch, running initializers");
5359 libDyldEntry
->runInitialzersBottomUp((mach_header
*)mainExecutableMH
);
5360 //dyld::log("returned from runInitialzersBottomUp()\n");
5362 dyld3::kdebug_trace_dyld_signpost(DBG_DYLD_SIGNPOST_START_MAIN
, 0, 0);
5363 if ( mainClosure
.mainExecutableUsesCRT() ) {
5364 // old style app linked with crt1.o
5365 // entry is "start" function in program
5367 *entry
= (uintptr_t)mainExecutableMH
+ mainClosure
.mainExecutableEntryOffset();
5370 // modern app with LC_MAIN
5371 // set startGlue to "start" function in libdyld.dylib
5372 // set entry to "main" function in program
5373 *startGlue
= (uintptr_t)(libDyldEntry
->startFunc
);
5374 *entry
=(uintptr_t)mainExecutableMH
+ mainClosure
.mainExecutableEntryOffset();
5376 CRSetCrashLogMessage(NULL
);
5380 static void putHexNibble(uint8_t value
, char*& p
)
5385 *p
++ = 'A' + value
- 10;
5388 static void putHexByte(uint8_t value
, char*& p
)
5391 putHexNibble(value
>> 4, p
);
5392 putHexNibble(value
& 0x0F, p
);
5395 static void makeHexLong(unsigned long value
, char* p
)
5400 putHexByte(value
>> 56, p
);
5401 putHexByte(value
>> 48, p
);
5402 putHexByte(value
>> 40, p
);
5403 putHexByte(value
>> 32, p
);
5405 putHexByte(value
>> 24, p
);
5406 putHexByte(value
>> 16, p
);
5407 putHexByte(value
>> 8, p
);
5408 putHexByte(value
, p
);
5412 static void makeUUID(uint8_t uuid
[16], char* p
)
5414 putHexByte(uuid
[0], p
);
5415 putHexByte(uuid
[1], p
);
5416 putHexByte(uuid
[2], p
);
5417 putHexByte(uuid
[3], p
);
5419 putHexByte(uuid
[4], p
);
5420 putHexByte(uuid
[5], p
);
5422 putHexByte(uuid
[6], p
);
5423 putHexByte(uuid
[7], p
);
5425 putHexByte(uuid
[8], p
);
5426 putHexByte(uuid
[9], p
);
5428 putHexByte(uuid
[10], p
);
5429 putHexByte(uuid
[11], p
);
5430 putHexByte(uuid
[12], p
);
5431 putHexByte(uuid
[13], p
);
5432 putHexByte(uuid
[14], p
);
5433 putHexByte(uuid
[15], p
);
5437 #if !TARGET_IPHONE_SIMULATOR
5438 static const dyld3::launch_cache::BinaryClosureData
* callClosureDaemon(const char* mainExecPath
, const char* envp
[])
5440 // temp, until we can get a bootstrap_lookup that works from dyld
5444 if ( ::pipe(sockets
) < 0 ) {
5445 dyld::log("error opening stream socket pair to closured\n");
5448 //dyld::log("created sockets %d and %d\n", sockets[0], sockets[1]);
5449 // use fork/exec to launch closured
5450 int child
= ::__fork();
5451 if ( child
== -1 ) {
5452 dyld::log("error forking, errno=%d\n", errno
);
5457 //dyld::log("parent side pid=%d\n", getpid());
5458 ::close(sockets
[1]);
5459 SocketBasedClousureHeader header
;
5460 long amount
= ::read(sockets
[0], &header
, sizeof(SocketBasedClousureHeader
));
5461 if ( amount
!= sizeof(SocketBasedClousureHeader
) ) {
5462 dyld::log("error reading, errno=%d\n", errno
);
5465 vm_address_t bufferAddress
= 0;
5466 if ( ::vm_allocate(mach_task_self(), &bufferAddress
, header
.length
, VM_FLAGS_ANYWHERE
) != 0 ) {
5467 dyld::log("error allocating buffer\n");
5470 amount
= ::read(sockets
[0], (void*)bufferAddress
, header
.length
);
5472 if ( amount
!= header
.length
) {
5473 dyld::log("dyld: error reading buffer header from closured, amount=%ld, errno=%d\n", amount
, errno
);
5476 if ( header
.success
) {
5477 // make buffer read-only
5478 vm_protect(mach_task_self(), bufferAddress
, header
.length
, VM_PROT_READ
, VM_PROT_READ
);
5479 return (const dyld3::launch_cache::BinaryClosureData
*)bufferAddress
;
5482 // buffer contains error message as to why closure could not be built
5483 dyld::log("%s", (char*)bufferAddress
);
5484 ::vm_deallocate(mach_task_self(), bufferAddress
, header
.length
);
5490 //dyld::log("child side pid=%d\n", getpid());
5492 const char* closuredPath
= "/usr/libexec/closured";
5494 pipeStr
[0] = '0' + sockets
[1];
5496 const char* argv
[32];
5497 char cacheUuidString
[64];
5498 char cacheAddrString
[64];
5499 char cacheSizeString
[64];
5502 sSharedCacheLoadInfo
.loadAddress
->getUUID(cacheUUID
);
5503 makeHexLong((long)sSharedCacheLoadInfo
.loadAddress
, cacheAddrString
);
5504 makeHexLong((long)sSharedCacheLoadInfo
.loadAddress
->mappedSize(), cacheSizeString
);
5505 makeUUID(cacheUUID
, cacheUuidString
);
5506 argv
[i
++] = closuredPath
;
5507 argv
[i
++] = "-create_closure";
5508 argv
[i
++] = mainExecPath
;
5509 argv
[i
++] = "-pipefd";
5510 argv
[i
++] = pipeStr
;
5511 argv
[i
++] = "-cache_uuid";
5512 argv
[i
++] = cacheUuidString
;
5513 argv
[i
++] = "-cache_address";
5514 argv
[i
++] = cacheAddrString
;
5515 argv
[i
++] = "-cache_size";
5516 argv
[i
++] = cacheSizeString
;
5517 for (const char**p
=envp
; *p
!= NULL
; ++p
) {
5518 const char* envToCheck
= *p
;
5519 for (const char* dyldEnvVar
: sEnvVarsToCheck
) {
5520 size_t dyldEnvVarLen
= strlen(dyldEnvVar
);
5521 if ( (strncmp(dyldEnvVar
, envToCheck
, dyldEnvVarLen
) == 0) && (envToCheck
[dyldEnvVarLen
] == '=') ) {
5523 argv
[i
++] = envToCheck
;
5528 //dyld::log("closured args:\n");
5529 //for (int j=0; argv[j] != nullptr; ++j)
5530 // dyld::log(" argv[%d]=%s\n", j, argv[j]);
5531 execve(closuredPath
, (char**)argv
, nullptr);
5532 dyld::log("exec() of closured failed, errno=%d\n", errno
);
5537 // get port to closured
5538 mach_port_t serverPort
= dyld3::loader::lookupClosuredPort();
5539 if ( serverPort
== MACH_PORT_NULL
)
5542 // build env var list
5543 char envBuffer
[2048];
5544 char* s
= envBuffer
;
5545 for (const char* envVar
: sEnvVarsToCheck
) {
5546 if ( const char* valueFromEnv
= _simple_getenv(envp
, envVar
) ) {
5549 strcat(s
, valueFromEnv
);
5555 // get uuid of main executable
5556 dyld3::MachOParser
mainParser((mach_header
*)sMainExecutableMachHeader
);
5558 mainParser
.getUuid(mainUuid
);
5560 // message closured to build closure
5561 bool success
= false;
5562 vm_offset_t reply
= 0;
5563 uint32_t replySize
= 0;
5564 if ( closured_CreateLaunchClosure(serverPort
, sExecPath
, sSharedCachePath
, mainUuid
, envBuffer
, &success
, &reply
, &replySize
) != KERN_SUCCESS
)
5567 // release server port
5568 mach_port_deallocate(mach_task_self(), serverPort
);
5571 return (const dyld3::launch_cache::BinaryClosureData
*)reply
;
5573 dyld::log("closure failed to build: %s\n", (char*)reply
);
5577 #endif // !TARGET_IPHONE_SIMULATOR
5580 #if !__MAC_OS_X_VERSION_MIN_REQUIRED
5581 static const char* sWhiteListDirs
[] = {
5588 static bool inWhiteList(const char* execPath
)
5590 // First test to see if we forced in dyld2 via a kernel boot-arg
5591 if ( dyld3::loader::bootArgsContains("force_dyld2=1") )
5594 #if __MAC_OS_X_VERSION_MIN_REQUIRED
5596 // rdar://problem/32701418: Don't use dyld3 for i386 for now.
5603 #endif // #if __i386__
5606 // <rdar://problem/33171968> enable dyld3 mode for all OS programs when using customer dyld cache (no roots)
5607 if ( (sSharedCacheLoadInfo
.loadAddress
!= nullptr) && (sSharedCacheLoadInfo
.loadAddress
->header
.cacheType
== kDyldSharedCacheTypeProduction
) )
5610 for (const char* dir
: sWhiteListDirs
) {
5611 if ( strncmp(dir
, sExecPath
, strlen(dir
)) == 0 ) {
5615 return dyld3::loader::bootArgsContains("force_dyld3=1");
5620 // Entry point for dyld. The kernel loads dyld and jumps to __dyld_start which
5621 // sets up some registers and call this function.
5623 // Returns address of main() in target program which __dyld_start jumps to
5626 _main(const macho_header
* mainExecutableMH
, uintptr_t mainExecutableSlide
,
5627 int argc
, const char* argv
[], const char* envp
[], const char* apple
[],
5628 uintptr_t* startGlue
)
5630 dyld3::kdebug_trace_dyld_signpost(DBG_DYLD_SIGNPOST_START_DYLD
, 0, 0);
5632 // Grab the cdHash of the main executable from the environment
5633 uint8_t mainExecutableCDHashBuffer
[20];
5634 const uint8_t* mainExecutableCDHash
= nullptr;
5635 if ( hexToBytes(_simple_getenv(apple
, "executable_cdhash"), 40, mainExecutableCDHashBuffer
) )
5636 mainExecutableCDHash
= mainExecutableCDHashBuffer
;
5638 // Trace dyld's load
5639 notifyKernelAboutImage((macho_header
*)&__dso_handle
, _simple_getenv(apple
, "dyld_file"));
5640 #if !TARGET_IPHONE_SIMULATOR
5641 // Trace the main executable's load
5642 notifyKernelAboutImage(mainExecutableMH
, _simple_getenv(apple
, "executable_file"));
5645 uintptr_t result
= 0;
5646 sMainExecutableMachHeader
= mainExecutableMH
;
5647 sMainExecutableSlide
= mainExecutableSlide
;
5648 #if __MAC_OS_X_VERSION_MIN_REQUIRED
5649 // if this is host dyld, check to see if iOS simulator is being run
5650 const char* rootPath
= _simple_getenv(envp
, "DYLD_ROOT_PATH");
5651 if ( rootPath
!= NULL
) {
5653 // look to see if simulator has its own dyld
5654 char simDyldPath
[PATH_MAX
];
5655 strlcpy(simDyldPath
, rootPath
, PATH_MAX
);
5656 strlcat(simDyldPath
, "/usr/lib/dyld_sim", PATH_MAX
);
5657 int fd
= my_open(simDyldPath
, O_RDONLY
, 0);
5659 const char* errMessage
= useSimulatorDyld(fd
, mainExecutableMH
, simDyldPath
, argc
, argv
, envp
, apple
, startGlue
, &result
);
5660 if ( errMessage
!= NULL
)
5667 CRSetCrashLogMessage("dyld: launch started");
5669 setContext(mainExecutableMH
, argc
, argv
, envp
, apple
);
5671 // Pickup the pointer to the exec path.
5672 sExecPath
= _simple_getenv(apple
, "executable_path");
5674 // <rdar://problem/13868260> Remove interim apple[0] transition code from dyld
5675 if (!sExecPath
) sExecPath
= apple
[0];
5677 if ( sExecPath
[0] != '/' ) {
5678 // have relative path, use cwd to make absolute
5679 char cwdbuff
[MAXPATHLEN
];
5680 if ( getcwd(cwdbuff
, MAXPATHLEN
) != NULL
) {
5681 // maybe use static buffer to avoid calling malloc so early...
5682 char* s
= new char[strlen(cwdbuff
) + strlen(sExecPath
) + 2];
5685 strcat(s
, sExecPath
);
5690 // Remember short name of process for later logging
5691 sExecShortName
= ::strrchr(sExecPath
, '/');
5692 if ( sExecShortName
!= NULL
)
5695 sExecShortName
= sExecPath
;
5697 configureProcessRestrictions(mainExecutableMH
);
5699 #if __MAC_OS_X_VERSION_MIN_REQUIRED
5700 if ( gLinkContext
.processIsRestricted
) {
5701 pruneEnvironmentVariables(envp
, &apple
);
5702 // set again because envp and apple may have changed or moved
5703 setContext(mainExecutableMH
, argc
, argv
, envp
, apple
);
5708 checkEnvironmentVariables(envp
);
5709 defaultUninitializedFallbackPaths(envp
);
5711 if ( sEnv
.DYLD_PRINT_OPTS
)
5713 if ( sEnv
.DYLD_PRINT_ENV
)
5714 printEnvironmentVariables(envp
);
5715 getHostInfo(mainExecutableMH
, mainExecutableSlide
);
5717 // load shared cache
5718 checkSharedRegionDisable((mach_header
*)mainExecutableMH
);
5719 #if TARGET_IPHONE_SIMULATOR
5720 // <HACK> until <rdar://30773711> is fixed
5721 gLinkContext
.sharedRegionMode
= ImageLoader::kUsePrivateSharedRegion
;
5724 if ( gLinkContext
.sharedRegionMode
!= ImageLoader::kDontUseSharedRegion
) {
5728 if ( (sEnableClosures
|| inWhiteList(sExecPath
)) && (sSharedCacheLoadInfo
.loadAddress
!= nullptr) ) {
5729 if ( sSharedCacheLoadInfo
.loadAddress
->header
.formatVersion
== dyld3::launch_cache::binary_format::kFormatVersion
) {
5730 const dyld3::launch_cache::BinaryClosureData
* mainClosureData
;
5731 // check for closure in cache first
5732 dyld3::DyldCacheParser
cacheParser(sSharedCacheLoadInfo
.loadAddress
, false);
5733 mainClosureData
= cacheParser
.findClosure(sExecPath
);
5734 #if __IPHONE_OS_VERSION_MIN_REQUIRED
5735 if ( mainClosureData
== nullptr ) {
5736 // see if this is an OS app that was moved
5737 if ( strncmp(sExecPath
, "/var/containers/Bundle/Application/", 35) == 0 ) {
5738 dyld3::MachOParser
mainParser((mach_header
*)mainExecutableMH
);
5739 uint32_t textOffset
;
5741 if ( !mainParser
.isFairPlayEncrypted(textOffset
, textSize
) ) {
5742 __block
bool hasEmbeddedDylibs
= false;
5743 mainParser
.forEachDependentDylib(^(const char* loadPath
, bool, bool, bool, uint32_t, uint32_t, bool& stop
) {
5744 if ( loadPath
[0] == '@' ) {
5745 hasEmbeddedDylibs
= true;
5749 if ( !hasEmbeddedDylibs
) {
5751 const char* lastSlash
= strrchr(sExecPath
, '/');
5752 if ( lastSlash
!= nullptr ) {
5753 strlcpy(altPath
, "/private/var/staged_system_apps", sizeof(altPath
));
5754 strlcat(altPath
, lastSlash
, sizeof(altPath
));
5755 strlcat(altPath
, ".app", sizeof(altPath
));
5756 strlcat(altPath
, lastSlash
, sizeof(altPath
));
5757 if ( gLinkContext
.verboseWarnings
)
5758 dyld::log("try path: %s\n", altPath
);
5759 mainClosureData
= cacheParser
.findClosure(altPath
);
5766 if ( gLinkContext
.verboseWarnings
&& (mainClosureData
!= nullptr) )
5767 dyld::log("dyld: found closure %p in dyld shared cache\n", mainClosureData
);
5768 #if !TARGET_IPHONE_SIMULATOR
5769 if ( (mainClosureData
== nullptr) || !closureValid(mainClosureData
, (mach_header
*)mainExecutableMH
, mainExecutableCDHash
, true, envp
) ) {
5770 mainClosureData
= nullptr;
5771 if ( sEnableClosures
) {
5772 // if forcing closures, and no closure in cache, or it is invalid, then RPC to closured
5773 mainClosureData
= callClosureDaemon(sExecPath
, envp
);
5774 if ( gLinkContext
.verboseWarnings
)
5775 dyld::log("dyld: closured return %p for %s\n", mainClosureData
, sExecPath
);
5776 if ( (mainClosureData
!= nullptr) && !closureValid(mainClosureData
, (mach_header
*)mainExecutableMH
, mainExecutableCDHash
, false, envp
) ) {
5777 // some how freshly generated closure is invalid...
5778 mainClosureData
= nullptr;
5783 // try using launch closure
5784 if ( mainClosureData
!= nullptr ) {
5785 CRSetCrashLogMessage("dyld3: launch started");
5786 if ( launchWithClosure(mainClosureData
, sSharedCacheLoadInfo
.loadAddress
, (mach_header
*)mainExecutableMH
, mainExecutableSlide
,
5787 argc
, argv
, envp
, apple
, &result
, startGlue
) ) {
5789 result
= (uintptr_t)&fake_main
;
5793 if ( gLinkContext
.verboseWarnings
)
5794 dyld::log("dyld: unable to use closure %p\n", mainClosureData
);
5799 if ( gLinkContext
.verboseWarnings
)
5800 dyld::log("dyld: not using closure because shared cache format version does not match dyld's\n");
5802 // could not use closure info, launch old way
5806 // install gdb notifier
5807 stateToHandlers(dyld_image_state_dependents_mapped
, sBatchHandlers
)->push_back(notifyGDB
);
5808 stateToHandlers(dyld_image_state_mapped
, sSingleHandlers
)->push_back(updateAllImages
);
5809 // make initial allocations large enough that it is unlikely to need to be re-alloced
5810 sImageRoots
.reserve(16);
5811 sAddImageCallbacks
.reserve(4);
5812 sRemoveImageCallbacks
.reserve(4);
5813 sImageFilesNeedingTermination
.reserve(16);
5814 sImageFilesNeedingDOFUnregistration
.reserve(8);
5816 #if !TARGET_IPHONE_SIMULATOR
5817 #ifdef WAIT_FOR_SYSTEM_ORDER_HANDSHAKE
5818 // <rdar://problem/6849505> Add gating mechanism to dyld support system order file generation process
5819 WAIT_FOR_SYSTEM_ORDER_HANDSHAKE(dyld::gProcessInfo
->systemOrderFlag
);
5825 // add dyld itself to UUID list
5826 addDyldImageToUUIDList();
5828 #if SUPPORT_ACCELERATE_TABLES
5829 bool mainExcutableAlreadyRebased
= false;
5830 if ( (sSharedCacheLoadInfo
.loadAddress
!= nullptr) && !dylibsCanOverrideCache() && !sDisableAcceleratorTables
&& (sSharedCacheLoadInfo
.loadAddress
->header
.accelerateInfoAddr
!= 0) ) {
5831 struct stat statBuf
;
5832 if ( ::stat(IPHONE_DYLD_SHARED_CACHE_DIR
"no-dyld2-accelerator-tables", &statBuf
) != 0 )
5833 sAllCacheImagesProxy
= ImageLoaderMegaDylib::makeImageLoaderMegaDylib(&sSharedCacheLoadInfo
.loadAddress
->header
, sSharedCacheLoadInfo
.slide
, mainExecutableMH
, gLinkContext
);
5839 CRSetCrashLogMessage(sLoadingCrashMessage
);
5840 // instantiate ImageLoader for main executable
5841 sMainExecutable
= instantiateFromLoadedImage(mainExecutableMH
, mainExecutableSlide
, sExecPath
);
5842 gLinkContext
.mainExecutable
= sMainExecutable
;
5843 gLinkContext
.mainExecutableCodeSigned
= hasCodeSignatureLoadCommand(mainExecutableMH
);
5845 #if TARGET_IPHONE_SIMULATOR
5846 // check main executable is not too new for this OS
5848 if ( ! isSimulatorBinary((uint8_t*)mainExecutableMH
, sExecPath
) ) {
5849 throwf("program was built for a platform that is not supported by this runtime");
5851 uint32_t mainMinOS
= sMainExecutable
->minOSVersion();
5853 // dyld is always built for the current OS, so we can get the current OS version
5854 // from the load command in dyld itself.
5855 uint32_t dyldMinOS
= ImageLoaderMachO::minOSVersion((const mach_header
*)&__dso_handle
);
5856 if ( mainMinOS
> dyldMinOS
) {
5858 throwf("app was built for watchOS %d.%d which is newer than this simulator %d.%d",
5859 mainMinOS
>> 16, ((mainMinOS
>> 8) & 0xFF),
5860 dyldMinOS
>> 16, ((dyldMinOS
>> 8) & 0xFF));
5862 throwf("app was built for tvOS %d.%d which is newer than this simulator %d.%d",
5863 mainMinOS
>> 16, ((mainMinOS
>> 8) & 0xFF),
5864 dyldMinOS
>> 16, ((dyldMinOS
>> 8) & 0xFF));
5866 throwf("app was built for iOS %d.%d which is newer than this simulator %d.%d",
5867 mainMinOS
>> 16, ((mainMinOS
>> 8) & 0xFF),
5868 dyldMinOS
>> 16, ((dyldMinOS
>> 8) & 0xFF));
5875 #if __MAC_OS_X_VERSION_MIN_REQUIRED
5876 // <rdar://problem/22805519> be less strict about old mach-o binaries
5877 uint32_t mainSDK
= sMainExecutable
->sdkVersion();
5878 gLinkContext
.strictMachORequired
= (mainSDK
>= DYLD_MACOSX_VERSION_10_12
) || gLinkContext
.processUsingLibraryValidation
;
5880 // simulators, iOS, tvOS, and watchOS are always strict
5881 gLinkContext
.strictMachORequired
= true;
5884 #if SUPPORT_ACCELERATE_TABLES
5885 sAllImages
.reserve((sAllCacheImagesProxy
!= NULL
) ? 16 : INITIAL_IMAGE_COUNT
);
5887 sAllImages
.reserve(INITIAL_IMAGE_COUNT
);
5890 // Now that shared cache is loaded, setup an versioned dylib overrides
5891 #if SUPPORT_VERSIONED_PATHS
5892 checkVersionedPaths();
5896 // dyld_all_image_infos image list does not contain dyld
5897 // add it as dyldPath field in dyld_all_image_infos
5898 // for simulator, dyld_sim is in image list, need host dyld added
5899 #if TARGET_IPHONE_SIMULATOR
5900 // get path of host dyld from table of syscall vectors in host dyld
5901 void* addressInDyld
= gSyscallHelpers
;
5903 // get path of dyld itself
5904 void* addressInDyld
= (void*)&__dso_handle
;
5906 char dyldPathBuffer
[MAXPATHLEN
+1];
5907 int len
= proc_regionfilename(getpid(), (uint64_t)(long)addressInDyld
, dyldPathBuffer
, MAXPATHLEN
);
5909 dyldPathBuffer
[len
] = '\0'; // proc_regionfilename() does not zero terminate returned string
5910 if ( strcmp(dyldPathBuffer
, gProcessInfo
->dyldPath
) != 0 )
5911 gProcessInfo
->dyldPath
= strdup(dyldPathBuffer
);
5914 // load any inserted libraries
5915 if ( sEnv
.DYLD_INSERT_LIBRARIES
!= NULL
) {
5916 for (const char* const* lib
= sEnv
.DYLD_INSERT_LIBRARIES
; *lib
!= NULL
; ++lib
)
5917 loadInsertedDylib(*lib
);
5919 // record count of inserted libraries so that a flat search will look at
5920 // inserted libraries, then main, then others.
5921 sInsertedDylibCount
= sAllImages
.size()-1;
5923 // link main executable
5924 gLinkContext
.linkingMainExecutable
= true;
5925 #if SUPPORT_ACCELERATE_TABLES
5926 if ( mainExcutableAlreadyRebased
) {
5927 // previous link() on main executable has already adjusted its internal pointers for ASLR
5928 // work around that by rebasing by inverse amount
5929 sMainExecutable
->rebase(gLinkContext
, -mainExecutableSlide
);
5932 link(sMainExecutable
, sEnv
.DYLD_BIND_AT_LAUNCH
, true, ImageLoader::RPathChain(NULL
, NULL
), -1);
5933 sMainExecutable
->setNeverUnloadRecursive();
5934 if ( sMainExecutable
->forceFlat() ) {
5935 gLinkContext
.bindFlat
= true;
5936 gLinkContext
.prebindUsage
= ImageLoader::kUseNoPrebinding
;
5939 // link any inserted libraries
5940 // do this after linking main executable so that any dylibs pulled in by inserted
5941 // dylibs (e.g. libSystem) will not be in front of dylibs the program uses
5942 if ( sInsertedDylibCount
> 0 ) {
5943 for(unsigned int i
=0; i
< sInsertedDylibCount
; ++i
) {
5944 ImageLoader
* image
= sAllImages
[i
+1];
5945 link(image
, sEnv
.DYLD_BIND_AT_LAUNCH
, true, ImageLoader::RPathChain(NULL
, NULL
), -1);
5946 image
->setNeverUnloadRecursive();
5948 // only INSERTED libraries can interpose
5949 // register interposing info after all inserted libraries are bound so chaining works
5950 for(unsigned int i
=0; i
< sInsertedDylibCount
; ++i
) {
5951 ImageLoader
* image
= sAllImages
[i
+1];
5952 image
->registerInterposing();
5956 // <rdar://problem/19315404> dyld should support interposition even without DYLD_INSERT_LIBRARIES
5957 for (long i
=sInsertedDylibCount
+1; i
< sAllImages
.size(); ++i
) {
5958 ImageLoader
* image
= sAllImages
[i
];
5959 if ( image
->inSharedCache() )
5961 image
->registerInterposing();
5963 #if SUPPORT_ACCELERATE_TABLES
5964 if ( (sAllCacheImagesProxy
!= NULL
) && ImageLoader::haveInterposingTuples() ) {
5965 // Accelerator tables cannot be used with implicit interposing, so relaunch with accelerator tables disabled
5966 ImageLoader::clearInterposingTuples();
5967 // unmap all loaded dylibs (but not main executable)
5968 for (long i
=1; i
< sAllImages
.size(); ++i
) {
5969 ImageLoader
* image
= sAllImages
[i
];
5970 if ( image
== sMainExecutable
)
5972 if ( image
== sAllCacheImagesProxy
)
5974 image
->setCanUnload();
5975 ImageLoader::deleteImage(image
);
5977 // note: we don't need to worry about inserted images because if DYLD_INSERT_LIBRARIES was set we would not be using the accelerator table
5979 sImageRoots
.clear();
5980 sImageFilesNeedingTermination
.clear();
5981 sImageFilesNeedingDOFUnregistration
.clear();
5982 sAddImageCallbacks
.clear();
5983 sRemoveImageCallbacks
.clear();
5984 sDisableAcceleratorTables
= true;
5985 sAllCacheImagesProxy
= NULL
;
5986 sMappedRangesStart
= NULL
;
5987 mainExcutableAlreadyRebased
= true;
5988 gLinkContext
.linkingMainExecutable
= false;
5990 goto reloadAllImages
;
5994 // apply interposing to initial set of images
5995 for(int i
=0; i
< sImageRoots
.size(); ++i
) {
5996 sImageRoots
[i
]->applyInterposing(gLinkContext
);
5998 gLinkContext
.linkingMainExecutable
= false;
6000 // <rdar://problem/12186933> do weak binding only after all inserted images linked
6001 sMainExecutable
->weakBind(gLinkContext
);
6003 // If cache has branch island dylibs, tell debugger about them
6004 if ( (sSharedCacheLoadInfo
.loadAddress
!= NULL
) && (sSharedCacheLoadInfo
.loadAddress
->header
.mappingOffset
>= 0x78) && (sSharedCacheLoadInfo
.loadAddress
->header
.branchPoolsOffset
!= 0) ) {
6005 uint32_t count
= sSharedCacheLoadInfo
.loadAddress
->header
.branchPoolsCount
;
6006 dyld_image_info info
[count
];
6007 const uint64_t* poolAddress
= (uint64_t*)((char*)sSharedCacheLoadInfo
.loadAddress
+ sSharedCacheLoadInfo
.loadAddress
->header
.branchPoolsOffset
);
6008 // <rdar://problem/20799203> empty branch pools can be in development cache
6009 if ( ((mach_header
*)poolAddress
)->magic
== sMainExecutableMachHeader
->magic
) {
6010 for (int poolIndex
=0; poolIndex
< count
; ++poolIndex
) {
6011 uint64_t poolAddr
= poolAddress
[poolIndex
] + sSharedCacheLoadInfo
.slide
;
6012 info
[poolIndex
].imageLoadAddress
= (mach_header
*)(long)poolAddr
;
6013 info
[poolIndex
].imageFilePath
= "dyld_shared_cache_branch_islands";
6014 info
[poolIndex
].imageFileModDate
= 0;
6016 // add to all_images list
6017 addImagesToAllImages(count
, info
);
6018 // tell gdb about new branch island images
6019 gProcessInfo
->notification(dyld_image_adding
, count
, info
);
6023 CRSetCrashLogMessage("dyld: launch, running initializers");
6024 #if SUPPORT_OLD_CRT_INITIALIZATION
6025 // Old way is to run initializers via a callback from crt1.o
6026 if ( ! gRunInitializersOldWay
)
6027 initializeMainExecutable();
6029 // run all initializers
6030 initializeMainExecutable();
6033 // notify any montoring proccesses that this process is about to enter main()
6034 dyld3::kdebug_trace_dyld_signpost(DBG_DYLD_SIGNPOST_START_MAIN_DYLD2
, 0, 0);
6035 notifyMonitoringDyldMain();
6037 // find entry point for main executable
6038 result
= (uintptr_t)sMainExecutable
->getThreadPC();
6039 if ( result
!= 0 ) {
6040 // main executable uses LC_MAIN, needs to return to glue in libdyld.dylib
6041 if ( (gLibSystemHelpers
!= NULL
) && (gLibSystemHelpers
->version
>= 9) )
6042 *startGlue
= (uintptr_t)gLibSystemHelpers
->startGlueToCallExit
;
6044 halt("libdyld.dylib support not present for LC_MAIN");
6047 // main executable uses LC_UNIXTHREAD, dyld needs to let "start" in program set up for main()
6048 result
= (uintptr_t)sMainExecutable
->getMain();
6052 catch(const char* message
) {
6057 dyld::log("dyld: launch failed\n");
6060 CRSetCrashLogMessage(NULL
);
6063 dyld3::kdebug_trace_dyld_signpost(DBG_DYLD_SIGNPOST_START_MAIN
, 0, 0);
6064 result
= (uintptr_t)&fake_main
;
6065 *startGlue
= (uintptr_t)gLibSystemHelpers
->startGlueToCallExit
;