Fix compilation on OpenBSD.
[luajit-2.0.git] / src / lj_cconv.c
blob818c1f440939605e6d3f05a5c0e693c6f3bc8933
1 /*
2 ** C type conversions.
3 ** Copyright (C) 2005-2012 Mike Pall. See Copyright Notice in luajit.h
4 */
6 #include "lj_obj.h"
8 #if LJ_HASFFI
10 #include "lj_err.h"
11 #include "lj_tab.h"
12 #include "lj_ctype.h"
13 #include "lj_cdata.h"
14 #include "lj_cconv.h"
15 #include "lj_ccallback.h"
17 /* -- Conversion errors --------------------------------------------------- */
19 /* Bad conversion. */
20 LJ_NORET static void cconv_err_conv(CTState *cts, CType *d, CType *s,
21 CTInfo flags)
23 const char *dst = strdata(lj_ctype_repr(cts->L, ctype_typeid(cts, d), NULL));
24 const char *src;
25 if ((flags & CCF_FROMTV))
26 src = lj_obj_typename[1+(ctype_isnum(s->info) ? LUA_TNUMBER :
27 ctype_isarray(s->info) ? LUA_TSTRING : LUA_TNIL)];
28 else
29 src = strdata(lj_ctype_repr(cts->L, ctype_typeid(cts, s), NULL));
30 if (CCF_GETARG(flags))
31 lj_err_argv(cts->L, CCF_GETARG(flags), LJ_ERR_FFI_BADCONV, src, dst);
32 else
33 lj_err_callerv(cts->L, LJ_ERR_FFI_BADCONV, src, dst);
36 /* Bad conversion from TValue. */
37 LJ_NORET static void cconv_err_convtv(CTState *cts, CType *d, TValue *o,
38 CTInfo flags)
40 const char *dst = strdata(lj_ctype_repr(cts->L, ctype_typeid(cts, d), NULL));
41 const char *src = typename(o);
42 if (CCF_GETARG(flags))
43 lj_err_argv(cts->L, CCF_GETARG(flags), LJ_ERR_FFI_BADCONV, src, dst);
44 else
45 lj_err_callerv(cts->L, LJ_ERR_FFI_BADCONV, src, dst);
48 /* Initializer overflow. */
49 LJ_NORET static void cconv_err_initov(CTState *cts, CType *d)
51 const char *dst = strdata(lj_ctype_repr(cts->L, ctype_typeid(cts, d), NULL));
52 lj_err_callerv(cts->L, LJ_ERR_FFI_INITOV, dst);
55 /* -- C type compatibility checks ----------------------------------------- */
57 /* Get raw type and qualifiers for a child type. Resolves enums, too. */
58 static CType *cconv_childqual(CTState *cts, CType *ct, CTInfo *qual)
60 ct = ctype_child(cts, ct);
61 for (;;) {
62 if (ctype_isattrib(ct->info)) {
63 if (ctype_attrib(ct->info) == CTA_QUAL) *qual |= ct->size;
64 } else if (!ctype_isenum(ct->info)) {
65 break;
67 ct = ctype_child(cts, ct);
69 *qual |= (ct->info & CTF_QUAL);
70 return ct;
73 /* Check for compatible types when converting to a pointer.
74 ** Note: these checks are more relaxed than what C99 mandates.
76 int lj_cconv_compatptr(CTState *cts, CType *d, CType *s, CTInfo flags)
78 if (!((flags & CCF_CAST) || d == s)) {
79 CTInfo dqual = 0, squal = 0;
80 d = cconv_childqual(cts, d, &dqual);
81 if (!ctype_isstruct(s->info))
82 s = cconv_childqual(cts, s, &squal);
83 if ((flags & CCF_SAME)) {
84 if (dqual != squal)
85 return 0; /* Different qualifiers. */
86 } else if (!(flags & CCF_IGNQUAL)) {
87 if ((dqual & squal) != squal)
88 return 0; /* Discarded qualifiers. */
89 if (ctype_isvoid(d->info) || ctype_isvoid(s->info))
90 return 1; /* Converting to/from void * is always ok. */
92 if (ctype_type(d->info) != ctype_type(s->info) ||
93 d->size != s->size)
94 return 0; /* Different type or different size. */
95 if (ctype_isnum(d->info)) {
96 if (((d->info ^ s->info) & (CTF_BOOL|CTF_FP)))
97 return 0; /* Different numeric types. */
98 } else if (ctype_ispointer(d->info)) {
99 /* Check child types for compatibility. */
100 return lj_cconv_compatptr(cts, d, s, flags|CCF_SAME);
101 } else if (ctype_isstruct(d->info)) {
102 if (d != s)
103 return 0; /* Must be exact same type for struct/union. */
104 } else if (ctype_isfunc(d->info)) {
105 /* NYI: structural equality of functions. */
108 return 1; /* Types are compatible. */
111 /* -- C type to C type conversion ----------------------------------------- */
113 /* Convert C type to C type. Caveat: expects to get the raw CType!
115 ** Note: This is only used by the interpreter and not optimized at all.
116 ** The JIT compiler will do a much better job specializing for each case.
118 void lj_cconv_ct_ct(CTState *cts, CType *d, CType *s,
119 uint8_t *dp, uint8_t *sp, CTInfo flags)
121 CTSize dsize = d->size, ssize = s->size;
122 CTInfo dinfo = d->info, sinfo = s->info;
123 void *tmpptr;
125 lua_assert(!ctype_isenum(dinfo) && !ctype_isenum(sinfo));
126 lua_assert(!ctype_isattrib(dinfo) && !ctype_isattrib(sinfo));
128 if (ctype_type(dinfo) > CT_MAYCONVERT || ctype_type(sinfo) > CT_MAYCONVERT)
129 goto err_conv;
131 /* Some basic sanity checks. */
132 lua_assert(!ctype_isnum(dinfo) || dsize > 0);
133 lua_assert(!ctype_isnum(sinfo) || ssize > 0);
134 lua_assert(!ctype_isbool(dinfo) || dsize == 1);
135 lua_assert(!ctype_isbool(sinfo) || ssize == 1);
136 lua_assert(!ctype_isinteger(dinfo) || (1u<<lj_fls(dsize)) == dsize);
137 lua_assert(!ctype_isinteger(sinfo) || (1u<<lj_fls(ssize)) == ssize);
139 switch (cconv_idx2(dinfo, sinfo)) {
140 /* Destination is a bool. */
141 case CCX(B, B):
142 *dp = *sp; /* Source operand is already normalized. */
143 break;
144 case CCX(B, I): {
145 MSize i;
146 uint8_t b = 0;
147 for (i = 0; i < ssize; i++) b |= sp[i];
148 *dp = (b != 0);
149 break;
151 case CCX(B, F): {
152 uint8_t b;
153 if (ssize == sizeof(double)) b = (*(double *)sp != 0);
154 else if (ssize == sizeof(float)) b = (*(float *)sp != 0);
155 else goto err_conv; /* NYI: long double. */
156 *dp = b;
157 break;
160 /* Destination is an integer. */
161 case CCX(I, B):
162 case CCX(I, I):
163 conv_I_I:
164 if (dsize > ssize) { /* Zero-extend or sign-extend LSB. */
165 #if LJ_LE
166 uint8_t fill = (!(sinfo & CTF_UNSIGNED) && (sp[ssize-1]&0x80)) ? 0xff : 0;
167 memcpy(dp, sp, ssize);
168 memset(dp + ssize, fill, dsize-ssize);
169 #else
170 uint8_t fill = (!(sinfo & CTF_UNSIGNED) && (sp[0]&0x80)) ? 0xff : 0;
171 memset(dp, fill, dsize-ssize);
172 memcpy(dp + (dsize-ssize), sp, ssize);
173 #endif
174 } else { /* Copy LSB. */
175 #if LJ_LE
176 memcpy(dp, sp, dsize);
177 #else
178 memcpy(dp, sp + (ssize-dsize), dsize);
179 #endif
181 break;
182 case CCX(I, F): {
183 double n; /* Always convert via double. */
184 conv_I_F:
185 /* Convert source to double. */
186 if (ssize == sizeof(double)) n = *(double *)sp;
187 else if (ssize == sizeof(float)) n = (double)*(float *)sp;
188 else goto err_conv; /* NYI: long double. */
189 /* Then convert double to integer. */
190 /* The conversion must exactly match the semantics of JIT-compiled code! */
191 if (dsize < 4 || (dsize == 4 && !(dinfo & CTF_UNSIGNED))) {
192 int32_t i = (int32_t)n;
193 if (dsize == 4) *(int32_t *)dp = i;
194 else if (dsize == 2) *(int16_t *)dp = (int16_t)i;
195 else *(int8_t *)dp = (int8_t)i;
196 } else if (dsize == 4) {
197 *(uint32_t *)dp = (uint32_t)n;
198 } else if (dsize == 8) {
199 if (!(dinfo & CTF_UNSIGNED))
200 *(int64_t *)dp = (int64_t)n;
201 else
202 *(uint64_t *)dp = lj_num2u64(n);
203 } else {
204 goto err_conv; /* NYI: conversion to >64 bit integers. */
206 break;
208 case CCX(I, C):
209 s = ctype_child(cts, s);
210 sinfo = s->info;
211 ssize = s->size;
212 goto conv_I_F; /* Just convert re. */
213 case CCX(I, P):
214 if (!(flags & CCF_CAST)) goto err_conv;
215 sinfo = CTINFO(CT_NUM, CTF_UNSIGNED);
216 goto conv_I_I;
217 case CCX(I, A):
218 if (!(flags & CCF_CAST)) goto err_conv;
219 sinfo = CTINFO(CT_NUM, CTF_UNSIGNED);
220 ssize = CTSIZE_PTR;
221 tmpptr = sp;
222 sp = (uint8_t *)&tmpptr;
223 goto conv_I_I;
225 /* Destination is a floating-point number. */
226 case CCX(F, B):
227 case CCX(F, I): {
228 double n; /* Always convert via double. */
229 conv_F_I:
230 /* First convert source to double. */
231 /* The conversion must exactly match the semantics of JIT-compiled code! */
232 if (ssize < 4 || (ssize == 4 && !(sinfo & CTF_UNSIGNED))) {
233 int32_t i;
234 if (ssize == 4) {
235 i = *(int32_t *)sp;
236 } else if (!(sinfo & CTF_UNSIGNED)) {
237 if (ssize == 2) i = *(int16_t *)sp;
238 else i = *(int8_t *)sp;
239 } else {
240 if (ssize == 2) i = *(uint16_t *)sp;
241 else i = *(uint8_t *)sp;
243 n = (double)i;
244 } else if (ssize == 4) {
245 n = (double)*(uint32_t *)sp;
246 } else if (ssize == 8) {
247 if (!(sinfo & CTF_UNSIGNED)) n = (double)*(int64_t *)sp;
248 else n = (double)*(uint64_t *)sp;
249 } else {
250 goto err_conv; /* NYI: conversion from >64 bit integers. */
252 /* Convert double to destination. */
253 if (dsize == sizeof(double)) *(double *)dp = n;
254 else if (dsize == sizeof(float)) *(float *)dp = (float)n;
255 else goto err_conv; /* NYI: long double. */
256 break;
258 case CCX(F, F): {
259 double n; /* Always convert via double. */
260 conv_F_F:
261 if (ssize == dsize) goto copyval;
262 /* Convert source to double. */
263 if (ssize == sizeof(double)) n = *(double *)sp;
264 else if (ssize == sizeof(float)) n = (double)*(float *)sp;
265 else goto err_conv; /* NYI: long double. */
266 /* Convert double to destination. */
267 if (dsize == sizeof(double)) *(double *)dp = n;
268 else if (dsize == sizeof(float)) *(float *)dp = (float)n;
269 else goto err_conv; /* NYI: long double. */
270 break;
272 case CCX(F, C):
273 s = ctype_child(cts, s);
274 sinfo = s->info;
275 ssize = s->size;
276 goto conv_F_F; /* Ignore im, and convert from re. */
278 /* Destination is a complex number. */
279 case CCX(C, I):
280 d = ctype_child(cts, d);
281 dinfo = d->info;
282 dsize = d->size;
283 memset(dp + dsize, 0, dsize); /* Clear im. */
284 goto conv_F_I; /* Convert to re. */
285 case CCX(C, F):
286 d = ctype_child(cts, d);
287 dinfo = d->info;
288 dsize = d->size;
289 memset(dp + dsize, 0, dsize); /* Clear im. */
290 goto conv_F_F; /* Convert to re. */
292 case CCX(C, C):
293 if (dsize != ssize) { /* Different types: convert re/im separately. */
294 CType *dc = ctype_child(cts, d);
295 CType *sc = ctype_child(cts, s);
296 lj_cconv_ct_ct(cts, dc, sc, dp, sp, flags);
297 lj_cconv_ct_ct(cts, dc, sc, dp + dc->size, sp + sc->size, flags);
298 return;
300 goto copyval; /* Otherwise this is easy. */
302 /* Destination is a vector. */
303 case CCX(V, I):
304 case CCX(V, F):
305 case CCX(V, C): {
306 CType *dc = ctype_child(cts, d);
307 CTSize esize;
308 /* First convert the scalar to the first element. */
309 lj_cconv_ct_ct(cts, dc, s, dp, sp, flags);
310 /* Then replicate it to the other elements (splat). */
311 for (sp = dp, esize = dc->size; dsize > esize; dsize -= esize) {
312 dp += esize;
313 memcpy(dp, sp, esize);
315 break;
318 case CCX(V, V):
319 /* Copy same-sized vectors, even for different lengths/element-types. */
320 if (dsize != ssize) goto err_conv;
321 goto copyval;
323 /* Destination is a pointer. */
324 case CCX(P, I):
325 if (!(flags & CCF_CAST)) goto err_conv;
326 dinfo = CTINFO(CT_NUM, CTF_UNSIGNED);
327 goto conv_I_I;
329 case CCX(P, F):
330 if (!(flags & CCF_CAST) || !(flags & CCF_FROMTV)) goto err_conv;
331 /* The signed conversion is cheaper. x64 really has 47 bit pointers. */
332 dinfo = CTINFO(CT_NUM, (LJ_64 && dsize == 8) ? 0 : CTF_UNSIGNED);
333 goto conv_I_F;
335 case CCX(P, P):
336 if (!lj_cconv_compatptr(cts, d, s, flags)) goto err_conv;
337 cdata_setptr(dp, dsize, cdata_getptr(sp, ssize));
338 break;
340 case CCX(P, A):
341 case CCX(P, S):
342 if (!lj_cconv_compatptr(cts, d, s, flags)) goto err_conv;
343 cdata_setptr(dp, dsize, sp);
344 break;
346 /* Destination is an array. */
347 case CCX(A, A):
348 if ((flags & CCF_CAST) || (d->info & CTF_VLA) || dsize != ssize ||
349 d->size == CTSIZE_INVALID || !lj_cconv_compatptr(cts, d, s, flags))
350 goto err_conv;
351 goto copyval;
353 /* Destination is a struct/union. */
354 case CCX(S, S):
355 if ((flags & CCF_CAST) || (d->info & CTF_VLA) || d != s)
356 goto err_conv; /* Must be exact same type. */
357 copyval: /* Copy value. */
358 lua_assert(dsize == ssize);
359 memcpy(dp, sp, dsize);
360 break;
362 default:
363 err_conv:
364 cconv_err_conv(cts, d, s, flags);
368 /* -- C type to TValue conversion ----------------------------------------- */
370 /* Convert C type to TValue. Caveat: expects to get the raw CType! */
371 int lj_cconv_tv_ct(CTState *cts, CType *s, CTypeID sid,
372 TValue *o, uint8_t *sp)
374 CTInfo sinfo = s->info;
375 lua_assert(!ctype_isenum(sinfo));
376 if (ctype_isnum(sinfo)) {
377 if (!ctype_isbool(sinfo)) {
378 if (ctype_isinteger(sinfo) && s->size > 4) goto copyval;
379 if (LJ_DUALNUM && ctype_isinteger(sinfo)) {
380 int32_t i;
381 lj_cconv_ct_ct(cts, ctype_get(cts, CTID_INT32), s,
382 (uint8_t *)&i, sp, 0);
383 if ((sinfo & CTF_UNSIGNED) && i < 0)
384 setnumV(o, (lua_Number)(uint32_t)i);
385 else
386 setintV(o, i);
387 } else {
388 lj_cconv_ct_ct(cts, ctype_get(cts, CTID_DOUBLE), s,
389 (uint8_t *)&o->n, sp, 0);
390 /* Numbers are NOT canonicalized here! Beware of uninitialized data. */
391 lua_assert(tvisnum(o));
393 } else {
394 uint32_t b = (*sp != 0);
395 setboolV(o, b);
396 setboolV(&cts->g->tmptv2, b); /* Remember for trace recorder. */
398 return 0;
399 } else if (ctype_isrefarray(sinfo) || ctype_isstruct(sinfo)) {
400 /* Create reference. */
401 setcdataV(cts->L, o, lj_cdata_newref(cts, sp, sid));
402 return 1; /* Need GC step. */
403 } else {
404 GCcdata *cd;
405 CTSize sz;
406 copyval: /* Copy value. */
407 sz = s->size;
408 lua_assert(sz != CTSIZE_INVALID);
409 /* Attributes are stripped, qualifiers are kept (but mostly ignored). */
410 cd = lj_cdata_new(cts, ctype_typeid(cts, s), sz);
411 setcdataV(cts->L, o, cd);
412 memcpy(cdataptr(cd), sp, sz);
413 return 1; /* Need GC step. */
417 /* Convert bitfield to TValue. */
418 int lj_cconv_tv_bf(CTState *cts, CType *s, TValue *o, uint8_t *sp)
420 CTInfo info = s->info;
421 CTSize pos, bsz;
422 uint32_t val;
423 lua_assert(ctype_isbitfield(info));
424 /* NYI: packed bitfields may cause misaligned reads. */
425 switch (ctype_bitcsz(info)) {
426 case 4: val = *(uint32_t *)sp; break;
427 case 2: val = *(uint16_t *)sp; break;
428 case 1: val = *(uint8_t *)sp; break;
429 default: lua_assert(0); val = 0; break;
431 /* Check if a packed bitfield crosses a container boundary. */
432 pos = ctype_bitpos(info);
433 bsz = ctype_bitbsz(info);
434 lua_assert(pos < 8*ctype_bitcsz(info));
435 lua_assert(bsz > 0 && bsz <= 8*ctype_bitcsz(info));
436 if (pos + bsz > 8*ctype_bitcsz(info))
437 lj_err_caller(cts->L, LJ_ERR_FFI_NYIPACKBIT);
438 if (!(info & CTF_BOOL)) {
439 CTSize shift = 32 - bsz;
440 if (!(info & CTF_UNSIGNED)) {
441 setintV(o, (int32_t)(val << (shift-pos)) >> shift);
442 } else {
443 val = (val << (shift-pos)) >> shift;
444 if (!LJ_DUALNUM || (int32_t)val < 0)
445 setnumV(o, (lua_Number)(uint32_t)val);
446 else
447 setintV(o, (int32_t)val);
449 } else {
450 lua_assert(bsz == 1);
451 setboolV(o, (val >> pos) & 1);
453 return 0; /* No GC step needed. */
456 /* -- TValue to C type conversion ----------------------------------------- */
458 /* Convert table to array. */
459 static void cconv_array_tab(CTState *cts, CType *d,
460 uint8_t *dp, GCtab *t, CTInfo flags)
462 int32_t i;
463 CType *dc = ctype_rawchild(cts, d); /* Array element type. */
464 CTSize size = d->size, esize = dc->size, ofs = 0;
465 for (i = 0; ; i++) {
466 TValue *tv = (TValue *)lj_tab_getint(t, i);
467 if (!tv || tvisnil(tv)) {
468 if (i == 0) continue; /* Try again for 1-based tables. */
469 break; /* Stop at first nil. */
471 if (ofs >= size)
472 cconv_err_initov(cts, d);
473 lj_cconv_ct_tv(cts, dc, dp + ofs, tv, flags);
474 ofs += esize;
476 if (size != CTSIZE_INVALID) { /* Only fill up arrays with known size. */
477 if (ofs == esize) { /* Replicate a single element. */
478 for (; ofs < size; ofs += esize) memcpy(dp + ofs, dp, esize);
479 } else { /* Otherwise fill the remainder with zero. */
480 memset(dp + ofs, 0, size - ofs);
485 /* Convert table to sub-struct/union. */
486 static void cconv_substruct_tab(CTState *cts, CType *d, uint8_t *dp,
487 GCtab *t, int32_t *ip, CTInfo flags)
489 CTypeID id = d->sib;
490 while (id) {
491 CType *df = ctype_get(cts, id);
492 id = df->sib;
493 if (ctype_isfield(df->info) || ctype_isbitfield(df->info)) {
494 TValue *tv;
495 int32_t i = *ip;
496 if (!gcref(df->name)) continue; /* Ignore unnamed fields. */
497 if (i >= 0) {
498 retry:
499 tv = (TValue *)lj_tab_getint(t, i);
500 if (!tv || tvisnil(tv)) {
501 if (i == 0) { i = 1; goto retry; } /* 1-based tables. */
502 break; /* Stop at first nil. */
504 *ip = i + 1;
505 } else {
506 tv = (TValue *)lj_tab_getstr(t, gco2str(gcref(df->name)));
507 if (!tv || tvisnil(tv)) continue;
509 if (ctype_isfield(df->info))
510 lj_cconv_ct_tv(cts, ctype_rawchild(cts, df), dp+df->size, tv, flags);
511 else
512 lj_cconv_bf_tv(cts, df, dp+df->size, tv);
513 if ((d->info & CTF_UNION)) break;
514 } else if (ctype_isxattrib(df->info, CTA_SUBTYPE)) {
515 cconv_substruct_tab(cts, ctype_child(cts, df), dp+df->size, t, ip, flags);
516 } /* Ignore all other entries in the chain. */
520 /* Convert table to struct/union. */
521 static void cconv_struct_tab(CTState *cts, CType *d,
522 uint8_t *dp, GCtab *t, CTInfo flags)
524 int32_t i = 0;
525 memset(dp, 0, d->size); /* Much simpler to clear the struct first. */
526 if (t->hmask) i = -1; else if (t->asize == 0) return; /* Fast exit. */
527 cconv_substruct_tab(cts, d, dp, t, &i, flags);
530 /* Convert TValue to C type. Caveat: expects to get the raw CType! */
531 void lj_cconv_ct_tv(CTState *cts, CType *d,
532 uint8_t *dp, TValue *o, CTInfo flags)
534 CTypeID sid = CTID_P_VOID;
535 CType *s;
536 void *tmpptr;
537 uint8_t tmpbool, *sp = (uint8_t *)&tmpptr;
538 if (LJ_LIKELY(tvisint(o))) {
539 sp = (uint8_t *)&o->i;
540 sid = CTID_INT32;
541 flags |= CCF_FROMTV;
542 } else if (LJ_LIKELY(tvisnum(o))) {
543 sp = (uint8_t *)&o->n;
544 sid = CTID_DOUBLE;
545 flags |= CCF_FROMTV;
546 } else if (tviscdata(o)) {
547 sp = cdataptr(cdataV(o));
548 sid = cdataV(o)->typeid;
549 s = ctype_get(cts, sid);
550 if (ctype_isref(s->info)) { /* Resolve reference for value. */
551 lua_assert(s->size == CTSIZE_PTR);
552 sp = *(void **)sp;
553 sid = ctype_cid(s->info);
555 s = ctype_raw(cts, sid);
556 if (ctype_isfunc(s->info)) {
557 sid = lj_ctype_intern(cts, CTINFO(CT_PTR, CTALIGN_PTR|sid), CTSIZE_PTR);
558 } else {
559 if (ctype_isenum(s->info)) s = ctype_child(cts, s);
560 goto doconv;
562 } else if (tvisstr(o)) {
563 GCstr *str = strV(o);
564 if (ctype_isenum(d->info)) { /* Match string against enum constant. */
565 CTSize ofs;
566 CType *cct = lj_ctype_getfield(cts, d, str, &ofs);
567 if (!cct || !ctype_isconstval(cct->info))
568 goto err_conv;
569 lua_assert(d->size == 4);
570 sp = (uint8_t *)&cct->size;
571 sid = ctype_cid(cct->info);
572 } else if (ctype_isrefarray(d->info)) { /* Copy string to array. */
573 CType *dc = ctype_rawchild(cts, d);
574 CTSize sz = str->len+1;
575 if (!ctype_isinteger(dc->info) || dc->size != 1)
576 goto err_conv;
577 if (d->size != 0 && d->size < sz)
578 sz = d->size;
579 memcpy(dp, strdata(str), sz);
580 return;
581 } else { /* Otherwise pass it as a const char[]. */
582 sp = (uint8_t *)strdata(str);
583 sid = CTID_A_CCHAR;
584 flags |= CCF_FROMTV;
586 } else if (tvistab(o)) {
587 if (ctype_isarray(d->info)) {
588 cconv_array_tab(cts, d, dp, tabV(o), flags);
589 return;
590 } else if (ctype_isstruct(d->info)) {
591 cconv_struct_tab(cts, d, dp, tabV(o), flags);
592 return;
593 } else {
594 goto err_conv;
596 } else if (tvisbool(o)) {
597 tmpbool = boolV(o);
598 sp = &tmpbool;
599 sid = CTID_BOOL;
600 } else if (tvisnil(o)) {
601 tmpptr = (void *)0;
602 flags |= CCF_FROMTV;
603 } else if (tvisudata(o)) {
604 tmpptr = uddata(udataV(o));
605 } else if (tvislightud(o)) {
606 tmpptr = lightudV(o);
607 } else if (tvisfunc(o)) {
608 void *p = lj_ccallback_new(cts, d, funcV(o));
609 if (p) {
610 *(void **)dp = p;
611 return;
613 goto err_conv;
614 } else {
615 err_conv:
616 cconv_err_convtv(cts, d, o, flags);
618 s = ctype_get(cts, sid);
619 doconv:
620 if (ctype_isenum(d->info)) d = ctype_child(cts, d);
621 lj_cconv_ct_ct(cts, d, s, dp, sp, flags);
624 /* Convert TValue to bitfield. */
625 void lj_cconv_bf_tv(CTState *cts, CType *d, uint8_t *dp, TValue *o)
627 CTInfo info = d->info;
628 CTSize pos, bsz;
629 uint32_t val, mask;
630 lua_assert(ctype_isbitfield(info));
631 if ((info & CTF_BOOL)) {
632 uint8_t tmpbool;
633 lua_assert(ctype_bitbsz(info) == 1);
634 lj_cconv_ct_tv(cts, ctype_get(cts, CTID_BOOL), &tmpbool, o, 0);
635 val = tmpbool;
636 } else {
637 CTypeID did = (info & CTF_UNSIGNED) ? CTID_UINT32 : CTID_INT32;
638 lj_cconv_ct_tv(cts, ctype_get(cts, did), (uint8_t *)&val, o, 0);
640 pos = ctype_bitpos(info);
641 bsz = ctype_bitbsz(info);
642 lua_assert(pos < 8*ctype_bitcsz(info));
643 lua_assert(bsz > 0 && bsz <= 8*ctype_bitcsz(info));
644 /* Check if a packed bitfield crosses a container boundary. */
645 if (pos + bsz > 8*ctype_bitcsz(info))
646 lj_err_caller(cts->L, LJ_ERR_FFI_NYIPACKBIT);
647 mask = ((1u << bsz) - 1u) << pos;
648 val = (val << pos) & mask;
649 /* NYI: packed bitfields may cause misaligned reads/writes. */
650 switch (ctype_bitcsz(info)) {
651 case 4: *(uint32_t *)dp = (*(uint32_t *)dp & ~mask) | (uint32_t)val; break;
652 case 2: *(uint16_t *)dp = (*(uint16_t *)dp & ~mask) | (uint16_t)val; break;
653 case 1: *(uint8_t *)dp = (*(uint8_t *)dp & ~mask) | (uint8_t)val; break;
654 default: lua_assert(0); break;
658 /* -- Initialize C type with TValues -------------------------------------- */
660 /* Initialize an array with TValues. */
661 static void cconv_array_init(CTState *cts, CType *d, CTSize sz, uint8_t *dp,
662 TValue *o, MSize len)
664 CType *dc = ctype_rawchild(cts, d); /* Array element type. */
665 CTSize ofs, esize = dc->size;
666 MSize i;
667 if (len*esize > sz)
668 cconv_err_initov(cts, d);
669 for (i = 0, ofs = 0; i < len; i++, ofs += esize)
670 lj_cconv_ct_tv(cts, dc, dp + ofs, o + i, 0);
671 if (ofs == esize) { /* Replicate a single element. */
672 for (; ofs < sz; ofs += esize) memcpy(dp + ofs, dp, esize);
673 } else { /* Otherwise fill the remainder with zero. */
674 memset(dp + ofs, 0, sz - ofs);
678 /* Initialize a sub-struct/union with TValues. */
679 static void cconv_substruct_init(CTState *cts, CType *d, uint8_t *dp,
680 TValue *o, MSize len, MSize *ip)
682 CTypeID id = d->sib;
683 while (id) {
684 CType *df = ctype_get(cts, id);
685 id = df->sib;
686 if (ctype_isfield(df->info) || ctype_isbitfield(df->info)) {
687 MSize i = *ip;
688 if (!gcref(df->name)) continue; /* Ignore unnamed fields. */
689 if (i >= len) break;
690 *ip = i + 1;
691 if (ctype_isfield(df->info))
692 lj_cconv_ct_tv(cts, ctype_rawchild(cts, df), dp+df->size, o + i, 0);
693 else
694 lj_cconv_bf_tv(cts, df, dp+df->size, o + i);
695 if ((d->info & CTF_UNION)) break;
696 } else if (ctype_isxattrib(df->info, CTA_SUBTYPE)) {
697 cconv_substruct_init(cts, ctype_child(cts, df), dp+df->size, o, len, ip);
698 } /* Ignore all other entries in the chain. */
702 /* Initialize a struct/union with TValues. */
703 static void cconv_struct_init(CTState *cts, CType *d, CTSize sz, uint8_t *dp,
704 TValue *o, MSize len)
706 MSize i = 0;
707 memset(dp, 0, sz); /* Much simpler to clear the struct first. */
708 cconv_substruct_init(cts, d, dp, o, len, &i);
709 if (i < len)
710 cconv_err_initov(cts, d);
713 /* Check whether to use a multi-value initializer.
714 ** This is true if an aggregate is to be initialized with a value.
715 ** Valarrays are treated as values here so ct_tv handles (V|C, I|F).
717 int lj_cconv_multi_init(CType *d, TValue *o)
719 if (!(ctype_isrefarray(d->info) || ctype_isstruct(d->info)))
720 return 0; /* Destination is not an aggregate. */
721 if (tvistab(o) || (tvisstr(o) && !ctype_isstruct(d->info)))
722 return 0; /* Initializer is not a value. */
723 return 1; /* Otherwise the initializer is a value. */
726 /* Initialize C type with TValues. Caveat: expects to get the raw CType! */
727 void lj_cconv_ct_init(CTState *cts, CType *d, CTSize sz,
728 uint8_t *dp, TValue *o, MSize len)
730 if (len == 0)
731 memset(dp, 0, sz);
732 else if (len == 1 && !lj_cconv_multi_init(d, o))
733 lj_cconv_ct_tv(cts, d, dp, o, 0);
734 else if (ctype_isarray(d->info)) /* Also handles valarray init with len>1. */
735 cconv_array_init(cts, d, sz, dp, o, len);
736 else if (ctype_isstruct(d->info))
737 cconv_struct_init(cts, d, sz, dp, o, len);
738 else
739 cconv_err_initov(cts, d);
742 #endif