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