node-ctypes 2.1.1 → 2.3.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.
Files changed (36) hide show
  1. package/README.md +98 -13
  2. package/build/Release/ctypes-darwin-arm64.node +0 -0
  3. package/build/Release/ctypes-darwin-x64.node +0 -0
  4. package/build/Release/ctypes-linux-arm64-musl.node +0 -0
  5. package/build/Release/ctypes-linux-arm64.node +0 -0
  6. package/build/Release/ctypes-linux-x64-musl.node +0 -0
  7. package/build/Release/ctypes-linux-x64.node +0 -0
  8. package/build/Release/ctypes-win32-arm64.node +0 -0
  9. package/build/Release/ctypes-win32-x64.node +0 -0
  10. package/lib/core/Library.js +86 -76
  11. package/lib/core/callback.js +10 -17
  12. package/lib/core/conversions.js +193 -3
  13. package/lib/core/funcptr.js +67 -52
  14. package/lib/core/lazy-loader.js +10 -4
  15. package/lib/core/types.js +196 -98
  16. package/lib/index.d.ts +193 -47
  17. package/lib/index.js +51 -28
  18. package/lib/memory/buffer.js +66 -19
  19. package/lib/memory/mirror.js +283 -0
  20. package/lib/memory/operations.js +59 -42
  21. package/lib/memory/pointer.js +180 -61
  22. package/lib/platform/constants.js +0 -1
  23. package/lib/platform/errors.js +48 -4
  24. package/lib/platform/find_library.js +78 -19
  25. package/lib/structures/Structure.js +260 -172
  26. package/lib/structures/Union.js +10 -21
  27. package/lib/structures/helpers/array.js +235 -92
  28. package/lib/structures/helpers/bitfield.js +66 -150
  29. package/lib/structures/helpers/common.js +115 -15
  30. package/lib/structures/helpers/layout.js +131 -0
  31. package/lib/structures/helpers/struct.js +144 -400
  32. package/lib/structures/helpers/union.js +132 -142
  33. package/lib/structures/helpers/wrap.js +29 -17
  34. package/lib/types/SimpleCData.js +14 -7
  35. package/lib/types/primitives.js +130 -101
  36. package/package.json +2 -1
@@ -137,6 +137,46 @@ export function _isBitField(type) {
137
137
  return typeof type === "object" && type !== null && type._isBitField === true;
138
138
  }
139
139
 
140
+ /**
141
+ * Writer of a SimpleCData field of a struct/union. An instance assigned to the
142
+ * field (or given as positional initializer) is copied when it has the same
143
+ * type, as Python (pointers keep the instance alive); another SimpleCData type
144
+ * is "incompatible types" (c_void_p fields accept the pointer types).
145
+ *
146
+ * @param {Function} fieldType - SimpleCData class of the field
147
+ * @param {Function} writer - `(buf, offset, value)` writer
148
+ * @param {number} offset - Field offset
149
+ * @returns {Function} `(buf, value)` writer
150
+ */
151
+ export function simpleFieldWriter(fieldType, writer, offset) {
152
+ const pointerValued = fieldType._isPointerValued === true;
153
+ return (buf, val) => {
154
+ if (typeof val === "object" && val !== null && val.constructor?._isSimpleCData === true) {
155
+ const T = val.constructor;
156
+ if (T._type === fieldType._type && T._size === fieldType._size) {
157
+ if (!pointerValued) return writer(buf, offset, val.value);
158
+ val._buffer.copy(buf, offset, 0, T._size);
159
+ keepAlive(buf, offset, val);
160
+ return;
161
+ }
162
+ if (!(fieldType._acceptsPointerValues === true && T._isPointerValued === true)) {
163
+ throw new TypeError(`incompatible types, ${T.name} instance instead of ${fieldType.name} instance`);
164
+ }
165
+ }
166
+ writer(buf, offset, val);
167
+ };
168
+ }
169
+
170
+ /**
171
+ * Python: a float is not an integer ("'float' object cannot be interpreted as
172
+ * an integer"); in JS, numbers that are not integral (or not finite).
173
+ *
174
+ * @throws {TypeError}
175
+ */
176
+ export function notIntegral() {
177
+ throw new TypeError("'float' object cannot be interpreted as an integer");
178
+ }
179
+
140
180
  /**
141
181
  * Address stored by a pointer field assignment: a pointer instance, a
142
182
  * CFUNCTYPE/callback object (`_as_parameter_`), a BigInt/number address,
@@ -179,23 +219,46 @@ export function funcPtrFieldType(prototype) {
179
219
  return fieldType;
180
220
  }
181
221
 
222
+ // Oggetti tenuti vivi dalla memoria che contiene i loro indirizzi, per
223
+ // ArrayBuffer e offset assoluto: tutte le view sulla stessa memoria (istanza,
224
+ // struct annidata, from_buffer) condividono la stessa tabella.
225
+ const keptObjects = new WeakMap();
226
+
182
227
  /**
183
- * Keep `value` alive as long as `targetBuf`, like Python ctypes `_objects`:
184
- * an object whose address is stored in the buffer (pointer, callback) must
185
- * not be garbage collected while native code can still read that address.
186
- * Shares the slot table used for c_char_p / c_wchar_p fields.
228
+ * Keep `value` alive as long as the memory of `targetBuf`, like Python ctypes
229
+ * `_objects`: an object whose address is stored in the buffer (string,
230
+ * pointer, callback) must not be garbage collected while native code can
231
+ * still read that address. The table belongs to the memory, not to the view,
232
+ * so assigning through a nested structure keeps the object alive with the
233
+ * outer one.
187
234
  *
188
- * @param {Buffer} targetBuf - Buffer holding the address
189
- * @param {number} offset - Offset of the slot
235
+ * @param {Uint8Array} targetBuf - Buffer holding the address
236
+ * @param {number} offset - Offset of the slot in `targetBuf`
190
237
  * @param {*} value - Referenced object (or null to clear the slot)
191
238
  */
192
239
  export function keepAlive(targetBuf, offset, value) {
193
- let keep = targetBuf.__ctypesKeepalive;
194
- if (keep === undefined) {
195
- keep = Object.create(null);
196
- Object.defineProperty(targetBuf, "__ctypesKeepalive", { value: keep });
240
+ const position = targetBuf.byteOffset + offset;
241
+ let kept = keptObjects.get(targetBuf.buffer);
242
+ if (value === null || typeof value !== "object") {
243
+ kept?.delete(position);
244
+ return;
245
+ }
246
+ if (kept === undefined) {
247
+ kept = new Map();
248
+ keptObjects.set(targetBuf.buffer, kept);
197
249
  }
198
- keep[offset] = value !== null && typeof value === "object" ? value : undefined;
250
+ kept.set(position, value);
251
+ }
252
+
253
+ /**
254
+ * Object kept alive at `offset` of `buf` (see {@link keepAlive}).
255
+ *
256
+ * @param {Uint8Array} buf - Buffer
257
+ * @param {number} offset - Offset in `buf`
258
+ * @returns {*} The object, or undefined
259
+ */
260
+ export function keptObject(buf, offset) {
261
+ return keptObjects.get(buf.buffer)?.get(buf.byteOffset + offset);
199
262
  }
200
263
 
201
264
  /**
@@ -214,6 +277,35 @@ export function writePointerField(buf, offset, value, pointerSize) {
214
277
  keepAlive(buf, offset, value);
215
278
  }
216
279
 
280
+ /**
281
+ * Fields given to struct() / union(): `[name, type]` pairs in declaration
282
+ * order (Structure._fieldMap; an object would put integer-like names such as
283
+ * "1" first), a Map or a `{ name: type }` object.
284
+ *
285
+ * @param {Array|Map|Object} fields - Field declarations
286
+ * @returns {Array} `[name, type]` pairs
287
+ */
288
+ export function fieldEntries(fields) {
289
+ if (Array.isArray(fields)) return fields;
290
+ if (fields instanceof Map) return [...fields];
291
+ return Object.entries(fields);
292
+ }
293
+
294
+ /**
295
+ * Fields of a value used as "name → value" map: a struct/union instance (its
296
+ * fields are accessors of its class, not own properties) becomes the object
297
+ * of its fields, any other value is returned as is.
298
+ *
299
+ * @param {*} value - Plain object or instance
300
+ * @returns {*} Object whose own properties are the fields
301
+ */
302
+ export function fieldsOf(value) {
303
+ if (value !== null && typeof value === "object" && Buffer.isBuffer(value._buffer) && typeof value.toObject === "function") {
304
+ return value.toObject();
305
+ }
306
+ return value;
307
+ }
308
+
217
309
  /**
218
310
  * Copy a struct/union instance into a nested field: the bytes (as Python
219
311
  * does) plus the objects it keeps alive (strings, pointers, callbacks), so
@@ -227,10 +319,18 @@ export function writePointerField(buf, offset, value, pointerSize) {
227
319
  export function copyInstance(buf, offset, size, value) {
228
320
  const source = value._buffer;
229
321
  source.copy(buf, offset, 0, size);
230
- const kept = source.__ctypesKeepalive;
231
- if (kept !== undefined) {
232
- for (const key of Object.keys(kept)) {
233
- if (Number(key) < size) keepAlive(buf, offset + Number(key), kept[key]);
322
+ const target = buf.byteOffset + offset;
323
+ const targetKept = keptObjects.get(buf.buffer);
324
+ if (targetKept !== undefined) {
325
+ for (const position of targetKept.keys()) {
326
+ if (position >= target && position < target + size) targetKept.delete(position);
327
+ }
328
+ }
329
+ const sourceKept = keptObjects.get(source.buffer);
330
+ if (sourceKept !== undefined) {
331
+ for (const [position, object] of sourceKept) {
332
+ const relative = position - source.byteOffset;
333
+ if (relative >= 0 && relative < size) keepAlive(buf, offset + relative, object);
234
334
  }
235
335
  }
236
336
  }
@@ -0,0 +1,131 @@
1
+ /**
2
+ * @file layout.js
3
+ * @module structures/helpers/layout
4
+ * @description Field layout of structures and unions, ported from CPython's
5
+ * `ctypes._layout.get_layout` (Python 3.14+), so that offsets, bitfields,
6
+ * `_pack_`, `_align_`, `_layout_` and inheritance give the same result as
7
+ * Python ctypes.
8
+ *
9
+ * Two layouts exist, as in Python:
10
+ * - `"gcc-sysv"` (default except on Windows): fields are placed bit by bit; a
11
+ * bitfield that would cross a boundary of its type moves to the next one.
12
+ * - `"ms"` (default on Windows, and whenever `_pack_` is set): adjacent
13
+ * bitfields share an allocation unit only if their types have the same size
14
+ * and the next one fits.
15
+ */
16
+
17
+ const roundDown = (n, multiple) => Math.floor(n / multiple) * multiple;
18
+ const roundUp = (n, multiple) => Math.ceil(n / multiple) * multiple;
19
+
20
+ /**
21
+ * Layout mode of a class or definition, as Python: `_layout_` if given,
22
+ * otherwise `"ms"` on Windows or with `_pack_`, `"gcc-sysv"` elsewhere.
23
+ *
24
+ * @param {string|undefined} layout - `_layout_`
25
+ * @param {number} pack - `_pack_` (0 when absent)
26
+ * @returns {boolean} true for the gcc-sysv layout
27
+ */
28
+ export function isGccLayout(layout, pack) {
29
+ if (layout === undefined || layout === null) {
30
+ return process.platform !== "win32" && !pack;
31
+ }
32
+ if (layout === "ms") return false;
33
+ if (layout === "gcc-sysv") {
34
+ if (pack) throw new Error("_pack_ is not compatible with gcc-sysv layout");
35
+ return true;
36
+ }
37
+ throw new Error(`unknown _layout_: ${String(layout)}`);
38
+ }
39
+
40
+ /**
41
+ * Compute the layout of a structure or union.
42
+ *
43
+ * @param {Array<{size: number, align: number, bitSize?: number}>} fields -
44
+ * Size and alignment of each field type; `bitSize` for bitfields.
45
+ * @param {Object} options
46
+ * @param {boolean} options.isStruct - false for unions
47
+ * @param {boolean} options.gccLayout - see {@link isGccLayout}
48
+ * @param {number} [options.pack=0] - `_pack_` (ms layout only)
49
+ * @param {number} [options.align=1] - `_align_` (minimum alignment)
50
+ * @param {{size: number, alignment: number}} [options.base] - Layout of the base class
51
+ * @param {boolean} [options.bigEndian=false] - Bitfields laid out from the big end
52
+ * @returns {{offsets: Array<{offset: number, bitOffset?: number}>, size: number, alignment: number}}
53
+ */
54
+ export function computeLayout(fields, { isStruct, gccLayout, pack = 0, align = 1, base = null, bigEndian = false }) {
55
+ if (!Number.isInteger(align) || align < 0) throw new RangeError("_align_ must be a non-negative integer");
56
+ let alignment = Math.max(align, 1);
57
+ if (base) alignment = Math.max(base.alignment, alignment);
58
+
59
+ let lastFieldBitSize = 0; // ms layout only
60
+ // `8 * nextByteOffset + nextBitOffset` points to where the next field would start.
61
+ let nextBitOffset = 0;
62
+ let nextByteOffset = 0;
63
+ let structSize = 0;
64
+ let unionSize = 0;
65
+
66
+ if (base) {
67
+ structSize = base.size;
68
+ if (gccLayout) nextBitOffset = structSize * 8;
69
+ else nextByteOffset = structSize;
70
+ unionSize = isStruct ? 0 : base.size;
71
+ }
72
+
73
+ const offsets = [];
74
+ for (const field of fields) {
75
+ if (!isStruct) {
76
+ // Unions start fresh each time
77
+ lastFieldBitSize = 0;
78
+ nextBitOffset = 0;
79
+ nextByteOffset = 0;
80
+ }
81
+
82
+ const isBitField = field.bitSize !== undefined && field.bitSize !== null;
83
+ const typeSize = field.size;
84
+ const typeBitSize = typeSize * 8;
85
+ const bitSize = isBitField ? field.bitSize : typeBitSize;
86
+ if (isBitField && (!Number.isInteger(bitSize) || bitSize <= 0 || bitSize > typeBitSize)) {
87
+ throw new RangeError(`number of bits invalid for bit field ${JSON.stringify(field.name)}`);
88
+ }
89
+ let typeAlign = field.align || 1;
90
+ let offset;
91
+ let bitOffset;
92
+
93
+ if (gccLayout) {
94
+ const typeBitAlign = typeAlign * 8;
95
+ // The "slot" sized and aligned for the type that contains the start of
96
+ // the field must also contain its last bit, otherwise pad to the next one.
97
+ const slotEndBit = roundDown(nextBitOffset, typeBitAlign) + typeBitSize;
98
+ if (nextBitOffset + bitSize > slotEndBit) {
99
+ nextBitOffset = roundUp(nextBitOffset, typeBitAlign);
100
+ }
101
+ offset = roundDown(nextBitOffset, typeBitAlign) / 8;
102
+ if (isBitField) bitOffset = nextBitOffset - 8 * offset;
103
+ nextBitOffset += bitSize;
104
+ structSize = roundUp(nextBitOffset, 8) / 8;
105
+ } else {
106
+ if (pack) typeAlign = Math.min(pack, typeAlign);
107
+ // Close the previous bitfield (if any) and start a new allocation unit.
108
+ if (0 < nextBitOffset + bitSize || typeBitSize !== lastFieldBitSize) {
109
+ nextByteOffset = roundUp(nextByteOffset, typeAlign) + typeSize;
110
+ lastFieldBitSize = typeBitSize;
111
+ nextBitOffset = -lastFieldBitSize;
112
+ }
113
+ offset = nextByteOffset - lastFieldBitSize / 8;
114
+ if (isBitField) bitOffset = lastFieldBitSize + nextBitOffset;
115
+ nextBitOffset += bitSize;
116
+ structSize = nextByteOffset;
117
+ }
118
+
119
+ if (isBitField && bigEndian) {
120
+ // Bitfields of big-endian structures start from the big end.
121
+ bitOffset = typeBitSize - bitSize - bitOffset;
122
+ }
123
+
124
+ offsets.push(isBitField ? { offset, bitOffset } : { offset });
125
+ alignment = Math.max(alignment, typeAlign);
126
+ if (!isStruct) unionSize = Math.max(unionSize, structSize);
127
+ }
128
+
129
+ const totalSize = isStruct ? structSize : unionSize;
130
+ return { offsets, size: roundUp(totalSize, alignment), alignment };
131
+ }