Skip to content

ffi: Random "Library is closed" exceptions at call time #63010

@Koromix

Description

@Koromix

Version

v26.0.0-pre / main branch / commit 2962ccf

Platform

Linux looper 6.17.0-22-generic #22~24.04.1-Ubuntu SMP PREEMPT_DYNAMIC Thu Mar 26 15:25:54 UTC 2 x86_64 x86_64 x86_64 GNU/Linux

Subsystem

ffi

What steps will reproduce the bug?

Run the following code with node --experimental-ffi, which calls memset through node:ffi in a loop:

const ffi = require('node:ffi');

const lib = new ffi.DynamicLibrary('libc.so.6');

const memset = lib.getFunction('memset', {
    parameters: ['ptr', 'i32', 'uint64'],
    result: 'ptr'
});

let buf = Buffer.alloc(8192);

for (let i = 0; i < 1000000; i++)
    memset(buf, 42, 8192n);

How often does it reproduce? Is there a required condition?

It works if the loop is changed to iterate only a few times.

This example uses memset but the error can happen with other calls, such as atoi.

What is the expected behavior? Why is that the expected behavior?

All memset calls succeed, script runs to the end, since lib is never closed and the handle remains in scope (which should ensure the GC does not try to free anything).

What do you see instead?

It fails most times on my machine but it runs to the end on occasion.

Here is the stack trace I get most (all?) times:

node:internal/ffi-shared-buffer:286
            return ReflectApply(slowInvoke, undefined, args);
                   ^

Error: Library is closed
    at memset (node:internal/ffi-shared-buffer:286:20)
    at Object.<anonymous> (/home/niels/Bureau/ffi.js:13:5)
    at Module._compile (node:internal/modules/cjs/loader:1829:14)
    at Object..js (node:internal/modules/cjs/loader:1969:10)
    at Module.load (node:internal/modules/cjs/loader:1552:32)
    at Module._load (node:internal/modules/cjs/loader:1354:12)
    at wrapModuleLoad (node:internal/modules/cjs/loader:255:19)
    at Module.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:154:5)
    at node:internal/main/run_main_module:33:47 {
  code: 'ERR_FFI_LIBRARY_CLOSED'
}

Node.js v26.0.0-pre

Additional information

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions