node-ctypes 2.8.0 → 2.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -7,6 +7,91 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [2.10.0] - 2026-11-06
11
+
12
+ ### Fixed
13
+
14
+ - **Callback exception boundary**: a C++ exception other than a Node-API error
15
+ (for example `std::bad_alloc` while copying an aggregate) raised while
16
+ converting arguments or results, calling the JavaScript function, its error
17
+ handler or the warning fallback is recorded and yields a zero result instead
18
+ of crossing the native callback frame.
19
+ - **Callback snapshot pool isolation**: snapshots of callback arguments no
20
+ longer share their pool with native-call temporaries. Since 2.9.0, detaching
21
+ a snapshot's `ArrayBuffer` broke every later by-value structure argument and
22
+ structure callback, and could let JavaScript read, alter or release memory
23
+ still used by an in-flight native call. A detached pool is now replaced.
24
+ - **Detached buffer arguments**: a Buffer, typed array, DataView or ArrayBuffer
25
+ argument detached while native code could still use it (by a callback during
26
+ a synchronous call, or before a `callAsync()` completes) now makes the call
27
+ throw or reject instead of returning silently. Node-API cannot prevent the
28
+ detach; synchronous calls check only when a JavaScript callback ran.
29
+
30
+ ### Documentation
31
+
32
+ - **Callback snapshot pool**: document the dedicated snapshot pool, how
33
+ retention affects memory and why the underlying `ArrayBuffer` should not be
34
+ exposed without copying.
35
+
36
+ ## [2.9.0] - 2026-11-05
37
+
38
+ ### Added
39
+
40
+ - **Backend-independent ABI regressions**: compiled C callers verify scalar
41
+ aliases, narrow GP/FP stack arguments, small/large aggregates and homogeneous
42
+ float/double aggregates for sync/async calls and ordinary/thread-safe callbacks.
43
+ Include Darwin stack-slot coverage and a safe indirect-pointer alignment probe.
44
+ - **Koffi C-loop callback comparison**: check 64 consecutive i32 callbacks per
45
+ native call with the same C fixture, reporting batch latency separately from
46
+ the single-callback workload and normalizing both int64 results to Number.
47
+ - **node:ffi benchmark coverage**: expand to 25 workloads with narrow scalars,
48
+ GP/FP stack arguments, C-loop/host-thread-safe callbacks and inferred calls.
49
+ Document numeric bool normalization and explicitly typed inference counterparts;
50
+ unsupported aggregate, variadic and async APIs remain not compared.
51
+
52
+ ### Changed
53
+
54
+ - **Native backend source boundaries**: keep `src` flat and isolate
55
+ `libffi_types`, `libffi_call` and `libffi_callback`, with concrete RAII-managed
56
+ state and lazy descriptor caches. Common wrappers retain Node-API marshalling,
57
+ selection and sync/async/TSFN ownership. Scalar/direct headers no longer depend
58
+ on libffi; return-word compatibility is checked at compile time. CMake discovers
59
+ native sources with `GLOB_RECURSE` and `CONFIGURE_DEPENDS`.
60
+ - **libffi upstream alignment**: temporarily pin the unmodified submodule to
61
+ `d02afc25e8ea3aac9e78e227748e1fd7c9f14c82` for the Darwin small-composite
62
+ stack-slot fixes and regenerate integration headers, pending an official tag.
63
+ The indirect-pointer alignment defect remains tracked in
64
+ [libffi/libffi#1057](https://github.com/libffi/libffi/issues/1057), without a local vendor patch.
65
+ - **Fixed sync/async preparation**: select direct invokers from finalized native
66
+ metadata before preparing libffi types, CIFs or call plans; fixed workers reuse
67
+ that selection and pin the parent function and library. Unsupported signatures
68
+ retain eager libffi setup. Extra calls use cached sync or worker-owned async
69
+ CIFs, prepared on the JavaScript thread without changing the fixed invoker.
70
+
71
+ ### Performance
72
+
73
+ - **Inferred and variadic arguments**: bypass object conversion for primitive
74
+ JavaScript extras and keep type/value metadata for up to 16 extras on the stack.
75
+ Generic sync calls fuse inference/storage for leading numeric extras within
76
+ 16 total arguments. Preserve the eight-argument simple path, conversion order,
77
+ scalar snapshots and ownership, with boundary, promotion, wide/non-finite
78
+ number and reentrant-cache regressions.
79
+ - **Owned callback snapshots**: reuse the existing aligned JavaScript buffer
80
+ pool for eligible high-level arguments, with independent, never-recycled
81
+ slices; raw native and over-aligned arguments retain Node-API copies.
82
+ Cache standard handlers and readers, not individual views, while respecting
83
+ custom definition getters and mirrored synchronization.
84
+
85
+ ### Known limitations
86
+
87
+ - **Darwin ARM64 indirect arguments**: libffi can misalign a large aggregate's
88
+ indirect pointer after a narrow stack scalar. Temporarily skip the stack-tag
89
+ regression only on Darwin ARM64 until an upstream fix is available.
90
+ - **Windows ARM64 variadic HFAs**: a named four-double HFA argument (32 bytes)
91
+ crashes in upstream libffi. Temporarily skip its regression only on Windows
92
+ ARM64, retaining coverage on other targets.
93
+ This is not a runtime fix.
94
+
10
95
  ## [2.8.0] - 2026-11-04
11
96
 
12
97
  ### Fixed
@@ -1071,7 +1156,9 @@ It contains breaking changes: see [Migrating from 1.x](README.md#migrating-from-
1071
1156
 
1072
1157
  Initial releases.
1073
1158
 
1074
- [Unreleased]: https://github.com/dmazzella/node-ctypes/compare/v2.8.0...HEAD
1159
+ [Unreleased]: https://github.com/dmazzella/node-ctypes/compare/v2.10.0...HEAD
1160
+ [2.10.0]: https://github.com/dmazzella/node-ctypes/compare/v2.9.0...v2.10.0
1161
+ [2.9.0]: https://github.com/dmazzella/node-ctypes/compare/v2.8.0...v2.9.0
1075
1162
  [2.8.0]: https://github.com/dmazzella/node-ctypes/compare/v2.7.0...v2.8.0
1076
1163
  [2.7.0]: https://github.com/dmazzella/node-ctypes/compare/v2.6.0...v2.7.0
1077
1164
  [2.6.0]: https://github.com/dmazzella/node-ctypes/compare/v2.5.0...v2.6.0
package/README.md CHANGED
@@ -36,7 +36,9 @@ import { CDLL, Structure, c_int32, c_size_t, c_char_p } from "node-ctypes";
36
36
  const libc = new CDLL(process.platform === "win32" ? "msvcrt" : null);
37
37
 
38
38
  // 2. Declare a function signature
39
- const strlen = libc.func("strlen", c_size_t, [c_char_p]);
39
+ const strlen = libc.strlen;
40
+ strlen.argtypes = [c_char_p];
41
+ strlen.restype = c_size_t;
40
42
  console.log(strlen("hello")); // 5n
41
43
 
42
44
  // 3. Declare a struct
@@ -88,10 +90,16 @@ auto-`HRESULT`-checking use `OleDLL`.
88
90
 
89
91
  Direct native calls are limited to a bounded set of exact scalar C++
90
92
  signatures with up to four arguments, on 64-bit little-endian targets using
91
- the default ABI. Other signatures use the existing cached libffi plans/CIFs,
93
+ the default ABI. By default, other signatures use the existing cached libffi plans/CIFs,
92
94
  including pointers and strings whose pointee types and qualifiers are not
93
95
  encoded in the native type metadata. Float/double arguments continue to use
94
96
  libffi on x86-64. This changes the optimization route, not the JavaScript API.
97
+ Eligible fixed invokers are selected before constructing libffi types, CIFs or
98
+ call plans. Fixed async workers reuse the same selected invoker, with their own
99
+ argument/result storage. Other signatures retain eager fallback setup;
100
+ additional arguments bypass fixed invokers and prepare their libffi metadata
101
+ on the JavaScript thread. Inferred calls use the ordinary ABI; true variadic
102
+ calls preserve the declared named-prefix boundary.
95
103
 
96
104
  ### Structs, unions, bit fields, arrays
97
105
 
@@ -269,7 +277,7 @@ qsort(arr, 5, 4, cmp);
269
277
  // CFUNCTYPE types also work as struct fields (read back as a callable).
270
278
 
271
279
  // IMPORTANT: release the trampoline when done. Unlike Python, we cannot
272
- // rely on GC — the callback holds a libffi closure that native code may
280
+ // rely on GC — the callback holds a native trampoline that C code may
273
281
  // still reference.
274
282
  cmp.release();
275
283
  cmp2.release();
@@ -289,6 +297,25 @@ Existing callers retain their result-check snapshot and their own `errcheck`.
289
297
  An installed `from_param` converter still resolves the method at call time,
290
298
  as before.
291
299
 
300
+ Structure, union and scalar-instance arguments received by `callback()`,
301
+ `CFUNCTYPE` and `threadSafeCallback()` are owned snapshots: each one is a
302
+ distinct slice of an 8 KB off-heap pool reserved for callback snapshots.
303
+ Native-call temporaries use a separate pool that is never exposed, so a
304
+ snapshot cannot reveal or alter memory that native code is still using.
305
+ Slices are never reused, so a retained argument keeps its own bytes and
306
+ identity. Detaching a snapshot's `ArrayBuffer` (`transfer()`, a transfer list)
307
+ only affects the snapshots in that pool; later callbacks use a fresh one.
308
+
309
+ - Retaining any slice keeps its whole 8 KB backing `ArrayBuffer` alive. When
310
+ storing many small arguments for a long time, copy them, for example
311
+ `Buffer.from(value._buffer)` or a new instance built from its fields.
312
+ - `value._buffer.buffer` is the whole pool and can contain other callback
313
+ snapshots. Use `_buffer` itself (or `byteOffset` and `length`), and copy
314
+ before handing the underlying `ArrayBuffer` to untrusted code.
315
+
316
+ Values larger than 2 KB, layouts aligned to more than 8 bytes and raw native
317
+ callbacks keep a dedicated allocation.
318
+
292
319
  Both callbacks and libraries implement `Symbol.dispose`, so they work
293
320
  with the `using` declaration for scope-bound cleanup (also on `throw`):
294
321
 
@@ -585,6 +612,17 @@ still stop at its end; raw native addresses remain the caller's responsibility.
585
612
  Scalar `from_buffer()` / `from_buffer_copy()` validate byte size and offset
586
613
  before producing an instance and accept Buffer, typed views and ctypes memory.
587
614
 
615
+ Do not detach (`ArrayBuffer.prototype.transfer()`, a `postMessage` /
616
+ `structuredClone` transfer list) memory passed to a call that is still running:
617
+ a pending `callAsync()`, or the outer call while a callback runs. Native code
618
+ keeps its address and may access memory that now belongs to another
619
+ `ArrayBuffer` or has been released. Node-API cannot prevent the detach, so
620
+ node-ctypes reports it instead. A synchronous call during which a JavaScript
621
+ callback ran throws `argument N: memory was detached ...` after native code
622
+ returns, and a `callAsync()` whose Buffer, typed array, DataView or ArrayBuffer
623
+ argument was detached rejects. The check covers those arguments as passed,
624
+ not addresses stored inside structures or obtained with `addressof()`.
625
+
588
626
  ### Electron
589
627
 
590
628
  Electron does not allow Buffers over memory that V8 did not allocate, so a
@@ -993,12 +1031,23 @@ Reports record library/runtime versions, CPU, OS/kernel, buffer mode, start/
993
1031
  finish timestamps and Git revision/working-tree status. Missing CPU or Git
994
1032
  metadata produces an explicit warning rather than invented values.
995
1033
 
996
- The comparisons cover scalars, mixed arguments, short/long strings, buffer
997
- arguments, field reads and callbacks. Koffi also covers structures by value,
1034
+ Both comparisons cover narrow scalars, mixed GP/FP stack arguments, short/long
1035
+ strings, buffer arguments, field reads, scalar callbacks and 64-callback C loops.
1036
+ The node:ffi comparison includes 25 workloads. Koffi also covers structures by value,
998
1037
  variadic calls and async calls with 1/8 calls in flight. Cases without an
999
1038
  equivalent documented node:ffi API are listed as **not compared**, not
1000
1039
  emulated with a different native signature.
1001
1040
 
1041
+ Inferred rows omit node-ctypes `argtypes`, while both competitors use explicit
1042
+ fixed signatures for the same C functions: these rows include node-ctypes
1043
+ inference overhead, not equivalent automatic-inference APIs.
1044
+ The node:ffi bool row passes numeric `1` and compares normalized Number results:
1045
+ node:ffi represents bool arguments/results as uint8 values, whereas node-ctypes
1046
+ returns a JavaScript Boolean. Koffi's bool row uses Boolean input/output.
1047
+ The thread-safe scalar callback rows measure node-ctypes dispatch on its host
1048
+ thread against a competitor callback on the same thread, not cross-thread handoff.
1049
+ The C-loop times are per batch of 64 completed callbacks, not per callback.
1050
+
1002
1051
  The `CFUNCTYPE` rows measure calls through an already-bound node-ctypes
1003
1052
  prototype, against an independently bound competitor function with the same
1004
1053
  C signature. Bindings are separate to avoid sharing optimization feedback
@@ -1009,8 +1058,9 @@ Both sides call the same C fixture and verify results before/after timing.
1009
1058
  String contents are encoded on every call; node-ctypes reuses scratch storage,
1010
1059
  not previously encoded strings. Measurements describe warmed repeated calls,
1011
1060
  not cold-start allocation costs.
1012
- String lengths are compared as Numbers, including conversion where the API
1013
- returns BigInt; wide integers are BigInt in both APIs. Structures are plain
1061
+ String lengths, narrow/inferred-stack i64 results and C-loop sums are compared
1062
+ as Numbers, including conversion where the API returns BigInt; wide integers
1063
+ are BigInt in both APIs. Structures are plain
1014
1064
  objects. Async times include scheduling and are reported per completed call,
1015
1065
  with the concurrency shown in the case name.
1016
1066
 
@@ -1032,9 +1082,73 @@ instead of the default HTML report. Parent directories are created automatically
1032
1082
  HTML generation runs only after all measurements finish.
1033
1083
  `benchmark_koffi.js` and `benchmark_node_ffi.js` define the actual side-by-side
1034
1084
  comparisons; `runner.js` shares timing, table output and HTML generation without
1035
- extra dependencies or a separate renderer script. There is no separate
1036
- self-benchmark command, and benchmarks are not run by the functional/parity
1037
- test suite.
1085
+ extra dependencies or a separate renderer script. Benchmarks are not run by the
1086
+ functional/parity test suite.
1087
+
1088
+ ### Native backends and upstream libffi
1089
+
1090
+ The maintained outgoing paths are the bounded C++ direct invokers and libffi.
1091
+ Callbacks use libffi closures and the shared Node-API bridge. The source tree
1092
+ stays flat, with backend-specific files prefixed where needed:
1093
+
1094
+ | Files | Responsibility |
1095
+ | -------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- |
1096
+ | [call_abi.h](./src/call_abi.h), [types.h](./src/types.h) | Shared calling conventions, ABI return words and scalar conversions, without libffi headers |
1097
+ | [direct_call.h](./src/direct_call.h) | Exact fixed-signature C++ invokers |
1098
+ | [libffi_types.cc](./src/libffi_types.cc), [libffi_types.h](./src/libffi_types.h) | Primitive mapping and aggregate descriptor factories |
1099
+ | [libffi_type_cache.h](./src/libffi_type_cache.h) | Concrete owned aggregate cache used by layout metadata |
1100
+ | [libffi_call.cc](./src/libffi_call.cc), [libffi_call.h](./src/libffi_call.h) | Calling conventions, CIFs, reusable plans and worker-owned extra-call interfaces |
1101
+ | [libffi_callback.cc](./src/libffi_callback.cc), [libffi_callback.h](./src/libffi_callback.h) | Closure preparation, allocation and release |
1102
+ | [function.cc](./src/function.cc), [function.h](./src/function.h) | Node-API call orchestration, marshalling, hooks and sync/async ownership |
1103
+ | [callback.cc](./src/callback.cc), [callback.h](./src/callback.h) | Shared callback conversions, TSFN delivery, native-context hooks and lifetime |
1104
+
1105
+ CMake discovers native files with `file(GLOB_RECURSE ... CONFIGURE_DEPENDS ...)`.
1106
+ The public layouts retain their physical size/alignment; the libffi descriptor
1107
+ cache in `layout.h` is intentionally concrete rather than ABI-agnostic.
1108
+ High-level callback snapshot pooling and cached struct/array readers remain:
1109
+ slices are never recycled, retained views have independent bytes and identity,
1110
+ and custom getters, mirrored synchronization and Node-API ownership are preserved.
1111
+
1112
+ **Temporary dependency pin.** The unmodified
1113
+ [libffi submodule](https://github.com/libffi/libffi/tree/d02afc25e8ea3aac9e78e227748e1fd7c9f14c82) is pinned to upstream commit
1114
+ [`d02afc25e8ea3aac9e78e227748e1fd7c9f14c82`](https://github.com/libffi/libffi/commit/d02afc25e8ea3aac9e78e227748e1fd7c9f14c82),
1115
+ after the v3.8.0 release. Generated version fields still report 3.8.0; the
1116
+ gitlink, not that version string, identifies the exact dependency source.
1117
+ This includes the Darwin GP-composite stack-slot
1118
+ [fix](https://github.com/libffi/libffi/commit/2472245a3430b9d24f085b7654e896e074bceb82)
1119
+ and its [compiler/ABI guard adjustment](https://github.com/libffi/libffi/commit/3365ad8b968a9b742922b6f1188462fe6ce142ec):
1120
+ small GP composites use aligned, whole-word stack slots in outgoing calls and
1121
+ closures, without widening ctypes buffers or changing scalar/HFA packing.
1122
+ This follows the compiler's C ABI rather than reproducing broken padding in
1123
+ older libffi builds, including those used by some Python installations.
1124
+
1125
+ Return to an official tag containing these fixes when released. After changing
1126
+ the submodule revision, run `npm run generate-ffi-headers`, rebuild and repeat
1127
+ the ABI/parity tests. Do not patch the vendored libffi internals.
1128
+
1129
+ **Darwin ARM64 upstream limitation.** When all GP registers are
1130
+ occupied, a byte-aligned non-HFA struct larger than 16 bytes after a narrow
1131
+ stack scalar can still misalign its indirect pointer and subsequent arguments.
1132
+ A callee dereferencing that pointer can crash. The upstream update does not
1133
+ resolve this case and this project does not disguise it by altering layouts.
1134
+ [test_function_abi.js](./tests/node_specific/test_function_abi.js) retains a
1135
+ safe C stack-tag probe for sync/async calls, temporarily skipped only on Darwin
1136
+ ARM64 until an upstream fix is available. The test remains active on other
1137
+ targets. Other supported GP/HFA/large-aggregate cases and ordinary/thread-safe
1138
+ callback ABI tests run normally.
1139
+
1140
+ **Windows ARM64 variadic HFA limitation.** A named HFA argument containing four
1141
+ doubles (32 bytes) in a variadic call triggers an access violation in upstream
1142
+ libffi, independently of the Node wrapper. Avoid this signature until an upstream
1143
+ fix is available. Its regression is temporarily skipped only on Windows ARM64
1144
+ and still runs on other targets. Native calling behavior is unchanged.
1145
+
1146
+ `CTYPES_ENABLE_DIRECT_CALLS` remains a build-time control, default ON. Fixed
1147
+ direct calls and workers need no CIF; unsupported fixed signatures use libffi,
1148
+ and async inferred/variadic calls own CIFs prepared on the JavaScript thread.
1149
+ Workers retain the parent function, metadata and library through completion.
1150
+ To compare the direct-enabled and libffi-only builds, follow the
1151
+ [native validation commands](./tests/README.md#native-backends-and-abi-regressions).
1038
1152
 
1039
1153
  ### Release validation
1040
1154
 
Binary file
Binary file
@@ -57,6 +57,7 @@ import { _toNativeReturnType, _toNativeTypes } from "./types.js";
57
57
  import { adaptCallbackFunction, scalarResult } from "./conversions.js";
58
58
  import { trackCallback } from "./callback-tracker.js";
59
59
  import { callbackPointer } from "../structures/helpers/common.js";
60
+ import { allocSnapshot } from "../memory/buffer.js";
60
61
 
61
62
  function nativeContextHook(value, name, owners) {
62
63
  if (value !== null && (typeof value === "object" || typeof value === "function")) {
@@ -174,7 +175,8 @@ function nativeContextAddresses(context, owners) {
174
175
  export function callback(fn, returnType, argTypes = [], native, abi = undefined) {
175
176
  const args = [adaptCallbackFunction(fn, argTypes, returnType, native), _toNativeReturnType(returnType, native), _toNativeTypes(argTypes, native)];
176
177
  const scalarArgs = argTypes.map(scalarResult);
177
- if (scalarArgs.some(Boolean)) args.push(abi ?? "default", scalarArgs);
178
+ const buffers = scalarArgs.some(Boolean) || args[2].some((type) => typeof type === "object" && type !== null);
179
+ if (buffers) args.push(abi ?? "default", scalarArgs, undefined, allocSnapshot);
178
180
  else if (abi) args.push(abi);
179
181
  const cb = new native.Callback(...args);
180
182
 
@@ -321,7 +323,9 @@ export function threadSafeCallback(fn, returnType, argTypes = [], native, option
321
323
  );
322
324
  const args = [dispatch, _toNativeReturnType(returnType, native), _toNativeTypes(argTypes, native)];
323
325
  const scalarArgs = argTypes.map(scalarResult);
324
- if (context !== undefined) args.push(abi ?? "default", scalarArgs, context);
326
+ const buffers = scalarArgs.some(Boolean) || args[2].some((type) => typeof type === "object" && type !== null);
327
+ if (buffers) args.push(abi ?? "default", scalarArgs, context, allocSnapshot);
328
+ else if (context !== undefined) args.push(abi ?? "default", scalarArgs, context);
325
329
  else if (scalarArgs.some(Boolean)) args.push(abi ?? "default", scalarArgs);
326
330
  else if (abi) args.push(abi);
327
331
  const cb = new native.ThreadSafeCallback(...args);
@@ -263,6 +263,7 @@ export function coerceValue(a, owners) {
263
263
  * value before the next conversion (`printf("%f", c_double(2.0))`).
264
264
  */
265
265
  export function coerceVariadic(a, owners) {
266
+ if (a === null || (typeof a !== "object" && typeof a !== "function")) return a;
266
267
  const info = scalarInstanceInfo(a);
267
268
  if (info !== undefined) {
268
269
  retainArgument(owners, a);
@@ -689,7 +690,11 @@ export function adaptCallbackFunction(fn, argTypes, returnType, native) {
689
690
  function structView(type) {
690
691
  if (typeof type === "function" && typeof type._buildStruct === "function") return (buf) => new type(buf);
691
692
  if (type !== null && typeof type === "object" && type._isStructType === true) {
692
- return (buf) => new Proxy(buf, buildWrapper(type, { instanceTag: "StructInstance", exposeAnonymous: true }));
693
+ let handler;
694
+ return (buf) => {
695
+ handler ??= buildWrapper(type, { instanceTag: "StructInstance", exposeAnonymous: true });
696
+ return new Proxy(buf, handler);
697
+ };
693
698
  }
694
699
  return null;
695
700
  }
package/lib/core/types.js CHANGED
@@ -111,7 +111,11 @@ function _buildNativeStructType(def, native) {
111
111
  if (!Number.isInteger(Math.log2(def.alignment))) {
112
112
  throw new TypeError("Native by-value ABI requires power-of-two alignment; use this layout only for memory serialization");
113
113
  }
114
- const st = new native.StructType({ union: !!def.isUnion, alignment: def.alignment, memoryClass: hasUnalignedFields(def) });
114
+ const st = new native.StructType({
115
+ union: !!def.isUnion,
116
+ alignment: def.alignment,
117
+ memoryClass: hasUnalignedFields(def),
118
+ });
115
119
  const fits = (alignment, offset) => alignment <= def.alignment && offset % alignment === 0;
116
120
 
117
121
  // La classe base è il primo membro della struct (i suoi campi sono i primi
@@ -71,29 +71,67 @@ export function alloc(size) {
71
71
  }
72
72
 
73
73
  const kTransientPoolSize = 8192;
74
- let transientPool = new ArrayBuffer(kTransientPoolSize);
74
+ const FixedArrayBuffer = ArrayBuffer;
75
+ const bufferFrom = Buffer.from;
76
+ const zeroBuffer = Buffer.alloc;
77
+
78
+ let transientPool = new FixedArrayBuffer(kTransientPoolSize);
75
79
  let transientOffset = 0;
80
+ let snapshotPool = new FixedArrayBuffer(kTransientPoolSize);
81
+ let snapshotOffset = 0;
76
82
 
77
83
  /**
78
84
  * Zero-filled buffer for a value that only lives for one native call. A small
79
85
  * Buffer.alloc lives on the V8 heap and must be externalized when native code
80
86
  * reads it; slices of an off-heap pool avoid that. Slices are never reused, so
81
- * a fresh pool is already zeroed.
87
+ * a fresh pool is already zeroed. The pool is never handed to user code:
88
+ * native code may still use these slices while JavaScript runs (callbacks,
89
+ * async calls).
82
90
  *
83
91
  * @param {number} size - Size in bytes to allocate
84
92
  * @returns {Buffer} Zero-initialized buffer
85
93
  */
86
94
  export function allocTransient(size) {
87
- if (size > kTransientPoolSize >>> 2) return Buffer.alloc(size);
95
+ if (size > kTransientPoolSize >>> 2) return zeroBuffer(size);
88
96
  if (transientOffset + size > kTransientPoolSize) {
89
- transientPool = new ArrayBuffer(kTransientPoolSize);
97
+ transientPool = new FixedArrayBuffer(kTransientPoolSize);
90
98
  transientOffset = 0;
91
99
  }
92
- const buf = Buffer.from(transientPool, transientOffset, size);
100
+ const buf = bufferFrom(transientPool, transientOffset, size);
93
101
  transientOffset += (size + 7) & ~7;
94
102
  return buf;
95
103
  }
96
104
 
105
+ /**
106
+ * Zero-filled buffer for an owned callback argument snapshot, sliced as
107
+ * {@link allocTransient} from a separate pool: a snapshot's `.buffer` exposes
108
+ * only other snapshots, and detaching it cannot affect native-call temporaries.
109
+ * Retained slices keep their pool alive; a pool detached by user code
110
+ * (`transfer()`, a transfer list) is replaced.
111
+ *
112
+ * @param {number} size - Size in bytes to allocate
113
+ * @returns {Buffer} Zero-initialized buffer
114
+ */
115
+ export function allocSnapshot(size) {
116
+ if (size > kTransientPoolSize >>> 2) return zeroBuffer(size);
117
+ if (snapshotOffset + size > kTransientPoolSize) {
118
+ snapshotPool = new FixedArrayBuffer(kTransientPoolSize);
119
+ snapshotOffset = 0;
120
+ }
121
+ let buf;
122
+ try {
123
+ buf = bufferFrom(snapshotPool, snapshotOffset, size);
124
+ } catch (error) {
125
+ // Un pool staccato ha byteLength 0: il controllo resta fuori dal percorso caldo.
126
+ if (!snapshotPool.detached) throw error;
127
+ snapshotPool = new FixedArrayBuffer(kTransientPoolSize);
128
+ snapshotOffset = 0;
129
+ buf = bufferFrom(snapshotPool, 0, size);
130
+ }
131
+ snapshotOffset += (size + 7) & ~7;
132
+ return buf;
133
+ }
134
+
97
135
  /**
98
136
  * Creates a buffer containing a null-terminated C string.
99
137
  *
@@ -14,6 +14,7 @@ export const activeOwnerStack = [];
14
14
  export const byrefOwners = new WeakMap();
15
15
  export const structArgumentFactories = new WeakMap();
16
16
  export const structResultReaders = new WeakMap();
17
+ export const structGetters = new WeakMap();
17
18
  // Brand of callback wrappers: their constant pointer (the `_as_parameter_`
18
19
  // value), read without the generic parameter probes.
19
20
  export const callbackPointer = Symbol("callbackPointer");
@@ -38,7 +38,7 @@ import { computeLayout, isGccLayout, normalizePack } from "./layout.js";
38
38
  import { buildWrapper } from "./wrap.js";
39
39
  import { isMirror, syncDefinition } from "../../memory/mirror.js";
40
40
  import { allocTransient } from "../../memory/buffer.js";
41
- import { copyInstance, fieldEntries, fieldsOf, funcPtrFieldType, isScalarSubclass, pointerOwner, scalarReader, simpleFieldWriter, structArgumentFactories, structResultReaders, writePointerField } from "./common.js";
41
+ import { copyInstance, fieldEntries, fieldsOf, funcPtrFieldType, isScalarSubclass, pointerOwner, scalarReader, simpleFieldWriter, structArgumentFactories, structGetters, structResultReaders, writePointerField } from "./common.js";
42
42
 
43
43
  /**
44
44
  * Creates a struct type definition with proper alignment and padding.
@@ -733,5 +733,7 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
733
733
  }
734
734
  }
735
735
 
736
- return syncDefinition(structDef);
736
+ syncDefinition(structDef);
737
+ structGetters.set(structDef, structDef.get);
738
+ return structDef;
737
739
  }
@@ -38,7 +38,7 @@ import { bitFieldAccessors } from "./bitfield.js";
38
38
  import { computeLayout, isGccLayout, normalizePack } from "./layout.js";
39
39
  import { buildWrapper } from "./wrap.js";
40
40
  import { syncDefinition } from "../../memory/mirror.js";
41
- import { clearKeepAlives, copyInstance, fieldEntries, fieldsOf, funcPtrFieldType, pointerOwner, scalarReader, simpleFieldWriter, writePointerField } from "./common.js";
41
+ import { clearKeepAlives, copyInstance, fieldEntries, fieldsOf, funcPtrFieldType, pointerOwner, scalarReader, simpleFieldWriter, structGetters, writePointerField } from "./common.js";
42
42
 
43
43
  /**
44
44
  * Creates a union type definition where all fields share offset 0.
@@ -602,5 +602,7 @@ export function union(fields, options, sizeof, alloc, readValue, writeValue, _is
602
602
  },
603
603
  };
604
604
 
605
- return syncDefinition(unionDef);
605
+ syncDefinition(unionDef);
606
+ structGetters.set(unionDef, unionDef.get);
607
+ return unionDef;
606
608
  }
@@ -19,6 +19,7 @@
19
19
  */
20
20
 
21
21
  import { mirroredAccessors } from "../../memory/mirror.js";
22
+ import { structGetters } from "./common.js";
22
23
 
23
24
  // Proprietà meta del Buffer che NON vanno mai interpretate come field name.
24
25
  // Per i campi Proxy passano direttamente attraverso al target buffer.
@@ -67,6 +68,18 @@ export function buildWrapper(def, { instanceTag, exposeAnonymous, mirrored = fal
67
68
  function createWrapper(def, instanceTag, exposeAnonymous, mirrored) {
68
69
  const { fieldMap, anonymousFieldNames } = def;
69
70
  const { fieldReaders, fieldWriters } = mirrored ? mirroredAccessors(def) : def;
71
+ const get = structGetters.get(def);
72
+ const arrayReaders = Object.create(null);
73
+ if (!mirrored && get !== undefined) {
74
+ for (const field of def.fields) {
75
+ if (field.isArray) {
76
+ arrayReaders[field.name] = (buf) => {
77
+ const view = buf.subarray(field.offset, field.offset + field.size);
78
+ return field.type._charKind !== undefined ? field.type.getValue(view) : field.type.wrap(view);
79
+ };
80
+ }
81
+ }
82
+ }
70
83
 
71
84
  // Precalcola la lista di chiavi visibili (stabile durante tutta la vita
72
85
  // del def). Evita di ricostruirla a ogni Object.keys / {...spread} / ecc.
@@ -89,15 +102,13 @@ function createWrapper(def, instanceTag, exposeAnonymous, mirrored) {
89
102
  if (typeof prop === "string" && BUFFER_META_PROPS.has(prop)) return target[prop];
90
103
 
91
104
  if (typeof prop === "string") {
92
- // FAST PATH: reader precompilato (scalari, POINTER, bitfield).
93
- // NB: questa è la differenza chiave rispetto ai 2 vecchi proxy
94
- // nested che non usavano fieldReaders — ora anche loro ottengono
95
- // il fast path gratis.
96
105
  if (fieldReaders !== undefined) {
97
106
  const r = fieldReaders[prop];
98
107
  if (r !== undefined) return r(target);
99
108
  }
100
- // FALLBACK: tipi complessi (nested/array) e anonymous subfields.
109
+ const arrayReader = arrayReaders[prop];
110
+ if (arrayReader !== undefined && def.get === get) return arrayReader(target);
111
+ // Mirrored arrays, nested fields and anonymous subfields use def.get.
101
112
  if (fieldMap?.has(prop) || (exposeAnonymous && anonymousFieldNames?.[prop] === true)) {
102
113
  return def.get(target, prop);
103
114
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "node-ctypes",
3
- "version": "2.8.0",
3
+ "version": "2.10.0",
4
4
  "description": "Python ctypes-like FFI for Node.js using libffi",
5
5
  "author": "Damiano Mazzella",
6
6
  "license": "MIT",