1'use strict'; 2const common = require('../common'); 3const assert = require('assert'); 4const { MessageChannel, Worker } = require('worker_threads'); 5 6// Test that SharedArrayBuffer instances created from WASM are transferrable 7// through MessageChannels (without crashing). 8 9const fixtures = require('../common/fixtures'); 10const wasmSource = fixtures.readSync('shared-memory.wasm'); 11const wasmModule = new WebAssembly.Module(wasmSource); 12const instance = new WebAssembly.Instance(wasmModule); 13 14const { buffer } = instance.exports.memory; 15assert(buffer instanceof SharedArrayBuffer); 16 17{ 18 const { port1, port2 } = new MessageChannel(); 19 port1.postMessage(buffer); 20 port2.once('message', common.mustCall((buffer2) => { 21 // Make sure serialized + deserialized buffer refer to the same memory. 22 const expected = 'Hello, world!'; 23 const bytes = Buffer.from(buffer).write(expected); 24 const deserialized = Buffer.from(buffer2).toString('utf8', 0, bytes); 25 assert.deepStrictEqual(deserialized, expected); 26 })); 27} 28 29{ 30 // Make sure we can free WASM memory originating from a thread that already 31 // stopped when we exit. 32 const worker = new Worker(` 33 const { parentPort } = require('worker_threads'); 34 35 // Compile the same WASM module from its source bytes. 36 const wasmSource = new Uint8Array([${wasmSource.join(',')}]); 37 const wasmModule = new WebAssembly.Module(wasmSource); 38 const instance = new WebAssembly.Instance(wasmModule); 39 parentPort.postMessage(instance.exports.memory); 40 41 // Do the same thing, except we receive the WASM module via transfer. 42 parentPort.once('message', ({ wasmModule }) => { 43 const instance = new WebAssembly.Instance(wasmModule); 44 parentPort.postMessage(instance.exports.memory); 45 }); 46 `, { eval: true }); 47 worker.on('message', common.mustCall(({ buffer }) => { 48 assert(buffer instanceof SharedArrayBuffer); 49 worker.buf = buffer; // Basically just keep the reference to buffer alive. 50 }, 2)); 51 worker.once('exit', common.mustCall()); 52 worker.postMessage({ wasmModule }); 53} 54