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
11 changes: 10 additions & 1 deletion doc/api/ffi.md
Original file line number Diff line number Diff line change
Expand Up @@ -540,7 +540,16 @@ For 8-, 16-, and 32-bit integer types and for floating-point types, pass
JavaScript `number` values that match the declared type.

For 64-bit integer types (`int64` and `uint64`), pass JavaScript `bigint`
values.
values within the declared type's range or safe integer `number` values.
For `int64`, numbers must be between `Number.MIN_SAFE_INTEGER` and
`Number.MAX_SAFE_INTEGER`, inclusive. For `uint64`, numbers must be between
`0` and `Number.MAX_SAFE_INTEGER`, inclusive. This allows buffer lengths such
as `buffer.byteLength` to be passed without an explicit `BigInt()` conversion.
Use `bigint` for integers outside JavaScript's safe integer range.

Invalid arguments, including fractional numbers, `NaN`, infinities, and values
outside these ranges, throw `ERR_INVALID_ARG_VALUE`. Return values for 64-bit
integer types are always exposed as `bigint` values.

For pointer-like arguments:

Expand Down
17 changes: 15 additions & 2 deletions lib/internal/ffi-shared-buffer.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
'use strict';

const {
BigInt,
DataView,
DataViewPrototypeGetBigInt64,
DataViewPrototypeGetBigUint64,
Expand All @@ -23,6 +24,7 @@ const {
DataViewPrototypeSetUint32,
DataViewPrototypeSetUint8,
NumberIsInteger,
NumberIsSafeInteger,
ObjectDefineProperty,
ReflectApply,
TypeError,
Expand Down Expand Up @@ -132,14 +134,25 @@ function writeNumericArg(view, info, offset, arg, index) {
return;
}
if (kind === 'i64') {
if (typeof arg !== 'bigint' || arg < I64_MIN || arg > I64_MAX) {
if (typeof arg === 'number') {
if (!NumberIsSafeInteger(arg)) {
throwFFIArgError(`Argument ${index} must be ${info.label}`);
}
arg = BigInt(arg);
} else if (typeof arg !== 'bigint' || arg < I64_MIN || arg > I64_MAX) {
throwFFIArgError(`Argument ${index} must be ${info.label}`);
}
sI64(view, offset, arg, true);
return;
}

if (kind === 'u64') {
if (typeof arg !== 'bigint' || arg < 0n || arg > U64_MAX) {
if (typeof arg === 'number') {
if (!NumberIsSafeInteger(arg) || arg < 0) {
throwFFIArgError(`Argument ${index} must be ${info.label}`);
}
arg = BigInt(arg);
} else if (typeof arg !== 'bigint' || arg < 0n || arg > U64_MAX) {
throwFFIArgError(`Argument ${index} must be ${info.label}`);
}
sU64(view, offset, arg, true);
Expand Down
23 changes: 18 additions & 5 deletions lib/internal/ffi/fast-api.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@
const {
ArrayBufferPrototypeGetDetached,
ArrayPrototypeIncludes,
BigInt,
DataViewPrototypeGetBuffer,
NumberIsInteger,
NumberIsSafeInteger,
ObjectDefineProperty,
ReflectApply,
SafeWeakMap,
Expand Down Expand Up @@ -83,15 +85,26 @@ function throwFFIArgCountError(expected, actual) {
`Invalid argument count: expected ${expected}, got ${actual}`);
}

function validateFastIntegerArg(type, value, index) {
function validateAndConvertFastIntegerArg(type, value, index) {
const info = fastIntegerTypeInfo[type];
if (info === undefined) return;
if (info === undefined) return value;

// The native Fast API expects BigInt for 64-bit integer arguments.
if (info.kind === 'bigint' && typeof value === 'number') {
if (!NumberIsSafeInteger(value) || (info.min === 0n && value < 0)) {
throwFFIArgError(`Argument ${index} must be ${info.label}`);
}
return BigInt(value);
}

const validType = info.kind === 'number' ?
typeof value === 'number' && NumberIsInteger(value) :
typeof value === 'bigint';
if (!validType || value < info.min || value > info.max) {
throwFFIArgError(`Argument ${index} must be ${info.label}`);
}

return value;
}

function needsRawPointerConversion(type) {
Expand Down Expand Up @@ -223,7 +236,8 @@ function getFastArgumentIndexes(argumentsTypes) {
}

function convertFastArg(type, value, stringState, index) {
validateFastIntegerArg(type, value, index);
value = validateAndConvertFastIntegerArg(type, value, index);

return needsPointerConversion(type) ?
convertPointerArg(type, value, stringState, index) : value;
}
Expand Down Expand Up @@ -295,9 +309,8 @@ function wrapWithRawPointerConversions(rawFn, argumentTypes, owner) {
if (arguments.length !== 1) {
throwFFIArgCountError(1, arguments.length);
}
validateFastIntegerArg(t0, a0, 0);
let arg = validateAndConvertFastIntegerArg(t0, a0, 0);
validateFastPointerArg(t0, a0, 0);
let arg = a0;
if (needsNullPointerConversion(t0) &&
(arg === null || arg === undefined)) {
arg = 0n;
Expand Down
51 changes: 33 additions & 18 deletions src/ffi/types.cc
Original file line number Diff line number Diff line change
Expand Up @@ -648,28 +648,43 @@ Maybe<FFIArgumentCategory> ToFFIArgument(Environment* env,

*static_cast<uint32_t*>(ret) = arg->Uint32Value(context).FromJust();
} else if (type == &ffi_type_sint64) {
if (!arg->IsBigInt()) {
THROW_ERR_INVALID_ARG_VALUE(env, "Argument %u must be an int64", index);
return {};
}
if (arg->IsBigInt()) {
bool lossless;
int64_t value = arg.As<BigInt>()->Int64Value(&lossless);
if (!lossless) {
THROW_ERR_INVALID_ARG_VALUE(env, "Argument %u must be an int64", index);
return {};
}

bool lossless;
*static_cast<int64_t*>(ret) = arg.As<BigInt>()->Int64Value(&lossless);
if (!lossless) {
THROW_ERR_INVALID_ARG_VALUE(env, "Argument %u must be an int64", index);
return {};
*static_cast<int64_t*>(ret) = value;
} else {
int64_t value;
if (!GetStrictSignedInteger(
arg, -kMaxSafeJsInteger, kMaxSafeJsInteger, &value)) {
THROW_ERR_INVALID_ARG_VALUE(env, "Argument %u must be an int64", index);
return {};
}

*static_cast<int64_t*>(ret) = value;
}
} else if (type == &ffi_type_uint64) {
if (!arg->IsBigInt()) {
THROW_ERR_INVALID_ARG_VALUE(env, "Argument %u must be a uint64", index);
return {};
}
if (arg->IsBigInt()) {
bool lossless;
uint64_t value = arg.As<BigInt>()->Uint64Value(&lossless);
if (!lossless) {
THROW_ERR_INVALID_ARG_VALUE(env, "Argument %u must be a uint64", index);
return {};
}

bool lossless;
*static_cast<uint64_t*>(ret) = arg.As<BigInt>()->Uint64Value(&lossless);
if (!lossless) {
THROW_ERR_INVALID_ARG_VALUE(env, "Argument %u must be a uint64", index);
return {};
*static_cast<uint64_t*>(ret) = value;
} else {
uint64_t value;
if (!GetStrictUnsignedInteger(arg, kMaxSafeJsInteger, &value)) {
THROW_ERR_INVALID_ARG_VALUE(env, "Argument %u must be a uint64", index);
return {};
}

*static_cast<uint64_t*>(ret) = value;
}
} else if (type == &ffi_type_float) {
if (!arg->IsNumber()) {
Expand Down
24 changes: 24 additions & 0 deletions test/ffi/fixture_library/ffi_test_library.c
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,30 @@ FFI_EXPORT int32_t identity_i32(int32_t value) {
return value;
}

FFI_EXPORT int64_t identity_i64(int64_t value) {
return value;
}

FFI_EXPORT uint64_t identity_u64(uint64_t value) {
return value;
}

FFI_EXPORT int64_t identity_i64_fallback(void* pointer,
int64_t value,
void (*callback)(void)) {
(void)pointer;
(void)callback;
return value;
}

FFI_EXPORT uint64_t identity_u64_fallback(void* pointer,
uint64_t value,
void (*callback)(void)) {
(void)pointer;
(void)callback;
return value;
}

FFI_EXPORT char identity_char(char value) {
return value;
}
Expand Down
30 changes: 22 additions & 8 deletions test/ffi/test-ffi-calls.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ test('ffi calls support integer arithmetic and char semantics', () => {
assert.strictEqual(symbols.add_u32(0xFFFFFFFF, 1), 0);
assert.strictEqual(symbols.add_i64(20n, 22n), 42n);
assert.strictEqual(symbols.add_u64(20n, 22n), 42n);
assert.strictEqual(symbols.add_i64(20, 22), symbols.add_i64(20n, 22n));
assert.strictEqual(symbols.add_u64(20, 22), symbols.add_u64(20n, 22n));
assert.strictEqual(symbols.add_i64(-20, 22n), 2n);
assert.strictEqual(symbols.add_u64(20n, 22), 42n);

if (symbols.char_is_signed()) {
assert.strictEqual(symbols.identity_char(-1), -1);
Expand Down Expand Up @@ -104,15 +108,18 @@ test('ffi strings and buffers cross the boundary correctly', () => {
symbols.free_string(duplicated);

const buffer = Buffer.from([1, 2, 3, 4]);
assert.strictEqual(symbols.sum_buffer(buffer, BigInt(buffer.length)), 10n);
symbols.reverse_buffer(buffer, BigInt(buffer.length));
assert.strictEqual(
symbols.sum_buffer(buffer, buffer.length),
symbols.sum_buffer(buffer, BigInt(buffer.length)),
);
symbols.reverse_buffer(buffer, buffer.length);
assert.deepStrictEqual([...buffer], [4, 3, 2, 1]);

const typed = new Uint8Array([5, 6, 7, 8]);
assert.strictEqual(symbols.sum_buffer(typed, BigInt(typed.byteLength)), 26n);
assert.strictEqual(symbols.sum_buffer(typed, typed.byteLength), 26n);

const arrayBuffer = new Uint8Array([9, 10, 11, 12]).buffer;
assert.strictEqual(symbols.sum_buffer(arrayBuffer, BigInt(arrayBuffer.byteLength)), 42n);
assert.strictEqual(symbols.sum_buffer(arrayBuffer, arrayBuffer.byteLength), 42n);
} finally {
lib.close();
}
Expand Down Expand Up @@ -204,13 +211,20 @@ test('ffi validates invalid arguments', () => {
assert.throws(() => symbols.add_i16(40_000, 1), /Argument 0 must be an int16/);
assert.throws(() => symbols.add_u16(Number.NaN, 1), /Argument 0 must be a uint16/);
assert.throws(() => symbols.add_u16(70_000, 1), /Argument 0 must be a uint16/);
assert.throws(() => symbols.add_i64(1, 2n), /Argument 0 must be an int64/);
assert.throws(() => symbols.add_i64(1.5, 2n), /Argument 0 must be an int64/);
assert.throws(() => symbols.add_i64(1.5, 2), /Argument 0 must be an int64/);
assert.throws(() => symbols.add_i64(Number.NaN, 2), /Argument 0 must be an int64/);
assert.throws(() => symbols.add_i64(Number.POSITIVE_INFINITY, 2), /Argument 0 must be an int64/);
assert.throws(() => symbols.add_i64(Number.NEGATIVE_INFINITY, 2), /Argument 0 must be an int64/);
assert.throws(() => symbols.add_i64(Number.MAX_SAFE_INTEGER + 1, 2), /Argument 0 must be an int64/);
assert.throws(() => symbols.add_i64(Number.MIN_SAFE_INTEGER - 1, 2), /Argument 0 must be an int64/);
assert.throws(() => symbols.add_i64(2n ** 63n, 2n), /Argument 0 must be an int64/);
assert.throws(() => symbols.add_i64(-(2n ** 63n) - 1n, 2n), /Argument 0 must be an int64/);
assert.throws(() => symbols.add_u64('1', 2n), /Argument 0 must be a uint64/);
assert.throws(() => symbols.add_u64(1, 2n), /Argument 0 must be a uint64/);
assert.throws(() => symbols.add_u64(Number.NaN, 2n), /Argument 0 must be a uint64/);
assert.throws(() => symbols.add_u64(-1, 2), /Argument 0 must be a uint64/);
assert.throws(() => symbols.add_u64(1.5, 2), /Argument 0 must be a uint64/);
assert.throws(() => symbols.add_u64(Number.NaN, 2), /Argument 0 must be a uint64/);
assert.throws(() => symbols.add_u64(Number.POSITIVE_INFINITY, 2), /Argument 0 must be a uint64/);
assert.throws(() => symbols.add_u64(Number.MAX_SAFE_INTEGER + 1, 2), /Argument 0 must be a uint64/);
assert.throws(() => symbols.add_u64(-1n, 2n), /Argument 0 must be a uint64/);
assert.throws(() => symbols.add_u64(2n ** 64n, 2n), /Argument 0 must be a uint64/);
assert.throws(() => symbols.identity_pointer(-1n), /Argument 0 must be a non-negative pointer bigint/);
Expand Down
80 changes: 76 additions & 4 deletions test/ffi/test-ffi-fast-integer-validation.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,9 @@ test('fast FFI validates integer argument ranges', () => {

function callU32(value) { return functions.add_u32(value, 0); }

function callI64(value) { return functions.add_i64(value, 0n); }
function callI64(value) { return functions.add_i64(value, 0); }

function callU64(value) { return functions.add_u64(value, 0n); }
function callU64(value) { return functions.add_u64(value, 0); }

for (const [fn, value] of [
[callI8, 0],
Expand All @@ -43,8 +43,8 @@ test('fast FFI validates integer argument ranges', () => {
[callU16, 0],
[callI32, 0],
[callU32, 0],
[callI64, 0n],
[callU64, 0n],
[callI64, 0],
[callU64, 0],
]) {
optimize(fn, value);
}
Expand All @@ -62,6 +62,24 @@ test('fast FFI validates integer argument ranges', () => {
assert.throws(() => callU32(-1), expect);
assert.throws(() => callU32(1.5), expect);
assert.throws(() => callU32('1'), expect);
assert.strictEqual(callI64(Number.MAX_SAFE_INTEGER),
BigInt(Number.MAX_SAFE_INTEGER));
assert.strictEqual(callI64(Number.MIN_SAFE_INTEGER),
BigInt(Number.MIN_SAFE_INTEGER));
assert.strictEqual(callU64(Number.MAX_SAFE_INTEGER),
BigInt(Number.MAX_SAFE_INTEGER));
assert.strictEqual(callI64((2n ** 63n) - 1n), (2n ** 63n) - 1n);
assert.strictEqual(callU64((2n ** 64n) - 1n), (2n ** 64n) - 1n);
assert.throws(() => callI64(Number.MAX_SAFE_INTEGER + 1), expect);
assert.throws(() => callI64(Number.MIN_SAFE_INTEGER - 1), expect);
assert.throws(() => callI64(1.5), expect);
assert.throws(() => callI64(Number.NaN), expect);
assert.throws(() => callI64(Number.POSITIVE_INFINITY), expect);
assert.throws(() => callU64(-1), expect);
assert.throws(() => callU64(Number.MAX_SAFE_INTEGER + 1), expect);
assert.throws(() => callU64(1.5), expect);
assert.throws(() => callU64(Number.NaN), expect);
assert.throws(() => callU64(Number.POSITIVE_INFINITY), expect);
assert.throws(() => callI64(2n ** 63n), expect);
assert.throws(() => callU64(2n ** 64n), expect);
} finally {
Expand All @@ -70,6 +88,60 @@ test('fast FFI validates integer argument ranges', () => {
}
});

test('fast FFI converts single i64/u64 Number arguments before and after optimization', () => {
const { lib, functions } = ffi.dlopen(libraryPath, {
identity_i64: { return: 'int64', arguments: ['int64'] },
identity_u64: { return: 'uint64', arguments: ['uint64'] },
});

try {
// The native signature must have one argument to exercise the single-argument wrapper.
function callI64(value) { return functions.identity_i64(value); }

function callU64(value) { return functions.identity_u64(value); }

for (const optimized of [false, true]) {
if (optimized) {
optimize(callI64, -42);
optimize(callU64, 42);
}

for (const value of [0, -0, 42, Number.MAX_SAFE_INTEGER, 0n, 42n]) {
assert.strictEqual(callI64(value), BigInt(value));
assert.strictEqual(callU64(value), BigInt(value));
}
for (const value of [-42, Number.MIN_SAFE_INTEGER,
-(2n ** 63n), (2n ** 63n) - 1n]) {
assert.strictEqual(callI64(value), BigInt(value));
}
assert.strictEqual(callU64((2n ** 64n) - 1n), (2n ** 64n) - 1n);

const signedError = {
code: 'ERR_INVALID_ARG_VALUE',
message: 'Argument 0 must be an int64',
};
const unsignedError = {
code: 'ERR_INVALID_ARG_VALUE',
message: 'Argument 0 must be a uint64',
};
for (const value of [Number.MAX_SAFE_INTEGER + 1, Number.MIN_SAFE_INTEGER - 1,
1.5, NaN, Infinity, -Infinity, '1', null, undefined, true, {}]) {
assert.throws(() => callI64(value), signedError);
assert.throws(() => callU64(value), unsignedError);
}
for (const value of [-(2n ** 63n) - 1n, 2n ** 63n]) {
assert.throws(() => callI64(value), signedError);
}
for (const value of [-1, -1n, 2n ** 64n]) {
assert.throws(() => callU64(value), unsignedError);
}
}
} finally {
eval('%WaitForBackgroundOptimization()');
lib.close();
}
});

test('fast FFI validates pointer BigInt ranges', () => {
const lib = new ffi.DynamicLibrary(libraryPath);
try {
Expand Down
Loading
Loading