node-ctypes 2.12.2 → 2.13.1

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,127 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [2.13.1] - 2026-11-14
11
+
12
+ ### Fixed
13
+
14
+ - **Argument conversion order through the JavaScript wrapper**: as in CPython,
15
+ where each argument goes through `from_param` and its C conversion before
16
+ the next one, a scalar argument the native call rejects now fails before the
17
+ converters of the later arguments run. Before, with `errcheck`,
18
+ `use_last_error`/`use_errno`, `callAsync` or an object among the
19
+ arguments, the `_as_parameter_` getters and `from_param` of the later
20
+ arguments ran first and the error came afterwards. Values the call accepts
21
+ as they are (integral numbers, booleans and BigInts for integers, numbers for
22
+ floats, one-character strings for `c_char`/`c_wchar`) are checked in
23
+ JavaScript; the others, objects included, by the native conversion itself
24
+ (`checkArgument`), so the rules and the `ArgumentError` messages are those
25
+ of the call. The native check returns the converted C value, so the
26
+ conversion is complete before the next argument: a later adapter changing a
27
+ Buffer passed to `c_char` no longer changes what C receives (as a
28
+ `bytearray` in CPython); memory passed by address (a Buffer for a 64-bit
29
+ integer) stays the original value. Scalar `CType` numbers as argtypes follow
30
+ the same order. Too few arguments are still reported first, as
31
+ "Expected N arguments, got M". The extra cost is a few nanoseconds per scalar
32
+ argument converted by the JavaScript wrapper, and the native check for
33
+ unusual values; calls through the native entry function are unchanged.
34
+ - **Flaky Executor test** (cancellation after an inline completion): on a
35
+ loaded machine the inline waits expired, the per-function backoff then
36
+ skipped the next ones and the 1 ms of inline completions per event loop turn
37
+ was spent by the warm-up calls, so no attempt produced the inline completion
38
+ the test needs. Each attempt now uses a new executor with the longest wait,
39
+ started with another function, and a fresh event loop turn; when the machine
40
+ is so loaded that the executor thread never runs within 10 ms, the test is
41
+ skipped with that reason instead of failing. The attempts stop after 3 s, so
42
+ the skip comes within the 5 s test timeout; a second test checks that the
43
+ attempts without inline completions (`spin: 0`) stop at their time budget.
44
+
45
+ ## [2.13.0] - 2026-11-14
46
+
47
+ ### Changed
48
+
49
+ - **Register-frame calls instead of libffi**: synchronous calls of any
50
+ signature of scalars, pointers and strings (up to 32 arguments) no longer go
51
+ through libffi on AArch64, x86-64 System V and Win64. Each argument is
52
+ converted straight into its register or stack word and one C++ signature per
53
+ ABI passes the frame; before, libffi handled every signature with a pointer
54
+ or a string and every one over four arguments. On x64 the call keeps the
55
+ variadic register setup of libffi (AL on System V, doubles mirrored in the
56
+ integer registers on Win64) for variadic functions declared with argtypes.
57
+ Functions without argtypes and, on x64, variadic arguments use it too. On
58
+ Apple ARM64 the stack arguments are packed by size and natural alignment,
59
+ as the platform ABI (and libffi) lay them out; variadic arguments there
60
+ stay with libffi.
61
+ - **Native functions returned by `CDLL.func()` and prototypes**: when the
62
+ arguments need no JavaScript conversion (scalars, `c_char_p` strings) the
63
+ returned function is the native one, as in Koffi, instead of a JavaScript
64
+ wrapper; calls with objects (`CData` instances, buffers for `c_char_p`,
65
+ `_as_parameter_`), with `errcheck` and the other signatures go to the
66
+ JavaScript converters as before. The JavaScript wrappers shared V8 feedback
67
+ across all functions, which made calls slower in programs using many of them.
68
+ Visible differences for `CDLL.func()`: the function's `length` is 0 (it was
69
+ the number of `argtypes` up to six) and its `name` is the C function's;
70
+ `Function.prototype.toString` shows `[native code]` (prototypes too). Its
71
+ properties (`errcheck`, `callAsync`, `callOn`, `address`, ...) are unchanged.
72
+ - **Fast path up to 32 arguments** (it was 8), reading the arguments with a
73
+ capacity close to the declared signature (2, 4 or 8); primitive arguments
74
+ pass through the JavaScript wrapper without conversion or copies.
75
+ - **Faster struct arguments**: structs passed by value take the fast path at
76
+ any size (it was up to 16 bytes); libffi copies their bytes from the buffer
77
+ before the call, as the general path did. A plain object of field values
78
+ skips the generic parameter probes and the struct's Buffer is passed without
79
+ a second conversion; `create`/`set` overrides, getters and field validation
80
+ are unchanged. A `{x, y}` argument is about 20% faster, a four-double HFA
81
+ argument about 30%.
82
+ - **Faster attribute calls** (`lib.name(...)`): a function already looked up
83
+ is found with one lookup, before the library's own properties, and its
84
+ arguments are forwarded without a rest array; a call through the attribute
85
+ is about 30% faster. As in Python, where `__getattr__` stores the function
86
+ on the library, a property defined later with the same name still replaces
87
+ it, and `delete lib.name` now forgets the function: the next access returns
88
+ a new one with no `argtypes`/`restype` (before, the same function).
89
+ - **Faster long string arguments**: strings that do not fit the 512-byte inline
90
+ buffer are encoded straight into the reusable scratch of the function in the
91
+ fast path, instead of retrying the conversion in the general path (three
92
+ partial copies before the complete one). Strings of 600 bytes are about 30%
93
+ faster, of 4 KB about 10-15%.
94
+ - **Faster pointer arguments**: each pointer position remembers the kind of
95
+ value it received last (BigInt, Number, `null`/`undefined`, or a buffer for
96
+ `c_char_p`) and reads that kind first, with one call to V8 instead of three;
97
+ another kind takes the full conversion as before. An address passed as a
98
+ BigInt or a Number is about 15-20% faster, `null` 5-10%.
99
+ - **Faster callbacks**: up to 64 callbacks running inside one synchronous call
100
+ reuse its handle scope instead of opening one each (`napi_open_handle_scope`
101
+ allocates); numeric results are converted with one read; after a callback,
102
+ only the arguments that are JavaScript memory are checked for detachment.
103
+
104
+ ### Fixed
105
+
106
+ - **gcc `-Wstringop-overread` warning** in the conversion of callback results:
107
+ the helper that widens a narrow integer result was also instantiated for the
108
+ types that fill the whole return word, and gcc 13 saw a read past the end of
109
+ the value. Narrow results now have their own helper
110
+ (`StoreNarrowIntegerValue`).
111
+ - **Flaky Executor test**: the coalescing test counted deliveries while the
112
+ executor thread was still completing the burst, so a loaded machine produced
113
+ more deliveries without any defect. Each call of the burst now marks its own
114
+ byte and the JavaScript thread waits for every mark before yielding; the test
115
+ fails with one delivery per call when coalescing is disabled.
116
+ - README: the Koffi version approved for the comparison benchmarks is 3.3.8.
117
+
118
+ ### Added
119
+
120
+ - README: an `Executor` for many short calls kept in flight, with the reasons
121
+ and the limits (one call at a time).
122
+ - Regression tests: many and nested callbacks in one call, out-of-range and
123
+ non-finite Number results of integer callbacks, pointer arguments whose kind
124
+ of value changes between calls, `_as_parameter_` adapters of structure
125
+ arguments read once with their errors normalized, assignment and `delete` of
126
+ library attributes, attribute functions with `use_last_error`, strings
127
+ that fill the inline buffer followed by any `c_char_p` value, and results
128
+ that point into long string arguments (with `errcheck` and reentrant
129
+ calls); test fixture function `fixture_string_lengths_nullable`.
130
+
10
131
  ## [2.12.2] - 2026-11-11
11
132
 
12
133
  ### Fixed
@@ -1310,7 +1431,9 @@ It contains breaking changes: see [Migrating from 1.x](README.md#migrating-from-
1310
1431
 
1311
1432
  Initial releases.
1312
1433
 
1313
- [Unreleased]: https://github.com/dmazzella/node-ctypes/compare/v2.12.2...HEAD
1434
+ [Unreleased]: https://github.com/dmazzella/node-ctypes/compare/v2.13.1...HEAD
1435
+ [2.13.1]: https://github.com/dmazzella/node-ctypes/compare/v2.13.0...v2.13.1
1436
+ [2.13.0]: https://github.com/dmazzella/node-ctypes/compare/v2.12.2...v2.13.0
1314
1437
  [2.12.2]: https://github.com/dmazzella/node-ctypes/compare/v2.12.1...v2.12.2
1315
1438
  [2.12.1]: https://github.com/dmazzella/node-ctypes/compare/v2.12.0...v2.12.1
1316
1439
  [2.12.0]: https://github.com/dmazzella/node-ctypes/compare/v2.11.1...v2.12.0
package/README.md CHANGED
@@ -153,6 +153,16 @@ await executor.close(); // waits for the accepted calls, then stops the thread
153
153
  - Callbacks invoked during the call run on the executor thread: use
154
154
  `threadSafeCallback`, as with `callAsync`.
155
155
 
156
+ An `Executor` also suits many short calls kept in flight. Each `callAsync()`
157
+ queues its own libuv work item, which wakes a worker, and completes
158
+ separately; the executor thread takes the next queued call without being
159
+ woken and delivers the completed calls to JavaScript together. With several
160
+ calls in flight this usually costs less than `callAsync()`: about a third on
161
+ Windows, where waking a thread is expensive, less of a difference elsewhere.
162
+ The calls then run one at a time: for short calls that is usually faster than
163
+ spreading them over the libuv workers, but blocking calls that must overlap
164
+ still need `callAsync()` or one executor each.
165
+
156
166
  ### Structs, unions, bit fields, arrays
157
167
 
158
168
  ```javascript
@@ -995,7 +1005,7 @@ Each example in `examples/` has its own README; see the [index](examples/README.
995
1005
  - [Cryptoki (PKCS #11)](examples/cross-platform/cryptoki/README.md) — complete 3.2 declarations with 2.20–3.2 dispatch and a standalone SoftHSM demo: temporary token, login, RSA, ECDSA, AES and SHA-256
996
1006
  - [Accessibility](examples/macos/accessibility/README.md) — macOS UI automation with the Accessibility API
997
1007
  - [COM automation](examples/windows/com/README.md) — shell shortcuts (`IShellLinkW`) and Active Directory (`IDirectorySearch`)
998
- - [Controls](examples/windows/controls/README.md) — Win32 common controls
1008
+ - [Controls](examples/windows/controls/README.md) — a small Win32 application with the common controls
999
1009
  - [LDAP](examples/windows/ldap/README.md) — LDAPv3 paged search (`wldap32`)
1000
1010
  - [Registry](examples/windows/registry/README.md) — `setValue` / `getValue` / `openKey` / `deleteKey`
1001
1011
  - [System tray](examples/windows/tray/README.md) — tray icon + popup menu
@@ -1048,7 +1058,7 @@ npm run bench:koffi # node-ctypes vs Koffi; Node 24+
1048
1058
  npm run bench:ffi # node-ctypes vs node:ffi; Node 26+
1049
1059
  ```
1050
1060
 
1051
- The private test package explicitly approves the install script for Koffi 3.3.3.
1061
+ The private test package explicitly approves the install script for Koffi 3.3.8.
1052
1062
  When upgrading Koffi, review the new version before updating that approval with
1053
1063
  `npm --prefix tests install-scripts approve koffi`; future versions are not
1054
1064
  automatically authorized.
@@ -1139,14 +1149,27 @@ functional/parity test suite.
1139
1149
 
1140
1150
  ### Native backends and upstream libffi
1141
1151
 
1142
- The maintained outgoing paths are the bounded C++ direct invokers and libffi.
1143
- Callbacks use libffi closures and the shared Node-API bridge. The source tree
1144
- stays flat, with backend-specific files prefixed where needed:
1152
+ The maintained outgoing paths are the bounded C++ direct invokers, register-frame
1153
+ calls and libffi. Register-frame calls cover any signature of scalars, pointers
1154
+ and strings up to 32 arguments on AArch64, x86-64 System V and Win64: each
1155
+ argument is converted straight into its register or stack word, and one C++
1156
+ signature per ABI passes the whole frame (on Apple ARM64 the stack arguments
1157
+ are packed by size and natural alignment, as the platform ABI requires).
1158
+ libffi remains for aggregates, other calling conventions
1159
+ and the remaining cases. `CDLL.func()` and prototype calls return the native
1160
+ function itself when the arguments need no JavaScript conversion (scalars,
1161
+ `c_char_p` strings), as Koffi does; objects, `errcheck` and the other
1162
+ signatures are forwarded to the JavaScript converters.
1163
+ Callbacks use libffi closures and the shared Node-API bridge; up to 64 callbacks
1164
+ running inside one synchronous call reuse its handle scope instead of opening
1165
+ their own. The source tree stays flat, with backend-specific files prefixed
1166
+ where needed:
1145
1167
 
1146
1168
  | Files | Responsibility |
1147
1169
  | -------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- |
1148
1170
  | [call_abi.h](./src/call_abi.h), [types.h](./src/types.h) | Shared calling conventions, ABI return words and scalar conversions, without libffi headers |
1149
1171
  | [direct_call.h](./src/direct_call.h) | Exact fixed-signature C++ invokers |
1172
+ | [frame_call.h](./src/frame_call.h) | Register-frame calls: argument placement per ABI and one C++ signature per return type |
1150
1173
  | [libffi_types.cc](./src/libffi_types.cc), [libffi_types.h](./src/libffi_types.h) | Primitive mapping and aggregate descriptor factories |
1151
1174
  | [libffi_type_cache.h](./src/libffi_type_cache.h) | Concrete owned aggregate cache used by layout metadata |
1152
1175
  | [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 |
@@ -1195,8 +1218,9 @@ libffi, independently of the Node wrapper. Avoid this signature until an upstrea
1195
1218
  fix is available. Its regression is temporarily skipped only on Windows ARM64
1196
1219
  and still runs on other targets. Native calling behavior is unchanged.
1197
1220
 
1198
- `CTYPES_ENABLE_DIRECT_CALLS` remains a build-time control, default ON. Fixed
1199
- direct calls and workers need no CIF; unsupported fixed signatures use libffi,
1221
+ `CTYPES_ENABLE_DIRECT_CALLS` remains a build-time control, default ON, for both
1222
+ the direct invokers and the register-frame calls. Fixed direct calls and workers
1223
+ need no CIF; unsupported fixed signatures use libffi,
1200
1224
  and async inferred/variadic calls own CIFs prepared on the JavaScript thread.
1201
1225
  Workers retain the parent function, metadata and library through completion.
1202
1226
  To compare the direct-enabled and libffi-only builds, follow the
Binary file
Binary file
@@ -57,6 +57,10 @@ import { callOn } from "./executor.js";
57
57
  */
58
58
  export function createLibraryClasses(Library, LRUCache, _toNativeType, _toNativeTypes, native) {
59
59
  const typeKey = createTypeKey();
60
+ // Captured at load so calls are not affected by later patches.
61
+ const reflectApply = Reflect.apply;
62
+ // Library Proxy -> the CDLL instance behind it.
63
+ const libraryTargets = new WeakMap();
60
64
  // Funzione passata a errcheck quando la chiamata passa da un attributo
61
65
  // della libreria (FunctionWrapper).
62
66
  const kErrcheckFunc = Symbol("errcheckFunc");
@@ -97,9 +101,16 @@ export function createLibraryClasses(Library, LRUCache, _toNativeType, _toNative
97
101
  return cachedFunc;
98
102
  };
99
103
 
100
- // Funzione semplice con accessor invece di un Proxy: ogni chiamata
101
- // attraverso un Proxy costava ~20 ns in più.
102
- const func = (...args) => (cachedFunc ?? resolve())(...args);
104
+ // A plain function with accessors instead of a Proxy: each call through
105
+ // a Proxy cost ~20 ns more. The arguments are forwarded as `arguments`,
106
+ // without the array of (...args): called as `lib.name(...)` (through the
107
+ // library's Proxy) V8 does not inline it and the array cost ~60 ns. A
108
+ // method, like an arrow function, is not a constructor.
109
+ const { func } = {
110
+ func() {
111
+ return reflectApply(cachedFunc ?? resolve(), undefined, arguments);
112
+ },
113
+ };
103
114
 
104
115
  Object.defineProperties(func, {
105
116
  address: { get: () => resolve().address },
@@ -182,23 +193,41 @@ export function createLibraryClasses(Library, LRUCache, _toNativeType, _toNative
182
193
  this._use_errno = !!options.use_errno;
183
194
 
184
195
  // Return a proxy to enable Python-like syntax: libc.abs.argtypes = [...]; libc.abs.restype = ...; libc.abs(...)
185
- return new Proxy(this, {
196
+ const wrappers = this._funcWrapperCache;
197
+ const proxy = new Proxy(this, {
186
198
  get(target, prop, receiver) {
199
+ // A function already looked up comes first, as in Python, where
200
+ // __getattr__ stores it on the instance: one Map lookup instead of
201
+ // the `in` walk of the prototype chain, which misses for functions.
202
+ if (typeof prop === "string") {
203
+ const cached = wrappers.get(prop);
204
+ if (cached !== undefined) {
205
+ return cached;
206
+ }
207
+ }
187
208
  // Allow access to existing properties/methods
188
209
  if (prop in target || typeof prop !== "string") {
189
210
  return Reflect.get(target, prop, receiver);
190
211
  }
191
- // Check if we already have a FunctionWrapper for this function name
192
- const cached = target._funcWrapperCache.get(prop);
193
- if (cached !== undefined) {
194
- return cached;
195
- }
196
212
  // Create and cache a new FunctionWrapper
197
213
  const wrapper = new FunctionWrapper(target, prop);
198
- target._funcWrapperCache.set(prop, wrapper);
214
+ wrappers.set(prop, wrapper);
199
215
  return wrapper;
200
216
  },
217
+ // As in Python, a property set later with the name of a function
218
+ // replaces it, and `delete lib.name` forgets the function: the next
219
+ // access creates a new one.
220
+ defineProperty(target, prop, descriptor) {
221
+ wrappers.delete(prop);
222
+ return Reflect.defineProperty(target, prop, descriptor);
223
+ },
224
+ deleteProperty(target, prop) {
225
+ wrappers.delete(prop);
226
+ return Reflect.deleteProperty(target, prop);
227
+ },
201
228
  });
229
+ libraryTargets.set(proxy, this);
230
+ return proxy;
202
231
  }
203
232
 
204
233
  /**
@@ -312,7 +341,8 @@ export function createLibraryClasses(Library, LRUCache, _toNativeType, _toNative
312
341
  // If use_last_error / use_errno is set on the library, wrap callMethod
313
342
  // so the most-recently-called FFIFunction is remembered on the library.
314
343
  if (this._use_last_error || this._use_errno) {
315
- const self = this;
344
+ // The library itself, not its Proxy: this write runs on every call.
345
+ const self = libraryTargets.get(this) ?? this;
316
346
  const origCall = callMethod;
317
347
  callMethod = function (...args) {
318
348
  self._lastCalledFfi = ffiFunc;
@@ -330,18 +360,29 @@ export function createLibraryClasses(Library, LRUCache, _toNativeType, _toNative
330
360
  };
331
361
  }
332
362
 
363
+ // La funzione restituita: come in Koffi, la funzione nativa stessa
364
+ // (_makeEntry) quando gli argomenti che il JavaScript non converte
365
+ // (primitivi per i parametri scalari, stringhe per c_char_p) bastano.
366
+ // Le altre chiamate (oggetti, errcheck) vanno a callMethod con gli
367
+ // stessi argomenti. Senza il wrapper JS il call site resta monomorfico:
368
+ // le closure di specializeCall condividono il feedback di V8.
369
+ let exposed = callMethod;
370
+ if (convertResult === undefined && !hasAdapters && !this._use_last_error && !this._use_errno && C.every((convert) => convert.passesPrimitives === true || convert.passesStrings === true)) {
371
+ exposed = ffiFunc._makeEntry(callMethod, name) ?? callMethod;
372
+ }
373
+
333
374
  // Python: errcheck riceve la funzione su cui è impostato (l'attributo
334
375
  // della libreria, se passa da lì), qualunque sia il restype.
335
- const errcheckFunc = () => callMethod[kErrcheckFunc] ?? callMethod;
376
+ const errcheckFunc = () => exposed[kErrcheckFunc] ?? exposed;
336
377
 
337
378
  // Aggiungi metadata come proprietà non-enumerable per non interferire
338
- Object.defineProperties(callMethod, {
379
+ Object.defineProperties(exposed, {
339
380
  funcName: { value: name },
340
381
  address: { value: ffiFunc.address },
341
382
  _as_parameter_: { value: ffiFunc.address },
342
383
  _ffi: { value: ffiFunc },
343
384
  callAsync: { value: asyncCallMethod, writable: false, enumerable: false, configurable: false },
344
- callOn: { value: (target, ...args) => callOn(callMethod, target, args), writable: false, enumerable: false, configurable: false },
385
+ callOn: { value: (target, ...args) => callOn(exposed, target, args), writable: false, enumerable: false, configurable: false },
345
386
  _callOn: { value: onExecutor },
346
387
  // Esponi errcheck come setter/getter
347
388
  errcheck: {
@@ -352,13 +393,15 @@ export function createLibraryClasses(Library, LRUCache, _toNativeType, _toNative
352
393
  callback = callback ?? null;
353
394
  if (callback !== null && typeof callback !== "function") throw new TypeError("errcheck must be a function or null");
354
395
  callState.errcheck = callback;
396
+ // Con errcheck la funzione nativa passa ogni chiamata al wrapper JS.
397
+ if (exposed !== callMethod) ffiFunc._setEntryDefer(callback !== null);
355
398
  },
356
399
  enumerable: false,
357
400
  configurable: true,
358
401
  },
359
402
  });
360
403
 
361
- return callMethod;
404
+ return exposed;
362
405
  }
363
406
 
364
407
  /**
@@ -50,6 +50,7 @@ export function specializeCall(ffiFunc, method, converters, state, invoke, captu
50
50
  const [C0, C1, C2, C3, C4, C5] = converters;
51
51
  const [N0, N1, N2, N3, N4, N5] = converters.map((convert) => convert.needsOwners ?? needsArgumentOwners);
52
52
  const hasAdapters = converters.some((convert) => convert.requiresOwners);
53
+ const primitivesPass = converters.every((convert) => convert.passesPrimitives === true);
53
54
  const sync = method !== "callAsync";
54
55
  switch (converters.length) {
55
56
  case 0:
@@ -101,9 +102,22 @@ export function specializeCall(ffiFunc, method, converters, state, invoke, captu
101
102
  return ffiFunc[method](C0(a0), C1(a1), C2(a2), C3(a3), C4(a4), C5(a5));
102
103
  };
103
104
  default:
104
- return function (...args) {
105
+ return function () {
105
106
  const checked = captureHere ? state.errcheck : null;
106
- return invoke(args, checked);
107
+ // Scalar parameters receiving primitives need no conversion and no
108
+ // owners: the arguments object goes to the native call as it is.
109
+ if (primitivesPass && checked === null && arguments.length === converters.length) {
110
+ let primitive = true;
111
+ for (let i = 0; i < arguments.length; i++) {
112
+ const value = arguments[i];
113
+ if (value !== null && (typeof value === "object" || typeof value === "function")) {
114
+ primitive = false;
115
+ break;
116
+ }
117
+ }
118
+ if (primitive) return reflectApply(ffiFunc[method], ffiFunc, arguments);
119
+ }
120
+ return invoke(arguments, checked);
107
121
  };
108
122
  }
109
123
  }
@@ -240,9 +254,20 @@ const isStructType = (t) => t !== null && (typeof t === "function" || typeof t =
240
254
  * An array is rejected, as a Python tuple.
241
255
  */
242
256
  function structArgument(T, index) {
243
- const instance = typeof T === "function" ? (values) => new T(values) : (structArgumentFactories.get(T) ?? ((values) => T.create(values)));
257
+ const factory = typeof T === "function" ? undefined : structArgumentFactories.get(T);
258
+ const instance = typeof T === "function" ? (values) => new T(values) : (factory ?? ((values) => T.create(values)));
244
259
  const coerce = mirrorsActive ? coerceStructValue : coerceObject;
260
+ // The functional struct factory returns its fresh Buffer unconverted.
261
+ const build = factory !== undefined && !mirrorsActive ? (values, owners) => factory(values, coerce, owners) : (values, owners) => coerce(instance(values), owners);
245
262
  const convert = (a, owners) => {
263
+ // A plain object of field values, the common case, skips the generic
264
+ // parameter probes: only `_as_parameter_` and `_buffer` change its meaning.
265
+ // Their presence is tested without reading them, so an adapter getter runs
266
+ // once, in resolveArgument, with its errors normalized there.
267
+ if (a !== null && typeof a === "object" && Object.getPrototypeOf(a) === Object.prototype && !("_as_parameter_" in a) && !("_buffer" in a)) {
268
+ retainArgument(owners, a);
269
+ return build(a, owners);
270
+ }
246
271
  a = resolveArgument(a, owners, index);
247
272
  retainArgument(owners, a);
248
273
  if (Array.isArray(a)) {
@@ -308,8 +333,12 @@ export function argumentConverters(argTypes, native) {
308
333
  const kind = typeof t === "function" ? t._type : t;
309
334
  if (kind === native.CType.STRING || kind === native.CType.WSTRING) return stringArgument(t, kind, index, native);
310
335
  if (kind === native.CType.POINTER) return voidPointerArgument(index, native);
311
- if (typeof t !== "function" || t._isSimpleCData !== true) return coerceObject;
312
- return scalarArgument(t, kind, index);
336
+ if (typeof t !== "function" || t._isSimpleCData !== true) {
337
+ // A scalar CType number as argtype: the same conversion order.
338
+ const check = typeof kind === "number" ? scalarCheck(kind, index, native) : undefined;
339
+ return check === undefined ? coerceObject : (a, owners) => check(coerceObject(a, owners));
340
+ }
341
+ return scalarArgument(t, kind, index, native);
313
342
  };
314
343
  const converters = argTypes.map((t, index) => {
315
344
  const base = baseConverter(t, index);
@@ -377,11 +406,79 @@ function stringArgument(T, kind, index, native) {
377
406
  return objectMemory(value, owners);
378
407
  },
379
408
  });
409
+ // c_char_p: strings, null and undefined are returned unchanged (the native
410
+ // entry function converts them itself, see Library._createFunction).
411
+ if (!wide) Object.defineProperty(convert, "passesStrings", { value: true });
380
412
  return convert;
381
413
  }
382
414
 
383
- function scalarArgument(T, kind, index) {
415
+ // The largest BigInt magnitude a float or double argument accepts here: the
416
+ // native conversion raises RangeError from 2 ** 1024.
417
+ const maxFloatBigInt = 2n ** 1023n;
418
+
419
+ /**
420
+ * Conversion of a scalar argument as the native call does it, before the next
421
+ * argument is converted (CPython: from_param, then the C conversion, argument
422
+ * by argument). Values the call accepts as they are pass unchanged: integral
423
+ * numbers, booleans and BigInts for the integer kinds (any integral Number is
424
+ * reduced to the type's bits), numbers, booleans and BigInts up to 2 ** 1023
425
+ * for float and double, a character below 256 or an integer in range(256) for
426
+ * c_char, one UTF-16 unit (not a surrogate) for c_wchar, anything for bool.
427
+ * Other values go to the native conversion itself (`checkArgument`): its
428
+ * rules and ArgumentError messages are those of the call, and it returns the
429
+ * converted C value, so code running afterwards (a later adapter changing a
430
+ * Buffer passed to c_char) cannot change it; memory passed by address stays
431
+ * the original value.
432
+ *
433
+ * @returns {Function|undefined} `(value) => value`, undefined for other kinds
434
+ */
435
+ function scalarCheck(kind, index, native) {
436
+ const C = native.CType;
437
+ let plain;
438
+ switch (kind) {
439
+ case C.BOOL:
440
+ // ToBoolean, which runs no JavaScript and cannot change later.
441
+ return (value) => value;
442
+ case C.FLOAT:
443
+ case C.DOUBLE:
444
+ plain = (value) => typeof value === "number" || typeof value === "boolean" || (typeof value === "bigint" && value >= -maxFloatBigInt && value <= maxFloatBigInt);
445
+ break;
446
+ case C.INT8:
447
+ case C.UINT8:
448
+ case C.INT16:
449
+ case C.UINT16:
450
+ case C.INT32:
451
+ case C.UINT32:
452
+ case C.INT64:
453
+ case C.UINT64:
454
+ case C.LONG:
455
+ case C.ULONG:
456
+ case C.SIZE_T:
457
+ case C.SSIZE_T:
458
+ plain = (value) => (typeof value === "number" && Number.isInteger(value)) || typeof value === "boolean" || typeof value === "bigint";
459
+ break;
460
+ case C.CHAR:
461
+ plain = (value) => (typeof value === "string" && value.length === 1 && value.charCodeAt(0) < 256) || (typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= 255) || typeof value === "boolean";
462
+ break;
463
+ case C.WCHAR:
464
+ plain = (value) => {
465
+ if (typeof value !== "string" || value.length !== 1) return false;
466
+ const unit = value.charCodeAt(0);
467
+ return unit < 0xd800 || unit > 0xdfff;
468
+ };
469
+ break;
470
+ default:
471
+ return undefined;
472
+ }
473
+ return (value) => (plain(value) ? value : native.checkArgument(index, kind, value));
474
+ }
475
+
476
+ function scalarArgument(T, kind, index, native) {
384
477
  const boolean = T._isBoolean === true;
478
+ // As CPython (from_param, then the C conversion, argument by argument), a
479
+ // value the call would reject fails here, before the converters of the later
480
+ // arguments can run user code (adapters, getters).
481
+ const checked = scalarCheck(kind, index, native) ?? ((value) => value);
385
482
  const stored = (value, info, owners, adapted) => {
386
483
  retainArgument(owners, value);
387
484
  if (!boolean && info.type !== T && !(value instanceof T) && !(adapted && info.kind === kind)) {
@@ -395,7 +492,7 @@ function scalarArgument(T, kind, index) {
395
492
  if (info !== undefined) return stored(value, info, owners, adapted);
396
493
  value = resolveArgument(value, owners, index);
397
494
  }
398
- if (value === null || typeof value !== "object") return value;
495
+ if (value === null || typeof value !== "object") return checked(value);
399
496
  const info = scalarInstanceInfo(value);
400
497
  if (info !== undefined) return stored(value, info, owners, adapted);
401
498
  retainArgument(owners, value);
@@ -405,10 +502,12 @@ function scalarArgument(T, kind, index) {
405
502
  }
406
503
  return scalarArgumentValue(value);
407
504
  }
408
- return objectMemory(value, owners);
505
+ return checked(objectMemory(value, owners));
409
506
  };
410
507
  const convert = make(false);
411
508
  Object.defineProperty(convert, "fromParam", { value: make(true) });
509
+ // A valid primitive value (not an object or a function) is returned unchanged.
510
+ Object.defineProperty(convert, "passesPrimitives", { value: true });
412
511
  return convert;
413
512
  }
414
513
 
@@ -546,6 +645,9 @@ function arrayArgument(T, index) {
546
645
  export function convertArguments(args, converters, owners) {
547
646
  const n = args.length;
548
647
  const declared = converters.length;
648
+ // The arity first, as the native call (and CPython) report it before any
649
+ // argument conversion error.
650
+ if (n < declared) throw new TypeError(`Expected ${declared} arguments, got ${n}`);
549
651
  const out = new Array(n);
550
652
  for (let i = 0; i < n; i++) {
551
653
  out[i] = i < declared ? converters[i](args[i], owners) : coerceVariadic(args[i], owners);
@@ -329,7 +329,7 @@ function createFuncPtrType(native, typeName, abi) {
329
329
  const finish = (result) => (convertResult === undefined ? result : convertResult(result));
330
330
  const checkedCall = (method, args, checked, target) => {
331
331
  const originalArgs = Array.isArray(args) ? args : Array.prototype.slice.call(args);
332
- const resultHandler = (result) => checked(finish(result), callMethod, originalArgs);
332
+ const resultHandler = (result) => checked(finish(result), exposed, originalArgs);
333
333
  const call = method === "call" ? (checkedSync ??= ffiFunc._makeCheckedCall()) : undefined;
334
334
  return callWithResultHandler(ffiFunc, method, originalArgs, converters, resultHandler, hasAdapters || argumentsNeedOwners(originalArgs), call, target);
335
335
  };
@@ -411,7 +411,14 @@ function createFuncPtrType(native, typeName, abi) {
411
411
  },
412
412
  };
413
413
  }
414
- Object.defineProperties(callMethod, {
414
+ // As CDLL.func: the native entry function when the arguments that the
415
+ // JavaScript does not convert are enough (see Library._createFunction);
416
+ // not for a JS callback, whose calls are counted here.
417
+ let exposed = callMethod;
418
+ if (callback === undefined && convertResult === undefined && !hasAdapters && converters.every((convert) => convert.passesPrimitives === true || convert.passesStrings === true)) {
419
+ exposed = ffiFunc._makeEntry(callMethod) ?? callMethod;
420
+ }
421
+ Object.defineProperties(exposed, {
415
422
  ...callbackProperties,
416
423
  name: { value: "callMethod", configurable: true },
417
424
  length: { value: 0, configurable: true },
@@ -426,7 +433,7 @@ function createFuncPtrType(native, typeName, abi) {
426
433
  configurable: false,
427
434
  },
428
435
  callOn: {
429
- value: (target, ...args) => callOn(callMethod, target, args),
436
+ value: (target, ...args) => callOn(exposed, target, args),
430
437
  writable: false,
431
438
  enumerable: false,
432
439
  configurable: false,
@@ -440,6 +447,7 @@ function createFuncPtrType(native, typeName, abi) {
440
447
  callback = callback ?? null;
441
448
  if (callback !== null && typeof callback !== "function") throw new TypeError("errcheck must be a function or null");
442
449
  callState.errcheck = callback;
450
+ if (exposed !== callMethod) ffiFunc._setEntryDefer(callback !== null);
443
451
  },
444
452
  enumerable: false,
445
453
  configurable: true,
@@ -447,8 +455,8 @@ function createFuncPtrType(native, typeName, abi) {
447
455
  });
448
456
 
449
457
  if (callback !== undefined) keepFunctionOwner(callMethod, callback);
450
- prototypeOwners.set(callMethod, factory);
451
- return callMethod;
458
+ prototypeOwners.set(exposed, factory);
459
+ return exposed;
452
460
  }
453
461
 
454
462
  // Attach metadata + paramflags binding to the factory
@@ -710,10 +710,15 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
710
710
  return buf;
711
711
  };
712
712
  const createFast = writers.every(([, write]) => typeof write === "function") ? createScalar : createBuffer;
713
- structArgumentFactories.set(structDef, (values) => {
713
+ // The Buffer built here is fresh and passed as is; with `convert` the
714
+ // result of a create override goes through it as any other argument.
715
+ structArgumentFactories.set(structDef, (values, convert, owners) => {
714
716
  // A later create override must still run, with the definition as receiver.
715
717
  const current = structDef.create;
716
- if (current !== create) return current.call(structDef, values);
718
+ if (current !== create) {
719
+ const value = current.call(structDef, values);
720
+ return convert === undefined ? value : convert(value, owners);
721
+ }
717
722
  return structDef.set === set ? createFast(values) : createBuffer(values);
718
723
  });
719
724
  const toObject = structDef.toObject;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "node-ctypes",
3
- "version": "2.12.2",
3
+ "version": "2.13.1",
4
4
  "description": "Python ctypes-like FFI for Node.js using libffi",
5
5
  "author": "Damiano Mazzella",
6
6
  "license": "MIT",