Skip to content
Closed
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
7 changes: 7 additions & 0 deletions src/jsc/DOMFormData.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ unsafe extern "C" {
arg4: &EncodedSlice,
);
safe fn WebCore__DOMFormData__count(arg0: &mut DOMFormData) -> usize;
safe fn WebCore__DOMFormData__reportMemoryCost(value: JSValue);
}

impl DOMFormData {
Expand Down Expand Up @@ -81,4 +82,10 @@ impl DOMFormData {
pub fn count(&mut self) -> usize {
WebCore__DOMFormData__count(self)
}

/// Report the native byte cost of the wrapper to the GC. Call after a batch
/// of native appends so the allocation-driven GC trigger can see the bytes.
Comment thread
robobun marked this conversation as resolved.
Resolved
pub fn report_memory_cost(value: JSValue) {
WebCore__DOMFormData__reportMemoryCost(value);
}
}
11 changes: 10 additions & 1 deletion src/jsc/bindings/bindings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6331,7 +6331,16 @@ CPP_DECL JSC::EncodedJSValue WebCore__DOMFormData__createFromURLQuery(JSC::JSGlo
return Bun::ERR::STRING_TOO_LONG(scope, globalObject);
}
auto formData = DOMFormData::create(globalObject->scriptExecutionContext(), WTF::move(str));
return JSValue::encode(toJSNewlyCreated(arg0, globalObject, WTF::move(formData)));
auto jsValue = toJSNewlyCreated(arg0, globalObject, WTF::move(formData));
if (auto* wrapper = dynamicDowncast<WebCore::JSDOMFormData>(jsValue))
wrapper->computeMemoryCost();
return JSValue::encode(jsValue);
}

CPP_DECL void WebCore__DOMFormData__reportMemoryCost(JSC::EncodedJSValue value)
{
if (auto* wrapper = dynamicDowncast<WebCore::JSDOMFormData>(JSC::JSValue::decode(value)))
wrapper->computeMemoryCost();
}
Comment thread
robobun marked this conversation as resolved.
Resolved

CPP_DECL JSC::EncodedJSValue WebCore__DOMFormData__create(JSC::JSGlobalObject* arg0)
Expand Down
1 change: 1 addition & 0 deletions src/jsc/bindings/headers.h

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

21 changes: 21 additions & 0 deletions src/jsc/bindings/webcore/JSDOMFormData.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,16 @@ void JSDOMFormData::finishCreation(VM& vm)
// static_assert(!std::is_base_of<ActiveDOMObject, DOMFormData>::value, "Interface is not marked as [ActiveDOMObject] even though implementation class subclasses ActiveDOMObject.");
}

void JSDOMFormData::computeMemoryCost()
{
size_t previousCost = m_memoryCost;
m_memoryCost = wrapped().memoryCost();
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
int64_t diff = static_cast<int64_t>(m_memoryCost) - static_cast<int64_t>(previousCost);
if (diff > 0) {
globalObject()->vm().heap.reportExtraMemoryAllocated(this, static_cast<uint64_t>(diff));
}
}

JSObject* JSDOMFormData::createPrototype(VM& vm, JSDOMGlobalObject& globalObject)
{
auto* structure = JSDOMFormDataPrototype::createStructure(vm, &globalObject, globalObject.objectPrototype());
Expand Down Expand Up @@ -725,4 +735,15 @@ size_t JSDOMFormData::estimatedSize(JSCell* cell, JSC::VM& vm)
return Base::estimatedSize(cell, vm) + wrapped.memoryCost();
}

template<typename Visitor>
void JSDOMFormData::visitChildrenImpl(JSCell* cell, Visitor& visitor)
{
auto* thisObject = uncheckedDowncast<JSDOMFormData>(cell);
ASSERT_GC_OBJECT_INHERITS(thisObject, info());
Base::visitChildren(thisObject, visitor);
visitor.reportExtraMemoryVisited(thisObject->m_memoryCost);
}

DEFINE_VISIT_CHILDREN(JSDOMFormData);

}
4 changes: 4 additions & 0 deletions src/jsc/bindings/webcore/JSDOMFormData.h
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ class JSDOMFormData : public JSDOMWrapper<DOMFormData> {
static void destroy(JSC::JSCell*);

DECLARE_INFO;
DECLARE_VISIT_CHILDREN;

static JSC::Structure* createStructure(JSC::VM& vm, JSC::JSGlobalObject* globalObject, JSC::JSValue prototype)
{
Expand All @@ -58,6 +59,9 @@ class JSDOMFormData : public JSDOMWrapper<DOMFormData> {
static void analyzeHeap(JSCell*, JSC::HeapAnalyzer&);
static size_t estimatedSize(JSCell* cell, JSC::VM& vm);

size_t m_memoryCost { 0 };
void computeMemoryCost();

protected:
JSDOMFormData(JSC::Structure*, JSDOMGlobalObject&, Ref<DOMFormData>&&);

Expand Down
1 change: 1 addition & 0 deletions src/runtime/webcore/FormData.rs
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,7 @@ pub(crate) fn to_js_from_multipart_data(
}
}

DOMFormData::report_memory_cost(form_data_value);
Comment thread
robobun marked this conversation as resolved.
Resolved
Ok(form_data_value)
}

Expand Down
63 changes: 63 additions & 0 deletions test/js/web/html/FormData.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1004,3 +1004,66 @@ describe("USVString conversion of lone surrogates", () => {
expect(formData.get("\uFFFD")).toBeNull();
});
});

// A parsed FormData stores its entries as native WTF::String bytes outside the
// JS heap. The JS wrapper must report those bytes to the GC, otherwise the
// allocation-driven GC trigger never fires and the native memory accumulates
// while requests keep arriving. See ledger #23371.
Comment thread
robobun marked this conversation as resolved.
Resolved
describe.concurrent("FormData native memory is reported to the GC", () => {
async function extraMemoryDelta(buildBody: string, contentType: string, count: number): Promise<number> {
const script = `
const { heapStats } = require("bun:jsc");
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
const headers = { "content-type": ${JSON.stringify(contentType)} };
const buildBody = ${buildBody};

Bun.gc(true);
const before = heapStats().extraMemorySize;

const live = [];
for (let i = 0; i < ${count}; i++) {
live.push(await new Response(buildBody(), { headers }).formData());
}

// Collect the transient request bodies. Only the referenced FormData
// objects and their reported native bytes remain.
Bun.gc(true);
const after = heapStats().extraMemorySize;
process.stdout.write(String(after - before));
if (live.length !== ${count}) throw new Error("unreachable");
`;

await using proc = Bun.spawn({
cmd: [bunExe(), "-e", script],
env: bunEnv,
stdout: "pipe",
stderr: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
const delta = Number(stdout);
expect({ stderr, exitCode, delta }).toEqual({ stderr: expect.any(String), exitCode: 0, delta: expect.any(Number) });
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
expect(Number.isFinite(delta)).toBe(true);
return delta;
}

// Each body has one 8 MB field value, parsed into a native WTF::String entry
// the FormData owns. After the fix the GC sees those bytes and they survive a
// collection while the FormData is referenced. Without the fix the delta is
// near zero. A few large entries keep the debug+ASAN parse fast.
const valueSize = 8 * 1024 * 1024;
const count = 2;

test("urlencoded entries report their bytes", async () => {
const buildBody = `() => "a=" + Buffer.alloc(${valueSize}, "x").toString()`;
const delta = await extraMemoryDelta(buildBody, "application/x-www-form-urlencoded", count);
expect(delta).toBeGreaterThan(count * valueSize * 0.5);
});

test("multipart string fields report their bytes", async () => {
const buildBody = `() => {
const value = Buffer.alloc(${valueSize}, "x").toString();
return "--X\\r\\nContent-Disposition: form-data; name=\\"a\\"\\r\\n\\r\\n" + value + "\\r\\n--X--\\r\\n";
}`;
const delta = await extraMemoryDelta(buildBody, "multipart/form-data; boundary=X", count);
expect(delta).toBeGreaterThan(count * valueSize * 0.5);
});
});
Loading