Open-Source Wikis

/

Node.js

/

Systems

/

FFI (`node:ffi`)

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 tests

Key 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 value

For 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 for char* parameters; lib/internal/ffi-shared-buffer.js provides 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-*.js covers the JS surface.

Entry points for modification

  • Bug in marshalling? src/node_ffi.cc has the ConvertJSToFFI and ConvertFFIToJS helpers.
  • Adding a new type? Edit lib/ffi.js (type table) and src/node_ffi.cc (libffi conversion). Document at doc/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.

FFI (`node:ffi`) – Node.js wiki | Factory