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