Merge remote-tracking branch 'origin/stable-2.0'
[bpt/guile.git] / libguile / foreign.c
1 /* Copyright (C) 2010, 2011, 2012, 2013 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 <alloca.h>
26 #include <alignof.h>
27 #include <string.h>
28 #include <assert.h>
29
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"
35
36 \f
37
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");
56 SCM_SYMBOL (sym_ssize_t, "ssize_t");
57 SCM_SYMBOL (sym_ptrdiff_t, "ptrdiff_t");
58
59 /* that's for pointers, you know. */
60 SCM_SYMBOL (sym_asterisk, "*");
61
62 SCM_SYMBOL (sym_null, "%null-pointer");
63 SCM_SYMBOL (sym_null_pointer_error, "null-pointer-error");
64
65 /* The cell representing the null pointer. */
66 static SCM null_pointer;
67
68 #if SIZEOF_VOID_P == 4
69 # define scm_to_uintptr scm_to_uint32
70 # define scm_from_uintptr scm_from_uint32
71 #elif SIZEOF_VOID_P == 8
72 # define scm_to_uintptr scm_to_uint64
73 # define scm_from_uintptr scm_from_uint64
74 #else
75 # error unsupported pointer size
76 #endif
77
78
79 /* Raise a null pointer dereference error. */
80 static void
81 null_pointer_error (const char *func_name)
82 {
83 scm_error (sym_null_pointer_error, func_name,
84 "null pointer dereference", SCM_EOL, SCM_EOL);
85 }
86
87 \f
88 static SCM cif_to_procedure (SCM cif, SCM func_ptr);
89
90
91 static SCM pointer_weak_refs = SCM_BOOL_F;
92
93
94 static void
95 register_weak_reference (SCM from, SCM to)
96 {
97 scm_weak_table_putq_x (pointer_weak_refs, from, to);
98 }
99
100 static void
101 pointer_finalizer_trampoline (void *ptr, void *data)
102 {
103 scm_t_pointer_finalizer finalizer = data;
104 finalizer (SCM_POINTER_VALUE (SCM_PACK_POINTER (ptr)));
105 }
106
107 SCM_DEFINE (scm_pointer_p, "pointer?", 1, 0, 0,
108 (SCM obj),
109 "Return @code{#t} if @var{obj} is a pointer object, "
110 "@code{#f} otherwise.\n")
111 #define FUNC_NAME s_scm_pointer_p
112 {
113 return scm_from_bool (SCM_POINTER_P (obj));
114 }
115 #undef FUNC_NAME
116
117 SCM_DEFINE (scm_make_pointer, "make-pointer", 1, 1, 0,
118 (SCM address, SCM finalizer),
119 "Return a foreign pointer object pointing to @var{address}. "
120 "If @var{finalizer} is passed, it should be a pointer to a "
121 "one-argument C function that will be called when the pointer "
122 "object becomes unreachable.")
123 #define FUNC_NAME s_scm_make_pointer
124 {
125 void *c_finalizer;
126 scm_t_uintptr c_address;
127
128 c_address = scm_to_uintptr (address);
129 if (SCM_UNBNDP (finalizer))
130 c_finalizer = NULL;
131 else
132 {
133 SCM_VALIDATE_POINTER (2, finalizer);
134 c_finalizer = SCM_POINTER_VALUE (finalizer);
135 }
136
137 return scm_from_pointer ((void *) c_address, c_finalizer);
138 }
139 #undef FUNC_NAME
140
141 void *
142 scm_to_pointer (SCM pointer)
143 #define FUNC_NAME "scm_to_pointer"
144 {
145 SCM_VALIDATE_POINTER (1, pointer);
146 return SCM_POINTER_VALUE (pointer);
147 }
148 #undef FUNC_NAME
149
150 SCM
151 scm_from_pointer (void *ptr, scm_t_pointer_finalizer finalizer)
152 {
153 SCM ret;
154
155 if (ptr == NULL && finalizer == NULL)
156 ret = null_pointer;
157 else
158 {
159 ret = scm_cell (scm_tc7_pointer, (scm_t_bits) ptr);
160
161 if (finalizer)
162 scm_i_set_finalizer (SCM2PTR (ret), pointer_finalizer_trampoline,
163 finalizer);
164 }
165
166 return ret;
167 }
168
169 SCM_DEFINE (scm_pointer_address, "pointer-address", 1, 0, 0,
170 (SCM pointer),
171 "Return the numerical value of @var{pointer}.")
172 #define FUNC_NAME s_scm_pointer_address
173 {
174 SCM_VALIDATE_POINTER (1, pointer);
175
176 return scm_from_uintptr ((scm_t_uintptr) SCM_POINTER_VALUE (pointer));
177 }
178 #undef FUNC_NAME
179
180 SCM_DEFINE (scm_pointer_to_scm, "pointer->scm", 1, 0, 0,
181 (SCM pointer),
182 "Unsafely cast @var{pointer} to a Scheme object.\n"
183 "Cross your fingers!")
184 #define FUNC_NAME s_scm_pointer_to_scm
185 {
186 SCM_VALIDATE_POINTER (1, pointer);
187
188 return SCM_PACK ((scm_t_bits) SCM_POINTER_VALUE (pointer));
189 }
190 #undef FUNC_NAME
191
192 SCM_DEFINE (scm_scm_to_pointer, "scm->pointer", 1, 0, 0,
193 (SCM scm),
194 "Return a foreign pointer object with the @code{object-address}\n"
195 "of @var{scm}.")
196 #define FUNC_NAME s_scm_scm_to_pointer
197 {
198 SCM ret;
199
200 ret = scm_from_pointer ((void*) SCM_UNPACK (scm), NULL);
201 if (SCM_HEAP_OBJECT_P (ret))
202 register_weak_reference (ret, scm);
203
204 return ret;
205 }
206 #undef FUNC_NAME
207
208 SCM_DEFINE (scm_pointer_to_bytevector, "pointer->bytevector", 2, 2, 0,
209 (SCM pointer, SCM len, SCM offset, SCM uvec_type),
210 "Return a bytevector aliasing the @var{len} bytes pointed\n"
211 "to by @var{pointer}.\n\n"
212 "The user may specify an alternate default interpretation for\n"
213 "the memory by passing the @var{uvec_type} argument, to indicate\n"
214 "that the memory is an array of elements of that type.\n"
215 "@var{uvec_type} should be something that\n"
216 "@code{uniform-vector-element-type} would return, like @code{f32}\n"
217 "or @code{s16}.\n\n"
218 "When @var{offset} is passed, it specifies the offset in bytes\n"
219 "relative to @var{pointer} of the memory region aliased by the\n"
220 "returned bytevector.")
221 #define FUNC_NAME s_scm_pointer_to_bytevector
222 {
223 SCM ret;
224 scm_t_int8 *ptr;
225 size_t boffset, blen;
226 scm_t_array_element_type btype;
227
228 SCM_VALIDATE_POINTER (1, pointer);
229 ptr = SCM_POINTER_VALUE (pointer);
230
231 if (SCM_UNLIKELY (ptr == NULL))
232 null_pointer_error (FUNC_NAME);
233
234 if (SCM_UNBNDP (uvec_type))
235 btype = SCM_ARRAY_ELEMENT_TYPE_VU8;
236 else
237 {
238 int i;
239 for (i = 0; i <= SCM_ARRAY_ELEMENT_TYPE_LAST; i++)
240 if (scm_is_eq (uvec_type, scm_i_array_element_types[i]))
241 break;
242 switch (i)
243 {
244 case SCM_ARRAY_ELEMENT_TYPE_VU8:
245 case SCM_ARRAY_ELEMENT_TYPE_U8:
246 case SCM_ARRAY_ELEMENT_TYPE_S8:
247 case SCM_ARRAY_ELEMENT_TYPE_U16:
248 case SCM_ARRAY_ELEMENT_TYPE_S16:
249 case SCM_ARRAY_ELEMENT_TYPE_U32:
250 case SCM_ARRAY_ELEMENT_TYPE_S32:
251 case SCM_ARRAY_ELEMENT_TYPE_U64:
252 case SCM_ARRAY_ELEMENT_TYPE_S64:
253 case SCM_ARRAY_ELEMENT_TYPE_F32:
254 case SCM_ARRAY_ELEMENT_TYPE_F64:
255 case SCM_ARRAY_ELEMENT_TYPE_C32:
256 case SCM_ARRAY_ELEMENT_TYPE_C64:
257 btype = i;
258 break;
259 default:
260 scm_wrong_type_arg_msg (FUNC_NAME, SCM_ARG1, uvec_type,
261 "uniform vector type");
262 }
263 }
264
265 if (SCM_UNBNDP (offset))
266 boffset = 0;
267 else
268 boffset = scm_to_size_t (offset);
269
270 blen = scm_to_size_t (len);
271
272 ret = scm_c_take_typed_bytevector ((signed char *) ptr + boffset,
273 blen, btype, pointer);
274
275 return ret;
276 }
277 #undef FUNC_NAME
278
279 SCM_DEFINE (scm_bytevector_to_pointer, "bytevector->pointer", 1, 1, 0,
280 (SCM bv, SCM offset),
281 "Return a pointer pointer aliasing the memory pointed to by\n"
282 "@var{bv} or @var{offset} bytes after @var{bv} when @var{offset}\n"
283 "is passed.")
284 #define FUNC_NAME s_scm_bytevector_to_pointer
285 {
286 SCM ret;
287 signed char *ptr;
288 size_t boffset;
289
290 SCM_VALIDATE_BYTEVECTOR (1, bv);
291 ptr = SCM_BYTEVECTOR_CONTENTS (bv);
292
293 if (SCM_UNBNDP (offset))
294 boffset = 0;
295 else
296 boffset = scm_to_unsigned_integer (offset, 0,
297 SCM_BYTEVECTOR_LENGTH (bv) - 1);
298
299 ret = scm_from_pointer (ptr + boffset, NULL);
300 register_weak_reference (ret, bv);
301 return ret;
302 }
303 #undef FUNC_NAME
304
305 SCM_DEFINE (scm_set_pointer_finalizer_x, "set-pointer-finalizer!", 2, 0, 0,
306 (SCM pointer, SCM finalizer),
307 "Arrange for the C procedure wrapped by @var{finalizer} to be\n"
308 "called on the pointer wrapped by @var{pointer} when @var{pointer}\n"
309 "becomes unreachable. Note: the C procedure should not call into\n"
310 "Scheme. If you need a Scheme finalizer, use guardians.")
311 #define FUNC_NAME s_scm_set_pointer_finalizer_x
312 {
313 SCM_VALIDATE_POINTER (1, pointer);
314 SCM_VALIDATE_POINTER (2, finalizer);
315
316 scm_i_add_finalizer (SCM2PTR (pointer), pointer_finalizer_trampoline,
317 SCM_POINTER_VALUE (finalizer));
318
319 return SCM_UNSPECIFIED;
320 }
321 #undef FUNC_NAME
322
323 void
324 scm_i_pointer_print (SCM pointer, SCM port, scm_print_state *pstate)
325 {
326 scm_puts_unlocked ("#<pointer 0x", port);
327 scm_uintprint (scm_to_uintptr (scm_pointer_address (pointer)), 16, port);
328 scm_putc_unlocked ('>', port);
329 }
330
331 \f
332 /* Non-primitive helpers functions. These procedures could be
333 implemented in terms of the primitives above but would be inefficient
334 (heap allocation overhead, Scheme/C round trips, etc.) */
335
336 SCM_DEFINE (scm_dereference_pointer, "dereference-pointer", 1, 0, 0,
337 (SCM pointer),
338 "Assuming @var{pointer} points to a memory region that\n"
339 "holds a pointer, return this pointer.")
340 #define FUNC_NAME s_scm_dereference_pointer
341 {
342 SCM_VALIDATE_POINTER (1, pointer);
343
344 return scm_from_pointer (* (void **) SCM_POINTER_VALUE (pointer), NULL);
345 }
346 #undef FUNC_NAME
347
348 SCM_DEFINE (scm_string_to_pointer, "string->pointer", 1, 1, 0,
349 (SCM string, SCM encoding),
350 "Return a foreign pointer to a nul-terminated copy of\n"
351 "@var{string} in the given @var{encoding}, defaulting to\n"
352 "the current locale encoding. The C string is freed when\n"
353 "the returned foreign pointer becomes unreachable.\n\n"
354 "This is the Scheme equivalent of @code{scm_to_stringn}.")
355 #define FUNC_NAME s_scm_string_to_pointer
356 {
357 SCM_VALIDATE_STRING (1, string);
358
359 /* XXX: Finalizers slow down libgc; they could be avoided if
360 `scm_to_string' & co. were able to use libgc-allocated memory. */
361
362 if (SCM_UNBNDP (encoding))
363 return scm_from_pointer (scm_to_locale_string (string), free);
364 else
365 {
366 char *enc;
367 SCM ret;
368
369 SCM_VALIDATE_STRING (2, encoding);
370
371 enc = scm_to_locale_string (encoding);
372 scm_dynwind_begin (0);
373 scm_dynwind_free (enc);
374
375 ret = scm_from_pointer
376 (scm_to_stringn (string, NULL, enc,
377 scm_i_default_port_conversion_handler ()),
378 free);
379
380 scm_dynwind_end ();
381
382 return ret;
383 }
384 }
385 #undef FUNC_NAME
386
387 SCM_DEFINE (scm_pointer_to_string, "pointer->string", 1, 2, 0,
388 (SCM pointer, SCM length, SCM encoding),
389 "Return the string representing the C string pointed to by\n"
390 "@var{pointer}. If @var{length} is omitted or @code{-1}, the\n"
391 "string is assumed to be nul-terminated. Otherwise\n"
392 "@var{length} is the number of bytes in memory pointed to by\n"
393 "@var{pointer}. The C string is assumed to be in the given\n"
394 "@var{encoding}, defaulting to the current locale encoding.\n\n"
395 "This is the Scheme equivalent of @code{scm_from_stringn}.")
396 #define FUNC_NAME s_scm_pointer_to_string
397 {
398 size_t len;
399
400 SCM_VALIDATE_POINTER (1, pointer);
401
402 if (SCM_UNBNDP (length)
403 || scm_is_true (scm_eqv_p (length, scm_from_int (-1))))
404 len = (size_t)-1;
405 else
406 len = scm_to_size_t (length);
407
408 if (SCM_UNBNDP (encoding))
409 return scm_from_locale_stringn (SCM_POINTER_VALUE (pointer), len);
410 else
411 {
412 char *enc;
413 SCM ret;
414
415 SCM_VALIDATE_STRING (3, encoding);
416
417 enc = scm_to_locale_string (encoding);
418 scm_dynwind_begin (0);
419 scm_dynwind_free (enc);
420
421 ret = scm_from_stringn (SCM_POINTER_VALUE (pointer), len, enc,
422 scm_i_default_port_conversion_handler ());
423
424 scm_dynwind_end ();
425
426 return ret;
427 }
428 }
429 #undef FUNC_NAME
430
431 \f
432
433 SCM_DEFINE (scm_alignof, "alignof", 1, 0, 0, (SCM type),
434 "Return the alignment of @var{type}, in bytes.\n\n"
435 "@var{type} should be a valid C type, like @code{int}.\n"
436 "Alternately @var{type} may be the symbol @code{*}, in which\n"
437 "case the alignment of a pointer is returned. @var{type} may\n"
438 "also be a list of types, in which case the alignment of a\n"
439 "@code{struct} with ABI-conventional packing is returned.")
440 #define FUNC_NAME s_scm_alignof
441 {
442 if (SCM_I_INUMP (type))
443 {
444 switch (SCM_I_INUM (type))
445 {
446 case SCM_FOREIGN_TYPE_FLOAT:
447 return scm_from_size_t (alignof_type (float));
448 case SCM_FOREIGN_TYPE_DOUBLE:
449 return scm_from_size_t (alignof_type (double));
450 case SCM_FOREIGN_TYPE_UINT8:
451 return scm_from_size_t (alignof_type (scm_t_uint8));
452 case SCM_FOREIGN_TYPE_INT8:
453 return scm_from_size_t (alignof_type (scm_t_int8));
454 case SCM_FOREIGN_TYPE_UINT16:
455 return scm_from_size_t (alignof_type (scm_t_uint16));
456 case SCM_FOREIGN_TYPE_INT16:
457 return scm_from_size_t (alignof_type (scm_t_int16));
458 case SCM_FOREIGN_TYPE_UINT32:
459 return scm_from_size_t (alignof_type (scm_t_uint32));
460 case SCM_FOREIGN_TYPE_INT32:
461 return scm_from_size_t (alignof_type (scm_t_int32));
462 case SCM_FOREIGN_TYPE_UINT64:
463 return scm_from_size_t (alignof_type (scm_t_uint64));
464 case SCM_FOREIGN_TYPE_INT64:
465 return scm_from_size_t (alignof_type (scm_t_int64));
466 default:
467 scm_wrong_type_arg (FUNC_NAME, 1, type);
468 }
469 }
470 else if (scm_is_eq (type, sym_asterisk))
471 /* a pointer */
472 return scm_from_size_t (alignof_type (void*));
473 else if (scm_is_pair (type))
474 {
475 /* TYPE is a structure. Section 3-3 of the i386, x86_64, PowerPC,
476 and SPARC P.S. of the System V ABI all say: "Aggregates
477 (structures and arrays) and unions assume the alignment of
478 their most strictly aligned component." */
479 size_t max;
480
481 for (max = 0; scm_is_pair (type); type = SCM_CDR (type))
482 {
483 size_t align;
484
485 align = scm_to_size_t (scm_alignof (SCM_CAR (type)));
486 if (align > max)
487 max = align;
488 }
489
490 return scm_from_size_t (max);
491 }
492 else
493 scm_wrong_type_arg (FUNC_NAME, 1, type);
494 }
495 #undef FUNC_NAME
496
497 SCM_DEFINE (scm_sizeof, "sizeof", 1, 0, 0, (SCM type),
498 "Return the size of @var{type}, in bytes.\n\n"
499 "@var{type} should be a valid C type, like @code{int}.\n"
500 "Alternately @var{type} may be the symbol @code{*}, in which\n"
501 "case the size of a pointer is returned. @var{type} may also\n"
502 "be a list of types, in which case the size of a @code{struct}\n"
503 "with ABI-conventional packing is returned.")
504 #define FUNC_NAME s_scm_sizeof
505 {
506 if (SCM_I_INUMP (type))
507 {
508 switch (SCM_I_INUM (type))
509 {
510 case SCM_FOREIGN_TYPE_FLOAT:
511 return scm_from_size_t (sizeof (float));
512 case SCM_FOREIGN_TYPE_DOUBLE:
513 return scm_from_size_t (sizeof (double));
514 case SCM_FOREIGN_TYPE_UINT8:
515 return scm_from_size_t (sizeof (scm_t_uint8));
516 case SCM_FOREIGN_TYPE_INT8:
517 return scm_from_size_t (sizeof (scm_t_int8));
518 case SCM_FOREIGN_TYPE_UINT16:
519 return scm_from_size_t (sizeof (scm_t_uint16));
520 case SCM_FOREIGN_TYPE_INT16:
521 return scm_from_size_t (sizeof (scm_t_int16));
522 case SCM_FOREIGN_TYPE_UINT32:
523 return scm_from_size_t (sizeof (scm_t_uint32));
524 case SCM_FOREIGN_TYPE_INT32:
525 return scm_from_size_t (sizeof (scm_t_int32));
526 case SCM_FOREIGN_TYPE_UINT64:
527 return scm_from_size_t (sizeof (scm_t_uint64));
528 case SCM_FOREIGN_TYPE_INT64:
529 return scm_from_size_t (sizeof (scm_t_int64));
530 default:
531 scm_wrong_type_arg (FUNC_NAME, 1, type);
532 }
533 }
534 else if (scm_is_eq (type, sym_asterisk))
535 /* a pointer */
536 return scm_from_size_t (sizeof (void*));
537 else if (scm_is_pair (type))
538 {
539 /* a struct */
540 size_t off = 0;
541 size_t align = scm_to_size_t (scm_alignof(type));
542 while (scm_is_pair (type))
543 {
544 off = ROUND_UP (off, scm_to_size_t (scm_alignof (scm_car (type))));
545 off += scm_to_size_t (scm_sizeof (scm_car (type)));
546 type = scm_cdr (type);
547 }
548 return scm_from_size_t (ROUND_UP(off, align));
549 }
550 else
551 scm_wrong_type_arg (FUNC_NAME, 1, type);
552 }
553 #undef FUNC_NAME
554
555
556 /* return 1 on success, 0 on failure */
557 static int
558 parse_ffi_type (SCM type, int return_p, long *n_structs, long *n_struct_elts)
559 {
560 if (SCM_I_INUMP (type))
561 {
562 if ((SCM_I_INUM (type) < 0 )
563 || (SCM_I_INUM (type) > SCM_FOREIGN_TYPE_LAST))
564 return 0;
565 else if (SCM_I_INUM (type) == SCM_FOREIGN_TYPE_VOID && !return_p)
566 return 0;
567 else
568 return 1;
569 }
570 else if (scm_is_eq (type, sym_asterisk))
571 /* a pointer */
572 return 1;
573 else
574 {
575 long len;
576
577 len = scm_ilength (type);
578 if (len < 1)
579 return 0;
580 while (len--)
581 {
582 if (!parse_ffi_type (scm_car (type), 0, n_structs, n_struct_elts))
583 return 0;
584 (*n_struct_elts)++;
585 type = scm_cdr (type);
586 }
587 (*n_structs)++;
588 return 1;
589 }
590 }
591
592 static void
593 fill_ffi_type (SCM type, ffi_type *ftype, ffi_type ***type_ptrs,
594 ffi_type **types)
595 {
596 if (SCM_I_INUMP (type))
597 {
598 switch (SCM_I_INUM (type))
599 {
600 case SCM_FOREIGN_TYPE_FLOAT:
601 *ftype = ffi_type_float;
602 return;
603 case SCM_FOREIGN_TYPE_DOUBLE:
604 *ftype = ffi_type_double;
605 return;
606 case SCM_FOREIGN_TYPE_UINT8:
607 *ftype = ffi_type_uint8;
608 return;
609 case SCM_FOREIGN_TYPE_INT8:
610 *ftype = ffi_type_sint8;
611 return;
612 case SCM_FOREIGN_TYPE_UINT16:
613 *ftype = ffi_type_uint16;
614 return;
615 case SCM_FOREIGN_TYPE_INT16:
616 *ftype = ffi_type_sint16;
617 return;
618 case SCM_FOREIGN_TYPE_UINT32:
619 *ftype = ffi_type_uint32;
620 return;
621 case SCM_FOREIGN_TYPE_INT32:
622 *ftype = ffi_type_sint32;
623 return;
624 case SCM_FOREIGN_TYPE_UINT64:
625 *ftype = ffi_type_uint64;
626 return;
627 case SCM_FOREIGN_TYPE_INT64:
628 *ftype = ffi_type_sint64;
629 return;
630 case SCM_FOREIGN_TYPE_VOID:
631 *ftype = ffi_type_void;
632 return;
633 default:
634 scm_wrong_type_arg_msg ("pointer->procedure", 0, type,
635 "foreign type");
636 }
637 }
638 else if (scm_is_eq (type, sym_asterisk))
639 /* a pointer */
640 {
641 *ftype = ffi_type_pointer;
642 return;
643 }
644 else
645 {
646 long i, len;
647
648 len = scm_ilength (type);
649
650 ftype->size = 0;
651 ftype->alignment = 0;
652 ftype->type = FFI_TYPE_STRUCT;
653 ftype->elements = *type_ptrs;
654 *type_ptrs += len + 1;
655
656 for (i = 0; i < len; i++)
657 {
658 ftype->elements[i] = *types;
659 *types += 1;
660 fill_ffi_type (scm_car (type), ftype->elements[i],
661 type_ptrs, types);
662 type = scm_cdr (type);
663 }
664 ftype->elements[i] = NULL;
665 }
666 }
667
668 /* Return a "cif" (call interface) for the given RETURN_TYPE and
669 ARG_TYPES. */
670 static ffi_cif *
671 make_cif (SCM return_type, SCM arg_types, const char *caller)
672 #define FUNC_NAME caller
673 {
674 SCM walk;
675 long i, nargs, n_structs, n_struct_elts;
676 size_t cif_len;
677 char *mem;
678 ffi_cif *cif;
679 ffi_type **type_ptrs;
680 ffi_type *types;
681
682 nargs = scm_ilength (arg_types);
683 SCM_ASSERT (nargs >= 0, arg_types, 3, FUNC_NAME);
684 /* fixme: assert nargs < 1<<32 */
685 n_structs = n_struct_elts = 0;
686
687 /* For want of talloc, we're going to have to do this in two passes: first we
688 figure out how much memory is needed for all types, then we allocate the
689 cif and the types all in one block. */
690 if (!parse_ffi_type (return_type, 1, &n_structs, &n_struct_elts))
691 scm_wrong_type_arg (FUNC_NAME, 1, return_type);
692 for (walk = arg_types; scm_is_pair (walk); walk = scm_cdr (walk))
693 if (!parse_ffi_type (scm_car (walk), 0, &n_structs, &n_struct_elts))
694 scm_wrong_type_arg (FUNC_NAME, 3, scm_car (walk));
695
696 /* the memory: with space for the cif itself */
697 cif_len = sizeof (ffi_cif);
698
699 /* then ffi_type pointers: one for each arg, one for each struct
700 element, and one for each struct (for null-termination) */
701 cif_len = (ROUND_UP (cif_len, alignof_type (void *))
702 + (nargs + n_structs + n_struct_elts)*sizeof(void*));
703
704 /* then the ffi_type structs themselves, one per arg and struct element, and
705 one for the return val */
706 cif_len = (ROUND_UP (cif_len, alignof_type (ffi_type))
707 + (nargs + n_struct_elts + 1)*sizeof(ffi_type));
708
709 mem = scm_gc_malloc_pointerless (cif_len, "foreign");
710 /* ensure all the memory is initialized, even the holes */
711 memset (mem, 0, cif_len);
712 cif = (ffi_cif *) mem;
713
714 /* reuse cif_len to walk through the mem */
715 cif_len = ROUND_UP (sizeof (ffi_cif), alignof_type (void *));
716 type_ptrs = (ffi_type**)(mem + cif_len);
717 cif_len = ROUND_UP (cif_len
718 + (nargs + n_structs + n_struct_elts)*sizeof(void*),
719 alignof_type (ffi_type));
720 types = (ffi_type*)(mem + cif_len);
721
722 /* whew. now knit the pointers together. */
723 cif->rtype = types++;
724 fill_ffi_type (return_type, cif->rtype, &type_ptrs, &types);
725 cif->arg_types = type_ptrs;
726 type_ptrs += nargs;
727 for (walk = arg_types, i = 0; scm_is_pair (walk); walk = scm_cdr (walk), i++)
728 {
729 cif->arg_types[i] = types++;
730 fill_ffi_type (scm_car (walk), cif->arg_types[i], &type_ptrs, &types);
731 }
732
733 /* round out the cif, and we're done. */
734 cif->abi = FFI_DEFAULT_ABI;
735 cif->nargs = nargs;
736 cif->bytes = 0;
737 cif->flags = 0;
738
739 if (FFI_OK != ffi_prep_cif (cif, FFI_DEFAULT_ABI, cif->nargs, cif->rtype,
740 cif->arg_types))
741 SCM_MISC_ERROR ("ffi_prep_cif failed", SCM_EOL);
742
743 return cif;
744 }
745 #undef FUNC_NAME
746
747 SCM_DEFINE (scm_pointer_to_procedure, "pointer->procedure", 3, 0, 0,
748 (SCM return_type, SCM func_ptr, SCM arg_types),
749 "Make a foreign function.\n\n"
750 "Given the foreign void pointer @var{func_ptr}, its argument and\n"
751 "return types @var{arg_types} and @var{return_type}, return a\n"
752 "procedure that will pass arguments to the foreign function\n"
753 "and return appropriate values.\n\n"
754 "@var{arg_types} should be a list of foreign types.\n"
755 "@code{return_type} should be a foreign type.")
756 #define FUNC_NAME s_scm_pointer_to_procedure
757 {
758 ffi_cif *cif;
759
760 SCM_VALIDATE_POINTER (2, func_ptr);
761
762 cif = make_cif (return_type, arg_types, FUNC_NAME);
763
764 return cif_to_procedure (scm_from_pointer (cif, NULL), func_ptr);
765 }
766 #undef FUNC_NAME
767
768 \f
769
770 /* Pre-generate trampolines for less than 10 arguments. */
771
772 #ifdef WORDS_BIGENDIAN
773 #define OBJCODE_HEADER(M) M (0), M (0), M (0), M (8), M (0), M (0), M (0), M (40)
774 #define META_HEADER(M) M (0), M (0), M (0), M (32), M (0), M (0), M (0), M (0)
775 #else
776 #define OBJCODE_HEADER(M) M (8), M (0), M (0), M (0), M (40), M (0), M (0), M (0)
777 #define META_HEADER(M) M (32), M (0), M (0), M (0), M (0), M (0), M (0), M (0)
778 #endif
779
780 #define GEN_CODE(M, nreq) \
781 OBJCODE_HEADER (M), \
782 /* 0 */ M (scm_op_assert_nargs_ee), M (0), M (nreq), /* assert number of args */ \
783 /* 3 */ M (scm_op_object_ref), M (0), /* push the pair with the cif and the function pointer */ \
784 /* 5 */ M (scm_op_foreign_call), M (nreq), /* and call (will return value as well) */ \
785 /* 7 */ M (scm_op_nop), \
786 /* 8 */ META (M, 3, 7, nreq)
787
788 #define META(M, start, end, nreq) \
789 META_HEADER (M), \
790 /* 0 */ M (scm_op_make_eol), /* bindings */ \
791 /* 1 */ M (scm_op_make_eol), /* sources */ \
792 /* 2 */ M (scm_op_make_int8), M (start), M (scm_op_make_int8), M (end), /* arity: from ip N to ip N */ \
793 /* 6 */ M (scm_op_make_int8), M (nreq), /* the arity is N required args */ \
794 /* 8 */ M (scm_op_list), M (0), M (3), /* make a list of those 3 vals */ \
795 /* 11 */ M (scm_op_list), M (0), M (1), /* and the arities will be a list of that one list */ \
796 /* 14 */ M (scm_op_load_symbol), M (0), M (0), M (4), M ('n'), M ('a'), M ('M'), M ('e'), /* `name' */ \
797 /* 22 */ M (scm_op_object_ref), M (1), /* the name from the object table */ \
798 /* 24 */ M (scm_op_cons), /* make a pair for the properties */ \
799 /* 25 */ M (scm_op_list), M (0), M (4), /* pack bindings, sources, and arities into list */ \
800 /* 28 */ M (scm_op_return), /* and return */ \
801 /* 29 */ M (scm_op_nop), M (scm_op_nop), M (scm_op_nop) \
802 /* 32 */
803
804 #define M_STATIC(x) (x)
805 #define CODE(nreq) GEN_CODE (M_STATIC, nreq)
806
807 static const struct
808 {
809 scm_t_uint64 dummy; /* ensure 8-byte alignment; perhaps there's a better way */
810 const scm_t_uint8 bytes[10 * (sizeof (struct scm_objcode) + 8
811 + sizeof (struct scm_objcode) + 32)];
812 } raw_bytecode = {
813 0,
814 {
815 CODE (0), CODE (1), CODE (2), CODE (3), CODE (4),
816 CODE (5), CODE (6), CODE (7), CODE (8), CODE (9)
817 }
818 };
819
820 static SCM
821 make_objcode_trampoline (unsigned int nargs)
822 {
823 const int size = sizeof (struct scm_objcode) + 8
824 + sizeof (struct scm_objcode) + 32;
825 SCM bytecode = scm_c_make_bytevector (size);
826 scm_t_uint8 *bytes = (scm_t_uint8 *) SCM_BYTEVECTOR_CONTENTS (bytecode);
827 int i = 0;
828
829 #define M_DYNAMIC(x) (bytes[i++] = (x))
830 GEN_CODE (M_DYNAMIC, nargs);
831 #undef M_DYNAMIC
832
833 if (i != size)
834 scm_syserror ("make_objcode_trampoline");
835 return scm_bytecode_to_objcode (bytecode, SCM_UNDEFINED);
836 }
837
838 #undef GEN_CODE
839 #undef META
840 #undef M_STATIC
841 #undef CODE
842 #undef OBJCODE_HEADER
843 #undef META_HEADER
844
845 /*
846 (defun generate-objcode-cells (n)
847 "Generate objcode cells for up to N arguments"
848 (interactive "p")
849 (let ((i 0))
850 (while (< i n)
851 (insert
852 (format " { STATIC_OBJCODE_TAG, SCM_PACK (raw_bytecode.bytes + %d) },\n"
853 (* (+ 4 4 8 4 4 32) i)))
854 (insert " { SCM_BOOL_F, SCM_PACK (0) },\n")
855 (setq i (1+ i)))))
856 */
857 #define STATIC_OBJCODE_TAG \
858 SCM_PACK (SCM_MAKE_OBJCODE_TAG (SCM_OBJCODE_TYPE_STATIC, 0))
859
860 static const struct
861 {
862 scm_t_uint64 dummy; /* alignment */
863 scm_t_cell cells[10 * 2]; /* 10 double cells */
864 } objcode_cells = {
865 0,
866 /* C-u 1 0 M-x generate-objcode-cells RET */
867 {
868 { STATIC_OBJCODE_TAG, SCM_PACK (raw_bytecode.bytes + 0) },
869 { SCM_BOOL_F, SCM_PACK (0) },
870 { STATIC_OBJCODE_TAG, SCM_PACK (raw_bytecode.bytes + 56) },
871 { SCM_BOOL_F, SCM_PACK (0) },
872 { STATIC_OBJCODE_TAG, SCM_PACK (raw_bytecode.bytes + 112) },
873 { SCM_BOOL_F, SCM_PACK (0) },
874 { STATIC_OBJCODE_TAG, SCM_PACK (raw_bytecode.bytes + 168) },
875 { SCM_BOOL_F, SCM_PACK (0) },
876 { STATIC_OBJCODE_TAG, SCM_PACK (raw_bytecode.bytes + 224) },
877 { SCM_BOOL_F, SCM_PACK (0) },
878 { STATIC_OBJCODE_TAG, SCM_PACK (raw_bytecode.bytes + 280) },
879 { SCM_BOOL_F, SCM_PACK (0) },
880 { STATIC_OBJCODE_TAG, SCM_PACK (raw_bytecode.bytes + 336) },
881 { SCM_BOOL_F, SCM_PACK (0) },
882 { STATIC_OBJCODE_TAG, SCM_PACK (raw_bytecode.bytes + 392) },
883 { SCM_BOOL_F, SCM_PACK (0) },
884 { STATIC_OBJCODE_TAG, SCM_PACK (raw_bytecode.bytes + 448) },
885 { SCM_BOOL_F, SCM_PACK (0) },
886 { STATIC_OBJCODE_TAG, SCM_PACK (raw_bytecode.bytes + 504) },
887 { SCM_BOOL_F, SCM_PACK (0) }
888 }
889 };
890
891 static const SCM objcode_trampolines[10] = {
892 SCM_PACK (objcode_cells.cells+0),
893 SCM_PACK (objcode_cells.cells+2),
894 SCM_PACK (objcode_cells.cells+4),
895 SCM_PACK (objcode_cells.cells+6),
896 SCM_PACK (objcode_cells.cells+8),
897 SCM_PACK (objcode_cells.cells+10),
898 SCM_PACK (objcode_cells.cells+12),
899 SCM_PACK (objcode_cells.cells+14),
900 SCM_PACK (objcode_cells.cells+16),
901 SCM_PACK (objcode_cells.cells+18),
902 };
903
904 static SCM large_objcode_trampolines = SCM_UNDEFINED;
905 static scm_i_pthread_mutex_t large_objcode_trampolines_mutex =
906 SCM_I_PTHREAD_MUTEX_INITIALIZER;
907
908 static SCM
909 get_objcode_trampoline (unsigned int nargs)
910 {
911 SCM objcode;
912
913 if (nargs < 10)
914 objcode = objcode_trampolines[nargs];
915 else if (nargs < 128)
916 {
917 scm_i_scm_pthread_mutex_lock (&large_objcode_trampolines_mutex);
918 if (SCM_UNBNDP (large_objcode_trampolines))
919 large_objcode_trampolines = scm_c_make_vector (128, SCM_UNDEFINED);
920 objcode = scm_c_vector_ref (large_objcode_trampolines, nargs);
921 if (SCM_UNBNDP (objcode))
922 scm_c_vector_set_x (large_objcode_trampolines, nargs,
923 objcode = make_objcode_trampoline (nargs));
924 scm_i_pthread_mutex_unlock (&large_objcode_trampolines_mutex);
925 }
926 else
927 scm_misc_error ("make-foreign-function", "args >= 128 currently unimplemented",
928 SCM_EOL);
929
930 return objcode;
931 }
932
933 static SCM
934 cif_to_procedure (SCM cif, SCM func_ptr)
935 {
936 ffi_cif *c_cif;
937 SCM objcode, table, ret;
938
939 c_cif = (ffi_cif *) SCM_POINTER_VALUE (cif);
940 objcode = get_objcode_trampoline (c_cif->nargs);
941
942 table = scm_c_make_vector (2, SCM_UNDEFINED);
943 SCM_SIMPLE_VECTOR_SET (table, 0, scm_cons (cif, func_ptr));
944 SCM_SIMPLE_VECTOR_SET (table, 1, SCM_BOOL_F); /* name */
945 ret = scm_make_program (objcode, table, SCM_BOOL_F);
946
947 return ret;
948 }
949
950 /* Set *LOC to the foreign representation of X with TYPE. */
951 static void
952 unpack (const ffi_type *type, void *loc, SCM x, int return_value_p)
953 #define FUNC_NAME "scm_i_foreign_call"
954 {
955 switch (type->type)
956 {
957 case FFI_TYPE_FLOAT:
958 *(float *) loc = scm_to_double (x);
959 break;
960 case FFI_TYPE_DOUBLE:
961 *(double *) loc = scm_to_double (x);
962 break;
963
964 /* For integer return values smaller than `int', libffi expects the
965 result in an `ffi_arg'-long buffer. */
966
967 case FFI_TYPE_UINT8:
968 if (return_value_p)
969 *(ffi_arg *) loc = scm_to_uint8 (x);
970 else
971 *(scm_t_uint8 *) loc = scm_to_uint8 (x);
972 break;
973 case FFI_TYPE_SINT8:
974 if (return_value_p)
975 *(ffi_arg *) loc = scm_to_int8 (x);
976 else
977 *(scm_t_int8 *) loc = scm_to_int8 (x);
978 break;
979 case FFI_TYPE_UINT16:
980 if (return_value_p)
981 *(ffi_arg *) loc = scm_to_uint16 (x);
982 else
983 *(scm_t_uint16 *) loc = scm_to_uint16 (x);
984 break;
985 case FFI_TYPE_SINT16:
986 if (return_value_p)
987 *(ffi_arg *) loc = scm_to_int16 (x);
988 else
989 *(scm_t_int16 *) loc = scm_to_int16 (x);
990 break;
991 case FFI_TYPE_UINT32:
992 if (return_value_p)
993 *(ffi_arg *) loc = scm_to_uint32 (x);
994 else
995 *(scm_t_uint32 *) loc = scm_to_uint32 (x);
996 break;
997 case FFI_TYPE_SINT32:
998 if (return_value_p)
999 *(ffi_arg *) loc = scm_to_int32 (x);
1000 else
1001 *(scm_t_int32 *) loc = scm_to_int32 (x);
1002 break;
1003 case FFI_TYPE_UINT64:
1004 *(scm_t_uint64 *) loc = scm_to_uint64 (x);
1005 break;
1006 case FFI_TYPE_SINT64:
1007 *(scm_t_int64 *) loc = scm_to_int64 (x);
1008 break;
1009 case FFI_TYPE_STRUCT:
1010 SCM_VALIDATE_POINTER (1, x);
1011 memcpy (loc, SCM_POINTER_VALUE (x), type->size);
1012 break;
1013 case FFI_TYPE_POINTER:
1014 SCM_VALIDATE_POINTER (1, x);
1015 *(void **) loc = SCM_POINTER_VALUE (x);
1016 break;
1017 case FFI_TYPE_VOID:
1018 /* Do nothing. */
1019 break;
1020 default:
1021 abort ();
1022 }
1023 }
1024 #undef FUNC_NAME
1025
1026 /* Return a Scheme representation of the foreign value at LOC of type
1027 TYPE. When RETURN_VALUE_P is true, LOC is assumed to point to a
1028 return value buffer; otherwise LOC is assumed to point to an
1029 argument buffer. */
1030 static SCM
1031 pack (const ffi_type * type, const void *loc, int return_value_p)
1032 {
1033 switch (type->type)
1034 {
1035 case FFI_TYPE_VOID:
1036 return SCM_UNSPECIFIED;
1037 case FFI_TYPE_FLOAT:
1038 return scm_from_double (*(float *) loc);
1039 case FFI_TYPE_DOUBLE:
1040 return scm_from_double (*(double *) loc);
1041
1042 /* For integer return values smaller than `int', libffi stores the
1043 result in an `ffi_arg'-long buffer, of which only the
1044 significant bits must be kept---hence the pair of casts below.
1045 See <http://thread.gmane.org/gmane.comp.lib.ffi.general/406>
1046 for details. */
1047
1048 case FFI_TYPE_UINT8:
1049 if (return_value_p)
1050 return scm_from_uint8 ((scm_t_uint8) *(ffi_arg *) loc);
1051 else
1052 return scm_from_uint8 (* (scm_t_uint8 *) loc);
1053 case FFI_TYPE_SINT8:
1054 if (return_value_p)
1055 return scm_from_int8 ((scm_t_int8) *(ffi_arg *) loc);
1056 else
1057 return scm_from_int8 (* (scm_t_int8 *) loc);
1058 case FFI_TYPE_UINT16:
1059 if (return_value_p)
1060 return scm_from_uint16 ((scm_t_uint16) *(ffi_arg *) loc);
1061 else
1062 return scm_from_uint16 (* (scm_t_uint16 *) loc);
1063 case FFI_TYPE_SINT16:
1064 if (return_value_p)
1065 return scm_from_int16 ((scm_t_int16) *(ffi_arg *) loc);
1066 else
1067 return scm_from_int16 (* (scm_t_int16 *) loc);
1068 case FFI_TYPE_UINT32:
1069 if (return_value_p)
1070 return scm_from_uint32 ((scm_t_uint32) *(ffi_arg *) loc);
1071 else
1072 return scm_from_uint32 (* (scm_t_uint32 *) loc);
1073 case FFI_TYPE_SINT32:
1074 if (return_value_p)
1075 return scm_from_int32 ((scm_t_int32) *(ffi_arg *) loc);
1076 else
1077 return scm_from_int32 (* (scm_t_int32 *) loc);
1078 case FFI_TYPE_UINT64:
1079 return scm_from_uint64 (*(scm_t_uint64 *) loc);
1080 case FFI_TYPE_SINT64:
1081 return scm_from_int64 (*(scm_t_int64 *) loc);
1082
1083 case FFI_TYPE_STRUCT:
1084 {
1085 void *mem = scm_gc_malloc_pointerless (type->size, "foreign");
1086 memcpy (mem, loc, type->size);
1087 return scm_from_pointer (mem, NULL);
1088 }
1089 case FFI_TYPE_POINTER:
1090 return scm_from_pointer (*(void **) loc, NULL);
1091 default:
1092 abort ();
1093 }
1094 }
1095
1096
1097 SCM
1098 scm_i_foreign_call (SCM foreign, const SCM *argv)
1099 {
1100 /* FOREIGN is the pair that cif_to_procedure set as the 0th element of the
1101 objtable. */
1102 ffi_cif *cif;
1103 void (*func) (void);
1104 scm_t_uint8 *data;
1105 void *rvalue;
1106 void **args;
1107 unsigned i;
1108 size_t arg_size;
1109 scm_t_ptrdiff off;
1110
1111 cif = SCM_POINTER_VALUE (SCM_CAR (foreign));
1112 func = SCM_POINTER_VALUE (SCM_CDR (foreign));
1113
1114 /* Argument pointers. */
1115 args = alloca (sizeof (void *) * cif->nargs);
1116
1117 /* Compute the worst-case amount of memory needed to store all the argument
1118 values. Note: as of libffi 3.0.9 `cif->bytes' is undocumented and is zero,
1119 so it can't be used for that purpose. */
1120 for (i = 0, arg_size = 0; i < cif->nargs; i++)
1121 arg_size += cif->arg_types[i]->size + cif->arg_types[i]->alignment - 1;
1122
1123 /* Space for argument values, followed by return value. */
1124 data = alloca (arg_size + cif->rtype->size
1125 + max (sizeof (void *), cif->rtype->alignment));
1126
1127 /* Unpack ARGV to native values, setting ARGV pointers. */
1128 for (i = 0, off = 0;
1129 i < cif->nargs;
1130 off = (scm_t_uint8 *) args[i] - data + cif->arg_types[i]->size,
1131 i++)
1132 {
1133 /* Suitably align the storage area for argument I. */
1134 args[i] = (void *) ROUND_UP ((scm_t_uintptr) data + off,
1135 cif->arg_types[i]->alignment);
1136 assert ((scm_t_uintptr) args[i] % cif->arg_types[i]->alignment == 0);
1137 unpack (cif->arg_types[i], args[i], argv[i], 0);
1138 }
1139
1140 /* Prepare space for the return value. On some platforms, such as
1141 `armv5tel-*-linux-gnueabi', the return value has to be at least
1142 word-aligned, even if its type doesn't have any alignment requirement as is
1143 the case with `char'. */
1144 rvalue = (void *) ROUND_UP ((scm_t_uintptr) data + off,
1145 max (sizeof (void *), cif->rtype->alignment));
1146
1147 /* off we go! */
1148 ffi_call (cif, func, rvalue, args);
1149
1150 return pack (cif->rtype, rvalue, 1);
1151 }
1152
1153 \f
1154 /* Function pointers aka. "callbacks" or "closures". */
1155
1156 #ifdef FFI_CLOSURES
1157
1158 /* Trampoline to invoke a libffi closure that wraps a Scheme
1159 procedure. */
1160 static void
1161 invoke_closure (ffi_cif *cif, void *ret, void **args, void *data)
1162 {
1163 size_t i;
1164 SCM proc, *argv, result;
1165
1166 proc = SCM_PACK_POINTER (data);
1167
1168 argv = alloca (cif->nargs * sizeof (*argv));
1169
1170 /* Pack ARGS to SCM values, setting ARGV pointers. */
1171 for (i = 0; i < cif->nargs; i++)
1172 argv[i] = pack (cif->arg_types[i], args[i], 0);
1173
1174 result = scm_call_n (proc, argv, cif->nargs);
1175
1176 unpack (cif->rtype, ret, result, 1);
1177 }
1178
1179 SCM_DEFINE (scm_procedure_to_pointer, "procedure->pointer", 3, 0, 0,
1180 (SCM return_type, SCM proc, SCM arg_types),
1181 "Return a pointer to a C function of type @var{return_type}\n"
1182 "taking arguments of types @var{arg_types} (a list) and\n"
1183 "behaving as a proxy to procedure @var{proc}. Thus\n"
1184 "@var{proc}'s arity, supported argument types, and return\n"
1185 "type should match @var{return_type} and @var{arg_types}.\n")
1186 #define FUNC_NAME s_scm_procedure_to_pointer
1187 {
1188 SCM cif_pointer, pointer;
1189 ffi_cif *cif;
1190 ffi_status err;
1191 void *closure, *executable;
1192
1193 cif = make_cif (return_type, arg_types, FUNC_NAME);
1194
1195 closure = ffi_closure_alloc (sizeof (ffi_closure), &executable);
1196 err = ffi_prep_closure_loc ((ffi_closure *) closure, cif,
1197 invoke_closure, SCM_UNPACK_POINTER (proc),
1198 executable);
1199 if (err != FFI_OK)
1200 {
1201 ffi_closure_free (closure);
1202 SCM_MISC_ERROR ("`ffi_prep_closure_loc' failed", SCM_EOL);
1203 }
1204
1205 /* CIF points to GC-managed memory and it should remain as long as
1206 POINTER (see below) is live. Wrap it in a Scheme pointer to then
1207 hold a weak reference on it. */
1208 cif_pointer = scm_from_pointer (cif, NULL);
1209
1210 if (closure == executable)
1211 {
1212 pointer = scm_from_pointer (executable, ffi_closure_free);
1213 register_weak_reference (pointer,
1214 scm_list_2 (proc, cif_pointer));
1215 }
1216 else
1217 {
1218 /* CLOSURE needs to be freed eventually. However, since
1219 `GC_all_interior_pointers' is disabled, we can't just register
1220 a finalizer for CLOSURE. Instead, we create a pointer object
1221 for CLOSURE, with a finalizer, and register it as a weak
1222 reference of POINTER. */
1223 SCM friend;
1224
1225 pointer = scm_from_pointer (executable, NULL);
1226 friend = scm_from_pointer (closure, ffi_closure_free);
1227
1228 register_weak_reference (pointer,
1229 scm_list_3 (proc, cif_pointer, friend));
1230 }
1231
1232 return pointer;
1233 }
1234 #undef FUNC_NAME
1235
1236 #endif /* FFI_CLOSURES */
1237
1238 \f
1239
1240 static void
1241 scm_init_foreign (void)
1242 {
1243 #ifndef SCM_MAGIC_SNARFER
1244 #include "libguile/foreign.x"
1245 #endif
1246 scm_define (sym_void, scm_from_uint8 (SCM_FOREIGN_TYPE_VOID));
1247 scm_define (sym_float, scm_from_uint8 (SCM_FOREIGN_TYPE_FLOAT));
1248 scm_define (sym_double, scm_from_uint8 (SCM_FOREIGN_TYPE_DOUBLE));
1249 scm_define (sym_uint8, scm_from_uint8 (SCM_FOREIGN_TYPE_UINT8));
1250 scm_define (sym_int8, scm_from_uint8 (SCM_FOREIGN_TYPE_INT8));
1251 scm_define (sym_uint16, scm_from_uint8 (SCM_FOREIGN_TYPE_UINT16));
1252 scm_define (sym_int16, scm_from_uint8 (SCM_FOREIGN_TYPE_INT16));
1253 scm_define (sym_uint32, scm_from_uint8 (SCM_FOREIGN_TYPE_UINT32));
1254 scm_define (sym_int32, scm_from_uint8 (SCM_FOREIGN_TYPE_INT32));
1255 scm_define (sym_uint64, scm_from_uint8 (SCM_FOREIGN_TYPE_UINT64));
1256 scm_define (sym_int64, scm_from_uint8 (SCM_FOREIGN_TYPE_INT64));
1257
1258 scm_define (sym_short,
1259 #if SIZEOF_SHORT == 8
1260 scm_from_uint8 (SCM_FOREIGN_TYPE_INT64)
1261 #elif SIZEOF_SHORT == 4
1262 scm_from_uint8 (SCM_FOREIGN_TYPE_INT32)
1263 #elif SIZEOF_SHORT == 2
1264 scm_from_uint8 (SCM_FOREIGN_TYPE_INT16)
1265 #else
1266 # error unsupported sizeof (short)
1267 #endif
1268 );
1269
1270 scm_define (sym_unsigned_short,
1271 #if SIZEOF_SHORT == 8
1272 scm_from_uint8 (SCM_FOREIGN_TYPE_UINT64)
1273 #elif SIZEOF_SHORT == 4
1274 scm_from_uint8 (SCM_FOREIGN_TYPE_UINT32)
1275 #elif SIZEOF_SHORT == 2
1276 scm_from_uint8 (SCM_FOREIGN_TYPE_UINT16)
1277 #else
1278 # error unsupported sizeof (short)
1279 #endif
1280 );
1281
1282 scm_define (sym_int,
1283 #if SIZEOF_INT == 8
1284 scm_from_uint8 (SCM_FOREIGN_TYPE_INT64)
1285 #elif SIZEOF_INT == 4
1286 scm_from_uint8 (SCM_FOREIGN_TYPE_INT32)
1287 #else
1288 # error unsupported sizeof (int)
1289 #endif
1290 );
1291
1292 scm_define (sym_unsigned_int,
1293 #if SIZEOF_UNSIGNED_INT == 8
1294 scm_from_uint8 (SCM_FOREIGN_TYPE_UINT64)
1295 #elif SIZEOF_UNSIGNED_INT == 4
1296 scm_from_uint8 (SCM_FOREIGN_TYPE_UINT32)
1297 #else
1298 # error unsupported sizeof (unsigned int)
1299 #endif
1300 );
1301
1302 scm_define (sym_long,
1303 #if SIZEOF_LONG == 8
1304 scm_from_uint8 (SCM_FOREIGN_TYPE_INT64)
1305 #elif SIZEOF_LONG == 4
1306 scm_from_uint8 (SCM_FOREIGN_TYPE_INT32)
1307 #else
1308 # error unsupported sizeof (long)
1309 #endif
1310 );
1311
1312 scm_define (sym_unsigned_long,
1313 #if SIZEOF_UNSIGNED_LONG == 8
1314 scm_from_uint8 (SCM_FOREIGN_TYPE_UINT64)
1315 #elif SIZEOF_UNSIGNED_LONG == 4
1316 scm_from_uint8 (SCM_FOREIGN_TYPE_UINT32)
1317 #else
1318 # error unsupported sizeof (unsigned long)
1319 #endif
1320 );
1321
1322 scm_define (sym_size_t,
1323 #if SIZEOF_SIZE_T == 8
1324 scm_from_uint8 (SCM_FOREIGN_TYPE_UINT64)
1325 #elif SIZEOF_SIZE_T == 4
1326 scm_from_uint8 (SCM_FOREIGN_TYPE_UINT32)
1327 #else
1328 # error unsupported sizeof (size_t)
1329 #endif
1330 );
1331
1332 scm_define (sym_ssize_t,
1333 #if SIZEOF_SIZE_T == 8
1334 scm_from_uint8 (SCM_FOREIGN_TYPE_INT64)
1335 #elif SIZEOF_SIZE_T == 4
1336 scm_from_uint8 (SCM_FOREIGN_TYPE_INT32)
1337 #else
1338 # error unsupported sizeof (ssize_t)
1339 #endif
1340 );
1341
1342 scm_define (sym_ptrdiff_t,
1343 #if SCM_SIZEOF_SCM_T_PTRDIFF == 8
1344 scm_from_uint8 (SCM_FOREIGN_TYPE_INT64)
1345 #elif SCM_SIZEOF_SCM_T_PTRDIFF == 4
1346 scm_from_uint8 (SCM_FOREIGN_TYPE_INT32)
1347 #else
1348 # error unsupported sizeof (scm_t_ptrdiff)
1349 #endif
1350 );
1351
1352 null_pointer = scm_cell (scm_tc7_pointer, 0);
1353 scm_define (sym_null, null_pointer);
1354 }
1355
1356 void
1357 scm_register_foreign (void)
1358 {
1359 scm_c_register_extension ("libguile-" SCM_EFFECTIVE_VERSION,
1360 "scm_init_foreign",
1361 (scm_t_extension_init_func)scm_init_foreign,
1362 NULL);
1363 pointer_weak_refs = scm_c_make_weak_table (0, SCM_WEAK_TABLE_KIND_KEY);
1364 }
1365
1366 /*
1367 Local Variables:
1368 c-file-style: "gnu"
1369 End:
1370 */