Loading...
src/ImageLoaderMachO.cpp dyld-360.22 dyld-519.2.1
--- dyld/dyld-360.22/src/ImageLoaderMachO.cpp
+++ dyld/dyld-519.2.1/src/ImageLoaderMachO.cpp
@@ -52,6 +52,8 @@
 #include "ImageLoaderMachOClassic.h"
 #endif
 #include "mach-o/dyld_images.h"
+#include "Tracing.h"
+#include "dyld.h"
 
 // <rdar://problem/8718137> use stack guard random value to add padding between dylibs
 extern "C" long __stack_chk_guard;
@@ -68,6 +70,49 @@
 	#define LC_VERSION_MIN_WATCHOS 0x30
 #endif
 
+#ifndef LC_BUILD_VERSION
+	#define LC_BUILD_VERSION 0x32 /* build for platform min OS version */
+
+	/*
+	 * The build_version_command contains the min OS version on which this 
+	 * binary was built to run for its platform.  The list of known platforms and
+	 * tool values following it.
+	 */
+	struct build_version_command {
+		uint32_t	cmd;		/* LC_BUILD_VERSION */
+		uint32_t	cmdsize;	/* sizeof(struct build_version_command) plus */
+								/* ntools * sizeof(struct build_tool_version) */
+		uint32_t	platform;	/* platform */
+		uint32_t	minos;		/* X.Y.Z is encoded in nibbles xxxx.yy.zz */
+		uint32_t	sdk;		/* X.Y.Z is encoded in nibbles xxxx.yy.zz */
+		uint32_t	ntools;		/* number of tool entries following this */
+	};
+
+	struct build_tool_version {
+		uint32_t	tool;		/* enum for the tool */
+		uint32_t	version;	/* version number of the tool */
+	};
+
+	/* Known values for the platform field above. */
+	#define PLATFORM_MACOS		1
+	#define PLATFORM_IOS		2
+	#define PLATFORM_TVOS		3
+	#define PLATFORM_WATCHOS	4
+	#define PLATFORM_BRIDGEOS	5
+
+	/* Known values for the tool field above. */
+	#define TOOL_CLANG	1
+	#define TOOL_SWIFT	2
+	#define TOOL_LD		3
+#endif
+
+
+
+#if TARGET_IPHONE_SIMULATOR
+	#define LIBSYSTEM_DYLIB_PATH "/usr/lib/libSystem.dylib"
+#else
+	#define LIBSYSTEM_DYLIB_PATH "/usr/lib/libSystem.B.dylib"
+#endif
 
 // relocation_info.r_length field has value 3 for 64-bit executables and value 2 for 32-bit executables
 #if __LP64__
@@ -87,7 +132,6 @@
 #endif
 
 uint32_t ImageLoaderMachO::fgSymbolTableBinarySearchs = 0;
-uint32_t ImageLoaderMachO::fgSymbolTrieSearchs = 0;
 
 
 ImageLoaderMachO::ImageLoaderMachO(const macho_header* mh, const char* path, unsigned int segCount, 
@@ -103,7 +147,7 @@
 	fReadOnlyImportSegment(false),
 #endif
 	fHasSubLibraries(false), fHasSubUmbrella(false), fInUmbrella(false), fHasDOFSections(false), fHasDashInit(false),
-	fHasInitializers(false), fHasTerminators(false), fRegisteredAsRequiresCoalescing(false)
+	fHasInitializers(false), fHasTerminators(false), fNotifyObjC(false), fRetainForObjC(false), fRegisteredAsRequiresCoalescing(false)
 {
 	fIsSplitSeg = ((mh->flags & MH_SPLIT_SEGS) != 0);        
 
@@ -126,6 +170,12 @@
 
 }
 
+#if __MAC_OS_X_VERSION_MIN_REQUIRED
+static uintptr_t pageAlign(uintptr_t value)
+{
+	return (value + 4095) & (-4096);
+}
+#endif
 
 // determine if this mach-o file has classic or compressed LINKEDIT and number of segments it has
 void ImageLoaderMachO::sniffLoadCommands(const macho_header* mh, const char* path, bool inCache, bool* compressed,
@@ -140,13 +190,24 @@
 	*encryptCmd = NULL;
 
 	const uint32_t cmd_count = mh->ncmds;
-	const struct load_command* const startCmds    = (struct load_command*)(((uint8_t*)mh) + sizeof(macho_header));
-	const struct load_command* const endCmds = (struct load_command*)(((uint8_t*)mh) + sizeof(macho_header) + mh->sizeofcmds);
+	const uint32_t sizeofcmds = mh->sizeofcmds;
+	if ( sizeofcmds > (MAX_MACH_O_HEADER_AND_LOAD_COMMANDS_SIZE-sizeof(macho_header)) )
+		dyld::throwf("malformed mach-o: load commands size (%u) > %u", sizeofcmds, MAX_MACH_O_HEADER_AND_LOAD_COMMANDS_SIZE);
+	if ( cmd_count > (sizeofcmds/sizeof(load_command)) )
+		dyld::throwf("malformed mach-o: ncmds (%u) too large to fit in sizeofcmds (%u)", cmd_count, sizeofcmds);
+	const struct load_command* const startCmds = (struct load_command*)(((uint8_t*)mh) + sizeof(macho_header));
+	const struct load_command* const endCmds = (struct load_command*)(((uint8_t*)mh) + sizeof(macho_header) + sizeofcmds);
 	const struct load_command* cmd = startCmds;
 	bool foundLoadCommandSegment = false;
+	const macho_segment_command* linkeditSegCmd = NULL;
+	const macho_segment_command* startOfFileSegCmd = NULL;
+	const dyld_info_command* dyldInfoCmd = NULL;
+	const symtab_command* symTabCmd = NULL;
+	const dysymtab_command*	dynSymbTabCmd = NULL;
 	for (uint32_t i = 0; i < cmd_count; ++i) {
 		uint32_t cmdLength = cmd->cmdsize;
-		struct macho_segment_command* segCmd;
+		const macho_segment_command* segCmd;
+		const dylib_command* dylibCmd;
 		if ( cmdLength < 8 ) {
 			dyld::throwf("malformed mach-o image: load command #%d length (%u) too small in %s",
 											   i, cmdLength, path);
@@ -159,35 +220,87 @@
 		switch (cmd->cmd) {
 			case LC_DYLD_INFO:
 			case LC_DYLD_INFO_ONLY:
+				if ( cmd->cmdsize != sizeof(dyld_info_command) )
+					throw "malformed mach-o image: LC_DYLD_INFO size wrong";
+				dyldInfoCmd = (struct dyld_info_command*)cmd;
 				*compressed = true;
 				break;
 			case LC_SEGMENT_COMMAND:
 				segCmd = (struct macho_segment_command*)cmd;
 #if __MAC_OS_X_VERSION_MIN_REQUIRED
 				// rdar://problem/19617624 allow unmapped segments on OSX (but not iOS)
-				if ( (segCmd->filesize > segCmd->vmsize) && (segCmd->vmsize != 0) )
+				if ( ((segCmd->filesize) > pageAlign(segCmd->vmsize)) && (segCmd->vmsize != 0) )
 #else
-				if ( segCmd->filesize > segCmd->vmsize )
-#endif
-				    dyld::throwf("malformed mach-o image: segment load command %s filesize is larger than vmsize", segCmd->segname);
+				// <rdar://problem/19986776> dyld should support non-allocatable __LLVM segment
+				if ( (segCmd->filesize > segCmd->vmsize) && ((segCmd->vmsize != 0) || ((segCmd->flags & SG_NORELOC) == 0)) )
+#endif
+				    dyld::throwf("malformed mach-o image: segment load command %s filesize (0x%0lX) is larger than vmsize (0x%0lX)", segCmd->segname, (long)segCmd->filesize , (long)segCmd->vmsize );
+				if ( cmd->cmdsize < sizeof(macho_segment_command) )
+					throw "malformed mach-o image: LC_SEGMENT size too small";
+				if ( cmd->cmdsize != (sizeof(macho_segment_command) + segCmd->nsects * sizeof(macho_section)) )
+					throw "malformed mach-o image: LC_SEGMENT size wrong for number of sections";
 				// ignore zero-sized segments
 				if ( segCmd->vmsize != 0 )
 					*segCount += 1;
-				if ( context.codeSigningEnforced ) {
+				if ( strcmp(segCmd->segname, "__LINKEDIT") == 0 ) {
+		#if TARGET_IPHONE_SIMULATOR
+					// Note: should check on all platforms that __LINKEDIT is read-only, but <rdar://problem/22637626&22525618>
+					if ( segCmd->initprot != VM_PROT_READ )
+						throw "malformed mach-o image: __LINKEDIT segment does not have read-only permissions";
+		#endif
+					if ( segCmd->fileoff ==  0 )
+						throw "malformed mach-o image: __LINKEDIT has fileoff==0 which overlaps mach_header";
+					if ( linkeditSegCmd != NULL )
+						throw "malformed mach-o image: multiple __LINKEDIT segments";
+					linkeditSegCmd = segCmd;
+				}
+				else {
+					if ( segCmd->initprot & 0xFFFFFFF8 )
+						dyld::throwf("malformed mach-o image: %s segment has invalid permission bits (0x%X) in initprot", segCmd->segname, segCmd->initprot);
+					if ( segCmd->maxprot & 0xFFFFFFF8 )
+						dyld::throwf("malformed mach-o image: %s segment has invalid permission bits (0x%X) in maxprot", segCmd->segname, segCmd->maxprot);
+					if ( (segCmd->initprot != 0) && ((segCmd->initprot & VM_PROT_READ) == 0) )
+						dyld::throwf("malformed mach-o image: %s segment is not mapped readable", segCmd->segname);
+				}
+                if ( (segCmd->fileoff == 0) && (segCmd->filesize != 0) ) {
+					if ( (segCmd->initprot & VM_PROT_READ) == 0 )
+						dyld::throwf("malformed mach-o image: %s segment maps start of file but is not readable", segCmd->segname);
+					if ( (segCmd->initprot & VM_PROT_WRITE) == VM_PROT_WRITE ) {
+						if ( context.strictMachORequired )
+							dyld::throwf("malformed mach-o image: %s segment maps start of file but is writable", segCmd->segname);
+					}
+					if ( segCmd->filesize < (sizeof(macho_header) + mh->sizeofcmds) )
+						dyld::throwf("malformed mach-o image: %s segment does not map all of load commands", segCmd->segname);
+					if ( startOfFileSegCmd != NULL )
+						dyld::throwf("malformed mach-o image: multiple segments map start of file: %s %s", startOfFileSegCmd->segname, segCmd->segname);
+					startOfFileSegCmd = segCmd;
+				}
+				if ( context.strictMachORequired ) {
 					uintptr_t vmStart   = segCmd->vmaddr;
 					uintptr_t vmSize    = segCmd->vmsize;
 					uintptr_t vmEnd     = vmStart + vmSize;
 					uintptr_t fileStart = segCmd->fileoff;
 					uintptr_t fileSize  = segCmd->filesize;
-					if ( (intptr_t)(vmEnd) < 0)
-						dyld::throwf("malformed mach-o image: segment load command %s vmsize too large", segCmd->segname);
+					if ( (intptr_t)(vmSize) < 0 )
+						dyld::throwf("malformed mach-o image: segment load command %s vmsize too large in %s", segCmd->segname, path);
 					if ( vmStart > vmEnd )
 						dyld::throwf("malformed mach-o image: segment load command %s wraps around address space", segCmd->segname);
 					if ( vmSize != fileSize ) {
-						if ( (segCmd->initprot == 0) && (fileSize != 0) )
-							dyld::throwf("malformed mach-o image: unaccessable segment %s has filesize != 0", segCmd->segname);
-						else if ( vmSize < fileSize )
-							dyld::throwf("malformed mach-o image: segment %s has vmsize < filesize", segCmd->segname);
+						if ( segCmd->initprot == 0 ) {
+							// allow: fileSize == 0 && initprot == 0		e.g. __PAGEZERO
+							// allow: vmSize == 0 && initprot == 0			e.g. __LLVM
+							if ( (fileSize != 0) && (vmSize != 0) )
+								dyld::throwf("malformed mach-o image: unaccessable segment %s has non-zero filesize and vmsize", segCmd->segname);
+						}
+						else {
+							// allow: vmSize > fileSize && initprot != X  e.g. __DATA
+							if ( vmSize < fileSize ) {
+								dyld::throwf("malformed mach-o image: segment %s has vmsize < filesize", segCmd->segname);
+							}
+							if ( segCmd->initprot & VM_PROT_EXECUTE ) {
+								dyld::throwf("malformed mach-o image: segment %s has vmsize != filesize and is executable", segCmd->segname);
+							}
+						}
 					}
 					if ( inCache ) {
 						if ( (fileSize != 0) && (segCmd->initprot == (VM_PROT_READ | VM_PROT_EXECUTE)) ) {
@@ -223,23 +336,68 @@
 			case LC_REEXPORT_DYLIB:
 			case LC_LOAD_UPWARD_DYLIB:
 				*libCount += 1;
+				// fall thru
+			case LC_ID_DYLIB:
+				dylibCmd = (dylib_command*)cmd;
+				if ( dylibCmd->dylib.name.offset > cmdLength )
+					dyld::throwf("malformed mach-o image: dylib load command #%d has offset (%u) outside its size (%u)", i, dylibCmd->dylib.name.offset, cmdLength);
+				if ( (dylibCmd->dylib.name.offset + strlen((char*)dylibCmd + dylibCmd->dylib.name.offset) + 1) > cmdLength )
+					dyld::throwf("malformed mach-o image: dylib load command #%d string extends beyond end of load command", i);
 				break;
 			case LC_CODE_SIGNATURE:
-				*codeSigCmd = (struct linkedit_data_command*)cmd; // only support one LC_CODE_SIGNATURE per image
+				if ( cmd->cmdsize != sizeof(linkedit_data_command) )
+					throw "malformed mach-o image: LC_CODE_SIGNATURE size wrong";
+				// <rdar://problem/22799652> only support one LC_CODE_SIGNATURE per image
+				if ( *codeSigCmd != NULL )
+					throw "malformed mach-o image: multiple LC_CODE_SIGNATURE load commands";
+				*codeSigCmd = (struct linkedit_data_command*)cmd;
 				break;
 			case LC_ENCRYPTION_INFO:
+				if ( cmd->cmdsize != sizeof(encryption_info_command) )
+					throw "malformed mach-o image: LC_ENCRYPTION_INFO size wrong";
+				// <rdar://problem/22799652> only support one LC_ENCRYPTION_INFO per image
+				if ( *encryptCmd != NULL )
+					throw "malformed mach-o image: multiple LC_ENCRYPTION_INFO load commands";
+				*encryptCmd = (encryption_info_command*)cmd;
+				break;
 			case LC_ENCRYPTION_INFO_64:
-				*encryptCmd = (struct encryption_info_command*)cmd; // only support one LC_ENCRYPTION_INFO[_64] per image
-				break;
+				if ( cmd->cmdsize != sizeof(encryption_info_command_64) )
+					throw "malformed mach-o image: LC_ENCRYPTION_INFO_64 size wrong";
+				// <rdar://problem/22799652> only support one LC_ENCRYPTION_INFO_64 per image
+				if ( *encryptCmd != NULL )
+					throw "malformed mach-o image: multiple LC_ENCRYPTION_INFO_64 load commands";
+				*encryptCmd = (encryption_info_command*)cmd;
+				break;
+			case LC_SYMTAB:
+				if ( cmd->cmdsize != sizeof(symtab_command) )
+					throw "malformed mach-o image: LC_SYMTAB size wrong";
+				symTabCmd = (symtab_command*)cmd;
+				break;
+			case LC_DYSYMTAB:
+				if ( cmd->cmdsize != sizeof(dysymtab_command) )
+					throw "malformed mach-o image: LC_DYSYMTAB size wrong";
+				dynSymbTabCmd = (dysymtab_command*)cmd;
+				break;
+#if __MAC_OS_X_VERSION_MIN_REQUIRED
+			// <rdar://problem/26797345> error when loading iOS Simulator mach-o binary into macOS process
+			case LC_VERSION_MIN_WATCHOS:
+			case LC_VERSION_MIN_TVOS:
+			case LC_VERSION_MIN_IPHONEOS:
+				throw "mach-o, but built for simulator (not macOS)";
+				break;
+#endif
 		}
 		cmd = nextCmd;
 	}
 
-	if ( context.codeSigningEnforced && !foundLoadCommandSegment )
+	if ( context.strictMachORequired && !foundLoadCommandSegment )
 		throw "load commands not in a segment";
-
+	if ( linkeditSegCmd == NULL )
+		throw "malformed mach-o image: missing __LINKEDIT segment";
+	if ( !inCache && (startOfFileSegCmd == NULL) )
+		throw "malformed mach-o image: missing __TEXT segment that maps start of file";
 	// <rdar://problem/13145644> verify every segment does not overlap another segment
-	if ( context.codeSigningEnforced ) {
+	if ( context.strictMachORequired ) {
 		uintptr_t lastFileStart = 0;
 		uintptr_t linkeditFileStart = 0;
 		const struct load_command* cmd1 = startCmds;
@@ -285,6 +443,114 @@
 			dyld::throwf("malformed mach-o image: __LINKEDIT must be last segment");
 	}
 
+	// validate linkedit content
+	if  ( (dyldInfoCmd == NULL) && (symTabCmd == NULL) )
+		throw "malformed mach-o image: missing LC_SYMTAB or LC_DYLD_INFO";
+	if  ( dynSymbTabCmd == NULL )
+		throw "malformed mach-o image: missing LC_DYSYMTAB";
+
+	uint32_t  linkeditFileOffsetStart = (uint32_t)linkeditSegCmd->fileoff;
+	uint32_t  linkeditFileOffsetEnd = (uint32_t)linkeditSegCmd->fileoff + (uint32_t)linkeditSegCmd->filesize;
+
+	if ( !inCache && (dyldInfoCmd != NULL) && context.strictMachORequired ) {
+		// validate all LC_DYLD_INFO chunks fit in LINKEDIT and don't overlap
+		uint32_t offset = linkeditFileOffsetStart;
+		if ( dyldInfoCmd->rebase_size != 0 ) {
+			if ( dyldInfoCmd->rebase_size & 0x80000000 )
+				throw "malformed mach-o image: dyld rebase info size overflow";
+			if ( dyldInfoCmd->rebase_off < offset )
+				throw "malformed mach-o image: dyld rebase info underruns __LINKEDIT";
+			offset = dyldInfoCmd->rebase_off + dyldInfoCmd->rebase_size;
+			if ( offset > linkeditFileOffsetEnd )
+				throw "malformed mach-o image: dyld rebase info overruns __LINKEDIT";
+		}
+		if ( dyldInfoCmd->bind_size != 0 ) {
+			if ( dyldInfoCmd->bind_size & 0x80000000 )
+				throw "malformed mach-o image: dyld bind info size overflow";
+			if ( dyldInfoCmd->bind_off < offset )
+				throw "malformed mach-o image: dyld bind info overlaps rebase info";
+			offset = dyldInfoCmd->bind_off + dyldInfoCmd->bind_size;
+			if ( offset > linkeditFileOffsetEnd )
+				throw "malformed mach-o image: dyld bind info overruns __LINKEDIT";
+		}
+		if ( dyldInfoCmd->weak_bind_size != 0 ) {
+			if ( dyldInfoCmd->weak_bind_size & 0x80000000 )
+				throw "malformed mach-o image: dyld weak bind info size overflow";
+			if ( dyldInfoCmd->weak_bind_off < offset )
+				throw "malformed mach-o image: dyld weak bind info overlaps bind info";
+			offset = dyldInfoCmd->weak_bind_off + dyldInfoCmd->weak_bind_size;
+			if ( offset > linkeditFileOffsetEnd )
+				throw "malformed mach-o image: dyld weak bind info overruns __LINKEDIT";
+		}
+		if ( dyldInfoCmd->lazy_bind_size != 0 ) {
+			if ( dyldInfoCmd->lazy_bind_size & 0x80000000 )
+				throw "malformed mach-o image: dyld lazy bind info size overflow";
+			if ( dyldInfoCmd->lazy_bind_off < offset )
+				throw "malformed mach-o image: dyld lazy bind info overlaps weak bind info";
+			offset = dyldInfoCmd->lazy_bind_off + dyldInfoCmd->lazy_bind_size;
+			if ( offset > linkeditFileOffsetEnd )
+				throw "malformed mach-o image: dyld lazy bind info overruns __LINKEDIT";
+		}
+		if ( dyldInfoCmd->export_size != 0 ) {
+			if ( dyldInfoCmd->export_size & 0x80000000 )
+				throw "malformed mach-o image: dyld export info size overflow";
+			if ( dyldInfoCmd->export_off < offset )
+				throw "malformed mach-o image: dyld export info overlaps lazy bind info";
+			offset = dyldInfoCmd->export_off + dyldInfoCmd->export_size;
+			if ( offset > linkeditFileOffsetEnd )
+				throw "malformed mach-o image: dyld export info overruns __LINKEDIT";
+		}
+	}
+
+	if ( symTabCmd != NULL ) {
+		// validate symbol table fits in LINKEDIT
+		if ( symTabCmd->symoff < linkeditFileOffsetStart )
+			throw "malformed mach-o image: symbol table underruns __LINKEDIT";
+		if ( symTabCmd->nsyms > 0x10000000 )
+			throw "malformed mach-o image: symbol table too large";
+		uint32_t symbolsSize = symTabCmd->nsyms * sizeof(macho_nlist);
+		if ( symbolsSize > linkeditSegCmd->filesize )
+			throw "malformed mach-o image: symbol table overruns __LINKEDIT";
+		if ( symTabCmd->symoff + symbolsSize < symTabCmd->symoff )
+			throw "malformed mach-o image: symbol table size wraps";
+		if ( symTabCmd->symoff + symbolsSize > symTabCmd->stroff )
+			throw "malformed mach-o image: symbol table overlaps symbol strings";
+		if ( symTabCmd->stroff + symTabCmd->strsize < symTabCmd->stroff )
+			throw "malformed mach-o image: symbol string size wraps";
+		if ( symTabCmd->stroff + symTabCmd->strsize > linkeditFileOffsetEnd ) {
+			// <rdar://problem/24220313> let old apps overflow as long as it stays within mapped page
+			if ( context.strictMachORequired || (symTabCmd->stroff + symTabCmd->strsize > ((linkeditFileOffsetEnd + 4095) & (-4096))) )
+				throw "malformed mach-o image: symbol strings overrun __LINKEDIT";
+		}
+		// validate indirect symbol table
+		if ( dynSymbTabCmd->nindirectsyms != 0 ) {
+			if ( dynSymbTabCmd->indirectsymoff < linkeditFileOffsetStart )
+				throw "malformed mach-o image: indirect symbol table underruns __LINKEDIT";
+			if ( dynSymbTabCmd->nindirectsyms > 0x10000000 )
+				throw "malformed mach-o image: indirect symbol table too large";
+			uint32_t indirectTableSize = dynSymbTabCmd->nindirectsyms * sizeof(uint32_t);
+			if ( indirectTableSize > linkeditSegCmd->filesize )
+				throw "malformed mach-o image: indirect symbol table overruns __LINKEDIT";
+			if ( dynSymbTabCmd->indirectsymoff + indirectTableSize < dynSymbTabCmd->indirectsymoff )
+				throw "malformed mach-o image: indirect symbol table size wraps";
+			if ( context.strictMachORequired && (dynSymbTabCmd->indirectsymoff + indirectTableSize > symTabCmd->stroff)  )
+				throw "malformed mach-o image: indirect symbol table overruns string pool";
+		}
+		if ( (dynSymbTabCmd->nlocalsym > symTabCmd->nsyms) || (dynSymbTabCmd->ilocalsym > symTabCmd->nsyms) )
+			throw "malformed mach-o image: indirect symbol table local symbol count exceeds total symbols";
+		if ( dynSymbTabCmd->ilocalsym + dynSymbTabCmd->nlocalsym < dynSymbTabCmd->ilocalsym  )
+			throw "malformed mach-o image: indirect symbol table local symbol count wraps";
+		if ( (dynSymbTabCmd->nextdefsym > symTabCmd->nsyms) || (dynSymbTabCmd->iextdefsym > symTabCmd->nsyms) )
+			throw "malformed mach-o image: indirect symbol table extern symbol count exceeds total symbols";
+		if ( dynSymbTabCmd->iextdefsym + dynSymbTabCmd->nextdefsym < dynSymbTabCmd->iextdefsym  )
+			throw "malformed mach-o image: indirect symbol table extern symbol count wraps";
+		if ( (dynSymbTabCmd->nundefsym > symTabCmd->nsyms) || (dynSymbTabCmd->iundefsym > symTabCmd->nsyms) )
+			throw "malformed mach-o image: indirect symbol table undefined symbol count exceeds total symbols";
+		if ( dynSymbTabCmd->iundefsym + dynSymbTabCmd->nundefsym < dynSymbTabCmd->iundefsym  )
+			throw "malformed mach-o image: indirect symbol table undefined symbol count wraps";
+	}
+
+
 	// fSegmentsArrayCount is only 8-bits
 	if ( *segCount > 255 )
 		dyld::throwf("malformed mach-o image: more than 255 segments in %s", path);
@@ -323,32 +589,21 @@
 
 
 // create image by mapping in a mach-o file
-ImageLoader* ImageLoaderMachO::instantiateFromFile(const char* path, int fd, const uint8_t firstPage[4096], uint64_t offsetInFat, 
+ImageLoader* ImageLoaderMachO::instantiateFromFile(const char* path, int fd, const uint8_t firstPages[], size_t firstPagesSize, uint64_t offsetInFat,
 									uint64_t lenInFat, const struct stat& info, const LinkContext& context)
 {
-	// get load commands
-	const unsigned int dataSize = sizeof(macho_header) + ((macho_header*)firstPage)->sizeofcmds;
-	uint8_t buffer[dataSize];
-	const uint8_t* fileData = firstPage;
-	if ( dataSize > 4096 ) {
-		// only read more if cmds take up more space than first page
-		fileData = buffer;
-		memcpy(buffer, firstPage, 4096);
-		pread(fd, &buffer[4096], dataSize-4096, offsetInFat+4096);
-	}
-
 	bool compressed;
 	unsigned int segCount;
 	unsigned int libCount;
 	const linkedit_data_command* codeSigCmd;
 	const encryption_info_command* encryptCmd;
-	sniffLoadCommands((const macho_header*)fileData, path, false, &compressed, &segCount, &libCount, context, &codeSigCmd, &encryptCmd);
+	sniffLoadCommands((const macho_header*)firstPages, path, false, &compressed, &segCount, &libCount, context, &codeSigCmd, &encryptCmd);
 	// instantiate concrete class based on content of load commands
 	if ( compressed ) 
-		return ImageLoaderMachOCompressed::instantiateFromFile(path, fd, fileData, dataSize, offsetInFat, lenInFat, info, segCount, libCount, codeSigCmd, encryptCmd, context);
+		return ImageLoaderMachOCompressed::instantiateFromFile(path, fd, firstPages, firstPagesSize, offsetInFat, lenInFat, info, segCount, libCount, codeSigCmd, encryptCmd, context);
 	else
 #if SUPPORT_CLASSIC_MACHO
-		return ImageLoaderMachOClassic::instantiateFromFile(path, fd, fileData, dataSize, offsetInFat, lenInFat, info, segCount, libCount, codeSigCmd, context);
+		return ImageLoaderMachOClassic::instantiateFromFile(path, fd, firstPages, firstPagesSize, offsetInFat, lenInFat, info, segCount, libCount, codeSigCmd, context);
 #else
 		throw "missing LC_DYLD_INFO load command";
 #endif
@@ -418,7 +673,7 @@
 	for(unsigned int i=0; i < fSegmentsCount; ++i) {
 		// set up pointer to __LINKEDIT segment
 		if ( strcmp(segName(i),"__LINKEDIT") == 0 ) {
-			if ( context.codeSigningEnforced && (segFileOffset(i) > fCoveredCodeLength))
+			if ( context.requireCodeSignature && (segFileOffset(i) > fCoveredCodeLength))
 				dyld::throwf("cannot load '%s' (segment outside of code signature)", this->getShortName());
 			fLinkEditBase = (uint8_t*)(segActualLoadAddress(i) - segFileOffset(i));
 		}
@@ -495,6 +750,13 @@
 				{
 					const struct macho_segment_command* seg = (struct macho_segment_command*)cmd;
 					const bool isTextSeg = (strcmp(seg->segname, "__TEXT") == 0);
+		#if __i386__ && __MAC_OS_X_VERSION_MIN_REQUIRED
+					const bool isObjCSeg = (strcmp(seg->segname, "__OBJC") == 0);
+					if ( isObjCSeg )
+						fNotifyObjC = true;
+		#else
+					const bool isDataSeg = (strncmp(seg->segname, "__DATA", 6) == 0);
+		#endif
 					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) {
@@ -509,6 +771,32 @@
 							fEHFrameSectionOffset = (uint32_t)((uint8_t*)sect - fMachOData);
 						else if ( isTextSeg && (strcmp(sect->sectname, "__unwind_info") == 0) )
 							fUnwindInfoSectionOffset = (uint32_t)((uint8_t*)sect - fMachOData);
+
+		#if __i386__ && __MAC_OS_X_VERSION_MIN_REQUIRED
+						else if ( isObjCSeg ) {
+							if ( strcmp(sect->sectname, "__image_info") == 0 ) {
+								const uint32_t* imageInfo = (uint32_t*)(sect->addr + fSlide);
+								uint32_t flags = imageInfo[1];
+								if ( (flags & 4) && (((macho_header*)fMachOData)->filetype != MH_EXECUTE) )
+									dyld::throwf("cannot load '%s' because Objective-C garbage collection is not supported", getPath());
+							}
+							else if ( ((macho_header*)fMachOData)->filetype == MH_DYLIB ) {
+								fRetainForObjC = true;
+							}
+						}
+		#else
+						else if ( isDataSeg && (strncmp(sect->sectname, "__objc_imageinfo", 16) == 0) ) {
+			#if __MAC_OS_X_VERSION_MIN_REQUIRED
+							const uint32_t* imageInfo = (uint32_t*)(sect->addr + fSlide);
+							uint32_t flags = imageInfo[1];
+							if ( (flags & 4) && (((macho_header*)fMachOData)->filetype != MH_EXECUTE) )
+								dyld::throwf("cannot load '%s' because Objective-C garbage collection is not supported", getPath());
+			#endif
+							fNotifyObjC = true;
+						}
+						else if ( isDataSeg && (strncmp(sect->sectname, "__objc_", 7) == 0) && (((macho_header*)fMachOData)->filetype == MH_DYLIB) )
+							fRetainForObjC = true;
+		#endif
 					}
 				}
 				break;
@@ -718,7 +1006,7 @@
 		unsigned int textSegmentIndex = 0;
 		for(unsigned int i=0; i < fSegmentsCount; ++i) {
 			//dyld::log("unmap %s at 0x%08lX\n", seg->getName(), seg->getActualLoadAddress(this));
-			if ( strcmp(segName(i), "__TEXT") == 0 ) {
+			if ( (segFileOffset(i) == 0) && (segFileSize(i) != 0) ) {
 				textSegmentIndex = i;
 			}
 			else {
@@ -847,33 +1135,13 @@
 void ImageLoaderMachO::loadCodeSignature(const struct linkedit_data_command* codeSigCmd, int fd,  uint64_t offsetInFatFile, const LinkContext& context)
 {
 	// if dylib being loaded has no code signature load command
-	if ( codeSigCmd == NULL ) {
-#if __MAC_OS_X_VERSION_MIN_REQUIRED
-		bool codeSigningEnforced = context.codeSigningEnforced;
-		if ( context.mainExecutableCodeSigned && !codeSigningEnforced ) {
-			static bool codeSignEnforcementDynamicallyEnabled = false;
-			if ( !codeSignEnforcementDynamicallyEnabled ) {
-				uint32_t flags;
-				if ( csops(0, CS_OPS_STATUS, &flags, sizeof(flags)) != -1 ) {
-					if ( flags & CS_ENFORCEMENT ) {
-						codeSignEnforcementDynamicallyEnabled = true;
-					}
-				}
-			}
-			codeSigningEnforced = codeSignEnforcementDynamicallyEnabled;
-		}
-		// if we require dylibs to be code signed
-		if ( codeSigningEnforced  ) {
-			// if there is a non-load command based code signature, use it
-			off_t offset = (off_t)offsetInFatFile;
-			if ( fcntl(fd, F_FINDSIGS, &offset, sizeof(offset)) != -1 )
-				return;
-			// otherwise gracefully return from dlopen()
+	if ( codeSigCmd == NULL) {
+		if (context.requireCodeSignature ) {
+			// if we require dylibs to be codesigned there needs to be a signature.
 			dyld::throwf("required code signature missing for '%s'\n", this->getPath());
-		}
-#endif
-		//Since we don't have a range for the signature we have to assume full coverage
-		fCoveredCodeLength = UINT64_MAX;
+		} else {
+			disableCoverageCheck();
+		}
 	}
 	else {
 #if __MAC_OS_X_VERSION_MIN_REQUIRED
@@ -908,6 +1176,21 @@
 			dyld::log("dyld: Registered code signature for %s\n", this->getPath());
 		}
 		fCoveredCodeLength = siginfo.fs_file_start;
+
+#if __MAC_OS_X_VERSION_MIN_REQUIRED
+		if ( context.processUsingLibraryValidation ) {
+			fchecklv checkInfo;
+			char  messageBuffer[512];
+			messageBuffer[0] = '\0';
+			checkInfo.lv_file_start = offsetInFatFile;
+			checkInfo.lv_error_message_size = sizeof(messageBuffer);
+			checkInfo.lv_error_message = messageBuffer;
+			int res = fcntl(fd, F_CHECK_LV, &checkInfo);
+			if ( res == -1 ) {
+				dyld::throwf("code signature in (%s) not valid for use in process using Library Validation: %s", this->getPath(), messageBuffer);
+			}
+		}
+#endif
 	}
 }
 
@@ -921,18 +1204,28 @@
 	}
 #endif
 	if (codeSigCmd != NULL) {
-		if ( context.verboseMapping )
-			dyld::log("dyld: validate pages: %llu\n", (unsigned long long)offsetInFat);
-
 		void *fdata = xmmap(NULL, lenFileData, PROT_READ | PROT_EXEC, MAP_SHARED, fd, offsetInFat);
 		if ( fdata == MAP_FAILED ) {
-			if ( context.processRequiresLibraryValidation )
+#if __MAC_OS_X_VERSION_MIN_REQUIRED
+			if ( context.processUsingLibraryValidation ) {
 				dyld::throwf("cannot load image with wrong team ID in process using Library Validation");
+			}
 			else
-				dyld::throwf("mmap() errno=%d validating first page of '%s'", errno, getInstallPath());
+#endif
+			{
+				int errnoCopy = errno;
+				if ( errnoCopy == EPERM ) {
+					if ( dyld::sandboxBlockedMmap(getPath()) )
+						dyld::throwf("file system sandbox blocked mmap() of '%s'", getPath());
+					else
+						dyld::throwf("code signing blocked mmap() of '%s'", getPath());
+				}
+				else
+					dyld::throwf("mmap() errno=%d validating first page of '%s'", errnoCopy, getPath());
+			}
 		}
 		if ( memcmp(fdata, fileData, lenFileData) != 0 )
-			dyld::throwf("mmap() page compare failed for '%s'", getInstallPath());
+			dyld::throwf("mmap() page compare failed for '%s'", getPath());
 		munmap(fdata, lenFileData);
 	}
 }
@@ -963,14 +1256,20 @@
 					const struct macho_section* const sectionsEnd = &sectionsStart[seg->nsects];
 					for (const struct macho_section* sect=sectionsStart; sect < sectionsEnd; ++sect) {
 						if ( ((sect->flags & SECTION_TYPE) == S_INTERPOSING) || ((strcmp(sect->sectname, "__interpose") == 0) && (strcmp(seg->segname, "__DATA") == 0)) ) {
+							// <rdar://problem/23929217> Ensure section is within segment
+							if ( (sect->addr < seg->vmaddr) || (sect->addr+sect->size > seg->vmaddr+seg->vmsize) || (sect->addr+sect->size < sect->addr) )
+								dyld::throwf("interpose section has malformed address range for %s\n", this->getPath());
 							const InterposeData* interposeArray = (InterposeData*)(sect->addr + fSlide);
 							const size_t count = sect->size / sizeof(InterposeData);
-							for (size_t i=0; i < count; ++i) {
+							for (size_t j=0; j < count; ++j) {
 								ImageLoader::InterposeTuple tuple;
-								tuple.replacement		= interposeArray[i].replacement;
+								tuple.replacement		= interposeArray[j].replacement;
 								tuple.neverImage		= this;
 								tuple.onlyImage		    = NULL;
-								tuple.replacee			= interposeArray[i].replacee;
+								tuple.replacee			= interposeArray[j].replacee;
+								// <rdar://problem/25686570> ignore interposing on a weak function that does not exist
+								if ( tuple.replacee == 0 )
+									continue;
 								// <rdar://problem/7937695> verify that replacement is in this image
 								if ( this->containsAddress((void*)tuple.replacement) ) {
 									// chain to any existing interpositions
@@ -991,12 +1290,13 @@
 	}
 }
 
-uint32_t ImageLoaderMachO::sdkVersion() const
-{
-	const uint32_t cmd_count = ((macho_header*)fMachOData)->ncmds;
-	const struct load_command* const cmds = (struct load_command*)&fMachOData[sizeof(macho_header)];
+uint32_t ImageLoaderMachO::sdkVersion(const mach_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;
 	const struct version_min_command* versCmd;
+	const struct build_version_command* buildVersCmd;
 	for (uint32_t i = 0; i < cmd_count; ++i) {
 		switch ( cmd->cmd ) {
 			case LC_VERSION_MIN_MACOSX:
@@ -1005,10 +1305,18 @@
 			case LC_VERSION_MIN_WATCHOS:
 				versCmd = (version_min_command*)cmd;
 				return versCmd->sdk;
+			case LC_BUILD_VERSION:
+				buildVersCmd = (build_version_command*)cmd;
+				return buildVersCmd->sdk;
 		}
 		cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
 	}
 	return 0;
+}
+
+uint32_t ImageLoaderMachO::sdkVersion() const
+{
+	return ImageLoaderMachO::sdkVersion(machHeader());
 }
 
 uint32_t ImageLoaderMachO::minOSVersion(const mach_header* mh)
@@ -1017,6 +1325,7 @@
 	const struct load_command* const cmds = (struct load_command*)(((char*)mh) + sizeof(macho_header));
 	const struct load_command* cmd = cmds;
 	const struct version_min_command* versCmd;
+	const struct build_version_command* buildVersCmd;
 	for (uint32_t i = 0; i < cmd_count; ++i) {
 		switch ( cmd->cmd ) {
 			case LC_VERSION_MIN_MACOSX:
@@ -1025,6 +1334,9 @@
 			case LC_VERSION_MIN_WATCHOS:
 				versCmd = (version_min_command*)cmd;
 				return versCmd->version;
+			case LC_BUILD_VERSION:
+				buildVersCmd = (build_version_command*)cmd;
+				return buildVersCmd->minos;
 		}
 		cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
 	}
@@ -1136,7 +1448,7 @@
 {
 	if ( needsAddedLibSystemDepency(libraryCount(), (macho_header*)fMachOData) ) {
 		DependentLibraryInfo* lib = &libs[0];
-		lib->name = "/usr/lib/libSystem.B.dylib";
+		lib->name = LIBSYSTEM_DYLIB_PATH;
 		lib->info.checksum = 0;
 		lib->info.minVersion = 0;
 		lib->info.maxVersion = 0;
@@ -1174,7 +1486,7 @@
 	}
 }
 
-ImageLoader::LibraryInfo ImageLoaderMachO::doGetLibraryInfo()
+ImageLoader::LibraryInfo ImageLoaderMachO::doGetLibraryInfo(const LibraryInfo&)
 {
 	LibraryInfo info;
 	if ( fDylibIDOffset != 0 ) {
@@ -1202,10 +1514,12 @@
 				const char* pathToAdd = NULL;
 				const char* path = (char*)cmd + ((struct rpath_command*)cmd)->path.offset;
 				if ( (strncmp(path, "@loader_path", 12) == 0) && ((path[12] == '/') || (path[12] == '\0')) ) {
-					if ( context.processIsRestricted && !context.processRequiresLibraryValidation && (context.mainExecutable == this) ) {
+#if __MAC_OS_X_VERSION_MIN_REQUIRED
+					if ( context.processIsRestricted && (context.mainExecutable == this) ) {
 						dyld::warn("LC_RPATH %s in %s being ignored in restricted program because of @loader_path\n", path, this->getPath());
 						break;
 					}
+#endif
 					char resolvedPath[PATH_MAX];
 					if ( realpath(this->getPath(), resolvedPath) != NULL ) {
 						char newRealPath[strlen(resolvedPath) + strlen(path)];
@@ -1218,10 +1532,12 @@
 					}
 				}
 				else if ( (strncmp(path, "@executable_path", 16) == 0) && ((path[16] == '/') || (path[16] == '\0')) ) {
-					if ( context.processIsRestricted && !context.processRequiresLibraryValidation ) {
+#if __MAC_OS_X_VERSION_MIN_REQUIRED
+					if ( context.processIsRestricted ) {
 						dyld::warn("LC_RPATH %s in %s being ignored in restricted program because of @executable_path\n", path, this->getPath());
 						break;
 					}
+#endif
 					char resolvedPath[PATH_MAX];
 					if ( realpath(context.mainExecutable->getPath(), resolvedPath) != NULL ) {
 						char newRealPath[strlen(resolvedPath) + strlen(path)];
@@ -1233,10 +1549,13 @@
 						}
 					}
 				}
-				else if ( (path[0] != '/') && context.processIsRestricted && !context.processRequiresLibraryValidation ) {
+#if __MAC_OS_X_VERSION_MIN_REQUIRED
+				else if ( (path[0] != '/') && context.processIsRestricted ) {
 					dyld::warn("LC_RPATH %s in %s being ignored in restricted program because it is a relative path\n", path, this->getPath());
 					break;
 				}
+#endif
+#if SUPPORT_ROOT_PATH
 				else if ( (path[0] == '/') && (context.rootPaths != NULL) ) {
 					// <rdar://problem/5869973> DYLD_ROOT_PATH should apply to LC_RPATH rpaths
 					// DYLD_ROOT_PATH can be a list of paths, but at this point we can only support one, so use first combination that exists
@@ -1258,6 +1577,7 @@
 						pathToAdd = strdup(path);
 					}
 				}
+#endif
 				else {
 					// make copy so that all elements of 'paths' can be freed
 					pathToAdd = strdup(path);
@@ -1291,6 +1611,10 @@
 
 void ImageLoaderMachO::doRebase(const LinkContext& context)
 {
+	// <rdar://problem/25329861> Delay calling setNeverUnload() until we know this is not for dlopen_preflight()
+	if ( fRetainForObjC )
+		this->setNeverUnload();
+
 	// if prebound and loaded at prebound address, then no need to rebase
 	if ( this->usablePrebinding(context) ) {
 		// skip rebasing because prebinding is valid
@@ -1337,7 +1661,7 @@
 #endif
 
 	// do actual rebasing
-	this->rebase(context);
+	this->rebase(context, fSlide);
 			
 #if TEXT_RELOC_SUPPORT
 	// if there were __TEXT fixups, restore write protection
@@ -1368,10 +1692,10 @@
 }
 #endif
 
-const ImageLoader::Symbol* ImageLoaderMachO::findExportedSymbol(const char* name, bool searchReExports, const ImageLoader** foundIn) const
+const ImageLoader::Symbol* ImageLoaderMachO::findExportedSymbol(const char* name, bool searchReExports, const char* thisPath, const ImageLoader** foundIn) const
 {
 	// look in this image first
-	const ImageLoader::Symbol* result = this->findExportedSymbol(name, foundIn);
+	const ImageLoader::Symbol* result = this->findShallowExportedSymbol(name, foundIn);
 	if ( result != NULL )
 		return result;
 	
@@ -1380,7 +1704,8 @@
 			if ( libReExported(i) ) {
 				ImageLoader* image = libImage(i);
 				if ( image != NULL ) {
-					const Symbol* result = image->findExportedSymbol(name, searchReExports, foundIn);
+					const char* reExPath = libPath(i);
+					result = image->findExportedSymbol(name, searchReExports, reExPath, foundIn);
 					if ( result != NULL )
 						return result;
 				}
@@ -1395,7 +1720,7 @@
 
 
 uintptr_t ImageLoaderMachO::getExportedSymbolAddress(const Symbol* sym, const LinkContext& context, 
-											const ImageLoader* requestor, bool runResolver) const
+											const ImageLoader* requestor, bool runResolver, const char* symbolName) const
 {
 	return this->getSymbolAddress(sym, requestor, context, runResolver);
 }
@@ -1505,6 +1830,49 @@
 		info->compact_unwind_section = (void*)(sect->addr + fSlide);
 		info->compact_unwind_section_length = sect->size;
 	}
+}
+
+intptr_t ImageLoaderMachO::computeSlide(const mach_header* mh)
+{
+	const uint32_t cmd_count = mh->ncmds;
+	const load_command* const cmds = (load_command*)((char*)mh + sizeof(macho_header));
+	const load_command* cmd = cmds;
+	for (uint32_t i = 0; i < cmd_count; ++i) {
+		if ( cmd->cmd == LC_SEGMENT_COMMAND ) {
+			const macho_segment_command* seg = (macho_segment_command*)cmd;
+			if ( strcmp(seg->segname, "__TEXT") == 0 )
+				return (char*)mh - (char*)(seg->vmaddr);
+		}
+		cmd = (const load_command*)(((char*)cmd)+cmd->cmdsize);
+	}
+	return 0;
+}
+
+bool ImageLoaderMachO::findSection(const mach_header* mh, const char* segmentName, const char* sectionName, void** sectAddress, size_t* sectSize)
+{
+	const uint32_t cmd_count = mh->ncmds;
+	const load_command* const cmds = (load_command*)((char*)mh + sizeof(macho_header));
+	const load_command* cmd = cmds;
+	for (uint32_t i = 0; i < cmd_count; ++i) {
+		switch (cmd->cmd) {
+			case LC_SEGMENT_COMMAND:
+				{
+					const macho_segment_command* seg = (macho_segment_command*)cmd;
+					const macho_section* const sectionsStart = (macho_section*)((char*)seg + sizeof(macho_segment_command));
+					const macho_section* const sectionsEnd = &sectionsStart[seg->nsects];
+					for (const macho_section* sect=sectionsStart; sect < sectionsEnd; ++sect) {
+						if ( (strcmp(sect->segname, segmentName) == 0) && (strcmp(sect->sectname, sectionName) == 0) ) {
+							*sectAddress = (void*)(sect->addr + computeSlide(mh));
+							*sectSize = sect->size;
+							return true;
+						}
+					}
+				}
+				break;
+		}
+		cmd = (const load_command*)(((char*)cmd)+cmd->cmdsize);
+	}
+	return false;
 }
 
 
@@ -1542,13 +1910,43 @@
 	return false;
 }
 
+const char* ImageLoaderMachO::libPath(unsigned int index) const
+{
+	const uint32_t cmd_count = ((macho_header*)fMachOData)->ncmds;
+	const struct load_command* const cmds = (struct load_command*)&fMachOData[sizeof(macho_header)];
+	const struct load_command* cmd = cmds;
+	unsigned count = 0;
+	for (uint32_t i = 0; i < cmd_count; ++i) {
+		switch ( cmd->cmd ) {
+			case LC_LOAD_DYLIB:
+			case LC_LOAD_WEAK_DYLIB:
+			case LC_REEXPORT_DYLIB:
+			case LC_LOAD_UPWARD_DYLIB:
+				if ( index == count ) {
+					const struct dylib_command*  dylibCmd = (struct dylib_command*)cmd;
+					return (char*)cmd + dylibCmd->dylib.name.offset;
+				}
+				++count;
+				break;
+		}
+		cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
+	}
+
+	// <rdar://problem/24256354> if image linked with nothing and we implicitly added libSystem.dylib, return that
+	if ( needsAddedLibSystemDepency(libraryCount(), (macho_header*)fMachOData) ) {
+		return LIBSYSTEM_DYLIB_PATH;
+	}
+
+	return NULL;
+}
+
 
 void __attribute__((noreturn)) ImageLoaderMachO::throwSymbolNotFound(const LinkContext& context, const char* symbol, 
 																	const char* referencedFrom, const char* fromVersMismatch,
 																	const char* expectedIn)
 {
 	// record values for possible use by CrashReporter or Finder
-	(*context.setErrorStrings)(dyld_error_kind_symbol_missing, referencedFrom, expectedIn, symbol);
+	(*context.setErrorStrings)(DYLD_EXIT_REASON_SYMBOL_MISSING, referencedFrom, expectedIn, symbol);
 	dyld::throwf("Symbol not found: %s\n  Referenced from: %s%s\n  Expected in: %s\n",
 					symbol, referencedFrom, fromVersMismatch, expectedIn);
 }
@@ -1579,20 +1977,20 @@
 
 
 uintptr_t ImageLoaderMachO::bindLocation(const LinkContext& context, uintptr_t location, uintptr_t value, 
-										const ImageLoader* targetImage, uint8_t type, const char* symbolName, 
-										intptr_t addend, const char* msg)
+										uint8_t type, const char* symbolName,
+										intptr_t addend, const char* inPath, const char* toPath, const char* msg)
 {
 	// log
 	if ( context.verboseBind ) {
 		if ( addend != 0 )
 			dyld::log("dyld: %sbind: %s:0x%08lX = %s:%s, *0x%08lX = 0x%08lX + %ld\n",
-						msg, this->getShortName(), (uintptr_t)location,
-						((targetImage != NULL) ? targetImage->getShortName() : "<weak_import-missing>"),
+						msg, shortName(inPath), (uintptr_t)location,
+						((toPath != NULL) ? shortName(toPath) : "<missing weak_import>"),
 						symbolName, (uintptr_t)location, value, addend);
 		else
 			dyld::log("dyld: %sbind: %s:0x%08lX = %s:%s, *0x%08lX = 0x%08lX\n",
-						msg, this->getShortName(), (uintptr_t)location,
-						((targetImage != NULL) ? targetImage->getShortName() : "<weak>import-missing>"),
+						msg, shortName(inPath), (uintptr_t)location,
+						((toPath != NULL) ? shortName(toPath) : "<missing weak_import>"),
 						 symbolName, (uintptr_t)location, value);
 	}
 #if LOG_BINDINGS
@@ -1652,7 +2050,7 @@
 
 // These are defined in dyldStartup.s
 extern "C" void stub_binding_helper();
-
+extern "C" int _dyld_func_lookup(const char* name, void** address);
 
 void ImageLoaderMachO::setupLazyPointerHandler(const LinkContext& context)
 {
@@ -1741,24 +2139,24 @@
 	vars.mh = (macho_header*)fMachOData;
 	
 	// lookup _NXArgc
-	sym = this->findExportedSymbol("_NXArgc", false, NULL);
+	sym = this->findShallowExportedSymbol("_NXArgc", NULL);
 	if ( sym != NULL )
-		vars.NXArgcPtr = (int*)this->getExportedSymbolAddress(sym, context, this, false);
+		vars.NXArgcPtr = (int*)this->getExportedSymbolAddress(sym, context, this, false, NULL);
 		
 	// lookup _NXArgv
-	sym = this->findExportedSymbol("_NXArgv", false, NULL);
+	sym = this->findShallowExportedSymbol("_NXArgv", NULL);
 	if ( sym != NULL )
-		vars.NXArgvPtr = (const char***)this->getExportedSymbolAddress(sym, context, this, false);
+		vars.NXArgvPtr = (const char***)this->getExportedSymbolAddress(sym, context, this, false, NULL);
 		
 	// lookup _environ
-	sym = this->findExportedSymbol("_environ", false, NULL);
+	sym = this->findShallowExportedSymbol("_environ", NULL);
 	if ( sym != NULL )
-		vars.environPtr = (const char***)this->getExportedSymbolAddress(sym, context, this, false);
+		vars.environPtr = (const char***)this->getExportedSymbolAddress(sym, context, this, false, NULL);
 		
 	// lookup __progname
-	sym = this->findExportedSymbol("___progname", false, NULL);
+	sym = this->findShallowExportedSymbol("___progname", NULL);
 	if ( sym != NULL )
-		vars.__prognamePtr = (const char**)this->getExportedSymbolAddress(sym, context, this, false);
+		vars.__prognamePtr = (const char**)this->getExportedSymbolAddress(sym, context, this, false, NULL);
 		
 	context.setNewProgramVars(vars);
 }
@@ -1802,9 +2200,15 @@
 					if ( ! this->containsAddress((void*)func) ) {
 						dyld::throwf("initializer function %p not in mapped image for %s\n", func, this->getPath());
 					}
+					if ( ! dyld::gProcessInfo->libSystemInitialized ) {
+						// <rdar://problem/17973316> libSystem initializer must run first
+						dyld::throwf("-init function in image (%s) that does not link with libSystem.dylib\n", this->getPath());
+					}
 					if ( context.verboseInit )
 						dyld::log("dyld: calling -init function %p in %s\n", func, this->getPath());
-					func(context.argc, context.argv, context.envp, context.apple, &context.programVars);
+                    dyld3::kdebug_trace_dyld_duration(DBG_DYLD_TIMING_STATIC_INITIALIZER, (uint64_t)func, 0, ^{
+                        func(context.argc, context.argv, context.envp, context.apple, &context.programVars);
+                    });
 					break;
 			}
 			cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
@@ -1828,15 +2232,32 @@
 					if ( type == S_MOD_INIT_FUNC_POINTERS ) {
 						Initializer* inits = (Initializer*)(sect->addr + fSlide);
 						const size_t count = sect->size / sizeof(uintptr_t);
-						for (size_t i=0; i < count; ++i) {
-							Initializer func = inits[i];
+						// <rdar://problem/23929217> Ensure __mod_init_func section is within segment
+						if ( (sect->addr < seg->vmaddr) || (sect->addr+sect->size > seg->vmaddr+seg->vmsize) || (sect->addr+sect->size < sect->addr) )
+							dyld::throwf("__mod_init_funcs section has malformed address range for %s\n", this->getPath());
+						for (size_t j=0; j < count; ++j) {
+							Initializer func = inits[j];
 							// <rdar://problem/8543820&9228031> verify initializers are in image
 							if ( ! this->containsAddress((void*)func) ) {
 								dyld::throwf("initializer function %p not in mapped image for %s\n", func, this->getPath());
 							}
+							if ( ! dyld::gProcessInfo->libSystemInitialized ) {
+								// <rdar://problem/17973316> libSystem initializer must run first
+								const char* installPath = getInstallPath();
+								if ( (installPath == NULL) || (strcmp(installPath, LIBSYSTEM_DYLIB_PATH) != 0) )
+									dyld::throwf("initializer in image (%s) that does not link with libSystem.dylib\n", this->getPath());
+							}
 							if ( context.verboseInit )
 								dyld::log("dyld: calling initializer function %p in %s\n", func, this->getPath());
-							func(context.argc, context.argv, context.envp, context.apple, &context.programVars);
+							bool haveLibSystemHelpersBefore = (dyld::gLibSystemHelpers != NULL);
+                            dyld3::kdebug_trace_dyld_duration(DBG_DYLD_TIMING_STATIC_INITIALIZER, (uint64_t)func, 0, ^{
+                                func(context.argc, context.argv, context.envp, context.apple, &context.programVars);
+                            });
+							bool haveLibSystemHelpersAfter = (dyld::gLibSystemHelpers != NULL);
+							if ( !haveLibSystemHelpersBefore && haveLibSystemHelpersAfter ) {
+								// now safe to use malloc() and other calls in libSystem.dylib
+								dyld::gProcessInfo->libSystemInitialized = true;
+							}
 						}
 					}
 				}
@@ -1845,9 +2266,6 @@
 		}
 	}
 }
-
-
-
 
 
 
@@ -1867,6 +2285,9 @@
 						const struct macho_section* const sectionsEnd = &sectionsStart[seg->nsects];
 						for (const struct macho_section* sect=sectionsStart; sect < sectionsEnd; ++sect) {
 							if ( (sect->flags & SECTION_TYPE) == S_DTRACE_DOF ) {
+								// <rdar://problem/23929217> Ensure section is within segment
+								if ( (sect->addr < seg->vmaddr) || (sect->addr+sect->size > seg->vmaddr+seg->vmsize) || (sect->addr+sect->size < sect->addr) )
+									dyld::throwf("DOF section has malformed address range for %s\n", this->getPath());
 								ImageLoader::DOFInfo info;
 								info.dof			= (void*)(sect->addr + fSlide);
 								info.imageHeader	= this->machHeader();
@@ -1922,10 +2343,13 @@
 				for (const struct macho_section* sect=sectionsStart; sect < sectionsEnd; ++sect) {
 					const uint8_t type = sect->flags & SECTION_TYPE;
 					if ( type == S_MOD_TERM_FUNC_POINTERS ) {
+						// <rdar://problem/23929217> Ensure section is within segment
+						if ( (sect->addr < seg->vmaddr) || (sect->addr+sect->size > seg->vmaddr+seg->vmsize) || (sect->addr+sect->size < sect->addr) )
+							dyld::throwf("DOF section has malformed address range for %s\n", this->getPath());
 						Terminator* terms = (Terminator*)(sect->addr + fSlide);
 						const size_t count = sect->size / sizeof(uintptr_t);
-						for (size_t i=count; i > 0; --i) {
-							Terminator func = terms[i-1];
+						for (size_t j=count; j > 0; --j) {
+							Terminator func = terms[j-1];
 							// <rdar://problem/8543820&9228031> verify terminators are in image
 							if ( ! this->containsAddress((void*)func) ) {
 								dyld::throwf("termination function %p not in mapped image for %s\n", func, this->getPath());
@@ -1943,9 +2367,9 @@
 }
 
 
-void ImageLoaderMachO::printStatistics(unsigned int imageCount, const InitializerTimingList& timingInfo)
-{
-	ImageLoader::printStatistics(imageCount, timingInfo);
+void ImageLoaderMachO::printStatisticsDetails(unsigned int imageCount, const InitializerTimingList& timingInfo)
+{
+	ImageLoader::printStatisticsDetails(imageCount, timingInfo);
 	dyld::log("total symbol trie searches:    %d\n", fgSymbolTrieSearchs);
 	dyld::log("total symbol table binary searches:    %d\n", fgSymbolTableBinarySearchs);
 	dyld::log("total images defining weak symbols:  %u\n", fgImagesHasWeakDefinitions);
@@ -1988,7 +2412,7 @@
 	} 
 	else if ( ! this->segmentsCanSlide() ) {
 		for(unsigned int i=0, e=segmentCount(); i < e; ++i) {
-			if ( strcmp(segName(i), "__PAGEZERO") == 0 )
+			if ( (strcmp(segName(i), "__PAGEZERO") == 0) && (segFileSize(i) == 0) && (segPreferredLoadAddress(i) == 0) )
 				continue;
 			if ( !reserveAddressRange(segPreferredLoadAddress(i), segSize(i)) )
 				dyld::throwf("can't map unslidable segment %s to 0x%lX with size 0x%lX", segName(i), segPreferredLoadAddress(i), segSize(i));
@@ -2048,7 +2472,7 @@
 	}
 	// map in all segments
 	for(unsigned int i=0, e=segmentCount(); i < e; ++i) {
-		vm_offset_t fileOffset = segFileOffset(i) + offsetInFat;
+		vm_offset_t fileOffset = (vm_offset_t)(segFileOffset(i) + offsetInFat);
 		vm_size_t size = segFileSize(i);
 		uintptr_t requestedLoadAddress = segPreferredLoadAddress(i) + slide;
 		int protection = 0;
@@ -2059,8 +2483,12 @@
 				protection   |= PROT_EXEC;
 			if ( segReadable(i) )
 				protection   |= PROT_READ;
-			if ( segWriteable(i) )
+			if ( segWriteable(i) ) {
 				protection   |= PROT_WRITE;
+				// rdar://problem/22525618 force __LINKEDIT to always be mapped read-only
+				if ( strcmp(segName(i), "__LINKEDIT") == 0 )
+					protection = PROT_READ;
+			}
 		}
 	#if __i386__
 		// initially map __IMPORT segments R/W so dyld can update them
@@ -2075,8 +2503,16 @@
 			}
 			void* loadAddress = xmmap((void*)requestedLoadAddress, size, protection, MAP_FIXED | MAP_PRIVATE, fd, fileOffset);
 			if ( loadAddress == ((void*)(-1)) ) {
-				dyld::throwf("mmap() error %d at address=0x%08lX, size=0x%08lX segment=%s in Segment::map() mapping %s", 
-					errno, requestedLoadAddress, (uintptr_t)size, segName(i), getPath());
+				int mmapErr = errno;
+				if ( mmapErr == EPERM ) {
+					if ( dyld::sandboxBlockedMmap(getPath()) )
+						dyld::throwf("file system sandbox blocked mmap() of '%s'", this->getPath());
+					else
+						dyld::throwf("code signing blocked mmap() of '%s'", this->getPath());
+				}
+				else
+					dyld::throwf("mmap() errno=%d at address=0x%08lX, size=0x%08lX segment=%s in Segment::map() mapping %s",
+						mmapErr, requestedLoadAddress, (uintptr_t)size, segName(i), getPath());
 			}
 		}
 		// update stats
@@ -2162,3 +2598,191 @@
 }
 
 
+const char* ImageLoaderMachO::findClosestSymbol(const mach_header* mh, const void* addr, const void** closestAddr)
+{
+	// called by dladdr()
+	// only works with compressed LINKEDIT if classic symbol table is also present
+	const dysymtab_command* dynSymbolTable = NULL;
+	const symtab_command* symtab = NULL;
+	const macho_segment_command* seg;
+	const uint8_t* unslidLinkEditBase = NULL;
+	bool linkEditBaseFound = false;
+	intptr_t slide = 0;
+	const uint32_t cmd_count = mh->ncmds;
+	const load_command* const cmds = (load_command*)((char*)mh + sizeof(macho_header));
+	const load_command* cmd = cmds;
+	for (uint32_t i = 0; i < cmd_count; ++i) {
+		switch (cmd->cmd) {
+			case LC_SEGMENT_COMMAND:
+				seg = (macho_segment_command*)cmd;
+				if ( strcmp(seg->segname, "__LINKEDIT") == 0 ) {
+					unslidLinkEditBase = (uint8_t*)(seg->vmaddr - seg->fileoff);
+					linkEditBaseFound = true;
+				}
+				else if ( strcmp(seg->segname, "__TEXT") == 0 ) {
+					slide = (uintptr_t)mh - seg->vmaddr;
+                }
+				break;
+			case LC_SYMTAB:
+				symtab = (symtab_command*)cmd;
+				break;
+			case LC_DYSYMTAB:
+				dynSymbolTable = (dysymtab_command*)cmd;
+				break;
+		}
+		cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
+	}
+	// no symbol table => no lookup by address
+	if ( (symtab == NULL) || (dynSymbolTable == NULL) || !linkEditBaseFound )
+		return NULL;
+
+	const uint8_t* linkEditBase = unslidLinkEditBase + slide;
+	const char* symbolTableStrings = (const char*)&linkEditBase[symtab->stroff];
+	const macho_nlist* symbolTable = (macho_nlist*)(&linkEditBase[symtab->symoff]);
+
+	uintptr_t targetAddress = (uintptr_t)addr - slide;
+	const struct macho_nlist* bestSymbol = NULL;
+	// first walk all global symbols
+	const struct macho_nlist* const globalsStart = &symbolTable[dynSymbolTable->iextdefsym];
+	const struct macho_nlist* const globalsEnd= &globalsStart[dynSymbolTable->nextdefsym];
+	for (const struct macho_nlist* s = globalsStart; s < globalsEnd; ++s) {
+ 		if ( (s->n_type & N_TYPE) == N_SECT ) {
+			if ( bestSymbol == NULL ) {
+				if ( s->n_value <= targetAddress )
+					bestSymbol = s;
+			}
+			else if ( (s->n_value <= targetAddress) && (bestSymbol->n_value < s->n_value) ) {
+				bestSymbol = s;
+			}
+		}
+	}
+	// next walk all local symbols
+	const struct macho_nlist* const localsStart = &symbolTable[dynSymbolTable->ilocalsym];
+	const struct macho_nlist* const localsEnd= &localsStart[dynSymbolTable->nlocalsym];
+	for (const struct macho_nlist* s = localsStart; s < localsEnd; ++s) {
+ 		if ( ((s->n_type & N_TYPE) == N_SECT) && ((s->n_type & N_STAB) == 0) ) {
+			if ( bestSymbol == NULL ) {
+				if ( s->n_value <= targetAddress )
+					bestSymbol = s;
+			}
+			else if ( (s->n_value <= targetAddress) && (bestSymbol->n_value < s->n_value) ) {
+				bestSymbol = s;
+			}
+		}
+	}
+	if ( bestSymbol != NULL ) {
+#if __arm__
+		if (bestSymbol->n_desc & N_ARM_THUMB_DEF)
+			*closestAddr = (void*)((bestSymbol->n_value | 1) + slide);
+		else
+			*closestAddr = (void*)(bestSymbol->n_value + slide);
+#else
+		*closestAddr = (void*)(bestSymbol->n_value + slide);
+#endif
+		return &symbolTableStrings[bestSymbol->n_un.n_strx];
+	}
+	return NULL;
+}
+
+bool ImageLoaderMachO::getLazyBindingInfo(uint32_t& lazyBindingInfoOffset, const uint8_t* lazyInfoStart, const uint8_t* lazyInfoEnd,
+													uint8_t* segIndex, uintptr_t* segOffset, int* ordinal, const char** symbolName, bool* doneAfterBind)
+{
+	if ( lazyBindingInfoOffset > (lazyInfoEnd-lazyInfoStart) )
+		return false;
+	uint8_t type = BIND_TYPE_POINTER;
+	uint8_t symboFlags = 0;
+	bool done = false;
+	const uint8_t* p = &lazyInfoStart[lazyBindingInfoOffset];
+	while ( !done && (p < lazyInfoEnd) ) {
+		uint8_t immediate = *p & BIND_IMMEDIATE_MASK;
+		uint8_t opcode = *p & BIND_OPCODE_MASK;
+		++p;
+		switch (opcode) {
+			case BIND_OPCODE_DONE:
+				*doneAfterBind = false;
+				return true;
+				break;
+			case BIND_OPCODE_SET_DYLIB_ORDINAL_IMM:
+				*ordinal = immediate;
+				break;
+			case BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB:
+				*ordinal = (int)read_uleb128(p, lazyInfoEnd);
+				break;
+			case BIND_OPCODE_SET_DYLIB_SPECIAL_IMM:
+				// the special ordinals are negative numbers
+				if ( immediate == 0 )
+					*ordinal = 0;
+				else {
+					int8_t signExtended = BIND_OPCODE_MASK | immediate;
+					*ordinal = signExtended;
+				}
+				break;
+			case BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM:
+				*symbolName = (char*)p;
+				symboFlags = immediate;
+				while (*p != '\0')
+					++p;
+				++p;
+				break;
+			case BIND_OPCODE_SET_TYPE_IMM:
+				type = immediate;
+				break;
+			case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:
+				*segIndex  = immediate;
+				*segOffset = read_uleb128(p, lazyInfoEnd);
+				break;
+			case BIND_OPCODE_DO_BIND:
+				*doneAfterBind = ((*p & BIND_OPCODE_MASK) == BIND_OPCODE_DONE);
+				lazyBindingInfoOffset += p - &lazyInfoStart[lazyBindingInfoOffset];
+				return true;
+				break;
+			case BIND_OPCODE_SET_ADDEND_SLEB:
+			case BIND_OPCODE_ADD_ADDR_ULEB:
+			case BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB:
+			case BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED:
+			case BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB:
+			default:
+				return false;
+		}
+	}	
+	return false;
+}
+
+const dyld_info_command* ImageLoaderMachO::findDyldInfoLoadCommand(const mach_header* mh)
+{
+	const uint32_t cmd_count = mh->ncmds;
+	const load_command* const cmds = (load_command*)((char*)mh + sizeof(macho_header));
+	const load_command* cmd = cmds;
+	for (uint32_t i = 0; i < cmd_count; ++i) {
+		switch (cmd->cmd) {
+			case LC_DYLD_INFO:
+			case LC_DYLD_INFO_ONLY:
+				return (dyld_info_command*)cmd;
+		}
+		cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
+	}
+	return NULL;
+}
+
+
+uintptr_t ImageLoaderMachO::segPreferredAddress(const mach_header* mh, unsigned segIndex)
+{
+	const uint32_t cmd_count = mh->ncmds;
+	const load_command* const cmds = (load_command*)((char*)mh + sizeof(macho_header));
+	const load_command* cmd = cmds;
+	unsigned curSegIndex = 0;
+	for (uint32_t i = 0; i < cmd_count; ++i) {
+		if ( cmd->cmd == LC_SEGMENT_COMMAND ) {
+			if ( segIndex == curSegIndex ) {
+				const macho_segment_command* segCmd = (macho_segment_command*)cmd;
+				return segCmd->vmaddr;
+			}
+			++curSegIndex;
+		}
+		cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
+	}
+	return 0;
+}
+
+
+