Allow using mmap for shared memory if hw bound check is disabled (#3029)

For shared memory, the max memory size must be defined in advanced. Re-allocation
for growing memory can't be used as it might change the base address, therefore when
OS_ENABLE_HW_BOUND_CHECK is enabled the memory is mmaped, and if the flag is
disabled, the memory is allocated. This change introduces a flag that allows users to use
mmap for reserving memory address space even if the OS_ENABLE_HW_BOUND_CHECK
is disabled.
This commit is contained in:
Marcin Kolny
2024-01-16 14:15:55 +00:00
committed by GitHub
parent b3aaf2abc0
commit ffa131b5ac
12 changed files with 183 additions and 112 deletions

View File

@ -6229,3 +6229,67 @@ wasm_runtime_set_linux_perf(bool flag)
enable_linux_perf = flag;
}
#endif
#ifdef WASM_LINEAR_MEMORY_MMAP
void
wasm_munmap_linear_memory(void *mapped_mem, uint64 commit_size, uint64 map_size)
{
#ifdef BH_PLATFORM_WINDOWS
os_mem_decommit(mapped_mem, commit_size);
#else
(void)commit_size;
#endif
os_munmap(mapped_mem, map_size);
}
void *
wasm_mmap_linear_memory(uint64_t map_size, uint64 *io_memory_data_size,
char *error_buf, uint32 error_buf_size)
{
uint64 page_size = os_getpagesize();
void *mapped_mem = NULL;
uint64 memory_data_size;
bh_assert(io_memory_data_size);
memory_data_size =
(*io_memory_data_size + page_size - 1) & ~(page_size - 1);
if (memory_data_size > UINT32_MAX)
memory_data_size = UINT32_MAX;
if (!(mapped_mem = os_mmap(NULL, map_size, MMAP_PROT_NONE, MMAP_MAP_NONE,
os_get_invalid_handle()))) {
set_error_buf(error_buf, error_buf_size, "mmap memory failed");
goto fail1;
}
#ifdef BH_PLATFORM_WINDOWS
if (memory_data_size > 0
&& !os_mem_commit(mapped_mem, memory_data_size,
MMAP_PROT_READ | MMAP_PROT_WRITE)) {
set_error_buf(error_buf, error_buf_size, "commit memory failed");
os_munmap(mapped_mem, map_size);
goto fail1;
}
#endif
if (os_mprotect(mapped_mem, memory_data_size,
MMAP_PROT_READ | MMAP_PROT_WRITE)
!= 0) {
set_error_buf(error_buf, error_buf_size, "mprotect memory failed");
goto fail2;
}
/* Newly allocated pages are filled with zero by the OS, we don't fill it
* again here */
*io_memory_data_size = memory_data_size;
return mapped_mem;
fail2:
wasm_munmap_linear_memory(mapped_mem, memory_data_size, map_size);
fail1:
return NULL;
}
#endif