• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Flags: --experimental-wasm-threads
2'use strict';
3const common = require('../common');
4const assert = require('assert');
5const { MessageChannel, Worker } = require('worker_threads');
6
7// Test that SharedArrayBuffer instances created from WASM are transferrable
8// through MessageChannels (without crashing).
9
10const fixtures = require('../common/fixtures');
11const wasmSource = fixtures.readSync('shared-memory.wasm');
12const wasmModule = new WebAssembly.Module(wasmSource);
13const instance = new WebAssembly.Instance(wasmModule);
14
15const { buffer } = instance.exports.memory;
16assert(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
36  // Compile the same WASM module from its source bytes.
37  const wasmSource = new Uint8Array([${wasmSource.join(',')}]);
38  const wasmModule = new WebAssembly.Module(wasmSource);
39  const instance = new WebAssembly.Instance(wasmModule);
40  parentPort.postMessage(instance.exports.memory);
41
42  // Do the same thing, except we receive the WASM module via transfer.
43  parentPort.once('message', ({ wasmModule }) => {
44    const instance = new WebAssembly.Instance(wasmModule);
45    parentPort.postMessage(instance.exports.memory);
46  });
47  `, { eval: true });
48  worker.on('message', common.mustCall(({ buffer }) => {
49    assert(buffer instanceof SharedArrayBuffer);
50    worker.buf = buffer; // Basically just keep the reference to buffer alive.
51  }, 2));
52  worker.once('exit', common.mustCall());
53  worker.postMessage({ wasmModule });
54}
55