@lakutata/ffi 0.0.0-stage → 3.1.5
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/LICENSE +23 -0
- package/README.md +163 -2
- package/README.zh-CN.md +140 -0
- package/dist/cjs/components/NativeLibrary.d.ts +229 -0
- package/dist/cjs/components/NativeLibrary.js +346 -0
- package/dist/cjs/decorators/Library.d.ts +61 -0
- package/dist/cjs/decorators/Library.js +44 -0
- package/dist/cjs/decorators/Native.d.ts +69 -0
- package/dist/cjs/decorators/Native.js +90 -0
- package/dist/cjs/exceptions/NativeDeclarationException.d.ts +12 -0
- package/dist/cjs/exceptions/NativeDeclarationException.js +19 -0
- package/dist/cjs/exceptions/NativeLibraryClosedException.d.ts +12 -0
- package/dist/cjs/exceptions/NativeLibraryClosedException.js +19 -0
- package/dist/cjs/exceptions/NativeLibraryNotFoundException.d.ts +11 -0
- package/dist/cjs/exceptions/NativeLibraryNotFoundException.js +18 -0
- package/dist/cjs/exceptions/NativeMemoryException.d.ts +11 -0
- package/dist/cjs/exceptions/NativeMemoryException.js +18 -0
- package/dist/cjs/exports/FFI.d.ts +12 -0
- package/dist/cjs/exports/FFI.js +40 -0
- package/dist/cjs/exports/Generator.d.ts +2 -0
- package/dist/cjs/exports/Generator.js +10 -0
- package/dist/cjs/lib/Memory.d.ts +188 -0
- package/dist/cjs/lib/Memory.js +227 -0
- package/dist/cjs/lib/Runtime.d.ts +98 -0
- package/dist/cjs/lib/Runtime.js +209 -0
- package/dist/cjs/lib/backend/Functions.d.ts +65 -0
- package/dist/cjs/lib/backend/Functions.js +214 -0
- package/dist/cjs/lib/backend/KoffiTypes.d.ts +53 -0
- package/dist/cjs/lib/backend/KoffiTypes.js +426 -0
- package/dist/cjs/lib/declarations/Builtins.d.ts +33 -0
- package/dist/cjs/lib/declarations/Builtins.js +179 -0
- package/dist/cjs/lib/declarations/Layout.d.ts +41 -0
- package/dist/cjs/lib/declarations/Layout.js +180 -0
- package/dist/cjs/lib/declarations/Lexer.d.ts +40 -0
- package/dist/cjs/lib/declarations/Lexer.js +325 -0
- package/dist/cjs/lib/declarations/Parser.d.ts +90 -0
- package/dist/cjs/lib/declarations/Parser.js +1425 -0
- package/dist/cjs/lib/declarations/Platform.d.ts +50 -0
- package/dist/cjs/lib/declarations/Platform.js +27 -0
- package/dist/cjs/lib/declarations/Types.d.ts +173 -0
- package/dist/cjs/lib/declarations/Types.js +179 -0
- package/dist/cjs/lib/generator/CText.d.ts +14 -0
- package/dist/cjs/lib/generator/CText.js +133 -0
- package/dist/cjs/lib/generator/Generator.d.ts +136 -0
- package/dist/cjs/lib/generator/Generator.js +395 -0
- package/dist/cjs/lib/generator/Preprocessor.d.ts +60 -0
- package/dist/cjs/lib/generator/Preprocessor.js +94 -0
- package/dist/cjs/lib/generator/TypeScriptTypes.d.ts +35 -0
- package/dist/cjs/lib/generator/TypeScriptTypes.js +153 -0
- package/dist/cjs/lib/library/NativeCallback.d.ts +44 -0
- package/dist/cjs/lib/library/NativeCallback.js +66 -0
- package/dist/cjs/lib/library/NativeLibraryHandle.d.ts +268 -0
- package/dist/cjs/lib/library/NativeLibraryHandle.js +540 -0
- package/dist/cjs/lib/library/Resolve.d.ts +49 -0
- package/dist/cjs/lib/library/Resolve.js +130 -0
- package/dist/cjs/lib/thread/NativeThreads.d.ts +80 -0
- package/dist/cjs/lib/thread/NativeThreads.js +384 -0
- package/dist/cjs/lib/thread/NativeWorker.d.ts +6 -0
- package/dist/cjs/lib/thread/NativeWorker.js +96 -0
- package/dist/cjs/lib/thread/NativeWorkerCode.d.ts +5 -0
- package/dist/cjs/lib/thread/NativeWorkerCode.js +4 -0
- package/dist/cjs/lib/thread/PackageRequire.d.ts +6 -0
- package/dist/cjs/lib/thread/PackageRequire.js +4 -0
- package/dist/cjs/lib/thread/ThreadProtocol.d.ts +77 -0
- package/dist/cjs/lib/thread/ThreadProtocol.js +2 -0
- package/dist/cjs/package.json +1 -0
- package/dist/esm/components/NativeLibrary.js +338 -0
- package/dist/esm/decorators/Library.js +40 -0
- package/dist/esm/decorators/Native.js +85 -0
- package/dist/esm/exceptions/NativeDeclarationException.js +15 -0
- package/dist/esm/exceptions/NativeLibraryClosedException.js +15 -0
- package/dist/esm/exceptions/NativeLibraryNotFoundException.js +14 -0
- package/dist/esm/exceptions/NativeMemoryException.js +14 -0
- package/dist/esm/exports/FFI.js +10 -0
- package/dist/esm/exports/Generator.js +2 -0
- package/dist/esm/lib/Memory.js +210 -0
- package/dist/esm/lib/Runtime.js +192 -0
- package/dist/esm/lib/backend/Functions.js +206 -0
- package/dist/esm/lib/backend/KoffiTypes.js +418 -0
- package/dist/esm/lib/declarations/Builtins.js +174 -0
- package/dist/esm/lib/declarations/Layout.js +175 -0
- package/dist/esm/lib/declarations/Lexer.js +321 -0
- package/dist/esm/lib/declarations/Parser.js +1421 -0
- package/dist/esm/lib/declarations/Platform.js +23 -0
- package/dist/esm/lib/declarations/Types.js +170 -0
- package/dist/esm/lib/generator/CText.js +129 -0
- package/dist/esm/lib/generator/Generator.js +388 -0
- package/dist/esm/lib/generator/Preprocessor.js +87 -0
- package/dist/esm/lib/generator/TypeScriptTypes.js +149 -0
- package/dist/esm/lib/library/NativeCallback.js +59 -0
- package/dist/esm/lib/library/NativeLibraryHandle.js +532 -0
- package/dist/esm/lib/library/Resolve.js +122 -0
- package/dist/esm/lib/thread/NativeThreads.js +377 -0
- package/dist/esm/lib/thread/NativeWorker.js +93 -0
- package/dist/esm/lib/thread/NativeWorkerCode.js +1 -0
- package/dist/esm/lib/thread/PackageRequire.js +2 -0
- package/dist/esm/lib/thread/ThreadProtocol.js +1 -0
- package/dist/types/components/NativeLibrary.d.ts +229 -0
- package/dist/types/decorators/Library.d.ts +61 -0
- package/dist/types/decorators/Native.d.ts +69 -0
- package/dist/types/exceptions/NativeDeclarationException.d.ts +12 -0
- package/dist/types/exceptions/NativeLibraryClosedException.d.ts +12 -0
- package/dist/types/exceptions/NativeLibraryNotFoundException.d.ts +11 -0
- package/dist/types/exceptions/NativeMemoryException.d.ts +11 -0
- package/dist/types/exports/FFI.d.ts +12 -0
- package/dist/types/exports/Generator.d.ts +2 -0
- package/dist/types/lib/Memory.d.ts +188 -0
- package/dist/types/lib/Runtime.d.ts +98 -0
- package/dist/types/lib/backend/Functions.d.ts +65 -0
- package/dist/types/lib/backend/KoffiTypes.d.ts +53 -0
- package/dist/types/lib/declarations/Builtins.d.ts +33 -0
- package/dist/types/lib/declarations/Layout.d.ts +41 -0
- package/dist/types/lib/declarations/Lexer.d.ts +40 -0
- package/dist/types/lib/declarations/Parser.d.ts +90 -0
- package/dist/types/lib/declarations/Platform.d.ts +50 -0
- package/dist/types/lib/declarations/Types.d.ts +173 -0
- package/dist/types/lib/generator/CText.d.ts +14 -0
- package/dist/types/lib/generator/Generator.d.ts +136 -0
- package/dist/types/lib/generator/Preprocessor.d.ts +60 -0
- package/dist/types/lib/generator/TypeScriptTypes.d.ts +35 -0
- package/dist/types/lib/library/NativeCallback.d.ts +44 -0
- package/dist/types/lib/library/NativeLibraryHandle.d.ts +268 -0
- package/dist/types/lib/library/Resolve.d.ts +49 -0
- package/dist/types/lib/thread/NativeThreads.d.ts +80 -0
- package/dist/types/lib/thread/NativeWorker.d.ts +6 -0
- package/dist/types/lib/thread/NativeWorkerCode.d.ts +5 -0
- package/dist/types/lib/thread/PackageRequire.d.ts +6 -0
- package/dist/types/lib/thread/ThreadProtocol.d.ts +77 -0
- package/package.json +85 -4
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import koffi from 'koffi';
|
|
2
|
+
/**
|
|
3
|
+
* A JS function a library can call at any time (a persistent callback), made by `callback()` of a library: give its
|
|
4
|
+
* `pointer` to the library, and release it when the library no longer calls it. The callbacks of a library are released
|
|
5
|
+
* when it is closed; a process has at most 8192 of them at a time.
|
|
6
|
+
*
|
|
7
|
+
* When it is called from another thread of the library, it runs in the JS thread once the event loop gets to it. An
|
|
8
|
+
* exception it throws goes to the error handler of its library (the `error` event of a component), and the library gets
|
|
9
|
+
* zero (or a null pointer) as its result.
|
|
10
|
+
* @example
|
|
11
|
+
* ```typescript
|
|
12
|
+
* import {loadNativeLibrary, type NativeCallback} from '@lakutata/ffi'
|
|
13
|
+
*
|
|
14
|
+
* const vendor = loadNativeLibrary('vendor', 'typedef void (*vendor_log)(int level, const char *message);')
|
|
15
|
+
* const setLogger = vendor.func<(logger: bigint | null) => void>('void vendor_set_logger(vendor_log logger)')
|
|
16
|
+
* const logger: NativeCallback = vendor.callback('vendor_log', (level: number, message: string): void => console.log(level, message))
|
|
17
|
+
* setLogger(logger.pointer)
|
|
18
|
+
* //Once the library no longer calls it
|
|
19
|
+
* setLogger(null)
|
|
20
|
+
* logger.release()
|
|
21
|
+
* ```
|
|
22
|
+
*/
|
|
23
|
+
export class NativeCallback {
|
|
24
|
+
#pointer;
|
|
25
|
+
#onRelease;
|
|
26
|
+
#released = false;
|
|
27
|
+
/**
|
|
28
|
+
* A registered callback (made by `callback()` of a library, not by this constructor).
|
|
29
|
+
* @param pointer Its pointer.
|
|
30
|
+
* @param onRelease Called once it is released.
|
|
31
|
+
*/
|
|
32
|
+
constructor(pointer, onRelease) {
|
|
33
|
+
this.#pointer = pointer;
|
|
34
|
+
this.#onRelease = onRelease;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* The pointer to give to the library: the address of a C function calling the JS function.
|
|
38
|
+
*/
|
|
39
|
+
get pointer() {
|
|
40
|
+
return this.#pointer;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Whether it is released: the library must not call it any more.
|
|
44
|
+
*/
|
|
45
|
+
get released() {
|
|
46
|
+
return this.#released;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Release it: its pointer is no longer valid, its slot is free for another callback. Releasing it again does
|
|
50
|
+
* nothing.
|
|
51
|
+
*/
|
|
52
|
+
release() {
|
|
53
|
+
if (this.#released)
|
|
54
|
+
return;
|
|
55
|
+
this.#released = true;
|
|
56
|
+
koffi.unregister(this.#pointer);
|
|
57
|
+
this.#onRelease(this);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
@@ -0,0 +1,532 @@
|
|
|
1
|
+
import koffi from 'koffi';
|
|
2
|
+
import { NativeDeclarationException } from '../../exceptions/NativeDeclarationException.js';
|
|
3
|
+
import { NativeLibraryClosedException } from '../../exceptions/NativeLibraryClosedException.js';
|
|
4
|
+
import { bindFunction, convertedCallback } from '../backend/Functions.js';
|
|
5
|
+
import { layoutOf } from '../declarations/Layout.js';
|
|
6
|
+
import { DeclarationParser } from '../declarations/Parser.js';
|
|
7
|
+
import { CURRENT_PLATFORM } from '../declarations/Platform.js';
|
|
8
|
+
import { typeText } from '../declarations/Types.js';
|
|
9
|
+
import { allocateNative, checkedPointer, freeNative, nativeErrno, nativeWindowsError, readNative, TypeNames, TYPES, typeSize, writeNative } from '../Runtime.js';
|
|
10
|
+
import { NativeThreads } from '../thread/NativeThreads.js';
|
|
11
|
+
import { NativeCallback } from './NativeCallback.js';
|
|
12
|
+
import { loadLibrary } from './Resolve.js';
|
|
13
|
+
/**
|
|
14
|
+
* The declarations of a library, shared by the libraries loaded with the same declarations: read once, their C types and
|
|
15
|
+
* their prototypes made once (koffi never frees a type)
|
|
16
|
+
*/
|
|
17
|
+
class LibraryModel {
|
|
18
|
+
#prototypes;
|
|
19
|
+
/**
|
|
20
|
+
* Read the declarations.
|
|
21
|
+
* @param declarations The C declarations.
|
|
22
|
+
*/
|
|
23
|
+
constructor(declarations) {
|
|
24
|
+
this.parser = new DeclarationParser(CURRENT_PLATFORM);
|
|
25
|
+
this.names = new TypeNames(this.parser);
|
|
26
|
+
this.#prototypes = new Map();
|
|
27
|
+
if (declarations)
|
|
28
|
+
this.parser.parse(declarations);
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* A prototype, read once.
|
|
32
|
+
* @param text The prototype.
|
|
33
|
+
*/
|
|
34
|
+
prototype(text) {
|
|
35
|
+
let declaration = this.#prototypes.get(text);
|
|
36
|
+
if (!declaration) {
|
|
37
|
+
declaration = this.parser.prototype(text);
|
|
38
|
+
this.#prototypes.set(text, declaration);
|
|
39
|
+
}
|
|
40
|
+
return declaration;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
const models = new Map();
|
|
44
|
+
/**
|
|
45
|
+
* The model of declarations, the same for the same text
|
|
46
|
+
* @param declarations
|
|
47
|
+
*/
|
|
48
|
+
function modelOf(declarations) {
|
|
49
|
+
let model = models.get(declarations);
|
|
50
|
+
if (!model) {
|
|
51
|
+
model = new LibraryModel(declarations);
|
|
52
|
+
models.set(declarations, model);
|
|
53
|
+
}
|
|
54
|
+
return model;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* The value a callback returns to the library when it throws: zero, false, a null pointer
|
|
58
|
+
* @param type
|
|
59
|
+
*/
|
|
60
|
+
function zeroOf(type) {
|
|
61
|
+
switch (type.kind) {
|
|
62
|
+
case 'primitive':
|
|
63
|
+
if (type.name === 'void')
|
|
64
|
+
return undefined;
|
|
65
|
+
if (type.name === 'bool')
|
|
66
|
+
return false;
|
|
67
|
+
return 0;
|
|
68
|
+
case 'enum':
|
|
69
|
+
return 0;
|
|
70
|
+
case 'pointer':
|
|
71
|
+
return null;
|
|
72
|
+
default:
|
|
73
|
+
return {};
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* A native library loaded with its declarations, without the container (scripts, tests): its functions, variables and
|
|
78
|
+
* callbacks, and the native memory read and written with its types. Made by {@link loadNativeLibrary}; a
|
|
79
|
+
* `NativeLibrary` component holds one.
|
|
80
|
+
* @example
|
|
81
|
+
* ```typescript
|
|
82
|
+
* import {loadNativeLibrary, type NativeLibraryHandle} from '@lakutata/ffi'
|
|
83
|
+
*
|
|
84
|
+
* const libc: NativeLibraryHandle = loadNativeLibrary('c', 'typedef struct { int quot; int rem; } div_t;')
|
|
85
|
+
* const div = libc.func<(numerator: number, denominator: number) => {quot: number, rem: number}>('div_t div(int numerator, int denominator)')
|
|
86
|
+
* console.log(div(17, 5))
|
|
87
|
+
* await libc.close()
|
|
88
|
+
* ```
|
|
89
|
+
*/
|
|
90
|
+
export class NativeLibraryHandle {
|
|
91
|
+
#library;
|
|
92
|
+
#file;
|
|
93
|
+
#model;
|
|
94
|
+
#parser;
|
|
95
|
+
#names;
|
|
96
|
+
#options;
|
|
97
|
+
#functions = new Map();
|
|
98
|
+
#callbacks = new Set();
|
|
99
|
+
#allocations = new Set();
|
|
100
|
+
#frees = new Map();
|
|
101
|
+
#calls;
|
|
102
|
+
#threads;
|
|
103
|
+
//The errno and the last error of Windows of the thread after the last asynchronous call completed in the threads
|
|
104
|
+
#threadErrno;
|
|
105
|
+
#threadWindowsError;
|
|
106
|
+
#pending = 0;
|
|
107
|
+
#drained = [];
|
|
108
|
+
#closed = false;
|
|
109
|
+
/**
|
|
110
|
+
* Load a library (see {@link loadNativeLibrary}).
|
|
111
|
+
* @param names Its file names: one, or one by platform; `c` for the C library.
|
|
112
|
+
* @param declarations Its C declarations: the types, functions and variables its functions use.
|
|
113
|
+
* @param options Where it is found, how it is closed.
|
|
114
|
+
*/
|
|
115
|
+
constructor(names, declarations = '', options = {}) {
|
|
116
|
+
this.#options = options;
|
|
117
|
+
this.#model = modelOf(declarations);
|
|
118
|
+
this.#parser = this.#model.parser;
|
|
119
|
+
this.#names = this.#model.names;
|
|
120
|
+
const { library, file } = loadLibrary(names, options);
|
|
121
|
+
this.#library = library;
|
|
122
|
+
this.#file = file;
|
|
123
|
+
if (options.threads !== undefined && (!Number.isInteger(options.threads) || options.threads < 0))
|
|
124
|
+
throw new NativeDeclarationException(`The threads of a library are a number of threads (${options.threads})`);
|
|
125
|
+
if (options.threads)
|
|
126
|
+
this.#threads = new NativeThreads(file, declarations, options.threads, options.crt);
|
|
127
|
+
this.#calls = {
|
|
128
|
+
start: () => {
|
|
129
|
+
if (this.#closed)
|
|
130
|
+
throw new NativeLibraryClosedException(`The library ${this.#file} is closed`);
|
|
131
|
+
this.#pending++;
|
|
132
|
+
},
|
|
133
|
+
end: () => {
|
|
134
|
+
if (--this.#pending > 0)
|
|
135
|
+
return;
|
|
136
|
+
const drained = this.#drained;
|
|
137
|
+
this.#drained = [];
|
|
138
|
+
for (const resolve of drained)
|
|
139
|
+
resolve();
|
|
140
|
+
}
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* The file the library was loaded from.
|
|
145
|
+
*/
|
|
146
|
+
get file() {
|
|
147
|
+
return this.#file;
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* Whether it is closed.
|
|
151
|
+
*/
|
|
152
|
+
get closed() {
|
|
153
|
+
return this.#closed;
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* The asynchronous calls running.
|
|
157
|
+
*/
|
|
158
|
+
get pending() {
|
|
159
|
+
return this.#pending;
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* The worker threads of the library (0: the asynchronous calls run in the thread pool of the runtime).
|
|
163
|
+
*/
|
|
164
|
+
get threads() {
|
|
165
|
+
return this.#threads?.count ?? 0;
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* Settled once the threads of the library have loaded it (at once without threads): rejected with the error of a
|
|
169
|
+
* thread that could not. The asynchronous calls wait for them anyway.
|
|
170
|
+
*/
|
|
171
|
+
get ready() {
|
|
172
|
+
return this.#threads?.ready ?? Promise.resolve();
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* The constants of its declarations: the values of the enumerations, of the static constants and of the macros whose
|
|
176
|
+
* value is an integer.
|
|
177
|
+
*/
|
|
178
|
+
get constants() {
|
|
179
|
+
return Object.fromEntries(this.#parser.declarations.constants);
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* Add C declarations to the ones of the library (and of the libraries loaded with the same declarations, which share
|
|
183
|
+
* them).
|
|
184
|
+
* @param text The declarations.
|
|
185
|
+
*/
|
|
186
|
+
declare(text) {
|
|
187
|
+
this.#parser.parse(text);
|
|
188
|
+
this.#threads?.declare(text);
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* A function of the library, from its prototype: the function of koffi itself when nothing has to be converted.
|
|
192
|
+
* @param prototype Its C prototype, with the types of the declarations: `int sqlite3_open(const char *filename,
|
|
193
|
+
* _Out_ sqlite3 **db)`.
|
|
194
|
+
* @param options Whether it is asynchronous, how its strings are freed, how its 64-bit integers are given.
|
|
195
|
+
* @returns The function.
|
|
196
|
+
*/
|
|
197
|
+
func(prototype, options = {}) {
|
|
198
|
+
this.#open();
|
|
199
|
+
const key = `${prototype}\u0000${JSON.stringify(options)}`;
|
|
200
|
+
let bound = this.#functions.get(key);
|
|
201
|
+
if (!bound) {
|
|
202
|
+
bound = this.#bind(this.#model.prototype(prototype), options, prototype, false);
|
|
203
|
+
this.#functions.set(key, bound);
|
|
204
|
+
}
|
|
205
|
+
return bound;
|
|
206
|
+
}
|
|
207
|
+
/**
|
|
208
|
+
* A function of the declarations, by its name.
|
|
209
|
+
* @param name Its name.
|
|
210
|
+
* @param options Whether it is asynchronous, how its strings are freed, how its 64-bit integers are given.
|
|
211
|
+
* @returns The function.
|
|
212
|
+
*/
|
|
213
|
+
function(name, options = {}) {
|
|
214
|
+
this.#open();
|
|
215
|
+
const declaration = this.#parser.declarations.functions.get(name);
|
|
216
|
+
if (!declaration)
|
|
217
|
+
throw new NativeDeclarationException(`The function ${name} is not declared`);
|
|
218
|
+
const key = `\u0001${name}\u0000${JSON.stringify(options)}`;
|
|
219
|
+
let bound = this.#functions.get(key);
|
|
220
|
+
if (!bound) {
|
|
221
|
+
bound = this.#bind(declaration, options, name, true);
|
|
222
|
+
this.#functions.set(key, bound);
|
|
223
|
+
}
|
|
224
|
+
return bound;
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* A variable the library exports: declared in the declarations (`extern const char sqlite3_version[];`), or by the
|
|
228
|
+
* declaration given.
|
|
229
|
+
* @param declaration Its name, or its declaration.
|
|
230
|
+
* @returns Its address, and the functions reading and writing its value.
|
|
231
|
+
*/
|
|
232
|
+
variable(declaration) {
|
|
233
|
+
this.#open();
|
|
234
|
+
let name = declaration.trim();
|
|
235
|
+
if (!/^[A-Za-z_]\w*$/.test(name)) {
|
|
236
|
+
const before = new Set(this.#parser.declarations.variables.keys());
|
|
237
|
+
this.#parser.parse(/;\s*$/.test(name) ? name : `${name};`);
|
|
238
|
+
name = [...this.#parser.declarations.variables.keys()].find((variable) => !before.has(variable)) ?? name.match(/(\w+)\s*(\[[^\]]*\])?\s*;?\s*$/)?.[1] ?? name;
|
|
239
|
+
}
|
|
240
|
+
const variable = this.#parser.declarations.variables.get(name);
|
|
241
|
+
if (!variable)
|
|
242
|
+
throw new NativeDeclarationException(`The variable ${name} is not declared`);
|
|
243
|
+
let address;
|
|
244
|
+
try {
|
|
245
|
+
address = this.#library.symbol(variable.symbol);
|
|
246
|
+
}
|
|
247
|
+
catch (error) {
|
|
248
|
+
throw new NativeDeclarationException(`The variable ${name} is not in the library (${variable.symbol}): ${error.message}`);
|
|
249
|
+
}
|
|
250
|
+
const type = variable.type;
|
|
251
|
+
const unknownLength = type.kind === 'array' && type.length === 0;
|
|
252
|
+
const converter = TYPES.converter(type);
|
|
253
|
+
return {
|
|
254
|
+
address: address,
|
|
255
|
+
get: () => {
|
|
256
|
+
this.#open();
|
|
257
|
+
if (unknownLength) {
|
|
258
|
+
const element = type.of;
|
|
259
|
+
return (element.kind === 'primitive' && element.name === 'char' ? koffi.decode.string(address) : address);
|
|
260
|
+
}
|
|
261
|
+
const value = koffi.decode(address, TYPES.type(type));
|
|
262
|
+
return (converter?.fromNative ? converter.fromNative(value) : value);
|
|
263
|
+
},
|
|
264
|
+
set: (value) => {
|
|
265
|
+
this.#open();
|
|
266
|
+
if (variable.constant)
|
|
267
|
+
throw new NativeDeclarationException(`The variable ${name} is const`);
|
|
268
|
+
if (unknownLength)
|
|
269
|
+
throw new NativeDeclarationException(`The array ${name} has no length: write its elements through its address`);
|
|
270
|
+
koffi.encode(address, TYPES.type(type), converter?.toNative ? converter.toNative(value) : value);
|
|
271
|
+
}
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
/**
|
|
275
|
+
* A persistent callback: a JS function the library can call at any time, released by `release()` or when the
|
|
276
|
+
* library is closed.
|
|
277
|
+
* @param type Its type: the name of a pointer-to-function type of the declarations (`vendor_log`), or its prototype
|
|
278
|
+
* (`void vendor_log(int level, const char *message)`).
|
|
279
|
+
* @param callback The JS function.
|
|
280
|
+
* @returns The callback, whose `pointer` is given to the library.
|
|
281
|
+
*/
|
|
282
|
+
callback(type, callback) {
|
|
283
|
+
this.#open();
|
|
284
|
+
let prototype;
|
|
285
|
+
if (type.includes('(')) {
|
|
286
|
+
prototype = this.#parser.prototype(type).type;
|
|
287
|
+
}
|
|
288
|
+
else {
|
|
289
|
+
const named = this.#names.type(type);
|
|
290
|
+
const target = named.kind === 'pointer' ? named.to : named;
|
|
291
|
+
if (target.kind !== 'function')
|
|
292
|
+
throw new NativeDeclarationException(`The type ${type} is not a function type (${typeText(named)})`);
|
|
293
|
+
prototype = target;
|
|
294
|
+
}
|
|
295
|
+
const onError = this.#options.onCallbackError ?? ((error) => console.error('A callback of a native library threw:', error));
|
|
296
|
+
const zero = zeroOf(prototype.result);
|
|
297
|
+
const safe = (...args) => {
|
|
298
|
+
try {
|
|
299
|
+
return callback(...args);
|
|
300
|
+
}
|
|
301
|
+
catch (error) {
|
|
302
|
+
onError(error);
|
|
303
|
+
return zero;
|
|
304
|
+
}
|
|
305
|
+
};
|
|
306
|
+
const pointer = koffi.register(convertedCallback(prototype, TYPES, safe), koffi.pointer(TYPES.prototype(prototype)));
|
|
307
|
+
const registered = new NativeCallback(pointer, (released) => this.#callbacks.delete(released));
|
|
308
|
+
this.#callbacks.add(registered);
|
|
309
|
+
return registered;
|
|
310
|
+
}
|
|
311
|
+
/**
|
|
312
|
+
* Read native memory, as a type of the declarations: a value, or an array of values.
|
|
313
|
+
* @param pointer The address.
|
|
314
|
+
* @param type The type: `int`, `struct timeval`, `char *` (a string).
|
|
315
|
+
* @param count The number of values, for an array.
|
|
316
|
+
* @returns The value, or the array.
|
|
317
|
+
*/
|
|
318
|
+
read(pointer, type, count) {
|
|
319
|
+
this.#open();
|
|
320
|
+
return readNative(this.#names, pointer, type, count);
|
|
321
|
+
}
|
|
322
|
+
/**
|
|
323
|
+
* Write a value to native memory, as a type of the declarations.
|
|
324
|
+
* @param pointer The address.
|
|
325
|
+
* @param type The type.
|
|
326
|
+
* @param value The value.
|
|
327
|
+
*/
|
|
328
|
+
write(pointer, type, value) {
|
|
329
|
+
this.#open();
|
|
330
|
+
writeNative(this.#names, pointer, type, value);
|
|
331
|
+
}
|
|
332
|
+
/**
|
|
333
|
+
* The size of a type of the declarations, in bytes.
|
|
334
|
+
* @param type The type.
|
|
335
|
+
*/
|
|
336
|
+
sizeOf(type) {
|
|
337
|
+
return typeSize(this.#names, type);
|
|
338
|
+
}
|
|
339
|
+
/**
|
|
340
|
+
* The offset of a member of a struct of the declarations, in bytes.
|
|
341
|
+
* @param type The struct.
|
|
342
|
+
* @param member The member.
|
|
343
|
+
*/
|
|
344
|
+
offsetOf(type, member) {
|
|
345
|
+
const record = this.#names.type(type);
|
|
346
|
+
if (record.kind !== 'struct' && record.kind !== 'union')
|
|
347
|
+
throw new NativeDeclarationException(`${type} is not a struct or a union`);
|
|
348
|
+
const placed = layoutOf(record, CURRENT_PLATFORM).members.find((candidate) => candidate.member.name === member);
|
|
349
|
+
if (!placed)
|
|
350
|
+
throw new NativeDeclarationException(`${type} has no member ${member}`);
|
|
351
|
+
return placed.offset;
|
|
352
|
+
}
|
|
353
|
+
/**
|
|
354
|
+
* Allocate native memory for values of a type of the declarations: memory that does not move, which the library can
|
|
355
|
+
* keep; freed by `free()`, or when the library is closed.
|
|
356
|
+
* @param type The type.
|
|
357
|
+
* @param count The number of values.
|
|
358
|
+
* @returns Its address.
|
|
359
|
+
*/
|
|
360
|
+
alloc(type, count = 1) {
|
|
361
|
+
this.#open();
|
|
362
|
+
const pointer = allocateNative(this.#names, type, count);
|
|
363
|
+
this.#allocations.add(pointer);
|
|
364
|
+
return pointer;
|
|
365
|
+
}
|
|
366
|
+
/**
|
|
367
|
+
* Free memory allocated by `alloc()`.
|
|
368
|
+
* @param pointer Its address.
|
|
369
|
+
*/
|
|
370
|
+
free(pointer) {
|
|
371
|
+
const address = checkedPointer(pointer, 'free');
|
|
372
|
+
this.#allocations.delete(address);
|
|
373
|
+
freeNative(address);
|
|
374
|
+
}
|
|
375
|
+
/**
|
|
376
|
+
* The errno of the last call of this thread (on Windows, the one of the C library given by the `crt` option); with
|
|
377
|
+
* threads, the one of the thread of the last asynchronous call completed (reliable with one thread, or when the
|
|
378
|
+
* asynchronous calls are awaited one at a time).
|
|
379
|
+
*/
|
|
380
|
+
errno() {
|
|
381
|
+
return this.#threadErrno ?? nativeErrno(this.#options.crt);
|
|
382
|
+
}
|
|
383
|
+
/**
|
|
384
|
+
* The last error of the Windows API (GetLastError) after the last call of this thread; with threads, the one of the
|
|
385
|
+
* thread of the last asynchronous call completed; undefined on the other systems.
|
|
386
|
+
*/
|
|
387
|
+
windowsError() {
|
|
388
|
+
return this.#threadWindowsError ?? nativeWindowsError();
|
|
389
|
+
}
|
|
390
|
+
/**
|
|
391
|
+
* The asynchronous calls running, once they have all returned.
|
|
392
|
+
* @param timeout How long to wait at most, in milliseconds.
|
|
393
|
+
* @returns Whether they have all returned.
|
|
394
|
+
*/
|
|
395
|
+
drain(timeout = Infinity) {
|
|
396
|
+
if (!this.#pending)
|
|
397
|
+
return Promise.resolve(true);
|
|
398
|
+
return new Promise((resolve) => {
|
|
399
|
+
const timer = Number.isFinite(timeout) ? setTimeout(() => resolve(false), timeout) : undefined;
|
|
400
|
+
this.#drained.push(() => {
|
|
401
|
+
if (timer)
|
|
402
|
+
clearTimeout(timer);
|
|
403
|
+
resolve(true);
|
|
404
|
+
});
|
|
405
|
+
});
|
|
406
|
+
}
|
|
407
|
+
/**
|
|
408
|
+
* Close the library: new asynchronous calls are refused, the running ones awaited (a worker thread stopped during
|
|
409
|
+
* one crashes Bun), the callbacks released, the memory of `alloc()` freed, the library unloaded (unless kept
|
|
410
|
+
* loaded; musl never unloads). Its functions must not be called any more: a function of an unloaded library ends
|
|
411
|
+
* the process. When calls still run after the timeout, the ones in the thread pool go on, the ones in the threads
|
|
412
|
+
* of the library are rejected (their threads end once they return), and the library, its callbacks and its memory
|
|
413
|
+
* are left as they are: a call returning into an unloaded library, or calling a released callback, would end the
|
|
414
|
+
* process.
|
|
415
|
+
* @param timeout How long to wait for the asynchronous calls, in milliseconds.
|
|
416
|
+
*/
|
|
417
|
+
async close(timeout = 10000) {
|
|
418
|
+
if (this.#closed)
|
|
419
|
+
return;
|
|
420
|
+
this.#closed = true;
|
|
421
|
+
//Decided before the threads close: they reject the calls still running, which then no longer count
|
|
422
|
+
const drained = await this.drain(timeout);
|
|
423
|
+
await this.#threads?.close();
|
|
424
|
+
this.#functions.clear();
|
|
425
|
+
if (!drained)
|
|
426
|
+
return;
|
|
427
|
+
for (const callback of [...this.#callbacks])
|
|
428
|
+
callback.release();
|
|
429
|
+
for (const pointer of this.#allocations)
|
|
430
|
+
freeNative(pointer);
|
|
431
|
+
this.#allocations.clear();
|
|
432
|
+
if (!this.#options.keepLoaded)
|
|
433
|
+
this.#library.unload();
|
|
434
|
+
}
|
|
435
|
+
/**
|
|
436
|
+
* Throws once the library is closed
|
|
437
|
+
*/
|
|
438
|
+
#open() {
|
|
439
|
+
if (this.#closed)
|
|
440
|
+
throw new NativeLibraryClosedException(`The library ${this.#file} is closed`);
|
|
441
|
+
}
|
|
442
|
+
/**
|
|
443
|
+
* A function bound, with its options; an asynchronous function of a library with threads, called in them
|
|
444
|
+
* @param declaration
|
|
445
|
+
* @param options
|
|
446
|
+
* @param text its prototype, or the name of the declared function
|
|
447
|
+
* @param named
|
|
448
|
+
*/
|
|
449
|
+
#bind(declaration, options, text, named) {
|
|
450
|
+
if (options.async && this.#threads)
|
|
451
|
+
return this.#threaded(this.#threads, { declaration: text, named: named, options: { free: options.free, int64: options.int64 }, type: declaration });
|
|
452
|
+
return bindFunction(this.#library, declaration, TYPES, (text) => this.#names.koffi(text), {
|
|
453
|
+
async: options.async,
|
|
454
|
+
int64: options.int64,
|
|
455
|
+
calls: this.#calls,
|
|
456
|
+
...options.free ? { free: this.#freeFunction(options.free) } : {}
|
|
457
|
+
});
|
|
458
|
+
}
|
|
459
|
+
/**
|
|
460
|
+
* An asynchronous function called in the threads of the library, counted as its other asynchronous calls
|
|
461
|
+
* @param threads
|
|
462
|
+
* @param fn
|
|
463
|
+
*/
|
|
464
|
+
#threaded(threads, fn) {
|
|
465
|
+
threads.bind(fn);
|
|
466
|
+
return (...args) => {
|
|
467
|
+
try {
|
|
468
|
+
this.#calls.start();
|
|
469
|
+
}
|
|
470
|
+
catch (error) {
|
|
471
|
+
return Promise.reject(error);
|
|
472
|
+
}
|
|
473
|
+
return threads.call(fn, args).then((result) => {
|
|
474
|
+
this.#threadErrno = result.errno;
|
|
475
|
+
this.#threadWindowsError = result.windowsError;
|
|
476
|
+
this.#calls.end();
|
|
477
|
+
return result.value;
|
|
478
|
+
}, (error) => {
|
|
479
|
+
this.#calls.end();
|
|
480
|
+
throw error;
|
|
481
|
+
});
|
|
482
|
+
};
|
|
483
|
+
}
|
|
484
|
+
/**
|
|
485
|
+
* The function freeing the strings of a function: one of the library, or free() of the C library
|
|
486
|
+
* @param free
|
|
487
|
+
*/
|
|
488
|
+
#freeFunction(free) {
|
|
489
|
+
if (free === true)
|
|
490
|
+
return (pointer) => koffi.free(pointer);
|
|
491
|
+
let found = this.#frees.get(free);
|
|
492
|
+
if (!found) {
|
|
493
|
+
try {
|
|
494
|
+
found = this.#library.func(free, 'void', ['void *']);
|
|
495
|
+
}
|
|
496
|
+
catch (error) {
|
|
497
|
+
throw new NativeDeclarationException(`The function ${free} freeing the strings is not in the library: ${error.message}`);
|
|
498
|
+
}
|
|
499
|
+
this.#frees.set(free, found);
|
|
500
|
+
}
|
|
501
|
+
return found;
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
/**
|
|
505
|
+
* Load a native library with its C declarations, without the container (scripts, tests); in an application, declare a
|
|
506
|
+
* `NativeLibrary` component instead. The library is looked for in the directories of `search`, then where the system
|
|
507
|
+
* looks for libraries.
|
|
508
|
+
* @param names Its file names: one (`sqlite3`, completed as the platform names libraries), one by platform
|
|
509
|
+
* (`{darwin: 'libsqlite3.dylib', linux: 'libsqlite3.so.0', win32: 'winsqlite3.dll'}`), or `c` for the C library.
|
|
510
|
+
* @param declarations Its C declarations: the types its functions use, its functions, its variables, its constants.
|
|
511
|
+
* @param options Where it is found, how it is closed.
|
|
512
|
+
* @returns The library.
|
|
513
|
+
* @throws {NativeLibraryNotFoundException} When it cannot be loaded (the message lists what was tried).
|
|
514
|
+
* @throws {NativeDeclarationException} When the declarations cannot be read.
|
|
515
|
+
* @example
|
|
516
|
+
* ```typescript
|
|
517
|
+
* import {loadNativeLibrary, type Out, type Pointer} from '@lakutata/ffi'
|
|
518
|
+
*
|
|
519
|
+
* const sqlite = loadNativeLibrary({darwin: 'libsqlite3.dylib', linux: 'libsqlite3.so.0', win32: 'winsqlite3.dll'}, `
|
|
520
|
+
* typedef struct sqlite3 sqlite3;
|
|
521
|
+
* #define SQLITE_OK 0
|
|
522
|
+
* `)
|
|
523
|
+
* const open = sqlite.func<(filename: string, db: Out<Pointer>) => number>('int sqlite3_open(const char *filename, _Out_ sqlite3 **db)')
|
|
524
|
+
* const close = sqlite.func<(db: Pointer) => number>('int sqlite3_close(sqlite3 *db)')
|
|
525
|
+
* const db: Out<Pointer> = [null]
|
|
526
|
+
* if (open(':memory:', db) === Number(sqlite.constants.SQLITE_OK)) close(db[0]!)
|
|
527
|
+
* await sqlite.close()
|
|
528
|
+
* ```
|
|
529
|
+
*/
|
|
530
|
+
export function loadNativeLibrary(names, declarations = '', options = {}) {
|
|
531
|
+
return new NativeLibraryHandle(names, declarations, options);
|
|
532
|
+
}
|