VOOZH about

URL: https://bytecodealliance.github.io/wasmtime-py/

⇱ wasmtime API documentation


Python bindings for the Wasmtime project

This library binds the Wasmtime project's C API to provide an implementation of a WebAssembly JIT compiler to Python. You can validate, compile, instantiate, and interact with WebAssembly modules via this library.

The API of this library is intended to be very similar to the wasmtime Rust crate, so if you find the docs are lacking here feel free to consult that documentation as well. While not exactly the same the two libraries are intended to be quite similar.

Sub-modules

wasmtime.component

Functions

def wat2wasm(wat: str | bytes) ‑> bytearray

Converts the WebAssembly Text format to the binary format.

This function is intended to be a convenience function for local development and you likely don't want to use it extensively in production. It's much faster to parse and compile the binary format than it is to process the text format.

Takes a str as input, raises an error if it fails to parse, and returns a bytes if conversion/parsing was successful.

>>> wat2wasm('(module)')
bytearray(b'\x00asm\x01\x00\x00\x00')

Classes

class Caller (ptr: ctypes._Pointer[ffi.wasmtime_caller_t])

Methods

def get(self, name: str) ‑> Func | Table | Memory | SharedMemory | Global | Tag | None

Looks up an export with name on the calling module.

May return None if the export isn't found, if it's not a memory (for now), or if the caller has gone away and this Caller object has persisted too long.

class Config

Global configuration, used to create an Engine.

A Config houses a number of configuration options which tweaks how wasm code is compiled or generated.

Ancestors

  • wasmtime._managed.Managed
  • typing.Generic

Instance variables

prop cache

Configures whether code caching is enabled for this Config.

The value True can be passed in here to enable the default caching configuration and location, or a path to a file can be passed in which is a path to a TOML configuration file for the cache.

More information about cache configuration can be found at https://bytecodealliance.github.io/wasmtime/cli-cache.html

 Note that this field can only be set, it cannot be read
prop consume_fuel

Configures whether wasm code will consume fuel as part of its execution.

Fuel consumption allows WebAssembly to trap when fuel runs out. Currently stores start with 0 fuel if this is enabled.

 Note that this field can only be set, it cannot be read
prop cranelift_debug_verifier
prop cranelift_nan_canonicalization

Configures whether Cranelift should perform a NaN-canonicalization pass.

This replaces NaNs with a single canonical value for fully deterministic WebAssembly execution. Not required by the spec; disabled by default.

 Note that this field can only be set, it cannot be read
prop cranelift_opt_level
prop debug_info

Configures whether DWARF debug information is emitted for the generated code. This can improve profiling and the debugging experience.

 Note that this field can only be set, it cannot be read
prop epoch_interruption

Configures whether wasm execution can be interrupted via epoch increments.

 Note that this field can only be set, it cannot be read
prop gc_support

Enables or disables GC support in Wasmtime entirely.

This defaults to True.

 Note that this field can only be set, it cannot be read
prop macos_use_mach_ports

Configures whether Mach ports are used for exception handling on macOS instead of traditional Unix signal handling.

This defaults to True on macOS.

 Note that this field can only be set, it cannot be read
prop max_wasm_stack

Configures the maximum stack size, in bytes, that JIT code can use.

This defaults to 2MB. Configuring this can help if you hit stack overflow or want to limit wasm stack usage.

Note that if this limit is set too high then the OS's stack guards may be hit which will result in an uncaught segfault. This limit can only be set to a size that's smaller than the actual OS stack, and that's not something able to be dynamically determined, so it's the responsibility of embedders to uphold this invariant.

 Note that this field can only be set, it cannot be read
prop memory_guard_size

Configures the guard region size, in bytes, for linear memory.

For more information see the Rust documentation at https://bytecodealliance.github.io/wasmtime/api/wasmtime/struct.Config.html#method.memory_guard_size

 Note that this field can only be set, it cannot be read
prop memory_init_cow

Configures whether copy-on-write memory-mapped data is used to initialize linear memory.

This can significantly improve instantiation performance. Defaults to True.

 Note that this field can only be set, it cannot be read
prop memory_may_move

Configures whether memory_reservation is the maximal size of linear memory (disabling movement) or whether linear memories may be moved to a new location when they need to grow.

 Note that this field can only be set, it cannot be read
prop memory_reservation

Configures the initial memory reservation size, in bytes, for linear memories.

For more information see the Rust documentation at https://bytecodealliance.github.io/wasmtime/api/wasmtime/struct.Config.html#method.memory_reservation

 Note that this field can only be set, it cannot be read
prop memory_reservation_for_growth

Configures the size, in bytes, of extra virtual memory reserved for memories to grow into after being relocated.

For more information see the Rust documentation at https://docs.wasmtime.dev/api/wasmtime/struct.Config.html#method.memory_reservation_for_growth

 Note that this field can only be set, it cannot be read
prop native_unwind_info

Configures whether to generate native unwind information (e.g. .eh_frame on Linux).

This defaults to True.

 Note that this field can only be set, it cannot be read
prop parallel_compilation

Configures whether parallel compilation is enabled for functions within a module.

This is enabled by default.

 Note that this field can only be set, it cannot be read
prop profiler

Configures the profiling strategy used for JIT code.

Acceptable values for profiler are:

  • "none"
  • "jitdump"
  • "vtune"
  • "perfmap"
    Note that this field can only be set, it cannot be read
    
prop shared_memory

Configures whether shared memories can be created.

This is disabled by default.

 Note that this field can only be set, it cannot be read
prop signals_based_traps

Configures whether signals-based trap handlers are enabled (e.g. SIGILL and SIGSEGV on Unix platforms).

This defaults to True.

 Note that this field can only be set, it cannot be read
prop strategy

Configures the compilation strategy used for wasm code.

Acceptable values for strategy are:

  • "auto"
  • "cranelift"
    Note that this field can only be set, it cannot be read
    
prop target

Configures the target triple that this configuration will produce machine code for.

Defaults to the native host. Setting this also disables automatic inference of native CPU features.

Raises a WasmtimeError if the target triple is not recognized.

Note that if this is set to something other than the host then an Engine created won't be able to run generated code, but it can still be used to compile code.

 Note that this field can only be set, it cannot be read
prop wasm_bulk_memory

Configures whether the wasm bulk memory proposal is enabled.

 Note that this field can only be set, it cannot be read
prop wasm_component_model

Configures whether the WebAssembly component model proposal is enabled.

 Note that this field can only be set, it cannot be read
prop wasm_component_model_map

Configures whether the WebAssembly component model map types proposal is enabled.

 Note that this field can only be set, it cannot be read
prop wasm_custom_page_sizes

Configures whether the wasm custom-page-sizes proposal is enabled.

 Note that this field can only be set, it cannot be read
prop wasm_exceptions

Configures whether the wasm exceptions proposal is enabled.

 Note that this field can only be set, it cannot be read
prop wasm_function_references

Configures whether the wasm typed function references proposal is enabled.

 Note that this field can only be set, it cannot be read
prop wasm_gc

Configures whether the wasm GC proposal is enabled.

 Note that this field can only be set, it cannot be read
prop wasm_memory64

Configures whether the wasm memory64 proposal is enabled.

 Note that this field can only be set, it cannot be read
prop wasm_multi_memory

Configures whether the wasm multi memory proposal is enabled.

 Note that this field can only be set, it cannot be read
prop wasm_multi_value

Configures whether the wasm multi value proposal is enabled.

 Note that this field can only be set, it cannot be read
prop wasm_reference_types

Configures whether the wasm reference types proposal is enabled.

 Note that this field can only be set, it cannot be read
prop wasm_relaxed_simd

Configures whether the wasm relaxed simd proposal is enabled.

 Note that this field can only be set, it cannot be read
prop wasm_relaxed_simd_deterministic

Configures whether the wasm relaxed simd proposal is deterministic in is execution as opposed to having the most optimal implementation for the current platform.

 Note that this field can only be set, it cannot be read
prop wasm_simd

Configures whether the wasm SIMD proposal is enabled.

 Note that this field can only be set, it cannot be read
prop wasm_stack_switching

Configures whether the wasm stack switching proposal is enabled.

 Note that this field can only be set, it cannot be read
prop wasm_tail_call

Configures whether the wasm tail call proposal is enabled.

 Note that this field can only be set, it cannot be read
prop wasm_threads

Configures whether the wasm threads proposal is enabled.

 Note that this field can only be set, it cannot be read
prop wasm_wide_arithmetic

Configures whether the wasm wide arithmetic proposal is enabled.

 Note that this field can only be set, it cannot be read

Methods

def cranelift_flag_enable(self, flag: str) ‑> None

Enables a target-specific flag in Cranelift.

This can be used to enable CPU features such as SSE4.2 on x86_64 hosts. Available flags can be explored with wasmtime settings.

def cranelift_flag_set(self, key: str, value: str) ‑> None

Sets a target-specific flag in Cranelift to the specified value.

This can be used to configure CPU features such as SSE4.2 on x86_64 hosts. Available flags can be explored with wasmtime settings.

class DirPerms (*values)

Create a collection of name/value pairs.

Example enumeration:

>>> class Color(Enum):
... RED = 1
... BLUE = 2
... GREEN = 3

Access them by:

  • attribute access:

Color.RED

  • value lookup:

Color(1)

  • name lookup:

Color['RED']

Enumerations can be iterated over, and know how many members they have:

>>> len(Color)
3
>>> list(Color)
[<Color.RED: 1>, <Color.BLUE: 2>, <Color.GREEN: 3>]

Methods can be added to enumerations, and members can have their own attributes – see the documentation for details.

Ancestors

  • enum.Enum

Class variables

var READ_ONLY

The type of the None singleton.

var READ_WRITE

The type of the None singleton.

var WRITE_ONLY

The type of the None singleton.

class Engine (config: wasmtime._config.Config | None = None)

Abstract base class for types which contain an owned pointer in the C FFI layer.

Not exported directly from this package.

Ancestors

  • wasmtime._managed.Managed
  • typing.Generic

Methods

def increment_epoch(self) ‑> None
def is_pulley(self) ‑> bool
class ExitTrap (message: str)

A special type of WasmtimeError which represents the process exiting via WASI's proc_exit function call.

Whenever a WASI program exits via proc_exit a trap is raised, but the trap will have this type instead of WasmtimeError, so you can catch just this type instead of all traps (if desired). Exit traps have a code associated with them which is the exit code provided at exit.

Note that ExitTrap is a subclass of WasmtimeError, so if you catch a trap you'll also catch ExitTrap.

Ancestors

  • wasmtime._error.WasmtimeError
  • builtins.Exception
  • builtins.BaseException
  • wasmtime._managed.Managed
  • typing.Generic

Class variables

var code : int

The type of the None singleton.

class ExportType

Abstract base class for types which contain an owned pointer in the C FFI layer.

Not exported directly from this package.

Ancestors

  • wasmtime._managed.Managed
  • typing.Generic

Instance variables

prop name : str

Returns the name in the modulethis export type refers to

prop type : AsExternType

Returns the type that this export refers to

class FilePerms (*values)

Create a collection of name/value pairs.

Example enumeration:

>>> class Color(Enum):
... RED = 1
... BLUE = 2
... GREEN = 3

Access them by:

  • attribute access:

Color.RED

  • value lookup:

Color(1)

  • name lookup:

Color['RED']

Enumerations can be iterated over, and know how many members they have:

>>> len(Color)
3
>>> list(Color)
[<Color.RED: 1>, <Color.BLUE: 2>, <Color.GREEN: 3>]

Methods can be added to enumerations, and members can have their own attributes – see the documentation for details.

Ancestors

  • enum.Enum

Class variables

var READ_ONLY

The type of the None singleton.

var READ_WRITE

The type of the None singleton.

var WRITE_ONLY

The type of the None singleton.

class Frame

Abstract base class for types which contain an owned pointer in the C FFI layer.

Not exported directly from this package.

Ancestors

  • wasmtime._managed.Managed
  • typing.Generic

Instance variables

prop func_index : int

Returns the function index this frame corresponds to in its wasm module

prop func_name : str | None

Returns the name of the function this frame corresponds to

May return None if no name can be inferred

prop func_offset : int

Returns the offset of this frame's program counter into the original wasm function.

prop module_name : str | None

Returns the name of the module this frame corresponds to

May return None if no name can be inferred

prop module_offset : int

Returns the offset of this frame's program counter into the original wasm source module.

class Func (store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext,
ty: wasmtime._types.FuncType,
func: Callable,
access_caller: bool = False)

Creates a new func in store with the given ty which calls the closure given

The func is called with the parameters natively and they'll have native Python values rather than being wrapped in Val. If access_caller is set to True then the first argument given to func is an instance of type Caller below.

Methods

def type(self,
store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext) ‑> wasmtime._types.FuncType

Gets the type of this func as a FuncType

class FuncType (params: List[wasmtime._types.ValType], results: List[wasmtime._types.ValType])

Abstract base class for types which contain an owned pointer in the C FFI layer.

Not exported directly from this package.

Ancestors

  • wasmtime._managed.Managed
  • typing.Generic

Instance variables

prop params : List[ValType]

Returns the list of parameter types for this function type

prop results : List[ValType]

Returns the list of result types for this function type

class Global (store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext,
ty: wasmtime._types.GlobalType,
val: Any)

Methods

def set_value(self,
store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext,
val: Any)

Sets the value of this global to a new value

def type(self,
store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext) ‑> wasmtime._types.GlobalType

Gets the type of this global as a GlobalType

def value(self,
store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext) ‑> Any

Gets the current value of this global

Returns a native python type

class GlobalType (valtype: wasmtime._types.ValType, mutable: bool)

Abstract base class for types which contain an owned pointer in the C FFI layer.

Not exported directly from this package.

Ancestors

  • wasmtime._managed.Managed
  • typing.Generic

Instance variables

prop content : wasmtime._types.ValType

Returns the type this global contains

prop mutable : bool

Returns whether this global is mutable or not

class ImportType

Abstract base class for types which contain an owned pointer in the C FFI layer.

Not exported directly from this package.

Ancestors

  • wasmtime._managed.Managed
  • typing.Generic

Instance variables

prop module : str

Returns the module this import type refers to

prop name : str | None

Returns the name in the module this import type refers to

Note that None may be returned for the module linking proposal where the field name is optional.

prop type : AsExternType

Returns the type that this import refers to

class Instance (store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext,
module: wasmtime._module.Module,
imports: Sequence[Func | Table | Memory | SharedMemory | Global | Tag])

Creates a new instance by instantiating the module given with the imports into the store provided.

The store must have type Store, the module must have type Module, and the imports must be an iterable of external values, either Extern, Func, Table, Memory, or Global.

Raises an error if instantiation fails (e.g. linking or trap) and otherwise initializes the new instance.

Methods

def exports(self,
store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext) ‑> InstanceExports

Returns the exports of this module

The returned type can be indexed both with integers and with strings for names of exports.

class InstancePre

A pre-instantiated module with all imports already satisfied.

InstancePre allows you to skip the import-resolution step on every call to instantiate, which can improve performance when creating many instances of the same module.

Created via Linker.instantiate_pre().

Ancestors

  • wasmtime._managed.Managed
  • typing.Generic

Instance variables

prop module : wasmtime._module.Module

Returns the Module that this InstancePre was created from.

Methods

def instantiate(self,
store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext) ‑> wasmtime._instance.Instance

Instantiates the pre-linked module in the given store.

Raises a WasmtimeError on error or a Trap if a trap occurs during instantiation.

class Limits (min: int, max: int | None)
class Linker (engine: wasmtime._engine.Engine)

Abstract base class for types which contain an owned pointer in the C FFI layer.

Not exported directly from this package.

Creates a new linker ready to instantiate modules within the store provided.

Ancestors

  • wasmtime._managed.Managed
  • typing.Generic

Class variables

var engine : wasmtime._engine.Engine

The type of the None singleton.

Instance variables

prop allow_shadowing

Configures whether definitions are allowed to shadow one another within this linker

 Note that this field can only be set, it cannot be read

Methods

def define(self,
store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext,
module: str,
name: str,
item: Func | Table | Memory | SharedMemory | Global | Tag)

Defines a new item, by name, in this linker.

This method will add a new definition to this linker. The module nad name provided are what to name the item within the linker.

This function will raise an error if item comes from the wrong store or if shadowing is disallowed and the module/name pair has already been defined.

def define_func(self,
module: str,
name: str,
ty: wasmtime._types.FuncType,
func: Callable[..., Any],
access_caller: bool = False) ‑> None

Defines a new function, by name, in this linker.

This method is similar to define except that you can directly define a function without creating a Func itself. This enables Store-independent functions to be inserted into this linker, meaning the linker can be used to instantiate modules in multiple stores.

def define_instance(self,
store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext,
name: str,
instance: wasmtime._instance.Instance)

Convenience wrapper to define an entire instance in this linker.

This function will define eaech of the exports on the instance into this linker, using the name provided as the module name and the export's own name as the field name.

This function will raise an error if instance comes from the wrong store or if shadowing is disallowed and a name was previously defined.

def define_module(self,
store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext,
name: str,
module: wasmtime._module.Module)

Defines automatic instantiations of the provided module in this linker.

The module provided is defined under name with automatic instantiations which respect WASI Commands and Reactors.

For more information see the Rust documentation at https://docs.wasmtime.dev/api/wasmtime/struct.Linker.html#method.module.

This method will throw an error if shadowing is disallowed and an item has previously been defined.

def define_unknown_imports_as_default_values(self,
store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext,
module: wasmtime._module.Module)

Defines all currently-unknown imports of module as default values (zero for numerics, null for references, etc.).

This is similar to define_unknown_imports_as_traps but instead of trapping the imported functions return appropriate zero/default values.

def define_unknown_imports_as_traps(self, module: wasmtime._module.Module) ‑> None

Defines all currently-unknown imports of module as functions that unconditionally trap when called.

This is useful when you want to instantiate a module whose imports aren't fully known yet and are willing to trap on any call to an unresolved import.

def define_wasi(self) ‑> None

Defines a WASI instance in this linker.

The instance provided has been previously constructed and this method will define all the appropriate imports and their names into this linker to assist with instantiating modules that use WASI.

This function will raise an error if shadowing is disallowed and a name was previously defined.

def get(self,
store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext,
module: str,
name: str) ‑> Func | Table | Memory | SharedMemory | Global | Tag

Gets a singular item defined in this linker.

Raises an error if this item hasn't been defined or if the item has been defined twice with different types.

def get_default(self,
store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext,
name: str) ‑> wasmtime._func.Func

Gets the default export for the named module in this linker.

For more information on this see the Rust documentation at https://docs.wasmtime.dev/api/wasmtime/struct.Linker.html#method.get_default.

Raises an error if the default export wasn't present.

def instantiate(self,
store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext,
module: wasmtime._module.Module) ‑> wasmtime._instance.Instance

Instantiates a module using this linker's defined set of names.

This method will attempt to satisfy all the imports of the module provided with the names defined within this linker. If all names are defined then the module is instantiated.

Raises an error if an import of module hasn't been defined in this linker or if a trap happens while instantiating the instance.

def instantiate_pre(self, module: wasmtime._module.Module) ‑> wasmtime._instance_pre.InstancePre

Pre-instantiates module by resolving all of its imports from the definitions in this linker.

Returns an InstancePre that can be used to cheaply create multiple instances of the same module without repeating import resolution.

Raises WasmtimeError if any imports are unresolvable.

class Memory (store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext,
ty: wasmtime._types.MemoryType)

Creates a new memory in store with the given ty

Methods

def data_len(self,
store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext) ‑> int

Returns the raw byte length of this memory.

def data_ptr(self,
store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext) ‑> ctypes._Pointer[ctypes.c_ubyte]

Returns the raw pointer in memory where this wasm memory lives.

Remember that all accesses to wasm memory should be bounds-checked against the data_len method.

def get_buffer_ptr(self,
store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext,
size: int | None = None,
offset: int = 0) ‑> _ctypes.Array

return raw pointer to buffer suitable for creating zero-copy writable NumPy Buffer Protocol this method is also used internally by read() and write()

np_mem = np.frombuffer(memory.get_buffer_ptr(store), dtype=np.uint8) np_mem[start:end] = A # write B = np_mem[start:end] # read

def grow(self,
store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext,
delta: int) ‑> int

Grows this memory by the given number of pages

def page_size(self,
store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext) ‑> int

Returns the page size, in bytes, for this memory.

WebAssembly memories are made up of a whole number of pages, so the byte size is always a multiple of the page size. Defaults to 65536 (64 KiB). The custom-page-sizes proposal allows opting into a page size of 1.

def page_size_log2(self,
store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext) ‑> int

Returns the log2 of this memory's page size, in bytes.

def read(self,
store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext,
start: int | None = 0,
stop: int | None = None) ‑> bytearray

Reads this memory starting from start and up to stop and returns a copy of the contents as a bytearray.

The indexing behavior of this method is similar to list[start:stop] where negative starts can be used to read from the end, for example.

def size(self,
store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext) ‑> int

Returns the size, in WebAssembly pages, of this memory.

def type(self,
store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext) ‑> wasmtime._types.MemoryType

Gets the type of this memory as a MemoryType

def write(self,
store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext,
value: bytearray | bytes,
start: int | None = None) ‑> int

write a bytearray value into a possibly large slice of memory negative start is allowed in a way similat to list slice mylist[-10:] if value is not bytearray it will be used to construct an intermediate bytearray (copyied twice) return number of bytes written raises IndexError when trying to write outside the memory range this happens when start offset is >= size or when end side of value is >= size

class MemoryType (limits: wasmtime._types.Limits,
is_64: bool = False,
shared: bool = False,
page_size_log2: int = 16)

Abstract base class for types which contain an owned pointer in the C FFI layer.

Not exported directly from this package.

Ancestors

  • wasmtime._managed.Managed
  • typing.Generic

Instance variables

prop is_64 : bool

Returns whether or not this is a 64-bit memory

prop is_shared : bool

Returns whether or not this is a shared memory

prop limits : wasmtime._types.Limits

Returns the limits on the size of this table

prop page_size : int

Returns the page size, in bytes, of this memory type.

Defaults to 65536 (64 KiB). The custom-page-sizes proposal allows opting into a page size of 1.

prop page_size_log2 : int

Returns the log2 of this memory type's page size, in bytes.

class Module (engine: wasmtime._engine.Engine, wasm: str | bytes)

Abstract base class for types which contain an owned pointer in the C FFI layer.

Not exported directly from this package.

Ancestors

  • wasmtime._managed.Managed
  • typing.Generic

Static methods

def deserialize(engine: wasmtime._engine.Engine, encoded: bytearray | bytes) ‑> wasmtime._module.Module

Deserializes bytes previously created by Module.serialize().

This constructor for Module will deserialize bytes previously created by a serialized module. This will only succeed if the bytes were previously created by the same version of wasmtime as well as the same configuration within Engine.

def deserialize_file(engine: wasmtime._engine.Engine, path: str) ‑> wasmtime._module.Module

Deserializes bytes previously created by Module.serialize() that are stored in a file on the filesystem.

Otherwise this function is the same as Module.deserialize().

def from_file(engine: wasmtime._engine.Engine, path: str | bytes | os.PathLike) ‑> wasmtime._module.Module

Compiles and creates a new Module by reading the file at path and then delegating to the Module constructor.

def validate(engine: wasmtime._engine.Engine, wasm: bytearray | bytes) ‑> None

Validates whether the list of bytes wasm provided is a valid WebAssembly binary given the configuration in store

Raises a WasmtimeError if the wasm isn't valid.

Instance variables

prop exports : List[wasmtime._types.ExportType]

Returns the types of the exports that this module has

prop imports : List[wasmtime._types.ImportType]

Returns the types of imports that this module has

Methods

def serialize(self) ‑> bytearray

Serializes this module to a binary representation.

This method will serialize this module to an in-memory byte array which can be cached and later passed to Module.deserialize() to recreate this module.

class SharedMemory (engine: wasmtime._engine.Engine, ty: wasmtime._types.MemoryType)

Abstract base class for types which contain an owned pointer in the C FFI layer.

Not exported directly from this package.

Creates a new shared memory in store with the given ty

Ancestors

  • wasmtime._managed.Managed
  • typing.Generic

Methods

def data_len(self) ‑> int

Returns the raw byte length of this memory.

def data_ptr(self) ‑> ctypes._Pointer[ctypes.c_ubyte]

Returns the raw pointer in memory where this wasm shared memory lives.

Remember that all accesses to wasm shared memory should be bounds-checked against the data_len method.

def grow(self, delta: int) ‑> int

Grows this memory by the given number of pages

def size(self) ‑> int

Returns the size, in WebAssembly pages, of this shared memory.

def type(self) ‑> wasmtime._types.MemoryType

Gets the type of this memory as a MemoryType

class Store (engine: wasmtime._engine.Engine | None = None, data: Any | None = None)

Abstract base class for types which contain an owned pointer in the C FFI layer.

Not exported directly from this package.

Ancestors

  • wasmtime._managed.Managed
  • typing.Generic

Methods

def data(self) ‑> Any | None

TODO

def gc(self) ‑> None

Runs a GC over externref values that have been passed into this Store, cleaning out anything that is no longer referenced.

This is not required to be run manually, but can be done so if you'd like more precise control over when unreferenced externref values are deallocated.

def get_fuel(self) ‑> int

Returns the amount of fuel left in the store.

This is only relevant when Config.consume_fuel is configured.

Raises a WasmtimeError if this store's configuration is not configured to consume fuel or if the store doesn't have enough fuel remaining.

def set_epoch_deadline(self, ticks_after_current: int) ‑> None

Configures the relative epoch deadline, after the current engine's epoch, after which WebAssembly code will trap.

def set_fuel(self, fuel: int) ‑> None

Sets the amount of fuel in this store to fuel.

This is only relevant when Config.consume_fuel is configured.

This is a required call to ensure that the store has fuel to execute WebAssembly since otherwise stores start with zero fuel.

Raises a WasmtimeError if this store's configuration is not configured to consume fuel.

def set_limits(self,
memory_size: int = -1,
table_elements: int = -1,
instances: int = -1,
tables: int = -1,
memories: int = -1) ‑> None

Configures the limits of various items within this store.

  • memory_size - the maximum size, in bytes, that linear memory is allowed to consume within this store. Setting this to a lower value will cause instantiation to fail if a module needs more memory. Additionally the memory.grow instruction will return -1 once this threshold is reached.

  • table_elements - the maximum number of elements that can be stored within tables in this store. Currently each table element takes 8 bytes.

  • instances - the maximum number of WebAssembly instances that can be created.

  • tables - the maximum number of WebAssembly tables that can be created.

  • memories - the maximum number of WebAssembly linear memories that can be created.

If any limit is negative then the limit will not be set as a part of this invocation and it will be ignored.

def set_wasi(self,
wasi: WasiConfig)

TODO

def set_wasi_http(self) ‑> None

Initializes the WASI HTTP context for this store.

Must be called before instantiating a component that uses wasi:http. Requires WASI to be configured first via set_wasi().

class StoreContext (ptr: ctypes._Pointer[ffi.wasmtime_context_t])
class Table (store: wasmtime._store.Store, ty: wasmtime._types.TableType, init: Any)

Creates a new table within store with the specified ty.

Methods

def get(self, store: wasmtime._store.Store, idx: int) ‑> Any | None

Gets an individual element within this table.

Returns None for null references in the table (i.e. a null funcref or a null `externref).

Returns a Func for non-null funcref table elements.

Returns the wrapped extern data for non-null externref table elements.

Returns None if idx is out of bounds.

def grow(self,
store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext,
amt: int,
init: Any) ‑> int

Grows this table by the specified number of slots, using the specified initializer for all new table slots.

Raises a WasmtimeError if the table could not be grown. Returns the previous size of the table otherwise.

def set(self, store: wasmtime._store.Store, idx: int, val: Any) ‑> None

Sets an individual element within this table.

idx must be an integer index.

The val specified must be convertible into this table's element type. I.e. for a funcref table, val must either be a Func or None, and for an externref table, val may be any arbitrary external data.

Raises a WasmtimeError if idx is out of bounds.

def size(self,
store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext) ‑> int

Gets the size, in elements, of this table

def type(self,
store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext) ‑> wasmtime._types.TableType

Gets the type of this table as a TableType

class TableType (valtype: wasmtime._types.ValType, limits: wasmtime._types.Limits)

Abstract base class for types which contain an owned pointer in the C FFI layer.

Not exported directly from this package.

Ancestors

  • wasmtime._managed.Managed
  • typing.Generic

Instance variables

prop element : wasmtime._types.ValType

Returns the type of this table's elements

prop limits : wasmtime._types.Limits

Returns the limits on the size of thi stable

class Tag (store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext,
ty: wasmtime._types.TagType)

Represents a WebAssembly tag, used to identify exception types.

Tags are associated with a store and describe the payload signature of exceptions that can be thrown and caught.

Creates a new host-defined tag with the given tag type.

Raises WasmtimeError if the tag cannot be created.

Methods

def eq(self,
store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext,
other: Tag) ‑> bool

Tests whether two tags are identical (same definition).

def type(self,
store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext) ‑> wasmtime._types.TagType

Returns the type of this tag.

class TagType (functype: wasmtime._types.FuncType)

Represents the type of a WebAssembly tag (used in exception handling and stack-switching).

A TagType wraps a function type that describes the payload of exceptions of this tag or types for stack switching.

Ancestors

  • wasmtime._managed.Managed
  • typing.Generic

Instance variables

prop functype : wasmtime._types.FuncType

Returns the function type that describes the tag's payload.

Methods

def ptr(self) ‑> ctypes._Pointer[ffi.wasm_tagtype_t]

Returns the underlying pointer for this FFI object, or a ValueError if it's already been closed.

class Trap (message: str)

Common base class for all non-exit exceptions.

Creates a new trap with the given message

Ancestors

  • builtins.Exception
  • builtins.BaseException
  • wasmtime._managed.Managed
  • typing.Generic

Instance variables

prop frames : List[Frame]
prop message : str

Returns the message for this trap

prop trap_code : wasmtime._trap.TrapCode | None

Returns an optional TrapCode that corresponds to why this trap happened.

Note that None may be returned for manually created traps which do not have an associated code with them.

class TrapCode (*values)

Create a collection of name/value pairs.

Example enumeration:

>>> class Color(Enum):
... RED = 1
... BLUE = 2
... GREEN = 3

Access them by:

  • attribute access:

Color.RED

  • value lookup:

Color(1)

  • name lookup:

Color['RED']

Enumerations can be iterated over, and know how many members they have:

>>> len(Color)
3
>>> list(Color)
[<Color.RED: 1>, <Color.BLUE: 2>, <Color.GREEN: 3>]

Methods can be added to enumerations, and members can have their own attributes – see the documentation for details.

Ancestors

  • enum.Enum

Class variables

var ALLOCATION_TOO_LARGE

The type of the None singleton.

var ARRAY_OUT_OF_BOUNDS

The type of the None singleton.

var ASYNC_DEADLOCK

The type of the None singleton.

var ATOMIC_WAIT_NON_SHARED_MEMORY

The type of the None singleton.

var BACKPRESSURE_OVERFLOW

The type of the None singleton.

var BAD_CONVERSION_TO_INTEGER

The type of the None singleton.

var BAD_SIGNATURE

The type of the None singleton.

var CANNOT_BLOCK_SYNC_TASK

The type of the None singleton.

var CANNOT_ENTER_COMPONENT

The type of the None singleton.

var CANNOT_LEAVE_COMPONENT

The type of the None singleton.

var CANNOT_RESUME_THREAD

The type of the None singleton.

var CAST_FAILURE

The type of the None singleton.

var CONCURRENT_FUTURE_STREAM_OP

The type of the None singleton.

var CONTINUATION_ALREADY_CONSUMED

The type of the None singleton.

var DEBUG_ASSERT_EQUAL_CODE_UNITS

The type of the None singleton.

var DEBUG_ASSERT_POINTER_ALIGNED

The type of the None singleton.

var DEBUG_ASSERT_STRING_ENCODING_FINISHED

The type of the None singleton.

var DEBUG_ASSERT_UPPER_BITS_UNSET

The type of the None singleton.

var DISABLED_OPCODE

The type of the None singleton.

var HEAP_MISALIGNED

The type of the None singleton.

var INDIRECT_CALL_TO_NULL

The type of the None singleton.

var INTEGER_DIVISION_BY_ZERO

The type of the None singleton.

var INTEGER_OVERFLOW

The type of the None singleton.

var INTERRUPT

The type of the None singleton.

var INVALID_CHAR

The type of the None singleton.

var INVALID_DISCRIMINANT

The type of the None singleton.

var LIST_OUT_OF_BOUNDS

The type of the None singleton.

var MEMORY_OUT_OF_BOUNDS

The type of the None singleton.

var NO_ASYNC_RESULT

The type of the None singleton.

var NULL_REFERENCE

The type of the None singleton.

var OUT_OF_FUEL

The type of the None singleton.

var STACK_OVERFLOW

The type of the None singleton.

var STRING_OUT_OF_BOUNDS

The type of the None singleton.

var SUBTASK_CANCEL_AFTER_TERMINAL

The type of the None singleton.

var SUBTASK_DROP_NOT_RESOLVED

The type of the None singleton.

var TABLE_OUT_OF_BOUNDS

The type of the None singleton.

var TASK_CANCEL_NOT_CANCELLED

The type of the None singleton.

var TASK_CANCEL_OR_RETURN_TWICE

The type of the None singleton.

var TASK_RETURN_INVALID

The type of the None singleton.

var THREAD_NEW_INDIRECT_INVALID_TYPE

The type of the None singleton.

var THREAD_NEW_INDIRECT_UNINITIALIZED

The type of the None singleton.

var UNALIGNED_POINTER

The type of the None singleton.

var UNHANDLED_TAG

The type of the None singleton.

var UNREACHABLE

The type of the None singleton.

var UNSUPPORTED_CALLBACK_CODE

The type of the None singleton.

var WAITABLE_SET_DROP_HAS_WAITERS

The type of the None singleton.

class Val (kind: ctypes.c_ubyte, val: Any)

Static methods

def externref(extern: Any | None) ‑> wasmtime._value.Val
def f32(val: float) ‑> wasmtime._value.Val

Create a new 32-bit float value

def f64(val: float) ‑> wasmtime._value.Val

Create a new 64-bit float value

def funcref(f: typing.Optional[Func]) ‑> wasmtime._value.Val
def i32(val: int) ‑> wasmtime._value.Val

Create a new 32-bit integer value

def i64(val: int) ‑> wasmtime._value.Val

Create a new 64-bit integer value

def ref_null(ty: wasmtime._types.ValType) ‑> wasmtime._value.Val

Create a null reference value of the given type.

Raise an exception if ty is not a reference type.

Instance variables

prop type : wasmtime._types.ValType

Returns the ValType corresponding to this Val

prop value : Any

Get the the underlying value as a python value

Methods

def as_externref(self) ‑> Any | None

Get the extern data referenced by this externref value, or None if it's not an externref.

def as_f32(self) ‑> float | None

Get the 32-bit float value of this value, or None if it's not an f32

def as_f64(self) ‑> float | None

Get the 64-bit float value of this value, or None if it's not an f64

def as_funcref(self) ‑> wasmtime._func.Func | None

Get the function that this funcref value is referencing, or None if this is not a funcref value, or is a null reference.

def as_i32(self) ‑> int | None

Get the 32-bit integer value of this value, or None if it's not an i32

def as_i64(self) ‑> int | None

Get the 64-bit integer value of this value, or None if it's not an i64

class ValType

Abstract base class for types which contain an owned pointer in the C FFI layer.

Not exported directly from this package.

Ancestors

  • wasmtime._managed.Managed
  • typing.Generic

Static methods

def externref() ‑> wasmtime._types.ValType
def f32() ‑> wasmtime._types.ValType
def f64() ‑> wasmtime._types.ValType
def funcref() ‑> wasmtime._types.ValType
def i32() ‑> wasmtime._types.ValType
def i64() ‑> wasmtime._types.ValType
class WasiConfig

Abstract base class for types which contain an owned pointer in the C FFI layer.

Not exported directly from this package.

Ancestors

  • wasmtime._managed.Managed
  • typing.Generic

Instance variables

prop argv

Explicitly configure the argv for this WASI configuration

 Note that this field can only be set, it cannot be read
prop env

Configure environment variables to be returned for this WASI configuration.

The pairs provided must be an iterable list of key/value pairs of environment variables.

 Note that this field can only be set, it cannot be read
prop stderr_custom

Sets a custom callback that is invoked whenever stderr is written to.

 Note that this field can only be set, it cannot be read
prop stderr_file

Configures a file to be used as the stderr stream of this WASI configuration.

Writes to stderr will be written to the file specified.

The file specified will be created if it doesn't exist, or truncated if it already exists. It must be available to open for writing. If it cannot be opened for writing then WasmtimeError is raised.

 Note that this field can only be set, it cannot be read
prop stdin_file

Configures a file to be used as the stdin stream of this WASI configuration.

Reads of the stdin stream will read the path specified.

The file must already exist on the filesystem. If it cannot be opened then WasmtimeError is raised.

 Note that this field can only be set, it cannot be read
prop stdout_custom

Sets a custom callback that is invoked whenever stdout is written to.

 Note that this field can only be set, it cannot be read
prop stdout_file

Configures a file to be used as the stdout stream of this WASI configuration.

Writes to stdout will be written to the file specified.

The file specified will be created if it doesn't exist, or truncated if it already exists. It must be available to open for writing. If it cannot be opened for writing then WasmtimeError is raised.

 Note that this field can only be set, it cannot be read

Methods

def inherit_argv(self) ‑> None
def inherit_env(self) ‑> None

Configures the environment variables available within WASI to be those in this own process's environment. All environment variables are inherited.

def inherit_stderr(self) ‑> None

Configures this own process's stderr to be used as the WASI program's stderr.

Writes to stderr stream will write to this process's stderr.

def inherit_stdin(self) ‑> None

Configures this own process's stdin to be used as the WASI program's stdin.

Reads of the stdin stream will read this process's stdin.

def inherit_stdout(self) ‑> None

Configures this own process's stdout to be used as the WASI program's stdout.

Writes to stdout stream will write to this process's stdout.

def preopen_dir(self,
path: str,
guest_path: str,
dir_perms: wasmtime._wasi.DirPerms = DirPerms.READ_WRITE,
file_perms: wasmtime._wasi.FilePerms = FilePerms.READ_WRITE) ‑> None

Allows the WASI program to access the directory at path using the path guest_path within the WASI program.

dir_perms specifies the permissions that wasm will have to operate on guest_path. This can be used, for example, to provide readonly access to a directory.

file_perms specifies the maximum set of permissions that can be used for any file in this directory.

class WasmtimeError (message: str)

Common base class for all non-exit exceptions.

Ancestors

  • builtins.Exception
  • builtins.BaseException
  • wasmtime._managed.Managed
  • typing.Generic

Subclasses

  • wasmtime._error.ExitTrap