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