Debian Codegraph @

texk/web2c/luatexdir/luaffi/ffi.h

raw
1 /* vim: ts=4 sw=4 sts=4 et tw=78
2 * Portions copyright (c) 2015-present, Facebook, Inc. All rights reserved.
3 * Portions copyright (c) 2011 James R. McKaskill.
4 *
5 * This source code is licensed under the BSD-style license found in the
6 * LICENSE file in the root directory of this source tree. An additional grant
7 * of patent rights can be found in the PATENTS file in the same directory.
8 */
9
10 #pragma once
11
12 #ifdef _MSC_VER
13 #define _CRT_SECURE_NO_WARNINGS
14 #endif
15
16 #include <stdint.h>
17 #include <stdbool.h>
18 #include <stdlib.h>
19 #include <string.h>
20 #include <assert.h>
21
22 /*
23 #include <execinfo.h>
24 #define STACK_TRACE() {\
25 void* callstack[128]; \
26 int i, frames = backtrace(callstack, 128); \
27 backtrace_symbols_fd(callstack, frames, STDERR_FILENO); \
28 }
29 */
30
31 #ifdef __cplusplus
32 extern "C" {
33 # include <lua.h>
34 # include <lauxlib.h>
35 # include <lualib.h>
36 }
37 # define EXTERN_C extern "C"
38 #else
39 # include <lua.h>
40 # include <lauxlib.h>
41 # include <lualib.h>
42 # define EXTERN_C extern
43 #endif
44
45 #ifdef _WIN32
46 #include <windows.h>
47 #else
48 #include <errno.h>
49 #include <unistd.h>
50 #include <dlfcn.h>
51 #include <sys/mman.h>
52 #endif
53
54 #if !defined(_MSC_VER) && !defined(__MINGW64__)
55 #include <complex.h>
56 #define HAVE_COMPLEX
57 #endif
58 #define HAVE_LONG_DOUBLE
59
60 #ifndef NDEBUG
61 #define DASM_CHECKS
62 #endif
63
64 struct jit;
65 #define Dst_DECL struct jit* Dst
66 #define Dst_REF (Dst->ctx)
67 #define DASM_EXTERN(a,b,c,d) get_extern(a,b,c,d)
68
69 #include "dynasm/dasm_proto.h"
70
71 #if defined LUA_FFI_BUILD_AS_DLL
72 # define EXPORT __declspec(dllexport)
73 #elif defined __GNUC__
74 # define EXPORT __attribute__((visibility("default")))
75 #else
76 # define EXPORT
77 #endif
78
79 EXTERN_C EXPORT int luaopen_ffi(lua_State* L);
80
81 static int lua_absindex2(lua_State* L, int idx) {
82 return (LUA_REGISTRYINDEX <= idx && idx < 0)
83 ? lua_gettop(L) + idx + 1
84 : idx;
85 }
86 /* use our own version of lua_absindex such that lua_absindex(L, 0) == 0 */
87 #define lua_absindex(L, idx) lua_absindex2(L, idx)
88
89 #if LUA_VERSION_NUM == 501
90 static void lua_callk(lua_State *L, int nargs, int nresults, int ctx, lua_CFunction k)
91 {
92 lua_call(L, nargs, nresults);
93 }
94 /*
95 ** set functions from list 'l' into table at top - 'nup'; each
96 ** function gets the 'nup' elements at the top as upvalues.
97 ** Returns with only the table at the stack.
98 */
99 static void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup) {
100 luaL_checkstack(L, nup, "too many upvalues");
101 for (; l && l->name; l++) { /* fill the table with given functions */
102 int i;
103 for (i = 0; i < nup; i++) /* copy upvalues to the top */
104 lua_pushvalue(L, -nup);
105 lua_pushcclosure(L, l->func, nup); /* closure with those upvalues */
106 lua_setfield(L, -(nup + 2), l->name);
107 }
108 lua_pop(L, nup); /* remove upvalues */
109 }
110 #define lua_setuservalue lua_setfenv
111 #define lua_getuservalue lua_getfenv
112 #define lua_rawlen lua_objlen
113 static char* luaL_prepbuffsize(luaL_Buffer* B, size_t sz) {
114 if (sz > LUAL_BUFFERSIZE) {
115 luaL_error(B->L, "string too long");
116 }
117 return luaL_prepbuffer(B);
118 }
119 #elif LUA_VERSION_NUM >= 503
120 static void (lua_remove)(lua_State *L, int idx) {
121 lua_remove(L, idx);
122 }
123 #endif
124
125 /* architectures */
126 #if defined _WIN32 && defined UNDER_CE
127 # define OS_CE
128 #elif defined _WIN32
129 # define OS_WIN
130 #elif defined __APPLE__ && defined __MACH__
131 # define OS_OSX
132 #elif defined __linux__
133 # define OS_LINUX
134 #elif defined __FreeBSD__ || defined __OpenBSD__ || defined __NetBSD__
135 # define OS_BSD
136 #elif defined unix || defined __unix__ || defined __unix || defined _POSIX_VERSION || defined _XOPEN_VERSION
137 # define OS_POSIX
138 #endif
139
140 /* architecture */
141 #if defined __i386__ || defined _M_IX86
142 # define ARCH_X86
143 #elif defined __amd64__ || defined _M_X64
144 # define ARCH_X64
145 #elif defined __arm__ || defined __ARM__ || defined ARM || defined __ARM || defined __arm
146 # define ARCH_ARM
147 #elif defined __aarch64__
148 # define ARCH_ARM64
149 #elif defined __powerpc64__
150 # define ARCH_PPC64
151 #else
152 # define UNSUPPORTED_ARCH /*error*/
153 # pragma message("luaffi: UNSUPPORTED_ARCH")
154 #endif
155
156
157 /* See ffi.c: replace luaopen_ffi with a stub */
158 /* if FFI_ENABLE_LUATEX_INTERFACE is not defined */
159 #if (defined ARCH_X86 || defined ARCH_X64) && (defined OS_CE || defined OS_WIN || defined OS_LINUX || defined OS_BSD || defined OS_POSIX || defined OS_OSX) || ( defined ARCH_ARM64 && (defined OS_LINUX ||defined OS_POSIX || defined OS_OSX))
160 #define FFI_ENABLE_LUATEX_INTERFACE
161 #endif
162 /* for the moment */
163 #if (defined __CYGWIN__)
164 #undef FFI_ENABLE_LUATEX_INTERFACE
165 #endif
166
167
168
169 #ifdef _WIN32
170
171 # ifdef UNDER_CE
172 static void* DoLoadLibraryA(const char* name) {
173 wchar_t buf[MAX_PATH];
174 int sz = MultiByteToWideChar(CP_UTF8, 0, name, -1, buf, 512);
175 if (sz > 0) {
176 buf[sz] = 0;
177 return LoadLibraryW(buf);
178 } else {
179 return NULL;
180 }
181 }
182 # define LoadLibraryA DoLoadLibraryA
183 # else
184 # define GetProcAddressA GetProcAddress
185 # endif
186
187 # define LIB_FORMAT_1 "%s.dll"
188 # define AllocPage(size) VirtualAlloc(NULL, size, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE)
189 # define FreePage(data, size) VirtualFree(data, 0, MEM_RELEASE)
190 # define EnableExecute(data, size) do {DWORD old; VirtualProtect(data, size, PAGE_EXECUTE, &old); FlushInstructionCache(GetCurrentProcess(), data, size);} while (0)
191 # define EnableWrite(data, size) do {DWORD old; VirtualProtect(data, size, PAGE_READWRITE, &old);} while (0)
192
193 #else
194 #ifdef OS_OSX
195 # define LIB_FORMAT_1 "%s.dylib"
196 # define LIB_FORMAT_2 "lib%s.dylib"
197 #else
198 # define LIB_FORMAT_1 "%s.so"
199 # define LIB_FORMAT_2 "lib%s.so"
200 #endif
201 # define LoadLibraryA(name) dlopen(name, RTLD_LAZY | RTLD_GLOBAL)
202 # define GetProcAddressA(lib, name) dlsym(lib, name)
203 # define AllocPage(size) mmap(NULL, size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON, -1, 0)
204 # define FreePage(data, size) munmap(data, size)
205 # define EnableExecute(data, size) mprotect(data, size, PROT_READ|PROT_EXEC)
206 # define EnableWrite(data, size) mprotect(data, size, PROT_READ|PROT_WRITE)
207 #endif
208
209 //#if defined ARCH_X86 || defined ARCH_X64
210 #if defined ARCH_X86 || defined ARCH_X64 || defined ARCH_ARM64
211 #define ALLOW_MISALIGNED_ACCESS
212 #endif
213
214 struct token;
215
216 struct parser {
217 int line;
218 const char* next;
219 const char* prev;
220 unsigned align_mask;
221 };
222
223 struct page {
224 size_t size;
225 size_t off;
226 size_t freed;
227 };
228
229 struct jit {
230 lua_State* L;
231 int32_t last_errno;
232 dasm_State* ctx;
233 size_t pagenum;
234 struct page** pages;
235 size_t align_page_size;
236 void** globals;
237 int function_extern;
238 void* lua_dll;
239 void* kernel32_dll;
240 };
241
242 #define ALIGN_DOWN(PTR, MASK) \
243 (((uintptr_t) (PTR)) & (~ ((uintptr_t) (MASK)) ))
244 #define ALIGN_UP(PTR, MASK) \
245 (( ((uintptr_t) (PTR)) + ((uintptr_t) (MASK)) ) & (~ ((uintptr_t) (MASK)) ))
246
247 /* struct cdata/struct ctype */
248
249 #define PTR_ALIGN_MASK (sizeof(void*) - 1)
250 #define FUNCTION_ALIGN_MASK (sizeof(void (*)()) - 1)
251 #define DEFAULT_ALIGN_MASK 7
252
253 #ifdef OS_OSX
254 /* TODO: figure out why the alignof trick doesn't work on OS X */
255 #define ALIGNED_DEFAULT 7
256 #elif defined __GNUC__
257 #define ALIGNED_DEFAULT (__alignof__(void* __attribute__((aligned))) - 1)
258 #else
259 #define ALIGNED_DEFAULT PTR_ALIGN_MASK
260 #endif
261
262 extern int jit_key;
263 extern int ctype_mt_key;
264 extern int cdata_mt_key;
265 extern int cmodule_mt_key;
266 extern int callback_mt_key;
267 extern int constants_key;
268 extern int types_key;
269 extern int gc_key;
270 extern int callbacks_key;
271 extern int functions_key;
272 extern int abi_key;
273 extern int next_unnamed_key;
274 extern int niluv_key;
275 extern int asmname_key;
276
277 int equals_upval(lua_State* L, int idx, int* key);
278 void push_upval(lua_State* L, int* key);
279 void set_upval(lua_State* L, int* key);
280 struct jit* get_jit(lua_State* L);
281
282 /* both ctype and cdata are stored as userdatas
283 *
284 * usr value is a table shared between the related subtypes which has:
285 * name -> member ctype (for structs and unions)
286 * +ves -> member ctype - in memory order (for structs)
287 * +ves -> argument ctype (for function prototypes)
288 * 0 -> return ctype (for function prototypes)
289 * light userdata -> misc
290 */
291
292 enum {
293 C_CALL,
294 STD_CALL,
295 FAST_CALL,
296 };
297
298 enum {
299 INVALID_TYPE,
300 VOID_TYPE,
301 FLOAT_TYPE,
302 DOUBLE_TYPE,
303 LONG_DOUBLE_TYPE,
304 COMPLEX_FLOAT_TYPE,
305 COMPLEX_DOUBLE_TYPE,
306 COMPLEX_LONG_DOUBLE_TYPE,
307 BOOL_TYPE,
308 INT8_TYPE,
309 INT16_TYPE,
310 INT32_TYPE,
311 INT64_TYPE,
312 INTPTR_TYPE,
313 ENUM_TYPE,
314 UNION_TYPE,
315 STRUCT_TYPE,
316 FUNCTION_TYPE,
317 FUNCTION_PTR_TYPE,
318 };
319
320 #define IS_CHAR_UNSIGNED (((char) -1) > 0)
321 #define IS_COMPLEX(type) ((type) == COMPLEX_FLOAT_TYPE || (type) == COMPLEX_DOUBLE_TYPE)
322
323 #define POINTER_BITS 2
324 #define POINTER_MAX ((1 << POINTER_BITS) - 1)
325
326 #define ALIGNOF(S) ((int) ((char*) &S.v - (char*) &S - 1))
327
328 /* Note: if adding a new member that is associated with a struct/union
329 * definition then it needs to be copied over in ctype.c:set_defined for when
330 * we create types based off of the declaration alone.
331 *
332 * Since this is used as a header for every ctype and cdata, and we create a
333 * ton of them on the stack, we try and minimise its size.
334 */
335 struct ctype {
336 size_t base_size; /* size of the base type in bytes */
337
338 union {
339 /* valid if is_bitfield */
340 struct {
341 /* size of bitfield in bits */
342 unsigned bit_size : 7;
343 /* offset within the current byte between 0-63 */
344 unsigned bit_offset : 6;
345 };
346 /* Valid if is_array */
347 size_t array_size;
348 /* Valid for is_variable_struct or is_variable_array. If
349 * variable_size_known (only used for is_variable_struct) then this is
350 * the total increment otherwise this is the per element increment.
351 */
352 size_t variable_increment;
353 };
354 size_t offset;
355 unsigned align_mask : 4; /* as (align bytes - 1) eg 7 gives 8 byte alignment */
356 unsigned pointers : POINTER_BITS; /* number of dereferences to get to the base type including +1 for arrays */
357 unsigned const_mask : POINTER_MAX + 1; /* const pointer mask, LSB is current pointer, +1 for the whether the base type is const */
358 unsigned type : 5; /* value given by type enum above */
359 unsigned is_reference : 1;
360 unsigned is_array : 1;
361 unsigned is_defined : 1;
362 unsigned is_null : 1;
363 unsigned has_member_name : 1;
364 unsigned calling_convention : 2;
365 unsigned has_var_arg : 1;
366 unsigned is_variable_array : 1; /* set for variable array types where we don't know the variable size yet */
367 unsigned is_variable_struct : 1;
368 unsigned variable_size_known : 1; /* used for variable structs after we know the variable size */
369 unsigned is_bitfield : 1;
370 unsigned has_bitfield : 1;
371 unsigned is_jitted : 1;
372 unsigned is_packed : 1;
373 unsigned is_unsigned : 1;
374 };
375
376 #ifdef _MSC_VER
377 __declspec(align(16))
378 #endif
379 struct cdata {
380 const struct ctype type
381 #ifdef __GNUC__
382 __attribute__ ((aligned(16)))
383 #endif
384 ;
385 };
386
387 typedef void (*cfunction)(void);
388
389 #ifdef HAVE_COMPLEX
390 typedef double complex complex_double;
391 typedef float complex complex_float;
392 static complex_double mk_complex_double(double real, double imag) {
393 return real + imag * 1i;
394 }
395 static complex_double mk_complex_float(double real, double imag) {
396 return real + imag * 1i;
397 }
398 #else
399 typedef struct {
400 double real, imag;
401 } complex_double;
402
403 typedef struct {
404 float real, imag;
405 } complex_float;
406
407 static complex_double mk_complex_double(double real, double imag) {
408 complex_double ret = { real, imag };
409 return ret;
410 }
411 static complex_float mk_complex_float(float real, float imag) {
412 complex_float ret = { real, imag };
413 return ret;
414 }
415 static double creal(complex_double c) {
416 return c.real;
417 }
418 static float crealf(complex_float c) {
419 return c.real;
420 }
421
422 static double cimag(complex_double c) {
423 return c.imag;
424 }
425 static float cimagf(complex_float c) {
426 return c.imag;
427 }
428 #endif
429
430 #define CALLBACK_FUNC_USR_IDX 1
431
432 void set_defined(lua_State* L, int ct_usr, struct ctype* ct);
433 struct ctype* push_ctype(lua_State* L, int ct_usr, const struct ctype* ct);
434 void* push_cdata(lua_State* L, int ct_usr, const struct ctype* ct); /* called from asm */
435 void push_callback(lua_State* L, cfunction luafunc, cfunction cfunc);
436 void check_ctype(lua_State* L, int idx, struct ctype* ct);
437 void* to_cdata(lua_State* L, int idx, struct ctype* ct);
438 void* check_cdata(lua_State* L, int idx, struct ctype* ct);
439 size_t ctype_size(lua_State* L, const struct ctype* ct);
440
441 int parse_type(lua_State* L, struct parser* P, struct ctype* type);
442 void parse_argument(lua_State* L, struct parser* P, int ct_usr, struct ctype* type, struct token* name, struct parser* asmname);
443 void push_type_name(lua_State* L, int usr, const struct ctype* ct);
444
445 int push_user_mt(lua_State* L, int ct_usr, const struct ctype* ct);
446
447 int ffi_cdef(lua_State* L);
448
449 void push_func_ref(lua_State* L, cfunction func);
450 void free_code(struct jit* jit, lua_State* L, cfunction func);
451 int x86_return_size(lua_State* L, int usr, const struct ctype* ct);
452 void compile_function(lua_State* L, cfunction f, int ct_usr, const struct ctype* ct);
453 cfunction compile_callback(lua_State* L, int fidx, int ct_usr, const struct ctype* ct);
454 void compile_globals(struct jit* jit, lua_State* L);
455 int get_extern(struct jit* jit, uint8_t* addr, int idx, int type);
456
457 /* WARNING: assembly needs to be updated for prototype changes of these functions */
458 int check_bool(lua_State* L, int idx);
459 double check_double(lua_State* L, int idx);
460 double check_complex_imag(lua_State* L, int idx);
461 float check_float(lua_State* L, int idx);
462 uint64_t check_uint64(lua_State* L, int idx);
463 int64_t check_int64(lua_State* L, int idx);
464 int32_t check_int32(lua_State* L, int idx);
465 uint32_t check_uint32(lua_State* L, int idx);
466 int16_t check_int16(lua_State* L, int idx);
467 uint16_t check_uint16(lua_State* L, int idx);
468 int8_t check_int8(lua_State* L, int idx);
469 uint8_t check_uint8(lua_State* L, int idx);
470 uintptr_t check_uintptr(lua_State* L, int idx);
471 int32_t check_enum(lua_State* L, int idx, int to_usr, const struct ctype* tt);
472 /* these two will always push a value so that we can create structs/functions on the fly */
473 void* check_typed_pointer(lua_State* L, int idx, int to_usr, const struct ctype* tt);
474 cfunction check_typed_cfunction(lua_State* L, int idx, int to_usr, const struct ctype* tt);
475 complex_double check_complex_double(lua_State* L, int idx);
476 complex_float check_complex_float(lua_State* L, int idx);
477
478 void unpack_varargs_stack(lua_State* L, int first, int last, char* to);
479 void unpack_varargs_reg(lua_State* L, int first, int last, char* to);
480
481 void unpack_varargs_stack_skip(lua_State* L, int first, int last, int ints_to_skip, int floats_to_skip, char* to);
482 void unpack_varargs_float(lua_State* L, int first, int last, int max, char* to);
483 void unpack_varargs_int(lua_State* L, int first, int last, int max, char* to);
484
485
486