wasm-micro-runtime icon indicating copy to clipboard operation
wasm-micro-runtime copied to clipboard

wasm-c-api: Register wasm-c-api function imports before calling post-instantiate functions

Open elliotsayes opened this issue 11 months ago • 2 comments

Feature

Currently, when calling wasm-c-api's wasm_instance_new* function, the wasm runtime is first instantiated with wasm_runtime_instantiate_ex, and later on the c_api_func_imports are registered to the instance. However, during the runtime instantiation process, some special wasm "post instantiate" functions are called (via execute_post_instantiate_functions), such as __post_instantiate and __wasm_call_ctors.

This feature proposes deferring the execution of those "post instantiate" functions until after the c_api_func_imports are registered.

Benefit

In some circumstances, the "post instantiate" functions might rely on the wasm-c-api function imports, and the instantiation to fail since they are not yet registered. By deferring the execution of the "post instantiate" functions until after the c_api_func_imports are registered, will can now be called successfully.

Implementation

Add a boolean parameter to wasm_instantiate to disable instantiation functions, and call execute_post_instantiate_functions later on in wasm-c-api's wasm_instance_new* function.

Alternatives

Open to any other alternatives that would achieve the same result.

Happy to make a PR for this if it passes the smell test :)

elliotsayes avatar Feb 07 '25 07:02 elliotsayes

Thank you for pointing out the issue.

Regarding the implementation, I have a different idea. The main goal is to preserve the current function signatures as much as possible. My suggestion is to shift the creation of c_api_func_imports and assignment of values into functions_instantiate().

Given that u.function.call_conv_wasm_c_api can serve as an indicator (in interp_link_func() and aot_link_func()), it seems feasible to gather sufficient information from the WASMModule to construct c_api_func_imports correctly.

lum1n0us avatar Feb 08 '25 07:02 lum1n0us

Hi @lum1n0us, I took a stab at your suggestion but didn't get too far. It seems like functions_instantiate() is not called inside aot_instantiate(), so unless I'm missing something I don't think that approach would work in AOT mode. Would I also have to add it into aot_runtime.c's init_func_ptrs() function? I may be getting a bit above my head 😅

elliotsayes avatar Feb 11 '25 08:02 elliotsayes