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