-
Notifications
You must be signed in to change notification settings - Fork 146
/
ffi.cc
360 lines (306 loc) · 11.2 KB
/
ffi.cc
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
#define NAPI_VERSION 6
#define NAPI_EXPERIMENTAL /* Until Node.js v12.17.0 is released */
#include "ffi.h"
#include "fficonfig.h"
#include <get-uv-event-loop-napi.h>
namespace FFI {
InstanceData* InstanceData::Get(Env env) {
void* d = nullptr;
napi_status status = napi_get_instance_data(env, &d);
assert(status == napi_ok);
return static_cast<InstanceData*>(d);
}
void InstanceData::Dispose() {
if (async.type != UV_ASYNC) return;
uv_close(reinterpret_cast<uv_handle_t*>(&async), [](uv_handle_t* handle) {
InstanceData* self = static_cast<InstanceData*>(handle->data);
uv_mutex_destroy(&self->mutex);
delete self;
});
}
TypedArray WrapPointerImpl(Env env, char* ptr, size_t length) {
InstanceData* data = InstanceData::Get(env);
assert(data->ref_napi_instance != nullptr);
return TypedArray(env, data->ref_napi_instance->WrapPointer(ptr, length));
}
char* GetBufferDataImpl(Value val) {
InstanceData* data = InstanceData::Get(val.Env());
assert(data->ref_napi_instance != nullptr);
return data->ref_napi_instance->GetBufferData(val);
}
static int __ffi_errno() { return errno; }
Object FFI::InitializeStaticFunctions(Env env) {
Object o = Object::New(env);
// dl functions used by the DynamicLibrary JS class
o["dlopen"] = WrapPointer(env, dlopen);
o["dlclose"] = WrapPointer(env, dlclose);
o["dlsym"] = WrapPointer(env, dlsym);
o["dlerror"] = WrapPointer(env, dlerror);
o["_errno"] = WrapPointer(env, __ffi_errno);
return o;
}
#define SET_ENUM_VALUE(_value) \
target[#_value] = Number::New(env, static_cast<uint32_t>(_value));
void FFI::InitializeBindings(Env env, Object target) {
target["version"] = PACKAGE_VERSION;
target["ffi_prep_cif"] = Function::New(env, FFIPrepCif);
target["ffi_prep_cif_var"] = Function::New(env, FFIPrepCifVar);
target["ffi_call"] = Function::New(env, FFICall);
target["ffi_call_async"] = Function::New(env, FFICallAsync);
// `ffi_status` enum values
SET_ENUM_VALUE(FFI_OK);
SET_ENUM_VALUE(FFI_BAD_TYPEDEF);
SET_ENUM_VALUE(FFI_BAD_ABI);
// `ffi_abi` enum values
SET_ENUM_VALUE(FFI_DEFAULT_ABI);
SET_ENUM_VALUE(FFI_FIRST_ABI);
SET_ENUM_VALUE(FFI_LAST_ABI);
/* ---- ARM processors ---------- */
#ifdef __arm__
SET_ENUM_VALUE(FFI_SYSV);
SET_ENUM_VALUE(FFI_VFP);
/* ---- Intel x86 Win32 ---------- */
#elif defined(X86_WIN32)
SET_ENUM_VALUE(FFI_SYSV);
SET_ENUM_VALUE(FFI_STDCALL);
SET_ENUM_VALUE(FFI_THISCALL);
SET_ENUM_VALUE(FFI_FASTCALL);
SET_ENUM_VALUE(FFI_MS_CDECL);
#elif defined(X86_WIN64)
SET_ENUM_VALUE(FFI_WIN64);
#elif defined __aarch64__
SET_ENUM_VALUE(FFI_SYSV);
#elif defined(X86_64) || (defined (__x86_64__) && defined (X86_DARWIN))
/* Unix variants all use the same ABI for x86-64 */
SET_ENUM_VALUE(FFI_UNIX64);
#else
/* ---- Intel x86 and AMD x86-64 - */
SET_ENUM_VALUE(FFI_SYSV);
#endif
/* flags for dlopen() */
#ifdef RTLD_LAZY
SET_ENUM_VALUE(RTLD_LAZY);
#endif
#ifdef RTLD_NOW
SET_ENUM_VALUE(RTLD_NOW);
#endif
#ifdef RTLD_LOCAL
SET_ENUM_VALUE(RTLD_LOCAL);
#endif
#ifdef RTLD_GLOBAL
SET_ENUM_VALUE(RTLD_GLOBAL);
#endif
#ifdef RTLD_NOLOAD
SET_ENUM_VALUE(RTLD_NOLOAD);
#endif
#ifdef RTLD_NODELETE
SET_ENUM_VALUE(RTLD_NODELETE);
#endif
#ifdef RTLD_FIRST
SET_ENUM_VALUE(RTLD_FIRST);
#endif
/* flags for dlsym() */
#ifdef RTLD_NEXT
target["RTLD_NEXT"] = WrapPointer(env, RTLD_NEXT);
#endif
#ifdef RTLD_DEFAULT
target["RTLD_DEFAULT"] = WrapPointer(env, RTLD_DEFAULT);
#endif
#ifdef RTLD_SELF
target["RTLD_SELF"] = WrapPointer(env, RTLD_SELF);
#endif
#ifdef RTLD_MAIN_ONLY
target["RTLD_MAIN_ONLY"] = WrapPointer(env, RTLD_MAIN_ONLY);
#endif
target["FFI_ARG_SIZE"] = Number::New(env, sizeof(ffi_arg));
target["FFI_SARG_SIZE"] = Number::New(env, sizeof(ffi_sarg));
target["FFI_TYPE_SIZE"] = Number::New(env, sizeof(ffi_type));
target["FFI_CIF_SIZE"] = Number::New(env, sizeof(ffi_cif));
Object ftmap = Object::New(env);
ftmap["void"] = WrapPointer(env, &ffi_type_void);
ftmap["uint8"] = WrapPointer(env, &ffi_type_uint8);
ftmap["int8"] = WrapPointer(env, &ffi_type_sint8);
ftmap["uint16"] = WrapPointer(env, &ffi_type_uint16);
ftmap["int16"] = WrapPointer(env, &ffi_type_sint16);
ftmap["uint32"] = WrapPointer(env, &ffi_type_uint32);
ftmap["int32"] = WrapPointer(env, &ffi_type_sint32);
ftmap["uint64"] = WrapPointer(env, &ffi_type_uint64);
ftmap["int64"] = WrapPointer(env, &ffi_type_sint64);
ftmap["uchar"] = WrapPointer(env, &ffi_type_uchar);
ftmap["char"] = WrapPointer(env, &ffi_type_schar);
ftmap["ushort"] = WrapPointer(env, &ffi_type_ushort);
ftmap["short"] = WrapPointer(env, &ffi_type_sshort);
ftmap["uint"] = WrapPointer(env, &ffi_type_uint);
ftmap["int"] = WrapPointer(env, &ffi_type_sint);
ftmap["float"] = WrapPointer(env, &ffi_type_float);
ftmap["double"] = WrapPointer(env, &ffi_type_double);
ftmap["pointer"] = WrapPointer(env, &ffi_type_pointer);
// NOTE: "long" and "ulong" get handled in JS-land
// Let libffi handle "long long"
ftmap["ulonglong"] = WrapPointer(env, &ffi_type_ulong);
ftmap["longlong"] = WrapPointer(env, &ffi_type_slong);
target["FFI_TYPES"] = ftmap;
}
/*
* Function that creates and returns an `ffi_cif` pointer from the given return
* value type and argument types.
*
* args[0] - the CIF buffer
* args[1] - the number of args
* args[2] - the "return type" pointer
* args[3] - the "arguments types array" pointer
* args[4] - the ABI to use
*
* returns the ffi_status result from ffi_prep_cif()
*/
Value FFI::FFIPrepCif(const Napi::CallbackInfo& args) {
Env env = args.Env();
if (!args[0].IsBuffer())
throw TypeError::New(env, "prepCif(): Buffer required as cif arg");
if (!args[2].IsBuffer())
throw TypeError::New(env, "prepCif(): Buffer required as rtype arg");
if (!args[3].IsBuffer())
throw TypeError::New(env, "prepCif(): Buffer required as atypes arg");
ffi_cif* cif = GetBufferData<ffi_cif>(args[0]);
uint32_t nargs = args[1].ToNumber();
ffi_type* rtype = GetBufferData<ffi_type>(args[2]);
ffi_type** atypes = GetBufferData<ffi_type*>(args[3]);
ffi_abi abi = static_cast<ffi_abi>(args[4].ToNumber().Int32Value());
ffi_status status = ffi_prep_cif(cif, abi, nargs, rtype, atypes);
return Number::New(env, status);
}
/*
* Function that creates and returns an `ffi_cif` pointer from the given return
* value type and argument types.
*
* args[0] - the CIF buffer
* args[1] - the number of fixed args
* args[2] - the number of total args
* args[3] - the "return type" pointer
* args[4] - the "arguments types array" pointer
* args[5] - the ABI to use
*
* returns the ffi_status result from ffi_prep_cif_var()
*/
Value FFI::FFIPrepCifVar(const Napi::CallbackInfo& args) {
Env env = args.Env();
if (!args[0].IsBuffer())
throw TypeError::New(env, "prepCifVar(): Buffer required as cif arg");
if (!args[3].IsBuffer())
throw TypeError::New(env, "prepCifVar(): Buffer required as rtype arg");
if (!args[3].IsBuffer())
throw TypeError::New(env, "prepCifVar(): Buffer required as atypes arg");
ffi_cif* cif = GetBufferData<ffi_cif>(args[0]);
uint32_t fargs = args[1].ToNumber();
uint32_t targs = args[2].ToNumber();
ffi_type* rtype = GetBufferData<ffi_type>(args[3]);
ffi_type** atypes = GetBufferData<ffi_type*>(args[4]);
ffi_abi abi = static_cast<ffi_abi>(args[5].ToNumber().Int32Value());
ffi_status status = ffi_prep_cif_var(cif, abi, fargs, targs, rtype, atypes);
return Number::New(env, status);
}
/*
* JS wrapper around `ffi_call()`.
*
* args[0] - Buffer - the `ffi_cif *`
* args[1] - Buffer - the C function pointer to invoke
* args[2] - Buffer - the `void *` buffer big enough to hold the return value
* args[3] - Buffer - the `void **` array of pointers containing the arguments
*/
void FFI::FFICall(const Napi::CallbackInfo& args) {
Env env = args.Env();
if (!args[0].IsBuffer() || !args[1].IsBuffer() ||
!args[2].IsBuffer() || !args[3].IsBuffer()) {
throw TypeError::New(env, "ffi_call() requires 4 Buffer arguments!");
}
ffi_cif* cif = GetBufferData<ffi_cif>(args[0]);
char* fn = GetBufferData<char>(args[1]);
char* res = GetBufferData<char>(args[2]);
void** fnargs = GetBufferData<void*>(args[3]);
ffi_call(cif, FFI_FN(fn), static_cast<void*>(res), fnargs);
}
/*
* Asynchronous JS wrapper around `ffi_call()`.
*
* args[0] - Buffer - the `ffi_cif *`
* args[1] - Buffer - the C function pointer to invoke
* args[2] - Buffer - the `void *` buffer big enough to hold the return value
* args[3] - Buffer - the `void **` array of pointers containing the arguments
* args[4] - Function - the callback function to invoke when complete
*/
void FFI::FFICallAsync(const Napi::CallbackInfo& args) {
Env env = args.Env();
if (!args[0].IsBuffer() || !args[1].IsBuffer() ||
!args[2].IsBuffer() || !args[3].IsBuffer()) {
throw TypeError::New(env, "ffi_call_async() requires 4 Buffer arguments!");
}
if (!args[4].IsFunction()) {
throw TypeError::New(env, "ffi_call_async() requires a function argument");
}
// store a persistent references to all the Buffers and the callback function
AsyncCallParams* p = new AsyncCallParams(env);
p->cif = GetBufferData<ffi_cif>(args[0]);
p->fn = GetBufferData<char>(args[1]);
p->res = GetBufferData<char>(args[2]);
p->argv = GetBufferData<void*>(args[3]);
p->result = FFI_OK;
p->callback = Reference<Function>::New(args[4].As<Function>(), 1);
p->req.data = p;
uv_queue_work(get_uv_event_loop(env),
&p->req,
FFI::AsyncFFICall,
FFI::FinishAsyncFFICall);
}
/*
* Called on the thread pool.
*/
void FFI::AsyncFFICall(uv_work_t* req) {
AsyncCallParams* p = static_cast<AsyncCallParams*>(req->data);
try {
ffi_call(p->cif, FFI_FN(p->fn), p->res, p->argv);
} catch (std::exception& e) {
p->err = e.what();
}
}
/*
* Called after the AsyncFFICall function completes on the thread pool.
* This gets run on the main loop thread.
*/
void FFI::FinishAsyncFFICall(uv_work_t* req, int status) {
AsyncCallParams* p = static_cast<AsyncCallParams*>(req->data);
Env env = p->env;
HandleScope scope(env);
std::vector<napi_value> argv = { env.Null() };
if (p->result != FFI_OK) {
argv[0] = String::New(env, p->err);
}
// invoke the registered callback function
// TODO: Track napi_async_context properly
p->callback.MakeCallback(Object::New(env), argv);
// free up our memory (allocated in FFICallAsync)
delete p;
}
Value InitializeBindings(const Napi::CallbackInfo& args) {
Env env = args.Env();
assert(args[0].IsExternal());
InstanceData* data = InstanceData::Get(env);
data->ref_napi_instance = args[0].As<External<RefNapi::Instance>>().Data();
Object exports = Object::New(env);
FFI::InitializeBindings(env, exports);
exports["StaticFunctions"] = FFI::InitializeStaticFunctions(env);
exports["Callback"] = CallbackInfo::Initialize(env);
return exports;
}
} // namespace FFI
Napi::Object BindingHook(Napi::Env env, Napi::Object exports) {
FFI::InstanceData* data = new FFI::InstanceData(env);
napi_status status = napi_set_instance_data(
env, data, [](napi_env env, void* data, void* hint) {
static_cast<FFI::InstanceData*>(data)->Dispose();
}, nullptr);
if (status != napi_ok) delete data;
exports["initializeBindings"] =
Napi::Function::New(env, FFI::InitializeBindings);
return exports;
}
NODE_API_MODULE(ffi_bindings, BindingHook)