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