Loading...
src/dyld.cpp dyld-360.21 dyld-195.5
--- dyld/dyld-360.21/src/dyld.cpp
+++ dyld/dyld-195.5/src/dyld.cpp
@@ -1,6 +1,6 @@
 /* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*-
  *
- * Copyright (c) 2004-2013 Apple Inc. All rights reserved.
+ * Copyright (c) 2004-2010 Apple Inc. All rights reserved.
  *
  * @APPLE_LICENSE_HEADER_START@
  * 
@@ -30,29 +30,20 @@
 #include <dirent.h>
 #include <sys/param.h>
 #include <mach/mach_time.h> // mach_absolute_time()
-#include <mach/mach_init.h> 
 #include <sys/types.h>
 #include <sys/stat.h> 
 #include <sys/syscall.h>
-#include <sys/socket.h>
-#include <sys/un.h>
-#include <sys/syslog.h>
-#include <sys/uio.h>
-#include <mach-o/fat.h>
+#include <mach-o/fat.h> 
 #include <mach-o/loader.h> 
 #include <mach-o/ldsyms.h> 
 #include <libkern/OSByteOrder.h> 
-#include <libkern/OSAtomic.h>
 #include <mach/mach.h>
 #include <sys/sysctl.h>
 #include <sys/mman.h>
 #include <sys/dtrace.h>
 #include <libkern/OSAtomic.h>
 #include <Availability.h>
-#include <System/sys/codesign.h>
-#include <System/sys/csr.h>
-#include <_simple.h>
-#include <os/lock_private.h>
+#include <Kernel/sys/codesign.h>
 
 
 #ifndef CPU_SUBTYPE_ARM_V5TEJ
@@ -64,22 +55,9 @@
 #ifndef CPU_SUBTYPE_ARM_V7
 	#define CPU_SUBTYPE_ARM_V7			((cpu_subtype_t) 9)
 #endif
-#ifndef CPU_SUBTYPE_ARM_V7F
-	#define CPU_SUBTYPE_ARM_V7F			((cpu_subtype_t) 10)
-#endif
-#ifndef CPU_SUBTYPE_ARM_V7S
-	#define CPU_SUBTYPE_ARM_V7S			((cpu_subtype_t) 11)
-#endif
-#ifndef CPU_SUBTYPE_ARM_V7K
-	#define CPU_SUBTYPE_ARM_V7K			((cpu_subtype_t) 12)
-#endif
 #ifndef LC_DYLD_ENVIRONMENT
 	#define LC_DYLD_ENVIRONMENT			0x27
 #endif
-
-#ifndef CPU_SUBTYPE_X86_64_H
-	#define CPU_SUBTYPE_X86_64_H		((cpu_subtype_t) 8) 
-#endif	
 
 #ifndef VM_PROT_SLIDE   
     #define VM_PROT_SLIDE 0x20
@@ -94,36 +72,26 @@
 #include "ImageLoader.h"
 #include "ImageLoaderMachO.h"
 #include "dyldLibSystemInterface.h"
-#include "dyldSyscallInterface.h"
 #if DYLD_SHARED_CACHE_SUPPORT
 #include "dyld_cache_format.h"
 #endif
-#include <coreSymbolicationDyldSupport.h>
-#if TARGET_IPHONE_SIMULATOR
-	extern "C" void xcoresymbolication_load_notifier(void *connection, uint64_t load_timestamp, const char *image_path, const struct mach_header *mach_header);
-	extern "C" void xcoresymbolication_unload_notifier(void *connection, uint64_t unload_timestamp, const char *image_path, const struct mach_header *mach_header);
-	#define coresymbolication_load_notifier(c, t, p, h) xcoresymbolication_load_notifier(c, t, p, h)
-	#define coresymbolication_unload_notifier(c, t, p, h) xcoresymbolication_unload_notifier(c, t, p, h)
-#endif
-
-// not libc header for send() syscall interface
-extern "C" ssize_t __sendto(int, const void *, size_t, int, const struct sockaddr *, socklen_t);
-
-
-// ARM and x86_64 are the only architecture that use cpu-sub-types
-#define CPU_SUBTYPES_SUPPORTED  ((__arm__ || __x86_64__) && !TARGET_IPHONE_SIMULATOR)
-
-#if __LP64__
-	#define LC_SEGMENT_COMMAND		LC_SEGMENT_64
-	#define LC_SEGMENT_COMMAND_WRONG LC_SEGMENT
-	#define macho_segment_command	segment_command_64
-	#define macho_section			section_64
-#else
-	#define LC_SEGMENT_COMMAND		LC_SEGMENT
-	#define LC_SEGMENT_COMMAND_WRONG LC_SEGMENT_64
-	#define macho_segment_command	segment_command
-	#define macho_section			section
-#endif
+#if CORESYMBOLICATION_SUPPORT
+#include "coreSymbolicationDyldSupport.hpp"
+#endif
+
+// from _simple.h in libc
+typedef struct _SIMPLE*		_SIMPLE_STRING;
+extern "C" void				_simple_vdprintf(int __fd, const char *__fmt, va_list __ap);
+extern "C" void				_simple_dprintf(int __fd, const char *__fmt, ...);
+extern "C" _SIMPLE_STRING	_simple_salloc(void);
+extern "C" int				_simple_vsprintf(_SIMPLE_STRING __b, const char *__fmt, va_list __ap);
+extern "C" void				_simple_sfree(_SIMPLE_STRING __b);
+extern "C" char *			_simple_string(_SIMPLE_STRING __b);
+
+
+
+// 32-bit ppc and ARM are the only architecture that use cpu-sub-types
+#define CPU_SUBTYPES_SUPPORTED __ppc__ || __arm__
 
 
 
@@ -144,8 +112,6 @@
 // implemented in dyldStartup.s for CrashReporter
 extern "C" void dyld_fatal_error(const char* errString) __attribute__((noreturn));
 
-// magic linker symbol for start of dyld binary
-extern "C" const macho_header __dso_handle;
 
 
 //
@@ -156,19 +122,7 @@
 //
 //
 //
-namespace dyld {
-	struct RegisteredDOF { const mach_header* mh; int registrationID; };
-	struct DylibOverride { const char* installName; const char* override; };
-}
-
-
-VECTOR_NEVER_DESTRUCTED(ImageLoader*);
-VECTOR_NEVER_DESTRUCTED(dyld::RegisteredDOF);
-VECTOR_NEVER_DESTRUCTED(dyld::ImageCallback);
-VECTOR_NEVER_DESTRUCTED(dyld::DylibOverride);
-VECTOR_NEVER_DESTRUCTED(ImageLoader::DynamicReference);
-
-VECTOR_NEVER_DESTRUCTED(dyld_image_state_change_handler);
+
 
 namespace dyld {
 
@@ -215,17 +169,13 @@
 							//	DYLD_PRINT_RPATHS				==> gLinkContext.verboseRPaths
 							//	DYLD_PRINT_INTERPOSING			==> gLinkContext.verboseInterposing
 };
-
-
-
+        
 typedef std::vector<dyld_image_state_change_handler> StateHandlers;
-
-
-enum RestrictedReason { restrictedNot, restrictedBySetGUid, restrictedBySegment, restrictedByEntitlements };
-	
+struct RegisteredDOF { const mach_header* mh; int registrationID; };
+struct DylibOverride { const char* installName; const char* override; };
+
 // all global state
 static const char*					sExecPath = NULL;
-static const char*					sExecShortName = NULL;
 static const macho_header*			sMainExecutableMachHeader = NULL;
 #if CPU_SUBTYPES_SUPPORTED
 static cpu_type_t					sHostCPU;
@@ -233,38 +183,29 @@
 #endif
 static ImageLoader*					sMainExecutable = NULL;
 static bool							sProcessIsRestricted = false;
-static bool							sProcessRequiresLibraryValidation = false;
-static RestrictedReason				sRestrictedReason = restrictedNot;
-static size_t						sInsertedDylibCount = 0;
+static unsigned int					sInsertedDylibCount = 0;
 static std::vector<ImageLoader*>	sAllImages;
 static std::vector<ImageLoader*>	sImageRoots;
 static std::vector<ImageLoader*>	sImageFilesNeedingTermination;
 static std::vector<RegisteredDOF>	sImageFilesNeedingDOFUnregistration;
 static std::vector<ImageCallback>   sAddImageCallbacks;
 static std::vector<ImageCallback>   sRemoveImageCallbacks;
-static bool							sRemoveImageCallbacksInUse = false;
-static void*						sSingleHandlers[7][3];
-static void*						sBatchHandlers[7][3];
+static StateHandlers				sSingleHandlers[7];
+static StateHandlers				sBatchHandlers[7];
 static ImageLoader*					sLastImageByAddressCache;
 static EnvironmentVariables			sEnv;
-#if __MAC_OS_X_VERSION_MIN_REQUIRED
 static const char*					sFrameworkFallbackPaths[] = { "$HOME/Library/Frameworks", "/Library/Frameworks", "/Network/Library/Frameworks", "/System/Library/Frameworks", NULL };
 static const char*					sLibraryFallbackPaths[] = { "$HOME/lib", "/usr/local/lib", "/usr/lib", NULL };
-#else
-static const char*					sFrameworkFallbackPaths[] = { "/System/Library/Frameworks", NULL };
-static const char*					sLibraryFallbackPaths[] = { "/usr/local/lib", "/usr/lib", NULL };
-#endif
 static UndefinedHandler				sUndefinedHandler = NULL;
 static ImageLoader*					sBundleBeingLoaded = NULL;	// hack until OFI is reworked
 #if DYLD_SHARED_CACHE_SUPPORT
 static const dyld_cache_header*		sSharedCache = NULL;
 static long							sSharedCacheSlide = 0;
 static bool							sSharedCacheIgnoreInodeAndTimeStamp = false;
-	   bool							gSharedCacheOverridden = false;
-#if __IPHONE_OS_VERSION_MIN_REQUIRED
+#if __IPHONE_OS_VERSION_MIN_REQUIRED	
+	bool							gSharedCacheOverridden = false;
 	static const char*				sSharedCacheDir = IPHONE_DYLD_SHARED_CACHE_DIR;
 	static bool						sDylibsOverrideCache = false;
-	#define ENABLE_DYLIBS_TO_OVERRIDE_CACHE_SIZE 1024
 #else
 	static const char*				sSharedCacheDir = MACOSX_DYLD_SHARED_CACHE_DIR;
 #endif
@@ -276,17 +217,6 @@
 bool								gRunInitializersOldWay = false;
 #endif
 static std::vector<DylibOverride>	sDylibOverrides;
-#if !TARGET_IPHONE_SIMULATOR	
-static int							sLogSocket = -1;
-#endif
-static bool							sFrameworksFoundAsDylibs = false;
-#if __x86_64__
-static bool							sHaswell = false;
-#endif
-static std::vector<ImageLoader::DynamicReference> sDynamicReferences;
-static OSSpinLock					sDynamicReferencesLock = 0;
-static bool							sLogToFile = false;
-static char							sLoadingCrashMessage[1024] = "dyld: launch, loading dependent libraries";
 
 //
 // The MappedRanges structure is used for fast address->image lookups.
@@ -402,9 +332,8 @@
 }
 
 
-#if !TARGET_IPHONE_SIMULATOR
+//#define ALTERNATIVE_LOGFILE "/dev/console"
 static int sLogfile = STDERR_FILENO;
-#endif
 
 #if LOG_BINDINGS
 static int sBindingsLogfile = -1;
@@ -432,110 +361,24 @@
 		va_end(list);
 	}
 }
-#endif
-
-#if !TARGET_IPHONE_SIMULATOR	
-// based on CFUtilities.c: also_do_stderr()
-static bool useSyslog()
-{
-	// Use syslog() for processes managed by launchd
-	if ( (gLibSystemHelpers != NULL) && (gLibSystemHelpers->version >= 11) ) {
-		if ( (*gLibSystemHelpers->isLaunchdOwned)() ) {
-			return true;
-		}
-	}
-
-	// If stderr is not available, use syslog()
-	struct stat sb;
-	int result = fstat(STDERR_FILENO, &sb);
-	if ( result < 0 )
-		return true; // file descriptor 2 is closed
-
-	return false;
-}
-
-	
-static void socket_syslogv(int priority, const char* format, va_list list)
-{
-	// lazily create socket and connection to syslogd
-	if ( sLogSocket == -1 ) {
-		sLogSocket = ::socket(AF_UNIX, SOCK_DGRAM, 0);
-		if (sLogSocket == -1)
-			return;  // cannot log
-		::fcntl(sLogSocket, F_SETFD, 1);
-	
-		struct sockaddr_un addr;
-		addr.sun_family = AF_UNIX;
-		strncpy(addr.sun_path, _PATH_LOG, sizeof(addr.sun_path));
-		if ( ::connect(sLogSocket, (struct sockaddr *)&addr, sizeof(addr)) == -1 ) {
-			::close(sLogSocket);
-			sLogSocket = -1;
-			return;
-		}
-	}
-	
-	// format message to syslogd like: "<priority>Process[pid]: message"
-	_SIMPLE_STRING buf = _simple_salloc();
-	if ( buf == NULL )
-		return;
-	if ( _simple_sprintf(buf, "<%d>%s[%d]: ", LOG_USER|LOG_NOTICE, sExecShortName, getpid()) == 0 ) {
-		if ( _simple_vsprintf(buf, format, list) == 0 ) {
-			const char* p = _simple_string(buf);
-			::__sendto(sLogSocket, p, strlen(p), 0, NULL, 0);
-		}
-	}
-	_simple_sfree(buf);
-}
-
-void vlog(const char* format, va_list list)
-{
-	if ( !sLogToFile && useSyslog() ) 
-		socket_syslogv(LOG_ERR, format, list);
-	else {
-		_simple_vdprintf(sLogfile, format, list);
-	}
-}
-
-void log(const char* format, ...)
+
+#endif
+
+void log(const char* format, ...) 
 {
 	va_list	list;
 	va_start(list, format);
-	vlog(format, list);
+	_simple_vdprintf(sLogfile, format, list);
 	va_end(list);
 }
 
-
-void vwarn(const char* format, va_list list) 
+void warn(const char* format, ...) 
 {
 	_simple_dprintf(sLogfile, "dyld: warning, ");
-	_simple_vdprintf(sLogfile, format, list);
-}
-
-void warn(const char* format, ...) 
-{
 	va_list	list;
 	va_start(list, format);
-	vwarn(format, list);
+	_simple_vdprintf(sLogfile, format, list);
 	va_end(list);
-}
-
-
-#endif // !TARGET_IPHONE_SIMULATOR	
-
-
-// <rdar://problem/8867781> control access to sAllImages through a lock 
-// because global dyld lock is not held during initialization phase of dlopen()
-// <rdar://problem/16145518> Use OSSpinLockLock to allow yielding
-static OSSpinLock sAllImagesLock = 0;
-
-static void allImagesLock()
-{
-	OSSpinLockLock(&sAllImagesLock);
-}
-
-static void allImagesUnlock()
-{
-	OSSpinLockUnlock(&sAllImagesLock);
 }
 
 
@@ -552,7 +395,7 @@
 FileOpener::FileOpener(const char* path)
  : fd(-1)
 {
-	fd = my_open(path, O_RDONLY, 0);
+	fd = open(path, O_RDONLY, 0);
 }
 
 FileOpener::~FileOpener()
@@ -562,9 +405,20 @@
 }
 
 
+// forward declaration
+#if __ppc__ || __i386__
+bool isRosetta();
+#endif
+
+
 static void	registerDOFs(const std::vector<ImageLoader::DOFInfo>& dofs)
 {
-	const size_t dofSectionCount = dofs.size();
+#if __ppc__
+	// can't dtrace a program running emulated under rosetta rdar://problem/5179640
+	if ( isRosetta() )
+		return;
+#endif
+	const unsigned int dofSectionCount = dofs.size();
 	if ( !sEnv.DYLD_DISABLE_DOFS && (dofSectionCount != 0) ) {
 		int fd = open("/dev/" DTRACEMNR_HELPER, O_RDWR);
 		if ( fd < 0 ) {
@@ -594,13 +448,13 @@
 					info.registrationID = (int)(ioctlData->dofiod_helpers[i].dofhp_dof);
 					sImageFilesNeedingDOFUnregistration.push_back(info);
 					if ( gLinkContext.verboseDOF ) {
-						dyld::log("dyld: registering DOF section %p in %s with dtrace, ID=0x%08X\n", 
+						dyld::log("dyld: registering DOF section 0x%p in %s with dtrace, ID=0x%08X\n", 
 							dofs[i].dof, dofs[i].imageShortName, info.registrationID);
 					}
 				}
 			}
 			else {
-				//dyld::log( "dyld: ioctl to register dtrace DOF section failed\n");
+				dyld::log( "dyld: ioctl to register dtrace DOF section failed\n");
 			}
 			close(fd);
 		}
@@ -647,32 +501,33 @@
 }
 
 
-static StateHandlers* stateToHandlers(dyld_image_states state, void* handlersArray[7][3])
+static StateHandlers* stateToHandlers(dyld_image_states state, StateHandlers handlersArray[8]) 
 {
 	switch ( state ) {
 		case dyld_image_state_mapped:
-			return reinterpret_cast<StateHandlers*>(&handlersArray[0]);
+			return &handlersArray[0];
 			
 		case dyld_image_state_dependents_mapped:
-			return reinterpret_cast<StateHandlers*>(&handlersArray[1]);
+			return &handlersArray[1];
 			
 		case dyld_image_state_rebased:
-			return reinterpret_cast<StateHandlers*>(&handlersArray[2]);
+			return &handlersArray[2];
 			
 		case dyld_image_state_bound:
-			return reinterpret_cast<StateHandlers*>(&handlersArray[3]);
+			return &handlersArray[3];
 			
 		case dyld_image_state_dependents_initialized:
-			return reinterpret_cast<StateHandlers*>(&handlersArray[4]);
+			return &handlersArray[4];
 
 		case dyld_image_state_initialized:
-			return reinterpret_cast<StateHandlers*>(&handlersArray[5]);
+			return &handlersArray[5];
 			
 		case dyld_image_state_terminated:
-			return reinterpret_cast<StateHandlers*>(&handlersArray[6]);
+			return &handlersArray[6];
 	}
 	return NULL;
 }
+
 
 static void notifySingle(dyld_image_states state, const ImageLoader* image)
 {
@@ -681,7 +536,7 @@
 	if ( handlers != NULL ) {
 		dyld_image_info info;
 		info.imageLoadAddress	= image->machHeader();
-		info.imageFilePath		= image->getRealPath();
+		info.imageFilePath		= image->getPath();
 		info.imageFileModDate	= image->lastModified();
 		for (std::vector<dyld_image_state_change_handler>::iterator it = handlers->begin(); it != handlers->end(); ++it) {
 			const char* result = (*it)(state, 1, &info);
@@ -703,17 +558,20 @@
 			}
 		}
 	}
-    // mach message csdlc about dynamically unloaded images
+#if CORESYMBOLICATION_SUPPORT
+    // mach message csdlc about dynamically loaded images 
 	if ( image->addFuncNotified() && (state == dyld_image_state_terminated) ) {
-		uint64_t loadTimestamp = mach_absolute_time();
 		if ( sEnv.DYLD_PRINT_CS_NOTIFICATIONS ) {
-			dyld::log("dyld: coresymbolication_unload_notifier(%p, 0x%016llX, %p, %s)\n",
-					  dyld::gProcessInfo->coreSymbolicationShmPage, loadTimestamp, image->machHeader(), image->getPath());
-		}
-		if ( dyld::gProcessInfo->coreSymbolicationShmPage != NULL) {
-			coresymbolication_unload_notifier(dyld::gProcessInfo->coreSymbolicationShmPage, loadTimestamp, image->getPath(), image->machHeader());
-		}
-	}
+			dyld::log("dyld core symbolication unload notification: %p %s\n", image->machHeader(), image->getPath());
+		}
+		if ( dyld_all_image_infos.coreSymbolicationShmPage != NULL) {
+			CSCppDyldSharedMemoryPage* connection = (CSCppDyldSharedMemoryPage*)dyld_all_image_infos.coreSymbolicationShmPage;
+			if ( connection->is_valid_version() ) {
+				coresymbolication_unload_image(connection, image);
+			}
+		}
+	}
+#endif
 }
 
 
@@ -725,7 +583,7 @@
 // dylibs needed by the main executable, dyld_all_image_infos is not yet set 
 // up, leading to usually brief crash logs.
 //
-// This function manually adds the images loaded so far to dyld::gProcessInfo.
+// This function manually adds the images loaded so far to dyld_all_image_infos.
 // It should only be called before terminating.
 //
 void syncAllImages()
@@ -734,12 +592,12 @@
 		dyld_image_info info;
 		ImageLoader* image = *it;
 		info.imageLoadAddress = image->machHeader();
-		info.imageFilePath = image->getRealPath();
+		info.imageFilePath = image->getPath();
 		info.imageFileModDate = image->lastModified();
 		// add to all_image_infos if not already there
 		bool found = false;
-		int existingCount = dyld::gProcessInfo->infoArrayCount;
-		const dyld_image_info* existing = dyld::gProcessInfo->infoArray;
+		int existingCount = dyld_all_image_infos.infoArrayCount;
+		const dyld_image_info* existing = dyld_all_image_infos.infoArray;
 		if ( existing != NULL ) {
 			for (int i=0; i < existingCount; ++i) {
 				if ( existing[i].imageLoadAddress == info.imageLoadAddress ) {
@@ -769,21 +627,19 @@
 	std::vector<dyld_image_state_change_handler>* handlers = stateToHandlers(state, sBatchHandlers);
 	if ( handlers != NULL ) {
 		// don't use a vector because it will use malloc/free and we want notifcation to be low cost
-        allImagesLock();
-        ImageLoader* images[sAllImages.size()+1];
-        ImageLoader** end = images;
-        for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
-            dyld_image_states imageState = (*it)->getState();
-            if ( (imageState == state) || (orLater && (imageState > state)) )
-                *end++ = *it;
-        }
+		ImageLoader* images[sAllImages.size()+1];
+		ImageLoader** end = images;
+		for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
+			dyld_image_states imageState = (*it)->getState();
+			if ( (imageState == state) || (orLater && (imageState > state)) )
+				*end++ = *it;
+		}
 		if ( sBundleBeingLoaded != NULL ) {
 			dyld_image_states imageState = sBundleBeingLoaded->getState();
 			if ( (imageState == state) || (orLater && (imageState > state)) )
 				*end++ = sBundleBeingLoaded;
 		}
-        const char* dontLoadReason = NULL;
-		uint32_t count = (uint32_t)(end-images);
+		unsigned int count = end-images;
 		if ( end != images ) {
 			// sort bottom up
 			qsort(images, count, sizeof(ImageLoader*), &imageSorter);
@@ -794,7 +650,7 @@
 				ImageLoader* image = images[i];
 				//dyld::log("  state=%d, name=%s\n", state, image->getPath());
 				p->imageLoadAddress = image->machHeader();
-				p->imageFilePath = image->getRealPath();
+				p->imageFilePath = image->getPath();
 				p->imageFileModDate = image->lastModified();
 				// special case for add_image hook
 				if ( state == dyld_image_state_bound )
@@ -806,7 +662,8 @@
 				if ( (result != NULL) && (state == dyld_image_state_dependents_mapped) ) {
 					//fprintf(stderr, "  images rejected by handler=%p\n", onlyHandler);
 					// make copy of thrown string so that later catch clauses can free it
-					dontLoadReason = strdup(result);
+					const char* str = strdup(result);
+					throw str;
 				}
 			}
 			else {
@@ -816,27 +673,36 @@
 					if ( (result != NULL) && (state == dyld_image_state_dependents_mapped) ) {
 						//fprintf(stderr, "  images rejected by handler=%p\n", *it);
 						// make copy of thrown string so that later catch clauses can free it
-						dontLoadReason = strdup(result);
-						break;
+						const char* str = strdup(result);
+						throw str;
 					}
 				}
 			}
-			if ( (state == dyld_image_state_dependents_mapped) && ((dyld::gProcessInfo->coreSymbolicationShmPage != NULL) || sEnv.DYLD_PRINT_CS_NOTIFICATIONS) ) {
-				// mach message csdlc about loaded images
-				uint64_t loadTimestamp = mach_absolute_time();
-				for (unsigned j=0; j < count; ++j) {
-					if ( sEnv.DYLD_PRINT_CS_NOTIFICATIONS ) {
-						dyld::log("dyld: coresymbolication_load_notifier(%p, 0x%016llX, %p, %s)\n",
-								  dyld::gProcessInfo->coreSymbolicationShmPage, loadTimestamp, infos[j].imageLoadAddress, infos[j].imageFilePath);
-					}
-					coresymbolication_load_notifier(dyld::gProcessInfo->coreSymbolicationShmPage, loadTimestamp, infos[j].imageFilePath, infos[j].imageLoadAddress);
+		}
+	}
+#if CORESYMBOLICATION_SUPPORT
+	if ( state == dyld_image_state_rebased ) {
+		if ( sEnv.DYLD_PRINT_CS_NOTIFICATIONS ) {
+			for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
+				dyld_image_states imageState = (*it)->getState();
+				if ( (imageState == dyld_image_state_rebased) || (orLater && (imageState > dyld_image_state_rebased)) )
+					dyld::log("dyld core symbolication load notification: %p %s\n", (*it)->machHeader(), (*it)->getPath());
+			}
+		}
+		if ( dyld_all_image_infos.coreSymbolicationShmPage != NULL) {
+			CSCppDyldSharedMemoryPage* connection = (CSCppDyldSharedMemoryPage*)dyld_all_image_infos.coreSymbolicationShmPage;
+			if ( connection->is_valid_version() ) {
+				// This needs to be captured now
+				uint64_t load_timestamp = mach_absolute_time();
+				for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
+					dyld_image_states imageState = (*it)->getState();
+					if ( (imageState == state) || (orLater && (imageState > state)) )
+						coresymbolication_load_image(connection, *it, load_timestamp);
 				}
 			}
 		}
-        allImagesUnlock();
-        if ( dontLoadReason != NULL )
-            throw dontLoadReason;
-	}
+	}
+#endif
 }
 
 
@@ -864,16 +730,9 @@
 		(*it)->clearDepth();
 }
 
-static void printAllDepths()
-{
-	for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++)
-		dyld::log("%03d %s\n",  (*it)->getDepth(), (*it)->getShortName());
-}
-
-
 static unsigned int imageCount()
 {
-	return (unsigned int)sAllImages.size();
+	return sAllImages.size();
 }
 
 
@@ -896,40 +755,10 @@
 }
 #endif
 
-static void addDynamicReference(ImageLoader* from, ImageLoader* to) {
-	// don't add dynamic reference if either are in the shared cache
-	if( from->inSharedCache() )
-		return;
-	if( to->inSharedCache() )
-		return;
-
-	// don't add dynamic reference if there already is a static one
-	if ( from->dependsOn(to) )
-		return;
-	
-	// don't add if this combination already exists
-	OSSpinLockLock(&sDynamicReferencesLock);
-	for (std::vector<ImageLoader::DynamicReference>::iterator it=sDynamicReferences.begin(); it != sDynamicReferences.end(); ++it) {
-		if ( (it->from == from) && (it->to == to) ) {
-			OSSpinLockUnlock(&sDynamicReferencesLock);
-			return;
-		}
-	}
-
-	//dyld::log("addDynamicReference(%s, %s\n", from->getShortName(), to->getShortName());
-	ImageLoader::DynamicReference t;
-	t.from = from;
-	t.to = to;
-	sDynamicReferences.push_back(t);
-	OSSpinLockUnlock(&sDynamicReferencesLock);
-}
-
 static void addImage(ImageLoader* image)
 {
 	// add to master list
-    allImagesLock();
-        sAllImages.push_back(image);
-    allImagesUnlock();
+	sAllImages.push_back(image);
 	
 	// update mapped ranges
 	uintptr_t lastSegStart = 0;
@@ -961,23 +790,17 @@
 	
 }
 
-//
-// Helper for std::remove_if
-//
-class RefUsesImage {
-public:
-	RefUsesImage(ImageLoader* image) : _image(image) {}
-	bool operator()(const ImageLoader::DynamicReference& ref) const {
-		return ( (ref.from == _image) || (ref.to == _image) );
-	}
-private:
-	ImageLoader* _image;
-};
-
-
-
 void removeImage(ImageLoader* image)
 {
+	// if in termination list, pull it out and run terminator
+	for (std::vector<ImageLoader*>::iterator it=sImageFilesNeedingTermination.begin(); it != sImageFilesNeedingTermination.end(); it++) {
+		if ( *it == image ) {
+			sImageFilesNeedingTermination.erase(it);
+			image->doTermination(gLinkContext);
+			break;
+		}
+	}
+	
 	// if has dtrace DOF section, tell dtrace it is going away, then remove from sImageFilesNeedingDOFUnregistration
 	for (std::vector<RegisteredDOF>::iterator it=sImageFilesNeedingDOFUnregistration.begin(); it != sImageFilesNeedingDOFUnregistration.end(); ) {
 		if ( it->mh == image->machHeader() ) {
@@ -993,34 +816,29 @@
 	// tell all registered remove image handlers about this
 	// do this before removing image from internal data structures so that the callback can query dyld about the image
 	if ( image->getState() >= dyld_image_state_bound ) {
-		sRemoveImageCallbacksInUse = true; // This only runs inside dyld's global lock, so ok to use a global for the in-use flag.
 		for (std::vector<ImageCallback>::iterator it=sRemoveImageCallbacks.begin(); it != sRemoveImageCallbacks.end(); it++) {
 			(*it)(image->machHeader(), image->getSlide());
 		}
-		sRemoveImageCallbacksInUse = false;
 	}
 	
 	// notify 
 	notifySingle(dyld_image_state_terminated, image);
 	
+	// <rdar://problem/7740779> dyld should directly call __cxa_finalize()
+	if ( (gLibSystemHelpers != NULL) && (gLibSystemHelpers->version >= 8) )
+		(*gLibSystemHelpers->cxa_finalize)(image->machHeader());
+	
 	// remove from mapped images table
 	removedMappedRanges(image);
 
 	// remove from master list
-    allImagesLock();
-        for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
-            if ( *it == image ) {
-                sAllImages.erase(it);
-                break;
-            }
-        }
-    allImagesUnlock();
-	
-	// remove from sDynamicReferences
-	OSSpinLockLock(&sDynamicReferencesLock);
-		sDynamicReferences.erase(std::remove_if(sDynamicReferences.begin(), sDynamicReferences.end(), RefUsesImage(image)), sDynamicReferences.end());
-	OSSpinLockUnlock(&sDynamicReferencesLock);
-
+	for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
+		if ( *it == image ) {
+			sAllImages.erase(it);
+			break;
+		}
+	}
+	
 	// flush find-by-address cache (do this after removed from master list, so there is no chance it can come back)
 	if ( sLastImageByAddressCache == image )
 		sLastImageByAddressCache = NULL;
@@ -1043,24 +861,6 @@
 }
 
 
-void runImageStaticTerminators(ImageLoader* image)
-{
-	// if in termination list, pull it out and run terminator
-	bool mightBeMore;
-	do {
-		mightBeMore = false;
-		for (std::vector<ImageLoader*>::iterator it=sImageFilesNeedingTermination.begin(); it != sImageFilesNeedingTermination.end(); it++) {
-			if ( *it == image ) {
-				sImageFilesNeedingTermination.erase(it);
-				if (gLogAPIs) dyld::log("dlclose(), running static terminators for %p %s\n", image, image->getShortName());
-				image->doTermination(gLinkContext);
-				mightBeMore = true;
-				break;
-			}
-		}
-	} while ( mightBeMore );
-}
-
 static void terminationRecorder(ImageLoader* image)
 {
 	sImageFilesNeedingTermination.push_back(image);
@@ -1071,47 +871,37 @@
 	return sExecPath;
 }
 
-static void runAllStaticTerminators(void* extra)
-{
-	try {
-		const size_t imageCount = sImageFilesNeedingTermination.size();
-		for(size_t i=imageCount; i > 0; --i){
-			ImageLoader* image = sImageFilesNeedingTermination[i-1];
-			image->doTermination(gLinkContext);
-		}
-		sImageFilesNeedingTermination.clear();
-		notifyBatch(dyld_image_state_terminated);
-	}
-	catch (const char* msg) {
-		halt(msg);
-	}
-}
 
 void initializeMainExecutable()
 {
+	// apply interposing to initial set of images
+	// do this before making the __IMPORT segments in shared cache read-only
+	sMainExecutable->applyInterposing(gLinkContext);
+
 	// record that we've reached this step
 	gLinkContext.startedInitializingMainExecutable = true;
 
 	// run initialzers for any inserted dylibs
 	ImageLoader::InitializerTimingList initializerTimes[sAllImages.size()];
+	const int rootCount = sImageRoots.size();
+	if ( rootCount > 1 ) {
+		for(int i=1; i < rootCount; ++i) {
+			initializerTimes[0].count = 0;
+			sImageRoots[i]->runInitializers(gLinkContext, initializerTimes[0]);
+		}
+	}
+	
+	// run initializers for main executable and everything it brings up 
 	initializerTimes[0].count = 0;
-	const size_t rootCount = sImageRoots.size();
-	if ( rootCount > 1 ) {
-		for(size_t i=1; i < rootCount; ++i) {
-			sImageRoots[i]->runInitializers(gLinkContext, initializerTimes[0]);
-		}
-	}
-	
-	// run initializers for main executable and everything it brings up 
 	sMainExecutable->runInitializers(gLinkContext, initializerTimes[0]);
 	
-	// register cxa_atexit() handler to run static terminators in all loaded images when this process exits
+	// register atexit() handler to run terminators in all loaded images when this process exits
 	if ( gLibSystemHelpers != NULL ) 
-		(*gLibSystemHelpers->cxa_atexit)(&runAllStaticTerminators, NULL, NULL);
+		(*gLibSystemHelpers->cxa_atexit)(&runTerminators, NULL, NULL);
 
 	// dump info if requested
 	if ( sEnv.DYLD_PRINT_STATISTICS )
-		ImageLoaderMachO::printStatistics((unsigned int)sAllImages.size(), initializerTimes[0]);
+		ImageLoaderMachO::printStatistics(sAllImages.size(), initializerTimes[0]);
 }
 
 bool mainExecutablePrebound()
@@ -1125,9 +915,17 @@
 }
 
 
-
-
-#if SUPPORT_VERSIONED_PATHS
+void runTerminators(void* extra)
+{
+	const unsigned int imageCount = sImageFilesNeedingTermination.size();
+	for(unsigned int i=imageCount; i > 0; --i){
+		ImageLoader* image = sImageFilesNeedingTermination[i-1];
+		image->doTermination(gLinkContext);
+	}
+	sImageFilesNeedingTermination.clear();
+	notifyBatch(dyld_image_state_terminated);
+}
+
 
 // forward reference
 static bool getDylibVersionAndInstallname(const char* dylibPath, uint32_t* version, char* installName);
@@ -1142,7 +940,7 @@
 	//dyld::log("checkDylibOverride('%s')\n", dylibFile);
 	uint32_t altVersion;
  	char sysInstallName[PATH_MAX];
-	if ( getDylibVersionAndInstallname(dylibFile, &altVersion, sysInstallName) && (sysInstallName[0] =='/') ) {
+	if ( getDylibVersionAndInstallname(dylibFile, &altVersion, sysInstallName) ) {
 		//dyld::log("%s has version 0x%08X and install name %s\n", dylibFile, altVersion, sysInstallName);
 		uint32_t sysVersion;
 		if ( getDylibVersionAndInstallname(sysInstallName, &sysVersion, NULL) ) {
@@ -1159,11 +957,7 @@
 							if ( altVersion > prevVersion ) {
 								// found an even newer override
 								free((void*)(it->override));
-								char resolvedPath[PATH_MAX];
-								if ( realpath(dylibFile, resolvedPath) != NULL )
-									it->override = strdup(resolvedPath);
-								else
-									it->override = strdup(dylibFile);
+								it->override = strdup(dylibFile);
 								break;
 							}
 						}
@@ -1172,11 +966,7 @@
 				if ( ! entryExists ) {
 					DylibOverride entry;
 					entry.installName = strdup(sysInstallName);
-					char resolvedPath[PATH_MAX];
-					if ( realpath(dylibFile, resolvedPath) != NULL )
-						entry.override = strdup(resolvedPath);
-					else
-						entry.override = strdup(dylibFile);
+					entry.override = strdup(dylibFile);
 					sDylibOverrides.push_back(entry);
 					//dyld::log("added override: %s -> %s\n", entry.installName, entry.override);
 				}
@@ -1190,9 +980,8 @@
 {
 	//dyld::log("checkDylibOverridesInDir('%s')\n", dirPath);
 	char dylibPath[PATH_MAX];
-	int dirPathLen = strlcpy(dylibPath, dirPath, PATH_MAX-1);
-	if ( dirPathLen >= PATH_MAX )
-		return;
+	int dirPathLen = strlen(dirPath);
+	strlcpy(dylibPath, dirPath, PATH_MAX); 
 	DIR* dirp = opendir(dirPath);
 	if ( dirp != NULL) {
 		dirent entry;
@@ -1202,9 +991,9 @@
 				break;
 			if ( entp->d_type != DT_REG ) 
 				continue;
-			dylibPath[dirPathLen] = '/';
-			dylibPath[dirPathLen+1] = '\0';
-			if ( strlcat(dylibPath, entp->d_name, PATH_MAX) >= PATH_MAX )
+			dylibPath[dirPathLen] = '/';     
+			dylibPath[dirPathLen+1] = '\0';     
+			if ( strlcat(dylibPath, entp->d_name, PATH_MAX) > PATH_MAX ) 
 				continue;
 			checkDylibOverride(dylibPath);
 		}
@@ -1217,9 +1006,8 @@
 {
 	//dyld::log("checkFrameworkOverridesInDir('%s')\n", dirPath);
 	char frameworkPath[PATH_MAX];
-	int dirPathLen = strlcpy(frameworkPath, dirPath, PATH_MAX-1);
-	if ( dirPathLen >= PATH_MAX )
-		return;
+	int dirPathLen = strlen(dirPath);
+	strlcpy(frameworkPath, dirPath, PATH_MAX); 
 	DIR* dirp = opendir(dirPath);
 	if ( dirp != NULL) {
 		dirent entry;
@@ -1229,18 +1017,18 @@
 				break;
 			if ( entp->d_type != DT_DIR ) 
 				continue;
-			frameworkPath[dirPathLen] = '/';
+			frameworkPath[dirPathLen] = '/';     
 			frameworkPath[dirPathLen+1] = '\0';
-			int dirNameLen = (int)strlen(entp->d_name);
+			int dirNameLen = strlen(entp->d_name);
 			if ( dirNameLen < 11 )
 				continue;
 			if ( strcmp(&entp->d_name[dirNameLen-10], ".framework") != 0 )
 				continue;
-			if ( strlcat(frameworkPath, entp->d_name, PATH_MAX) >= PATH_MAX )
+			if ( strlcat(frameworkPath, entp->d_name, PATH_MAX) > PATH_MAX ) 
 				continue;
-			if ( strlcat(frameworkPath, "/", PATH_MAX) >= PATH_MAX )
+			if ( strlcat(frameworkPath, "/", PATH_MAX) > PATH_MAX ) 
 				continue;
-			if ( strlcat(frameworkPath, entp->d_name, PATH_MAX) >= PATH_MAX )
+			if ( strlcat(frameworkPath, entp->d_name, PATH_MAX) > PATH_MAX ) 
 				continue;
 			frameworkPath[strlen(frameworkPath)-10] = '\0';
 			checkDylibOverride(frameworkPath);
@@ -1248,8 +1036,6 @@
 		closedir(dirp);
 	}
 }
-#endif // SUPPORT_VERSIONED_PATHS
-
 
 //
 // Turns a colon separated list of strings into a NULL terminated array 
@@ -1274,9 +1060,9 @@
 	char** result = new char*[colonCount+2];
 	for(const char* s=list; *s != '\0'; ++s) {
 		if (*s == ':') {
-			size_t len = s-start;
+			int len = s-start;
 			if ( (mainExecutableDir != NULL) && (strncmp(start, "@loader_path/", 13) == 0) ) {
-				size_t mainExecDirLen = strlen(mainExecutableDir);
+				int mainExecDirLen = strlen(mainExecutableDir);
 				char* str = new char[mainExecDirLen+len+1];
 				strcpy(str, mainExecutableDir);
 				strlcat(str, &start[13], mainExecDirLen+len+1);
@@ -1285,7 +1071,7 @@
 				result[index++] = str;
 			}
 			else if ( (mainExecutableDir != NULL) && (strncmp(start, "@executable_path/", 17) == 0) ) {
-				size_t mainExecDirLen = strlen(mainExecutableDir);
+				int mainExecDirLen = strlen(mainExecutableDir);
 				char* str = new char[mainExecDirLen+len+1];
 				strcpy(str, mainExecutableDir);
 				strlcat(str, &start[17], mainExecDirLen+len+1);
@@ -1302,9 +1088,9 @@
 			}
 		}
 	}
-	size_t len = strlen(start);
+	int len = strlen(start);
 	if ( (mainExecutableDir != NULL) && (strncmp(start, "@loader_path/", 13) == 0) ) {
-		size_t mainExecDirLen = strlen(mainExecutableDir);
+		int mainExecDirLen = strlen(mainExecutableDir);
 		char* str = new char[mainExecDirLen+len+1];
 		strcpy(str, mainExecutableDir);
 		strlcat(str, &start[13], mainExecDirLen+len+1);
@@ -1312,7 +1098,7 @@
 		result[index++] = str;
 	}
 	else if ( (mainExecutableDir != NULL) && (strncmp(start, "@executable_path/", 17) == 0) ) {
-		size_t mainExecDirLen = strlen(mainExecutableDir);
+		int mainExecDirLen = strlen(mainExecutableDir);
 		char* str = new char[mainExecDirLen+len+1];
 		strcpy(str, mainExecutableDir);
 		strlcat(str, &start[17], mainExecDirLen+len+1);
@@ -1524,9 +1310,6 @@
 	else if ( strcmp(key, "DYLD_PRINT_INTERPOSING") == 0 ) {
 		gLinkContext.verboseInterposing = true;
 	}
-	else if ( strcmp(key, "DYLD_PRINT_CODE_SIGNATURES") == 0 ) {
-		gLinkContext.verboseCodeSignatures = true;
-	}
 	else if ( strcmp(key, "DYLD_SHARED_REGION") == 0 ) {
 		if ( strcmp(value, "private") == 0 ) {
 			gLinkContext.sharedRegionMode = ImageLoader::kUsePrivateSharedRegion;
@@ -1575,18 +1358,6 @@
 	}
 	else if ( strcmp(key, "DYLD_VERSIONED_FRAMEWORK_PATH") == 0 ) {
 		appendParsedColonList(value, mainExecutableDir, &sEnv.DYLD_VERSIONED_FRAMEWORK_PATH);
-	}
-#endif
-#if !TARGET_IPHONE_SIMULATOR
-	else if ( (strcmp(key, "DYLD_PRINT_TO_FILE") == 0) && (mainExecutableDir == NULL) ) {
-		int fd = open(value, O_WRONLY | O_CREAT | O_APPEND, 0644);
-		if ( fd != -1 ) {
-			sLogfile = fd;
-			sLogToFile = true;
-		}
-		else {
-			dyld::log("dyld: could not open DYLD_PRINT_TO_FILE='%s', errno=%d\n", value, errno);
-		}
 	}
 #endif
 	else {
@@ -1608,7 +1379,7 @@
 			{
 				const struct dylinker_command* envcmd = (struct dylinker_command*)cmd;
 				const char* keyEqualsValue = (char*)envcmd + envcmd->name.offset;
-				char mainExecutableDir[strlen(sExecPath)+2];
+				char mainExecutableDir[strlen(sExecPath)];
 				strcpy(mainExecutableDir, sExecPath);
 				char* lastSlash = strrchr(mainExecutableDir, '/');
 				if ( lastSlash != NULL)
@@ -1619,16 +1390,13 @@
 					if ( equals != NULL ) {
 						if ( strncmp(&equals[-5], "_PATH", 5) == 0 ) {
 							const char* value = &equals[1];
-							const size_t keyLen = equals-keyEqualsValue;
-							// <rdar://problem/22799635> don't let malformed load command overflow stack
-							if ( keyLen < 40 ) {
-								char key[keyLen+1];
-								strncpy(key, keyEqualsValue, keyLen);
-								key[keyLen] = '\0';
-								//dyld::log("processing: %s\n", keyEqualsValue);
-								//dyld::log("mainExecutableDir: %s\n", mainExecutableDir);
-								processDyldEnvironmentVariable(key, value, mainExecutableDir);
-							}
+							const int keyLen = equals-keyEqualsValue;
+							char key[keyLen+1];
+							strncpy(key, keyEqualsValue, keyLen);
+							key[keyLen] = '\0';
+							//dyld::log("processing: %s\n", keyEqualsValue);
+							//dyld::log("mainExecutableDir: %s\n", mainExecutableDir);
+							processDyldEnvironmentVariable(key, value, mainExecutableDir);
 						}
 					}
 				}
@@ -1640,20 +1408,6 @@
 }
 #endif // SUPPORT_LC_DYLD_ENVIRONMENT	
 
-	
-static bool hasCodeSignatureLoadCommand(const macho_header* mh)
-{
-	const uint32_t cmd_count = mh->ncmds;
-	const struct load_command* const cmds = (struct load_command*)(((char*)mh)+sizeof(macho_header));
-	const struct load_command* cmd = cmds;
-	for (uint32_t i = 0; i < cmd_count; ++i) {
-		if (cmd->cmd == LC_CODE_SIGNATURE) 
-			return true;
-		cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
-	}
-	return false;
-}
-	
 
 #if SUPPORT_VERSIONED_PATHS
 static void checkVersionedPaths()
@@ -1694,25 +1448,7 @@
 		}
 	}
 	*d++ = NULL;
-// <rdar://11894054> Disable warnings about DYLD_ env vars being ignored.  The warnings are causing too much confusion.
-#if 0
-	if ( removedCount != 0 ) {
-		dyld::log("dyld: DYLD_ environment variables being ignored because ");
-		switch (sRestrictedReason) {
-			case restrictedNot:
-				break;
-			case restrictedBySetGUid:
-				dyld::log("main executable (%s) is setuid or setgid\n", sExecPath);
-				break;
-			case restrictedBySegment:
-				dyld::log("main executable (%s) has __RESTRICT/__restrict section\n", sExecPath);
-				break;
-			case restrictedByEntitlements:
-				dyld::log("main executable (%s) is code signed with entitlements\n", sExecPath);
-				break;
-		}
-	}
-#endif
+	
 	// slide apple parameters
 	if ( removedCount > 0 ) {
 		*applep = d;
@@ -1726,62 +1462,29 @@
 	// disable framework and library fallback paths for setuid binaries rdar://problem/4589305
 	sEnv.DYLD_FALLBACK_FRAMEWORK_PATH = NULL;
 	sEnv.DYLD_FALLBACK_LIBRARY_PATH = NULL;
-
-	if ( removedCount > 0 )
-		strlcat(sLoadingCrashMessage, ", ignoring DYLD_* env vars", sizeof(sLoadingCrashMessage));
-}
-
-static void defaultUninitializedFallbackPaths(const char* envp[])
-{
-#if __MAC_OS_X_VERSION_MIN_REQUIRED
-	// default value for DYLD_FALLBACK_FRAMEWORK_PATH, if not set in environment
-	const char* home = _simple_getenv(envp, "HOME");;
-	if ( sEnv.DYLD_FALLBACK_FRAMEWORK_PATH == NULL ) {
-		const char** fpaths = sFrameworkFallbackPaths;
-		if ( home == NULL )
-			removePathWithPrefix(fpaths, "$HOME");
-		else
-			paths_expand_roots(fpaths, "$HOME", home);
-		sEnv.DYLD_FALLBACK_FRAMEWORK_PATH = fpaths;
-	}
-
-    // default value for DYLD_FALLBACK_LIBRARY_PATH, if not set in environment
-	if ( sEnv.DYLD_FALLBACK_LIBRARY_PATH == NULL ) {
-		const char** lpaths = sLibraryFallbackPaths;
-		if ( home == NULL )
-			removePathWithPrefix(lpaths, "$HOME");
-		else
-			paths_expand_roots(lpaths, "$HOME", home);
-		sEnv.DYLD_FALLBACK_LIBRARY_PATH = lpaths;
-	}
-#else
-	if ( sEnv.DYLD_FALLBACK_FRAMEWORK_PATH == NULL )
-		sEnv.DYLD_FALLBACK_FRAMEWORK_PATH = sFrameworkFallbackPaths;
-
-	if ( sEnv.DYLD_FALLBACK_LIBRARY_PATH == NULL )
-		sEnv.DYLD_FALLBACK_LIBRARY_PATH = sLibraryFallbackPaths;
-#endif
-}
-
-
-static void checkEnvironmentVariables(const char* envp[])
-{
+}
+
+
+static void checkEnvironmentVariables(const char* envp[], bool ignoreEnviron)
+{
+	const char* home = NULL;
 	const char** p;
 	for(p = envp; *p != NULL; p++) {
 		const char* keyEqualsValue = *p;
 	    if ( strncmp(keyEqualsValue, "DYLD_", 5) == 0 ) {
 			const char* equals = strchr(keyEqualsValue, '=');
-			if ( equals != NULL ) {
-				strlcat(sLoadingCrashMessage, "\n", sizeof(sLoadingCrashMessage));
-				strlcat(sLoadingCrashMessage, keyEqualsValue, sizeof(sLoadingCrashMessage));
+			if ( (equals != NULL) && !ignoreEnviron ) {
 				const char* value = &equals[1];
-				const size_t keyLen = equals-keyEqualsValue;
+				const int keyLen = equals-keyEqualsValue;
 				char key[keyLen+1];
 				strncpy(key, keyEqualsValue, keyLen);
 				key[keyLen] = '\0';
 				processDyldEnvironmentVariable(key, value, NULL);
 			}
 		}
+	    else if ( strncmp(keyEqualsValue, "HOME=", 5) == 0 ) {
+			home = &keyEqualsValue[5];
+		}
 		else if ( strncmp(keyEqualsValue, "LD_LIBRARY_PATH=", 16) == 0 ) {
 			const char* path = &keyEqualsValue[16];
 			sEnv.LD_LIBRARY_PATH = parseColonList(path, NULL);
@@ -1792,60 +1495,41 @@
 	checkLoadCommandEnvironmentVariables();
 #endif // SUPPORT_LC_DYLD_ENVIRONMENT	
 	
-	// <rdar://problem/11281064> DYLD_IMAGE_SUFFIX and DYLD_ROOT_PATH cannot be used together
-	if ( (gLinkContext.imageSuffix != NULL) && (gLinkContext.rootPaths != NULL) ) {
-		dyld::warn("Ignoring DYLD_IMAGE_SUFFIX because DYLD_ROOT_PATH is used.\n");
-		gLinkContext.imageSuffix = NULL;
-	}
-}
-
-#if __x86_64__
-static bool isGCProgram(const macho_header* mh, uintptr_t slide)
-{
-	const uint32_t cmd_count = mh->ncmds;
-	const struct load_command* const cmds = (struct load_command*)(((char*)mh)+sizeof(macho_header));
-	const struct load_command* cmd = cmds;
-	for (uint32_t i = 0; i < cmd_count; ++i) {
-		switch (cmd->cmd) {
-			case LC_SEGMENT_COMMAND:
-			{
-				const struct macho_segment_command* seg = (struct macho_segment_command*)cmd;
-				if (strcmp(seg->segname, "__DATA") == 0) {
-					const struct macho_section* const sectionsStart = (struct macho_section*)((char*)seg + sizeof(struct macho_segment_command));
-					const struct macho_section* const sectionsEnd = &sectionsStart[seg->nsects];
-					for (const struct macho_section* sect=sectionsStart; sect < sectionsEnd; ++sect) {
-						if (strncmp(sect->sectname, "__objc_imageinfo", 16) == 0) {
-							const uint32_t*  objcInfo = (uint32_t*)(sect->addr + slide);
-							return (objcInfo[1] & 6); // 6 = (OBJC_IMAGE_SUPPORTS_GC | OBJC_IMAGE_REQUIRES_GC)
-						}
-					}
-				}
-			}
-			break;
-		}
-		cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
-	}
-	return false;
-}
-#endif
-static void getHostInfo(const macho_header* mainExecutableMH, uintptr_t mainExecutableSlide)
+	// default value for DYLD_FALLBACK_FRAMEWORK_PATH, if not set in environment
+	if ( sEnv.DYLD_FALLBACK_FRAMEWORK_PATH == NULL ) {
+		const char** paths = sFrameworkFallbackPaths;
+		if ( home == NULL )
+			removePathWithPrefix(paths, "$HOME");
+		else
+			paths_expand_roots(paths, "$HOME", home);
+		sEnv.DYLD_FALLBACK_FRAMEWORK_PATH = paths;
+	}
+
+	// default value for DYLD_FALLBACK_LIBRARY_PATH, if not set in environment
+	if ( sEnv.DYLD_FALLBACK_LIBRARY_PATH == NULL ) {
+		const char** paths = sLibraryFallbackPaths;
+		if ( home == NULL ) 
+			removePathWithPrefix(paths, "$HOME");
+		else
+			paths_expand_roots(paths, "$HOME", home);
+		sEnv.DYLD_FALLBACK_LIBRARY_PATH = paths;
+	}
+	
+#if SUPPORT_VERSIONED_PATHS
+	checkVersionedPaths();
+#endif	
+}
+
+
+static void getHostInfo()
 {
 #if CPU_SUBTYPES_SUPPORTED
-#if __ARM_ARCH_7K__
-	sHostCPU		= CPU_TYPE_ARM;
-	sHostCPUsubtype = CPU_SUBTYPE_ARM_V7K;
-#elif __ARM_ARCH_7A__
+#if __ARM_ARCH_7A__
 	sHostCPU		= CPU_TYPE_ARM;
 	sHostCPUsubtype = CPU_SUBTYPE_ARM_V7;
 #elif __ARM_ARCH_6K__
 	sHostCPU		= CPU_TYPE_ARM;
 	sHostCPUsubtype = CPU_SUBTYPE_ARM_V6;
-#elif __ARM_ARCH_7F__
-	sHostCPU		= CPU_TYPE_ARM;
-	sHostCPUsubtype = CPU_SUBTYPE_ARM_V7F;
-#elif __ARM_ARCH_7S__
-	sHostCPU		= CPU_TYPE_ARM;
-	sHostCPUsubtype = CPU_SUBTYPE_ARM_V7S;
 #else
 	struct host_basic_info info;
 	mach_msg_type_number_t count = HOST_BASIC_INFO_COUNT;
@@ -1855,23 +1539,6 @@
 		throw "host_info() failed";
 	sHostCPU		= info.cpu_type;
 	sHostCPUsubtype = info.cpu_subtype;
-	mach_port_deallocate(mach_task_self(), hostPort);
-  #if __x86_64__
-	#if TARGET_IPHONE_SIMULATOR
-	  sHaswell = false;
-	#else
-	  sHaswell = (sHostCPUsubtype == CPU_SUBTYPE_X86_64_H);
-	  // <rdar://problem/18528074> x86_64h: Fall back to the x86_64 slice if an app requires GC.
-	  if ( sHaswell ) {
-		if ( isGCProgram(mainExecutableMH, mainExecutableSlide) ) {
-			// When running a GC program on a haswell machine, don't use and 'h slices
-			sHostCPUsubtype = CPU_SUBTYPE_X86_64_ALL;
-			sHaswell = false;
-			gLinkContext.sharedRegionMode = ImageLoader::kDontUseSharedRegion;
-		}
-	  }
-	#endif
-  #endif
 #endif
 #endif
 }
@@ -1886,30 +1553,24 @@
 		if ( gLinkContext.verboseMapping )
 			dyld::warn("disabling shared region because main executable overlaps\n");
 	}
-#if __i386__
-	if ( sProcessIsRestricted ) {
-		// <rdar://problem/15280847> use private or no shared region for suid processes
-		gLinkContext.sharedRegionMode = ImageLoader::kUsePrivateSharedRegion;
-	}
-#endif
 #endif
 	// iPhoneOS cannot run without shared region
 }
 
 bool validImage(const ImageLoader* possibleImage)
 {
-    const size_t imageCount = sAllImages.size();
-    for(size_t i=0; i < imageCount; ++i) {
-        if ( possibleImage == sAllImages[i] ) {
-            return true;
-        }
-    }
+	const unsigned int imageCount = sAllImages.size();
+	for(unsigned int i=0; i < imageCount; ++i) {
+		if ( possibleImage == sAllImages[i] ) {
+			return true;
+		}
+	}
 	return false;
 }
 
 uint32_t getImageCount()
 {
-	return (uint32_t)sAllImages.size();
+	return sAllImages.size();
 }
 
 ImageLoader* getIndexedImage(unsigned int index)
@@ -1945,8 +1606,8 @@
 
 void forEachImageDo( void (*callback)(ImageLoader*, void* userData), void* userData)
 {
-	const size_t imageCount = sAllImages.size();
-	for(size_t i=0; i < imageCount; ++i) {
+	const unsigned int imageCount = sAllImages.size();
+	for(unsigned int i=0; i < imageCount; ++i) {
 		ImageLoader* anImage = sAllImages[i];
 		(*callback)(anImage, userData);
 	}
@@ -1954,8 +1615,8 @@
 
 ImageLoader* findLoadedImage(const struct stat& stat_buf)
 {
-	const size_t imageCount = sAllImages.size();
-	for(size_t i=0; i < imageCount; ++i){
+	const unsigned int imageCount = sAllImages.size();
+	for(unsigned int i=0; i < imageCount; ++i){
 		ImageLoader* anImage = sAllImages[i];
 		if ( anImage->statMatch(stat_buf) )
 			return anImage;
@@ -1966,7 +1627,7 @@
 // based on ANSI-C strstr()
 static const char* strrstr(const char* str, const char* sub) 
 {
-	const size_t sublen = strlen(sub);
+	const int sublen = strlen(sub);
 	for(const char* p = &str[strlen(str)]; p != str; --p) {
 		if ( strncmp(p, sub, sublen) == 0 )
 			return p;
@@ -1996,7 +1657,7 @@
 				const char* frameworkStart = &dirStart[1];
 				if ( dirStart == path )
 					--frameworkStart;
-				size_t len = dirDot - frameworkStart;
+				int len = dirDot - frameworkStart;
 				char framework[len+1];
 				strncpy(framework, frameworkStart, len);
 				framework[len] = '\0';
@@ -2049,22 +1710,31 @@
 //
 
 
+#if __ppc__
+//	 
+//	32-bit PowerPC sub-type lists
+//
+const int kPPC_RowCount = 4;
+static const cpu_subtype_t kPPC32[kPPC_RowCount][6] = { 
+	// G5 can run any code
+	{  CPU_SUBTYPE_POWERPC_970, CPU_SUBTYPE_POWERPC_7450,  CPU_SUBTYPE_POWERPC_7400, CPU_SUBTYPE_POWERPC_750, CPU_SUBTYPE_POWERPC_ALL, CPU_SUBTYPE_END_OF_LIST },
+	
+	// G4 can run all but G5 code
+	{  CPU_SUBTYPE_POWERPC_7450,  CPU_SUBTYPE_POWERPC_7400,  CPU_SUBTYPE_POWERPC_750, CPU_SUBTYPE_POWERPC_ALL, CPU_SUBTYPE_END_OF_LIST, CPU_SUBTYPE_END_OF_LIST },
+	{  CPU_SUBTYPE_POWERPC_7400,  CPU_SUBTYPE_POWERPC_7450,  CPU_SUBTYPE_POWERPC_750, CPU_SUBTYPE_POWERPC_ALL, CPU_SUBTYPE_END_OF_LIST, CPU_SUBTYPE_END_OF_LIST },
+
+	// G3 cannot run G4 or G5 code
+	{ CPU_SUBTYPE_POWERPC_750,  CPU_SUBTYPE_POWERPC_ALL, CPU_SUBTYPE_END_OF_LIST,  CPU_SUBTYPE_END_OF_LIST, CPU_SUBTYPE_END_OF_LIST, CPU_SUBTYPE_END_OF_LIST }
+};
+#endif
+
+
 #if __arm__
 //      
 //     ARM sub-type lists
 //
-const int kARM_RowCount = 8;
-static const cpu_subtype_t kARM[kARM_RowCount][9] = { 
-
-	// armv7f can run: v7f, v7, v6, v5, and v4
-	{  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 },
-
-	// armv7k can run: v7k
-	{  CPU_SUBTYPE_ARM_V7K, CPU_SUBTYPE_END_OF_LIST },
-
-	// armv7s can run: v7s, v7, v7f, v7k, v6, v5, and v4
-	{  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 },
-
+const int kARM_RowCount = 5;
+static const cpu_subtype_t kARM[kARM_RowCount][6] = { 
 	// armv7 can run: v7, v6, v5, and v4
 	{  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 },
 	
@@ -2082,40 +1752,24 @@
 };
 #endif
 
-#if __x86_64__
-//      
-//     x86_64 sub-type lists
-//
-const int kX86_64_RowCount = 2;
-static const cpu_subtype_t kX86_64[kX86_64_RowCount][5] = {
-
-	// x86_64h can run: x86_64h, x86_64h(lib), x86_64(lib), and x86_64
-	{ CPU_SUBTYPE_X86_64_H, CPU_SUBTYPE_LIB64|CPU_SUBTYPE_X86_64_H, CPU_SUBTYPE_LIB64|CPU_SUBTYPE_X86_64_ALL, CPU_SUBTYPE_X86_64_ALL,  CPU_SUBTYPE_END_OF_LIST },
-
-	// x86_64 can run: x86_64(lib) and x86_64
-	{ CPU_SUBTYPE_X86_64_ALL, CPU_SUBTYPE_LIB64|CPU_SUBTYPE_X86_64_ALL, CPU_SUBTYPE_END_OF_LIST },
-
-};
-#endif
-
 
 // scan the tables above to find the cpu-sub-type-list for this machine
 static const cpu_subtype_t* findCPUSubtypeList(cpu_type_t cpu, cpu_subtype_t subtype)
 {
 	switch (cpu) {
+#if __ppc__
+		case CPU_TYPE_POWERPC:
+			for (int i=0; i < kPPC_RowCount ; ++i) {
+				if ( kPPC32[i][0] == subtype )
+					return kPPC32[i];
+			}
+			break;
+#endif
 #if __arm__
 		case CPU_TYPE_ARM:
 			for (int i=0; i < kARM_RowCount ; ++i) {
 				if ( kARM[i][0] == subtype )
 					return kARM[i];
-			}
-			break;
-#endif
-#if __x86_64__
-		case CPU_TYPE_X86_64:
-			for (int i=0; i < kX86_64_RowCount ; ++i) {
-				if ( kX86_64[i][0] == subtype )
-					return kX86_64[i];
 			}
 			break;
 #endif
@@ -2165,18 +1819,18 @@
 	for(uint32_t i=0; i < OSSwapBigToHostInt32(fh->nfat_arch); ++i) {
 		if ( (cpu_type_t)OSSwapBigToHostInt32(archs[i].cputype) == cpu) {
 			switch (cpu) {
-#if __arm__
-				case CPU_TYPE_ARM:
-					if ( (cpu_subtype_t)OSSwapBigToHostInt32(archs[i].cpusubtype) == CPU_SUBTYPE_ARM_ALL ) {
+#if __ppc__
+				case CPU_TYPE_POWERPC:
+					if ( (cpu_subtype_t)OSSwapBigToHostInt32(archs[i].cpusubtype) == CPU_SUBTYPE_POWERPC_ALL ) {
 						*offset = OSSwapBigToHostInt32(archs[i].offset);
 						*len = OSSwapBigToHostInt32(archs[i].size);
 						return true;
 					}
 					break;
 #endif
-#if __x86_64__
-				case CPU_TYPE_X86_64:
-					if ( (cpu_subtype_t)OSSwapBigToHostInt32(archs[i].cpusubtype) == CPU_SUBTYPE_X86_64_ALL ) {
+#if __arm__
+				case CPU_TYPE_ARM:
+					if ( (cpu_subtype_t)OSSwapBigToHostInt32(archs[i].cpusubtype) == CPU_SUBTYPE_ARM_ALL ) {
 						*offset = OSSwapBigToHostInt32(archs[i].offset);
 						*len = OSSwapBigToHostInt32(archs[i].size);
 						return true;
@@ -2266,6 +1920,12 @@
 			
 			// cpu type has no ordered list of subtypes
 			switch (mh->cputype) {
+				case CPU_TYPE_POWERPC:
+					// allow _ALL to be used by any client
+					if ( mh->cpusubtype == CPU_SUBTYPE_POWERPC_ALL ) 
+						return true;
+					break;
+				case CPU_TYPE_POWERPC64:
 				case CPU_TYPE_I386:
 				case CPU_TYPE_X86_64:
 					// subtypes are not used or these architectures
@@ -2305,7 +1965,7 @@
 
 
 #if DYLD_SHARED_CACHE_SUPPORT
-static bool findInSharedCacheImage(const char* path, bool searchByPath, const struct stat* stat_buf, const macho_header** mh, const char** pathInCache, long* slide)
+static bool findInSharedCacheImage(const char* path, const struct stat* stat_buf, const macho_header** mh, const char** pathInCache, long* slide)
 {
 	if ( sSharedCache != NULL ) {
 #if __MAC_OS_X_VERSION_MIN_REQUIRED	
@@ -2313,29 +1973,18 @@
 		// if stat() not done yet, do it now
 		struct stat statb;
 		if ( stat_buf == NULL ) {
-			if ( my_stat(path, &statb) == -1 )
+			if ( stat(path, &statb) == -1 )
 				return false;
 			stat_buf = &statb;
 		}
 #endif
-#if __IPHONE_OS_VERSION_MIN_REQUIRED	
-		uint64_t hash = 0;
-		for (const char* s=path; *s != '\0'; ++s)
-			hash += hash*4 + *s;
-#endif
-
 		// walk shared cache to see if there is a cached image that matches the inode/mtime/path desired
 		const dyld_cache_image_info* const start = (dyld_cache_image_info*)((uint8_t*)sSharedCache + sSharedCache->imagesOffset);
 		const dyld_cache_image_info* const end = &start[sSharedCache->imagesCount];
-#if __IPHONE_OS_VERSION_MIN_REQUIRED	
-		const bool cacheHasHashInfo = (start->modTime == 0);
-#endif
 		for( const dyld_cache_image_info* p = start; p != end; ++p) {
 #if __IPHONE_OS_VERSION_MIN_REQUIRED	
 			// just check path
 			const char* aPath = (char*)sSharedCache + p->pathFileOffset;
-			if ( cacheHasHashInfo && (p->inode != hash) )
-				continue;
 			if ( strcmp(path, aPath) == 0 ) {
 				// found image in cache
 				*mh = (macho_header*)(p->address+sSharedCacheSlide);
@@ -2345,16 +1994,16 @@
 			}
 #elif __MAC_OS_X_VERSION_MIN_REQUIRED
 			// check mtime and inode first because it is fast
-			bool inodeMatch = ( ((time_t)p->modTime == stat_buf->st_mtime) && ((ino_t)p->inode == stat_buf->st_ino) );
-			if ( searchByPath || sSharedCacheIgnoreInodeAndTimeStamp || inodeMatch ) {
+			if ( sSharedCacheIgnoreInodeAndTimeStamp 
+				|| ( ((time_t)p->modTime == stat_buf->st_mtime) && ((ino_t)p->inode == stat_buf->st_ino) ) ) {
 				// mod-time and inode match an image in the shared cache, now check path
 				const char* aPath = (char*)sSharedCache + p->pathFileOffset;
 				bool cacheHit = (strcmp(path, aPath) == 0);
-				if ( inodeMatch && !cacheHit ) {
+				if ( ! cacheHit ) {
 					// path does not match install name of dylib in cache, but inode and mtime does match
 					// perhaps path is a symlink to the cached dylib
 					struct stat pathInCacheStatBuf;
-					if ( my_stat(aPath, &pathInCacheStatBuf) != -1 )
+					if ( stat(aPath, &pathInCacheStatBuf) != -1 )
 						cacheHit = ( (pathInCacheStatBuf.st_dev == stat_buf->st_dev) && (pathInCacheStatBuf.st_ino == stat_buf->st_ino) );	
 				}
 				if ( cacheHit ) {
@@ -2378,7 +2027,7 @@
 	const macho_header* mhInCache;
 	const char*			pathInCache;
 	long				slide;
-	return findInSharedCacheImage(path, true, NULL, &mhInCache, &pathInCache, &slide);
+	return findInSharedCacheImage(path, NULL, &mhInCache, &pathInCache, &slide);
 }
 
 #endif
@@ -2421,34 +2070,6 @@
 	return image;
 }
 
-#if TARGET_IPHONE_SIMULATOR	
-static bool isSimulatorBinary(const uint8_t* firstPage, const char* path)
-{
-	const macho_header* mh = (macho_header*)firstPage;
-	const uint32_t cmd_count = mh->ncmds;
-	const struct load_command* const cmds = (struct load_command*)(((char*)mh)+sizeof(macho_header));
-	const struct load_command* const cmdsReadEnd = (struct load_command*)(((char*)mh)+4096);
-	const struct load_command* cmd = cmds;
-	for (uint32_t i = 0; i < cmd_count; ++i) {
-		switch (cmd->cmd) {
-			case LC_VERSION_MIN_IPHONEOS:
-			case LC_VERSION_MIN_TVOS:
-			case LC_VERSION_MIN_WATCHOS:
-				return true;
-			case LC_VERSION_MIN_MACOSX:
-				// grandfather in a few libSystem dylibs
-				if (strstr(path, "/usr/lib/system") || strstr(path, "/usr/lib/libSystem"))
- 					return true;
-				return false;
-		}
-		cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
-		if ( cmd > cmdsReadEnd )
-			return true;
-	}
-	return false;
-}
-#endif
-
 // map in file and instantiate an ImageLoader
 static ImageLoader* loadPhase6(int fd, const struct stat& stat_buf, const char* path, const LoadContext& context)
 {
@@ -2502,18 +2123,7 @@
 			default:
 				throw "mach-o, but wrong filetype";
 		}
-
-#if TARGET_IPHONE_SIMULATOR	
-	#if TARGET_OS_WATCH || TARGET_OS_TV
-		// disable error during bring up of these simulators
-	#else
-		// <rdar://problem/14168872> dyld_sim should restrict loading osx binaries
-		if ( !isSimulatorBinary(firstPage, path) ) {
-			throw "mach-o, but not built for iOS simulator";
-		}
-	#endif
-#endif
-
+		
 		// instantiate an image
 		ImageLoader* image = ImageLoaderMachO::instantiateFromFile(path, fd, firstPage, fileOffset, fileLength, stat_buf, gLinkContext);
 		
@@ -2575,7 +2185,7 @@
 
 	// just return NULL if file not found, but record any other errors
 	struct stat stat_buf;
-	if ( my_stat(path, &stat_buf) == -1 ) {
+	if ( stat(path, &stat_buf) == -1 ) {
 		int err = errno;
 		if ( err != ENOENT ) {
 			exceptions->push_back(dyld::mkstringf("%s: stat() failed with errno=%d", path, err));
@@ -2597,7 +2207,7 @@
 	const macho_header* mhInCache;
 	const char*			pathInCache;
 	long				slideInCache;
-	if ( findInSharedCacheImage(path, false, &stat_buf, &mhInCache, &pathInCache, &slideInCache) ) {
+	if ( findInSharedCacheImage(path, &stat_buf, &mhInCache, &pathInCache, &slideInCache) ) {
 		image = ImageLoaderMachO::instantiateFromCache(mhInCache, pathInCache, slideInCache, stat_buf, gLinkContext);
 		return checkandAddImage(image, context);
 	}
@@ -2615,8 +2225,7 @@
 {
 	ImageLoader* image = NULL;
 	*imageFound = false;
-	*statErrNo = 0;
-	if ( my_stat(path, stat_buf) == 0 ) {
+	if ( stat(path, stat_buf) == 0 ) {
 		// in case image was renamed or found via symlinks, check for inode match
 		image = findLoadedImage(*stat_buf);
 		if ( image != NULL ) {
@@ -2659,11 +2268,11 @@
 	const macho_header* mhInCache;
 	const char*			pathInCache;
 	long				slideInCache;
-	if ( findInSharedCacheImage(path, true, NULL, &mhInCache, &pathInCache, &slideInCache) ) {
+	if ( findInSharedCacheImage(path, NULL, &mhInCache, &pathInCache, &slideInCache) ) {
 		// see if this image in the cache was already loaded via a different path
 		for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); ++it) {
 			ImageLoader* anImage = *it;
-			if ( (const macho_header*)anImage->machHeader() == mhInCache )
+			if ( anImage->machHeader() == mhInCache )
 				return anImage;
 		}
 		// do nothing if not already loaded and if RTLD_NOLOAD 
@@ -2688,7 +2297,7 @@
 		return image;
 #endif
 	// just return NULL if file not found, but record any other errors
-	if ( (statErrNo != ENOENT) && (statErrNo != 0) ) {
+	if ( statErrNo != ENOENT ) {
 		exceptions->push_back(dyld::mkstringf("%s: stat() failed with errno=%d", path, statErrNo));
 	}
 	return NULL;
@@ -2787,7 +2396,7 @@
 	ImageLoader* image = NULL;
 	if ( strncmp(path, "@executable_path/", 17) == 0 ) {
 		// executable_path cannot be in used in any binary in a setuid process rdar://problem/4589305
-		if ( sProcessIsRestricted && !sProcessRequiresLibraryValidation )
+		if ( sProcessIsRestricted ) 
 			throwf("unsafe use of @executable_path in %s with restricted binary", context.origin);
 		// handle @executable_path path prefix
 		const char* executablePath = sExecPath;
@@ -2819,7 +2428,7 @@
 	}
 	else if ( (strncmp(path, "@loader_path/", 13) == 0) && (context.origin != NULL) ) {
 		// @loader_path cannot be used from the main executable of a setuid process rdar://problem/4589305
-		if ( sProcessIsRestricted && (strcmp(context.origin, sExecPath) == 0) && !sProcessRequiresLibraryValidation )
+		if ( sProcessIsRestricted && (strcmp(context.origin, sExecPath) == 0) )
 			throwf("unsafe use of @loader_path in %s with restricted binary", context.origin);
 		// handle @loader_path path prefix
 		char newPath[strlen(context.origin) + strlen(path)];
@@ -2883,7 +2492,7 @@
 		if ( (exceptions != NULL) && (trailingPath != path) )
 			return NULL;
 	}
-	else if (sProcessIsRestricted && (path[0] != '/' ) && !sProcessRequiresLibraryValidation) {
+	else if (sProcessIsRestricted && (path[0] != '/' )) {
 		throwf("unsafe use of relative rpath %s in %s with restricted binary", path, context.origin);
 	}
 	
@@ -2901,7 +2510,7 @@
 	const char* frameworkPartialPath = getFrameworkPartialPath(path);
 	if ( frameworkPaths != NULL ) {
 		if ( frameworkPartialPath != NULL ) {
-			const size_t frameworkPartialPathLen = strlen(frameworkPartialPath);
+			const int frameworkPartialPathLen = strlen(frameworkPartialPath);
 			for(const char* const* fp = frameworkPaths; *fp != NULL; ++fp) {
 				char npath[strlen(*fp)+frameworkPartialPathLen+8];
 				strcpy(npath, *fp);
@@ -2914,11 +2523,9 @@
 			}
 		}
 	}
-	// <rdar://problem/12649639> An executable with the same name as a framework & DYLD_LIBRARY_PATH pointing to it gets loaded twice
-	// <rdar://problem/14160846> Some apps depend on frameworks being found via library paths
-	if ( (libraryPaths != NULL) && ((frameworkPartialPath == NULL) || sFrameworksFoundAsDylibs) ) {
+	if ( libraryPaths != NULL ) {
 		const char* libraryLeafName = getLibraryLeafName(path);
-		const size_t libraryLeafNameLen = strlen(libraryLeafName);
+		const int libraryLeafNameLen = strlen(libraryLeafName);
 		for(const char* const* lp = libraryPaths; *lp != NULL; ++lp) {
 			char libpath[strlen(*lp)+libraryLeafNameLen+8];
 			strcpy(libpath, *lp);
@@ -2991,16 +2598,6 @@
 	// try raw path
 	return loadPhase1(path, orgPath, context, exceptions);
 }
-
-#if DYLD_SHARED_CACHE_SUPPORT
-	static bool cacheablePath(const char* path) {
-		if (strncmp(path, "/usr/lib/", 9) == 0)
-			return true;
-		if (strncmp(path, "/System/Library/", 16) == 0)
-			return true;
-		return false;
-	}
-#endif
 
 //
 // Given all the DYLD_ environment variables, the general case for loading libraries
@@ -3039,44 +2636,19 @@
 	// try all path permutations and try open() until first success
 	std::vector<const char*> exceptions;
 	image = loadPhase0(path, orgPath, context, &exceptions);
-#if __IPHONE_OS_VERSION_MIN_REQUIRED && DYLD_SHARED_CACHE_SUPPORT && !TARGET_IPHONE_SIMULATOR
-	// <rdar://problem/16704628> support symlinks on disk to a path in dyld shared cache
-	if ( (image == NULL) && cacheablePath(path) && !context.dontLoad ) {
-		char resolvedPath[PATH_MAX];
-		realpath(path, resolvedPath);
-		int myerr = errno;
-		// If realpath() resolves to a path which does not exist on disk, errno is set to ENOENT
-		if ( (myerr == ENOENT) || (myerr == 0) )
-		{
-			// see if this image is in shared cache
-			const macho_header* mhInCache;
-			const char*			pathInCache;
-			long				slideInCache;
-			if ( findInSharedCacheImage(resolvedPath, false, NULL, &mhInCache, &pathInCache, &slideInCache) ) {
-				struct stat stat_buf;
-				bzero(&stat_buf, sizeof(stat_buf));
-				try {
-					image = ImageLoaderMachO::instantiateFromCache(mhInCache, pathInCache, slideInCache, stat_buf, gLinkContext);
-					image = checkandAddImage(image, context);
-				}
-				catch (...) {
-					image = NULL;
-				}
-			}
-		}
-	}
-#endif
     CRSetCrashLogMessage2(NULL);
 	if ( image != NULL ) {
 		// <rdar://problem/6916014> leak in dyld during dlopen when using DYLD_ variables
 		for (std::vector<const char*>::iterator it = exceptions.begin(); it != exceptions.end(); ++it) {
 			free((void*)(*it));
 		}
-#if DYLD_SHARED_CACHE_SUPPORT
+#if __IPHONE_OS_VERSION_MIN_REQUIRED
 		// if loaded image is not from cache, but original path is in cache
 		// set gSharedCacheOverridden flag to disable some ObjC optimizations
-		if ( !gSharedCacheOverridden && !image->inSharedCache() && image->isDylib() && cacheablePath(path) && inSharedCache(path) ) {
-			gSharedCacheOverridden = true;
+		if ( !gSharedCacheOverridden ) {
+			if ( !image->inSharedCache() && inSharedCache(path) ) {
+				gSharedCacheOverridden = true;
+			}
 		}
 #endif
 		return image;
@@ -3092,11 +2664,11 @@
 		const char* msgStart = "no suitable image found.  Did find:";
 		const char* delim = "\n\t";
 		size_t allsizes = strlen(msgStart)+8;
-		for (size_t i=0; i < exceptions.size(); ++i) 
+		for (unsigned int i=0; i < exceptions.size(); ++i) 
 			allsizes += (strlen(exceptions[i]) + strlen(delim));
 		char* fullMsg = new char[allsizes];
 		strcpy(fullMsg, msgStart);
-		for (size_t i=0; i < exceptions.size(); ++i) {
+		for (unsigned int i=0; i < exceptions.size(); ++i) {
 			strcat(fullMsg, delim);
 			strcat(fullMsg, exceptions[i]);
 			free((void*)exceptions[i]);
@@ -3107,53 +2679,59 @@
 
 
 
+
 #if DYLD_SHARED_CACHE_SUPPORT
 
 
 
-#if __i386__
+
+#if __ppc__
+	#define ARCH_NAME			"ppc"
+	#define ARCH_NAME_ROSETTA	"rosetta"
+	#define ARCH_CACHE_MAGIC	"dyld_v1     ppc"
+#elif __ppc64__
+	#define ARCH_NAME			"ppc64"
+	#define ARCH_CACHE_MAGIC	"dyld_v1   ppc64"
+#elif __i386__
 	#define ARCH_NAME			"i386"
 	#define ARCH_CACHE_MAGIC	"dyld_v1    i386"
 #elif __x86_64__
 	#define ARCH_NAME			"x86_64"
 	#define ARCH_CACHE_MAGIC	"dyld_v1  x86_64"
-	#define ARCH_NAME_H			"x86_64h"
-	#define ARCH_CACHE_MAGIC_H	"dyld_v1 x86_64h"
+	#define SHARED_REGION_READ_ONLY_START   0x7FFF80000000LL
+	#define SHARED_REGION_READ_ONLY_END     0x7FFFC0000000LL
+	#define SHARED_REGION_WRITABLE_START    0x7FFF70000000LL
+	#define SHARED_REGION_WRITABLE_END      0x7FFF80000000LL
+	#define SLIDEABLE_CACHE_SUPPORT		    1
 #elif __ARM_ARCH_5TEJ__
 	#define ARCH_NAME			"armv5"
 	#define ARCH_CACHE_MAGIC	"dyld_v1   armv5"
 #elif __ARM_ARCH_6K__
 	#define ARCH_NAME			"armv6"
 	#define ARCH_CACHE_MAGIC	"dyld_v1   armv6"
-#elif __ARM_ARCH_7F__
-	#define ARCH_NAME			"armv7f"
-	#define ARCH_CACHE_MAGIC	"dyld_v1  armv7f"
-#elif __ARM_ARCH_7K__
-	#define ARCH_NAME			"armv7k"
-	#define ARCH_CACHE_MAGIC	"dyld_v1  armv7k"
 #elif __ARM_ARCH_7A__
 	#define ARCH_NAME			"armv7"
 	#define ARCH_CACHE_MAGIC	"dyld_v1   armv7"
-#elif __ARM_ARCH_7S__
-	#define ARCH_NAME			"armv7s"
-	#define ARCH_CACHE_MAGIC	"dyld_v1  armv7s"
-#elif __arm64__
-	#define ARCH_NAME			"arm64"
-	#define ARCH_CACHE_MAGIC	"dyld_v1   arm64"
+	#define SHARED_REGION_READ_ONLY_START   0x30000000
+	#define SHARED_REGION_READ_ONLY_END     0x3E000000
+	#define SHARED_REGION_WRITABLE_START    0x3E000000
+	#define SHARED_REGION_WRITABLE_END      0x40000000
+	#define SLIDEABLE_CACHE_SUPPORT		    1
 #endif
 
 
 static int __attribute__((noinline)) _shared_region_check_np(uint64_t* start_address)
 {
-	if ( gLinkContext.sharedRegionMode == ImageLoader::kUseSharedRegion ) 
+	if ( (gLinkContext.sharedRegionMode == ImageLoader::kUseSharedRegion) ) 
 		return syscall(294, start_address);
 	return -1;
 }
 
 
-static int __attribute__((noinline)) _shared_region_map_and_slide_np(int fd, uint32_t count, const shared_file_mapping_np mappings[],
-												int codeSignatureMappingIndex, long slide, void* slideInfo, unsigned long slideInfoSize)
-{
+static int __attribute__((noinline)) _shared_region_map_and_slide_np(int fd, uint32_t count, const shared_file_mapping_np mappings[], 
+												int codeSignatureMappingIndex, int slide, void* slideInfo, uint32_t slideInfoSize)
+{
+#if __IPHONE_OS_VERSION_MIN_REQUIRED	
 	// register code signature blob for whole dyld cache
 	if ( codeSignatureMappingIndex != -1 ) {
 		fsignatures_t siginfo;
@@ -3161,12 +2739,11 @@
 		siginfo.fs_blob_start = (void*)mappings[codeSignatureMappingIndex].sfm_file_offset;
 		siginfo.fs_blob_size  = mappings[codeSignatureMappingIndex].sfm_size;
 		int result = fcntl(fd, F_ADDFILESIGS, &siginfo);
-		// <rdar://problem/12891874> don't warn in chrooted case because mapping syscall is about to fail too
-		if ( (result == -1) && gLinkContext.verboseMapping )
-			dyld::log("dyld: code signature registration for shared cache failed with errno=%d\n", errno);
-	}
-
-	if ( gLinkContext.sharedRegionMode == ImageLoader::kUseSharedRegion ) {
+		if ( result == -1 ) 
+			dyld::log("dyld: code signature for shared cache failed with errno=%d\n", errno);
+	}
+#endif
+	if ( (gLinkContext.sharedRegionMode == ImageLoader::kUseSharedRegion) ) {
 		return syscall(438, fd, count, mappings, slide, slideInfo, slideInfoSize);
 	}
 
@@ -3174,7 +2751,7 @@
 	vm_deallocate(mach_task_self(), (vm_address_t)SHARED_REGION_BASE, SHARED_REGION_SIZE);
 	
 	// notify gdb or other lurkers that this process is no longer using the shared region
-	dyld::gProcessInfo->processDetachedFromSharedRegion = true;
+	dyld_all_image_infos.processDetachedFromSharedRegion = true;
 
 	// map cache just for this process with mmap()
 	const shared_file_mapping_np* const start = mappings;
@@ -3206,6 +2783,7 @@
 		}
 	}
 
+#if SLIDEABLE_CACHE_SUPPORT
 	// update all __DATA pages with slide info
 	if ( slide != 0 ) {
 		const uintptr_t dataPagesStart = mappings[1].sfm_address;
@@ -3232,6 +2810,7 @@
 			}
 		}
 	}
+#endif // SLIDEABLE_CACHE_SUPPORT
 
 	// succesfully mapped shared cache for just this process
 	gLinkContext.sharedRegionMode = ImageLoader::kUsePrivateSharedRegion;
@@ -3245,105 +2824,62 @@
 	return sSharedCache;
 }
 
-const char* getStandardSharedCacheFilePath()
-{
-#if __IPHONE_OS_VERSION_MIN_REQUIRED
-	return IPHONE_DYLD_SHARED_CACHE_DIR DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME;
-#else
-  #if __x86_64__
-	if ( sHaswell ) {
-		const char* path2 = MACOSX_DYLD_SHARED_CACHE_DIR DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME_H;
-		struct stat statBuf;
-		if ( my_stat(path2, &statBuf) == 0 )
-			return path2;
-	}
-  #endif
-	return MACOSX_DYLD_SHARED_CACHE_DIR DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME;
-#endif
-}
-
 int openSharedCacheFile()
 {
-	char path[MAXPATHLEN];
-	strlcpy(path, sSharedCacheDir, MAXPATHLEN);
-	strlcat(path, "/", MAXPATHLEN);
-#if __x86_64__
-	if ( sHaswell ) {
-		strlcat(path, DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME_H, MAXPATHLEN);
-		int fd = my_open(path, O_RDONLY, 0);
-		if ( fd != -1 ) {
-			if ( gLinkContext.verboseMapping ) 
-				dyld::log("dyld: Mapping%s shared cache from %s\n", (gLinkContext.sharedRegionMode == ImageLoader::kUsePrivateSharedRegion) ? " private": "", path);
-			return fd;
-		}
-		strlcpy(path, sSharedCacheDir, MAXPATHLEN);
-	}
-#endif
-	strlcat(path, DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME, MAXPATHLEN);
-	if ( gLinkContext.verboseMapping ) 
-		dyld::log("dyld: Mapping%s shared cache from %s\n", (gLinkContext.sharedRegionMode == ImageLoader::kUsePrivateSharedRegion) ? " private": "", path);
-	return my_open(path, O_RDONLY, 0);
-}
-
-
-static void getCacheBounds(uint32_t mappingsCount, const shared_file_mapping_np mappings[], uint64_t& lowAddress, uint64_t& highAddress)
-{
-	lowAddress = 0;
-	highAddress = 0;
+	char path[1024];
+	strcpy(path, sSharedCacheDir);
+	strcat(path, "/");
+#if __ppc__
+	// rosetta cannot handle optimized _ppc cache, so it use _rosetta cache instead, rdar://problem/5495438
+    if ( isRosetta() )
+		strcat(path, DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME_ROSETTA);
+    else
+#endif
+		strcat(path, DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME);
+	return ::open(path, O_RDONLY);
+}
+
+#if SLIDEABLE_CACHE_SUPPORT
+static long pickCacheSlide(uint32_t mappingsCount, shared_file_mapping_np mappings[])
+{
+	// get bounds of cache
+	uint64_t readOnlyLowAddress = 0;
+	uint64_t readOnlyHighAddress = 0;
+	uint64_t writableLowAddress = 0;
+	uint64_t writableHighAddress = 0;
 	for(uint32_t i=0; i < mappingsCount; ++i) {
-		if ( lowAddress == 0 ) {
-			lowAddress = mappings[i].sfm_address;
-			highAddress = mappings[i].sfm_address + mappings[i].sfm_size;
+		if ( mappings[i].sfm_init_prot & VM_PROT_WRITE ) {
+			writableLowAddress = mappings[i].sfm_address;
+			writableHighAddress = mappings[i].sfm_address + mappings[i].sfm_size;
 		}
 		else {
-			if ( mappings[i].sfm_address < lowAddress )
-				lowAddress = mappings[i].sfm_address;
-			if ( (mappings[i].sfm_address + mappings[i].sfm_size) > highAddress )
-				highAddress = mappings[i].sfm_address + mappings[i].sfm_size;
-		}
-	}
-}
-
-static long pickCacheSlide(uint32_t mappingsCount, shared_file_mapping_np mappings[])
-{
-#if __x86_64__
-	// x86_64 has a two memory regions:
-	//       256MB at 0x00007FFF70000000 
-	//      1024MB at 0x00007FFF80000000
-	// Some old shared caches have r/w region after rx region, so all regions slide within 1GB range
-	// Newer shared caches have r/w region based at 0x7FFF70000000 and r/o regions at 0x7FFF80000000, so each part has max slide
-	if ( (mappingsCount >= 3) && (mappings[1].sfm_init_prot == (VM_PROT_READ|VM_PROT_WRITE)) && (mappings[1].sfm_address == 0x00007FFF70000000) ) {
-		const uint64_t rwSize = mappings[1].sfm_size;
-		const uint64_t rwSlop = 0x10000000ULL - rwSize;
-		const uint64_t roSize = (mappings[2].sfm_address + mappings[2].sfm_size) - mappings[0].sfm_address;
-		const uint64_t roSlop = 0x40000000ULL - roSize;
-		const uint64_t space = (rwSlop < roSlop) ? rwSlop : roSlop;
-		
-		// choose new random slide
-		long slide = (arc4random() % space) & (-4096);
-		//dyld::log("rwSlop=0x%0llX, roSlop=0x%0llX\n", rwSlop, roSlop);
-		//dyld::log("space=0x%0llX, slide=0x%0lX\n", space, slide);
-		
-		// update mappings
-		for(uint32_t i=0; i < mappingsCount; ++i) {
-			mappings[i].sfm_address += slide;
-		}
-		
-		return slide;
-	}
-	// else fall through to handle old style cache
-#endif
-	// get bounds of cache
-	uint64_t lowAddress;
-	uint64_t highAddress;
-	getCacheBounds(mappingsCount, mappings, lowAddress, highAddress);
-	
-	// find slop space
-	const uint64_t space = (SHARED_REGION_BASE + SHARED_REGION_SIZE) - highAddress;
+			if ( readOnlyLowAddress == 0 ) {
+				readOnlyLowAddress = mappings[i].sfm_address;
+				readOnlyHighAddress = mappings[i].sfm_address + mappings[i].sfm_size;
+			}
+			else {
+				if ( readOnlyLowAddress < mappings[i].sfm_address ) {
+					readOnlyHighAddress = mappings[i].sfm_address + mappings[i].sfm_size;
+				}
+				else {
+					readOnlyLowAddress = mappings[i].sfm_address;
+				}
+			}
+		}
+	}
+	
+	// find read-only slop space
+	uint64_t roSpace = SHARED_REGION_READ_ONLY_END - readOnlyHighAddress;
+
+	// find writable slop space
+	uint64_t rwSpace = SHARED_REGION_WRITABLE_END - writableHighAddress;
 	
 	// choose new random slide
-	long slide = dyld_page_trunc(arc4random() % space);
-	//dyld::log("slideSpace=0x%0llX\n", space);
+	long slideSpace = (roSpace > rwSpace) ? rwSpace : roSpace;
+	long slide = (arc4random() % slideSpace) & (-4096);
+	//dyld::log("roSpace=0x%0llX\n", roSpace);
+	//dyld::log("rwSpace=0x%0llX\n", rwSpace);
+	//dyld::log("slideSpace=0x%0lX\n", slideSpace);
 	//dyld::log("slide=0x%0lX\n", slide);
 	
 	// update mappings
@@ -3353,44 +2889,30 @@
 	
 	return slide;
 }
+#endif // SLIDEABLE_CACHE_SUPPORT
 
 static void mapSharedCache()
 {
-	uint64_t cacheBaseAddress = 0;
-	// quick check if a cache is already mapped into shared region
+	uint64_t cacheBaseAddress;
+	// quick check if a cache is alreay mapped into shared region
 	if ( _shared_region_check_np(&cacheBaseAddress) == 0 ) {
 		sSharedCache = (dyld_cache_header*)cacheBaseAddress;
 		// if we don't understand the currently mapped shared cache, then ignore
-#if __x86_64__
-		const char* magic = (sHaswell ? ARCH_CACHE_MAGIC_H : ARCH_CACHE_MAGIC);
-#else
-		const char* magic = ARCH_CACHE_MAGIC;
-#endif
-		if ( strcmp(sSharedCache->magic, magic) != 0 ) {
+		if ( strcmp(sSharedCache->magic, ARCH_CACHE_MAGIC) != 0 ) {
 			sSharedCache = NULL;
-			if ( gLinkContext.verboseMapping ) {
+			if ( gLinkContext.verboseMapping ) 
 				dyld::log("dyld: existing shared cached in memory is not compatible\n");
-				return;
-			}
 		}
 		// check if cache file is slidable
-		const dyld_cache_header* header = sSharedCache;
+		dyld_cache_header* header = (dyld_cache_header*)sSharedCache;
 		if ( (header->mappingOffset >= 0x48) && (header->slideInfoSize != 0) ) {
 			// solve for slide by comparing loaded address to address of first region
 			const uint8_t* loadedAddress = (uint8_t*)sSharedCache;
 			const dyld_cache_mapping_info* const mappings = (dyld_cache_mapping_info*)(loadedAddress+header->mappingOffset);
 			const uint8_t* preferedLoadAddress = (uint8_t*)(long)(mappings[0].address);
 			sSharedCacheSlide = loadedAddress - preferedLoadAddress;
-			dyld::gProcessInfo->sharedCacheSlide = sSharedCacheSlide;
+			dyld_all_image_infos.sharedCacheSlide = sSharedCacheSlide;
 			//dyld::log("sSharedCacheSlide=0x%08lX, loadedAddress=%p, preferedLoadAddress=%p\n", sSharedCacheSlide, loadedAddress, preferedLoadAddress);
-		}
-		// if cache has a uuid, copy it 
-		if ( header->mappingOffset >= 0x68 ) {
-			memcpy(dyld::gProcessInfo->sharedCacheUUID, header->uuid, 16);
-		}
-		// verbose logging
-		if ( gLinkContext.verboseMapping ) {
-			dyld::log("dyld: re-using existing shared cache mapping\n");
 		}
 	}
 	else {
@@ -3404,7 +2926,7 @@
 			// user booted machine in safe-boot mode
 			struct stat dyldCacheStatInfo;
 			//  Don't use custom DYLD_SHARED_CACHE_DIR if provided, use standard path
-			if ( my_stat(MACOSX_DYLD_SHARED_CACHE_DIR DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME, &dyldCacheStatInfo) == 0 ) {
+			if ( ::stat(MACOSX_DYLD_SHARED_CACHE_DIR DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME, &dyldCacheStatInfo) == 0 ) {
 				struct timeval bootTimeValue;
 				size_t bootTimeValueSize = sizeof(bootTimeValue);
 				if ( (sysctlbyname("kern.boottime", &bootTimeValue, &bootTimeValueSize, NULL, 0) == 0) && (bootTimeValue.tv_sec != 0) ) {
@@ -3424,19 +2946,12 @@
 			uint8_t firstPages[8192];
 			if ( ::read(fd, firstPages, 8192) == 8192 ) {
 				dyld_cache_header* header = (dyld_cache_header*)firstPages;
-		#if __x86_64__
-				const char* magic = (sHaswell ? ARCH_CACHE_MAGIC_H : ARCH_CACHE_MAGIC);
-		#else
-				const char* magic = ARCH_CACHE_MAGIC;
-		#endif
-				if ( strcmp(header->magic, magic) == 0 ) {
+				if ( strcmp(header->magic, ARCH_CACHE_MAGIC) == 0 ) {
 					const dyld_cache_mapping_info* const fileMappingsStart = (dyld_cache_mapping_info*)&firstPages[header->mappingOffset];
 					const dyld_cache_mapping_info* const fileMappingsEnd = &fileMappingsStart[header->mappingCount];
 					shared_file_mapping_np	mappings[header->mappingCount+1]; // add room for code-sig 
 					unsigned int mappingCount = header->mappingCount;
 					int codeSignatureMappingIndex = -1;
-					int readWriteMappingIndex = -1;
-					int readOnlyMappingIndex = -1;
 					// validate that the cache file has not been truncated
 					bool goodCache = false;
 					struct stat stat_buf;
@@ -3455,15 +2970,10 @@
 								dyld::log("dyld: shared cached file is corrupt: %s" DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME "\n", sSharedCacheDir);
 								goodCache = false;
 							}
-							if ( (mappings[i].sfm_init_prot & (VM_PROT_READ|VM_PROT_WRITE)) == (VM_PROT_READ|VM_PROT_WRITE) ) {
-								readWriteMappingIndex = i;
-							}
-							if ( mappings[i].sfm_init_prot == VM_PROT_READ ) {
-								readOnlyMappingIndex = i;
-							}
 						}
+#if __IPHONE_OS_VERSION_MIN_REQUIRED	
 						// if shared cache is code signed, add a mapping for the code signature
-						uint64_t signatureSize = header->codeSignatureSize;
+						uint32_t signatureSize = header->codeSignatureSize;
 						// zero size in header means signature runs to end-of-file
 						if ( signatureSize == 0 )
 							signatureSize = stat_buf.st_size - header->codeSignatureOffset;
@@ -3471,21 +2981,18 @@
                             int linkeditMapping = mappingCount-1;
 							codeSignatureMappingIndex = mappingCount++;
 							mappings[codeSignatureMappingIndex].sfm_address		= mappings[linkeditMapping].sfm_address + mappings[linkeditMapping].sfm_size;
-#if __arm__ || __arm64__
-							mappings[codeSignatureMappingIndex].sfm_size		= (signatureSize+16383) & (-16384);
-#else
 							mappings[codeSignatureMappingIndex].sfm_size		= (signatureSize+4095) & (-4096);
-#endif
 							mappings[codeSignatureMappingIndex].sfm_file_offset	= header->codeSignatureOffset;
 							mappings[codeSignatureMappingIndex].sfm_max_prot	= VM_PROT_READ;
 							mappings[codeSignatureMappingIndex].sfm_init_prot	= VM_PROT_READ;
 						}
+#endif
 					}
 #if __MAC_OS_X_VERSION_MIN_REQUIRED	
 					// sanity check that /usr/lib/libSystem.B.dylib stat() info matches cache
 					if ( header->imagesCount * sizeof(dyld_cache_image_info) + header->imagesOffset < 8192 ) {
 						bool foundLibSystem = false;
-						if ( my_stat("/usr/lib/libSystem.B.dylib", &stat_buf) == 0 ) {
+						if ( stat("/usr/lib/libSystem.B.dylib", &stat_buf) == 0 ) {
 							const dyld_cache_image_info* images = (dyld_cache_image_info*)&firstPages[header->imagesOffset];
 							const dyld_cache_image_info* const imagesEnd = &images[header->imagesCount];
 							for (const dyld_cache_image_info* p = images; p < imagesEnd; ++p) {
@@ -3501,29 +3008,12 @@
 							goodCache = false;
 						}
 					}
-#endif
-#if __IPHONE_OS_VERSION_MIN_REQUIRED
-					{
-						uint64_t lowAddress;
-						uint64_t highAddress;
-						getCacheBounds(mappingCount, mappings, lowAddress, highAddress);
-						if ( (highAddress-lowAddress) > SHARED_REGION_SIZE ) 
-							throw "dyld shared cache is too big to fit in shared region";
-					}
-#endif
-
-					if ( goodCache && (readWriteMappingIndex == -1) ) {
-						dyld::log("dyld: shared cached file is missing read/write mapping: %s" DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME "\n", sSharedCacheDir);
-						goodCache = false;
-					}
-					if ( goodCache && (readOnlyMappingIndex == -1) ) {
-						dyld::log("dyld: shared cached file is missing read-only mapping: %s" DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME "\n", sSharedCacheDir);
-						goodCache = false;
-					}
+#endif										
 					if ( goodCache ) {
 						long cacheSlide = 0;
 						void* slideInfo = NULL;
-						uint64_t slideInfoSize = 0;
+						uint32_t slideInfoSize = 0;
+					#if SLIDEABLE_CACHE_SUPPORT
 						// check if shared cache contains slid info
 						if ( header->slideInfoSize != 0 ) {
 							// <rdar://problem/8611968> don't slide shared cache if ASLR disabled (main executable didn't slide)
@@ -3532,34 +3022,22 @@
 							else {
 								// generate random slide amount
 								cacheSlide = pickCacheSlide(mappingCount, mappings);
-								slideInfo = (void*)(long)(mappings[readOnlyMappingIndex].sfm_address + (header->slideInfoOffset - mappings[readOnlyMappingIndex].sfm_file_offset));
+								slideInfo = (void*)(long)(mappings[2].sfm_address + (header->slideInfoOffset - mappings[2].sfm_file_offset));
 								slideInfoSize = header->slideInfoSize;
 								// add VM_PROT_SLIDE bit to __DATA area of cache
-								mappings[readWriteMappingIndex].sfm_max_prot  |= VM_PROT_SLIDE;
-								mappings[readWriteMappingIndex].sfm_init_prot |= VM_PROT_SLIDE;
+								mappings[1].sfm_max_prot  |= VM_PROT_SLIDE;
+								mappings[1].sfm_init_prot |= VM_PROT_SLIDE;
 							}
 						}
-						if ( gLinkContext.verboseMapping ) {
-							dyld::log("dyld: calling _shared_region_map_and_slide_np() with regions:\n");
-							for (int i=0; i < mappingCount; ++i) {
-								dyld::log("   address=0x%08llX, size=0x%08llX, fileOffset=0x%08llX\n", mappings[i].sfm_address, mappings[i].sfm_size, mappings[i].sfm_file_offset);
-							}
-						}
+					#endif
 						if (_shared_region_map_and_slide_np(fd, mappingCount, mappings, codeSignatureMappingIndex, cacheSlide, slideInfo, slideInfoSize) == 0) {
 							// successfully mapped cache into shared region
 							sSharedCache = (dyld_cache_header*)mappings[0].sfm_address;
 							sSharedCacheSlide = cacheSlide;
-							dyld::gProcessInfo->sharedCacheSlide = cacheSlide;
+							dyld_all_image_infos.sharedCacheSlide = cacheSlide;
 							//dyld::log("sSharedCache=%p sSharedCacheSlide=0x%08lX\n", sSharedCache, sSharedCacheSlide);
-							// if cache has a uuid, copy it
-							if ( header->mappingOffset >= 0x68 ) {
-								memcpy(dyld::gProcessInfo->sharedCacheUUID, header->uuid, 16);
-							}
 						}
 						else {
-#if __IPHONE_OS_VERSION_MIN_REQUIRED
-							throw "dyld shared cache could not be mapped";
-#endif
 							if ( gLinkContext.verboseMapping ) 
 								dyld::log("dyld: shared cached file could not be mapped\n");
 						}
@@ -3594,6 +3072,12 @@
 		// only room to tell gdb about first four regions
 		if ( dyld_shared_cache_ranges.sharedRegionsCount > 4 )
 			dyld_shared_cache_ranges.sharedRegionsCount = 4;
+		if ( gLinkContext.verboseMapping ) {
+			if ( gLinkContext.sharedRegionMode == ImageLoader::kUseSharedRegion )
+				dyld::log("dyld: Mapping shared cache from %s/" DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME "\n", sSharedCacheDir);
+			else if ( gLinkContext.sharedRegionMode == ImageLoader::kUsePrivateSharedRegion )
+				dyld::log("dyld: Mapping private shared cache from %s/" DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME "\n", sSharedCacheDir);
+		}
 		const dyld_cache_mapping_info* const end = &start[dyld_shared_cache_ranges.sharedRegionsCount];
 		int index = 0;
 		for (const dyld_cache_mapping_info* p = start; p < end; ++p, ++index ) {
@@ -3622,15 +3106,15 @@
 			}
 		#endif
 		}
+#if __IPHONE_OS_VERSION_MIN_REQUIRED	
 		if ( gLinkContext.verboseMapping ) {
 			// list the code blob
 			dyld_cache_header* header = (dyld_cache_header*)sSharedCache;
-			uint64_t signatureSize = header->codeSignatureSize;
+			uint32_t signatureSize = header->codeSignatureSize;
 			// zero size in header means signature runs to end-of-file
 			if ( signatureSize == 0 ) {
 				struct stat stat_buf;
-				// FIXME: need size of cache file actually used
-				if ( my_stat(IPHONE_DYLD_SHARED_CACHE_DIR DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME, &stat_buf) == 0 )
+				if ( ::stat(IPHONE_DYLD_SHARED_CACHE_DIR DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME, &stat_buf) == 0 ) 
 					signatureSize = stat_buf.st_size - header->codeSignatureOffset;
 			}
 			if ( signatureSize != 0 ) {
@@ -3639,14 +3123,11 @@
 				dyld::log("        0x%08llX->0x%08llX (code signature)\n", codeBlobStart, codeBlobStart+signatureSize);
 			}
 		}
-#if __IPHONE_OS_VERSION_MIN_REQUIRED
 		// check for file that enables dyld shared cache dylibs to be overridden
 		struct stat enableStatBuf;
-		// check file size to determine if correct file is in place. 
-		// See <rdar://problem/13591370> Need a way to disable roots without removing /S/L/C/com.apple.dyld/enable...
-		sDylibsOverrideCache = ( (my_stat(IPHONE_DYLD_SHARED_CACHE_DIR "enable-dylibs-to-override-cache", &enableStatBuf) == 0)
-									&& (enableStatBuf.st_size < ENABLE_DYLIBS_TO_OVERRIDE_CACHE_SIZE) );
-#endif	
+		sDylibsOverrideCache = ( ::stat(IPHONE_DYLD_SHARED_CACHE_DIR "enable-dylibs-to-override-cache", &enableStatBuf) == 0 );
+#endif		
+
 	}
 }
 #endif // #if DYLD_SHARED_CACHE_SUPPORT
@@ -3735,9 +3216,6 @@
 
 void registerRemoveCallback(ImageCallback func)
 {
-	// <rdar://problem/15025198> ignore calls to register a notification during a notification
-	if ( sRemoveImageCallbacksInUse )
-		return;
 	sRemoveImageCallbacks.push_back(func);
 }
 
@@ -3772,10 +3250,10 @@
 static void setErrorStrings(unsigned errorCode, const char* errorClientOfDylibPath,
 								const char* errorTargetDylibPath, const char* errorSymbol)
 {
-	dyld::gProcessInfo->errorKind = errorCode;
-	dyld::gProcessInfo->errorClientOfDylibPath = errorClientOfDylibPath;
-	dyld::gProcessInfo->errorTargetDylibPath = errorTargetDylibPath;
-	dyld::gProcessInfo->errorSymbol = errorSymbol;
+	dyld_all_image_infos.errorKind = errorCode;
+	dyld_all_image_infos.errorClientOfDylibPath = errorClientOfDylibPath;
+	dyld_all_image_infos.errorTargetDylibPath = errorTargetDylibPath;
+	dyld_all_image_infos.errorSymbol = errorSymbol;
 }
 
 
@@ -3834,7 +3312,7 @@
 	
 	// bind lazy pointer and return it
 	try {
-		result = (*imageLoaderCache)->doBindFastLazySymbol((uint32_t)lazyBindingInfoOffset, gLinkContext, 
+		result = (*imageLoaderCache)->doBindFastLazySymbol(lazyBindingInfoOffset, gLinkContext, 
 								(dyld::gLibSystemHelpers != NULL) ? dyld::gLibSystemHelpers->acquireGlobalDyldLock : NULL,
 								(dyld::gLibSystemHelpers != NULL) ? dyld::gLibSystemHelpers->releaseGlobalDyldLock : NULL);
 	}
@@ -3866,8 +3344,8 @@
 	// search all images in order
 	const ImageLoader* firstWeakImage = NULL;
 	const ImageLoader::Symbol* firstWeakSym = NULL;
-	const size_t imageCount = sAllImages.size();
-	for(size_t i=0; i < imageCount; ++i) {
+	const unsigned int imageCount = sAllImages.size();
+	for(unsigned int i=0; i < imageCount; ++i) {
 		ImageLoader* anImage = sAllImages[i];
 		// the use of inserted libraries alters search order
 		// so that inserted libraries are found before the main executable
@@ -3918,8 +3396,8 @@
 bool flatFindExportedSymbolWithHint(const char* name, const char* librarySubstring, const ImageLoader::Symbol** sym, const ImageLoader** image)
 {
 	// search all images in order
-	const size_t imageCount = sAllImages.size();
-	for(size_t i=0; i < imageCount; ++i){
+	const unsigned int imageCount = sAllImages.size();
+	for(unsigned int i=0; i < imageCount; ++i){
 		ImageLoader* anImage = sAllImages[i];
 		// only look at images whose paths contain the hint string (NULL hint string is wildcard)
 		if ( ! anImage->isBundle() && ((librarySubstring==NULL) || (strstr(anImage->getPath(), librarySubstring) != NULL)) ) {
@@ -3965,19 +3443,14 @@
 	// add to list of handlers
 	std::vector<dyld_image_state_change_handler>* handlers = stateToHandlers(state, sSingleHandlers);
 	if ( handlers != NULL ) {
-        // <rdar://problem/10332417> need updateAllImages() to be last in dyld_image_state_mapped list
-        // so that if ObjC adds a handler that prevents a load, it happens before the gdb list is updated
-        if ( state == dyld_image_state_mapped )
-            handlers->insert(handlers->begin(), handler);
-        else
-            handlers->push_back(handler);
+		handlers->push_back(handler);
 
 		// call callback with all existing images
 		for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
 			ImageLoader* image = *it;
 			dyld_image_info	 info;
 			info.imageLoadAddress	= image->machHeader();
-			info.imageFilePath		= image->getRealPath();
+			info.imageFilePath		= image->getPath();
 			info.imageFileModDate	= image->lastModified();
 			// should only call handler if state == image->state
 			if ( image->getState() == state )
@@ -4052,7 +3525,6 @@
 	gLinkContext.removeImage			= &removeImage;
 	gLinkContext.registerDOFs			= &registerDOFs;
 	gLinkContext.clearAllDepths			= &clearAllDepths;
-	gLinkContext.printAllDepths			= &printAllDepths;
 	gLinkContext.imageCount				= &imageCount;
 	gLinkContext.setNewProgramVars		= &setNewProgramVars;
 #if DYLD_SHARED_CACHE_SUPPORT
@@ -4062,8 +3534,6 @@
 #if SUPPORT_OLD_CRT_INITIALIZATION
 	gLinkContext.setRunInitialzersOldWay= &setRunInitialzersOldWay;
 #endif
-	gLinkContext.findImageContainingAddress	= &findImageContainingAddress;
-	gLinkContext.addDynamicReference	= &addDynamicReference;
 	gLinkContext.bindingOptions			= ImageLoader::kBindingNone;
 	gLinkContext.argc					= argc;
 	gLinkContext.argv					= argv;
@@ -4077,16 +3547,35 @@
 	gLinkContext.programVars.__prognamePtr=&gLinkContext.progname;
 	gLinkContext.mainExecutable			= NULL;
 	gLinkContext.imageSuffix			= NULL;
-	gLinkContext.dynamicInterposeArray	= NULL;
-	gLinkContext.dynamicInterposeCount	= 0;
 	gLinkContext.prebindUsage			= ImageLoader::kUseAllPrebinding;
-#if TARGET_IPHONE_SIMULATOR
-	gLinkContext.sharedRegionMode		= ImageLoader::kDontUseSharedRegion;
+	gLinkContext.sharedRegionMode		= ImageLoader::kUseSharedRegion;
+}
+
+#if __ppc__ || __i386__
+bool isRosetta()
+{
+	int mib[] = { CTL_KERN, KERN_CLASSIC, getpid() };
+	int is_classic = 0;
+	size_t len = sizeof(int);
+	int ret = sysctl(mib, 3, &is_classic, &len, NULL, 0);
+	if ((ret != -1) && is_classic) {
+		// we're running under Rosetta 
+		return true;
+	}
+	return false;
+}
+#endif
+
+
+#if __LP64__
+	#define LC_SEGMENT_COMMAND		LC_SEGMENT_64
+	#define macho_segment_command	segment_command_64
+	#define macho_section			section_64
 #else
-	gLinkContext.sharedRegionMode		= ImageLoader::kUseSharedRegion;
-#endif
-}
-
+	#define LC_SEGMENT_COMMAND		LC_SEGMENT
+	#define macho_segment_command	segment_command
+	#define macho_section			section
+#endif
 
 
 //
@@ -4124,17 +3613,19 @@
 }
 
 
-#if SUPPORT_VERSIONED_PATHS
-
-static bool readFirstPage(const char* dylibPath, uint8_t firstPage[4096]) 
-{
-	firstPage[0] = 0;
+//
+// Peeks at a dylib file and returns its current_version and install_name.
+// Returns false on error.
+//			
+static bool getDylibVersionAndInstallname(const char* dylibPath, uint32_t* version, char* installName)
+{
 	// open file (automagically closed when this function exits)
 	FileOpener file(dylibPath);
-
+	
 	if ( file.getFileDescriptor() == -1 ) 
 		return false;
 	
+	uint8_t firstPage[4096];
 	if ( pread(file.getFileDescriptor(), firstPage, 4096, 0) != 4096 )
 		return false;
 
@@ -4151,33 +3642,9 @@
 			return false;
 		}
 	}
-	
-	return true;
-}
-
-//
-// Peeks at a dylib file and returns its current_version and install_name.
-// Returns false on error.
-//
-static bool getDylibVersionAndInstallname(const char* dylibPath, uint32_t* version, char* installName)
-{
-	uint8_t firstPage[4096];
-	const macho_header* mh = (macho_header*)firstPage;
-	if ( !readFirstPage(dylibPath, firstPage) ) {
-	#if DYLD_SHARED_CACHE_SUPPORT
-		// If file cannot be read, check to see if path is in shared cache
-		const macho_header* mhInCache;
-		const char*			pathInCache;
-		long				slideInCache;
-		if ( !findInSharedCacheImage(dylibPath, true, NULL, &mhInCache, &pathInCache, &slideInCache) )
-			return false;
-		mh = mhInCache;
-	#else
-		return false;
-	#endif
-	}
 
 	// check mach-o header
+	const mach_header* mh = (mach_header*)firstPage;
 	if ( mh->magic != sMainExecutableMachHeader->magic ) 
 		return false;
 	if ( mh->cputype != sMainExecutableMachHeader->cputype )
@@ -4207,9 +3674,7 @@
 	
 	return false;
 }
-#endif // SUPPORT_VERSIONED_PATHS
-						
-
+								
 #if 0
 static void printAllImages()
 {
@@ -4217,13 +3682,13 @@
 	for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
 		ImageLoader* image = *it;
 		dyld_image_states imageState = image->getState();
-		dyld::log("  state=%d, dlopen-count=%d, never-unload=%d, in-use=%d, name=%s\n",
-				  imageState, image->dlopenCount(), image->neverUnload(), image->isMarkedInUse(), image->getShortName());
-	}
-}
-#endif
-
-void link(ImageLoader* image, bool forceLazysBound, bool neverUnload, const ImageLoader::RPathChain& loaderRPaths)
+		dyld::log("  state=%d, refcount=%d, name=%s\n", imageState, image->referenceCount(), image->getShortName());
+		image->printReferenceCounts();
+	}
+}
+#endif
+
+void link(ImageLoader* image, bool forceLazysBound, const ImageLoader::RPathChain& loaderRPaths)
 {
 	// add to list of known images.  This did not happen at creation time for bundles
 	if ( image->isBundle() && !image->isLinked() )
@@ -4235,7 +3700,7 @@
 	
 	// process images
 	try {
-		image->link(gLinkContext, forceLazysBound, false, neverUnload, loaderRPaths);
+		image->link(gLinkContext, forceLazysBound, false, loaderRPaths);
 	}
 	catch (const char* msg) {
 		garbageCollectImages();
@@ -4252,117 +3717,30 @@
 	image->runInitializers(gLinkContext, initializerTimes[0]);
 }
 
-// This function is called at the end of dlclose() when the reference count goes to zero.
-// The dylib being unloaded may have brought in other dependent dylibs when it was loaded.
-// Those dependent dylibs need to be unloaded, but only if they are not referenced by
-// something else.  We use a standard mark and sweep garbage collection.
-//
-// The tricky part is that when a dylib is unloaded it may have a termination function that
-// can run and itself call dlclose() on yet another dylib.  The problem is that this
-// sort of gabage collection is not re-entrant.  Instead a terminator's call to dlclose()
-// which calls garbageCollectImages() will just set a flag to re-do the garbage collection
-// when the current pass is done.
-//
-// Also note that this is done within the dyld global lock, so it is always single threaded.
-//
 void garbageCollectImages()
 {
-	static bool sDoingGC = false;
-	static bool sRedo = false;
-
-	if ( sDoingGC ) {
-		// GC is currently being run, just set a flag to have it run again.
-		sRedo = true;
-		return;
-	}
-	
-	sDoingGC = true;
-	do {
-		sRedo = false;
-		
-		// mark phase: mark all images not-in-use
+	// keep scanning list of images until entire list is scanned with no unreferenced images
+	bool mightBeUnreferencedImages = true;
+	while ( mightBeUnreferencedImages ) {
+		mightBeUnreferencedImages = false;
 		for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
 			ImageLoader* image = *it;
-			//dyld::log("gc: neverUnload=%d name=%s\n", image->neverUnload(), image->getShortName());
-			image->markNotUsed();
-		}
-		
-		// sweep phase: mark as in-use, images reachable from never-unload or in-use image
-		for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
-			ImageLoader* image = *it;
-			if ( (image->dlopenCount() != 0) || image->neverUnload() ) {
-				OSSpinLockLock(&sDynamicReferencesLock);
-					image->markedUsedRecursive(sDynamicReferences);
-				OSSpinLockUnlock(&sDynamicReferencesLock);
-			}
-		}
-
-		// collect phase: build array of images not marked in-use
-		ImageLoader* deadImages[sAllImages.size()];
-		unsigned deadCount = 0;
-		int maxRangeCount = 0;
-		unsigned i = 0;
-		for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
-			ImageLoader* image = *it;
-			if ( ! image->isMarkedInUse() ) {
-				deadImages[i++] = image;
-				if (gLogAPIs) dyld::log("dlclose(), found unused image %p %s\n", image, image->getShortName());
-				++deadCount;
-				maxRangeCount += image->segmentCount();
-			}
-		}
-
-		// collect phase: run termination routines for images not marked in-use
-		__cxa_range_t ranges[maxRangeCount];
-		int rangeCount = 0;
-		for (unsigned i=0; i < deadCount; ++i) {
-			ImageLoader* image = deadImages[i];
-			for (unsigned int j=0; j < image->segmentCount(); ++j) {
-				if ( !image->segExecutable(j) )
-					continue;
-				if ( rangeCount < maxRangeCount ) {
-					ranges[rangeCount].addr = (const void*)image->segActualLoadAddress(j);
-					ranges[rangeCount].length = image->segSize(j);
-					++rangeCount;
+			if ( (image->referenceCount() == 0) && !image->neverUnload() && !image->isBeingRemoved() ) {
+				try {
+					//dyld::log("garbageCollectImages: deleting %s\n", image->getPath());
+					image->setBeingRemoved();
+					removeImage(image);
+					ImageLoader::deleteImage(image);
 				}
-			}
-			try {
-				runImageStaticTerminators(image);
-			}
-			catch (const char* msg) {
-				dyld::warn("problem running terminators for image: %s\n", msg);
-			}
-		}
-		
-		// <rdar://problem/14718598> dyld should call __cxa_finalize_ranges()
-		if ( (rangeCount > 0) && (gLibSystemHelpers != NULL) && (gLibSystemHelpers->version >= 13) )
-			(*gLibSystemHelpers->cxa_finalize_ranges)(ranges, rangeCount);
-
-		// collect phase: delete all images which are not marked in-use
-		bool mightBeMore;
-		do {
-			mightBeMore = false;
-			for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
-				ImageLoader* image = *it;
-				if ( ! image->isMarkedInUse() ) {
-					try {
-						if (gLogAPIs) dyld::log("dlclose(), deleting %p %s\n", image, image->getShortName());
-						removeImage(image);
-						ImageLoader::deleteImage(image);
-						mightBeMore = true;
-						break;  // interator in invalidated by this removal
-					}
-					catch (const char* msg) {
-						dyld::warn("problem deleting image: %s\n", msg);
-					}
+				catch (const char* msg) {
+					dyld::warn("problem deleting image: %s\n", msg);
 				}
-			}
-		} while ( mightBeMore );
-	} while (sRedo);
-	sDoingGC = false;
-
+				mightBeUnreferencedImages = true;
+				break;
+			}
+		}
+	}
 	//printAllImages();
-
 }
 
 
@@ -4382,7 +3760,7 @@
 	try {
 		if ( image->isBundle() ) 
 			sBundleBeingLoaded = image;	// hack
-		image->link(gLinkContext, false, true, false, loaderRPaths);
+		image->link(gLinkContext, false, true, loaderRPaths);
 	}
 	catch (const char* msg) {	
 		preflight_finally(image);
@@ -4408,334 +3786,38 @@
 		context.origin				= NULL;	// can't use @loader_path with DYLD_INSERT_LIBRARIES
 		context.rpath				= NULL;
 		image = load(path, context);
-	}
-	catch (const char* msg) {
-#if TARGET_IPHONE_SIMULATOR
-		dyld::log("dyld: warning: could not load inserted library '%s' because %s\n", path, msg);
-#else
-		if ( sProcessRequiresLibraryValidation )
-			dyld::log("dyld: warning: could not load inserted library '%s' into library validated process because %s\n", path, msg);
-		else
-			halt(dyld::mkstringf("could not load inserted library '%s' because %s\n", path, msg));
-#endif
+		image->setNeverUnload();
 	}
 	catch (...) {
-		halt(dyld::mkstringf("could not load inserted library '%s'\n", path));
-	}
-}
-
-static bool processRestricted(const macho_header* mainExecutableMH, bool* ignoreEnvVars, bool* processRequiresLibraryValidation)
-{	
-#if TARGET_IPHONE_SIMULATOR
-	gLinkContext.codeSigningEnforced = true;
-#else
+		halt(dyld::mkstringf("could not load inserted library: %s\n", path));
+	}
+}
+
+static bool processRestricted(const macho_header* mainExecutableMH)
+{
+    // all processes with setuid or setgid bit set are restricted
+    if ( issetugid() )
+        return true;
+        
+	if ( hasRestrictedSegment(mainExecutableMH) && (geteuid() != 0) ) {
+		// existence of __RESTRICT/__restrict section make process restricted
+		return true;
+	}
+    
+#if __MAC_OS_X_VERSION_MIN_REQUIRED    
     // ask kernel if code signature of program makes it restricted
     uint32_t flags;
-	if ( csops(0, CS_OPS_STATUS, &flags, sizeof(flags)) != -1 ) {
-		if (flags & CS_REQUIRE_LV)
-			*processRequiresLibraryValidation = true;
-
-  #if __MAC_OS_X_VERSION_MIN_REQUIRED
-		if ( flags & CS_ENFORCEMENT ) {
-			gLinkContext.codeSigningEnforced = true;
-		}
-		if ( ((flags & CS_RESTRICT) == CS_RESTRICT) && (csr_check(CSR_ALLOW_TASK_FOR_PID) != 0) ) {
-			sRestrictedReason = restrictedByEntitlements;
-			return true;
-		}
-  #else
-		if ((flags & CS_ENFORCEMENT) && !(flags & CS_GET_TASK_ALLOW)) {
-			*ignoreEnvVars = true;
-		}
-		gLinkContext.codeSigningEnforced = true;
-  #endif
-	}
-#endif
-
-	// all processes with setuid or setgid bit set are restricted
-    if ( issetugid() ) {
-		sRestrictedReason = restrictedBySetGUid;
-		return true;
-	}
-		
-	// <rdar://problem/13158444&13245742> Respect __RESTRICT,__restrict section for root processes
-	if ( hasRestrictedSegment(mainExecutableMH) ) {
-		// existence of __RESTRICT/__restrict section make process restricted
-		sRestrictedReason = restrictedBySegment;
-		return true;
-	}
+    if ( syscall(SYS_csops /* 169 */,
+                0 /* asking about myself */,
+                CS_OPS_STATUS,
+                &flags,
+                sizeof(flags)) != -1) {
+        if (flags & CS_RESTRICT)
+            return true;
+    }
+#endif
     return false;
 }
-
-
-bool processIsRestricted()
-{
-	return sProcessIsRestricted;
-}
-
-
-// <rdar://problem/10583252> Add dyld to uuidArray to enable symbolication of stackshots
-static void addDyldImageToUUIDList()
-{
-	const struct macho_header* mh = (macho_header*)&__dso_handle;
-	const uint32_t cmd_count = mh->ncmds;
-	const struct load_command* const cmds = (struct load_command*)((char*)mh + sizeof(macho_header));
-	const struct load_command* cmd = cmds;
-	for (uint32_t i = 0; i < cmd_count; ++i) {
-		switch (cmd->cmd) {
-			case LC_UUID: {
-				uuid_command* uc = (uuid_command*)cmd;
-				dyld_uuid_info info;
-				info.imageLoadAddress = (mach_header*)mh;
-				memcpy(info.imageUUID, uc->uuid, 16);
-				addNonSharedCacheImageUUID(info);
-				return;
-			}
-		}
-		cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
-	}
-}
-
-#if __MAC_OS_X_VERSION_MIN_REQUIRED
-typedef int (*open_proc_t)(const char*, int, int);
-typedef int (*fcntl_proc_t)(int, int, void*);
-typedef int (*ioctl_proc_t)(int, unsigned long, void*);
-static void* getProcessInfo() { return dyld::gProcessInfo; }
-static SyscallHelpers sSysCalls = {
-		4,
-		// added in version 1
-		(open_proc_t)&open, 
-		&close, 
-		&pread, 
-		&write, 
-		&mmap, 
-		&munmap, 
-		&madvise,
-		&stat, 
-		(fcntl_proc_t)&fcntl, 
-		(ioctl_proc_t)&ioctl, 
-		&issetugid, 
-		&getcwd, 
-		&realpath, 
-		&vm_allocate, 
-		&vm_deallocate,
-		&vm_protect,
-		&vlog, 
-		&vwarn, 
-		&pthread_mutex_lock, 
-		&pthread_mutex_unlock,
-		&mach_thread_self, 
-		&mach_port_deallocate, 
-		&task_self_trap,
-		&mach_timebase_info,
-		&OSAtomicCompareAndSwapPtrBarrier, 
-		&OSMemoryBarrier,
-		&getProcessInfo,
-		&__error,
-		&mach_absolute_time,
-		// added in version 2
-		&thread_switch,
-		// added in version 3
-		&opendir,
-		&readdir_r,
-		&closedir,
-		// added in version 4
-		&coresymbolication_load_notifier,
-		&coresymbolication_unload_notifier
-};
-
-__attribute__((noinline))
-static uintptr_t useSimulatorDyld(int fd, const macho_header* mainExecutableMH, const char* dyldPath, 
-								int argc, const char* argv[], const char* envp[], const char* apple[], uintptr_t* startGlue)
-{
-	*startGlue = 0;
-	
-	// verify simulator dyld file is owned by root
-	struct stat sb;
-	if ( fstat(fd, &sb) == -1 )
-		return 0;
-
-	// read first page of dyld file
-	uint8_t firstPage[4096];
-	if ( pread(fd, firstPage, 4096, 0) != 4096 )
-		return 0;
-	
-	// if fat file, pick matching slice
-	uint64_t fileOffset = 0;
-	uint64_t fileLength = sb.st_size;
-	const fat_header* fileStartAsFat = (fat_header*)firstPage;
-	if ( fileStartAsFat->magic == OSSwapBigToHostInt32(FAT_MAGIC) ) {
-		if ( !fatFindBest(fileStartAsFat, &fileOffset, &fileLength) ) 
-			return 0;
-		// re-read buffer from start of mach-o slice in fat file
-		if ( pread(fd, firstPage, 4096, fileOffset) != 4096 )
-			return 0;
-	}
-	else if ( !isCompatibleMachO(firstPage, dyldPath) ) {
-		return 0;
-	}
-	
-	// calculate total size of dyld segments
-	const macho_header* mh = (const macho_header*)firstPage;
-	struct macho_segment_command* lastSeg = NULL;
-	struct macho_segment_command* firstSeg = NULL;
-	uintptr_t mappingSize = 0;
-	uintptr_t preferredLoadAddress = 0;
-	const uint32_t cmd_count = mh->ncmds;
-	if ( (sizeof(macho_header) + mh->sizeofcmds) > 4096 )
-		return 0;
-	const struct load_command* const cmds = (struct load_command*)(((char*)mh)+sizeof(macho_header));
-	const struct load_command* const endCmds = (struct load_command*)(((char*)mh) + sizeof(macho_header) + mh->sizeofcmds);
-	const struct load_command* cmd = cmds;
-	for (uint32_t i = 0; i < cmd_count; ++i) {
-		uint32_t cmdLength = cmd->cmdsize;
-		if ( cmdLength < 8 )
-			return 0;
-		const struct load_command* const nextCmd = (const struct load_command*)(((char*)cmd)+cmdLength);
-		if ( (nextCmd > endCmds) || (nextCmd < cmd) )
-			return 0;
-		switch (cmd->cmd) {
-			case LC_SEGMENT_COMMAND:
-				{
-					struct macho_segment_command* seg = (struct macho_segment_command*)cmd;
-					if ( seg->vmaddr + seg->vmsize < seg->vmaddr )
-						return 0;
-					if ( seg->vmsize < seg->filesize )
-						return 0;
-					if ( lastSeg == NULL ) {
-						// first segment must be __TEXT and start at beginning of file/slice
-						firstSeg = seg;
-						if ( strcmp(seg->segname, "__TEXT") != 0 )
-							return 0;
-						if ( seg->fileoff != 0 )
-							return 0;
-						if ( seg->filesize < (sizeof(macho_header) + mh->sizeofcmds) )
-							return 0;
-						preferredLoadAddress = seg->vmaddr;
-					}
-					else {
-						// other sements must be continguous with previous segment and not executable
-						if ( lastSeg->fileoff + lastSeg->filesize != seg->fileoff )
-							return 0;
-						if ( lastSeg->vmaddr + lastSeg->vmsize != seg->vmaddr )
-							return 0;
-						if ( (seg->initprot & VM_PROT_EXECUTE) != 0 )
-							return 0;
-					}
-					mappingSize += seg->vmsize;
-					lastSeg = seg;
-				}
-				break;
-			case LC_SEGMENT_COMMAND_WRONG:
-				return 0;
-		}
-		cmd = nextCmd;
-	}
-	// last segment must be named __LINKEDIT and not writable
-	if ( strcmp(lastSeg->segname, "__LINKEDIT") != 0 )
-		return 0;
-	if ( lastSeg->initprot & VM_PROT_WRITE )
-		return 0;
-
-	// reserve space, then mmap each segment
-	vm_address_t loadAddress = 0;
-	if ( ::vm_allocate(mach_task_self(), &loadAddress, mappingSize, VM_FLAGS_ANYWHERE) != 0 )
-		return 0;
-	cmd = cmds;
-	struct linkedit_data_command* codeSigCmd = NULL;
-	struct source_version_command* dyldVersionCmd = NULL;
-	for (uint32_t i = 0; i < cmd_count; ++i) {
-		switch (cmd->cmd) {
-			case LC_SEGMENT_COMMAND:
-				{
-					struct macho_segment_command* seg = (struct macho_segment_command*)cmd;
-					uintptr_t requestedLoadAddress = seg->vmaddr - preferredLoadAddress + loadAddress;
-					void* segAddress = ::mmap((void*)requestedLoadAddress, seg->filesize, seg->initprot, MAP_FIXED | MAP_PRIVATE, fd, fileOffset + seg->fileoff);
-					//dyld::log("dyld_sim %s mapped at %p\n", seg->segname, segAddress);
-					if ( segAddress == (void*)(-1) )
-						return 0;
-					if ( ((uintptr_t)segAddress < loadAddress) || ((uintptr_t)segAddress+seg->filesize > loadAddress+mappingSize) )
-						return 0;
-				}
-				break;
-			case LC_CODE_SIGNATURE:
-				codeSigCmd = (struct linkedit_data_command*)cmd;
-				break;
-			case LC_SOURCE_VERSION:
-				dyldVersionCmd = (struct source_version_command*)cmd;
-				break;
-		}
-		cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
-	}
-
-	// must have code signature which is contained within LINKEDIT segment
-	if ( codeSigCmd == NULL )
-		return 0;
-	if ( codeSigCmd->dataoff < lastSeg->fileoff )
-		return 0;
-	if ( (codeSigCmd->dataoff + codeSigCmd->datasize) > (lastSeg->fileoff + lastSeg->filesize) )
-		return 0;
-
-	fsignatures_t siginfo;
-	siginfo.fs_file_start=fileOffset;							// start of mach-o slice in fat file 
-	siginfo.fs_blob_start=(void*)(long)(codeSigCmd->dataoff);	// start of code-signature in mach-o file
-	siginfo.fs_blob_size=codeSigCmd->datasize;					// size of code-signature
-	int result = fcntl(fd, F_ADDFILESIGS_FOR_DYLD_SIM, &siginfo);
-	if ( result == -1 ) {
-		dyld::log("fcntl(F_ADDFILESIGS_FOR_DYLD_SIM) failed with errno=%d\n", errno);
-		return 0;
-	}
-	close(fd);
-	// file range covered by code signature must extend up to code signature itself
-	if ( siginfo.fs_file_start < codeSigCmd->dataoff )
-		return 0;
-
-	// walk newly mapped dyld_sim __TEXT load commands to find entry point
-	uintptr_t entry = 0;
-	cmd = (struct load_command*)(((char*)loadAddress)+sizeof(macho_header));
-	const uint32_t count = ((macho_header*)(loadAddress))->ncmds;
-	for (uint32_t i = 0; i < count; ++i) {
-		if (cmd->cmd == LC_UNIXTHREAD) {
-		#if __i386__
-			const i386_thread_state_t* registers = (i386_thread_state_t*)(((char*)cmd) + 16);
-			// entry point must be in first segment
-			if ( registers->__eip < firstSeg->vmaddr )
-				return 0;
-			if ( registers->__eip > (firstSeg->vmaddr + firstSeg->vmsize) )
-				return 0;
-			entry = (registers->__eip + loadAddress - preferredLoadAddress);
-		#elif __x86_64__
-			const x86_thread_state64_t* registers = (x86_thread_state64_t*)(((char*)cmd) + 16);
-			// entry point must be in first segment
-			if ( registers->__rip < firstSeg->vmaddr )
-				return 0;
-			if ( registers->__rip > (firstSeg->vmaddr + firstSeg->vmsize) )
-				return 0;
-			entry = (registers->__rip + loadAddress - preferredLoadAddress);
-		#endif
-		}
-		cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
-	}
-
-	// notify debugger that dyld_sim is loaded
-	dyld_image_info info;
-	info.imageLoadAddress = (mach_header*)loadAddress;
-	info.imageFilePath	  = strdup(dyldPath);
-	info.imageFileModDate = sb.st_mtime;
-	addImagesToAllImages(1, &info);
-	dyld::gProcessInfo->notification(dyld_image_adding, 1, &info);
-
-	const char** appleParams = apple;
-	// jump into new simulator dyld
-	typedef uintptr_t (*sim_entry_proc_t)(int argc, const char* argv[], const char* envp[], const char* apple[],
-								const macho_header* mainExecutableMH, const macho_header* dyldMH, uintptr_t dyldSlide,
-								const dyld::SyscallHelpers* vtable, uintptr_t* startGlue);
-	sim_entry_proc_t newDyld = (sim_entry_proc_t)entry;
-	return (*newDyld)(argc, argv, envp, appleParams, mainExecutableMH, (macho_header*)loadAddress,
-					 loadAddress - preferredLoadAddress, 
-					 &sSysCalls, startGlue);
-}
-#endif
 
 
 //
@@ -4745,31 +3827,16 @@
 // Returns address of main() in target program which __dyld_start jumps to
 //
 uintptr_t
-_main(const macho_header* mainExecutableMH, uintptr_t mainExecutableSlide, 
-		int argc, const char* argv[], const char* envp[], const char* apple[], 
-		uintptr_t* startGlue)
-{
-	uintptr_t result = 0;
-	sMainExecutableMachHeader = mainExecutableMH;
-#if __MAC_OS_X_VERSION_MIN_REQUIRED
-	// if this is host dyld, check to see if iOS simulator is being run
-	const char* rootPath = _simple_getenv(envp, "DYLD_ROOT_PATH");
-	if ( rootPath != NULL ) {
-		// look to see if simulator has its own dyld
-		char simDyldPath[PATH_MAX]; 
-		strlcpy(simDyldPath, rootPath, PATH_MAX);
-		strlcat(simDyldPath, "/usr/lib/dyld_sim", PATH_MAX);
-		int fd = my_open(simDyldPath, O_RDONLY, 0);
-		if ( fd != -1 ) {
-			result = useSimulatorDyld(fd, mainExecutableMH, simDyldPath, argc, argv, envp, apple, startGlue);
-			if ( !result && (*startGlue == 0) )
-				halt("problem loading iOS simulator dyld");
-			return result;
-		}
-	}
-#endif
-
+_main(const macho_header* mainExecutableMH, uintptr_t mainExecutableSlide, int argc, const char* argv[], const char* envp[], const char* apple[])
+{	
 	CRSetCrashLogMessage("dyld: launch started");
+#ifdef ALTERNATIVE_LOGFILE
+	sLogfile = open(ALTERNATIVE_LOGFILE, O_WRONLY | O_CREAT | O_APPEND);
+	if ( sLogfile == -1 ) {
+		sLogfile = STDERR_FILENO;
+		dyld::log("error opening alternate log file %s, errno = %d\n", ALTERNATIVE_LOGFILE, errno);
+	}
+#endif
 
 #if LOG_BINDINGS
 	char bindingsLogPath[256];
@@ -4793,12 +3860,18 @@
 	setContext(mainExecutableMH, argc, argv, envp, apple);
 
 	// Pickup the pointer to the exec path.
-	sExecPath = _simple_getenv(apple, "executable_path");
-
-	// <rdar://problem/13868260> Remove interim apple[0] transition code from dyld
-	if (!sExecPath) sExecPath = apple[0];
-	
+	sExecPath = apple[0];
 	bool ignoreEnvironmentVariables = false;
+#if __i386__
+	if ( isRosetta() ) {
+		// under Rosetta (x86 side)
+		// When a 32-bit ppc program is run under emulation on an Intel processor,
+		// we want any i386 dylibs (e.g. any used by Rosetta) to not load in the shared region
+		// because the shared region is being used by ppc dylibs
+		gLinkContext.sharedRegionMode = ImageLoader::kDontUseSharedRegion;
+		ignoreEnvironmentVariables = true;
+	}
+#endif
 	if ( sExecPath[0] != '/' ) {
 		// have relative path, use cwd to make absolute
 		char cwdbuff[MAXPATHLEN];
@@ -4811,31 +3884,27 @@
 			sExecPath = s;
 		}
 	}
-	// Remember short name of process for later logging
-	sExecShortName = ::strrchr(sExecPath, '/');
-	if ( sExecShortName != NULL )
-		++sExecShortName;
-	else
-		sExecShortName = sExecPath;
-    sProcessIsRestricted = processRestricted(mainExecutableMH, &ignoreEnvironmentVariables, &sProcessRequiresLibraryValidation);
+	uintptr_t result = 0;
+	sMainExecutableMachHeader = mainExecutableMH;
+    sProcessIsRestricted = processRestricted(mainExecutableMH);
     if ( sProcessIsRestricted ) {
 #if SUPPORT_LC_DYLD_ENVIRONMENT
 		checkLoadCommandEnvironmentVariables();
+#if SUPPORT_VERSIONED_PATHS
+		checkVersionedPaths();
+#endif	
 #endif 	
 		pruneEnvironmentVariables(envp, &apple);
 		// set again because envp and apple may have changed or moved
 		setContext(mainExecutableMH, argc, argv, envp, apple);
 	}
-	else {
-		if ( !ignoreEnvironmentVariables )
-			checkEnvironmentVariables(envp);
-		defaultUninitializedFallbackPaths(envp);
-	}
-	if ( sEnv.DYLD_PRINT_OPTS )
+	else
+		checkEnvironmentVariables(envp, ignoreEnvironmentVariables);
+	if ( sEnv.DYLD_PRINT_OPTS ) 
 		printOptions(argv);
 	if ( sEnv.DYLD_PRINT_ENV ) 
 		printEnvironmentVariables(envp);
-	getHostInfo(mainExecutableMH, mainExecutableSlide);
+	getHostInfo();
 	// install gdb notifier
 	stateToHandlers(dyld_image_state_dependents_mapped, sBatchHandlers)->push_back(notifyGDB);
 	stateToHandlers(dyld_image_state_mapped, sSingleHandlers)->push_back(updateAllImages);
@@ -4849,55 +3918,22 @@
 	
 #ifdef WAIT_FOR_SYSTEM_ORDER_HANDSHAKE
 	// <rdar://problem/6849505> Add gating mechanism to dyld support system order file generation process
-	WAIT_FOR_SYSTEM_ORDER_HANDSHAKE(dyld::gProcessInfo->systemOrderFlag);
-#endif
-	
-
+	WAIT_FOR_SYSTEM_ORDER_HANDSHAKE(dyld_all_image_infos.systemOrderFlag);
+#endif
+	
 	try {
-		// add dyld itself to UUID list
-		addDyldImageToUUIDList();
-		CRSetCrashLogMessage(sLoadingCrashMessage);
+		CRSetCrashLogMessage("dyld: launch, loading dependent libraries");
 		// instantiate ImageLoader for main executable
 		sMainExecutable = instantiateFromLoadedImage(mainExecutableMH, mainExecutableSlide, sExecPath);
+		sMainExecutable->setNeverUnload();
 		gLinkContext.mainExecutable = sMainExecutable;
 		gLinkContext.processIsRestricted = sProcessIsRestricted;
-		gLinkContext.processRequiresLibraryValidation = sProcessRequiresLibraryValidation;
-		gLinkContext.mainExecutableCodeSigned = hasCodeSignatureLoadCommand(mainExecutableMH);
-
-#if TARGET_IPHONE_SIMULATOR
-	#if TARGET_OS_WATCH || TARGET_OS_TV
-		// disable error during bring up of these simulators
-	#else
-		// check main executable is not too new for this OS
-		{
-			if ( ! isSimulatorBinary((uint8_t*)mainExecutableMH, sExecPath) ) {
-				throwf("program was built for Mac OS X and cannot be run in simulator"); 
-			}
-			uint32_t mainMinOS = sMainExecutable->minOSVersion();
-			// dyld is always built for the current OS, so we can get the current OS version
-			// from the load command in dyld itself.
-			uint32_t dyldMinOS = ImageLoaderMachO::minOSVersion((const mach_header*)&__dso_handle);
-			if ( mainMinOS > dyldMinOS ) {
-				throwf("app was built for iOS %d.%d which is newer than this simulator %d.%d", 
-						mainMinOS >> 16, ((mainMinOS >> 8) & 0xFF),
-						dyldMinOS >> 16, ((dyldMinOS >> 8) & 0xFF));
-			}
-		}
-	#endif
-#endif
-
 		// load shared cache
 		checkSharedRegionDisable();
 	#if DYLD_SHARED_CACHE_SUPPORT
 		if ( gLinkContext.sharedRegionMode != ImageLoader::kDontUseSharedRegion )
 			mapSharedCache();
 	#endif
-
-		// Now that shared cache is loaded, setup an versioned dylib overrides
-	#if SUPPORT_VERSIONED_PATHS
-		checkVersionedPaths();
-	#endif
-
 		// load any inserted libraries
 		if	( sEnv.DYLD_INSERT_LIBRARIES != NULL ) {
 			for (const char* const* lib = sEnv.DYLD_INSERT_LIBRARIES; *lib != NULL; ++lib) 
@@ -4909,12 +3945,13 @@
 
 		// link main executable
 		gLinkContext.linkingMainExecutable = true;
-		link(sMainExecutable, sEnv.DYLD_BIND_AT_LAUNCH, true, ImageLoader::RPathChain(NULL, NULL));
-		sMainExecutable->setNeverUnloadRecursive();
+		link(sMainExecutable, sEnv.DYLD_BIND_AT_LAUNCH, ImageLoader::RPathChain(NULL, NULL));
+		gLinkContext.linkingMainExecutable = false;
 		if ( sMainExecutable->forceFlat() ) {
 			gLinkContext.bindFlat = true;
 			gLinkContext.prebindUsage = ImageLoader::kUseNoPrebinding;
 		}
+		result = (uintptr_t)sMainExecutable->getMain();
 
 		// link any inserted libraries
 		// do this after linking main executable so that any dylibs pulled in by inserted 
@@ -4922,57 +3959,18 @@
 		if ( sInsertedDylibCount > 0 ) {
 			for(unsigned int i=0; i < sInsertedDylibCount; ++i) {
 				ImageLoader* image = sAllImages[i+1];
-				link(image, sEnv.DYLD_BIND_AT_LAUNCH, true, ImageLoader::RPathChain(NULL, NULL));
-				image->setNeverUnloadRecursive();
-			}
-			// only INSERTED libraries can interpose
-			// register interposing info after all inserted libraries are bound so chaining works
-			for(unsigned int i=0; i < sInsertedDylibCount; ++i) {
-				ImageLoader* image = sAllImages[i+1];
+				link(image, sEnv.DYLD_BIND_AT_LAUNCH, ImageLoader::RPathChain(NULL, NULL));
+				// only INSERTED libraries can interpose
 				image->registerInterposing();
 			}
 		}
-
-		// <rdar://problem/19315404> dyld should support interposition even without DYLD_INSERT_LIBRARIES
-		for (int i=sInsertedDylibCount+1; i < sAllImages.size(); ++i) {
-			ImageLoader* image = sAllImages[i];
-			if ( image->inSharedCache() )
-				continue;
-			image->registerInterposing();
-		}
-
-		// apply interposing to initial set of images
-		for(int i=0; i < sImageRoots.size(); ++i) {
-			sImageRoots[i]->applyInterposing(gLinkContext);
-		}
-		gLinkContext.linkingMainExecutable = false;
-		
-		// <rdar://problem/12186933> do weak binding only after all inserted images linked
-		sMainExecutable->weakBind(gLinkContext);
 		
 		CRSetCrashLogMessage("dyld: launch, running initializers");
 	#if SUPPORT_OLD_CRT_INITIALIZATION
 		// Old way is to run initializers via a callback from crt1.o
 		if ( ! gRunInitializersOldWay ) 
-			initializeMainExecutable(); 
-	#else
-		// run all initializers
-		initializeMainExecutable(); 
 	#endif
-		// find entry point for main executable
-		result = (uintptr_t)sMainExecutable->getThreadPC();
-		if ( result != 0 ) {
-			// main executable uses LC_MAIN, needs to return to glue in libdyld.dylib
-			if ( (gLibSystemHelpers != NULL) && (gLibSystemHelpers->version >= 9) )
-				*startGlue = (uintptr_t)gLibSystemHelpers->startGlueToCallExit;
-			else
-				halt("libdyld.dylib support not present for LC_MAIN");
-		}
-		else {
-			// main executable uses LC_UNIXTHREAD, dyld needs to let "start" in program set up for main()
-			result = (uintptr_t)sMainExecutable->getMain();
-			*startGlue = 0;
-		}
+		initializeMainExecutable(); // run all initializers
 	}
 	catch(const char* message) {
 		syncAllImages();
@@ -4982,6 +3980,13 @@
 		dyld::log("dyld: launch failed\n");
 	}
 
+#ifdef ALTERNATIVE_LOGFILE
+	// only use alternate log during launch, otherwise file is open forever
+	if ( sLogfile != STDERR_FILENO ) {
+		close(sLogfile);
+		sLogfile = STDERR_FILENO;
+	}
+#endif
 	CRSetCrashLogMessage(NULL);
 	
 	return result;
@@ -4989,7 +3994,8 @@
 
 
 
-} // namespace
-
-
-
+
+}; // namespace
+
+
+