node-ctypes 2.8.0 → 2.9.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 +61 -1
- package/README.md +94 -10
- package/build/Release/ctypes-darwin-arm64.node +0 -0
- package/build/Release/ctypes-darwin-x64.node +0 -0
- package/build/Release/ctypes-linux-arm64-musl.node +0 -0
- package/build/Release/ctypes-linux-arm64.node +0 -0
- package/build/Release/ctypes-linux-x64-musl.node +0 -0
- package/build/Release/ctypes-linux-x64.node +0 -0
- package/build/Release/ctypes-win32-arm64.node +0 -0
- package/build/Release/ctypes-win32-x64.node +0 -0
- package/lib/core/callback.js +6 -2
- package/lib/core/conversions.js +6 -1
- package/lib/core/types.js +5 -1
- package/lib/memory/buffer.js +9 -6
- package/lib/structures/helpers/common.js +1 -0
- package/lib/structures/helpers/struct.js +4 -2
- package/lib/structures/helpers/union.js +4 -2
- package/lib/structures/helpers/wrap.js +16 -5
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,65 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [2.9.0] - 2026-11-05
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
|
|
14
|
+
- **Backend-independent ABI regressions**: compiled C callers verify scalar
|
|
15
|
+
aliases, narrow GP/FP stack arguments, small/large aggregates and homogeneous
|
|
16
|
+
float/double aggregates for sync/async calls and ordinary/thread-safe callbacks.
|
|
17
|
+
Include Darwin stack-slot coverage and a safe indirect-pointer alignment probe.
|
|
18
|
+
- **Koffi C-loop callback comparison**: check 64 consecutive i32 callbacks per
|
|
19
|
+
native call with the same C fixture, reporting batch latency separately from
|
|
20
|
+
the single-callback workload and normalizing both int64 results to Number.
|
|
21
|
+
- **node:ffi benchmark coverage**: expand to 25 workloads with narrow scalars,
|
|
22
|
+
GP/FP stack arguments, C-loop/host-thread-safe callbacks and inferred calls.
|
|
23
|
+
Document numeric bool normalization and explicitly typed inference counterparts;
|
|
24
|
+
unsupported aggregate, variadic and async APIs remain not compared.
|
|
25
|
+
|
|
26
|
+
### Changed
|
|
27
|
+
|
|
28
|
+
- **Native backend source boundaries**: keep `src` flat and isolate
|
|
29
|
+
`libffi_types`, `libffi_call` and `libffi_callback`, with concrete RAII-managed
|
|
30
|
+
state and lazy descriptor caches. Common wrappers retain Node-API marshalling,
|
|
31
|
+
selection and sync/async/TSFN ownership. Scalar/direct headers no longer depend
|
|
32
|
+
on libffi; return-word compatibility is checked at compile time. CMake discovers
|
|
33
|
+
native sources with `GLOB_RECURSE` and `CONFIGURE_DEPENDS`.
|
|
34
|
+
- **libffi upstream alignment**: temporarily pin the unmodified submodule to
|
|
35
|
+
`d02afc25e8ea3aac9e78e227748e1fd7c9f14c82` for the Darwin small-composite
|
|
36
|
+
stack-slot fixes and regenerate integration headers, pending an official tag.
|
|
37
|
+
The indirect-pointer alignment defect remains tracked in
|
|
38
|
+
[libffi/libffi#1057](https://github.com/libffi/libffi/issues/1057), without a local vendor patch.
|
|
39
|
+
- **Fixed sync/async preparation**: select direct invokers from finalized native
|
|
40
|
+
metadata before preparing libffi types, CIFs or call plans; fixed workers reuse
|
|
41
|
+
that selection and pin the parent function and library. Unsupported signatures
|
|
42
|
+
retain eager libffi setup. Extra calls use cached sync or worker-owned async
|
|
43
|
+
CIFs, prepared on the JavaScript thread without changing the fixed invoker.
|
|
44
|
+
|
|
45
|
+
### Performance
|
|
46
|
+
|
|
47
|
+
- **Inferred and variadic arguments**: bypass object conversion for primitive
|
|
48
|
+
JavaScript extras and keep type/value metadata for up to 16 extras on the stack.
|
|
49
|
+
Generic sync calls fuse inference/storage for leading numeric extras within
|
|
50
|
+
16 total arguments. Preserve the eight-argument simple path, conversion order,
|
|
51
|
+
scalar snapshots and ownership, with boundary, promotion, wide/non-finite
|
|
52
|
+
number and reentrant-cache regressions.
|
|
53
|
+
- **Owned callback snapshots**: reuse the existing aligned JavaScript buffer
|
|
54
|
+
pool for eligible high-level arguments, with independent, never-recycled
|
|
55
|
+
slices; raw native and over-aligned arguments retain Node-API copies.
|
|
56
|
+
Cache standard handlers and readers, not individual views, while respecting
|
|
57
|
+
custom definition getters and mirrored synchronization.
|
|
58
|
+
|
|
59
|
+
### Known limitations
|
|
60
|
+
|
|
61
|
+
- **Darwin ARM64 indirect arguments**: libffi can misalign a large aggregate's
|
|
62
|
+
indirect pointer after a narrow stack scalar. Temporarily skip the stack-tag
|
|
63
|
+
regression only on Darwin ARM64 until an upstream fix is available.
|
|
64
|
+
- **Windows ARM64 variadic HFAs**: a named four-double HFA argument (32 bytes)
|
|
65
|
+
crashes in upstream libffi. Temporarily skip its regression only on Windows
|
|
66
|
+
ARM64, retaining coverage on other targets.
|
|
67
|
+
This is not a runtime fix.
|
|
68
|
+
|
|
10
69
|
## [2.8.0] - 2026-11-04
|
|
11
70
|
|
|
12
71
|
### Fixed
|
|
@@ -1071,7 +1130,8 @@ It contains breaking changes: see [Migrating from 1.x](README.md#migrating-from-
|
|
|
1071
1130
|
|
|
1072
1131
|
Initial releases.
|
|
1073
1132
|
|
|
1074
|
-
[Unreleased]: https://github.com/dmazzella/node-ctypes/compare/v2.
|
|
1133
|
+
[Unreleased]: https://github.com/dmazzella/node-ctypes/compare/v2.9.0...HEAD
|
|
1134
|
+
[2.9.0]: https://github.com/dmazzella/node-ctypes/compare/v2.8.0...v2.9.0
|
|
1075
1135
|
[2.8.0]: https://github.com/dmazzella/node-ctypes/compare/v2.7.0...v2.8.0
|
|
1076
1136
|
[2.7.0]: https://github.com/dmazzella/node-ctypes/compare/v2.6.0...v2.7.0
|
|
1077
1137
|
[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.
|
|
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.
|
|
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
|
|
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();
|
|
@@ -993,12 +1001,23 @@ Reports record library/runtime versions, CPU, OS/kernel, buffer mode, start/
|
|
|
993
1001
|
finish timestamps and Git revision/working-tree status. Missing CPU or Git
|
|
994
1002
|
metadata produces an explicit warning rather than invented values.
|
|
995
1003
|
|
|
996
|
-
|
|
997
|
-
arguments, field reads
|
|
1004
|
+
Both comparisons cover narrow scalars, mixed GP/FP stack arguments, short/long
|
|
1005
|
+
strings, buffer arguments, field reads, scalar callbacks and 64-callback C loops.
|
|
1006
|
+
The node:ffi comparison includes 25 workloads. Koffi also covers structures by value,
|
|
998
1007
|
variadic calls and async calls with 1/8 calls in flight. Cases without an
|
|
999
1008
|
equivalent documented node:ffi API are listed as **not compared**, not
|
|
1000
1009
|
emulated with a different native signature.
|
|
1001
1010
|
|
|
1011
|
+
Inferred rows omit node-ctypes `argtypes`, while both competitors use explicit
|
|
1012
|
+
fixed signatures for the same C functions: these rows include node-ctypes
|
|
1013
|
+
inference overhead, not equivalent automatic-inference APIs.
|
|
1014
|
+
The node:ffi bool row passes numeric `1` and compares normalized Number results:
|
|
1015
|
+
node:ffi represents bool arguments/results as uint8 values, whereas node-ctypes
|
|
1016
|
+
returns a JavaScript Boolean. Koffi's bool row uses Boolean input/output.
|
|
1017
|
+
The thread-safe scalar callback rows measure node-ctypes dispatch on its host
|
|
1018
|
+
thread against a competitor callback on the same thread, not cross-thread handoff.
|
|
1019
|
+
The C-loop times are per batch of 64 completed callbacks, not per callback.
|
|
1020
|
+
|
|
1002
1021
|
The `CFUNCTYPE` rows measure calls through an already-bound node-ctypes
|
|
1003
1022
|
prototype, against an independently bound competitor function with the same
|
|
1004
1023
|
C signature. Bindings are separate to avoid sharing optimization feedback
|
|
@@ -1009,8 +1028,9 @@ Both sides call the same C fixture and verify results before/after timing.
|
|
|
1009
1028
|
String contents are encoded on every call; node-ctypes reuses scratch storage,
|
|
1010
1029
|
not previously encoded strings. Measurements describe warmed repeated calls,
|
|
1011
1030
|
not cold-start allocation costs.
|
|
1012
|
-
String lengths
|
|
1013
|
-
|
|
1031
|
+
String lengths, narrow/inferred-stack i64 results and C-loop sums are compared
|
|
1032
|
+
as Numbers, including conversion where the API returns BigInt; wide integers
|
|
1033
|
+
are BigInt in both APIs. Structures are plain
|
|
1014
1034
|
objects. Async times include scheduling and are reported per completed call,
|
|
1015
1035
|
with the concurrency shown in the case name.
|
|
1016
1036
|
|
|
@@ -1032,9 +1052,73 @@ instead of the default HTML report. Parent directories are created automatically
|
|
|
1032
1052
|
HTML generation runs only after all measurements finish.
|
|
1033
1053
|
`benchmark_koffi.js` and `benchmark_node_ffi.js` define the actual side-by-side
|
|
1034
1054
|
comparisons; `runner.js` shares timing, table output and HTML generation without
|
|
1035
|
-
extra dependencies or a separate renderer script.
|
|
1036
|
-
|
|
1037
|
-
|
|
1055
|
+
extra dependencies or a separate renderer script. Benchmarks are not run by the
|
|
1056
|
+
functional/parity test suite.
|
|
1057
|
+
|
|
1058
|
+
### Native backends and upstream libffi
|
|
1059
|
+
|
|
1060
|
+
The maintained outgoing paths are the bounded C++ direct invokers and libffi.
|
|
1061
|
+
Callbacks use libffi closures and the shared Node-API bridge. The source tree
|
|
1062
|
+
stays flat, with backend-specific files prefixed where needed:
|
|
1063
|
+
|
|
1064
|
+
| Files | Responsibility |
|
|
1065
|
+
| -------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- |
|
|
1066
|
+
| [call_abi.h](./src/call_abi.h), [types.h](./src/types.h) | Shared calling conventions, ABI return words and scalar conversions, without libffi headers |
|
|
1067
|
+
| [direct_call.h](./src/direct_call.h) | Exact fixed-signature C++ invokers |
|
|
1068
|
+
| [libffi_types.cc](./src/libffi_types.cc), [libffi_types.h](./src/libffi_types.h) | Primitive mapping and aggregate descriptor factories |
|
|
1069
|
+
| [libffi_type_cache.h](./src/libffi_type_cache.h) | Concrete owned aggregate cache used by layout metadata |
|
|
1070
|
+
| [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 |
|
|
1071
|
+
| [libffi_callback.cc](./src/libffi_callback.cc), [libffi_callback.h](./src/libffi_callback.h) | Closure preparation, allocation and release |
|
|
1072
|
+
| [function.cc](./src/function.cc), [function.h](./src/function.h) | Node-API call orchestration, marshalling, hooks and sync/async ownership |
|
|
1073
|
+
| [callback.cc](./src/callback.cc), [callback.h](./src/callback.h) | Shared callback conversions, TSFN delivery, native-context hooks and lifetime |
|
|
1074
|
+
|
|
1075
|
+
CMake discovers native files with `file(GLOB_RECURSE ... CONFIGURE_DEPENDS ...)`.
|
|
1076
|
+
The public layouts retain their physical size/alignment; the libffi descriptor
|
|
1077
|
+
cache in `layout.h` is intentionally concrete rather than ABI-agnostic.
|
|
1078
|
+
High-level callback snapshot pooling and cached struct/array readers remain:
|
|
1079
|
+
slices are never recycled, retained views have independent bytes and identity,
|
|
1080
|
+
and custom getters, mirrored synchronization and Node-API ownership are preserved.
|
|
1081
|
+
|
|
1082
|
+
**Temporary dependency pin.** The unmodified
|
|
1083
|
+
[libffi submodule](https://github.com/libffi/libffi/tree/d02afc25e8ea3aac9e78e227748e1fd7c9f14c82) is pinned to upstream commit
|
|
1084
|
+
[`d02afc25e8ea3aac9e78e227748e1fd7c9f14c82`](https://github.com/libffi/libffi/commit/d02afc25e8ea3aac9e78e227748e1fd7c9f14c82),
|
|
1085
|
+
after the v3.8.0 release. Generated version fields still report 3.8.0; the
|
|
1086
|
+
gitlink, not that version string, identifies the exact dependency source.
|
|
1087
|
+
This includes the Darwin GP-composite stack-slot
|
|
1088
|
+
[fix](https://github.com/libffi/libffi/commit/2472245a3430b9d24f085b7654e896e074bceb82)
|
|
1089
|
+
and its [compiler/ABI guard adjustment](https://github.com/libffi/libffi/commit/3365ad8b968a9b742922b6f1188462fe6ce142ec):
|
|
1090
|
+
small GP composites use aligned, whole-word stack slots in outgoing calls and
|
|
1091
|
+
closures, without widening ctypes buffers or changing scalar/HFA packing.
|
|
1092
|
+
This follows the compiler's C ABI rather than reproducing broken padding in
|
|
1093
|
+
older libffi builds, including those used by some Python installations.
|
|
1094
|
+
|
|
1095
|
+
Return to an official tag containing these fixes when released. After changing
|
|
1096
|
+
the submodule revision, run `npm run generate-ffi-headers`, rebuild and repeat
|
|
1097
|
+
the ABI/parity tests. Do not patch the vendored libffi internals.
|
|
1098
|
+
|
|
1099
|
+
**Darwin ARM64 upstream limitation.** When all GP registers are
|
|
1100
|
+
occupied, a byte-aligned non-HFA struct larger than 16 bytes after a narrow
|
|
1101
|
+
stack scalar can still misalign its indirect pointer and subsequent arguments.
|
|
1102
|
+
A callee dereferencing that pointer can crash. The upstream update does not
|
|
1103
|
+
resolve this case and this project does not disguise it by altering layouts.
|
|
1104
|
+
[test_function_abi.js](./tests/node_specific/test_function_abi.js) retains a
|
|
1105
|
+
safe C stack-tag probe for sync/async calls, temporarily skipped only on Darwin
|
|
1106
|
+
ARM64 until an upstream fix is available. The test remains active on other
|
|
1107
|
+
targets. Other supported GP/HFA/large-aggregate cases and ordinary/thread-safe
|
|
1108
|
+
callback ABI tests run normally.
|
|
1109
|
+
|
|
1110
|
+
**Windows ARM64 variadic HFA limitation.** A named HFA argument containing four
|
|
1111
|
+
doubles (32 bytes) in a variadic call triggers an access violation in upstream
|
|
1112
|
+
libffi, independently of the Node wrapper. Avoid this signature until an upstream
|
|
1113
|
+
fix is available. Its regression is temporarily skipped only on Windows ARM64
|
|
1114
|
+
and still runs on other targets. Native calling behavior is unchanged.
|
|
1115
|
+
|
|
1116
|
+
`CTYPES_ENABLE_DIRECT_CALLS` remains a build-time control, default ON. Fixed
|
|
1117
|
+
direct calls and workers need no CIF; unsupported fixed signatures use libffi,
|
|
1118
|
+
and async inferred/variadic calls own CIFs prepared on the JavaScript thread.
|
|
1119
|
+
Workers retain the parent function, metadata and library through completion.
|
|
1120
|
+
To compare the direct-enabled and libffi-only builds, follow the
|
|
1121
|
+
[native validation commands](./tests/README.md#native-backends-and-abi-regressions).
|
|
1038
1122
|
|
|
1039
1123
|
### Release validation
|
|
1040
1124
|
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
package/lib/core/callback.js
CHANGED
|
@@ -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 { allocTransient } 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
|
-
|
|
178
|
+
const buffers = scalarArgs.some(Boolean) || args[2].some((type) => typeof type === "object" && type !== null);
|
|
179
|
+
if (buffers) args.push(abi ?? "default", scalarArgs, undefined, allocTransient);
|
|
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
|
-
|
|
326
|
+
const buffers = scalarArgs.some(Boolean) || args[2].some((type) => typeof type === "object" && type !== null);
|
|
327
|
+
if (buffers) args.push(abi ?? "default", scalarArgs, context, allocTransient);
|
|
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);
|
package/lib/core/conversions.js
CHANGED
|
@@ -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
|
-
|
|
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({
|
|
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
|
package/lib/memory/buffer.js
CHANGED
|
@@ -71,25 +71,28 @@ export function alloc(size) {
|
|
|
71
71
|
}
|
|
72
72
|
|
|
73
73
|
const kTransientPoolSize = 8192;
|
|
74
|
-
|
|
74
|
+
const FixedArrayBuffer = ArrayBuffer;
|
|
75
|
+
const bufferFrom = Buffer.from;
|
|
76
|
+
const zeroBuffer = Buffer.alloc;
|
|
77
|
+
let transientPool = new FixedArrayBuffer(kTransientPoolSize);
|
|
75
78
|
let transientOffset = 0;
|
|
76
79
|
|
|
77
80
|
/**
|
|
78
|
-
* Zero-filled buffer for a
|
|
81
|
+
* Zero-filled buffer for a native-call temporary or an owned callback snapshot. A small
|
|
79
82
|
* Buffer.alloc lives on the V8 heap and must be externalized when native code
|
|
80
83
|
* reads it; slices of an off-heap pool avoid that. Slices are never reused, so
|
|
81
|
-
* a fresh pool is already zeroed.
|
|
84
|
+
* a fresh pool is already zeroed. Retained slices keep their backing store alive.
|
|
82
85
|
*
|
|
83
86
|
* @param {number} size - Size in bytes to allocate
|
|
84
87
|
* @returns {Buffer} Zero-initialized buffer
|
|
85
88
|
*/
|
|
86
89
|
export function allocTransient(size) {
|
|
87
|
-
if (size > kTransientPoolSize >>> 2) return
|
|
90
|
+
if (size > kTransientPoolSize >>> 2) return zeroBuffer(size);
|
|
88
91
|
if (transientOffset + size > kTransientPoolSize) {
|
|
89
|
-
transientPool = new
|
|
92
|
+
transientPool = new FixedArrayBuffer(kTransientPoolSize);
|
|
90
93
|
transientOffset = 0;
|
|
91
94
|
}
|
|
92
|
-
const buf =
|
|
95
|
+
const buf = bufferFrom(transientPool, transientOffset, size);
|
|
93
96
|
transientOffset += (size + 7) & ~7;
|
|
94
97
|
return buf;
|
|
95
98
|
}
|
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
}
|