Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
8 changes: 1 addition & 7 deletions src/event_loop/AnyEventLoop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -313,13 +313,7 @@ impl EventLoopHandle {
#[inline]
pub fn as_event_loop_ctx(self) -> bun_io::EventLoopCtx {
match self {
// SAFETY: `owner.bun_vm()` returns the owning `*mut VirtualMachine`,
// which is what the `EventLoopCtxKind::Js` `link_impl_EventLoopCtx!`
// (in `bun_jsc`) is written for. Both are per-thread singletons
// that outlive the ctx.
EventLoopHandle::Js { owner } => unsafe {
bun_io::EventLoopCtx::new(bun_io::EventLoopCtxKind::Js, owner.bun_vm())
},
EventLoopHandle::Js { owner } => owner.event_loop_ctx(),
// `mini` is a `BackRef` to the live per-thread singleton (see
// `mini_mut` doc) — valid for the ctx's lifetime.
EventLoopHandle::Mini(mut mini) => {
Expand Down
44 changes: 26 additions & 18 deletions src/event_loop/SpawnSyncEventLoop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@
//! Implementation approach:
//! - Creates a separate uws.Loop instance with its own kqueue/epoll fd (POSIX) or libuv loop (Windows)
//! - Wraps it in a full jsc.EventLoop instance whose `uws_loop` is the isolated loop
//! - Temporarily overrides vm.event_loop_handle to point to the isolated loop
//! - What the call makes for its child is handed that EventLoop, and so counts on the isolated loop
//! - Nothing else can reach it: a finalizer that runs during the wait finds the thread's own loop
//! (Windows still overrides vm.event_loop_handle, where a libuv handle keeps the loop it was made on)
//! - Minimal handler callbacks (wakeup/pre/post are no-ops)
//!
//! Similar to Node.js's approach in vendor/node/src/spawn_sync.cc but adapted for Bun's architecture.
Expand All @@ -29,9 +31,6 @@ use bun_uws as uws;
// MOVE-IN: EventLoopHandle relocated from bun_jsc — see AnyEventLoop.rs.
use crate::EventLoopHandle;

// On POSIX this is `?*uws.Loop`, on Windows `?*libuv.Loop`.
#[cfg(unix)]
pub type VmEventLoopHandle = Option<NonNull<uws::Loop>>;
#[cfg(windows)]
pub type VmEventLoopHandle = Option<NonNull<libuv::Loop>>;

Expand All @@ -51,7 +50,9 @@ unsafe extern "Rust" {
/// Re-bind `event_loop.{global, virtual_machine}` to `vm` (prepare path).
safe fn __bun_spawn_sync_event_loop_set_vm(el: *mut (), vm: *mut ());
safe fn __bun_spawn_sync_event_loop_tick_tasks_only(el: *mut ());
#[cfg(windows)]
safe fn __bun_spawn_sync_vm_get_event_loop_handle(vm: *mut ()) -> VmEventLoopHandle;
#[cfg(windows)]
safe fn __bun_spawn_sync_vm_set_event_loop_handle(vm: *mut (), h: VmEventLoopHandle);
/// Swap `vm.suppress_microtask_drain`, return previous.
safe fn __bun_spawn_sync_vm_swap_suppress_microtask_drain(vm: *mut (), v: bool) -> bool;
Expand Down Expand Up @@ -99,6 +100,7 @@ pub struct SpawnSyncEventLoop {

/// `prepare` overrides the VM's event_loop_handle; the original, restored
/// by `cleanup`.
#[cfg(windows)]
original_event_loop_handle: VmEventLoopHandle,

#[cfg(windows)]
Expand Down Expand Up @@ -157,6 +159,7 @@ impl SpawnSyncEventLoop {

this.write(Self {
uws_loop: loop_,
#[cfg(windows)]
original_event_loop_handle: None, // overwritten in `prepare`
#[cfg(windows)]
uv_timer: None,
Expand Down Expand Up @@ -283,31 +286,36 @@ impl Drop for SpawnSyncEventLoop {
impl SpawnSyncEventLoop {
/// Configure the event loop for a specific VM context
pub fn prepare(&mut self, vm: *mut () /* SAFETY: erased *mut VirtualMachine */) {
#[cfg(unix)]
debug_assert!(
self.uws_loop().num_polls == 0 && self.uws_loop().active == 0,
"the last spawnSync left num_polls={} active={} on its loop",
self.uws_loop().num_polls,
self.uws_loop().active,
);
__bun_spawn_sync_event_loop_set_vm(self.event_loop, vm);
self.did_timeout.set(false);
self.vm = vm;

self.original_event_loop_handle = __bun_spawn_sync_vm_get_event_loop_handle(vm);
#[cfg(unix)]
let new_handle: VmEventLoopHandle = Some(self.uws_loop);
#[cfg(windows)]
let new_handle: VmEventLoopHandle = Some(
NonNull::new(self.uws_loop().uv_loop)
.expect("uv_loop is set by us_create_loop for the loop's lifetime"),
);
__bun_spawn_sync_vm_set_event_loop_handle(vm, new_handle);
{
self.original_event_loop_handle = __bun_spawn_sync_vm_get_event_loop_handle(vm);
let new_handle: VmEventLoopHandle = Some(
NonNull::new(self.uws_loop().uv_loop)
.expect("uv_loop is set by us_create_loop for the loop's lifetime"),
);
__bun_spawn_sync_vm_set_event_loop_handle(vm, new_handle);
}
}

/// Restore the original event loop handle after spawnSync completes
#[cfg(windows)]
pub fn cleanup(&mut self, vm: *mut () /* SAFETY: erased *mut VirtualMachine */) {
__bun_spawn_sync_vm_set_event_loop_handle(vm, self.original_event_loop_handle);

#[cfg(windows)]
{
if let Some(timer) = self.uv_timer_mut() {
timer.stop();
timer.unref();
}
if let Some(timer) = self.uv_timer_mut() {
timer.stop();
timer.unref();
}
}
}
Expand Down
1 change: 1 addition & 0 deletions src/event_loop/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ bun_dispatch::link_interface! {
fn file_polls() -> *mut bun_io::file_poll::Store;
fn put_file_poll(poll: *mut bun_io::FilePoll, was_ever_registered: bool);
fn uws_loop() -> *mut bun_uws::Loop;
fn event_loop_ctx() -> bun_io::EventLoopCtx;
fn tick();
fn auto_tick();
fn auto_tick_active();
Expand Down
11 changes: 8 additions & 3 deletions src/io/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -312,7 +312,7 @@ pub type OpaqueCallback = unsafe extern "C" fn(*mut core::ffi::c_void);
// `uv_loop_t` whereas the impl bodies
// (`VirtualMachine::uws_loop` / `MiniEventLoop::loop_ptr`) hand back the wrapper.
bun_dispatch::link_interface! {
pub EventLoopCtx[Js, Mini] {
pub EventLoopCtx[Js, Mini, SpawnSync] {
fn platform_event_loop_ptr() -> *mut bun_uws_sys::Loop;
fn file_polls_ptr() -> *mut Store;
// `alloc_file_poll() -> *mut FilePoll` was removed — it
Expand Down Expand Up @@ -415,10 +415,15 @@ impl EventLoopCtx {
self.file_polls_mut().get_init(value)
}

/// What a `FilePoll` keeps of the ctx it was made with; [`get_vm_ctx`] gives that ctx back.
#[inline]
#[cfg(not(windows))]
pub(crate) fn is_js(&self) -> bool {
self.is(EventLoopCtxKind::Js)
pub(crate) fn allocator_type(&self) -> AllocatorType {
match self.kind {
EventLoopCtxKind::Js => AllocatorType::Js,
EventLoopCtxKind::Mini => AllocatorType::Mini,
EventLoopCtxKind::SpawnSync => AllocatorType::SpawnSync,
}
}
#[inline]
pub fn loop_(&self) -> *mut bun_uws_sys::Loop {
Expand Down
4 changes: 3 additions & 1 deletion src/io/posix_event_loop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,8 @@ pub enum AllocatorType {
#[default]
Js,
Mini,
/// The loop `Bun.spawnSync` waits on. Only what that call makes for its own child lives there.
SpawnSync,
}

// `FilePoll`/`Store` here are POSIX-specific (kqueue/epoll registration,
Expand Down Expand Up @@ -520,7 +522,7 @@ impl FilePoll {
flags,
owner,
next_to_free: ptr::null_mut(),
allocator_type: if vm.is_js() { AllocatorType::Js } else { AllocatorType::Mini },
allocator_type: vm.allocator_type(),
#[cfg(all(target_os = "macos", debug_assertions))]
// Single-threaded event loop so `Relaxed` ordering is sufficient.
generation_number: MAX_GENERATION_NUMBER
Expand Down
41 changes: 38 additions & 3 deletions src/jsc/event_loop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -694,9 +694,9 @@ impl EventLoop {
/// ports/channels/sockets on a loop that no longer ticks) so the loop is not
/// torn down still believing something keeps it alive.
///
/// Targets `self.native_loop()`, never `vm.event_loop_handle`: `Bun.spawnSync`
/// points the latter at its private loop, and a GC inside it still refs
/// this loop (FinalizationRegistry, MessagePort).
/// Targets `self.native_loop()`, never `vm.event_loop_handle`: on Windows
/// `Bun.spawnSync` points the latter at its private loop, and a GC inside it
/// still refs this loop (FinalizationRegistry, MessagePort).
pub(crate) fn apply_concurrent_ref_delta(&self) {
let delta = self.concurrent_ref.swap(0, Ordering::SeqCst);
// SAFETY: `native_loop()` is live for this loop's lifetime; JS thread only.
Expand Down Expand Up @@ -1153,6 +1153,23 @@ impl EventLoop {
}
}

/// The ctx whose loop is the one this `EventLoop` runs on. Windows has none for a spawnSync loop:
/// a libuv handle knows its loop, and the counters stay on the thread's.
pub fn event_loop_ctx(&self) -> Async::EventLoopCtx {
#[cfg(unix)]
if self.isolated_poster.is_some() {
// SAFETY: the VM owns the spawnSync loop, which outlives what the call makes on it.
return unsafe {
Async::EventLoopCtx::new(
Async::EventLoopCtxKind::SpawnSync,
core::ptr::from_ref(self).cast_mut(),
)
};
}
// SAFETY: the VM this loop belongs to outlives it.
unsafe { VirtualMachine::event_loop_ctx(self.vm()) }
}

/// JS thread: the weak poster other threads use to reach the loop this
/// `EventLoop` is — the VM's handle for its embedded loops, or the isolated
/// loop's own poster for a spawnSync loop.
Expand Down Expand Up @@ -1507,6 +1524,7 @@ bun_event_loop::link_impl_JsEventLoop! {
(*store).put(core::ptr::NonNull::new_unchecked(poll), ctx, was_ever_registered);
},
uws_loop() => (*this).usockets_loop(),
event_loop_ctx() => (*this).event_loop_ctx(),
tick() => (*this).tick(),
auto_tick() => (*this).auto_tick(),
auto_tick_active() => (*this).auto_tick_active(),
Expand All @@ -1526,6 +1544,21 @@ bun_event_loop::link_impl_JsEventLoop! {
}
}

// A spawnSync loop differs from its VM's in the loop alone.
bun_io::link_impl_EventLoopCtx! {
SpawnSync for EventLoop => |this| {
platform_event_loop_ptr() => (*this).usockets_loop(),
file_polls_ptr() => VirtualMachine::event_loop_ctx((*this).vm()).file_polls_ptr(),
increment_pending_unref_counter() =>
VirtualMachine::event_loop_ctx((*this).vm()).increment_pending_unref_counter(),
after_event_loop_callback() =>
VirtualMachine::event_loop_ctx((*this).vm()).after_event_loop_callback(),
set_after_event_loop_callback(cb, ctx) =>
VirtualMachine::event_loop_ctx((*this).vm()).set_after_event_loop_callback(cb, ctx),
pipe_read_scratch() => VirtualMachine::event_loop_ctx((*this).vm()).pipe_read_scratch(),
}
}

#[unsafe(no_mangle)]
pub(crate) fn __bun_js_event_loop_current() -> *mut () {
// SAFETY: `VirtualMachine::get()` panics if no VM on this thread;
Expand Down Expand Up @@ -1592,13 +1625,15 @@ pub(crate) fn __bun_spawn_sync_event_loop_tick_tasks_only(el: *mut ()) {
el_ref(el).tick_tasks_only();
}

#[cfg(windows)]
#[unsafe(no_mangle)]
pub(crate) fn __bun_spawn_sync_vm_get_event_loop_handle(
vm: *mut (),
) -> bun_event_loop::SpawnSyncEventLoop::VmEventLoopHandle {
vm_from_ptr(vm).event_loop_handle.and_then(NonNull::new)
}

#[cfg(windows)]
#[unsafe(no_mangle)]
pub(crate) fn __bun_spawn_sync_vm_set_event_loop_handle(
vm: *mut (),
Expand Down
5 changes: 5 additions & 0 deletions src/jsc/rare_data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -832,6 +832,11 @@ impl RareData {
.push(CleanupHook::from(global_this, ctx, func));
}

/// The loop a first `spawn_sync_event_loop` call made.
pub fn existing_spawn_sync_event_loop(&self) -> Option<&SpawnSyncEventLoop> {
self.spawn_sync_event_loop_.as_deref()
}

/// `None` if the loop cannot be created; nothing is cached, so a later call retries.
pub fn spawn_sync_event_loop(
&mut self,
Expand Down
24 changes: 21 additions & 3 deletions src/runtime/api/bun/js_bun_spawn_bindings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1058,7 +1058,9 @@ fn spawn_maybe_sync(
// would capture the *place* `*jsc_vm_ptr` and conflict with later
// `&mut *jsc_vm_ptr` re-borrows below. Copy the raw pointer into a sibling
// local so the closure's captured place is disjoint.
#[cfg(windows)]
let jsc_vm_ptr_cleanup = jsc_vm_ptr;
#[cfg(windows)]
scopeguard::defer! {
if is_sync {
// SAFETY: defer runs while `jsc_vm` (the thread VM) is still live.
Expand Down Expand Up @@ -1721,12 +1723,16 @@ fn spawn_maybe_sync(
Writable::Buffer(buffer) => Writable::buffer_writer_mut(buffer).start().err(),
_ => None,
};
if let Some(err) = stdin_start_err {
if let Some(err) = &stdin_start_err {
// An unstarted writer never reports on_close; a Buffer left here pins the wrapper.
#[cfg(not(windows))] // Windows adopts the pipe at create and start() cannot fail there.
subprocess.on_close_io(Subprocess::StdioKind::Stdin);
let _ = subprocess.try_kill(subprocess.kill_signal);
return Err(cx.global().throw_value(err.to_js(cx.global())));
// No wrapper finalizes a sync Subprocess, and only this call can reap its child: it is killed once
// it is watched, and the error is thrown after the wait below has released everything.
if !is_sync {
let _ = subprocess.try_kill(subprocess.kill_signal);
return Err(cx.global().throw_value(err.to_js(cx.global())));
}
}

// Every `return Err` above is past; the Subprocess will be returned to
Expand Down Expand Up @@ -1803,10 +1809,19 @@ fn spawn_maybe_sync(
}
}
sys::Result::Err(_) => {
if stdin_start_err.is_some() {
let _ = subprocess.try_kill(SignalCode::SIGKILL);
}
subprocess.process_mut().wait(true);
}
}

if stdin_start_err.is_some() {
// Not `kill_signal`, which the child may ignore: nothing else bounds the wait.
let _ = subprocess.try_kill(SignalCode::SIGKILL);
subprocess.close_readable_pipes();
}

if !subprocess.has_exited() {
// SAFETY: jsc_vm_ptr points to the live thread VM; `subprocess.process`
// is a `BackRef` (wraps `NonNull`), so its pointer is non-null.
Expand Down Expand Up @@ -1992,6 +2007,9 @@ fn spawn_maybe_sync(
unsafe {
bun_jsc::host_fn::host_fn_finalize_ref_counted(subprocess_ptr, SubprocessT::finalize)
};
if let Some(err) = stdin_start_err {
return Err(cx.global().throw_value(err.to_js(cx.global())));
}
let (stdout, stderr, resource_usage) = output?;
if let Some(read_error) = read_error {
// The process ran to completion and its output was lost. `pid`, `exitCode` and `signalCode`
Expand Down
17 changes: 8 additions & 9 deletions src/runtime/api/bun/subprocess/SubprocessPipeReader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -362,6 +362,12 @@ impl PipeReader {
}
}

#[cfg(unix)]
fn loop_(&self) -> *mut AsyncLoop {
self.event_loop.native_loop()
}

#[cfg(windows)]
fn loop_(&self) -> *mut AsyncLoop {
// `event_loop.virtual_machine` is set by the time a PipeReader is
// created. The VM is the per-thread singleton owning `event_loop`, so
Expand All @@ -372,15 +378,8 @@ impl PipeReader {
.map(bun_ptr::BackRef::from)
.expect("event_loop.virtual_machine");
let uws = vm.uws_loop();
#[cfg(windows)]
{
// SAFETY: uws loop pointer is live for the VM lifetime.
unsafe { (*uws).uv_loop }
}
#[cfg(not(windows))]
{
uws.cast()
}
// SAFETY: uws loop pointer is live for the VM lifetime.
unsafe { (*uws).uv_loop }
}
}

Expand Down
12 changes: 12 additions & 0 deletions src/runtime/jsc_hooks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4701,6 +4701,18 @@ fn __bun_get_vm_ctx(kind: bun_io::AllocatorType) -> bun_io::EventLoopCtx {
bun_jsc::virtual_machine::VirtualMachine::get_mut_ptr(),
)
},
bun_io::AllocatorType::SpawnSync => {
// SAFETY: `get_mut_ptr()` is the live per-thread VM singleton.
let vm = unsafe { &mut *bun_jsc::virtual_machine::VirtualMachine::get_mut_ptr() };
// SAFETY: the call that is waiting on the loop borrows it from `RareData`; this only reads.
let event_loop = unsafe { &*vm.rare_data_ptr() }
.existing_spawn_sync_event_loop()
.expect("a FilePoll of the spawnSync loop outlived it")
.event_loop_ptr()
.cast::<bun_jsc::event_loop::EventLoop>();
// SAFETY: owned by the VM's `RareData`.
unsafe { (*event_loop).event_loop_ctx() }
}
bun_io::AllocatorType::Mini => {
// SAFETY: `GLOBAL` is set by `MiniEventLoop::init_global` before
// any caller asks for `AllocatorType::Mini` (the global mini loop
Expand Down
Loading
Loading