Quellcode durchsuchen

fix: missing locks in wasm_c_api (#4881)

- add missing lock in check_loaded_module()
- add missing lock in wasm_module_exports()
- add missing lock in wasm_module_serialize()
liang.he vor 1 Monat
Ursprung
Commit
4547587f60
1 geänderte Dateien mit 25 neuen und 9 gelöschten Zeilen
  1. 25 9
      core/iwasm/common/wasm_c_api.c

+ 25 - 9
core/iwasm/common/wasm_c_api.c

@@ -2206,12 +2206,15 @@ check_loaded_module(Vector *modules, char *binary_hash)
             return NULL;
         }
 
-        if (!module->ref_count)
-            /* deleted */
-            continue;
+        os_mutex_lock(&module->lock);
+        bool is_valid =
+            (module->ref_count > 0
+             && memcmp(module->hash, binary_hash, SHA256_DIGEST_LENGTH) == 0);
+        os_mutex_unlock(&module->lock);
 
-        if (memcmp(module->hash, binary_hash, SHA256_DIGEST_LENGTH) == 0)
+        if (is_valid) {
             return module;
+        }
     }
     return NULL;
 }
@@ -2456,8 +2459,13 @@ wasm_module_imports(const wasm_module_t *module, own wasm_importtype_vec_t *out)
         return;
     }
 
-    if (((const wasm_module_ex_t *)(module))->ref_count == 0)
+    wasm_module_ex_t *module_ex = module_to_module_ext((wasm_module_t *)module);
+    os_mutex_lock(&module_ex->lock);
+    if (module_ex->ref_count == 0) {
+        os_mutex_unlock(&module_ex->lock);
         return;
+    }
+    os_mutex_unlock(&module_ex->lock);
 
 #if WASM_ENABLE_INTERP != 0
     if ((*module)->module_type == Wasm_Module_Bytecode) {
@@ -2696,8 +2704,13 @@ wasm_module_exports(const wasm_module_t *module, wasm_exporttype_vec_t *out)
         return;
     }
 
-    if (((const wasm_module_ex_t *)(module))->ref_count == 0)
+    wasm_module_ex_t *module_ex = module_to_module_ext((wasm_module_t *)module);
+    os_mutex_lock(&module_ex->lock);
+    if (module_ex->ref_count == 0) {
+        os_mutex_unlock(&module_ex->lock);
         return;
+    }
+    os_mutex_unlock(&module_ex->lock);
 
 #if WASM_ENABLE_INTERP != 0
     if ((*module)->module_type == Wasm_Module_Bytecode) {
@@ -2891,10 +2904,13 @@ wasm_module_serialize(wasm_module_t *module, own wasm_byte_vec_t *out)
     if (!module || !out)
         return;
 
-    if (((const wasm_module_ex_t *)(module))->ref_count == 0)
-        return;
-
     module_ex = module_to_module_ext(module);
+    os_mutex_lock(&module_ex->lock);
+    if (module_ex->ref_count == 0) {
+        os_mutex_unlock(&module_ex->lock);
+        return;
+    }
+    os_mutex_unlock(&module_ex->lock);
     comp_ctx = ((WASMModule *)(module_ex->module_comm_rt))->comp_ctx;
     comp_data = ((WASMModule *)(module_ex->module_comm_rt))->comp_data;
     bh_assert(comp_ctx != NULL && comp_data != NULL);