Class NativeStoreBindings
Provides type-safe wrappers for all Wasmtime store lifecycle, fuel management, epoch
deadlines, garbage collection, exception handling, call hooks, and resource limiter native
functions. Hot-path methods use eagerly initialized volatile MethodHandle fields for
invokeExact optimization.
This class follows the singleton pattern with initialization-on-demand holder.
-
Method Summary
Modifier and TypeMethodDescriptionprotected voidaddFunctionBinding(String functionName, FunctionDescriptor descriptor) Registers a native function binding with a given descriptor.<T> TcallNativeFunction(String functionName, Class<T> returnType, Object... args) Calls a native function with type safety.protected Object[]extractValueForNative(ai.tegmentum.wasmtime4j.WasmValue value) Extracts value components from WasmValue for passing to native code.voidfreeBuffer(MemorySegment dataPtr, int len) Frees a byte array buffer allocated by native backtrace capture functions.protected ai.tegmentum.wasmtime4j.panama.NativeBindingsBase.FunctionBindinggetFunctionBinding(String functionName) Gets a registered function binding by name.static NativeStoreBindingsGets the singleton instance.Gets the method handle for adding fuel to a store.Gets the method handle for consuming fuel from a store.Gets the method handle for getting remaining fuel from a store.Gets the method handle for getting hostcall fuel from a store.Gets the method handle for setting epoch deadline in a store.Gets the method handle for setting fuel level in a store.Gets the method handle for setting fuel async yield interval in a store.Gets the method handle for setting hostcall fuel in a store.Gets the method handle for trying to create a store (OOM-safe).Gets the method handle for adding a breakpoint.Gets the method handle for getting breakpoint count.Gets the method handle for retrieving debug exit frames.Gets the method handle for getting debug instance count.Gets the method handle for getting debug module count.Gets the method handle for checking async support.Gets the method handle for checking single-step mode.Gets the method handle for removing a breakpoint.Gets the method handle for setting single-step mode.booleanChecks if the bindings are initialized and available.protected voidMarks this binding set as initialized.intstoreCaptureBacktrace(MemorySegment storePtr, MemorySegment bufferOutPtr, MemorySegment bufferLenOutPtr) Captures backtrace from a WebAssembly store.intstoreClearCallHook(MemorySegment storePtr) Clears the call hook from the store.intstoreClearCallHookAsync(MemorySegment storePtr) Clears the async call hook from the store.intstoreClearDebugHandler(MemorySegment storePtr) Clears the debug handler from the store.intstoreClearEpochDeadlineCallback(MemorySegment storePtr) Clears the epoch deadline callback from the store.storeCreate(MemorySegment enginePtr) Creates a new Wasmtime store.storeCreateForModule(MemorySegment modulePtr) Creates a WebAssembly store that is compatible with a specific module.voidstoreCreateInstanceAsyncBridge(MemorySegment storePtr, MemorySegment modulePtr, MemorySegment callbackStub, long callbackData) Spawns async instance creation on Tokio runtime.voidstoreCreateMemoryAsyncBridge(MemorySegment storePtr, long initialPages, long maxPages, int isShared, int is64, MemorySegment callbackStub, long callbackData) Spawns async memory creation on Tokio runtime.voidstoreCreateTableAsyncBridge(MemorySegment storePtr, int elementType, int initialSize, int maxSize, MemorySegment callbackStub, long callbackData) Spawns async table creation on Tokio runtime.intstoreCreateWithConfig(MemorySegment enginePtr, long fuelLimit, long memoryLimitBytes, long executionTimeoutSecs, int maxInstances, int maxTableElements, int maxTables, int maxMemories, int trapOnGrowFailure, MemorySegment storePtr) Creates a WebAssembly store with custom configuration.voidstoreDestroy(MemorySegment storePtr) Destroys a WebAssembly store.intstoreEpochDeadlineAsyncYieldAndUpdate(MemorySegment storePtr, long deltaTicks) Configures the epoch deadline to async yield and update.intstoreEpochDeadlineTrap(MemorySegment storePtr) Configures the epoch deadline to trap when reached.intstoreForceCaptureBacktrace(MemorySegment storePtr, MemorySegment bufferOutPtr, MemorySegment bufferLenOutPtr) Force captures backtrace from a WebAssembly store.intstoreGc(MemorySegment storePtr) Performs garbage collection on a WebAssembly store.voidstoreGcAsyncBridge(MemorySegment storePtr, MemorySegment callbackStub, long callbackData) Spawns async gc on Tokio runtime.intstoreHasPendingException(MemorySegment storePtr) Checks if the store has a pending exception.intstoreHasWasiContext(MemorySegment storePtr) Checks if a store has WASI context attached.intstoreSetCallHook(MemorySegment storePtr) Sets a call hook on the store.intstoreSetCallHookAsync(MemorySegment storePtr) Sets an async call hook on the store.intstoreSetDebugHandlerFn(MemorySegment storePtr, MemorySegment callbackFn, long callbackId) Sets a debug handler with a function pointer on the store.intstoreSetEpochDeadlineCallbackFn(MemorySegment storePtr, MemorySegment callbackFn, long callbackId) Sets an epoch deadline callback with a function pointer on the store.intstoreSetResourceLimiter(MemorySegment storePtr, long callbackId, MemorySegment memoryGrowingFn, MemorySegment tableGrowingFn, MemorySegment memoryGrowFailedFn, MemorySegment tableGrowFailedFn) Sets a dynamic resource limiter on the store with callback function pointers.intstoreSetResourceLimiterAsync(MemorySegment storePtr, long callbackId, MemorySegment memoryGrowingFn, MemorySegment tableGrowingFn, MemorySegment memoryGrowFailedFn, MemorySegment tableGrowFailedFn) Sets a dynamic async resource limiter on the store with callback function pointers.intstoreSetWasiContext(MemorySegment storePtr, MemorySegment wasiCtxPtr) Sets WASI context on a WebAssembly store.storeTakePendingException(MemorySegment storePtr) Takes and removes the pending exception from the store.protected voidvalidatePointer(MemorySegment pointer, String name) Validates that a pointer is not null.protected voidvalidateSize(long size, String name) Validates that a size is positive.
-
Method Details
-
getInstance
Gets the singleton instance.- Returns:
- the singleton instance
- Throws:
RuntimeException- if initialization fails
-
storeCreate
Creates a new Wasmtime store.- Parameters:
enginePtr- pointer to the engine- Returns:
- memory segment pointer to the store, or null on failure
-
storeCreateForModule
Creates a WebAssembly store that is compatible with a specific module.CRITICAL: This ensures the Store's internal wasmtime::Store uses the SAME Engine Arc as the Module's internal wasmtime::Module. This is required because wasmtime's Instance::new() uses Arc::ptr_eq() to verify engine compatibility.
- Parameters:
modulePtr- pointer to the module- Returns:
- memory segment pointer to the store, or null on failure
-
storeDestroy
Destroys a WebAssembly store.- Parameters:
storePtr- pointer to the store to destroy
-
storeCreateWithConfig
public int storeCreateWithConfig(MemorySegment enginePtr, long fuelLimit, long memoryLimitBytes, long executionTimeoutSecs, int maxInstances, int maxTableElements, int maxTables, int maxMemories, int trapOnGrowFailure, MemorySegment storePtr) Creates a WebAssembly store with custom configuration.- Parameters:
enginePtr- pointer to the enginefuelLimit- the fuel limit (0 = no limit)memoryLimitBytes- the memory limit in bytes (0 = no limit)executionTimeoutSecs- the execution timeout in seconds (0 = no timeout)maxInstances- the maximum number of instances (0 = no limit)maxTableElements- the maximum table elements (0 = no limit)maxTables- the maximum number of tables (0 = no limit)maxMemories- the maximum number of memories (0 = no limit)trapOnGrowFailure- whether growth failures should trap (0 = false, non-zero = true)storePtr- pointer to store the created store (output parameter)- Returns:
- 0 on success, negative error code on failure
-
storeSetWasiContext
Sets WASI context on a WebAssembly store.This function attaches a WASI context to a store, which is required before instantiating modules that import WASI functions.
- Parameters:
storePtr- pointer to the storewasiCtxPtr- pointer to the WASI context- Returns:
- 0 on success, negative error code on failure
-
storeHasWasiContext
Checks if a store has WASI context attached.- Parameters:
storePtr- pointer to the store- Returns:
- 1 if store has WASI context, 0 if not, negative on error
-
storeCaptureBacktrace
public int storeCaptureBacktrace(MemorySegment storePtr, MemorySegment bufferOutPtr, MemorySegment bufferLenOutPtr) Captures backtrace from a WebAssembly store.- Parameters:
storePtr- pointer to the storebufferOutPtr- pointer to store the backtrace buffer pointerbufferLenOutPtr- pointer to store the buffer length- Returns:
- 0 on success, negative error code on failure
-
storeForceCaptureBacktrace
public int storeForceCaptureBacktrace(MemorySegment storePtr, MemorySegment bufferOutPtr, MemorySegment bufferLenOutPtr) Force captures backtrace from a WebAssembly store.- Parameters:
storePtr- pointer to the storebufferOutPtr- pointer to store the backtrace buffer pointerbufferLenOutPtr- pointer to store the buffer length- Returns:
- 0 on success, negative error code on failure
-
freeBuffer
Frees a byte array buffer allocated by native backtrace capture functions.- Parameters:
dataPtr- pointer to the datalen- length of the data in bytes
-
storeGc
Performs garbage collection on a WebAssembly store.This triggers garbage collection to reclaim unreachable GC objects. If GC support is not enabled in the engine configuration, this is a no-op.
- Parameters:
storePtr- pointer to the store- Returns:
- 0 on success, negative error code on failure
-
storeEpochDeadlineAsyncYieldAndUpdate
Configures the epoch deadline to async yield and update.When the epoch deadline is reached, execution will yield back to the async executor and then continue with a new deadline of current epoch + deltaTicks.
- Parameters:
storePtr- pointer to the storedeltaTicks- number of ticks to add for the new deadline- Returns:
- 0 on success, negative error code on failure
-
storeEpochDeadlineTrap
Configures the epoch deadline to trap when reached.When the epoch deadline is reached, execution will trap immediately.
- Parameters:
storePtr- pointer to the store- Returns:
- 0 on success, negative error code on failure
-
storeClearEpochDeadlineCallback
Clears the epoch deadline callback from the store.- Parameters:
storePtr- pointer to the store- Returns:
- 0 on success, negative error code on failure
-
storeSetEpochDeadlineCallbackFn
public int storeSetEpochDeadlineCallbackFn(MemorySegment storePtr, MemorySegment callbackFn, long callbackId) Sets an epoch deadline callback with a function pointer on the store.This allows the Java code to receive callbacks when the epoch deadline is reached and decide whether to continue execution (by returning a positive delta) or trap (by returning a negative value).
- Parameters:
storePtr- pointer to the storecallbackFn- function pointer for the epoch callback (takes callback_id, epoch; returns delta or negative to trap)callbackId- identifier passed to the callback to identify the Java callback- Returns:
- 0 on success, negative error code on failure
-
storeSetDebugHandlerFn
public int storeSetDebugHandlerFn(MemorySegment storePtr, MemorySegment callbackFn, long callbackId) Sets a debug handler with a function pointer on the store.- Parameters:
storePtr- pointer to the storecallbackFn- function pointer for the debug handler callback (takes callback_id, event_code)callbackId- identifier passed to the callback to identify the Java handler- Returns:
- 0 on success, negative error code on failure
-
storeClearDebugHandler
Clears the debug handler from the store.- Parameters:
storePtr- pointer to the store- Returns:
- 0 on success, negative error code on failure
-
storeSetResourceLimiter
public int storeSetResourceLimiter(MemorySegment storePtr, long callbackId, MemorySegment memoryGrowingFn, MemorySegment tableGrowingFn, MemorySegment memoryGrowFailedFn, MemorySegment tableGrowFailedFn) Sets a dynamic resource limiter on the store with callback function pointers.The callbacks are invoked by the Wasmtime runtime each time a memory or table needs to grow, allowing dynamic per-request resource allocation decisions.
- Parameters:
storePtr- pointer to the storecallbackId- identifier passed to callbacks for Java-side dispatchmemoryGrowingFn- function pointer for memory grow decisionstableGrowingFn- function pointer for table grow decisionsmemoryGrowFailedFn- function pointer for memory grow failure notifications (nullable)tableGrowFailedFn- function pointer for table grow failure notifications (nullable)- Returns:
- 0 on success, negative error code on failure
-
storeSetResourceLimiterAsync
public int storeSetResourceLimiterAsync(MemorySegment storePtr, long callbackId, MemorySegment memoryGrowingFn, MemorySegment tableGrowingFn, MemorySegment memoryGrowFailedFn, MemorySegment tableGrowFailedFn) Sets a dynamic async resource limiter on the store with callback function pointers.This is the async counterpart to
storeSetResourceLimiter(java.lang.foreign.MemorySegment, long, java.lang.foreign.MemorySegment, java.lang.foreign.MemorySegment, java.lang.foreign.MemorySegment, java.lang.foreign.MemorySegment). It uses the same callback signatures but registers via the async limiter path in Wasmtime. Requires the engine to be configured with async support.- Parameters:
storePtr- pointer to the storecallbackId- identifier passed to callbacks for Java-side dispatchmemoryGrowingFn- function pointer for memory grow decisionstableGrowingFn- function pointer for table grow decisionsmemoryGrowFailedFn- function pointer for memory grow failure notifications (nullable)tableGrowFailedFn- function pointer for table grow failure notifications (nullable)- Returns:
- 0 on success, negative error code on failure
-
storeTakePendingException
Takes and removes the pending exception from the store.- Parameters:
storePtr- the store pointer- Returns:
- the exception reference pointer, or NULL if no pending exception
-
storeHasPendingException
Checks if the store has a pending exception.- Parameters:
storePtr- the store pointer- Returns:
- 1 if pending exception exists, 0 if not, -1 on error
-
storeSetCallHook
Sets a call hook on the store.- Parameters:
storePtr- the store pointer- Returns:
- 0 on success, non-zero on error
-
storeClearCallHook
Clears the call hook from the store.- Parameters:
storePtr- the store pointer- Returns:
- 0 on success, non-zero on error
-
storeSetCallHookAsync
Sets an async call hook on the store.- Parameters:
storePtr- the store pointer- Returns:
- 0 on success, non-zero on error
-
storeClearCallHookAsync
Clears the async call hook from the store.- Parameters:
storePtr- the store pointer- Returns:
- 0 on success, non-zero on error
-
getPanamaStoreSetFuel
Gets the method handle for setting fuel level in a store.- Returns:
- the method handle, or null if not available
-
getPanamaStoreGetFuel
Gets the method handle for getting remaining fuel from a store.- Returns:
- the method handle, or null if not available
-
getPanamaStoreAddFuel
Gets the method handle for adding fuel to a store.- Returns:
- the method handle, or null if not available
-
getPanamaStoreConsumeFuel
Gets the method handle for consuming fuel from a store.- Returns:
- the method handle, or null if not available
-
getPanamaStoreSetFuelAsyncYieldInterval
Gets the method handle for setting fuel async yield interval in a store.- Returns:
- the method handle, or null if not available
-
getPanamaStoreTryCreate
Gets the method handle for trying to create a store (OOM-safe).- Returns:
- the method handle, or null if not available
-
getPanamaStoreGetHostcallFuel
Gets the method handle for getting hostcall fuel from a store.- Returns:
- the method handle, or null if not available
-
getPanamaStoreSetHostcallFuel
Gets the method handle for setting hostcall fuel in a store.- Returns:
- the method handle, or null if not available
-
getPanamaStoreSetEpochDeadline
Gets the method handle for setting epoch deadline in a store.- Returns:
- the method handle, or null if not available
-
getStoreIsSingleStep
Gets the method handle for checking single-step mode.- Returns:
- the method handle, or null if not available
-
getStoreBreakpointCount
Gets the method handle for getting breakpoint count.- Returns:
- the method handle, or null if not available
-
getStoreSetSingleStep
Gets the method handle for setting single-step mode.- Returns:
- the method handle, or null if not available
-
getStoreAddBreakpoint
Gets the method handle for adding a breakpoint.- Returns:
- the method handle, or null if not available
-
getStoreRemoveBreakpoint
Gets the method handle for removing a breakpoint.- Returns:
- the method handle, or null if not available
-
getStoreIsAsync
Gets the method handle for checking async support.- Returns:
- the method handle, or null if not available
-
getStoreDebugExitFrames
Gets the method handle for retrieving debug exit frames.- Returns:
- the method handle, or null if not available
-
getStoreDebugInstanceCount
Gets the method handle for getting debug instance count.- Returns:
- the method handle, or null if not available
-
getStoreDebugModuleCount
Gets the method handle for getting debug module count.- Returns:
- the method handle, or null if not available
-
storeGcAsyncBridge
public void storeGcAsyncBridge(MemorySegment storePtr, MemorySegment callbackStub, long callbackData) Spawns async gc on Tokio runtime. Callback invoked when complete.- Parameters:
storePtr- pointer to the storecallbackStub- upcall stub for completion callbackcallbackData- opaque ID passed back to callback
-
storeCreateInstanceAsyncBridge
public void storeCreateInstanceAsyncBridge(MemorySegment storePtr, MemorySegment modulePtr, MemorySegment callbackStub, long callbackData) Spawns async instance creation on Tokio runtime. Callback invoked with instance pointer.- Parameters:
storePtr- pointer to the storemodulePtr- pointer to the modulecallbackStub- upcall stub for completion callbackcallbackData- opaque ID passed back to callback
-
storeCreateMemoryAsyncBridge
public void storeCreateMemoryAsyncBridge(MemorySegment storePtr, long initialPages, long maxPages, int isShared, int is64, MemorySegment callbackStub, long callbackData) Spawns async memory creation on Tokio runtime. Callback invoked with memory pointer.- Parameters:
storePtr- pointer to the storeinitialPages- initial size in pagesmaxPages- maximum size in pages (-1 for unlimited)isShared- 1 if shared memory, 0 otherwiseis64- 1 if Memory64, 0 otherwisecallbackStub- upcall stub for completion callbackcallbackData- opaque ID passed back to callback
-
storeCreateTableAsyncBridge
public void storeCreateTableAsyncBridge(MemorySegment storePtr, int elementType, int initialSize, int maxSize, MemorySegment callbackStub, long callbackData) Spawns async table creation on Tokio runtime. Callback invoked with table pointer.- Parameters:
storePtr- pointer to the storeelementType- element type code (0x70=FUNCREF, 0x6F=EXTERNREF)initialSize- initial table sizemaxSize- maximum table size (-1 for unlimited)callbackStub- upcall stub for completion callbackcallbackData- opaque ID passed back to callback
-
markInitialized
protected void markInitialized()Marks this binding set as initialized. Subclasses should call this after registering all function bindings and initializing hot-path MethodHandles. -
isInitialized
public boolean isInitialized()Checks if the bindings are initialized and available.- Returns:
- true if initialized, false otherwise
-
addFunctionBinding
Registers a native function binding with a given descriptor.- Parameters:
functionName- the native function symbol namedescriptor- the Panama FunctionDescriptor for the native function
-
getFunctionBinding
protected ai.tegmentum.wasmtime4j.panama.NativeBindingsBase.FunctionBinding getFunctionBinding(String functionName) Gets a registered function binding by name.- Parameters:
functionName- the native function symbol name- Returns:
- the function binding, or null if not registered
-
callNativeFunction
Calls a native function with type safety.- Parameters:
functionName- the name of the functionreturnType- the expected return typeargs- the function arguments- Returns:
- the function result
- Throws:
IllegalStateException- if the function call fails
-
validatePointer
Validates that a pointer is not null.- Parameters:
pointer- the pointer to validatename- the name of the parameter for error messages- Throws:
IllegalArgumentException- if the pointer is null
-
validateSize
Validates that a size is positive.- Parameters:
size- the size to validatename- the name of the parameter for error messages- Throws:
IllegalArgumentException- if the size is not positive
-
extractValueForNative
Extracts value components from WasmValue for passing to native code.- Parameters:
value- the WasmValue to extract components from- Returns:
- array containing [i32Value, i64Value, f32Value, f64Value, refValue]
-