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@
34 #include <sys/param.h>
35 #include <mach/mach_time.h> // mach_absolute_time()
36 #include <mach/mach_init.h>
37 #include <sys/types.h>
39 #include <sys/syscall.h>
40 #include <sys/socket.h>
42 #include <sys/syslog.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 <sys/fsgetpath.h>
66 #if TARGET_OS_SIMULATOR
68 AMFI_DYLD_INPUT_PROC_IN_SIMULATOR
= (1 << 0),
70 enum amfi_dyld_policy_output_flag_set
{
71 AMFI_DYLD_OUTPUT_ALLOW_AT_PATH
= (1 << 0),
72 AMFI_DYLD_OUTPUT_ALLOW_PATH_VARS
= (1 << 1),
73 AMFI_DYLD_OUTPUT_ALLOW_CUSTOM_SHARED_CACHE
= (1 << 2),
74 AMFI_DYLD_OUTPUT_ALLOW_FALLBACK_PATHS
= (1 << 3),
75 AMFI_DYLD_OUTPUT_ALLOW_PRINT_VARS
= (1 << 4),
76 AMFI_DYLD_OUTPUT_ALLOW_FAILED_LIBRARY_INSERTION
= (1 << 5),
78 extern "C" int amfi_check_dyld_policy_self(uint64_t input_flags
, uint64_t* output_flags
);
83 #include <sandbox/private.h>
84 #if __has_feature(ptrauth_calls)
88 extern "C" int __fork();
96 #include "ImageLoader.h"
97 #include "ImageLoaderMachO.h"
98 #include "dyldLibSystemInterface.h"
99 #include "dyld_cache_format.h"
100 #include "dyld_process_info_internal.h"
102 #if SUPPORT_ACCELERATE_TABLES
103 #include "ImageLoaderMegaDylib.h"
106 #if TARGET_OS_SIMULATOR
107 extern "C" void* gSyscallHelpers
;
109 #include "dyldSyscallInterface.h"
113 #include "libdyldEntryVector.h"
114 #include "MachOLoaded.h"
116 #include "DyldSharedCache.h"
117 #include "SharedCacheRuntime.h"
118 #include "StringUtils.h"
120 #include "ClosureBuilder.h"
121 #include "ClosureFileSystemPhysical.h"
122 #include "FileUtils.h"
123 #include "BootArgs.h"
126 #define MH_HAS_OBJC 0x40000000
129 // not libc header for send() syscall interface
130 extern "C" ssize_t
__sendto(int, const void *, size_t, int, const struct sockaddr
*, socklen_t
);
133 // ARM and x86_64 are the only architecture that use cpu-sub-types
134 #define CPU_SUBTYPES_SUPPORTED ((__arm__ || __arm64__ || __x86_64__) && !TARGET_OS_SIMULATOR)
137 #define LC_SEGMENT_COMMAND LC_SEGMENT_64
138 #define LC_SEGMENT_COMMAND_WRONG LC_SEGMENT
139 #define LC_ENCRYPT_COMMAND LC_ENCRYPTION_INFO
140 #define macho_segment_command segment_command_64
141 #define macho_section section_64
143 #define LC_SEGMENT_COMMAND LC_SEGMENT
144 #define LC_SEGMENT_COMMAND_WRONG LC_SEGMENT_64
145 #define LC_ENCRYPT_COMMAND LC_ENCRYPTION_INFO_64
146 #define macho_segment_command segment_command
147 #define macho_section section
152 #define CPU_TYPE_MASK 0x00FFFFFF /* complement of CPU_ARCH_MASK */
155 /* implemented in dyld_gdb.cpp */
156 extern void resetAllImages();
157 extern void addImagesToAllImages(uint32_t infoCount
, const dyld_image_info info
[]);
158 extern void removeImageFromAllImages(const mach_header
* mh
);
159 extern void addNonSharedCacheImageUUID(const dyld_uuid_info
& info
);
160 extern const char* notifyGDB(enum dyld_image_states state
, uint32_t infoCount
, const dyld_image_info info
[]);
161 extern size_t allImagesCount();
163 // magic so CrashReporter logs message
165 char error_string
[1024];
168 // magic linker symbol for start of dyld binary
169 extern "C" const macho_header __dso_handle
;
173 // The file contains the core of dyld used to get a process to main().
174 // The API's that dyld supports are implemented in dyldAPIs.cpp.
181 struct RegisteredDOF
{ const mach_header
* mh
; int registrationID
; };
182 struct DylibOverride
{ const char* installName
; const char* override
; };
186 VECTOR_NEVER_DESTRUCTED(ImageLoader
*);
187 VECTOR_NEVER_DESTRUCTED(dyld::RegisteredDOF
);
188 VECTOR_NEVER_DESTRUCTED(dyld::ImageCallback
);
189 VECTOR_NEVER_DESTRUCTED(dyld::DylibOverride
);
190 VECTOR_NEVER_DESTRUCTED(ImageLoader::DynamicReference
);
192 VECTOR_NEVER_DESTRUCTED(dyld_image_state_change_handler
);
198 // state of all environment variables dyld uses
200 struct EnvironmentVariables
{
201 const char* const * DYLD_FRAMEWORK_PATH
;
202 const char* const * DYLD_FALLBACK_FRAMEWORK_PATH
;
203 const char* const * DYLD_LIBRARY_PATH
;
204 const char* const * DYLD_FALLBACK_LIBRARY_PATH
;
205 const char* const * DYLD_INSERT_LIBRARIES
;
206 const char* const * LD_LIBRARY_PATH
; // for unix conformance
207 const char* const * DYLD_VERSIONED_LIBRARY_PATH
;
208 const char* const * DYLD_VERSIONED_FRAMEWORK_PATH
;
209 bool DYLD_PRINT_LIBRARIES_POST_LAUNCH
;
210 bool DYLD_BIND_AT_LAUNCH
;
211 bool DYLD_PRINT_STATISTICS
;
212 bool DYLD_PRINT_STATISTICS_DETAILS
;
213 bool DYLD_PRINT_OPTS
;
215 bool DYLD_DISABLE_DOFS
;
217 // DYLD_SHARED_CACHE_DIR ==> sSharedCacheOverrideDir
218 // DYLD_ROOT_PATH ==> gLinkContext.rootPaths
219 // DYLD_IMAGE_SUFFIX ==> gLinkContext.imageSuffix
220 // DYLD_PRINT_OPTS ==> gLinkContext.verboseOpts
221 // DYLD_PRINT_ENV ==> gLinkContext.verboseEnv
222 // DYLD_FORCE_FLAT_NAMESPACE ==> gLinkContext.bindFlat
223 // DYLD_PRINT_INITIALIZERS ==> gLinkContext.verboseInit
224 // DYLD_PRINT_SEGMENTS ==> gLinkContext.verboseMapping
225 // DYLD_PRINT_BINDINGS ==> gLinkContext.verboseBind
226 // DYLD_PRINT_WEAK_BINDINGS ==> gLinkContext.verboseWeakBind
227 // DYLD_PRINT_REBASINGS ==> gLinkContext.verboseRebase
228 // DYLD_PRINT_DOFS ==> gLinkContext.verboseDOF
229 // DYLD_PRINT_APIS ==> gLogAPIs
230 // DYLD_IGNORE_PREBINDING ==> gLinkContext.prebindUsage
231 // DYLD_PREBIND_DEBUG ==> gLinkContext.verbosePrebinding
232 // DYLD_NEW_LOCAL_SHARED_REGIONS ==> gLinkContext.sharedRegionMode
233 // DYLD_SHARED_REGION ==> gLinkContext.sharedRegionMode
234 // DYLD_PRINT_WARNINGS ==> gLinkContext.verboseWarnings
235 // DYLD_PRINT_RPATHS ==> gLinkContext.verboseRPaths
236 // DYLD_PRINT_INTERPOSING ==> gLinkContext.verboseInterposing
237 // DYLD_PRINT_LIBRARIES ==> gLinkContext.verboseLoading
242 typedef std::vector
<dyld_image_state_change_handler
> StateHandlers
;
245 enum EnvVarMode
{ envNone
, envPrintOnly
, envAll
};
248 static const char* sExecPath
= NULL
;
249 static const char* sExecShortName
= NULL
;
250 static const macho_header
* sMainExecutableMachHeader
= NULL
;
251 static uintptr_t sMainExecutableSlide
= 0;
252 #if CPU_SUBTYPES_SUPPORTED
253 static cpu_type_t sHostCPU
;
254 static cpu_subtype_t sHostCPUsubtype
;
256 static ImageLoaderMachO
* sMainExecutable
= NULL
;
257 static size_t sInsertedDylibCount
= 0;
258 static std::vector
<ImageLoader
*> sAllImages
;
259 static std::vector
<ImageLoader
*> sImageRoots
;
260 static std::vector
<ImageLoader
*> sImageFilesNeedingTermination
;
261 static std::vector
<RegisteredDOF
> sImageFilesNeedingDOFUnregistration
;
262 static std::vector
<ImageCallback
> sAddImageCallbacks
;
263 static std::vector
<ImageCallback
> sRemoveImageCallbacks
;
264 static std::vector
<LoadImageCallback
> sAddLoadImageCallbacks
;
265 static std::vector
<LoadImageBulkCallback
> sAddBulkLoadImageCallbacks
;
266 static bool sRemoveImageCallbacksInUse
= false;
267 static void* sSingleHandlers
[7][3];
268 static void* sBatchHandlers
[7][3];
269 static ImageLoader
* sLastImageByAddressCache
;
270 static EnvironmentVariables sEnv
;
271 #if __MAC_OS_X_VERSION_MIN_REQUIRED
272 static const char* sFrameworkFallbackPaths
[] = { "$HOME/Library/Frameworks", "/Library/Frameworks", "/Network/Library/Frameworks", "/System/Library/Frameworks", NULL
};
273 static const char* sLibraryFallbackPaths
[] = { "$HOME/lib", "/usr/local/lib", "/usr/lib", NULL
};
274 static const char* sRestrictedFrameworkFallbackPaths
[] = { "/System/Library/Frameworks", NULL
};
275 static const char* sRestrictedLibraryFallbackPaths
[] = { "/usr/lib", NULL
};
277 static const char* sFrameworkFallbackPaths
[] = { "/System/Library/Frameworks", NULL
};
278 static const char* sLibraryFallbackPaths
[] = { "/usr/local/lib", "/usr/lib", NULL
};
280 static UndefinedHandler sUndefinedHandler
= NULL
;
281 static ImageLoader
* sBundleBeingLoaded
= NULL
; // hack until OFI is reworked
282 static dyld3::SharedCacheLoadInfo sSharedCacheLoadInfo
;
283 static const char* sSharedCacheOverrideDir
;
284 bool gSharedCacheOverridden
= false;
285 ImageLoader::LinkContext gLinkContext
;
286 bool gLogAPIs
= false;
287 #if SUPPORT_ACCELERATE_TABLES
288 bool gLogAppAPIs
= false;
290 const struct LibSystemHelpers
* gLibSystemHelpers
= NULL
;
291 #if SUPPORT_OLD_CRT_INITIALIZATION
292 bool gRunInitializersOldWay
= false;
294 static std::vector
<DylibOverride
> sDylibOverrides
;
295 #if !TARGET_OS_SIMULATOR
296 static int sLogSocket
= -1;
298 static bool sFrameworksFoundAsDylibs
= false;
299 #if __x86_64__ && !TARGET_OS_SIMULATOR
300 static bool sHaswell
= false;
302 static std::vector
<ImageLoader::DynamicReference
> sDynamicReferences
;
303 #pragma clang diagnostic push
304 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
305 static OSSpinLock sDynamicReferencesLock
= 0;
306 #pragma clang diagnostic pop
307 #if !TARGET_OS_SIMULATOR
308 static bool sLogToFile
= false;
310 static char sLoadingCrashMessage
[1024] = "dyld: launch, loading dependent libraries";
311 static _dyld_objc_notify_mapped sNotifyObjCMapped
;
312 static _dyld_objc_notify_init sNotifyObjCInit
;
313 static _dyld_objc_notify_unmapped sNotifyObjCUnmapped
;
315 #if __IPHONE_OS_VERSION_MIN_REQUIRED && !TARGET_OS_SIMULATOR
316 static bool sForceStderr
= false;
320 #if SUPPORT_ACCELERATE_TABLES
321 static ImageLoaderMegaDylib
* sAllCacheImagesProxy
= NULL
;
322 // Note these are now off by default as everything should use dyld3.
323 static bool sDisableAcceleratorTables
= true;
326 bool gUseDyld3
= false;
327 static bool sSkipMain
= false;
328 static void (*sEntryOveride
)() = nullptr;
329 static bool sJustBuildClosure
= false;
330 static bool sLogClosureFailure
= false;
332 enum class ClosureMode
{
333 // Unset means we haven't provided an env variable or boot-arg to explicitly choose a mode
335 // On means we set DYLD_USE_CLOSURES=1, or we didn't have DYLD_USE_CLOSURES=0 but did have
336 // -force_dyld3=1 env variable or a customer cache on iOS
338 // Off means we set DYLD_USE_CLOSURES=0, or we didn't have DYLD_USE_CLOSURES=1 but did have
339 // -force_dyld2=1 env variable or an internal cache on iOS
341 // PreBuiltOnly means only use a shared cache closure and don't try build a new one
345 static ClosureMode sClosureMode
= ClosureMode::Unset
;
346 static bool sForceInvalidSharedCacheClosureFormat
= false;
347 static uint64_t launchTraceID
= 0;
350 // The MappedRanges structure is used for fast address->image lookups.
351 // The table is only updated when the dyld lock is held, so we don't
352 // need to worry about multiple writers. But readers may look at this
353 // data without holding the lock. Therefore, all updates must be done
354 // in an order that will never cause readers to see inconsistent data.
355 // The general rule is that if the image field is non-NULL then
356 // the other fields are valid.
369 static MappedRanges
* sMappedRangesStart
;
371 #pragma clang diagnostic push
372 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
373 void addMappedRange(ImageLoader
* image
, uintptr_t start
, uintptr_t end
)
375 //dyld::log("addMappedRange(0x%lX->0x%lX) for %s\n", start, end, image->getShortName());
376 for (MappedRanges
* p
= sMappedRangesStart
; p
!= NULL
; p
= p
->next
) {
377 for (unsigned long i
=0; i
< p
->count
; ++i
) {
378 if ( p
->array
[i
].image
== NULL
) {
379 p
->array
[i
].start
= start
;
380 p
->array
[i
].end
= end
;
381 // add image field last with a barrier so that any reader will see consistent records
383 p
->array
[i
].image
= image
;
388 // table must be full, chain another
389 #if SUPPORT_ACCELERATE_TABLES
390 unsigned count
= (sAllCacheImagesProxy
!= NULL
) ? 16 : 400;
392 unsigned count
= 400;
394 size_t allocationSize
= sizeof(MappedRanges
) + (count
-1)*3*sizeof(void*);
395 MappedRanges
* newRanges
= (MappedRanges
*)malloc(allocationSize
);
396 bzero(newRanges
, allocationSize
);
397 newRanges
->count
= count
;
398 newRanges
->array
[0].start
= start
;
399 newRanges
->array
[0].end
= end
;
400 newRanges
->array
[0].image
= image
;
402 if ( sMappedRangesStart
== NULL
) {
403 sMappedRangesStart
= newRanges
;
406 for (MappedRanges
* p
= sMappedRangesStart
; p
!= NULL
; p
= p
->next
) {
407 if ( p
->next
== NULL
) {
416 void removedMappedRanges(ImageLoader
* image
)
418 for (MappedRanges
* p
= sMappedRangesStart
; p
!= NULL
; p
= p
->next
) {
419 for (unsigned long i
=0; i
< p
->count
; ++i
) {
420 if ( p
->array
[i
].image
== image
) {
421 // clear with a barrier so that any reader will see consistent records
423 p
->array
[i
].image
= NULL
;
428 #pragma clang diagnostic pop
430 ImageLoader
* findMappedRange(uintptr_t target
)
432 for (MappedRanges
* p
= sMappedRangesStart
; p
!= NULL
; p
= p
->next
) {
433 for (unsigned long i
=0; i
< p
->count
; ++i
) {
434 if ( p
->array
[i
].image
!= NULL
) {
435 if ( (p
->array
[i
].start
<= target
) && (target
< p
->array
[i
].end
) )
436 return p
->array
[i
].image
;
445 const char* mkstringf(const char* format
, ...)
447 _SIMPLE_STRING buf
= _simple_salloc();
450 va_start(list
, format
);
451 _simple_vsprintf(buf
, format
, list
);
453 const char* t
= strdup(_simple_string(buf
));
458 return "mkstringf, out of memory error";
462 void throwf(const char* format
, ...)
464 _SIMPLE_STRING buf
= _simple_salloc();
467 va_start(list
, format
);
468 _simple_vsprintf(buf
, format
, list
);
470 const char* t
= strdup(_simple_string(buf
));
475 throw "throwf, out of memory error";
479 #if !TARGET_OS_SIMULATOR
480 static int sLogfile
= STDERR_FILENO
;
483 #if !TARGET_OS_SIMULATOR
484 // based on CFUtilities.c: also_do_stderr()
485 static bool useSyslog()
487 // Use syslog() for processes managed by launchd
488 static bool launchdChecked
= false;
489 static bool launchdOwned
= false;
490 if ( !launchdChecked
&& gProcessInfo
->libSystemInitialized
) {
491 if ( (gLibSystemHelpers
!= NULL
) && (gLibSystemHelpers
->version
>= 11) ) {
492 // <rdar://problem/23520449> only call isLaunchdOwned() after libSystem is initialized
493 launchdOwned
= (*gLibSystemHelpers
->isLaunchdOwned
)();
494 launchdChecked
= true;
497 if ( launchdChecked
&& launchdOwned
)
500 // If stderr is not available, use syslog()
502 int result
= fstat(STDERR_FILENO
, &sb
);
504 return true; // file descriptor 2 is closed
510 static void socket_syslogv(int priority
, const char* format
, va_list list
)
512 // lazily create socket and connection to syslogd
513 if ( sLogSocket
== -1 ) {
514 sLogSocket
= ::socket(AF_UNIX
, SOCK_DGRAM
, 0);
515 if (sLogSocket
== -1)
516 return; // cannot log
517 ::fcntl(sLogSocket
, F_SETFD
, 1);
519 struct sockaddr_un addr
;
520 addr
.sun_family
= AF_UNIX
;
521 strncpy(addr
.sun_path
, _PATH_LOG
, sizeof(addr
.sun_path
));
522 if ( ::connect(sLogSocket
, (struct sockaddr
*)&addr
, sizeof(addr
)) == -1 ) {
529 // format message to syslogd like: "<priority>Process[pid]: message"
530 _SIMPLE_STRING buf
= _simple_salloc();
533 if ( _simple_sprintf(buf
, "<%d>%s[%d]: ", LOG_USER
|LOG_NOTICE
, sExecShortName
, getpid()) == 0 ) {
534 if ( _simple_vsprintf(buf
, format
, list
) == 0 ) {
535 const char* p
= _simple_string(buf
);
536 ::__sendto(sLogSocket
, p
, strlen(p
), 0, NULL
, 0);
544 void vlog(const char* format
, va_list list
)
546 #if __IPHONE_OS_VERSION_MIN_REQUIRED && !TARGET_OS_SIMULATOR
547 // <rdar://problem/25965832> log to console when running iOS app from Xcode
548 if ( !sLogToFile
&& !sForceStderr
&& useSyslog() )
550 if ( !sLogToFile
&& useSyslog() )
552 socket_syslogv(LOG_ERR
, format
, list
);
554 _simple_vdprintf(sLogfile
, format
, list
);
558 void log(const char* format
, ...)
561 va_start(list
, format
);
567 void vwarn(const char* format
, va_list list
)
569 _simple_dprintf(sLogfile
, "dyld: warning, ");
570 _simple_vdprintf(sLogfile
, format
, list
);
573 void warn(const char* format
, ...)
576 va_start(list
, format
);
582 extern void vlog(const char* format
, va_list list
);
583 #endif // !TARGET_OS_SIMULATOR
586 #pragma clang diagnostic push
587 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
588 // <rdar://problem/8867781> control access to sAllImages through a lock
589 // because global dyld lock is not held during initialization phase of dlopen()
590 // <rdar://problem/16145518> Use OSSpinLockLock to allow yielding
591 static OSSpinLock sAllImagesLock
= 0;
593 static void allImagesLock()
595 OSSpinLockLock(&sAllImagesLock
);
598 static void allImagesUnlock()
600 OSSpinLockUnlock(&sAllImagesLock
);
602 #pragma clang diagnostic pop
605 // utility class to assure files are closed when an exception is thrown
608 FileOpener(const char* path
);
610 int getFileDescriptor() { return fd
; }
615 FileOpener::FileOpener(const char* path
)
618 fd
= my_open(path
, O_RDONLY
, 0);
621 FileOpener::~FileOpener()
628 static void registerDOFs(const std::vector
<ImageLoader::DOFInfo
>& dofs
)
630 const size_t dofSectionCount
= dofs
.size();
631 if ( !sEnv
.DYLD_DISABLE_DOFS
&& (dofSectionCount
!= 0) ) {
632 int fd
= open("/dev/" DTRACEMNR_HELPER
, O_RDWR
);
634 //dyld::warn("can't open /dev/" DTRACEMNR_HELPER " to register dtrace DOF sections\n");
637 // allocate a buffer on the stack for the variable length dof_ioctl_data_t type
638 uint8_t buffer
[sizeof(dof_ioctl_data_t
) + dofSectionCount
*sizeof(dof_helper_t
)];
639 dof_ioctl_data_t
* ioctlData
= (dof_ioctl_data_t
*)buffer
;
641 // fill in buffer with one dof_helper_t per DOF section
642 ioctlData
->dofiod_count
= dofSectionCount
;
643 for (unsigned int i
=0; i
< dofSectionCount
; ++i
) {
644 strlcpy(ioctlData
->dofiod_helpers
[i
].dofhp_mod
, dofs
[i
].imageShortName
, DTRACE_MODNAMELEN
);
645 ioctlData
->dofiod_helpers
[i
].dofhp_dof
= (uintptr_t)(dofs
[i
].dof
);
646 ioctlData
->dofiod_helpers
[i
].dofhp_addr
= (uintptr_t)(dofs
[i
].dof
);
649 // tell kernel about all DOF sections en mas
650 // pass pointer to ioctlData because ioctl() only copies a fixed size amount of data into kernel
651 user_addr_t val
= (user_addr_t
)(unsigned long)ioctlData
;
652 if ( ioctl(fd
, DTRACEHIOC_ADDDOF
, &val
) != -1 ) {
653 // kernel returns a unique identifier for each section in the dofiod_helpers[].dofhp_dof field.
654 for (unsigned int i
=0; i
< dofSectionCount
; ++i
) {
656 info
.mh
= dofs
[i
].imageHeader
;
657 info
.registrationID
= (int)(ioctlData
->dofiod_helpers
[i
].dofhp_dof
);
658 sImageFilesNeedingDOFUnregistration
.push_back(info
);
659 if ( gLinkContext
.verboseDOF
) {
660 dyld::log("dyld: registering DOF section %p in %s with dtrace, ID=0x%08X\n",
661 dofs
[i
].dof
, dofs
[i
].imageShortName
, info
.registrationID
);
666 //dyld::log( "dyld: ioctl to register dtrace DOF section failed\n");
673 static void unregisterDOF(int registrationID
)
675 int fd
= open("/dev/" DTRACEMNR_HELPER
, O_RDWR
);
677 dyld::warn("can't open /dev/" DTRACEMNR_HELPER
" to unregister dtrace DOF section\n");
680 ioctl(fd
, DTRACEHIOC_REMOVE
, registrationID
);
682 if ( gLinkContext
.verboseInit
)
683 dyld::warn("unregistering DOF section ID=0x%08X with dtrace\n", registrationID
);
689 // _dyld_register_func_for_add_image() is implemented as part of the general image state change notification
690 // Returns true if we did call add image callbacks on this image
692 static bool notifyAddImageCallbacks(ImageLoader
* image
)
694 // use guard so that we cannot notify about the same image twice
695 if ( ! image
->addFuncNotified() ) {
696 for (std::vector
<ImageCallback
>::iterator it
=sAddImageCallbacks
.begin(); it
!= sAddImageCallbacks
.end(); it
++) {
697 dyld3::ScopedTimer
timer(DBG_DYLD_TIMING_FUNC_FOR_ADD_IMAGE
, (uint64_t)image
->machHeader(), (uint64_t)(*it
), 0);
698 (*it
)(image
->machHeader(), image
->getSlide());
700 for (LoadImageCallback func
: sAddLoadImageCallbacks
) {
701 dyld3::ScopedTimer
timer(DBG_DYLD_TIMING_FUNC_FOR_ADD_IMAGE
, (uint64_t)image
->machHeader(), (uint64_t)(*func
), 0);
702 (*func
)(image
->machHeader(), image
->getPath(), !image
->neverUnload());
704 image
->setAddFuncNotified();
712 // notify gdb about these new images
713 static const char* updateAllImages(enum dyld_image_states state
, uint32_t infoCount
, const struct dyld_image_info info
[])
715 // <rdar://problem/8812589> don't add images without paths to all-image-info-list
716 if ( info
[0].imageFilePath
!= NULL
)
717 addImagesToAllImages(infoCount
, info
);
722 static StateHandlers
* stateToHandlers(dyld_image_states state
, void* handlersArray
[7][3])
725 case dyld_image_state_mapped
:
726 return reinterpret_cast<StateHandlers
*>(&handlersArray
[0]);
728 case dyld_image_state_dependents_mapped
:
729 return reinterpret_cast<StateHandlers
*>(&handlersArray
[1]);
731 case dyld_image_state_rebased
:
732 return reinterpret_cast<StateHandlers
*>(&handlersArray
[2]);
734 case dyld_image_state_bound
:
735 return reinterpret_cast<StateHandlers
*>(&handlersArray
[3]);
737 case dyld_image_state_dependents_initialized
:
738 return reinterpret_cast<StateHandlers
*>(&handlersArray
[4]);
740 case dyld_image_state_initialized
:
741 return reinterpret_cast<StateHandlers
*>(&handlersArray
[5]);
743 case dyld_image_state_terminated
:
744 return reinterpret_cast<StateHandlers
*>(&handlersArray
[6]);
749 #if SUPPORT_ACCELERATE_TABLES
750 static dyld_image_state_change_handler
getPreInitNotifyHandler(unsigned index
)
752 std::vector
<dyld_image_state_change_handler
>* handlers
= stateToHandlers(dyld_image_state_dependents_initialized
, sSingleHandlers
);
753 if ( index
>= handlers
->size() )
755 return (*handlers
)[index
];
758 static dyld_image_state_change_handler
getBoundBatchHandler(unsigned index
)
760 std::vector
<dyld_image_state_change_handler
>* handlers
= stateToHandlers(dyld_image_state_bound
, sBatchHandlers
);
761 if ( index
>= handlers
->size() )
763 return (*handlers
)[index
];
766 static void notifySingleFromCache(dyld_image_states state
, const mach_header
* mh
, const char* path
)
768 //dyld::log("notifySingle(state=%d, image=%s)\n", state, image->getPath());
769 std::vector
<dyld_image_state_change_handler
>* handlers
= stateToHandlers(state
, sSingleHandlers
);
770 if ( handlers
!= NULL
) {
771 dyld_image_info info
;
772 info
.imageLoadAddress
= mh
;
773 info
.imageFilePath
= path
;
774 info
.imageFileModDate
= 0;
775 for (dyld_image_state_change_handler handler
: *handlers
) {
776 const char* result
= (*handler
)(state
, 1, &info
);
777 if ( (result
!= NULL
) && (state
== dyld_image_state_mapped
) ) {
778 //fprintf(stderr, " image rejected by handler=%p\n", *it);
779 // make copy of thrown string so that later catch clauses can free it
780 const char* str
= strdup(result
);
785 if ( (state
== dyld_image_state_dependents_initialized
) && (sNotifyObjCInit
!= NULL
) && (mh
->flags
& MH_HAS_OBJC
) ) {
786 dyld3::ScopedTimer
timer(DBG_DYLD_TIMING_OBJC_INIT
, (uint64_t)mh
, 0, 0);
787 (*sNotifyObjCInit
)(path
, mh
);
792 #if !TARGET_OS_SIMULATOR
793 static void sendMessage(unsigned portSlot
, mach_msg_id_t msgId
, mach_msg_size_t sendSize
, mach_msg_header_t
* buffer
, mach_msg_size_t bufferSize
) {
794 // Allocate a port to listen on in this monitoring task
795 mach_port_t sendPort
= dyld::gProcessInfo
->notifyPorts
[portSlot
];
796 if (sendPort
== MACH_PORT_NULL
) {
799 mach_port_t replyPort
= MACH_PORT_NULL
;
800 mach_port_options_t options
= { .flags
= MPO_CONTEXT_AS_GUARD
| MPO_STRICT
,
802 kern_return_t kr
= mach_port_construct(mach_task_self(), &options
, (mach_port_context_t
)&replyPort
, &replyPort
);
803 if (kr
!= KERN_SUCCESS
) {
806 // Assemble a message
807 mach_msg_header_t
* h
= buffer
;
808 h
->msgh_bits
= MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND
,MACH_MSG_TYPE_MAKE_SEND_ONCE
);
810 h
->msgh_local_port
= replyPort
;
811 h
->msgh_remote_port
= sendPort
;
812 h
->msgh_reserved
= 0;
813 h
->msgh_size
= sendSize
;
814 kr
= mach_msg(h
, MACH_SEND_MSG
| MACH_RCV_MSG
, h
->msgh_size
, bufferSize
, replyPort
, 0, MACH_PORT_NULL
);
816 if ( kr
== MACH_SEND_INVALID_DEST
) {
817 if (OSAtomicCompareAndSwap32(sendPort
, 0, (volatile int32_t*)&dyld::gProcessInfo
->notifyPorts
[portSlot
])) {
818 mach_port_deallocate(mach_task_self(), sendPort
);
821 mach_port_destruct(mach_task_self(), replyPort
, 0, (mach_port_context_t
)&replyPort
);
824 static void notifyMonitoringDyld(bool unloading
, unsigned imageCount
, const struct mach_header
* loadAddresses
[],
825 const char* imagePaths
[])
827 dyld3::ScopedTimer(DBG_DYLD_REMOTE_IMAGE_NOTIFIER
, 0, 0, 0);
828 for (int slot
=0; slot
< DYLD_MAX_PROCESS_INFO_NOTIFY_COUNT
; ++slot
) {
829 if ( dyld::gProcessInfo
->notifyPorts
[slot
] == 0) continue;
830 unsigned entriesSize
= imageCount
*sizeof(dyld_process_info_image_entry
);
831 unsigned pathsSize
= 0;
832 for (unsigned j
=0; j
< imageCount
; ++j
) {
833 pathsSize
+= (strlen(imagePaths
[j
]) + 1);
835 unsigned totalSize
= (sizeof(dyld_process_info_notify_header
) + entriesSize
+ pathsSize
+ 127) & -128; // align
836 if ( totalSize
> DYLD_PROCESS_INFO_NOTIFY_MAX_BUFFER_SIZE
) {
837 // Putting all image paths into one message would make buffer too big.
838 // Instead split into two messages. Recurse as needed until paths fit in buffer.
839 unsigned imageHalfCount
= imageCount
/2;
840 notifyMonitoringDyld(unloading
, imageHalfCount
, loadAddresses
, imagePaths
);
841 notifyMonitoringDyld(unloading
, imageCount
- imageHalfCount
, &loadAddresses
[imageHalfCount
], &imagePaths
[imageHalfCount
]);
844 uint8_t buffer
[totalSize
+ MAX_TRAILER_SIZE
];
845 dyld_process_info_notify_header
* header
= (dyld_process_info_notify_header
*)buffer
;
847 header
->imageCount
= imageCount
;
848 header
->imagesOffset
= sizeof(dyld_process_info_notify_header
);
849 header
->stringsOffset
= sizeof(dyld_process_info_notify_header
) + entriesSize
;
850 header
->timestamp
= dyld::gProcessInfo
->infoArrayChangeTimestamp
;
851 dyld_process_info_image_entry
* entries
= (dyld_process_info_image_entry
*)&buffer
[header
->imagesOffset
];
852 char* const pathPoolStart
= (char*)&buffer
[header
->stringsOffset
];
853 char* pathPool
= pathPoolStart
;
854 for (unsigned j
=0; j
< imageCount
; ++j
) {
855 strcpy(pathPool
, imagePaths
[j
]);
856 uint32_t len
= (uint32_t)strlen(pathPool
);
857 bzero(entries
->uuid
, 16);
858 dyld3::MachOFile
* mf
= (dyld3::MachOFile
*)loadAddresses
[j
];
859 mf
->getUuid(entries
->uuid
);
860 entries
->loadAddress
= (uint64_t)loadAddresses
[j
];
861 entries
->pathStringOffset
= (uint32_t)(pathPool
- pathPoolStart
);
862 entries
->pathLength
= len
;
863 pathPool
+= (len
+1);
867 sendMessage(slot
, DYLD_PROCESS_INFO_NOTIFY_UNLOAD_ID
, totalSize
, (mach_msg_header_t
*)buffer
, totalSize
+MAX_TRAILER_SIZE
);
869 sendMessage(slot
, DYLD_PROCESS_INFO_NOTIFY_LOAD_ID
, totalSize
, (mach_msg_header_t
*)buffer
, totalSize
+MAX_TRAILER_SIZE
);
874 static void notifyMonitoringDyldMain()
876 dyld3::ScopedTimer(DBG_DYLD_REMOTE_IMAGE_NOTIFIER
, 0, 0, 0);
877 for (int slot
=0; slot
< DYLD_MAX_PROCESS_INFO_NOTIFY_COUNT
; ++slot
) {
878 if ( dyld::gProcessInfo
->notifyPorts
[slot
] == 0) continue;
879 uint8_t buffer
[sizeof(mach_msg_header_t
) + MAX_TRAILER_SIZE
];
880 sendMessage(slot
, DYLD_PROCESS_INFO_NOTIFY_MAIN_ID
, sizeof(mach_msg_header_t
), (mach_msg_header_t
*)buffer
, sizeof(mach_msg_header_t
) + MAX_TRAILER_SIZE
);
884 extern void notifyMonitoringDyldMain() VIS_HIDDEN
;
885 extern void notifyMonitoringDyld(bool unloading
, unsigned imageCount
, const struct mach_header
* loadAddresses
[],
886 const char* imagePaths
[]) VIS_HIDDEN
;
889 void notifyKernel(const ImageLoader
& image
, bool loading
) {
890 uint32_t baseCode
= loading
? DBG_DYLD_UUID_MAP_A
: DBG_DYLD_UUID_UNMAP_A
;
893 if ( image
.inSharedCache() ) {
894 dyld3::kdebug_trace_dyld_image(baseCode
, image
.getInstallPath(), (const uuid_t
*)&uuid
, {0}, {{ 0, 0 }}, image
.machHeader());
896 fsid_t fsid
= {{0, 0}};
897 fsobj_id_t fsobj
= {0};
898 ino_t inode
= image
.getInode();
899 fsobj
.fid_objno
= (uint32_t)inode
;
900 fsobj
.fid_generation
= (uint32_t)(inode
>>32);
901 fsid
.val
[0] = image
.getDevice();
902 dyld3::kdebug_trace_dyld_image(baseCode
, image
.getPath(), (const uuid_t
*)&uuid
, fsobj
, fsid
, image
.machHeader());
906 static void notifySingle(dyld_image_states state
, const ImageLoader
* image
, ImageLoader::InitializerTimingList
* timingInfo
)
908 //dyld::log("notifySingle(state=%d, image=%s)\n", state, image->getPath());
909 std::vector
<dyld_image_state_change_handler
>* handlers
= stateToHandlers(state
, sSingleHandlers
);
910 if ( handlers
!= NULL
) {
911 dyld_image_info info
;
912 info
.imageLoadAddress
= image
->machHeader();
913 info
.imageFilePath
= image
->getRealPath();
914 info
.imageFileModDate
= image
->lastModified();
915 for (std::vector
<dyld_image_state_change_handler
>::iterator it
= handlers
->begin(); it
!= handlers
->end(); ++it
) {
916 const char* result
= (*it
)(state
, 1, &info
);
917 if ( (result
!= NULL
) && (state
== dyld_image_state_mapped
) ) {
918 //fprintf(stderr, " image rejected by handler=%p\n", *it);
919 // make copy of thrown string so that later catch clauses can free it
920 const char* str
= strdup(result
);
925 if ( state
== dyld_image_state_mapped
) {
926 // <rdar://problem/7008875> Save load addr + UUID for images from outside the shared cache
927 if ( !image
->inSharedCache() ) {
929 if ( image
->getUUID(info
.imageUUID
) ) {
930 info
.imageLoadAddress
= image
->machHeader();
931 addNonSharedCacheImageUUID(info
);
935 if ( (state
== dyld_image_state_dependents_initialized
) && (sNotifyObjCInit
!= NULL
) && image
->notifyObjC() ) {
936 uint64_t t0
= mach_absolute_time();
937 dyld3::ScopedTimer
timer(DBG_DYLD_TIMING_OBJC_INIT
, (uint64_t)image
->machHeader(), 0, 0);
938 (*sNotifyObjCInit
)(image
->getRealPath(), image
->machHeader());
939 uint64_t t1
= mach_absolute_time();
940 uint64_t t2
= mach_absolute_time();
941 uint64_t timeInObjC
= t1
-t0
;
942 uint64_t emptyTime
= (t2
-t1
)*100;
943 if ( (timeInObjC
> emptyTime
) && (timingInfo
!= NULL
) ) {
944 timingInfo
->addTime(image
->getShortName(), timeInObjC
);
947 // mach message csdlc about dynamically unloaded images
948 if ( image
->addFuncNotified() && (state
== dyld_image_state_terminated
) ) {
949 notifyKernel(*image
, false);
950 const struct mach_header
* loadAddress
[] = { image
->machHeader() };
951 const char* loadPath
[] = { image
->getPath() };
952 notifyMonitoringDyld(true, 1, loadAddress
, loadPath
);
958 // Normally, dyld_all_image_infos is only updated in batches after an entire
959 // graph is loaded. But if there is an error loading the initial set of
960 // dylibs needed by the main executable, dyld_all_image_infos is not yet set
961 // up, leading to usually brief crash logs.
963 // This function manually adds the images loaded so far to dyld::gProcessInfo.
964 // It should only be called before terminating.
968 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); ++it
) {
969 dyld_image_info info
;
970 ImageLoader
* image
= *it
;
971 info
.imageLoadAddress
= image
->machHeader();
972 info
.imageFilePath
= image
->getRealPath();
973 info
.imageFileModDate
= image
->lastModified();
974 // add to all_image_infos if not already there
976 int existingCount
= dyld::gProcessInfo
->infoArrayCount
;
977 const dyld_image_info
* existing
= dyld::gProcessInfo
->infoArray
;
978 if ( existing
!= NULL
) {
979 for (int i
=0; i
< existingCount
; ++i
) {
980 if ( existing
[i
].imageLoadAddress
== info
.imageLoadAddress
) {
981 //dyld::log("not adding %s\n", info.imageFilePath);
988 //dyld::log("adding %s\n", info.imageFilePath);
989 addImagesToAllImages(1, &info
);
995 static int imageSorter(const void* l
, const void* r
)
997 const ImageLoader
* left
= *((ImageLoader
**)l
);
998 const ImageLoader
* right
= *((ImageLoader
**)r
);
999 return left
->compare(right
);
1002 static void notifyBatchPartial(dyld_image_states state
, bool orLater
, dyld_image_state_change_handler onlyHandler
, bool preflightOnly
, bool onlyObjCMappedNotification
)
1004 std::vector
<dyld_image_state_change_handler
>* handlers
= stateToHandlers(state
, sBatchHandlers
);
1005 if ( (handlers
!= NULL
) || ((state
== dyld_image_state_bound
) && (sNotifyObjCMapped
!= NULL
)) ) {
1006 // don't use a vector because it will use malloc/free and we want notifcation to be low cost
1008 dyld_image_info infos
[allImagesCount()+1];
1009 ImageLoader
* images
[allImagesCount()+1];
1010 ImageLoader
** end
= images
;
1011 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
1012 dyld_image_states imageState
= (*it
)->getState();
1013 if ( (imageState
== state
) || (orLater
&& (imageState
> state
)) )
1016 if ( sBundleBeingLoaded
!= NULL
) {
1017 dyld_image_states imageState
= sBundleBeingLoaded
->getState();
1018 if ( (imageState
== state
) || (orLater
&& (imageState
> state
)) )
1019 *end
++ = sBundleBeingLoaded
;
1021 const char* dontLoadReason
= NULL
;
1022 uint32_t imageCount
= (uint32_t)(end
-images
);
1023 if ( imageCount
!= 0 ) {
1025 qsort(images
, imageCount
, sizeof(ImageLoader
*), &imageSorter
);
1027 const mach_header
* mhs
[imageCount
];
1028 const char* paths
[imageCount
];
1029 uint32_t bulkNotifyImageCount
= 0;
1032 for (unsigned int i
=0; i
< imageCount
; ++i
) {
1033 dyld_image_info
* p
= &infos
[i
];
1034 ImageLoader
* image
= images
[i
];
1035 //dyld::log(" state=%d, name=%s\n", state, image->getPath());
1036 p
->imageLoadAddress
= image
->machHeader();
1037 p
->imageFilePath
= image
->getRealPath();
1038 p
->imageFileModDate
= image
->lastModified();
1039 // get these registered with the kernel as early as possible
1040 if ( state
== dyld_image_state_dependents_mapped
)
1041 notifyKernel(*image
, true);
1042 // special case for add_image hook
1043 if ( state
== dyld_image_state_bound
) {
1044 if ( notifyAddImageCallbacks(image
) ) {
1045 // Add this to the list of images to bulk notify
1046 mhs
[bulkNotifyImageCount
] = infos
[i
].imageLoadAddress
;
1047 paths
[bulkNotifyImageCount
] = infos
[i
].imageFilePath
;
1048 ++bulkNotifyImageCount
;
1053 if ( (state
== dyld_image_state_bound
) && !sAddBulkLoadImageCallbacks
.empty() && (bulkNotifyImageCount
!= 0) ) {
1054 for (LoadImageBulkCallback func
: sAddBulkLoadImageCallbacks
) {
1055 dyld3::ScopedTimer
timer(DBG_DYLD_TIMING_FUNC_FOR_ADD_IMAGE
, (uint64_t)mhs
[0], (uint64_t)func
, 0);
1056 (*func
)(bulkNotifyImageCount
, mhs
, paths
);
1060 #if SUPPORT_ACCELERATE_TABLES
1061 if ( sAllCacheImagesProxy
!= NULL
) {
1062 unsigned cacheCount
= sAllCacheImagesProxy
->appendImagesToNotify(state
, orLater
, &infos
[imageCount
]);
1063 // support _dyld_register_func_for_add_image()
1064 if ( state
== dyld_image_state_bound
) {
1065 for (ImageCallback callback
: sAddImageCallbacks
) {
1066 for (unsigned i
=0; i
< cacheCount
; ++i
) {
1067 dyld3::ScopedTimer
timer(DBG_DYLD_TIMING_FUNC_FOR_ADD_IMAGE
, (uint64_t)infos
[imageCount
+i
].imageLoadAddress
, (uint64_t)(*callback
), 0);
1068 (*callback
)(infos
[imageCount
+i
].imageLoadAddress
, sSharedCacheLoadInfo
.slide
);
1071 for (LoadImageCallback func
: sAddLoadImageCallbacks
) {
1072 for (unsigned i
=0; i
< cacheCount
; ++i
) {
1073 dyld3::ScopedTimer
timer(DBG_DYLD_TIMING_FUNC_FOR_ADD_IMAGE
, (uint64_t)infos
[imageCount
+i
].imageLoadAddress
, (uint64_t)(*func
), 0);
1074 (*func
)(infos
[imageCount
+i
].imageLoadAddress
, infos
[imageCount
+i
].imageFilePath
, false);
1077 if ( !sAddBulkLoadImageCallbacks
.empty() ) {
1078 const mach_header
* bulk_mhs
[cacheCount
];
1079 const char* bulk_paths
[cacheCount
];
1080 for (int i
=0; i
< cacheCount
; ++i
) {
1081 bulk_mhs
[i
] = infos
[imageCount
+i
].imageLoadAddress
;
1082 bulk_paths
[i
] = infos
[imageCount
+i
].imageFilePath
;
1084 for (LoadImageBulkCallback func
: sAddBulkLoadImageCallbacks
) {
1085 dyld3::ScopedTimer
timer(DBG_DYLD_TIMING_FUNC_FOR_ADD_IMAGE
, (uint64_t)bulk_mhs
[0], (uint64_t)func
, 0);
1086 (*func
)(cacheCount
, bulk_mhs
, bulk_paths
);
1090 imageCount
+= cacheCount
;
1093 if ( imageCount
!= 0 ) {
1094 if ( !onlyObjCMappedNotification
) {
1095 if ( onlyHandler
!= NULL
) {
1096 const char* result
= NULL
;
1097 if ( result
== NULL
) {
1098 result
= (*onlyHandler
)(state
, imageCount
, infos
);
1100 if ( (result
!= NULL
) && (state
== dyld_image_state_dependents_mapped
) ) {
1101 //fprintf(stderr, " images rejected by handler=%p\n", onlyHandler);
1102 // make copy of thrown string so that later catch clauses can free it
1103 dontLoadReason
= strdup(result
);
1107 // call each handler with whole array
1108 if ( handlers
!= NULL
) {
1109 for (std::vector
<dyld_image_state_change_handler
>::iterator it
= handlers
->begin(); it
!= handlers
->end(); ++it
) {
1110 const char* result
= (*it
)(state
, imageCount
, infos
);
1111 if ( (result
!= NULL
) && (state
== dyld_image_state_dependents_mapped
) ) {
1112 //fprintf(stderr, " images rejected by handler=%p\n", *it);
1113 // make copy of thrown string so that later catch clauses can free it
1114 dontLoadReason
= strdup(result
);
1121 // tell objc about new images
1122 if ( (onlyHandler
== NULL
) && ((state
== dyld_image_state_bound
) || (orLater
&& (dyld_image_state_bound
> state
))) && (sNotifyObjCMapped
!= NULL
) ) {
1123 const char* paths
[imageCount
];
1124 const mach_header
* mhs
[imageCount
];
1125 unsigned objcImageCount
= 0;
1126 for (int i
=0; i
< imageCount
; ++i
) {
1127 ImageLoader
* image
= findImageByMachHeader(infos
[i
].imageLoadAddress
);
1128 bool hasObjC
= false;
1129 if ( image
!= NULL
) {
1130 if ( image
->objCMappedNotified() )
1132 hasObjC
= image
->notifyObjC();
1134 #if SUPPORT_ACCELERATE_TABLES
1135 else if ( sAllCacheImagesProxy
!= NULL
) {
1136 const mach_header
* mh
;
1139 if ( sAllCacheImagesProxy
->addressInCache(infos
[i
].imageLoadAddress
, &mh
, &path
, &index
) ) {
1140 hasObjC
= (mh
->flags
& MH_HAS_OBJC
);
1145 paths
[objcImageCount
] = infos
[i
].imageFilePath
;
1146 mhs
[objcImageCount
] = infos
[i
].imageLoadAddress
;
1148 if ( image
!= NULL
)
1149 image
->setObjCMappedNotified();
1152 if ( objcImageCount
!= 0 ) {
1153 dyld3::ScopedTimer
timer(DBG_DYLD_TIMING_OBJC_MAP
, 0, 0, 0);
1154 uint64_t t0
= mach_absolute_time();
1155 (*sNotifyObjCMapped
)(objcImageCount
, paths
, mhs
);
1156 uint64_t t1
= mach_absolute_time();
1157 ImageLoader::fgTotalObjCSetupTime
+= (t1
-t0
);
1162 if ( dontLoadReason
!= NULL
)
1163 throw dontLoadReason
;
1164 if ( !preflightOnly
&& (state
== dyld_image_state_dependents_mapped
) ) {
1165 const struct mach_header
* loadAddresses
[imageCount
];
1166 const char* loadPaths
[imageCount
];
1167 for(uint32_t i
= 0; i
<imageCount
; ++i
) {
1168 loadAddresses
[i
] = infos
[i
].imageLoadAddress
;
1169 loadPaths
[i
] = infos
[i
].imageFilePath
;
1171 notifyMonitoringDyld(false, imageCount
, loadAddresses
, loadPaths
);
1176 static void notifyBatch(dyld_image_states state
, bool preflightOnly
)
1178 notifyBatchPartial(state
, false, NULL
, preflightOnly
, false);
1181 #if __MAC_OS_X_VERSION_MIN_REQUIRED
1183 void coresymbolication_load_notifier(void* connection
, uint64_t timestamp
, const char* path
, const struct mach_header
* mh
)
1185 const struct mach_header
* loadAddress
[] = { mh
};
1186 const char* loadPath
[] = { path
};
1187 notifyMonitoringDyld(false, 1, loadAddress
, loadPath
);
1191 void coresymbolication_unload_notifier(void* connection
, uint64_t timestamp
, const char* path
, const struct mach_header
* mh
)
1193 const struct mach_header
* loadAddress
= { mh
};
1194 const char* loadPath
= { path
};
1195 notifyMonitoringDyld(true, 1, &loadAddress
, &loadPath
);
1199 kern_return_t
legacy_task_register_dyld_image_infos(task_t task
, dyld_kernel_image_info_array_t dyld_images
,
1200 mach_msg_type_number_t dyld_imagesCnt
)
1202 return KERN_SUCCESS
;
1206 kern_return_t
legacy_task_unregister_dyld_image_infos(task_t task
, dyld_kernel_image_info_array_t dyld_images
,
1207 mach_msg_type_number_t dyld_imagesCnt
)
1209 return KERN_SUCCESS
;
1213 kern_return_t
legacy_task_get_dyld_image_infos(task_inspect_t task
, dyld_kernel_image_info_array_t
*dyld_images
,
1214 mach_msg_type_number_t
*dyld_imagesCnt
)
1216 return KERN_SUCCESS
;
1220 kern_return_t
legacy_task_register_dyld_shared_cache_image_info(task_t task
, dyld_kernel_image_info_t dyld_cache_image
,
1221 boolean_t no_cache
, boolean_t private_cache
)
1223 return KERN_SUCCESS
;
1227 kern_return_t
legacy_task_register_dyld_set_dyld_state(task_t task
, uint8_t dyld_state
)
1229 return KERN_SUCCESS
;
1233 kern_return_t
legacy_task_register_dyld_get_process_state(task_t task
, dyld_kernel_process_info_t
*dyld_process_state
)
1235 return KERN_SUCCESS
;
1239 // In order for register_func_for_add_image() callbacks to to be called bottom up,
1240 // we need to maintain a list of root images. The main executable is usally the
1241 // first root. Any images dynamically added are also roots (unless already loaded).
1242 // If DYLD_INSERT_LIBRARIES is used, those libraries are first.
1243 static void addRootImage(ImageLoader
* image
)
1245 //dyld::log("addRootImage(%p, %s)\n", image, image->getPath());
1246 // add to list of roots
1247 sImageRoots
.push_back(image
);
1251 static void clearAllDepths()
1253 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++)
1254 (*it
)->clearDepth();
1257 static void printAllDepths()
1259 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++)
1260 dyld::log("%03d %s\n", (*it
)->getDepth(), (*it
)->getShortName());
1264 static unsigned int imageCount()
1267 unsigned int result
= (unsigned int)sAllImages
.size();
1273 static void setNewProgramVars(const ProgramVars
& newVars
)
1275 // make a copy of the pointers to program variables
1276 gLinkContext
.programVars
= newVars
;
1278 // now set each program global to their initial value
1279 *gLinkContext
.programVars
.NXArgcPtr
= gLinkContext
.argc
;
1280 *gLinkContext
.programVars
.NXArgvPtr
= gLinkContext
.argv
;
1281 *gLinkContext
.programVars
.environPtr
= gLinkContext
.envp
;
1282 *gLinkContext
.programVars
.__prognamePtr
= gLinkContext
.progname
;
1285 #if SUPPORT_OLD_CRT_INITIALIZATION
1286 static void setRunInitialzersOldWay()
1288 gRunInitializersOldWay
= true;
1292 static bool sandboxBlocked(const char* path
, const char* kind
)
1294 #if TARGET_OS_SIMULATOR
1295 // sandbox calls not yet supported in simulator runtime
1298 sandbox_filter_type filter
= (sandbox_filter_type
)(SANDBOX_FILTER_PATH
| SANDBOX_CHECK_NO_REPORT
);
1299 return ( sandbox_check(getpid(), kind
, filter
, path
) > 0 );
1303 bool sandboxBlockedMmap(const char* path
)
1305 return sandboxBlocked(path
, "file-map-executable");
1308 bool sandboxBlockedOpen(const char* path
)
1310 return sandboxBlocked(path
, "file-read-data");
1313 bool sandboxBlockedStat(const char* path
)
1315 return sandboxBlocked(path
, "file-read-metadata");
1319 static void addDynamicReference(ImageLoader
* from
, ImageLoader
* to
) {
1320 // don't add dynamic reference if target is in the shared cache (since it can't be unloaded)
1321 if ( to
->inSharedCache() )
1324 // don't add dynamic reference if there already is a static one
1325 if ( from
->dependsOn(to
) )
1328 #pragma clang diagnostic push
1329 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
1330 // don't add if this combination already exists
1331 OSSpinLockLock(&sDynamicReferencesLock
);
1332 for (std::vector
<ImageLoader::DynamicReference
>::iterator it
=sDynamicReferences
.begin(); it
!= sDynamicReferences
.end(); ++it
) {
1333 if ( (it
->from
== from
) && (it
->to
== to
) ) {
1334 OSSpinLockUnlock(&sDynamicReferencesLock
);
1339 //dyld::log("addDynamicReference(%s, %s\n", from->getShortName(), to->getShortName());
1340 ImageLoader::DynamicReference t
;
1343 sDynamicReferences
.push_back(t
);
1344 OSSpinLockUnlock(&sDynamicReferencesLock
);
1345 #pragma clang diagnostic pop
1348 static void addImage(ImageLoader
* image
)
1350 // add to master list
1352 sAllImages
.push_back(image
);
1355 // update mapped ranges
1356 uintptr_t lastSegStart
= 0;
1357 uintptr_t lastSegEnd
= 0;
1358 for(unsigned int i
=0, e
=image
->segmentCount(); i
< e
; ++i
) {
1359 if ( image
->segUnaccessible(i
) )
1361 uintptr_t start
= image
->segActualLoadAddress(i
);
1362 uintptr_t end
= image
->segActualEndAddress(i
);
1363 if ( start
== lastSegEnd
) {
1364 // two segments are contiguous, just record combined segments
1368 // non-contiguous segments, record last (if any)
1369 if ( lastSegEnd
!= 0 )
1370 addMappedRange(image
, lastSegStart
, lastSegEnd
);
1371 lastSegStart
= start
;
1375 if ( lastSegEnd
!= 0 )
1376 addMappedRange(image
, lastSegStart
, lastSegEnd
);
1379 if ( gLinkContext
.verboseLoading
|| (sEnv
.DYLD_PRINT_LIBRARIES_POST_LAUNCH
&& (sMainExecutable
!=NULL
) && sMainExecutable
->isLinked()) ) {
1380 const char *imagePath
= image
->getPath();
1382 if ( image
->getUUID(imageUUID
) ) {
1383 uuid_string_t imageUUIDStr
;
1384 uuid_unparse_upper(imageUUID
, imageUUIDStr
);
1385 dyld::log("dyld: loaded: <%s> %s\n", imageUUIDStr
, imagePath
);
1388 dyld::log("dyld: loaded: %s\n", imagePath
);
1395 // Helper for std::remove_if
1397 class RefUsesImage
{
1399 RefUsesImage(ImageLoader
* image
) : _image(image
) {}
1400 bool operator()(const ImageLoader::DynamicReference
& ref
) const {
1401 return ( (ref
.from
== _image
) || (ref
.to
== _image
) );
1404 ImageLoader
* _image
;
1409 void removeImage(ImageLoader
* image
)
1411 // if has dtrace DOF section, tell dtrace it is going away, then remove from sImageFilesNeedingDOFUnregistration
1412 for (std::vector
<RegisteredDOF
>::iterator it
=sImageFilesNeedingDOFUnregistration
.begin(); it
!= sImageFilesNeedingDOFUnregistration
.end(); ) {
1413 if ( it
->mh
== image
->machHeader() ) {
1414 unregisterDOF(it
->registrationID
);
1415 sImageFilesNeedingDOFUnregistration
.erase(it
);
1416 // don't increment iterator, the erase caused next element to be copied to where this iterator points
1423 // tell all registered remove image handlers about this
1424 // do this before removing image from internal data structures so that the callback can query dyld about the image
1425 if ( image
->getState() >= dyld_image_state_bound
) {
1426 sRemoveImageCallbacksInUse
= true; // This only runs inside dyld's global lock, so ok to use a global for the in-use flag.
1427 for (std::vector
<ImageCallback
>::iterator it
=sRemoveImageCallbacks
.begin(); it
!= sRemoveImageCallbacks
.end(); it
++) {
1428 dyld3::ScopedTimer
timer(DBG_DYLD_TIMING_FUNC_FOR_REMOVE_IMAGE
, (uint64_t)image
->machHeader(), (uint64_t)(*it
), 0);
1429 (*it
)(image
->machHeader(), image
->getSlide());
1431 sRemoveImageCallbacksInUse
= false;
1433 if ( sNotifyObjCUnmapped
!= NULL
&& image
->notifyObjC() )
1434 (*sNotifyObjCUnmapped
)(image
->getRealPath(), image
->machHeader());
1438 notifySingle(dyld_image_state_terminated
, image
, NULL
);
1440 // remove from mapped images table
1441 removedMappedRanges(image
);
1443 // remove from master list
1445 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
1446 if ( *it
== image
) {
1447 sAllImages
.erase(it
);
1453 #pragma clang diagnostic push
1454 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
1455 // remove from sDynamicReferences
1456 OSSpinLockLock(&sDynamicReferencesLock
);
1457 sDynamicReferences
.erase(std::remove_if(sDynamicReferences
.begin(), sDynamicReferences
.end(), RefUsesImage(image
)), sDynamicReferences
.end());
1458 OSSpinLockUnlock(&sDynamicReferencesLock
);
1459 #pragma clang diagnostic pop
1461 // flush find-by-address cache (do this after removed from master list, so there is no chance it can come back)
1462 if ( sLastImageByAddressCache
== image
)
1463 sLastImageByAddressCache
= NULL
;
1465 // if in root list, pull it out
1466 for (std::vector
<ImageLoader
*>::iterator it
=sImageRoots
.begin(); it
!= sImageRoots
.end(); it
++) {
1467 if ( *it
== image
) {
1468 sImageRoots
.erase(it
);
1474 if ( gLinkContext
.verboseLoading
|| (sEnv
.DYLD_PRINT_LIBRARIES_POST_LAUNCH
&& (sMainExecutable
!=NULL
) && sMainExecutable
->isLinked()) ) {
1475 const char *imagePath
= image
->getPath();
1477 if ( image
->getUUID(imageUUID
) ) {
1478 uuid_string_t imageUUIDStr
;
1479 uuid_unparse_upper(imageUUID
, imageUUIDStr
);
1480 dyld::log("dyld: unloaded: <%s> %s\n", imageUUIDStr
, imagePath
);
1483 dyld::log("dyld: unloaded: %s\n", imagePath
);
1487 // tell gdb, new way
1488 removeImageFromAllImages(image
->machHeader());
1492 void runImageStaticTerminators(ImageLoader
* image
)
1494 // if in termination list, pull it out and run terminator
1497 mightBeMore
= false;
1498 for (std::vector
<ImageLoader
*>::iterator it
=sImageFilesNeedingTermination
.begin(); it
!= sImageFilesNeedingTermination
.end(); it
++) {
1499 if ( *it
== image
) {
1500 sImageFilesNeedingTermination
.erase(it
);
1501 if (gLogAPIs
) dyld::log("dlclose(), running static terminators for %p %s\n", image
, image
->getShortName());
1502 image
->doTermination(gLinkContext
);
1507 } while ( mightBeMore
);
1510 static void terminationRecorder(ImageLoader
* image
)
1512 sImageFilesNeedingTermination
.push_back(image
);
1515 const char* getExecutablePath()
1520 static void runAllStaticTerminators(void* extra
)
1523 const size_t imageCount
= sImageFilesNeedingTermination
.size();
1524 for(size_t i
=imageCount
; i
> 0; --i
){
1525 ImageLoader
* image
= sImageFilesNeedingTermination
[i
-1];
1526 image
->doTermination(gLinkContext
);
1528 sImageFilesNeedingTermination
.clear();
1529 notifyBatch(dyld_image_state_terminated
, false);
1531 catch (const char* msg
) {
1536 void initializeMainExecutable()
1538 // record that we've reached this step
1539 gLinkContext
.startedInitializingMainExecutable
= true;
1541 // run initialzers for any inserted dylibs
1542 ImageLoader::InitializerTimingList initializerTimes
[allImagesCount()];
1543 initializerTimes
[0].count
= 0;
1544 const size_t rootCount
= sImageRoots
.size();
1545 if ( rootCount
> 1 ) {
1546 for(size_t i
=1; i
< rootCount
; ++i
) {
1547 sImageRoots
[i
]->runInitializers(gLinkContext
, initializerTimes
[0]);
1551 // run initializers for main executable and everything it brings up
1552 sMainExecutable
->runInitializers(gLinkContext
, initializerTimes
[0]);
1554 // register cxa_atexit() handler to run static terminators in all loaded images when this process exits
1555 if ( gLibSystemHelpers
!= NULL
)
1556 (*gLibSystemHelpers
->cxa_atexit
)(&runAllStaticTerminators
, NULL
, NULL
);
1558 // dump info if requested
1559 if ( sEnv
.DYLD_PRINT_STATISTICS
)
1560 ImageLoader::printStatistics((unsigned int)allImagesCount(), initializerTimes
[0]);
1561 if ( sEnv
.DYLD_PRINT_STATISTICS_DETAILS
)
1562 ImageLoaderMachO::printStatisticsDetails((unsigned int)allImagesCount(), initializerTimes
[0]);
1565 bool mainExecutablePrebound()
1567 return sMainExecutable
->usablePrebinding(gLinkContext
);
1570 ImageLoader
* mainExecutable()
1572 return sMainExecutable
;
1578 #if SUPPORT_VERSIONED_PATHS
1580 // forward reference
1581 static bool getDylibVersionAndInstallname(const char* dylibPath
, uint32_t* version
, char* installName
);
1585 // Examines a dylib file and if its current_version is newer than the installed
1586 // dylib at its install_name, then add the dylib file to sDylibOverrides.
1588 static void checkDylibOverride(const char* dylibFile
)
1590 //dyld::log("checkDylibOverride('%s')\n", dylibFile);
1591 uint32_t altVersion
;
1592 char sysInstallName
[PATH_MAX
];
1593 if ( getDylibVersionAndInstallname(dylibFile
, &altVersion
, sysInstallName
) && (sysInstallName
[0] =='/') ) {
1594 //dyld::log("%s has version 0x%08X and install name %s\n", dylibFile, altVersion, sysInstallName);
1595 uint32_t sysVersion
;
1596 if ( getDylibVersionAndInstallname(sysInstallName
, &sysVersion
, NULL
) ) {
1597 //dyld::log("%s has version 0x%08X\n", sysInstallName, sysVersion);
1598 if ( altVersion
> sysVersion
) {
1599 //dyld::log("override found: %s -> %s\n", sysInstallName, dylibFile);
1600 // see if there already is an override for this dylib
1601 bool entryExists
= false;
1602 for (std::vector
<DylibOverride
>::iterator it
= sDylibOverrides
.begin(); it
!= sDylibOverrides
.end(); ++it
) {
1603 if ( strcmp(it
->installName
, sysInstallName
) == 0 ) {
1605 uint32_t prevVersion
;
1606 if ( getDylibVersionAndInstallname(it
->override
, &prevVersion
, NULL
) ) {
1607 if ( altVersion
> prevVersion
) {
1608 // found an even newer override
1609 free((void*)(it
->override
));
1610 char resolvedPath
[PATH_MAX
];
1611 if ( realpath(dylibFile
, resolvedPath
) != NULL
)
1612 it
->override
= strdup(resolvedPath
);
1614 it
->override
= strdup(dylibFile
);
1620 if ( ! entryExists
) {
1621 DylibOverride entry
;
1622 entry
.installName
= strdup(sysInstallName
);
1623 char resolvedPath
[PATH_MAX
];
1624 if ( realpath(dylibFile
, resolvedPath
) != NULL
)
1625 entry
.override
= strdup(resolvedPath
);
1627 entry
.override
= strdup(dylibFile
);
1628 sDylibOverrides
.push_back(entry
);
1629 //dyld::log("added override: %s -> %s\n", entry.installName, entry.override);
1637 static void checkDylibOverridesInDir(const char* dirPath
)
1639 //dyld::log("checkDylibOverridesInDir('%s')\n", dirPath);
1640 char dylibPath
[PATH_MAX
];
1641 long dirPathLen
= strlcpy(dylibPath
, dirPath
, PATH_MAX
-1);
1642 if ( dirPathLen
>= PATH_MAX
)
1644 DIR* dirp
= opendir(dirPath
);
1645 if ( dirp
!= NULL
) {
1647 dirent
* entp
= NULL
;
1648 while ( readdir_r(dirp
, &entry
, &entp
) == 0 ) {
1651 if ( entp
->d_type
!= DT_REG
)
1653 dylibPath
[dirPathLen
] = '/';
1654 dylibPath
[dirPathLen
+1] = '\0';
1655 if ( strlcat(dylibPath
, entp
->d_name
, PATH_MAX
) >= PATH_MAX
)
1657 checkDylibOverride(dylibPath
);
1664 static void checkFrameworkOverridesInDir(const char* dirPath
)
1666 //dyld::log("checkFrameworkOverridesInDir('%s')\n", dirPath);
1667 char frameworkPath
[PATH_MAX
];
1668 long dirPathLen
= strlcpy(frameworkPath
, dirPath
, PATH_MAX
-1);
1669 if ( dirPathLen
>= PATH_MAX
)
1671 DIR* dirp
= opendir(dirPath
);
1672 if ( dirp
!= NULL
) {
1674 dirent
* entp
= NULL
;
1675 while ( readdir_r(dirp
, &entry
, &entp
) == 0 ) {
1678 if ( entp
->d_type
!= DT_DIR
)
1680 frameworkPath
[dirPathLen
] = '/';
1681 frameworkPath
[dirPathLen
+1] = '\0';
1682 int dirNameLen
= (int)strlen(entp
->d_name
);
1683 if ( dirNameLen
< 11 )
1685 if ( strcmp(&entp
->d_name
[dirNameLen
-10], ".framework") != 0 )
1687 if ( strlcat(frameworkPath
, entp
->d_name
, PATH_MAX
) >= PATH_MAX
)
1689 if ( strlcat(frameworkPath
, "/", PATH_MAX
) >= PATH_MAX
)
1691 if ( strlcat(frameworkPath
, entp
->d_name
, PATH_MAX
) >= PATH_MAX
)
1693 frameworkPath
[strlen(frameworkPath
)-10] = '\0';
1694 checkDylibOverride(frameworkPath
);
1699 #endif // SUPPORT_VERSIONED_PATHS
1703 // Turns a colon separated list of strings into a NULL terminated array
1704 // of string pointers. If mainExecutableDir param is not NULL,
1705 // substitutes @loader_path with main executable's dir.
1707 static const char** parseColonList(const char* list
, const char* mainExecutableDir
)
1709 static const char* sEmptyList
[] = { NULL
};
1711 if ( list
[0] == '\0' )
1715 for(const char* s
=list
; *s
!= '\0'; ++s
) {
1721 const char* start
= list
;
1722 char** result
= new char*[colonCount
+2];
1723 for(const char* s
=list
; *s
!= '\0'; ++s
) {
1725 size_t len
= s
-start
;
1726 if ( (mainExecutableDir
!= NULL
) && (strncmp(start
, "@loader_path/", 13) == 0) ) {
1727 if ( !gLinkContext
.allowAtPaths
) {
1728 dyld::log("dyld: warning: @loader_path/ ignored because of amfi policy (Codesign main executable with Library Validation to allow @ paths)\n");
1731 size_t mainExecDirLen
= strlen(mainExecutableDir
);
1732 char* str
= new char[mainExecDirLen
+len
+1];
1733 strcpy(str
, mainExecutableDir
);
1734 strlcat(str
, &start
[13], mainExecDirLen
+len
+1);
1735 str
[mainExecDirLen
+len
-13] = '\0';
1737 result
[index
++] = str
;
1739 else if ( (mainExecutableDir
!= NULL
) && (strncmp(start
, "@executable_path/", 17) == 0) ) {
1740 if ( !gLinkContext
.allowAtPaths
) {
1741 dyld::log("dyld: warning: @executable_path/ ignored because of amfi policy (Codesign main executable with Library Validation to allow @ paths)\n");
1744 size_t mainExecDirLen
= strlen(mainExecutableDir
);
1745 char* str
= new char[mainExecDirLen
+len
+1];
1746 strcpy(str
, mainExecutableDir
);
1747 strlcat(str
, &start
[17], mainExecDirLen
+len
+1);
1748 str
[mainExecDirLen
+len
-17] = '\0';
1750 result
[index
++] = str
;
1753 char* str
= new char[len
+1];
1754 strncpy(str
, start
, len
);
1757 result
[index
++] = str
;
1761 size_t len
= strlen(start
);
1762 if ( (mainExecutableDir
!= NULL
) && (strncmp(start
, "@loader_path/", 13) == 0) ) {
1763 if ( !gLinkContext
.allowAtPaths
) {
1764 dyld::log("dyld: warning: @loader_path/ ignored because of amfi policy (Codesign main executable with Library Validation to allow @ paths)\n");
1768 size_t mainExecDirLen
= strlen(mainExecutableDir
);
1769 char* str
= new char[mainExecDirLen
+len
+1];
1770 strcpy(str
, mainExecutableDir
);
1771 strlcat(str
, &start
[13], mainExecDirLen
+len
+1);
1772 str
[mainExecDirLen
+len
-13] = '\0';
1773 result
[index
++] = str
;
1776 else if ( (mainExecutableDir
!= NULL
) && (strncmp(start
, "@executable_path/", 17) == 0) ) {
1777 if ( !gLinkContext
.allowAtPaths
) {
1778 dyld::log("dyld: warning: @executable_path/ ignored because of amfi policy (Codesign main executable with Library Validation to allow @ paths)\n");
1782 size_t mainExecDirLen
= strlen(mainExecutableDir
);
1783 char* str
= new char[mainExecDirLen
+len
+1];
1784 strcpy(str
, mainExecutableDir
);
1785 strlcat(str
, &start
[17], mainExecDirLen
+len
+1);
1786 str
[mainExecDirLen
+len
-17] = '\0';
1787 result
[index
++] = str
;
1791 char* str
= new char[len
+1];
1793 result
[index
++] = str
;
1795 result
[index
] = NULL
;
1797 //dyld::log("parseColonList(%s)\n", list);
1798 //for(int i=0; result[i] != NULL; ++i)
1799 // dyld::log(" %s\n", result[i]);
1800 return (const char**)result
;
1803 static void appendParsedColonList(const char* list
, const char* mainExecutableDir
, const char* const ** storage
)
1805 const char** newlist
= parseColonList(list
, mainExecutableDir
);
1806 if ( *storage
== NULL
) {
1807 // first time, just set
1811 // need to append to existing list
1812 const char* const* existing
= *storage
;
1814 for(int i
=0; existing
[i
] != NULL
; ++i
)
1816 for(int i
=0; newlist
[i
] != NULL
; ++i
)
1818 const char** combinedList
= new const char*[count
+2];
1820 for(int i
=0; existing
[i
] != NULL
; ++i
)
1821 combinedList
[index
++] = existing
[i
];
1822 for(int i
=0; newlist
[i
] != NULL
; ++i
)
1823 combinedList
[index
++] = newlist
[i
];
1824 combinedList
[index
] = NULL
;
1825 delete[] newlist
; // free array, note: strings in newList may be leaked
1826 *storage
= combinedList
;
1830 #if __MAC_OS_X_VERSION_MIN_REQUIRED
1831 static void paths_expand_roots(const char **paths
, const char *key
, const char *val
)
1833 // assert(val != NULL);
1834 // assert(paths != NULL);
1836 size_t keyLen
= strlen(key
);
1837 for(int i
=0; paths
[i
] != NULL
; ++i
) {
1838 if ( strncmp(paths
[i
], key
, keyLen
) == 0 ) {
1839 char* newPath
= new char[strlen(val
) + (strlen(paths
[i
]) - keyLen
) + 1];
1840 strcpy(newPath
, val
);
1841 strcat(newPath
, &paths
[i
][keyLen
]);
1849 static void removePathWithPrefix(const char* paths
[], const char* prefix
)
1851 size_t prefixLen
= strlen(prefix
);
1854 for(i
= 0; paths
[i
] != NULL
; ++i
) {
1855 if ( strncmp(paths
[i
], prefix
, prefixLen
) == 0 )
1858 paths
[i
-skip
] = paths
[i
];
1860 paths
[i
-skip
] = NULL
;
1866 static void paths_dump(const char **paths
)
1868 // assert(paths != NULL);
1869 const char **strs
= paths
;
1870 while(*strs
!= NULL
)
1872 dyld::log("\"%s\"\n", *strs
);
1881 static void printOptions(const char* argv
[])
1884 while ( NULL
!= argv
[i
] ) {
1885 dyld::log("opt[%i] = \"%s\"\n", i
, argv
[i
]);
1890 static void printEnvironmentVariables(const char* envp
[])
1892 while ( NULL
!= *envp
) {
1893 dyld::log("%s\n", *envp
);
1898 void processDyldEnvironmentVariable(const char* key
, const char* value
, const char* mainExecutableDir
)
1900 if ( strcmp(key
, "DYLD_FRAMEWORK_PATH") == 0 ) {
1901 appendParsedColonList(value
, mainExecutableDir
, &sEnv
.DYLD_FRAMEWORK_PATH
);
1902 sEnv
.hasOverride
= true;
1904 else if ( strcmp(key
, "DYLD_FALLBACK_FRAMEWORK_PATH") == 0 ) {
1905 appendParsedColonList(value
, mainExecutableDir
, &sEnv
.DYLD_FALLBACK_FRAMEWORK_PATH
);
1906 sEnv
.hasOverride
= true;
1908 else if ( strcmp(key
, "DYLD_LIBRARY_PATH") == 0 ) {
1909 appendParsedColonList(value
, mainExecutableDir
, &sEnv
.DYLD_LIBRARY_PATH
);
1910 sEnv
.hasOverride
= true;
1912 else if ( strcmp(key
, "DYLD_FALLBACK_LIBRARY_PATH") == 0 ) {
1913 appendParsedColonList(value
, mainExecutableDir
, &sEnv
.DYLD_FALLBACK_LIBRARY_PATH
);
1914 sEnv
.hasOverride
= true;
1916 #if SUPPORT_ROOT_PATH
1917 else if ( (strcmp(key
, "DYLD_ROOT_PATH") == 0) || (strcmp(key
, "DYLD_PATHS_ROOT") == 0) ) {
1918 if ( strcmp(value
, "/") != 0 ) {
1919 gLinkContext
.rootPaths
= parseColonList(value
, mainExecutableDir
);
1920 for (int i
=0; gLinkContext
.rootPaths
[i
] != NULL
; ++i
) {
1921 if ( gLinkContext
.rootPaths
[i
][0] != '/' ) {
1922 dyld::warn("DYLD_ROOT_PATH not used because it contains a non-absolute path\n");
1923 gLinkContext
.rootPaths
= NULL
;
1928 sEnv
.hasOverride
= true;
1931 else if ( strcmp(key
, "DYLD_IMAGE_SUFFIX") == 0 ) {
1932 gLinkContext
.imageSuffix
= parseColonList(value
, NULL
);
1933 sEnv
.hasOverride
= true;
1935 else if ( strcmp(key
, "DYLD_INSERT_LIBRARIES") == 0 ) {
1936 sEnv
.DYLD_INSERT_LIBRARIES
= parseColonList(value
, NULL
);
1937 #if SUPPORT_ACCELERATE_TABLES
1938 sDisableAcceleratorTables
= true;
1940 sEnv
.hasOverride
= true;
1942 else if ( strcmp(key
, "DYLD_PRINT_OPTS") == 0 ) {
1943 sEnv
.DYLD_PRINT_OPTS
= true;
1945 else if ( strcmp(key
, "DYLD_PRINT_ENV") == 0 ) {
1946 sEnv
.DYLD_PRINT_ENV
= true;
1948 else if ( strcmp(key
, "DYLD_DISABLE_DOFS") == 0 ) {
1949 sEnv
.DYLD_DISABLE_DOFS
= true;
1951 else if ( strcmp(key
, "DYLD_PRINT_LIBRARIES") == 0 ) {
1952 gLinkContext
.verboseLoading
= true;
1954 else if ( strcmp(key
, "DYLD_PRINT_LIBRARIES_POST_LAUNCH") == 0 ) {
1955 sEnv
.DYLD_PRINT_LIBRARIES_POST_LAUNCH
= true;
1957 else if ( strcmp(key
, "DYLD_BIND_AT_LAUNCH") == 0 ) {
1958 sEnv
.DYLD_BIND_AT_LAUNCH
= true;
1960 else if ( strcmp(key
, "DYLD_FORCE_FLAT_NAMESPACE") == 0 ) {
1961 gLinkContext
.bindFlat
= true;
1963 else if ( strcmp(key
, "DYLD_NEW_LOCAL_SHARED_REGIONS") == 0 ) {
1964 // ignore, no longer relevant but some scripts still set it
1966 else if ( strcmp(key
, "DYLD_NO_FIX_PREBINDING") == 0 ) {
1968 else if ( strcmp(key
, "DYLD_PREBIND_DEBUG") == 0 ) {
1969 gLinkContext
.verbosePrebinding
= true;
1971 else if ( strcmp(key
, "DYLD_PRINT_INITIALIZERS") == 0 ) {
1972 gLinkContext
.verboseInit
= true;
1974 else if ( strcmp(key
, "DYLD_PRINT_DOFS") == 0 ) {
1975 gLinkContext
.verboseDOF
= true;
1977 else if ( strcmp(key
, "DYLD_PRINT_STATISTICS") == 0 ) {
1978 sEnv
.DYLD_PRINT_STATISTICS
= true;
1979 #if __IPHONE_OS_VERSION_MIN_REQUIRED && !TARGET_OS_SIMULATOR
1980 // <rdar://problem/26614838> DYLD_PRINT_STATISTICS no longer logs to xcode console for device apps
1981 sForceStderr
= true;
1984 else if ( strcmp(key
, "DYLD_PRINT_TO_STDERR") == 0 ) {
1985 #if __IPHONE_OS_VERSION_MIN_REQUIRED && !TARGET_OS_SIMULATOR
1986 // <rdar://problem/26633440> DYLD_PRINT_STATISTICS no longer logs to xcode console for device apps
1987 sForceStderr
= true;
1990 else if ( strcmp(key
, "DYLD_PRINT_STATISTICS_DETAILS") == 0 ) {
1991 sEnv
.DYLD_PRINT_STATISTICS_DETAILS
= true;
1993 else if ( strcmp(key
, "DYLD_PRINT_SEGMENTS") == 0 ) {
1994 gLinkContext
.verboseMapping
= true;
1996 else if ( strcmp(key
, "DYLD_PRINT_BINDINGS") == 0 ) {
1997 gLinkContext
.verboseBind
= true;
1999 else if ( strcmp(key
, "DYLD_PRINT_WEAK_BINDINGS") == 0 ) {
2000 gLinkContext
.verboseWeakBind
= true;
2002 else if ( strcmp(key
, "DYLD_PRINT_REBASINGS") == 0 ) {
2003 gLinkContext
.verboseRebase
= true;
2005 else if ( strcmp(key
, "DYLD_PRINT_APIS") == 0 ) {
2008 #if SUPPORT_ACCELERATE_TABLES
2009 else if ( strcmp(key
, "DYLD_PRINT_APIS_APP") == 0 ) {
2013 else if ( strcmp(key
, "DYLD_PRINT_WARNINGS") == 0 ) {
2014 gLinkContext
.verboseWarnings
= true;
2016 else if ( strcmp(key
, "DYLD_PRINT_RPATHS") == 0 ) {
2017 gLinkContext
.verboseRPaths
= true;
2019 else if ( strcmp(key
, "DYLD_PRINT_INTERPOSING") == 0 ) {
2020 gLinkContext
.verboseInterposing
= true;
2022 else if ( strcmp(key
, "DYLD_PRINT_CODE_SIGNATURES") == 0 ) {
2023 gLinkContext
.verboseCodeSignatures
= true;
2025 else if ( (strcmp(key
, "DYLD_SHARED_REGION") == 0) && gLinkContext
.allowEnvVarsSharedCache
) {
2026 if ( strcmp(value
, "private") == 0 ) {
2027 gLinkContext
.sharedRegionMode
= ImageLoader::kUsePrivateSharedRegion
;
2029 else if ( strcmp(value
, "avoid") == 0 ) {
2030 gLinkContext
.sharedRegionMode
= ImageLoader::kDontUseSharedRegion
;
2032 else if ( strcmp(value
, "use") == 0 ) {
2033 gLinkContext
.sharedRegionMode
= ImageLoader::kUseSharedRegion
;
2035 else if ( value
[0] == '\0' ) {
2036 gLinkContext
.sharedRegionMode
= ImageLoader::kUseSharedRegion
;
2039 dyld::warn("unknown option to DYLD_SHARED_REGION. Valid options are: use, private, avoid\n");
2042 else if ( (strcmp(key
, "DYLD_SHARED_CACHE_DIR") == 0) && gLinkContext
.allowEnvVarsSharedCache
) {
2043 sSharedCacheOverrideDir
= value
;
2045 else if ( strcmp(key
, "DYLD_USE_CLOSURES") == 0 ) {
2046 // Handled elsewhere
2048 else if ( strcmp(key
, "DYLD_FORCE_INVALID_CACHE_CLOSURES") == 0 ) {
2049 if ( dyld3::internalInstall() ) {
2050 sForceInvalidSharedCacheClosureFormat
= true;
2053 else if ( strcmp(key
, "DYLD_IGNORE_PREBINDING") == 0 ) {
2054 if ( strcmp(value
, "all") == 0 ) {
2055 gLinkContext
.prebindUsage
= ImageLoader::kUseNoPrebinding
;
2057 else if ( strcmp(value
, "app") == 0 ) {
2058 gLinkContext
.prebindUsage
= ImageLoader::kUseAllButAppPredbinding
;
2060 else if ( strcmp(value
, "nonsplit") == 0 ) {
2061 gLinkContext
.prebindUsage
= ImageLoader::kUseSplitSegPrebinding
;
2063 else if ( value
[0] == '\0' ) {
2064 gLinkContext
.prebindUsage
= ImageLoader::kUseSplitSegPrebinding
;
2067 dyld::warn("unknown option to DYLD_IGNORE_PREBINDING. Valid options are: all, app, nonsplit\n");
2070 #if SUPPORT_VERSIONED_PATHS
2071 else if ( strcmp(key
, "DYLD_VERSIONED_LIBRARY_PATH") == 0 ) {
2072 appendParsedColonList(value
, mainExecutableDir
, &sEnv
.DYLD_VERSIONED_LIBRARY_PATH
);
2073 #if SUPPORT_ACCELERATE_TABLES
2074 sDisableAcceleratorTables
= true;
2076 sEnv
.hasOverride
= true;
2078 else if ( strcmp(key
, "DYLD_VERSIONED_FRAMEWORK_PATH") == 0 ) {
2079 appendParsedColonList(value
, mainExecutableDir
, &sEnv
.DYLD_VERSIONED_FRAMEWORK_PATH
);
2080 #if SUPPORT_ACCELERATE_TABLES
2081 sDisableAcceleratorTables
= true;
2083 sEnv
.hasOverride
= true;
2086 #if !TARGET_OS_SIMULATOR
2087 else if ( (strcmp(key
, "DYLD_PRINT_TO_FILE") == 0) && (mainExecutableDir
== NULL
) && gLinkContext
.allowEnvVarsSharedCache
) {
2088 int fd
= open(value
, O_WRONLY
| O_CREAT
| O_APPEND
, 0644);
2094 dyld::log("dyld: could not open DYLD_PRINT_TO_FILE='%s', errno=%d\n", value
, errno
);
2097 else if ( (strcmp(key
, "DYLD_SKIP_MAIN") == 0)) {
2098 if ( dyld3::internalInstall() )
2101 else if ( (strcmp(key
, "DYLD_JUST_BUILD_CLOSURE") == 0) ) {
2102 // handled elsewhere
2105 else if (strcmp(key
, "DYLD_FORCE_PLATFORM") == 0) {
2106 // handled elsewhere
2108 else if (strcmp(key
, "DYLD_AMFI_FAKE") == 0) {
2109 // handled elsewhere
2112 dyld::warn("unknown environment variable: %s\n", key
);
2117 #if SUPPORT_LC_DYLD_ENVIRONMENT
2118 static void checkLoadCommandEnvironmentVariables()
2120 // <rdar://problem/8440934> Support augmenting dyld environment variables in load commands
2121 const uint32_t cmd_count
= sMainExecutableMachHeader
->ncmds
;
2122 const struct load_command
* const cmds
= (struct load_command
*)(((char*)sMainExecutableMachHeader
)+sizeof(macho_header
));
2123 const struct load_command
* cmd
= cmds
;
2124 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
2126 case LC_DYLD_ENVIRONMENT
:
2128 const struct dylinker_command
* envcmd
= (struct dylinker_command
*)cmd
;
2129 const char* keyEqualsValue
= (char*)envcmd
+ envcmd
->name
.offset
;
2130 char mainExecutableDir
[strlen(sExecPath
)+2];
2131 strcpy(mainExecutableDir
, sExecPath
);
2132 char* lastSlash
= strrchr(mainExecutableDir
, '/');
2133 if ( lastSlash
!= NULL
)
2134 lastSlash
[1] = '\0';
2135 // only process variables that start with DYLD_ and end in _PATH
2136 if ( (strncmp(keyEqualsValue
, "DYLD_", 5) == 0) ) {
2137 const char* equals
= strchr(keyEqualsValue
, '=');
2138 if ( equals
!= NULL
) {
2139 if ( strncmp(&equals
[-5], "_PATH", 5) == 0 ) {
2140 const char* value
= &equals
[1];
2141 const size_t keyLen
= equals
-keyEqualsValue
;
2142 // <rdar://problem/22799635> don't let malformed load command overflow stack
2143 if ( keyLen
< 40 ) {
2145 strncpy(key
, keyEqualsValue
, keyLen
);
2147 //dyld::log("processing: %s\n", keyEqualsValue);
2148 //dyld::log("mainExecutableDir: %s\n", mainExecutableDir);
2149 #if SUPPORT_ROOT_PATH
2150 if ( (strcmp(key
, "DYLD_ROOT_PATH") == 0) || (strcmp(key
, "DYLD_PATHS_ROOT") == 0) )
2153 processDyldEnvironmentVariable(key
, value
, mainExecutableDir
);
2161 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
2164 #endif // SUPPORT_LC_DYLD_ENVIRONMENT
2167 static bool hasCodeSignatureLoadCommand(const macho_header
* mh
)
2169 const uint32_t cmd_count
= mh
->ncmds
;
2170 const struct load_command
* const cmds
= (struct load_command
*)(((char*)mh
)+sizeof(macho_header
));
2171 const struct load_command
* cmd
= cmds
;
2172 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
2173 if (cmd
->cmd
== LC_CODE_SIGNATURE
)
2175 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
2181 #if SUPPORT_VERSIONED_PATHS
2182 static void checkVersionedPaths()
2184 // search DYLD_VERSIONED_LIBRARY_PATH directories for dylibs and check if they are newer
2185 if ( sEnv
.DYLD_VERSIONED_LIBRARY_PATH
!= NULL
) {
2186 for(const char* const* lp
= sEnv
.DYLD_VERSIONED_LIBRARY_PATH
; *lp
!= NULL
; ++lp
) {
2187 checkDylibOverridesInDir(*lp
);
2191 // search DYLD_VERSIONED_FRAMEWORK_PATH directories for dylibs and check if they are newer
2192 if ( sEnv
.DYLD_VERSIONED_FRAMEWORK_PATH
!= NULL
) {
2193 for(const char* const* fp
= sEnv
.DYLD_VERSIONED_FRAMEWORK_PATH
; *fp
!= NULL
; ++fp
) {
2194 checkFrameworkOverridesInDir(*fp
);
2201 #if __MAC_OS_X_VERSION_MIN_REQUIRED
2203 // For security, setuid programs ignore DYLD_* environment variables.
2204 // Additionally, the DYLD_* enviroment variables are removed
2205 // from the environment, so that any child processes don't see them.
2207 static void pruneEnvironmentVariables(const char* envp
[], const char*** applep
)
2209 #if SUPPORT_LC_DYLD_ENVIRONMENT
2210 checkLoadCommandEnvironmentVariables();
2213 // Are we testing dyld on an internal config?
2214 if ( _simple_getenv(envp
, "DYLD_SKIP_MAIN") != NULL
) {
2215 if ( dyld3::internalInstall() )
2219 // delete all DYLD_* and LD_LIBRARY_PATH environment variables
2220 int removedCount
= 0;
2221 const char** d
= envp
;
2222 for(const char** s
= envp
; *s
!= NULL
; s
++) {
2224 if ( (strncmp(*s
, "DYLD_", 5) != 0) && (strncmp(*s
, "LD_LIBRARY_PATH=", 16) != 0) ) {
2232 // slide apple parameters
2233 if ( removedCount
> 0 ) {
2236 *d
= d
[removedCount
];
2237 } while ( *d
++ != NULL
);
2238 for(int i
=0; i
< removedCount
; ++i
)
2242 // disable framework and library fallback paths for setuid binaries rdar://problem/4589305
2243 sEnv
.DYLD_FALLBACK_FRAMEWORK_PATH
= NULL
;
2244 sEnv
.DYLD_FALLBACK_LIBRARY_PATH
= NULL
;
2246 if ( removedCount
> 0 )
2247 strlcat(sLoadingCrashMessage
, ", ignoring DYLD_* env vars", sizeof(sLoadingCrashMessage
));
2251 static void defaultUninitializedFallbackPaths(const char* envp
[])
2253 #if __MAC_OS_X_VERSION_MIN_REQUIRED
2254 if ( !gLinkContext
.allowClassicFallbackPaths
) {
2255 sEnv
.DYLD_FALLBACK_FRAMEWORK_PATH
= sRestrictedFrameworkFallbackPaths
;
2256 sEnv
.DYLD_FALLBACK_LIBRARY_PATH
= sRestrictedLibraryFallbackPaths
;
2260 // default value for DYLD_FALLBACK_FRAMEWORK_PATH, if not set in environment
2261 const char* home
= _simple_getenv(envp
, "HOME");;
2262 if ( sEnv
.DYLD_FALLBACK_FRAMEWORK_PATH
== NULL
) {
2263 const char** fpaths
= sFrameworkFallbackPaths
;
2265 removePathWithPrefix(fpaths
, "$HOME");
2267 paths_expand_roots(fpaths
, "$HOME", home
);
2268 sEnv
.DYLD_FALLBACK_FRAMEWORK_PATH
= fpaths
;
2271 // default value for DYLD_FALLBACK_LIBRARY_PATH, if not set in environment
2272 if ( sEnv
.DYLD_FALLBACK_LIBRARY_PATH
== NULL
) {
2273 const char** lpaths
= sLibraryFallbackPaths
;
2275 removePathWithPrefix(lpaths
, "$HOME");
2277 paths_expand_roots(lpaths
, "$HOME", home
);
2278 sEnv
.DYLD_FALLBACK_LIBRARY_PATH
= lpaths
;
2281 if ( sEnv
.DYLD_FALLBACK_FRAMEWORK_PATH
== NULL
)
2282 sEnv
.DYLD_FALLBACK_FRAMEWORK_PATH
= sFrameworkFallbackPaths
;
2284 if ( sEnv
.DYLD_FALLBACK_LIBRARY_PATH
== NULL
)
2285 sEnv
.DYLD_FALLBACK_LIBRARY_PATH
= sLibraryFallbackPaths
;
2290 static void checkEnvironmentVariables(const char* envp
[])
2292 if ( !gLinkContext
.allowEnvVarsPath
&& !gLinkContext
.allowEnvVarsPrint
)
2295 for(p
= envp
; *p
!= NULL
; p
++) {
2296 const char* keyEqualsValue
= *p
;
2297 if ( strncmp(keyEqualsValue
, "DYLD_", 5) == 0 ) {
2298 const char* equals
= strchr(keyEqualsValue
, '=');
2299 if ( equals
!= NULL
) {
2300 strlcat(sLoadingCrashMessage
, "\n", sizeof(sLoadingCrashMessage
));
2301 strlcat(sLoadingCrashMessage
, keyEqualsValue
, sizeof(sLoadingCrashMessage
));
2302 const char* value
= &equals
[1];
2303 const size_t keyLen
= equals
-keyEqualsValue
;
2305 strncpy(key
, keyEqualsValue
, keyLen
);
2307 if ( (strncmp(key
, "DYLD_PRINT_", 11) == 0) && !gLinkContext
.allowEnvVarsPrint
)
2309 processDyldEnvironmentVariable(key
, value
, NULL
);
2312 else if ( strncmp(keyEqualsValue
, "LD_LIBRARY_PATH=", 16) == 0 ) {
2313 const char* path
= &keyEqualsValue
[16];
2314 sEnv
.LD_LIBRARY_PATH
= parseColonList(path
, NULL
);
2318 #if SUPPORT_LC_DYLD_ENVIRONMENT
2319 checkLoadCommandEnvironmentVariables();
2320 #endif // SUPPORT_LC_DYLD_ENVIRONMENT
2322 #if SUPPORT_ROOT_PATH
2323 // <rdar://problem/11281064> DYLD_IMAGE_SUFFIX and DYLD_ROOT_PATH cannot be used together
2324 if ( (gLinkContext
.imageSuffix
!= NULL
&& *gLinkContext
.imageSuffix
!= NULL
) && (gLinkContext
.rootPaths
!= NULL
) ) {
2325 dyld::warn("Ignoring DYLD_IMAGE_SUFFIX because DYLD_ROOT_PATH is used.\n");
2326 gLinkContext
.imageSuffix
= NULL
; // this leaks allocations from parseColonList
2331 #if __x86_64__ && !TARGET_OS_SIMULATOR
2332 static bool isGCProgram(const macho_header
* mh
, uintptr_t slide
)
2334 const uint32_t cmd_count
= mh
->ncmds
;
2335 const struct load_command
* const cmds
= (struct load_command
*)(((char*)mh
)+sizeof(macho_header
));
2336 const struct load_command
* cmd
= cmds
;
2337 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
2339 case LC_SEGMENT_COMMAND
:
2341 const struct macho_segment_command
* seg
= (struct macho_segment_command
*)cmd
;
2342 if (strcmp(seg
->segname
, "__DATA") == 0) {
2343 const struct macho_section
* const sectionsStart
= (struct macho_section
*)((char*)seg
+ sizeof(struct macho_segment_command
));
2344 const struct macho_section
* const sectionsEnd
= §ionsStart
[seg
->nsects
];
2345 for (const struct macho_section
* sect
=sectionsStart
; sect
< sectionsEnd
; ++sect
) {
2346 if (strncmp(sect
->sectname
, "__objc_imageinfo", 16) == 0) {
2347 const uint32_t* objcInfo
= (uint32_t*)(sect
->addr
+ slide
);
2348 return (objcInfo
[1] & 6); // 6 = (OBJC_IMAGE_SUPPORTS_GC | OBJC_IMAGE_REQUIRES_GC)
2355 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
2361 static void getHostInfo(const macho_header
* mainExecutableMH
, uintptr_t mainExecutableSlide
)
2363 #if CPU_SUBTYPES_SUPPORTED
2365 sHostCPU
= CPU_TYPE_ARM
;
2366 sHostCPUsubtype
= CPU_SUBTYPE_ARM_V7K
;
2367 #elif __ARM_ARCH_7A__
2368 sHostCPU
= CPU_TYPE_ARM
;
2369 sHostCPUsubtype
= CPU_SUBTYPE_ARM_V7
;
2370 #elif __ARM_ARCH_6K__
2371 sHostCPU
= CPU_TYPE_ARM
;
2372 sHostCPUsubtype
= CPU_SUBTYPE_ARM_V6
;
2373 #elif __ARM_ARCH_7F__
2374 sHostCPU
= CPU_TYPE_ARM
;
2375 sHostCPUsubtype
= CPU_SUBTYPE_ARM_V7F
;
2376 #elif __ARM_ARCH_7S__
2377 sHostCPU
= CPU_TYPE_ARM
;
2378 sHostCPUsubtype
= CPU_SUBTYPE_ARM_V7S
;
2379 #elif __ARM64_ARCH_8_32__
2380 sHostCPU
= CPU_TYPE_ARM64_32
;
2381 sHostCPUsubtype
= CPU_SUBTYPE_ARM64_32_V8
;
2383 sHostCPU
= CPU_TYPE_ARM64
;
2384 sHostCPUsubtype
= CPU_SUBTYPE_ARM64E
;
2386 sHostCPU
= CPU_TYPE_ARM64
;
2387 sHostCPUsubtype
= CPU_SUBTYPE_ARM64_V8
;
2389 struct host_basic_info info
;
2390 mach_msg_type_number_t count
= HOST_BASIC_INFO_COUNT
;
2391 mach_port_t hostPort
= mach_host_self();
2392 kern_return_t result
= host_info(hostPort
, HOST_BASIC_INFO
, (host_info_t
)&info
, &count
);
2393 if ( result
!= KERN_SUCCESS
)
2394 throw "host_info() failed";
2395 sHostCPU
= info
.cpu_type
;
2396 sHostCPUsubtype
= info
.cpu_subtype
;
2397 mach_port_deallocate(mach_task_self(), hostPort
);
2399 // host_info returns CPU_TYPE_I386 even for x86_64. Override that here so that
2400 // we don't need to mask the cpu type later.
2401 sHostCPU
= CPU_TYPE_X86_64
;
2402 #if !TARGET_OS_SIMULATOR
2403 sHaswell
= (sHostCPUsubtype
== CPU_SUBTYPE_X86_64_H
);
2404 // <rdar://problem/18528074> x86_64h: Fall back to the x86_64 slice if an app requires GC.
2406 if ( isGCProgram(mainExecutableMH
, mainExecutableSlide
) ) {
2407 // When running a GC program on a haswell machine, don't use and 'h slices
2408 sHostCPUsubtype
= CPU_SUBTYPE_X86_64_ALL
;
2410 gLinkContext
.sharedRegionMode
= ImageLoader::kDontUseSharedRegion
;
2419 static void checkSharedRegionDisable(const dyld3::MachOLoaded
* mainExecutableMH
, uintptr_t mainExecutableSlide
)
2421 #if __MAC_OS_X_VERSION_MIN_REQUIRED
2422 // if main executable has segments that overlap the shared region,
2423 // then disable using the shared region
2424 if ( mainExecutableMH
->intersectsRange(SHARED_REGION_BASE
, SHARED_REGION_SIZE
) ) {
2425 gLinkContext
.sharedRegionMode
= ImageLoader::kDontUseSharedRegion
;
2426 if ( gLinkContext
.verboseMapping
)
2427 dyld::warn("disabling shared region because main executable overlaps\n");
2430 if ( !gLinkContext
.allowEnvVarsPath
) {
2431 // <rdar://problem/15280847> use private or no shared region for suid processes
2432 gLinkContext
.sharedRegionMode
= ImageLoader::kUsePrivateSharedRegion
;
2436 // iOS cannot run without shared region
2439 bool validImage(const ImageLoader
* possibleImage
)
2441 const size_t imageCount
= sAllImages
.size();
2442 for(size_t i
=0; i
< imageCount
; ++i
) {
2443 if ( possibleImage
== sAllImages
[i
] ) {
2450 uint32_t getImageCount()
2452 return (uint32_t)sAllImages
.size();
2455 ImageLoader
* getIndexedImage(unsigned int index
)
2457 if ( index
< sAllImages
.size() )
2458 return sAllImages
[index
];
2462 ImageLoader
* findImageByMachHeader(const struct mach_header
* target
)
2464 return findMappedRange((uintptr_t)target
);
2468 ImageLoader
* findImageContainingAddress(const void* addr
)
2470 #if SUPPORT_ACCELERATE_TABLES
2471 if ( sAllCacheImagesProxy
!= NULL
) {
2472 const mach_header
* mh
;
2475 if ( sAllCacheImagesProxy
->addressInCache(addr
, &mh
, &path
, &index
) )
2476 return sAllCacheImagesProxy
;
2479 return findMappedRange((uintptr_t)addr
);
2483 ImageLoader
* findImageContainingSymbol(const void* symbol
)
2485 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
2486 ImageLoader
* anImage
= *it
;
2487 if ( anImage
->containsSymbol(symbol
) )
2495 void forEachImageDo( void (*callback
)(ImageLoader
*, void* userData
), void* userData
)
2497 const size_t imageCount
= sAllImages
.size();
2498 for(size_t i
=0; i
< imageCount
; ++i
) {
2499 ImageLoader
* anImage
= sAllImages
[i
];
2500 (*callback
)(anImage
, userData
);
2504 ImageLoader
* findLoadedImage(const struct stat
& stat_buf
)
2506 const size_t imageCount
= sAllImages
.size();
2507 for(size_t i
=0; i
< imageCount
; ++i
){
2508 ImageLoader
* anImage
= sAllImages
[i
];
2509 if ( anImage
->statMatch(stat_buf
) )
2515 // based on ANSI-C strstr()
2516 static const char* strrstr(const char* str
, const char* sub
)
2518 const size_t sublen
= strlen(sub
);
2519 for(const char* p
= &str
[strlen(str
)]; p
!= str
; --p
) {
2520 if ( strncmp(p
, sub
, sublen
) == 0 )
2528 // Find framework path
2530 // /path/foo.framework/foo => foo.framework/foo
2531 // /path/foo.framework/Versions/A/foo => foo.framework/Versions/A/foo
2532 // /path/foo.framework/Frameworks/bar.framework/bar => bar.framework/bar
2533 // /path/foo.framework/Libraries/bar.dylb => NULL
2534 // /path/foo.framework/bar => NULL
2536 // Returns NULL if not a framework path
2538 static const char* getFrameworkPartialPath(const char* path
)
2540 const char* dirDot
= strrstr(path
, ".framework/");
2541 if ( dirDot
!= NULL
) {
2542 const char* dirStart
= dirDot
;
2543 for ( ; dirStart
>= path
; --dirStart
) {
2544 if ( (*dirStart
== '/') || (dirStart
== path
) ) {
2545 const char* frameworkStart
= &dirStart
[1];
2546 if ( dirStart
== path
)
2548 size_t len
= dirDot
- frameworkStart
;
2549 char framework
[len
+1];
2550 strncpy(framework
, frameworkStart
, len
);
2551 framework
[len
] = '\0';
2552 const char* leaf
= strrchr(path
, '/');
2553 if ( leaf
!= NULL
) {
2554 if ( strcmp(framework
, &leaf
[1]) == 0 ) {
2555 return frameworkStart
;
2557 if ( gLinkContext
.imageSuffix
!= NULL
) {
2558 // some debug frameworks have install names that end in _debug
2559 if ( strncmp(framework
, &leaf
[1], len
) == 0 ) {
2560 for (const char* const* suffix
=gLinkContext
.imageSuffix
; *suffix
!= NULL
; ++suffix
) {
2561 if ( strcmp(*suffix
, &leaf
[len
+1]) == 0 )
2562 return frameworkStart
;
2574 static const char* getLibraryLeafName(const char* path
)
2576 const char* start
= strrchr(path
, '/');
2577 if ( start
!= NULL
)
2584 // only for architectures that use cpu-sub-types
2585 #if CPU_SUBTYPES_SUPPORTED
2587 const cpu_subtype_t CPU_SUBTYPE_END_OF_LIST
= -1;
2591 // A fat file may contain multiple sub-images for the same CPU type.
2592 // In that case, dyld picks which sub-image to use by scanning a table
2593 // of preferred cpu-sub-types for the running cpu.
2595 // There is one row in the table for each cpu-sub-type on which dyld might run.
2596 // The first entry in a row is that cpu-sub-type. It is followed by all
2597 // cpu-sub-types that can run on that cpu, if preferred order. Each row ends with
2598 // a "SUBTYPE_ALL" (to denote that images written to run on any cpu-sub-type are usable),
2599 // followed by one or more CPU_SUBTYPE_END_OF_LIST to pad out this row.
2605 // ARM sub-type lists
2607 const int kARM_RowCount
= 8;
2608 static const cpu_subtype_t kARM
[kARM_RowCount
][9] = {
2610 // armv7f can run: v7f, v7, v6, v5, and v4
2611 { 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
},
2613 // armv7k can run: v7k
2614 { CPU_SUBTYPE_ARM_V7K
, CPU_SUBTYPE_END_OF_LIST
},
2616 // armv7s can run: v7s, v7, v7f, v7k, v6, v5, and v4
2617 { 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
},
2619 // armv7 can run: v7, v6, v5, and v4
2620 { 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
},
2622 // armv6 can run: v6, v5, and v4
2623 { 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
},
2625 // xscale can run: xscale, v5, and v4
2626 { 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
},
2628 // armv5 can run: v5 and v4
2629 { 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
},
2631 // armv4 can run: v4
2632 { 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
},
2638 // ARM64 sub-type lists
2640 const int kARM64_RowCount
= 2;
2641 static const cpu_subtype_t kARM64
[kARM64_RowCount
][4] = {
2643 // armv64e can run: 64e, 64
2644 { CPU_SUBTYPE_ARM64E
, CPU_SUBTYPE_ARM64_V8
, CPU_SUBTYPE_ARM64_ALL
, CPU_SUBTYPE_END_OF_LIST
},
2646 // armv64 can run: 64
2647 { CPU_SUBTYPE_ARM64_V8
, CPU_SUBTYPE_ARM64_ALL
, CPU_SUBTYPE_END_OF_LIST
},
2650 #if __ARM64_ARCH_8_32__
2651 const int kARM64_32_RowCount
= 2;
2652 static const cpu_subtype_t kARM64_32
[kARM64_32_RowCount
][4] = {
2654 // armv64_32 can run: v8
2655 { CPU_SUBTYPE_ARM64_32_V8
, CPU_SUBTYPE_END_OF_LIST
},
2657 // armv64 can run: 64
2658 { CPU_SUBTYPE_ARM64_V8
, CPU_SUBTYPE_ARM64_ALL
, CPU_SUBTYPE_END_OF_LIST
},
2666 // x86_64 sub-type lists
2668 const int kX86_64_RowCount
= 2;
2669 static const cpu_subtype_t kX86_64
[kX86_64_RowCount
][5] = {
2671 // x86_64h can run: x86_64h, x86_64h(lib), x86_64(lib), and x86_64
2672 { 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
},
2674 // x86_64 can run: x86_64(lib) and x86_64
2675 { CPU_SUBTYPE_X86_64_ALL
, (cpu_subtype_t
)(CPU_SUBTYPE_LIB64
|CPU_SUBTYPE_X86_64_ALL
), CPU_SUBTYPE_END_OF_LIST
},
2681 // scan the tables above to find the cpu-sub-type-list for this machine
2682 static const cpu_subtype_t
* findCPUSubtypeList(cpu_type_t cpu
, cpu_subtype_t subtype
)
2687 for (int i
=0; i
< kARM_RowCount
; ++i
) {
2688 if ( kARM
[i
][0] == subtype
)
2694 case CPU_TYPE_ARM64
:
2695 for (int i
=0; i
< kARM64_RowCount
; ++i
) {
2696 if ( kARM64
[i
][0] == subtype
)
2701 #if __ARM64_ARCH_8_32__
2702 case CPU_TYPE_ARM64_32
:
2703 for (int i
=0; i
< kARM64_32_RowCount
; ++i
) {
2704 if ( kARM64_32
[i
][0] == subtype
)
2705 return kARM64_32
[i
];
2712 case CPU_TYPE_X86_64
:
2713 for (int i
=0; i
< kX86_64_RowCount
; ++i
) {
2714 if ( kX86_64
[i
][0] == subtype
)
2726 // scan fat table-of-contents for best most preferred subtype
2727 static bool fatFindBestFromOrderedList(cpu_type_t cpu
, const cpu_subtype_t list
[], const fat_header
* fh
, uint64_t* offset
, uint64_t* len
)
2729 const fat_arch
* const archs
= (fat_arch
*)(((char*)fh
)+sizeof(fat_header
));
2730 for (uint32_t subTypeIndex
=0; list
[subTypeIndex
] != CPU_SUBTYPE_END_OF_LIST
; ++subTypeIndex
) {
2731 for(uint32_t fatIndex
=0; fatIndex
< OSSwapBigToHostInt32(fh
->nfat_arch
); ++fatIndex
) {
2732 if ( ((cpu_type_t
)OSSwapBigToHostInt32(archs
[fatIndex
].cputype
) == cpu
)
2733 && (list
[subTypeIndex
] == (cpu_subtype_t
)OSSwapBigToHostInt32(archs
[fatIndex
].cpusubtype
)) ) {
2734 *offset
= OSSwapBigToHostInt32(archs
[fatIndex
].offset
);
2735 *len
= OSSwapBigToHostInt32(archs
[fatIndex
].size
);
2743 // scan fat table-of-contents for exact match of cpu and cpu-sub-type
2744 static bool fatFindExactMatch(cpu_type_t cpu
, cpu_subtype_t subtype
, const fat_header
* fh
, uint64_t* offset
, uint64_t* len
)
2746 const fat_arch
* archs
= (fat_arch
*)(((char*)fh
)+sizeof(fat_header
));
2747 for(uint32_t i
=0; i
< OSSwapBigToHostInt32(fh
->nfat_arch
); ++i
) {
2748 if ( ((cpu_type_t
)OSSwapBigToHostInt32(archs
[i
].cputype
) == cpu
)
2749 && ((cpu_subtype_t
)OSSwapBigToHostInt32(archs
[i
].cpusubtype
) == subtype
) ) {
2750 *offset
= OSSwapBigToHostInt32(archs
[i
].offset
);
2751 *len
= OSSwapBigToHostInt32(archs
[i
].size
);
2758 // scan fat table-of-contents for image with matching cpu-type and runs-on-all-sub-types
2759 static bool fatFindRunsOnAllCPUs(cpu_type_t cpu
, const fat_header
* fh
, uint64_t* offset
, uint64_t* len
)
2761 const fat_arch
* archs
= (fat_arch
*)(((char*)fh
)+sizeof(fat_header
));
2762 for(uint32_t i
=0; i
< OSSwapBigToHostInt32(fh
->nfat_arch
); ++i
) {
2763 if ( (cpu_type_t
)OSSwapBigToHostInt32(archs
[i
].cputype
) == cpu
) {
2767 if ( (cpu_subtype_t
)OSSwapBigToHostInt32(archs
[i
].cpusubtype
) == CPU_SUBTYPE_ARM_ALL
) {
2768 *offset
= OSSwapBigToHostInt32(archs
[i
].offset
);
2769 *len
= OSSwapBigToHostInt32(archs
[i
].size
);
2775 case CPU_TYPE_ARM64
:
2776 if ( (cpu_subtype_t
)OSSwapBigToHostInt32(archs
[i
].cpusubtype
) == CPU_SUBTYPE_ARM64_ALL
) {
2777 *offset
= OSSwapBigToHostInt32(archs
[i
].offset
);
2778 *len
= OSSwapBigToHostInt32(archs
[i
].size
);
2784 case CPU_TYPE_X86_64
:
2785 if ( (cpu_subtype_t
)OSSwapBigToHostInt32(archs
[i
].cpusubtype
) == CPU_SUBTYPE_X86_64_ALL
) {
2786 *offset
= OSSwapBigToHostInt32(archs
[i
].offset
);
2787 *len
= OSSwapBigToHostInt32(archs
[i
].size
);
2798 #endif // CPU_SUBTYPES_SUPPORTED
2802 // Validate the fat_header and fat_arch array:
2804 // 1) arch count would not cause array to extend past 4096 byte read buffer
2805 // 2) no slice overlaps the fat_header and arch array
2806 // 3) arch list does not contain duplicate cputype/cpusubtype tuples
2807 // 4) arch list does not have two overlapping slices.
2809 static bool fatValidate(const fat_header
* fh
)
2811 if ( fh
->magic
!= OSSwapBigToHostInt32(FAT_MAGIC
) )
2814 // since only first 4096 bytes of file read, we can only handle up to 204 slices.
2815 const uint32_t sliceCount
= OSSwapBigToHostInt32(fh
->nfat_arch
);
2816 if ( sliceCount
> 204 )
2819 // compare all slices looking for conflicts
2820 const fat_arch
* archs
= (fat_arch
*)(((char*)fh
)+sizeof(fat_header
));
2821 for (uint32_t i
=0; i
< sliceCount
; ++i
) {
2822 uint32_t i_offset
= OSSwapBigToHostInt32(archs
[i
].offset
);
2823 uint32_t i_size
= OSSwapBigToHostInt32(archs
[i
].size
);
2824 uint32_t i_cputype
= OSSwapBigToHostInt32(archs
[i
].cputype
);
2825 uint32_t i_cpusubtype
= OSSwapBigToHostInt32(archs
[i
].cpusubtype
);
2826 uint32_t i_end
= i_offset
+ i_size
;
2827 // slice cannot overlap with header
2828 if ( i_offset
< 4096 )
2830 // slice size cannot overflow
2831 if ( i_end
< i_offset
)
2833 for (uint32_t j
=i
+1; j
< sliceCount
; ++j
) {
2834 uint32_t j_offset
= OSSwapBigToHostInt32(archs
[j
].offset
);
2835 uint32_t j_size
= OSSwapBigToHostInt32(archs
[j
].size
);
2836 uint32_t j_cputype
= OSSwapBigToHostInt32(archs
[j
].cputype
);
2837 uint32_t j_cpusubtype
= OSSwapBigToHostInt32(archs
[j
].cpusubtype
);
2838 uint32_t j_end
= j_offset
+ j_size
;
2839 // duplicate slices types not allowed
2840 if ( (i_cputype
== j_cputype
) && (i_cpusubtype
== j_cpusubtype
) )
2842 // slice size cannot overflow
2843 if ( j_end
< j_offset
)
2845 // check for overlap of slices
2846 if ( i_offset
<= j_offset
) {
2847 if ( j_offset
< i_end
)
2848 return false; // j overlaps end of i
2851 // j overlaps end of i
2852 if ( i_offset
< j_end
)
2853 return false; // i overlaps end of j
2861 // A fat file may contain multiple sub-images for the same cpu-type,
2862 // each optimized for a different cpu-sub-type (e.g G3 or G5).
2863 // This routine picks the optimal sub-image.
2865 static bool fatFindBest(const fat_header
* fh
, uint64_t* offset
, uint64_t* len
)
2867 if ( !fatValidate(fh
) )
2870 #if CPU_SUBTYPES_SUPPORTED
2871 // assume all dylibs loaded must have same cpu type as main executable
2872 const cpu_type_t cpu
= sMainExecutableMachHeader
->cputype
;
2874 // We only know the subtype to use if the main executable cpu type matches the host
2875 if ( cpu
== sHostCPU
) {
2876 // get preference ordered list of subtypes
2877 const cpu_subtype_t
* subTypePreferenceList
= findCPUSubtypeList(cpu
, sHostCPUsubtype
);
2879 // use ordered list to find best sub-image in fat file
2880 if ( subTypePreferenceList
!= NULL
) {
2881 if ( fatFindBestFromOrderedList(cpu
, subTypePreferenceList
, fh
, offset
, len
) )
2885 // if running cpu is not in list, try for an exact match
2886 if ( fatFindExactMatch(cpu
, sHostCPUsubtype
, fh
, offset
, len
) )
2890 // running on an uknown cpu, can only load generic code
2891 return fatFindRunsOnAllCPUs(cpu
, fh
, offset
, len
);
2893 // just find first slice with matching architecture
2894 const fat_arch
* archs
= (fat_arch
*)(((char*)fh
)+sizeof(fat_header
));
2895 for(uint32_t i
=0; i
< OSSwapBigToHostInt32(fh
->nfat_arch
); ++i
) {
2896 if ( (cpu_type_t
)OSSwapBigToHostInt32(archs
[i
].cputype
) == sMainExecutableMachHeader
->cputype
) {
2897 *offset
= OSSwapBigToHostInt32(archs
[i
].offset
);
2898 *len
= OSSwapBigToHostInt32(archs
[i
].size
);
2909 // This is used to validate if a non-fat (aka thin or raw) mach-o file can be used
2910 // on the current processor. //
2911 bool isCompatibleMachO(const uint8_t* firstPage
, const char* path
)
2913 #if CPU_SUBTYPES_SUPPORTED
2914 // It is deemed compatible if any of the following are true:
2915 // 1) mach_header subtype is in list of compatible subtypes for running processor
2916 // 2) mach_header subtype is same as running processor subtype
2917 // 3) mach_header subtype runs on all processor variants
2918 const mach_header
* mh
= (mach_header
*)firstPage
;
2919 if ( mh
->magic
== sMainExecutableMachHeader
->magic
) {
2920 if ( mh
->cputype
== sMainExecutableMachHeader
->cputype
) {
2921 if ( mh
->cputype
== sHostCPU
) {
2922 // get preference ordered list of subtypes that this machine can use
2923 const cpu_subtype_t
* subTypePreferenceList
= findCPUSubtypeList(mh
->cputype
, sHostCPUsubtype
);
2924 if ( subTypePreferenceList
!= NULL
) {
2925 // if image's subtype is in the list, it is compatible
2926 for (const cpu_subtype_t
* p
= subTypePreferenceList
; *p
!= CPU_SUBTYPE_END_OF_LIST
; ++p
) {
2927 if ( *p
== mh
->cpusubtype
)
2930 // have list and not in list, so not compatible
2931 throwf("incompatible cpu-subtype: 0x%08X in %s", mh
->cpusubtype
, path
);
2933 // unknown cpu sub-type, but if exact match for current subtype then ok to use
2934 if ( mh
->cpusubtype
== sHostCPUsubtype
)
2938 // cpu type has no ordered list of subtypes
2939 switch (mh
->cputype
) {
2941 case CPU_TYPE_X86_64
:
2942 // subtypes are not used or these architectures
2948 // For architectures that don't support cpu-sub-types
2949 // this just check the cpu type.
2950 const mach_header
* mh
= (mach_header
*)firstPage
;
2951 if ( mh
->magic
== sMainExecutableMachHeader
->magic
) {
2952 if ( mh
->cputype
== sMainExecutableMachHeader
->cputype
) {
2963 // The kernel maps in main executable before dyld gets control. We need to
2964 // make an ImageLoader* for the already mapped in main executable.
2965 static ImageLoaderMachO
* instantiateFromLoadedImage(const macho_header
* mh
, uintptr_t slide
, const char* path
)
2967 // try mach-o loader
2968 if ( isCompatibleMachO((const uint8_t*)mh
, path
) ) {
2969 ImageLoader
* image
= ImageLoaderMachO::instantiateMainExecutable(mh
, slide
, path
, gLinkContext
);
2971 return (ImageLoaderMachO
*)image
;
2974 throw "main executable not a known format";
2977 #if SUPPORT_ACCELERATE_TABLES
2978 static bool dylibsCanOverrideCache()
2980 if ( !dyld3::internalInstall() )
2982 return ( (sSharedCacheLoadInfo
.loadAddress
!= nullptr) && (sSharedCacheLoadInfo
.loadAddress
->header
.cacheType
== kDyldSharedCacheTypeDevelopment
) );
2986 const void* imMemorySharedCacheHeader()
2988 return sSharedCacheLoadInfo
.loadAddress
;
2992 const char* getStandardSharedCacheFilePath()
2994 if ( sSharedCacheLoadInfo
.loadAddress
!= nullptr )
2995 return sSharedCacheLoadInfo
.path
;
3000 bool hasInsertedOrInterposingLibraries() {
3001 return (sInsertedDylibCount
> 0) || ImageLoader::haveInterposingTuples();
3005 #if SUPPORT_VERSIONED_PATHS
3006 static bool findInSharedCacheImage(const char* path
, bool searchByPath
, const struct stat
* stat_buf
, const macho_header
** mh
, const char** pathInCache
, long* slide
)
3008 dyld3::SharedCacheFindDylibResults results
;
3009 if ( dyld3::findInSharedCacheImage(sSharedCacheLoadInfo
, path
, &results
) ) {
3010 *mh
= (macho_header
*)results
.mhInCache
;
3011 *pathInCache
= results
.pathInCache
;
3012 *slide
= results
.slideInCache
;
3019 bool inSharedCache(const char* path
)
3021 return dyld3::pathIsInSharedCacheImage(sSharedCacheLoadInfo
, path
);
3025 static ImageLoader
* checkandAddImage(ImageLoader
* image
, const LoadContext
& context
)
3027 // now sanity check that this loaded image does not have the same install path as any existing image
3028 const char* loadedImageInstallPath
= image
->getInstallPath();
3029 if ( image
->isDylib() && (loadedImageInstallPath
!= NULL
) && (loadedImageInstallPath
[0] == '/') ) {
3030 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
3031 ImageLoader
* anImage
= *it
;
3032 const char* installPath
= anImage
->getInstallPath();
3033 if ( installPath
!= NULL
) {
3034 if ( strcmp(loadedImageInstallPath
, installPath
) == 0 ) {
3035 //dyld::log("duplicate(%s) => %p\n", installPath, anImage);
3037 ImageLoader::deleteImage(image
);
3044 // some API's restrict what they can load
3045 if ( context
.mustBeBundle
&& !image
->isBundle() )
3046 throw "not a bundle";
3047 if ( context
.mustBeDylib
&& !image
->isDylib() )
3048 throw "not a dylib";
3050 // regular main executables cannot be loaded
3051 if ( image
->isExecutable() ) {
3052 if ( !context
.canBePIE
|| !image
->isPositionIndependentExecutable() )
3053 throw "can't load a main executable";
3056 // don't add bundles to global list, they can be loaded but not linked. When linked it will be added to list
3057 if ( ! image
->isBundle() )
3063 #if TARGET_OS_SIMULATOR
3064 static bool isSimulatorBinary(const uint8_t* firstPages
, const char* path
)
3066 const macho_header
* mh
= (macho_header
*)firstPages
;
3067 const uint32_t cmd_count
= mh
->ncmds
;
3068 const load_command
* const cmds
= (struct load_command
*)(((char*)mh
)+sizeof(macho_header
));
3069 const load_command
* const cmdsEnd
= (load_command
*)((char*)cmds
+ mh
->sizeofcmds
);
3070 const struct load_command
* cmd
= cmds
;
3071 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
3074 case LC_VERSION_MIN_WATCHOS
:
3077 case LC_VERSION_MIN_TVOS
:
3080 case LC_VERSION_MIN_IPHONEOS
:
3083 case LC_VERSION_MIN_MACOSX
:
3084 // grandfather in a few libSystem dylibs
3085 if ((strcmp(path
, "/usr/lib/system/libsystem_kernel.dylib") == 0) ||
3086 (strcmp(path
, "/usr/lib/system/libsystem_platform.dylib") == 0) ||
3087 (strcmp(path
, "/usr/lib/system/libsystem_pthread.dylib") == 0) ||
3088 (strcmp(path
, "/usr/lib/system/libsystem_platform_debug.dylib") == 0) ||
3089 (strcmp(path
, "/usr/lib/system/libsystem_pthread_debug.dylib") == 0) ||
3090 (strcmp(path
, "/sbin/launchd_sim_trampoline") == 0) ||
3091 (strcmp(path
, "/usr/sbin/iokitsimd") == 0) ||
3092 (strcmp(path
, "/usr/lib/system/host/liblaunch_sim.dylib") == 0))
3095 case LC_BUILD_VERSION
:
3097 // Same logic as above, but for LC_BUILD_VERSION instead of legacy load commands
3098 const struct build_version_command
* buildVersionCmd
= (build_version_command
*)cmd
;
3099 switch(buildVersionCmd
->platform
) {
3100 case PLATFORM_IOSSIMULATOR
:
3101 case PLATFORM_TVOSSIMULATOR
:
3102 case PLATFORM_WATCHOSSIMULATOR
:
3103 case PLATFORM_WATCHOS
:
3105 #if TARGET_OS_IOSMAC
3109 case PLATFORM_MACOS
:
3110 if ((strcmp(path
, "/usr/lib/system/libsystem_kernel.dylib") == 0) ||
3111 (strcmp(path
, "/usr/lib/system/libsystem_platform.dylib") == 0) ||
3112 (strcmp(path
, "/usr/lib/system/libsystem_pthread.dylib") == 0) ||
3113 (strcmp(path
, "/usr/lib/system/libsystem_platform_debug.dylib") == 0) ||
3114 (strcmp(path
, "/usr/lib/system/libsystem_pthread_debug.dylib") == 0) ||
3115 (strcmp(path
, "/sbin/launchd_sim_trampoline") == 0) ||
3116 (strcmp(path
, "/usr/sbin/iokitsimd") == 0) ||
3117 (strcmp(path
, "/usr/lib/system/host/liblaunch_sim.dylib") == 0))
3122 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
3123 if ( cmd
> cmdsEnd
)
3130 #if __MAC_OS_X_VERSION_MIN_REQUIRED
3131 static bool iOSonMacDenied(const char* path
)
3133 static char* blackListBuffer
= nullptr;
3134 static size_t blackListSize
= 0;
3135 static bool tried
= false;
3137 // only try to map file once
3138 blackListBuffer
= (char*)mapFileReadOnly("/System/iOSSupport/dyld/macOS-deny-list.txt", blackListSize
);
3141 __block
bool result
= false;
3142 if ( blackListBuffer
!= nullptr ) {
3143 dyld3::forEachLineInFile(blackListBuffer
, blackListSize
, ^(const char* line
, bool& stop
) {
3144 // lines in the file are prefixes. Any path that starts with one of these lines is allowed to be unzippered
3145 size_t lineLen
= strlen(line
);
3146 if ( (*line
== '/') && strncmp(line
, path
, lineLen
) == 0 ) {
3156 // map in file and instantiate an ImageLoader
3157 static ImageLoader
* loadPhase6(int fd
, const struct stat
& stat_buf
, const char* path
, const LoadContext
& context
)
3159 //dyld::log("%s(%s)\n", __func__ , path);
3160 uint64_t fileOffset
= 0;
3161 uint64_t fileLength
= stat_buf
.st_size
;
3163 // validate it is a file (not directory)
3164 if ( (stat_buf
.st_mode
& S_IFMT
) != S_IFREG
)
3167 uint8_t firstPages
[MAX_MACH_O_HEADER_AND_LOAD_COMMANDS_SIZE
];
3168 uint8_t *firstPagesPtr
= firstPages
;
3169 bool shortPage
= false;
3171 // min mach-o file is 4K
3172 if ( fileLength
< 4096 ) {
3173 if ( pread(fd
, firstPages
, (size_t)fileLength
, 0) != (ssize_t
)fileLength
)
3174 throwf("pread of short file failed: %d", errno
);
3178 // optimistically read only first 4KB
3179 if ( pread(fd
, firstPages
, 4096, 0) != 4096 )
3180 throwf("pread of first 4K failed: %d", errno
);
3183 // if fat wrapper, find usable sub-file
3184 const fat_header
* fileStartAsFat
= (fat_header
*)firstPages
;
3185 if ( fileStartAsFat
->magic
== OSSwapBigToHostInt32(FAT_MAGIC
) ) {
3186 if ( OSSwapBigToHostInt32(fileStartAsFat
->nfat_arch
) > ((4096 - sizeof(fat_header
)) / sizeof(fat_arch
)) )
3187 throwf("fat header too large: %u entries", OSSwapBigToHostInt32(fileStartAsFat
->nfat_arch
));
3188 if ( fatFindBest(fileStartAsFat
, &fileOffset
, &fileLength
) ) {
3189 if ( (fileOffset
+fileLength
) > (uint64_t)(stat_buf
.st_size
) )
3190 throwf("truncated fat file. file length=%llu, but needed slice goes to %llu", stat_buf
.st_size
, fileOffset
+fileLength
);
3191 if (pread(fd
, firstPages
, 4096, fileOffset
) != 4096)
3192 throwf("pread of fat file failed: %d", errno
);
3195 throw "no matching architecture in universal wrapper";
3199 // try mach-o loader
3201 throw "file too short";
3203 if ( isCompatibleMachO(firstPages
, path
) ) {
3205 // only MH_BUNDLE, MH_DYLIB, and some MH_EXECUTE can be dynamically loaded
3206 const mach_header
* mh
= (mach_header
*)firstPages
;
3207 switch ( mh
->filetype
) {
3213 throw "mach-o, but wrong filetype";
3216 uint32_t headerAndLoadCommandsSize
= sizeof(macho_header
) + mh
->sizeofcmds
;
3217 if ( headerAndLoadCommandsSize
> MAX_MACH_O_HEADER_AND_LOAD_COMMANDS_SIZE
)
3218 throwf("malformed mach-o: load commands size (%u) > %u", headerAndLoadCommandsSize
, MAX_MACH_O_HEADER_AND_LOAD_COMMANDS_SIZE
);
3220 if ( headerAndLoadCommandsSize
> fileLength
)
3221 dyld::throwf("malformed mach-o: load commands size (%u) > mach-o file size (%llu)", headerAndLoadCommandsSize
, fileLength
);
3223 if ( headerAndLoadCommandsSize
> 4096 ) {
3225 unsigned readAmount
= headerAndLoadCommandsSize
- 4096;
3226 if ( pread(fd
, &firstPages
[4096], readAmount
, fileOffset
+4096) != readAmount
)
3227 throwf("pread of extra load commands past 4KB failed: %d", errno
);
3230 #if TARGET_OS_SIMULATOR
3231 // <rdar://problem/14168872> dyld_sim should restrict loading osx binaries
3232 if ( !isSimulatorBinary(firstPages
, path
) ) {
3234 throw "mach-o, but not built for watchOS simulator";
3236 throw "mach-o, but not built for tvOS simulator";
3238 throw "mach-o, but not built for iOS simulator";
3243 #if __MAC_OS_X_VERSION_MIN_REQUIRED
3244 if ( gLinkContext
.iOSonMac
) {
3245 const dyld3::MachOFile
* mf
= (dyld3::MachOFile
*)firstPages
;
3246 bool supportsiOSMac
= mf
->supportsPlatform(dyld3::Platform::iOSMac
);
3247 if ( !supportsiOSMac
&& iOSonMacDenied(path
) ) {
3248 throw "mach-o, but not built for UIKitForMac";
3251 else if ( gLinkContext
.driverKit
) {
3252 const dyld3::MachOFile
* mf
= (dyld3::MachOFile
*)firstPages
;
3253 bool isDriverKitDylib
= mf
->supportsPlatform(dyld3::Platform::driverKit
);
3254 if ( !isDriverKitDylib
) {
3255 throw "mach-o, but not built for driverkit";
3261 if ( (sMainExecutableMachHeader
->cpusubtype
== CPU_SUBTYPE_ARM64E
) && (mh
->cpusubtype
!= CPU_SUBTYPE_ARM64E
) )
3262 throw "arm64 dylibs cannot be loaded into arm64e processes";
3264 ImageLoader
* image
= nullptr;
3266 dyld3::ScopedTimer
timer(DBG_DYLD_TIMING_MAP_IMAGE
, path
, 0, 0);
3267 image
= ImageLoaderMachO::instantiateFromFile(path
, fd
, firstPagesPtr
, headerAndLoadCommandsSize
, fileOffset
, fileLength
, stat_buf
, gLinkContext
);
3268 timer
.setData4((uint64_t)image
->machHeader());
3272 return checkandAddImage(image
, context
);
3275 // try other file formats here...
3278 // throw error about what was found
3279 switch (*(uint32_t*)firstPages
) {
3284 throw "mach-o, but wrong architecture";
3286 throwf("unknown file type, first eight bytes: 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X",
3287 firstPages
[0], firstPages
[1], firstPages
[2], firstPages
[3], firstPages
[4], firstPages
[5], firstPages
[6],firstPages
[7]);
3292 static ImageLoader
* loadPhase5open(const char* path
, const LoadContext
& context
, const struct stat
& stat_buf
, std::vector
<const char*>* exceptions
)
3294 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
3296 // open file (automagically closed when this function exits)
3297 FileOpener
file(path
);
3299 // just return NULL if file not found, but record any other errors
3300 if ( file
.getFileDescriptor() == -1 ) {
3302 if ( err
!= ENOENT
) {
3304 if ( (err
== EPERM
) && sandboxBlockedOpen(path
) )
3305 newMsg
= dyld::mkstringf("file system sandbox blocked open() of '%s'", path
);
3307 newMsg
= dyld::mkstringf("%s: open() failed with errno=%d", path
, err
);
3308 exceptions
->push_back(newMsg
);
3314 return loadPhase6(file
.getFileDescriptor(), stat_buf
, path
, context
);
3316 catch (const char* msg
) {
3317 const char* newMsg
= dyld::mkstringf("%s: %s", path
, msg
);
3318 exceptions
->push_back(newMsg
);
3324 static bool isFileRelativePath(const char* path
)
3326 if ( path
[0] == '/' )
3328 if ( path
[0] != '.' )
3330 if ( path
[1] == '/' )
3332 if ( (path
[1] == '.') && (path
[2] == '/') )
3339 static ImageLoader
* loadPhase5load(const char* path
, const char* orgPath
, const LoadContext
& context
, unsigned& cacheIndex
, std::vector
<const char*>* exceptions
)
3341 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
3343 // <rdar://problem/47682983> don't allow file system relative paths in hardened programs
3344 if ( (exceptions
!= NULL
) && !gLinkContext
.allowEnvVarsPath
&& isFileRelativePath(path
) ) {
3345 exceptions
->push_back("file system relative paths not allowed in hardened programs");
3349 #if SUPPORT_ACCELERATE_TABLES
3350 if ( sAllCacheImagesProxy
!= NULL
) {
3351 if ( sAllCacheImagesProxy
->hasDylib(path
, &cacheIndex
) )
3352 return sAllCacheImagesProxy
;
3355 #if TARGET_OS_SIMULATOR
3356 // in simulators, 'path' has DYLD_ROOT_PATH prepended, but cache index does not have the prefix, so use orgPath
3357 const char* pathToFindInCache
= orgPath
;
3359 const char* pathToFindInCache
= path
;
3362 struct stat statBuf
;
3363 bool didStat
= false;
3365 dyld3::SharedCacheFindDylibResults shareCacheResults
;
3366 shareCacheResults
.image
= nullptr;
3367 if ( dyld3::findInSharedCacheImage(sSharedCacheLoadInfo
, pathToFindInCache
, &shareCacheResults
) ) {
3368 // see if this image in the cache was already loaded via a different path
3369 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); ++it
) {
3370 ImageLoader
* anImage
= *it
;
3371 if ( (const mach_header
*)anImage
->machHeader() == shareCacheResults
.mhInCache
)
3374 // if RTLD_NOLOAD, do nothing if not already loaded
3375 if ( context
.dontLoad
) {
3376 // <rdar://33412890> possible that there is an override of cache
3377 if ( my_stat(path
, &statBuf
) == 0 ) {
3378 ImageLoader
* imageLoader
= findLoadedImage(statBuf
);
3379 if ( imageLoader
!= NULL
)
3384 bool useCache
= false;
3385 if ( shareCacheResults
.image
== nullptr ) {
3386 // HACK to support old caches
3387 existsOnDisk
= ( my_stat(path
, &statBuf
) == 0 );
3390 useCache
= !existsOnDisk
;
3393 // <rdar://problem/7014995> zero out stat buffer so mtime, etc are zero for items from the shared cache
3394 bzero(&statBuf
, sizeof(statBuf
));
3395 if ( shareCacheResults
.image
->overridableDylib() ) {
3396 existsOnDisk
= ( my_stat(path
, &statBuf
) == 0 );
3399 if ( sSharedCacheLoadInfo
.loadAddress
->header
.dylibsExpectedOnDisk
) {
3400 uint64_t expectedINode
;
3401 uint64_t expectedMtime
;
3402 if ( shareCacheResults
.image
->hasFileModTimeAndInode(expectedINode
, expectedMtime
) ) {
3403 if ( (expectedMtime
== statBuf
.st_mtime
) && (expectedINode
== statBuf
.st_ino
) )
3408 if ( !existsOnDisk
)
3417 #if __MAC_OS_X_VERSION_MIN_REQUIRED
3418 if ( gLinkContext
.iOSonMac
) {
3419 const dyld3::MachOFile
* mf
= (dyld3::MachOFile
*)shareCacheResults
.mhInCache
;
3420 bool supportsiOSMac
= mf
->supportsPlatform(dyld3::Platform::iOSMac
);
3421 if ( !supportsiOSMac
&& iOSonMacDenied(path
) ) {
3422 throw "mach-o, but not built for UIKitForMac";
3426 ImageLoader
* imageLoader
= ImageLoaderMachO::instantiateFromCache((macho_header
*)shareCacheResults
.mhInCache
, shareCacheResults
.pathInCache
, shareCacheResults
.slideInCache
, statBuf
, gLinkContext
);
3427 return checkandAddImage(imageLoader
, context
);
3431 // not in cache or cache not usable
3433 existsOnDisk
= ( my_stat(path
, &statBuf
) == 0 );
3436 if ( existsOnDisk
) {
3437 // in case image was renamed or found via symlinks, check for inode match
3438 ImageLoader
* imageLoader
= findLoadedImage(statBuf
);
3439 if ( imageLoader
!= NULL
)
3441 // do nothing if not already loaded and if RTLD_NOLOAD
3442 if ( context
.dontLoad
)
3445 imageLoader
= loadPhase5open(path
, context
, statBuf
, exceptions
);
3446 if ( imageLoader
!= NULL
) {
3447 if ( shareCacheResults
.image
!= nullptr ) {
3448 // if image was found in cache, but is overridden by a newer file on disk, record what the image overrides
3449 imageLoader
->setOverridesCachedDylib(shareCacheResults
.image
->imageNum());
3455 // just return NULL if file not found, but record any other errors
3456 if ( (statErrNo
!= ENOENT
) && (statErrNo
!= 0) ) {
3457 if ( (statErrNo
== EPERM
) && sandboxBlockedStat(path
) )
3458 exceptions
->push_back(dyld::mkstringf("%s: file system sandbox blocked stat()", path
));
3460 exceptions
->push_back(dyld::mkstringf("%s: stat() failed with errno=%d", path
, statErrNo
));
3465 // look for path match with existing loaded images
3466 static ImageLoader
* loadPhase5check(const char* path
, const char* orgPath
, const LoadContext
& context
)
3468 //dyld::log("%s(%s, %s)\n", __func__ , path, orgPath);
3469 // search path against load-path and install-path of all already loaded images
3470 uint32_t hash
= ImageLoader::hash(path
);
3471 //dyld::log("check() hash=%d, path=%s\n", hash, path);
3472 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
3473 ImageLoader
* anImage
= *it
;
3474 // check hash first to cut down on strcmp calls
3475 //dyld::log(" check() hash=%d, path=%s\n", anImage->getPathHash(), anImage->getPath());
3476 if ( anImage
->getPathHash() == hash
) {
3477 if ( strcmp(path
, anImage
->getPath()) == 0 ) {
3478 // if we are looking for a dylib don't return something else
3479 if ( !context
.mustBeDylib
|| anImage
->isDylib() )
3483 if ( context
.matchByInstallName
|| anImage
->matchInstallPath() ) {
3484 const char* installPath
= anImage
->getInstallPath();
3485 if ( installPath
!= NULL
) {
3486 if ( strcmp(path
, installPath
) == 0 ) {
3487 // if we are looking for a dylib don't return something else
3488 if ( !context
.mustBeDylib
|| anImage
->isDylib() )
3493 // an install name starting with @rpath should match by install name, not just real path
3494 if ( (orgPath
[0] == '@') && (strncmp(orgPath
, "@rpath/", 7) == 0) ) {
3495 const char* installPath
= anImage
->getInstallPath();
3496 if ( installPath
!= NULL
) {
3497 if ( !context
.mustBeDylib
|| anImage
->isDylib() ) {
3498 if ( strcmp(orgPath
, installPath
) == 0 )
3505 //dyld::log("%s(%s) => NULL\n", __func__, path);
3510 // open or check existing
3511 static ImageLoader
* loadPhase5(const char* path
, const char* orgPath
, const LoadContext
& context
, unsigned& cacheIndex
, std::vector
<const char*>* exceptions
)
3513 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
3515 // check for specific dylib overrides
3516 for (std::vector
<DylibOverride
>::iterator it
= sDylibOverrides
.begin(); it
!= sDylibOverrides
.end(); ++it
) {
3517 if ( strcmp(it
->installName
, path
) == 0 ) {
3518 path
= it
->override
;
3523 if ( exceptions
!= NULL
)
3524 return loadPhase5load(path
, orgPath
, context
, cacheIndex
, exceptions
);
3526 return loadPhase5check(path
, orgPath
, context
);
3529 // try with and without image suffix
3530 static ImageLoader
* loadPhase4(const char* path
, const char* orgPath
, const LoadContext
& context
, unsigned& cacheIndex
, std::vector
<const char*>* exceptions
)
3532 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
3533 ImageLoader
* image
= NULL
;
3534 if ( gLinkContext
.imageSuffix
!= NULL
) {
3535 for (const char* const* suffix
=gLinkContext
.imageSuffix
; *suffix
!= NULL
; ++suffix
) {
3536 char pathWithSuffix
[strlen(path
)+strlen(*suffix
)+2];
3537 ImageLoader::addSuffix(path
, *suffix
, pathWithSuffix
);
3538 image
= loadPhase5(pathWithSuffix
, orgPath
, context
, cacheIndex
, exceptions
);
3539 if ( image
!= NULL
)
3542 if ( image
!= NULL
) {
3543 // if original path is in the dyld cache, then mark this one found as an override
3544 dyld3::SharedCacheFindDylibResults shareCacheResults
;
3545 if ( dyld3::findInSharedCacheImage(sSharedCacheLoadInfo
, path
, &shareCacheResults
) && (shareCacheResults
.image
!= nullptr) )
3546 image
->setOverridesCachedDylib(shareCacheResults
.image
->imageNum());
3549 if ( image
== NULL
)
3550 image
= loadPhase5(path
, orgPath
, context
, cacheIndex
, exceptions
);
3554 static ImageLoader
* loadPhase2(const char* path
, const char* orgPath
, const LoadContext
& context
,
3555 const char* const frameworkPaths
[], const char* const libraryPaths
[],
3556 unsigned& cacheIndex
, std::vector
<const char*>* exceptions
); // forward reference
3559 // expand @ variables
3560 static ImageLoader
* loadPhase3(const char* path
, const char* orgPath
, const LoadContext
& context
, unsigned& cacheIndex
, std::vector
<const char*>* exceptions
)
3562 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
3563 ImageLoader
* image
= NULL
;
3564 if ( strncmp(path
, "@executable_path/", 17) == 0 ) {
3565 // executable_path cannot be in used in any binary in a setuid process rdar://problem/4589305
3566 if ( !gLinkContext
.allowAtPaths
)
3567 throwf("unsafe use of @executable_path in %s with restricted binary (Codesign main executable with Library Validation to allow @ paths)", context
.origin
);
3568 // handle @executable_path path prefix
3569 const char* executablePath
= sExecPath
;
3570 char newPath
[strlen(executablePath
) + strlen(path
)];
3571 strcpy(newPath
, executablePath
);
3572 char* addPoint
= strrchr(newPath
,'/');
3573 if ( addPoint
!= NULL
)
3574 strcpy(&addPoint
[1], &path
[17]);
3576 strcpy(newPath
, &path
[17]);
3577 image
= loadPhase4(newPath
, orgPath
, context
, cacheIndex
, exceptions
);
3578 if ( image
!= NULL
)
3581 // perhaps main executable path is a sym link, find realpath and retry
3582 char resolvedPath
[PATH_MAX
];
3583 if ( realpath(sExecPath
, resolvedPath
) != NULL
) {
3584 char newRealPath
[strlen(resolvedPath
) + strlen(path
)];
3585 strcpy(newRealPath
, resolvedPath
);
3586 addPoint
= strrchr(newRealPath
,'/');
3587 if ( addPoint
!= NULL
)
3588 strcpy(&addPoint
[1], &path
[17]);
3590 strcpy(newRealPath
, &path
[17]);
3591 image
= loadPhase4(newRealPath
, orgPath
, context
, cacheIndex
, exceptions
);
3592 if ( image
!= NULL
)
3596 else if ( (strncmp(path
, "@loader_path/", 13) == 0) && (context
.origin
!= NULL
) ) {
3597 // @loader_path cannot be used from the main executable of a setuid process rdar://problem/4589305
3598 if ( !gLinkContext
.allowAtPaths
&& (strcmp(context
.origin
, sExecPath
) == 0) )
3599 throwf("unsafe use of @loader_path in %s with restricted binary (Codesign main executable with Library Validation to allow @ paths)", context
.origin
);
3600 // handle @loader_path path prefix
3601 char newPath
[strlen(context
.origin
) + strlen(path
)];
3602 strcpy(newPath
, context
.origin
);
3603 char* addPoint
= strrchr(newPath
,'/');
3604 if ( addPoint
!= NULL
)
3605 strcpy(&addPoint
[1], &path
[13]);
3607 strcpy(newPath
, &path
[13]);
3608 image
= loadPhase4(newPath
, orgPath
, context
, cacheIndex
, exceptions
);
3609 if ( image
!= NULL
)
3612 // perhaps loader path is a sym link, find realpath and retry
3613 char resolvedPath
[PATH_MAX
];
3614 if ( realpath(context
.origin
, resolvedPath
) != NULL
) {
3615 char newRealPath
[strlen(resolvedPath
) + strlen(path
)];
3616 strcpy(newRealPath
, resolvedPath
);
3617 addPoint
= strrchr(newRealPath
,'/');
3618 if ( addPoint
!= NULL
)
3619 strcpy(&addPoint
[1], &path
[13]);
3621 strcpy(newRealPath
, &path
[13]);
3622 image
= loadPhase4(newRealPath
, orgPath
, context
, cacheIndex
, exceptions
);
3623 if ( image
!= NULL
)
3627 else if ( context
.implicitRPath
|| (strncmp(path
, "@rpath/", 7) == 0) ) {
3628 const char* trailingPath
= (strncmp(path
, "@rpath/", 7) == 0) ? &path
[7] : path
;
3629 // substitute @rpath with all -rpath paths up the load chain
3630 for(const ImageLoader::RPathChain
* rp
=context
.rpath
; rp
!= NULL
; rp
=rp
->next
) {
3631 if (rp
->paths
!= NULL
) {
3632 for(std::vector
<const char*>::iterator it
=rp
->paths
->begin(); it
!= rp
->paths
->end(); ++it
) {
3633 const char* anRPath
= *it
;
3634 char newPath
[strlen(anRPath
) + strlen(trailingPath
)+2];
3635 strcpy(newPath
, anRPath
);
3636 if ( newPath
[strlen(newPath
)-1] != '/' )
3637 strcat(newPath
, "/");
3638 strcat(newPath
, trailingPath
);
3639 image
= loadPhase4(newPath
, orgPath
, context
, cacheIndex
, exceptions
);
3640 if ( gLinkContext
.verboseRPaths
&& (exceptions
!= NULL
) ) {
3641 if ( image
!= NULL
)
3642 dyld::log("RPATH successful expansion of %s to: %s\n", orgPath
, newPath
);
3644 dyld::log("RPATH failed expanding %s to: %s\n", orgPath
, newPath
);
3646 if ( image
!= NULL
)
3652 // substitute @rpath with LD_LIBRARY_PATH
3653 if ( sEnv
.LD_LIBRARY_PATH
!= NULL
) {
3654 image
= loadPhase2(trailingPath
, orgPath
, context
, NULL
, sEnv
.LD_LIBRARY_PATH
, cacheIndex
, exceptions
);
3655 if ( image
!= NULL
)
3659 // if this is the "open" pass, don't try to open @rpath/... as a relative path
3660 if ( (exceptions
!= NULL
) && (trailingPath
!= path
) )
3663 else if ( !gLinkContext
.allowEnvVarsPath
&& (path
[0] != '/' ) ) {
3664 throwf("unsafe use of relative rpath %s in %s with restricted binary", path
, context
.origin
);
3667 return loadPhase4(path
, orgPath
, context
, cacheIndex
, exceptions
);
3670 static ImageLoader
* loadPhase2cache(const char* path
, const char *orgPath
, const LoadContext
& context
, unsigned& cacheIndex
, std::vector
<const char*>* exceptions
) {
3671 ImageLoader
* image
= NULL
;
3672 #if !TARGET_OS_SIMULATOR
3673 if ( (exceptions
!= NULL
) && (gLinkContext
.allowEnvVarsPath
|| !isFileRelativePath(path
)) && (path
[0] != '@') ) {
3674 char resolvedPath
[PATH_MAX
];
3675 realpath(path
, resolvedPath
);
3677 // If realpath() resolves to a path which does not exist on disk, errno is set to ENOENT
3678 if ( (myerr
== ENOENT
) || (myerr
== 0) )
3680 image
= loadPhase4(resolvedPath
, orgPath
, context
, cacheIndex
, exceptions
);
3689 static ImageLoader
* loadPhase2(const char* path
, const char* orgPath
, const LoadContext
& context
,
3690 const char* const frameworkPaths
[], const char* const libraryPaths
[],
3691 unsigned& cacheIndex
, std::vector
<const char*>* exceptions
)
3693 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
3694 ImageLoader
* image
= NULL
;
3695 const char* frameworkPartialPath
= getFrameworkPartialPath(path
);
3696 if ( frameworkPaths
!= NULL
) {
3697 if ( frameworkPartialPath
!= NULL
) {
3698 const size_t frameworkPartialPathLen
= strlen(frameworkPartialPath
);
3699 for(const char* const* fp
= frameworkPaths
; *fp
!= NULL
; ++fp
) {
3700 char npath
[strlen(*fp
)+frameworkPartialPathLen
+8];
3703 strcat(npath
, frameworkPartialPath
);
3704 //dyld::log("dyld: fallback framework path used: %s() -> loadPhase4(\"%s\", ...)\n", __func__, npath);
3705 image
= loadPhase4(npath
, orgPath
, context
, cacheIndex
, exceptions
);
3706 // Look in the cache if appropriate
3708 image
= loadPhase2cache(npath
, orgPath
, context
, cacheIndex
, exceptions
);
3709 if ( image
!= NULL
) {
3710 // if original path is in the dyld cache, then mark this one found as an override
3711 dyld3::SharedCacheFindDylibResults shareCacheResults
;
3712 if ( dyld3::findInSharedCacheImage(sSharedCacheLoadInfo
, path
, &shareCacheResults
) && (shareCacheResults
.image
!= nullptr) )
3713 image
->setOverridesCachedDylib(shareCacheResults
.image
->imageNum());
3719 // <rdar://problem/12649639> An executable with the same name as a framework & DYLD_LIBRARY_PATH pointing to it gets loaded twice
3720 // <rdar://problem/14160846> Some apps depend on frameworks being found via library paths
3721 if ( (libraryPaths
!= NULL
) && ((frameworkPartialPath
== NULL
) || sFrameworksFoundAsDylibs
) ) {
3722 const char* libraryLeafName
= getLibraryLeafName(path
);
3723 const size_t libraryLeafNameLen
= strlen(libraryLeafName
);
3724 for(const char* const* lp
= libraryPaths
; *lp
!= NULL
; ++lp
) {
3725 char libpath
[strlen(*lp
)+libraryLeafNameLen
+8];
3726 strcpy(libpath
, *lp
);
3727 strcat(libpath
, "/");
3728 strcat(libpath
, libraryLeafName
);
3729 //dyld::log("dyld: fallback library path used: %s() -> loadPhase4(\"%s\", ...)\n", __func__, libpath);
3730 image
= loadPhase4(libpath
, orgPath
, context
, cacheIndex
, exceptions
);
3731 // Look in the cache if appropriate
3733 image
= loadPhase2cache(libpath
, orgPath
, context
, cacheIndex
, exceptions
);
3734 if ( image
!= NULL
) {
3735 // if original path is in the dyld cache, then mark this one found as an override
3736 dyld3::SharedCacheFindDylibResults shareCacheResults
;
3737 if ( dyld3::findInSharedCacheImage(sSharedCacheLoadInfo
, path
, &shareCacheResults
) && (shareCacheResults
.image
!= nullptr) )
3738 image
->setOverridesCachedDylib(shareCacheResults
.image
->imageNum());
3746 // try search overrides and fallbacks
3747 static ImageLoader
* loadPhase1(const char* path
, const char* orgPath
, const LoadContext
& context
, unsigned& cacheIndex
, std::vector
<const char*>* exceptions
)
3749 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
3750 ImageLoader
* image
= NULL
;
3752 bool pathIsInDyldCacheWhichCannotBeOverridden
= false;
3753 if ( sSharedCacheLoadInfo
.loadAddress
!= nullptr ) {
3754 pathIsInDyldCacheWhichCannotBeOverridden
= sSharedCacheLoadInfo
.loadAddress
->hasNonOverridablePath(path
);
3757 // <rdar://problem/48490116> dyld customer cache cannot be overridden
3758 if ( !pathIsInDyldCacheWhichCannotBeOverridden
) {
3759 // handle LD_LIBRARY_PATH environment variables that force searching
3760 if ( context
.useLdLibraryPath
&& (sEnv
.LD_LIBRARY_PATH
!= NULL
) ) {
3761 image
= loadPhase2(path
, orgPath
, context
, NULL
, sEnv
.LD_LIBRARY_PATH
, cacheIndex
,exceptions
);
3762 if ( image
!= NULL
)
3766 // handle DYLD_ environment variables that force searching
3767 if ( context
.useSearchPaths
&& ((sEnv
.DYLD_FRAMEWORK_PATH
!= NULL
) || (sEnv
.DYLD_LIBRARY_PATH
!= NULL
)) ) {
3768 image
= loadPhase2(path
, orgPath
, context
, sEnv
.DYLD_FRAMEWORK_PATH
, sEnv
.DYLD_LIBRARY_PATH
, cacheIndex
, exceptions
);
3769 if ( image
!= NULL
)
3775 image
= loadPhase3(path
, orgPath
, context
, cacheIndex
, exceptions
);
3776 if ( image
!= NULL
)
3779 // try fallback paths during second time (will open file)
3780 const char* const* fallbackLibraryPaths
= sEnv
.DYLD_FALLBACK_LIBRARY_PATH
;
3781 if ( (fallbackLibraryPaths
!= NULL
) && !context
.useFallbackPaths
)
3782 fallbackLibraryPaths
= NULL
;
3783 if ( !context
.dontLoad
&& (exceptions
!= NULL
) && ((sEnv
.DYLD_FALLBACK_FRAMEWORK_PATH
!= NULL
) || (fallbackLibraryPaths
!= NULL
)) ) {
3784 image
= loadPhase2(path
, orgPath
, context
, sEnv
.DYLD_FALLBACK_FRAMEWORK_PATH
, fallbackLibraryPaths
, cacheIndex
, exceptions
);
3785 if ( image
!= NULL
)
3789 // <rdar://problem/47682983> if hardened app calls dlopen() with a leaf path, dyld should only look in /usr/lib
3790 if ( context
.useLdLibraryPath
&& (fallbackLibraryPaths
== NULL
) ) {
3791 const char* stdPaths
[2] = { "/usr/lib", NULL
};
3792 image
= loadPhase2(path
, orgPath
, context
, NULL
, stdPaths
, cacheIndex
, exceptions
);
3793 if ( image
!= NULL
)
3800 // try root substitutions
3801 static ImageLoader
* loadPhase0(const char* path
, const char* orgPath
, const LoadContext
& context
, unsigned& cacheIndex
, std::vector
<const char*>* exceptions
)
3803 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
3805 #if __MAC_OS_X_VERSION_MIN_REQUIRED
3806 // handle macOS dylibs dlopen()ing versioned path which needs to map to flat path in mazipan simulator
3807 if ( gLinkContext
.iOSonMac
&& strstr(path
, ".framework/Versions/")) {
3808 uintptr_t sourceOffset
= 0;
3809 uintptr_t destOffset
= 0;
3810 size_t sourceLangth
= strlen(path
);
3811 char flatPath
[sourceLangth
];
3813 const char* frameworkBase
= NULL
;
3814 while ((frameworkBase
= strstr(&path
[sourceOffset
], ".framework/Versions/"))) {
3815 uintptr_t foundLength
= (frameworkBase
- &path
[sourceOffset
]) + strlen(".framework/") ;
3816 strlcat(&flatPath
[destOffset
], &path
[sourceOffset
], foundLength
);
3817 sourceOffset
+= foundLength
+ strlen("Versions/") + 1;
3818 destOffset
+= foundLength
- 1;
3820 strlcat(&flatPath
[destOffset
], &path
[sourceOffset
], sourceLangth
);
3821 ImageLoader
* image
= loadPhase0(flatPath
, orgPath
, context
, cacheIndex
, exceptions
);
3822 if ( image
!= NULL
)
3827 #if SUPPORT_ROOT_PATH
3828 // handle DYLD_ROOT_PATH which forces absolute paths to use a new root
3829 if ( (gLinkContext
.rootPaths
!= NULL
) && (path
[0] == '/') ) {
3830 for(const char* const* rootPath
= gLinkContext
.rootPaths
; *rootPath
!= NULL
; ++rootPath
) {
3831 size_t rootLen
= strlen(*rootPath
);
3832 if ( strncmp(path
, *rootPath
, rootLen
) != 0 ) {
3833 char newPath
[rootLen
+ strlen(path
)+2];
3834 strcpy(newPath
, *rootPath
);
3835 strcat(newPath
, path
);
3836 ImageLoader
* image
= loadPhase1(newPath
, orgPath
, context
, cacheIndex
, exceptions
);
3837 if ( image
!= NULL
)
3845 return loadPhase1(path
, orgPath
, context
, cacheIndex
, exceptions
);
3849 // Given all the DYLD_ environment variables, the general case for loading libraries
3850 // is that any given path expands into a list of possible locations to load. We
3851 // also must take care to ensure two copies of the "same" library are never loaded.
3853 // The algorithm used here is that there is a separate function for each "phase" of the
3854 // path expansion. Each phase function calls the next phase with each possible expansion
3855 // of that phase. The result is the last phase is called with all possible paths.
3857 // To catch duplicates the algorithm is run twice. The first time, the last phase checks
3858 // the path against all loaded images. The second time, the last phase calls open() on
3859 // the path. Either time, if an image is found, the phases all unwind without checking
3862 ImageLoader
* load(const char* path
, const LoadContext
& context
, unsigned& cacheIndex
)
3864 CRSetCrashLogMessage2(path
);
3865 const char* orgPath
= path
;
3866 cacheIndex
= UINT32_MAX
;
3868 //dyld::log("%s(%s)\n", __func__ , path);
3869 char realPath
[PATH_MAX
];
3870 // when DYLD_IMAGE_SUFFIX is in used, do a realpath(), otherwise a load of "Foo.framework/Foo" will not match
3871 if ( context
.useSearchPaths
&& ( gLinkContext
.imageSuffix
!= NULL
&& *gLinkContext
.imageSuffix
!= NULL
) ) {
3872 if ( realpath(path
, realPath
) != NULL
)
3876 // try all path permutations and check against existing loaded images
3878 ImageLoader
* image
= loadPhase0(path
, orgPath
, context
, cacheIndex
, NULL
);
3879 if ( image
!= NULL
) {
3880 CRSetCrashLogMessage2(NULL
);
3884 // try all path permutations and try open() until first success
3885 std::vector
<const char*> exceptions
;
3886 image
= loadPhase0(path
, orgPath
, context
, cacheIndex
, &exceptions
);
3887 #if !TARGET_OS_SIMULATOR
3888 // <rdar://problem/16704628> support symlinks on disk to a path in dyld shared cache
3890 image
= loadPhase2cache(path
, orgPath
, context
, cacheIndex
, &exceptions
);
3892 CRSetCrashLogMessage2(NULL
);
3893 if ( image
!= NULL
) {
3894 // <rdar://problem/6916014> leak in dyld during dlopen when using DYLD_ variables
3895 for (std::vector
<const char*>::iterator it
= exceptions
.begin(); it
!= exceptions
.end(); ++it
) {
3898 // if loaded image is not from cache, but original path is in cache
3899 // set gSharedCacheOverridden flag to disable some ObjC optimizations
3900 if ( !gSharedCacheOverridden
&& !image
->inSharedCache() && image
->isDylib() && dyld3::MachOFile::isSharedCacheEligiblePath(path
) && inSharedCache(path
) ) {
3901 gSharedCacheOverridden
= true;
3905 else if ( exceptions
.size() == 0 ) {
3906 if ( context
.dontLoad
) {
3910 throw "image not found";
3913 const char* msgStart
= "no suitable image found. Did find:";
3914 const char* delim
= "\n\t";
3915 size_t allsizes
= strlen(msgStart
)+8;
3916 for (size_t i
=0; i
< exceptions
.size(); ++i
)
3917 allsizes
+= (strlen(exceptions
[i
]) + strlen(delim
));
3918 char* fullMsg
= new char[allsizes
];
3919 strcpy(fullMsg
, msgStart
);
3920 for (size_t i
=0; i
< exceptions
.size(); ++i
) {
3921 strcat(fullMsg
, delim
);
3922 strcat(fullMsg
, exceptions
[i
]);
3923 free((void*)exceptions
[i
]);
3925 throw (const char*)fullMsg
;
3933 static void mapSharedCache()
3935 dyld3::SharedCacheOptions opts
;
3936 opts
.cacheDirOverride
= sSharedCacheOverrideDir
;
3937 opts
.forcePrivate
= (gLinkContext
.sharedRegionMode
== ImageLoader::kUsePrivateSharedRegion
);
3940 #if __x86_64__ && !TARGET_OS_SIMULATOR
3941 opts
.useHaswell
= sHaswell
;
3943 opts
.useHaswell
= false;
3945 opts
.verbose
= gLinkContext
.verboseMapping
;
3946 loadDyldCache(opts
, &sSharedCacheLoadInfo
);
3948 // update global state
3949 if ( sSharedCacheLoadInfo
.loadAddress
!= nullptr ) {
3950 gLinkContext
.dyldCache
= sSharedCacheLoadInfo
.loadAddress
;
3951 dyld::gProcessInfo
->processDetachedFromSharedRegion
= opts
.forcePrivate
;
3952 dyld::gProcessInfo
->sharedCacheSlide
= sSharedCacheLoadInfo
.slide
;
3953 dyld::gProcessInfo
->sharedCacheBaseAddress
= (unsigned long)sSharedCacheLoadInfo
.loadAddress
;
3954 sSharedCacheLoadInfo
.loadAddress
->getUUID(dyld::gProcessInfo
->sharedCacheUUID
);
3955 dyld3::kdebug_trace_dyld_image(DBG_DYLD_UUID_SHARED_CACHE_A
, sSharedCacheLoadInfo
.path
, (const uuid_t
*)&dyld::gProcessInfo
->sharedCacheUUID
[0], {0,0}, {{ 0, 0 }}, (const mach_header
*)sSharedCacheLoadInfo
.loadAddress
);
3958 //#if __IPHONE_OS_VERSION_MIN_REQUIRED && !TARGET_OS_SIMULATOR
3959 // RAM disk booting does not have shared cache yet
3960 // Don't make lack of a shared cache fatal in that case
3961 // if ( sSharedCacheLoadInfo.loadAddress == nullptr ) {
3962 // if ( sSharedCacheLoadInfo.errorMessage != nullptr )
3963 // halt(sSharedCacheLoadInfo.errorMessage);
3965 // halt("error loading dyld shared cache");
3972 // create when NSLinkModule is called for a second time on a bundle
3973 ImageLoader
* cloneImage(ImageLoader
* image
)
3975 // open file (automagically closed when this function exits)
3976 FileOpener
file(image
->getPath());
3978 struct stat stat_buf
;
3979 if ( fstat(file
.getFileDescriptor(), &stat_buf
) == -1)
3982 dyld::LoadContext context
;
3983 context
.useSearchPaths
= false;
3984 context
.useFallbackPaths
= false;
3985 context
.useLdLibraryPath
= false;
3986 context
.implicitRPath
= false;
3987 context
.matchByInstallName
= false;
3988 context
.dontLoad
= false;
3989 context
.mustBeBundle
= true;
3990 context
.mustBeDylib
= false;
3991 context
.canBePIE
= false;
3992 context
.origin
= NULL
;
3993 context
.rpath
= NULL
;
3994 return loadPhase6(file
.getFileDescriptor(), stat_buf
, image
->getPath(), context
);
3998 ImageLoader
* loadFromMemory(const uint8_t* mem
, uint64_t len
, const char* moduleName
)
4000 // if fat wrapper, find usable sub-file
4001 const fat_header
* memStartAsFat
= (fat_header
*)mem
;
4002 uint64_t fileOffset
= 0;
4003 uint64_t fileLength
= len
;
4004 if ( memStartAsFat
->magic
== OSSwapBigToHostInt32(FAT_MAGIC
) ) {
4005 if ( fatFindBest(memStartAsFat
, &fileOffset
, &fileLength
) ) {
4006 mem
= &mem
[fileOffset
];
4010 throw "no matching architecture in universal wrapper";
4015 if ( isCompatibleMachO(mem
, moduleName
) ) {
4016 ImageLoader
* image
= ImageLoaderMachO::instantiateFromMemory(moduleName
, (macho_header
*)mem
, len
, gLinkContext
);
4017 // don't add bundles to global list, they can be loaded but not linked. When linked it will be added to list
4018 if ( ! image
->isBundle() )
4023 // try other file formats here...
4025 // throw error about what was found
4026 switch (*(uint32_t*)mem
) {
4031 throw "mach-o, but wrong architecture";
4033 throwf("unknown file type, first eight bytes: 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X",
4034 mem
[0], mem
[1], mem
[2], mem
[3], mem
[4], mem
[5], mem
[6],mem
[7]);
4039 void registerAddCallback(ImageCallback func
)
4041 // now add to list to get notified when any more images are added
4042 sAddImageCallbacks
.push_back(func
);
4044 // call callback with all existing images
4045 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
4046 ImageLoader
* image
= *it
;
4047 if ( image
->getState() >= dyld_image_state_bound
&& image
->getState() < dyld_image_state_terminated
) {
4048 dyld3::ScopedTimer
timer(DBG_DYLD_TIMING_FUNC_FOR_ADD_IMAGE
, (uint64_t)image
->machHeader(), (uint64_t)(*func
), 0);
4049 (*func
)(image
->machHeader(), image
->getSlide());
4052 #if SUPPORT_ACCELERATE_TABLES
4053 if ( sAllCacheImagesProxy
!= NULL
) {
4054 dyld_image_info infos
[allImagesCount()+1];
4055 unsigned cacheCount
= sAllCacheImagesProxy
->appendImagesToNotify(dyld_image_state_bound
, true, infos
);
4056 for (unsigned i
=0; i
< cacheCount
; ++i
) {
4057 dyld3::ScopedTimer
timer(DBG_DYLD_TIMING_FUNC_FOR_ADD_IMAGE
, (uint64_t)infos
[i
].imageLoadAddress
, (uint64_t)(*func
), 0);
4058 (*func
)(infos
[i
].imageLoadAddress
, sSharedCacheLoadInfo
.slide
);
4064 void registerLoadCallback(LoadImageCallback func
)
4066 // now add to list to get notified when any more images are added
4067 sAddLoadImageCallbacks
.push_back(func
);
4069 // call callback with all existing images
4070 for (ImageLoader
* image
: sAllImages
) {
4071 if ( image
->getState() >= dyld_image_state_bound
&& image
->getState() < dyld_image_state_terminated
) {
4072 dyld3::ScopedTimer
timer(DBG_DYLD_TIMING_FUNC_FOR_ADD_IMAGE
, (uint64_t)image
->machHeader(), (uint64_t)(*func
), 0);
4073 (*func
)(image
->machHeader(), image
->getPath(), !image
->neverUnload());
4076 #if SUPPORT_ACCELERATE_TABLES
4077 if ( sAllCacheImagesProxy
!= NULL
) {
4078 dyld_image_info infos
[allImagesCount()+1];
4079 unsigned cacheCount
= sAllCacheImagesProxy
->appendImagesToNotify(dyld_image_state_bound
, true, infos
);
4080 for (unsigned i
=0; i
< cacheCount
; ++i
) {
4081 dyld3::ScopedTimer
timer(DBG_DYLD_TIMING_FUNC_FOR_ADD_IMAGE
, (uint64_t)infos
[i
].imageLoadAddress
, (uint64_t)(*func
), 0);
4082 (*func
)(infos
[i
].imageLoadAddress
, infos
[i
].imageFilePath
, false);
4088 void registerBulkLoadCallback(LoadImageBulkCallback func
)
4090 // call callback with all existing images
4091 unsigned count
= dyld::gProcessInfo
->infoArrayCount
;
4092 const dyld_image_info
* infoArray
= dyld::gProcessInfo
->infoArray
;
4093 if ( infoArray
!= NULL
) {
4094 const mach_header
* mhs
[count
];
4095 const char* paths
[count
];
4096 for (unsigned i
=0; i
< count
; ++i
) {
4097 mhs
[i
] = infoArray
[i
].imageLoadAddress
;
4098 paths
[i
] = infoArray
[i
].imageFilePath
;
4100 dyld3::ScopedTimer
timer(DBG_DYLD_TIMING_FUNC_FOR_ADD_IMAGE
, (uint64_t)mhs
[0], (uint64_t)func
, 0);
4101 func(count
, mhs
, paths
);
4104 // now add to list to get notified when any more images are added
4105 sAddBulkLoadImageCallbacks
.push_back(func
);
4108 void registerRemoveCallback(ImageCallback func
)
4110 // <rdar://problem/15025198> ignore calls to register a notification during a notification
4111 if ( sRemoveImageCallbacksInUse
)
4113 sRemoveImageCallbacks
.push_back(func
);
4116 void clearErrorMessage()
4118 error_string
[0] = '\0';
4121 void setErrorMessage(const char* message
)
4123 // save off error message in global buffer for CrashReporter to find
4124 strlcpy(error_string
, message
, sizeof(error_string
));
4127 const char* getErrorMessage()
4129 return error_string
;
4132 void halt(const char* message
)
4134 if ( sSharedCacheLoadInfo
.errorMessage
!= nullptr ) {
4135 // <rdar://problem/45957449> if dyld fails with a missing dylib and there is no shared cache, display the shared cache load error message
4136 dyld::log("dyld: dyld cache load error: %s\n", sSharedCacheLoadInfo
.errorMessage
);
4137 dyld::log("dyld: %s\n", message
);
4138 strlcpy(error_string
, "dyld cache load error: ", sizeof(error_string
));
4139 strlcat(error_string
, sSharedCacheLoadInfo
.errorMessage
, sizeof(error_string
));
4140 strlcat(error_string
, "\n", sizeof(error_string
));
4141 strlcat(error_string
, message
, sizeof(error_string
));
4144 dyld::log("dyld: %s\n", message
);
4145 strlcpy(error_string
, message
, sizeof(error_string
));
4148 dyld::gProcessInfo
->errorMessage
= error_string
;
4149 if ( !gLinkContext
.startedInitializingMainExecutable
)
4150 dyld::gProcessInfo
->terminationFlags
= 1;
4152 dyld::gProcessInfo
->terminationFlags
= 0;
4154 char payloadBuffer
[EXIT_REASON_PAYLOAD_MAX_LEN
];
4155 dyld_abort_payload
* payload
= (dyld_abort_payload
*)payloadBuffer
;
4156 payload
->version
= 1;
4157 payload
->flags
= gLinkContext
.startedInitializingMainExecutable
? 0 : 1;
4158 payload
->targetDylibPathOffset
= 0;
4159 payload
->clientPathOffset
= 0;
4160 payload
->symbolOffset
= 0;
4161 int payloadSize
= sizeof(dyld_abort_payload
);
4163 if ( dyld::gProcessInfo
->errorTargetDylibPath
!= NULL
) {
4164 payload
->targetDylibPathOffset
= payloadSize
;
4165 payloadSize
+= strlcpy(&payloadBuffer
[payloadSize
], dyld::gProcessInfo
->errorTargetDylibPath
, sizeof(payloadBuffer
)-payloadSize
) + 1;
4167 if ( dyld::gProcessInfo
->errorClientOfDylibPath
!= NULL
) {
4168 payload
->clientPathOffset
= payloadSize
;
4169 payloadSize
+= strlcpy(&payloadBuffer
[payloadSize
], dyld::gProcessInfo
->errorClientOfDylibPath
, sizeof(payloadBuffer
)-payloadSize
) + 1;
4171 if ( dyld::gProcessInfo
->errorSymbol
!= NULL
) {
4172 payload
->symbolOffset
= payloadSize
;
4173 payloadSize
+= strlcpy(&payloadBuffer
[payloadSize
], dyld::gProcessInfo
->errorSymbol
, sizeof(payloadBuffer
)-payloadSize
) + 1;
4175 char truncMessage
[EXIT_REASON_USER_DESC_MAX_LEN
];
4176 strlcpy(truncMessage
, error_string
, EXIT_REASON_USER_DESC_MAX_LEN
);
4177 abort_with_payload(OS_REASON_DYLD
, dyld::gProcessInfo
->errorKind
? dyld::gProcessInfo
->errorKind
: DYLD_EXIT_REASON_OTHER
, payloadBuffer
, payloadSize
, truncMessage
, 0);
4180 static void setErrorStrings(unsigned errorCode
, const char* errorClientOfDylibPath
,
4181 const char* errorTargetDylibPath
, const char* errorSymbol
)
4183 dyld::gProcessInfo
->errorKind
= errorCode
;
4184 dyld::gProcessInfo
->errorClientOfDylibPath
= errorClientOfDylibPath
;
4185 dyld::gProcessInfo
->errorTargetDylibPath
= errorTargetDylibPath
;
4186 dyld::gProcessInfo
->errorSymbol
= errorSymbol
;
4190 uintptr_t bindLazySymbol(const mach_header
* mh
, uintptr_t* lazyPointer
)
4192 uintptr_t result
= 0;
4193 // acquire read-lock on dyld's data structures
4194 #if 0 // rdar://problem/3811777 turn off locking until deadlock is resolved
4195 if ( gLibSystemHelpers
!= NULL
)
4196 (*gLibSystemHelpers
->lockForReading
)();
4198 // lookup and bind lazy pointer and get target address
4200 ImageLoader
* target
;
4202 // fast stubs pass NULL for mh and image is instead found via the location of stub (aka lazyPointer)
4204 target
= dyld::findImageContainingAddress(lazyPointer
);
4206 target
= dyld::findImageByMachHeader(mh
);
4208 // note, target should always be mach-o, because only mach-o lazy handler wired up to this
4209 target
= dyld::findImageByMachHeader(mh
);
4211 if ( target
== NULL
)
4212 throwf("image not found for lazy pointer at %p", lazyPointer
);
4213 result
= target
->doBindLazySymbol(lazyPointer
, gLinkContext
);
4215 catch (const char* message
) {
4216 dyld::log("dyld: lazy symbol binding failed: %s\n", message
);
4219 // release read-lock on dyld's data structures
4221 if ( gLibSystemHelpers
!= NULL
)
4222 (*gLibSystemHelpers
->unlockForReading
)();
4224 // return target address to glue which jumps to it with real parameters restored
4229 uintptr_t fastBindLazySymbol(ImageLoader
** imageLoaderCache
, uintptr_t lazyBindingInfoOffset
)
4231 uintptr_t result
= 0;
4233 if ( *imageLoaderCache
== NULL
) {
4235 *imageLoaderCache
= dyld::findMappedRange((uintptr_t)imageLoaderCache
);
4236 if ( *imageLoaderCache
== NULL
) {
4237 #if SUPPORT_ACCELERATE_TABLES
4238 if ( sAllCacheImagesProxy
!= NULL
) {
4239 const mach_header
* mh
;
4242 if ( sAllCacheImagesProxy
->addressInCache(imageLoaderCache
, &mh
, &path
, &index
) ) {
4243 result
= sAllCacheImagesProxy
->bindLazy(lazyBindingInfoOffset
, gLinkContext
, mh
, index
);
4244 if ( result
== 0 ) {
4245 halt("dyld: lazy symbol binding failed for image in dyld shared\n");
4251 const char* message
= "fast lazy binding from unknown image";
4252 dyld::log("dyld: %s\n", message
);
4257 // bind lazy pointer and return it
4259 result
= (*imageLoaderCache
)->doBindFastLazySymbol((uint32_t)lazyBindingInfoOffset
, gLinkContext
,
4260 (dyld::gLibSystemHelpers
!= NULL
) ? dyld::gLibSystemHelpers
->acquireGlobalDyldLock
: NULL
,
4261 (dyld::gLibSystemHelpers
!= NULL
) ? dyld::gLibSystemHelpers
->releaseGlobalDyldLock
: NULL
);
4263 catch (const char* message
) {
4264 dyld::log("dyld: lazy symbol binding failed: %s\n", message
);
4268 // return target address to glue which jumps to it with real parameters restored
4274 void registerUndefinedHandler(UndefinedHandler handler
)
4276 sUndefinedHandler
= handler
;
4279 static void undefinedHandler(const char* symboName
)
4281 if ( sUndefinedHandler
!= NULL
) {
4282 (*sUndefinedHandler
)(symboName
);
4286 static bool findExportedSymbol(const char* name
, bool onlyInCoalesced
, const ImageLoader::Symbol
** sym
, const ImageLoader
** image
, ImageLoader::CoalesceNotifier notifier
=NULL
)
4288 // search all images in order
4289 const ImageLoader
* firstWeakImage
= NULL
;
4290 const ImageLoader::Symbol
* firstWeakSym
= NULL
;
4291 const ImageLoader
* firstNonWeakImage
= NULL
;
4292 const ImageLoader::Symbol
* firstNonWeakSym
= NULL
;
4293 const size_t imageCount
= sAllImages
.size();
4294 for(size_t i
=0; i
< imageCount
; ++i
) {
4295 ImageLoader
* anImage
= sAllImages
[i
];
4296 // the use of inserted libraries alters search order
4297 // so that inserted libraries are found before the main executable
4298 if ( sInsertedDylibCount
> 0 ) {
4299 if ( i
< sInsertedDylibCount
)
4300 anImage
= sAllImages
[i
+1];
4301 else if ( i
== sInsertedDylibCount
)
4302 anImage
= sAllImages
[0];
4304 //dyld::log("findExportedSymbol(%s) looking at %s\n", name, anImage->getPath());
4305 if ( ! anImage
->hasHiddenExports() && (!onlyInCoalesced
|| anImage
->hasCoalescedExports()) ) {
4306 const ImageLoader
* foundInImage
;
4307 *sym
= anImage
->findExportedSymbol(name
, false, &foundInImage
);
4308 //dyld::log("findExportedSymbol(%s) found: sym=%p, anImage=%p, foundInImage=%p\n", name, *sym, anImage, foundInImage /*, (foundInImage ? foundInImage->getPath() : "")*/);
4309 if ( *sym
!= NULL
) {
4310 if ( notifier
&& (foundInImage
== anImage
) )
4311 notifier(*sym
, foundInImage
, foundInImage
->machHeader());
4312 // if weak definition found, record first one found
4313 if ( (foundInImage
->getExportedSymbolInfo(*sym
) & ImageLoader::kWeakDefinition
) != 0 ) {
4314 if ( firstWeakImage
== NULL
) {
4315 firstWeakImage
= foundInImage
;
4316 firstWeakSym
= *sym
;
4321 if ( !onlyInCoalesced
) {
4322 // for flat lookups, return first found
4323 *image
= foundInImage
;
4326 if ( firstNonWeakImage
== NULL
) {
4327 firstNonWeakImage
= foundInImage
;
4328 firstNonWeakSym
= *sym
;
4334 if ( firstNonWeakImage
!= NULL
) {
4335 // found a weak definition, but no non-weak, so return first weak found
4336 *sym
= firstNonWeakSym
;
4337 *image
= firstNonWeakImage
;
4340 if ( firstWeakSym
!= NULL
) {
4341 // found a weak definition, but no non-weak, so return first weak found
4342 *sym
= firstWeakSym
;
4343 *image
= firstWeakImage
;
4346 #if SUPPORT_ACCELERATE_TABLES
4347 if ( sAllCacheImagesProxy
!= NULL
) {
4348 if ( sAllCacheImagesProxy
->flatFindSymbol(name
, onlyInCoalesced
, sym
, image
, notifier
) )
4356 bool flatFindExportedSymbol(const char* name
, const ImageLoader::Symbol
** sym
, const ImageLoader
** image
)
4358 return findExportedSymbol(name
, false, sym
, image
);
4361 bool findCoalescedExportedSymbol(const char* name
, const ImageLoader::Symbol
** sym
, const ImageLoader
** image
, ImageLoader::CoalesceNotifier notifier
)
4363 return findExportedSymbol(name
, true, sym
, image
, notifier
);
4367 bool flatFindExportedSymbolWithHint(const char* name
, const char* librarySubstring
, const ImageLoader::Symbol
** sym
, const ImageLoader
** image
)
4369 // search all images in order
4370 const size_t imageCount
= sAllImages
.size();
4371 for(size_t i
=0; i
< imageCount
; ++i
){
4372 ImageLoader
* anImage
= sAllImages
[i
];
4373 // only look at images whose paths contain the hint string (NULL hint string is wildcard)
4374 if ( ! anImage
->isBundle() && ((librarySubstring
==NULL
) || (strstr(anImage
->getPath(), librarySubstring
) != NULL
)) ) {
4375 *sym
= anImage
->findExportedSymbol(name
, false, image
);
4376 if ( *sym
!= NULL
) {
4385 unsigned int getCoalescedImages(ImageLoader
* images
[], unsigned imageIndex
[])
4387 unsigned int count
= 0;
4388 const size_t imageCount
= sAllImages
.size();
4389 for(size_t i
=0; i
< imageCount
; ++i
) {
4390 ImageLoader
* anImage
= sAllImages
[i
];
4391 // the use of inserted libraries alters search order
4392 // so that inserted libraries are found before the main executable
4393 if ( sInsertedDylibCount
> 0 ) {
4394 if ( i
< sInsertedDylibCount
)
4395 anImage
= sAllImages
[i
+1];
4396 else if ( i
== sInsertedDylibCount
)
4397 anImage
= sAllImages
[0];
4399 if ( anImage
->participatesInCoalescing() ) {
4400 images
[count
] = anImage
;
4401 imageIndex
[count
] = 0;
4405 #if SUPPORT_ACCELERATE_TABLES
4406 if ( sAllCacheImagesProxy
!= NULL
) {
4407 sAllCacheImagesProxy
->appendImagesNeedingCoalescing(images
, imageIndex
, count
);
4414 static ImageLoader::MappedRegion
* getMappedRegions(ImageLoader::MappedRegion
* regions
)
4416 ImageLoader::MappedRegion
* end
= regions
;
4417 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
4418 (*it
)->getMappedRegions(end
);
4423 void registerImageStateSingleChangeHandler(dyld_image_states state
, dyld_image_state_change_handler handler
)
4425 // mark the image that the handler is in as never-unload because dyld has a reference into it
4426 ImageLoader
* handlerImage
= findImageContainingAddress((void*)handler
);
4427 if ( handlerImage
!= NULL
)
4428 handlerImage
->setNeverUnload();
4430 // add to list of handlers
4431 std::vector
<dyld_image_state_change_handler
>* handlers
= stateToHandlers(state
, sSingleHandlers
);
4432 if ( handlers
!= NULL
) {
4433 // <rdar://problem/10332417> need updateAllImages() to be last in dyld_image_state_mapped list
4434 // so that if ObjC adds a handler that prevents a load, it happens before the gdb list is updated
4435 if ( state
== dyld_image_state_mapped
)
4436 handlers
->insert(handlers
->begin(), handler
);
4438 handlers
->push_back(handler
);
4440 // call callback with all existing images
4441 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
4442 ImageLoader
* image
= *it
;
4443 dyld_image_info info
;
4444 info
.imageLoadAddress
= image
->machHeader();
4445 info
.imageFilePath
= image
->getRealPath();
4446 info
.imageFileModDate
= image
->lastModified();
4447 // should only call handler if state == image->state
4448 if ( image
->getState() == state
)
4449 (*handler
)(state
, 1, &info
);
4450 // ignore returned string, too late to do anything
4455 void registerImageStateBatchChangeHandler(dyld_image_states state
, dyld_image_state_change_handler handler
)
4457 // mark the image that the handler is in as never-unload because dyld has a reference into it
4458 ImageLoader
* handlerImage
= findImageContainingAddress((void*)handler
);
4459 if ( handlerImage
!= NULL
)
4460 handlerImage
->setNeverUnload();
4462 // add to list of handlers
4463 std::vector
<dyld_image_state_change_handler
>* handlers
= stateToHandlers(state
, sBatchHandlers
);
4464 if ( handlers
!= NULL
) {
4465 // insert at front, so that gdb handler is always last
4466 handlers
->insert(handlers
->begin(), handler
);
4468 // call callback with all existing images
4470 notifyBatchPartial(state
, true, handler
, false, false);
4472 catch (const char* msg
) {
4473 // ignore request to abort during registration
4479 void registerObjCNotifiers(_dyld_objc_notify_mapped mapped
, _dyld_objc_notify_init init
, _dyld_objc_notify_unmapped unmapped
)
4481 // record functions to call
4482 sNotifyObjCMapped
= mapped
;
4483 sNotifyObjCInit
= init
;
4484 sNotifyObjCUnmapped
= unmapped
;
4486 // call 'mapped' function with all images mapped so far
4488 notifyBatchPartial(dyld_image_state_bound
, true, NULL
, false, true);
4490 catch (const char* msg
) {
4491 // ignore request to abort during registration
4494 // <rdar://problem/32209809> call 'init' function on all images already init'ed (below libSystem)
4495 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
4496 ImageLoader
* image
= *it
;
4497 if ( (image
->getState() == dyld_image_state_initialized
) && image
->notifyObjC() ) {
4498 dyld3::ScopedTimer
timer(DBG_DYLD_TIMING_OBJC_INIT
, (uint64_t)image
->machHeader(), 0, 0);
4499 (*sNotifyObjCInit
)(image
->getRealPath(), image
->machHeader());
4504 bool sharedCacheUUID(uuid_t uuid
)
4506 if ( sSharedCacheLoadInfo
.loadAddress
== nullptr )
4509 sSharedCacheLoadInfo
.loadAddress
->getUUID(uuid
);
4513 #if SUPPORT_ACCELERATE_TABLES
4515 bool dlopenFromCache(const char* path
, int mode
, void** handle
)
4517 if ( sAllCacheImagesProxy
== NULL
)
4519 char fallbackPath
[PATH_MAX
];
4520 bool result
= sAllCacheImagesProxy
->dlopenFromCache(gLinkContext
, path
, mode
, handle
);
4521 if ( !result
&& (strchr(path
, '/') == NULL
) ) {
4522 // POSIX says you can call dlopen() with a leaf name (e.g. dlopen("libz.dylb"))
4523 strcpy(fallbackPath
, "/usr/lib/");
4524 strlcat(fallbackPath
, path
, PATH_MAX
);
4525 result
= sAllCacheImagesProxy
->dlopenFromCache(gLinkContext
, fallbackPath
, mode
, handle
);
4527 path
= fallbackPath
;
4530 // leaf name could be a symlink
4531 char resolvedPath
[PATH_MAX
];
4532 realpath(path
, resolvedPath
);
4533 int realpathErrno
= errno
;
4534 // If realpath() resolves to a path which does not exist on disk, errno is set to ENOENT
4535 if ( (realpathErrno
== ENOENT
) || (realpathErrno
== 0) ) {
4536 result
= sAllCacheImagesProxy
->dlopenFromCache(gLinkContext
, resolvedPath
, mode
, handle
);
4543 bool makeCacheHandle(ImageLoader
* image
, unsigned cacheIndex
, int mode
, void** result
)
4545 if ( sAllCacheImagesProxy
== NULL
)
4547 return sAllCacheImagesProxy
->makeCacheHandle(gLinkContext
, cacheIndex
, mode
, result
);
4550 bool isCacheHandle(void* handle
)
4552 if ( sAllCacheImagesProxy
== NULL
)
4554 return sAllCacheImagesProxy
->isCacheHandle(handle
, NULL
, NULL
);
4557 bool isPathInCache(const char* path
)
4559 if ( sAllCacheImagesProxy
== NULL
)
4562 return sAllCacheImagesProxy
->hasDylib(path
, &index
);
4565 const char* getPathFromIndex(unsigned cacheIndex
)
4567 if ( sAllCacheImagesProxy
== NULL
)
4569 return sAllCacheImagesProxy
->getIndexedPath(cacheIndex
);
4572 void* dlsymFromCache(void* handle
, const char* symName
, unsigned index
)
4574 if ( sAllCacheImagesProxy
== NULL
)
4576 return sAllCacheImagesProxy
->dlsymFromCache(gLinkContext
, handle
, symName
, index
);
4579 bool addressInCache(const void* address
, const mach_header
** mh
, const char** path
, unsigned* index
)
4581 if ( sAllCacheImagesProxy
== NULL
)
4584 return sAllCacheImagesProxy
->addressInCache(address
, mh
, path
, index
? index
: &ignore
);
4587 bool findUnwindSections(const void* addr
, dyld_unwind_sections
* info
)
4589 if ( sAllCacheImagesProxy
== NULL
)
4591 return sAllCacheImagesProxy
->findUnwindSections(addr
, info
);
4594 bool dladdrFromCache(const void* address
, Dl_info
* info
)
4596 if ( sAllCacheImagesProxy
== NULL
)
4598 return sAllCacheImagesProxy
->dladdrFromCache(address
, info
);
4602 static ImageLoader
* libraryLocator(const char* libraryName
, bool search
, const char* origin
, const ImageLoader::RPathChain
* rpaths
, unsigned& cacheIndex
)
4604 dyld::LoadContext context
;
4605 context
.useSearchPaths
= search
;
4606 context
.useFallbackPaths
= search
;
4607 context
.useLdLibraryPath
= false;
4608 context
.implicitRPath
= false;
4609 context
.matchByInstallName
= false;
4610 context
.dontLoad
= false;
4611 context
.mustBeBundle
= false;
4612 context
.mustBeDylib
= true;
4613 context
.canBePIE
= false;
4614 context
.origin
= origin
;
4615 context
.rpath
= rpaths
;
4616 return load(libraryName
, context
, cacheIndex
);
4619 static const char* basename(const char* path
)
4621 const char* last
= path
;
4622 for (const char* s
= path
; *s
!= '\0'; s
++) {
4629 static void setContext(const macho_header
* mainExecutableMH
, int argc
, const char* argv
[], const char* envp
[], const char* apple
[])
4631 gLinkContext
.loadLibrary
= &libraryLocator
;
4632 gLinkContext
.terminationRecorder
= &terminationRecorder
;
4633 gLinkContext
.flatExportFinder
= &flatFindExportedSymbol
;
4634 gLinkContext
.coalescedExportFinder
= &findCoalescedExportedSymbol
;
4635 gLinkContext
.getCoalescedImages
= &getCoalescedImages
;
4636 gLinkContext
.undefinedHandler
= &undefinedHandler
;
4637 gLinkContext
.getAllMappedRegions
= &getMappedRegions
;
4638 gLinkContext
.bindingHandler
= NULL
;
4639 gLinkContext
.notifySingle
= ¬ifySingle
;
4640 gLinkContext
.notifyBatch
= ¬ifyBatch
;
4641 gLinkContext
.removeImage
= &removeImage
;
4642 gLinkContext
.registerDOFs
= dyld3::Loader::dtraceUserProbesEnabled() ? ®isterDOFs
: NULL
;
4643 gLinkContext
.clearAllDepths
= &clearAllDepths
;
4644 gLinkContext
.printAllDepths
= &printAllDepths
;
4645 gLinkContext
.imageCount
= &imageCount
;
4646 gLinkContext
.setNewProgramVars
= &setNewProgramVars
;
4647 gLinkContext
.inSharedCache
= &inSharedCache
;
4648 gLinkContext
.setErrorStrings
= &setErrorStrings
;
4649 #if SUPPORT_OLD_CRT_INITIALIZATION
4650 gLinkContext
.setRunInitialzersOldWay
= &setRunInitialzersOldWay
;
4652 gLinkContext
.findImageContainingAddress
= &findImageContainingAddress
;
4653 gLinkContext
.addDynamicReference
= &addDynamicReference
;
4654 #if SUPPORT_ACCELERATE_TABLES
4655 gLinkContext
.notifySingleFromCache
= ¬ifySingleFromCache
;
4656 gLinkContext
.getPreInitNotifyHandler
= &getPreInitNotifyHandler
;
4657 gLinkContext
.getBoundBatchHandler
= &getBoundBatchHandler
;
4659 gLinkContext
.bindingOptions
= ImageLoader::kBindingNone
;
4660 gLinkContext
.argc
= argc
;
4661 gLinkContext
.argv
= argv
;
4662 gLinkContext
.envp
= envp
;
4663 gLinkContext
.apple
= apple
;
4664 gLinkContext
.progname
= (argv
[0] != NULL
) ? basename(argv
[0]) : "";
4665 gLinkContext
.programVars
.mh
= mainExecutableMH
;
4666 gLinkContext
.programVars
.NXArgcPtr
= &gLinkContext
.argc
;
4667 gLinkContext
.programVars
.NXArgvPtr
= &gLinkContext
.argv
;
4668 gLinkContext
.programVars
.environPtr
= &gLinkContext
.envp
;
4669 gLinkContext
.programVars
.__prognamePtr
=&gLinkContext
.progname
;
4670 gLinkContext
.mainExecutable
= NULL
;
4671 gLinkContext
.imageSuffix
= NULL
;
4672 gLinkContext
.dynamicInterposeArray
= NULL
;
4673 gLinkContext
.dynamicInterposeCount
= 0;
4674 gLinkContext
.prebindUsage
= ImageLoader::kUseAllPrebinding
;
4675 gLinkContext
.sharedRegionMode
= ImageLoader::kUseSharedRegion
;
4681 // Look for a special segment in the mach header.
4682 // Its presences means that the binary wants to have DYLD ignore
4683 // DYLD_ environment variables.
4685 #if __MAC_OS_X_VERSION_MIN_REQUIRED
4686 static bool hasRestrictedSegment(const macho_header
* mh
)
4688 const uint32_t cmd_count
= mh
->ncmds
;
4689 const struct load_command
* const cmds
= (struct load_command
*)(((char*)mh
)+sizeof(macho_header
));
4690 const struct load_command
* cmd
= cmds
;
4691 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
4693 case LC_SEGMENT_COMMAND
:
4695 const struct macho_segment_command
* seg
= (struct macho_segment_command
*)cmd
;
4697 //dyld::log("seg name: %s\n", seg->segname);
4698 if (strcmp(seg
->segname
, "__RESTRICT") == 0) {
4699 const struct macho_section
* const sectionsStart
= (struct macho_section
*)((char*)seg
+ sizeof(struct macho_segment_command
));
4700 const struct macho_section
* const sectionsEnd
= §ionsStart
[seg
->nsects
];
4701 for (const struct macho_section
* sect
=sectionsStart
; sect
< sectionsEnd
; ++sect
) {
4702 if (strcmp(sect
->sectname
, "__restrict") == 0)
4709 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
4716 #if __IPHONE_OS_VERSION_MIN_REQUIRED && !TARGET_OS_SIMULATOR
4717 static bool isFairPlayEncrypted(const macho_header
* mh
)
4719 const uint32_t cmd_count
= mh
->ncmds
;
4720 const struct load_command
* const cmds
= (struct load_command
*)(((char*)mh
)+sizeof(macho_header
));
4721 const struct load_command
* cmd
= cmds
;
4722 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
4723 if ( cmd
->cmd
== LC_ENCRYPT_COMMAND
) {
4724 const encryption_info_command
* enc
= (encryption_info_command
*)cmd
;
4725 return (enc
->cryptid
!= 0);
4727 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
4734 #if SUPPORT_VERSIONED_PATHS
4736 static bool readFirstPage(const char* dylibPath
, uint8_t firstPage
[4096])
4739 // open file (automagically closed when this function exits)
4740 FileOpener
file(dylibPath
);
4742 if ( file
.getFileDescriptor() == -1 )
4745 if ( pread(file
.getFileDescriptor(), firstPage
, 4096, 0) != 4096 )
4748 // if fat wrapper, find usable sub-file
4749 const fat_header
* fileStartAsFat
= (fat_header
*)firstPage
;
4750 if ( fileStartAsFat
->magic
== OSSwapBigToHostInt32(FAT_MAGIC
) ) {
4751 uint64_t fileOffset
;
4752 uint64_t fileLength
;
4753 if ( fatFindBest(fileStartAsFat
, &fileOffset
, &fileLength
) ) {
4754 if ( pread(file
.getFileDescriptor(), firstPage
, 4096, fileOffset
) != 4096 )
4766 // Peeks at a dylib file and returns its current_version and install_name.
4767 // Returns false on error.
4769 static bool getDylibVersionAndInstallname(const char* dylibPath
, uint32_t* version
, char* installName
)
4771 uint8_t firstPage
[4096];
4772 const macho_header
* mh
= (macho_header
*)firstPage
;
4773 if ( !readFirstPage(dylibPath
, firstPage
) ) {
4774 // If file cannot be read, check to see if path is in shared cache
4775 const macho_header
* mhInCache
;
4776 const char* pathInCache
;
4778 if ( !findInSharedCacheImage(dylibPath
, true, NULL
, &mhInCache
, &pathInCache
, &slideInCache
) )
4783 // check mach-o header
4784 if ( mh
->magic
!= sMainExecutableMachHeader
->magic
)
4786 if ( mh
->cputype
!= sMainExecutableMachHeader
->cputype
)
4789 // scan load commands for LC_ID_DYLIB
4790 const uint32_t cmd_count
= mh
->ncmds
;
4791 const struct load_command
* const cmds
= (struct load_command
*)(((char*)mh
)+sizeof(macho_header
));
4792 const struct load_command
* const cmdsReadEnd
= (struct load_command
*)(((char*)mh
)+4096);
4793 const struct load_command
* cmd
= cmds
;
4794 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
4798 const struct dylib_command
* id
= (struct dylib_command
*)cmd
;
4799 *version
= id
->dylib
.current_version
;
4800 if ( installName
!= NULL
)
4801 strlcpy(installName
, (char *)id
+ id
->dylib
.name
.offset
, PATH_MAX
);
4806 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
4807 if ( cmd
> cmdsReadEnd
)
4813 #endif // SUPPORT_VERSIONED_PATHS
4817 static void printAllImages()
4819 dyld::log("printAllImages()\n");
4820 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
4821 ImageLoader
* image
= *it
;
4822 dyld_image_states imageState
= image
->getState();
4823 dyld::log(" state=%d, dlopen-count=%d, never-unload=%d, in-use=%d, name=%s\n",
4824 imageState
, image
->dlopenCount(), image
->neverUnload(), image
->isMarkedInUse(), image
->getShortName());
4829 void link(ImageLoader
* image
, bool forceLazysBound
, bool neverUnload
, const ImageLoader::RPathChain
& loaderRPaths
, unsigned cacheIndex
)
4831 // add to list of known images. This did not happen at creation time for bundles
4832 if ( image
->isBundle() && !image
->isLinked() )
4835 // we detect root images as those not linked in yet
4836 if ( !image
->isLinked() )
4837 addRootImage(image
);
4841 const char* path
= image
->getPath();
4842 #if SUPPORT_ACCELERATE_TABLES
4843 if ( image
== sAllCacheImagesProxy
)
4844 path
= sAllCacheImagesProxy
->getIndexedPath(cacheIndex
);
4846 image
->link(gLinkContext
, forceLazysBound
, false, neverUnload
, loaderRPaths
, path
);
4848 catch (const char* msg
) {
4849 garbageCollectImages();
4855 void runInitializers(ImageLoader
* image
)
4857 // do bottom up initialization
4858 ImageLoader::InitializerTimingList initializerTimes
[allImagesCount()];
4859 initializerTimes
[0].count
= 0;
4860 image
->runInitializers(gLinkContext
, initializerTimes
[0]);
4863 // This function is called at the end of dlclose() when the reference count goes to zero.
4864 // The dylib being unloaded may have brought in other dependent dylibs when it was loaded.
4865 // Those dependent dylibs need to be unloaded, but only if they are not referenced by
4866 // something else. We use a standard mark and sweep garbage collection.
4868 // The tricky part is that when a dylib is unloaded it may have a termination function that
4869 // can run and itself call dlclose() on yet another dylib. The problem is that this
4870 // sort of gabage collection is not re-entrant. Instead a terminator's call to dlclose()
4871 // which calls garbageCollectImages() will just set a flag to re-do the garbage collection
4872 // when the current pass is done.
4874 // Also note that this is done within the dyld global lock, so it is always single threaded.
4876 void garbageCollectImages()
4878 static bool sDoingGC
= false;
4879 static bool sRedo
= false;
4882 // GC is currently being run, just set a flag to have it run again.
4891 // mark phase: mark all images not-in-use
4892 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
4893 ImageLoader
* image
= *it
;
4894 //dyld::log("gc: neverUnload=%d name=%s\n", image->neverUnload(), image->getShortName());
4895 image
->markNotUsed();
4898 #pragma clang diagnostic push
4899 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
4900 // sweep phase: mark as in-use, images reachable from never-unload or in-use image
4901 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
4902 ImageLoader
* image
= *it
;
4903 if ( (image
->dlopenCount() != 0) || (image
->neverUnload() && (image
->getState() >= dyld_image_state_bound
)) || (image
== sMainExecutable
) ) {
4904 OSSpinLockLock(&sDynamicReferencesLock
);
4905 image
->markedUsedRecursive(sDynamicReferences
);
4906 OSSpinLockUnlock(&sDynamicReferencesLock
);
4909 #pragma clang diagnostic pop
4911 // collect phase: build array of images not marked in-use
4912 ImageLoader
* deadImages
[sAllImages
.size()];
4913 unsigned deadCount
= 0;
4914 int maxRangeCount
= 0;
4915 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
4916 ImageLoader
* image
= *it
;
4917 if ( ! image
->isMarkedInUse() ) {
4918 deadImages
[deadCount
++] = image
;
4919 if (gLogAPIs
) dyld::log("dlclose(), found unused image %p %s\n", image
, image
->getShortName());
4920 maxRangeCount
+= image
->segmentCount();
4924 // collect phase: run termination routines for images not marked in-use
4925 if ( maxRangeCount
!= 0 ) {
4926 __cxa_range_t ranges
[maxRangeCount
];
4928 for (unsigned i
=0; i
< deadCount
; ++i
) {
4929 ImageLoader
* image
= deadImages
[i
];
4930 for (unsigned int j
=0; j
< image
->segmentCount(); ++j
) {
4931 if ( !image
->segExecutable(j
) )
4933 if ( rangeCount
< maxRangeCount
) {
4934 ranges
[rangeCount
].addr
= (const void*)image
->segActualLoadAddress(j
);
4935 ranges
[rangeCount
].length
= image
->segSize(j
);
4940 runImageStaticTerminators(image
);
4942 catch (const char* msg
) {
4943 dyld::warn("problem running terminators for image: %s\n", msg
);
4947 // <rdar://problem/14718598> dyld should call __cxa_finalize_ranges()
4948 if ( (rangeCount
> 0) && (gLibSystemHelpers
!= NULL
) && (gLibSystemHelpers
->version
>= 13) )
4949 (*gLibSystemHelpers
->cxa_finalize_ranges
)(ranges
, rangeCount
);
4952 // collect phase: delete all images which are not marked in-use
4955 mightBeMore
= false;
4956 for (std::vector
<ImageLoader
*>::iterator it
=sAllImages
.begin(); it
!= sAllImages
.end(); it
++) {
4957 ImageLoader
* image
= *it
;
4958 if ( ! image
->isMarkedInUse() ) {
4960 if (gLogAPIs
) dyld::log("dlclose(), deleting %p %s\n", image
, image
->getShortName());
4962 ImageLoader::deleteImage(image
);
4964 break; // interator in invalidated by this removal
4966 catch (const char* msg
) {
4967 dyld::warn("problem deleting image: %s\n", msg
);
4971 } while ( mightBeMore
);
4980 static void preflight_finally(ImageLoader
* image
)
4982 if ( image
->isBundle() ) {
4983 removeImageFromAllImages(image
->machHeader());
4984 ImageLoader::deleteImage(image
);
4986 sBundleBeingLoaded
= NULL
;
4987 dyld::garbageCollectImages();
4991 void preflight(ImageLoader
* image
, const ImageLoader::RPathChain
& loaderRPaths
, unsigned cacheIndex
)
4994 if ( image
->isBundle() )
4995 sBundleBeingLoaded
= image
; // hack
4996 const char* path
= image
->getPath();
4997 #if SUPPORT_ACCELERATE_TABLES
4998 if ( image
== sAllCacheImagesProxy
)
4999 path
= sAllCacheImagesProxy
->getIndexedPath(cacheIndex
);
5001 image
->link(gLinkContext
, false, true, false, loaderRPaths
, path
);
5003 catch (const char* msg
) {
5004 preflight_finally(image
);
5007 preflight_finally(image
);
5010 static void loadInsertedDylib(const char* path
)
5012 unsigned cacheIndex
;
5014 LoadContext context
;
5015 context
.useSearchPaths
= false;
5016 context
.useFallbackPaths
= false;
5017 context
.useLdLibraryPath
= false;
5018 context
.implicitRPath
= false;
5019 context
.matchByInstallName
= false;
5020 context
.dontLoad
= false;
5021 context
.mustBeBundle
= false;
5022 context
.mustBeDylib
= true;
5023 context
.canBePIE
= false;
5024 context
.origin
= NULL
; // can't use @loader_path with DYLD_INSERT_LIBRARIES
5025 context
.rpath
= NULL
;
5026 load(path
, context
, cacheIndex
);
5028 catch (const char* msg
) {
5029 if ( gLinkContext
.allowInsertFailures
)
5030 dyld::log("dyld: warning: could not load inserted library '%s' into hardened process because %s\n", path
, msg
);
5032 halt(dyld::mkstringf("could not load inserted library '%s' because %s\n", path
, msg
));
5035 halt(dyld::mkstringf("could not load inserted library '%s'\n", path
));
5040 static void configureProcessRestrictions(const macho_header
* mainExecutableMH
, const char* envp
[])
5042 uint64_t amfiInputFlags
= 0;
5043 #if TARGET_OS_SIMULATOR
5044 amfiInputFlags
|= AMFI_DYLD_INPUT_PROC_IN_SIMULATOR
;
5045 #elif __MAC_OS_X_VERSION_MIN_REQUIRED
5046 if ( hasRestrictedSegment(mainExecutableMH
) )
5047 amfiInputFlags
|= AMFI_DYLD_INPUT_PROC_HAS_RESTRICT_SEG
;
5048 #elif __IPHONE_OS_VERSION_MIN_REQUIRED
5049 if ( isFairPlayEncrypted(mainExecutableMH
) )
5050 amfiInputFlags
|= AMFI_DYLD_INPUT_PROC_IS_ENCRYPTED
;
5052 uint64_t amfiOutputFlags
= 0;
5053 const char* amfiFake
= nullptr;
5054 if ( dyld3::internalInstall() && dyld3::BootArgs::enableDyldTestMode() ) {
5055 amfiFake
= _simple_getenv(envp
, "DYLD_AMFI_FAKE");
5057 if ( amfiFake
!= nullptr ) {
5058 amfiOutputFlags
= hexToUInt64(amfiFake
, nullptr);
5060 if ( (amfiFake
!= nullptr) || (amfi_check_dyld_policy_self(amfiInputFlags
, &amfiOutputFlags
) == 0) ) {
5061 gLinkContext
.allowAtPaths
= (amfiOutputFlags
& AMFI_DYLD_OUTPUT_ALLOW_AT_PATH
);
5062 gLinkContext
.allowEnvVarsPrint
= (amfiOutputFlags
& AMFI_DYLD_OUTPUT_ALLOW_PRINT_VARS
);
5063 gLinkContext
.allowEnvVarsPath
= (amfiOutputFlags
& AMFI_DYLD_OUTPUT_ALLOW_PATH_VARS
);
5064 gLinkContext
.allowEnvVarsSharedCache
= (amfiOutputFlags
& AMFI_DYLD_OUTPUT_ALLOW_CUSTOM_SHARED_CACHE
);
5065 gLinkContext
.allowClassicFallbackPaths
= (amfiOutputFlags
& AMFI_DYLD_OUTPUT_ALLOW_FALLBACK_PATHS
);
5066 gLinkContext
.allowInsertFailures
= (amfiOutputFlags
& AMFI_DYLD_OUTPUT_ALLOW_FAILED_LIBRARY_INSERTION
);
5069 #if __MAC_OS_X_VERSION_MIN_REQUIRED
5070 // support chrooting from old kernel
5071 bool isRestricted
= false;
5072 bool libraryValidation
= false;
5073 // any processes with setuid or setgid bit set or with __RESTRICT segment is restricted
5074 if ( issetugid() || hasRestrictedSegment(mainExecutableMH
) ) {
5075 isRestricted
= true;
5077 bool usingSIP
= (csr_check(CSR_ALLOW_TASK_FOR_PID
) != 0);
5079 if ( csops(0, CS_OPS_STATUS
, &flags
, sizeof(flags
)) != -1 ) {
5080 // On OS X CS_RESTRICT means the program was signed with entitlements
5081 if ( ((flags
& CS_RESTRICT
) == CS_RESTRICT
) && usingSIP
) {
5082 isRestricted
= true;
5084 // Library Validation loosens searching but requires everything to be code signed
5085 if ( flags
& CS_REQUIRE_LV
) {
5086 isRestricted
= false;
5087 libraryValidation
= true;
5090 gLinkContext
.allowAtPaths
= !isRestricted
;
5091 gLinkContext
.allowEnvVarsPrint
= !isRestricted
;
5092 gLinkContext
.allowEnvVarsPath
= !isRestricted
;
5093 gLinkContext
.allowEnvVarsSharedCache
= !libraryValidation
|| !usingSIP
;
5094 gLinkContext
.allowClassicFallbackPaths
= !isRestricted
;
5095 gLinkContext
.allowInsertFailures
= false;
5097 halt("amfi_check_dyld_policy_self() failed\n");
5102 // called by _dyld_register_driverkit_main()
5103 void setMainEntry(void (*main
)())
5105 if ( sEntryOveride
== nullptr )
5106 sEntryOveride
= main
;
5108 halt("_dyld_register_driverkit_main() may only be called once");
5111 bool processIsRestricted()
5113 #if __MAC_OS_X_VERSION_MIN_REQUIRED
5114 return !gLinkContext
.allowEnvVarsPath
;
5121 // <rdar://problem/10583252> Add dyld to uuidArray to enable symbolication of stackshots
5122 static void addDyldImageToUUIDList()
5124 const struct macho_header
* mh
= (macho_header
*)&__dso_handle
;
5125 const uint32_t cmd_count
= mh
->ncmds
;
5126 const struct load_command
* const cmds
= (struct load_command
*)((char*)mh
+ sizeof(macho_header
));
5127 const struct load_command
* cmd
= cmds
;
5128 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
5131 uuid_command
* uc
= (uuid_command
*)cmd
;
5132 dyld_uuid_info info
;
5133 info
.imageLoadAddress
= (mach_header
*)mh
;
5134 memcpy(info
.imageUUID
, uc
->uuid
, 16);
5135 addNonSharedCacheImageUUID(info
);
5139 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
5143 void notifyKernelAboutImage(const struct macho_header
* mh
, const char* fileInfo
)
5145 const char *endptr
= nullptr;
5146 uint64_t tmp
= hexToUInt64(fileInfo
, &endptr
);
5147 fsid_t fsid
= *reinterpret_cast<fsid_t
*>(&tmp
);
5148 uint64_t fsobj_id_scalar
= 0;
5149 fsobj_id_t fsobj_id
= {0};
5150 if (endptr
!= nullptr) {
5151 fsobj_id_scalar
= hexToUInt64(endptr
+1, &endptr
);
5152 fsobj_id
= *reinterpret_cast<fsobj_id_t
*>(&tmp
);
5154 const uint32_t cmd_count
= mh
->ncmds
;
5155 const struct load_command
* const cmds
= (struct load_command
*)((char*)mh
+ sizeof(macho_header
));
5156 const struct load_command
* cmd
= cmds
;
5157 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
5160 // Add dyld to the kernel image info
5161 uuid_command
* uc
= (uuid_command
*)cmd
;
5162 char path
[MAXPATHLEN
];
5163 if (fsgetpath(path
, MAXPATHLEN
, &fsid
, fsobj_id_scalar
) < 0) {
5166 dyld3::kdebug_trace_dyld_image(DBG_DYLD_UUID_MAP_A
, path
, (const uuid_t
*)&uc
->uuid
[0], fsobj_id
, fsid
, (const mach_header
*)mh
);
5170 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
5174 #if __MAC_OS_X_VERSION_MIN_REQUIRED
5175 typedef int (*open_proc_t
)(const char*, int, int);
5176 typedef int (*fcntl_proc_t
)(int, int, void*);
5177 typedef int (*ioctl_proc_t
)(int, unsigned long, void*);
5178 static void* getProcessInfo() { return dyld::gProcessInfo
; }
5179 static const SyscallHelpers sSysCalls
= {
5181 // added in version 1
5190 (fcntl_proc_t
)&fcntl
,
5191 (ioctl_proc_t
)&ioctl
,
5200 &pthread_mutex_lock
,
5201 &pthread_mutex_unlock
,
5203 &mach_port_deallocate
,
5205 &mach_timebase_info
,
5206 &OSAtomicCompareAndSwapPtrBarrier
,
5210 &mach_absolute_time
,
5211 // added in version 2
5213 // added in version 3
5217 // added in version 4
5218 &coresymbolication_load_notifier
,
5219 &coresymbolication_unload_notifier
,
5220 // Added in version 5
5221 &proc_regionfilename
,
5223 &mach_port_insert_right
,
5224 &mach_port_allocate
,
5226 // Added in version 6
5227 &abort_with_payload
,
5228 // Added in version 7
5229 &legacy_task_register_dyld_image_infos
,
5230 &legacy_task_unregister_dyld_image_infos
,
5231 &legacy_task_get_dyld_image_infos
,
5232 &legacy_task_register_dyld_shared_cache_image_info
,
5233 &legacy_task_register_dyld_set_dyld_state
,
5234 &legacy_task_register_dyld_get_process_state
,
5235 // Added in version 8
5240 // Added in version 9
5241 &kdebug_trace_string
,
5242 // Added in version 10
5243 &amfi_check_dyld_policy_self
,
5244 // Added in version 11
5245 ¬ifyMonitoringDyldMain
,
5246 ¬ifyMonitoringDyld
,
5247 // Add in version 12
5249 &mach_port_construct
,
5253 __attribute__((noinline
))
5254 static const char* useSimulatorDyld(int fd
, const macho_header
* mainExecutableMH
, const char* dyldPath
,
5255 int argc
, const char* argv
[], const char* envp
[], const char* apple
[],
5256 uintptr_t* startGlue
, uintptr_t* mainAddr
)
5261 // <rdar://problem/25311921> simulator does not support restricted processes
5263 if ( csops(0, CS_OPS_STATUS
, &flags
, sizeof(flags
)) == -1 )
5264 return "csops() failed";
5265 if ( (flags
& CS_RESTRICT
) == CS_RESTRICT
)
5266 return "dyld_sim cannot be loaded in a restricted process";
5268 return "dyld_sim cannot be loaded in a setuid process";
5269 if ( hasRestrictedSegment(mainExecutableMH
) )
5270 return "dyld_sim cannot be loaded in a restricted process";
5272 // get file size of dyld_sim
5274 if ( fstat(fd
, &sb
) == -1 )
5275 return "stat(dyld_sim) failed";
5277 // read first page of dyld_sim file
5278 uint8_t firstPage
[4096];
5279 if ( pread(fd
, firstPage
, 4096, 0) != 4096 )
5280 return "pread(dyld_sim) failed";
5282 // if fat file, pick matching slice
5283 uint64_t fileOffset
= 0;
5284 uint64_t fileLength
= sb
.st_size
;
5285 const fat_header
* fileStartAsFat
= (fat_header
*)firstPage
;
5286 if ( fileStartAsFat
->magic
== OSSwapBigToHostInt32(FAT_MAGIC
) ) {
5287 if ( !fatFindBest(fileStartAsFat
, &fileOffset
, &fileLength
) )
5288 return "no matching arch in dyld_sim";
5289 // re-read buffer from start of mach-o slice in fat file
5290 if ( pread(fd
, firstPage
, 4096, fileOffset
) != 4096 )
5291 return "pread(dyld_sim) failed";
5293 else if ( !isCompatibleMachO(firstPage
, dyldPath
) ) {
5294 return "dyld_sim is not compatible with the loaded process, likely due to architecture mismatch";
5297 // calculate total size of dyld segments
5298 const macho_header
* mh
= (const macho_header
*)firstPage
;
5299 struct macho_segment_command
* lastSeg
= NULL
;
5300 struct macho_segment_command
* firstSeg
= NULL
;
5301 uintptr_t mappingSize
= 0;
5302 uintptr_t preferredLoadAddress
= 0;
5303 const uint32_t cmd_count
= mh
->ncmds
;
5304 if ( mh
->sizeofcmds
> 4096 )
5305 return "dyld_sim load commands to large";
5306 if ( (sizeof(macho_header
) + mh
->sizeofcmds
) > 4096 )
5307 return "dyld_sim load commands to large";
5308 struct linkedit_data_command
* codeSigCmd
= NULL
;
5309 const struct load_command
* const cmds
= (struct load_command
*)(((char*)mh
)+sizeof(macho_header
));
5310 const struct load_command
* const endCmds
= (struct load_command
*)(((char*)mh
) + sizeof(macho_header
) + mh
->sizeofcmds
);
5311 const struct load_command
* cmd
= cmds
;
5312 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
5313 uint32_t cmdLength
= cmd
->cmdsize
;
5314 if ( cmdLength
< 8 )
5315 return "dyld_sim load command too small";
5316 const struct load_command
* const nextCmd
= (const struct load_command
*)(((char*)cmd
)+cmdLength
);
5317 if ( (nextCmd
> endCmds
) || (nextCmd
< cmd
) )
5318 return "dyld_sim load command too large";
5320 case LC_SEGMENT_COMMAND
:
5322 struct macho_segment_command
* seg
= (struct macho_segment_command
*)cmd
;
5323 if ( seg
->vmaddr
+ seg
->vmsize
< seg
->vmaddr
)
5324 return "dyld_sim seg wraps address space";
5325 if ( seg
->vmsize
< seg
->filesize
)
5326 return "dyld_sim seg vmsize too small";
5327 if ( (seg
->fileoff
+ seg
->filesize
) < seg
->fileoff
)
5328 return "dyld_sim seg size wraps address space";
5329 if ( lastSeg
== NULL
) {
5330 // first segment must be __TEXT and start at beginning of file/slice
5332 if ( strcmp(seg
->segname
, "__TEXT") != 0 )
5333 return "dyld_sim first segment not __TEXT";
5334 if ( seg
->fileoff
!= 0 )
5335 return "dyld_sim first segment not at file offset zero";
5336 if ( seg
->filesize
< (sizeof(macho_header
) + mh
->sizeofcmds
) )
5337 return "dyld_sim first segment smaller than load commands";
5338 preferredLoadAddress
= seg
->vmaddr
;
5341 // other sements must be continguous with previous segment and not executable
5342 if ( lastSeg
->fileoff
+ lastSeg
->filesize
!= seg
->fileoff
)
5343 return "dyld_sim segments not contiguous";
5344 if ( lastSeg
->vmaddr
+ lastSeg
->vmsize
!= seg
->vmaddr
)
5345 return "dyld_sim segments not address contiguous";
5346 if ( (seg
->initprot
& VM_PROT_EXECUTE
) != 0 )
5347 return "dyld_sim non-first segment is executable";
5349 mappingSize
+= seg
->vmsize
;
5353 case LC_SEGMENT_COMMAND_WRONG
:
5354 return "dyld_sim wrong load segment load command";
5355 case LC_CODE_SIGNATURE
:
5356 codeSigCmd
= (struct linkedit_data_command
*)cmd
;
5361 // last segment must be named __LINKEDIT and not writable
5362 if ( lastSeg
== NULL
)
5363 return "dyld_sim has no segments";
5364 if ( strcmp(lastSeg
->segname
, "__LINKEDIT") != 0 )
5365 return "dyld_sim last segment not __LINKEDIT";
5366 if ( lastSeg
->initprot
& VM_PROT_WRITE
)
5367 return "dyld_sim __LINKEDIT segment writable";
5369 // must have code signature which is contained within LINKEDIT segment
5370 if ( codeSigCmd
== NULL
)
5371 return "dyld_sim not code signed";
5372 if ( codeSigCmd
->dataoff
< lastSeg
->fileoff
)
5373 return "dyld_sim code signature not in __LINKEDIT";
5374 if ( (codeSigCmd
->dataoff
+ codeSigCmd
->datasize
) < codeSigCmd
->dataoff
)
5375 return "dyld_sim code signature size wraps";
5376 if ( (codeSigCmd
->dataoff
+ codeSigCmd
->datasize
) > (lastSeg
->fileoff
+ lastSeg
->filesize
) )
5377 return "dyld_sim code signature extends beyond __LINKEDIT";
5379 // register code signature with kernel before mmap()ing segments
5380 fsignatures_t siginfo
;
5381 siginfo
.fs_file_start
=fileOffset
; // start of mach-o slice in fat file
5382 siginfo
.fs_blob_start
=(void*)(long)(codeSigCmd
->dataoff
); // start of code-signature in mach-o file
5383 siginfo
.fs_blob_size
=codeSigCmd
->datasize
; // size of code-signature
5384 int result
= fcntl(fd
, F_ADDFILESIGS_FOR_DYLD_SIM
, &siginfo
);
5385 if ( result
== -1 ) {
5386 return mkstringf("dyld_sim fcntl(F_ADDFILESIGS_FOR_DYLD_SIM) failed with errno=%d", errno
);
5388 // file range covered by code signature must extend up to code signature itself
5389 if ( siginfo
.fs_file_start
< codeSigCmd
->dataoff
)
5390 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
);
5392 // reserve space, then mmap each segment
5393 vm_address_t loadAddress
= 0;
5394 if ( ::vm_allocate(mach_task_self(), &loadAddress
, mappingSize
, VM_FLAGS_ANYWHERE
) != 0 )
5395 return "dyld_sim cannot allocate space";
5397 struct source_version_command
* dyldVersionCmd
= NULL
;
5398 struct uuid_command
* uuidCmd
= NULL
;
5399 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
5401 case LC_SEGMENT_COMMAND
:
5403 struct macho_segment_command
* seg
= (struct macho_segment_command
*)cmd
;
5404 uintptr_t requestedLoadAddress
= seg
->vmaddr
- preferredLoadAddress
+ loadAddress
;
5405 void* segAddress
= ::mmap((void*)requestedLoadAddress
, seg
->filesize
, seg
->initprot
, MAP_FIXED
| MAP_PRIVATE
, fd
, fileOffset
+ seg
->fileoff
);
5406 //dyld::log("dyld_sim %s mapped at %p\n", seg->segname, segAddress);
5407 if ( segAddress
== (void*)(-1) )
5408 return "dyld_sim mmap() of segment failed";
5409 if ( ((uintptr_t)segAddress
< loadAddress
) || ((uintptr_t)segAddress
+seg
->filesize
> loadAddress
+mappingSize
) )
5410 return "dyld_sim mmap() to wrong location";
5413 case LC_SOURCE_VERSION
:
5414 dyldVersionCmd
= (struct source_version_command
*)cmd
;
5417 uuidCmd
= (uuid_command
*)cmd
;
5421 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
5425 // walk newly mapped dyld_sim __TEXT load commands to find entry point
5426 uintptr_t entry
= 0;
5427 cmd
= (struct load_command
*)(((char*)loadAddress
)+sizeof(macho_header
));
5428 const uint32_t count
= ((macho_header
*)(loadAddress
))->ncmds
;
5429 for (uint32_t i
= 0; i
< count
; ++i
) {
5430 if (cmd
->cmd
== LC_UNIXTHREAD
) {
5432 const i386_thread_state_t
* registers
= (i386_thread_state_t
*)(((char*)cmd
) + 16);
5433 // entry point must be in first segment
5434 if ( registers
->__eip
< firstSeg
->vmaddr
)
5435 return "dyld_sim entry point not in __TEXT segment";
5436 if ( registers
->__eip
> (firstSeg
->vmaddr
+ firstSeg
->vmsize
) )
5437 return "dyld_sim entry point not in __TEXT segment";
5438 entry
= (registers
->__eip
+ loadAddress
- preferredLoadAddress
);
5440 const x86_thread_state64_t
* registers
= (x86_thread_state64_t
*)(((char*)cmd
) + 16);
5441 // entry point must be in first segment
5442 if ( registers
->__rip
< firstSeg
->vmaddr
)
5443 return "dyld_sim entry point not in __TEXT segment";
5444 if ( registers
->__rip
> (firstSeg
->vmaddr
+ firstSeg
->vmsize
) )
5445 return "dyld_sim entry point not in __TEXT segment";
5446 entry
= (registers
->__rip
+ loadAddress
- preferredLoadAddress
);
5449 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
5452 return "dyld_sim entry not found";
5454 // notify debugger that dyld_sim is loaded
5455 dyld_image_info info
;
5456 info
.imageLoadAddress
= (mach_header
*)loadAddress
;
5457 info
.imageFilePath
= strdup(dyldPath
);
5458 info
.imageFileModDate
= sb
.st_mtime
;
5459 addImagesToAllImages(1, &info
);
5460 dyld::gProcessInfo
->notification(dyld_image_adding
, 1, &info
);
5462 fsid_t fsid
= {{0, 0}};
5463 fsobj_id_t fsobj
= {0};
5464 ino_t inode
= sb
.st_ino
;
5465 fsobj
.fid_objno
= (uint32_t)inode
;
5466 fsobj
.fid_generation
= (uint32_t)(inode
>>32);
5467 fsid
.val
[0] = sb
.st_dev
;
5468 dyld3::kdebug_trace_dyld_image(DBG_DYLD_UUID_MAP_A
, dyldPath
, (const uuid_t
*)&uuidCmd
->uuid
[0], fsobj
, fsid
, (const mach_header
*)mh
);
5470 const char** appleParams
= apple
;
5472 // <rdar://problem/5077374> have host dyld detach macOS shared cache from process before jumping into dyld_sim
5473 dyld3::deallocateExistingSharedCache();
5475 // jump into new simulator dyld
5476 typedef uintptr_t (*sim_entry_proc_t
)(int argc
, const char* argv
[], const char* envp
[], const char* apple
[],
5477 const macho_header
* mainExecutableMH
, const macho_header
* dyldMH
, uintptr_t dyldSlide
,
5478 const dyld::SyscallHelpers
* vtable
, uintptr_t* startGlue
);
5479 sim_entry_proc_t newDyld
= (sim_entry_proc_t
)entry
;
5480 *mainAddr
= (*newDyld
)(argc
, argv
, envp
, appleParams
, mainExecutableMH
, (macho_header
*)loadAddress
,
5481 loadAddress
- preferredLoadAddress
,
5482 &sSysCalls
, startGlue
);
5488 // If the DYLD_SKIP_MAIN environment is set to 1, dyld will return the
5489 // address of this function instead of main() in the target program which
5490 // __dyld_start jumps to. Useful for qualifying dyld itself.
5500 #if !TARGET_OS_SIMULATOR
5502 static bool envVarMatches(const dyld3::closure::LaunchClosure
* mainClosure
, const char* envp
[], const char* varName
)
5504 __block
const char* valueFromClosure
= nullptr;
5505 mainClosure
->forEachEnvVar(^(const char* keyEqualValue
, bool& stop
) {
5506 size_t keyLen
= strlen(varName
);
5507 if ( (strncmp(varName
, keyEqualValue
, keyLen
) == 0) && (keyEqualValue
[keyLen
] == '=') ) {
5508 valueFromClosure
= &keyEqualValue
[keyLen
+1];
5513 const char* valueFromEnv
= _simple_getenv(envp
, varName
);
5515 bool inClosure
= (valueFromClosure
!= nullptr);
5516 bool inEnv
= (valueFromEnv
!= nullptr);
5517 if ( inClosure
!= inEnv
)
5519 if ( !inClosure
&& !inEnv
)
5521 return ( strcmp(valueFromClosure
, valueFromEnv
) == 0 );
5524 static const char* const sEnvVarsToCheck
[] = {
5525 "DYLD_LIBRARY_PATH",
5526 "DYLD_FRAMEWORK_PATH",
5527 "DYLD_FALLBACK_LIBRARY_PATH",
5528 "DYLD_FALLBACK_FRAMEWORK_PATH",
5529 "DYLD_INSERT_LIBRARIES",
5530 "DYLD_IMAGE_SUFFIX",
5531 "DYLD_VERSIONED_FRAMEWORK_PATH",
5532 "DYLD_VERSIONED_LIBRARY_PATH",
5536 static bool envVarsMatch(const dyld3::closure::LaunchClosure
* mainClosure
, const char* envp
[])
5538 for (const char* envVar
: sEnvVarsToCheck
) {
5539 if ( !envVarMatches(mainClosure
, envp
, envVar
) ) {
5540 if ( gLinkContext
.verboseWarnings
)
5541 dyld::log("dyld: closure %p not used because %s changed\n", mainClosure
, envVar
);
5546 // FIXME: dyld3 doesn't support versioned paths so we need to fall back to dyld2 if we have them.
5547 // <rdar://problem/37004660> dyld3: support DYLD_VERSIONED_*_PATHs ?
5548 if ( sEnv
.DYLD_VERSIONED_LIBRARY_PATH
!= nullptr ) {
5549 if ( gLinkContext
.verboseWarnings
)
5550 dyld::log("dyld: closure %p not used because DYLD_VERSIONED_LIBRARY_PATH used\n", mainClosure
);
5553 if ( sEnv
.DYLD_VERSIONED_FRAMEWORK_PATH
!= nullptr ) {
5554 if ( gLinkContext
.verboseWarnings
)
5555 dyld::log("dyld: closure %p not used because DYLD_VERSIONED_FRAMEWORK_PATH used\n", mainClosure
);
5562 static bool closureValid(const dyld3::closure::LaunchClosure
* mainClosure
, const dyld3::closure::LoadedFileInfo
& mainFileInfo
,
5563 const uint8_t* mainExecutableCDHash
, bool closureInCache
, const char* envp
[])
5565 if ( closureInCache
) {
5566 // We can only use the cache closure if the cache version is the same as dyld
5567 if (sSharedCacheLoadInfo
.loadAddress
->header
.formatVersion
!= dyld3::closure::kFormatVersion
) {
5568 if ( gLinkContext
.verboseWarnings
)
5569 dyld::log("dyld: dyld closure version 0x%08X does not match dyld cache version 0x%08X\n",
5570 dyld3::closure::kFormatVersion
, sSharedCacheLoadInfo
.loadAddress
->header
.formatVersion
);
5573 if (sForceInvalidSharedCacheClosureFormat
) {
5574 if ( gLinkContext
.verboseWarnings
)
5575 dyld::log("dyld: closure %p dyld cache version forced invalid\n", mainClosure
);
5579 // verify current dyld cache is same as expected
5580 uuid_t expectedCacheUUID
;
5581 if ( mainClosure
->builtAgainstDyldCache(expectedCacheUUID
) ) {
5582 if ( sSharedCacheLoadInfo
.loadAddress
== nullptr ) {
5583 if ( gLinkContext
.verboseWarnings
)
5584 dyld::log("dyld: closure %p dyld cache not loaded\n", mainClosure
);
5588 uuid_t actualCacheUUID
;
5589 sSharedCacheLoadInfo
.loadAddress
->getUUID(actualCacheUUID
);
5590 if ( memcmp(expectedCacheUUID
, actualCacheUUID
, sizeof(uuid_t
)) != 0 ) {
5591 if ( gLinkContext
.verboseWarnings
)
5592 dyld::log("dyld: closure %p not used because built against different dyld cache\n", mainClosure
);
5598 // closure built assume there is no dyld cache
5599 if ( sSharedCacheLoadInfo
.loadAddress
!= nullptr ) {
5600 if ( gLinkContext
.verboseWarnings
)
5601 dyld::log("dyld: closure %p built expecting no dyld cache\n", mainClosure
);
5605 #if __IPHONE_OS_VERSION_MIN_REQUIRED
5606 // verify this closure is not from a previous reboot
5607 const char* expectedBootUUID
= mainClosure
->bootUUID();
5608 char actualBootSessionUUID
[256] = { 0 };
5609 size_t bootSize
= sizeof(actualBootSessionUUID
);
5610 bool gotActualBootUUID
= (sysctlbyname("kern.bootsessionuuid", actualBootSessionUUID
, &bootSize
, NULL
, 0) == 0);
5611 if ( gotActualBootUUID
) {
5612 // If we got a boot UUID then we should have also recorded it in the closure
5613 if ( expectedBootUUID
== nullptr) {
5614 // The closure didn't have a UUID but now we do. This isn't valid.
5615 if ( gLinkContext
.verboseWarnings
)
5616 dyld::log("dyld: closure %p missing boot-UUID\n", mainClosure
);
5618 } else if ( strcmp(expectedBootUUID
, actualBootSessionUUID
) != 0 ) {
5619 if ( gLinkContext
.verboseWarnings
)
5620 dyld::log("dyld: closure %p built in different boot context\n", mainClosure
);
5624 // We didn't get a UUID now, which is ok so long as the closure also doesn't have one.
5625 if ( expectedBootUUID
!= nullptr) {
5626 if ( gLinkContext
.verboseWarnings
)
5627 dyld::log("dyld: closure %p has boot-UUID\n", mainClosure
);
5634 // verify all mach-o files have not changed since closure was built
5635 __block
bool foundFileThatInvalidatesClosure
= false;
5636 mainClosure
->images()->forEachImage(^(const dyld3::closure::Image
* image
, bool& stop
) {
5637 __block
uint64_t expectedInode
;
5638 __block
uint64_t expectedMtime
;
5639 if ( image
->hasFileModTimeAndInode(expectedInode
, expectedMtime
) ) {
5640 struct stat statBuf
;
5641 if ( ::stat(image
->path(), &statBuf
) == 0 ) {
5642 if ( (statBuf
.st_mtime
!= expectedMtime
) || (statBuf
.st_ino
!= expectedInode
) ) {
5643 if ( gLinkContext
.verboseWarnings
)
5644 dyld::log("dyld: closure %p not used because mtime/inode for '%s' has changed since closure was built\n", mainClosure
, image
->path());
5645 foundFileThatInvalidatesClosure
= true;
5650 if ( gLinkContext
.verboseWarnings
)
5651 dyld::log("dyld: closure %p not used because '%s' is needed by closure but is missing\n", mainClosure
, image
->path());
5652 foundFileThatInvalidatesClosure
= true;
5657 if ( foundFileThatInvalidatesClosure
)
5660 // verify cdHash of main executable is same as recorded in closure
5661 const dyld3::closure::Image
* mainImage
= mainClosure
->images()->imageForNum(mainClosure
->topImage());
5663 __block
bool foundCDHash
= false;
5664 __block
bool foundValidCDHash
= false;
5665 mainImage
->forEachCDHash(^(const uint8_t *expectedHash
, bool& stop
) {
5666 if ( mainExecutableCDHash
== nullptr ) {
5667 if ( gLinkContext
.verboseWarnings
)
5668 dyld::log("dyld: closure %p not used because main executable is not code signed but was expected to be\n", mainClosure
);
5673 if ( memcmp(mainExecutableCDHash
, expectedHash
, 20) == 0 ) {
5674 // found a match, so lets use this one.
5675 foundValidCDHash
= true;
5681 // If we found cd hashes, but they were all invalid, then print them out
5682 if ( foundCDHash
&& !foundValidCDHash
) {
5683 auto getCDHashString
= [](const uint8_t cdHash
[20], char* cdHashBuffer
) {
5684 for (int i
=0; i
< 20; ++i
) {
5685 uint8_t byte
= cdHash
[i
];
5686 uint8_t nibbleL
= byte
& 0x0F;
5687 uint8_t nibbleH
= byte
>> 4;
5688 if ( nibbleH
< 10 ) {
5689 *cdHashBuffer
= '0' + nibbleH
;
5692 *cdHashBuffer
= 'a' + (nibbleH
-10);
5695 if ( nibbleL
< 10 ) {
5696 *cdHashBuffer
= '0' + nibbleL
;
5699 *cdHashBuffer
= 'a' + (nibbleL
-10);
5704 if ( gLinkContext
.verboseWarnings
) {
5705 mainImage
->forEachCDHash(^(const uint8_t *expectedHash
, bool &stop
) {
5706 char mainExecutableCDHashBuffer
[128] = { '\0' };
5707 char expectedCDHashBuffer
[128] = { '\0' };
5709 getCDHashString(mainExecutableCDHash
, mainExecutableCDHashBuffer
);
5710 getCDHashString(expectedHash
, expectedCDHashBuffer
);
5712 dyld::log("dyld: closure %p not used because main executable cd-hash (%s) changed since closure was built with (%s)\n",
5713 mainClosure
, mainExecutableCDHashBuffer
, expectedCDHashBuffer
);
5720 // verify UUID of main executable is same as recorded in closure
5721 uuid_t expectedUUID
;
5722 bool hasExpect
= mainImage
->getUuid(expectedUUID
);
5724 const dyld3::MachOLoaded
* mainExecutableMH
= (const dyld3::MachOLoaded
*)mainFileInfo
.fileContent
;
5725 bool hasActual
= mainExecutableMH
->getUuid(actualUUID
);
5726 if ( hasExpect
!= hasActual
) {
5727 if ( gLinkContext
.verboseWarnings
)
5728 dyld::log("dyld: closure %p not used because UUID of executable changed since closure was built\n", mainClosure
);
5731 if ( hasExpect
&& hasActual
&& memcmp(actualUUID
, expectedUUID
, sizeof(uuid_t
)) != 0 ) {
5732 if ( gLinkContext
.verboseWarnings
)
5733 dyld::log("dyld: closure %p not used because UUID of executable changed since closure was built\n", mainClosure
);
5737 // verify DYLD_* env vars are same as when closure was built
5738 if ( !envVarsMatch(mainClosure
, envp
) ) {
5742 // verify files that are supposed to be missing actually are missing
5743 mainClosure
->forEachMustBeMissingFile(^(const char* path
, bool& stop
) {
5744 struct stat statBuf
;
5745 if ( ::stat(path
, &statBuf
) == 0 ) {
5747 foundFileThatInvalidatesClosure
= true;
5748 if ( gLinkContext
.verboseWarnings
)
5749 dyld::log("dyld: closure %p not used because found unexpected file '%s'\n", mainClosure
, path
);
5753 // verify files that are supposed to exist are there with the
5754 mainClosure
->forEachSkipIfExistsFile(^(const dyld3::closure::LaunchClosure::SkippedFile
&file
, bool &stop
) {
5755 struct stat statBuf
;
5756 if ( ::stat(file
.path
, &statBuf
) == 0 ) {
5757 if ( (statBuf
.st_mtime
!= file
.mtime
) || (statBuf
.st_ino
!= file
.inode
) ) {
5758 if ( gLinkContext
.verboseWarnings
)
5759 dyld::log("dyld: closure %p not used because mtime/inode for '%s' has changed since closure was built\n", mainClosure
, file
.path
);
5760 foundFileThatInvalidatesClosure
= true;
5766 // verify closure did not require anything unavailable
5767 if ( mainClosure
->usedAtPaths() && !gLinkContext
.allowAtPaths
) {
5768 if ( gLinkContext
.verboseWarnings
)
5769 dyld::log("dyld: closure %p not used because is used @paths, but process does not allow that\n", mainClosure
);
5772 if ( mainClosure
->usedFallbackPaths() && !gLinkContext
.allowClassicFallbackPaths
) {
5773 if ( gLinkContext
.verboseWarnings
)
5774 dyld::log("dyld: closure %p not used because is used default fallback paths, but process does not allow that\n", mainClosure
);
5778 return !foundFileThatInvalidatesClosure
;
5781 static bool nolog(const char* format
, ...)
5786 static bool dolog(const char* format
, ...)
5789 va_start(list
, format
);
5795 static bool launchWithClosure(const dyld3::closure::LaunchClosure
* mainClosure
,
5796 const DyldSharedCache
* dyldCache
,
5797 const dyld3::MachOLoaded
* mainExecutableMH
, uintptr_t mainExecutableSlide
,
5798 int argc
, const char* argv
[], const char* envp
[], const char* apple
[],
5799 uintptr_t* entry
, uintptr_t* startGlue
)
5801 // build list of all known ImageArrays (at most three: cached dylibs, other OS dylibs, and main prog)
5802 STACK_ALLOC_ARRAY(const dyld3::closure::ImageArray
*, imagesArrays
, 3);
5803 const dyld3::closure::ImageArray
* mainClosureImages
= mainClosure
->images();
5804 if ( dyldCache
!= nullptr ) {
5805 imagesArrays
.push_back(dyldCache
->cachedDylibsImageArray());
5806 if ( auto others
= dyldCache
->otherOSImageArray() )
5807 imagesArrays
.push_back(others
);
5809 imagesArrays
.push_back(mainClosureImages
);
5811 // allocate space for Array<LoadedImage>
5812 STACK_ALLOC_ARRAY(dyld3::LoadedImage
, allImages
, mainClosure
->initialLoadCount());
5814 // Get the pre-optimized Objective-C so that we can bind the selectors
5815 const dyld3::closure::ObjCSelectorOpt
* selectorOpt
= nullptr;
5816 dyld3::Array
<dyld3::closure::Image::ObjCSelectorImage
> selectorImages
;
5817 mainClosure
->selectorHashTable(selectorImages
, selectorOpt
);
5819 __block
dyld3::Loader
loader({}, allImages
, dyldCache
, imagesArrays
,
5820 selectorOpt
, selectorImages
,
5821 (gLinkContext
.verboseLoading
? &dolog
: &nolog
),
5822 (gLinkContext
.verboseMapping
? &dolog
: &nolog
),
5823 (gLinkContext
.verboseBind
? &dolog
: &nolog
),
5824 (gLinkContext
.verboseDOF
? &dolog
: &nolog
));
5825 dyld3::closure::ImageNum mainImageNum
= mainClosure
->topImage();
5826 mainClosureImages
->forEachImage(^(const dyld3::closure::Image
* image
, bool& stop
) {
5827 if ( image
->imageNum() == mainImageNum
) {
5828 // add main executable (which is already mapped by kernel) to list
5829 dyld3::LoadedImage mainLoadedImage
= dyld3::LoadedImage::make(image
, mainExecutableMH
);
5830 mainLoadedImage
.setState(dyld3::LoadedImage::State::mapped
);
5831 mainLoadedImage
.markLeaveMapped();
5832 loader
.addImage(mainLoadedImage
);
5836 // add inserted library to initial list
5837 loader
.addImage(dyld3::LoadedImage::make(image
));
5841 // recursively load all dependents and fill in allImages array
5842 bool someCacheImageOverridden
= false;
5844 loader
.completeAllDependents(diag
, someCacheImageOverridden
);
5845 if ( diag
.noError() )
5846 loader
.mapAndFixupAllImages(diag
, dyld3::Loader::dtraceUserProbesEnabled());
5847 if ( diag
.hasError() ) {
5848 if ( gLinkContext
.verboseWarnings
)
5849 dyld::log("dyld: %s\n", diag
.errorMessage());
5853 //dyld::log("loaded image list:\n");
5854 //for (const dyld3::LoadedImage& info : allImages) {
5855 // dyld::log("mh=%p, path=%s\n", info.loadedAddress(), info.image()->path());
5858 // find libdyld entry
5859 dyld3::closure::Image::ResolvedSymbolTarget dyldEntry
;
5860 mainClosure
->libDyldEntry(dyldEntry
);
5861 const dyld3::LibDyldEntryVector
* libDyldEntry
= (dyld3::LibDyldEntryVector
*)loader
.resolveTarget(dyldEntry
);
5863 // send info on all images to libdyld.dylb
5864 libDyldEntry
->setVars(mainExecutableMH
, argc
, argv
, envp
, apple
);
5865 if ( libDyldEntry
->vectorVersion
> 4 )
5866 libDyldEntry
->setRestrictions(gLinkContext
.allowAtPaths
, gLinkContext
.allowEnvVarsPath
, gLinkContext
.allowClassicFallbackPaths
);
5867 libDyldEntry
->setHaltFunction(&halt
);
5868 if ( libDyldEntry
->vectorVersion
> 5 ) {
5869 libDyldEntry
->setNotifyMonitoringDyldMain(¬ifyMonitoringDyldMain
);
5870 libDyldEntry
->setNotifyMonitoringDyld(¬ifyMonitoringDyld
);
5873 if ( libDyldEntry
->vectorVersion
> 6 )
5874 libDyldEntry
->setHasCacheOverrides(someCacheImageOverridden
);
5876 if ( libDyldEntry
->vectorVersion
> 2 )
5877 libDyldEntry
->setChildForkFunction(&_dyld_fork_child
);
5878 #if !TARGET_OS_SIMULATOR
5879 if ( libDyldEntry
->vectorVersion
> 3 )
5880 libDyldEntry
->setLogFunction(&dyld::vlog
);
5882 libDyldEntry
->setOldAllImageInfo(gProcessInfo
);
5883 dyld3::LoadedImage
* libSys
= loader
.findImage(mainClosure
->libSystemImageNum());
5884 libDyldEntry
->setInitialImageList(mainClosure
, dyldCache
, sSharedCacheLoadInfo
.path
, allImages
, *libSys
);
5886 CRSetCrashLogMessage("dyld3: launch, running initializers");
5887 libDyldEntry
->runInitialzersBottomUp((mach_header
*)mainExecutableMH
);
5888 //dyld::log("returned from runInitialzersBottomUp()\n");
5890 if (dyld3::kdebug_trace_dyld_enabled(DBG_DYLD_TIMING_LAUNCH_EXECUTABLE
)) {
5891 dyld3::kdebug_trace_dyld_duration_end(launchTraceID
, DBG_DYLD_TIMING_LAUNCH_EXECUTABLE
, 0, 0, 3);
5893 #if __MAC_OS_X_VERSION_MIN_REQUIRED
5894 if ( gLinkContext
.driverKit
) {
5895 *entry
= (uintptr_t)sEntryOveride
;
5897 halt("no entry point registered");
5898 *startGlue
= (uintptr_t)(libDyldEntry
->startFunc
);
5903 dyld3::closure::Image::ResolvedSymbolTarget progEntry
;
5904 if ( mainClosure
->mainEntry(progEntry
) ) {
5905 // modern app with LC_MAIN
5906 // set startGlue to "start" function in libdyld.dylib
5907 // set entry to "main" function in program
5908 *startGlue
= (uintptr_t)(libDyldEntry
->startFunc
);
5909 *entry
= loader
.resolveTarget(progEntry
);
5911 else if ( mainClosure
->startEntry(progEntry
) ) {
5912 // old style app linked with crt1.o
5913 // entry is "start" function in program
5915 *entry
= loader
.resolveTarget(progEntry
);
5921 CRSetCrashLogMessage("dyld3 mode");
5926 static const char* getTempDir(const char* envp
[])
5928 if (const char* tempDir
= _simple_getenv(envp
, "TMPDIR"))
5931 #if __MAC_OS_X_VERSION_MIN_REQUIRED
5932 return "/private/tmp/";
5934 return "/private/var/tmp/";
5938 static const dyld3::closure::LaunchClosure
* mapClosureFile(const char* closurePath
)
5940 struct stat statbuf
;
5941 if ( ::stat(closurePath
, &statbuf
) == -1 )
5944 // check for tombstone file
5945 if ( statbuf
.st_size
== 0 )
5948 int fd
= ::open(closurePath
, O_RDONLY
);
5952 const dyld3::closure::LaunchClosure
* closure
= (dyld3::closure::LaunchClosure
*)::mmap(NULL
, (size_t)statbuf
.st_size
, PROT_READ
, MAP_PRIVATE
, fd
, 0);
5955 if ( closure
== MAP_FAILED
)
5961 static bool needsDyld2ErrorMessage(const char* msg
)
5963 if ( strcmp(msg
, "lazy bind opcodes missing binds") == 0 )
5969 // Note: buildLaunchClosure calls halt() if there is an error building the closure
5970 static const dyld3::closure::LaunchClosure
* buildLaunchClosure(const uint8_t* mainExecutableCDHash
,
5971 const dyld3::closure::LoadedFileInfo
& mainFileInfo
, const char* envp
[])
5973 const dyld3::MachOLoaded
* mainExecutableMH
= (const dyld3::MachOLoaded
*)mainFileInfo
.fileContent
;
5974 dyld3::closure::PathOverrides pathOverrides
;
5975 pathOverrides
.setFallbackPathHandling(gLinkContext
.allowClassicFallbackPaths
? dyld3::closure::PathOverrides::FallbackPathMode::classic
: dyld3::closure::PathOverrides::FallbackPathMode::restricted
);
5976 pathOverrides
.setEnvVars(envp
, mainExecutableMH
, mainFileInfo
.path
);
5977 STACK_ALLOC_ARRAY(const dyld3::closure::ImageArray
*, imagesArrays
, 3);
5978 if ( sSharedCacheLoadInfo
.loadAddress
!= nullptr ) {
5979 imagesArrays
.push_back(sSharedCacheLoadInfo
.loadAddress
->cachedDylibsImageArray());
5980 if ( auto others
= sSharedCacheLoadInfo
.loadAddress
->otherOSImageArray() )
5981 imagesArrays
.push_back(others
);
5984 char closurePath
[PATH_MAX
];
5985 dyld3::closure::ClosureBuilder::LaunchErrorInfo
* errorInfo
= (dyld3::closure::ClosureBuilder::LaunchErrorInfo
*)&gProcessInfo
->errorKind
;
5986 dyld3::closure::FileSystemPhysical fileSystem
;
5987 const dyld3::GradedArchs
& archs
= dyld3::GradedArchs::forCurrentOS(mainExecutableMH
);
5988 dyld3::closure::ClosureBuilder::AtPath atPathHanding
= (gLinkContext
.allowAtPaths
? dyld3::closure::ClosureBuilder::AtPath::all
: dyld3::closure::ClosureBuilder::AtPath::none
);
5989 dyld3::closure::ClosureBuilder
builder(dyld3::closure::kFirstLaunchClosureImageNum
, fileSystem
, sSharedCacheLoadInfo
.loadAddress
, true,
5990 archs
, pathOverrides
, atPathHanding
, gLinkContext
.allowEnvVarsPath
, errorInfo
);
5991 if (sForceInvalidSharedCacheClosureFormat
)
5992 builder
.setDyldCacheInvalidFormatVersion();
5993 const dyld3::closure::LaunchClosure
* result
= builder
.makeLaunchClosure(mainFileInfo
, gLinkContext
.allowInsertFailures
);
5994 if ( builder
.diagnostics().hasError() ) {
5995 const char* errMsg
= builder
.diagnostics().errorMessage();
5996 // let apps with this error fallback to dyld2 mode
5997 if ( needsDyld2ErrorMessage(errMsg
) ) {
5998 if ( dyld3::closure::LaunchClosure::buildClosureCachePath(mainFileInfo
.path
, closurePath
, getTempDir(envp
), true) ) {
5999 // create empty file as a tombstone to not keep trying
6000 int fd
= ::open(closurePath
, O_WRONLY
|O_CREAT
, S_IRUSR
|S_IWUSR
);
6002 ::fchmod(fd
, S_IRUSR
);
6004 if ( gLinkContext
.verboseWarnings
)
6005 dyld::log("dyld: just built tombstone closure for %s\n", sExecPath
);
6006 // We only care about closure failures that do not also cause dyld2 to fail, so defer logging
6007 // until after dyld2 has tried to launch the binary
6008 sLogClosureFailure
= true;
6013 // terminate process
6017 if ( result
== nullptr )
6020 if ( !closureValid(result
, mainFileInfo
, mainExecutableCDHash
, false, envp
) ) {
6021 // some how the freshly generated closure is invalid...
6022 result
->deallocate();
6023 if ( gLinkContext
.verboseWarnings
)
6024 dyld::log("dyld: somehow just built closure is invalid\n");
6027 // try to atomically save closure to disk to speed up next launch
6028 if ( dyld3::closure::LaunchClosure::buildClosureCachePath(mainFileInfo
.path
, closurePath
, getTempDir(envp
), true) ) {
6029 char closurePathTemp
[PATH_MAX
];
6030 strlcpy(closurePathTemp
, closurePath
, PATH_MAX
);
6031 int mypid
= getpid();
6035 putHexByte(mypid
>> 24, s
);
6036 putHexByte(mypid
>> 16, s
);
6037 putHexByte(mypid
>> 8, s
);
6038 putHexByte(mypid
, s
);
6040 strlcat(closurePathTemp
, pidBuf
, PATH_MAX
);
6041 int fd
= ::open(closurePathTemp
, O_WRONLY
|O_CREAT
, S_IRUSR
|S_IWUSR
);
6043 ::ftruncate(fd
, result
->size());
6044 ::write(fd
, result
, result
->size());
6045 ::fchmod(fd
, S_IRUSR
);
6047 ::rename(closurePathTemp
, closurePath
);
6048 // free built closure and mmap file() to reduce dirty memory
6049 result
->deallocate();
6050 result
= mapClosureFile(closurePath
);
6052 else if ( gLinkContext
.verboseWarnings
) {
6053 dyld::log("could not save closure (errno=%d) to: %s\n", errno
, closurePathTemp
);
6057 if ( gLinkContext
.verboseWarnings
)
6058 dyld::log("dyld: just built closure %p (size=%lu) for %s\n", result
, result
->size(), sExecPath
);
6063 static const dyld3::closure::LaunchClosure
* findCachedLaunchClosure(const uint8_t* mainExecutableCDHash
,
6064 const dyld3::closure::LoadedFileInfo
& mainFileInfo
,
6067 char closurePath
[PATH_MAX
];
6068 // build base path of $TMPDIR/dyld/<prog-name>-
6069 if ( !dyld3::closure::LaunchClosure::buildClosureCachePath(mainFileInfo
.path
, closurePath
, getTempDir(envp
), false) )
6071 const dyld3::closure::LaunchClosure
* closure
= mapClosureFile(closurePath
);
6072 if ( closure
== nullptr )
6075 if ( !closureValid(closure
, mainFileInfo
, mainExecutableCDHash
, false, envp
) ) {
6076 ::munmap((void*)closure
, closure
->size());
6080 if ( gLinkContext
.verboseWarnings
)
6081 dyld::log("dyld: used cached closure %p (size=%lu) for %s\n", closure
, closure
->size(), sExecPath
);
6086 #endif // !TARGET_OS_SIMULATOR
6089 static ClosureMode
getPlatformDefaultClosureMode() {
6090 #if __MAC_OS_X_VERSION_MIN_REQUIRED
6092 // rdar://problem/32701418: Don't use dyld3 for i386 for now.
6093 return ClosureMode::Off
;
6095 // x86_64 defaults to using the shared cache closures
6096 return ClosureMode::PreBuiltOnly
;
6100 // <rdar://problem/33171968> enable dyld3 mode for all OS programs when using customer dyld cache (no roots)
6101 if ( (sSharedCacheLoadInfo
.loadAddress
!= nullptr) && (sSharedCacheLoadInfo
.loadAddress
->header
.cacheType
== kDyldSharedCacheTypeProduction
) )
6102 return ClosureMode::On
;
6104 return ClosureMode::Off
;
6105 #endif // __MAC_OS_X_VERSION_MIN_REQUIRED
6109 // Entry point for dyld. The kernel loads dyld and jumps to __dyld_start which
6110 // sets up some registers and call this function.
6112 // Returns address of main() in target program which __dyld_start jumps to
6115 _main(const macho_header
* mainExecutableMH
, uintptr_t mainExecutableSlide
,
6116 int argc
, const char* argv
[], const char* envp
[], const char* apple
[],
6117 uintptr_t* startGlue
)
6119 if (dyld3::kdebug_trace_dyld_enabled(DBG_DYLD_TIMING_LAUNCH_EXECUTABLE
)) {
6120 launchTraceID
= dyld3::kdebug_trace_dyld_duration_start(DBG_DYLD_TIMING_LAUNCH_EXECUTABLE
, (uint64_t)mainExecutableMH
, 0, 0);
6123 //Check and see if there are any kernel flags
6124 dyld3::BootArgs::setFlags(hexToUInt64(_simple_getenv(apple
, "dyld_flags"), nullptr));
6126 // Grab the cdHash of the main executable from the environment
6127 uint8_t mainExecutableCDHashBuffer
[20];
6128 const uint8_t* mainExecutableCDHash
= nullptr;
6129 if ( hexToBytes(_simple_getenv(apple
, "executable_cdhash"), 40, mainExecutableCDHashBuffer
) )
6130 mainExecutableCDHash
= mainExecutableCDHashBuffer
;
6132 #if !TARGET_OS_SIMULATOR
6133 // Trace dyld's load
6134 notifyKernelAboutImage((macho_header
*)&__dso_handle
, _simple_getenv(apple
, "dyld_file"));
6135 // Trace the main executable's load
6136 notifyKernelAboutImage(mainExecutableMH
, _simple_getenv(apple
, "executable_file"));
6139 uintptr_t result
= 0;
6140 sMainExecutableMachHeader
= mainExecutableMH
;
6141 sMainExecutableSlide
= mainExecutableSlide
;
6144 // Set the platform ID in the all image infos so debuggers can tell the process type
6145 // FIXME: This can all be removed once we make the kernel handle it in rdar://43369446
6146 if (gProcessInfo
->version
>= 16) {
6147 __block
bool platformFound
= false;
6148 ((dyld3::MachOFile
*)mainExecutableMH
)->forEachSupportedPlatform(^(dyld3::Platform platform
, uint32_t minOS
, uint32_t sdk
) {
6149 if (platformFound
) {
6150 halt("MH_EXECUTE binaries may only specify one platform");
6152 gProcessInfo
->platform
= (uint32_t)platform
;
6153 platformFound
= true;
6155 if (gProcessInfo
->platform
== (uint32_t)dyld3::Platform::unknown
) {
6156 // There were no platforms found in the binary. This may occur on macOS for alternate toolchains and old binaries.
6157 // It should never occur on any of our embedded platforms.
6158 #if __MAC_OS_X_VERSION_MIN_REQUIRED
6159 gProcessInfo
->platform
= (uint32_t)dyld3::Platform::macOS
;
6161 halt("MH_EXECUTE binaries must specify a minimum supported OS version");
6166 #if __MAC_OS_X_VERSION_MIN_REQUIRED
6167 // Check to see if we need to override the platform
6168 const char* forcedPlatform
= _simple_getenv(envp
, "DYLD_FORCE_PLATFORM");
6169 if (forcedPlatform
) {
6170 if (strncmp(forcedPlatform
, "6", 1) != 0) {
6171 halt("DYLD_FORCE_PLATFORM is only supported for platform 6");
6173 const dyld3::MachOFile
* mf
= (dyld3::MachOFile
*)sMainExecutableMachHeader
;
6174 if (mf
->allowsAlternatePlatform()) {
6175 gProcessInfo
->platform
= PLATFORM_IOSMAC
;
6179 // if this is host dyld, check to see if iOS simulator is being run
6180 const char* rootPath
= _simple_getenv(envp
, "DYLD_ROOT_PATH");
6181 if ( (rootPath
!= NULL
) ) {
6182 // look to see if simulator has its own dyld
6183 char simDyldPath
[PATH_MAX
];
6184 strlcpy(simDyldPath
, rootPath
, PATH_MAX
);
6185 strlcat(simDyldPath
, "/usr/lib/dyld_sim", PATH_MAX
);
6186 int fd
= my_open(simDyldPath
, O_RDONLY
, 0);
6188 const char* errMessage
= useSimulatorDyld(fd
, mainExecutableMH
, simDyldPath
, argc
, argv
, envp
, apple
, startGlue
, &result
);
6189 if ( errMessage
!= NULL
)
6195 ((dyld3::MachOFile
*)mainExecutableMH
)->forEachSupportedPlatform(^(dyld3::Platform platform
, uint32_t minOS
, uint32_t sdk
) {
6196 if ( dyld3::MachOFile::isSimulatorPlatform(platform
) )
6197 halt("attempt to run simulator program outside simulator (DYLD_ROOT_PATH not set)");
6202 CRSetCrashLogMessage("dyld: launch started");
6204 setContext(mainExecutableMH
, argc
, argv
, envp
, apple
);
6206 // Pickup the pointer to the exec path.
6207 sExecPath
= _simple_getenv(apple
, "executable_path");
6209 // <rdar://problem/13868260> Remove interim apple[0] transition code from dyld
6210 if (!sExecPath
) sExecPath
= apple
[0];
6212 #if __IPHONE_OS_VERSION_MIN_REQUIRED && !TARGET_OS_SIMULATOR
6213 // <rdar://54095622> kernel is not passing a real path for main executable
6214 if ( strncmp(sExecPath
, "/var/containers/Bundle/Application/", 35) == 0 ) {
6215 if ( char* newPath
= (char*)malloc(strlen(sExecPath
)+10) ) {
6216 strcpy(newPath
, "/private");
6217 strcat(newPath
, sExecPath
);
6218 sExecPath
= newPath
;
6223 if ( sExecPath
[0] != '/' ) {
6224 // have relative path, use cwd to make absolute
6225 char cwdbuff
[MAXPATHLEN
];
6226 if ( getcwd(cwdbuff
, MAXPATHLEN
) != NULL
) {
6227 // maybe use static buffer to avoid calling malloc so early...
6228 char* s
= new char[strlen(cwdbuff
) + strlen(sExecPath
) + 2];
6231 strcat(s
, sExecPath
);
6236 // Remember short name of process for later logging
6237 sExecShortName
= ::strrchr(sExecPath
, '/');
6238 if ( sExecShortName
!= NULL
)
6241 sExecShortName
= sExecPath
;
6243 configureProcessRestrictions(mainExecutableMH
, envp
);
6245 // Check if we should force dyld3. Note we have to do this outside of the regular env parsing due to AMFI
6246 if ( dyld3::internalInstall() ) {
6247 if (const char* useClosures
= _simple_getenv(envp
, "DYLD_USE_CLOSURES")) {
6248 if ( strcmp(useClosures
, "0") == 0 ) {
6249 sClosureMode
= ClosureMode::Off
;
6250 } else if ( strcmp(useClosures
, "1") == 0 ) {
6251 #if __MAC_OS_X_VERSION_MIN_REQUIRED
6254 // don't support dyld3 for 32-bit macOS
6256 // Also don't support dyld3 for iOSMac right now
6257 if ( gProcessInfo
->platform
!= PLATFORM_IOSMAC
) {
6258 sClosureMode
= ClosureMode::On
;
6263 sClosureMode
= ClosureMode::On
;
6264 #endif // __MAC_OS_X_VERSION_MIN_REQUIRED
6266 dyld::warn("unknown option to DYLD_USE_CLOSURES. Valid options are: 0 and 1\n");
6272 #if __MAC_OS_X_VERSION_MIN_REQUIRED
6273 if ( !gLinkContext
.allowEnvVarsPrint
&& !gLinkContext
.allowEnvVarsPath
&& !gLinkContext
.allowEnvVarsSharedCache
) {
6274 pruneEnvironmentVariables(envp
, &apple
);
6275 // set again because envp and apple may have changed or moved
6276 setContext(mainExecutableMH
, argc
, argv
, envp
, apple
);
6281 checkEnvironmentVariables(envp
);
6282 defaultUninitializedFallbackPaths(envp
);
6284 #if __MAC_OS_X_VERSION_MIN_REQUIRED
6285 if ( gProcessInfo
->platform
== PLATFORM_IOSMAC
) {
6286 gLinkContext
.rootPaths
= parseColonList("/System/iOSSupport", NULL
);
6287 gLinkContext
.iOSonMac
= true;
6288 if ( sEnv
.DYLD_FALLBACK_LIBRARY_PATH
== sLibraryFallbackPaths
)
6289 sEnv
.DYLD_FALLBACK_LIBRARY_PATH
= sRestrictedLibraryFallbackPaths
;
6290 if ( sEnv
.DYLD_FALLBACK_FRAMEWORK_PATH
== sFrameworkFallbackPaths
)
6291 sEnv
.DYLD_FALLBACK_FRAMEWORK_PATH
= sRestrictedFrameworkFallbackPaths
;
6293 else if ( ((dyld3::MachOFile
*)mainExecutableMH
)->supportsPlatform(dyld3::Platform::driverKit
) ) {
6294 gLinkContext
.driverKit
= true;
6295 gLinkContext
.sharedRegionMode
= ImageLoader::kDontUseSharedRegion
;
6298 if ( sEnv
.DYLD_PRINT_OPTS
)
6300 if ( sEnv
.DYLD_PRINT_ENV
)
6301 printEnvironmentVariables(envp
);
6303 // Parse this envirionment variable outside of the regular logic as we want to accept
6304 // this on binaries without an entitelment
6305 #if !TARGET_OS_SIMULATOR
6306 if ( _simple_getenv(envp
, "DYLD_JUST_BUILD_CLOSURE") != nullptr ) {
6307 #if TARGET_OS_IPHONE
6308 const char* tempDir
= getTempDir(envp
);
6309 if ( (tempDir
!= nullptr) && (geteuid() != 0) ) {
6310 // Use realpath to prevent something like TMPRIR=/tmp/../usr/bin
6311 char realPath
[PATH_MAX
];
6312 if ( realpath(tempDir
, realPath
) != NULL
)
6314 if (strncmp(tempDir
, "/private/var/mobile/Containers/", strlen("/private/var/mobile/Containers/")) == 0) {
6315 sJustBuildClosure
= true;
6319 // If we didn't like the format of TMPDIR, just exit. We don't want to launch the app as that would bring up the UI
6320 if (!sJustBuildClosure
) {
6321 _exit(EXIT_SUCCESS
);
6326 if ( sJustBuildClosure
)
6327 sClosureMode
= ClosureMode::On
;
6328 getHostInfo(mainExecutableMH
, mainExecutableSlide
);
6330 // load shared cache
6331 checkSharedRegionDisable((dyld3::MachOLoaded
*)mainExecutableMH
, mainExecutableSlide
);
6332 if ( gLinkContext
.sharedRegionMode
!= ImageLoader::kDontUseSharedRegion
) {
6333 #if TARGET_OS_SIMULATOR
6334 if ( sSharedCacheOverrideDir
)
6341 // If we haven't got a closure mode yet, then check the environment and cache type
6342 if ( sClosureMode
== ClosureMode::Unset
) {
6343 // First test to see if we forced in dyld2 via a kernel boot-arg
6344 if ( dyld3::BootArgs::forceDyld2() ) {
6345 sClosureMode
= ClosureMode::Off
;
6346 } else if ( inDenyList(sExecPath
) ) {
6347 sClosureMode
= ClosureMode::Off
;
6348 } else if ( sEnv
.hasOverride
) {
6349 sClosureMode
= ClosureMode::Off
;
6350 } else if ( dyld3::BootArgs::forceDyld3() ) {
6351 sClosureMode
= ClosureMode::On
;
6353 sClosureMode
= getPlatformDefaultClosureMode();
6357 #if !TARGET_OS_SIMULATOR
6358 if ( sClosureMode
== ClosureMode::Off
) {
6359 if ( gLinkContext
.verboseWarnings
)
6360 dyld::log("dyld: not using closure because of DYLD_USE_CLOSURES or -force_dyld2=1 override\n");
6362 const dyld3::closure::LaunchClosure
* mainClosure
= nullptr;
6363 dyld3::closure::LoadedFileInfo mainFileInfo
;
6364 mainFileInfo
.fileContent
= mainExecutableMH
;
6365 mainFileInfo
.path
= sExecPath
;
6366 // FIXME: If we are saving this closure, this slice offset/length is probably wrong in the case of FAT files.
6367 mainFileInfo
.sliceOffset
= 0;
6368 mainFileInfo
.sliceLen
= -1;
6369 struct stat mainExeStatBuf
;
6370 if ( ::stat(sExecPath
, &mainExeStatBuf
) == 0 ) {
6371 mainFileInfo
.inode
= mainExeStatBuf
.st_ino
;
6372 mainFileInfo
.mtime
= mainExeStatBuf
.st_mtime
;
6374 // check for closure in cache first
6375 if ( sSharedCacheLoadInfo
.loadAddress
!= nullptr ) {
6376 mainClosure
= sSharedCacheLoadInfo
.loadAddress
->findClosure(sExecPath
);
6377 if ( gLinkContext
.verboseWarnings
&& (mainClosure
!= nullptr) )
6378 dyld::log("dyld: found closure %p (size=%lu) in dyld shared cache\n", mainClosure
, mainClosure
->size());
6381 // We only want to try build a closure at runtime if its an iOS third party binary, or a macOS binary from the shared cache
6382 bool allowClosureRebuilds
= false;
6383 if ( sClosureMode
== ClosureMode::On
) {
6384 allowClosureRebuilds
= true;
6385 } else if ( (sClosureMode
== ClosureMode::PreBuiltOnly
) && (mainClosure
!= nullptr) ) {
6386 allowClosureRebuilds
= true;
6389 if ( (mainClosure
!= nullptr) && !closureValid(mainClosure
, mainFileInfo
, mainExecutableCDHash
, true, envp
) )
6390 mainClosure
= nullptr;
6392 // If we didn't find a valid cache closure then try build a new one
6393 if ( (mainClosure
== nullptr) && allowClosureRebuilds
) {
6394 // if forcing closures, and no closure in cache, or it is invalid, check for cached closure
6395 if ( !sForceInvalidSharedCacheClosureFormat
)
6396 mainClosure
= findCachedLaunchClosure(mainExecutableCDHash
, mainFileInfo
, envp
);
6397 if ( mainClosure
== nullptr ) {
6398 // if no cached closure found, build new one
6399 mainClosure
= buildLaunchClosure(mainExecutableCDHash
, mainFileInfo
, envp
);
6403 // exit dyld after closure is built, without running program
6404 if ( sJustBuildClosure
)
6405 _exit(EXIT_SUCCESS
);
6407 // try using launch closure
6408 if ( mainClosure
!= nullptr ) {
6409 CRSetCrashLogMessage("dyld3: launch started");
6410 bool launched
= launchWithClosure(mainClosure
, sSharedCacheLoadInfo
.loadAddress
, (dyld3::MachOLoaded
*)mainExecutableMH
,
6411 mainExecutableSlide
, argc
, argv
, envp
, apple
, &result
, startGlue
);
6412 if ( !launched
&& allowClosureRebuilds
) {
6413 // closure is out of date, build new one
6414 mainClosure
= buildLaunchClosure(mainExecutableCDHash
, mainFileInfo
, envp
);
6415 if ( mainClosure
!= nullptr ) {
6416 launched
= launchWithClosure(mainClosure
, sSharedCacheLoadInfo
.loadAddress
, (dyld3::MachOLoaded
*)mainExecutableMH
,
6417 mainExecutableSlide
, argc
, argv
, envp
, apple
, &result
, startGlue
);
6421 #if __has_feature(ptrauth_calls)
6422 // start() calls the result pointer as a function pointer so we need to sign it.
6423 result
= (uintptr_t)__builtin_ptrauth_sign_unauthenticated((void*)result
, 0, 0);
6426 result
= (uintptr_t)&fake_main
;
6430 if ( gLinkContext
.verboseWarnings
) {
6431 dyld::log("dyld: unable to use closure %p\n", mainClosure
);
6436 #endif // TARGET_OS_SIMULATOR
6437 // could not use closure info, launch old way
6441 // install gdb notifier
6442 stateToHandlers(dyld_image_state_dependents_mapped
, sBatchHandlers
)->push_back(notifyGDB
);
6443 stateToHandlers(dyld_image_state_mapped
, sSingleHandlers
)->push_back(updateAllImages
);
6444 // make initial allocations large enough that it is unlikely to need to be re-alloced
6445 sImageRoots
.reserve(16);
6446 sAddImageCallbacks
.reserve(4);
6447 sRemoveImageCallbacks
.reserve(4);
6448 sAddLoadImageCallbacks
.reserve(4);
6449 sImageFilesNeedingTermination
.reserve(16);
6450 sImageFilesNeedingDOFUnregistration
.reserve(8);
6452 #if !TARGET_OS_SIMULATOR
6453 #ifdef WAIT_FOR_SYSTEM_ORDER_HANDSHAKE
6454 // <rdar://problem/6849505> Add gating mechanism to dyld support system order file generation process
6455 WAIT_FOR_SYSTEM_ORDER_HANDSHAKE(dyld::gProcessInfo
->systemOrderFlag
);
6461 // add dyld itself to UUID list
6462 addDyldImageToUUIDList();
6464 #if SUPPORT_ACCELERATE_TABLES
6466 // Disable accelerator tables when we have threaded rebase/bind, which is arm64e executables only for now.
6467 if (sMainExecutableMachHeader
->cpusubtype
== CPU_SUBTYPE_ARM64E
)
6468 sDisableAcceleratorTables
= true;
6470 bool mainExcutableAlreadyRebased
= false;
6471 if ( (sSharedCacheLoadInfo
.loadAddress
!= nullptr) && !dylibsCanOverrideCache() && !sDisableAcceleratorTables
&& (sSharedCacheLoadInfo
.loadAddress
->header
.accelerateInfoAddr
!= 0) ) {
6472 struct stat statBuf
;
6473 if ( ::stat(IPHONE_DYLD_SHARED_CACHE_DIR
"no-dyld2-accelerator-tables", &statBuf
) != 0 )
6474 sAllCacheImagesProxy
= ImageLoaderMegaDylib::makeImageLoaderMegaDylib(&sSharedCacheLoadInfo
.loadAddress
->header
, sSharedCacheLoadInfo
.slide
, mainExecutableMH
, gLinkContext
);
6481 #if __MAC_OS_X_VERSION_MIN_REQUIRED
6482 gLinkContext
.strictMachORequired
= false;
6483 // <rdar://problem/22805519> be less strict about old macOS mach-o binaries
6484 ((dyld3::MachOFile
*)mainExecutableMH
)->forEachSupportedPlatform(^(dyld3::Platform platform
, uint32_t minOS
, uint32_t sdk
) {
6485 if ( (platform
== dyld3::Platform::macOS
) && (sdk
>= DYLD_PACKED_VERSION(10,15,0)) ) {
6486 gLinkContext
.strictMachORequired
= true;
6489 if ( gLinkContext
.iOSonMac
)
6490 gLinkContext
.strictMachORequired
= true;
6492 // simulators, iOS, tvOS, watchOS, are always strict
6493 gLinkContext
.strictMachORequired
= true;
6497 CRSetCrashLogMessage(sLoadingCrashMessage
);
6498 // instantiate ImageLoader for main executable
6499 sMainExecutable
= instantiateFromLoadedImage(mainExecutableMH
, mainExecutableSlide
, sExecPath
);
6500 gLinkContext
.mainExecutable
= sMainExecutable
;
6501 gLinkContext
.mainExecutableCodeSigned
= hasCodeSignatureLoadCommand(mainExecutableMH
);
6503 #if TARGET_OS_SIMULATOR
6504 // check main executable is not too new for this OS
6506 if ( ! isSimulatorBinary((uint8_t*)mainExecutableMH
, sExecPath
) ) {
6507 throwf("program was built for a platform that is not supported by this runtime");
6509 uint32_t mainMinOS
= sMainExecutable
->minOSVersion();
6511 // dyld is always built for the current OS, so we can get the current OS version
6512 // from the load command in dyld itself.
6513 uint32_t dyldMinOS
= ImageLoaderMachO::minOSVersion((const mach_header
*)&__dso_handle
);
6514 if ( mainMinOS
> dyldMinOS
) {
6516 throwf("app was built for watchOS %d.%d which is newer than this simulator %d.%d",
6517 mainMinOS
>> 16, ((mainMinOS
>> 8) & 0xFF),
6518 dyldMinOS
>> 16, ((dyldMinOS
>> 8) & 0xFF));
6520 throwf("app was built for tvOS %d.%d which is newer than this simulator %d.%d",
6521 mainMinOS
>> 16, ((mainMinOS
>> 8) & 0xFF),
6522 dyldMinOS
>> 16, ((dyldMinOS
>> 8) & 0xFF));
6524 throwf("app was built for iOS %d.%d which is newer than this simulator %d.%d",
6525 mainMinOS
>> 16, ((mainMinOS
>> 8) & 0xFF),
6526 dyldMinOS
>> 16, ((dyldMinOS
>> 8) & 0xFF));
6533 #if SUPPORT_ACCELERATE_TABLES
6534 sAllImages
.reserve((sAllCacheImagesProxy
!= NULL
) ? 16 : INITIAL_IMAGE_COUNT
);
6536 sAllImages
.reserve(INITIAL_IMAGE_COUNT
);
6539 // Now that shared cache is loaded, setup an versioned dylib overrides
6540 #if SUPPORT_VERSIONED_PATHS
6541 checkVersionedPaths();
6545 // dyld_all_image_infos image list does not contain dyld
6546 // add it as dyldPath field in dyld_all_image_infos
6547 // for simulator, dyld_sim is in image list, need host dyld added
6548 #if TARGET_OS_SIMULATOR
6549 // get path of host dyld from table of syscall vectors in host dyld
6550 void* addressInDyld
= gSyscallHelpers
;
6552 // get path of dyld itself
6553 void* addressInDyld
= (void*)&__dso_handle
;
6555 char dyldPathBuffer
[MAXPATHLEN
+1];
6556 int len
= proc_regionfilename(getpid(), (uint64_t)(long)addressInDyld
, dyldPathBuffer
, MAXPATHLEN
);
6558 dyldPathBuffer
[len
] = '\0'; // proc_regionfilename() does not zero terminate returned string
6559 if ( strcmp(dyldPathBuffer
, gProcessInfo
->dyldPath
) != 0 )
6560 gProcessInfo
->dyldPath
= strdup(dyldPathBuffer
);
6563 // load any inserted libraries
6564 if ( sEnv
.DYLD_INSERT_LIBRARIES
!= NULL
) {
6565 for (const char* const* lib
= sEnv
.DYLD_INSERT_LIBRARIES
; *lib
!= NULL
; ++lib
)
6566 loadInsertedDylib(*lib
);
6568 // record count of inserted libraries so that a flat search will look at
6569 // inserted libraries, then main, then others.
6570 sInsertedDylibCount
= sAllImages
.size()-1;
6572 // link main executable
6573 gLinkContext
.linkingMainExecutable
= true;
6574 #if SUPPORT_ACCELERATE_TABLES
6575 if ( mainExcutableAlreadyRebased
) {
6576 // previous link() on main executable has already adjusted its internal pointers for ASLR
6577 // work around that by rebasing by inverse amount
6578 sMainExecutable
->rebase(gLinkContext
, -mainExecutableSlide
);
6581 link(sMainExecutable
, sEnv
.DYLD_BIND_AT_LAUNCH
, true, ImageLoader::RPathChain(NULL
, NULL
), -1);
6582 sMainExecutable
->setNeverUnloadRecursive();
6583 if ( sMainExecutable
->forceFlat() ) {
6584 gLinkContext
.bindFlat
= true;
6585 gLinkContext
.prebindUsage
= ImageLoader::kUseNoPrebinding
;
6588 // link any inserted libraries
6589 // do this after linking main executable so that any dylibs pulled in by inserted
6590 // dylibs (e.g. libSystem) will not be in front of dylibs the program uses
6591 if ( sInsertedDylibCount
> 0 ) {
6592 for(unsigned int i
=0; i
< sInsertedDylibCount
; ++i
) {
6593 ImageLoader
* image
= sAllImages
[i
+1];
6594 link(image
, sEnv
.DYLD_BIND_AT_LAUNCH
, true, ImageLoader::RPathChain(NULL
, NULL
), -1);
6595 image
->setNeverUnloadRecursive();
6597 // only INSERTED libraries can interpose
6598 // register interposing info after all inserted libraries are bound so chaining works
6599 for(unsigned int i
=0; i
< sInsertedDylibCount
; ++i
) {
6600 ImageLoader
* image
= sAllImages
[i
+1];
6601 image
->registerInterposing(gLinkContext
);
6605 // <rdar://problem/19315404> dyld should support interposition even without DYLD_INSERT_LIBRARIES
6606 for (long i
=sInsertedDylibCount
+1; i
< sAllImages
.size(); ++i
) {
6607 ImageLoader
* image
= sAllImages
[i
];
6608 if ( image
->inSharedCache() )
6610 image
->registerInterposing(gLinkContext
);
6612 #if SUPPORT_ACCELERATE_TABLES
6613 if ( (sAllCacheImagesProxy
!= NULL
) && ImageLoader::haveInterposingTuples() ) {
6614 // Accelerator tables cannot be used with implicit interposing, so relaunch with accelerator tables disabled
6615 ImageLoader::clearInterposingTuples();
6616 // unmap all loaded dylibs (but not main executable)
6617 for (long i
=1; i
< sAllImages
.size(); ++i
) {
6618 ImageLoader
* image
= sAllImages
[i
];
6619 if ( image
== sMainExecutable
)
6621 if ( image
== sAllCacheImagesProxy
)
6623 image
->setCanUnload();
6624 ImageLoader::deleteImage(image
);
6626 // 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
6628 sImageRoots
.clear();
6629 sImageFilesNeedingTermination
.clear();
6630 sImageFilesNeedingDOFUnregistration
.clear();
6631 sAddImageCallbacks
.clear();
6632 sRemoveImageCallbacks
.clear();
6633 sAddLoadImageCallbacks
.clear();
6634 sAddBulkLoadImageCallbacks
.clear();
6635 sDisableAcceleratorTables
= true;
6636 sAllCacheImagesProxy
= NULL
;
6637 sMappedRangesStart
= NULL
;
6638 mainExcutableAlreadyRebased
= true;
6639 gLinkContext
.linkingMainExecutable
= false;
6641 goto reloadAllImages
;
6645 // apply interposing to initial set of images
6646 for(int i
=0; i
< sImageRoots
.size(); ++i
) {
6647 sImageRoots
[i
]->applyInterposing(gLinkContext
);
6649 ImageLoader::applyInterposingToDyldCache(gLinkContext
);
6651 // Bind and notify for the main executable now that interposing has been registered
6652 uint64_t bindMainExecutableStartTime
= mach_absolute_time();
6653 sMainExecutable
->recursiveBindWithAccounting(gLinkContext
, sEnv
.DYLD_BIND_AT_LAUNCH
, true);
6654 uint64_t bindMainExecutableEndTime
= mach_absolute_time();
6655 ImageLoaderMachO::fgTotalBindTime
+= bindMainExecutableEndTime
- bindMainExecutableStartTime
;
6656 gLinkContext
.notifyBatch(dyld_image_state_bound
, false);
6658 // Bind and notify for the inserted images now interposing has been registered
6659 if ( sInsertedDylibCount
> 0 ) {
6660 for(unsigned int i
=0; i
< sInsertedDylibCount
; ++i
) {
6661 ImageLoader
* image
= sAllImages
[i
+1];
6662 image
->recursiveBind(gLinkContext
, sEnv
.DYLD_BIND_AT_LAUNCH
, true);
6666 // <rdar://problem/12186933> do weak binding only after all inserted images linked
6667 sMainExecutable
->weakBind(gLinkContext
);
6668 gLinkContext
.linkingMainExecutable
= false;
6670 sMainExecutable
->recursiveMakeDataReadOnly(gLinkContext
);
6672 CRSetCrashLogMessage("dyld: launch, running initializers");
6673 #if SUPPORT_OLD_CRT_INITIALIZATION
6674 // Old way is to run initializers via a callback from crt1.o
6675 if ( ! gRunInitializersOldWay
)
6676 initializeMainExecutable();
6678 // run all initializers
6679 initializeMainExecutable();
6682 // notify any montoring proccesses that this process is about to enter main()
6683 notifyMonitoringDyldMain();
6684 if (dyld3::kdebug_trace_dyld_enabled(DBG_DYLD_TIMING_LAUNCH_EXECUTABLE
)) {
6685 dyld3::kdebug_trace_dyld_duration_end(launchTraceID
, DBG_DYLD_TIMING_LAUNCH_EXECUTABLE
, 0, 0, 2);
6687 ARIADNEDBG_CODE(220, 1);
6689 #if __MAC_OS_X_VERSION_MIN_REQUIRED
6690 if ( gLinkContext
.driverKit
) {
6691 result
= (uintptr_t)sEntryOveride
;
6693 halt("no entry point registered");
6694 *startGlue
= (uintptr_t)gLibSystemHelpers
->startGlueToCallExit
;
6699 // find entry point for main executable
6700 result
= (uintptr_t)sMainExecutable
->getEntryFromLC_MAIN();
6701 if ( result
!= 0 ) {
6702 // main executable uses LC_MAIN, we need to use helper in libdyld to call into main()
6703 if ( (gLibSystemHelpers
!= NULL
) && (gLibSystemHelpers
->version
>= 9) )
6704 *startGlue
= (uintptr_t)gLibSystemHelpers
->startGlueToCallExit
;
6706 halt("libdyld.dylib support not present for LC_MAIN");
6709 // main executable uses LC_UNIXTHREAD, dyld needs to let "start" in program set up for main()
6710 result
= (uintptr_t)sMainExecutable
->getEntryFromLC_UNIXTHREAD();
6714 #if __has_feature(ptrauth_calls)
6715 // start() calls the result pointer as a function pointer so we need to sign it.
6716 result
= (uintptr_t)__builtin_ptrauth_sign_unauthenticated((void*)result
, 0, 0);
6719 catch(const char* message
) {
6724 dyld::log("dyld: launch failed\n");
6727 CRSetCrashLogMessage("dyld2 mode");
6728 #if !TARGET_OS_SIMULATOR
6729 if (sLogClosureFailure
) {
6730 // We failed to launch in dyld3, but dyld2 can handle it. synthesize a crash report for analytics
6731 dyld3::syntheticBacktrace("Could not generate launchClosure, falling back to dyld2", true);
6736 notifyMonitoringDyldMain();
6737 if (dyld3::kdebug_trace_dyld_enabled(DBG_DYLD_TIMING_LAUNCH_EXECUTABLE
)) {
6738 dyld3::kdebug_trace_dyld_duration_end(launchTraceID
, DBG_DYLD_TIMING_LAUNCH_EXECUTABLE
, 0, 0, 2);
6740 ARIADNEDBG_CODE(220, 1);
6741 result
= (uintptr_t)&fake_main
;
6742 *startGlue
= (uintptr_t)gLibSystemHelpers
->startGlueToCallExit
;