From the repository root, npm --prefix tests test first builds a small C library (tests/fixtures/, into
build/fixture/) used by the tests of structures by value, array parameters
and reentrant calls; npm run build:test-fixture builds it alone. Matched
Python/JavaScript contracts live under tests/cpython_parity/, divided by domain,
and load the same library. Node-specific async, representation and GC checks
live under tests/node_specific/; genuine Python-only scheduling checks live
under tests/python_specific/. The former common/ and windows/ suites have
been migrated into these domains.
Paired JavaScript uses the Python-shaped API: Structure/Union classes,
ARRAY, library attributes with argtypes/restype, and CFUNCTYPE bindings.
The structural guard checks neighboring files and matching class/method IDs
using the existing TypeScript parser and Python AST; runtime assertions remain
independent checks against CPython, not a claim based on file names alone.
npm install
npm run build
npm --prefix tests install
npm --prefix tests test # functional/parity tests
NODE_CTYPES_NO_EXTERNAL_BUFFERS=1 npm --prefix tests test # mirrored native memory
npm --prefix tests run test:parity # matched CPython and JS contracts
npm --prefix tests run test:parity:check # paired file/case/discovery/style guard
npm --prefix tests run test:python # all Python references
npm run test:aotffi # standalone C++20/C11 CTest suite for deps/aotffi
npm run test:types # TypeScript declarations
npm run docs # TypeDoc API site in docs/
npm run docs:serve # preview
See the test suite guide for paired-case conventions, runtime differences and focused commands.
For both structures and unions, fields.js
resolves field declarations and records natural alignment before packing.
layout.js computes field positions,
types.js normalizes argument and return declarations,
and native-aggregate.js turns the computed
layout into a cached ABI descriptor. Extend the descriptor builder when a new
field representation needs ABI support; do not recalculate offsets in the
call wrappers. An array parameter decays to a pointer; a matrix field stays
inline. Preserve the leaf type (four floats can use floating-point registers)
and propagate unaligned members through every nonempty dimension, whether the
element is a class or a struct() definition.
To test that last rule on x86-64 System V, keep the natural and packed controls
at or below 16 bytes. The ABI fixture uses rows[2][2] of {uint8_t, uint16_t}:
the natural matrix uses registers, but the packed matrix must use memory. A
larger integer matrix would use memory either way and could mask a descriptor
bug. Compare arguments and results separately against a typed C caller.
funcptr.js owns prototype caching and binding by
address, symbol or JavaScript callback. Only callbacks own a native trampoline:
callback.js prevents its release until the callable's
active invocations finish, including result hooks and pending completions.
Bindings with output or named parameters use paramflags.js.
Keep shape and pointer checks before symbol lookup, and read names and defaults
after it: getters and the first exception are observable. Plain address calls
do not go through either the release guard or the paramflags wrapper.
conversions.js selects a converter for each
declared argument type, then captures its optional from_param hook. When
a hook returns a value, marshalAdapted handles it if the type accepts a
different representation from an unadapted input. Finish converting each
argument before running the next hook. Share the byte decoding of pointer
values, not their acceptance rules: a typed pointer accepts a direct null
but rejects an _as_parameter_ chain that resolves to null. Each converter
may retain a temporary in the current call's owner list, but does not manage
that list's lifetime.
invocation.js keeps those temporaries alive
through synchronous result handling or asynchronous completion, including
when another call reenters an adapter. For the reverse direction, change
callback-conversions.js: it presents
C arguments to the JS callback and converts its return value back to C.
For a new scalar representation, start in
scalar-protocol.js: reading an argument and
constructing a view of C-owned bytes must not invoke application constructors.
For _as_parameter_ chains, change parameters.js;
it retains intermediate objects while a getter can reenter a call.
Aggregate builders share their identity and conversion hooks with the call
code through protocol.js, without adding
properties to user declarations.
Pointer ownership is a separate concern from field layout. In
ownership.js, all views of a known memory domain
share registrations keyed by byte position. A typed copy captures the owners
of complete pointer slots before overwriting the destination, since the
two views can overlap. A by-value argument keeps those owners even if a
later argument adapter changes the original fields. Copying bytes with
memmove does not acquire those owners.
results.js defines how a declared restype represents
the native value and applies its captured _check_retval_. It has no reference
to the invoked function or its arguments. Those belong to a single invocation:
the checked path in invocation.js passes the
converted result, public callable and original arguments to the captured
errcheck while any argument owners are still alive. Keep this distinction
when adding a return type or changing how a call completes.
The maintained outgoing paths have two tiers: bounded C++ direct invokers
(call_fixed.h) and the standalone zero-JIT aotffi static library
(deps/aotffi/, linked as aotffi::aotffi). For eligible scalar and pointer
signatures (including c_char_p) up to 32 arguments, CallSignature::direct
precomputes each argument's byte offset in DirectCallFrame (register or stack
area) so hot Node-API entries convert straight into the AOT frame and invoke
aotffi_call directly (on Apple ARM64 fixed stack arguments are packed by
size and natural alignment, and anonymous variadic arguments use 8-byte aligned
stack slots, as the platform ABI requires).
The general AOT execution path (ExecuteCall) handles arbitrary aggregate shapes,
long double, large stack frames and the remaining cases over the same
CallSignature and aotffi_call trampoline. CDLL.func() and prototype calls return the native
function itself when the arguments need no JavaScript conversion (scalars,
c_char_p strings), as Koffi does; objects, errcheck and the other
signatures are forwarded to the JavaScript converters.
Ordinary and thread-safe callbacks use precompiled static AOT trampolines in .text
(4,096 slots process-wide by default, configurable via -DCTYPES_MAX_CALLBACKS=<1..65535> on the addon build or
-DAOTFFI_MAX_CALLBACKS=<1..65535> when building deps/aotffi standalone, with Intel CET endbr64, ARM BTI bti c, Windows Control Flow Guard /guard:cf, and zero runtime executable
memory allocation), independently of the outgoing call path. On Windows the Release
addon is compiled and linked with CFG; use dumpbin /loadconfig to
inspect the guard flags and function table in the final PE. The Linux package check inspects the addon in
the npm archive for a non-executable stack, GNU_RELRO and immediate binding.
It reports the final GNU property notes separately: landing instructions in
an object do not establish that the linked addon enables BTI or IBT. Each slot tracks in-flight
native entries lock-free (SlotRecord) so callback metadata and pinned state stay valid
until the last C caller exits aotffi_cb_dispatch. They share the Node-API bridge; up to 2048 callbacks
running inside one synchronous call reuse its handle scope instead of opening
their own.
The Node-API binding headers live in src/ and link against the self-contained
aotffi::aotffi static library in deps/aotffi (which has zero Node-API dependencies
and its own standalone CTest suite via npm run test:aotffi).
After finalizing the layouts, FFIFunction calls abi::PrepareCall
once for the declared signature to select a fixed C++ invoker when supported;
the plan retains no layout pointers. Whenever there is no fixed invoker, the addon
prepares an aotffi::CallSignature (which includes DirectFramePlan when eligible)
used by fast frame calls, general synchronous calls and asynchronous workers. Argument
conversion, buffer ownership, error state and callback delivery stay in the addon.
| Files | Responsibility |
|---|---|
| deps/aotffi/include/aotffi/, deps/aotffi/src/ | Standalone aotffi C++20 ABI classifier, CallFrame / DirectCallFrame execution, lock-free callback slot pool and src/asm/aot_*.{S,asm} trampolines |
| call_platform.h, c_types.h | Calling conventions, C types, sizes, alignments and ABI return words |
| call_plan.h, call_prepare.h | Declared-signature CallPlan and fixed C++ invoker selection from finalized layouts |
| types.h, types.cc | JavaScript/native scalar conversion |
| call_fixed.h | Exact fixed-signature and common-aggregate C++ direct invokers (Tier 1) |
| abi_call.cc, abi_call.h | Node-API bridge to aotffi forward calls, variadic cache and async workers |
| abi_callback.cc, abi_callback.h | Node-API bridge to aotffi static callback slots (Callback and ThreadSafeCallback) |
| function.cc, function.h | FFIFunction lifecycle, call preparation, error state and general synchronous calls |
| function_marshal.cc, function_marshal.h | Scalar, pointer, string, aggregate and variadic marshalling helpers and return conversion |
| function_fast.cc | Hot Node-API entry points (FastCall, FastEntry, SimpleCall and specialized entries) |
| function_async.cc | PreparedCall (inline SBO up to 8 args / 64 B return), CallWorker and callOn dispatch |
| callback.cc, callback.h | Shared callback JS-thread execution, snapshot pool and main-thread Callback |
| callback_threadsafe.cc | ThreadSafeCallback, TSFN delivery, nativeContext hooks and drain() |
CMake discovers native C++ files with file(GLOB_RECURSE ... CONFIGURE_DEPENDS ...)
and selects the matching static assembly trampoline in src/asm/.
The public layouts retain their physical size/alignment without any external FFI
descriptor cache in layout.h.
Callback snapshot pooling (a native C++ 8 KB ArrayBuffer pool for functional
struct()/union() callbacks, with allocSnapshot and Buffer::Copy
retained for derived scalars, mirror mode, class aggregates, over-aligned
layouts and raw callbacks) and prototype-backed struct/array views remain
non-recycling: retained views have independent bytes and identity, and custom
getters, CPython write validation, mirrored synchronization and Node-API
ownership are preserved.
AOT ABI invariants. On Apple ARM64, fixed scalars and HFAs pack to their
natural alignment on the stack while non-HFA composites up to 16 bytes use
whole pointer-sized stack slots and anonymous variadic arguments use 8-byte
aligned stack slots. On Linux ARM64, a spilled HFA or a small non-HFA composite uses its members'
alignment for the argument copy: raising only the enclosing type's alignment does
not add padding before its stack slot. The callback still receives a pointer
aligned for the declared C type. Indirect aggregates (> 8 B or non-power-of-two sizes on
Win64, > 16 B non-HFAs on AArch64) are copied to caller-owned aligned scratch
memory (honoring over-alignment beyond 16 bytes) and their pointer is placed in
an 8-byte register or 8-byte-aligned stack slot. Oversized or zero-sized
by-value aggregate signatures are rejected during signature preparation.
test_function_abi.js checks the
stack slots on every target.
Extra arguments on Windows. As CPython 3.14, whose Windows build never
defines HAVE_FFI_PREP_CIF_VAR, node-ctypes prepares the arguments beyond a
non-empty argtypes as fixed arguments on Windows and as variadic arguments
on POSIX (kVariadicExtras in call_platform.h).
The tests that call a variadic function with floating-point extras are
skipped on Windows ARM64 (SKIP_WINDOWS_ARM64_VARIADIC_FP) and still run on
other targets.
Fixed direct calls and workers need no CallSignature; other signatures use the
AOT trampoline, and async inferred/variadic calls own CallSignature instances
prepared on the JavaScript thread. Workers retain the parent function, metadata
and library through completion. Follow the
native validation commands
when modifying ABI classification or assembly trampolines.
The workflow retains the eight Node 24 native build targets (Windows/macOS,
x64/ARM64, and Linux glibc/musl). C++20 conformance is checked with
-pedantic-errors on GCC/Clang and /permissive- on MSVC; vendor optimization
and the node-addon-api integration remain unchanged.
Three runtime-control jobs reuse the built artifacts on Node 26 without rebuilding the addon, running the functional parity suite normally and with mirrored buffers. A Linux job runs the focused Python 3.15 reference tests in addition to the Python 3.14 reference coverage.
The package assembler requires all eight nonempty binaries and includes
declarations, README, changelog and license. It fails on missing/unknown
artifacts or a stale output directory. Publish depends on the runtime gates,
requires a pushed tag matching the manifest version exactly, and uses next
for prereleases instead of latest. Manual workflow runs never publish.
These are configured gates, not a substitute for a successful native CI run.
npm --prefix tests test builds the fixture and runs the suite;
npm --prefix tests run test:js reuses an already-built fixture/addon.
Both use the documented --test-timeout runner option.