Skip to content

Commit b581535

Browse files
committed
Fix the WASM Worker cannot start in node.js environment
`emscripten_malloc_wasm_worker` and `emscripten_create_wasm_worker` functions adapted to the nodejs environment and modified the core related tests.
1 parent 813a727 commit b581535

File tree

8 files changed

+101
-21
lines changed

8 files changed

+101
-21
lines changed

emscripten.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -910,6 +910,7 @@ def create_pointer_conversion_wrappers(metadata):
910910
'__main_argc_argv': '__PP',
911911
'emscripten_stack_set_limits': '_pp',
912912
'__set_stack_limits': '_pp',
913+
'__set_thread_state': '_p___',
913914
'__cxa_can_catch': '_ppp',
914915
'__cxa_increment_exception_refcount': '_p',
915916
'__cxa_decrement_exception_refcount': '_p',

src/library_wasm_worker.js

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,12 @@ 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+
let data = ENVIRONMENT_IS_NODE ? e : e.data;
52+
#else
53+
let data = e.data;
54+
#endif
55+
let wasmCall = data['_wsc'];
5156
wasmCall && getWasmTableEntry(wasmCall)(...data['x']);
5257
},
5358

@@ -155,6 +160,12 @@ if (ENVIRONMENT_IS_WASM_WORKER) {
155160
#endif
156161
'sb': stackLowestAddress, // sb = stack bottom (lowest stack address, SP points at this when stack is full)
157162
'sz': stackSize, // sz = stack size
163+
#if USE_OFFSET_CONVERTER
164+
'wasmOffsetData': wasmOffsetConverter,
165+
#endif
166+
#if LOAD_SOURCE_MAP
167+
'wasmSourceMapData': wasmSourceMap,
168+
#endif
158169
});
159170
worker.onmessage = _wasmWorkerRunPostMessage;
160171
return _wasmWorkersID++;

src/parseTools.js

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

737+
function runIfWorkerThread(text) {
738+
if (WASM_WORKERS && PTHREADS) {
739+
return 'if (ENVIRONMENT_IS_WASM_WORKER || ENVIRONMENT_IS_PTHREAD) { ' + text + ' }';
740+
} else if (WASM_WORKERS) {
741+
return 'if (ENVIRONMENT_IS_WASM_WORKER) { ' + text + ' }';
742+
} else if (PTHREADS) {
743+
return 'if (ENVIRONMENT_IS_PTHREAD) { ' + text + ' }';
744+
} else {
745+
return '';
746+
}
747+
}
748+
737749
// Legacy name for runIfMainThread.
738750
// TODO(remove).
739751
const runOnMainThread = runIfMainThread;
@@ -1021,3 +1033,7 @@ function getPerformanceNow() {
10211033
return 'performance.now';
10221034
}
10231035
}
1036+
1037+
function implicitSelf() {
1038+
return ENVIRONMENT.includes('node') ? 'self.' : '';
1039+
}

src/preamble.js

Lines changed: 25 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -226,14 +226,16 @@ function initRuntime() {
226226
#endif
227227
runtimeInitialized = true;
228228

229-
#if WASM_WORKERS
230-
if (ENVIRONMENT_IS_WASM_WORKER) return _wasmWorkerInitializeRuntime();
231-
#endif
232-
233229
#if PTHREADS
234230
if (ENVIRONMENT_IS_PTHREAD) return;
235231
#endif
236232

233+
#if WASM_WORKERS
234+
if (ENVIRONMENT_IS_WASM_WORKER) {
235+
_wasmWorkerInitializeRuntime();
236+
} else {
237+
#endif
238+
237239
#if STACK_OVERFLOW_CHECK
238240
checkStackCookie();
239241
#endif
@@ -245,7 +247,19 @@ function initRuntime() {
245247
#if RELOCATABLE
246248
callRuntimeCallbacks(__RELOC_FUNCS__);
247249
#endif
250+
251+
#if WASM_WORKERS
252+
}
253+
#endif
254+
248255
<<< ATINITS >>>
256+
257+
#if WASM_WORKERS
258+
if (ENVIRONMENT_IS_WASM_WORKER) {
259+
return;
260+
}
261+
#endif
262+
249263
callRuntimeCallbacks(__ATINIT__);
250264
}
251265

@@ -792,7 +806,7 @@ function instantiateSync(file, info) {
792806
}
793807
#endif
794808

795-
#if PTHREADS && (LOAD_SOURCE_MAP || USE_OFFSET_CONVERTER)
809+
#if (PTHREADS || WASM_WORKERS) && (LOAD_SOURCE_MAP || USE_OFFSET_CONVERTER)
796810
// When using postMessage to send an object, it is processed by the structured
797811
// clone algorithm. The prototype, and hence methods, on that object is then
798812
// lost. This function adds back the lost prototype. This does not work with
@@ -1089,22 +1103,18 @@ function createWasm() {
10891103
// path.
10901104
if (Module['instantiateWasm']) {
10911105

1092-
#if USE_OFFSET_CONVERTER && PTHREADS
1093-
if (ENVIRONMENT_IS_PTHREAD) {
1106+
#if USE_OFFSET_CONVERTER
10941107
#if ASSERTIONS
1095-
assert(Module['wasmOffsetData'], 'wasmOffsetData not found on Module object');
1108+
{{{ runIfWorkerThread("assert(Module['wasmOffsetData'], 'wasmOffsetData not found on Module object');") }}}
10961109
#endif
1097-
wasmOffsetConverter = resetPrototype(WasmOffsetConverter, Module['wasmOffsetData']);
1098-
}
1110+
{{{ runIfWorkerThread("wasmOffsetConverter = resetPrototype(WasmOffsetConverter, Module['wasmOffsetData']);") }}}
10991111
#endif
11001112

1101-
#if LOAD_SOURCE_MAP && PTHREADS
1102-
if (ENVIRONMENT_IS_PTHREAD) {
1113+
#if LOAD_SOURCE_MAP
11031114
#if ASSERTIONS
1104-
assert(Module['wasmSourceMapData'], 'wasmSourceMapData not found on Module object');
1115+
{{{ runIfWorkerThread("assert(Module['wasmSourceMapData'], 'wasmSourceMapData not found on Module object');") }}}
11051116
#endif
1106-
wasmSourceMap = resetPrototype(WasmSourceMap, Module['wasmSourceMapData']);
1107-
}
1117+
{{{ runIfWorkerThread("wasmSourceMap = resetPrototype(WasmSourceMap, Module['wasmSourceMapData']);") }}}
11081118
#endif
11091119

11101120
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
@@ -9845,16 +9845,23 @@ def test_emscripten_async_load_script(self):
98459845
self.run_process([FILE_PACKAGER, 'test.data', '--preload', 'file1.txt', 'file2.txt', '--from-emcc', '--js-output=script2.js'])
98469846
self.do_runf(test_file('test_emscripten_async_load_script.c'), emcc_args=['-sFORCE_FILESYSTEM'])
98479847

9848+
def prep_wsam_worker_in_node(self):
9849+
# Auto exit after 3 seconds in Nodejs environment to get WASM Worker stdout
9850+
self.add_pre_run("setTimeout(()=>process.exit(), 3000);")
9851+
98489852
@node_pthreads
98499853
def test_wasm_worker_hello(self):
9850-
self.do_runf(test_file('wasm_worker/hello_wasm_worker.c'), emcc_args=['-sWASM_WORKERS'])
9854+
self.prep_wsam_worker_in_node()
9855+
self.do_run_in_out_file_test(test_file('wasm_worker/hello_wasm_worker.c'), emcc_args=['-sWASM_WORKERS'])
98519856

98529857
@node_pthreads
98539858
def test_wasm_worker_malloc(self):
9854-
self.do_runf(test_file('wasm_worker/malloc_wasm_worker.c'), emcc_args=['-sWASM_WORKERS'])
9859+
self.prep_wsam_worker_in_node()
9860+
self.do_run_in_out_file_test(test_file('wasm_worker/malloc_wasm_worker.c'), emcc_args=['-sWASM_WORKERS'])
98559861

98569862
@node_pthreads
98579863
def test_wasm_worker_wait_async(self):
9864+
self.prep_wsam_worker_in_node()
98589865
self.do_runf(test_file('wasm_worker/wait_async.c'), emcc_args=['-sWASM_WORKERS'])
98599866

98609867

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)