1 /*
2 ** C type conversions.
3 ** Copyright (C) 2005-2021 Mike Pall. See Copyright Notice in luajit.h
4 */
5 
6 #include "lj_obj.h"
7 
8 #if LJ_HASFFI
9 
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"
16 
17 /* -- Conversion errors --------------------------------------------------- */
18 
19 /* Bad conversion. */
cconv_err_conv(CTState * cts,CType * d,CType * s,CTInfo flags)20 LJ_NORET static void cconv_err_conv(CTState *cts, CType *d, CType *s,
21 				    CTInfo flags)
22 {
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);
34 }
35 
36 /* Bad conversion from TValue. */
cconv_err_convtv(CTState * cts,CType * d,TValue * o,CTInfo flags)37 LJ_NORET static void cconv_err_convtv(CTState *cts, CType *d, TValue *o,
38 				      CTInfo flags)
39 {
40   const char *dst = strdata(lj_ctype_repr(cts->L, ctype_typeid(cts, d), NULL));
41   const char *src = lj_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);
46 }
47 
48 /* Initializer overflow. */
cconv_err_initov(CTState * cts,CType * d)49 LJ_NORET static void cconv_err_initov(CTState *cts, CType *d)
50 {
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);
53 }
54 
55 /* -- C type compatibility checks ----------------------------------------- */
56 
57 /* Get raw type and qualifiers for a child type. Resolves enums, too. */
cconv_childqual(CTState * cts,CType * ct,CTInfo * qual)58 static CType *cconv_childqual(CTState *cts, CType *ct, CTInfo *qual)
59 {
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;
66     }
67     ct = ctype_child(cts, ct);
68   }
69   *qual |= (ct->info & CTF_QUAL);
70   return ct;
71 }
72 
73 /* Check for compatible types when converting to a pointer.
74 ** Note: these checks are more relaxed than what C99 mandates.
75 */
lj_cconv_compatptr(CTState * cts,CType * d,CType * s,CTInfo flags)76 int lj_cconv_compatptr(CTState *cts, CType *d, CType *s, CTInfo flags)
77 {
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. */
91     }
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. */
106     }
107   }
108   return 1;  /* Types are compatible. */
109 }
110 
111 /* -- C type to C type conversion ----------------------------------------- */
112 
113 /* Convert C type to C type. Caveat: expects to get the raw CType!
114 **
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.
117 */
lj_cconv_ct_ct(CTState * cts,CType * d,CType * s,uint8_t * dp,uint8_t * sp,CTInfo flags)118 void lj_cconv_ct_ct(CTState *cts, CType *d, CType *s,
119 		    uint8_t *dp, uint8_t *sp, CTInfo flags)
120 {
121   CTSize dsize = d->size, ssize = s->size;
122   CTInfo dinfo = d->info, sinfo = s->info;
123   void *tmpptr;
124 
125   lj_assertCTS(!ctype_isenum(dinfo) && !ctype_isenum(sinfo),
126 	       "unresolved enum");
127   lj_assertCTS(!ctype_isattrib(dinfo) && !ctype_isattrib(sinfo),
128 	       "unstripped attribute");
129 
130   if (ctype_type(dinfo) > CT_MAYCONVERT || ctype_type(sinfo) > CT_MAYCONVERT)
131     goto err_conv;
132 
133   /* Some basic sanity checks. */
134   lj_assertCTS(!ctype_isnum(dinfo) || dsize > 0, "bad size for number type");
135   lj_assertCTS(!ctype_isnum(sinfo) || ssize > 0, "bad size for number type");
136   lj_assertCTS(!ctype_isbool(dinfo) || dsize == 1 || dsize == 4,
137 	       "bad size for bool type");
138   lj_assertCTS(!ctype_isbool(sinfo) || ssize == 1 || ssize == 4,
139 	       "bad size for bool type");
140   lj_assertCTS(!ctype_isinteger(dinfo) || (1u<<lj_fls(dsize)) == dsize,
141 	       "bad size for integer type");
142   lj_assertCTS(!ctype_isinteger(sinfo) || (1u<<lj_fls(ssize)) == ssize,
143 	       "bad size for integer type");
144 
145   switch (cconv_idx2(dinfo, sinfo)) {
146   /* Destination is a bool. */
147   case CCX(B, B):
148     /* Source operand is already normalized. */
149     if (dsize == 1) *dp = *sp; else *(int *)dp = *sp;
150     break;
151   case CCX(B, I): {
152     MSize i;
153     uint8_t b = 0;
154     for (i = 0; i < ssize; i++) b |= sp[i];
155     b = (b != 0);
156     if (dsize == 1) *dp = b; else *(int *)dp = b;
157     break;
158     }
159   case CCX(B, F): {
160     uint8_t b;
161     if (ssize == sizeof(double)) b = (*(double *)sp != 0);
162     else if (ssize == sizeof(float)) b = (*(float *)sp != 0);
163     else goto err_conv;  /* NYI: long double. */
164     if (dsize == 1) *dp = b; else *(int *)dp = b;
165     break;
166     }
167 
168   /* Destination is an integer. */
169   case CCX(I, B):
170   case CCX(I, I):
171   conv_I_I:
172     if (dsize > ssize) {  /* Zero-extend or sign-extend LSB. */
173 #if LJ_LE
174       uint8_t fill = (!(sinfo & CTF_UNSIGNED) && (sp[ssize-1]&0x80)) ? 0xff : 0;
175       memcpy(dp, sp, ssize);
176       memset(dp + ssize, fill, dsize-ssize);
177 #else
178       uint8_t fill = (!(sinfo & CTF_UNSIGNED) && (sp[0]&0x80)) ? 0xff : 0;
179       memset(dp, fill, dsize-ssize);
180       memcpy(dp + (dsize-ssize), sp, ssize);
181 #endif
182     } else {  /* Copy LSB. */
183 #if LJ_LE
184       memcpy(dp, sp, dsize);
185 #else
186       memcpy(dp, sp + (ssize-dsize), dsize);
187 #endif
188     }
189     break;
190   case CCX(I, F): {
191     double n;  /* Always convert via double. */
192   conv_I_F:
193     /* Convert source to double. */
194     if (ssize == sizeof(double)) n = *(double *)sp;
195     else if (ssize == sizeof(float)) n = (double)*(float *)sp;
196     else goto err_conv;  /* NYI: long double. */
197     /* Then convert double to integer. */
198     /* The conversion must exactly match the semantics of JIT-compiled code! */
199     if (dsize < 4 || (dsize == 4 && !(dinfo & CTF_UNSIGNED))) {
200       int32_t i = (int32_t)n;
201       if (dsize == 4) *(int32_t *)dp = i;
202       else if (dsize == 2) *(int16_t *)dp = (int16_t)i;
203       else *(int8_t *)dp = (int8_t)i;
204     } else if (dsize == 4) {
205       *(uint32_t *)dp = (uint32_t)n;
206     } else if (dsize == 8) {
207       if (!(dinfo & CTF_UNSIGNED))
208 	*(int64_t *)dp = (int64_t)n;
209       else
210 	*(uint64_t *)dp = lj_num2u64(n);
211     } else {
212       goto err_conv;  /* NYI: conversion to >64 bit integers. */
213     }
214     break;
215     }
216   case CCX(I, C):
217     s = ctype_child(cts, s);
218     sinfo = s->info;
219     ssize = s->size;
220     goto conv_I_F;  /* Just convert re. */
221   case CCX(I, P):
222     if (!(flags & CCF_CAST)) goto err_conv;
223     sinfo = CTINFO(CT_NUM, CTF_UNSIGNED);
224     goto conv_I_I;
225   case CCX(I, A):
226     if (!(flags & CCF_CAST)) goto err_conv;
227     sinfo = CTINFO(CT_NUM, CTF_UNSIGNED);
228     ssize = CTSIZE_PTR;
229     tmpptr = sp;
230     sp = (uint8_t *)&tmpptr;
231     goto conv_I_I;
232 
233   /* Destination is a floating-point number. */
234   case CCX(F, B):
235   case CCX(F, I): {
236     double n;  /* Always convert via double. */
237   conv_F_I:
238     /* First convert source to double. */
239     /* The conversion must exactly match the semantics of JIT-compiled code! */
240     if (ssize < 4 || (ssize == 4 && !(sinfo & CTF_UNSIGNED))) {
241       int32_t i;
242       if (ssize == 4) {
243 	i = *(int32_t *)sp;
244       } else if (!(sinfo & CTF_UNSIGNED)) {
245 	if (ssize == 2) i = *(int16_t *)sp;
246 	else i = *(int8_t *)sp;
247       } else {
248 	if (ssize == 2) i = *(uint16_t *)sp;
249 	else i = *(uint8_t *)sp;
250       }
251       n = (double)i;
252     } else if (ssize == 4) {
253       n = (double)*(uint32_t *)sp;
254     } else if (ssize == 8) {
255       if (!(sinfo & CTF_UNSIGNED)) n = (double)*(int64_t *)sp;
256       else n = (double)*(uint64_t *)sp;
257     } else {
258       goto err_conv;  /* NYI: conversion from >64 bit integers. */
259     }
260     /* Convert double to destination. */
261     if (dsize == sizeof(double)) *(double *)dp = n;
262     else if (dsize == sizeof(float)) *(float *)dp = (float)n;
263     else goto err_conv;  /* NYI: long double. */
264     break;
265     }
266   case CCX(F, F): {
267     double n;  /* Always convert via double. */
268   conv_F_F:
269     if (ssize == dsize) goto copyval;
270     /* Convert source to double. */
271     if (ssize == sizeof(double)) n = *(double *)sp;
272     else if (ssize == sizeof(float)) n = (double)*(float *)sp;
273     else goto err_conv;  /* NYI: long double. */
274     /* Convert double to destination. */
275     if (dsize == sizeof(double)) *(double *)dp = n;
276     else if (dsize == sizeof(float)) *(float *)dp = (float)n;
277     else goto err_conv;  /* NYI: long double. */
278     break;
279     }
280   case CCX(F, C):
281     s = ctype_child(cts, s);
282     sinfo = s->info;
283     ssize = s->size;
284     goto conv_F_F;  /* Ignore im, and convert from re. */
285 
286   /* Destination is a complex number. */
287   case CCX(C, I):
288     d = ctype_child(cts, d);
289     dinfo = d->info;
290     dsize = d->size;
291     memset(dp + dsize, 0, dsize);  /* Clear im. */
292     goto conv_F_I;  /* Convert to re. */
293   case CCX(C, F):
294     d = ctype_child(cts, d);
295     dinfo = d->info;
296     dsize = d->size;
297     memset(dp + dsize, 0, dsize);  /* Clear im. */
298     goto conv_F_F;  /* Convert to re. */
299 
300   case CCX(C, C):
301     if (dsize != ssize) {  /* Different types: convert re/im separately. */
302       CType *dc = ctype_child(cts, d);
303       CType *sc = ctype_child(cts, s);
304       lj_cconv_ct_ct(cts, dc, sc, dp, sp, flags);
305       lj_cconv_ct_ct(cts, dc, sc, dp + dc->size, sp + sc->size, flags);
306       return;
307     }
308     goto copyval;  /* Otherwise this is easy. */
309 
310   /* Destination is a vector. */
311   case CCX(V, I):
312   case CCX(V, F):
313   case CCX(V, C): {
314     CType *dc = ctype_child(cts, d);
315     CTSize esize;
316     /* First convert the scalar to the first element. */
317     lj_cconv_ct_ct(cts, dc, s, dp, sp, flags);
318     /* Then replicate it to the other elements (splat). */
319     for (sp = dp, esize = dc->size; dsize > esize; dsize -= esize) {
320       dp += esize;
321       memcpy(dp, sp, esize);
322     }
323     break;
324     }
325 
326   case CCX(V, V):
327     /* Copy same-sized vectors, even for different lengths/element-types. */
328     if (dsize != ssize) goto err_conv;
329     goto copyval;
330 
331   /* Destination is a pointer. */
332   case CCX(P, I):
333     if (!(flags & CCF_CAST)) goto err_conv;
334     dinfo = CTINFO(CT_NUM, CTF_UNSIGNED);
335     goto conv_I_I;
336 
337   case CCX(P, F):
338     if (!(flags & CCF_CAST) || !(flags & CCF_FROMTV)) goto err_conv;
339     /* The signed conversion is cheaper. x64 really has 47 bit pointers. */
340     dinfo = CTINFO(CT_NUM, (LJ_64 && dsize == 8) ? 0 : CTF_UNSIGNED);
341     goto conv_I_F;
342 
343   case CCX(P, P):
344     if (!lj_cconv_compatptr(cts, d, s, flags)) goto err_conv;
345     cdata_setptr(dp, dsize, cdata_getptr(sp, ssize));
346     break;
347 
348   case CCX(P, A):
349   case CCX(P, S):
350     if (!lj_cconv_compatptr(cts, d, s, flags)) goto err_conv;
351     cdata_setptr(dp, dsize, sp);
352     break;
353 
354   /* Destination is an array. */
355   case CCX(A, A):
356     if ((flags & CCF_CAST) || (d->info & CTF_VLA) || dsize != ssize ||
357 	d->size == CTSIZE_INVALID || !lj_cconv_compatptr(cts, d, s, flags))
358       goto err_conv;
359     goto copyval;
360 
361   /* Destination is a struct/union. */
362   case CCX(S, S):
363     if ((flags & CCF_CAST) || (d->info & CTF_VLA) || d != s)
364       goto err_conv;  /* Must be exact same type. */
365 copyval:  /* Copy value. */
366     lj_assertCTS(dsize == ssize, "value copy with different sizes");
367     memcpy(dp, sp, dsize);
368     break;
369 
370   default:
371   err_conv:
372     cconv_err_conv(cts, d, s, flags);
373   }
374 }
375 
376 /* -- C type to TValue conversion ----------------------------------------- */
377 
378 /* Convert C type to TValue. Caveat: expects to get the raw CType! */
lj_cconv_tv_ct(CTState * cts,CType * s,CTypeID sid,TValue * o,uint8_t * sp)379 int lj_cconv_tv_ct(CTState *cts, CType *s, CTypeID sid,
380 		   TValue *o, uint8_t *sp)
381 {
382   CTInfo sinfo = s->info;
383   if (ctype_isnum(sinfo)) {
384     if (!ctype_isbool(sinfo)) {
385       if (ctype_isinteger(sinfo) && s->size > 4) goto copyval;
386       if (LJ_DUALNUM && ctype_isinteger(sinfo)) {
387 	int32_t i;
388 	lj_cconv_ct_ct(cts, ctype_get(cts, CTID_INT32), s,
389 		       (uint8_t *)&i, sp, 0);
390 	if ((sinfo & CTF_UNSIGNED) && i < 0)
391 	  setnumV(o, (lua_Number)(uint32_t)i);
392 	else
393 	  setintV(o, i);
394       } else {
395 	lj_cconv_ct_ct(cts, ctype_get(cts, CTID_DOUBLE), s,
396 		       (uint8_t *)&o->n, sp, 0);
397 	/* Numbers are NOT canonicalized here! Beware of uninitialized data. */
398 	lj_assertCTS(tvisnum(o), "non-canonical NaN passed");
399       }
400     } else {
401       uint32_t b = s->size == 1 ? (*sp != 0) : (*(int *)sp != 0);
402       setboolV(o, b);
403       setboolV(&cts->g->tmptv2, b);  /* Remember for trace recorder. */
404     }
405     return 0;
406   } else if (ctype_isrefarray(sinfo) || ctype_isstruct(sinfo)) {
407     /* Create reference. */
408     setcdataV(cts->L, o, lj_cdata_newref(cts, sp, sid));
409     return 1;  /* Need GC step. */
410   } else {
411     GCcdata *cd;
412     CTSize sz;
413   copyval:  /* Copy value. */
414     sz = s->size;
415     lj_assertCTS(sz != CTSIZE_INVALID, "value copy with invalid size");
416     /* Attributes are stripped, qualifiers are kept (but mostly ignored). */
417     cd = lj_cdata_new(cts, ctype_typeid(cts, s), sz);
418     setcdataV(cts->L, o, cd);
419     memcpy(cdataptr(cd), sp, sz);
420     return 1;  /* Need GC step. */
421   }
422 }
423 
424 /* Convert bitfield to TValue. */
lj_cconv_tv_bf(CTState * cts,CType * s,TValue * o,uint8_t * sp)425 int lj_cconv_tv_bf(CTState *cts, CType *s, TValue *o, uint8_t *sp)
426 {
427   CTInfo info = s->info;
428   CTSize pos, bsz;
429   uint32_t val;
430   lj_assertCTS(ctype_isbitfield(info), "bitfield expected");
431   /* NYI: packed bitfields may cause misaligned reads. */
432   switch (ctype_bitcsz(info)) {
433   case 4: val = *(uint32_t *)sp; break;
434   case 2: val = *(uint16_t *)sp; break;
435   case 1: val = *(uint8_t *)sp; break;
436   default:
437     lj_assertCTS(0, "bad bitfield container size %d", ctype_bitcsz(info));
438     val = 0;
439     break;
440   }
441   /* Check if a packed bitfield crosses a container boundary. */
442   pos = ctype_bitpos(info);
443   bsz = ctype_bitbsz(info);
444   lj_assertCTS(pos < 8*ctype_bitcsz(info), "bad bitfield position");
445   lj_assertCTS(bsz > 0 && bsz <= 8*ctype_bitcsz(info), "bad bitfield size");
446   if (pos + bsz > 8*ctype_bitcsz(info))
447     lj_err_caller(cts->L, LJ_ERR_FFI_NYIPACKBIT);
448   if (!(info & CTF_BOOL)) {
449     CTSize shift = 32 - bsz;
450     if (!(info & CTF_UNSIGNED)) {
451       setintV(o, (int32_t)(val << (shift-pos)) >> shift);
452     } else {
453       val = (val << (shift-pos)) >> shift;
454       if (!LJ_DUALNUM || (int32_t)val < 0)
455 	setnumV(o, (lua_Number)(uint32_t)val);
456       else
457 	setintV(o, (int32_t)val);
458     }
459   } else {
460     uint32_t b = (val >> pos) & 1;
461     lj_assertCTS(bsz == 1, "bad bool bitfield size");
462     setboolV(o, b);
463     setboolV(&cts->g->tmptv2, b);  /* Remember for trace recorder. */
464   }
465   return 0;  /* No GC step needed. */
466 }
467 
468 /* -- TValue to C type conversion ----------------------------------------- */
469 
470 /* Convert table to array. */
cconv_array_tab(CTState * cts,CType * d,uint8_t * dp,GCtab * t,CTInfo flags)471 static void cconv_array_tab(CTState *cts, CType *d,
472 			    uint8_t *dp, GCtab *t, CTInfo flags)
473 {
474   int32_t i;
475   CType *dc = ctype_rawchild(cts, d);  /* Array element type. */
476   CTSize size = d->size, esize = dc->size, ofs = 0;
477   for (i = 0; ; i++) {
478     TValue *tv = (TValue *)lj_tab_getint(t, i);
479     if (!tv || tvisnil(tv)) {
480       if (i == 0) continue;  /* Try again for 1-based tables. */
481       break;  /* Stop at first nil. */
482     }
483     if (ofs >= size)
484       cconv_err_initov(cts, d);
485     lj_cconv_ct_tv(cts, dc, dp + ofs, tv, flags);
486     ofs += esize;
487   }
488   if (size != CTSIZE_INVALID) {  /* Only fill up arrays with known size. */
489     if (ofs == esize) {  /* Replicate a single element. */
490       for (; ofs < size; ofs += esize) memcpy(dp + ofs, dp, esize);
491     } else {  /* Otherwise fill the remainder with zero. */
492       memset(dp + ofs, 0, size - ofs);
493     }
494   }
495 }
496 
497 /* Convert table to sub-struct/union. */
cconv_substruct_tab(CTState * cts,CType * d,uint8_t * dp,GCtab * t,int32_t * ip,CTInfo flags)498 static void cconv_substruct_tab(CTState *cts, CType *d, uint8_t *dp,
499 				GCtab *t, int32_t *ip, CTInfo flags)
500 {
501   CTypeID id = d->sib;
502   while (id) {
503     CType *df = ctype_get(cts, id);
504     id = df->sib;
505     if (ctype_isfield(df->info) || ctype_isbitfield(df->info)) {
506       TValue *tv;
507       int32_t i = *ip, iz = i;
508       if (!gcref(df->name)) continue;  /* Ignore unnamed fields. */
509       if (i >= 0) {
510       retry:
511 	tv = (TValue *)lj_tab_getint(t, i);
512 	if (!tv || tvisnil(tv)) {
513 	  if (i == 0) { i = 1; goto retry; }  /* 1-based tables. */
514 	  if (iz == 0) { *ip = i = -1; goto tryname; }  /* Init named fields. */
515 	  break;  /* Stop at first nil. */
516 	}
517 	*ip = i + 1;
518       } else {
519       tryname:
520 	tv = (TValue *)lj_tab_getstr(t, gco2str(gcref(df->name)));
521 	if (!tv || tvisnil(tv)) continue;
522       }
523       if (ctype_isfield(df->info))
524 	lj_cconv_ct_tv(cts, ctype_rawchild(cts, df), dp+df->size, tv, flags);
525       else
526 	lj_cconv_bf_tv(cts, df, dp+df->size, tv);
527       if ((d->info & CTF_UNION)) break;
528     } else if (ctype_isxattrib(df->info, CTA_SUBTYPE)) {
529       cconv_substruct_tab(cts, ctype_rawchild(cts, df),
530 			  dp+df->size, t, ip, flags);
531     }  /* Ignore all other entries in the chain. */
532   }
533 }
534 
535 /* Convert table to struct/union. */
cconv_struct_tab(CTState * cts,CType * d,uint8_t * dp,GCtab * t,CTInfo flags)536 static void cconv_struct_tab(CTState *cts, CType *d,
537 			     uint8_t *dp, GCtab *t, CTInfo flags)
538 {
539   int32_t i = 0;
540   memset(dp, 0, d->size);  /* Much simpler to clear the struct first. */
541   cconv_substruct_tab(cts, d, dp, t, &i, flags);
542 }
543 
544 /* Convert TValue to C type. Caveat: expects to get the raw CType! */
lj_cconv_ct_tv(CTState * cts,CType * d,uint8_t * dp,TValue * o,CTInfo flags)545 void lj_cconv_ct_tv(CTState *cts, CType *d,
546 		    uint8_t *dp, TValue *o, CTInfo flags)
547 {
548   CTypeID sid = CTID_P_VOID;
549   CType *s;
550   void *tmpptr;
551   uint8_t tmpbool, *sp = (uint8_t *)&tmpptr;
552   if (LJ_LIKELY(tvisint(o))) {
553     sp = (uint8_t *)&o->i;
554     sid = CTID_INT32;
555     flags |= CCF_FROMTV;
556   } else if (LJ_LIKELY(tvisnum(o))) {
557     sp = (uint8_t *)&o->n;
558     sid = CTID_DOUBLE;
559     flags |= CCF_FROMTV;
560   } else if (tviscdata(o)) {
561     sp = cdataptr(cdataV(o));
562     sid = cdataV(o)->ctypeid;
563     s = ctype_get(cts, sid);
564     if (ctype_isref(s->info)) {  /* Resolve reference for value. */
565       lj_assertCTS(s->size == CTSIZE_PTR, "ref is not pointer-sized");
566       sp = *(void **)sp;
567       sid = ctype_cid(s->info);
568     }
569     s = ctype_raw(cts, sid);
570     if (ctype_isfunc(s->info)) {
571       sid = lj_ctype_intern(cts, CTINFO(CT_PTR, CTALIGN_PTR|sid), CTSIZE_PTR);
572     } else {
573       if (ctype_isenum(s->info)) s = ctype_child(cts, s);
574       goto doconv;
575     }
576   } else if (tvisstr(o)) {
577     GCstr *str = strV(o);
578     if (ctype_isenum(d->info)) {  /* Match string against enum constant. */
579       CTSize ofs;
580       CType *cct = lj_ctype_getfield(cts, d, str, &ofs);
581       if (!cct || !ctype_isconstval(cct->info))
582 	goto err_conv;
583       lj_assertCTS(d->size == 4, "only 32 bit enum supported");  /* NYI */
584       sp = (uint8_t *)&cct->size;
585       sid = ctype_cid(cct->info);
586     } else if (ctype_isrefarray(d->info)) {  /* Copy string to array. */
587       CType *dc = ctype_rawchild(cts, d);
588       CTSize sz = str->len+1;
589       if (!ctype_isinteger(dc->info) || dc->size != 1)
590 	goto err_conv;
591       if (d->size != 0 && d->size < sz)
592 	sz = d->size;
593       memcpy(dp, strdata(str), sz);
594       return;
595     } else {  /* Otherwise pass it as a const char[]. */
596       sp = (uint8_t *)strdata(str);
597       sid = CTID_A_CCHAR;
598       flags |= CCF_FROMTV;
599     }
600   } else if (tvistab(o)) {
601     if (ctype_isarray(d->info)) {
602       cconv_array_tab(cts, d, dp, tabV(o), flags);
603       return;
604     } else if (ctype_isstruct(d->info)) {
605       cconv_struct_tab(cts, d, dp, tabV(o), flags);
606       return;
607     } else {
608       goto err_conv;
609     }
610   } else if (tvisbool(o)) {
611     tmpbool = boolV(o);
612     sp = &tmpbool;
613     sid = CTID_BOOL;
614   } else if (tvisnil(o)) {
615     tmpptr = (void *)0;
616     flags |= CCF_FROMTV;
617   } else if (tvisudata(o)) {
618     GCudata *ud = udataV(o);
619     tmpptr = uddata(ud);
620     if (ud->udtype == UDTYPE_IO_FILE)
621       tmpptr = *(void **)tmpptr;
622   } else if (tvislightud(o)) {
623     tmpptr = lightudV(cts->g, o);
624   } else if (tvisfunc(o)) {
625     void *p = lj_ccallback_new(cts, d, funcV(o));
626     if (p) {
627       *(void **)dp = p;
628       return;
629     }
630     goto err_conv;
631   } else {
632   err_conv:
633     cconv_err_convtv(cts, d, o, flags);
634   }
635   s = ctype_get(cts, sid);
636 doconv:
637   if (ctype_isenum(d->info)) d = ctype_child(cts, d);
638   lj_cconv_ct_ct(cts, d, s, dp, sp, flags);
639 }
640 
641 /* Convert TValue to bitfield. */
lj_cconv_bf_tv(CTState * cts,CType * d,uint8_t * dp,TValue * o)642 void lj_cconv_bf_tv(CTState *cts, CType *d, uint8_t *dp, TValue *o)
643 {
644   CTInfo info = d->info;
645   CTSize pos, bsz;
646   uint32_t val, mask;
647   lj_assertCTS(ctype_isbitfield(info), "bitfield expected");
648   if ((info & CTF_BOOL)) {
649     uint8_t tmpbool;
650     lj_assertCTS(ctype_bitbsz(info) == 1, "bad bool bitfield size");
651     lj_cconv_ct_tv(cts, ctype_get(cts, CTID_BOOL), &tmpbool, o, 0);
652     val = tmpbool;
653   } else {
654     CTypeID did = (info & CTF_UNSIGNED) ? CTID_UINT32 : CTID_INT32;
655     lj_cconv_ct_tv(cts, ctype_get(cts, did), (uint8_t *)&val, o, 0);
656   }
657   pos = ctype_bitpos(info);
658   bsz = ctype_bitbsz(info);
659   lj_assertCTS(pos < 8*ctype_bitcsz(info), "bad bitfield position");
660   lj_assertCTS(bsz > 0 && bsz <= 8*ctype_bitcsz(info), "bad bitfield size");
661   /* Check if a packed bitfield crosses a container boundary. */
662   if (pos + bsz > 8*ctype_bitcsz(info))
663     lj_err_caller(cts->L, LJ_ERR_FFI_NYIPACKBIT);
664   mask = ((1u << bsz) - 1u) << pos;
665   val = (val << pos) & mask;
666   /* NYI: packed bitfields may cause misaligned reads/writes. */
667   switch (ctype_bitcsz(info)) {
668   case 4: *(uint32_t *)dp = (*(uint32_t *)dp & ~mask) | (uint32_t)val; break;
669   case 2: *(uint16_t *)dp = (*(uint16_t *)dp & ~mask) | (uint16_t)val; break;
670   case 1: *(uint8_t *)dp = (*(uint8_t *)dp & ~mask) | (uint8_t)val; break;
671   default:
672     lj_assertCTS(0, "bad bitfield container size %d", ctype_bitcsz(info));
673     break;
674   }
675 }
676 
677 /* -- Initialize C type with TValues -------------------------------------- */
678 
679 /* Initialize an array with TValues. */
cconv_array_init(CTState * cts,CType * d,CTSize sz,uint8_t * dp,TValue * o,MSize len)680 static void cconv_array_init(CTState *cts, CType *d, CTSize sz, uint8_t *dp,
681 			     TValue *o, MSize len)
682 {
683   CType *dc = ctype_rawchild(cts, d);  /* Array element type. */
684   CTSize ofs, esize = dc->size;
685   MSize i;
686   if (len*esize > sz)
687     cconv_err_initov(cts, d);
688   for (i = 0, ofs = 0; i < len; i++, ofs += esize)
689     lj_cconv_ct_tv(cts, dc, dp + ofs, o + i, 0);
690   if (ofs == esize) {  /* Replicate a single element. */
691     for (; ofs < sz; ofs += esize) memcpy(dp + ofs, dp, esize);
692   } else {  /* Otherwise fill the remainder with zero. */
693     memset(dp + ofs, 0, sz - ofs);
694   }
695 }
696 
697 /* Initialize a sub-struct/union with TValues. */
cconv_substruct_init(CTState * cts,CType * d,uint8_t * dp,TValue * o,MSize len,MSize * ip)698 static void cconv_substruct_init(CTState *cts, CType *d, uint8_t *dp,
699 				 TValue *o, MSize len, MSize *ip)
700 {
701   CTypeID id = d->sib;
702   while (id) {
703     CType *df = ctype_get(cts, id);
704     id = df->sib;
705     if (ctype_isfield(df->info) || ctype_isbitfield(df->info)) {
706       MSize i = *ip;
707       if (!gcref(df->name)) continue;  /* Ignore unnamed fields. */
708       if (i >= len) break;
709       *ip = i + 1;
710       if (ctype_isfield(df->info))
711 	lj_cconv_ct_tv(cts, ctype_rawchild(cts, df), dp+df->size, o + i, 0);
712       else
713 	lj_cconv_bf_tv(cts, df, dp+df->size, o + i);
714       if ((d->info & CTF_UNION)) break;
715     } else if (ctype_isxattrib(df->info, CTA_SUBTYPE)) {
716       cconv_substruct_init(cts, ctype_rawchild(cts, df),
717 			   dp+df->size, o, len, ip);
718       if ((d->info & CTF_UNION)) break;
719     }  /* Ignore all other entries in the chain. */
720   }
721 }
722 
723 /* Initialize a struct/union with TValues. */
cconv_struct_init(CTState * cts,CType * d,CTSize sz,uint8_t * dp,TValue * o,MSize len)724 static void cconv_struct_init(CTState *cts, CType *d, CTSize sz, uint8_t *dp,
725 			      TValue *o, MSize len)
726 {
727   MSize i = 0;
728   memset(dp, 0, sz);  /* Much simpler to clear the struct first. */
729   cconv_substruct_init(cts, d, dp, o, len, &i);
730   if (i < len)
731     cconv_err_initov(cts, d);
732 }
733 
734 /* Check whether to use a multi-value initializer.
735 ** This is true if an aggregate is to be initialized with a value.
736 ** Valarrays are treated as values here so ct_tv handles (V|C, I|F).
737 */
lj_cconv_multi_init(CTState * cts,CType * d,TValue * o)738 int lj_cconv_multi_init(CTState *cts, CType *d, TValue *o)
739 {
740   if (!(ctype_isrefarray(d->info) || ctype_isstruct(d->info)))
741     return 0;  /* Destination is not an aggregate. */
742   if (tvistab(o) || (tvisstr(o) && !ctype_isstruct(d->info)))
743     return 0;  /* Initializer is not a value. */
744   if (tviscdata(o) && lj_ctype_rawref(cts, cdataV(o)->ctypeid) == d)
745     return 0;  /* Source and destination are identical aggregates. */
746   return 1;  /* Otherwise the initializer is a value. */
747 }
748 
749 /* Initialize C type with TValues. Caveat: expects to get the raw CType! */
lj_cconv_ct_init(CTState * cts,CType * d,CTSize sz,uint8_t * dp,TValue * o,MSize len)750 void lj_cconv_ct_init(CTState *cts, CType *d, CTSize sz,
751 		      uint8_t *dp, TValue *o, MSize len)
752 {
753   if (len == 0)
754     memset(dp, 0, sz);
755   else if (len == 1 && !lj_cconv_multi_init(cts, d, o))
756     lj_cconv_ct_tv(cts, d, dp, o, 0);
757   else if (ctype_isarray(d->info))  /* Also handles valarray init with len>1. */
758     cconv_array_init(cts, d, sz, dp, o, len);
759   else if (ctype_isstruct(d->info))
760     cconv_struct_init(cts, d, sz, dp, o, len);
761   else
762     cconv_err_initov(cts, d);
763 }
764 
765 #endif
766