Skip to content
Closed
Show file tree
Hide file tree
Changes from 8 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
6 changes: 6 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,9 @@ impl DOMFormData {
pub fn count(&mut self) -> usize {
WebCore__DOMFormData__count(self)
}

/// Report the wrapper's native byte cost to the GC after native appends.
pub fn report_memory_cost(value: JSValue) {
WebCore__DOMFormData__reportMemoryCost(value);
}
}
20 changes: 14 additions & 6 deletions src/jsc/bindings/DOMFormData.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -192,16 +192,24 @@ std::optional<KeyValuePair<String, DOMFormData::FormDataEntryValue>> DOMFormData
return makeKeyValuePair(item.name, item.data);
}

size_t DOMFormData::reportableMemoryCost() const
{
size_t cost = m_items.capacity() * sizeof(Item);
for (auto& item : m_items) {
cost += stringMemoryCost(item.name);
if (auto value = std::get_if<String>(&item.data))
cost += stringMemoryCost(*value);
}

return cost;
}

size_t DOMFormData::memoryCost() const
{
size_t cost = m_items.sizeInBytes();
size_t cost = reportableMemoryCost();
for (auto& item : m_items) {
cost += item.name.sizeInBytes();
if (auto value = std::get_if<RefPtr<Blob>>(&item.data)) {
if (auto value = std::get_if<RefPtr<Blob>>(&item.data))
cost += value->get()->memoryCost();
} else if (auto value = std::get_if<String>(&item.data)) {
cost += value->sizeInBytes();
}
}

return cost;
Expand Down
8 changes: 7 additions & 1 deletion src/jsc/bindings/DOMFormData.h
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,13 @@ class DOMFormData : public RefCounted<DOMFormData>, public ContextDestructionObs
void set(const String& name, RefPtr<Blob>, const String& filename = {});

size_t count() const { return m_items.size(); }
size_t memoryCost() const;
size_t memoryCost() const; // every entry, for heap snapshots
size_t reportableMemoryCost() const; // excludes Blob stores, which their JSBlob wrapper reports
static size_t stringMemoryCost(const String& string)
{
auto* impl = string.impl();
return impl ? impl->sizeInBytes() : 0;
}

String toURLEncodedString();

Expand Down
11 changes: 10 additions & 1 deletion src/jsc/bindings/bindings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6344,7 +6344,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().reportableMemoryCost();
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
65 changes: 65 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,68 @@ describe("USVString conversion of lone surrogates", () => {
expect(formData.get("\uFFFD")).toBeNull();
});
});

// A 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 a server that parses one body
// per request accumulates native memory until the idle collector runs.
describe.concurrent("FormData native memory is reported to the GC", () => {
// `create` is the source of an async function that returns one FormData.
async function extraMemoryDelta(create: string, count: number): Promise<number> {
const script = `
import { heapStats } from "bun:jsc";
const create = ${create};

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

const live = [];
for (let i = 0; i < ${count}; i++) {
live.push(await create());
}

// Collect the transient inputs. 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).toBe("");
expect({ exitCode, delta }).toEqual({ exitCode: 0, delta: expect.any(Number) });
expect(Number.isFinite(delta)).toBe(true);
return delta;
}

// Each FormData holds one 8 MB field value as a native WTF::String. 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;
const value = `Buffer.alloc(${valueSize}, "x").toString()`;

test("urlencoded entries report their bytes", async () => {
const create = `async () => new Response("a=" + ${value}, {
headers: { "content-type": "application/x-www-form-urlencoded" },
}).formData()`;
expect(await extraMemoryDelta(create, count)).toBeGreaterThan(count * valueSize * 0.5);
});

test("multipart string fields report their bytes", async () => {
const create = `async () => new Response(
"--X\\r\\nContent-Disposition: form-data; name=\\"a\\"\\r\\n\\r\\n" + ${value} + "\\r\\n--X--\\r\\n",
{ headers: { "content-type": "multipart/form-data; boundary=X" } },
).formData()`;
expect(await extraMemoryDelta(create, count)).toBeGreaterThan(count * valueSize * 0.5);
});
});
Loading