Debian Codegraph @

texk/web2c/luatexdir/luaffi/ffi.c.orig

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 = 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 void* to;
1424 struct ctype ct;
1425 char* data;
1426 ptrdiff_t off;
1427
1428 lua_settop(L, 2);
1429 check_ctype(L, 1, &ct);
1430 assert(lua_gettop(L) == 3);
1431
1432 if (!push_user_mt(L, -1, &ct)) {
1433 goto err;
1434 }
1435 lua_pushliteral(L, "__index");
1436 lua_rawget(L, -2);
1437
1438 if (lua_isnil(L, -1)) {
1439 goto err;
1440 }
1441
1442 if (lua_istable(L, -1)) {
1443 lua_pushvalue(L, 2);
1444 lua_rawget(L, -2);
1445 if (lua_isnil(L, -1))
1446 goto err;
1447 return 1;
1448 }
1449
1450 lua_insert(L, 1);
1451 lua_settop(L, 3);
1452 lua_call(L, 2, LUA_MULTRET);
1453 return lua_gettop(L);
1454
1455 err:
1456 push_type_name(L, 3, &ct);
1457 return luaL_error(L, "type %s has no member %s", lua_tostring(L, -1), lua_tostring(L, 2));
1458 }
1459
1460 static int ffi_sizeof(lua_State* L)
1461 {
1462 struct ctype ct;
1463 check_ctype(L, 1, &ct);
1464 get_variable_array_size(L, 2, &ct);
1465 lua_pushinteger(L, ctype_size(L, &ct));
1466 return 1;
1467 }
1468
1469 static int ffi_alignof(lua_State* L)
1470 {
1471 struct ctype ct, mt;
1472 lua_settop(L, 2);
1473 check_ctype(L, 1, &ct);
1474 //debug_print_type(&ct);
1475
1476 /* if no member is specified then we return the alignment of the type */
1477 if (lua_isnil(L, 2)) {
1478 lua_pushinteger(L, ct.align_mask + 1);
1479 return 1;
1480 }
1481
1482 /* get the alignment of the member */
1483 lua_pushvalue(L, 2);
1484 if (get_member(L, -2, &ct, &mt) < 0) {
1485 push_type_name(L, 3, &ct);
1486 return luaL_error(L, "type %s has no member %s", lua_tostring(L, -1), lua_tostring(L, 2));
1487 }
1488
1489 lua_pushinteger(L, mt.align_mask + 1);
1490 return 1;
1491 }
1492
1493 static int ffi_offsetof(lua_State* L)
1494 {
1495 ptrdiff_t off;
1496 struct ctype ct, mt;
1497 lua_settop(L, 2);
1498 check_ctype(L, 1, &ct);
1499
1500 lua_pushvalue(L, 2);
1501 off = get_member(L, -2, &ct, &mt); /* this replaces the member key at -1 with the mbr usr value */
1502 if (off < 0) {
1503 push_type_name(L, 3, &ct);
1504 return luaL_error(L, "type %s has no member %s", lua_tostring(L, -1), lua_tostring(L, 2));
1505 }
1506
1507 lua_pushinteger(L, off);
1508
1509 if (!mt.is_bitfield) {
1510 return 1;
1511 }
1512
1513 lua_pushinteger(L, mt.bit_offset);
1514 lua_pushinteger(L, mt.bit_size);
1515 return 3;
1516 }
1517
1518 static int type_is_same_incl_unsigned(lua_State* L, int usr1, int usr2, const struct ctype* t1, const struct ctype* t2)
1519 {
1520 if ((t1->type != t2->type) ||
1521 (t1->is_unsigned != t2->is_unsigned)) {
1522 return 0;
1523 }
1524
1525 #if LUA_VERSION_NUM == 501
1526 if (lua_isnil(L, usr1) != lua_isnil(L, usr2)) {
1527 int ret;
1528 usr1 = lua_absindex(L, usr1);
1529 usr2 = lua_absindex(L, usr2);
1530 push_upval(L, &niluv_key);
1531
1532 ret = lua_rawequal(L, usr1, -1)
1533 || lua_rawequal(L, usr2, -1);
1534
1535 lua_pop(L, 1);
1536
1537 if (ret) {
1538 return 1;
1539 }
1540 }
1541 #endif
1542
1543 return lua_rawequal(L, usr1, usr2);
1544 }
1545
1546 static int ffi_istype(lua_State* L)
1547 {
1548 struct ctype tt, ft;
1549 check_ctype(L, 1, &tt);
1550 to_cdata(L, 2, &ft);
1551
1552 if (ft.type == INVALID_TYPE) {
1553 goto fail;
1554 }
1555
1556 //if (!is_same_type(L, 3, 4, &tt, &ft))
1557 if (!type_is_same_incl_unsigned(L, 3, 4, &tt, &ft)) {
1558 goto fail;
1559 }
1560
1561 if (tt.pointers != ft.pointers) {
1562 goto fail;
1563 }
1564
1565 if (tt.is_array != ft.is_array) {
1566 goto fail;
1567 }
1568
1569 if (tt.is_array && tt.array_size != ft.array_size) {
1570 goto fail;
1571 }
1572
1573 if (tt.calling_convention != ft.calling_convention) {
1574 goto fail;
1575 }
1576
1577 lua_pushboolean(L, 1);
1578 return 1;
1579
1580 fail:
1581 lua_pushboolean(L, 0);
1582 return 1;
1583 }
1584
1585 static int cdata_gc(lua_State* L)
1586 {
1587 struct ctype ct;
1588 check_cdata(L, 1, &ct);
1589 lua_settop(L, 1);
1590
1591 /* call the gc func if there is any registered */
1592 lua_pushvalue(L, 1);
1593 lua_rawget(L, lua_upvalueindex(2));
1594 if (!lua_isnil(L, -1)) {
1595 lua_pushvalue(L, 1);
1596 lua_pcall(L, 1, 0, 0);
1597 }
1598
1599 /* unset the closure */
1600 lua_pushvalue(L, 1);
1601 lua_pushnil(L);
1602 lua_rawset(L, lua_upvalueindex(1));
1603
1604 return 0;
1605 }
1606
1607 static int callback_free(lua_State* L)
1608 {
1609 cfunction* p = (cfunction*) lua_touserdata(L, 1);
1610 // FIXME: temporarily disabled to prevent SIGTRAP on exit
1611 // free_code(get_jit(L), L, *p);
1612 return 0;
1613 }
1614
1615 static int cdata_free(lua_State* L)
1616 {
1617 struct ctype ct;
1618 cfunction* p = (cfunction*) check_cdata(L, 1, &ct);
1619 lua_settop(L, 1);
1620
1621 /* unset the closure */
1622 lua_pushvalue(L, 1);
1623 lua_pushnil(L);
1624 lua_rawset(L, lua_upvalueindex(1));
1625
1626 if (ct.is_jitted) {
1627 free_code(get_jit(L), L, *p);
1628 *p = NULL;
1629 }
1630
1631 return 0;
1632 }
1633
1634 static int cdata_set(lua_State* L)
1635 {
1636 struct ctype ct;
1637 cfunction* p = (cfunction*) check_cdata(L, 1, &ct);
1638 luaL_checktype(L, 2, LUA_TFUNCTION);
1639
1640 if (!ct.is_jitted) {
1641 luaL_error(L, "can't set the function for a non-lua callback");
1642 }
1643
1644 if (*p == NULL) {
1645 luaL_error(L, "can't set the function for a free'd callback");
1646 }
1647
1648 push_func_ref(L, *p);
1649 lua_pushvalue(L, 2);
1650 lua_rawseti(L, -2, CALLBACK_FUNC_USR_IDX);
1651
1652 /* remove the closure for this callback as it embeds the function pointer
1653 * value */
1654 lua_pushvalue(L, 1);
1655 lua_pushboolean(L, 1);
1656 lua_rawset(L, lua_upvalueindex(1));
1657
1658 return 0;
1659 }
1660
1661 static int cdata_call(lua_State* L)
1662 {
1663 struct ctype ct;
1664 int top = lua_gettop(L);
1665 cfunction* p = (cfunction*) check_cdata(L, 1, &ct);
1666
1667 if (push_user_mt(L, -1, &ct)) {
1668 lua_pushliteral(L, "__call");
1669 lua_rawget(L, -2);
1670
1671 if (!lua_isnil(L, -1)) {
1672 lua_insert(L, 1);
1673 lua_pop(L, 2); /* ct_usr, user_mt */
1674 lua_call(L, lua_gettop(L) - 1, LUA_MULTRET);
1675 return lua_gettop(L);
1676 }
1677 }
1678 if (ct.pointers || ct.type != FUNCTION_PTR_TYPE) {
1679 return luaL_error(L, "only function callbacks are callable");
1680 }
1681
1682 lua_pushvalue(L, 1);
1683 lua_rawget(L, lua_upvalueindex(1));
1684
1685 if (!lua_isfunction(L, -1)) {
1686 lua_pop(L, 1);
1687 compile_function(L, *p, -1, &ct);
1688 #ifdef ARCH_ARM64
1689 /* Ref: https://developer.arm.com/documentation/ihi0053/latest
1690 * Generates an ISB (instruction synchronization barrier) instruction or
1691 * equivalent CP15 instruction. This instruction flushes the processor
1692 * pipeline fetch buffers, so that following instructions are fetched
1693 * from cache or memory. An ISB is needed after some system maintenance
1694 * operations. An ISB is also needed before transferring control to code
1695 * that has been loaded or modified in memory, for example by an overlay
1696 * mechanism or just-in-time code generator. (Note that if instruction
1697 * and data caches are separate, privileged cache maintenance operations
1698 * would be needed in order to unify the caches.) The only supported
1699 * argument for the __isb() intrinsic is 15, corresponding to the SY
1700 * (full system) scope of the ISB instruction.
1701 */
1702 #ifdef __clang__
1703 __isb(15);
1704 #elif __GNUC__
1705 asm("isb 15");
1706 #endif
1707 #endif
1708
1709 assert(lua_gettop(L) == top + 2); /* uv, closure */
1710
1711 /* closures[func] = closure */
1712 lua_pushvalue(L, 1);
1713 lua_pushvalue(L, -2);
1714 lua_rawset(L, lua_upvalueindex(1));
1715
1716 lua_replace(L, 1);
1717 } else {
1718 lua_replace(L, 1);
1719 }
1720
1721 lua_pop(L, 1); /* uv */
1722 assert(lua_gettop(L) == top);
1723
1724 lua_call(L, lua_gettop(L) - 1, LUA_MULTRET);
1725 return lua_gettop(L);
1726 }
1727
1728 static int user_mt_key;
1729
1730 static int ffi_metatype(lua_State* L)
1731 {
1732 struct ctype ct;
1733 lua_settop(L, 2);
1734
1735 check_ctype(L, 1, &ct);
1736 if (lua_type(L, 2) != LUA_TTABLE && lua_type(L, 2) != LUA_TNIL) {
1737 return luaL_argerror(L, 2, "metatable must be a table or nil");
1738 }
1739
1740 lua_pushlightuserdata(L, &user_mt_key);
1741 lua_rawget(L, 3);
1742 if (!lua_isnil(L, -1)) {
1743 push_type_name(L, 3, &ct);
1744 return luaL_error(L, "type %s already has a user metatable", lua_tostring(L, -1));
1745 }
1746 lua_pop(L, 1);
1747
1748 lua_pushlightuserdata(L, &user_mt_key);
1749 lua_pushvalue(L, 2);
1750 lua_rawset(L, 3); /* user[user_mt_key] = mt */
1751
1752 /* return the passed in ctype */
1753 push_ctype(L, 3, &ct);
1754 return 1;
1755 }
1756
1757 /* push_user_mt returns 1 if the type has a user metatable and pushes it onto
1758 * the stack, otherwise it returns 0 and pushes nothing */
1759 int push_user_mt(lua_State* L, int ct_usr, const struct ctype* ct)
1760 {
1761 if (ct->type != STRUCT_TYPE && ct->type != UNION_TYPE && !IS_COMPLEX(ct->type)) {
1762 return 0;
1763 }
1764 if (!lua_istable(L, ct_usr)) {
1765 return 0;
1766 }
1767
1768 ct_usr = lua_absindex(L, ct_usr);
1769 lua_pushlightuserdata(L, &user_mt_key);
1770 lua_rawget(L, ct_usr);
1771
1772 if (lua_isnil(L, -1)) {
1773 lua_pop(L, 1);
1774 return 0;
1775 }
1776 return 1;
1777 }
1778
1779 static int ffi_gc(lua_State* L)
1780 {
1781 struct ctype ct;
1782 lua_settop(L, 2);
1783 check_cdata(L, 1, &ct);
1784
1785 push_upval(L, &gc_key);
1786 lua_pushvalue(L, 1);
1787 lua_pushvalue(L, 2);
1788 lua_rawset(L, -3);
1789
1790 /* return the cdata back */
1791 lua_settop(L, 1);
1792 return 1;
1793 }
1794
1795 /* lookup_cdata_index returns the offset of the found type and user value on
1796 * the stack if valid. Otherwise returns -ve and doesn't touch the stack.
1797 */
1798 static ptrdiff_t lookup_cdata_index(lua_State* L, int idx, int ct_usr, struct ctype* ct)
1799 {
1800 struct ctype mt;
1801 ptrdiff_t off;
1802
1803 ct_usr = lua_absindex(L, ct_usr);
1804 int type = lua_type(L, idx);
1805
1806 switch (type) {
1807 case LUA_TNUMBER:
1808 case LUA_TUSERDATA:
1809 /* possibilities are array, pointer */
1810
1811 if (!ct->pointers || is_void_ptr(ct)) {
1812 return -1;
1813 }
1814
1815 // unbox cdata
1816 if (type == LUA_TUSERDATA) {
1817 if (!cdata_tointeger(L, idx, &off)) {
1818 return -1;
1819 }
1820 } else {
1821 off = lua_tointeger(L, idx);
1822 }
1823
1824 ct->is_array = 0;
1825 ct->pointers--;
1826 ct->const_mask >>= 1;
1827 ct->is_reference = 0;
1828
1829 lua_pushvalue(L, ct_usr);
1830
1831 return (ct->pointers ? sizeof(void*) : ct->base_size) * off;
1832
1833 case LUA_TSTRING:
1834 /* possibilities are struct/union, pointer to struct/union */
1835
1836 if ((ct->type != STRUCT_TYPE && ct->type != UNION_TYPE) || ct->is_array || ct->pointers > 1) {
1837 return -1;
1838 }
1839
1840 lua_pushvalue(L, idx);
1841 off = get_member(L, ct_usr, ct, &mt);
1842 if (off < 0) {
1843 return -1;
1844 }
1845
1846 *ct = mt;
1847 return off;
1848
1849 default:
1850 return -1;
1851 }
1852 }
1853
1854 static int cdata_newindex(lua_State* L)
1855 {
1856 struct ctype tt;
1857 char* to;
1858 ptrdiff_t off;
1859
1860 lua_settop(L, 3);
1861
1862 to = (char*) check_cdata(L, 1, &tt);
1863 off = lookup_cdata_index(L, 2, -1, &tt);
1864
1865 if (off < 0) {
1866 if (!push_user_mt(L, -1, &tt)) {
1867 goto err;
1868 }
1869
1870 lua_pushliteral(L, "__newindex");
1871 lua_rawget(L, -2);
1872
1873 if (lua_isnil(L, -1)) {
1874 goto err;
1875 }
1876
1877 if (tt.const_mask & 0xFF) {
1878 return luaL_error(L, "can't set const data");
1879 }
1880
1881 if (lua_istable(L, -1)) {
1882 lua_pushvalue(L, 2);
1883 lua_pushvalue(L, 3);
1884 lua_settable(L, -3);
1885 return 1;
1886 }
1887
1888 lua_insert(L, 1);
1889 lua_settop(L, 4);
1890 lua_call(L, 3, LUA_MULTRET);
1891 return lua_gettop(L);
1892 }
1893
1894 if (tt.const_mask & 1) {
1895 return luaL_error(L, "can't set const data");
1896 }
1897
1898 set_value(L, 3, to + off, -1, &tt, 1);
1899 return 0;
1900
1901 err:
1902 push_type_name(L, 4, &tt);
1903 return luaL_error(L, "type %s has no member %s", lua_tostring(L, -1), lua_tostring(L, 2));
1904 }
1905
1906 static int cdata_index(lua_State* L)
1907 {
1908 void* to;
1909 struct ctype ct;
1910 char* data;
1911 ptrdiff_t off;
1912
1913 lua_settop(L, 2);
1914 data = (char*) check_cdata(L, 1, &ct);
1915 assert(lua_gettop(L) == 3);
1916
1917 if (!ct.pointers) {
1918 switch (ct.type) {
1919 case FUNCTION_PTR_TYPE:
1920 /* Callbacks use the same metatable as standard cdata values, but have set
1921 * and free members. So instead of mt.__index = mt, we do the equiv here. */
1922 lua_getmetatable(L, 1);
1923 lua_pushvalue(L, 2);
1924 lua_rawget(L, -2);
1925 return 1;
1926
1927 /* This provides the .re and .im virtual members */
1928 case COMPLEX_DOUBLE_TYPE:
1929 case COMPLEX_FLOAT_TYPE:
1930 if (!lua_isstring(L, 2)) {
1931 luaL_error(L, "invalid member for complex number");
1932
1933 } else if (strcmp(lua_tostring(L, 2), "re") == 0) {
1934 lua_pushnumber(L, ct.type == COMPLEX_DOUBLE_TYPE ? creal(*(complex_double*) data) : crealf(*(complex_float*) data));
1935
1936 } else if (strcmp(lua_tostring(L, 2), "im") == 0) {
1937 lua_pushnumber(L, ct.type == COMPLEX_DOUBLE_TYPE ? cimag(*(complex_double*) data) : cimagf(*(complex_float*) data));
1938
1939 } else {
1940 luaL_error(L, "invalid member for complex number");
1941 }
1942 return 1;
1943 }
1944 }
1945
1946 off = lookup_cdata_index(L, 2, -1, &ct);
1947
1948 if (off < 0) {
1949 assert(lua_gettop(L) == 3);
1950 if (!push_user_mt(L, -1, &ct)) {
1951 goto err;
1952 }
1953
1954 lua_pushliteral(L, "__index");
1955 lua_rawget(L, -2);
1956
1957 if (lua_isnil(L, -1)) {
1958 goto err;
1959 }
1960
1961 if (lua_istable(L, -1)) {
1962 lua_pushvalue(L, 2);
1963 lua_gettable(L, -2);
1964 if (lua_isnil(L, -1))
1965 goto err;
1966 return 1;
1967 }
1968
1969 lua_insert(L, 1);
1970 lua_settop(L, 3);
1971 lua_call(L, 2, LUA_MULTRET);
1972 return lua_gettop(L);
1973
1974 err:
1975 push_type_name(L, 3, &ct);
1976 return luaL_error(L, "type %s has no member %s", lua_tostring(L, -1), lua_tostring(L, 2));
1977 }
1978
1979 assert(lua_gettop(L) == 4); /* ct, key, ct_usr, mbr_usr */
1980 data += off;
1981
1982 if (ct.is_array) {
1983 /* push a reference to the array */
1984 ct.is_reference = 1;
1985 to = push_cdata(L, -1, &ct);
1986 *(void**) to = data;
1987 return 1;
1988
1989 } else if (ct.is_bitfield) {
1990
1991 if (ct.type == INT64_TYPE) {
1992 struct ctype rt;
1993 uint64_t val = *(uint64_t*) data;
1994 val >>= ct.bit_offset;
1995 val &= (UINT64_C(1) << ct.bit_size) - 1;
1996
1997 memset(&rt, 0, sizeof(rt));
1998 rt.base_size = 8;
1999 rt.type = INT64_TYPE;
2000 rt.is_unsigned = 1;
2001 rt.is_defined = 1;
2002
2003 to = push_cdata(L, 0, &rt);
2004 *(uint64_t*) to = val;
2005
2006 return 1;
2007
2008 } else if (ct.type == BOOL_TYPE) {
2009 uint64_t val = *(uint8_t*) data;
2010 lua_pushboolean(L, (int) (val & (UINT64_C(1) << ct.bit_offset)));
2011 return 1;
2012
2013 } else {
2014 //uint64_t val = *(uint64_t*) data; //Trial fix
2015 uint64_t val = 0;
2016 switch (ct.type) {
2017 case INT8_TYPE: {
2018 uint8_t ui;
2019 memcpy(&ui, data, sizeof(uint8_t));
2020 val = ui;
2021 //val = *(uint8_t*)data;
2022 break;
2023 }
2024 case INT16_TYPE: {
2025 uint16_t ui;
2026 memcpy(&ui, data, sizeof(uint16_t));
2027 val = ui;
2028 //val = *(uint16_t*)data;
2029 break;
2030 }
2031 case INT32_TYPE: {
2032 uint32_t ui;
2033 memcpy(&ui, data, sizeof(uint32_t));
2034 val = ui;
2035 //val = *(uint32_t*)data;
2036 break;
2037 }
2038 case INT64_TYPE:
2039 default:
2040 return luaL_error(L, "Inavaid data type");
2041 }
2042 val >>= ct.bit_offset;
2043 val &= (UINT64_C(1) << ct.bit_size) - 1;
2044 lua_pushinteger(L, val);
2045 return 1;
2046 }
2047
2048 } else if (ct.pointers) {
2049 #ifndef ALLOW_MISALIGNED_ACCESS
2050 union {
2051 uint8_t c[8];
2052 void* p;
2053 } misalignbuf;
2054
2055 if ((uintptr_t) data & PTR_ALIGN_MASK) {
2056 memcpy(misalignbuf.c, data, sizeof(void*));
2057 data = misalignbuf.c;
2058 }
2059 #endif
2060 to = push_cdata(L, -1, &ct);
2061 *(void**) to = *(void**) data;
2062 return 1;
2063
2064 } else if (ct.type == STRUCT_TYPE || ct.type == UNION_TYPE) {
2065 /* push a reference to the member */
2066 ct.is_reference = 1;
2067 to = push_cdata(L, -1, &ct);
2068 *(void**) to = data;
2069 return 1;
2070
2071 } else if (ct.type == FUNCTION_PTR_TYPE) {
2072 cfunction* pf = (cfunction*) push_cdata(L, -1, &ct);
2073 *pf = *(cfunction*) data;
2074 return 1;
2075
2076 } else {
2077 #ifndef ALLOW_MISALIGNED_ACCESS
2078 union {
2079 uint8_t c[8];
2080 double d;
2081 float f;
2082 uint64_t u64;
2083 } misalignbuf;
2084
2085 assert(ct.base_size <= 8);
2086
2087 if ((uintptr_t) data & (ct.base_size - 1)) {
2088 memcpy(misalignbuf.c, data, ct.base_size);
2089 data = misalignbuf.c;
2090 }
2091 #endif
2092
2093 switch (ct.type) {
2094 case BOOL_TYPE:
2095 lua_pushboolean(L, *(_Bool*) data);
2096 break;
2097 case INT8_TYPE:
2098 lua_pushinteger(L, ct.is_unsigned ? (lua_Integer) *(uint8_t*) data : (lua_Integer) *(int8_t*) data);
2099 break;
2100 case INT16_TYPE:
2101 lua_pushinteger(L, ct.is_unsigned ? (lua_Integer) *(uint16_t*) data : (lua_Integer) *(int16_t*) data);
2102 break;
2103 case ENUM_TYPE:
2104 case INT32_TYPE:
2105 lua_pushinteger(L, ct.is_unsigned ? (lua_Integer) *(uint32_t*) data : (lua_Integer) *(int32_t*) data);
2106 break;
2107 case INT64_TYPE:
2108 to = push_cdata(L, -1, &ct);
2109 *(int64_t*) to = *(int64_t*) data;
2110 break;
2111 case INTPTR_TYPE:
2112 to = push_cdata(L, -1, &ct);
2113 *(intptr_t*) to = *(intptr_t*) data;
2114 break;
2115 case FLOAT_TYPE:
2116 lua_pushnumber(L, *(float*) data);
2117 break;
2118 case DOUBLE_TYPE:
2119 lua_pushnumber(L, *(double*) data);
2120 break;
2121 case COMPLEX_DOUBLE_TYPE:
2122 to = push_cdata(L, -1, &ct);
2123 *(complex_double*) to = *(complex_double*) data;
2124 break;
2125 case COMPLEX_FLOAT_TYPE:
2126 to = push_cdata(L, -1, &ct);
2127 *(complex_float*) to = *(complex_float*) data;
2128 break;
2129 default:
2130 luaL_error(L, "internal error: invalid member type");
2131 }
2132
2133 return 1;
2134 }
2135 }
2136
2137 static complex_double check_complex(lua_State* L, int idx, void* p, struct ctype* ct)
2138 {
2139 if (ct->type == INVALID_TYPE) {
2140 double d = luaL_checknumber(L, idx);
2141 #ifdef HAVE_COMPLEX
2142 return d;
2143 #else
2144 complex_double c;
2145 c.real = d;
2146 c.imag = 0;
2147 return c;
2148 #endif
2149 } else if (ct->type == COMPLEX_DOUBLE_TYPE) {
2150 return *(complex_double*) p;
2151 } else if (ct->type == COMPLEX_FLOAT_TYPE) {
2152 complex_float* f = (complex_float*) p;
2153 #ifdef HAVE_COMPLEX
2154 return *f;
2155 #else
2156 complex_double d;
2157 d.real = f->real;
2158 d.imag = f->imag;
2159 return d;
2160 #endif
2161 } else {
2162 complex_double dummy;
2163 type_error(L, idx, "complex", 0, NULL);
2164 memset(&dummy, 0, sizeof(dummy));
2165 return dummy;
2166 }
2167 }
2168
2169 static int rank(const struct ctype* ct)
2170 {
2171 if (ct->pointers) {
2172 return 5;
2173 }
2174
2175 switch (ct->type) {
2176 case COMPLEX_DOUBLE_TYPE:
2177 return 7;
2178 case COMPLEX_FLOAT_TYPE:
2179 return 6;
2180 case INTPTR_TYPE:
2181 return sizeof(intptr_t) >= sizeof(int64_t) ? 4 : 1;
2182 case INT64_TYPE:
2183 return ct->is_unsigned ? 3 : 2;
2184 case INT32_TYPE:
2185 case INT16_TYPE:
2186 case INT8_TYPE:
2187 return 2;
2188 default:
2189 return 0;
2190 }
2191 }
2192
2193 static void push_complex(lua_State* L, complex_double res, int ct_usr, const struct ctype* ct)
2194 {
2195 if (ct->type == COMPLEX_DOUBLE_TYPE) {
2196 complex_double* p = (complex_double*) push_cdata(L, ct_usr, ct);
2197 *p = res;
2198 } else {
2199 complex_float* p = (complex_float*) push_cdata(L, ct_usr, ct);
2200 #ifdef HAVE_COMPLEX
2201 *p = (complex float) res;
2202 #else
2203 p->real = (float) res.real;
2204 p->imag = (float) res.imag;
2205 #endif
2206 }
2207 }
2208
2209 static void push_number(lua_State* L, int64_t val, int ct_usr, const struct ctype* ct)
2210 {
2211 if ((ct->pointers || ct->type == INTPTR_TYPE) && sizeof(intptr_t) != sizeof(int64_t)) {
2212 intptr_t* p = (intptr_t*) push_cdata(L, ct_usr, ct);
2213 *p = val;
2214 } else {
2215 void* p = (int64_t*) push_cdata(L, ct_usr, ct);
2216 //*p = val;
2217 /* TODO : Will this work for big endian architectures?
2218 * ctype_size returns 64 for all integer types
2219 */
2220 memset(p, 0, ctype_size(L, ct));
2221 switch (ct->type) {
2222 case BOOL_TYPE:
2223 case INT8_TYPE: {
2224 memcpy(p, &val, ctype_size(L, ct));
2225 }
2226 break;
2227 case INT16_TYPE: {
2228 memcpy(p, &val, ctype_size(L, ct));
2229 }
2230 break;
2231 case ENUM_TYPE:
2232 case INT32_TYPE: {
2233 memcpy(p, &val, ctype_size(L, ct));
2234 }
2235 break;
2236 case INT64_TYPE: {
2237 memcpy(p, &val, ctype_size(L, ct));
2238 }
2239 break;
2240 default:
2241 luaL_error(L, "Unsupported type for this operation");
2242 break;
2243 }
2244 }
2245 }
2246
2247 static int call_user_op(lua_State* L, const char* opfield, int idx, int ct_usr, const struct ctype* ct)
2248 {
2249 idx = lua_absindex(L, idx);
2250
2251 if (push_user_mt(L, ct_usr, ct)) {
2252 lua_pushstring(L, opfield);
2253 lua_rawget(L, -2);
2254 if (!lua_isnil(L, -1)) {
2255 int top = lua_gettop(L);
2256 lua_pushvalue(L, idx);
2257 lua_call(L, 1, LUA_MULTRET);
2258 return lua_gettop(L) - top + 1;
2259 }
2260 lua_pop(L, 2);
2261 }
2262 return -1;
2263 }
2264
2265 static int cdata_unm(lua_State* L)
2266 {
2267 struct ctype ct;
2268 void* p;
2269 int64_t val;
2270 int ret;
2271
2272 lua_settop(L, 1);
2273 p = to_cdata(L, 1, &ct);
2274
2275 ret = call_user_op(L, "__unm", 1, 2, &ct);
2276 if (ret >= 0) {
2277 return ret;
2278 }
2279
2280 val = check_intptr(L, 1, p, &ct);
2281
2282 if (ct.pointers) {
2283 luaL_error(L, "can't negate a pointer value");
2284 } else {
2285 memset(&ct, 0, sizeof(ct));
2286 ct.type = INT64_TYPE;
2287 ct.base_size = 8;
2288 ct.is_defined = 1;
2289 push_number(L, -val, 0, &ct);
2290 }
2291
2292 return 1;
2293 }
2294
2295 /* returns -ve if no binop was called otherwise returns the number of return
2296 * arguments */
2297 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)
2298 {
2299 lidx = lua_absindex(L, lidx);
2300 ridx = lua_absindex(L, ridx);
2301
2302 if (push_user_mt(L, lusr, lt)) {
2303 lua_pushstring(L, opfield);
2304 lua_rawget(L, -2);
2305
2306 if (!lua_isnil(L, -1)) {
2307 int top = lua_gettop(L);
2308 lua_pushvalue(L, lidx);
2309 lua_pushvalue(L, ridx);
2310 lua_call(L, 2, LUA_MULTRET);
2311 return lua_gettop(L) - top + 1;
2312 }
2313
2314 lua_pop(L, 2); /* user_mt and user_mt.op */
2315 }
2316
2317 if (push_user_mt(L, rusr, rt)) {
2318 lua_pushstring(L, opfield);
2319 lua_rawget(L, -2);
2320
2321 if (!lua_isnil(L, -1)) {
2322 int top = lua_gettop(L);
2323 lua_pushvalue(L, lidx);
2324 lua_pushvalue(L, ridx);
2325 lua_call(L, 2, LUA_MULTRET);
2326 return lua_gettop(L) - top + 1;
2327 }
2328
2329 lua_pop(L, 2); /* user_mt and user_mt.op */
2330 }
2331
2332 return -1;
2333 }
2334
2335 static int user_cdata_concat(lua_State* L)
2336 {
2337 struct ctype lt, rt;
2338 int ret;
2339
2340 lua_settop(L, 2);
2341 to_cdata(L, 1, &lt);
2342 to_cdata(L, 2, &rt);
2343
2344 ret = call_user_binop(L, "__concat", 1, 3, &lt, 2, 4, &rt);
2345 if (ret >= 0) {
2346 return ret;
2347 }
2348
2349 lua_settop(L, 2);
2350 return -1;
2351 }
2352
2353 #if LUA_VERSION_NUM > 501
2354 static int stringified_cdata_concat(lua_State* L)
2355 {
2356 size_t l_size = 0, r_size = 0;
2357 const char * l_str = NULL;
2358 const char * r_str = NULL;
2359 char * o_str = NULL;
2360
2361 lua_settop(L, 2);
2362
2363 r_str = luaL_tolstring(L, 2, &r_size);
2364 if (!r_str) return luaL_error(L, "NYI");
2365 l_str = luaL_tolstring(L, 1, &l_size);
2366 if (!l_str) return luaL_error(L, "NYI");
2367
2368 o_str = malloc(l_size + r_size);
2369
2370 memcpy(o_str, l_str, l_size);
2371 memcpy((o_str+l_size), r_str, r_size);
2372
2373 lua_pushlstring(L, o_str, l_size + r_size);
2374
2375 free(o_str);
2376
2377 return 1;
2378 }
2379 #endif
2380
2381 static int cdata_concat(lua_State* L)
2382 {
2383 int ret = user_cdata_concat(L);
2384 if (ret != -1) {
2385 return ret;
2386 }
2387
2388 #if LUA_VERSION_NUM > 501
2389 return stringified_cdata_concat(L);
2390 #else
2391 return ret;
2392 #endif
2393 }
2394
2395 static int cdata_len(lua_State* L)
2396 {
2397 struct ctype ct;
2398 int ret;
2399
2400 lua_settop(L, 1);
2401 to_cdata(L, 1, &ct);
2402
2403 ret = call_user_op(L, "__len", 1, 2, &ct);
2404 if (ret >= 0) {
2405 return ret;
2406 }
2407
2408 push_type_name(L, 2, &ct);
2409 return luaL_error(L, "type %s does not implement the __len metamethod", lua_tostring(L, -1));
2410 }
2411
2412 static int cdata_pairs(lua_State* L)
2413 {
2414 struct ctype ct;
2415 int ret;
2416
2417 lua_settop(L, 1);
2418 to_cdata(L, 1, &ct);
2419
2420 ret = call_user_op(L, "__pairs", 1, 2, &ct);
2421 if (ret >= 0) {
2422 return ret;
2423 }
2424
2425 push_type_name(L, 2, &ct);
2426 return luaL_error(L, "type %s does not implement the __pairs metamethod", lua_tostring(L, -1));
2427 }
2428
2429 static int cdata_ipairs(lua_State* L)
2430 {
2431 struct ctype ct;
2432 int ret;
2433
2434 lua_settop(L, 1);
2435 to_cdata(L, 1, &ct);
2436
2437 ret = call_user_op(L, "__ipairs", 1, 2, &ct);
2438 if (ret >= 0) {
2439 return ret;
2440 }
2441
2442 push_type_name(L, 2, &ct);
2443 return luaL_error(L, "type %s does not implement the __ipairs metamethod", lua_tostring(L, -1));
2444 }
2445
2446 static int cdata_add(lua_State* L)
2447 {
2448 struct ctype lt, llt, rt, rrt, ct;
2449 void *lp, *rp;
2450 int ct_usr;
2451 int ret;
2452
2453 lua_settop(L, 2);
2454
2455 lp = to_cdata(L, 1, &lt);
2456 rp = to_cdata(L, 2, &rt);
2457 llt = lt;
2458 rrt = rt;
2459 assert(lua_gettop(L) == 4);
2460
2461 ret = call_user_binop(L, "__add", 1, 3, &lt, 2, 4, &rt);
2462 if (ret >= 0) {
2463 return ret;
2464 }
2465 assert(lua_gettop(L) == 4);
2466
2467 ct_usr = rank(&lt) > rank(&rt) ? 3 : 4;
2468 ct = rank(&lt) > rank(&rt) ? lt : rt;
2469
2470 if (IS_COMPLEX(ct.type)) {
2471 complex_double left, right, res;
2472
2473 left = check_complex(L, 1, lp, &lt);
2474 right = check_complex(L, 2, rp, &rt);
2475 assert(lua_gettop(L) == 4);
2476
2477 #ifdef HAVE_COMPLEX
2478 res = left + right;
2479 #else
2480 res.real = left.real + right.real;
2481 res.imag = left.imag + right.imag;
2482 #endif
2483
2484 push_complex(L, res, ct_usr, &ct);
2485 return 1;
2486
2487 } else {
2488 int64_t left = check_intptr(L, 1, lp, &llt);
2489 int64_t right = check_intptr(L, 2, rp, &rrt);
2490 /*
2491 * There is a side effect of check_intptr that it freshly assigns
2492 * values for lt and rrt if one of them is an INVALID type (e.g. LUA NUMBER)
2493 * thus the rank and therefore ct and ct_usr should get re-evaluated once again.
2494 */
2495 ct_usr = rank(&lt) > rank(&rt) ? 3 : 4;
2496 ct = rank(&lt) > rank(&rt) ? lt : rt;
2497 assert(lua_gettop(L) == 4);
2498
2499 /* note due to 2s complement it doesn't matter if we do the addition as int or uint,
2500 * but the result needs to be uint64_t if either of the sources are */
2501
2502 if (llt.pointers && rrt.pointers) {
2503 luaL_error(L, "can't add two pointers");
2504
2505 } else if (llt.pointers) {
2506 int64_t res = left + (llt.pointers > 1 ? sizeof(void*) : llt.base_size) * right;
2507 llt.is_array = 0;
2508 push_number(L, res, 3, &llt);
2509
2510 } else if (rrt.pointers) {
2511 int64_t res = right + (rrt.pointers > 1 ? sizeof(void*) : rrt.base_size) * left;
2512 rrt.is_array = 0;
2513 push_number(L, res, 4, &rrt);
2514
2515 } else {
2516 push_number(L, left + right, ct_usr, &ct);
2517 }
2518
2519 return 1;
2520 }
2521 }
2522
2523 static int cdata_sub(lua_State* L)
2524 {
2525 struct ctype lt, llt, rt, rrt, ct;
2526 void *lp, *rp;
2527 int ct_usr;
2528 int ret;
2529
2530 lua_settop(L, 2);
2531
2532 lp = to_cdata(L, 1, &lt);
2533 rp = to_cdata(L, 2, &rt);
2534 llt = lt;
2535 rrt = rt;
2536
2537 ret = call_user_binop(L, "__sub", 1, 3, &lt, 2, 4, &rt);
2538 if (ret >= 0) {
2539 return ret;
2540 }
2541
2542 ct_usr = rank(&lt) > rank(&rt) ? 3 : 4;
2543 ct = rank(&lt) > rank(&rt) ? lt : rt;
2544
2545 if (IS_COMPLEX(ct.type)) {
2546 complex_double left, right, res;
2547
2548 left = check_complex(L, 1, lp, &lt);
2549 right = check_complex(L, 2, rp, &rt);
2550
2551 #ifdef HAVE_COMPLEX
2552 res = left - right;
2553 #else
2554 res.real = left.real - right.real;
2555 res.imag = left.imag - right.imag;
2556 #endif
2557
2558 push_complex(L, res, ct_usr, &ct);
2559 return 1;
2560
2561 } else {
2562 int64_t left = check_intptr(L, 1, lp, &llt);
2563 int64_t right = check_intptr(L, 2, rp, &rrt);
2564 /*
2565 * There is a side effect of check_intptr that it freshly assigns
2566 * values for llt and rt if one of them is an INVALID type (e.g. LUA NUMBER)
2567 * thus the rank and therefore ct and ct_usr should get re-evaluated once again.
2568 */
2569 ct_usr = rank(&lt) > rank(&rt) ? 3 : 4;
2570 ct = rank(&lt) > rank(&rt) ? lt : rt;
2571 assert(lua_gettop(L) == 4);
2572
2573 if (rrt.pointers) {
2574 luaL_error(L, "NYI: can't subtract a pointer value");
2575
2576 } else if (llt.pointers) {
2577 int64_t res = left - (llt.pointers > 1 ? sizeof(void*) : llt.base_size) * right;
2578 llt.is_array = 0;
2579 push_number(L, res, 3, &llt);
2580
2581 } else {
2582 int64_t res = left - right;
2583 push_number(L, res, ct_usr, &ct);
2584 }
2585
2586 return 1;
2587 }
2588 }
2589
2590 #define NUMBER_ONLY_BINOP(OPSTR, DO_NORMAL, DO_COMPLEX) \
2591 struct ctype lt, llt, rt, rrt, ct; \
2592 void *lp, *rp; \
2593 int ct_usr; \
2594 int ret; \
2595 \
2596 lua_settop(L, 2); \
2597 \
2598 lp = to_cdata(L, 1, &lt); \
2599 rp = to_cdata(L, 2, &rt); \
2600 llt = lt; \
2601 rrt = rt; \
2602 \
2603 ret = call_user_binop(L, OPSTR, 1, 3, &lt, 2, 4, &rt); \
2604 if (ret >= 0) { \
2605 return ret; \
2606 } \
2607 \
2608 ct_usr = rank(&lt) > rank(&rt) ? 3 : 4; \
2609 ct = rank(&lt) > rank(&rt) ? lt : rt; \
2610 \
2611 if (IS_COMPLEX(ct.type)) { \
2612 complex_double res; \
2613 complex_double left = check_complex(L, 1, lp, &lt); \
2614 complex_double right = check_complex(L, 2, rp, &rt); \
2615 \
2616 DO_COMPLEX(left, right, res); \
2617 push_complex(L, res, ct_usr, &ct); \
2618 \
2619 } else if (lt.pointers || rt.pointers) { \
2620 luaL_error(L, "can't operate on a pointer value"); \
2621 \
2622 } else if (ct.is_unsigned) { \
2623 uint64_t res; \
2624 uint64_t left = check_intptr(L, 1, lp, &llt); \
2625 uint64_t right = check_intptr(L, 2, rp, &rrt); \
2626 \
2627 DO_NORMAL(left, right, res); \
2628 push_number(L, res, ct_usr, &ct); \
2629 } else { \
2630 int64_t res; \
2631 int64_t left = check_intptr(L, 1, lp, &llt); \
2632 int64_t right = check_intptr(L, 2, rp, &rrt); \
2633 \
2634 DO_NORMAL(left, right, res); \
2635 push_number(L, res, ct_usr, &ct); \
2636 } \
2637 \
2638 return 1
2639
2640 #define MUL(l,r,s) s = l * r
2641 #define DIV(l,r,s) s = l / r
2642 #define MOD(l,r,s) s = l % r
2643 #define POW(l,r,s) s = pow(l, r)
2644
2645 #ifdef HAVE_COMPLEX
2646 #define MULC(l,r,s) s = l * r
2647 #define DIVC(l,r,s) s = l / r
2648 #define MODC(l,r,s) (void) l, (void) r, memset(&s, 0, sizeof(s)), luaL_error(L, "NYI: complex mod")
2649 #define POWC(l,r,s) s = cpow(l, r)
2650 #else
2651 #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
2652 #define DIVC(l,r,s) s.real = (l.real * r.real + l.imag * r.imag) / (r.real * r.real + r.imag * r.imag), \
2653 s.imag = (l.imag * r.real - l.real * r.imag) / (r.real * r.real + r.imag * r.imag)
2654 #define MODC(l,r,s) (void) l, (void) r, memset(&s, 0, sizeof(s)), luaL_error(L, "NYI: complex mod")
2655 #define POWC(l,r,s) (void) l, (void) r, memset(&s, 0, sizeof(s)), luaL_error(L, "NYI: complex pow")
2656 #endif
2657
2658 static int cdata_mul(lua_State* L)
2659 { NUMBER_ONLY_BINOP("__mul", MUL, MULC); }
2660
2661 static int cdata_div(lua_State* L)
2662 { NUMBER_ONLY_BINOP("__div", DIV, DIVC); }
2663
2664 static int cdata_mod(lua_State* L)
2665 { NUMBER_ONLY_BINOP("__mod", MOD, MODC); }
2666
2667 static int cdata_pow(lua_State* L)
2668 { NUMBER_ONLY_BINOP("__pow", POW, POWC); }
2669
2670 #define COMPARE_BINOP(OPSTR, OP, OPC) \
2671 struct ctype lt, rt; \
2672 void *lp, *rp; \
2673 int ret, res; \
2674 \
2675 lua_settop(L, 2); \
2676 \
2677 lp = to_cdata(L, 1, &lt); \
2678 rp = to_cdata(L, 2, &rt); \
2679 \
2680 ret = call_user_binop(L, OPSTR, 1, 3, &lt, 2, 4, &rt); \
2681 if (ret >= 0) { \
2682 return ret; \
2683 } \
2684 \
2685 if (IS_COMPLEX(lt.type) || IS_COMPLEX(rt.type)) { \
2686 complex_double left = check_complex(L, 1, lp, &lt); \
2687 complex_double right = check_complex(L, 2, rp, &rt); \
2688 \
2689 res = OPC(left, right); \
2690 \
2691 lua_pushboolean(L, res); \
2692 \
2693 } else { \
2694 int64_t left = check_intptr(L, 1, lp, &lt); \
2695 int64_t right = check_intptr(L, 2, rp, &rt); \
2696 \
2697 if (lt.pointers && rt.pointers) { \
2698 if (is_void_ptr(&lt) || is_void_ptr(&rt) || is_same_type(L, 3, 4, &lt, &rt)) { \
2699 res = OP((uint64_t) left, (uint64_t) right); \
2700 } else { \
2701 goto err; \
2702 } \
2703 \
2704 } else if (lt.is_null && rt.type == FUNCTION_PTR_TYPE) { \
2705 res = OP((uint64_t) left, (uint64_t) right); \
2706 \
2707 } else if (rt.is_null && lt.type == FUNCTION_PTR_TYPE) { \
2708 res = OP((uint64_t) left, (uint64_t) right); \
2709 \
2710 } else if (lt.pointers && rt.type == INTPTR_TYPE && rt.is_unsigned) {\
2711 res = OP((uint64_t) left, (uint64_t) right); \
2712 \
2713 } else if (rt.pointers && lt.type == INTPTR_TYPE && lt.is_unsigned) {\
2714 res = OP((uint64_t) left, (uint64_t) right); \
2715 \
2716 } else if (rt.pointers || lt.pointers) { \
2717 goto err; \
2718 \
2719 } else if (lt.is_unsigned && rt.is_unsigned) { \
2720 res = OP((uint64_t) left, (uint64_t) right); \
2721 \
2722 } else if (lt.is_unsigned) { \
2723 res = OP((int64_t) (uint64_t) left, right); \
2724 \
2725 } else if (rt.is_unsigned) { \
2726 res = OP(left, (int64_t) (uint64_t) right); \
2727 \
2728 } else { \
2729 res = OP(left, right); \
2730 } \
2731 \
2732 lua_pushboolean(L, res); \
2733 } \
2734 return 1
2735
2736 #define EQ(l, r) (l) == (r)
2737 #define LT(l, r) (l) < (r)
2738 #define LE(l, r) (l) <= (r)
2739
2740 #ifdef HAVE_COMPLEX
2741 #define EQC(l, r) (l) == (r)
2742 #else
2743 #define EQC(l, r) (l).real == (r).real && (l).imag == (r).imag
2744 #endif
2745
2746 #define LEC(l, r) EQC(l, r), luaL_error(L, "complex numbers are non-orderable")
2747 #define LTC(l, r) EQC(l, r), luaL_error(L, "complex numbers are non-orderable")
2748
2749 static int cdata_eq(lua_State* L)
2750 {
2751 COMPARE_BINOP("__eq", EQ, EQC);
2752 err:
2753 lua_pushboolean(L, 0);
2754 return 1;
2755 }
2756
2757 static int cdata_lt(lua_State* L)
2758 {
2759 COMPARE_BINOP("__lt", LT, LTC);
2760 err:
2761 lua_getuservalue(L, 1);
2762 lua_getuservalue(L, 2);
2763 push_type_name(L, -2, &lt);
2764 push_type_name(L, -2, &lt);
2765 return luaL_error(L, "trying to compare incompatible types %s and %s", lua_tostring(L, -2), lua_tostring(L, -1));
2766 }
2767
2768 static int cdata_le(lua_State* L)
2769 {
2770 COMPARE_BINOP("__le", LE, LEC);
2771 err:
2772 lua_getuservalue(L, 1);
2773 lua_getuservalue(L, 2);
2774 push_type_name(L, -2, &lt);
2775 push_type_name(L, -2, &lt);
2776 return luaL_error(L, "trying to compare incompatible types %s and %s", lua_tostring(L, -2), lua_tostring(L, -1));
2777 }
2778
2779 static const char* etype_tostring(int type)
2780 {
2781 switch (type) {
2782 case VOID_TYPE: return "void";
2783 case DOUBLE_TYPE: return "double";
2784 case FLOAT_TYPE: return "float";
2785 case COMPLEX_DOUBLE_TYPE: return "complex double";
2786 case COMPLEX_FLOAT_TYPE: return "complex float";
2787 case BOOL_TYPE: return "bool";
2788 case INT8_TYPE: return "int8";
2789 case INT16_TYPE: return "int16";
2790 case INT32_TYPE: return "int32";
2791 case INT64_TYPE: return "int64";
2792 case INTPTR_TYPE: return "intptr";
2793 case ENUM_TYPE: return "enum";
2794 case UNION_TYPE: return "union";
2795 case STRUCT_TYPE: return "struct";
2796 case FUNCTION_PTR_TYPE: return "function ptr";
2797 case FUNCTION_TYPE: return "function";
2798 default: return "invalid";
2799 }
2800 }
2801
2802 static void print_type(lua_State* L, const struct ctype* ct)
2803 {
2804 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",
2805 /* sz */
2806 ct->base_size,
2807 ct->array_size,
2808 ct->offset,
2809 /* align */
2810 ct->align_mask,
2811 /* ptr */
2812 ct->is_array,
2813 ct->pointers,
2814 /* const */
2815 ct->const_mask,
2816 /* type */
2817 ct->is_unsigned ? "u" : "",
2818 etype_tostring(ct->type),
2819 ct->is_reference,
2820 ct->is_defined,
2821 ct->is_null,
2822 /* name */
2823 ct->has_member_name,
2824 /* call */
2825 ct->calling_convention,
2826 ct->has_var_arg,
2827 /* var */
2828 ct->is_variable_array,
2829 ct->is_variable_struct,
2830 ct->variable_size_known,
2831 /* bit */
2832 ct->is_bitfield,
2833 ct->has_bitfield,
2834 ct->bit_offset,
2835 ct->bit_size,
2836 /* jit */
2837 ct->is_jitted);
2838 }
2839
2840 static int ctype_tostring(lua_State* L)
2841 {
2842 struct ctype ct;
2843 assert(lua_type(L, 1) == LUA_TUSERDATA);
2844 lua_settop(L, 1);
2845 check_ctype(L, 1, &ct);
2846 assert(lua_gettop(L) == 2);
2847 push_type_name(L, -1, &ct);
2848 lua_pushfstring(L, "ctype<%s>", lua_tostring(L, -1));
2849
2850 if (DEBUG_TOSTRING) {
2851 print_type(L, &ct);
2852 lua_concat(L, 2);
2853 }
2854
2855 return 1;
2856 }
2857
2858 static int cdata_tostring(lua_State* L)
2859 {
2860 struct ctype ct;
2861 char buf[64];
2862 void* p;
2863 int ret;
2864
2865 lua_settop(L, 1);
2866 p = to_cdata(L, 1, &ct);
2867
2868 ret = call_user_op(L, "__tostring", 1, 2, &ct);
2869 if (ret >= 0) {
2870 return ret;
2871 }
2872
2873 if (ct.pointers > 0 || ct.is_reference || ct.type == STRUCT_TYPE || ct.type == UNION_TYPE) {
2874 push_type_name(L, -1, &ct);
2875 lua_pushfstring(L, "cdata<%s>: %p", lua_tostring(L, -1), p);
2876
2877 if (DEBUG_TOSTRING) {
2878 print_type(L, &ct);
2879 lua_concat(L, 2);
2880 }
2881
2882 return 1;
2883 }
2884
2885 switch (ct.type) {
2886 case COMPLEX_DOUBLE_TYPE:
2887 {
2888 complex_double c = *(complex_double*) p;
2889 lua_pushfstring(L, "%f+%fi", creal(c), cimag(c));
2890 }
2891 return 1;
2892
2893 case COMPLEX_FLOAT_TYPE:
2894 {
2895 complex_float c = *(complex_float*) p;
2896 lua_pushfstring(L, "%f+%fi", crealf(c), cimagf(c));
2897 }
2898 return 1;
2899
2900 case FUNCTION_PTR_TYPE:
2901 p = *(void**) p;
2902 push_type_name(L, -1, &ct);
2903 lua_pushfstring(L, "cdata<%s>: %p", lua_tostring(L, -1), *(void**) p);
2904 return 1;
2905
2906 case INTPTR_TYPE:
2907 lua_pushfstring(L, "%p", *(uintptr_t*) p);
2908 return 1;
2909
2910 case BOOL_TYPE:
2911 sprintf(buf,"%s", (*(_Bool*) p) ? "true" : "false");
2912 lua_pushstring(L, buf);
2913 return 1;
2914
2915 case INT8_TYPE:
2916 sprintf(buf, ct.is_unsigned ? "%hhu" : "%hhd", *(uint8_t*) p);
2917 lua_pushstring(L, buf);
2918 return 1;
2919
2920 case INT16_TYPE:
2921 sprintf(buf, ct.is_unsigned ? "%hu" : "%hd", *(uint16_t*) p);
2922 lua_pushstring(L, buf);
2923 return 1;
2924
2925 case INT32_TYPE:
2926 sprintf(buf, ct.is_unsigned ? "%u" : "%d", *(uint32_t*) p);
2927 lua_pushstring(L, buf);
2928 return 1;
2929
2930 case INT64_TYPE:
2931 sprintf(buf, ct.is_unsigned ? "%"PRIu64 : "%"PRId64, *(uint64_t*) p);
2932 lua_pushstring(L, buf);
2933 return 1;
2934
2935 case FLOAT_TYPE:
2936 sprintf(buf,"%f", *(float*) p);
2937 lua_pushstring(L, buf);
2938 return 1;
2939
2940 case DOUBLE_TYPE:
2941 sprintf(buf,"%lf", *(double*) p);
2942 lua_pushstring(L, buf);
2943 return 1;
2944
2945 default:
2946 sprintf(buf, ct.is_unsigned ? "%"PRId64 : "%"PRId64, (int64_t) check_intptr(L, 1, p, &ct));
2947 lua_pushstring(L, buf);
2948 return 1;
2949 }
2950 }
2951
2952 static int ffi_getptr(lua_State* L)
2953 {
2954 struct ctype ct;
2955 char buf[64];
2956 void* p = NULL;
2957 int ret;
2958
2959 lua_settop(L, 1);
2960 p = to_cdata(L, 1, &ct);
2961 lua_pushlightuserdata(L, p);
2962 return 1;
2963
2964 }
2965
2966 static int ffi_errno(lua_State* L)
2967 {
2968 struct jit* jit = get_jit(L);
2969
2970 if (!lua_isnoneornil(L, 1)) {
2971 lua_pushinteger(L, jit->last_errno);
2972 jit->last_errno = luaL_checknumber(L, 1);
2973 } else {
2974 lua_pushinteger(L, jit->last_errno);
2975 }
2976
2977 return 1;
2978 }
2979
2980 static int ffi_type(lua_State* L)
2981 {
2982 if (lua_isuserdata(L, 1) && lua_getmetatable(L, 1)) {
2983 if (equals_upval(L, -1, &cdata_mt_key) || equals_upval(L, -1, &ctype_mt_key)) {
2984 lua_pushstring(L, "cdata");
2985 return 1;
2986 }
2987 lua_pop(L, 1); /* mt */
2988 }
2989
2990 /* call the old _G.type, we use an upvalue as _G.type is set
2991 * to this function */
2992 lua_pushvalue(L, lua_upvalueindex(1));
2993 lua_insert(L, 1);
2994 lua_call(L, lua_gettop(L)-1, LUA_MULTRET);
2995 return lua_gettop(L);
2996 }
2997
2998 static int ffi_number(lua_State* L)
2999 {
3000 struct ctype ct;
3001 void* data = to_cdata(L, 1, &ct);
3002
3003 //pfintf("%s:%d\n", __FILE__, __LINE__);
3004
3005 if (ct.type != INVALID_TYPE) {
3006 switch (ct.type) {
3007 case FLOAT_TYPE:
3008 lua_pushnumber(L, *(float*)data);
3009 break;
3010 default:
3011 lua_pushinteger(L, check_intptr(L, 1, data, &ct));
3012 break;
3013 }
3014 return 1;
3015 } else {
3016 /* call the old _G.tonumber, we use an upvalue as _G.tonumber is set
3017 * to this function */
3018 lua_pushvalue(L, lua_upvalueindex(1));
3019 lua_insert(L, 1);
3020 lua_call(L, lua_gettop(L)-1, LUA_MULTRET);
3021 return lua_gettop(L);
3022 }
3023 }
3024
3025 static int ffi_string(lua_State* L)
3026 {
3027 struct ctype ct;
3028 char* data;
3029 lua_settop(L, 2);
3030
3031 data = (char*) check_cdata(L, 1, &ct);
3032
3033 if (is_void_ptr(&ct)) {
3034 lua_pushlstring(L, data, (size_t) luaL_checknumber(L, 2));
3035 return 1;
3036
3037 } else if (ct.type == INT8_TYPE && ct.pointers == 1) {
3038 size_t sz;
3039
3040 if (lua_isuserdata(L, 2)) {
3041 ptrdiff_t val;
3042 if (!cdata_tointeger(L, 2, &val)) {
3043 type_error(L, 2, "int", 0, NULL);
3044 }
3045 sz = (size_t) val;
3046 } else if (!lua_isnil(L, 2)) {
3047 sz = (size_t) luaL_checknumber(L, 2);
3048
3049 } else if (ct.is_array && !ct.is_variable_array) {
3050 char* nul = memchr(data, '\0', ct.array_size);
3051 sz = nul ? nul - data : ct.array_size;
3052
3053 } else {
3054 sz = strlen(data);
3055 }
3056
3057 lua_pushlstring(L, data, sz);
3058 return 1;
3059 }
3060
3061 return luaL_error(L, "unable to convert cdata to string");
3062 }
3063
3064 static int ffi_copy(lua_State* L)
3065 {
3066 struct ctype ft, tt;
3067 char *to, *from;
3068
3069 setmintop(L, 3);
3070 to = (char*) check_pointer(L, 1, &tt);
3071 from = (char*) check_pointer(L, 2, &ft);
3072
3073 if (!lua_isnoneornil(L, 3)) {
3074 memcpy(to, from, (size_t) luaL_checknumber(L, 3));
3075
3076 } else if (ft.type == INT8_TYPE && ft.pointers == 1) {
3077 size_t sz = ft.is_array ? ft.array_size : strlen(from);
3078 memcpy(to, from, sz);
3079 to[sz] = '\0';
3080 }
3081
3082 return 0;
3083 }
3084
3085 static int ffi_fill(lua_State* L)
3086 {
3087 struct ctype ct;
3088 void* to;
3089 size_t sz;
3090 int val = 0;
3091
3092 setmintop(L, 3);
3093 to = check_pointer(L, 1, &ct);
3094 sz = (size_t) luaL_checknumber(L, 2);
3095
3096 if (!lua_isnoneornil(L, 3)) {
3097 val = (int) luaL_checkinteger(L, 3);
3098 }
3099
3100 memset(to, val, sz);
3101 return 0;
3102 }
3103
3104 static int ffi_abi(lua_State* L)
3105 {
3106 luaL_checkstring(L, 1);
3107 push_upval(L, &abi_key);
3108 lua_pushvalue(L, 1);
3109 lua_rawget(L, -2);
3110 lua_pushboolean(L, lua_toboolean(L, -1));
3111 return 1;
3112 }
3113
3114 static int ffi_load(lua_State* L)
3115 {
3116 const char* libname = luaL_checkstring(L, 1);
3117 void** lib = (void**) lua_newuserdata(L, sizeof(void*));
3118
3119 *lib = LoadLibraryA(libname);
3120
3121 #ifdef LIB_FORMAT_1
3122 if (!*lib) {
3123 libname = lua_pushfstring(L, LIB_FORMAT_1, lua_tostring(L, 1));
3124 *lib = LoadLibraryA(libname);
3125 lua_pop(L, 1);
3126 }
3127 #endif
3128
3129 #ifdef LIB_FORMAT_2
3130 if (!*lib) {
3131 libname = lua_pushfstring(L, LIB_FORMAT_2, lua_tostring(L, 1));
3132 *lib = LoadLibraryA(libname);
3133 lua_pop(L, 1);
3134 }
3135 #endif
3136
3137 if (!*lib) {
3138 return luaL_error(L, "could not load library %s", lua_tostring(L, 1));
3139 }
3140
3141 lua_newtable(L);
3142 lua_setuservalue(L, -2);
3143
3144 push_upval(L, &cmodule_mt_key);
3145 lua_setmetatable(L, -2);
3146 return 1;
3147 }
3148
3149 static void* find_symbol(lua_State* L, int modidx, const char* asmname)
3150 {
3151 size_t i;
3152 void** libs;
3153 size_t num;
3154 void* sym = NULL;
3155
3156 libs = (void**) lua_touserdata(L, modidx);
3157 num = lua_rawlen(L, modidx) / sizeof(void*);
3158
3159 for (i = 0; i < num && sym == NULL; i++) {
3160 if (libs[i]) {
3161 sym = GetProcAddressA(libs[i], asmname);
3162 }
3163 }
3164
3165 return sym;
3166 }
3167
3168 /* pushes the user table */
3169 static void* lookup_global(lua_State* L, int modidx, int nameidx, const char** pname, struct ctype* ct)
3170 {
3171 int top = lua_gettop(L);
3172 void* sym;
3173
3174 modidx = lua_absindex(L, modidx);
3175 nameidx = lua_absindex(L, nameidx);
3176
3177 *pname = luaL_checkstring(L, nameidx);
3178
3179 /* get the ctype */
3180 push_upval(L, &functions_key);
3181 lua_pushvalue(L, nameidx);
3182 lua_rawget(L, -2);
3183 if (lua_isnil(L, -1)) {
3184 luaL_error(L, "missing declaration for function/global %s", *pname);
3185 return NULL;
3186 }
3187
3188 /* leave just the ct_usr on the stack */
3189 //*ct = *(const struct ctype*) lua_touserdata(L, -1);
3190 memcpy(ct, lua_touserdata(L, -1), sizeof(struct ctype));
3191 lua_getuservalue(L, -1);
3192 lua_replace(L, top + 1);
3193 lua_pop(L, 1);
3194
3195 assert(lua_gettop(L) == top + 1);
3196
3197 /* get the assembly name */
3198 push_upval(L, &asmname_key);
3199 lua_pushvalue(L, nameidx);
3200 lua_rawget(L, -2);
3201 if (lua_isstring(L, -1)) {
3202 *pname = lua_tostring(L, -1);
3203 }
3204 lua_pop(L, 2);
3205
3206 sym = find_symbol(L, modidx, *pname);
3207
3208 assert(lua_gettop(L) == top + 1);
3209 return sym;
3210 }
3211
3212 static int cmodule_index(lua_State* L)
3213 {
3214 const char* asmname;
3215 struct ctype ct;
3216 void *sym = 0;
3217
3218 lua_settop(L, 2);
3219
3220 /* see if we have already loaded the function */
3221 lua_getuservalue(L, 1);
3222 lua_pushvalue(L, 2);
3223 lua_rawget(L, -2);
3224 if (!lua_isnil(L, -1)) {
3225 return 1;
3226 }
3227 lua_pop(L, 2);
3228
3229 /* check the constants table */
3230 push_upval(L, &constants_key);
3231 lua_pushvalue(L, 2);
3232 lua_rawget(L, -2);
3233 if (!lua_isnil(L, -1)) {
3234 return 1;
3235 }
3236 lua_pop(L, 2);
3237
3238 /* lookup_global pushes the ct_usr */
3239 sym = lookup_global(L, 1, 2, &asmname, &ct);
3240
3241 #if defined _WIN32 && !defined _WIN64 && (defined __i386__ || defined _M_IX86)
3242 if (!sym && ct.type == FUNCTION_TYPE) {
3243 ct.calling_convention = STD_CALL;
3244 lua_pushfstring(L, "_%s@%d", asmname, x86_return_size(L, -1, &ct));
3245 sym = find_symbol(L, 1, lua_tostring(L, -1));
3246 lua_pop(L, 1);
3247 }
3248
3249 if (!sym && ct.type == FUNCTION_TYPE) {
3250 ct.calling_convention = FAST_CALL;
3251 lua_pushfstring(L, "@%s@%d", asmname, x86_return_size(L, -1, &ct));
3252 sym = find_symbol(L, 1, lua_tostring(L, -1));
3253 lua_pop(L, 1);
3254 }
3255 #endif
3256
3257 if (!sym) {
3258 return luaL_error(L, "failed to find function/global %s", asmname);
3259 }
3260
3261 assert(lua_gettop(L) == 3); /* module, name, ct_usr */
3262
3263 if (ct.type == FUNCTION_TYPE) {
3264 compile_function(L, (cfunction) sym, -1, &ct);
3265 #ifdef ARCH_ARM64
3266 /* Ref: https://developer.arm.com/documentation/ihi0053/latest
3267 * Generates an ISB (instruction synchronization barrier) instruction or
3268 * equivalent CP15 instruction. This instruction flushes the processor
3269 * pipeline fetch buffers, so that following instructions are fetched
3270 * from cache or memory. An ISB is needed after some system maintenance
3271 * operations. An ISB is also needed before transferring control to code
3272 * that has been loaded or modified in memory, for example by an overlay
3273 * mechanism or just-in-time code generator. (Note that if instruction
3274 * and data caches are separate, privileged cache maintenance operations
3275 * would be needed in order to unify the caches.) The only supported
3276 * argument for the __isb() intrinsic is 15, corresponding to the SY
3277 * (full system) scope of the ISB instruction.
3278 */
3279 #ifdef __clang__
3280 __isb(15);
3281 #elif __GNUC__
3282 asm("isb 15");
3283 #endif
3284 #endif
3285 assert(lua_gettop(L) == 4); /* module, name, ct_usr, function */
3286
3287 /* set module usr value[luaname] = function to cache for next time */
3288 lua_getuservalue(L, 1);
3289 lua_pushvalue(L, 2);
3290 lua_pushvalue(L, -3);
3291 lua_rawset(L, -3);
3292 lua_pop(L, 1); /* module uv */
3293 return 1;
3294 }
3295
3296 /* extern const char* foo; and extern const char foo[]; */
3297 if (ct.pointers == 1 && ct.type == INT8_TYPE) {
3298 char* str = (char*) sym;
3299 if (!ct.is_array) {
3300 str = *(char**) sym;
3301 }
3302 lua_pushstring(L, str);
3303 return 1;
3304 }
3305
3306 /* extern struct foo foo[], extern void* foo[]; and extern struct foo foo; */
3307 if (ct.is_array || (!ct.pointers && (ct.type == UNION_TYPE || ct.type == STRUCT_TYPE))) {
3308 void* p;
3309 ct.is_reference = 1;
3310 p = push_cdata(L, -1, &ct);
3311 *(void**) p = sym;
3312 return 1;
3313 }
3314
3315 /* extern void* foo; and extern void (*foo)(); */
3316 if (ct.pointers || ct.type == FUNCTION_PTR_TYPE) {
3317 void* p = push_cdata(L, -1, &ct);
3318 *(void**) p = *(void**) sym;
3319 return 1;
3320 }
3321
3322 switch (ct.type) {
3323 case COMPLEX_DOUBLE_TYPE:
3324 case COMPLEX_FLOAT_TYPE:
3325 case INTPTR_TYPE:
3326 case INT64_TYPE:
3327 {
3328 /* TODO: complex float/double need to be references if .re and
3329 * .imag are setable */
3330 void* p = push_cdata(L, -1, &ct);
3331 memcpy(p, sym, ct.base_size);
3332 return 1;
3333 }
3334
3335 case DOUBLE_TYPE:
3336 lua_pushnumber(L, *(double*) sym);
3337 return 1;
3338
3339 case FLOAT_TYPE:
3340 lua_pushnumber(L, *(float*) sym);
3341 return 1;
3342
3343 case BOOL_TYPE:
3344 lua_pushboolean(L, *(bool*) sym);
3345 return 1;
3346
3347 case INT8_TYPE:
3348 lua_pushinteger(L, ct.is_unsigned ? (lua_Integer) *(uint8_t*) sym : (lua_Integer) *(int8_t*) sym);
3349 return 1;
3350
3351 case INT16_TYPE:
3352 lua_pushinteger(L, ct.is_unsigned ? (lua_Integer) *(uint16_t*) sym : (lua_Integer) *(int16_t*) sym);
3353 return 1;
3354
3355 case INT32_TYPE:
3356 case ENUM_TYPE:
3357 lua_pushinteger(L, ct.is_unsigned ? (lua_Integer) *(uint32_t*) sym : (lua_Integer) *(int32_t*) sym);
3358 return 1;
3359 }
3360
3361 return luaL_error(L, "NYI - global value type");
3362 }
3363
3364 static int cmodule_newindex(lua_State* L)
3365 {
3366 const char* name;
3367 void* sym;
3368 struct ctype ct;
3369
3370 lua_settop(L, 3);
3371
3372 /* pushes the ct_usr */
3373 sym = lookup_global(L, 1, 2, &name, &ct);
3374 assert(lua_gettop(L) == 4); /* module, name, value, ct_usr */
3375
3376 if (sym == NULL) {
3377 return luaL_error(L, "failed to find global %s", name);
3378 }
3379
3380 if (ct.type == FUNCTION_TYPE || ct.is_array || (ct.const_mask & 1)) {
3381 return luaL_error(L, "can not set global %s", name);
3382 }
3383
3384 set_value(L, 3, sym, -1, &ct, 1);
3385 return 0;
3386 }
3387
3388 static int jit_gc(lua_State* L)
3389 {
3390 size_t i;
3391 struct jit* jit = get_jit(L);
3392 dasm_free(jit);
3393 for (i = 0; i < jit->pagenum; i++) {
3394 FreePage(jit->pages[i], jit->pages[i]->size);
3395 }
3396 free(jit->pages);
3397 free(jit->globals);
3398 return 0;
3399 }
3400
3401 static int ffi_debug(lua_State* L)
3402 {
3403 lua_newtable(L);
3404 push_upval(L, &ctype_mt_key);
3405 lua_setfield(L, -2, "ctype_mt");
3406 push_upval(L, &cdata_mt_key);
3407 lua_setfield(L, -2, "cdata_mt");
3408 push_upval(L, &cmodule_mt_key);
3409 lua_setfield(L, -2, "cmodule_mt");
3410 push_upval(L, &constants_key);
3411 lua_setfield(L, -2, "constants");
3412 push_upval(L, &types_key);
3413 lua_setfield(L, -2, "types");
3414 push_upval(L, &jit_key);
3415 lua_setfield(L, -2, "jit");
3416 push_upval(L, &gc_key);
3417 lua_setfield(L, -2, "gc");
3418 push_upval(L, &callbacks_key);
3419 lua_setfield(L, -2, "callbacks");
3420 push_upval(L, &functions_key);
3421 lua_setfield(L, -2, "functions");
3422 push_upval(L, &abi_key);
3423 lua_setfield(L, -2, "abi");
3424 push_upval(L, &next_unnamed_key);
3425 lua_setfield(L, -2, "next_unnamed");
3426 return 1;
3427 }
3428
3429 static int do64(lua_State* L, int is_unsigned)
3430 {
3431 lua_Number low, high;
3432 struct ctype ct;
3433 int64_t val;
3434
3435 lua_settop(L, 2);
3436
3437 if (!lua_isnil(L, 2)) {
3438 high = luaL_checknumber(L, 1);
3439 low = luaL_checknumber(L, 2);
3440 } else {
3441 high = 0;
3442 low = luaL_checknumber(L, 1);
3443 }
3444
3445 val = ((int64_t) (uint32_t) high << 32) | (int64_t) (uint32_t) low;
3446
3447 if (!is_unsigned && (high < 0 || low < 0)) {
3448 val = -val;
3449 }
3450
3451 memset(&ct, 0, sizeof(ct));
3452 ct.type = INT64_TYPE;
3453 ct.is_unsigned = is_unsigned;
3454 ct.is_defined = 1;
3455 ct.base_size = sizeof(int64_t);
3456 push_number(L, (int64_t) val, 0, &ct);
3457
3458 return 1;
3459 }
3460
3461 static int ffi_i64(lua_State* L)
3462 { return do64(L, 0); }
3463
3464 static int ffi_u64(lua_State* L)
3465 { return do64(L, 1); }
3466
3467 static const luaL_Reg cdata_mt[] = {
3468 {"__gc", &cdata_gc},
3469 {"__call", &cdata_call},
3470 {"free", &cdata_free},
3471 {"set", &cdata_set},
3472 {"__index", &cdata_index},
3473 {"__newindex", &cdata_newindex},
3474 {"__add", &cdata_add},
3475 {"__sub", &cdata_sub},
3476 {"__mul", &cdata_mul},
3477 {"__div", &cdata_div},
3478 {"__mod", &cdata_mod},
3479 {"__pow", &cdata_pow},
3480 {"__unm", &cdata_unm},
3481 {"__eq", &cdata_eq},
3482 {"__lt", &cdata_lt},
3483 {"__le", &cdata_le},
3484 {"__tostring", &cdata_tostring},
3485 {"__concat", &cdata_concat},
3486 {"__len", &cdata_len},
3487 {"__pairs", &cdata_pairs},
3488 {"__ipairs", &cdata_ipairs},
3489 {NULL, NULL}
3490 };
3491
3492 static const luaL_Reg callback_mt[] = {
3493 {"__gc", &callback_free},
3494 {NULL, NULL}
3495 };
3496
3497 static const luaL_Reg ctype_mt[] = {
3498 {"__call", &ctype_call},
3499 {"__new", &ctype_new},
3500 {"__index", &ctype_index},
3501 {"__tostring", &ctype_tostring},
3502 {NULL, NULL}
3503 };
3504
3505 static const luaL_Reg cmodule_mt[] = {
3506 {"__index", &cmodule_index},
3507 {"__newindex", &cmodule_newindex},
3508 {NULL, NULL}
3509 };
3510
3511 static const luaL_Reg jit_mt[] = {
3512 {"__gc", &jit_gc},
3513 {NULL, NULL}
3514 };
3515
3516 static const luaL_Reg ffi_reg[] = {
3517 {"cdef", &ffi_cdef},
3518 {"load", &ffi_load},
3519 {"new", &ffi_new},
3520 {"typeof", &ffi_typeof},
3521 {"cast", &ffi_cast},
3522 {"metatype", &ffi_metatype},
3523 {"gc", &ffi_gc},
3524 {"sizeof", &ffi_sizeof},
3525 {"alignof", &ffi_alignof},
3526 {"offsetof", &ffi_offsetof},
3527 {"istype", &ffi_istype},
3528 {"errno", &ffi_errno},
3529 {"string", &ffi_string},
3530 {"copy", &ffi_copy},
3531 {"fill", &ffi_fill},
3532 {"abi", &ffi_abi},
3533 {"debug", &ffi_debug},
3534 {"i64", &ffi_i64},
3535 {"u64", &ffi_u64},
3536 {"getptr", &ffi_getptr},
3537 {NULL, NULL}
3538 };
3539
3540 /* leaves the usr table on the stack */
3541 static void push_builtin(lua_State* L, struct ctype* ct, const char* name, int type, int size, int align, int is_unsigned)
3542 {
3543 memset(ct, 0, sizeof(*ct));
3544 ct->type = type;
3545 ct->base_size = size;
3546 ct->align_mask = align;
3547 ct->is_defined = 1;
3548 ct->is_unsigned = is_unsigned;
3549
3550 if (IS_COMPLEX(type)) {
3551 lua_newtable(L);
3552 } else {
3553 lua_pushnil(L);
3554 }
3555
3556 push_upval(L, &types_key);
3557 push_ctype(L, -2, ct);
3558 lua_setfield(L, -2, name);
3559 lua_pop(L, 2); /* types, usr table */
3560 }
3561
3562 static void push_builtin_undef(lua_State* L, struct ctype* ct, const char* name, int type)
3563 {
3564 memset(ct, 0, sizeof(*ct));
3565 ct->type = type;
3566
3567 push_upval(L, &types_key);
3568 push_ctype(L, 0, ct);
3569 lua_setfield(L, -2, name);
3570 lua_pop(L, 1); /* types */
3571 }
3572
3573 static void add_typedef(lua_State* L, const char* from, const char* to)
3574 {
3575 struct ctype ct;
3576 struct parser P;
3577 P.line = 1;
3578 P.align_mask = DEFAULT_ALIGN_MASK;
3579 P.next = P.prev = from;
3580
3581 push_upval(L, &types_key);
3582 parse_type(L, &P, &ct);
3583 parse_argument(L, &P, -1, &ct, NULL, NULL);
3584 push_ctype(L, -1, &ct);
3585
3586 /* stack is at +4: types, type usr, arg usr, ctype */
3587
3588 lua_setfield(L, -4, to);
3589 lua_pop(L, 3); /* types, type usr, arg usr */
3590 }
3591
3592 static int setup_upvals(lua_State* L)
3593 {
3594 struct jit* jit = get_jit(L);
3595
3596 /* jit setup */
3597 {
3598 dasm_init(jit, 64);
3599 #ifdef _WIN32
3600 {
3601 SYSTEM_INFO si;
3602 GetSystemInfo(&si);
3603 jit->align_page_size = si.dwAllocationGranularity - 1;
3604 }
3605 #else
3606 jit->align_page_size = sysconf(_SC_PAGE_SIZE) - 1;
3607 #endif
3608 jit->globals = (void**) malloc(64 * sizeof(void*));
3609 dasm_setupglobal(jit, jit->globals, 64);
3610 compile_globals(jit, L);
3611 }
3612
3613 /* ffi.C */
3614 {
3615 #ifdef _WIN32 //{
3616 size_t sz = sizeof(HMODULE) * 6;
3617 HMODULE* libs = lua_newuserdata(L, sz);
3618 memset(libs, 0, sz);
3619
3620 /* exe */
3621 GetModuleHandle(NULL);
3622 /* lua dll */
3623 #ifdef LUA_DLL_NAME //{
3624 #define STR2(tok) #tok
3625 #define STR(tok) STR2(tok)
3626 libs[1] = LoadLibraryA(STR(LUA_DLL_NAME));
3627 #undef STR
3628 #undef STR2
3629 #endif //}
3630
3631 /* crt */
3632 #ifdef UNDER_CE //{
3633 libs[2] = LoadLibraryA("coredll.dll");
3634 #else //}{
3635 GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (char*) &_fmode, &libs[2]);
3636 libs[3] = LoadLibraryA("kernel32.dll");
3637 libs[4] = LoadLibraryA("user32.dll");
3638 libs[5] = LoadLibraryA("gdi32.dll");
3639 #endif //}
3640
3641 jit->lua_dll = libs[1];
3642 jit->kernel32_dll = libs[3];
3643
3644 #else /* !_WIN32 */ //}{
3645 size_t sz = sizeof(void*) * 5;
3646 void** libs = lua_newuserdata(L, sz);
3647 memset(libs, 0, sz);
3648
3649 libs[0] = LoadLibraryA(NULL); /* exe */
3650 libs[1] = LoadLibraryA("libc.so");
3651 #ifdef __GNUC__ //{
3652 libs[2] = LoadLibraryA("libgcc.so");
3653 #endif //}
3654 libs[3] = LoadLibraryA("libm.so");
3655 libs[4] = LoadLibraryA("libdl.so");
3656 #endif //}
3657
3658 lua_newtable(L);
3659 lua_setuservalue(L, -2);
3660
3661 push_upval(L, &cmodule_mt_key);
3662 lua_setmetatable(L, -2);
3663
3664 lua_setfield(L, 1, "C");
3665 }
3666
3667 /* setup builtin types */
3668 {
3669 complex_double* pc;
3670 struct {char ch; uint16_t v;} a16;
3671 struct {char ch; uint32_t v;} a32;
3672 struct {char ch; uint64_t v;} a64;
3673 struct {char ch; float v;} af;
3674 struct {char ch; double v;} ad;
3675 #ifdef HAVE_LONG_DOUBLE
3676 struct {char ch; long double v;} ald;
3677 #endif
3678 struct {char ch; uintptr_t v;} aptr;
3679 struct ctype ct;
3680 struct {char ch; complex_float v;} cf;
3681 struct {char ch; complex_double v;} cd;
3682 #if defined HAVE_LONG_DOUBLE && defined HAVE_COMPLEX
3683 struct {char ch; complex long double v;} cld;
3684 #endif
3685
3686 push_builtin(L, &ct, "void", VOID_TYPE, 0, 0, 0);
3687 push_builtin(L, &ct, "bool", BOOL_TYPE, sizeof(_Bool), sizeof(_Bool) -1, 1);
3688 push_builtin(L, &ct, "uint8_t", INT8_TYPE, sizeof(uint8_t), 0, 1);
3689 push_builtin(L, &ct, "int8_t", INT8_TYPE, sizeof(int8_t), 0, 0);
3690 push_builtin(L, &ct, "uint16_t", INT16_TYPE, sizeof(uint16_t), ALIGNOF(a16), 1);
3691 push_builtin(L, &ct, "int16_t", INT16_TYPE, sizeof(int16_t), ALIGNOF(a16), 0);
3692 push_builtin(L, &ct, "uint32_t", INT32_TYPE, sizeof(uint32_t), ALIGNOF(a32), 1);
3693 push_builtin(L, &ct, "int32_t", INT32_TYPE, sizeof(int32_t), ALIGNOF(a32), 0);
3694 push_builtin(L, &ct, "uint64_t", INT64_TYPE, sizeof(uint64_t), ALIGNOF(a64), 1);
3695 push_builtin(L, &ct, "int64_t", INT64_TYPE, sizeof(int64_t), ALIGNOF(a64), 0);
3696 push_builtin(L, &ct, "float", FLOAT_TYPE, sizeof(float), ALIGNOF(af), 0);
3697 push_builtin(L, &ct, "double", DOUBLE_TYPE, sizeof(double), ALIGNOF(ad), 0);
3698 #ifdef HAVE_LONG_DOUBLE
3699 push_builtin(L, &ct, "long double", LONG_DOUBLE_TYPE, sizeof(long double), ALIGNOF(ald), 0);
3700 #else
3701 push_builtin_undef(L, &ct, "long double", LONG_DOUBLE_TYPE);
3702 #endif
3703 push_builtin(L, &ct, "uintptr_t", INTPTR_TYPE, sizeof(uintptr_t), ALIGNOF(aptr), 1);
3704 push_builtin(L, &ct, "intptr_t", INTPTR_TYPE, sizeof(uintptr_t), ALIGNOF(aptr), 0);
3705 push_builtin(L, &ct, "complex float", COMPLEX_FLOAT_TYPE, sizeof(complex_float), ALIGNOF(cf), 0);
3706 push_builtin(L, &ct, "complex double", COMPLEX_DOUBLE_TYPE, sizeof(complex_double), ALIGNOF(cd), 0);
3707 #if defined HAVE_LONG_DOUBLE && defined HAVE_COMPLEX
3708 push_builtin(L, &ct, "complex long double", COMPLEX_LONG_DOUBLE_TYPE, sizeof(complex long double), ALIGNOF(cld), 0);
3709 #else
3710 push_builtin_undef(L, &ct, "complex long double", COMPLEX_LONG_DOUBLE_TYPE);
3711 #endif
3712
3713 /* add NULL and i constants */
3714 push_upval(L, &constants_key);
3715
3716 memset(&ct, 0, sizeof(ct));
3717 ct.type = VOID_TYPE;
3718 ct.is_defined = 1;
3719 ct.pointers = 1;
3720 ct.is_null = 1;
3721
3722 /* add ffi.C.NULL */
3723 push_cdata(L, 0, &ct);
3724 lua_setfield(L, -2, "NULL");
3725
3726 /* add ffi.NULL */
3727 push_cdata(L, 0, &ct);
3728 lua_setfield(L, 1, "NULL");
3729
3730 memset(&ct, 0, sizeof(ct));
3731 ct.type = COMPLEX_DOUBLE_TYPE;
3732 ct.is_defined = 1;
3733 ct.base_size = sizeof(complex_double);
3734 pc = (complex_double*) push_cdata(L, 0, &ct);
3735 #ifdef HAVE_COMPLEX
3736 *pc = 1i;
3737 #else
3738 pc->real = 0;
3739 pc->imag = 1;
3740 #endif
3741 lua_setfield(L, -2, "i");
3742
3743 lua_pop(L, 1); /* constants */
3744 }
3745
3746 assert(lua_gettop(L) == 1);
3747
3748 /* setup builtin typedefs */
3749 {
3750 add_typedef(L, "bool", "_Bool");
3751
3752 if (sizeof(uint32_t) == sizeof(size_t)) {
3753 add_typedef(L, "uint32_t", "size_t");
3754 add_typedef(L, "int32_t", "ssize_t");
3755 } else if (sizeof(uint64_t) == sizeof(size_t)) {
3756 add_typedef(L, "uint64_t", "size_t");
3757 add_typedef(L, "int64_t", "ssize_t");
3758 }
3759
3760 if (sizeof(int32_t) == sizeof(intptr_t)) {
3761 add_typedef(L, "int32_t", "intptr_t");
3762 add_typedef(L, "int32_t", "ptrdiff_t");
3763 } else if (sizeof(int64_t) == sizeof(intptr_t)) {
3764 add_typedef(L, "int64_t", "intptr_t");
3765 add_typedef(L, "int64_t", "ptrdiff_t");
3766 }
3767
3768 if (sizeof(uint8_t) == sizeof(wchar_t)) {
3769 add_typedef(L, "uint8_t", "wchar_t");
3770 } else if (sizeof(uint16_t) == sizeof(wchar_t)) {
3771 add_typedef(L, "uint16_t", "wchar_t");
3772 } else if (sizeof(uint32_t) == sizeof(wchar_t)) {
3773 add_typedef(L, "uint32_t", "wchar_t");
3774 }
3775
3776 if (sizeof(va_list) == sizeof(char*)) {
3777 add_typedef(L, "char*", "va_list");
3778 } else {
3779 struct {char ch; va_list v;} av;
3780 lua_pushfstring(L, "struct {char data[%d] __attribute__((align(%d)));}", (int) sizeof(va_list), (int) ALIGNOF(av) + 1);
3781 add_typedef(L, lua_tostring(L, -1), "va_list");
3782 lua_pop(L, 1);
3783 }
3784
3785 add_typedef(L, "va_list", "__builtin_va_list");
3786 add_typedef(L, "va_list", "__gnuc_va_list");
3787 }
3788
3789 assert(lua_gettop(L) == 1);
3790
3791 /* setup ABI params table */
3792 push_upval(L, &abi_key);
3793
3794 #if defined ARCH_X86 || defined ARCH_ARM
3795 lua_pushboolean(L, 1);
3796 lua_setfield(L, -2, "32bit");
3797 #elif defined ARCH_X64 || defined ARCH_PPC64 || defined ARCH_ARM64
3798 lua_pushboolean(L, 1);
3799 lua_setfield(L, -2, "64bit");
3800 #else
3801 #error
3802 #endif
3803
3804 #if defined ARCH_X86 || defined ARCH_X64 || defined ARCH_ARM || defined ARCH_PPC64 || defined ARCH_ARM64
3805 lua_pushboolean(L, 1);
3806 lua_setfield(L, -2, "le");
3807 #else
3808 #error
3809 #endif
3810
3811 #if defined ARCH_X86 || defined ARCH_X64 || defined ARCH_PPC64 || defined ARCH_ARM64
3812 lua_pushboolean(L, 1);
3813 lua_setfield(L, -2, "fpu");
3814 #elif defined ARCH_ARM
3815 lua_pushboolean(L, 1);
3816 lua_setfield(L, -2, "softfp");
3817 #else
3818 #error
3819 #endif
3820 lua_pop(L, 1); /* abi tbl */
3821
3822
3823 /* GC table - shouldn't pin cdata values */
3824 push_upval(L, &gc_key);
3825 lua_newtable(L);
3826 lua_pushliteral(L, "k");
3827 lua_setfield(L, -2, "__mode");
3828 lua_setmetatable(L, -2);
3829 lua_pop(L, 1); /* gc table */
3830
3831 /* ffi.os */
3832 #if defined OS_CE
3833 lua_pushliteral(L, "WindowsCE");
3834 #elif defined OS_WIN
3835 lua_pushliteral(L, "Windows");
3836 #elif defined OS_OSX
3837 lua_pushliteral(L, "OSX");
3838 #elif defined OS_LINUX
3839 lua_pushliteral(L, "Linux");
3840 #elif defined OS_BSD
3841 lua_pushliteral(L, "BSD");
3842 #elif defined OS_POSIX
3843 lua_pushliteral(L, "POSIX");
3844 #else
3845 lua_pushliteral(L, "Other");
3846 #endif
3847 lua_setfield(L, 1, "os");
3848
3849
3850 /* ffi.arch */
3851 #if defined ARCH_X86
3852 lua_pushliteral(L, "x86");
3853 #elif defined ARCH_X64
3854 lua_pushliteral(L, "x64");
3855 #elif defined ARCH_ARM
3856 lua_pushliteral(L, "arm");
3857 #elif defined ARCH_ARM64
3858 lua_pushliteral(L, "arm64");
3859 #elif defined ARCH_PPC64
3860 lua_pushliteral(L, "ppc64");
3861 #else
3862 # error
3863 #endif
3864 lua_setfield(L, 1, "arch");
3865
3866 assert(lua_gettop(L) == 1);
3867
3868 return 0;
3869 }
3870
3871 static void setup_mt(lua_State* L, const luaL_Reg* mt, int upvals)
3872 {
3873 lua_pushboolean(L, 1);
3874 lua_setfield(L, -upvals-2, "__metatable");
3875 luaL_setfuncs(L, mt, upvals);
3876 }
3877
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 }