From c3e9b66b2ac7f09d1f7cd5c318a969123a5c9119 Mon Sep 17 00:00:00 2001 From: Wenyong Huang Date: Fri, 3 Feb 2023 11:15:03 +0800 Subject: [PATCH] Fix jit memory overwritten after instance deinstantiate (#1936) When de-instantiating the wasm module instance, remove it from the module's instance list before freeing func_ptrs and fast_jit_func_ptrs of the instance, to avoid accessing these freed memory in the JIT backend compilation threads. --- core/iwasm/interpreter/wasm_runtime.c | 54 ++++++++++++++------------- 1 file changed, 29 insertions(+), 25 deletions(-) diff --git a/core/iwasm/interpreter/wasm_runtime.c b/core/iwasm/interpreter/wasm_runtime.c index 45356207..eabdea68 100644 --- a/core/iwasm/interpreter/wasm_runtime.c +++ b/core/iwasm/interpreter/wasm_runtime.c @@ -2066,6 +2066,35 @@ wasm_deinstantiate(WASMModuleInstance *module_inst, bool is_sub_inst) if (!module_inst) return; +#if WASM_ENABLE_DEBUG_INTERP != 0 \ + || (WASM_ENABLE_FAST_JIT != 0 && WASM_ENABLE_JIT != 0 \ + && WASM_ENABLE_LAZY_JIT != 0) + /* Remove instance from module's instance list before freeing + func_ptrs and fast_jit_func_ptrs of the instance, to avoid + accessing the freed memory in the jit backend compilation + threads */ + if (!is_sub_inst) { + WASMModule *module = module_inst->module; + WASMModuleInstance *instance_prev = NULL, *instance; + os_mutex_lock(&module->instance_list_lock); + + instance = module->instance_list; + while (instance) { + if (instance == module_inst) { + if (!instance_prev) + module->instance_list = instance->e->next; + else + instance_prev->e->next = instance->e->next; + break; + } + instance_prev = instance; + instance = instance->e->next; + } + + os_mutex_unlock(&module->instance_list_lock); + } +#endif + #if WASM_ENABLE_JIT != 0 if (module_inst->func_ptrs) wasm_runtime_free(module_inst->func_ptrs); @@ -2130,31 +2159,6 @@ wasm_deinstantiate(WASMModuleInstance *module_inst, bool is_sub_inst) } #endif -#if WASM_ENABLE_DEBUG_INTERP != 0 \ - || (WASM_ENABLE_FAST_JIT != 0 && WASM_ENABLE_JIT != 0 \ - && WASM_ENABLE_LAZY_JIT != 0) - if (!is_sub_inst) { - WASMModule *module = module_inst->module; - WASMModuleInstance *instance_prev = NULL, *instance; - os_mutex_lock(&module->instance_list_lock); - - instance = module->instance_list; - while (instance) { - if (instance == module_inst) { - if (!instance_prev) - module->instance_list = instance->e->next; - else - instance_prev->e->next = instance->e->next; - break; - } - instance_prev = instance; - instance = instance->e->next; - } - - os_mutex_unlock(&module->instance_list_lock); - } -#endif - #if WASM_ENABLE_SHARED_MEMORY != 0 if (module_inst->e->mem_lock_inited) os_mutex_destroy(&module_inst->e->mem_lock);