def __init__(self): self.store = Store() self.module = Module.from_file(self.store, "main.wasm") self.imports = return_wasi_imports(self.store, self.module) load_callback_type = FuncType([ValType.i32()], [ValType.i32()]) call_callback_type = FuncType( [ValType.i32(), ValType.i32()], [ValType.i32()]) unload_callback_type = FuncType([ValType.i32()], [ValType.i32()]) load_callback_func = Func(self.store, load_callback_type, load, access_caller=True) call_callback_func = Func(self.store, call_callback_type, call, access_caller=True) unload_callback_func = Func(self.store, unload_callback_type, unload, access_caller=True) self.instance = Instance( self.module, [ load_callback_func, call_callback_func, unload_callback_func, *self.imports, ], )
def __init__( self, pathname: str, import_object: Dict[str, Dict[str, Union[Func, Table, Global, Memory, Callable]]] ) -> None: import_object['env'].update({'__web_on_grow': lambda: None}) self.store = store = Store() self.module = module = Module.from_file(store.engine, pathname) imoprts = [] for wasm_import in module.imports: module_name = wasm_import.module filed_name = wasm_import.name item = import_object[module_name][filed_name] if not isinstance(item, (Func, Table, Global, Memory)): item = Func(store, wasm_import.type, item) imoprts.append(item) self.instance = instance = Instance(store, module, imoprts) self.exports = exports = instance.exports self.memory = exports['memory'] self.web_free = exports['__web_free'] self.web_malloc = exports['__web_malloc'] self.HEAP8 = Heap(self.memory, HeapKind.S8) self.HEAP16 = Heap(self.memory, HeapKind.S16) self.HEAP32 = Heap(self.memory, HeapKind.S32) self.HEAPU8 = Heap(self.memory, HeapKind.U8) self.HEAPU16 = Heap(self.memory, HeapKind.U16) self.HEAPU32 = Heap(self.memory, HeapKind.U32)
def load(caller, name): memory = caller.get_export("memory").memory() if memory is not None: store = Store() index = seek(name, memory) data = memory.data_ptr()[name:name + index] module_name = "".join(map(chr, data)) module = Module.from_file(store, module_name) wasi_imports = return_wasi_imports(store, module) instance = Instance(module, wasi_imports) INSTANCES[module_name] = instance return 0
def exec_module(self, module): # type: ignore wasm_module = Module.from_file(store.engine, self.filename) for wasm_import in wasm_module.imports: module_name = wasm_import.module field_name = wasm_import.name imported_module = importlib.import_module(module_name) item = imported_module.__dict__[field_name] if not isinstance(item, Func) and \ not isinstance(item, Table) and \ not isinstance(item, Global) and \ not isinstance(item, Memory): item = Func(store, wasm_import.type, item) linker.define(module_name, field_name, item) res = linker.instantiate(wasm_module) exports = res.exports for i, export in enumerate(wasm_module.exports): module.__dict__[export.name] = exports[i]
def __init__(self): wasm_cfg = Config() wasm_cfg.cache = True store = Store(Engine(wasm_cfg)) linker = Linker(store) wasi_cfg = WasiConfig() wasi_inst = WasiInstance(store, "wasi_snapshot_preview1", wasi_cfg) linker.define_wasi(wasi_inst) self.inst = None err_handler_type = FuncType([ValType.i32(), ValType.i32()], []) err_handler_func = Func(store, err_handler_type, self._err_handler) linker.define("env", "AStyleErrorHandler", err_handler_func) wasm_file = os.path.join(os.path.dirname(__file__), "libastyle.wasm") module = Module.from_file(store.engine, wasm_file) self.inst = linker.instantiate(module) self.inst.exports["_initialize"]() self._opts_ptr = WasmString.from_str(self.inst, "")
# Example of instantiating two modules which link to each other. from wasmtime import Store, Module, Linker, WasiConfig, WasiInstance store = Store() # First set up our linker which is going to be linking modules together. We # want our linker to have wasi available, so we set that up here as well. linker = Linker(store) wasi = WasiInstance(store, "wasi_snapshot_preview1", WasiConfig()) linker.define_wasi(wasi) # Load and compile our two modules linking1 = Module.from_file(store.engine, "examples/linking1.wat") linking2 = Module.from_file(store.engine, "examples/linking2.wat") # Instantiate our first module which only uses WASI, then register that # instance with the linker since the next linking will use it. linking2 = linker.instantiate(linking2) linker.define_instance("linking2", linking2) # And with that we can perform the final link and the execute the module. linking1 = linker.instantiate(linking1) run = linking1.exports["run"] run()
# This is an example of working with mulit-value modules and dealing with # multi-value functions. from wasmtime import Config, Store, Engine, Module, FuncType, Func, ValType, Instance # Configure our `Store`, but be sure to use a `Config` that enables the # wasm multi-value feature since it's not stable yet. print("Initializing...") config = Config() config.wasm_multi_value = True store = Store(Engine(config)) print("Compiling module...") module = Module.from_file(store.engine, "examples/multi.wat") print("Creating callback...") callback_type = FuncType([ValType.i32(), ValType.i64()], [ValType.i64(), ValType.i32()]) def callback(a, b): return [b + 1, a + 1] callback_func = Func(store, callback_type, callback) print("Instantiating module...") instance = Instance(store, module, [callback_func]) print("Extracting export...") g = instance.exports["g"]
# Example of instantiating a wasm module and calling an export on it from wasmtime import Store, Module, Instance store = Store() module = Module.from_file(store, './examples/gcd.wat') instance = Instance(module, []) gcd = instance.get_export("gcd").func() print("gcd(6, 27) = %d" % gcd.call(6, 27))
from wasmtime import Store, Module, Instance, Func, FuncType # Almost all operations in wasmtime require a contextual "store" argument to be # shared amongst objects store = Store() # Here we can compile a `Module` which is then ready for instantiation # afterwards module = Module.from_file(store.engine, './examples/hello.wat') # Our module needs one import, so we'll create that here. def say_hello(): print("Hello from Python!") hello = Func(store, FuncType([], []), say_hello) # And with all that we can instantiate our module and call the export! instance = Instance(store, module, [hello]) instance.exports["run"]()
# An example of how to interact with wasm memory. # # Here a small wasm module is used to show how memory is initialized, how to # read and write memory through the `Memory` object, and how wasm functions # can trap when dealing with out-of-bounds addresses. from wasmtime import Store, Module, Instance, Trap, MemoryType, Memory, Limits # Create our `Store` context and then compile a module and create an # instance from the compiled module all in one go. wasmtime_store = Store() module = Module.from_file(wasmtime_store, "examples/memory.wat") instance = Instance(module, []) # Load up our exports from the instance memory = instance.get_export("memory").memory() size = instance.get_export("size").func() load = instance.get_export("load").func() store = instance.get_export("store").func() print("Checking memory...") assert (memory.size() == 2) assert (memory.data_len() == 0x20000) # Note that usage of `data_ptr` is unsafe! This is a raw C pointer which is not # bounds checked at all. We checked our `data_len` above but you'll want to be # very careful when accessing data through `data_ptr()` assert (memory.data_ptr()[0] == 0) assert (memory.data_ptr()[0x1000] == 1) assert (memory.data_ptr()[0x1003] == 4)
# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from wasmtime import Store, Module, FuncType, MemoryType, TableType, GlobalType wasm_file = '../../libtvmwasm.wasm' store = Store() module = Module.from_file(store, wasm_file) for i, e in enumerate(module.exports): if isinstance(e.type, FuncType): print("{}: {}, params={}, results={}".format(i, e.name, e.type.params, e.type.results)) elif isinstance(e.type, MemoryType): print("{}: {}, limits=[{}, {}]".format(i, e.name, e.type.limits.min, e.type.limits.max)) elif isinstance(e.type, TableType): print("{}: {}".format(i, e.name)) elif isinstance(e.type, GlobalType): print("{}: {}, content={}, mutable={}".format(i, e.name, e.type.content, e.type.mutable))
from wasmtime import Store, Module, Instance, Config, Engine #settings configution config = Config() config.debug_info = True config.wasm_threads = False config.wasm_module_linking = False engine = Engine(config) store: Store = Store(engine) module = Module.from_file(store.engine, 'fac.wat') instance = Instance(store, module, []) if __name__ == "__main__": print(f'instance {instance}')
vals[k] = v def get_f(k): print("get: {}".format(k)) if k in vals: return vals[k] else: return 0 def print_f(v): print("print: {}".format(v)) store = Store() module = Module.from_file(store, '../get_set.wat') set_type = FuncType([ValType.i32(), ValType.i32()], []) set_func = Func(store, set_type, set_f) get_type = FuncType([ValType.i32()], [ValType.i32()]) get_func = Func(store, get_type, get_f) print_type = FuncType([ValType.i32()], []) print_func = Func(store, print_type, print_f) instance = Instance(module, [set_func, get_func, print_func]) run = instance.exports['run'] run()