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