node-ctypes 2.3.0 → 2.4.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 +932 -0
- package/README.md +446 -99
- 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 +79 -62
- package/lib/core/callback.js +7 -3
- package/lib/core/conversions.js +226 -34
- package/lib/core/funcptr.js +115 -57
- package/lib/core/types.js +7 -2
- package/lib/index.d.ts +119 -54
- package/lib/index.js +10 -8
- package/lib/memory/buffer.js +39 -8
- package/lib/memory/operations.js +4 -6
- package/lib/memory/pointer.js +105 -38
- package/lib/platform/win_types.js +8 -3
- package/lib/structures/Structure.js +8 -39
- package/lib/structures/helpers/array.js +31 -12
- package/lib/structures/helpers/bitfield.js +17 -8
- package/lib/structures/helpers/common.js +218 -29
- package/lib/structures/helpers/layout.js +17 -3
- package/lib/structures/helpers/struct.js +25 -26
- package/lib/structures/helpers/union.js +32 -22
- package/lib/types/SimpleCData.js +11 -32
- package/lib/types/primitives.js +34 -16
- package/lib/utils/cache.js +34 -2
- package/package.json +3 -1
|
@@ -105,25 +105,30 @@
|
|
|
105
105
|
* ```
|
|
106
106
|
*/
|
|
107
107
|
import { encodeWide, decodeWide } from "../../memory/buffer.js";
|
|
108
|
-
import { funcPtrFieldType, writePointerField } from "./common.js";
|
|
108
|
+
import { copyInstance, funcPtrFieldType, pointerOwner, scalarReader, simpleFieldWriter, writePointerField } from "./common.js";
|
|
109
109
|
import { buildWrapper } from "./wrap.js";
|
|
110
110
|
import { flush, isMirror, mirrorsActive, refresh } from "../../memory/mirror.js";
|
|
111
111
|
|
|
112
112
|
// Python: gli array di c_char / c_wchar (anche come campi struct) hanno un
|
|
113
113
|
// `.value` stringa fino al primo NUL; quelli di c_char anche `.raw` (bytes).
|
|
114
|
-
function charArrayValue(buf, charKind, wcharSize) {
|
|
114
|
+
function charArrayValue(buf, charKind, wcharSize, swapped) {
|
|
115
115
|
if (charKind === "char") {
|
|
116
116
|
const end = buf.indexOf(0);
|
|
117
117
|
return buf.toString("utf8", 0, end === -1 ? buf.length : end);
|
|
118
118
|
}
|
|
119
|
+
if (swapped) {
|
|
120
|
+
buf = Buffer.from(buf);
|
|
121
|
+
wcharSize === 2 ? buf.swap16() : buf.swap32();
|
|
122
|
+
}
|
|
119
123
|
return decodeWide(buf, wcharSize);
|
|
120
124
|
}
|
|
121
125
|
|
|
122
|
-
function setCharArrayValue(buf, charKind, wcharSize, value, message) {
|
|
126
|
+
function setCharArrayValue(buf, charKind, wcharSize, value, message, swapped) {
|
|
123
127
|
const units = charKind === "char" ? (Buffer.isBuffer(value) ? value : Buffer.from(String(value), "utf8")) : encodeWide(String(value), wcharSize);
|
|
124
128
|
if (units.length > buf.length) {
|
|
125
129
|
throw new RangeError(message(units.length / (charKind === "char" ? 1 : wcharSize), buf.length / (charKind === "char" ? 1 : wcharSize)));
|
|
126
130
|
}
|
|
131
|
+
if (swapped && charKind === "wchar") wcharSize === 2 ? units.swap16() : units.swap32();
|
|
127
132
|
units.copy(buf);
|
|
128
133
|
const unit = charKind === "char" ? 1 : wcharSize;
|
|
129
134
|
if (units.length + unit <= buf.length) {
|
|
@@ -179,7 +184,7 @@ function charSlice(...args) {
|
|
|
179
184
|
return Array.prototype.slice.apply(this, args).join("");
|
|
180
185
|
}
|
|
181
186
|
|
|
182
|
-
export function array(elementType, count, sizeof, alloc, readValue, writeValue, Structure, Union, ArrayType, voidPointerType, ptrToBuffer) {
|
|
187
|
+
export function array(elementType, count, sizeof, alloc, readValue, writeValue, Structure, Union, ArrayType, voidPointerType, ptrToBuffer, swapped = false) {
|
|
183
188
|
// Validate elementType: accept SimpleCData classes, Structure/Union classes,
|
|
184
189
|
// or native CType-like objects.
|
|
185
190
|
const isSimple = typeof elementType === "function" && elementType._isSimpleCData;
|
|
@@ -194,6 +199,7 @@ export function array(elementType, count, sizeof, alloc, readValue, writeValue,
|
|
|
194
199
|
if (!isSimple && !isStruct && !isStructDef && !isNativeTypeObj && !isArrayElem && !isPointerElem) {
|
|
195
200
|
throw new TypeError("array elementType must be a SimpleCData class or a Structure/Union class");
|
|
196
201
|
}
|
|
202
|
+
if (swapped && isArrayElem) elementType = elementType._swappedType ?? elementType;
|
|
197
203
|
|
|
198
204
|
const elementSize = sizeof(elementType);
|
|
199
205
|
// Array alignment == element alignment (C standard), NOT element size.
|
|
@@ -233,14 +239,14 @@ export function array(elementType, count, sizeof, alloc, readValue, writeValue,
|
|
|
233
239
|
// Precalcolati una volta per tipo: l'handler del Proxy li ripeteva ad ogni
|
|
234
240
|
// accesso indicizzato (instanceof Structure/Union + dispatch di readValue).
|
|
235
241
|
const isStructElem = typeof elementType === "function" && (elementType.prototype instanceof Structure || elementType.prototype instanceof Union);
|
|
236
|
-
const elemReader = isSimple ? elementType._reader : null;
|
|
237
|
-
const elemWriter = isSimple ? elementType._writer : null;
|
|
242
|
+
const elemReader = isSimple ? scalarReader(elementType, swapped && elementType._readerBE ? elementType._readerBE : elementType._reader, swapped) : null;
|
|
243
|
+
const elemWriter = isSimple ? simpleFieldWriter(elementType, swapped && elementType._writerBE ? elementType._writerBE : elementType._writer, 0) : null;
|
|
238
244
|
|
|
239
245
|
// Array di caratteri (Python: c_char * n / c_wchar * n): `.value` e `.raw`.
|
|
240
246
|
const charKind = isSimple ? elementType._charKind : undefined;
|
|
241
247
|
const tooLong = charKind === "char" ? () => "byte string too long" : () => "string too long";
|
|
242
|
-
const getValue = charKind === undefined ? undefined : (buf) => charArrayValue(buf, charKind, elementSize);
|
|
243
|
-
const setValue = charKind === undefined ? undefined : (buf, value, message = tooLong) => setCharArrayValue(buf, charKind, elementSize, value, message);
|
|
248
|
+
const getValue = charKind === undefined ? undefined : (buf) => charArrayValue(buf, charKind, elementSize, swapped);
|
|
249
|
+
const setValue = charKind === undefined ? undefined : (buf, value, message = tooLong) => setCharArrayValue(buf, charKind, elementSize, value, message, swapped);
|
|
244
250
|
const setRaw = (buf, value) => {
|
|
245
251
|
const bytes = Buffer.isBuffer(value) ? value : Buffer.from(String(value), "utf8");
|
|
246
252
|
if (bytes.length > buf.length) throw new RangeError("byte string too long");
|
|
@@ -252,7 +258,8 @@ export function array(elementType, count, sizeof, alloc, readValue, writeValue,
|
|
|
252
258
|
const pointerElemType = !isPointerElem ? null : typeof elementType === "function" ? funcPtrFieldType(elementType) : elementType;
|
|
253
259
|
const readPointer = (target, off) => {
|
|
254
260
|
const address = elementSize === 8 ? target.readBigUInt64LE(off) : BigInt(target.readUInt32LE(off));
|
|
255
|
-
|
|
261
|
+
const owner = pointerOwner(target, off, address);
|
|
262
|
+
return address === 0n ? null : pointerElemType.fromAddress(address, owner);
|
|
256
263
|
};
|
|
257
264
|
const writePointer = (target, off, value) => writePointerField(target, off, value, elementSize);
|
|
258
265
|
|
|
@@ -290,13 +297,13 @@ export function array(elementType, count, sizeof, alloc, readValue, writeValue,
|
|
|
290
297
|
const inner = target.subarray(off, off + elementSize);
|
|
291
298
|
const source = value !== null && typeof value === "object" && Buffer.isBuffer(value._buffer) ? value._buffer : value;
|
|
292
299
|
if (Buffer.isBuffer(source)) {
|
|
293
|
-
|
|
300
|
+
copyInstance(inner, 0, elementSize, value, 0, elementType);
|
|
294
301
|
} else if (source !== null && typeof source === "object" && typeof source.length === "number") {
|
|
295
302
|
const view = elementType.wrap(inner);
|
|
296
303
|
for (let i = 0; i < Math.min(source.length, elementType.length); i++) view[i] = source[i];
|
|
297
304
|
}
|
|
298
305
|
} else if (elemWriter !== null && off + elementSize <= target.length) {
|
|
299
|
-
elemWriter(target,
|
|
306
|
+
elemWriter(target, value, off);
|
|
300
307
|
} else {
|
|
301
308
|
writeValue(target, elementType, value, off);
|
|
302
309
|
}
|
|
@@ -510,7 +517,7 @@ export function array(elementType, count, sizeof, alloc, readValue, writeValue,
|
|
|
510
517
|
const bytes = bytesOf(source, "from_buffer_copy");
|
|
511
518
|
checkRange(bytes, offset, "from_buffer_copy");
|
|
512
519
|
const copy = alloc(byteSize);
|
|
513
|
-
copy
|
|
520
|
+
copyInstance(copy, 0, byteSize, bytes, offset, ArrayCType);
|
|
514
521
|
return wrap(copy);
|
|
515
522
|
};
|
|
516
523
|
const from_address = (address) => {
|
|
@@ -524,6 +531,7 @@ export function array(elementType, count, sizeof, alloc, readValue, writeValue,
|
|
|
524
531
|
const ArrayCType = function (...values) {
|
|
525
532
|
return create(values);
|
|
526
533
|
};
|
|
534
|
+
let swappedType;
|
|
527
535
|
|
|
528
536
|
// `length` (numero di elementi) è una proprietà propria non scrivibile delle
|
|
529
537
|
// funzioni: va ridefinita con defineProperties.
|
|
@@ -557,6 +565,17 @@ export function array(elementType, count, sizeof, alloc, readValue, writeValue,
|
|
|
557
565
|
|
|
558
566
|
// Helper to check if this is an ArrayType wrapper
|
|
559
567
|
_isArrayType: { value: true },
|
|
568
|
+
_swapped_: { value: swapped },
|
|
569
|
+
_swappedType: {
|
|
570
|
+
get() {
|
|
571
|
+
if (swapped) return ArrayCType;
|
|
572
|
+
if (swappedType === undefined) {
|
|
573
|
+
swappedType = array(elementType, count, sizeof, alloc, readValue, writeValue, Structure, Union, ArrayType, voidPointerType, ptrToBuffer, true);
|
|
574
|
+
Object.defineProperty(swappedType, "_baseArrayType", { value: ArrayCType });
|
|
575
|
+
}
|
|
576
|
+
return swappedType;
|
|
577
|
+
},
|
|
578
|
+
},
|
|
560
579
|
});
|
|
561
580
|
|
|
562
581
|
return ArrayCType;
|
|
@@ -24,7 +24,7 @@ const writers = {
|
|
|
24
24
|
8: { le: (buf, off, v) => buf.writeBigUInt64LE(v, off), be: (buf, off, v) => buf.writeBigUInt64BE(v, off) },
|
|
25
25
|
};
|
|
26
26
|
|
|
27
|
-
import { notIntegral } from "./common.js";
|
|
27
|
+
import { booleanValue, notIntegral } from "./common.js";
|
|
28
28
|
|
|
29
29
|
/**
|
|
30
30
|
* Reader and writer of one bitfield.
|
|
@@ -36,27 +36,36 @@ import { notIntegral } from "./common.js";
|
|
|
36
36
|
* @param {number} field.bitSize - Width in bits
|
|
37
37
|
* @param {boolean} [field.signed=false] - Signed base type
|
|
38
38
|
* @param {boolean} [field.bigEndian=false] - Unit stored big-endian
|
|
39
|
-
* @
|
|
39
|
+
* @param {boolean} [field.boolean=false] - Normalize and return boolean values
|
|
40
|
+
* @returns {{read: (buf: Buffer) => number|bigint|boolean, write: (buf: Buffer, value: number|bigint|boolean) => void}}
|
|
40
41
|
*/
|
|
41
|
-
export function bitFieldAccessors({ offset, baseSize, bitOffset, bitSize, signed = false, bigEndian = false }) {
|
|
42
|
+
export function bitFieldAccessors({ offset, baseSize, bitOffset, bitSize, signed = false, bigEndian = false, boolean = false }) {
|
|
42
43
|
const order = bigEndian ? "be" : "le";
|
|
43
44
|
const readUnit = readers[baseSize]?.[order];
|
|
44
45
|
const writeUnit = writers[baseSize]?.[order];
|
|
45
46
|
if (readUnit === undefined) throw new RangeError(`Unsupported bitfield base size: ${baseSize}`);
|
|
47
|
+
const integerValue = (value) => {
|
|
48
|
+
if (boolean) return booleanValue(value) ? 1 : 0;
|
|
49
|
+
if (typeof value === "number") {
|
|
50
|
+
if (!Number.isInteger(value)) notIntegral();
|
|
51
|
+
return value;
|
|
52
|
+
}
|
|
53
|
+
if (typeof value === "bigint" || typeof value === "boolean") return value;
|
|
54
|
+
throw new TypeError(`'${value === null ? "null" : typeof value}' object cannot be interpreted as an integer`);
|
|
55
|
+
};
|
|
46
56
|
|
|
47
57
|
if (baseSize === 8) {
|
|
48
58
|
const shift = BigInt(bitOffset);
|
|
49
59
|
const width = BigInt(bitSize);
|
|
50
60
|
const mask = ((1n << width) - 1n) << shift;
|
|
51
|
-
const toValue = bitSize <= 53 ? Number : (v) => v;
|
|
61
|
+
const toValue = boolean ? Boolean : bitSize <= 53 ? Number : (v) => v;
|
|
52
62
|
return {
|
|
53
63
|
read: (buf) => {
|
|
54
64
|
const raw = (readUnit(buf, offset) & mask) >> shift;
|
|
55
65
|
return toValue(signed ? BigInt.asIntN(bitSize, raw) : raw);
|
|
56
66
|
},
|
|
57
67
|
write: (buf, value) => {
|
|
58
|
-
|
|
59
|
-
const bits = BigInt.asUintN(bitSize, BigInt(value)) << shift;
|
|
68
|
+
const bits = BigInt.asUintN(bitSize, BigInt(integerValue(value))) << shift;
|
|
60
69
|
writeUnit(buf, offset, (readUnit(buf, offset) & ~mask) | bits);
|
|
61
70
|
},
|
|
62
71
|
};
|
|
@@ -66,13 +75,13 @@ export function bitFieldAccessors({ offset, baseSize, bitOffset, bitSize, signed
|
|
|
66
75
|
const fieldMask = bitSize === 32 ? 0xffffffff : 2 ** bitSize - 1;
|
|
67
76
|
const unitMask = (fieldMask * 2 ** bitOffset) >>> 0;
|
|
68
77
|
const unsignedValue = (value) => {
|
|
78
|
+
value = integerValue(value);
|
|
69
79
|
if (typeof value === "bigint") return Number(BigInt.asUintN(bitSize, value)) >>> 0;
|
|
70
|
-
if (typeof value === "number" && !Number.isInteger(value)) notIntegral();
|
|
71
80
|
return (Number(value) & fieldMask) >>> 0;
|
|
72
81
|
};
|
|
73
82
|
const signShift = 32 - bitSize;
|
|
74
83
|
return {
|
|
75
|
-
read: signed ? (buf) => (((readUnit(buf, offset) & unitMask) >>> bitOffset) << signShift) >> signShift : (buf) => (readUnit(buf, offset) & unitMask) >>> bitOffset,
|
|
84
|
+
read: boolean ? (buf) => (readUnit(buf, offset) & unitMask) !== 0 : signed ? (buf) => (((readUnit(buf, offset) & unitMask) >>> bitOffset) << signShift) >> signShift : (buf) => (readUnit(buf, offset) & unitMask) >>> bitOffset,
|
|
76
85
|
write: (buf, value) => {
|
|
77
86
|
const bits = (unsignedValue(value) << bitOffset) >>> 0;
|
|
78
87
|
writeUnit(buf, offset, ((readUnit(buf, offset) & ~unitMask) | bits) >>> 0);
|
|
@@ -1,3 +1,72 @@
|
|
|
1
|
+
import { flush, kMirrorBase, mirrorBase, mirroredPrototype, mirrorsActive, refresh } from "../../memory/mirror.js";
|
|
2
|
+
import { POINTER_SIZE } from "../../platform/constants.js";
|
|
3
|
+
|
|
4
|
+
const simpleTypes = new WeakSet();
|
|
5
|
+
export const byrefOwners = new WeakMap();
|
|
6
|
+
|
|
7
|
+
export function resolveParameter(value, owners) {
|
|
8
|
+
let seen;
|
|
9
|
+
for (let depth = 0; value !== null && (typeof value === "object" || typeof value === "function"); depth++) {
|
|
10
|
+
if (owners !== undefined) owners.push(value);
|
|
11
|
+
if (ArrayBuffer.isView(value) && !("_as_parameter_" in value)) return value;
|
|
12
|
+
if (value._isSimpleCDataInstance === true || value._pointerType !== undefined || value._arrayType !== undefined || value._structDef !== undefined || byrefOwners.has(value)) return value;
|
|
13
|
+
const parameter = value._as_parameter_;
|
|
14
|
+
if (parameter === undefined) return value;
|
|
15
|
+
if (depth >= 128) throw new RangeError("_as_parameter_ maximum depth exceeded");
|
|
16
|
+
seen ??= new Set();
|
|
17
|
+
if (seen.has(value)) throw new TypeError("_as_parameter_ cycle detected");
|
|
18
|
+
seen.add(value);
|
|
19
|
+
value = parameter;
|
|
20
|
+
}
|
|
21
|
+
return value;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function sourceBytes(source, offset, size, name) {
|
|
25
|
+
const bytes = source !== null && typeof source === "object" && !ArrayBuffer.isView(source) && Buffer.isBuffer(source._buffer) ? source._buffer : source;
|
|
26
|
+
if (!ArrayBuffer.isView(bytes)) throw new TypeError(`${name}: source must be a Buffer, a typed array or a ctypes instance`);
|
|
27
|
+
if (!Number.isSafeInteger(offset)) throw new TypeError(`${name}: offset must be a safe integer`);
|
|
28
|
+
if (offset < 0) throw new RangeError(`${name}: offset cannot be negative`);
|
|
29
|
+
if (bytes.byteLength - offset < size) throw new RangeError(`${name}: Buffer size too small (${bytes.byteLength} instead of at least ${size + offset} bytes)`);
|
|
30
|
+
return bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function registerSimpleType(type) {
|
|
34
|
+
simpleTypes.add(type);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function isScalarSubclass(type) {
|
|
38
|
+
return typeof type === "function" && type._isSimpleCData === true && !simpleTypes.has(type);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function scalarView(type, buffer, swapped = false) {
|
|
42
|
+
// C-owned representations must bypass application constructors and writers.
|
|
43
|
+
const base = mirrorsActive ? mirrorBase(buffer) : undefined;
|
|
44
|
+
const value = Object.create(base === undefined ? type.prototype : mirroredPrototype(type));
|
|
45
|
+
value._buffer = buffer;
|
|
46
|
+
if (base !== undefined) value[kMirrorBase] = base;
|
|
47
|
+
if (swapped && type._readerBE && type._writerBE) {
|
|
48
|
+
Object.defineProperty(value, "value", {
|
|
49
|
+
get() {
|
|
50
|
+
if (base !== undefined) refresh(buffer);
|
|
51
|
+
return type._readerBE(buffer, 0);
|
|
52
|
+
},
|
|
53
|
+
set(v) {
|
|
54
|
+
type._writerBE(buffer, 0, v);
|
|
55
|
+
if (base !== undefined) flush(buffer);
|
|
56
|
+
},
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
return value;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function scalarReader(type, reader, swapped = false) {
|
|
63
|
+
return isScalarSubclass(type) ? (buffer, offset) => scalarView(type, buffer.subarray(offset, offset + type._size), swapped) : reader;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function scalarOutparam() {
|
|
67
|
+
return isScalarSubclass(this.constructor) ? this : this.value;
|
|
68
|
+
}
|
|
69
|
+
|
|
1
70
|
/**
|
|
2
71
|
* @file helpers.js
|
|
3
72
|
* @module structures/helpers
|
|
@@ -146,24 +215,24 @@ export function _isBitField(type) {
|
|
|
146
215
|
* @param {Function} fieldType - SimpleCData class of the field
|
|
147
216
|
* @param {Function} writer - `(buf, offset, value)` writer
|
|
148
217
|
* @param {number} offset - Field offset
|
|
149
|
-
* @returns {Function} `(buf, value)` writer
|
|
218
|
+
* @returns {Function} `(buf, value, relativeOffset = 0)` writer
|
|
150
219
|
*/
|
|
151
220
|
export function simpleFieldWriter(fieldType, writer, offset) {
|
|
152
221
|
const pointerValued = fieldType._isPointerValued === true;
|
|
153
|
-
return (buf, val) => {
|
|
222
|
+
return (buf, val, relativeOffset = 0) => {
|
|
223
|
+
const fieldOffset = offset + relativeOffset;
|
|
154
224
|
if (typeof val === "object" && val !== null && val.constructor?._isSimpleCData === true) {
|
|
155
225
|
const T = val.constructor;
|
|
156
|
-
if (T._type === fieldType._type && T._size === fieldType._size) {
|
|
157
|
-
if (!pointerValued) return writer(buf,
|
|
158
|
-
|
|
159
|
-
keepAlive(buf, offset, val);
|
|
226
|
+
if (T._type === fieldType._type && T._size === fieldType._size && T._isBoolean === fieldType._isBoolean) {
|
|
227
|
+
if (!pointerValued) return writer(buf, fieldOffset, val.value);
|
|
228
|
+
copyInstance(buf, fieldOffset, T._size, val, 0, fieldType);
|
|
160
229
|
return;
|
|
161
230
|
}
|
|
162
231
|
if (!(fieldType._acceptsPointerValues === true && T._isPointerValued === true)) {
|
|
163
232
|
throw new TypeError(`incompatible types, ${T.name} instance instead of ${fieldType.name} instance`);
|
|
164
233
|
}
|
|
165
234
|
}
|
|
166
|
-
writer(buf,
|
|
235
|
+
writer(buf, fieldOffset, val);
|
|
167
236
|
};
|
|
168
237
|
}
|
|
169
238
|
|
|
@@ -177,6 +246,10 @@ export function notIntegral() {
|
|
|
177
246
|
throw new TypeError("'float' object cannot be interpreted as an integer");
|
|
178
247
|
}
|
|
179
248
|
|
|
249
|
+
export function booleanValue(value) {
|
|
250
|
+
return !!(value !== null && typeof value === "object" && value._isSimpleCDataInstance === true ? value.value : value);
|
|
251
|
+
}
|
|
252
|
+
|
|
180
253
|
/**
|
|
181
254
|
* Address stored by a pointer field assignment: a pointer instance, a
|
|
182
255
|
* CFUNCTYPE/callback object (`_as_parameter_`), a BigInt/number address,
|
|
@@ -188,10 +261,11 @@ export function notIntegral() {
|
|
|
188
261
|
* @returns {bigint} Address to store
|
|
189
262
|
*/
|
|
190
263
|
export function pointerFieldAddress(value, pointerSize) {
|
|
264
|
+
value = resolveParameter(value);
|
|
191
265
|
if (typeof value === "bigint") return value;
|
|
192
266
|
if (typeof value === "number") return BigInt(value);
|
|
193
267
|
if (value === null || value === undefined) return 0n;
|
|
194
|
-
if (typeof value === "object") {
|
|
268
|
+
if (typeof value === "object" || typeof value === "function") {
|
|
195
269
|
if (typeof value.address === "bigint") return value.address;
|
|
196
270
|
const param = value._as_parameter_;
|
|
197
271
|
if (typeof param === "bigint") return param;
|
|
@@ -213,16 +287,100 @@ const funcPtrFieldTypes = new WeakMap();
|
|
|
213
287
|
export function funcPtrFieldType(prototype) {
|
|
214
288
|
let fieldType = funcPtrFieldTypes.get(prototype);
|
|
215
289
|
if (fieldType === undefined) {
|
|
216
|
-
fieldType = {
|
|
290
|
+
fieldType = {
|
|
291
|
+
_pointerTo: prototype,
|
|
292
|
+
_isFuncPtrField: true,
|
|
293
|
+
fromAddress: (address, owner) => keepFunctionOwner(prototype(address), owner),
|
|
294
|
+
};
|
|
217
295
|
funcPtrFieldTypes.set(prototype, fieldType);
|
|
218
296
|
}
|
|
219
297
|
return fieldType;
|
|
220
298
|
}
|
|
221
299
|
|
|
300
|
+
export function keepFunctionOwner(fn, owner) {
|
|
301
|
+
if (owner !== undefined) {
|
|
302
|
+
Object.defineProperty(fn, "_objects", { value: owner });
|
|
303
|
+
// AsyncWorker pins the native handle, not its public JS function.
|
|
304
|
+
Object.defineProperty(fn._ffi, "_objects", { value: owner });
|
|
305
|
+
}
|
|
306
|
+
return fn;
|
|
307
|
+
}
|
|
308
|
+
|
|
222
309
|
// Oggetti tenuti vivi dalla memoria che contiene i loro indirizzi, per
|
|
223
310
|
// ArrayBuffer e offset assoluto: tutte le view sulla stessa memoria (istanza,
|
|
224
311
|
// struct annidata, from_buffer) condividono la stessa tabella.
|
|
225
312
|
const keptObjects = new WeakMap();
|
|
313
|
+
const memoryOwners = new WeakMap();
|
|
314
|
+
// Address-backed aliases share the reference table of their known owner.
|
|
315
|
+
const memoryDomains = new WeakMap();
|
|
316
|
+
export const kPointerMemory = Symbol("pointerMemory");
|
|
317
|
+
|
|
318
|
+
export function memoryDomain(buf) {
|
|
319
|
+
return memoryDomains.get(buf.buffer) ?? { root: buf.buffer, offset: 0n };
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
function memoryPosition(buf, offset) {
|
|
323
|
+
return BigInt(buf.byteOffset + offset) + (memoryDomains.get(buf.buffer)?.offset ?? 0n);
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
export function shareMemory(buf, memory, position) {
|
|
327
|
+
memoryDomains.set(buf.buffer, { root: memory.root, offset: position - BigInt(buf.byteOffset) });
|
|
328
|
+
return keepMemoryOwner(buf, memory);
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
// Attach to the backing store, so subarrays and typed arrays keep the lease too.
|
|
332
|
+
export function keepMemoryOwner(buf, owner) {
|
|
333
|
+
if (owner === undefined || owner === null) return buf;
|
|
334
|
+
let owners = memoryOwners.get(buf.buffer);
|
|
335
|
+
if (owners === undefined) memoryOwners.set(buf.buffer, (owners = new Set()));
|
|
336
|
+
owners.add(owner);
|
|
337
|
+
return buf;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
function storedAddress(buf, offset) {
|
|
341
|
+
return POINTER_SIZE === 8 ? buf.readBigUInt64LE(offset) : BigInt(buf.readUInt32LE(offset));
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
export function pointerOwner(buf, offset, address) {
|
|
345
|
+
const root = memoryDomains.get(buf.buffer)?.root ?? buf.buffer;
|
|
346
|
+
const kept = keptObjects.get(root);
|
|
347
|
+
if (kept === undefined) return buf;
|
|
348
|
+
const position = memoryPosition(buf, offset);
|
|
349
|
+
const reference = kept.get(position);
|
|
350
|
+
if (reference !== undefined && reference.address !== (address ?? storedAddress(buf, offset))) {
|
|
351
|
+
kept.delete(position);
|
|
352
|
+
return buf;
|
|
353
|
+
}
|
|
354
|
+
return reference?.owner ?? buf;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
export function inDllBuffer(library, name, size, ptrToBuffer) {
|
|
358
|
+
const lib = library?._lib ?? library;
|
|
359
|
+
if (typeof lib?._symbolView !== "function") throw new TypeError("in_dll: first arg must be a Library (CDLL/WinDLL)");
|
|
360
|
+
const { address, owner } = lib._symbolView(name);
|
|
361
|
+
return keepMemoryOwner(ptrToBuffer(address, size), owner);
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
function pointerSlots(type, offset = 0, size) {
|
|
365
|
+
if (type?._isPointerValued || type?._isFuncPtr || type?._pointerTo !== undefined) return [[offset, type._size ?? type.size ?? size]];
|
|
366
|
+
if (type?._isArrayType) {
|
|
367
|
+
const slots = [];
|
|
368
|
+
const elementSize = type.length === 0 ? 0 : type.getSize() / type.length;
|
|
369
|
+
const elements = pointerSlots(type.elementType, 0, elementSize);
|
|
370
|
+
if (elements.length === 0) return slots;
|
|
371
|
+
for (let i = 0; i < type.length; i++) {
|
|
372
|
+
for (const [position, width] of elements) slots.push([offset + i * elementSize + position, width]);
|
|
373
|
+
}
|
|
374
|
+
return slots;
|
|
375
|
+
}
|
|
376
|
+
const def = typeof type?._buildStruct === "function" ? (type._structDef ?? type._buildStruct()) : type;
|
|
377
|
+
const slots = [];
|
|
378
|
+
for (const field of def?.fields ?? []) {
|
|
379
|
+
if (field.isPointer) slots.push([offset + field.offset, field.size]);
|
|
380
|
+
else slots.push(...pointerSlots(field.type, offset + field.offset, field.size));
|
|
381
|
+
}
|
|
382
|
+
return slots;
|
|
383
|
+
}
|
|
226
384
|
|
|
227
385
|
/**
|
|
228
386
|
* Keep `value` alive as long as the memory of `targetBuf`, like Python ctypes
|
|
@@ -237,17 +395,21 @@ const keptObjects = new WeakMap();
|
|
|
237
395
|
* @param {*} value - Referenced object (or null to clear the slot)
|
|
238
396
|
*/
|
|
239
397
|
export function keepAlive(targetBuf, offset, value) {
|
|
240
|
-
const position = targetBuf
|
|
241
|
-
|
|
242
|
-
|
|
398
|
+
const position = memoryPosition(targetBuf, offset);
|
|
399
|
+
const root = memoryDomains.get(targetBuf.buffer)?.root ?? targetBuf.buffer;
|
|
400
|
+
let kept = keptObjects.get(root);
|
|
401
|
+
if (value === null || (typeof value !== "object" && typeof value !== "function")) {
|
|
243
402
|
kept?.delete(position);
|
|
244
403
|
return;
|
|
245
404
|
}
|
|
246
405
|
if (kept === undefined) {
|
|
247
406
|
kept = new Map();
|
|
248
|
-
keptObjects.set(
|
|
407
|
+
keptObjects.set(root, kept);
|
|
249
408
|
}
|
|
250
|
-
|
|
409
|
+
// A pointer wrapper can later be repointed; retain its current memory.
|
|
410
|
+
if (value._pointerType !== undefined) value = value._buffer ?? value._objects ?? value;
|
|
411
|
+
else if (value._isSimpleCDataInstance && value.constructor._isPointerValued) value = pointerOwner(value._buffer, 0);
|
|
412
|
+
kept.set(position, { owner: value, address: storedAddress(targetBuf, offset) });
|
|
251
413
|
}
|
|
252
414
|
|
|
253
415
|
/**
|
|
@@ -258,7 +420,19 @@ export function keepAlive(targetBuf, offset, value) {
|
|
|
258
420
|
* @returns {*} The object, or undefined
|
|
259
421
|
*/
|
|
260
422
|
export function keptObject(buf, offset) {
|
|
261
|
-
|
|
423
|
+
const root = memoryDomains.get(buf.buffer)?.root ?? buf.buffer;
|
|
424
|
+
return keptObjects.get(root)?.get(memoryPosition(buf, offset))?.owner;
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
export function clearKeepAlives(buf, offset, size) {
|
|
428
|
+
const root = memoryDomains.get(buf.buffer)?.root ?? buf.buffer;
|
|
429
|
+
const kept = keptObjects.get(root);
|
|
430
|
+
if (kept === undefined) return;
|
|
431
|
+
const start = BigInt(memoryPosition(buf, offset));
|
|
432
|
+
const end = start + BigInt(size);
|
|
433
|
+
for (const position of kept.keys()) {
|
|
434
|
+
if (position >= start && position < end) kept.delete(position);
|
|
435
|
+
}
|
|
262
436
|
}
|
|
263
437
|
|
|
264
438
|
/**
|
|
@@ -314,23 +488,38 @@ export function fieldsOf(value) {
|
|
|
314
488
|
* @param {Buffer} buf - Target buffer
|
|
315
489
|
* @param {number} offset - Field offset
|
|
316
490
|
* @param {number} size - Field size
|
|
317
|
-
* @param {Object} value - Instance with a `_buffer
|
|
491
|
+
* @param {Object|Buffer} value - Instance with a `_buffer`, or source bytes
|
|
492
|
+
* @param {number} [sourceOffset=0] - Byte offset in the source
|
|
493
|
+
* @param {Function|Object} [type] - Layout used to retain references into leased memory
|
|
318
494
|
*/
|
|
319
|
-
export function copyInstance(buf, offset, size, value) {
|
|
320
|
-
const
|
|
321
|
-
source.
|
|
322
|
-
|
|
323
|
-
const
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
495
|
+
export function copyInstance(buf, offset, size, value, sourceOffset = 0, type) {
|
|
496
|
+
const bytes = value._buffer ?? value;
|
|
497
|
+
const source = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
498
|
+
if (mirrorsActive) refresh(source, sourceOffset, size);
|
|
499
|
+
const start = memoryPosition(source, sourceOffset);
|
|
500
|
+
const sourceRoot = memoryDomains.get(source.buffer)?.root ?? source.buffer;
|
|
501
|
+
const sourceKept = keptObjects.get(sourceRoot);
|
|
502
|
+
const snapshot = new Map();
|
|
503
|
+
if (sourceKept !== undefined) {
|
|
504
|
+
for (const [position, reference] of sourceKept) {
|
|
505
|
+
if (position < start || position + BigInt(POINTER_SIZE) > start + BigInt(size)) continue;
|
|
506
|
+
const relative = Number(position - start);
|
|
507
|
+
if (reference.address === storedAddress(source, sourceOffset + relative)) snapshot.set(relative, reference.owner);
|
|
327
508
|
}
|
|
328
509
|
}
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
510
|
+
if (type !== undefined && memoryOwners.has(source.buffer)) {
|
|
511
|
+
for (const [position, width] of pointerSlots(type)) {
|
|
512
|
+
if (snapshot.has(position) || position + width > size) continue;
|
|
513
|
+
for (let i = 0; i < width; i++) {
|
|
514
|
+
if (source[sourceOffset + position + i] !== 0) {
|
|
515
|
+
snapshot.set(position, source);
|
|
516
|
+
break;
|
|
517
|
+
}
|
|
518
|
+
}
|
|
334
519
|
}
|
|
335
520
|
}
|
|
521
|
+
source.copy(buf, offset, sourceOffset, sourceOffset + size);
|
|
522
|
+
clearKeepAlives(buf, offset, size);
|
|
523
|
+
for (const [relative, object] of snapshot) keepAlive(buf, offset + relative, object);
|
|
524
|
+
if (mirrorsActive) flush(buf, offset, size);
|
|
336
525
|
}
|
|
@@ -17,6 +17,20 @@
|
|
|
17
17
|
const roundDown = (n, multiple) => Math.floor(n / multiple) * multiple;
|
|
18
18
|
const roundUp = (n, multiple) => Math.ceil(n / multiple) * multiple;
|
|
19
19
|
|
|
20
|
+
export function normalizePack(value) {
|
|
21
|
+
if (value === null || value === undefined) return 0;
|
|
22
|
+
if (typeof value === "string") {
|
|
23
|
+
if (!/^[+-]?\d+$/.test(value.trim())) throw new TypeError("_pack_ must be convertible to an integer");
|
|
24
|
+
value = Number(value);
|
|
25
|
+
} else if (typeof value === "boolean" || typeof value === "bigint") {
|
|
26
|
+
value = Number(value);
|
|
27
|
+
}
|
|
28
|
+
if (typeof value !== "number" || !Number.isFinite(value)) throw new TypeError("_pack_ must be convertible to an integer");
|
|
29
|
+
const pack = Math.trunc(value);
|
|
30
|
+
if (pack < 0 || pack > 0x7fffffff) throw new RangeError("_pack_ must be between 0 and 2147483647");
|
|
31
|
+
return pack;
|
|
32
|
+
}
|
|
33
|
+
|
|
20
34
|
/**
|
|
21
35
|
* Layout mode of a class or definition, as Python: `_layout_` if given,
|
|
22
36
|
* otherwise `"ms"` on Windows or with `_pack_`, `"gcc-sysv"` elsewhere.
|
|
@@ -25,13 +39,13 @@ const roundUp = (n, multiple) => Math.ceil(n / multiple) * multiple;
|
|
|
25
39
|
* @param {number} pack - `_pack_` (0 when absent)
|
|
26
40
|
* @returns {boolean} true for the gcc-sysv layout
|
|
27
41
|
*/
|
|
28
|
-
export function isGccLayout(layout, pack) {
|
|
42
|
+
export function isGccLayout(layout, pack, specified = pack !== 0) {
|
|
29
43
|
if (layout === undefined || layout === null) {
|
|
30
|
-
return process.platform !== "win32" && !
|
|
44
|
+
return process.platform !== "win32" && !specified;
|
|
31
45
|
}
|
|
32
46
|
if (layout === "ms") return false;
|
|
33
47
|
if (layout === "gcc-sysv") {
|
|
34
|
-
if (
|
|
48
|
+
if (specified) throw new Error("_pack_ is not compatible with gcc-sysv layout");
|
|
35
49
|
return true;
|
|
36
50
|
}
|
|
37
51
|
throw new Error(`unknown _layout_: ${String(layout)}`);
|