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
94 changes: 49 additions & 45 deletions src/node_buffer.cc
Original file line number Diff line number Diff line change
Expand Up @@ -1776,12 +1776,24 @@ static void SetDetachKey(const FunctionCallbackInfo<Value>& args) {
ab->SetDetachKey(key);
}

// Converts a number parameter to size_t suitable for ArrayBuffer sizes
// Could be larger than uint32_t
// See v8::internal::TryNumberToSize and v8::internal::NumberToSize
inline size_t CheckNumberToSize(Local<Value> number) {
CHECK(number->IsNumber());
double value = number.As<Number>()->Value();
// See v8::internal::TryNumberToSize on this (and on < comparison)
double maxSize = static_cast<double>(std::numeric_limits<size_t>::max());
CHECK(value >= 0 && value < maxSize);
return static_cast<size_t>(value);
}

void CopyArrayBufferImpl(Local<ArrayBuffer> target,
uint32_t target_start,
size_t target_start,
Local<ArrayBuffer> source,
uint32_t source_start,
uint32_t bytes_to_copy) {
uint32_t bytes_copied = source->CopyArrayBufferBytes(
size_t source_start,
size_t bytes_to_copy) {
size_t bytes_copied = source->CopyArrayBufferBytes(
source_start, bytes_to_copy, target, target_start);
CHECK_EQ(bytes_copied, bytes_to_copy);
}
Expand All @@ -1794,48 +1806,37 @@ void CopyArrayBuffer(const FunctionCallbackInfo<Value>& args) {
// args[4] == bytesToCopy

CHECK(args[0]->IsArrayBuffer());
CHECK(args[1]->IsUint32());
CHECK(args[1]->IsNumber());
CHECK(args[2]->IsArrayBuffer());
CHECK(args[3]->IsUint32());
CHECK(args[4]->IsUint32());
CHECK(args[3]->IsNumber());
CHECK(args[4]->IsNumber());

// Offsets and lengths can exceed uint32 for ArrayBuffers larger than 4 GiB.
CopyArrayBufferImpl(args[0].As<ArrayBuffer>(),
args[1].As<Uint32>()->Value(),
CheckNumberToSize(args[1]),
args[2].As<ArrayBuffer>(),
args[3].As<Uint32>()->Value(),
args[4].As<Uint32>()->Value());
CheckNumberToSize(args[3]),
CheckNumberToSize(args[4]));
}

void FastCopyArrayBuffer(Local<Value> receiver,
Local<Value> target,
uint32_t target_start,
double target_start,
Local<Value> source,
uint32_t source_start,
uint32_t bytes_to_copy) {
double source_start,
double bytes_to_copy) {
CHECK(target->IsArrayBuffer());
CHECK(source->IsArrayBuffer());

CopyArrayBufferImpl(target.As<ArrayBuffer>(),
target_start,
static_cast<size_t>(target_start),
source.As<ArrayBuffer>(),
source_start,
bytes_to_copy);
static_cast<size_t>(source_start),
static_cast<size_t>(bytes_to_copy));
}

static CFunction fast_copy_array_buffer(CFunction::Make(FastCopyArrayBuffer));

// Converts a number parameter to size_t suitable for ArrayBuffer sizes
// Could be larger than uint32_t
// See v8::internal::TryNumberToSize and v8::internal::NumberToSize
inline size_t CheckNumberToSize(Local<Value> number) {
CHECK(number->IsNumber());
double value = number.As<Number>()->Value();
// See v8::internal::TryNumberToSize on this (and on < comparison)
double maxSize = static_cast<double>(std::numeric_limits<size_t>::max());
CHECK(value >= 0 && value < maxSize);
return static_cast<size_t>(value);
}

// Allocates an ArrayBuffer of `size` bytes. Its contents are left
// uninitialized, unless zero-filling is required.
MaybeLocal<ArrayBuffer> AllocateUnsafeArrayBuffer(Environment* env,
Expand Down Expand Up @@ -1917,10 +1918,10 @@ void ArrayBufferAlignedOffset(const FunctionCallbackInfo<Value>& args) {
}

template <encoding encoding>
uint32_t WriteOneByteString(const char* src,
uint32_t src_len,
char* dst,
uint32_t dst_len) {
size_t WriteOneByteString(const char* src,
size_t src_len,
char* dst,
size_t dst_len) {
if (dst_len == 0) {
return 0;
}
Expand Down Expand Up @@ -1967,7 +1968,7 @@ void SlowWriteString(const FunctionCallbackInfo<Value>& args) {

if (max_length == 0) return args.GetReturnValue().Set(0);

uint32_t written = 0;
size_t written = 0;

if ((encoding == UTF8 || encoding == LATIN1 || encoding == ASCII) &&
str->IsExternalOneByte()) {
Expand All @@ -1983,13 +1984,16 @@ void SlowWriteString(const FunctionCallbackInfo<Value>& args) {
}

template <encoding encoding>
uint32_t FastWriteString(Local<Value> receiver,
Local<Value> dst_obj,
const FastOneByteString& src,
uint32_t offset,
uint32_t max_length,
// NOLINTNEXTLINE(runtime/references)
FastApiCallbackOptions& options) {
double FastWriteString(Local<Value> receiver,
Local<Value> dst_obj,
const FastOneByteString& src,
// Offsets and lengths can exceed uint32 for buffers
// larger than 4 GiB, so they are passed as doubles
// (exact for integers < 2^53).
double offset,
double max_length,
// NOLINTNEXTLINE(runtime/references)
FastApiCallbackOptions& options) {
// Just a heads up... this is a v8 fast api function. The use of
// FastOneByteString has some caveats. Specifically, a GC occurring
// between the time the FastOneByteString is created and the time
Expand All @@ -2000,15 +2004,15 @@ uint32_t FastWriteString(Local<Value> receiver,
// modifying this code to ensure that no operations would trigger a GC.
HandleScope handle_scope(options.isolate);
SPREAD_BUFFER_ARG(dst_obj, dst);
CHECK(offset <= dst_length);
CHECK(dst_length - offset <= std::numeric_limits<uint32_t>::max());
const size_t start = static_cast<size_t>(offset);
CHECK(start <= dst_length);
TRACK_V8_FAST_API_CALL("buffer.writeString");

return WriteOneByteString<encoding>(
return static_cast<double>(WriteOneByteString<encoding>(
src.data,
src.length,
reinterpret_cast<char*>(dst_data + offset),
std::min<uint32_t>(dst_length - offset, max_length));
reinterpret_cast<char*>(dst_data + start),
std::min(dst_length - start, static_cast<size_t>(max_length))));
}

static const CFunction fast_write_string_ascii(
Expand Down
42 changes: 42 additions & 0 deletions test/pummel/test-buffer-large-size-write-string.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
'use strict';
const common = require('../common');

// Regression test for the string-write fast API with Buffers larger than
// 4 GiB. Offsets and lengths were passed to the fast call as uint32_t, which
// wrapped them, and a CHECK then aborted the process.
common.skipIf32Bits();

const assert = require('node:assert');

const size = 2 ** 32 + 4096;

let buf;
try {
buf = Buffer.alloc(size);
} catch (e) {
if (
e.code === 'ERR_MEMORY_ALLOCATION_FAILED' ||
/Array buffer allocation failed/.test(e.message)
) {
common.skip('insufficient memory for Buffer.alloc');
}
throw e;
}

// Run enough iterations for V8 to tier up and call the fast API function.
const hot = 200_000;
for (const encoding of ['utf8', 'latin1', 'ascii']) {
// More than 4 GiB remain after the offset.
for (let i = 0; i < hot; i++) {
assert.strictEqual(buf.write('abc', 0, encoding), 3);
}
assert.strictEqual(buf.toString('latin1', 0, 3), 'abc');

// The offset itself is larger than 4 GiB. A wrapped offset would write at
// index 32 instead.
for (let i = 0; i < hot; i++) {
assert.strictEqual(buf.write('xyz', 2 ** 32 + 32, encoding), 3);
}
assert.strictEqual(buf.toString('latin1', 2 ** 32 + 32, 2 ** 32 + 35), 'xyz');
assert.strictEqual(buf.toString('latin1', 32, 35), '\0\0\0');
}
40 changes: 40 additions & 0 deletions test/pummel/test-webstream-byob-large-offset.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
'use strict';
const common = require('../common');

// Regression test for ReadableStream BYOB reads into a view whose offset into
// the underlying ArrayBuffer is larger than 4 GiB. The offset was passed to
// the native copy as a uint32_t and failed a CHECK.
common.skipIf32Bits();

const assert = require('node:assert');
const { ReadableStream } = require('node:stream/web');

const offset = 2 ** 32 + 8;

let ab;
try {
ab = new ArrayBuffer(2 ** 32 + 64);
} catch (e) {
if (/Array buffer allocation failed/.test(e.message)) {
common.skip('insufficient memory for ArrayBuffer');
}
throw e;
}

const stream = new ReadableStream({
type: 'bytes',
start(controller) {
controller.enqueue(new Uint8Array([1, 2, 3, 4]));
controller.close();
},
});

(async () => {
const reader = stream.getReader({ mode: 'byob' });
const { value } = await reader.read(new Uint8Array(ab, offset, 16));
// The read transfers the buffer, so inspect the returned view.
assert.strictEqual(value.byteOffset, offset);
assert.strictEqual(value.length, 4);
assert.deepStrictEqual([...value], [1, 2, 3, 4]);
assert.strictEqual(value.buffer.byteLength, 2 ** 32 + 64);
})().then(common.mustCall());