-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
Copy pathffi.exports.js
386 lines (338 loc) · 9.49 KB
/
ffi.exports.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
// --- FFIType ---
var ffi = globalThis.Bun.FFI;
export const ptr = (arg1, arg2) =>
typeof arg2 === "undefined" ? ffi.ptr(arg1) : ffi.ptr(arg1, arg2);
export const toBuffer = ffi.toBuffer;
export const toArrayBuffer = ffi.toArrayBuffer;
export const viewSource = ffi.viewSource;
const BunCString = ffi.CString;
const nativeLinkSymbols = ffi.linkSymbols;
export class CString extends String {
constructor(ptr, byteOffset, byteLength) {
super(
ptr
? typeof byteLength === "number" && Number.isSafeInteger(byteLength)
? new BunCString(ptr, byteOffset || 0, byteLength)
: new BunCString(ptr)
: ""
);
this.ptr = typeof ptr === "number" ? ptr : 0;
if (typeof byteOffset !== "undefined") {
this.byteOffset = byteOffset;
}
if (typeof byteLength !== "undefined") {
this.byteLength = byteLength;
}
}
ptr;
byteOffset;
byteLength;
#cachedArrayBuffer;
get arrayBuffer() {
if (this.#cachedArrayBuffer) {
return this.#cachedArrayBuffer;
}
if (!this.ptr) {
return (this.#cachedArrayBuffer = new ArrayBuffer(0));
}
return (this.#cachedArrayBuffer = toArrayBuffer(
this.ptr,
this.byteOffset,
this.byteLength
));
}
}
Object.defineProperty(globalThis, "__GlobalBunCString", {
value: CString,
enumerable: false,
configurable: false,
});
const ffiWrappers = new Array(16);
var char = (val) => val | 0;
ffiWrappers.fill(char);
ffiWrappers[FFIType.uint8_t] = function uint8(val) {
return val < 0 ? 0 : val >= 255 ? 255 : val | 0;
};
ffiWrappers[FFIType.int16_t] = function int16(val) {
return val <= -8192 ? -8192 : val >= 8192 ? 8192 : val | 0;
};
ffiWrappers[FFIType.uint16_t] = function uint16(val) {
return val <= 0 ? 0 : val >= 16384 ? 16384 : val | 0;
};
ffiWrappers[FFIType.int32_t] = function int32(val) {
return val | 0;
};
// we never want to return NaN
ffiWrappers[FFIType.uint32_t] = function uint32(val) {
return val <= 0 ? 0 : val >= 0xffffffff ? 0xffffffff : +val || 0;
};
ffiWrappers[FFIType.i64_fast] = function int64(val) {
if (typeof val === "bigint") {
if (val < BigInt(Number.MAX_VALUE)) {
return Number(val).valueOf() || 0;
}
return val;
}
return !val ? 0 : +val || 0;
};
ffiWrappers[FFIType.u64_fast] = function u64_fast(val) {
if (typeof val === "bigint") {
if (val < BigInt(Number.MAX_VALUE) && val > 0) {
return Number(val).valueOf() || 0;
}
return val;
}
return !val ? 0 : +val || 0;
};
ffiWrappers[FFIType.int64_t] = function int64(val) {
if (typeof val === "bigint") {
return val;
}
if (typeof val === "number") {
return BigInt(val || 0);
}
return BigInt(+val || 0);
};
ffiWrappers[FFIType.uint64_t] = function uint64(val) {
if (typeof val === "bigint") {
return val;
}
if (typeof val === "number") {
return val <= 0 ? BigInt(0) : BigInt(val || 0);
}
return BigInt(+val || 0);
};
ffiWrappers[FFIType.u64_fast] = function u64_fast(val) {
if (typeof val === "bigint") {
return val < BigInt(Number.MAX_VALUE)
? val <= BigInt(0)
? 0
: Number(val)
: val;
}
return typeof val === "number" ? (val <= 0 ? 0 : +val || 0) : +val || 0;
};
ffiWrappers[FFIType.uint16_t] = function uint16(val) {
const ret = (typeof val === "bigint" ? Number(val) : val) | 0;
return ret <= 0 ? 0 : ret > 0xffff ? 0xffff : ret;
};
ffiWrappers[FFIType.double] = function double(val) {
if (typeof val === "bigint") {
if (val.valueOf() < BigInt(Number.MAX_VALUE)) {
return (
Math.abs(Number(val).valueOf()) + 0.00000000000001 - 0.00000000000001
);
}
}
if (!val) {
return 0 + 0.00000000000001 - 0.00000000000001;
}
return val + 0.00000000000001 - 0.00000000000001;
};
ffiWrappers[FFIType.float] = ffiWrappers[10] = function float(val) {
return Math.fround(val);
};
ffiWrappers[FFIType.bool] = function bool(val) {
return !!val;
};
// This prevents an extra property getter in potentially hot code
Object.defineProperty(globalThis, "__GlobalBunFFIPtrFunctionForWrapper", {
value: ptr,
enumerable: false,
configurable: true,
});
ffiWrappers[FFIType.cstring] = ffiWrappers[FFIType.pointer] = function pointer(
val
) {
if (typeof val === "number") return val;
if (!val) {
return 0;
}
if (ArrayBuffer.isView(val) || val instanceof ArrayBuffer) {
return __GlobalBunFFIPtrFunctionForWrapper(val);
}
if (typeof val === "string") {
throw new TypeError(
"To convert a string to a pointer, encode it as a buffer"
);
}
throw new TypeError(`Unable to convert ${val} to a pointer`);
};
function cstringReturnType(val) {
return new __GlobalBunCString(val);
}
function FFIBuilder(params, returnType, functionToCall, name) {
const hasReturnType =
typeof FFIType[returnType] === "number" &&
FFIType[returnType] !== FFIType.void;
var paramNames = new Array(params.length);
var args = new Array(params.length);
for (let i = 0; i < params.length; i++) {
paramNames[i] = `p${i}`;
const wrapper = ffiWrappers[FFIType[params[i]]];
if (wrapper) {
// doing this inline benchmarked about 4x faster than referencing
args[i] = `(${wrapper.toString()})(p${i})`;
} else {
throw new TypeError(
`Unsupported type ${params[i]}. Must be one of: ${Object.keys(FFIType)
.sort()
.join(", ")}`
);
}
}
var code = `functionToCall(${args.join(", ")})`;
if (hasReturnType) {
if (FFIType[returnType] === FFIType.cstring) {
code = `return (${cstringReturnType.toString()})(${code})`;
} else {
code = `return ${code}`;
}
}
var func = new Function("functionToCall", ...paramNames, code);
Object.defineProperty(func, "name", {
value: name,
});
// variadic arguments can be expensive
// most FFI functions are going to be < 5 arguments
// so we just inline it
var wrap;
switch (paramNames.length) {
case 0:
wrap = () => func(functionToCall);
break;
case 1:
wrap = (arg1) => func(functionToCall, arg1);
break;
case 2:
wrap = (arg1, arg2) => func(functionToCall, arg1, arg2);
break;
case 3:
wrap = (arg1, arg2, arg3) => func(functionToCall, arg1, arg2, arg3);
break;
case 4:
wrap = (arg1, arg2, arg3, arg4) =>
func(functionToCall, arg1, arg2, arg3, arg4);
break;
case 5:
wrap = (arg1, arg2, arg3, arg4, arg5) =>
func(functionToCall, arg1, arg2, arg3, arg4, arg5);
case 6:
wrap = (arg1, arg2, arg3, arg4, arg5, arg6) =>
func(functionToCall, arg1, arg2, arg3, arg4, arg5, arg6);
break;
case 7:
wrap = (arg1, arg2, arg3, arg4, arg5, arg6, arg7) =>
func(functionToCall, arg1, arg2, arg3, arg4, arg5, arg6, arg7);
break;
case 8:
wrap = (arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8) =>
func(functionToCall, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8);
break;
case 9:
wrap = (arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9) =>
func(
functionToCall,
arg1,
arg2,
arg3,
arg4,
arg5,
arg6,
arg7,
arg8,
arg9
);
break;
default: {
wrap = (...args) => func(functionToCall, ...args);
break;
}
}
wrap.native = functionToCall;
wrap.ptr = functionToCall.ptr;
return wrap;
}
const nativeDLOpen = ffi.dlopen;
const nativeCallback = ffi.callback;
export const native = {
dlopen: nativeDLOpen,
callback: nativeCallback,
};
export function dlopen(path, options) {
const result = nativeDLOpen(path, options);
for (let key in result.symbols) {
var symbol = result.symbols[key];
if (
options[key]?.args?.length ||
FFIType[options[key]?.returns] === FFIType.cstring
) {
result.symbols[key] = FFIBuilder(
options[key].args ?? [],
options[key].returns ?? FFIType.void,
symbol,
// in stacktraces:
// instead of
// "/usr/lib/sqlite3.so"
// we want
// "sqlite3_get_version() - sqlit3.so"
path.includes("/")
? `${key} (${path.split("/").pop()})`
: `${key} (${path})`
);
} else {
// consistentcy
result.symbols[key].native = result.symbols[key];
}
}
return result;
}
export function linkSymbols(options) {
const result = nativeLinkSymbols(options);
for (let key in result.symbols) {
var symbol = result.symbols[key];
if (
options[key]?.args?.length ||
FFIType[options[key]?.returns] === FFIType.cstring
) {
result.symbols[key] = FFIBuilder(
options[key].args ?? [],
options[key].returns ?? FFIType.void,
symbol,
key
);
} else {
// consistentcy
result.symbols[key].native = result.symbols[key];
}
}
return result;
}
var cFunctionI = 0;
var cFunctionRegistry;
function onCloseCFunction(close) {
close();
}
export function CFunction(options) {
const identifier = `CFunction${cFunctionI++}`;
var result = linkSymbols({
[identifier]: options,
});
var hasClosed = false;
var close = result.close;
result.symbols[identifier].close = () => {
if (hasClosed || !close) return;
hasClosed = true;
close();
close = undefined;
};
cFunctionRegistry ||= new FinalizationRegistry(onCloseCFunction);
cFunctionRegistry.register(
result.symbols[identifier],
result.symbols[identifier].close
);
return result.symbols[identifier];
}
export function callback(options, cb) {
return nativeCallback(options, cb);
}