Skip to content
Closed
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
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);
}
}
24 changes: 17 additions & 7 deletions src/jsc/bindings/DOMFormData.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,9 @@ Ref<DOMFormData> DOMFormData::create(ScriptExecutionContext* context)
Ref<DOMFormData> DOMFormData::create(ScriptExecutionContext* context, const StringView& urlEncodedString)
{
auto newFormData = adoptRef(*new DOMFormData(context));
for (auto& entry : WTF::URLParser::parseURLEncodedForm(urlEncodedString)) {
auto form = WTF::URLParser::parseURLEncodedForm(urlEncodedString);
newFormData->m_items.reserveInitialCapacity(form.size());
for (auto& entry : form) {
newFormData->append(entry.key, entry.value);
}

Expand Down Expand Up @@ -192,16 +194,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
5 changes: 4 additions & 1 deletion src/jsc/bindings/bindings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6344,7 +6344,10 @@ 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 JSC::EncodedJSValue WebCore__DOMFormData__create(JSC::JSGlobalObject* arg0)
Expand Down
27 changes: 27 additions & 0 deletions src/jsc/bindings/webcore/JSDOMFormData.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,22 @@ 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));
}
}

extern "C" void WebCore__DOMFormData__reportMemoryCost(JSC::EncodedJSValue value)
{
if (auto* wrapper = dynamicDowncast<JSDOMFormData>(JSC::JSValue::decode(value)))
wrapper->computeMemoryCost();
}

JSObject* JSDOMFormData::createPrototype(VM& vm, JSDOMGlobalObject& globalObject)
{
auto* structure = JSDOMFormDataPrototype::createStructure(vm, &globalObject, globalObject.objectPrototype());
Expand Down Expand Up @@ -725,4 +741,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
13 changes: 8 additions & 5 deletions src/runtime/webcore/FormData.rs
Original file line number Diff line number Diff line change
Expand Up @@ -226,13 +226,16 @@ pub(crate) fn to_js_from_multipart_data(
}
}

{
let result = {
let mut wrap = Wrapper { global, form };
for_each_multipart_entry(input, boundary, &mut wrap, Wrapper::on_entry)
};

if let Err(e) = for_each_multipart_entry(input, boundary, &mut wrap, Wrapper::on_entry) {
scoped_log!(FormData, "failed to parse multipart data");
return Err(e);
}
// A failed parse leaves the parts it already copied in the wrapper.
DOMFormData::report_memory_cost(form_data_value);
if let Err(e) = result {
scoped_log!(FormData, "failed to parse multipart data");
return Err(e);
}

Ok(form_data_value)
Expand Down
97 changes: 97 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,100 @@ 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", () => {
async function runAndReadNumber(script: string): Promise<number> {
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 value = Number(stdout);
expect(stderr).toBe("");
expect({ exitCode, value }).toEqual({ exitCode: 0, value: expect.any(Number) });
expect(Number.isFinite(value)).toBe(true);
return value;
}

// `create` is the source of an async function that returns one FormData.
function extraMemoryDelta(create: string, count: number): Promise<number> {
return runAndReadNumber(`
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");
`);
}

// 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);
});

test("a failed multipart parse reports the parts it already copied", async () => {
// The first part is copied into the native FormData. The second part has no
// header terminator, so the parse then fails and the FormData is garbage.
// Nothing else in the loop allocates, so only the reported bytes can make
// the GC run and collect those FormData objects before the loop ends.
const parses = 64;
const alive = await runAndReadNumber(`
import { heapStats } from "bun:jsc";
const headers = { "content-type": "multipart/form-data; boundary=X" };
const body = new Blob([
"--X\\r\\nContent-Disposition: form-data; name=\\"a\\"\\r\\n\\r\\n" +
Buffer.alloc(4 * 1024 * 1024, "x").toString() +
"\\r\\n--X\\r\\nContent-Disposition: form-data; name=\\"b\\"\\r\\n--X--\\r\\n",
]);
Bun.gc(true);
// This message proves the parse reached the second part, after the copy.
const expected = "FormData parse error is missing header end";
let rejected = 0;
for (let i = 0; i < ${parses}; i++) {
await new Response(body, { headers }).formData().catch(e => {
if (e.message !== expected) throw e;
rejected++;
});
}
if (rejected !== ${parses}) throw new Error("expected every parse to fail, got " + rejected);
process.stdout.write(String(heapStats().objectTypeCounts.FormData ?? 0));
`);
expect(alive).toBeLessThan(parses / 2);
});
});
Loading