Loading...
src/dyldInitialization.cpp dyld-195.5 dyld-95.3
--- dyld/dyld-195.5/src/dyldInitialization.cpp
+++ dyld/dyld-95.3/src/dyldInitialization.cpp
@@ -1,6 +1,6 @@
 /* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*-
  *
- * Copyright (c) 2004-2008 Apple Inc. All rights reserved.
+ * Copyright (c) 2004-2005 Apple Computer, Inc. All rights reserved.
  *
  * @APPLE_LICENSE_HEADER_START@
  * 
@@ -45,11 +45,13 @@
 
 
 #if __LP64__
+	#define macho_header			mach_header_64
 	#define LC_SEGMENT_COMMAND		LC_SEGMENT_64
 	#define macho_segment_command	segment_command_64
 	#define macho_section			section_64
 	#define RELOC_SIZE				3
 #else
+	#define macho_header			mach_header
 	#define LC_SEGMENT_COMMAND		LC_SEGMENT
 	#define macho_segment_command	segment_command
 	#define macho_section			section
@@ -112,28 +114,6 @@
 	}
 }
 
-
-//
-//  The kernel may have slid a Position Independent Executable
-//
-static uintptr_t slideOfMainExecutable(const struct 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_SEGMENT_COMMAND ) {
-			const struct macho_segment_command* segCmd = (struct macho_segment_command*)cmd;
-			if ( strcmp(segCmd->segname, "__TEXT") == 0 ) {
-				return (uintptr_t)mh - segCmd->vmaddr;
-			}
-		}
-		cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
-	}
-	return 0;
-}
-
-
 //
 // If the kernel does not load dyld at its preferred address, we need to apply 
 // fixups to various initialized parts of the __DATA segment
@@ -208,6 +188,126 @@
 }
 
 
+//
+// For some reason the kernel loads dyld with __TEXT and __LINKEDIT writable
+// rdar://problem/3702311 
+//
+static void segmentProtectDyld(const struct macho_header* mh, intptr_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;
+					vm_address_t addr = seg->vmaddr + slide;
+					vm_size_t size = seg->vmsize;
+					const bool setCurrentPermissions = false;
+					vm_protect(mach_task_self(), addr, size, setCurrentPermissions, seg->initprot);
+					//dyld::log("dyld: segment %s, 0x%08X -> 0x%08X, set to %d\n", seg->segname, addr, addr+size-1, seg->initprot);
+				}
+				break;
+		}
+		cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
+	}
+	
+}
+
+
+//
+// re-map the main executable to a new random address
+//
+static const struct mach_header* randomizeExecutableLoadAddress(const struct mach_header* orgMH, uintptr_t* appsSlide)
+{
+#if __ppc__
+	// don't slide PIE programs running under rosetta
+	if ( dyld::isRosetta() )
+		return orgMH;
+#endif
+	// count segments
+	uint32_t segCount = 0;
+	const uint32_t cmd_count = orgMH->ncmds;
+	const struct load_command* const cmds = (struct load_command*)(((char*)orgMH)+sizeof(macho_header));
+	const struct load_command* cmd = cmds;
+	for (uint32_t i = 0; i < cmd_count; ++i) {
+		if ( cmd->cmd == LC_SEGMENT_COMMAND ) {
+			const struct macho_segment_command* segCmd = (struct macho_segment_command*)cmd;
+			// page-zero and custom stacks don't move
+			if ( (strcmp(segCmd->segname, "__PAGEZERO") != 0) && (strcmp(segCmd->segname, "__UNIXSTACK") != 0) ) 
+				++segCount;
+		}
+		cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
+	}
+	
+	// make copy of segment info
+	macho_segment_command segs[segCount];
+	uint32_t index = 0;
+	uintptr_t highestAddressUsed = 0;
+	uintptr_t lowestAddressUsed = UINTPTR_MAX;
+	cmd = cmds;
+	for (uint32_t i = 0; i < cmd_count; ++i) {
+		if ( cmd->cmd == LC_SEGMENT_COMMAND ) {
+			const struct macho_segment_command* segCmd = (struct macho_segment_command*)cmd;
+			if ( (strcmp(segCmd->segname, "__PAGEZERO") != 0) && (strcmp(segCmd->segname, "__UNIXSTACK") != 0) ) {
+				segs[index++] = *segCmd;
+				if ( (segCmd->vmaddr + segCmd->vmsize) > highestAddressUsed )
+					highestAddressUsed = ((segCmd->vmaddr + segCmd->vmsize) + 4095) & -4096;
+				if ( segCmd->vmaddr < lowestAddressUsed )
+					lowestAddressUsed = segCmd->vmaddr;
+				// do nothing if kernel has already randomized load address
+				if ( (strcmp(segCmd->segname, "__TEXT") == 0) && (segCmd->vmaddr != (uintptr_t)orgMH) )
+					return orgMH;
+			}
+		}
+		cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
+	}
+	
+	// choose a random new base address
+#if __LP64__
+	uintptr_t highestAddressPossible = highestAddressUsed + 0x100000000ULL;
+#else
+	uintptr_t highestAddressPossible = 0x80000000;
+#endif
+	uintptr_t sizeNeeded = highestAddressUsed-lowestAddressUsed;
+	if ( (highestAddressPossible-sizeNeeded) < highestAddressUsed ) {
+		// new and old segments will overlap 
+		// need better algorithm for remapping
+		// punt and don't re-map
+		return orgMH;
+	}
+	uintptr_t possibleRange = (highestAddressPossible-sizeNeeded) - highestAddressUsed;
+	uintptr_t newBaseAddress = highestAddressUsed + ((arc4random() % possibleRange) & -4096);
+	
+	vm_address_t addr = newBaseAddress;
+	// reserve new address range
+	if ( vm_allocate(mach_task_self(), &addr, sizeNeeded, VM_FLAGS_FIXED) == KERN_SUCCESS ) {
+		// copy each segment to new address
+		for (uint32_t i = 0; i < segCount; ++i) {
+			uintptr_t newSegAddress = segs[i].vmaddr - lowestAddressUsed + newBaseAddress;
+			if ( (vm_copy(mach_task_self(), segs[i].vmaddr, segs[i].vmsize, newSegAddress) != KERN_SUCCESS)
+				|| (vm_protect(mach_task_self(), newSegAddress, segs[i].vmsize, true, segs[i].maxprot) != KERN_SUCCESS) 
+				|| (vm_protect(mach_task_self(), newSegAddress, segs[i].vmsize, false, segs[i].initprot) != KERN_SUCCESS) ) {
+				// can't copy so dealloc new region and run with original base address
+				vm_deallocate(mach_task_self(), newBaseAddress, sizeNeeded);
+				dyld::warn("could not relocate position independent exectable\n");
+				return orgMH;
+			}
+		}
+		// unmap original segments
+		vm_deallocate(mach_task_self(), lowestAddressUsed, highestAddressUsed-lowestAddressUsed);
+	
+		// run with newly mapped executable
+		*appsSlide = newBaseAddress - lowestAddressUsed;
+		return (const struct mach_header*)newBaseAddress;
+	}
+	
+	// can't get new range, so don't slide to random address
+	return orgMH;
+}
+
+
 extern "C" void dyld_exceptions_init(const struct macho_header*, uintptr_t slide); // in dyldExceptions.cpp
 extern "C" void mach_init();
 
@@ -227,27 +327,32 @@
 //  This is code to bootstrap dyld.  This work in normally done for a program by dyld and crt.
 //  In dyld we have to do this manually.
 //
-uintptr_t start(const struct macho_header* appsMachHeader, int argc, const char* argv[], 
-								intptr_t slide, const struct macho_header* dyldsMachHeader)
-{
+uintptr_t start(const struct mach_header* appsMachHeader, int argc, const char* argv[], intptr_t slide)
+{
+	// _mh_dylinker_header is magic symbol defined by static linker (ld), see <mach-o/ldsyms.h>
+	const struct macho_header* dyldsMachHeader =  (const struct macho_header*)(((char*)&_mh_dylinker_header)+slide);
+	
 	// if kernel had to slide dyld, we need to fix up load sensitive locations
 	// we have to do this before using any global variables
 	if ( slide != 0 ) {
 		rebaseDyld(dyldsMachHeader, slide);
 	}
-
-#if __IPHONE_OS_VERSION_MIN_REQUIRED		
+	
+	uintptr_t appsSlide = 0;
+	
 	// set pthread keys to dyld range
 	__pthread_tsd_first = 1;
 	_pthread_keys_init();
-#endif
-
+	
 	// enable C++ exceptions to work inside dyld
 	dyld_exceptions_init(dyldsMachHeader, slide);
 	
 	// allow dyld to use mach messaging
 	mach_init();
 
+	// set protection on segments (has to be done after mach_init)
+	segmentProtectDyld(dyldsMachHeader, slide);
+	
 	// kernel sets up env pointer to be just past end of agv array
 	const char** envp = &argv[argc+1];
 	
@@ -258,9 +363,12 @@
 
 	// run all C++ initializers inside dyld
 	runDyldInitializers(dyldsMachHeader, slide, argc, argv, envp, apple);
-		
+	
+	// if main executable was linked -pie, then randomize its load address
+	if ( appsMachHeader->flags & MH_PIE )
+		appsMachHeader = randomizeExecutableLoadAddress(appsMachHeader, &appsSlide);
+	
 	// now that we are done bootstrapping dyld, call dyld's main
-	uintptr_t appsSlide = slideOfMainExecutable(appsMachHeader);
 	return dyld::_main(appsMachHeader, appsSlide, argc, argv, envp, apple);
 }