aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorMike Pall <mike>2010-12-05 00:18:07 +0100
committerMike Pall <mike>2010-12-05 00:18:07 +0100
commit526e087e63daaaeab517932351c8941f678e071c (patch)
treee7a1460ba4c120b1cc464a3702fb915de9388fe9 /src
parent05973ee44075698e6c578cfb0fa72cfccdf7b742 (diff)
downloadluajit-526e087e63daaaeab517932351c8941f678e071c.tar.gz
luajit-526e087e63daaaeab517932351c8941f678e071c.tar.bz2
luajit-526e087e63daaaeab517932351c8941f678e071c.zip
FFI: Add C data handling and C type conversions.
Diffstat (limited to 'src')
-rw-r--r--src/Makefile2
-rw-r--r--src/Makefile.dep34
-rw-r--r--src/lj_cconv.c741
-rw-r--r--src/lj_cconv.h64
-rw-r--r--src/lj_cdata.c235
-rw-r--r--src/lj_cdata.h62
-rw-r--r--src/lj_errmsg.h17
-rw-r--r--src/lj_gc.c9
-rw-r--r--src/ljamalg.c2
9 files changed, 1149 insertions, 17 deletions
diff --git a/src/Makefile b/src/Makefile
index 563c6c08..34a966cd 100644
--- a/src/Makefile
+++ b/src/Makefile
@@ -327,7 +327,7 @@ LJCORE_O= lj_gc.o lj_err.o lj_char.o lj_bc.o lj_obj.o \
327 lj_ir.o lj_opt_mem.o lj_opt_fold.o lj_opt_narrow.o \ 327 lj_ir.o lj_opt_mem.o lj_opt_fold.o lj_opt_narrow.o \
328 lj_opt_dce.o lj_opt_loop.o \ 328 lj_opt_dce.o lj_opt_loop.o \
329 lj_mcode.o lj_snap.o lj_record.o lj_asm.o lj_trace.o lj_gdbjit.o \ 329 lj_mcode.o lj_snap.o lj_record.o lj_asm.o lj_trace.o lj_gdbjit.o \
330 lj_ctype.o \ 330 lj_ctype.o lj_cdata.o lj_cconv.o \
331 lj_lib.o lj_alloc.o lib_aux.o \ 331 lj_lib.o lj_alloc.o lib_aux.o \
332 $(LJLIB_O) lib_init.o 332 $(LJLIB_O) lib_init.o
333 333
diff --git a/src/Makefile.dep b/src/Makefile.dep
index 761fd9fa..f7ee92ec 100644
--- a/src/Makefile.dep
+++ b/src/Makefile.dep
@@ -52,6 +52,10 @@ lj_asm.o: lj_asm.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h lj_gc.h \
52 lj_vm.h lj_target.h lj_target_*.h 52 lj_vm.h lj_target.h lj_target_*.h
53lj_bc.o: lj_bc.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h lj_bc.h \ 53lj_bc.o: lj_bc.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h lj_bc.h \
54 lj_bcdef.h 54 lj_bcdef.h
55lj_cconv.o: lj_cconv.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \
56 lj_err.h lj_errmsg.h lj_tab.h lj_ctype.h lj_gc.h lj_cdata.h lj_cconv.h
57lj_cdata.o: lj_cdata.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \
58 lj_gc.h lj_err.h lj_errmsg.h lj_str.h lj_ctype.h lj_cconv.h lj_cdata.h
55lj_char.o: lj_char.c lj_char.h lj_def.h lua.h luaconf.h 59lj_char.o: lj_char.c lj_char.h lj_def.h lua.h luaconf.h
56lj_ctype.o: lj_ctype.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \ 60lj_ctype.o: lj_ctype.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \
57 lj_gc.h lj_err.h lj_errmsg.h lj_str.h lj_tab.h lj_ctype.h 61 lj_gc.h lj_err.h lj_errmsg.h lj_str.h lj_tab.h lj_ctype.h
@@ -66,8 +70,8 @@ lj_func.o: lj_func.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h lj_gc.h \
66 lj_traceerr.h lj_vm.h 70 lj_traceerr.h lj_vm.h
67lj_gc.o: lj_gc.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h lj_gc.h \ 71lj_gc.o: lj_gc.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h lj_gc.h \
68 lj_err.h lj_errmsg.h lj_str.h lj_tab.h lj_func.h lj_udata.h lj_meta.h \ 72 lj_err.h lj_errmsg.h lj_str.h lj_tab.h lj_func.h lj_udata.h lj_meta.h \
69 lj_state.h lj_frame.h lj_bc.h lj_trace.h lj_jit.h lj_ir.h lj_dispatch.h \ 73 lj_state.h lj_frame.h lj_bc.h lj_cdata.h lj_ctype.h lj_trace.h lj_jit.h \
70 lj_traceerr.h lj_vm.h 74 lj_ir.h lj_dispatch.h lj_traceerr.h lj_vm.h
71lj_gdbjit.o: lj_gdbjit.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \ 75lj_gdbjit.o: lj_gdbjit.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \
72 lj_gc.h lj_err.h lj_errmsg.h lj_frame.h lj_bc.h lj_jit.h lj_ir.h \ 76 lj_gc.h lj_err.h lj_errmsg.h lj_frame.h lj_bc.h lj_jit.h lj_ir.h \
73 lj_dispatch.h 77 lj_dispatch.h
@@ -129,17 +133,17 @@ lj_vmevent.o: lj_vmevent.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \
129 lj_vm.h lj_vmevent.h 133 lj_vm.h lj_vmevent.h
130ljamalg.o: ljamalg.c lua.h luaconf.h lauxlib.h lj_gc.c lj_obj.h lj_def.h \ 134ljamalg.o: ljamalg.c lua.h luaconf.h lauxlib.h lj_gc.c lj_obj.h lj_def.h \
131 lj_arch.h lj_gc.h lj_err.h lj_errmsg.h lj_str.h lj_tab.h lj_func.h \ 135 lj_arch.h lj_gc.h lj_err.h lj_errmsg.h lj_str.h lj_tab.h lj_func.h \
132 lj_udata.h lj_meta.h lj_state.h lj_frame.h lj_bc.h lj_trace.h lj_jit.h \ 136 lj_udata.h lj_meta.h lj_state.h lj_frame.h lj_bc.h lj_cdata.h lj_ctype.h \
133 lj_ir.h lj_dispatch.h lj_traceerr.h lj_vm.h lj_err.c lj_char.c lj_char.h \ 137 lj_trace.h lj_jit.h lj_ir.h lj_dispatch.h lj_traceerr.h lj_vm.h lj_err.c \
134 lj_bc.c lj_bcdef.h lj_obj.c lj_str.c lj_tab.c lj_func.c lj_udata.c \ 138 lj_char.c lj_char.h lj_bc.c lj_bcdef.h lj_obj.c lj_str.c lj_tab.c \
135 lj_meta.c lj_state.c lj_ctype.h lj_lex.h lj_alloc.h lj_dispatch.c \ 139 lj_func.c lj_udata.c lj_meta.c lj_state.c lj_lex.h lj_alloc.h \
136 lj_ff.h lj_ffdef.h luajit.h lj_vmevent.c lj_vmevent.h lj_api.c \ 140 lj_dispatch.c lj_ff.h lj_ffdef.h luajit.h lj_vmevent.c lj_vmevent.h \
137 lj_parse.h lj_lex.c lj_parse.c lj_ctype.c lj_lib.c lj_lib.h lj_ir.c \ 141 lj_api.c lj_parse.h lj_lex.c lj_parse.c lj_ctype.c lj_cdata.c lj_cconv.h \
138 lj_iropt.h lj_opt_mem.c lj_opt_fold.c lj_folddef.h lj_opt_narrow.c \ 142 lj_cconv.c lj_lib.c lj_lib.h lj_ir.c lj_iropt.h lj_opt_mem.c \
139 lj_opt_dce.c lj_opt_loop.c lj_snap.h lj_mcode.c lj_mcode.h lj_snap.c \ 143 lj_opt_fold.c lj_folddef.h lj_opt_narrow.c lj_opt_dce.c lj_opt_loop.c \
140 lj_target.h lj_target_*.h lj_record.c lj_record.h lj_asm.h lj_recdef.h \ 144 lj_snap.h lj_mcode.c lj_mcode.h lj_snap.c lj_target.h lj_target_*.h \
141 lj_asm.c lj_trace.c lj_gdbjit.h lj_gdbjit.c lj_alloc.c lib_aux.c \ 145 lj_record.c lj_record.h lj_asm.h lj_recdef.h lj_asm.c lj_trace.c \
142 lib_base.c lualib.h lj_libdef.h lib_math.c lib_string.c lib_table.c \ 146 lj_gdbjit.h lj_gdbjit.c lj_alloc.c lib_aux.c lib_base.c lualib.h \
143 lib_io.c lib_os.c lib_package.c lib_debug.c lib_bit.c lib_jit.c \ 147 lj_libdef.h lib_math.c lib_string.c lib_table.c lib_io.c lib_os.c \
144 lib_init.c 148 lib_package.c lib_debug.c lib_bit.c lib_jit.c lib_init.c
145luajit.o: luajit.c lua.h luaconf.h lauxlib.h lualib.h luajit.h lj_arch.h 149luajit.o: luajit.c lua.h luaconf.h lauxlib.h lualib.h luajit.h lj_arch.h
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
diff --git a/src/lj_cconv.h b/src/lj_cconv.h
new file mode 100644
index 00000000..45afe718
--- /dev/null
+++ b/src/lj_cconv.h
@@ -0,0 +1,64 @@
1/*
2** C type conversions.
3** Copyright (C) 2005-2010 Mike Pall. See Copyright Notice in luajit.h
4*/
5
6#ifndef _LJ_CCONV_H
7#define _LJ_CCONV_H
8
9#include "lj_obj.h"
10#include "lj_ctype.h"
11
12#if LJ_HASFFI
13
14/* Compressed C type index. ORDER CCX. */
15enum {
16 CCX_B, /* Bool. */
17 CCX_I, /* Integer. */
18 CCX_F, /* Floating-point number. */
19 CCX_C, /* Complex. */
20 CCX_V, /* Vector. */
21 CCX_P, /* Pointer. */
22 CCX_A, /* Refarray. */
23 CCX_S /* Struct/union. */
24};
25
26/* Convert C type info to compressed C type index. ORDER CT. ORDER CCX. */
27static LJ_AINLINE uint32_t cconv_idx(CTInfo info)
28{
29 uint32_t idx = ((info >> 26) & 15u); /* Dispatch bits. */
30 lua_assert(ctype_type(info) <= CT_MAYCONVERT);
31#if LJ_64
32 idx = ((U64x(f436fff5,fff7f021) >> 4*idx) & 15u);
33#else
34 idx = (((idx < 8 ? 0xfff7f021u : 0xf436fff5) >> 4*(idx & 7u)) & 15u);
35#endif
36 lua_assert(idx < 8);
37 return idx;
38}
39
40#define cconv_idx2(dinfo, sinfo) \
41 ((cconv_idx((dinfo)) << 3) + cconv_idx((sinfo)))
42
43#define CCX(dst, src) ((CCX_##dst << 3) + CCX_##src)
44
45/* Conversion flags. */
46#define CCF_CAST 0x00000001u
47#define CCF_FROMTV 0x00000002u
48#define CCF_SAME 0x00000004u
49
50
51LJ_FUNC void lj_cconv_ct_ct(CTState *cts, CType *d, CType *s,
52 uint8_t *dp, uint8_t *sp, CTInfo flags);
53LJ_FUNC void lj_cconv_tv_ct(CTState *cts, CType *s, CTypeID sid,
54 TValue *o, uint8_t *sp);
55LJ_FUNC void lj_cconv_tv_bf(CTState *cts, CType *s, TValue *o, uint8_t *sp);
56LJ_FUNC void lj_cconv_ct_tv(CTState *cts, CType *d,
57 uint8_t *dp, TValue *o, CTInfo flags);
58LJ_FUNC void lj_cconv_bf_tv(CTState *cts, CType *d, uint8_t *dp, TValue *o);
59LJ_FUNC void lj_cconv_ct_init(CTState *cts, CType *d, CTSize sz,
60 uint8_t *dp, TValue *o, MSize len);
61
62#endif
63
64#endif
diff --git a/src/lj_cdata.c b/src/lj_cdata.c
new file mode 100644
index 00000000..15ba2dde
--- /dev/null
+++ b/src/lj_cdata.c
@@ -0,0 +1,235 @@
1/*
2** C data management.
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_gc.h"
11#include "lj_err.h"
12#include "lj_str.h"
13#include "lj_ctype.h"
14#include "lj_cconv.h"
15#include "lj_cdata.h"
16
17/* -- C data allocation --------------------------------------------------- */
18
19/* Allocate a new C data object holding a reference to another object. */
20GCcdata *lj_cdata_newref(CTState *cts, const void *p, CTypeID id)
21{
22 CTypeID refid = lj_ctype_intern(cts, CTINFO_REF(id), CTSIZE_PTR);
23 GCcdata *cd = lj_cdata_new(cts, refid, CTSIZE_PTR);
24 *(const void **)cdataptr(cd) = p;
25 return cd;
26}
27
28/* Allocate variable-sized or specially aligned C data object. */
29GCcdata *lj_cdata_newv(CTState *cts, CTypeID id, CTSize sz, CTSize align)
30{
31 global_State *g;
32 MSize extra = sizeof(GCcdataVar) + sizeof(GCcdata) +
33 (align > CT_MEMALIGN ? (1u<<align) - (1u<<CT_MEMALIGN) : 0);
34 char *p = lj_mem_newt(cts->L, extra + sz, char);
35 uintptr_t adata = (uintptr_t)p + sizeof(GCcdataVar) + sizeof(GCcdata);
36 uintptr_t almask = (1u << align) - 1u;
37 GCcdata *cd = (GCcdata *)(((adata + almask) & ~almask) - sizeof(GCcdata));
38 lua_assert((char *)cd - p < 65536);
39 cdatav(cd)->offset = (uint16_t)((char *)cd - p);
40 cdatav(cd)->extra = extra;
41 cdatav(cd)->len = sz;
42 g = cts->g;
43 setgcrefr(cd->nextgc, g->gc.root);
44 setgcref(g->gc.root, obj2gco(cd));
45 newwhite(g, obj2gco(cd));
46 cd->marked |= 0x80;
47 cd->gct = ~LJ_TCDATA;
48 cd->typeid = id;
49 return cd;
50}
51
52/* Free a C data object. */
53void LJ_FASTCALL lj_cdata_free(global_State *g, GCcdata *cd)
54{
55 if (LJ_LIKELY(!cdataisv(cd))) {
56 CType *ct = ctype_raw(ctype_ctsG(g), cd->typeid);
57 CTSize sz = ctype_hassize(ct->info) ? ct->size : CTSIZE_PTR;
58 lua_assert(ctype_hassize(ct->info) || ctype_isfunc(ct->info));
59 lj_mem_free(g, cd, sizeof(GCcdata) + sz);
60 } else {
61 lj_mem_free(g, memcdatav(cd), sizecdatav(cd));
62 }
63}
64
65/* -- C data indexing ----------------------------------------------------- */
66
67/* Index C data by a TValue. Return CType and pointer. */
68CType *lj_cdata_index(CTState *cts, GCcdata *cd, cTValue *key, uint8_t **pp,
69 CTInfo *qual)
70{
71 uint8_t *p = (uint8_t *)cdataptr(cd);
72 CType *ct = ctype_get(cts, cd->typeid);
73
74 /* Resolve reference for cdata object. */
75 if (ctype_isref(ct->info)) {
76 lua_assert(ct->size == CTSIZE_PTR);
77 p = *(uint8_t **)p;
78 ct = ctype_child(cts, ct);
79 }
80
81 /* Skip attributes and collect qualifiers. */
82 while (ctype_isattrib(ct->info)) {
83 if (ctype_attrib(ct->info) == CTA_QUAL) *qual |= ct->size;
84 ct = ctype_child(cts, ct);
85 }
86 lua_assert(!ctype_isref(ct->info)); /* Interning rejects refs to refs. */
87
88 if (tvisnum(key)) { /* Numeric key. */
89 ptrdiff_t idx = LJ_64 ? (ptrdiff_t)numV(key) :
90 (ptrdiff_t)lj_num2int(numV(key));
91 if (ctype_ispointer(ct->info)) {
92 CTSize sz = lj_ctype_size(cts, ctype_cid(ct->info));
93 if (sz != CTSIZE_INVALID) {
94 if (ctype_isptr(ct->info))
95 p = (uint8_t *)cdata_getptr(p, ct->size);
96 else if ((ct->info & (CTF_VECTOR|CTF_COMPLEX)))
97 *qual |= CTF_CONST; /* Valarray elements are constant. */
98 *pp = p + idx*(int32_t)sz;
99 return ct;
100 }
101 }
102 } else if (tvisstr(key)) { /* String key. */
103 GCstr *name = strV(key);
104 if (ctype_isptr(ct->info)) { /* Automatically perform '->'. */
105 CType *cct = ctype_child(cts, ct);
106 if (ctype_isstruct(cct->info)) {
107 p = (uint8_t *)cdata_getptr(p, ct->size);
108 ct = cct;
109 goto index_struct;
110 }
111 } if (ctype_isstruct(ct->info)) {
112 CTSize ofs;
113 CType *fct;
114 index_struct:
115 fct = lj_ctype_getfield(cts, ct, name, &ofs);
116 if (fct) {
117 *pp = p + ofs;
118 return fct;
119 }
120 } else if (ctype_iscomplex(ct->info)) {
121 if (name->len == 2) {
122 *qual |= CTF_CONST; /* Complex fields are constant. */
123 if (strdata(name)[0] == 'r' && strdata(name)[1] == 'e') {
124 *pp = p;
125 return ct;
126 } else if (strdata(name)[0] == 'i' && strdata(name)[1] == 'm') {
127 *pp = p + (ct->size >> 1);
128 return ct;
129 }
130 }
131 }
132 {
133 GCstr *s = lj_ctype_repr(cts->L, ctype_typeid(cts, ct), NULL);
134 lj_err_callerv(cts->L, LJ_ERR_FFI_BADMEMBER, strdata(s), strdata(name));
135 }
136 }
137 {
138 GCstr *s = lj_ctype_repr(cts->L, ctype_typeid(cts, ct), NULL);
139 lj_err_callerv(cts->L, LJ_ERR_FFI_BADIDX, strdata(s));
140 }
141 return NULL; /* unreachable */
142}
143
144/* -- C data getters ------------------------------------------------------ */
145
146/* Get constant value and convert to TValue. */
147static void cdata_getconst(CTState *cts, TValue *o, CType *ct)
148{
149 CType *ctt = ctype_child(cts, ct);
150 lua_assert(ctype_isinteger(ctt->info) && ctt->size <= 4);
151 /* Constants are already zero-extended/sign-extended to 32 bits. */
152 if (!(ctt->info & CTF_UNSIGNED))
153 setintV(o, (int32_t)ct->size);
154 else
155 setnumV(o, (lua_Number)(uint32_t)ct->size);
156}
157
158/* Get C data value and convert to TValue. */
159void lj_cdata_get(CTState *cts, CType *s, TValue *o, uint8_t *sp)
160{
161 CTypeID sid;
162
163 if (ctype_isconstval(s->info)) {
164 cdata_getconst(cts, o, s);
165 return;
166 } else if (ctype_isbitfield(s->info)) {
167 lj_cconv_tv_bf(cts, s, o, sp);
168 return;
169 }
170
171 /* Get child type of pointer/array/field. */
172 lua_assert(ctype_ispointer(s->info) || ctype_isfield(s->info));
173 sid = ctype_cid(s->info);
174 s = ctype_get(cts, sid);
175
176 /* Resolve reference for field. */
177 if (ctype_isref(s->info)) {
178 lua_assert(s->size == CTSIZE_PTR);
179 sp = *(uint8_t **)sp;
180 sid = ctype_cid(s->info);
181 s = ctype_get(cts, sid);
182 }
183
184 /* Skip attributes and enums. */
185 while (ctype_isattrib(s->info) || ctype_isenum(s->info))
186 s = ctype_child(cts, s);
187
188 lj_cconv_tv_ct(cts, s, sid, o, sp);
189}
190
191/* -- C data setters ------------------------------------------------------ */
192
193/* Convert TValue and set C data value. */
194void lj_cdata_set(CTState *cts, CType *d, uint8_t *dp, TValue *o, CTInfo qual)
195{
196 if (ctype_isconstval(d->info)) {
197 goto err_const;
198 } else if (ctype_isbitfield(d->info)) {
199 if (((d->info|qual) & CTF_CONST)) goto err_const;
200 lj_cconv_bf_tv(cts, d, dp, o);
201 return;
202 }
203
204 /* Get child type of pointer/array/field. */
205 lua_assert(ctype_ispointer(d->info) || ctype_isfield(d->info));
206 d = ctype_child(cts, d);
207
208 /* Resolve reference for field. */
209 if (ctype_isref(d->info)) {
210 lua_assert(d->size == CTSIZE_PTR);
211 dp = *(uint8_t **)dp;
212 d = ctype_child(cts, d);
213 }
214
215 /* Skip attributes and collect qualifiers. */
216 for (;;) {
217 if (ctype_isattrib(d->info)) {
218 if (ctype_attrib(d->info) == CTA_QUAL) qual |= d->size;
219 } else {
220 break;
221 }
222 d = ctype_child(cts, d);
223 }
224
225 lua_assert(ctype_hassize(d->info) && !ctype_isvoid(d->info));
226
227 if (((d->info|qual) & CTF_CONST)) {
228 err_const:
229 lj_err_caller(cts->L, LJ_ERR_FFI_WRCONST);
230 }
231
232 lj_cconv_ct_tv(cts, d, dp, o, 0);
233}
234
235#endif
diff --git a/src/lj_cdata.h b/src/lj_cdata.h
new file mode 100644
index 00000000..38b6ce16
--- /dev/null
+++ b/src/lj_cdata.h
@@ -0,0 +1,62 @@
1/*
2** C data management.
3** Copyright (C) 2005-2010 Mike Pall. See Copyright Notice in luajit.h
4*/
5
6#ifndef _LJ_CDATA_H
7#define _LJ_CDATA_H
8
9#include "lj_obj.h"
10#include "lj_gc.h"
11#include "lj_ctype.h"
12
13#if LJ_HASFFI
14
15/* Get C data pointer. */
16static LJ_AINLINE void *cdata_getptr(void *p, CTSize sz)
17{
18 if (LJ_64 && sz == 4) { /* Support 32 bit pointers on 64 bit targets. */
19 return ((void *)(uintptr_t)*(uint32_t *)p);
20 } else {
21 lua_assert(sz == CTSIZE_PTR);
22 return *(void **)p;
23 }
24}
25
26/* Set C data pointer. */
27static LJ_AINLINE void cdata_setptr(void *p, CTSize sz, const void *v)
28{
29 if (LJ_64 && sz == 4) { /* Support 32 bit pointers on 64 bit targets. */
30 *(uint32_t *)p = (uint32_t)(uintptr_t)v;
31 } else {
32 lua_assert(sz == CTSIZE_PTR);
33 *(void **)p = (void *)v;
34 }
35}
36
37/* Allocate fixed-size C data object. */
38static LJ_AINLINE GCcdata *lj_cdata_new(CTState *cts, CTypeID id, CTSize sz)
39{
40 GCcdata *cd;
41 lua_assert(lj_ctype_size(cts, id) == sz);
42 cd = (GCcdata *)lj_mem_newgco(cts->L, sizeof(GCcdata) + sz);
43 cd->gct = ~LJ_TCDATA;
44 cd->typeid = ctype_check(cts, id);
45 return cd;
46}
47
48LJ_FUNC GCcdata *lj_cdata_newref(CTState *cts, const void *pp, CTypeID id);
49LJ_FUNC GCcdata *lj_cdata_newv(CTState *cts, CTypeID id, CTSize sz,
50 CTSize align);
51
52LJ_FUNC void LJ_FASTCALL lj_cdata_free(global_State *g, GCcdata *cd);
53
54LJ_FUNC CType *lj_cdata_index(CTState *cts, GCcdata *cd, cTValue *key,
55 uint8_t **pp, CTInfo *qual);
56LJ_FUNC void lj_cdata_get(CTState *cts, CType *s, TValue *o, uint8_t *sp);
57LJ_FUNC void lj_cdata_set(CTState *cts, CType *d, uint8_t *dp, TValue *o,
58 CTInfo qual);
59
60#endif
61
62#endif
diff --git a/src/lj_errmsg.h b/src/lj_errmsg.h
index d9fc615b..1075a9b4 100644
--- a/src/lj_errmsg.h
+++ b/src/lj_errmsg.h
@@ -137,6 +137,23 @@ ERRDEF(XSYNTAX, "syntax error")
137ERRDEF(XBREAK, "no loop to break") 137ERRDEF(XBREAK, "no loop to break")
138ERRDEF(XFOR, LUA_QL("=") " or " LUA_QL("in") " expected") 138ERRDEF(XFOR, LUA_QL("=") " or " LUA_QL("in") " expected")
139 139
140#if LJ_HASFFI
141/* FFI errors. */
142ERRDEF(FFI_INVTYPE, "invalid C type")
143ERRDEF(FFI_INVSIZE, "size of C type is unknown or too large")
144ERRDEF(FFI_BADSCL, "bad storage class")
145ERRDEF(FFI_DECLSPEC, "declaration specifier expected")
146ERRDEF(FFI_BADTAG, "undeclared or implicit tag " LUA_QS)
147ERRDEF(FFI_REDEF, "attempt to redefine " LUA_QS)
148ERRDEF(FFI_INITOV, "too many initializers for " LUA_QS)
149ERRDEF(FFI_BADCONV, "cannot convert " LUA_QS " to " LUA_QS)
150ERRDEF(FFI_BADMEMBER, LUA_QS " has no member named " LUA_QS)
151ERRDEF(FFI_BADIDX, LUA_QS " cannot be indexed")
152ERRDEF(FFI_WRCONST, "attempt to write to constant location")
153ERRDEF(FFI_NYIPACKBIT, "NYI: packed bit fields")
154ERRDEF(FFI_NYICALL, "NYI: C function calls")
155#endif
156
140#undef ERRDEF 157#undef ERRDEF
141 158
142/* Detecting unused error messages: 159/* Detecting unused error messages:
diff --git a/src/lj_gc.c b/src/lj_gc.c
index c9c5e131..e0f74404 100644
--- a/src/lj_gc.c
+++ b/src/lj_gc.c
@@ -19,6 +19,9 @@
19#include "lj_meta.h" 19#include "lj_meta.h"
20#include "lj_state.h" 20#include "lj_state.h"
21#include "lj_frame.h" 21#include "lj_frame.h"
22#if LJ_HASFFI
23#include "lj_cdata.h"
24#endif
22#include "lj_trace.h" 25#include "lj_trace.h"
23#include "lj_vm.h" 26#include "lj_vm.h"
24 27
@@ -373,7 +376,11 @@ static const GCFreeFunc gc_freefunc[] = {
373#else 376#else
374 (GCFreeFunc)0, 377 (GCFreeFunc)0,
375#endif 378#endif
376 (GCFreeFunc)0, /* Placeholder for C data. */ 379#if LJ_HASFFI
380 (GCFreeFunc)lj_cdata_free,
381#else
382 (GCFreeFunc)0,
383#endif
377 (GCFreeFunc)lj_tab_free, 384 (GCFreeFunc)lj_tab_free,
378 (GCFreeFunc)lj_udata_free 385 (GCFreeFunc)lj_udata_free
379}; 386};
diff --git a/src/ljamalg.c b/src/ljamalg.c
index d37daa2f..dac09561 100644
--- a/src/ljamalg.c
+++ b/src/ljamalg.c
@@ -41,6 +41,8 @@
41#include "lj_lex.c" 41#include "lj_lex.c"
42#include "lj_parse.c" 42#include "lj_parse.c"
43#include "lj_ctype.c" 43#include "lj_ctype.c"
44#include "lj_cdata.c"
45#include "lj_cconv.c"
44#include "lj_lib.c" 46#include "lj_lib.c"
45#include "lj_ir.c" 47#include "lj_ir.c"
46#include "lj_opt_mem.c" 48#include "lj_opt_mem.c"