From 2615646c203278201e4eff5d8459d5167cde5efd Mon Sep 17 00:00:00 2001 From: Marcin Kolny Date: Fri, 6 Jan 2023 10:21:28 +0000 Subject: [PATCH] Fix on-heap aux stack allocation (#1865) Because stack grows from high address towards low address, the value returned by malloc is the end of the stack, not top of the stack. The top of the stack is the end of the allocated space (i.e. address returned by malloc + cluster size). Refer to #1790. --- core/iwasm/libraries/thread-mgr/thread_manager.c | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/core/iwasm/libraries/thread-mgr/thread_manager.c b/core/iwasm/libraries/thread-mgr/thread_manager.c index ede36ebe..611414a4 100644 --- a/core/iwasm/libraries/thread-mgr/thread_manager.c +++ b/core/iwasm/libraries/thread-mgr/thread_manager.c @@ -83,11 +83,14 @@ allocate_aux_stack(WASMExecEnv *exec_env, uint32 *start, uint32 *size) #if WASM_ENABLE_HEAP_AUX_STACK_ALLOCATION != 0 WASMModuleInstanceCommon *module_inst = wasm_exec_env_get_module_inst(exec_env); + uint32 stack_end; - *start = wasm_runtime_module_malloc(module_inst, cluster->stack_size, NULL); + stack_end = + wasm_runtime_module_malloc(module_inst, cluster->stack_size, NULL); + *start = stack_end + cluster->stack_size; *size = cluster->stack_size; - return *start != 0; + return stack_end != 0; #else uint32 i; @@ -116,15 +119,18 @@ allocate_aux_stack(WASMExecEnv *exec_env, uint32 *start, uint32 *size) static bool free_aux_stack(WASMExecEnv *exec_env, uint32 start) { + WASMCluster *cluster = wasm_exec_env_get_cluster(exec_env); + #if WASM_ENABLE_HEAP_AUX_STACK_ALLOCATION != 0 WASMModuleInstanceCommon *module_inst = wasm_exec_env_get_module_inst(exec_env); - wasm_runtime_module_free(module_inst, start); + bh_assert(start >= cluster->stack_size); + + wasm_runtime_module_free(module_inst, start - cluster->stack_size); return true; #else - WASMCluster *cluster = wasm_exec_env_get_cluster(exec_env); uint32 i; for (i = 0; i < cluster_max_thread_num; i++) {