Debian Codegraph @

texk/web2c/luatexdir/luaffi/ffi.c

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 #include "ffi.h"
10 #include <math.h>
11 #include <inttypes.h>
12
13 #ifdef ARCH_ARM64
14 #include <arm_acle.h>
15 #endif
16
17
18 /* Set to 1 to get extra debugging on print */
19 #define DEBUG_TOSTRING 0
20
21 int jit_key;
22 int ctype_mt_key;
23 int cdata_mt_key;
24 int callback_mt_key;
25 int cmodule_mt_key;
26 int constants_key;
27 int types_key;
28 int gc_key;
29 int callbacks_key;
30 int functions_key;
31 int abi_key;
32 int next_unnamed_key;
33 int niluv_key;
34 int asmname_key;
35
36 static const char* etype_tostring(int type);
37 static void debug_print_type(const struct ctype* ct)
38 {
39 printf(" sz %zu %zu %zu align %d ptr %d %d %d type %s%s %d %d %d name %d call %d %d var %d %d %d bit %d %d %d %d jit %d\n",
40 /* sz */
41 ct->base_size,
42 ct->array_size,
43 ct->offset,
44 /* align */
45 ct->align_mask,
46 /* ptr */
47 ct->is_array,
48 ct->pointers,
49 ct->const_mask,
50 /* type */
51 ct->is_unsigned ? "u" : "",
52 etype_tostring(ct->type),
53 ct->is_reference,
54 ct->is_defined,
55 ct->is_null,
56 /* name */
57 ct->has_member_name,
58 /* call */
59 ct->calling_convention,
60 ct->has_var_arg,
61 /* var */
62 ct->is_variable_array,
63 ct->is_variable_struct,
64 ct->variable_size_known,
65 /* bit */
66 ct->is_bitfield,
67 ct->has_bitfield,
68 ct->bit_offset,
69 ct->bit_size,
70 /* jit */
71 ct->is_jitted);
72 }
73
74 void push_upval(lua_State* L, int* key)
75 {
76 lua_pushinteger(L, *key);
77 lua_rawget(L, LUA_REGISTRYINDEX);
78 }
79
80 void set_upval(lua_State* L, int* key)
81 {
82 *key = luaL_ref(L, LUA_REGISTRYINDEX);
83 }
84
85 int equals_upval(lua_State* L, int idx, int* key)
86 {
87 int ret;
88 lua_pushvalue(L, idx);
89 push_upval(L, key);
90 ret = lua_rawequal(L, -2, -1);
91 lua_pop(L, 2);
92 return ret;
93 }
94
95 struct jit* get_jit(lua_State* L)
96 {
97 struct jit* jit;
98 push_upval(L, &jit_key);
99 jit = (struct jit*) lua_touserdata(L, -1);
100 jit->L = L;
101 lua_pop(L, 1); /* still in registry */
102 return jit;
103 }
104
105 static int type_error(lua_State* L, int idx, const char* to_type, int to_usr, const struct ctype* to_ct)
106 {
107 luaL_Buffer B;
108 struct ctype ft;
109
110 assert(to_type || (to_usr && to_ct));
111 if (to_usr) {
112 to_usr = lua_absindex(L, to_usr);
113 }
114
115 idx = lua_absindex(L, idx);
116
117 luaL_buffinit(L, &B);
118 to_cdata(L, idx, &ft);
119
120 if (ft.type != INVALID_TYPE) {
121 push_type_name(L, -1, &ft);
122 lua_pushfstring(L, "unable to convert argument %d from cdata<%s> to cdata<", idx, lua_tostring(L, -1));
123 lua_remove(L, -2);
124 luaL_addvalue(&B);
125 } else {
126 lua_pushfstring(L, "unable to convert argument %d from lua<%s> to cdata<", idx, luaL_typename(L, idx));
127 luaL_addvalue(&B);
128 }
129
130 if (to_ct) {
131 push_type_name(L, to_usr, to_ct);
132 luaL_addvalue(&B);
133 } else {
134 luaL_addstring(&B, to_type);
135 }
136
137 luaL_addchar(&B, '>');
138
139 luaL_pushresult(&B);
140 return lua_error(L);
141 }
142
143 static void* userdata_toptr(lua_State* L, int idx)
144 {
145 void* ptr = lua_touserdata(L, idx);
146
147 // check for FILE*
148 lua_getmetatable(L, idx);
149 luaL_getmetatable(L, LUA_FILEHANDLE);
150 int isfile = lua_rawequal(L, -1, -2);
151 lua_pop(L, 2);
152
153 if (isfile) {
154 #if LUA_VERSION_NUM == 501
155 FILE** stream = (FILE**) ptr;
156 return *stream;
157 #else
158 luaL_Stream* stream = (luaL_Stream*) ptr;
159 return stream->f;
160 #endif
161 }
162
163 return ptr;
164 }
165
166 static int cdata_tointeger(lua_State* L, int idx, ptrdiff_t* val)
167 {
168 struct ctype ct;
169 void* addr = to_cdata(L, idx, &ct);
170 lua_pop(L, 1);
171
172 if (ct.pointers) {
173 return 0;
174 }
175
176 switch (ct.type) {
177 case INT8_TYPE:
178 *val = *(int8_t*)addr;
179 return 1;
180 case INT16_TYPE:
181 *val = *(int16_t*)addr;
182 return 1;
183 case INT32_TYPE:
184 *val = *(int32_t*)addr;
185 return 1;
186 case INT64_TYPE:
187 *val = *(int64_t*)addr;
188 return 1;
189 default:
190 return 0;
191 }
192 }
193
194 static int64_t check_intptr(lua_State* L, int idx, void* p, struct ctype* ct)
195 {
196 if (ct->type == INVALID_TYPE) {
197 int64_t ret;
198 memset(ct, 0, sizeof(*ct));
199 ct->base_size = 8;
200 ct->type = INT64_TYPE;
201 ct->is_defined = 1;
202 ret = (int64_t) luaL_checknumber(L, idx);
203 return ret;
204
205 } else if (ct->pointers) {
206 return (intptr_t) p;
207 }
208
209 switch (ct->type) {
210 case INTPTR_TYPE:
211 case FUNCTION_PTR_TYPE:
212 return *(intptr_t*) p;
213
214 case INT64_TYPE:
215 return *(int64_t*) p;
216
217 case INT32_TYPE:
218 return ct->is_unsigned ? (int64_t) *(uint32_t*) p : (int64_t) *(int32_t*) p;
219
220 case INT16_TYPE:
221 return ct->is_unsigned ? (int64_t) *(uint16_t*) p : (int64_t) *(int16_t*) p;
222
223 case INT8_TYPE:
224 return ct->is_unsigned ? (int64_t) *(uint8_t*) p : (int64_t) *(int8_t*) p;
225
226 default:
227 type_error(L, idx, "intptr_t", 0, NULL);
228 return 0;
229 }
230 }
231
232 static int get_cfunction_address(lua_State* L, int idx, cfunction* addr);
233
234 #define TO_NUMBER(TYPE, ALLOW_POINTERS, LUA_TONUMBER) \
235 TYPE ret = 0; \
236 void* p; \
237 struct ctype ct; \
238 cfunction f; \
239 \
240 switch (lua_type(L, idx)) { \
241 case LUA_TBOOLEAN: \
242 ret = (TYPE) lua_toboolean(L, idx); \
243 break; \
244 \
245 case LUA_TNUMBER: \
246 ret = (TYPE) LUA_TONUMBER(L, idx); \
247 break; \
248 \
249 case LUA_TSTRING: \
250 if (!ALLOW_POINTERS) { \
251 type_error(L, idx, #TYPE, 0, NULL); \
252 } \
253 ret = (TYPE) (intptr_t) lua_tostring(L, idx); \
254 break; \
255 \
256 case LUA_TLIGHTUSERDATA: \
257 if (!ALLOW_POINTERS) { \
258 type_error(L, idx, #TYPE, 0, NULL); \
259 } \
260 ret = (TYPE) (intptr_t) lua_topointer(L, idx); \
261 break; \
262 \
263 case LUA_TFUNCTION: \
264 if (!ALLOW_POINTERS) { \
265 type_error(L, idx, #TYPE, 0, NULL); \
266 } \
267 if (!get_cfunction_address(L, idx, &f)) { \
268 type_error(L, idx, #TYPE, 0, NULL); \
269 } \
270 ret = (TYPE) (intptr_t) f; \
271 break; \
272 \
273 case LUA_TUSERDATA: \
274 p = to_cdata(L, idx, &ct); \
275 \
276 if (ct.type == INVALID_TYPE) { \
277 if (!ALLOW_POINTERS) { \
278 type_error(L, idx, #TYPE, 0, NULL); \
279 } \
280 ret = (TYPE) (intptr_t) userdata_toptr(L, idx); \
281 } else if (ct.pointers || ct.type == STRUCT_TYPE || ct.type == UNION_TYPE) {\
282 if (!ALLOW_POINTERS) { \
283 type_error(L, idx, #TYPE, 0, NULL); \
284 } \
285 ret = (TYPE) (intptr_t) p; \
286 } else if (ct.type == COMPLEX_DOUBLE_TYPE) { \
287 ret = (TYPE) creal(*(complex_double*) p); \
288 } else if (ct.type == COMPLEX_FLOAT_TYPE) { \
289 ret = (TYPE) crealf(*(complex_float*) p); \
290 } else if (ct.type == DOUBLE_TYPE) { \
291 ret = (TYPE) *(double*) p; \
292 } else if (ct.type == FLOAT_TYPE) { \
293 ret = (TYPE) *(float*) p; \
294 } else { \
295 ret = check_intptr(L, idx, p, &ct); \
296 } \
297 lua_pop(L, 1); \
298 break; \
299 \
300 case LUA_TNIL: \
301 ret = (TYPE) 0; \
302 break; \
303 \
304 default: \
305 type_error(L, idx, #TYPE, 0, NULL); \
306 } \
307
308 static int64_t cast_int64(lua_State* L, int idx, int is_cast)
309 { TO_NUMBER(int64_t, is_cast, lua_tointeger); return ret; }
310
311 static uint64_t cast_uint64(lua_State* L, int idx, int is_cast)
312 { TO_NUMBER(uint64_t, is_cast, lua_tointeger); return ret; }
313
314 int8_t check_int8(lua_State* L, int idx)
315 { return (int8_t) cast_int64(L, idx, 0); }
316
317 uint8_t check_uint8(lua_State* L, int idx)
318 { return (uint8_t) cast_uint64(L, idx, 0); }
319
320 int16_t check_int16(lua_State* L, int idx)
321 { return (int16_t) cast_int64(L, idx, 0); }
322
323 uint16_t check_uint16(lua_State* L, int idx)
324 { return (uint16_t) cast_uint64(L, idx, 0); }
325 int32_t check_int32(lua_State* L, int idx)
326 { return (int32_t) cast_int64(L, idx, 0); }
327
328 uint32_t check_uint32(lua_State* L, int idx)
329 { return (uint32_t) cast_uint64(L, idx, 0); }
330
331 int64_t check_int64(lua_State* L, int idx)
332 { return cast_int64(L, idx, 0); }
333
334 uint64_t check_uint64(lua_State* L, int idx)
335 { return cast_uint64(L, idx, 0); }
336
337 double check_double(lua_State* L, int idx)
338 { TO_NUMBER(double, 0, lua_tonumber); return ret; }
339
340 float check_float(lua_State* L, int idx)
341 { TO_NUMBER(double, 0, lua_tonumber); return ret; }
342
343 uintptr_t check_uintptr(lua_State* L, int idx)
344 { TO_NUMBER(uintptr_t, 1, lua_tointeger); return ret; }
345
346 complex_double check_complex_double(lua_State* L, int idx)
347 {
348 double real = 0, imag = 0;
349 void* p;
350 struct ctype ct;
351
352 switch (lua_type(L, idx)) {
353 case LUA_TNUMBER:
354 real = (double) lua_tonumber(L, idx);
355 break;
356 case LUA_TTABLE:
357 lua_rawgeti(L, idx, 1);
358 real = check_double(L, -1);
359 lua_pop(L, 1);
360
361 lua_rawgeti(L, idx, 2);
362 if (lua_isnil(L, -1)) {
363 imag = real;
364 } else {
365 imag = check_double(L, -1);
366 }
367 lua_pop(L, 1);
368 break;
369 case LUA_TUSERDATA:
370 p = to_cdata(L, idx, &ct);
371 if (ct.type == COMPLEX_DOUBLE_TYPE) {
372 real = creal(*(complex_double*) p);
373 imag = cimag(*(complex_double*) p);
374 } else if (ct.type == COMPLEX_FLOAT_TYPE) {
375 real = crealf(*(complex_float*) p);
376 imag = cimagf(*(complex_float*) p);
377 } else if (ct.type == DOUBLE_TYPE) {
378 real = *(double*) p;
379 } else if (ct.type == FLOAT_TYPE) {
380 real = *(float*) p;
381 } else {
382 real = check_intptr(L, idx, p, &ct);
383 }
384 lua_pop(L, 1);
385 break;
386
387 default:
388 type_error(L, idx, "complex", 0, NULL);
389 }
390
391 return mk_complex_double(real, imag);
392 }
393
394 complex_float check_complex_float(lua_State* L, int idx)
395 {
396 complex_double d = check_complex_double(L, idx);
397 complex_float fc = mk_complex_float(creal(d), cimag(d));
398 return fc;
399 }
400
401 static size_t unpack_vararg(lua_State* L, int i, char* to)
402 {
403 void* p;
404 struct ctype ct;
405
406 switch (lua_type(L, i)) {
407 case LUA_TBOOLEAN:
408 *(int*) to = lua_toboolean(L, i);
409 return sizeof(int);
410
411 case LUA_TNUMBER:
412 *(double*) to = lua_tonumber(L, i); // TODO in Lua 5.3: lua_tointeger sometimes should be here
413 return sizeof(double);
414
415 case LUA_TSTRING:
416 *(const char**) to = lua_tostring(L, i);
417 return sizeof(const char*);
418
419 case LUA_TLIGHTUSERDATA:
420 *(void**) to = lua_touserdata(L, i);
421 return sizeof(void*);
422
423 case LUA_TUSERDATA:
424 p = to_cdata(L, i, &ct);
425 lua_pop(L, 1);
426
427 if (ct.type == INVALID_TYPE) {
428 *(void**) to = userdata_toptr(L, i);
429 return sizeof(void*);
430
431 } else if (ct.pointers || ct.type == INTPTR_TYPE) {
432 *(void**) to = p;
433 return sizeof(void*);
434
435 } else if (ct.type == INT8_TYPE) {
436 *(int8_t*) to = *(int8_t*) p;
437 return sizeof(int8_t);
438
439 } else if (ct.type == INT16_TYPE) {
440 *(int16_t*) to = *(int16_t*) p;
441 return sizeof(int16_t);
442
443 } else if (ct.type == INT32_TYPE) {
444 *(int32_t*) to = *(int32_t*) p;
445 return sizeof(int32_t);
446
447 } else if (ct.type == INT64_TYPE) {
448 *(int64_t*) to = *(int64_t*) p;
449 return sizeof(int64_t);
450 }
451 goto err;
452
453 case LUA_TNIL:
454 *(void**) to = NULL;
455 return sizeof(void*);
456
457 default:
458 goto err;
459 }
460
461 err:
462 return type_error(L, i, "vararg", 0, NULL);
463 }
464
465 void unpack_varargs_stack(lua_State* L, int first, int last, char* to)
466 {
467 int i;
468
469 for (i = first; i <= last; i++) {
470 #ifdef ARCH_ARM64
471 /* In 64 bit arm on all OS variadic stack arguments are 8 or 16 byte aligned */
472 {
473 size_t sz = unpack_vararg(L, i, to);
474 if (sz > 8) {
475 /* Aligned to 16 bytes */
476 sz += 16 - (sz % 16);
477 to += sz;
478 }
479 else {
480 /* Aligned to 8 bytes */
481 to += 8;
482 }
483 }
484 #else
485 to += unpack_vararg(L, i, to);
486 #endif
487 }
488 }
489
490 void unpack_varargs_stack_skip(lua_State* L, int first, int last, int ints_to_skip, int floats_to_skip, char* to)
491 {
492 int i;
493
494 for (i = first; i <= last; i++) {
495 int type = lua_type(L, i);
496
497 if (type == LUA_TNUMBER && --floats_to_skip >= 0) {
498 continue;
499 } else if (type != LUA_TNUMBER && --ints_to_skip >= 0) {
500 continue;
501 }
502
503 #ifdef ARCH_ARM64
504 /* In 64 bit arm on all OS variadic stack arguments are 8 or 16 byte aligned */
505 {
506 size_t sz = unpack_vararg(L, i, to);
507 if (sz > 8) {
508 /* Aligned to 16 bytes */
509 sz += 16 - (sz % 16);
510 to += sz;
511 }
512 else {
513 /* Aligned to 8 bytes */
514 to += 8;
515 }
516 }
517 #else
518 to += unpack_vararg(L, i, to);
519 #endif
520 }
521 }
522
523 void unpack_varargs_float(lua_State* L, int first, int last, int max, char* to)
524 {
525 int i;
526
527 for (i = first; i <= last && max > 0; i++) {
528 if (lua_type(L, i) == LUA_TNUMBER) {
529 unpack_vararg(L, i, to);
530 to += sizeof(double);
531 max--;
532 }
533 }
534 }
535
536 void unpack_varargs_int(lua_State* L, int first, int last, int max, char* to)
537 {
538 int i;
539
540 for (i = first; i <= last && max > 0; i++) {
541 if (lua_type(L, i) != LUA_TNUMBER) {
542 unpack_vararg(L, i, to);
543 to += sizeof(void*);
544 max--;
545 }
546 }
547 }
548
549 void unpack_varargs_reg(lua_State* L, int first, int last, char* to)
550 {
551 int i;
552
553 for (i = first; i <= last; i++) {
554 unpack_vararg(L, i, to);
555 to += sizeof(double);
556 }
557 }
558
559 /* to_enum tries to convert a value at idx to the enum type indicated by to_ct
560 * and uv to_usr. For strings this means it will do a string lookup for the
561 * enum type. It leaves the stack unchanged. Will throw an error if the type
562 * at idx can't be conerted.
563 */
564 int32_t check_enum(lua_State* L, int idx, int to_usr, const struct ctype* to_ct)
565 {
566 int32_t ret;
567
568 switch (lua_type(L, idx)) {
569 case LUA_TSTRING:
570 /* lookup string in to_usr to find value */
571 to_usr = lua_absindex(L, to_usr);
572 lua_pushvalue(L, idx);
573 lua_rawget(L, to_usr);
574
575 if (lua_isnil(L, -1)) {
576 goto err;
577 }
578
579 ret = (int32_t) lua_tointeger(L, -1);
580 lua_pop(L, 1);
581 return ret;
582
583 case LUA_TUSERDATA:
584 return check_int32(L, idx);
585
586 case LUA_TNIL:
587 return (int32_t) 0;
588
589 case LUA_TNUMBER:
590 return (int32_t) lua_tointeger(L, idx);
591
592 default:
593 goto err;
594 }
595
596 err:
597 return type_error(L, idx, NULL, to_usr, to_ct);
598 }
599
600 /* to_pointer tries converts a value at idx to a pointer. It fills out ct and
601 * pushes the uv of the found type. It will throw a lua error if it can not
602 * convert the value to a pointer. */
603 static void* check_pointer(lua_State* L, int idx, struct ctype* ct)
604 {
605 void* p;
606 memset(ct, 0, sizeof(*ct));
607 idx = lua_absindex(L, idx);
608
609 switch (lua_type(L, idx)) {
610 case LUA_TNIL:
611 ct->type = VOID_TYPE;
612 ct->pointers = 1;
613 ct->is_null = 1;
614 lua_pushnil(L);
615 return NULL;
616
617 case LUA_TNUMBER:
618 ct->type = INTPTR_TYPE;
619 ct->is_unsigned = 1;
620 ct->pointers = 0;
621 lua_pushnil(L);
622 return (void*) (uintptr_t) lua_tonumber(L, idx); // TODO in Lua 5.3: maybe change to lua_tointeger
623
624 case LUA_TLIGHTUSERDATA:
625 ct->type = VOID_TYPE;
626 ct->pointers = 1;
627 lua_pushnil(L);
628 return lua_touserdata(L, idx);
629
630 case LUA_TSTRING:
631 ct->type = INT8_TYPE;
632 ct->pointers = 1;
633 ct->is_unsigned = IS_CHAR_UNSIGNED;
634 ct->is_array = 1;
635 ct->base_size = 1;
636 ct->const_mask = 2;
637 lua_pushnil(L);
638 return (void*) lua_tolstring(L, idx, &ct->array_size);
639
640 case LUA_TUSERDATA:
641 p = to_cdata(L, idx, ct);
642
643 if (ct->type == INVALID_TYPE) {
644 /* some other type of user data */
645 ct->type = VOID_TYPE;
646 ct->pointers = 1;
647 return userdata_toptr(L, idx);
648 } else if (ct->type == STRUCT_TYPE || ct->type == UNION_TYPE) {
649 return p;
650 } else {
651 return (void*) (intptr_t) check_intptr(L, idx, p, ct);
652 }
653 break;
654 }
655
656 type_error(L, idx, "pointer", 0, NULL);
657 return NULL;
658 }
659
660 static int is_void_ptr(const struct ctype* ct)
661 {
662 return ct->type == VOID_TYPE
663 && ct->pointers == 1;
664 }
665
666 static int is_same_type(lua_State* L, int usr1, int usr2, const struct ctype* t1, const struct ctype* t2)
667 {
668 if (t1->type != t2->type) {
669 return 0;
670 }
671
672 #if LUA_VERSION_NUM == 501
673 if (lua_isnil(L, usr1) != lua_isnil(L, usr2)) {
674 int ret;
675 usr1 = lua_absindex(L, usr1);
676 usr2 = lua_absindex(L, usr2);
677 push_upval(L, &niluv_key);
678
679 ret = lua_rawequal(L, usr1, -1)
680 || lua_rawequal(L, usr2, -1);
681
682 lua_pop(L, 1);
683
684 if (ret) {
685 return 1;
686 }
687 }
688 #endif
689
690 return lua_rawequal(L, usr1, usr2);
691 }
692
693 static void set_struct(lua_State* L, int idx, void* to, int to_usr, const struct ctype* tt, int check_pointers);
694
695 /* to_typed_pointer converts a value at idx to a type tt with target uv to_usr
696 * checking all types. May push a temporary value so that it can create
697 * structs on the fly. */
698 void* check_typed_pointer(lua_State* L, int idx, int to_usr, const struct ctype* tt)
699 {
700 struct ctype ft;
701 void* p;
702
703 to_usr = lua_absindex(L, to_usr);
704 idx = lua_absindex(L, idx);
705
706 if (tt->pointers == 1 && (tt->type == STRUCT_TYPE || tt->type == UNION_TYPE) && lua_type(L, idx) == LUA_TTABLE) {
707 /* need to construct a struct of the target type */
708 struct ctype ct = *tt;
709 ct.pointers = ct.is_array = 0;
710 p = push_cdata(L, to_usr, &ct);
711 set_struct(L, idx, p, to_usr, &ct, 1);
712 return p;
713 }
714
715 p = check_pointer(L, idx, &ft);
716
717 if (tt->pointers == 1 && ft.pointers == 0 && (ft.type == STRUCT_TYPE || ft.type == UNION_TYPE)) {
718 /* auto dereference structs */
719 ft.pointers = 1;
720 ft.const_mask <<= 1;
721 }
722
723 if (is_void_ptr(tt)) {
724 /* any pointer can convert to void* */
725 goto suc;
726
727 } else if (is_void_ptr(&ft) && (ft.pointers || ft.is_reference)) {
728 /* void* can convert to any pointer */
729 goto suc;
730
731 } else if (ft.is_null) {
732 /* NULL can convert to any pointer */
733 goto suc;
734
735 } else if (!is_same_type(L, to_usr, -1, tt, &ft)) {
736 /* the base type is different */
737 goto err;
738
739 } else if (tt->pointers != ft.pointers) {
740 goto err;
741
742 } else if (ft.const_mask & ~tt->const_mask) {
743 /* for every const in from it must be in to, there are further rules
744 * for const casting (see the c++ spec), but they are hard to test
745 * quickly */
746 goto err;
747 }
748
749 suc:
750 return p;
751
752 err:
753 type_error(L, idx, NULL, to_usr, tt);
754 return NULL;
755 }
756
757 /**
758 * gets the address of the wrapped C function for the lua function value at idx
759 * and returns 1 if it exists; otherwise returns 0 and nothing is pushed */
760 static int get_cfunction_address(lua_State* L, int idx, cfunction* addr)
761 {
762 if (!lua_isfunction(L, idx)) return 0;
763
764 int top = lua_gettop(L);
765
766 // Get the last upvalue
767 int n = 2;
768 while (lua_getupvalue(L, idx, n)) {
769 lua_pop(L, 1);
770 n++;
771 }
772
773 if (!lua_getupvalue(L, idx, n - 1))
774 return 0;
775
776 if (!lua_isuserdata(L, -1) || !lua_getmetatable(L, -1)) {
777 lua_pop(L, 1);
778 return 0;
779 }
780
781 push_upval(L, &callback_mt_key);
782 if (!lua_rawequal(L, -1, -2)) {
783 lua_pop(L, 3);
784 return 0;
785 }
786
787 /* stack is:
788 * userdata upval
789 * metatable
790 * callback_mt
791 */
792
793 cfunction* f = lua_touserdata(L, -3);
794 *addr = f[1];
795 lua_pop(L, 3);
796 return 1;
797 }
798
799 /* to_cfunction converts a value at idx with usr table at to_usr and type tt
800 * into a function. Leaves the stack unchanged. */
801 static cfunction check_cfunction(lua_State* L, int idx, int to_usr, const struct ctype* tt, int check_pointers)
802 {
803 void* p;
804 struct ctype ft;
805 cfunction f;
806 int top = lua_gettop(L);
807
808 idx = lua_absindex(L, idx);
809 to_usr = lua_absindex(L, to_usr);
810
811 switch (lua_type(L, idx)) {
812 case LUA_TFUNCTION:
813 if (get_cfunction_address(L, idx, &f)) {
814 return f;
815 }
816
817 /* Function cdatas are pinned and must be manually cleaned up by
818 * calling func:free(). */
819 push_upval(L, &callbacks_key);
820 f = compile_callback(L, idx, to_usr, tt);
821 lua_pushboolean(L, 1);
822 lua_rawset(L, -3);
823 lua_pop(L, 1); /* callbacks tbl */
824 return f;
825
826 case LUA_TNIL:
827 return NULL;
828
829 case LUA_TLIGHTUSERDATA:
830 if (check_pointers) {
831 goto err;
832 } else {
833 return (cfunction) lua_touserdata(L, idx);
834 }
835
836 case LUA_TUSERDATA:
837 p = to_cdata(L, idx, &ft);
838 assert(lua_gettop(L) == top + 1);
839
840 if (ft.type == INVALID_TYPE) {
841 if (check_pointers) {
842 goto err;
843 } else {
844 lua_pop(L, 1);
845 return (cfunction) lua_touserdata(L, idx);
846 }
847
848 } else if (ft.is_null) {
849 lua_pop(L, 1);
850 return NULL;
851
852 } else if (!check_pointers && (ft.pointers || ft.type == INTPTR_TYPE)) {
853 lua_pop(L, 1);
854 return (cfunction) *(void**) p;
855
856 } else if (ft.type != FUNCTION_PTR_TYPE) {
857 goto err;
858
859 } else if (!check_pointers) {
860 lua_pop(L, 1);
861 return *(cfunction*) p;
862
863 } else if (ft.calling_convention != tt->calling_convention) {
864 goto err;
865
866 } else if (!is_same_type(L, -1, to_usr, &ft, tt)) {
867 goto err;
868
869 } else {
870 lua_pop(L, 1);
871 return *(cfunction*) p;
872 }
873
874 default:
875 goto err;
876 }
877
878 err:
879 type_error(L, idx, NULL, to_usr, tt);
880 return NULL;
881 }
882
883 /* to_type_cfunction converts a value at idx with uv at to_usr and type tt to
884 * a cfunction. Leaves the stack unchanged. */
885 cfunction check_typed_cfunction(lua_State* L, int idx, int to_usr, const struct ctype* tt)
886 { return check_cfunction(L, idx, to_usr, tt, 1); }
887
888 static void set_value(lua_State* L, int idx, void* to, int to_usr, const struct ctype* tt, int check_pointers);
889
890 static void set_array(lua_State* L, int idx, void* to, int to_usr, const struct ctype* tt, int check_pointers)
891 {
892 size_t i, sz, esz;
893 struct ctype et;
894
895 idx = lua_absindex(L, idx);
896 to_usr = lua_absindex(L, to_usr);
897
898 switch (lua_type(L, idx)) {
899 case LUA_TSTRING:
900 if (tt->pointers == 1 && tt->type == INT8_TYPE) {
901 const char* str = lua_tolstring(L, idx, &sz);
902
903 if (!tt->is_variable_array && sz >= tt->array_size) {
904 memcpy(to, str, tt->array_size);
905 } else {
906 /* include nul terminator */
907 memcpy(to, str, sz+1);
908 }
909 } else {
910 goto err;
911 }
912 break;
913
914 case LUA_TTABLE:
915 et = *tt;
916 et.pointers--;
917 et.const_mask >>= 1;
918 et.is_array = 0;
919 esz = et.pointers ? sizeof(void*) : et.base_size;
920
921 lua_rawgeti(L, idx, 2);
922
923 if (tt->is_variable_array) {
924 /* we have no idea how big the array is, so set values based off
925 * how many items were given to us */
926 lua_pop(L, 1);
927 for (i = 0; i < lua_rawlen(L, idx); i++) {
928 lua_rawgeti(L, idx, (int) i + 1);
929 set_value(L, -1, (char*) to + esz * i, to_usr, &et, check_pointers);
930 lua_pop(L, 1);
931 }
932
933 } else if (lua_isnil(L, -1)) {
934 /* there is no second element, so we set the whole array to the
935 * first element (or nil - ie 0) if there is no first element) */
936 lua_pop(L, 1);
937 lua_rawgeti(L, idx, 1);
938
939 if (lua_isnil(L, -1)) {
940 memset(to, 0, ctype_size(L, tt));
941 } else {
942 /* if its still variable we have no idea how many values to set */
943 for (i = 0; i < tt->array_size; i++) {
944 set_value(L, -1, (char*) to + esz * i, to_usr, &et, check_pointers);
945 }
946 }
947
948 lua_pop(L, 1);
949
950 } else {
951 /* there is a second element, so we set each element using the
952 * equiv index in the table initializer */
953 lua_pop(L, 1);
954 for (i = 0; i < tt->array_size; i++) {
955 lua_rawgeti(L, idx, (int) (i+1));
956
957 if (lua_isnil(L, -1)) {
958 /* we've hit the end of the values provided in the
959 * initializer, so memset the rest to zero */
960 lua_pop(L, 1);
961 memset((char*) to + esz * i, 0, (tt->array_size - i) * esz);
962 break;
963
964 } else {
965 set_value(L, -1, (char*) to + esz * i, to_usr, &et, check_pointers);
966 lua_pop(L, 1);
967 }
968 }
969 }
970 break;
971
972 default:
973 goto err;
974 }
975
976 return;
977
978 err:
979 type_error(L, idx, NULL, to_usr, tt);
980 }
981
982 /* pops the member key from the stack, leaves the member user value on the
983 * stack. Returns the member offset. Returns -ve if the member can not be
984 * found. */
985 static ptrdiff_t get_member(lua_State* L, int usr, const struct ctype* ct, struct ctype* mt)
986 {
987 ptrdiff_t off;
988 lua_rawget(L, usr);
989
990 if (lua_isnil(L, -1)) {
991 lua_pop(L, 1);
992 return -1;
993 }
994
995 //*mt = *(const struct ctype*) lua_touserdata(L, -1); TRIAL FIX 06-May-2022
996 memcpy(mt, (const struct ctype*) lua_touserdata(L, -1), sizeof(struct ctype));
997 lua_getuservalue(L, -1);
998 lua_replace(L, -2);
999
1000 if (mt->is_variable_array && ct->variable_size_known) {
1001 /* eg char mbr[?] */
1002 size_t sz = (mt->pointers > 1) ? sizeof(void*) : mt->base_size;
1003 assert(ct->is_variable_struct && mt->is_array);
1004 mt->array_size = ct->variable_increment / sz;
1005 mt->is_variable_array = 0;
1006
1007 } else if (mt->is_variable_struct && ct->variable_size_known) {
1008 /* eg struct {char a; char b[?]} mbr; */
1009 assert(ct->is_variable_struct);
1010 mt->variable_size_known = 1;
1011 mt->variable_increment = ct->variable_increment;
1012 }
1013
1014 off = mt->offset;
1015 mt->offset = 0;
1016 return off;
1017 }
1018
1019 static void set_struct(lua_State* L, int idx, void* to, int to_usr, const struct ctype* tt, int check_pointers)
1020 {
1021 int have_first = 0;
1022 int have_other = 0;
1023 struct ctype mt;
1024 void* p;
1025
1026 to_usr = lua_absindex(L, to_usr);
1027 idx = lua_absindex(L, idx);
1028
1029 switch (lua_type(L, idx)) {
1030 case LUA_TTABLE:
1031 /* match up to the members based off the table initializers key - this
1032 * will match both numbered and named members in the user table
1033 * we need a special case for when no entries in the initializer -
1034 * zero initialize the c struct, and only one entry in the initializer
1035 * - set all members to this value */
1036 memset(to, 0, ctype_size(L, tt));
1037 lua_pushnil(L);
1038 while (lua_next(L, idx)) {
1039 ptrdiff_t off;
1040
1041 if (!have_first && lua_tonumber(L, -2) == 1 && lua_tonumber(L, -1) != 0) {
1042 have_first = 1;
1043 } else if (!have_other && (lua_type(L, -2) != LUA_TNUMBER || lua_tonumber(L, -2) != 1)) {
1044 have_other = 1;
1045 }
1046
1047 lua_pushvalue(L, -2);
1048 off = get_member(L, to_usr, tt, &mt);
1049 assert(off >= 0);
1050 set_value(L, -2, (char*) to + off, -1, &mt, check_pointers);
1051
1052 /* initializer value, mt usr */
1053 lua_pop(L, 2);
1054 }
1055
1056 /* if we only had a single non zero value then initialize all members to that value */
1057 if (!have_other && have_first && tt->type != UNION_TYPE) {
1058 size_t i, sz;
1059 ptrdiff_t off;
1060 lua_rawgeti(L, idx, 1);
1061 sz = lua_rawlen(L, to_usr);
1062
1063 for (i = 2; i < sz; i++) {
1064 lua_pushinteger(L, i);
1065 off = get_member(L, to_usr, tt, &mt);
1066 assert(off >= 0);
1067 set_value(L, -2, (char*) to + off, -1, &mt, check_pointers);
1068 lua_pop(L, 1); /* mt usr */
1069 }
1070
1071 lua_pop(L, 1); /* initializer table */
1072 }
1073 break;
1074
1075 case LUA_TUSERDATA:
1076 if (check_pointers) {
1077 p = check_typed_pointer(L, idx, to_usr, tt);
1078 } else {
1079 struct ctype ct;
1080 p = check_pointer(L, idx, &ct);
1081 }
1082 memcpy(to, p, tt->base_size);
1083 lua_pop(L, 1);
1084 break;
1085
1086 default:
1087 goto err;
1088 }
1089
1090 return;
1091
1092 err:
1093 type_error(L, idx, NULL, to_usr, tt);
1094 }
1095
1096 static void set_value(lua_State* L, int idx, void* to, int to_usr, const struct ctype* tt, int check_pointers)
1097 {
1098 int top = lua_gettop(L);
1099
1100 if (tt->is_array) {
1101 set_array(L, idx, to, to_usr, tt, check_pointers);
1102
1103 } else if (tt->pointers || tt->is_reference) {
1104 union {
1105 uint8_t c[sizeof(void*)];
1106 void* p;
1107 } u;
1108
1109 if (lua_istable(L, idx)) {
1110 luaL_error(L, "Can't set a pointer member to a struct that's about to be freed");
1111 }
1112
1113 if (check_pointers) {
1114 u.p = check_typed_pointer(L, idx, to_usr, tt);
1115 } else {
1116 struct ctype ct;
1117 u.p = check_pointer(L, idx, &ct);
1118 }
1119
1120 #ifndef ALLOW_MISALIGNED_ACCESS
1121 if ((uintptr_t) to & PTR_ALIGN_MASK) {
1122 memcpy(to, u.c, sizeof(void*));
1123 } else
1124 #endif
1125 {
1126 *(void**) to = u.p;
1127 }
1128
1129 lua_pop(L, 1);
1130
1131 } else if (tt->is_bitfield) {
1132
1133 uint64_t hi_mask = UINT64_C(0) - (UINT64_C(1) << (tt->bit_offset + tt->bit_size));
1134 uint64_t low_mask = (UINT64_C(1) << tt->bit_offset) - UINT64_C(1);
1135 uint64_t val = check_uint64(L, idx);
1136 val &= (UINT64_C(1) << tt->bit_size) - 1;
1137 val <<= tt->bit_offset;
1138 *(uint64_t*) to = val | (*(uint64_t*) to & (hi_mask | low_mask));
1139
1140 } else if (tt->type == STRUCT_TYPE || tt->type == UNION_TYPE) {
1141 set_struct(L, idx, to, to_usr, tt, check_pointers);
1142
1143 } else {
1144
1145 #ifndef ALLOW_MISALIGNED_ACCESS
1146 union {
1147 uint8_t c[8];
1148 _Bool b;
1149 uint64_t u64;
1150 float f;
1151 double d;
1152 cfunction func;
1153 } misalign;
1154
1155 void* origto = to;
1156
1157 if ((uintptr_t) origto & (tt->base_size - 1)) {
1158 to = misalign.c;
1159 }
1160 #endif
1161
1162 switch (tt->type) {
1163 case BOOL_TYPE:
1164 *(_Bool*) to = (uint8_t)(cast_int64(L, idx, !check_pointers) != 0);
1165 break;
1166 case INT8_TYPE:
1167 if (tt->is_unsigned) {
1168 *(uint8_t*) to = (uint8_t) cast_uint64(L, idx, !check_pointers);
1169 } else {
1170 *(int8_t*) to = (int8_t) cast_int64(L, idx, !check_pointers);
1171 }
1172 break;
1173 case INT16_TYPE:
1174 if (tt->is_unsigned) {
1175 *(uint16_t*) to = (uint16_t) cast_uint64(L, idx, !check_pointers);
1176 } else {
1177 *(int16_t*) to = (int16_t) cast_int64(L, idx, !check_pointers);
1178 }
1179 break;
1180 case INT32_TYPE:
1181 if (tt->is_unsigned) {
1182 *(uint32_t*) to = (uint32_t) cast_uint64(L, idx, !check_pointers);
1183 } else {
1184 *(int32_t*) to = (int32_t) cast_int64(L, idx, !check_pointers);
1185 }
1186 break;
1187 case INT64_TYPE:
1188 if (tt->is_unsigned) {
1189 *(uint64_t*) to = cast_uint64(L, idx, !check_pointers);
1190 } else {
1191 *(int64_t*) to = cast_int64(L, idx, !check_pointers);
1192 }
1193 break;
1194 case FLOAT_TYPE:
1195 *(float*) to = (float) check_double(L, idx);
1196 break;
1197 case DOUBLE_TYPE:
1198 *(double*) to = check_double(L, idx);
1199 break;
1200 case COMPLEX_FLOAT_TYPE:
1201 *(complex_float*) to = check_complex_float(L, idx);
1202 break;
1203 case COMPLEX_DOUBLE_TYPE:
1204 *(complex_double*) to = check_complex_double(L, idx);
1205 break;
1206 case INTPTR_TYPE:
1207 *(uintptr_t*) to = check_uintptr(L, idx);
1208 break;
1209 case ENUM_TYPE:
1210 *(int32_t*) to = check_enum(L, idx, to_usr, tt);
1211 break;
1212 case FUNCTION_PTR_TYPE:
1213 *(cfunction*) to = check_cfunction(L, idx, to_usr, tt, check_pointers);
1214 break;
1215 default:
1216 goto err;
1217 }
1218
1219 #ifndef ALLOW_MISALIGNED_ACCESS
1220 if ((uintptr_t) origto & (tt->base_size - 1)) {
1221 memcpy(origto, misalign.c, tt->base_size);
1222 }
1223 #endif
1224 }
1225
1226 assert(lua_gettop(L) == top);
1227 return;
1228 err:
1229 type_error(L, idx, NULL, to_usr, tt);
1230 }
1231
1232 static int ffi_typeof(lua_State* L)
1233 {
1234 struct ctype ct;
1235 check_ctype(L, 1, &ct);
1236 push_ctype(L, -1, &ct);
1237 return 1;
1238 }
1239
1240 static void setmintop(lua_State* L, int idx)
1241 {
1242 if (lua_gettop(L) < idx) {
1243 lua_settop(L, idx);
1244 }
1245 }
1246
1247 /* warning: in the case that it finds an array size, it removes that index */
1248 static void get_variable_array_size(lua_State* L, int idx, struct ctype* ct)
1249 {
1250 /* we only care about the variable buisness for the variable array
1251 * directly ie ffi.new('char[?]') or the struct that contains the variable
1252 * array ffi.new('struct {char v[?]}'). A pointer to the struct doesn't
1253 * care about the variable size (it treats it as a zero sized array). */
1254
1255 if (ct->is_variable_array) {
1256 assert(ct->is_array);
1257 ct->array_size = (size_t) luaL_checknumber(L, idx);
1258 ct->is_variable_array = 0;
1259 lua_remove(L, idx);
1260
1261 } else if (ct->is_variable_struct && !ct->variable_size_known) {
1262 assert(ct->type == STRUCT_TYPE && !ct->is_array);
1263 ct->variable_increment *= (size_t) luaL_checknumber(L, idx);
1264 ct->variable_size_known = 1;
1265 lua_remove(L, idx);
1266 }
1267 }
1268
1269 static int is_scalar(struct ctype* ct)
1270 {
1271 int type = ct->type;
1272 if (ct->pointers || ct->is_reference) {
1273 return !ct->is_array;
1274 }
1275 return type != STRUCT_TYPE && type != UNION_TYPE && !IS_COMPLEX(type);
1276 }
1277
1278 static int should_pack(lua_State *L, int ct_usr, struct ctype* ct, int idx)
1279 {
1280 struct ctype argt;
1281 ct_usr = lua_absindex(L, ct_usr);
1282
1283 if (IS_COMPLEX(ct->type)) {
1284 return 0;
1285 }
1286
1287 switch (lua_type(L, idx)) {
1288 case LUA_TTABLE:
1289 return 0;
1290 case LUA_TSTRING:
1291 return ct->type == STRUCT_TYPE;
1292 case LUA_TUSERDATA:
1293 // don't pack if the argument is a cdata with the same type
1294 to_cdata(L, idx, &argt);
1295 int same = is_same_type(L, ct_usr, -1, ct, &argt);
1296 lua_pop(L, 1);
1297 return !same;
1298 default:
1299 return 1;
1300 }
1301 }
1302
1303 static int do_new(lua_State* L, int is_cast)
1304 {
1305 int cargs=0, i;
1306 void* p;
1307 struct ctype ct;
1308 int check_ptrs = !is_cast;
1309
1310 check_ctype(L, 1, &ct);
1311
1312 /* don't push a callback when we have a c function, as cb:set needs a
1313 * compiled callback from a lua function to work */
1314 if (!ct.pointers && ct.type == FUNCTION_PTR_TYPE && (lua_isnil(L, 2) || lua_isfunction(L, 2))) {
1315 // Get the bound C function if this is a ffi lua function
1316 cfunction func;
1317 if (get_cfunction_address(L, 2, &func)) {
1318 p = push_cdata(L, -1, &ct);
1319 *(cfunction*) p = func;
1320 return 1;
1321 }
1322
1323 /* Function cdatas are pinned and must be manually cleaned up by
1324 * calling func:free(). */
1325 compile_callback(L, 2, -1, &ct);
1326 push_upval(L, &callbacks_key);
1327 lua_pushvalue(L, -2);
1328 lua_pushboolean(L, 1);
1329 lua_rawset(L, -3);
1330 lua_pop(L, 1); /* callbacks tbl */
1331 return 1;
1332 }
1333
1334 /* this removes the vararg argument if its needed, and errors if its invalid */
1335 if (!is_cast) {
1336 get_variable_array_size(L, 2, &ct);
1337 }
1338
1339 p = push_cdata(L, -1, &ct);
1340
1341 /* if the user mt has a __gc function then call ffi.gc on this value */
1342 if (push_user_mt(L, -2, &ct)) {
1343 push_upval(L, &gc_key);
1344 lua_pushvalue(L, -3);
1345
1346 /* user_mt.__gc */
1347 lua_pushliteral(L, "__gc");
1348 lua_rawget(L, -4);
1349
1350 lua_rawset(L, -3); /* gc_upval[cdata] = user_mt.__gc */
1351 lua_pop(L, 2); /* user_mt and gc_upval */
1352 }
1353
1354 /* stack is:
1355 * ctype arg
1356 * ctor args ... 0+
1357 * ctype usr
1358 * cdata
1359 */
1360
1361 cargs = lua_gettop(L) - 3;
1362
1363 if (cargs == 0) {
1364 return 1;
1365 }
1366
1367 int scalar = is_scalar(&ct);
1368 if (scalar && cargs > 1) {
1369 return luaL_error(L, "too many initializers");
1370 }
1371
1372 if (cargs > 1 || (!scalar && should_pack(L, -2, &ct, 2))) {
1373 lua_createtable(L, cargs, 0);
1374 lua_replace(L, 1);
1375 for (i = 1; i <= cargs; i++) {
1376 lua_pushvalue(L, i + 1);
1377 lua_rawseti(L, 1, i);
1378 }
1379 assert(lua_gettop(L) == cargs + 3);
1380 set_value(L, 1, p, -2, &ct, check_ptrs);
1381 return 1;
1382 }
1383
1384 set_value(L, 2, p, -2, &ct, check_ptrs);
1385 return 1;
1386 }
1387
1388 static int ffi_new(lua_State* L)
1389 { return do_new(L, 0); }
1390
1391 static int ffi_cast(lua_State* L)
1392 { return do_new(L, 1); }
1393
1394 static int ctype_new(lua_State* L)
1395 { return do_new(L, 0); }
1396
1397 static int ctype_call(lua_State* L)
1398 {
1399 struct ctype ct;
1400 int top = lua_gettop(L);
1401
1402 check_ctype(L, 1, &ct);
1403
1404 if (push_user_mt(L, -1, &ct)) {
1405 lua_pushstring(L, "__new");
1406 lua_rawget(L, -2);
1407 if (!lua_isnil(L, -1)) {
1408 lua_insert(L, 1); // function at bottom of stack under args
1409 lua_pop(L, 2);
1410 lua_call(L, top, 1);
1411 return 1;
1412 }
1413 lua_pop(L, 2);
1414 }
1415 lua_pop(L, 1);
1416
1417 assert(lua_gettop(L) == top);
1418 return do_new(L, 0);
1419 }
1420
1421 static int ctype_index(lua_State* L)
1422 {
1423 struct ctype ct;
1424
1425 lua_settop(L, 2);
1426 check_ctype(L, 1, &ct);
1427 assert(lua_gettop(L) == 3);
1428
1429 if (!push_user_mt(L, -1, &ct)) {
1430 goto err;
1431 }
1432 lua_pushliteral(L, "__index");
1433 lua_rawget(L, -2);
1434
1435 if (lua_isnil(L, -1)) {
1436 goto err;
1437 }
1438
1439 if (lua_istable(L, -1)) {
1440 lua_pushvalue(L, 2);
1441 lua_rawget(L, -2);
1442 if (lua_isnil(L, -1))
1443 goto err;
1444 return 1;
1445 }
1446
1447 lua_insert(L, 1);
1448 lua_settop(L, 3);
1449 lua_call(L, 2, LUA_MULTRET);
1450 return lua_gettop(L);
1451
1452 err:
1453 push_type_name(L, 3, &ct);
1454 return luaL_error(L, "type %s has no member %s", lua_tostring(L, -1), lua_tostring(L, 2));
1455 }
1456
1457 static int ffi_sizeof(lua_State* L)
1458 {
1459 struct ctype ct;
1460 check_ctype(L, 1, &ct);
1461 get_variable_array_size(L, 2, &ct);
1462 lua_pushinteger(L, ctype_size(L, &ct));
1463 return 1;
1464 }
1465
1466 static int ffi_alignof(lua_State* L)
1467 {
1468 struct ctype ct, mt;
1469 lua_settop(L, 2);
1470 check_ctype(L, 1, &ct);
1471 //debug_print_type(&ct);
1472
1473 /* if no member is specified then we return the alignment of the type */
1474 if (lua_isnil(L, 2)) {
1475 lua_pushinteger(L, ct.align_mask + 1);
1476 return 1;
1477 }
1478
1479 /* get the alignment of the member */
1480 lua_pushvalue(L, 2);
1481 if (get_member(L, -2, &ct, &mt) < 0) {
1482 push_type_name(L, 3, &ct);
1483 return luaL_error(L, "type %s has no member %s", lua_tostring(L, -1), lua_tostring(L, 2));
1484 }
1485
1486 lua_pushinteger(L, mt.align_mask + 1);
1487 return 1;
1488 }
1489
1490 static int ffi_offsetof(lua_State* L)
1491 {
1492 ptrdiff_t off;
1493 struct ctype ct, mt;
1494 lua_settop(L, 2);
1495 check_ctype(L, 1, &ct);
1496
1497 lua_pushvalue(L, 2);
1498 off = get_member(L, -2, &ct, &mt); /* this replaces the member key at -1 with the mbr usr value */
1499 if (off < 0) {
1500 push_type_name(L, 3, &ct);
1501 return luaL_error(L, "type %s has no member %s", lua_tostring(L, -1), lua_tostring(L, 2));
1502 }
1503
1504 lua_pushinteger(L, off);
1505
1506 if (!mt.is_bitfield) {
1507 return 1;
1508 }
1509
1510 lua_pushinteger(L, mt.bit_offset);
1511 lua_pushinteger(L, mt.bit_size);
1512 return 3;
1513 }
1514
1515 static int type_is_same_incl_unsigned(lua_State* L, int usr1, int usr2, const struct ctype* t1, const struct ctype* t2)
1516 {
1517 if ((t1->type != t2->type) ||
1518 (t1->is_unsigned != t2->is_unsigned)) {
1519 return 0;
1520 }
1521
1522 #if LUA_VERSION_NUM == 501
1523 if (lua_isnil(L, usr1) != lua_isnil(L, usr2)) {
1524 int ret;
1525 usr1 = lua_absindex(L, usr1);
1526 usr2 = lua_absindex(L, usr2);
1527 push_upval(L, &niluv_key);
1528
1529 ret = lua_rawequal(L, usr1, -1)
1530 || lua_rawequal(L, usr2, -1);
1531
1532 lua_pop(L, 1);
1533
1534 if (ret) {
1535 return 1;
1536 }
1537 }
1538 #endif
1539
1540 return lua_rawequal(L, usr1, usr2);
1541 }
1542
1543 static int ffi_istype(lua_State* L)
1544 {
1545 struct ctype tt, ft;
1546 check_ctype(L, 1, &tt);
1547 to_cdata(L, 2, &ft);
1548
1549 if (ft.type == INVALID_TYPE) {
1550 goto fail;
1551 }
1552
1553 //if (!is_same_type(L, 3, 4, &tt, &ft))
1554 if (!type_is_same_incl_unsigned(L, 3, 4, &tt, &ft)) {
1555 goto fail;
1556 }
1557
1558 if (tt.pointers != ft.pointers) {
1559 goto fail;
1560 }
1561
1562 if (tt.is_array != ft.is_array) {
1563 goto fail;
1564 }
1565
1566 if (tt.is_array && tt.array_size != ft.array_size) {
1567 goto fail;
1568 }
1569
1570 if (tt.calling_convention != ft.calling_convention) {
1571 goto fail;
1572 }
1573
1574 lua_pushboolean(L, 1);
1575 return 1;
1576
1577 fail:
1578 lua_pushboolean(L, 0);
1579 return 1;
1580 }
1581
1582 static int cdata_gc(lua_State* L)
1583 {
1584 struct ctype ct;
1585 check_cdata(L, 1, &ct);
1586 lua_settop(L, 1);
1587
1588 /* call the gc func if there is any registered */
1589 lua_pushvalue(L, 1);
1590 lua_rawget(L, lua_upvalueindex(2));
1591 if (!lua_isnil(L, -1)) {
1592 lua_pushvalue(L, 1);
1593 lua_pcall(L, 1, 0, 0);
1594 }
1595
1596 /* unset the closure */
1597 lua_pushvalue(L, 1);
1598 lua_pushnil(L);
1599 lua_rawset(L, lua_upvalueindex(1));
1600
1601 return 0;
1602 }
1603
1604 static int callback_free(lua_State* L)
1605 {
1606 cfunction* p = (cfunction*) lua_touserdata(L, 1);
1607 // FIXME: temporarily disabled to prevent SIGTRAP on exit
1608 // free_code(get_jit(L), L, *p);
1609 return 0;
1610 }
1611
1612 static int cdata_free(lua_State* L)
1613 {
1614 struct ctype ct;
1615 cfunction* p = (cfunction*) check_cdata(L, 1, &ct);
1616 lua_settop(L, 1);
1617
1618 /* unset the closure */
1619 lua_pushvalue(L, 1);
1620 lua_pushnil(L);
1621 lua_rawset(L, lua_upvalueindex(1));
1622
1623 if (ct.is_jitted) {
1624 free_code(get_jit(L), L, *p);
1625 *p = NULL;
1626 }
1627
1628 return 0;
1629 }
1630
1631 static int cdata_set(lua_State* L)
1632 {
1633 struct ctype ct;
1634 cfunction* p = (cfunction*) check_cdata(L, 1, &ct);
1635 luaL_checktype(L, 2, LUA_TFUNCTION);
1636
1637 if (!ct.is_jitted) {
1638 luaL_error(L, "can't set the function for a non-lua callback");
1639 }
1640
1641 if (*p == NULL) {
1642 luaL_error(L, "can't set the function for a free'd callback");
1643 }
1644
1645 push_func_ref(L, *p);
1646 lua_pushvalue(L, 2);
1647 lua_rawseti(L, -2, CALLBACK_FUNC_USR_IDX);
1648
1649 /* remove the closure for this callback as it embeds the function pointer
1650 * value */
1651 lua_pushvalue(L, 1);
1652 lua_pushboolean(L, 1);
1653 lua_rawset(L, lua_upvalueindex(1));
1654
1655 return 0;
1656 }
1657
1658 static int cdata_call(lua_State* L)
1659 {
1660 struct ctype ct;
1661 int top = lua_gettop(L);
1662 cfunction* p = (cfunction*) check_cdata(L, 1, &ct);
1663
1664 if (push_user_mt(L, -1, &ct)) {
1665 lua_pushliteral(L, "__call");
1666 lua_rawget(L, -2);
1667
1668 if (!lua_isnil(L, -1)) {
1669 lua_insert(L, 1);
1670 lua_pop(L, 2); /* ct_usr, user_mt */
1671 lua_call(L, lua_gettop(L) - 1, LUA_MULTRET);
1672 return lua_gettop(L);
1673 }
1674 }
1675 if (ct.pointers || ct.type != FUNCTION_PTR_TYPE) {
1676 return luaL_error(L, "only function callbacks are callable");
1677 }
1678
1679 lua_pushvalue(L, 1);
1680 lua_rawget(L, lua_upvalueindex(1));
1681
1682 if (!lua_isfunction(L, -1)) {
1683 lua_pop(L, 1);
1684 compile_function(L, *p, -1, &ct);
1685 #ifdef ARCH_ARM64
1686 /* Ref: https://developer.arm.com/documentation/ihi0053/latest
1687 * Generates an ISB (instruction synchronization barrier) instruction or
1688 * equivalent CP15 instruction. This instruction flushes the processor
1689 * pipeline fetch buffers, so that following instructions are fetched
1690 * from cache or memory. An ISB is needed after some system maintenance
1691 * operations. An ISB is also needed before transferring control to code
1692 * that has been loaded or modified in memory, for example by an overlay
1693 * mechanism or just-in-time code generator. (Note that if instruction
1694 * and data caches are separate, privileged cache maintenance operations
1695 * would be needed in order to unify the caches.) The only supported
1696 * argument for the __isb() intrinsic is 15, corresponding to the SY
1697 * (full system) scope of the ISB instruction.
1698 */
1699 #ifdef __clang__
1700 __isb(15);
1701 #elif __GNUC__
1702 asm("isb 15");
1703 #endif
1704 #endif
1705
1706 assert(lua_gettop(L) == top + 2); /* uv, closure */
1707
1708 /* closures[func] = closure */
1709 lua_pushvalue(L, 1);
1710 lua_pushvalue(L, -2);
1711 lua_rawset(L, lua_upvalueindex(1));
1712
1713 lua_replace(L, 1);
1714 } else {
1715 lua_replace(L, 1);
1716 }
1717
1718 lua_pop(L, 1); /* uv */
1719 assert(lua_gettop(L) == top);
1720
1721 lua_call(L, lua_gettop(L) - 1, LUA_MULTRET);
1722 return lua_gettop(L);
1723 }
1724
1725 static int user_mt_key;
1726
1727 static int ffi_metatype(lua_State* L)
1728 {
1729 struct ctype ct;
1730 lua_settop(L, 2);
1731
1732 check_ctype(L, 1, &ct);
1733 if (lua_type(L, 2) != LUA_TTABLE && lua_type(L, 2) != LUA_TNIL) {
1734 return luaL_argerror(L, 2, "metatable must be a table or nil");
1735 }
1736
1737 lua_pushlightuserdata(L, &user_mt_key);
1738 lua_rawget(L, 3);
1739 if (!lua_isnil(L, -1)) {
1740 push_type_name(L, 3, &ct);
1741 return luaL_error(L, "type %s already has a user metatable", lua_tostring(L, -1));
1742 }
1743 lua_pop(L, 1);
1744
1745 lua_pushlightuserdata(L, &user_mt_key);
1746 lua_pushvalue(L, 2);
1747 lua_rawset(L, 3); /* user[user_mt_key] = mt */
1748
1749 /* return the passed in ctype */
1750 push_ctype(L, 3, &ct);
1751 return 1;
1752 }
1753
1754 /* push_user_mt returns 1 if the type has a user metatable and pushes it onto
1755 * the stack, otherwise it returns 0 and pushes nothing */
1756 int push_user_mt(lua_State* L, int ct_usr, const struct ctype* ct)
1757 {
1758 if (ct->type != STRUCT_TYPE && ct->type != UNION_TYPE && !IS_COMPLEX(ct->type)) {
1759 return 0;
1760 }
1761 if (!lua_istable(L, ct_usr)) {
1762 return 0;
1763 }
1764
1765 ct_usr = lua_absindex(L, ct_usr);
1766 lua_pushlightuserdata(L, &user_mt_key);
1767 lua_rawget(L, ct_usr);
1768
1769 if (lua_isnil(L, -1)) {
1770 lua_pop(L, 1);
1771 return 0;
1772 }
1773 return 1;
1774 }
1775
1776 static int ffi_gc(lua_State* L)
1777 {
1778 struct ctype ct;
1779 lua_settop(L, 2);
1780 check_cdata(L, 1, &ct);
1781
1782 push_upval(L, &gc_key);
1783 lua_pushvalue(L, 1);
1784 lua_pushvalue(L, 2);
1785 lua_rawset(L, -3);
1786
1787 /* return the cdata back */
1788 lua_settop(L, 1);
1789 return 1;
1790 }
1791
1792 /* lookup_cdata_index returns the offset of the found type and user value on
1793 * the stack if valid. Otherwise returns -ve and doesn't touch the stack.
1794 */
1795 static ptrdiff_t lookup_cdata_index(lua_State* L, int idx, int ct_usr, struct ctype* ct)
1796 {
1797 struct ctype mt;
1798 ptrdiff_t off;
1799
1800 ct_usr = lua_absindex(L, ct_usr);
1801 int type = lua_type(L, idx);
1802
1803 switch (type) {
1804 case LUA_TNUMBER:
1805 case LUA_TUSERDATA:
1806 /* possibilities are array, pointer */
1807
1808 if (!ct->pointers || is_void_ptr(ct)) {
1809 return -1;
1810 }
1811
1812 // unbox cdata
1813 if (type == LUA_TUSERDATA) {
1814 if (!cdata_tointeger(L, idx, &off)) {
1815 return -1;
1816 }
1817 } else {
1818 off = lua_tointeger(L, idx);
1819 }
1820
1821 ct->is_array = 0;
1822 ct->pointers--;
1823 ct->const_mask >>= 1;
1824 ct->is_reference = 0;
1825
1826 lua_pushvalue(L, ct_usr);
1827
1828 return (ct->pointers ? sizeof(void*) : ct->base_size) * off;
1829
1830 case LUA_TSTRING:
1831 /* possibilities are struct/union, pointer to struct/union */
1832
1833 if ((ct->type != STRUCT_TYPE && ct->type != UNION_TYPE) || ct->is_array || ct->pointers > 1) {
1834 return -1;
1835 }
1836
1837 lua_pushvalue(L, idx);
1838 off = get_member(L, ct_usr, ct, &mt);
1839 if (off < 0) {
1840 return -1;
1841 }
1842
1843 *ct = mt;
1844 return off;
1845
1846 default:
1847 return -1;
1848 }
1849 }
1850
1851 static int cdata_newindex(lua_State* L)
1852 {
1853 struct ctype tt;
1854 char* to;
1855 ptrdiff_t off;
1856
1857 lua_settop(L, 3);
1858
1859 to = (char*) check_cdata(L, 1, &tt);
1860 off = lookup_cdata_index(L, 2, -1, &tt);
1861
1862 if (off < 0) {
1863 if (!push_user_mt(L, -1, &tt)) {
1864 goto err;
1865 }
1866
1867 lua_pushliteral(L, "__newindex");
1868 lua_rawget(L, -2);
1869
1870 if (lua_isnil(L, -1)) {
1871 goto err;
1872 }
1873
1874 if (tt.const_mask & 0xFF) {
1875 return luaL_error(L, "can't set const data");
1876 }
1877
1878 if (lua_istable(L, -1)) {
1879 lua_pushvalue(L, 2);
1880 lua_pushvalue(L, 3);
1881 lua_settable(L, -3);
1882 return 1;
1883 }
1884
1885 lua_insert(L, 1);
1886 lua_settop(L, 4);
1887 lua_call(L, 3, LUA_MULTRET);
1888 return lua_gettop(L);
1889 }
1890
1891 if (tt.const_mask & 1) {
1892 return luaL_error(L, "can't set const data");
1893 }
1894
1895 set_value(L, 3, to + off, -1, &tt, 1);
1896 return 0;
1897
1898 err:
1899 push_type_name(L, 4, &tt);
1900 return luaL_error(L, "type %s has no member %s", lua_tostring(L, -1), lua_tostring(L, 2));
1901 }
1902
1903 static int cdata_index(lua_State* L)
1904 {
1905 void* to;
1906 struct ctype ct;
1907 char* data;
1908 ptrdiff_t off;
1909
1910 lua_settop(L, 2);
1911 data = (char*) check_cdata(L, 1, &ct);
1912 assert(lua_gettop(L) == 3);
1913
1914 if (!ct.pointers) {
1915 switch (ct.type) {
1916 case FUNCTION_PTR_TYPE:
1917 /* Callbacks use the same metatable as standard cdata values, but have set
1918 * and free members. So instead of mt.__index = mt, we do the equiv here. */
1919 lua_getmetatable(L, 1);
1920 lua_pushvalue(L, 2);
1921 lua_rawget(L, -2);
1922 return 1;
1923
1924 /* This provides the .re and .im virtual members */
1925 case COMPLEX_DOUBLE_TYPE:
1926 case COMPLEX_FLOAT_TYPE:
1927 if (!lua_isstring(L, 2)) {
1928 luaL_error(L, "invalid member for complex number");
1929
1930 } else if (strcmp(lua_tostring(L, 2), "re") == 0) {
1931 lua_pushnumber(L, ct.type == COMPLEX_DOUBLE_TYPE ? creal(*(complex_double*) data) : crealf(*(complex_float*) data));
1932
1933 } else if (strcmp(lua_tostring(L, 2), "im") == 0) {
1934 lua_pushnumber(L, ct.type == COMPLEX_DOUBLE_TYPE ? cimag(*(complex_double*) data) : cimagf(*(complex_float*) data));
1935
1936 } else {
1937 luaL_error(L, "invalid member for complex number");
1938 }
1939 return 1;
1940 }
1941 }
1942
1943 off = lookup_cdata_index(L, 2, -1, &ct);
1944
1945 if (off < 0) {
1946 assert(lua_gettop(L) == 3);
1947 if (!push_user_mt(L, -1, &ct)) {
1948 goto err;
1949 }
1950
1951 lua_pushliteral(L, "__index");
1952 lua_rawget(L, -2);
1953
1954 if (lua_isnil(L, -1)) {
1955 goto err;
1956 }
1957
1958 if (lua_istable(L, -1)) {
1959 lua_pushvalue(L, 2);
1960 lua_gettable(L, -2);
1961 if (lua_isnil(L, -1))
1962 goto err;
1963 return 1;
1964 }
1965
1966 lua_insert(L, 1);
1967 lua_settop(L, 3);
1968 lua_call(L, 2, LUA_MULTRET);
1969 return lua_gettop(L);
1970
1971 err:
1972 push_type_name(L, 3, &ct);
1973 return luaL_error(L, "type %s has no member %s", lua_tostring(L, -1), lua_tostring(L, 2));
1974 }
1975
1976 assert(lua_gettop(L) == 4); /* ct, key, ct_usr, mbr_usr */
1977 data += off;
1978
1979 if (ct.is_array) {
1980 /* push a reference to the array */
1981 ct.is_reference = 1;
1982 to = push_cdata(L, -1, &ct);
1983 *(void**) to = data;
1984 return 1;
1985
1986 } else if (ct.is_bitfield) {
1987
1988 if (ct.type == INT64_TYPE) {
1989 struct ctype rt;
1990 uint64_t val = *(uint64_t*) data;
1991 val >>= ct.bit_offset;
1992 val &= (UINT64_C(1) << ct.bit_size) - 1;
1993
1994 memset(&rt, 0, sizeof(rt));
1995 rt.base_size = 8;
1996 rt.type = INT64_TYPE;
1997 rt.is_unsigned = 1;
1998 rt.is_defined = 1;
1999
2000 to = push_cdata(L, 0, &rt);
2001 *(uint64_t*) to = val;
2002
2003 return 1;
2004
2005 } else if (ct.type == BOOL_TYPE) {
2006 uint64_t val = *(uint8_t*) data;
2007 lua_pushboolean(L, (int) (val & (UINT64_C(1) << ct.bit_offset)));
2008 return 1;
2009
2010 } else {
2011 //uint64_t val = *(uint64_t*) data; //Trial fix
2012 uint64_t val = 0;
2013 switch (ct.type) {
2014 case INT8_TYPE: {
2015 uint8_t ui;
2016 memcpy(&ui, data, sizeof(uint8_t));
2017 val = ui;
2018 //val = *(uint8_t*)data;
2019 break;
2020 }
2021 case INT16_TYPE: {
2022 uint16_t ui;
2023 memcpy(&ui, data, sizeof(uint16_t));
2024 val = ui;
2025 //val = *(uint16_t*)data;
2026 break;
2027 }
2028 case INT32_TYPE: {
2029 uint32_t ui;
2030 memcpy(&ui, data, sizeof(uint32_t));
2031 val = ui;
2032 //val = *(uint32_t*)data;
2033 break;
2034 }
2035 case INT64_TYPE:
2036 default:
2037 return luaL_error(L, "Inavaid data type");
2038 }
2039 val >>= ct.bit_offset;
2040 val &= (UINT64_C(1) << ct.bit_size) - 1;
2041 lua_pushinteger(L, val);
2042 return 1;
2043 }
2044
2045 } else if (ct.pointers) {
2046 #ifndef ALLOW_MISALIGNED_ACCESS
2047 union {
2048 uint8_t c[8];
2049 void* p;
2050 } misalignbuf;
2051
2052 if ((uintptr_t) data & PTR_ALIGN_MASK) {
2053 memcpy(misalignbuf.c, data, sizeof(void*));
2054 data = misalignbuf.c;
2055 }
2056 #endif
2057 to = push_cdata(L, -1, &ct);
2058 *(void**) to = *(void**) data;
2059 return 1;
2060
2061 } else if (ct.type == STRUCT_TYPE || ct.type == UNION_TYPE) {
2062 /* push a reference to the member */
2063 ct.is_reference = 1;
2064 to = push_cdata(L, -1, &ct);
2065 *(void**) to = data;
2066 return 1;
2067
2068 } else if (ct.type == FUNCTION_PTR_TYPE) {
2069 cfunction* pf = (cfunction*) push_cdata(L, -1, &ct);
2070 *pf = *(cfunction*) data;
2071 return 1;
2072
2073 } else {
2074 #ifndef ALLOW_MISALIGNED_ACCESS
2075 union {
2076 uint8_t c[8];
2077 double d;
2078 float f;
2079 uint64_t u64;
2080 } misalignbuf;
2081
2082 assert(ct.base_size <= 8);
2083
2084 if ((uintptr_t) data & (ct.base_size - 1)) {
2085 memcpy(misalignbuf.c, data, ct.base_size);
2086 data = misalignbuf.c;
2087 }
2088 #endif
2089
2090 switch (ct.type) {
2091 case BOOL_TYPE:
2092 lua_pushboolean(L, *(_Bool*) data);
2093 break;
2094 case INT8_TYPE:
2095 lua_pushinteger(L, ct.is_unsigned ? (lua_Integer) *(uint8_t*) data : (lua_Integer) *(int8_t*) data);
2096 break;
2097 case INT16_TYPE:
2098 lua_pushinteger(L, ct.is_unsigned ? (lua_Integer) *(uint16_t*) data : (lua_Integer) *(int16_t*) data);
2099 break;
2100 case ENUM_TYPE:
2101 case INT32_TYPE:
2102 lua_pushinteger(L, ct.is_unsigned ? (lua_Integer) *(uint32_t*) data : (lua_Integer) *(int32_t*) data);
2103 break;
2104 case INT64_TYPE:
2105 to = push_cdata(L, -1, &ct);
2106 *(int64_t*) to = *(int64_t*) data;
2107 break;
2108 case INTPTR_TYPE:
2109 to = push_cdata(L, -1, &ct);
2110 *(intptr_t*) to = *(intptr_t*) data;
2111 break;
2112 case FLOAT_TYPE:
2113 lua_pushnumber(L, *(float*) data);
2114 break;
2115 case DOUBLE_TYPE:
2116 lua_pushnumber(L, *(double*) data);
2117 break;
2118 case COMPLEX_DOUBLE_TYPE:
2119 to = push_cdata(L, -1, &ct);
2120 *(complex_double*) to = *(complex_double*) data;
2121 break;
2122 case COMPLEX_FLOAT_TYPE:
2123 to = push_cdata(L, -1, &ct);
2124 *(complex_float*) to = *(complex_float*) data;
2125 break;
2126 default:
2127 luaL_error(L, "internal error: invalid member type");
2128 }
2129
2130 return 1;
2131 }
2132 }
2133
2134 static complex_double check_complex(lua_State* L, int idx, void* p, struct ctype* ct)
2135 {
2136 if (ct->type == INVALID_TYPE) {
2137 double d = luaL_checknumber(L, idx);
2138 #ifdef HAVE_COMPLEX
2139 return d;
2140 #else
2141 complex_double c;
2142 c.real = d;
2143 c.imag = 0;
2144 return c;
2145 #endif
2146 } else if (ct->type == COMPLEX_DOUBLE_TYPE) {
2147 return *(complex_double*) p;
2148 } else if (ct->type == COMPLEX_FLOAT_TYPE) {
2149 complex_float* f = (complex_float*) p;
2150 #ifdef HAVE_COMPLEX
2151 return *f;
2152 #else
2153 complex_double d;
2154 d.real = f->real;
2155 d.imag = f->imag;
2156 return d;
2157 #endif
2158 } else {
2159 complex_double dummy;
2160 type_error(L, idx, "complex", 0, NULL);
2161 memset(&dummy, 0, sizeof(dummy));
2162 return dummy;
2163 }
2164 }
2165
2166 static int rank(const struct ctype* ct)
2167 {
2168 if (ct->pointers) {
2169 return 5;
2170 }
2171
2172 switch (ct->type) {
2173 case COMPLEX_DOUBLE_TYPE:
2174 return 7;
2175 case COMPLEX_FLOAT_TYPE:
2176 return 6;
2177 case INTPTR_TYPE:
2178 return sizeof(intptr_t) >= sizeof(int64_t) ? 4 : 1;
2179 case INT64_TYPE:
2180 return ct->is_unsigned ? 3 : 2;
2181 case INT32_TYPE:
2182 case INT16_TYPE:
2183 case INT8_TYPE:
2184 return 2;
2185 default:
2186 return 0;
2187 }
2188 }
2189
2190 static void push_complex(lua_State* L, complex_double res, int ct_usr, const struct ctype* ct)
2191 {
2192 if (ct->type == COMPLEX_DOUBLE_TYPE) {
2193 complex_double* p = (complex_double*) push_cdata(L, ct_usr, ct);
2194 *p = res;
2195 } else {
2196 complex_float* p = (complex_float*) push_cdata(L, ct_usr, ct);
2197 #ifdef HAVE_COMPLEX
2198 *p = (complex float) res;
2199 #else
2200 p->real = (float) res.real;
2201 p->imag = (float) res.imag;
2202 #endif
2203 }
2204 }
2205
2206 static void push_number(lua_State* L, int64_t val, int ct_usr, const struct ctype* ct)
2207 {
2208 if ((ct->pointers || ct->type == INTPTR_TYPE) && sizeof(intptr_t) != sizeof(int64_t)) {
2209 intptr_t* p = (intptr_t*) push_cdata(L, ct_usr, ct);
2210 *p = val;
2211 } else {
2212 void* p = (int64_t*) push_cdata(L, ct_usr, ct);
2213 //*p = val;
2214 /* TODO : Will this work for big endian architectures?
2215 * ctype_size returns 64 for all integer types
2216 */
2217 memset(p, 0, ctype_size(L, ct));
2218 switch (ct->type) {
2219 case BOOL_TYPE:
2220 case INT8_TYPE: {
2221 memcpy(p, &val, ctype_size(L, ct));
2222 }
2223 break;
2224 case INT16_TYPE: {
2225 memcpy(p, &val, ctype_size(L, ct));
2226 }
2227 break;
2228 case ENUM_TYPE:
2229 case INT32_TYPE: {
2230 memcpy(p, &val, ctype_size(L, ct));
2231 }
2232 break;
2233 case INT64_TYPE: {
2234 memcpy(p, &val, ctype_size(L, ct));
2235 }
2236 break;
2237 default:
2238 luaL_error(L, "Unsupported type for this operation");
2239 break;
2240 }
2241 }
2242 }
2243
2244 static int call_user_op(lua_State* L, const char* opfield, int idx, int ct_usr, const struct ctype* ct)
2245 {
2246 idx = lua_absindex(L, idx);
2247
2248 if (push_user_mt(L, ct_usr, ct)) {
2249 lua_pushstring(L, opfield);
2250 lua_rawget(L, -2);
2251 if (!lua_isnil(L, -1)) {
2252 int top = lua_gettop(L);
2253 lua_pushvalue(L, idx);
2254 lua_call(L, 1, LUA_MULTRET);
2255 return lua_gettop(L) - top + 1;
2256 }
2257 lua_pop(L, 2);
2258 }
2259 return -1;
2260 }
2261
2262 static int cdata_unm(lua_State* L)
2263 {
2264 struct ctype ct;
2265 void* p;
2266 int64_t val;
2267 int ret;
2268
2269 lua_settop(L, 1);
2270 p = to_cdata(L, 1, &ct);
2271
2272 ret = call_user_op(L, "__unm", 1, 2, &ct);
2273 if (ret >= 0) {
2274 return ret;
2275 }
2276
2277 val = check_intptr(L, 1, p, &ct);
2278
2279 if (ct.pointers) {
2280 luaL_error(L, "can't negate a pointer value");
2281 } else {
2282 memset(&ct, 0, sizeof(ct));
2283 ct.type = INT64_TYPE;
2284 ct.base_size = 8;
2285 ct.is_defined = 1;
2286 push_number(L, -val, 0, &ct);
2287 }
2288
2289 return 1;
2290 }
2291
2292 /* returns -ve if no binop was called otherwise returns the number of return
2293 * arguments */
2294 static int call_user_binop(lua_State* L, const char* opfield, int lidx, int lusr, const struct ctype* lt, int ridx, int rusr, const struct ctype* rt)
2295 {
2296 lidx = lua_absindex(L, lidx);
2297 ridx = lua_absindex(L, ridx);
2298
2299 if (push_user_mt(L, lusr, lt)) {
2300 lua_pushstring(L, opfield);
2301 lua_rawget(L, -2);
2302
2303 if (!lua_isnil(L, -1)) {
2304 int top = lua_gettop(L);
2305 lua_pushvalue(L, lidx);
2306 lua_pushvalue(L, ridx);
2307 lua_call(L, 2, LUA_MULTRET);
2308 return lua_gettop(L) - top + 1;
2309 }
2310
2311 lua_pop(L, 2); /* user_mt and user_mt.op */
2312 }
2313
2314 if (push_user_mt(L, rusr, rt)) {
2315 lua_pushstring(L, opfield);
2316 lua_rawget(L, -2);
2317
2318 if (!lua_isnil(L, -1)) {
2319 int top = lua_gettop(L);
2320 lua_pushvalue(L, lidx);
2321 lua_pushvalue(L, ridx);
2322 lua_call(L, 2, LUA_MULTRET);
2323 return lua_gettop(L) - top + 1;
2324 }
2325
2326 lua_pop(L, 2); /* user_mt and user_mt.op */
2327 }
2328
2329 return -1;
2330 }
2331
2332 static int user_cdata_concat(lua_State* L)
2333 {
2334 struct ctype lt, rt;
2335 int ret;
2336
2337 lua_settop(L, 2);
2338 to_cdata(L, 1, &lt);
2339 to_cdata(L, 2, &rt);
2340
2341 ret = call_user_binop(L, "__concat", 1, 3, &lt, 2, 4, &rt);
2342 if (ret >= 0) {
2343 return ret;
2344 }
2345
2346 lua_settop(L, 2);
2347 return -1;
2348 }
2349
2350 #if LUA_VERSION_NUM > 501
2351 static int stringified_cdata_concat(lua_State* L)
2352 {
2353 size_t l_size = 0, r_size = 0;
2354 const char * l_str = NULL;
2355 const char * r_str = NULL;
2356 char * o_str = NULL;
2357
2358 lua_settop(L, 2);
2359
2360 r_str = luaL_tolstring(L, 2, &r_size);
2361 if (!r_str) return luaL_error(L, "NYI");
2362 l_str = luaL_tolstring(L, 1, &l_size);
2363 if (!l_str) return luaL_error(L, "NYI");
2364
2365 o_str = malloc(l_size + r_size);
2366
2367 memcpy(o_str, l_str, l_size);
2368 memcpy((o_str+l_size), r_str, r_size);
2369
2370 lua_pushlstring(L, o_str, l_size + r_size);
2371
2372 free(o_str);
2373
2374 return 1;
2375 }
2376 #endif
2377
2378 static int cdata_concat(lua_State* L)
2379 {
2380 int ret = user_cdata_concat(L);
2381 if (ret != -1) {
2382 return ret;
2383 }
2384
2385 #if LUA_VERSION_NUM > 501
2386 return stringified_cdata_concat(L);
2387 #else
2388 return ret;
2389 #endif
2390 }
2391
2392 static int cdata_len(lua_State* L)
2393 {
2394 struct ctype ct;
2395 int ret;
2396
2397 lua_settop(L, 1);
2398 to_cdata(L, 1, &ct);
2399
2400 ret = call_user_op(L, "__len", 1, 2, &ct);
2401 if (ret >= 0) {
2402 return ret;
2403 }
2404
2405 push_type_name(L, 2, &ct);
2406 return luaL_error(L, "type %s does not implement the __len metamethod", lua_tostring(L, -1));
2407 }
2408
2409 static int cdata_pairs(lua_State* L)
2410 {
2411 struct ctype ct;
2412 int ret;
2413
2414 lua_settop(L, 1);
2415 to_cdata(L, 1, &ct);
2416
2417 ret = call_user_op(L, "__pairs", 1, 2, &ct);
2418 if (ret >= 0) {
2419 return ret;
2420 }
2421
2422 push_type_name(L, 2, &ct);
2423 return luaL_error(L, "type %s does not implement the __pairs metamethod", lua_tostring(L, -1));
2424 }
2425
2426 static int cdata_ipairs(lua_State* L)
2427 {
2428 struct ctype ct;
2429 int ret;
2430
2431 lua_settop(L, 1);
2432 to_cdata(L, 1, &ct);
2433
2434 ret = call_user_op(L, "__ipairs", 1, 2, &ct);
2435 if (ret >= 0) {
2436 return ret;
2437 }
2438
2439 push_type_name(L, 2, &ct);
2440 return luaL_error(L, "type %s does not implement the __ipairs metamethod", lua_tostring(L, -1));
2441 }
2442
2443 static int cdata_add(lua_State* L)
2444 {
2445 struct ctype lt, llt, rt, rrt, ct;
2446 void *lp, *rp;
2447 int ct_usr;
2448 int ret;
2449
2450 lua_settop(L, 2);
2451
2452 lp = to_cdata(L, 1, &lt);
2453 rp = to_cdata(L, 2, &rt);
2454 llt = lt;
2455 rrt = rt;
2456 assert(lua_gettop(L) == 4);
2457
2458 ret = call_user_binop(L, "__add", 1, 3, &lt, 2, 4, &rt);
2459 if (ret >= 0) {
2460 return ret;
2461 }
2462 assert(lua_gettop(L) == 4);
2463
2464 ct_usr = rank(&lt) > rank(&rt) ? 3 : 4;
2465 ct = rank(&lt) > rank(&rt) ? lt : rt;
2466
2467 if (IS_COMPLEX(ct.type)) {
2468 complex_double left, right, res;
2469
2470 left = check_complex(L, 1, lp, &lt);
2471 right = check_complex(L, 2, rp, &rt);
2472 assert(lua_gettop(L) == 4);
2473
2474 #ifdef HAVE_COMPLEX
2475 res = left + right;
2476 #else
2477 res.real = left.real + right.real;
2478 res.imag = left.imag + right.imag;
2479 #endif
2480
2481 push_complex(L, res, ct_usr, &ct);
2482 return 1;
2483
2484 } else {
2485 int64_t left = check_intptr(L, 1, lp, &llt);
2486 int64_t right = check_intptr(L, 2, rp, &rrt);
2487 /*
2488 * There is a side effect of check_intptr that it freshly assigns
2489 * values for lt and rrt if one of them is an INVALID type (e.g. LUA NUMBER)
2490 * thus the rank and therefore ct and ct_usr should get re-evaluated once again.
2491 */
2492 ct_usr = rank(&lt) > rank(&rt) ? 3 : 4;
2493 ct = rank(&lt) > rank(&rt) ? lt : rt;
2494 assert(lua_gettop(L) == 4);
2495
2496 /* note due to 2s complement it doesn't matter if we do the addition as int or uint,
2497 * but the result needs to be uint64_t if either of the sources are */
2498
2499 if (llt.pointers && rrt.pointers) {
2500 luaL_error(L, "can't add two pointers");
2501
2502 } else if (llt.pointers) {
2503 int64_t res = left + (llt.pointers > 1 ? sizeof(void*) : llt.base_size) * right;
2504 llt.is_array = 0;
2505 push_number(L, res, 3, &llt);
2506
2507 } else if (rrt.pointers) {
2508 int64_t res = right + (rrt.pointers > 1 ? sizeof(void*) : rrt.base_size) * left;
2509 rrt.is_array = 0;
2510 push_number(L, res, 4, &rrt);
2511
2512 } else {
2513 push_number(L, left + right, ct_usr, &ct);
2514 }
2515
2516 return 1;
2517 }
2518 }
2519
2520 static int cdata_sub(lua_State* L)
2521 {
2522 struct ctype lt, llt, rt, rrt, ct;
2523 void *lp, *rp;
2524 int ct_usr;
2525 int ret;
2526
2527 lua_settop(L, 2);
2528
2529 lp = to_cdata(L, 1, &lt);
2530 rp = to_cdata(L, 2, &rt);
2531 llt = lt;
2532 rrt = rt;
2533
2534 ret = call_user_binop(L, "__sub", 1, 3, &lt, 2, 4, &rt);
2535 if (ret >= 0) {
2536 return ret;
2537 }
2538
2539 ct_usr = rank(&lt) > rank(&rt) ? 3 : 4;
2540 ct = rank(&lt) > rank(&rt) ? lt : rt;
2541
2542 if (IS_COMPLEX(ct.type)) {
2543 complex_double left, right, res;
2544
2545 left = check_complex(L, 1, lp, &lt);
2546 right = check_complex(L, 2, rp, &rt);
2547
2548 #ifdef HAVE_COMPLEX
2549 res = left - right;
2550 #else
2551 res.real = left.real - right.real;
2552 res.imag = left.imag - right.imag;
2553 #endif
2554
2555 push_complex(L, res, ct_usr, &ct);
2556 return 1;
2557
2558 } else {
2559 int64_t left = check_intptr(L, 1, lp, &llt);
2560 int64_t right = check_intptr(L, 2, rp, &rrt);
2561 /*
2562 * There is a side effect of check_intptr that it freshly assigns
2563 * values for llt and rt if one of them is an INVALID type (e.g. LUA NUMBER)
2564 * thus the rank and therefore ct and ct_usr should get re-evaluated once again.
2565 */
2566 ct_usr = rank(&lt) > rank(&rt) ? 3 : 4;
2567 ct = rank(&lt) > rank(&rt) ? lt : rt;
2568 assert(lua_gettop(L) == 4);
2569
2570 if (rrt.pointers) {
2571 luaL_error(L, "NYI: can't subtract a pointer value");
2572
2573 } else if (llt.pointers) {
2574 int64_t res = left - (llt.pointers > 1 ? sizeof(void*) : llt.base_size) * right;
2575 llt.is_array = 0;
2576 push_number(L, res, 3, &llt);
2577
2578 } else {
2579 int64_t res = left - right;
2580 push_number(L, res, ct_usr, &ct);
2581 }
2582
2583 return 1;
2584 }
2585 }
2586
2587 #define NUMBER_ONLY_BINOP(OPSTR, DO_NORMAL, DO_COMPLEX) \
2588 struct ctype lt, llt, rt, rrt, ct; \
2589 void *lp, *rp; \
2590 int ct_usr; \
2591 int ret; \
2592 \
2593 lua_settop(L, 2); \
2594 \
2595 lp = to_cdata(L, 1, &lt); \
2596 rp = to_cdata(L, 2, &rt); \
2597 llt = lt; \
2598 rrt = rt; \
2599 \
2600 ret = call_user_binop(L, OPSTR, 1, 3, &lt, 2, 4, &rt); \
2601 if (ret >= 0) { \
2602 return ret; \
2603 } \
2604 \
2605 ct_usr = rank(&lt) > rank(&rt) ? 3 : 4; \
2606 ct = rank(&lt) > rank(&rt) ? lt : rt; \
2607 \
2608 if (IS_COMPLEX(ct.type)) { \
2609 complex_double res; \
2610 complex_double left = check_complex(L, 1, lp, &lt); \
2611 complex_double right = check_complex(L, 2, rp, &rt); \
2612 \
2613 DO_COMPLEX(left, right, res); \
2614 push_complex(L, res, ct_usr, &ct); \
2615 \
2616 } else if (lt.pointers || rt.pointers) { \
2617 luaL_error(L, "can't operate on a pointer value"); \
2618 \
2619 } else if (ct.is_unsigned) { \
2620 uint64_t res; \
2621 uint64_t left = check_intptr(L, 1, lp, &llt); \
2622 uint64_t right = check_intptr(L, 2, rp, &rrt); \
2623 \
2624 DO_NORMAL(left, right, res); \
2625 push_number(L, res, ct_usr, &ct); \
2626 } else { \
2627 int64_t res; \
2628 int64_t left = check_intptr(L, 1, lp, &llt); \
2629 int64_t right = check_intptr(L, 2, rp, &rrt); \
2630 \
2631 DO_NORMAL(left, right, res); \
2632 push_number(L, res, ct_usr, &ct); \
2633 } \
2634 \
2635 return 1
2636
2637 #define MUL(l,r,s) s = l * r
2638 #define DIV(l,r,s) s = l / r
2639 #define MOD(l,r,s) s = l % r
2640 #define POW(l,r,s) s = pow(l, r)
2641
2642 #ifdef HAVE_COMPLEX
2643 #define MULC(l,r,s) s = l * r
2644 #define DIVC(l,r,s) s = l / r
2645 #define MODC(l,r,s) (void) l, (void) r, memset(&s, 0, sizeof(s)), luaL_error(L, "NYI: complex mod")
2646 #define POWC(l,r,s) s = cpow(l, r)
2647 #else
2648 #define MULC(l,r,s) s.real = l.real * r.real - l.imag * r.imag, s.imag = l.real * r.imag + l.imag * r.real
2649 #define DIVC(l,r,s) s.real = (l.real * r.real + l.imag * r.imag) / (r.real * r.real + r.imag * r.imag), \
2650 s.imag = (l.imag * r.real - l.real * r.imag) / (r.real * r.real + r.imag * r.imag)
2651 #define MODC(l,r,s) (void) l, (void) r, memset(&s, 0, sizeof(s)), luaL_error(L, "NYI: complex mod")
2652 #define POWC(l,r,s) (void) l, (void) r, memset(&s, 0, sizeof(s)), luaL_error(L, "NYI: complex pow")
2653 #endif
2654
2655 static int cdata_mul(lua_State* L)
2656 { NUMBER_ONLY_BINOP("__mul", MUL, MULC); }
2657
2658 static int cdata_div(lua_State* L)
2659 { NUMBER_ONLY_BINOP("__div", DIV, DIVC); }
2660
2661 static int cdata_mod(lua_State* L)
2662 { NUMBER_ONLY_BINOP("__mod", MOD, MODC); }
2663
2664 static int cdata_pow(lua_State* L)
2665 { NUMBER_ONLY_BINOP("__pow", POW, POWC); }
2666
2667 #define COMPARE_BINOP(OPSTR, OP, OPC) \
2668 struct ctype lt, rt; \
2669 void *lp, *rp; \
2670 int ret, res; \
2671 \
2672 lua_settop(L, 2); \
2673 \
2674 lp = to_cdata(L, 1, &lt); \
2675 rp = to_cdata(L, 2, &rt); \
2676 \
2677 ret = call_user_binop(L, OPSTR, 1, 3, &lt, 2, 4, &rt); \
2678 if (ret >= 0) { \
2679 return ret; \
2680 } \
2681 \
2682 if (IS_COMPLEX(lt.type) || IS_COMPLEX(rt.type)) { \
2683 complex_double left = check_complex(L, 1, lp, &lt); \
2684 complex_double right = check_complex(L, 2, rp, &rt); \
2685 \
2686 res = OPC(left, right); \
2687 \
2688 lua_pushboolean(L, res); \
2689 \
2690 } else { \
2691 int64_t left = check_intptr(L, 1, lp, &lt); \
2692 int64_t right = check_intptr(L, 2, rp, &rt); \
2693 \
2694 if (lt.pointers && rt.pointers) { \
2695 if (is_void_ptr(&lt) || is_void_ptr(&rt) || is_same_type(L, 3, 4, &lt, &rt)) { \
2696 res = OP((uint64_t) left, (uint64_t) right); \
2697 } else { \
2698 goto err; \
2699 } \
2700 \
2701 } else if (lt.is_null && rt.type == FUNCTION_PTR_TYPE) { \
2702 res = OP((uint64_t) left, (uint64_t) right); \
2703 \
2704 } else if (rt.is_null && lt.type == FUNCTION_PTR_TYPE) { \
2705 res = OP((uint64_t) left, (uint64_t) right); \
2706 \
2707 } else if (lt.pointers && rt.type == INTPTR_TYPE && rt.is_unsigned) {\
2708 res = OP((uint64_t) left, (uint64_t) right); \
2709 \
2710 } else if (rt.pointers && lt.type == INTPTR_TYPE && lt.is_unsigned) {\
2711 res = OP((uint64_t) left, (uint64_t) right); \
2712 \
2713 } else if (rt.pointers || lt.pointers) { \
2714 goto err; \
2715 \
2716 } else if (lt.is_unsigned && rt.is_unsigned) { \
2717 res = OP((uint64_t) left, (uint64_t) right); \
2718 \
2719 } else if (lt.is_unsigned) { \
2720 res = OP((int64_t) (uint64_t) left, right); \
2721 \
2722 } else if (rt.is_unsigned) { \
2723 res = OP(left, (int64_t) (uint64_t) right); \
2724 \
2725 } else { \
2726 res = OP(left, right); \
2727 } \
2728 \
2729 lua_pushboolean(L, res); \
2730 } \
2731 return 1
2732
2733 #define EQ(l, r) (l) == (r)
2734 #define LT(l, r) (l) < (r)
2735 #define LE(l, r) (l) <= (r)
2736
2737 #ifdef HAVE_COMPLEX
2738 #define EQC(l, r) (l) == (r)
2739 #else
2740 #define EQC(l, r) (l).real == (r).real && (l).imag == (r).imag
2741 #endif
2742
2743 #define LEC(l, r) EQC(l, r), luaL_error(L, "complex numbers are non-orderable")
2744 #define LTC(l, r) EQC(l, r), luaL_error(L, "complex numbers are non-orderable")
2745
2746 static int cdata_eq(lua_State* L)
2747 {
2748 COMPARE_BINOP("__eq", EQ, EQC);
2749 err:
2750 lua_pushboolean(L, 0);
2751 return 1;
2752 }
2753
2754 static int cdata_lt(lua_State* L)
2755 {
2756 COMPARE_BINOP("__lt", LT, LTC);
2757 err:
2758 lua_getuservalue(L, 1);
2759 lua_getuservalue(L, 2);
2760 push_type_name(L, -2, &lt);
2761 push_type_name(L, -2, &lt);
2762 return luaL_error(L, "trying to compare incompatible types %s and %s", lua_tostring(L, -2), lua_tostring(L, -1));
2763 }
2764
2765 static int cdata_le(lua_State* L)
2766 {
2767 COMPARE_BINOP("__le", LE, LEC);
2768 err:
2769 lua_getuservalue(L, 1);
2770 lua_getuservalue(L, 2);
2771 push_type_name(L, -2, &lt);
2772 push_type_name(L, -2, &lt);
2773 return luaL_error(L, "trying to compare incompatible types %s and %s", lua_tostring(L, -2), lua_tostring(L, -1));
2774 }
2775
2776 static const char* etype_tostring(int type)
2777 {
2778 switch (type) {
2779 case VOID_TYPE: return "void";
2780 case DOUBLE_TYPE: return "double";
2781 case FLOAT_TYPE: return "float";
2782 case COMPLEX_DOUBLE_TYPE: return "complex double";
2783 case COMPLEX_FLOAT_TYPE: return "complex float";
2784 case BOOL_TYPE: return "bool";
2785 case INT8_TYPE: return "int8";
2786 case INT16_TYPE: return "int16";
2787 case INT32_TYPE: return "int32";
2788 case INT64_TYPE: return "int64";
2789 case INTPTR_TYPE: return "intptr";
2790 case ENUM_TYPE: return "enum";
2791 case UNION_TYPE: return "union";
2792 case STRUCT_TYPE: return "struct";
2793 case FUNCTION_PTR_TYPE: return "function ptr";
2794 case FUNCTION_TYPE: return "function";
2795 default: return "invalid";
2796 }
2797 }
2798
2799 static void print_type(lua_State* L, const struct ctype* ct)
2800 {
2801 lua_pushfstring(L, " sz %d %d %d align %d ptr %d %d const %d type %s%s %d %d %d name %d call %d %d var %d %d %d bit %d %d %d %d jit %d",
2802 /* sz */
2803 ct->base_size,
2804 ct->array_size,
2805 ct->offset,
2806 /* align */
2807 ct->align_mask,
2808 /* ptr */
2809 ct->is_array,
2810 ct->pointers,
2811 /* const */
2812 ct->const_mask,
2813 /* type */
2814 ct->is_unsigned ? "u" : "",
2815 etype_tostring(ct->type),
2816 ct->is_reference,
2817 ct->is_defined,
2818 ct->is_null,
2819 /* name */
2820 ct->has_member_name,
2821 /* call */
2822 ct->calling_convention,
2823 ct->has_var_arg,
2824 /* var */
2825 ct->is_variable_array,
2826 ct->is_variable_struct,
2827 ct->variable_size_known,
2828 /* bit */
2829 ct->is_bitfield,
2830 ct->has_bitfield,
2831 ct->bit_offset,
2832 ct->bit_size,
2833 /* jit */
2834 ct->is_jitted);
2835 }
2836
2837 static int ctype_tostring(lua_State* L)
2838 {
2839 struct ctype ct;
2840 assert(lua_type(L, 1) == LUA_TUSERDATA);
2841 lua_settop(L, 1);
2842 check_ctype(L, 1, &ct);
2843 assert(lua_gettop(L) == 2);
2844 push_type_name(L, -1, &ct);
2845 lua_pushfstring(L, "ctype<%s>", lua_tostring(L, -1));
2846
2847 if (DEBUG_TOSTRING) {
2848 print_type(L, &ct);
2849 lua_concat(L, 2);
2850 }
2851
2852 return 1;
2853 }
2854
2855 static int cdata_tostring(lua_State* L)
2856 {
2857 struct ctype ct;
2858 char buf[64];
2859 void* p;
2860 int ret;
2861
2862 lua_settop(L, 1);
2863 p = to_cdata(L, 1, &ct);
2864
2865 ret = call_user_op(L, "__tostring", 1, 2, &ct);
2866 if (ret >= 0) {
2867 return ret;
2868 }
2869
2870 if (ct.pointers > 0 || ct.is_reference || ct.type == STRUCT_TYPE || ct.type == UNION_TYPE) {
2871 push_type_name(L, -1, &ct);
2872 lua_pushfstring(L, "cdata<%s>: %p", lua_tostring(L, -1), p);
2873
2874 if (DEBUG_TOSTRING) {
2875 print_type(L, &ct);
2876 lua_concat(L, 2);
2877 }
2878
2879 return 1;
2880 }
2881
2882 switch (ct.type) {
2883 case COMPLEX_DOUBLE_TYPE:
2884 {
2885 complex_double c = *(complex_double*) p;
2886 lua_pushfstring(L, "%f+%fi", creal(c), cimag(c));
2887 }
2888 return 1;
2889
2890 case COMPLEX_FLOAT_TYPE:
2891 {
2892 complex_float c = *(complex_float*) p;
2893 lua_pushfstring(L, "%f+%fi", crealf(c), cimagf(c));
2894 }
2895 return 1;
2896
2897 case FUNCTION_PTR_TYPE:
2898 p = *(void**) p;
2899 push_type_name(L, -1, &ct);
2900 lua_pushfstring(L, "cdata<%s>: %p", lua_tostring(L, -1), *(void**) p);
2901 return 1;
2902
2903 case INTPTR_TYPE:
2904 lua_pushfstring(L, "%p", *(uintptr_t*) p);
2905 return 1;
2906
2907 case BOOL_TYPE:
2908 sprintf(buf,"%s", (*(_Bool*) p) ? "true" : "false");
2909 lua_pushstring(L, buf);
2910 return 1;
2911
2912 case INT8_TYPE:
2913 sprintf(buf, ct.is_unsigned ? "%hhu" : "%hhd", *(uint8_t*) p);
2914 lua_pushstring(L, buf);
2915 return 1;
2916
2917 case INT16_TYPE:
2918 sprintf(buf, ct.is_unsigned ? "%hu" : "%hd", *(uint16_t*) p);
2919 lua_pushstring(L, buf);
2920 return 1;
2921
2922 case INT32_TYPE:
2923 sprintf(buf, ct.is_unsigned ? "%u" : "%d", *(uint32_t*) p);
2924 lua_pushstring(L, buf);
2925 return 1;
2926
2927 case INT64_TYPE:
2928 sprintf(buf, ct.is_unsigned ? "%"PRIu64 : "%"PRId64, *(uint64_t*) p);
2929 lua_pushstring(L, buf);
2930 return 1;
2931
2932 case FLOAT_TYPE:
2933 sprintf(buf,"%f", *(float*) p);
2934 lua_pushstring(L, buf);
2935 return 1;
2936
2937 case DOUBLE_TYPE:
2938 sprintf(buf,"%lf", *(double*) p);
2939 lua_pushstring(L, buf);
2940 return 1;
2941
2942 default:
2943 sprintf(buf, ct.is_unsigned ? "%"PRId64 : "%"PRId64, (int64_t) check_intptr(L, 1, p, &ct));
2944 lua_pushstring(L, buf);
2945 return 1;
2946 }
2947 }
2948
2949 static int ffi_getptr(lua_State* L)
2950 {
2951 struct ctype ct;
2952 void* p = NULL;
2953
2954 lua_settop(L, 1);
2955 p = to_cdata(L, 1, &ct);
2956 lua_pushlightuserdata(L, p);
2957 return 1;
2958
2959 }
2960
2961 static int ffi_errno(lua_State* L)
2962 {
2963 struct jit* jit = get_jit(L);
2964
2965 if (!lua_isnoneornil(L, 1)) {
2966 lua_pushinteger(L, jit->last_errno);
2967 jit->last_errno = luaL_checknumber(L, 1);
2968 } else {
2969 lua_pushinteger(L, jit->last_errno);
2970 }
2971
2972 return 1;
2973 }
2974
2975 static int ffi_type(lua_State* L)
2976 {
2977 if (lua_isuserdata(L, 1) && lua_getmetatable(L, 1)) {
2978 if (equals_upval(L, -1, &cdata_mt_key) || equals_upval(L, -1, &ctype_mt_key)) {
2979 lua_pushstring(L, "cdata");
2980 return 1;
2981 }
2982 lua_pop(L, 1); /* mt */
2983 }
2984
2985 /* call the old _G.type, we use an upvalue as _G.type is set
2986 * to this function */
2987 lua_pushvalue(L, lua_upvalueindex(1));
2988 lua_insert(L, 1);
2989 lua_call(L, lua_gettop(L)-1, LUA_MULTRET);
2990 return lua_gettop(L);
2991 }
2992
2993 static int ffi_number(lua_State* L)
2994 {
2995 struct ctype ct;
2996 void* data = to_cdata(L, 1, &ct);
2997
2998 //pfintf("%s:%d\n", __FILE__, __LINE__);
2999
3000 if (ct.type != INVALID_TYPE) {
3001 switch (ct.type) {
3002 case FLOAT_TYPE:
3003 lua_pushnumber(L, *(float*)data);
3004 break;
3005 default:
3006 lua_pushinteger(L, check_intptr(L, 1, data, &ct));
3007 break;
3008 }
3009 return 1;
3010 } else {
3011 /* call the old _G.tonumber, we use an upvalue as _G.tonumber is set
3012 * to this function */
3013 lua_pushvalue(L, lua_upvalueindex(1));
3014 lua_insert(L, 1);
3015 lua_call(L, lua_gettop(L)-1, LUA_MULTRET);
3016 return lua_gettop(L);
3017 }
3018 }
3019
3020 static int ffi_string(lua_State* L)
3021 {
3022 struct ctype ct;
3023 char* data;
3024 lua_settop(L, 2);
3025
3026 data = (char*) check_cdata(L, 1, &ct);
3027
3028 if (is_void_ptr(&ct)) {
3029 lua_pushlstring(L, data, (size_t) luaL_checknumber(L, 2));
3030 return 1;
3031
3032 } else if (ct.type == INT8_TYPE && ct.pointers == 1) {
3033 size_t sz;
3034
3035 if (lua_isuserdata(L, 2)) {
3036 ptrdiff_t val;
3037 if (!cdata_tointeger(L, 2, &val)) {
3038 type_error(L, 2, "int", 0, NULL);
3039 }
3040 sz = (size_t) val;
3041 } else if (!lua_isnil(L, 2)) {
3042 sz = (size_t) luaL_checknumber(L, 2);
3043
3044 } else if (ct.is_array && !ct.is_variable_array) {
3045 char* nul = memchr(data, '\0', ct.array_size);
3046 sz = nul ? nul - data : ct.array_size;
3047
3048 } else {
3049 sz = strlen(data);
3050 }
3051
3052 lua_pushlstring(L, data, sz);
3053 return 1;
3054 }
3055
3056 return luaL_error(L, "unable to convert cdata to string");
3057 }
3058
3059 static int ffi_copy(lua_State* L)
3060 {
3061 struct ctype ft, tt;
3062 char *to, *from;
3063
3064 setmintop(L, 3);
3065 to = (char*) check_pointer(L, 1, &tt);
3066 from = (char*) check_pointer(L, 2, &ft);
3067
3068 if (!lua_isnoneornil(L, 3)) {
3069 memcpy(to, from, (size_t) luaL_checknumber(L, 3));
3070
3071 } else if (ft.type == INT8_TYPE && ft.pointers == 1) {
3072 size_t sz = ft.is_array ? ft.array_size : strlen(from);
3073 memcpy(to, from, sz);
3074 to[sz] = '\0';
3075 }
3076
3077 return 0;
3078 }
3079
3080 static int ffi_fill(lua_State* L)
3081 {
3082 struct ctype ct;
3083 void* to;
3084 size_t sz;
3085 int val = 0;
3086
3087 setmintop(L, 3);
3088 to = check_pointer(L, 1, &ct);
3089 sz = (size_t) luaL_checknumber(L, 2);
3090
3091 if (!lua_isnoneornil(L, 3)) {
3092 val = (int) luaL_checkinteger(L, 3);
3093 }
3094
3095 memset(to, val, sz);
3096 return 0;
3097 }
3098
3099 static int ffi_abi(lua_State* L)
3100 {
3101 luaL_checkstring(L, 1);
3102 push_upval(L, &abi_key);
3103 lua_pushvalue(L, 1);
3104 lua_rawget(L, -2);
3105 lua_pushboolean(L, lua_toboolean(L, -1));
3106 return 1;
3107 }
3108
3109 static int ffi_load(lua_State* L)
3110 {
3111 const char* libname = luaL_checkstring(L, 1);
3112 void** lib = (void**) lua_newuserdata(L, sizeof(void*));
3113
3114 *lib = LoadLibraryA(libname);
3115
3116 #ifdef LIB_FORMAT_1
3117 if (!*lib) {
3118 libname = lua_pushfstring(L, LIB_FORMAT_1, lua_tostring(L, 1));
3119 *lib = LoadLibraryA(libname);
3120 lua_pop(L, 1);
3121 }
3122 #endif
3123
3124 #ifdef LIB_FORMAT_2
3125 if (!*lib) {
3126 libname = lua_pushfstring(L, LIB_FORMAT_2, lua_tostring(L, 1));
3127 *lib = LoadLibraryA(libname);
3128 lua_pop(L, 1);
3129 }
3130 #endif
3131
3132 if (!*lib) {
3133 return luaL_error(L, "could not load library %s", lua_tostring(L, 1));
3134 }
3135
3136 lua_newtable(L);
3137 lua_setuservalue(L, -2);
3138
3139 push_upval(L, &cmodule_mt_key);
3140 lua_setmetatable(L, -2);
3141 return 1;
3142 }
3143
3144 static void* find_symbol(lua_State* L, int modidx, const char* asmname)
3145 {
3146 size_t i;
3147 void** libs;
3148 size_t num;
3149 void* sym = NULL;
3150
3151 libs = (void**) lua_touserdata(L, modidx);
3152 num = lua_rawlen(L, modidx) / sizeof(void*);
3153
3154 for (i = 0; i < num && sym == NULL; i++) {
3155 if (libs[i]) {
3156 sym = GetProcAddressA(libs[i], asmname);
3157 }
3158 }
3159
3160 return sym;
3161 }
3162
3163 /* pushes the user table */
3164 static void* lookup_global(lua_State* L, int modidx, int nameidx, const char** pname, struct ctype* ct)
3165 {
3166 int top = lua_gettop(L);
3167 void* sym;
3168
3169 modidx = lua_absindex(L, modidx);
3170 nameidx = lua_absindex(L, nameidx);
3171
3172 *pname = luaL_checkstring(L, nameidx);
3173
3174 /* get the ctype */
3175 push_upval(L, &functions_key);
3176 lua_pushvalue(L, nameidx);
3177 lua_rawget(L, -2);
3178 if (lua_isnil(L, -1)) {
3179 luaL_error(L, "missing declaration for function/global %s", *pname);
3180 return NULL;
3181 }
3182
3183 /* leave just the ct_usr on the stack */
3184 //*ct = *(const struct ctype*) lua_touserdata(L, -1);
3185 memcpy(ct, lua_touserdata(L, -1), sizeof(struct ctype));
3186 lua_getuservalue(L, -1);
3187 lua_replace(L, top + 1);
3188 lua_pop(L, 1);
3189
3190 assert(lua_gettop(L) == top + 1);
3191
3192 /* get the assembly name */
3193 push_upval(L, &asmname_key);
3194 lua_pushvalue(L, nameidx);
3195 lua_rawget(L, -2);
3196 if (lua_isstring(L, -1)) {
3197 *pname = lua_tostring(L, -1);
3198 }
3199 lua_pop(L, 2);
3200
3201 sym = find_symbol(L, modidx, *pname);
3202
3203 assert(lua_gettop(L) == top + 1);
3204 return sym;
3205 }
3206
3207 static int cmodule_index(lua_State* L)
3208 {
3209 const char* asmname;
3210 struct ctype ct;
3211 void *sym = 0;
3212
3213 lua_settop(L, 2);
3214
3215 /* see if we have already loaded the function */
3216 lua_getuservalue(L, 1);
3217 lua_pushvalue(L, 2);
3218 lua_rawget(L, -2);
3219 if (!lua_isnil(L, -1)) {
3220 return 1;
3221 }
3222 lua_pop(L, 2);
3223
3224 /* check the constants table */
3225 push_upval(L, &constants_key);
3226 lua_pushvalue(L, 2);
3227 lua_rawget(L, -2);
3228 if (!lua_isnil(L, -1)) {
3229 return 1;
3230 }
3231 lua_pop(L, 2);
3232
3233 /* lookup_global pushes the ct_usr */
3234 sym = lookup_global(L, 1, 2, &asmname, &ct);
3235
3236 #if defined _WIN32 && !defined _WIN64 && (defined __i386__ || defined _M_IX86)
3237 if (!sym && ct.type == FUNCTION_TYPE) {
3238 ct.calling_convention = STD_CALL;
3239 lua_pushfstring(L, "_%s@%d", asmname, x86_return_size(L, -1, &ct));
3240 sym = find_symbol(L, 1, lua_tostring(L, -1));
3241 lua_pop(L, 1);
3242 }
3243
3244 if (!sym && ct.type == FUNCTION_TYPE) {
3245 ct.calling_convention = FAST_CALL;
3246 lua_pushfstring(L, "@%s@%d", asmname, x86_return_size(L, -1, &ct));
3247 sym = find_symbol(L, 1, lua_tostring(L, -1));
3248 lua_pop(L, 1);
3249 }
3250 #endif
3251
3252 if (!sym) {
3253 return luaL_error(L, "failed to find function/global %s", asmname);
3254 }
3255
3256 assert(lua_gettop(L) == 3); /* module, name, ct_usr */
3257
3258 if (ct.type == FUNCTION_TYPE) {
3259 compile_function(L, (cfunction) sym, -1, &ct);
3260 #ifdef ARCH_ARM64
3261 /* Ref: https://developer.arm.com/documentation/ihi0053/latest
3262 * Generates an ISB (instruction synchronization barrier) instruction or
3263 * equivalent CP15 instruction. This instruction flushes the processor
3264 * pipeline fetch buffers, so that following instructions are fetched
3265 * from cache or memory. An ISB is needed after some system maintenance
3266 * operations. An ISB is also needed before transferring control to code
3267 * that has been loaded or modified in memory, for example by an overlay
3268 * mechanism or just-in-time code generator. (Note that if instruction
3269 * and data caches are separate, privileged cache maintenance operations
3270 * would be needed in order to unify the caches.) The only supported
3271 * argument for the __isb() intrinsic is 15, corresponding to the SY
3272 * (full system) scope of the ISB instruction.
3273 */
3274 #ifdef __clang__
3275 __isb(15);
3276 #elif __GNUC__
3277 asm("isb 15");
3278 #endif
3279 #endif
3280 assert(lua_gettop(L) == 4); /* module, name, ct_usr, function */
3281
3282 /* set module usr value[luaname] = function to cache for next time */
3283 lua_getuservalue(L, 1);
3284 lua_pushvalue(L, 2);
3285 lua_pushvalue(L, -3);
3286 lua_rawset(L, -3);
3287 lua_pop(L, 1); /* module uv */
3288 return 1;
3289 }
3290
3291 /* extern const char* foo; and extern const char foo[]; */
3292 if (ct.pointers == 1 && ct.type == INT8_TYPE) {
3293 char* str = (char*) sym;
3294 if (!ct.is_array) {
3295 str = *(char**) sym;
3296 }
3297 lua_pushstring(L, str);
3298 return 1;
3299 }
3300
3301 /* extern struct foo foo[], extern void* foo[]; and extern struct foo foo; */
3302 if (ct.is_array || (!ct.pointers && (ct.type == UNION_TYPE || ct.type == STRUCT_TYPE))) {
3303 void* p;
3304 ct.is_reference = 1;
3305 p = push_cdata(L, -1, &ct);
3306 *(void**) p = sym;
3307 return 1;
3308 }
3309
3310 /* extern void* foo; and extern void (*foo)(); */
3311 if (ct.pointers || ct.type == FUNCTION_PTR_TYPE) {
3312 void* p = push_cdata(L, -1, &ct);
3313 *(void**) p = *(void**) sym;
3314 return 1;
3315 }
3316
3317 switch (ct.type) {
3318 case COMPLEX_DOUBLE_TYPE:
3319 case COMPLEX_FLOAT_TYPE:
3320 case INTPTR_TYPE:
3321 case INT64_TYPE:
3322 {
3323 /* TODO: complex float/double need to be references if .re and
3324 * .imag are setable */
3325 void* p = push_cdata(L, -1, &ct);
3326 memcpy(p, sym, ct.base_size);
3327 return 1;
3328 }
3329
3330 case DOUBLE_TYPE:
3331 lua_pushnumber(L, *(double*) sym);
3332 return 1;
3333
3334 case FLOAT_TYPE:
3335 lua_pushnumber(L, *(float*) sym);
3336 return 1;
3337
3338 case BOOL_TYPE:
3339 lua_pushboolean(L, *(bool*) sym);
3340 return 1;
3341
3342 case INT8_TYPE:
3343 lua_pushinteger(L, ct.is_unsigned ? (lua_Integer) *(uint8_t*) sym : (lua_Integer) *(int8_t*) sym);
3344 return 1;
3345
3346 case INT16_TYPE:
3347 lua_pushinteger(L, ct.is_unsigned ? (lua_Integer) *(uint16_t*) sym : (lua_Integer) *(int16_t*) sym);
3348 return 1;
3349
3350 case INT32_TYPE:
3351 case ENUM_TYPE:
3352 lua_pushinteger(L, ct.is_unsigned ? (lua_Integer) *(uint32_t*) sym : (lua_Integer) *(int32_t*) sym);
3353 return 1;
3354 }
3355
3356 return luaL_error(L, "NYI - global value type");
3357 }
3358
3359 static int cmodule_newindex(lua_State* L)
3360 {
3361 const char* name;
3362 void* sym;
3363 struct ctype ct;
3364
3365 lua_settop(L, 3);
3366
3367 /* pushes the ct_usr */
3368 sym = lookup_global(L, 1, 2, &name, &ct);
3369 assert(lua_gettop(L) == 4); /* module, name, value, ct_usr */
3370
3371 if (sym == NULL) {
3372 return luaL_error(L, "failed to find global %s", name);
3373 }
3374
3375 if (ct.type == FUNCTION_TYPE || ct.is_array || (ct.const_mask & 1)) {
3376 return luaL_error(L, "can not set global %s", name);
3377 }
3378
3379 set_value(L, 3, sym, -1, &ct, 1);
3380 return 0;
3381 }
3382
3383 static int jit_gc(lua_State* L)
3384 {
3385 size_t i;
3386 struct jit* jit = get_jit(L);
3387 dasm_free(jit);
3388 for (i = 0; i < jit->pagenum; i++) {
3389 FreePage(jit->pages[i], jit->pages[i]->size);
3390 }
3391 free(jit->pages);
3392 free(jit->globals);
3393 return 0;
3394 }
3395
3396 static int ffi_debug(lua_State* L)
3397 {
3398 lua_newtable(L);
3399 push_upval(L, &ctype_mt_key);
3400 lua_setfield(L, -2, "ctype_mt");
3401 push_upval(L, &cdata_mt_key);
3402 lua_setfield(L, -2, "cdata_mt");
3403 push_upval(L, &cmodule_mt_key);
3404 lua_setfield(L, -2, "cmodule_mt");
3405 push_upval(L, &constants_key);
3406 lua_setfield(L, -2, "constants");
3407 push_upval(L, &types_key);
3408 lua_setfield(L, -2, "types");
3409 push_upval(L, &jit_key);
3410 lua_setfield(L, -2, "jit");
3411 push_upval(L, &gc_key);
3412 lua_setfield(L, -2, "gc");
3413 push_upval(L, &callbacks_key);
3414 lua_setfield(L, -2, "callbacks");
3415 push_upval(L, &functions_key);
3416 lua_setfield(L, -2, "functions");
3417 push_upval(L, &abi_key);
3418 lua_setfield(L, -2, "abi");
3419 push_upval(L, &next_unnamed_key);
3420 lua_setfield(L, -2, "next_unnamed");
3421 return 1;
3422 }
3423
3424 static int do64(lua_State* L, int is_unsigned)
3425 {
3426 lua_Number low, high;
3427 struct ctype ct;
3428 int64_t val;
3429
3430 lua_settop(L, 2);
3431
3432 if (!lua_isnil(L, 2)) {
3433 high = luaL_checknumber(L, 1);
3434 low = luaL_checknumber(L, 2);
3435 } else {
3436 high = 0;
3437 low = luaL_checknumber(L, 1);
3438 }
3439
3440 val = ((int64_t) (uint32_t) high << 32) | (int64_t) (uint32_t) low;
3441
3442 if (!is_unsigned && (high < 0 || low < 0)) {
3443 val = -val;
3444 }
3445
3446 memset(&ct, 0, sizeof(ct));
3447 ct.type = INT64_TYPE;
3448 ct.is_unsigned = is_unsigned;
3449 ct.is_defined = 1;
3450 ct.base_size = sizeof(int64_t);
3451 push_number(L, (int64_t) val, 0, &ct);
3452
3453 return 1;
3454 }
3455
3456 static int ffi_i64(lua_State* L)
3457 { return do64(L, 0); }
3458
3459 static int ffi_u64(lua_State* L)
3460 { return do64(L, 1); }
3461
3462 static const luaL_Reg cdata_mt[] = {
3463 {"__gc", &cdata_gc},
3464 {"__call", &cdata_call},
3465 {"free", &cdata_free},
3466 {"set", &cdata_set},
3467 {"__index", &cdata_index},
3468 {"__newindex", &cdata_newindex},
3469 {"__add", &cdata_add},
3470 {"__sub", &cdata_sub},
3471 {"__mul", &cdata_mul},
3472 {"__div", &cdata_div},
3473 {"__mod", &cdata_mod},
3474 {"__pow", &cdata_pow},
3475 {"__unm", &cdata_unm},
3476 {"__eq", &cdata_eq},
3477 {"__lt", &cdata_lt},
3478 {"__le", &cdata_le},
3479 {"__tostring", &cdata_tostring},
3480 {"__concat", &cdata_concat},
3481 {"__len", &cdata_len},
3482 {"__pairs", &cdata_pairs},
3483 {"__ipairs", &cdata_ipairs},
3484 {NULL, NULL}
3485 };
3486
3487 static const luaL_Reg callback_mt[] = {
3488 {"__gc", &callback_free},
3489 {NULL, NULL}
3490 };
3491
3492 static const luaL_Reg ctype_mt[] = {
3493 {"__call", &ctype_call},
3494 {"__new", &ctype_new},
3495 {"__index", &ctype_index},
3496 {"__tostring", &ctype_tostring},
3497 {NULL, NULL}
3498 };
3499
3500 static const luaL_Reg cmodule_mt[] = {
3501 {"__index", &cmodule_index},
3502 {"__newindex", &cmodule_newindex},
3503 {NULL, NULL}
3504 };
3505
3506 static const luaL_Reg jit_mt[] = {
3507 {"__gc", &jit_gc},
3508 {NULL, NULL}
3509 };
3510
3511 static const luaL_Reg ffi_reg[] = {
3512 {"cdef", &ffi_cdef},
3513 {"load", &ffi_load},
3514 {"new", &ffi_new},
3515 {"typeof", &ffi_typeof},
3516 {"cast", &ffi_cast},
3517 {"metatype", &ffi_metatype},
3518 {"gc", &ffi_gc},
3519 {"sizeof", &ffi_sizeof},
3520 {"alignof", &ffi_alignof},
3521 {"offsetof", &ffi_offsetof},
3522 {"istype", &ffi_istype},
3523 {"errno", &ffi_errno},
3524 {"string", &ffi_string},
3525 {"copy", &ffi_copy},
3526 {"fill", &ffi_fill},
3527 {"abi", &ffi_abi},
3528 {"debug", &ffi_debug},
3529 {"i64", &ffi_i64},
3530 {"u64", &ffi_u64},
3531 {"getptr", &ffi_getptr},
3532 {NULL, NULL}
3533 };
3534
3535 /* leaves the usr table on the stack */
3536 static void push_builtin(lua_State* L, struct ctype* ct, const char* name, int type, int size, int align, int is_unsigned)
3537 {
3538 memset(ct, 0, sizeof(*ct));
3539 ct->type = type;
3540 ct->base_size = size;
3541 ct->align_mask = align;
3542 ct->is_defined = 1;
3543 ct->is_unsigned = is_unsigned;
3544
3545 if (IS_COMPLEX(type)) {
3546 lua_newtable(L);
3547 } else {
3548 lua_pushnil(L);
3549 }
3550
3551 push_upval(L, &types_key);
3552 push_ctype(L, -2, ct);
3553 lua_setfield(L, -2, name);
3554 lua_pop(L, 2); /* types, usr table */
3555 }
3556
3557 static void push_builtin_undef(lua_State* L, struct ctype* ct, const char* name, int type)
3558 {
3559 memset(ct, 0, sizeof(*ct));
3560 ct->type = type;
3561
3562 push_upval(L, &types_key);
3563 push_ctype(L, 0, ct);
3564 lua_setfield(L, -2, name);
3565 lua_pop(L, 1); /* types */
3566 }
3567
3568 static void add_typedef(lua_State* L, const char* from, const char* to)
3569 {
3570 struct ctype ct;
3571 struct parser P;
3572 P.line = 1;
3573 P.align_mask = DEFAULT_ALIGN_MASK;
3574 P.next = P.prev = from;
3575
3576 push_upval(L, &types_key);
3577 parse_type(L, &P, &ct);
3578 parse_argument(L, &P, -1, &ct, NULL, NULL);
3579 push_ctype(L, -1, &ct);
3580
3581 /* stack is at +4: types, type usr, arg usr, ctype */
3582
3583 lua_setfield(L, -4, to);
3584 lua_pop(L, 3); /* types, type usr, arg usr */
3585 }
3586
3587 static int setup_upvals(lua_State* L)
3588 {
3589 struct jit* jit = get_jit(L);
3590
3591 /* jit setup */
3592 {
3593 dasm_init(jit, 64);
3594 #ifdef _WIN32
3595 {
3596 SYSTEM_INFO si;
3597 GetSystemInfo(&si);
3598 jit->align_page_size = si.dwAllocationGranularity - 1;
3599 }
3600 #else
3601 jit->align_page_size = sysconf(_SC_PAGE_SIZE) - 1;
3602 #endif
3603 jit->globals = (void**) malloc(64 * sizeof(void*));
3604 dasm_setupglobal(jit, jit->globals, 64);
3605 compile_globals(jit, L);
3606 }
3607
3608 /* ffi.C */
3609 {
3610 #ifdef _WIN32 //{
3611 size_t sz = sizeof(HMODULE) * 6;
3612 HMODULE* libs = lua_newuserdata(L, sz);
3613 memset(libs, 0, sz);
3614
3615 /* exe */
3616 GetModuleHandle(NULL);
3617 /* lua dll */
3618 #ifdef LUA_DLL_NAME //{
3619 #define STR2(tok) #tok
3620 #define STR(tok) STR2(tok)
3621 libs[1] = LoadLibraryA(STR(LUA_DLL_NAME));
3622 #undef STR
3623 #undef STR2
3624 #endif //}
3625
3626 /* crt */
3627 #ifdef UNDER_CE //{
3628 libs[2] = LoadLibraryA("coredll.dll");
3629 #else //}{
3630 GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (char*) &_fmode, &libs[2]);
3631 libs[3] = LoadLibraryA("kernel32.dll");
3632 libs[4] = LoadLibraryA("user32.dll");
3633 libs[5] = LoadLibraryA("gdi32.dll");
3634 #endif //}
3635
3636 jit->lua_dll = libs[1];
3637 jit->kernel32_dll = libs[3];
3638
3639 #else /* !_WIN32 */ //}{
3640 size_t sz = sizeof(void*) * 5;
3641 void** libs = lua_newuserdata(L, sz);
3642 memset(libs, 0, sz);
3643
3644 libs[0] = LoadLibraryA(NULL); /* exe */
3645 libs[1] = LoadLibraryA("libc.so");
3646 #ifdef __GNUC__ //{
3647 libs[2] = LoadLibraryA("libgcc.so");
3648 #endif //}
3649 libs[3] = LoadLibraryA("libm.so");
3650 libs[4] = LoadLibraryA("libdl.so");
3651 #endif //}
3652
3653 lua_newtable(L);
3654 lua_setuservalue(L, -2);
3655
3656 push_upval(L, &cmodule_mt_key);
3657 lua_setmetatable(L, -2);
3658
3659 lua_setfield(L, 1, "C");
3660 }
3661
3662 /* setup builtin types */
3663 {
3664 complex_double* pc;
3665 struct {char ch; uint16_t v;} a16;
3666 struct {char ch; uint32_t v;} a32;
3667 struct {char ch; uint64_t v;} a64;
3668 struct {char ch; float v;} af;
3669 struct {char ch; double v;} ad;
3670 #ifdef HAVE_LONG_DOUBLE
3671 struct {char ch; long double v;} ald;
3672 #endif
3673 struct {char ch; uintptr_t v;} aptr;
3674 struct ctype ct;
3675 struct {char ch; complex_float v;} cf;
3676 struct {char ch; complex_double v;} cd;
3677 #if defined HAVE_LONG_DOUBLE && defined HAVE_COMPLEX
3678 struct {char ch; complex long double v;} cld;
3679 #endif
3680
3681 push_builtin(L, &ct, "void", VOID_TYPE, 0, 0, 0);
3682 push_builtin(L, &ct, "bool", BOOL_TYPE, sizeof(_Bool), sizeof(_Bool) -1, 1);
3683 push_builtin(L, &ct, "uint8_t", INT8_TYPE, sizeof(uint8_t), 0, 1);
3684 push_builtin(L, &ct, "int8_t", INT8_TYPE, sizeof(int8_t), 0, 0);
3685 push_builtin(L, &ct, "uint16_t", INT16_TYPE, sizeof(uint16_t), ALIGNOF(a16), 1);
3686 push_builtin(L, &ct, "int16_t", INT16_TYPE, sizeof(int16_t), ALIGNOF(a16), 0);
3687 push_builtin(L, &ct, "uint32_t", INT32_TYPE, sizeof(uint32_t), ALIGNOF(a32), 1);
3688 push_builtin(L, &ct, "int32_t", INT32_TYPE, sizeof(int32_t), ALIGNOF(a32), 0);
3689 push_builtin(L, &ct, "uint64_t", INT64_TYPE, sizeof(uint64_t), ALIGNOF(a64), 1);
3690 push_builtin(L, &ct, "int64_t", INT64_TYPE, sizeof(int64_t), ALIGNOF(a64), 0);
3691 push_builtin(L, &ct, "float", FLOAT_TYPE, sizeof(float), ALIGNOF(af), 0);
3692 push_builtin(L, &ct, "double", DOUBLE_TYPE, sizeof(double), ALIGNOF(ad), 0);
3693 #ifdef HAVE_LONG_DOUBLE
3694 push_builtin(L, &ct, "long double", LONG_DOUBLE_TYPE, sizeof(long double), ALIGNOF(ald), 0);
3695 #else
3696 push_builtin_undef(L, &ct, "long double", LONG_DOUBLE_TYPE);
3697 #endif
3698 push_builtin(L, &ct, "uintptr_t", INTPTR_TYPE, sizeof(uintptr_t), ALIGNOF(aptr), 1);
3699 push_builtin(L, &ct, "intptr_t", INTPTR_TYPE, sizeof(uintptr_t), ALIGNOF(aptr), 0);
3700 push_builtin(L, &ct, "complex float", COMPLEX_FLOAT_TYPE, sizeof(complex_float), ALIGNOF(cf), 0);
3701 push_builtin(L, &ct, "complex double", COMPLEX_DOUBLE_TYPE, sizeof(complex_double), ALIGNOF(cd), 0);
3702 #if defined HAVE_LONG_DOUBLE && defined HAVE_COMPLEX
3703 push_builtin(L, &ct, "complex long double", COMPLEX_LONG_DOUBLE_TYPE, sizeof(complex long double), ALIGNOF(cld), 0);
3704 #else
3705 push_builtin_undef(L, &ct, "complex long double", COMPLEX_LONG_DOUBLE_TYPE);
3706 #endif
3707
3708 /* add NULL and i constants */
3709 push_upval(L, &constants_key);
3710
3711 memset(&ct, 0, sizeof(ct));
3712 ct.type = VOID_TYPE;
3713 ct.is_defined = 1;
3714 ct.pointers = 1;
3715 ct.is_null = 1;
3716
3717 /* add ffi.C.NULL */
3718 push_cdata(L, 0, &ct);
3719 lua_setfield(L, -2, "NULL");
3720
3721 /* add ffi.NULL */
3722 push_cdata(L, 0, &ct);
3723 lua_setfield(L, 1, "NULL");
3724
3725 memset(&ct, 0, sizeof(ct));
3726 ct.type = COMPLEX_DOUBLE_TYPE;
3727 ct.is_defined = 1;
3728 ct.base_size = sizeof(complex_double);
3729 pc = (complex_double*) push_cdata(L, 0, &ct);
3730 #ifdef HAVE_COMPLEX
3731 *pc = 1i;
3732 #else
3733 pc->real = 0;
3734 pc->imag = 1;
3735 #endif
3736 lua_setfield(L, -2, "i");
3737
3738 lua_pop(L, 1); /* constants */
3739 }
3740
3741 assert(lua_gettop(L) == 1);
3742
3743 /* setup builtin typedefs */
3744 {
3745 add_typedef(L, "bool", "_Bool");
3746
3747 if (sizeof(uint32_t) == sizeof(size_t)) {
3748 add_typedef(L, "uint32_t", "size_t");
3749 add_typedef(L, "int32_t", "ssize_t");
3750 } else if (sizeof(uint64_t) == sizeof(size_t)) {
3751 add_typedef(L, "uint64_t", "size_t");
3752 add_typedef(L, "int64_t", "ssize_t");
3753 }
3754
3755 if (sizeof(int32_t) == sizeof(intptr_t)) {
3756 add_typedef(L, "int32_t", "intptr_t");
3757 add_typedef(L, "int32_t", "ptrdiff_t");
3758 } else if (sizeof(int64_t) == sizeof(intptr_t)) {
3759 add_typedef(L, "int64_t", "intptr_t");
3760 add_typedef(L, "int64_t", "ptrdiff_t");
3761 }
3762
3763 if (sizeof(uint8_t) == sizeof(wchar_t)) {
3764 add_typedef(L, "uint8_t", "wchar_t");
3765 } else if (sizeof(uint16_t) == sizeof(wchar_t)) {
3766 add_typedef(L, "uint16_t", "wchar_t");
3767 } else if (sizeof(uint32_t) == sizeof(wchar_t)) {
3768 add_typedef(L, "uint32_t", "wchar_t");
3769 }
3770
3771 if (sizeof(va_list) == sizeof(char*)) {
3772 add_typedef(L, "char*", "va_list");
3773 } else {
3774 struct {char ch; va_list v;} av;
3775 lua_pushfstring(L, "struct {char data[%d] __attribute__((align(%d)));}", (int) sizeof(va_list), (int) ALIGNOF(av) + 1);
3776 add_typedef(L, lua_tostring(L, -1), "va_list");
3777 lua_pop(L, 1);
3778 }
3779
3780 add_typedef(L, "va_list", "__builtin_va_list");
3781 add_typedef(L, "va_list", "__gnuc_va_list");
3782 }
3783
3784 assert(lua_gettop(L) == 1);
3785
3786 /* setup ABI params table */
3787 push_upval(L, &abi_key);
3788
3789 #if defined ARCH_X86 || defined ARCH_ARM
3790 lua_pushboolean(L, 1);
3791 lua_setfield(L, -2, "32bit");
3792 #elif defined ARCH_X64 || defined ARCH_PPC64 || defined ARCH_ARM64
3793 lua_pushboolean(L, 1);
3794 lua_setfield(L, -2, "64bit");
3795 #else
3796 # define UNSUPPORTED_ARCH /*error*/
3797 # pragma message("luaffi: UNSUPPORTED_ARCH")
3798 #endif
3799
3800 #if defined ARCH_X86 || defined ARCH_X64 || defined ARCH_ARM || defined ARCH_PPC64 || defined ARCH_ARM64
3801 lua_pushboolean(L, 1);
3802 lua_setfield(L, -2, "le");
3803 #else
3804 # define UNSUPPORTED_ARCH /*error*/
3805 # pragma message("luaffi: UNSUPPORTED_ARCH")
3806 #endif
3807
3808 #if defined ARCH_X86 || defined ARCH_X64 || defined ARCH_PPC64 || defined ARCH_ARM64
3809 lua_pushboolean(L, 1);
3810 lua_setfield(L, -2, "fpu");
3811 #elif defined ARCH_ARM
3812 lua_pushboolean(L, 1);
3813 lua_setfield(L, -2, "softfp");
3814 #else
3815 # define UNSUPPORTED_ARCH /*error*/
3816 # pragma message("luaffi: UNSUPPORTED_ARCH")
3817 #endif
3818 lua_pop(L, 1); /* abi tbl */
3819
3820
3821 /* GC table - shouldn't pin cdata values */
3822 push_upval(L, &gc_key);
3823 lua_newtable(L);
3824 lua_pushliteral(L, "k");
3825 lua_setfield(L, -2, "__mode");
3826 lua_setmetatable(L, -2);
3827 lua_pop(L, 1); /* gc table */
3828
3829 /* ffi.os */
3830 #if defined OS_CE
3831 lua_pushliteral(L, "WindowsCE");
3832 #elif defined OS_WIN
3833 lua_pushliteral(L, "Windows");
3834 #elif defined OS_OSX
3835 lua_pushliteral(L, "OSX");
3836 #elif defined OS_LINUX
3837 lua_pushliteral(L, "Linux");
3838 #elif defined OS_BSD
3839 lua_pushliteral(L, "BSD");
3840 #elif defined OS_POSIX
3841 lua_pushliteral(L, "POSIX");
3842 #else
3843 lua_pushliteral(L, "Other");
3844 #endif
3845 lua_setfield(L, 1, "os");
3846
3847
3848 /* ffi.arch */
3849 #if defined ARCH_X86
3850 lua_pushliteral(L, "x86");
3851 #elif defined ARCH_X64
3852 lua_pushliteral(L, "x64");
3853 #elif defined ARCH_ARM
3854 lua_pushliteral(L, "arm");
3855 #elif defined ARCH_ARM64
3856 lua_pushliteral(L, "arm64");
3857 #elif defined ARCH_PPC64
3858 lua_pushliteral(L, "ppc64");
3859 #else
3860 # define UNSUPPORTED_ARCH /* error */
3861 # pragma message("luaffi: UNSUPPORTED_ARCH")
3862 #endif
3863 lua_setfield(L, 1, "arch");
3864
3865 assert(lua_gettop(L) == 1);
3866
3867 return 0;
3868 }
3869
3870 static void setup_mt(lua_State* L, const luaL_Reg* mt, int upvals)
3871 {
3872 lua_pushboolean(L, 1);
3873 lua_setfield(L, -upvals-2, "__metatable");
3874 luaL_setfuncs(L, mt, upvals);
3875 }
3876
3877 #if defined FFI_ENABLE_LUATEX_INTERFACE
3878 int luaopen_ffi(lua_State* L)
3879 {
3880 lua_settop(L, 0);
3881
3882 lua_newtable(L);
3883 set_upval(L, &niluv_key);
3884
3885 lua_newtable(L);
3886 setup_mt(L, ctype_mt, 0);
3887 set_upval(L, &ctype_mt_key);
3888
3889 lua_newtable(L);
3890 set_upval(L, &callbacks_key);
3891
3892 lua_newtable(L);
3893 set_upval(L, &gc_key);
3894
3895 lua_newtable(L);
3896 push_upval(L, &callbacks_key);
3897 push_upval(L, &gc_key);
3898 setup_mt(L, cdata_mt, 2);
3899 set_upval(L, &cdata_mt_key);
3900
3901 lua_newtable(L);
3902 setup_mt(L, callback_mt, 0);
3903 set_upval(L, &callback_mt_key);
3904
3905 lua_newtable(L);
3906 setup_mt(L, cmodule_mt, 0);
3907 set_upval(L, &cmodule_mt_key);
3908
3909 memset(lua_newuserdata(L, sizeof(struct jit)), 0, sizeof(struct jit));
3910 lua_newtable(L);
3911 setup_mt(L, jit_mt, 0);
3912 lua_setmetatable(L, -2);
3913 set_upval(L, &jit_key);
3914
3915 lua_newtable(L);
3916 set_upval(L, &constants_key);
3917
3918 lua_newtable(L);
3919 set_upval(L, &types_key);
3920
3921 lua_newtable(L);
3922 set_upval(L, &functions_key);
3923
3924 lua_newtable(L);
3925 set_upval(L, &asmname_key);
3926
3927 lua_newtable(L);
3928 set_upval(L, &abi_key);
3929
3930 lua_pushinteger(L, 1);
3931 set_upval(L, &next_unnamed_key);
3932
3933 assert(lua_gettop(L) == 0);
3934
3935 /* ffi table */
3936 lua_newtable(L);
3937 luaL_setfuncs(L, ffi_reg, 0);
3938
3939 /* setup_upvals(ffi tbl) */
3940 lua_pushcfunction(L, &setup_upvals);
3941 lua_pushvalue(L, 1);
3942 lua_call(L, 1, 0);
3943
3944 assert(lua_gettop(L) == 1);
3945
3946 lua_getglobal(L, "tonumber");
3947 lua_pushcclosure(L, &ffi_number, 1);
3948 lua_pushvalue(L, -1);
3949 lua_setglobal(L, "tonumber");
3950 lua_setfield(L, -2, "number"); /* ffi.number */
3951
3952 lua_getglobal(L, "type");
3953 lua_pushcclosure(L, &ffi_type, 1);
3954 lua_pushvalue(L, -1);
3955 lua_setglobal(L, "type");
3956 lua_setfield(L, -2, "type"); /* ffi.type */
3957 return 1;
3958 }
3959 #else
3960 /* This is a stub for OS/ARCH that at this moment don't support ffi */
3961 int luaopen_ffi(lua_State *L)
3962 {
3963 int k ;
3964
3965 k = luaL_dostring(L, "local info = [[\n"
3966 "The ffi module is available for:\n"
3967 "\n"
3968 " archictures : ARCH_X86, ARCH_X64 and ARM_64,\n"
3969 " operating systems : OS_CE, OS_WIN, OS_LINUX, OS_BSD and OS_POSIX\n"
3970 "\n"
3971 "The ARM 32bit processor is currently not supported. There are subtle\n"
3972 "differences between this module and the one in luajitTeX \n"
3973 "and we hope to be in sync around TeXLive 2025.\n"
3974 "Different OS can have different interfaces,\n"
3975 "for instance OS_WIN has not 'complex.h'. If you want portable\n"
3976 "code, stick to the most common concepts.\n"
3977 "]]\n"
3978 "\n"
3979 "local function stub()\n"
3980 " texio.write_nl(info)\n"
3981 "end\n"
3982 "\n"
3983 "return {\n"
3984 " fill = stub,\n"
3985 " cast = stub,\n"
3986 " offsetof = stub,\n"
3987 " copy = stub,\n"
3988 " string = stub,\n"
3989 " abi = stub,\n"
3990 " cdef = stub,\n"
3991 " typeof = stub,\n"
3992 " sizeof = stub,\n"
3993 " type = stub,\n"
3994 " number = stub,\n"
3995 " gc = stub,\n"
3996 " metatype = stub,\n"
3997 " errno = stub,\n"
3998 " debug = stub,\n"
3999 " os = '' ,\n"
4000 " arch = '' ,\n"
4001 " NULL = nil ,\n"
4002 " alignof = stub,\n"
4003 " new = stub,\n"
4004 " u64 = stub,\n"
4005 " i64 = stub,\n"
4006 " istype = stub,\n"
4007 " load = stub,\n"
4008 " C = nil ,\n"
4009 "}");
4010
4011 return k==0 ? 1 : k;
4012 }
4013 #endif