nodejs/node
FFI (node:ffi)
Owners: @nodejs/ffi. Public docs at doc/api/ffi.md.
Purpose
Provide a built-in foreign-function-interface so JavaScript code can call functions from arbitrary shared libraries (libc, OpenSSL, vendor-specific .so/.dll/.dylib) without writing a Node-API addon. Backed by libffi.
Directory layout
lib/ffi.js // public node:ffi module
lib/internal/ffi-shared-buffer.js // SharedArrayBuffer helpers
src/
ffi/ // FFI helpers (libffi types + arena)
node_ffi.{cc,h} // top-level binding
deps/
libffi/ // libffi vendored
test/
ffi/ // integration testsKey abstractions
| Type | Role |
|---|---|
Library (lib/ffi.js) |
A loaded shared library handle; opens via dlopen/LoadLibrary. |
ForeignFunction (lib/ffi.js) |
A function declared with parameter and return types. |
Pointer (lib/ffi.js) |
Wraps a raw memory pointer; lifetime aware. |
node_ffi::FFIBinding (src/node_ffi.cc) |
C++ implementation: dispatches calls through libffi. |
ArenaAllocator (src/ffi/) |
Pooled memory used for argument marshalling. |
How a call is dispatched
sequenceDiagram
participant JS
participant FFI as node_ffi
participant libffi
participant Lib as target shared library
JS->>FFI: lib.func(arg1, arg2)
FFI->>FFI: marshal args using ffi_type[]
FFI->>libffi: ffi_call(cif, fn, &ret, &args)
libffi->>Lib: call function via platform ABI
Lib-->>libffi: return value
libffi-->>FFI: write into ret buffer
FFI-->>JS: convert ret to JS valueFor functions taking pointers, FFI either passes a Buffer's data pointer or a wrapped Pointer. Variadic functions are handled by re-creating a ffi_cif per call site.
Permission model
FFI is one of the most dangerous capabilities in Node — it allows arbitrary native code execution. The ffi permission domain (src/permission/ffi_permission.cc) blocks all Library opens unless --allow-ffi is granted.
Integration points
Buffer: FFI uses Buffer pointers forchar*parameters;lib/internal/ffi-shared-buffer.jsprovides explicit shared-memory helpers.- Threading: foreign functions block the JS thread. Callers can offload heavy calls to a worker thread.
- Tests:
test/ffi/exercises common types;test/parallel/test-ffi-*.jscovers the JS surface.
Entry points for modification
- Bug in marshalling?
src/node_ffi.cchas theConvertJSToFFIandConvertFFIToJShelpers. - Adding a new type? Edit
lib/ffi.js(type table) andsrc/node_ffi.cc(libffi conversion). Document atdoc/api/ffi.md. - libffi update?
tools/dep_updaters/update-libffi.sh.
Built by Factory AutoWiki from public repository content. It is a generated preview for codebase exploration, not source-maintained documentation.