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