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
@@ -26,7 +26,8 @@
26
26
  * ```
27
27
  */
28
28
 
29
- import { writePointerField } from "../structures/helpers/common.js";
29
+ import { keepAlive, writePointerField } from "../structures/helpers/common.js";
30
+ import { flush, mirrorAddress, mirrorsActive } from "./mirror.js";
30
31
 
31
32
  /**
32
33
  * Gets the memory address of a buffer or pointer.
@@ -55,6 +56,11 @@ import { writePointerField } from "../structures/helpers/common.js";
55
56
  * ```
56
57
  */
57
58
  export function addressOf(ptr, alloc, native) {
59
+ // Puntatore: l'indirizzo del puntatore stesso (Python addressof(p)), non
60
+ // quello della memoria puntata.
61
+ if (ptr && typeof ptr === "object" && ptr._pointerType !== undefined) {
62
+ ptr = ptr._pointerSlot;
63
+ }
58
64
  // Object wrapper (SimpleCData, Structure, Union, array proxy) → unwrap al Buffer.
59
65
  // Le istanze di array sono Proxy su un Buffer: Buffer.isBuffer() è vero in JS
60
66
  // ma il nativo non vede un Buffer, quindi si usa sempre `_buffer` se presente.
@@ -121,6 +127,11 @@ export function addressOf(ptr, alloc, native) {
121
127
  * ```
122
128
  */
123
129
  export function byref(obj) {
130
+ // Puntatore: la memoria del puntatore (T**), così una funzione C può
131
+ // scriverci un indirizzo e ri-puntarlo (Python byref(p)).
132
+ if (obj && typeof obj === "object" && obj._pointerType !== undefined) {
133
+ return obj._pointerSlot;
134
+ }
124
135
  // SimpleCData instance or Structure instance - return its buffer
125
136
  if (obj && obj._buffer && Buffer.isBuffer(obj._buffer)) {
126
137
  return obj._buffer;
@@ -193,15 +204,16 @@ export function cast(ptr, targetType, readValue, sizeof, ptrToBuffer, native) {
193
204
  if (ptr._buffer) {
194
205
  return targetType.fromBuffer(ptr._buffer);
195
206
  }
196
- return targetType.fromAddress(ptr.address);
207
+ return targetType.fromAddress(ptr.address, ptr);
197
208
  }
198
209
 
199
210
  // ctypes object with _buffer — distinguish data objects from pointer-value objects
200
211
  // Note: array proxies are Buffer.isBuffer()==true but also have ._buffer, so don't exclude Buffers
201
212
  if (ptr && typeof ptr === "object" && ptr._buffer && Buffer.isBuffer(ptr._buffer)) {
202
- // SimpleCData storing a pointer/address value (c_void_p, c_char_p, etc.)
203
- // → read the stored address value from the buffer
204
- if (ptr.constructor && ptr.constructor._isSimpleCData && ptr.constructor._type === native.CType.POINTER) {
213
+ // SimpleCData storing a pointer/address value (c_void_p, c_char_p,
214
+ // c_wchar_p) → read the stored address value from the buffer
215
+ const pointerValued = new Set([native.CType.POINTER, native.CType.STRING, native.CType.WSTRING]);
216
+ if (ptr.constructor && ptr.constructor._isSimpleCData && pointerValued.has(ptr.constructor._type)) {
205
217
  // This is a pointer-valued SimpleCData — read address from buffer
206
218
  const buf = ptr._buffer;
207
219
  let addr;
@@ -212,7 +224,8 @@ export function cast(ptr, targetType, readValue, sizeof, ptrToBuffer, native) {
212
224
  } else {
213
225
  throw new TypeError("cast(): buffer too small to contain a pointer");
214
226
  }
215
- return targetType.fromAddress(addr);
227
+ // Python: il risultato tiene viva la sorgente (la stringa di un c_char_p).
228
+ return targetType.fromAddress(addr, ptr);
216
229
  }
217
230
  // Array, Structure, Union — pointer to their data buffer
218
231
  // Python: cast(arr, POINTER(c_int32)) points to arr's memory
@@ -241,6 +254,15 @@ export function cast(ptr, targetType, readValue, sizeof, ptrToBuffer, native) {
241
254
  return targetType.fromAddress(addr);
242
255
  }
243
256
 
257
+ // c_void_p / c_char_p / c_wchar_p: an instance pointing to the source,
258
+ // which it keeps alive (Python: cast(buf, c_void_p).value == addressof(buf)).
259
+ if (typeof targetType === "function" && targetType._isSimpleCData === true && isPointerValued(targetType, native)) {
260
+ const result = new targetType();
261
+ writePointerField(result._buffer, 0, castSourceAddress(ptr, native), native.POINTER_SIZE);
262
+ if (typeof ptr === "object") keepAlive(result._buffer, 0, ptr);
263
+ return result;
264
+ }
265
+
244
266
  // Struct type - return wrapper object
245
267
  if (typeof targetType === "object" && targetType.size !== undefined) {
246
268
  const buf = Buffer.isBuffer(ptr) ? ptr : ptrToBuffer(ptr, targetType.size);
@@ -269,34 +291,39 @@ export function cast(ptr, targetType, readValue, sizeof, ptrToBuffer, native) {
269
291
  return readValue(tempBuf, targetType, 0);
270
292
  }
271
293
 
294
+ function isPointerValued(type, native) {
295
+ return type._type === native.CType.POINTER || type._type === native.CType.STRING || type._type === native.CType.WSTRING;
296
+ }
297
+
298
+ // Address given by a cast() source, as Python's c_void_p.from_param: the value
299
+ // of pointers, c_void_p, c_char_p and c_wchar_p, the memory of the others.
300
+ function castSourceAddress(ptr, native) {
301
+ if (typeof ptr === "bigint") return ptr;
302
+ if (typeof ptr === "number") return BigInt(ptr);
303
+ if (ptr !== null && typeof ptr === "object") {
304
+ if (ptr._pointerType !== undefined) return ptr.address;
305
+ const T = ptr.constructor;
306
+ if (T?._isSimpleCData === true && isPointerValued(T, native)) {
307
+ return native.POINTER_SIZE === 8 ? ptr._buffer.readBigUInt64LE(0) : BigInt(ptr._buffer.readUInt32LE(0));
308
+ }
309
+ if (Buffer.isBuffer(ptr._buffer)) return addressOf(ptr._buffer, null, native);
310
+ if (Buffer.isBuffer(ptr)) return addressOf(ptr, null, native);
311
+ if (ptr._as_parameter_ !== undefined) return castSourceAddress(ptr._as_parameter_, native);
312
+ }
313
+ throw new TypeError("cast(): ptr must be a BigInt, number, Buffer, ctypes instance, or PointerInstance");
314
+ }
315
+
272
316
  /**
273
- * Creates a buffer backed by a specific memory address.
274
- *
275
- * **WARNING**: This is a low-level operation! Accessing invalid memory will
276
- * crash the process. Only use with addresses from trusted sources (FFI returns,
277
- * addressOf, etc.).
317
+ * Buffer over the memory at an address, used by `from_address`, `cast` and
318
+ * pointers (not exported: the public, Python-compatible way is
319
+ * `array(c_uint8, n).from_address(address)`). Where external buffers are not
320
+ * allowed it is a synchronized copy (see memory/mirror.js).
278
321
  *
279
322
  * @param {bigint|number} address - Memory address
280
323
  * @param {number} size - Size in bytes
281
324
  * @param {Object} native - Native module reference
282
- * @returns {Buffer} Buffer pointing to the address
283
- *
284
- * @example Read C string from pointer
285
- * ```javascript
286
- * import { ptrToBuffer } from 'node-ctypes';
287
- *
288
- * // Got pointer from C function
289
- * const str_ptr = some_c_function(); // Returns pointer
290
- * const buf = ptrToBuffer(str_ptr, 256);
291
- * const str = buf.toString('utf8');
292
- * ```
293
- *
294
- * @example Access struct at address
295
- * ```javascript
296
- * const addr = get_struct_ptr(); // From C
297
- * const buf = ptrToBuffer(addr, sizeof(MyStruct));
298
- * const struct_data = MyStruct.toObject(buf);
299
- * ```
325
+ * @returns {Buffer|null} Buffer over the address, `null` for NULL
326
+ * @private
300
327
  */
301
328
  export function ptrToBuffer(address, size, native) {
302
329
  return native.ptrToBuffer(address, size);
@@ -423,8 +450,10 @@ export function POINTER(baseType, sizeof, alloc, readValue, writeValue, c_void_p
423
450
 
424
451
  // Python: per tipi semplici e Structure/Union `contents` (e p[i] per le struct)
425
452
  // è un'istanza viva sulla memoria puntata, non una copia del valore.
426
- const hasInstances = () => typeof baseType === "function" && (baseType._isSimpleCData === true || typeof baseType._buildStruct === "function" || typeof baseType._buildUnion === "function");
427
- const isStructBase = () => typeof baseType === "function" && (typeof baseType._buildStruct === "function" || typeof baseType._buildUnion === "function");
453
+ // Array (Python POINTER(c_int * 3)): contents e p[i] sono istanze dell'array.
454
+ const isArrayBase = () => baseType !== null && (typeof baseType === "function" || typeof baseType === "object") && baseType._isArrayType === true;
455
+ const hasInstances = () => isArrayBase() || (typeof baseType === "function" && (baseType._isSimpleCData === true || typeof baseType._buildStruct === "function" || typeof baseType._buildUnion === "function"));
456
+ const isStructBase = () => isArrayBase() || (typeof baseType === "function" && (typeof baseType._buildStruct === "function" || typeof baseType._buildUnion === "function"));
428
457
 
429
458
  // POINTER(POINTER(T)) / POINTER(CFUNCTYPE): elementi puntatore, letti come
430
459
  // oggetto puntatore / funzione (NULL → null) e scritti come indirizzo.
@@ -440,8 +469,13 @@ export function POINTER(baseType, sizeof, alloc, readValue, writeValue, c_void_p
440
469
  }
441
470
 
442
471
  function writePointerAt(buffer, address, offset, value) {
443
- const inBuffer = buffer && offset + baseSize <= buffer.length;
444
- writePointerField(inBuffer ? buffer : native.ptrToBuffer(address + BigInt(offset), baseSize), inBuffer ? offset : 0, value, baseSize);
472
+ if (buffer && offset + baseSize <= buffer.length) {
473
+ writePointerField(buffer, offset, value, baseSize);
474
+ return;
475
+ }
476
+ const target = native.ptrToBuffer(address + BigInt(offset), baseSize);
477
+ writePointerField(target, 0, value, baseSize);
478
+ if (mirrorsActive) flush(target);
445
479
  }
446
480
 
447
481
  function instanceAt(buffer, address, offset) {
@@ -451,6 +485,22 @@ export function POINTER(baseType, sizeof, alloc, readValue, writeValue, c_void_p
451
485
  return baseType.from_address(address + BigInt(offset));
452
486
  }
453
487
 
488
+ // Scrittura a un indirizzo senza Buffer associato: per le primitive il
489
+ // valore va in un Buffer V8 (uno per tipo puntatore, riusato) e il nativo
490
+ // lo copia all'indirizzo, invece di creare un Buffer esterno (~400 ns,
491
+ // vietato in Electron).
492
+ let scratch = null;
493
+ function writeAtAddress(addr, value) {
494
+ if (typeof baseType === "function" && baseType._isSimpleCData) {
495
+ scratch ??= alloc(baseSize);
496
+ baseType._writer(scratch, 0, value);
497
+ native.writeMemory(scratch, 0, baseSize, addr);
498
+ return;
499
+ }
500
+ const buf = native.ptrToBuffer(addr, baseSize);
501
+ writeValue(buf, baseType, value, 0);
502
+ }
503
+
454
504
  // Lettura a un indirizzo senza Buffer associato: per le primitive
455
505
  // readValue(indirizzo) evita il Buffer esterno di ptrToBuffer.
456
506
  function readAtAddress(addr) {
@@ -465,13 +515,37 @@ export function POINTER(baseType, sizeof, alloc, readValue, writeValue, c_void_p
465
515
  * Creates a pointer instance with Python ctypes-compatible API.
466
516
  * Supports .contents property and [index] access for pointer arithmetic.
467
517
  */
468
- function createPointerInstance(addressOrBuffer) {
518
+ function createPointerInstance(addressOrBuffer, keep) {
469
519
  // Risolvi il thunk lazy alla prima creazione di istanza: a questo
470
520
  // punto la classe target è sicuramente inizializzata.
471
521
  resolveIfLazy();
472
522
 
473
523
  let _address = 0n;
474
524
  let _buffer = null;
525
+ // Python `_objects`: ciò che deve restare vivo finché il puntatore punta
526
+ // lì (la sorgente di cast(), il puntatore da cui deriva add()).
527
+ let _objects = keep;
528
+ // Memoria del puntatore (Python: un puntatore è un oggetto ctypes di
529
+ // POINTER_SIZE byte), creata alla prima richiesta di byref(p) /
530
+ // addressof(p). Da allora è lei a dare l'indirizzo: una funzione C che ci
531
+ // scrive (f(byref(p))) ri-punta p.
532
+ let _slot = null;
533
+
534
+ function sync() {
535
+ if (_slot === null) return;
536
+ const addr = native.POINTER_SIZE === 8 ? _slot.readBigUInt64LE(0) : BigInt(_slot.readUInt32LE(0));
537
+ if (addr !== _address) {
538
+ _address = addr;
539
+ _buffer = null;
540
+ _objects = undefined;
541
+ }
542
+ }
543
+
544
+ function store() {
545
+ if (_slot === null) return;
546
+ if (native.POINTER_SIZE === 8) _slot.writeBigUInt64LE(BigInt.asUintN(64, _address), 0);
547
+ else _slot.writeUInt32LE(Number(BigInt.asUintN(32, _address)), 0);
548
+ }
475
549
 
476
550
  if (addressOrBuffer === undefined || addressOrBuffer === null) {
477
551
  _address = 0n;
@@ -479,10 +553,27 @@ export function POINTER(baseType, sizeof, alloc, readValue, writeValue, c_void_p
479
553
  _address = addressOrBuffer;
480
554
  } else if (typeof addressOrBuffer === "number") {
481
555
  _address = BigInt(addressOrBuffer);
556
+ } else if (typeof addressOrBuffer === "object" && Buffer.isBuffer(addressOrBuffer._buffer)) {
557
+ // Istanza ctypes (array, struct): la sua memoria.
558
+ pointTo(addressOrBuffer._buffer);
482
559
  } else if (Buffer.isBuffer(addressOrBuffer)) {
483
- // This is a buffer we're pointing TO
484
- _buffer = addressOrBuffer;
485
- _address = getBufferAddress(addressOrBuffer);
560
+ pointTo(addressOrBuffer);
561
+ }
562
+
563
+ // Puntare a un Buffer; una copia di memoria nativa (memory/mirror.js)
564
+ // vale il suo indirizzo originale, come un puntatore creato da indirizzo.
565
+ function pointTo(buf) {
566
+ _objects = undefined;
567
+ const mirrored = mirrorAddress(buf);
568
+ if (mirrored !== undefined) {
569
+ _buffer = null;
570
+ _address = mirrored;
571
+ _objects = buf;
572
+ } else {
573
+ _buffer = buf;
574
+ _address = getBufferAddress(buf);
575
+ }
576
+ store();
486
577
  }
487
578
 
488
579
  const instance = {
@@ -494,9 +585,27 @@ export function POINTER(baseType, sizeof, alloc, readValue, writeValue, c_void_p
494
585
  * Get the raw address as BigInt
495
586
  */
496
587
  get address() {
588
+ sync();
497
589
  return _address;
498
590
  },
499
591
 
592
+ /**
593
+ * Memoria del puntatore (POINTER_SIZE byte con l'indirizzo): ciò che
594
+ * byref(p) / addressof(p) passano al C.
595
+ */
596
+ get _pointerSlot() {
597
+ if (_slot === null) {
598
+ _slot = alloc(native.POINTER_SIZE);
599
+ store();
600
+ }
601
+ return _slot;
602
+ },
603
+
604
+ /** Oggetti tenuti vivi dal puntatore (Python `_objects`). */
605
+ get _objects() {
606
+ return _objects;
607
+ },
608
+
500
609
  /**
501
610
  * Python ctypes compatible: the pointed object. For simple types and
502
611
  * Structure/Union classes it is a live instance on the pointed memory
@@ -504,6 +613,7 @@ export function POINTER(baseType, sizeof, alloc, readValue, writeValue, c_void_p
504
613
  * the pointer to it, assigning a plain value writes it.
505
614
  */
506
615
  get contents() {
616
+ sync();
507
617
  if (_address === 0n && !_buffer) {
508
618
  throw new Error("NULL pointer access");
509
619
  }
@@ -521,10 +631,15 @@ export function POINTER(baseType, sizeof, alloc, readValue, writeValue, c_void_p
521
631
  },
522
632
 
523
633
  set contents(value) {
634
+ sync();
524
635
  // Python: assegnare un'istanza ri-punta il puntatore a quell'istanza.
525
- if (value !== null && typeof value === "object" && (value._isSimpleCDataInstance === true || value._structDef !== undefined) && Buffer.isBuffer(value._buffer)) {
526
- _buffer = value._buffer;
527
- _address = getBufferAddress(value._buffer);
636
+ if (value !== null && typeof value === "object" && (value._isSimpleCDataInstance === true || value._structDef !== undefined || value._arrayType !== undefined) && Buffer.isBuffer(value._buffer)) {
637
+ // Python accetta anche un'istanza di un altro tipo; una più piccola
638
+ // del tipo puntato farebbe leggere e scrivere oltre la sua memoria.
639
+ if (value._buffer.length < baseSize) {
640
+ throw new TypeError(`contents: ${value.constructor?.name ?? "instance"} (${value._buffer.length} bytes) is smaller than the pointed type (${baseSize} bytes)`);
641
+ }
642
+ pointTo(value._buffer);
528
643
  return;
529
644
  }
530
645
  if (_address === 0n && !_buffer) {
@@ -535,8 +650,7 @@ export function POINTER(baseType, sizeof, alloc, readValue, writeValue, c_void_p
535
650
  } else if (_buffer) {
536
651
  writeValue(_buffer, baseType, value, 0);
537
652
  } else {
538
- const buf = native.ptrToBuffer(_address, baseSize);
539
- writeValue(buf, baseType, value, 0);
653
+ writeAtAddress(_address, value);
540
654
  }
541
655
  },
542
656
 
@@ -544,6 +658,7 @@ export function POINTER(baseType, sizeof, alloc, readValue, writeValue, c_void_p
544
658
  * Returns the buffer this pointer points to (if available)
545
659
  */
546
660
  get _buffer() {
661
+ sync();
547
662
  return _buffer;
548
663
  },
549
664
 
@@ -559,14 +674,12 @@ export function POINTER(baseType, sizeof, alloc, readValue, writeValue, c_void_p
559
674
  */
560
675
  set(value) {
561
676
  if (Buffer.isBuffer(value)) {
562
- _buffer = value;
563
- _address = getBufferAddress(value);
564
- } else if (typeof value === "bigint") {
565
- _address = value;
566
- _buffer = null;
567
- } else if (typeof value === "number") {
677
+ pointTo(value);
678
+ } else if (typeof value === "bigint" || typeof value === "number") {
568
679
  _address = BigInt(value);
569
680
  _buffer = null;
681
+ _objects = undefined;
682
+ store();
570
683
  }
571
684
  },
572
685
 
@@ -574,6 +687,7 @@ export function POINTER(baseType, sizeof, alloc, readValue, writeValue, c_void_p
574
687
  * Check if pointer is NULL
575
688
  */
576
689
  get isNull() {
690
+ sync();
577
691
  return _address === 0n && !_buffer;
578
692
  },
579
693
 
@@ -587,6 +701,7 @@ export function POINTER(baseType, sizeof, alloc, readValue, writeValue, c_void_p
587
701
  },
588
702
 
589
703
  toString() {
704
+ sync();
590
705
  return `<${typeName} pointer at 0x${_address.toString(16)}>`;
591
706
  },
592
707
 
@@ -595,8 +710,10 @@ export function POINTER(baseType, sizeof, alloc, readValue, writeValue, c_void_p
595
710
  * `ptr + n`. The pointer keeps the same element type.
596
711
  */
597
712
  add(n) {
713
+ sync();
598
714
  const offsetBytes = BigInt(n) * BigInt(baseSize);
599
- return PointerType.fromAddress(_address + offsetBytes);
715
+ // Il nuovo puntatore tiene viva la memoria di questo (Python _objects).
716
+ return createPointerInstance(_address + offsetBytes, _buffer ?? _objects);
600
717
  },
601
718
 
602
719
  /**
@@ -656,10 +773,7 @@ export function POINTER(baseType, sizeof, alloc, readValue, writeValue, c_void_p
656
773
  writeValue(_buffer, baseType, value, offset);
657
774
  return true;
658
775
  }
659
- // Use native to write at address + offset
660
- const addr = _address + BigInt(offset);
661
- const buf = native.ptrToBuffer(addr, baseSize);
662
- writeValue(buf, baseType, value, 0);
776
+ writeAtAddress(_address + BigInt(offset), value);
663
777
  return true;
664
778
  }
665
779
  return Reflect.set(target, prop, value, receiver);
@@ -707,8 +821,8 @@ export function POINTER(baseType, sizeof, alloc, readValue, writeValue, c_void_p
707
821
  * @param {bigint|number} address - Memory address
708
822
  * @returns {Object} Pointer instance
709
823
  */
710
- fromAddress(address) {
711
- return createPointerInstance(typeof address === "bigint" ? address : BigInt(address));
824
+ fromAddress(address, keep) {
825
+ return createPointerInstance(typeof address === "bigint" ? address : BigInt(address), keep);
712
826
  },
713
827
 
714
828
  /**
@@ -773,14 +887,16 @@ export function pointer(obj, POINTER_fn, sizeof, alloc, readValue, writeValue, c
773
887
  let targetBuffer;
774
888
  let baseType;
775
889
 
776
- if (Buffer.isBuffer(obj)) {
777
- targetBuffer = obj;
778
- baseType = c_void_p; // Generic pointer
779
- } else if (obj && obj._buffer) {
780
- // Structure/Union instance or SimpleCData with _buffer
890
+ // Le istanze di array sono Proxy su un Buffer (Buffer.isBuffer è vero): la
891
+ // loro memoria è `_buffer`, controllato per primo.
892
+ if (obj !== null && typeof obj === "object" && Buffer.isBuffer(obj._buffer)) {
893
+ // Structure/Union instance, array or SimpleCData with _buffer
781
894
  targetBuffer = obj._buffer;
782
895
  // Get the base type for POINTER creation
783
- if (obj.constructor && obj.constructor._type) {
896
+ if (obj._arrayType !== undefined) {
897
+ // Python: pointer(c_int * 3 instance) è un POINTER(c_int * 3).
898
+ baseType = obj._arrayType;
899
+ } else if (obj.constructor && obj.constructor._type) {
784
900
  // SimpleCData instance - use the class itself (c_int32, c_double, etc.)
785
901
  baseType = obj.constructor;
786
902
  } else if (obj._structDef) {
@@ -789,6 +905,9 @@ export function pointer(obj, POINTER_fn, sizeof, alloc, readValue, writeValue, c
789
905
  } else {
790
906
  baseType = c_void_p;
791
907
  }
908
+ } else if (Buffer.isBuffer(obj)) {
909
+ targetBuffer = obj;
910
+ baseType = c_void_p; // Generic pointer
792
911
  } else {
793
912
  throw new TypeError("pointer() argument must be a ctypes instance or Buffer");
794
913
  }
@@ -11,7 +11,6 @@
11
11
  * console.log(`Wide char size: ${WCHAR_SIZE} bytes`);
12
12
  */
13
13
 
14
- import { createRequire } from "node:module";
15
14
  import path from "node:path";
16
15
 
17
16
  /**
@@ -114,13 +114,57 @@ export function FormatError(code, WinDLL, alloc, c_uint32, c_void, c_void_p) {
114
114
  * @param {Object} c_void_p - c_void_p type reference
115
115
  * @returns {Error} Error with `.winerror = code` and a formatted message
116
116
  */
117
- export function WinError(code, WinDLL, alloc, c_uint32, c_void, c_void_p) {
118
- const msg = FormatError(code, WinDLL, alloc, c_uint32, c_void, c_void_p);
117
+ export function WinError(code, WinDLL, alloc, c_uint32, c_void, c_void_p, descr) {
118
+ const msg = descr ?? FormatError(code, WinDLL, alloc, c_uint32, c_void, c_void_p);
119
119
  const err = new Error(`[WinError ${code}] ${msg}`);
120
+ // Python: OSError(None, descr, None, code) — errno derivato da winerror.
120
121
  err.winerror = code;
122
+ err.errno = winerrorToErrno(code);
123
+ err.strerror = msg;
121
124
  return err;
122
125
  }
123
126
 
127
+ // errno (valori del CRT Microsoft) di un codice Windows, come
128
+ // winerror_to_errno di CPython (PC/errmap.h).
129
+ const ENOENT = 2;
130
+ const errnoGroups = [
131
+ [ENOENT, [2, 3, 15, 18, 53, 67, 161, 206]],
132
+ [7, [10]], // E2BIG
133
+ [8, [11, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202]], // ENOEXEC
134
+ [9, [6, 114, 130]], // EBADF
135
+ [10, [128, 129]], // ECHILD
136
+ [11, [89, 164, 215]], // EAGAIN
137
+ [12, [7, 8, 9, 1816]], // ENOMEM
138
+ [13, [5, 16, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 65, 82, 83, 108, 132, 158, 167]], // EACCES
139
+ [17, [80, 183]], // EEXIST
140
+ [18, [17]], // EXDEV
141
+ [20, [267]], // ENOTDIR
142
+ [24, [4]], // EMFILE
143
+ [28, [112]], // ENOSPC
144
+ [32, [109, 232]], // EPIPE
145
+ [41, [145]], // ENOTEMPTY
146
+ [42, [1113]], // EILSEQ
147
+ [138, [258]], // ETIMEDOUT
148
+ ];
149
+ const errnoByWinerror = new Map(errnoGroups.flatMap(([errno, codes]) => codes.map((code) => [code, errno])));
150
+ const EINVAL = 22;
151
+
152
+ /**
153
+ * errno of a Windows error code (CPython `winerror_to_errno`).
154
+ *
155
+ * @param {number} winerror - Windows error code (or FACILITY_WIN32 HRESULT)
156
+ * @returns {number} errno value
157
+ */
158
+ export function winerrorToErrno(winerror) {
159
+ let code = winerror >>> 0;
160
+ if ((code & 0xffff0000) >>> 0 === 0x80070000) code &= 0xffff;
161
+ if (code >= 10000 && code < 12000) {
162
+ // Winsock: i codici sono già errno (alcuni con offset 10000).
163
+ return [10004, 10009, 10013, 10014, 10022, 10024].includes(code) ? code - 10000 : code;
164
+ }
165
+ return errnoByWinerror.get(code) ?? EINVAL;
166
+ }
167
+
124
168
  /**
125
169
  * Raised when a foreign function call cannot convert one of the passed
126
170
  * arguments (Python ctypes `ctypes.ArgumentError`). Subclass of `TypeError`.
@@ -135,8 +179,8 @@ export function WinError(code, WinDLL, alloc, c_uint32, c_void, c_void_p) {
135
179
  * ```
136
180
  */
137
181
  export class ArgumentError extends TypeError {
138
- constructor(message) {
139
- super(message);
182
+ constructor(message, options) {
183
+ super(message, options);
140
184
  this.name = "ArgumentError";
141
185
  }
142
186
  }
@@ -18,7 +18,8 @@
18
18
  */
19
19
 
20
20
  import { execSync } from "node:child_process";
21
- import { existsSync } from "node:fs";
21
+ import { existsSync, readdirSync, statSync } from "node:fs";
22
+ import os from "node:os";
22
23
  import path from "node:path";
23
24
 
24
25
  // Windows has no canonical mapping for generic library names (CPython returns
@@ -43,37 +44,94 @@ function findLibraryWindows(name) {
43
44
  return `${name}.dll`;
44
45
  }
45
46
 
46
- function findLibraryDarwin(name) {
47
- const candidates = [`lib${name}.dylib`, `${name}.framework/${name}`, `/usr/lib/lib${name}.dylib`, `/usr/local/lib/lib${name}.dylib`, `/opt/homebrew/lib/lib${name}.dylib`, `/opt/homebrew/opt/${name}/lib/lib${name}.dylib`];
48
- for (const p of candidates) {
49
- if (p.startsWith("/") && existsSync(p)) return p;
47
+ // Search order of ctypes.macholib.dyld.dyld_find: DYLD_* paths, then the
48
+ // fallback directories of dyld, with Homebrew first as in Homebrew's Python
49
+ // (Apple's /usr/lib/libssl.dylib and libcrypto.dylib abort the process).
50
+ function findLibraryDarwin(name, inSharedCache) {
51
+ const home = os.homedir();
52
+ const envDirs = (variable) => (process.env[variable] ?? "").split(":").filter(Boolean);
53
+ const libDirs = [...envDirs("DYLD_LIBRARY_PATH"), ...envDirs("DYLD_FALLBACK_LIBRARY_PATH"), "/opt/homebrew/lib", path.join(home, "lib"), "/usr/local/lib", "/lib", "/usr/lib"];
54
+ const frameworkDirs = [
55
+ ...envDirs("DYLD_FRAMEWORK_PATH"),
56
+ ...envDirs("DYLD_FALLBACK_FRAMEWORK_PATH"),
57
+ "/opt/homebrew/Frameworks",
58
+ path.join(home, "Library/Frameworks"),
59
+ "/Library/Frameworks",
60
+ "/Network/Library/Frameworks",
61
+ "/System/Library/Frameworks",
62
+ ];
63
+ const candidates = [
64
+ ...libDirs.map((dir) => path.join(dir, `lib${name}.dylib`)),
65
+ ...libDirs.map((dir) => path.join(dir, `${name}.dylib`)),
66
+ ...frameworkDirs.map((dir) => path.join(dir, `${name}.framework`, name)),
67
+ `/opt/homebrew/opt/${name}/lib/lib${name}.dylib`,
68
+ ];
69
+ for (const candidate of candidates) {
70
+ if (isFile(candidate) || inSharedCache(candidate)) return candidate;
50
71
  }
51
72
  // Fallback: bare soname, let dlopen do the work
52
73
  return `lib${name}.dylib`;
53
74
  }
54
75
 
76
+ function isFile(file) {
77
+ try {
78
+ return statSync(file).isFile();
79
+ } catch {
80
+ return false;
81
+ }
82
+ }
83
+
84
+ // ABI di `ldconfig -p` per l'architettura del processo, come il mach_map di
85
+ // ctypes.util: su sistemi multiarch evita di scegliere la libreria a 32 bit.
86
+ function ldconfigAbi() {
87
+ switch (os.arch()) {
88
+ case "x64":
89
+ return "libc6,x86-64";
90
+ case "ppc64":
91
+ case "s390x":
92
+ return "libc6,64bit";
93
+ default:
94
+ return "libc6";
95
+ }
96
+ }
97
+
98
+ // Confronto di versioni numeriche di soname ("so.1.10" > "so.1.9").
99
+ function compareVersions(a, b) {
100
+ const pa = a.split(".").map(Number);
101
+ const pb = b.split(".").map(Number);
102
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
103
+ const d = (pa[i] ?? -1) - (pb[i] ?? -1);
104
+ if (d !== 0) return d;
105
+ }
106
+ return 0;
107
+ }
108
+
55
109
  function findLibraryLinux(name) {
56
- // 1) Try the ldconfig cache — most reliable on modern glibc.
110
+ // 1) ldconfig cache, as ctypes.util._findSoname_ldconfig: the soname (e.g.
111
+ // "libc.so.6") of the first entry with the ABI of this process.
57
112
  try {
58
- const out = execSync("/sbin/ldconfig -p", { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
59
- const re = new RegExp(`^\\s*lib${escapeRegex(name)}\\.so[^\\s]*\\s.*=>\\s*(\\S+)`, "m");
113
+ const out = execSync("/sbin/ldconfig -p", { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], env: { ...process.env, LC_ALL: "C", LANG: "C" } });
114
+ const re = new RegExp(`\\s+(lib${escapeRegex(name)}\\.[^\\s]+)\\s+\\(${escapeRegex(ldconfigAbi())}`);
60
115
  const m = out.match(re);
61
116
  if (m) return m[1];
62
117
  } catch {}
63
118
 
64
- // 2) Walk common directories.
119
+ // 2) Walk common directories: highest versioned soname, then the bare name.
65
120
  const dirs = ["/usr/lib", "/usr/lib64", "/usr/local/lib", "/lib", "/lib64", "/lib/x86_64-linux-gnu", "/usr/lib/x86_64-linux-gnu", "/usr/lib/aarch64-linux-gnu"];
121
+ const prefix = `lib${name}.so.`;
66
122
  for (const dir of dirs) {
67
- const bare = path.join(dir, `lib${name}.so`);
68
- if (existsSync(bare)) return bare;
69
- // Also try versioned sonames (libc.so.6, libssl.so.3, ...)
123
+ let versions = [];
70
124
  try {
71
- // Can't glob here without fs.readdirSync; do a cheap scan.
72
- const fs = require("node:fs");
73
- for (const entry of fs.readdirSync(dir)) {
74
- if (entry.startsWith(`lib${name}.so.`)) return path.join(dir, entry);
75
- }
125
+ versions = readdirSync(dir)
126
+ .filter((entry) => entry.startsWith(prefix) && /^\d+(\.\d+)*$/.test(entry.slice(prefix.length)))
127
+ .map((entry) => entry.slice(prefix.length));
76
128
  } catch {}
129
+ if (versions.length > 0) {
130
+ versions.sort(compareVersions);
131
+ return path.join(dir, prefix + versions[versions.length - 1]);
132
+ }
133
+ const bare = path.join(dir, `lib${name}.so`);
134
+ if (existsSync(bare)) return bare;
77
135
  }
78
136
 
79
137
  // 3) Fallback: bare soname. dlopen will still try LD_LIBRARY_PATH.
@@ -88,6 +146,7 @@ function escapeRegex(s) {
88
146
  * Resolve a library name to a platform-specific filename/path.
89
147
  *
90
148
  * @param {string} name - Bare library name (e.g. "c", "ssl", "user32").
149
+ * @param {Object} [native] - Native module (dyld shared cache lookup on macOS)
91
150
  * @returns {string|null} Resolved filename/path, or null if the input is invalid.
92
151
  *
93
152
  * @example
@@ -95,13 +154,13 @@ function escapeRegex(s) {
95
154
  * find_library("ssl") // "libssl.so.3" / "ssl.dll"
96
155
  * find_library("user32") // "user32.dll" (Windows)
97
156
  */
98
- export function find_library(name) {
157
+ export function find_library(name, native) {
99
158
  if (!name || typeof name !== "string") return null;
100
159
  switch (process.platform) {
101
160
  case "win32":
102
161
  return findLibraryWindows(name);
103
162
  case "darwin":
104
- return findLibraryDarwin(name);
163
+ return findLibraryDarwin(name, (file) => native?.dyldSharedCacheContains?.(file) === true);
105
164
  default:
106
165
  return findLibraryLinux(name);
107
166
  }