Skip to content

Commit 8a67aaf

Browse files
authored
Fix Wasm Workers in node.js (#20188)
1 parent 12777ca commit 8a67aaf

File tree

9 files changed

+88
-20
lines changed

9 files changed

+88
-20
lines changed

emscripten.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -912,6 +912,7 @@ def create_pointer_conversion_wrappers(metadata):
912912
'__main_argc_argv': '__PP',
913913
'emscripten_stack_set_limits': '_pp',
914914
'__set_stack_limits': '_pp',
915+
'__set_thread_state': '_p___',
915916
'__cxa_can_catch': '_ppp',
916917
'__cxa_increment_exception_refcount': '_p',
917918
'__cxa_decrement_exception_refcount': '_p',

src/library_wasm_worker.js

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,14 @@ addToLibrary({
4747
$_wasmWorkerRunPostMessage: (e) => {
4848
// '_wsc' is short for 'wasm call', trying to use an identifier name that
4949
// will never conflict with user code
50-
let data = e.data, wasmCall = data['_wsc'];
50+
#if ENVIRONMENT_MAY_BE_NODE
51+
// In Node.js environment, message event 'e' containing the actual data sent,
52+
// while in the browser environment it's contained by 'e.data'.
53+
let data = ENVIRONMENT_IS_NODE ? e : e.data;
54+
#else
55+
let data = e.data;
56+
#endif
57+
let wasmCall = data['_wsc'];
5158
wasmCall && getWasmTableEntry(wasmCall)(...data['x']);
5259
},
5360

@@ -155,6 +162,12 @@ if (ENVIRONMENT_IS_WASM_WORKER) {
155162
#endif
156163
'sb': stackLowestAddress, // sb = stack bottom (lowest stack address, SP points at this when stack is full)
157164
'sz': stackSize, // sz = stack size
165+
#if USE_OFFSET_CONVERTER
166+
'wasmOffsetData': wasmOffsetConverter,
167+
#endif
168+
#if LOAD_SOURCE_MAP
169+
'wasmSourceMapData': wasmSourceMap,
170+
#endif
158171
});
159172
worker.onmessage = _wasmWorkerRunPostMessage;
160173
return _wasmWorkersID++;

src/parseTools.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -736,6 +736,18 @@ function runIfMainThread(text) {
736736
}
737737
}
738738

739+
function runIfWorkerThread(text) {
740+
if (WASM_WORKERS && PTHREADS) {
741+
return `if (ENVIRONMENT_IS_WASM_WORKER || ENVIRONMENT_IS_PTHREAD) { ${text} }`;
742+
} else if (WASM_WORKERS) {
743+
return `if (ENVIRONMENT_IS_WASM_WORKER) { ${text} }`;
744+
} else if (PTHREADS) {
745+
return `if (ENVIRONMENT_IS_PTHREAD) { ${text} }`;
746+
} else {
747+
return '';
748+
}
749+
}
750+
739751
function expectToReceiveOnModule(name) {
740752
return INCOMING_MODULE_JS_API.has(name);
741753
}
@@ -1031,3 +1043,7 @@ function getPerformanceNow() {
10311043
return 'performance.now';
10321044
}
10331045
}
1046+
1047+
function implicitSelf() {
1048+
return ENVIRONMENT.includes('node') ? 'self.' : '';
1049+
}

src/preamble.js

Lines changed: 7 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -785,7 +785,7 @@ function instantiateSync(file, info) {
785785
}
786786
#endif
787787

788-
#if PTHREADS && (LOAD_SOURCE_MAP || USE_OFFSET_CONVERTER)
788+
#if (PTHREADS || WASM_WORKERS) && (LOAD_SOURCE_MAP || USE_OFFSET_CONVERTER)
789789
// When using postMessage to send an object, it is processed by the structured
790790
// clone algorithm. The prototype, and hence methods, on that object is then
791791
// lost. This function adds back the lost prototype. This does not work with
@@ -1082,22 +1082,18 @@ function createWasm() {
10821082
// path.
10831083
if (Module['instantiateWasm']) {
10841084

1085-
#if USE_OFFSET_CONVERTER && PTHREADS
1086-
if (ENVIRONMENT_IS_PTHREAD) {
1085+
#if USE_OFFSET_CONVERTER
10871086
#if ASSERTIONS
1088-
assert(Module['wasmOffsetData'], 'wasmOffsetData not found on Module object');
1087+
{{{ runIfWorkerThread("assert(Module['wasmOffsetData'], 'wasmOffsetData not found on Module object');") }}}
10891088
#endif
1090-
wasmOffsetConverter = resetPrototype(WasmOffsetConverter, Module['wasmOffsetData']);
1091-
}
1089+
{{{ runIfWorkerThread("wasmOffsetConverter = resetPrototype(WasmOffsetConverter, Module['wasmOffsetData']);") }}}
10921090
#endif
10931091

1094-
#if LOAD_SOURCE_MAP && PTHREADS
1095-
if (ENVIRONMENT_IS_PTHREAD) {
1092+
#if LOAD_SOURCE_MAP
10961093
#if ASSERTIONS
1097-
assert(Module['wasmSourceMapData'], 'wasmSourceMapData not found on Module object');
1094+
{{{ runIfWorkerThread("assert(Module['wasmSourceMapData'], 'wasmSourceMapData not found on Module object');") }}}
10981095
#endif
1099-
wasmSourceMap = resetPrototype(WasmSourceMap, Module['wasmSourceMapData']);
1100-
}
1096+
{{{ runIfWorkerThread("wasmSourceMap = resetPrototype(WasmSourceMap, Module['wasmSourceMapData']);") }}}
11011097
#endif
11021098

11031099
try {

src/wasm_worker.js

Lines changed: 36 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,51 @@
11
// N.B. The contents of this file are duplicated in src/library_wasm_worker.js
22
// in variable "_wasmWorkerBlobUrl" (where the contents are pre-minified) If
33
// doing any changes to this file, be sure to update the contents there too.
4-
onmessage = function(d) {
4+
5+
'use strict';
6+
7+
#if ENVIRONMENT_MAY_BE_NODE
8+
// Node.js support
9+
var ENVIRONMENT_IS_NODE = typeof process == 'object' && typeof process.versions == 'object' && typeof process.versions.node == 'string';
10+
if (ENVIRONMENT_IS_NODE) {
11+
// Create as web-worker-like an environment as we can.
12+
13+
var nodeWorkerThreads = require('worker_threads');
14+
15+
var parentPort = nodeWorkerThreads.parentPort;
16+
17+
parentPort.on('message', (data) => typeof onmessage === "function" && onmessage({ data: data }));
18+
19+
var fs = require('fs');
20+
21+
Object.assign(global, {
22+
self: global,
23+
require,
24+
location: {
25+
href: __filename
26+
},
27+
Worker: nodeWorkerThreads.Worker,
28+
importScripts: (f) => (0, eval)(fs.readFileSync(f, 'utf8') + '//# sourceURL=' + f),
29+
postMessage: (msg) => parentPort.postMessage(msg),
30+
performance: global.performance || { now: Date.now },
31+
addEventListener: (name, handler) => parentPort.on(name, handler),
32+
removeEventListener: (name, handler) => parentPort.off(name, handler),
33+
});
34+
}
35+
#endif // ENVIRONMENT_MAY_BE_NODE
36+
37+
{{{ implicitSelf() }}}onmessage = function(d) {
538
// The first message sent to the Worker is always the bootstrap message.
639
// Drop this message listener, it served its purpose of bootstrapping
740
// the Wasm Module load, and is no longer needed. Let user code register
841
// any desired message handlers from now on.
9-
onmessage = null;
42+
{{{ implicitSelf() }}}onmessage = null;
1043
d = d.data;
1144
#if !MODULARIZE
1245
self.{{{ EXPORT_NAME }}} = d;
1346
#endif
1447
#if !MINIMAL_RUNTIME
15-
d['instantiateWasm'] = (info, receiveInstance) => { var instance = new WebAssembly.Instance(d['wasm'], info); receiveInstance(instance, d['wasm']); return instance.exports; }
48+
d['instantiateWasm'] = (info, receiveInstance) => { var instance = new WebAssembly.Instance(d['wasm'], info); return receiveInstance(instance, d['wasm']); }
1649
#endif
1750
importScripts(d.js);
1851
#if MODULARIZE

test/test_core.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9912,16 +9912,23 @@ def test_emscripten_async_load_script(self):
99129912
self.run_process([FILE_PACKAGER, 'test.data', '--preload', 'file1.txt', 'file2.txt', '--from-emcc', '--js-output=script2.js'])
99139913
self.do_runf(test_file('test_emscripten_async_load_script.c'), emcc_args=['-sFORCE_FILESYSTEM'])
99149914

9915+
def prep_wasm_worker_in_node(self):
9916+
# Auto exit after 3 seconds in Nodejs environment to get WASM Worker stdout
9917+
self.add_pre_run("setTimeout(()=>process.exit(), 3000);")
9918+
99159919
@node_pthreads
99169920
def test_wasm_worker_hello(self):
9917-
self.do_runf(test_file('wasm_worker/hello_wasm_worker.c'), emcc_args=['-sWASM_WORKERS'])
9921+
self.prep_wasm_worker_in_node()
9922+
self.do_run_in_out_file_test(test_file('wasm_worker/hello_wasm_worker.c'), emcc_args=['-sWASM_WORKERS'])
99189923

99199924
@node_pthreads
99209925
def test_wasm_worker_malloc(self):
9921-
self.do_runf(test_file('wasm_worker/malloc_wasm_worker.c'), emcc_args=['-sWASM_WORKERS'])
9926+
self.prep_wasm_worker_in_node()
9927+
self.do_run_in_out_file_test(test_file('wasm_worker/malloc_wasm_worker.c'), emcc_args=['-sWASM_WORKERS'])
99229928

99239929
@node_pthreads
99249930
def test_wasm_worker_wait_async(self):
9931+
self.prep_wasm_worker_in_node()
99259932
self.do_runf(test_file('wasm_worker/wait_async.c'), emcc_args=['-sWASM_WORKERS'])
99269933

99279934

test/wasm_worker/hello_wasm_worker.c

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
1-
#include <assert.h>
1+
#include <emscripten.h>
22
#include <emscripten/wasm_worker.h>
3-
#include <stdio.h>
3+
#include <assert.h>
44

55
// This is the code example in site/source/docs/api_reference/wasm_workers.rst
66

77
void run_in_worker()
88
{
9-
printf("Hello from wasm worker!\n");
9+
emscripten_console_log("Hello from wasm worker!\n");
1010
#ifdef REPORT_RESULT
1111
REPORT_RESULT(0);
1212
#endif
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Hello from wasm worker!
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Hello from wasm worker!

0 commit comments

Comments
 (0)