ffi: prevent premature GC of DynamicLibrary

Signed-off-by: semimikoh <ejffjeosms@gmail.com>
PR-URL: https://github.com/nodejs/node/pull/63024
Fixes: https://github.com/nodejs/node/issues/63010
Reviewed-By: Paolo Insogna <paolo@cowtech.it>
Reviewed-By: Anna Henningsen <anna@addaleax.net>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Bryan English <bryan@bryanenglish.com>
This commit is contained in:
semimikoh authored and Antoine du Hamel committed 2026-05-05 16:19:54 +02:00
1 parent 58dc92f502
commit 53eb7abeba
3 files changed
+27 -1

No files matched your search

+2
View File
@@ -194,6 +194,7 @@ void DynamicLibrary::CleanupFunctionInfo(
FFIFunctionInfo* info = data.GetParameter();
info->fn.reset();
info->self.Reset();
info->library.Reset();
delete info;
}
@@ -313,6 +314,7 @@ MaybeLocal<Function> DynamicLibrary::CreateFunction(
}
info->self.Reset(isolate, ret);
info->library.Reset(isolate, object());
info->self.SetWeak(info.release(),
DynamicLibrary::CleanupFunctionInfo,
WeakCallbackType::kParameter);
+2
View File
@@ -33,6 +33,8 @@ struct FFIFunctionInfo {
std::shared_ptr<FFIFunction> fn;
v8::Global<v8::Function> self;
std::shared_ptr<v8::BackingStore> sb_backing;
// Keep the owning DynamicLibrary alive while the generated function is alive.
v8::Global<v8::Object> library;
};
struct FFICallback {
+23 -1
View File
@@ -1,7 +1,8 @@
// Flags: --experimental-ffi
// Flags: --experimental-ffi --expose-gc
'use strict';
const common = require('../common');
common.skipIfFFIMissing();
const { gcUntil } = require('../common/gc');
const assert = require('node:assert');
const { test } = require('node:test');
const ffi = require('node:ffi');
@@ -117,6 +118,27 @@ test('getFunction caches signatures consistently', () => {
}
});
test('FFI functions keep their owning library alive', async () => {
let lib = new ffi.DynamicLibrary(libraryPath);
const addI32 = lib.getFunction('add_i32', fixtureSymbols.add_i32);
const ref = new WeakRef(lib);
lib = null;
for (let i = 0; i < 5; i++) {
await gcUntil(
'FFI function keeps its owning library alive',
() => true,
1,
);
assert.ok(ref.deref() instanceof ffi.DynamicLibrary);
assert.strictEqual(addI32(20, 22), 42);
}
ref.deref().close();
assert.throws(() => addI32(20, 22), /Library is closed/);
});
test('closed libraries reject subsequent operations', () => {
const { lib, functions } = ffi.dlopen(libraryPath, {
add_i32: fixtureSymbols.add_i32,