  {
      se_mutex_lock(&s_device_mutex);
  
-@@ -382,22 +385,38 @@
+@@ -382,22 +385,48 @@
          }
          //The in-kernel driver does not do the base and size alignment. This is up to user mode to do it. 
          //Therefore enclave_size will be virtual_size*2. The unused region will be released by calling munmap later.

     {
         uint64_t aligned_addr = ((uint64_t)enclave_base + virtual_size - 1) & ~(virtual_size - 1);
         if(aligned_addr != (uint64_t)enclave_base)
@@ -784,15 +803,7 @@
 
         enclave_css_t* enclave_css = (enclave_css_t*)enclave_init_sgx->sigstruct;
         if (0 == enclave_css->header.hw_version) {

     {
         hdevice_temp = s_hdevice;
     }
-    
-    void* enclave_base = mmap(base_address, enclave_size, PROT_NONE, MAP_SHARED, hdevice_temp, 0);
+
+    int flag;
+    if (s_driver_type == SGX_DRIVER_IN_KERNEL) {
+      flag = MAP_PRIVATE | MAP_ANONYMOUS;
+    } else {
+      flag = MAP_SHARED;
+    }
+    // If enclave is to be created at a specified address, release that memory
+    // and fix the mapping space.
+    if (base_address)
+    {
+        munmap(base_address, virtual_size);
+        flag |= MAP_FIXED;
+    }
+    void* enclave_base = nullptr;
+    if (s_driver_type == SGX_DRIVER_IN_KERNEL) {
+      enclave_base = mmap(base_address, enclave_size, PROT_NONE, flag, -1, 0);
+    } else {
+      enclave_base = mmap(base_address, enclave_size, PROT_NONE, flag, hdevice_temp, 0);
+    }
     if (enclave_base == MAP_FAILED) {
         SE_TRACE(SE_TRACE_WARNING, "\ncreate enclave: mmap failed, errno = %d\n", errno);
         if (enclave_error != NULL)
