Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
3fac049
Make bun_core::String own its WTF ref (Drop = deref, Clone = ref)
dylan-conway Aug 23, 2026
f56f83c
Address clippy: borrow instead of by-value String params, drop identi…
dylan-conway Aug 23, 2026
07e13f7
Add regression test for the jsonb bind leak (#40102); propagate into_…
dylan-conway Aug 23, 2026
d6df770
Merge remote-tracking branch 'origin/main' into claude/bun-core-strin…
dylan-conway Aug 23, 2026
8d4d029
Trim refcount traffic: into_js for last-use strings, borrow TOML key …
dylan-conway Aug 23, 2026
1abee86
Simplify around the owning String: drop StringCell, return values not…
dylan-conway Aug 23, 2026
b7691c1
Fix putIndex on non-array objects (http2 custom settings), address re…
dylan-conway Aug 23, 2026
9686e63
FFI: a by-value String in an extern signature means ownership crosses
dylan-conway Aug 23, 2026
409a4cd
Second simplification pass: return Strings instead of writing out-params
dylan-conway Aug 23, 2026
6b64206
ZigException::Holder: drop only the populated frame/source-line prefixes
dylan-conway Aug 23, 2026
e22735d
shell lexer: drop stale borrowck comment on string_refs
dylan-conway Aug 23, 2026
045baf2
bun_core::String: spell the inner POD as bun_alloc::String, drop the …
dylan-conway Aug 23, 2026
e34fd40
node_process: fix getRedirectWarnings doc comment
dylan-conway Aug 23, 2026
83737ac
Remove JSValue::get_zig_string/to_zig_string; JSString::view is lifet…
dylan-conway Aug 23, 2026
9b40b6b
Third pass: one-FFI JSString views, owned class/name getters, drop Zi…
dylan-conway Aug 23, 2026
6b8c76f
Drop LoaderHooks table, tie property-iterator names to the iterator, …
dylan-conway Aug 23, 2026
c09b5ec
Merge remote-tracking branch 'origin/main' into claude/bun-core-strin…
dylan-conway Aug 23, 2026
eb6b654
Review follow-ups: static symbol_for keys, borrowed symbol descriptio…
dylan-conway Aug 23, 2026
3aad87c
ZigException::Holder::deinit takes &mut self so the boxed holder is n…
dylan-conway Aug 23, 2026
fd9863e
DevServer: hand the server HMR runtime to JSC as a static external st…
dylan-conway Aug 23, 2026
76a30ab
JSStringView: a borrowed JSString view that pins the cell while alive
dylan-conway Aug 23, 2026
79251c6
postgres-json-bind-leak test: widen RSS bound for macOS allocator sla…
dylan-conway Aug 23, 2026
f900aa5
Rename JSC__JSValue__toStringAndView to JSC__JSValue__toJSStringView …
dylan-conway Aug 23, 2026
ad949cf
Add regression tests for eight of the string leaks
dylan-conway Aug 23, 2026
59397f8
Add regression test for leaked RESP map keys (150 MiB on 1.4.0 via a …
dylan-conway Aug 24, 2026
37ae971
ModuleLoader.cpp: Bun__fetchBuiltinModule returning true implies succ…
dylan-conway Aug 24, 2026
1528f23
doc: point to_utf8_borrowed / WtfBorrowed docs at String::into_slice
dylan-conway Aug 24, 2026
5c56975
Merge remote-tracking branch 'origin/main' into claude/bun-core-strin…
dylan-conway Aug 24, 2026
7007f7a
Review round: JSString::view without flattening, FFI consume/read con…
dylan-conway Aug 24, 2026
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/ast_jsc/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ pub fn log_to_js(this: &Log, global: &JSGlobalObject, message: &[u8]) -> JsResul
pub fn log_to_js_aggregate_error(
this: &Log,
global: &JSGlobalObject,
message: bun_core::String,
message: &bun_core::String,
) -> JsResult<JSValue> {
global.create_aggregate_error_with_array(message, log_to_js_array(this, global)?)
}
Expand Down
4 changes: 2 additions & 2 deletions src/bun_core/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,8 @@ pub mod string;
pub use ::bstr::{BStr, BString, ByteSlice};
pub use string::string_joiner::StringJoiner;
pub use string::{
HashedString, MutableString, NodeEncoding, OwnedString, OwnedStringCell,
SliceWithUnderlyingString, SmolStr, String, StringBuilder, WTFStringImpl, WTFStringImplExt,
HashedString, MutableString, NodeEncoding, RawString, SliceWithUnderlyingString, SmolStr,
String, StringBuilder, StringCell, StringView, WTFStringImpl, WTFStringImplExt,
WTFStringImplStruct, ZigString, ZigStringSlice,
};
pub use string::{
Expand Down
402 changes: 214 additions & 188 deletions src/bun_core/string/mod.rs

Large diffs are not rendered by default.

33 changes: 15 additions & 18 deletions src/bundler/analyze_transpiled_module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -162,11 +162,23 @@ pub enum Owner {
ModuleInfo(*mut ModuleInfo),
AllocatedSlice {
/// [`MODULE_INFO_ALIGN`]-aligned heap slice from [`dupe_aligned`];
/// freed in `deinit` via [`free_aligned_dup`].
/// freed via [`free_aligned_dup`].
slice: *mut [u8],
},
}

impl Drop for ModuleInfoDeserialized {
fn drop(&mut self) {
// SAFETY: `owner` is the unique owner of its allocation (see `Owner`).
unsafe {
match self.owner {
Owner::ModuleInfo(mi) => drop(bun_core::heap::take(mi)),
Owner::AllocatedSlice { slice } => free_aligned_dup(slice),
}
}
}
}

impl ModuleInfoDeserialized {
// ── safe accessors ───────────────────────────────────────────────────
// All slice fields are non-null self-referential views into `self.owner`
Expand Down Expand Up @@ -209,29 +221,14 @@ impl ModuleInfoDeserialized {
self.record_kinds.slice()
}

/// Consumes the heap allocation containing `self` (and, for
/// `Owner::ModuleInfo`, the enclosing `ModuleInfo`). Not `Drop` because it
/// deallocates the object itself and is invoked across FFI on a raw `*mut`.
/// Consumes the heap allocation containing `self`.
///
/// # Safety
/// `this` must have been produced by [`Self::create`] (heap box) or by
/// [`ModuleInfoExt::into_deserialized`].
pub(crate) unsafe fn deinit(this: *mut ModuleInfoDeserialized) {
// SAFETY: caller contract — see fn doc above.
unsafe {
match (*this).owner {
Owner::ModuleInfo(mi) => {
// The `*mut ModuleInfo` is stored directly because the printer
// crate's `ModuleInfo` no longer embeds this struct.
drop(bun_core::heap::take(mi));
drop(bun_core::heap::take(this));
}
Owner::AllocatedSlice { slice } => {
free_aligned_dup(slice);
drop(bun_core::heap::take(this));
}
}
}
drop(unsafe { bun_core::heap::take(this) });
}

#[inline]
Expand Down
4 changes: 2 additions & 2 deletions src/bundler/bundle_v2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1408,7 +1408,7 @@ pub mod bv2_impl {
safe fn __bun_jsc_generate_cached_bytecode(
format: crate::options_impl::Format,
source: &[u8],
source_provider_url: &mut bun_core::String,
source_provider_url: &bun_core::String,
) -> Option<Box<[u8]>>;
}

Expand Down Expand Up @@ -1446,7 +1446,7 @@ pub mod bv2_impl {
pub(crate) fn generate_cached_bytecode(
format: crate::options_impl::Format,
source: &[u8],
source_provider_url: &mut bun_core::String,
source_provider_url: &bun_core::String,
) -> Option<Box<[u8]>> {
__bun_jsc_generate_cached_bytecode(format, source, source_provider_url)
}
Expand Down
7 changes: 1 addition & 6 deletions src/bundler/linker_context/generateChunksInParallel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1053,16 +1053,11 @@ pub(crate) fn generate_chunks_in_parallel<const IS_DEV_SERVER: bool>(
BYTECODE_EXTENSION
))
};
source_provider_url.ref_();
// RAII: `defer source_provider_url.deref()` — `OwnedString::Drop`
// releases the ref bumped above on every exit path (incl. `break 'brk`).
let mut source_provider_url =
bun_core::OwnedString::new(source_provider_url);

if let Some(bytecode) = crate::bundle_v2::dispatch::generate_cached_bytecode(
c.options.output_format,
&code_result.buffer,
&mut source_provider_url,
&source_provider_url,
) {
let source_provider_url_str = source_provider_url.to_utf8();
debug!(
Expand Down
5 changes: 1 addition & 4 deletions src/bundler/linker_context/writeOutputFilesToDisk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -400,14 +400,11 @@ pub(crate) fn write_output_files_to_disk(
bstr::BStr::new(&chunk.final_rel_path),
BYTECODE_EXTENSION,
));
source_provider_url.ref_();
// `defer source_provider_url.deref()` handled by Drop on OwnedString.
let mut source_provider_url = bun_core::OwnedString::new(source_provider_url);

if let Some(bytecode) = crate::bundle_v2::dispatch::generate_cached_bytecode(
c.options.output_format,
&code_result.buffer,
&mut source_provider_url,
&source_provider_url,
) {
let source_provider_url_str = source_provider_url.to_utf8();
debug!(
Expand Down
3 changes: 3 additions & 0 deletions src/codegen/cppbind.ts
Original file line number Diff line number Diff line change
Expand Up @@ -559,6 +559,9 @@ function generateRustType(type: CppType, parent: CppType | null): string {
if (bannedTypes[type.name]) {
appendError(type.position, bannedTypes[type.name]);
}
// `BunString` by value crosses the boundary as the `Copy` FFI mirror; the
// owning `bun_core::String` (has `Drop`) only ever appears behind a pointer.
if (type.name === "BunString" && parent?.type !== "pointer") return "bun_core::RawString";
const t = rustSharedTypes[type.name];
if (t) return t;
// Unknown opaque — only valid behind a pointer (the per-type shim casts the
Expand Down
4 changes: 2 additions & 2 deletions src/css_jsc/color_js.rs
Original file line number Diff line number Diff line change
Expand Up @@ -368,7 +368,7 @@ pub fn js_function_color(global: &JSGlobalObject, frame: &CallFrame) -> JsResult
};

'formatted: {
let mut str: BunString = 'color: {
let str: BunString = 'color: {
match format {
// resolved above.
OutputColorFormat::Ansi => unreachable!(),
Expand Down Expand Up @@ -597,7 +597,7 @@ pub fn js_function_color(global: &JSGlobalObject, frame: &CallFrame) -> JsResult
}
};

return str.transfer_to_js(global);
return str.into_js(global);
}

// Fallback to CSS string output
Expand Down
13 changes: 6 additions & 7 deletions src/css_jsc/css_internals.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use bun_alloc::Arena; // bumpalo::Bump re-export
use bun_ast::Log;
use bun_core::{OwnedString, String as BunString};
use bun_core::String as BunString;
use bun_css::targets::{Browsers, Targets};
use bun_jsc::{CallFrame, JSGlobalObject, JSValue};

Expand Down Expand Up @@ -61,16 +61,16 @@ pub fn _test(global: &JSGlobalObject, frame: &CallFrame) -> JsResult<JSValue> {
/// Shared arg-validation for the test-only CSS internals: pulls the next arg,
/// throws "{fn_name}: expected {expected_n} arguments, got {got_n}" if absent,
/// throws "{fn_name}: expected {arg_label} to be a string" if not a string,
/// otherwise returns the +1-ref BunString wrapped in `OwnedString` for RAII deref.
/// Caller does `.to_utf8()` (borrows the OwnedString, so can't be returned here).
/// otherwise returns the +1-ref `bun_core::String`.
/// Caller does `.to_utf8()` (borrows the bun_core::String, so can't be returned here).
fn eat_string_arg(
arguments: &mut bun_jsc::ArgumentsSlice<'_>,
global: &JSGlobalObject,
fn_name: &str,
expected_n: u32,
got_n: u32,
arg_label: &str,
) -> JsResult<OwnedString> {
) -> JsResult<bun_core::String> {
let Some(arg) = arguments.next_eat() else {
return Err(global.throw(format_args!(
"{fn_name}: expected {expected_n} arguments, got {got_n}"
Expand All @@ -81,7 +81,7 @@ fn eat_string_arg(
"{fn_name}: expected {arg_label} to be a string"
)));
}
Ok(OwnedString::new(arg.to_bun_string(global)?))
Ok(arg.to_bun_string(global)?)
}

fn testing_impl(
Expand Down Expand Up @@ -238,8 +238,7 @@ fn parser_options_from_js(
if val.is_array() {
let mut iter = val.array_iterator(global)?;
while let Some(item) = iter.next()? {
// `OwnedString` releases the +1 ref at the end of each iteration.
let bunstr = OwnedString::new(item.to_bun_string(global)?);
let bunstr = item.to_bun_string(global)?;
let str = bunstr.to_utf8();
if str.slice() == b"DEEP_SELECTOR_COMBINATOR" {
opts.flags |= bun_css::ParserFlags::DEEP_SELECTOR_COMBINATOR;
Expand Down
3 changes: 0 additions & 3 deletions src/css_jsc/error_jsc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,6 @@ where
T: Display,
{
let str = BunString::create_format(format_args!("{}", this.kind));
// `to_error_instance` consumes the caller's reference (it derefs the string
// itself), so the `+1` from `create_format` must not be dropped again here —
// an extra deref frees the WTFStringImpl while the error still uses it.
let js = bun_jsc::bun_string_jsc::to_error_instance(&str, global_this);
Ok(js)
}
8 changes: 4 additions & 4 deletions src/http/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -997,7 +997,7 @@ use bun_boringssl as boringssl;
use bun_collections::{ArrayHashMap, VecExt};
use bun_core::StringBuilder;
use bun_core::{FeatureFlags, Global, Output};
use bun_core::{OwnedString, String as BunString, Tag as BunStringTag, strings};
use bun_core::{String as BunString, Tag as BunStringTag, strings};
use bun_http_types::ETag::StringPointer;
use bun_uws as uws;
// the std Wyhash algorithm, not Wyhash11.
Expand Down Expand Up @@ -5085,7 +5085,7 @@ impl<'a> HTTPClient<'a> {
debug_assert!(string_builder.cap == string_builder.len);

let input = BunString::borrow_utf8(string_builder.allocated_slice());
let normalized_url = OwnedString::new(bun_url::href_from_string(&input));
let normalized_url = bun_url::href_from_string(&input);
if normalized_url.tag() == BunStringTag::Dead {
// URL__getHref failed, dont pass dead tagged string to toOwnedSlice.
return Err(crate::Error::RedirectURLInvalid);
Expand Down Expand Up @@ -5141,7 +5141,7 @@ impl<'a> HTTPClient<'a> {
debug_assert!(string_builder.cap == string_builder.len);

let input = BunString::borrow_utf8(string_builder.allocated_slice());
let normalized_url = OwnedString::new(bun_url::href_from_string(&input));
let normalized_url = bun_url::href_from_string(&input);
if normalized_url.tag() == BunStringTag::Dead {
return Err(crate::Error::RedirectURLInvalid);
}
Expand All @@ -5165,7 +5165,7 @@ impl<'a> HTTPClient<'a> {

let base = BunString::borrow_utf8(original_url.href);
let rel = BunString::borrow_utf8(location);
let new_url_ = OwnedString::new(bun_url::join(&base, &rel));
let new_url_ = bun_url::join(&base, &rel);

if new_url_.is_empty() {
return Err(crate::Error::InvalidRedirectURL);
Expand Down
6 changes: 2 additions & 4 deletions src/http_jsc/method_jsc.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! JSC bridge for `bun_http_types::Method`. Keeps `bun_http_types` free of JSC types.

use bun_core::{OwnedString, String as BunString};
use bun_core::String as BunString;
use bun_http_types::Method::Method;
use bun_jsc::{JSGlobalObject, JSValue, JsResult, StringJsc as _};

Expand All @@ -17,9 +17,7 @@ unsafe extern "C" {
///
/// Lives here (not in `bun_http_types`) so the base crate stays JSC-free.
pub fn from_js(global_this: &JSGlobalObject, input: JSValue) -> JsResult<Option<Method>> {
// `defer str.deref()` — `bun_core::String` is `Copy` (no `Drop`), so wrap the
// +1 ref from `BunString::from_js` in `OwnedString` to release it on scope exit.
let str = OwnedString::new(BunString::from_js(input, global_this)?);
let str = BunString::from_js(input, global_this)?;
debug_assert!(str.tag() != bun_core::Tag::Dead);
// `Method::which` is keyed on `&[u8]`, so materialize UTF-8 and call it
// directly.
Expand Down
16 changes: 7 additions & 9 deletions src/http_jsc/websocket_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -183,9 +183,7 @@ impl<const SSL: bool> WebSocket<SSL> {
self.clear_send_buffers(true);
self.control_frame_started.set(false);
self.ping_len.set(0);
if let Some((_, reason)) = self.close_dispatch_pending.take() {
reason.deref();
}
self.close_dispatch_pending.take();
self.receiving_compressed.set(false);
self.message_is_compressed.set(false);
self.deflate.replace(None);
Expand Down Expand Up @@ -294,13 +292,13 @@ impl<const SSL: bool> WebSocket<SSL> {
pub fn handle_close(&self, _socket: Socket<SSL>, _code: c_int, _reason: *mut c_void) {
log!("onClose");
jsc::mark_binding!();
if let Some((code, mut reason)) = self.close_dispatch_pending.take() {
if let Some((code, reason)) = self.close_dispatch_pending.take() {
// The socket closed while our close frame was mid-flush; the peer
// either got it or didn't, but JS should still see the
// user-initiated code/reason (not an abrupt 1006).
self.detach_tcp();
self.clear_data();
self.dispatch_close(code, &mut reason);
self.dispatch_close(code, reason);
// For the socket.
self.release_io_ref();
return;
Expand Down Expand Up @@ -1152,7 +1150,7 @@ impl<const SSL: bool> WebSocket<SSL> {
if self.send_buffer.borrow().readable_length() == 0 {
self.shutdown_after_close_frame();
self.clear_data();
self.dispatch_close(dispatch_code, &mut reason);
self.dispatch_close(dispatch_code, reason);
} else {
// The close frame was only partially written; the remainder is
// in send_buffer. clear_data() would discard it (and the
Expand All @@ -1178,10 +1176,10 @@ impl<const SSL: bool> WebSocket<SSL> {
}

fn finish_pending_close(&self) {
if let Some((code, mut reason)) = self.close_dispatch_pending.take() {
if let Some((code, reason)) = self.close_dispatch_pending.take() {
self.shutdown_after_close_frame();
self.clear_data();
self.dispatch_close(code, &mut reason);
self.dispatch_close(code, reason);
}
}

Expand Down Expand Up @@ -1374,7 +1372,7 @@ impl<const SSL: bool> WebSocket<SSL> {
}

/// May free `self`.
fn dispatch_close(&self, code: u16, reason: &mut bun_core::String) {
fn dispatch_close(&self, code: u16, reason: bun_core::String) {
let Some((out, cpp_ref)) = self.outgoing_websocket.replace(None) else {
return;
};
Expand Down
8 changes: 4 additions & 4 deletions src/http_jsc/websocket_client/CppWebSocket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,10 +118,10 @@ impl CppWebSocket {
event_loop.exit();
}

pub(crate) fn did_close(&self, code: u16, reason: &mut BunString) {
pub(crate) fn did_close(&self, code: u16, mut reason: BunString) {
let event_loop = VirtualMachine::get().event_loop_mut();
event_loop.enter();
WebSocket__didClose(self, code, reason);
WebSocket__didClose(self, code, &mut reason);
event_loop.exit();
}

Expand Down Expand Up @@ -188,9 +188,9 @@ impl CppWebSocket {
WebSocket__releasePendingActivityForClient(self);
}

pub(crate) fn set_protocol(&self, protocol: &mut BunString) {
pub(crate) fn set_protocol(&self, mut protocol: BunString) {
bun_jsc::mark_binding!();
WebSocket__setProtocol(self, protocol);
WebSocket__setProtocol(self, &mut protocol);
}
}

Expand Down
6 changes: 1 addition & 5 deletions src/http_jsc/websocket_client/WebSocketUpgradeClient.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1160,11 +1160,7 @@ where
}

if let Some(ws) = this.cpp_websocket() {
let mut protocol_str = BunString::clone_latin1(protocol);
ws.set_protocol(&mut protocol_str);
// `BunString` is `Copy`; explicitly drop the
// ref taken by `clone_latin1`.
protocol_str.deref();
ws.set_protocol(BunString::clone_latin1(protocol));
}
true
};
Expand Down
Loading
Loading