Exemplo n.º 1
0
    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,
            ],
        )
Exemplo n.º 2
0
    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)
Exemplo n.º 3
0
def wrap_extern(ptr: 'pointer[ffi.wasm_extern_t]',
                owner: Optional[Any]) -> AsExtern:
    from wasmtime import Func, Table, Global, Memory, Module, Instance

    if not isinstance(ptr, POINTER(ffi.wasm_extern_t)):
        raise TypeError("wrong pointer type")

    # We must free this as an extern, so if there's no ambient owner then
    # configure an owner with the right destructor
    if owner is None:
        owner = Extern(ptr)

    val = ffi.wasm_extern_as_func(ptr)
    if val:
        return Func._from_ptr(val, owner)
    val = ffi.wasm_extern_as_table(ptr)
    if val:
        return Table._from_ptr(val, owner)
    val = ffi.wasm_extern_as_global(ptr)
    if val:
        return Global._from_ptr(val, owner)
    val = ffi.wasm_extern_as_memory(ptr)
    if val:
        return Memory._from_ptr(val, owner)
    val = ffi.wasm_extern_as_instance(ptr)
    if val:
        return Instance._from_ptr(val, owner)
    val = ffi.wasm_extern_as_module(ptr)
    if val:
        return Module._from_ptr(val, owner)
    raise WasmtimeError("unknown extern")
Exemplo n.º 4
0
    def func(self):
        """
        Returns this type as a `Func` or `None` if it's not a function
        """
        from wasmtime import Func

        val = dll.wasm_extern_as_func(self.__ptr__)
        if val:
            return Func.__from_ptr__(val, self.__owner__ or self)
        else:
            return None
Exemplo n.º 5
0
    def get_default(self, name: str) -> 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.
        """
        name_raw = ffi.str_to_name(name)
        default = POINTER(ffi.wasm_func_t)()
        error = ffi.wasmtime_linker_get_default(self._ptr, byref(name_raw), byref(default))
        if error:
            raise WasmtimeError._from_ptr(error)
        return Func._from_ptr(default, None)
Exemplo n.º 6
0
def invoke_wasm(data):

    wasm_key = data[1]
    operand_b = int(data[2])

    wasm = execute('GET', wasm_key)
    wasm_bytes = bytes(wasm, 'ascii')

    store = Store()
    module = Module.validate(store, wasm_bytes)
    module = Module(store.engine, wasm_bytes)

    get_a_func = Func(store, FuncType([], [ValType.i32()]), get_a)

    instance = Instance(store, module, [get_a_func])

    return instance.exports["run"](operand_b)
Exemplo n.º 7
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]
Exemplo n.º 8
0
    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, "")
Exemplo n.º 9
0
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"]

print("Calling export \"g\"...")
results = g(1, 3)
print("> {} {}".format(results[0], results[1]))

assert(results[0] == 4)
assert(results[1] == 2)

print("Calling export \"round_trip_many\"...")
Exemplo n.º 10
0
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"]()
Exemplo n.º 11
0
    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()