64-bit random fixes
[bpt/guile.git] / libguile / foreign.c
CommitLineData
e2c2a699
AW
1/* Copyright (C) 2010 Free Software Foundation, Inc.
2 *
3 * This library is free software; you can redistribute it and/or
4 * modify it under the terms of the GNU Lesser General Public License
5 * as published by the Free Software Foundation; either version 3 of
6 * the License, or (at your option) any later version.
7 *
8 * This library is distributed in the hope that it will be useful, but
9 * WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * Lesser General Public License for more details.
12 *
13 * You should have received a copy of the GNU Lesser General Public
14 * License along with this library; if not, write to the Free Software
15 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
16 * 02110-1301 USA
17 */
18
19#if HAVE_CONFIG_H
20# include <config.h>
21#endif
22
d8b04f04
AW
23#include <ffi.h>
24
25#include <alignof.h>
e2c2a699 26#include <string.h>
86425e26
LC
27#include <assert.h>
28
ea7d717b 29#include "libguile/_scm.h"
20aafae2 30#include "libguile/bytevectors.h"
d8b04f04 31#include "libguile/instructions.h"
ea7d717b 32#include "libguile/foreign.h"
e2c2a699
AW
33
34\f
35
ab4779ff
AW
36SCM_SYMBOL (sym_void, "void");
37SCM_SYMBOL (sym_float, "float");
38SCM_SYMBOL (sym_double, "double");
39SCM_SYMBOL (sym_uint8, "uint8");
40SCM_SYMBOL (sym_int8, "int8");
41SCM_SYMBOL (sym_uint16, "uint16");
42SCM_SYMBOL (sym_int16, "int16");
43SCM_SYMBOL (sym_uint32, "uint32");
44SCM_SYMBOL (sym_int32, "int32");
45SCM_SYMBOL (sym_uint64, "uint64");
46SCM_SYMBOL (sym_int64, "int64");
dd1464bf
LC
47SCM_SYMBOL (sym_int, "int");
48SCM_SYMBOL (sym_long, "long");
49SCM_SYMBOL (sym_unsigned_int, "unsigned-int");
50SCM_SYMBOL (sym_unsigned_long, "unsigned-long");
51SCM_SYMBOL (sym_size_t, "size_t");
ab4779ff 52
3435f3c0
AW
53/* that's for pointers, you know. */
54SCM_SYMBOL (sym_asterisk, "*");
55
54eb59cf 56SCM_SYMBOL (sym_null, "%null-pointer");
01ad5a7b 57SCM_SYMBOL (sym_null_pointer_error, "null-pointer-error");
54eb59cf
LC
58
59/* The cell representing the null pointer. */
3e5ea35c 60static SCM null_pointer;
3435f3c0 61
d4149a51
LC
62#if SIZEOF_VOID_P == 4
63# define scm_to_uintptr scm_to_uint32
64# define scm_from_uintptr scm_from_uint32
65#elif SIZEOF_VOID_P == 8
66# define scm_to_uintptr scm_to_uint64
67# define scm_from_uintptr scm_from_uint64
68#else
69# error unsupported pointer size
70#endif
71
72
01ad5a7b
LC
73/* Raise a null pointer dereference error. */
74static void
75null_pointer_error (const char *func_name)
76{
77 scm_error (sym_null_pointer_error, func_name,
78 "null pointer dereference", SCM_EOL, SCM_EOL);
79}
80
81\f
d8b04f04
AW
82static SCM cif_to_procedure (SCM cif, SCM func_ptr);
83
84
20aafae2
AW
85static SCM foreign_weak_refs = SCM_BOOL_F;
86
87static void
88register_weak_reference (SCM from, SCM to)
89{
90 scm_hashq_set_x (foreign_weak_refs, from, to);
91}
d4149a51 92
e2c2a699
AW
93static void
94foreign_finalizer_trampoline (GC_PTR ptr, GC_PTR data)
95{
96 scm_t_foreign_finalizer finalizer = data;
d4149a51 97 finalizer (SCM_FOREIGN_POINTER (PTR2SCM (ptr)));
e2c2a699
AW
98}
99
d4149a51
LC
100SCM_DEFINE (scm_make_pointer, "make-pointer", 1, 1, 0,
101 (SCM address, SCM finalizer),
102 "Return a foreign pointer object pointing to @var{address}. "
103 "If @var{finalizer} is passed, it should be a pointer to a "
104 "one-argument C function that will be called when the pointer "
105 "object becomes unreachable.")
106#define FUNC_NAME s_scm_make_pointer
107{
108 void *c_finalizer;
109 scm_t_uintptr c_address;
110 SCM result;
111
112 c_address = scm_to_uintptr (address);
113 if (SCM_UNBNDP (finalizer))
114 c_finalizer = NULL;
115 else
116 {
117 SCM_VALIDATE_FOREIGN (2, finalizer);
118 c_finalizer = SCM_FOREIGN_POINTER (finalizer);
119 }
120
121 if (c_address == 0 && c_finalizer == NULL)
122 result = null_pointer;
123 else
124 result = scm_take_foreign_pointer ((void *) c_address, c_finalizer);
125
126 return result;
127}
128#undef FUNC_NAME
129
e2c2a699 130SCM
d4149a51 131scm_take_foreign_pointer (void *ptr, scm_t_foreign_finalizer finalizer)
e2c2a699 132{
9fdee5b4 133 SCM ret;
52fd9639 134 scm_t_bits word0;
d4149a51
LC
135
136 word0 = scm_tc7_foreign | (finalizer ? (1 << 16UL) : 0UL);
e2c2a699 137
4551e860 138 ret = scm_cell (word0, (scm_t_bits) ptr);
e2c2a699
AW
139 if (finalizer)
140 {
141 /* Register a finalizer for the newly created instance. */
142 GC_finalization_proc prev_finalizer;
143 GC_PTR prev_finalizer_data;
9fdee5b4 144 GC_REGISTER_FINALIZER_NO_ORDER (SCM2PTR (ret),
e2c2a699
AW
145 foreign_finalizer_trampoline,
146 finalizer,
147 &prev_finalizer,
148 &prev_finalizer_data);
149 }
150
9fdee5b4 151 return ret;
e2c2a699
AW
152}
153
d4149a51 154SCM_DEFINE (scm_foreign_address, "foreign-address", 1, 0, 0,
20aafae2 155 (SCM foreign),
d4149a51
LC
156 "Return the numerical value of @var{foreign}.")
157#define FUNC_NAME s_scm_foreign_address
e2c2a699 158{
52fd9639 159 SCM_VALIDATE_FOREIGN (1, foreign);
01ad5a7b 160
d4149a51 161 return scm_from_uintptr ((scm_t_uintptr) SCM_FOREIGN_POINTER (foreign));
e2c2a699
AW
162}
163#undef FUNC_NAME
164
17fc9efe
LC
165SCM_DEFINE (scm_dereference_pointer, "dereference-pointer", 1, 0, 0,
166 (SCM foreign),
167 "Return the a foreign object representing the pointer "
168 "pointed to by @var{foreign}.")
169#define FUNC_NAME s_scm_dereference_pointer
170{
171 SCM_VALIDATE_FOREIGN (1, foreign);
172
173 return scm_take_foreign_pointer (* (void **) SCM_FOREIGN_POINTER (foreign),
174 NULL);
175}
176#undef FUNC_NAME
177
d4149a51
LC
178SCM_DEFINE (scm_foreign_to_bytevector, "foreign->bytevector", 2, 2, 0,
179 (SCM foreign, SCM len, SCM offset, SCM uvec_type),
20aafae2
AW
180 "Return a bytevector aliasing the memory pointed to by\n"
181 "@var{foreign}.\n\n"
182 "@var{foreign} must be a void pointer, a foreign whose type is\n"
183 "@var{void}. By default, the resulting bytevector will alias\n"
184 "all of the memory pointed to by @var{foreign}, from beginning\n"
185 "to end, treated as a @code{vu8} array.\n\n"
186 "The user may specify an alternate default interpretation for\n"
187 "the memory by passing the @var{uvec_type} argument, to indicate\n"
188 "that the memory is an array of elements of that type.\n"
189 "@var{uvec_type} should be something that\n"
190 "@code{uniform-vector-element-type} would return, like @code{f32}\n"
191 "or @code{s16}.\n\n"
192 "Users may also specify that the bytevector should only alias a\n"
193 "subset of the memory, by specifying @var{offset} and @var{len}\n"
194 "arguments.")
195#define FUNC_NAME s_scm_foreign_to_bytevector
196{
197 SCM ret;
198 scm_t_int8 *ptr;
199 size_t boffset, blen;
200 scm_t_array_element_type btype;
201
d4149a51
LC
202 SCM_VALIDATE_FOREIGN (1, foreign);
203 ptr = SCM_FOREIGN_POINTER (foreign);
54eb59cf
LC
204
205 if (SCM_UNLIKELY (ptr == NULL))
01ad5a7b 206 null_pointer_error (FUNC_NAME);
54eb59cf 207
20aafae2
AW
208 if (SCM_UNBNDP (uvec_type))
209 btype = SCM_ARRAY_ELEMENT_TYPE_VU8;
210 else
211 {
212 int i;
213 for (i = 0; i <= SCM_ARRAY_ELEMENT_TYPE_LAST; i++)
214 if (scm_is_eq (uvec_type, scm_i_array_element_types[i]))
215 break;
216 switch (i)
217 {
218 case SCM_ARRAY_ELEMENT_TYPE_VU8:
219 case SCM_ARRAY_ELEMENT_TYPE_U8:
220 case SCM_ARRAY_ELEMENT_TYPE_S8:
221 case SCM_ARRAY_ELEMENT_TYPE_U16:
222 case SCM_ARRAY_ELEMENT_TYPE_S16:
223 case SCM_ARRAY_ELEMENT_TYPE_U32:
224 case SCM_ARRAY_ELEMENT_TYPE_S32:
225 case SCM_ARRAY_ELEMENT_TYPE_U64:
226 case SCM_ARRAY_ELEMENT_TYPE_S64:
227 case SCM_ARRAY_ELEMENT_TYPE_F32:
228 case SCM_ARRAY_ELEMENT_TYPE_F64:
229 case SCM_ARRAY_ELEMENT_TYPE_C32:
230 case SCM_ARRAY_ELEMENT_TYPE_C64:
231 btype = i;
232 break;
233 default:
234 scm_wrong_type_arg_msg (FUNC_NAME, SCM_ARG1, uvec_type,
235 "uniform vector type");
236 }
237 }
d4149a51 238
20aafae2
AW
239 if (SCM_UNBNDP (offset))
240 boffset = 0;
20aafae2
AW
241 else
242 boffset = scm_to_size_t (offset);
243
d4149a51 244 blen = scm_to_size_t (len);
20aafae2
AW
245
246 ret = scm_c_take_typed_bytevector (ptr + boffset, blen, btype);
247 register_weak_reference (ret, foreign);
248 return ret;
249}
250#undef FUNC_NAME
251
252SCM_DEFINE (scm_bytevector_to_foreign, "bytevector->foreign", 1, 2, 0,
253 (SCM bv, SCM offset, SCM len),
254 "Return a foreign pointer aliasing the memory pointed to by\n"
255 "@var{bv}.\n\n"
256 "The resulting foreign will be a void pointer, a foreign whose\n"
257 "type is @code{void}. By default it will alias all of the\n"
258 "memory pointed to by @var{bv}, from beginning to end.\n\n"
259 "Users may explicily specify that the foreign should only alias a\n"
260 "subset of the memory, by specifying @var{offset} and @var{len}\n"
261 "arguments.")
262#define FUNC_NAME s_scm_bytevector_to_foreign
263{
264 SCM ret;
265 scm_t_int8 *ptr;
266 size_t boffset, blen;
267
268 SCM_VALIDATE_BYTEVECTOR (1, bv);
269 ptr = SCM_BYTEVECTOR_CONTENTS (bv);
270
271 if (SCM_UNBNDP (offset))
272 boffset = 0;
273 else
274 boffset = scm_to_unsigned_integer (offset, 0,
275 SCM_BYTEVECTOR_LENGTH (bv) - 1);
276
277 if (SCM_UNBNDP (len))
278 blen = SCM_BYTEVECTOR_LENGTH (bv) - boffset;
279 else
280 blen = scm_to_unsigned_integer (len, 0,
281 SCM_BYTEVECTOR_LENGTH (bv) - boffset);
282
d4149a51 283 ret = scm_take_foreign_pointer (ptr + boffset, NULL);
20aafae2
AW
284 register_weak_reference (ret, bv);
285 return ret;
286}
287#undef FUNC_NAME
288
3435f3c0
AW
289SCM_DEFINE (scm_foreign_set_finalizer_x, "foreign-set-finalizer!", 2, 0, 0,
290 (SCM foreign, SCM finalizer),
291 "Arrange for the C procedure wrapped by @var{finalizer} to be\n"
292 "called on the pointer wrapped by @var{foreign} when @var{foreign}\n"
293 "becomes unreachable. Note: the C procedure should not call into\n"
294 "Scheme. If you need a Scheme finalizer, use guardians.")
295#define FUNC_NAME s_scm_foreign_set_finalizer_x
296{
297 void *c_finalizer;
298 GC_finalization_proc prev_finalizer;
299 GC_PTR prev_finalizer_data;
300
d4149a51
LC
301 SCM_VALIDATE_FOREIGN (1, foreign);
302 SCM_VALIDATE_FOREIGN (2, finalizer);
303
304 c_finalizer = SCM_FOREIGN_POINTER (finalizer);
3435f3c0
AW
305
306 SCM_SET_CELL_WORD_0 (foreign, SCM_CELL_WORD_0 (foreign) | (1<<16));
307
308 GC_REGISTER_FINALIZER_NO_ORDER (SCM2PTR (foreign),
309 foreign_finalizer_trampoline,
310 c_finalizer,
311 &prev_finalizer,
312 &prev_finalizer_data);
313
314 return SCM_UNSPECIFIED;
315}
316#undef FUNC_NAME
317
318\f
319
e2c2a699
AW
320void
321scm_i_foreign_print (SCM foreign, SCM port, scm_print_state *pstate)
322{
323 scm_puts ("#<foreign ", port);
d4149a51 324 scm_display (scm_foreign_address (foreign), port);
e2c2a699
AW
325 scm_putc ('>', port);
326}
327
328\f
329
b9264dc5
AW
330SCM_DEFINE (scm_alignof, "alignof", 1, 0, 0, (SCM type),
331 "Return the alignment of @var{type}, in bytes.\n\n"
332 "@var{type} should be a valid C type, like @code{int}.\n"
333 "Alternately @var{type} may be the symbol @code{*}, in which\n"
334 "case the alignment of a pointer is returned. @var{type} may\n"
335 "also be a list of types, in which case the alignment of a\n"
336 "@code{struct} with ABI-conventional packing is returned.")
9a396cbd
AW
337#define FUNC_NAME s_scm_alignof
338{
339 if (SCM_I_INUMP (type))
340 {
341 switch (SCM_I_INUM (type))
342 {
343 case SCM_FOREIGN_TYPE_FLOAT:
344 return scm_from_size_t (alignof (float));
345 case SCM_FOREIGN_TYPE_DOUBLE:
346 return scm_from_size_t (alignof (double));
347 case SCM_FOREIGN_TYPE_UINT8:
348 return scm_from_size_t (alignof (scm_t_uint8));
349 case SCM_FOREIGN_TYPE_INT8:
350 return scm_from_size_t (alignof (scm_t_int8));
351 case SCM_FOREIGN_TYPE_UINT16:
352 return scm_from_size_t (alignof (scm_t_uint16));
353 case SCM_FOREIGN_TYPE_INT16:
354 return scm_from_size_t (alignof (scm_t_int16));
355 case SCM_FOREIGN_TYPE_UINT32:
356 return scm_from_size_t (alignof (scm_t_uint32));
357 case SCM_FOREIGN_TYPE_INT32:
358 return scm_from_size_t (alignof (scm_t_int32));
359 case SCM_FOREIGN_TYPE_UINT64:
360 return scm_from_size_t (alignof (scm_t_uint64));
361 case SCM_FOREIGN_TYPE_INT64:
362 return scm_from_size_t (alignof (scm_t_int64));
363 default:
364 scm_wrong_type_arg (FUNC_NAME, 1, type);
365 }
366 }
3435f3c0
AW
367 else if (scm_is_eq (type, sym_asterisk))
368 /* a pointer */
369 return scm_from_size_t (alignof (void*));
9a396cbd
AW
370 else if (scm_is_pair (type))
371 /* a struct, yo */
372 return scm_alignof (scm_car (type));
373 else
374 scm_wrong_type_arg (FUNC_NAME, 1, type);
375}
376#undef FUNC_NAME
377
b9264dc5
AW
378SCM_DEFINE (scm_sizeof, "sizeof", 1, 0, 0, (SCM type),
379 "Return the size of @var{type}, in bytes.\n\n"
380 "@var{type} should be a valid C type, like @code{int}.\n"
381 "Alternately @var{type} may be the symbol @code{*}, in which\n"
382 "case the size of a pointer is returned. @var{type} may also\n"
383 "be a list of types, in which case the size of a @code{struct}\n"
384 "with ABI-conventional packing is returned.")
9a396cbd
AW
385#define FUNC_NAME s_scm_sizeof
386{
387 if (SCM_I_INUMP (type))
388 {
389 switch (SCM_I_INUM (type))
390 {
391 case SCM_FOREIGN_TYPE_FLOAT:
392 return scm_from_size_t (sizeof (float));
393 case SCM_FOREIGN_TYPE_DOUBLE:
394 return scm_from_size_t (sizeof (double));
395 case SCM_FOREIGN_TYPE_UINT8:
396 return scm_from_size_t (sizeof (scm_t_uint8));
397 case SCM_FOREIGN_TYPE_INT8:
398 return scm_from_size_t (sizeof (scm_t_int8));
399 case SCM_FOREIGN_TYPE_UINT16:
400 return scm_from_size_t (sizeof (scm_t_uint16));
401 case SCM_FOREIGN_TYPE_INT16:
402 return scm_from_size_t (sizeof (scm_t_int16));
403 case SCM_FOREIGN_TYPE_UINT32:
404 return scm_from_size_t (sizeof (scm_t_uint32));
405 case SCM_FOREIGN_TYPE_INT32:
406 return scm_from_size_t (sizeof (scm_t_int32));
407 case SCM_FOREIGN_TYPE_UINT64:
408 return scm_from_size_t (sizeof (scm_t_uint64));
409 case SCM_FOREIGN_TYPE_INT64:
410 return scm_from_size_t (sizeof (scm_t_int64));
411 default:
412 scm_wrong_type_arg (FUNC_NAME, 1, type);
413 }
414 }
3435f3c0
AW
415 else if (scm_is_eq (type, sym_asterisk))
416 /* a pointer */
417 return scm_from_size_t (sizeof (void*));
9a396cbd
AW
418 else if (scm_is_pair (type))
419 {
420 /* a struct */
421 size_t off = 0;
422 while (scm_is_pair (type))
423 {
424 off = ROUND_UP (off, scm_to_size_t (scm_alignof (scm_car (type))));
425 off += scm_to_size_t (scm_sizeof (scm_car (type)));
426 type = scm_cdr (type);
427 }
428 return scm_from_size_t (off);
429 }
430 else
431 scm_wrong_type_arg (FUNC_NAME, 1, type);
432}
433#undef FUNC_NAME
434
435
d8b04f04
AW
436/* return 1 on success, 0 on failure */
437static int
438parse_ffi_type (SCM type, int return_p, long *n_structs, long *n_struct_elts)
439{
440 if (SCM_I_INUMP (type))
441 {
442 if ((SCM_I_INUM (type) < 0 )
443 || (SCM_I_INUM (type) > SCM_FOREIGN_TYPE_LAST))
444 return 0;
445 else if (SCM_I_INUM (type) == SCM_FOREIGN_TYPE_VOID && !return_p)
446 return 0;
447 else
448 return 1;
449 }
3435f3c0
AW
450 else if (scm_is_eq (type, sym_asterisk))
451 /* a pointer */
452 return 1;
d8b04f04
AW
453 else
454 {
455 long len;
456
457 len = scm_ilength (type);
458 if (len < 1)
459 return 0;
460 while (len--)
461 {
462 if (!parse_ffi_type (scm_car (type), 0, n_structs, n_struct_elts))
463 return 0;
464 (*n_struct_elts)++;
465 type = scm_cdr (type);
466 }
467 (*n_structs)++;
468 return 1;
469 }
470}
471
472static void
473fill_ffi_type (SCM type, ffi_type *ftype, ffi_type ***type_ptrs,
474 ffi_type **types)
475{
476 if (SCM_I_INUMP (type))
477 {
478 switch (SCM_I_INUM (type))
479 {
480 case SCM_FOREIGN_TYPE_FLOAT:
481 *ftype = ffi_type_float;
482 return;
483 case SCM_FOREIGN_TYPE_DOUBLE:
484 *ftype = ffi_type_double;
485 return;
486 case SCM_FOREIGN_TYPE_UINT8:
487 *ftype = ffi_type_uint8;
488 return;
489 case SCM_FOREIGN_TYPE_INT8:
490 *ftype = ffi_type_sint8;
491 return;
492 case SCM_FOREIGN_TYPE_UINT16:
493 *ftype = ffi_type_uint16;
494 return;
495 case SCM_FOREIGN_TYPE_INT16:
496 *ftype = ffi_type_sint16;
497 return;
498 case SCM_FOREIGN_TYPE_UINT32:
499 *ftype = ffi_type_uint32;
500 return;
501 case SCM_FOREIGN_TYPE_INT32:
502 *ftype = ffi_type_sint32;
503 return;
504 case SCM_FOREIGN_TYPE_UINT64:
505 *ftype = ffi_type_uint64;
506 return;
507 case SCM_FOREIGN_TYPE_INT64:
508 *ftype = ffi_type_sint64;
509 return;
510 case SCM_FOREIGN_TYPE_VOID:
511 *ftype = ffi_type_void;
512 return;
513 default:
75383ddb
AW
514 scm_wrong_type_arg_msg ("make-foreign-function", 0, type,
515 "foreign type");
d8b04f04
AW
516 }
517 }
3435f3c0
AW
518 else if (scm_is_eq (type, sym_asterisk))
519 /* a pointer */
520 {
521 *ftype = ffi_type_pointer;
522 return;
523 }
d8b04f04
AW
524 else
525 {
526 long i, len;
527
528 len = scm_ilength (type);
529
530 ftype->size = 0;
531 ftype->alignment = 0;
532 ftype->type = FFI_TYPE_STRUCT;
533 ftype->elements = *type_ptrs;
534 *type_ptrs += len + 1;
535
536 for (i = 0; i < len; i++)
537 {
9a396cbd
AW
538 ftype->elements[i] = *types;
539 *types += 1;
d8b04f04
AW
540 fill_ffi_type (scm_car (type), ftype->elements[i],
541 type_ptrs, types);
542 type = scm_cdr (type);
543 }
544 ftype->elements[i] = NULL;
545 }
546}
547
548SCM_DEFINE (scm_make_foreign_function, "make-foreign-function", 3, 0, 0,
549 (SCM return_type, SCM func_ptr, SCM arg_types),
71725997
AW
550 "Make a foreign function.\n\n"
551 "Given the foreign void pointer @var{func_ptr}, its argument and\n"
552 "return types @var{arg_types} and @var{return_type}, return a\n"
553 "procedure that will pass arguments to the foreign function\n"
554 "and return appropriate values.\n\n"
555 "@var{arg_types} should be a list of foreign types.\n"
556 "@code{return_type} should be a foreign type.")
d8b04f04
AW
557#define FUNC_NAME s_scm_make_foreign_function
558{
559 SCM walk, scm_cif;
560 long i, nargs, n_structs, n_struct_elts;
561 size_t cif_len;
562 char *mem;
563 ffi_cif *cif;
564 ffi_type **type_ptrs;
565 ffi_type *types;
566
d4149a51
LC
567 SCM_VALIDATE_FOREIGN (2, func_ptr);
568
d8b04f04
AW
569 nargs = scm_ilength (arg_types);
570 SCM_ASSERT (nargs >= 0, arg_types, 3, FUNC_NAME);
571 /* fixme: assert nargs < 1<<32 */
572 n_structs = n_struct_elts = 0;
573
574 /* For want of talloc, we're going to have to do this in two passes: first we
575 figure out how much memory is needed for all types, then we allocate the
576 cif and the types all in one block. */
577 if (!parse_ffi_type (return_type, 1, &n_structs, &n_struct_elts))
578 scm_wrong_type_arg (FUNC_NAME, 1, return_type);
579 for (walk = arg_types; scm_is_pair (walk); walk = scm_cdr (walk))
580 if (!parse_ffi_type (scm_car (walk), 0, &n_structs, &n_struct_elts))
581 scm_wrong_type_arg (FUNC_NAME, 3, scm_car (walk));
582
583 /* the memory: with space for the cif itself */
584 cif_len = sizeof (ffi_cif);
585
586 /* then ffi_type pointers: one for each arg, one for each struct
587 element, and one for each struct (for null-termination) */
588 cif_len = (ROUND_UP (cif_len, alignof(void*))
589 + (nargs + n_structs + n_struct_elts)*sizeof(void*));
590
591 /* then the ffi_type structs themselves, one per arg and struct element, and
592 one for the return val */
593 cif_len = (ROUND_UP (cif_len, alignof(ffi_type))
594 + (nargs + n_struct_elts + 1)*sizeof(ffi_type));
087aa6aa
LC
595
596 mem = scm_gc_malloc_pointerless (cif_len, "foreign");
d4149a51 597 scm_cif = scm_take_foreign_pointer (mem, NULL);
087aa6aa
LC
598 cif = (ffi_cif *) mem;
599
d8b04f04
AW
600 /* reuse cif_len to walk through the mem */
601 cif_len = ROUND_UP (sizeof (ffi_cif), alignof(void*));
602 type_ptrs = (ffi_type**)(mem + cif_len);
603 cif_len = ROUND_UP (cif_len
604 + (nargs + n_structs + n_struct_elts)*sizeof(void*),
605 alignof(ffi_type));
606 types = (ffi_type*)(mem + cif_len);
607
608 /* whew. now knit the pointers together. */
609 cif->rtype = types++;
610 fill_ffi_type (return_type, cif->rtype, &type_ptrs, &types);
611 cif->arg_types = type_ptrs;
612 type_ptrs += nargs;
613 for (walk = arg_types, i = 0; scm_is_pair (walk); walk = scm_cdr (walk), i++)
614 {
615 cif->arg_types[i] = types++;
616 fill_ffi_type (scm_car (walk), cif->arg_types[i], &type_ptrs, &types);
617 }
618
619 /* round out the cif, and we're done. */
620 cif->abi = FFI_DEFAULT_ABI;
621 cif->nargs = nargs;
622 cif->bytes = 0;
623 cif->flags = 0;
624
625 if (FFI_OK != ffi_prep_cif (cif, FFI_DEFAULT_ABI, cif->nargs, cif->rtype,
626 cif->arg_types))
627 scm_misc_error (FUNC_NAME, "ffi_prep_cif failed", SCM_EOL);
628
629 return cif_to_procedure (scm_cif, func_ptr);
630}
631#undef FUNC_NAME
632
633\f
634
635/* Pre-generate trampolines for less than 10 arguments. */
636
637#ifdef WORDS_BIGENDIAN
638#define OBJCODE_HEADER 0, 0, 0, 8, 0, 0, 0, 40
639#define META_HEADER 0, 0, 0, 32, 0, 0, 0, 0
640#else
641#define OBJCODE_HEADER 8, 0, 0, 0, 40, 0, 0, 0
642#define META_HEADER 32, 0, 0, 0, 0, 0, 0, 0
643#endif
644
645#define CODE(nreq) \
646 OBJCODE_HEADER, \
647 /* 0 */ scm_op_assert_nargs_ee, 0, nreq, /* assert number of args */ \
648 /* 3 */ scm_op_object_ref, 0, /* push the pair with the cif and the function pointer */ \
649 /* 5 */ scm_op_foreign_call, nreq, /* and call (will return value as well) */ \
650 /* 7 */ scm_op_nop, \
651 /* 8 */ META (3, 7, nreq)
652
653#define META(start, end, nreq) \
654 META_HEADER, \
655 /* 0 */ scm_op_make_eol, /* bindings */ \
656 /* 1 */ scm_op_make_eol, /* sources */ \
657 /* 2 */ scm_op_make_int8, start, scm_op_make_int8, end, /* arity: from ip N to ip N */ \
658 /* 6 */ scm_op_make_int8, nreq, /* the arity is N required args */ \
659 /* 8 */ scm_op_list, 0, 3, /* make a list of those 3 vals */ \
660 /* 11 */ scm_op_list, 0, 1, /* and the arities will be a list of that one list */ \
661 /* 14 */ scm_op_load_symbol, 0, 0, 4, 'n', 'a', 'm', 'e', /* `name' */ \
662 /* 22 */ scm_op_object_ref, 1, /* the name from the object table */ \
663 /* 24 */ scm_op_cons, /* make a pair for the properties */ \
664 /* 25 */ scm_op_list, 0, 4, /* pack bindings, sources, and arities into list */ \
665 /* 28 */ scm_op_return, /* and return */ \
666 /* 29 */ scm_op_nop, scm_op_nop, scm_op_nop \
667 /* 32 */
668
669static const struct
670{
671 scm_t_uint64 dummy; /* ensure 8-byte alignment; perhaps there's a better way */
672 const scm_t_uint8 bytes[10 * (sizeof (struct scm_objcode) + 8
673 + sizeof (struct scm_objcode) + 32)];
674} raw_bytecode = {
675 0,
676 {
677 CODE (0), CODE (1), CODE (2), CODE (3), CODE (4),
678 CODE (5), CODE (6), CODE (7), CODE (8), CODE (9)
679 }
680};
681
682#undef CODE
683#undef META
684#undef OBJCODE_HEADER
685#undef META_HEADER
686
687/*
688 (defun generate-objcode-cells (n)
689 "Generate objcode cells for up to N arguments"
690 (interactive "p")
691 (let ((i 0))
692 (while (< i n)
693 (insert
694 (format " { STATIC_OBJCODE_TAG, SCM_PACK (raw_bytecode.bytes + %d) },\n"
695 (* (+ 4 4 8 4 4 32) i)))
696 (insert " { SCM_BOOL_F, SCM_PACK (0) },\n")
697 (setq i (1+ i)))))
698*/
699#define STATIC_OBJCODE_TAG \
700 SCM_PACK (scm_tc7_objcode | (SCM_F_OBJCODE_IS_STATIC << 8))
701
702static const struct
703{
704 scm_t_uint64 dummy; /* alignment */
705 scm_t_cell cells[10 * 2]; /* 10 double cells */
706} objcode_cells = {
707 0,
708 /* C-u 1 0 M-x generate-objcode-cells RET */
709 {
710 { STATIC_OBJCODE_TAG, SCM_PACK (raw_bytecode.bytes + 0) },
711 { SCM_BOOL_F, SCM_PACK (0) },
712 { STATIC_OBJCODE_TAG, SCM_PACK (raw_bytecode.bytes + 56) },
713 { SCM_BOOL_F, SCM_PACK (0) },
714 { STATIC_OBJCODE_TAG, SCM_PACK (raw_bytecode.bytes + 112) },
715 { SCM_BOOL_F, SCM_PACK (0) },
716 { STATIC_OBJCODE_TAG, SCM_PACK (raw_bytecode.bytes + 168) },
717 { SCM_BOOL_F, SCM_PACK (0) },
718 { STATIC_OBJCODE_TAG, SCM_PACK (raw_bytecode.bytes + 224) },
719 { SCM_BOOL_F, SCM_PACK (0) },
720 { STATIC_OBJCODE_TAG, SCM_PACK (raw_bytecode.bytes + 280) },
721 { SCM_BOOL_F, SCM_PACK (0) },
722 { STATIC_OBJCODE_TAG, SCM_PACK (raw_bytecode.bytes + 336) },
723 { SCM_BOOL_F, SCM_PACK (0) },
724 { STATIC_OBJCODE_TAG, SCM_PACK (raw_bytecode.bytes + 392) },
725 { SCM_BOOL_F, SCM_PACK (0) },
726 { STATIC_OBJCODE_TAG, SCM_PACK (raw_bytecode.bytes + 448) },
727 { SCM_BOOL_F, SCM_PACK (0) },
728 { STATIC_OBJCODE_TAG, SCM_PACK (raw_bytecode.bytes + 504) },
729 { SCM_BOOL_F, SCM_PACK (0) }
730 }
731};
732
733static const SCM objcode_trampolines[10] = {
734 SCM_PACK (objcode_cells.cells+0),
735 SCM_PACK (objcode_cells.cells+2),
736 SCM_PACK (objcode_cells.cells+4),
737 SCM_PACK (objcode_cells.cells+6),
738 SCM_PACK (objcode_cells.cells+8),
739 SCM_PACK (objcode_cells.cells+10),
740 SCM_PACK (objcode_cells.cells+12),
741 SCM_PACK (objcode_cells.cells+14),
742 SCM_PACK (objcode_cells.cells+16),
743 SCM_PACK (objcode_cells.cells+18),
744};
745
746static SCM
747cif_to_procedure (SCM cif, SCM func_ptr)
748{
d4149a51
LC
749 ffi_cif *c_cif;
750 unsigned int nargs;
d8b04f04 751 SCM objcode, table, ret;
d4149a51
LC
752
753 c_cif = (ffi_cif *) SCM_FOREIGN_POINTER (cif);
754 nargs = c_cif->nargs;
755
d8b04f04
AW
756 if (nargs < 10)
757 objcode = objcode_trampolines[nargs];
758 else
75383ddb
AW
759 scm_misc_error ("make-foreign-function", "args >= 10 currently unimplemented",
760 SCM_EOL);
d8b04f04
AW
761
762 table = scm_c_make_vector (2, SCM_UNDEFINED);
763 SCM_SIMPLE_VECTOR_SET (table, 0, scm_cons (cif, func_ptr));
764 SCM_SIMPLE_VECTOR_SET (table, 1, SCM_BOOL_F); /* name */
765 ret = scm_make_program (objcode, table, SCM_BOOL_F);
766
767 return ret;
768}
769
165a8643 770/* Set *LOC to the foreign representation of X with TYPE. */
4d9130a5 771static void
165a8643 772unpack (const ffi_type *type, void *loc, SCM x)
4d9130a5
AW
773{
774 switch (type->type)
775 {
776 case FFI_TYPE_FLOAT:
165a8643 777 *(float *) loc = scm_to_double (x);
4d9130a5
AW
778 break;
779 case FFI_TYPE_DOUBLE:
165a8643 780 *(double *) loc = scm_to_double (x);
4d9130a5
AW
781 break;
782 case FFI_TYPE_UINT8:
165a8643 783 *(scm_t_uint8 *) loc = scm_to_uint8 (x);
4d9130a5
AW
784 break;
785 case FFI_TYPE_SINT8:
165a8643 786 *(scm_t_int8 *) loc = scm_to_int8 (x);
4d9130a5
AW
787 break;
788 case FFI_TYPE_UINT16:
165a8643 789 *(scm_t_uint16 *) loc = scm_to_uint16 (x);
4d9130a5
AW
790 break;
791 case FFI_TYPE_SINT16:
165a8643 792 *(scm_t_int16 *) loc = scm_to_int16 (x);
4d9130a5
AW
793 break;
794 case FFI_TYPE_UINT32:
165a8643 795 *(scm_t_uint32 *) loc = scm_to_uint32 (x);
4d9130a5
AW
796 break;
797 case FFI_TYPE_SINT32:
165a8643 798 *(scm_t_int32 *) loc = scm_to_int32 (x);
4d9130a5
AW
799 break;
800 case FFI_TYPE_UINT64:
165a8643 801 *(scm_t_uint64 *) loc = scm_to_uint64 (x);
4d9130a5
AW
802 break;
803 case FFI_TYPE_SINT64:
165a8643 804 *(scm_t_int64 *) loc = scm_to_int64 (x);
4d9130a5
AW
805 break;
806 case FFI_TYPE_STRUCT:
d4149a51 807 memcpy (loc, SCM_FOREIGN_POINTER (x), type->size);
4d9130a5
AW
808 break;
809 case FFI_TYPE_POINTER:
d4149a51 810 *(void **) loc = SCM_FOREIGN_POINTER (x);
4d9130a5
AW
811 break;
812 default:
813 abort ();
814 }
815}
816
165a8643 817/* Return a Scheme representation of the foreign value at LOC of type TYPE. */
4d9130a5 818static SCM
165a8643 819pack (const ffi_type * type, const void *loc)
4d9130a5
AW
820{
821 switch (type->type)
822 {
823 case FFI_TYPE_VOID:
824 return SCM_UNSPECIFIED;
825 case FFI_TYPE_FLOAT:
165a8643 826 return scm_from_double (*(float *) loc);
4d9130a5 827 case FFI_TYPE_DOUBLE:
165a8643 828 return scm_from_double (*(double *) loc);
4d9130a5 829 case FFI_TYPE_UINT8:
165a8643 830 return scm_from_uint8 (*(scm_t_uint8 *) loc);
4d9130a5 831 case FFI_TYPE_SINT8:
165a8643 832 return scm_from_int8 (*(scm_t_int8 *) loc);
4d9130a5 833 case FFI_TYPE_UINT16:
165a8643 834 return scm_from_uint16 (*(scm_t_uint16 *) loc);
4d9130a5 835 case FFI_TYPE_SINT16:
165a8643 836 return scm_from_int16 (*(scm_t_int16 *) loc);
4d9130a5 837 case FFI_TYPE_UINT32:
165a8643 838 return scm_from_uint32 (*(scm_t_uint32 *) loc);
4d9130a5 839 case FFI_TYPE_SINT32:
165a8643 840 return scm_from_int32 (*(scm_t_int32 *) loc);
4d9130a5 841 case FFI_TYPE_UINT64:
165a8643 842 return scm_from_uint64 (*(scm_t_uint64 *) loc);
4d9130a5 843 case FFI_TYPE_SINT64:
165a8643 844 return scm_from_int64 (*(scm_t_int64 *) loc);
4d9130a5
AW
845 case FFI_TYPE_STRUCT:
846 {
165a8643
LC
847 void *mem = scm_gc_malloc_pointerless (type->size, "foreign");
848 memcpy (mem, loc, type->size);
d4149a51 849 return scm_take_foreign_pointer (mem, NULL);
4d9130a5
AW
850 }
851 case FFI_TYPE_POINTER:
d4149a51 852 return scm_take_foreign_pointer (*(void **) loc, NULL);
4d9130a5
AW
853 default:
854 abort ();
855 }
856}
857
165a8643 858
4d9130a5 859SCM
165a8643 860scm_i_foreign_call (SCM foreign, const SCM *argv)
4d9130a5
AW
861{
862 /* FOREIGN is the pair that cif_to_procedure set as the 0th element of the
863 objtable. */
864 ffi_cif *cif;
b577bc90 865 void (*func) (void);
4d9130a5
AW
866 scm_t_uint8 *data;
867 void *rvalue;
868 void **args;
869 unsigned i;
a2c69049 870 size_t arg_size;
4d9130a5
AW
871 scm_t_ptrdiff off;
872
d4149a51
LC
873 cif = SCM_FOREIGN_POINTER (SCM_CAR (foreign));
874 func = SCM_FOREIGN_POINTER (SCM_CDR (foreign));
a2c69049
LC
875
876 /* Argument pointers. */
b577bc90 877 args = alloca (sizeof (void *) * cif->nargs);
a2c69049 878
86425e26
LC
879 /* Compute the worst-case amount of memory needed to store all the argument
880 values. Note: as of libffi 3.0.9 `cif->bytes' is undocumented and is zero,
881 so it can't be used for that purpose. */
882 for (i = 0, arg_size = 0; i < cif->nargs; i++)
883 arg_size += cif->arg_types[i]->size + cif->arg_types[i]->alignment - 1;
a2c69049
LC
884
885 /* Space for argument values, followed by return value. */
86425e26
LC
886 data = alloca (arg_size + cif->rtype->size
887 + max (sizeof (void *), cif->rtype->alignment));
a2c69049 888
165a8643
LC
889 /* Unpack ARGV to native values, setting ARGV pointers. */
890 for (i = 0, off = 0;
891 i < cif->nargs;
86425e26
LC
892 off = (scm_t_uint8 *) args[i] - data + cif->arg_types[i]->size,
893 i++)
4d9130a5 894 {
86425e26
LC
895 /* Suitably align the storage area for argument I. */
896 args[i] = (void *) ROUND_UP ((scm_t_uintptr) data + off,
897 cif->arg_types[i]->alignment);
898 assert ((scm_t_uintptr) args[i] % cif->arg_types[i]->alignment == 0);
4d9130a5 899 unpack (cif->arg_types[i], args[i], argv[i]);
4d9130a5 900 }
165a8643 901
86425e26
LC
902 /* Prepare space for the return value. On some platforms, such as
903 `armv5tel-*-linux-gnueabi', the return value has to be at least
904 word-aligned, even if its type doesn't have any alignment requirement as is
905 the case with `char'. */
906 rvalue = (void *) ROUND_UP ((scm_t_uintptr) data + off,
907 max (sizeof (void *), cif->rtype->alignment));
4d9130a5
AW
908
909 /* off we go! */
910 ffi_call (cif, func, rvalue, args);
911
912 return pack (cif->rtype, rvalue);
913}
914
d8b04f04
AW
915\f
916
ab4779ff 917static void
e2c2a699
AW
918scm_init_foreign (void)
919{
920#ifndef SCM_MAGIC_SNARFER
921#include "libguile/foreign.x"
922#endif
ab4779ff
AW
923 scm_define (sym_void, scm_from_uint8 (SCM_FOREIGN_TYPE_VOID));
924 scm_define (sym_float, scm_from_uint8 (SCM_FOREIGN_TYPE_FLOAT));
925 scm_define (sym_double, scm_from_uint8 (SCM_FOREIGN_TYPE_DOUBLE));
926 scm_define (sym_uint8, scm_from_uint8 (SCM_FOREIGN_TYPE_UINT8));
927 scm_define (sym_int8, scm_from_uint8 (SCM_FOREIGN_TYPE_INT8));
928 scm_define (sym_uint16, scm_from_uint8 (SCM_FOREIGN_TYPE_UINT16));
929 scm_define (sym_int16, scm_from_uint8 (SCM_FOREIGN_TYPE_INT16));
930 scm_define (sym_uint32, scm_from_uint8 (SCM_FOREIGN_TYPE_UINT32));
931 scm_define (sym_int32, scm_from_uint8 (SCM_FOREIGN_TYPE_INT32));
932 scm_define (sym_uint64, scm_from_uint8 (SCM_FOREIGN_TYPE_UINT64));
933 scm_define (sym_int64, scm_from_uint8 (SCM_FOREIGN_TYPE_INT64));
dd1464bf
LC
934
935 scm_define (sym_int,
936#if SIZEOF_INT == 8
937 scm_from_uint8 (SCM_FOREIGN_TYPE_INT64)
938#elif SIZEOF_INT == 4
939 scm_from_uint8 (SCM_FOREIGN_TYPE_INT32)
940#else
941# error unsupported sizeof (int)
942#endif
943 );
944
945 scm_define (sym_unsigned_int,
946#if SIZEOF_UNSIGNED_INT == 8
947 scm_from_uint8 (SCM_FOREIGN_TYPE_UINT64)
948#elif SIZEOF_UNSIGNED_INT == 4
949 scm_from_uint8 (SCM_FOREIGN_TYPE_UINT32)
950#else
951# error unsupported sizeof (unsigned int)
952#endif
953 );
954
955 scm_define (sym_long,
956#if SIZEOF_LONG == 8
957 scm_from_uint8 (SCM_FOREIGN_TYPE_INT64)
958#elif SIZEOF_LONG == 4
959 scm_from_uint8 (SCM_FOREIGN_TYPE_INT32)
960#else
961# error unsupported sizeof (long)
962#endif
963 );
964
965 scm_define (sym_unsigned_long,
966#if SIZEOF_UNSIGNED_LONG == 8
967 scm_from_uint8 (SCM_FOREIGN_TYPE_UINT64)
968#elif SIZEOF_UNSIGNED_LONG == 4
969 scm_from_uint8 (SCM_FOREIGN_TYPE_UINT32)
970#else
971# error unsupported sizeof (unsigned long)
972#endif
973 );
974
975 scm_define (sym_size_t,
976#if SIZEOF_SIZE_T == 8
977 scm_from_uint8 (SCM_FOREIGN_TYPE_UINT64)
978#elif SIZEOF_SIZE_T == 4
979 scm_from_uint8 (SCM_FOREIGN_TYPE_UINT32)
980#else
981# error unsupported sizeof (size_t)
982#endif
983 );
54eb59cf 984
d4149a51 985 null_pointer = scm_cell (scm_tc7_foreign, 0);
3e5ea35c 986 scm_define (sym_null, null_pointer);
ab4779ff
AW
987}
988
989void
990scm_register_foreign (void)
991{
44602b08
AW
992 scm_c_register_extension ("libguile-" SCM_EFFECTIVE_VERSION,
993 "scm_init_foreign",
ab4779ff
AW
994 (scm_t_extension_init_func)scm_init_foreign,
995 NULL);
20aafae2 996 foreign_weak_refs = scm_make_weak_key_hash_table (SCM_UNDEFINED);
e2c2a699
AW
997}
998
999/*
1000 Local Variables:
1001 c-file-style: "gnu"
1002 End:
1003*/