def test_wat2wasm2instance(): wat = """ (module (type (func (param i32 i32) (result i32))) (func (type 0) local.get 0 local.get 1 i32.add) (export "sum" (func 0))) """ wasm_bytes = wat2wasm(wat) instance = Instance(wasm_bytes) assert instance.exports.sum(1, 2) == 3
def test_hello_world(): instance = Instance(TEST_BYTES) pointer = instance.exports.string() memory = instance.memory.uint8_view(pointer) nth = 0 string = '' while (0 != memory[nth]): string += chr(memory[nth]) nth += 1 assert string, 'Hello, World!'
def test_bytes_per_element(): assert Instance(TEST_BYTES).memory.uint8_view().bytes_per_element == 1 assert Instance(TEST_BYTES).memory.int8_view().bytes_per_element == 1 assert Instance(TEST_BYTES).memory.uint16_view().bytes_per_element == 2 assert Instance(TEST_BYTES).memory.int16_view().bytes_per_element == 2 assert Instance(TEST_BYTES).memory.uint32_view().bytes_per_element == 4 assert Instance(TEST_BYTES).memory.int32_view().bytes_per_element == 4
def test_memory_buffer_memoryview(): memory = Instance(TEST_BYTES).memory int8 = memory.int8_view() int8[0] = 1 int8[1] = 2 int8[2] = 3 memory_view = memoryview(memory.buffer) assert memory_view.nbytes == 1114112 assert memory_view.readonly == True assert memory_view.format == 'B' assert memory_view.itemsize == 1 assert memory_view.ndim == 1 assert memory_view.shape == (1114112,) assert memory_view.strides == (1,) assert memory_view.suboffsets == () assert memory_view.c_contiguous == True assert memory_view.f_contiguous == True assert memory_view.contiguous == True assert memory_view[0:3].tolist() == [1, 2, 3]
def test_getfullargspec(): instance = Instance(TEST_BYTES) assert instance.exports.sum.getfullargspec == inspect.FullArgSpec( args=['x0', 'x1'], varargs=None, varkw=None, defaults=None, kwonlyargs=None, kwonlydefaults=None, annotations={ 'x0': Type.I32, 'x1': Type.I32, 'return': Type.I32 })
def test_memory_grow(): instance = Instance(TEST_BYTES) memory = instance.memory int8 = memory.int8_view() old_memory_length = len(int8) assert old_memory_length == 1114112 memory.grow(1) memory_length = len(int8) assert memory_length == 1179648 assert memory_length - old_memory_length == 65536
def test_return_multiple_values(): store = Store() module = Module( store, """ (module (type $swap_t (func (param i32 i64) (result i64 i32))) (func $swap_f (type $swap_t) (param $x i32) (param $y i64) (result i64 i32) local.get $y local.get $x) (export "swap" (func $swap_f))) """ ) instance = Instance(module) assert instance.exports.swap(41, 42) == (42, 41)
def test_exports_all_kind(): module = Module( Store(), """ (module (func (export "func") (param i32 i64)) (global (export "glob") i32 (i32.const 7)) (table (export "tab") 0 funcref) (memory (export "mem") 1)) """) instance = Instance(module) exports = instance.exports assert isinstance(exports, Exports) assert isinstance(exports.func, Function) assert isinstance(exports.glob, Global) assert isinstance(exports.tab, Table) assert isinstance(exports.mem, Memory)
def test_global_read_write_and_exported_functions(): instance = Instance(TEST_BYTES) exports = instance.exports x = instance.globals.x assert x.value == 0 assert exports.get_x() == 0 x.value = 1 assert x.value == 1 assert exports.get_x() == 1 exports.increment_x() assert x.value == 2 assert exports.get_x() == 2
def test_memory_views_share_the_same_buffer(): instance = Instance(TEST_BYTES) int8 = instance.memory.int8_view() int16 = instance.memory.int16_view() int32 = instance.memory.int32_view() int8[0] = 0b00000001 int8[1] = 0b00000100 int8[2] = 0b00010000 int8[3] = 0b01000000 assert int8[0] == 0b00000001 assert int8[1] == 0b00000100 assert int8[2] == 0b00010000 assert int8[3] == 0b01000000 assert int16[0] == 0b00000100_00000001 assert int16[1] == 0b01000000_00010000 assert int32[0] == 0b01000000_00010000_00000100_00000001
def test_exports_iterable(): module = Module( Store(), """ (module (func (export "func") (param i32 i64)) (global (export "glob") i32 (i32.const 7)) (table (export "tab") 0 funcref) (memory (export "mem") 1)) """) instance = Instance(module) exports_iterator = iter(instance.exports) assert isinstance(exports_iterator, ExportsIterator) (export_name, export) = next(exports_iterator) assert export_name == "func" assert isinstance(export, Function) (export_name, export) = next(exports_iterator) assert export_name == "glob" assert isinstance(export, Global) (export_name, export) = next(exports_iterator) assert export_name == "tab" assert isinstance(export, Table) (export_name, export) = next(exports_iterator) assert export_name == "mem" assert isinstance(export, Memory) with pytest.raises(StopIteration): next(exports_iterator) # Works in a loop. for (name, export) in instance.exports: assert True # Works in a loop with `iter` called while it's not necessary. for (name, export) in iter(instance.exports): assert True assert [name for (name, _) in instance.exports ] == ["func", "glob", "tab", "mem"]
def build_instance(): import_object = ImportObject() store = Store(engine.JIT(Compiler)) import_object.register( "env", { "__sys_getpid": Function(store, lambda: 42, FunctionType([], [Type.I32])), }) import_object.register( "wasi_snapshot_preview1", { "proc_exit": Function(store, lambda *args: None, FunctionType([Type.I32], [])), "clock_time_get": Function(store, lambda *args: int(time.time()), FunctionType([Type.I32, Type.I64, Type.I32], [Type.I32])), "fd_close": Function(store, lambda *args: 1, FunctionType([Type.I32], [Type.I32])), "fd_write": Function( store, lambda *args: 1, FunctionType([Type.I32, Type.I32, Type.I32, Type.I32], [Type.I32])), "fd_seek": Function( store, lambda *args: 1, FunctionType([Type.I32, Type.I64, Type.I32, Type.I32], [Type.I32])), "fd_read": Function( store, lambda *args: 1, FunctionType([Type.I32, Type.I32, Type.I32, Type.I32], [Type.I32])), }) # Let's compile the module to be able to execute it! module = Module(store, open(quiet_path, 'rb').read()) # Now the module is compiled, we can instantiate it. return Instance(module, import_object)
def test_import_function_defaultdict(): def sum(x: int, y: int) -> int: return x + y store = Store() module = Module( store, """ (module (import "math" "sum" (func $sum (param i32 i32) (result i32))) (func (export "add_one") (param i32) (result i32) local.get 0 i32.const 1 call $sum)) """) import_object = defaultdict(dict) import_object["math"]["sum"] = Function(store, sum) instance = Instance(module, import_object) assert instance.exports.add_one(1) == 2
def test_import_function(): def sum(x: int, y: int) -> int: return x + y store = Store() module = Module( store, """ (module (import "math" "sum" (func $sum (param i32 i32) (result i32))) (func (export "add_one") (param i32) (result i32) local.get 0 i32.const 1 call $sum)) """) import_object = ImportObject() import_object.register("math", {"sum": Function(store, sum)}) instance = Instance(module, import_object) assert instance.exports.add_one(1) == 2
def test_early_exit(): store = Store() module = Module( store, """ (module (type $run_t (func (param i32 i32) (result i32))) (type $early_exit_t (func (param) (result))) (import "env" "early_exit" (func $early_exit (type $early_exit_t))) (func $run (type $run_t) (param $x i32) (param $y i32) (result i32) (call $early_exit) (i32.add local.get $x local.get $y)) (export "run" (func $run))) """ ) def early_exit(): raise Exception('oops') import_object = ImportObject() import_object.register( "env", { "early_exit": Function(store, early_exit), } ) instance = Instance(module, import_object) try: instance.exports.run(1, 2) except Exception as err: assert 'oops' in str(err) else: assert False
def main(): # Create a store store = Store(engine.JIT(Compiler)) # Convert Wat file contents into Wasm binary code wat_file_name = str(sys.argv[1]) with open(wat_file_name) as wat_file: wat_source_code = wat_file.read() wasm_bytes = wat2wasm(wat_source_code) # Compile the Wasm module module = Module(store, wasm_bytes) # Obtain functions to be imported from the Wasm module import_object = make_import_object(store) # Instantiate the module instance = Instance(module, import_object) # Run start function and return to OS its exit code sys.exit(instance.exports.main())
def create_app(test_config=None): """Create and configure an instance of the Flask application.""" app = Flask(__name__, instance_relative_config=True) app.config.from_mapping( # a default secret that should be overridden by instance config SECRET_KEY="dev") if test_config is None: # load the instance config, if it exists, when not testing app.config.from_pyfile("config.py", silent=True) else: # load the test config if passed in app.config.update(test_config) # load the Wasm binary for Flask app from wasmer import Instance path = join( dirname(root_path), 'target/wasm32-unknown-unknown/release/rust_wasm_python_101.wasm') wasm_bytes = open(path, 'rb').read() app.wasm = Instance(wasm_bytes) return app
def test_import_global(): store = Store() module = Module( store, """ (module (import "env" "global" (global $global (mut i32))) (func (export "read_g") (result i32) global.get $global) (func (export "write_g") (param i32) local.get 0 global.set $global)) """) global_ = Global(store, Value.i32(7), mutable=True) import_object = defaultdict(dict) import_object["env"]["global"] = global_ instance = Instance(module, import_object) assert instance.exports.read_g() == 7 global_.value = 153 assert instance.exports.read_g() == 153 instance.exports.write_g(11) assert global_.value == 11
memory[length_of_string] = 0 return (string_ptr, length_of_string) relative_dir = 'lib/python' wasm_bytes = open(f'{relative_dir}/smartcore_wasi_lib.wasm', 'rb').read() store = Store(engine.JIT(Compiler)) module = Module(store, wasm_bytes) wasi_version = wasi.get_version(module, strict=True) wasi_env = wasi.StateBuilder('smartcore-wasi-lib').preopen_directory( ".").finalize() import_object = wasi_env.generate_import_object(store, wasi_version) instance = Instance(module, import_object) (file_ptr, file_len) = get_string_ptr(f'{relative_dir}/iris_knn.model', instance) instance.exports.init(file_ptr) perfomances = [] num_executions = 1000 if os.environ.get("noe") is not None: num_executions = int(os.environ.get("noe")) print(f"Executing {num_executions} times") start_time = datetime.datetime.now() for i in range(num_executions): t1 = time.monotonic_ns() instance.exports.load_model() t2 = time.monotonic_ns() perfomances.append(t2 - t1) end_time = datetime.datetime.now()
from wasmer import Instance, Module, ImportObject import os __dir__ = os.path.dirname(os.path.realpath(__file__)) wasm_bytes = open(__dir__ + '/imported_function.wasm', 'rb').read() def sum(x: int, y: int) -> int: return x + y instance = Instance( wasm_bytes, { "env": { "sum": sum } } ) print(instance.exports.sum_plus_one(1, 2)) module = Module(wasm_bytes) import_object = module.generate_import_object() import_object.extend({ "env": { "sum": sum } }) instance = module.instantiate(import_object) print(instance.exports.sum_plus_one(3, 4))
from wasmer import Instance wasm_bytes = open('my_lib.wasm', 'rb').read() instance = Instance(wasm_bytes) result = instance.exports.sum_of_squares(100) print(result)
def instance(): return Instance(Module(Store(), TEST_BYTES))
def test_length(): assert len(Instance(TEST_BYTES).memory.uint8_view()) == (1114112)
def test_memory_is_absent(): bytes = open(here + '/no_memory.wasm', 'rb').read() instance = Instance(bytes) assert instance.memory == None
def test_comments(): wasm = emitter() instance = Instance(wasm)
def test_set_values_with_slice_and_step(): memory = Instance(TEST_BYTES).memory.uint8_view() memory[7:12:2] = [1, 2, 3, 4, 5] assert memory[7:12] == [1, 0, 2, 0, 3]
def test_set_bytearray(): memory = Instance(TEST_BYTES).memory.uint8_view() memory[7:12] = bytearray(b'abcde') assert memory[7:12] == [97, 98, 99, 100, 101]
def test_set_list(): memory = Instance(TEST_BYTES).memory.uint8_view() memory[7:12] = [1, 2, 3, 4, 5] assert memory[7:12] == [1, 2, 3, 4, 5]
# Define the engine that will drive everything. # # In this case, the engine is `wasmer.engine.JIT` which roughly # means that the executable code will live in memory. engine = engine.JIT(Compiler) # Create a store, that holds the engine. store = Store(engine) # Here we go. # # Let's compile the Wasm module. It is at this step that the Wasm text # is transformed into Wasm bytes (if necessary), and then compiled to # executable code by the compiler, which is then stored in memory by # the engine. module = Module(store, wasm_bytes) # Congrats, the Wasm module is compiled! Now let's execute it for the # sake of having a complete example. # # Let's instantiate the Wasm module. instance = Instance(module) # The Wasm module exports a function called `sum`. sum = instance.exports.sum results = sum(1, 2) print(results) assert results == 3
def test_set_single_value(): memory = Instance(TEST_BYTES).memory.uint8_view() assert memory[7] == 0 memory[7] = 42 assert memory[7] == 42