summaryrefslogtreecommitdiff
path: root/src/lj_cconv.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/lj_cconv.c')
-rw-r--r--src/lj_cconv.c741
1 files changed, 741 insertions, 0 deletions
diff --git a/src/lj_cconv.c b/src/lj_cconv.c
new file mode 100644
index 00000000..f68f86a4
--- /dev/null
+++ b/src/lj_cconv.c
@@ -0,0 +1,741 @@
1/*
2** C type conversions.
3** Copyright (C) 2005-2010 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
16/* -- Conversion errors --------------------------------------------------- */
17
18/* Bad conversion. */
19LJ_NORET static void cconv_err_conv(CTState *cts, CType *d, CType *s,
20 CTInfo flags)
21{
22 const char *dst = strdata(lj_ctype_repr(cts->L, ctype_typeid(cts, d), NULL));
23 const char *src;
24 if ((flags & CCF_FROMTV))
25 src = lj_obj_typename[1+(ctype_isnum(s->info) ? LUA_TNUMBER : LUA_TSTRING)];
26 else
27 src = strdata(lj_ctype_repr(cts->L, ctype_typeid(cts, s), NULL));
28 lj_err_callerv(cts->L, LJ_ERR_FFI_BADCONV, src, dst);
29}
30
31/* Bad conversion from TValue. */
32LJ_NORET static void cconv_err_convtv(CTState *cts, CType *d, TValue *o)
33{
34 const char *dst = strdata(lj_ctype_repr(cts->L, ctype_typeid(cts, d), NULL));
35 lj_err_callerv(cts->L, LJ_ERR_FFI_BADCONV, typename(o), dst);
36}
37
38/* Initializer overflow. */
39LJ_NORET static void cconv_err_initov(CTState *cts, CType *d)
40{
41 const char *dst = strdata(lj_ctype_repr(cts->L, ctype_typeid(cts, d), NULL));
42 lj_err_callerv(cts->L, LJ_ERR_FFI_INITOV, dst);
43}
44
45/* -- C type compatibility checks ----------------------------------------- */
46
47/* Get raw type and qualifiers for a child type. Resolves enums, too. */
48static CType *cconv_childqual(CTState *cts, CType *ct, CTInfo *qual)
49{
50 ct = ctype_child(cts, ct);
51 for (;;) {
52 if (ctype_isattrib(ct->info)) {
53 if (ctype_attrib(ct->info) == CTA_QUAL) *qual |= ct->size;
54 } else if (!ctype_isenum(ct->info)) {
55 break;
56 }
57 ct = ctype_child(cts, ct);
58 }
59 *qual |= (ct->info & CTF_QUAL);
60 return ct;
61}
62
63/* Check for compatible types when converting to a pointer.
64** Note: these checks are more relaxed than what C99 mandates.
65*/
66static int cconv_compatptr(CTState *cts, CType *d, CType *s, CTInfo flags)
67{
68 if (!((flags & CCF_CAST) || d == s)) {
69 CTInfo dqual = 0, squal = 0;
70 d = cconv_childqual(cts, d, &dqual);
71 if (!ctype_isstruct(s->info))
72 s = cconv_childqual(cts, s, &squal);
73 if ((flags & CCF_SAME)) {
74 if (dqual != squal)
75 return 0; /* Different qualifiers. */
76 } else {
77 if ((dqual & squal) != squal)
78 return 0; /* Discarded qualifiers. */
79 if (ctype_isvoid(d->info) || ctype_isvoid(s->info))
80 return 1; /* Converting to/from void * is always ok. */
81 }
82 if (ctype_type(d->info) != ctype_type(s->info) ||
83 d->size != s->size)
84 return 0; /* Different type or different size. */
85 if (ctype_isnum(d->info)) {
86 if (((d->info ^ s->info) & (CTF_BOOL|CTF_FP)))
87 return 0; /* Different numeric types. */
88 } else if (ctype_ispointer(d->info)) {
89 /* Check child types for compatibility. */
90 return cconv_compatptr(cts, d, s, flags|CCF_SAME);
91 } else if (ctype_isstruct(d->info)) {
92 if (d != s)
93 return 0; /* Must be exact same type for struct/union. */
94 } else if (ctype_isfunc(d->info)) {
95 /* NYI: structural equality of functions. */
96 }
97 }
98 return 1; /* Types are compatible. */
99}
100
101/* -- C type to C type conversion ----------------------------------------- */
102
103/* Convert C type to C type. Caveat: expects to get the raw CType!
104**
105** Note: This is only used by the interpreter and not optimized at all.
106** The JIT compiler will do a much better job specializing for each case.
107*/
108void lj_cconv_ct_ct(CTState *cts, CType *d, CType *s,
109 uint8_t *dp, uint8_t *sp, CTInfo flags)
110{
111 CTSize dsize = d->size, ssize = s->size;
112 CTInfo dinfo = d->info, sinfo = s->info;
113 void *tmpptr;
114
115 lua_assert(!ctype_isenum(dinfo) && !ctype_isenum(sinfo));
116 lua_assert(!ctype_isattrib(dinfo) && !ctype_isattrib(sinfo));
117
118 if (ctype_type(dinfo) > CT_MAYCONVERT || ctype_type(sinfo) > CT_MAYCONVERT)
119 goto err_conv;
120
121 /* Some basic sanity checks. */
122 lua_assert(!ctype_isnum(dinfo) || dsize > 0);
123 lua_assert(!ctype_isnum(sinfo) || ssize > 0);
124 lua_assert(!ctype_isbool(dinfo) || dsize == 1);
125 lua_assert(!ctype_isbool(sinfo) || ssize == 1);
126 lua_assert(!ctype_isinteger(dinfo) || (1u<<lj_fls(dsize)) == dsize);
127 lua_assert(!ctype_isinteger(sinfo) || (1u<<lj_fls(ssize)) == ssize);
128
129 switch (cconv_idx2(dinfo, sinfo)) {
130 /* Destination is a bool. */
131 case CCX(B, B):
132 *dp = *sp; /* Source operand already normalized. */
133 break;
134 case CCX(B, I):
135 case CCX(B, P): {
136 MSize i;
137 uint8_t b = 0;
138 for (i = 0; i < ssize; i++) b |= sp[i];
139 *dp = (b != 0);
140 break;
141 }
142 case CCX(B, F): {
143 uint8_t b;
144 if (ssize == sizeof(double)) b = (*(double *)sp != 0);
145 else if (ssize == sizeof(float)) b = (*(float *)sp != 0);
146 else goto err_conv; /* NYI: long double. */
147 *dp = b;
148 break;
149 }
150 case CCX(B, C): {
151 CType *sc = ctype_child(cts, s);
152 uint8_t c;
153 lj_cconv_ct_ct(cts, d, sc, &c, sp, flags);
154 lj_cconv_ct_ct(cts, d, sc, dp, sp + sc->size, flags);
155 *dp = (*dp | c);
156 break;
157 }
158 case CCX(B, A):
159 *dp = (sp != (uint8_t *)0);
160 break;
161
162 /* Destination is an integer. */
163 case CCX(I, B):
164 case CCX(I, I):
165 conv_I_I:
166 if (dsize > ssize) { /* Zero-extend or sign-extend LSB. */
167#if LJ_LE
168 uint8_t fill = (!(sinfo & CTF_UNSIGNED) && (sp[ssize-1]&0x80)) ? 0xff : 0;
169 memcpy(dp, sp, ssize);
170 memset(dp + ssize, fill, dsize-ssize);
171#else
172 uint8_t fill = (!(sinfo & CTF_UNSIGNED) && (sp[0]&0x80)) ? 0xff : 0;
173 memset(dp, fill, dsize-ssize);
174 memcpy(dp + (dsize-ssize), sp, ssize);
175#endif
176 } else { /* Copy LSB. */
177#if LJ_LE
178 memcpy(dp, sp, dsize);
179#else
180 memcpy(dp, sp + (ssize-dsize), dsize);
181#endif
182 }
183 break;
184 case CCX(I, F): {
185 double n; /* Always convert via double. */
186 conv_I_F:
187 /* Convert source to double. */
188 if (ssize == sizeof(double)) n = *(double *)sp;
189 else if (ssize == sizeof(float)) n = (double)*(float *)sp;
190 else goto err_conv; /* NYI: long double. */
191 /* Then convert double to integer. */
192 /* The conversion must exactly match the semantics of JIT-compiled code! */
193 if (dsize < 4 || (dsize == 4 && !(dinfo & CTF_UNSIGNED))) {
194 int32_t i = (int32_t)n;
195 if (dsize == 4) *(int32_t *)dp = i;
196 else if (dsize == 2) *(int16_t *)dp = (int16_t)i;
197 else *(int8_t *)dp = (int8_t)i;
198 } else if (dsize == 4) {
199 *(uint32_t *)dp = (uint32_t)n;
200 } else if (dsize == 8) {
201 if (!(dinfo & CTF_UNSIGNED))
202 *(int64_t *)dp = (int64_t)n;
203#ifdef _MSC_VER
204 else if (n >= 9223372036854775808.0) /* They think it's a feature. */
205 *(uint64_t *)dp = (uint64_t)(int64_t)(n - 9223372036854775808.0) +
206 U64x(80000000,00000000);
207#endif
208 else
209 *(uint64_t *)dp = (uint64_t)n;
210 } else {
211 goto err_conv; /* NYI: conversion to >64 bit integers. */
212 }
213 break;
214 }
215 case CCX(I, C):
216 s = ctype_child(cts, s);
217 sinfo = s->info;
218 ssize = s->size;
219 goto conv_I_F; /* Just convert re. */
220 case CCX(I, P):
221 if (!(flags & CCF_CAST)) goto err_conv;
222 sinfo = CTINFO(CT_NUM, CTF_UNSIGNED);
223 goto conv_I_I;
224 case CCX(I, A):
225 if (!(flags & CCF_CAST)) goto err_conv;
226 sinfo = CTINFO(CT_NUM, CTF_UNSIGNED);
227 ssize = CTSIZE_PTR;
228 tmpptr = sp;
229 sp = (uint8_t *)&tmpptr;
230 goto conv_I_I;
231
232 /* Destination is a floating-point number. */
233 case CCX(F, B):
234 case CCX(F, I): {
235 double n; /* Always convert via double. */
236 conv_F_I:
237 /* First convert source to double. */
238 /* The conversion must exactly match the semantics of JIT-compiled code! */
239 if (ssize < 4 || (ssize == 4 && !(sinfo & CTF_UNSIGNED))) {
240 int32_t i;
241 if (ssize == 4) {
242 i = *(int32_t *)sp;
243 } else if (!(sinfo & CTF_UNSIGNED)) {
244 if (ssize == 2) i = *(int16_t *)sp;
245 else i = *(int8_t *)sp;
246 } else {
247 if (ssize == 2) i = *(uint16_t *)sp;
248 else i = *(uint8_t *)sp;
249 }
250 n = (double)i;
251 } else if (ssize == 4) {
252 n = (double)*(uint32_t *)sp;
253 } else if (ssize == 8) {
254 if (!(sinfo & CTF_UNSIGNED)) n = (double)*(int64_t *)sp;
255 else n = (double)*(uint64_t *)sp;
256 } else {
257 goto err_conv; /* NYI: conversion from >64 bit integers. */
258 }
259 /* Convert double to destination. */
260 if (dsize == sizeof(double)) *(double *)dp = n;
261 else if (dsize == sizeof(float)) *(float *)dp = (float)n;
262 else goto err_conv; /* NYI: long double. */
263 break;
264 }
265 case CCX(F, F): {
266 double n; /* Always convert via double. */
267 conv_F_F:
268 if (ssize == dsize) goto copyval;
269 /* Convert source to double. */
270 if (ssize == sizeof(double)) n = *(double *)sp;
271 else if (ssize == sizeof(float)) n = (double)*(float *)sp;
272 else goto err_conv; /* NYI: long double. */
273 /* Convert double to destination. */
274 if (dsize == sizeof(double)) *(double *)dp = n;
275 else if (dsize == sizeof(float)) *(float *)dp = (float)n;
276 else goto err_conv; /* NYI: long double. */
277 break;
278 }
279 case CCX(F, C):
280 s = ctype_child(cts, s);
281 sinfo = s->info;
282 ssize = s->size;
283 goto conv_F_F; /* Ignore im, and convert from re. */
284
285 /* Destination is a complex number. */
286 case CCX(C, I):
287 d = ctype_child(cts, d);
288 dinfo = d->info;
289 dsize = d->size;
290 memset(dp + dsize, 0, dsize); /* Clear im. */
291 goto conv_F_I; /* Convert to re. */
292 case CCX(C, F):
293 d = ctype_child(cts, d);
294 dinfo = d->info;
295 dsize = d->size;
296 memset(dp + dsize, 0, dsize); /* Clear im. */
297 goto conv_F_F; /* Convert to re. */
298
299 case CCX(C, C):
300 if (dsize != ssize) { /* Different types: convert re/im separately. */
301 CType *dc = ctype_child(cts, d);
302 CType *sc = ctype_child(cts, s);
303 lj_cconv_ct_ct(cts, dc, sc, dp, sp, flags);
304 lj_cconv_ct_ct(cts, dc, sc, dp + dc->size, sp + sc->size, flags);
305 return;
306 }
307 goto copyval; /* Otherwise this is easy. */
308
309 /* Destination is a vector. */
310 case CCX(V, I):
311 case CCX(V, F):
312 case CCX(V, C): {
313 CType *dc = ctype_child(cts, d);
314 CTSize esize;
315 /* First convert the scalar to the first element. */
316 lj_cconv_ct_ct(cts, dc, s, dp, sp, flags);
317 /* Then replicate it to the other elements (splat). */
318 for (sp = dp, esize = dc->size; dsize > esize; dsize -= esize) {
319 dp += esize;
320 memcpy(dp, sp, esize);
321 }
322 break;
323 }
324
325 case CCX(V, V):
326 /* Copy same-sized vectors, even for different lengths/element-types. */
327 if (dsize != ssize) goto err_conv;
328 goto copyval;
329
330 /* Destination is a pointer. */
331 case CCX(P, I):
332 if (!(flags & CCF_CAST)) goto err_conv;
333 dinfo = CTINFO(CT_NUM, CTF_UNSIGNED);
334 goto conv_I_I;
335
336 case CCX(P, F):
337 if (!(flags & CCF_CAST) || !(flags & CCF_FROMTV)) goto err_conv;
338 dinfo = CTINFO(CT_NUM, CTF_UNSIGNED);
339 goto conv_I_F;
340
341 case CCX(P, P):
342 if (!cconv_compatptr(cts, d, s, flags)) goto err_conv;
343 cdata_setptr(dp, dsize, cdata_getptr(sp, ssize));
344 break;
345
346 case CCX(P, A):
347 case CCX(P, S):
348 if (!cconv_compatptr(cts, d, s, flags)) goto err_conv;
349 cdata_setptr(dp, dsize, sp);
350 break;
351
352 /* Destination is an array. */
353 case CCX(A, A):
354 if ((flags & CCF_CAST) || (d->info & CTF_VLA) || d->size != s->size ||
355 d->size == CTSIZE_INVALID || !cconv_compatptr(cts, d, s, flags))
356 goto err_conv;
357 goto copyval;
358
359 /* Destination is a struct/union. */
360 case CCX(S, S):
361 if ((flags & CCF_CAST) || (d->info & CTF_VLA) || d != s)
362 goto err_conv; /* Must be exact same type. */
363copyval: /* Copy value. */
364 lua_assert(dsize == ssize);
365 memcpy(dp, sp, dsize);
366 break;
367
368 default:
369 err_conv:
370 cconv_err_conv(cts, d, s, flags);
371 }
372}
373
374/* -- C type to TValue conversion ----------------------------------------- */
375
376/* Copy value to new cdata. Strip attributes and qualifiers. */
377static GCcdata *cconv_copyval(CTState *cts, CTypeID id, void *sp)
378{
379 CType *ct = ctype_raw(cts, id);
380 CTInfo info = ct->info;
381 CTSize size = ct->size;
382 GCcdata *cd;
383 lua_assert(ctype_isnum(info) || ctype_isenum(info) ||
384 ctype_isptr(info) || ctype_isvalarray(info));
385 if (LJ_UNLIKELY((info & CTF_QUAL))) { /* Any qualifiers to strip? */
386 if (ctype_isarray(info)) {
387 CType *cct = ctype_child(cts, ct);
388 id = lj_ctype_intern(cts, (cct->info & ~CTF_QUAL), cct->size);
389 info = ((info & ~CTMASK_CID) + id);
390 }
391 id = lj_ctype_intern(cts, (info & ~CTF_QUAL), size);
392 }
393 cd = lj_cdata_new(cts, id, size);
394 memcpy(cdataptr(cd), sp, size);
395 return cd;
396}
397
398/* Convert C type to TValue. Caveat: expects to get the raw CType! */
399void lj_cconv_tv_ct(CTState *cts, CType *s, CTypeID sid,
400 TValue *o, uint8_t *sp)
401{
402 CTInfo sinfo = s->info;
403 lua_assert(!ctype_isenum(sinfo));
404 if (ctype_isnum(sinfo)) {
405 uint8_t tmpbool;
406 uint8_t *dp;
407 CTypeID did;
408 if (!ctype_isbool(sinfo)) {
409 if (ctype_isinteger(sinfo) && s->size > 4) goto copyval;
410 dp = (uint8_t *)&o->n;
411 did = CTID_DOUBLE;
412 } else {
413 dp = &tmpbool;
414 did = CTID_BOOL;
415 }
416 lj_cconv_ct_ct(cts, ctype_get(cts, did), s, dp, sp, 0);
417 /* Numbers are NOT canonicalized here! Beware of uninitialized data. */
418 if (did == CTID_BOOL)
419 setboolV(o, tmpbool);
420 else
421 lua_assert(tvisnum(o));
422 } else if (ctype_isrefarray(sinfo) || ctype_isstruct(sinfo)) {
423 /* Create reference. */
424 setcdataV(cts->L, o, lj_cdata_newref(cts, sp, sid));
425 } else {
426 copyval: /* Copy value. */
427 setcdataV(cts->L, o, cconv_copyval(cts, sid, sp));
428 }
429}
430
431/* Convert bitfield to TValue. */
432void lj_cconv_tv_bf(CTState *cts, CType *s, TValue *o, uint8_t *sp)
433{
434 CTInfo info = s->info;
435 CTSize pos, bsz;
436 uint32_t val;
437 lua_assert(ctype_isbitfield(info));
438 /* NYI: packed bitfields may cause misaligned reads. */
439 switch (ctype_bitcsz(info)) {
440 case 4: val = *(uint32_t *)sp; break;
441 case 2: val = *(uint16_t *)sp; break;
442 case 1: val = *(uint8_t *)sp; break;
443 default: lua_assert(0); val = 0; break;
444 }
445 /* Check if a packed bitfield crosses a container boundary. */
446 pos = ctype_bitpos(info);
447 bsz = ctype_bitbsz(info);
448 lua_assert(pos < 8*ctype_bitcsz(info));
449 lua_assert(bsz > 0 && bsz <= 8*ctype_bitcsz(info));
450 if (pos + bsz > 8*ctype_bitcsz(info))
451 lj_err_caller(cts->L, LJ_ERR_FFI_NYIPACKBIT);
452 if (!(info & CTF_BOOL)) {
453 CTSize shift = 32 - bsz;
454 if (!(info & CTF_UNSIGNED))
455 setnumV(o, (lua_Number)((int32_t)(val << (shift-pos)) >> shift));
456 else
457 setnumV(o, (lua_Number)((val << (shift-pos)) >> shift));
458 } else {
459 lua_assert(bsz == 1);
460 setboolV(o, (val >> pos) & 1);
461 }
462}
463
464/* -- TValue to C type conversion ----------------------------------------- */
465
466/* Convert table to array. */
467static void cconv_array_tab(CTState *cts, CType *d,
468 uint8_t *dp, GCtab *t, CTInfo flags)
469{
470 int32_t i;
471 CType *dc = ctype_rawchild(cts, d); /* Array element type. */
472 CTSize size = d->size, esize = dc->size, ofs = 0;
473 for (i = 0; ; i++) {
474 TValue *tv = (TValue *)lj_tab_getint(t, i);
475 if (!tv || tvisnil(tv)) {
476 if (i == 0) continue; /* Try again for 1-based tables. */
477 break; /* Stop at first nil. */
478 }
479 if (ofs >= size)
480 cconv_err_initov(cts, d);
481 lj_cconv_ct_tv(cts, dc, dp + ofs, tv, flags);
482 ofs += esize;
483 }
484 if (size != CTSIZE_INVALID) { /* Only fill up arrays with known size. */
485 if (ofs == esize) { /* Replicate a single element. */
486 for (; ofs < size; ofs += esize) memcpy(dp + ofs, dp, esize);
487 } else { /* Otherwise fill the remainder with zero. */
488 memset(dp + ofs, 0, size - ofs);
489 }
490 }
491}
492
493/* Convert table to sub-struct/union. */
494static void cconv_substruct_tab(CTState *cts, CType *d, uint8_t *dp,
495 GCtab *t, int32_t *ip, CTInfo flags)
496{
497 CTypeID id = d->sib;
498 while (id) {
499 CType *df = ctype_get(cts, id);
500 id = df->sib;
501 if (ctype_isfield(df->info) || ctype_isbitfield(df->info)) {
502 TValue *tv;
503 int32_t i = *ip;
504 if (!gcref(df->name)) continue; /* Ignore unnamed fields. */
505 if (i >= 0) {
506 retry:
507 tv = (TValue *)lj_tab_getint(t, i);
508 if (!tv || tvisnil(tv)) {
509 if (i == 0) { i = 1; goto retry; } /* 1-based tables. */
510 break; /* Stop at first nil. */
511 }
512 *ip = i + 1;
513 } else {
514 tv = (TValue *)lj_tab_getstr(t, gco2str(gcref(df->name)));
515 if (!tv || tvisnil(tv)) continue;
516 }
517 if (ctype_isfield(df->info))
518 lj_cconv_ct_tv(cts, ctype_rawchild(cts, df), dp+df->size, tv, flags);
519 else
520 lj_cconv_bf_tv(cts, df, dp+df->size, tv);
521 if ((d->info & CTF_UNION)) break;
522 } else if (ctype_isxattrib(df->info, CTA_SUBTYPE)) {
523 cconv_substruct_tab(cts, ctype_child(cts, df), dp+df->size, t, ip, flags);
524 } /* Ignore all other entries in the chain. */
525 }
526}
527
528/* Convert table to struct/union. */
529static void cconv_struct_tab(CTState *cts, CType *d,
530 uint8_t *dp, GCtab *t, CTInfo flags)
531{
532 int32_t i = 0;
533 memset(dp, 0, d->size); /* Much simpler to clear the struct first. */
534 if (t->hmask) i = -1; else if (t->asize == 0) return; /* Fast exit. */
535 cconv_substruct_tab(cts, d, dp, t, &i, flags);
536}
537
538/* Convert TValue to C type. Caveat: expects to get the raw CType! */
539void lj_cconv_ct_tv(CTState *cts, CType *d,
540 uint8_t *dp, TValue *o, CTInfo flags)
541{
542 CTypeID sid = CTID_P_VOID;
543 CType *s;
544 void *tmpptr;
545 uint8_t tmpbool, *sp = (uint8_t *)&tmpptr;
546 if (LJ_LIKELY(tvisnum(o))) {
547 sp = (uint8_t *)&o->n;
548 sid = CTID_DOUBLE;
549 flags |= CCF_FROMTV;
550 } else if (tviscdata(o)) {
551 sp = cdataptr(cdataV(o));
552 sid = cdataV(o)->typeid;
553 s = ctype_get(cts, sid);
554 if (ctype_isref(s->info)) { /* Resolve reference for value. */
555 lua_assert(s->size == CTSIZE_PTR);
556 sp = *(void **)sp;
557 sid = ctype_cid(s->info);
558 }
559 s = ctype_raw(cts, sid);
560 if (ctype_isenum(s->info)) s = ctype_child(cts, s);
561 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-1;
579 dp[sz] = '\0';
580 }
581 memcpy(dp, strdata(str), sz);
582 return;
583 } else { /* Otherwise pass it as a const char[]. */
584 sp = (uint8_t *)strdata(str);
585 sid = CTID_A_CCHAR;
586 flags |= CCF_FROMTV;
587 }
588 } else if (tvistab(o)) {
589 if (ctype_isarray(d->info)) {
590 cconv_array_tab(cts, d, dp, tabV(o), flags);
591 return;
592 } else if (ctype_isstruct(d->info)) {
593 cconv_struct_tab(cts, d, dp, tabV(o), flags);
594 return;
595 } else {
596 goto err_conv;
597 }
598 } else if (tvisbool(o)) {
599 tmpbool = boolV(o);
600 sp = &tmpbool;
601 sid = CTID_BOOL;
602 } else if (tvisnil(o)) {
603 tmpptr = (void *)0;
604 } else if (tvisudata(o)) {
605 tmpptr = uddata(udataV(o));
606 } else if (tvislightud(o)) {
607 tmpptr = lightudV(o);
608 } else {
609 err_conv:
610 cconv_err_convtv(cts, d, o);
611 }
612 s = ctype_get(cts, sid);
613doconv:
614 if (ctype_isenum(d->info)) d = ctype_child(cts, d);
615 lj_cconv_ct_ct(cts, d, s, dp, sp, flags);
616}
617
618/* Convert TValue to bitfield. */
619void lj_cconv_bf_tv(CTState *cts, CType *d, uint8_t *dp, TValue *o)
620{
621 CTInfo info = d->info;
622 CTSize pos, bsz;
623 uint32_t val, mask;
624 lua_assert(ctype_isbitfield(info));
625 if ((info & CTF_BOOL)) {
626 uint8_t tmpbool;
627 lua_assert(ctype_bitbsz(info) == 1);
628 lj_cconv_ct_tv(cts, ctype_get(cts, CTID_BOOL), &tmpbool, o, 0);
629 val = tmpbool;
630 } else {
631 CTypeID did = (info & CTF_UNSIGNED) ? CTID_UINT32 : CTID_INT32;
632 lj_cconv_ct_tv(cts, ctype_get(cts, did), (uint8_t *)&val, o, 0);
633 }
634 pos = ctype_bitpos(info);
635 bsz = ctype_bitbsz(info);
636 lua_assert(pos < 8*ctype_bitcsz(info));
637 lua_assert(bsz > 0 && bsz <= 8*ctype_bitcsz(info));
638 /* Check if a packed bitfield crosses a container boundary. */
639 if (pos + bsz > 8*ctype_bitcsz(info))
640 lj_err_caller(cts->L, LJ_ERR_FFI_NYIPACKBIT);
641 mask = ((1u << bsz) - 1u) << pos;
642 val = (val << pos) & mask;
643 /* NYI: packed bitfields may cause misaligned reads/writes. */
644 switch (ctype_bitcsz(info)) {
645 case 4: *(uint32_t *)dp = (*(uint32_t *)dp & ~mask) | (uint32_t)val; break;
646 case 2: *(uint16_t *)dp = (*(uint16_t *)dp & ~mask) | (uint16_t)val; break;
647 case 1: *(uint8_t *)dp = (*(uint8_t *)dp & ~mask) | (uint8_t)val; break;
648 default: lua_assert(0); break;
649 }
650}
651
652/* -- Initialize C type with TValues -------------------------------------- */
653
654/* Initialize an array with TValues. */
655static void cconv_array_init(CTState *cts, CType *d, CTSize sz, uint8_t *dp,
656 TValue *o, MSize len)
657{
658 CType *dc = ctype_rawchild(cts, d); /* Array element type. */
659 CTSize ofs, esize = dc->size;
660 MSize i;
661 if (len*esize > sz)
662 cconv_err_initov(cts, d);
663 for (i = 0, ofs = 0; i < len; i++, ofs += esize)
664 lj_cconv_ct_tv(cts, dc, dp + ofs, o + i, 0);
665 if (ofs == esize) { /* Replicate a single element. */
666 for (; ofs < sz; ofs += esize) memcpy(dp + ofs, dp, esize);
667 } else { /* Otherwise fill the remainder with zero. */
668 memset(dp + ofs, 0, sz - ofs);
669 }
670}
671
672/* Initialize a sub-struct/union with TValues. */
673static void cconv_substruct_init(CTState *cts, CType *d, uint8_t *dp,
674 TValue *o, MSize len, MSize *ip)
675{
676 CTypeID id = d->sib;
677 while (id) {
678 CType *df = ctype_get(cts, id);
679 id = df->sib;
680 if (ctype_isfield(df->info) || ctype_isbitfield(df->info)) {
681 MSize i = *ip;
682 if (!gcref(df->name)) continue; /* Ignore unnamed fields. */
683 if (i >= len) break;
684 *ip = i + 1;
685 if (ctype_isfield(df->info))
686 lj_cconv_ct_tv(cts, ctype_rawchild(cts, df), dp+df->size, o + i, 0);
687 else
688 lj_cconv_bf_tv(cts, df, dp+df->size, o + i);
689 if ((d->info & CTF_UNION)) break;
690 } else if (ctype_isxattrib(df->info, CTA_SUBTYPE)) {
691 cconv_substruct_init(cts, ctype_child(cts, df), dp+df->size, o, len, ip);
692 } /* Ignore all other entries in the chain. */
693 }
694}
695
696/* Initialize a struct/union with TValues. */
697static void cconv_struct_init(CTState *cts, CType *d, CTSize sz, uint8_t *dp,
698 TValue *o, MSize len)
699{
700 MSize i = 0;
701 memset(dp, 0, sz); /* Much simpler to clear the struct first. */
702 cconv_substruct_init(cts, d, dp, o, len, &i);
703 if (i < len)
704 cconv_err_initov(cts, d);
705}
706
707/* Check whether to use a multi-value initializer.
708** This is true if an aggregate is to be initialized with a value.
709** Valarrays are treated as values here so ct_tv handles (V|C, I|F).
710*/
711static int cconv_multi_init(CTState *cts, CType *d, TValue *o)
712{
713 if (!(ctype_isrefarray(d->info) || ctype_isstruct(d->info)))
714 return 0; /* Destination is not an aggregate. */
715 if (tvistab(o) || (tvisstr(o) && !ctype_isstruct(d->info)))
716 return 0; /* Initializer is not a value. */
717 if (tviscdata(o)) {
718 CTInfo info = lj_ctype_rawref(cts, cdataV(o)->typeid)->info;
719 if (ctype_isrefarray(info) || ctype_isstruct(info))
720 return 0; /* Initializer is not a value. */
721 }
722 return 1; /* Otherwise the initializer is a value. */
723}
724
725/* Initialize C type with TValues. Caveat: expects to get the raw CType! */
726void lj_cconv_ct_init(CTState *cts, CType *d, CTSize sz,
727 uint8_t *dp, TValue *o, MSize len)
728{
729 if (len == 0)
730 memset(dp, 0, sz);
731 else if (len == 1 && !cconv_multi_init(cts, d, o))
732 lj_cconv_ct_tv(cts, d, dp, o, 0);
733 else if (ctype_isarray(d->info)) /* Also handles valarray init with len>1. */
734 cconv_array_init(cts, d, sz, dp, o, len);
735 else if (ctype_isstruct(d->info))
736 cconv_struct_init(cts, d, sz, dp, o, len);
737 else
738 cconv_err_initov(cts, d);
739}
740
741#endif