Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
ffi: throw on allocation failure in toArrayBuffer()
The copy path of toArrayBuffer() allocated its backing store with
V8's default failure mode, so a large length aborted the process
with a fatal out-of-memory error. toBuffer() throws a catchable
ERR_MEMORY_ALLOCATION_FAILED for the same input.

Allocate with kReturnNull and throw ERR_MEMORY_ALLOCATION_FAILED
when the allocation fails. The memory is left uninitialized because
memcpy() fills it right after.

Signed-off-by: Trivikram Kamat <16024985+trivikr@users.noreply.github.com>
Assisted-by: claude:opus-5.5
  • Loading branch information
trivikr committed Sep 30, 2026
commit 54907ac7ba97691fce83078635c465bbf465c855
13 changes: 11 additions & 2 deletions src/ffi/data.cc
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
using v8::ArrayBuffer;
using v8::ArrayBufferView;
using v8::BackingStore;
using v8::BackingStoreInitializationMode;
using v8::BackingStoreOnFailureMode;
using v8::BigInt;
using v8::FunctionCallbackInfo;
using v8::Integer;
Expand Down Expand Up @@ -670,8 +672,15 @@ void ToArrayBuffer(const FunctionCallbackInfo<Value>& args) {

Local<ArrayBuffer> ab;
if (copy) {
std::unique_ptr<BackingStore> store =
ArrayBuffer::NewBackingStore(isolate, len);
std::unique_ptr<BackingStore> store = ArrayBuffer::NewBackingStore(
isolate,
len,
BackingStoreInitializationMode::kUninitialized,
BackingStoreOnFailureMode::kReturnNull);
if (!store) [[unlikely]] {
THROW_ERR_MEMORY_ALLOCATION_FAILED(env);
return;
}
if (len > 0) memcpy(store->Data(), reinterpret_cast<void*>(ptr), len);
ab = ArrayBuffer::New(isolate, std::move(store));
} else {
Expand Down
10 changes: 10 additions & 0 deletions test/ffi/test-ffi-memory.js
Original file line number Diff line number Diff line change
Expand Up @@ -371,6 +371,16 @@ test('ffi rejects unsafe integers as an offset or length', () => {
}));
});

test('ffi toBuffer and toArrayBuffer throw when the copy cannot be allocated', {
skip: (bufferConstants.MAX_LENGTH < 2 ** 50 && 'requires a 64-bit buffer length limit') ||
(common.isASan && 'ASan aborts on huge allocations'),
}, () => {
// The allocation fails before the source pointer is read.
const error = { code: 'ERR_MEMORY_ALLOCATION_FAILED' };
assert.throws(() => ffi.toBuffer(1n, 2 ** 50), error);
assert.throws(() => ffi.toArrayBuffer(1n, 2 ** 50), error);
});

test('ffi memory helpers reject missing required arguments', () => {
const widths = ['Int8', 'Uint8', 'Int16', 'Uint16', 'Int32', 'Uint32',
'Int64', 'Uint64', 'Float32', 'Float64'];
Expand Down