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