Specify the MAP_JIT flag when allocating executable memory on macOS

On macOS 10.14 and higher, executables that are code signed with the
"runtime" option cannot execute writable memory by default. They can opt
into this capability by specifying the "com.apple.security.cs.allow-jit"
code signing entitlement and allocating the region with the MAP_JIT flag.

Note this change only affects use of the Subzero backend of Reactor.

Bug: chromium:985816
Change-Id: I7ea213cc2b62b64c85c4c46a0d4f28e0bace5d21
Reviewed-on: https://swiftshader-review.googlesource.com/c/SwiftShader/+/34509
Tested-by: Nicolas Capens <nicolascapens@google.com>
Kokoro-Presubmit: kokoro <noreply+kokoro@google.com>
Reviewed-by: Alexis Hétu <sugoi@google.com>
diff --git a/src/Reactor/ExecutableMemory.cpp b/src/Reactor/ExecutableMemory.cpp
index bb1285a..24c83ce 100644
--- a/src/Reactor/ExecutableMemory.cpp
+++ b/src/Reactor/ExecutableMemory.cpp
@@ -194,7 +194,7 @@
 {
 	size_t pageSize = memoryPageSize();
 	size_t length = roundUp(bytes, pageSize);
-	void *mapping;
+	void *mapping = nullptr;
 
 	#if defined(LINUX_ENABLE_NAMED_MMAP)
 		// Try to name the memory region for the executable code,
@@ -237,6 +237,18 @@
 		ASSERT(roundUp(reservation, pageSize) == reservation);
 
 		mapping = reinterpret_cast<void*>(reservation);
+	#elif defined(__APPLE__)
+		// On macOS 10.14 and higher, executables that are code signed with the
+		// "runtime" option cannot execute writable memory by default. They can opt
+		// into this capability by specifying the "com.apple.security.cs.allow-jit"
+		// code signing entitlement and allocating the region with the MAP_JIT flag.
+		mapping = mmap(nullptr, length, PROT_READ | PROT_WRITE,
+		               MAP_PRIVATE | MAP_ANONYMOUS | MAP_JIT, -1, 0);
+
+		if(mapping == MAP_FAILED)
+		{
+			mapping = nullptr;
+		}
 	#else
 		mapping = allocate(length, pageSize);
 	#endif
@@ -267,7 +279,7 @@
 		unsigned long oldProtection;
 		VirtualProtect(memory, bytes, PAGE_READWRITE, &oldProtection);
 		deallocate(memory);
-	#elif defined(LINUX_ENABLE_NAMED_MMAP)
+	#elif defined(LINUX_ENABLE_NAMED_MMAP) || defined(__APPLE__)
 		size_t pageSize = memoryPageSize();
 		size_t length = (bytes + pageSize - 1) & ~(pageSize - 1);
 		munmap(memory, length);
diff --git a/tests/VulkanUnitTests/Driver.cpp b/tests/VulkanUnitTests/Driver.cpp
index 962d946..abcb1ac 100644
--- a/tests/VulkanUnitTests/Driver.cpp
+++ b/tests/VulkanUnitTests/Driver.cpp
@@ -72,7 +72,8 @@
 	#endif
 #elif OS_MAC
 	return load("./build/Darwin/libvk_swiftshader.dylib") ||
-	       load("swiftshader/libvulkan.dylib");
+	       load("swiftshader/libvulkan.dylib") ||
+	       load("libvk_swiftshader.dylib");
 #elif OS_LINUX
 	return load("./build/Linux/libvk_swiftshader.so") ||
 	       load("swiftshader/libvulkan.so") ||