eda/EDASQLite: Improved SQL Custom Functions support, now taking an arbitrary set...
[sdk] / deps / libffi-3.0.11 / doc / libffi.texi
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
19 This manual is for Libffi, a portable foreign-function interface
20 library.
21
22 Copyright @copyright{} 2008, 2010, 2011 Red Hat, Inc.
23
24 @quotation
25 Permission is granted to copy, distribute and/or modify this document
26 under the terms of the GNU General Public License as published by the
27 Free Software Foundation; either version 2, or (at your option) any
28 later version.  A copy of the license is included in the
29 section 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
66 Compilers for high level languages generate code that follow certain
67 conventions.  These conventions are necessary, in part, for separate
68 compilation to work.  One such convention is the @dfn{calling
69 convention}.  The calling convention is a set of assumptions made by
70 the compiler about where function arguments will be found on entry to
71 a function.  A calling convention also specifies where the return
72 value for a function is found.  The calling convention is also
73 sometimes called the @dfn{ABI} or @dfn{Application Binary Interface}.
74 @cindex calling convention
75 @cindex ABI
76 @cindex Application Binary Interface
77
78 Some programs may not know at the time of compilation what arguments
79 are to be passed to a function.  For instance, an interpreter may be
80 told at run-time about the number and types of arguments used to call
81 a given function.  @samp{Libffi} can be used in such programs to
82 provide a bridge from the interpreter program to compiled code.
83
84 The @samp{libffi} library provides a portable, high level programming
85 interface to various calling conventions.  This allows a programmer to
86 call any function specified by a call interface description at run
87 time.
88
89 @acronym{FFI} stands for Foreign Function Interface.  A foreign
90 function interface is the popular name for the interface that allows
91 code written in one language to call code written in another language.
92 The @samp{libffi} library really only provides the lowest, machine
93 dependent layer of a fully featured foreign function interface.  A
94 layer must exist above @samp{libffi} that handles type conversions for
95 values 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 @end menu
111
112
113 @node The Basics
114 @section The Basics
115
116 @samp{Libffi} assumes that you have a pointer to the function you wish
117 to call and that you know the number and types of arguments to pass
118 it, as well as the return type of the function.
119
120 The first thing you must do is create an @code{ffi_cif} object that
121 matches the signature of the function you wish to call.  This is a
122 separate step because it is common to make multiple calls using a
123 single @code{ffi_cif}.  The @dfn{cif} in @code{ffi_cif} stands for
124 Call InterFace.  To prepare a call interface object, use the function
125 @code{ffi_prep_cif}.
126 @cindex cif
127
128 @findex ffi_prep_cif
129 @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})
130 This initializes @var{cif} according to the given parameters.
131
132 @var{abi} is the ABI to use; normally @code{FFI_DEFAULT_ABI} is what
133 you want.  @ref{Multiple ABIs} for more information.
134
135 @var{nargs} is the number of arguments that this function accepts.
136
137 @var{rtype} is a pointer to an @code{ffi_type} structure that
138 describes the return type of the function.  @xref{Types}.
139
140 @var{argtypes} is a vector of @code{ffi_type} pointers.
141 @var{argtypes} must have @var{nargs} elements.  If @var{nargs} is 0,
142 this argument is ignored.
143
144 @code{ffi_prep_cif} returns a @code{libffi} status code, of type
145 @code{ffi_status}.  This will be either @code{FFI_OK} if everything
146 worked properly; @code{FFI_BAD_TYPEDEF} if one of the @code{ffi_type}
147 objects is incorrect; or @code{FFI_BAD_ABI} if the @var{abi} parameter
148 is invalid.
149 @end defun
150
151 If the function being called is variadic (varargs) then
152 @code{ffi_prep_cif_var} must be used instead of @code{ffi_prep_cif}.
153
154 @findex ffi_prep_cif_var
155 @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})
156 This initializes @var{cif} according to the given parameters for
157 a call to a variadic function.  In general it's operation is the
158 same as for @code{ffi_prep_cif} except that:
159
160 @var{nfixedargs} is the number of fixed arguments, prior to any
161 variadic arguments.  It must be greater than zero.
162
163 @var{ntotalargs} the total number of arguments, including variadic
164 and fixed arguments.
165
166 Note that, different cif's must be prepped for calls to the same
167 function when different numbers of arguments are passed.
168
169 Also note that a call to @code{ffi_prep_cif_var} with
170 @var{nfixedargs}=@var{nototalargs} is NOT equivalent to a call to
171 @code{ffi_prep_cif}.
172
173 @end defun
174
175
176 To call a function using an initialized @code{ffi_cif}, use the
177 @code{ffi_call} function:
178
179 @findex ffi_call
180 @defun void ffi_call (ffi_cif *@var{cif}, void *@var{fn}, void *@var{rvalue}, void **@var{avalues})
181 This calls the function @var{fn} according to the description given in
182 @var{cif}.  @var{cif} must have already been prepared using
183 @code{ffi_prep_cif}.
184
185 @var{rvalue} is a pointer to a chunk of memory that will hold the
186 result of the function call.  This must be large enough to hold the
187 result and must be suitably aligned; it is the caller's responsibility
188 to ensure this.  If @var{cif} declares that the function returns
189 @code{void} (using @code{ffi_type_void}), then @var{rvalue} is
190 ignored.  If @var{rvalue} is @samp{NULL}, then the return value is
191 discarded.
192
193 @var{avalues} is a vector of @code{void *} pointers that point to the
194 memory locations holding the argument values for a call.  If @var{cif}
195 declares that the function has no arguments (i.e., @var{nargs} was 0),
196 then @var{avalues} is ignored.  Note that argument values may be
197 modified by the callee (for instance, structs passed by value); the
198 burden of copying pass-by-value arguments is placed on the caller.
199 @end defun
200
201
202 @node Simple Example
203 @section Simple Example
204
205 Here is a trivial example that calls @code{puts} a few times.
206
207 @example
208 #include <stdio.h>
209 #include <ffi.h>
210
211 int main()
212 @{
213   ffi_cif cif;
214   ffi_type *args[1];
215   void *values[1];
216   char *s;
217   int rc;
218   
219   /* Initialize the argument info vectors */    
220   args[0] = &ffi_type_pointer;
221   values[0] = &s;
222   
223   /* Initialize the cif */
224   if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1, 
225                        &ffi_type_uint, args) == FFI_OK)
226     @{
227       s = "Hello World!";
228       ffi_call(&cif, puts, &rc, values);
229       /* rc now holds the result of the call to puts */
230       
231       /* values holds a pointer to the function's arg, so to 
232          call puts() again all we need to do is change the 
233          value of s */
234       s = "This is cool!";
235       ffi_call(&cif, puts, &rc, values);
236     @}
237   
238   return 0;
239 @}
240 @end example
241
242
243 @node Types
244 @section Types
245
246 @menu
247 * Primitive Types::             Built-in types.
248 * Structures::                  Structure types.
249 * Type Example::                Structure type example.
250 @end menu
251
252 @node Primitive Types
253 @subsection Primitive Types
254
255 @code{Libffi} provides a number of built-in type descriptors that can
256 be used to describe argument and return types:
257
258 @table @code
259 @item ffi_type_void
260 @tindex ffi_type_void
261 The type @code{void}.  This cannot be used for argument types, only
262 for return values.
263
264 @item ffi_type_uint8
265 @tindex ffi_type_uint8
266 An unsigned, 8-bit integer type.
267
268 @item ffi_type_sint8
269 @tindex ffi_type_sint8
270 A signed, 8-bit integer type.
271
272 @item ffi_type_uint16
273 @tindex ffi_type_uint16
274 An unsigned, 16-bit integer type.
275
276 @item ffi_type_sint16
277 @tindex ffi_type_sint16
278 A signed, 16-bit integer type.
279
280 @item ffi_type_uint32
281 @tindex ffi_type_uint32
282 An unsigned, 32-bit integer type.
283
284 @item ffi_type_sint32
285 @tindex ffi_type_sint32
286 A signed, 32-bit integer type.
287
288 @item ffi_type_uint64
289 @tindex ffi_type_uint64
290 An unsigned, 64-bit integer type.
291
292 @item ffi_type_sint64
293 @tindex ffi_type_sint64
294 A signed, 64-bit integer type.
295
296 @item ffi_type_float
297 @tindex ffi_type_float
298 The C @code{float} type.
299
300 @item ffi_type_double
301 @tindex ffi_type_double
302 The C @code{double} type.
303
304 @item ffi_type_uchar
305 @tindex ffi_type_uchar
306 The C @code{unsigned char} type.
307
308 @item ffi_type_schar
309 @tindex ffi_type_schar
310 The C @code{signed char} type.  (Note that there is not an exact
311 equivalent to the C @code{char} type in @code{libffi}; ordinarily you
312 should either use @code{ffi_type_schar} or @code{ffi_type_uchar}
313 depending on whether @code{char} is signed.)
314
315 @item ffi_type_ushort
316 @tindex ffi_type_ushort
317 The C @code{unsigned short} type.
318
319 @item ffi_type_sshort
320 @tindex ffi_type_sshort
321 The C @code{short} type.
322
323 @item ffi_type_uint
324 @tindex ffi_type_uint
325 The C @code{unsigned int} type.
326
327 @item ffi_type_sint
328 @tindex ffi_type_sint
329 The C @code{int} type.
330
331 @item ffi_type_ulong
332 @tindex ffi_type_ulong
333 The C @code{unsigned long} type.
334
335 @item ffi_type_slong
336 @tindex ffi_type_slong
337 The C @code{long} type.
338
339 @item ffi_type_longdouble
340 @tindex ffi_type_longdouble
341 On platforms that have a C @code{long double} type, this is defined.
342 On other platforms, it is not.
343
344 @item ffi_type_pointer
345 @tindex ffi_type_pointer
346 A generic @code{void *} pointer.  You should use this for all
347 pointers, regardless of their real type.
348 @end table
349
350 Each of these is of type @code{ffi_type}, so you must take the address
351 when passing to @code{ffi_prep_cif}.
352
353
354 @node Structures
355 @subsection Structures
356
357 Although @samp{libffi} has no special support for unions or
358 bit-fields, it is perfectly happy passing structures back and forth.
359 You must first describe the structure to @samp{libffi} by creating a
360 new @code{ffi_type} object for it.
361
362 @tindex ffi_type
363 @deftp ffi_type
364 The @code{ffi_type} has the following members:
365 @table @code
366 @item size_t size
367 This is set by @code{libffi}; you should initialize it to zero.
368
369 @item unsigned short alignment
370 This is set by @code{libffi}; you should initialize it to zero.
371
372 @item unsigned short type
373 For a structure, this should be set to @code{FFI_TYPE_STRUCT}.
374
375 @item ffi_type **elements
376 This is a @samp{NULL}-terminated array of pointers to @code{ffi_type}
377 objects.  There is one element per field of the struct.
378 @end table
379 @end deftp
380
381
382 @node Type Example
383 @subsection Type Example
384
385 The following example initializes a @code{ffi_type} object
386 representing the @code{tm} struct from Linux's @file{time.h}.
387
388 Here is how the struct is defined:
389
390 @example
391 struct tm @{
392     int tm_sec;
393     int tm_min;
394     int tm_hour;
395     int tm_mday;
396     int tm_mon;
397     int tm_year;
398     int tm_wday;
399     int tm_yday;
400     int tm_isdst;
401     /* Those are for future use. */
402     long int __tm_gmtoff__;
403     __const char *__tm_zone__;
404 @};
405 @end example
406
407 Here is the corresponding code to describe this struct to
408 @code{libffi}:
409
410 @example
411     @{
412       ffi_type tm_type;
413       ffi_type *tm_type_elements[12];
414       int i;
415
416       tm_type.size = tm_type.alignment = 0;
417       tm_type.elements = &tm_type_elements;
418     
419       for (i = 0; i < 9; i++)
420           tm_type_elements[i] = &ffi_type_sint;
421
422       tm_type_elements[9] = &ffi_type_slong;
423       tm_type_elements[10] = &ffi_type_pointer;
424       tm_type_elements[11] = NULL;
425
426       /* tm_type can now be used to represent tm argument types and
427          return types for ffi_prep_cif() */
428     @}
429 @end example
430
431
432 @node Multiple ABIs
433 @section Multiple ABIs
434
435 A given platform may provide multiple different ABIs at once.  For
436 instance, the x86 platform has both @samp{stdcall} and @samp{fastcall}
437 functions.
438
439 @code{libffi} provides some support for this.  However, this is
440 necessarily platform-specific.
441
442 @c FIXME: document the platforms
443
444 @node The Closure API
445 @section The Closure API
446
447 @code{libffi} also provides a way to write a generic function -- a
448 function that can accept and decode any combination of arguments.
449 This can be useful when writing an interpreter, or to provide wrappers
450 for arbitrary functions.
451
452 This facility is called the @dfn{closure API}.  Closures are not
453 supported on all platforms; you can check the @code{FFI_CLOSURES}
454 define to determine whether they are supported on the current
455 platform.
456 @cindex closures
457 @cindex closure API
458 @findex FFI_CLOSURES
459
460 Because closures work by assembling a tiny function at runtime, they
461 require special allocation on platforms that have a non-executable
462 heap.  Memory management for closures is handled by a pair of
463 functions:
464
465 @findex ffi_closure_alloc
466 @defun void *ffi_closure_alloc (size_t @var{size}, void **@var{code})
467 Allocate a chunk of memory holding @var{size} bytes.  This returns a
468 pointer to the writable address, and sets *@var{code} to the
469 corresponding executable address.
470
471 @var{size} should be sufficient to hold a @code{ffi_closure} object.
472 @end defun
473
474 @findex ffi_closure_free
475 @defun void ffi_closure_free (void *@var{writable})
476 Free memory allocated using @code{ffi_closure_alloc}.  The argument is
477 the writable address that was returned.
478 @end defun
479
480
481 Once you have allocated the memory for a closure, you must construct a
482 @code{ffi_cif} describing the function call.  Finally you can prepare
483 the closure function:
484
485 @findex ffi_prep_closure_loc
486 @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})
487 Prepare a closure function.
488
489 @var{closure} is the address of a @code{ffi_closure} object; this is
490 the writable address returned by @code{ffi_closure_alloc}.
491
492 @var{cif} is the @code{ffi_cif} describing the function parameters.
493
494 @var{user_data} is an arbitrary datum that is passed, uninterpreted,
495 to your closure function.
496
497 @var{codeloc} is the executable address returned by
498 @code{ffi_closure_alloc}.
499
500 @var{fun} is the function which will be called when the closure is
501 invoked.  It is called with the arguments:
502 @table @var
503 @item cif
504 The @code{ffi_cif} passed to @code{ffi_prep_closure_loc}.
505
506 @item ret
507 A pointer to the memory used for the function's return value.
508 @var{fun} must fill this, unless the function is declared as returning
509 @code{void}.
510 @c FIXME: is this NULL for void-returning functions?
511
512 @item args
513 A vector of pointers to memory holding the arguments to the function.
514
515 @item user_data
516 The same @var{user_data} that was passed to
517 @code{ffi_prep_closure_loc}.
518 @end table
519
520 @code{ffi_prep_closure_loc} will return @code{FFI_OK} if everything
521 went ok, and something else on error.
522 @c FIXME: what?
523
524 After calling @code{ffi_prep_closure_loc}, you can cast @var{codeloc}
525 to the appropriate pointer-to-function type.
526 @end defun
527
528 You may see old code referring to @code{ffi_prep_closure}.  This
529 function is deprecated, as it cannot handle the need for separate
530 writable and executable addresses.
531
532 @node Closure Example
533 @section Closure Example
534
535 A trivial example that creates a new @code{puts} by binding 
536 @code{fputs} with @code{stdin}.
537
538 @example
539 #include <stdio.h>
540 #include <ffi.h>
541
542 /* Acts like puts with the file given at time of enclosure. */
543 void puts_binding(ffi_cif *cif, unsigned int *ret, void* args[], 
544                   FILE *stream)
545 @{
546   *ret = fputs(*(char **)args[0], stream);
547 @}
548
549 int main()
550 @{
551   ffi_cif cif;
552   ffi_type *args[1];
553   ffi_closure *closure;
554
555   int (*bound_puts)(char *);
556   int rc;
557   
558   /* Allocate closure and bound_puts */
559   closure = ffi_closure_alloc(sizeof(ffi_closure), &bound_puts);
560
561   if (closure)
562     @{
563       /* Initialize the argument info vectors */
564       args[0] = &ffi_type_pointer;
565
566       /* Initialize the cif */
567       if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1,
568                        &ffi_type_uint, args) == FFI_OK)
569         @{
570           /* Initialize the closure, setting stream to stdout */
571           if (ffi_prep_closure_loc(closure, &cif, puts_binding, 
572                                    stdout, bound_puts) == FFI_OK)
573             @{
574               rc = bound_puts("Hello World!");
575               /* rc now holds the result of the call to fputs */
576             @}
577         @}
578     @}
579
580   /* Deallocate both closure, and bound_puts */
581   ffi_closure_free(closure);
582
583   return 0;
584 @}
585
586 @end example
587
588
589 @node Missing Features
590 @chapter Missing Features
591
592 @code{libffi} is missing a few features.  We welcome patches to add
593 support for these.
594
595 @itemize @bullet
596 @item
597 Variadic closures.
598
599 @item
600 There is no support for bit fields in structures.
601
602 @item
603 The closure API is
604
605 @c FIXME: ...
606
607 @item
608 The ``raw'' API is undocumented.
609 @c argument promotion?
610 @c unions?
611 @c anything else?
612 @end itemize
613
614 Note that variadic support is very new and tested on a relatively
615 small number of platforms.
616
617 @node Index
618 @unnumbered Index
619
620 @printindex cp
621
622 @bye