Skip to content
Merged
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
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
11 changes: 11 additions & 0 deletions test/ffi/test-ffi-memory.js
Original file line number Diff line number Diff line change
Expand Up @@ -371,6 +371,17 @@ 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') ||
(common.isAIX && 'huge allocations may succeed on AIX and get the process killed'),
}, () => {
// 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
Loading