Skip to content
Open
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
20 changes: 20 additions & 0 deletions src/node_buffer.cc
Original file line number Diff line number Diff line change
Expand Up @@ -768,6 +768,12 @@ void Fill(const FunctionCallbackInfo<Value>& args) {
}
}

// 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) {
Expand Down Expand Up @@ -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);

Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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,
Expand Down
3 changes: 2 additions & 1 deletion src/util.h
Original file line number Diff line number Diff line change
Expand Up @@ -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::ArrayBuffer> name##_buffer = name->Buffer(); \
char* const name##_data = \
static_cast<char*>(name->Buffer()->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
Expand Down
91 changes: 91 additions & 0 deletions test/parallel/test-buffer-write-immutable.js
Original file line number Diff line number Diff line change
@@ -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);
}
}
Loading