Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
25 changes: 10 additions & 15 deletions src/runtime/api/JSON5Object.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use bun_ast::{E, Expr, expr::Data as ExprData};
use bun_collections::HashMap;
use bun_collections::VecExt;
use bun_core::StackCheck;
use bun_core::{String as BunString, ZigString};
use bun_core::{OwnedString, String as BunString, ZigString};
use bun_js_parser::lexer;
use bun_jsc::{self as jsc, CallFrame, JSGlobalObject, JSValue, JsError, JsResult, StringJsc, wtf};
use bun_parsers::json5;
Expand Down Expand Up @@ -109,7 +109,8 @@ type StringifyResult<T> = Result<T, StringifyError>;
enum Space {
Minified,
Number(u32),
Str(BunString),
/// +1 WTF ref owned for the lifetime of the `Stringifier`.
Str(OwnedString),
}

impl Space {
Expand All @@ -126,9 +127,8 @@ impl Space {
return Ok(Space::Number(if num_f > 10.0 { 10 } else { num_f as u32 }));
}
if space.is_string() {
let str = space.to_bun_string(global)?;
let str = OwnedString::new(space.to_bun_string(global)?);
if str.length() == 0 {
// `str` drops here (deref)
return Ok(Space::Minified);
}
return Ok(Space::Str(str));
Expand All @@ -137,8 +137,6 @@ impl Space {
}
}

// NOTE: `Space::deinit` deleted — `BunString` field derefs via `Drop`.

impl Stringifier {
pub(crate) fn init(global: &JSGlobalObject, space_value: JSValue) -> JsResult<Stringifier> {
Ok(Stringifier {
Expand All @@ -150,9 +148,6 @@ impl Stringifier {
})
}

// NOTE: `deinit` deleted — all fields (`builder`, `space`, `visiting`)
// free via `Drop`.

pub(crate) fn stringify_value(
&mut self,
global: &JSGlobalObject,
Expand Down Expand Up @@ -203,7 +198,7 @@ impl Stringifier {
}

if unwrapped.is_string() {
let str = bun_core::OwnedString::new(unwrapped.to_bun_string(global)?);
let str = OwnedString::new(unwrapped.to_bun_string(global)?);
self.append_quoted_string(&str);
return Ok(());
}
Expand Down Expand Up @@ -372,7 +367,7 @@ impl Stringifier {
};

if is_identifier {
self.builder.append_string(name.clone());
self.builder.append_string(*name);
} else {
self.append_quoted_string(name);
}
Expand Down Expand Up @@ -419,13 +414,13 @@ impl Stringifier {
}
Space::Str(space_str) => {
self.builder.append_lchar(b'\n');
let clamped = if space_str.length() > 10 {
let clamped: BunString = if space_str.length() > 10 {
space_str.substring_with_len(0, 10)
} else {
space_str.clone()
**space_str
};
for _ in 0..self.indent {
self.builder.append_string(clamped.clone());
self.builder.append_string(clamped);
}
}
}
Expand Down Expand Up @@ -476,7 +471,7 @@ fn expr_to_js_with_check(
stack_check,
)?;
let key_js = expr_to_js_with_check(key_expr, global, stack_check)?;
let key_str = bun_core::OwnedString::new(key_js.to_bun_string(global)?);
let key_str = OwnedString::new(key_js.to_bun_string(global)?);
js_obj.put_may_be_index(global, &key_str, value)?;
}
Ok(js_obj)
Expand Down
40 changes: 40 additions & 0 deletions test/js/bun/json5/json5.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1659,3 +1659,43 @@ describe("deeply nested parse results", () => {
expect(exitCode).toBe(0);
});
});

describe("stringify memory", () => {
test("does not leak with a string space argument", async () => {
// Unique >10-char space string per call so each iteration allocates a
// fresh WTFStringImpl for the stored space and hits the clamp branch in
// newline(). Nested object/array so indent > 0.
await using proc = Bun.spawn({
cmd: [
bunExe(),
"--smol",
"-e",
/* js */ `
const obj = { a: [1, 2, 3], b: { c: 4 }, d: 5 };
const pad = Buffer.alloc(1024 * 1024, " ").toString();
for (let i = 0; i < 20; i++) Bun.JSON5.stringify(obj, null, pad + i);
Bun.gc(true);
const before = process.memoryUsage.rss();
for (let i = 0; i < 200; i++) Bun.JSON5.stringify(obj, null, pad + i);
Bun.gc(true);
const growthMB = (process.memoryUsage.rss() - before) / 1024 / 1024;
if (growthMB > 64) throw new Error("leaked " + growthMB.toFixed(2) + "MB");
`,
],
env: {
...bunEnv,
// Under ASAN every freed allocation parks in the allocator quarantine
// (default quarantine_size_mb=256) instead of being returned, so the
// RSS-delta heuristic over-reports even when nothing leaks. Disable
// the quarantine for this measurement process so the 64 MB threshold
// keeps separating "fixed" from "leaking ~200 MB". Harmless when the
// binary is not ASAN-built.
ASAN_OPTIONS: [bunEnv.ASAN_OPTIONS, "quarantine_size_mb=0"].filter(Boolean).join(":"),
},
stdout: "pipe",
stderr: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
expect({ stdout, stderr, exitCode }).toEqual({ stdout: "", stderr: "", exitCode: 0 });
Comment thread
robobun marked this conversation as resolved.
Resolved
});
});
Loading