Skip to content

Commit f0f60fd

Browse files
authored
[JSC] Atomics.wait / memory.atomic.wait: wake up for a termination requested from another thread (#432)
* [JSC] DeferTermination: preserve a TerminationException that is pending outside any VMEntryScope VMTraps::deferTerminationSlow() suspends a pending TerminationException and relies on VM::hasTerminationRequest() staying set so that undoDeferTermination() re-throws it. That holds while a VMEntryScope is on the stack, but the outermost VMEntryScope's exit resets the request. A client that deliberately leaves the TerminationException pending past that exit — so that nothing re-enters the VM until it tears it down — can still reach a DeferTermination scope from host code (a LazyProperty / LazyClassStructure initializer, JSObject::putDirect...) before then. In debug that failed ASSERT(vm.hasTerminationRequest()); in release the exception was cleared, undoDeferTermination() saw no request and never re-threw it, so the pending termination was silently dropped (and m_suspendedTerminationException left stale). When the request has already been reset, re-establish it for the duration of the deferral and reset it again once the exception has been re-thrown, so the scope is transparent in that state. Behaviour with a VMEntryScope on the stack, or without a pending TerminationException, is unchanged. * [JSC] Atomics.wait / memory.atomic.wait: wake up for a termination requested from another thread WaiterListManager::waitSyncImpl() parks the thread until it is dequeued by a notify, times out, or `vm.hasTerminationRequest()`. Since 305643@main ("Fix a race condition with the setting of VM::m_hasTerminationRequest") that request is only established by the mutator thread itself when it handles the NeedTermination trap — which it cannot do while parked — and VM::notifyNeedTermination() from another thread merely fires the trap. So a worker blocked in Atomics.wait() with no timeout could no longer be stopped: VMTraps woke its condition, the predicate was still false, and it went back to sleep for good (worker.terminate() never completing; the sync-over-async worker pools that park in Atomics.wait leak their thread). - The wait predicate also honours a pending NeedTermination trap, and on that exit waitSyncImpl() handles the trap itself (establishing the request and throwing the TerminationException) before returning Terminated, so both callers just propagate. - The wake-up moves from requestThreadStopIfNeeded() — which only runs when no other async event already has a stop requested — to fireTrap() for NeedTermination, and is delivered by Waiter::notifyOfTerminationRequest() under the lock of the list the waiter is parked on, so it cannot fall between the waiter's predicate check and its park. That matters where traps are polled rather than signalled (no SignalSender re-notifying every millisecond), e.g. on Windows. * Review follow-ups: drop the entryScope assertion; establish the termination in waitSyncImpl without handleTraps() - deferTerminationSlow(): re-establishing the request does not depend on being outside a VMEntryScope, so don't assert it. - waitSyncImpl(): consume the NeedTermination trap and establish/throw the termination directly instead of calling VMTraps::handleTraps(), whose trap check also walks vm.topCallFrame to jettison optimized code — not needed to throw here, and best avoided from wasm's memory.atomic.wait operation. * Address review: survive a VM entry inside the deferral; don't interrupt a wait while termination is deferred DeferTermination (commit 1): - undoDeferTermination() takes its slow path when a TerminationException was suspended even if the request has meanwhile been reset - which happens when the deferred code itself enters the VM (a LazyProperty initializer may) and that outermost VMEntryScope exits. The slow path re-establishes the request for the re-throw if needed and then leaves it as it was before the deferral, so neither the exception nor the flags go stale in that case. Atomics.wait (commit 2): - While termination is being deferred, a termination request does not cut the wait short (it takes effect when the deferral ends); previously that corner returned Terminated without an exception thrown, handing Atomics.wait an empty value / wasm a bogus trap. The tail now always throws and both callers assert a pending exception. - Waiter::setParkedList() accessor instead of befriending WaiterListManager; CONCURRENT_SAFE on the notifySyncWaiterOfTermination definition; comment fixes (handleTraps() jettisons trap-breakpointed code blocks rather than walking the stack; ASCII). * Drop the DeferTermination change; keep only the Atomics.wait termination wake-up The state the DeferTermination change handled (TerminationException left pending outside any VMEntryScope while host code keeps initialising lazy structures) is one WebKit's own clients never produce: WebCore either clears the exception at the JS entry (NakedPtr<Exception> calls) or, in WorkerDedicatedRunLoop::Task::performTask, leaves it pending but then runs no further non-cleanup task. It is the embedder's job to keep "TerminationException pending => hasTerminationRequest()" true if it keeps the exception; Bun will do that on its side. Restores deferTerminationSlow(), undoDeferTerminationSlow(), undoDeferTermination() and VMTraps' members to origin/main.
1 parent e2f13c6 commit f0f60fd

6 files changed

Lines changed: 81 additions & 10 deletions

File tree

‎Source/JavaScriptCore/runtime/AtomicsObject.cpp‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -470,7 +470,7 @@ JSValue atomicsWaitImpl(JSGlobalObject* globalObject, JSArrayType* typedArray, u
470470
case WaiterListManager::WaitSyncResult::TimedOut:
471471
return vm.smallStrings.timedOutString();
472472
case WaiterListManager::WaitSyncResult::Terminated:
473-
vm.throwTerminationException();
473+
ASSERT(vm.hasPendingTerminationException());
474474
return { };
475475
}
476476
RELEASE_ASSERT_NOT_REACHED();

‎Source/JavaScriptCore/runtime/VMTraps.cpp‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -327,7 +327,7 @@ class VMTraps::SignalSender final : public ThreadSafeRefCounted<VMTraps::SignalS
327327
}
328328

329329
if (vm.traps().hasTrapBit(NeedTermination))
330-
vm.syncWaiter()->condition().notifyOne();
330+
vm.syncWaiter()->notifyOfTerminationRequest();
331331

332332
{
333333
Locker locker { *m_lock };
@@ -398,7 +398,6 @@ CONCURRENT_SAFE void VMTraps::requestThreadStopIfNeeded(Locker<Lock>& locker)
398398
ASSERT(!m_threadStopRequested);
399399
ASSERT(!m_isShuttingDown);
400400

401-
VM& vm = this->vm();
402401
m_stack.requestStop();
403402

404403
m_needToInvalidateCodeBlocks = true;
@@ -409,19 +408,21 @@ CONCURRENT_SAFE void VMTraps::requestThreadStopIfNeeded(Locker<Lock>& locker)
409408
// has received the trap request. We'll call it from another thread so that
410409
// requestThreadStopIfNeeded() does not block.
411410
if (!m_signalSender)
412-
m_signalSender = adoptRef(new SignalSender(locker, vm));
411+
m_signalSender = adoptRef(new SignalSender(locker, vm()));
413412
m_signalSender->notify(locker);
414413
}
415414
#else
416415
UNUSED_PARAM(locker);
417416
#endif
418417

419-
if (hasTrapBit(NeedTermination))
420-
vm.syncWaiter()->condition().notifyOne();
421-
422418
m_threadStopRequested = true;
423419
}
424420

421+
CONCURRENT_SAFE void VMTraps::notifySyncWaiterOfTermination()
422+
{
423+
vm().syncWaiter()->notifyOfTerminationRequest();
424+
}
425+
425426
CONCURRENT_SAFE void VMTraps::updateThreadStopRequestIfNeeded()
426427
{
427428
Locker locker { *m_trapSignalingLock };

‎Source/JavaScriptCore/runtime/VMTraps.h‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -249,8 +249,13 @@ class VMTraps {
249249
// Trap bit must be set before we update the thread stop request.
250250
if (isAsyncEvent(event))
251251
updateThreadStopRequestIfNeeded();
252+
// A thread parked in Atomics.wait / memory.atomic.wait handles no traps; wake it so it sees this one.
253+
if (event == NeedTermination)
254+
notifySyncWaiterOfTermination();
252255
}
253256

257+
JS_EXPORT_PRIVATE CONCURRENT_SAFE void notifySyncWaiterOfTermination();
258+
254259
// The following returns true if a trap was handled.
255260
bool handleTraps(BitField mask = AsyncEvents);
256261
bool handleTrapsIfNeeded(BitField mask = AsyncEvents);

‎Source/JavaScriptCore/runtime/WaiterListManager.cpp‎

Lines changed: 55 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,44 @@ Waiter::Waiter(JSPromise* promise)
6262
{
6363
}
6464

65+
Waiter::~Waiter() = default;
66+
67+
void Waiter::setParkedList(RefPtr<WaiterList>&& list)
68+
{
69+
ASSERT(!m_isAsync);
70+
Locker locker { m_parkedListLock };
71+
m_parkedList = WTF::move(list);
72+
}
73+
74+
void Waiter::notifyOfTerminationRequest()
75+
{
76+
ASSERT(!m_isAsync);
77+
RefPtr<WaiterList> parkedList;
78+
{
79+
Locker locker { m_parkedListLock };
80+
parkedList = m_parkedList;
81+
}
82+
// Not parked (yet): waitSyncImpl publishes the list before it tests for the request, so a wait
83+
// that starts after this sees the NeedTermination trap our caller has already fired.
84+
if (!parkedList)
85+
return;
86+
// Notify under the list's lock, which the waiter holds from testing for the request until it is
87+
// parked, so that the notification cannot fall in between.
88+
Locker listLocker { parkedList->lock };
89+
m_condition.notifyOne();
90+
}
91+
92+
// A termination is only ever established (VM::hasTerminationRequest) by the mutator thread itself,
93+
// which cannot do that while it is parked in a wait. Another thread asking this VM to terminate
94+
// (VM::notifyNeedTermination) is visible as the pending NeedTermination trap. Neither interrupts the
95+
// wait while termination is being deferred (DeferTermination); it takes effect when the deferral ends.
96+
static ALWAYS_INLINE bool shouldStopWaitingForTermination(VM& vm)
97+
{
98+
if (vm.traps().isDeferringTermination()) [[unlikely]]
99+
return false;
100+
return vm.hasTerminationRequest() || vm.traps().needHandling(VMTraps::NeedTermination);
101+
}
102+
65103

66104
WaiterListManager& WaiterListManager::singleton()
67105
{
@@ -91,19 +129,34 @@ WaiterListManager::WaitSyncResult WaiterListManager::waitSyncImpl(VM& vm, ValueT
91129

92130
list->addLast(listLocker, syncWaiter);
93131
dataLogLnIf(WaiterListsManagerInternal::verbose, "<WaiterListManager> <Thread:", Thread::currentSingleton(), "> added a new SyncWaiter=", syncWaiter.get(), " to a waiterList for ptr ", RawPointer(ptr));
132+
syncWaiter->setParkedList(list.copyRef());
94133

95-
while (syncWaiter->isOnList() && time.now() < time && !vm.hasTerminationRequest())
134+
while (syncWaiter->isOnList() && time.now() < time && !shouldStopWaitingForTermination(vm))
96135
syncWaiter->condition().waitUntil(list->lock, time.approximate<WallTime>());
97136

137+
syncWaiter->setParkedList(nullptr);
138+
98139
// At this point, syncWaiter should be either notified (dequeued) or timeout (not dequeued).
99140
bool didGetDequeued = !syncWaiter->isOnList();
100141
if (didGetDequeued)
101142
return WaitSyncResult::OK;
102143

103144
didGetDequeued = list->findAndRemove(listLocker, syncWaiter);
104145
ASSERT(didGetDequeued);
105-
return vm.hasTerminationRequest() ? WaitSyncResult::Terminated : WaitSyncResult::TimedOut;
146+
if (!shouldStopWaitingForTermination(vm))
147+
return WaitSyncResult::TimedOut;
106148
}
149+
150+
// The wait was cut short by a termination request: leave with it established and the
151+
// TerminationException thrown, consuming the trap if another thread's request is what woke us
152+
// (as VMTraps::handleTraps() would, minus jettisoning the code blocks that have trap breakpoints
153+
// installed, which throwing from here does not need).
154+
ASSERT(!vm.traps().isDeferringTermination());
155+
if (vm.traps().clearTrap(VMTraps::NeedTermination))
156+
vm.setHasTerminationRequest();
157+
if (!vm.hasPendingTerminationException())
158+
vm.throwTerminationException();
159+
return WaitSyncResult::Terminated;
107160
}
108161

109162
template <typename ValueType>

‎Source/JavaScriptCore/runtime/WaiterListManager.h‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,12 +37,21 @@ namespace JSC {
3737
enum class AtomicsWaitType : uint8_t { Sync, Async };
3838
enum class AtomicsWaitValidation : uint8_t { Pass, Fail };
3939

40+
class WaiterList;
41+
4042
class Waiter final : public WTF::BasicRawSentinelNode<Waiter>, public ThreadSafeRefCounted<Waiter> {
4143
WTF_MAKE_TZONE_ALLOCATED(Waiter);
4244

4345
public:
4446
Waiter(VM*);
4547
Waiter(JSPromise*);
48+
~Waiter();
49+
50+
// Sync waiter only; any thread. Wake the VM's thread if it is parked in Atomics.wait /
51+
// memory.atomic.wait so that it sees the termination request that was just fired.
52+
void notifyOfTerminationRequest();
53+
// Sync waiter only; its own thread, holding the lock of the list it is (un)parking on.
54+
void setParkedList(RefPtr<WaiterList>&&);
4655

4756
bool isAsync() const
4857
{
@@ -117,6 +126,9 @@ class Waiter final : public WTF::BasicRawSentinelNode<Waiter>, public ThreadSafe
117126
ThreadSafeWeakPtr<DeferredWorkTimer::Ticket> m_ticket { nullptr };
118127
RefPtr<RunLoop::DispatchTimer> m_timer { nullptr };
119128
Condition m_condition;
129+
// Sync waiter only: the list it is parked on, for notifyOfTerminationRequest() to lock.
130+
Lock m_parkedListLock;
131+
RefPtr<WaiterList> m_parkedList WTF_GUARDED_BY_LOCK(m_parkedListLock);
120132
bool m_isAsync { false };
121133
};
122134

‎Source/JavaScriptCore/wasm/WasmOperationsInlines.h‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -747,7 +747,7 @@ static inline int32_t waitImpl(VM& vm, ValueType* pointer, ValueType expectedVal
747747
case WaiterListManager::WaitSyncResult::TimedOut:
748748
return static_cast<int32_t>(result);
749749
case WaiterListManager::WaitSyncResult::Terminated:
750-
vm.throwTerminationException();
750+
ASSERT(vm.hasPendingTerminationException());
751751
return -1;
752752
}
753753
RELEASE_ASSERT_NOT_REACHED();

0 commit comments

Comments
 (0)