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
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
stras input, raises an error if it fails to parse, and returns abytesif conversion/parsing was successful.>>> wat2wasm('(module)') bytearray(b'\x00asm\x01\x00\x00\x00')
Classes
class Caller (ptr: ctypes._Pointer[ffi.wasmtime_caller_t])-
Methods
class Config-
Global configuration, used to create an
Engine.A
Confighouses 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
Truecan 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_verifierprop 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_levelprop 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
Trueon 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_reservationis 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_frameon 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
profilerare:"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.
SIGILLandSIGSEGVon 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
strategyare:"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
WasmtimeErrorif the target triple is not recognized.Note that if this is set to something other than the host then an
Enginecreated 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 = 3Access 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) ‑> Nonedef is_pulley(self) ‑> bool
class ExitTrap (message: str)-
A special type of
WasmtimeErrorwhich represents the process exiting via WASI'sproc_exitfunction call.Whenever a WASI program exits via
proc_exita trap is raised, but the trap will have this type instead ofWasmtimeError, so you can catch just this type instead of all traps (if desired). Exit traps have acodeassociated with them which is the exit code provided at exit.Note that
ExitTrapis a subclass ofWasmtimeError, so if you catch a trap you'll also catchExitTrap.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 = 3Access 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
Noneif 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
Noneif 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
storewith the giventywhich calls the closure givenThe
funcis called with the parameters natively and they'll have native Python values rather than being wrapped inVal. Ifaccess_calleris set toTruethen the first argument given tofuncis an instance of typeCallerbelow.Methods
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
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
Nonemay 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
modulegiven with theimportsinto thestoreprovided.The
storemust have typeStore, themodulemust have typeModule, and theimportsmust be an iterable of external values, eitherExtern,Func,Table,Memory, orGlobal.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.
InstancePreallows you to skip the import-resolution step on every call toinstantiate, 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
Modulethat thisInstancePrewas 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
WasmtimeErroron error or aTrapif 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
modulenadnameprovided are what to name theitemwithin the linker.This function will raise an error if
itemcomes 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
defineexcept that you can directly define a function without creating aFuncitself. This enablesStore-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
defineeaech 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
instancecomes 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
moduleprovided is defined undernamewith 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
moduleas default values (zero for numerics, null for references, etc.).This is similar to
define_unknown_imports_as_trapsbut 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
moduleas 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
moduleprovided with the names defined within this linker. If all names are defined then the module is instantiated.Raises an error if an import of
modulehasn'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
moduleby resolving all of its imports from the definitions in this linker.Returns an
InstancePrethat can be used to cheaply create multiple instances of the same module without repeating import resolution.Raises
WasmtimeErrorif any imports are unresolvable.
class Memory (store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext,
ty: wasmtime._types.MemoryType)-
Creates a new memory in
storewith the giventyMethods
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_lenmethod. 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()andwrite()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
startand up tostopand returns a copy of the contents as abytearray.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
Modulewill deserialize bytes previously created by a serialized module. This will only succeed if the bytes were previously created by the same version ofwasmtimeas well as the same configuration withinEngine. 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.Moduledef validate(engine: wasmtime._engine.Engine, wasm: bytearray | bytes) ‑> None-
Validates whether the list of bytes
wasmprovided is a valid WebAssembly binary given the configuration instoreRaises a
WasmtimeErrorif 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
storewith the giventyAncestors
- 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_lenmethod. 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
externrefvalues 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
externrefvalues are deallocated. def get_fuel(self) ‑> int-
Returns the amount of fuel left in the store.
This is only relevant when
Config.consume_fuelis configured.Raises a
WasmtimeErrorif 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_fuelis 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
WasmtimeErrorif 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 thememory.growinstruction 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 viaset_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
storewith the specifiedty.Methods
def get(self, store: wasmtime._store.Store, idx: int) ‑> Any | None-
Gets an individual element within this table.
Returns
Nonefor null references in the table (i.e. a nullfuncrefor a null `externref).Returns a
Funcfor non-nullfuncreftable elements.Returns the wrapped extern data for non-null
externreftable elements.Returns
Noneifidxis 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
WasmtimeErrorif 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.
idxmust be an integer index.The
valspecified must be convertible into this table's element type. I.e. for afuncreftable,valmust either be aFuncorNone, and for anexternreftable,valmay be any arbitrary external data.Raises a
WasmtimeErrorifidxis 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
WasmtimeErrorif the tag cannot be created.Methods
class TagType (functype: wasmtime._types.FuncType)-
Represents the type of a WebAssembly tag (used in exception handling and stack-switching).
A
TagTypewraps 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
ValueErrorif it's already been closed.
class Trap (message: str)-
Common base class for all non-exit exceptions.
Creates a new trap with the given
messageAncestors
- 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
TrapCodethat corresponds to why this trap happened.Note that
Nonemay 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 = 3Access 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.Valdef 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.Valdef 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
tyis not a reference type.
Instance variables
prop type : wasmtime._types.ValTypeprop 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
externrefvalue, orNoneif it's not anexternref. def as_f32(self) ‑> float | None-
Get the 32-bit float value of this value, or
Noneif it's not an f32 def as_f64(self) ‑> float | None-
Get the 64-bit float value of this value, or
Noneif it's not an f64 def as_funcref(self) ‑> wasmtime._func.Func | None-
Get the function that this
funcrefvalue is referencing, orNoneif this is not afuncrefvalue, or is a null reference. def as_i32(self) ‑> int | None-
Get the 32-bit integer value of this value, or
Noneif it's not an i32 def as_i64(self) ‑> int | None-
Get the 64-bit integer value of this value, or
Noneif 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.ValTypedef f32() ‑> wasmtime._types.ValTypedef f64() ‑> wasmtime._types.ValTypedef funcref() ‑> wasmtime._types.ValTypedef i32() ‑> wasmtime._types.ValTypedef 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
argvfor this WASI configurationNote that this field can only be set, it cannot be read prop env-
Configure environment variables to be returned for this WASI configuration.
The
pairsprovided 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
callbackthat 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
WasmtimeErroris 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
WasmtimeErroris raised.Note that this field can only be set, it cannot be read prop stdout_custom-
Sets a custom
callbackthat 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
WasmtimeErroris raised.Note that this field can only be set, it cannot be read
Methods
def inherit_argv(self) ‑> Nonedef 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
pathusing the pathguest_pathwithin the WASI program.dir_permsspecifies the permissions that wasm will have to operate onguest_path. This can be used, for example, to provide readonly access to a directory.file_permsspecifies 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
