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