1+ from textwrap import dedent
12from typing import Any , List , cast
23from polywrap_core import Invoker , InvokerOptions , Uri
34from polywrap_result import Result , Ok , Err
@@ -25,9 +26,56 @@ async def unsync_invoke(invoker: Invoker, options: InvokerOptions) -> Result[Any
2526 return await invoker .invoke (options )
2627
2728
29+ def create_memory (
30+ store : Store ,
31+ module : bytes ,
32+ ) -> Memory :
33+ env_memory_import_signature = bytearray (
34+ [
35+ # env ; import module name
36+ 0x65 ,
37+ 0x6E ,
38+ 0x76 ,
39+ # string length
40+ 0x06 ,
41+ # memory ; import field name
42+ 0x6D ,
43+ 0x65 ,
44+ 0x6D ,
45+ 0x6F ,
46+ 0x72 ,
47+ 0x79 ,
48+ # import kind
49+ 0x02 ,
50+ # limits ; https://github.com/sunfishcode/wasm-reference-manual/blob/master/WebAssembly.md#resizable-limits
51+ # limits ; flags
52+ # 0x??,
53+ # limits ; initial
54+ # 0x__,
55+ ]
56+ )
57+ idx = module .find (env_memory_import_signature )
58+
59+ if idx < 0 :
60+ raise RuntimeError (
61+ dedent (
62+ """
63+ Unable to find Wasm memory import section. \
64+ Modules must import memory from the "env" module's\
65+ "memory" field like so:
66+ (import "env" "memory" (memory (;0;) #))
67+ """
68+ )
69+ )
70+
71+ memory_inital_limits = module [idx + len (env_memory_import_signature ) + 1 ]
72+
73+ return Memory (store , MemoryType (Limits (memory_inital_limits , None )))
74+
75+
2876def create_instance (
2977 store : Store ,
30- module : Module ,
78+ module : bytes ,
3179 state : State ,
3280 invoker : Invoker ,
3381) -> Instance :
@@ -37,7 +85,7 @@ def create_instance(
3785 TODO: Re-check this based on issue https://github.com/polywrap/toolchain/issues/561
3886 This probably means that memory creation should be moved to its own function
3987 """
40- mem = Memory (store , MemoryType ( Limits ( 1 , None )) )
88+ mem = create_memory (store , module )
4189
4290 wrap_debug_log_type = FuncType (
4391 [ValType .i32 (), ValType .i32 ()],
@@ -252,7 +300,9 @@ def wrap_subinvoke_implementation(
252300 return True
253301 elif result .is_err ():
254302 error = cast (Err , result ).unwrap_err ()
255- state .subinvoke_implementation ["error" ] = "" .join (str (x ) for x in error .args )
303+ state .subinvoke_implementation ["error" ] = "" .join (
304+ str (x ) for x in error .args
305+ )
256306 return False
257307 else :
258308 raise ValueError (
@@ -374,4 +424,6 @@ def wrap_get_implementations_result(ptr: int) -> None:
374424
375425 # memory
376426 linker .define ("env" , "memory" , mem )
377- return linker .instantiate (store , module )
427+
428+ instantiated_module = Module (store .engine , module )
429+ return linker .instantiate (store , instantiated_module )
0 commit comments