Skip to content
Closed
Show file tree
Hide file tree
Changes from 10 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
12 changes: 11 additions & 1 deletion src/jsc/AbortSignal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ unsafe extern "C" {
// the non-`repr(C)` interior of `EventLoopTimer` is irrelevant to FFI.
#[allow(improper_ctypes)]
safe fn WebCore__AbortSignal__getTimeout(arg0: &AbortSignal) -> *mut Timeout;
safe fn WebCore__AbortSignal__clearTimeoutAsyncContext(arg0: &AbortSignal);
safe fn WebCore__AbortSignal__signal(
arg0: &AbortSignal,
arg1: &JSGlobalObject,
Expand Down Expand Up @@ -209,6 +210,13 @@ impl AbortSignal {
// (see doc comment).
NonNull::new(ptr).map(|p| unsafe { p.as_ref() })
}

/// Release the async context snapshot AbortSignal.timeout() captured.
/// Every path that retires the timer without going through the C++
/// `cancelTimer()` must call this, or the snapshot stays a GC root.
pub fn clear_timeout_async_context(&self) {
WebCore__AbortSignal__clearTimeoutAsyncContext(self)
}
}

// SAFETY: `WebCore::AbortSignal` is intrusively refcounted on the C++ side
Expand Down Expand Up @@ -371,8 +379,10 @@ impl Timeout {

// The signal and its handlers belong to a previous isolated test
// file's global; firing now would run them against the new global.
// Drop the extra ref that signalAbort() would have released.
// Release the async context snapshot (this path never reaches
// cancelTimer()), then drop the extra ref signalAbort() would have.
if (*this).generation != (*vm).test_isolation_generation {
(*(*this).signal).clear_timeout_async_context();
(*(*this).signal).unref();
return;
}
Expand Down
37 changes: 37 additions & 0 deletions src/jsc/bindings/AsyncContextFrame.cpp
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
#include "root.h"
#include "ZigGlobalObject.h"
#include "AsyncContextFrame.h"
#include "JSValueInWrappedObject.h"
#include <JavaScriptCore/InternalFieldTuple.h>
#include <JavaScriptCore/StrongInlines.h>

#if ASSERT_ENABLED
#include <JavaScriptCore/IntegrityInlines.h>
Expand Down Expand Up @@ -34,6 +36,41 @@ JSC::Structure* AsyncContextFrame::createStructure(JSC::VM& vm, JSC::JSGlobalObj
return Structure::create(vm, globalObject, jsNull(), TypeInfo(ObjectType, StructureFlags), info());
}

void AsyncContextFrame::captureCurrentContext(JSGlobalObject* globalObject, WebCore::JSValueInWrappedObject& slot)
{
JSValue context = globalObject->m_asyncContextData.get()->getInternalField(0);
// If there is no async context, do not snapshot it.
if (context.isUndefined())
return;
slot.setWeakly(context);
}

void AsyncContextFrame::captureCurrentContext(JSGlobalObject* globalObject, JSC::Strong<JSC::Unknown>& slot)
{
JSValue context = globalObject->m_asyncContextData.get()->getInternalField(0);
// If there is no async context, do not snapshot it.
if (context.isUndefined())
return;
slot.set(globalObject->vm(), context);
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

AsyncContextFrameScope::AsyncContextFrameScope(JSGlobalObject* globalObject, JSValue context)
{
if (!globalObject || !context || context.isUndefined())
return;
m_globalObject = globalObject;
auto* asyncContextData = globalObject->m_asyncContextData.get();
m_previousContext = asyncContextData->getInternalField(0);
asyncContextData->putInternalField(globalObject->vm(), 0, context);
}

AsyncContextFrameScope::~AsyncContextFrameScope()
{
if (!m_globalObject)
return;
m_globalObject->m_asyncContextData.get()->putInternalField(m_globalObject->vm(), 0, m_previousContext);
}

JSValue AsyncContextFrame::withAsyncContextIfNeeded(JSGlobalObject* globalObject, JSValue callback)
{
JSValue context = globalObject->m_asyncContextData.get()->getInternalField(0);
Expand Down
45 changes: 45 additions & 0 deletions src/jsc/bindings/AsyncContextFrame.h
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,12 @@
#include "root.h"
#include "BunClientData.h"
#include <JavaScriptCore/CallData.h>
#include <JavaScriptCore/Strong.h>
#include <wtf/Noncopyable.h>

namespace WebCore {
class JSValueInWrappedObject;
}

class AsyncContextFrame : public JSC::JSNonFinalObject {
public:
Expand All @@ -17,6 +23,23 @@ class AsyncContextFrame : public JSC::JSNonFinalObject {
// When given a JSFunction that you want to call later, wrap it with this function
static JSC::JSValue withAsyncContextIfNeeded(JSC::JSGlobalObject* globalObject, JSC::JSValue callback);

// Snapshots the currently-active async context (the value AsyncLocalStorage
// is running with) into `slot`, for AsyncContextFrameScope to restore
// around a later asynchronous event dispatch. No-op when there is none.
//
// Prefer the JSValueInWrappedObject overload and visit `slot` from the
// owner's JS wrapper. The snapshot can reference that wrapper (the user's
// store may hold the resource), so rooting it with a JSC::Strong on an
// object whose wrapper holds a Ref back to it forms an uncollectable
// native-to-GC cycle. Only use the Strong overload when a GC-independent
// release is guaranteed to run: AbortSignal.timeout() needs it (its abort
// is observed through a dependent AbortSignal.any() signal's wrapper, not
// its own), and every path that retires its timer, including the Rust
// teardown paths that never reach cancelTimer(), calls
// clearTimeoutAsyncContext() to drop the handle.
static void captureCurrentContext(JSC::JSGlobalObject* globalObject, WebCore::JSValueInWrappedObject& slot);
static void captureCurrentContext(JSC::JSGlobalObject* globalObject, JSC::Strong<JSC::Unknown>& slot);

// The following is JSC::call but
// - it unwraps AsyncContextFrame
// - does not take a CallData, because JSC::getCallData(AsyncContextFrame) -> not callable
Expand Down Expand Up @@ -64,3 +87,25 @@ class AsyncContextFrame : public JSC::JSNonFinalObject {
{
}
};

// RAII: installs `context` as the active async context (the value every
// AsyncLocalStorage.getStore() reads) and restores the previous one on exit.
//
// Use this around an event dispatch that happens asynchronously (from an
// event-loop task) on behalf of a resource created earlier, passing the
// snapshot AsyncContextFrame::captureCurrentContext() took when the resource
// was created. For a single callback, prefer withAsyncContextIfNeeded + call.
//
// A no-op when `context` is empty or undefined, mirroring
// withAsyncContextIfNeeded's "no async context, no snapshot".
class AsyncContextFrameScope {
WTF_MAKE_NONCOPYABLE(AsyncContextFrameScope);

public:
AsyncContextFrameScope(JSC::JSGlobalObject*, JSC::JSValue context);
~AsyncContextFrameScope();

private:
JSC::JSGlobalObject* m_globalObject { nullptr };
JSC::JSValue m_previousContext;
};
5 changes: 5 additions & 0 deletions src/jsc/bindings/bindings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5620,6 +5620,11 @@ extern "C" WebCore::AbortSignalTimeout WebCore__AbortSignal__getTimeout(WebCore:
return abortSignal->getTimeout();
}

extern "C" void WebCore__AbortSignal__clearTimeoutAsyncContext(WebCore::AbortSignal* abortSignal)
{
abortSignal->clearTimeoutAsyncContext();
}

extern "C" WebCore::AbortSignal* WebCore__AbortSignal__ref(WebCore::AbortSignal* abortSignal)
{
abortSignal->ref();
Expand Down
20 changes: 20 additions & 0 deletions src/jsc/bindings/webcore/AbortSignal.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
#include "AbortSignal.h"

#include "AbortAlgorithm.h"
#include "AsyncContextFrame.h"
#include "DOMException.h"
// #include "DOMTimer.h"
#include "Event.h"
Expand Down Expand Up @@ -66,6 +67,11 @@ Ref<AbortSignal> AbortSignal::abort(JSDOMGlobalObject& globalObject, ScriptExecu
Ref<AbortSignal> AbortSignal::timeout(ScriptExecutionContext& context, uint64_t milliseconds)
{
auto signal = adoptRef(*new AbortSignal(&context));
// The abort fires from the timer heap, not from a JS caller, so snapshot
// the caller's async context now. Node does the equivalent through the
// setTimeout() that backs its AbortSignal.timeout().
if (auto* globalObject = context.jsGlobalObject())
AsyncContextFrame::captureCurrentContext(globalObject, signal->m_timeoutAsyncContext);
signal->m_timeout = AbortSignal__Timeout__create(bunVM(context.vm()), signal.ptr(), milliseconds);
ASSERT(signal->m_timeout);
signal->ref();
Expand Down Expand Up @@ -152,6 +158,14 @@ void AbortSignal::cancelTimer()
if (auto timeout = std::exchange(m_timeout, nullptr)) {
AbortSignal__Timeout__deinit(timeout);
}
clearTimeoutAsyncContext();
}

void AbortSignal::clearTimeoutAsyncContext()
{
// The timer can never fire past this point, so release the snapshot taken
// in timeout(); signalAbort() has already copied it into its restore scope.
m_timeoutAsyncContext.clear();
}

void AbortSignal::markAborted(JSC::JSValue reason)
Expand Down Expand Up @@ -217,6 +231,12 @@ void AbortSignal::signalAbort(JSC::JSValue reason)
// alive throughout.
bool hadTimeout = m_timeout != nullptr;

// Restore the async context captured by AbortSignal.timeout(): the timer
// fires from the event loop with no active AsyncLocalStorage context.
// Undefined (and so a no-op) for every other abort path.
auto* context = scriptExecutionContext();
AsyncContextFrameScope asyncContextScope(context ? context->jsGlobalObject() : nullptr, m_timeoutAsyncContext.get());

// 2. Set signal’s abort reason to reason if it is given; otherwise to a new "AbortError" DOMException.
markAborted(reason);

Expand Down
10 changes: 10 additions & 0 deletions src/jsc/bindings/webcore/AbortSignal.h
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
#include "JSValueInWrappedObject.h"
#include "JavaScriptCore/JSGlobalObject.h"
#include "ZigGlobalObject.h"
#include <JavaScriptCore/Strong.h>
#include "wtf/DebugHeap.h"
#include "wtf/FastMalloc.h"
#include <wtf/Function.h>
Expand Down Expand Up @@ -138,6 +139,11 @@ class AbortSignal final : public RefCounted<AbortSignal>, public EventTargetWith

AbortSignalTimeout getTimeout() const { return m_timeout; }

// Every path that retires the timeout (cancelTimer(), and the Rust timer
// teardown paths that unref the signal without reaching it) must call this
// so m_timeoutAsyncContext never outlives the timer as a GC root.
void clearTimeoutAsyncContext();

private:
enum class Aborted : bool {
No,
Expand Down Expand Up @@ -202,6 +208,10 @@ class AbortSignal final : public RefCounted<AbortSignal>, public EventTargetWith
AbortSignalSet m_sourceSignals;
AbortSignalSet m_dependentSignals;
JSValueInWrappedObject m_reason;
// AbortSignal.timeout() only: the async context active when timeout() was
// called, restored around the timer-driven abort and released by
// clearTimeoutAsyncContext(). See AsyncContextFrame::captureCurrentContext.
JSC::Strong<JSC::Unknown> m_timeoutAsyncContext;
Comment thread
robobun marked this conversation as resolved.
Resolved
CommonAbortReason m_commonReason { CommonAbortReason::None };
Vector<NativeCallbackTuple, 2> m_native_callbacks;
Vector<NativeCallbackTuple, 2>* m_nativeCallbacksBeingDispatched { nullptr };
Expand Down
10 changes: 10 additions & 0 deletions src/jsc/bindings/webcore/BroadcastChannel.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
#include "config.h"
#include "BroadcastChannel.h"

#include "AsyncContextFrame.h"
#include "BunBroadcastChannelRegistry.h"
#include "BunClientData.h"
#include "EventNames.h"
Expand All @@ -45,6 +46,10 @@ BroadcastChannel::BroadcastChannel(ScriptExecutionContext& context, const String
, m_contextId(context.identifier())
{
initializeWeakPtrFactory();
// dispatchMessage() runs from a posted task, not from a JS caller, so
// snapshot the creator's async context now (Node's AsyncWrap does the same).
if (auto* globalObject = context.jsGlobalObject())
AsyncContextFrame::captureCurrentContext(globalObject, m_creationAsyncContext);
BunBroadcastChannelRegistry::singleton().subscribe(m_name, m_contextId, *this);
jsRef(context.jsGlobalObject());
}
Expand Down Expand Up @@ -89,6 +94,9 @@ void BroadcastChannel::dispatchMessage(Ref<SerializedScriptValue>&& message)
RELEASE_ASSERT(vm.hasPendingTerminationException());
return;
}
// Listeners observe the async context that was active when this channel
// was created.
AsyncContextFrameScope asyncContextScope(globalObject, m_creationAsyncContext.getValue());
dispatchEvent(event.event);
}

Expand All @@ -97,6 +105,8 @@ void BroadcastChannel::close()
uint64_t prev = m_state.fetch_or(Closed, std::memory_order_acq_rel);
if (prev & Closed)
return;
// A closed channel can never dispatch again; release the creation snapshot.
m_creationAsyncContext.clear();
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
BunBroadcastChannelRegistry::singleton().unsubscribe(m_name, *this);
}

Expand Down
7 changes: 7 additions & 0 deletions src/jsc/bindings/webcore/BroadcastChannel.h
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
#include "ContextDestructionObserver.h"
#include "EventTarget.h"
#include "ExceptionOr.h"
#include "JSValueInWrappedObject.h"
#include "ScriptExecutionContext.h"
#include <wtf/Forward.h>
#include <wtf/ThreadSafeWeakPtr.h>
Expand Down Expand Up @@ -79,6 +80,8 @@ class BroadcastChannel final : public ThreadSafeRefCountedAndCanMakeThreadSafeWe
void jsRef(JSGlobalObject*);
void jsUnref(JSGlobalObject*);

const JSValueInWrappedObject& creationAsyncContext() const { return m_creationAsyncContext; }

private:
friend class BunBroadcastChannelRegistry;

Expand All @@ -102,6 +105,10 @@ class BroadcastChannel final : public ThreadSafeRefCountedAndCanMakeThreadSafeWe
const String m_name;
const ScriptExecutionContextIdentifier m_contextId;

// The async context active when the channel was created, restored around
// dispatchMessage(). Visited by JSBroadcastChannel::visitChildrenImpl.
JSValueInWrappedObject m_creationAsyncContext;

std::atomic<uint64_t> m_state { 0 };

bool m_hasRef { false };
Expand Down
14 changes: 14 additions & 0 deletions src/jsc/bindings/webcore/JSBroadcastChannel.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -421,6 +421,20 @@ JSC::GCClient::IsoSubspace* JSBroadcastChannel::subspaceForImpl(JSC::VM& vm)
[](auto& spaces, auto&& space) { spaces.m_subspaceForBroadcastChannel = std::forward<decltype(space)>(space); });
}

template<typename Visitor>
void JSBroadcastChannel::visitChildrenImpl(JSCell* cell, Visitor& visitor)
{
auto* thisObject = uncheckedDowncast<JSBroadcastChannel>(cell);
ASSERT_GC_OBJECT_INHERITS(thisObject, info());
Base::visitChildren(thisObject, visitor);
// Set once in the BroadcastChannel constructor (before this wrapper
// exists) and only ever cleared afterwards (on close()), so it can never
// acquire a new value post-marking: no output constraint is needed.
thisObject->wrapped().creationAsyncContext().visit(visitor);
}

DEFINE_VISIT_CHILDREN(JSBroadcastChannel);

void JSBroadcastChannel::analyzeHeap(JSCell* cell, HeapAnalyzer& analyzer)
{
auto* thisObject = uncheckedDowncast<JSBroadcastChannel>(cell);
Expand Down
1 change: 1 addition & 0 deletions src/jsc/bindings/webcore/JSBroadcastChannel.h
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ class JSBroadcastChannel : public JSEventTarget {
static BroadcastChannel* toWrapped(JSC::VM&, JSC::JSValue);

DECLARE_INFO;
DECLARE_VISIT_CHILDREN;

static JSC::Structure* createStructure(JSC::VM& vm, JSC::JSGlobalObject* globalObject, JSC::JSValue prototype)
{
Expand Down
6 changes: 6 additions & 0 deletions src/jsc/bindings/webcore/JSMessageChannelCustom.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,12 @@ void JSMessageChannel::visitAdditionalChildrenInGCThread(Visitor& visitor)
visitor.addOpaqueRoot(WTF::getPtr(wrapped().port2()));
// addWebCoreOpaqueRoot(visitor, wrapped().port1());
// addWebCoreOpaqueRoot(visitor, wrapped().port2());

// port1/port2 have no JSMessagePort wrapper until first read (the getters
// are lazy), so until then this is the only visitor that can keep the
// ports' captured async context alive.
wrapped().port1().creationAsyncContext().visit(visitor);
wrapped().port2().creationAsyncContext().visit(visitor);
}

DEFINE_VISIT_ADDITIONAL_CHILDREN_IN_GC_THREAD(JSMessageChannel);
Expand Down
1 change: 1 addition & 0 deletions src/jsc/bindings/webcore/JSMessagePortCustom.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ using namespace JSC;
template<typename Visitor>
void JSMessagePort::visitAdditionalChildrenInGCThread(Visitor& visitor)
{
wrapped().creationAsyncContext().visit(visitor);
// If we have a locally entangled port, we can directly mark it as reachable. Ports that are remotely entangled are marked in-use by markActiveObjectsForContext().
if (auto* port = wrapped().locallyEntangledPort()) {
visitor.addOpaqueRoot(port);
Expand Down
14 changes: 14 additions & 0 deletions src/jsc/bindings/webcore/JSWorker.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -944,6 +944,20 @@ JSC::GCClient::IsoSubspace* JSWorker::subspaceForImpl(JSC::VM& vm)
[](auto& spaces, auto&& space) { spaces.m_subspaceForWorker = std::forward<decltype(space)>(space); });
}

template<typename Visitor>
void JSWorker::visitChildrenImpl(JSCell* cell, Visitor& visitor)
{
auto* thisObject = uncheckedDowncast<JSWorker>(cell);
ASSERT_GC_OBJECT_INHERITS(thisObject, info());
Base::visitChildren(thisObject, visitor);
// Set once in the Worker constructor (before this wrapper exists) and
// only ever cleared afterwards (when the worker reaches Closed), so it
// can never acquire a new value post-marking: no output constraint needed.
thisObject->wrapped().creationAsyncContext().visit(visitor);
}

DEFINE_VISIT_CHILDREN(JSWorker);

void JSWorker::analyzeHeap(JSCell* cell, HeapAnalyzer& analyzer)
{
auto* thisObject = uncheckedDowncast<JSWorker>(cell);
Expand Down
1 change: 1 addition & 0 deletions src/jsc/bindings/webcore/JSWorker.h
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ class JSWorker : public JSEventTarget {
static Worker* toWrapped(JSC::VM&, JSC::JSValue);

DECLARE_INFO;
DECLARE_VISIT_CHILDREN;

static JSC::Structure* createStructure(JSC::VM& vm, JSC::JSGlobalObject* globalObject, JSC::JSValue prototype)
{
Expand Down
Loading
Loading