Skip to content

[pull] main from oven-sh:main - #33

Merged
pull[bot] merged 3 commits into
coleleavitt:mainfrom
oven-sh:main
Aug 15, 2026
Merged

pull[bot] merged 3 commits into
coleleavitt:mainfrom
oven-sh:main

Conversation

@pull

@pull pull Bot commented Aug 15, 2026 •

Copy link
Copy Markdown

See Commits and Changes for more details.


Created by pull[bot] (v2.0.0-alpha.4)

Can you help keep this open source service alive? 💖 Please sponsor : )


Summary by cubic

Makes threadsafe FFI callbacks safe after VM teardown and adds VM-scoped wall-clock termination deadlines. Also standardizes i64/u64 Number conversions to be architecture-independent.

  • Threadsafe JSFFICallbacks: the entry thunk now targets a persistent FFI::ThreadsafeCallbackHandle instead of the GC cell. Late calls (after close() or VM/global destruction) are dropped and return 0; runThreadsafeInvocation exits early if the cell is gone. Threadsafe callbacks are rooted VM‑wide until closed and drained, and the handle (with thunk) is kept alive once an entrypoint was handed out to avoid UAF.
  • i64/u64 Number conversion: writeInt64Slot uses modular conversion via JSC::toInt64 and stores the low 64 bits, making behavior identical on x86‑64 and arm64; NaN/±∞ convert to 0. Pointer types keep using the CPU truncation (doubleToInt64). Tests and fuzzers were updated to cover the new edges.
  • Termination deadlines: new VM::addTerminationDeadline, VM::cancelTermination, and VM::hasPendingTermination, plus $vm.callWithTimeLimit(fn, ms) that withdraws its own termination and throws RangeError "timed out" on expiry. Nested limits re‑request termination for enclosing scopes. A new stress test validates semantics.

Migration

  • If an embedder accepts a threadsafe invocation but chooses not to run it, call FFI::retireThreadsafeInvocation (exported in BunFFI.h) to withdraw the pending count and unroot if needed.

Written for commit 8a31c0d. Summary will update on new commits.

Review in cubic

dylan-conway and others added 3 commits August 14, 2026 14:43
…e after its cell and VM are gone (#437)

* [JSC] bun:ffi: a threadsafe JSFFICallback's entry thunk stays callable after its cell and VM are gone

Native code may call a `threadsafe` callback's entrypoint from any thread
at any time -- including after the global object that created it has been
destroyed (a terminated worker), which the embedder cannot always order
against close(). Everything that entrypoint touched lived in the GC cell:
the JIT'd thunk (freed by ~JSFFICallback), the signature, the
closed/pending word. A call arriving after the worker's VM teardown (or
after GC of a closed callback) executed freed thunk memory or read a dead
cell; in Bun that is a null Ref<Signature> assert on debug and a segfault
on release.

The threadsafe thunk now targets a ThreadSafeRefCounted
FFI::ThreadsafeCallbackHandle instead of the cell. The handle owns the
thunk code, a ref to the signature, the closed-bit/pending-count word and
the embedder's routing token; the cell and each ThreadsafeInvocation hold
refs to it, and only the owning thread reads handle->callback(). When a
threadsafe callback's cell is destroyed it clears that pointer and sets the
closed bit; if the callback was never close()d -- native code was never
told to stop calling -- the handle is additionally kept alive for the rest
of the process, so late calls count themselves out and return instead of
jumping into freed code. close()d callbacks are released as before.
runThreadsafeInvocation() returns early for a handle whose cell is gone,
and retireThreadsafeInvocation() is exported for invocations an embedder
accepted but will not run ($vm's drain uses it).

Non-threadsafe callbacks are unchanged: they may only be called on the
owning thread while it is inside the FFI call that handed them out.

* Review: only keep the handle alive if an entrypoint was handed out; forward-declare ThreadsafeCallbackHandle in FFICallbackThunk.h

* Review: handles are immortal once an entrypoint exists (close()d or not); root threadsafe callbacks VM-wide; retire under the API lock; testFFI second-VM regression test

- ~JSFFICallback keeps the handle (and thunk) alive whenever an entrypoint
  was handed out, closed or not: there is no happens-before between a
  foreign thread leaving the thunk and this thread freeing it, and a
  close()-then-worker-exit-then-late-call reproduced the original crash.
  ~200-250 bytes per threadsafe callback ever created.
- Threadsafe callbacks are Heap::protect()ed until closed and drained, so
  the cell cannot die (and sit unswept, still reachable through
  handle->callback() from a delivered invocation) while its VM lives on,
  as it could when rooted only through a collectable global object.
- runThreadsafeInvocation retires (and possibly unroots) under the API
  lock; a call into a closed/dead handle is logged under verboseFFI.
- testFFI: testThreadsafeCallbackOutlivesVM creates a threadsafe callback
  in a VM of its own, destroys that VM (unclosed / closed / with an
  invocation pending) and checks the entrypoint still drops calls and
  returns zero, and that the pending invocation retires harmlessly.
  Heap-use-after-free under ASAN with the previous close() policy.

* Review: retireThreadsafeInvocation takes the API lock; testFFI destroys the VM on the defensive path too

* FFIContext.h: include <atomic>
writeInt64Slot converted a double-encoded Number with the CPU's truncating
double -> int64 instruction (FFI::doubleToInt64). For u64 / u64_fast that
has no representation for values in [2^63, 2^64): every such Number arrived
in the callee as 9223372036854775808 on x86-64 (cvttsd2si's indefinite
value) or 9223372036854775807 on arm64 (fcvtzs saturates). NaN and values
outside the int64 range likewise got a different answer on each CPU.

Use JSC::toInt64 instead: truncate toward zero and keep the low 64 bits of
the two's complement result, with NaN and the infinities becoming 0. That is
the ToInt32 conversion writeIntegerSlot already applies to the narrower
integer types, widened to 64 bits, and it is what the int32 encoding and the
BigInt branch of the same function already produce, so a Number now reaches
an i64 / u64 parameter (or leaves an i64 / u64 callback) with the same bits
however the engine happened to box it and as the BigInt of the same value.
The signed and unsigned types share that bit pattern, so the isUnsigned
split goes away, and doubleToUInt64 has no remaining user. doubleToInt64
itself stays the pointer conversion, where the IC stub and DFG inline the
same instruction.

testFFI pins the slot bits for the new cases; the JSTests batteries gain
the Numbers that used to be CPU-specific, and the fuzzer's reference model
now covers every double edge instead of excluding |d| >= 2^63.
…dingTermination() for embedder-scoped wall-clock time limits (#440)

* [JSC] Add VM::requestTerminationAt() and VM::cancelTerminationRequest() for embedder-scoped wall-clock time limits

An embedder that gives one bounded call a time limit (node:vm's `timeout`
in Bun) has two needs JSC does not serve directly today: request
termination at a wall-clock deadline, and — once that call is over —
take the request back so that nothing of it reaches whatever the same VM
entry runs next. The per-VM Watchdog is a CPU-time budget for the whole
entry: armed mid-entry, its timer, deadline and CPU deadline outlive the
call that armed it and there is no way to retire them, so a late fire
either terminates unrelated code or re-arms under a cleared limit
(asserting hasTimeLimit()). And "taking a termination back" means
clearing three pieces of state (the NeedTermination trap, the request
flag, a pending TerminationException) that only VM/VMTraps should be
touching in concert.

* VM::requestTerminationAt(MonotonicTime) -> Ref<VM::TerminationDeadline>:
  the deadline is served by one WorkQueue timer per VM for the earliest
  pending deadline (the Watchdog's shape, so cancelled deadlines do not
  linger as timers); when it passes, notifyNeedTermination() is called
  from the timer thread. TerminationDeadline::didFire() says whether that
  happened, cancel() withdraws it, and VM destruction detaches whatever is
  still pending, so a late timer never touches a dead VM.
* VM::cancelTerminationRequest(): withdraws a requested termination in
  whichever form it has reached — unhandled trap, request flag, pending
  TerminationException — for use by the scope that requested it once that
  scope has ended. Asserts the API lock and no DeferTermination in
  progress.
* $vm.requestTerminationAfter / terminationDeadlineDidFire /
  cancelTerminationDeadline / cancelTerminationRequest, and
  $vm.callWithTimeLimit(fn, ms) showing the intended embedder pattern
  (including re-requesting for an enclosing limited call whose own limit
  passed meanwhile).
* JSTests/stress/vm-termination-deadline.js: a passed limit cuts its call
  short and leaves nothing behind; a met limit's late expiry terminates
  nothing; ordinary throws pass through; nested limits (inner fires /
  outer fires / both fire) each behave.

* Review: TerminationDeadline in its own files; addTerminationDeadline / cancelTermination / hasPendingTermination; smaller $vm surface; sharper test

* Move the deadline classes out of VM.h into runtime/TerminationDeadline.{h,cpp}
  (TZone-allocated; VM.h keeps forward declarations, a RefPtr and three
  short methods). TerminationDeadline is now just {deadline, fired}: no
  back-pointer to its set — cancel() takes the VM, which the contract
  already requires to be alive — and cancel() is void, didFire() being
  final once it returns. The set tracks its armed timer with a
  MonotonicTime (infinity = none) and never arms for infinity;
  willDestroyVM() naming as for Watchdog/VMTraps.
* VM::requestTerminationAt -> addTerminationDeadline ([[nodiscard]]:
  dropping the Ref does not cancel), VM::cancelTerminationRequest ->
  cancelTermination, so the two no longer read as a pair (one adds a
  timer, the other withdraws termination state), and add
  VM::hasPendingTermination() covering all three forms a request can be
  in. Document that cancelTermination() withdraws whatever is pending —
  an embedder whose VM may also be stopped from outside checks that
  first — and does not undo executionForbidden(); assert against NaN
  deadlines and against VMs that forbidExecutionOnTermination().
* $vm: keep callWithTimeLimit (per-VM stack of active limits as VM side
  data rather than a thread_local; validates ms; "cut short" judged by
  hasTerminationRequest() so a termination swallowed in C++ still
  counts), cancelTermination and hasPendingTermination; drop the unused
  index-table hooks; register them allowIfNotFuzz.
* Test: the blocked case really blocks (sleepSeconds is a shell global)
  and no longer depends on trap-delivery latency; the "both limits
  passed" case now reaches the enclosing re-request path; a
  deterministic "limit passes with the request never acted on" case; and
  hasPendingTermination() must be false after every case.
@pull pull Bot locked and limited conversation to collaborators Aug 15, 2026
@pull pull Bot added the ⤵️ pull label Aug 15, 2026
@pull
pull Bot merged commit 8a31c0d into coleleavitt:main Aug 15, 2026
1 check failed
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants