@@ -51,21 +51,49 @@ const selectWASIBackend = () => {
5151 return WASI . Node ;
5252} ;
5353
54+ function isUsingSharedMemory ( module ) {
55+ const imports = WebAssembly . Module . imports ( module ) ;
56+ for ( const entry of imports ) {
57+ if ( entry . module === "env" && entry . name === "memory" && entry . kind == "memory" ) {
58+ return true ;
59+ }
60+ }
61+ return false ;
62+ }
63+
5464export const startWasiTask = async ( wasmPath , wasiConstructor = selectWASIBackend ( ) ) => {
5565 const swift = new SwiftRuntime ( ) ;
5666 // Fetch our Wasm File
5767 const wasmBinary = await fs . readFile ( wasmPath ) ;
5868 const wasi = wasiConstructor ( { programName : wasmPath } ) ;
5969
60- // Instantiate the WebAssembly file
61- let { instance } = await WebAssembly . instantiate ( wasmBinary , {
70+ const module = await WebAssembly . compile ( wasmBinary ) ;
71+
72+ const importObject = {
6273 wasi_snapshot_preview1 : wasi . wasiImport ,
6374 javascript_kit : swift . importObjects ( ) ,
6475 benchmark_helper : {
6576 noop : ( ) => { } ,
6677 noop_with_int : ( _ ) => { } ,
6778 }
68- } ) ;
79+ } ;
80+
81+ if ( isUsingSharedMemory ( module ) ) {
82+ importObject [ "env" ] = {
83+ // We don't have JS API to get memory descriptor of imported memory
84+ // at this moment, so we assume 256 pages (16MB) memory is enough
85+ // large for initial memory size.
86+ memory : new WebAssembly . Memory ( { initial : 256 , maximum : 16384 , shared : true } ) ,
87+ } ;
88+ importObject [ "wasi" ] = {
89+ "thread-spawn" : ( ) => {
90+ throw new Error ( "thread-spawn not implemented" ) ;
91+ }
92+ }
93+ }
94+
95+ // Instantiate the WebAssembly file
96+ const instance = await WebAssembly . instantiate ( module , importObject ) ;
6997
7098 swift . setInstance ( instance ) ;
7199 // Start the WebAssembly WASI instance!
0 commit comments