Commit 3a234fe20cb for nodejs
commit 3a234fe20cbecbb066e0f619fadda06290d477f7
Author: Ved Chaudhari <84765263+vedchaudhari@users.noreply.github.com>
Date: Sun Dec 6 21:05:10 2026 +0530
buffer: throw on write() to immutable buffers
buf.write() could change the bytes of a buffer backed by an
immutable ArrayBuffer. Throw ERR_INVALID_ARG_VALUE instead, like
other APIs already do.
Refs: https://github.com/nodejs/node/issues/66346
Signed-off-by: vedchaudhari <vedc2853@gmail.com>
PR-URL: https://github.com/nodejs/node/pull/67741
Reviewed-By: James M Snell <jasnell@gmail.com>
diff --git a/src/node_buffer.cc b/src/node_buffer.cc
index 6c2321d5f1b..79b69536aee 100644
--- a/src/node_buffer.cc
+++ b/src/node_buffer.cc
@@ -768,6 +768,12 @@ start_fill:
}
}
+// Kept out of line so the string write paths stay small.
+void COLD_NOINLINE ThrowImmutableWriteError(Isolate* isolate) {
+ THROW_ERR_INVALID_ARG_VALUE(
+ isolate,
+ "The argument 'buffer' must not be backed by an immutable ArrayBuffer");
+}
template <encoding encoding>
void StringWrite(const FunctionCallbackInfo<Value>& args) {
@@ -797,6 +803,10 @@ void StringWrite(const FunctionCallbackInfo<Value>& args) {
max_length = std::min(ts_obj_length - offset, max_length);
+ if (ts_obj_buffer->IsImmutable()) [[unlikely]] {
+ return ThrowImmutableWriteError(env->isolate());
+ }
+
if (max_length == 0)
return args.GetReturnValue().Set(0);
@@ -1965,6 +1975,10 @@ void SlowWriteString(const FunctionCallbackInfo<Value>& args) {
max_length = std::min(ts_obj_length - offset, max_length);
+ if (ts_obj_buffer->IsImmutable()) [[unlikely]] {
+ return ThrowImmutableWriteError(env->isolate());
+ }
+
if (max_length == 0) return args.GetReturnValue().Set(0);
uint32_t written = 0;
@@ -2004,6 +2018,12 @@ uint32_t FastWriteString(Local<Value> receiver,
CHECK(dst_length - offset <= std::numeric_limits<uint32_t>::max());
TRACK_V8_FAST_API_CALL("buffer.writeString");
+ // Throw before `src` is read, as creating the error may trigger a GC.
+ if (dst_buffer->IsImmutable()) [[unlikely]] {
+ ThrowImmutableWriteError(options.isolate);
+ return 0;
+ }
+
return WriteOneByteString<encoding>(
src.data,
src.length,
diff --git a/src/util.h b/src/util.h
index 15dc1dcaebd..4e6d3c78d7e 100644
--- a/src/util.h
+++ b/src/util.h
@@ -694,8 +694,9 @@ class BufferValue : public MaybeStackBuffer<char> {
v8::Local<v8::ArrayBufferView> name = (val).As<v8::ArrayBufferView>(); \
const size_t name##_offset = name->ByteOffset(); \
const size_t name##_length = name->ByteLength(); \
+ v8::Local<v8::ArrayBufferBase> name##_buffer = name->GetBuffer(); \
char* const name##_data = \
- static_cast<char*>(name->GetBuffer()->Data()) + name##_offset; \
+ static_cast<char*>(name##_buffer->Data()) + name##_offset; \
if (name##_length > 0) CHECK_NE(name##_data, nullptr);
// Use this when a variable or parameter is unused in order to explicitly
diff --git a/test/parallel/test-buffer-write-immutable.js b/test/parallel/test-buffer-write-immutable.js
new file mode 100644
index 00000000000..561038ce598
--- /dev/null
+++ b/test/parallel/test-buffer-write-immutable.js
@@ -0,0 +1,91 @@
+// Flags: --js-immutable-arraybuffer --expose-internals --allow-natives-syntax --no-warnings
+'use strict';
+
+const common = require('../common');
+const assert = require('assert');
+const { internalBinding } = require('internal/test/binding');
+const { utf8Write } = require('internal/buffer');
+
+if (typeof ArrayBuffer.prototype.transferToImmutable !== 'function')
+ common.skip('ArrayBuffer.prototype.transferToImmutable is not available');
+
+const immutableError = {
+ code: 'ERR_INVALID_ARG_VALUE',
+ name: 'TypeError',
+ message: "The argument 'buffer' must not be backed by an immutable ArrayBuffer",
+};
+
+function immutable(bytes) {
+ return Buffer.from(Uint8Array.from(bytes).buffer.transferToImmutable());
+}
+
+const bytes = [1, 2, 3, 4, 5, 6, 7, 8];
+
+// Writing into an immutable buffer throws and leaves the bytes unchanged.
+for (const [string, encoding] of [
+ ['ab', 'utf8'],
+ ['ab', 'latin1'],
+ ['ab', 'ascii'],
+ ['ab', 'ucs2'],
+ ['abcd', 'hex'],
+ ['YWI=', 'base64'],
+ ['YWI', 'base64url'],
+]) {
+ const buf = immutable(bytes);
+ assert.throws(() => buf.write(string, encoding), immutableError);
+ assert.throws(() => buf.write(string, 2, encoding), immutableError);
+ assert.throws(() => buf[`${encoding}Write`](string), immutableError);
+ assert.deepStrictEqual([...buf], bytes);
+}
+
+// Views into part of an immutable buffer are rejected too.
+{
+ const ab = Uint8Array.from(bytes).buffer.transferToImmutable();
+ const view = Buffer.from(ab, 2, 4);
+ assert.throws(() => view.write('ab'), immutableError);
+ assert.deepStrictEqual([...new Uint8Array(ab)], bytes);
+}
+
+// Like TypedArray methods, a write of zero bytes is rejected as well.
+{
+ const buf = immutable(bytes);
+ assert.throws(() => buf.write(''), immutableError);
+ assert.throws(() => buf.write('ab', 8), immutableError);
+}
+
+// Invalid arguments are reported before the immutable backing store.
+{
+ const buf = immutable(bytes);
+ assert.throws(() => buf.write(1), { code: 'ERR_INVALID_ARG_TYPE' });
+ assert.throws(() => buf.write(1, 'hex'), { code: 'ERR_INVALID_ARG_TYPE' });
+ assert.throws(() => buf.write('ab', 9), { code: 'ERR_OUT_OF_RANGE' });
+ assert.throws(() => buf.write('ab', 'nope'), { code: 'ERR_UNKNOWN_ENCODING' });
+ assert.throws(() => buf.hexWrite('ab', 9),
+ { code: 'ERR_BUFFER_OUT_OF_BOUNDS' });
+ assert.deepStrictEqual([...buf], bytes);
+}
+
+// Mutable buffers are unaffected.
+{
+ const buf = Buffer.from(bytes);
+ assert.strictEqual(buf.write('ab'), 2);
+ assert.deepStrictEqual([...buf.subarray(0, 2)], [0x61, 0x62]);
+}
+
+// The optimized fast path rejects immutable buffers before writing.
+{
+ const buf = immutable(bytes);
+ function write(target) {
+ return utf8Write(target, 'ab', 0, 2);
+ }
+ eval('%PrepareFunctionForOptimization(utf8Write)');
+ utf8Write(Buffer.alloc(8), 'ab', 0, 2);
+ eval('%OptimizeFunctionOnNextCall(utf8Write)');
+ assert.throws(() => write(buf), immutableError);
+ assert.deepStrictEqual([...buf], bytes);
+
+ if (common.isDebug) {
+ const { getV8FastApiCallCount } = internalBinding('debug');
+ assert.strictEqual(getV8FastApiCallCount('buffer.writeString'), 1);
+ }
+}