From f8ee05db4bf34e4a3665005eb8a80a7731cefdc4 Mon Sep 17 00:00:00 2001 From: lucianoiam Date: Tue, 22 Mar 2022 10:14:15 +0100 Subject: [PATCH] Add a reference counter to wasm_engine_t (#1001) This patch allows safer (note: safer, not safe) embedding in a plugin environment where multiple instances of the engine could be needed. Original code initializes and tears down the full runtime during wasm_engine_new() and wasm_engine_delete() respectively. After this update the C API implementation keeps track of engine instances count and inits/deinits the runtime only when needed. This allows for example to call wasm_engine_new() twice and then call wasm_engine_delete() once without rendering the first engine instance invalid. --- core/iwasm/common/wasm_c_api.c | 4 +++- core/iwasm/common/wasm_c_api_internal.h | 1 + 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/core/iwasm/common/wasm_c_api.c b/core/iwasm/common/wasm_c_api.c index b19cf75f0..410290711 100644 --- a/core/iwasm/common/wasm_c_api.c +++ b/core/iwasm/common/wasm_c_api.c @@ -320,6 +320,7 @@ wasm_engine_new() singleton_engine = wasm_engine_new_internal(Alloc_With_System_Allocator, NULL); } + singleton_engine->ref_count++; return singleton_engine; } @@ -336,6 +337,7 @@ wasm_engine_new_with_args(mem_alloc_type_t type, const MemAllocOption *opts) if (!singleton_engine) { singleton_engine = wasm_engine_new_internal(type, opts); } + singleton_engine->ref_count++; return singleton_engine; } @@ -343,7 +345,7 @@ wasm_engine_new_with_args(mem_alloc_type_t type, const MemAllocOption *opts) void wasm_engine_delete(wasm_engine_t *engine) { - if (engine) { + if (engine && (--engine->ref_count == 0)) { wasm_engine_delete_internal(engine); singleton_engine = NULL; } diff --git a/core/iwasm/common/wasm_c_api_internal.h b/core/iwasm/common/wasm_c_api_internal.h index d80bd0d68..38954a68e 100644 --- a/core/iwasm/common/wasm_c_api_internal.h +++ b/core/iwasm/common/wasm_c_api_internal.h @@ -27,6 +27,7 @@ WASM_DECLARE_VEC(store, *) struct wasm_engine_t { /* support one store for now */ wasm_store_vec_t *stores; + uint32_t ref_count; }; struct wasm_store_t {