node-ctypes 2.2.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.
Files changed (38) hide show
  1. package/CHANGELOG.md +932 -0
  2. package/README.md +504 -99
  3. package/build/Release/ctypes-darwin-arm64.node +0 -0
  4. package/build/Release/ctypes-darwin-x64.node +0 -0
  5. package/build/Release/ctypes-linux-arm64-musl.node +0 -0
  6. package/build/Release/ctypes-linux-arm64.node +0 -0
  7. package/build/Release/ctypes-linux-x64-musl.node +0 -0
  8. package/build/Release/ctypes-linux-x64.node +0 -0
  9. package/build/Release/ctypes-win32-arm64.node +0 -0
  10. package/build/Release/ctypes-win32-x64.node +0 -0
  11. package/lib/core/Library.js +136 -109
  12. package/lib/core/callback.js +17 -20
  13. package/lib/core/conversions.js +376 -16
  14. package/lib/core/funcptr.js +148 -73
  15. package/lib/core/lazy-loader.js +10 -4
  16. package/lib/core/types.js +201 -98
  17. package/lib/index.d.ts +276 -83
  18. package/lib/index.js +44 -32
  19. package/lib/memory/buffer.js +82 -22
  20. package/lib/memory/operations.js +55 -45
  21. package/lib/memory/pointer.js +233 -57
  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/platform/win_types.js +8 -3
  26. package/lib/structures/Structure.js +252 -203
  27. package/lib/structures/Union.js +10 -21
  28. package/lib/structures/helpers/array.js +102 -16
  29. package/lib/structures/helpers/bitfield.js +75 -150
  30. package/lib/structures/helpers/common.js +310 -21
  31. package/lib/structures/helpers/layout.js +145 -0
  32. package/lib/structures/helpers/struct.js +160 -419
  33. package/lib/structures/helpers/union.js +154 -155
  34. package/lib/structures/helpers/wrap.js +3 -15
  35. package/lib/types/SimpleCData.js +11 -32
  36. package/lib/types/primitives.js +160 -113
  37. package/lib/utils/cache.js +34 -2
  38. package/package.json +4 -1
@@ -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
  }
@@ -1,3 +1,5 @@
1
+ import { booleanValue, registerSimpleType } from "../structures/helpers/common.js";
2
+
1
3
  /**
2
4
  * @file win_types.js
3
5
  * @module platform/win_types
@@ -43,14 +45,17 @@ export function createWinTypes(prims, { Structure, POINTER, array }) {
43
45
 
44
46
  // VARIANT_BOOL: 16-bit, VARIANT_TRUE = -1. Reads as a boolean, as Python.
45
47
  class VARIANT_BOOL extends c_short {
48
+ static _isBoolean = true;
49
+ static _isVariantBool = true;
46
50
  static _reader = (buf, off) => buf.readInt16LE(off) !== 0;
47
- static _writer = (buf, off, val) => buf.writeInt16LE(val ? -1 : 0, off);
51
+ static _writer = (buf, off, val) => buf.writeInt16LE(booleanValue(val) ? -1 : 0, off);
48
52
  static _readerBE = (buf, off) => buf.readInt16BE(off) !== 0;
49
- static _writerBE = (buf, off, val) => buf.writeInt16BE(val ? -1 : 0, off);
53
+ static _writerBE = (buf, off, val) => buf.writeInt16BE(booleanValue(val) ? -1 : 0, off);
50
54
  static from_param(val) {
51
- return val ? -1 : 0;
55
+ return booleanValue(val) ? -1 : 0;
52
56
  }
53
57
  }
58
+ registerSimpleType(VARIANT_BOOL);
54
59
 
55
60
  // String types
56
61
  const LPCOLESTR = c_wchar_p;