1 /* Copyright (C) 2010, 2011, 2012 Free Software Foundation, Inc.
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.
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.
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
30 #include "libguile/_scm.h"
31 #include "libguile/bytevectors.h"
32 #include "libguile/instructions.h"
33 #include "libguile/threads.h"
34 #include "libguile/foreign.h"
38 SCM_SYMBOL (sym_void
, "void");
39 SCM_SYMBOL (sym_float
, "float");
40 SCM_SYMBOL (sym_double
, "double");
41 SCM_SYMBOL (sym_uint8
, "uint8");
42 SCM_SYMBOL (sym_int8
, "int8");
43 SCM_SYMBOL (sym_uint16
, "uint16");
44 SCM_SYMBOL (sym_int16
, "int16");
45 SCM_SYMBOL (sym_uint32
, "uint32");
46 SCM_SYMBOL (sym_int32
, "int32");
47 SCM_SYMBOL (sym_uint64
, "uint64");
48 SCM_SYMBOL (sym_int64
, "int64");
49 SCM_SYMBOL (sym_short
, "short");
50 SCM_SYMBOL (sym_int
, "int");
51 SCM_SYMBOL (sym_long
, "long");
52 SCM_SYMBOL (sym_unsigned_short
, "unsigned-short");
53 SCM_SYMBOL (sym_unsigned_int
, "unsigned-int");
54 SCM_SYMBOL (sym_unsigned_long
, "unsigned-long");
55 SCM_SYMBOL (sym_size_t
, "size_t");
57 /* that's for pointers, you know. */
58 SCM_SYMBOL (sym_asterisk
, "*");
60 SCM_SYMBOL (sym_null
, "%null-pointer");
61 SCM_SYMBOL (sym_null_pointer_error
, "null-pointer-error");
63 /* The cell representing the null pointer. */
64 static SCM null_pointer
;
66 #if SIZEOF_VOID_P == 4
67 # define scm_to_uintptr scm_to_uint32
68 # define scm_from_uintptr scm_from_uint32
69 #elif SIZEOF_VOID_P == 8
70 # define scm_to_uintptr scm_to_uint64
71 # define scm_from_uintptr scm_from_uint64
73 # error unsupported pointer size
77 /* Raise a null pointer dereference error. */
79 null_pointer_error (const char *func_name
)
81 scm_error (sym_null_pointer_error
, func_name
,
82 "null pointer dereference", SCM_EOL
, SCM_EOL
);
86 static SCM
cif_to_procedure (SCM cif
, SCM func_ptr
);
89 static SCM pointer_weak_refs
= SCM_BOOL_F
;
93 register_weak_reference (SCM from
, SCM to
)
95 scm_weak_table_putq_x (pointer_weak_refs
, from
, to
);
99 pointer_finalizer_trampoline (GC_PTR ptr
, GC_PTR data
)
101 scm_t_pointer_finalizer finalizer
= data
;
102 finalizer (SCM_POINTER_VALUE (SCM_PACK_POINTER (ptr
)));
105 SCM_DEFINE (scm_pointer_p
, "pointer?", 1, 0, 0,
107 "Return @code{#t} if @var{obj} is a pointer object, "
108 "@code{#f} otherwise.\n")
109 #define FUNC_NAME s_scm_pointer_p
111 return scm_from_bool (SCM_POINTER_P (obj
));
115 SCM_DEFINE (scm_make_pointer
, "make-pointer", 1, 1, 0,
116 (SCM address
, SCM finalizer
),
117 "Return a foreign pointer object pointing to @var{address}. "
118 "If @var{finalizer} is passed, it should be a pointer to a "
119 "one-argument C function that will be called when the pointer "
120 "object becomes unreachable.")
121 #define FUNC_NAME s_scm_make_pointer
124 scm_t_uintptr c_address
;
126 c_address
= scm_to_uintptr (address
);
127 if (SCM_UNBNDP (finalizer
))
131 SCM_VALIDATE_POINTER (2, finalizer
);
132 c_finalizer
= SCM_POINTER_VALUE (finalizer
);
135 return scm_from_pointer ((void *) c_address
, c_finalizer
);
140 scm_to_pointer (SCM pointer
)
141 #define FUNC_NAME "scm_to_pointer"
143 SCM_VALIDATE_POINTER (1, pointer
);
144 return SCM_POINTER_VALUE (pointer
);
149 scm_from_pointer (void *ptr
, scm_t_pointer_finalizer finalizer
)
153 if (ptr
== NULL
&& finalizer
== NULL
)
157 ret
= scm_cell (scm_tc7_pointer
, (scm_t_bits
) ptr
);
160 scm_i_set_finalizer (SCM2PTR (ret
), pointer_finalizer_trampoline
,
167 SCM_DEFINE (scm_pointer_address
, "pointer-address", 1, 0, 0,
169 "Return the numerical value of @var{pointer}.")
170 #define FUNC_NAME s_scm_pointer_address
172 SCM_VALIDATE_POINTER (1, pointer
);
174 return scm_from_uintptr ((scm_t_uintptr
) SCM_POINTER_VALUE (pointer
));
178 SCM_DEFINE (scm_pointer_to_scm
, "pointer->scm", 1, 0, 0,
180 "Unsafely cast @var{pointer} to a Scheme object.\n"
181 "Cross your fingers!")
182 #define FUNC_NAME s_scm_pointer_to_scm
184 SCM_VALIDATE_POINTER (1, pointer
);
186 return SCM_PACK ((scm_t_bits
) SCM_POINTER_VALUE (pointer
));
190 SCM_DEFINE (scm_scm_to_pointer
, "scm->pointer", 1, 0, 0,
192 "Return a foreign pointer object with the @code{object-address}\n"
194 #define FUNC_NAME s_scm_scm_to_pointer
198 ret
= scm_from_pointer ((void*) SCM_UNPACK (scm
), NULL
);
199 if (SCM_HEAP_OBJECT_P (ret
))
200 register_weak_reference (ret
, scm
);
206 SCM_DEFINE (scm_pointer_to_bytevector
, "pointer->bytevector", 2, 2, 0,
207 (SCM pointer
, SCM len
, SCM offset
, SCM uvec_type
),
208 "Return a bytevector aliasing the @var{len} bytes pointed\n"
209 "to by @var{pointer}.\n\n"
210 "The user may specify an alternate default interpretation for\n"
211 "the memory by passing the @var{uvec_type} argument, to indicate\n"
212 "that the memory is an array of elements of that type.\n"
213 "@var{uvec_type} should be something that\n"
214 "@code{uniform-vector-element-type} would return, like @code{f32}\n"
216 "When @var{offset} is passed, it specifies the offset in bytes\n"
217 "relative to @var{pointer} of the memory region aliased by the\n"
218 "returned bytevector.")
219 #define FUNC_NAME s_scm_pointer_to_bytevector
223 size_t boffset
, blen
;
224 scm_t_array_element_type btype
;
226 SCM_VALIDATE_POINTER (1, pointer
);
227 ptr
= SCM_POINTER_VALUE (pointer
);
229 if (SCM_UNLIKELY (ptr
== NULL
))
230 null_pointer_error (FUNC_NAME
);
232 if (SCM_UNBNDP (uvec_type
))
233 btype
= SCM_ARRAY_ELEMENT_TYPE_VU8
;
237 for (i
= 0; i
<= SCM_ARRAY_ELEMENT_TYPE_LAST
; i
++)
238 if (scm_is_eq (uvec_type
, scm_i_array_element_types
[i
]))
242 case SCM_ARRAY_ELEMENT_TYPE_VU8
:
243 case SCM_ARRAY_ELEMENT_TYPE_U8
:
244 case SCM_ARRAY_ELEMENT_TYPE_S8
:
245 case SCM_ARRAY_ELEMENT_TYPE_U16
:
246 case SCM_ARRAY_ELEMENT_TYPE_S16
:
247 case SCM_ARRAY_ELEMENT_TYPE_U32
:
248 case SCM_ARRAY_ELEMENT_TYPE_S32
:
249 case SCM_ARRAY_ELEMENT_TYPE_U64
:
250 case SCM_ARRAY_ELEMENT_TYPE_S64
:
251 case SCM_ARRAY_ELEMENT_TYPE_F32
:
252 case SCM_ARRAY_ELEMENT_TYPE_F64
:
253 case SCM_ARRAY_ELEMENT_TYPE_C32
:
254 case SCM_ARRAY_ELEMENT_TYPE_C64
:
258 scm_wrong_type_arg_msg (FUNC_NAME
, SCM_ARG1
, uvec_type
,
259 "uniform vector type");
263 if (SCM_UNBNDP (offset
))
266 boffset
= scm_to_size_t (offset
);
268 blen
= scm_to_size_t (len
);
270 ret
= scm_c_take_typed_bytevector ((signed char *) ptr
+ boffset
,
271 blen
, btype
, pointer
);
277 SCM_DEFINE (scm_bytevector_to_pointer
, "bytevector->pointer", 1, 1, 0,
278 (SCM bv
, SCM offset
),
279 "Return a pointer pointer aliasing the memory pointed to by\n"
280 "@var{bv} or @var{offset} bytes after @var{bv} when @var{offset}\n"
282 #define FUNC_NAME s_scm_bytevector_to_pointer
288 SCM_VALIDATE_BYTEVECTOR (1, bv
);
289 ptr
= SCM_BYTEVECTOR_CONTENTS (bv
);
291 if (SCM_UNBNDP (offset
))
294 boffset
= scm_to_unsigned_integer (offset
, 0,
295 SCM_BYTEVECTOR_LENGTH (bv
) - 1);
297 ret
= scm_from_pointer (ptr
+ boffset
, NULL
);
298 register_weak_reference (ret
, bv
);
303 SCM_DEFINE (scm_set_pointer_finalizer_x
, "set-pointer-finalizer!", 2, 0, 0,
304 (SCM pointer
, SCM finalizer
),
305 "Arrange for the C procedure wrapped by @var{finalizer} to be\n"
306 "called on the pointer wrapped by @var{pointer} when @var{pointer}\n"
307 "becomes unreachable. Note: the C procedure should not call into\n"
308 "Scheme. If you need a Scheme finalizer, use guardians.")
309 #define FUNC_NAME s_scm_set_pointer_finalizer_x
311 SCM_VALIDATE_POINTER (1, pointer
);
312 SCM_VALIDATE_POINTER (2, finalizer
);
314 scm_i_add_finalizer (SCM2PTR (pointer
), pointer_finalizer_trampoline
,
315 SCM_POINTER_VALUE (finalizer
));
317 return SCM_UNSPECIFIED
;
322 scm_i_pointer_print (SCM pointer
, SCM port
, scm_print_state
*pstate
)
324 scm_puts_unlocked ("#<pointer 0x", port
);
325 scm_uintprint (scm_to_uintptr (scm_pointer_address (pointer
)), 16, port
);
326 scm_putc_unlocked ('>', port
);
330 /* Non-primitive helpers functions. These procedures could be
331 implemented in terms of the primitives above but would be inefficient
332 (heap allocation overhead, Scheme/C round trips, etc.) */
334 SCM_DEFINE (scm_dereference_pointer
, "dereference-pointer", 1, 0, 0,
336 "Assuming @var{pointer} points to a memory region that\n"
337 "holds a pointer, return this pointer.")
338 #define FUNC_NAME s_scm_dereference_pointer
340 SCM_VALIDATE_POINTER (1, pointer
);
342 return scm_from_pointer (* (void **) SCM_POINTER_VALUE (pointer
), NULL
);
346 SCM_DEFINE (scm_string_to_pointer
, "string->pointer", 1, 1, 0,
347 (SCM string
, SCM encoding
),
348 "Return a foreign pointer to a nul-terminated copy of\n"
349 "@var{string} in the given @var{encoding}, defaulting to\n"
350 "the current locale encoding. The C string is freed when\n"
351 "the returned foreign pointer becomes unreachable.\n\n"
352 "This is the Scheme equivalent of @code{scm_to_stringn}.")
353 #define FUNC_NAME s_scm_string_to_pointer
355 SCM_VALIDATE_STRING (1, string
);
357 /* XXX: Finalizers slow down libgc; they could be avoided if
358 `scm_to_string' & co. were able to use libgc-allocated memory. */
360 if (SCM_UNBNDP (encoding
))
361 return scm_from_pointer (scm_to_locale_string (string
), free
);
367 SCM_VALIDATE_STRING (2, encoding
);
369 enc
= scm_to_locale_string (encoding
);
370 scm_dynwind_begin (0);
371 scm_dynwind_free (enc
);
373 ret
= scm_from_pointer
374 (scm_to_stringn (string
, NULL
, enc
,
375 scm_i_get_conversion_strategy (SCM_BOOL_F
)),
385 SCM_DEFINE (scm_pointer_to_string
, "pointer->string", 1, 2, 0,
386 (SCM pointer
, SCM length
, SCM encoding
),
387 "Return the string representing the C string pointed to by\n"
388 "@var{pointer}. If @var{length} is omitted or @code{-1}, the\n"
389 "string is assumed to be nul-terminated. Otherwise\n"
390 "@var{length} is the number of bytes in memory pointed to by\n"
391 "@var{pointer}. The C string is assumed to be in the given\n"
392 "@var{encoding}, defaulting to the current locale encoding.\n\n"
393 "This is the Scheme equivalent of @code{scm_from_stringn}.")
394 #define FUNC_NAME s_scm_pointer_to_string
398 SCM_VALIDATE_POINTER (1, pointer
);
400 if (SCM_UNBNDP (length
)
401 || scm_is_true (scm_eqv_p (length
, scm_from_int (-1))))
404 len
= scm_to_size_t (length
);
406 if (SCM_UNBNDP (encoding
))
407 return scm_from_locale_stringn (SCM_POINTER_VALUE (pointer
), len
);
413 SCM_VALIDATE_STRING (3, encoding
);
415 enc
= scm_to_locale_string (encoding
);
416 scm_dynwind_begin (0);
417 scm_dynwind_free (enc
);
419 ret
= scm_from_stringn (SCM_POINTER_VALUE (pointer
), len
, enc
,
420 scm_i_get_conversion_strategy (SCM_BOOL_F
));
431 SCM_DEFINE (scm_alignof
, "alignof", 1, 0, 0, (SCM type
),
432 "Return the alignment of @var{type}, in bytes.\n\n"
433 "@var{type} should be a valid C type, like @code{int}.\n"
434 "Alternately @var{type} may be the symbol @code{*}, in which\n"
435 "case the alignment of a pointer is returned. @var{type} may\n"
436 "also be a list of types, in which case the alignment of a\n"
437 "@code{struct} with ABI-conventional packing is returned.")
438 #define FUNC_NAME s_scm_alignof
440 if (SCM_I_INUMP (type
))
442 switch (SCM_I_INUM (type
))
444 case SCM_FOREIGN_TYPE_FLOAT
:
445 return scm_from_size_t (alignof_type (float));
446 case SCM_FOREIGN_TYPE_DOUBLE
:
447 return scm_from_size_t (alignof_type (double));
448 case SCM_FOREIGN_TYPE_UINT8
:
449 return scm_from_size_t (alignof_type (scm_t_uint8
));
450 case SCM_FOREIGN_TYPE_INT8
:
451 return scm_from_size_t (alignof_type (scm_t_int8
));
452 case SCM_FOREIGN_TYPE_UINT16
:
453 return scm_from_size_t (alignof_type (scm_t_uint16
));
454 case SCM_FOREIGN_TYPE_INT16
:
455 return scm_from_size_t (alignof_type (scm_t_int16
));
456 case SCM_FOREIGN_TYPE_UINT32
:
457 return scm_from_size_t (alignof_type (scm_t_uint32
));
458 case SCM_FOREIGN_TYPE_INT32
:
459 return scm_from_size_t (alignof_type (scm_t_int32
));
460 case SCM_FOREIGN_TYPE_UINT64
:
461 return scm_from_size_t (alignof_type (scm_t_uint64
));
462 case SCM_FOREIGN_TYPE_INT64
:
463 return scm_from_size_t (alignof_type (scm_t_int64
));
465 scm_wrong_type_arg (FUNC_NAME
, 1, type
);
468 else if (scm_is_eq (type
, sym_asterisk
))
470 return scm_from_size_t (alignof_type (void*));
471 else if (scm_is_pair (type
))
473 /* TYPE is a structure. Section 3-3 of the i386, x86_64, PowerPC,
474 and SPARC P.S. of the System V ABI all say: "Aggregates
475 (structures and arrays) and unions assume the alignment of
476 their most strictly aligned component." */
479 for (max
= 0; scm_is_pair (type
); type
= SCM_CDR (type
))
483 align
= scm_to_size_t (scm_alignof (SCM_CAR (type
)));
488 return scm_from_size_t (max
);
491 scm_wrong_type_arg (FUNC_NAME
, 1, type
);
495 SCM_DEFINE (scm_sizeof
, "sizeof", 1, 0, 0, (SCM type
),
496 "Return the size of @var{type}, in bytes.\n\n"
497 "@var{type} should be a valid C type, like @code{int}.\n"
498 "Alternately @var{type} may be the symbol @code{*}, in which\n"
499 "case the size of a pointer is returned. @var{type} may also\n"
500 "be a list of types, in which case the size of a @code{struct}\n"
501 "with ABI-conventional packing is returned.")
502 #define FUNC_NAME s_scm_sizeof
504 if (SCM_I_INUMP (type
))
506 switch (SCM_I_INUM (type
))
508 case SCM_FOREIGN_TYPE_FLOAT
:
509 return scm_from_size_t (sizeof (float));
510 case SCM_FOREIGN_TYPE_DOUBLE
:
511 return scm_from_size_t (sizeof (double));
512 case SCM_FOREIGN_TYPE_UINT8
:
513 return scm_from_size_t (sizeof (scm_t_uint8
));
514 case SCM_FOREIGN_TYPE_INT8
:
515 return scm_from_size_t (sizeof (scm_t_int8
));
516 case SCM_FOREIGN_TYPE_UINT16
:
517 return scm_from_size_t (sizeof (scm_t_uint16
));
518 case SCM_FOREIGN_TYPE_INT16
:
519 return scm_from_size_t (sizeof (scm_t_int16
));
520 case SCM_FOREIGN_TYPE_UINT32
:
521 return scm_from_size_t (sizeof (scm_t_uint32
));
522 case SCM_FOREIGN_TYPE_INT32
:
523 return scm_from_size_t (sizeof (scm_t_int32
));
524 case SCM_FOREIGN_TYPE_UINT64
:
525 return scm_from_size_t (sizeof (scm_t_uint64
));
526 case SCM_FOREIGN_TYPE_INT64
:
527 return scm_from_size_t (sizeof (scm_t_int64
));
529 scm_wrong_type_arg (FUNC_NAME
, 1, type
);
532 else if (scm_is_eq (type
, sym_asterisk
))
534 return scm_from_size_t (sizeof (void*));
535 else if (scm_is_pair (type
))
539 size_t align
= scm_to_size_t (scm_alignof(type
));
540 while (scm_is_pair (type
))
542 off
= ROUND_UP (off
, scm_to_size_t (scm_alignof (scm_car (type
))));
543 off
+= scm_to_size_t (scm_sizeof (scm_car (type
)));
544 type
= scm_cdr (type
);
546 return scm_from_size_t (ROUND_UP(off
, align
));
549 scm_wrong_type_arg (FUNC_NAME
, 1, type
);
554 /* return 1 on success, 0 on failure */
556 parse_ffi_type (SCM type
, int return_p
, long *n_structs
, long *n_struct_elts
)
558 if (SCM_I_INUMP (type
))
560 if ((SCM_I_INUM (type
) < 0 )
561 || (SCM_I_INUM (type
) > SCM_FOREIGN_TYPE_LAST
))
563 else if (SCM_I_INUM (type
) == SCM_FOREIGN_TYPE_VOID
&& !return_p
)
568 else if (scm_is_eq (type
, sym_asterisk
))
575 len
= scm_ilength (type
);
580 if (!parse_ffi_type (scm_car (type
), 0, n_structs
, n_struct_elts
))
583 type
= scm_cdr (type
);
591 fill_ffi_type (SCM type
, ffi_type
*ftype
, ffi_type
***type_ptrs
,
594 if (SCM_I_INUMP (type
))
596 switch (SCM_I_INUM (type
))
598 case SCM_FOREIGN_TYPE_FLOAT
:
599 *ftype
= ffi_type_float
;
601 case SCM_FOREIGN_TYPE_DOUBLE
:
602 *ftype
= ffi_type_double
;
604 case SCM_FOREIGN_TYPE_UINT8
:
605 *ftype
= ffi_type_uint8
;
607 case SCM_FOREIGN_TYPE_INT8
:
608 *ftype
= ffi_type_sint8
;
610 case SCM_FOREIGN_TYPE_UINT16
:
611 *ftype
= ffi_type_uint16
;
613 case SCM_FOREIGN_TYPE_INT16
:
614 *ftype
= ffi_type_sint16
;
616 case SCM_FOREIGN_TYPE_UINT32
:
617 *ftype
= ffi_type_uint32
;
619 case SCM_FOREIGN_TYPE_INT32
:
620 *ftype
= ffi_type_sint32
;
622 case SCM_FOREIGN_TYPE_UINT64
:
623 *ftype
= ffi_type_uint64
;
625 case SCM_FOREIGN_TYPE_INT64
:
626 *ftype
= ffi_type_sint64
;
628 case SCM_FOREIGN_TYPE_VOID
:
629 *ftype
= ffi_type_void
;
632 scm_wrong_type_arg_msg ("pointer->procedure", 0, type
,
636 else if (scm_is_eq (type
, sym_asterisk
))
639 *ftype
= ffi_type_pointer
;
646 len
= scm_ilength (type
);
649 ftype
->alignment
= 0;
650 ftype
->type
= FFI_TYPE_STRUCT
;
651 ftype
->elements
= *type_ptrs
;
652 *type_ptrs
+= len
+ 1;
654 for (i
= 0; i
< len
; i
++)
656 ftype
->elements
[i
] = *types
;
658 fill_ffi_type (scm_car (type
), ftype
->elements
[i
],
660 type
= scm_cdr (type
);
662 ftype
->elements
[i
] = NULL
;
666 /* Return a "cif" (call interface) for the given RETURN_TYPE and
669 make_cif (SCM return_type
, SCM arg_types
, const char *caller
)
670 #define FUNC_NAME caller
673 long i
, nargs
, n_structs
, n_struct_elts
;
677 ffi_type
**type_ptrs
;
680 nargs
= scm_ilength (arg_types
);
681 SCM_ASSERT (nargs
>= 0, arg_types
, 3, FUNC_NAME
);
682 /* fixme: assert nargs < 1<<32 */
683 n_structs
= n_struct_elts
= 0;
685 /* For want of talloc, we're going to have to do this in two passes: first we
686 figure out how much memory is needed for all types, then we allocate the
687 cif and the types all in one block. */
688 if (!parse_ffi_type (return_type
, 1, &n_structs
, &n_struct_elts
))
689 scm_wrong_type_arg (FUNC_NAME
, 1, return_type
);
690 for (walk
= arg_types
; scm_is_pair (walk
); walk
= scm_cdr (walk
))
691 if (!parse_ffi_type (scm_car (walk
), 0, &n_structs
, &n_struct_elts
))
692 scm_wrong_type_arg (FUNC_NAME
, 3, scm_car (walk
));
694 /* the memory: with space for the cif itself */
695 cif_len
= sizeof (ffi_cif
);
697 /* then ffi_type pointers: one for each arg, one for each struct
698 element, and one for each struct (for null-termination) */
699 cif_len
= (ROUND_UP (cif_len
, alignof_type (void *))
700 + (nargs
+ n_structs
+ n_struct_elts
)*sizeof(void*));
702 /* then the ffi_type structs themselves, one per arg and struct element, and
703 one for the return val */
704 cif_len
= (ROUND_UP (cif_len
, alignof_type (ffi_type
))
705 + (nargs
+ n_struct_elts
+ 1)*sizeof(ffi_type
));
707 mem
= scm_gc_malloc_pointerless (cif_len
, "foreign");
708 /* ensure all the memory is initialized, even the holes */
709 memset (mem
, 0, cif_len
);
710 cif
= (ffi_cif
*) mem
;
712 /* reuse cif_len to walk through the mem */
713 cif_len
= ROUND_UP (sizeof (ffi_cif
), alignof_type (void *));
714 type_ptrs
= (ffi_type
**)(mem
+ cif_len
);
715 cif_len
= ROUND_UP (cif_len
716 + (nargs
+ n_structs
+ n_struct_elts
)*sizeof(void*),
717 alignof_type (ffi_type
));
718 types
= (ffi_type
*)(mem
+ cif_len
);
720 /* whew. now knit the pointers together. */
721 cif
->rtype
= types
++;
722 fill_ffi_type (return_type
, cif
->rtype
, &type_ptrs
, &types
);
723 cif
->arg_types
= type_ptrs
;
725 for (walk
= arg_types
, i
= 0; scm_is_pair (walk
); walk
= scm_cdr (walk
), i
++)
727 cif
->arg_types
[i
] = types
++;
728 fill_ffi_type (scm_car (walk
), cif
->arg_types
[i
], &type_ptrs
, &types
);
731 /* round out the cif, and we're done. */
732 cif
->abi
= FFI_DEFAULT_ABI
;
737 if (FFI_OK
!= ffi_prep_cif (cif
, FFI_DEFAULT_ABI
, cif
->nargs
, cif
->rtype
,
739 SCM_MISC_ERROR ("ffi_prep_cif failed", SCM_EOL
);
745 SCM_DEFINE (scm_pointer_to_procedure
, "pointer->procedure", 3, 0, 0,
746 (SCM return_type
, SCM func_ptr
, SCM arg_types
),
747 "Make a foreign function.\n\n"
748 "Given the foreign void pointer @var{func_ptr}, its argument and\n"
749 "return types @var{arg_types} and @var{return_type}, return a\n"
750 "procedure that will pass arguments to the foreign function\n"
751 "and return appropriate values.\n\n"
752 "@var{arg_types} should be a list of foreign types.\n"
753 "@code{return_type} should be a foreign type.")
754 #define FUNC_NAME s_scm_pointer_to_procedure
758 SCM_VALIDATE_POINTER (2, func_ptr
);
760 cif
= make_cif (return_type
, arg_types
, FUNC_NAME
);
762 return cif_to_procedure (scm_from_pointer (cif
, NULL
), func_ptr
);
768 /* Pre-generate trampolines for less than 10 arguments. */
770 #ifdef WORDS_BIGENDIAN
771 #define OBJCODE_HEADER 0, 0, 0, 8, 0, 0, 0, 40
772 #define META_HEADER 0, 0, 0, 32, 0, 0, 0, 0
774 #define OBJCODE_HEADER 8, 0, 0, 0, 40, 0, 0, 0
775 #define META_HEADER 32, 0, 0, 0, 0, 0, 0, 0
780 /* 0 */ scm_op_assert_nargs_ee, 0, nreq, /* assert number of args */ \
781 /* 3 */ scm_op_object_ref, 0, /* push the pair with the cif and the function pointer */ \
782 /* 5 */ scm_op_foreign_call, nreq, /* and call (will return value as well) */ \
783 /* 7 */ scm_op_nop, \
784 /* 8 */ META (3, 7, nreq)
786 #define META(start, end, nreq) \
788 /* 0 */ scm_op_make_eol, /* bindings */ \
789 /* 1 */ scm_op_make_eol, /* sources */ \
790 /* 2 */ scm_op_make_int8, start, scm_op_make_int8, end, /* arity: from ip N to ip N */ \
791 /* 6 */ scm_op_make_int8, nreq, /* the arity is N required args */ \
792 /* 8 */ scm_op_list, 0, 3, /* make a list of those 3 vals */ \
793 /* 11 */ scm_op_list, 0, 1, /* and the arities will be a list of that one list */ \
794 /* 14 */ scm_op_load_symbol, 0, 0, 4, 'n', 'a', 'm', 'e', /* `name' */ \
795 /* 22 */ scm_op_object_ref, 1, /* the name from the object table */ \
796 /* 24 */ scm_op_cons, /* make a pair for the properties */ \
797 /* 25 */ scm_op_list, 0, 4, /* pack bindings, sources, and arities into list */ \
798 /* 28 */ scm_op_return, /* and return */ \
799 /* 29 */ scm_op_nop, scm_op_nop, scm_op_nop \
804 scm_t_uint64 dummy
; /* ensure 8-byte alignment; perhaps there's a better way */
805 const scm_t_uint8 bytes
[10 * (sizeof (struct scm_objcode
) + 8
806 + sizeof (struct scm_objcode
) + 32)];
810 CODE (0), CODE (1), CODE (2), CODE (3), CODE (4),
811 CODE (5), CODE (6), CODE (7), CODE (8), CODE (9)
817 #undef OBJCODE_HEADER
821 (defun generate-objcode-cells (n)
822 "Generate objcode cells for up to N arguments"
827 (format " { STATIC_OBJCODE_TAG, SCM_PACK (raw_bytecode.bytes + %d) },\n"
828 (* (+ 4 4 8 4 4 32) i)))
829 (insert " { SCM_BOOL_F, SCM_PACK (0) },\n")
832 #define STATIC_OBJCODE_TAG \
833 SCM_PACK (SCM_MAKE_OBJCODE_TAG (SCM_OBJCODE_TYPE_STATIC, 0))
837 scm_t_uint64 dummy
; /* alignment */
838 scm_t_cell cells
[10 * 2]; /* 10 double cells */
841 /* C-u 1 0 M-x generate-objcode-cells RET */
843 { STATIC_OBJCODE_TAG
, SCM_PACK (raw_bytecode
.bytes
+ 0) },
844 { SCM_BOOL_F
, SCM_PACK (0) },
845 { STATIC_OBJCODE_TAG
, SCM_PACK (raw_bytecode
.bytes
+ 56) },
846 { SCM_BOOL_F
, SCM_PACK (0) },
847 { STATIC_OBJCODE_TAG
, SCM_PACK (raw_bytecode
.bytes
+ 112) },
848 { SCM_BOOL_F
, SCM_PACK (0) },
849 { STATIC_OBJCODE_TAG
, SCM_PACK (raw_bytecode
.bytes
+ 168) },
850 { SCM_BOOL_F
, SCM_PACK (0) },
851 { STATIC_OBJCODE_TAG
, SCM_PACK (raw_bytecode
.bytes
+ 224) },
852 { SCM_BOOL_F
, SCM_PACK (0) },
853 { STATIC_OBJCODE_TAG
, SCM_PACK (raw_bytecode
.bytes
+ 280) },
854 { SCM_BOOL_F
, SCM_PACK (0) },
855 { STATIC_OBJCODE_TAG
, SCM_PACK (raw_bytecode
.bytes
+ 336) },
856 { SCM_BOOL_F
, SCM_PACK (0) },
857 { STATIC_OBJCODE_TAG
, SCM_PACK (raw_bytecode
.bytes
+ 392) },
858 { SCM_BOOL_F
, SCM_PACK (0) },
859 { STATIC_OBJCODE_TAG
, SCM_PACK (raw_bytecode
.bytes
+ 448) },
860 { SCM_BOOL_F
, SCM_PACK (0) },
861 { STATIC_OBJCODE_TAG
, SCM_PACK (raw_bytecode
.bytes
+ 504) },
862 { SCM_BOOL_F
, SCM_PACK (0) }
866 static const SCM objcode_trampolines
[10] = {
867 SCM_PACK (objcode_cells
.cells
+0),
868 SCM_PACK (objcode_cells
.cells
+2),
869 SCM_PACK (objcode_cells
.cells
+4),
870 SCM_PACK (objcode_cells
.cells
+6),
871 SCM_PACK (objcode_cells
.cells
+8),
872 SCM_PACK (objcode_cells
.cells
+10),
873 SCM_PACK (objcode_cells
.cells
+12),
874 SCM_PACK (objcode_cells
.cells
+14),
875 SCM_PACK (objcode_cells
.cells
+16),
876 SCM_PACK (objcode_cells
.cells
+18),
880 cif_to_procedure (SCM cif
, SCM func_ptr
)
884 SCM objcode
, table
, ret
;
886 c_cif
= (ffi_cif
*) SCM_POINTER_VALUE (cif
);
887 nargs
= c_cif
->nargs
;
890 objcode
= objcode_trampolines
[nargs
];
892 scm_misc_error ("make-foreign-function", "args >= 10 currently unimplemented",
895 table
= scm_c_make_vector (2, SCM_UNDEFINED
);
896 SCM_SIMPLE_VECTOR_SET (table
, 0, scm_cons (cif
, func_ptr
));
897 SCM_SIMPLE_VECTOR_SET (table
, 1, SCM_BOOL_F
); /* name */
898 ret
= scm_make_program (objcode
, table
, SCM_BOOL_F
);
903 /* Set *LOC to the foreign representation of X with TYPE. */
905 unpack (const ffi_type
*type
, void *loc
, SCM x
, int return_value_p
)
906 #define FUNC_NAME "scm_i_foreign_call"
911 *(float *) loc
= scm_to_double (x
);
913 case FFI_TYPE_DOUBLE
:
914 *(double *) loc
= scm_to_double (x
);
917 /* For integer return values smaller than `int', libffi expects the
918 result in an `ffi_arg'-long buffer. */
922 *(ffi_arg
*) loc
= scm_to_uint8 (x
);
924 *(scm_t_uint8
*) loc
= scm_to_uint8 (x
);
928 *(ffi_arg
*) loc
= scm_to_int8 (x
);
930 *(scm_t_int8
*) loc
= scm_to_int8 (x
);
932 case FFI_TYPE_UINT16
:
934 *(ffi_arg
*) loc
= scm_to_uint16 (x
);
936 *(scm_t_uint16
*) loc
= scm_to_uint16 (x
);
938 case FFI_TYPE_SINT16
:
940 *(ffi_arg
*) loc
= scm_to_int16 (x
);
942 *(scm_t_int16
*) loc
= scm_to_int16 (x
);
944 case FFI_TYPE_UINT32
:
946 *(ffi_arg
*) loc
= scm_to_uint32 (x
);
948 *(scm_t_uint32
*) loc
= scm_to_uint32 (x
);
950 case FFI_TYPE_SINT32
:
952 *(ffi_arg
*) loc
= scm_to_int32 (x
);
954 *(scm_t_int32
*) loc
= scm_to_int32 (x
);
956 case FFI_TYPE_UINT64
:
957 *(scm_t_uint64
*) loc
= scm_to_uint64 (x
);
959 case FFI_TYPE_SINT64
:
960 *(scm_t_int64
*) loc
= scm_to_int64 (x
);
962 case FFI_TYPE_STRUCT
:
963 SCM_VALIDATE_POINTER (1, x
);
964 memcpy (loc
, SCM_POINTER_VALUE (x
), type
->size
);
966 case FFI_TYPE_POINTER
:
967 SCM_VALIDATE_POINTER (1, x
);
968 *(void **) loc
= SCM_POINTER_VALUE (x
);
979 /* Return a Scheme representation of the foreign value at LOC of type
980 TYPE. When RETURN_VALUE_P is true, LOC is assumed to point to a
981 return value buffer; otherwise LOC is assumed to point to an
984 pack (const ffi_type
* type
, const void *loc
, int return_value_p
)
989 return SCM_UNSPECIFIED
;
991 return scm_from_double (*(float *) loc
);
992 case FFI_TYPE_DOUBLE
:
993 return scm_from_double (*(double *) loc
);
995 /* For integer return values smaller than `int', libffi stores the
996 result in an `ffi_arg'-long buffer, of which only the
997 significant bits must be kept---hence the pair of casts below.
998 See <http://thread.gmane.org/gmane.comp.lib.ffi.general/406>
1001 case FFI_TYPE_UINT8
:
1003 return scm_from_uint8 ((scm_t_uint8
) *(ffi_arg
*) loc
);
1005 return scm_from_uint8 (* (scm_t_uint8
*) loc
);
1006 case FFI_TYPE_SINT8
:
1008 return scm_from_int8 ((scm_t_int8
) *(ffi_arg
*) loc
);
1010 return scm_from_int8 (* (scm_t_int8
*) loc
);
1011 case FFI_TYPE_UINT16
:
1013 return scm_from_uint16 ((scm_t_uint16
) *(ffi_arg
*) loc
);
1015 return scm_from_uint16 (* (scm_t_uint16
*) loc
);
1016 case FFI_TYPE_SINT16
:
1018 return scm_from_int16 ((scm_t_int16
) *(ffi_arg
*) loc
);
1020 return scm_from_int16 (* (scm_t_int16
*) loc
);
1021 case FFI_TYPE_UINT32
:
1023 return scm_from_uint32 ((scm_t_uint32
) *(ffi_arg
*) loc
);
1025 return scm_from_uint32 (* (scm_t_uint32
*) loc
);
1026 case FFI_TYPE_SINT32
:
1028 return scm_from_int32 ((scm_t_int32
) *(ffi_arg
*) loc
);
1030 return scm_from_int32 (* (scm_t_int32
*) loc
);
1031 case FFI_TYPE_UINT64
:
1032 return scm_from_uint64 (*(scm_t_uint64
*) loc
);
1033 case FFI_TYPE_SINT64
:
1034 return scm_from_int64 (*(scm_t_int64
*) loc
);
1036 case FFI_TYPE_STRUCT
:
1038 void *mem
= scm_gc_malloc_pointerless (type
->size
, "foreign");
1039 memcpy (mem
, loc
, type
->size
);
1040 return scm_from_pointer (mem
, NULL
);
1042 case FFI_TYPE_POINTER
:
1043 return scm_from_pointer (*(void **) loc
, NULL
);
1051 scm_i_foreign_call (SCM foreign
, const SCM
*argv
)
1053 /* FOREIGN is the pair that cif_to_procedure set as the 0th element of the
1056 void (*func
) (void);
1064 cif
= SCM_POINTER_VALUE (SCM_CAR (foreign
));
1065 func
= SCM_POINTER_VALUE (SCM_CDR (foreign
));
1067 /* Argument pointers. */
1068 args
= alloca (sizeof (void *) * cif
->nargs
);
1070 /* Compute the worst-case amount of memory needed to store all the argument
1071 values. Note: as of libffi 3.0.9 `cif->bytes' is undocumented and is zero,
1072 so it can't be used for that purpose. */
1073 for (i
= 0, arg_size
= 0; i
< cif
->nargs
; i
++)
1074 arg_size
+= cif
->arg_types
[i
]->size
+ cif
->arg_types
[i
]->alignment
- 1;
1076 /* Space for argument values, followed by return value. */
1077 data
= alloca (arg_size
+ cif
->rtype
->size
1078 + max (sizeof (void *), cif
->rtype
->alignment
));
1080 /* Unpack ARGV to native values, setting ARGV pointers. */
1081 for (i
= 0, off
= 0;
1083 off
= (scm_t_uint8
*) args
[i
] - data
+ cif
->arg_types
[i
]->size
,
1086 /* Suitably align the storage area for argument I. */
1087 args
[i
] = (void *) ROUND_UP ((scm_t_uintptr
) data
+ off
,
1088 cif
->arg_types
[i
]->alignment
);
1089 assert ((scm_t_uintptr
) args
[i
] % cif
->arg_types
[i
]->alignment
== 0);
1090 unpack (cif
->arg_types
[i
], args
[i
], argv
[i
], 0);
1093 /* Prepare space for the return value. On some platforms, such as
1094 `armv5tel-*-linux-gnueabi', the return value has to be at least
1095 word-aligned, even if its type doesn't have any alignment requirement as is
1096 the case with `char'. */
1097 rvalue
= (void *) ROUND_UP ((scm_t_uintptr
) data
+ off
,
1098 max (sizeof (void *), cif
->rtype
->alignment
));
1101 ffi_call (cif
, func
, rvalue
, args
);
1103 return pack (cif
->rtype
, rvalue
, 1);
1107 /* Function pointers aka. "callbacks" or "closures". */
1111 /* Trampoline to invoke a libffi closure that wraps a Scheme
1114 invoke_closure (ffi_cif
*cif
, void *ret
, void **args
, void *data
)
1117 SCM proc
, *argv
, result
;
1119 proc
= SCM_PACK_POINTER (data
);
1121 argv
= alloca (cif
->nargs
* sizeof (*argv
));
1123 /* Pack ARGS to SCM values, setting ARGV pointers. */
1124 for (i
= 0; i
< cif
->nargs
; i
++)
1125 argv
[i
] = pack (cif
->arg_types
[i
], args
[i
], 0);
1127 result
= scm_call_n (proc
, argv
, cif
->nargs
);
1129 unpack (cif
->rtype
, ret
, result
, 1);
1132 SCM_DEFINE (scm_procedure_to_pointer
, "procedure->pointer", 3, 0, 0,
1133 (SCM return_type
, SCM proc
, SCM arg_types
),
1134 "Return a pointer to a C function of type @var{return_type}\n"
1135 "taking arguments of types @var{arg_types} (a list) and\n"
1136 "behaving as a proxy to procedure @var{proc}. Thus\n"
1137 "@var{proc}'s arity, supported argument types, and return\n"
1138 "type should match @var{return_type} and @var{arg_types}.\n")
1139 #define FUNC_NAME s_scm_procedure_to_pointer
1141 SCM cif_pointer
, pointer
;
1144 void *closure
, *executable
;
1146 cif
= make_cif (return_type
, arg_types
, FUNC_NAME
);
1148 closure
= ffi_closure_alloc (sizeof (ffi_closure
), &executable
);
1149 err
= ffi_prep_closure_loc ((ffi_closure
*) closure
, cif
,
1150 invoke_closure
, SCM_UNPACK_POINTER (proc
),
1154 ffi_closure_free (closure
);
1155 SCM_MISC_ERROR ("`ffi_prep_closure_loc' failed", SCM_EOL
);
1158 /* CIF points to GC-managed memory and it should remain as long as
1159 POINTER (see below) is live. Wrap it in a Scheme pointer to then
1160 hold a weak reference on it. */
1161 cif_pointer
= scm_from_pointer (cif
, NULL
);
1163 if (closure
== executable
)
1165 pointer
= scm_from_pointer (executable
, ffi_closure_free
);
1166 register_weak_reference (pointer
,
1167 scm_list_2 (proc
, cif_pointer
));
1171 /* CLOSURE needs to be freed eventually. However, since
1172 `GC_all_interior_pointers' is disabled, we can't just register
1173 a finalizer for CLOSURE. Instead, we create a pointer object
1174 for CLOSURE, with a finalizer, and register it as a weak
1175 reference of POINTER. */
1178 pointer
= scm_from_pointer (executable
, NULL
);
1179 friend = scm_from_pointer (closure
, ffi_closure_free
);
1181 register_weak_reference (pointer
,
1182 scm_list_3 (proc
, cif_pointer
, friend));
1189 #endif /* FFI_CLOSURES */
1194 scm_init_foreign (void)
1196 #ifndef SCM_MAGIC_SNARFER
1197 #include "libguile/foreign.x"
1199 scm_define (sym_void
, scm_from_uint8 (SCM_FOREIGN_TYPE_VOID
));
1200 scm_define (sym_float
, scm_from_uint8 (SCM_FOREIGN_TYPE_FLOAT
));
1201 scm_define (sym_double
, scm_from_uint8 (SCM_FOREIGN_TYPE_DOUBLE
));
1202 scm_define (sym_uint8
, scm_from_uint8 (SCM_FOREIGN_TYPE_UINT8
));
1203 scm_define (sym_int8
, scm_from_uint8 (SCM_FOREIGN_TYPE_INT8
));
1204 scm_define (sym_uint16
, scm_from_uint8 (SCM_FOREIGN_TYPE_UINT16
));
1205 scm_define (sym_int16
, scm_from_uint8 (SCM_FOREIGN_TYPE_INT16
));
1206 scm_define (sym_uint32
, scm_from_uint8 (SCM_FOREIGN_TYPE_UINT32
));
1207 scm_define (sym_int32
, scm_from_uint8 (SCM_FOREIGN_TYPE_INT32
));
1208 scm_define (sym_uint64
, scm_from_uint8 (SCM_FOREIGN_TYPE_UINT64
));
1209 scm_define (sym_int64
, scm_from_uint8 (SCM_FOREIGN_TYPE_INT64
));
1211 scm_define (sym_short
,
1212 #if SIZEOF_SHORT == 8
1213 scm_from_uint8 (SCM_FOREIGN_TYPE_INT64
)
1214 #elif SIZEOF_SHORT == 4
1215 scm_from_uint8 (SCM_FOREIGN_TYPE_INT32
)
1216 #elif SIZEOF_SHORT == 2
1217 scm_from_uint8 (SCM_FOREIGN_TYPE_INT16
)
1219 # error unsupported sizeof (short)
1223 scm_define (sym_unsigned_short
,
1224 #if SIZEOF_SHORT == 8
1225 scm_from_uint8 (SCM_FOREIGN_TYPE_UINT64
)
1226 #elif SIZEOF_SHORT == 4
1227 scm_from_uint8 (SCM_FOREIGN_TYPE_UINT32
)
1228 #elif SIZEOF_SHORT == 2
1229 scm_from_uint8 (SCM_FOREIGN_TYPE_UINT16
)
1231 # error unsupported sizeof (short)
1235 scm_define (sym_int
,
1237 scm_from_uint8 (SCM_FOREIGN_TYPE_INT64
)
1238 #elif SIZEOF_INT == 4
1239 scm_from_uint8 (SCM_FOREIGN_TYPE_INT32
)
1241 # error unsupported sizeof (int)
1245 scm_define (sym_unsigned_int
,
1246 #if SIZEOF_UNSIGNED_INT == 8
1247 scm_from_uint8 (SCM_FOREIGN_TYPE_UINT64
)
1248 #elif SIZEOF_UNSIGNED_INT == 4
1249 scm_from_uint8 (SCM_FOREIGN_TYPE_UINT32
)
1251 # error unsupported sizeof (unsigned int)
1255 scm_define (sym_long
,
1256 #if SIZEOF_LONG == 8
1257 scm_from_uint8 (SCM_FOREIGN_TYPE_INT64
)
1258 #elif SIZEOF_LONG == 4
1259 scm_from_uint8 (SCM_FOREIGN_TYPE_INT32
)
1261 # error unsupported sizeof (long)
1265 scm_define (sym_unsigned_long
,
1266 #if SIZEOF_UNSIGNED_LONG == 8
1267 scm_from_uint8 (SCM_FOREIGN_TYPE_UINT64
)
1268 #elif SIZEOF_UNSIGNED_LONG == 4
1269 scm_from_uint8 (SCM_FOREIGN_TYPE_UINT32
)
1271 # error unsupported sizeof (unsigned long)
1275 scm_define (sym_size_t
,
1276 #if SIZEOF_SIZE_T == 8
1277 scm_from_uint8 (SCM_FOREIGN_TYPE_UINT64
)
1278 #elif SIZEOF_SIZE_T == 4
1279 scm_from_uint8 (SCM_FOREIGN_TYPE_UINT32
)
1281 # error unsupported sizeof (size_t)
1285 null_pointer
= scm_cell (scm_tc7_pointer
, 0);
1286 scm_define (sym_null
, null_pointer
);
1290 scm_register_foreign (void)
1292 scm_c_register_extension ("libguile-" SCM_EFFECTIVE_VERSION
,
1294 (scm_t_extension_init_func
)scm_init_foreign
,
1296 pointer_weak_refs
= scm_c_make_weak_table (0, SCM_WEAK_TABLE_KIND_KEY
);