Skip to content
Closed
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
17 changes: 12 additions & 5 deletions src/ffi/data.cc
Original file line number Diff line number Diff line change
Expand Up @@ -546,7 +546,6 @@ static bool ZeroCopyUnavailable(Environment* env) {

void ToBuffer(const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args);
Isolate* isolate = env->isolate();

THROW_IF_INSUFFICIENT_PERMISSIONS(env, permission::PermissionScope::kFFI, "");

Expand Down Expand Up @@ -589,8 +588,12 @@ void ToBuffer(const FunctionCallbackInfo<Value>& args) {
return;
}

bool copy = args.Length() < 3 || args[2]->IsUndefined() ||
args[2]->BooleanValue(isolate);
if (!args[2]->IsUndefined() && !args[2]->IsBoolean()) {
THROW_ERR_INVALID_ARG_TYPE(env, "The copy argument must be a boolean");
return;
}

bool copy = !args[2]->IsFalse();
if (!copy && ZeroCopyUnavailable(env)) return;

Local<Object> buf;
Expand Down Expand Up @@ -654,8 +657,12 @@ void ToArrayBuffer(const FunctionCallbackInfo<Value>& args) {
return;
}

bool copy = args.Length() < 3 || args[2]->IsUndefined() ||
args[2]->BooleanValue(isolate);
if (!args[2]->IsUndefined() && !args[2]->IsBoolean()) {
THROW_ERR_INVALID_ARG_TYPE(env, "The copy argument must be a boolean");
return;
}

bool copy = !args[2]->IsFalse();
if (!copy && ZeroCopyUnavailable(env)) return;

Local<ArrayBuffer> ab;
Expand Down
12 changes: 12 additions & 0 deletions test/ffi/test-ffi-memory.js
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,18 @@ test('ffi zero-copy views throw with the V8 sandbox', { skip: !common.hasV8Sandb
}));
});

test('ffi toBuffer and toArrayBuffer require a boolean copy argument', () => {
withAllocations(common.mustCall((alloc) => {
const ptr = alloc(4);
const type = { code: 'ERR_INVALID_ARG_TYPE' };

for (const copy of [null, 0, '', 'false', 1, {}]) {
assert.throws(() => ffi.toBuffer(ptr, 4, copy), type);
assert.throws(() => ffi.toArrayBuffer(ptr, 4, copy), type);
}
}));
});

test('ffi getRawPointer returns raw addresses for byte sources', () => {
const buffer = Buffer.from([1, 2, 3]);
const arrayBuffer = new Uint8Array([4, 5, 6, 7]).buffer;
Expand Down
Loading