Loading...
src/dyldAPIs.cpp dyld-132.13 dyld-239.3
--- dyld/dyld-132.13/src/dyldAPIs.cpp
+++ dyld/dyld-239.3/src/dyldAPIs.cpp
@@ -57,6 +57,11 @@
 #undef _POSIX_C_SOURCE
 #include "dlfcn.h"
 
+// from dyldExceptions.c
+extern "C" void __Unwind_SjLj_SetThreadKey(pthread_key_t key);
+
+// from dyld_gdb.cpp 
+extern void addImagesToAllImages(uint32_t infoCount, const dyld_image_info info[]);
 
 // deprecated APIs are still availble on Mac OS X, but not on iPhone OS
 #if __IPHONE_OS_VERSION_MIN_REQUIRED	
@@ -75,12 +80,10 @@
 // In 10.3.x and earlier all the NSObjectFileImage API's were implemeneted in libSystem.dylib
 // Beginning in 10.4 the NSObjectFileImage API's are implemented in dyld and libSystem just forwards
 // This conditional keeps support for old libSystem's which needed some help implementing the API's
-#define OLD_LIBSYSTEM_SUPPORT (__ppc__ || __i386__)
-
+#define OLD_LIBSYSTEM_SUPPORT (__i386__)
 
 // The following functions have no prototype in any header.  They are special cases
 // where _dyld_func_lookup() is used directly.
-static void _dyld_fork_child();
 static void _dyld_make_delayed_module_initializer_calls();
 static void registerThreadHelpers(const dyld::LibSystemHelpers*);
 #if DEPRECATED_APIS_SUPPORTED
@@ -97,7 +100,9 @@
 static void		client_dyld_lookup_and_bind(const char* symbolName, void** address, NSModule* module);
 static bool		client_NSIsSymbolNameDefined(const char* symbolName);
 #endif // DEPRECATED_APIS_SUPPORTED
+#if !__arm__
 static bool client_dyld_find_unwind_sections(void* addr, dyld_unwind_sections* info);
+#endif
 
 static void unimplemented()
 {
@@ -118,7 +123,6 @@
     {"__dyld_dlopen",									(void*)dlopen },
     {"__dyld_dlsym",									(void*)dlsym },
     {"__dyld_dlopen_preflight",							(void*)dlopen_preflight },
-    {"__dyld_get_image_header_containing_address",		(void*)_dyld_get_image_header_containing_address },
 	{"__dyld_image_count",								(void*)_dyld_image_count },
     {"__dyld_get_image_header",							(void*)_dyld_get_image_header },
     {"__dyld_get_image_vmaddr_slide",					(void*)_dyld_get_image_vmaddr_slide },
@@ -136,13 +140,18 @@
 #if !__arm__
 	{"__dyld_find_unwind_sections",						(void*)client_dyld_find_unwind_sections },
 #endif
-#if __i386__ || __x86_64__
+#if __i386__ || __x86_64__ || __arm__
 	{"__dyld_fast_stub_entry",							(void*)dyld::fastBindLazySymbol },
 #endif
 	{"__dyld_image_path_containing_address",			(void*)dyld_image_path_containing_address },
+#if __IPHONE_OS_VERSION_MIN_REQUIRED	
+	{"__dyld_shared_cache_some_image_overridden",		(void*)dyld_shared_cache_some_image_overridden },
+#endif
+	{"__dyld_process_is_restricted",					(void*)dyld::processIsRestricted },
 
 	// deprecated
 #if DEPRECATED_APIS_SUPPORTED
+    {"__dyld_get_image_header_containing_address",		(void*)_dyld_get_image_header_containing_address },
     {"__dyld_lookup_and_bind",						(void*)client_dyld_lookup_and_bind },
     {"__dyld_lookup_and_bind_with_hint",			(void*)_dyld_lookup_and_bind_with_hint },
     {"__dyld_lookup_and_bind_fully",				(void*)_dyld_lookup_and_bind_fully },
@@ -231,6 +240,9 @@
 	const void*		imageBaseAddress;	// not used with OFI created from files
 	size_t			imageLength;		// not used with OFI created from files
 };
+
+
+VECTOR_NEVER_DESTRUCTED(NSObjectFileImage);
 static std::vector<NSObjectFileImage> sObjectFileImages;
 
 
@@ -325,7 +337,7 @@
 		dyld::log("%s(%u)\n", __func__, image_index);
 	ImageLoader* image = dyld::getIndexedImage(image_index);
 	if ( image != NULL )
-		return image->getPath();
+		return image->getRealPath();
 	else
 		return NULL;
 }
@@ -534,7 +546,7 @@
 		if ( image != NULL ) {
 			if ( context.matchByInstallName )
 				image->setMatchInstallPath(true);
-			dyld::link(image, false, callersRPaths);
+			dyld::link(image, false, false, callersRPaths);
 			dyld::runInitializers(image);
 			// images added with NSAddImage() can never be unloaded
 			image->setNeverUnload(); 
@@ -573,7 +585,7 @@
 	const bool dontLoad = ( (options & NSADDIMAGE_OPTION_RETURN_ONLY_IF_LOADED) != 0 );
 	const bool search = ( (options & NSADDIMAGE_OPTION_WITH_SEARCHING) != 0 );
 	const bool matchInstallName = ( (options & NSADDIMAGE_OPTION_MATCH_FILENAME_BY_INSTALLNAME) != 0 );
-	const bool abortOnError = ( (options & NSADDIMAGE_OPTION_RETURN_ON_ERROR|NSADDIMAGE_OPTION_RETURN_ONLY_IF_LOADED) == 0 );
+	const bool abortOnError = ( (options & (NSADDIMAGE_OPTION_RETURN_ON_ERROR|NSADDIMAGE_OPTION_RETURN_ONLY_IF_LOADED)) == 0 );
 	void* callerAddress = __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
 	return addImage(callerAddress, path, search, dontLoad, matchInstallName, abortOnError);
 }
@@ -964,16 +976,26 @@
 	
 	dyld::clearErrorMessage();
 	try {
+		if ( (options & NSLINKMODULE_OPTION_CAN_UNLOAD) != 0 )
+			objectFileImage->image->setCanUnload();
+
 		// NSLinkModule allows a bundle to be link multpile times
 		// each link causes the bundle to be copied to a new address
 		if ( objectFileImage->image->isLinked() ) {
 			// already linked, so clone a new one and link it
 			objectFileImage->image = dyld::cloneImage(objectFileImage->image);
 		}
-			
+		
 		// for memory based images, set moduleName as the name anyone calling _dyld_get_image_name() will see
-		if ( objectFileImage->image->getPath() == NULL )
+		if ( objectFileImage->image->getPath() == NULL ) {
 			objectFileImage->image->setPath(moduleName);
+			// <rdar://problem/8812589> dyld has NULL paths in image info array
+			dyld_image_info info;
+			info.imageLoadAddress = objectFileImage->image->machHeader();
+			info.imageFilePath = moduleName;
+			info.imageFileModDate = 0;
+			addImagesToAllImages(1, &info);
+		}
 
 		// support private bundles
 		if ( (options & NSLINKMODULE_OPTION_PRIVATE) != 0 )
@@ -983,7 +1005,7 @@
 		bool forceLazysBound = ( (options & NSLINKMODULE_OPTION_BINDNOW) != 0 );
 		
 		// load libraries, rebase, bind, to make this image usable
-		dyld::link(objectFileImage->image, forceLazysBound, ImageLoader::RPathChain(NULL,NULL));
+		dyld::link(objectFileImage->image, forceLazysBound, false, ImageLoader::RPathChain(NULL,NULL));
 		
 		// bump reference count to keep this bundle from being garbage collected
 		objectFileImage->image->incrementDlopenReferenceCount();
@@ -1029,7 +1051,7 @@
 			bool forceLazysBound = ( (options & NSLINKMODULE_OPTION_BINDNOW) != 0 );
 			
 			// load libraries, rebase, bind, to make this image usable
-			dyld::link(image, forceLazysBound, ImageLoader::RPathChain(NULL,NULL));
+			dyld::link(image, forceLazysBound, false, ImageLoader::RPathChain(NULL,NULL));
 			
 			// run initializers unless magic flag says not to
 			if ( (options & NSLINKMODULE_OPTION_DONT_CALL_MOD_INIT_ROUTINES) == 0 )
@@ -1092,6 +1114,7 @@
 	ImageLoader* image = NSModuleToImageLoader(module);
 	if ( image == NULL ) 
 		return false;
+	dyld::runImageTerminators(image);
 	dyld::removeImage(image);
 	
 	if ( (options & NSUNLINKMODULE_OPTION_KEEP_MEMORY_MAPPED) != 0 )
@@ -1150,7 +1173,7 @@
 
 
 // Call by fork() in libSystem after the kernel trap is done on the child side
-static void _dyld_fork_child()
+void _dyld_fork_child()
 {
 	if ( dyld::gLogAPIs )
 		dyld::log("%s()\n", __func__);
@@ -1167,12 +1190,10 @@
 	// If dyld is sending load/unload notices to CoreSymbolication, the shared memory
 	// page is not copied on fork. <rdar://problem/6797342>
  	// NULL the CoreSymbolication shared memory pointer to prevent a crash.
- 	dyld_all_image_infos.coreSymbolicationShmPage = NULL;
+ 	dyld::gProcessInfo->coreSymbolicationShmPage = NULL;
 	// for safety, make sure child starts with clean systemOrderFlag
-	dyld_all_image_infos.systemOrderFlag = 0;
-}
-
-
+	dyld::gProcessInfo->systemOrderFlag = 0;
+}
 
 typedef void (*MonitorProc)(char *lowpc, char *highpc);
 
@@ -1243,18 +1264,36 @@
 	return false;
 }
 
+
 static void registerThreadHelpers(const dyld::LibSystemHelpers* helpers)
 {
 	dyld::gLibSystemHelpers = helpers;
 	
 	// let gdb know it is safe to run code in inferior that might call malloc()
-	dyld_all_image_infos.libSystemInitialized = true;	
+	dyld::gProcessInfo->libSystemInitialized = true;	
+	
+#if __arm__
+	if ( helpers->version >= 5 )  {
+		// create key use by dyld exception handling
+		pthread_key_t key;
+		int result = helpers->pthread_key_create(&key, NULL);
+		if ( result == 0 )
+			__Unwind_SjLj_SetThreadKey(key);
+	}
+#endif
 }
 
 
 static void dlerrorClear()
 {
 	if ( dyld::gLibSystemHelpers != NULL ) {
+		// <rdar://problem/10595338> dlerror buffer leak
+		// dlerrorClear() should not force allocation, but zero it if already allocated
+		if ( dyld::gLibSystemHelpers->version >= 10 ) {
+			if ( ! (*dyld::gLibSystemHelpers->hasPerThreadBufferFor_dlerror)() )
+				return;
+		}
+
 		// first char of buffer is flag whether string (starting at second char) is valid
 		char* buffer = (*dyld::gLibSystemHelpers->getThreadBufferFor_dlerror)(2);
 		buffer[0] = '\0';
@@ -1286,6 +1325,8 @@
 	if ( dyld::inSharedCache(path) )
 		return true;
 #endif
+	
+	CRSetCrashLogMessage("dyld: in dlopen_preflight()");
 	
 	bool result = false;
 	std::vector<const char*> rpathsFromCallerImage;
@@ -1303,6 +1344,27 @@
 		ImageLoader*	image = NULL;
 		const bool leafName = (strchr(path, '/') == NULL);
 		const bool absolutePath = (path[0] == '/');
+#if __IPHONE_OS_VERSION_MIN_REQUIRED
+		char canonicalPath[PATH_MAX]; 
+		// <rdar://problem/7017050> dlopen() not opening frameworks from shared cache with // or ./ in path
+		if ( !leafName ) {
+			// make path canonical if it contains a // or ./
+			if ( (strstr(path, "//") != NULL) || (strstr(path, "./") != NULL) ) {
+				const char* lastSlash = strrchr(path, '/');
+				char dirPath[PATH_MAX]; 
+				if ( strlcpy(dirPath, path, sizeof(dirPath)) < sizeof(dirPath) ) {
+					dirPath[lastSlash-path] = '\0';
+					if ( realpath(dirPath, canonicalPath) ) {
+						strlcat(canonicalPath, "/", sizeof(canonicalPath));
+						if ( strlcat(canonicalPath, lastSlash+1, sizeof(canonicalPath)) < sizeof(canonicalPath) ) {
+							// if all fit in buffer, use new canonical path
+							path = canonicalPath;
+						}
+					}
+				}
+			}
+		}
+#endif
 		dyld::LoadContext context;
 		context.useSearchPaths	= true;
 		context.useFallbackPaths= leafName;					// a partial path implies don't use fallback paths
@@ -1333,6 +1395,7 @@
 		const char* str = *it;
 		free((void*)str);
 	}
+	CRSetCrashLogMessage(NULL);
 	return result;
 }
 
@@ -1357,6 +1420,7 @@
 	bool lockHeld = false;
 	if ( (dyld::gLibSystemHelpers != NULL) && (dyld::gLibSystemHelpers->version >= 4) ) {
 		dyld::gLibSystemHelpers->acquireGlobalDyldLock();
+		CRSetCrashLogMessage("dyld: in dlopen()");
 		lockHeld = true;
 	}
 		
@@ -1376,6 +1440,27 @@
  
 		const bool leafName = (strchr(path, '/') == NULL);
 		const bool absolutePath = (path[0] == '/');
+#if __IPHONE_OS_VERSION_MIN_REQUIRED
+		char canonicalPath[PATH_MAX]; 
+		// <rdar://problem/7017050> dlopen() not opening frameworks from shared cache with // or ./ in path
+		if ( !leafName ) {
+			// make path canonical if it contains a // or ./
+			if ( (strstr(path, "//") != NULL) || (strstr(path, "./") != NULL) ) {
+				const char* lastSlash = strrchr(path, '/');
+				char dirPath[PATH_MAX]; 
+				if ( strlcpy(dirPath, path, sizeof(dirPath)) < sizeof(dirPath) ) {
+					dirPath[lastSlash-path] = '\0';
+					if ( realpath(dirPath, canonicalPath) ) {
+						strlcat(canonicalPath, "/", sizeof(canonicalPath));
+						if ( strlcat(canonicalPath, lastSlash+1, sizeof(canonicalPath)) < sizeof(canonicalPath) ) {
+							// if all fit in buffer, use new canonical path
+							path = canonicalPath;
+						}
+					}
+				}
+			}
+		}
+#endif
 		dyld::LoadContext context;
 		context.useSearchPaths	= true;
 		context.useFallbackPaths= leafName;				// a partial path means no fallback paths
@@ -1398,7 +1483,7 @@
 			if ( (mode & RTLD_NOLOAD) == 0 ) {
 				bool alreadyLinked = image->isLinked();
 				bool forceLazysBound = ( (mode & RTLD_NOW) != 0 );
-				dyld::link(image, forceLazysBound, callersRPaths);
+				dyld::link(image, forceLazysBound, false, callersRPaths);
 				if ( ! alreadyLinked ) {
 					// only hide exports if image is not already in use
 					if ( (mode & RTLD_LOCAL) != 0 )
@@ -1416,6 +1501,7 @@
 			
 			// release global dyld lock early, this enables initializers to do threaded operations
 			if ( lockHeld ) {
+				CRSetCrashLogMessage(NULL);
 				dyld::gLibSystemHelpers->releaseGlobalDyldLock();
 				lockHeld = false;
 			}
@@ -1443,9 +1529,12 @@
 			// load() succeeded but, link() failed
 			// back down reference count and do GC
 			image->decrementDlopenReferenceCount();
-			dyld::garbageCollectImages();
+			if ( image->dlopenCount() == 0 )
+				dyld::garbageCollectImages();
 		}
 		const char* str = dyld::mkstringf("dlopen(%s, %d): %s", path, mode, msg);
+		if ( dyld::gLogAPIs )
+			dyld::log("  %s() failed, error: '%s'\n", __func__, str);
 		dlerrorSet(str);
 		free((void*)str);
 		free((void*)msg); 	// our free() will do nothing if msg is a string literal
@@ -1462,8 +1551,12 @@
 		dlerrorSet("image not already loaded");
 	}
 	
-	if ( lockHeld ) 
+	if ( lockHeld ) {
+		CRSetCrashLogMessage(NULL);
 		dyld::gLibSystemHelpers->releaseGlobalDyldLock();
+	}
+	if ( dyld::gLogAPIs && (result != NULL) )
+		dyld::log("  %s(%s) ==> %p\n", __func__, path, result);
 	return result;
 }
 
@@ -1489,7 +1582,8 @@
 			return -1;
 		}
 		// remove image if reference count went to zero
-		dyld::garbageCollectImages();
+		if ( image->dlopenCount() == 0 )
+			dyld::garbageCollectImages();
 		return 0;
 	}
 	else {
@@ -1505,28 +1599,40 @@
 	if ( dyld::gLogAPIs )
 		dyld::log("%s(%p, %p)\n", __func__, address, info);
 
+	CRSetCrashLogMessage("dyld: in dladdr()");
 	ImageLoader* image = dyld::findImageContainingAddress(address);
 	if ( image != NULL ) {
-		info->dli_fname = image->getPath();
+		info->dli_fname = image->getRealPath();
 		info->dli_fbase = (void*)image->machHeader();
 		if ( address == info->dli_fbase ) {
 			// special case lookup of header
 			info->dli_sname = "__dso_handle";
 			info->dli_saddr = info->dli_fbase;
+			CRSetCrashLogMessage(NULL);
 			return 1; // success
 		}
 		// find closest symbol in the image
 		info->dli_sname = image->findClosestSymbol(address, (const void**)&info->dli_saddr);
+		// never return the mach_header symbol
+		if ( info->dli_saddr == info->dli_fbase ) {
+			info->dli_sname = NULL;
+			info->dli_saddr = NULL;
+			CRSetCrashLogMessage(NULL);
+			return 1; // success
+		}
 		if ( info->dli_sname != NULL ) {
 			if ( info->dli_sname[0] == '_' )
 				info->dli_sname = info->dli_sname +1; // strip off leading underscore
 			//dyld::log("dladdr(%p) => %p %s\n", address, info->dli_saddr, info->dli_sname);
+			CRSetCrashLogMessage(NULL);
 			return 1; // success
 		}
 		info->dli_sname = NULL;
 		info->dli_saddr = NULL;
+		CRSetCrashLogMessage(NULL);
 		return 1; // success
 	}
+	CRSetCrashLogMessage(NULL);
 	return 0;  // failure
 }
 
@@ -1537,6 +1643,12 @@
 		dyld::log("%s()\n", __func__);
 
 	if ( dyld::gLibSystemHelpers != NULL ) {
+		// if using newer libdyld.dylib and buffer if buffer not yet allocated, return NULL
+		if ( dyld::gLibSystemHelpers->version >= 10 ) {
+			if ( ! (*dyld::gLibSystemHelpers->hasPerThreadBufferFor_dlerror)() )
+				return NULL;
+		}
+
 		// first char of buffer is flag whether string (starting at second char) is valid
 		char* buffer = (*dyld::gLibSystemHelpers->getThreadBufferFor_dlerror)(2);
 		if ( buffer[0] != '\0' ) {	// if valid buffer
@@ -1552,6 +1664,7 @@
 	if ( dyld::gLogAPIs )
 		dyld::log("%s(%p, %s)\n", __func__, handle, symbolName);
 
+	CRSetCrashLogMessage("dyld: in dlsym()");
 	dlerrorClear();
 
 	const ImageLoader* image;
@@ -1566,11 +1679,13 @@
 	// magic "search all" handle
 	if ( handle == RTLD_DEFAULT ) {
 		if ( dyld::flatFindExportedSymbol(underscoredName, &sym, &image) ) {
+			CRSetCrashLogMessage(NULL);
 			return (void*)image->getExportedSymbolAddress(sym, dyld::gLinkContext);
 		}
 		const char* str = dyld::mkstringf("dlsym(RTLD_DEFAULT, %s): symbol not found", symbolName);
 		dlerrorSet(str);
 		free((void*)str);
+		CRSetCrashLogMessage(NULL);
 		return NULL;
 	}
 	
@@ -1579,11 +1694,13 @@
 		image = dyld::mainExecutable();
 		sym = image->findExportedSymbol(underscoredName, true, &image); // search RTLD_FIRST way
 		if ( sym != NULL ) {
+			CRSetCrashLogMessage(NULL);
 			return (void*)image->getExportedSymbolAddress(sym, dyld::gLinkContext);
 		}
 		const char* str = dyld::mkstringf("dlsym(RTLD_MAIN_ONLY, %s): symbol not found", symbolName);
 		dlerrorSet(str);
 		free((void*)str);
+		CRSetCrashLogMessage(NULL);
 		return NULL;
 	}
 	
@@ -1593,11 +1710,13 @@
 		ImageLoader* callerImage = dyld::findImageContainingAddress(callerAddress);
 		sym = callerImage->findExportedSymbolInDependentImages(underscoredName, dyld::gLinkContext, &image); // don't search image, but do search what it links against
 		if ( sym != NULL ) {
+			CRSetCrashLogMessage(NULL);
 			return (void*)image->getExportedSymbolAddress(sym, dyld::gLinkContext);
 		}
 		const char* str = dyld::mkstringf("dlsym(RTLD_NEXT, %s): symbol not found", symbolName);
 		dlerrorSet(str);
 		free((void*)str);
+		CRSetCrashLogMessage(NULL);
 		return NULL;
 	}
 	// magic "search me, then what I would see" handle
@@ -1606,11 +1725,13 @@
 		ImageLoader* callerImage = dyld::findImageContainingAddress(callerAddress);
 		sym = callerImage->findExportedSymbolInImageOrDependentImages(underscoredName, dyld::gLinkContext, &image); // search image and what it links against
 		if ( sym != NULL ) {
+			CRSetCrashLogMessage(NULL);
 			return (void*)image->getExportedSymbolAddress(sym, dyld::gLinkContext);
 		}
 		const char* str = dyld::mkstringf("dlsym(RTLD_SELF, %s): symbol not found", symbolName);
 		dlerrorSet(str);
 		free((void*)str);
+		CRSetCrashLogMessage(NULL);
 		return NULL;
 	}
 	// real handle
@@ -1622,6 +1743,7 @@
 			sym = image->findExportedSymbolInImageOrDependentImages(underscoredName, dyld::gLinkContext, &image); // search image and what it links against
 		
 		if ( sym != NULL ) {
+			CRSetCrashLogMessage(NULL);
 			return (void*)image->getExportedSymbolAddress(sym, dyld::gLinkContext);
 		}
 		const char* str = dyld::mkstringf("dlsym(%p, %s): symbol not found", handle, symbolName);
@@ -1631,6 +1753,7 @@
 	else {
 		dlerrorSet("invalid handle passed to dlsym()");
 	}
+	CRSetCrashLogMessage(NULL);
 	return NULL;
 }
 
@@ -1645,7 +1768,7 @@
 
 const struct dyld_all_image_infos* _dyld_get_all_image_infos()
 {
-	return &dyld_all_image_infos;
+	return dyld::gProcessInfo;
 }
 
 #if !__arm__
@@ -1675,7 +1798,6 @@
 		dyld::registerImageStateSingleChangeHandler(state, handler);
 }
 
-
 const char* dyld_image_path_containing_address(const void* address)
 {
 	if ( dyld::gLogAPIs )
@@ -1683,8 +1805,22 @@
 
 	ImageLoader* image = dyld::findImageContainingAddress(address);
 	if ( image != NULL )
-		return image->getPath();
+		return image->getRealPath();
 	return NULL;
 }
 
 
+
+#if __IPHONE_OS_VERSION_MIN_REQUIRED	
+bool dyld_shared_cache_some_image_overridden()
+{
+ #if DYLD_SHARED_CACHE_SUPPORT
+	return dyld::gSharedCacheOverridden;
+ #else
+    return true;
+ #endif
+}
+#endif
+
+
+