Debian Codegraph @

doc/libffi.texi

raw
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--2025 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. @code{libffi} can be used in such programs to
95 provide a bridge from the interpreter program to compiled code.
96
97 The @code{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 @code{libffi} library really only provides the lowest, machine
106 dependent layer of a fully featured foreign function interface. A
107 layer must exist above @code{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 @code{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, @code{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 @code{libffi}. @code{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}, @code{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.
230
231 Note that while the return value must be register-sized, arguments
232 should exactly match their declared type. For example, if an argument
233 is a @code{short}, then the entry in @var{avalues} should point to an
234 object declared as @code{short}; but if the return type is
235 @code{short}, then @var{rvalue} should point to an object declared as
236 a larger type -- usually @code{ffi_arg}.
237 @end defun
238
239 @findex ffi_get_version
240 @defun {const char *} ffi_get_version (void)
241 Returns the library version as a string. This string is also
242 available at build time as the macro @code{FFI_VERSION_STRING}.
243 @end defun
244
245 @findex ffi_get_version_number
246 @defun {unsigned long} ffi_get_version_number (void)
247 Returns the library version as an unsigned long value where
248 version ``x.y.z'' is represented as the number x*10000+y*100+z.
249 This number is also available at build time as the macro
250 @code{FFI_VERSION_NUMBER}.
251 @end defun
252
253 @findex ffi_get_default_abi
254 @defun {unsigned int} ffi_get_default_abi (void)
255 Return the value of @code{FFI_DEFAULT_ABI}.
256 @end defun
257
258 @findex ffi_get_closure_size
259 @defun {size_t} ffi_get_closure_size (void)
260 Return @code{sizeof(ffi_closure)}.
261 @end defun
262
263 @node Simple Example
264 @section Simple Example
265
266 Here is a trivial example that calls @code{puts} a few times.
267
268 @example
269 #include <stdio.h>
270 #include <ffi.h>
271
272 int main()
273 @{
274 ffi_cif cif;
275 ffi_type *args[1];
276 void *values[1];
277 char *s;
278 ffi_arg rc;
279
280 /* Initialize the argument info vectors */
281 args[0] = &ffi_type_pointer;
282 values[0] = &s;
283
284 /* Initialize the cif */
285 if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1,
286 &ffi_type_sint, args) == FFI_OK)
287 @{
288 s = "Hello World!";
289 ffi_call(&cif, (void(*)())puts, &rc, values);
290 /* rc now holds the result of the call to puts */
291
292 /* values holds a pointer to the function's arg, so to
293 call puts() again all we need to do is change the
294 value of s */
295 s = "This is cool!";
296 ffi_call(&cif, (void(*)())puts, &rc, values);
297 @}
298
299 return 0;
300 @}
301 @end example
302
303
304 @node Types
305 @section Types
306
307 @menu
308 * Primitive Types:: Built-in types.
309 * Structures:: Structure types.
310 * Size and Alignment:: Size and alignment of types.
311 * Arrays Unions Enums:: Arrays, unions, and enumerations.
312 * Type Example:: Structure type example.
313 * Complex:: Complex types.
314 * Complex Type Example:: Complex type example.
315 @end menu
316
317 @node Primitive Types
318 @subsection Primitive Types
319
320 @code{Libffi} provides a number of built-in type descriptors that can
321 be used to describe argument and return types:
322
323 @table @code
324 @item ffi_type_void
325 @tindex ffi_type_void
326 The type @code{void}. This cannot be used for argument types, only
327 for return values.
328
329 @item ffi_type_uint8
330 @tindex ffi_type_uint8
331 An unsigned, 8-bit integer type.
332
333 @item ffi_type_sint8
334 @tindex ffi_type_sint8
335 A signed, 8-bit integer type.
336
337 @item ffi_type_uint16
338 @tindex ffi_type_uint16
339 An unsigned, 16-bit integer type.
340
341 @item ffi_type_sint16
342 @tindex ffi_type_sint16
343 A signed, 16-bit integer type.
344
345 @item ffi_type_uint32
346 @tindex ffi_type_uint32
347 An unsigned, 32-bit integer type.
348
349 @item ffi_type_sint32
350 @tindex ffi_type_sint32
351 A signed, 32-bit integer type.
352
353 @item ffi_type_uint64
354 @tindex ffi_type_uint64
355 An unsigned, 64-bit integer type.
356
357 @item ffi_type_sint64
358 @tindex ffi_type_sint64
359 A signed, 64-bit integer type.
360
361 @item ffi_type_float
362 @tindex ffi_type_float
363 The C @code{float} type.
364
365 @item ffi_type_double
366 @tindex ffi_type_double
367 The C @code{double} type.
368
369 @item ffi_type_uchar
370 @tindex ffi_type_uchar
371 The C @code{unsigned char} type.
372
373 @item ffi_type_schar
374 @tindex ffi_type_schar
375 The C @code{signed char} type. (Note that there is not an exact
376 equivalent to the C @code{char} type in @code{libffi}; ordinarily you
377 should either use @code{ffi_type_schar} or @code{ffi_type_uchar}
378 depending on whether @code{char} is signed.)
379
380 @item ffi_type_ushort
381 @tindex ffi_type_ushort
382 The C @code{unsigned short} type.
383
384 @item ffi_type_sshort
385 @tindex ffi_type_sshort
386 The C @code{short} type.
387
388 @item ffi_type_uint
389 @tindex ffi_type_uint
390 The C @code{unsigned int} type.
391
392 @item ffi_type_sint
393 @tindex ffi_type_sint
394 The C @code{int} type.
395
396 @item ffi_type_ulong
397 @tindex ffi_type_ulong
398 The C @code{unsigned long} type.
399
400 @item ffi_type_slong
401 @tindex ffi_type_slong
402 The C @code{long} type.
403
404 @item ffi_type_longdouble
405 @tindex ffi_type_longdouble
406 On platforms that have a C @code{long double} type, this is defined.
407 On other platforms, it is not.
408
409 @item ffi_type_pointer
410 @tindex ffi_type_pointer
411 A generic @code{void *} pointer. You should use this for all
412 pointers, regardless of their real type.
413
414 @item ffi_type_complex_float
415 @tindex ffi_type_complex_float
416 The C @code{_Complex float} type.
417
418 @item ffi_type_complex_double
419 @tindex ffi_type_complex_double
420 The C @code{_Complex double} type.
421
422 @item ffi_type_complex_longdouble
423 @tindex ffi_type_complex_longdouble
424 The C @code{_Complex long double} type.
425 On platforms that have a C @code{long double} type, this is defined.
426 On other platforms, it is not.
427 @end table
428
429 Each of these is of type @code{ffi_type}, so you must take the address
430 when passing to @code{ffi_prep_cif}.
431
432
433 @node Structures
434 @subsection Structures
435
436 @code{libffi} is perfectly happy passing structures back and forth.
437 You must first describe the structure to @code{libffi} by creating a
438 new @code{ffi_type} object for it.
439
440 @tindex ffi_type
441 @deftp {Data type} ffi_type
442 The @code{ffi_type} has the following members:
443 @table @code
444 @item size_t size
445 This is set by @code{libffi}; you should initialize it to zero.
446
447 @item unsigned short alignment
448 This is set by @code{libffi}; you should initialize it to zero.
449
450 @item unsigned short type
451 For a structure, this should be set to @code{FFI_TYPE_STRUCT}.
452
453 @item ffi_type **elements
454 This is a @samp{NULL}-terminated array of pointers to @code{ffi_type}
455 objects. There is one element per field of the struct.
456
457 Note that @code{libffi} has no special support for bit-fields. You
458 must manage these manually.
459 @end table
460 @end deftp
461
462 The @code{size} and @code{alignment} fields will be filled in by
463 @code{ffi_prep_cif} or @code{ffi_prep_cif_var}, as needed.
464
465 @node Size and Alignment
466 @subsection Size and Alignment
467
468 @code{libffi} will set the @code{size} and @code{alignment} fields of
469 an @code{ffi_type} object for you. It does so using its knowledge of
470 the ABI.
471
472 You might expect that you can simply read these fields for a type that
473 has been laid out by @code{libffi}. However, there are some caveats.
474
475 @itemize @bullet
476 @item
477 The size or alignment of some of the built-in types may vary depending
478 on the chosen ABI.
479
480 @item
481 The size and alignment of a new structure type will not be set by
482 @code{libffi} until it has been passed to @code{ffi_prep_cif} or
483 @code{ffi_get_struct_offsets}.
484
485 @item
486 A structure type cannot be shared across ABIs. Instead each ABI needs
487 its own copy of the structure type.
488 @end itemize
489
490 So, before examining these fields, it is safest to pass the
491 @code{ffi_type} object to @code{ffi_prep_cif} or
492 @code{ffi_get_struct_offsets} first. This function will do all the
493 needed setup.
494
495 @example
496 ffi_type *desired_type;
497 ffi_abi desired_abi;
498 @dots{}
499 ffi_cif cif;
500 if (ffi_prep_cif (&cif, desired_abi, 0, desired_type, NULL) == FFI_OK)
501 @{
502 size_t size = desired_type->size;
503 unsigned short alignment = desired_type->alignment;
504 @}
505 @end example
506
507 @code{libffi} also provides a way to get the offsets of the members of
508 a structure.
509
510 @findex ffi_get_struct_offsets
511 @defun ffi_status ffi_get_struct_offsets (ffi_abi abi, ffi_type *struct_type, size_t *offsets)
512 Compute the offset of each element of the given structure type.
513 @var{abi} is the ABI to use; this is needed because in some cases the
514 layout depends on the ABI.
515
516 @var{offsets} is an out parameter. The caller is responsible for
517 providing enough space for all the results to be written -- one
518 element per element type in @var{struct_type}. If @var{offsets} is
519 @code{NULL}, then the type will be laid out but not otherwise
520 modified. This can be useful for accessing the type's size or layout,
521 as mentioned above.
522
523 This function returns @code{FFI_OK} on success; @code{FFI_BAD_ABI} if
524 @var{abi} is invalid; or @code{FFI_BAD_TYPEDEF} if @var{struct_type}
525 is invalid in some way. Note that only @code{FFI_STRUCT} types are
526 valid here.
527 @end defun
528
529 @node Arrays Unions Enums
530 @subsection Arrays, Unions, and Enumerations
531
532 @subsubsection Arrays
533
534 @code{libffi} does not have direct support for arrays or unions.
535 However, they can be emulated using structures.
536
537 To emulate an array, simply create an @code{ffi_type} using
538 @code{FFI_TYPE_STRUCT} with as many members as there are elements in
539 the array.
540
541 @example
542 ffi_type array_type;
543 ffi_type **elements
544 int i;
545
546 elements = malloc ((n + 1) * sizeof (ffi_type *));
547 for (i = 0; i < n; ++i)
548 elements[i] = array_element_type;
549 elements[n] = NULL;
550
551 array_type.size = array_type.alignment = 0;
552 array_type.type = FFI_TYPE_STRUCT;
553 array_type.elements = elements;
554 @end example
555
556 Note that arrays cannot be passed or returned by value in C --
557 structure types created like this should only be used to refer to
558 members of real @code{FFI_TYPE_STRUCT} objects.
559
560 However, a phony array type like this will not cause any errors from
561 @code{libffi} if you use it as an argument or return type. This may
562 be confusing.
563
564 @subsubsection Unions
565
566 A union can also be emulated using @code{FFI_TYPE_STRUCT}. In this
567 case, however, you must make sure that the size and alignment match
568 the real requirements of the union.
569
570 One simple way to do this is to ensue that each element type is laid
571 out. Then, give the new structure type a single element; the size of
572 the largest element; and the largest alignment seen as well.
573
574 This example uses the @code{ffi_prep_cif} trick to ensure that each
575 element type is laid out.
576
577 @example
578 ffi_abi desired_abi;
579 ffi_type union_type;
580 ffi_type **union_elements;
581
582 int i;
583 ffi_type element_types[2];
584
585 element_types[1] = NULL;
586
587 union_type.size = union_type.alignment = 0;
588 union_type.type = FFI_TYPE_STRUCT;
589 union_type.elements = element_types;
590
591 for (i = 0; union_elements[i]; ++i)
592 @{
593 ffi_cif cif;
594 if (ffi_prep_cif (&cif, desired_abi, 0, union_elements[i], NULL) == FFI_OK)
595 @{
596 if (union_elements[i]->size > union_type.size)
597 @{
598 union_type.size = union_elements[i];
599 size = union_elements[i]->size;
600 @}
601 if (union_elements[i]->alignment > union_type.alignment)
602 union_type.alignment = union_elements[i]->alignment;
603 @}
604 @}
605 @end example
606
607 @subsubsection Enumerations
608
609 @code{libffi} does not have any special support for C @code{enum}s.
610 Although any given @code{enum} is implemented using a specific
611 underlying integral type, exactly which type will be used cannot be
612 determined by @code{libffi} -- it may depend on the values in the
613 enumeration or on compiler flags such as @option{-fshort-enums}.
614 @xref{Structures unions enumerations and bit-fields implementation, , , gcc},
615 for more information about how GCC handles enumerations.
616
617 @node Type Example
618 @subsection Type Example
619
620 The following example initializes a @code{ffi_type} object
621 representing the @code{tm} struct from Linux's @file{time.h}.
622
623 Here is how the struct is defined:
624
625 @example
626 struct tm @{
627 int tm_sec;
628 int tm_min;
629 int tm_hour;
630 int tm_mday;
631 int tm_mon;
632 int tm_year;
633 int tm_wday;
634 int tm_yday;
635 int tm_isdst;
636 /* Those are for future use. */
637 long int __tm_gmtoff__;
638 __const char *__tm_zone__;
639 @};
640 @end example
641
642 Here is the corresponding code to describe this struct to
643 @code{libffi}:
644
645 @example
646 @{
647 ffi_type tm_type;
648 ffi_type *tm_type_elements[12];
649 int i;
650
651 tm_type.size = tm_type.alignment = 0;
652 tm_type.type = FFI_TYPE_STRUCT;
653 tm_type.elements = tm_type_elements;
654
655 for (i = 0; i < 9; i++)
656 tm_type_elements[i] = &ffi_type_sint;
657
658 tm_type_elements[9] = &ffi_type_slong;
659 tm_type_elements[10] = &ffi_type_pointer;
660 tm_type_elements[11] = NULL;
661
662 /* tm_type can now be used to represent tm argument types and
663 return types for ffi_prep_cif() */
664 @}
665 @end example
666
667 @node Complex
668 @subsection Complex Types
669
670 @code{libffi} supports the complex types defined by the C99
671 standard (@code{_Complex float}, @code{_Complex double} and
672 @code{_Complex long double} with the built-in type descriptors
673 @code{ffi_type_complex_float}, @code{ffi_type_complex_double} and
674 @code{ffi_type_complex_longdouble}.
675
676 Custom complex types like @code{_Complex int} can also be used.
677 An @code{ffi_type} object has to be defined to describe the
678 complex type to @code{libffi}.
679
680 @tindex ffi_type
681 @deftp {Data type} ffi_type
682 @table @code
683 @item size_t size
684 This must be manually set to the size of the complex type.
685
686 @item unsigned short alignment
687 This must be manually set to the alignment of the complex type.
688
689 @item unsigned short type
690 For a complex type, this must be set to @code{FFI_TYPE_COMPLEX}.
691
692 @item ffi_type **elements
693
694 This is a @samp{NULL}-terminated array of pointers to
695 @code{ffi_type} objects. The first element is set to the
696 @code{ffi_type} of the complex's base type. The second element
697 must be set to @code{NULL}.
698 @end table
699 @end deftp
700
701 The section @ref{Complex Type Example} shows a way to determine
702 the @code{size} and @code{alignment} members in a platform
703 independent way.
704
705 For platforms that have no complex support in @code{libffi} yet,
706 the functions @code{ffi_prep_cif} and @code{ffi_prep_args} abort
707 the program if they encounter a complex type.
708
709 @node Complex Type Example
710 @subsection Complex Type Example
711
712 This example demonstrates how to use complex types:
713
714 @example
715 #include <stdio.h>
716 #include <ffi.h>
717 #include <complex.h>
718
719 void complex_fn(_Complex float cf,
720 _Complex double cd,
721 _Complex long double cld)
722 @{
723 printf("cf=%f+%fi\ncd=%f+%fi\ncld=%f+%fi\n",
724 (float)creal (cf), (float)cimag (cf),
725 (float)creal (cd), (float)cimag (cd),
726 (float)creal (cld), (float)cimag (cld));
727 @}
728
729 int main()
730 @{
731 ffi_cif cif;
732 ffi_type *args[3];
733 void *values[3];
734 _Complex float cf;
735 _Complex double cd;
736 _Complex long double cld;
737
738 /* Initialize the argument info vectors */
739 args[0] = &ffi_type_complex_float;
740 args[1] = &ffi_type_complex_double;
741 args[2] = &ffi_type_complex_longdouble;
742 values[0] = &cf;
743 values[1] = &cd;
744 values[2] = &cld;
745
746 /* Initialize the cif */
747 if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 3,
748 &ffi_type_void, args) == FFI_OK)
749 @{
750 cf = 1.0 + 20.0 * I;
751 cd = 300.0 + 4000.0 * I;
752 cld = 50000.0 + 600000.0 * I;
753 /* Call the function */
754 ffi_call(&cif, (void (*)(void))complex_fn, 0, values);
755 @}
756
757 return 0;
758 @}
759 @end example
760
761 This is an example for defining a custom complex type descriptor
762 for compilers that support them:
763
764 @example
765 /*
766 * This macro can be used to define new complex type descriptors
767 * in a platform independent way.
768 *
769 * name: Name of the new descriptor is ffi_type_complex_<name>.
770 * type: The C base type of the complex type.
771 */
772 #define FFI_COMPLEX_TYPEDEF(name, type, ffitype) \
773 static ffi_type *ffi_elements_complex_##name [2] = @{ \
774 (ffi_type *)(&ffitype), NULL \
775 @}; \
776 struct struct_align_complex_##name @{ \
777 char c; \
778 _Complex type x; \
779 @}; \
780 ffi_type ffi_type_complex_##name = @{ \
781 sizeof(_Complex type), \
782 offsetof(struct struct_align_complex_##name, x), \
783 FFI_TYPE_COMPLEX, \
784 (ffi_type **)ffi_elements_complex_##name \
785 @}
786
787 /* Define new complex type descriptors using the macro: */
788 /* ffi_type_complex_sint */
789 FFI_COMPLEX_TYPEDEF(sint, int, ffi_type_sint);
790 /* ffi_type_complex_uchar */
791 FFI_COMPLEX_TYPEDEF(uchar, unsigned char, ffi_type_uint8);
792 @end example
793
794 The new type descriptors can then be used like one of the built-in
795 type descriptors in the previous example.
796
797 @node Multiple ABIs
798 @section Multiple ABIs
799
800 A given platform may provide multiple different ABIs at once. For
801 instance, the x86 platform has both @samp{stdcall} and @samp{fastcall}
802 functions.
803
804 @code{libffi} provides some support for this. However, this is
805 necessarily platform-specific.
806
807 @c FIXME: document the platforms
808
809 @node The Closure API
810 @section The Closure API
811
812 @code{libffi} also provides a way to write a generic function -- a
813 function that can accept and decode any combination of arguments.
814 This can be useful when writing an interpreter, or to provide wrappers
815 for arbitrary functions.
816
817 This facility is called the @dfn{closure API}. Closures are not
818 supported on all platforms; you can check the @code{FFI_CLOSURES}
819 define to determine whether they are supported on the current
820 platform.
821 @cindex closures
822 @cindex closure API
823 @findex FFI_CLOSURES
824
825 Because closures work by assembling a tiny function at runtime, they
826 require special allocation on platforms that have a non-executable
827 heap. Memory management for closures is handled by a pair of
828 functions:
829
830 @findex ffi_closure_alloc
831 @defun void *ffi_closure_alloc (size_t @var{size}, void **@var{code})
832 Allocate a chunk of memory holding @var{size} bytes. This returns a
833 pointer to the writable address, and sets *@var{code} to the
834 corresponding executable address.
835
836 @var{size} should be sufficient to hold a @code{ffi_closure} object.
837 @end defun
838
839 @findex ffi_closure_free
840 @defun void ffi_closure_free (void *@var{writable})
841 Free memory allocated using @code{ffi_closure_alloc}. The argument is
842 the writable address that was returned.
843 @end defun
844
845 Once you have allocated the memory for a closure, you must construct a
846 @code{ffi_cif} describing the function call. Finally you can prepare
847 the closure function:
848
849 @findex ffi_prep_closure_loc
850 @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})
851 Prepare a closure function. The arguments to
852 @code{ffi_prep_closure_loc} are:
853
854 @table @var
855 @item closure
856 The address of a @code{ffi_closure} object; this is the writable
857 address returned by @code{ffi_closure_alloc}.
858
859 @item cif
860 The @code{ffi_cif} describing the function parameters. Note that this
861 object, and the types to which it refers, must be kept alive until the
862 closure itself is freed.
863
864 @item user_data
865 An arbitrary datum that is passed, uninterpreted, to your closure
866 function.
867
868 @item codeloc
869 The executable address returned by @code{ffi_closure_alloc}.
870
871 @item fun
872 The function which will be called when the closure is invoked. It is
873 called with the arguments:
874
875 @table @var
876 @item cif
877 The @code{ffi_cif} passed to @code{ffi_prep_closure_loc}.
878
879 @item ret
880 A pointer to the memory used for the function's return value.
881
882 If the function is declared as returning @code{void}, then this value
883 is garbage and should not be used.
884
885 Otherwise, @var{fun} must fill the object to which this points,
886 following the same special promotion behavior as @code{ffi_call}.
887 That is, in most cases, @var{ret} points to an object of exactly the
888 size of the type specified when @var{cif} was constructed. However,
889 integral types narrower than the system register size are widened. In
890 these cases your program may assume that @var{ret} points to an
891 @code{ffi_arg} object.
892
893 @item args
894 A vector of pointers to memory holding the arguments to the function.
895
896 @item user_data
897 The same @var{user_data} that was passed to
898 @code{ffi_prep_closure_loc}.
899 @end table
900 @end table
901
902 @code{ffi_prep_closure_loc} will return @code{FFI_OK} if everything
903 went ok, and one of the other @code{ffi_status} values on error.
904
905 After calling @code{ffi_prep_closure_loc}, you can cast @var{codeloc}
906 to the appropriate pointer-to-function type.
907 @end defun
908
909 You may see old code referring to @code{ffi_prep_closure}. This
910 function is deprecated, as it cannot handle the need for separate
911 writable and executable addresses.
912
913 @node Closure Example
914 @section Closure Example
915
916 A trivial example that creates a new @code{puts} by binding
917 @code{fputs} with @code{stdout}.
918
919 @example
920 #include <stdio.h>
921 #include <ffi.h>
922
923 /* Acts like puts with the file given at time of enclosure. */
924 void puts_binding(ffi_cif *cif, void *ret, void* args[],
925 void *stream)
926 @{
927 *(ffi_arg *)ret = fputs(*(char **)args[0], (FILE *)stream);
928 @}
929
930 typedef int (*puts_t)(char *);
931
932 int main()
933 @{
934 ffi_cif cif;
935 ffi_type *args[1];
936 ffi_closure *closure;
937
938 void *bound_puts;
939 int rc;
940
941 /* Allocate closure and bound_puts */
942 closure = ffi_closure_alloc(sizeof(ffi_closure), &bound_puts);
943
944 if (closure)
945 @{
946 /* Initialize the argument info vectors */
947 args[0] = &ffi_type_pointer;
948
949 /* Initialize the cif */
950 if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1,
951 &ffi_type_sint, args) == FFI_OK)
952 @{
953 /* Initialize the closure, setting stream to stdout */
954 if (ffi_prep_closure_loc(closure, &cif, puts_binding,
955 stdout, bound_puts) == FFI_OK)
956 @{
957 rc = ((puts_t)bound_puts)("Hello World!");
958 /* rc now holds the result of the call to fputs */
959 @}
960 @}
961 @}
962
963 /* Deallocate both closure, and bound_puts */
964 ffi_closure_free(closure);
965
966 return 0;
967 @}
968
969 @end example
970
971 @node Thread Safety
972 @section Thread Safety
973
974 @code{libffi} is not completely thread-safe. However, many parts are,
975 and if you follow some simple rules, you can use it safely in a
976 multi-threaded program.
977
978 @itemize @bullet
979 @item
980 @code{ffi_prep_cif} may modify the @code{ffi_type} objects passed to
981 it. It is best to ensure that only a single thread prepares a given
982 @code{ffi_cif} at a time.
983
984 @item
985 On some platforms, @code{ffi_prep_cif} may modify the size and
986 alignment of some types, depending on the chosen ABI. On these
987 platforms, if you switch between ABIs, you must ensure that there is
988 only one call to @code{ffi_prep_cif} at a time.
989
990 Currently the only affected platform is PowerPC and the only affected
991 type is @code{long double}.
992 @end itemize
993
994 @node Memory Usage
995 @chapter Memory Usage
996
997 Note that memory allocated by @code{ffi_closure_alloc} and freed by
998 @code{ffi_closure_free} does not come from the same general pool of
999 memory that @code{malloc} and @code{free} use. To accomodate security
1000 settings, @code{libffi} may aquire memory, for example, by mapping
1001 temporary files into multiple places in the address space (once to
1002 write out the closure, a second to execute it). The search follows
1003 this list, using the first that works:
1004
1005 @itemize @bullet
1006
1007 @item
1008 A anonymous mapping (i.e. not file-backed)
1009
1010 @item
1011 @code{memfd_create()}, if the kernel supports it.
1012
1013 @item
1014 A file created in the directory referenced by the environment variable
1015 @code{LIBFFI_TMPDIR}.
1016
1017 @item
1018 Likewise for the environment variable @code{TMPDIR}.
1019
1020 @item
1021 A file created in @code{/tmp}.
1022
1023 @item
1024 A file created in @code{/var/tmp}.
1025
1026 @item
1027 A file created in @code{/dev/shm}.
1028
1029 @item
1030 A file created in the user's home directory (@code{$HOME}).
1031
1032 @item
1033 A file created in any directory listed in @code{/etc/mtab}.
1034
1035 @item
1036 A file created in any directory listed in @code{/proc/mounts}.
1037
1038 @end itemize
1039
1040 If security settings prohibit using any of these for closures,
1041 @code{ffi_closure_alloc} will fail.
1042
1043 @node Missing Features
1044 @chapter Missing Features
1045
1046 @code{libffi} is missing a few features. We welcome patches to add
1047 support for these.
1048
1049 @itemize @bullet
1050 @item
1051 Variadic closures.
1052
1053 @item
1054 There is no support for bit fields in structures.
1055
1056 @item
1057 The ``raw'' API is undocumented.
1058 @c anything else?
1059
1060 @item
1061 The Go API is undocumented.
1062 @end itemize
1063
1064 @node Index
1065 @unnumbered Index
1066
1067 @printindex cp
1068
1069 @bye