1\input texinfo   @c -*-texinfo-*-
2@c %**start of header
3@setfilename libffi.info
4@settitle libffi
5@setchapternewpage off
6@c %**end of header
7
8@c Merge the standard indexes into a single one.
9@syncodeindex fn cp
10@syncodeindex vr cp
11@syncodeindex ky cp
12@syncodeindex pg cp
13@syncodeindex tp cp
14
15@include version.texi
16
17@copying
18
19This manual is for Libffi, a portable foreign-function interface
20library.
21
22Copyright @copyright{} 2008, 2010, 2011 Red Hat, Inc.
23
24@quotation
25Permission is granted to copy, distribute and/or modify this document
26under the terms of the GNU General Public License as published by the
27Free Software Foundation; either version 2, or (at your option) any
28later version.  A copy of the license is included in the
29section entitled ``GNU General Public License''.
30
31@end quotation
32@end copying
33
34@dircategory Development
35@direntry
36* libffi: (libffi).             Portable foreign-function interface library.
37@end direntry
38
39@titlepage
40@title Libffi
41@page
42@vskip 0pt plus 1filll
43@insertcopying
44@end titlepage
45
46
47@ifnottex
48@node Top
49@top libffi
50
51@insertcopying
52
53@menu
54* Introduction::                What is libffi?
55* Using libffi::                How to use libffi.
56* Missing Features::            Things libffi can't do.
57* Index::                       Index.
58@end menu
59
60@end ifnottex
61
62
63@node Introduction
64@chapter What is libffi?
65
66Compilers for high level languages generate code that follow certain
67conventions.  These conventions are necessary, in part, for separate
68compilation to work.  One such convention is the @dfn{calling
69convention}.  The calling convention is a set of assumptions made by
70the compiler about where function arguments will be found on entry to
71a function.  A calling convention also specifies where the return
72value for a function is found.  The calling convention is also
73sometimes called the @dfn{ABI} or @dfn{Application Binary Interface}.
74@cindex calling convention
75@cindex ABI
76@cindex Application Binary Interface
77
78Some programs may not know at the time of compilation what arguments
79are to be passed to a function.  For instance, an interpreter may be
80told at run-time about the number and types of arguments used to call
81a given function.  @samp{Libffi} can be used in such programs to
82provide a bridge from the interpreter program to compiled code.
83
84The @samp{libffi} library provides a portable, high level programming
85interface to various calling conventions.  This allows a programmer to
86call any function specified by a call interface description at run
87time.
88
89@acronym{FFI} stands for Foreign Function Interface.  A foreign
90function interface is the popular name for the interface that allows
91code written in one language to call code written in another language.
92The @samp{libffi} library really only provides the lowest, machine
93dependent layer of a fully featured foreign function interface.  A
94layer must exist above @samp{libffi} that handles type conversions for
95values passed between the two languages.
96@cindex FFI
97@cindex Foreign Function Interface
98
99
100@node Using libffi
101@chapter Using libffi
102
103@menu
104* The Basics::                  The basic libffi API.
105* Simple Example::              A simple example.
106* Types::                       libffi type descriptions.
107* Multiple ABIs::               Different passing styles on one platform.
108* The Closure API::             Writing a generic function.
109* Closure Example::             A closure example.
110* Thread Safety::               Thread safety.
111@end menu
112
113
114@node The Basics
115@section The Basics
116
117@samp{Libffi} assumes that you have a pointer to the function you wish
118to call and that you know the number and types of arguments to pass
119it, as well as the return type of the function.
120
121The first thing you must do is create an @code{ffi_cif} object that
122matches the signature of the function you wish to call.  This is a
123separate step because it is common to make multiple calls using a
124single @code{ffi_cif}.  The @dfn{cif} in @code{ffi_cif} stands for
125Call InterFace.  To prepare a call interface object, use the function
126@code{ffi_prep_cif}.
127@cindex cif
128
129@findex ffi_prep_cif
130@defun ffi_status ffi_prep_cif (ffi_cif *@var{cif}, ffi_abi @var{abi}, unsigned int @var{nargs}, ffi_type *@var{rtype}, ffi_type **@var{argtypes})
131This initializes @var{cif} according to the given parameters.
132
133@var{abi} is the ABI to use; normally @code{FFI_DEFAULT_ABI} is what
134you want.  @ref{Multiple ABIs} for more information.
135
136@var{nargs} is the number of arguments that this function accepts.
137
138@var{rtype} is a pointer to an @code{ffi_type} structure that
139describes the return type of the function.  @xref{Types}.
140
141@var{argtypes} is a vector of @code{ffi_type} pointers.
142@var{argtypes} must have @var{nargs} elements.  If @var{nargs} is 0,
143this argument is ignored.
144
145@code{ffi_prep_cif} returns a @code{libffi} status code, of type
146@code{ffi_status}.  This will be either @code{FFI_OK} if everything
147worked properly; @code{FFI_BAD_TYPEDEF} if one of the @code{ffi_type}
148objects is incorrect; or @code{FFI_BAD_ABI} if the @var{abi} parameter
149is invalid.
150@end defun
151
152If the function being called is variadic (varargs) then
153@code{ffi_prep_cif_var} must be used instead of @code{ffi_prep_cif}.
154
155@findex ffi_prep_cif_var
156@defun ffi_status ffi_prep_cif_var (ffi_cif *@var{cif}, ffi_abi @var{abi}, unsigned int @var{nfixedargs}, unsigned int @var{ntotalargs}, ffi_type *@var{rtype}, ffi_type **@var{argtypes})
157This initializes @var{cif} according to the given parameters for
158a call to a variadic function.  In general its operation is the
159same as for @code{ffi_prep_cif} except that:
160
161@var{nfixedargs} is the number of fixed arguments, prior to any
162variadic arguments.  It must be greater than zero.
163
164@var{ntotalargs} the total number of arguments, including variadic
165and fixed arguments.  @var{argtypes} must have this many elements.
166
167Note that, different cif's must be prepped for calls to the same
168function when different numbers of arguments are passed.
169
170Also note that a call to @code{ffi_prep_cif_var} with
171@var{nfixedargs}=@var{nototalargs} is NOT equivalent to a call to
172@code{ffi_prep_cif}.
173
174@end defun
175
176Note that the resulting @code{ffi_cif} holds pointers to all the
177@code{ffi_type} objects that were used during initialization.  You
178must ensure that these type objects have a lifetime at least as long
179as that of the @code{ffi_cif}.
180
181To call a function using an initialized @code{ffi_cif}, use the
182@code{ffi_call} function:
183
184@findex ffi_call
185@defun void ffi_call (ffi_cif *@var{cif}, void *@var{fn}, void *@var{rvalue}, void **@var{avalues})
186This calls the function @var{fn} according to the description given in
187@var{cif}.  @var{cif} must have already been prepared using
188@code{ffi_prep_cif}.
189
190@var{rvalue} is a pointer to a chunk of memory that will hold the
191result of the function call.  This must be large enough to hold the
192result, no smaller than the system register size (generally 32 or 64
193bits), and must be suitably aligned; it is the caller's responsibility
194to ensure this.  If @var{cif} declares that the function returns
195@code{void} (using @code{ffi_type_void}), then @var{rvalue} is
196ignored.
197
198In most situations, @samp{libffi} will handle promotion according to
199the ABI.  However, for historical reasons, there is a special case
200with return values that must be handled by your code.  In particular,
201for integral (not @code{struct}) types that are narrower than the
202system register size, the return value will be widened by
203@samp{libffi}.  @samp{libffi} provides a type, @code{ffi_arg}, that
204can be used as the return type.  For example, if the CIF was defined
205with a return type of @code{char}, @samp{libffi} will try to store a
206full @code{ffi_arg} into the return value.
207
208@var{avalues} is a vector of @code{void *} pointers that point to the
209memory locations holding the argument values for a call.  If @var{cif}
210declares that the function has no arguments (i.e., @var{nargs} was 0),
211then @var{avalues} is ignored.  Note that argument values may be
212modified by the callee (for instance, structs passed by value); the
213burden of copying pass-by-value arguments is placed on the caller.
214
215Note that while the return value must be register-sized, arguments
216should exactly match their declared type.  For example, if an argument
217is a @code{short}, then the entry in @var{avalues} should point to an
218object declared as @code{short}; but if the return type is
219@code{short}, then @var{rvalue} should point to an object declared as
220a larger type -- usually @code{ffi_arg}.
221@end defun
222
223
224@node Simple Example
225@section Simple Example
226
227Here is a trivial example that calls @code{puts} a few times.
228
229@example
230#include <stdio.h>
231#include <ffi.h>
232
233int main()
234@{
235  ffi_cif cif;
236  ffi_type *args[1];
237  void *values[1];
238  char *s;
239  ffi_arg rc;
240
241  /* Initialize the argument info vectors */
242  args[0] = &ffi_type_pointer;
243  values[0] = &s;
244
245  /* Initialize the cif */
246  if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1,
247		       &ffi_type_sint, args) == FFI_OK)
248    @{
249      s = "Hello World!";
250      ffi_call(&cif, puts, &rc, values);
251      /* rc now holds the result of the call to puts */
252
253      /* values holds a pointer to the function's arg, so to
254         call puts() again all we need to do is change the
255         value of s */
256      s = "This is cool!";
257      ffi_call(&cif, puts, &rc, values);
258    @}
259
260  return 0;
261@}
262@end example
263
264
265@node Types
266@section Types
267
268@menu
269* Primitive Types::             Built-in types.
270* Structures::                  Structure types.
271* Size and Alignment::          Size and alignment of types.
272* Arrays Unions Enums::         Arrays, unions, and enumerations.
273* Type Example::                Structure type example.
274* Complex::                     Complex types.
275* Complex Type Example::        Complex type example.
276@end menu
277
278@node Primitive Types
279@subsection Primitive Types
280
281@code{Libffi} provides a number of built-in type descriptors that can
282be used to describe argument and return types:
283
284@table @code
285@item ffi_type_void
286@tindex ffi_type_void
287The type @code{void}.  This cannot be used for argument types, only
288for return values.
289
290@item ffi_type_uint8
291@tindex ffi_type_uint8
292An unsigned, 8-bit integer type.
293
294@item ffi_type_sint8
295@tindex ffi_type_sint8
296A signed, 8-bit integer type.
297
298@item ffi_type_uint16
299@tindex ffi_type_uint16
300An unsigned, 16-bit integer type.
301
302@item ffi_type_sint16
303@tindex ffi_type_sint16
304A signed, 16-bit integer type.
305
306@item ffi_type_uint32
307@tindex ffi_type_uint32
308An unsigned, 32-bit integer type.
309
310@item ffi_type_sint32
311@tindex ffi_type_sint32
312A signed, 32-bit integer type.
313
314@item ffi_type_uint64
315@tindex ffi_type_uint64
316An unsigned, 64-bit integer type.
317
318@item ffi_type_sint64
319@tindex ffi_type_sint64
320A signed, 64-bit integer type.
321
322@item ffi_type_float
323@tindex ffi_type_float
324The C @code{float} type.
325
326@item ffi_type_double
327@tindex ffi_type_double
328The C @code{double} type.
329
330@item ffi_type_uchar
331@tindex ffi_type_uchar
332The C @code{unsigned char} type.
333
334@item ffi_type_schar
335@tindex ffi_type_schar
336The C @code{signed char} type.  (Note that there is not an exact
337equivalent to the C @code{char} type in @code{libffi}; ordinarily you
338should either use @code{ffi_type_schar} or @code{ffi_type_uchar}
339depending on whether @code{char} is signed.)
340
341@item ffi_type_ushort
342@tindex ffi_type_ushort
343The C @code{unsigned short} type.
344
345@item ffi_type_sshort
346@tindex ffi_type_sshort
347The C @code{short} type.
348
349@item ffi_type_uint
350@tindex ffi_type_uint
351The C @code{unsigned int} type.
352
353@item ffi_type_sint
354@tindex ffi_type_sint
355The C @code{int} type.
356
357@item ffi_type_ulong
358@tindex ffi_type_ulong
359The C @code{unsigned long} type.
360
361@item ffi_type_slong
362@tindex ffi_type_slong
363The C @code{long} type.
364
365@item ffi_type_longdouble
366@tindex ffi_type_longdouble
367On platforms that have a C @code{long double} type, this is defined.
368On other platforms, it is not.
369
370@item ffi_type_pointer
371@tindex ffi_type_pointer
372A generic @code{void *} pointer.  You should use this for all
373pointers, regardless of their real type.
374
375@item ffi_type_complex_float
376@tindex ffi_type_complex_float
377The C @code{_Complex float} type.
378
379@item ffi_type_complex_double
380@tindex ffi_type_complex_double
381The C @code{_Complex double} type.
382
383@item ffi_type_complex_longdouble
384@tindex ffi_type_complex_longdouble
385The C @code{_Complex long double} type.
386On platforms that have a C @code{long double} type, this is defined.
387On other platforms, it is not.
388@end table
389
390Each of these is of type @code{ffi_type}, so you must take the address
391when passing to @code{ffi_prep_cif}.
392
393
394@node Structures
395@subsection Structures
396
397@samp{libffi} is perfectly happy passing structures back and forth.
398You must first describe the structure to @samp{libffi} by creating a
399new @code{ffi_type} object for it.
400
401@tindex ffi_type
402@deftp {Data type} ffi_type
403The @code{ffi_type} has the following members:
404@table @code
405@item size_t size
406This is set by @code{libffi}; you should initialize it to zero.
407
408@item unsigned short alignment
409This is set by @code{libffi}; you should initialize it to zero.
410
411@item unsigned short type
412For a structure, this should be set to @code{FFI_TYPE_STRUCT}.
413
414@item ffi_type **elements
415This is a @samp{NULL}-terminated array of pointers to @code{ffi_type}
416objects.  There is one element per field of the struct.
417
418Note that @samp{libffi} has no special support for bit-fields.  You
419must manage these manually.
420@end table
421@end deftp
422
423The @code{size} and @code{alignment} fields will be filled in by
424@code{ffi_prep_cif} or @code{ffi_prep_cif_var}, as needed.
425
426@node Size and Alignment
427@subsection Size and Alignment
428
429@code{libffi} will set the @code{size} and @code{alignment} fields of
430an @code{ffi_type} object for you.  It does so using its knowledge of
431the ABI.
432
433You might expect that you can simply read these fields for a type that
434has been laid out by @code{libffi}.  However, there are some caveats.
435
436@itemize @bullet
437@item
438The size or alignment of some of the built-in types may vary depending
439on the chosen ABI.
440
441@item
442The size and alignment of a new structure type will not be set by
443@code{libffi} until it has been passed to @code{ffi_prep_cif} or
444@code{ffi_get_struct_offsets}.
445
446@item
447A structure type cannot be shared across ABIs.  Instead each ABI needs
448its own copy of the structure type.
449@end itemize
450
451So, before examining these fields, it is safest to pass the
452@code{ffi_type} object to @code{ffi_prep_cif} or
453@code{ffi_get_struct_offsets} first.  This function will do all the
454needed setup.
455
456@example
457ffi_type *desired_type;
458ffi_abi desired_abi;
459@dots{}
460ffi_cif cif;
461if (ffi_prep_cif (&cif, desired_abi, 0, desired_type, NULL) == FFI_OK)
462  @{
463    size_t size = desired_type->size;
464    unsigned short alignment = desired_type->alignment;
465  @}
466@end example
467
468@code{libffi} also provides a way to get the offsets of the members of
469a structure.
470
471@findex ffi_get_struct_offsets
472@defun ffi_status ffi_get_struct_offsets (ffi_abi abi, ffi_type *struct_type, size_t *offsets)
473Compute the offset of each element of the given structure type.
474@var{abi} is the ABI to use; this is needed because in some cases the
475layout depends on the ABI.
476
477@var{offsets} is an out parameter.  The caller is responsible for
478providing enough space for all the results to be written -- one
479element per element type in @var{struct_type}.  If @var{offsets} is
480@code{NULL}, then the type will be laid out but not otherwise
481modified.  This can be useful for accessing the type's size or layout,
482as mentioned above.
483
484This function returns @code{FFI_OK} on success; @code{FFI_BAD_ABI} if
485@var{abi} is invalid; or @code{FFI_BAD_TYPEDEF} if @var{struct_type}
486is invalid in some way.  Note that only @code{FFI_STRUCT} types are
487valid here.
488@end defun
489
490@node Arrays Unions Enums
491@subsection Arrays, Unions, and Enumerations
492
493@subsubsection Arrays
494
495@samp{libffi} does not have direct support for arrays or unions.
496However, they can be emulated using structures.
497
498To emulate an array, simply create an @code{ffi_type} using
499@code{FFI_TYPE_STRUCT} with as many members as there are elements in
500the array.
501
502@example
503ffi_type array_type;
504ffi_type **elements
505int i;
506
507elements = malloc ((n + 1) * sizeof (ffi_type *));
508for (i = 0; i < n; ++i)
509  elements[i] = array_element_type;
510elements[n] = NULL;
511
512array_type.size = array_type.alignment = 0;
513array_type.type = FFI_TYPE_STRUCT;
514array_type.elements = elements;
515@end example
516
517Note that arrays cannot be passed or returned by value in C --
518structure types created like this should only be used to refer to
519members of real @code{FFI_TYPE_STRUCT} objects.
520
521However, a phony array type like this will not cause any errors from
522@samp{libffi} if you use it as an argument or return type.  This may
523be confusing.
524
525@subsubsection Unions
526
527A union can also be emulated using @code{FFI_TYPE_STRUCT}.  In this
528case, however, you must make sure that the size and alignment match
529the real requirements of the union.
530
531One simple way to do this is to ensue that each element type is laid
532out.  Then, give the new structure type a single element; the size of
533the largest element; and the largest alignment seen as well.
534
535This example uses the @code{ffi_prep_cif} trick to ensure that each
536element type is laid out.
537
538@example
539ffi_abi desired_abi;
540ffi_type union_type;
541ffi_type **union_elements;
542
543int i;
544ffi_type element_types[2];
545
546element_types[1] = NULL;
547
548union_type.size = union_type.alignment = 0;
549union_type.type = FFI_TYPE_STRUCT;
550union_type.elements = element_types;
551
552for (i = 0; union_elements[i]; ++i)
553  @{
554    ffi_cif cif;
555    if (ffi_prep_cif (&cif, desired_abi, 0, union_elements[i], NULL) == FFI_OK)
556      @{
557        if (union_elements[i]->size > union_type.size)
558          @{
559            union_type.size = union_elements[i];
560            size = union_elements[i]->size;
561          @}
562        if (union_elements[i]->alignment > union_type.alignment)
563          union_type.alignment = union_elements[i]->alignment;
564      @}
565  @}
566@end example
567
568@subsubsection Enumerations
569
570@code{libffi} does not have any special support for C @code{enum}s.
571Although any given @code{enum} is implemented using a specific
572underlying integral type, exactly which type will be used cannot be
573determined by @code{libffi} -- it may depend on the values in the
574enumeration or on compiler flags such as @option{-fshort-enums}.
575@xref{Structures unions enumerations and bit-fields implementation, , , gcc},
576for more information about how GCC handles enumerations.
577
578@node Type Example
579@subsection Type Example
580
581The following example initializes a @code{ffi_type} object
582representing the @code{tm} struct from Linux's @file{time.h}.
583
584Here is how the struct is defined:
585
586@example
587struct tm @{
588    int tm_sec;
589    int tm_min;
590    int tm_hour;
591    int tm_mday;
592    int tm_mon;
593    int tm_year;
594    int tm_wday;
595    int tm_yday;
596    int tm_isdst;
597    /* Those are for future use. */
598    long int __tm_gmtoff__;
599    __const char *__tm_zone__;
600@};
601@end example
602
603Here is the corresponding code to describe this struct to
604@code{libffi}:
605
606@example
607    @{
608      ffi_type tm_type;
609      ffi_type *tm_type_elements[12];
610      int i;
611
612      tm_type.size = tm_type.alignment = 0;
613      tm_type.type = FFI_TYPE_STRUCT;
614      tm_type.elements = &tm_type_elements;
615
616      for (i = 0; i < 9; i++)
617          tm_type_elements[i] = &ffi_type_sint;
618
619      tm_type_elements[9] = &ffi_type_slong;
620      tm_type_elements[10] = &ffi_type_pointer;
621      tm_type_elements[11] = NULL;
622
623      /* tm_type can now be used to represent tm argument types and
624	 return types for ffi_prep_cif() */
625    @}
626@end example
627
628@node Complex
629@subsection Complex Types
630
631@samp{libffi} supports the complex types defined by the C99
632standard (@code{_Complex float}, @code{_Complex double} and
633@code{_Complex long double} with the built-in type descriptors
634@code{ffi_type_complex_float}, @code{ffi_type_complex_double} and
635@code{ffi_type_complex_longdouble}.
636
637Custom complex types like @code{_Complex int} can also be used.
638An @code{ffi_type} object has to be defined to describe the
639complex type to @samp{libffi}.
640
641@tindex ffi_type
642@deftp {Data type} ffi_type
643@table @code
644@item size_t size
645This must be manually set to the size of the complex type.
646
647@item unsigned short alignment
648This must be manually set to the alignment of the complex type.
649
650@item unsigned short type
651For a complex type, this must be set to @code{FFI_TYPE_COMPLEX}.
652
653@item ffi_type **elements
654
655This is a @samp{NULL}-terminated array of pointers to
656@code{ffi_type} objects.  The first element is set to the
657@code{ffi_type} of the complex's base type.  The second element
658must be set to @code{NULL}.
659@end table
660@end deftp
661
662The section @ref{Complex Type Example} shows a way to determine
663the @code{size} and @code{alignment} members in a platform
664independent way.
665
666For platforms that have no complex support in @code{libffi} yet,
667the functions @code{ffi_prep_cif} and @code{ffi_prep_args} abort
668the program if they encounter a complex type.
669
670@node Complex Type Example
671@subsection Complex Type Example
672
673This example demonstrates how to use complex types:
674
675@example
676#include <stdio.h>
677#include <ffi.h>
678#include <complex.h>
679
680void complex_fn(_Complex float cf,
681                _Complex double cd,
682                _Complex long double cld)
683@{
684  printf("cf=%f+%fi\ncd=%f+%fi\ncld=%f+%fi\n",
685         (float)creal (cf), (float)cimag (cf),
686         (float)creal (cd), (float)cimag (cd),
687         (float)creal (cld), (float)cimag (cld));
688@}
689
690int main()
691@{
692  ffi_cif cif;
693  ffi_type *args[3];
694  void *values[3];
695  _Complex float cf;
696  _Complex double cd;
697  _Complex long double cld;
698
699  /* Initialize the argument info vectors */
700  args[0] = &ffi_type_complex_float;
701  args[1] = &ffi_type_complex_double;
702  args[2] = &ffi_type_complex_longdouble;
703  values[0] = &cf;
704  values[1] = &cd;
705  values[2] = &cld;
706
707  /* Initialize the cif */
708  if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 3,
709                   &ffi_type_void, args) == FFI_OK)
710    @{
711      cf = 1.0 + 20.0 * I;
712      cd = 300.0 + 4000.0 * I;
713      cld = 50000.0 + 600000.0 * I;
714      /* Call the function */
715      ffi_call(&cif, (void (*)(void))complex_fn, 0, values);
716    @}
717
718  return 0;
719@}
720@end example
721
722This is an example for defining a custom complex type descriptor
723for compilers that support them:
724
725@example
726/*
727 * This macro can be used to define new complex type descriptors
728 * in a platform independent way.
729 *
730 * name: Name of the new descriptor is ffi_type_complex_<name>.
731 * type: The C base type of the complex type.
732 */
733#define FFI_COMPLEX_TYPEDEF(name, type, ffitype)             \
734  static ffi_type *ffi_elements_complex_##name [2] = @{      \
735    (ffi_type *)(&ffitype), NULL                             \
736  @};                                                        \
737  struct struct_align_complex_##name @{                      \
738    char c;                                                  \
739    _Complex type x;                                         \
740  @};                                                        \
741  ffi_type ffi_type_complex_##name = @{                      \
742    sizeof(_Complex type),                                   \
743    offsetof(struct struct_align_complex_##name, x),         \
744    FFI_TYPE_COMPLEX,                                        \
745    (ffi_type **)ffi_elements_complex_##name                 \
746  @}
747
748/* Define new complex type descriptors using the macro: */
749/* ffi_type_complex_sint */
750FFI_COMPLEX_TYPEDEF(sint, int, ffi_type_sint);
751/* ffi_type_complex_uchar */
752FFI_COMPLEX_TYPEDEF(uchar, unsigned char, ffi_type_uint8);
753@end example
754
755The new type descriptors can then be used like one of the built-in
756type descriptors in the previous example.
757
758@node Multiple ABIs
759@section Multiple ABIs
760
761A given platform may provide multiple different ABIs at once.  For
762instance, the x86 platform has both @samp{stdcall} and @samp{fastcall}
763functions.
764
765@code{libffi} provides some support for this.  However, this is
766necessarily platform-specific.
767
768@c FIXME: document the platforms
769
770@node The Closure API
771@section The Closure API
772
773@code{libffi} also provides a way to write a generic function -- a
774function that can accept and decode any combination of arguments.
775This can be useful when writing an interpreter, or to provide wrappers
776for arbitrary functions.
777
778This facility is called the @dfn{closure API}.  Closures are not
779supported on all platforms; you can check the @code{FFI_CLOSURES}
780define to determine whether they are supported on the current
781platform.
782@cindex closures
783@cindex closure API
784@findex FFI_CLOSURES
785
786Because closures work by assembling a tiny function at runtime, they
787require special allocation on platforms that have a non-executable
788heap.  Memory management for closures is handled by a pair of
789functions:
790
791@findex ffi_closure_alloc
792@defun void *ffi_closure_alloc (size_t @var{size}, void **@var{code})
793Allocate a chunk of memory holding @var{size} bytes.  This returns a
794pointer to the writable address, and sets *@var{code} to the
795corresponding executable address.
796
797@var{size} should be sufficient to hold a @code{ffi_closure} object.
798@end defun
799
800@findex ffi_closure_free
801@defun void ffi_closure_free (void *@var{writable})
802Free memory allocated using @code{ffi_closure_alloc}.  The argument is
803the writable address that was returned.
804@end defun
805
806
807Once you have allocated the memory for a closure, you must construct a
808@code{ffi_cif} describing the function call.  Finally you can prepare
809the closure function:
810
811@findex ffi_prep_closure_loc
812@defun ffi_status ffi_prep_closure_loc (ffi_closure *@var{closure}, ffi_cif *@var{cif}, void (*@var{fun}) (ffi_cif *@var{cif}, void *@var{ret}, void **@var{args}, void *@var{user_data}), void *@var{user_data}, void *@var{codeloc})
813Prepare a closure function.  The arguments to
814@code{ffi_prep_closure_loc} are:
815
816@table @var
817@item closure
818The address of a @code{ffi_closure} object; this is the writable
819address returned by @code{ffi_closure_alloc}.
820
821@item cif
822The @code{ffi_cif} describing the function parameters.  Note that this
823object, and the types to which it refers, must be kept alive until the
824closure itself is freed.
825
826@item user_data
827An arbitrary datum that is passed, uninterpreted, to your closure
828function.
829
830@item codeloc
831The executable address returned by @code{ffi_closure_alloc}.
832
833@item fun
834The function which will be called when the closure is invoked.  It is
835called with the arguments:
836
837@table @var
838@item cif
839The @code{ffi_cif} passed to @code{ffi_prep_closure_loc}.
840
841@item ret
842A pointer to the memory used for the function's return value.
843
844If the function is declared as returning @code{void}, then this value
845is garbage and should not be used.
846
847Otherwise, @var{fun} must fill the object to which this points,
848following the same special promotion behavior as @code{ffi_call}.
849That is, in most cases, @var{ret} points to an object of exactly the
850size of the type specified when @var{cif} was constructed.  However,
851integral types narrower than the system register size are widened.  In
852these cases your program may assume that @var{ret} points to an
853@code{ffi_arg} object.
854
855@item args
856A vector of pointers to memory holding the arguments to the function.
857
858@item user_data
859The same @var{user_data} that was passed to
860@code{ffi_prep_closure_loc}.
861@end table
862@end table
863
864@code{ffi_prep_closure_loc} will return @code{FFI_OK} if everything
865went ok, and one of the other @code{ffi_status} values on error.
866
867After calling @code{ffi_prep_closure_loc}, you can cast @var{codeloc}
868to the appropriate pointer-to-function type.
869@end defun
870
871You may see old code referring to @code{ffi_prep_closure}.  This
872function is deprecated, as it cannot handle the need for separate
873writable and executable addresses.
874
875@node Closure Example
876@section Closure Example
877
878A trivial example that creates a new @code{puts} by binding
879@code{fputs} with @code{stdout}.
880
881@example
882#include <stdio.h>
883#include <ffi.h>
884
885/* Acts like puts with the file given at time of enclosure. */
886void puts_binding(ffi_cif *cif, void *ret, void* args[],
887                  void *stream)
888@{
889  *(ffi_arg *)ret = fputs(*(char **)args[0], (FILE *)stream);
890@}
891
892typedef int (*puts_t)(char *);
893
894int main()
895@{
896  ffi_cif cif;
897  ffi_type *args[1];
898  ffi_closure *closure;
899
900  void *bound_puts;
901  int rc;
902
903  /* Allocate closure and bound_puts */
904  closure = ffi_closure_alloc(sizeof(ffi_closure), &bound_puts);
905
906  if (closure)
907    @{
908      /* Initialize the argument info vectors */
909      args[0] = &ffi_type_pointer;
910
911      /* Initialize the cif */
912      if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1,
913                       &ffi_type_sint, args) == FFI_OK)
914        @{
915          /* Initialize the closure, setting stream to stdout */
916          if (ffi_prep_closure_loc(closure, &cif, puts_binding,
917                                   stdout, bound_puts) == FFI_OK)
918            @{
919              rc = ((puts_t)bound_puts)("Hello World!");
920              /* rc now holds the result of the call to fputs */
921            @}
922        @}
923    @}
924
925  /* Deallocate both closure, and bound_puts */
926  ffi_closure_free(closure);
927
928  return 0;
929@}
930
931@end example
932
933@node Thread Safety
934@section Thread Safety
935
936@code{libffi} is not completely thread-safe.  However, many parts are,
937and if you follow some simple rules, you can use it safely in a
938multi-threaded program.
939
940@itemize @bullet
941@item
942@code{ffi_prep_cif} may modify the @code{ffi_type} objects passed to
943it.  It is best to ensure that only a single thread prepares a given
944@code{ffi_cif} at a time.
945
946@item
947On some platforms, @code{ffi_prep_cif} may modify the size and
948alignment of some types, depending on the chosen ABI.  On these
949platforms, if you switch between ABIs, you must ensure that there is
950only one call to @code{ffi_prep_cif} at a time.
951
952Currently the only affected platform is PowerPC and the only affected
953type is @code{long double}.
954@end itemize
955
956@node Missing Features
957@chapter Missing Features
958
959@code{libffi} is missing a few features.  We welcome patches to add
960support for these.
961
962@itemize @bullet
963@item
964Variadic closures.
965
966@item
967There is no support for bit fields in structures.
968
969@item
970The ``raw'' API is undocumented.
971@c anything else?
972
973@item
974The Go API is undocumented.
975@end itemize
976
977Note that variadic support is very new and tested on a relatively
978small number of platforms.
979
980@node Index
981@unnumbered Index
982
983@printindex cp
984
985@bye
986