node-ctypes 2.13.2 → 2.15.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 +71 -1
- 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/Library.js +69 -51
- package/lib/core/callback-conversions.js +123 -0
- package/lib/core/callback.js +68 -4
- package/lib/core/conversions.js +74 -412
- package/lib/core/funcptr.js +31 -287
- package/lib/core/invocation.js +170 -0
- package/lib/core/native-aggregate.js +193 -0
- package/lib/core/parameters.js +45 -0
- package/lib/core/paramflags.js +183 -0
- package/lib/core/results.js +86 -0
- package/lib/core/types.js +14 -277
- package/lib/index.d.ts +3 -0
- package/lib/index.js +2 -1
- package/lib/memory/buffer.js +1 -1
- package/lib/memory/mirror.js +2 -2
- package/lib/memory/operations.js +2 -1
- package/lib/memory/ownership.js +218 -0
- package/lib/memory/pointer.js +6 -1
- package/lib/platform/win_types.js +1 -1
- package/lib/structures/Structure.js +50 -37
- package/lib/structures/helpers/array.js +27 -13
- package/lib/structures/helpers/bitfield.js +1 -1
- package/lib/structures/helpers/common.js +3 -368
- package/lib/structures/helpers/fields.js +111 -0
- package/lib/structures/helpers/layout.js +44 -57
- package/lib/structures/helpers/struct.js +19 -108
- package/lib/structures/helpers/union.js +13 -114
- package/lib/structures/helpers/wrap.js +1 -1
- package/lib/structures/protocol.js +8 -0
- package/lib/types/SimpleCData.js +2 -1
- package/lib/types/primitives.js +2 -1
- package/lib/types/scalar-protocol.js +120 -0
- package/package.json +1 -1
|
@@ -1,175 +1,6 @@
|
|
|
1
|
-
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
const simpleTypes = new WeakSet();
|
|
5
|
-
const scalarInstances = new WeakMap();
|
|
6
|
-
const scalarTypeInfos = new WeakMap();
|
|
7
|
-
const scalarAccessors = [];
|
|
8
|
-
const scalarArgumentKinds = new Set();
|
|
9
|
-
const scalarArgumentTypes = new Map();
|
|
10
|
-
const applyScalarReader = Reflect.apply;
|
|
11
|
-
export const activeArgumentOwners = new Set();
|
|
12
|
-
// GC roots of in-progress synchronous conversions, released in LIFO order.
|
|
13
|
-
export const activeOwnerStack = [];
|
|
14
|
-
export const byrefOwners = new WeakMap();
|
|
15
|
-
export const structArgumentFactories = new WeakMap();
|
|
16
|
-
export const structResultReaders = new WeakMap();
|
|
17
|
-
export const structGetters = new WeakMap();
|
|
18
|
-
// Brand of callback wrappers: their constant pointer (the `_as_parameter_`
|
|
19
|
-
// value), read without the generic parameter probes.
|
|
20
|
-
export const callbackPointer = Symbol("callbackPointer");
|
|
21
|
-
|
|
22
|
-
export function resolveParameter(value, owners) {
|
|
23
|
-
if (value === null || (typeof value !== "object" && typeof value !== "function")) return value;
|
|
24
|
-
const pointer = value[callbackPointer];
|
|
25
|
-
if (pointer !== undefined) {
|
|
26
|
-
if (owners !== undefined) owners.push(value);
|
|
27
|
-
return pointer;
|
|
28
|
-
}
|
|
29
|
-
if (owners !== undefined) owners.push(value);
|
|
30
|
-
if (ArrayBuffer.isView(value) && !("_as_parameter_" in value)) return value;
|
|
31
|
-
if (value._isSimpleCDataInstance === true || value._pointerType !== undefined || value._arrayType !== undefined || value._structDef !== undefined || byrefOwners.has(value)) return value;
|
|
32
|
-
const parameter = value._as_parameter_;
|
|
33
|
-
if (parameter === undefined) return value;
|
|
34
|
-
if (parameter === null || (typeof parameter !== "object" && typeof parameter !== "function")) return parameter;
|
|
35
|
-
if (owners !== undefined) return resolveParameter(parameter, owners);
|
|
36
|
-
|
|
37
|
-
// Resolver-only memory operations also retain parents while nested getters can collect.
|
|
38
|
-
const retained = [value];
|
|
39
|
-
activeOwnerStack.push(retained);
|
|
40
|
-
try {
|
|
41
|
-
return resolveParameter(parameter, retained);
|
|
42
|
-
} finally {
|
|
43
|
-
activeOwnerStack.pop();
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
export function sourceBytes(source, offset, size, name) {
|
|
48
|
-
const bytes = source !== null && typeof source === "object" && !ArrayBuffer.isView(source) && Buffer.isBuffer(source._buffer) ? source._buffer : source;
|
|
49
|
-
if (!ArrayBuffer.isView(bytes)) throw new TypeError(`${name}: source must be a Buffer, a typed array or a ctypes instance`);
|
|
50
|
-
if (!Number.isSafeInteger(offset)) throw new TypeError(`${name}: offset must be a safe integer`);
|
|
51
|
-
if (offset < 0) throw new RangeError(`${name}: offset cannot be negative`);
|
|
52
|
-
if (bytes.byteLength - offset < size) throw new RangeError(`${name}: Buffer size too small (${bytes.byteLength} instead of at least ${size + offset} bytes)`);
|
|
53
|
-
return bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
export function registerSimpleType(type) {
|
|
57
|
-
simpleTypes.add(type);
|
|
58
|
-
scalarArgumentKinds.add(type._type);
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
export function scalarTypeInfo(type, swapped = false) {
|
|
62
|
-
let variants = scalarTypeInfos.get(type);
|
|
63
|
-
if (variants === undefined) {
|
|
64
|
-
const kind = type._type;
|
|
65
|
-
variants = [{ type, kind, swapped: false, pointer: type._isPointerValued === true }];
|
|
66
|
-
scalarTypeInfos.set(type, variants);
|
|
67
|
-
}
|
|
68
|
-
const index = swapped ? 1 : 0;
|
|
69
|
-
if (variants[index] === undefined) variants[index] = { ...variants[0], swapped: true };
|
|
70
|
-
return variants[index];
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
export function registerScalarAccessor(accessor) {
|
|
74
|
-
scalarAccessors.push(accessor);
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
export function registerScalarInstance(value, type, swapped = false) {
|
|
78
|
-
scalarInstances.set(value, scalarTypeInfo(type, swapped));
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
export function scalarInstanceInfo(value) {
|
|
82
|
-
if (value === null || (typeof value !== "object" && typeof value !== "function")) return undefined;
|
|
83
|
-
for (const accessor of scalarAccessors) {
|
|
84
|
-
const info = accessor(value);
|
|
85
|
-
if (info !== undefined) return info;
|
|
86
|
-
}
|
|
87
|
-
return scalarInstances.get(value);
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
export function scalarArgumentKind(value) {
|
|
91
|
-
return scalarInstanceInfo(value)?.kind;
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
export function scalarArgumentValue(value, info = scalarInstanceInfo(value)) {
|
|
95
|
-
if (info === undefined) return value.value;
|
|
96
|
-
const buffer = value._buffer;
|
|
97
|
-
if (mirrorsActive) refresh(buffer);
|
|
98
|
-
const reader = info.swapped ? info.type._readerBE : info.type._reader;
|
|
99
|
-
return applyScalarReader(reader, info.type, [buffer, 0]);
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
export function scalarArgumentSnapshot(value, info = scalarInstanceInfo(value)) {
|
|
103
|
-
if (info === undefined || info.pointer || info.kind === 0 || !scalarArgumentKinds.has(info.kind)) return value;
|
|
104
|
-
let constructor = scalarArgumentTypes.get(info.kind);
|
|
105
|
-
if (constructor === undefined) {
|
|
106
|
-
constructor = function ScalarArgument() {};
|
|
107
|
-
Object.defineProperties(constructor, {
|
|
108
|
-
_isSimpleCData: { value: true },
|
|
109
|
-
_type: { value: info.kind },
|
|
110
|
-
});
|
|
111
|
-
scalarArgumentTypes.set(info.kind, constructor);
|
|
112
|
-
}
|
|
113
|
-
// Keep the inferred type, but snapshot the value before the next adapter.
|
|
114
|
-
return { constructor, value: scalarArgumentValue(value, info) };
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
export function isScalarSubclass(type) {
|
|
118
|
-
return typeof type === "function" && type._isSimpleCData === true && !simpleTypes.has(type);
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
export function scalarView(type, buffer, swapped = false) {
|
|
122
|
-
// C-owned representations must bypass application constructors and writers.
|
|
123
|
-
const base = mirrorsActive ? mirrorBase(buffer) : undefined;
|
|
124
|
-
const value = Object.create(base === undefined ? type.prototype : mirroredPrototype(type));
|
|
125
|
-
value._buffer = buffer;
|
|
126
|
-
if (base !== undefined) value[kMirrorBase] = base;
|
|
127
|
-
const useSwapped = !!(swapped && type._readerBE && type._writerBE);
|
|
128
|
-
registerScalarInstance(value, type, useSwapped);
|
|
129
|
-
if (useSwapped) {
|
|
130
|
-
Object.defineProperty(value, "value", {
|
|
131
|
-
get() {
|
|
132
|
-
if (base !== undefined) refresh(buffer);
|
|
133
|
-
return type._readerBE(buffer, 0);
|
|
134
|
-
},
|
|
135
|
-
set(v) {
|
|
136
|
-
type._writerBE(buffer, 0, v);
|
|
137
|
-
if (base !== undefined) flush(buffer);
|
|
138
|
-
},
|
|
139
|
-
});
|
|
140
|
-
}
|
|
141
|
-
return value;
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
export function scalarReader(type, reader, swapped = false) {
|
|
145
|
-
return isScalarSubclass(type) ? (buffer, offset) => scalarView(type, buffer.subarray(offset, offset + type._size), swapped) : reader;
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
export function scalarOutparam() {
|
|
149
|
-
return isScalarSubclass(this.constructor) ? this : this.value;
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
/**
|
|
153
|
-
* @file helpers.js
|
|
154
|
-
* @module structures/helpers
|
|
155
|
-
* @description Helper functions and type checks for structure and type system.
|
|
156
|
-
*
|
|
157
|
-
* This module provides utility functions for working with structures, arrays,
|
|
158
|
-
* and bitfields in the node-ctypes type system.
|
|
159
|
-
*
|
|
160
|
-
* @example
|
|
161
|
-
* ```javascript
|
|
162
|
-
* import { bitfield, _isStruct, _isArrayType } from './structures/helpers.js';
|
|
163
|
-
*
|
|
164
|
-
* // Create a bitfield
|
|
165
|
-
* const flags = bitfield(c_uint32, 8); // 8-bit field
|
|
166
|
-
*
|
|
167
|
-
* // Check if type is a struct
|
|
168
|
-
* if (_isStruct(myType)) {
|
|
169
|
-
* // Handle struct type
|
|
170
|
-
* }
|
|
171
|
-
* ```
|
|
172
|
-
*/
|
|
1
|
+
/** Field declarations, accessors and value assignment for aggregate types. */
|
|
2
|
+
import { resolveParameter } from "../../core/parameters.js";
|
|
3
|
+
import { copyInstance, keepAlive, keepFunctionOwner } from "../../memory/ownership.js";
|
|
173
4
|
|
|
174
5
|
/**
|
|
175
6
|
* Creates a bitfield definition.
|
|
@@ -318,20 +149,6 @@ export function simpleFieldWriter(fieldType, writer, offset) {
|
|
|
318
149
|
};
|
|
319
150
|
}
|
|
320
151
|
|
|
321
|
-
/**
|
|
322
|
-
* Python: a float is not an integer ("'float' object cannot be interpreted as
|
|
323
|
-
* an integer"); in JS, numbers that are not integral (or not finite).
|
|
324
|
-
*
|
|
325
|
-
* @throws {TypeError}
|
|
326
|
-
*/
|
|
327
|
-
export function notIntegral() {
|
|
328
|
-
throw new TypeError("'float' object cannot be interpreted as an integer");
|
|
329
|
-
}
|
|
330
|
-
|
|
331
|
-
export function booleanValue(value) {
|
|
332
|
-
return !!(value !== null && typeof value === "object" && value._isSimpleCDataInstance === true ? value.value : value);
|
|
333
|
-
}
|
|
334
|
-
|
|
335
152
|
/**
|
|
336
153
|
* Address stored by a pointer field assignment: a pointer instance, a
|
|
337
154
|
* CFUNCTYPE/callback object (`_as_parameter_`), a BigInt/number address,
|
|
@@ -379,144 +196,6 @@ export function funcPtrFieldType(prototype) {
|
|
|
379
196
|
return fieldType;
|
|
380
197
|
}
|
|
381
198
|
|
|
382
|
-
export function keepFunctionOwner(fn, owner) {
|
|
383
|
-
if (owner !== undefined) {
|
|
384
|
-
Object.defineProperty(fn, "_objects", { value: owner });
|
|
385
|
-
// AsyncWorker pins the native handle, not its public JS function.
|
|
386
|
-
Object.defineProperty(fn._ffi, "_objects", { value: owner });
|
|
387
|
-
}
|
|
388
|
-
return fn;
|
|
389
|
-
}
|
|
390
|
-
|
|
391
|
-
// Oggetti tenuti vivi dalla memoria che contiene i loro indirizzi, per
|
|
392
|
-
// ArrayBuffer e offset assoluto: tutte le view sulla stessa memoria (istanza,
|
|
393
|
-
// struct annidata, from_buffer) condividono la stessa tabella.
|
|
394
|
-
const keptObjects = new WeakMap();
|
|
395
|
-
const memoryOwners = new WeakMap();
|
|
396
|
-
// Address-backed aliases share the reference table of their known owner.
|
|
397
|
-
const memoryDomains = new WeakMap();
|
|
398
|
-
export const kPointerMemory = Symbol("pointerMemory");
|
|
399
|
-
|
|
400
|
-
export function memoryDomain(buf) {
|
|
401
|
-
return memoryDomains.get(buf.buffer) ?? { root: buf.buffer, offset: 0n };
|
|
402
|
-
}
|
|
403
|
-
|
|
404
|
-
function memoryPosition(buf, offset) {
|
|
405
|
-
return BigInt(buf.byteOffset + offset) + (memoryDomains.get(buf.buffer)?.offset ?? 0n);
|
|
406
|
-
}
|
|
407
|
-
|
|
408
|
-
export function shareMemory(buf, memory, position) {
|
|
409
|
-
memoryDomains.set(buf.buffer, { root: memory.root, offset: position - BigInt(buf.byteOffset) });
|
|
410
|
-
return keepMemoryOwner(buf, memory);
|
|
411
|
-
}
|
|
412
|
-
|
|
413
|
-
// Attach to the backing store, so subarrays and typed arrays keep the lease too.
|
|
414
|
-
export function keepMemoryOwner(buf, owner) {
|
|
415
|
-
if (owner === undefined || owner === null) return buf;
|
|
416
|
-
let owners = memoryOwners.get(buf.buffer);
|
|
417
|
-
if (owners === undefined) memoryOwners.set(buf.buffer, (owners = new Set()));
|
|
418
|
-
owners.add(owner);
|
|
419
|
-
return buf;
|
|
420
|
-
}
|
|
421
|
-
|
|
422
|
-
function storedAddress(buf, offset) {
|
|
423
|
-
return POINTER_SIZE === 8 ? buf.readBigUInt64LE(offset) : BigInt(buf.readUInt32LE(offset));
|
|
424
|
-
}
|
|
425
|
-
|
|
426
|
-
export function pointerOwner(buf, offset, address) {
|
|
427
|
-
const root = memoryDomains.get(buf.buffer)?.root ?? buf.buffer;
|
|
428
|
-
const kept = keptObjects.get(root);
|
|
429
|
-
if (kept === undefined) return buf;
|
|
430
|
-
const position = memoryPosition(buf, offset);
|
|
431
|
-
const reference = kept.get(position);
|
|
432
|
-
if (reference !== undefined && reference.address !== (address ?? storedAddress(buf, offset))) {
|
|
433
|
-
kept.delete(position);
|
|
434
|
-
return buf;
|
|
435
|
-
}
|
|
436
|
-
return reference?.owner ?? buf;
|
|
437
|
-
}
|
|
438
|
-
|
|
439
|
-
export function inDllBuffer(library, name, size, ptrToBuffer) {
|
|
440
|
-
const lib = library?._lib ?? library;
|
|
441
|
-
if (typeof lib?._symbolView !== "function") throw new TypeError("in_dll: first arg must be a Library (CDLL/WinDLL)");
|
|
442
|
-
const { address, owner } = lib._symbolView(name);
|
|
443
|
-
return keepMemoryOwner(ptrToBuffer(address, size), owner);
|
|
444
|
-
}
|
|
445
|
-
|
|
446
|
-
function pointerSlots(type, offset = 0, size) {
|
|
447
|
-
if (type?._isPointerValued || type?._isFuncPtr || type?._pointerTo !== undefined) return [[offset, type._size ?? type.size ?? size]];
|
|
448
|
-
if (type?._isArrayType) {
|
|
449
|
-
const slots = [];
|
|
450
|
-
const elementSize = type.length === 0 ? 0 : type.getSize() / type.length;
|
|
451
|
-
const elements = pointerSlots(type.elementType, 0, elementSize);
|
|
452
|
-
if (elements.length === 0) return slots;
|
|
453
|
-
for (let i = 0; i < type.length; i++) {
|
|
454
|
-
for (const [position, width] of elements) slots.push([offset + i * elementSize + position, width]);
|
|
455
|
-
}
|
|
456
|
-
return slots;
|
|
457
|
-
}
|
|
458
|
-
const def = typeof type?._buildStruct === "function" ? (type._structDef ?? type._buildStruct()) : type;
|
|
459
|
-
const slots = [];
|
|
460
|
-
for (const field of def?.fields ?? []) {
|
|
461
|
-
if (field.isPointer) slots.push([offset + field.offset, field.size]);
|
|
462
|
-
else slots.push(...pointerSlots(field.type, offset + field.offset, field.size));
|
|
463
|
-
}
|
|
464
|
-
return slots;
|
|
465
|
-
}
|
|
466
|
-
|
|
467
|
-
/**
|
|
468
|
-
* Keep `value` alive as long as the memory of `targetBuf`, like Python ctypes
|
|
469
|
-
* `_objects`: an object whose address is stored in the buffer (string,
|
|
470
|
-
* pointer, callback) must not be garbage collected while native code can
|
|
471
|
-
* still read that address. The table belongs to the memory, not to the view,
|
|
472
|
-
* so assigning through a nested structure keeps the object alive with the
|
|
473
|
-
* outer one.
|
|
474
|
-
*
|
|
475
|
-
* @param {Uint8Array} targetBuf - Buffer holding the address
|
|
476
|
-
* @param {number} offset - Offset of the slot in `targetBuf`
|
|
477
|
-
* @param {*} value - Referenced object (or null to clear the slot)
|
|
478
|
-
*/
|
|
479
|
-
export function keepAlive(targetBuf, offset, value) {
|
|
480
|
-
const position = memoryPosition(targetBuf, offset);
|
|
481
|
-
const root = memoryDomains.get(targetBuf.buffer)?.root ?? targetBuf.buffer;
|
|
482
|
-
let kept = keptObjects.get(root);
|
|
483
|
-
if (value === null || (typeof value !== "object" && typeof value !== "function")) {
|
|
484
|
-
kept?.delete(position);
|
|
485
|
-
return;
|
|
486
|
-
}
|
|
487
|
-
if (kept === undefined) {
|
|
488
|
-
kept = new Map();
|
|
489
|
-
keptObjects.set(root, kept);
|
|
490
|
-
}
|
|
491
|
-
// A pointer wrapper can later be repointed; retain its current memory.
|
|
492
|
-
if (value._pointerType !== undefined) value = value._buffer ?? value._objects ?? value;
|
|
493
|
-
else if (value._isSimpleCDataInstance && value.constructor._isPointerValued) value = pointerOwner(value._buffer, 0);
|
|
494
|
-
kept.set(position, { owner: value, address: storedAddress(targetBuf, offset) });
|
|
495
|
-
}
|
|
496
|
-
|
|
497
|
-
/**
|
|
498
|
-
* Object kept alive at `offset` of `buf` (see {@link keepAlive}).
|
|
499
|
-
*
|
|
500
|
-
* @param {Uint8Array} buf - Buffer
|
|
501
|
-
* @param {number} offset - Offset in `buf`
|
|
502
|
-
* @returns {*} The object, or undefined
|
|
503
|
-
*/
|
|
504
|
-
export function keptObject(buf, offset) {
|
|
505
|
-
const root = memoryDomains.get(buf.buffer)?.root ?? buf.buffer;
|
|
506
|
-
return keptObjects.get(root)?.get(memoryPosition(buf, offset))?.owner;
|
|
507
|
-
}
|
|
508
|
-
|
|
509
|
-
export function clearKeepAlives(buf, offset, size) {
|
|
510
|
-
const root = memoryDomains.get(buf.buffer)?.root ?? buf.buffer;
|
|
511
|
-
const kept = keptObjects.get(root);
|
|
512
|
-
if (kept === undefined) return;
|
|
513
|
-
const start = BigInt(memoryPosition(buf, offset));
|
|
514
|
-
const end = start + BigInt(size);
|
|
515
|
-
for (const position of kept.keys()) {
|
|
516
|
-
if (position >= start && position < end) kept.delete(position);
|
|
517
|
-
}
|
|
518
|
-
}
|
|
519
|
-
|
|
520
199
|
/**
|
|
521
200
|
* Write a pointer field (struct, union or array element) and keep the
|
|
522
201
|
* assigned object alive with the buffer, as Python ctypes `_objects`.
|
|
@@ -561,47 +240,3 @@ export function fieldsOf(value) {
|
|
|
561
240
|
}
|
|
562
241
|
return value;
|
|
563
242
|
}
|
|
564
|
-
|
|
565
|
-
/**
|
|
566
|
-
* Copy a struct/union instance into a nested field: the bytes (as Python
|
|
567
|
-
* does) plus the objects it keeps alive (strings, pointers, callbacks), so
|
|
568
|
-
* the addresses copied with them stay valid.
|
|
569
|
-
*
|
|
570
|
-
* @param {Buffer} buf - Target buffer
|
|
571
|
-
* @param {number} offset - Field offset
|
|
572
|
-
* @param {number} size - Field size
|
|
573
|
-
* @param {Object|Buffer} value - Instance with a `_buffer`, or source bytes
|
|
574
|
-
* @param {number} [sourceOffset=0] - Byte offset in the source
|
|
575
|
-
* @param {Function|Object} [type] - Layout used to retain references into leased memory
|
|
576
|
-
*/
|
|
577
|
-
export function copyInstance(buf, offset, size, value, sourceOffset = 0, type) {
|
|
578
|
-
const bytes = value._buffer ?? value;
|
|
579
|
-
const source = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
580
|
-
if (mirrorsActive) refresh(source, sourceOffset, size);
|
|
581
|
-
const start = memoryPosition(source, sourceOffset);
|
|
582
|
-
const sourceRoot = memoryDomains.get(source.buffer)?.root ?? source.buffer;
|
|
583
|
-
const sourceKept = keptObjects.get(sourceRoot);
|
|
584
|
-
const snapshot = new Map();
|
|
585
|
-
if (sourceKept !== undefined) {
|
|
586
|
-
for (const [position, reference] of sourceKept) {
|
|
587
|
-
if (position < start || position + BigInt(POINTER_SIZE) > start + BigInt(size)) continue;
|
|
588
|
-
const relative = Number(position - start);
|
|
589
|
-
if (reference.address === storedAddress(source, sourceOffset + relative)) snapshot.set(relative, reference.owner);
|
|
590
|
-
}
|
|
591
|
-
}
|
|
592
|
-
if (type !== undefined && memoryOwners.has(source.buffer)) {
|
|
593
|
-
for (const [position, width] of pointerSlots(type)) {
|
|
594
|
-
if (snapshot.has(position) || position + width > size) continue;
|
|
595
|
-
for (let i = 0; i < width; i++) {
|
|
596
|
-
if (source[sourceOffset + position + i] !== 0) {
|
|
597
|
-
snapshot.set(position, source);
|
|
598
|
-
break;
|
|
599
|
-
}
|
|
600
|
-
}
|
|
601
|
-
}
|
|
602
|
-
}
|
|
603
|
-
source.copy(buf, offset, sourceOffset, sourceOffset + size);
|
|
604
|
-
clearKeepAlives(buf, offset, size);
|
|
605
|
-
for (const [relative, object] of snapshot) keepAlive(buf, offset + relative, object);
|
|
606
|
-
if (mirrorsActive) flush(buf, offset, size);
|
|
607
|
-
}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
/** Resolve aggregate field declarations before compiling their accessors or ABI descriptors. */
|
|
2
|
+
import { fieldEntries, funcPtrFieldType } from "./common.js";
|
|
3
|
+
import { computeLayout, isGccLayout } from "./layout.js";
|
|
4
|
+
|
|
5
|
+
function nestedField(name, type, cls, anonymous, isStruct) {
|
|
6
|
+
const field = { name, type };
|
|
7
|
+
if (anonymous || cls !== undefined) field.cls = cls;
|
|
8
|
+
// `fields` is public: unions enumerate the kind flags before size/alignment.
|
|
9
|
+
if (!isStruct) {
|
|
10
|
+
field.isNested = true;
|
|
11
|
+
if (anonymous) field.isAnonymous = true;
|
|
12
|
+
}
|
|
13
|
+
field.size = type.size;
|
|
14
|
+
field.alignment = type.alignment;
|
|
15
|
+
if (isStruct) {
|
|
16
|
+
field.isNested = true;
|
|
17
|
+
if (anonymous) field.isAnonymous = true;
|
|
18
|
+
}
|
|
19
|
+
return field;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function bitField(name, declaration, native, isStruct) {
|
|
23
|
+
if (isStruct) {
|
|
24
|
+
const { baseType, bits, baseSize } = declaration;
|
|
25
|
+
return { name, type: baseType, size: 0, alignment: Math.min(baseSize, native.POINTER_SIZE), isBitField: true, bitSize: bits, baseSize };
|
|
26
|
+
}
|
|
27
|
+
const size = declaration.baseSize;
|
|
28
|
+
const alignment = Math.min(size, native.POINTER_SIZE);
|
|
29
|
+
const bitSize = declaration.bits;
|
|
30
|
+
const baseSize = declaration.baseSize;
|
|
31
|
+
return { name, type: declaration.baseType, isBitField: true, bitSize, baseSize, size, alignment };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function arrayField(name, declaration, { isStruct, swapped, sizeof, native }) {
|
|
35
|
+
const type = swapped ? (declaration._swappedType ?? declaration) : declaration;
|
|
36
|
+
if (isStruct) {
|
|
37
|
+
const elementSize = sizeof(type.elementType);
|
|
38
|
+
const alignment = typeof type.getAlignment === "function" ? type.getAlignment() : Math.min(elementSize, native.POINTER_SIZE);
|
|
39
|
+
return { name, type, size: type.getSize(), alignment, isArray: true };
|
|
40
|
+
}
|
|
41
|
+
// Union views use the swapped type, but their layout comes from the declaration.
|
|
42
|
+
const size = declaration.getSize();
|
|
43
|
+
const alignment = typeof declaration.getAlignment === "function" ? declaration.getAlignment() : Math.min(sizeof(declaration.elementType), native.POINTER_SIZE);
|
|
44
|
+
return { name, type, isArray: true, size, alignment };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function pointerType(type) {
|
|
48
|
+
return typeof type === "function" ? funcPtrFieldType(type) : type;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function describeField(name, type, context) {
|
|
52
|
+
const { isStruct, Structure, native, _isStruct, _isArrayType, _isBitField } = context;
|
|
53
|
+
if (typeof type === "object" && type !== null && type.anonymous === true && type.type) {
|
|
54
|
+
let { type: def, cls } = type;
|
|
55
|
+
if (typeof def === "function" && typeof def._buildStruct === "function") {
|
|
56
|
+
cls = def;
|
|
57
|
+
def = def._finalizeFields();
|
|
58
|
+
}
|
|
59
|
+
if (def === null || typeof def !== "object" || !Array.isArray(def.fields)) throw new TypeError(`anonymous field "${name}" must be a structure or union`);
|
|
60
|
+
return nestedField(name, def, cls, true, isStruct);
|
|
61
|
+
}
|
|
62
|
+
// Structs recognize bitfields before nested/array protocols, unions after them.
|
|
63
|
+
if (isStruct && _isBitField(type)) return bitField(name, type, native, true);
|
|
64
|
+
const isClass = typeof type === "function" && type.prototype instanceof Structure;
|
|
65
|
+
if (isClass || _isStruct(type)) {
|
|
66
|
+
const finalize = isStruct ? isClass : typeof type === "function" && typeof type._buildStruct === "function";
|
|
67
|
+
return nestedField(name, finalize ? type._finalizeFields() : type, finalize ? type : undefined, false, isStruct);
|
|
68
|
+
}
|
|
69
|
+
if (_isArrayType(type)) return arrayField(name, type, context);
|
|
70
|
+
if (!isStruct && _isBitField(type)) return bitField(name, type, native, false);
|
|
71
|
+
if ((typeof type === "object" && type !== null && type._pointerTo !== undefined) || (typeof type === "function" && type._isFuncPtr === true)) {
|
|
72
|
+
if (isStruct) return { name, type: pointerType(type), size: native.POINTER_SIZE, alignment: native.POINTER_SIZE, isPointer: true };
|
|
73
|
+
const size = native.POINTER_SIZE;
|
|
74
|
+
const alignment = native.POINTER_SIZE;
|
|
75
|
+
return { name, type: pointerType(type), isPointer: true, size, alignment };
|
|
76
|
+
}
|
|
77
|
+
if (!(typeof type === "function" && type._isSimpleCData)) throw new TypeError(`${isStruct ? "struct" : "union"} field "${name}": type must be a SimpleCData class, struct, union, or array`);
|
|
78
|
+
const size = type._size;
|
|
79
|
+
return { name, type, size, alignment: Math.min(isStruct ? type._size : size, native.POINTER_SIZE) };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function declareFields(fields, options, context) {
|
|
83
|
+
const { isStruct, pack, swapped } = context;
|
|
84
|
+
const gccLayout = isGccLayout(options.layout, pack, options.pack != null || options.packed === true);
|
|
85
|
+
const base = options.base ?? null;
|
|
86
|
+
const fieldDefs = base ? base.fields.map((f) => ({ ...f })) : [];
|
|
87
|
+
const names = new Set(fieldDefs.map((f) => f.name));
|
|
88
|
+
const own = [];
|
|
89
|
+
for (const [name, type] of fieldEntries(fields)) {
|
|
90
|
+
if (isStruct && (typeof name !== "string" || (!Array.isArray(fields) && !(fields instanceof Map) && name.trim().length === 0))) throw new TypeError("Field name must be a non-empty string");
|
|
91
|
+
if (names.has(name)) throw new TypeError(`Duplicate field name: ${name}`);
|
|
92
|
+
names.add(name);
|
|
93
|
+
own.push(describeField(name, type, context));
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const layout = computeLayout(
|
|
97
|
+
own.map((f) => (f.isBitField ? { name: f.name, size: f.baseSize, align: f.alignment, bitSize: f.bitSize } : { name: f.name, size: f.size, align: f.alignment })),
|
|
98
|
+
{ isStruct, gccLayout, pack, align: options.align ?? 1, base, bigEndian: swapped },
|
|
99
|
+
);
|
|
100
|
+
own.forEach((f, i) => {
|
|
101
|
+
f.offset = layout.offsets[i].offset;
|
|
102
|
+
if (f.isBitField) f.bitOffset = layout.offsets[i].bitOffset;
|
|
103
|
+
f.naturalAlignment = f.alignment;
|
|
104
|
+
if (pack) f.alignment = Math.min(f.alignment, pack);
|
|
105
|
+
f.swapped = swapped;
|
|
106
|
+
fieldDefs.push(f);
|
|
107
|
+
});
|
|
108
|
+
const fieldMap = new Map();
|
|
109
|
+
for (const field of fieldDefs) fieldMap.set(field.name, field);
|
|
110
|
+
return { base, fieldDefs, fieldMap, size: layout.size, alignment: layout.alignment };
|
|
111
|
+
}
|
|
@@ -70,76 +70,63 @@ export function computeLayout(fields, { isStruct, gccLayout, pack = 0, align = 1
|
|
|
70
70
|
let alignment = Math.max(align, 1);
|
|
71
71
|
if (base) alignment = Math.max(base.alignment, alignment);
|
|
72
72
|
|
|
73
|
-
let
|
|
74
|
-
|
|
75
|
-
let
|
|
76
|
-
let
|
|
77
|
-
let
|
|
78
|
-
let unionSize = 0;
|
|
79
|
-
|
|
80
|
-
if (base) {
|
|
81
|
-
structSize = base.size;
|
|
82
|
-
if (gccLayout) nextBitOffset = structSize * 8;
|
|
83
|
-
else nextByteOffset = structSize;
|
|
84
|
-
unionSize = isStruct ? 0 : base.size;
|
|
85
|
-
}
|
|
73
|
+
let size = base ? base.size : 0;
|
|
74
|
+
let unionSize = isStruct ? 0 : size;
|
|
75
|
+
let nextBit = size * 8; // SysV can reuse the tail of a partially occupied byte.
|
|
76
|
+
let msUnitSize = 0;
|
|
77
|
+
let msBitsLeft = 0;
|
|
86
78
|
|
|
87
79
|
const offsets = [];
|
|
88
80
|
for (const field of fields) {
|
|
89
81
|
if (!isStruct) {
|
|
90
|
-
|
|
91
|
-
lastFieldBitSize = 0;
|
|
92
|
-
nextBitOffset = 0;
|
|
93
|
-
nextByteOffset = 0;
|
|
82
|
+
size = nextBit = msUnitSize = msBitsLeft = 0;
|
|
94
83
|
}
|
|
95
84
|
|
|
96
|
-
const isBitField = field.bitSize !== undefined && field.bitSize !== null;
|
|
97
85
|
const typeSize = field.size;
|
|
98
|
-
const
|
|
99
|
-
const
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
// the field must also contain its last bit, otherwise pad to the next one.
|
|
111
|
-
const slotEndBit = roundDown(nextBitOffset, typeBitAlign) + typeBitSize;
|
|
112
|
-
if (nextBitOffset + bitSize > slotEndBit) {
|
|
113
|
-
nextBitOffset = roundUp(nextBitOffset, typeBitAlign);
|
|
114
|
-
}
|
|
115
|
-
offset = roundDown(nextBitOffset, typeBitAlign) / 8;
|
|
116
|
-
if (isBitField) bitOffset = nextBitOffset - 8 * offset;
|
|
117
|
-
nextBitOffset += bitSize;
|
|
118
|
-
structSize = roundUp(nextBitOffset, 8) / 8;
|
|
86
|
+
const naturalAlign = field.align || 1;
|
|
87
|
+
const typeAlign = !gccLayout && pack ? Math.min(pack, naturalAlign) : naturalAlign;
|
|
88
|
+
const bitSize = field.bitSize;
|
|
89
|
+
if (bitSize == null) {
|
|
90
|
+
// MS reuses an empty allocation unit for another zero-sized field.
|
|
91
|
+
const reuseEmptyUnit = !gccLayout && typeSize === 0 && msUnitSize === 0;
|
|
92
|
+
const offset = reuseEmptyUnit ? size : roundUp(size, typeAlign);
|
|
93
|
+
size = offset + typeSize;
|
|
94
|
+
nextBit = size * 8;
|
|
95
|
+
msUnitSize = typeSize;
|
|
96
|
+
msBitsLeft = 0;
|
|
97
|
+
offsets.push({ offset });
|
|
119
98
|
} else {
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
nextByteOffset = roundUp(nextByteOffset, typeAlign) + typeSize;
|
|
124
|
-
lastFieldBitSize = typeBitSize;
|
|
125
|
-
nextBitOffset = -lastFieldBitSize;
|
|
99
|
+
const typeBitSize = typeSize * 8;
|
|
100
|
+
if (!Number.isInteger(bitSize) || bitSize <= 0 || bitSize > typeBitSize) {
|
|
101
|
+
throw new RangeError(`number of bits invalid for bit field ${JSON.stringify(field.name)}`);
|
|
126
102
|
}
|
|
127
|
-
offset = nextByteOffset - lastFieldBitSize / 8;
|
|
128
|
-
if (isBitField) bitOffset = lastFieldBitSize + nextBitOffset;
|
|
129
|
-
nextBitOffset += bitSize;
|
|
130
|
-
structSize = nextByteOffset;
|
|
131
|
-
}
|
|
132
103
|
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
104
|
+
let offset, bitOffset;
|
|
105
|
+
if (gccLayout) {
|
|
106
|
+
const bitAlign = typeAlign * 8;
|
|
107
|
+
// The aligned slot containing the first bit must also contain the last.
|
|
108
|
+
const slotEnd = roundDown(nextBit, bitAlign) + typeBitSize;
|
|
109
|
+
if (nextBit + bitSize > slotEnd) nextBit = roundUp(nextBit, bitAlign);
|
|
110
|
+
offset = roundDown(nextBit, bitAlign) / 8;
|
|
111
|
+
bitOffset = nextBit - offset * 8;
|
|
112
|
+
nextBit += bitSize;
|
|
113
|
+
size = Math.ceil(nextBit / 8);
|
|
114
|
+
} else {
|
|
115
|
+
if (msUnitSize !== typeSize || msBitsLeft < bitSize) {
|
|
116
|
+
size = roundUp(size, typeAlign) + typeSize;
|
|
117
|
+
msUnitSize = typeSize;
|
|
118
|
+
msBitsLeft = typeBitSize;
|
|
119
|
+
}
|
|
120
|
+
offset = size - typeSize;
|
|
121
|
+
bitOffset = typeBitSize - msBitsLeft;
|
|
122
|
+
msBitsLeft -= bitSize;
|
|
123
|
+
}
|
|
124
|
+
offsets.push({ offset, bitOffset: bigEndian ? typeBitSize - bitSize - bitOffset : bitOffset });
|
|
136
125
|
}
|
|
137
|
-
|
|
138
|
-
offsets.push(isBitField ? { offset, bitOffset } : { offset });
|
|
139
126
|
alignment = Math.max(alignment, typeAlign);
|
|
140
|
-
if (!isStruct) unionSize = Math.max(unionSize,
|
|
127
|
+
if (!isStruct) unionSize = Math.max(unionSize, size);
|
|
141
128
|
}
|
|
142
129
|
|
|
143
|
-
const totalSize = isStruct ?
|
|
130
|
+
const totalSize = isStruct ? size : unionSize;
|
|
144
131
|
return { offsets, size: roundUp(totalSize, alignment), alignment };
|
|
145
132
|
}
|