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