Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/codegen/generate-js2native.ts
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,8 @@ export function getJS2NativeCPP() {
"\n" + "namespace JS2NativeGenerated {",
"using namespace Bun;",
"using namespace JSC;",
"using namespace WebCore;" + "\n",
"using namespace WebCore;",
"using namespace Zig;" + "\n",
...nativeCallStrings,
...wrapperCallStrings,
...nativeCalls
Expand Down
41 changes: 22 additions & 19 deletions src/js/node/worker_threads.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
// import type { Readable, Writable } from "node:stream";
// import type { WorkerOptions } from "node:worker_threads";
declare const self: typeof globalThis;
type WebWorker = InstanceType<typeof globalThis.Worker>;

const EventEmitter = require("node:events");
Expand Down Expand Up @@ -754,29 +753,29 @@ function receiveMessageOnPort(port: MessagePort) {

// TODO: parent port emulation is not complete
function fakeParentPort() {
// Inside a node:worker_threads worker the Web Worker globals
// (self/addEventListener/postMessage/...) are not on globalThis, so reach
// the backing global EventTarget through direct native bindings instead.
const postMessage = $newCppFunction("ZigGlobalObject.cpp", "jsFunctionPostMessage", 1);
const addEventListener = $newCppFunction("ZigGlobalObject.cpp", "jsFunctionAddEventListener", 2);
const removeEventListener = $newCppFunction("ZigGlobalObject.cpp", "jsFunctionRemoveEventListener", 2);
const dispatchEvent = $newCppFunction("ZigGlobalObject.cpp", "jsFunctionDispatchEvent", 1);

const fake = Object.create(MessagePort.prototype);

Object.defineProperty(fake, "onmessage", {
get() {
return self.onmessage;
},
set(value) {
self.onmessage = value;
},
get: $newCppFunction("ZigGlobalObject.cpp", "jsFunctionGetGlobalOnMessage", 0),
set: $newCppFunction("ZigGlobalObject.cpp", "jsFunctionSetGlobalOnMessage", 1),
});

Object.defineProperty(fake, "onmessageerror", {
get() {
return self.onmessageerror;
},
set(value) {
self.onmessageerror = value;
},
get: $newCppFunction("ZigGlobalObject.cpp", "jsFunctionGetGlobalOnMessageError", 0),
set: $newCppFunction("ZigGlobalObject.cpp", "jsFunctionSetGlobalOnMessageError", 1),
});

const postMessage = $newCppFunction("ZigGlobalObject.cpp", "jsFunctionPostMessage", 1);
Object.defineProperty(fake, "postMessage", {
value(...args: [any, any]) {
return postMessage.$apply(null, args);
return postMessage.$apply(undefined, args);
},
});

Expand Down Expand Up @@ -807,20 +806,24 @@ function fakeParentPort() {
});

Object.defineProperty(fake, "addEventListener", {
value: self.addEventListener.bind(self),
value: addEventListener,
});

Object.defineProperty(fake, "removeEventListener", {
value: self.removeEventListener.bind(self),
value: removeEventListener,
});

Object.defineProperty(fake, "dispatchEvent", {
value: dispatchEvent,
});

Object.defineProperty(fake, "removeListener", {
value: self.removeEventListener.bind(self),
value: removeEventListener,
enumerable: false,
});

Object.defineProperty(fake, "addListener", {
value: self.addEventListener.bind(self),
value: addEventListener,
enumerable: false,
});

Expand Down
80 changes: 65 additions & 15 deletions src/jsc/bindings/ZigGlobalObject.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -417,9 +417,10 @@ GlobalObject* GlobalObject::create(JSC::VM& vm, JSC::Structure* structure)
return ptr;
}

GlobalObject* GlobalObject::create(JSC::VM& vm, JSC::Structure* structure, uint32_t scriptExecutionContextId)
GlobalObject* GlobalObject::create(JSC::VM& vm, JSC::Structure* structure, uint32_t scriptExecutionContextId, bool isNodeWorker)
{
GlobalObject* ptr = new (NotNull, JSC::allocateCell<GlobalObject>(vm)) GlobalObject(vm, structure, scriptExecutionContextId, &globalObjectMethodTable());
ptr->m_isNodeWorker = isNodeWorker;
ptr->finishCreation(vm);
return ptr;
}
Expand Down Expand Up @@ -509,6 +510,8 @@ extern "C" JSC::JSGlobalObject* Zig__GlobalObject__create(void* console_client,

WebCore::JSVMClientData::create(&vm, Bun__getVM());

bool isNodeWorker = worker_ptr && static_cast<WebCore::Worker*>(worker_ptr)->options().kind == WebCore::WorkerOptions::Kind::Node;

const auto createGlobalObject = [&]() -> Zig::GlobalObject* {
if (executionContextId == std::numeric_limits<int32_t>::max() || executionContextId > 1) [[unlikely]] {
auto* structure = Zig::GlobalObject::createStructure(vm);
Expand All @@ -518,7 +521,8 @@ extern "C" JSC::JSGlobalObject* Zig__GlobalObject__create(void* console_client,
return Zig::GlobalObject::create(
vm,
structure,
static_cast<ScriptExecutionContextIdentifier>(executionContextId));
static_cast<ScriptExecutionContextIdentifier>(executionContextId),
isNodeWorker);
} else if (evalMode) {
auto* structure = Zig::EvalGlobalObject::createStructure(vm);
if (!structure) [[unlikely]] {
Expand Down Expand Up @@ -1188,6 +1192,43 @@ JSC_DEFINE_CUSTOM_SETTER(setGlobalOnError,
return true;
}

// Host-function wrappers so node:worker_threads' fakeParentPort can reach the
// globalEventScope attribute-listener slot without the onmessage/onerror
// accessors being exposed on globalThis.
JSC_DEFINE_HOST_FUNCTION(jsFunctionGetGlobalOnMessage, (JSC::JSGlobalObject * lexicalGlobalObject, JSC::CallFrame*))
{
auto* globalObject = defaultGlobalObject(lexicalGlobalObject);
return JSValue::encode(eventHandlerAttribute(globalObject->eventTarget(), eventNames().messageEvent, globalObject->world()));
}

JSC_DEFINE_HOST_FUNCTION(jsFunctionSetGlobalOnMessage, (JSC::JSGlobalObject * lexicalGlobalObject, JSC::CallFrame* callFrame))
{
auto& vm = JSC::getVM(lexicalGlobalObject);
auto* globalObject = defaultGlobalObject(lexicalGlobalObject);
JSValue value = callFrame->argument(0);
setEventHandlerAttribute<JSEventListener>(globalObject->eventTarget(), eventNames().messageEvent, value, *globalObject);
vm.writeBarrier(globalObject, value);
ensureStillAliveHere(value);
return JSValue::encode(jsUndefined());
}

JSC_DEFINE_HOST_FUNCTION(jsFunctionGetGlobalOnMessageError, (JSC::JSGlobalObject * lexicalGlobalObject, JSC::CallFrame*))
{
auto* globalObject = defaultGlobalObject(lexicalGlobalObject);
return JSValue::encode(eventHandlerAttribute(globalObject->eventTarget(), eventNames().messageerrorEvent, globalObject->world()));
}

JSC_DEFINE_HOST_FUNCTION(jsFunctionSetGlobalOnMessageError, (JSC::JSGlobalObject * lexicalGlobalObject, JSC::CallFrame* callFrame))
{
auto& vm = JSC::getVM(lexicalGlobalObject);
auto* globalObject = defaultGlobalObject(lexicalGlobalObject);
JSValue value = callFrame->argument(0);
setEventHandlerAttribute<JSEventListener>(globalObject->eventTarget(), eventNames().messageerrorEvent, value, *globalObject);
vm.writeBarrier(globalObject, value);
ensureStillAliveHere(value);
return JSValue::encode(jsUndefined());
}

WebCore::EventTarget& GlobalObject::eventTarget()
{
return globalEventScope;
Expand Down Expand Up @@ -3172,20 +3213,29 @@ void GlobalObject::addBuiltinGlobals(JSC::VM& vm)

// ----- Public Properties -----

// a direct accessor (uses js functions for get and set) cannot be on the lookup table. i think.
putDirectAccessor(
this,
builtinNames.selfPublicName(),
JSC::GetterSetter::create(
vm,
// Web Worker-style globals. Node.js worker_threads workers don't expose
// these on globalThis; node:worker_threads reaches the backing
// globalEventScope via $newCppFunction instead (see fakeParentPort).
if (!m_isNodeWorker) {
// A JSFunction-backed accessor cannot live in the static lookup table.
putDirectAccessor(
this,
JSFunction::create(vm, this, 0, "get"_s, functionGetSelf, ImplementationVisibility::Public),
JSFunction::create(vm, this, 0, "set"_s, functionSetSelf, ImplementationVisibility::Public)),
PropertyAttribute::Accessor | 0);

// TODO: this should be usable on the lookup table. it crashed las time i tried it
putDirectCustomAccessor(vm, JSC::Identifier::fromString(vm, "onmessage"_s), JSC::CustomGetterSetter::create(vm, globalOnMessage, setGlobalOnMessage), 0);
putDirectCustomAccessor(vm, JSC::Identifier::fromString(vm, "onerror"_s), JSC::CustomGetterSetter::create(vm, globalOnError, setGlobalOnError), 0);
builtinNames.selfPublicName(),
JSC::GetterSetter::create(
vm,
this,
JSFunction::create(vm, this, 0, "get"_s, functionGetSelf, ImplementationVisibility::Public),
JSFunction::create(vm, this, 0, "set"_s, functionSetSelf, ImplementationVisibility::Public)),
PropertyAttribute::Accessor | 0);

putDirectCustomAccessor(vm, JSC::Identifier::fromString(vm, "onmessage"_s), JSC::CustomGetterSetter::create(vm, globalOnMessage, setGlobalOnMessage), 0);
putDirectCustomAccessor(vm, JSC::Identifier::fromString(vm, "onerror"_s), JSC::CustomGetterSetter::create(vm, globalOnError, setGlobalOnError), 0);

putDirectNativeFunction(vm, this, JSC::Identifier::fromString(vm, "addEventListener"_s), 2, jsFunctionAddEventListener, ImplementationVisibility::Public, NoIntrinsic, 0);
putDirectNativeFunction(vm, this, JSC::Identifier::fromString(vm, "removeEventListener"_s), 2, jsFunctionRemoveEventListener, ImplementationVisibility::Public, NoIntrinsic, 0);
putDirectNativeFunction(vm, this, JSC::Identifier::fromString(vm, "dispatchEvent"_s), 1, jsFunctionDispatchEvent, ImplementationVisibility::Public, NoIntrinsic, 0);
putDirectNativeFunction(vm, this, JSC::Identifier::fromString(vm, "postMessage"_s), 1, WebCore::jsFunctionPostMessage, ImplementationVisibility::Public, NoIntrinsic, 0);
}

// ----- Extensions to Built-in objects -----

Expand Down
16 changes: 15 additions & 1 deletion src/jsc/bindings/ZigGlobalObject.h
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ class GlobalObject : public Bun::GlobalScope {
}

static GlobalObject* create(JSC::VM& vm, JSC::Structure* structure);
static GlobalObject* create(JSC::VM& vm, JSC::Structure* structure, uint32_t scriptExecutionContextId);
static GlobalObject* create(JSC::VM& vm, JSC::Structure* structure, uint32_t scriptExecutionContextId, bool isNodeWorker = false);
static GlobalObject* create(JSC::VM& vm, JSC::Structure* structure, const JSC::GlobalObjectMethodTable* methodTable);
static GlobalObject* create(JSC::VM& vm, JSC::Structure* structure, uint32_t scriptExecutionContextId, const JSC::GlobalObjectMethodTable* methodTable);

Expand Down Expand Up @@ -364,6 +364,10 @@ class GlobalObject : public Bun::GlobalScope {
}
#endif
bool isThreadLocalDefaultGlobalObject = false;
// Set by Zig__GlobalObject__create before finishCreation() when this
// global backs a node:worker_threads worker. Gates the Web Worker
// globals (self/postMessage/addEventListener/...) in addBuiltinGlobals.
bool m_isNodeWorker = false;

JSObject* subtleCrypto() { return m_subtleCryptoObject.getInitializedOnMainThread(this); }

Expand Down Expand Up @@ -905,6 +909,16 @@ inline void* bunVM(Zig::GlobalObject* globalObject)
JSC_DECLARE_HOST_FUNCTION(jsFunctionNotImplemented);
JSC_DECLARE_HOST_FUNCTION(jsFunctionCreateFunctionThatMasqueradesAsUndefined);

namespace Zig {
JSC_DECLARE_HOST_FUNCTION(jsFunctionAddEventListener);
JSC_DECLARE_HOST_FUNCTION(jsFunctionRemoveEventListener);
JSC_DECLARE_HOST_FUNCTION(jsFunctionDispatchEvent);
JSC_DECLARE_HOST_FUNCTION(jsFunctionGetGlobalOnMessage);
JSC_DECLARE_HOST_FUNCTION(jsFunctionSetGlobalOnMessage);
JSC_DECLARE_HOST_FUNCTION(jsFunctionGetGlobalOnMessageError);
JSC_DECLARE_HOST_FUNCTION(jsFunctionSetGlobalOnMessageError);
} // namespace Zig

extern "C" JSC::EncodedJSValue ZigGlobalObject__readableStreamToText(Zig::GlobalObject* globalObject, JSC::EncodedJSValue readableStreamValue);
extern "C" JSC::EncodedJSValue ZigGlobalObject__readableStreamToArrayBuffer(Zig::GlobalObject* globalObject, JSC::EncodedJSValue readableStreamValue);
extern "C" JSC::EncodedJSValue ZigGlobalObject__readableStreamToBytes(Zig::GlobalObject* globalObject, JSC::EncodedJSValue readableStreamValue);
Expand Down
4 changes: 0 additions & 4 deletions src/jsc/bindings/ZigGlobalObject.lut.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,16 @@

/* Source for ZigGlobalObject.lut.h
@begin bunGlobalObjectTable
addEventListener jsFunctionAddEventListener Function 2
alert WebCore__alert Function 1
atob functionATOB Function 1
btoa functionBTOA Function 1
clearImmediate functionClearImmediate Function 1
clearInterval functionClearInterval Function 1
clearTimeout functionClearTimeout Function 1
confirm WebCore__confirm Function 1
dispatchEvent jsFunctionDispatchEvent Function 1
fetch constructBunFetchObject PropertyCallback
postMessage jsFunctionPostMessage Function 1
prompt WebCore__prompt Function 1
queueMicrotask functionQueueMicrotask Function 1
removeEventListener jsFunctionRemoveEventListener Function 2
reportError functionReportError Function 1
setImmediate functionSetImmediate Function 1
setInterval functionSetInterval Function 1
Expand Down
35 changes: 35 additions & 0 deletions test/js/node/worker_threads/worker-shadow-global-fixture.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading