Commit 31e9dc0eb25 for nodejs
commit 31e9dc0eb2526df195c1dd983810380d1df9b218
Author: Guilherme Araújo <arauujogui@gmail.com>
Date: Sun Dec 6 10:51:24 2026 -0300
src: retain buffer memory for pending writes
`StreamBase::WriteBuffer()` and `StreamBase::Writev()` pass raw
pointers into Buffer memory to the stream. Nothing kept that memory
alive while the write was pending, so detaching the ArrayBuffer (e.g.
with `transfer()` or `postMessage()`) freed it, and the stream sent
whatever reused the memory to the peer.
Keep the backing store of each Buffer chunk in the `WriteWrap` until
the write completes.
Assisted-by: Claude Code
Signed-off-by: Guilherme Araújo <arauujogui@gmail.com>
PR-URL: https://github.com/nodejs/node/pull/67907
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Anna Henningsen <anna@addaleax.net>
diff --git a/src/stream_base-inl.h b/src/stream_base-inl.h
index cc468ee566a..6621b4739e1 100644
--- a/src/stream_base-inl.h
+++ b/src/stream_base-inl.h
@@ -5,6 +5,7 @@
#include "async_wrap-inl.h"
#include "base_object-inl.h"
+#include "memory_tracker-inl.h"
#include "node.h"
#include "stream_base.h"
#include "v8.h"
@@ -154,6 +155,25 @@ void WriteWrap::SetBackingStore(std::unique_ptr<v8::BackingStore> bs) {
backing_store_ = std::move(bs);
}
+void WriteWrap::RetainBackingStore(std::shared_ptr<v8::BackingStore> bs) {
+ if (bs) retained_backing_stores_.push_back(std::move(bs));
+}
+
+void WriteWrap::ReserveRetainedBackingStores(size_t count) {
+ retained_backing_stores_.reserve(count);
+}
+
+void WriteWrap::TrackBackingStores(MemoryTracker* tracker) const {
+ tracker->TrackField("backing_store", backing_store_);
+ size_t retained_size = 0;
+ for (const auto& bs : retained_backing_stores_)
+ retained_size += bs->ByteLength();
+ if (retained_size > 0) {
+ tracker->TrackFieldWithSize(
+ "retained_backing_stores", retained_size, "BackingStore");
+ }
+}
+
void StreamReq::ResetObject(v8::Local<v8::Object> obj) {
DCHECK_GT(obj->InternalFieldCount(), StreamReq::kStreamReqField);
diff --git a/src/stream_base.cc b/src/stream_base.cc
index e2f2d724834..32e595665e6 100644
--- a/src/stream_base.cc
+++ b/src/stream_base.cc
@@ -19,6 +19,7 @@ namespace node {
using v8::Array;
using v8::ArrayBuffer;
+using v8::ArrayBufferBase;
using v8::ArrayBufferView;
using v8::BackingStore;
using v8::BackingStoreInitializationMode;
@@ -34,6 +35,7 @@ using v8::HandleScope;
using v8::Integer;
using v8::Isolate;
using v8::Local;
+using v8::LocalVector;
using v8::MaybeLocal;
using v8::Object;
using v8::PropertyAttribute;
@@ -252,6 +254,13 @@ int StreamBase::Writev(const FunctionCallbackInfo<Value>& args) {
count = chunks->Length() >> 1;
MaybeStackBuffer<uv_buf_t, 16> bufs(count);
+ // ArrayBuffers that `bufs` points into, collected before dispatch.
+ LocalVector<ArrayBufferBase> array_buffers(isolate);
+ auto add_array_buffer = [&](Local<Value> chunk) {
+ Local<ArrayBufferBase> ab = chunk.As<ArrayBufferView>()->GetBuffer();
+ if (array_buffers.empty() || array_buffers.back() != ab)
+ array_buffers.push_back(ab);
+ };
size_t storage_size = 0;
size_t offset;
@@ -295,6 +304,7 @@ int StreamBase::Writev(const FunctionCallbackInfo<Value>& args) {
return -1;
bufs[i].base = Buffer::Data(chunk);
bufs[i].len = Buffer::Length(chunk);
+ add_array_buffer(chunk);
}
}
@@ -315,6 +325,7 @@ int StreamBase::Writev(const FunctionCallbackInfo<Value>& args) {
if (Buffer::HasInstance(chunk)) {
bufs[i].base = Buffer::Data(chunk);
bufs[i].len = Buffer::Length(chunk);
+ add_array_buffer(chunk);
continue;
}
@@ -340,8 +351,12 @@ int StreamBase::Writev(const FunctionCallbackInfo<Value>& args) {
}
StreamWriteResult res = Write(*bufs, count, nullptr, req_wrap_obj);
- if (res.wrap != nullptr && storage_size > 0)
- res.wrap->SetBackingStore(std::move(bs));
+ if (res.wrap != nullptr) {
+ if (storage_size > 0) res.wrap->SetBackingStore(std::move(bs));
+ res.wrap->ReserveRetainedBackingStores(array_buffers.size());
+ for (Local<ArrayBufferBase> ab : array_buffers)
+ res.wrap->RetainBackingStore(ab->GetBackingStore());
+ }
return FinishWrite(args, res, lazy_req);
}
@@ -396,6 +411,10 @@ int StreamBase::WriteBuffer(const FunctionCallbackInfo<Value>& args) {
}
StreamWriteResult res = Write(&buf, 1, send_handle, req_wrap_obj);
+ if (res.wrap != nullptr) {
+ res.wrap->RetainBackingStore(
+ args[1].As<ArrayBufferView>()->GetBuffer()->GetBackingStore());
+ }
return FinishWrite(args, res, lazy_req);
}
diff --git a/src/stream_base.h b/src/stream_base.h
index a46348c26df..07d80afa9e2 100644
--- a/src/stream_base.h
+++ b/src/stream_base.h
@@ -12,6 +12,7 @@
#include <climits> // INT_MIN
#include <memory>
+#include <vector>
namespace node {
@@ -95,6 +96,10 @@ class ShutdownWrap : public StreamReq {
class WriteWrap : public StreamReq {
public:
inline void SetBackingStore(std::unique_ptr<v8::BackingStore> bs);
+ // Keeps `bs` alive until the write completes, even if it gets detached.
+ inline void RetainBackingStore(std::shared_ptr<v8::BackingStore> bs);
+ inline void ReserveRetainedBackingStores(size_t count);
+ inline void TrackBackingStores(MemoryTracker* tracker) const;
inline WriteWrap(
StreamBase* stream,
@@ -110,6 +115,7 @@ class WriteWrap : public StreamReq {
private:
std::unique_ptr<v8::BackingStore> backing_store_;
+ std::vector<std::shared_ptr<v8::BackingStore>> retained_backing_stores_;
};
@@ -490,7 +496,9 @@ class SimpleWriteWrap : public WriteWrap, public OtherBase {
AsyncWrap* GetAsyncWrap() override { return this; }
- SET_NO_MEMORY_INFO()
+ void MemoryInfo(MemoryTracker* tracker) const override {
+ WriteWrap::TrackBackingStores(tracker);
+ }
SET_MEMORY_INFO_NAME(SimpleWriteWrap)
SET_SELF_SIZE(SimpleWriteWrap)
diff --git a/test/parallel/test-net-write-buffer-detached.js b/test/parallel/test-net-write-buffer-detached.js
new file mode 100644
index 00000000000..26db9642731
--- /dev/null
+++ b/test/parallel/test-net-write-buffer-detached.js
@@ -0,0 +1,96 @@
+'use strict';
+
+// A pending write must survive its buffers being detached.
+
+const common = require('../common');
+const assert = require('node:assert');
+const net = require('node:net');
+
+const total = 16 * 1024 * 1024;
+
+function detachAndReuse(buffers) {
+ // Detach and let other allocations reuse the memory.
+ const others = [];
+ for (const buf of buffers) {
+ const { byteLength } = buf.buffer;
+ buf.buffer.transfer(1);
+ others.push(Buffer.allocUnsafeSlow(byteLength).fill('b'));
+ others.push(Buffer.allocUnsafeSlow(byteLength).fill('b'));
+ }
+ return others;
+}
+
+function test(write, length) {
+ const { promise, resolve } = Promise.withResolvers();
+ let expected = 0;
+ const server = net.createServer(common.mustCall((socket) => {
+ // Windows can flush a write of any size synchronously.
+ let buffers;
+ do {
+ buffers = write(socket);
+ expected += length;
+ } while (socket.writableLength === 0);
+ assert.strictEqual(socket.writableLength, length);
+ const others = detachAndReuse(buffers);
+ socket.end();
+ socket.on('close', common.mustCall(() => {
+ assert.strictEqual(others.length, buffers.length * 2);
+ server.close(resolve);
+ }));
+ }));
+
+ server.listen(0, common.mustCall(() => {
+ const client = net.connect(server.address().port);
+ let received = 0;
+ client.on('data', common.mustCallAtLeast((chunk) => {
+ received += chunk.length;
+ assert.strictEqual(chunk.indexOf('b'), -1);
+ }));
+ client.on('end', common.mustCall(() => {
+ assert.strictEqual(received, expected);
+ }));
+ }));
+ return promise;
+}
+
+function alloc(count) {
+ const buffers = [];
+ for (let i = 0; i < count; i++)
+ buffers.push(Buffer.allocUnsafeSlow(total / count).fill('a'));
+ return buffers;
+}
+
+(async () => {
+ await test((socket) => {
+ const buffers = alloc(1);
+ socket.write(buffers[0]);
+ return buffers;
+ }, total);
+
+ // writev(), buffers only.
+ await test((socket) => {
+ const buffers = alloc(4);
+ const half = buffers[0].length / 2;
+ socket.cork();
+ socket.write(buffers[0].subarray(0, half));
+ socket.write(buffers[0].subarray(half));
+ for (let i = 1; i < buffers.length; i++)
+ socket.write(buffers[i]);
+ socket.uncork();
+ return buffers;
+ }, total);
+
+ // writev(), buffers and strings.
+ const string = 'a'.repeat(1024);
+ await test((socket) => {
+ const buffers = alloc(4);
+ socket.cork();
+ socket.write(string);
+ for (const buf of buffers) {
+ socket.write(buf);
+ socket.write(string, 'latin1');
+ }
+ socket.uncork();
+ return buffers;
+ }, total + string.length * 5);
+})().then(common.mustCall());