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