Skip to content
Open
Show file tree
Hide file tree
Changes from 12 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
2 changes: 1 addition & 1 deletion src/CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -358,7 +358,7 @@ encodes the three modes:

- `borrow = mut` — body forms `&mut *this`; safe when nothing re-enters
- `borrow = shared` — body forms `&*this`; safe when re-entrant code only needs `&Self`
- `borrow = ptr` — body calls `Self::method(this, ..)` with `this: *mut Self`; required when the callback may free `self`
- `borrow = this` — body calls `Self::method(ThisPtr::new(this), ..)` with a root-provenance `bun_ptr::ThisPtr<Self>`; required when the callback may free `self` (the handler is a safe fn that holds its own ref for the call)

### `Strong` / `Weak` JS handles

Expand Down
19 changes: 16 additions & 3 deletions src/codegen/generate-jssink.ts
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,7 @@ using namespace JSC;

${classes.map(name => `extern "C" size_t ${name}__memoryCost(void* sinkPtr);`).join("\n")}
${classes.map(name => `extern "C" void ${name}__controllerDetached(void* sinkPtr, JSC::EncodedJSValue controllerValue);`).join("\n")}
${classes.map(name => `extern "C" void ${name}__controllerFinalize(void* sinkPtr);`).join("\n")}

const ClassInfo JSReadableSinkControllerBase::s_info = { "ReadableSinkController"_s, &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(JSReadableSinkControllerBase) };
`;
Expand Down Expand Up @@ -647,7 +648,7 @@ ${controller}::~${controller}()

if (m_sinkPtr) {
${name}__controllerDetached(m_sinkPtr, JSC::JSValue::encode(this));
${name}__finalize(m_sinkPtr);
${name}__controllerFinalize(m_sinkPtr);
}
}

Expand Down Expand Up @@ -1164,15 +1165,27 @@ pub extern "C" fn ${name}__memoryCost(this: &${name}) -> usize {
`;

// ZIG_DECL void ${name}__finalize(void* sinkPtr) — called from
// JS${name}::~JS${name}, ~JSReadable${name}Controller and ${name}__doClose.
// JS${name}::~JS${name} and ${name}__doClose.
// C++ caller null-checks `m_sinkPtr` / `ptr` before calling. `*mut`, not
// `&mut`: this call may free the sink (see `JsSinkType::finalize`).
symbols.push(`${name}__finalize`);
templ += `#[allow(dead_code, unreachable_pub, unused)]
#[unsafe(no_mangle)]
pub unsafe extern "C" fn ${name}__finalize(this: *mut ${name}) {
// SAFETY: C++ hands over its live \`m_sinkPtr\` once and never uses it again.
unsafe { ${JSSinkT}::js_finalize(this) }
${JSSinkT}::js_finalize(unsafe { bun_ptr::ThisPtr::new(this) })
}

`;

// extern "C" void ${name}__controllerFinalize(void* sinkPtr) — called from
// ~JSReadable${name}Controller when the controller dies still attached.
symbols.push(`${name}__controllerFinalize`);
templ += `#[allow(dead_code, unreachable_pub, unused)]
#[unsafe(no_mangle)]
pub unsafe extern "C" fn ${name}__controllerFinalize(this: *mut ${name}) {
// SAFETY: as \`__finalize\`: the controller's live \`m_sinkPtr\`, handed over once.
${JSSinkT}::js_controller_finalize(unsafe { bun_ptr::ThisPtr::new(this) })
}

`;
Expand Down
20 changes: 12 additions & 8 deletions src/event_loop/ManagedTask.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,10 @@ impl ManagedTask {

/// # Safety
/// `this` must be the live `*mut ManagedTask` embedded in a `Task` returned
/// by `new()`/`new_owned()`; ownership transfers — `this` is freed (via
/// by `new()`/`new_boxed()`; ownership transfers — `this` is freed (via
/// `heap::take`) before return on both Ok and Err paths.
pub unsafe fn run(this: *mut ManagedTask) -> JsResult<()> {
// SAFETY: `this` was produced by `heap::into_raw` in `new`/`new_owned`
// SAFETY: `this` was produced by `heap::into_raw` in `new`/`new_boxed`
// (caller contract). Reconstituting the Box here frees it at scope
// exit on both the Ok and Err paths.
let this = unsafe { bun_core::heap::take(this) };
Expand All @@ -33,7 +33,7 @@ impl ManagedTask {
callback(ctx.unwrap().as_ptr())
}

/// Free without running: the owned context (if `new_owned`) is dropped.
/// Free without running: the owned context (if `new_boxed`) is dropped.
///
/// # Safety
/// As [`run`](Self::run); the task is not queued anywhere.
Expand Down Expand Up @@ -63,19 +63,23 @@ impl ManagedTask {
ManagedTask::task(managed)
}

pub fn new_owned<T>(ctx: *mut T, callback: fn(*mut T) -> JsResult<()>) -> Task {
/// A task that owns `ctx` until it runs: `callback` gets the box back on
/// the JS thread, or it is dropped if the task is released unrun.
pub fn new_boxed<T>(ctx: Box<T>, callback: fn(Box<T>) -> JsResult<()>) -> Task {
fn drop_ctx<T>(p: *mut c_void) {
// SAFETY: `p` is the `heap::into_raw(Box<T>)` stored in `ctx` by `new_owned`.
// SAFETY: `p` is the `heap::into_raw(Box<T>)` stored in `ctx` by `new_boxed`.
unsafe { bun_core::heap::destroy(p.cast::<T>()) };
}
let managed = bun_core::heap::into_raw(Box::new(ManagedTask {
// SAFETY: same fn-pointer ABI cast as `new`.
// SAFETY: `Box<T>` (sized `T`) is ABI-compatible with `*mut c_void`;
// `run` passes back the exact pointer `into_raw` produced below,
// exactly once, so the callee re-owns the box it was given.
callback: unsafe {
bun_ptr::cast_fn_ptr::<fn(*mut T) -> JsResult<()>, fn(*mut c_void) -> JsResult<()>>(
bun_ptr::cast_fn_ptr::<fn(Box<T>) -> JsResult<()>, fn(*mut c_void) -> JsResult<()>>(
callback,
)
},
ctx: NonNull::new(ctx.cast::<c_void>()),
ctx: NonNull::new(bun_core::heap::into_raw(ctx).cast::<c_void>()),
cleanup: Some(drop_ctx::<T>),
}));
ManagedTask::task(managed)
Expand Down
108 changes: 76 additions & 32 deletions src/io/PipeWriter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1302,14 +1302,12 @@ pub trait BaseWindowsPipeWriter: Sized {
self.start_with_current_pipe()
}

/// SAFETY: `pipe` must be a `Box<uv::Pipe>`-allocated pointer.
unsafe fn set_pipe(&mut self, pipe: *mut uv::Pipe) {
fn set_pipe(&mut self, pipe: Box<uv::Pipe>) {
// The assignment below would Drop the prior Box WITHOUT uv_close, leaving
// libuv with a dangling handle → UAF on next loop tick. All other
// start_* paths assert empty; enforce the same invariant here.
debug_assert!(self.source().is_none());
// SAFETY: caller contract — Box-allocated, ownership transfers.
*self.source_mut() = Some(Source::Pipe(unsafe { bun_core::heap::take(pipe) }));
*self.source_mut() = Some(Source::Pipe(pipe));
let p = self.parent_ptr();
self.set_parent(p);
}
Expand Down Expand Up @@ -2572,8 +2570,8 @@ pub type StreamingWriter<P> = WindowsStreamingWriter<P>;
// differing only in:
// (a) the inherent-method names the vtable forwards to,
// (b) how the callback is dispatched off `*mut Self` — as `&mut`, `&`, or
// a raw-ptr method call (re-entrancy under Stacked/Tree Borrows — see
// `borrow = shared` / `borrow = ptr` callers),
// a `ThisPtr` (re-entrancy under Stacked/Tree Borrows — see
// `borrow = shared` / `borrow = this` callers),
// (c) the `event_loop` / `loop_` / refcount accessor expressions.
// These macros stamp that triple once per parent.
//
Expand All @@ -2583,21 +2581,25 @@ pub type StreamingWriter<P> = WindowsStreamingWriter<P>;
// `borrow = shared` → bodies form `&*this` (callback may re-enter JS or
// `enqueue(&self)` and observe a fresh `&Self`; aliased
// `&Self` is sound where `&mut Self` is not).
// `borrow = ptr` → bodies call `Self::method(this, ..)` — no reference is
// materialized at the boundary; for parents that must
// keep full write/dealloc provenance through a re-entrant,
// freeing callback (the callback may run `Box::from_raw`
// on `this`, so a `&self`-derived ptr would carry only
// SharedReadOnly provenance and dealloc through it is UB).
// `borrow = this` → bodies call `Self::method(ThisPtr::new(this), ..)` — no
// reference is materialized at the boundary; for
// intrusively refcounted parents that may drop their last
// ref mid-callback (freeing the allocation under a live
// `&self` argument is UB, and a `&self`-derived pointer
// could not free it), whose handlers are safe fns taking
// `bun_ptr::ThisPtr<Self>` (root provenance).
//
// Accessor args use closure-literal syntax (`|this| expr`) purely as a binder
// for the macro — no actual closure is created; `expr` is pasted into an
// `unsafe` block with `this: *mut Self` in scope.
// for the macro — no actual closure is created. For `mut`/`shared`, `expr`
// is pasted into an `unsafe` block with `this: *mut Self` in scope; for
// `this`, `expr` is pasted as-is with `this: ThisPtr<Self>` in scope.

/// Re-exports for `$crate::`-qualified use inside the macro bodies so callers
/// need no extra `use` items.
#[doc(hidden)]
pub mod __parent_macro {
pub use ::bun_ptr::AnyRefCounted;
pub use ::bun_ptr::ThisPtr;
pub use ::bun_sys::Error as SysError;
#[cfg(windows)]
pub use ::bun_sys::windows::libuv::Loop as UvLoop;
Expand All @@ -2611,7 +2613,22 @@ macro_rules! impl_streaming_writer_parent {
// Internal: dispatch a callback off the raw-ptr backref per `borrow` mode.
(@call mut $p:expr; $m:ident($($a:tt)*)) => { (&mut *$p).$m($($a)*) };
(@call shared $p:expr; $m:ident($($a:tt)*)) => { (&*$p).$m($($a)*) };
(@call ptr $p:expr; $m:ident($($a:tt)*)) => { <Self>::$m($p, $($a)*) };
(@call this $p:expr; $m:ident($($a:tt)*)) => {
<Self>::$m($crate::pipe_writer::__parent_macro::ThisPtr::<Self>::new($p), $($a)*)
};

// Internal: evaluate an accessor body with `$id` bound per `borrow` mode.
(@acc this $id:ident = $p:ident; $e:expr) => {{
// SAFETY: `$p` is the BACKREF set via `set_parent` — the live parent's
// root pointer for as long as the writer it embeds is being called.
let $id = unsafe { $crate::pipe_writer::__parent_macro::ThisPtr::<Self>::new($p) };
$e
}};
(@acc $borrow:tt $id:ident = $p:ident; $e:expr) => {{
let $id = $p;
#[allow(unused_unsafe)]
unsafe { $e }
}};

// Internal: expand the three impls once generics are normalized.
(@emit
Expand All @@ -2635,8 +2652,8 @@ macro_rules! impl_streaming_writer_parent {
unsafe fn on_write(this: *mut Self, amount: usize, status: $crate::WriteStatus) {
// SAFETY: `this` is the BACKREF set via `set_parent`; the
// StreamingWriter never materializes `&mut Parent`. The handler
// is dispatched per the `borrow` mode (`mut`/`shared`/`ptr` —
// see the module comment); `ptr` keeps full write/dealloc
// is dispatched per the `borrow` mode (`mut`/`shared`/`this` —
// see the module comment); `this` keeps full write/dealloc
// provenance through re-entrant, freeing callbacks.
unsafe { $crate::impl_streaming_writer_parent!(@call $borrow this; $on_write(amount, status)) }
}
Expand All @@ -2658,16 +2675,12 @@ macro_rules! impl_streaming_writer_parent {
#[inline]
unsafe fn event_loop(this: *mut Self) -> $crate::EventLoopHandle {
// SAFETY: see on_write. Shared-only read.
let $el_this = this;
#[allow(unused_unsafe)]
unsafe { $el }
$crate::impl_streaming_writer_parent!(@acc $borrow $el_this = this; $el)
}
#[inline]
unsafe fn loop_(this: *mut Self) -> *mut $crate::pipe_writer::__parent_macro::UwsLoop {
// SAFETY: see on_write. Shared-only read.
let $uws_this = this;
#[allow(unused_unsafe)]
unsafe { $uws }
$crate::impl_streaming_writer_parent!(@acc $borrow $uws_this = this; $uws)
}
}

Expand All @@ -2676,23 +2689,17 @@ macro_rules! impl_streaming_writer_parent {
#[inline]
unsafe fn loop_(this: *mut Self) -> *mut $crate::pipe_writer::__parent_macro::UvLoop {
// SAFETY: BACKREF set via `set_parent`; shared-only read.
let $uv_this = this;
#[allow(unused_unsafe)]
unsafe { $uv }
$crate::impl_streaming_writer_parent!(@acc $borrow $uv_this = this; $uv)
}
#[inline]
unsafe fn ref_(this: *mut Self) {
// SAFETY: see loop_. Intrusive refcount bump.
let $ref_this = this;
#[allow(unused_unsafe)]
unsafe { $ref_ };
$crate::impl_streaming_writer_parent!(@acc $borrow $ref_this = this; $ref_)
}
#[inline]
unsafe fn deref(this: *mut Self) {
// SAFETY: see loop_. May free `this`.
let $deref_this = this;
#[allow(unused_unsafe)]
unsafe { $deref };
$crate::impl_streaming_writer_parent!(@acc $borrow $deref_this = this; $deref)
}
}

Expand Down Expand Up @@ -2733,6 +2740,43 @@ macro_rules! impl_streaming_writer_parent {
}
};

// Public entry — `borrow = this`, intrusively refcounted parent: the
// writer's per-write `ref_`/`deref` hooks are the parent's own refcount.
(
$Ty:ty;
poll_tag = $poll_tag:expr,
borrow = this,
on_write = $on_write:ident,
on_error = $on_error:ident,
on_ready = $on_ready:ident,
on_close = $on_close:ident,
event_loop = |$el_this:ident| $el:expr,
uws_loop = |$uws_this:ident| $uws:expr,
uv_loop = |$uv_this:ident| $uv:expr,
) => {
$crate::impl_streaming_writer_parent! {
@emit [] $Ty;
poll_tag = $poll_tag,
borrow = this,
on_write = $on_write,
on_error = $on_error,
on_ready = $on_ready,
on_close = $on_close,
event_loop = |$el_this| $el,
uws_loop = |$uws_this| $uws,
uv_loop = |$uv_this| $uv,
// SAFETY: `this_` is the live parent's root pointer.
ref_ = |this_| unsafe {
<$Ty as $crate::pipe_writer::__parent_macro::AnyRefCounted>::rc_ref(this_.as_ptr())
},
// SAFETY: releases the ref the writer took through `ref_` above for
// the write that just completed; `this_` is the parent's root pointer.
deref = |this_| unsafe {
<$Ty as $crate::pipe_writer::__parent_macro::AnyRefCounted>::rc_deref(this_.as_ptr())
},
}
};

// Public entry — non-generic parent.
(
$Ty:ty;
Expand Down
Loading
Loading