Class NativeStoreBindings

java.lang.Object
ai.tegmentum.wasmtime4j.panama.NativeStoreBindings

public final class NativeStoreBindings extends Object
Native function bindings for Store operations.

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 Details

    • getInstance

      public static NativeStoreBindings getInstance()
      Gets the singleton instance.
      Returns:
      the singleton instance
      Throws:
      RuntimeException - if initialization fails
    • storeCreate

      public MemorySegment storeCreate(MemorySegment enginePtr)
      Creates a new Wasmtime store.
      Parameters:
      enginePtr - pointer to the engine
      Returns:
      memory segment pointer to the store, or null on failure
    • storeCreateForModule

      public MemorySegment storeCreateForModule(MemorySegment modulePtr)
      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

      public void storeDestroy(MemorySegment storePtr)
      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 engine
      fuelLimit - 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

      public int storeSetWasiContext(MemorySegment storePtr, MemorySegment wasiCtxPtr)
      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 store
      wasiCtxPtr - pointer to the WASI context
      Returns:
      0 on success, negative error code on failure
    • storeHasWasiContext

      public int storeHasWasiContext(MemorySegment storePtr)
      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 store
      bufferOutPtr - pointer to store the backtrace buffer pointer
      bufferLenOutPtr - 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 store
      bufferOutPtr - pointer to store the backtrace buffer pointer
      bufferLenOutPtr - pointer to store the buffer length
      Returns:
      0 on success, negative error code on failure
    • freeBuffer

      public void freeBuffer(MemorySegment dataPtr, int len)
      Frees a byte array buffer allocated by native backtrace capture functions.
      Parameters:
      dataPtr - pointer to the data
      len - length of the data in bytes
    • storeGc

      public int storeGc(MemorySegment storePtr)
      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

      public int storeEpochDeadlineAsyncYieldAndUpdate(MemorySegment storePtr, long deltaTicks)
      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 store
      deltaTicks - number of ticks to add for the new deadline
      Returns:
      0 on success, negative error code on failure
    • storeEpochDeadlineTrap

      public int storeEpochDeadlineTrap(MemorySegment storePtr)
      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

      public int storeClearEpochDeadlineCallback(MemorySegment storePtr)
      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 store
      callbackFn - 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 store
      callbackFn - 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

      public int storeClearDebugHandler(MemorySegment storePtr)
      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 store
      callbackId - identifier passed to callbacks for Java-side dispatch
      memoryGrowingFn - function pointer for memory grow decisions
      tableGrowingFn - function pointer for table grow decisions
      memoryGrowFailedFn - 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 store
      callbackId - identifier passed to callbacks for Java-side dispatch
      memoryGrowingFn - function pointer for memory grow decisions
      tableGrowingFn - function pointer for table grow decisions
      memoryGrowFailedFn - 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

      public MemorySegment storeTakePendingException(MemorySegment storePtr)
      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

      public int storeHasPendingException(MemorySegment storePtr)
      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

      public int storeSetCallHook(MemorySegment storePtr)
      Sets a call hook on the store.
      Parameters:
      storePtr - the store pointer
      Returns:
      0 on success, non-zero on error
    • storeClearCallHook

      public int storeClearCallHook(MemorySegment storePtr)
      Clears the call hook from the store.
      Parameters:
      storePtr - the store pointer
      Returns:
      0 on success, non-zero on error
    • storeSetCallHookAsync

      public int storeSetCallHookAsync(MemorySegment storePtr)
      Sets an async call hook on the store.
      Parameters:
      storePtr - the store pointer
      Returns:
      0 on success, non-zero on error
    • storeClearCallHookAsync

      public int storeClearCallHookAsync(MemorySegment storePtr)
      Clears the async call hook from the store.
      Parameters:
      storePtr - the store pointer
      Returns:
      0 on success, non-zero on error
    • getPanamaStoreSetFuel

      public MethodHandle getPanamaStoreSetFuel()
      Gets the method handle for setting fuel level in a store.
      Returns:
      the method handle, or null if not available
    • getPanamaStoreGetFuel

      public MethodHandle getPanamaStoreGetFuel()
      Gets the method handle for getting remaining fuel from a store.
      Returns:
      the method handle, or null if not available
    • getPanamaStoreAddFuel

      public MethodHandle getPanamaStoreAddFuel()
      Gets the method handle for adding fuel to a store.
      Returns:
      the method handle, or null if not available
    • getPanamaStoreConsumeFuel

      public MethodHandle getPanamaStoreConsumeFuel()
      Gets the method handle for consuming fuel from a store.
      Returns:
      the method handle, or null if not available
    • getPanamaStoreSetFuelAsyncYieldInterval

      public MethodHandle getPanamaStoreSetFuelAsyncYieldInterval()
      Gets the method handle for setting fuel async yield interval in a store.
      Returns:
      the method handle, or null if not available
    • getPanamaStoreTryCreate

      public MethodHandle getPanamaStoreTryCreate()
      Gets the method handle for trying to create a store (OOM-safe).
      Returns:
      the method handle, or null if not available
    • getPanamaStoreGetHostcallFuel

      public MethodHandle getPanamaStoreGetHostcallFuel()
      Gets the method handle for getting hostcall fuel from a store.
      Returns:
      the method handle, or null if not available
    • getPanamaStoreSetHostcallFuel

      public MethodHandle getPanamaStoreSetHostcallFuel()
      Gets the method handle for setting hostcall fuel in a store.
      Returns:
      the method handle, or null if not available
    • getPanamaStoreSetEpochDeadline

      public MethodHandle getPanamaStoreSetEpochDeadline()
      Gets the method handle for setting epoch deadline in a store.
      Returns:
      the method handle, or null if not available
    • getStoreIsSingleStep

      public MethodHandle getStoreIsSingleStep()
      Gets the method handle for checking single-step mode.
      Returns:
      the method handle, or null if not available
    • getStoreBreakpointCount

      public MethodHandle getStoreBreakpointCount()
      Gets the method handle for getting breakpoint count.
      Returns:
      the method handle, or null if not available
    • getStoreSetSingleStep

      public MethodHandle getStoreSetSingleStep()
      Gets the method handle for setting single-step mode.
      Returns:
      the method handle, or null if not available
    • getStoreAddBreakpoint

      public MethodHandle getStoreAddBreakpoint()
      Gets the method handle for adding a breakpoint.
      Returns:
      the method handle, or null if not available
    • getStoreRemoveBreakpoint

      public MethodHandle getStoreRemoveBreakpoint()
      Gets the method handle for removing a breakpoint.
      Returns:
      the method handle, or null if not available
    • getStoreIsAsync

      public MethodHandle getStoreIsAsync()
      Gets the method handle for checking async support.
      Returns:
      the method handle, or null if not available
    • getStoreDebugExitFrames

      public MethodHandle getStoreDebugExitFrames()
      Gets the method handle for retrieving debug exit frames.
      Returns:
      the method handle, or null if not available
    • getStoreDebugInstanceCount

      public MethodHandle getStoreDebugInstanceCount()
      Gets the method handle for getting debug instance count.
      Returns:
      the method handle, or null if not available
    • getStoreDebugModuleCount

      public MethodHandle 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 store
      callbackStub - upcall stub for completion callback
      callbackData - 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 store
      modulePtr - pointer to the module
      callbackStub - upcall stub for completion callback
      callbackData - 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 store
      initialPages - initial size in pages
      maxPages - maximum size in pages (-1 for unlimited)
      isShared - 1 if shared memory, 0 otherwise
      is64 - 1 if Memory64, 0 otherwise
      callbackStub - upcall stub for completion callback
      callbackData - 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 store
      elementType - element type code (0x70=FUNCREF, 0x6F=EXTERNREF)
      initialSize - initial table size
      maxSize - maximum table size (-1 for unlimited)
      callbackStub - upcall stub for completion callback
      callbackData - 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

      protected void addFunctionBinding(String functionName, FunctionDescriptor descriptor)
      Registers a native function binding with a given descriptor.
      Parameters:
      functionName - the native function symbol name
      descriptor - 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

      public <T> T callNativeFunction(String functionName, Class<T> returnType, Object... args)
      Calls a native function with type safety.
      Parameters:
      functionName - the name of the function
      returnType - the expected return type
      args - the function arguments
      Returns:
      the function result
      Throws:
      IllegalStateException - if the function call fails
    • validatePointer

      protected void validatePointer(MemorySegment pointer, String name)
      Validates that a pointer is not null.
      Parameters:
      pointer - the pointer to validate
      name - the name of the parameter for error messages
      Throws:
      IllegalArgumentException - if the pointer is null
    • validateSize

      protected void validateSize(long size, String name)
      Validates that a size is positive.
      Parameters:
      size - the size to validate
      name - the name of the parameter for error messages
      Throws:
      IllegalArgumentException - if the size is not positive
    • extractValueForNative

      protected Object[] extractValueForNative(ai.tegmentum.wasmtime4j.WasmValue value)
      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]